diff --git a/Applications/ApplicationsLib/ProjectData.cpp b/Applications/ApplicationsLib/ProjectData.cpp index d0e92051910bcdb15db524a33f597647049d1b55..a66c1b0db6b400357ee7538a99b807f1e7500520 100644 --- a/Applications/ApplicationsLib/ProjectData.cpp +++ b/Applications/ApplicationsLib/ProjectData.cpp @@ -41,7 +41,6 @@ // FileIO #include "GeoLib/IO/XmlIO/Boost/BoostXmlGmlInterface.h" #include "MeshLib/IO/readMeshFromFile.h" - #include "ParameterLib/ConstantParameter.h" #include "ParameterLib/Utils.h" #include "ProcessLib/CreateTimeLoop.h" @@ -490,9 +489,8 @@ void ProjectData::parseMedia( { OGS_FATAL( "Multiple media were specified for the same material id " - "'{:d}'. " - "Keep in mind, that if no material id is specified, it is " - "assumed to be 0 by default.", + "'{:d}'. Keep in mind, that if no material id is " + "specified, it is assumed to be 0 by default.", id); } @@ -538,8 +536,8 @@ ProjectData::parseChemicalSolverInterface( if (boost::iequals(chemical_solver, "Phreeqc")) { INFO( - "Configuring phreeqc interface for water chemistry " - "calculation using file-based approach."); + "Configuring phreeqc interface for water chemistry calculation " + "using file-based approach."); chemical_solver_interface = ChemistryLib::createChemicalSolverInterface< ChemistryLib::ChemicalSolver::Phreeqc>(_mesh_vec, *config, @@ -548,9 +546,9 @@ ProjectData::parseChemicalSolverInterface( else if (boost::iequals(chemical_solver, "PhreeqcKernel")) { OGS_FATAL( - "The chemical solver option of PhreeqcKernel is not accessible " - "for the time being. Please set 'Phreeqc'' as the chemical " - "solver for reactive transport modeling."); + "The chemical solver option of PhreeqcKernel is not accessible for " + "the time being. Please set 'Phreeqc'' as the chemical solver for " + "reactive transport modeling."); } else { @@ -810,8 +808,8 @@ void ProjectData::parseProcesses( break; default: OGS_FATAL( - "SMALL_DEFORMATION process does not support " - "given dimension"); + "SMALL_DEFORMATION process does not support given " + "dimension"); } } else diff --git a/Applications/ApplicationsLib/TestDefinition.cpp b/Applications/ApplicationsLib/TestDefinition.cpp index 342e58d2dee4ebe6bd11e75f8371877eb0978f1f..d2713d4c7c1479d5ce3e4a1d60521bcfd34c4b63 100644 --- a/Applications/ApplicationsLib/TestDefinition.cpp +++ b/Applications/ApplicationsLib/TestDefinition.cpp @@ -21,8 +21,9 @@ #include "BaseLib/FileTools.h" #include "filesystem.h" #ifdef USE_PETSC -#include "MeshLib/IO/VtkIO/VtuInterface.h" // For petsc file name conversion. #include <petsc.h> + +#include "MeshLib/IO/VtkIO/VtuInterface.h" // For petsc file name conversion. #endif namespace @@ -114,8 +115,7 @@ std::string findVtkdiff() } WARN( "Calling {:s} from the VTKDIFF_EXE environment variable didn't " - "work " - "as expected. Return value was {:d}.", + "work as expected. Return value was {:d}.", vtkdiff_exe, return_value); } @@ -168,13 +168,14 @@ TestDefinition::TestDefinition(BaseLib::ConfigTree const& config_tree, std::vector<std::string> filenames; if (auto const regex_string = - //! \ogs_file_param{prj__test_definition__vtkdiff__regex} + //! \ogs_file_param{prj__test_definition__vtkdiff__regex} vtkdiff_config.getConfigParameterOptional<std::string>("regex")) { // TODO: insert rank into regex for mpi case DBUG("vtkdiff regex is '{}'.", *regex_string); auto const regex = std::regex(*regex_string); - for (auto const & p: fs::directory_iterator(fs::path(reference_path))) + for (auto const& p : + fs::directory_iterator(fs::path(reference_path))) { auto const filename = p.path().filename().string(); if (std::regex_match(filename, regex)) @@ -242,7 +243,7 @@ TestDefinition::TestDefinition(BaseLib::ConfigTree const& config_tree, std::string const relative_tolerance_parameter = "--rel " + relative_tolerance; - for (auto const &filename : filenames) + for (auto const& filename : filenames) { std::string const& output_filename = BaseLib::joinPaths(output_directory, filename); @@ -257,7 +258,8 @@ TestDefinition::TestDefinition(BaseLib::ConfigTree const& config_tree, vtkdiff + " -a " + safeString(field_name) + " -b " + safeString(field_name) + " " + safeString(reference_filename) + " " + safeString(output_filename) + " " + - absolute_tolerance_parameter + " " + relative_tolerance_parameter; + absolute_tolerance_parameter + " " + + relative_tolerance_parameter; INFO("Will run '{:s}'", command_line); _command_lines.emplace_back(std::move(command_line)); } diff --git a/Applications/CLI/ogs.cpp b/Applications/CLI/ogs.cpp index 72a5c732cfa4daabc6817de3f157b1ee623be8d8..d2b52a3c68abe726ec06532643c83ad9ea35bed6 100644 --- a/Applications/CLI/ogs.cpp +++ b/Applications/CLI/ogs.cpp @@ -29,20 +29,18 @@ #endif // BaseLib -#include "BaseLib/ConfigTreeUtil.h" -#include "BaseLib/DateTools.h" -#include "BaseLib/FileTools.h" -#include "BaseLib/RunTime.h" - #include "Applications/ApplicationsLib/LinearSolverLibrarySetup.h" #include "Applications/ApplicationsLib/ProjectData.h" #include "Applications/ApplicationsLib/TestDefinition.h" #include "Applications/InSituLib/Adaptor.h" +#include "BaseLib/ConfigTreeUtil.h" +#include "BaseLib/DateTools.h" +#include "BaseLib/FileTools.h" +#include "BaseLib/RunTime.h" #include "InfoLib/CMakeInfo.h" #include "InfoLib/GitInfo.h" -#include "ProcessLib/TimeLoop.h" - #include "NumLib/NumericsConfig.h" +#include "ProcessLib/TimeLoop.h" #ifdef OGS_USE_PYTHON #include "ogs_embedded_python.h" @@ -60,8 +58,7 @@ int main(int argc, char* argv[]) "http://www.opengeosys.org/project/license\n" "version: " + GitInfoLib::GitInfo::ogs_version + "\n" + - "CMake arguments: " + - CMakeInfoLib::CMakeInfo::cmake_args, + "CMake arguments: " + CMakeInfoLib::CMakeInfo::cmake_args, ' ', GitInfoLib::GitInfo::ogs_version); @@ -86,17 +83,17 @@ int main(int argc, char* argv[]) false, "", "PATH"); cmd.add(outdir_arg); - TCLAP::ValueArg<std::string> log_level_arg("l", "log-level", - "the verbosity of logging " - "messages: none, error, warn, " - "info, debug, all", - false, + TCLAP::ValueArg<std::string> log_level_arg( + "l", "log-level", + "the verbosity of logging messages: none, error, warn, info, debug, " + "all", + false, #ifdef NDEBUG - "info", + "info", #else - "all", + "all", #endif - "LOG_LEVEL"); + "LOG_LEVEL"); cmd.add(log_level_arg); TCLAP::SwitchArg nonfatal_arg("", @@ -174,7 +171,7 @@ int main(int argc, char* argv[]) controller->Initialize(&argc, &argv, 1); vtkMPIController::SetGlobalController(controller); - { // Can be called only after MPI_INIT. + { // Can be called only after MPI_INIT. int mpi_rank; MPI_Comm_rank(PETSC_COMM_WORLD, &mpi_rank); spdlog::set_pattern(fmt::format("[{}] %^%l:%$ %v", mpi_rank)); @@ -205,7 +202,7 @@ int main(int argc, char* argv[]) project_config->getConfigSubtree("test_definition"), reference_path_arg.getValue(), outdir_arg.getValue()); - if( test_definition->numberOfTests() == 0) + if (test_definition->numberOfTests() == 0) { OGS_FATAL( "No tests were constructed from the test definitions, " diff --git a/Applications/CLI/ogs_embedded_python.cpp b/Applications/CLI/ogs_embedded_python.cpp index cd0c28d234d7f546e5cac8f9c3fec6cd6db245a8..5c170cfe98a2596a178b76f9b0e990e0bb7a7b50 100644 --- a/Applications/CLI/ogs_embedded_python.cpp +++ b/Applications/CLI/ogs_embedded_python.cpp @@ -12,7 +12,6 @@ #include <pybind11/embed.h> #include "BaseLib/Logging.h" - #include "ProcessLib/BoundaryCondition/Python/BHEInflowPythonBoundaryConditionModule.h" #include "ProcessLib/BoundaryCondition/Python/PythonBoundaryConditionModule.h" #include "ProcessLib/SourceTerms/Python/PythonSourceTermModule.h" diff --git a/Applications/DataExplorer/Base/CheckboxDelegate.cpp b/Applications/DataExplorer/Base/CheckboxDelegate.cpp index 00f5b302cd8fa437069bc747a2455b5e57194153..59f7bf346e977746da010b0002678c2025fb8d68 100644 --- a/Applications/DataExplorer/Base/CheckboxDelegate.cpp +++ b/Applications/DataExplorer/Base/CheckboxDelegate.cpp @@ -14,6 +14,7 @@ // ** INCLUDES ** #include "CheckboxDelegate.h" + #include <QApplication> #include <QCheckBox> #include <QEvent> @@ -21,15 +22,13 @@ #include <QPainter> #include <QStyleOptionButton> -CheckboxDelegate::CheckboxDelegate(QObject* parent) - : QItemDelegate(parent) -{ -} +CheckboxDelegate::CheckboxDelegate(QObject* parent) : QItemDelegate(parent) {} -void CheckboxDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, +void CheckboxDelegate::paint(QPainter* painter, + const QStyleOptionViewItem& option, const QModelIndex& index) const { - if(index.isValid()) + if (index.isValid()) { bool checked = index.model()->data(index, Qt::DisplayRole).toBool(); @@ -56,7 +55,8 @@ void CheckboxDelegate::paint(QPainter* painter, const QStyleOptionViewItem& opti } bool CheckboxDelegate::editorEvent(QEvent* event, QAbstractItemModel* model, - const QStyleOptionViewItem &option, const QModelIndex &index) + const QStyleOptionViewItem& option, + const QModelIndex& index) { Q_UNUSED(option); @@ -91,8 +91,8 @@ bool CheckboxDelegate::editorEvent(QEvent* event, QAbstractItemModel* model, return model->setData(index, !checked, Qt::EditRole); } -QSize CheckboxDelegate::sizeHint(const QStyleOptionViewItem & option, - const QModelIndex & index) const +QSize CheckboxDelegate::sizeHint(const QStyleOptionViewItem& option, + const QModelIndex& index) const { Q_UNUSED(index); @@ -100,14 +100,16 @@ QSize CheckboxDelegate::sizeHint(const QStyleOptionViewItem & option, return QSize(rect.width(), rect.height()); } -QRect CheckboxDelegate::checkboxRect(const QStyleOptionViewItem& viewItemStyleOptions) const +QRect CheckboxDelegate::checkboxRect( + const QStyleOptionViewItem& viewItemStyleOptions) const { QStyleOptionButton styleOptionButton; QRect rect = QApplication::style()->subElementRect( - QStyle::SE_CheckBoxIndicator, &styleOptionButton); + QStyle::SE_CheckBoxIndicator, &styleOptionButton); QPoint point(viewItemStyleOptions.rect.x() + - viewItemStyleOptions.rect.width() / 2 - rect.width() / 2, - viewItemStyleOptions.rect.y() + viewItemStyleOptions.rect.height() / 2 - - rect.height() / 2); + viewItemStyleOptions.rect.width() / 2 - rect.width() / 2, + viewItemStyleOptions.rect.y() + + viewItemStyleOptions.rect.height() / 2 - + rect.height() / 2); return QRect(point, rect.size()); } diff --git a/Applications/DataExplorer/Base/ColorPickerPushButton.cpp b/Applications/DataExplorer/Base/ColorPickerPushButton.cpp index f2aec37f3d434c3749e646c441e2a2a56ed83246..399c09beb09763190fc9476430da6f9076befac7 100644 --- a/Applications/DataExplorer/Base/ColorPickerPushButton.cpp +++ b/Applications/DataExplorer/Base/ColorPickerPushButton.cpp @@ -17,7 +17,7 @@ #include <QColorDialog> -ColorPickerPushButton::ColorPickerPushButton( QWidget* parent /*= 0*/ ) +ColorPickerPushButton::ColorPickerPushButton(QWidget* parent /*= 0*/) : QPushButton(parent) { setAutoFillBackground(true); @@ -38,7 +38,7 @@ void ColorPickerPushButton::mouseReleaseEvent(QMouseEvent* e) emit colorPicked(_color); } -QString ColorPickerPushButton::colorToCss( QColor color ) +QString ColorPickerPushButton::colorToCss(QColor color) { QString colorStr = "rgb"; colorStr.append(colorToString(color)); @@ -46,7 +46,7 @@ QString ColorPickerPushButton::colorToCss( QColor color ) return colorStr; } -QString ColorPickerPushButton::colorToString( QColor color ) +QString ColorPickerPushButton::colorToString(QColor color) { QString colorStr = "("; colorStr.append(QString::number(color.red())); @@ -59,7 +59,7 @@ QString ColorPickerPushButton::colorToString( QColor color ) return colorStr; } -void ColorPickerPushButton::setColor( QColor color ) +void ColorPickerPushButton::setColor(QColor color) { _color = color; @@ -84,7 +84,7 @@ void ColorPickerPushButton::setColor( QColor color ) this->setText(colorToString(_color)); } -void ColorPickerPushButton::setColor( double* color ) +void ColorPickerPushButton::setColor(double* color) { setColor(QColor::fromRgbF(color[0], color[1], color[2])); } diff --git a/Applications/DataExplorer/Base/OGSError.cpp b/Applications/DataExplorer/Base/OGSError.cpp index acbc5c7f23dbd6510b191e88fa4a3971015bc316..c5f9f7df6671cfca4187bb220b6b9ef798ef6e76 100644 --- a/Applications/DataExplorer/Base/OGSError.cpp +++ b/Applications/DataExplorer/Base/OGSError.cpp @@ -20,12 +20,12 @@ OGSError::OGSError() = default; OGSError::~OGSError() = default; -void OGSError::box(const QString &e) +void OGSError::box(const QString& e) { box(e, "OpenGeoSys"); } -void OGSError::box(const QString &e, const QString &t) +void OGSError::box(const QString& e, const QString& t) { QMessageBox msgBox; msgBox.setWindowTitle(t); @@ -33,7 +33,7 @@ void OGSError::box(const QString &e, const QString &t) msgBox.exec(); } -bool OGSError::question(const QString &e, const QString &t) +bool OGSError::question(const QString& e, const QString& t) { QMessageBox msgBox; msgBox.setWindowTitle(t); @@ -43,4 +43,3 @@ bool OGSError::question(const QString &e, const QString &t) return msgBox.exec() == QMessageBox::Ok; } - diff --git a/Applications/DataExplorer/Base/QNonScalableGraphicsTextItem.cpp b/Applications/DataExplorer/Base/QNonScalableGraphicsTextItem.cpp index 476787a7d0807317493fa283e9259fe18ff988c7..27cfd3d11a5c9d14d7b199c08d39d105ba1cdcb1 100644 --- a/Applications/DataExplorer/Base/QNonScalableGraphicsTextItem.cpp +++ b/Applications/DataExplorer/Base/QNonScalableGraphicsTextItem.cpp @@ -13,11 +13,13 @@ */ #include "QNonScalableGraphicsTextItem.h" + #include <QPainter> /// Constructor using a QGraphicsTextItem. -QNonScalableGraphicsTextItem::QNonScalableGraphicsTextItem(QGraphicsItem* parent) : - QGraphicsTextItem(parent) +QNonScalableGraphicsTextItem::QNonScalableGraphicsTextItem( + QGraphicsItem* parent) + : QGraphicsTextItem(parent) { setAcceptDrops(true); setAcceptHoverEvents(true); @@ -25,9 +27,9 @@ QNonScalableGraphicsTextItem::QNonScalableGraphicsTextItem(QGraphicsItem* parent } /// Constructor using a QString. -QNonScalableGraphicsTextItem::QNonScalableGraphicsTextItem(const QString & text, - QGraphicsItem* parent) : - QGraphicsTextItem(parent) +QNonScalableGraphicsTextItem::QNonScalableGraphicsTextItem( + const QString& text, QGraphicsItem* parent) + : QGraphicsTextItem(parent) { if (!text.isEmpty()) { @@ -45,7 +47,7 @@ void QNonScalableGraphicsTextItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) { - //painter->drawRect(boundingRect()); + // painter->drawRect(boundingRect()); QRectF rect = boundingRect(); painter->translate(-rect.width() / 2, -rect.height() / 2); QGraphicsTextItem::paint(painter, option, widget); @@ -55,5 +57,6 @@ void QNonScalableGraphicsTextItem::paint(QPainter* painter, QRectF QNonScalableGraphicsTextItem::boundingRect() const { QRectF rect = QGraphicsTextItem::boundingRect(); - return rect; //QRectF(rect.x()-rect.width()/2, rect.y()-rect.height()/2,rect.width(), rect.height()); + return rect; // QRectF(rect.x()-rect.width()/2, + // rect.y()-rect.height()/2,rect.width(), rect.height()); } diff --git a/Applications/DataExplorer/Base/QValueTooltipSlider.cpp b/Applications/DataExplorer/Base/QValueTooltipSlider.cpp index 672f08e05db8f4f7ca63af44f73264767e61ccc3..6c93e8915ae80013a7ea9a25a34a12b41d95d92d 100644 --- a/Applications/DataExplorer/Base/QValueTooltipSlider.cpp +++ b/Applications/DataExplorer/Base/QValueTooltipSlider.cpp @@ -19,8 +19,7 @@ #include <QString> #include <QToolTip> -QValueTooltipSlider::QValueTooltipSlider(QWidget* parent) - : QSlider(parent) +QValueTooltipSlider::QValueTooltipSlider(QWidget* parent) : QSlider(parent) { connect(this, SIGNAL(sliderMoved(int)), this, SLOT(setTooltipValue(int))); } diff --git a/Applications/DataExplorer/Base/RecentFiles.cpp b/Applications/DataExplorer/Base/RecentFiles.cpp index d8a52f4e09835480623921a2a0e800411e2cc7d7..12a7a329a61228d2bad6588f297e172fa666b99d 100644 --- a/Applications/DataExplorer/Base/RecentFiles.cpp +++ b/Applications/DataExplorer/Base/RecentFiles.cpp @@ -43,7 +43,7 @@ QMenu* RecentFiles::menu() { return _filesMenu; } -void RecentFiles::setCurrentFile( const QString& filename ) +void RecentFiles::setCurrentFile(const QString& filename) { _currentFile = filename; @@ -81,7 +81,7 @@ void RecentFiles::updateRecentFileActions() } } -QString RecentFiles::strippedName( const QString& fullFileName ) +QString RecentFiles::strippedName(const QString& fullFileName) { return QFileInfo(fullFileName).fileName(); } diff --git a/Applications/DataExplorer/Base/TreeItem.cpp b/Applications/DataExplorer/Base/TreeItem.cpp index 412d8122c0a7d7844380d8b6337fcb23d99fe2e5..98dc4c9cd89ceb11ce9833203a8fd2341705959d 100644 --- a/Applications/DataExplorer/Base/TreeItem.cpp +++ b/Applications/DataExplorer/Base/TreeItem.cpp @@ -12,10 +12,10 @@ * */ -#include <utility> - #include "TreeItem.h" +#include <utility> + /** * The constructor is only used to record the item's parent * and the data associated with each column. @@ -99,7 +99,7 @@ QVariant TreeItem::data(int column) const /** * Sets the data at a given column. */ -bool TreeItem::setData( int column, const QVariant &value ) +bool TreeItem::setData(int column, const QVariant& value) { if (column < 0 || column >= _itemData.size()) { @@ -118,7 +118,8 @@ TreeItem* TreeItem::parentItem() const } /** - * Removes a number of children of the TreeItem starting from the given position. + * Removes a number of children of the TreeItem starting from the given + * position. */ bool TreeItem::removeChildren(int position, int count) { diff --git a/Applications/DataExplorer/Base/TreeModel.cpp b/Applications/DataExplorer/Base/TreeModel.cpp index af3aabac9eae125df8a0d15288226fb5d6f9736a..e5920eaddd4e48e61ef43a2bbd44416b80a20e60 100644 --- a/Applications/DataExplorer/Base/TreeModel.cpp +++ b/Applications/DataExplorer/Base/TreeModel.cpp @@ -14,23 +14,24 @@ #include "TreeModel.h" -#include "TreeItem.h" - #include <QModelIndex> #include <QStringList> #include <QVariant> +#include "TreeItem.h" + /** * A model for the QTreeView implementing the tree as a double-linked list. */ -TreeModel::TreeModel( QObject* parent ) - : QAbstractItemModel(parent) +TreeModel::TreeModel(QObject* parent) : QAbstractItemModel(parent) { //_modelType = TREE_MODEL; QList<QVariant> rootData; - rootData << "1" << "2" << "3"; + rootData << "1" + << "2" + << "3"; _rootItem = new TreeItem(rootData, nullptr); - //setupModelData(data, _rootItem); + // setupModelData(data, _rootItem); } TreeModel::~TreeModel() @@ -40,15 +41,14 @@ TreeModel::~TreeModel() /** * Returns the index of a TreeItem given its parent and position. - * It is first checked if the model index is valid. If it is not, it is assumed that a - * top-level item is being referred to; otherwise, the data pointer from the model - * index is obtained with its internalPointer() function and is used to reference a - * TreeItem object - * \param row Row of the tree object - * \param column Column of the tree object - * \param parent Index of the parent object + * It is first checked if the model index is valid. If it is not, it is assumed + * that a top-level item is being referred to; otherwise, the data pointer from + * the model index is obtained with its internalPointer() function and is used + * to reference a TreeItem object \param row Row of the tree object \param + * column Column of the tree object \param parent Index of the parent object */ -QModelIndex TreeModel::index(int row, int column, const QModelIndex &parent) const +QModelIndex TreeModel::index(int row, int column, + const QModelIndex& parent) const { if (!hasIndex(row, column, parent)) { @@ -78,7 +78,7 @@ QModelIndex TreeModel::index(int row, int column, const QModelIndex &parent) con /** * Returns the model index of a TreeItem based on its index. */ -QModelIndex TreeModel::parent(const QModelIndex &index) const +QModelIndex TreeModel::parent(const QModelIndex& index) const { if (!index.isValid()) { @@ -97,10 +97,11 @@ QModelIndex TreeModel::parent(const QModelIndex &index) const } /** - * Returns the number of child items for the TreeItem that corresponds to a given - * model index, or the number of top-level items if an invalid index is specified. + * Returns the number of child items for the TreeItem that corresponds to a + * given model index, or the number of top-level items if an invalid index is + * specified. */ -int TreeModel::rowCount(const QModelIndex &parent) const +int TreeModel::rowCount(const QModelIndex& parent) const { TreeItem* parentItem; if (parent.column() > 0) @@ -123,7 +124,7 @@ int TreeModel::rowCount(const QModelIndex &parent) const /** * Determines how many columns are present for a given model index. */ -int TreeModel::columnCount(const QModelIndex &parent) const +int TreeModel::columnCount(const QModelIndex& parent) const { if (parent.isValid()) { @@ -133,14 +134,12 @@ int TreeModel::columnCount(const QModelIndex &parent) const return _rootItem->columnCount(); } -void TreeModel::updateData() -{ -} +void TreeModel::updateData() {} /** - * Since each item manages its own columns, the column number is used to retrieve - * the data with the TreeItem::data() function + * Since each item manages its own columns, the column number is used to + * retrieve the data with the TreeItem::data() function */ -QVariant TreeModel::data(const QModelIndex &index, int role) const +QVariant TreeModel::data(const QModelIndex& index, int role) const { if (!index.isValid()) { @@ -157,7 +156,8 @@ QVariant TreeModel::data(const QModelIndex &index, int role) const return QVariant(); } -bool TreeModel::setData( const QModelIndex &index, const QVariant &value, int role /* = Qt::EditRole */ ) +bool TreeModel::setData(const QModelIndex& index, const QVariant& value, + int role /* = Qt::EditRole */) { if (!index.isValid()) { @@ -172,7 +172,7 @@ bool TreeModel::setData( const QModelIndex &index, const QVariant &value, int ro } return false; } -Qt::ItemFlags TreeModel::flags(const QModelIndex &index) const +Qt::ItemFlags TreeModel::flags(const QModelIndex& index) const { if (!index.isValid()) { @@ -185,7 +185,7 @@ Qt::ItemFlags TreeModel::flags(const QModelIndex &index) const /** * Returns the Item characterized by the given index. */ -TreeItem* TreeModel::getItem(const QModelIndex &index) const +TreeItem* TreeModel::getItem(const QModelIndex& index) const { if (index.isValid()) { @@ -198,7 +198,8 @@ TreeItem* TreeModel::getItem(const QModelIndex &index) const return _rootItem; } -QVariant TreeModel::headerData(int section, Qt::Orientation orientation, int role) const +QVariant TreeModel::headerData(int section, Qt::Orientation orientation, + int role) const { if (orientation == Qt::Horizontal && role == Qt::DisplayRole) { @@ -211,7 +212,7 @@ QVariant TreeModel::headerData(int section, Qt::Orientation orientation, int rol /** * Removes item from the model. */ -bool TreeModel::removeRows(int position, int count, const QModelIndex & parent) +bool TreeModel::removeRows(int position, int count, const QModelIndex& parent) { TreeItem* parentItem = getItem(parent); bool success = true; @@ -226,7 +227,7 @@ bool TreeModel::removeRows(int position, int count, const QModelIndex & parent) /** * Test method for creating a tree model */ -void TreeModel::setupModelData(const QStringList &lines, TreeItem* parent) +void TreeModel::setupModelData(const QStringList& lines, TreeItem* parent) { QList<TreeItem*> parents; QList<int> indentations; @@ -252,7 +253,8 @@ void TreeModel::setupModelData(const QStringList &lines, TreeItem* parent) if (!lineData.isEmpty()) { // Read the column data from the rest of the line. - QStringList columnStrings = lineData.split("\t", QString::SkipEmptyParts); + QStringList columnStrings = + lineData.split("\t", QString::SkipEmptyParts); QList<QVariant> columnData; for (int column = 0; column < columnStrings.count(); ++column) { @@ -266,8 +268,8 @@ void TreeModel::setupModelData(const QStringList &lines, TreeItem* parent) if (parents.last()->childCount() > 0) { - parents << parents.last()->child(parents.last()->childCount( - ) - 1); + parents << parents.last()->child( + parents.last()->childCount() - 1); indentations << position; } } @@ -281,7 +283,8 @@ void TreeModel::setupModelData(const QStringList &lines, TreeItem* parent) } // Append a new item to the current parent's list of children. - parents.last()->appendChild(new TreeItem(columnData, parents.last())); + parents.last()->appendChild( + new TreeItem(columnData, parents.last())); } number++; diff --git a/Applications/DataExplorer/Base/TreeModelIterator.cpp b/Applications/DataExplorer/Base/TreeModelIterator.cpp index db3539ab89133cb119f346a69eae16af053145bb..dc8d2041399de3d63af204305ee24c98a0461452 100644 --- a/Applications/DataExplorer/Base/TreeModelIterator.cpp +++ b/Applications/DataExplorer/Base/TreeModelIterator.cpp @@ -42,7 +42,7 @@ TreeModelIterator& TreeModelIterator::operator++() return *this; } -TreeItem* TreeModelIterator::next( const TreeItem* current ) +TreeItem* TreeModelIterator::next(const TreeItem* current) { if (!current) { @@ -62,7 +62,7 @@ TreeItem* TreeModelIterator::next( const TreeItem* current ) // walk the sibling TreeItem* parent = current->parentItem(); next = parent ? parent->child(_currentIndex + 1) - : _model->rootItem()->child(_currentIndex + 1); + : _model->rootItem()->child(_currentIndex + 1); while (!next && parent) { // if we had no sibling walk up the parent @@ -70,7 +70,7 @@ TreeItem* TreeModelIterator::next( const TreeItem* current ) parent = parent->parentItem(); _currentIndex = _parentIndex.pop(); next = parent ? parent->child(_currentIndex + 1) - : _model->rootItem()->child(_currentIndex + 1); + : _model->rootItem()->child(_currentIndex + 1); } if (next) { diff --git a/Applications/DataExplorer/Base/modeltest.cpp b/Applications/DataExplorer/Base/modeltest.cpp index 45ba447084a91875f8bb3b4c5b71247e37c91164..9f6b31049ab2a285a2dc494f85e3a7fac7f6841e 100644 --- a/Applications/DataExplorer/Base/modeltest.cpp +++ b/Applications/DataExplorer/Base/modeltest.cpp @@ -21,58 +21,60 @@ ** ****************************************************************************/ -#include <QtGui/QtGui> - #include "modeltest.h" +#include <QtGui/QtGui> + Q_DECLARE_METATYPE(QModelIndex) /*! - Connect to all of the models signals. Whenever anything happens recheck everything. + Connect to all of the models signals. Whenever anything happens recheck + everything. */ -ModelTest::ModelTest(QAbstractItemModel* _model, - QObject* parent) : QObject(parent), model(_model), fetchingMore(false) +ModelTest::ModelTest(QAbstractItemModel* _model, QObject* parent) + : QObject(parent), model(_model), fetchingMore(false) { Q_ASSERT(model); - connect(model, SIGNAL(columnsAboutToBeInserted(const QModelIndex &, int, int)), - this, SLOT(runAllTests())); - connect(model, SIGNAL(columnsAboutToBeRemoved(const QModelIndex &, int, int)), - this, SLOT(runAllTests())); - connect(model, SIGNAL(columnsInserted(const QModelIndex &, int, int)), - this, SLOT(runAllTests())); - connect(model, SIGNAL(columnsRemoved(const QModelIndex &, int, int)), - this, SLOT(runAllTests())); - connect(model, SIGNAL(dataChanged(const QModelIndex &, const QModelIndex &)), - this, SLOT(runAllTests())); - connect(model, SIGNAL(headerDataChanged(Qt::Orientation, int, int)), - this, SLOT(runAllTests())); - connect(model, SIGNAL(layoutAboutToBeChanged ()), this, SLOT(runAllTests())); - connect(model, SIGNAL(layoutChanged ()), this, SLOT(runAllTests())); - connect(model, SIGNAL(modelReset ()), this, SLOT(runAllTests())); - connect(model, SIGNAL(rowsAboutToBeInserted(const QModelIndex &, int, int)), + connect(model, + SIGNAL(columnsAboutToBeInserted(const QModelIndex&, int, int)), this, SLOT(runAllTests())); - connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)), + connect(model, + SIGNAL(columnsAboutToBeRemoved(const QModelIndex&, int, int)), this, + SLOT(runAllTests())); + connect(model, SIGNAL(columnsInserted(const QModelIndex&, int, int)), this, + SLOT(runAllTests())); + connect(model, SIGNAL(columnsRemoved(const QModelIndex&, int, int)), this, + SLOT(runAllTests())); + connect(model, SIGNAL(dataChanged(const QModelIndex&, const QModelIndex&)), this, SLOT(runAllTests())); - connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)), + connect(model, SIGNAL(headerDataChanged(Qt::Orientation, int, int)), this, + SLOT(runAllTests())); + connect(model, SIGNAL(layoutAboutToBeChanged()), this, SLOT(runAllTests())); + connect(model, SIGNAL(layoutChanged()), this, SLOT(runAllTests())); + connect(model, SIGNAL(modelReset()), this, SLOT(runAllTests())); + connect(model, SIGNAL(rowsAboutToBeInserted(const QModelIndex&, int, int)), this, SLOT(runAllTests())); - connect(model, SIGNAL(rowsRemoved(const QModelIndex &, int, int)), + connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex&, int, int)), this, SLOT(runAllTests())); + connect(model, SIGNAL(rowsInserted(const QModelIndex&, int, int)), this, + SLOT(runAllTests())); + connect(model, SIGNAL(rowsRemoved(const QModelIndex&, int, int)), this, + SLOT(runAllTests())); // Special checks for inserting/removing - connect(model, SIGNAL(layoutAboutToBeChanged()), - this, SLOT(layoutAboutToBeChanged())); - connect(model, SIGNAL(layoutChanged()), - this, SLOT(layoutChanged())); - - connect(model, SIGNAL(rowsAboutToBeInserted(const QModelIndex &, int, int)), - this, SLOT(rowsAboutToBeInserted(const QModelIndex &, int, int))); - connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)), - this, SLOT(rowsAboutToBeRemoved(const QModelIndex &, int, int))); - connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)), - this, SLOT(rowsInserted(const QModelIndex &, int, int))); - connect(model, SIGNAL(rowsRemoved(const QModelIndex &, int, int)), - this, SLOT(rowsRemoved(const QModelIndex &, int, int))); + connect(model, SIGNAL(layoutAboutToBeChanged()), this, + SLOT(layoutAboutToBeChanged())); + connect(model, SIGNAL(layoutChanged()), this, SLOT(layoutChanged())); + + connect(model, SIGNAL(rowsAboutToBeInserted(const QModelIndex&, int, int)), + this, SLOT(rowsAboutToBeInserted(const QModelIndex&, int, int))); + connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex&, int, int)), + this, SLOT(rowsAboutToBeRemoved(const QModelIndex&, int, int))); + connect(model, SIGNAL(rowsInserted(const QModelIndex&, int, int)), this, + SLOT(rowsInserted(const QModelIndex&, int, int))); + connect(model, SIGNAL(rowsRemoved(const QModelIndex&, int, int)), this, + SLOT(rowsRemoved(const QModelIndex&, int, int))); runAllTests(); } @@ -91,8 +93,9 @@ void ModelTest::runAllTests() } /*! - nonDestructiveBasicTest tries to call a number of the basic functions (not all) - to make sure the model doesn't outright segfault, testing the functions that makes sense. + nonDestructiveBasicTest tries to call a number of the basic functions (not + all) to make sure the model doesn't outright segfault, testing the functions + that makes sense. */ void ModelTest::nonDestructiveBasicTest() { @@ -128,7 +131,8 @@ void ModelTest::nonDestructiveBasicTest() } /*! - Tests model's implementation of QAbstractItemModel::rowCount() and hasChildren() + Tests model's implementation of QAbstractItemModel::rowCount() and + hasChildren() Models that are dynamically populated are not as fully tested here. */ @@ -142,8 +146,8 @@ void ModelTest::rowCount() Q_ASSERT(model->hasChildren(topIndex) == true); QModelIndex secondLevelIndex = model->index(0, 0, topIndex); - if (secondLevelIndex.isValid()) // not the top level - { // check a row count where parent is valid + if (secondLevelIndex.isValid()) // not the top level + { // check a row count where parent is valid rows = model->rowCount(secondLevelIndex); Q_ASSERT(rows >= 0); if (rows > 0) @@ -155,7 +159,8 @@ void ModelTest::rowCount() } /*! - Tests model's implementation of QAbstractItemModel::columnCount() and hasChildren() + Tests model's implementation of QAbstractItemModel::columnCount() and + hasChildren() */ void ModelTest::columnCount() { @@ -277,15 +282,15 @@ void ModelTest::parent() A model that returns an index of parent X should also return X when asking for the parent of the index. - This recursive function does pretty extensive testing on the whole model in an - effort to catch edge cases. + This recursive function does pretty extensive testing on the whole model in + an effort to catch edge cases. - This function assumes that rowCount(), columnCount() and index() already work. - If they have a bug it will point it out, but the above tests should have already - found the basic bugs because it is easier to figure out the problem in - those tests then this one. + This function assumes that rowCount(), columnCount() and index() already + work. If they have a bug it will point it out, but the above tests should + have already found the basic bugs because it is easier to figure out the + problem in those tests then this one. */ -void ModelTest::checkChildren(const QModelIndex &parent, int currentDepth) +void ModelTest::checkChildren(const QModelIndex& parent, int currentDepth) { // First just try walking back up the tree. QModelIndex p = parent; @@ -312,7 +317,8 @@ void ModelTest::checkChildren(const QModelIndex &parent, int currentDepth) if (rows > 0) Q_ASSERT(model->hasChildren(parent) == true); - //qDebug() << "parent:" << model->data(parent).toString() << "rows:" << rows + // qDebug() << "parent:" << model->data(parent).toString() << "rows:" << + // rows // << "columns:" << columns << "parent column:" << parent.column(); Q_ASSERT(model->hasIndex(rows + 1, 0, parent) == false); @@ -332,7 +338,8 @@ void ModelTest::checkChildren(const QModelIndex &parent, int currentDepth) // rowCount() and columnCount() said that it existed... Q_ASSERT(index.isValid() == true); - // index() should always return the same index when called twice in a row + // index() should always return the same index when called twice in + // a row QModelIndex modifiedIndex = model->index(r, c, parent); Q_ASSERT(index == modifiedIndex); @@ -345,14 +352,17 @@ void ModelTest::checkChildren(const QModelIndex &parent, int currentDepth) Q_ASSERT(index.model() == model); Q_ASSERT(index.row() == r); Q_ASSERT(index.column() == c); - // While you can technically return a QVariant usually this is a sign - // of an bug in data() Disable if this really is ok in your model. - //Q_ASSERT(model->data(index, Qt::DisplayRole).isValid() == true); + // While you can technically return a QVariant usually this is a + // sign of an bug in data() Disable if this really is ok in your + // model. + // Q_ASSERT(model->data(index, Qt::DisplayRole).isValid() == true); - // If the next test fails here is some somewhat useful debug you play with. + // If the next test fails here is some somewhat useful debug you + // play with. /* if (model->parent(index) != parent) { - qDebug() << r << c << currentDepth << model->data(index).toString() + qDebug() << r << c << currentDepth << + model->data(index).toString() << model->data(parent).toString(); qDebug() << index << parent << model->parent(index); // And a view that you can even use to show the model. @@ -363,18 +373,21 @@ void ModelTest::checkChildren(const QModelIndex &parent, int currentDepth) // Check that we can get back our real parent. QModelIndex p = model->parent(index); - //qDebug() << "child:" << index; - //qDebug() << p; - //qDebug() << parent; + // qDebug() << "child:" << index; + // qDebug() << p; + // qDebug() << parent; Q_ASSERT(model->parent(index) == parent); // recursively go down the children - if (model->hasChildren(index) && currentDepth < 10 ) - //qDebug() << r << c << "has children" << model->rowCount(index); + if (model->hasChildren(index) && currentDepth < 10) + // qDebug() << r << c << "has children" << + // model->rowCount(index); checkChildren(index, ++currentDepth); - /* else { if (currentDepth >= 10) qDebug() << "checked 10 deep"; };*/ + /* else { if (currentDepth >= 10) qDebug() << "checked 10 deep"; + * };*/ - // make sure that after testing the children that the index doesn't change. + // make sure that after testing the children that the index doesn't + // change. QModelIndex newerIndex = model->index(r, c, parent); Q_ASSERT(index == newerIndex); } @@ -396,7 +409,8 @@ void ModelTest::data() Q_ASSERT(model->index(0, 0).isValid()); // shouldn't be able to set data on an invalid index - Q_ASSERT(model->setData(QModelIndex(), QLatin1String("foo"), Qt::DisplayRole) == false); + Q_ASSERT(model->setData(QModelIndex(), QLatin1String("foo"), + Qt::DisplayRole) == false); // General Purpose roles that should return a QString QVariant variant = model->data(model->index(0, 0), Qt::ToolTipRole); @@ -420,25 +434,23 @@ void ModelTest::data() Q_ASSERT(fontVariant.canConvert(QMetaType::QFont))); // Check that the alignment is one we know about - QVariant textAlignmentVariant = model->data(model->index(0, 0), Qt::TextAlignmentRole); + QVariant textAlignmentVariant = + model->data(model->index(0, 0), Qt::TextAlignmentRole); if (textAlignmentVariant.isValid()) { int alignment = textAlignmentVariant.toInt(); - Q_ASSERT(alignment == Qt::AlignLeft || - alignment == Qt::AlignRight || - alignment == Qt::AlignHCenter || - alignment == Qt::AlignJustify || - alignment == Qt::AlignTop || - alignment == Qt::AlignBottom || - alignment == Qt::AlignVCenter || - alignment == Qt::AlignCenter || - alignment == Qt::AlignAbsolute || - alignment == Qt::AlignLeading || - alignment == Qt::AlignTrailing); + Q_ASSERT( + alignment == Qt::AlignLeft || alignment == Qt::AlignRight || + alignment == Qt::AlignHCenter || alignment == Qt::AlignJustify || + alignment == Qt::AlignTop || alignment == Qt::AlignBottom || + alignment == Qt::AlignVCenter || alignment == Qt::AlignCenter || + alignment == Qt::AlignAbsolute || alignment == Qt::AlignLeading || + alignment == Qt::AlignTrailing); } // General Purpose roles that should return a QColor - QVariant colorVariant = model->data(model->index(0, 0), Qt::BackgroundColorRole); + QVariant colorVariant = + model->data(model->index(0, 0), Qt::BackgroundColorRole); if (colorVariant.isValid()) Q_ASSERT(colorVariant.canConvert(QMetaType::QColor))); @@ -447,12 +459,12 @@ void ModelTest::data() Q_ASSERT(colorVariant.canConvert(QMetaType::QColor))); // Check that the "check state" is one we know about. - QVariant checkStateVariant = model->data(model->index(0, 0), Qt::CheckStateRole); + QVariant checkStateVariant = + model->data(model->index(0, 0), Qt::CheckStateRole); if (checkStateVariant.isValid()) { int state = checkStateVariant.toInt(); - Q_ASSERT(state == Qt::Unchecked || - state == Qt::PartiallyChecked || + Q_ASSERT(state == Qt::Unchecked || state == Qt::PartiallyChecked || state == Qt::Checked); } } @@ -462,7 +474,8 @@ void ModelTest::data() \sa rowsInserted() */ -void ModelTest::rowsAboutToBeInserted(const QModelIndex &parent, int start, int end) +void ModelTest::rowsAboutToBeInserted(const QModelIndex& parent, int start, + int end) { Q_UNUSED(end); Changing c; @@ -478,7 +491,7 @@ void ModelTest::rowsAboutToBeInserted(const QModelIndex &parent, int start, int \sa rowsAboutToBeInserted() */ -void ModelTest::rowsInserted(const QModelIndex & parent, int start, int end) +void ModelTest::rowsInserted(const QModelIndex& parent, int start, int end) { Changing c = insert.pop(); Q_ASSERT(c.parent == parent); @@ -516,7 +529,8 @@ void ModelTest::layoutChanged() \sa rowsRemoved() */ -void ModelTest::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) +void ModelTest::rowsAboutToBeRemoved(const QModelIndex& parent, int start, + int end) { Changing c; c.parent = parent; @@ -531,7 +545,7 @@ void ModelTest::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int e \sa rowsAboutToBeRemoved() */ -void ModelTest::rowsRemoved(const QModelIndex & parent, int start, int end) +void ModelTest::rowsRemoved(const QModelIndex& parent, int start, int end) { Changing c = remove.pop(); Q_ASSERT(c.parent == parent); diff --git a/Applications/DataExplorer/DataView/AddLayerToMeshDialog.cpp b/Applications/DataExplorer/DataView/AddLayerToMeshDialog.cpp index cc683323ca756bd6a52fa19a4210244aaa7e6928..26cca07ed144ad95102a68bd0af8db930cad5f6a 100644 --- a/Applications/DataExplorer/DataView/AddLayerToMeshDialog.cpp +++ b/Applications/DataExplorer/DataView/AddLayerToMeshDialog.cpp @@ -13,17 +13,16 @@ */ #include "AddLayerToMeshDialog.h" + #include "OGSError.h" #include "StrictDoubleValidator.h" - -AddLayerToMeshDialog::AddLayerToMeshDialog(QDialog* parent) -: QDialog(parent) +AddLayerToMeshDialog::AddLayerToMeshDialog(QDialog* parent) : QDialog(parent) { setupUi(this); auto* thickness_validator = new StrictDoubleValidator(0, 1000000, 7, this); - this->thicknessEdit->setValidator (thickness_validator); + this->thicknessEdit->setValidator(thickness_validator); } void AddLayerToMeshDialog::accept() @@ -47,4 +46,3 @@ void AddLayerToMeshDialog::reject() { this->done(QDialog::Rejected); } - diff --git a/Applications/DataExplorer/DataView/ColorTableModel.cpp b/Applications/DataExplorer/DataView/ColorTableModel.cpp index 09c66619230e1c3104a58f4a3c0a90a72466058b..6f8d3a74c0ffea447c001dcce01e7cc9ea8c8d7a 100644 --- a/Applications/DataExplorer/DataView/ColorTableModel.cpp +++ b/Applications/DataExplorer/DataView/ColorTableModel.cpp @@ -14,8 +14,9 @@ #include "ColorTableModel.h" -ColorTableModel::ColorTableModel( const std::map<std::string, DataHolderLib::Color*> &colorLookupTable, - QObject* parent /*= 0*/ ) +ColorTableModel::ColorTableModel( + const std::map<std::string, DataHolderLib::Color*>& colorLookupTable, + QObject* parent /*= 0*/) { Q_UNUSED(parent) @@ -24,15 +25,16 @@ ColorTableModel::ColorTableModel( const std::map<std::string, DataHolderLib::Col ColorTableModel::~ColorTableModel() = default; -int ColorTableModel::columnCount( const QModelIndex& parent /*= QModelIndex()*/ ) const +int ColorTableModel::columnCount( + const QModelIndex& parent /*= QModelIndex()*/) const { Q_UNUSED(parent) return 2; } -QVariant ColorTableModel::headerData( int section, Qt::Orientation orientation, - int role /*= Qt::DisplayRole*/ ) const +QVariant ColorTableModel::headerData(int section, Qt::Orientation orientation, + int role /*= Qt::DisplayRole*/) const { if (role != Qt::DisplayRole) { @@ -43,9 +45,12 @@ QVariant ColorTableModel::headerData( int section, Qt::Orientation orientation, { switch (section) { - case 0: return "Name"; - case 1: return "Colour"; - default: return QVariant(); + case 0: + return "Name"; + case 1: + return "Colour"; + default: + return QVariant(); } } else @@ -54,7 +59,7 @@ QVariant ColorTableModel::headerData( int section, Qt::Orientation orientation, } } -QVariant ColorTableModel::data( const QModelIndex& index, int role ) const +QVariant ColorTableModel::data(const QModelIndex& index, int role) const { if (!index.isValid()) { @@ -72,18 +77,19 @@ QVariant ColorTableModel::data( const QModelIndex& index, int role ) const switch (index.column()) { - case 0: - return pair.first; - case 1: - return pair.second; - default: - return QVariant(); + case 0: + return pair.first; + case 1: + return pair.second; + default: + return QVariant(); } } return QVariant(); } -bool ColorTableModel::buildTable(const std::map<std::string, DataHolderLib::Color*> &colorLookupTable) +bool ColorTableModel::buildTable( + const std::map<std::string, DataHolderLib::Color*>& colorLookupTable) { int count = 0; beginInsertRows(QModelIndex(), 0, colorLookupTable.size() - 1); @@ -110,4 +116,3 @@ bool ColorTableModel::buildTable(const std::map<std::string, DataHolderLib::Colo endInsertRows(); return true; } - diff --git a/Applications/DataExplorer/DataView/ColorTableView.cpp b/Applications/DataExplorer/DataView/ColorTableView.cpp index ffe19c6e97997feaa6f4c70a89727fc267b60ad5..cd99107b12a6281ba21128b7c763662cf8f5821d 100644 --- a/Applications/DataExplorer/DataView/ColorTableView.cpp +++ b/Applications/DataExplorer/DataView/ColorTableView.cpp @@ -14,10 +14,11 @@ */ #include "ColorTableView.h" + #include <QHeaderView> #include <QPainter> -ColorTableView::ColorTableView( QWidget* parent /*= 0*/ ) : QTableView(parent) +ColorTableView::ColorTableView(QWidget* parent /*= 0*/) : QTableView(parent) { this->verticalHeader()->hide(); this->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); @@ -26,8 +27,8 @@ ColorTableView::ColorTableView( QWidget* parent /*= 0*/ ) : QTableView(parent) } void ColorTableViewDelegate::paint(QPainter* painter, - const QStyleOptionViewItem &option, - const QModelIndex &index) const + const QStyleOptionViewItem& option, + const QModelIndex& index) const { QColor val; if (index.column() == 1) @@ -45,8 +46,8 @@ void ColorTableViewDelegate::paint(QPainter* painter, } } -QSize ColorTableViewDelegate::sizeHint( const QStyleOptionViewItem &option, - const QModelIndex &index ) const +QSize ColorTableViewDelegate::sizeHint(const QStyleOptionViewItem& option, + const QModelIndex& index) const { QSize s = QItemDelegate::sizeHint(option, index); if (s.isValid()) diff --git a/Applications/DataExplorer/DataView/CondFromRasterDialog.cpp b/Applications/DataExplorer/DataView/CondFromRasterDialog.cpp index bbc1a4b51c75713a039b54750b353186cc8ef665..570764d7918f2d634bd700dcb7a0c9077777c4d5 100644 --- a/Applications/DataExplorer/DataView/CondFromRasterDialog.cpp +++ b/Applications/DataExplorer/DataView/CondFromRasterDialog.cpp @@ -13,13 +13,13 @@ */ #include "CondFromRasterDialog.h" -#include "Mesh.h" #include <QFileDialog> #include <QSettings> #include <utility> #include "DirectConditionGenerator.h" +#include "Mesh.h" #include "OGSError.h" #include "StrictDoubleValidator.h" @@ -32,7 +32,7 @@ CondFromRasterDialog::CondFromRasterDialog(std::vector<MeshLib::Mesh*> msh_vec, this->scalingEdit->setEnabled(false); _scale_validator = new StrictDoubleValidator(-1e+10, 1e+20, 5); this->scalingEdit->setText("1.0"); - this->scalingEdit->setValidator (_scale_validator); + this->scalingEdit->setValidator(_scale_validator); for (auto mesh : _msh_vec) { @@ -55,9 +55,10 @@ void CondFromRasterDialog::on_selectButton_pressed() #else QString geotiffExtension(""); #endif - QString fileName = QFileDialog::getOpenFileName(this, "Select raster file", - settings.value("lastOpenedRasterFileDirectory").toString(), - QString("Raster files (*.asc *.grd);;").arg(geotiffExtension)); + QString fileName = QFileDialog::getOpenFileName( + this, "Select raster file", + settings.value("lastOpenedRasterFileDirectory").toString(), + QString("Raster files (*.asc *.grd);;").arg(geotiffExtension)); if (!fileName.isEmpty()) { @@ -68,13 +69,12 @@ void CondFromRasterDialog::on_selectButton_pressed() } } - void CondFromRasterDialog::accept() { - std::string mesh_name (this->meshBox->currentText().toStdString()); - std::string raster_name (this->rasterEdit->text().toStdString()); + std::string mesh_name(this->meshBox->currentText().toStdString()); + std::string raster_name(this->rasterEdit->text().toStdString()); double scaling_factor = this->scalingEdit->text().toDouble(); - std::vector< std::pair<std::size_t,double> > direct_values; + std::vector<std::pair<std::size_t, double>> direct_values; if (mesh_name.empty()) { @@ -101,7 +101,7 @@ void CondFromRasterDialog::accept() { DirectConditionGenerator dcg; direct_values = dcg.directToSurfaceNodes(*mesh, raster_name); - //dcg.writeToFile(direct_node_name); + // dcg.writeToFile(direct_node_name); } else { @@ -112,11 +112,12 @@ void CondFromRasterDialog::accept() } auto* new_mesh = const_cast<MeshLib::Mesh*>(mesh); DirectConditionGenerator dcg; - direct_values = dcg.directWithSurfaceIntegration(*new_mesh, raster_name, scaling_factor); + direct_values = dcg.directWithSurfaceIntegration(*new_mesh, raster_name, + scaling_factor); - //dcg.writeToFile(direct_node_name); + // dcg.writeToFile(direct_node_name); } - //emit directNodesWritten(direct_node_name); + // emit directNodesWritten(direct_node_name); emit transmitDisValues(direct_values); this->done(QDialog::Accepted); } diff --git a/Applications/DataExplorer/DataView/CreateStructuredGridDialog.cpp b/Applications/DataExplorer/DataView/CreateStructuredGridDialog.cpp index 18ecbc8e93e94350f7cdf79cc868b527ffc0eb30..f9a64d936ac7fbd6dd65787325dbcf8fc1e32c88 100644 --- a/Applications/DataExplorer/DataView/CreateStructuredGridDialog.cpp +++ b/Applications/DataExplorer/DataView/CreateStructuredGridDialog.cpp @@ -18,12 +18,11 @@ #include "GeoLib/Point.h" #include "MeshLib/MeshGenerators/MeshGenerator.h" - -#include "StrictDoubleValidator.h" #include "OGSError.h" +#include "StrictDoubleValidator.h" - -CreateStructuredGridDialog::CreateStructuredGridDialog(QDialog* parent) : QDialog(parent) +CreateStructuredGridDialog::CreateStructuredGridDialog(QDialog* parent) + : QDialog(parent) { setupUi(this); setValidators(); @@ -32,25 +31,25 @@ CreateStructuredGridDialog::CreateStructuredGridDialog(QDialog* parent) : QDialo void CreateStructuredGridDialog::setValidators() { auto* origin_x_validator = new StrictDoubleValidator(this); - this->xOriginEdit->setValidator (origin_x_validator); + this->xOriginEdit->setValidator(origin_x_validator); auto* origin_y_validator = new StrictDoubleValidator(this); - this->yOriginEdit->setValidator (origin_y_validator); + this->yOriginEdit->setValidator(origin_y_validator); auto* origin_z_validator = new StrictDoubleValidator(this); - this->zOriginEdit->setValidator (origin_z_validator); + this->zOriginEdit->setValidator(origin_z_validator); auto* x_length_validator = new StrictDoubleValidator(0, 10000000, 10, this); - this->xLengthEdit->setValidator (x_length_validator); + this->xLengthEdit->setValidator(x_length_validator); auto* y_length_validator = new StrictDoubleValidator(0, 10000000, 10, this); - this->yLengthEdit->setValidator (y_length_validator); + this->yLengthEdit->setValidator(y_length_validator); auto* z_length_validator = new StrictDoubleValidator(0, 10000000, 10, this); - this->zLengthEdit->setValidator (z_length_validator); + this->zLengthEdit->setValidator(z_length_validator); auto* x_n_elem_validator = new QIntValidator(1, 10000000, this); - this->xElemEdit->setValidator (x_n_elem_validator); + this->xElemEdit->setValidator(x_n_elem_validator); auto* y_n_elem_validator = new QIntValidator(1, 10000000, this); - this->yElemEdit->setValidator (y_n_elem_validator); + this->yElemEdit->setValidator(y_n_elem_validator); auto* z_n_elem_validator = new QIntValidator(1, 10000000, this); - this->zElemEdit->setValidator (z_n_elem_validator); + this->zElemEdit->setValidator(z_n_elem_validator); } void CreateStructuredGridDialog::on_lineButton_toggled() const @@ -105,10 +104,12 @@ void CreateStructuredGridDialog::on_elemExtentButton_toggled() bool CreateStructuredGridDialog::inputIsEmpty() const { - QString const type_str = (this->meshExtentButton->isChecked()) ? "mesh" : "element"; + QString const type_str = + (this->meshExtentButton->isChecked()) ? "mesh" : "element"; if (this->xLengthEdit->text().isEmpty()) { - OGSError::box("Please specify " + type_str + "\nextent in x-direction."); + OGSError::box("Please specify " + type_str + + "\nextent in x-direction."); return true; } if (this->xElemEdit->text().isEmpty()) @@ -133,7 +134,8 @@ bool CreateStructuredGridDialog::inputIsEmpty() const { if (this->yLengthEdit->text().isEmpty()) { - OGSError::box("Please specify " + type_str + "\nextent in y-direction."); + OGSError::box("Please specify " + type_str + + "\nextent in y-direction."); return true; } if (this->yElemEdit->text().isEmpty()) @@ -147,7 +149,8 @@ bool CreateStructuredGridDialog::inputIsEmpty() const { if (this->zLengthEdit->text().isEmpty()) { - OGSError::box("Please specify " + type_str + "\nextent in z-direction."); + OGSError::box("Please specify " + type_str + + "\nextent in z-direction."); return true; } if (this->zElemEdit->text().isEmpty()) @@ -185,14 +188,15 @@ void CreateStructuredGridDialog::accept() GeoLib::Point const origin(this->xOriginEdit->text().toDouble(), this->yOriginEdit->text().toDouble(), this->zOriginEdit->text().toDouble()); - std::string const name (this->meshNameEdit->text().toStdString()); - MeshLib::Mesh* mesh (nullptr); + std::string const name(this->meshNameEdit->text().toStdString()); + MeshLib::Mesh* mesh(nullptr); if (this->lineButton->isChecked()) { if (this->meshExtentButton->isChecked()) { mesh = MeshLib::MeshGenerator::generateLineMesh( - this->xLengthEdit->text().toDouble(), this->xElemEdit->text().toInt(), origin, name); + this->xLengthEdit->text().toDouble(), + this->xElemEdit->text().toInt(), origin, name); } else { @@ -206,9 +210,10 @@ void CreateStructuredGridDialog::accept() if (this->meshExtentButton->isChecked()) { mesh = MeshLib::MeshGenerator::generateRegularTriMesh( - this->xLengthEdit->text().toDouble(), this->yLengthEdit->text().toDouble(), - this->xElemEdit->text().toInt(), this->yElemEdit->text().toInt(), - origin, name); + this->xLengthEdit->text().toDouble(), + this->yLengthEdit->text().toDouble(), + this->xElemEdit->text().toInt(), + this->yElemEdit->text().toInt(), origin, name); } else { @@ -224,9 +229,10 @@ void CreateStructuredGridDialog::accept() if (this->meshExtentButton->isChecked()) { mesh = MeshLib::MeshGenerator::generateRegularQuadMesh( - this->xLengthEdit->text().toDouble(), this->yLengthEdit->text().toDouble(), - this->xElemEdit->text().toInt(), this->yElemEdit->text().toInt(), - origin, name); + this->xLengthEdit->text().toDouble(), + this->yLengthEdit->text().toDouble(), + this->xElemEdit->text().toInt(), + this->yElemEdit->text().toInt(), origin, name); } else { @@ -242,10 +248,12 @@ void CreateStructuredGridDialog::accept() if (this->meshExtentButton->isChecked()) { mesh = MeshLib::MeshGenerator::generateRegularPrismMesh( - this->xLengthEdit->text().toDouble(), this->yLengthEdit->text().toDouble(), - this->zLengthEdit->text().toDouble(), this->xElemEdit->text().toInt(), - this->yElemEdit->text().toInt(), this->zElemEdit->text().toInt(), - origin, name); + this->xLengthEdit->text().toDouble(), + this->yLengthEdit->text().toDouble(), + this->zLengthEdit->text().toDouble(), + this->xElemEdit->text().toInt(), + this->yElemEdit->text().toInt(), + this->zElemEdit->text().toInt(), origin, name); } else { @@ -295,4 +303,3 @@ void CreateStructuredGridDialog::accept() emit meshAdded(mesh); this->done(QDialog::Accepted); } - diff --git a/Applications/DataExplorer/DataView/DataExplorerSettingsDialog.cpp b/Applications/DataExplorer/DataView/DataExplorerSettingsDialog.cpp index ba617cf60f7c0e528d77356fefcd526a9eefaad2..1f3c082a88a425dc593f98000df9ddde64608671 100644 --- a/Applications/DataExplorer/DataView/DataExplorerSettingsDialog.cpp +++ b/Applications/DataExplorer/DataView/DataExplorerSettingsDialog.cpp @@ -17,16 +17,16 @@ #include <QFileDialog> #include <QSettings> - #include "OGSError.h" - -DataExplorerSettingsDialog::DataExplorerSettingsDialog(QDialog* parent) : QDialog(parent) +DataExplorerSettingsDialog::DataExplorerSettingsDialog(QDialog* parent) + : QDialog(parent) { setupUi(this); QSettings settings; - this->gmshPathEdit->setText(settings.value("DataExplorerGmshPath").toString()); + this->gmshPathEdit->setText( + settings.value("DataExplorerGmshPath").toString()); } DataExplorerSettingsDialog::~DataExplorerSettingsDialog() = default; @@ -34,9 +34,9 @@ DataExplorerSettingsDialog::~DataExplorerSettingsDialog() = default; void DataExplorerSettingsDialog::on_gmshPathButton_clicked() { QSettings settings; - QString file_name = QFileDialog::getOpenFileName(this, "Select path for GMSH...", - settings.value("DataExplorerGmshPath").toString(), - "*gmsh*"); + QString file_name = QFileDialog::getOpenFileName( + this, "Select path for GMSH...", + settings.value("DataExplorerGmshPath").toString(), "*gmsh*"); if (!file_name.isEmpty()) { this->gmshPathEdit->setText(file_name); @@ -49,5 +49,3 @@ void DataExplorerSettingsDialog::accept() settings.setValue("DataExplorerGmshPath", this->gmshPathEdit->text()); this->done(QDialog::Accepted); } - - diff --git a/Applications/DataExplorer/DataView/DiagramView/DetailWindow.cpp b/Applications/DataExplorer/DataView/DiagramView/DetailWindow.cpp index 165409069759f14cb0847a39e5a988a5d281fde9..9443448038b7afeda576dfdf983cc6b81992eefd 100644 --- a/Applications/DataExplorer/DataView/DiagramView/DetailWindow.cpp +++ b/Applications/DataExplorer/DataView/DiagramView/DetailWindow.cpp @@ -23,53 +23,53 @@ DetailWindow::DetailWindow(QWidget* parent) : QWidget(parent) { setupUi(this); - stationView->setRenderHints( QPainter::Antialiasing ); - -/* - DiagramList* list = new DiagramList(); - DiagramList* list2 = new DiagramList(); - - - // ================================================== - // input files should be defined in WaterML - // inserting the details below into the list-objects - // kind of simulates the information that would be - // included in a WaterML-file and is needed for - // display - // ================================================== - - // make up list-object for the first test station - list->setName("Water Level Observation Station: Halberstadt 2002"); - list->setXLabel("Time"); - list->setYLabel("Water Level"); - list->setXUnit("day"); - list->setYUnit("metres"); - list->setColor(QColor(Qt::red)); - list->readList("c:\\project\\timeseries-a.stn"); - - // make up list-object for the second test station - list2->setName("Water Level Observation Station: Oschersleben 2002"); - list2->setXLabel("Time"); - list2->setYLabel("Water Level"); - list2->setXUnit("day"); - list2->setYUnit("metres"); - list2->setColor(QColor(Qt::green)); - list2->readList("c:\\project\\timeseries-b.stn"); - - // ================================================== + stationView->setRenderHints(QPainter::Antialiasing); + + /* + DiagramList* list = new DiagramList(); + DiagramList* list2 = new DiagramList(); + + + // ================================================== + // input files should be defined in WaterML + // inserting the details below into the list-objects + // kind of simulates the information that would be + // included in a WaterML-file and is needed for + // display + // ================================================== + + // make up list-object for the first test station + list->setName("Water Level Observation Station: Halberstadt 2002"); + list->setXLabel("Time"); + list->setYLabel("Water Level"); + list->setXUnit("day"); + list->setYUnit("metres"); + list->setColor(QColor(Qt::red)); + list->readList("c:\\project\\timeseries-a.stn"); + + // make up list-object for the second test station + list2->setName("Water Level Observation Station: Oschersleben 2002"); + list2->setXLabel("Time"); + list2->setYLabel("Water Level"); + list2->setXUnit("day"); + list2->setYUnit("metres"); + list2->setColor(QColor(Qt::green)); + list2->readList("c:\\project\\timeseries-b.stn"); + + // ================================================== - stationView->addGraph(list); - stationView->addGraph(list2); + stationView->addGraph(list); + stationView->addGraph(list2); - resizeWindow(); - */ + resizeWindow(); + */ } DetailWindow::DetailWindow(QString filename, QWidget* parent) : QWidget(parent) { setupUi(this); - stationView->setRenderHints( QPainter::Antialiasing ); + stationView->setRenderHints(QPainter::Antialiasing); std::vector<DiagramList*> lists; DiagramList::readList(filename, lists); @@ -85,16 +85,17 @@ DetailWindow::DetailWindow(QString filename, QWidget* parent) : QWidget(parent) DetailWindow::DetailWindow(DiagramList* list, QWidget* parent) : QWidget(parent) { setupUi(this); - stationView->setRenderHints( QPainter::Antialiasing ); + stationView->setRenderHints(QPainter::Antialiasing); stationView->addGraph(list); resizeWindow(); } -DetailWindow::DetailWindow(std::vector<std::size_t> data, QWidget* parent) : QWidget(parent) +DetailWindow::DetailWindow(std::vector<std::size_t> data, QWidget* parent) + : QWidget(parent) { setupUi(this); std::size_t nEntries = data.size(); - std::vector< std::pair<float, float> > list_data(nEntries); + std::vector<std::pair<float, float>> list_data(nEntries); for (std::size_t i = 0; i < nEntries; i++) { @@ -107,7 +108,7 @@ DetailWindow::DetailWindow(std::vector<std::size_t> data, QWidget* parent) : QWi list->setXUnit("Value"); list->setYUnit("Amount"); list->setName("Histogram"); - stationView->setRenderHints( QPainter::Antialiasing ); + stationView->setRenderHints(QPainter::Antialiasing); stationView->addGraph(list); resizeWindow(); } @@ -122,7 +123,8 @@ void DetailWindow::on_closeButton_clicked() void DetailWindow::resizeWindow() { int width = (stationView->getWidth() > 800) ? 800 : stationView->getWidth(); - int height = (stationView->getHeight() > 600) ? 600 : stationView->getHeight(); + int height = + (stationView->getHeight() > 600) ? 600 : stationView->getHeight(); resize(width, height); } @@ -143,9 +145,10 @@ void DetailWindow::addList(DiagramList* list, QColor c) void DetailWindow::on_addDataButton_clicked() { QSettings settings; - QString fileName = QFileDialog::getOpenFileName( this, "Select data file to open", - settings.value("lastOpenedFileDirectory").toString(), - "Text files (*.txt);;All files (* *.*)"); + QString fileName = QFileDialog::getOpenFileName( + this, "Select data file to open", + settings.value("lastOpenedFileDirectory").toString(), + "Text files (*.txt);;All files (* *.*)"); if (!fileName.isEmpty()) { QDir dir = QDir(fileName); @@ -155,4 +158,3 @@ void DetailWindow::on_addDataButton_clicked() prefs->show(); } } - diff --git a/Applications/DataExplorer/DataView/DiagramView/DiagramList.cpp b/Applications/DataExplorer/DataView/DiagramView/DiagramList.cpp index b33db5f1cc2ff91268a6ded1c48ecaec6d662c87..bba60cb056eb5082bc65288ee24b636c27c9abff 100644 --- a/Applications/DataExplorer/DataView/DiagramView/DiagramList.cpp +++ b/Applications/DataExplorer/DataView/DiagramView/DiagramList.cpp @@ -13,17 +13,17 @@ */ #include "DiagramList.h" -#include "GetDateTime.h" - -#include "BaseLib/Logging.h" -#include "DateTools.h" -#include "StringTools.h" -#include "SensorData.h" #include <QFile> #include <QTextStream> #include <limits> +#include "BaseLib/Logging.h" +#include "DateTools.h" +#include "GetDateTime.h" +#include "SensorData.h" +#include "StringTools.h" + DiagramList::DiagramList() : _xLabel(""), _yLabel(""), _xUnit(""), _yUnit("") {} DiagramList::~DiagramList() = default; @@ -82,7 +82,7 @@ float DiagramList::calcMaxYValue() return max; } -bool DiagramList::getPath(QPainterPath &path, float scaleX, float scaleY) +bool DiagramList::getPath(QPainterPath& path, float scaleX, float scaleY) { QPointF p; if (getPoint(p, 0)) @@ -102,7 +102,7 @@ bool DiagramList::getPath(QPainterPath &path, float scaleX, float scaleY) return false; } -bool DiagramList::getPoint(QPointF &p, std::size_t i) +bool DiagramList::getPoint(QPointF& p, std::size_t i) { if (i < _coords.size()) { @@ -154,10 +154,10 @@ bool DiagramList::getPoint(QPointF &p, std::size_t i) return 1; }*/ -int DiagramList::readList(const QString &path, std::vector<DiagramList*> &lists) +int DiagramList::readList(const QString& path, std::vector<DiagramList*>& lists) { QFile file(path); - QTextStream in( &file ); + QTextStream in(&file); if (!file.open(QIODevice::ReadOnly)) { @@ -176,16 +176,17 @@ int DiagramList::readList(const QString &path, std::vector<DiagramList*> &lists) { auto* l = new DiagramList; l->setName(fields.takeFirst()); - //value = strtod(BaseLib::replaceStringreplaceString(",", ".", fields.takeFirst().toStdString()).c_str(),0); - //l->setStartDate(startDate); - //l->addNextPoint(0,value); + // value = strtod(BaseLib::replaceStringreplaceString(",", ".", + // fields.takeFirst().toStdString()).c_str(),0); + // l->setStartDate(startDate); + // l->addNextPoint(0,value); lists.push_back(l); } bool first_loop(true); QDateTime startDate; QDateTime currentDate; - unsigned line_count (1); + unsigned line_count(1); while (!in.atEnd()) { @@ -215,7 +216,7 @@ int DiagramList::readList(const QString &path, std::vector<DiagramList*> &lists) ",", ".", fields.takeFirst().toStdString()) .c_str(), nullptr)); - lists[i]->addNextPoint(numberOfSecs,value); + lists[i]->addNextPoint(numberOfSecs, value); } } else @@ -244,16 +245,18 @@ int DiagramList::readList(const QString &path, std::vector<DiagramList*> &lists) return nLists; } -int DiagramList::readList(const SensorData* data, std::vector<DiagramList*> &lists) +int DiagramList::readList(const SensorData* data, + std::vector<DiagramList*>& lists) { - std::vector<SensorDataType> const& time_series_names (data->getTimeSeriesNames()); + std::vector<SensorDataType> const& time_series_names( + data->getTimeSeriesNames()); int nLists(time_series_names.size()); std::vector<std::size_t> time_steps; - if (data->getStepSize()>0) + if (data->getStepSize() > 0) { - const std::size_t start = data->getStartTime(); - const std::size_t end = data->getEndTime(); + const std::size_t start = data->getStartTime(); + const std::size_t end = data->getEndTime(); const std::size_t stepsize = data->getStepSize(); for (std::size_t i = start; i <= end; i += stepsize) { @@ -265,23 +268,25 @@ int DiagramList::readList(const SensorData* data, std::vector<DiagramList*> &lis time_steps = data->getTimeSteps(); } - bool is_date (false); + bool is_date(false); if (!(BaseLib::int2date(time_steps[0])).empty()) { is_date = true; } - std::size_t nValues (time_steps.size()); + std::size_t nValues(time_steps.size()); for (int i = 0; i < nLists; i++) { auto* l = new DiagramList; - l->setName(QString::fromStdString(SensorData::convertSensorDataType2String(time_series_names[i]))); + l->setName(QString::fromStdString( + SensorData::convertSensorDataType2String(time_series_names[i]))); l->setXLabel("Time"); lists.push_back(l); - const std::vector<float> *time_series = data->getTimeSeries(time_series_names[i]); + const std::vector<float>* time_series = + data->getTimeSeries(time_series_names[i]); if (is_date) { @@ -389,5 +394,3 @@ void DiagramList::update() _minY = calcMinYValue(); _maxY = calcMaxYValue(); } - - diff --git a/Applications/DataExplorer/DataView/DiagramView/DiagramPrefsDialog.cpp b/Applications/DataExplorer/DataView/DiagramView/DiagramPrefsDialog.cpp index e739773f0b8fb02e27d9748cad09942496c62d98..f70458f486d4790344fdeb736c87794220d0426c 100644 --- a/Applications/DataExplorer/DataView/DiagramView/DiagramPrefsDialog.cpp +++ b/Applications/DataExplorer/DataView/DiagramView/DiagramPrefsDialog.cpp @@ -13,19 +13,20 @@ */ #include "DiagramPrefsDialog.h" + +#include <QCheckBox> +#include <QFileDialog> +#include <QMessageBox> + #include "DetailWindow.h" #include "DiagramList.h" #include "GetDateTime.h" #include "OGSError.h" #include "Station.h" -#include <QCheckBox> -#include <QFileDialog> -#include <QMessageBox> - DiagramPrefsDialog::DiagramPrefsDialog(const GeoLib::Station* stn, - const QString &listName, - //DatabaseConnection* db, + const QString& listName, + // DatabaseConnection* db, QDialog* parent) : QDialog(parent), _window(nullptr) { @@ -44,12 +45,13 @@ DiagramPrefsDialog::DiagramPrefsDialog(GeoLib::Station* stn, QDialog* parent) stationTypeLabel->setText(""); DiagramList::readList(stn->getSensorData(), _list); - fromDateLine->setText(QString::number(stn->getSensorData()->getStartTime())); + fromDateLine->setText( + QString::number(stn->getSensorData()->getStartTime())); toDateLine->setText(QString::number(stn->getSensorData()->getEndTime())); this->createVisibilityCheckboxes(); } -DiagramPrefsDialog::DiagramPrefsDialog(const QString &filename, +DiagramPrefsDialog::DiagramPrefsDialog(const QString& filename, DetailWindow* window, QDialog* parent) : QDialog(parent), _window(window) @@ -125,17 +127,18 @@ void DiagramPrefsDialog::reject() void DiagramPrefsDialog::on_loadFileButton_clicked() { - QString fileName = QFileDialog::getOpenFileName(this, - "Select time series file to open", - "", - "Time series files (*.stn *.txt)"); + QString fileName = + QFileDialog::getOpenFileName(this, + "Select time series file to open", + "", + "Time series files (*.stn *.txt)"); if (!fileName.isEmpty()) { loadFile(fileName); } } -int DiagramPrefsDialog::loadFile(const QString &filename) +int DiagramPrefsDialog::loadFile(const QString& filename) { if (DiagramList::readList(filename, _list)) { @@ -161,16 +164,17 @@ int DiagramPrefsDialog::loadFile(const QString &filename) return 0; } -int DiagramPrefsDialog::loadList(const std::vector< std::pair<QDateTime, float> > &coords) +int DiagramPrefsDialog::loadList( + const std::vector<std::pair<QDateTime, float>>& coords) { if (!coords.empty()) { auto* l = new DiagramList; l->setName(stationTypeLabel->text() + ": " + stationNameLabel->text()); l->setXLabel("Time"); - //l->setYLabel("Water Level"); + // l->setYLabel("Water Level"); l->setXUnit("day"); - //l->setYUnit("metres"); + // l->setYUnit("metres"); l->setColor(QColor(Qt::red)); l->setList(coords); _list.push_back(l); @@ -189,4 +193,3 @@ void DiagramPrefsDialog::createVisibilityCheckboxes() _visability.push_back(box); } } - diff --git a/Applications/DataExplorer/DataView/DiagramView/DiagramScene.cpp b/Applications/DataExplorer/DataView/DiagramView/DiagramScene.cpp index 6bb8776674ceb43d9b2479e25ca016e620546d7d..f781292a44fda9348f3d7f19916318ea05c0ee61 100644 --- a/Applications/DataExplorer/DataView/DiagramView/DiagramScene.cpp +++ b/Applications/DataExplorer/DataView/DiagramView/DiagramScene.cpp @@ -13,8 +13,9 @@ */ #include "DiagramScene.h" -#include <limits> + #include <cmath> +#include <limits> // default size of a new window const float DEFAULTX = 500.0; @@ -26,7 +27,7 @@ const float DEFAULTY = 300.0; */ DiagramScene::DiagramScene(QObject* parent) : QGraphicsScene(parent) { - _bounds.setRect(0,0,1,1); + _bounds.setRect(0, 0, 1, 1); initialize(); } @@ -35,7 +36,8 @@ DiagramScene::DiagramScene(QObject* parent) : QGraphicsScene(parent) * \param list includes all necessary information of the graph to display. * \param parent The parent QObject. */ -DiagramScene::DiagramScene(DiagramList* list, QObject* parent) : QGraphicsScene(parent) +DiagramScene::DiagramScene(DiagramList* list, QObject* parent) + : QGraphicsScene(parent) { setDiagramBoundaries(list); initialize(); @@ -77,7 +79,8 @@ DiagramScene::~DiagramScene() _lists.clear(); } -/// Adds an arrow object to the diagram which might be used as a coordinate axis, etc. +/// Adds an arrow object to the diagram which might be used as a coordinate +/// axis, etc. QArrow* DiagramScene::addArrow(qreal length, qreal angle, QPen& pen) { auto* arrow = new QArrow(length, angle, 8, 5, pen); @@ -86,12 +89,12 @@ QArrow* DiagramScene::addArrow(qreal length, qreal angle, QPen& pen) } /// Adds a caption for a graph beneath the actual diagram. -void DiagramScene::addCaption(const QString &name, QPen &pen) +void DiagramScene::addCaption(const QString& name, QPen& pen) { auto* caption = new QGraphicsItemGroup(nullptr); - QGraphicsLineItem* l = addLine(0,0,100,0,pen); + QGraphicsLineItem* l = addLine(0, 0, 100, 0, pen); QGraphicsTextItem* t = addText(name); - l->setPos(0,0); + l->setPos(0, 0); t->setPos(110, -(t->boundingRect()).height() / 2); caption->addToGroup(l); caption->addToGroup(t); @@ -124,7 +127,8 @@ void DiagramScene::addGraph(DiagramList* list) } /// Adds a grid-object to the scene -QGraphicsGrid* DiagramScene::addGrid(const QRectF &rect, int xTicks, int yTicks, const QPen &pen) +QGraphicsGrid* DiagramScene::addGrid(const QRectF& rect, int xTicks, int yTicks, + const QPen& pen) { QGraphicsGrid* g = new QGraphicsGrid(rect, xTicks, yTicks, true, pen); addItem(g); @@ -132,8 +136,8 @@ QGraphicsGrid* DiagramScene::addGrid(const QRectF &rect, int xTicks, int yTicks, } /// Adds a non-scalable text object to the scene -QNonScalableGraphicsTextItem* DiagramScene::addNonScalableText(const QString &text, - const QFont &font) +QNonScalableGraphicsTextItem* DiagramScene::addNonScalableText( + const QString& text, const QFont& font) { auto* item = new QNonScalableGraphicsTextItem(text); item->setFont(font); @@ -141,7 +145,8 @@ QNonScalableGraphicsTextItem* DiagramScene::addNonScalableText(const QString &te return item; } -/// Resizes a given axis to "nice" dimensions and calculates an adequate number of ticks to be placed on it +/// Resizes a given axis to "nice" dimensions and calculates an adequate number +/// of ticks to be placed on it void DiagramScene::adjustAxis(qreal& min, qreal& max, int& numberOfTicks) { const int MinTicks = 4; @@ -164,10 +169,11 @@ void DiagramScene::adjustAxis(qreal& min, qreal& max, int& numberOfTicks) max = ceil(max / step) * step; } -///Calculates scaling factors to set coordinate system and graphs to default window size +/// Calculates scaling factors to set coordinate system and graphs to default +/// window size void DiagramScene::adjustScaling() { - if ( (_unscaledBounds.width() > 0) && (_unscaledBounds.height() > 0)) + if ((_unscaledBounds.width() > 0) && (_unscaledBounds.height() > 0)) { _scaleX = DEFAULTX / static_cast<float>(_unscaledBounds.width()); _scaleY = DEFAULTY / static_cast<float>(_unscaledBounds.height()); @@ -205,7 +211,8 @@ void DiagramScene::clearGrid() } } -/// Adjusts the underlying grid based on the graphs that are displayed in the diagram +/// Adjusts the underlying grid based on the graphs that are displayed in the +/// diagram void DiagramScene::constructGrid() { // be very careful with scaling parameters here! @@ -220,11 +227,10 @@ void DiagramScene::constructGrid() adjustAxis(yMin, yMax, numYTicks); // adjust boundaries of coordinate system according to scaling - _bounds.setRect( xMin * _scaleX, - yMin * _scaleY, - (xMax - xMin) * _scaleX, - (yMax - yMin) * _scaleY - ); + _bounds.setRect(xMin * _scaleX, + yMin * _scaleY, + (xMax - xMin) * _scaleX, + (yMax - yMin) * _scaleY); QPen pen(Qt::black, 1, Qt::SolidLine, Qt::SquareCap, Qt::RoundJoin); _grid = addGrid(_bounds, numXTicks, numYTicks, pen); @@ -272,7 +278,8 @@ void DiagramScene::drawGraph(DiagramList* list) if (list->getPath(path, _scaleX, _scaleY)) { - QPen pen(list->getColor(), 2, Qt::SolidLine, Qt::SquareCap, Qt::RoundJoin); + QPen pen(list->getColor(), 2, Qt::SolidLine, Qt::SquareCap, + Qt::RoundJoin); pen.setCosmetic(true); _graphs.push_back(addPath(path, pen)); addCaption(list->getName(), pen); @@ -284,10 +291,10 @@ void DiagramScene::drawGraph(DiagramList* list) * translated back to its original position */ int verticalShift = - static_cast<int>(2 * - (list->minYValue() * - _scaleY) + (_graphs[last]->boundingRect()).height()); - _graphs[last]->setTransform(QTransform(QMatrix(1,0,0,-1,0,verticalShift))); + static_cast<int>(2 * (list->minYValue() * _scaleY) + + (_graphs[last]->boundingRect()).height()); + _graphs[last]->setTransform( + QTransform(QMatrix(1, 0, 0, -1, 0, verticalShift))); } } @@ -316,7 +323,7 @@ void DiagramScene::initialize() QPen pen(Qt::black, 1, Qt::SolidLine, Qt::SquareCap, Qt::RoundJoin); pen.setCosmetic(true); - setXAxis(addArrow(_bounds.width(), 0, pen)); + setXAxis(addArrow(_bounds.width(), 0, pen)); setYAxis(addArrow(_bounds.height(), -90, pen)); _xLabel = addNonScalableText(" "); _yLabel = addNonScalableText(" "); @@ -328,8 +335,8 @@ void DiagramScene::initialize() update(); } -/// Updates the (unscaled) boundaries of the visible coordinate system when a new -/// list is added (boundaries are rescaled in the constructGrid-method +/// Updates the (unscaled) boundaries of the visible coordinate system when a +/// new list is added (boundaries are rescaled in the constructGrid-method void DiagramScene::setDiagramBoundaries(DiagramList* list) { if (!_lists.isEmpty()) @@ -372,16 +379,18 @@ void DiagramScene::setDiagramBoundaries(DiagramList* list) */ void DiagramScene::update() { - _xAxis->setPos(_bounds.left(),getXAxisOffset()); - _yAxis->setPos(getYAxisOffset(),_bounds.bottom()); + _xAxis->setPos(_bounds.left(), getXAxisOffset()); + _yAxis->setPos(getYAxisOffset(), _bounds.bottom()); _xAxis->setLength(_bounds.width()); _yAxis->setLength(_bounds.height()); - _xLabel->setPos( _bounds.left() + _bounds.width() / 2, _bounds.bottom() + 1.5 * MARGIN ); - _yLabel->setPos( _bounds.left() - 1.5 * MARGIN, _bounds.top() + _bounds.height() / 2 ); + _xLabel->setPos(_bounds.left() + _bounds.width() / 2, + _bounds.bottom() + 1.5 * MARGIN); + _yLabel->setPos(_bounds.left() - 1.5 * MARGIN, + _bounds.top() + _bounds.height() / 2); - _xUnit->setPos( _bounds.right(), _bounds.bottom() + 1.2 * MARGIN); - _yUnit->setPos( _bounds.left(), _bounds.top() - 0.5 * MARGIN); + _xUnit->setPos(_bounds.right(), _bounds.bottom() + 1.2 * MARGIN); + _yUnit->setPos(_bounds.left(), _bounds.top() - 0.5 * MARGIN); /* update graphs and their captions */ QRectF rect; @@ -393,6 +402,6 @@ void DiagramScene::update() _graphs[i]->setPos(0, offset); rect = itemsBoundingRect(); - _graphCaptions[i]->setPos(_bounds.left(),rect.bottom() + 10); + _graphCaptions[i]->setPos(_bounds.left(), rect.bottom() + 10); } } diff --git a/Applications/DataExplorer/DataView/DiagramView/DiagramView.cpp b/Applications/DataExplorer/DataView/DiagramView/DiagramView.cpp index 840c32058c2a78505d4012d1aa363eb301afcbe3..18ba33927c3139af22e6300d75683ce6b28347ca 100644 --- a/Applications/DataExplorer/DataView/DiagramView/DiagramView.cpp +++ b/Applications/DataExplorer/DataView/DiagramView/DiagramView.cpp @@ -13,9 +13,11 @@ */ #include "DiagramView.h" -#include <QGraphicsTextItem> + #include <math.h> +#include <QGraphicsTextItem> + DiagramView::DiagramView(QWidget* parent) : QGraphicsView(parent) { _scene = new DiagramScene(); @@ -23,7 +25,8 @@ DiagramView::DiagramView(QWidget* parent) : QGraphicsView(parent) initialize(); } -DiagramView::DiagramView(DiagramList* list, QWidget* parent) : QGraphicsView(parent) +DiagramView::DiagramView(DiagramList* list, QWidget* parent) + : QGraphicsView(parent) { _scene = new DiagramScene(list); setScene(_scene); @@ -56,8 +59,8 @@ int DiagramView::getWidth() */ void DiagramView::initialize() { - //QMatrix currentMatrix = matrix(); - //setMatrix(currentMatrix * scene->getTransformationMatrix()); + // QMatrix currentMatrix = matrix(); + // setMatrix(currentMatrix * scene->getTransformationMatrix()); setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); @@ -98,9 +101,9 @@ QSize DiagramView::sizeHint() const void DiagramView::resizeEvent(QResizeEvent* event) { - Q_UNUSED (event) + Q_UNUSED(event) update(); - //keepItemAspectRatio(); + // keepItemAspectRatio(); } /** @@ -111,7 +114,7 @@ void DiagramView::resizeEvent(QResizeEvent* event) */ void DiagramView::update() { - //setResizeAnchor(QGraphicsView::AnchorViewCenter); + // setResizeAnchor(QGraphicsView::AnchorViewCenter); QRectF viewRect = _scene->itemsBoundingRect(); _scene->setSceneRect(viewRect); QRectF sceneInView(0 /*_scene->MARGIN*/, DiagramScene::MARGIN / 2, diff --git a/Applications/DataExplorer/DataView/DiagramView/QArrow.cpp b/Applications/DataExplorer/DataView/DiagramView/QArrow.cpp index 2f5204971b1faf5c182591d1cf4e23ae921066f8..2eb1a2b5674709c60372896cd0afc1b8fe69d556 100644 --- a/Applications/DataExplorer/DataView/DiagramView/QArrow.cpp +++ b/Applications/DataExplorer/DataView/DiagramView/QArrow.cpp @@ -13,9 +13,11 @@ */ #include "QArrow.h" -#include <QPainter> + #include <math.h> +#include <QPainter> + /** * Creates an arrow as a QGraphicItem. * \param l Length of the arrow @@ -30,39 +32,38 @@ QArrow::QArrow(qreal l, qreal a, qreal hl, qreal hw, QPen& pen, : QGraphicsItem(parent) { _arrowLength = l; - _arrowAngle = a; - _headLength = hl; - _headWidth = hw; - _arrowPen = pen; + _arrowAngle = a; + _headLength = hl; + _headWidth = hw; + _arrowPen = pen; } /** - * Creates an arrow as a QGraphicItem. Length and width of the arrow head are given by default values. - * \param l Length of the arrow - * \param a Orientation of the arrow - * \param pen The pen for drawing the arrow - * \param parent The parent QGraphicsItem. + * Creates an arrow as a QGraphicItem. Length and width of the arrow head are + * given by default values. \param l Length of the arrow \param a Orientation of + * the arrow \param pen The pen for drawing the arrow \param parent The parent + * QGraphicsItem. */ QArrow::QArrow(qreal l, qreal a, QPen& pen, QGraphicsItem* parent) : QGraphicsItem(parent) { _arrowLength = l; - _arrowAngle = a; - _headLength = 8; // default headlength - _headWidth = 5; // default headwidth - _arrowPen = pen; + _arrowAngle = a; + _headLength = 8; // default headlength + _headWidth = 5; // default headwidth + _arrowPen = pen; } QArrow::~QArrow() = default; double QArrow::calcCos(double angle) { - return cos (angle * PI / 180); + return cos(angle * PI / 180); } double QArrow::calcSin(double angle) { - return sin (angle * PI / 180); + return sin(angle * PI / 180); } /// The bounding box of the arrow @@ -88,17 +89,19 @@ double QArrow::getAngle() /** * Overloaded paint-method from QGraphicsItem. - * Basically it draws a line with an arrowhead consisting of two short lines at the end + * Basically it draws a line with an arrowhead consisting of two short lines at + * the end */ -void QArrow::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) +void QArrow::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, + QWidget* widget) { - Q_UNUSED (option) - Q_UNUSED (widget) + Q_UNUSED(option) + Q_UNUSED(widget) - double ddeltaX = calcCos(_arrowAngle) * _arrowLength; - double ddeltaY = calcSin(_arrowAngle) * _arrowLength; - double theta = atan(ddeltaY / ddeltaX); - double theta2 = (ddeltaX < 0.0) ? (theta + PI) : theta; + double ddeltaX = calcCos(_arrowAngle) * _arrowLength; + double ddeltaY = calcSin(_arrowAngle) * _arrowLength; + double theta = atan(ddeltaY / ddeltaX); + double theta2 = (ddeltaX < 0.0) ? (theta + PI) : theta; int lengthdeltaX = -static_cast<int>(cos(theta2) * _headLength); int lengthdeltaY = -static_cast<int>(sin(theta2) * _headLength); auto widthdeltaX = static_cast<int>(sin(theta2) * _headWidth); diff --git a/Applications/DataExplorer/DataView/DiagramView/QGraphicsGrid.cpp b/Applications/DataExplorer/DataView/DiagramView/QGraphicsGrid.cpp index 3eaa741cbd1ef4da60764436b61f5248479a9ae4..5f692161def3d726bc0ab824ee234575d24b1d2a 100644 --- a/Applications/DataExplorer/DataView/DiagramView/QGraphicsGrid.cpp +++ b/Applications/DataExplorer/DataView/DiagramView/QGraphicsGrid.cpp @@ -13,6 +13,7 @@ */ #include "QGraphicsGrid.h" + #include <QPainter> /** @@ -23,25 +24,25 @@ * \param parent The parent QGraphicsItem. */ QGraphicsGrid::QGraphicsGrid(QRectF rect, int xCells, int yCells, - QGraphicsItem* parent) : QGraphicsItem(parent) + QGraphicsItem* parent) + : QGraphicsItem(parent) { _numberOfXCells = xCells; _numberOfYCells = yCells; - _bounds = rect; - _showTicks = false; + _bounds = rect; + _showTicks = false; initDefaultPens(); } /** - * Creates a grid by specifying its bounding rectangle using a default pen and no ticks. - * \param x X-coordinate for the lower left corner of the bounding rectangle for the grid. - * \param y Y-coordinate for the lower left corner of the bounding rectangle for the grid. - * \param width Width of the bounding rectangle. - * \param height Height of the bounding rectangle. - * \param xCells The number of grid cells in x-direction. - * \param yCells The number of grid cells in y-direction. - * \param parent The parent QGraphicsItem. + * Creates a grid by specifying its bounding rectangle using a default pen and + * no ticks. \param x X-coordinate for the lower left corner of the bounding + * rectangle for the grid. \param y Y-coordinate for the lower left corner of + * the bounding rectangle for the grid. \param width Width of the bounding + * rectangle. \param height Height of the bounding rectangle. \param xCells The + * number of grid cells in x-direction. \param yCells The number of grid cells + * in y-direction. \param parent The parent QGraphicsItem. */ QGraphicsGrid::QGraphicsGrid(int x, int y, @@ -49,12 +50,13 @@ QGraphicsGrid::QGraphicsGrid(int x, int height, int xCells, int yCells, - QGraphicsItem* parent) : QGraphicsItem(parent) + QGraphicsItem* parent) + : QGraphicsItem(parent) { _numberOfXCells = xCells; _numberOfYCells = yCells; - _bounds = QRectF(x,y,width,height); - _showTicks = false; + _bounds = QRectF(x, y, width, height); + _showTicks = false; initDefaultPens(); } @@ -73,17 +75,18 @@ QGraphicsGrid::QGraphicsGrid(QRectF rect, int yCells, bool ticks, QPen pen, - QGraphicsItem* parent) : QGraphicsItem(parent) + QGraphicsItem* parent) + : QGraphicsItem(parent) { _numberOfXCells = xCells; _numberOfYCells = yCells; - _bounds = rect; - _showTicks = ticks; + _bounds = rect; + _showTicks = ticks; _outside = pen; _outside.setCosmetic(true); - _inside = pen; + _inside = pen; QColor iColour = pen.color(); iColour.setAlpha(125); _inside.setColor(iColour); @@ -92,14 +95,13 @@ QGraphicsGrid::QGraphicsGrid(QRectF rect, } /** - * Creates a grid by specifying its bounding rectangle using a default pen and no ticks. - * \param x X-coordinate for the lower left corner of the bounding rectangle for the grid. - * \param y Y-coordinate for the lower left corner of the bounding rectangle for the grid. - * \param width Width of the bounding rectangle. - * \param height Height of the bounding rectangle. - * \param xCells The number of grid cells in x-direction. - * \param yCells The number of grid cells in y-direction. - * \param ticks Specifies if ticks are displayed for the grid. + * Creates a grid by specifying its bounding rectangle using a default pen and + * no ticks. \param x X-coordinate for the lower left corner of the bounding + * rectangle for the grid. \param y Y-coordinate for the lower left corner of + * the bounding rectangle for the grid. \param width Width of the bounding + * rectangle. \param height Height of the bounding rectangle. \param xCells The + * number of grid cells in x-direction. \param yCells The number of grid cells + * in y-direction. \param ticks Specifies if ticks are displayed for the grid. * \param pen The pen for drawing the grid. * \param parent The parent QGraphicsItem. */ @@ -111,17 +113,18 @@ QGraphicsGrid::QGraphicsGrid(int x, int yCells, bool ticks, QPen pen, - QGraphicsItem* parent) : QGraphicsItem(parent) + QGraphicsItem* parent) + : QGraphicsItem(parent) { _numberOfXCells = xCells; _numberOfYCells = yCells; - _bounds = QRectF(x,y,width,height); - _showTicks = ticks; + _bounds = QRectF(x, y, width, height); + _showTicks = ticks; _outside = pen; _outside.setCosmetic(true); - _inside = pen; + _inside = pen; QColor iColour = pen.color(); iColour.setAlpha(125); _inside.setColor(iColour); @@ -142,7 +145,7 @@ void QGraphicsGrid::initDefaultPens() { QPen in(Qt::gray, 1, Qt::DotLine, Qt::SquareCap, Qt::RoundJoin); QPen out(Qt::black, 1, Qt::SolidLine, Qt::SquareCap, Qt::RoundJoin); - _inside = in; + _inside = in; _outside = out; _inside.setCosmetic(true); _outside.setCosmetic(true); @@ -153,8 +156,8 @@ void QGraphicsGrid::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) { - Q_UNUSED (option) - Q_UNUSED (widget) + Q_UNUSED(option) + Q_UNUSED(widget) if (!_bounds.isValid()) { @@ -182,12 +185,14 @@ void QGraphicsGrid::paint(QPainter* painter, /* draw ticks on x-axis */ if (_showTicks) { - //double label = bounds.left() + (i * bounds.width() / numberOfXCells); + // double label = bounds.left() + (i * bounds.width() / + // numberOfXCells); painter->setPen(_outside); painter->drawLine(x, static_cast<int>(_bounds.bottom()), x, static_cast<int>(_bounds.bottom()) + 5); - //painter->drawText(x - margin, bounds.bottom() + 5, 2*margin, 20, - // Qt::AlignHCenter | Qt::AlignTop, QString::number(label)); + // painter->drawText(x - margin, bounds.bottom() + 5, 2*margin, 20, + // Qt::AlignHCenter | Qt::AlignTop, + // QString::number(label)); } } @@ -207,12 +212,14 @@ void QGraphicsGrid::paint(QPainter* painter, /* draw ticks on y-axis */ if (_showTicks) { - //double label = bounds.top() + (j * bounds.height() / numberOfYCells); + // double label = bounds.top() + (j * bounds.height() / + // numberOfYCells); painter->setPen(_outside); painter->drawLine(static_cast<int>(_bounds.left()) - 5, y, static_cast<int>(_bounds.left()), y); - //painter->drawText(bounds.left() - margin, y - 10, margin - 5, 20, - // Qt::AlignRight | Qt::AlignVCenter, QString::number(label)); + // painter->drawText(bounds.left() - margin, y - 10, margin - 5, 20, + // Qt::AlignRight | Qt::AlignVCenter, + // QString::number(label)); } } } @@ -232,5 +239,5 @@ void QGraphicsGrid::setNumberOfYCells(int yCells) /// Sets the bounding rectangle of the grid. void QGraphicsGrid::setRect(int x, int y, int width, int height) { - _bounds = QRectF(x,y,width,height); + _bounds = QRectF(x, y, width, height); } diff --git a/Applications/DataExplorer/DataView/DirectConditionGenerator.cpp b/Applications/DataExplorer/DataView/DirectConditionGenerator.cpp index 3eb26e11e633abb8cb50734b0e016d513bb938f3..9dd6725b95acb94de40643c2afca980c1838d89b 100644 --- a/Applications/DataExplorer/DataView/DirectConditionGenerator.cpp +++ b/Applications/DataExplorer/DataView/DirectConditionGenerator.cpp @@ -12,22 +12,19 @@ * */ +#include "DirectConditionGenerator.h" + +#include <cmath> #include <fstream> +#include <limits> #include <memory> -#include "BaseLib/Logging.h" - -#include "DirectConditionGenerator.h" - #include "Applications/FileIO/AsciiRasterInterface.h" - -#include "Raster.h" -#include "MeshSurfaceExtraction.h" +#include "BaseLib/Logging.h" #include "Mesh.h" #include "MeshLib/Node.h" - -#include <cmath> -#include <limits> +#include "MeshSurfaceExtraction.h" +#include "Raster.h" const std::vector<std::pair<std::size_t, double>>& DirectConditionGenerator::directToSurfaceNodes(const MeshLib::Mesh& mesh, @@ -67,9 +64,12 @@ DirectConditionGenerator::directToSurfaceNodes(const MeshLib::Mesh& mesh, return _direct_values; } -const std::vector< std::pair<std::size_t,double> >& DirectConditionGenerator::directWithSurfaceIntegration(MeshLib::Mesh &mesh, const std::string &filename, double scaling) +const std::vector<std::pair<std::size_t, double>>& +DirectConditionGenerator::directWithSurfaceIntegration( + MeshLib::Mesh& mesh, const std::string& filename, double scaling) { - if (!_direct_values.empty()) { + if (!_direct_values.empty()) + { ERR("Error in DirectConditionGenerator::directWithSurfaceIntegration()" "- Data vector contains outdated values..."); return _direct_values; @@ -77,7 +77,8 @@ const std::vector< std::pair<std::size_t,double> >& DirectConditionGenerator::di std::unique_ptr<GeoLib::Raster> raster( FileIO::AsciiRasterInterface::readRaster(filename)); - if (!raster) { + if (!raster) + { ERR("Error in DirectConditionGenerator::directWithSurfaceIntegration()" "- could not load raster file."); return _direct_values; @@ -87,12 +88,12 @@ const std::vector< std::pair<std::size_t,double> >& DirectConditionGenerator::di double const angle(90); std::string const prop_name("bulk_node_ids"); std::unique_ptr<MeshLib::Mesh> surface_mesh( - MeshLib::MeshSurfaceExtraction::getMeshSurface( - mesh, dir, angle, prop_name)); + MeshLib::MeshSurfaceExtraction::getMeshSurface(mesh, dir, angle, + prop_name)); std::vector<double> node_area_vec = MeshLib::MeshSurfaceExtraction::getSurfaceAreaForNodes(*surface_mesh); - const std::vector<MeshLib::Node*> &surface_nodes(surface_mesh->getNodes()); + const std::vector<MeshLib::Node*>& surface_nodes(surface_mesh->getNodes()); const std::size_t nNodes(surface_mesh->getNumberOfNodes()); const double no_data(raster->getHeader().no_data); @@ -119,10 +120,9 @@ const std::vector< std::pair<std::size_t,double> >& DirectConditionGenerator::di return _direct_values; } - -int DirectConditionGenerator::writeToFile(const std::string &name) const +int DirectConditionGenerator::writeToFile(const std::string& name) const { - std::ofstream out( name.c_str(), std::ios::out ); + std::ofstream out(name.c_str(), std::ios::out); if (out) { diff --git a/Applications/DataExplorer/DataView/ElementTreeModel.cpp b/Applications/DataExplorer/DataView/ElementTreeModel.cpp index a7ff0aee23cb487c932b2b888c8913494d343d0e..493ef0be3e6ae07208bcf409f29684c4947cf6fb 100644 --- a/Applications/DataExplorer/DataView/ElementTreeModel.cpp +++ b/Applications/DataExplorer/DataView/ElementTreeModel.cpp @@ -14,15 +14,12 @@ #include "ElementTreeModel.h" +#include "GeoLib/AABB.h" +#include "MeshLib/Elements/Element.h" #include "MeshLib/Mesh.h" -#include "MeshLib/Node.h" #include "MeshLib/MeshInformation.h" -#include "MeshLib/Elements/Element.h" - -#include "GeoLib/AABB.h" - +#include "MeshLib/Node.h" #include "MeshLib/Vtk/VtkMappedMeshSource.h" - #include "TreeItem.h" namespace @@ -48,13 +45,17 @@ ElementTreeModel::ElementTreeModel(QObject* parent) : TreeModel(parent) { QList<QVariant> rootData; delete _rootItem; - rootData << "Name" << "Type" << "" << ""; + rootData << "Name" + << "Type" + << "" + << ""; _rootItem = new TreeItem(rootData, nullptr); } ElementTreeModel::~ElementTreeModel() = default; -void ElementTreeModel::setElement(vtkUnstructuredGridAlgorithm const*const grid, const unsigned elem_index) +void ElementTreeModel::setElement( + vtkUnstructuredGridAlgorithm const* const grid, const unsigned elem_index) { beginResetModel(); @@ -73,34 +74,42 @@ void ElementTreeModel::setElement(vtkUnstructuredGridAlgorithm const*const grid, const MeshLib::Element* elem = mesh->getElement(elem_index); QList<QVariant> elemData; - elemData << "Element " + QString::number(elem_index) << "" << "" << ""; + elemData << "Element " + QString::number(elem_index) << "" + << "" + << ""; auto* elemItem = new TreeItem(elemData, _rootItem); _rootItem->appendChild(elemItem); QList<QVariant> typeData; - typeData << "Element Type: " << QString::fromStdString(MeshElemType2String(elem->getGeomType())); + typeData << "Element Type: " + << QString::fromStdString( + MeshElemType2String(elem->getGeomType())); auto* typeItem = new TreeItem(typeData, elemItem); elemItem->appendChild(typeItem); auto const mat_ids = materialIDs(*mesh); - QString matIdString = !mat_ids ? QString("not defined") : QString::number((*mat_ids)[elem->getID()]); + QString matIdString = !mat_ids ? QString("not defined") + : QString::number((*mat_ids)[elem->getID()]); QList<QVariant> materialData; materialData << "MaterialID: " << matIdString; auto* matItem = new TreeItem(materialData, elemItem); elemItem->appendChild(matItem); QList<QVariant> volData; - volData << "Area/Volume: " << - QString::number(mesh->getElement(elem_index)->getContent()); + volData << "Area/Volume: " + << QString::number(mesh->getElement(elem_index)->getContent()); auto* volItem = new TreeItem(volData, elemItem); elemItem->appendChild(volItem); QList<QVariant> nodeListData; - nodeListData << "Nodes" << "" << "" << ""; + nodeListData << "Nodes" + << "" + << "" + << ""; auto* nodeListItem = new TreeItem(nodeListData, elemItem); elemItem->appendChild(nodeListItem); - //const std::vector<MeshLib::Node*> nodes_vec = grid->getNodes(); + // const std::vector<MeshLib::Node*> nodes_vec = grid->getNodes(); std::size_t nElemNodes = elem->getNumberOfBaseNodes(); for (std::size_t i = 0; i < nElemNodes; i++) { @@ -130,17 +139,22 @@ void ElementTreeModel::setMesh(MeshLib::Mesh const& mesh) this->clearView(); QList<QVariant> mesh_name; - mesh_name << "Name:" << QString::fromStdString(mesh.getName()) << "" << "" << ""; + mesh_name << "Name:" << QString::fromStdString(mesh.getName()) << "" + << "" + << ""; auto* name_item = new TreeItem(mesh_name, _rootItem); _rootItem->appendChild(name_item); QList<QVariant> nodes_number; - nodes_number << "#Nodes: " << QString::number(mesh.getNumberOfNodes()) << "" << ""; + nodes_number << "#Nodes: " << QString::number(mesh.getNumberOfNodes()) << "" + << ""; auto* nodes_item = new TreeItem(nodes_number, _rootItem); _rootItem->appendChild(nodes_item); QList<QVariant> elements_number; - elements_number << "#Elements: " << QString::number(mesh.getNumberOfElements()) << "" << ""; + elements_number << "#Elements: " + << QString::number(mesh.getNumberOfElements()) << "" + << ""; auto* elements_item = new TreeItem(elements_number, _rootItem); _rootItem->appendChild(elements_item); @@ -161,26 +175,34 @@ void ElementTreeModel::setMesh(MeshLib::Mesh const& mesh) } QList<QVariant> bounding_box; - bounding_box << "Bounding Box" << "" << "" << ""; + bounding_box << "Bounding Box" + << "" + << "" + << ""; auto* aabb_item = new TreeItem(bounding_box, _rootItem); _rootItem->appendChild(aabb_item); - const GeoLib::AABB aabb (MeshLib::MeshInformation::getBoundingBox(mesh)); + const GeoLib::AABB aabb(MeshLib::MeshInformation::getBoundingBox(mesh)); auto const& min = aabb.getMinPoint(); auto const& max = aabb.getMaxPoint(); QList<QVariant> min_aabb; - min_aabb << "Min:" << QString::number(min[0], 'f') << QString::number(min[1], 'f') << QString::number(min[2], 'f'); + min_aabb << "Min:" << QString::number(min[0], 'f') + << QString::number(min[1], 'f') << QString::number(min[2], 'f'); auto* min_item = new TreeItem(min_aabb, aabb_item); aabb_item->appendChild(min_item); QList<QVariant> max_aabb; - max_aabb << "Max:" << QString::number(max[0], 'f') << QString::number(max[1], 'f') << QString::number(max[2], 'f'); + max_aabb << "Max:" << QString::number(max[0], 'f') + << QString::number(max[1], 'f') << QString::number(max[2], 'f'); auto* max_item = new TreeItem(max_aabb, aabb_item); aabb_item->appendChild(max_item); QList<QVariant> edges; - edges << "Edge Length: " << "[" + QString::number(mesh.getMinEdgeLength(), 'f') + "," << QString::number(mesh.getMaxEdgeLength(), 'f') + "]" << ""; + edges << "Edge Length: " + << "[" + QString::number(mesh.getMinEdgeLength(), 'f') + "," + << QString::number(mesh.getMaxEdgeLength(), 'f') + "]" + << ""; auto* edge_item = new TreeItem(edges, _rootItem); _rootItem->appendChild(edge_item); diff --git a/Applications/DataExplorer/DataView/ElementTreeView.cpp b/Applications/DataExplorer/DataView/ElementTreeView.cpp index 6125988db6fe31dcd269b7c564ccdc3700c774c9..2770f4a930b41aa0a75adab75d5c35687d3679d3 100644 --- a/Applications/DataExplorer/DataView/ElementTreeView.cpp +++ b/Applications/DataExplorer/DataView/ElementTreeView.cpp @@ -15,20 +15,17 @@ #include "ElementTreeView.h" +#include <QModelIndex> + #include "ElementTreeModel.h" #include "TreeItem.h" -#include <QModelIndex> - -ElementTreeView::ElementTreeView( QWidget* parent) -: QTreeView(parent) -{ -} +ElementTreeView::ElementTreeView(QWidget* parent) : QTreeView(parent) {} void ElementTreeView::updateView() { setAlternatingRowColors(true); - setColumnWidth(0,150); + setColumnWidth(0, 150); std::size_t nColumns = (this->model() != nullptr) ? this->model()->columnCount() : 0; for (std::size_t i = 1; i < nColumns; i++) @@ -38,7 +35,8 @@ void ElementTreeView::updateView() this->expandAll(); } -void ElementTreeView::selectionChanged( const QItemSelection &selected, const QItemSelection &deselected ) +void ElementTreeView::selectionChanged(const QItemSelection& selected, + const QItemSelection& deselected) { Q_UNUSED(deselected); if (!selected.isEmpty()) @@ -47,12 +45,16 @@ void ElementTreeView::selectionChanged( const QItemSelection &selected, const QI const QModelIndex idx = *(selected.indexes().begin()); if (idx.parent().isValid()) - { // not root node - if (idx.parent().parent().isValid()) // not property node + { // not root node + if (idx.parent().parent().isValid()) // not property node { - const TreeItem* tree_item = static_cast<TreeModel*>(this->model())->getItem(idx); - const unsigned node_index = tree_item->data(0).toString().mid(5).toUInt(); - emit nodeSelected(static_cast<ElementTreeModel*>(this->model())->getSource(), node_index, false); + const TreeItem* tree_item = + static_cast<TreeModel*>(this->model())->getItem(idx); + const unsigned node_index = + tree_item->data(0).toString().mid(5).toUInt(); + emit nodeSelected( + static_cast<ElementTreeModel*>(this->model())->getSource(), + node_index, false); } } } diff --git a/Applications/DataExplorer/DataView/FemConditionModel.cpp b/Applications/DataExplorer/DataView/FemConditionModel.cpp index 04ef46567fb9768738b4f26a07aaac28172295d3..4a6f1ff26afadf89e6eaea42c097e186415e78d7 100644 --- a/Applications/DataExplorer/DataView/FemConditionModel.cpp +++ b/Applications/DataExplorer/DataView/FemConditionModel.cpp @@ -12,7 +12,6 @@ #include "Applications/DataHolderLib/BoundaryCondition.h" #include "Applications/DataHolderLib/SourceTerm.h" - #include "TreeItem.h" /** diff --git a/Applications/DataExplorer/DataView/FemConditionView.cpp b/Applications/DataExplorer/DataView/FemConditionView.cpp index 6a3b6c23a5e6d74afc6d4096444313a3c3909f94..13fdd235113f6d326f9572227dbf5f994c1359d0 100644 --- a/Applications/DataExplorer/DataView/FemConditionView.cpp +++ b/Applications/DataExplorer/DataView/FemConditionView.cpp @@ -11,11 +11,11 @@ #include "FemConditionView.h" +#include <QModelIndex> + #include "CondItem.h" #include "FemConditionModel.h" -#include <QModelIndex> - FemConditionView::FemConditionView(QWidget* parent) : QTreeView(parent) {} void FemConditionView::updateView() diff --git a/Applications/DataExplorer/DataView/GEOModels.cpp b/Applications/DataExplorer/DataView/GEOModels.cpp index 74a91f92337c8d7842ab0dd8ddbc14c23e222beb..952f62457638cb69cc8315f27e9f66adb6494105 100644 --- a/Applications/DataExplorer/DataView/GEOModels.cpp +++ b/Applications/DataExplorer/DataView/GEOModels.cpp @@ -15,15 +15,12 @@ // ** INCLUDES ** #include "GEOModels.h" -#include "BaseLib/Logging.h" - #include "Applications/FileIO/Legacy/createSurface.h" +#include "BaseLib/Logging.h" +#include "GeoLib/Triangle.h" #include "GeoTreeModel.h" -#include "StationTreeModel.h" - #include "OGSError.h" - -#include "GeoLib/Triangle.h" +#include "StationTreeModel.h" GEOModels::GEOModels(GeoLib::GEOObjects& geo_objects, QObject* parent /*= 0*/) : QObject(parent), _geo_objects(geo_objects) @@ -40,11 +37,11 @@ GEOModels::~GEOModels() delete _geoModel; } -void GEOModels::updateGeometry(const std::string &geo_name) +void GEOModels::updateGeometry(const std::string& geo_name) { - GeoLib::PointVec* points (_geo_objects.getPointVecObj(geo_name)); - GeoLib::PolylineVec* lines (_geo_objects.getPolylineVecObj(geo_name)); - GeoLib::SurfaceVec* surfaces (_geo_objects.getSurfaceVecObj(geo_name)); + GeoLib::PointVec* points(_geo_objects.getPointVecObj(geo_name)); + GeoLib::PolylineVec* lines(_geo_objects.getPolylineVecObj(geo_name)); + GeoLib::SurfaceVec* surfaces(_geo_objects.getSurfaceVecObj(geo_name)); if (points) { @@ -57,7 +54,8 @@ void GEOModels::updateGeometry(const std::string &geo_name) { emit geoDataRemoved(_geoModel, geo_name, GeoLib::GEOTYPE::POLYLINE); this->_geoModel->removeGeoList(geo_name, GeoLib::GEOTYPE::POLYLINE); - _geoModel->addPolylineList(QString::fromStdString(geo_name), *lines); + _geoModel->addPolylineList(QString::fromStdString(geo_name), + *lines); emit geoDataAdded(_geoModel, geo_name, GeoLib::GEOTYPE::POLYLINE); } @@ -65,7 +63,8 @@ void GEOModels::updateGeometry(const std::string &geo_name) { emit geoDataRemoved(_geoModel, geo_name, GeoLib::GEOTYPE::SURFACE); this->_geoModel->removeGeoList(geo_name, GeoLib::GEOTYPE::SURFACE); - _geoModel->addSurfaceList(QString::fromStdString(geo_name), *surfaces); + _geoModel->addSurfaceList(QString::fromStdString(geo_name), + *surfaces); emit geoDataAdded(_geoModel, geo_name, GeoLib::GEOTYPE::SURFACE); } } @@ -187,7 +186,8 @@ void GEOModels::connectPolylineSegments( if (new_line) { - // insert result in a new vector of polylines (because the GEOObjects::appendPolylines()-method requires a vector) + // insert result in a new vector of polylines (because the + // GEOObjects::appendPolylines()-method requires a vector) std::vector<GeoLib::Polyline*> connected_ply; connected_ply.push_back(new_line); @@ -240,29 +240,31 @@ void GEOModels::addNameForElement(std::string const& geometry_name, { if (object_type == GeoLib::GEOTYPE::POINT) { - _geo_objects.getPointVecObj(geometry_name)->setNameForElement(id, new_name); + _geo_objects.getPointVecObj(geometry_name) + ->setNameForElement(id, new_name); } else if (object_type == GeoLib::GEOTYPE::POLYLINE) { - _geo_objects.getPolylineVecObj(geometry_name)->setNameForElement(id, new_name); + _geo_objects.getPolylineVecObj(geometry_name) + ->setNameForElement(id, new_name); } else if (object_type == GeoLib::GEOTYPE::SURFACE) { - _geo_objects.getSurfaceVecObj(geometry_name)->setNameForElement(id, new_name); + _geo_objects.getSurfaceVecObj(geometry_name) + ->setNameForElement(id, new_name); } else ERR("GEOModels::addNameForElement() - Unknown GEOTYPE {:s}.", GeoLib::convertGeoTypeToString(object_type)); } -void GEOModels::addNameForObjectPoints(const std::string &geometry_name, +void GEOModels::addNameForObjectPoints(const std::string& geometry_name, const GeoLib::GEOTYPE object_type, - const std::string &geo_object_name, - const std::string &new_name) + const std::string& geo_object_name, + const std::string& new_name) { - const GeoLib::GeoObject* obj = _geo_objects.getGeoObject(geometry_name, - object_type, - geo_object_name); + const GeoLib::GeoObject* obj = + _geo_objects.getGeoObject(geometry_name, object_type, geo_object_name); GeoLib::PointVec* pnt_vec = _geo_objects.getPointVecObj(geometry_name); if (object_type == GeoLib::GEOTYPE::POLYLINE) { diff --git a/Applications/DataExplorer/DataView/GMSHPrefsDialog.cpp b/Applications/DataExplorer/DataView/GMSHPrefsDialog.cpp index e1ae987cd00da9d37342f48f31e5f1de56c141b0..e8cf72ff6f888d0ed4997fd627d064e4ff9e97a6 100644 --- a/Applications/DataExplorer/DataView/GMSHPrefsDialog.cpp +++ b/Applications/DataExplorer/DataView/GMSHPrefsDialog.cpp @@ -16,18 +16,20 @@ #include "StringTools.h" // Qt/Base -#include "StrictDoubleValidator.h" -#include "StrictIntValidator.h" - -#include "GEOObjects.h" -#include "GMSHPrefsDialog.h" #include <QStringList> #include <QStringListModel> +#include "GEOObjects.h" +#include "GMSHPrefsDialog.h" #include "OGSError.h" +#include "StrictDoubleValidator.h" +#include "StrictIntValidator.h" -GMSHPrefsDialog::GMSHPrefsDialog(GeoLib::GEOObjects const& geoObjects, QDialog* parent) - : QDialog(parent), _allGeo(new QStringListModel), _selGeo(new QStringListModel) +GMSHPrefsDialog::GMSHPrefsDialog(GeoLib::GEOObjects const& geoObjects, + QDialog* parent) + : QDialog(parent), + _allGeo(new QStringListModel), + _selGeo(new QStringListModel) { setupUi(this); @@ -40,15 +42,15 @@ GMSHPrefsDialog::GMSHPrefsDialog(GeoLib::GEOObjects const& geoObjects, QDialog* // object will be deleted by Qt auto* max_number_of_points_in_quadtree_leaf_validator( new StrictIntValidator(1, 1000, this->param1)); - param1->setValidator (max_number_of_points_in_quadtree_leaf_validator); + param1->setValidator(max_number_of_points_in_quadtree_leaf_validator); // object will be deleted by Qt auto* mesh_density_scaling_pnts_validator( new StrictDoubleValidator(0, 1, 5, this->param2)); - param2->setValidator (mesh_density_scaling_pnts_validator); + param2->setValidator(mesh_density_scaling_pnts_validator); // object will be deleted by Qt# auto* mesh_density_scaling_stations_validator( new StrictDoubleValidator(0, 1, 5, this->param3)); - param3->setValidator (mesh_density_scaling_stations_validator); + param3->setValidator(mesh_density_scaling_stations_validator); auto geoNames = geoObjects.getGeometryNames(); @@ -76,7 +78,7 @@ GMSHPrefsDialog::GMSHPrefsDialog(GeoLib::GEOObjects const& geoObjects, QDialog* _allGeo->setStringList(list); this->allGeoView->setModel(_allGeo); this->selectedGeoView->setModel(_selGeo); - this->radioAdaptive->toggle(); // default is adaptive meshing + this->radioAdaptive->toggle(); // default is adaptive meshing this->on_radioAdaptive_toggled(true); } @@ -88,7 +90,8 @@ GMSHPrefsDialog::~GMSHPrefsDialog() void GMSHPrefsDialog::on_selectGeoButton_pressed() { - QModelIndexList selected = this->allGeoView->selectionModel()->selectedIndexes(); + QModelIndexList selected = + this->allGeoView->selectionModel()->selectedIndexes(); QStringList list = _selGeo->stringList(); for (auto& index : selected) @@ -102,7 +105,8 @@ void GMSHPrefsDialog::on_selectGeoButton_pressed() void GMSHPrefsDialog::on_deselectGeoButton_pressed() { - QModelIndexList selected = this->selectedGeoView->selectionModel()->selectedIndexes(); + QModelIndexList selected = + this->selectedGeoView->selectionModel()->selectedIndexes(); QStringList list = _allGeo->stringList(); for (auto& index : selected) @@ -116,14 +120,14 @@ void GMSHPrefsDialog::on_deselectGeoButton_pressed() void GMSHPrefsDialog::on_radioAdaptive_toggled(bool isTrue) { - if (isTrue) // meshing set to adaptive + if (isTrue) // meshing set to adaptive { this->param1->setEnabled(true); this->param2->setEnabled(true); this->param3->setEnabled(true); this->param4->setEnabled(false); } - else // meshing set to homogeneous + else // meshing set to homogeneous { this->param1->setEnabled(false); this->param2->setEnabled(false); @@ -136,26 +140,29 @@ void GMSHPrefsDialog::accept() { if (this->_selGeo->stringList().empty()) { - OGSError::box("No geometry selected. Geometric data\n is necessary for mesh generation."); + OGSError::box( + "No geometry selected. Geometric data\n is necessary for mesh " + "generation."); return; } - std::vector<std::string> selectedObjects = this->getSelectedObjects(_selGeo->stringList()); - unsigned max_number_of_points_in_quadtree_leaf (10); + std::vector<std::string> selectedObjects = + this->getSelectedObjects(_selGeo->stringList()); + unsigned max_number_of_points_in_quadtree_leaf(10); double mesh_density_scaling_pnts(0.5); - double mesh_density_scaling_stations (0.05); + double mesh_density_scaling_stations(0.05); double val4(-1); if (this->radioAdaptive->isChecked()) { - double const min_scaling_factor (1e-10); + double const min_scaling_factor(1e-10); max_number_of_points_in_quadtree_leaf = BaseLib::str2number<unsigned>(param1->text().toStdString()); if (max_number_of_points_in_quadtree_leaf == 0) { max_number_of_points_in_quadtree_leaf = 10; } - mesh_density_scaling_pnts = fabs (param2->text().toDouble()); + mesh_density_scaling_pnts = fabs(param2->text().toDouble()); if (mesh_density_scaling_pnts < min_scaling_factor) { mesh_density_scaling_pnts = min_scaling_factor; diff --git a/Applications/DataExplorer/DataView/GeoOnMeshMappingDialog.cpp b/Applications/DataExplorer/DataView/GeoOnMeshMappingDialog.cpp index a48e29bb64d2fbc4c73013a24612cf7611291a1b..7d08d2af184f2ac9208472ddf87e35b33d4c47cb 100644 --- a/Applications/DataExplorer/DataView/GeoOnMeshMappingDialog.cpp +++ b/Applications/DataExplorer/DataView/GeoOnMeshMappingDialog.cpp @@ -13,15 +13,14 @@ */ #include "GeoOnMeshMappingDialog.h" -#include "Mesh.h" - +#include "Mesh.h" #include "OGSError.h" GeoOnMeshMappingDialog::GeoOnMeshMappingDialog( std::vector<std::unique_ptr<MeshLib::Mesh>> const& mesh_vec, QDialog* parent) -: QDialog(parent), _new_geo_name("") + : QDialog(parent), _new_geo_name("") { setupUi(this); @@ -49,7 +48,8 @@ void GeoOnMeshMappingDialog::on_meshNameComboBox_currentIndexChanged(int idx) bool is_enabled(idx != 1); this->normalMappingButton->setEnabled(is_enabled); this->advancedMappingButton->setEnabled(is_enabled); - this->geoNameEdit->setEnabled(is_enabled && this->advancedMappingButton->isChecked()); + this->geoNameEdit->setEnabled(is_enabled && + this->advancedMappingButton->isChecked()); } void GeoOnMeshMappingDialog::accept() @@ -65,5 +65,3 @@ void GeoOnMeshMappingDialog::accept() } this->done(QDialog::Accepted); } - - diff --git a/Applications/DataExplorer/DataView/GeoTabWidget.cpp b/Applications/DataExplorer/DataView/GeoTabWidget.cpp index 9e7a3363953c9ef3adf43833bcd4fb22648e0a3b..954abc564084aa61a2a43acb675247d60bc4286c 100644 --- a/Applications/DataExplorer/DataView/GeoTabWidget.cpp +++ b/Applications/DataExplorer/DataView/GeoTabWidget.cpp @@ -15,14 +15,18 @@ // ** INCLUDES ** #include "GeoTabWidget.h" -GeoTabWidget::GeoTabWidget( QWidget* parent /*= 0*/ ) - : QWidget(parent) +GeoTabWidget::GeoTabWidget(QWidget* parent /*= 0*/) : QWidget(parent) { setupUi(this); - connect(this->openGeoPushButton, SIGNAL(clicked()), this->treeView, SLOT(addGeometry())); - connect(this->saveGeoPushButton, SIGNAL(clicked()), this->treeView, SLOT(writeToFile())); - connect(this->removeGeoPushButton, SIGNAL(clicked()), this->treeView, SLOT(removeGeometry())); - connect(this->treeView, SIGNAL(enableSaveButton(bool)), this, SLOT(enableSaveButton(bool))); - connect(this->treeView, SIGNAL(enableRemoveButton(bool)), this, SLOT(enableRemoveButton(bool))); + connect(this->openGeoPushButton, SIGNAL(clicked()), this->treeView, + SLOT(addGeometry())); + connect(this->saveGeoPushButton, SIGNAL(clicked()), this->treeView, + SLOT(writeToFile())); + connect(this->removeGeoPushButton, SIGNAL(clicked()), this->treeView, + SLOT(removeGeometry())); + connect(this->treeView, SIGNAL(enableSaveButton(bool)), this, + SLOT(enableSaveButton(bool))); + connect(this->treeView, SIGNAL(enableRemoveButton(bool)), this, + SLOT(enableRemoveButton(bool))); } diff --git a/Applications/DataExplorer/DataView/GeoTreeModel.cpp b/Applications/DataExplorer/DataView/GeoTreeModel.cpp index 2d8023018fbbc64c22d32b73260112a793ced574..5df9e13f42e5f477f65073ec0b7205b7a849574b 100644 --- a/Applications/DataExplorer/DataView/GeoTreeModel.cpp +++ b/Applications/DataExplorer/DataView/GeoTreeModel.cpp @@ -12,43 +12,53 @@ * */ -#include "BaseLib/Logging.h" +#include "GeoTreeModel.h" +#include "BaseLib/Logging.h" +#include "GeoLib/Triangle.h" #include "GeoObjectListItem.h" #include "GeoTreeItem.h" -#include "GeoTreeModel.h" #include "OGSError.h" -#include "GeoLib/Triangle.h" - /** * Constructor. */ -GeoTreeModel::GeoTreeModel( QObject* parent ) - : TreeModel(parent) +GeoTreeModel::GeoTreeModel(QObject* parent) : TreeModel(parent) { QList<QVariant> rootData; delete _rootItem; - rootData << "Id" << "x" << "y" << "z" << "name "; + rootData << "Id" + << "x" + << "y" + << "z" + << "name "; _rootItem = new GeoTreeItem(rootData, nullptr, nullptr); } GeoTreeModel::~GeoTreeModel() = default; -void GeoTreeModel::addPointList(QString geoName, GeoLib::PointVec const& pointVec) +void GeoTreeModel::addPointList(QString geoName, + GeoLib::PointVec const& pointVec) { beginResetModel(); const std::vector<GeoLib::Point*>* points = pointVec.getVector(); QList<QVariant> geoData; - geoData << QVariant(geoName) << "" << "" << "" << ""; + geoData << QVariant(geoName) << "" + << "" + << "" + << ""; auto* geo(new GeoTreeItem(geoData, _rootItem)); _lists.push_back(geo); _rootItem->appendChild(geo); QList<QVariant> pointData; - pointData << "Points" << "" << "" << "" << ""; + pointData << "Points" + << "" + << "" + << "" + << ""; auto* pointList = new GeoObjectListItem(pointData, geo, points, GeoLib::GEOTYPE::POINT); geo->appendChild(pointList); @@ -57,17 +67,14 @@ void GeoTreeModel::addPointList(QString geoName, GeoLib::PointVec const& pointVe for (std::size_t j = 0; j < nPoints; j++) { - const GeoLib::Point &pnt(*(*points)[j]); + const GeoLib::Point& pnt(*(*points)[j]); QList<QVariant> pnt_data; pnt_data.reserve(5); - pnt_data << static_cast<unsigned>(j) - << QString::number(pnt[0], 'f') - << QString::number(pnt[1], 'f') - << QString::number(pnt[2], 'f') + pnt_data << static_cast<unsigned>(j) << QString::number(pnt[0], 'f') + << QString::number(pnt[1], 'f') << QString::number(pnt[2], 'f') << ""; - pointList->appendChild(new GeoTreeItem(pnt_data, - pointList, - static_cast<const GeoLib::Point*>(&pnt))); + pointList->appendChild(new GeoTreeItem( + pnt_data, pointList, static_cast<const GeoLib::Point*>(&pnt))); } for (auto pnt = pointVec.getNameIDMapBegin(); @@ -84,7 +91,8 @@ void GeoTreeModel::addPointList(QString geoName, GeoLib::PointVec const& pointVe endResetModel(); } -void GeoTreeModel::addPolylineList(QString geoName, GeoLib::PolylineVec const& polylineVec) +void GeoTreeModel::addPolylineList(QString geoName, + GeoLib::PolylineVec const& polylineVec) { beginResetModel(); @@ -109,7 +117,10 @@ void GeoTreeModel::addPolylineList(QString geoName, GeoLib::PolylineVec const& p const std::vector<GeoLib::Polyline*>* lines = polylineVec.getVector(); QList<QVariant> plyData; - plyData << "Polylines" << "" << "" << ""; + plyData << "Polylines" + << "" + << "" + << ""; auto* plyList = new GeoObjectListItem(plyData, geo, lines, GeoLib::GEOTYPE::POLYLINE); geo->appendChild(plyList); @@ -118,7 +129,8 @@ void GeoTreeModel::addPolylineList(QString geoName, GeoLib::PolylineVec const& p endResetModel(); } -void GeoTreeModel::appendPolylines(const std::string &name, GeoLib::PolylineVec const& polylineVec) +void GeoTreeModel::appendPolylines(const std::string& name, + GeoLib::PolylineVec const& polylineVec) { for (auto& list : _lists) { @@ -153,9 +165,11 @@ void GeoTreeModel::addChildren(GeoObjectListItem* plyList, { QList<QVariant> line_data; line_data.reserve(4); - line_data << "Line " + QString::number(i) << "" << "" << ""; + line_data << "Line " + QString::number(i) << "" + << "" + << ""; - const GeoLib::Polyline &line(*(lines[i])); + const GeoLib::Polyline& line(*(lines[i])); auto* lineItem(new GeoTreeItem(line_data, plyList, &line)); plyList->appendChild(lineItem); @@ -185,7 +199,8 @@ void GeoTreeModel::addChildren(GeoObjectListItem* plyList, INFO("{:d} polylines added.", end_index - start_index); } -void GeoTreeModel::addSurfaceList(QString geoName, GeoLib::SurfaceVec const& surfaceVec) +void GeoTreeModel::addSurfaceList(QString geoName, + GeoLib::SurfaceVec const& surfaceVec) { beginResetModel(); @@ -210,7 +225,10 @@ void GeoTreeModel::addSurfaceList(QString geoName, GeoLib::SurfaceVec const& sur const std::vector<GeoLib::Surface*>* surfaces = surfaceVec.getVector(); QList<QVariant> sfcData; - sfcData << "Surfaces" << "" << "" << ""; + sfcData << "Surfaces" + << "" + << "" + << ""; auto* sfcList = new GeoObjectListItem(sfcData, geo, surfaces, GeoLib::GEOTYPE::SURFACE); geo->appendChild(sfcList); @@ -219,7 +237,8 @@ void GeoTreeModel::addSurfaceList(QString geoName, GeoLib::SurfaceVec const& sur endResetModel(); } -void GeoTreeModel::appendSurfaces(const std::string &name, GeoLib::SurfaceVec const& surfaceVec) +void GeoTreeModel::appendSurfaces(const std::string& name, + GeoLib::SurfaceVec const& surfaceVec) { for (auto& list : _lists) { @@ -251,15 +270,17 @@ void GeoTreeModel::addChildren(GeoObjectListItem* sfcList, { const std::vector<GeoLib::Surface*>* surfaces = surface_vec.getVector(); - const std::vector<GeoLib::Point*> &nodesVec(*((*surfaces)[start_index]->getPointVec())); + const std::vector<GeoLib::Point*>& nodesVec( + *((*surfaces)[start_index]->getPointVec())); for (std::size_t i = start_index; i < end_index; i++) { QList<QVariant> surface; surface.reserve(4); - surface << "Surface " + QString::number(i) << "" << - "" << ""; + surface << "Surface " + QString::number(i) << "" + << "" + << ""; - const GeoLib::Surface &sfc(*(*surfaces)[i]); + const GeoLib::Surface& sfc(*(*surfaces)[i]); auto* surfaceItem(new GeoTreeItem(surface, sfcList, &sfc)); sfcList->appendChild(surfaceItem); @@ -268,7 +289,7 @@ void GeoTreeModel::addChildren(GeoObjectListItem* sfcList, { QList<QVariant> elem; elem.reserve(4); - const GeoLib::Triangle &triangle(*sfc[j]); + const GeoLib::Triangle& triangle(*sfc[j]); elem << j << static_cast<int>(triangle[0]) << static_cast<int>(triangle[1]) << static_cast<int>(triangle[2]); @@ -279,7 +300,7 @@ void GeoTreeModel::addChildren(GeoObjectListItem* sfcList, { QList<QVariant> node; node.reserve(4); - const GeoLib::Point &pnt(*(nodesVec[triangle[k]])); + const GeoLib::Point& pnt(*(nodesVec[triangle[k]])); node << static_cast<int>(triangle[k]) << QString::number(pnt[0], 'f') << QString::number(pnt[1], 'f') @@ -332,8 +353,8 @@ void GeoTreeModel::removeGeoList(const std::string& name, GeoLib::GEOTYPE type) { for (int j = 0; j < _lists[i]->childCount(); j++) { - if (type == - static_cast<GeoObjectListItem*>(_lists[i]->child(j))->getType()) + if (type == static_cast<GeoObjectListItem*>(_lists[i]->child(j)) + ->getType()) { QModelIndex index = createIndex(j, 0, _lists[i]->child(j)); removeRows(0, _lists[i]->child(j)->childCount(), index); @@ -350,7 +371,8 @@ void GeoTreeModel::removeGeoList(const std::string& name, GeoLib::GEOTYPE type) } } -vtkPolyDataAlgorithm* GeoTreeModel::vtkSource(const std::string &name, GeoLib::GEOTYPE type) const +vtkPolyDataAlgorithm* GeoTreeModel::vtkSource(const std::string& name, + GeoLib::GEOTYPE type) const { std::size_t nLists = _lists.size(); for (std::size_t i = 0; i < nLists; i++) @@ -371,7 +393,7 @@ vtkPolyDataAlgorithm* GeoTreeModel::vtkSource(const std::string &name, GeoLib::G return nullptr; } -void GeoTreeModel::setNameForItem(const std::string &name, +void GeoTreeModel::setNameForItem(const std::string& name, GeoLib::GEOTYPE type, std::size_t id, std::string item_name) @@ -379,20 +401,20 @@ void GeoTreeModel::setNameForItem(const std::string &name, std::string geo_type_str; int col_idx(1); - switch(type) + switch (type) { - case GeoLib::GEOTYPE::POINT: - geo_type_str = "Points"; - col_idx = 4; // for points the name is at a different position - break; - case GeoLib::GEOTYPE::POLYLINE: - geo_type_str = "Polylines"; - break; - case GeoLib::GEOTYPE::SURFACE: - geo_type_str = "Surfaces"; - break; - default: - geo_type_str = ""; + case GeoLib::GEOTYPE::POINT: + geo_type_str = "Points"; + col_idx = 4; // for points the name is at a different position + break; + case GeoLib::GEOTYPE::POLYLINE: + geo_type_str = "Polylines"; + break; + case GeoLib::GEOTYPE::SURFACE: + geo_type_str = "Surfaces"; + break; + default: + geo_type_str = ""; } auto it = find_if(_lists.begin(), _lists.end(), [&name](GeoTreeItem* geo) { diff --git a/Applications/DataExplorer/DataView/GeoTreeView.cpp b/Applications/DataExplorer/DataView/GeoTreeView.cpp index 91beffebd06fad0783202cba5cbed6426cf84d63..dc1416b9084a3f30088eb0d1f7b572b53e54c4ed 100644 --- a/Applications/DataExplorer/DataView/GeoTreeView.cpp +++ b/Applications/DataExplorer/DataView/GeoTreeView.cpp @@ -12,6 +12,8 @@ * */ +#include "GeoTreeView.h" + #include <QFileDialog> #include <QMenu> #include <QSettings> @@ -19,42 +21,40 @@ #include "GeoObjectListItem.h" #include "GeoTreeItem.h" #include "GeoTreeModel.h" -#include "GeoTreeView.h" -#include "OGSError.h" #include "ImportFileTypes.h" #include "LastSavedFileDirectory.h" +#include "OGSError.h" - -GeoTreeView::GeoTreeView(QWidget* parent) : QTreeView(parent) -{ -} +GeoTreeView::GeoTreeView(QWidget* parent) : QTreeView(parent) {} void GeoTreeView::updateView() { setAlternatingRowColors(true); - setColumnWidth(0,150); - setColumnWidth(1,75); - setColumnWidth(2,75); - setColumnWidth(3,75); + setColumnWidth(0, 150); + setColumnWidth(1, 75); + setColumnWidth(2, 75); + setColumnWidth(3, 75); } void GeoTreeView::on_Clicked(QModelIndex idx) { - qDebug("%d, %d",idx.parent().row(), idx.row()); + qDebug("%d, %d", idx.parent().row(), idx.row()); } -void GeoTreeView::selectionChanged( const QItemSelection &selected, - const QItemSelection &deselected ) +void GeoTreeView::selectionChanged(const QItemSelection& selected, + const QItemSelection& deselected) { Q_UNUSED(deselected); if (!selected.isEmpty()) { const QModelIndex idx = *(selected.indexes().begin()); - const TreeItem* tree_item = static_cast<TreeModel*>(this->model())->getItem(idx); + const TreeItem* tree_item = + static_cast<TreeModel*>(this->model())->getItem(idx); emit removeGeoItemSelection(); - const GeoObjectListItem* geo_object = dynamic_cast<GeoObjectListItem*>(tree_item->parentItem()); - if (geo_object) // geometry object + const GeoObjectListItem* geo_object = + dynamic_cast<GeoObjectListItem*>(tree_item->parentItem()); + if (geo_object) // geometry object { emit enableSaveButton(false); emit enableRemoveButton(false); @@ -62,12 +62,12 @@ void GeoTreeView::selectionChanged( const QItemSelection &selected, } else { - if (!idx.parent().isValid()) // geometry item + if (!idx.parent().isValid()) // geometry item { emit enableSaveButton(true); emit enableRemoveButton(true); } - else // line points or surface triangles + else // line points or surface triangles { emit enableSaveButton(false); const auto* geo_type = @@ -94,7 +94,8 @@ void GeoTreeView::selectionChanged( const QItemSelection &selected, } // highlight a point for an expanded surface - list_item = dynamic_cast<GeoObjectListItem*>(tree_item->parentItem()->parentItem()->parentItem()); + list_item = dynamic_cast<GeoObjectListItem*>( + tree_item->parentItem()->parentItem()->parentItem()); if (list_item && list_item->getType() == GeoLib::GEOTYPE::SURFACE) { @@ -110,16 +111,14 @@ void GeoTreeView::selectionChanged( const QItemSelection &selected, emit enableRemoveButton(false); } } - } - } - //emit itemSelectionChanged(selected, deselected); - //return QTreeView::selectionChanged(selected, deselected); + // emit itemSelectionChanged(selected, deselected); + // return QTreeView::selectionChanged(selected, deselected); } -void GeoTreeView::selectionChangedFromOutside( const QItemSelection &selected, - const QItemSelection &deselected ) +void GeoTreeView::selectionChangedFromOutside(const QItemSelection& selected, + const QItemSelection& deselected) { QItemSelectionModel* selModel = this->selectionModel(); @@ -131,7 +130,7 @@ void GeoTreeView::selectionChangedFromOutside( const QItemSelection &selected, QTreeView::selectionChanged(selected, deselected); } -void GeoTreeView::contextMenuEvent( QContextMenuEvent* event ) +void GeoTreeView::contextMenuEvent(QContextMenuEvent* event) { QModelIndex index = this->selectionModel()->currentIndex(); auto* item = static_cast<TreeItem*>(index.internalPointer()); @@ -146,8 +145,8 @@ void GeoTreeView::contextMenuEvent( QContextMenuEvent* event ) { auto const* convertToStationAction = menu.addAction("Convert to Stations"); - connect(convertToStationAction, SIGNAL(triggered()), - this, SLOT(convertPointsToStations())); + connect(convertToStationAction, SIGNAL(triggered()), this, + SLOT(convertPointsToStations())); } if (list->getType() == GeoLib::GEOTYPE::POLYLINE) { @@ -157,8 +156,9 @@ void GeoTreeView::contextMenuEvent( QContextMenuEvent* event ) SLOT(connectPolylines())); } menu.addSeparator(); - //QAction* removeAction = menu.addAction("Remove " + item->data(0).toString()); - //connect(removeAction, SIGNAL(triggered()), this, SLOT(removeList())); + // QAction* removeAction = menu.addAction("Remove " + + // item->data(0).toString()); connect(removeAction, SIGNAL(triggered()), + // this, SLOT(removeList())); } else { @@ -174,12 +174,15 @@ void GeoTreeView::contextMenuEvent( QContextMenuEvent* event ) if (parent != nullptr) { QMenu* cond_menu = new QMenu("Set FEM Condition"); - //menu.addMenu(cond_menu); + // menu.addMenu(cond_menu); QAction* addCondAction = cond_menu->addAction("On object..."); - QAction* addCondPointAction = cond_menu->addAction("On all points..."); + QAction* addCondPointAction = + cond_menu->addAction("On all points..."); QAction* addNameAction = menu.addAction("Set name..."); - connect(addCondAction, SIGNAL(triggered()), this, SLOT(setObjectAsCondition())); - connect(addNameAction, SIGNAL(triggered()), this, SLOT(setNameForElement())); + connect(addCondAction, SIGNAL(triggered()), this, + SLOT(setObjectAsCondition())); + connect(addNameAction, SIGNAL(triggered()), this, + SLOT(setNameForElement())); if (parent->getType() == GeoLib::GEOTYPE::POINT) { @@ -194,19 +197,25 @@ void GeoTreeView::contextMenuEvent( QContextMenuEvent* event ) // The current index refers to the name of a geometry-object else if (item->childCount() > 0) { - if (item->child(0)->data(0).toString().compare("Points") == 0) // clumsy way to find out + if (item->child(0)->data(0).toString().compare("Points") == + 0) // clumsy way to find out { - //QAction* saveAction = menu.addAction("Save geometry..."); + // QAction* saveAction = menu.addAction("Save geometry..."); QAction* mapAction = menu.addAction("Map geometry..."); - //QAction* addCNDAction = menu.addAction("Load FEM Conditions..."); - //QAction* saveCondAction = menu.addAction("Save FEM conditions..."); + // QAction* addCNDAction = menu.addAction("Load FEM + // Conditions..."); QAction* saveCondAction = + // menu.addAction("Save FEM conditions..."); menu.addSeparator(); - //QAction* removeAction = menu.addAction("Remove geometry"); - //connect(saveAction, SIGNAL(triggered()), this, SLOT(writeToFile())); - connect(mapAction, SIGNAL(triggered()), this, SLOT(mapGeometry())); - //connect(addCNDAction, SIGNAL(triggered()), this, SLOT(loadFEMConditions())); - //connect(saveCondAction, SIGNAL(triggered()), this, SLOT(saveFEMConditions())); - //connect(removeAction, SIGNAL(triggered()), this, SLOT(removeList())); + // QAction* removeAction = menu.addAction("Remove geometry"); + // connect(saveAction, SIGNAL(triggered()), this, + // SLOT(writeToFile())); + connect(mapAction, SIGNAL(triggered()), this, + SLOT(mapGeometry())); + // connect(addCNDAction, SIGNAL(triggered()), this, + // SLOT(loadFEMConditions())); connect(saveCondAction, + // SIGNAL(triggered()), this, SLOT(saveFEMConditions())); + // connect(removeAction, SIGNAL(triggered()), this, + // SLOT(removeList())); } } } @@ -216,16 +225,19 @@ void GeoTreeView::contextMenuEvent( QContextMenuEvent* event ) void GeoTreeView::convertPointsToStations() { - TreeItem const*const item = static_cast<GeoTreeModel*>(model()) - ->getItem(this->selectionModel()->currentIndex()) - ->parentItem(); - emit requestPointToStationConversion(item->data(0).toString().toStdString()); + TreeItem const* const item = + static_cast<GeoTreeModel*>(model()) + ->getItem(this->selectionModel()->currentIndex()) + ->parentItem(); + emit requestPointToStationConversion( + item->data(0).toString().toStdString()); } void GeoTreeView::connectPolylines() { - TreeItem* item = static_cast<GeoTreeModel*>(model())->getItem( - this->selectionModel()->currentIndex())->parentItem(); + TreeItem* item = static_cast<GeoTreeModel*>(model()) + ->getItem(this->selectionModel()->currentIndex()) + ->parentItem(); emit requestLineEditDialog(item->data(0).toString().toStdString()); } @@ -236,7 +248,7 @@ void GeoTreeView::addGeometry() void GeoTreeView::removeGeometry() { - QModelIndex index (this->selectionModel()->currentIndex()); + QModelIndex index(this->selectionModel()->currentIndex()); if (!index.isValid()) { OGSError::box("No geometry selected."); @@ -245,16 +257,23 @@ void GeoTreeView::removeGeometry() { TreeItem* item = static_cast<GeoTreeModel*>(model())->getItem(index); auto* list = dynamic_cast<GeoObjectListItem*>(item); - if (list) { - emit listRemoved((item->parentItem()->data( - 0).toString()).toStdString(), list->getType()); - } else { - emit listRemoved((item->data(0).toString()).toStdString(), GeoLib::GEOTYPE::SURFACE); - emit listRemoved((item->data(0).toString()).toStdString(), GeoLib::GEOTYPE::POLYLINE); - emit listRemoved((item->data(0).toString()).toStdString(), GeoLib::GEOTYPE::POINT); + if (list) + { + emit listRemoved( + (item->parentItem()->data(0).toString()).toStdString(), + list->getType()); + } + else + { + emit listRemoved((item->data(0).toString()).toStdString(), + GeoLib::GEOTYPE::SURFACE); + emit listRemoved((item->data(0).toString()).toStdString(), + GeoLib::GEOTYPE::POLYLINE); + emit listRemoved((item->data(0).toString()).toStdString(), + GeoLib::GEOTYPE::POINT); } - if(this->selectionModel()->selectedIndexes().count() == 0) + if (this->selectionModel()->selectedIndexes().count() == 0) { emit enableSaveButton(false); emit enableRemoveButton(false); @@ -265,34 +284,38 @@ void GeoTreeView::removeGeometry() void GeoTreeView::setElementAsCondition(bool set_on_points) { const TreeItem* item = static_cast<GeoTreeModel*>(model())->getItem( - this->selectionModel()->currentIndex()); + this->selectionModel()->currentIndex()); const std::size_t id = item->row(); - const GeoLib::GEOTYPE type = static_cast<GeoObjectListItem*>(item->parentItem())->getType(); - const std::string geometry_name = item->parentItem()->parentItem()->data(0).toString().toStdString(); + const GeoLib::GEOTYPE type = + static_cast<GeoObjectListItem*>(item->parentItem())->getType(); + const std::string geometry_name = + item->parentItem()->parentItem()->data(0).toString().toStdString(); emit requestCondSetupDialog(geometry_name, type, id, set_on_points); } void GeoTreeView::setNameForElement() { const TreeItem* item = static_cast<GeoTreeModel*>(model())->getItem( - this->selectionModel()->currentIndex()); + this->selectionModel()->currentIndex()); const std::size_t id = item->row(); - const GeoLib::GEOTYPE type = static_cast<GeoObjectListItem*>(item->parentItem())->getType(); - const std::string geometry_name = item->parentItem()->parentItem()->data(0).toString().toStdString(); + const GeoLib::GEOTYPE type = + static_cast<GeoObjectListItem*>(item->parentItem())->getType(); + const std::string geometry_name = + item->parentItem()->parentItem()->data(0).toString().toStdString(); emit requestNameChangeDialog(geometry_name, type, id); } void GeoTreeView::mapGeometry() { TreeItem* item = static_cast<GeoTreeModel*>(model())->getItem( - this->selectionModel()->currentIndex()); - std::string geo_name (item->data(0).toString().toStdString()); + this->selectionModel()->currentIndex()); + std::string geo_name(item->data(0).toString().toStdString()); emit geometryMappingRequested(geo_name); } void GeoTreeView::writeToFile() const { - QModelIndex index (this->selectionModel()->currentIndex()); + QModelIndex index(this->selectionModel()->currentIndex()); if (!index.isValid()) { OGSError::box("No geometry selected."); @@ -300,10 +323,10 @@ void GeoTreeView::writeToFile() const else { TreeItem* item = static_cast<GeoTreeModel*>(model())->getItem(index); - QString file_type ("GeoSys geometry file (*.gml)"); + QString file_type("GeoSys geometry file (*.gml)"); #ifndef NDEBUG - file_type.append(";;Legacy geometry file (*.gli)"); -#endif // DEBUG + file_type.append(";;Legacy geometry file (*.gli)"); +#endif // DEBUG QString geoName = item->data(0).toString(); QString fileName = QFileDialog::getSaveFileName( nullptr, "Save geometry as", @@ -319,7 +342,7 @@ void GeoTreeView::writeToFile() const void GeoTreeView::loadFEMConditions() { TreeItem* item = static_cast<GeoTreeModel*>(model())->getItem( - this->selectionModel()->currentIndex()); + this->selectionModel()->currentIndex()); emit loadFEMCondFileRequested(item->data(0).toString().toStdString()); } /* diff --git a/Applications/DataExplorer/DataView/LicenseDialog.cpp b/Applications/DataExplorer/DataView/LicenseDialog.cpp index d6d402097a6c0b3fa41afc215b4e0b8826eda090..1b3589f47057ac4b7bf5a1ac7e3b7627a60213b4 100644 --- a/Applications/DataExplorer/DataView/LicenseDialog.cpp +++ b/Applications/DataExplorer/DataView/LicenseDialog.cpp @@ -13,6 +13,7 @@ */ #include "LicenseDialog.h" + #include <QTextStream> LicenseDialog::LicenseDialog(QDialog* parent) : QDialog(parent) @@ -26,37 +27,61 @@ void LicenseDialog::setText() { QString text; QTextStream stream(&text); - stream << "<p>Copyright (c) 2012-2021, OpenGeoSys Community " - << "(<a href='http://www.opengeosys.org'>http://www.opengeosys.org</a>)<br />" - << "All rights reserved.</p>" - << "<p>Redistribution and use in source and binary forms, with or without" - << "modification, are permitted provided that the following conditions are met:" - << "<ol>" - << "<li>Redistributions of source code must retain the above copyright" - << "notice, this list of conditions and the following disclaimer.</li>" - << "<li>Redistributions in binary form must reproduce the above copyright" - << "notice, this list of conditions and the following disclaimer in the" - << "documentation and/or other materials provided with the distribution.</li>" - << "<li>All advertising materials mentioning features or use of this software" - << "must display the following acknowledgement:" << "<br />" - << "'This product includes software developed by the OpenGeoSys Community.'</li>" - << "<li>Neither the name of the OpenGeoSys Community nor the" - << "names of its contributors may be used to endorse or promote products" - << "derived from this software without specific prior written permission.</li>" - << "<li>Attribute the OpenGeoSys Community, preferably citing an appropriate" - << "paper listed on the OpenGeoSys Community homepage:" - << "<a href='http://www.opengeosys.org/papers'>http://www.opengeosys.org/papers</a></li>" - << "</ol></p>" - << "<p>THIS SOFTWARE IS PROVIDED BY THE OpenGeoSys Community ''AS IS'' AND ANY" - << "EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED" - << "WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE" - << "DISCLAIMED. IN NO EVENT SHALL THE OpenGeoSys Community BE LIABLE FOR ANY" - << "DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES" - << "(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;" - << "LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND" - << "ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT" - << "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS" - << "SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</p>"; + stream + << "<p>Copyright (c) 2012-2021, OpenGeoSys Community " + << "(<a " + "href='http://www.opengeosys.org'>http://www.opengeosys.org</a>)<br " + "/>" + << "All rights reserved.</p>" + << "<p>Redistribution and use in source and binary forms, with or " + "without" + << "modification, are permitted provided that the following conditions " + "are met:" + << "<ol>" + << "<li>Redistributions of source code must retain the above copyright" + << "notice, this list of conditions and the following disclaimer.</li>" + << "<li>Redistributions in binary form must reproduce the above " + "copyright" + << "notice, this list of conditions and the following disclaimer in the" + << "documentation and/or other materials provided with the " + "distribution.</li>" + << "<li>All advertising materials mentioning features or use of this " + "software" + << "must display the following acknowledgement:" + << "<br />" + << "'This product includes software developed by the OpenGeoSys " + "Community.'</li>" + << "<li>Neither the name of the OpenGeoSys Community nor the" + << "names of its contributors may be used to endorse or promote " + "products" + << "derived from this software without specific prior written " + "permission.</li>" + << "<li>Attribute the OpenGeoSys Community, preferably citing an " + "appropriate" + << "paper listed on the OpenGeoSys Community homepage:" + << "<a " + "href='http://www.opengeosys.org/papers'>http://www.opengeosys.org/" + "papers</a></li>" + << "</ol></p>" + << "<p>THIS SOFTWARE IS PROVIDED BY THE OpenGeoSys Community ''AS IS'' " + "AND ANY" + << "EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE " + "IMPLIED" + << "WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE " + "ARE" + << "DISCLAIMED. IN NO EVENT SHALL THE OpenGeoSys Community BE LIABLE " + "FOR ANY" + << "DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL " + "DAMAGES" + << "(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR " + "SERVICES;" + << "LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER " + "CAUSED AND" + << "ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, " + "OR TORT" + << "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE " + "USE OF THIS" + << "SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</p>"; this->licenseTextBrowser->setHtml(*(stream.string())); } @@ -65,4 +90,3 @@ void LicenseDialog::on_okPushButton_pressed() { this->done(QDialog::Accepted); } - diff --git a/Applications/DataExplorer/DataView/LineEditDialog.cpp b/Applications/DataExplorer/DataView/LineEditDialog.cpp index eec707fcbf11c961bc77312e2c41fa4d03ddb753..c85293d57caecd87927f0483e7475b85b930dcba 100644 --- a/Applications/DataExplorer/DataView/LineEditDialog.cpp +++ b/Applications/DataExplorer/DataView/LineEditDialog.cpp @@ -13,12 +13,17 @@ */ #include "LineEditDialog.h" -#include "OGSError.h" + #include <QStringList> #include <QStringListModel> -LineEditDialog::LineEditDialog(const GeoLib::PolylineVec &ply_vec, QDialog* parent) - : QDialog(parent), _allPly(new QStringListModel), _selPly(new QStringListModel), +#include "OGSError.h" + +LineEditDialog::LineEditDialog(const GeoLib::PolylineVec& ply_vec, + QDialog* parent) + : QDialog(parent), + _allPly(new QStringListModel), + _selPly(new QStringListModel), _geoName(ply_vec.getName()) { setupUi(this); @@ -31,7 +36,8 @@ LineEditDialog::LineEditDialog(const GeoLib::PolylineVec &ply_vec, QDialog* pare { std::string ply_name; ply_vec.getNameOfElementByID(i, ply_name); - list.append("Line " + QString::number(i) + " " + QString::fromStdString(ply_name)); + list.append("Line " + QString::number(i) + " " + + QString::fromStdString(ply_name)); } _allPly->setStringList(list); @@ -47,7 +53,8 @@ LineEditDialog::~LineEditDialog() void LineEditDialog::on_selectPlyButton_pressed() { - QModelIndexList selected = this->allPlyView->selectionModel()->selectedIndexes(); + QModelIndexList selected = + this->allPlyView->selectionModel()->selectedIndexes(); QStringList list = _selPly->stringList(); for (auto& index : selected) @@ -61,7 +68,8 @@ void LineEditDialog::on_selectPlyButton_pressed() void LineEditDialog::on_deselectPlyButton_pressed() { - QModelIndexList selected = this->selectedPlyView->selectionModel()->selectedIndexes(); + QModelIndexList selected = + this->selectedPlyView->selectionModel()->selectedIndexes(); QStringList list = _allPly->stringList(); for (auto& index : selected) @@ -75,16 +83,17 @@ void LineEditDialog::on_deselectPlyButton_pressed() void LineEditDialog::accept() { - std::vector<std::size_t> selectedIndeces = this->getSelectedIndeces(_selPly->stringList()); + std::vector<std::size_t> selectedIndeces = + this->getSelectedIndeces(_selPly->stringList()); if (!selectedIndeces.empty()) { std::string prox_string = this->proximityEdit->text().toStdString(); double prox = (prox_string.empty()) ? 0.0 : strtod(prox_string.c_str(), nullptr); - std::string ply_name = - (plyNameEdit->text().toStdString().empty()) ? "" : plyNameEdit->text(). - toStdString(); + std::string ply_name = (plyNameEdit->text().toStdString().empty()) + ? "" + : plyNameEdit->text().toStdString(); emit connectPolylines(_geoName, selectedIndeces, prox, diff --git a/Applications/DataExplorer/DataView/LinearEditDialog.cpp b/Applications/DataExplorer/DataView/LinearEditDialog.cpp index 1227a09576a007d4d069b0c32c98df765ab678c6..c470662332e32b6c349b21674b9be68f3cdaf66e 100644 --- a/Applications/DataExplorer/DataView/LinearEditDialog.cpp +++ b/Applications/DataExplorer/DataView/LinearEditDialog.cpp @@ -14,9 +14,9 @@ #include "LinearEditDialog.h" -LinearEditDialog::LinearEditDialog(const GeoLib::Polyline &line, - const std::vector<std::size_t> &dis_nodes, - const std::vector<double> &dis_values, +LinearEditDialog::LinearEditDialog(const GeoLib::Polyline& line, + const std::vector<std::size_t>& dis_nodes, + const std::vector<double>& dis_values, QDialog* parent) : QDialog(parent), _line(line) { @@ -24,8 +24,8 @@ LinearEditDialog::LinearEditDialog(const GeoLib::Polyline &line, setupDialog(dis_nodes, dis_values); } -void LinearEditDialog::setupDialog(const std::vector<std::size_t> &dis_nodes, - const std::vector<double> &dis_values) +void LinearEditDialog::setupDialog(const std::vector<std::size_t>& dis_nodes, + const std::vector<double>& dis_values) { std::size_t nPoints(_line.getNumberOfPoints()); this->tableWidget->setRowCount(nPoints); @@ -34,13 +34,13 @@ void LinearEditDialog::setupDialog(const std::vector<std::size_t> &dis_nodes, for (std::size_t i = 0; i < nPoints; i++) { indexlist.push_back(QString::number(i)); - QTableWidgetItem *newItem = new QTableWidgetItem(""); + QTableWidgetItem* newItem = new QTableWidgetItem(""); tableWidget->setItem(i, 0, newItem); } QStringList vHeaders(indexlist); tableWidget->setVerticalHeaderLabels(vHeaders); - std::size_t nValues (dis_values.size()); + std::size_t nValues(dis_values.size()); for (std::size_t i = 0; i < nValues; i++) { tableWidget->item(static_cast<int>(dis_nodes[i]), 0) @@ -52,7 +52,7 @@ LinearEditDialog::~LinearEditDialog() = default; void LinearEditDialog::on_comboBox_currentIndexChanged(int index) { - if (index > 0) //elevation + if (index > 0) // elevation { std::size_t nRows = tableWidget->rowCount(); for (std::size_t i = 0; i < nRows; i++) @@ -65,12 +65,12 @@ void LinearEditDialog::on_comboBox_currentIndexChanged(int index) void LinearEditDialog::accept() { - std::vector< std::pair<std::size_t,double> > linear_values; + std::vector<std::pair<std::size_t, double>> linear_values; std::size_t nRows = tableWidget->rowCount(); for (std::size_t i = 0; i < nRows; i++) { - QString row_text (tableWidget->item(i,0)->text()); + QString row_text(tableWidget->item(i, 0)->text()); if (row_text.length() > 0) { linear_values.emplace_back(i, row_text.toDouble()); diff --git a/Applications/DataExplorer/DataView/MergeGeometriesDialog.cpp b/Applications/DataExplorer/DataView/MergeGeometriesDialog.cpp index 9c80f74cd5b14d7e5897f3167f7c6c8d4773ca1f..b3b678aa3c8f317670f8db61890aed4945686bea 100644 --- a/Applications/DataExplorer/DataView/MergeGeometriesDialog.cpp +++ b/Applications/DataExplorer/DataView/MergeGeometriesDialog.cpp @@ -14,14 +14,18 @@ #include "MergeGeometriesDialog.h" -#include "GEOObjects.h" #include <QStringList> #include <QStringListModel> +#include "GEOObjects.h" #include "OGSError.h" -MergeGeometriesDialog::MergeGeometriesDialog(GeoLib::GEOObjects& geoObjects, QDialog* parent) - : QDialog(parent), _geo_objects(geoObjects), _allGeo(new QStringListModel), _selGeo(new QStringListModel) +MergeGeometriesDialog::MergeGeometriesDialog(GeoLib::GEOObjects& geoObjects, + QDialog* parent) + : QDialog(parent), + _geo_objects(geoObjects), + _allGeo(new QStringListModel), + _selGeo(new QStringListModel) { setupUi(this); @@ -31,9 +35,11 @@ MergeGeometriesDialog::MergeGeometriesDialog(GeoLib::GEOObjects& geoObjects, QDi std::vector<std::string> geo_station_names; _geo_objects.getStationVectorNames(geo_station_names); - // merge method does currently not merge stations, converter function needed first - //geoNames.reserve(geo_station_names.size()); - //std::copy(geo_station_names.begin(), geo_station_names.end(), std::back_inserter(geoNames)); + // merge method does currently not merge stations, converter function needed + // first + // geoNames.reserve(geo_station_names.size()); + // std::copy(geo_station_names.begin(), geo_station_names.end(), + // std::back_inserter(geoNames)); std::size_t nGeoObjects(geoNames.size()); @@ -66,7 +72,8 @@ MergeGeometriesDialog::~MergeGeometriesDialog() void MergeGeometriesDialog::on_selectGeoButton_pressed() { - QModelIndexList selected = this->allGeoView->selectionModel()->selectedIndexes(); + QModelIndexList selected = + this->allGeoView->selectionModel()->selectedIndexes(); QStringList list = _selGeo->stringList(); for (auto& index : selected) @@ -80,7 +87,8 @@ void MergeGeometriesDialog::on_selectGeoButton_pressed() void MergeGeometriesDialog::on_deselectGeoButton_pressed() { - QModelIndexList selected = this->selectedGeoView->selectionModel()->selectedIndexes(); + QModelIndexList selected = + this->selectedGeoView->selectionModel()->selectedIndexes(); QStringList list = _allGeo->stringList(); for (auto& index : selected) diff --git a/Applications/DataExplorer/DataView/MeshAnalysisDialog.cpp b/Applications/DataExplorer/DataView/MeshAnalysisDialog.cpp index dc356a6843d57c149f971fe89a1faa43d0dbcdd3..b3ff0a1b0444719a4bf900640080b37f946f058b 100644 --- a/Applications/DataExplorer/DataView/MeshAnalysisDialog.cpp +++ b/Applications/DataExplorer/DataView/MeshAnalysisDialog.cpp @@ -13,18 +13,17 @@ */ #include "MeshAnalysisDialog.h" + #include "Mesh.h" -#include "MeshQuality/MeshValidation.h" #include "MeshEditing/MeshRevision.h" +#include "MeshQuality/MeshValidation.h" #include "MeshSearch/NodeSearch.h" - #include "StrictDoubleValidator.h" - MeshAnalysisDialog::MeshAnalysisDialog( std::vector<std::unique_ptr<MeshLib::Mesh>> const& mesh_vec, QDialog* parent) -: QDialog(parent), _mesh_vec(mesh_vec) + : QDialog(parent), _mesh_vec(mesh_vec) { setupUi(this); @@ -40,34 +39,42 @@ MeshAnalysisDialog::MeshAnalysisDialog( auto* collapse_threshold_validator = new StrictDoubleValidator(0, 1000000, 7, this); - this->collapsibleNodesThreshold->setValidator (collapse_threshold_validator); + this->collapsibleNodesThreshold->setValidator(collapse_threshold_validator); auto* volume_threshold_validator = new StrictDoubleValidator(0, 1e10, 10, this); - this->zeroVolumeThreshold->setValidator (volume_threshold_validator); + this->zeroVolumeThreshold->setValidator(volume_threshold_validator); } MeshAnalysisDialog::~MeshAnalysisDialog() = default; void MeshAnalysisDialog::on_startButton_pressed() { - MeshLib::Mesh const& mesh (*_mesh_vec[this->meshListBox->currentIndex()].get()); + MeshLib::Mesh const& mesh( + *_mesh_vec[this->meshListBox->currentIndex()].get()); MeshLib::NodeSearch ns(mesh); ns.searchUnused(); - const std::vector<std::size_t> unusedNodesIdx (ns.getSearchedNodeIDs()); + const std::vector<std::size_t> unusedNodesIdx(ns.getSearchedNodeIDs()); MeshLib::MeshRevision rev(const_cast<MeshLib::Mesh&>(mesh)); - std::vector<std::size_t> const& collapsibleNodeIds (rev.collapseNodeIndices( - this->collapsibleNodesThreshold->text().toDouble() + std::numeric_limits<double>::epsilon())); - this->nodesGroupBox->setTitle("Nodes (out of " + QString::number(mesh.getNumberOfNodes()) + ")"); + std::vector<std::size_t> const& collapsibleNodeIds(rev.collapseNodeIndices( + this->collapsibleNodesThreshold->text().toDouble() + + std::numeric_limits<double>::epsilon())); + this->nodesGroupBox->setTitle( + "Nodes (out of " + QString::number(mesh.getNumberOfNodes()) + ")"); this->nodesMsgOutput(unusedNodesIdx, collapsibleNodeIds); - const std::vector<ElementErrorCode> element_error_codes (MeshLib::MeshValidation::testElementGeometry( - mesh, this->zeroVolumeThreshold->text().toDouble() + std::numeric_limits<double>::epsilon())); - this->elementsGroupBox->setTitle("Elements (out of " + QString::number(mesh.getNumberOfElements()) + ")"); + const std::vector<ElementErrorCode> element_error_codes( + MeshLib::MeshValidation::testElementGeometry( + mesh, + this->zeroVolumeThreshold->text().toDouble() + + std::numeric_limits<double>::epsilon())); + this->elementsGroupBox->setTitle( + "Elements (out of " + QString::number(mesh.getNumberOfElements()) + + ")"); this->elementsMsgOutput(element_error_codes); - unsigned const n_holes (MeshLib::MeshValidation::detectHoles(mesh)); + unsigned const n_holes(MeshLib::MeshValidation::detectHoles(mesh)); if (n_holes > 0) { this->meshHoleOutputLabel->setText( @@ -76,9 +83,11 @@ void MeshAnalysisDialog::on_startButton_pressed() } } -void MeshAnalysisDialog::nodesMsgOutput(std::vector<std::size_t> const& node_ids, std::vector<std::size_t> const& collapsibleNodeIds) +void MeshAnalysisDialog::nodesMsgOutput( + std::vector<std::size_t> const& node_ids, + std::vector<std::size_t> const& collapsibleNodeIds) { - const std::size_t nNodeIds (node_ids.size()); + const std::size_t nNodeIds(node_ids.size()); QString nodes_output(""); if (node_ids.empty()) { @@ -86,7 +95,8 @@ void MeshAnalysisDialog::nodesMsgOutput(std::vector<std::size_t> const& node_ids } else { - nodes_output += (QString::number(nNodeIds) + " nodes are not part of any element:\n"); + nodes_output += (QString::number(nNodeIds) + + " nodes are not part of any element:\n"); for (std::size_t i = 0; i < nNodeIds; ++i) { nodes_output += (QString::number(node_ids[i]) + ", "); @@ -105,17 +115,22 @@ void MeshAnalysisDialog::nodesMsgOutput(std::vector<std::size_t> const& node_ids count++; } } - nodes_output = (count > 0) ? QString::number(count) + " nodes found:\n" : "No nodes found."; + nodes_output = (count > 0) ? QString::number(count) + " nodes found:\n" + : "No nodes found."; nodes_output.append(node_ids_str); this->collapsibleNodesText->setText(nodes_output); } -void MeshAnalysisDialog::elementsMsgOutput(const std::vector<ElementErrorCode> &element_error_codes) +void MeshAnalysisDialog::elementsMsgOutput( + const std::vector<ElementErrorCode>& element_error_codes) { - std::array<std::string, static_cast<std::size_t>(ElementErrorFlag::MaxValue)> output_str(MeshLib::MeshValidation::ElementErrorCodeOutput(element_error_codes)); + std::array<std::string, + static_cast<std::size_t>(ElementErrorFlag::MaxValue)> + output_str(MeshLib::MeshValidation::ElementErrorCodeOutput( + element_error_codes)); this->zeroVolumeText->setText(QString::fromStdString(output_str[0])); - this-> nonPlanarText->setText(QString::fromStdString(output_str[1])); - this-> nonConvexText->setText(QString::fromStdString(output_str[2])); - this-> nodeOrderText->setText(QString::fromStdString(output_str[3])); + this->nonPlanarText->setText(QString::fromStdString(output_str[1])); + this->nonConvexText->setText(QString::fromStdString(output_str[2])); + this->nodeOrderText->setText(QString::fromStdString(output_str[3])); } diff --git a/Applications/DataExplorer/DataView/MeshElementRemovalDialog.cpp b/Applications/DataExplorer/DataView/MeshElementRemovalDialog.cpp index 22bb71f3be109f1994dbba25333600b1188f6043..f4c84ffa0373a938c56dcefd326ebaa454614f12 100644 --- a/Applications/DataExplorer/DataView/MeshElementRemovalDialog.cpp +++ b/Applications/DataExplorer/DataView/MeshElementRemovalDialog.cpp @@ -41,8 +41,8 @@ MeshElementRemovalDialog::MeshElementRemovalDialog( auto const& mesh_vec(_project.getMeshObjects()); - const std::size_t nMeshes (mesh_vec.size()); - for (std::size_t i=0; i<nMeshes; ++i) + const std::size_t nMeshes(mesh_vec.size()); + for (std::size_t i = 0; i < nMeshes; ++i) { std::string name = mesh_vec[i]->getName(); this->meshNameComboBox->addItem(QString::fromStdString(name)); @@ -59,19 +59,21 @@ MeshElementRemovalDialog::~MeshElementRemovalDialog() = default; void MeshElementRemovalDialog::accept() { - if (this->newMeshNameEdit->text().size()==0) + if (this->newMeshNameEdit->text().size() == 0) { OGSError::box("Please enter name for new mesh."); return; } - bool anything_checked (false); + bool anything_checked(false); - const MeshLib::Mesh* msh = _project.getMesh(this->meshNameComboBox->currentText().toStdString()); + const MeshLib::Mesh* msh = + _project.getMesh(this->meshNameComboBox->currentText().toStdString()); MeshLib::ElementSearch ex(*msh); if (this->elementTypeCheckBox->isChecked()) { - QList<QListWidgetItem*> items = this->elementTypeListWidget->selectedItems(); + QList<QListWidgetItem*> items = + this->elementTypeListWidget->selectedItems(); for (auto& item : items) { ex.searchByElementType( @@ -81,7 +83,8 @@ void MeshElementRemovalDialog::accept() } if (this->scalarArrayCheckBox->isChecked()) { - std::string const array_name = this->scalarArrayComboBox->currentText().toStdString(); + std::string const array_name = + this->scalarArrayComboBox->currentText().toStdString(); double min_val; double max_val; bool outside = this->outsideButton->isChecked(); @@ -117,18 +120,28 @@ void MeshElementRemovalDialog::accept() } if (this->boundingBoxCheckBox->isChecked()) { - std::vector<MeshLib::Node*> const& nodes (_project.getMesh(this->meshNameComboBox->currentText().toStdString())->getNodes()); + std::vector<MeshLib::Node*> const& nodes( + _project + .getMesh(this->meshNameComboBox->currentText().toStdString()) + ->getNodes()); GeoLib::AABB const aabb(nodes.begin(), nodes.end()); auto minAABB = aabb.getMinPoint(); auto maxAABB = aabb.getMaxPoint(); - // only extract bounding box parameters that have been edited (otherwise there will be rounding errors!) - minAABB[0] = (aabb_edits[0]) ? this->xMinEdit->text().toDouble() : (minAABB[0]); - maxAABB[0] = (aabb_edits[1]) ? this->xMaxEdit->text().toDouble() : (maxAABB[0]); - minAABB[1] = (aabb_edits[2]) ? this->yMinEdit->text().toDouble() : (minAABB[1]); - maxAABB[1] = (aabb_edits[3]) ? this->yMaxEdit->text().toDouble() : (maxAABB[1]); - minAABB[2] = (aabb_edits[4]) ? this->zMinEdit->text().toDouble() : (minAABB[2]); - maxAABB[2] = (aabb_edits[5]) ? this->zMaxEdit->text().toDouble() : (maxAABB[2]); + // only extract bounding box parameters that have been edited (otherwise + // there will be rounding errors!) + minAABB[0] = + (aabb_edits[0]) ? this->xMinEdit->text().toDouble() : (minAABB[0]); + maxAABB[0] = + (aabb_edits[1]) ? this->xMaxEdit->text().toDouble() : (maxAABB[0]); + minAABB[1] = + (aabb_edits[2]) ? this->yMinEdit->text().toDouble() : (minAABB[1]); + maxAABB[1] = + (aabb_edits[3]) ? this->yMaxEdit->text().toDouble() : (maxAABB[1]); + minAABB[2] = + (aabb_edits[4]) ? this->zMinEdit->text().toDouble() : (minAABB[2]); + maxAABB[2] = + (aabb_edits[5]) ? this->zMaxEdit->text().toDouble() : (maxAABB[2]); std::vector<MathLib::Point3d> extent; extent.push_back(minAABB); extent.push_back(maxAABB); @@ -176,7 +189,8 @@ void MeshElementRemovalDialog::reject() this->done(QDialog::Rejected); } -std::size_t MeshElementRemovalDialog::addScalarArrays(MeshLib::Mesh const& mesh) const +std::size_t MeshElementRemovalDialog::addScalarArrays( + MeshLib::Mesh const& mesh) const { for (auto [name, property] : mesh.getProperties()) { @@ -195,10 +209,14 @@ void MeshElementRemovalDialog::enableScalarArrayWidgets(bool enable) const this->scalarArrayComboBox->setEnabled(enable); this->outsideButton->setEnabled(enable); this->insideButton->setEnabled(enable); - this->outsideScalarMinEdit->setEnabled(enable && this->outsideButton->isChecked()); - this->outsideScalarMaxEdit->setEnabled(enable && this->outsideButton->isChecked()); - this->insideScalarMinEdit->setEnabled(enable && this->insideButton->isChecked()); - this->insideScalarMaxEdit->setEnabled(enable && this->insideButton->isChecked()); + this->outsideScalarMinEdit->setEnabled(enable && + this->outsideButton->isChecked()); + this->outsideScalarMaxEdit->setEnabled(enable && + this->outsideButton->isChecked()); + this->insideScalarMinEdit->setEnabled(enable && + this->insideButton->isChecked()); + this->insideScalarMaxEdit->setEnabled(enable && + this->insideButton->isChecked()); } void MeshElementRemovalDialog::toggleScalarEdits(bool outside) const @@ -216,14 +234,20 @@ void MeshElementRemovalDialog::on_insideButton_toggled(bool /*is_checked*/) void MeshElementRemovalDialog::on_boundingBoxCheckBox_toggled(bool is_checked) { - this->xMinEdit->setEnabled(is_checked); this->xMaxEdit->setEnabled(is_checked); - this->yMinEdit->setEnabled(is_checked); this->yMaxEdit->setEnabled(is_checked); - this->zMinEdit->setEnabled(is_checked); this->zMaxEdit->setEnabled(is_checked); + this->xMinEdit->setEnabled(is_checked); + this->xMaxEdit->setEnabled(is_checked); + this->yMinEdit->setEnabled(is_checked); + this->yMaxEdit->setEnabled(is_checked); + this->zMinEdit->setEnabled(is_checked); + this->zMaxEdit->setEnabled(is_checked); if (is_checked && (_currentIndex != _aabbIndex)) { _aabbIndex = _currentIndex; - std::vector<MeshLib::Node*> const& nodes (_project.getMesh(this->meshNameComboBox->currentText().toStdString())->getNodes()); + std::vector<MeshLib::Node*> const& nodes( + _project + .getMesh(this->meshNameComboBox->currentText().toStdString()) + ->getNodes()); GeoLib::AABB aabb(nodes.begin(), nodes.end()); auto const& minAABB = aabb.getMinPoint(); auto const& maxAABB = aabb.getMaxPoint(); @@ -268,7 +292,8 @@ void MeshElementRemovalDialog::on_meshNameComboBox_currentIndexChanged(int idx) { Q_UNUSED(idx); this->_currentIndex = this->meshNameComboBox->currentIndex(); - this->newMeshNameEdit->setText(this->meshNameComboBox->currentText() + "_new"); + this->newMeshNameEdit->setText(this->meshNameComboBox->currentText() + + "_new"); this->elementTypeListWidget->clearSelection(); this->scalarArrayComboBox->clear(); this->outsideScalarMinEdit->setText(""); @@ -279,10 +304,12 @@ void MeshElementRemovalDialog::on_meshNameComboBox_currentIndexChanged(int idx) on_boundingBoxCheckBox_toggled(this->boundingBoxCheckBox->isChecked()); } -void MeshElementRemovalDialog::on_scalarArrayComboBox_currentIndexChanged(int idx) +void MeshElementRemovalDialog::on_scalarArrayComboBox_currentIndexChanged( + int idx) { Q_UNUSED(idx); - std::string const vec_name(scalarArrayComboBox->currentText().toStdString()); + std::string const vec_name( + scalarArrayComboBox->currentText().toStdString()); if (vec_name.empty()) { return; @@ -307,7 +334,8 @@ void MeshElementRemovalDialog::on_scalarArrayComboBox_currentIndexChanged(int id } template <typename T> -void MeshElementRemovalDialog::setRangeValues(MeshLib::PropertyVector<T> const& vec) +void MeshElementRemovalDialog::setRangeValues( + MeshLib::PropertyVector<T> const& vec) { auto min = std::min_element(vec.cbegin(), vec.cend()); auto max = std::max_element(vec.cbegin(), vec.cend()); diff --git a/Applications/DataExplorer/DataView/MeshItem.cpp b/Applications/DataExplorer/DataView/MeshItem.cpp index 8b690fd3e92335382492c6999545cee5bae41810..010f8fc70b6ac1a4fd6ed6743a539087c8b0412a 100644 --- a/Applications/DataExplorer/DataView/MeshItem.cpp +++ b/Applications/DataExplorer/DataView/MeshItem.cpp @@ -13,6 +13,7 @@ */ #include "MeshItem.h" + #include "MeshLib/Vtk/VtkMappedMeshSource.h" MeshItem::MeshItem(const QList<QVariant>& data, TreeItem* parent, diff --git a/Applications/DataExplorer/DataView/MeshLayerEditDialog.cpp b/Applications/DataExplorer/DataView/MeshLayerEditDialog.cpp index 1d33c8b0c34ba67ae87d7f6f862ab1d2770d2d42..9ba27b04474b79e7ab604b6ea757446b54be3e67 100644 --- a/Applications/DataExplorer/DataView/MeshLayerEditDialog.cpp +++ b/Applications/DataExplorer/DataView/MeshLayerEditDialog.cpp @@ -12,20 +12,11 @@ * */ -#include "MeshGenerators/LayeredVolume.h" #include "MeshLayerEditDialog.h" -#include "BaseLib/Logging.h" - -#include "OGSError.h" -#include "StringTools.h" -#include "Mesh.h" - -#include "Applications/FileIO/AsciiRasterInterface.h" -#include "TetGenInterface.h" - #include <QCheckBox> #include <QDoubleValidator> +#include <QElapsedTimer> #include <QFileDialog> #include <QFileInfo> #include <QGridLayout> @@ -35,32 +26,43 @@ #include <QPushButton> #include <QRadioButton> #include <QSettings> -#include <QElapsedTimer> #include <QVBoxLayout> -MeshLayerEditDialog::MeshLayerEditDialog(const MeshLib::Mesh* mesh, QDialog* parent) - : QDialog(parent), _msh(mesh), _n_layers(0), - _layerEdit (new QLineEdit("1", this)), +#include "Applications/FileIO/AsciiRasterInterface.h" +#include "BaseLib/Logging.h" +#include "Mesh.h" +#include "MeshGenerators/LayeredVolume.h" +#include "OGSError.h" +#include "StringTools.h" +#include "TetGenInterface.h" + +MeshLayerEditDialog::MeshLayerEditDialog(const MeshLib::Mesh* mesh, + QDialog* parent) + : QDialog(parent), + _msh(mesh), + _n_layers(0), + _layerEdit(new QLineEdit("1", this)), _noDataReplacementEdit(nullptr), _minThicknessEdit(nullptr), - _nextButton (new QPushButton("Next", this)), - _layerBox (nullptr), - _radioButtonBox (nullptr), - _ogsMeshButton (nullptr), - _layerSelectionLayout (new QGridLayout(_layerBox)), + _nextButton(new QPushButton("Next", this)), + _layerBox(nullptr), + _radioButtonBox(nullptr), + _ogsMeshButton(nullptr), + _layerSelectionLayout(new QGridLayout(_layerBox)), _use_rasters(true) { setupUi(this); - this->gridLayoutLayerMapping->addWidget(new QLabel("Please specify the number of layers to add:", this), 0, 0); + this->gridLayoutLayerMapping->addWidget( + new QLabel("Please specify the number of layers to add:", this), 0, 0); this->gridLayoutLayerMapping->addWidget(_layerEdit, 0, 1); this->gridLayoutLayerMapping->addWidget(_nextButton, 0, 2); - _layerEdit->setValidator(new QIntValidator(1,999,_layerEdit)); + _layerEdit->setValidator(new QIntValidator(1, 999, _layerEdit)); connect(_nextButton, SIGNAL(pressed()), this, SLOT(nextButtonPressed())); // configure group box + layout this->_layerSelectionLayout->setMargin(10); - this->_layerSelectionLayout->setColumnMinimumWidth(2,10); + this->_layerSelectionLayout->setColumnMinimumWidth(2, 10); this->_layerSelectionLayout->setColumnStretch(0, 80); this->_layerSelectionLayout->setColumnStretch(1, 200); this->_layerSelectionLayout->setColumnStretch(2, 10); @@ -70,7 +72,7 @@ MeshLayerEditDialog::~MeshLayerEditDialog() = default; void MeshLayerEditDialog::nextButtonPressed() { - _n_layers = static_cast<unsigned>(_layerEdit->text().toInt()); + _n_layers = static_cast<unsigned>(_layerEdit->text().toInt()); if (_n_layers < 1) { @@ -82,8 +84,10 @@ void MeshLayerEditDialog::nextButtonPressed() _nextButton->setEnabled(false); auto* _radiobuttonLayout(new QVBoxLayout(_radioButtonBox)); - QRadioButton* selectButton1 (new QRadioButton("Add layers based on raster files", _radioButtonBox)); - QRadioButton* selectButton2 (new QRadioButton("Add layers with static thickness", _radioButtonBox)); + QRadioButton* selectButton1( + new QRadioButton("Add layers based on raster files", _radioButtonBox)); + QRadioButton* selectButton2( + new QRadioButton("Add layers with static thickness", _radioButtonBox)); _radioButtonBox = new QGroupBox(this); _radiobuttonLayout->addWidget(selectButton1); _radiobuttonLayout->addWidget(selectButton2); @@ -97,9 +101,9 @@ void MeshLayerEditDialog::createWithRasters() { this->_use_rasters = true; this->_radioButtonBox->setEnabled(false); - const QString selectText = (_n_layers>0) ? - "Please specify a raster file for mapping each layer:" : - "Please specify raster file for surface mapping:"; + const QString selectText = + (_n_layers > 0) ? "Please specify a raster file for mapping each layer:" + : "Please specify raster file for surface mapping:"; this->_layerBox = new QGroupBox(this); this->_layerBox->setTitle(selectText); @@ -119,14 +123,15 @@ void MeshLayerEditDialog::createWithRasters() text = "Layer" + QString::number(i + 1) + "-Top"; } auto* edit(new QLineEdit(this)); - QPushButton* button (new QPushButton("...", _layerBox)); + QPushButton* button(new QPushButton("...", _layerBox)); this->_edits.push_back(edit); this->_fileButtonMap.insert(button, edit); connect(button, SIGNAL(clicked()), this, SLOT(getFileName())); - this->_layerSelectionLayout->addWidget(new QLabel(text, _layerBox), i, 0); - this->_layerSelectionLayout->addWidget(_edits[i], i, 1); + this->_layerSelectionLayout->addWidget(new QLabel(text, _layerBox), i, + 0); + this->_layerSelectionLayout->addWidget(_edits[i], i, 1); this->_layerSelectionLayout->addWidget(button, i, 2); } this->_layerBox->setLayout(this->_layerSelectionLayout); @@ -150,8 +155,9 @@ void MeshLayerEditDialog::createStatic() QLineEdit* staticLayerEdit = new QLineEdit("10", this); staticLayerEdit->setValidator(new QDoubleValidator(staticLayerEdit)); _edits.push_back(staticLayerEdit); - this->_layerSelectionLayout->addWidget(new QLabel(text, _layerBox), i, 0); - this->_layerSelectionLayout->addWidget(_edits[i], i, 1); + this->_layerSelectionLayout->addWidget(new QLabel(text, _layerBox), i, + 0); + this->_layerSelectionLayout->addWidget(_edits[i], i, 1); } this->_layerBox->setLayout(this->_layerSelectionLayout); this->gridLayoutLayerMapping->addWidget(_layerBox, 4, 0, 1, 3); @@ -164,7 +170,8 @@ void MeshLayerEditDialog::createMeshToolSelection() meshToolSelectionBox->setTitle("Output element type"); auto* meshToolSelectionLayout(new QGridLayout(meshToolSelectionBox)); _ogsMeshButton = new QRadioButton("Prisms", meshToolSelectionBox); - QRadioButton* tetgenMeshButton = new QRadioButton("Tetrahedra", meshToolSelectionBox); + QRadioButton* tetgenMeshButton = + new QRadioButton("Tetrahedra", meshToolSelectionBox); tetgenMeshButton->setFixedWidth(150); auto* minThicknessLabel = new QLabel(meshToolSelectionBox); minThicknessLabel->setText("Minimum thickness of layers:"); @@ -195,7 +202,7 @@ MeshLib::Mesh* MeshLayerEditDialog::createPrismMesh() myTimer0.start(); if (_use_rasters) { - float minimum_thickness (_minThicknessEdit->text().toFloat()); + float minimum_thickness(_minThicknessEdit->text().toFloat()); if (minimum_thickness <= 0) { minimum_thickness = std::numeric_limits<float>::epsilon(); @@ -227,9 +234,10 @@ MeshLib::Mesh* MeshLayerEditDialog::createPrismMesh() MeshLib::Mesh* MeshLayerEditDialog::createTetMesh() { QSettings settings; - QString filename = QFileDialog::getSaveFileName(this, "Write TetGen input file to", - settings.value("lastOpenedTetgenFileDirectory").toString(), - "TetGen Geometry (*.smesh)"); + QString filename = QFileDialog::getSaveFileName( + this, "Write TetGen input file to", + settings.value("lastOpenedTetgenFileDirectory").toString(), + "TetGen Geometry (*.smesh)"); if (filename.isEmpty()) { return nullptr; @@ -242,7 +250,7 @@ MeshLib::Mesh* MeshLayerEditDialog::createTetMesh() if (_use_rasters) { - float minimum_thickness (_minThicknessEdit->text().toFloat()); + float minimum_thickness(_minThicknessEdit->text().toFloat()); if (minimum_thickness <= 0) { minimum_thickness = std::numeric_limits<float>::epsilon(); @@ -262,9 +270,10 @@ MeshLib::Mesh* MeshLayerEditDialog::createTetMesh() if (tg_mesh) { - std::vector<MeshLib::Node> tg_attr (lv.getAttributePoints()); + std::vector<MeshLib::Node> tg_attr(lv.getAttributePoints()); FileIO::TetGenInterface tetgen_interface; - tetgen_interface.writeTetGenSmesh(filename.toStdString(), *tg_mesh, tg_attr); + tetgen_interface.writeTetGenSmesh(filename.toStdString(), *tg_mesh, + tg_attr); } } else @@ -274,10 +283,12 @@ MeshLib::Mesh* MeshLayerEditDialog::createTetMesh() { layer_thickness.push_back(this->_edits[i]->text().toFloat()); } - tg_mesh = MeshLib::MeshLayerMapper::createStaticLayers(*_msh, layer_thickness); + tg_mesh = MeshLib::MeshLayerMapper::createStaticLayers(*_msh, + layer_thickness); std::vector<MeshLib::Node> tg_attr; FileIO::TetGenInterface tetgen_interface; - tetgen_interface.writeTetGenSmesh(filename.toStdString(), *tg_mesh, tg_attr); + tetgen_interface.writeTetGenSmesh(filename.toStdString(), *tg_mesh, + tg_attr); } INFO("Mesh construction time: {:d} ms.", myTimer0.elapsed()); @@ -293,8 +304,8 @@ void MeshLayerEditDialog::accept() return; } - bool all_paths_set (true); - if (_n_layers==0) + bool all_paths_set(true); + if (_n_layers == 0) { if (_edits[0]->text().isEmpty()) { @@ -303,7 +314,7 @@ void MeshLayerEditDialog::accept() } else { - int start_idx = (_use_rasters) ? 1:0; + int start_idx = (_use_rasters) ? 1 : 0; for (int i = start_idx; i < _edits.size(); ++i) { if (_edits[i]->text().isEmpty()) @@ -319,7 +330,7 @@ void MeshLayerEditDialog::accept() return; } - MeshLib::Mesh* new_mesh (nullptr); + MeshLib::Mesh* new_mesh(nullptr); if (_ogsMeshButton->isChecked()) { new_mesh = createPrismMesh(); diff --git a/Applications/DataExplorer/DataView/MeshMapping2DDialog.cpp b/Applications/DataExplorer/DataView/MeshMapping2DDialog.cpp index 9e28e5e8078427043e43b169f9677411dcdd426b..a588d33d3fa5e62e3955dd8f71ef1822fc796109 100644 --- a/Applications/DataExplorer/DataView/MeshMapping2DDialog.cpp +++ b/Applications/DataExplorer/DataView/MeshMapping2DDialog.cpp @@ -8,21 +8,21 @@ */ #include "MeshMapping2DDialog.h" -#include "OGSError.h" -#include "StrictDoubleValidator.h" -#include <QSettings> #include <QFileDialog> +#include <QSettings> -MeshMapping2DDialog::MeshMapping2DDialog(QDialog* parent) -: QDialog(parent) +#include "OGSError.h" +#include "StrictDoubleValidator.h" + +MeshMapping2DDialog::MeshMapping2DDialog(QDialog* parent) : QDialog(parent) { setupUi(this); auto* no_data_validator = new StrictDoubleValidator(this); - this->noDataValueEdit->setValidator (no_data_validator); + this->noDataValueEdit->setValidator(no_data_validator); auto* static_value_validator = new StrictDoubleValidator(this); - this->staticValueEdit->setValidator (static_value_validator); + this->staticValueEdit->setValidator(static_value_validator); } void MeshMapping2DDialog::on_ignoreNoDataCheckbox_toggled(bool isChecked) @@ -54,7 +54,8 @@ void MeshMapping2DDialog::on_rasterSelectButton_pressed() void MeshMapping2DDialog::accept() { - if (this->rasterValueButton->isChecked() && this->rasterPathEdit->text().isEmpty()) + if (this->rasterValueButton->isChecked() && + this->rasterPathEdit->text().isEmpty()) { OGSError::box("Please specify path to raster file."); return; @@ -66,7 +67,8 @@ void MeshMapping2DDialog::accept() OGSError::box("Please specify No Data value."); return; } - if (this->staticValueButton->isChecked() && this->staticValueEdit->text().isEmpty()) + if (this->staticValueButton->isChecked() && + this->staticValueEdit->text().isEmpty()) { OGSError::box("Please specify value for mapping."); return; @@ -83,4 +85,3 @@ void MeshMapping2DDialog::accept() this->done(QDialog::Accepted); } - diff --git a/Applications/DataExplorer/DataView/MeshModel.cpp b/Applications/DataExplorer/DataView/MeshModel.cpp index 264681e34a5833ebce47defd7434650e93e2f612..4ad7156620c05b4a2d2df3d6cd21da675062a91d 100644 --- a/Applications/DataExplorer/DataView/MeshModel.cpp +++ b/Applications/DataExplorer/DataView/MeshModel.cpp @@ -15,32 +15,34 @@ #include "MeshModel.h" #include <vtkUnstructuredGridAlgorithm.h> + #include <QFileInfo> #include <QString> -#include "BaseLib/Logging.h" #include "Applications/DataHolderLib/Project.h" +#include "BaseLib/Logging.h" #include "BaseLib/StringTools.h" #include "Elements/Element.h" -#include "MeshLib/Node.h" - #include "MeshItem.h" +#include "MeshLib/Node.h" #include "TreeItem.h" - const QVariant MeshModel::element_str = "Element"; -const std::map<MeshLib::MeshElemType, QVariant> MeshModel::elem_type_map = MeshModel::createMeshElemTypeMap(); +const std::map<MeshLib::MeshElemType, QVariant> MeshModel::elem_type_map = + MeshModel::createMeshElemTypeMap(); -MeshModel::MeshModel(DataHolderLib::Project &project, QObject* parent /*= 0*/ ) +MeshModel::MeshModel(DataHolderLib::Project& project, QObject* parent /*= 0*/) : TreeModel(parent), _project(project) { delete _rootItem; QList<QVariant> rootData; - rootData << "Mesh Name" << "#" << "Type"; + rootData << "Mesh Name" + << "#" + << "Type"; _rootItem = new TreeItem(rootData, nullptr); } -int MeshModel::columnCount( const QModelIndex &parent /*= QModelIndex()*/ ) const +int MeshModel::columnCount(const QModelIndex& parent /*= QModelIndex()*/) const { Q_UNUSED(parent) @@ -66,9 +68,10 @@ void MeshModel::addMeshObject(const MeshLib::Mesh* mesh) beginResetModel(); INFO("name: {:s}", mesh->getName()); - QVariant const display_name (QString::fromStdString(mesh->getName())); + QVariant const display_name(QString::fromStdString(mesh->getName())); QList<QVariant> meshData; - meshData << display_name << "" << ""; + meshData << display_name << "" + << ""; auto* const newMesh = new MeshItem(meshData, _rootItem, mesh); _rootItem->appendChild(newMesh); @@ -80,15 +83,17 @@ void MeshModel::addMeshObject(const MeshLib::Mesh* mesh) { QList<QVariant> elemData; elemData.reserve(3); - elemData << element_str << i << elem_type_map.at(elems[i]->getGeomType()); + elemData << element_str << i + << elem_type_map.at(elems[i]->getGeomType()); newMesh->appendChild(new TreeItem(elemData, newMesh)); } endResetModel(); - emit meshAdded(this, this->index(_rootItem->childCount() - 1, 0, QModelIndex())); + emit meshAdded(this, + this->index(_rootItem->childCount() - 1, 0, QModelIndex())); } -const MeshLib::Mesh* MeshModel::getMesh(const QModelIndex &idx) const +const MeshLib::Mesh* MeshModel::getMesh(const QModelIndex& idx) const { if (idx.isValid()) { @@ -104,7 +109,7 @@ const MeshLib::Mesh* MeshModel::getMesh(const QModelIndex &idx) const return nullptr; } -const MeshLib::Mesh* MeshModel::getMesh(const std::string &name) const +const MeshLib::Mesh* MeshModel::getMesh(const std::string& name) const { for (int i = 0; i < _rootItem->childCount(); i++) { @@ -119,7 +124,7 @@ const MeshLib::Mesh* MeshModel::getMesh(const std::string &name) const return nullptr; } -bool MeshModel::removeMesh(const QModelIndex &idx) +bool MeshModel::removeMesh(const QModelIndex& idx) { if (idx.isValid()) { @@ -133,7 +138,7 @@ bool MeshModel::removeMesh(const QModelIndex &idx) return false; } -bool MeshModel::removeMesh(const std::string &name) +bool MeshModel::removeMesh(const std::string& name) { for (int i = 0; i < _rootItem->childCount(); i++) { @@ -142,7 +147,7 @@ bool MeshModel::removeMesh(const std::string &name) { beginResetModel(); emit meshRemoved(this, this->index(i, 0, QModelIndex())); - _rootItem->removeChildren(i,1); + _rootItem->removeChildren(i, 1); endResetModel(); return _project.removeMesh(name); } @@ -156,10 +161,11 @@ void MeshModel::updateMesh(MeshLib::Mesh* mesh) { for (int i = 0; i < _rootItem->childCount(); i++) { - if (dynamic_cast<MeshItem*>(this->_rootItem->child(i))->getMesh() == mesh) + if (dynamic_cast<MeshItem*>(this->_rootItem->child(i))->getMesh() == + mesh) { emit meshRemoved(this, this->index(i, 0, QModelIndex())); - _rootItem->removeChildren(i,1); + _rootItem->removeChildren(i, 1); } } this->addMeshObject(mesh); @@ -179,7 +185,8 @@ void MeshModel::updateModel() std::map<MeshLib::MeshElemType, QVariant> MeshModel::createMeshElemTypeMap() { - std::vector<MeshLib::MeshElemType> const& elem_types (MeshLib::getMeshElemTypes()); + std::vector<MeshLib::MeshElemType> const& elem_types( + MeshLib::getMeshElemTypes()); std::map<MeshLib::MeshElemType, QVariant> elem_map; for (MeshLib::MeshElemType t : elem_types) @@ -191,7 +198,7 @@ std::map<MeshLib::MeshElemType, QVariant> MeshModel::createMeshElemTypeMap() return elem_map; } -vtkUnstructuredGridAlgorithm* MeshModel::vtkSource(const QModelIndex &idx) const +vtkUnstructuredGridAlgorithm* MeshModel::vtkSource(const QModelIndex& idx) const { if (idx.isValid()) { @@ -203,7 +210,8 @@ vtkUnstructuredGridAlgorithm* MeshModel::vtkSource(const QModelIndex &idx) const return nullptr; } -vtkUnstructuredGridAlgorithm* MeshModel::vtkSource(const std::string &name) const +vtkUnstructuredGridAlgorithm* MeshModel::vtkSource( + const std::string& name) const { for (int i = 0; i < _rootItem->childCount(); i++) { diff --git a/Applications/DataExplorer/DataView/MeshQualitySelectionDialog.cpp b/Applications/DataExplorer/DataView/MeshQualitySelectionDialog.cpp index 4e4dac9c42923cfad18cb296f53bd0e28627be92..2d085f672a9d8465b34148a31d70ad25d6ae16ed 100644 --- a/Applications/DataExplorer/DataView/MeshQualitySelectionDialog.cpp +++ b/Applications/DataExplorer/DataView/MeshQualitySelectionDialog.cpp @@ -13,12 +13,13 @@ */ #include "MeshQualitySelectionDialog.h" -#include "OGSError.h" #include <QFileDialog> #include <QFileInfo> #include <QSettings> +#include "OGSError.h" + /// Constructor MeshQualitySelectionDialog::MeshQualitySelectionDialog(QDialog* parent) : QDialog(parent), _histogram_path("") @@ -29,7 +30,8 @@ MeshQualitySelectionDialog::MeshQualitySelectionDialog(QDialog* parent) MeshQualitySelectionDialog::~MeshQualitySelectionDialog() = default; -void MeshQualitySelectionDialog::on_histogramCheckBox_toggled(bool is_checked) const +void MeshQualitySelectionDialog::on_histogramCheckBox_toggled( + bool is_checked) const { histogramPathEdit->setEnabled(is_checked); histogramPathButton->setEnabled(is_checked); @@ -39,9 +41,9 @@ void MeshQualitySelectionDialog::on_histogramPathButton_pressed() { QSettings settings; QFileInfo fi(settings.value("lastOpenedFileDirectory").toString()); - QString file_name = QFileDialog::getSaveFileName(this, "Save histogram as", - fi.baseName(), - "Text files (*.txt);;All files (* *.*)"); + QString file_name = + QFileDialog::getSaveFileName(this, "Save histogram as", fi.baseName(), + "Text files (*.txt);;All files (* *.*)"); this->histogramPathEdit->setText(file_name); } diff --git a/Applications/DataExplorer/DataView/MeshTabWidget.cpp b/Applications/DataExplorer/DataView/MeshTabWidget.cpp index 0387777a616899e8d700b7cf6437df4f701ab31f..b006464f8a0bbcb08777036bd258e9912bf2f857 100644 --- a/Applications/DataExplorer/DataView/MeshTabWidget.cpp +++ b/Applications/DataExplorer/DataView/MeshTabWidget.cpp @@ -15,14 +15,18 @@ // ** INCLUDES ** #include "MeshTabWidget.h" -MeshTabWidget::MeshTabWidget( QWidget* parent /*= 0*/ ) - : QWidget(parent) +MeshTabWidget::MeshTabWidget(QWidget* parent /*= 0*/) : QWidget(parent) { setupUi(this); - connect(this->addMeshPushButton, SIGNAL(clicked()), this->treeView, SLOT(addMesh())); - connect(this->saveMeshPushButton, SIGNAL(clicked()), this->treeView, SLOT(writeToFile())); - connect(this->removeMeshPushButton, SIGNAL(clicked()), this->treeView, SLOT(removeMesh())); - connect(this->treeView, SIGNAL(enableSaveButton(bool)), this, SLOT(enableSaveButton(bool))); - connect(this->treeView, SIGNAL(enableRemoveButton(bool)), this, SLOT(enableRemoveButton(bool))); + connect(this->addMeshPushButton, SIGNAL(clicked()), this->treeView, + SLOT(addMesh())); + connect(this->saveMeshPushButton, SIGNAL(clicked()), this->treeView, + SLOT(writeToFile())); + connect(this->removeMeshPushButton, SIGNAL(clicked()), this->treeView, + SLOT(removeMesh())); + connect(this->treeView, SIGNAL(enableSaveButton(bool)), this, + SLOT(enableSaveButton(bool))); + connect(this->treeView, SIGNAL(enableRemoveButton(bool)), this, + SLOT(enableRemoveButton(bool))); } diff --git a/Applications/DataExplorer/DataView/MeshValueEditDialog.cpp b/Applications/DataExplorer/DataView/MeshValueEditDialog.cpp index 5d024870aa7e23bd01ea06369896fa8594c2b8df..7e66bc4e0c1151c45d06e4e6c7640cc9d0a81e7c 100644 --- a/Applications/DataExplorer/DataView/MeshValueEditDialog.cpp +++ b/Applications/DataExplorer/DataView/MeshValueEditDialog.cpp @@ -13,10 +13,10 @@ */ #include "MeshValueEditDialog.h" + #include "MeshEditing/ElementValueModification.h" #include "OGSError.h" - MeshValueEditDialog::MeshValueEditDialog(MeshLib::Mesh* mesh, QDialog* parent) : QDialog(parent), _mesh(mesh) { @@ -41,15 +41,19 @@ void MeshValueEditDialog::accept() OGSError::box("Please input which material you want to replace."); return; } - unsigned old_value = static_cast<unsigned>(this->edit_old_value->text().toInt()); + unsigned old_value = + static_cast<unsigned>(this->edit_old_value->text().toInt()); if (this->edit_new_value->text().isEmpty()) { - OGSError::box("Please input the new material to replace group " + this->edit_old_value->text() + "."); + OGSError::box("Please input the new material to replace group " + + this->edit_old_value->text() + "."); return; } - unsigned new_value = static_cast<unsigned>(this->edit_new_value->text().toInt()); + unsigned new_value = + static_cast<unsigned>(this->edit_new_value->text().toInt()); bool do_not_replace = this->replaceCheckBox->isChecked(); - bool result = MeshLib::ElementValueModification::replace(*_mesh, old_value, new_value, !do_not_replace); + bool result = MeshLib::ElementValueModification::replace( + *_mesh, old_value, new_value, !do_not_replace); if (!result && do_not_replace) { OGSError::box("The new material group already exists."); @@ -72,5 +76,3 @@ void MeshValueEditDialog::on_replaceButton_toggled(bool isSelected) this->edit_new_value->setEnabled(isSelected); this->replaceCheckBox->setEnabled(isSelected); } - - diff --git a/Applications/DataExplorer/DataView/MeshView.cpp b/Applications/DataExplorer/DataView/MeshView.cpp index a999c9cae24eed9dd3a0f6a630f6929d13b99b98..d41989066bcb44c510c978da82687e2418d3cbc7 100644 --- a/Applications/DataExplorer/DataView/MeshView.cpp +++ b/Applications/DataExplorer/DataView/MeshView.cpp @@ -14,46 +14,40 @@ #include "MeshView.h" -#include <memory> - -#include <QHeaderView> #include <QContextMenuEvent> #include <QFileDialog> +#include <QHeaderView> #include <QMenu> #include <QObject> #include <QSettings> +#include <memory> -#include "SHPInterface.h" -#include "TetGenInterface.h" +#include "AddLayerToMeshDialog.h" #include "Applications/FileIO/AsciiRasterInterface.h" - +#include "ImportFileTypes.h" +#include "LastSavedFileDirectory.h" +#include "MeshItem.h" +#include "MeshLayerEditDialog.h" #include "MeshLib/Mesh.h" -#include "MeshLib/Node.h" -#include "MeshLib/MeshSurfaceExtraction.h" #include "MeshLib/MeshEditing/AddLayerToMesh.h" #include "MeshLib/MeshEditing/RasterDataToMesh.h" - -#include "OGSError.h" +#include "MeshLib/MeshSurfaceExtraction.h" +#include "MeshLib/Node.h" #include "MeshMapping2DDialog.h" -#include "RasterDataToMeshDialog.h" -#include "MeshLayerEditDialog.h" -#include "MeshValueEditDialog.h" -#include "SurfaceExtractionDialog.h" -#include "AddLayerToMeshDialog.h" -#include "MeshItem.h" #include "MeshModel.h" - -#include "ImportFileTypes.h" -#include "LastSavedFileDirectory.h" +#include "MeshValueEditDialog.h" +#include "OGSError.h" +#include "RasterDataToMeshDialog.h" +#include "SHPInterface.h" #include "SaveMeshDialog.h" +#include "SurfaceExtractionDialog.h" +#include "TetGenInterface.h" - -MeshView::MeshView( QWidget* parent /*= 0*/ ) - : QTreeView(parent) +MeshView::MeshView(QWidget* parent /*= 0*/) : QTreeView(parent) { setUniformRowHeights(true); - //resizeColumnsToContents(); - //resizeRowsToContents(); + // resizeColumnsToContents(); + // resizeRowsToContents(); } MeshView::~MeshView() = default; @@ -61,22 +55,25 @@ MeshView::~MeshView() = default; void MeshView::updateView() { setAlternatingRowColors(true); - setColumnWidth(0,150); - std::size_t nColumns = (this->model() != nullptr) ? this->model()->columnCount() : 0; + setColumnWidth(0, 150); + std::size_t nColumns = + (this->model() != nullptr) ? this->model()->columnCount() : 0; for (std::size_t i = 1; i < nColumns; i++) { resizeColumnToContents(i); } } -void MeshView::selectionChanged( const QItemSelection &selected, const QItemSelection &deselected ) +void MeshView::selectionChanged(const QItemSelection& selected, + const QItemSelection& deselected) { Q_UNUSED(deselected); if (!selected.isEmpty()) { emit removeSelectedMeshComponent(); const QModelIndex idx = *(selected.indexes().begin()); - const TreeItem* tree_item = static_cast<TreeModel*>(this->model())->getItem(idx); + const TreeItem* tree_item = + static_cast<TreeModel*>(this->model())->getItem(idx); const auto* list_item = dynamic_cast<const MeshItem*>(tree_item); if (list_item) @@ -89,7 +86,10 @@ void MeshView::selectionChanged( const QItemSelection &selected, const QItemSele { emit enableSaveButton(false); emit enableRemoveButton(false); - emit elementSelected(dynamic_cast<const MeshItem*>(tree_item->parentItem())->vtkSource(), static_cast<unsigned>(tree_item->row()), true); + emit elementSelected( + dynamic_cast<const MeshItem*>(tree_item->parentItem()) + ->vtkSource(), + static_cast<unsigned>(tree_item->row()), true); } } } @@ -101,7 +101,7 @@ void MeshView::addMesh() void MeshView::removeMesh() { - QModelIndex index (this->selectionModel()->currentIndex()); + QModelIndex index(this->selectionModel()->currentIndex()); if (!index.isValid()) { OGSError::box("No mesh selected."); @@ -114,39 +114,52 @@ void MeshView::removeMesh() } } -void MeshView::contextMenuEvent( QContextMenuEvent* event ) +void MeshView::contextMenuEvent(QContextMenuEvent* event) { QModelIndex const& index = this->selectionModel()->currentIndex(); - MeshItem const*const item = dynamic_cast<MeshItem*>(static_cast<TreeItem*>(index.internalPointer())); + MeshItem const* const item = dynamic_cast<MeshItem*>( + static_cast<TreeItem*>(index.internalPointer())); if (item == nullptr) { return; } - unsigned const mesh_dim (item->getMesh()->getDimension()); + unsigned const mesh_dim(item->getMesh()->getDimension()); std::vector<MeshAction> actions; actions.push_back({new QAction("Map mesh...", this), 1, 2}); - connect(actions.back().action, SIGNAL(triggered()), this, SLOT(openMap2dMeshDialog())); - actions.push_back({new QAction("Assign raster data to mesh...", this), 1, 2}); - connect(actions.back().action, SIGNAL(triggered()), this, SLOT(openRasterDataToMeshDialog())); + connect(actions.back().action, SIGNAL(triggered()), this, + SLOT(openMap2dMeshDialog())); + actions.push_back( + {new QAction("Assign raster data to mesh...", this), 1, 2}); + connect(actions.back().action, SIGNAL(triggered()), this, + SLOT(openRasterDataToMeshDialog())); actions.push_back({new QAction("Edit mesh...", this), 2, 3}); - connect(actions.back().action, SIGNAL(triggered()), this, SLOT(openMeshEditDialog())); + connect(actions.back().action, SIGNAL(triggered()), this, + SLOT(openMeshEditDialog())); actions.push_back({new QAction("Add layer...", this), 1, 3}); - connect(actions.back().action, SIGNAL(triggered()), this, SLOT(openAddLayerDialog())); + connect(actions.back().action, SIGNAL(triggered()), this, + SLOT(openAddLayerDialog())); actions.push_back({new QAction("Edit material groups...", this), 1, 3}); - connect(actions.back().action, SIGNAL(triggered()), this, SLOT(openValuesEditDialog())); + connect(actions.back().action, SIGNAL(triggered()), this, + SLOT(openValuesEditDialog())); actions.push_back({new QAction("Extract surface...", this), 3, 3}); - connect(actions.back().action, SIGNAL(triggered()), this, SLOT(extractSurfaceMesh())); - actions.push_back({new QAction("Calculate element quality...", this), 2, 3}); - connect(actions.back().action, SIGNAL(triggered()), this, SLOT(checkMeshQuality())); + connect(actions.back().action, SIGNAL(triggered()), this, + SLOT(extractSurfaceMesh())); + actions.push_back( + {new QAction("Calculate element quality...", this), 2, 3}); + connect(actions.back().action, SIGNAL(triggered()), this, + SLOT(checkMeshQuality())); actions.push_back({new QAction("Convert to geometry", this), 1, 2}); - connect(actions.back().action, SIGNAL(triggered()), this, SLOT(convertMeshToGeometry())); + connect(actions.back().action, SIGNAL(triggered()), this, + SLOT(convertMeshToGeometry())); actions.push_back({new QAction("Export to Shapefile...", this), 2, 2}); - connect(actions.back().action, SIGNAL(triggered()), this, SLOT(exportToShapefile())); + connect(actions.back().action, SIGNAL(triggered()), this, + SLOT(exportToShapefile())); actions.push_back({new QAction("Export to TetGen...", this), 3, 3}); - connect(actions.back().action, SIGNAL(triggered()), this, SLOT(exportToTetGen())); + connect(actions.back().action, SIGNAL(triggered()), this, + SLOT(exportToTetGen())); QMenu menu(this); for (MeshAction a : actions) @@ -161,9 +174,9 @@ void MeshView::contextMenuEvent( QContextMenuEvent* event ) void MeshView::openMap2dMeshDialog() { - MeshModel const*const model = static_cast<MeshModel*>(this->model()); + MeshModel const* const model = static_cast<MeshModel*>(this->model()); QModelIndex const index = this->selectionModel()->currentIndex(); - MeshLib::Mesh const*const mesh = model->getMesh(index); + MeshLib::Mesh const* const mesh = model->getMesh(index); if (mesh == nullptr) { return; @@ -202,7 +215,6 @@ void MeshView::openMap2dMeshDialog() dlg.getStaticValue()); } static_cast<MeshModel*>(this->model())->addMesh(std::move(result)); - } void MeshView::openRasterDataToMeshDialog() @@ -246,25 +258,25 @@ void MeshView::openRasterDataToMeshDialog() void MeshView::openMeshEditDialog() { - MeshModel const*const model = static_cast<MeshModel*>(this->model()); + MeshModel const* const model = static_cast<MeshModel*>(this->model()); QModelIndex const index = this->selectionModel()->currentIndex(); - MeshLib::Mesh const*const mesh = model->getMesh(index); + MeshLib::Mesh const* const mesh = model->getMesh(index); MeshLayerEditDialog meshLayerEdit(mesh); - connect(&meshLayerEdit, SIGNAL(mshEditFinished(MeshLib::Mesh*)), - model, SLOT(addMesh(MeshLib::Mesh*))); + connect(&meshLayerEdit, SIGNAL(mshEditFinished(MeshLib::Mesh*)), model, + SLOT(addMesh(MeshLib::Mesh*))); meshLayerEdit.exec(); } void MeshView::openValuesEditDialog() { - MeshModel const*const model = static_cast<MeshModel*>(this->model()); + MeshModel const* const model = static_cast<MeshModel*>(this->model()); QModelIndex const index = this->selectionModel()->currentIndex(); auto* mesh = const_cast<MeshLib::Mesh*>(model->getMesh(index)); MeshValueEditDialog valueEdit(mesh); - connect(&valueEdit, SIGNAL(valueEditFinished(MeshLib::Mesh*)), - model, SLOT(updateMesh(MeshLib::Mesh*))); + connect(&valueEdit, SIGNAL(valueEditFinished(MeshLib::Mesh*)), model, + SLOT(updateMesh(MeshLib::Mesh*))); valueEdit.exec(); } @@ -276,7 +288,8 @@ void MeshView::openAddLayerDialog() return; } - MeshLib::Mesh const*const mesh = static_cast<MeshModel*>(this->model())->getMesh(index); + MeshLib::Mesh const* const mesh = + static_cast<MeshModel*>(this->model())->getMesh(index); if (mesh == nullptr) { return; @@ -290,9 +303,8 @@ void MeshView::openAddLayerDialog() bool const copy_material_ids = false; double const thickness(dlg.getThickness()); - std::unique_ptr<MeshLib::Mesh> result( - MeshLib::addLayerToMesh(*mesh, thickness, dlg.getName(), - dlg.isTopLayer(), copy_material_ids)); + std::unique_ptr<MeshLib::Mesh> result(MeshLib::addLayerToMesh( + *mesh, thickness, dlg.getName(), dlg.isTopLayer(), copy_material_ids)); if (result) { @@ -312,7 +324,8 @@ void MeshView::extractSurfaceMesh() return; } - MeshLib::Mesh const*const mesh = static_cast<MeshModel*>(this->model())->getMesh(index); + MeshLib::Mesh const* const mesh = + static_cast<MeshModel*>(this->model())->getMesh(index); SurfaceExtractionDialog dlg; if (dlg.exec() != QDialog::Accepted) { @@ -320,7 +333,7 @@ void MeshView::extractSurfaceMesh() } Eigen::Vector3d const& dir(dlg.getNormal()); - int const tolerance (dlg.getTolerance()); + int const tolerance(dlg.getTolerance()); std::unique_ptr<MeshLib::Mesh> sfc_mesh( MeshLib::MeshSurfaceExtraction::getMeshSurface( *mesh, dir, tolerance, "Bulk Mesh Node IDs", @@ -339,7 +352,8 @@ void MeshView::extractSurfaceMesh() void MeshView::convertMeshToGeometry() { QModelIndex const index = this->selectionModel()->currentIndex(); - MeshLib::Mesh const*const mesh = static_cast<MeshModel*>(this->model())->getMesh(index); + MeshLib::Mesh const* const mesh = + static_cast<MeshModel*>(this->model())->getMesh(index); emit requestMeshToGeometryConversion(mesh); } @@ -352,10 +366,14 @@ void MeshView::exportToShapefile() const } QSettings const settings; - QFileInfo const fi (settings.value("lastOpenedMeshFileDirectory").toString()); - MeshLib::Mesh const*const mesh = static_cast<MeshModel*>(this->model())->getMesh(index); - QString const fileName = QFileDialog::getSaveFileName(nullptr, "Convert mesh to shapefile...", - LastSavedFileDirectory::getDir() + QString::fromStdString(mesh->getName()), + QFileInfo const fi( + settings.value("lastOpenedMeshFileDirectory").toString()); + MeshLib::Mesh const* const mesh = + static_cast<MeshModel*>(this->model())->getMesh(index); + QString const fileName = QFileDialog::getSaveFileName( + nullptr, "Convert mesh to shapefile...", + LastSavedFileDirectory::getDir() + + QString::fromStdString(mesh->getName()), "ESRI Shapefile (*.shp)"); if (!fileName.isEmpty()) { @@ -376,9 +394,11 @@ void MeshView::exportToTetGen() return; } - MeshLib::Mesh const*const mesh = static_cast<MeshModel*>(this->model())->getMesh(index); + MeshLib::Mesh const* const mesh = + static_cast<MeshModel*>(this->model())->getMesh(index); QSettings const settings; - QString const filename = QFileDialog::getSaveFileName(this, "Write TetGen input file to", + QString const filename = QFileDialog::getSaveFileName( + this, "Write TetGen input file to", settings.value("lastOpenedTetgenFileDirectory").toString(), "TetGen Geometry (*.smesh)"); if (!filename.isEmpty()) @@ -398,7 +418,8 @@ void MeshView::writeToFile() const return; } - MeshLib::Mesh const*const mesh = static_cast<MeshModel*>(this->model())->getMesh(index); + MeshLib::Mesh const* const mesh = + static_cast<MeshModel*>(this->model())->getMesh(index); if (mesh == nullptr) { OGSError::box("No mesh selected."); @@ -411,8 +432,9 @@ void MeshView::writeToFile() const void MeshView::addDIRECTSourceTerms() { - //QModelIndex const index = this->selectionModel()->currentIndex(); - //MeshLib::Mesh const*const grid = static_cast<MeshModel*>(this->model())->getMesh(index); + // QModelIndex const index = this->selectionModel()->currentIndex(); + // MeshLib::Mesh const*const grid = + // static_cast<MeshModel*>(this->model())->getMesh(index); } void MeshView::loadDIRECTSourceTerms() @@ -421,10 +443,10 @@ void MeshView::loadDIRECTSourceTerms() emit loadFEMCondFileRequested(index.data(0).toString().toStdString()); } -void MeshView::checkMeshQuality () +void MeshView::checkMeshQuality() { QModelIndex const index = this->selectionModel()->currentIndex(); - MeshItem const*const item = static_cast<MeshItem*>(static_cast<MeshModel*>(this->model())->getItem(index)); + MeshItem const* const item = static_cast<MeshItem*>( + static_cast<MeshModel*>(this->model())->getItem(index)); emit qualityCheckRequested(item->vtkSource()); } - diff --git a/Applications/DataExplorer/DataView/ModelTreeItem.cpp b/Applications/DataExplorer/DataView/ModelTreeItem.cpp index f13aa4a3d9f5231f8d533e1addff23148d072784..ae6c52ba7bacf2ad46669577d9f4da1d3dee7f02 100644 --- a/Applications/DataExplorer/DataView/ModelTreeItem.cpp +++ b/Applications/DataExplorer/DataView/ModelTreeItem.cpp @@ -14,7 +14,8 @@ #include "ModelTreeItem.h" -ModelTreeItem::ModelTreeItem(const QList<QVariant> &data, TreeItem* parent, BaseItem* item) +ModelTreeItem::ModelTreeItem(const QList<QVariant>& data, TreeItem* parent, + BaseItem* item) : TreeItem(data, parent), _item(item), _stn(nullptr) { } @@ -27,4 +28,3 @@ BaseItem* ModelTreeItem::getItem() const } return nullptr; } - diff --git a/Applications/DataExplorer/DataView/ModellingTabWidget.cpp b/Applications/DataExplorer/DataView/ModellingTabWidget.cpp index 0bcde55b2f069983d7210550bf6534c48e45ed09..f2625254386ad2a2e403858207b8b88d36b53750 100644 --- a/Applications/DataExplorer/DataView/ModellingTabWidget.cpp +++ b/Applications/DataExplorer/DataView/ModellingTabWidget.cpp @@ -16,10 +16,8 @@ //#include "ProcessModel.h" #include "ModellingTabWidget.h" -ModellingTabWidget::ModellingTabWidget( QWidget* parent /*= 0*/ ) +ModellingTabWidget::ModellingTabWidget(QWidget* parent /*= 0*/) : QWidget(parent) { setupUi(this); } - - diff --git a/Applications/DataExplorer/DataView/ProcessView.cpp b/Applications/DataExplorer/DataView/ProcessView.cpp index 954112a9f26aa4e055a509f9e0d643aa7e058a61..08e925b9bf673e88f51f8929eb2b97543575b8f0 100644 --- a/Applications/DataExplorer/DataView/ProcessView.cpp +++ b/Applications/DataExplorer/DataView/ProcessView.cpp @@ -8,15 +8,15 @@ * */ +#include "ProcessView.h" + #include <QFileDialog> #include <QMenu> #include "Applications/DataHolderLib/FemCondition.h" - #include "CondItem.h" #include "ProcessModel.h" #include "ProcessVarItem.h" -#include "ProcessView.h" //#include "FEMConditionSetupDialog.h" #include "SelectMeshDialog.h" diff --git a/Applications/DataExplorer/DataView/RasterDataToMeshDialog.cpp b/Applications/DataExplorer/DataView/RasterDataToMeshDialog.cpp index 05ffa235b38f689d0cadd858e3ccce3b53823eff..d132b3e7fa14680dc0e9d1e558c082d467f1456c 100644 --- a/Applications/DataExplorer/DataView/RasterDataToMeshDialog.cpp +++ b/Applications/DataExplorer/DataView/RasterDataToMeshDialog.cpp @@ -9,11 +9,12 @@ */ #include "RasterDataToMeshDialog.h" -#include "OGSError.h" -#include "StrictDoubleValidator.h" -#include <QSettings> #include <QFileDialog> +#include <QSettings> + +#include "OGSError.h" +#include "StrictDoubleValidator.h" RasterDataToMeshDialog::RasterDataToMeshDialog(std::string const& mesh_name, QDialog* parent) @@ -23,7 +24,7 @@ RasterDataToMeshDialog::RasterDataToMeshDialog(std::string const& mesh_name, this->meshNameEdit->setText(QString::fromStdString(mesh_name) + "_Raster"); auto* no_data_validator = new StrictDoubleValidator(this); - this->noDataValueEdit->setValidator (no_data_validator); + this->noDataValueEdit->setValidator(no_data_validator); } void RasterDataToMeshDialog::on_rasterSelectButton_pressed() @@ -63,4 +64,3 @@ void RasterDataToMeshDialog::accept() this->done(QDialog::Accepted); } - diff --git a/Applications/DataExplorer/DataView/SHPImportDialog.cpp b/Applications/DataExplorer/DataView/SHPImportDialog.cpp index f7eb9c36cc79b033a82d9adb672d49d0e5b43ace..076496baf6ef93679cf0ac8adf5c1e04ef325038 100644 --- a/Applications/DataExplorer/DataView/SHPImportDialog.cpp +++ b/Applications/DataExplorer/DataView/SHPImportDialog.cpp @@ -12,10 +12,7 @@ * */ -#include "GeoLib/GEOObjects.h" -#include "OGSError.h" #include "SHPImportDialog.h" -#include "SHPInterface.h" #include <QDialogButtonBox> #include <QFileInfo> @@ -24,6 +21,10 @@ #include <QRadioButton> #include <QVBoxLayout> +#include "GeoLib/GEOObjects.h" +#include "OGSError.h" +#include "SHPInterface.h" + SHPImportDialog::SHPImportDialog(std::string filename, GeoLib::GEOObjects& geo_objects, std::string const& gmsh_path, @@ -90,26 +91,28 @@ void SHPImportDialog::setupDialog() } _shpContentLabel = - new QLabel("The selected file contains " + QString::number( - numberOfEntities) + " " + type, this); + new QLabel("The selected file contains " + + QString::number(numberOfEntities) + " " + type, + this); _nameLabel = new QLabel("List Name: ", this); QFileInfo fi(QString::fromStdString(_filename)); _listName->setText(fi.baseName()); - if ((shpType - 1) % 10 == 0 && shpType != 31) // Points + if ((shpType - 1) % 10 == 0 && shpType != 31) // Points { _choice1 = new QRadioButton("Read as Geometry Points"); _choice2 = new QRadioButton("Read as Station Points"); - _choice1->toggle(); // default choice - _layout->addWidget( _shpContentLabel ); - _layout->addWidget( _choice1 ); - _layout->addWidget( _choice2 ); - _layout->addWidget( _nameLabel ); - _layout->addWidget( _listName ); + _choice1->toggle(); // default choice + _layout->addWidget(_shpContentLabel); + _layout->addWidget(_choice1); + _layout->addWidget(_choice2); + _layout->addWidget(_nameLabel); + _layout->addWidget(_listName); _fileType = 1; } - else if ((shpType - 3) % 10 == 0 || (shpType - 5) % 10 == 0) // Polylines + else if ((shpType - 3) % 10 == 0 || + (shpType - 5) % 10 == 0) // Polylines { _choice1 = new QRadioButton("Read Polylines only"); _choice2 = new QRadioButton("Read Polylines/Surfaces"); @@ -118,25 +121,27 @@ void SHPImportDialog::setupDialog() _choice2->setDisabled(true); // disable polygon-choice if file // contains only polylines } - _choice1->toggle(); // default choice - _layout->addWidget( _shpContentLabel ); - _layout->addWidget( _choice1 ); - _layout->addWidget( _choice2 ); - _layout->addWidget( _nameLabel ); - _layout->addWidget( _listName ); + _choice1->toggle(); // default choice + _layout->addWidget(_shpContentLabel); + _layout->addWidget(_choice1); + _layout->addWidget(_choice2); + _layout->addWidget(_nameLabel); + _layout->addWidget(_listName); _fileType = 2; } else { - _nameLabel->setText("This element type is currently not supported."); - _layout->addWidget( _shpContentLabel ); - _layout->addWidget( _nameLabel ); + _nameLabel->setText( + "This element type is currently not supported."); + _layout->addWidget(_shpContentLabel); + _layout->addWidget(_nameLabel); } - _buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + _buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | + QDialogButtonBox::Cancel); connect(_buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(_buttonBox, SIGNAL(rejected()), this, SLOT(reject())); - _layout->addWidget( _buttonBox ); + _layout->addWidget(_buttonBox); setLayout(_layout); } diff --git a/Applications/DataExplorer/DataView/SaveMeshDialog.cpp b/Applications/DataExplorer/DataView/SaveMeshDialog.cpp index ecb3acc8d4b19ae81b80e20ba0cc59322efe4c2c..ed699c3e74dfe7137ce2db7c698d7e439664129f 100644 --- a/Applications/DataExplorer/DataView/SaveMeshDialog.cpp +++ b/Applications/DataExplorer/DataView/SaveMeshDialog.cpp @@ -17,30 +17,33 @@ #include <QFileDialog> #include <QSettings> - -#include "MeshLib/IO/VtkIO/VtuInterface.h" +#include "LastSavedFileDirectory.h" #include "MeshLib/IO/Legacy/MeshIO.h" +#include "MeshLib/IO/VtkIO/VtuInterface.h" #include "MeshLib/Mesh.h" #include "OGSError.h" -#include "LastSavedFileDirectory.h" SaveMeshDialog::SaveMeshDialog(MeshLib::Mesh const& mesh, QDialog* parent) : QDialog(parent), _mesh(mesh) { setupUi(this); - this->fileNameEdit->setText(LastSavedFileDirectory::getDir() + QString::fromStdString(_mesh.getName()) + ".vtu"); + this->fileNameEdit->setText(LastSavedFileDirectory::getDir() + + QString::fromStdString(_mesh.getName()) + + ".vtu"); } void SaveMeshDialog::on_selectDirButton_clicked() { - QString file_type ("VTK Unstructured Grid (*.vtu)"); + QString file_type("VTK Unstructured Grid (*.vtu)"); #ifndef NDEBUG file_type.append(";;Legacy geometry file (*.msh)"); -#endif // DEBUG +#endif // DEBUG QSettings settings; - QString const file_name = QFileDialog::getSaveFileName(this, + QString const file_name = QFileDialog::getSaveFileName( + this, "Save mesh as...", - LastSavedFileDirectory::getDir() + QString::fromStdString(_mesh.getName()), + LastSavedFileDirectory::getDir() + + QString::fromStdString(_mesh.getName()), file_type); if (!file_name.isEmpty()) @@ -52,7 +55,7 @@ void SaveMeshDialog::on_selectDirButton_clicked() void SaveMeshDialog::on_dataModeBox_currentIndexChanged(int index) { // Disable compression on Ascii - if(index == 0) + if (index == 0) { this->compressionCheckBox->setChecked(false); this->compressionCheckBox->setEnabled(false); @@ -67,7 +70,7 @@ void SaveMeshDialog::on_dataModeBox_currentIndexChanged(int index) void SaveMeshDialog::accept() { - QString const& file_name (this->fileNameEdit->text()); + QString const& file_name(this->fileNameEdit->text()); if (file_name.isEmpty()) { OGSError::box("No file name entered."); @@ -77,9 +80,8 @@ void SaveMeshDialog::accept() QFileInfo fi(file_name); if (fi.suffix().toLower() == "vtu") { - int dataMode = this->dataModeBox->currentIndex(); - bool compress (this->compressionCheckBox->isChecked()); + bool compress(this->compressionCheckBox->isChecked()); MeshLib::IO::VtuInterface vtkIO(&_mesh, dataMode, compress); vtkIO.writeToFile(file_name.toStdString()); } @@ -94,4 +96,3 @@ void SaveMeshDialog::accept() this->done(QDialog::Accepted); } - diff --git a/Applications/DataExplorer/DataView/SelectMeshDialog.cpp b/Applications/DataExplorer/DataView/SelectMeshDialog.cpp index 4844f717077f64dced9492a59b7abb120e826148..4f80705dc777e40ad4902cd06ccd65d6e6d9fb97 100644 --- a/Applications/DataExplorer/DataView/SelectMeshDialog.cpp +++ b/Applications/DataExplorer/DataView/SelectMeshDialog.cpp @@ -13,15 +13,18 @@ */ #include "SelectMeshDialog.h" -#include "GeoObject.h" +#include <QComboBox> #include <QDialogButtonBox> #include <QLabel> -#include <QComboBox> #include <QVBoxLayout> -SelectMeshDialog::SelectMeshDialog(const GeoLib::GeoObject* geo_object, const std::list<std::string> &msh_names, QDialog* parent) : - QDialog(parent), _geo_object(geo_object) +#include "GeoObject.h" + +SelectMeshDialog::SelectMeshDialog(const GeoLib::GeoObject* geo_object, + const std::list<std::string>& msh_names, + QDialog* parent) + : QDialog(parent), _geo_object(geo_object) { setupDialog(msh_names); show(); @@ -35,14 +38,13 @@ SelectMeshDialog::~SelectMeshDialog() delete _txt_label; } -void SelectMeshDialog::setupDialog(const std::list<std::string> &msh_names) +void SelectMeshDialog::setupDialog(const std::list<std::string>& msh_names) { _layout = new QVBoxLayout(this); QString dialog_text("Select Mesh"); _txt_label = new QLabel(this); _txt_label->setText(dialog_text); - _msh_names = new QComboBox(); for (const auto& msh_name : msh_names) { @@ -50,19 +52,22 @@ void SelectMeshDialog::setupDialog(const std::list<std::string> &msh_names) } setWindowTitle("Select Mesh..."); - _layout->addWidget( _txt_label ); - _layout->addWidget( _msh_names ); - _buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + _layout->addWidget(_txt_label); + _layout->addWidget(_msh_names); + _buttonBox = + new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); connect(_buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(_buttonBox, SIGNAL(rejected()), this, SLOT(reject())); - _layout->addWidget( _buttonBox ); + _layout->addWidget(_buttonBox); setLayout(_layout); } void SelectMeshDialog::accept() { - //emit requestNameChange(_parent_name, GeoLib::convertGeoType(_object_type_name), _id, _new_name->text().toStdString()); + // emit requestNameChange(_parent_name, + // GeoLib::convertGeoType(_object_type_name), _id, + // _new_name->text().toStdString()); this->done(QDialog::Accepted); } diff --git a/Applications/DataExplorer/DataView/SetNameDialog.cpp b/Applications/DataExplorer/DataView/SetNameDialog.cpp index e6f730d32cf533b26ba788a1e533255e9ad75543..f6ab85f0e654b44ea2115c0da218c060414594b0 100644 --- a/Applications/DataExplorer/DataView/SetNameDialog.cpp +++ b/Applications/DataExplorer/DataView/SetNameDialog.cpp @@ -14,16 +14,17 @@ #include "SetNameDialog.h" -#include <QDialogButtonBox> #include <QDialogButtonBox> #include <QLabel> #include <QLineEdit> #include <QVBoxLayout> -SetNameDialog::SetNameDialog(const std::string &geo_object_type, std::size_t id, const std::string &old_name = "", QDialog* parent) -:QDialog(parent) +SetNameDialog::SetNameDialog(const std::string& geo_object_type, std::size_t id, + const std::string& old_name = "", QDialog* parent) + : QDialog(parent) { - QString const& label = QString::fromStdString(geo_object_type) + "#" + QString::number(id); + QString const& label = + QString::fromStdString(geo_object_type) + "#" + QString::number(id); setupDialog(label, old_name); show(); } @@ -36,7 +37,8 @@ SetNameDialog::~SetNameDialog() delete _txt_label; } -void SetNameDialog::setupDialog(const QString &label, const std::string &old_name) +void SetNameDialog::setupDialog(const QString& label, + const std::string& old_name) { _layout = new QVBoxLayout(this); QString dialog_text("Please enter a name for " + label); @@ -44,12 +46,13 @@ void SetNameDialog::setupDialog(const QString &label, const std::string &old_nam _new_name = new QLineEdit(QString::fromStdString(old_name)); setWindowTitle("Set name..."); - _layout->addWidget( _txt_label ); - _layout->addWidget( _new_name ); - _buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + _layout->addWidget(_txt_label); + _layout->addWidget(_new_name); + _buttonBox = + new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); connect(_buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(_buttonBox, SIGNAL(rejected()), this, SLOT(reject())); - _layout->addWidget( _buttonBox ); + _layout->addWidget(_buttonBox); setLayout(_layout); } diff --git a/Applications/DataExplorer/DataView/StationTabWidget.cpp b/Applications/DataExplorer/DataView/StationTabWidget.cpp index d2d6e373c190faba1592bff518e9112ab5d30dd1..17f425a59fd696d0ce639ad7f01d32ddc833bdf2 100644 --- a/Applications/DataExplorer/DataView/StationTabWidget.cpp +++ b/Applications/DataExplorer/DataView/StationTabWidget.cpp @@ -15,14 +15,18 @@ // ** INCLUDES ** #include "StationTabWidget.h" -StationTabWidget::StationTabWidget( QWidget* parent /*= 0*/ ) - : QWidget(parent) +StationTabWidget::StationTabWidget(QWidget* parent /*= 0*/) : QWidget(parent) { setupUi(this); - connect(this->openStnPushButton, SIGNAL(clicked()), this->treeView, SLOT(addStationList())); - connect(this->saveStnPushButton, SIGNAL(clicked()), this->treeView, SLOT(writeToFile())); - connect(this->removeStnPushButton, SIGNAL(clicked()), this->treeView, SLOT(removeStationList())); - connect(this->treeView, SIGNAL(enableSaveButton(bool)), this, SLOT(enableSaveButton(bool))); - connect(this->treeView, SIGNAL(enableRemoveButton(bool)), this, SLOT(enableRemoveButton(bool))); + connect(this->openStnPushButton, SIGNAL(clicked()), this->treeView, + SLOT(addStationList())); + connect(this->saveStnPushButton, SIGNAL(clicked()), this->treeView, + SLOT(writeToFile())); + connect(this->removeStnPushButton, SIGNAL(clicked()), this->treeView, + SLOT(removeStationList())); + connect(this->treeView, SIGNAL(enableSaveButton(bool)), this, + SLOT(enableSaveButton(bool))); + connect(this->treeView, SIGNAL(enableRemoveButton(bool)), this, + SLOT(enableRemoveButton(bool))); } diff --git a/Applications/DataExplorer/DataView/StationTreeModel.cpp b/Applications/DataExplorer/DataView/StationTreeModel.cpp index 26d89fc96e66eb961e822653ae074fff2999ac57..dfc2255dbf7b7dea9fe838da49d47911e17baabd 100644 --- a/Applications/DataExplorer/DataView/StationTreeModel.cpp +++ b/Applications/DataExplorer/DataView/StationTreeModel.cpp @@ -14,22 +14,23 @@ #include "StationTreeModel.h" +#include <QDebug> #include "BaseItem.h" #include "OGSError.h" #include "Station.h" -#include <QDebug> - /** * Constructor. */ -StationTreeModel::StationTreeModel( QObject* parent ) - : TreeModel(parent) +StationTreeModel::StationTreeModel(QObject* parent) : TreeModel(parent) { QList<QVariant> rootData; delete _rootItem; - rootData << "Station Name" << "x" << "y" << "z"; + rootData << "Station Name" + << "x" + << "y" + << "z"; _rootItem = new ModelTreeItem(rootData, nullptr, nullptr); } @@ -42,8 +43,8 @@ StationTreeModel::~StationTreeModel() = default; * \param parent The parent of the item * \return The model index of the item */ -QModelIndex StationTreeModel::index( int row, int column, - const QModelIndex &parent /*= QModelIndex()*/ ) const +QModelIndex StationTreeModel::index( + int row, int column, const QModelIndex& parent /*= QModelIndex()*/) const { if (!hasIndex(row, column, parent)) { @@ -78,13 +79,13 @@ QModelIndex StationTreeModel::index( int row, int column, } /** - * Returns the Station-Object of the ModelTreeItem with the given index and the name of the list this station belongs to. - * \param index Index of the requested item - * \param listName Here, the method will put the name of the list this station belongs to. - * \return The station object associated with the tree item + * Returns the Station-Object of the ModelTreeItem with the given index and the + * name of the list this station belongs to. \param index Index of the requested + * item \param listName Here, the method will put the name of the list this + * station belongs to. \return The station object associated with the tree item */ -GeoLib::Station* StationTreeModel::stationFromIndex( const QModelIndex& index, - QString &listName ) const +GeoLib::Station* StationTreeModel::stationFromIndex(const QModelIndex& index, + QString& listName) const { if (index.isValid()) { @@ -97,7 +98,7 @@ GeoLib::Station* StationTreeModel::stationFromIndex( const QModelIndex& index, return nullptr; } -vtkPolyDataAlgorithm* StationTreeModel::vtkSource(const std::string &name) const +vtkPolyDataAlgorithm* StationTreeModel::vtkSource(const std::string& name) const { std::size_t nLists = _lists.size(); for (std::size_t i = 0; i < nLists; i++) @@ -124,26 +125,31 @@ void StationTreeModel::setNameForItem(const std::string& stn_vec_name, { return; } - TreeItem *const item = (*stn_list)->child(id); + TreeItem* const item = (*stn_list)->child(id); item->setData(0, QString::fromStdString(item_name)); } /** * Inserts a subtree under _rootItem. - * \param listName Name of the new subtree. If no name is given a default name is assigned. - * \param stations The list with stations to be added as children of that subtree + * \param listName Name of the new subtree. If no name is given a default name + * is assigned. \param stations The list with stations to be added as children + * of that subtree */ -void StationTreeModel::addStationList(QString listName, const std::vector<GeoLib::Point*>* stations) +void StationTreeModel::addStationList( + QString listName, const std::vector<GeoLib::Point*>* stations) { beginResetModel(); QList<QVariant> grpName; - if (listName.compare("") == 0) // if no name is given a default name is assigned + if (listName.compare("") == + 0) // if no name is given a default name is assigned { listName = "List"; listName.append(QString::number(rowCount() + 1)); } - grpName << listName << "" << "" << ""; + grpName << listName << "" + << "" + << ""; auto* group = new ModelTreeItem(grpName, _rootItem, new BaseItem(listName, stations)); _lists.push_back(group); @@ -153,17 +159,19 @@ void StationTreeModel::addStationList(QString listName, const std::vector<GeoLib for (int i = 0; i < vectorSize; i++) { QList<QVariant> stn; - stn << QString::fromStdString(static_cast<GeoLib::Station*>((*stations)[i])->getName()) - << QString::number((*(*stations)[i])[0],'f') - << QString::number((*(*stations)[i])[1],'f') - << QString::number((*(*stations)[i])[2],'f'); + stn << QString::fromStdString( + static_cast<GeoLib::Station*>((*stations)[i])->getName()) + << QString::number((*(*stations)[i])[0], 'f') + << QString::number((*(*stations)[i])[1], 'f') + << QString::number((*(*stations)[i])[2], 'f'); auto* child = new ModelTreeItem(stn, group); child->setStation(static_cast<GeoLib::Station*>((*stations)[i])); group->appendChild(child); } - qDebug() << "List" << listName << "loaded, " << stations->size() << "items added."; + qDebug() << "List" << listName << "loaded, " << stations->size() + << "items added."; endResetModel(); } @@ -173,7 +181,7 @@ void StationTreeModel::addStationList(QString listName, const std::vector<GeoLib */ void StationTreeModel::removeStationList(QModelIndex index) { - if (index.isValid()) // + if (index.isValid()) // { auto* item = static_cast<ModelTreeItem*>(getItem(index)); @@ -194,7 +202,7 @@ void StationTreeModel::removeStationList(QModelIndex index) /** * Removes the TreeItem with the given name including all its children */ -void StationTreeModel::removeStationList(const std::string &name) +void StationTreeModel::removeStationList(const std::string& name) { for (auto& list : _lists) { diff --git a/Applications/DataExplorer/DataView/StationTreeView.cpp b/Applications/DataExplorer/DataView/StationTreeView.cpp index 064ec9eeb63f7e7b92d0c5b3e876eec88cf02862..3949001ffdf830e3eeb83b1f7d6036a1ba5c0853 100644 --- a/Applications/DataExplorer/DataView/StationTreeView.cpp +++ b/Applications/DataExplorer/DataView/StationTreeView.cpp @@ -12,44 +12,46 @@ * */ +#include "StationTreeView.h" + #include <QFileDialog> #include <QMenu> -#include "GMSInterface.h" -#include "Station.h" - #include "DiagramPrefsDialog.h" +#include "GMSInterface.h" +#include "ImportFileTypes.h" +#include "LastSavedFileDirectory.h" #include "ModelTreeItem.h" #include "OGSError.h" +#include "Station.h" #include "StationTreeModel.h" -#include "StationTreeView.h" #include "StratWindow.h" -#include "ImportFileTypes.h" -#include "LastSavedFileDirectory.h" StationTreeView::StationTreeView(QWidget* parent) : QTreeView(parent) { -// setContextMenuPolicy(Qt::CustomContextMenu); -// connect(this, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(showContextMenu(const QPoint &))); + // setContextMenuPolicy(Qt::CustomContextMenu); + // connect(this, SIGNAL(customContextMenuRequested(const QPoint &)), + // this, SLOT(showContextMenu(const QPoint &))); } void StationTreeView::updateView() { setAlternatingRowColors(true); - setColumnWidth(0,150); - setColumnWidth(1,75); - setColumnWidth(2,75); - setColumnWidth(3,75); + setColumnWidth(0, 150); + setColumnWidth(1, 75); + setColumnWidth(2, 75); + setColumnWidth(3, 75); } -void StationTreeView::selectionChanged( const QItemSelection &selected, - const QItemSelection &deselected ) +void StationTreeView::selectionChanged(const QItemSelection& selected, + const QItemSelection& deselected) { Q_UNUSED(deselected); if (!selected.isEmpty()) { const QModelIndex idx = *(selected.indexes().begin()); - const TreeItem* tree_item = static_cast<TreeModel*>(this->model())->getItem(idx); + const TreeItem* tree_item = + static_cast<TreeModel*>(this->model())->getItem(idx); const auto* list_item = dynamic_cast<const ModelTreeItem*>(tree_item->parentItem()); @@ -70,12 +72,12 @@ void StationTreeView::selectionChanged( const QItemSelection &selected, emit enableRemoveButton(true); } } - //emit itemSelectionChanged(selected, deselected); - //return QTreeView::selectionChanged(selected, deselected); + // emit itemSelectionChanged(selected, deselected); + // return QTreeView::selectionChanged(selected, deselected); } -void StationTreeView::selectionChangedFromOutside( const QItemSelection &selected, - const QItemSelection &deselected ) +void StationTreeView::selectionChangedFromOutside( + const QItemSelection& selected, const QItemSelection& deselected) { QItemSelectionModel* selModel = this->selectionModel(); @@ -87,7 +89,7 @@ void StationTreeView::selectionChangedFromOutside( const QItemSelection &selecte return QTreeView::selectionChanged(selected, deselected); } -void StationTreeView::contextMenuEvent( QContextMenuEvent* event ) +void StationTreeView::contextMenuEvent(QContextMenuEvent* event) { QModelIndex index = this->selectionModel()->currentIndex(); auto* item = static_cast<ModelTreeItem*>(index.internalPointer()); @@ -102,10 +104,10 @@ void StationTreeView::contextMenuEvent( QContextMenuEvent* event ) if (item->childCount() > 0) { QMenu menu; - QAction* exportAction = menu.addAction("Export to GMS..."); + QAction* exportAction = menu.addAction("Export to GMS..."); menu.addSeparator(); - connect(exportAction, SIGNAL(triggered()), this, SLOT(exportList())); + connect(exportAction, SIGNAL(triggered()), this, SLOT(exportList())); menu.exec(event->globalPos()); } // The current index refers to a station object @@ -115,14 +117,18 @@ void StationTreeView::contextMenuEvent( QContextMenuEvent* event ) QMenu menu; QAction* setNameAction = menu.addAction("Set name..."); - connect(setNameAction, SIGNAL(triggered()), this, SLOT(setNameForElement())); - if (static_cast<StationTreeModel*>(model())->stationFromIndex(index, temp_name)->type() - == GeoLib::Station::StationType::BOREHOLE) + connect(setNameAction, SIGNAL(triggered()), this, + SLOT(setNameForElement())); + if (static_cast<StationTreeModel*>(model()) + ->stationFromIndex(index, temp_name) + ->type() == GeoLib::Station::StationType::BOREHOLE) { QAction* stratAction = menu.addAction("Display Stratigraphy..."); QAction* exportAction = menu.addAction("Export to GMS..."); - connect(stratAction, SIGNAL(triggered()), this, SLOT(displayStratigraphy())); - connect(exportAction, SIGNAL(triggered()), this, SLOT(exportStation())); + connect(stratAction, SIGNAL(triggered()), this, + SLOT(displayStratigraphy())); + connect(exportAction, SIGNAL(triggered()), this, + SLOT(exportStation())); menu.exec(event->globalPos()); } else @@ -137,9 +143,11 @@ void StationTreeView::contextMenuEvent( QContextMenuEvent* event ) void StationTreeView::setNameForElement() { - TreeItem const*const item = static_cast<StationTreeModel*>(model())->getItem( + TreeItem const* const item = + static_cast<StationTreeModel*>(model())->getItem( this->selectionModel()->currentIndex()); - std::string const stn_vec_name = item->parentItem()->data(0).toString().toStdString(); + std::string const stn_vec_name = + item->parentItem()->data(0).toString().toStdString(); emit requestNameChangeDialog(stn_vec_name, item->row()); } @@ -150,17 +158,20 @@ void StationTreeView::displayStratigraphy() QString temp_name; // get list name static_cast<StationTreeModel*>(model())->stationFromIndex( - this->selectionModel()->currentIndex(), temp_name); + this->selectionModel()->currentIndex(), temp_name); // get color table (horrible way to do it but there you go ...) std::map<std::string, DataHolderLib::Color> colorLookupTable = - static_cast<VtkStationSource*>(static_cast<StationTreeModel*> - (model())->vtkSource(temp_name.toStdString()))->getColorLookupTable(); + static_cast<VtkStationSource*>( + static_cast<StationTreeModel*>(model())->vtkSource( + temp_name.toStdString())) + ->getColorLookupTable(); auto* stratView = new StratWindow( static_cast<GeoLib::StationBorehole*>( static_cast<StationTreeModel*>(model())->stationFromIndex( index, temp_name)), &colorLookupTable); - stratView->setAttribute(Qt::WA_DeleteOnClose); // this fixes the memory leak shown by cppcheck + stratView->setAttribute( + Qt::WA_DeleteOnClose); // this fixes the memory leak shown by cppcheck stratView->show(); } @@ -171,16 +182,18 @@ void StationTreeView::addStationList() void StationTreeView::writeToFile() { - QModelIndex index (this->selectionModel()->currentIndex()); + QModelIndex index(this->selectionModel()->currentIndex()); if (!index.isValid()) { OGSError::box("No station list selected."); } else { - TreeItem* item = static_cast<StationTreeModel*>(model())->getItem(index); + TreeItem* item = + static_cast<StationTreeModel*>(model())->getItem(index); QString listName = item->data(0).toString(); - QString fileName = QFileDialog::getSaveFileName(this, "Save station list", + QString fileName = QFileDialog::getSaveFileName( + this, "Save station list", LastSavedFileDirectory::getDir() + listName, "*.stn"); if (!fileName.isEmpty()) { @@ -193,50 +206,57 @@ void StationTreeView::writeToFile() void StationTreeView::exportList() { // only a test for the stratigraphy screenshot tool and writer!! - //QString Name = static_cast<StationTreeModel*>(model())->getItem(this->selectionModel()->currentIndex())->data(0).toString(); - //writeStratigraphiesAsImages(Name); + // QString Name = + // static_cast<StationTreeModel*>(model())->getItem(this->selectionModel()->currentIndex())->data(0).toString(); + // writeStratigraphiesAsImages(Name); TreeItem* item = static_cast<StationTreeModel*>(model())->getItem( - this->selectionModel()->currentIndex()); + this->selectionModel()->currentIndex()); QString listName = item->data(0).toString(); - QString fileName = QFileDialog::getSaveFileName(this, "Export Boreholes to GMS-Format", + QString fileName = QFileDialog::getSaveFileName( + this, "Export Boreholes to GMS-Format", LastSavedFileDirectory::getDir() + listName, "*.txt"); if (!fileName.isEmpty()) { LastSavedFileDirectory::setDir(fileName); - emit stationListExportRequested(listName.toStdString(), fileName.toStdString()); + emit stationListExportRequested(listName.toStdString(), + fileName.toStdString()); } } void StationTreeView::exportStation() { QModelIndex index = this->selectionModel()->currentIndex(); - QString fileName = QFileDialog::getSaveFileName(this, "Export Borehole to GMS-Format", - LastSavedFileDirectory::getDir(), "*.txt"); + QString fileName = + QFileDialog::getSaveFileName(this, "Export Borehole to GMS-Format", + LastSavedFileDirectory::getDir(), "*.txt"); if (!fileName.isEmpty()) { QString temp_name; std::vector<GeoLib::Point*> stations; stations.push_back(static_cast<GeoLib::StationBorehole*>( - static_cast<StationTreeModel*>(model())->stationFromIndex(index,temp_name))); - FileIO::GMSInterface::writeBoreholesToGMS(&stations, fileName.toStdString()); + static_cast<StationTreeModel*>(model())->stationFromIndex( + index, temp_name))); + FileIO::GMSInterface::writeBoreholesToGMS(&stations, + fileName.toStdString()); LastSavedFileDirectory::setDir(fileName); } } void StationTreeView::removeStationList() { - QModelIndex index (this->selectionModel()->currentIndex()); + QModelIndex index(this->selectionModel()->currentIndex()); if (!index.isValid()) { OGSError::box("No station list selected."); } else { - TreeItem* item = static_cast<StationTreeModel*>(model())->getItem(index); + TreeItem* item = + static_cast<StationTreeModel*>(model())->getItem(index); emit stationListRemoved((item->data(0).toString()).toStdString()); - if(this->selectionModel()->selectedIndexes().count() == 0) + if (this->selectionModel()->selectedIndexes().count() == 0) { emit enableSaveButton(false); emit enableRemoveButton(false); @@ -253,9 +273,12 @@ void StationTreeView::showDiagramPrefsDialog() void StationTreeView::writeStratigraphiesAsImages(QString listName) { std::map<std::string, DataHolderLib::Color> colorLookupTable = - static_cast<VtkStationSource*>(static_cast<StationTreeModel*> - (model())->vtkSource(listName.toStdString()))->getColorLookupTable(); - std::vector<ModelTreeItem*> lists = static_cast<StationTreeModel*>(model())->getLists(); + static_cast<VtkStationSource*>( + static_cast<StationTreeModel*>(model())->vtkSource( + listName.toStdString())) + ->getColorLookupTable(); + std::vector<ModelTreeItem*> lists = + static_cast<StationTreeModel*>(model())->getLists(); std::size_t nLists = lists.size(); for (std::size_t i = 0; i < nLists; i++) { diff --git a/Applications/DataExplorer/DataView/StratView/StratBar.cpp b/Applications/DataExplorer/DataView/StratView/StratBar.cpp index 80323c9509eb2de15ea795dec01c29f6970b47ba..2ab579e9b71ee0ff6f4ac246f990d37254435bbf 100644 --- a/Applications/DataExplorer/DataView/StratView/StratBar.cpp +++ b/Applications/DataExplorer/DataView/StratView/StratBar.cpp @@ -13,12 +13,13 @@ */ #include "StratBar.h" + #include <QPainter> StratBar::StratBar(GeoLib::StationBorehole* station, std::map<std::string, DataHolderLib::Color>* stratColors, - QGraphicsItem* parent) : - QGraphicsItem(parent), _station(station) + QGraphicsItem* parent) + : QGraphicsItem(parent), _station(station) { if (stratColors) { @@ -31,10 +32,12 @@ QRectF StratBar::boundingRect() const return QRectF(0, 0, BARWIDTH + 10, totalLogHeight()); } -void StratBar::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) +void StratBar::paint(QPainter* painter, + const QStyleOptionGraphicsItem* option, + QWidget* widget) { - Q_UNUSED (option) - Q_UNUSED (widget) + Q_UNUSED(option) + Q_UNUSED(widget) double top = 0; double height = 0; @@ -42,9 +45,9 @@ void StratBar::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QPen pen(Qt::black, 1, Qt::SolidLine, Qt::SquareCap, Qt::RoundJoin); pen.setCosmetic(true); painter->setPen(pen); - //painter->drawRect(_bar); + // painter->drawRect(_bar); - //pen.setWidth(1); + // pen.setWidth(1); std::vector<GeoLib::Point*> profile = _station->getProfile(); std::vector<std::string> soilNames = _station->getSoilNames(); std::size_t nLayers = profile.size(); @@ -56,7 +59,8 @@ void StratBar::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, top += height; height = logHeight(((*(profile[i - 1]))[2] - (*(profile[i]))[2])); QRectF layer(0, top, BARWIDTH, height); - DataHolderLib::Color const& c (DataHolderLib::getColor(soilNames[i], _stratColors)); + DataHolderLib::Color const& c( + DataHolderLib::getColor(soilNames[i], _stratColors)); QBrush brush(QColor(static_cast<int>(c[0]), static_cast<int>(c[1]), static_cast<int>(c[2]), @@ -69,7 +73,8 @@ void StratBar::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, static_cast<int>(layer.bottom()), BARWIDTH + 5, static_cast<int>(layer.bottom())); - //painter->drawText(BARWIDTH+10, layer.bottom(), QString::number((*(profile[i]))[2])); + // painter->drawText(BARWIDTH+10, layer.bottom(), + // QString::number((*(profile[i]))[2])); } } diff --git a/Applications/DataExplorer/DataView/StratView/StratScene.cpp b/Applications/DataExplorer/DataView/StratView/StratScene.cpp index edb398d9e3687d307e733703d8320f686d55bf9c..37e14d18c2356a2bff6c415959ac58b69c8bccbd 100644 --- a/Applications/DataExplorer/DataView/StratView/StratScene.cpp +++ b/Applications/DataExplorer/DataView/StratView/StratScene.cpp @@ -12,43 +12,46 @@ * */ -#include <limits> +#include "StratScene.h" + #include <math.h> #include <QGraphicsTextItem> +#include <limits> #include "DateTools.h" #include "QNonScalableGraphicsTextItem.h" #include "StratBar.h" -#include "StratScene.h" StratScene::StratScene(GeoLib::StationBorehole* station, std::map<std::string, DataHolderLib::Color>* stratColors, - QObject* parent) : QGraphicsScene(parent) + QObject* parent) + : QGraphicsScene(parent) { QRectF textBounds; int stratBarOffset = 250; - QFont font( "Arial", 15, QFont::DemiBold, false); + QFont font("Arial", 15, QFont::DemiBold, false); - QNonScalableGraphicsTextItem* boreholeTag = addNonScalableText("Borehole", font); + QNonScalableGraphicsTextItem* boreholeTag = + addNonScalableText("Borehole", font); QNonScalableGraphicsTextItem* boreholeName = addNonScalableText( - "\"" + QString::fromStdString(station->getName()) + "\"", - font); + "\"" + QString::fromStdString(station->getName()) + "\"", font); textBounds = boreholeTag->boundingRect(); boreholeTag->setPos((textBounds.width() / 2.0), 80); textBounds = boreholeName->boundingRect(); boreholeName->setPos((textBounds.width() / 2.0), 200); - QNonScalableGraphicsTextItem* totalDepth = - addNonScalableText("Depth: " + QString::number(station->getDepth()) + " m"); + QNonScalableGraphicsTextItem* totalDepth = addNonScalableText( + "Depth: " + QString::number(station->getDepth()) + " m"); textBounds = totalDepth->boundingRect(); totalDepth->setPos((textBounds.width() / 2.0), 350); -/* - QNonScalableGraphicsTextItem* dateText = addNonScalableText("Date: " + QString::fromStdString(date2string(station->getDate()))); - textBounds = dateText->boundingRect(); - dateText->setPos(this->MARGIN + (textBounds.width()/2.0), 350); - */ + /* + QNonScalableGraphicsTextItem* dateText = addNonScalableText("Date: " + + QString::fromStdString(date2string(station->getDate()))); textBounds = + dateText->boundingRect(); dateText->setPos(this->MARGIN + + (textBounds.width()/2.0), 350); + */ QNonScalableGraphicsTextItem* dot = addNonScalableText(" "); dot->setPos(0, 0); @@ -56,7 +59,8 @@ StratScene::StratScene(GeoLib::StationBorehole* station, stratBar->setPos(stratBarOffset, MARGIN); QRectF stratBarBounds = stratBar->boundingRect(); - addDepthLabels(station->getProfile(), stratBarOffset + stratBarBounds.width()); + addDepthLabels(station->getProfile(), + stratBarOffset + stratBarBounds.width()); if (!station->getSoilNames().empty()) { @@ -67,25 +71,29 @@ StratScene::StratScene(GeoLib::StationBorehole* station, StratScene::~StratScene() = default; -void StratScene::addDepthLabels(std::vector<GeoLib::Point*> profile, double offset) +void StratScene::addDepthLabels(std::vector<GeoLib::Point*> profile, + double offset) { QRectF textBounds; double vertPos = MARGIN; std::vector<QNonScalableGraphicsTextItem*> depthText; - depthText.push_back(addNonScalableText(QString::number((*(profile[0]))[2]))); + depthText.push_back( + addNonScalableText(QString::number((*(profile[0]))[2]))); textBounds = depthText[0]->boundingRect(); depthText[0]->setPos(offset + textBounds.width() / 2, vertPos); for (std::size_t i = 1; i < profile.size(); i++) { - depthText.push_back(addNonScalableText(QString::number((*(profile[i]))[2]))); + depthText.push_back( + addNonScalableText(QString::number((*(profile[i]))[2]))); vertPos += log((*(profile[i - 1]))[2] - (*(profile[i]))[2] + 1) * 100; textBounds = depthText[i]->boundingRect(); depthText[i]->setPos(offset + textBounds.width() / 2, vertPos); } } -QNonScalableGraphicsTextItem* StratScene::addNonScalableText(const QString &text, const QFont &font) +QNonScalableGraphicsTextItem* StratScene::addNonScalableText( + const QString& text, const QFont& font) { auto* item = new QNonScalableGraphicsTextItem(text); item->setFont(font); @@ -94,29 +102,35 @@ QNonScalableGraphicsTextItem* StratScene::addNonScalableText(const QString &text } void StratScene::addSoilNameLabels(std::vector<std::string> soilNames, - std::vector<GeoLib::Point*> profile, + std::vector<GeoLib::Point*> + profile, double offset) { - //QRectF textBounds; + // QRectF textBounds; double vertPos = MARGIN; double halfHeight = 0; std::vector<QNonScalableGraphicsTextItem*> soilText; - soilText.push_back(addNonScalableText(QString::fromStdString(soilNames[0]))); - //textBounds = soilText[0]->boundingRect(); + soilText.push_back( + addNonScalableText(QString::fromStdString(soilNames[0]))); + // textBounds = soilText[0]->boundingRect(); soilText[0]->setPos(offset /* - textBounds.width() */, vertPos); for (std::size_t i = 1; i < soilNames.size(); i++) { - soilText.push_back(addNonScalableText(QString::fromStdString(soilNames[i]))); - halfHeight = log((*(profile[i - 1]))[2] - (*(profile[i]))[2] + 1) * 100 / 2; - //textBounds = soilText[i]->boundingRect(); - soilText[i]->setPos(offset /* - textBounds.width() */, vertPos + halfHeight); - vertPos += ( 2 * halfHeight ); + soilText.push_back( + addNonScalableText(QString::fromStdString(soilNames[i]))); + halfHeight = + log((*(profile[i - 1]))[2] - (*(profile[i]))[2] + 1) * 100 / 2; + // textBounds = soilText[i]->boundingRect(); + soilText[i]->setPos(offset /* - textBounds.width() */, + vertPos + halfHeight); + vertPos += (2 * halfHeight); } } -StratBar* StratScene::addStratBar(GeoLib::StationBorehole* station, - std::map<std::string, DataHolderLib::Color>* stratColors) +StratBar* StratScene::addStratBar( + GeoLib::StationBorehole* station, + std::map<std::string, DataHolderLib::Color>* stratColors) { auto* b = new StratBar(station, stratColors); addItem(b); diff --git a/Applications/DataExplorer/DataView/StratView/StratView.cpp b/Applications/DataExplorer/DataView/StratView/StratView.cpp index c8e9117df2d143f58dcdbbd99abe1665f54c5c77..ebbb08d696cb244ec927ea1333282f47846b782f 100644 --- a/Applications/DataExplorer/DataView/StratView/StratView.cpp +++ b/Applications/DataExplorer/DataView/StratView/StratView.cpp @@ -12,17 +12,20 @@ * */ -#include "Station.h" #include "StratView.h" + #include <math.h> +#include "Station.h" + StratView::~StratView() { delete _scene; } -void StratView::setStation(GeoLib::StationBorehole* station, - std::map<std::string, DataHolderLib::Color>* stratColors) +void StratView::setStation( + GeoLib::StationBorehole* station, + std::map<std::string, DataHolderLib::Color>* stratColors) { _scene = new StratScene(station, stratColors); setScene(_scene); @@ -39,7 +42,7 @@ void StratView::initialize() void StratView::resizeEvent(QResizeEvent* event) { - Q_UNUSED (event) + Q_UNUSED(event) update(); } diff --git a/Applications/DataExplorer/DataView/StratView/StratWindow.cpp b/Applications/DataExplorer/DataView/StratView/StratWindow.cpp index b9a189219753b6193a27c6572d7564b1121d9876..2fe2c92187b3744ec88442fa466919639a593209 100644 --- a/Applications/DataExplorer/DataView/StratView/StratWindow.cpp +++ b/Applications/DataExplorer/DataView/StratView/StratWindow.cpp @@ -12,15 +12,18 @@ * */ -#include "Station.h" #include "StratWindow.h" -StratWindow::StratWindow(GeoLib::StationBorehole* station, - std::map<std::string, DataHolderLib::Color>* stratColors, - QWidget* parent) : QWidget(parent) +#include "Station.h" + +StratWindow::StratWindow( + GeoLib::StationBorehole* station, + std::map<std::string, DataHolderLib::Color>* stratColors, + QWidget* parent) + : QWidget(parent) { setupUi(this); - stationView->setRenderHints( QPainter::Antialiasing ); + stationView->setRenderHints(QPainter::Antialiasing); stationView->setStation(station, stratColors); resizeWindow(); } @@ -33,6 +36,7 @@ void StratWindow::on_closeButton_clicked() void StratWindow::resizeWindow() { int width = (stationView->getWidth() > 800) ? 800 : stationView->getWidth(); - int height = (stationView->getHeight() > 600) ? 600 : stationView->getHeight(); + int height = + (stationView->getHeight() > 600) ? 600 : stationView->getHeight(); resize(width, height); } diff --git a/Applications/DataExplorer/DataView/SurfaceExtractionDialog.cpp b/Applications/DataExplorer/DataView/SurfaceExtractionDialog.cpp index 62c404b6255ffe69c3ba858e3ae8d34645ed5d5c..0c11bea4615d76e113a9f8a33401a8072ca1d24f 100644 --- a/Applications/DataExplorer/DataView/SurfaceExtractionDialog.cpp +++ b/Applications/DataExplorer/DataView/SurfaceExtractionDialog.cpp @@ -20,9 +20,12 @@ SurfaceExtractionDialog::SurfaceExtractionDialog(QDialog* parent) : QDialog(parent) { setupUi(this); - this->xNormalEdit->setValidator(new QDoubleValidator(-1, 1, 3, xNormalEdit)); - this->yNormalEdit->setValidator(new QDoubleValidator(-1, 1, 3, yNormalEdit)); - this->zNormalEdit->setValidator(new QDoubleValidator(-1, 1, 3, zNormalEdit)); + this->xNormalEdit->setValidator( + new QDoubleValidator(-1, 1, 3, xNormalEdit)); + this->yNormalEdit->setValidator( + new QDoubleValidator(-1, 1, 3, yNormalEdit)); + this->zNormalEdit->setValidator( + new QDoubleValidator(-1, 1, 3, zNormalEdit)); } void SurfaceExtractionDialog::accept() @@ -34,4 +37,3 @@ void SurfaceExtractionDialog::accept() this->done(QDialog::Accepted); } - diff --git a/Applications/DataExplorer/VtkVis/MeshFromRasterDialog.cpp b/Applications/DataExplorer/VtkVis/MeshFromRasterDialog.cpp index 1648cf6d9e732700162fb851c748e2fec4d4c0a5..f8550a499e9f49bd7c84d3a110cc2d18ee642ac3 100644 --- a/Applications/DataExplorer/VtkVis/MeshFromRasterDialog.cpp +++ b/Applications/DataExplorer/VtkVis/MeshFromRasterDialog.cpp @@ -13,11 +13,12 @@ */ #include "MeshFromRasterDialog.h" -#include "OGSError.h" + #include "MeshGenerators/VtkMeshConverter.h" +#include "OGSError.h" MeshFromRasterDialog::MeshFromRasterDialog(QDialog* parent) -: QDialog(parent), _mesh_name("mesh"), _array_name("MaterialIDs") + : QDialog(parent), _mesh_name("mesh"), _array_name("MaterialIDs") { setupUi(this); @@ -100,4 +101,3 @@ void MeshFromRasterDialog::reject() { this->done(QDialog::Rejected); } - diff --git a/Applications/DataExplorer/VtkVis/NetCdfConfigureDialog.cpp b/Applications/DataExplorer/VtkVis/NetCdfConfigureDialog.cpp index 2948bba58190a2f1fec1a8a9a5e03f8672d53480..b5e05ca3c682bb22fcb35fb4cccb6e26d0b63be7 100644 --- a/Applications/DataExplorer/VtkVis/NetCdfConfigureDialog.cpp +++ b/Applications/DataExplorer/VtkVis/NetCdfConfigureDialog.cpp @@ -9,22 +9,23 @@ #include "NetCdfConfigureDialog.h" -#include "MathLib/Point3d.h" -#include "GeoLib/Raster.h" -#include "MeshLib/MeshGenerators/RasterToMesh.h" -#include "MeshLib/MeshEnums.h" -#include "VtkVis/VtkGeoImageSource.h" -#include "VtkVis/VtkRaster.h" +#include <vtkImageImport.h> #include <QMessageBox> #include <QSettings> -#include <vtkImageImport.h> +#include "GeoLib/Raster.h" +#include "MathLib/Point3d.h" +#include "MeshLib/MeshEnums.h" +#include "MeshLib/MeshGenerators/RasterToMesh.h" +#include "VtkVis/VtkGeoImageSource.h" +#include "VtkVis/VtkRaster.h" using namespace netCDF; // Constructor -NetCdfConfigureDialog::NetCdfConfigureDialog(std::string const& fileName, QDialog* parent) +NetCdfConfigureDialog::NetCdfConfigureDialog(std::string const& fileName, + QDialog* parent) : QDialog(parent), _currentFile(fileName.c_str(), NcFile::read), _currentMesh(nullptr), @@ -33,9 +34,13 @@ NetCdfConfigureDialog::NetCdfConfigureDialog(std::string const& fileName, QDialo { setupUi(this); - int const idx = setVariableSelect(); // set up variables of the file in the combobox - comboBoxVariable->setCurrentIndex(idx); //pre-select the variable with the biggest number of dimensions...valueWithMaxDim() - _currentVar = _currentFile.getVar(comboBoxVariable->itemText(idx).toStdString()); + int const idx = + setVariableSelect(); // set up variables of the file in the combobox + comboBoxVariable->setCurrentIndex( + idx); // pre-select the variable with the biggest number of + // dimensions...valueWithMaxDim() + _currentVar = + _currentFile.getVar(comboBoxVariable->itemText(idx).toStdString()); setDimensionSelect(); @@ -50,16 +55,25 @@ NetCdfConfigureDialog::~NetCdfConfigureDialog() = default; void NetCdfConfigureDialog::accept() { QMessageBox valueErrorBox; - if (_currentVar.getDimCount() < 2){ + if (_currentVar.getDimCount() < 2) + { valueErrorBox.setText("Selected Variable has not enough dimensions."); valueErrorBox.exec(); - }else if (doubleSpinBoxDim2Start->value() == doubleSpinBoxDim2Start->maximum()){ + } + else if (doubleSpinBoxDim2Start->value() == + doubleSpinBoxDim2Start->maximum()) + { valueErrorBox.setText("Lon has invalid extend."); valueErrorBox.exec(); - }else if(doubleSpinBoxDim1Start->value() == doubleSpinBoxDim1Start->maximum()){ + } + else if (doubleSpinBoxDim1Start->value() == + doubleSpinBoxDim1Start->maximum()) + { valueErrorBox.setText("Lat has invalid extend."); valueErrorBox.exec(); - }else{ + } + else + { createDataObject(); this->done(QDialog::Accepted); } @@ -78,38 +92,41 @@ void NetCdfConfigureDialog::on_comboBoxVariable_currentIndexChanged(int /*id*/) setDimensionSelect(); } -//set up x-axis/lat +// set up x-axis/lat void NetCdfConfigureDialog::on_comboBoxDim1_currentIndexChanged(int /*id*/) { - double firstValue=0, lastValue=0; + double firstValue = 0, lastValue = 0; unsigned size = 0; - getDimEdges(comboBoxDim1->currentText().toStdString(), size, firstValue, lastValue); + getDimEdges(comboBoxDim1->currentText().toStdString(), size, firstValue, + lastValue); doubleSpinBoxDim1Start->setValue(firstValue); doubleSpinBoxDim1End->setValue(lastValue); doubleSpinBoxResolution->setValue(getResolution()); } -//set up y-axis/lon +// set up y-axis/lon void NetCdfConfigureDialog::on_comboBoxDim2_currentIndexChanged(int /*id*/) { if (_currentVar.getDimCount() > 1) { - double firstValue=0, lastValue=0; + double firstValue = 0, lastValue = 0; unsigned size = 0; - getDimEdges(comboBoxDim2->currentText().toStdString(), size, firstValue, lastValue); + getDimEdges(comboBoxDim2->currentText().toStdString(), size, firstValue, + lastValue); doubleSpinBoxDim2Start->setValue(firstValue); doubleSpinBoxDim2End->setValue(lastValue); } } -//set up time +// set up time void NetCdfConfigureDialog::on_comboBoxDim3_currentIndexChanged(int /*id*/) { if (_currentVar.getDimCount() > 2) { - double firstValue=0, lastValue=0; + double firstValue = 0, lastValue = 0; unsigned size = 0; - getDimEdges(comboBoxDim3->currentText().toStdString(), size, firstValue, lastValue); + getDimEdges(comboBoxDim3->currentText().toStdString(), size, firstValue, + lastValue); dateTimeEditDim3->setValue(static_cast<int>(firstValue)); dateTimeEditDim3->setMinimum(static_cast<int>(firstValue)); dateTimeEditDim3->setMaximum(static_cast<int>(lastValue)); @@ -117,14 +134,15 @@ void NetCdfConfigureDialog::on_comboBoxDim3_currentIndexChanged(int /*id*/) } } -//set up additional dimension +// set up additional dimension void NetCdfConfigureDialog::on_comboBoxDim4_currentIndexChanged(int /*id*/) { if (_currentVar.getDimCount() > 3) { - double firstValue=0, lastValue=0; + double firstValue = 0, lastValue = 0; unsigned size = 0; - getDimEdges(comboBoxDim4->currentText().toStdString(), size, firstValue, lastValue); + getDimEdges(comboBoxDim4->currentText().toStdString(), size, firstValue, + lastValue); spinBoxDim4->setValue(static_cast<int>(firstValue)); spinBoxDim4->setMinimum(static_cast<int>(firstValue)); spinBoxDim4->setMaximum(static_cast<int>(lastValue)); @@ -135,7 +153,7 @@ int NetCdfConfigureDialog::setVariableSelect() { int max_dim = 0; int max_dim_idx = 0; - auto const& names =_currentFile.getVars(); + auto const& names = _currentFile.getVars(); for (auto [name, var] : names) { int const var_dim_count = var.getDimCount(); @@ -155,7 +173,8 @@ int NetCdfConfigureDialog::setVariableSelect() void NetCdfConfigureDialog::setDimensionSelect() { int const dim_count = _currentVar.getDimCount(); - std::array<QComboBox*,4> dim_box = {{ comboBoxDim1, comboBoxDim2, comboBoxDim3, comboBoxDim4 }}; + std::array<QComboBox*, 4> dim_box = { + {comboBoxDim1, comboBoxDim2, comboBoxDim3, comboBoxDim4}}; for (int i = 0; i < 4; ++i) { @@ -168,7 +187,8 @@ void NetCdfConfigureDialog::setDimensionSelect() { for (int j = 0; j < dim_count; ++j) { - dim_box[j]->addItem(QString::fromStdString(_currentVar.getDim(i).getName())); + dim_box[j]->addItem( + QString::fromStdString(_currentVar.getDim(i).getName())); } } comboBoxDim1->setCurrentIndex(dim_count - 2); @@ -224,11 +244,13 @@ int NetCdfConfigureDialog::getDim4() const { NcVar const& dim3Var = _currentFile.getVar(comboBoxDim4->currentText().toStdString()); - std::vector<std::size_t> start{static_cast<std::size_t>(spinBoxDim4->value())}; + std::vector<std::size_t> start{ + static_cast<std::size_t>(spinBoxDim4->value())}; int value(0); dim3Var.getVar(start, {1}, &value); if (value < 0) - value = 0; //if the value isn't found in the array, set it to 0 as default... + value = 0; // if the value isn't found in the array, set it to 0 as + // default... return value; } @@ -236,7 +258,8 @@ double NetCdfConfigureDialog::getResolution() { if (comboBoxDim1->currentIndex() > -1) { - NcVar const& var = _currentFile.getVar(comboBoxDim1->currentText().toStdString()); + NcVar const& var = + _currentFile.getVar(comboBoxDim1->currentText().toStdString()); double firstValue = 0, lastValue = 0; unsigned size = 0; getDimEdges(var.getName(), size, firstValue, lastValue); @@ -282,8 +305,8 @@ void NetCdfConfigureDialog::createDataObject() } } - data_origin.push_back(0); // x-origin - data_origin.push_back(0); // y-origin + data_origin.push_back(0); // x-origin + data_origin.push_back(0); // y-origin data_length.push_back(sizeLat); data_length.push_back(sizeLon); _currentVar.getVar(data_origin, data_length, data_array.data()); @@ -294,10 +317,12 @@ void NetCdfConfigureDialog::createDataObject() double origin_x = (originLon < lastLon) ? originLon : lastLon; double origin_y = (originLat < lastLat) ? originLat : lastLat; - MathLib::Point3d origin(std::array<double,3>{{origin_x, origin_y, 0}}); + MathLib::Point3d origin(std::array<double, 3>{{origin_x, origin_y, 0}}); double resolution = (doubleSpinBoxResolution->value()); - if (originLat > lastLat) // reverse lines in vertical direction if the original file has its origin in the northwest corner + if (originLat > + lastLat) // reverse lines in vertical direction if the original file + // has its origin in the northwest corner this->reverseNorthSouth(data_array.data(), sizeLon, sizeLat); GeoLib::RasterHeader const header = {sizeLon, sizeLat, 1, @@ -305,27 +330,35 @@ void NetCdfConfigureDialog::createDataObject() if (this->radioMesh->isChecked()) { MeshLib::MeshElemType meshElemType = MeshLib::MeshElemType::QUAD; - MeshLib::UseIntensityAs useIntensity = MeshLib::UseIntensityAs::DATAVECTOR; + MeshLib::UseIntensityAs useIntensity = + MeshLib::UseIntensityAs::DATAVECTOR; if (comboBoxMeshElemType->currentIndex() == 1) { meshElemType = MeshLib::MeshElemType::TRIANGLE; - }else{ + } + else + { meshElemType = MeshLib::MeshElemType::QUAD; } if ((comboBoxUseIntensity->currentIndex()) == 1) { useIntensity = MeshLib::UseIntensityAs::ELEVATION; - }else{ + } + else + { useIntensity = MeshLib::UseIntensityAs::DATAVECTOR; } _currentMesh = MeshLib::RasterToMesh::convert( - data_array.data(), header, meshElemType, useIntensity, _currentVar.getName()); + data_array.data(), header, meshElemType, useIntensity, + _currentVar.getName()); } else { - vtkImageImport* image = VtkRaster::loadImageFromArray(data_array.data(), header); + vtkImageImport* image = + VtkRaster::loadImageFromArray(data_array.data(), header); _currentRaster = VtkGeoImageSource::New(); - _currentRaster->setImage(image, QString::fromStdString(this->getName())); + _currentRaster->setImage(image, + QString::fromStdString(this->getName())); } } @@ -333,7 +366,7 @@ QString NetCdfConfigureDialog::setName() { std::string name; name.append(_currentPath); - name.erase(0,name.find_last_of("/")+1); + name.erase(0, name.find_last_of("/") + 1); name.erase(name.find_last_of(".")); return QString::fromStdString(name); } @@ -346,22 +379,23 @@ std::string NetCdfConfigureDialog::getName() return name; } -void NetCdfConfigureDialog::reverseNorthSouth(double* data, std::size_t width, std::size_t height) +void NetCdfConfigureDialog::reverseNorthSouth(double* data, std::size_t width, + std::size_t height) { auto* cp_array = new double[width * height]; - for (std::size_t i=0; i<height; i++) + for (std::size_t i = 0; i < height; i++) { - for (std::size_t j=0; j<width; j++) + for (std::size_t j = 0; j < width; j++) { - std::size_t old_index((width*height)-(width*(i+1))); - std::size_t new_index(width*i); - cp_array[new_index+j] = data[old_index+j]; + std::size_t old_index((width * height) - (width * (i + 1))); + std::size_t new_index(width * i); + cp_array[new_index + j] = data[old_index + j]; } } - std::size_t length(height*width); - for (std::size_t i=0; i<length; i++) + std::size_t length(height * width); + for (std::size_t i = 0; i < length; i++) data[i] = cp_array[i]; delete[] cp_array; @@ -369,14 +403,14 @@ void NetCdfConfigureDialog::reverseNorthSouth(double* data, std::size_t width, s void NetCdfConfigureDialog::on_radioMesh_toggled(bool isTrue) { - if (isTrue) // output set to "mesh" + if (isTrue) // output set to "mesh" { this->label_2->setEnabled(true); this->label_3->setEnabled(false); this->comboBoxMeshElemType->setEnabled(true); this->comboBoxUseIntensity->setEnabled(false); } - else // output set to "raster" + else // output set to "raster" { this->label_2->setEnabled(false); this->label_3->setEnabled(true); diff --git a/Applications/DataExplorer/VtkVis/QVtkDataSetMapper.cpp b/Applications/DataExplorer/VtkVis/QVtkDataSetMapper.cpp index 2bb261e0c91114a79cf80432283cacf1646eb284..99130cb8f9429c07cf88305374c063800d9d7246 100644 --- a/Applications/DataExplorer/VtkVis/QVtkDataSetMapper.cpp +++ b/Applications/DataExplorer/VtkVis/QVtkDataSetMapper.cpp @@ -19,9 +19,7 @@ vtkStandardNewMacro(QVtkDataSetMapper); -QVtkDataSetMapper::QVtkDataSetMapper() : QObject(nullptr) -{ -} +QVtkDataSetMapper::QVtkDataSetMapper() : QObject(nullptr) {} QVtkDataSetMapper::~QVtkDataSetMapper() = default; @@ -30,8 +28,7 @@ void QVtkDataSetMapper::PrintSelf(ostream& os, vtkIndent indent) this->Superclass::PrintSelf(os, indent); } -void QVtkDataSetMapper::SetScalarVisibility( bool on ) +void QVtkDataSetMapper::SetScalarVisibility(bool on) { vtkDataSetMapper::SetScalarVisibility(static_cast<int>(on)); } - diff --git a/Applications/DataExplorer/VtkVis/VisPrefsDialog.cpp b/Applications/DataExplorer/VtkVis/VisPrefsDialog.cpp index 57d918b3f201b440bcfb1e769360b357a1dfb65a..60e37af110e860d2a42704f1f9b039a8eb4218ca 100644 --- a/Applications/DataExplorer/VtkVis/VisPrefsDialog.cpp +++ b/Applications/DataExplorer/VtkVis/VisPrefsDialog.cpp @@ -13,6 +13,7 @@ */ #include "VisPrefsDialog.h" + #include <QDoubleValidator> #include <QLineEdit> #include <QSettings> @@ -22,11 +23,14 @@ #include "VtkVisPipeline.h" /// Constructor -VisPrefsDialog::VisPrefsDialog(VtkVisPipeline &pipeline, - VisualizationWidget &widget, - QDialog* parent) : - QDialog(parent), _vtkVisPipeline(pipeline), _visWidget(widget), - _above(0,0,2000000), _below(0,0,-2000000) +VisPrefsDialog::VisPrefsDialog(VtkVisPipeline& pipeline, + VisualizationWidget& widget, + QDialog* parent) + : QDialog(parent), + _vtkVisPipeline(pipeline), + _visWidget(widget), + _above(0, 0, 2000000), + _below(0, 0, -2000000) { setupUi(this); if (_vtkVisPipeline.getLight(_above)) @@ -43,12 +47,15 @@ VisPrefsDialog::VisPrefsDialog(VtkVisPipeline &pipeline, QValidator* validator = new QDoubleValidator(0, 100000, 2, this); superelevationLineEdit->setValidator(validator); QSettings settings; - superelevationLineEdit->setText(settings.value("globalSuperelevation", 1.0).toString()); - cullBackfacesCheckBox->setCheckState(Qt::CheckState(settings.value("globalCullBackfaces", 0).toInt())); - loadShowAllCheckBox->setCheckState(Qt::CheckState(settings.value("resetViewOnLoad", 2).toInt())); + superelevationLineEdit->setText( + settings.value("globalSuperelevation", 1.0).toString()); + cullBackfacesCheckBox->setCheckState( + Qt::CheckState(settings.value("globalCullBackfaces", 0).toInt())); + loadShowAllCheckBox->setCheckState( + Qt::CheckState(settings.value("resetViewOnLoad", 2).toInt())); } -void VisPrefsDialog::on_bgColorButton_colorPicked( QColor color ) +void VisPrefsDialog::on_bgColorButton_colorPicked(QColor color) { QColor bgColor(color.red(), color.green(), color.blue()); _vtkVisPipeline.setBGColor(bgColor); @@ -103,4 +110,3 @@ void VisPrefsDialog::on_cullBackfacesCheckBox_stateChanged(int state) QSettings settings; settings.setValue("globalCullBackfaces", state); } - diff --git a/Applications/DataExplorer/VtkVis/VisualizationWidget.cpp b/Applications/DataExplorer/VtkVis/VisualizationWidget.cpp index 6d8901a99124a6bb7f6694b0d15410f7baea1c62..30a542e139ed1cf47a9eec08957bc5fb752a5e53 100644 --- a/Applications/DataExplorer/VtkVis/VisualizationWidget.cpp +++ b/Applications/DataExplorer/VtkVis/VisualizationWidget.cpp @@ -13,12 +13,7 @@ */ // ** INCLUDES ** -#include <cmath> - -#include "Point.h" #include "VisualizationWidget.h" -#include "VtkCustomInteractorStyle.h" -#include "VtkPickCallback.h" #include <vtkAxesActor.h> #include <vtkCamera.h> @@ -31,11 +26,9 @@ #include <vtkNew.h> #include <vtkOrientationMarkerWidget.h> #include <vtkPNGWriter.h> -#include <vtkRenderer.h> -#include <vtkRenderWindow.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> -#include <vtkSmartPointer.h> +#include <vtkRenderer.h> #include <vtkSmartPointer.h> #include <vtkWindowToImageFilter.h> @@ -46,6 +39,11 @@ #include <QLineEdit> #include <QSettings> #include <QString> +#include <cmath> + +#include "Point.h" +#include "VtkCustomInteractorStyle.h" +#include "VtkPickCallback.h" VisualizationWidget::VisualizationWidget(QWidget* parent /*= 0*/) : QWidget(parent) @@ -64,16 +62,18 @@ VisualizationWidget::VisualizationWidget(QWidget* parent /*= 0*/) _interactorStyle->SetDefaultRenderer(ren); _vtkPickCallback = VtkPickCallback::New(); - vtkSmartPointer<vtkCellPicker> picker = vtkSmartPointer<vtkCellPicker>::New(); + vtkSmartPointer<vtkCellPicker> picker = + vtkSmartPointer<vtkCellPicker>::New(); picker->AddObserver(vtkCommand::EndPickEvent, _vtkPickCallback); renderWindow->GetInteractor()->SetPicker(picker); QSettings settings; - ren->SetBackground(0.0,0.0,0.0); + ren->SetBackground(0.0, 0.0, 0.0); // Create an orientation marker using vtkAxesActor - vtkSmartPointer<vtkAxesActor> axesActor = vtkSmartPointer<vtkAxesActor>::New(); + vtkSmartPointer<vtkAxesActor> axesActor = + vtkSmartPointer<vtkAxesActor>::New(); _markerWidget = vtkOrientationMarkerWidget::New(); _markerWidget->SetOrientationMarker(axesActor); _markerWidget->SetInteractor(renderWindow->GetInteractor()); @@ -83,11 +83,11 @@ VisualizationWidget::VisualizationWidget(QWidget* parent /*= 0*/) _isShowAllOnLoad = settings.value("resetViewOnLoad", true).toBool(); // Set alternate cursor shapes - connect(_interactorStyle, SIGNAL(cursorChanged(Qt::CursorShape)), - this, SLOT(setCursorShape(Qt::CursorShape))); + connect(_interactorStyle, SIGNAL(cursorChanged(Qt::CursorShape)), this, + SLOT(setCursorShape(Qt::CursorShape))); - connect((QObject*)_interactorStyle, SIGNAL(requestViewUpdate()), - this, SLOT(updateView())); + connect((QObject*)_interactorStyle, SIGNAL(requestViewUpdate()), this, + SLOT(updateView())); } VisualizationWidget::~VisualizationWidget() @@ -122,7 +122,8 @@ void VisualizationWidget::showAll(int x, int y, int z) double* fp = cam->GetFocalPoint(); double* p = cam->GetPosition(); double dist = std::sqrt(vtkMath::Distance2BetweenPoints(p, fp)); - cam->SetPosition(fp[0]+(x*dist), fp[1]+(y*dist), fp[2]+(z*dist)); + cam->SetPosition(fp[0] + (x * dist), fp[1] + (y * dist), + fp[2] + (z * dist)); if (x != 0 || y != 0) { @@ -147,20 +148,22 @@ void VisualizationWidget::updateViewOnLoad() } } -void VisualizationWidget::on_zoomToolButton_toggled( bool checked ) +void VisualizationWidget::on_zoomToolButton_toggled(bool checked) { if (checked) { vtkSmartPointer<vtkInteractorStyleRubberBandZoom> interactorStyle = - vtkSmartPointer<vtkInteractorStyleRubberBandZoom>::New(); - vtkWidget->GetRenderWindow()->GetInteractor()->SetInteractorStyle(interactorStyle); + vtkSmartPointer<vtkInteractorStyleRubberBandZoom>::New(); + vtkWidget->GetRenderWindow()->GetInteractor()->SetInteractorStyle( + interactorStyle); QCursor cursor; cursor.setShape(Qt::CrossCursor); vtkWidget->setCursor(cursor); } else { - vtkWidget->GetRenderWindow()->GetInteractor()->SetInteractorStyle(_interactorStyle); + vtkWidget->GetRenderWindow()->GetInteractor()->SetInteractorStyle( + _interactorStyle); QCursor cursor; cursor.setShape(Qt::ArrowCursor); vtkWidget->setCursor(cursor); @@ -172,7 +175,8 @@ void VisualizationWidget::on_highlightToolButton_toggled(bool checked) _interactorStyle->setHighlightActor(checked); } -void VisualizationWidget::on_orthogonalProjectionToolButton_toggled( bool checked ) +void VisualizationWidget::on_orthogonalProjectionToolButton_toggled( + bool checked) { _vtkRender->GetActiveCamera()->SetParallelProjection(checked); this->updateView(); @@ -181,17 +185,16 @@ void VisualizationWidget::on_orthogonalProjectionToolButton_toggled( bool checke void VisualizationWidget::on_screenshotPushButton_pressed() { QSettings settings; - QString filename = QFileDialog::getSaveFileName(this, tr("Save screenshot"), - settings.value( - "lastScreenshotDir").toString(), - "PNG file (*.png)"); + QString filename = QFileDialog::getSaveFileName( + this, tr("Save screenshot"), + settings.value("lastScreenshotDir").toString(), "PNG file (*.png)"); if (filename.count() > 4) { bool ok; - int magnification = QInputDialog::getInt(this, tr("Screenshot magnification"), - tr( - "Enter a magnification factor for the resulting image."), - 2, 1, 10, 1, &ok); + int magnification = QInputDialog::getInt( + this, tr("Screenshot magnification"), + tr("Enter a magnification factor for the resulting image."), 2, 1, + 10, 1, &ok); if (ok) { QDir dir(filename); diff --git a/Applications/DataExplorer/VtkVis/VtkAddFilterDialog.cpp b/Applications/DataExplorer/VtkVis/VtkAddFilterDialog.cpp index 838e9938f6e72ceda1a215bab8641d96331759c0..07830e56bf2968ef12dfd74c957531108186d87a 100644 --- a/Applications/DataExplorer/VtkVis/VtkAddFilterDialog.cpp +++ b/Applications/DataExplorer/VtkVis/VtkAddFilterDialog.cpp @@ -15,8 +15,13 @@ // ** INCLUDES ** #include "VtkAddFilterDialog.h" -#include "BaseLib/Logging.h" +#include <vtkContourFilter.h> +#include <vtkOutlineFilter.h> +#include <vtkTransformFilter.h> +#include <QModelIndex> + +#include "BaseLib/Logging.h" #include "VtkCompositeFilter.h" #include "VtkFilterFactory.h" #include "VtkVisImageItem.h" @@ -24,15 +29,9 @@ #include "VtkVisPipelineItem.h" #include "VtkVisPointSetItem.h" -#include <vtkContourFilter.h> -#include <vtkOutlineFilter.h> -#include <vtkTransformFilter.h> - -#include <QModelIndex> - -VtkAddFilterDialog::VtkAddFilterDialog( VtkVisPipeline &pipeline, - QModelIndex parentIndex, - QDialog* parent /*= 0*/ ) +VtkAddFilterDialog::VtkAddFilterDialog(VtkVisPipeline& pipeline, + QModelIndex parentIndex, + QDialog* parent /*= 0*/) : QDialog(parent), _pipeline(pipeline), _parentIndex(parentIndex) { setupUi(this); @@ -40,11 +39,12 @@ VtkAddFilterDialog::VtkAddFilterDialog( VtkVisPipeline &pipeline, auto* parentItem = static_cast<VtkVisPipelineItem*>(_pipeline.getItem(parentIndex)); - vtkDataObject* parentDataObject = parentItem->algorithm()->GetOutputDataObject(0); + vtkDataObject* parentDataObject = + parentItem->algorithm()->GetOutputDataObject(0); int parentDataObjectType = parentDataObject->GetDataObjectType(); QVector<VtkFilterInfo> filterList = VtkFilterFactory::GetFilterList(); - foreach(VtkFilterInfo filter, filterList) + foreach (VtkFilterInfo filter, filterList) { // Check for suitable filters (see vtkDataSet inheritance diagram) int inputType = filter.inputDataObjectType; @@ -60,17 +60,18 @@ VtkAddFilterDialog::VtkAddFilterDialog( VtkVisPipeline &pipeline, } // On double clicking an item the dialog gets accepted - connect(filterListWidget,SIGNAL(itemDoubleClicked(QListWidgetItem*)), - this->buttonBox,SIGNAL(accepted())); + connect(filterListWidget, SIGNAL(itemDoubleClicked(QListWidgetItem*)), + this->buttonBox, SIGNAL(accepted())); } void VtkAddFilterDialog::on_buttonBox_accepted() { QVector<VtkFilterInfo> filterList = VtkFilterFactory::GetFilterList(); QString filterName; - foreach(VtkFilterInfo filter, filterList) + foreach (VtkFilterInfo filter, filterList) { - if (filter.readableName.compare(filterListWidget->currentItem()->text()) == 0) + if (filter.readableName.compare( + filterListWidget->currentItem()->text()) == 0) { filterName = filter.name; break; @@ -84,7 +85,8 @@ void VtkAddFilterDialog::on_buttonBox_accepted() VtkCompositeFilter* filter; if (dynamic_cast<VtkVisImageItem*>(parentItem)) { - filter = VtkFilterFactory::CreateCompositeFilter(filterName, parentItem->algorithm()); + filter = VtkFilterFactory::CreateCompositeFilter( + filterName, parentItem->algorithm()); } else { @@ -106,7 +108,8 @@ void VtkAddFilterDialog::on_buttonBox_accepted() } else { - vtkAlgorithm* algorithm = VtkFilterFactory::CreateSimpleFilter(filterName); + vtkAlgorithm* algorithm = + VtkFilterFactory::CreateSimpleFilter(filterName); if (algorithm) { item = new VtkVisPointSetItem(algorithm, parentItem, itemData); @@ -121,17 +124,17 @@ void VtkAddFilterDialog::on_buttonBox_accepted() _pipeline.addPipelineItem(item, _parentIndex); } -void VtkAddFilterDialog::on_filterListWidget_currentRowChanged( int currentRow ) +void VtkAddFilterDialog::on_filterListWidget_currentRowChanged(int currentRow) { - foreach(VtkFilterInfo filter, VtkFilterFactory::GetFilterList()) + foreach (VtkFilterInfo filter, VtkFilterFactory::GetFilterList()) { - if (filter.readableName.compare(filterListWidget->item(currentRow)->text()) == 0) + if (filter.readableName.compare( + filterListWidget->item(currentRow)->text()) == 0) { QString desc = filter.description; desc = desc + QString("\n\nThis filter outputs ") + filter.OutputDataObjectTypeAsString() + - QString("\n\nFilter class name: ") + - filter.name; + QString("\n\nFilter class name: ") + filter.name; this->filterDescTextEdit->setText(desc); continue; diff --git a/Applications/DataExplorer/VtkVis/VtkAlgorithmProperties.cpp b/Applications/DataExplorer/VtkVis/VtkAlgorithmProperties.cpp index 0e43c6f187c46a6c8c1cf77d0ab2f0a448234c4d..913745a747fdee077be7f33c96c514bc4a91d9f2 100644 --- a/Applications/DataExplorer/VtkVis/VtkAlgorithmProperties.cpp +++ b/Applications/DataExplorer/VtkVis/VtkAlgorithmProperties.cpp @@ -15,12 +15,11 @@ // ** INCLUDES ** #include "VtkAlgorithmProperties.h" -#include "BaseLib/Logging.h" - #include <vtkProperty.h> #include <vtkTexture.h> #include "Applications/DataHolderLib/ColorLookupTable.h" +#include "BaseLib/Logging.h" #include "VtkColorLookupTable.h" #include "XmlIO/Qt/XmlLutReader.h" @@ -28,10 +27,10 @@ VtkAlgorithmProperties::VtkAlgorithmProperties(QObject* parent /*= nullptr*/) : QObject(parent) { _property = vtkProperty::New(); - _texture = nullptr; + _texture = nullptr; _scalarVisibility = true; _algorithmUserProperties = new QMap<QString, QVariant>; - _algorithmUserVectorProperties = new QMap<QString, QList<QVariant> >; + _algorithmUserVectorProperties = new QMap<QString, QList<QVariant>>; _activeAttributeName = ""; _removable = true; } @@ -52,7 +51,8 @@ VtkAlgorithmProperties::~VtkAlgorithmProperties() delete _algorithmUserVectorProperties; } -vtkLookupTable* VtkAlgorithmProperties::GetLookupTable(const QString& array_name) +vtkLookupTable* VtkAlgorithmProperties::GetLookupTable( + const QString& array_name) { auto it = _lut.find(array_name); if (it != _lut.end()) @@ -73,19 +73,21 @@ void VtkAlgorithmProperties::RemoveLookupTable(const QString& array_name) } } -void VtkAlgorithmProperties::SetLookUpTable(const QString &array_name, vtkLookupTable* lut) +void VtkAlgorithmProperties::SetLookUpTable(const QString& array_name, + vtkLookupTable* lut) { lut->Build(); if (array_name.length() > 0) { this->RemoveLookupTable(array_name); - _lut.insert( std::pair<QString, vtkLookupTable*>(array_name, lut) ); + _lut.insert(std::pair<QString, vtkLookupTable*>(array_name, lut)); _activeAttributeName = array_name; } } -void VtkAlgorithmProperties::SetLookUpTable(const QString &array_name, const QString &filename) +void VtkAlgorithmProperties::SetLookUpTable(const QString& array_name, + const QString& filename) { DataHolderLib::ColorLookupTable lut; if (FileIO::XmlLutReader::readFromFile(filename, lut)) @@ -95,7 +97,7 @@ void VtkAlgorithmProperties::SetLookUpTable(const QString &array_name, const QSt SetLookUpTable(array_name, colorLookupTable); } else - ERR ("Error reading color look-up table."); + ERR("Error reading color look-up table."); } void VtkAlgorithmProperties::SetScalarVisibility(bool on) @@ -115,7 +117,8 @@ QVariant VtkAlgorithmProperties::GetUserProperty(QString name) const return QVariant(); } -QList<QVariant> VtkAlgorithmProperties::GetUserVectorProperty(QString name) const +QList<QVariant> VtkAlgorithmProperties::GetUserVectorProperty( + QString name) const { if (this->_algorithmUserVectorProperties->contains(name)) { diff --git a/Applications/DataExplorer/VtkVis/VtkAlgorithmPropertyCheckbox.cpp b/Applications/DataExplorer/VtkVis/VtkAlgorithmPropertyCheckbox.cpp index e20e6465f37eb5c82ecccb5db14c7e6e9552434f..7dec2be8f11afe6988ce8f3728ad19ece3910125 100644 --- a/Applications/DataExplorer/VtkVis/VtkAlgorithmPropertyCheckbox.cpp +++ b/Applications/DataExplorer/VtkVis/VtkAlgorithmPropertyCheckbox.cpp @@ -13,10 +13,10 @@ */ // ** INCLUDES ** -#include <utility> - #include "VtkAlgorithmPropertyCheckbox.h" +#include <utility> + #include "VtkAlgorithmProperties.h" VtkAlgorithmPropertyCheckbox::VtkAlgorithmPropertyCheckbox( @@ -32,7 +32,7 @@ VtkAlgorithmPropertyCheckbox::VtkAlgorithmPropertyCheckbox( VtkAlgorithmPropertyCheckbox::~VtkAlgorithmPropertyCheckbox() = default; -void VtkAlgorithmPropertyCheckbox::setNewValue( int state ) +void VtkAlgorithmPropertyCheckbox::setNewValue(int state) { auto boolState = static_cast<bool>(state); _algProps->SetUserProperty(_name, QVariant(boolState)); diff --git a/Applications/DataExplorer/VtkVis/VtkAlgorithmPropertyLineEdit.cpp b/Applications/DataExplorer/VtkVis/VtkAlgorithmPropertyLineEdit.cpp index 8d95745bb49215ed915f3e26ed107b7f4a52bccd..35eb3dbee48932cc60b70ba5078c5216313fb105 100644 --- a/Applications/DataExplorer/VtkVis/VtkAlgorithmPropertyLineEdit.cpp +++ b/Applications/DataExplorer/VtkVis/VtkAlgorithmPropertyLineEdit.cpp @@ -15,12 +15,12 @@ // ** INCLUDES ** #include "VtkAlgorithmPropertyLineEdit.h" -#include "VtkAlgorithmProperties.h" - #include <QDoubleValidator> #include <QIntValidator> #include <utility> +#include "VtkAlgorithmProperties.h" + VtkAlgorithmPropertyLineEdit::VtkAlgorithmPropertyLineEdit( const QString& contents, QString name, @@ -32,18 +32,18 @@ VtkAlgorithmPropertyLineEdit::VtkAlgorithmPropertyLineEdit( _algProps(algProps), _type(type) { - switch(_type) + switch (_type) { - case QVariant::Double: - this->setValidator(new QDoubleValidator(this)); - break; + case QVariant::Double: + this->setValidator(new QDoubleValidator(this)); + break; - case QVariant::Int: - this->setValidator(new QIntValidator(this)); - break; + case QVariant::Int: + this->setValidator(new QIntValidator(this)); + break; - default: - break; + default: + break; } connect(this, SIGNAL(editingFinished()), this, SLOT(setNewValue())); diff --git a/Applications/DataExplorer/VtkVis/VtkAlgorithmPropertyVectorEdit.cpp b/Applications/DataExplorer/VtkVis/VtkAlgorithmPropertyVectorEdit.cpp index 1d58e2306072c321b00958f518079b566843b00a..a14afbe806b83017ea7b013ecae2fbad17da84bb 100644 --- a/Applications/DataExplorer/VtkVis/VtkAlgorithmPropertyVectorEdit.cpp +++ b/Applications/DataExplorer/VtkVis/VtkAlgorithmPropertyVectorEdit.cpp @@ -15,8 +15,6 @@ // ** INCLUDES ** #include "VtkAlgorithmPropertyVectorEdit.h" -#include "VtkAlgorithmProperties.h" - #include <QDoubleValidator> #include <QHBoxLayout> #include <QIntValidator> @@ -24,6 +22,8 @@ #include <QSize> #include <utility> +#include "VtkAlgorithmProperties.h" + VtkAlgorithmPropertyVectorEdit::VtkAlgorithmPropertyVectorEdit( const QList<QString> contents, QString name, @@ -36,23 +36,23 @@ VtkAlgorithmPropertyVectorEdit::VtkAlgorithmPropertyVectorEdit( layout->setSpacing(3); layout->setContentsMargins(0, 0, 0, 0); - foreach(QString content, contents) + foreach (QString content, contents) { auto* lineEdit = new QLineEdit(content, this); layout->addWidget(lineEdit); - switch(_type) + switch (_type) { - case QVariant::Double: - lineEdit->setValidator(new QDoubleValidator(this)); - break; + case QVariant::Double: + lineEdit->setValidator(new QDoubleValidator(this)); + break; - case QVariant::Int: - lineEdit->setValidator(new QIntValidator(this)); - break; + case QVariant::Int: + lineEdit->setValidator(new QIntValidator(this)); + break; - default: - break; + default: + break; } connect(lineEdit, SIGNAL(editingFinished()), this, SLOT(setNewValue())); diff --git a/Applications/DataExplorer/VtkVis/VtkAppendArrayFilter.cpp b/Applications/DataExplorer/VtkVis/VtkAppendArrayFilter.cpp index 70d6fad5a6102a516ffbcb390c07006aaa2cd0d0..f223d600066e2e17a6ec74c7a8d242b836a263f8 100644 --- a/Applications/DataExplorer/VtkVis/VtkAppendArrayFilter.cpp +++ b/Applications/DataExplorer/VtkVis/VtkAppendArrayFilter.cpp @@ -15,8 +15,6 @@ // ** VTK INCLUDES ** #include "VtkAppendArrayFilter.h" -#include "BaseLib/Logging.h" - #include <vtkCellData.h> #include <vtkDoubleArray.h> #include <vtkInformation.h> @@ -27,15 +25,17 @@ #include <vtkStreamingDemandDrivenPipeline.h> #include <vtkUnstructuredGrid.h> +#include "BaseLib/Logging.h" + vtkStandardNewMacro(VtkAppendArrayFilter); VtkAppendArrayFilter::VtkAppendArrayFilter() = default; VtkAppendArrayFilter::~VtkAppendArrayFilter() = default; -void VtkAppendArrayFilter::PrintSelf( ostream& os, vtkIndent indent ) +void VtkAppendArrayFilter::PrintSelf(ostream& os, vtkIndent indent) { - this->Superclass::PrintSelf(os,indent); + this->Superclass::PrintSelf(os, indent); os << indent << "== VtkAppendArrayFilter ==" << endl; } @@ -49,10 +49,11 @@ int VtkAppendArrayFilter::RequestData(vtkInformation* /*request*/, return 0; } vtkInformation* inInfo = inputVector[0]->GetInformationObject(0); - vtkUnstructuredGrid* input = - vtkUnstructuredGrid::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT())); + vtkUnstructuredGrid* input = vtkUnstructuredGrid::SafeDownCast( + inInfo->Get(vtkDataObject::DATA_OBJECT())); - vtkSmartPointer<vtkDoubleArray> colors = vtkSmartPointer<vtkDoubleArray>::New(); + vtkSmartPointer<vtkDoubleArray> colors = + vtkSmartPointer<vtkDoubleArray>::New(); colors->SetNumberOfComponents(1); std::size_t arrayLength = this->_array.size(); colors->SetNumberOfValues(arrayLength); @@ -60,7 +61,9 @@ int VtkAppendArrayFilter::RequestData(vtkInformation* /*request*/, std::size_t nCells = input->GetNumberOfCells(); if (nCells > arrayLength) - WARN("VtkAppendArrayFilter::RequestData(): Number of cells exceeds selection array length. Surplus cells won't be examined."); + WARN( + "VtkAppendArrayFilter::RequestData(): Number of cells exceeds " + "selection array length. Surplus cells won't be examined."); for (std::size_t i = 0; i < arrayLength; i++) { @@ -68,8 +71,8 @@ int VtkAppendArrayFilter::RequestData(vtkInformation* /*request*/, } vtkInformation* outInfo = outputVector->GetInformationObject(0); - vtkUnstructuredGrid* output = - vtkUnstructuredGrid::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); + vtkUnstructuredGrid* output = vtkUnstructuredGrid::SafeDownCast( + outInfo->Get(vtkDataObject::DATA_OBJECT())); output->CopyStructure(input); output->GetPointData()->PassData(input->GetPointData()); output->GetCellData()->PassData(input->GetCellData()); @@ -79,8 +82,8 @@ int VtkAppendArrayFilter::RequestData(vtkInformation* /*request*/, return 1; } -void VtkAppendArrayFilter::SetArray(const std::string &array_name, - const std::vector<double> &new_array) +void VtkAppendArrayFilter::SetArray(const std::string& array_name, + const std::vector<double>& new_array) { this->_array_name = array_name; this->_array = new_array; diff --git a/Applications/DataExplorer/VtkVis/VtkBGImageSource.cpp b/Applications/DataExplorer/VtkVis/VtkBGImageSource.cpp index 781a45a5545451dffcc4ceca52028ee907dc0d16..ec997ed8cbfaa18d66f2a2c9d1435d517db10b63 100644 --- a/Applications/DataExplorer/VtkVis/VtkBGImageSource.cpp +++ b/Applications/DataExplorer/VtkVis/VtkBGImageSource.cpp @@ -14,34 +14,37 @@ // ** INCLUDES ** #include "VtkBGImageSource.h" -#include "VtkVisHelper.h" #include <vtkImageAlgorithm.h> -#include <vtkObjectFactory.h> +#include <vtkImageData.h> +#include <vtkImageShiftScale.h> #include <vtkInformation.h> #include <vtkInformationVector.h> +#include <vtkObjectFactory.h> #include <vtkPlaneSource.h> +#include <vtkPointData.h> #include <vtkSmartPointer.h> #include <vtkStreamingDemandDrivenPipeline.h> #include <vtkTexture.h> -#include <vtkImageData.h> -#include <vtkPointData.h> -#include <vtkImageShiftScale.h> + +#include "VtkVisHelper.h" vtkStandardNewMacro(VtkBGImageSource); VtkBGImageSource::VtkBGImageSource() = default; VtkBGImageSource::~VtkBGImageSource() = default; -void VtkBGImageSource::SetRaster(vtkImageAlgorithm *img, double x0, double y0, double scalingFactor) +void VtkBGImageSource::SetRaster(vtkImageAlgorithm* img, double x0, double y0, + double scalingFactor) { double range[2]; img->Update(); img->GetOutput()->GetPointData()->GetScalars()->GetRange(range); - vtkSmartPointer<vtkImageShiftScale> scale = vtkSmartPointer<vtkImageShiftScale>::New(); + vtkSmartPointer<vtkImageShiftScale> scale = + vtkSmartPointer<vtkImageShiftScale>::New(); scale->SetInputConnection(img->GetOutputPort()); scale->SetShift(-range[0]); - scale->SetScale(255.0/(range[1]-range[0])); + scale->SetScale(255.0 / (range[1] - range[0])); scale->SetOutputScalarTypeToUnsignedChar(); scale->Update(); @@ -55,20 +58,21 @@ void VtkBGImageSource::SetRaster(vtkImageAlgorithm *img, double x0, double y0, d texture->SetInputData(imageData); this->SetTexture(texture); - _origin = std::pair<float, float>(static_cast<float>(x0), static_cast<float>(y0)); + _origin = + std::pair<float, float>(static_cast<float>(x0), static_cast<float>(y0)); _cellsize = scalingFactor; - - vtkSmartPointer<vtkPlaneSource> plane = vtkSmartPointer<vtkPlaneSource>::New(); - plane->SetOrigin( _origin.first, _origin.second, -1 ); - plane->SetPoint1( _origin.first + dims[0] * _cellsize, _origin.second, -1 ); - plane->SetPoint2( _origin.first,_origin.second + dims[1] * _cellsize, -1 ); + vtkSmartPointer<vtkPlaneSource> plane = + vtkSmartPointer<vtkPlaneSource>::New(); + plane->SetOrigin(_origin.first, _origin.second, -1); + plane->SetPoint1(_origin.first + dims[0] * _cellsize, _origin.second, -1); + plane->SetPoint2(_origin.first, _origin.second + dims[1] * _cellsize, -1); this->SetInputConnection(0, plane->GetOutputPort(0)); this->SetTexture(texture); } -void VtkBGImageSource::SetUserProperty( QString name, QVariant value ) +void VtkBGImageSource::SetUserProperty(QString name, QVariant value) { VtkAlgorithmProperties::SetUserProperty(name, value); } diff --git a/Applications/DataExplorer/VtkVis/VtkColorByHeightFilter.cpp b/Applications/DataExplorer/VtkVis/VtkColorByHeightFilter.cpp index 02f6381abe2d7d97666ce73d11f310c2938e5288..954b4e7518b3dc7826168e5491beac2a9cde0c79 100644 --- a/Applications/DataExplorer/VtkVis/VtkColorByHeightFilter.cpp +++ b/Applications/DataExplorer/VtkVis/VtkColorByHeightFilter.cpp @@ -15,10 +15,6 @@ // ** VTK INCLUDES ** #include "VtkColorByHeightFilter.h" -#include "BaseLib/Logging.h" - -#include "VtkColorLookupTable.h" - #include <vtkCellData.h> #include <vtkDoubleArray.h> #include <vtkInformation.h> @@ -30,6 +26,9 @@ #include <vtkSmartPointer.h> #include <vtkStreamingDemandDrivenPipeline.h> +#include "BaseLib/Logging.h" +#include "VtkColorLookupTable.h" + vtkStandardNewMacro(VtkColorByHeightFilter); VtkColorByHeightFilter::VtkColorByHeightFilter() @@ -39,15 +38,16 @@ VtkColorByHeightFilter::VtkColorByHeightFilter() VtkColorByHeightFilter::~VtkColorByHeightFilter() = default; -void VtkColorByHeightFilter::PrintSelf( ostream& os, vtkIndent indent ) +void VtkColorByHeightFilter::PrintSelf(ostream& os, vtkIndent indent) { - this->Superclass::PrintSelf(os,indent); + this->Superclass::PrintSelf(os, indent); double range[2]; ColorLookupTable->GetTableRange(range); os << indent << "== VtkColorByHeightFilter ==" << endl; os << indent << "Range: " << range[0] << "-" << range[1] << endl; - os << indent << "Interpolation Type:" << static_cast<int>(ColorLookupTable->getInterpolationType()) << endl; + os << indent << "Interpolation Type:" + << static_cast<int>(ColorLookupTable->getInterpolationType()) << endl; } vtkMTimeType VtkColorByHeightFilter::GetMTime() @@ -65,9 +65,11 @@ int VtkColorByHeightFilter::RequestData(vtkInformation* /*request*/, vtkInformationVector* outputVector) { vtkInformation* inInfo = inputVector[0]->GetInformationObject(0); - vtkPolyData* input = vtkPolyData::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT())); + vtkPolyData* input = + vtkPolyData::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT())); - vtkSmartPointer<vtkDoubleArray> colors = vtkSmartPointer<vtkDoubleArray>::New(); + vtkSmartPointer<vtkDoubleArray> colors = + vtkSmartPointer<vtkDoubleArray>::New(); colors->SetNumberOfComponents(1); std::size_t nPoints = input->GetNumberOfPoints(); colors->SetNumberOfValues(nPoints); @@ -77,12 +79,13 @@ int VtkColorByHeightFilter::RequestData(vtkInformation* /*request*/, for (std::size_t i = 0; i < nPoints; i++) { double p[3]; - input->GetPoint(i,p); + input->GetPoint(i, p); colors->SetValue(i, p[2]); } vtkInformation* outInfo = outputVector->GetInformationObject(0); - vtkPolyData* output = vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); + vtkPolyData* output = + vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); output->CopyStructure(input); output->GetPointData()->PassData(input->GetPointData()); output->GetCellData()->PassData(input->GetCellData()); @@ -110,6 +113,6 @@ void VtkColorByHeightFilter::SetTableRange(double min, double max) void VtkColorByHeightFilter::SetTableRangeScaling(double scale) { this->_tableRangeScaling = scale; - this->ColorLookupTable->SetTableRange( - this->_tableRange[0] * scale, this->_tableRange[1] * scale); + this->ColorLookupTable->SetTableRange(this->_tableRange[0] * scale, + this->_tableRange[1] * scale); } diff --git a/Applications/DataExplorer/VtkVis/VtkColorLookupTable.cpp b/Applications/DataExplorer/VtkVis/VtkColorLookupTable.cpp index e6d91251af1f9a96656229e1e9d7fb7c09fdbcbb..c8f325cff9321c85897c0db0cc7a3336f4736ade 100644 --- a/Applications/DataExplorer/VtkVis/VtkColorLookupTable.cpp +++ b/Applications/DataExplorer/VtkVis/VtkColorLookupTable.cpp @@ -14,14 +14,13 @@ #include "VtkColorLookupTable.h" +#include <vtkObjectFactory.h> + #include <cmath> #include <sstream> -#include "BaseLib/Logging.h" - -#include <vtkObjectFactory.h> - #include "Applications/DataHolderLib/Color.h" +#include "BaseLib/Logging.h" vtkStandardNewMacro(VtkColorLookupTable); @@ -35,7 +34,8 @@ VtkColorLookupTable::~VtkColorLookupTable() } } -unsigned char VtkColorLookupTable::linInterpolation(unsigned char a, unsigned char b, +unsigned char VtkColorLookupTable::linInterpolation(unsigned char a, + unsigned char b, double p) const { return static_cast<unsigned char>(a * (1 - p) + b * p); @@ -46,21 +46,22 @@ unsigned char VtkColorLookupTable::expInterpolation(unsigned char a, double gamma, double p) const { - assert (gamma > 0 && gamma < 4); - return static_cast<unsigned char>((b - a) * pow(p,gamma) + a); + assert(gamma > 0 && gamma < 4); + return static_cast<unsigned char>((b - a) * pow(p, gamma) + a); } void VtkColorLookupTable::Build() { double range[2]; this->GetTableRange(range); - const double interval = range[1]-range[0]; - this->SetNumberOfTableValues(static_cast<vtkIdType>(ceil(interval))+1); -// const vtkIdType nColours = this->GetNumberOfTableValues(); + const double interval = range[1] - range[0]; + this->SetNumberOfTableValues(static_cast<vtkIdType>(ceil(interval)) + 1); + // const vtkIdType nColours = this->GetNumberOfTableValues(); if (!_dict.empty()) { - // make sure that color map starts with the first color in the dictionary - unsigned char startcolor[4] = { 0, 0 , 0 , 0 }; + // make sure that color map starts with the first color in the + // dictionary + unsigned char startcolor[4] = {0, 0, 0, 0}; std::pair<std::size_t, unsigned char*> lastValue(0, startcolor); for (auto& it : _dict) @@ -121,31 +122,33 @@ void VtkColorLookupTable::Build() } } -void VtkColorLookupTable::setLookupTable(DataHolderLib::ColorLookupTable const& lut) +void VtkColorLookupTable::setLookupTable( + DataHolderLib::ColorLookupTable const& lut) { - std::size_t const n_colors (lut.size()); + std::size_t const n_colors(lut.size()); for (std::size_t i = 0; i < n_colors; ++i) { setColor(std::get<0>(lut[i]), std::get<1>(lut[i])); } setInterpolationType(lut.getInterpolationType()); - auto const range (lut.getTableRange()); + auto const range(lut.getTableRange()); SetTableRange(range.first, range.second); Build(); } -void VtkColorLookupTable::writeToFile(const std::string &filename) +void VtkColorLookupTable::writeToFile(const std::string& filename) { std::stringstream strout; strout << "Writing color table to " << filename << " ... "; - std::ofstream out( filename.c_str(), std::ios::out ); + std::ofstream out(filename.c_str(), std::ios::out); std::size_t nColors = this->GetNumberOfTableValues(); for (std::size_t i = 0; i < nColors; i++) { unsigned char rgba[4]; this->GetTableValue(i, rgba); - out << i << "\t" << rgba[0] << "\t" << rgba[1] << "\t" << rgba[2] << "\n"; + out << i << "\t" << rgba[0] << "\t" << rgba[1] << "\t" << rgba[2] + << "\n"; } strout << " done." << std::endl; @@ -153,7 +156,8 @@ void VtkColorLookupTable::writeToFile(const std::string &filename) out.close(); } -void VtkColorLookupTable::SetTableValueRGBA(vtkIdType idx, unsigned char rgba[4]) +void VtkColorLookupTable::SetTableValueRGBA(vtkIdType idx, + unsigned char rgba[4]) { double value[4]; @@ -175,25 +179,27 @@ void VtkColorLookupTable::GetTableValue(vtkIdType idx, unsigned char rgba[4]) } } -void VtkColorLookupTable::setColor(double pos, DataHolderLib::Color const& color) +void VtkColorLookupTable::setColor(double pos, + DataHolderLib::Color const& color) { auto* dict_rgba = new unsigned char[4]; for (std::size_t i = 0; i < 4; i++) { dict_rgba[i] = color[i]; } - _dict.insert( std::pair<double, unsigned char*>(pos, dict_rgba) ); + _dict.insert(std::pair<double, unsigned char*>(pos, dict_rgba)); } void VtkColorLookupTable::getColor(vtkIdType indx, unsigned char rgba[4]) const { - indx = - ((indx < this->TableRange[0]) + indx = ((indx < this->TableRange[0]) ? static_cast<vtkIdType>(this->TableRange[0]) - : (indx >=this->TableRange[1] ? static_cast<vtkIdType>(this->TableRange[1]) - 1 : indx)); - indx = - static_cast<std::size_t>( std::floor( (indx - this->TableRange[0]) * - (this->NumberOfColors / (this->TableRange[1] - this->TableRange[0])) ) ); + : (indx >= this->TableRange[1] + ? static_cast<vtkIdType>(this->TableRange[1]) - 1 + : indx)); + indx = static_cast<std::size_t>(std::floor( + (indx - this->TableRange[0]) * + (this->NumberOfColors / (this->TableRange[1] - this->TableRange[0])))); unsigned char* _rgba; _rgba = this->Table->GetPointer(indx * 4); diff --git a/Applications/DataExplorer/VtkVis/VtkCompositeColorByHeightFilter.cpp b/Applications/DataExplorer/VtkVis/VtkCompositeColorByHeightFilter.cpp index a54409efd0d85f16f43f811edec92a606fc1ee20..c238e9062364fcda16ccbb7cda946222b4689a1e 100644 --- a/Applications/DataExplorer/VtkVis/VtkCompositeColorByHeightFilter.cpp +++ b/Applications/DataExplorer/VtkVis/VtkCompositeColorByHeightFilter.cpp @@ -13,15 +13,17 @@ */ // ** INCLUDES ** -#include "VtkColorByHeightFilter.h" -#include "VtkColorLookupTable.h" #include "VtkCompositeColorByHeightFilter.h" #include <vtkDataSetSurfaceFilter.h> #include <vtkSmartPointer.h> #include <vtkUnstructuredGrid.h> -VtkCompositeColorByHeightFilter::VtkCompositeColorByHeightFilter( vtkAlgorithm* inputAlgorithm ) +#include "VtkColorByHeightFilter.h" +#include "VtkColorLookupTable.h" + +VtkCompositeColorByHeightFilter::VtkCompositeColorByHeightFilter( + vtkAlgorithm* inputAlgorithm) : VtkCompositeFilter(inputAlgorithm) { this->init(); @@ -35,7 +37,8 @@ void VtkCompositeColorByHeightFilter::init() vtkSmartPointer<vtkDataSetSurfaceFilter> surfaceFilter; VtkColorByHeightFilter* heightFilter = VtkColorByHeightFilter::New(); - if (dynamic_cast<vtkUnstructuredGrid*>(_inputAlgorithm->GetOutputDataObject(0))) + if (dynamic_cast<vtkUnstructuredGrid*>( + _inputAlgorithm->GetOutputDataObject(0))) { surfaceFilter = vtkSmartPointer<vtkDataSetSurfaceFilter>::New(); surfaceFilter->SetInputConnection(_inputAlgorithm->GetOutputPort()); @@ -46,18 +49,19 @@ void VtkCompositeColorByHeightFilter::init() heightFilter->SetInputConnection(_inputAlgorithm->GetOutputPort()); } - DataHolderLib::Color a{{0, 0, 255, 255}}; // blue - DataHolderLib::Color b{{0, 255, 0, 255}}; // green - DataHolderLib::Color c{{255, 255, 0, 255}}; // yellow - DataHolderLib::Color d{{155, 100, 50, 255}}; // brown - DataHolderLib::Color e{{255, 0, 0, 255}}; // red + DataHolderLib::Color a{{0, 0, 255, 255}}; // blue + DataHolderLib::Color b{{0, 255, 0, 255}}; // green + DataHolderLib::Color c{{255, 255, 0, 255}}; // yellow + DataHolderLib::Color d{{155, 100, 50, 255}}; // brown + DataHolderLib::Color e{{255, 0, 0, 255}}; // red VtkColorLookupTable* ColorLookupTable = heightFilter->GetColorLookupTable(); ColorLookupTable->setInterpolationType(DataHolderLib::LUTType::LINEAR); ColorLookupTable->setColor(-50, a); ColorLookupTable->setColor(0, a); - ColorLookupTable->setColor(1, b); // instant change at 0m a.s.l. - ColorLookupTable->setColor(200, b); // green at about 200m a.s.l. - ColorLookupTable->setColor(500, c); // yellow at about 500m and changing to red from then on + ColorLookupTable->setColor(1, b); // instant change at 0m a.s.l. + ColorLookupTable->setColor(200, b); // green at about 200m a.s.l. + ColorLookupTable->setColor( + 500, c); // yellow at about 500m and changing to red from then on ColorLookupTable->setColor(1000, d); ColorLookupTable->setColor(2000, e); ColorLookupTable->SetTableRange(-35, 2000); @@ -71,7 +75,8 @@ void VtkCompositeColorByHeightFilter::init() _activeAttributeName = heightFilter->GetActiveAttribute(); } -void VtkCompositeColorByHeightFilter::SetUserProperty( QString name, QVariant value ) +void VtkCompositeColorByHeightFilter::SetUserProperty(QString name, + QVariant value) { Q_UNUSED(name); Q_UNUSED(value); diff --git a/Applications/DataExplorer/VtkVis/VtkCompositeColormapToImageFilter.cpp b/Applications/DataExplorer/VtkVis/VtkCompositeColormapToImageFilter.cpp index c87ad34279c3181f23da8fcafebf415424e4baa8..1298484a2066810a57a6b8f05fdfe192adf43a21 100644 --- a/Applications/DataExplorer/VtkVis/VtkCompositeColormapToImageFilter.cpp +++ b/Applications/DataExplorer/VtkVis/VtkCompositeColormapToImageFilter.cpp @@ -15,19 +15,20 @@ // ** INCLUDES ** #include "VtkCompositeColormapToImageFilter.h" -#include <vtkImageMapToColors.h> #include <vtkImageData.h> +#include <vtkImageMapToColors.h> #include <vtkLookupTable.h> #include <vtkPointData.h> #include <vtkSmartPointer.h> -#include <QSettings> #include <QFileDialog> +#include <QSettings> #include "VtkColorLookupTable.h" #include "XmlIO/Qt/XmlLutReader.h" -VtkCompositeColormapToImageFilter::VtkCompositeColormapToImageFilter( vtkAlgorithm* inputAlgorithm ) +VtkCompositeColormapToImageFilter::VtkCompositeColormapToImageFilter( + vtkAlgorithm* inputAlgorithm) : VtkCompositeFilter(inputAlgorithm) { this->init(); @@ -41,15 +42,21 @@ void VtkCompositeColormapToImageFilter::init() this->_inputDataObjectType = VTK_IMAGE_DATA; this->_outputDataObjectType = VTK_IMAGE_DATA; - vtkSmartPointer<VtkColorLookupTable> colormap = vtkSmartPointer<VtkColorLookupTable>::New(); + vtkSmartPointer<VtkColorLookupTable> colormap = + vtkSmartPointer<VtkColorLookupTable>::New(); QWidget* parent = nullptr; QSettings settings; - QString fileName = QFileDialog::getOpenFileName(parent, "Select color lookup table", - settings.value("lastOpenedLookupTableFileDirectory").toString(), - "Lookup table XML files (*.xml);;"); + QString fileName = QFileDialog::getOpenFileName( + parent, "Select color lookup table", + settings.value("lastOpenedLookupTableFileDirectory").toString(), + "Lookup table XML files (*.xml);;"); double range[2]; - dynamic_cast<vtkImageAlgorithm*>(_inputAlgorithm)->GetOutput()->GetPointData()->GetScalars()->GetRange(range); + dynamic_cast<vtkImageAlgorithm*>(_inputAlgorithm) + ->GetOutput() + ->GetPointData() + ->GetScalars() + ->GetRange(range); DataHolderLib::ColorLookupTable lut; if (FileIO::XmlLutReader::readFromFile(fileName, lut)) @@ -85,7 +92,8 @@ void VtkCompositeColormapToImageFilter::init() _outputAlgorithm = map; } -void VtkCompositeColormapToImageFilter::SetUserProperty( QString name, QVariant value ) +void VtkCompositeColormapToImageFilter::SetUserProperty(QString name, + QVariant value) { VtkAlgorithmProperties::SetUserProperty(name, value); @@ -101,15 +109,16 @@ void VtkCompositeColormapToImageFilter::SetUserProperty( QString name, QVariant } } -void VtkCompositeColormapToImageFilter::SetUserVectorProperty( QString name, QList<QVariant> values ) +void VtkCompositeColormapToImageFilter::SetUserVectorProperty( + QString name, QList<QVariant> values) { VtkAlgorithmProperties::SetUserVectorProperty(name, values); auto* map = static_cast<vtkImageMapToColors*>(_outputAlgorithm); if (name.compare("TableRange") == 0) { - static_cast<vtkLookupTable*>(map->GetLookupTable())->SetTableRange( - values[0].toInt(), values[1].toInt()); + static_cast<vtkLookupTable*>(map->GetLookupTable()) + ->SetTableRange(values[0].toInt(), values[1].toInt()); } else if (name.compare("HueRange") == 0) { diff --git a/Applications/DataExplorer/VtkVis/VtkCompositeContourFilter.cpp b/Applications/DataExplorer/VtkVis/VtkCompositeContourFilter.cpp index 8d99aa11dd0b0b48808c9121d6e79fa92ed10e0b..bdff7ff68e11128b8053a47547ec87440aa318c3 100644 --- a/Applications/DataExplorer/VtkVis/VtkCompositeContourFilter.cpp +++ b/Applications/DataExplorer/VtkVis/VtkCompositeContourFilter.cpp @@ -15,14 +15,15 @@ // ** INCLUDES ** #include "VtkCompositeContourFilter.h" -#include <vtkPointData.h> #include <vtkContourFilter.h> +#include <vtkPointData.h> #include <vtkSmartPointer.h> #include <vtkUnstructuredGrid.h> #include <limits> -VtkCompositeContourFilter::VtkCompositeContourFilter( vtkAlgorithm* inputAlgorithm ) +VtkCompositeContourFilter::VtkCompositeContourFilter( + vtkAlgorithm* inputAlgorithm) : VtkCompositeFilter(inputAlgorithm) { this->init(); @@ -33,18 +34,19 @@ VtkCompositeContourFilter::~VtkCompositeContourFilter() = default; void VtkCompositeContourFilter::init() { // Set meta information about input and output data types - this->_inputDataObjectType = VTK_UNSTRUCTURED_GRID; //VTK_DATA_SET; + this->_inputDataObjectType = VTK_UNSTRUCTURED_GRID; // VTK_DATA_SET; this->_outputDataObjectType = VTK_UNSTRUCTURED_GRID; // Because this is the only filter here we cannot use vtkSmartPointer vtkContourFilter* contour = vtkContourFilter::New(); contour->SetInputConnection(_inputAlgorithm->GetOutputPort()); - // Getting the scalar range from the active point data scalar of the input algorithm - // This assumes that we do not want to contour on cell data. + // Getting the scalar range from the active point data scalar of the input + // algorithm This assumes that we do not want to contour on cell data. double range[2]; - vtkDataSet* dataSet = vtkDataSet::SafeDownCast(_inputAlgorithm->GetOutputDataObject(0)); - if(dataSet) + vtkDataSet* dataSet = + vtkDataSet::SafeDownCast(_inputAlgorithm->GetOutputDataObject(0)); + if (dataSet) { vtkPointData* pointData = dataSet->GetPointData(); if (pointData) @@ -54,8 +56,8 @@ void VtkCompositeContourFilter::init() } else { - // Setting the range to min / max values, this will result in a "bad table range" - // vtk warning. + // Setting the range to min / max values, this will result in a "bad + // table range" vtk warning. range[0] = std::numeric_limits<double>::lowest(); range[1] = std::numeric_limits<double>::max(); } @@ -78,7 +80,7 @@ void VtkCompositeContourFilter::init() _outputAlgorithm = contour; } -void VtkCompositeContourFilter::SetUserProperty( QString name, QVariant value ) +void VtkCompositeContourFilter::SetUserProperty(QString name, QVariant value) { VtkAlgorithmProperties::SetUserProperty(name, value); @@ -90,7 +92,8 @@ void VtkCompositeContourFilter::SetUserProperty( QString name, QVariant value ) } } -void VtkCompositeContourFilter::SetUserVectorProperty( QString name, QList<QVariant> values ) +void VtkCompositeContourFilter::SetUserVectorProperty( + QString name, QList<QVariant> values) { VtkAlgorithmProperties::SetUserVectorProperty(name, values); diff --git a/Applications/DataExplorer/VtkVis/VtkCompositeElementSelectionFilter.cpp b/Applications/DataExplorer/VtkVis/VtkCompositeElementSelectionFilter.cpp index bb1ac6d1e2ae16b249d1413b728723ba24ff56eb..179fbe8f737286e74f74ca620ada467a86db26c9 100644 --- a/Applications/DataExplorer/VtkVis/VtkCompositeElementSelectionFilter.cpp +++ b/Applications/DataExplorer/VtkVis/VtkCompositeElementSelectionFilter.cpp @@ -14,23 +14,25 @@ // ** INCLUDES ** #include "VtkCompositeElementSelectionFilter.h" -#include "VtkAppendArrayFilter.h" -#include "VtkCompositePointToGlyphFilter.h" -#include "VtkColorLookupTable.h" -#include "VtkPointsSource.h" #include <vtkDataSetSurfaceFilter.h> +#include <vtkIdFilter.h> +#include <vtkPointData.h> #include <vtkSmartPointer.h> #include <vtkThreshold.h> -#include <vtkIdFilter.h> #include <vtkUnstructuredGrid.h> - #include <vtkUnstructuredGridAlgorithm.h> -#include <vtkPointData.h> +#include "VtkAppendArrayFilter.h" +#include "VtkColorLookupTable.h" +#include "VtkCompositePointToGlyphFilter.h" +#include "VtkPointsSource.h" -VtkCompositeElementSelectionFilter::VtkCompositeElementSelectionFilter( vtkAlgorithm* inputAlgorithm ) -: VtkCompositeFilter(inputAlgorithm), _range(0.0, 1.0), _selection_name("Selection") +VtkCompositeElementSelectionFilter::VtkCompositeElementSelectionFilter( + vtkAlgorithm* inputAlgorithm) + : VtkCompositeFilter(inputAlgorithm), + _range(0.0, 1.0), + _selection_name("Selection") { } @@ -41,7 +43,8 @@ void VtkCompositeElementSelectionFilter::init() this->_inputDataObjectType = VTK_UNSTRUCTURED_GRID; this->_outputDataObjectType = VTK_UNSTRUCTURED_GRID; - this->SetLookUpTable(QString::fromStdString(_selection_name), this->GetLookupTable()); + this->SetLookUpTable(QString::fromStdString(_selection_name), + this->GetLookupTable()); vtkSmartPointer<VtkAppendArrayFilter> selFilter(nullptr); if (!_selection.empty()) { @@ -61,17 +64,19 @@ void VtkCompositeElementSelectionFilter::init() { idFilter->SetInputConnection(selFilter->GetOutputPort()); } - idFilter->PointIdsOn(); - idFilter->CellIdsOn(); - idFilter->FieldDataOn(); - idFilter->Update(); + idFilter->PointIdsOn(); + idFilter->CellIdsOn(); + idFilter->FieldDataOn(); + idFilter->Update(); vtkThreshold* threshold = vtkThreshold::New(); - threshold->SetInputConnection(idFilter->GetOutputPort()); - threshold->SetInputArrayToProcess(0,0,0,vtkDataObject::FIELD_ASSOCIATION_CELLS, _selection_name.c_str()); - threshold->SetSelectedComponent(0); - threshold->ThresholdBetween(thresholdLower, thresholdUpper); - threshold->Update(); + threshold->SetInputConnection(idFilter->GetOutputPort()); + threshold->SetInputArrayToProcess(0, 0, 0, + vtkDataObject::FIELD_ASSOCIATION_CELLS, + _selection_name.c_str()); + threshold->SetSelectedComponent(0); + threshold->ThresholdBetween(thresholdLower, thresholdUpper); + threshold->Update(); QList<QVariant> thresholdRangeList; thresholdRangeList.push_back(thresholdLower); @@ -80,14 +85,16 @@ void VtkCompositeElementSelectionFilter::init() _outputAlgorithm = threshold; } -void VtkCompositeElementSelectionFilter::setSelectionArray(const std::string &selection_name, const std::vector<double> &selection) +void VtkCompositeElementSelectionFilter::setSelectionArray( + const std::string& selection_name, const std::vector<double>& selection) { _selection_name = selection_name; _selection = selection; init(); } -void VtkCompositeElementSelectionFilter::SetUserVectorProperty( QString name, QList<QVariant> values) +void VtkCompositeElementSelectionFilter::SetUserVectorProperty( + QString name, QList<QVariant> values) { VtkAlgorithmProperties::SetUserVectorProperty(name, values); @@ -101,9 +108,9 @@ void VtkCompositeElementSelectionFilter::SetUserVectorProperty( QString name, QL VtkColorLookupTable* VtkCompositeElementSelectionFilter::GetLookupTable() { VtkColorLookupTable* lut = VtkColorLookupTable::New(); - lut->SetTableRange(0,1); - DataHolderLib::Color a{{0, 0, 255, 255}}; // blue - DataHolderLib::Color b{{0, 255, 0, 255}}; // green + lut->SetTableRange(0, 1); + DataHolderLib::Color a{{0, 0, 255, 255}}; // blue + DataHolderLib::Color b{{0, 255, 0, 255}}; // green DataHolderLib::Color c{{255, 255, 0, 255}}; // yellow DataHolderLib::Color d{{255, 0, 0, 255}}; // red lut->setColor(1.0, a); diff --git a/Applications/DataExplorer/VtkVis/VtkCompositeFilter.cpp b/Applications/DataExplorer/VtkVis/VtkCompositeFilter.cpp index 1413e4596a7c06edafefe38fb93cf47dc48c90c7..ce45808da5d41dadcdc055980de3d99b8254dbdb 100644 --- a/Applications/DataExplorer/VtkVis/VtkCompositeFilter.cpp +++ b/Applications/DataExplorer/VtkVis/VtkCompositeFilter.cpp @@ -23,8 +23,10 @@ #include <QVector> VtkCompositeFilter::VtkCompositeFilter(vtkAlgorithm* inputAlgorithm) - : _inputDataObjectType(0), _outputDataObjectType(1), - _inputAlgorithm(inputAlgorithm), _outputAlgorithm(nullptr) + : _inputDataObjectType(0), + _outputDataObjectType(1), + _inputAlgorithm(inputAlgorithm), + _outputAlgorithm(nullptr) { } @@ -36,14 +38,15 @@ VtkCompositeFilter::~VtkCompositeFilter() double VtkCompositeFilter::GetInitialRadius() const { double bounding_box[6]; - static_cast<vtkPolyData*>(this->_inputAlgorithm->GetOutputDataObject(0))->GetBounds(bounding_box); - double x_diff = fabs(bounding_box[0]-bounding_box[1]); - double y_diff = fabs(bounding_box[2]-bounding_box[3]); - double z_diff = fabs(bounding_box[4]-bounding_box[5]); + static_cast<vtkPolyData*>(this->_inputAlgorithm->GetOutputDataObject(0)) + ->GetBounds(bounding_box); + double x_diff = fabs(bounding_box[0] - bounding_box[1]); + double y_diff = fabs(bounding_box[2] - bounding_box[3]); + double z_diff = fabs(bounding_box[4] - bounding_box[5]); double max = (x_diff == 0) ? 1 : x_diff; max = (max > y_diff) ? max : y_diff; max = (max > z_diff) ? max : z_diff; - return max/200.0; + return max / 200.0; } diff --git a/Applications/DataExplorer/VtkVis/VtkCompositeGeoObjectFilter.cpp b/Applications/DataExplorer/VtkVis/VtkCompositeGeoObjectFilter.cpp index 45daa1176fc7ad4533c002e71a625ad340dacf4d..aa33bacd69f830e9250e1fe4ac8be5eafe2e19f2 100644 --- a/Applications/DataExplorer/VtkVis/VtkCompositeGeoObjectFilter.cpp +++ b/Applications/DataExplorer/VtkVis/VtkCompositeGeoObjectFilter.cpp @@ -15,47 +15,51 @@ // ** INCLUDES ** #include "VtkCompositeGeoObjectFilter.h" +#include <vtkAlgorithmOutput.h> #include <vtkDataSetSurfaceFilter.h> +#include <vtkPointData.h> #include <vtkSmartPointer.h> #include <vtkThreshold.h> -#include <vtkAlgorithmOutput.h> +#include "VtkCompositeLineToTubeFilter.h" +#include "VtkCompositePointToGlyphFilter.h" #include "VtkPolylinesSource.h" -#include "VtkSurfacesSource.h" #include "VtkStationSource.h" -#include "VtkCompositePointToGlyphFilter.h" -#include "VtkCompositeLineToTubeFilter.h" - -#include <vtkPointData.h> +#include "VtkSurfacesSource.h" -VtkCompositeGeoObjectFilter::VtkCompositeGeoObjectFilter( vtkAlgorithm* inputAlgorithm ) - : VtkCompositeFilter(inputAlgorithm), _type(GeoLib::GEOTYPE::POINT), _threshold(vtkThreshold::New()) +VtkCompositeGeoObjectFilter::VtkCompositeGeoObjectFilter( + vtkAlgorithm* inputAlgorithm) + : VtkCompositeFilter(inputAlgorithm), + _type(GeoLib::GEOTYPE::POINT), + _threshold(vtkThreshold::New()) { - if (inputAlgorithm->GetNumberOfInputPorts() && inputAlgorithm->GetNumberOfInputConnections(0)) + if (inputAlgorithm->GetNumberOfInputPorts() && + inputAlgorithm->GetNumberOfInputConnections(0)) { - vtkAlgorithmOutput* ao = inputAlgorithm->GetInputConnection(0,0); - - if (ao) - { - vtkAlgorithm* parentAlg = ao->GetProducer(); + vtkAlgorithmOutput* ao = inputAlgorithm->GetInputConnection(0, 0); - if (dynamic_cast<VtkPolylinesSource*>(parentAlg) != nullptr) + if (ao) { - _type = GeoLib::GEOTYPE::POLYLINE; - } - else if (dynamic_cast<VtkSurfacesSource*>(parentAlg) != nullptr) - { - _type = GeoLib::GEOTYPE::SURFACE; - } - else if (dynamic_cast<VtkStationSource*>(parentAlg) != nullptr) - { - /* TODO - if (dynamic_cast<VtkStationSource*>(parentAlg)->getType() == GeoLib::Station::StationType::BOREHOLE) + vtkAlgorithm* parentAlg = ao->GetProducer(); + + if (dynamic_cast<VtkPolylinesSource*>(parentAlg) != nullptr) + { _type = GeoLib::GEOTYPE::POLYLINE; - */ + } + else if (dynamic_cast<VtkSurfacesSource*>(parentAlg) != nullptr) + { + _type = GeoLib::GEOTYPE::SURFACE; + } + else if (dynamic_cast<VtkStationSource*>(parentAlg) != nullptr) + { + /* TODO + if (dynamic_cast<VtkStationSource*>(parentAlg)->getType() == + GeoLib::Station::StationType::BOREHOLE) _type = + GeoLib::GEOTYPE::POLYLINE; + */ + } } - } - this->init(); + this->init(); } } @@ -68,7 +72,7 @@ void VtkCompositeGeoObjectFilter::init() _threshold->SetInputConnection(_inputAlgorithm->GetOutputPort()); _threshold->SetSelectedComponent(0); - _threshold->ThresholdBetween(0,0); + _threshold->ThresholdBetween(0, 0); vtkDataSetSurfaceFilter* surface = vtkDataSetSurfaceFilter::New(); surface->SetInputConnection(_threshold->GetOutputPort()); @@ -97,5 +101,3 @@ void VtkCompositeGeoObjectFilter::SetIndex(std::size_t idx) double const d_idx = static_cast<double>(idx); _threshold->ThresholdBetween(d_idx, d_idx); } - - diff --git a/Applications/DataExplorer/VtkVis/VtkCompositeImageToCylindersFilter.cpp b/Applications/DataExplorer/VtkVis/VtkCompositeImageToCylindersFilter.cpp index 2773d81dc47a4e7d677c43c01be64b08e2d0bb55..750c6c93fd38a472587d4277a5ebfb9f823462d0 100644 --- a/Applications/DataExplorer/VtkVis/VtkCompositeImageToCylindersFilter.cpp +++ b/Applications/DataExplorer/VtkVis/VtkCompositeImageToCylindersFilter.cpp @@ -15,8 +15,6 @@ // ** INCLUDES ** #include "VtkCompositeImageToCylindersFilter.h" -#include "VtkImageDataToLinePolyDataFilter.h" - #include <vtkLookupTable.h> #include <vtkPointData.h> #include <vtkSmartPointer.h> @@ -28,8 +26,10 @@ #include <QVariant> #include <QVector> +#include "VtkImageDataToLinePolyDataFilter.h" + VtkCompositeImageToCylindersFilter::VtkCompositeImageToCylindersFilter( - vtkAlgorithm* inputAlgorithm ) + vtkAlgorithm* inputAlgorithm) : VtkCompositeFilter(inputAlgorithm), _lineFilter(nullptr) { this->init(); @@ -48,7 +48,10 @@ void VtkCompositeImageToCylindersFilter::init() double range[2]; // The data is always on points - vtkDataSet::SafeDownCast(_lineFilter->GetOutputDataObject(0))->GetPointData()->GetScalars()->GetRange(range); + vtkDataSet::SafeDownCast(_lineFilter->GetOutputDataObject(0)) + ->GetPointData() + ->GetScalars() + ->GetRange(range); vtkLookupTable* colormap = vtkLookupTable::New(); colormap->SetTableRange(range[0], range[1]); @@ -79,7 +82,8 @@ void VtkCompositeImageToCylindersFilter::init() _outputAlgorithm = tubeFilter; } -void VtkCompositeImageToCylindersFilter::SetUserProperty( QString name, QVariant value ) +void VtkCompositeImageToCylindersFilter::SetUserProperty(QString name, + QVariant value) { VtkAlgorithmProperties::SetUserProperty(name, value); @@ -97,11 +101,13 @@ void VtkCompositeImageToCylindersFilter::SetUserProperty( QString name, QVariant } else if (name.compare("NumberOfSides") == 0) { - static_cast<vtkTubeFilter*>(_outputAlgorithm)->SetNumberOfSides(value.toInt()); + static_cast<vtkTubeFilter*>(_outputAlgorithm) + ->SetNumberOfSides(value.toInt()); } else if (name.compare("Capping") == 0) { - static_cast<vtkTubeFilter*>(_outputAlgorithm)->SetCapping(value.toBool()); + static_cast<vtkTubeFilter*>(_outputAlgorithm) + ->SetCapping(value.toBool()); } else if (name.compare("RadiusFactor") == 0) { @@ -110,8 +116,8 @@ void VtkCompositeImageToCylindersFilter::SetUserProperty( QString name, QVariant } } -void VtkCompositeImageToCylindersFilter::SetUserVectorProperty( QString name, - QList<QVariant> values ) +void VtkCompositeImageToCylindersFilter::SetUserVectorProperty( + QString name, QList<QVariant> values) { VtkAlgorithmProperties::SetUserVectorProperty(name, values); diff --git a/Applications/DataExplorer/VtkVis/VtkCompositeImageToPointCloudFilter.cpp b/Applications/DataExplorer/VtkVis/VtkCompositeImageToPointCloudFilter.cpp index 1ced539342d859c9380e98db4bf772b602824a34..2b8904f03acebbae991e94f4e8cf089fef91dae3 100644 --- a/Applications/DataExplorer/VtkVis/VtkCompositeImageToPointCloudFilter.cpp +++ b/Applications/DataExplorer/VtkVis/VtkCompositeImageToPointCloudFilter.cpp @@ -18,7 +18,8 @@ #include "VtkImageDataToPointCloudFilter.h" -VtkCompositeImageToPointCloudFilter::VtkCompositeImageToPointCloudFilter(vtkAlgorithm* inputAlgorithm) +VtkCompositeImageToPointCloudFilter::VtkCompositeImageToPointCloudFilter( + vtkAlgorithm* inputAlgorithm) : VtkCompositeFilter(inputAlgorithm) { init(); @@ -35,34 +36,41 @@ void VtkCompositeImageToPointCloudFilter::init() _inputAlgorithm->Update(); QList<QVariant> n_points_range_list; - n_points_range_list.push_back(point_cloud_filter->GetMinNumberOfPointsPerCell()); - n_points_range_list.push_back(point_cloud_filter->GetMaxNumberOfPointsPerCell()); - (*_algorithmUserVectorProperties)["Number of points range"] = n_points_range_list; + n_points_range_list.push_back( + point_cloud_filter->GetMinNumberOfPointsPerCell()); + n_points_range_list.push_back( + point_cloud_filter->GetMaxNumberOfPointsPerCell()); + (*_algorithmUserVectorProperties)["Number of points range"] = + n_points_range_list; QList<QVariant> vertical_extent_list; vertical_extent_list.push_back(point_cloud_filter->GetMinHeight()); vertical_extent_list.push_back(point_cloud_filter->GetMaxHeight()); (*_algorithmUserVectorProperties)["Vertical extent"] = vertical_extent_list; - (*_algorithmUserProperties)["Logarithmic interpolation"] = !point_cloud_filter->GetIsLinear(); + (*_algorithmUserProperties)["Logarithmic interpolation"] = + !point_cloud_filter->GetIsLinear(); (*_algorithmUserProperties)["Gamma value"] = point_cloud_filter->GetGamma(); point_cloud_filter->Update(); _outputAlgorithm = point_cloud_filter; } -void VtkCompositeImageToPointCloudFilter::SetUserProperty(QString name, QVariant value) +void VtkCompositeImageToPointCloudFilter::SetUserProperty(QString name, + QVariant value) { VtkAlgorithmProperties::SetUserProperty(name, value); if ((name == "Gamma value") && (value.toDouble() > 0)) { - static_cast<VtkImageDataToPointCloudFilter*>(_outputAlgorithm)->SetGamma(value.toDouble()); + static_cast<VtkImageDataToPointCloudFilter*>(_outputAlgorithm) + ->SetGamma(value.toDouble()); } if (name == "Logarithmic interpolation") { if (value.toBool()) { double const gamma = - VtkAlgorithmProperties::GetUserProperty("Gamma value").toDouble(); + VtkAlgorithmProperties::GetUserProperty("Gamma value") + .toDouble(); if (gamma > 0) { static_cast<VtkImageDataToPointCloudFilter*>(_outputAlgorithm) @@ -77,7 +85,8 @@ void VtkCompositeImageToPointCloudFilter::SetUserProperty(QString name, QVariant } } -void VtkCompositeImageToPointCloudFilter::SetUserVectorProperty(QString name, QList<QVariant> values) +void VtkCompositeImageToPointCloudFilter::SetUserVectorProperty( + QString name, QList<QVariant> values) { VtkAlgorithmProperties::SetUserVectorProperty(name, values); diff --git a/Applications/DataExplorer/VtkVis/VtkCompositeImageToSurfacePointsFilter.cpp b/Applications/DataExplorer/VtkVis/VtkCompositeImageToSurfacePointsFilter.cpp index b8f35aa650c399219acbf9e52bd4a0a775dd7e83..f113c23d120b107784e618dc75079e3a9df6c659 100644 --- a/Applications/DataExplorer/VtkVis/VtkCompositeImageToSurfacePointsFilter.cpp +++ b/Applications/DataExplorer/VtkVis/VtkCompositeImageToSurfacePointsFilter.cpp @@ -41,7 +41,8 @@ void VtkCompositeImageToSurfacePointsFilter::init() _outputAlgorithm = point_cloud_filter; } -void VtkCompositeImageToSurfacePointsFilter::SetUserProperty(QString name, QVariant value) +void VtkCompositeImageToSurfacePointsFilter::SetUserProperty(QString name, + QVariant value) { VtkAlgorithmProperties::SetUserProperty(name, value); if ((name == "Points per pixel") && (value.toInt() > 0)) diff --git a/Applications/DataExplorer/VtkVis/VtkCompositeLineToTubeFilter.cpp b/Applications/DataExplorer/VtkVis/VtkCompositeLineToTubeFilter.cpp index 77119f61d2097d0499a7c2eec80d03b6f24c60e7..01c285537182f0a7f6f6b532e89e8640da288d1b 100644 --- a/Applications/DataExplorer/VtkVis/VtkCompositeLineToTubeFilter.cpp +++ b/Applications/DataExplorer/VtkVis/VtkCompositeLineToTubeFilter.cpp @@ -19,7 +19,8 @@ #include <vtkSmartPointer.h> #include <vtkTubeFilter.h> -VtkCompositeLineToTubeFilter::VtkCompositeLineToTubeFilter( vtkAlgorithm* inputAlgorithm ) +VtkCompositeLineToTubeFilter::VtkCompositeLineToTubeFilter( + vtkAlgorithm* inputAlgorithm) : VtkCompositeFilter(inputAlgorithm) { this->init(); @@ -33,7 +34,8 @@ void VtkCompositeLineToTubeFilter::init() this->_outputDataObjectType = VTK_POLY_DATA; // collapse coincident points - vtkSmartPointer<vtkCleanPolyData> mergePoints = vtkSmartPointer<vtkCleanPolyData>::New(); + vtkSmartPointer<vtkCleanPolyData> mergePoints = + vtkSmartPointer<vtkCleanPolyData>::New(); mergePoints->SetInputConnection(0, _inputAlgorithm->GetOutputPort(0)); mergePoints->SetTolerance(0.0); mergePoints->ConvertLinesToPointsOn(); @@ -43,10 +45,12 @@ void VtkCompositeLineToTubeFilter::init() vtkTubeFilter* tubes = vtkTubeFilter::New(); tubes->SetInputConnection(0, mergePoints->GetOutputPort(0)); - //tubes->SetInputArrayToProcess(1,0,0,vtkDataObject::FIELD_ASSOCIATION_CELLS,"StationValue"); - //tubes->SetVaryRadiusToVaryRadiusByScalar(); // KR radius changes with scalar + // tubes->SetInputArrayToProcess(1,0,0,vtkDataObject::FIELD_ASSOCIATION_CELLS,"StationValue"); + // tubes->SetVaryRadiusToVaryRadiusByScalar(); // KR radius changes with + // scalar - tubes->SetInputArrayToProcess(1,0,0,vtkDataObject::FIELD_ASSOCIATION_CELLS,"Stratigraphies"); + tubes->SetInputArrayToProcess( + 1, 0, 0, vtkDataObject::FIELD_ASSOCIATION_CELLS, "Stratigraphies"); tubes->SetRadius(default_radius); tubes->SetNumberOfSides(default_number_of_sides); tubes->SetCapping(1); @@ -58,17 +62,19 @@ void VtkCompositeLineToTubeFilter::init() _outputAlgorithm = tubes; } -void VtkCompositeLineToTubeFilter::SetUserProperty( QString name, QVariant value ) +void VtkCompositeLineToTubeFilter::SetUserProperty(QString name, QVariant value) { VtkAlgorithmProperties::SetUserProperty(name, value); if (name.compare("Radius") == 0) { - static_cast<vtkTubeFilter*>(_outputAlgorithm)->SetRadius(value.toDouble()); + static_cast<vtkTubeFilter*>(_outputAlgorithm) + ->SetRadius(value.toDouble()); } else if (name.compare("NumberOfSides") == 0) { - static_cast<vtkTubeFilter*>(_outputAlgorithm)->SetNumberOfSides(value.toInt()); + static_cast<vtkTubeFilter*>(_outputAlgorithm) + ->SetNumberOfSides(value.toInt()); } else if (name.compare("Capping") == 0) { diff --git a/Applications/DataExplorer/VtkVis/VtkCompositeNodeSelectionFilter.cpp b/Applications/DataExplorer/VtkVis/VtkCompositeNodeSelectionFilter.cpp index 480effba873ce89c2b760f632b31325ce06460ab..6e0cc72c1004d8d4d9db47c2c67184ace2464acc 100644 --- a/Applications/DataExplorer/VtkVis/VtkCompositeNodeSelectionFilter.cpp +++ b/Applications/DataExplorer/VtkVis/VtkCompositeNodeSelectionFilter.cpp @@ -13,22 +13,22 @@ */ // ** INCLUDES ** -#include <memory> - #include "VtkCompositeNodeSelectionFilter.h" -//#include "VtkCompositePointToGlyphFilter.h" -#include "VtkPointsSource.h" +#include <memory> +//#include "VtkCompositePointToGlyphFilter.h" #include <vtkDataSetAlgorithm.h> +#include <vtkGlyph3D.h> #include <vtkSmartPointer.h> #include <vtkSphereSource.h> -#include <vtkGlyph3D.h> +#include "VtkPointsSource.h" -VtkCompositeNodeSelectionFilter::VtkCompositeNodeSelectionFilter( vtkAlgorithm* inputAlgorithm ) -: VtkCompositeFilter(inputAlgorithm) +VtkCompositeNodeSelectionFilter::VtkCompositeNodeSelectionFilter( + vtkAlgorithm* inputAlgorithm) + : VtkCompositeFilter(inputAlgorithm) { - //this->init(); + // this->init(); } VtkCompositeNodeSelectionFilter::~VtkCompositeNodeSelectionFilter() @@ -46,15 +46,17 @@ void VtkCompositeNodeSelectionFilter::init() if (!_selection.empty()) { - vtkSmartPointer<VtkPointsSource> point_source = vtkSmartPointer<VtkPointsSource>::New(); + vtkSmartPointer<VtkPointsSource> point_source = + vtkSmartPointer<VtkPointsSource>::New(); point_source->setPoints(&_selection); - vtkSmartPointer<vtkSphereSource> _glyphSource = vtkSmartPointer<vtkSphereSource>::New(); - _glyphSource->SetRadius(this->GetInitialRadius()); + vtkSmartPointer<vtkSphereSource> _glyphSource = + vtkSmartPointer<vtkSphereSource>::New(); + _glyphSource->SetRadius(this->GetInitialRadius()); vtkGlyph3D* glyphFilter = vtkGlyph3D::New(); - glyphFilter->SetSourceConnection(_glyphSource->GetOutputPort()); - glyphFilter->SetInputConnection(point_source->GetOutputPort()); + glyphFilter->SetSourceConnection(_glyphSource->GetOutputPort()); + glyphFilter->SetInputConnection(point_source->GetOutputPort()); _outputAlgorithm = glyphFilter; } @@ -64,7 +66,8 @@ void VtkCompositeNodeSelectionFilter::init() } } -void VtkCompositeNodeSelectionFilter::setSelectionArray(const std::vector<unsigned> &point_indeces) +void VtkCompositeNodeSelectionFilter::setSelectionArray( + const std::vector<unsigned>& point_indeces) { for (unsigned int point_index : point_indeces) { @@ -76,4 +79,3 @@ void VtkCompositeNodeSelectionFilter::setSelectionArray(const std::vector<unsign } init(); } - diff --git a/Applications/DataExplorer/VtkVis/VtkCompositePointToGlyphFilter.cpp b/Applications/DataExplorer/VtkVis/VtkCompositePointToGlyphFilter.cpp index 004ca46fd3044c2eec4f32c193a9ac9780a12048..03eb51fab4f62de2b4b7769d728c284698b383b8 100644 --- a/Applications/DataExplorer/VtkVis/VtkCompositePointToGlyphFilter.cpp +++ b/Applications/DataExplorer/VtkVis/VtkCompositePointToGlyphFilter.cpp @@ -20,7 +20,8 @@ #include <vtkPointData.h> #include <vtkSphereSource.h> -VtkCompositePointToGlyphFilter::VtkCompositePointToGlyphFilter( vtkAlgorithm* inputAlgorithm ) +VtkCompositePointToGlyphFilter::VtkCompositePointToGlyphFilter( + vtkAlgorithm* inputAlgorithm) : VtkCompositeFilter(inputAlgorithm), _glyphSource(nullptr) { this->init(); @@ -37,13 +38,16 @@ void VtkCompositePointToGlyphFilter::init() this->_outputDataObjectType = VTK_POLY_DATA; std::size_t nPoints = static_cast<vtkDataSetAlgorithm*>(_inputAlgorithm) - ->GetOutput()->GetPointData()->GetNumberOfTuples(); - int phi (10 - static_cast<std::size_t>(nPoints / 2000.0)); - int theta (phi); + ->GetOutput() + ->GetPointData() + ->GetNumberOfTuples(); + int phi(10 - static_cast<std::size_t>(nPoints / 2000.0)); + int theta(phi); if (phi < 4) { phi = 4; - theta = 4; // for theta 3 would be possible, too, but 4 looks much better + theta = + 4; // for theta 3 would be possible, too, but 4 looks much better } double default_radius(GetInitialRadius()); @@ -57,9 +61,14 @@ void VtkCompositePointToGlyphFilter::init() (*_algorithmUserProperties)["ThetaResolution"] = theta; vtkGlyph3D* glyphFilter = vtkGlyph3D::New(); - glyphFilter->ScalingOn(); // KR important to scale glyphs with double precision (e.g. 0.1 of their size for small datasets) - //glyphFilter->SetScaleModeToScaleByScalar(); // KR can easily obscure view when scalar values have large differences (this is also the default scaling method) - glyphFilter->SetScaleModeToDataScalingOff(); // KR scaling is possible but scalar values are ignored + glyphFilter + ->ScalingOn(); // KR important to scale glyphs with double precision + // (e.g. 0.1 of their size for small datasets) + // glyphFilter->SetScaleModeToScaleByScalar(); // KR can easily obscure + // view when scalar values have large differences (this is also the default + // scaling method) + glyphFilter->SetScaleModeToDataScalingOff(); // KR scaling is possible but + // scalar values are ignored glyphFilter->SetScaleFactor(1.0); glyphFilter->SetSourceConnection(_glyphSource->GetOutputPort()); glyphFilter->SetInputConnection(_inputAlgorithm->GetOutputPort()); @@ -72,7 +81,8 @@ void VtkCompositePointToGlyphFilter::init() _outputAlgorithm = glyphFilter; } -void VtkCompositePointToGlyphFilter::SetUserProperty( QString name, QVariant value ) +void VtkCompositePointToGlyphFilter::SetUserProperty(QString name, + QVariant value) { VtkAlgorithmProperties::SetUserProperty(name, value); @@ -94,7 +104,8 @@ void VtkCompositePointToGlyphFilter::SetUserProperty( QString name, QVariant val } else if (name.compare("ScaleFactor") == 0) { - static_cast<vtkGlyph3D*>(_outputAlgorithm)->SetScaleFactor(value.toDouble()); + static_cast<vtkGlyph3D*>(_outputAlgorithm) + ->SetScaleFactor(value.toDouble()); } else if (name.compare("ColorMode") == 0) { @@ -102,7 +113,8 @@ void VtkCompositePointToGlyphFilter::SetUserProperty( QString name, QVariant val } else if (name.compare("VectorMode") == 0) { - static_cast<vtkGlyph3D*>(_outputAlgorithm)->SetVectorMode(value.toInt()); + static_cast<vtkGlyph3D*>(_outputAlgorithm) + ->SetVectorMode(value.toInt()); } else if (name.compare("Orient") == 0) { diff --git a/Applications/DataExplorer/VtkVis/VtkCompositeTextureOnSurfaceFilter.cpp b/Applications/DataExplorer/VtkVis/VtkCompositeTextureOnSurfaceFilter.cpp index 41602c4ff6eb1bc194e8317dbcb2e1734e399f78..c915c449ec6164b903686a861db39ea3b810364b 100644 --- a/Applications/DataExplorer/VtkVis/VtkCompositeTextureOnSurfaceFilter.cpp +++ b/Applications/DataExplorer/VtkVis/VtkCompositeTextureOnSurfaceFilter.cpp @@ -15,14 +15,14 @@ // ** INCLUDES ** #include "VtkCompositeTextureOnSurfaceFilter.h" -#include "BaseLib/Logging.h" - -#include "VtkTextureOnSurfaceFilter.h" #include <vtkDataSetSurfaceFilter.h> #include <vtkSmartPointer.h> #include <vtkUnstructuredGrid.h> + +#include "BaseLib/Logging.h" #include "VtkGeoImageSource.h" #include "VtkRaster.h" +#include "VtkTextureOnSurfaceFilter.h" #ifdef OGS_USE_NETCDF #include "NetCdfConfigureDialog.h" #endif // OGS_USE_NETCDF @@ -33,9 +33,8 @@ //#include "VtkCompositeColormapToImageFilter.h" - VtkCompositeTextureOnSurfaceFilter::VtkCompositeTextureOnSurfaceFilter( - vtkAlgorithm* inputAlgorithm ) + vtkAlgorithm* inputAlgorithm) : VtkCompositeFilter(inputAlgorithm) { this->init(); @@ -52,7 +51,8 @@ void VtkCompositeTextureOnSurfaceFilter::init() vtkSmartPointer<vtkDataSetSurfaceFilter> surfaceFilter; VtkTextureOnSurfaceFilter* surface = VtkTextureOnSurfaceFilter::New(); - if (dynamic_cast<vtkUnstructuredGrid*>(_inputAlgorithm->GetOutputDataObject(0))) + if (dynamic_cast<vtkUnstructuredGrid*>( + _inputAlgorithm->GetOutputDataObject(0))) { surfaceFilter = vtkSmartPointer<vtkDataSetSurfaceFilter>::New(); surfaceFilter->SetInputConnection(_inputAlgorithm->GetOutputPort()); @@ -101,12 +101,14 @@ void VtkCompositeTextureOnSurfaceFilter::init() } #endif // OGS_USE_NETCDF else - ERR("VtkCompositeTextureOnSurfaceFilter::init(): Error reading texture file."); + ERR("VtkCompositeTextureOnSurfaceFilter::init(): Error reading texture " + "file."); _outputAlgorithm = surface; } -void VtkCompositeTextureOnSurfaceFilter::SetUserProperty( QString name, QVariant value ) +void VtkCompositeTextureOnSurfaceFilter::SetUserProperty(QString name, + QVariant value) { VtkAlgorithmProperties::SetUserProperty(name, value); } diff --git a/Applications/DataExplorer/VtkVis/VtkCompositeThresholdFilter.cpp b/Applications/DataExplorer/VtkVis/VtkCompositeThresholdFilter.cpp index 39713fbafc3ee5797c45e3f123e73f717a2f8453..1770c2f2ab733e6d34e18b07e08547dc76e5329a 100644 --- a/Applications/DataExplorer/VtkVis/VtkCompositeThresholdFilter.cpp +++ b/Applications/DataExplorer/VtkVis/VtkCompositeThresholdFilter.cpp @@ -15,13 +15,14 @@ // ** INCLUDES ** #include "VtkCompositeThresholdFilter.h" -#include "BaseLib/Logging.h" - #include <vtkCellData.h> #include <vtkThreshold.h> #include <vtkUnstructuredGrid.h> -VtkCompositeThresholdFilter::VtkCompositeThresholdFilter( vtkAlgorithm* inputAlgorithm ) +#include "BaseLib/Logging.h" + +VtkCompositeThresholdFilter::VtkCompositeThresholdFilter( + vtkAlgorithm* inputAlgorithm) : VtkCompositeFilter(inputAlgorithm) { this->init(); @@ -41,20 +42,22 @@ void VtkCompositeThresholdFilter::init() // Use first array of parent as input array _inputAlgorithm->Update(); - vtkDataSet* dataSet = vtkDataSet::SafeDownCast( - _inputAlgorithm->GetOutputDataObject(0)); + vtkDataSet* dataSet = + vtkDataSet::SafeDownCast(_inputAlgorithm->GetOutputDataObject(0)); vtkDataSetAttributes* pointAttributes = dataSet->GetAttributes(vtkDataObject::AttributeTypes::POINT); vtkDataSetAttributes* cellAttributes = dataSet->GetAttributes(vtkDataObject::AttributeTypes::CELL); if (pointAttributes->GetNumberOfArrays() > 0) { - threshold->SetInputArrayToProcess(0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, + threshold->SetInputArrayToProcess( + 0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, pointAttributes->GetArray(0)->GetName()); } else if (cellAttributes->GetNumberOfArrays() > 0) { - threshold->SetInputArrayToProcess(0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_CELLS, + threshold->SetInputArrayToProcess( + 0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_CELLS, cellAttributes->GetArray(0)->GetName()); } else @@ -91,7 +94,7 @@ void VtkCompositeThresholdFilter::init() _outputAlgorithm = threshold; } -void VtkCompositeThresholdFilter::SetUserProperty( QString name, QVariant value ) +void VtkCompositeThresholdFilter::SetUserProperty(QString name, QVariant value) { VtkAlgorithmProperties::SetUserProperty(name, value); @@ -99,7 +102,8 @@ void VtkCompositeThresholdFilter::SetUserProperty( QString name, QVariant value if (name.compare("Selected Component") == 0) { // Set the property on the algorithm - static_cast<vtkThreshold*>(_outputAlgorithm)->SetSelectedComponent(value.toInt()); + static_cast<vtkThreshold*>(_outputAlgorithm) + ->SetSelectedComponent(value.toInt()); } else if (name.compare("Evaluate all points") == 0) { @@ -108,7 +112,8 @@ void VtkCompositeThresholdFilter::SetUserProperty( QString name, QVariant value } } -void VtkCompositeThresholdFilter::SetUserVectorProperty( QString name, QList<QVariant> values ) +void VtkCompositeThresholdFilter::SetUserVectorProperty(QString name, + QList<QVariant> values) { VtkAlgorithmProperties::SetUserVectorProperty(name, values); diff --git a/Applications/DataExplorer/VtkVis/VtkConsoleOutputWindow.cpp b/Applications/DataExplorer/VtkVis/VtkConsoleOutputWindow.cpp index f3ff2b88fc6a209f70c641a18ec3cddc7d597afc..9701b1d43fd366982e548a05ca934a70ff3ad70b 100644 --- a/Applications/DataExplorer/VtkVis/VtkConsoleOutputWindow.cpp +++ b/Applications/DataExplorer/VtkVis/VtkConsoleOutputWindow.cpp @@ -9,8 +9,8 @@ */ #include "VtkConsoleOutputWindow.h" -#include <string> #include <ostream> +#include <string> #include "vtkObjectFactory.h" #ifdef WIN32 @@ -56,5 +56,5 @@ void VtkConsoleOutputWindow::DisplayText(const char* someText) //---------------------------------------------------------------------------- void VtkConsoleOutputWindow::PrintSelf(ostream& os, vtkIndent indent) { - this->Superclass::PrintSelf(os,indent); + this->Superclass::PrintSelf(os, indent); } diff --git a/Applications/DataExplorer/VtkVis/VtkCustomInteractorStyle.cpp b/Applications/DataExplorer/VtkVis/VtkCustomInteractorStyle.cpp index 48b44eca3478d19bf1b4c837eb3613844aa4c1e1..2670a92868000e7f65bf17a4d4c34280b313de46 100644 --- a/Applications/DataExplorer/VtkVis/VtkCustomInteractorStyle.cpp +++ b/Applications/DataExplorer/VtkVis/VtkCustomInteractorStyle.cpp @@ -15,8 +15,6 @@ // ** INCLUDES ** #include "VtkCustomInteractorStyle.h" -#include "BaseLib/Logging.h" - #include <vtkActor.h> #include <vtkAlgorithmOutput.h> #include <vtkCamera.h> @@ -39,6 +37,7 @@ #include <string> +#include "BaseLib/Logging.h" #include "VtkCompositeElementSelectionFilter.h" vtkStandardNewMacro(VtkCustomInteractorStyle); @@ -49,7 +48,7 @@ VtkCustomInteractorStyle::VtkCustomInteractorStyle() _selectedActor = vtkActor::New(); _selectedActor->SetMapper(_selectedMapper); _selectedActor->GetProperty()->EdgeVisibilityOn(); - _selectedActor->GetProperty()->SetEdgeColor(1,0,0); + _selectedActor->GetProperty()->SetEdgeColor(1, 0, 0); _selectedActor->GetProperty()->SetLineWidth(3); } @@ -63,13 +62,13 @@ void VtkCustomInteractorStyle::OnChar() { switch (Interactor->GetKeyCode()) { - case '3': - INFO("The 3 key was pressed."); - break; - case 'a': - break; - default: - vtkInteractorStyleTrackballCamera::OnChar(); + case '3': + INFO("The 3 key was pressed."); + break; + case 'a': + break; + default: + vtkInteractorStyleTrackballCamera::OnChar(); } } @@ -77,12 +76,12 @@ void VtkCustomInteractorStyle::OnKeyDown() { switch (Interactor->GetKeyCode()) { - case 32: // Space - _alternateMouseActions = true; - emit cursorChanged(Qt::CrossCursor); - break; - default: - vtkInteractorStyleTrackballCamera::OnKeyDown(); + case 32: // Space + _alternateMouseActions = true; + emit cursorChanged(Qt::CrossCursor); + break; + default: + vtkInteractorStyleTrackballCamera::OnKeyDown(); } } @@ -90,16 +89,16 @@ void VtkCustomInteractorStyle::OnKeyUp() { switch (Interactor->GetKeyCode()) { - case 32: // Space - _alternateMouseActions = false; - emit cursorChanged(Qt::ArrowCursor); - break; - default: - vtkInteractorStyleTrackballCamera::OnKeyUp(); + case 32: // Space + _alternateMouseActions = false; + emit cursorChanged(Qt::ArrowCursor); + break; + default: + vtkInteractorStyleTrackballCamera::OnKeyUp(); } } -void VtkCustomInteractorStyle::highlightActor( vtkProp3D* actor ) +void VtkCustomInteractorStyle::highlightActor(vtkProp3D* actor) { if (_highlightActor) { @@ -109,8 +108,10 @@ void VtkCustomInteractorStyle::highlightActor( vtkProp3D* actor ) void VtkCustomInteractorStyle::removeHighlightActor() { - this->Interactor->GetRenderWindow()->GetRenderers()->GetFirstRenderer()-> - RemoveActor(_selectedActor); + this->Interactor->GetRenderWindow() + ->GetRenderers() + ->GetFirstRenderer() + ->RemoveActor(_selectedActor); } void VtkCustomInteractorStyle::setHighlightActor(bool on) @@ -127,8 +128,10 @@ void VtkCustomInteractorStyle::pickableDataObject(vtkDataObject* object) _data = object; if (!object) { - this->Interactor->GetRenderWindow()->GetRenderers()->GetFirstRenderer()-> - RemoveActor(_selectedActor); + this->Interactor->GetRenderWindow() + ->GetRenderers() + ->GetFirstRenderer() + ->RemoveActor(_selectedActor); _selectedMapper->SetInputConnection(nullptr); } } @@ -147,7 +150,7 @@ void VtkCustomInteractorStyle::OnLeftButtonDown() int* pos = this->GetInteractor()->GetEventPosition(); vtkSmartPointer<vtkCellPicker> picker = - vtkSmartPointer<vtkCellPicker>::New(); + vtkSmartPointer<vtkCellPicker>::New(); picker->SetTolerance(0.0005); // Pick from this location. @@ -156,35 +159,35 @@ void VtkCustomInteractorStyle::OnLeftButtonDown() double* worldPosition = picker->GetPickPosition(); INFO("Cell id is: {:d}", picker->GetCellId()); - if(picker->GetCellId() != -1) + if (picker->GetCellId() != -1) { INFO("Pick position is: {:f} {:f} {:f}", worldPosition[0], worldPosition[1], worldPosition[2]); vtkSmartPointer<vtkIdTypeArray> ids = - vtkSmartPointer<vtkIdTypeArray>::New(); + vtkSmartPointer<vtkIdTypeArray>::New(); ids->SetNumberOfValues(1); ids->SetValue(0, picker->GetCellId()); vtkSmartPointer<vtkSelectionNode> selectionNode = - vtkSmartPointer<vtkSelectionNode>::New(); + vtkSmartPointer<vtkSelectionNode>::New(); selectionNode->SetFieldType(vtkSelectionNode::CELL); selectionNode->SetContentType(vtkSelectionNode::INDICES); selectionNode->SetSelectionList(ids); vtkSmartPointer<vtkSelection> selection = - vtkSmartPointer<vtkSelection>::New(); + vtkSmartPointer<vtkSelection>::New(); selection->AddNode(selectionNode); vtkSmartPointer<vtkExtractSelection> extractSelection = - vtkSmartPointer<vtkExtractSelection>::New(); + vtkSmartPointer<vtkExtractSelection>::New(); extractSelection->SetInputData(0, _data); extractSelection->SetInputData(1, selection); extractSelection->Update(); // In selection vtkSmartPointer<vtkUnstructuredGrid> selected = - vtkSmartPointer<vtkUnstructuredGrid>::New(); + vtkSmartPointer<vtkUnstructuredGrid>::New(); selected->ShallowCopy(extractSelection->GetOutput()); INFO("There are {:d} points in the selection.", @@ -192,13 +195,21 @@ void VtkCustomInteractorStyle::OnLeftButtonDown() INFO("There are {:d} cells in the selection.", selected->GetNumberOfCells()); - // check if the underlying object is a mesh and if so, send a signal to the element model for display of information about the picked element. - vtkAlgorithm* data_set = picker->GetActor()->GetMapper()->GetInputConnection(0, 0)->GetProducer()->GetInputConnection(0,0)->GetProducer(); + // check if the underlying object is a mesh and if so, send a signal + // to the element model for display of information about the picked + // element. + vtkAlgorithm* data_set = picker->GetActor() + ->GetMapper() + ->GetInputConnection(0, 0) + ->GetProducer() + ->GetInputConnection(0, 0) + ->GetProducer(); auto* source = dynamic_cast<vtkUnstructuredGridAlgorithm*>(data_set); if (source) { - emit elementPicked(source, static_cast<unsigned>(picker->GetCellId())); + emit elementPicked(source, + static_cast<unsigned>(picker->GetCellId())); } else { @@ -206,8 +217,10 @@ void VtkCustomInteractorStyle::OnLeftButtonDown() } _selectedMapper->SetInputData(selected); - this->Interactor->GetRenderWindow()->GetRenderers()->GetFirstRenderer()-> - AddActor(_selectedActor); + this->Interactor->GetRenderWindow() + ->GetRenderers() + ->GetFirstRenderer() + ->AddActor(_selectedActor); //_highlightActor = true; } else @@ -239,7 +252,7 @@ void VtkCustomInteractorStyle::OnRightButtonDown() int* pos = this->GetInteractor()->GetEventPosition(); vtkSmartPointer<vtkCellPicker> picker = - vtkSmartPointer<vtkCellPicker>::New(); + vtkSmartPointer<vtkCellPicker>::New(); picker->SetTolerance(0.0005); // Pick from this location. @@ -248,11 +261,11 @@ void VtkCustomInteractorStyle::OnRightButtonDown() double* worldPosition = picker->GetPickPosition(); INFO("Cell id is: {:d}", picker->GetCellId()); - if(picker->GetCellId() != -1) + if (picker->GetCellId() != -1) { - vtkRenderer* renderer = - this->Interactor->GetRenderWindow()->GetRenderers()-> - GetFirstRenderer(); + vtkRenderer* renderer = this->Interactor->GetRenderWindow() + ->GetRenderers() + ->GetFirstRenderer(); vtkCamera* cam = renderer->GetActiveCamera(); cam->SetFocalPoint(worldPosition); emit requestViewUpdate(); diff --git a/Applications/DataExplorer/VtkVis/VtkFilterFactory.cpp b/Applications/DataExplorer/VtkVis/VtkFilterFactory.cpp index 5fe3f349e12e5c282809d86a271c3103a0a1e256..1e7a8c10686682371d3d26be29dc349df1533848 100644 --- a/Applications/DataExplorer/VtkVis/VtkFilterFactory.cpp +++ b/Applications/DataExplorer/VtkVis/VtkFilterFactory.cpp @@ -15,6 +15,8 @@ // ** INCLUDES ** #include "VtkFilterFactory.h" +#include <vtkDataSetSurfaceFilter.h> + #include "VtkCompositeColorByHeightFilter.h" #include "VtkCompositeColormapToImageFilter.h" #include "VtkCompositeContourFilter.h" @@ -30,60 +32,60 @@ #include "VtkCompositeThresholdFilter.h" #include "VtkImageDataToLinePolyDataFilter.h" -#include <vtkDataSetSurfaceFilter.h> - QVector<VtkFilterInfo> VtkFilterFactory::GetFilterList() { QVector<VtkFilterInfo> filterList; // Composite filters - filterList.push_back(VtkFilterInfo( - "VtkCompositeImageToCylindersFilter", - "Image to bar chart", - "This filter converts the red pixel values of the image into a bar graph.", - VTK_IMAGE_DATA, VTK_POLY_DATA)); - - filterList.push_back(VtkFilterInfo( - "VtkCompositePointToGlyphFilter", - "Points to spheres", - "This filter generates spheres on point data that can be scaled and colored by scalar data.", - VTK_POLY_DATA, VTK_POLY_DATA)); - - filterList.push_back(VtkFilterInfo( - "VtkCompositeLineToTubeFilter", - "Lines to tubes", - "This filter will convert lines to tubes that can be colored by scalar data.", - VTK_POLY_DATA, VTK_POLY_DATA)); + filterList.push_back(VtkFilterInfo("VtkCompositeImageToCylindersFilter", + "Image to bar chart", + "This filter converts the red pixel " + "values of the image into a bar graph.", + VTK_IMAGE_DATA, VTK_POLY_DATA)); + + filterList.push_back( + VtkFilterInfo("VtkCompositePointToGlyphFilter", "Points to spheres", + "This filter generates spheres on point data that can be " + "scaled and colored by scalar data.", + VTK_POLY_DATA, VTK_POLY_DATA)); + + filterList.push_back( + VtkFilterInfo("VtkCompositeLineToTubeFilter", "Lines to tubes", + "This filter will convert lines to tubes that can be " + "colored by scalar data.", + VTK_POLY_DATA, VTK_POLY_DATA)); filterList.push_back(VtkFilterInfo( - "VtkCompositeColormapToImageFilter", - "Apply lookup table to image", - "This filter will take an input image of any valid scalar type, and map the first component of the image through a lookup table.", - VTK_IMAGE_DATA, VTK_IMAGE_DATA)); + "VtkCompositeColormapToImageFilter", "Apply lookup table to image", + "This filter will take an input image of any valid scalar type, and " + "map the first component of the image through a lookup table.", + VTK_IMAGE_DATA, VTK_IMAGE_DATA)); filterList.push_back(VtkFilterInfo( - "VtkCompositeTextureOnSurfaceFilter", - "Apply texture to surface", - "This filter assigns an image or raster file as a texture for the given surface.", - VTK_POINT_SET, VTK_POLY_DATA)); + "VtkCompositeTextureOnSurfaceFilter", "Apply texture to surface", + "This filter assigns an image or raster file as a texture for the " + "given surface.", + VTK_POINT_SET, VTK_POLY_DATA)); filterList.push_back(VtkFilterInfo( - "VtkCompositeThresholdFilter", - "Extract cells by threshold", - "This filter extracts cells from any dataset type that satisfy a threshold criterion. A cell satisfies the criterion if the (first) scalar value of (every or any) point satisfies the criterion. For example this can be used to show only certain material groups in a mesh.", - VTK_POINT_SET, VTK_UNSTRUCTURED_GRID)); + "VtkCompositeThresholdFilter", "Extract cells by threshold", + "This filter extracts cells from any dataset type that satisfy a " + "threshold criterion. A cell satisfies the criterion if the (first) " + "scalar value of (every or any) point satisfies the criterion. For " + "example this can be used to show only certain material groups in a " + "mesh.", + VTK_POINT_SET, VTK_UNSTRUCTURED_GRID)); filterList.push_back(VtkFilterInfo( - "VtkCompositeColorByHeightFilter", - "Elevation-based colouring", - "This filter will generate scalar values based on the elevation of each point in the dataset.", - VTK_POINT_SET, VTK_POLY_DATA)); + "VtkCompositeColorByHeightFilter", "Elevation-based colouring", + "This filter will generate scalar values based on the elevation of " + "each point in the dataset.", + VTK_POINT_SET, VTK_POLY_DATA)); filterList.push_back(VtkFilterInfo( - "VtkCompositeContourFilter", - "Generate contours based on scalar fields", - "Visualisation of contour-lines/-planes within dense scalar fields.", - VTK_UNSTRUCTURED_GRID, VTK_UNSTRUCTURED_GRID)); + "VtkCompositeContourFilter", "Generate contours based on scalar fields", + "Visualisation of contour-lines/-planes within dense scalar fields.", + VTK_UNSTRUCTURED_GRID, VTK_UNSTRUCTURED_GRID)); filterList.push_back(VtkFilterInfo( "VtkCompositeImageToPointCloudFilter", "Image to point cloud", @@ -99,29 +101,29 @@ QVector<VtkFilterInfo> VtkFilterFactory::GetFilterList() // Simple filters filterList.push_back(VtkFilterInfo( - "VtkImageDataToLinePolyDataFilter", - "Image to vertical lines", - "This filter converts the red pixel values of the image to lines with length of the value.", - VTK_IMAGE_DATA, VTK_POLY_DATA)); + "VtkImageDataToLinePolyDataFilter", "Image to vertical lines", + "This filter converts the red pixel values of the image to lines with " + "length of the value.", + VTK_IMAGE_DATA, VTK_POLY_DATA)); // Standard VTK filter without properties - filterList.push_back(VtkFilterInfo( - "vtkDataSetSurfaceFilter", - "Surface filter", - "Extracts outer (polygonal) surface.", - VTK_UNSTRUCTURED_GRID, VTK_POLY_DATA)); - -// filterList.push_back(VtkFilterInfo( -// "VtkCompositeSelectionFilter", -// "Mesh Quality Filter", -// "This filter calculates the quality of meshes and highlights deformed elements.", -// VTK_UNSTRUCTURED_GRID, VTK_UNSTRUCTURED_GRID)); + filterList.push_back(VtkFilterInfo("vtkDataSetSurfaceFilter", + "Surface filter", + "Extracts outer (polygonal) surface.", + VTK_UNSTRUCTURED_GRID, VTK_POLY_DATA)); + + // filterList.push_back(VtkFilterInfo( + // "VtkCompositeSelectionFilter", + // "Mesh Quality Filter", + // "This filter calculates the quality of meshes and highlights + // deformed elements.", VTK_UNSTRUCTURED_GRID, + // VTK_UNSTRUCTURED_GRID)); return filterList; } -VtkCompositeFilter* VtkFilterFactory::CreateCompositeFilter( QString type, - vtkAlgorithm* inputAlgorithm ) +VtkCompositeFilter* VtkFilterFactory::CreateCompositeFilter( + QString type, vtkAlgorithm* inputAlgorithm) { if (type.compare(QString("VtkCompositeImageToCylindersFilter")) == 0) { @@ -179,7 +181,7 @@ VtkCompositeFilter* VtkFilterFactory::CreateCompositeFilter( QString type, return nullptr; } -vtkAlgorithm* VtkFilterFactory::CreateSimpleFilter( QString type ) +vtkAlgorithm* VtkFilterFactory::CreateSimpleFilter(QString type) { if (type.compare(QString("VtkImageDataToLinePolyDataFilter")) == 0) { diff --git a/Applications/DataExplorer/VtkVis/VtkGeoImageSource.cpp b/Applications/DataExplorer/VtkVis/VtkGeoImageSource.cpp index edae06f821d1b4445a826d6a92193bf0b794b801..b5cc0a1962714af008e287523d7cac353055f930 100644 --- a/Applications/DataExplorer/VtkVis/VtkGeoImageSource.cpp +++ b/Applications/DataExplorer/VtkVis/VtkGeoImageSource.cpp @@ -16,16 +16,16 @@ #include "VtkGeoImageSource.h" //#include "OGSRaster.h" -#include "VtkRaster.h" - #include <vtkFloatArray.h> #include <vtkImageChangeInformation.h> #include <vtkImageData.h> #include <vtkImageImport.h> #include <vtkImageShiftScale.h> +#include <vtkIntArray.h> #include <vtkObjectFactory.h> #include <vtkPointData.h> -#include <vtkIntArray.h> + +#include "VtkRaster.h" vtkStandardNewMacro(VtkGeoImageSource); @@ -37,19 +37,21 @@ vtkStandardNewMacro(VtkGeoImageSource); // This is not always the case. template <class IT> void vtkSimpleImageFilterExampleExecute(vtkImageData* input, - vtkImageData* output, - IT* inPtr, IT* outPtr) + vtkImageData* output, IT* inPtr, + IT* outPtr) { int dims[3]; input->GetDimensions(dims); if (input->GetScalarType() != output->GetScalarType()) { - vtkGenericWarningMacro(<< "Execute: input ScalarType, " << input->GetScalarType() - << ", must match out ScalarType " << output->GetScalarType()); + vtkGenericWarningMacro( + << "Execute: input ScalarType, " << input->GetScalarType() + << ", must match out ScalarType " << output->GetScalarType()); return; } // HACK LB Multiply by number of scalar components due to RGBA values ????? - int size = dims[0] * dims[1] * dims[2] * input->GetNumberOfScalarComponents(); + int size = + dims[0] * dims[1] * dims[2] * input->GetNumberOfScalarComponents(); for (int i = 0; i < size; i++) { @@ -72,9 +74,9 @@ void VtkGeoImageSource::PrintSelf(ostream& os, vtkIndent indent) this->Superclass::PrintSelf(os, indent); } -bool VtkGeoImageSource::readImage(const QString &filename) +bool VtkGeoImageSource::readImage(const QString& filename) { - vtkImageAlgorithm* img (VtkRaster::loadImage(filename.toStdString())); + vtkImageAlgorithm* img(VtkRaster::loadImage(filename.toStdString())); if (img == nullptr) { return false; @@ -83,7 +85,7 @@ bool VtkGeoImageSource::readImage(const QString &filename) return true; } -void VtkGeoImageSource::setImage(vtkImageAlgorithm* image, const QString &name) +void VtkGeoImageSource::setImage(vtkImageAlgorithm* image, const QString& name) { this->_imageSource = image; this->SetInputConnection(_imageSource->GetOutputPort()); @@ -100,19 +102,19 @@ void VtkGeoImageSource::SimpleExecute(vtkImageData* input, vtkImageData* output) vtkDebugMacro(<< "Executing VtkGeoImageSource"); void* inPtr = input->GetScalarPointer(); void* outPtr = output->GetScalarPointer(); - switch(output->GetScalarType()) + switch (output->GetScalarType()) { // This is simply a #define for a big case list. // It handles all data types that VTK supports. vtkTemplateMacro(vtkSimpleImageFilterExampleExecute( - input, output, (VTK_TT*)(inPtr), (VTK_TT*)(outPtr))); - default: - vtkGenericWarningMacro("Execute: Unknown input ScalarType"); - return; + input, output, (VTK_TT*)(inPtr), (VTK_TT*)(outPtr))); + default: + vtkGenericWarningMacro("Execute: Unknown input ScalarType"); + return; } } -void VtkGeoImageSource::SetUserProperty( QString name, QVariant value ) +void VtkGeoImageSource::SetUserProperty(QString name, QVariant value) { Q_UNUSED(name); Q_UNUSED(value); diff --git a/Applications/DataExplorer/VtkVis/VtkImageDataToLinePolyDataFilter.cpp b/Applications/DataExplorer/VtkVis/VtkImageDataToLinePolyDataFilter.cpp index ea1c786c9f31d756bb949cfbd5a1857bf670b1ec..0ee1a536bad663b26fe886b3f637a5081dd5fdd1 100644 --- a/Applications/DataExplorer/VtkVis/VtkImageDataToLinePolyDataFilter.cpp +++ b/Applications/DataExplorer/VtkVis/VtkImageDataToLinePolyDataFilter.cpp @@ -56,8 +56,10 @@ int VtkImageDataToLinePolyDataFilter::RequestData( vtkInformation* inInfo = inputVector[0]->GetInformationObject(0); vtkInformation* outInfo = outputVector->GetInformationObject(0); - vtkImageData* input = vtkImageData::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT())); - vtkPolyData* output = vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); + vtkImageData* input = + vtkImageData::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT())); + vtkPolyData* output = + vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); void* inScalarPtr = input->GetScalarPointer(); int numScalarComponents = input->GetNumberOfScalarComponents(); @@ -98,7 +100,8 @@ int VtkImageDataToLinePolyDataFilter::RequestData( double dir[3] = {0, 0, 1}; - // Traverse all points creating another point with scalar distance in Z direction + // Traverse all points creating another point with scalar distance in Z + // direction for (vtkIdType ptId = 0; ptId < numPts; ++ptId) { // Skip translucent pixels @@ -153,8 +156,7 @@ int VtkImageDataToLinePolyDataFilter::RequestData( // Avoid keeping extra memory around output->Squeeze(); - vtkDebugMacro(<< "Created: " - << newPts->GetNumberOfPoints() << " points, " + vtkDebugMacro(<< "Created: " << newPts->GetNumberOfPoints() << " points, " << output->GetNumberOfCells() << " lines"); return 1; diff --git a/Applications/DataExplorer/VtkVis/VtkImageDataToPointCloudFilter.cpp b/Applications/DataExplorer/VtkVis/VtkImageDataToPointCloudFilter.cpp index 6df9350a29054ca660dda00d4e51b58e614c909a..bd29889d3c62feea90e7eec3c485b31896b7e147 100644 --- a/Applications/DataExplorer/VtkVis/VtkImageDataToPointCloudFilter.cpp +++ b/Applications/DataExplorer/VtkVis/VtkImageDataToPointCloudFilter.cpp @@ -11,9 +11,6 @@ // ** INCLUDES ** #include "VtkImageDataToPointCloudFilter.h" -#include <algorithm> -#include <vector> - #include <vtkDoubleArray.h> #include <vtkIdList.h> #include <vtkImageData.h> @@ -25,6 +22,9 @@ #include <vtkPolyData.h> #include <vtkSmartPointer.h> +#include <algorithm> +#include <vector> + vtkStandardNewMacro(VtkImageDataToPointCloudFilter); VtkImageDataToPointCloudFilter::VtkImageDataToPointCloudFilter() = default; @@ -57,7 +57,8 @@ int VtkImageDataToPointCloudFilter::RequestData( if (input->GetScalarSize() != sizeof(float)) { - vtkDebugMacro("Existing data does not have float-type and cannot be processed. " + vtkDebugMacro( + "Existing data does not have float-type and cannot be processed. " "Aborting filter process..."); return 0; } @@ -120,7 +121,8 @@ int VtkImageDataToPointCloudFilter::RequestData( new_points->SetNumberOfPoints(sum); vtkSmartPointer<vtkCellArray> cells = vtkSmartPointer<vtkCellArray>::New(); cells->Allocate(sum); - vtkSmartPointer<vtkDoubleArray> intensity = vtkSmartPointer<vtkDoubleArray>::New(); + vtkSmartPointer<vtkDoubleArray> intensity = + vtkSmartPointer<vtkDoubleArray>::New(); intensity->Allocate(sum); intensity->SetName("Intensity"); double const half_cellsize(spacing[0] / 2.0); @@ -149,10 +151,12 @@ int VtkImageDataToPointCloudFilter::RequestData( output->SetPoints(new_points); output->SetVerts(cells); output->GetPointData()->AddArray(intensity); - output->GetPointData()->SetActiveAttribute("Intensity", vtkDataSetAttributes::SCALARS); + output->GetPointData()->SetActiveAttribute("Intensity", + vtkDataSetAttributes::SCALARS); output->Squeeze(); - vtkDebugMacro(<< "Created " << new_points->GetNumberOfPoints() << " points."); + vtkDebugMacro(<< "Created " << new_points->GetNumberOfPoints() + << " points."); return 1; } @@ -176,7 +180,8 @@ void VtkImageDataToPointCloudFilter::createPoints( } } -double VtkImageDataToPointCloudFilter::getRandomNumber(double const& min, double const& max) const +double VtkImageDataToPointCloudFilter::getRandomNumber(double const& min, + double const& max) const { return (static_cast<double>(std::rand()) / RAND_MAX) * (max - min) + min; } @@ -189,6 +194,7 @@ std::size_t VtkImageDataToPointCloudFilter::interpolate(double low, p = std::clamp(p, low, high); double const r = (p - low) / (high - low); return static_cast<std::size_t>( - (MaxNumberOfPointsPerCell - MinNumberOfPointsPerCell) * std::pow(r, gamma) + - MinNumberOfPointsPerCell); + (MaxNumberOfPointsPerCell - MinNumberOfPointsPerCell) * + std::pow(r, gamma) + + MinNumberOfPointsPerCell); } diff --git a/Applications/DataExplorer/VtkVis/VtkImageDataToSurfacePointsFilter.cpp b/Applications/DataExplorer/VtkVis/VtkImageDataToSurfacePointsFilter.cpp index 5ca4010daf9ad2e9d0d7c806cea9b0ca47d36a4c..8adbdc9ea912a25a8bf6a6210c4b994676f9dacb 100644 --- a/Applications/DataExplorer/VtkVis/VtkImageDataToSurfacePointsFilter.cpp +++ b/Applications/DataExplorer/VtkVis/VtkImageDataToSurfacePointsFilter.cpp @@ -11,9 +11,6 @@ // ** INCLUDES ** #include "VtkImageDataToSurfacePointsFilter.h" -#include <algorithm> -#include <vector> - #include <vtkIdList.h> #include <vtkImageData.h> #include <vtkInformation.h> @@ -24,6 +21,9 @@ #include <vtkPolyData.h> #include <vtkSmartPointer.h> +#include <algorithm> +#include <vector> + vtkStandardNewMacro(VtkImageDataToSurfacePointsFilter); VtkImageDataToSurfacePointsFilter::VtkImageDataToSurfacePointsFilter() = @@ -80,7 +80,8 @@ int VtkImageDataToSurfacePointsFilter::RequestData( input->GetDimensions(dimensions); double origin[3]; input->GetOrigin(origin); - MathLib::Point3d const ll(std::array<double, 3>{{origin[0], origin[1], origin[2]}}); + MathLib::Point3d const ll( + std::array<double, 3>{{origin[0], origin[1], origin[2]}}); std::vector<double> pixels; pixels.reserve(n_points); @@ -137,7 +138,8 @@ int VtkImageDataToSurfacePointsFilter::RequestData( output->SetVerts(cells); output->Squeeze(); - vtkDebugMacro(<< "Created " << new_points->GetNumberOfPoints() << " points."); + vtkDebugMacro(<< "Created " << new_points->GetNumberOfPoints() + << " points."); return 1; } @@ -163,7 +165,8 @@ void VtkImageDataToSurfacePointsFilter::createPointSurface( } } -double VtkImageDataToSurfacePointsFilter::getRandomNumber(double const& min, double const& max) const +double VtkImageDataToSurfacePointsFilter::getRandomNumber( + double const& min, double const& max) const { return (static_cast<double>(std::rand()) / RAND_MAX) * (max - min) + min; } diff --git a/Applications/DataExplorer/VtkVis/VtkPointsSource.cpp b/Applications/DataExplorer/VtkVis/VtkPointsSource.cpp index 041c6f1de7699e1486acc7735689927269f89b0f..6817df014aacd96d194d1467fde08009e145afc5 100644 --- a/Applications/DataExplorer/VtkVis/VtkPointsSource.cpp +++ b/Applications/DataExplorer/VtkVis/VtkPointsSource.cpp @@ -14,57 +14,57 @@ #include "VtkPointsSource.h" -#include "BaseLib/Logging.h" - #include <vtkCellArray.h> +#include <vtkCellData.h> #include <vtkInformation.h> #include <vtkInformationVector.h> #include <vtkObjectFactory.h> #include <vtkPointData.h> #include <vtkPoints.h> #include <vtkPolyData.h> +#include <vtkProperty.h> #include <vtkSmartPointer.h> #include <vtkStreamingDemandDrivenPipeline.h> -#include <vtkCellData.h> -#include <vtkProperty.h> #include "Applications/DataHolderLib/Color.h" +#include "BaseLib/Logging.h" vtkStandardNewMacro(VtkPointsSource); VtkPointsSource::VtkPointsSource() { - _removable = false; // From VtkAlgorithmProperties + _removable = false; // From VtkAlgorithmProperties this->SetNumberOfInputPorts(0); const DataHolderLib::Color c = DataHolderLib::getRandomColor(); - GetProperties()->SetColor(c[0] / 255.0,c[1] / 255.0,c[2] / 255.0); + GetProperties()->SetColor(c[0] / 255.0, c[1] / 255.0, c[2] / 255.0); } -void VtkPointsSource::PrintSelf( ostream& os, vtkIndent indent ) +void VtkPointsSource::PrintSelf(ostream& os, vtkIndent indent) { - this->Superclass::PrintSelf(os,indent); + this->Superclass::PrintSelf(os, indent); if (_points->empty()) { return; } - os << indent << "== VtkPointsSource ==" << "\n"; + os << indent << "== VtkPointsSource ==" + << "\n"; int i = 0; for (auto point : *_points) { const double* coords = point->getCoords(); - os << indent << "Point " << i << " (" << coords[0] << ", " << coords[1] << ", " << - coords[2] << ")\n"; + os << indent << "Point " << i << " (" << coords[0] << ", " << coords[1] + << ", " << coords[2] << ")\n"; i++; } } -int VtkPointsSource::RequestData( vtkInformation* request, - vtkInformationVector** inputVector, - vtkInformationVector* outputVector ) +int VtkPointsSource::RequestData(vtkInformation* request, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector) { (void)request; (void)inputVector; @@ -80,12 +80,14 @@ int VtkPointsSource::RequestData( vtkInformation* request, return 0; } - vtkSmartPointer<vtkInformation> outInfo = outputVector->GetInformationObject(0); + vtkSmartPointer<vtkInformation> outInfo = + outputVector->GetInformationObject(0); vtkSmartPointer<vtkPolyData> output = - vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); + vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); vtkSmartPointer<vtkPoints> newPoints = vtkSmartPointer<vtkPoints>::New(); - vtkSmartPointer<vtkCellArray> newVerts = vtkSmartPointer<vtkCellArray>::New(); + vtkSmartPointer<vtkCellArray> newVerts = + vtkSmartPointer<vtkCellArray>::New(); newPoints->SetNumberOfPoints(numPoints); newVerts->Allocate(numPoints); @@ -116,19 +118,20 @@ int VtkPointsSource::RequestData( vtkInformation* request, output->SetPoints(newPoints); output->SetVerts(newVerts); output->GetCellData()->AddArray(pointIDs); - output->GetCellData()->SetActiveAttribute("PointIDs", vtkDataSetAttributes::SCALARS); + output->GetCellData()->SetActiveAttribute("PointIDs", + vtkDataSetAttributes::SCALARS); return 1; } -int VtkPointsSource::RequestInformation( vtkInformation* /*request*/, - vtkInformationVector** /*inputVector*/, - vtkInformationVector* /*outputVector*/ ) +int VtkPointsSource::RequestInformation(vtkInformation* /*request*/, + vtkInformationVector** /*inputVector*/, + vtkInformationVector* /*outputVector*/) { return 1; } -void VtkPointsSource::SetUserProperty( QString name, QVariant value ) +void VtkPointsSource::SetUserProperty(QString name, QVariant value) { Q_UNUSED(name); Q_UNUSED(value); diff --git a/Applications/DataExplorer/VtkVis/VtkPolylinesSource.cpp b/Applications/DataExplorer/VtkVis/VtkPolylinesSource.cpp index c3d5226cbafa82e6effd9c8f5bab521aea0d3147..03278132371e0983c7c1f6f70368904937ed8620 100644 --- a/Applications/DataExplorer/VtkVis/VtkPolylinesSource.cpp +++ b/Applications/DataExplorer/VtkVis/VtkPolylinesSource.cpp @@ -15,8 +15,6 @@ // ** INCLUDES ** #include "VtkPolylinesSource.h" -#include "BaseLib/Logging.h" - #include <vtkCellArray.h> #include <vtkCellData.h> #include <vtkInformation.h> @@ -29,16 +27,15 @@ #include <vtkSmartPointer.h> #include <vtkStreamingDemandDrivenPipeline.h> -#include "Polyline.h" - #include "Applications/DataHolderLib/Color.h" - +#include "BaseLib/Logging.h" +#include "Polyline.h" vtkStandardNewMacro(VtkPolylinesSource); VtkPolylinesSource::VtkPolylinesSource() { - _removable = false; // From VtkAlgorithmProperties + _removable = false; // From VtkAlgorithmProperties this->SetNumberOfInputPorts(0); const DataHolderLib::Color c = DataHolderLib::getRandomColor(); @@ -47,9 +44,9 @@ VtkPolylinesSource::VtkPolylinesSource() VtkPolylinesSource::~VtkPolylinesSource() = default; -void VtkPolylinesSource::PrintSelf( ostream& os, vtkIndent indent ) +void VtkPolylinesSource::PrintSelf(ostream& os, vtkIndent indent) { - this->Superclass::PrintSelf(os,indent); + this->Superclass::PrintSelf(os, indent); if (_polylines->empty()) { @@ -58,21 +55,22 @@ void VtkPolylinesSource::PrintSelf( ostream& os, vtkIndent indent ) for (auto polyline : *_polylines) { - os << indent << "== Polyline ==" << "\n"; + os << indent << "== Polyline ==" + << "\n"; int numPoints = polyline->getNumberOfPoints(); for (int i = 0; i < numPoints; i++) { const GeoLib::Point* point = polyline->getPoint(i); const double* coords = point->getCoords(); - os << indent << "Point " << i << " (" << coords[0] << ", " << coords[1] << - ", " << coords[2] << ")\n"; + os << indent << "Point " << i << " (" << coords[0] << ", " + << coords[1] << ", " << coords[2] << ")\n"; } } } -int VtkPolylinesSource::RequestData( vtkInformation* request, - vtkInformationVector** inputVector, - vtkInformationVector* outputVector ) +int VtkPolylinesSource::RequestData(vtkInformation* request, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector) { (void)request; (void)inputVector; @@ -87,15 +85,17 @@ int VtkPolylinesSource::RequestData( vtkInformation* request, return 0; } - vtkSmartPointer<vtkInformation> outInfo = outputVector->GetInformationObject(0); + vtkSmartPointer<vtkInformation> outInfo = + outputVector->GetInformationObject(0); vtkSmartPointer<vtkPolyData> output = - vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); + vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); vtkSmartPointer<vtkPoints> newPoints = vtkSmartPointer<vtkPoints>::New(); - vtkSmartPointer<vtkCellArray> newLines = vtkSmartPointer<vtkCellArray>::New(); + vtkSmartPointer<vtkCellArray> newLines = + vtkSmartPointer<vtkCellArray>::New(); - //newPoints->Allocate(numPoints); - //newLines->Allocate(newLines->EstimateSize(numLines, 2)); + // newPoints->Allocate(numPoints); + // newLines->Allocate(newLines->EstimateSize(numLines, 2)); if (outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()) > 0) @@ -107,15 +107,15 @@ int VtkPolylinesSource::RequestData( vtkInformation* request, plyIDs->SetNumberOfComponents(1); plyIDs->SetName("PolylineIDs"); - unsigned lastMaxIndex (0); - const std::size_t nPolylines (_polylines->size()); + unsigned lastMaxIndex(0); + const std::size_t nPolylines(_polylines->size()); for (std::size_t j = 0; j < nPolylines; j++) { const int numPoints = (*_polylines)[j]->getNumberOfPoints(); const bool isClosed = (*_polylines)[j]->isClosed(); // Generate points - const int numVerts = (isClosed) ? numPoints-1 : numPoints; + const int numVerts = (isClosed) ? numPoints - 1 : numPoints; for (int i = 0; i < numVerts; i++) { const GeoLib::Point* point = (*_polylines)[j]->getPoint(i); @@ -142,20 +142,22 @@ int VtkPolylinesSource::RequestData( vtkInformation* request, output->SetPoints(newPoints); output->SetLines(newLines); output->GetCellData()->AddArray(plyIDs); - output->GetCellData()->SetActiveAttribute("PolylineIDs", vtkDataSetAttributes::SCALARS); + output->GetCellData()->SetActiveAttribute("PolylineIDs", + vtkDataSetAttributes::SCALARS); output->Squeeze(); return 1; } -int VtkPolylinesSource::RequestInformation( vtkInformation* /*request*/, - vtkInformationVector** /*inputVector*/, - vtkInformationVector* /*outputVector*/ ) +int VtkPolylinesSource::RequestInformation( + vtkInformation* /*request*/, + vtkInformationVector** /*inputVector*/, + vtkInformationVector* /*outputVector*/) { return 1; } -void VtkPolylinesSource::SetUserProperty( QString name, QVariant value ) +void VtkPolylinesSource::SetUserProperty(QString name, QVariant value) { Q_UNUSED(name); Q_UNUSED(value); diff --git a/Applications/DataExplorer/VtkVis/VtkRaster.cpp b/Applications/DataExplorer/VtkVis/VtkRaster.cpp index 2df3218025f6f5adb42ed3282188d994b9e3d677..44429ee0f537f92c5f7bc884330556411a566165 100644 --- a/Applications/DataExplorer/VtkVis/VtkRaster.cpp +++ b/Applications/DataExplorer/VtkVis/VtkRaster.cpp @@ -14,12 +14,6 @@ #include "VtkRaster.h" -#include <algorithm> -#include <cmath> -#include <limits> - -#include <QFileInfo> - #include <vtkBMPReader.h> #include <vtkImageData.h> #include <vtkImageImport.h> @@ -28,9 +22,14 @@ #include <vtkPNGReader.h> #include <vtkTIFFReader.h> +#include <QFileInfo> +#include <algorithm> +#include <cmath> +#include <limits> + #ifdef GEOTIFF_FOUND -#include "geo_tiffp.h" -#include "xtiffio.h" +#include <geo_tiffp.h> +#include <xtiffio.h> #endif #include <memory> @@ -41,14 +40,15 @@ #include "BaseLib/StringTools.h" #include "GeoLib/Raster.h" -vtkImageAlgorithm* VtkRaster::loadImage(const std::string &fileName) +vtkImageAlgorithm* VtkRaster::loadImage(const std::string& fileName) { QFileInfo fileInfo(QString::fromStdString(fileName)); std::unique_ptr<GeoLib::Raster> raster(nullptr); if (fileInfo.suffix().toLower() == "asc") { - raster.reset(FileIO::AsciiRasterInterface::getRasterFromASCFile(fileName)); + raster.reset( + FileIO::AsciiRasterInterface::getRasterFromASCFile(fileName)); } else if (fileInfo.suffix().toLower() == "grd") { @@ -74,18 +74,21 @@ vtkImageAlgorithm* VtkRaster::loadImage(const std::string &fileName) return loadImageFromFile(fileName); } -vtkImageImport* VtkRaster::loadImageFromArray(double const*const data_array, GeoLib::RasterHeader header) +vtkImageImport* VtkRaster::loadImageFromArray(double const* const data_array, + GeoLib::RasterHeader header) { const unsigned length = header.n_rows * header.n_cols * header.n_depth; auto* data = new float[length * 2]; - float max_val = static_cast<float>(*std::max_element(data_array, data_array+length)); - for (unsigned j=0; j<length; ++j) + float max_val = + static_cast<float>(*std::max_element(data_array, data_array + length)); + for (unsigned j = 0; j < length; ++j) { - data[j*2] = static_cast<float>(data_array[j]); - if (fabs(data[j*2]-header.no_data) < std::numeric_limits<double>::epsilon()) + data[j * 2] = static_cast<float>(data_array[j]); + if (fabs(data[j * 2] - header.no_data) < + std::numeric_limits<double>::epsilon()) { - data[j*2] = max_val; - data[j*2+1] = 0; + data[j * 2] = max_val; + data[j * 2 + 1] = 0; } else { @@ -94,17 +97,19 @@ vtkImageImport* VtkRaster::loadImageFromArray(double const*const data_array, Geo } vtkImageImport* image = vtkImageImport::New(); - image->SetDataSpacing(header.cell_size, header.cell_size, header.cell_size); - image->SetDataOrigin(header.origin[0]+(header.cell_size/2.0), header.origin[1]+(header.cell_size/2.0), 0); // translate whole mesh by half a pixel in x and y - image->SetWholeExtent(0, header.n_cols - 1, 0, header.n_rows - 1, 0, - header.n_depth - 1); - image->SetDataExtent(0, header.n_cols - 1, 0, header.n_rows - 1, 0, - header.n_depth - 1); - image->SetDataExtentToWholeExtent(); - image->SetDataScalarTypeToFloat(); - image->SetNumberOfScalarComponents(2); - image->SetImportVoidPointer(data, 0); - image->Update(); + image->SetDataSpacing(header.cell_size, header.cell_size, header.cell_size); + image->SetDataOrigin(header.origin[0] + (header.cell_size / 2.0), + header.origin[1] + (header.cell_size / 2.0), + 0); // translate whole mesh by half a pixel in x and y + image->SetWholeExtent(0, header.n_cols - 1, 0, header.n_rows - 1, 0, + header.n_depth - 1); + image->SetDataExtent(0, header.n_cols - 1, 0, header.n_rows - 1, 0, + header.n_depth - 1); + image->SetDataExtentToWholeExtent(); + image->SetDataScalarTypeToFloat(); + image->SetNumberOfScalarComponents(2); + image->SetImportVoidPointer(data, 0); + image->Update(); return image; } @@ -119,7 +124,7 @@ vtkImageAlgorithm* VtkRaster::loadImageFromTIFF(const std::string& fileName) GTIF* geoTiff = GTIFNew(tiff); int version[3]; - int count (0); + int count(0); GTIFDirectoryInfo(geoTiff, version, &count); if (count == 0) @@ -137,7 +142,8 @@ vtkImageAlgorithm* VtkRaster::loadImageFromTIFF(const std::string& fileName) double* pnts = nullptr; // get actual number of images in the tiff file - do { + do + { ++nImages; } while (TIFFReadDirectory(tiff)); if (nImages > 1) @@ -147,15 +153,18 @@ vtkImageAlgorithm* VtkRaster::loadImageFromTIFF(const std::string& fileName) nImages); // get image size - TIFFGetField(tiff, TIFFTAG_IMAGEWIDTH, &imgWidth); + TIFFGetField(tiff, TIFFTAG_IMAGEWIDTH, &imgWidth); TIFFGetField(tiff, TIFFTAG_IMAGELENGTH, &imgHeight); // get cellsize - // Note: GeoTiff allows anisotropic pixels. This is not supported here and equilateral pixels are assumed. + // Note: GeoTiff allows anisotropic pixels. This is not supported + // here and equilateral pixels are assumed. if (TIFFGetField(tiff, GTIFF_PIXELSCALE, &pntCount, &pnts)) { if (pnts[0] != pnts[1]) - WARN("VtkRaster::loadImageFromTIFF(): Original raster data has anisotrop pixel size!"); + WARN( + "VtkRaster::loadImageFromTIFF(): Original raster data " + "has anisotrop pixel size!"); cellsize = pnts[0]; } @@ -163,7 +172,9 @@ vtkImageAlgorithm* VtkRaster::loadImageFromTIFF(const std::string& fileName) if (TIFFGetField(tiff, GTIFF_TIEPOINTS, &pntCount, &pnts)) { x0 = pnts[3]; - y0 = pnts[4] - (imgHeight * cellsize); // the origin should be the lower left corner of the img + y0 = pnts[4] - + (imgHeight * cellsize); // the origin should be the lower + // left corner of the img } // read pixel values @@ -173,7 +184,8 @@ vtkImageAlgorithm* VtkRaster::loadImageFromTIFF(const std::string& fileName) { if (!TIFFReadRGBAImage(tiff, imgWidth, imgHeight, pixVal, 0)) { - ERR("VtkRaster::loadImageFromTIFF(): reading GeoTIFF file."); + ERR("VtkRaster::loadImageFromTIFF(): reading GeoTIFF " + "file."); _TIFFfree(pixVal); GTIFFree(geoTiff); XTIFFClose(tiff); @@ -185,12 +197,10 @@ vtkImageAlgorithm* VtkRaster::loadImageFromTIFF(const std::string& fileName) uint16 photometric; TIFFGetField(tiff, TIFFTAG_PHOTOMETRIC, &photometric); // read colormap - uint16* cmap_red = nullptr, * cmap_green = nullptr, * cmap_blue = nullptr; - int colormap_used = TIFFGetField(tiff, - TIFFTAG_COLORMAP, - &cmap_red, - &cmap_green, - &cmap_blue); + uint16 *cmap_red = nullptr, *cmap_green = nullptr, + *cmap_blue = nullptr; + int colormap_used = TIFFGetField( + tiff, TIFFTAG_COLORMAP, &cmap_red, &cmap_green, &cmap_blue); auto* data = new float[imgWidth * imgHeight * 4]; auto* pxl(new int[4]); @@ -198,33 +208,39 @@ vtkImageAlgorithm* VtkRaster::loadImageFromTIFF(const std::string& fileName) { int lineindex = j * imgWidth; for (int i = 0; i < imgWidth; ++i) - { // scale intensities and set nodata values to white (i.e. the background colour) - unsigned pxl_idx(lineindex+i); - unsigned pos = 4 * (pxl_idx); - if (photometric==1 && colormap_used==1) + { // scale intensities and set nodata values to white (i.e. the + // background colour) + unsigned pxl_idx(lineindex + i); + unsigned pos = 4 * (pxl_idx); + if (photometric == 1 && colormap_used == 1) { int idx = TIFFGetR(pixVal[pxl_idx]); - data[pos] = static_cast<float>(cmap_red[idx] >> 8); - data[pos+1] = static_cast<float>(cmap_green[idx] >> 8); - data[pos+2] = static_cast<float>(cmap_blue[idx] >> 8); - data[pos+3] = 1; + data[pos] = static_cast<float>(cmap_red[idx] >> 8); + data[pos + 1] = + static_cast<float>(cmap_green[idx] >> 8); + data[pos + 2] = static_cast<float>(cmap_blue[idx] >> 8); + data[pos + 3] = 1; } else { - data[pos] = static_cast<float>(TIFFGetR(pixVal[pxl_idx])); - data[pos+1] = static_cast<float>(TIFFGetG(pixVal[pxl_idx])); - data[pos+2] = static_cast<float>(TIFFGetB(pixVal[pxl_idx])); - data[pos+3] = static_cast<float>(TIFFGetA(pixVal[pxl_idx])); + data[pos] = + static_cast<float>(TIFFGetR(pixVal[pxl_idx])); + data[pos + 1] = + static_cast<float>(TIFFGetG(pixVal[pxl_idx])); + data[pos + 2] = + static_cast<float>(TIFFGetB(pixVal[pxl_idx])); + data[pos + 3] = + static_cast<float>(TIFFGetA(pixVal[pxl_idx])); } } } - delete [] pxl; + delete[] pxl; // set transparency values according to maximum pixel value - if (photometric==1) + if (photometric == 1) { float max_val(0); - unsigned nPixels = 4*imgWidth*imgHeight; + unsigned nPixels = 4 * imgWidth * imgHeight; for (unsigned j = 0; j < nPixels; ++j) { if (data[j] > max_val) @@ -240,15 +256,15 @@ vtkImageAlgorithm* VtkRaster::loadImageFromTIFF(const std::string& fileName) } vtkImageImport* image = vtkImageImport::New(); - image->SetDataOrigin(x0, y0, 0); - image->SetDataSpacing(cellsize, cellsize, cellsize); - image->SetWholeExtent(0, imgWidth-1, 0, imgHeight-1, 0, 0); - image->SetDataExtent(0, imgWidth-1, 0, imgHeight-1, 0, 0); - image->SetDataExtentToWholeExtent(); - image->SetDataScalarTypeToFloat(); - image->SetNumberOfScalarComponents(4); - image->SetImportVoidPointer(data, 0); - image->Update(); + image->SetDataOrigin(x0, y0, 0); + image->SetDataSpacing(cellsize, cellsize, cellsize); + image->SetWholeExtent(0, imgWidth - 1, 0, imgHeight - 1, 0, 0); + image->SetDataExtent(0, imgWidth - 1, 0, imgHeight - 1, 0, 0); + image->SetDataExtentToWholeExtent(); + image->SetDataScalarTypeToFloat(); + image->SetNumberOfScalarComponents(4); + image->SetImportVoidPointer(data, 0); + image->Update(); _TIFFfree(pixVal); GTIFFree(geoTiff); @@ -267,9 +283,9 @@ vtkImageAlgorithm* VtkRaster::loadImageFromTIFF(const std::string& fileName) } #endif -vtkImageReader2* VtkRaster::loadImageFromFile(const std::string &fileName) +vtkImageReader2* VtkRaster::loadImageFromFile(const std::string& fileName) { - QString file_name (QString::fromStdString(fileName)); + QString file_name(QString::fromStdString(fileName)); QFileInfo fi(file_name); vtkImageReader2* image(nullptr); diff --git a/Applications/DataExplorer/VtkVis/VtkStationSource.cpp b/Applications/DataExplorer/VtkVis/VtkStationSource.cpp index e3f888b57b11ae6e31c084ff53cfad7b64286ddf..33857343a2b0e3aca88626dafcdcbbaabdeed8c4 100644 --- a/Applications/DataExplorer/VtkVis/VtkStationSource.cpp +++ b/Applications/DataExplorer/VtkVis/VtkStationSource.cpp @@ -15,60 +15,60 @@ // ** VTK INCLUDES ** #include "VtkStationSource.h" -#include "BaseLib/Logging.h" - -#include "StationBorehole.h" - -#include "vtkObjectFactory.h" -#include <vtkDoubleArray.h> #include <vtkCellArray.h> #include <vtkCellData.h> +#include <vtkDoubleArray.h> #include <vtkInformation.h> #include <vtkInformationVector.h> #include <vtkLine.h> #include <vtkPointData.h> #include <vtkPoints.h> #include <vtkPolyData.h> +#include <vtkProperty.h> #include <vtkSmartPointer.h> #include <vtkStreamingDemandDrivenPipeline.h> -#include <vtkProperty.h> + +#include "BaseLib/Logging.h" +#include "StationBorehole.h" +#include "vtkObjectFactory.h" vtkStandardNewMacro(VtkStationSource); VtkStationSource::VtkStationSource() { - _removable = false; // From VtkAlgorithmProperties + _removable = false; // From VtkAlgorithmProperties this->SetNumberOfInputPorts(0); const DataHolderLib::Color c = DataHolderLib::getRandomColor(); GetProperties()->SetColor(c[0] / 255.0, c[1] / 255.0, c[2] / 255.0); } -void VtkStationSource::PrintSelf( ostream& os, vtkIndent indent ) +void VtkStationSource::PrintSelf(ostream& os, vtkIndent indent) { - this->Superclass::PrintSelf(os,indent); + this->Superclass::PrintSelf(os, indent); if (_stations->empty()) { return; } - os << indent << "== VtkStationSource ==" << "\n"; + os << indent << "== VtkStationSource ==" + << "\n"; int i = 0; for (auto station : *_stations) { const double* coords = station->getCoords(); - os << indent << "Station " << i << " (" << coords[0] << ", " << coords[1] << - ", " << coords[2] << ")\n"; + os << indent << "Station " << i << " (" << coords[0] << ", " + << coords[1] << ", " << coords[2] << ")\n"; i++; } } /// Create 3d Station objects -int VtkStationSource::RequestData( vtkInformation* request, - vtkInformationVector** inputVector, - vtkInformationVector* outputVector ) +int VtkStationSource::RequestData(vtkInformation* request, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector) { (void)request; (void)inputVector; @@ -84,10 +84,12 @@ int VtkStationSource::RequestData( vtkInformation* request, } bool useStationValues(false); - double sValue=static_cast<GeoLib::Station*>((*_stations)[0])->getStationValue(); + double sValue = + static_cast<GeoLib::Station*>((*_stations)[0])->getStationValue(); for (std::size_t i = 1; i < nStations; i++) { - if (static_cast<GeoLib::Station*>((*_stations)[i])->getStationValue() != sValue) + if (static_cast<GeoLib::Station*>((*_stations)[i])->getStationValue() != + sValue) { useStationValues = true; break; @@ -97,12 +99,14 @@ int VtkStationSource::RequestData( vtkInformation* request, bool isBorehole = static_cast<GeoLib::Station*>((*_stations)[0])->type() == GeoLib::Station::StationType::BOREHOLE; - vtkSmartPointer<vtkInformation> outInfo = outputVector->GetInformationObject(0); + vtkSmartPointer<vtkInformation> outInfo = + outputVector->GetInformationObject(0); vtkSmartPointer<vtkPolyData> output = - vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); + vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); vtkSmartPointer<vtkPoints> newStations = vtkSmartPointer<vtkPoints>::New(); - vtkSmartPointer<vtkCellArray> newVerts = vtkSmartPointer<vtkCellArray>::New(); + vtkSmartPointer<vtkCellArray> newVerts = + vtkSmartPointer<vtkCellArray>::New(); newVerts->Allocate(nStations); vtkSmartPointer<vtkCellArray> newLines; @@ -118,15 +122,18 @@ int VtkStationSource::RequestData( vtkInformation* request, return 1; } - vtkSmartPointer<vtkIntArray> station_ids = vtkSmartPointer<vtkIntArray>::New(); + vtkSmartPointer<vtkIntArray> station_ids = + vtkSmartPointer<vtkIntArray>::New(); station_ids->SetNumberOfComponents(1); station_ids->SetName("SiteIDs"); - vtkSmartPointer<vtkDoubleArray> station_values = vtkSmartPointer<vtkDoubleArray>::New(); + vtkSmartPointer<vtkDoubleArray> station_values = + vtkSmartPointer<vtkDoubleArray>::New(); station_values->SetNumberOfComponents(1); station_values->SetName("StationValue"); - vtkSmartPointer<vtkIntArray> strat_ids = vtkSmartPointer<vtkIntArray>::New(); + vtkSmartPointer<vtkIntArray> strat_ids = + vtkSmartPointer<vtkIntArray>::New(); strat_ids->SetNumberOfComponents(1); strat_ids->SetName("Stratigraphies"); @@ -187,14 +194,16 @@ int VtkStationSource::RequestData( vtkInformation* request, { output->SetVerts(newVerts); output->GetCellData()->AddArray(station_ids); - output->GetCellData()->SetActiveAttribute("SiteIDs", vtkDataSetAttributes::SCALARS); + output->GetCellData()->SetActiveAttribute( + "SiteIDs", vtkDataSetAttributes::SCALARS); } else { output->SetLines(newLines); - //output->GetCellData()->AddArray(station_ids); + // output->GetCellData()->AddArray(station_ids); output->GetCellData()->AddArray(strat_ids); - output->GetCellData()->SetActiveAttribute("Stratigraphies", vtkDataSetAttributes::SCALARS); + output->GetCellData()->SetActiveAttribute( + "Stratigraphies", vtkDataSetAttributes::SCALARS); } if (useStationValues) { @@ -206,20 +215,20 @@ int VtkStationSource::RequestData( vtkInformation* request, return 1; } -int VtkStationSource::RequestInformation( vtkInformation* /*request*/, - vtkInformationVector** /*inputVector*/, - vtkInformationVector* /*outputVector*/ ) +int VtkStationSource::RequestInformation(vtkInformation* /*request*/, + vtkInformationVector** /*inputVector*/, + vtkInformationVector* /*outputVector*/) { return 1; } -void VtkStationSource::SetUserProperty( QString name, QVariant value ) +void VtkStationSource::SetUserProperty(QString name, QVariant value) { Q_UNUSED(name); Q_UNUSED(value); } -std::size_t VtkStationSource::GetIndexByName( std::string const& name ) +std::size_t VtkStationSource::GetIndexByName(std::string const& name) { vtkIdType max_key(0); for (auto& it : _id_map) @@ -234,9 +243,8 @@ std::size_t VtkStationSource::GetIndexByName( std::string const& name ) } } - vtkIdType new_index = (_id_map.empty()) ? 0 : (max_key+1); + vtkIdType new_index = (_id_map.empty()) ? 0 : (max_key + 1); INFO("Key '{:s}' has been assigned index {:d}.", name, new_index); _id_map.insert(std::pair<std::string, vtkIdType>(name, new_index)); return new_index; } - diff --git a/Applications/DataExplorer/VtkVis/VtkSurfacesSource.cpp b/Applications/DataExplorer/VtkVis/VtkSurfacesSource.cpp index 878c0759466edd4961ac2993a4dbddde0e0a7d38..a993903f0b3e41b4f5cce14a37f08f8585dc1299 100644 --- a/Applications/DataExplorer/VtkVis/VtkSurfacesSource.cpp +++ b/Applications/DataExplorer/VtkVis/VtkSurfacesSource.cpp @@ -14,7 +14,6 @@ // ** INCLUDES ** #include "VtkSurfacesSource.h" -#include <limits> #include <vtkCellArray.h> #include <vtkCellData.h> @@ -22,43 +21,46 @@ #include <vtkInformationVector.h> #include <vtkObjectFactory.h> #include <vtkPolyData.h> -#include <vtkTriangle.h> +#include <vtkProperty.h> #include <vtkSmartPointer.h> #include <vtkStreamingDemandDrivenPipeline.h> -#include <vtkProperty.h> +#include <vtkTriangle.h> + +#include <limits> -#include "GeoLib/Triangle.h" #include "Applications/DataHolderLib/Color.h" +#include "GeoLib/Triangle.h" vtkStandardNewMacro(VtkSurfacesSource); VtkSurfacesSource::VtkSurfacesSource() { - _removable = false; // From VtkAlgorithmProperties + _removable = false; // From VtkAlgorithmProperties this->SetNumberOfInputPorts(0); - //this->SetColorBySurface(true); + // this->SetColorBySurface(true); const DataHolderLib::Color c = DataHolderLib::getRandomColor(); vtkProperty* vtkProps = GetProperties(); - vtkProps->SetColor(c[0] / 255.0,c[1] / 255.0,c[2] / 255.0); + vtkProps->SetColor(c[0] / 255.0, c[1] / 255.0, c[2] / 255.0); vtkProps->SetEdgeVisibility(0); } -void VtkSurfacesSource::PrintSelf( ostream& os, vtkIndent indent ) +void VtkSurfacesSource::PrintSelf(ostream& os, vtkIndent indent) { - this->Superclass::PrintSelf(os,indent); + this->Superclass::PrintSelf(os, indent); if (_surfaces->empty()) { return; } - os << indent << "== VtkSurfacesSource ==" << "\n"; + os << indent << "== VtkSurfacesSource ==" + << "\n"; } -int VtkSurfacesSource::RequestData( vtkInformation* request, - vtkInformationVector** inputVector, - vtkInformationVector* outputVector ) +int VtkSurfacesSource::RequestData(vtkInformation* request, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector) { (void)request; (void)inputVector; @@ -69,12 +71,14 @@ int VtkSurfacesSource::RequestData( vtkInformation* request, return 0; } - const std::vector<GeoLib::Point*>* surfacePoints = (*_surfaces)[0]->getPointVec(); + const std::vector<GeoLib::Point*>* surfacePoints = + (*_surfaces)[0]->getPointVec(); std::size_t nPoints = surfacePoints->size(); - vtkSmartPointer<vtkInformation> outInfo = outputVector->GetInformationObject(0); + vtkSmartPointer<vtkInformation> outInfo = + outputVector->GetInformationObject(0); vtkSmartPointer<vtkPolyData> output = - vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); + vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); if (outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()) > 0) { @@ -84,8 +88,9 @@ int VtkSurfacesSource::RequestData( vtkInformation* request, vtkSmartPointer<vtkPoints> newPoints = vtkSmartPointer<vtkPoints>::New(); newPoints->SetNumberOfPoints(nPoints); - vtkSmartPointer<vtkCellArray> newPolygons = vtkSmartPointer<vtkCellArray>::New(); - //newPolygons->Allocate(nSurfaces); + vtkSmartPointer<vtkCellArray> newPolygons = + vtkSmartPointer<vtkCellArray>::New(); + // newPolygons->Allocate(nSurfaces); vtkSmartPointer<vtkIntArray> sfcIDs = vtkSmartPointer<vtkIntArray>::New(); sfcIDs->SetNumberOfComponents(1); @@ -93,7 +98,8 @@ int VtkSurfacesSource::RequestData( vtkInformation* request, for (std::size_t i = 0; i < nPoints; ++i) { - const double* coords = const_cast<double*>((*surfacePoints)[i]->getCoords()); + const double* coords = + const_cast<double*>((*surfacePoints)[i]->getCoords()); newPoints->SetPoint(i, coords); } @@ -122,22 +128,23 @@ int VtkSurfacesSource::RequestData( vtkInformation* request, output->SetPoints(newPoints); output->SetPolys(newPolygons); output->GetCellData()->AddArray(sfcIDs); - output->GetCellData()->SetActiveAttribute("SurfaceIDs", vtkDataSetAttributes::SCALARS); + output->GetCellData()->SetActiveAttribute("SurfaceIDs", + vtkDataSetAttributes::SCALARS); output->Squeeze(); return 1; } -int VtkSurfacesSource::RequestInformation( vtkInformation* /*request*/, - vtkInformationVector** /*inputVector*/, - vtkInformationVector* /*outputVector*/ ) +int VtkSurfacesSource::RequestInformation( + vtkInformation* /*request*/, + vtkInformationVector** /*inputVector*/, + vtkInformationVector* /*outputVector*/) { return 1; } -void VtkSurfacesSource::SetUserProperty( QString name, QVariant value ) +void VtkSurfacesSource::SetUserProperty(QString name, QVariant value) { VtkAlgorithmProperties::SetUserProperty(name, value); (*_algorithmUserProperties)[name] = value; } - diff --git a/Applications/DataExplorer/VtkVis/VtkTextureOnSurfaceFilter.cpp b/Applications/DataExplorer/VtkVis/VtkTextureOnSurfaceFilter.cpp index 2bfeac1ec84432624c5280e622f9b45e057911d1..319494010d97fd19e75adf1a9a6014234c3f1748 100644 --- a/Applications/DataExplorer/VtkVis/VtkTextureOnSurfaceFilter.cpp +++ b/Applications/DataExplorer/VtkVis/VtkTextureOnSurfaceFilter.cpp @@ -15,21 +15,20 @@ // ** INCLUDES ** #include "VtkTextureOnSurfaceFilter.h" -#include "BaseLib/Logging.h" - #include <vtkCellData.h> #include <vtkFloatArray.h> +#include <vtkImageAlgorithm.h> +#include <vtkImageShiftScale.h> #include <vtkInformation.h> #include <vtkInformationVector.h> #include <vtkObjectFactory.h> #include <vtkPointData.h> +#include <vtkProperty.h> #include <vtkSmartPointer.h> #include <vtkStreamingDemandDrivenPipeline.h> -#include <vtkImageShiftScale.h> -#include <vtkImageAlgorithm.h> -#include <vtkProperty.h> #include <vtkTexture.h> +#include "BaseLib/Logging.h" #include "MathTools.h" #include "VtkVisHelper.h" @@ -38,14 +37,14 @@ vtkStandardNewMacro(VtkTextureOnSurfaceFilter); VtkTextureOnSurfaceFilter::VtkTextureOnSurfaceFilter() = default; VtkTextureOnSurfaceFilter::~VtkTextureOnSurfaceFilter() = default; -void VtkTextureOnSurfaceFilter::PrintSelf( ostream& os, vtkIndent indent ) +void VtkTextureOnSurfaceFilter::PrintSelf(ostream& os, vtkIndent indent) { - this->Superclass::PrintSelf(os,indent); + this->Superclass::PrintSelf(os, indent); } -int VtkTextureOnSurfaceFilter::RequestData( vtkInformation* request, - vtkInformationVector** inputVector, - vtkInformationVector* outputVector ) +int VtkTextureOnSurfaceFilter::RequestData(vtkInformation* request, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector) { (void)request; @@ -56,7 +55,8 @@ int VtkTextureOnSurfaceFilter::RequestData( vtkInformation* request, } vtkInformation* inInfo = inputVector[0]->GetInformationObject(0); - vtkPolyData* input = vtkPolyData::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT())); + vtkPolyData* input = + vtkPolyData::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT())); int dims[3]; this->GetTexture()->GetInput()->GetDimensions(dims); @@ -69,42 +69,43 @@ int VtkTextureOnSurfaceFilter::RequestData( vtkInformation* request, static_cast<int>(_origin.first + (imgWidth * _scalingFactor)), static_cast<int>(_origin.second + (imgHeight * _scalingFactor))); - //calculate texture coordinates + // calculate texture coordinates vtkPoints* points = input->GetPoints(); - vtkSmartPointer<vtkFloatArray> textureCoordinates = vtkSmartPointer<vtkFloatArray>::New(); + vtkSmartPointer<vtkFloatArray> textureCoordinates = + vtkSmartPointer<vtkFloatArray>::New(); textureCoordinates->SetNumberOfComponents(2); std::size_t nPoints = points->GetNumberOfPoints(); textureCoordinates->SetNumberOfTuples(nPoints); textureCoordinates->SetName("textureCoords"); -/* // adaptation for netcdf-curtain for TERENO Demo - double dist(0.0); - for (std::size_t i = 0; i < nPoints; i++) - { - double coords[3]; - if ((i==0) || (i==173)) - { - if (i==0) dist=0; - } - else + /* // adaptation for netcdf-curtain for TERENO Demo + double dist(0.0); + for (std::size_t i = 0; i < nPoints; i++) { - points->GetPoint(i-1, coords); - GeoLib::Point* pnt = new GeoLib::Point(coords); - points->GetPoint(i, coords); - GeoLib::Point* pnt2 = new GeoLib::Point(coords); - if (i<173) - dist += std::sqrt(MathLib::sqrDist(pnt, pnt2)); + double coords[3]; + if ((i==0) || (i==173)) + { + if (i==0) dist=0; + } else - dist -= std::sqrt(MathLib::sqrDist(pnt, pnt2)); + { + points->GetPoint(i-1, coords); + GeoLib::Point* pnt = new GeoLib::Point(coords); + points->GetPoint(i, coords); + GeoLib::Point* pnt2 = new GeoLib::Point(coords); + if (i<173) + dist += std::sqrt(MathLib::sqrDist(pnt, pnt2)); + else + dist -= std::sqrt(MathLib::sqrDist(pnt, pnt2)); + } + points->GetPoint(i, coords); + double x = MathLib::normalize(0, 8404, dist); + double z = MathLib::normalize(-79.5, 1.5, coords[2]); + float newcoords[2] = {x, z}; + textureCoordinates->InsertNextTuple(newcoords); } - points->GetPoint(i, coords); - double x = MathLib::normalize(0, 8404, dist); - double z = MathLib::normalize(-79.5, 1.5, coords[2]); - float newcoords[2] = {x, z}; - textureCoordinates->InsertNextTuple(newcoords); - } -*/ + */ - int const range[2] = { max.first - min.first, max.second - min.second }; + int const range[2] = {max.first - min.first, max.second - min.second}; // Scale values relative to the range. double coords[3]; @@ -113,13 +114,14 @@ int VtkTextureOnSurfaceFilter::RequestData( vtkInformation* request, points->GetPoint(i, coords); textureCoordinates->SetTuple2(i, - (coords[0] - min.first) / range[0], - (coords[1] - min.second) / range[1]); + (coords[0] - min.first) / range[0], + (coords[1] - min.second) / range[1]); } // put it all together vtkInformation* outInfo = outputVector->GetInformationObject(0); - vtkPolyData* output = vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); + vtkPolyData* output = + vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); output->CopyStructure(input); output->GetPointData()->PassData(input->GetPointData()); output->GetCellData()->PassData(input->GetCellData()); @@ -134,11 +136,13 @@ void VtkTextureOnSurfaceFilter::SetRaster(vtkImageAlgorithm* img) double range[2]; img->Update(); img->GetOutput()->GetPointData()->GetScalars()->GetRange(range); - vtkSmartPointer<vtkImageShiftScale> scale = vtkSmartPointer<vtkImageShiftScale>::New(); + vtkSmartPointer<vtkImageShiftScale> scale = + vtkSmartPointer<vtkImageShiftScale>::New(); scale->SetInputConnection(img->GetOutputPort()); scale->SetShift(-range[0]); - scale->SetScale(255.0/(range[1]-range[0])); - scale->SetOutputScalarTypeToUnsignedChar(); // Comment this out to get colored grayscale textures + scale->SetScale(255.0 / (range[1] - range[0])); + scale->SetOutputScalarTypeToUnsignedChar(); // Comment this out to get + // colored grayscale textures scale->Update(); vtkTexture* texture = vtkTexture::New(); @@ -153,7 +157,7 @@ void VtkTextureOnSurfaceFilter::SetRaster(vtkImageAlgorithm* img) _scalingFactor = img->GetOutput()->GetSpacing()[0]; } -void VtkTextureOnSurfaceFilter::SetUserProperty( QString name, QVariant value ) +void VtkTextureOnSurfaceFilter::SetUserProperty(QString name, QVariant value) { VtkAlgorithmProperties::SetUserProperty(name, value); } diff --git a/Applications/DataExplorer/VtkVis/VtkVisHelper.cpp b/Applications/DataExplorer/VtkVis/VtkVisHelper.cpp index 439ce320a536d530e27431ff8bbda379645cba7d..1b2ad5c43c777fd08a043a0545521ab541d4ca17 100644 --- a/Applications/DataExplorer/VtkVis/VtkVisHelper.cpp +++ b/Applications/DataExplorer/VtkVis/VtkVisHelper.cpp @@ -23,23 +23,23 @@ #include <QImage> -vtkImageData* VtkVisHelper::QImageToVtkImageData(QImage &img) +vtkImageData* VtkVisHelper::QImageToVtkImageData(QImage& img) { std::size_t imgWidth = img.width(); std::size_t imgHeight = img.height(); - vtkSmartPointer<vtkUnsignedCharArray> data = vtkSmartPointer<vtkUnsignedCharArray>::New(); + vtkSmartPointer<vtkUnsignedCharArray> data = + vtkSmartPointer<vtkUnsignedCharArray>::New(); data->SetNumberOfComponents(3); - data->SetNumberOfTuples( imgWidth * imgHeight ); + data->SetNumberOfTuples(imgWidth * imgHeight); for (std::size_t j = 0; j < imgHeight; j++) { for (std::size_t i = 0; i < imgWidth; i++) { - QRgb pix = img.pixel(i,j); - const float color[3] = { static_cast<float>(qRed(pix)), - static_cast<float>(qGreen(pix)), - static_cast<float>(qBlue(pix)) - }; + QRgb pix = img.pixel(i, j); + const float color[3] = {static_cast<float>(qRed(pix)), + static_cast<float>(qGreen(pix)), + static_cast<float>(qBlue(pix))}; data->SetTuple(j * imgWidth + i, color); } } @@ -53,15 +53,15 @@ vtkImageData* VtkVisHelper::QImageToVtkImageData(QImage &img) return imgData; } -vtkTexture* VtkVisHelper::QImageToVtkTexture(QImage &img) +vtkTexture* VtkVisHelper::QImageToVtkTexture(QImage& img) { vtkSmartPointer<vtkImageData> imgData = QImageToVtkImageData(img); vtkTexture* texture = vtkTexture::New(); texture->InterpolateOff(); texture->RepeatOff(); - //texture->EdgeClampOff(); - //texture->SetBlendingMode(0); + // texture->EdgeClampOff(); + // texture->SetBlendingMode(0); texture->SetInputData(imgData); return texture; diff --git a/Applications/DataExplorer/VtkVis/VtkVisImageItem.cpp b/Applications/DataExplorer/VtkVis/VtkVisImageItem.cpp index 7277870213da9484463d878c7b7f24d2841567f9..ff01e097d697bbd1194da844c3ab36ddd7db31c2 100644 --- a/Applications/DataExplorer/VtkVis/VtkVisImageItem.cpp +++ b/Applications/DataExplorer/VtkVis/VtkVisImageItem.cpp @@ -15,23 +15,21 @@ // ** INCLUDES ** #include "VtkVisImageItem.h" -#include "BaseLib/Logging.h" - -#include "BaseLib/FileTools.h" - -#include "VtkAlgorithmProperties.h" -#include "VtkGeoImageSource.h" - #include <vtkActor.h> +#include <vtkDataArray.h> #include <vtkDataSetMapper.h> #include <vtkImageAlgorithm.h> #include <vtkImageChangeInformation.h> #include <vtkImageData.h> +#include <vtkImageShiftScale.h> #include <vtkPointData.h> #include <vtkRenderer.h> #include <vtkSmartPointer.h> -#include <vtkImageShiftScale.h> -#include <vtkDataArray.h> + +#include "BaseLib/FileTools.h" +#include "BaseLib/Logging.h" +#include "VtkAlgorithmProperties.h" +#include "VtkGeoImageSource.h" // export #include <vtkImageActor.h> @@ -151,14 +149,15 @@ void VtkVisImageItem::setVtkProperties(VtkAlgorithmProperties* vtkProps) (void)vtkProps; } -int VtkVisImageItem::callVTKWriter(vtkAlgorithm* algorithm, const std::string &filename) const +int VtkVisImageItem::callVTKWriter(vtkAlgorithm* algorithm, + const std::string& filename) const { std::string file_name_cpy(filename); auto* algID = dynamic_cast<vtkImageAlgorithm*>(algorithm); if (algID) { vtkSmartPointer<vtkXMLImageDataWriter> iWriter = - vtkSmartPointer<vtkXMLImageDataWriter>::New(); + vtkSmartPointer<vtkXMLImageDataWriter>::New(); iWriter->SetInputData(algID->GetOutputDataObject(0)); if (BaseLib::getFileExtension(filename) != ".vti") { @@ -173,7 +172,7 @@ int VtkVisImageItem::callVTKWriter(vtkAlgorithm* algorithm, const std::string &f void VtkVisImageItem::setTranslation(double x, double y, double z) const { - _transformFilter->SetOriginTranslation(x,y,z); + _transformFilter->SetOriginTranslation(x, y, z); } vtkAlgorithm* VtkVisImageItem::transformFilter() const diff --git a/Applications/DataExplorer/VtkVis/VtkVisPipeline.cpp b/Applications/DataExplorer/VtkVis/VtkVisPipeline.cpp index afce826c140b590dae455f57a68f96a4d1033c25..adc45ead081c5983fec135be5d41e5639e6cbd13 100644 --- a/Applications/DataExplorer/VtkVis/VtkVisPipeline.cpp +++ b/Applications/DataExplorer/VtkVis/VtkVisPipeline.cpp @@ -17,10 +17,13 @@ #include <vtkAlgorithm.h> #include <vtkCamera.h> +#include <vtkCellData.h> +#include <vtkFieldData.h> #include <vtkGenericDataObjectReader.h> #include <vtkImageActor.h> #include <vtkImageReader2.h> #include <vtkLight.h> +#include <vtkPointData.h> #include <vtkPointSet.h> #include <vtkProp3D.h> #include <vtkRenderer.h> @@ -32,10 +35,6 @@ #include <vtkXMLStructuredGridReader.h> #include <vtkXMLUnstructuredGridReader.h> -#include <vtkCellData.h> -#include <vtkFieldData.h> -#include <vtkPointData.h> - #include <QColor> #ifndef NDEBUG #include <QElapsedTimer> @@ -45,13 +44,11 @@ #include <QString> #include "BaseLib/Logging.h" - +#include "GeoTreeModel.h" #include "MathLib/InterpolationAlgorithms/LinearIntervalInterpolation.h" +#include "MeshItem.h" #include "MeshLib/Mesh.h" #include "MeshLib/Vtk/VtkMappedMeshSource.h" - -#include "GeoTreeModel.h" -#include "MeshItem.h" #include "MeshModel.h" #include "StationTreeModel.h" #include "TreeModel.h" @@ -68,7 +65,8 @@ VtkVisPipeline::VtkVisPipeline(vtkRenderer* renderer, QObject* parent /*= 0*/) : TreeModel(parent), _renderer(renderer) { QList<QVariant> rootData; - rootData << "Object name" << "Visible"; + rootData << "Object name" + << "Visible"; delete _rootItem; _rootItem = new TreeItem(rootData, nullptr); @@ -79,18 +77,19 @@ VtkVisPipeline::VtkVisPipeline(vtkRenderer* renderer, QObject* parent /*= 0*/) this->setBGColor(backgroundColorVariant.value<QColor>()); } - _resetCameraOnAddOrRemove = settings.value("resetViewOnLoad", true).toBool(); + _resetCameraOnAddOrRemove = + settings.value("resetViewOnLoad", true).toBool(); } -bool VtkVisPipeline::setData( const QModelIndex &index, const QVariant &value, - int role /* = Qt::EditRole */ ) +bool VtkVisPipeline::setData(const QModelIndex& index, const QVariant& value, + int role /* = Qt::EditRole */) { emit vtkVisPipelineChanged(); return TreeModel::setData(index, value, role); } -void VtkVisPipeline::addLight(const GeoLib::Point &pos) +void VtkVisPipeline::addLight(const GeoLib::Point& pos) { double lightPos[3]; for (auto& light : _lights) @@ -108,7 +107,7 @@ void VtkVisPipeline::addLight(const GeoLib::Point &pos) _lights.push_back(l); } -vtkLight* VtkVisPipeline::getLight(const GeoLib::Point &pos) const +vtkLight* VtkVisPipeline::getLight(const GeoLib::Point& pos) const { double lightPos[3]; for (auto light : _lights) @@ -123,13 +122,14 @@ vtkLight* VtkVisPipeline::getLight(const GeoLib::Point &pos) const return nullptr; } -void VtkVisPipeline::removeLight(const GeoLib::Point &pos) +void VtkVisPipeline::removeLight(const GeoLib::Point& pos) { double lightPos[3]; for (auto it = _lights.begin(); it != _lights.end(); ++it) { (*it)->GetPosition(lightPos); - if (pos[0] == lightPos[0] && pos[1] == lightPos[1] && pos[2] == lightPos[2]) + if (pos[0] == lightPos[0] && pos[1] == lightPos[1] && + pos[2] == lightPos[2]) { _renderer->RemoveLight(*it); (*it)->Delete(); @@ -148,19 +148,19 @@ QColor VtkVisPipeline::getBGColor() const return c; } -void VtkVisPipeline::setBGColor(const QColor &color) +void VtkVisPipeline::setBGColor(const QColor& color) { QSettings settings; settings.setValue("VtkBackgroundColor", color); _renderer->SetBackground(color.redF(), color.greenF(), color.blueF()); } -QModelIndex VtkVisPipeline::getIndex( vtkProp3D* actor ) +QModelIndex VtkVisPipeline::getIndex(vtkProp3D* actor) { return _actorMap.value(actor, QModelIndex()); } -Qt::ItemFlags VtkVisPipeline::flags( const QModelIndex &index ) const +Qt::ItemFlags VtkVisPipeline::flags(const QModelIndex& index) const { Qt::ItemFlags defaultFlags = Qt::ItemIsEnabled | Qt::ItemIsSelectable; @@ -169,7 +169,7 @@ Qt::ItemFlags VtkVisPipeline::flags( const QModelIndex &index ) const return Qt::ItemIsEnabled; } - //if (index.column() == 1) + // if (index.column() == 1) // defaultFlags |= Qt::ItemIsEditable; return defaultFlags; @@ -209,12 +209,13 @@ void VtkVisPipeline::loadFromFile(QString filename) else if (filename.endsWith("vtk")) { vtkGenericDataObjectReader* oldStyleReader = - vtkGenericDataObjectReader::New(); + vtkGenericDataObjectReader::New(); oldStyleReader->SetFileName(filename.toStdString().c_str()); oldStyleReader->ReadAllFieldsOn(); oldStyleReader->ReadAllScalarsOn(); oldStyleReader->Update(); - vtkDataSet* dataSet = vtkDataSet::SafeDownCast(oldStyleReader->GetOutput()); + vtkDataSet* dataSet = + vtkDataSet::SafeDownCast(oldStyleReader->GetOutput()); if (dataSet) { this->listArrays(dataSet); @@ -230,10 +231,12 @@ void VtkVisPipeline::loadFromFile(QString filename) } reader->SetFileName(filename.toStdString().c_str()); - // TODO: insert ReadAllScalarsOn()-equivalent for xml-file-reader here, otherwise arrays are not available in GUI! + // TODO: insert ReadAllScalarsOn()-equivalent for xml-file-reader here, + // otherwise arrays are not available in GUI! reader->Update(); - //std::cout << "#cell scalars: " << reader->GetNumberOfCellArrays() << std::endl; - //std::cout << "#point scalars: " << reader->GetNumberOfPointArrays() << std::endl; + // std::cout << "#cell scalars: " << reader->GetNumberOfCellArrays() << + // std::endl; std::cout << "#point scalars: " << + // reader->GetNumberOfPointArrays() << std::endl; vtkSmartPointer<vtkDataSet> dataSet = reader->GetOutputAsDataSet(); if (dataSet) @@ -281,23 +284,25 @@ void VtkVisPipeline::setGlobalBackfaceCulling(bool enable) const } void VtkVisPipeline::addPipelineItem(GeoTreeModel* model, - const std::string &name, + const std::string& name, GeoLib::GEOTYPE type) { addPipelineItem(model->vtkSource(name, type)); } -void VtkVisPipeline::addPipelineItem(StationTreeModel* model, const std::string &name) +void VtkVisPipeline::addPipelineItem(StationTreeModel* model, + const std::string& name) { addPipelineItem(model->vtkSource(name)); } -void VtkVisPipeline::addPipelineItem(MeshModel* model, const QModelIndex &idx) +void VtkVisPipeline::addPipelineItem(MeshModel* model, const QModelIndex& idx) { addPipelineItem(static_cast<MeshItem*>(model->getItem(idx))->vtkSource()); } -QModelIndex VtkVisPipeline::addPipelineItem(VtkVisPipelineItem* item, const QModelIndex &parent) +QModelIndex VtkVisPipeline::addPipelineItem(VtkVisPipelineItem* item, + const QModelIndex& parent) { beginResetModel(); @@ -305,7 +310,7 @@ QModelIndex VtkVisPipeline::addPipelineItem(VtkVisPipelineItem* item, const QMod TreeItem* parentItem = item->parentItem(); parentItem->appendChild(item); - if (!parent.isValid()) // Set global superelevation on source objects + if (!parent.isValid()) // Set global superelevation on source objects { QSettings settings; if (dynamic_cast<vtkImageAlgorithm*>(item->algorithm()) == nullptr) @@ -338,11 +343,12 @@ QModelIndex VtkVisPipeline::addPipelineItem(VtkVisPipelineItem* item, const QMod return newIndex; } -QModelIndex VtkVisPipeline::addPipelineItem( vtkAlgorithm* source, QModelIndex parent /* = QModelindex() */) +QModelIndex VtkVisPipeline::addPipelineItem( + vtkAlgorithm* source, QModelIndex parent /* = QModelindex() */) { std::string itemName; - if (!parent.isValid()) // if source object + if (!parent.isValid()) // if source object { auto* old_reader = dynamic_cast<vtkGenericDataObjectReader*>(source); auto* new_reader = dynamic_cast<vtkXMLReader*>(source); @@ -392,12 +398,13 @@ QModelIndex VtkVisPipeline::addPipelineItem( vtkAlgorithm* source, QModelIndex p } void VtkVisPipeline::removeSourceItem(GeoTreeModel* model, - const std::string &name, + const std::string& name, GeoLib::GEOTYPE type) { for (int i = 0; i < _rootItem->childCount(); i++) { - VtkVisPipelineItem* item = static_cast<VtkVisPipelineItem*>(getItem(index(i, 0))); + VtkVisPipelineItem* item = + static_cast<VtkVisPipelineItem*>(getItem(index(i, 0))); if (item->algorithm() == model->vtkSource(name, type)) { removePipelineItem(index(i, 0)); @@ -406,11 +413,13 @@ void VtkVisPipeline::removeSourceItem(GeoTreeModel* model, } } -void VtkVisPipeline::removeSourceItem(StationTreeModel* model, const std::string &name) +void VtkVisPipeline::removeSourceItem(StationTreeModel* model, + const std::string& name) { for (int i = 0; i < _rootItem->childCount(); i++) { - VtkVisPipelineItem* item = static_cast<VtkVisPipelineItem*>(getItem(index(i, 0))); + VtkVisPipelineItem* item = + static_cast<VtkVisPipelineItem*>(getItem(index(i, 0))); if (item->algorithm() == model->vtkSource(name)) { removePipelineItem(index(i, 0)); @@ -419,7 +428,7 @@ void VtkVisPipeline::removeSourceItem(StationTreeModel* model, const std::string } } -void VtkVisPipeline::removeSourceItem(MeshModel* model, const QModelIndex &idx) +void VtkVisPipeline::removeSourceItem(MeshModel* model, const QModelIndex& idx) { auto* sItem = static_cast<MeshItem*>(model->getItem(idx)); @@ -435,7 +444,7 @@ void VtkVisPipeline::removeSourceItem(MeshModel* model, const QModelIndex &idx) } } -void VtkVisPipeline::removePipelineItem( QModelIndex index ) +void VtkVisPipeline::removePipelineItem(QModelIndex index) { if (!index.isValid()) { @@ -454,7 +463,7 @@ void VtkVisPipeline::removePipelineItem( QModelIndex index ) ++it; } - //TreeItem* item = getItem(index); + // TreeItem* item = getItem(index); removeRows(index.row(), 1, index.parent()); if (_resetCameraOnAddOrRemove) @@ -483,8 +492,8 @@ void VtkVisPipeline::listArrays(vtkDataSet* dataSet) } void VtkVisPipeline::showMeshElementQuality( - MeshLib::VtkMappedMeshSource* source, - MeshLib::MeshQualityType t, std::vector<double> const& quality) + MeshLib::VtkMappedMeshSource* source, MeshLib::MeshQualityType t, + std::vector<double> const& quality) { if (!source || quality.empty()) { @@ -516,14 +525,17 @@ void VtkVisPipeline::showMeshElementQuality( static_cast<VtkCompositeElementSelectionFilter*>(filter)->setRange( *range.first, *range.second); } - static_cast<VtkCompositeElementSelectionFilter*>(filter)->setSelectionArray("Selection", quality); - VtkVisPointSetItem* item = new VtkVisPointSetItem(filter, parentItem, itemData); + static_cast<VtkCompositeElementSelectionFilter*>(filter) + ->setSelectionArray("Selection", quality); + VtkVisPointSetItem* item = + new VtkVisPointSetItem(filter, parentItem, itemData); this->addPipelineItem(item, this->createIndex(i, 0, item)); break; } } -void VtkVisPipeline::highlightGeoObject(const vtkPolyDataAlgorithm* source, int index) +void VtkVisPipeline::highlightGeoObject(const vtkPolyDataAlgorithm* source, + int index) { this->removeHighlightedGeoObject(); int nSources = this->_rootItem->childCount(); @@ -560,7 +572,9 @@ void VtkVisPipeline::removeHighlightedGeoObject() } } -void VtkVisPipeline::highlightMeshComponent(vtkUnstructuredGridAlgorithm const*const source, unsigned index, bool is_element) +void VtkVisPipeline::highlightMeshComponent( + vtkUnstructuredGridAlgorithm const* const source, unsigned index, + bool is_element) { int nSources = this->_rootItem->childCount(); for (int i = 0; i < nSources; i++) diff --git a/Applications/DataExplorer/VtkVis/VtkVisPipelineItem.cpp b/Applications/DataExplorer/VtkVis/VtkVisPipelineItem.cpp index ff1754466e178c56975e8051f618157ebecc4f1f..5989710ba9b00dce52da55cd2488967fc274f883 100644 --- a/Applications/DataExplorer/VtkVis/VtkVisPipelineItem.cpp +++ b/Applications/DataExplorer/VtkVis/VtkVisPipelineItem.cpp @@ -13,27 +13,28 @@ */ // ** INCLUDES ** -#include "FileTools.h" -#include "VtkAlgorithmProperties.h" #include "VtkVisPipelineItem.h" -#include "VtkCompositeFilter.h" -#include "QVtkDataSetMapper.h" #include <vtkActor.h> #include <vtkAlgorithm.h> +#include <vtkCellData.h> #include <vtkDataSetMapper.h> +#include <vtkGenericDataObjectWriter.h> +#include <vtkImageActor.h> +#include <vtkPointData.h> #include <vtkPointSet.h> #include <vtkProperty.h> #include <vtkRenderer.h> #include <vtkSmartPointer.h> #include <vtkTextureMapToPlane.h> -#include <vtkGenericDataObjectWriter.h> -#include <vtkCellData.h> -#include <vtkPointData.h> -#include <vtkImageActor.h> #include <QMessageBox> +#include "FileTools.h" +#include "QVtkDataSetMapper.h" +#include "VtkAlgorithmProperties.h" +#include "VtkCompositeFilter.h" + VtkVisPipelineItem::VtkVisPipelineItem( vtkAlgorithm* algorithm, TreeItem* parentItem, const QList<QVariant> data /*= QList<QVariant>()*/) @@ -71,7 +72,7 @@ VtkVisPipelineItem::~VtkVisPipelineItem() delete _compositeFilter; } -VtkVisPipelineItem* VtkVisPipelineItem::child( int row ) const +VtkVisPipelineItem* VtkVisPipelineItem::child(int row) const { TreeItem* treeItem = TreeItem::child(row); if (treeItem) @@ -82,7 +83,7 @@ VtkVisPipelineItem* VtkVisPipelineItem::child( int row ) const return nullptr; } -QVariant VtkVisPipelineItem::data( int column ) const +QVariant VtkVisPipelineItem::data(int column) const { if (column == 1) { @@ -92,7 +93,7 @@ QVariant VtkVisPipelineItem::data( int column ) const return TreeItem::data(column); } -bool VtkVisPipelineItem::setData( int column, const QVariant &value ) +bool VtkVisPipelineItem::setData(int column, const QVariant& value) { if (column == 1) { @@ -107,14 +108,14 @@ bool VtkVisPipelineItem::isVisible() const return static_cast<bool>(_actor->GetVisibility()); } -void VtkVisPipelineItem::setVisible( bool visible ) +void VtkVisPipelineItem::setVisible(bool visible) { _actor->SetVisibility(static_cast<int>(visible)); _actor->Modified(); _renderer->Render(); } -int VtkVisPipelineItem::writeToFile(const std::string &filename) const +int VtkVisPipelineItem::writeToFile(const std::string& filename) const { if (!filename.empty()) { @@ -123,7 +124,8 @@ int VtkVisPipelineItem::writeToFile(const std::string &filename) const return 0; } -int VtkVisPipelineItem::callVTKWriter(vtkAlgorithm* algorithm, const std::string &filename) const +int VtkVisPipelineItem::callVTKWriter(vtkAlgorithm* algorithm, + const std::string& filename) const { // needs to be implemented in derived classes! (void)algorithm; @@ -176,24 +178,31 @@ void VtkVisPipelineItem::setBackfaceCullingOnChildren(bool enable) const QStringList VtkVisPipelineItem::getScalarArrayNames() const { this->algorithm()->Update(); - vtkDataSet* dataSet = vtkDataSet::SafeDownCast(this->algorithm()->GetOutputDataObject(0)); + vtkDataSet* dataSet = + vtkDataSet::SafeDownCast(this->algorithm()->GetOutputDataObject(0)); QStringList dataSetAttributesList; if (dataSet) { vtkPointData* pointData = dataSet->GetPointData(); - //std::cout << " #point data arrays: " << pointData->GetNumberOfArrays() << std::endl; + // std::cout << " #point data arrays: " << + // pointData->GetNumberOfArrays() << std::endl; for (int i = 0; i < pointData->GetNumberOfArrays(); i++) { - // std::cout << " Name: " << pointData->GetArrayName(i) << std::endl; - dataSetAttributesList.push_back(QString("P-") + pointData->GetArrayName(i)); + // std::cout << " Name: " << pointData->GetArrayName(i) << + // std::endl; + dataSetAttributesList.push_back(QString("P-") + + pointData->GetArrayName(i)); } vtkCellData* cellData = dataSet->GetCellData(); - //std::cout << " #cell data arrays: " << cellData->GetNumberOfArrays() << std::endl; + // std::cout << " #cell data arrays: " << cellData->GetNumberOfArrays() + // << std::endl; for (int i = 0; i < cellData->GetNumberOfArrays(); i++) { - // std::cout << " Name: " << cellData->GetArrayName(i) << std::endl; - dataSetAttributesList.push_back(QString("C-") + cellData->GetArrayName(i)); + // std::cout << " Name: " << cellData->GetArrayName(i) << + // std::endl; + dataSetAttributesList.push_back(QString("C-") + + cellData->GetArrayName(i)); } } return dataSetAttributesList; diff --git a/Applications/DataExplorer/VtkVis/VtkVisPipelineView.cpp b/Applications/DataExplorer/VtkVis/VtkVisPipelineView.cpp index 06ab02ec9fc926adc67f2ee6605cdffed44983da..ba59fee94b5c454db4e532f60490276211ace5f2 100644 --- a/Applications/DataExplorer/VtkVis/VtkVisPipelineView.cpp +++ b/Applications/DataExplorer/VtkVis/VtkVisPipelineView.cpp @@ -15,17 +15,6 @@ // ** INCLUDES ** #include "VtkVisPipelineView.h" -#include "Mesh.h" -#include "MeshGenerators/RasterToMesh.h" -#include "MeshGenerators/VtkMeshConverter.h" - -#include "OGSError.h" - -#include "CheckboxDelegate.h" -#include "VtkVisPipeline.h" -#include "VtkVisPipelineItem.h" -#include "VtkVisPointSetItem.h" - #include <vtkDataSetMapper.h> #include <vtkProp3D.h> @@ -34,23 +23,32 @@ #include <QFileDialog> #include <QHeaderView> #include <QMenu> -#include <QSettings> #include <QMessageBox> +#include <QSettings> -//image to mesh conversion -#include "VtkGeoImageSource.h" -#include <vtkImageData.h> -#include "MeshFromRasterDialog.h" +#include "CheckboxDelegate.h" +#include "Mesh.h" +#include "MeshGenerators/RasterToMesh.h" +#include "MeshGenerators/VtkMeshConverter.h" +#include "OGSError.h" +#include "VtkVisPipeline.h" +#include "VtkVisPipelineItem.h" +#include "VtkVisPointSetItem.h" + +// image to mesh conversion #include <vtkDataObject.h> -#include <vtkSmartPointer.h> #include <vtkGenericDataObjectReader.h> +#include <vtkImageData.h> +#include <vtkSmartPointer.h> #include <vtkTransformFilter.h> #include <vtkUnstructuredGrid.h> #include <vtkUnstructuredGridAlgorithm.h> #include <vtkXMLUnstructuredGridReader.h> +#include "MeshFromRasterDialog.h" +#include "VtkGeoImageSource.h" -VtkVisPipelineView::VtkVisPipelineView( QWidget* parent /*= 0*/ ) +VtkVisPipelineView::VtkVisPipelineView(QWidget* parent /*= 0*/) : QTreeView(parent) { this->setItemsExpandable(false); @@ -69,15 +67,17 @@ void VtkVisPipelineView::setModel(QAbstractItemModel* model) this->header()->moveSection(1, 0); } -void VtkVisPipelineView::contextMenuEvent( QContextMenuEvent* event ) +void VtkVisPipelineView::contextMenuEvent(QContextMenuEvent* event) { QModelIndex index = selectionModel()->currentIndex(); if (index.isValid()) { // check object type - VtkVisPipelineItem* item = static_cast<VtkVisPipelineItem*>(static_cast<VtkVisPipeline*>( - this->model())->getItem(this->selectionModel()->currentIndex())); - int objectType = item->algorithm()->GetOutputDataObject(0)->GetDataObjectType(); + VtkVisPipelineItem* item = static_cast<VtkVisPipelineItem*>( + static_cast<VtkVisPipeline*>(this->model()) + ->getItem(this->selectionModel()->currentIndex())); + int objectType = + item->algorithm()->GetOutputDataObject(0)->GetDataObjectType(); VtkAlgorithmProperties* vtkProps = item->getVtkProperties(); bool isSourceItem = !(this->selectionModel()->currentIndex().parent().isValid()); @@ -87,7 +87,8 @@ void VtkVisPipelineView::contextMenuEvent( QContextMenuEvent* event ) if (objectType == VTK_IMAGE_DATA) { - // this exception is needed as image object are only displayed in the vis-pipeline + // this exception is needed as image object are only displayed in + // the vis-pipeline isSourceItem = false; QAction* addMeshingAction = menu.addAction("Convert Image to Mesh..."); @@ -97,7 +98,8 @@ void VtkVisPipelineView::contextMenuEvent( QContextMenuEvent* event ) else { QAction* addLUTAction = menu.addAction("Add color table..."); - connect(addLUTAction, SIGNAL(triggered()), this, SLOT(addColorTable())); + connect(addLUTAction, SIGNAL(triggered()), this, + SLOT(addColorTable())); } if (objectType == VTK_UNSTRUCTURED_GRID) @@ -118,7 +120,8 @@ void VtkVisPipelineView::contextMenuEvent( QContextMenuEvent* event ) SLOT(removeSelectedPipelineItem())); } - connect(addFilterAction, SIGNAL(triggered()), this, SLOT(addPipelineFilterItem())); + connect(addFilterAction, SIGNAL(triggered()), this, + SLOT(addPipelineFilterItem())); connect(exportVtkAction, SIGNAL(triggered()), this, SLOT(exportSelectedPipelineItemAsVtk())); @@ -130,13 +133,15 @@ void VtkVisPipelineView::exportSelectedPipelineItemAsVtk() { QSettings settings; QModelIndex idx = this->selectionModel()->currentIndex(); - QString filename = QFileDialog::getSaveFileName(this, "Export object to vtk-file", - settings.value("lastExportedFileDirectory").toString(), - "VTK file (*.*)"); + QString filename = QFileDialog::getSaveFileName( + this, "Export object to vtk-file", + settings.value("lastExportedFileDirectory").toString(), + "VTK file (*.*)"); if (!filename.isEmpty()) { - static_cast<VtkVisPipelineItem*>(static_cast<VtkVisPipeline*>(this->model())-> - getItem(idx))->writeToFile(filename.toStdString()); + static_cast<VtkVisPipelineItem*>( + static_cast<VtkVisPipeline*>(this->model())->getItem(idx)) + ->writeToFile(filename.toStdString()); QDir dir = QDir(filename); settings.setValue("lastExportedFileDirectory", dir.absolutePath()); } @@ -161,10 +166,13 @@ void VtkVisPipelineView::showImageToMeshConversionDialog() } vtkSmartPointer<vtkAlgorithm> algorithm = - static_cast<VtkVisPipelineItem*>(static_cast<VtkVisPipeline*>(this->model())-> - getItem(this->selectionModel()->currentIndex()))->algorithm(); + static_cast<VtkVisPipelineItem*>( + static_cast<VtkVisPipeline*>(this->model()) + ->getItem(this->selectionModel()->currentIndex())) + ->algorithm(); - vtkSmartPointer<VtkGeoImageSource> imageSource = VtkGeoImageSource::SafeDownCast(algorithm); + vtkSmartPointer<VtkGeoImageSource> imageSource = + VtkGeoImageSource::SafeDownCast(algorithm); double origin[3]; imageSource->GetOutput()->GetOrigin(origin); double spacing[3]; @@ -187,11 +195,13 @@ void VtkVisPipelineView::showImageToMeshConversionDialog() void VtkVisPipelineView::convertVTKToOGSMesh() { VtkVisPipelineItem* item = static_cast<VtkVisPipelineItem*>( - static_cast<VtkVisPipeline*>(this->model())->getItem(this->selectionModel()->currentIndex())); + static_cast<VtkVisPipeline*>(this->model()) + ->getItem(this->selectionModel()->currentIndex())); vtkSmartPointer<vtkAlgorithm> algorithm = item->algorithm(); vtkUnstructuredGrid* grid(nullptr); - vtkUnstructuredGridAlgorithm* ugAlg = vtkUnstructuredGridAlgorithm::SafeDownCast(algorithm); + vtkUnstructuredGridAlgorithm* ugAlg = + vtkUnstructuredGridAlgorithm::SafeDownCast(algorithm); if (ugAlg) { grid = ugAlg->GetOutput(); @@ -199,7 +209,8 @@ void VtkVisPipelineView::convertVTKToOGSMesh() else { // for old filetypes - vtkGenericDataObjectReader* dataReader = vtkGenericDataObjectReader::SafeDownCast(algorithm); + vtkGenericDataObjectReader* dataReader = + vtkGenericDataObjectReader::SafeDownCast(algorithm); if (dataReader) { grid = vtkUnstructuredGrid::SafeDownCast(dataReader->GetOutput()); @@ -207,17 +218,19 @@ void VtkVisPipelineView::convertVTKToOGSMesh() else { // for new filetypes - vtkXMLUnstructuredGridReader* xmlReader = vtkXMLUnstructuredGridReader::SafeDownCast(algorithm); + vtkXMLUnstructuredGridReader* xmlReader = + vtkXMLUnstructuredGridReader::SafeDownCast(algorithm); grid = vtkUnstructuredGrid::SafeDownCast(xmlReader->GetOutput()); } } - MeshLib::Mesh* mesh = MeshLib::VtkMeshConverter::convertUnstructuredGrid(grid); + MeshLib::Mesh* mesh = + MeshLib::VtkMeshConverter::convertUnstructuredGrid(grid); mesh->setName(item->data(0).toString().toStdString()); emit meshAdded(mesh); } -void VtkVisPipelineView::selectionChanged( const QItemSelection &selected, - const QItemSelection &deselected ) +void VtkVisPipelineView::selectionChanged(const QItemSelection& selected, + const QItemSelection& deselected) { QTreeView::selectionChanged(selected, deselected); @@ -248,10 +261,11 @@ void VtkVisPipelineView::selectionChanged( const QItemSelection &selected, void VtkVisPipelineView::selectItem(vtkProp3D* actor) { - this->selectItem(static_cast<VtkVisPipeline*>(this->model())->getIndex(actor)); + this->selectItem( + static_cast<VtkVisPipeline*>(this->model())->getIndex(actor)); } -void VtkVisPipelineView::selectItem(const QModelIndex &index) +void VtkVisPipelineView::selectItem(const QModelIndex& index) { if (!index.isValid()) { @@ -265,15 +279,16 @@ void VtkVisPipelineView::selectItem(const QModelIndex &index) void VtkVisPipelineView::addColorTable() { - VtkVisPipelineItem* item ( - static_cast<VtkVisPipelineItem*>(static_cast<VtkVisPipeline*>(this->model())-> - getItem(this->selectionModel()->currentIndex())) ); + VtkVisPipelineItem* item(static_cast<VtkVisPipelineItem*>( + static_cast<VtkVisPipeline*>(this->model()) + ->getItem(this->selectionModel()->currentIndex()))); const QString array_name = item->GetActiveAttribute(); QSettings settings; - QString filename = QFileDialog::getOpenFileName(this, "Select color table", - settings.value("lastOpenedLutFileDirectory"). toString(), - "Color table files (*.xml);;"); + QString filename = QFileDialog::getOpenFileName( + this, "Select color table", + settings.value("lastOpenedLutFileDirectory").toString(), + "Color table files (*.xml);;"); QFileInfo fi(filename); if (fi.suffix().toLower() == "xml") diff --git a/Applications/DataExplorer/VtkVis/VtkVisPointSetItem.cpp b/Applications/DataExplorer/VtkVis/VtkVisPointSetItem.cpp index 66735792e70c48efa8479cbe0495fb6d80f373cb..62cd4754ecf130440209dac393fdcf8d1a92bb26 100644 --- a/Applications/DataExplorer/VtkVis/VtkVisPointSetItem.cpp +++ b/Applications/DataExplorer/VtkVis/VtkVisPointSetItem.cpp @@ -15,37 +15,35 @@ // ** INCLUDES ** #include "VtkVisPointSetItem.h" -#include <limits> +#include <vtkActor.h> +#include <vtkCellData.h> +#include <vtkDataSetMapper.h> +#include <vtkImageAlgorithm.h> +#include <vtkLookupTable.h> +#include <vtkPointData.h> +#include <vtkProperty.h> +#include <vtkRenderer.h> +#include <vtkSmartPointer.h> +#include <vtkTransform.h> +#include <vtkTransformFilter.h> #include <QObject> #include <QRegExp> #include <QSettings> #include <QStringList> - -#include "BaseLib/Logging.h" +#include <limits> #include "BaseLib/FileTools.h" - +#include "BaseLib/Logging.h" +#include "MeshLib/Vtk/VtkMappedMeshSource.h" +#include "QVtkDataSetMapper.h" #include "VtkAlgorithmProperties.h" -#include "VtkCompositeFilter.h" #include "VtkCompositeContourFilter.h" +#include "VtkCompositeFilter.h" #include "VtkCompositeThresholdFilter.h" -#include "MeshLib/Vtk/VtkMappedMeshSource.h" - -#include "QVtkDataSetMapper.h" -#include <vtkActor.h> -#include <vtkCellData.h> -#include <vtkDataSetMapper.h> -#include <vtkImageAlgorithm.h> -#include <vtkPointData.h> -#include <vtkRenderer.h> -#include <vtkSmartPointer.h> -#include <vtkTransform.h> -#include <vtkTransformFilter.h> -#include <vtkProperty.h> -#include <vtkLookupTable.h> // export test +#include <vtkDataSetAttributes.h> #include <vtkPolyDataAlgorithm.h> #include <vtkTriangleFilter.h> #include <vtkTubeFilter.h> @@ -53,13 +51,14 @@ #include <vtkXMLPolyDataWriter.h> #include <vtkXMLUnstructuredGridWriter.h> -#include <vtkDataSetAttributes.h> - VtkVisPointSetItem::VtkVisPointSetItem( - vtkAlgorithm* algorithm, TreeItem* parentItem, - const QList<QVariant> data /*= QList<QVariant>()*/) - : VtkVisPipelineItem(algorithm, parentItem, data), _mapper(nullptr), - _transformFilter(nullptr), _onPointData(true), _activeArrayName("") + vtkAlgorithm* algorithm, TreeItem* parentItem, + const QList<QVariant> data /*= QList<QVariant>()*/) + : VtkVisPipelineItem(algorithm, parentItem, data), + _mapper(nullptr), + _transformFilter(nullptr), + _onPointData(true), + _activeArrayName("") { auto* visParentItem = dynamic_cast<VtkVisPipelineItem*>(parentItem); if (parentItem->parentItem()) @@ -84,10 +83,13 @@ VtkVisPointSetItem::VtkVisPointSetItem( } VtkVisPointSetItem::VtkVisPointSetItem( - VtkCompositeFilter* compositeFilter, TreeItem* parentItem, - const QList<QVariant> data /*= QList<QVariant>()*/) - : VtkVisPipelineItem(compositeFilter, parentItem, data), _mapper(nullptr), - _transformFilter(nullptr), _onPointData(true), _activeArrayName("") + VtkCompositeFilter* compositeFilter, TreeItem* parentItem, + const QList<QVariant> data /*= QList<QVariant>()*/) + : VtkVisPipelineItem(compositeFilter, parentItem, data), + _mapper(nullptr), + _transformFilter(nullptr), + _onPointData(true), + _activeArrayName("") { } @@ -106,7 +108,8 @@ void VtkVisPointSetItem::Initialize(vtkRenderer* renderer) // TODO vtkTransformFilter creates a new copy of the point coordinates which // conflicts with VtkMappedMeshSource. Find a workaround! _transformFilter = vtkTransformFilter::New(); - vtkSmartPointer<vtkTransform> transform = vtkSmartPointer<vtkTransform>::New(); + vtkSmartPointer<vtkTransform> transform = + vtkSmartPointer<vtkTransform>::New(); transform->Identity(); _transformFilter->SetTransform(transform); @@ -124,7 +127,8 @@ void VtkVisPointSetItem::Initialize(vtkRenderer* renderer) _renderer->AddActor(_actor); // Determine the right pre-set properties - // Order is: _algorithm, _compositeFilter, create a new one with props copied from parent + // Order is: _algorithm, _compositeFilter, create a new one with props + // copied from parent auto* vtkProps = dynamic_cast<VtkAlgorithmProperties*>(_algorithm); if (!vtkProps) { @@ -186,14 +190,13 @@ void VtkVisPointSetItem::Initialize(vtkRenderer* renderer) this->setVtkProperties(vtkProps); this->SetActiveAttribute(vtkProps->GetActiveAttribute()); - // Set global backface culling QSettings settings; bool backfaceCulling = settings.value("globalCullBackfaces", 0).toBool(); this->setBackfaceCulling(backfaceCulling); // Set the correct threshold range - if (dynamic_cast<VtkCompositeThresholdFilter*>(this->_compositeFilter) ) + if (dynamic_cast<VtkCompositeThresholdFilter*>(this->_compositeFilter)) { double range[2]; this->GetRangeForActiveAttribute(range); @@ -211,15 +214,15 @@ void VtkVisPointSetItem::Initialize(vtkRenderer* renderer) } } -void VtkVisPointSetItem::SetScalarVisibility( bool on ) +void VtkVisPointSetItem::SetScalarVisibility(bool on) { _mapper->SetScalarVisibility(on); } void VtkVisPointSetItem::setVtkProperties(VtkAlgorithmProperties* vtkProps) { - QObject::connect(vtkProps, SIGNAL(ScalarVisibilityChanged(bool)), - _mapper, SLOT(SetScalarVisibility(bool))); + QObject::connect(vtkProps, SIGNAL(ScalarVisibilityChanged(bool)), _mapper, + SLOT(SetScalarVisibility(bool))); auto* actor = dynamic_cast<vtkActor*>(_actor); if (actor) @@ -227,12 +230,13 @@ void VtkVisPointSetItem::setVtkProperties(VtkAlgorithmProperties* vtkProps) if (vtkProps->GetTexture() != nullptr) { vtkProps->SetScalarVisibility(false); - actor->GetProperty()->SetColor(1,1,1); // don't colorise textures + actor->GetProperty()->SetColor(1, 1, 1); // don't colorise textures actor->SetTexture(vtkProps->GetTexture()); } else { - vtkSmartPointer<vtkProperty> itemProperty = vtkProps->GetProperties(); + vtkSmartPointer<vtkProperty> itemProperty = + vtkProps->GetProperties(); actor->SetProperty(itemProperty); } @@ -243,14 +247,15 @@ void VtkVisPointSetItem::setVtkProperties(VtkAlgorithmProperties* vtkProps) } } -int VtkVisPointSetItem::callVTKWriter(vtkAlgorithm* algorithm, const std::string &filename) const +int VtkVisPointSetItem::callVTKWriter(vtkAlgorithm* algorithm, + const std::string& filename) const { std::string file_name_cpy(filename); auto* algPD = dynamic_cast<vtkPolyDataAlgorithm*>(algorithm); if (algPD) { vtkSmartPointer<vtkXMLPolyDataWriter> pdWriter = - vtkSmartPointer<vtkXMLPolyDataWriter>::New(); + vtkSmartPointer<vtkXMLPolyDataWriter>::New(); pdWriter->SetInputData(algPD->GetOutputDataObject(0)); if (BaseLib::getFileExtension(filename) != ".vtp") { @@ -264,7 +269,7 @@ int VtkVisPointSetItem::callVTKWriter(vtkAlgorithm* algorithm, const std::string if (algUG) { vtkSmartPointer<vtkXMLUnstructuredGridWriter> ugWriter = - vtkSmartPointer<vtkXMLUnstructuredGridWriter>::New(); + vtkSmartPointer<vtkXMLUnstructuredGridWriter>::New(); ugWriter->SetInputData(algUG->GetOutputDataObject(0)); if (BaseLib::getFileExtension(filename) != ".vtu") { @@ -278,7 +283,7 @@ int VtkVisPointSetItem::callVTKWriter(vtkAlgorithm* algorithm, const std::string return 0; } -void VtkVisPointSetItem::SetActiveAttribute( const QString& name ) +void VtkVisPointSetItem::SetActiveAttribute(const QString& name) { // Get type by identifier if (name.contains(QRegExp("^P-"))) @@ -303,7 +308,8 @@ void VtkVisPointSetItem::SetActiveAttribute( const QString& name ) // Remove type identifier _activeArrayName = QString(name).remove(0, 2).toStdString(); - vtkDataSet* dataSet = vtkDataSet::SafeDownCast(this->_algorithm->GetOutputDataObject(0)); + vtkDataSet* dataSet = + vtkDataSet::SafeDownCast(this->_algorithm->GetOutputDataObject(0)); if (!dataSet) { return; @@ -314,20 +320,22 @@ void VtkVisPointSetItem::SetActiveAttribute( const QString& name ) if (_onPointData) { vtkPointData* pointData = dataSet->GetPointData(); - if(pointData) + if (pointData) { - _algorithm->SetInputArrayToProcess(0, 0, 0, - vtkDataObject::FIELD_ASSOCIATION_POINTS, _activeArrayName.c_str()); + _algorithm->SetInputArrayToProcess( + 0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, + _activeArrayName.c_str()); _mapper->SetScalarModeToUsePointFieldData(); } } else { vtkCellData* cellData = dataSet->GetCellData(); - if(cellData) + if (cellData) { - _algorithm->SetInputArrayToProcess(0, 0, 0, - vtkDataObject::FIELD_ASSOCIATION_CELLS, _activeArrayName.c_str()); + _algorithm->SetInputArrayToProcess( + 0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_CELLS, + _activeArrayName.c_str()); _mapper->SetScalarModeToUseCellFieldData(); } } @@ -340,21 +348,25 @@ void VtkVisPointSetItem::SetActiveAttribute( const QString& name ) auto* mapper = dynamic_cast<QVtkDataSetMapper*>(_mapper); if (mapper) { - // Create a default color table when there is no lookup table for this attribute + // Create a default color table when there is no lookup table for this + // attribute vtkLookupTable* lut = _vtkProps->GetLookupTable(name); if (lut == nullptr) { - //std::cout << "Creating new lookup table for: " << name.toStdString() << std::endl; - lut = vtkLookupTable::New(); // is not a memory leak, gets deleted in VtkAlgorithmProperties + // std::cout << "Creating new lookup table for: " << + // name.toStdString() << std::endl; + lut = vtkLookupTable::New(); // is not a memory leak, gets deleted + // in VtkAlgorithmProperties lut->SetTableRange(range); _vtkProps->SetLookUpTable(name, lut); } _mapper->SetLookupTable(lut); } - _mapper->SelectColorArray( _activeArrayName.c_str()); + _mapper->SelectColorArray(_activeArrayName.c_str()); } -bool VtkVisPointSetItem::activeAttributeExists(vtkDataSetAttributes* data, std::string& name) +bool VtkVisPointSetItem::activeAttributeExists(vtkDataSetAttributes* data, + std::string& name) { bool arrayFound = false; for (int i = 0; i < data->GetNumberOfArrays() && !arrayFound; i++) @@ -417,7 +429,8 @@ void VtkVisPointSetItem::setBackfaceCulling(bool enable) const void VtkVisPointSetItem::GetRangeForActiveAttribute(double range[2]) const { - vtkDataSet* dataSet = vtkDataSet::SafeDownCast(this->_algorithm->GetOutputDataObject(0)); + vtkDataSet* dataSet = + vtkDataSet::SafeDownCast(this->_algorithm->GetOutputDataObject(0)); if (dataSet && _activeArrayName.length() > 0) { if (_onPointData) @@ -431,7 +444,7 @@ void VtkVisPointSetItem::GetRangeForActiveAttribute(double range[2]) const else { vtkCellData* cellData = dataSet->GetCellData(); - cellData->GetArray(_activeArrayName.c_str())->GetRange(range); + cellData->GetArray(_activeArrayName.c_str())->GetRange(range); } } } diff --git a/Applications/DataExplorer/VtkVis/VtkVisTabWidget.cpp b/Applications/DataExplorer/VtkVis/VtkVisTabWidget.cpp index 8560a5bf2100d6ec14416ef98280d24ffa722366..c4b97af2fde58eb86eb9ab3ef17fc8422983bd78 100644 --- a/Applications/DataExplorer/VtkVis/VtkVisTabWidget.cpp +++ b/Applications/DataExplorer/VtkVis/VtkVisTabWidget.cpp @@ -14,6 +14,13 @@ #include "VtkVisTabWidget.h" +#include <vtkActor.h> +#include <vtkImageChangeInformation.h> +#include <vtkProperty.h> +#include <vtkTransform.h> +#include <vtkTransformFilter.h> + +#include "BaseLib/Logging.h" #include "VtkAlgorithmPropertyCheckbox.h" #include "VtkAlgorithmPropertyLineEdit.h" #include "VtkAlgorithmPropertyVectorEdit.h" @@ -22,14 +29,6 @@ #include "VtkVisImageItem.h" #include "VtkVisPipelineItem.h" -#include "BaseLib/Logging.h" - -#include <vtkActor.h> -#include <vtkImageChangeInformation.h> -#include <vtkProperty.h> -#include <vtkTransform.h> -#include <vtkTransformFilter.h> - VtkVisTabWidget::VtkVisTabWidget(QWidget* parent /*= 0*/) : QWidget(parent) { setupUi(this); @@ -40,25 +39,27 @@ VtkVisTabWidget::VtkVisTabWidget(QWidget* parent /*= 0*/) : QWidget(parent) this->transY->setValidator(new QDoubleValidator(this)); this->transZ->setValidator(new QDoubleValidator(this)); - connect(this->vtkVisPipelineView, SIGNAL(requestViewUpdate()), - this, SIGNAL(requestViewUpdate())); + connect(this->vtkVisPipelineView, SIGNAL(requestViewUpdate()), this, + SIGNAL(requestViewUpdate())); connect(this->vtkVisPipelineView, SIGNAL(itemSelected(VtkVisPipelineItem*)), this, SLOT(setActiveItem(VtkVisPipelineItem*))); - connect(this->activeScalarComboBox, SIGNAL(currentIndexChanged(const QString &)), - this, SLOT(SetActiveAttributeOnItem(const QString &))); + connect(this->activeScalarComboBox, + SIGNAL(currentIndexChanged(const QString&)), this, + SLOT(SetActiveAttributeOnItem(const QString&))); } void VtkVisTabWidget::on_arrayResetPushButton_clicked() { VtkAlgorithmProperties* props = _item->getVtkProperties(); - const QString selected_array_name = this->activeScalarComboBox->currentText(); + const QString selected_array_name = + this->activeScalarComboBox->currentText(); props->RemoveLookupTable(selected_array_name); _item->SetActiveAttribute(selected_array_name); } -void VtkVisTabWidget::setActiveItem( VtkVisPipelineItem* item ) +void VtkVisTabWidget::setActiveItem(VtkVisPipelineItem* item) { if (item) { @@ -67,10 +68,11 @@ void VtkVisTabWidget::setActiveItem( VtkVisPipelineItem* item ) auto* transform_filter = dynamic_cast<vtkTransformFilter*>(_item->transformFilter()); - if (transform_filter) // if data set + if (transform_filter) // if data set { actorPropertiesGroupBox->setEnabled(true); - vtkProperty* vtkProps = static_cast<vtkActor*>(_item->actor())->GetProperty(); + vtkProperty* vtkProps = + static_cast<vtkActor*>(_item->actor())->GetProperty(); diffuseColorPickerButton->setColor(vtkProps->GetDiffuseColor()); visibleEdgesCheckBox->setChecked(vtkProps->GetEdgeVisibility()); edgeColorPickerButton->setColor(vtkProps->GetEdgeColor()); @@ -86,7 +88,8 @@ void VtkVisTabWidget::setActiveItem( VtkVisPipelineItem* item ) double trans[3]; transform->GetPosition(trans); - //switch signals off for just filling in text-boxes after clicking on an item + // switch signals off for just filling in text-boxes after + // clicking on an item this->scaleZ->blockSignals(true); this->transX->blockSignals(true); this->transY->blockSignals(true); @@ -99,7 +102,7 @@ void VtkVisTabWidget::setActiveItem( VtkVisPipelineItem* item ) this->transX->blockSignals(false); this->transY->blockSignals(false); this->transZ->blockSignals(false); - //switch signals back on + // switch signals back on } this->buildScalarArrayComboBox(_item); @@ -118,7 +121,7 @@ void VtkVisTabWidget::setActiveItem( VtkVisPipelineItem* item ) } } } - else // if image + else // if image { const VtkVisImageItem* img = static_cast<VtkVisImageItem*>(_item); actorPropertiesGroupBox->setEnabled(false); @@ -149,44 +152,52 @@ void VtkVisTabWidget::setActiveItem( VtkVisPipelineItem* item ) } } -void VtkVisTabWidget::on_diffuseColorPickerButton_colorPicked( QColor color ) +void VtkVisTabWidget::on_diffuseColorPickerButton_colorPicked(QColor color) { - static_cast<vtkActor*>(_item->actor())->GetProperty()->SetDiffuseColor( - color.redF(), color.greenF(), color.blueF()); + static_cast<vtkActor*>(_item->actor()) + ->GetProperty() + ->SetDiffuseColor(color.redF(), color.greenF(), color.blueF()); emit requestViewUpdate(); } -void VtkVisTabWidget::on_visibleEdgesCheckBox_stateChanged( int state ) +void VtkVisTabWidget::on_visibleEdgesCheckBox_stateChanged(int state) { if (state == Qt::Checked) { - static_cast<vtkActor*>(_item->actor())->GetProperty()->SetEdgeVisibility(1); + static_cast<vtkActor*>(_item->actor()) + ->GetProperty() + ->SetEdgeVisibility(1); edgeColorPickerButton->setEnabled(true); } else { - static_cast<vtkActor*>(_item->actor())->GetProperty()->SetEdgeVisibility(0); + static_cast<vtkActor*>(_item->actor()) + ->GetProperty() + ->SetEdgeVisibility(0); edgeColorPickerButton->setEnabled(false); } emit requestViewUpdate(); } -void VtkVisTabWidget::on_edgeColorPickerButton_colorPicked( QColor color ) +void VtkVisTabWidget::on_edgeColorPickerButton_colorPicked(QColor color) { - static_cast<vtkActor*>(_item->actor())->GetProperty()->SetEdgeColor( - color.redF(), color.greenF(), color.blueF()); + static_cast<vtkActor*>(_item->actor()) + ->GetProperty() + ->SetEdgeColor(color.redF(), color.greenF(), color.blueF()); emit requestViewUpdate(); } -void VtkVisTabWidget::on_opacitySlider_sliderMoved( int value ) +void VtkVisTabWidget::on_opacitySlider_sliderMoved(int value) { - static_cast<vtkActor*>(_item->actor())->GetProperty()->SetOpacity(value / 100.0); + static_cast<vtkActor*>(_item->actor()) + ->GetProperty() + ->SetOpacity(value / 100.0); emit requestViewUpdate(); } -void VtkVisTabWidget::on_scaleZ_textChanged(const QString &text) +void VtkVisTabWidget::on_scaleZ_textChanged(const QString& text) { bool ok = true; double scale = text.toDouble(&ok); @@ -281,45 +292,41 @@ void VtkVisTabWidget::buildProportiesDialog(VtkVisPipelineItem* item) VtkAlgorithmPropertyCheckbox* checkbox; switch (value.type()) { - case QVariant::Double: - lineEdit = - new VtkAlgorithmPropertyLineEdit(QString::number( - value.toDouble()), - key, QVariant::Double, - algProps); - connect(lineEdit, SIGNAL(editingFinished()), this, - SIGNAL(requestViewUpdate())); - layout->addRow(key, lineEdit); - break; - - case QVariant::Int: - lineEdit = - new VtkAlgorithmPropertyLineEdit(QString::number( - value.toInt()), - key, QVariant::Int, - algProps); - connect(lineEdit, SIGNAL(editingFinished()), this, - SIGNAL(requestViewUpdate())); - layout->addRow(key, lineEdit); - break; - - case QVariant::Bool: - checkbox = new VtkAlgorithmPropertyCheckbox( - value.toBool(), key, algProps); - connect(checkbox, SIGNAL(stateChanged(int)), this, - SIGNAL(requestViewUpdate())); - layout->addRow(key, checkbox); - break; - - default: - break; + case QVariant::Double: + lineEdit = new VtkAlgorithmPropertyLineEdit( + QString::number(value.toDouble()), key, + QVariant::Double, algProps); + connect(lineEdit, SIGNAL(editingFinished()), this, + SIGNAL(requestViewUpdate())); + layout->addRow(key, lineEdit); + break; + + case QVariant::Int: + lineEdit = new VtkAlgorithmPropertyLineEdit( + QString::number(value.toInt()), key, QVariant::Int, + algProps); + connect(lineEdit, SIGNAL(editingFinished()), this, + SIGNAL(requestViewUpdate())); + layout->addRow(key, lineEdit); + break; + + case QVariant::Bool: + checkbox = new VtkAlgorithmPropertyCheckbox(value.toBool(), + key, algProps); + connect(checkbox, SIGNAL(stateChanged(int)), this, + SIGNAL(requestViewUpdate())); + layout->addRow(key, checkbox); + break; + + default: + break; } } } if (propVecMap) { - QMapIterator<QString, QList<QVariant> > i(*propVecMap); + QMapIterator<QString, QList<QVariant>> i(*propVecMap); while (i.hasNext()) { i.next(); @@ -330,7 +337,7 @@ void VtkVisTabWidget::buildProportiesDialog(VtkVisPipelineItem* item) { QList<QString> valuesAsString; foreach (QVariant variant, values) - valuesAsString.push_back(variant.toString()); + valuesAsString.push_back(variant.toString()); VtkAlgorithmPropertyVectorEdit* vectorEdit = new VtkAlgorithmPropertyVectorEdit( @@ -346,7 +353,7 @@ void VtkVisTabWidget::buildProportiesDialog(VtkVisPipelineItem* item) void VtkVisTabWidget::buildScalarArrayComboBox(VtkVisPipelineItem* item) { QStringList dataSetAttributesList = item->getScalarArrayNames(); - dataSetAttributesList.push_back("Solid Color"); // all scalars switched off + dataSetAttributesList.push_back("Solid Color"); // all scalars switched off this->activeScalarComboBox->blockSignals(true); this->activeScalarComboBox->clear(); this->activeScalarComboBox->insertItems(0, dataSetAttributesList); @@ -364,7 +371,7 @@ void VtkVisTabWidget::buildScalarArrayComboBox(VtkVisPipelineItem* item) it != dataSetAttributesList.end(); ++it) { - if (active_array_name.compare((*it).right((*it).length()-2))==0) + if (active_array_name.compare((*it).right((*it).length() - 2)) == 0) { this->activeScalarComboBox->setCurrentIndex(idx); break; @@ -375,9 +382,8 @@ void VtkVisTabWidget::buildScalarArrayComboBox(VtkVisPipelineItem* item) } } -void VtkVisTabWidget::SetActiveAttributeOnItem( const QString &name ) +void VtkVisTabWidget::SetActiveAttributeOnItem(const QString& name) { _item->SetActiveAttribute(name); emit requestViewUpdate(); } - diff --git a/Applications/DataExplorer/main.cpp b/Applications/DataExplorer/main.cpp index 2c7e28772a3d77e08f82600df0fa27b6499cba90..eb33b1c2368798995fc3130687b6f3c3baef9a06 100644 --- a/Applications/DataExplorer/main.cpp +++ b/Applications/DataExplorer/main.cpp @@ -1,13 +1,13 @@ -#include "mainwindow.h" +#include <QVTKOpenGLWidget.h> +#include <vtkSmartPointer.h> #include <QApplication> #include <QSurfaceFormat> -#include <QVTKOpenGLWidget.h> #include <memory> -#include <vtkSmartPointer.h> #include "InfoLib/GitInfo.h" #include "VtkVis/VtkConsoleOutputWindow.h" +#include "mainwindow.h" int main(int argc, char* argv[]) { @@ -19,16 +19,17 @@ int main(int argc, char* argv[]) QApplication a(argc, argv); QApplication::setApplicationName("OpenGeoSys - Data Explorer"); - QApplication::setApplicationVersion(QString::fromStdString( - GitInfoLib::GitInfo::ogs_version)); + QApplication::setApplicationVersion( + QString::fromStdString(GitInfoLib::GitInfo::ogs_version)); QApplication::setOrganizationName("OpenGeoSys Community"); QApplication::setOrganizationDomain("opengeosys.org"); - setlocale(LC_NUMERIC,"C"); + setlocale(LC_NUMERIC, "C"); QLocale::setDefault(QLocale::German); auto w = std::make_unique<MainWindow>(); - w->setWindowTitle( w->windowTitle() + " - " + - QString::fromStdString(GitInfoLib::GitInfo::ogs_version)); - if (QCoreApplication::arguments().size()>1) { + w->setWindowTitle(w->windowTitle() + " - " + + QString::fromStdString(GitInfoLib::GitInfo::ogs_version)); + if (QCoreApplication::arguments().size() > 1) + { w->loadFileOnStartUp(QCoreApplication::arguments().at(1)); } w->show(); diff --git a/Applications/DataExplorer/mainwindow.cpp b/Applications/DataExplorer/mainwindow.cpp index da7f10411de85567216ae437054242ccad27e076..f5d42b5196f3f7236d4a79f27e5d3d4db7bb7a92 100644 --- a/Applications/DataExplorer/mainwindow.cpp +++ b/Applications/DataExplorer/mainwindow.cpp @@ -48,13 +48,13 @@ #include "Applications/FileIO/TetGenInterface.h" #include "Applications/FileIO/XmlIO/Qt/XmlPrjInterface.h" #include "Applications/Utils/OGSFileConverter/OGSFileConverter.h" -#include "InfoLib/GitInfo.h" #include "BaseLib/FileTools.h" #include "BaseLib/Histogram.h" #include "GeoLib/DuplicateGeometry.h" #include "GeoLib/IO/XmlIO/Qt/XmlGmlInterface.h" #include "GeoLib/IO/XmlIO/Qt/XmlStnInterface.h" #include "GeoLib/Raster.h" +#include "InfoLib/GitInfo.h" #include "MeshGeoToolsLib/GeoMapper.h" #include "MeshLib/Elements/Element.h" #include "MeshLib/IO/Legacy/MeshIO.h" @@ -81,16 +81,15 @@ #ifdef OGS_USE_NETCDF #include "NetCdfConfigureDialog.h" #endif // OGS_USE_NETCDF -#include "SHPImportDialog.h" -#include "SetNameDialog.h" -#include "VtkAddFilterDialog.h" - #include "GeoTreeModel.h" #include "LastSavedFileDirectory.h" #include "OGSError.h" #include "RecentFiles.h" +#include "SHPImportDialog.h" +#include "SetNameDialog.h" #include "StationTreeModel.h" #include "TreeModelIterator.h" +#include "VtkAddFilterDialog.h" #include "VtkBGImageSource.h" #include "VtkGeoImageSource.h" #include "VtkRaster.h" @@ -121,71 +120,113 @@ MainWindow::MainWindow(QWidget* parent /* = 0*/) : QMainWindow(parent) std::make_unique<VtkVisPipeline>(visualizationWidget->renderer()); // station model connects - connect(stationTabWidget->treeView, SIGNAL(openStationListFile(int)), - this, SLOT(open(int))); - connect(stationTabWidget->treeView, SIGNAL(stationListExportRequested(std::string, std::string)), - this, SLOT(exportBoreholesToGMS(std::string, std::string))); // export Stationlist to GMS - connect(stationTabWidget->treeView, SIGNAL(stationListRemoved(std::string)), _geo_model.get(), - SLOT(removeStationVec(std::string))); // update model when stations are removed - connect(stationTabWidget->treeView, SIGNAL(stationListSaved(QString, QString)), this, - SLOT(writeStationListToFile(QString, QString))); // save Stationlist to File - connect(_geo_model.get(), SIGNAL(stationVectorRemoved(StationTreeModel *, std::string)), - this, SLOT(updateDataViews())); // update data view when stations are removed - connect(stationTabWidget->treeView, SIGNAL(requestNameChangeDialog(const std::string&, std::size_t)), + connect(stationTabWidget->treeView, SIGNAL(openStationListFile(int)), this, + SLOT(open(int))); + connect(stationTabWidget->treeView, + SIGNAL(stationListExportRequested(std::string, std::string)), this, + SLOT(exportBoreholesToGMS( + std::string, std::string))); // export Stationlist to GMS + connect(stationTabWidget->treeView, SIGNAL(stationListRemoved(std::string)), + _geo_model.get(), + SLOT(removeStationVec( + std::string))); // update model when stations are removed + connect(stationTabWidget->treeView, + SIGNAL(stationListSaved(QString, QString)), this, + SLOT(writeStationListToFile(QString, + QString))); // save Stationlist to File + connect( + _geo_model.get(), + SIGNAL(stationVectorRemoved(StationTreeModel*, std::string)), this, + SLOT(updateDataViews())); // update data view when stations are removed + connect(stationTabWidget->treeView, + SIGNAL(requestNameChangeDialog(const std::string&, std::size_t)), this, SLOT(showStationNameDialog(const std::string&, std::size_t))); - connect(stationTabWidget->treeView, SIGNAL(diagramRequested(QModelIndex &)), - this, SLOT(showDiagramPrefsDialog(QModelIndex &))); // connect treeview to diagramview + connect(stationTabWidget->treeView, SIGNAL(diagramRequested(QModelIndex&)), + this, + SLOT(showDiagramPrefsDialog( + QModelIndex&))); // connect treeview to diagramview // geo model connects - connect(geoTabWidget->treeView, SIGNAL(openGeometryFile(int)), - this, SLOT(open(int))); - connect(geoTabWidget->treeView, SIGNAL(listRemoved(std::string, GeoLib::GEOTYPE)), - _geo_model.get(), SLOT(removeGeometry(std::string, GeoLib::GEOTYPE))); - connect(geoTabWidget->treeView, SIGNAL(geometryMappingRequested(const std::string&)), - this, SLOT(mapGeometry(const std::string&))); - connect(geoTabWidget->treeView, SIGNAL(saveToFileRequested(QString, QString)), - this, SLOT(writeGeometryToFile(QString, QString))); // save geometry to file - connect(geoTabWidget->treeView, SIGNAL(requestPointToStationConversion(std::string const&)), this, - SLOT(convertPointsToStations( std::string const&))); - connect(geoTabWidget->treeView, SIGNAL(requestLineEditDialog(const std::string &)), - this, SLOT(showLineEditDialog(const std::string &))); // open line edit dialog - connect(geoTabWidget->treeView, SIGNAL(requestNameChangeDialog(const std::string&, const GeoLib::GEOTYPE, std::size_t)), - this, SLOT(showGeoNameDialog(const std::string&, const GeoLib::GEOTYPE, std::size_t))); - connect(_geo_model.get(), SIGNAL(geoDataAdded(GeoTreeModel *, std::string, GeoLib::GEOTYPE)), + connect(geoTabWidget->treeView, SIGNAL(openGeometryFile(int)), this, + SLOT(open(int))); + connect(geoTabWidget->treeView, + SIGNAL(listRemoved(std::string, GeoLib::GEOTYPE)), _geo_model.get(), + SLOT(removeGeometry(std::string, GeoLib::GEOTYPE))); + connect(geoTabWidget->treeView, + SIGNAL(geometryMappingRequested(const std::string&)), this, + SLOT(mapGeometry(const std::string&))); + connect( + geoTabWidget->treeView, SIGNAL(saveToFileRequested(QString, QString)), + this, + SLOT(writeGeometryToFile(QString, QString))); // save geometry to file + connect(geoTabWidget->treeView, + SIGNAL(requestPointToStationConversion(std::string const&)), this, + SLOT(convertPointsToStations(std::string const&))); + connect( + geoTabWidget->treeView, + SIGNAL(requestLineEditDialog(const std::string&)), this, + SLOT(showLineEditDialog(const std::string&))); // open line edit dialog + connect(geoTabWidget->treeView, + SIGNAL(requestNameChangeDialog(const std::string&, + const GeoLib::GEOTYPE, std::size_t)), + this, + SLOT(showGeoNameDialog(const std::string&, const GeoLib::GEOTYPE, + std::size_t))); + connect(_geo_model.get(), + SIGNAL(geoDataAdded(GeoTreeModel*, std::string, GeoLib::GEOTYPE)), this, SLOT(updateDataViews())); - connect(_geo_model.get(), SIGNAL(geoDataRemoved(GeoTreeModel *, std::string, GeoLib::GEOTYPE)), + connect(_geo_model.get(), + SIGNAL(geoDataRemoved(GeoTreeModel*, std::string, GeoLib::GEOTYPE)), this, SLOT(updateDataViews())); - connect(geoTabWidget->treeView, SIGNAL(geoItemSelected(const vtkPolyDataAlgorithm*, int)), - _vtkVisPipeline.get(), SLOT(highlightGeoObject(const vtkPolyDataAlgorithm*, int))); + connect(geoTabWidget->treeView, + SIGNAL(geoItemSelected(const vtkPolyDataAlgorithm*, int)), + _vtkVisPipeline.get(), + SLOT(highlightGeoObject(const vtkPolyDataAlgorithm*, int))); connect(geoTabWidget->treeView, SIGNAL(removeGeoItemSelection()), _vtkVisPipeline.get(), SLOT(removeHighlightedGeoObject())); - connect(stationTabWidget->treeView, SIGNAL(geoItemSelected(const vtkPolyDataAlgorithm*, int)), - _vtkVisPipeline.get(), SLOT(highlightGeoObject(const vtkPolyDataAlgorithm*, int))); + connect(stationTabWidget->treeView, + SIGNAL(geoItemSelected(const vtkPolyDataAlgorithm*, int)), + _vtkVisPipeline.get(), + SLOT(highlightGeoObject(const vtkPolyDataAlgorithm*, int))); connect(stationTabWidget->treeView, SIGNAL(removeGeoItemSelection()), _vtkVisPipeline.get(), SLOT(removeHighlightedGeoObject())); // Setup connections for mesh models to GUI - connect(meshTabWidget->treeView, SIGNAL(openMeshFile(int)), - this, SLOT(open(int))); - connect(meshTabWidget->treeView, SIGNAL(requestMeshRemoval(const QModelIndex &)), - _meshModel.get(), SLOT(removeMesh(const QModelIndex &))); - connect(meshTabWidget->treeView, SIGNAL(requestMeshRemoval(const QModelIndex &)), - _elementModel.get(), SLOT(clearView())); + connect(meshTabWidget->treeView, SIGNAL(openMeshFile(int)), this, + SLOT(open(int))); + connect(meshTabWidget->treeView, + SIGNAL(requestMeshRemoval(const QModelIndex&)), _meshModel.get(), + SLOT(removeMesh(const QModelIndex&))); connect(meshTabWidget->treeView, + SIGNAL(requestMeshRemoval(const QModelIndex&)), _elementModel.get(), + SLOT(clearView())); + connect( + meshTabWidget->treeView, SIGNAL(qualityCheckRequested(MeshLib::VtkMappedMeshSource*)), - this, - SLOT(showMeshQualitySelectionDialog(MeshLib::VtkMappedMeshSource*))); - connect(meshTabWidget->treeView, SIGNAL(requestMeshToGeometryConversion(const MeshLib::Mesh*)), - this, SLOT(convertMeshToGeometry(const MeshLib::Mesh*))); - connect(meshTabWidget->treeView, SIGNAL(elementSelected(vtkUnstructuredGridAlgorithm const*const, unsigned, bool)), - _vtkVisPipeline.get(), SLOT(highlightMeshComponent(vtkUnstructuredGridAlgorithm const*const, unsigned, bool))); + this, + SLOT(showMeshQualitySelectionDialog(MeshLib::VtkMappedMeshSource*))); + connect(meshTabWidget->treeView, + SIGNAL(requestMeshToGeometryConversion(const MeshLib::Mesh*)), this, + SLOT(convertMeshToGeometry(const MeshLib::Mesh*))); + connect(meshTabWidget->treeView, + SIGNAL(elementSelected(vtkUnstructuredGridAlgorithm const* const, + unsigned, bool)), + _vtkVisPipeline.get(), + SLOT(highlightMeshComponent( + vtkUnstructuredGridAlgorithm const* const, unsigned, bool))); connect(meshTabWidget->treeView, SIGNAL(meshSelected(MeshLib::Mesh const&)), this->_elementModel.get(), SLOT(setMesh(MeshLib::Mesh const&))); connect(meshTabWidget->treeView, SIGNAL(meshSelected(MeshLib::Mesh const&)), meshTabWidget->elementView, SLOT(updateView())); - connect(meshTabWidget->treeView, SIGNAL(elementSelected(vtkUnstructuredGridAlgorithm const*const, unsigned, bool)), - this->_elementModel.get(), SLOT(setElement(vtkUnstructuredGridAlgorithm const*const, unsigned))); - connect(meshTabWidget->treeView, SIGNAL(elementSelected(vtkUnstructuredGridAlgorithm const*const, unsigned, bool)), + connect( + meshTabWidget->treeView, + SIGNAL(elementSelected(vtkUnstructuredGridAlgorithm const* const, + unsigned, bool)), + this->_elementModel.get(), + SLOT(setElement(vtkUnstructuredGridAlgorithm const* const, unsigned))); + connect(meshTabWidget->treeView, + SIGNAL(elementSelected(vtkUnstructuredGridAlgorithm const* const, + unsigned, bool)), meshTabWidget->elementView, SLOT(updateView())); connect(meshTabWidget->treeView, SIGNAL(elementSelected(vtkUnstructuredGridAlgorithm const* const, @@ -199,8 +240,12 @@ MainWindow::MainWindow(QWidget* parent /* = 0*/) : QMainWindow(parent) unsigned, bool)), reinterpret_cast<QObject*>(visualizationWidget->interactorStyle()), SLOT(removeHighlightActor())); - connect(meshTabWidget->elementView, SIGNAL(nodeSelected(vtkUnstructuredGridAlgorithm const*const, unsigned, bool)), - _vtkVisPipeline.get(), SLOT(highlightMeshComponent(vtkUnstructuredGridAlgorithm const*const, unsigned, bool))); + connect(meshTabWidget->elementView, + SIGNAL(nodeSelected(vtkUnstructuredGridAlgorithm const* const, + unsigned, bool)), + _vtkVisPipeline.get(), + SLOT(highlightMeshComponent( + vtkUnstructuredGridAlgorithm const* const, unsigned, bool))); connect(meshTabWidget->elementView, SIGNAL(removeSelectedMeshComponent()), _vtkVisPipeline.get(), SLOT(removeHighlightedMeshComponent())); @@ -230,31 +275,43 @@ MainWindow::MainWindow(QWidget* parent /* = 0*/) : QMainWindow(parent) modellingTabWidget->conditionView, SLOT(updateView())); // VisPipeline Connects - connect(_geo_model.get(), SIGNAL(geoDataAdded(GeoTreeModel *, std::string, GeoLib::GEOTYPE)), - _vtkVisPipeline.get(), SLOT(addPipelineItem(GeoTreeModel *, std::string, GeoLib::GEOTYPE))); - connect(_geo_model.get(), SIGNAL(geoDataRemoved(GeoTreeModel *, std::string, GeoLib::GEOTYPE)), - _vtkVisPipeline.get(), SLOT(removeSourceItem(GeoTreeModel *, std::string, GeoLib::GEOTYPE))); - - connect(_geo_model.get(), SIGNAL(stationVectorAdded(StationTreeModel *, std::string)), - _vtkVisPipeline.get(), SLOT(addPipelineItem(StationTreeModel *, std::string))); - connect(_geo_model.get(), SIGNAL(stationVectorRemoved(StationTreeModel *, std::string)), - _vtkVisPipeline.get(), SLOT(removeSourceItem(StationTreeModel *, std::string))); - - connect(_meshModel.get(), SIGNAL(meshAdded(MeshModel *, QModelIndex)), - _vtkVisPipeline.get(), SLOT(addPipelineItem(MeshModel *,QModelIndex))); - connect(_meshModel.get(), SIGNAL(meshRemoved(MeshModel *, QModelIndex)), - _vtkVisPipeline.get(), SLOT(removeSourceItem(MeshModel *, QModelIndex))); + connect(_geo_model.get(), + SIGNAL(geoDataAdded(GeoTreeModel*, std::string, GeoLib::GEOTYPE)), + _vtkVisPipeline.get(), + SLOT(addPipelineItem(GeoTreeModel*, std::string, GeoLib::GEOTYPE))); + connect( + _geo_model.get(), + SIGNAL(geoDataRemoved(GeoTreeModel*, std::string, GeoLib::GEOTYPE)), + _vtkVisPipeline.get(), + SLOT(removeSourceItem(GeoTreeModel*, std::string, GeoLib::GEOTYPE))); + + connect(_geo_model.get(), + SIGNAL(stationVectorAdded(StationTreeModel*, std::string)), + _vtkVisPipeline.get(), + SLOT(addPipelineItem(StationTreeModel*, std::string))); + connect(_geo_model.get(), + SIGNAL(stationVectorRemoved(StationTreeModel*, std::string)), + _vtkVisPipeline.get(), + SLOT(removeSourceItem(StationTreeModel*, std::string))); + + connect(_meshModel.get(), SIGNAL(meshAdded(MeshModel*, QModelIndex)), + _vtkVisPipeline.get(), + SLOT(addPipelineItem(MeshModel*, QModelIndex))); + connect(_meshModel.get(), SIGNAL(meshRemoved(MeshModel*, QModelIndex)), + _vtkVisPipeline.get(), + SLOT(removeSourceItem(MeshModel*, QModelIndex))); connect(_vtkVisPipeline.get(), SIGNAL(vtkVisPipelineChanged()), visualizationWidget->vtkWidget, SLOT(update())); connect(_vtkVisPipeline.get(), SIGNAL(vtkVisPipelineChanged()), vtkVisTabWidget->vtkVisPipelineView, SLOT(expandAll())); connect(_vtkVisPipeline.get(), SIGNAL(itemSelected(const QModelIndex&)), - vtkVisTabWidget->vtkVisPipelineView, SLOT(selectItem(const QModelIndex&))); - + vtkVisTabWidget->vtkVisPipelineView, + SLOT(selectItem(const QModelIndex&))); vtkVisTabWidget->vtkVisPipelineView->setModel(_vtkVisPipeline.get()); - connect(vtkVisTabWidget->vtkVisPipelineView, SIGNAL(requestRemovePipelineItem(QModelIndex)), + connect(vtkVisTabWidget->vtkVisPipelineView, + SIGNAL(requestRemovePipelineItem(QModelIndex)), _vtkVisPipeline.get(), SLOT(removePipelineItem(QModelIndex))); connect(vtkVisTabWidget->vtkVisPipelineView, SIGNAL(requestAddPipelineFilterItem(QModelIndex)), this, @@ -296,8 +353,9 @@ MainWindow::MainWindow(QWidget* parent /* = 0*/) : QMainWindow(parent) this->_vtkVisPipeline.get(), SLOT(removeHighlightedMeshComponent())); - connect(vtkVisTabWidget->vtkVisPipelineView, SIGNAL(meshAdded(MeshLib::Mesh*)), - _meshModel.get(), SLOT(addMesh(MeshLib::Mesh*))); + connect(vtkVisTabWidget->vtkVisPipelineView, + SIGNAL(meshAdded(MeshLib::Mesh*)), _meshModel.get(), + SLOT(addMesh(MeshLib::Mesh*))); // Stack the data dock widgets together tabifyDockWidget(geoDock, mshDock); @@ -315,11 +373,12 @@ MainWindow::MainWindow(QWidget* parent /* = 0*/) : QMainWindow(parent) } // Setup import files menu - QMenu* import_files_menu = createImportFilesMenu(); //owned by MainWindow + QMenu* import_files_menu = createImportFilesMenu(); // owned by MainWindow menu_File->insertMenu(action_Exit, import_files_menu); // Setup recent files menu - RecentFiles* recentFiles = new RecentFiles(this, SLOT(openRecentFile()), "recentFileList"); + RecentFiles* recentFiles = + new RecentFiles(this, SLOT(openRecentFile()), "recentFileList"); connect(this, SIGNAL(fileUsed(QString)), recentFiles, SLOT(setCurrentFile(QString))); menu_File->insertMenu(action_Exit, recentFiles->menu()); @@ -436,17 +495,18 @@ void MainWindow::open(int file_type) { QSettings settings; auto t = static_cast<ImportFileType::type>(file_type); - QString type_str = QString::fromStdString((ImportFileType::convertImportFileTypeToString(t))); - QString fileName = QFileDialog::getOpenFileName(this, "Select " + type_str + " file to import", - settings.value("lastOpenedFileDirectory").toString(), - QString::fromStdString(ImportFileType::getFileSuffixString(t))); + QString type_str = QString::fromStdString( + (ImportFileType::convertImportFileTypeToString(t))); + QString fileName = QFileDialog::getOpenFileName( + this, "Select " + type_str + " file to import", + settings.value("lastOpenedFileDirectory").toString(), + QString::fromStdString(ImportFileType::getFileSuffixString(t))); if (!fileName.isEmpty()) { loadFile(t, fileName); QDir dir = QDir(fileName); settings.setValue("lastOpenedFileDirectory", dir.absolutePath()); } - } void MainWindow::openRecentFile() @@ -506,14 +566,15 @@ void MainWindow::save() } } -void MainWindow::loadFile(ImportFileType::type t, const QString &fileName) +void MainWindow::loadFile(ImportFileType::type t, const QString& fileName) { QFile file(fileName); if (!file.exists()) { - QMessageBox::warning(this, tr("Application"), tr( - "Cannot read file %1:\n%2.").arg(fileName).arg( - file.errorString())); + QMessageBox::warning(this, tr("Application"), + tr("Cannot read file %1:\n%2.") + .arg(fileName) + .arg(file.errorString())); return; } @@ -521,9 +582,11 @@ void MainWindow::loadFile(ImportFileType::type t, const QString &fileName) QFileInfo fi(fileName); QSettings settings; QDir dir = QDir(fileName); - std::string base = fi.absoluteDir().absoluteFilePath(fi.completeBaseName()).toStdString(); + std::string base = + fi.absoluteDir().absoluteFilePath(fi.completeBaseName()).toStdString(); - if (t == ImportFileType::OGS || t == ImportFileType::OGS_GEO || t == ImportFileType::OGS_STN || t == ImportFileType::OGS_MSH) + if (t == ImportFileType::OGS || t == ImportFileType::OGS_GEO || + t == ImportFileType::OGS_STN || t == ImportFileType::OGS_MSH) { if (fi.suffix().toLower() == "gli") { @@ -617,7 +680,7 @@ void MainWindow::loadFile(ImportFileType::type t, const QString &fileName) } else if (t == ImportFileType::FEFLOW) { - if (fi.suffix().toLower() == "fem") // FEFLOW model files + if (fi.suffix().toLower() == "fem") // FEFLOW model files { FileIO::FEFLOWMeshInterface feflowMeshIO; std::unique_ptr<MeshLib::Mesh> mesh( @@ -631,14 +694,14 @@ void MainWindow::loadFile(ImportFileType::type t, const QString &fileName) OGSError::box("Failed to load a FEFLOW mesh."); } FileIO::FEFLOWGeoInterface feflowGeoIO; - feflowGeoIO.readFEFLOWFile(fileName.toStdString(), _project.getGEOObjects()); + feflowGeoIO.readFEFLOWFile(fileName.toStdString(), + _project.getGEOObjects()); } settings.setValue("lastOpenedFileDirectory", dir.absolutePath()); - } else if (t == ImportFileType::GMS) { - if (fi.suffix().toLower() == "txt") // GMS borehole files + if (fi.suffix().toLower() == "txt") // GMS borehole files { auto boreholes = std::make_unique<std::vector<GeoLib::Point*>>(); std::string name = fi.baseName().toStdString(); @@ -646,17 +709,19 @@ void MainWindow::loadFile(ImportFileType::type t, const QString &fileName) if (GMSInterface::readBoreholesFromGMS(boreholes.get(), fileName.toStdString())) { - _project.getGEOObjects().addStationVec(std::move(boreholes), name); + _project.getGEOObjects().addStationVec(std::move(boreholes), + name); } else { OGSError::box("Error reading GMS file."); } } - else if (fi.suffix().toLower() == "3dm") // GMS mesh files + else if (fi.suffix().toLower() == "3dm") // GMS mesh files { std::string name = fileName.toStdString(); - std::unique_ptr<MeshLib::Mesh> mesh(GMSInterface::readGMS3DMMesh(name)); + std::unique_ptr<MeshLib::Mesh> mesh( + GMSInterface::readGMS3DMMesh(name)); if (mesh) { _meshModel->addMesh(std::move(mesh)); @@ -670,10 +735,11 @@ void MainWindow::loadFile(ImportFileType::type t, const QString &fileName) } else if (t == ImportFileType::GMSH) { - std::string msh_name (fileName.toStdString()); - if (FileIO::GMSH::isGMSHMeshFile (msh_name)) + std::string msh_name(fileName.toStdString()); + if (FileIO::GMSH::isGMSHMeshFile(msh_name)) { - std::unique_ptr<MeshLib::Mesh> mesh(FileIO::GMSH::readGMSHMesh(msh_name)); + std::unique_ptr<MeshLib::Mesh> mesh( + FileIO::GMSH::readGMSHMesh(msh_name)); if (mesh) { _meshModel->addMesh(std::move(mesh)); @@ -706,9 +772,8 @@ void MainWindow::loadFile(ImportFileType::type t, const QString &fileName) settings.setValue("lastOpenedFileDirectory", dir.absolutePath()); } #ifdef OGS_USE_NETCDF - else if (t == ImportFileType::NETCDF) // CH 01.2012 + else if (t == ImportFileType::NETCDF) // CH 01.2012 { - NetCdfConfigureDialog dlg(fileName.toStdString()); dlg.exec(); if (dlg.getMesh()) @@ -743,7 +808,8 @@ void MainWindow::loadFile(ImportFileType::type t, const QString &fileName) vtkImageAlgorithm* img = VtkRaster::loadImage(fileName.toStdString()); VtkBGImageSource* bg = VtkBGImageSource::New(); double* origin = img->GetOutput()->GetOrigin(); - bg->SetRaster(img, origin[0], origin[1], img->GetOutput()->GetSpacing()[0]); + bg->SetRaster(img, origin[0], origin[1], + img->GetOutput()->GetSpacing()[0]); bg->SetName(fileName); _vtkVisPipeline->addPipelineItem(bg); settings.setValue("lastOpenedRasterFileDirectory", dir.absolutePath()); @@ -759,14 +825,19 @@ void MainWindow::loadFile(ImportFileType::type t, const QString &fileName) } else if (t == ImportFileType::TETGEN) { - if (fi.suffix().toLower().compare("poly") == 0 || fi.suffix().toLower().compare("smesh") == 0) + if (fi.suffix().toLower().compare("poly") == 0 || + fi.suffix().toLower().compare("smesh") == 0) { FileIO::TetGenInterface tetgen; - tetgen.readTetGenGeometry(fileName.toStdString(), _project.getGEOObjects()); + tetgen.readTetGenGeometry(fileName.toStdString(), + _project.getGEOObjects()); } - else { - settings.setValue("lastOpenedTetgenFileDirectory", QFileInfo(fileName).absolutePath()); - QString element_fname(fi.path() + "/" + fi.completeBaseName() + ".ele"); + else + { + settings.setValue("lastOpenedTetgenFileDirectory", + QFileInfo(fileName).absolutePath()); + QString element_fname(fi.path() + "/" + fi.completeBaseName() + + ".ele"); if (!fileName.isEmpty()) { @@ -826,13 +897,20 @@ void MainWindow::showLicense() void MainWindow::about() { - QString about("<a href='https://www.opengeosys.org'>www.opengeosys.org</a><br /><br />"); - about.append(QString("Version: %1<br />") - .arg(QString::fromStdString(GitInfoLib::GitInfo::ogs_version))); - - about.append(QString("Git commit: <a href='https://github.com/ufz/ogs/commit/%1'>%1</a><br />") - .arg(QString::fromStdString(GitInfoLib::GitInfo::git_version_sha1_short))); - about.append(QString("Built date: %1<br />").arg(QDate::currentDate().toString(Qt::ISODate))); + QString about( + "<a href='https://www.opengeosys.org'>www.opengeosys.org</a><br /><br " + "/>"); + about.append( + QString("Version: %1<br />") + .arg(QString::fromStdString(GitInfoLib::GitInfo::ogs_version))); + + about.append( + QString("Git commit: <a " + "href='https://github.com/ufz/ogs/commit/%1'>%1</a><br />") + .arg(QString::fromStdString( + GitInfoLib::GitInfo::git_version_sha1_short))); + about.append(QString("Built date: %1<br />") + .arg(QDate::currentDate().toString(Qt::ISODate))); QMessageBox::about(this, "About OpenGeoSys 6", about); } @@ -852,8 +930,7 @@ QMenu* MainWindow::createImportFilesMenu() importFiles->addAction("&NetCDF Files...", [this] { open(ImportFileType::NETCDF); }); #endif // OGS_USE_NETCDF - importFiles->addAction("&Petrel Files...", - [this] { loadPetrelFiles(); }); + importFiles->addAction("&Petrel Files...", [this] { loadPetrelFiles(); }); importFiles->addAction("&Raster Files...", [this] { open(ImportFileType::RASTER); }); importFiles->addAction("&Shape Files...", @@ -869,9 +946,10 @@ void MainWindow::loadPetrelFiles() { QSettings settings; QStringList sfc_file_names = QFileDialog::getOpenFileNames( - this, "Select surface data file(s) to import", "", "Petrel files (*)"); + this, "Select surface data file(s) to import", "", "Petrel files (*)"); QStringList well_path_file_names = QFileDialog::getOpenFileNames( - this, "Select well path data file(s) to import", "", "Petrel files (*)"); + this, "Select well path data file(s) to import", "", + "Petrel files (*)"); if (!sfc_file_names.empty() || !well_path_file_names.empty()) { QStringList::const_iterator it = sfc_file_names.begin(); @@ -892,8 +970,8 @@ void MainWindow::loadPetrelFiles() std::string unique_str(*(sfc_files.begin())); - PetrelInterface(sfc_files, well_path_files, unique_str, &_project.getGEOObjects()); - + PetrelInterface(sfc_files, well_path_files, unique_str, + &_project.getGEOObjects()); QDir dir = QDir(sfc_file_names.at(0)); settings.setValue("lastOpenedFileDirectory", dir.absolutePath()); @@ -929,7 +1007,7 @@ void MainWindow::writeStationListToFile(QString listName, QString fileName) BaseLib::IO::writeStringToFile(xml.writeToString(), fileName.toStdString()); } -void MainWindow::mapGeometry(const std::string &geo_name) +void MainWindow::mapGeometry(const std::string& geo_name) { GeoOnMeshMappingDialog dlg(this->_project.getMeshObjects()); if (dlg.exec() != QDialog::Accepted) @@ -937,17 +1015,19 @@ void MainWindow::mapGeometry(const std::string &geo_name) return; } - int choice (dlg.getDataSetChoice()); + int choice(dlg.getDataSetChoice()); QString file_name(""); - if (choice<2) // load something from a file + if (choice < 2) // load something from a file { - QString file_type[2] = {"OpenGeoSys mesh files (*.vtu *.msh)", "Raster files(*.asc *.grd)" }; + QString file_type[2] = {"OpenGeoSys mesh files (*.vtu *.msh)", + "Raster files(*.asc *.grd)"}; QSettings settings; - file_name = QFileDialog::getOpenFileName( this, - "Select file for mapping", - settings.value("lastOpenedFileDirectory").toString(), - file_type[choice]); + file_name = QFileDialog::getOpenFileName( + this, + "Select file for mapping", + settings.value("lastOpenedFileDirectory").toString(), + file_type[choice]); if (file_name.isEmpty()) { return; @@ -958,12 +1038,13 @@ void MainWindow::mapGeometry(const std::string &geo_name) MeshGeoToolsLib::GeoMapper geo_mapper(_project.getGEOObjects(), geo_name); QFileInfo fi(file_name); - if (choice == 1) // load raster from file + if (choice == 1) // load raster from file { if (fi.suffix().toLower() == "asc" || fi.suffix().toLower() == "grd") { - std::unique_ptr<GeoLib::Raster> raster ( - FileIO::AsciiRasterInterface::getRasterFromASCFile(file_name.toStdString())); + std::unique_ptr<GeoLib::Raster> raster( + FileIO::AsciiRasterInterface::getRasterFromASCFile( + file_name.toStdString())); if (raster) { geo_mapper.mapOnDEM(std::move(raster)); @@ -981,11 +1062,10 @@ void MainWindow::mapGeometry(const std::string &geo_name) return; } - MeshLib::Mesh* mesh (nullptr); - if (choice == 0) // load mesh from file + MeshLib::Mesh* mesh(nullptr); + if (choice == 0) // load mesh from file { - if (fi.suffix().toLower() == "vtu" || - fi.suffix().toLower() == "vtk" || + if (fi.suffix().toLower() == "vtu" || fi.suffix().toLower() == "vtk" || fi.suffix().toLower() == "msh") { mesh = MeshLib::IO::readMeshFromFile(file_name.toStdString()); @@ -1013,7 +1093,8 @@ void MainWindow::mapGeometry(const std::string &geo_name) GeoLib::DuplicateGeometry dup(_project.getGEOObjects(), geo_name, new_geo_name); new_geo_name = dup.getFinalizedOutputName(); - MeshGeoToolsLib::GeoMapper mapper(_project.getGEOObjects(), new_geo_name); + MeshGeoToolsLib::GeoMapper mapper(_project.getGEOObjects(), + new_geo_name); mapper.advancedMapOnMesh(*mesh); _geo_model->updateGeometry(new_geo_name); } @@ -1028,15 +1109,17 @@ void MainWindow::convertMeshToGeometry(const MeshLib::Mesh* mesh) MeshLib::convertMeshToGeo(*mesh, _project.getGEOObjects()); } -void MainWindow::exportBoreholesToGMS(std::string listName, std::string fileName) +void MainWindow::exportBoreholesToGMS(std::string listName, + std::string fileName) { - const std::vector<GeoLib::Point*>* stations(_project.getGEOObjects().getStationVec(listName)); + const std::vector<GeoLib::Point*>* stations( + _project.getGEOObjects().getStationVec(listName)); GMSInterface::writeBoreholesToGMS(stations, fileName); } -void MainWindow::callGMSH(std::vector<std::string> & selectedGeometries, - unsigned param1, double param2, double param3, double param4, - bool delete_geo_file) +void MainWindow::callGMSH(std::vector<std::string>& selectedGeometries, + unsigned param1, double param2, double param3, + double param4, bool delete_geo_file) { if (!selectedGeometries.empty()) { @@ -1047,9 +1130,10 @@ void MainWindow::callGMSH(std::vector<std::string> & selectedGeometries, if (!delete_geo_file) { - fileName = QFileDialog::getSaveFileName(this, "Save GMSH-file as", - LastSavedFileDirectory::getDir() + "tmp_gmsh.geo", - "GMSH geometry files (*.geo)"); + fileName = QFileDialog::getSaveFileName( + this, "Save GMSH-file as", + LastSavedFileDirectory::getDir() + "tmp_gmsh.geo", + "GMSH geometry files (*.geo)"); } else { @@ -1058,14 +1142,17 @@ void MainWindow::callGMSH(std::vector<std::string> & selectedGeometries, if (!fileName.isEmpty()) { - if (param4 == -1) { // adaptive meshing selected + if (param4 == -1) + { // adaptive meshing selected FileIO::GMSH::GMSHInterface gmsh_io( _project.getGEOObjects(), true, FileIO::GMSH::MeshDensityAlgorithm::AdaptiveMeshDensity, param2, param3, param1, selectedGeometries, false, false); BaseLib::IO::writeStringToFile(gmsh_io.writeToString(), fileName.toStdString()); - } else { // homogeneous meshing selected + } + else + { // homogeneous meshing selected FileIO::GMSH::GMSHInterface gmsh_io( _project.getGEOObjects(), true, FileIO::GMSH::MeshDensityAlgorithm::FixedMeshDensity, @@ -1077,7 +1164,9 @@ void MainWindow::callGMSH(std::vector<std::string> & selectedGeometries, if (system(nullptr) != 0) // command processor available { QSettings settings; - std::string gmsh_path = settings.value("DataExplorerGmshPath").toString().toStdString(); + std::string gmsh_path = settings.value("DataExplorerGmshPath") + .toString() + .toStdString(); if (!gmsh_path.empty()) { @@ -1144,13 +1233,14 @@ void MainWindow::showFileConverter() dlg->raise(); } -void MainWindow::showDiagramPrefsDialog(QModelIndex &index) +void MainWindow::showDiagramPrefsDialog(QModelIndex& index) { QString listName; GeoLib::Station* stn = _geo_model->getStationModel()->stationFromIndex(index, listName); - if ((stn->type() == GeoLib::Station::StationType::STATION) && stn->getSensorData()) + if ((stn->type() == GeoLib::Station::StationType::STATION) && + stn->getSensorData()) { auto* prefs(new DiagramPrefsDialog(stn)); prefs->setAttribute(Qt::WA_DeleteOnClose); @@ -1165,9 +1255,10 @@ void MainWindow::showDiagramPrefsDialog(QModelIndex &index) void MainWindow::showDiagramPrefsDialog() { QSettings settings; - QString fileName = QFileDialog::getOpenFileName( this, "Select data file to open", - settings.value("lastOpenedFileDirectory").toString(), - "Text files (*.txt);;All files (* *.*)"); + QString fileName = QFileDialog::getOpenFileName( + this, "Select data file to open", + settings.value("lastOpenedFileDirectory").toString(), + "Text files (*.txt);;All files (* *.*)"); if (!fileName.isEmpty()) { QDir dir = QDir(fileName); @@ -1178,23 +1269,32 @@ void MainWindow::showDiagramPrefsDialog() } } -void MainWindow::showGeoNameDialog(const std::string &geometry_name, const GeoLib::GEOTYPE object_type, std::size_t id) +void MainWindow::showGeoNameDialog(const std::string& geometry_name, + const GeoLib::GEOTYPE object_type, + std::size_t id) { - std::string old_name = _project.getGEOObjects().getElementNameByID(geometry_name, object_type, id); - SetNameDialog dlg(GeoLib::convertGeoTypeToString(object_type), id, old_name); + std::string old_name = _project.getGEOObjects().getElementNameByID( + geometry_name, object_type, id); + SetNameDialog dlg(GeoLib::convertGeoTypeToString(object_type), id, + old_name); if (dlg.exec() != QDialog::Accepted) { return; } - _geo_model->addNameForElement(geometry_name, object_type, id, dlg.getNewName()); - static_cast<GeoTreeModel*>(this->geoTabWidget->treeView->model())->setNameForItem(geometry_name, object_type, - id, _project.getGEOObjects().getElementNameByID(geometry_name, object_type, id)); + _geo_model->addNameForElement(geometry_name, object_type, id, + dlg.getNewName()); + static_cast<GeoTreeModel*>(this->geoTabWidget->treeView->model()) + ->setNameForItem(geometry_name, object_type, id, + _project.getGEOObjects().getElementNameByID( + geometry_name, object_type, id)); } -void MainWindow::showStationNameDialog(const std::string& stn_vec_name, std::size_t id) +void MainWindow::showStationNameDialog(const std::string& stn_vec_name, + std::size_t id) { - std::vector<GeoLib::Point*> const* stations = _project.getGEOObjects().getStationVec(stn_vec_name); + std::vector<GeoLib::Point*> const* stations = + _project.getGEOObjects().getStationVec(stn_vec_name); auto* const stn = static_cast<GeoLib::Station*>((*stations)[id]); SetNameDialog dlg("Station", id, stn->getName()); if (dlg.exec() != QDialog::Accepted) @@ -1203,22 +1303,23 @@ void MainWindow::showStationNameDialog(const std::string& stn_vec_name, std::siz } stn->setName(dlg.getNewName()); - static_cast<StationTreeModel*>(this->stationTabWidget->treeView->model())->setNameForItem(stn_vec_name, id, stn->getName()); + static_cast<StationTreeModel*>(this->stationTabWidget->treeView->model()) + ->setNameForItem(stn_vec_name, id, stn->getName()); } void MainWindow::showCreateStructuredGridDialog() { CreateStructuredGridDialog dlg; - connect(&dlg, SIGNAL(meshAdded(MeshLib::Mesh*)), - _meshModel.get(), SLOT(addMesh(MeshLib::Mesh*))); + connect(&dlg, SIGNAL(meshAdded(MeshLib::Mesh*)), _meshModel.get(), + SLOT(addMesh(MeshLib::Mesh*))); dlg.exec(); } void MainWindow::showMeshElementRemovalDialog() { MeshElementRemovalDialog dlg(this->_project); - connect(&dlg, SIGNAL(meshAdded(MeshLib::Mesh*)), - _meshModel.get(), SLOT(addMesh(MeshLib::Mesh*))); + connect(&dlg, SIGNAL(meshAdded(MeshLib::Mesh*)), _meshModel.get(), + SLOT(addMesh(MeshLib::Mesh*))); dlg.exec(); } @@ -1238,24 +1339,30 @@ void MainWindow::convertPointsToStations(std::string const& geo_name) } } -void MainWindow::showLineEditDialog(const std::string &geoName) +void MainWindow::showLineEditDialog(const std::string& geoName) { LineEditDialog lineEdit( *(_project.getGEOObjects().getPolylineVecObj(geoName))); - connect(&lineEdit, SIGNAL(connectPolylines(const std::string&, - std::vector<std::size_t>, double, - std::string, bool, bool)), - _geo_model.get(), SLOT(connectPolylineSegments( - const std::string&, std::vector<std::size_t>, - double, std::string, bool, bool))); + connect( + &lineEdit, + SIGNAL(connectPolylines(const std::string&, std::vector<std::size_t>, + double, std::string, bool, bool)), + _geo_model.get(), + SLOT(connectPolylineSegments(const std::string&, + std::vector<std::size_t>, double, + std::string, bool, bool))); lineEdit.exec(); } void MainWindow::showGMSHPrefsDialog() { GMSHPrefsDialog dlg(_project.getGEOObjects()); - connect(&dlg, SIGNAL(requestMeshing(std::vector<std::string> &, unsigned, double, double, double, bool)), - this, SLOT(callGMSH(std::vector<std::string> &, unsigned, double, double, double, bool))); + connect(&dlg, + SIGNAL(requestMeshing(std::vector<std::string>&, unsigned, double, + double, double, bool)), + this, + SLOT(callGMSH(std::vector<std::string>&, unsigned, double, double, + double, bool))); dlg.exec(); } @@ -1266,7 +1373,7 @@ void MainWindow::showMergeGeometriesDialog() { return; } - std::string name (dlg.getGeometryName()); + std::string name(dlg.getGeometryName()); if (_project.getGEOObjects().mergeGeometries(dlg.getSelectedGeometries(), name) < 0) { @@ -1274,7 +1381,8 @@ void MainWindow::showMergeGeometriesDialog() } } -void MainWindow::showMeshQualitySelectionDialog(MeshLib::VtkMappedMeshSource* mshSource) +void MainWindow::showMeshQualitySelectionDialog( + MeshLib::VtkMappedMeshSource* mshSource) { if (mshSource == nullptr) { @@ -1286,9 +1394,11 @@ void MainWindow::showMeshQualitySelectionDialog(MeshLib::VtkMappedMeshSource* ms { return; } - MeshLib::MeshQualityType const type (dlg.getSelectedMetric()); - MeshLib::ElementQualityInterface quality_interface(*mshSource->GetMesh(), type); - _vtkVisPipeline->showMeshElementQuality(mshSource, type, quality_interface.getQualityVector()); + MeshLib::MeshQualityType const type(dlg.getSelectedMetric()); + MeshLib::ElementQualityInterface quality_interface(*mshSource->GetMesh(), + type); + _vtkVisPipeline->showMeshElementQuality( + mshSource, type, quality_interface.getQualityVector()); if (dlg.getHistogram()) { @@ -1307,9 +1417,7 @@ void MainWindow::showDataExplorerSettingsDialog() dlg.exec(); } -void MainWindow::FEMTestStart() -{ -} +void MainWindow::FEMTestStart() {} void MainWindow::ShowWindow() { @@ -1321,11 +1429,12 @@ void MainWindow::HideWindow() this->hide(); } -void MainWindow::loadFileOnStartUp(const QString &fileName) +void MainWindow::loadFileOnStartUp(const QString& fileName) { QString ext = QFileInfo(fileName).suffix(); - if (ext=="msh" || ext=="vtu" || ext=="gli" || ext=="gml") { - this->loadFile(ImportFileType::OGS,fileName); + if (ext == "msh" || ext == "vtu" || ext == "gli" || ext == "gml") + { + this->loadFile(ImportFileType::OGS, fileName); } } @@ -1344,14 +1453,15 @@ void MainWindow::on_actionExportVTK_triggered(bool checked /*= false*/) QDir const dir = QDir(filename); settings.setValue("lastExportedFileDirectory", dir.absolutePath()); - std::string const basename = QFileInfo(filename).path().toStdString() + "/" + - QFileInfo(filename).baseName().toStdString(); + std::string const basename = + QFileInfo(filename).path().toStdString() + "/" + + QFileInfo(filename).baseName().toStdString(); TreeModelIterator it(_vtkVisPipeline.get()); ++it; while (*it) { std::string const name = basename + std::to_string(++count) + "-" + - (*it)->data(0).toString().toStdString(); + (*it)->data(0).toString().toStdString(); static_cast<VtkVisPipelineItem*>(*it)->writeToFile(name); ++it; } @@ -1362,9 +1472,10 @@ void MainWindow::on_actionExportVRML2_triggered(bool checked /*= false*/) { Q_UNUSED(checked) QSettings settings; - QString fileName = QFileDialog::getSaveFileName(this, "Save scene to VRML file", - settings.value("lastExportedFileDirectory").toString(), - "VRML files (*.wrl);;"); + QString fileName = QFileDialog::getSaveFileName( + this, "Save scene to VRML file", + settings.value("lastExportedFileDirectory").toString(), + "VRML files (*.wrl);;"); if (!fileName.isEmpty()) { QDir dir = QDir(fileName); @@ -1373,7 +1484,7 @@ void MainWindow::on_actionExportVRML2_triggered(bool checked /*= false*/) vtkVRMLExporter* exporter = vtkVRMLExporter::New(); exporter->SetFileName(fileName.toStdString().c_str()); exporter->SetRenderWindow( - visualizationWidget->vtkWidget->GetRenderWindow()); + visualizationWidget->vtkWidget->GetRenderWindow()); exporter->Write(); exporter->Delete(); } @@ -1383,9 +1494,9 @@ void MainWindow::on_actionExportObj_triggered(bool checked /*= false*/) { Q_UNUSED(checked) QSettings settings; - QString fileName = QFileDialog::getSaveFileName(this, "Save scene to Wavefront OBJ files", - settings.value("lastExportedFileDirectory").toString(), - ";;"); + QString fileName = QFileDialog::getSaveFileName( + this, "Save scene to Wavefront OBJ files", + settings.value("lastExportedFileDirectory").toString(), ";;"); if (!fileName.isEmpty()) { QDir dir = QDir(fileName); @@ -1394,7 +1505,7 @@ void MainWindow::on_actionExportObj_triggered(bool checked /*= false*/) vtkOBJExporter* exporter = vtkOBJExporter::New(); exporter->SetFilePrefix(fileName.toStdString().c_str()); exporter->SetRenderWindow( - visualizationWidget->vtkWidget->GetRenderWindow()); + visualizationWidget->vtkWidget->GetRenderWindow()); exporter->Write(); exporter->Delete(); } @@ -1416,13 +1527,13 @@ void MainWindow::createPresentationMenu() else { int count = 0; - const int currentScreen = QApplication::desktop()->screenNumber( - visualizationWidget); + const int currentScreen = + QApplication::desktop()->screenNumber(visualizationWidget); foreach (QRect screenGeo, _screenGeometries) { Q_UNUSED(screenGeo); - QAction* action = new QAction( - QString("On screen %1").arg(count), menu); + QAction* action = + new QAction(QString("On screen %1").arg(count), menu); connect(action, SIGNAL(triggered()), this, SLOT(startPresentationMode())); if (count == currentScreen) @@ -1441,14 +1552,14 @@ void MainWindow::startPresentationMode() _windowState = this->saveState(); // Get the screen number from the QAction which sent the signal - QString actionText = static_cast<QAction*> (QObject::sender())->text(); + QString actionText = static_cast<QAction*>(QObject::sender())->text(); int screen = actionText.split(" ").back().toInt(); // Move the widget to the screen and maximize it // Real fullscreen hides the menu _vtkWidget->setParent(nullptr, Qt::Window); - _vtkWidget->move(QPoint(_screenGeometries[screen].x(), - _screenGeometries[screen].y())); + _vtkWidget->move( + QPoint(_screenGeometries[screen].x(), _screenGeometries[screen].y())); //_vtkWidget->showFullScreen(); _vtkWidget->showMaximized(); diff --git a/Applications/DataHolderLib/Color.cpp b/Applications/DataHolderLib/Color.cpp index 7b57ded696021d58fff54a842518aa4b9873be84..fe1e1ae5fb7c9937f71e26a22fd8c6df458003f1 100644 --- a/Applications/DataHolderLib/Color.cpp +++ b/Applications/DataHolderLib/Color.cpp @@ -16,11 +16,14 @@ #include "BaseLib/Logging.h" -namespace DataHolderLib { - -Color createColor(unsigned char r, unsigned char g, unsigned char b, unsigned char a) +namespace DataHolderLib +{ +Color createColor(unsigned char r, + unsigned char g, + unsigned char b, + unsigned char a) { - return Color{{r,g,b,a}}; + return Color{{r, g, b, a}}; } Color getRandomColor() diff --git a/Applications/DataHolderLib/ColorLookupTable.cpp b/Applications/DataHolderLib/ColorLookupTable.cpp index 418d4cf269a3d38915f91bf4d4a2dbaa211c9d86..4af25187674c1959f3d10ef31918d9f320bf634d 100644 --- a/Applications/DataHolderLib/ColorLookupTable.cpp +++ b/Applications/DataHolderLib/ColorLookupTable.cpp @@ -18,7 +18,8 @@ ColorLookupTable::ColorLookupTable() std::make_pair<double, double>(std::numeric_limits<double>::lowest(), std::numeric_limits<double>::max())) -{} +{ +} void ColorLookupTable::setTableRange(double min, double max) { @@ -36,7 +37,8 @@ void ColorLookupTable::setColor(double id, DataHolderLib::Color const& color) } } -void ColorLookupTable::setColor(std::string const& name, DataHolderLib::Color const& color) +void ColorLookupTable::setColor(std::string const& name, + DataHolderLib::Color const& color) { _lut.emplace_back(0, color, name); } diff --git a/Applications/DataHolderLib/Project.cpp b/Applications/DataHolderLib/Project.cpp index e4b8b2580917a01a2ae9265b0397159eced3e53b..8a365abf1a14b9d451d7952da5c05a44209c57d6 100644 --- a/Applications/DataHolderLib/Project.cpp +++ b/Applications/DataHolderLib/Project.cpp @@ -18,7 +18,6 @@ namespace DataHolderLib { - void Project::addMesh(std::unique_ptr<MeshLib::Mesh> mesh) { std::string name = mesh->getName(); @@ -33,21 +32,22 @@ Project::findMeshByName(std::string const& name) const return const_cast<Project&>(*this).findMeshByName(name); } -std::vector<std::unique_ptr<MeshLib::Mesh>>::iterator -Project::findMeshByName(std::string const& name) +std::vector<std::unique_ptr<MeshLib::Mesh>>::iterator Project::findMeshByName( + std::string const& name) { return std::find_if(_mesh_vec.begin(), _mesh_vec.end(), - [&name](std::unique_ptr<MeshLib::Mesh> & mesh) - { return mesh && (name == mesh->getName()); }); + [&name](std::unique_ptr<MeshLib::Mesh>& mesh) { + return mesh && (name == mesh->getName()); + }); } -const MeshLib::Mesh* Project::getMesh(const std::string &name) const +const MeshLib::Mesh* Project::getMesh(const std::string& name) const { auto it = findMeshByName(name); return (it == _mesh_vec.end() ? nullptr : it->get()); } -bool Project::removeMesh(const std::string &name) +bool Project::removeMesh(const std::string& name) { auto it = findMeshByName(name); if (it != _mesh_vec.end()) @@ -59,7 +59,7 @@ bool Project::removeMesh(const std::string &name) return false; } -bool Project::getUniqueName(std::string &name) const +bool Project::getUniqueName(std::string& name) const { int count(0); bool isUnique(false); @@ -71,8 +71,8 @@ bool Project::getUniqueName(std::string &name) const cpName = name; count++; - // If the original name already exists we start to add numbers to name for - // as long as it takes to make the name unique. + // If the original name already exists we start to add numbers to name + // for as long as it takes to make the name unique. if (count > 1) { cpName = cpName + "-" + std::to_string(count); @@ -88,8 +88,8 @@ bool Project::getUniqueName(std::string &name) const } // At this point cpName is a unique name and isUnique is true. - // If cpName is not the original name, "name" is changed and isUnique is set to false, - // indicating that a vector with the original name already exists. + // If cpName is not the original name, "name" is changed and isUnique is set + // to false, indicating that a vector with the original name already exists. if (count > 1) { isUnique = false; diff --git a/Applications/FileIO/AsciiRasterInterface.cpp b/Applications/FileIO/AsciiRasterInterface.cpp index 0ccbff1fbdddffa3772dee0b5160fe7cd21f8742..feb49a25d1e4deeeb3dc25cb28d514b5fa7247a2 100644 --- a/Applications/FileIO/AsciiRasterInterface.cpp +++ b/Applications/FileIO/AsciiRasterInterface.cpp @@ -22,10 +22,9 @@ namespace FileIO { - GeoLib::Raster* AsciiRasterInterface::readRaster(std::string const& fname) { - std::string ext (BaseLib::getFileExtension(fname)); + std::string ext(BaseLib::getFileExtension(fname)); std::transform(ext.begin(), ext.end(), ext.begin(), tolower); if (ext == ".asc") { @@ -38,11 +37,13 @@ GeoLib::Raster* AsciiRasterInterface::readRaster(std::string const& fname) return nullptr; } -GeoLib::Raster* AsciiRasterInterface::getRasterFromASCFile(std::string const& fname) +GeoLib::Raster* AsciiRasterInterface::getRasterFromASCFile( + std::string const& fname) { std::ifstream in(fname.c_str()); - if (!in.is_open()) { + if (!in.is_open()) + { WARN("Raster::getRasterFromASCFile(): Could not open file {:s}.", fname); return nullptr; @@ -50,13 +51,16 @@ GeoLib::Raster* AsciiRasterInterface::getRasterFromASCFile(std::string const& fn // header information GeoLib::RasterHeader header; - if (readASCHeader(in, header)) { + if (readASCHeader(in, header)) + { std::vector<double> values(header.n_cols * header.n_rows); std::string s; // read the data into the double-array - for (std::size_t j(0); j < header.n_rows; ++j) { - const std::size_t idx ((header.n_rows - j - 1) * header.n_cols); - for (std::size_t i(0); i < header.n_cols; ++i) { + for (std::size_t j(0); j < header.n_rows; ++j) + { + const std::size_t idx((header.n_rows - j - 1) * header.n_cols); + for (std::size_t i(0); i < header.n_cols; ++i) + { in >> s; values[idx + i] = strtod( BaseLib::replaceString(",", ".", s).c_str(), nullptr); @@ -73,7 +77,8 @@ GeoLib::Raster* AsciiRasterInterface::getRasterFromASCFile(std::string const& fn return nullptr; } -bool AsciiRasterInterface::readASCHeader(std::ifstream &in, GeoLib::RasterHeader &header) +bool AsciiRasterInterface::readASCHeader(std::ifstream& in, + GeoLib::RasterHeader& header) { std::string tag; std::string value; @@ -154,11 +159,13 @@ bool AsciiRasterInterface::readASCHeader(std::ifstream &in, GeoLib::RasterHeader return true; } -GeoLib::Raster* AsciiRasterInterface::getRasterFromSurferFile(std::string const& fname) +GeoLib::Raster* AsciiRasterInterface::getRasterFromSurferFile( + std::string const& fname) { std::ifstream in(fname.c_str()); - if (!in.is_open()) { + if (!in.is_open()) + { ERR("Raster::getRasterFromSurferFile() - Could not open file {:s}", fname); return nullptr; @@ -171,19 +178,19 @@ GeoLib::Raster* AsciiRasterInterface::getRasterFromSurferFile(std::string const& if (readSurferHeader(in, header, min, max)) { - const double no_data_val (min-1); + const double no_data_val(min - 1); std::vector<double> values(header.n_cols * header.n_rows); std::string s; // read the data into the double-array for (std::size_t j(0); j < header.n_rows; ++j) { - const std::size_t idx (j * header.n_cols); + const std::size_t idx(j * header.n_cols); for (std::size_t i(0); i < header.n_cols; ++i) { in >> s; const double val(strtod( BaseLib::replaceString(",", ".", s).c_str(), nullptr)); - values[idx+i] = (val > max || val < min) ? no_data_val : val; + values[idx + i] = (val > max || val < min) ? no_data_val : val; } } in.close(); @@ -197,8 +204,9 @@ GeoLib::Raster* AsciiRasterInterface::getRasterFromSurferFile(std::string const& return nullptr; } -bool AsciiRasterInterface::readSurferHeader( - std::ifstream &in, GeoLib::RasterHeader &header, double &min, double &max) +bool AsciiRasterInterface::readSurferHeader(std::ifstream& in, + GeoLib::RasterHeader& header, + double& min, double& max) { std::string tag; @@ -236,12 +244,13 @@ bool AsciiRasterInterface::readSurferHeader( return true; } -void AsciiRasterInterface::writeRasterAsASC(GeoLib::Raster const& raster, std::string const& file_name) +void AsciiRasterInterface::writeRasterAsASC(GeoLib::Raster const& raster, + std::string const& file_name) { - GeoLib::RasterHeader header (raster.getHeader()); - MathLib::Point3d const& origin (header.origin); - unsigned const nCols (header.n_cols); - unsigned const nRows (header.n_rows); + GeoLib::RasterHeader header(raster.getHeader()); + MathLib::Point3d const& origin(header.origin); + unsigned const nCols(header.n_cols); + unsigned const nRows(header.n_rows); // write header std::ofstream out(file_name); @@ -251,15 +260,15 @@ void AsciiRasterInterface::writeRasterAsASC(GeoLib::Raster const& raster, std::s out.precision(std::numeric_limits<double>::digits10); out << "xllcorner " << origin[0] << "\n"; out << "yllcorner " << origin[1] << "\n"; - out << "cellsize " << header.cell_size << "\n"; + out << "cellsize " << header.cell_size << "\n"; out.precision(default_precision); out << "NODATA_value " << header.no_data << "\n"; // write data - double const*const elevation(raster.begin()); + double const* const elevation(raster.begin()); for (unsigned row(0); row < nRows; ++row) { - for (unsigned col(0); col < nCols-1; ++col) + for (unsigned col(0); col < nCols - 1; ++col) { out << elevation[(nRows - row - 1) * nCols + col] << " "; } @@ -268,7 +277,6 @@ void AsciiRasterInterface::writeRasterAsASC(GeoLib::Raster const& raster, std::s out.close(); } - /// Checks if all raster files actually exist static bool allRastersExist(std::vector<std::string> const& raster_paths) { @@ -300,4 +308,4 @@ std::optional<std::vector<GeoLib::Raster const*>> readRasters( }); return std::make_optional(rasters); } -} // end namespace FileIO +} // end namespace FileIO diff --git a/Applications/FileIO/FEFLOW/FEFLOWGeoInterface.cpp b/Applications/FileIO/FEFLOW/FEFLOWGeoInterface.cpp index 3bc29ae86d17a08cfcd3d6716f05699bf616ac9b..0e2ab79a91390535f03df0226316f580b4d30736 100644 --- a/Applications/FileIO/FEFLOW/FEFLOWGeoInterface.cpp +++ b/Applications/FileIO/FEFLOW/FEFLOWGeoInterface.cpp @@ -8,20 +8,16 @@ #include "FEFLOWGeoInterface.h" -#include <cctype> -#include <memory> - -#include <boost/algorithm/string/trim.hpp> - #include <QDomElement> #include <QString> #include <QtXml/QDomDocument> - -#include "BaseLib/Logging.h" +#include <boost/algorithm/string/trim.hpp> +#include <cctype> +#include <memory> #include "BaseLib/FileTools.h" +#include "BaseLib/Logging.h" #include "BaseLib/StringTools.h" - #include "GeoLib/GEOObjects.h" #include "GeoLib/Point.h" #include "GeoLib/Polygon.h" diff --git a/Applications/FileIO/FEFLOW/FEFLOWMeshInterface.cpp b/Applications/FileIO/FEFLOW/FEFLOWMeshInterface.cpp index 4d5f32195810263e2dd055e7f01e2539963db8c8..fcbbd9f1d1cbe62029c29c064c596c09a6b36d41 100644 --- a/Applications/FileIO/FEFLOW/FEFLOWMeshInterface.cpp +++ b/Applications/FileIO/FEFLOW/FEFLOWMeshInterface.cpp @@ -8,20 +8,16 @@ #include "FEFLOWMeshInterface.h" +#include <boost/algorithm/string/trim.hpp> #include <cctype> #include <memory> -#include <boost/algorithm/string/trim.hpp> - -#include "BaseLib/Logging.h" - +#include "Applications/FileIO/FEFLOW/FEFLOWGeoInterface.h" #include "BaseLib/FileTools.h" +#include "BaseLib/Logging.h" #include "BaseLib/StringTools.h" - -#include "Applications/FileIO/FEFLOW/FEFLOWGeoInterface.h" #include "GeoLib/Point.h" #include "GeoLib/Polygon.h" - #include "MeshLib/Elements/Elements.h" #include "MeshLib/Mesh.h" #include "MeshLib/Node.h" @@ -86,10 +82,9 @@ MeshLib::Mesh* FEFLOWMeshInterface::readFEFLOWFile(const std::string& filename) vec_nodes.resize(fem_dim.n_nodes); std::size_t count = 0; double dummy_coords[3] = {}; - std::generate(vec_nodes.begin(), vec_nodes.end(), [&]() - { - return new MeshLib::Node(dummy_coords, count++); - }); + std::generate(vec_nodes.begin(), vec_nodes.end(), [&]() { + return new MeshLib::Node(dummy_coords, count++); + }); line_stream.clear(); } //.................................................................... @@ -134,10 +129,7 @@ MeshLib::Mesh* FEFLOWMeshInterface::readFEFLOWFile(const std::string& filename) "type with the number of node = {:d} and dim = {:d}", fem_dim.n_nodes_of_element, fem_class.dimension); std::for_each(vec_nodes.begin(), vec_nodes.end(), - [](MeshLib::Node* nod) - { - delete nod; - }); + [](MeshLib::Node* nod) { delete nod; }); vec_nodes.clear(); return nullptr; } @@ -171,8 +163,7 @@ MeshLib::Mesh* FEFLOWMeshInterface::readFEFLOWFile(const std::string& filename) for (std::size_t i = 0; i < fem_dim.n_elements; i++) { std::getline(in, line_string); - vec_elements.push_back( - readElement(line_string, vec_nodes)); + vec_elements.push_back(readElement(line_string, vec_nodes)); } } //.................................................................... @@ -219,8 +210,8 @@ MeshLib::Mesh* FEFLOWMeshInterface::readFEFLOWFile(const std::string& filename) // SUPERMESH else if (line_string == "SUPERMESH") { - FileIO::FEFLOWGeoInterface::readSuperMesh( - in, fem_class.dimension, points, lines); + FileIO::FEFLOWGeoInterface::readSuperMesh(in, fem_class.dimension, + points, lines); } //.................................................................... } @@ -614,8 +605,7 @@ MeshLib::Element* FEFLOWMeshInterface::readElement( void FEFLOWMeshInterface::readELEMENTALSETS( std::ifstream& in, std::vector<std::vector<std::size_t>>& vec_elementsets) { - auto compressSpaces = [](std::string const& str) - { + auto compressSpaces = [](std::string const& str) { std::stringstream ss(str); std::string new_str; std::string word; @@ -716,7 +706,7 @@ void FEFLOWMeshInterface::setMaterialIDs( std::vector<MeshLib::Element*> const& vec_elements, std::vector<int>& material_ids) { - assert(material_ids.size()==vec_elements.size()); + assert(material_ids.size() == vec_elements.size()); if (!vec_elementsets.empty()) { for (std::size_t matid = 0; matid < vec_elementsets.size(); ++matid) diff --git a/Applications/FileIO/GMSInterface.cpp b/Applications/FileIO/GMSInterface.cpp index ee76ecb75bf758cf90655d88d506fefee51ba518..3bf83e2f2961af820b20cd9e64c84506e9a9de28 100644 --- a/Applications/FileIO/GMSInterface.cpp +++ b/Applications/FileIO/GMSInterface.cpp @@ -84,8 +84,7 @@ int GMSInterface::readBoreholesFromGMS(std::vector<GeoLib::Point*>* boreholes, { if (newBorehole == nullptr) OGS_FATAL("Trying to access a nullptr."); - newBorehole->addSoilLayer( - pnt[0], pnt[1], pnt[2], sName); + newBorehole->addSoilLayer(pnt[0], pnt[1], pnt[2], sName); sName = (*(++it)); depth = pnt[2]; } @@ -278,8 +277,8 @@ MeshLib::Mesh* GMSInterface::readGMS3DMMesh(const std::string& filename) mat_ids.push_back(mat_id); } else if (element_id == "ND ") - { // Node - continue; // skip because nodes have already been read + { // Node + continue; // skip because nodes have already been read } else // default { diff --git a/Applications/FileIO/Gmsh/GMSHAdaptiveMeshDensity.cpp b/Applications/FileIO/Gmsh/GMSHAdaptiveMeshDensity.cpp index 67f6072ed11100249dc8afa84e5f8cd408087c27..0c8e72e2ed2e5e4f78b103e782fee813030946f3 100644 --- a/Applications/FileIO/Gmsh/GMSHAdaptiveMeshDensity.cpp +++ b/Applications/FileIO/Gmsh/GMSHAdaptiveMeshDensity.cpp @@ -16,14 +16,12 @@ #include <list> #include "BaseLib/Logging.h" - #include "GeoLib/Point.h" #include "GeoLib/Polygon.h" #ifndef NDEBUG #include "GeoLib/Polyline.h" #endif #include "GeoLib/QuadTree.h" - #include "MathLib/MathTools.h" namespace FileIO @@ -45,15 +43,19 @@ GMSHAdaptiveMeshDensity::~GMSHAdaptiveMeshDensity() delete _quad_tree; } -void GMSHAdaptiveMeshDensity::initialize(std::vector<GeoLib::Point const*> const& pnts) +void GMSHAdaptiveMeshDensity::initialize( + std::vector<GeoLib::Point const*> const& pnts) { // *** QuadTree - determining bounding box - DBUG("GMSHAdaptiveMeshDensity::init(): computing axis aligned bounding box (2D) for quadtree."); + DBUG( + "GMSHAdaptiveMeshDensity::init(): computing axis aligned bounding box " + "(2D) for quadtree."); GeoLib::Point min(*pnts[0]); GeoLib::Point max(*pnts[0]); std::size_t n_pnts(pnts.size()); - for (std::size_t k(1); k<n_pnts; k++) { + for (std::size_t k(1); k < n_pnts; k++) + { for (std::size_t j(0); j < 2; j++) { if ((*(pnts[k]))[j] < min[j]) @@ -75,14 +77,16 @@ void GMSHAdaptiveMeshDensity::initialize(std::vector<GeoLib::Point const*> const // *** QuadTree - create object DBUG("GMSHAdaptiveMeshDensity::init(): Creating quadtree."); - _quad_tree = new GeoLib::QuadTree<GeoLib::Point> (min, max, _max_pnts_per_leaf); + _quad_tree = + new GeoLib::QuadTree<GeoLib::Point>(min, max, _max_pnts_per_leaf); DBUG("GMSHAdaptiveMeshDensity::init(): \tok."); // *** QuadTree - insert points addPoints(pnts); } -void GMSHAdaptiveMeshDensity::addPoints(std::vector<GeoLib::Point const*> const& pnts) +void GMSHAdaptiveMeshDensity::addPoints( + std::vector<GeoLib::Point const*> const& pnts) { // *** QuadTree - insert points const std::size_t n_pnts(pnts.size()); @@ -98,7 +102,8 @@ void GMSHAdaptiveMeshDensity::addPoints(std::vector<GeoLib::Point const*> const& _quad_tree->balance(); } -double GMSHAdaptiveMeshDensity::getMeshDensityAtPoint(GeoLib::Point const* const pnt) const +double GMSHAdaptiveMeshDensity::getMeshDensityAtPoint( + GeoLib::Point const* const pnt) const { GeoLib::Point ll; GeoLib::Point ur; @@ -106,7 +111,8 @@ double GMSHAdaptiveMeshDensity::getMeshDensityAtPoint(GeoLib::Point const* const return _pnt_density * (ur[0] - ll[0]); } -double GMSHAdaptiveMeshDensity::getMeshDensityAtStation(GeoLib::Point const* const pnt) const +double GMSHAdaptiveMeshDensity::getMeshDensityAtStation( + GeoLib::Point const* const pnt) const { GeoLib::Point ll; GeoLib::Point ur; @@ -114,8 +120,8 @@ double GMSHAdaptiveMeshDensity::getMeshDensityAtStation(GeoLib::Point const* con return _station_density * (ur[0] - ll[0]); } -void GMSHAdaptiveMeshDensity::getSteinerPoints (std::vector<GeoLib::Point*> & pnts, - std::size_t additional_levels) const +void GMSHAdaptiveMeshDensity::getSteinerPoints( + std::vector<GeoLib::Point*>& pnts, std::size_t additional_levels) const { // get Steiner points std::size_t max_depth(0); @@ -124,49 +130,59 @@ void GMSHAdaptiveMeshDensity::getSteinerPoints (std::vector<GeoLib::Point*> & pn std::list<GeoLib::QuadTree<GeoLib::Point>*> leaf_list; _quad_tree->getLeafs(leaf_list); - for (std::list<GeoLib::QuadTree<GeoLib::Point>*>::const_iterator it(leaf_list.begin()); it - != leaf_list.end(); ++it) { - if ((*it)->getPoints().empty()) { + for (std::list<GeoLib::QuadTree<GeoLib::Point>*>::const_iterator it( + leaf_list.begin()); + it != leaf_list.end(); + ++it) + { + if ((*it)->getPoints().empty()) + { // compute point from square GeoLib::Point ll; GeoLib::Point ur; (*it)->getSquarePoints(ll, ur); - if ((*it)->getDepth() + additional_levels > max_depth) { + if ((*it)->getDepth() + additional_levels > max_depth) + { additional_levels = max_depth - (*it)->getDepth(); } const std::size_t n_pnts_per_quad_dim = static_cast<std::size_t>(1) << additional_levels; - const double delta ((ur[0] - ll[0]) / (2 * n_pnts_per_quad_dim)); - for (std::size_t i(0); i<n_pnts_per_quad_dim; i++) { - for (std::size_t j(0); j<n_pnts_per_quad_dim; j++) { + const double delta((ur[0] - ll[0]) / (2 * n_pnts_per_quad_dim)); + for (std::size_t i(0); i < n_pnts_per_quad_dim; i++) + { + for (std::size_t j(0); j < n_pnts_per_quad_dim; j++) + { pnts.push_back(new GeoLib::Point( ll[0] + (2 * i + 1) * delta, ll[1] + (2 * j + 1) * delta, 0.0, pnts.size())); } } - } } } #ifndef NDEBUG -void GMSHAdaptiveMeshDensity::getQuadTreeGeometry(std::vector<GeoLib::Point*> &pnts, - std::vector<GeoLib::Polyline*> &plys) const +void GMSHAdaptiveMeshDensity::getQuadTreeGeometry( + std::vector<GeoLib::Point*>& pnts, + std::vector<GeoLib::Polyline*>& plys) const { std::list<GeoLib::QuadTree<GeoLib::Point>*> leaf_list; _quad_tree->getLeafs(leaf_list); - for (std::list<GeoLib::QuadTree<GeoLib::Point>*>::const_iterator it(leaf_list.begin()); it - != leaf_list.end(); ++it) { + for (std::list<GeoLib::QuadTree<GeoLib::Point>*>::const_iterator it( + leaf_list.begin()); + it != leaf_list.end(); + ++it) + { // fetch corner points from leaf GeoLib::Point ll; GeoLib::Point ur; (*it)->getSquarePoints(ll, ur); - std::size_t const pnt_offset (pnts.size()); + std::size_t const pnt_offset(pnts.size()); pnts.push_back(new GeoLib::Point(ll, pnt_offset)); - pnts.push_back(new GeoLib::Point(ur[0], ll[1], 0.0, pnt_offset+1)); - pnts.push_back(new GeoLib::Point(ur, pnt_offset+2)); - pnts.push_back(new GeoLib::Point(ll[0], ur[1], 0.0, pnt_offset+3)); + pnts.push_back(new GeoLib::Point(ur[0], ll[1], 0.0, pnt_offset + 1)); + pnts.push_back(new GeoLib::Point(ur, pnt_offset + 2)); + pnts.push_back(new GeoLib::Point(ll[0], ur[1], 0.0, pnt_offset + 3)); plys.push_back(new GeoLib::Polyline(pnts)); plys[plys.size() - 1]->addPoint(pnt_offset); plys[plys.size() - 1]->addPoint(pnt_offset + 1); @@ -178,4 +194,4 @@ void GMSHAdaptiveMeshDensity::getQuadTreeGeometry(std::vector<GeoLib::Point*> &p #endif } // namespace GMSH -} // end namespace FileIO +} // end namespace FileIO diff --git a/Applications/FileIO/Gmsh/GMSHFixedMeshDensity.cpp b/Applications/FileIO/Gmsh/GMSHFixedMeshDensity.cpp index f2307c14e459e8fb825bcbc964ba504623930316..ea969359ca5035c92661de8ceae6726d73f03e0b 100644 --- a/Applications/FileIO/Gmsh/GMSHFixedMeshDensity.cpp +++ b/Applications/FileIO/Gmsh/GMSHFixedMeshDensity.cpp @@ -14,13 +14,13 @@ namespace FileIO { namespace GMSH { - -GMSHFixedMeshDensity::GMSHFixedMeshDensity(double mesh_density) : - _mesh_density(mesh_density) +GMSHFixedMeshDensity::GMSHFixedMeshDensity(double mesh_density) + : _mesh_density(mesh_density) { } -void GMSHFixedMeshDensity::initialize(std::vector<GeoLib::Point const*> const& vec) +void GMSHFixedMeshDensity::initialize( + std::vector<GeoLib::Point const*> const& vec) { // to avoid a warning here: (void)(vec); @@ -39,4 +39,4 @@ double GMSHFixedMeshDensity::getMeshDensityAtStation( } } // namespace GMSH -} // end namespace FileIO +} // end namespace FileIO diff --git a/Applications/FileIO/Gmsh/GMSHInterface.cpp b/Applications/FileIO/Gmsh/GMSHInterface.cpp index 94cc68a9cad2564820564d8b6826d54550cb5a2f..c4cd03ac19a4e7d5ddee1927fb423a9871c71a04 100644 --- a/Applications/FileIO/Gmsh/GMSHInterface.cpp +++ b/Applications/FileIO/Gmsh/GMSHInterface.cpp @@ -7,27 +7,25 @@ * http://www.opengeosys.org/project/license */ +#include "Applications/FileIO/Gmsh/GMSHInterface.h" + #include <fstream> #include <memory> #include <vector> -#include "BaseLib/Logging.h" - -#include "InfoLib/GitInfo.h" -#include "BaseLib/FileTools.h" - -#include "Applications/FileIO/Gmsh/GMSHInterface.h" #include "Applications/FileIO/Gmsh/GMSHAdaptiveMeshDensity.h" #include "Applications/FileIO/Gmsh/GMSHFixedMeshDensity.h" +#include "Applications/FileIO/Gmsh/GMSHMeshDensityStrategy.h" #include "Applications/FileIO/Gmsh/GMSHPoint.h" #include "Applications/FileIO/Gmsh/GMSHPolygonTree.h" -#include "Applications/FileIO/Gmsh/GMSHMeshDensityStrategy.h" - +#include "BaseLib/FileTools.h" +#include "BaseLib/Logging.h" #include "GeoLib/AnalyticalGeometry.h" #include "GeoLib/GEOObjects.h" #include "GeoLib/Polygon.h" -#include "GeoLib/PolylineWithSegmentMarker.h" #include "GeoLib/PolygonWithSegmentMarker.h" +#include "GeoLib/PolylineWithSegmentMarker.h" +#include "InfoLib/GitInfo.h" namespace FileIO { @@ -60,16 +58,17 @@ GMSHInterface::GMSHInterface( _rotate(rotate), _keep_preprocessed_geometry(keep_preprocessed_geometry) { - switch (mesh_density_algorithm) { - case GMSH::MeshDensityAlgorithm::FixedMeshDensity: - _mesh_density_strategy = - std::make_unique<GMSH::GMSHFixedMeshDensity>(pnt_density); - break; - case GMSH::MeshDensityAlgorithm::AdaptiveMeshDensity: - _mesh_density_strategy = - std::make_unique<GMSH::GMSHAdaptiveMeshDensity>( - pnt_density, station_density, max_pnts_per_leaf); - break; + switch (mesh_density_algorithm) + { + case GMSH::MeshDensityAlgorithm::FixedMeshDensity: + _mesh_density_strategy = + std::make_unique<GMSH::GMSHFixedMeshDensity>(pnt_density); + break; + case GMSH::MeshDensityAlgorithm::AdaptiveMeshDensity: + _mesh_density_strategy = + std::make_unique<GMSH::GMSHAdaptiveMeshDensity>( + pnt_density, station_density, max_pnts_per_leaf); + break; } } @@ -104,34 +103,41 @@ int GMSHInterface::writeGMSHInputFile(std::ostream& out) } // *** get and merge data from _geo_objs - if (_selected_geometries.size() > 1) { + if (_selected_geometries.size() > 1) + { _gmsh_geo_name = "GMSHGeometry"; if (_geo_objs.mergeGeometries(_selected_geometries, _gmsh_geo_name)) { return 2; } - } else { + } + else + { _gmsh_geo_name = _selected_geometries[0]; _keep_preprocessed_geometry = true; } auto* merged_pnts(const_cast<std::vector<GeoLib::Point*>*>( _geo_objs.getPointVec(_gmsh_geo_name))); - if (! merged_pnts) { + if (!merged_pnts) + { ERR("GMSHInterface::writeGMSHInputFile(): Did not found any points."); return 2; } - if (_rotate) { + if (_rotate) + { // Rotate points to the x-y-plane. _inverse_rot_mat = GeoLib::rotatePointsToXY(*merged_pnts); // Compute inverse rotation matrix to reverse the rotation later on. _inverse_rot_mat.transposeInPlace(); - } else { + } + else + { // project data on the x-y-plane - _inverse_rot_mat(0,0) = 1.0; - _inverse_rot_mat(1,1) = 1.0; - _inverse_rot_mat(2,2) = 1.0; + _inverse_rot_mat(0, 0) = 1.0; + _inverse_rot_mat(1, 1) = 1.0; + _inverse_rot_mat(2, 2) = 1.0; for (auto pnt : *merged_pnts) { (*pnt)[2] = 0.0; @@ -142,7 +148,8 @@ int GMSHInterface::writeGMSHInputFile(std::ostream& out) _geo_objs.getPolylineVec(_gmsh_geo_name)); DBUG("GMSHInterface::writeGMSHInputFile(): Obtained data."); - if (!merged_plys) { + if (!merged_plys) + { ERR("GMSHInterface::writeGMSHInputFile(): Did not find any polylines."); return 2; } @@ -150,12 +157,14 @@ int GMSHInterface::writeGMSHInputFile(std::ostream& out) // *** compute and insert all intersection points between polylines GeoLib::PointVec& pnt_vec(*const_cast<GeoLib::PointVec*>( _geo_objs.getPointVecObj(_gmsh_geo_name))); - GeoLib::computeAndInsertAllIntersectionPoints(pnt_vec, - *(const_cast<std::vector<GeoLib::Polyline*>*>(merged_plys))); + GeoLib::computeAndInsertAllIntersectionPoints( + pnt_vec, *(const_cast<std::vector<GeoLib::Polyline*>*>(merged_plys))); // *** compute topological hierarchy of polygons - for (auto polyline : *merged_plys) { - if (!polyline->isClosed()) { + for (auto polyline : *merged_plys) + { + if (!polyline->isClosed()) + { continue; } _polygon_tree_list.push_back(new GMSH::GMSHPolygonTree( @@ -178,35 +187,46 @@ int GMSHInterface::writeGMSHInputFile(std::ostream& out) polygon_tree->markSharedSegments(); } - // *** insert stations and polylines (except polygons) in the appropriate object of + // *** insert stations and polylines (except polygons) in the appropriate + // object of // class GMSHPolygonTree // *** insert stations auto gmsh_stations = std::make_unique<std::vector<GeoLib::Point*>>(); - for (auto const& geometry_name : _selected_geometries) { + for (auto const& geometry_name : _selected_geometries) + { auto const* stations(_geo_objs.getStationVec(geometry_name)); - if (stations) { - for (auto * station : *stations) { + if (stations) + { + for (auto* station : *stations) + { bool found(false); for (auto it(_polygon_tree_list.begin()); - it != _polygon_tree_list.end() && !found; ++it) { + it != _polygon_tree_list.end() && !found; + ++it) + { gmsh_stations->emplace_back(new GeoLib::Station( *static_cast<GeoLib::Station*>(station))); - if ((*it)->insertStation(gmsh_stations->back())) { + if ((*it)->insertStation(gmsh_stations->back())) + { found = true; } } } } } - std::string gmsh_stations_name(_gmsh_geo_name+"-Stations"); - if (! gmsh_stations->empty()) { + std::string gmsh_stations_name(_gmsh_geo_name + "-Stations"); + if (!gmsh_stations->empty()) + { _geo_objs.addStationVec(std::move(gmsh_stations), gmsh_stations_name); } // *** insert polylines - for (auto polyline : *merged_plys) { - if (!polyline->isClosed()) { - for (auto * polygon_tree : _polygon_tree_list) { + for (auto polyline : *merged_plys) + { + if (!polyline->isClosed()) + { + for (auto* polygon_tree : _polygon_tree_list) + { auto polyline_with_segment_marker = new GeoLib::PolylineWithSegmentMarker(*polyline); polygon_tree->insertPolyline(polyline_with_segment_marker); @@ -223,7 +243,8 @@ int GMSHInterface::writeGMSHInputFile(std::ostream& out) // *** create GMSH data structures const std::size_t n_merged_pnts(merged_pnts->size()); _gmsh_pnts.resize(n_merged_pnts); - for (std::size_t k(0); k<n_merged_pnts; k++) { + for (std::size_t k(0); k < n_merged_pnts; k++) + { _gmsh_pnts[k] = nullptr; } for (auto& polygon_tree : _polygon_tree_list) @@ -240,13 +261,16 @@ int GMSHInterface::writeGMSHInputFile(std::ostream& out) { polygon_tree->writeLineLoop(_n_lines, _n_plane_sfc, out, _write_physical_groups); - polygon_tree->writeSubPolygonsAsLineConstraints(_n_lines, _n_plane_sfc-1, out); - polygon_tree->writeLineConstraints(_n_lines, _n_plane_sfc-1, out); - polygon_tree->writeStations(pnt_id_offset, _n_plane_sfc-1, out); - polygon_tree->writeAdditionalPointData(pnt_id_offset, _n_plane_sfc-1, out); + polygon_tree->writeSubPolygonsAsLineConstraints(_n_lines, + _n_plane_sfc - 1, out); + polygon_tree->writeLineConstraints(_n_lines, _n_plane_sfc - 1, out); + polygon_tree->writeStations(pnt_id_offset, _n_plane_sfc - 1, out); + polygon_tree->writeAdditionalPointData(pnt_id_offset, _n_plane_sfc - 1, + out); } - if (! _keep_preprocessed_geometry) { + if (!_keep_preprocessed_geometry) + { _geo_objs.removeSurfaceVec(_gmsh_geo_name); _geo_objs.removePolylineVec(_gmsh_geo_name); _geo_objs.removePointVec(_gmsh_geo_name); @@ -256,5 +280,5 @@ int GMSHInterface::writeGMSHInputFile(std::ostream& out) return 0; } -} // end namespace GMSH -} // end namespace FileIO +} // end namespace GMSH +} // end namespace FileIO diff --git a/Applications/FileIO/Gmsh/GMSHLine.cpp b/Applications/FileIO/Gmsh/GMSHLine.cpp index 65027872f821ddc925181ecde592e4b02e1c48ff..5e467de58b01cef007901b9b0caa79b36571416b 100644 --- a/Applications/FileIO/Gmsh/GMSHLine.cpp +++ b/Applications/FileIO/Gmsh/GMSHLine.cpp @@ -8,22 +8,24 @@ * */ -#include <ostream> #include "GMSHLine.h" +#include <ostream> + namespace FileIO { namespace GMSH { +GMSHLine::GMSHLine(std::size_t start_point_id, std::size_t end_point_id) + : _start_pnt_id(start_point_id), _end_pnt_id(end_point_id) +{ +} -GMSHLine::GMSHLine(std::size_t start_point_id, std::size_t end_point_id) : - _start_pnt_id(start_point_id), _end_pnt_id(end_point_id) -{} - -void GMSHLine::write(std::ostream &os, std::size_t id) const +void GMSHLine::write(std::ostream& os, std::size_t id) const { - os << "Line(" << id << ") = {" << _start_pnt_id << "," << _end_pnt_id << "};\n"; + os << "Line(" << id << ") = {" << _start_pnt_id << "," << _end_pnt_id + << "};\n"; } -} // end namespace GMSH -} // end namespace FileIO +} // end namespace GMSH +} // end namespace FileIO diff --git a/Applications/FileIO/Gmsh/GMSHLineLoop.cpp b/Applications/FileIO/Gmsh/GMSHLineLoop.cpp index 9ab3854037ac43f72068dd0fc32866267c4d68ee..8322e9d2b1eeb06912b7481edd5b0023331933aa 100644 --- a/Applications/FileIO/Gmsh/GMSHLineLoop.cpp +++ b/Applications/FileIO/Gmsh/GMSHLineLoop.cpp @@ -8,10 +8,11 @@ * */ +#include "GMSHLineLoop.h" + #include <ostream> #include "GMSHLine.h" -#include "GMSHLineLoop.h" namespace FileIO { diff --git a/Applications/FileIO/Gmsh/GMSHPoint.cpp b/Applications/FileIO/Gmsh/GMSHPoint.cpp index 17cb737891fbf60eaa5f65f5348c2a595dc7a115..026575f8c3018f331cf3ebdb35c1434dca751bfd 100644 --- a/Applications/FileIO/Gmsh/GMSHPoint.cpp +++ b/Applications/FileIO/Gmsh/GMSHPoint.cpp @@ -8,33 +8,37 @@ * */ +#include "GMSHPoint.h" + #include <cmath> #include <limits> -#include "GMSHPoint.h" - namespace FileIO { namespace GMSH { +GMSHPoint::GMSHPoint(GeoLib::Point const& pnt, std::size_t id, + double mesh_density) + : GeoLib::Point(pnt, id), _mesh_density(mesh_density) +{ +} -GMSHPoint::GMSHPoint(GeoLib::Point const& pnt, std::size_t id, double mesh_density) : - GeoLib::Point(pnt, id), _mesh_density(mesh_density) -{} - -void GMSHPoint::write(std::ostream &os) const +void GMSHPoint::write(std::ostream& os) const { os << "Point(" << _id << ") = {" << _x[0] << ", " << _x[1] << ", " << _x[2]; - if (fabs(_mesh_density) > std::numeric_limits<double>::epsilon()) { + if (fabs(_mesh_density) > std::numeric_limits<double>::epsilon()) + { os << ", " << _mesh_density << "};"; - } else { + } + else + { os << "};"; } } -std::ostream& operator<< (std::ostream &os, GMSHPoint const& p) +std::ostream& operator<<(std::ostream& os, GMSHPoint const& p) { - p.write (os); + p.write(os); return os; } diff --git a/Applications/FileIO/Gmsh/GMSHPolygonTree.cpp b/Applications/FileIO/Gmsh/GMSHPolygonTree.cpp index 910e36cbf4f5f41db83229be2fd15fd53789f2d2..765c8c63484a672aeb7111b4046ab2b803f3d2d2 100644 --- a/Applications/FileIO/Gmsh/GMSHPolygonTree.cpp +++ b/Applications/FileIO/Gmsh/GMSHPolygonTree.cpp @@ -10,15 +10,14 @@ #include "GMSHPolygonTree.h" -#include "GMSHFixedMeshDensity.h" #include "GMSHAdaptiveMeshDensity.h" - +#include "GMSHFixedMeshDensity.h" #include "GeoLib/AnalyticalGeometry.h" #include "GeoLib/GEOObjects.h" #include "GeoLib/Point.h" #include "GeoLib/Polygon.h" -#include "GeoLib/PolylineWithSegmentMarker.h" #include "GeoLib/PolygonWithSegmentMarker.h" +#include "GeoLib/PolylineWithSegmentMarker.h" namespace FileIO { @@ -33,13 +32,15 @@ GMSHPolygonTree::GMSHPolygonTree(GeoLib::PolygonWithSegmentMarker* polygon, _geo_objs(geo_objs), _geo_name(geo_name), _mesh_density_strategy(mesh_density_strategy) -{} +{ +} GMSHPolygonTree::~GMSHPolygonTree() { // the polylines are processed also by the children, but the root is // responsible to cleanup up - if (_parent == nullptr) { // root + if (_parent == nullptr) + { // root for (auto* polyline : _plys) { delete polyline; @@ -64,7 +65,8 @@ void GMSHPolygonTree::markSharedSegments() for (auto& child : _children) { std::size_t const n_pnts(child->getPolygon()->getNumberOfPoints()); - for (std::size_t k(1); k<n_pnts; k++) { + for (std::size_t k(1); k < n_pnts; k++) + { if (GeoLib::containsEdge(*(_parent->getPolygon()), _node_polygon->getPointID(k - 1), _node_polygon->getPointID(k))) @@ -78,12 +80,18 @@ void GMSHPolygonTree::markSharedSegments() bool GMSHPolygonTree::insertStation(GeoLib::Point const* station) { - if (_node_polygon->isPntInPolygon(*station)) { + if (_node_polygon->isPntInPolygon(*station)) + { // try to insert station into the child nodes - for (std::list<SimplePolygonTree*>::const_iterator it (_children.begin()); - it != _children.end(); ++it) { - if (((*it)->getPolygon())->isPntInPolygon (*station)) { - bool rval(dynamic_cast<GMSHPolygonTree*>((*it))->insertStation (station)); + for (std::list<SimplePolygonTree*>::const_iterator it( + _children.begin()); + it != _children.end(); + ++it) + { + if (((*it)->getPolygon())->isPntInPolygon(*station)) + { + bool rval(dynamic_cast<GMSHPolygonTree*>((*it))->insertStation( + station)); // stop recursion if sub SimplePolygonTree is a leaf if (rval && (*it)->getNumberOfChildren() == 0) { @@ -92,14 +100,15 @@ bool GMSHPolygonTree::insertStation(GeoLib::Point const* station) return rval; } } - // station did not fit into child nodes -> insert the station into this node - _stations.push_back (station); + // station did not fit into child nodes -> insert the station into this + // node + _stations.push_back(station); return true; } return false; } -void GMSHPolygonTree::insertPolyline(GeoLib::PolylineWithSegmentMarker * ply) +void GMSHPolygonTree::insertPolyline(GeoLib::PolylineWithSegmentMarker* ply) { if (!_node_polygon->isPartOfPolylineInPolygon(*ply)) { @@ -108,7 +117,8 @@ void GMSHPolygonTree::insertPolyline(GeoLib::PolylineWithSegmentMarker * ply) // check if polyline segments are inside of the polygon, intersect the // polygon or are part of the boundary of the polygon - for (auto * polygon_tree : _children) { + for (auto* polygon_tree : _children) + { dynamic_cast<GMSHPolygonTree*>(polygon_tree)->insertPolyline(ply); } @@ -116,16 +126,16 @@ void GMSHPolygonTree::insertPolyline(GeoLib::PolylineWithSegmentMarker * ply) // (_node_polygon) and the given polyline ply // pay attention: loop bound is not fix! GeoLib::Point tmp_pnt; - GeoLib::PointVec & pnt_vec(*(_geo_objs.getPointVecObj(_geo_name))); - for (auto segment_it(ply->begin()); segment_it != ply->end(); - ++segment_it) + GeoLib::PointVec& pnt_vec(*(_geo_objs.getPointVecObj(_geo_name))); + for (auto segment_it(ply->begin()); segment_it != ply->end(); ++segment_it) { if (ply->isSegmentMarked(segment_it.getSegmentNumber())) { continue; } - if (_node_polygon->containsSegment(*segment_it)) { + if (_node_polygon->containsSegment(*segment_it)) + { ply->markSegment(segment_it.getSegmentNumber(), true); continue; } @@ -135,38 +145,46 @@ void GMSHPolygonTree::insertPolyline(GeoLib::PolylineWithSegmentMarker * ply) while (_node_polygon->getNextIntersectionPointPolygonLine( *segment_it, intersection_pnt, seg_num)) { - // insert the intersection point to point vector of GEOObjects instance + // insert the intersection point to point vector of GEOObjects + // instance const std::size_t pnt_vec_size(pnt_vec.size()); std::size_t pnt_id( pnt_vec.push_back(new GeoLib::Point(intersection_pnt))); - if (pnt_vec_size < pnt_vec.size()) { // case: new point + if (pnt_vec_size < pnt_vec.size()) + { // case: new point // modify the polygon - _node_polygon->insertPoint(seg_num+1, pnt_id); + _node_polygon->insertPoint(seg_num + 1, pnt_id); // modify the polyline ply->insertPoint(segment_it.getSegmentNumber(), pnt_id); - } else { // case: existing point + } + else + { // case: existing point // check if point id is within the polygon - if (! _node_polygon->isPointIDInPolyline(pnt_id)) { - _node_polygon->insertPoint(seg_num+1, pnt_id); + if (!_node_polygon->isPointIDInPolyline(pnt_id)) + { + _node_polygon->insertPoint(seg_num + 1, pnt_id); } // check if point id is in polyline - if (! ply->isPointIDInPolyline(pnt_id)) { - ply->insertPoint(segment_it.getSegmentNumber()+1, pnt_id); + if (!ply->isPointIDInPolyline(pnt_id)) + { + ply->insertPoint(segment_it.getSegmentNumber() + 1, pnt_id); } } - std::size_t tmp_seg_num(seg_num+1); + std::size_t tmp_seg_num(seg_num + 1); if (!_node_polygon->getNextIntersectionPointPolygonLine( *segment_it, tmp_pnt, tmp_seg_num)) { // check a point of the segment except the end points - for (std::size_t i(0); i<3; i++) { + for (std::size_t i(0); i < 3; i++) + { tmp_pnt[i] = ((*segment_it).getBeginPoint()[i] + (*segment_it).getEndPoint()[i]) / 2; } - if (_node_polygon->isPntInPolygon(tmp_pnt)) { + if (_node_polygon->isPntInPolygon(tmp_pnt)) + { ply->markSegment(segment_it.getSegmentNumber(), true); // insert line segment as constraint _gmsh_lines_for_constraints.push_back( @@ -177,7 +195,8 @@ void GMSHPolygonTree::insertPolyline(GeoLib::PolylineWithSegmentMarker * ply) seg_num++; // check a point of the segment except the end points - for (std::size_t i(0); i<3; i++) { + for (std::size_t i(0); i < 3; i++) + { tmp_pnt[i] = ((*segment_it).getBeginPoint()[i] + (*segment_it).getEndPoint()[i]) / 2; @@ -185,7 +204,8 @@ void GMSHPolygonTree::insertPolyline(GeoLib::PolylineWithSegmentMarker * ply) checkIntersectionsSegmentExistingPolylines(ply, segment_it); - if (_node_polygon->isPntInPolygon(tmp_pnt)) { + if (_node_polygon->isPntInPolygon(tmp_pnt)) + { ply->markSegment(segment_it.getSegmentNumber(), true); // insert line segment as constraint _gmsh_lines_for_constraints.push_back( @@ -203,30 +223,39 @@ void GMSHPolygonTree::checkIntersectionsSegmentExistingPolylines( GeoLib::Polyline::SegmentIterator const& seg_it) { std::size_t const ply_segment_number(seg_it.getSegmentNumber()); - for(GeoLib::PolylineWithSegmentMarker *const p : _plys) { - GeoLib::PointVec & pnt_vec(*(_geo_objs.getPointVecObj(_geo_name))); - for (auto seg_it_p(p->begin()); seg_it_p != p->end(); ++seg_it_p) { - GeoLib::Point s; // intersection point + for (GeoLib::PolylineWithSegmentMarker* const p : _plys) + { + GeoLib::PointVec& pnt_vec(*(_geo_objs.getPointVecObj(_geo_name))); + for (auto seg_it_p(p->begin()); seg_it_p != p->end(); ++seg_it_p) + { + GeoLib::Point s; // intersection point if (GeoLib::lineSegmentIntersect(*seg_it, *seg_it_p, s)) { const std::size_t pnt_vec_size(pnt_vec.size()); // point id of new point in GEOObjects instance - const std::size_t pnt_id(pnt_vec.push_back(new GeoLib::Point(s))); - if (pnt_vec_size < pnt_vec.size()) { // case: new point + const std::size_t pnt_id( + pnt_vec.push_back(new GeoLib::Point(s))); + if (pnt_vec_size < pnt_vec.size()) + { // case: new point // modify polyline already in this node - p->insertPoint(seg_it_p.getSegmentNumber()+1, pnt_id); + p->insertPoint(seg_it_p.getSegmentNumber() + 1, pnt_id); // modify polyline - ply->insertPoint(ply_segment_number+1, pnt_id); - } else { // case: point exists already in geometry + ply->insertPoint(ply_segment_number + 1, pnt_id); + } + else + { // case: point exists already in geometry // check if point is not already in polyline p std::size_t const k(seg_it_p.getSegmentNumber()); - if (p->getPointID(k) != pnt_id && p->getPointID(k+1) != pnt_id) { - p->insertPoint(k+1, pnt_id); + if (p->getPointID(k) != pnt_id && + p->getPointID(k + 1) != pnt_id) + { + p->insertPoint(k + 1, pnt_id); } // check if point is not already in polyline ply - if (ply->getPointID(ply_segment_number) != pnt_id - && ply->getPointID(ply_segment_number+1) != pnt_id) { - ply->insertPoint(ply_segment_number+1, pnt_id); + if (ply->getPointID(ply_segment_number) != pnt_id && + ply->getPointID(ply_segment_number + 1) != pnt_id) + { + ply->insertPoint(ply_segment_number + 1, pnt_id); } } } @@ -241,16 +270,19 @@ void GMSHPolygonTree::initMeshDensityStrategy() { // collect points std::vector<GeoLib::Point const*> pnts; - const std::size_t n_pnts_polygon (_node_polygon->getNumberOfPoints()); - for (std::size_t k(0); k<n_pnts_polygon; k++) { + const std::size_t n_pnts_polygon(_node_polygon->getNumberOfPoints()); + for (std::size_t k(0); k < n_pnts_polygon; k++) + { pnts.push_back(_node_polygon->getPoint(k)); } getPointsFromSubPolygons(pnts); - const std::size_t n_plys (_plys.size()); - for (std::size_t k(0); k<n_plys; k++) { + const std::size_t n_plys(_plys.size()); + for (std::size_t k(0); k < n_plys; k++) + { const std::size_t n_pnts_in_kth_ply(_plys[k]->getNumberOfPoints()); - for (std::size_t j(0); j<n_pnts_in_kth_ply; j++) { + for (std::size_t j(0); j < n_pnts_in_kth_ply; j++) + { pnts.push_back(_plys[k]->getPoint(j)); } } @@ -265,12 +297,13 @@ void GMSHPolygonTree::initMeshDensityStrategy() } } -void GMSHPolygonTree::createGMSHPoints(std::vector<GMSHPoint*> & gmsh_pnts) const +void GMSHPolygonTree::createGMSHPoints(std::vector<GMSHPoint*>& gmsh_pnts) const { - const std::size_t n_pnts_polygon (_node_polygon->getNumberOfPoints()); - for (std::size_t k(0); k<n_pnts_polygon-1; k++) { - const std::size_t id (_node_polygon->getPointID(k)); - GeoLib::Point const*const pnt(_node_polygon->getPoint(k)); + const std::size_t n_pnts_polygon(_node_polygon->getNumberOfPoints()); + for (std::size_t k(0); k < n_pnts_polygon - 1; k++) + { + const std::size_t id(_node_polygon->getPointID(k)); + GeoLib::Point const* const pnt(_node_polygon->getPoint(k)); // if this point was already part of another polyline if (gmsh_pnts[id] != nullptr) { @@ -281,17 +314,20 @@ void GMSHPolygonTree::createGMSHPoints(std::vector<GMSHPoint*> & gmsh_pnts) cons } const std::size_t n_plys(_plys.size()); - for (std::size_t k(0); k<n_plys; k++) { + for (std::size_t k(0); k < n_plys; k++) + { const std::size_t n_pnts_in_ply(_plys[k]->getNumberOfPoints()); - for (std::size_t j(0); j<n_pnts_in_ply; j++) { - if (_node_polygon->isPntInPolygon(*(_plys[k]->getPoint(j)))) { - const std::size_t id (_plys[k]->getPointID(j)); + for (std::size_t j(0); j < n_pnts_in_ply; j++) + { + if (_node_polygon->isPntInPolygon(*(_plys[k]->getPoint(j)))) + { + const std::size_t id(_plys[k]->getPointID(j)); // if this point was already part of another polyline if (gmsh_pnts[id] != nullptr) { continue; } - GeoLib::Point const*const pnt(_plys[k]->getPoint(j)); + GeoLib::Point const* const pnt(_plys[k]->getPoint(j)); gmsh_pnts[id] = new GMSHPoint( *pnt, id, _mesh_density_strategy.getMeshDensityAtPoint(pnt)); @@ -319,11 +355,12 @@ void GMSHPolygonTree::writeLineLoop(std::size_t& line_offset, << second_pnt_id << "};\n"; first_pnt_id = second_pnt_id; } - out << "Line Loop(" << line_offset + n_pnts-1 << ") = {"; - for (std::size_t k(0); k<n_pnts - 2; k++) { - out << line_offset+k << ","; + out << "Line Loop(" << line_offset + n_pnts - 1 << ") = {"; + for (std::size_t k(0); k < n_pnts - 2; k++) + { + out << line_offset + k << ","; } - out << line_offset+n_pnts-2 << "};\n"; + out << line_offset + n_pnts - 2 << "};\n"; out << "Plane Surface(" << sfc_offset << ") = {" << line_offset + n_pnts - 1 << "};\n"; if (write_physical) @@ -334,8 +371,8 @@ void GMSHPolygonTree::writeLineLoop(std::size_t& line_offset, out << line_offset + k << ","; } out << line_offset + n_pnts - 2 << "};\n"; - out << "Physical Surface(" << sfc_offset << ") = {" - << sfc_offset << "};\n"; + out << "Physical Surface(" << sfc_offset << ") = {" << sfc_offset + << "};\n"; } line_offset += n_pnts; sfc_offset++; @@ -354,7 +391,8 @@ void GMSHPolygonTree::writeLineConstraints(std::size_t& line_offset, auto const second_pnt_id = polyline->getPointID(k); if (polyline->isSegmentMarked(k - 1) && _node_polygon->isPntInPolygon(*(polyline->getPoint(k))) && - !GeoLib::containsEdge(*_node_polygon, first_pnt_id, second_pnt_id)) + !GeoLib::containsEdge(*_node_polygon, first_pnt_id, + second_pnt_id)) { out << "Line(" << line_offset + k - 1 << ") = {" << first_pnt_id << "," << second_pnt_id << "};\n"; @@ -367,7 +405,8 @@ void GMSHPolygonTree::writeLineConstraints(std::size_t& line_offset, } } -void GMSHPolygonTree::writeSubPolygonsAsLineConstraints(std::size_t &line_offset, std::size_t sfc_number, std::ostream& out) const +void GMSHPolygonTree::writeSubPolygonsAsLineConstraints( + std::size_t& line_offset, std::size_t sfc_number, std::ostream& out) const { for (auto child : _children) { @@ -379,31 +418,39 @@ void GMSHPolygonTree::writeSubPolygonsAsLineConstraints(std::size_t &line_offset { const std::size_t n_pnts(_node_polygon->getNumberOfPoints()); std::size_t first_pnt_id(_node_polygon->getPointID(0)); - for (std::size_t k(1); k<n_pnts; k++) { + for (std::size_t k(1); k < n_pnts; k++) + { auto const second_pnt_id = _node_polygon->getPointID(k); - out << "Line(" << line_offset + k-1 << ") = {" << first_pnt_id << "," << second_pnt_id << "};\n"; + out << "Line(" << line_offset + k - 1 << ") = {" << first_pnt_id + << "," << second_pnt_id << "};\n"; first_pnt_id = second_pnt_id; - out << "Line { " << line_offset+k-1 << " } In Surface { " << sfc_number << " };\n"; + out << "Line { " << line_offset + k - 1 << " } In Surface { " + << sfc_number << " };\n"; } line_offset += n_pnts; } - } -void GMSHPolygonTree::writeStations(std::size_t & pnt_id_offset, std::size_t sfc_number, std::ostream& out) const +void GMSHPolygonTree::writeStations(std::size_t& pnt_id_offset, + std::size_t sfc_number, + std::ostream& out) const { - for (auto const* station : _stations) { + for (auto const* station : _stations) + { out << "Point(" << pnt_id_offset << ") = {" << (*station)[0] << ", " << (*station)[1] << ", 0.0, " << _mesh_density_strategy.getMeshDensityAtStation(station) << "}; // Station " << static_cast<GeoLib::Station const*>(station)->getName() << " \n"; - out << "Point { " << pnt_id_offset << " } In Surface { " << sfc_number << " };\n"; + out << "Point { " << pnt_id_offset << " } In Surface { " << sfc_number + << " };\n"; ++pnt_id_offset; } } -void GMSHPolygonTree::writeAdditionalPointData(std::size_t & pnt_id_offset, std::size_t sfc_number, std::ostream& out) const +void GMSHPolygonTree::writeAdditionalPointData(std::size_t& pnt_id_offset, + std::size_t sfc_number, + std::ostream& out) const { if (auto* adaptive_mesh_density = dynamic_cast<GMSHAdaptiveMeshDensity*>(&_mesh_density_strategy)) @@ -411,13 +458,18 @@ void GMSHPolygonTree::writeAdditionalPointData(std::size_t & pnt_id_offset, std: std::vector<GeoLib::Point*> steiner_pnts; adaptive_mesh_density->getSteinerPoints(steiner_pnts, 0); const std::size_t n(steiner_pnts.size()); - for (std::size_t k(0); k<n; k++) { - if (_node_polygon->isPntInPolygon(*(steiner_pnts[k]))) { - out << "Point(" << pnt_id_offset + k << ") = {" << (*(steiner_pnts[k]))[0] << "," << (*(steiner_pnts[k]))[1] << ", 0.0, "; + for (std::size_t k(0); k < n; k++) + { + if (_node_polygon->isPntInPolygon(*(steiner_pnts[k]))) + { + out << "Point(" << pnt_id_offset + k << ") = {" + << (*(steiner_pnts[k]))[0] << "," << (*(steiner_pnts[k]))[1] + << ", 0.0, "; out << _mesh_density_strategy.getMeshDensityAtPoint( steiner_pnts[k]) << "};\n"; - out << "Point { " << pnt_id_offset + k << " } In Surface { " << sfc_number << " };\n"; + out << "Point { " << pnt_id_offset + k << " } In Surface { " + << sfc_number << " };\n"; } delete steiner_pnts[k]; } @@ -433,34 +485,45 @@ void GMSHPolygonTree::writeAdditionalPointData(std::size_t & pnt_id_offset, std: adaptive_mesh_density->getQuadTreeGeometry(*pnts, *plys); std::string quad_tree_geo("QuadTree"); _geo_objs.addPointVec(std::move(pnts), quad_tree_geo); - std::vector<std::size_t> const& id_map ((_geo_objs.getPointVecObj(quad_tree_geo))->getIDMap()); - for (std::size_t k(0); k<plys->size(); k++) { - for (std::size_t j(0); j<(*plys)[k]->getNumberOfPoints(); j++) { - ((*plys)[k])->setPointID(j, id_map[((*plys)[k])->getPointID(j)]); + std::vector<std::size_t> const& id_map( + (_geo_objs.getPointVecObj(quad_tree_geo))->getIDMap()); + for (std::size_t k(0); k < plys->size(); k++) + { + for (std::size_t j(0); j < (*plys)[k]->getNumberOfPoints(); j++) + { + ((*plys)[k]) + ->setPointID(j, id_map[((*plys)[k])->getPointID(j)]); } } _geo_objs.addPolylineVec(std::move(plys), quad_tree_geo); } #endif - } -void GMSHPolygonTree::getPointsFromSubPolygons(std::vector<GeoLib::Point const*>& pnts) +void GMSHPolygonTree::getPointsFromSubPolygons( + std::vector<GeoLib::Point const*>& pnts) { - for (std::list<SimplePolygonTree*>::const_iterator it (_children.begin()); it != _children.end(); ++it) { + for (std::list<SimplePolygonTree*>::const_iterator it(_children.begin()); + it != _children.end(); ++it) + { dynamic_cast<GMSHPolygonTree*>((*it))->getPointsFromSubPolygons(pnts); } } -void GMSHPolygonTree::getStationsInsideSubPolygons(std::vector<GeoLib::Point const*>& stations) +void GMSHPolygonTree::getStationsInsideSubPolygons( + std::vector<GeoLib::Point const*>& stations) { const std::size_t n_stations(_stations.size()); - for (std::size_t k(0); k<n_stations; k++) { + for (std::size_t k(0); k < n_stations; k++) + { stations.push_back(_stations[k]); } - for (std::list<SimplePolygonTree*>::const_iterator it (_children.begin()); it != _children.end(); ++it) { - dynamic_cast<GMSHPolygonTree*>((*it))->getStationsInsideSubPolygons(stations); + for (std::list<SimplePolygonTree*>::const_iterator it(_children.begin()); + it != _children.end(); ++it) + { + dynamic_cast<GMSHPolygonTree*>((*it))->getStationsInsideSubPolygons( + stations); } } diff --git a/Applications/FileIO/Gmsh/GmshReader.cpp b/Applications/FileIO/Gmsh/GmshReader.cpp index bcc0d4d40d37bfd66620348c0a2a7ee118c50374..1cefa6aa7593eb59bfaff6eb8df0ccffbcb092ff 100644 --- a/Applications/FileIO/Gmsh/GmshReader.cpp +++ b/Applications/FileIO/Gmsh/GmshReader.cpp @@ -9,43 +9,41 @@ #include "GmshReader.h" +#include <fstream> +#include <map> +#include <vector> + +#include "BaseLib/FileTools.h" #include "MeshLib/Elements/Element.h" -#include "MeshLib/Elements/Line.h" -#include "MeshLib/Elements/Tri.h" -#include "MeshLib/Elements/Quad.h" -#include "MeshLib/Elements/Tet.h" #include "MeshLib/Elements/Hex.h" +#include "MeshLib/Elements/Line.h" #include "MeshLib/Elements/Prism.h" #include "MeshLib/Elements/Pyramid.h" - -#include "MeshLib/Node.h" +#include "MeshLib/Elements/Quad.h" +#include "MeshLib/Elements/Tet.h" +#include "MeshLib/Elements/Tri.h" #include "MeshLib/Mesh.h" - #include "MeshLib/MeshEditing/ElementValueModification.h" - -#include "BaseLib/FileTools.h" - -#include <fstream> -#include <map> -#include <vector> +#include "MeshLib/Node.h" namespace FileIO { namespace GMSH { - bool isGMSHMeshFile(const std::string& fname) { std::ifstream input(fname.c_str()); - if (!input) { + if (!input) + { ERR("isGMSHMeshFile(): Could not open file {:s}.", fname); return false; } std::string header_first_line; input >> header_first_line; - if (header_first_line.find("$MeshFormat") != std::string::npos) { + if (header_first_line.find("$MeshFormat") != std::string::npos) + { // read version std::string version; getline(input, version); @@ -81,79 +79,86 @@ std::pair<MeshLib::Element*, int> readElement( int mat_id; std::vector<unsigned> node_ids; - //element format is structured like this: - //element-id element-type n-tags physical-entity elementary entity node-ids + // element format is structured like this: + // element-id element-type n-tags physical-entity elementary entity node-ids in >> idx >> type >> n_tags >> dummy >> mat_id; switch (type) { - case 1: { - readNodeIDs(in, 2, node_ids, id_map); - // edge_nodes array will be deleted from Line object - auto edge_nodes = new MeshLib::Node*[2]; - edge_nodes[0] = nodes[node_ids[0]]; - edge_nodes[1] = nodes[node_ids[1]]; - return std::make_pair(new MeshLib::Line(edge_nodes), mat_id); - } - case 2: { - readNodeIDs(in, 3, node_ids, id_map); - auto tri_nodes = new MeshLib::Node*[3]; - tri_nodes[0] = nodes[node_ids[2]]; - tri_nodes[1] = nodes[node_ids[1]]; - tri_nodes[2] = nodes[node_ids[0]]; - return std::make_pair(new MeshLib::Tri(tri_nodes), mat_id); - } - case 3: { - readNodeIDs(in, 4, node_ids, id_map); - auto quad_nodes = new MeshLib::Node*[4]; - for (unsigned k(0); k < 4; k++) + case 1: { - quad_nodes[k] = nodes[node_ids[k]]; + readNodeIDs(in, 2, node_ids, id_map); + // edge_nodes array will be deleted from Line object + auto edge_nodes = new MeshLib::Node*[2]; + edge_nodes[0] = nodes[node_ids[0]]; + edge_nodes[1] = nodes[node_ids[1]]; + return std::make_pair(new MeshLib::Line(edge_nodes), mat_id); } - return std::make_pair(new MeshLib::Quad(quad_nodes), mat_id); - } - case 4: { - readNodeIDs(in, 4, node_ids, id_map); - auto tet_nodes = new MeshLib::Node*[5]; - for (unsigned k(0); k < 4; k++) + case 2: { - tet_nodes[k] = nodes[node_ids[k]]; + readNodeIDs(in, 3, node_ids, id_map); + auto tri_nodes = new MeshLib::Node*[3]; + tri_nodes[0] = nodes[node_ids[2]]; + tri_nodes[1] = nodes[node_ids[1]]; + tri_nodes[2] = nodes[node_ids[0]]; + return std::make_pair(new MeshLib::Tri(tri_nodes), mat_id); } - return std::make_pair(new MeshLib::Tet(tet_nodes), mat_id); - } - case 5: { - readNodeIDs(in, 8, node_ids, id_map); - auto hex_nodes = new MeshLib::Node*[8]; - for (unsigned k(0); k < 8; k++) + case 3: { - hex_nodes[k] = nodes[node_ids[k]]; + readNodeIDs(in, 4, node_ids, id_map); + auto quad_nodes = new MeshLib::Node*[4]; + for (unsigned k(0); k < 4; k++) + { + quad_nodes[k] = nodes[node_ids[k]]; + } + return std::make_pair(new MeshLib::Quad(quad_nodes), mat_id); } - return std::make_pair(new MeshLib::Hex(hex_nodes), mat_id); - } - case 6: { - readNodeIDs(in, 6, node_ids, id_map); - auto prism_nodes = new MeshLib::Node*[6]; - for (unsigned k(0); k < 6; k++) + case 4: { - prism_nodes[k] = nodes[node_ids[k]]; + readNodeIDs(in, 4, node_ids, id_map); + auto tet_nodes = new MeshLib::Node*[5]; + for (unsigned k(0); k < 4; k++) + { + tet_nodes[k] = nodes[node_ids[k]]; + } + return std::make_pair(new MeshLib::Tet(tet_nodes), mat_id); } - return std::make_pair(new MeshLib::Prism(prism_nodes), mat_id); - } - case 7: { - readNodeIDs(in, 5, node_ids, id_map); - auto pyramid_nodes = new MeshLib::Node*[5]; - for (unsigned k(0); k < 5; k++) + case 5: + { + readNodeIDs(in, 8, node_ids, id_map); + auto hex_nodes = new MeshLib::Node*[8]; + for (unsigned k(0); k < 8; k++) + { + hex_nodes[k] = nodes[node_ids[k]]; + } + return std::make_pair(new MeshLib::Hex(hex_nodes), mat_id); + } + case 6: { - pyramid_nodes[k] = nodes[node_ids[k]]; + readNodeIDs(in, 6, node_ids, id_map); + auto prism_nodes = new MeshLib::Node*[6]; + for (unsigned k(0); k < 6; k++) + { + prism_nodes[k] = nodes[node_ids[k]]; + } + return std::make_pair(new MeshLib::Prism(prism_nodes), mat_id); } - return std::make_pair(new MeshLib::Pyramid(pyramid_nodes), mat_id); - } - case 15: - in >> dummy; // skip rest of line - break; - default: - WARN("readGMSHMesh(): Unknown element type {:d}.", type); - break; + case 7: + { + readNodeIDs(in, 5, node_ids, id_map); + auto pyramid_nodes = new MeshLib::Node*[5]; + for (unsigned k(0); k < 5; k++) + { + pyramid_nodes[k] = nodes[node_ids[k]]; + } + return std::make_pair(new MeshLib::Pyramid(pyramid_nodes), mat_id); + } + case 15: + in >> dummy; // skip rest of line + break; + default: + WARN("readGMSHMesh(): Unknown element type {:d}.", type); + break; } return std::make_pair(nullptr, -1); } @@ -168,15 +173,15 @@ MeshLib::Mesh* readGMSHMesh(std::string const& fname) return nullptr; } - getline(in, line); // $MeshFormat keyword + getline(in, line); // $MeshFormat keyword if (line.find("$MeshFormat") == std::string::npos) { in.close(); - WARN ("No GMSH file format recognized."); + WARN("No GMSH file format recognized."); return nullptr; } - getline(in, line); // version-number file-type data-size + getline(in, line); // version-number file-type data-size if (line.substr(0, 3) != "2.2") { WARN("Wrong gmsh file format version '{:s}'.", line.substr(0, 3)); @@ -188,7 +193,7 @@ MeshLib::Mesh* readGMSHMesh(std::string const& fname) WARN("Currently reading gmsh binary file type is not supported."); return nullptr; } - getline(in, line); //$EndMeshFormat + getline(in, line); //$EndMeshFormat std::vector<MeshLib::Node*> nodes; std::vector<MeshLib::Element*> elements; @@ -197,7 +202,7 @@ MeshLib::Mesh* readGMSHMesh(std::string const& fname) while (line.find("$EndElements") == std::string::npos) { // Node data - getline(in, line); //$Nodes Keywords + getline(in, line); //$Nodes Keywords if (line.find("$Nodes") != std::string::npos) { std::size_t n_nodes(0); @@ -207,19 +212,21 @@ MeshLib::Mesh* readGMSHMesh(std::string const& fname) double z; in >> n_nodes >> std::ws; nodes.resize(n_nodes); - for (std::size_t i = 0; i < n_nodes; i++) { + for (std::size_t i = 0; i < n_nodes; i++) + { in >> id >> x >> y >> z >> std::ws; id_map.insert(std::map<unsigned, unsigned>::value_type(id, i)); - nodes[i] = new MeshLib::Node(x,y,z,id); + nodes[i] = new MeshLib::Node(x, y, z, id); } - getline(in, line); // End Node keyword $EndNodes + getline(in, line); // End Node keyword $EndNodes } // Element data if (line.find("$Elements") != std::string::npos) { std::size_t n_elements(0); - if (! (in >> n_elements >> std::ws)) { // number-of-elements + if (!(in >> n_elements >> std::ws)) + { // number-of-elements ERR("Read GMSH mesh does not contain any elements"); } elements.reserve(n_elements); @@ -230,27 +237,29 @@ MeshLib::Mesh* readGMSHMesh(std::string const& fname) int mat_id(0); std::tie(elem, mat_id) = readElement(in, nodes, id_map); - if (elem) { + if (elem) + { elements.push_back(elem); materials.push_back(mat_id); } } - getline(in, line); // END keyword + getline(in, line); // END keyword } if (line.find("PhysicalNames") != std::string::npos) { std::size_t n_lines(0); - in >> n_lines >> std::ws; // number-of-lines + in >> n_lines >> std::ws; // number-of-lines for (std::size_t i = 0; i < n_lines; i++) { getline(in, line); } - getline(in, line); // END keyword + getline(in, line); // END keyword } } in.close(); - if (elements.empty()) { + if (elements.empty()) + { for (auto& node : nodes) { delete node; @@ -258,7 +267,7 @@ MeshLib::Mesh* readGMSHMesh(std::string const& fname) return nullptr; } - MeshLib::Mesh * mesh(new MeshLib::Mesh( + MeshLib::Mesh* mesh(new MeshLib::Mesh( BaseLib::extractBaseNameWithoutExtension(fname), nodes, elements)); auto* const material_ids = @@ -283,5 +292,5 @@ MeshLib::Mesh* readGMSHMesh(std::string const& fname) return mesh; } -} // end namespace GMSH -} // end namespace FileIO +} // end namespace GMSH +} // end namespace FileIO diff --git a/Applications/FileIO/GocadIO/CoordinateSystem.cpp b/Applications/FileIO/GocadIO/CoordinateSystem.cpp index 146133ed81fff438a13143f16595c90c54e26451..e13a7a05fcb3f6fee14bce6ab75482da2a855eeb 100644 --- a/Applications/FileIO/GocadIO/CoordinateSystem.cpp +++ b/Applications/FileIO/GocadIO/CoordinateSystem.cpp @@ -19,7 +19,6 @@ namespace FileIO { namespace Gocad { - std::string parseName(std::string const& str) { std::string name; @@ -27,7 +26,7 @@ std::string parseName(std::string const& str) if (start != std::string::npos) { std::size_t const end = str.find_last_of('\"'); - name = str.substr(start+1, end-start-1); + name = str.substr(start + 1, end - start - 1); } else { @@ -53,7 +52,7 @@ bool CoordinateSystem::parse(std::istream& in) projection = ""; datum = ""; - while ( std::getline(in, line)) + while (std::getline(in, line)) { tok.assign(line); it = tok.begin(); @@ -105,7 +104,7 @@ bool CoordinateSystem::parse(std::istream& in) line); } } - ERR ("Error: Unexpected end of file."); + ERR("Error: Unexpected end of file."); return false; } diff --git a/Applications/FileIO/GocadIO/GenerateFaceSetMeshes.cpp b/Applications/FileIO/GocadIO/GenerateFaceSetMeshes.cpp index ec7d06e33188be09c7368a1ad0a5ff2d16b1a11b..e2ac86c10bc0c621c1acc53bb871e6ef75126881 100644 --- a/Applications/FileIO/GocadIO/GenerateFaceSetMeshes.cpp +++ b/Applications/FileIO/GocadIO/GenerateFaceSetMeshes.cpp @@ -8,6 +8,7 @@ */ #include "GenerateFaceSetMeshes.h" + #include "MeshLib/Elements/Quad.h" #include "MeshLib/IO/writeMeshToFile.h" @@ -15,7 +16,6 @@ namespace FileIO { namespace Gocad { - void generateFaceSets(GocadSGridReader const& reader, std::string const& path) { for (std::size_t l(0); l < 128; l++) diff --git a/Applications/FileIO/GocadIO/GocadNode.cpp b/Applications/FileIO/GocadIO/GocadNode.cpp index 4bdfc290ce5831cc21e54b90c1be3fc739adfbfb..ca341adb39122aa5c158c9c40e745dcb6c04eec4 100644 --- a/Applications/FileIO/GocadIO/GocadNode.cpp +++ b/Applications/FileIO/GocadIO/GocadNode.cpp @@ -33,4 +33,3 @@ bool operator<=(GocadNode const& n0, GocadNode const& n1) } // end namespace Gocad } // end namespace FileIO - diff --git a/Applications/FileIO/GocadIO/GocadSGridReader.cpp b/Applications/FileIO/GocadIO/GocadSGridReader.cpp index 17c111c92333c24e2db2b9544e4ec67b4e925101..46014b1c21ca520543a339bcfe23aaa6c9e5f4f6 100644 --- a/Applications/FileIO/GocadIO/GocadSGridReader.cpp +++ b/Applications/FileIO/GocadIO/GocadSGridReader.cpp @@ -435,8 +435,7 @@ void GocadSGridReader::readNodesBinary() { const std::size_t layer_transition_idx( _index_calculator.getCoordsForID(k / 3)[2]); - _nodes[k / 3] = - new GocadNode(coords, k / 3, layer_transition_idx); + _nodes[k / 3] = new GocadNode(coords, k / 3, layer_transition_idx); } k++; } diff --git a/Applications/FileIO/GocadIO/Layer.cpp b/Applications/FileIO/GocadIO/Layer.cpp index 111b8f3f15bb9ed398c8cf51b2ec106fd315a306..b3233392645715850171563321c2f7b8ca6420e7 100644 --- a/Applications/FileIO/GocadIO/Layer.cpp +++ b/Applications/FileIO/GocadIO/Layer.cpp @@ -19,7 +19,6 @@ namespace FileIO { namespace Gocad { - std::ostream& operator<<(std::ostream& os, Layer const& l) { std::copy(l.regions.begin(), l.regions.end(), @@ -27,8 +26,8 @@ std::ostream& operator<<(std::ostream& os, Layer const& l) return os; } - -Layer parseLayer(std::string const& line, std::vector<Gocad::Region> const& regions) +Layer parseLayer(std::string const& line, + std::vector<Gocad::Region> const& regions) { std::istringstream iss(line); std::istream_iterator<std::string> it(iss); diff --git a/Applications/FileIO/GocadIO/Property.cpp b/Applications/FileIO/GocadIO/Property.cpp index 2e2146e5b3bcad14dae6309e1a19da21b881d575..d3da0a815111efa136fc677e99f4035ddaf256e8 100644 --- a/Applications/FileIO/GocadIO/Property.cpp +++ b/Applications/FileIO/GocadIO/Property.cpp @@ -7,21 +7,19 @@ * http://www.opengeosys.org/project/license */ +#include "Property.h" + #include <algorithm> +#include <boost/tokenizer.hpp> #include <iterator> #include <sstream> -#include <boost/tokenizer.hpp> - -#include "Property.h" - #include "BaseLib/StringTools.h" namespace FileIO { namespace Gocad { - std::ostream& operator<<(std::ostream& os, Property const& p) { return os << "'" << p._property_name << "' '" << p._property_id << "' '" diff --git a/Applications/FileIO/GocadIO/Region.cpp b/Applications/FileIO/GocadIO/Region.cpp index e2e8d466c3a40cdb1ae3094170251b9c6015b693..90fc1acca8622cce39cc58c374ff5f38f6c7178f 100644 --- a/Applications/FileIO/GocadIO/Region.cpp +++ b/Applications/FileIO/GocadIO/Region.cpp @@ -18,7 +18,6 @@ namespace FileIO { namespace Gocad { - std::ostream& operator<<(std::ostream& os, Region const& r) { return os << "(" << r.name << "|" << r.bit << ")"; diff --git a/Applications/FileIO/Legacy/OGSIOVer4.cpp b/Applications/FileIO/Legacy/OGSIOVer4.cpp index 1fb9af6232e91169dff2c8936ccefdfb42f3572d..f23fa6baa8aabef56d025151a2d8107af6e37994 100644 --- a/Applications/FileIO/Legacy/OGSIOVer4.cpp +++ b/Applications/FileIO/Legacy/OGSIOVer4.cpp @@ -18,15 +18,13 @@ #include <limits> #include <sstream> -#include "BaseLib/Logging.h" - #include "Applications/FileIO/Legacy/createSurface.h" - #include "BaseLib/FileTools.h" +#include "BaseLib/Logging.h" #include "BaseLib/StringTools.h" - #include "GeoLib/AnalyticalGeometry.h" #include "GeoLib/GEOObjects.h" +#include "GeoLib/IO/TINInterface.h" #include "GeoLib/Point.h" #include "GeoLib/PointVec.h" #include "GeoLib/Polygon.h" @@ -35,12 +33,10 @@ #include "GeoLib/Surface.h" #include "GeoLib/Triangle.h" -#include "GeoLib/IO/TINInterface.h" - namespace FileIO { -namespace Legacy { - +namespace Legacy +{ /************************************************************************** GeoLib- Function: readPoints Aufgabe: Lesen der GLI Points und schreiben in einen Vector @@ -49,8 +45,9 @@ namespace Legacy { **************************************************************************/ /** reads the points inclusive their names from input stream in * using the OGS-4 file format */ -std::string readPoints(std::istream &in, std::vector<GeoLib::Point*>* pnt_vec, - bool &zero_based_indexing, std::map<std::string,std::size_t>* pnt_id_name_map) +std::string readPoints(std::istream& in, std::vector<GeoLib::Point*>* pnt_vec, + bool& zero_based_indexing, + std::map<std::string, std::size_t>* pnt_id_name_map) { std::string line; std::size_t cnt(0); @@ -67,7 +64,7 @@ std::string readPoints(std::istream &in, std::vector<GeoLib::Point*>* pnt_vec, double y; double z; inss >> id >> x >> y >> z; - if (!inss.fail ()) + if (!inss.fail()) { if (cnt == 0) { @@ -85,13 +82,13 @@ std::string readPoints(std::istream &in, std::vector<GeoLib::Point*>* pnt_vec, } // read name of point - std::size_t pos (line.find("$NAME")); - if (pos != std::string::npos) //OK + std::size_t pos(line.find("$NAME")); + if (pos != std::string::npos) // OK { - std::size_t end_pos ((line.substr (pos + 6)).find(' ')); + std::size_t end_pos((line.substr(pos + 6)).find(' ')); if (end_pos != std::string::npos) { - (*pnt_id_name_map)[line.substr (pos + 6, end_pos)] = id; + (*pnt_id_name_map)[line.substr(pos + 6, end_pos)] = id; } else { @@ -99,7 +96,7 @@ std::string readPoints(std::istream &in, std::vector<GeoLib::Point*>* pnt_vec, } } - std::size_t id_pos (line.find("$ID")); + std::size_t id_pos(line.find("$ID")); if (id_pos != std::string::npos) { WARN( @@ -116,18 +113,20 @@ std::string readPoints(std::istream &in, std::vector<GeoLib::Point*>* pnt_vec, } /** reads points from a vector */ -void readPolylinePointVector(const std::string &fname, +void readPolylinePointVector(const std::string& fname, std::vector<GeoLib::Point*>& pnt_vec, GeoLib::Polyline* ply, - const std::string &path, - std::vector<std::string> &errors) + const std::string& path, + std::vector<std::string>& errors) { // open file std::ifstream in(BaseLib::joinPaths(path, fname).c_str()); - if (!in) { + if (!in) + { WARN("readPolylinePointVector(): error opening stream from {:s}", fname); - errors.push_back ("[readPolylinePointVector] error opening stream from " + fname); + errors.push_back( + "[readPolylinePointVector] error opening stream from " + fname); return; } @@ -155,37 +154,38 @@ void readPolylinePointVector(const std::string &fname, 01/2010 TF cleaned method from unused variables **************************************************************************/ /** read a single Polyline from stream in into the ply_vec-vector */ -std::string readPolyline(std::istream &in, +std::string readPolyline(std::istream& in, std::vector<GeoLib::Polyline*>* ply_vec, - std::map<std::string,std::size_t>& ply_vec_names, - std::vector<GeoLib::Point*> & pnt_vec, + std::map<std::string, std::size_t>& ply_vec_names, + std::vector<GeoLib::Point*>& pnt_vec, bool zero_based_indexing, const std::vector<std::size_t>& pnt_id_map, - const std::string &path, - std::vector<std::string> &errors) + const std::string& path, + std::vector<std::string>& errors) { std::string line; std::string name_of_ply; auto* ply(new GeoLib::Polyline(pnt_vec)); - std::size_t type = 2; // need an initial value + std::size_t type = 2; // need an initial value // Loop over all phases or components - do { + do + { in >> line; if (line.find("$ID") != std::string::npos) { // subkeyword found CC in >> line; // read value } //.................................................................... - if (line.find("$NAME") != std::string::npos) // subkeyword found + if (line.find("$NAME") != std::string::npos) // subkeyword found { in >> line; - name_of_ply = line; // read value + name_of_ply = line; // read value } //.................................................................... - if (line.find("$TYPE") != std::string::npos) // subkeyword found + if (line.find("$TYPE") != std::string::npos) // subkeyword found { - in >> line; // read value + in >> line; // read value type = static_cast<std::size_t>(strtol(line.c_str(), nullptr, 0)); } //.................................................................... @@ -199,8 +199,8 @@ std::string readPolyline(std::istream &in, in >> line; // read value } //.................................................................... - if (line.find("$POINTS") != std::string::npos) // subkeyword found - { // read the point ids + if (line.find("$POINTS") != std::string::npos) // subkeyword found + { // read the point ids in >> line; if (type != 100) { @@ -230,7 +230,9 @@ std::string readPolyline(std::istream &in, } else { - WARN("readPolyline(): polyline is an arc *** reading not implemented"); + WARN( + "readPolyline(): polyline is an arc *** reading not " + "implemented"); errors.emplace_back( "[readPolyline] reading polyline as an arc is not " "implemented"); @@ -238,17 +240,19 @@ std::string readPolyline(std::istream &in, // empty line or the keyword or subkeyword or end of file } //.................................................................... - if (line.find("$POINT_VECTOR") != std::string::npos) // subkeyword found + if (line.find("$POINT_VECTOR") != + std::string::npos) // subkeyword found { - in >> line; // read file name + in >> line; // read file name line = BaseLib::joinPaths(path, line); readPolylinePointVector(line, pnt_vec, ply, path, errors); - } // subkeyword found + } // subkeyword found } while (line.find('#') == std::string::npos && !line.empty() && in); if (type != 100) { - ply_vec_names.insert (std::pair<std::string,std::size_t>(name_of_ply, ply_vec->size())); + ply_vec_names.insert( + std::pair<std::string, std::size_t>(name_of_ply, ply_vec->size())); ply_vec->push_back(ply); } @@ -261,20 +265,22 @@ std::string readPolyline(std::istream &in, Programming: 03/2004 CC Implementation 05/2004 CC Modification - 04/2005 CC Modification calculate the minimal distance between points reference for - mesh density of line element calculation - 07/2005 CC read ID of polyline - 08/2005 CC parameter - 01/2010 TF changed signature of function + 04/2005 CC Modification calculate the minimal distance between points +reference for mesh density of line element calculation 07/2005 CC read ID of +polyline 08/2005 CC parameter 01/2010 TF changed signature of function **************************************************************************/ /** reads polylines */ -std::string readPolylines(std::istream &in, std::vector<GeoLib::Polyline*>* ply_vec, - std::map<std::string,std::size_t>& ply_vec_names, - std::vector<GeoLib::Point*> & pnt_vec, - bool zero_based_indexing, const std::vector<std::size_t>& pnt_id_map, - const std::string &path, std::vector<std::string>& errors) +std::string readPolylines(std::istream& in, + std::vector<GeoLib::Polyline*>* ply_vec, + std::map<std::string, std::size_t>& ply_vec_names, + std::vector<GeoLib::Point*>& pnt_vec, + bool zero_based_indexing, + const std::vector<std::size_t>& pnt_id_map, + const std::string& path, + std::vector<std::string>& errors) { - if (!in) { + if (!in) + { WARN("readPolylines(): input stream error."); return std::string(""); } @@ -312,26 +318,27 @@ std::string readSurface(std::istream& in, std::string line; GeoLib::Surface* sfc(nullptr); - int type (-1); + int type(-1); std::string name; - std::size_t ply_id (std::numeric_limits<std::size_t>::max()); + std::size_t ply_id(std::numeric_limits<std::size_t>::max()); - do { + do + { in >> line; if (line.find("$ID") != std::string::npos) { // subkeyword found CC in >> line; // read value } //.................................................................... - if (line.find("$NAME") != std::string::npos) // subkeyword found + if (line.find("$NAME") != std::string::npos) // subkeyword found { - in >> line; // read value + in >> line; // read value name = line; } //.................................................................... - if (line.find("$TYPE") != std::string::npos) // subkeyword found + if (line.find("$TYPE") != std::string::npos) // subkeyword found { - in >> line; // read value + in >> line; // read value type = strtol(line.c_str(), nullptr, 0); } //.................................................................... @@ -340,11 +347,12 @@ std::string readSurface(std::istream& in, in >> line; // read value } //.................................................................... - if (line.find("$TIN") != std::string::npos) // subkeyword found + if (line.find("$TIN") != std::string::npos) // subkeyword found { - in >> line; // read value (file name) + in >> line; // read value (file name) std::string const file_name = BaseLib::joinPaths(path, line); - sfc = GeoLib::IO::TINInterface::readTIN(file_name, pnt_vec, &errors); + sfc = + GeoLib::IO::TINInterface::readTIN(file_name, pnt_vec, &errors); } //.................................................................... if (line.find("$MAT_GROUP") != std::string::npos) @@ -352,14 +360,15 @@ std::string readSurface(std::istream& in, in >> line; // read value } //.................................................................... - if (line.find("$POLYLINES") != std::string::npos) // subkeyword found - { // read the name of the polyline(s) + if (line.find("$POLYLINES") != std::string::npos) // subkeyword found + { // read the name of the polyline(s) in >> line; while (!in.eof() && !in.fail() && !line.empty() && (line.find('#') == std::string::npos) && (line.find('$') == std::string::npos)) { - // we did read the name of a polyline -> search the id for polyline + // we did read the name of a polyline -> search the id for + // polyline auto it(ply_vec_names.find(line)); if (it != ply_vec_names.end()) { @@ -370,19 +379,28 @@ std::string readSurface(std::istream& in, ply_id = ply_vec.size(); } - if (ply_id == ply_vec.size()) { + if (ply_id == ply_vec.size()) + { WARN("readSurface(): polyline for surface not found!"); errors.emplace_back( "[readSurface] polyline for surface not found!"); - } else { - if (type == 3) { - WARN("readSurface(): surface type 3: flat surface with any normal direction - reading not implemented."); + } + else + { + if (type == 3) + { + WARN( + "readSurface(): surface type 3: flat surface with " + "any normal direction - reading not implemented."); errors.emplace_back( "[readSurface] surface type 3: flat surface with " "any normal direction - reading not implemented"); } - if (type == 2) { - WARN("readSurface(): vertical surface (type 2) - reading not implemented"); + if (type == 2) + { + WARN( + "readSurface(): vertical surface (type 2) - " + "reading not implemented"); errors.emplace_back( "[readSurface] vertical surface (type 2) - reading " "not implemented"); @@ -403,16 +421,18 @@ std::string readSurface(std::istream& in, if (sfc) { // surface create by TIN - sfc_vec.push_back (sfc); + sfc_vec.push_back(sfc); } else { // surface created by polygon - if (ply_id != std::numeric_limits<std::size_t>::max() && ply_id != ply_vec.size()) + if (ply_id != std::numeric_limits<std::size_t>::max() && + ply_id != ply_vec.size()) { if (ply_vec[ply_id]->isClosed()) { - polygon_vec.push_back (new GeoLib::Polygon (*(ply_vec[ply_id]), true)); + polygon_vec.push_back( + new GeoLib::Polygon(*(ply_vec[ply_id]), true)); } else { @@ -442,8 +462,7 @@ std::string readSurfaces( const std::map<std::string, std::size_t>& ply_vec_names, GeoLib::PointVec& pnt_vec, const std::string& path, std::vector<std::string>& errors, GeoLib::GEOObjects& geo, - std::string const& unique_name, - std::string const& gmsh_path) + std::string const& unique_name, std::string const& gmsh_path) { if (!in.good()) { @@ -456,7 +475,7 @@ std::string readSurfaces( while (!in.eof() && !in.fail() && tag.find("#SURFACE") != std::string::npos) { - std::size_t n_polygons (polygon_vec.size()); + std::size_t n_polygons(polygon_vec.size()); tag = readSurface(in, polygon_vec, sfc_vec, sfc_names, ply_vec, ply_vec_names, pnt_vec, path, errors); if (n_polygons < polygon_vec.size()) @@ -492,7 +511,8 @@ bool readGLIFileV4(const std::string& fname, { INFO("GeoLib::readGLIFile(): open stream from file {:s}.", fname); std::ifstream in(fname.c_str()); - if (!in) { + if (!in) + { WARN("GeoLib::readGLIFile(): could not open file {:s}.", fname); errors.push_back("[readGLIFileV4] error opening stream from " + fname); return false; @@ -506,9 +526,8 @@ bool readGLIFileV4(const std::string& fname, } // read names of points into vector of strings - auto pnt_id_names_map = - std::unique_ptr<std::map<std::string, std::size_t>> - { new std::map<std::string, std::size_t> }; + auto pnt_id_names_map = std::unique_ptr<std::map<std::string, std::size_t>>{ + new std::map<std::string, std::size_t>}; bool zero_based_idx(true); auto pnt_vec = std::make_unique<std::vector<GeoLib::Point*>>(); @@ -529,16 +548,16 @@ bool readGLIFileV4(const std::string& fname, // read names of plys into temporary string-vec auto ply_names = std::make_unique<std::map<std::string, std::size_t>>(); auto ply_vec = std::make_unique<std::vector<GeoLib::Polyline*>>(); - GeoLib::PointVec & point_vec( + GeoLib::PointVec& point_vec( *const_cast<GeoLib::PointVec*>(geo.getPointVecObj(unique_name))); auto* geo_pnt_vec( const_cast<std::vector<GeoLib::Point*>*>(point_vec.getVector())); if (tag.find("#POLYLINE") != std::string::npos && in) { INFO("GeoLib::readGLIFile(): read polylines from stream."); - tag = readPolylines(in, ply_vec.get(), *ply_names, *geo_pnt_vec, - zero_based_idx, - geo.getPointVecObj(unique_name)->getIDMap(), path, errors); + tag = readPolylines( + in, ply_vec.get(), *ply_names, *geo_pnt_vec, zero_based_idx, + geo.getPointVecObj(unique_name)->getIDMap(), path, errors); INFO("GeoLib::readGLIFile(): \t ok, {:d} polylines read.", ply_vec->size()); } @@ -591,21 +610,32 @@ bool readGLIFileV4(const std::string& fname, return errors.empty(); } -std::size_t writeTINSurfaces(std::ofstream &os, GeoLib::SurfaceVec const* sfcs_vec, std::size_t sfc_count, std::string const& path) +std::size_t writeTINSurfaces(std::ofstream& os, + GeoLib::SurfaceVec const* sfcs_vec, + std::size_t sfc_count, std::string const& path) { - const std::vector<GeoLib::Surface*>* sfcs (sfcs_vec->getVector()); + const std::vector<GeoLib::Surface*>* sfcs(sfcs_vec->getVector()); for (auto sfc : *sfcs) { - os << "#SURFACE" << "\n"; + os << "#SURFACE" + << "\n"; std::string sfc_name; - if (sfcs_vec->getNameOfElementByID (sfc_count, sfc_name)) { - os << "\t$NAME " << "\n" << "\t\t" << sfc_name << "\n"; - } else { - os << "\t$NAME " << "\n" << "\t\t" << sfc_count << "\n"; - sfc_name = std::to_string (sfc_count); + if (sfcs_vec->getNameOfElementByID(sfc_count, sfc_name)) + { + os << "\t$NAME " + << "\n" + << "\t\t" << sfc_name << "\n"; + } + else + { + os << "\t$NAME " + << "\n" + << "\t\t" << sfc_count << "\n"; + sfc_name = std::to_string(sfc_count); } sfc_name += ".tin"; - os << "\t$TIN" << "\n"; + os << "\t$TIN" + << "\n"; os << "\t\t" << sfc_name << "\n"; // create tin file sfc_name = BaseLib::joinPaths(path, sfc_name); @@ -615,42 +645,50 @@ std::size_t writeTINSurfaces(std::ofstream &os, GeoLib::SurfaceVec const* sfcs_v return sfc_count; } -void writeGLIFileV4 (const std::string& fname, - const std::string& geo_name, - const GeoLib::GEOObjects& geo) +void writeGLIFileV4(const std::string& fname, + const std::string& geo_name, + const GeoLib::GEOObjects& geo) { GeoLib::PointVec const* const pnt_vec(geo.getPointVecObj(geo_name)); - std::vector<GeoLib::Point*> const* const pnts (pnt_vec->getVector()); - std::ofstream os (fname.c_str()); - if (pnts) { + std::vector<GeoLib::Point*> const* const pnts(pnt_vec->getVector()); + std::ofstream os(fname.c_str()); + if (pnts) + { const std::size_t n_pnts(pnts->size()); INFO("GeoLib::writeGLIFileV4(): writing {:d} points to file {:s}.", n_pnts, fname); - os << "#POINTS" << "\n"; + os << "#POINTS" + << "\n"; os.precision(std::numeric_limits<double>::digits10); - for (std::size_t k(0); k < n_pnts; k++) { + for (std::size_t k(0); k < n_pnts; k++) + { os << k << " " << *((*pnts)[k]); std::string const& pnt_name(pnt_vec->getItemNameByID(k)); - if (!pnt_name.empty()) { + if (!pnt_name.empty()) + { os << " $NAME " << pnt_name; } os << "\n"; } } - const GeoLib::PolylineVec* plys_vec (geo.getPolylineVecObj (geo_name)); + const GeoLib::PolylineVec* plys_vec(geo.getPolylineVecObj(geo_name)); if (plys_vec) { - const std::vector<GeoLib::Polyline*>* plys (plys_vec->getVector()); + const std::vector<GeoLib::Polyline*>* plys(plys_vec->getVector()); INFO("GeoLib::writeGLIFileV4(): {:d} polylines to file {:s}.", plys->size(), fname); for (auto ply : *plys) { - os << "#POLYLINE" << "\n"; + os << "#POLYLINE" + << "\n"; std::string polyline_name; plys_vec->getNameOfElement(ply, polyline_name); - os << " $NAME " << "\n" << " " << polyline_name << "\n"; - os << " $POINTS" << "\n"; + os << " $NAME " + << "\n" + << " " << polyline_name << "\n"; + os << " $POINTS" + << "\n"; for (std::size_t j(0); j < ply->getNumberOfPoints(); j++) { os << " " << ply->getPointID(j) << "\n"; @@ -659,48 +697,54 @@ void writeGLIFileV4 (const std::string& fname, } // writing surfaces as TIN files - const GeoLib::SurfaceVec* sfcs_vec (geo.getSurfaceVecObj (geo_name)); + const GeoLib::SurfaceVec* sfcs_vec(geo.getSurfaceVecObj(geo_name)); if (sfcs_vec) { writeTINSurfaces(os, sfcs_vec, 0, BaseLib::extractPath(fname)); } - os << "#STOP" << "\n"; - os.close (); + os << "#STOP" + << "\n"; + os.close(); } -void writeAllDataToGLIFileV4 (const std::string& fname, const GeoLib::GEOObjects& geo) +void writeAllDataToGLIFileV4(const std::string& fname, + const GeoLib::GEOObjects& geo) { auto const geo_names = geo.getGeometryNames(); // extract path for reading external files const std::string path = BaseLib::extractPath(fname); - std::ofstream os (fname.c_str()); + std::ofstream os(fname.c_str()); - std::size_t pnts_offset (0); + std::size_t pnts_offset(0); std::vector<std::size_t> pnts_id_offset; - pnts_id_offset.push_back (0); + pnts_id_offset.push_back(0); // writing all points - os << "#POINTS" << "\n"; - for (auto & geo_name : geo_names) + os << "#POINTS" + << "\n"; + for (auto& geo_name : geo_names) { os.precision(std::numeric_limits<double>::digits10); GeoLib::PointVec const* const pnt_vec(geo.getPointVecObj(geo_name)); - std::vector<GeoLib::Point*> const* const pnts (pnt_vec->getVector()); - if (pnts) { + std::vector<GeoLib::Point*> const* const pnts(pnt_vec->getVector()); + if (pnts) + { const std::size_t n_pnts(pnts->size()); - for (std::size_t k(0); k < n_pnts; k++) { + for (std::size_t k(0); k < n_pnts; k++) + { os << pnts_offset + k << " " << *((*pnts)[k]); std::string const& pnt_name(pnt_vec->getItemNameByID(k)); - if (! pnt_name.empty()) { + if (!pnt_name.empty()) + { os << "$NAME " << pnt_name; } os << "\n"; } pnts_offset += pnts->size(); - pnts_id_offset.push_back (pnts_offset); + pnts_id_offset.push_back(pnts_offset); } } @@ -708,11 +752,11 @@ void writeAllDataToGLIFileV4 (const std::string& fname, const GeoLib::GEOObjects // writing all stations std::vector<std::string> stn_names; - geo.getStationVectorNames (stn_names); - for (auto & stn_name : stn_names) + geo.getStationVectorNames(stn_names); + for (auto& stn_name : stn_names) { os.precision(std::numeric_limits<double>::digits10); - const std::vector<GeoLib::Point*>* pnts (geo.getStationVec(stn_name)); + const std::vector<GeoLib::Point*>* pnts(geo.getStationVec(stn_name)); if (pnts) { for (std::size_t k(0); k < pnts->size(); k++) @@ -722,20 +766,24 @@ void writeAllDataToGLIFileV4 (const std::string& fname, const GeoLib::GEOObjects << "\n"; } pnts_offset += pnts->size(); - pnts_id_offset.push_back (pnts_offset); + pnts_id_offset.push_back(pnts_offset); } } - std::size_t plys_cnt (0); + std::size_t plys_cnt(0); // writing all polylines for (std::size_t j(0); j < geo_names.size(); j++) { - const GeoLib::PolylineVec* plys_vec (geo.getPolylineVecObj (geo_names[j])); - if (plys_vec) { - const std::vector<GeoLib::Polyline*>* plys (plys_vec->getVector()); - for (auto ply : *plys) { - os << "#POLYLINE" << "\n"; + const GeoLib::PolylineVec* plys_vec( + geo.getPolylineVecObj(geo_names[j])); + if (plys_vec) + { + const std::vector<GeoLib::Polyline*>* plys(plys_vec->getVector()); + for (auto ply : *plys) + { + os << "#POLYLINE" + << "\n"; std::string ply_name; os << " $NAME\n"; if (plys_vec->getNameOfElementByID(plys_cnt, ply_name)) @@ -746,7 +794,8 @@ void writeAllDataToGLIFileV4 (const std::string& fname, const GeoLib::GEOObjects { os << " " << geo_names[j] << "-" << plys_cnt << "\n"; } - os << " $POINTS" << "\n"; + os << " $POINTS" + << "\n"; for (std::size_t l(0); l < ply->getNumberOfPoints(); l++) { os << " " << pnts_id_offset[j] + ply->getPointID(l) @@ -758,19 +807,20 @@ void writeAllDataToGLIFileV4 (const std::string& fname, const GeoLib::GEOObjects } // writing surfaces as TIN files - std::size_t sfcs_cnt (0); - for (auto & geo_name : geo_names) + std::size_t sfcs_cnt(0); + for (auto& geo_name : geo_names) { - const GeoLib::SurfaceVec* sfcs_vec (geo.getSurfaceVecObj (geo_name)); + const GeoLib::SurfaceVec* sfcs_vec(geo.getSurfaceVecObj(geo_name)); if (sfcs_vec) { sfcs_cnt += writeTINSurfaces(os, sfcs_vec, sfcs_cnt, path); } } - os << "#STOP" << "\n"; - os.close (); + os << "#STOP" + << "\n"; + os.close(); } } // namespace Legacy -} // end namespace FileIO +} // end namespace FileIO diff --git a/Applications/FileIO/Legacy/createSurface.cpp b/Applications/FileIO/Legacy/createSurface.cpp index 72cb2f6bf63d6f261b8868b04dad2d2df4c2f536..bd956f3026039d37ae4ecac31b04cdfd96a79016 100644 --- a/Applications/FileIO/Legacy/createSurface.cpp +++ b/Applications/FileIO/Legacy/createSurface.cpp @@ -8,28 +8,24 @@ * */ +#include "createSurface.h" + #include <cstdio> #include <list> #include <memory> -#include "BaseLib/Logging.h" - -#include "createSurface.h" -#include "filesystem.h" - #include "Applications/FileIO/Gmsh/GMSHInterface.h" - +#include "BaseLib/Logging.h" #include "BaseLib/StringTools.h" - #include "GeoLib/GEOObjects.h" #include "GeoLib/Point.h" #include "GeoLib/Polygon.h" #include "GeoLib/Polyline.h" #include "GeoLib/Surface.h" - #include "MeshLib/IO/readMeshFromFile.h" -#include "MeshLib/convertMeshToGeo.h" #include "MeshLib/Mesh.h" +#include "MeshLib/convertMeshToGeo.h" +#include "filesystem.h" namespace FileIO { @@ -84,9 +80,9 @@ bool createSurface(GeoLib::Polyline const& ply, BaseLib::IO::writeStringToFile(gmsh_io.writeToString(), geo_file); // Using GMSH's vtk output here so we don't have to deal with GMSH and it's // various file format versions here - std::string gmsh_command = - "\"" + gmsh_binary + "\" -2 -algo meshadapt -format vtk -o " - + msh_file.string() + " " + geo_file.string(); + std::string gmsh_command = "\"" + gmsh_binary + + "\" -2 -algo meshadapt -format vtk -o " + + msh_file.string() + " " + geo_file.string(); int const gmsh_return_value = std::system(gmsh_command.c_str()); if (gmsh_return_value != 0) diff --git a/Applications/FileIO/PetrelInterface.cpp b/Applications/FileIO/PetrelInterface.cpp index 071d45679aa9b02399d56f20258869ce48ee4b52..d4d4b70eecb416dd17f91a84736255d9b115206e 100644 --- a/Applications/FileIO/PetrelInterface.cpp +++ b/Applications/FileIO/PetrelInterface.cpp @@ -20,21 +20,24 @@ #include <fstream> #include "BaseLib/Logging.h" - #include "BaseLib/StringTools.h" -#include "GeoLib/StationBorehole.h" #include "GeoLib/GEOObjects.h" +#include "GeoLib/StationBorehole.h" namespace FileIO { -PetrelInterface::PetrelInterface(std::list<std::string> &sfc_fnames, - std::list<std::string> &well_path_fnames, - std::string &unique_model_name, GeoLib::GEOObjects* geo_obj) : - _unique_name(unique_model_name), pnt_vec(new std::vector<GeoLib::Point*>), - well_vec(new std::vector<GeoLib::Point*>), ply_vec(new std::vector<GeoLib::Polyline*>) +PetrelInterface::PetrelInterface(std::list<std::string>& sfc_fnames, + std::list<std::string>& well_path_fnames, + std::string& unique_model_name, + GeoLib::GEOObjects* geo_obj) + : _unique_name(unique_model_name), + pnt_vec(new std::vector<GeoLib::Point*>), + well_vec(new std::vector<GeoLib::Point*>), + ply_vec(new std::vector<GeoLib::Polyline*>) { - for (std::list<std::string>::const_iterator it(sfc_fnames.begin()); it - != sfc_fnames.end(); ++it) + for (std::list<std::string>::const_iterator it(sfc_fnames.begin()); + it != sfc_fnames.end(); + ++it) { INFO("PetrelInterface::PetrelInterface(): open surface file."); std::ifstream in((*it).c_str()); @@ -53,8 +56,9 @@ PetrelInterface::PetrelInterface(std::list<std::string> &sfc_fnames, } } - for (std::list<std::string>::const_iterator it(well_path_fnames.begin()); it - != well_path_fnames.end(); ++it) + for (std::list<std::string>::const_iterator it(well_path_fnames.begin()); + it != well_path_fnames.end(); + ++it) { INFO("PetrelInterface::PetrelInterface(): open well path file."); std::ifstream in((*it).c_str()); @@ -90,7 +94,7 @@ PetrelInterface::PetrelInterface(std::list<std::string> &sfc_fnames, } } -void PetrelInterface::readPetrelSurface(std::istream &in) +void PetrelInterface::readPetrelSurface(std::istream& in) { char buffer[MAX_COLS_PER_ROW]; in.getline(buffer, MAX_COLS_PER_ROW); @@ -138,7 +142,7 @@ void PetrelInterface::readPetrelSurface(std::istream &in) } } -void PetrelInterface::readPetrelWellTrace(std::istream &in) +void PetrelInterface::readPetrelWellTrace(std::istream& in) { char buffer[MAX_COLS_PER_ROW]; in.getline(buffer, MAX_COLS_PER_ROW); @@ -152,7 +156,8 @@ void PetrelInterface::readPetrelWellTrace(std::istream &in) line = buffer; std::list<std::string> str_list(BaseLib::splitString(line, ' ')); std::list<std::string>::const_iterator it(str_list.begin()); - while (it != str_list.end()) { + while (it != str_list.end()) + { INFO("PetrelInterface::readPetrelWellTrace(): well name: {:s}.", it->c_str()); ++it; @@ -163,7 +168,8 @@ void PetrelInterface::readPetrelWellTrace(std::istream &in) line = buffer; str_list = BaseLib::splitString(line, ' '); it = str_list.begin(); - while (it != str_list.end()) { + while (it != str_list.end()) + { INFO( "PetrelInterface::readPetrelWellTrace(): well head x coord: " "{:s}.", @@ -180,7 +186,8 @@ void PetrelInterface::readPetrelWellTrace(std::istream &in) line = buffer; str_list = BaseLib::splitString(line, ' '); it = str_list.begin(); - while (it != str_list.end()) { + while (it != str_list.end()) + { INFO( "PetrelInterface::readPetrelWellTrace(): well head y coord: " "{:s}.", @@ -196,7 +203,8 @@ void PetrelInterface::readPetrelWellTrace(std::istream &in) line = buffer; str_list = BaseLib::splitString(line, ' '); it = str_list.begin(); - while (it != str_list.end()) { + while (it != str_list.end()) + { INFO("PetrelInterface::readPetrelWellTrace(): well kb entry: {:s}.", it->c_str()); ++it; @@ -209,17 +217,18 @@ void PetrelInterface::readPetrelWellTrace(std::istream &in) well_head_x, well_head_y, well_kb); - well_vec->push_back(new GeoLib::StationBorehole(well_head_x, well_head_y, well_kb)); + well_vec->push_back( + new GeoLib::StationBorehole(well_head_x, well_head_y, well_kb)); // read well type in.getline(buffer, MAX_COLS_PER_ROW); -// std::string type(*((str_list.end())--)); + // std::string type(*((str_list.end())--)); readPetrelWellTraceData(in); } } -void PetrelInterface::readPetrelWellTraceData(std::istream &in) +void PetrelInterface::readPetrelWellTraceData(std::istream& in) { char buffer[MAX_COLS_PER_ROW]; in.getline(buffer, MAX_COLS_PER_ROW); @@ -237,7 +246,8 @@ void PetrelInterface::readPetrelWellTraceData(std::istream &in) // read column information std::list<std::string> str_list = BaseLib::splitString(line, ' '); auto it = str_list.begin(); - while (it != str_list.end()) { + while (it != str_list.end()) + { INFO( "PetrelInterface::readPetrelWellTraceData(): column information: " "{:s}.", @@ -266,12 +276,13 @@ void PetrelInterface::readPetrelWellTraceData(std::istream &in) stream >> md; stream >> x >> y >> z; // pnt_vec->push_back (new GeoLib::Point (x,y,z)); - static_cast<GeoLib::StationBorehole*> ((*well_vec)[well_vec->size() - 1])->addSoilLayer( - x, y, z, "unknown"); + static_cast<GeoLib::StationBorehole*>( + (*well_vec)[well_vec->size() - 1]) + ->addSoilLayer(x, y, z, "unknown"); stream >> tvd >> dx >> dy >> azim >> incl >> dls; } in.getline(buffer, MAX_COLS_PER_ROW); line = buffer; } } -} // end namespace FileIO +} // end namespace FileIO diff --git a/Applications/FileIO/SHPInterface.cpp b/Applications/FileIO/SHPInterface.cpp index 5aaa0d61fa785fe753c4e2faf6b112eaca120ebc..5eddb3d215add9600fee2afb0df4a52be485bcd5 100644 --- a/Applications/FileIO/SHPInterface.cpp +++ b/Applications/FileIO/SHPInterface.cpp @@ -17,25 +17,22 @@ #include "SHPInterface.h" -#include "BaseLib/Logging.h" - #include "Applications/FileIO/Legacy/createSurface.h" - +#include "BaseLib/Logging.h" #include "GeoLib/AnalyticalGeometry.h" #include "GeoLib/GEOObjects.h" -#include "GeoLib/Polyline.h" #include "GeoLib/Point.h" - -#include "MeshLib/Mesh.h" -#include "MeshLib/Node.h" +#include "GeoLib/Polyline.h" #include "MeshLib/Elements/Element.h" -#include "MeshLib/Elements/Tri.h" #include "MeshLib/Elements/Quad.h" +#include "MeshLib/Elements/Tri.h" +#include "MeshLib/Mesh.h" +#include "MeshLib/Node.h" namespace FileIO { - -bool SHPInterface::readSHPInfo(const std::string &filename, int &shapeType, int &numberOfEntities) +bool SHPInterface::readSHPInfo(const std::string& filename, int& shapeType, + int& numberOfEntities) { SHPHandle hSHP = SHPOpen(filename.c_str(), "rb"); if (!hSHP) @@ -46,8 +43,9 @@ bool SHPInterface::readSHPInfo(const std::string &filename, int &shapeType, int double padfMinBound[4]; double padfMaxBound[4]; - // The SHPGetInfo() function retrieves various information about shapefile as a whole. - // The bounds are read from the file header, and may be inaccurate if the file was improperly generated. + // The SHPGetInfo() function retrieves various information about shapefile + // as a whole. The bounds are read from the file header, and may be + // inaccurate if the file was improperly generated. SHPGetInfo(hSHP, &numberOfEntities, &shapeType, padfMinBound, padfMaxBound); SHPClose(hSHP); @@ -87,13 +85,16 @@ void SHPInterface::readSHPFile(const std::string& filename, OGSType choice, } } -void SHPInterface::readPoints(const SHPHandle &hSHP, int numberOfElements, std::string listName) +void SHPInterface::readPoints(const SHPHandle& hSHP, int numberOfElements, + std::string listName) { - if (numberOfElements > 0) { + if (numberOfElements > 0) + { auto points = std::make_unique<std::vector<GeoLib::Point*>>(); SHPObject* hSHPObject; - for (int i = 0; i < numberOfElements; i++) { + for (int i = 0; i < numberOfElements; i++) + { hSHPObject = SHPReadObject(hSHP, i); auto* pnt = @@ -103,32 +104,37 @@ void SHPInterface::readPoints(const SHPHandle &hSHP, int numberOfElements, std:: } _geoObjects.addPointVec(std::move(points), listName); - SHPDestroyObject(hSHPObject); // de-allocate SHPObject + SHPDestroyObject(hSHPObject); // de-allocate SHPObject } } -void SHPInterface::readStations(const SHPHandle &hSHP, int numberOfElements, std::string listName) +void SHPInterface::readStations(const SHPHandle& hSHP, int numberOfElements, + std::string listName) { - if (numberOfElements > 0) { + if (numberOfElements > 0) + { auto stations = std::make_unique<std::vector<GeoLib::Point*>>(); stations->reserve(numberOfElements); SHPObject* hSHPObject; - for (int i = 0; i < numberOfElements; i++) { + for (int i = 0; i < numberOfElements; i++) + { hSHPObject = SHPReadObject(hSHP, i); - GeoLib::Station* stn = GeoLib::Station::createStation(std::to_string(i), - *(hSHPObject->padfX), - *(hSHPObject->padfY), - *(hSHPObject->padfZ)); + GeoLib::Station* stn = + GeoLib::Station::createStation(std::to_string(i), + *(hSHPObject->padfX), + *(hSHPObject->padfY), + *(hSHPObject->padfZ)); stations->push_back(stn); } _geoObjects.addStationVec(std::move(stations), listName); - SHPDestroyObject(hSHPObject); // de-allocate SHPObject + SHPDestroyObject(hSHPObject); // de-allocate SHPObject } } -void SHPInterface::readPolylines(const SHPHandle &hSHP, int numberOfElements, std::string listName) +void SHPInterface::readPolylines(const SHPHandle& hSHP, int numberOfElements, + std::string listName) { if (numberOfElements <= 0) { @@ -139,24 +145,29 @@ void SHPInterface::readPolylines(const SHPHandle &hSHP, int numberOfElements, st std::size_t pnt_id(0); // for each polyline - for (int i = 0; i < numberOfElements; ++i) { - SHPObject *hSHPObject = SHPReadObject(hSHP, i); + for (int i = 0; i < numberOfElements; ++i) + { + SHPObject* hSHPObject = SHPReadObject(hSHP, i); int const noOfPoints = hSHPObject->nVertices; int const noOfParts = hSHPObject->nParts; - for (int p = 0; p < noOfParts; ++p) { + for (int p = 0; p < noOfParts; ++p) + { int const firstPnt = *(hSHPObject->panPartStart + p); - int const lastPnt = (p<(noOfParts - 1)) ? - *(hSHPObject->panPartStart + p + 1) : noOfPoints; + int const lastPnt = (p < (noOfParts - 1)) + ? *(hSHPObject->panPartStart + p + 1) + : noOfPoints; // for each point in that polyline - for (int j = firstPnt; j < lastPnt; ++j) { - pnts->push_back(new GeoLib::Point(*(hSHPObject->padfX+j), - *(hSHPObject->padfY+j), *(hSHPObject->padfZ+j), pnt_id)); + for (int j = firstPnt; j < lastPnt; ++j) + { + pnts->push_back(new GeoLib::Point( + *(hSHPObject->padfX + j), *(hSHPObject->padfY + j), + *(hSHPObject->padfZ + j), pnt_id)); pnt_id++; } } - SHPDestroyObject(hSHPObject); // de-allocate SHPObject + SHPDestroyObject(hSHPObject); // de-allocate SHPObject } _geoObjects.addPointVec(std::move(pnts), listName); @@ -164,27 +175,31 @@ void SHPInterface::readPolylines(const SHPHandle &hSHP, int numberOfElements, st std::vector<std::size_t> const& pnt_id_map(points.getIDMap()); pnt_id = 0; - for (int i = 0; i < numberOfElements; ++i) { + for (int i = 0; i < numberOfElements; ++i) + { SHPObject* hSHPObject = SHPReadObject(hSHP, i); int const noOfPoints = hSHPObject->nVertices; int const noOfParts = hSHPObject->nParts; - for (int p = 0; p < noOfParts; ++p) { + for (int p = 0; p < noOfParts; ++p) + { int const firstPnt = *(hSHPObject->panPartStart + p); - int const lastPnt = (p<(noOfParts - 1)) ? - *(hSHPObject->panPartStart + p + 1) : noOfPoints; + int const lastPnt = (p < (noOfParts - 1)) + ? *(hSHPObject->panPartStart + p + 1) + : noOfPoints; auto* line = new GeoLib::Polyline(*points.getVector()); // create polyline - for (int j = firstPnt; j < lastPnt; ++j) { + for (int j = firstPnt; j < lastPnt; ++j) + { line->addPoint(pnt_id_map[pnt_id]); pnt_id++; } // add polyline to polyline vector lines->push_back(line); } - SHPDestroyObject(hSHPObject); // de-allocate SHPObject + SHPDestroyObject(hSHPObject); // de-allocate SHPObject } _geoObjects.addPolylineVec(std::move(lines), listName); } @@ -213,7 +228,8 @@ void SHPInterface::readPolygons(const SHPHandle& hSHP, int numberOfElements, } } -bool SHPInterface::write2dMeshToSHP(const std::string &file_name, const MeshLib::Mesh &mesh) +bool SHPInterface::write2dMeshToSHP(const std::string& file_name, + const MeshLib::Mesh& mesh) { if (mesh.getDimension() != 2) { @@ -233,7 +249,7 @@ bool SHPInterface::write2dMeshToSHP(const std::string &file_name, const MeshLib: // integer values. The exponent controls maximum number of elements and // the maximum number of digits written in the DBF file. std::size_t const max_exp = 8; - if (n_elements >= std::pow(10,max_exp)) + if (n_elements >= std::pow(10, max_exp)) { ERR("SHPInterface::write2dMeshToSHP(): Mesh contains too many elements " "for currently implemented DBF-boundaries."); @@ -242,7 +258,8 @@ bool SHPInterface::write2dMeshToSHP(const std::string &file_name, const MeshLib: SHPHandle hSHP = SHPCreate(file_name.c_str(), SHPT_POLYGON); DBFHandle hDBF = DBFCreate(file_name.c_str()); - int const elem_id_field = DBFAddField(hDBF, "Elem_ID", FTInteger, max_exp, 0); + int const elem_id_field = + DBFAddField(hDBF, "Elem_ID", FTInteger, max_exp, 0); // Writing mesh elements to shape file std::size_t shp_record(0); @@ -258,7 +275,8 @@ bool SHPInterface::write2dMeshToSHP(const std::string &file_name, const MeshLib: SHPDestroyObject(object); // write element ID to DBF-file - DBFWriteIntegerAttribute(hDBF, shp_record, elem_id_field, e->getID()); + DBFWriteIntegerAttribute(hDBF, shp_record, elem_id_field, + e->getID()); shp_record++; } } @@ -273,7 +291,8 @@ bool SHPInterface::write2dMeshToSHP(const std::string &file_name, const MeshLib: int const field = DBFAddField(hDBF, name.c_str(), FTInteger, 16, 0); for (int i = 0; i < n_recs; ++i) { - std::size_t const elem_idx = DBFReadIntegerAttribute(hDBF, i, elem_id_field); + std::size_t const elem_idx = + DBFReadIntegerAttribute(hDBF, i, elem_id_field); DBFWriteIntegerAttribute(hDBF, i, field, (*p)[elem_idx]); } } @@ -283,7 +302,8 @@ bool SHPInterface::write2dMeshToSHP(const std::string &file_name, const MeshLib: int const field = DBFAddField(hDBF, name.c_str(), FTDouble, 33, 16); for (int i = 0; i < n_recs; ++i) { - std::size_t const elem_idx = DBFReadIntegerAttribute(hDBF, i, elem_id_field); + std::size_t const elem_idx = + DBFReadIntegerAttribute(hDBF, i, elem_id_field); DBFWriteDoubleAttribute(hDBF, i, field, (*p)[elem_idx]); } } diff --git a/Applications/FileIO/SWMM/SWMMInterface.cpp b/Applications/FileIO/SWMM/SWMMInterface.cpp index 43029fc13233aec33dd5558ce77f2cfdca75a188..55b36b8ac25ad0365c953ccc64b250a36898cbea 100644 --- a/Applications/FileIO/SWMM/SWMMInterface.cpp +++ b/Applications/FileIO/SWMM/SWMMInterface.cpp @@ -8,6 +8,8 @@ #include "SwmmInterface.h" +#include <swmm5_iface.h> + #include <boost/algorithm/string/predicate.hpp> #include <cctype> #include <fstream> @@ -25,14 +27,11 @@ #include "MeshLib/Mesh.h" #include "MeshLib/Node.h" #include "MeshLib/Properties.h" -#include <swmm5_iface.h> namespace FileIO { - /// Variables that always exist for subcatchments. There might be more. -const std::array<std::string,9> subcatchment_vars = -{ +const std::array<std::string, 9> subcatchment_vars = { "rainfall", "snow depth", "evaporation loss", @@ -41,35 +40,27 @@ const std::array<std::string,9> subcatchment_vars = "groundwater outflow", "groundwater head", "moisture content", - "concentration of pollutant" -}; + "concentration of pollutant"}; /// Variables that always exist for nodes. There might be more. -const std::array<std::string,7> node_vars = -{ - "water depth", - "hydraulic head", - "volume of stored water", - "lateral inflow", - "total inflow", - "flow lost to flooding", - "concentration of pollutant" -}; +const std::array<std::string, 7> node_vars = {"water depth", + "hydraulic head", + "volume of stored water", + "lateral inflow", + "total inflow", + "flow lost to flooding", + "concentration of pollutant"}; /// Variables that always exist for links. There might be more. -const std::array<std::string,6> link_vars = -{ - "flow rate", - "flow depth", - "flow velocity", - "flow volume", - "fraction conduit/non-conduit", - "concentration of pollutant" -}; +const std::array<std::string, 6> link_vars = {"flow rate", + "flow depth", + "flow velocity", + "flow volume", + "fraction conduit/non-conduit", + "concentration of pollutant"}; /// All variables that exist for the system. -const std::array<std::string,15> system_vars = -{ +const std::array<std::string, 15> system_vars = { "air temperature", "rainfall", "snow depth", @@ -84,41 +75,43 @@ const std::array<std::string,15> system_vars = "flow leaving through outfalls", "volume of stored water", "actual evaporation rate", - "potential evaporation rate" -}; + "potential evaporation rate"}; -/// Number of base variables for the four object types (subcatchments/nodes/links/system). -std::array<std::size_t,4> const n_obj_params = { 8, 6, 5, 15 }; +/// Number of base variables for the four object types +/// (subcatchments/nodes/links/system). +std::array<std::size_t, 4> const n_obj_params = {8, 6, 5, 15}; -std::unique_ptr<SwmmInterface> SwmmInterface::create(std::string const& file_name) +std::unique_ptr<SwmmInterface> SwmmInterface::create( + std::string const& file_name) { - //The input/output methods take a base name and check if the corresponding i/o file for that base name exists. - //This check takes any swmm project file, i.e. [base name].[extension] which needs to be at least 5 chars - //because the extension is always 3 chars. + // The input/output methods take a base name and check if the corresponding + // i/o file for that base name exists. This check takes any swmm project + // file, i.e. [base name].[extension] which needs to be at least 5 chars + // because the extension is always 3 chars. if (file_name.length() < 5) return nullptr; if (!SwmmInterface::isSwmmInputFile(file_name)) return nullptr; - std::string const base_name (file_name.substr(0, file_name.length() - 4)); + std::string const base_name(file_name.substr(0, file_name.length() - 4)); SwmmInterface* swmm = new SwmmInterface(base_name); if (swmm->readSwmmInputToLineMesh()) return std::unique_ptr<SwmmInterface>(swmm); - ERR ("Error creating mesh from SWMM file."); + ERR("Error creating mesh from SWMM file."); delete swmm; return nullptr; } SwmmInterface::SwmmInterface(std::string const& swmm_base_name) -: _base_name (swmm_base_name), _mesh(nullptr) + : _base_name(swmm_base_name), _mesh(nullptr) { } SwmmInterface::~SwmmInterface() { - for (Subcatchment& sc : _subcatchments) + for (Subcatchment& sc : _subcatchments) delete sc.outline; for (GeoLib::Point* pnt : _subcatchment_points) @@ -133,7 +126,7 @@ bool SwmmInterface::isSwmmInputFile(std::string const& inp_file_name) return false; } - std::ifstream in ( inp_file_name.c_str() ); + std::ifstream in(inp_file_name.c_str()); if (!in.is_open()) { ERR("SWMMInterface: Could not open input file {:s}.", inp_file_name); @@ -141,7 +134,7 @@ bool SwmmInterface::isSwmmInputFile(std::string const& inp_file_name) } std::string line; - bool header_found (false); + bool header_found(false); std::size_t pos_end(0); while (!header_found) { @@ -152,7 +145,7 @@ bool SwmmInterface::isSwmmInputFile(std::string const& inp_file_name) pos_end = line.find_first_of(" \n", pos_beg); // skip empty or comment lines at the beginning of the file - if (line.empty() || pos_beg==pos_end || isCommentLine(line)) + if (line.empty() || pos_beg == pos_end || isCommentLine(line)) continue; if (line == "[TITLE]") @@ -171,16 +164,17 @@ bool SwmmInterface::isSwmmInputFile(std::string const& inp_file_name) bool SwmmInterface::existsSwmmOutputFile() const { - std::string const outfile (_base_name + ".out"); + std::string const outfile(_base_name + ".out"); if (OpenSwmmOutFile(const_cast<char*>(outfile.c_str())) != 0) return false; return true; } template <typename T> -bool SwmmInterface::readCoordinates(std::ifstream &in, std::vector<T*> &points, std::vector<std::string> &names) +bool SwmmInterface::readCoordinates(std::ifstream& in, std::vector<T*>& points, + std::vector<std::string>& names) { - std::size_t id (points.size()); + std::size_t id(points.size()); std::string line; while (std::getline(in, line)) @@ -191,10 +185,10 @@ bool SwmmInterface::readCoordinates(std::ifstream &in, std::vector<T*> &points, if (isCommentLine(line)) continue; - std::vector<std::string> split_str (BaseLib::splitString(line)); + std::vector<std::string> split_str(BaseLib::splitString(line)); if (split_str.size() != 3) { - ERR ("Format not recognised."); + ERR("Format not recognised."); return false; } names.push_back(split_str[0]); @@ -208,15 +202,17 @@ bool SwmmInterface::readCoordinates(std::ifstream &in, std::vector<T*> &points, return true; } -bool SwmmInterface::readPolygons(std::ifstream &in, std::vector<GeoLib::Polyline*> &lines, - std::vector<std::string> &ply_names, std::vector<GeoLib::Point*> &points, - std::vector<std::string> &pnt_names) +bool SwmmInterface::readPolygons(std::ifstream& in, + std::vector<GeoLib::Polyline*>& lines, + std::vector<std::string>& ply_names, + std::vector<GeoLib::Point*>& points, + std::vector<std::string>& pnt_names) { - bool finished (false); - std::size_t id (points.size()); + bool finished(false); + std::size_t id(points.size()); std::string line; std::string polygon_name(""); - GeoLib::Polyline* p (nullptr); + GeoLib::Polyline* p(nullptr); while (std::getline(in, line)) { if (isSectionFinished(line)) @@ -225,10 +221,10 @@ bool SwmmInterface::readPolygons(std::ifstream &in, std::vector<GeoLib::Polyline if (isCommentLine(line)) continue; - std::vector<std::string> split_str (BaseLib::splitString(line)); + std::vector<std::string> split_str(BaseLib::splitString(line)); if (split_str.size() != 3) { - ERR ("Polygon format not recognised."); + ERR("Polygon format not recognised."); delete p; return false; } @@ -250,7 +246,7 @@ bool SwmmInterface::readPolygons(std::ifstream &in, std::vector<GeoLib::Polyline double const x = BaseLib::str2number<double>(split_str[1]); double const y = BaseLib::str2number<double>(split_str[2]); points.push_back(new GeoLib::Point(x, y, 0, id)); - p->addPoint(points.size()-1); + p->addPoint(points.size() - 1); pnt_names.push_back(""); id++; } @@ -265,9 +261,9 @@ bool SwmmInterface::readPolygons(std::ifstream &in, std::vector<GeoLib::Polyline return true; } -bool SwmmInterface::addPointElevation(std::ifstream &in, - std::vector<GeoLib::Point*> &points, std::map<std::string, - std::size_t> const& name_id_map) +bool SwmmInterface::addPointElevation( + std::ifstream& in, std::vector<GeoLib::Point*>& points, + std::map<std::string, std::size_t> const& name_id_map) { std::string line; while (std::getline(in, line)) @@ -278,14 +274,14 @@ bool SwmmInterface::addPointElevation(std::ifstream &in, if (isCommentLine(line)) continue; - std::vector<std::string> const split_str (BaseLib::splitString(line)); + std::vector<std::string> const split_str(BaseLib::splitString(line)); // Junctions = 6, Outfalls = 4, Storage = 8 if (split_str.size() < 4) { - ERR ("Format not recognised."); + ERR("Format not recognised."); return false; } - std::string const current_name (split_str[0]); + std::string const current_name(split_str[0]); auto const it = name_id_map.find(current_name); if (it == name_id_map.end()) { @@ -300,9 +296,11 @@ bool SwmmInterface::addPointElevation(std::ifstream &in, return true; } -bool SwmmInterface::readLinksAsPolylines(std::ifstream &in, - std::vector<GeoLib::Polyline*> &lines, std::vector<std::string> &line_names, - std::vector<GeoLib::Point*> const& points, std::map<std::string, std::size_t> const& point_names) +bool SwmmInterface::readLinksAsPolylines( + std::ifstream& in, std::vector<GeoLib::Polyline*>& lines, + std::vector<std::string>& line_names, + std::vector<GeoLib::Point*> const& points, + std::map<std::string, std::size_t> const& point_names) { std::string line; while (std::getline(in, line)) @@ -313,15 +311,15 @@ bool SwmmInterface::readLinksAsPolylines(std::ifstream &in, if (isCommentLine(line)) continue; - std::vector<std::string> const split_str (BaseLib::splitString(line)); + std::vector<std::string> const split_str(BaseLib::splitString(line)); // Conduits = 9, Pumps = 7, Weirs = 8 if (split_str.size() < 7) { - ERR ("Conduit format not recognised."); + ERR("Conduit format not recognised."); return false; } - std::string const inlet (split_str[1]); + std::string const inlet(split_str[1]); auto const i_it = point_names.find(inlet); if (i_it == point_names.end()) { @@ -331,7 +329,7 @@ bool SwmmInterface::readLinksAsPolylines(std::ifstream &in, return false; } - std::string const outlet (split_str[2]); + std::string const outlet(split_str[2]); auto const o_it = point_names.find(outlet); if (o_it == point_names.end()) { @@ -341,7 +339,7 @@ bool SwmmInterface::readLinksAsPolylines(std::ifstream &in, return false; } GeoLib::Polyline* ply = new GeoLib::Polyline(points); - std::size_t a (i_it->second); + std::size_t a(i_it->second); ply->addPoint(i_it->second); ply->addPoint(o_it->second); lines.push_back(ply); @@ -351,12 +349,13 @@ bool SwmmInterface::readLinksAsPolylines(std::ifstream &in, } bool SwmmInterface::convertSwmmInputToGeometry(std::string const& inp_file_name, - GeoLib::GEOObjects &geo_objects, bool add_subcatchments) + GeoLib::GEOObjects& geo_objects, + bool add_subcatchments) { if (!isSwmmInputFile(inp_file_name)) return false; - std::ifstream in ( inp_file_name.c_str() ); + std::ifstream in(inp_file_name.c_str()); if (!in.is_open()) { ERR("SWMMInterface: Could not open input file {:s}.", inp_file_name); @@ -368,7 +367,8 @@ bool SwmmInterface::convertSwmmInputToGeometry(std::string const& inp_file_name, std::vector<std::string> pnt_names; std::vector<std::string> line_names; - std::string geo_name = BaseLib::extractBaseNameWithoutExtension(inp_file_name); + std::string geo_name = + BaseLib::extractBaseNameWithoutExtension(inp_file_name); std::string line; while (std::getline(in, line)) { @@ -393,7 +393,7 @@ bool SwmmInterface::convertSwmmInputToGeometry(std::string const& inp_file_name, if (points->empty()) { - ERR ("No points found in file"); + ERR("No points found in file"); return false; } if (points->size() != pnt_names.size()) @@ -421,7 +421,7 @@ bool SwmmInterface::convertSwmmInputToGeometry(std::string const& inp_file_name, { if (line == "[JUNCTIONS]") { - INFO ("Reading point elevation..."); + INFO("Reading point elevation..."); if (!addPointElevation(in, *points, *name_id_map)) { BaseLib::cleanupVectorElements(*points, *lines); @@ -430,8 +430,9 @@ bool SwmmInterface::convertSwmmInputToGeometry(std::string const& inp_file_name, } if (line == "[CONDUITS]") { - INFO ("Reading conduits..."); - if (!readLinksAsPolylines(in, *lines, line_names, *points, *name_id_map)) + INFO("Reading conduits..."); + if (!readLinksAsPolylines(in, *lines, line_names, *points, + *name_id_map)) { BaseLib::cleanupVectorElements(*points, *lines); return false; @@ -439,8 +440,9 @@ bool SwmmInterface::convertSwmmInputToGeometry(std::string const& inp_file_name, } else if (line == "[PUMPS]") { - INFO ("Reading pumps..."); - if (!readLinksAsPolylines(in, *lines, line_names, *points, *name_id_map)) + INFO("Reading pumps..."); + if (!readLinksAsPolylines(in, *lines, line_names, *points, + *name_id_map)) { BaseLib::cleanupVectorElements(*points, *lines); return false; @@ -448,8 +450,9 @@ bool SwmmInterface::convertSwmmInputToGeometry(std::string const& inp_file_name, } else if (line == "[WEIRS]") { - INFO ("Reading weirs..."); - if (!readLinksAsPolylines(in, *lines, line_names, *points, *name_id_map)) + INFO("Reading weirs..."); + if (!readLinksAsPolylines(in, *lines, line_names, *points, + *name_id_map)) { BaseLib::cleanupVectorElements(*points, *lines); return false; @@ -457,12 +460,13 @@ bool SwmmInterface::convertSwmmInputToGeometry(std::string const& inp_file_name, } } - geo_objects.addPointVec(std::move(points), geo_name, std::move(name_id_map)); + geo_objects.addPointVec(std::move(points), geo_name, + std::move(name_id_map)); if (!lines->empty()) { if (lines->size() != line_names.size()) { - ERR ("Length of line vector and line name vector do not match."); + ERR("Length of line vector and line name vector do not match."); geo_objects.removePointVec(geo_name); for (auto ply : *lines) delete ply; @@ -477,7 +481,8 @@ bool SwmmInterface::convertSwmmInputToGeometry(std::string const& inp_file_name, line_id_map->insert(std::make_pair(line_names[i], i)); } } - std::vector<std::size_t> const& pnt_id_map (geo_objects.getPointVecObj(geo_name)->getIDMap()); + std::vector<std::size_t> const& pnt_id_map( + geo_objects.getPointVecObj(geo_name)->getIDMap()); for (GeoLib::Polyline* polyline : *lines) { for (std::size_t i = 0; i < polyline->getNumberOfPoints(); ++i) @@ -503,8 +508,10 @@ bool SwmmInterface::convertSwmmInputToGeometry(std::string const& inp_file_name, return true; } -bool SwmmInterface::readNodeData(std::ifstream &in, std::vector<MeshLib::Node*> &nodes, std::map<std::string, - std::size_t> const& name_id_map, std::vector<double> &max_depth, bool read_max_depth) +bool SwmmInterface::readNodeData( + std::ifstream& in, std::vector<MeshLib::Node*>& nodes, + std::map<std::string, std::size_t> const& name_id_map, + std::vector<double>& max_depth, bool read_max_depth) { std::string line; while (std::getline(in, line)) @@ -515,14 +522,14 @@ bool SwmmInterface::readNodeData(std::ifstream &in, std::vector<MeshLib::Node*> if (isCommentLine(line)) continue; - std::vector<std::string> const split_str (BaseLib::splitString(line)); + std::vector<std::string> const split_str(BaseLib::splitString(line)); // Junctions = 6, Outfalls = 4, Storage = 8 if (split_str.size() < 3) { - ERR ("Format not recognised."); + ERR("Format not recognised."); return false; } - std::string const current_name (split_str[0]); + std::string const current_name(split_str[0]); auto const it = name_id_map.find(current_name); if (it == name_id_map.end()) { @@ -542,8 +549,10 @@ bool SwmmInterface::readNodeData(std::ifstream &in, std::vector<MeshLib::Node*> return true; } -bool SwmmInterface::readLineElements(std::ifstream &in, std::vector<MeshLib::Element*> &elements, - std::vector<MeshLib::Node*> const& nodes, std::map<std::string, std::size_t> const& name_id_map) +bool SwmmInterface::readLineElements( + std::ifstream& in, std::vector<MeshLib::Element*>& elements, + std::vector<MeshLib::Node*> const& nodes, + std::map<std::string, std::size_t> const& name_id_map) { std::string line; while (std::getline(in, line)) @@ -554,15 +563,15 @@ bool SwmmInterface::readLineElements(std::ifstream &in, std::vector<MeshLib::Ele if (isCommentLine(line)) continue; - std::vector<std::string> const split_str (BaseLib::splitString(line)); + std::vector<std::string> const split_str(BaseLib::splitString(line)); // Conduits = 9, Pumps = 7, Weirs = 8 if (split_str.size() < 7) { - ERR ("Conduit format not recognised."); + ERR("Conduit format not recognised."); return false; } - std::string const inlet (split_str[1]); + std::string const inlet(split_str[1]); auto const i_it = name_id_map.find(inlet); if (i_it == name_id_map.end()) { @@ -572,7 +581,7 @@ bool SwmmInterface::readLineElements(std::ifstream &in, std::vector<MeshLib::Ele return false; } - std::string const outlet (split_str[2]); + std::string const outlet(split_str[2]); auto const o_it = name_id_map.find(outlet); if (o_it == name_id_map.end()) { @@ -582,14 +591,16 @@ bool SwmmInterface::readLineElements(std::ifstream &in, std::vector<MeshLib::Ele return false; } - std::array<MeshLib::Node*, 2> const line_nodes = { nodes[i_it->second], nodes[o_it->second] }; + std::array<MeshLib::Node*, 2> const line_nodes = {nodes[i_it->second], + nodes[o_it->second]}; elements.push_back(new MeshLib::Line(line_nodes)); _id_linkname_map.push_back(split_str[0]); } return true; } -bool SwmmInterface::readSubcatchments(std::ifstream &in, std::map< std::string, std::size_t> const& name_id_map) +bool SwmmInterface::readSubcatchments( + std::ifstream& in, std::map<std::string, std::size_t> const& name_id_map) { std::string line; while (getline(in, line)) @@ -600,18 +611,18 @@ bool SwmmInterface::readSubcatchments(std::ifstream &in, std::map< std::string, if (isCommentLine(line)) continue; - std::vector<std::string> const split_str (BaseLib::splitString(line)); + std::vector<std::string> const split_str(BaseLib::splitString(line)); if (split_str.size() < 8) { - ERR ("Subcatchment format not recognised."); + ERR("Subcatchment format not recognised."); return false; } Subcatchment sc; sc.name = split_str[0]; sc.rain_gauge = std::numeric_limits<std::size_t>::max(); - std::size_t const n_gauges (_rain_gauges.size()); - for (std::size_t i=0; i<n_gauges; ++i) + std::size_t const n_gauges(_rain_gauges.size()); + for (std::size_t i = 0; i < n_gauges; ++i) { if (_rain_gauges[i].first.getName() == split_str[1]) { @@ -643,15 +654,15 @@ bool SwmmInterface::readSwmmInputToLineMesh() { if (_mesh != nullptr) { - ERR ("Mesh already exists."); + ERR("Mesh already exists."); return false; } - std::string const inp_file_name (_base_name + ".inp"); + std::string const inp_file_name(_base_name + ".inp"); if (!isSwmmInputFile(inp_file_name)) return false; - std::ifstream in ( inp_file_name.c_str() ); + std::ifstream in(inp_file_name.c_str()); if (!in.is_open()) { ERR("SWMMInterface: Could not open input file {:s}.", inp_file_name); @@ -659,13 +670,13 @@ bool SwmmInterface::readSwmmInputToLineMesh() } _id_nodename_map.clear(); - std::vector< MeshLib::Node* > nodes; + std::vector<MeshLib::Node*> nodes; std::string line; - while ( getline(in, line) ) + while (getline(in, line)) { if (line == "[COORDINATES]") { - INFO ("Reading coordinates..."); + INFO("Reading coordinates..."); if (!readCoordinates<MeshLib::Node>(in, nodes, _id_nodename_map)) return false; } @@ -679,15 +690,16 @@ bool SwmmInterface::readSwmmInputToLineMesh() */ else if (line == "[SYMBOLS]") { - INFO ("Reading symbols..."); + INFO("Reading symbols..."); std::vector<GeoLib::Point*> points; std::vector<std::string> names; - if (!readCoordinates(in,points, names)) + if (!readCoordinates(in, points, names)) return false; - for (std::size_t i=0; i<points.size(); ++i) + for (std::size_t i = 0; i < points.size(); ++i) { - GeoLib::Station stn (points[i], names[i]); - _rain_gauges.push_back(std::pair<GeoLib::Station, std::string>(stn, "")); + GeoLib::Station stn(points[i], names[i]); + _rain_gauges.push_back( + std::pair<GeoLib::Station, std::string>(stn, "")); } } } @@ -697,18 +709,18 @@ bool SwmmInterface::readSwmmInputToLineMesh() // After end of file is reached, create name-id-map and // start reading again to get line elements and node data. - std::map< std::string, std::size_t> name_id_map; - std::size_t const n_nodes (nodes.size()); - for (std::size_t i=0; i<n_nodes; ++i) + std::map<std::string, std::size_t> name_id_map; + std::size_t const n_nodes(nodes.size()); + for (std::size_t i = 0; i < n_nodes; ++i) name_id_map[_id_nodename_map[i]] = i; in.clear(); in.seekg(0, in.beg); - std::vector< MeshLib::Element* > elements; + std::vector<MeshLib::Element*> elements; std::vector<double> max_depth(n_nodes); std::size_t const n_types = 3; - std::array< std::size_t, n_types> n_elem_types {{0,0,0}}; - while ( getline(in, line) ) + std::array<std::size_t, n_types> n_elem_types{{0, 0, 0}}; + while (getline(in, line)) { if (line == "[RAINGAGES]") { @@ -717,7 +729,7 @@ bool SwmmInterface::readSwmmInputToLineMesh() } else if (line == "[SUBCATCHMENTS]") { - INFO ("Reading subcatchment information..."); + INFO("Reading subcatchment information..."); if (!readSubcatchments(in, name_id_map)) return false; } @@ -731,39 +743,39 @@ bool SwmmInterface::readSwmmInputToLineMesh() } else if (line == "[JUNCTIONS]") { - INFO ("Reading junctions..."); + INFO("Reading junctions..."); if (!readNodeData(in, nodes, name_id_map, max_depth, true)) return false; } else if (line == "[OUTFALLS]") { - INFO ("Reading outfalls..."); + INFO("Reading outfalls..."); if (!readNodeData(in, nodes, name_id_map, max_depth, false)) return false; } else if (line == "[STORAGE]") { - INFO ("Reading storages..."); + INFO("Reading storages..."); if (!readNodeData(in, nodes, name_id_map, max_depth, true)) return false; } else if (line == "[CONDUITS]") { - INFO ("Reading conduits..."); + INFO("Reading conduits..."); if (!readLineElements(in, elements, nodes, name_id_map)) return false; n_elem_types[0] = elements.size(); } else if (line == "[PUMPS]") { - INFO ("Reading pumps..."); + INFO("Reading pumps..."); if (!readLineElements(in, elements, nodes, name_id_map)) return false; n_elem_types[1] = elements.size(); } else if (line == "[WEIRS]") { - INFO ("Reading weirs..."); + INFO("Reading weirs..."); if (!readLineElements(in, elements, nodes, name_id_map)) return false; n_elem_types[2] = elements.size(); @@ -775,11 +787,14 @@ bool SwmmInterface::readSwmmInputToLineMesh() } else if (line == "[Polygons]") { - INFO ("Reading subcatchments..."); + INFO("Reading subcatchments..."); std::vector<GeoLib::Polyline*> lines; std::vector<std::string> line_names; - std::vector<std::string> tmp_names; // polygon points are nameless but the method requires a vector - if (!readPolygons(in, lines, line_names, _subcatchment_points, tmp_names)) + std::vector<std::string> + tmp_names; // polygon points are nameless but the method + // requires a vector + if (!readPolygons(in, lines, line_names, _subcatchment_points, + tmp_names)) return false; if (!matchSubcatchmentsWithPolygons(lines, line_names)) @@ -798,10 +813,11 @@ bool SwmmInterface::readSwmmInputToLineMesh() auto* const mat_ids = props.createNewPropertyVector<int>( "MaterialIDs", MeshLib::MeshItemType::Cell, 1); mat_ids->resize(elements.size(), 0); - for (std::size_t i=1; i<n_types; ++i) + for (std::size_t i = 1; i < n_types; ++i) { if (n_elem_types[i] > 0) - std::fill(mat_ids->begin()+n_elem_types[i-1], mat_ids->begin()+n_elem_types[i], i); + std::fill(mat_ids->begin() + n_elem_types[i - 1], + mat_ids->begin() + n_elem_types[i], i); } if (nodes.size() == max_depth.size()) @@ -809,29 +825,33 @@ bool SwmmInterface::readSwmmInputToLineMesh() auto* const depth = props.createNewPropertyVector<double>( "Max Depth", MeshLib::MeshItemType::Node, 1); depth->reserve(max_depth.size()); - std::copy(max_depth.cbegin(), max_depth.cend(), std::back_inserter(*depth)); + std::copy(max_depth.cbegin(), max_depth.cend(), + std::back_inserter(*depth)); } else - ERR ("Size of max depth array does not fit number of elements. Skipping array."); + ERR("Size of max depth array does not fit number of elements. Skipping " + "array."); _mesh.reset(new MeshLib::Mesh(_base_name, nodes, elements, props)); return true; } -bool SwmmInterface::matchSubcatchmentsWithPolygons(std::vector<GeoLib::Polyline*> const& lines, std::vector<std::string> const& names) +bool SwmmInterface::matchSubcatchmentsWithPolygons( + std::vector<GeoLib::Polyline*> const& lines, + std::vector<std::string> const& names) { - std::size_t const n_lines (lines.size()); - std::size_t const n_subcatchments (_subcatchments.size()); + std::size_t const n_lines(lines.size()); + std::size_t const n_subcatchments(_subcatchments.size()); if (n_lines != n_subcatchments) { - ERR ("Number of subcatchments does not match number of outlines."); + ERR("Number of subcatchments does not match number of outlines."); return false; } - for (std::size_t i=0; i<n_lines; ++i) + for (std::size_t i = 0; i < n_lines; ++i) { bool found = false; - for (std::size_t j=0; j<n_subcatchments; ++j) + for (std::size_t j = 0; j < n_subcatchments; ++j) { if (names[i] == _subcatchments[j].name) { @@ -863,17 +883,17 @@ std::vector<std::string> SwmmInterface::getNames(SwmmObject obj_type) const { switch (obj_type) { - case SwmmObject::NODE: - return _id_nodename_map; - case SwmmObject::LINK: - return _id_linkname_map; - case SwmmObject::SUBCATCHMENT: - return getSubcatchmentNameMap(); - case SwmmObject::SYSTEM: - std::vector<std::string> system_name { "System" }; - return system_name; + case SwmmObject::NODE: + return _id_nodename_map; + case SwmmObject::LINK: + return _id_linkname_map; + case SwmmObject::SUBCATCHMENT: + return getSubcatchmentNameMap(); + case SwmmObject::SYSTEM: + std::vector<std::string> system_name{"System"}; + return system_name; } - ERR ("Object type has no name map"); + ERR("Object type has no name map"); std::vector<std::string> empty_vec; return empty_vec; } @@ -882,26 +902,26 @@ std::string SwmmInterface::getName(SwmmObject obj_type, std::size_t idx) const { switch (obj_type) { - case SwmmObject::NODE: - if (idx < _id_nodename_map.size()) - return _id_nodename_map[idx]; - case SwmmObject::LINK: - if (idx < _id_linkname_map.size()) - return _id_linkname_map[idx]; - case SwmmObject::SUBCATCHMENT: - if (idx < _subcatchments.size()) - return _subcatchments[idx].name; - case SwmmObject::SYSTEM: - if (idx == 0) - return std::string("System"); + case SwmmObject::NODE: + if (idx < _id_nodename_map.size()) + return _id_nodename_map[idx]; + case SwmmObject::LINK: + if (idx < _id_linkname_map.size()) + return _id_linkname_map[idx]; + case SwmmObject::SUBCATCHMENT: + if (idx < _subcatchments.size()) + return _subcatchments[idx].name; + case SwmmObject::SYSTEM: + if (idx == 0) + return std::string("System"); } - ERR ("Index out of bounds."); + ERR("Index out of bounds."); return std::string(""); } std::size_t SwmmInterface::getNumberOfObjects(SwmmObject obj_type) const { - std::string const outfile (_base_name + ".out"); + std::string const outfile(_base_name + ".out"); if (OpenSwmmOutFile(const_cast<char*>(outfile.c_str())) != 0) return 0; @@ -916,7 +936,7 @@ std::size_t SwmmInterface::getNumberOfObjects(SwmmObject obj_type) const case SwmmObject::SYSTEM: return 1; default: - ERR ("Object type not recognised."); + ERR("Object type not recognised."); } CloseSwmmOutFile(); return 0; @@ -924,8 +944,8 @@ std::size_t SwmmInterface::getNumberOfObjects(SwmmObject obj_type) const std::size_t SwmmInterface::getNumberOfParameters(SwmmObject obj_type) const { - std::string const outfile (_base_name + ".out"); - std::size_t n_time_steps (std::numeric_limits<std::size_t>::max()); + std::string const outfile(_base_name + ".out"); + std::size_t n_time_steps(std::numeric_limits<std::size_t>::max()); if (OpenSwmmOutFile(const_cast<char*>(outfile.c_str())) != 0) return 0; @@ -945,7 +965,7 @@ std::size_t SwmmInterface::getNumberOfParameters(SwmmObject obj_type) const n_params = n_obj_params[3]; break; default: - ERR ("Object type not recognised."); + ERR("Object type not recognised."); } CloseSwmmOutFile(); return n_params; @@ -953,26 +973,28 @@ std::size_t SwmmInterface::getNumberOfParameters(SwmmObject obj_type) const std::size_t SwmmInterface::getNumberOfTimeSteps() const { - std::string const outfile (_base_name + ".out"); + std::string const outfile(_base_name + ".out"); if (OpenSwmmOutFile(const_cast<char*>(outfile.c_str())) != 0) return std::numeric_limits<std::size_t>::max(); - std::size_t const n_time_steps (static_cast<std::size_t>(SWMM_Nperiods)); + std::size_t const n_time_steps(static_cast<std::size_t>(SWMM_Nperiods)); CloseSwmmOutFile(); return n_time_steps; } -bool SwmmInterface::addResultsToMesh(MeshLib::Mesh &mesh, SwmmObject const swmm_type, - std::string const& vec_name, std::vector<double> const& data) +bool SwmmInterface::addResultsToMesh(MeshLib::Mesh& mesh, + SwmmObject const swmm_type, + std::string const& vec_name, + std::vector<double> const& data) { if (!(swmm_type == SwmmObject::NODE || swmm_type == SwmmObject::LINK)) { - ERR ("Information of this object type cannot be added to mesh."); + ERR("Information of this object type cannot be added to mesh."); return false; } if (data.empty()) { - ERR ("Data array is empty and cannot be added to mesh."); + ERR("Data array is empty and cannot be added to mesh."); return false; } @@ -984,7 +1006,8 @@ bool SwmmInterface::addResultsToMesh(MeshLib::Mesh &mesh, SwmmObject const swmm_ return false; } - if (swmm_type == SwmmObject::LINK && data.size() != mesh.getNumberOfElements()) + if (swmm_type == SwmmObject::LINK && + data.size() != mesh.getNumberOfElements()) { ERR("Number of mesh elements ({:d}) does not match length of array " "({:d}).", @@ -1006,10 +1029,12 @@ bool SwmmInterface::addResultsToMesh(MeshLib::Mesh &mesh, SwmmObject const swmm_ return true; } -std::vector<double> SwmmInterface::getArrayAtTimeStep(SwmmObject obj_type, std::size_t time_step, std::size_t var_idx) const +std::vector<double> SwmmInterface::getArrayAtTimeStep(SwmmObject obj_type, + std::size_t time_step, + std::size_t var_idx) const { std::vector<double> data; - std::string const outfile (_base_name + ".out"); + std::string const outfile(_base_name + ".out"); if (OpenSwmmOutFile(const_cast<char*>(outfile.c_str())) != 0) return data; @@ -1049,15 +1074,15 @@ std::vector<double> SwmmInterface::getArrayAtTimeStep(SwmmObject obj_type, std:: if (var_idx > n_obj_params[obj_type_id]) is_var_idx_okay = false; break; - default: - ERR ("Object type not recognised."); - CloseSwmmOutFile(); - return data; + default: + ERR("Object type not recognised."); + CloseSwmmOutFile(); + return data; } if (!is_var_idx_okay) { - ERR ("Requested variable does not exist."); + ERR("Requested variable does not exist."); CloseSwmmOutFile(); return data; } @@ -1065,7 +1090,7 @@ std::vector<double> SwmmInterface::getArrayAtTimeStep(SwmmObject obj_type, std:: INFO("Fetching '{:s}'-data for time step {:d}...", getArrayName(obj_type, var_idx, SWMM_Npolluts), time_step); - for (std::size_t i=0; i<n_objects; ++i) + for (std::size_t i = 0; i < n_objects; ++i) { float val; GetSwmmResult(obj_type_id, i, var_idx, time_step, &val); @@ -1076,10 +1101,12 @@ std::vector<double> SwmmInterface::getArrayAtTimeStep(SwmmObject obj_type, std:: return data; } -std::vector<double> SwmmInterface::getArrayForObject(SwmmObject obj_type, std::size_t obj_idx, std::size_t var_idx) const +std::vector<double> SwmmInterface::getArrayForObject(SwmmObject obj_type, + std::size_t obj_idx, + std::size_t var_idx) const { std::vector<double> data; - std::string const outfile (_base_name + ".out"); + std::string const outfile(_base_name + ".out"); if (OpenSwmmOutFile(const_cast<char*>(outfile.c_str())) != 0) return data; @@ -1116,31 +1143,31 @@ std::vector<double> SwmmInterface::getArrayForObject(SwmmObject obj_type, std::s if (var_idx > n_obj_params[obj_type_id]) is_var_idx_okay = false; break; - default: - ERR ("Object type not recognised."); - CloseSwmmOutFile(); - return data; + default: + ERR("Object type not recognised."); + CloseSwmmOutFile(); + return data; } if (!is_obj_idx_okay) { - ERR ("Requested object index does not exist."); + ERR("Requested object index does not exist."); CloseSwmmOutFile(); return data; } if (!is_var_idx_okay) { - ERR ("Requested variable does not exist."); + ERR("Requested variable does not exist."); CloseSwmmOutFile(); return data; } - std::size_t const n_time_steps (static_cast<std::size_t>(SWMM_Nperiods)); - for (std::size_t i=0; i<n_time_steps; ++i) + std::size_t const n_time_steps(static_cast<std::size_t>(SWMM_Nperiods)); + for (std::size_t i = 0; i < n_time_steps; ++i) { float val; - GetSwmmResult(obj_type_id , obj_idx, var_idx, i, &val); + GetSwmmResult(obj_type_id, obj_idx, var_idx, i, &val); data.push_back(static_cast<double>(val)); } @@ -1148,9 +1175,10 @@ std::vector<double> SwmmInterface::getArrayForObject(SwmmObject obj_type, std::s return data; } -std::string SwmmInterface::getArrayName(SwmmObject obj_type, std::size_t var_idx) const +std::string SwmmInterface::getArrayName(SwmmObject obj_type, + std::size_t var_idx) const { - std::string const outfile (_base_name + ".out"); + std::string const outfile(_base_name + ".out"); if (OpenSwmmOutFile(const_cast<char*>(outfile.c_str())) != 0) return std::string(""); @@ -1159,20 +1187,22 @@ std::string SwmmInterface::getArrayName(SwmmObject obj_type, std::size_t var_idx return name; } -std::string SwmmInterface::getArrayName(SwmmObject obj_type, std::size_t var_idx, std::size_t n_pollutants) const +std::string SwmmInterface::getArrayName(SwmmObject obj_type, + std::size_t var_idx, + std::size_t n_pollutants) const { if (obj_type == SwmmObject::SUBCATCHMENT) { if (var_idx < n_obj_params[0]) return subcatchment_vars[var_idx]; - if (var_idx < n_obj_params[0]+n_pollutants) - return _pollutant_names[var_idx-n_obj_params[0]]; + if (var_idx < n_obj_params[0] + n_pollutants) + return _pollutant_names[var_idx - n_obj_params[0]]; } if (obj_type == SwmmObject::NODE) { if (var_idx < n_obj_params[1]) return node_vars[var_idx]; - if (var_idx < n_obj_params[1]+n_pollutants) + if (var_idx < n_obj_params[1] + n_pollutants) return std::string("Node_" + _pollutant_names[var_idx - n_obj_params[1]]); } @@ -1180,7 +1210,7 @@ std::string SwmmInterface::getArrayName(SwmmObject obj_type, std::size_t var_idx { if (var_idx < n_obj_params[2]) return link_vars[var_idx]; - if (var_idx < n_obj_params[2]+n_pollutants) + if (var_idx < n_obj_params[2] + n_pollutants) return std::string("Link_" + _pollutant_names[var_idx - n_obj_params[2]]); } @@ -1188,11 +1218,11 @@ std::string SwmmInterface::getArrayName(SwmmObject obj_type, std::size_t var_idx { return system_vars[var_idx]; } - ERR ("SwmmInterface::getArrayName() - Index error, no name found."); + ERR("SwmmInterface::getArrayName() - Index error, no name found."); return std::string(""); } -bool SwmmInterface::addRainGaugeTimeSeriesLocations(std::ifstream &in) +bool SwmmInterface::addRainGaugeTimeSeriesLocations(std::ifstream& in) { std::string line; while (getline(in, line)) @@ -1203,17 +1233,17 @@ bool SwmmInterface::addRainGaugeTimeSeriesLocations(std::ifstream &in) if (isCommentLine(line)) continue; - std::vector<std::string> const split_str (BaseLib::splitString(line)); + std::vector<std::string> const split_str(BaseLib::splitString(line)); if (split_str.size() < 6) { - ERR ("Rain gauge parameter format not recognised."); + ERR("Rain gauge parameter format not recognised."); return false; } for (auto& stn : _rain_gauges) { if (stn.first.getName() == split_str[0] && split_str[4] == "FILE") - stn.second = split_str[5].substr(1, split_str[5].size()-2); + stn.second = split_str[5].substr(1, split_str[5].size() - 2); } } @@ -1224,7 +1254,7 @@ bool SwmmInterface::addRainGaugeTimeSeriesLocations(std::ifstream &in) return true; } -bool SwmmInterface::readPollutants(std::ifstream &in) +bool SwmmInterface::readPollutants(std::ifstream& in) { std::string line; while (getline(in, line)) @@ -1235,10 +1265,10 @@ bool SwmmInterface::readPollutants(std::ifstream &in) if (isCommentLine(line)) continue; - std::vector<std::string> split_str (BaseLib::splitString(line)); + std::vector<std::string> split_str(BaseLib::splitString(line)); if (split_str.size() < 6) { - ERR ("Parameter format for pollutants not recognised."); + ERR("Parameter format for pollutants not recognised."); return false; } _pollutant_names.push_back(split_str[0]); @@ -1260,13 +1290,15 @@ bool SwmmInterface::isSectionFinished(std::string const& str) bool SwmmInterface::isCommentLine(std::string const& str) { - return (str.compare(str.find_first_not_of(' ', 0),1,";") == 0); + return (str.compare(str.find_first_not_of(' ', 0), 1, ";") == 0); } -bool SwmmInterface::getNodeCoordinateVectors(std::vector<double> &x, std::vector<double> &y, std::vector<double> &z) const +bool SwmmInterface::getNodeCoordinateVectors(std::vector<double>& x, + std::vector<double>& y, + std::vector<double>& z) const { - std::vector<MeshLib::Node*> const& nodes (_mesh->getNodes()); - for (MeshLib::Node const*const node : nodes) + std::vector<MeshLib::Node*> const& nodes(_mesh->getNodes()); + for (MeshLib::Node const* const node : nodes) { x.push_back((*node)[0]); y.push_back((*node)[1]); @@ -1275,14 +1307,15 @@ bool SwmmInterface::getNodeCoordinateVectors(std::vector<double> &x, std::vector return true; } -bool SwmmInterface::getLinkPointIds(std::vector<std::size_t> &inlets, std::vector<std::size_t> &outlets) const +bool SwmmInterface::getLinkPointIds(std::vector<std::size_t>& inlets, + std::vector<std::size_t>& outlets) const { - std::vector<MeshLib::Element*> const& elements (_mesh->getElements()); - for (MeshLib::Element const*const elem : elements) + std::vector<MeshLib::Element*> const& elements(_mesh->getElements()); + for (MeshLib::Element const* const elem : elements) { if (elem->getGeomType() != MeshLib::MeshElemType::LINE) { - ERR ("Non line-element found in mesh."); + ERR("Non line-element found in mesh."); return false; } inlets.push_back(elem->getNodeIndex(0)); @@ -1304,13 +1337,15 @@ std::string SwmmInterface::swmmObjectTypeToString(SwmmObject const obj_type) return "undefined"; } -bool SwmmInterface::writeCsvForTimestep(std::string const& file_name, SwmmObject obj_type, std::size_t time_step) const +bool SwmmInterface::writeCsvForTimestep(std::string const& file_name, + SwmmObject obj_type, + std::size_t time_step) const { FileIO::CsvInterface csv; csv.addIndexVectorForWriting(getNumberOfObjects(obj_type)); csv.addVectorForWriting("Name", getNames(obj_type)); std::size_t const n_params(getNumberOfParameters(obj_type)); - for (std::size_t i=0; i<n_params; ++i) + for (std::size_t i = 0; i < n_params; ++i) { std::vector<double> data = getArrayAtTimeStep(obj_type, time_step, i); if (!data.empty()) @@ -1318,21 +1353,23 @@ bool SwmmInterface::writeCsvForTimestep(std::string const& file_name, SwmmObject } if (csv.getNArrays() < 2) { - ERR ("No data to write"); + ERR("No data to write"); return false; } BaseLib::IO::writeStringToFile(csv.writeToString(), file_name); return true; } -bool SwmmInterface::writeCsvForObject(std::string const& file_name, SwmmObject obj_type, std::size_t obj_idx) const +bool SwmmInterface::writeCsvForObject(std::string const& file_name, + SwmmObject obj_type, + std::size_t obj_idx) const { FileIO::CsvInterface csv; INFO("Writing data for {:s} {:d}.", swmmObjectTypeToString(obj_type), obj_idx); csv.addIndexVectorForWriting(getNumberOfTimeSteps()); - std::size_t const n_params (getNumberOfParameters(obj_type)); - for (std::size_t i=0; i<n_params; ++i) + std::size_t const n_params(getNumberOfParameters(obj_type)); + for (std::size_t i = 0; i < n_params; ++i) { std::vector<double> data = getArrayForObject(obj_type, obj_idx, i); if (!data.empty()) @@ -1340,11 +1377,11 @@ bool SwmmInterface::writeCsvForObject(std::string const& file_name, SwmmObject o } if (csv.getNArrays() < 2) { - ERR ("No data to write"); + ERR("No data to write"); return false; } BaseLib::IO::writeStringToFile(csv.writeToString(), file_name); return true; } -} // namespace FileIO +} // namespace FileIO diff --git a/Applications/FileIO/TetGenInterface.cpp b/Applications/FileIO/TetGenInterface.cpp index 133245369a10cbbb68526ab1338ea8458edb615f..81fceff00ea82f49c5dd1c16e0df2eb71f75b227 100644 --- a/Applications/FileIO/TetGenInterface.cpp +++ b/Applications/FileIO/TetGenInterface.cpp @@ -15,30 +15,27 @@ #include "TetGenInterface.h" #include <cstddef> -#include <string> #include <fstream> - -#include "BaseLib/Logging.h" +#include <string> #include "BaseLib/FileTools.h" +#include "BaseLib/Logging.h" #include "BaseLib/StringTools.h" - #include "GeoLib/Triangle.h" - -#include "MeshLib/Mesh.h" -#include "MeshLib/Node.h" #include "MeshLib/Elements/Element.h" #include "MeshLib/Elements/Tet.h" +#include "MeshLib/Mesh.h" #include "MeshLib/MeshInformation.h" +#include "MeshLib/Node.h" namespace FileIO { TetGenInterface::TetGenInterface() = default; -bool TetGenInterface::readTetGenGeometry (std::string const& geo_fname, - GeoLib::GEOObjects &geo_objects) +bool TetGenInterface::readTetGenGeometry(std::string const& geo_fname, + GeoLib::GEOObjects& geo_objects) { - std::ifstream poly_stream (geo_fname.c_str()); + std::ifstream poly_stream(geo_fname.c_str()); if (!poly_stream) { @@ -46,15 +43,16 @@ bool TetGenInterface::readTetGenGeometry (std::string const& geo_fname, geo_fname); return false; } - std::string ext (BaseLib::getFileExtension(geo_fname)); + std::string ext(BaseLib::getFileExtension(geo_fname)); if (ext != ".smesh") { - ERR ("TetGenInterface::readTetGenGeometry() - unknown file type (only *.smesh is supported)."); + ERR("TetGenInterface::readTetGenGeometry() - unknown file type (only " + "*.smesh is supported)."); return false; } std::vector<MeshLib::Node*> nodes; - if (!readNodesFromStream (poly_stream, nodes)) + if (!readNodesFromStream(poly_stream, nodes)) { // remove nodes read until now for (auto& node : nodes) @@ -63,20 +61,22 @@ bool TetGenInterface::readTetGenGeometry (std::string const& geo_fname, } return false; } - const std::size_t nNodes (nodes.size()); + const std::size_t nNodes(nodes.size()); auto points = std::make_unique<std::vector<GeoLib::Point*>>(); points->reserve(nNodes); - for (std::size_t k(0); k<nNodes; ++k) + for (std::size_t k(0); k < nNodes; ++k) { points->push_back(new GeoLib::Point(*(nodes[k]), nodes[k]->getID())); delete nodes[k]; } - std::string geo_name (BaseLib::extractBaseNameWithoutExtension(geo_fname)); + std::string geo_name(BaseLib::extractBaseNameWithoutExtension(geo_fname)); geo_objects.addPointVec(std::move(points), geo_name); - const std::vector<std::size_t> &id_map (geo_objects.getPointVecObj(geo_name)->getIDMap()); + const std::vector<std::size_t>& id_map( + geo_objects.getPointVecObj(geo_name)->getIDMap()); auto surfaces = std::make_unique<std::vector<GeoLib::Surface*>>(); - if (!parseSmeshFacets(poly_stream, *surfaces, *geo_objects.getPointVec(geo_name), id_map)) + if (!parseSmeshFacets( + poly_stream, *surfaces, *geo_objects.getPointVec(geo_name), id_map)) { // remove surfaces read until now but keep the points for (std::size_t k = 0; k < surfaces->size(); k++) @@ -89,15 +89,16 @@ bool TetGenInterface::readTetGenGeometry (std::string const& geo_fname, return true; } -std::size_t TetGenInterface::getNFacets(std::ifstream &input) +std::size_t TetGenInterface::getNFacets(std::ifstream& input) { std::string line; while (!input.fail()) { - getline (input, line); + getline(input, line); if (input.fail()) { - ERR("TetGenInterface::getNFacets(): Error reading number of facets."); + ERR("TetGenInterface::getNFacets(): Error reading number of " + "facets."); return 0; } @@ -119,12 +120,13 @@ std::size_t TetGenInterface::getNFacets(std::ifstream &input) return 0; } -bool TetGenInterface::parseSmeshFacets(std::ifstream &input, - std::vector<GeoLib::Surface*> &surfaces, - const std::vector<GeoLib::Point*> &points, - const std::vector<std::size_t> &pnt_id_map) +bool TetGenInterface::parseSmeshFacets( + std::ifstream& input, + std::vector<GeoLib::Surface*>& surfaces, + const std::vector<GeoLib::Point*>& points, + const std::vector<std::size_t>& pnt_id_map) { - const std::size_t nFacets (this->getNFacets(input)); + const std::size_t nFacets(this->getNFacets(input)); std::string line; surfaces.reserve(nFacets); std::list<std::string>::const_iterator it; @@ -133,9 +135,9 @@ bool TetGenInterface::parseSmeshFacets(std::ifstream &input, std::vector<std::size_t> idx_map; std::size_t k(0); - while (k<nFacets && !input.fail()) + while (k < nFacets && !input.fail()) { - getline (input, line); + getline(input, line); if (input.fail()) { ERR("TetGenInterface::parseFacets(): Error reading facet {:d}.", k); @@ -143,22 +145,25 @@ bool TetGenInterface::parseSmeshFacets(std::ifstream &input, } BaseLib::simplify(line); - if (line.empty() || line.compare(0,1,"#") == 0) + if (line.empty() || line.compare(0, 1, "#") == 0) { continue; } // read facets - const std::list<std::string> point_fields = BaseLib::splitString(line, ' '); + const std::list<std::string> point_fields = + BaseLib::splitString(line, ' '); it = point_fields.begin(); const auto nPoints = BaseLib::str2number<std::size_t>(*it); if (nPoints != 3) { - ERR ("Smesh-files are currently only supported for triangle meshes."); + ERR("Smesh-files are currently only supported for triangle " + "meshes."); return false; } std::vector<std::size_t> point_ids; - const std::size_t point_field_size = (_boundary_markers) ? nPoints+1 : nPoints; + const std::size_t point_field_size = + (_boundary_markers) ? nPoints + 1 : nPoints; if (point_fields.size() > point_field_size) { for (std::size_t j(0); j < nPoints; ++j) @@ -168,14 +173,19 @@ bool TetGenInterface::parseSmeshFacets(std::ifstream &input, offset]); } - const std::size_t sfc_marker = (_boundary_markers) ? BaseLib::str2number<std::size_t>(*(++it)) : 0; - const std::size_t idx = std::find(idx_map.begin(), idx_map.end(), sfc_marker) - idx_map.begin(); + const std::size_t sfc_marker = + (_boundary_markers) ? BaseLib::str2number<std::size_t>(*(++it)) + : 0; + const std::size_t idx = + std::find(idx_map.begin(), idx_map.end(), sfc_marker) - + idx_map.begin(); if (idx >= surfaces.size()) { idx_map.push_back(sfc_marker); surfaces.push_back(new GeoLib::Surface(points)); } - surfaces[idx]->addTriangle(point_ids[0], point_ids[1], point_ids[2]); + surfaces[idx]->addTriangle( + point_ids[0], point_ids[1], point_ids[2]); } else { @@ -186,10 +196,12 @@ bool TetGenInterface::parseSmeshFacets(std::ifstream &input, } ++k; } - // here the poly-file potentially defines a number of points to mark holes within the volumes defined by the facets, these are ignored for now - // here the poly-file potentially defines a number of region attributes, these are ignored for now + // here the poly-file potentially defines a number of points to mark holes + // within the volumes defined by the facets, these are ignored for now here + // the poly-file potentially defines a number of region attributes, these + // are ignored for now - std::size_t nTotalTriangles (0); + std::size_t nTotalTriangles(0); for (auto& surface : surfaces) { nTotalTriangles += surface->getNumberOfTriangles(); @@ -206,11 +218,11 @@ bool TetGenInterface::parseSmeshFacets(std::ifstream &input, return false; } -MeshLib::Mesh* TetGenInterface::readTetGenMesh (std::string const& nodes_fname, - std::string const& ele_fname) +MeshLib::Mesh* TetGenInterface::readTetGenMesh(std::string const& nodes_fname, + std::string const& ele_fname) { - std::ifstream ins_nodes (nodes_fname.c_str()); - std::ifstream ins_ele (ele_fname.c_str()); + std::ifstream ins_nodes(nodes_fname.c_str()); + std::ifstream ins_ele(ele_fname.c_str()); if (!ins_nodes || !ins_ele) { @@ -228,9 +240,11 @@ MeshLib::Mesh* TetGenInterface::readTetGenMesh (std::string const& nodes_fname, } std::vector<MeshLib::Node*> nodes; - if (!readNodesFromStream (ins_nodes, nodes)) { + if (!readNodesFromStream(ins_nodes, nodes)) + { // remove nodes read until now - for (auto & node : nodes) { + for (auto& node : nodes) + { delete node; } return nullptr; @@ -238,14 +252,16 @@ MeshLib::Mesh* TetGenInterface::readTetGenMesh (std::string const& nodes_fname, std::vector<MeshLib::Element*> elements; std::vector<int> materials; - if (!readElementsFromStream (ins_ele, elements, materials, nodes)) { + if (!readElementsFromStream(ins_ele, elements, materials, nodes)) + { BaseLib::cleanupVectorElements(nodes, elements); return nullptr; } MeshLib::Properties properties; // Transmit material values if there is any material value != 0 - if (std::any_of(materials.cbegin(), materials.cend(), [](int m){ return m != 0; })) + if (std::any_of( + materials.cbegin(), materials.cend(), [](int m) { return m != 0; })) { auto* const mat_props = properties.createNewPropertyVector<int>( "MaterialIDs", MeshLib::MeshItemType::Cell); @@ -255,15 +271,16 @@ MeshLib::Mesh* TetGenInterface::readTetGenMesh (std::string const& nodes_fname, std::back_inserter(*mat_props)); } - const std::string mesh_name (BaseLib::extractBaseNameWithoutExtension(nodes_fname)); + const std::string mesh_name( + BaseLib::extractBaseNameWithoutExtension(nodes_fname)); return new MeshLib::Mesh(mesh_name, nodes, elements, properties); } -bool TetGenInterface::readNodesFromStream (std::ifstream &ins, - std::vector<MeshLib::Node*> &nodes) +bool TetGenInterface::readNodesFromStream(std::ifstream& ins, + std::vector<MeshLib::Node*>& nodes) { std::string line; - getline (ins, line); + getline(ins, line); std::size_t n_nodes; std::size_t dim; std::size_t n_attributes; @@ -272,14 +289,15 @@ bool TetGenInterface::readNodesFromStream (std::ifstream &ins, while (!ins.fail()) { BaseLib::simplify(line); - if (line.empty() || line.compare(0,1,"#") == 0) + if (line.empty() || line.compare(0, 1, "#") == 0) { // this line is a comment - skip - getline (ins, line); + getline(ins, line); continue; } // read header line - bool header_okay = parseNodesFileHeader(line, n_nodes, dim, n_attributes, boundary_markers); + bool header_okay = parseNodesFileHeader( + line, n_nodes, dim, n_attributes, boundary_markers); if (!header_okay) { return false; @@ -302,28 +320,30 @@ bool TetGenInterface::parseNodesFileHeader(std::string const& line, std::list<std::string> pnt_header = BaseLib::splitString(line, ' '); if (pnt_header.empty()) { - ERR("TetGenInterface::parseNodesFileHeader(): could not read number of nodes specified in header."); + ERR("TetGenInterface::parseNodesFileHeader(): could not read number of " + "nodes specified in header."); return false; } auto it = pnt_header.begin(); - n_nodes = BaseLib::str2number<std::size_t> (*it); - dim = (pnt_header.size()==1) ? 3 : BaseLib::str2number<std::size_t> (*(++it)); + n_nodes = BaseLib::str2number<std::size_t>(*it); + dim = (pnt_header.size() == 1) ? 3 + : BaseLib::str2number<std::size_t>(*(++it)); - if (pnt_header.size()<4) + if (pnt_header.size() < 4) { n_attributes = 0; boundary_markers = false; return true; } - n_attributes = BaseLib::str2number<std::size_t> (*(++it)); + n_attributes = BaseLib::str2number<std::size_t>(*(++it)); boundary_markers = *(++it) == "1"; return true; } -bool TetGenInterface::parseNodes(std::ifstream &ins, - std::vector<MeshLib::Node*> &nodes, +bool TetGenInterface::parseNodes(std::ifstream& ins, + std::vector<MeshLib::Node*>& nodes, std::size_t n_nodes, std::size_t dim) { @@ -346,25 +366,31 @@ bool TetGenInterface::parseNodes(std::ifstream &ins, std::size_t pos_beg = line.find_first_not_of(' ', pos_end); pos_end = line.find_first_of(" \n", pos_beg); - if (line.empty() || pos_beg==pos_end || line.compare(pos_beg,1,"#") == 0) + if (line.empty() || pos_beg == pos_end || + line.compare(pos_beg, 1, "#") == 0) { continue; } - if (pos_beg != std::string::npos && pos_end != std::string::npos) { - id = BaseLib::str2number<std::size_t> (line.substr(pos_beg, pos_end - pos_beg)); + if (pos_beg != std::string::npos && pos_end != std::string::npos) + { + id = BaseLib::str2number<std::size_t>( + line.substr(pos_beg, pos_end - pos_beg)); if (k == 0 && id == 0) { _zero_based_idx = true; } - } else { + } + else + { ERR("TetGenInterface::parseNodes(): Error reading ID of node {:d}.", k); return false; } // read coordinates const unsigned offset = (_zero_based_idx) ? 0 : 1; - for (std::size_t i(0); i < dim; i++) { + for (std::size_t i(0); i < dim; i++) + { pos_beg = line.find_first_not_of(' ', pos_end); pos_end = line.find_first_of(" \n", pos_beg); if (pos_end == std::string::npos) @@ -373,7 +399,8 @@ bool TetGenInterface::parseNodes(std::ifstream &ins, } if (pos_beg != std::string::npos) { - coordinates[i] = BaseLib::str2number<double>(line.substr(pos_beg, pos_end-pos_beg)); + coordinates[i] = BaseLib::str2number<double>( + line.substr(pos_beg, pos_end - pos_beg)); } else { @@ -385,8 +412,9 @@ bool TetGenInterface::parseNodes(std::ifstream &ins, } } - nodes.push_back(new MeshLib::Node(coordinates.data(), id-offset)); - // read attributes and boundary markers ... - at the moment we do not use this information + nodes.push_back(new MeshLib::Node(coordinates.data(), id - offset)); + // read attributes and boundary markers ... - at the moment we do not + // use this information ++k; } @@ -446,23 +474,26 @@ bool TetGenInterface::parseElementsFileHeader(std::string& line, std::size_t pos_end; // number of tetrahedras - pos_beg = line.find_first_not_of (' '); + pos_beg = line.find_first_not_of(' '); pos_end = line.find_first_of(' ', pos_beg); if (pos_beg != std::string::npos && pos_end != std::string::npos) { - n_tets = BaseLib::str2number<std::size_t> (line.substr(pos_beg, pos_end - pos_beg)); + n_tets = BaseLib::str2number<std::size_t>( + line.substr(pos_beg, pos_end - pos_beg)); } else { - ERR("TetGenInterface::parseElementsFileHeader(): Could not read number of tetrahedra specified in header."); + ERR("TetGenInterface::parseElementsFileHeader(): Could not read number " + "of tetrahedra specified in header."); return false; } // nodes per tet - either 4 or 10 - pos_beg = line.find_first_not_of (" \t", pos_end); + pos_beg = line.find_first_not_of(" \t", pos_end); pos_end = line.find_first_of(" \t", pos_beg); - n_nodes_per_tet = BaseLib::str2number<std::size_t> (line.substr(pos_beg, pos_end - pos_beg)); + n_nodes_per_tet = BaseLib::str2number<std::size_t>( + line.substr(pos_beg, pos_end - pos_beg)); // region attribute at tetrahedra? - pos_beg = line.find_first_not_of (" \t", pos_end); + pos_beg = line.find_first_not_of(" \t", pos_end); pos_end = line.find_first_of(" \t\n", pos_beg); if (pos_end == std::string::npos) { @@ -474,9 +505,9 @@ bool TetGenInterface::parseElementsFileHeader(std::string& line, } bool TetGenInterface::parseElements(std::ifstream& ins, - std::vector<MeshLib::Element*> &elements, - std::vector<int> &materials, - const std::vector<MeshLib::Node*> &nodes, + std::vector<MeshLib::Element*>& elements, + std::vector<int>& materials, + const std::vector<MeshLib::Node*>& nodes, std::size_t n_tets, std::size_t n_nodes_per_tet, bool region_attribute) const @@ -490,7 +521,7 @@ bool TetGenInterface::parseElements(std::ifstream& ins, const unsigned offset = (_zero_based_idx) ? 0 : 1; for (std::size_t k(0); k < n_tets && !ins.fail(); k++) { - getline (ins, line); + getline(ins, line); if (ins.fail()) { ERR("TetGenInterface::parseElements(): Error reading tetrahedron " @@ -503,7 +534,8 @@ bool TetGenInterface::parseElements(std::ifstream& ins, std::size_t pos_beg = line.find_first_not_of(' ', pos_end); pos_end = line.find_first_of(" \n", pos_beg); - if (line.empty() || pos_beg==pos_end || line.compare(pos_beg,1,"#") == 0) + if (line.empty() || pos_beg == pos_end || + line.compare(pos_beg, 1, "#") == 0) { k--; continue; @@ -528,7 +560,9 @@ bool TetGenInterface::parseElements(std::ifstream& ins, } if (pos_beg != std::string::npos && pos_end != std::string::npos) { - ids[i] = BaseLib::str2number<std::size_t>(line.substr(pos_beg, pos_end - pos_beg)) - offset; + ids[i] = BaseLib::str2number<std::size_t>( + line.substr(pos_beg, pos_end - pos_beg)) - + offset; } else { @@ -541,8 +575,9 @@ bool TetGenInterface::parseElements(std::ifstream& ins, } // read region attribute - this is something like material group - int region (0); - if (region_attribute) { + int region(0); + if (region_attribute) + { pos_beg = line.find_first_not_of(' ', pos_end); pos_end = line.find_first_of(' ', pos_beg); if (pos_end == std::string::npos) @@ -551,7 +586,8 @@ bool TetGenInterface::parseElements(std::ifstream& ins, } if (pos_beg != std::string::npos && pos_end != std::string::npos) { - region = BaseLib::str2number<int> (line.substr(pos_beg, pos_end - pos_beg)); + region = BaseLib::str2number<int>( + line.substr(pos_beg, pos_end - pos_beg)); } else { @@ -567,7 +603,7 @@ bool TetGenInterface::parseElements(std::ifstream& ins, { tet_nodes[n] = nodes[ids[n]]; } - elements.push_back (new MeshLib::Tet(tet_nodes)); + elements.push_back(new MeshLib::Tet(tet_nodes)); materials.push_back(region); } @@ -580,24 +616,26 @@ bool TetGenInterface::writeTetGenSmesh( const std::string& geo_name, const std::vector<GeoLib::Point>& attribute_points) { - std::vector<GeoLib::Point*> const*const points = geo_objects.getPointVec(geo_name); - std::vector<GeoLib::Surface*> const*const surfaces = geo_objects.getSurfaceVec(geo_name); + std::vector<GeoLib::Point*> const* const points = + geo_objects.getPointVec(geo_name); + std::vector<GeoLib::Surface*> const* const surfaces = + geo_objects.getSurfaceVec(geo_name); - if (points==nullptr) + if (points == nullptr) { ERR("Geometry {:s} not found.", geo_name); return false; } - if (surfaces==nullptr) + if (surfaces == nullptr) { WARN("No surfaces found for geometry {:s}. Writing points only.", geo_name); } - std::ofstream out( file_name.c_str(), std::ios::out ); + std::ofstream out(file_name.c_str(), std::ios::out); out.precision(std::numeric_limits<double>::digits10); // the points header - const std::size_t nPoints (points->size()); + const std::size_t nPoints(points->size()); out << nPoints << " 3\n"; // the point list for (std::size_t i = 0; i < nPoints; ++i) @@ -607,25 +645,26 @@ bool TetGenInterface::writeTetGenSmesh( } // the surfaces header const std::size_t nSurfaces = (surfaces) ? surfaces->size() : 0; - std::size_t nTotalTriangles (0); + std::size_t nTotalTriangles(0); for (std::size_t i = 0; i < nSurfaces; ++i) { nTotalTriangles += (*surfaces)[i]->getNumberOfTriangles(); } out << nTotalTriangles << " 1\n"; - for (std::size_t i=0; i<nSurfaces; ++i) + for (std::size_t i = 0; i < nSurfaces; ++i) { - const std::size_t nTriangles ((*surfaces)[i]->getNumberOfTriangles()); - const std::size_t marker (i+1); // must NOT be 0! + const std::size_t nTriangles((*surfaces)[i]->getNumberOfTriangles()); + const std::size_t marker(i + 1); // must NOT be 0! // the poly list - for (std::size_t j=0; j<nTriangles; ++j) + for (std::size_t j = 0; j < nTriangles; ++j) { - const GeoLib::Triangle &tri = *(*(*surfaces)[i])[j]; - out << "3 " << tri[0] << " " << tri[1] << " " << tri[2] << " " << marker << "\n"; + const GeoLib::Triangle& tri = *(*(*surfaces)[i])[j]; + out << "3 " << tri[0] << " " << tri[1] << " " << tri[2] << " " + << marker << "\n"; } } - out << "0\n"; // the polygon holes list + out << "0\n"; // the polygon holes list // the region attributes list if (attribute_points.empty()) { @@ -633,7 +672,7 @@ bool TetGenInterface::writeTetGenSmesh( } else { - const std::size_t nAttributePoints (attribute_points.size()); + const std::size_t nAttributePoints(attribute_points.size()); out << nAttributePoints << "\n"; for (std::size_t i = 0; i < nAttributePoints; ++i) { @@ -651,21 +690,22 @@ bool TetGenInterface::writeTetGenSmesh( return true; } -bool TetGenInterface::writeTetGenSmesh(const std::string &file_name, - const MeshLib::Mesh &mesh, - std::vector<MeshLib::Node> &attribute_points) const +bool TetGenInterface::writeTetGenSmesh( + const std::string& file_name, + const MeshLib::Mesh& mesh, + std::vector<MeshLib::Node>& attribute_points) const { if (mesh.getDimension() == 1) { return false; } - const std::vector<MeshLib::Node*> &nodes = mesh.getNodes(); + const std::vector<MeshLib::Node*>& nodes = mesh.getNodes(); - std::ofstream out( file_name.c_str(), std::ios::out ); + std::ofstream out(file_name.c_str(), std::ios::out); out.precision(std::numeric_limits<double>::digits10); // the points header - const std::size_t nPoints (nodes.size()); + const std::size_t nPoints(nodes.size()); out << nPoints << " 3\n"; // the point list for (std::size_t i = 0; i < nPoints; ++i) @@ -683,7 +723,7 @@ bool TetGenInterface::writeTetGenSmesh(const std::string &file_name, write3dElements(out, mesh, attribute_points); } - out << "0\n"; // the polygon holes list + out << "0\n"; // the polygon holes list // the region attributes list if (attribute_points.empty()) @@ -692,7 +732,7 @@ bool TetGenInterface::writeTetGenSmesh(const std::string &file_name, } else { - const std::size_t nAttributePoints (attribute_points.size()); + const std::size_t nAttributePoints(attribute_points.size()); out << nAttributePoints << "\n"; for (std::size_t i = 0; i < nAttributePoints; ++i) { @@ -711,65 +751,70 @@ bool TetGenInterface::writeTetGenSmesh(const std::string &file_name, return true; } -void TetGenInterface::write2dElements(std::ofstream &out, - const MeshLib::Mesh &mesh) const +void TetGenInterface::write2dElements(std::ofstream& out, + const MeshLib::Mesh& mesh) const { // the surfaces header auto const& types = MeshLib::MeshInformation::getNumberOfElementTypes(mesh); std::size_t const n_tri = (types.find(MeshLib::MeshElemType::TRIANGLE) != types.end()) - ? types.at(MeshLib::MeshElemType::TRIANGLE) : 0; + ? types.at(MeshLib::MeshElemType::TRIANGLE) + : 0; std::size_t const n_quad = (types.find(MeshLib::MeshElemType::QUAD) != types.end()) - ? types.at(MeshLib::MeshElemType::QUAD) : 0; + ? types.at(MeshLib::MeshElemType::QUAD) + : 0; unsigned const nTotalTriangles = n_tri + 2 * n_quad; out << nTotalTriangles << " 1\n"; - const std::vector<MeshLib::Element*> &elements = mesh.getElements(); - MeshLib::PropertyVector<int> const*const mat_ids = + const std::vector<MeshLib::Element*>& elements = mesh.getElements(); + MeshLib::PropertyVector<int> const* const mat_ids = mesh.getProperties().existsPropertyVector<int>("MaterialIDs") ? mesh.getProperties().getPropertyVector<int>("MaterialIDs") : nullptr; - const std::size_t nElements (elements.size()); + const std::size_t nElements(elements.size()); unsigned element_count(0); - for (std::size_t i=0; i<nElements; ++i) + for (std::size_t i = 0; i < nElements; ++i) { std::string const matId = mat_ids ? std::to_string((*mat_ids)[i]) : ""; this->writeElementToFacets(out, *elements[i], element_count, matId); } } -void TetGenInterface::write3dElements(std::ofstream &out, - const MeshLib::Mesh &mesh, - std::vector<MeshLib::Node> &attribute_points) const +void TetGenInterface::write3dElements( + std::ofstream& out, + const MeshLib::Mesh& mesh, + std::vector<MeshLib::Node>& attribute_points) const { - const std::vector<MeshLib::Element*> &elements = mesh.getElements(); - const std::size_t nElements (elements.size()); + const std::vector<MeshLib::Element*>& elements = mesh.getElements(); + const std::size_t nElements(elements.size()); if (!attribute_points.empty()) { attribute_points.clear(); } - // get position where number of facets need to be written and figure out worst case of chars that are needed - const std::streamoff before_elems_pos (out.tellp()); - const unsigned n_spaces (static_cast<unsigned>(std::floor(log(nElements*8))) + 1); + // get position where number of facets need to be written and figure out + // worst case of chars that are needed + const std::streamoff before_elems_pos(out.tellp()); + const unsigned n_spaces( + static_cast<unsigned>(std::floor(log(nElements * 8))) + 1); out << std::string(n_spaces, ' ') << " 1\n"; auto const* const materialIds = mesh.getProperties().getPropertyVector<int>("MaterialIDs"); unsigned element_count(0); - for (std::size_t i=0; i<nElements; ++i) + for (std::size_t i = 0; i < nElements; ++i) { if (elements[i]->getDimension() < 3) { continue; } - const unsigned nFaces (elements[i]->getNumberOfNeighbors()); + const unsigned nFaces(elements[i]->getNumberOfNeighbors()); std::string const mat_id_str = materialIds ? std::to_string((*materialIds)[i]) : ""; - for (std::size_t j=0; j<nFaces; ++j) + for (std::size_t j = 0; j < nFaces; ++j) { - MeshLib::Element const*const neighbor ( elements[i]->getNeighbor(j) ); + MeshLib::Element const* const neighbor(elements[i]->getNeighbor(j)); if (neighbor && materialIds && (*materialIds)[i] <= (*materialIds)[neighbor->getID()]) @@ -777,7 +822,8 @@ void TetGenInterface::write3dElements(std::ofstream &out, continue; } - std::unique_ptr<MeshLib::Element const> const face (elements[i]->getFace(j)); + std::unique_ptr<MeshLib::Element const> const face( + elements[i]->getFace(j)); this->writeElementToFacets(out, *face, element_count, mat_id_str); } if (materialIds) @@ -788,7 +834,7 @@ void TetGenInterface::write3dElements(std::ofstream &out, } } // add number of facets at correct position and jump back - const std::streamoff after_elems_pos (out.tellp()); + const std::streamoff after_elems_pos(out.tellp()); out.seekp(before_elems_pos); out << element_count; out.seekp(after_elems_pos); @@ -802,14 +848,20 @@ void TetGenInterface::writeElementToFacets(std::ofstream& out, element_count++; if (element.getGeomType() == MeshLib::MeshElemType::TRIANGLE) { - out << "3 " << element.getNodeIndex(0) << " " << element.getNodeIndex(1) << " " << element.getNodeIndex(2) << " " << matId << " # " << element_count << "\n"; + out << "3 " << element.getNodeIndex(0) << " " + << element.getNodeIndex(1) << " " << element.getNodeIndex(2) << " " + << matId << " # " << element_count << "\n"; } else if (element.getGeomType() == MeshLib::MeshElemType::QUAD) { - out << "3 " << element.getNodeIndex(0) << " " << element.getNodeIndex(1) << " " << element.getNodeIndex(2) << " " << matId << " # " << element_count << "\n"; + out << "3 " << element.getNodeIndex(0) << " " + << element.getNodeIndex(1) << " " << element.getNodeIndex(2) << " " + << matId << " # " << element_count << "\n"; element_count++; - out << "3 " << element.getNodeIndex(0) << " " << element.getNodeIndex(2) << " " << element.getNodeIndex(3) << " " << matId << " # " << element_count << "\n"; + out << "3 " << element.getNodeIndex(0) << " " + << element.getNodeIndex(2) << " " << element.getNodeIndex(3) << " " + << matId << " # " << element_count << "\n"; } } -} // end namespace FileIO +} // end namespace FileIO diff --git a/Applications/FileIO/XmlIO/Qt/XmlPrjInterface.cpp b/Applications/FileIO/XmlIO/Qt/XmlPrjInterface.cpp index 20452c12552de6ca9818a6427d39d83b08344885..8f376f65391d7324a93b85e3bbf32d2d7f3bc151 100644 --- a/Applications/FileIO/XmlIO/Qt/XmlPrjInterface.cpp +++ b/Applications/FileIO/XmlIO/Qt/XmlPrjInterface.cpp @@ -10,25 +10,20 @@ #include "XmlPrjInterface.h" -#include <iostream> -#include <vector> - #include <QFile> #include <QFileInfo> #include <QtXml/QDomDocument> -#include "BaseLib/Logging.h" +#include <iostream> +#include <vector> #include "Applications/DataExplorer/Base/OGSError.h" #include "Applications/DataHolderLib/FemCondition.h" - #include "BaseLib/FileTools.h" #include "BaseLib/IO/Writer.h" - +#include "BaseLib/Logging.h" #include "GeoLib/GEOObjects.h" - #include "GeoLib/IO/XmlIO/Qt/XmlGmlInterface.h" #include "GeoLib/IO/XmlIO/Qt/XmlStnInterface.h" - #include "MeshLib/IO/readMeshFromFile.h" #include "MeshLib/IO/writeMeshToFile.h" #include "MeshLib/Mesh.h" diff --git a/Applications/FileIO/readGeometryFromFile.cpp b/Applications/FileIO/readGeometryFromFile.cpp index 620dfc57ef91573a4c28bfac8529ae2d88bfc4f0..93f60287409da92b54fb4908b096c19c3b75a6ed 100644 --- a/Applications/FileIO/readGeometryFromFile.cpp +++ b/Applications/FileIO/readGeometryFromFile.cpp @@ -14,12 +14,10 @@ #include "BaseLib/Error.h" #include "BaseLib/FileTools.h" - +#include "GeoLib/GEOObjects.h" #include "GeoLib/IO/XmlIO/Boost/BoostXmlGmlInterface.h" #include "Legacy/OGSIOVer4.h" -#include "GeoLib/GEOObjects.h" - namespace FileIO { void readGeometryFromFile(std::string const& fname, @@ -30,9 +28,11 @@ void readGeometryFromFile(std::string const& fname, { GeoLib::IO::BoostXmlGmlInterface xml(geo_objs); xml.readFile(fname); - } else { + } + else + { std::vector<std::string> errors; - std::string geo_name; // geo_name is output of the reading function + std::string geo_name; // geo_name is output of the reading function FileIO::Legacy::readGLIFileV4( fname, geo_objs, geo_name, errors, gmsh_path); } diff --git a/Applications/FileIO/writeGeometryToFile.cpp b/Applications/FileIO/writeGeometryToFile.cpp index 23e8f25bc556399e648daa49ebee37a28826fff1..77844c49871adafeaaf839faa1ceff23732d1b00 100644 --- a/Applications/FileIO/writeGeometryToFile.cpp +++ b/Applications/FileIO/writeGeometryToFile.cpp @@ -11,25 +11,28 @@ #include "writeGeometryToFile.h" #include "BaseLib/FileTools.h" - +#include "GeoLib/GEOObjects.h" #include "GeoLib/IO/XmlIO/Boost/BoostXmlGmlInterface.h" #include "Legacy/OGSIOVer4.h" -#include "GeoLib/GEOObjects.h" - namespace FileIO { void writeGeometryToFile(std::string const& geo_name, - GeoLib::GEOObjects& geo_objs, std::string const& fname) + GeoLib::GEOObjects& geo_objs, std::string const& fname) { std::string const extension(BaseLib::getFileExtension(fname)); - if (extension == ".gml" || extension == ".GML") { + if (extension == ".gml" || extension == ".GML") + { GeoLib::IO::BoostXmlGmlInterface xml(geo_objs); xml.export_name = geo_name; BaseLib::IO::writeStringToFile(xml.writeToString(), fname); - } else if (extension == "gli" || extension == "GLI") { + } + else if (extension == "gli" || extension == "GLI") + { FileIO::Legacy::writeGLIFileV4(fname, geo_name, geo_objs); - } else { + } + else + { ERR("Writing of geometry failed, since it was not possible to determine" " the required format from file extension."); } diff --git a/Applications/Utils/FileConverter/ConvertSHPToGLI.cpp b/Applications/Utils/FileConverter/ConvertSHPToGLI.cpp index 48c7362a712d7ba9b12e20a29cd2e2837b1051fe..10c2c6f755f302c9532a2ec0e7488a27bf9a0d0b 100644 --- a/Applications/Utils/FileConverter/ConvertSHPToGLI.cpp +++ b/Applications/Utils/FileConverter/ConvertSHPToGLI.cpp @@ -13,38 +13,39 @@ */ // STL +#include <tclap/CmdLine.h> + #include <fstream> #include <vector> -#include <tclap/CmdLine.h> - // ShapeLib #include <shapefil.h> -#include "InfoLib/GitInfo.h" #include "GeoLib/GEOObjects.h" #include "GeoLib/IO/XmlIO/Qt/XmlGmlInterface.h" #include "GeoLib/IO/XmlIO/Qt/XmlStnInterface.h" #include "GeoLib/Point.h" #include "GeoLib/Station.h" +#include "InfoLib/GitInfo.h" -void convertPoints (DBFHandle dbf_handle, - std::string const& out_fname, - std::size_t x_id, - std::size_t y_id, - std::size_t z_id, - std::vector<std::size_t> const& name_component_ids, - std::string& points_group_name, - bool station) +void convertPoints(DBFHandle dbf_handle, + std::string const& out_fname, + std::size_t x_id, + std::size_t y_id, + std::size_t z_id, + std::vector<std::size_t> const& name_component_ids, + std::string& points_group_name, + bool station) { - int n_records (DBFGetRecordCount (dbf_handle)); + int n_records(DBFGetRecordCount(dbf_handle)); INFO("Reading {:d} records.", n_records); auto points = std::make_unique<std::vector<GeoLib::Point*>>(); - points->reserve (n_records); + points->reserve(n_records); std::string name; - for (int k = 0; k < n_records; k++) { + for (int k = 0; k < n_records; k++) + { double x(DBFReadDoubleAttribute(dbf_handle, k, x_id)); double y(DBFReadDoubleAttribute(dbf_handle, k, y_id)); double z(0.0); @@ -54,7 +55,8 @@ void convertPoints (DBFHandle dbf_handle, } name.clear(); - if (!name_component_ids.empty()) { + if (!name_component_ids.empty()) + { for (unsigned long name_component_id : name_component_ids) { if (name_component_id != @@ -71,10 +73,13 @@ void convertPoints (DBFHandle dbf_handle, name = std::to_string(k); } - if (station) { + if (station) + { GeoLib::Station* pnt(GeoLib::Station::createStation(name, x, y, z)); points->push_back(pnt); - } else { + } + else + { GeoLib::Point* pnt(new GeoLib::Point(x, y, z)); points->push_back(pnt); } @@ -90,18 +95,22 @@ void convertPoints (DBFHandle dbf_handle, geo_objs.addPointVec(std::move(points), points_group_name); } - if (station) { - GeoLib::IO::XmlStnInterface xml (geo_objs); + if (station) + { + GeoLib::IO::XmlStnInterface xml(geo_objs); xml.export_name = points_group_name; BaseLib::IO::writeStringToFile(xml.writeToString(), out_fname); - } else { - GeoLib::IO::XmlGmlInterface xml (geo_objs); + } + else + { + GeoLib::IO::XmlGmlInterface xml(geo_objs); xml.export_name = points_group_name; BaseLib::IO::writeStringToFile(xml.writeToString(), out_fname); } } -void printFieldInformationTable(DBFHandle const& dbf_handle, std::size_t n_fields) +void printFieldInformationTable(DBFHandle const& dbf_handle, + std::size_t n_fields) { char* field_name(new char[256]); int width(0); @@ -111,7 +120,8 @@ void printFieldInformationTable(DBFHandle const& dbf_handle, std::size_t n_field out << "************************************************" << std::endl; out << "field idx | name of field | data type of field " << std::endl; out << "------------------------------------------------" << std::endl; - for (std::size_t field_idx(0); field_idx < n_fields; field_idx++) { + for (std::size_t field_idx(0); field_idx < n_fields; field_idx++) + { DBFGetFieldInfo(dbf_handle, field_idx, field_name, &width, &n_decimals); if (field_idx < 10) { @@ -129,19 +139,20 @@ void printFieldInformationTable(DBFHandle const& dbf_handle, std::size_t n_field out << field_name_str << " |"; char native_field_type(DBFGetNativeFieldType(dbf_handle, field_idx)); - switch (native_field_type) { - case 'C': - out << " string" << std::endl; - break; - case 'F': - out << " float" << std::endl; - break; - case 'N': - out << " numeric" << std::endl; - break; - default: - out << " n_decimal " << n_decimals << std::endl; - break; + switch (native_field_type) + { + case 'C': + out << " string" << std::endl; + break; + case 'F': + out << " float" << std::endl; + break; + case 'N': + out << " numeric" << std::endl; + break; + default: + out << " n_decimal " << n_decimals << std::endl; + break; } } delete[] field_name; @@ -149,7 +160,7 @@ void printFieldInformationTable(DBFHandle const& dbf_handle, std::size_t n_field INFO("{:s}", out.str()); } -int main (int argc, char* argv[]) +int main(int argc, char* argv[]) { TCLAP::CmdLine cmd( "Converts points contained in shape file\n\n" @@ -165,23 +176,24 @@ int main (int argc, char* argv[]) true, "", "shape file"); - cmd.add( shapefile_arg ); + cmd.add(shapefile_arg); cmd.parse(argc, argv); - std::string fname (shapefile_arg.getValue()); + std::string fname(shapefile_arg.getValue()); int shape_type; int number_of_elements; - SHPHandle hSHP = SHPOpen(fname.c_str(),"rb"); - if (hSHP) { + SHPHandle hSHP = SHPOpen(fname.c_str(), "rb"); + if (hSHP) + { SHPGetInfo(hSHP, &number_of_elements, &shape_type, nullptr /*padfMinBound*/, nullptr /*padfMinBound*/); if ((shape_type - 1) % 10 == 0) INFO("Shape file contains {:d} points.", number_of_elements); - if ( ((shape_type - 3) % 10 == 0 || (shape_type - 5) % 10 == 0)) + if (((shape_type - 3) % 10 == 0 || (shape_type - 5) % 10 == 0)) { ERR("Shape file contains {:d} polylines.", number_of_elements); ERR("This programme only handles only files containing points."); @@ -189,12 +201,14 @@ int main (int argc, char* argv[]) return EXIT_SUCCESS; } SHPClose(hSHP); - } else { + } + else + { ERR("Could not open shapefile {:s}.", fname); } - DBFHandle dbf_handle = DBFOpen(fname.c_str(),"rb"); - if(dbf_handle) + DBFHandle dbf_handle = DBFOpen(fname.c_str(), "rb"); + if (dbf_handle) { std::size_t n_fields(DBFGetFieldCount(dbf_handle)); printFieldInformationTable(dbf_handle, n_fields); @@ -202,11 +216,17 @@ int main (int argc, char* argv[]) std::size_t x_id; std::size_t y_id; std::size_t z_id; - INFO("Please give the field idx that should be used for reading the x coordinate: "); + INFO( + "Please give the field idx that should be used for reading the x " + "coordinate: "); std::cin >> x_id; - INFO("Please give the field idx that should be used for reading the y coordinate: "); + INFO( + "Please give the field idx that should be used for reading the y " + "coordinate: "); std::cin >> y_id; - INFO("Please give the field idx that should be used for reading the z coordinate: "); + INFO( + "Please give the field idx that should be used for reading the z " + "coordinate: "); std::cin >> z_id; if (z_id > n_fields) @@ -218,12 +238,15 @@ int main (int argc, char* argv[]) INFO("Please give the number of fields that should be added to name: "); std::cin >> n_name_components; - std::vector<std::size_t> name_component_ids (n_name_components, - std::numeric_limits<std::size_t>::max()); - if (n_name_components != 0) { + std::vector<std::size_t> name_component_ids( + n_name_components, std::numeric_limits<std::size_t>::max()); + if (n_name_components != 0) + { for (std::size_t j(0); j < n_name_components; j++) { - INFO("- please give the field idx that should be used for reading the name: "); + INFO( + "- please give the field idx that should be used for " + "reading the name: "); std::cin >> name_component_ids[j]; } } @@ -235,9 +258,11 @@ int main (int argc, char* argv[]) } } - std::size_t station (0); + std::size_t station(0); - INFO("Should I read the information as GeoLib::Station (0) or as GeoLib::Point (1)? Please give the number: "); + INFO( + "Should I read the information as GeoLib::Station (0) or as " + "GeoLib::Point (1)? Please give the number: "); std::cin >> station; std::string fname_base(fname); @@ -259,9 +284,11 @@ int main (int argc, char* argv[]) name_component_ids, fname_base, station == 0); - DBFClose (dbf_handle); + DBFClose(dbf_handle); INFO("\tok."); - } else { + } + else + { ERR("Could not open the database file."); } diff --git a/Applications/Utils/FileConverter/FEFLOW2OGS.cpp b/Applications/Utils/FileConverter/FEFLOW2OGS.cpp index f060e7087fb0e882d51f0ee38d7e3e9be0ed4575..ac3fe6d8be76d1dbad051a6925a22c87d7abcaba 100644 --- a/Applications/Utils/FileConverter/FEFLOW2OGS.cpp +++ b/Applications/Utils/FileConverter/FEFLOW2OGS.cpp @@ -7,29 +7,28 @@ * */ -#include <string> #include <memory> +#include <string> // ThirdParty #include <tclap/CmdLine.h> // BaseLib -#include "InfoLib/GitInfo.h" #include "BaseLib/FileTools.h" #include "BaseLib/RunTime.h" +#include "InfoLib/GitInfo.h" #ifndef WIN32 #include "BaseLib/MemWatch.h" #endif // FileIO #include "Applications/FileIO/FEFLOW/FEFLOWMeshInterface.h" - -#include "MeshLib/IO/writeMeshToFile.h" #include "MeshLib/IO/Legacy/MeshIO.h" #include "MeshLib/IO/VtkIO/VtuInterface.h" +#include "MeshLib/IO/writeMeshToFile.h" #include "MeshLib/Mesh.h" -int main (int argc, char* argv[]) +int main(int argc, char* argv[]) { TCLAP::CmdLine cmd( "Converting a mesh in FEFLOW file format (ASCII, version 5.4) to a vtk " @@ -45,19 +44,15 @@ int main (int argc, char* argv[]) TCLAP::ValueArg<std::string> ogs_mesh_arg( "o", "out", - "filename for output mesh (if extension is msh, old OGS fileformat is written)", + "filename for output mesh (if extension is msh, old OGS fileformat is " + "written)", true, "", "filename as string"); cmd.add(ogs_mesh_arg); TCLAP::ValueArg<std::string> feflow_mesh_arg( - "i", - "in", - "FEFLOW input file (*.fem)", - true, - "", - "filename as string"); + "i", "in", "FEFLOW input file (*.fem)", true, "", "filename as string"); cmd.add(feflow_mesh_arg); cmd.parse(argc, argv); @@ -66,7 +61,7 @@ int main (int argc, char* argv[]) INFO("Reading {:s}.", feflow_mesh_arg.getValue()); #ifndef WIN32 BaseLib::MemWatch mem_watch; - unsigned long mem_without_mesh (mem_watch.getVirtMemUsage()); + unsigned long mem_without_mesh(mem_watch.getVirtMemUsage()); #endif BaseLib::RunTime run_time; run_time.start(); @@ -74,12 +69,13 @@ int main (int argc, char* argv[]) std::unique_ptr<MeshLib::Mesh const> mesh( feflowIO.readFEFLOWFile(feflow_mesh_arg.getValue())); - if (mesh == nullptr) { + if (mesh == nullptr) + { INFO("Could not read mesh from {:s}.", feflow_mesh_arg.getValue()); return EXIT_FAILURE; } #ifndef WIN32 - unsigned long mem_with_mesh (mem_watch.getVirtMemUsage()); + unsigned long mem_with_mesh(mem_watch.getVirtMemUsage()); INFO("Mem for mesh: {} MiB", (mem_with_mesh - mem_without_mesh) / (1024 * 1024)); #endif @@ -93,4 +89,3 @@ int main (int argc, char* argv[]) INFO("\tDone."); return EXIT_SUCCESS; } - diff --git a/Applications/Utils/FileConverter/GMSH2OGS.cpp b/Applications/Utils/FileConverter/GMSH2OGS.cpp index eea94851845e30fa67068ac7da9a9ca8da97a1d0..350be21df762209e7a0988d164772cfa5f9cb9a8 100644 --- a/Applications/Utils/FileConverter/GMSH2OGS.cpp +++ b/Applications/Utils/FileConverter/GMSH2OGS.cpp @@ -13,16 +13,16 @@ */ // STL -#include <string> #include <algorithm> +#include <string> // ThirdParty #include <tclap/CmdLine.h> // BaseLib -#include "InfoLib/GitInfo.h" #include "BaseLib/FileTools.h" #include "BaseLib/RunTime.h" +#include "InfoLib/GitInfo.h" #ifndef WIN32 #include "BaseLib/MemWatch.h" #endif @@ -131,7 +131,7 @@ static void identifyAndWriteBoundaryMeshes( } } -int main (int argc, char* argv[]) +int main(int argc, char* argv[]) { TCLAP::CmdLine cmd( "Converting meshes in gmsh file format (ASCII, version 2.2) to a vtk " @@ -147,19 +147,16 @@ int main (int argc, char* argv[]) TCLAP::ValueArg<std::string> ogs_mesh_arg( "o", "out", - "filename for output mesh (if extension is .msh, old OGS-5 fileformat is written, if extension is .vtu, a vtk unstructure grid file is written (OGS-6 mesh format))", + "filename for output mesh (if extension is .msh, old OGS-5 fileformat " + "is written, if extension is .vtu, a vtk unstructure grid file is " + "written (OGS-6 mesh format))", true, "", "filename as string"); cmd.add(ogs_mesh_arg); TCLAP::ValueArg<std::string> gmsh_mesh_arg( - "i", - "in", - "gmsh input file", - true, - "", - "filename as string"); + "i", "in", "gmsh input file", true, "", "filename as string"); cmd.add(gmsh_mesh_arg); TCLAP::SwitchArg valid_arg("v", "validation", "validate the mesh"); @@ -169,7 +166,8 @@ int main (int argc, char* argv[]) "b", "boundaries", "if set, boundary meshes will be generated"); cmd.add(create_boundary_meshes_arg); - TCLAP::SwitchArg exclude_lines_arg("e", "exclude-lines", + TCLAP::SwitchArg exclude_lines_arg( + "e", "exclude-lines", "if set, lines will not be written to the ogs mesh"); cmd.add(exclude_lines_arg); @@ -179,14 +177,14 @@ int main (int argc, char* argv[]) INFO("Reading {:s}.", gmsh_mesh_arg.getValue()); #ifndef WIN32 BaseLib::MemWatch mem_watch; - unsigned long mem_without_mesh (mem_watch.getVirtMemUsage()); + unsigned long mem_without_mesh(mem_watch.getVirtMemUsage()); #endif BaseLib::RunTime run_time; run_time.start(); - MeshLib::Mesh* mesh( - FileIO::GMSH::readGMSHMesh(gmsh_mesh_arg.getValue())); + MeshLib::Mesh* mesh(FileIO::GMSH::readGMSHMesh(gmsh_mesh_arg.getValue())); - if (mesh == nullptr) { + if (mesh == nullptr) + { INFO("Could not read mesh from {:s}.", gmsh_mesh_arg.getValue()); return -1; } @@ -278,4 +276,3 @@ int main (int argc, char* argv[]) delete mesh; } - diff --git a/Applications/Utils/FileConverter/GocadTSurfaceReader.cpp b/Applications/Utils/FileConverter/GocadTSurfaceReader.cpp index eac31c6a5a87fe1e41da179a6f58b946e84c9007..ab34df0fa9f065bc48d7ec4691fd657d90dbf7a1 100644 --- a/Applications/Utils/FileConverter/GocadTSurfaceReader.cpp +++ b/Applications/Utils/FileConverter/GocadTSurfaceReader.cpp @@ -9,10 +9,10 @@ #include <tclap/CmdLine.h> +#include "Applications/FileIO/GocadIO/GocadAsciiReader.h" #include "InfoLib/GitInfo.h" -#include "MeshLib/Mesh.h" #include "MeshLib/IO/VtkIO/VtuInterface.h" -#include "Applications/FileIO/GocadIO/GocadAsciiReader.h" +#include "MeshLib/Mesh.h" std::string getDelim(std::string const& str) { @@ -68,7 +68,7 @@ int main(int argc, char* argv[]) return 2; } - std::string const file_name (input_arg.getValue()); + std::string const file_name(input_arg.getValue()); FileIO::Gocad::DataType t(FileIO::Gocad::DataType::ALL); if (export_lines_arg.isSet()) diff --git a/Applications/Utils/FileConverter/Mesh2Raster.cpp b/Applications/Utils/FileConverter/Mesh2Raster.cpp index e2c9e8ea8877e682b0ce6f9f714d885cd05ff869..27ad44ee22b1e735c53cbb0c60d1b71aeb302afa 100644 --- a/Applications/Utils/FileConverter/Mesh2Raster.cpp +++ b/Applications/Utils/FileConverter/Mesh2Raster.cpp @@ -109,7 +109,8 @@ int main(int argc, char* argv[]) // centre of the pixel is located within a mesh element if (element != nullptr) { - out << MeshLib::ProjectPointOnMesh::getElevation(*element, node) << " "; + out << MeshLib::ProjectPointOnMesh::getElevation(*element, node) + << " "; } else { diff --git a/Applications/Utils/FileConverter/NetCdfConverter.cpp b/Applications/Utils/FileConverter/NetCdfConverter.cpp index ee414a6185321c94f41f5dcaa1b8ec679f32339a..b199acb1e34500b2cb9d29d1e8062b613ad3bf05 100644 --- a/Applications/Utils/FileConverter/NetCdfConverter.cpp +++ b/Applications/Utils/FileConverter/NetCdfConverter.cpp @@ -188,7 +188,7 @@ static void flipRaster(std::vector<double>& data, std::size_t const layers, tmp_vec.reserve(length); for (std::size_t k = 0; k < layers; k++) { - std::size_t const layer_end = (k+1) * height * width; + std::size_t const layer_end = (k + 1) * height * width; for (std::size_t i = 0; i < height; i++) { std::size_t const line_idx(layer_end - (width * (i + 1))); @@ -205,7 +205,8 @@ static bool canConvert(NcVar const& var) { bool ret(var.getDimCount() < 2); if (ret) - ERR("Only 2+ dimensional variables can be converted into OGS Meshes.\n"); + ERR("Only 2+ dimensional variables can be converted into OGS " + "Meshes.\n"); return !ret; } @@ -224,7 +225,7 @@ static std::string arraySelectionLoop(NcFile const& dataset) } static bool dimensionSelectionLoop(NcVar const& var, - std::vector<std::size_t>& dim_idx_map) + std::vector<std::size_t>& dim_idx_map) { showArraysDims(var); std::size_t const n_dims(var.getDimCount()); @@ -272,9 +273,11 @@ static bool dimensionSelectionLoop(NcVar const& var, { dim_idx_map[i] = std::numeric_limits<std::size_t>::max(); - std::string const request_str("Enter ID for dimension " + std::to_string(i) + - " " + dim_comment[i - start_idx] + ": "); - std::size_t const idx = parseInput(request_str, var.getDimCount(), true); + std::string const request_str("Enter ID for dimension " + + std::to_string(i) + " " + + dim_comment[i - start_idx] + ": "); + std::size_t const idx = + parseInput(request_str, var.getDimCount(), true); if (static_cast<int>(idx) == var.getDimCount()) { @@ -297,11 +300,13 @@ static std::pair<std::size_t, std::size_t> timestepSelectionLoop( std::cout << "\nThe dataset contains " << n_time_steps << " time steps.\n"; while (bounds.first == max_val) { - bounds.first = parseInput("Specify first time step to export: ", n_time_steps, false); + bounds.first = parseInput( + "Specify first time step to export: ", n_time_steps, false); } while (bounds.first > bounds.second || bounds.second > n_time_steps) { - bounds.second = parseInput( "Specify last time step to export: ", n_time_steps, false); + bounds.second = parseInput( + "Specify last time step to export: ", n_time_steps, false); } return bounds; } @@ -352,7 +357,8 @@ static OutputType multFilesSelectionLoop( OutputType t = OutputType::INVALID; while (t == OutputType::INVALID) { - std::size_t const n_time_steps(time_bounds.second - time_bounds.first + 1); + std::size_t const n_time_steps(time_bounds.second - time_bounds.first + + 1); std::cout << "\nThe selection includes " << n_time_steps << " time steps.\n"; std::cout << "0. Save data in " << n_time_steps @@ -361,7 +367,8 @@ static OutputType multFilesSelectionLoop( << " scalar arrays.\n"; std::cout << "2. Save data as " << n_time_steps << " ASC images.\n"; - std::size_t const ret = parseInput("Select preferred method: ", 3, false); + std::size_t const ret = + parseInput("Select preferred method: ", 3, false); if (ret == 0) t = OutputType::MULTIMESH; @@ -383,7 +390,7 @@ static std::string getIterationString(std::size_t i, std::size_t max) static double getResolution(NcFile const& dataset, NcVar const& var) { std::size_t const dim_idx = var.getDimCount() - 1; - NcVar const dim_var (getDimVar(dataset, var, dim_idx)); + NcVar const dim_var(getDimVar(dataset, var, dim_idx)); auto const bounds = (dim_var.isNull()) ? getDimLength(var, dim_idx) : getBoundaries(dim_var); std::size_t const dim_size = var.getDim(dim_idx).getSize(); @@ -392,7 +399,8 @@ static double getResolution(NcFile const& dataset, NcVar const& var) OGS_FATAL("Dimension '{:s}' has size 0. Aborting...", var.getDim(dim_idx).getName()); } - return std::fabs(bounds.second - bounds.first) / static_cast<double>(dim_size); + return std::fabs(bounds.second - bounds.first) / + static_cast<double>(dim_size); } static GeoLib::RasterHeader createRasterHeader( @@ -408,10 +416,14 @@ static GeoLib::RasterHeader createRasterHeader( (n_dims - time_offset == 3) ? length[dim_idx_map.back()] : 1; return {length[dim_idx_map[0 + time_offset]], length[dim_idx_map[1 + time_offset]], - z_length, origin, res, no_data_output}; + z_length, + origin, + res, + no_data_output}; } -static std::vector<std::size_t> getLength(NcVar const& var, std::size_t const time_offset) +static std::vector<std::size_t> getLength(NcVar const& var, + std::size_t const time_offset) { std::size_t const n_dims = (var.getDimCount()); std::vector<std::size_t> length(n_dims, 1); @@ -423,9 +435,9 @@ static std::vector<std::size_t> getLength(NcVar const& var, std::size_t const ti } static std::vector<double> getData(NcFile const& dataset, NcVar const& var, - std::size_t const total_length, - std::size_t const time_step, - std::vector<std::size_t> const& length) + std::size_t const total_length, + std::size_t const time_step, + std::vector<std::size_t> const& length) { std::size_t const n_dims(var.getDimCount()); std::vector<std::size_t> offset(n_dims, 0); @@ -441,11 +453,11 @@ static std::vector<double> getData(NcFile const& dataset, NcVar const& var, } 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) + 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) { std::size_t dim_param_count = 0; if (arg_dim_time.isSet()) @@ -460,7 +472,8 @@ static bool assignDimParams(NcVar const& var, std::size_t const n_dims = var.getDimCount(); if (dim_param_count != n_dims) { - ERR("Number of parameters set does not fit number of parameters for specified variable."); + ERR("Number of parameters set does not fit number of parameters for " + "specified variable."); return false; } @@ -491,7 +504,8 @@ static std::pair<std::size_t, std::size_t> assignTimeBounds( auto const bounds = getBoundaries(var); if (arg_time_start.getValue() > bounds.second) { - ERR("Start time step larger than total number of time steps. Resetting to 0."); + ERR("Start time step larger than total number of time steps. Resetting " + "to 0."); arg_time_start.reset(); } @@ -500,7 +514,8 @@ static std::pair<std::size_t, std::size_t> assignTimeBounds( if (arg_time_end.getValue() > bounds.second) { - ERR("End time step larger than total number of time steps. Resetting to starting time step"); + ERR("End time step larger than total number of time steps. Resetting " + "to starting time step"); return {arg_time_start.getValue(), arg_time_start.getValue()}; } @@ -542,8 +557,10 @@ static bool convert(NcFile const& dataset, NcVar const& var, length.cbegin(), length.cend(), 1, std::multiplies<std::size_t>()); for (std::size_t i = time_bounds.first; i <= time_bounds.second; ++i) { - std::string const step_str = (time_bounds.first != time_bounds.second) - ? std::string(" time step " + std::to_string(i)) : ""; + std::string const step_str = + (time_bounds.first != time_bounds.second) + ? std::string(" time step " + std::to_string(i)) + : ""; std::cout << "Converting" << step_str << "...\n"; std::vector<double> data_vec = getData(dataset, var, array_length, i, length); @@ -558,7 +575,8 @@ static bool convert(NcFile const& dataset, NcVar const& var, { std::size_t n_layers = (length.size() - time_offset == 3) ? length[n_dims - 3] : 1; - flipRaster(data_vec, n_layers, length[n_dims - 1], length[n_dims - 2]); + flipRaster(data_vec, n_layers, length[n_dims - 1], + length[n_dims - 2]); } GeoLib::RasterHeader const header = @@ -603,19 +621,22 @@ static bool convert(NcFile const& dataset, NcVar const& var, MeshLib::IO::VtuInterface vtu(mesh.get()); std::string const output_file_name = (BaseLib::getFileExtension(output_name) == ".vtu") - ? output_name : output_name + ".vtu"; + ? output_name + : output_name + ".vtu"; vtu.writeToFile(output_file_name); } } - else //OutputType::IMAGES + else // OutputType::IMAGES { - GeoLib::Raster const raster( - header, data_vec.data(), - data_vec.data() + header.n_cols * header.n_rows * header.n_depth); + GeoLib::Raster const raster(header, data_vec.data(), + data_vec.data() + header.n_cols * + header.n_rows * + header.n_depth); std::string const output_file_name( BaseLib::dropFileExtension(output_name) + getIterationString(i, time_bounds.second) + ".asc"); - FileIO::AsciiRasterInterface::writeRasterAsASC(raster, output_file_name); + FileIO::AsciiRasterInterface::writeRasterAsASC(raster, + output_file_name); } } return true; @@ -634,7 +655,8 @@ int main(int argc, char* argv[]) TCLAP::ValueArg<int> arg_nodata( "n", "nodata", - "explicitly specifies the no data value used in the dataset (usually it is not necessary to set this)", + "explicitly specifies the no data value used in the dataset (usually " + "it is not necessary to set this)", false, no_data_input, "integer specifying no data value"); cmd.add(arg_nodata); @@ -683,8 +705,7 @@ int main(int argc, char* argv[]) TCLAP::ValueArg<std::size_t> arg_dim2( "", "dim2", - "index of second dimension (y/latitude) for the selected " - "variable", + "index of second dimension (y/latitude) for the selected variable", false, 0, &allowed_dim_vals); cmd.add(arg_dim2); @@ -752,11 +773,12 @@ int main(int argc, char* argv[]) } std::vector<std::size_t> dim_idx_map(var.getDimCount(), 0); - bool is_time_dep (false); + bool is_time_dep(false); if (arg_dim1.isSet() && arg_dim2.isSet()) { is_time_dep = arg_dim_time.isSet(); - if (!assignDimParams(var, dim_idx_map, arg_dim_time, arg_dim1, arg_dim2, arg_dim3)) + if (!assignDimParams(var, dim_idx_map, arg_dim_time, arg_dim1, arg_dim2, + arg_dim3)) return EXIT_FAILURE; } else @@ -766,7 +788,8 @@ int main(int argc, char* argv[]) std::pair<std::size_t, std::size_t> time_bounds(0, 0); if (is_time_dep) - time_bounds = (arg_time_start.isSet()) + time_bounds = + (arg_time_start.isSet()) ? assignTimeBounds(getDimVar(dataset, var, dim_idx_map[0]), arg_time_start, arg_time_end) : timestepSelectionLoop(var, dim_idx_map[0]); @@ -781,7 +804,7 @@ int main(int argc, char* argv[]) output = OutputType::MULTIMESH; } else if (arg_single_file.isSet() || !is_time_dep || - time_bounds.first == time_bounds.second) + time_bounds.first == time_bounds.second) { output = OutputType::SINGLEMESH; } diff --git a/Applications/Utils/FileConverter/OGS2VTK.cpp b/Applications/Utils/FileConverter/OGS2VTK.cpp index d538783ff9544875db5fa4030f87dc47b1519c2a..3d8aa3c05f5b6744b1e04a19649e080d68e6474c 100644 --- a/Applications/Utils/FileConverter/OGS2VTK.cpp +++ b/Applications/Utils/FileConverter/OGS2VTK.cpp @@ -11,17 +11,17 @@ * http://www.opengeosys.org/project/license */ -#include <string> -#include <memory> - #include <tclap/CmdLine.h> +#include <memory> +#include <string> + #include "InfoLib/GitInfo.h" #include "MeshLib/IO/VtkIO/VtuInterface.h" #include "MeshLib/IO/readMeshFromFile.h" #include "MeshLib/Mesh.h" -int main (int argc, char* argv[]) +int main(int argc, char* argv[]) { TCLAP::CmdLine cmd( "Converts OGS mesh into VTK mesh.\n\n" diff --git a/Applications/Utils/FileConverter/TIN2VTK.cpp b/Applications/Utils/FileConverter/TIN2VTK.cpp index 2226293cd5e48dd56bdc39a4e86c987ab9ed20b3..11877aed731b29b261f130109b9470d53d0fe96a 100644 --- a/Applications/Utils/FileConverter/TIN2VTK.cpp +++ b/Applications/Utils/FileConverter/TIN2VTK.cpp @@ -8,30 +8,28 @@ */ // STL +#include <tclap/CmdLine.h> + #include <memory> #include <string> #include <vector> -#include <tclap/CmdLine.h> - // BaseLib -#include "InfoLib/GitInfo.h" #include "BaseLib/FileTools.h" +#include "InfoLib/GitInfo.h" // GeoLib +#include "GeoLib/IO/TINInterface.h" #include "GeoLib/Point.h" -#include "GeoLib/Surface.h" #include "GeoLib/PointVec.h" -#include "GeoLib/IO/TINInterface.h" - +#include "GeoLib/Surface.h" #include "MeshLib/IO/VtkIO/VtuInterface.h" // MeshLib #include "MeshLib/Mesh.h" #include "MeshLib/convertMeshToGeo.h" - -int main (int argc, char* argv[]) +int main(int argc, char* argv[]) { TCLAP::CmdLine cmd( "Converts TIN file into VTU file.\n\n" @@ -41,13 +39,13 @@ int main (int argc, char* argv[]) "Copyright (c) 2012-2021, OpenGeoSys Community " "(http://www.opengeosys.org)", ' ', GitInfoLib::GitInfo::ogs_version); - TCLAP::ValueArg<std::string> inArg("i", "input-tin-file", - "the name of the file containing the input TIN", true, - "", "string"); + TCLAP::ValueArg<std::string> inArg( + "i", "input-tin-file", "the name of the file containing the input TIN", + true, "", "string"); cmd.add(inArg); - TCLAP::ValueArg<std::string> outArg("o", "output-vtu-file", - "the name of the file the mesh will be written to", true, - "", "string"); + TCLAP::ValueArg<std::string> outArg( + "o", "output-vtu-file", + "the name of the file the mesh will be written to", true, "", "string"); cmd.add(outArg); cmd.parse(argc, argv); @@ -65,7 +63,9 @@ int main (int argc, char* argv[]) sfc->getNumberOfTriangles()); INFO("converting to mesh data"); - std::unique_ptr<MeshLib::Mesh> mesh(MeshLib::convertSurfaceToMesh(*sfc, BaseLib::extractBaseNameWithoutExtension(tinFileName), std::numeric_limits<double>::epsilon())); + std::unique_ptr<MeshLib::Mesh> mesh(MeshLib::convertSurfaceToMesh( + *sfc, BaseLib::extractBaseNameWithoutExtension(tinFileName), + std::numeric_limits<double>::epsilon())); INFO("Mesh created: {:d} nodes, {:d} elements.", mesh->getNumberOfNodes(), mesh->getNumberOfElements()); diff --git a/Applications/Utils/FileConverter/TecPlotTools.cpp b/Applications/Utils/FileConverter/TecPlotTools.cpp index bf6d1183d3a03b410c63b7081342f8fbfcaa0a6b..796e1bd9337b7b56dee0721580064edcbfda4e61 100644 --- a/Applications/Utils/FileConverter/TecPlotTools.cpp +++ b/Applications/Utils/FileConverter/TecPlotTools.cpp @@ -21,7 +21,8 @@ #include "MeshLib/Mesh.h" #include "MeshLib/MeshGenerators/RasterToMesh.h" -/// Returns the value for the given parameter name (i.e. for "x = 3" it returns "3") +/// Returns the value for the given parameter name (i.e. for "x = 3" it returns +/// "3") std::string getValue(std::string const& line, std::string const& val_name, bool is_string) @@ -111,7 +112,8 @@ std::vector<std::string> getVariables(std::string const& line) { std::string const var_str("VARIABLES"); std::size_t start(line.find(var_str)); - std::string all_vars = line.substr(start + var_str.length(), std::string::npos); + std::string all_vars = + line.substr(start + var_str.length(), std::string::npos); start = all_vars.find("="); all_vars = all_vars.substr(start + 1, std::string::npos); BaseLib::trim(all_vars); @@ -185,7 +187,8 @@ void writeTecPlotSection(std::ofstream& out, { std::size_t const delim_pos(file_name.find_last_of(".")); std::string const base_name(file_name.substr(0, delim_pos + 1)); - std::string const extension(file_name.substr(delim_pos, std::string::npos)); + std::string const extension( + file_name.substr(delim_pos, std::string::npos)); val_count = 0; val_total = 0; @@ -219,7 +222,8 @@ int writeDataToMesh(std::string const& file_name, } GeoLib::Point origin(0, 0, 0); - GeoLib::RasterHeader header{dims.first, dims.second, 1, origin, cellsize, -9999}; + GeoLib::RasterHeader header{dims.first, dims.second, 1, + origin, cellsize, -9999}; std::unique_ptr<MeshLib::Mesh> mesh( MeshLib::RasterToMesh::convert(scalars[0].data(), @@ -238,7 +242,8 @@ int writeDataToMesh(std::string const& file_name, return -5; } prop->reserve(scalars[i].size()); - std::copy(scalars[i].cbegin(), scalars[i].cend(), std::back_inserter(*prop)); + std::copy(scalars[i].cbegin(), scalars[i].cend(), + std::back_inserter(*prop)); } std::size_t const delim_pos(file_name.find_last_of(".")); @@ -282,7 +287,8 @@ int splitFile(std::ifstream& in, std::string const& file_name) { return -3; } - writeTecPlotSection(out, file_name, write_count, val_count, val_total); + writeTecPlotSection(out, file_name, write_count, val_count, + val_total); out << line << "\n"; continue; } @@ -292,7 +298,8 @@ int splitFile(std::ifstream& in, std::string const& file_name) { return -3; } - writeTecPlotSection(out, file_name, write_count, val_count, val_total); + writeTecPlotSection(out, file_name, write_count, val_count, + val_total); out << line << "\n"; continue; } @@ -302,7 +309,8 @@ int splitFile(std::ifstream& in, std::string const& file_name) { return -3; } - writeTecPlotSection(out, file_name, write_count, val_count, val_total); + writeTecPlotSection(out, file_name, write_count, val_count, + val_total); out << line << "\n"; name = getName(line); std::pair<std::size_t, std::size_t> dims = getDimensions(line); @@ -324,7 +332,8 @@ int splitFile(std::ifstream& in, std::string const& file_name) return 0; } -/// Converts a TecPlot file into one or more OGS-meshes (one mesh per section/zone) +/// Converts a TecPlot file into one or more OGS-meshes (one mesh per +/// section/zone) int convertFile(std::ifstream& in, std::string const& file_name) { std::string line; @@ -354,7 +363,8 @@ int convertFile(std::ifstream& in, std::string const& file_name) } if (val_count != 0) { - writeDataToMesh(file_name, write_count, var_names, scalars, dims); + writeDataToMesh(file_name, write_count, var_names, scalars, + dims); resetDataStructures(var_names.size(), scalars, val_count); } continue; @@ -367,7 +377,8 @@ int convertFile(std::ifstream& in, std::string const& file_name) { return -3; } - writeDataToMesh(file_name, write_count, var_names, scalars, dims); + writeDataToMesh(file_name, write_count, var_names, scalars, + dims); } var_names.clear(); var_names = getVariables(line); @@ -382,7 +393,8 @@ int convertFile(std::ifstream& in, std::string const& file_name) { return -3; } - writeDataToMesh(file_name, write_count, var_names, scalars, dims); + writeDataToMesh(file_name, write_count, var_names, scalars, + dims); resetDataStructures(var_names.size(), scalars, val_count); } name = getName(line); @@ -450,10 +462,10 @@ int main(int argc, char* argv[]) "(http://www.opengeosys.org)", ' ', GitInfoLib::GitInfo::ogs_version); TCLAP::SwitchArg split_arg("s", "split", - "split time steps into separate files"); + "split time steps into separate files"); cmd.add(split_arg); TCLAP::SwitchArg convert_arg("c", "convert", - "convert TecPlot data into OGS meshes"); + "convert TecPlot data into OGS meshes"); cmd.add(convert_arg); TCLAP::ValueArg<std::string> output_arg( "o", "output-file", "output mesh file", false, "", "string"); @@ -488,8 +500,8 @@ int main(int argc, char* argv[]) return 0; } - std::string const filename = (output_arg.isSet()) ? - output_arg.getValue() : input_arg.getValue(); + std::string const filename = + (output_arg.isSet()) ? output_arg.getValue() : input_arg.getValue(); int return_val(0); if (split_arg.getValue()) { diff --git a/Applications/Utils/FileConverter/VTK2OGS.cpp b/Applications/Utils/FileConverter/VTK2OGS.cpp index 1d1f767f931c86c02390f80e95d1b7afa19e6258..7c17c2147f43a19cc7b762db6141d78e7d9dfb4a 100644 --- a/Applications/Utils/FileConverter/VTK2OGS.cpp +++ b/Applications/Utils/FileConverter/VTK2OGS.cpp @@ -12,16 +12,16 @@ */ // STL -#include <string> - #include <tclap/CmdLine.h> +#include <string> + #include "InfoLib/GitInfo.h" #include "MeshLib/IO/Legacy/MeshIO.h" #include "MeshLib/IO/VtkIO/VtuInterface.h" #include "MeshLib/Mesh.h" -int main (int argc, char* argv[]) +int main(int argc, char* argv[]) { TCLAP::CmdLine cmd( "Converts VTK mesh into OGS mesh.\n\n" @@ -31,17 +31,20 @@ int main (int argc, char* argv[]) "Copyright (c) 2012-2021, OpenGeoSys Community " "(http://www.opengeosys.org)", ' ', GitInfoLib::GitInfo::ogs_version); - TCLAP::ValueArg<std::string> mesh_in("i", "mesh-input-file", - "the name of the file containing the input mesh", true, - "", "file name of input mesh"); + TCLAP::ValueArg<std::string> mesh_in( + "i", "mesh-input-file", + "the name of the file containing the input mesh", true, "", + "file name of input mesh"); cmd.add(mesh_in); - TCLAP::ValueArg<std::string> mesh_out("o", "mesh-output-file", - "the name of the file the mesh will be written to", true, - "", "file name of output mesh"); + TCLAP::ValueArg<std::string> mesh_out( + "o", "mesh-output-file", + "the name of the file the mesh will be written to", true, "", + "file name of output mesh"); cmd.add(mesh_out); cmd.parse(argc, argv); - MeshLib::Mesh* mesh (MeshLib::IO::VtuInterface::readVTUFile(mesh_in.getValue())); + MeshLib::Mesh* mesh( + MeshLib::IO::VtuInterface::readVTUFile(mesh_in.getValue())); INFO("Mesh read: {:d} nodes, {:d} elements.", mesh->getNumberOfNodes(), mesh->getNumberOfElements()); diff --git a/Applications/Utils/FileConverter/VTK2TIN.cpp b/Applications/Utils/FileConverter/VTK2TIN.cpp index 4833a02621b6c9b8525196b695b10c4a45bd7ac0..4aec6bf6af811bd5d29216ad05158d31d206e884 100644 --- a/Applications/Utils/FileConverter/VTK2TIN.cpp +++ b/Applications/Utils/FileConverter/VTK2TIN.cpp @@ -8,31 +8,29 @@ */ // STL +#include <tclap/CmdLine.h> + +#include <fstream> #include <memory> #include <string> -#include <fstream> - -#include <tclap/CmdLine.h> // BaseLib -#include "InfoLib/GitInfo.h" #include "BaseLib/Logging.h" +#include "InfoLib/GitInfo.h" // GeoLib #include "GeoLib/GEOObjects.h" -#include "GeoLib/Surface.h" #include "GeoLib/IO/TINInterface.h" +#include "GeoLib/Surface.h" // MeshLib -#include "MeshLib/Mesh.h" #include "MeshLib/Elements/Element.h" +#include "MeshLib/IO/VtkIO/VtuInterface.h" +#include "MeshLib/Mesh.h" #include "MeshLib/Node.h" #include "MeshLib/convertMeshToGeo.h" -#include "MeshLib/IO/VtkIO/VtuInterface.h" - - -int main (int argc, char* argv[]) +int main(int argc, char* argv[]) { TCLAP::CmdLine cmd( "Converts VTK mesh into TIN file.\n\n" @@ -42,23 +40,27 @@ int main (int argc, char* argv[]) "Copyright (c) 2012-2021, OpenGeoSys Community " "(http://www.opengeosys.org)", ' ', GitInfoLib::GitInfo::ogs_version); - TCLAP::ValueArg<std::string> mesh_in("i", "mesh-input-file", - "the name of the file containing the input mesh", true, - "", "file name of input mesh"); + TCLAP::ValueArg<std::string> mesh_in( + "i", "mesh-input-file", + "the name of the file containing the input mesh", true, "", + "file name of input mesh"); cmd.add(mesh_in); - TCLAP::ValueArg<std::string> mesh_out("o", "TIN-output-file", - "the name of the file the TIN will be written to", true, - "", "file name of output TIN"); + TCLAP::ValueArg<std::string> mesh_out( + "o", "TIN-output-file", + "the name of the file the TIN will be written to", true, "", + "file name of output TIN"); cmd.add(mesh_out); cmd.parse(argc, argv); - std::unique_ptr<MeshLib::Mesh> mesh (MeshLib::IO::VtuInterface::readVTUFile(mesh_in.getValue())); + std::unique_ptr<MeshLib::Mesh> mesh( + MeshLib::IO::VtuInterface::readVTUFile(mesh_in.getValue())); INFO("Mesh read: {:d} nodes, {:d} elements.", mesh->getNumberOfNodes(), mesh->getNumberOfElements()); INFO("Converting the mesh to TIN"); GeoLib::GEOObjects geo_objects; - if (MeshLib::convertMeshToGeo(*mesh, geo_objects)) { + if (MeshLib::convertMeshToGeo(*mesh, geo_objects)) + { INFO("Writing TIN into the file"); GeoLib::IO::TINInterface::writeSurfaceAsTIN( *(*geo_objects.getSurfaceVec(mesh->getName()))[0], diff --git a/Applications/Utils/FileConverter/convertGEO.cpp b/Applications/Utils/FileConverter/convertGEO.cpp index af7129bc0a82601adcbf7b66ed1b2268a94f4362..2111ecb7f9a9d3b272354b26a596b5127b3cae63 100644 --- a/Applications/Utils/FileConverter/convertGEO.cpp +++ b/Applications/Utils/FileConverter/convertGEO.cpp @@ -7,19 +7,17 @@ * */ -#include <string> -#include <vector> - #include <tclap/CmdLine.h> -#include "InfoLib/GitInfo.h" +#include <string> +#include <vector> #include "Applications/FileIO/readGeometryFromFile.h" #include "Applications/FileIO/writeGeometryToFile.h" #include "GeoLib/GEOObjects.h" +#include "InfoLib/GitInfo.h" - -int main (int argc, char* argv[]) +int main(int argc, char* argv[]) { TCLAP::CmdLine cmd( "Converts OGS geometry file into another file format. " @@ -31,18 +29,20 @@ int main (int argc, char* argv[]) "Copyright (c) 2012-2021, OpenGeoSys Community " "(http://www.opengeosys.org)", ' ', GitInfoLib::GitInfo::ogs_version); - TCLAP::ValueArg<std::string> argInputFileName("i", "input-file", - "the name of the geometry file to be converted", true, - "", "file name"); + TCLAP::ValueArg<std::string> argInputFileName( + "i", "input-file", "the name of the geometry file to be converted", + true, "", "file name"); cmd.add(argInputFileName); - TCLAP::ValueArg<std::string> argOutputFileName("o", "output-file", - "the name of the new geometry file whose file format is guessed from its file extension", true, - "", "file name"); + TCLAP::ValueArg<std::string> argOutputFileName( + "o", "output-file", + "the name of the new geometry file whose file format is guessed from " + "its file extension", + true, "", "file name"); cmd.add(argOutputFileName); TCLAP::ValueArg<std::string> gmsh_path_arg("g", "gmsh-path", - "the path to the gmsh binary", false, - "", "path as string"); + "the path to the gmsh binary", + false, "", "path as string"); cmd.add(gmsh_path_arg); cmd.parse(argc, argv); @@ -52,7 +52,8 @@ int main (int argc, char* argv[]) auto const geo_names = geoObjects.getGeometryNames(); assert(geo_names.size() == 1); - FileIO::writeGeometryToFile(geo_names[0], geoObjects, argOutputFileName.getValue()); + FileIO::writeGeometryToFile(geo_names[0], geoObjects, + argOutputFileName.getValue()); return EXIT_SUCCESS; } diff --git a/Applications/Utils/FileConverter/generateMatPropsFromMatID.cpp b/Applications/Utils/FileConverter/generateMatPropsFromMatID.cpp index ec3ca9f05a0f519fab2dbdae7748f23562f2defa..329f076326aa7d1a6cec4d2611a0b4415b5a0ea7 100644 --- a/Applications/Utils/FileConverter/generateMatPropsFromMatID.cpp +++ b/Applications/Utils/FileConverter/generateMatPropsFromMatID.cpp @@ -12,20 +12,18 @@ * */ -#include <memory> - #include <tclap/CmdLine.h> -#include "InfoLib/GitInfo.h" -#include "BaseLib/FileTools.h" +#include <memory> +#include "BaseLib/FileTools.h" +#include "InfoLib/GitInfo.h" +#include "MeshLib/Elements/Element.h" #include "MeshLib/IO/readMeshFromFile.h" #include "MeshLib/IO/writeMeshToFile.h" - #include "MeshLib/Mesh.h" -#include "MeshLib/Elements/Element.h" -int main (int argc, char* argv[]) +int main(int argc, char* argv[]) { TCLAP::CmdLine cmd( "Creates a new file for material properties and sets the material ids " @@ -38,14 +36,14 @@ int main (int argc, char* argv[]) ' ', GitInfoLib::GitInfo::ogs_version); TCLAP::ValueArg<std::string> mesh_arg("m", - "mesh", - "the mesh to open from a file", - false, - "", - "filename for mesh input"); - cmd.add( mesh_arg ); - - cmd.parse( argc, argv ); + "mesh", + "the mesh to open from a file", + false, + "", + "filename for mesh input"); + cmd.add(mesh_arg); + + cmd.parse(argc, argv); // read mesh std::unique_ptr<MeshLib::Mesh> mesh( diff --git a/Applications/Utils/GeoTools/MoveGeometry.cpp b/Applications/Utils/GeoTools/MoveGeometry.cpp index 87c60334622be7e90ce0ce56ad262529df99c24f..c0e46cd3860c3c5da809b61d1d978791f3a914b1 100644 --- a/Applications/Utils/GeoTools/MoveGeometry.cpp +++ b/Applications/Utils/GeoTools/MoveGeometry.cpp @@ -14,13 +14,13 @@ // ThirdParty #include <tclap/CmdLine.h> -#include "InfoLib/GitInfo.h" +#include <QCoreApplication> + #include "GeoLib/GEOObjects.h" #include "GeoLib/IO/XmlIO/Qt/XmlGmlInterface.h" +#include "InfoLib/GitInfo.h" -#include <QCoreApplication> - -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { QCoreApplication app(argc, argv); @@ -32,22 +32,22 @@ int main(int argc, char *argv[]) "Copyright (c) 2012-2021, OpenGeoSys Community " "(http://www.opengeosys.org)", ' ', GitInfoLib::GitInfo::ogs_version); - TCLAP::ValueArg<double> z_arg - ("z", "z", "displacement in z direction", false, 0.0, "z-displacement"); + TCLAP::ValueArg<double> z_arg("z", "z", "displacement in z direction", + false, 0.0, "z-displacement"); cmd.add(z_arg); - TCLAP::ValueArg<double> y_arg - ("y", "y", "displacement in y direction", false, 0.0, "y-displacement"); + TCLAP::ValueArg<double> y_arg("y", "y", "displacement in y direction", + false, 0.0, "y-displacement"); cmd.add(y_arg); - TCLAP::ValueArg<double> x_arg - ("x", "x", "displacement in x direction", false, 0.0, "x-displacement"); + TCLAP::ValueArg<double> x_arg("x", "x", "displacement in x direction", + false, 0.0, "x-displacement"); cmd.add(x_arg); - TCLAP::ValueArg<std::string> geo_output_arg - ("o","output", "output geometry file (*.gml)", true, "", "output file"); + TCLAP::ValueArg<std::string> geo_output_arg( + "o", "output", "output geometry file (*.gml)", true, "", "output file"); cmd.add(geo_output_arg); - TCLAP::ValueArg<std::string> geo_input_arg - ("i","input", "input geometry file (*.gml)", true, "", "input file"); + TCLAP::ValueArg<std::string> geo_input_arg( + "i", "input", "input geometry file (*.gml)", true, "", "input file"); cmd.add(geo_input_arg); - cmd.parse( argc, argv ); + cmd.parse(argc, argv); GeoLib::GEOObjects geo_objects; GeoLib::IO::XmlGmlInterface xml(geo_objects); diff --git a/Applications/Utils/GeoTools/TriangulatePolyline.cpp b/Applications/Utils/GeoTools/TriangulatePolyline.cpp index 8eeb8170aba3d8e08408c23da85d93ca904213d1..191f0cb55201f231aa411e7b86800fb83908c005 100644 --- a/Applications/Utils/GeoTools/TriangulatePolyline.cpp +++ b/Applications/Utils/GeoTools/TriangulatePolyline.cpp @@ -11,31 +11,28 @@ * http://www.opengeosys.org/project/license */ -#include <string> - #include <tclap/CmdLine.h> -#include "Applications/FileIO/Legacy/createSurface.h" - -#include "InfoLib/GitInfo.h" +#include <QCoreApplication> +#include <string> -#include "GeoLib/IO/XmlIO/Qt/XmlGmlInterface.h" +#include "Applications/FileIO/Legacy/createSurface.h" #include "GeoLib/AnalyticalGeometry.h" #include "GeoLib/GEOObjects.h" +#include "GeoLib/IO/XmlIO/Qt/XmlGmlInterface.h" #include "GeoLib/Polyline.h" - -#include <QCoreApplication> +#include "InfoLib/GitInfo.h" std::string output_question() { - WARN ("Given polyline is not closed. Close polyline now?"); - WARN ("Enter (Y)es for closing the line or (N)o for abort and press ENTER."); + WARN("Given polyline is not closed. Close polyline now?"); + WARN("Enter (Y)es for closing the line or (N)o for abort and press ENTER."); std::string input; std::cin >> input; return input; } -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { QCoreApplication app(argc, argv, false); @@ -47,17 +44,20 @@ int main(int argc, char *argv[]) "Copyright (c) 2012-2021, OpenGeoSys Community " "(http://www.opengeosys.org)", ' ', GitInfoLib::GitInfo::ogs_version); - TCLAP::ValueArg<std::string> input_arg("i", "input", "GML input file (*.gml)", true, "", "string"); - TCLAP::ValueArg<std::string> output_arg("o", "output", "GML output file (*.gml)", true, "", "string"); - TCLAP::ValueArg<std::string> name_arg("n", "name", "Name of polyline in given file", true, "", "string"); + TCLAP::ValueArg<std::string> input_arg( + "i", "input", "GML input file (*.gml)", true, "", "string"); + TCLAP::ValueArg<std::string> output_arg( + "o", "output", "GML output file (*.gml)", true, "", "string"); + TCLAP::ValueArg<std::string> name_arg( + "n", "name", "Name of polyline in given file", true, "", "string"); TCLAP::ValueArg<std::string> gmsh_path_arg("g", "gmsh-path", "the path to the gmsh binary", false, "", "path as string"); - cmd.add( input_arg ); - cmd.add( name_arg ); - cmd.add( output_arg ); + cmd.add(input_arg); + cmd.add(name_arg); + cmd.add(output_arg); cmd.add(gmsh_path_arg); - cmd.parse( argc, argv ); + cmd.parse(argc, argv); std::string const& file_name(input_arg.getValue()); std::string const& polyline_name(name_arg.getValue()); @@ -95,7 +95,8 @@ int main(int argc, char *argv[]) // check if polyline can be triangulated (i.e. closed + coplanar) if (!line->isCoplanar()) { - ERR ("Polyline is not coplanar, no unambiguous triangulation possible. Aborting..."); + ERR("Polyline is not coplanar, no unambiguous triangulation possible. " + "Aborting..."); return EXIT_FAILURE; } @@ -110,7 +111,7 @@ int main(int argc, char *argv[]) if (input == "y" || input == "Y") { line->closePolyline(); - INFO ("Polyline closed."); + INFO("Polyline closed."); } else { @@ -118,7 +119,7 @@ int main(int argc, char *argv[]) } } - INFO ("Creating a surface by triangulation of the polyline ..."); + INFO("Creating a surface by triangulation of the polyline ..."); if (FileIO::createSurface(*line, geo_objects, geo_name, gmsh_path_arg.getValue())) { @@ -126,16 +127,15 @@ int main(int argc, char *argv[]) } else { - WARN( - "\t Creating a surface by triangulation of the polyline " - "failed."); + WARN("\t Creating a surface by triangulation of the polyline failed."); } GeoLib::SurfaceVec* sfc_vec(geo_objects.getSurfaceVecObj(geo_name)); std::size_t const sfc_id = geo_objects.getSurfaceVec(geo_name)->size() - 1; - std::string const surface_name (polyline_name + "_surface"); - for (std::size_t i=1;;++i) + std::string const surface_name(polyline_name + "_surface"); + for (std::size_t i = 1;; ++i) { - std::string const new_surface_name = (i>1) ? (surface_name + std::to_string(i)) : surface_name; + std::string const new_surface_name = + (i > 1) ? (surface_name + std::to_string(i)) : surface_name; if (sfc_vec->getElementByName(new_surface_name) == nullptr) { sfc_vec->setNameForElement(sfc_id, new_surface_name); @@ -146,7 +146,7 @@ int main(int argc, char *argv[]) // write new file xml.export_name = geo_name; BaseLib::IO::writeStringToFile(xml.writeToString(), output_arg.getValue()); - INFO ("...done."); + INFO("...done."); return EXIT_SUCCESS; } diff --git a/Applications/Utils/MeshEdit/AddElementQuality.cpp b/Applications/Utils/MeshEdit/AddElementQuality.cpp index 5829ed63150e494c0d0fe6f0cee13f192a957540..20f4c54fce0c9662e6f2cabc8c356cb9a3b9fe6c 100644 --- a/Applications/Utils/MeshEdit/AddElementQuality.cpp +++ b/Applications/Utils/MeshEdit/AddElementQuality.cpp @@ -20,7 +20,7 @@ #include "MeshLib/MeshEnums.h" #include "MeshLib/MeshQuality/ElementQualityInterface.h" -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { TCLAP::CmdLine cmd( "Add element quality as a mesh property.\n\n" diff --git a/Applications/Utils/MeshEdit/AddFaultToVoxelGrid.cpp b/Applications/Utils/MeshEdit/AddFaultToVoxelGrid.cpp index 7b560f6b9cb9b17eb3bcdb77f075783ec81cc4d9..17c94f70dc91e0065b3c6eb583a3cce3748bcc57 100644 --- a/Applications/Utils/MeshEdit/AddFaultToVoxelGrid.cpp +++ b/Applications/Utils/MeshEdit/AddFaultToVoxelGrid.cpp @@ -33,7 +33,6 @@ bool testAABBIntersectingPlane(Eigen::Vector3d const& aabb_centre, Eigen::Vector3d const& plane_normal, double const pd) { - double const r = aabb_extent.dot(plane_normal.cwiseAbs()); double const s = plane_normal.dot(aabb_centre) - pd; return std::abs(s) > r; @@ -205,9 +204,9 @@ int main(int argc, char* argv[]) "Copyright (c) 2012-2021, OpenGeoSys Community " "(http://www.opengeosys.org)", ' ', GitInfoLib::GitInfo::ogs_version); - TCLAP::ValueArg<int> id_arg( - "m", "material", "material id for cells intersected by fault", false, - mat_not_set, "non-negative integer"); + TCLAP::ValueArg<int> id_arg("m", "material", + "material id for cells intersected by fault", + false, mat_not_set, "non-negative integer"); cmd.add(id_arg); TCLAP::ValueArg<std::string> output_arg( diff --git a/Applications/Utils/MeshEdit/AddLayer.cpp b/Applications/Utils/MeshEdit/AddLayer.cpp index e5d01b42933e8d9fbe38aa7c9dccb23ccea909cc..eb1850cabbdfbb5ebf971ea50483320551484f70 100644 --- a/Applications/Utils/MeshEdit/AddLayer.cpp +++ b/Applications/Utils/MeshEdit/AddLayer.cpp @@ -9,18 +9,18 @@ * http://www.opengeosys.org/project/license */ -#include <memory> - #include <tclap/CmdLine.h> -#include "InfoLib/GitInfo.h" +#include <memory> + #include "BaseLib/FileTools.h" +#include "InfoLib/GitInfo.h" #include "MeshLib/IO/readMeshFromFile.h" #include "MeshLib/IO/writeMeshToFile.h" #include "MeshLib/Mesh.h" #include "MeshLib/MeshEditing/AddLayerToMesh.h" -int main (int argc, char* argv[]) +int main(int argc, char* argv[]) { TCLAP::CmdLine cmd( "Adds a layer to an existing mesh." @@ -32,18 +32,20 @@ int main (int argc, char* argv[]) "Copyright (c) 2012-2021, OpenGeoSys Community " "(http://www.opengeosys.org)", ' ', GitInfoLib::GitInfo::ogs_version); - TCLAP::ValueArg<std::string> mesh_arg("i", "input-mesh-file", - "the name of the file containing the mesh", true, - "", "file name"); + TCLAP::ValueArg<std::string> mesh_arg( + "i", "input-mesh-file", "the name of the file containing the mesh", + true, "", "file name"); cmd.add(mesh_arg); - TCLAP::ValueArg<std::string> mesh_out_arg("o", "output-mesh-file", + TCLAP::ValueArg<std::string> mesh_out_arg( + "o", "output-mesh-file", "the name of the file the mesh should be written to (vtu format)", true, "", "file name"); cmd.add(mesh_out_arg); - TCLAP::ValueArg<double> layer_thickness_arg("t", "layer-tickness", - "the thickness of the new layer", false, 10, "floating point value"); + TCLAP::ValueArg<double> layer_thickness_arg( + "t", "layer-tickness", "the thickness of the new layer", false, 10, + "floating point value"); cmd.add(layer_thickness_arg); TCLAP::SwitchArg layer_position_arg( @@ -66,7 +68,8 @@ int main (int argc, char* argv[]) INFO("Reading mesh '{:s}' ... ", mesh_arg.getValue()); auto subsfc_mesh = std::unique_ptr<MeshLib::Mesh>( MeshLib::IO::readMeshFromFile(mesh_arg.getValue())); - if (!subsfc_mesh) { + if (!subsfc_mesh) + { ERR("Error reading mesh '{:s}'.", mesh_arg.getValue()); return EXIT_FAILURE; } diff --git a/Applications/Utils/MeshEdit/CreateBoundaryConditionsAlongPolylines.cpp b/Applications/Utils/MeshEdit/CreateBoundaryConditionsAlongPolylines.cpp index ed3682d203fa307db77e6d2ac084b3288d090a9c..c06b29886849ea8366ba03828bc064fcf37b39bc 100644 --- a/Applications/Utils/MeshEdit/CreateBoundaryConditionsAlongPolylines.cpp +++ b/Applications/Utils/MeshEdit/CreateBoundaryConditionsAlongPolylines.cpp @@ -9,44 +9,40 @@ * http://www.opengeosys.org/project/license */ +#include <tclap/CmdLine.h> + +#include <fstream> #include <map> #include <string> #include <vector> -#include <fstream> - -#include <tclap/CmdLine.h> #include "Applications/FileIO/readGeometryFromFile.h" #include "Applications/FileIO/writeGeometryToFile.h" - -#include "InfoLib/GitInfo.h" #include "BaseLib/FileTools.h" - -#include "MeshLib/IO/readMeshFromFile.h" -#include "MeshLib/IO/writeMeshToFile.h" - #include "GeoLib/GEOObjects.h" #include "GeoLib/Point.h" - +#include "InfoLib/GitInfo.h" +#include "MeshGeoToolsLib/MeshNodeSearcher.h" +#include "MeshLib/IO/readMeshFromFile.h" +#include "MeshLib/IO/writeMeshToFile.h" #include "MeshLib/Mesh.h" -#include "MeshLib/Node.h" #include "MeshLib/MeshSurfaceExtraction.h" - -#include "MeshGeoToolsLib/MeshNodeSearcher.h" +#include "MeshLib/Node.h" void convertMeshNodesToGeometry(std::vector<MeshLib::Node*> const& nodes, - std::vector<std::size_t> const& node_ids, - std::string & geo_name, - GeoLib::GEOObjects & geometry_sets) + std::vector<std::size_t> const& node_ids, + std::string& geo_name, + GeoLib::GEOObjects& geometry_sets) { // copy data auto pnts = std::make_unique<std::vector<GeoLib::Point*>>(); auto pnt_names = std::make_unique<std::map<std::string, std::size_t>>(); std::size_t cnt(0); - for (std::size_t id: node_ids) { + for (std::size_t id : node_ids) + { pnts->push_back(new GeoLib::Point(*(nodes[id]), cnt)); pnt_names->insert(std::pair<std::string, std::size_t>( - geo_name+"-PNT-"+std::to_string(cnt), cnt)); + geo_name + "-PNT-" + std::to_string(cnt), cnt)); cnt++; } @@ -68,7 +64,7 @@ void writeGroundwaterFlowPointBC(std::ostream& bc_out, bc_out << " CONSTANT " << head_value << "\n"; } -void writeLiquidFlowPointBC(std::ostream & bc_out, std::string const& pnt_name) +void writeLiquidFlowPointBC(std::ostream& bc_out, std::string const& pnt_name) { bc_out << "#BOUNDARY_CONDITION\n"; bc_out << " $PCS_TYPE\n"; @@ -85,14 +81,17 @@ void writeLiquidFlowPointBC(std::ostream & bc_out, std::string const& pnt_name) // set on, geo_name is the name the geometry can be accessed with, out_fname is // the base file name the gli and bc as well as the gml file will be written to. void writeBCsAndGeometry(GeoLib::GEOObjects& geometry_sets, - std::string const& geo_name, std::string const& out_fname, + std::string const& geo_name, + std::string const& out_fname, std::string const& bc_type, bool const write_gml) { - if (write_gml) { + if (write_gml) + { INFO("write points to '{:s}.gml'.", geo_name); - FileIO::writeGeometryToFile(geo_name, geometry_sets, out_fname+".gml"); + FileIO::writeGeometryToFile(geo_name, geometry_sets, + out_fname + ".gml"); } - FileIO::writeGeometryToFile(geo_name, geometry_sets, out_fname+".gli"); + FileIO::writeGeometryToFile(geo_name, geometry_sets, out_fname + ".gli"); bool liquid_flow(false); if (bc_type == "LIQUID_FLOW") @@ -100,12 +99,15 @@ void writeBCsAndGeometry(GeoLib::GEOObjects& geometry_sets, liquid_flow = true; } - GeoLib::PointVec const* pnt_vec_objs(geometry_sets.getPointVecObj(geo_name)); + GeoLib::PointVec const* pnt_vec_objs( + geometry_sets.getPointVecObj(geo_name)); std::vector<GeoLib::Point*> const& pnts(*(pnt_vec_objs->getVector())); - std::ofstream bc_out (out_fname+".bc"); - for (std::size_t k(0); k<pnts.size(); k++) { + std::ofstream bc_out(out_fname + ".bc"); + for (std::size_t k(0); k < pnts.size(); k++) + { std::string const& pnt_name(pnt_vec_objs->getItemNameByID(k)); - if (!pnt_name.empty()) { + if (!pnt_name.empty()) + { if (liquid_flow) { writeLiquidFlowPointBC(bc_out, pnt_name); @@ -120,7 +122,7 @@ void writeBCsAndGeometry(GeoLib::GEOObjects& geometry_sets, bc_out.close(); } -int main (int argc, char* argv[]) +int main(int argc, char* argv[]) { TCLAP::CmdLine cmd( "Creates boundary conditions for mesh nodes along polylines." @@ -136,34 +138,38 @@ int main (int argc, char* argv[]) TCLAP::SwitchArg gml_arg("", "gml", "Write found nodes to gml file."); cmd.add(gml_arg); - TCLAP::ValueArg<std::string> output_base_fname("o", "output-base-file-name", - "the base name of the file the output (geometry (gli) and boundary"\ - "condition (bc)) will be written to", true, - "", "file name"); + TCLAP::ValueArg<std::string> output_base_fname( + "o", "output-base-file-name", + "the base name of the file the output (geometry (gli) and boundary " + "condition (bc)) will be written to", + true, "", "file name"); cmd.add(output_base_fname); - TCLAP::ValueArg<std::string> bc_type("t", "type", - "the process type the boundary condition will be written for "\ - "currently LIQUID_FLOW (primary variable PRESSURE1) and "\ - "GROUNDWATER_FLOW (primary variable HEAD, default) are supported", true, - "", + TCLAP::ValueArg<std::string> bc_type( + "t", "type", + "the process type the boundary condition will be written for currently " + "LIQUID_FLOW (primary variable PRESSURE1) and GROUNDWATER_FLOW " + "(primary variable HEAD, default) are supported", + true, "", "process type as string (LIQUID_FLOW or GROUNDWATER_FLOW (default))"); cmd.add(bc_type); - TCLAP::ValueArg<double> search_length_arg("s", "search-length", + TCLAP::ValueArg<double> search_length_arg( + "s", "search-length", "The size of the search length. The default value is " - "std::numeric_limits<double>::epsilon()", false, - std::numeric_limits<double>::epsilon(), "floating point number"); + "std::numeric_limits<double>::epsilon()", + false, std::numeric_limits<double>::epsilon(), "floating point number"); cmd.add(search_length_arg); - TCLAP::ValueArg<std::string> geometry_fname("i", "input-geometry", - "the name of the file containing the input geometry", true, - "", "file name"); + TCLAP::ValueArg<std::string> geometry_fname( + "i", "input-geometry", + "the name of the file containing the input geometry", true, "", + "file name"); cmd.add(geometry_fname); - TCLAP::ValueArg<std::string> mesh_arg("m", "mesh-file", - "the name of the file containing the mesh", true, - "", "file name"); + TCLAP::ValueArg<std::string> mesh_arg( + "m", "mesh-file", "the name of the file containing the mesh", true, "", + "file name"); cmd.add(mesh_arg); TCLAP::ValueArg<std::string> gmsh_path_arg("g", "gmsh-path", @@ -196,8 +202,10 @@ int main (int argc, char* argv[]) // *** check if the data is usable // *** get vector of polylines - std::vector<GeoLib::Polyline*> const* plys(geometries.getPolylineVec(geo_name)); - if (!plys) { + std::vector<GeoLib::Polyline*> const* plys( + geometries.getPolylineVec(geo_name)); + if (!plys) + { ERR("Could not get vector of polylines out of geometry '{:s}'.", geo_name); return EXIT_FAILURE; @@ -205,7 +213,8 @@ int main (int argc, char* argv[]) auto search_length_strategy = std::make_unique<MeshGeoToolsLib::SearchLength>(); - if (search_length_arg.isSet()) { + if (search_length_arg.isSet()) + { search_length_strategy.reset( new MeshGeoToolsLib::SearchLength(search_length_arg.getValue())); } @@ -228,7 +237,8 @@ int main (int argc, char* argv[]) // merge all together auto const geo_names = geometry_sets.getGeometryNames(); - if (geo_names.empty()) { + if (geo_names.empty()) + { ERR("Did not find mesh nodes along polylines."); return EXIT_FAILURE; } @@ -244,16 +254,17 @@ int main (int argc, char* argv[]) std::vector<GeoLib::Point> pnts_with_id; const std::size_t n_merged_pnts(merged_pnts->size()); - for(std::size_t k(0); k<n_merged_pnts; ++k) { + for (std::size_t k(0); k < n_merged_pnts; ++k) + { pnts_with_id.emplace_back(*((*merged_pnts)[k]), k); } std::sort(pnts_with_id.begin(), pnts_with_id.end(), - [](GeoLib::Point const& p0, GeoLib::Point const& p1) - { return p0 < p1; } - ); + [](GeoLib::Point const& p0, GeoLib::Point const& p1) { + return p0 < p1; + }); - double const eps (std::numeric_limits<double>::epsilon()); + double const eps(std::numeric_limits<double>::epsilon()); auto surface_pnts = std::make_unique<std::vector<GeoLib::Point*>>(); auto name_id_map = std::make_unique<std::map<std::string, std::size_t>>(); @@ -266,22 +277,23 @@ int main (int argc, char* argv[]) name_id_map->insert( std::pair<std::string, std::size_t>(element_name, 0)); } - for (std::size_t k(1); k < n_merged_pnts; ++k) { - const GeoLib::Point& p0 (pnts_with_id[k-1]); - const GeoLib::Point& p1 (pnts_with_id[k]); - if (std::abs (p0[0] - p1[0]) > eps || std::abs (p0[1] - p1[1]) > eps) { - surface_pnts->push_back(new GeoLib::Point(pnts_with_id[k], - surface_pnts->size())); + for (std::size_t k(1); k < n_merged_pnts; ++k) + { + const GeoLib::Point& p0(pnts_with_id[k - 1]); + const GeoLib::Point& p1(pnts_with_id[k]); + if (std::abs(p0[0] - p1[0]) > eps || std::abs(p0[1] - p1[1]) > eps) + { + surface_pnts->push_back( + new GeoLib::Point(pnts_with_id[k], surface_pnts->size())); std::string element_name; pnt_vec->getNameOfElementByID(k, element_name); - name_id_map->insert( - std::pair<std::string, std::size_t>(element_name, - surface_pnts->size()-1) - ); + name_id_map->insert(std::pair<std::string, std::size_t>( + element_name, surface_pnts->size() - 1)); } } - std::string surface_name(BaseLib::dropFileExtension(mesh_arg.getValue())+"-MeshNodesAlongPolylines"); + std::string surface_name(BaseLib::dropFileExtension(mesh_arg.getValue()) + + "-MeshNodesAlongPolylines"); geometry_sets.addPointVec(std::move(surface_pnts), surface_name, std::move(name_id_map), 1e-6); diff --git a/Applications/Utils/MeshEdit/ExtractBoundary.cpp b/Applications/Utils/MeshEdit/ExtractBoundary.cpp index 2941ce4849184ba0a71d0e97d9206e7d85a66e4d..751bd23f9e0bc3a08ef6719c872508e403ef1d0a 100644 --- a/Applications/Utils/MeshEdit/ExtractBoundary.cpp +++ b/Applications/Utils/MeshEdit/ExtractBoundary.cpp @@ -27,7 +27,7 @@ #include "MeshLib/MeshSurfaceExtraction.h" #include "MeshLib/Node.h" -int main (int argc, char* argv[]) +int main(int argc, char* argv[]) { TCLAP::CmdLine cmd( "Tool extracts the boundary of the given mesh. The documentation is " diff --git a/Applications/Utils/MeshEdit/ExtractMaterials.cpp b/Applications/Utils/MeshEdit/ExtractMaterials.cpp index 4684c809235790761b94fa639c03a77b7936db2f..4afe7d90c40b30842f84b556f689713ef74bbb63 100644 --- a/Applications/Utils/MeshEdit/ExtractMaterials.cpp +++ b/Applications/Utils/MeshEdit/ExtractMaterials.cpp @@ -12,12 +12,11 @@ // ThirdParty #include <tclap/CmdLine.h> -#include "InfoLib/GitInfo.h" - #include "BaseLib/FileTools.h" -#include "MeshLib/Mesh.h" -#include "MeshLib/IO/readMeshFromFile.h" +#include "InfoLib/GitInfo.h" #include "MeshLib/IO/VtkIO/VtuInterface.h" +#include "MeshLib/IO/readMeshFromFile.h" +#include "MeshLib/Mesh.h" #include "MeshLib/MeshEditing/RemoveMeshComponents.h" MeshLib::Mesh* extractMatGroup(MeshLib::Mesh const& mesh, int const mat_id) @@ -42,7 +41,6 @@ MeshLib::Mesh* extractMatGroup(MeshLib::Mesh const& mesh, int const mat_id) return MeshLib::removeElements(mesh, elem_list, "matgroup"); } - int main(int argc, char* argv[]) { TCLAP::CmdLine cmd( @@ -61,24 +59,23 @@ int main(int argc, char* argv[]) "mesh.", false, 0, "Number specifying the MaterialID"); cmd.add(arg_mat_id); - TCLAP::ValueArg<std::string> output_arg( - "o", "output", - "Name of the output mesh (*.vtu)", - true, "", "output file name"); + TCLAP::ValueArg<std::string> output_arg("o", "output", + "Name of the output mesh (*.vtu)", + true, "", "output file name"); cmd.add(output_arg); - TCLAP::ValueArg<std::string> input_arg( - "i", "input", - "Name of the input mesh (*.vtu)", - true, "", "input file name"); + TCLAP::ValueArg<std::string> input_arg("i", "input", + "Name of the input mesh (*.vtu)", + true, "", "input file name"); cmd.add(input_arg); - cmd.parse( argc, argv ); + cmd.parse(argc, argv); std::string const input_name = input_arg.getValue(); std::string const output_name = output_arg.getValue(); std::string const base_name = BaseLib::dropFileExtension(output_name); std::string const ext = BaseLib::getFileExtension(output_name); - std::unique_ptr<MeshLib::Mesh> const mesh (MeshLib::IO::readMeshFromFile(input_name)); + std::unique_ptr<MeshLib::Mesh> const mesh( + MeshLib::IO::readMeshFromFile(input_name)); if (mesh == nullptr) { ERR("Error reading input mesh. Aborting..."); @@ -124,14 +121,15 @@ int main(int argc, char* argv[]) for (int i = min_id; i <= max_id; ++i) { INFO("Extracting material group {:d}...", i); - std::unique_ptr<MeshLib::Mesh> mat_group (extractMatGroup(*mesh, i)); + std::unique_ptr<MeshLib::Mesh> mat_group(extractMatGroup(*mesh, i)); if (mat_group == nullptr) { WARN("No elements with material group {:d} found.", i); continue; } MeshLib::IO::VtuInterface vtu(mat_group.get()); - std::string const file_name(base_name + "_Layer" + std::to_string(i) + ext); + std::string const file_name(base_name + "_Layer" + std::to_string(i) + + ext); vtu.writeToFile(file_name); if (ostream.is_open()) { diff --git a/Applications/Utils/MeshEdit/ExtractSurface.cpp b/Applications/Utils/MeshEdit/ExtractSurface.cpp index 75ea332ce2119beb1c306af661fb2e448ebf631d..eea4e30c038a135cd2169e2e96b14dbba8416e5e 100644 --- a/Applications/Utils/MeshEdit/ExtractSurface.cpp +++ b/Applications/Utils/MeshEdit/ExtractSurface.cpp @@ -9,32 +9,31 @@ * http://www.opengeosys.org/project/license */ +#include <tclap/CmdLine.h> + #include <algorithm> #include <memory> #include <string> #include <vector> -#include <tclap/CmdLine.h> - -#include "InfoLib/GitInfo.h" #include "BaseLib/FileTools.h" #include "BaseLib/StringTools.h" - +#include "InfoLib/GitInfo.h" +#include "MeshLib/IO/VtkIO/VtuInterface.h" #include "MeshLib/IO/readMeshFromFile.h" #include "MeshLib/IO/writeMeshToFile.h" -#include "MeshLib/IO/VtkIO/VtuInterface.h" - #include "MeshLib/Mesh.h" #include "MeshLib/MeshSurfaceExtraction.h" -int main (int argc, char* argv[]) +int main(int argc, char* argv[]) { TCLAP::CmdLine cmd( "Extracts a 2D surface from a 3D input mesh by specifying a normal " "vector and an angle. (The surface normal (0, 0, 0) will extract the " "complete outer boundary of the 3D mesh.)\n" "An extensive documentation can be found at " - "https://docs.opengeosys.org/docs/tools/meshing-submeshes/extract-surface\n" + "https://docs.opengeosys.org/docs/tools/meshing-submeshes/" + "extract-surface\n" "OpenGeoSys-6 software, version " + GitInfoLib::GitInfo::ogs_version + ".\n" diff --git a/Applications/Utils/MeshEdit/Layers2Grid.cpp b/Applications/Utils/MeshEdit/Layers2Grid.cpp index a758e8a0a63937c14d6d403861e8a15faf57475e..12f6b6252592ec6c4681831579af2ad7678409ea 100644 --- a/Applications/Utils/MeshEdit/Layers2Grid.cpp +++ b/Applications/Utils/MeshEdit/Layers2Grid.cpp @@ -51,8 +51,8 @@ std::unique_ptr<MeshLib::Mesh> generateInitialMesh( { INFO("Creating initial mesh..."); std::array<double, 3> mesh_range{{extent.second[0] - extent.first[0], - extent.second[1] - extent.first[1], - extent.second[2] - extent.first[2]}}; + extent.second[1] - extent.first[1], + extent.second[2] - extent.first[2]}}; std::array<std::size_t, 3> const n_cells{ {static_cast<std::size_t>(std::ceil(mesh_range[0] / res[0])), static_cast<std::size_t>(std::ceil(mesh_range[1] / res[1])), diff --git a/Applications/Utils/MeshEdit/MapGeometryToMeshSurface.cpp b/Applications/Utils/MeshEdit/MapGeometryToMeshSurface.cpp index 0047666847f4bb67228368a16f051d72a3a9814a..6c0506a48be5570142558dda5f4806b750e7350f 100644 --- a/Applications/Utils/MeshEdit/MapGeometryToMeshSurface.cpp +++ b/Applications/Utils/MeshEdit/MapGeometryToMeshSurface.cpp @@ -8,23 +8,23 @@ * See accompanying file LICENSE.txt or */ +#include <tclap/CmdLine.h> + #include <algorithm> #include <cstdlib> #include <vector> -#include <tclap/CmdLine.h> - -#include "InfoLib/GitInfo.h" #include "GeoLib/GEOObjects.h" #include "GeoLib/IO/XmlIO/Boost/BoostXmlGmlInterface.h" +#include "InfoLib/GitInfo.h" #include "MeshGeoToolsLib/GeoMapper.h" #include "MeshLib/IO/readMeshFromFile.h" #include "MeshLib/Mesh.h" -int main (int argc, char* argv[]) +int main(int argc, char* argv[]) { TCLAP::CmdLine cmd( - "Maps geometric objects to the surface of a given mesh." + "Maps geometric objects to the surface of a given mesh. " "The documentation is available at " "https://docs.opengeosys.org/docs/tools/model-preparation/" "map-geometric-object-to-the-surface-of-a-mesh.\n\n" @@ -34,22 +34,24 @@ int main (int argc, char* argv[]) "Copyright (c) 2012-2021, OpenGeoSys Community " "(http://www.opengeosys.org)", ' ', GitInfoLib::GitInfo::ogs_version); - TCLAP::ValueArg<std::string> mesh_in("m", "mesh-file", - "the name of the file containing the mesh", true, - "", "file name"); + TCLAP::ValueArg<std::string> mesh_in( + "m", "mesh-file", "the name of the file containing the mesh", true, "", + "file name"); cmd.add(mesh_in); - TCLAP::ValueArg<std::string> input_geometry_fname("i", "input-geometry", - "the name of the file containing the input geometry", true, - "", "file name"); + TCLAP::ValueArg<std::string> input_geometry_fname( + "i", "input-geometry", + "the name of the file containing the input geometry", true, "", + "file name"); cmd.add(input_geometry_fname); TCLAP::SwitchArg additional_insert_mapping( "a", "additional-insert-mapping", "Advanced mapping algorithm will be applied, i.e. a new geometry will " "be created and possibly new points will be inserted."); cmd.add(additional_insert_mapping); - TCLAP::ValueArg<std::string> output_geometry_fname("o", "output-geometry", - "the name of the file containing the input geometry", true, - "", "file name"); + TCLAP::ValueArg<std::string> output_geometry_fname( + "o", "output-geometry", + "the name of the file containing the input geometry", true, "", + "file name"); cmd.add(output_geometry_fname); cmd.parse(argc, argv); @@ -57,10 +59,13 @@ int main (int argc, char* argv[]) GeoLib::GEOObjects geometries; { GeoLib::IO::BoostXmlGmlInterface xml_io(geometries); - if (xml_io.readFile(input_geometry_fname.getValue())) { + if (xml_io.readFile(input_geometry_fname.getValue())) + { INFO("Read geometry from file '{:s}'.", input_geometry_fname.getValue()); - } else { + } + else + { return EXIT_FAILURE; } } @@ -73,9 +78,12 @@ int main (int argc, char* argv[]) std::unique_ptr<MeshLib::Mesh> mesh( MeshLib::IO::readMeshFromFile(mesh_in.getValue())); - if (additional_insert_mapping.getValue()) { + if (additional_insert_mapping.getValue()) + { geo_mapper.advancedMapOnMesh(*mesh); - } else { + } + else + { geo_mapper.mapOnMesh(mesh.get()); } diff --git a/Applications/Utils/MeshEdit/MoveMesh.cpp b/Applications/Utils/MeshEdit/MoveMesh.cpp index 3fb7b9744c17d153717ef288f4476e6332393172..b5addf760da0fe930689397ac40f3624e662b136 100644 --- a/Applications/Utils/MeshEdit/MoveMesh.cpp +++ b/Applications/Utils/MeshEdit/MoveMesh.cpp @@ -12,10 +12,10 @@ #include <tclap/CmdLine.h> -#include "InfoLib/GitInfo.h" #include "BaseLib/FileTools.h" #include "BaseLib/StringTools.h" #include "GeoLib/AABB.h" +#include "InfoLib/GitInfo.h" #include "MeshLib/Elements/Element.h" #include "MeshLib/IO/readMeshFromFile.h" #include "MeshLib/IO/writeMeshToFile.h" @@ -23,7 +23,7 @@ #include "MeshLib/MeshEditing/moveMeshNodes.h" #include "MeshLib/Node.h" -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { TCLAP::CmdLine cmd( "Moves the mesh nodes using the given displacement vector or if no " @@ -38,42 +38,54 @@ int main(int argc, char *argv[]) // Define a value argument and add it to the command line. // A value arg defines a flag and a type of value that it expects, // such as "-m meshfile". - TCLAP::ValueArg<std::string> mesh_arg("m","mesh","input mesh file",true,"","string"); + TCLAP::ValueArg<std::string> mesh_arg("m", "mesh", "input mesh file", true, + "", "string"); // Add the argument mesh_arg to the CmdLine object. The CmdLine object // uses this Arg to parse the command line. - cmd.add( mesh_arg ); + cmd.add(mesh_arg); - TCLAP::ValueArg<double> x_arg("x","x","displacement in x direction", false, 0.0,"floating point number"); + TCLAP::ValueArg<double> x_arg("x", "x", "displacement in x direction", + false, 0.0, "floating point number"); cmd.add(x_arg); - TCLAP::ValueArg<double> y_arg("y","y","displacement in y direction", false, 0.0,"floating point number"); + TCLAP::ValueArg<double> y_arg("y", "y", "displacement in y direction", + false, 0.0, "floating point number"); cmd.add(y_arg); - TCLAP::ValueArg<double> z_arg("z","z","displacement in z direction", false, 0.0,"floating point number"); + TCLAP::ValueArg<double> z_arg("z", "z", "displacement in z direction", + false, 0.0, "floating point number"); cmd.add(z_arg); - TCLAP::ValueArg<std::string> mesh_out_arg("o","output-mesh","output mesh file", false, "", "string"); + TCLAP::ValueArg<std::string> mesh_out_arg( + "o", "output-mesh", "output mesh file", false, "", "string"); cmd.add(mesh_out_arg); - cmd.parse( argc, argv ); + cmd.parse(argc, argv); - std::string fname (mesh_arg.getValue()); + std::string fname(mesh_arg.getValue()); std::unique_ptr<MeshLib::Mesh> mesh(MeshLib::IO::readMeshFromFile(fname)); - if (!mesh) { + if (!mesh) + { ERR("Could not read mesh from file '{:s}'.", fname); return EXIT_FAILURE; } MeshLib::Node displacement(0.0, 0.0, 0.0); - if (fabs(x_arg.getValue()) < std::numeric_limits<double>::epsilon() - && fabs(y_arg.getValue()) < std::numeric_limits<double>::epsilon() - && fabs(z_arg.getValue()) < std::numeric_limits<double>::epsilon()) { + if (fabs(x_arg.getValue()) < std::numeric_limits<double>::epsilon() && + fabs(y_arg.getValue()) < std::numeric_limits<double>::epsilon() && + fabs(z_arg.getValue()) < std::numeric_limits<double>::epsilon()) + { GeoLib::AABB aabb(mesh->getNodes().begin(), mesh->getNodes().end()); - displacement[0] = -(aabb.getMaxPoint()[0] + aabb.getMinPoint()[0])/2.0; - displacement[1] = -(aabb.getMaxPoint()[1] + aabb.getMinPoint()[1])/2.0; - displacement[2] = -(aabb.getMaxPoint()[2] + aabb.getMinPoint()[2])/2.0; - } else { + displacement[0] = + -(aabb.getMaxPoint()[0] + aabb.getMinPoint()[0]) / 2.0; + displacement[1] = + -(aabb.getMaxPoint()[1] + aabb.getMinPoint()[1]) / 2.0; + displacement[2] = + -(aabb.getMaxPoint()[2] + aabb.getMinPoint()[2]) / 2.0; + } + else + { displacement[0] = x_arg.getValue(); displacement[1] = y_arg.getValue(); displacement[2] = z_arg.getValue(); @@ -83,11 +95,12 @@ int main(int argc, char *argv[]) displacement[0], displacement[1], displacement[2]); - MeshLib::moveMeshNodes( - mesh->getNodes().begin(), mesh->getNodes().end(), displacement); + MeshLib::moveMeshNodes(mesh->getNodes().begin(), mesh->getNodes().end(), + displacement); std::string out_fname(mesh_out_arg.getValue()); - if (out_fname.empty()) { + if (out_fname.empty()) + { out_fname = BaseLib::dropFileExtension(mesh_out_arg.getValue()); out_fname += "_displaced.vtu"; } diff --git a/Applications/Utils/MeshEdit/NodeReordering.cpp b/Applications/Utils/MeshEdit/NodeReordering.cpp index faa7a1aad1bbee06e90ce0a03d9775ee55dc0de5..9f0bf783d0c7b8359129bc89237f12dc276926a4 100644 --- a/Applications/Utils/MeshEdit/NodeReordering.cpp +++ b/Applications/Utils/MeshEdit/NodeReordering.cpp @@ -9,13 +9,13 @@ * http://www.opengeosys.org/project/license */ -#include <array> +#include <tclap/CmdLine.h> + #include <algorithm> +#include <array> #include <memory> #include <vector> -#include <tclap/CmdLine.h> - #include "BaseLib/Algorithm.h" #include "InfoLib/GitInfo.h" #include "MeshLib/Elements/Element.h" @@ -24,7 +24,8 @@ #include "MeshLib/Mesh.h" #include "MeshLib/Node.h" -/// Re-ordering mesh elements to correct Data Explorer 5 meshes to work with Data Explorer 6. +/// Re-ordering mesh elements to correct Data Explorer 5 meshes to work with +/// Data Explorer 6. void reorderNodes(std::vector<MeshLib::Element*>& elements) { std::size_t n_corrected_elements = 0; @@ -80,7 +81,8 @@ void reorderNodes(std::vector<MeshLib::Element*>& elements) INFO("Corrected {:d} elements.", n_corrected_elements); } -/// Re-ordering prism elements to correct OGS6 meshes with and without InSitu-Lib +/// Re-ordering prism elements to correct OGS6 meshes with and without +/// InSitu-Lib void reorderNodes2(std::vector<MeshLib::Element*>& elements) { std::size_t const nElements(elements.size()); @@ -105,7 +107,7 @@ void reorderNodes2(std::vector<MeshLib::Element*>& elements) } } -void reorderNonlinearNodes(MeshLib::Mesh &mesh) +void reorderNonlinearNodes(MeshLib::Mesh& mesh) { std::vector<MeshLib::Node*> base_nodes; std::vector<MeshLib::Node*> nonlinear_nodes; @@ -137,12 +139,13 @@ void reorderNonlinearNodes(MeshLib::Mesh &mesh) allnodes.clear(); allnodes.insert(allnodes.end(), base_nodes.begin(), base_nodes.end()); - allnodes.insert(allnodes.end(), nonlinear_nodes.begin(), nonlinear_nodes.end()); + allnodes.insert(allnodes.end(), nonlinear_nodes.begin(), + nonlinear_nodes.end()); mesh.resetNodeIDs(); } -int main (int argc, char* argv[]) +int main(int argc, char* argv[]) { TCLAP::CmdLine cmd( "Reorders mesh nodes in elements to make old or incorrectly ordered " @@ -188,11 +191,13 @@ int main (int argc, char* argv[]) INFO("Reordering nodes... "); if (!method_arg.isSet() || method_arg.getValue() == 1) { - reorderNodes(const_cast<std::vector<MeshLib::Element*>&>(mesh->getElements())); + reorderNodes( + const_cast<std::vector<MeshLib::Element*>&>(mesh->getElements())); } else if (method_arg.getValue() == 2) { - reorderNodes2(const_cast<std::vector<MeshLib::Element*>&>(mesh->getElements())); + reorderNodes2( + const_cast<std::vector<MeshLib::Element*>&>(mesh->getElements())); } else if (method_arg.getValue() == 3) { @@ -205,6 +210,3 @@ int main (int argc, char* argv[]) return EXIT_SUCCESS; } - - - diff --git a/Applications/Utils/MeshEdit/RemoveGhostData.cpp b/Applications/Utils/MeshEdit/RemoveGhostData.cpp index 6e0223a7dcfb339b30cf953e7241b9de425d3d3b..b6afaed49dfef224eb63104c5bbc691b3486f9e1 100644 --- a/Applications/Utils/MeshEdit/RemoveGhostData.cpp +++ b/Applications/Utils/MeshEdit/RemoveGhostData.cpp @@ -18,25 +18,25 @@ #include "InfoLib/GitInfo.h" #include "MeshLib/IO/writeMeshToFile.h" -int main (int argc, char* argv[]) +int main(int argc, char* argv[]) { TCLAP::CmdLine cmd( "Reads a VTK partitioned unstructured grid (*.pvtu), cleans the ghost " "information and saves the data as as a regular, connected mesh file." "\n\nOpenGeoSys-6 software, version " + - GitInfoLib::GitInfo::ogs_version + - ".\n" - "Copyright (c) 2012-2021, OpenGeoSys Community " - "(http://www.opengeosys.org)", + GitInfoLib::GitInfo::ogs_version + + ".\n" + "Copyright (c) 2012-2021, OpenGeoSys Community " + "(http://www.opengeosys.org)", ' ', GitInfoLib::GitInfo::ogs_version); TCLAP::ValueArg<std::string> output_arg( "o", "output", "the output mesh (*.vtu)", true, "", "output.vtu"); cmd.add(output_arg); - TCLAP::ValueArg<std::string> input_arg("i", "input", - "the partitioned input mesh (*.pvtu)", - true, "", "input.pvtu"); + TCLAP::ValueArg<std::string> input_arg( + "i", "input", "the partitioned input mesh (*.pvtu)", true, "", + "input.pvtu"); cmd.add(input_arg); cmd.parse(argc, argv); diff --git a/Applications/Utils/MeshEdit/ResetPropertiesInPolygonalRegion.cpp b/Applications/Utils/MeshEdit/ResetPropertiesInPolygonalRegion.cpp index 75159e58d94000bc9ef2eaf50671f0e9e536efd7..6bed6f4e44faf8e4c7fe6e39774359a6a00ad138 100644 --- a/Applications/Utils/MeshEdit/ResetPropertiesInPolygonalRegion.cpp +++ b/Applications/Utils/MeshEdit/ResetPropertiesInPolygonalRegion.cpp @@ -51,8 +51,8 @@ int main(int argc, char* argv[]) cmd.add(polygon_name_arg); TCLAP::ValueArg<std::string> geometry_fname( "g", "geometry", - "the name of " - "the file containing the input geometry (gli or gml format)", + "the name of the file containing the input geometry (gli or gml " + "format)", true, "", "file name"); cmd.add(geometry_fname); TCLAP::ValueArg<char> char_property_arg( diff --git a/Applications/Utils/MeshEdit/Vtu2Grid.cpp b/Applications/Utils/MeshEdit/Vtu2Grid.cpp index 1db81bed240dd45628e477ecf6ffc8da16ff4892..4179fe3ad01c0e894ca5d985fa3e23279a02f7f2 100644 --- a/Applications/Utils/MeshEdit/Vtu2Grid.cpp +++ b/Applications/Utils/MeshEdit/Vtu2Grid.cpp @@ -8,15 +8,6 @@ */ #include <tclap/CmdLine.h> - -#include "InfoLib/GitInfo.h" - -#include "MeshLib/IO/writeMeshToFile.h" -#include "MeshLib/Mesh.h" -#include "MeshLib/MeshEditing/RemoveMeshComponents.h" -#include "MeshLib/MeshGenerators/MeshGenerator.h" -#include "MeshLib/MeshSearch/ElementSearch.h" - #include <vtkAbstractArray.h> #include <vtkCellData.h> #include <vtkCellLocator.h> @@ -27,18 +18,23 @@ #include <vtkUnstructuredGrid.h> #include <vtkXMLUnstructuredGridReader.h> +#include "InfoLib/GitInfo.h" +#include "MeshLib/IO/writeMeshToFile.h" +#include "MeshLib/Mesh.h" +#include "MeshLib/MeshEditing/RemoveMeshComponents.h" +#include "MeshLib/MeshGenerators/MeshGenerator.h" +#include "MeshLib/MeshSearch/ElementSearch.h" + std::string const cell_id_name = "CellIds"; std::array<std::size_t, 3> getDimensions(MathLib::Point3d const& min, MathLib::Point3d const& max, std::array<double, 3> const& cellsize) { - return - { + return { static_cast<std::size_t>(std::ceil((max[0] - min[0]) / cellsize[0])), static_cast<std::size_t>(std::ceil((max[1] - min[1]) / cellsize[1])), - static_cast<std::size_t>(std::ceil((max[2] - min[2]) / cellsize[2])) - }; + static_cast<std::size_t>(std::ceil((max[2] - min[2]) / cellsize[2]))}; } std::vector<int> assignCellIds(vtkSmartPointer<vtkUnstructuredGrid> const& mesh, @@ -51,7 +47,7 @@ std::vector<int> assignCellIds(vtkSmartPointer<vtkUnstructuredGrid> const& mesh, locator->SetDataSet(mesh); locator->Update(); - std::vector<int> cell_ids; + std::vector<int> cell_ids; cell_ids.reserve(dims[0] * dims[1] * dims[2]); std::array<double, 3> const grid_max = {min[0] + dims[0] * cellsize[0], min[1] + dims[1] * cellsize[1], @@ -82,7 +78,7 @@ bool removeUnusedGridCells(vtkSmartPointer<vtkUnstructuredGrid> const& mesh, if (n_elems_marked == grid->getNumberOfElements()) { - ERR ("No valid elements found. Aborting..."); + ERR("No valid elements found. Aborting..."); return false; } @@ -101,7 +97,7 @@ void mapArray(MeshLib::Mesh& grid, VTK_TYPE vtk_arr, std::string const& name) *grid.getProperties().getPropertyVector<int>( cell_id_name, MeshLib::MeshItemType::Cell, 1); std::vector<T>& arr = *grid.getProperties().createNewPropertyVector<T>( - name, MeshLib::MeshItemType::Cell, vtk_arr->GetNumberOfComponents()); + name, MeshLib::MeshItemType::Cell, vtk_arr->GetNumberOfComponents()); std::size_t const n_elems = cell_ids.size(); arr.resize(n_elems); for (std::size_t j = 0; j < n_elems; ++j) @@ -119,7 +115,8 @@ void mapMeshArraysOntoGrid(vtkSmartPointer<vtkUnstructuredGrid> const& mesh, dynamic_cast<vtkDoubleArray*>(cell_data->GetArray(name.c_str())); if (dbl_arr) { - mapArray<double, vtkSmartPointer<vtkDoubleArray>>(*grid, dbl_arr, name); + mapArray<double, vtkSmartPointer<vtkDoubleArray>>(*grid, dbl_arr, + name); continue; } vtkSmartPointer<vtkIntArray> const int_arr = @@ -133,7 +130,7 @@ void mapMeshArraysOntoGrid(vtkSmartPointer<vtkUnstructuredGrid> const& mesh, } } -int main (int argc, char* argv[]) +int main(int argc, char* argv[]) { TCLAP::CmdLine cmd( "Reads a 3D unstructured mesh and samples it onto a structured grid of " @@ -187,7 +184,7 @@ int main (int argc, char* argv[]) double const x_size = x_arg.getValue(); double const y_size = (y_arg.isSet()) ? y_arg.getValue() : x_arg.getValue(); double const z_size = (z_arg.isSet()) ? z_arg.getValue() : x_arg.getValue(); - std::array<double, 3> const cellsize = { x_size, y_size, z_size }; + std::array<double, 3> const cellsize = {x_size, y_size, z_size}; vtkSmartPointer<vtkXMLUnstructuredGridReader> reader = vtkSmartPointer<vtkXMLUnstructuredGridReader>::New(); @@ -196,15 +193,16 @@ int main (int argc, char* argv[]) vtkSmartPointer<vtkUnstructuredGrid> mesh = reader->GetOutput(); double* const bounds = mesh->GetBounds(); - MathLib::Point3d const min(std::array<double, 3>{bounds[0], bounds[2], bounds[4]}); - MathLib::Point3d const max(std::array<double, 3>{bounds[1], bounds[3], bounds[5]}); + MathLib::Point3d const min( + std::array<double, 3>{bounds[0], bounds[2], bounds[4]}); + MathLib::Point3d const max( + std::array<double, 3>{bounds[1], bounds[3], bounds[5]}); std::array<std::size_t, 3> const dims = getDimensions(min, max, cellsize); std::unique_ptr<MeshLib::Mesh> grid( MeshLib::MeshGenerator::generateRegularHexMesh( dims[0], dims[1], dims[2], cellsize[0], cellsize[1], cellsize[2], min, "grid")); - std::vector<int> const tmp_ids = assignCellIds(mesh, min, dims, cellsize); std::vector<int>& cell_ids = *grid->getProperties().createNewPropertyVector<int>( diff --git a/Applications/Utils/MeshEdit/appendLinesAlongPolyline.cpp b/Applications/Utils/MeshEdit/appendLinesAlongPolyline.cpp index 240fa23492a92cebb9babd7d9b2a8459200e9ad7..f34d0c7aab0e7b162c5d7f96eb699d3698dcd16d 100644 --- a/Applications/Utils/MeshEdit/appendLinesAlongPolyline.cpp +++ b/Applications/Utils/MeshEdit/appendLinesAlongPolyline.cpp @@ -7,23 +7,20 @@ * http://www.opengeosys.org/project/license */ +#include "MeshGeoToolsLib/AppendLinesAlongPolyline.h" + #include <tclap/CmdLine.h> #include "Applications/FileIO/readGeometryFromFile.h" - -#include "InfoLib/GitInfo.h" #include "BaseLib/FileTools.h" - #include "GeoLib/GEOObjects.h" #include "GeoLib/PolylineVec.h" - -#include "MeshGeoToolsLib/AppendLinesAlongPolyline.h" - -#include "MeshLib/IO/writeMeshToFile.h" +#include "InfoLib/GitInfo.h" #include "MeshLib/IO/readMeshFromFile.h" +#include "MeshLib/IO/writeMeshToFile.h" #include "MeshLib/Mesh.h" -int main (int argc, char* argv[]) +int main(int argc, char* argv[]) { TCLAP::CmdLine cmd( "Append line elements into a mesh.\n\n" @@ -33,16 +30,20 @@ int main (int argc, char* argv[]) "Copyright (c) 2012-2021, OpenGeoSys Community " "(http://www.opengeosys.org)", ' ', GitInfoLib::GitInfo::ogs_version); - TCLAP::ValueArg<std::string> mesh_in("i", "mesh-input-file", - "the name of the file containing the input mesh", true, - "", "file name of input mesh"); + TCLAP::ValueArg<std::string> mesh_in( + "i", "mesh-input-file", + "the name of the file containing the input mesh", true, "", + "file name of input mesh"); cmd.add(mesh_in); - TCLAP::ValueArg<std::string> mesh_out("o", "mesh-output-file", - "the name of the file the mesh will be written to", true, - "", "file name of output mesh"); + TCLAP::ValueArg<std::string> mesh_out( + "o", "mesh-output-file", + "the name of the file the mesh will be written to", true, "", + "file name of output mesh"); cmd.add(mesh_out); - TCLAP::ValueArg<std::string> geoFileArg("g", "geo-file", - "the name of the geometry file which contains polylines", true, "", "the name of the geometry file"); + TCLAP::ValueArg<std::string> geoFileArg( + "g", "geo-file", + "the name of the geometry file which contains polylines", true, "", + "the name of the geometry file"); cmd.add(geoFileArg); TCLAP::ValueArg<std::string> gmsh_path_arg("g", "gmsh-path", @@ -64,7 +65,8 @@ int main (int argc, char* argv[]) ERR("No geometries found."); return EXIT_FAILURE; } - const GeoLib::PolylineVec* ply_vec (geo_objs.getPolylineVecObj(geo_names[0])); + const GeoLib::PolylineVec* ply_vec( + geo_objs.getPolylineVecObj(geo_names[0])); if (!ply_vec) { ERR("Could not find polylines in geometry '{:s}'.", geo_names.front()); @@ -72,7 +74,8 @@ int main (int argc, char* argv[]) } // read a mesh - MeshLib::Mesh const*const mesh (MeshLib::IO::readMeshFromFile(mesh_in.getValue())); + MeshLib::Mesh const* const mesh( + MeshLib::IO::readMeshFromFile(mesh_in.getValue())); if (!mesh) { ERR("Mesh file '{:s}' not found", mesh_in.getValue()); diff --git a/Applications/Utils/MeshEdit/checkMesh.cpp b/Applications/Utils/MeshEdit/checkMesh.cpp index 6b7bc4c5be855cbd18c97cdc3e98487a3555b976..1d69c3aeafcdedcee5dc07bf8f53074f998718c9 100644 --- a/Applications/Utils/MeshEdit/checkMesh.cpp +++ b/Applications/Utils/MeshEdit/checkMesh.cpp @@ -7,26 +7,23 @@ * http://www.opengeosys.org/project/license */ +#include <tclap/CmdLine.h> + #include <array> #include <string> -#include <tclap/CmdLine.h> - -#include "InfoLib/GitInfo.h" -#include "BaseLib/StringTools.h" +#include "BaseLib/FileTools.h" #include "BaseLib/MemWatch.h" #include "BaseLib/RunTime.h" -#include "BaseLib/FileTools.h" - +#include "BaseLib/StringTools.h" #include "GeoLib/AABB.h" - -#include "MeshLib/Node.h" +#include "InfoLib/GitInfo.h" #include "MeshLib/Elements/Element.h" +#include "MeshLib/IO/readMeshFromFile.h" #include "MeshLib/Mesh.h" #include "MeshLib/MeshInformation.h" #include "MeshLib/MeshQuality/MeshValidation.h" - -#include "MeshLib/IO/readMeshFromFile.h" +#include "MeshLib/Node.h" int main(int argc, char* argv[]) { diff --git a/Applications/Utils/MeshEdit/convertToLinearMesh.cpp b/Applications/Utils/MeshEdit/convertToLinearMesh.cpp index 8346b2ae1aaaa369e910557741f26869d9539559..5cab4e7b29da56319779ad4eab0a7d0eea52fdc4 100644 --- a/Applications/Utils/MeshEdit/convertToLinearMesh.cpp +++ b/Applications/Utils/MeshEdit/convertToLinearMesh.cpp @@ -7,21 +7,19 @@ * http://www.opengeosys.org/project/license */ -#include <memory> -#include <string> +#include "MeshLib/MeshEditing/ConvertToLinearMesh.h" #include <tclap/CmdLine.h> -#include "InfoLib/GitInfo.h" - -#include "MeshLib/Mesh.h" -#include "MeshLib/MeshEditing/ConvertToLinearMesh.h" +#include <memory> +#include <string> +#include "InfoLib/GitInfo.h" #include "MeshLib/IO/readMeshFromFile.h" #include "MeshLib/IO/writeMeshToFile.h" +#include "MeshLib/Mesh.h" - -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { TCLAP::CmdLine cmd( "Convert a non-linear mesh to a linear mesh.\n\n" @@ -31,12 +29,14 @@ int main(int argc, char *argv[]) "Copyright (c) 2012-2021, OpenGeoSys Community " "(http://www.opengeosys.org)", ' ', GitInfoLib::GitInfo::ogs_version); - TCLAP::ValueArg<std::string> input_arg("i", "input-mesh-file","input mesh file",true,"","string"); - cmd.add( input_arg ); - TCLAP::ValueArg<std::string> output_arg("o", "output-mesh-file","output mesh file",true,"","string"); - cmd.add( output_arg ); + TCLAP::ValueArg<std::string> input_arg( + "i", "input-mesh-file", "input mesh file", true, "", "string"); + cmd.add(input_arg); + TCLAP::ValueArg<std::string> output_arg( + "o", "output-mesh-file", "output mesh file", true, "", "string"); + cmd.add(output_arg); - cmd.parse( argc, argv ); + cmd.parse(argc, argv); std::unique_ptr<MeshLib::Mesh> mesh( MeshLib::IO::readMeshFromFile(input_arg.getValue())); @@ -51,7 +51,8 @@ int main(int argc, char *argv[]) } INFO("Converting to a linear order mesh"); - std::unique_ptr<MeshLib::Mesh> new_mesh(MeshLib::convertToLinearMesh(*mesh, mesh->getName()+"_linear")); + std::unique_ptr<MeshLib::Mesh> new_mesh( + MeshLib::convertToLinearMesh(*mesh, mesh->getName() + "_linear")); INFO("Save the new mesh into a file"); MeshLib::IO::writeMeshToFile(*new_mesh, output_arg.getValue()); diff --git a/Applications/Utils/MeshEdit/createLayeredMeshFromRasters.cpp b/Applications/Utils/MeshEdit/createLayeredMeshFromRasters.cpp index 2d3c1c7144c62917dbdf5f0496dc7232a7e560ba..6603a7c3970cb4adbd8365e585820e2f6c1bc3fe 100644 --- a/Applications/Utils/MeshEdit/createLayeredMeshFromRasters.cpp +++ b/Applications/Utils/MeshEdit/createLayeredMeshFromRasters.cpp @@ -9,26 +9,24 @@ * http://www.opengeosys.org/project/license */ +#include <tclap/CmdLine.h> + #include <algorithm> #include <iterator> #include <memory> #include <string> #include <vector> -#include <tclap/CmdLine.h> - -#include "InfoLib/GitInfo.h" +#include "Applications/FileIO/AsciiRasterInterface.h" #include "BaseLib/FileTools.h" #include "BaseLib/IO/readStringListFromFile.h" - -#include "MeshLib/IO/readMeshFromFile.h" +#include "InfoLib/GitInfo.h" #include "MeshLib/IO/VtkIO/VtuInterface.h" -#include "Applications/FileIO/AsciiRasterInterface.h" - +#include "MeshLib/IO/readMeshFromFile.h" #include "MeshLib/Mesh.h" #include "MeshLib/MeshGenerators/MeshLayerMapper.h" -int main (int argc, char* argv[]) +int main(int argc, char* argv[]) { TCLAP::CmdLine cmd( "Creates a layered 3D OGS mesh from an existing 2D OGS mesh and a list " @@ -63,16 +61,14 @@ int main (int argc, char* argv[]) true, "", "file name"); cmd.add(raster_path_arg); - TCLAP::ValueArg<std::string> mesh_out_arg( - "o", "output-mesh-file", - "The file name of the resulting 3D mesh.", + TCLAP::ValueArg<std::string> mesh_out_arg( + "o", "output-mesh-file", "The file name of the resulting 3D mesh.", true, "", "file name"); cmd.add(mesh_out_arg); - TCLAP::ValueArg<std::string> mesh_arg( - "i", "input-mesh-file", - "The file name of the 2D input mesh.", true, "", - "file name"); + TCLAP::ValueArg<std::string> mesh_arg("i", "input-mesh-file", + "The file name of the 2D input mesh.", + true, "", "file name"); cmd.add(mesh_arg); cmd.parse(argc, argv); @@ -104,9 +100,9 @@ int main (int argc, char* argv[]) std::vector<std::string> raster_paths = BaseLib::IO::readStringListFromFile(raster_path_arg.getValue()); - if (raster_paths.size()<2) + if (raster_paths.size() < 2) { - ERR ("At least two raster files needed to create 3D mesh."); + ERR("At least two raster files needed to create 3D mesh."); return EXIT_FAILURE; } std::reverse(raster_paths.begin(), raster_paths.end()); diff --git a/Applications/Utils/MeshEdit/createQuadraticMesh.cpp b/Applications/Utils/MeshEdit/createQuadraticMesh.cpp index 474580c172df9578c5e8c7b7a4683d9cf780770f..9a5818a8f31713acc4c8449261c112156e363982 100644 --- a/Applications/Utils/MeshEdit/createQuadraticMesh.cpp +++ b/Applications/Utils/MeshEdit/createQuadraticMesh.cpp @@ -7,21 +7,18 @@ * http://www.opengeosys.org/project/license */ +#include <tclap/CmdLine.h> + #include <memory> #include <string> -#include <tclap/CmdLine.h> - #include "InfoLib/GitInfo.h" - -#include "MeshLib/Mesh.h" -#include "MeshLib/MeshGenerators/QuadraticMeshGenerator.h" - #include "MeshLib/IO/readMeshFromFile.h" #include "MeshLib/IO/writeMeshToFile.h" +#include "MeshLib/Mesh.h" +#include "MeshLib/MeshGenerators/QuadraticMeshGenerator.h" - -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { TCLAP::CmdLine cmd( "Create quadratic order mesh.\n\n" @@ -32,14 +29,16 @@ int main(int argc, char *argv[]) "(http://www.opengeosys.org)", ' ', GitInfoLib::GitInfo::ogs_version); - TCLAP::ValueArg<std::string> input_arg("i", "input-mesh-file","input mesh file",true,"","string"); - cmd.add( input_arg ); - TCLAP::ValueArg<std::string> output_arg("o", "output-mesh-file","output mesh file",true,"","string"); - cmd.add( output_arg ); + TCLAP::ValueArg<std::string> input_arg( + "i", "input-mesh-file", "input mesh file", true, "", "string"); + cmd.add(input_arg); + TCLAP::ValueArg<std::string> output_arg( + "o", "output-mesh-file", "output mesh file", true, "", "string"); + cmd.add(output_arg); TCLAP::SwitchArg add_centre_node_arg("c", "add-centre-node", "add centre node", false); cmd.add(add_centre_node_arg); - cmd.parse( argc, argv ); + cmd.parse(argc, argv); std::unique_ptr<MeshLib::Mesh> mesh( MeshLib::IO::readMeshFromFile(input_arg.getValue())); diff --git a/Applications/Utils/MeshEdit/editMaterialID.cpp b/Applications/Utils/MeshEdit/editMaterialID.cpp index cf318c15810fe51c860aedcd421c49940b6163ec..15763dd850399fc80eb147c2d23e99bbf15cca95 100644 --- a/Applications/Utils/MeshEdit/editMaterialID.cpp +++ b/Applications/Utils/MeshEdit/editMaterialID.cpp @@ -7,10 +7,10 @@ * http://www.opengeosys.org/project/license */ -#include <memory> - #include <tclap/CmdLine.h> +#include <memory> + #include "InfoLib/GitInfo.h" #include "MeshLib/Elements/Element.h" #include "MeshLib/IO/readMeshFromFile.h" @@ -18,7 +18,7 @@ #include "MeshLib/Mesh.h" #include "MeshLib/MeshEditing/ElementValueModification.h" -int main (int argc, char* argv[]) +int main(int argc, char* argv[]) { TCLAP::CmdLine cmd( "Edit material IDs of mesh elements.\n\n" @@ -29,36 +29,42 @@ int main (int argc, char* argv[]) "(http://www.opengeosys.org)", ' ', GitInfoLib::GitInfo::ogs_version); TCLAP::SwitchArg replaceArg("r", "replace", "replace material IDs", false); - TCLAP::SwitchArg condenseArg("c", "condense", "condense material IDs", false); - TCLAP::SwitchArg specifyArg("s", "specify", "specify material IDs by element types (-e)", false); + TCLAP::SwitchArg condenseArg("c", "condense", "condense material IDs", + false); + TCLAP::SwitchArg specifyArg( + "s", "specify", "specify material IDs by element types (-e)", false); std::vector<TCLAP::Arg*> vec_xors; vec_xors.push_back(&replaceArg); vec_xors.push_back(&condenseArg); vec_xors.push_back(&specifyArg); cmd.xorAdd(vec_xors); - TCLAP::ValueArg<std::string> mesh_in("i", "mesh-input-file", - "the name of the file containing the input mesh", true, - "", "file name"); + TCLAP::ValueArg<std::string> mesh_in( + "i", "mesh-input-file", + "the name of the file containing the input mesh", true, "", + "file name"); cmd.add(mesh_in); - TCLAP::ValueArg<std::string> mesh_out("o", "mesh-output-file", - "the name of the file the mesh will be written to", true, - "", "file name"); + TCLAP::ValueArg<std::string> mesh_out( + "o", "mesh-output-file", + "the name of the file the mesh will be written to", true, "", + "file name"); cmd.add(mesh_out); TCLAP::MultiArg<unsigned> matIDArg("m", "current-material-id", - "current material id to be replaced", false, "number"); + "current material id to be replaced", + false, "number"); cmd.add(matIDArg); TCLAP::ValueArg<unsigned> newIDArg("n", "new-material-id", - "new material id", false, 0, "number"); + "new material id", false, 0, "number"); cmd.add(newIDArg); std::vector<std::string> eleList(MeshLib::getMeshElemTypeStringsShort()); TCLAP::ValuesConstraint<std::string> allowedVals(eleList); - TCLAP::ValueArg<std::string> eleTypeArg("e", "element-type", - "element type", false, "", &allowedVals); + TCLAP::ValueArg<std::string> eleTypeArg("e", "element-type", "element type", + false, "", &allowedVals); cmd.add(eleTypeArg); cmd.parse(argc, argv); - if (!replaceArg.isSet() && !condenseArg.isSet() && !specifyArg.isSet()) { + if (!replaceArg.isSet() && !condenseArg.isSet() && !specifyArg.isSet()) + { INFO("Please select editing mode: -r or -c or -s"); return 0; } @@ -69,13 +75,21 @@ int main (int argc, char* argv[]) } if (replaceArg.isSet()) { - if (!matIDArg.isSet() || !newIDArg.isSet()) { - INFO("current and new material IDs must be provided for replacement"); + if (!matIDArg.isSet() || !newIDArg.isSet()) + { + INFO( + "current and new material IDs must be provided for " + "replacement"); return 0; } - } else if (specifyArg.isSet()) { - if (!eleTypeArg.isSet() || !newIDArg.isSet()) { - INFO("element type and new material IDs must be provided to specify elements"); + } + else if (specifyArg.isSet()) + { + if (!eleTypeArg.isSet() || !newIDArg.isSet()) + { + INFO( + "element type and new material IDs must be provided to specify " + "elements"); return 0; } } @@ -85,23 +99,32 @@ int main (int argc, char* argv[]) INFO("Mesh read: {:d} nodes, {:d} elements.", mesh->getNumberOfNodes(), mesh->getNumberOfElements()); - if (condenseArg.isSet()) { + if (condenseArg.isSet()) + { INFO("Condensing material ID..."); MeshLib::ElementValueModification::condense(*mesh); - } else if (replaceArg.isSet()) { + } + else if (replaceArg.isSet()) + { INFO("Replacing material ID..."); const auto vecOldID = matIDArg.getValue(); const unsigned newID = newIDArg.getValue(); - for (auto oldID : vecOldID) { + for (auto oldID : vecOldID) + { INFO("{:d} -> {:d}", oldID, newID); - MeshLib::ElementValueModification::replace(*mesh, oldID, newID, true); + MeshLib::ElementValueModification::replace(*mesh, oldID, newID, + true); } - } else if (specifyArg.isSet()) { + } + else if (specifyArg.isSet()) + { INFO("Specifying material ID..."); const std::string eleTypeName(eleTypeArg.getValue()); - const MeshLib::MeshElemType eleType = MeshLib::String2MeshElemType(eleTypeName); + const MeshLib::MeshElemType eleType = + MeshLib::String2MeshElemType(eleTypeName); const unsigned newID = newIDArg.getValue(); - unsigned cnt = MeshLib::ElementValueModification::setByElementType(*mesh, eleType, newID); + unsigned cnt = MeshLib::ElementValueModification::setByElementType( + *mesh, eleType, newID); INFO("updated {:d} elements", cnt); } diff --git a/Applications/Utils/MeshEdit/moveMeshNodes.cpp b/Applications/Utils/MeshEdit/moveMeshNodes.cpp index 66b730645395cbf068e7dd7e450af7807aba1b99..33e13bdf7acbec74420c2705365b701828a0ed9a 100644 --- a/Applications/Utils/MeshEdit/moveMeshNodes.cpp +++ b/Applications/Utils/MeshEdit/moveMeshNodes.cpp @@ -12,23 +12,23 @@ #include <memory> #include <string> -#include "InfoLib/GitInfo.h" #include "BaseLib/FileTools.h" #include "GeoLib/AABB.h" +#include "InfoLib/GitInfo.h" #include "MathLib/MathTools.h" #include "MeshLib/IO/readMeshFromFile.h" #include "MeshLib/IO/writeMeshToFile.h" #include "MeshLib/Mesh.h" -#include "MeshLib/Node.h" -#include "MeshLib/MeshSearch/MeshElementGrid.h" #include "MeshLib/MeshEditing/ProjectPointOnMesh.h" +#include "MeshLib/MeshSearch/MeshElementGrid.h" +#include "MeshLib/Node.h" double getClosestPointElevation(MeshLib::Node const& p, - std::vector<MeshLib::Node*> const& nodes, - double const& max_dist) + std::vector<MeshLib::Node*> const& nodes, + double const& max_dist) { - double sqr_shortest_dist (max_dist); - double elevation (p[2]); + double sqr_shortest_dist(max_dist); + double elevation(p[2]); for (MeshLib::Node* node : nodes) { double sqr_dist = (p[0] - (*node)[0]) * (p[0] - (*node)[0]) + @@ -42,7 +42,7 @@ double getClosestPointElevation(MeshLib::Node const& p, return elevation; } -int main (int argc, char* argv[]) +int main(int argc, char* argv[]) { std::vector<std::string> keywords; keywords.emplace_back("-ALL"); @@ -71,7 +71,7 @@ int main (int argc, char* argv[]) const std::string msh_name(argv[1]); const std::string current_key(argv[2]); - std::string const ext (BaseLib::getFileExtension(msh_name)); + std::string const ext(BaseLib::getFileExtension(msh_name)); if (!(ext == ".msh" || ext == ".vtu")) { ERR("Error: Parameter 1 must be a mesh-file (*.msh / *.vtu)."); @@ -91,10 +91,11 @@ int main (int argc, char* argv[]) return EXIT_FAILURE; } - std::unique_ptr<MeshLib::Mesh> mesh (MeshLib::IO::readMeshFromFile(msh_name)); + std::unique_ptr<MeshLib::Mesh> mesh( + MeshLib::IO::readMeshFromFile(msh_name)); if (mesh == nullptr) { - ERR ("Error reading mesh file."); + ERR("Error reading mesh file."); return 1; } @@ -110,19 +111,20 @@ int main (int argc, char* argv[]) } const std::string dir(argv[3]); unsigned idx = (dir == "x") ? 0 : (dir == "y") ? 1 : 2; - const double value(strtod(argv[4],0)); + const double value(strtod(argv[4], 0)); INFO("Moving all mesh nodes by {:g} in direction {:d} ({:s})...", value, idx, dir); - //double value(-10); + // double value(-10); const std::size_t nNodes(mesh->getNumberOfNodes()); - std::vector<MeshLib::Node*> nodes (mesh->getNodes()); - for (std::size_t i=0; i<nNodes; i++) + std::vector<MeshLib::Node*> nodes(mesh->getNodes()); + for (std::size_t i = 0; i < nNodes; i++) { (*nodes[i])[idx] += value; } } - // maps the elevation of mesh nodes according to a ground truth mesh whenever nodes exist within max_dist + // maps the elevation of mesh nodes according to a ground truth mesh + // whenever nodes exist within max_dist if (current_key == "-MESH") { if (argc < 4) @@ -130,12 +132,13 @@ int main (int argc, char* argv[]) ERR("Missing parameter..."); return EXIT_FAILURE; } - const std::string value (argv[3]); - double max_dist(pow(strtod(argv[4],0), 2)); - std::unique_ptr<MeshLib::Mesh> ground_truth (MeshLib::IO::readMeshFromFile(value)); + const std::string value(argv[3]); + double max_dist(pow(strtod(argv[4], 0), 2)); + std::unique_ptr<MeshLib::Mesh> ground_truth( + MeshLib::IO::readMeshFromFile(value)); if (ground_truth == nullptr) { - ERR ("Error reading mesh file."); + ERR("Error reading mesh file."); return EXIT_FAILURE; } @@ -155,18 +158,21 @@ int main (int argc, char* argv[]) grid.getElementsInVolume(min_vol, max_vol); auto const* element = MeshLib::ProjectPointOnMesh::getProjectedElement(elems, *node); - (*node)[2] = (element != nullptr) - ? MeshLib::ProjectPointOnMesh::getElevation(*element, *node) - : getClosestPointElevation( *node, ground_truth->getNodes(), max_dist); + (*node)[2] = + (element != nullptr) + ? MeshLib::ProjectPointOnMesh::getElevation(*element, *node) + : getClosestPointElevation(*node, ground_truth->getNodes(), + max_dist); } } - // a simple lowpass filter for the elevation of mesh nodes using the elevation of each node - // weighted by 2 and the elevation of each connected node weighted by 1 + // a simple lowpass filter for the elevation of mesh nodes using the + // elevation of each node weighted by 2 and the elevation of each connected + // node weighted by 1 if (current_key == "-LOWPASS") { const std::size_t nNodes(mesh->getNumberOfNodes()); - std::vector<MeshLib::Node*> nodes (mesh->getNodes()); + std::vector<MeshLib::Node*> nodes(mesh->getNodes()); std::vector<double> elevation(nNodes); for (std::size_t i = 0; i < nNodes; i++) @@ -174,16 +180,17 @@ int main (int argc, char* argv[]) elevation[i] = (*nodes[i])[2]; } - for (std::size_t i=0; i<nNodes; i++) + for (std::size_t i = 0; i < nNodes; i++) { - const std::vector<MeshLib::Node*> conn_nodes (nodes[i]->getConnectedNodes()); - const unsigned nConnNodes (conn_nodes.size()); - elevation[i] = (2*(*nodes[i])[2]); + const std::vector<MeshLib::Node*> conn_nodes( + nodes[i]->getConnectedNodes()); + const unsigned nConnNodes(conn_nodes.size()); + elevation[i] = (2 * (*nodes[i])[2]); for (std::size_t j = 0; j < nConnNodes; ++j) { elevation[i] += (*conn_nodes[j])[2]; } - elevation[i] /= (nConnNodes+2); + elevation[i] /= (nConnNodes + 2); } for (std::size_t i = 0; i < nNodes; i++) @@ -193,7 +200,8 @@ int main (int argc, char* argv[]) } /**** add other keywords here ****/ - std::string const new_mesh_name (msh_name.substr(0, msh_name.length() - 4) + "_new.vtu"); + std::string const new_mesh_name(msh_name.substr(0, msh_name.length() - 4) + + "_new.vtu"); if (MeshLib::IO::writeMeshToFile(*mesh, new_mesh_name) != 0) { return EXIT_FAILURE; diff --git a/Applications/Utils/MeshEdit/queryMesh.cpp b/Applications/Utils/MeshEdit/queryMesh.cpp index c4d6ecd7325632e94c47de8a5459b2aab67e9a75..e844ce81809c2397de7f5b0e8f8eb1bb5d778b4a 100644 --- a/Applications/Utils/MeshEdit/queryMesh.cpp +++ b/Applications/Utils/MeshEdit/queryMesh.cpp @@ -7,23 +7,22 @@ * http://www.opengeosys.org/project/license */ +#include <tclap/CmdLine.h> + #include <array> #include <memory> #include <sstream> #include <string> -#include <tclap/CmdLine.h> - -#include "InfoLib/GitInfo.h" -#include "BaseLib/StringTools.h" #include "BaseLib/FileTools.h" - -#include "MeshLib/Node.h" +#include "BaseLib/StringTools.h" +#include "InfoLib/GitInfo.h" #include "MeshLib/Elements/Element.h" -#include "MeshLib/Mesh.h" #include "MeshLib/IO/readMeshFromFile.h" +#include "MeshLib/Mesh.h" +#include "MeshLib/Node.h" -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { TCLAP::CmdLine cmd( "Query mesh information.\n\n" @@ -33,39 +32,49 @@ int main(int argc, char *argv[]) "Copyright (c) 2012-2021, OpenGeoSys Community " "(http://www.opengeosys.org)", ' ', GitInfoLib::GitInfo::ogs_version); - TCLAP::UnlabeledValueArg<std::string> mesh_arg("mesh-file","input mesh file",true,"","string"); - cmd.add( mesh_arg ); - TCLAP::MultiArg<std::size_t> eleId_arg("e","element-id","element ID",false,"number"); - cmd.add( eleId_arg ); - TCLAP::MultiArg<std::size_t> nodeId_arg("n","node-id","node ID",false,"number"); - cmd.add( nodeId_arg ); - TCLAP::SwitchArg showNodeWithMaxEle_arg("", "show-node-with-max-elements", "show a node having the max number of connected elements", false); - cmd.add( showNodeWithMaxEle_arg ); + TCLAP::UnlabeledValueArg<std::string> mesh_arg( + "mesh-file", "input mesh file", true, "", "string"); + cmd.add(mesh_arg); + TCLAP::MultiArg<std::size_t> eleId_arg("e", "element-id", "element ID", + false, "number"); + cmd.add(eleId_arg); + TCLAP::MultiArg<std::size_t> nodeId_arg("n", "node-id", "node ID", false, + "number"); + cmd.add(nodeId_arg); + TCLAP::SwitchArg showNodeWithMaxEle_arg( + "", "show-node-with-max-elements", + "show a node having the max number of connected elements", false); + cmd.add(showNodeWithMaxEle_arg); - cmd.parse( argc, argv ); + cmd.parse(argc, argv); const std::string filename(mesh_arg.getValue()); // read the mesh file - auto const mesh = std::unique_ptr<MeshLib::Mesh>( - MeshLib::IO::readMeshFromFile(filename)); + auto const mesh = + std::unique_ptr<MeshLib::Mesh>(MeshLib::IO::readMeshFromFile(filename)); if (!mesh) { return EXIT_FAILURE; } std::vector<std::size_t> selected_node_ids; - if (showNodeWithMaxEle_arg.getValue()) + if (showNodeWithMaxEle_arg.getValue()) { - auto itr = std::max_element(mesh->getNodes().begin(), mesh->getNodes().end(), - [](MeshLib::Node* i, MeshLib::Node* j) { return i->getNumberOfElements() < j->getNumberOfElements(); }); + auto itr = std::max_element( + mesh->getNodes().begin(), mesh->getNodes().end(), + [](MeshLib::Node* i, MeshLib::Node* j) { + return i->getNumberOfElements() < j->getNumberOfElements(); + }); if (itr != mesh->getNodes().end()) { MeshLib::Node* node = *itr; selected_node_ids.push_back(node->getID()); } } - selected_node_ids.insert(selected_node_ids.end(), nodeId_arg.getValue().begin(), nodeId_arg.getValue().end()); + selected_node_ids.insert(selected_node_ids.end(), + nodeId_arg.getValue().begin(), + nodeId_arg.getValue().end()); auto const materialIds = materialIDs(*mesh); for (auto ele_id : eleId_arg.getValue()) @@ -73,7 +82,8 @@ int main(int argc, char *argv[]) std::stringstream out; out << std::scientific << std::setprecision(std::numeric_limits<double>::digits10); - out << "--------------------------------------------------------" << std::endl; + out << "--------------------------------------------------------" + << std::endl; auto* ele = mesh->getElement(ele_id); out << "# Element " << ele->getID() << std::endl; out << "Type : " << CellType2String(ele->getCellType()) << std::endl; @@ -89,7 +99,7 @@ int main(int argc, char *argv[]) } out << "Content: " << ele->getContent() << std::endl; out << "Neighbors: "; - for (unsigned i=0; i<ele->getNumberOfNeighbors(); i++) + for (unsigned i = 0; i < ele->getNumberOfNeighbors(); i++) { if (ele->getNeighbor(i)) { @@ -109,7 +119,8 @@ int main(int argc, char *argv[]) std::stringstream out; out << std::scientific << std::setprecision(std::numeric_limits<double>::digits10); - out << "--------------------------------------------------------" << std::endl; + out << "--------------------------------------------------------" + << std::endl; MeshLib::Node const* node = mesh->getNode(node_id); out << "# Node " << node->getID() << std::endl; out << "Coordinates: " << *node << std::endl; diff --git a/Applications/Utils/MeshEdit/removeMeshElements.cpp b/Applications/Utils/MeshEdit/removeMeshElements.cpp index 6b598c4dd7c6fff4ac40bd3220593ed3525d3ee4..2ed89a584bf25e4a588904145c0bd8b2e1142759 100644 --- a/Applications/Utils/MeshEdit/removeMeshElements.cpp +++ b/Applications/Utils/MeshEdit/removeMeshElements.cpp @@ -11,10 +11,10 @@ * http://www.opengeosys.org/project/license */ -#include <memory> - #include <tclap/CmdLine.h> +#include <memory> + #include "InfoLib/GitInfo.h" #include "MeshLib/Elements/Element.h" #include "MeshLib/IO/readMeshFromFile.h" @@ -66,7 +66,7 @@ void searchByPropertyRange(std::string const& property_name, std::to_string(min_value), std::to_string(max_value)); } -int main (int argc, char* argv[]) +int main(int argc, char* argv[]) { TCLAP::CmdLine cmd( "Removes mesh elements based on element type, element volume, scalar " @@ -81,27 +81,34 @@ int main (int argc, char* argv[]) ' ', GitInfoLib::GitInfo::ogs_version); // Bounding box params - TCLAP::ValueArg<double> zLargeArg("", "z-max", "largest allowed extent in z-dimension", - false, std::numeric_limits<double>::max(), "value"); + TCLAP::ValueArg<double> zLargeArg( + "", "z-max", "largest allowed extent in z-dimension", false, + std::numeric_limits<double>::max(), "value"); cmd.add(zLargeArg); - TCLAP::ValueArg<double> zSmallArg("", "z-min", "smallest allowed extent in z-dimension", - false, -1 * std::numeric_limits<double>::max(), "value"); + TCLAP::ValueArg<double> zSmallArg( + "", "z-min", "smallest allowed extent in z-dimension", false, + -1 * std::numeric_limits<double>::max(), "value"); cmd.add(zSmallArg); - TCLAP::ValueArg<double> yLargeArg("", "y-max", "largest allowed extent in y-dimension", - false, std::numeric_limits<double>::max(), "value"); + TCLAP::ValueArg<double> yLargeArg( + "", "y-max", "largest allowed extent in y-dimension", false, + std::numeric_limits<double>::max(), "value"); cmd.add(yLargeArg); - TCLAP::ValueArg<double> ySmallArg("", "y-min", "smallest allowed extent in y-dimension", - false, -1 * std::numeric_limits<double>::max(), "value"); + TCLAP::ValueArg<double> ySmallArg( + "", "y-min", "smallest allowed extent in y-dimension", false, + -1 * std::numeric_limits<double>::max(), "value"); cmd.add(ySmallArg); - TCLAP::ValueArg<double> xLargeArg("", "x-max", "largest allowed extent in x-dimension", - false, std::numeric_limits<double>::max(), "value"); + TCLAP::ValueArg<double> xLargeArg( + "", "x-max", "largest allowed extent in x-dimension", false, + std::numeric_limits<double>::max(), "value"); cmd.add(xLargeArg); - TCLAP::ValueArg<double> xSmallArg("", "x-min", "smallest allowed extent in x-dimension", - false, -1 * std::numeric_limits<double>::max(), "value"); + TCLAP::ValueArg<double> xSmallArg( + "", "x-min", "smallest allowed extent in x-dimension", false, + -1 * std::numeric_limits<double>::max(), "value"); cmd.add(xSmallArg); // Non-bounding-box params - TCLAP::SwitchArg zveArg("z", "zero-volume", "remove zero volume elements", false); + TCLAP::SwitchArg zveArg("z", "zero-volume", "remove zero volume elements", + false); cmd.add(zveArg); std::vector<std::string> allowed_ele_types{"line", "tri", "quad", "hex", @@ -116,19 +123,23 @@ int main (int argc, char* argv[]) // scalar array params TCLAP::ValueArg<std::string> property_name_arg( - "n", "property-name", "name of property in the mesh", false, "MaterialIDs", "string"); + "n", "property-name", "name of property in the mesh", false, + "MaterialIDs", "string"); cmd.add(property_name_arg); TCLAP::MultiArg<int> property_arg( - "", "property-value", "value of selected property to be removed", false, "number"); + "", "property-value", "value of selected property to be removed", false, + "number"); cmd.add(property_arg); TCLAP::ValueArg<double> min_property_arg( - "", "min-value", "minimum value of range for selected property", false, 0, "number"); + "", "min-value", "minimum value of range for selected property", false, + 0, "number"); cmd.add(min_property_arg); TCLAP::ValueArg<double> max_property_arg( - "", "max-value", "maximum value of range for selected property", false, 0, "number"); + "", "max-value", "maximum value of range for selected property", false, + 0, "number"); cmd.add(max_property_arg); TCLAP::SwitchArg outside_property_arg( @@ -140,13 +151,15 @@ int main (int argc, char* argv[]) cmd.add(inside_property_arg); // I/O params - TCLAP::ValueArg<std::string> mesh_out("o", "mesh-output-file", - "the name of the file the mesh will be written to", true, - "", "file name of output mesh"); + TCLAP::ValueArg<std::string> mesh_out( + "o", "mesh-output-file", + "the name of the file the mesh will be written to", true, "", + "file name of output mesh"); cmd.add(mesh_out); - TCLAP::ValueArg<std::string> mesh_in("i", "mesh-input-file", - "the name of the file containing the input mesh", true, - "", "file name of input mesh"); + TCLAP::ValueArg<std::string> mesh_in( + "i", "mesh-input-file", + "the name of the file containing the input mesh", true, "", + "file name of input mesh"); cmd.add(mesh_in); cmd.parse(argc, argv); @@ -162,13 +175,17 @@ int main (int argc, char* argv[]) MeshLib::ElementSearch searcher(*mesh); // search elements IDs to be removed - if (zveArg.isSet()) { + if (zveArg.isSet()) + { INFO("{:d} zero volume elements found.", searcher.searchByContent()); } - if (eleTypeArg.isSet()) { + if (eleTypeArg.isSet()) + { const std::vector<std::string> eleTypeNames = eleTypeArg.getValue(); - for (const auto& typeName : eleTypeNames) { - const MeshLib::MeshElemType type = MeshLib::String2MeshElemType(typeName); + for (const auto& typeName : eleTypeNames) + { + const MeshLib::MeshElemType type = + MeshLib::String2MeshElemType(typeName); if (type == MeshLib::MeshElemType::INVALID) { continue; @@ -181,7 +198,8 @@ int main (int argc, char* argv[]) if (property_name_arg.isSet() || property_arg.isSet() || min_property_arg.isSet() || max_property_arg.isSet()) { - if ((property_arg.isSet() || min_property_arg.isSet() || max_property_arg.isSet()) && + if ((property_arg.isSet() || min_property_arg.isSet() || + max_property_arg.isSet()) && !property_name_arg.isSet()) { ERR("Specify a property name for the value/range selected."); @@ -189,10 +207,11 @@ int main (int argc, char* argv[]) } if (property_name_arg.isSet() && - !((min_property_arg.isSet() && max_property_arg.isSet()) || property_arg.isSet())) + !((min_property_arg.isSet() && max_property_arg.isSet()) || + property_arg.isSet())) { - ERR("Specify a value or range ('-min-value' and '-max_value') " - "for the property selected."); + ERR("Specify a value or range ('-min-value' and '-max_value') for " + "the property selected."); return EXIT_FAILURE; } @@ -223,24 +242,23 @@ int main (int argc, char* argv[]) } } - if (xSmallArg.isSet() || xLargeArg.isSet() || - ySmallArg.isSet() || yLargeArg.isSet() || - zSmallArg.isSet() || zLargeArg.isSet()) + if (xSmallArg.isSet() || xLargeArg.isSet() || ySmallArg.isSet() || + yLargeArg.isSet() || zSmallArg.isSet() || zLargeArg.isSet()) { - bool aabb_error (false); + bool aabb_error(false); if (xSmallArg.getValue() >= xLargeArg.getValue()) { - ERR ("Minimum x-extent larger than maximum x-extent."); + ERR("Minimum x-extent larger than maximum x-extent."); aabb_error = true; } if (ySmallArg.getValue() >= yLargeArg.getValue()) { - ERR ("Minimum y-extent larger than maximum y-extent."); + ERR("Minimum y-extent larger than maximum y-extent."); aabb_error = true; } if (zSmallArg.getValue() >= zLargeArg.getValue()) { - ERR ("Minimum z-extent larger than maximum z-extent."); + ERR("Minimum z-extent larger than maximum z-extent."); aabb_error = true; } if (aabb_error) @@ -248,11 +266,13 @@ int main (int argc, char* argv[]) return EXIT_FAILURE; } - std::array<MathLib::Point3d, 2> extent({{ - MathLib::Point3d(std::array<double,3>{{xSmallArg.getValue(), - ySmallArg.getValue(), zSmallArg.getValue()}}), - MathLib::Point3d(std::array<double,3>{{xLargeArg.getValue(), - yLargeArg.getValue(), zLargeArg.getValue()}})}}); + std::array<MathLib::Point3d, 2> extent( + {{MathLib::Point3d(std::array<double, 3>{{xSmallArg.getValue(), + ySmallArg.getValue(), + zSmallArg.getValue()}}), + MathLib::Point3d(std::array<double, 3>{ + {xLargeArg.getValue(), yLargeArg.getValue(), + zLargeArg.getValue()}})}}); INFO("{:d} elements found.", searcher.searchByBoundingBox( GeoLib::AABB(extent.begin(), extent.end()))); diff --git a/Applications/Utils/MeshEdit/reviseMesh.cpp b/Applications/Utils/MeshEdit/reviseMesh.cpp index 0ad872059e414957c113c247e0bd03e3cf2607bd..ff97da6b27f652f308f7008a2e14579a2326435c 100644 --- a/Applications/Utils/MeshEdit/reviseMesh.cpp +++ b/Applications/Utils/MeshEdit/reviseMesh.cpp @@ -7,25 +7,23 @@ * http://www.opengeosys.org/project/license */ +#include <tclap/CmdLine.h> + #include <array> #include <memory> #include <string> -#include <tclap/CmdLine.h> - -#include "InfoLib/GitInfo.h" -#include "BaseLib/StringTools.h" #include "BaseLib/FileTools.h" - -#include "MeshLib/Node.h" +#include "BaseLib/StringTools.h" +#include "InfoLib/GitInfo.h" #include "MeshLib/Elements/Element.h" -#include "MeshLib/Mesh.h" -#include "MeshLib/MeshEditing/MeshRevision.h" - #include "MeshLib/IO/readMeshFromFile.h" #include "MeshLib/IO/writeMeshToFile.h" +#include "MeshLib/Mesh.h" +#include "MeshLib/MeshEditing/MeshRevision.h" +#include "MeshLib/Node.h" -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { TCLAP::CmdLine cmd( "Revises meshes by collapsing duplicate nodes, (optionally) removing " @@ -55,7 +53,7 @@ int main(int argc, char *argv[]) TCLAP::ValueArg<std::string> input_arg( "i", "input-mesh-file", "input mesh file", true, "", "string"); cmd.add(input_arg); - cmd.parse( argc, argv ); + cmd.parse(argc, argv); // read a mesh file std::unique_ptr<MeshLib::Mesh> org_mesh( @@ -70,12 +68,14 @@ int main(int argc, char *argv[]) // revise the mesh INFO("Simplifying the mesh..."); MeshLib::MeshRevision const rev(const_cast<MeshLib::Mesh&>(*org_mesh)); - unsigned int minDim = (minDim_arg.isSet() ? minDim_arg.getValue() : org_mesh->getDimension()); + unsigned int minDim = + (minDim_arg.isSet() ? minDim_arg.getValue() : org_mesh->getDimension()); std::unique_ptr<MeshLib::Mesh> new_mesh( rev.simplifyMesh("revised_mesh", eps_arg.getValue(), minDim)); // write into a file - if (new_mesh) { + if (new_mesh) + { INFO("Revised mesh: {:d} nodes, {:d} elements.", new_mesh->getNumberOfNodes(), new_mesh->getNumberOfElements()); MeshLib::IO::writeMeshToFile(*new_mesh, output_arg.getValue()); diff --git a/Applications/Utils/MeshEdit/swapNodeCoordinateAxes.cpp b/Applications/Utils/MeshEdit/swapNodeCoordinateAxes.cpp index 3fd895d738fd7541c76c81f8f0a1025ba0ac1507..0b3e741251c3e16252c159f81a2d7b848cf704e1 100644 --- a/Applications/Utils/MeshEdit/swapNodeCoordinateAxes.cpp +++ b/Applications/Utils/MeshEdit/swapNodeCoordinateAxes.cpp @@ -7,20 +7,18 @@ * http://www.opengeosys.org/project/license */ +#include <tclap/CmdLine.h> + #include <array> #include <memory> #include <string> -#include <tclap/CmdLine.h> - -#include "InfoLib/GitInfo.h" #include "BaseLib/Logging.h" - -#include "MeshLib/Mesh.h" -#include "MeshLib/Node.h" - +#include "InfoLib/GitInfo.h" #include "MeshLib/IO/readMeshFromFile.h" #include "MeshLib/IO/writeMeshToFile.h" +#include "MeshLib/Mesh.h" +#include "MeshLib/Node.h" static void swapNodeCoordinateAxes(MeshLib::Mesh const& mesh, std::array<int, 3> const& new_axes_indices) @@ -39,17 +37,19 @@ static void swapNodeCoordinateAxes(MeshLib::Mesh const& mesh, } } -static bool parseNewOrder(std::string const& str_order, std::array<int, 3> &new_axes_indices) +static bool parseNewOrder(std::string const& str_order, + std::array<int, 3>& new_axes_indices) { - if (str_order.length()!=3) + if (str_order.length() != 3) { - ERR("Invalid argument for the new order. The argument should contain three characters."); + ERR("Invalid argument for the new order. The argument should contain " + "three characters."); return false; } new_axes_indices.fill(-1); - for (int i=0; i<3; i++) + for (int i = 0; i < 3; i++) { if (str_order[i] == 'x') { @@ -76,7 +76,8 @@ static bool parseNewOrder(std::string const& str_order, std::array<int, 3> &new_ { if (isAxisSet[new_axes_indice]) { - ERR("Invalid argument for the new order. The argument contains some character used more than once."); + ERR("Invalid argument for the new order. The argument contains " + "some character used more than once."); return false; } isAxisSet[new_axes_indice] = true; @@ -85,7 +86,7 @@ static bool parseNewOrder(std::string const& str_order, std::array<int, 3> &new_ return true; } -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { TCLAP::CmdLine cmd( "Swap node coordinate values.\n\n" @@ -95,17 +96,19 @@ int main(int argc, char *argv[]) "Copyright (c) 2012-2021, OpenGeoSys Community " "(http://www.opengeosys.org)", ' ', GitInfoLib::GitInfo::ogs_version); - TCLAP::ValueArg<std::string> input_arg("i", "input-mesh-file","input mesh file",true,"","string"); - cmd.add( input_arg ); - TCLAP::ValueArg<std::string> output_arg("o", "output-mesh-file","output mesh file",true,"","string"); - cmd.add( output_arg ); + TCLAP::ValueArg<std::string> input_arg( + "i", "input-mesh-file", "input mesh file", true, "", "string"); + cmd.add(input_arg); + TCLAP::ValueArg<std::string> output_arg( + "o", "output-mesh-file", "output mesh file", true, "", "string"); + cmd.add(output_arg); TCLAP::ValueArg<std::string> new_order_arg( "n", "new-order", - "the new order of swapped coordinate values " - "(e.g. 'xzy' for converting XYZ values to XZY values)", + "the new order of swapped coordinate values (e.g. 'xzy' for converting " + "XYZ values to XZY values)", true, "", "string"); - cmd.add( new_order_arg ); - cmd.parse( argc, argv ); + cmd.add(new_order_arg); + cmd.parse(argc, argv); const std::string str_order = new_order_arg.getValue(); std::array<int, 3> new_order = {{}}; @@ -123,7 +126,9 @@ int main(int argc, char *argv[]) if (mesh->getDimension() == 3) { - WARN("Swapping coordinate values of 3D elements can result in incorrect node-ordering."); + WARN( + "Swapping coordinate values of 3D elements can result in incorrect " + "node-ordering."); } INFO("Exchange node coordinates from xyz to {:s}", diff --git a/Applications/Utils/MeshGeoTools/IntegrateBoreholesIntoMesh.cpp b/Applications/Utils/MeshGeoTools/IntegrateBoreholesIntoMesh.cpp index 572b9746ed1a383ed36b15df1e40198de89aeb6c..460ff05dfb615a2368ce879a60980e0ce42c6d99 100644 --- a/Applications/Utils/MeshGeoTools/IntegrateBoreholesIntoMesh.cpp +++ b/Applications/Utils/MeshGeoTools/IntegrateBoreholesIntoMesh.cpp @@ -78,8 +78,8 @@ int main(int argc, char* argv[]) "via line elements. Each borehole (i.e. all points at a given " "(x,y)-location but at different depths) is assigned a unique material " "ID. Vertical limits of boreholes can be specified via Material IDs " - "and/or elevation. Point not matching any mesh nodes or located outside " - "the mesh are ignored.\n\n" + "and/or elevation. Point not matching any mesh nodes or located outside" + " the mesh are ignored.\n\n" "OpenGeoSys-6 software, version " + GitInfoLib::GitInfo::ogs_version + ".\n" diff --git a/Applications/Utils/MeshGeoTools/Raster2Mesh.cpp b/Applications/Utils/MeshGeoTools/Raster2Mesh.cpp index 2e20dd5a76dc4fd1cca318286bcfc31ff935a0a6..d73870eb532cb287029e1af2bced1b540f0fe331 100644 --- a/Applications/Utils/MeshGeoTools/Raster2Mesh.cpp +++ b/Applications/Utils/MeshGeoTools/Raster2Mesh.cpp @@ -13,16 +13,15 @@ // ThirdParty #include <tclap/CmdLine.h> -#include "InfoLib/GitInfo.h" - +#include "Applications/FileIO/AsciiRasterInterface.h" #include "GeoLib/Raster.h" +#include "InfoLib/GitInfo.h" +#include "MeshLib/IO/VtkIO/VtuInterface.h" #include "MeshLib/Mesh.h" #include "MeshLib/MeshEnums.h" -#include "MeshLib/IO/VtkIO/VtuInterface.h" #include "MeshLib/MeshGenerators/RasterToMesh.h" -#include "Applications/FileIO/AsciiRasterInterface.h" -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { TCLAP::CmdLine cmd( "Converts an ASCII raster file (*.asc) into a 2D triangle- or " @@ -59,17 +58,15 @@ int main(int argc, char *argv[]) "e", "elem-type", "The element type used in the resulting OGS mesh.", true, "", &allowed_elem_vals); cmd.add(arg_elem_type); - TCLAP::ValueArg<std::string> output_arg( - "o", "output", - "Name of the output mesh (*.vtu)", - true, "", "output file name"); + TCLAP::ValueArg<std::string> output_arg("o", "output", + "Name of the output mesh (*.vtu)", + true, "", "output file name"); cmd.add(output_arg); - TCLAP::ValueArg<std::string> input_arg( - "i", "input", - "Name of the input raster (*.asc)", - true, "", "input file name"); + TCLAP::ValueArg<std::string> input_arg("i", "input", + "Name of the input raster (*.asc)", + true, "", "input file name"); cmd.add(input_arg); - cmd.parse( argc, argv ); + cmd.parse(argc, argv); std::string const input_name = input_arg.getValue().c_str(); std::string const output_name = output_arg.getValue().c_str(); @@ -89,7 +86,8 @@ int main(int argc, char *argv[]) intensity_type = MeshLib::UseIntensityAs::DATAVECTOR; std::string array_name = "Values"; - if (intensity_type == MeshLib::UseIntensityAs::DATAVECTOR && array_name_arg.isSet()) + if (intensity_type == MeshLib::UseIntensityAs::DATAVECTOR && + array_name_arg.isSet()) array_name = array_name_arg.getValue().c_str(); else if (intensity_type == MeshLib::UseIntensityAs::MATERIALS) array_name = "MaterialIDs"; diff --git a/Applications/Utils/MeshGeoTools/VerticalSliceFromLayers.cpp b/Applications/Utils/MeshGeoTools/VerticalSliceFromLayers.cpp index a542e141cc7432b8718290289f9640ece711ee2d..6d6a07f80b5ab4f30cbad3a7ef6c2d6a3a989d50 100644 --- a/Applications/Utils/MeshGeoTools/VerticalSliceFromLayers.cpp +++ b/Applications/Utils/MeshGeoTools/VerticalSliceFromLayers.cpp @@ -15,6 +15,7 @@ // ThirdParty #include <tclap/CmdLine.h> + #include <QCoreApplication> #include "Applications/FileIO/Gmsh/GMSHInterface.h" @@ -183,7 +184,8 @@ std::pair<Eigen::Matrix3d, double> rotateGeometryToXY( GeoLib::rotatePoints(rotation_matrix, points.begin(), points.end()); GeoLib::AABB aabb(points.begin(), points.end()); - double const z_shift = (aabb.getMinPoint()[2] + aabb.getMaxPoint()[2]) / 2.0; + double const z_shift = + (aabb.getMinPoint()[2] + aabb.getMaxPoint()[2]) / 2.0; std::for_each(points.begin(), points.end(), [z_shift](GeoLib::Point* p) { (*p)[2] -= z_shift; }); return {rotation_matrix, z_shift}; @@ -236,8 +238,7 @@ MeshLib::Mesh* generateMesh(GeoLib::GEOObjects& geo, int const return_value = std::system(gmsh_command.c_str()); if (return_value != 0) { - ERR("Execution of gmsh command returned non-zero " - "status, %d", + ERR("Execution of gmsh command returned non-zero status, %d", return_value); } return FileIO::GMSH::readGMSHMesh(gmsh_mesh_name); @@ -323,7 +324,7 @@ void extractBoundaries(MeshLib::Mesh const& mesh, continue; } // elements located at top or bottom - if (dist2.squaredNorm() < dist1.squaredNorm() ) + if (dist2.squaredNorm() < dist1.squaredNorm()) { top_bound_idx.push_back(id); left_bound_idx.push_back(id); diff --git a/Applications/Utils/MeshGeoTools/computeSurfaceNodeIDsInPolygonalRegion.cpp b/Applications/Utils/MeshGeoTools/computeSurfaceNodeIDsInPolygonalRegion.cpp index cbb08d44a623bcfe45c09e1f37a22a043359b43c..a0e61a2d1c8ed504dc4ee1df9c6f18daf52e3c84 100644 --- a/Applications/Utils/MeshGeoTools/computeSurfaceNodeIDsInPolygonalRegion.cpp +++ b/Applications/Utils/MeshGeoTools/computeSurfaceNodeIDsInPolygonalRegion.cpp @@ -10,55 +10,62 @@ * http://www.opengeosys.org/project/license */ +#include <tclap/CmdLine.h> + #include <algorithm> #include <memory> #include <string> #include <vector> -#include <tclap/CmdLine.h> - #include "Applications/FileIO/readGeometryFromFile.h" -#include "InfoLib/GitInfo.h" #include "BaseLib/Error.h" #include "BaseLib/FileTools.h" #include "GeoLib/GEOObjects.h" #include "GeoLib/Polygon.h" +#include "InfoLib/GitInfo.h" #include "MeshLib/IO/readMeshFromFile.h" #include "MeshLib/Mesh.h" #include "MeshLib/MeshSurfaceExtraction.h" #include "MeshLib/Node.h" -void writeToFile(std::string const& id_area_fname, std::string const& csv_fname, +void writeToFile( + std::string const& id_area_fname, std::string const& csv_fname, std::vector<std::pair<std::size_t, double>> const& ids_and_areas, std::vector<MeshLib::Node*> const& mesh_nodes) { std::ofstream ids_and_area_out(id_area_fname); - if (!ids_and_area_out) { + if (!ids_and_area_out) + { OGS_FATAL("Unable to open the file '{:s}' - aborting.", id_area_fname); } std::ofstream csv_out(csv_fname); - if (!csv_out) { + if (!csv_out) + { OGS_FATAL("Unable to open the file '{:s}' - aborting.", csv_fname); } ids_and_area_out << std::setprecision(20); csv_out << std::setprecision(20); - ids_and_area_out << ids_and_areas[0].first << " " << ids_and_areas[0].second; - csv_out << "ID x y z area node_id\n"; // CSV header + ids_and_area_out << ids_and_areas[0].first << " " + << ids_and_areas[0].second; + csv_out << "ID x y z area node_id\n"; // CSV header csv_out << 0 << " " << *mesh_nodes[ids_and_areas[0].first] << ids_and_areas[0].second << " " << ids_and_areas[0].first; - for (std::size_t k(1); k<ids_and_areas.size(); k++) { + for (std::size_t k(1); k < ids_and_areas.size(); k++) + { ids_and_area_out << "\n" - << ids_and_areas[k].first << " " << ids_and_areas[k].second; - csv_out << "\n" << k << " " << *mesh_nodes[ids_and_areas[k].first] - << ids_and_areas[k].second << " " << ids_and_areas[k].first; + << ids_and_areas[k].first << " " + << ids_and_areas[k].second; + csv_out << "\n" + << k << " " << *mesh_nodes[ids_and_areas[k].first] + << ids_and_areas[k].second << " " << ids_and_areas[k].first; } ids_and_area_out << "\n"; csv_out << "\n"; } -int main (int argc, char* argv[]) +int main(int argc, char* argv[]) { TCLAP::CmdLine cmd( "Computes ids of mesh nodes that are in polygonal regions and resides " @@ -73,13 +80,14 @@ int main (int argc, char* argv[]) "Copyright (c) 2012-2021, OpenGeoSys Community " "(http://www.opengeosys.org)", ' ', GitInfoLib::GitInfo::ogs_version); - TCLAP::ValueArg<std::string> mesh_in("m", "mesh-input-file", - "the name of the file containing the input mesh", true, - "", "file name of input mesh"); + TCLAP::ValueArg<std::string> mesh_in( + "m", "mesh-input-file", + "the name of the file containing the input mesh", true, "", + "file name of input mesh"); cmd.add(mesh_in); - TCLAP::ValueArg<std::string> geo_in("g", "geo-file", - "the name of the gml file containing the polygons", true, - "", "file name of input geometry"); + TCLAP::ValueArg<std::string> geo_in( + "g", "geo-file", "the name of the gml file containing the polygons", + true, "", "file name of input geometry"); cmd.add(geo_in); TCLAP::ValueArg<std::string> gmsh_path_arg("g", "gmsh-path", @@ -88,7 +96,8 @@ int main (int argc, char* argv[]) cmd.add(gmsh_path_arg); cmd.parse(argc, argv); - std::unique_ptr<MeshLib::Mesh const> mesh(MeshLib::IO::readMeshFromFile(mesh_in.getValue())); + std::unique_ptr<MeshLib::Mesh const> mesh( + MeshLib::IO::readMeshFromFile(mesh_in.getValue())); INFO("Mesh read: {:d} nodes, {:d} elements.", mesh->getNumberOfNodes(), mesh->getNumberOfElements()); @@ -104,31 +113,29 @@ int main (int argc, char* argv[]) Eigen::Vector3d const dir({0.0, 0.0, -1.0}); double angle(90); - auto computeElementTopSurfaceAreas = [](MeshLib::Mesh const& mesh, - Eigen::Vector3d const& d, double angle) - { - std::unique_ptr<MeshLib::Mesh> surface_mesh( - MeshLib::MeshSurfaceExtraction::getMeshSurface(mesh, d, angle)); - return MeshLib::MeshSurfaceExtraction::getSurfaceAreaForNodes( - *surface_mesh); - }; + auto computeElementTopSurfaceAreas = + [](MeshLib::Mesh const& mesh, Eigen::Vector3d const& d, double angle) { + std::unique_ptr<MeshLib::Mesh> surface_mesh( + MeshLib::MeshSurfaceExtraction::getMeshSurface(mesh, d, angle)); + return MeshLib::MeshSurfaceExtraction::getSurfaceAreaForNodes( + *surface_mesh); + }; std::vector<double> areas(computeElementTopSurfaceAreas(*mesh, dir, angle)); std::vector<MeshLib::Node*> all_sfc_nodes( - MeshLib::MeshSurfaceExtraction::getSurfaceNodes(*mesh, dir, angle) - ); + MeshLib::MeshSurfaceExtraction::getSurfaceNodes(*mesh, dir, angle)); std::for_each(all_sfc_nodes.begin(), all_sfc_nodes.end(), [](MeshLib::Node* p) { (*p)[2] = 0.0; }); std::vector<MeshLib::Node*> const& mesh_nodes(mesh->getNodes()); - GeoLib::PolylineVec const* ply_vec( - geo_objs.getPolylineVecObj(geo_name) - ); + GeoLib::PolylineVec const* ply_vec(geo_objs.getPolylineVecObj(geo_name)); std::vector<GeoLib::Polyline*> const& plys(*(ply_vec->getVector())); - for (std::size_t j(0); j<plys.size(); j++) { - if (! plys[j]->isClosed()) { + for (std::size_t j(0); j < plys.size(); j++) + { + if (!plys[j]->isClosed()) + { continue; } std::string polygon_name; @@ -141,13 +148,16 @@ int main (int argc, char* argv[]) GeoLib::Polygon const polygon{*plys[j]}; // ids of mesh nodes on surface that are within the given polygon std::vector<std::pair<std::size_t, double>> ids_and_areas; - for (std::size_t k(0); k<all_sfc_nodes.size(); k++) { + for (std::size_t k(0); k < all_sfc_nodes.size(); k++) + { MeshLib::Node const& pnt(*(all_sfc_nodes[k])); - if (polygon.isPntInPolygon(pnt[0], pnt[1], pnt[2])) { + if (polygon.isPntInPolygon(pnt[0], pnt[1], pnt[2])) + { ids_and_areas.emplace_back(pnt.getID(), areas[k]); } } - if (ids_and_areas.empty()) { + if (ids_and_areas.empty()) + { ERR("Polygonal part of surface '{:s}' doesn't contains nodes. No " "output will be generated.", polygon_name); @@ -160,8 +170,8 @@ int main (int argc, char* argv[]) id_and_area_fname += std::to_string(j) + ".txt"; csv_fname += std::to_string(j) + ".csv"; INFO( - "Polygonal part of surface '{:s}' contains %{ul} nodes. Writing to" - " files '{:s}' and '{:s}'.", + "Polygonal part of surface '{:s}' contains %{ul} nodes. Writing to " + "files '{:s}' and '{:s}'.", polygon_name, ids_and_areas.size(), id_and_area_fname, diff --git a/Applications/Utils/MeshGeoTools/constructMeshesFromGeometry.cpp b/Applications/Utils/MeshGeoTools/constructMeshesFromGeometry.cpp index 78a6ab6970e3177b923eac3b7028cad8f9d32a80..53318974179d4b62799dca9ae9cdede218d3ed29 100644 --- a/Applications/Utils/MeshGeoTools/constructMeshesFromGeometry.cpp +++ b/Applications/Utils/MeshGeoTools/constructMeshesFromGeometry.cpp @@ -9,9 +9,9 @@ #include <tclap/CmdLine.h> -#include "InfoLib/GitInfo.h" #include "GeoLib/GEOObjects.h" #include "GeoLib/IO/XmlIO/Boost/BoostXmlGmlInterface.h" +#include "InfoLib/GitInfo.h" #include "MeshGeoToolsLib/ConstructMeshesFromGeometries.h" #include "MeshGeoToolsLib/SearchLength.h" #include "MeshLib/IO/readMeshFromFile.h" diff --git a/Applications/Utils/MeshGeoTools/createIntermediateRasters.cpp b/Applications/Utils/MeshGeoTools/createIntermediateRasters.cpp index d5e91c968f9ecb60a5f04a335bae9dddd143211d..719d95d6ccd0444fd2caadda31d90321a3476e89 100644 --- a/Applications/Utils/MeshGeoTools/createIntermediateRasters.cpp +++ b/Applications/Utils/MeshGeoTools/createIntermediateRasters.cpp @@ -7,15 +7,15 @@ * http://www.opengeosys.org/project/license */ +#include <tclap/CmdLine.h> + #include <memory> #include <string> -#include <tclap/CmdLine.h> - -#include "InfoLib/GitInfo.h" -#include "BaseLib/FileTools.h" #include "Applications/FileIO/AsciiRasterInterface.h" +#include "BaseLib/FileTools.h" #include "GeoLib/Raster.h" +#include "InfoLib/GitInfo.h" int main(int argc, char* argv[]) { @@ -122,7 +122,7 @@ int main(int argc, char* argv[]) double const step = (max - min) / static_cast<double>(n + 1); for (std::size_t i = 0; i < n; ++i) { - raster[i].push_back(max - ((i+1) * step)); + raster[i].push_back(max - ((i + 1) * step)); } } it2++; @@ -140,7 +140,8 @@ int main(int argc, char* argv[]) std::string const ext = BaseLib::getFileExtension(filename); GeoLib::Raster r(h1, raster[i].begin(), raster[i].end()); - FileIO::AsciiRasterInterface::writeRasterAsASC(r, basename + std::to_string(i) + ext); + FileIO::AsciiRasterInterface::writeRasterAsASC( + r, basename + std::to_string(i) + ext); INFO("Layer {:d} written.", i + 1); } return EXIT_SUCCESS; diff --git a/Applications/Utils/ModelPreparation/ComputeNodeAreasFromSurfaceMesh.cpp b/Applications/Utils/ModelPreparation/ComputeNodeAreasFromSurfaceMesh.cpp index 71808e5c8ff7447b9981235d3d3e6fe8acef5d7f..f35c3977da54fc01dec376fffccf3bec727dbdb4 100644 --- a/Applications/Utils/ModelPreparation/ComputeNodeAreasFromSurfaceMesh.cpp +++ b/Applications/Utils/ModelPreparation/ComputeNodeAreasFromSurfaceMesh.cpp @@ -9,41 +9,44 @@ * http://www.opengeosys.org/project/license */ +#include <tclap/CmdLine.h> + #include <fstream> #include <memory> #include <numeric> #include <string> #include <vector> -#include <tclap/CmdLine.h> - -#include "InfoLib/GitInfo.h" #include "BaseLib/Error.h" #include "BaseLib/FileTools.h" +#include "InfoLib/GitInfo.h" #include "MeshLib/IO/readMeshFromFile.h" #include "MeshLib/Mesh.h" #include "MeshLib/MeshSurfaceExtraction.h" #include "MeshLib/Node.h" -static -void writeToFile(std::string const& id_area_fname, std::string const& csv_fname, +static void writeToFile( + std::string const& id_area_fname, std::string const& csv_fname, std::vector<std::pair<std::size_t, double>> const& ids_and_areas, std::vector<MeshLib::Node*> const& mesh_nodes) { std::ofstream ids_and_area_out(id_area_fname); - if (!ids_and_area_out) { + if (!ids_and_area_out) + { OGS_FATAL("Unable to open the file '{:s}' - aborting.", id_area_fname); } std::ofstream csv_out(csv_fname); - if (!csv_out) { + if (!csv_out) + { OGS_FATAL("Unable to open the file '{:s}' - aborting.", csv_fname); } ids_and_area_out.precision(std::numeric_limits<double>::digits10); csv_out.precision(std::numeric_limits<double>::digits10); - csv_out << "ID x y z area node_id\n"; // CSV header - for (std::size_t k(0); k<ids_and_areas.size(); k++) { + csv_out << "ID x y z area node_id\n"; // CSV header + for (std::size_t k(0); k < ids_and_areas.size(); k++) + { ids_and_area_out << ids_and_areas[k].first << " " << ids_and_areas[k].second << "\n"; csv_out << k << " " << *(mesh_nodes[k]) << ids_and_areas[k].second @@ -53,7 +56,7 @@ void writeToFile(std::string const& id_area_fname, std::string const& csv_fname, csv_out << "\n"; } -int main (int argc, char* argv[]) +int main(int argc, char* argv[]) { TCLAP::CmdLine cmd( "The tool computes the area per node of the surface mesh and writes " @@ -64,18 +67,20 @@ int main (int argc, char* argv[]) "Copyright (c) 2012-2021, OpenGeoSys Community " "(http://www.opengeosys.org)", ' ', GitInfoLib::GitInfo::ogs_version); - TCLAP::ValueArg<std::string> mesh_in("i", "mesh-input-file", - "the name of the file containing the input mesh", true, - "", "file name of input mesh"); + TCLAP::ValueArg<std::string> mesh_in( + "i", "mesh-input-file", + "the name of the file containing the input mesh", true, "", + "file name of input mesh"); cmd.add(mesh_in); TCLAP::ValueArg<std::string> id_prop_name( "", "id-prop-name", "the name of the property containing the id information", false, "bulk_node_ids", "property name"); cmd.add(id_prop_name); - TCLAP::ValueArg<std::string> out_base_fname("p", "output-base-name", - "the path and base file name the output will be written to", false, - "", "output path and base name as one string"); + TCLAP::ValueArg<std::string> out_base_fname( + "p", "output-base-name", + "the path and base file name the output will be written to", false, "", + "output path and base name as one string"); cmd.add(out_base_fname); cmd.parse(argc, argv); @@ -125,8 +130,8 @@ int main (int argc, char* argv[]) { path = BaseLib::dropFileExtension(mesh_in.getValue()); } - std::string const id_and_area_fname(path+".txt"); - std::string const csv_fname(path+".csv"); + std::string const id_and_area_fname(path + ".txt"); + std::string const csv_fname(path + ".csv"); writeToFile(id_and_area_fname, csv_fname, ids_and_areas, surface_mesh->getNodes()); diff --git a/Applications/Utils/ModelPreparation/PartitionMesh/Metis.cpp b/Applications/Utils/ModelPreparation/PartitionMesh/Metis.cpp index d8d9fe748eeb87939be9468c572a43ae148f9d8e..3a08f783e93b413f63e3942aee1bff0078616ae3 100644 --- a/Applications/Utils/ModelPreparation/PartitionMesh/Metis.cpp +++ b/Applications/Utils/ModelPreparation/PartitionMesh/Metis.cpp @@ -63,7 +63,6 @@ std::vector<std::size_t> readMetisData(const std::string& file_name_base, std::vector<std::size_t> partition_ids(number_of_nodes); - std::size_t counter = 0; while (!npart_in.eof()) { diff --git a/Applications/Utils/ModelPreparation/PartitionMesh/NodeWiseMeshPartitioner.cpp b/Applications/Utils/ModelPreparation/PartitionMesh/NodeWiseMeshPartitioner.cpp index a9e57cfec4295be06d5e43019308469fb2a29c27..74fa6e95051e383be51a2ba3fdc97b2f6f7a283d 100644 --- a/Applications/Utils/ModelPreparation/PartitionMesh/NodeWiseMeshPartitioner.cpp +++ b/Applications/Utils/ModelPreparation/PartitionMesh/NodeWiseMeshPartitioner.cpp @@ -291,9 +291,8 @@ void NodeWiseMeshPartitioner::processPartition( _mesh->getNodes(), _nodes_partition_ids); partition.number_of_regular_base_nodes = partition.nodes.size(); - partition.number_of_regular_nodes = - partition.number_of_regular_base_nodes + - higher_order_regular_nodes.size(); + partition.number_of_regular_nodes = partition.number_of_regular_base_nodes + + higher_order_regular_nodes.size(); std::tie(partition.regular_elements, partition.ghost_elements) = findElementsInPartition(part_id, _mesh->getElements(), @@ -415,8 +414,8 @@ bool copyPropertyVector( *partitioned_pv); } OGS_FATAL( - "Copying of property vector values for mesh item type {:s} is " - "not implemented.", + "Copying of property vector values for mesh item type {:s} is not " + "implemented.", item_type); }; @@ -471,7 +470,7 @@ void addVtkGhostTypeProperty(MeshLib::Properties& partitioned_properties, vtk_ghost_type->resize(total_number_of_cells); std::size_t offset = 0; - for(auto const& partition : partitions) + for (auto const& partition : partitions) { offset += partition.regular_elements.size(); for (std::size_t i = 0; i < partition.ghost_elements.size(); ++i) @@ -484,7 +483,6 @@ void addVtkGhostTypeProperty(MeshLib::Properties& partitioned_properties, } offset += partition.ghost_elements.size(); } - } /// Partition existing properties and add vtkGhostType cell data array property. @@ -508,8 +506,8 @@ MeshLib::Properties partitionProperties( {MeshItemType::Node, count_tuples(MeshItemType::Node)}}; DBUG( - "total number of tuples after partitioning defined for cells is" - " {:d} and for nodes {:d}.", + "total number of tuples after partitioning defined for cells is {:d} " + "and for nodes {:d}.", total_number_of_tuples.at(MeshItemType::Cell), total_number_of_tuples.at(MeshItemType::Node)); @@ -736,8 +734,7 @@ void NodeWiseMeshPartitioner::renumberNodeIndices( // -- Base nodes for (auto& partition : _partitions) { - for (std::size_t i = 0; i < partition.number_of_regular_base_nodes; - i++) + for (std::size_t i = 0; i < partition.number_of_regular_base_nodes; i++) { _nodes_global_ids[partition.nodes[i]->getID()] = node_global_id_offset; @@ -962,7 +959,8 @@ void getElementIntegerVariables( std::vector<long>& elem_info, long& counter) { - constexpr unsigned mat_id = 0; // TODO: Material ID to be set from the mesh data + constexpr unsigned mat_id = + 0; // TODO: Material ID to be set from the mesh data const long nn = elem.getNumberOfNodes(); elem_info[counter++] = mat_id; elem_info[counter++] = static_cast<long>(elem.getCellType()); diff --git a/Applications/Utils/ModelPreparation/PartitionMesh/PartitionMesh.cpp b/Applications/Utils/ModelPreparation/PartitionMesh/PartitionMesh.cpp index 5ede41a51589214c74cdd6674eab0cfa18bbafb3..00b46c06901a3da470f069dd6a727f28dfa63e40 100644 --- a/Applications/Utils/ModelPreparation/PartitionMesh/PartitionMesh.cpp +++ b/Applications/Utils/ModelPreparation/PartitionMesh/PartitionMesh.cpp @@ -51,8 +51,8 @@ int main(int argc, char* argv[]) TCLAP::ValueArg<std::string> metis_mesh_input( "x", "metis-mesh-input-file", - "base name (without .mesh extension) of the file containing the " - "metis input mesh", + "base name (without .mesh extension) of the file containing the metis " + "input mesh", false, "", "base name (without .mesh extension) of the file containing the metis " "input mesh"); @@ -81,17 +81,17 @@ int main(int argc, char* argv[]) "q", "lh_elements", "Mixed linear and high order elements.", false); cmd.add(lh_elems_flag); - TCLAP::ValueArg<std::string> log_level_arg("l", "log-level", - "the verbosity of logging " - "messages: none, error, warn, " - "info, debug, all", - false, + TCLAP::ValueArg<std::string> log_level_arg( + "l", "log-level", + "the verbosity of logging messages: none, error, warn, info, debug, " + "all", + false, #ifdef NDEBUG - "info", + "info", #else - "all", + "all", #endif - "LOG_LEVEL"); + "LOG_LEVEL"); cmd.add(log_level_arg); // All the remaining arguments are used as file names for boundary/subdomain diff --git a/Applications/Utils/ModelPreparation/convertVtkDataArrayToVtkDataArray.cpp b/Applications/Utils/ModelPreparation/convertVtkDataArrayToVtkDataArray.cpp index f60b120d7f6a758ecec16b65df692905a052e715..40aa9ba9a1425017edb94e614e4597c07ea75112 100644 --- a/Applications/Utils/ModelPreparation/convertVtkDataArrayToVtkDataArray.cpp +++ b/Applications/Utils/ModelPreparation/convertVtkDataArrayToVtkDataArray.cpp @@ -8,18 +8,16 @@ * */ +#include <tclap/CmdLine.h> + #include <algorithm> #include <cmath> #include <memory> #include <numeric> -#include <tclap/CmdLine.h> - #include "InfoLib/GitInfo.h" - #include "MeshLib/IO/readMeshFromFile.h" #include "MeshLib/IO/writeMeshToFile.h" - #include "MeshLib/Mesh.h" template <typename T1, typename T2> diff --git a/Applications/Utils/ModelPreparation/createNeumannBc.cpp b/Applications/Utils/ModelPreparation/createNeumannBc.cpp index 7ee126969037c29bd28a8b7035a9e1f7f4623dc0..9e5ab188c8bedbf357f1a9177088fd37c656b62e 100644 --- a/Applications/Utils/ModelPreparation/createNeumannBc.cpp +++ b/Applications/Utils/ModelPreparation/createNeumannBc.cpp @@ -7,9 +7,10 @@ * */ -#include <fstream> #include <tclap/CmdLine.h> +#include <fstream> + #include "InfoLib/GitInfo.h" #include "MeshLib/Elements/Element.h" #include "MeshLib/IO/readMeshFromFile.h" @@ -39,8 +40,7 @@ std::vector<double> getSurfaceIntegratedValuesForNodes( if (!mesh.getProperties().existsPropertyVector<double>(prop_name)) { - ERR("Need element property, but the property '{:s}' is not " - "available.", + ERR("Need element property, but the property '{:s}' is not available.", prop_name); return std::vector<double>(); } @@ -76,9 +76,9 @@ int main(int argc, char* argv[]) TCLAP::CmdLine cmd( "Integrates the given element property and outputs an OGS-5 direct " "Neumann boundary condition. The mesh has to contain a property " - "'bulk_node_ids' that stores the original subsurface " - "mesh node ids. Such surface meshes can be created using the OGS-6 " - "tool ExtractSurface.\n\n" + "'bulk_node_ids' that stores the original subsurface mesh node ids. " + "Such surface meshes can be created using the OGS-6 tool " + "ExtractSurface.\n\n" "OpenGeoSys-6 software, version " + GitInfoLib::GitInfo::ogs_version + ".\n" @@ -86,21 +86,21 @@ int main(int argc, char* argv[]) "(http://www.opengeosys.org)", ' ', GitInfoLib::GitInfo::ogs_version); - TCLAP::ValueArg<std::string> in_mesh("i", - "in-mesh", - "the surface mesh that has an element " - "property for the Neumann " - "boundary condition", - true, - "", - "filename for surface mesh input"); + TCLAP::ValueArg<std::string> in_mesh( + "i", + "in-mesh", + "the surface mesh that has an element property for the Neumann " + "boundary condition", + true, + "", + "filename for surface mesh input"); cmd.add(in_mesh); TCLAP::ValueArg<std::string> property_in_arg( "p", "property-in-name", - "name of an element property used for the computation of the " - "Neumann boundary condition", + "name of an element property used for the computation of the Neumann " + "boundary condition", true, "", "string (property name)"); @@ -109,8 +109,8 @@ int main(int argc, char* argv[]) TCLAP::ValueArg<std::string> property_out_arg( "", "property-out-name", - "name of the node based property used for the output of the " - "Neumann boundary condition", + "name of the node based property used for the output of the Neumann " + "boundary condition", true, "", "string (property name)"); @@ -124,7 +124,7 @@ int main(int argc, char* argv[]) "", "output file name"); cmd.add(result_file); - cmd.parse( argc, argv ); + cmd.parse(argc, argv); // read surface mesh std::unique_ptr<MeshLib::Mesh> surface_mesh( diff --git a/Applications/Utils/ModelPreparation/scaleProperty.cpp b/Applications/Utils/ModelPreparation/scaleProperty.cpp index 3fd5d9cb9701bd0296e446947079d0f01dd0f454..450f088b59e9bebfb44df4eb256f3c804deed119 100644 --- a/Applications/Utils/ModelPreparation/scaleProperty.cpp +++ b/Applications/Utils/ModelPreparation/scaleProperty.cpp @@ -8,13 +8,13 @@ * */ +#include <tclap/CmdLine.h> + #include <algorithm> -#include <memory> #include <cmath> +#include <memory> #include <numeric> -#include <tclap/CmdLine.h> - #include "InfoLib/GitInfo.h" #include "MeshLib/IO/readMeshFromFile.h" #include "MeshLib/IO/writeMeshToFile.h" @@ -49,15 +49,11 @@ int main(int argc, char* argv[]) "property name as string"); cmd.add(property_arg); - TCLAP::ValueArg<std::string> mesh_arg("m", - "mesh", - "the mesh is read from this file", - true, - "", - "file name"); + TCLAP::ValueArg<std::string> mesh_arg( + "m", "mesh", "the mesh is read from this file", true, "", "file name"); cmd.add(mesh_arg); - std::vector<std::string> allowed_units{ "mm/a", "mm/month", "m/s" }; + std::vector<std::string> allowed_units{"mm/a", "mm/month", "m/s"}; TCLAP::ValuesConstraint<std::string> allowed_units_constraints{ allowed_units}; TCLAP::ValueArg<std::string> unit_arg("u", diff --git a/Applications/Utils/OGSFileConverter/FileListDialog.cpp b/Applications/Utils/OGSFileConverter/FileListDialog.cpp index 2d01989732b20a0200a3449a96e1cf62dbbad2d0..c958240cdacb78a580feaca75433db510f4e318d 100644 --- a/Applications/Utils/OGSFileConverter/FileListDialog.cpp +++ b/Applications/Utils/OGSFileConverter/FileListDialog.cpp @@ -14,16 +14,19 @@ #include "FileListDialog.h" -#include <QSettings> #include <QFileInfo> #include <QFont> #include <QLineEdit> +#include <QSettings> #include "Applications/DataExplorer/Base/OGSError.h" #include "BaseLib/StringTools.h" FileListDialog::FileListDialog(FileType input, FileType output, QWidget* parent) -: QDialog(parent), _output_dir(""), _input_file_type(input), _output_file_type(output) + : QDialog(parent), + _output_dir(""), + _input_file_type(input), + _output_file_type(output) { setupUi(this); @@ -64,7 +67,8 @@ void FileListDialog::on_addButton_pressed() void FileListDialog::on_removeButton_pressed() { - QModelIndexList selected = this->listView->selectionModel()->selectedIndexes(); + QModelIndexList selected = + this->listView->selectionModel()->selectedIndexes(); for (auto& item : selected) { this->_allFiles.removeRow(item.row()); @@ -75,7 +79,8 @@ void FileListDialog::on_browseButton_pressed() { QSettings const settings("UFZ", "OpenGeoSys-5"); QFileInfo const fi(settings.value("lastOpenedOgsFileDirectory").toString()); - QString const dirName = QFileDialog::getExistingDirectory(this, "Save to", fi.absolutePath().append("/")); + QString const dirName = QFileDialog::getExistingDirectory( + this, "Save to", fi.absolutePath().append("/")); this->outputDirEdit->setText(dirName); } @@ -133,5 +138,7 @@ void FileListDialog::displayWarningLabel() const font.setBold(true); warningLabel->setFont(font); this->warningLabel->setStyleSheet("QLabel { color : red; }"); - this->warningLabel->setText("Warning: all scalar information except<br />MaterialIDs will be lost!"); + this->warningLabel->setText( + "Warning: all scalar information except<br />MaterialIDs will be " + "lost!"); } diff --git a/Applications/Utils/OGSFileConverter/OGSFileConverter.cpp b/Applications/Utils/OGSFileConverter/OGSFileConverter.cpp index f40de784429bf9bc4e41d52db608b1ba7e8ddd94..8ac13db8aa94cf39a5aeda398b31f6368c9b7ebb 100644 --- a/Applications/Utils/OGSFileConverter/OGSFileConverter.cpp +++ b/Applications/Utils/OGSFileConverter/OGSFileConverter.cpp @@ -38,7 +38,8 @@ OGSFileConverter::OGSFileConverter(std::string const& gmsh_path, OGSFileConverter::~OGSFileConverter() = default; -void OGSFileConverter::convertGML2GLI(const QStringList &input, const QString &output) const +void OGSFileConverter::convertGML2GLI(const QStringList& input, + const QString& output) const { if (input.empty()) { @@ -51,7 +52,9 @@ void OGSFileConverter::convertGML2GLI(const QStringList &input, const QString &o for (const auto& input_string : input) { const QFileInfo fi(input_string); - const std::string output_str = QString(output + "/" + fi.completeBaseName() + ".gli").toStdString(); + const std::string output_str = + QString(output + "/" + fi.completeBaseName() + ".gli") + .toStdString(); if (fileExists(output_str)) { @@ -82,7 +85,8 @@ void OGSFileConverter::convertGML2GLI(const QStringList &input, const QString &o OGSError::box("File conversion finished"); } -void OGSFileConverter::convertGLI2GML(const QStringList &input, const QString &output) const +void OGSFileConverter::convertGLI2GML(const QStringList& input, + const QString& output) const { if (input.empty()) { @@ -95,7 +99,9 @@ void OGSFileConverter::convertGLI2GML(const QStringList &input, const QString &o for (const auto& input_string : input) { const QFileInfo fi(input_string); - const std::string output_str = QString(output + "/" + fi.completeBaseName() + ".gml").toStdString(); + const std::string output_str = + QString(output + "/" + fi.completeBaseName() + ".gml") + .toStdString(); if (fileExists(output_str)) { @@ -130,7 +136,8 @@ void OGSFileConverter::convertGLI2GML(const QStringList &input, const QString &o OGSError::box("File conversion finished"); } -void OGSFileConverter::convertVTU2MSH(const QStringList &input, const QString &output) const +void OGSFileConverter::convertVTU2MSH(const QStringList& input, + const QString& output) const { if (input.empty()) { @@ -140,7 +147,9 @@ void OGSFileConverter::convertVTU2MSH(const QStringList &input, const QString &o for (const auto& input_string : input) { const QFileInfo fi(input_string); - const std::string output_str = QString(output + "/" + fi.completeBaseName() + ".msh").toStdString(); + const std::string output_str = + QString(output + "/" + fi.completeBaseName() + ".msh") + .toStdString(); if (fileExists(output_str)) { @@ -162,7 +171,8 @@ void OGSFileConverter::convertVTU2MSH(const QStringList &input, const QString &o OGSError::box("File conversion finished"); } -void OGSFileConverter::convertMSH2VTU(const QStringList &input, const QString &output) const +void OGSFileConverter::convertMSH2VTU(const QStringList& input, + const QString& output) const { if (input.empty()) { @@ -172,7 +182,9 @@ void OGSFileConverter::convertMSH2VTU(const QStringList &input, const QString &o for (const auto& input_string : input) { const QFileInfo fi(input_string); - const std::string output_str = QString(output + "/" + fi.completeBaseName() + ".vtu").toStdString(); + const std::string output_str = + QString(output + "/" + fi.completeBaseName() + ".vtu") + .toStdString(); if (fileExists(output_str)) { @@ -235,12 +247,13 @@ void OGSFileConverter::on_closeDialogButton_pressed() this->close(); } -bool OGSFileConverter::fileExists(const std::string &file_name) const +bool OGSFileConverter::fileExists(const std::string& file_name) const { std::ifstream const file(file_name.c_str()); if (file) { - QString const name = QString::fromStdString(BaseLib::extractBaseName(file_name)); + QString const name = + QString::fromStdString(BaseLib::extractBaseName(file_name)); return !OGSError::question( "The file '" + name + "' already exists.\n Do you want to overwrite it?", diff --git a/Applications/Utils/OGSFileConverter/main.cpp b/Applications/Utils/OGSFileConverter/main.cpp index d40db7bf31050e3e88925b44674b8c1cdab226ce..69d6ff5162d1b049ba7e385ecc9170abcbf81afb 100644 --- a/Applications/Utils/OGSFileConverter/main.cpp +++ b/Applications/Utils/OGSFileConverter/main.cpp @@ -7,14 +7,13 @@ * http://www.opengeosys.org/project/license */ -#include "OGSFileConverter.h" - -#include <clocale> #include <tclap/CmdLine.h> -#include "InfoLib/GitInfo.h" #include <QApplication> +#include <clocale> +#include "InfoLib/GitInfo.h" +#include "OGSFileConverter.h" int main(int argc, char* argv[]) { @@ -30,11 +29,11 @@ int main(int argc, char* argv[]) "the path to the gmsh binary", false, "", "path as string"); cmd.add(gmsh_path_arg); - cmd.parse( argc, argv ); + cmd.parse(argc, argv); QApplication app(argc, argv); - setlocale(LC_NUMERIC,"C"); + setlocale(LC_NUMERIC, "C"); auto* fc = new OGSFileConverter(gmsh_path_arg.getValue()); - fc->setWindowTitle( fc->windowTitle() ); + fc->setWindowTitle(fc->windowTitle()); fc->show(); int returncode = QApplication::exec(); delete fc; diff --git a/Applications/Utils/PostProcessing/Raster2PointCloud.cpp b/Applications/Utils/PostProcessing/Raster2PointCloud.cpp index af3238f38e273825f5ad823a88691cdabb7de664..66cc0b68a7d8c9cfb937e4d1a60911608feaa4e6 100644 --- a/Applications/Utils/PostProcessing/Raster2PointCloud.cpp +++ b/Applications/Utils/PostProcessing/Raster2PointCloud.cpp @@ -13,20 +13,17 @@ // ThirdParty #include <tclap/CmdLine.h> - -#include "InfoLib/GitInfo.h" - #include <vtkPolyDataAlgorithm.h> -#include <vtkXMLPolyDataWriter.h> #include <vtkSmartPointer.h> +#include <vtkXMLPolyDataWriter.h> -#include "BaseLib/FileTools.h" - -#include "Applications/FileIO/AsciiRasterInterface.h" #include "Applications/DataExplorer/VtkVis/VtkGeoImageSource.h" #include "Applications/DataExplorer/VtkVis/VtkImageDataToPointCloudFilter.h" +#include "Applications/FileIO/AsciiRasterInterface.h" +#include "BaseLib/FileTools.h" +#include "InfoLib/GitInfo.h" -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { TCLAP::CmdLine cmd( "Batch conversion of raster files into VTK point cloud data.\n" @@ -34,7 +31,8 @@ int main(int argc, char *argv[]) "number of random points based on the intensity value in each pixel " "(the higher the value, the more points. The [x,y]-extend of these " "random points is limited by the extent of the pixel they represent, " - "the elevation is limited by the max-elevation parameter. Likewise, the " + "the elevation is limited by the max-elevation parameter. Likewise, " + "the " "maximum number of points per pixel is limited by the max-points " "parameter. The increase of the number of points in relation to the " "pixel value is indicated by gamma, where 1 is a linear increase and " @@ -77,7 +75,7 @@ int main(int argc, char *argv[]) "'file1.asc', etc.", true, "", "input file name"); cmd.add(input_arg); - cmd.parse( argc, argv ); + cmd.parse(argc, argv); std::string const input_name = input_arg.getValue().c_str(); std::string const output_name = output_arg.getValue().c_str(); @@ -86,8 +84,7 @@ int main(int argc, char *argv[]) (max_height_arg.isSet()) ? max_height_arg.getValue() : 5000; std::size_t const max_points = (max_points_arg.isSet()) ? max_points_arg.getValue() : 1000; - double const gamma = - (gamma_arg.isSet()) ? gamma_arg.getValue() : 1; + double const gamma = (gamma_arg.isSet()) ? gamma_arg.getValue() : 1; std::string const ibase_name = BaseLib::dropFileExtension(input_name); std::string const ifile_ext = BaseLib::getFileExtension(input_name); @@ -101,9 +98,10 @@ int main(int argc, char *argv[]) double global_max = 0; std::size_t n_rasters = 0; - for (std::size_t i = 0; ; ++i) + for (std::size_t i = 0;; ++i) { - std::string const file_name = ibase_name + std::to_string(i) + ifile_ext; + std::string const file_name = + ibase_name + std::to_string(i) + ifile_ext; std::unique_ptr<GeoLib::Raster> r( FileIO::AsciiRasterInterface::getRasterFromASCFile(file_name)); if (r == nullptr) @@ -129,7 +127,7 @@ int main(int argc, char *argv[]) vtkSmartPointer<VtkGeoImageSource> geo_image = vtkSmartPointer<VtkGeoImageSource>::New(); geo_image->readImage(QString::fromStdString(file_name)); - VtkImageDataToPointCloudFilter *const point_cloud_filter = + VtkImageDataToPointCloudFilter* const point_cloud_filter = VtkImageDataToPointCloudFilter::New(); point_cloud_filter->SetInputConnection(geo_image->GetOutputPort()); geo_image->Update(); diff --git a/Applications/Utils/PostProcessing/postLIE.cpp b/Applications/Utils/PostProcessing/postLIE.cpp index 1425f83a3775357fa659400ceafe4778f92fdc11..b65803bb53054c830573a16b94fb47bd9606f87b 100644 --- a/Applications/Utils/PostProcessing/postLIE.cpp +++ b/Applications/Utils/PostProcessing/postLIE.cpp @@ -7,17 +7,16 @@ * http://www.opengeosys.org/project/license */ -#include <map> -#include <memory> -#include <vector> - #include <tclap/CmdLine.h> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> +#include <map> +#include <memory> +#include <vector> -#include "InfoLib/GitInfo.h" #include "BaseLib/FileTools.h" +#include "InfoLib/GitInfo.h" #include "MeshLib/IO/readMeshFromFile.h" #include "MeshLib/IO/writeMeshToFile.h" #include "MeshLib/Mesh.h" diff --git a/Applications/Utils/SWMMConverter/SWMMConverter.cpp b/Applications/Utils/SWMMConverter/SWMMConverter.cpp index 1fa4fd9781ae57390459240b27c2af7fb7afccd1..7b3b988c3f846dbbafeab125dc5a79f13c7be23a 100644 --- a/Applications/Utils/SWMMConverter/SWMMConverter.cpp +++ b/Applications/Utils/SWMMConverter/SWMMConverter.cpp @@ -8,20 +8,16 @@ #include <tclap/CmdLine.h> +#include "Applications/FileIO/CsvInterface.h" #include "Applications/FileIO/SWMM/SWMMInterface.h" - -#include "InfoLib/GitInfo.h" #include "BaseLib/FileTools.h" #include "BaseLib/StringTools.h" - #include "GeoLib/GEOObjects.h" #include "GeoLib/IO/XmlIO/Boost/BoostXmlGmlInterface.h" - +#include "InfoLib/GitInfo.h" +#include "MeshLib/IO/VtkIO/VtuInterface.h" #include "MeshLib/Mesh.h" #include "MeshLib/Properties.h" -#include "MeshLib/IO/VtkIO/VtuInterface.h" - -#include "Applications/FileIO/CsvInterface.h" int writeGeoOutput(std::string input_file, std::string output_file) { diff --git a/Applications/Utils/SimpleMeshCreation/createMeshElemPropertiesFromASCRaster.cpp b/Applications/Utils/SimpleMeshCreation/createMeshElemPropertiesFromASCRaster.cpp index b7d5424a4de4aae9bcb02a71861fcab5422d0152..ae9b315f125c5c3d028b33cf377fa21a1cdd6bf6 100644 --- a/Applications/Utils/SimpleMeshCreation/createMeshElemPropertiesFromASCRaster.cpp +++ b/Applications/Utils/SimpleMeshCreation/createMeshElemPropertiesFromASCRaster.cpp @@ -9,18 +9,18 @@ * */ +#include <tclap/CmdLine.h> + #include <algorithm> -#include <memory> #include <cmath> +#include <memory> #include <numeric> -#include <tclap/CmdLine.h> - #include "Applications/FileIO/AsciiRasterInterface.h" -#include "InfoLib/GitInfo.h" #include "BaseLib/FileTools.h" #include "BaseLib/quicksort.h" #include "GeoLib/Raster.h" +#include "InfoLib/GitInfo.h" #include "MathLib/MathTools.h" #include "MeshLib/Elements/Element.h" #include "MeshLib/IO/readMeshFromFile.h" @@ -83,12 +83,8 @@ int main(int argc, char* argv[]) "property name as string"); cmd.add(property_arg); - TCLAP::ValueArg<std::string> mesh_arg("m", - "mesh", - "the mesh is read from this file", - true, - "", - "file name"); + TCLAP::ValueArg<std::string> mesh_arg( + "m", "mesh", "the mesh is read from this file", true, "", "file name"); cmd.add(mesh_arg); cmd.parse(argc, argv); diff --git a/Applications/Utils/SimpleMeshCreation/generateStructuredMesh.cpp b/Applications/Utils/SimpleMeshCreation/generateStructuredMesh.cpp index 37e8353b9ae44c1267628926b3214e760473f627..f75c9eb039d4aba17af8314b8036677639c78208 100644 --- a/Applications/Utils/SimpleMeshCreation/generateStructuredMesh.cpp +++ b/Applications/Utils/SimpleMeshCreation/generateStructuredMesh.cpp @@ -7,29 +7,26 @@ * http://www.opengeosys.org/project/license */ +#include <tclap/CmdLine.h> + #include <algorithm> #include <memory> #include <string> #include <vector> -#include <tclap/CmdLine.h> - -#include "InfoLib/GitInfo.h" #include "BaseLib/Error.h" #include "BaseLib/Subdivision.h" #include "BaseLib/TCLAPCustomOutput.h" - -#include "MeshLib/Mesh.h" -#include "MeshLib/Node.h" +#include "InfoLib/GitInfo.h" #include "MeshLib/Elements/Element.h" +#include "MeshLib/IO/writeMeshToFile.h" +#include "MeshLib/Mesh.h" #include "MeshLib/MeshEnums.h" #include "MeshLib/MeshGenerators/MeshGenerator.h" - -#include "MeshLib/IO/writeMeshToFile.h" +#include "MeshLib/Node.h" namespace { - /// Get dimension of the mesh element type. /// @param eleType element type unsigned getDimension(MeshLib::MeshElemType eleType) @@ -53,10 +50,9 @@ unsigned getDimension(MeshLib::MeshElemType eleType) return 0; } -} // end namespace - +} // end namespace -int main (int argc, char* argv[]) +int main(int argc, char* argv[]) { TCLAP::CmdLine cmd( "Structured mesh generator.\n" @@ -88,61 +84,69 @@ int main (int argc, char* argv[]) "pyramid", true, "line", &allowedVals); cmd.add(eleTypeArg); - TCLAP::ValueArg<std::string> mesh_out("o", "mesh-output-file", - "the name of the file the mesh will be written to", true, - "", "file name of output mesh"); + TCLAP::ValueArg<std::string> mesh_out( + "o", "mesh-output-file", + "the name of the file the mesh will be written to", true, "", + "file name of output mesh"); cmd.add(mesh_out); - TCLAP::ValueArg<double> lengthXArg("", "lx", - "length of a domain in x direction", false, 10.0, "real"); + TCLAP::ValueArg<double> lengthXArg( + "", "lx", "length of a domain in x direction", false, 10.0, "real"); cmd.add(lengthXArg); - TCLAP::ValueArg<double> lengthYArg("", "ly", - "length of a domain in y direction", false, 10.0, "real"); + TCLAP::ValueArg<double> lengthYArg( + "", "ly", "length of a domain in y direction", false, 10.0, "real"); cmd.add(lengthYArg); - TCLAP::ValueArg<double> lengthZArg("", "lz", - "length of a domain in z direction", false, 10.0, "real"); + TCLAP::ValueArg<double> lengthZArg( + "", "lz", "length of a domain in z direction", false, 10.0, "real"); cmd.add(lengthZArg); - TCLAP::ValueArg<unsigned> nsubdivXArg("", "nx", - "the number of subdivision in x direction", false, 10, "integer"); + TCLAP::ValueArg<unsigned> nsubdivXArg( + "", "nx", "the number of subdivision in x direction", false, 10, + "integer"); cmd.add(nsubdivXArg); - TCLAP::ValueArg<unsigned> nsubdivYArg("", "ny", - "the number of subdivision in y direction", false, 10, "integer"); + TCLAP::ValueArg<unsigned> nsubdivYArg( + "", "ny", "the number of subdivision in y direction", false, 10, + "integer"); cmd.add(nsubdivYArg); - TCLAP::ValueArg<unsigned> nsubdivZArg("", "nz", - "the number of subdivision in z direction", false, 10, "integer"); + TCLAP::ValueArg<unsigned> nsubdivZArg( + "", "nz", "the number of subdivision in z direction", false, 10, + "integer"); cmd.add(nsubdivZArg); // in case of gradual refinement - TCLAP::ValueArg<double> d0XArg("", "dx0", - "initial cell length in x direction", false, 1, "real"); + TCLAP::ValueArg<double> d0XArg( + "", "dx0", "initial cell length in x direction", false, 1, "real"); cmd.add(d0XArg); - TCLAP::ValueArg<double> d0YArg("", "dy0", - "initial cell length in y direction", false, 1, "real"); + TCLAP::ValueArg<double> d0YArg( + "", "dy0", "initial cell length in y direction", false, 1, "real"); cmd.add(d0YArg); - TCLAP::ValueArg<double> d0ZArg("", "dz0", - "initial cell length in z direction", false, 1, "real"); + TCLAP::ValueArg<double> d0ZArg( + "", "dz0", "initial cell length in z direction", false, 1, "real"); cmd.add(d0ZArg); - TCLAP::ValueArg<double> dmaxXArg("", "dx-max", - "maximum cell length in x direction", false, std::numeric_limits<double>::max(), "real"); + TCLAP::ValueArg<double> dmaxXArg( + "", "dx-max", "maximum cell length in x direction", false, + std::numeric_limits<double>::max(), "real"); cmd.add(dmaxXArg); - TCLAP::ValueArg<double> dmaxYArg("", "dy-max", - "maximum cell length in y direction", false, std::numeric_limits<double>::max(), "real"); + TCLAP::ValueArg<double> dmaxYArg( + "", "dy-max", "maximum cell length in y direction", false, + std::numeric_limits<double>::max(), "real"); cmd.add(dmaxYArg); - TCLAP::ValueArg<double> dmaxZArg("", "dz-max", - "maximum cell length in z direction", false, std::numeric_limits<double>::max(), "real"); + TCLAP::ValueArg<double> dmaxZArg( + "", "dz-max", "maximum cell length in z direction", false, + std::numeric_limits<double>::max(), "real"); cmd.add(dmaxZArg); - TCLAP::ValueArg<double> multiXArg("", "mx", - "multiplier in x direction", false, 1, "real"); + TCLAP::ValueArg<double> multiXArg("", "mx", "multiplier in x direction", + false, 1, "real"); cmd.add(multiXArg); - TCLAP::ValueArg<double> multiYArg("", "my", - "multiplier in y direction", false, 1, "real"); + TCLAP::ValueArg<double> multiYArg("", "my", "multiplier in y direction", + false, 1, "real"); cmd.add(multiYArg); - TCLAP::ValueArg<double> multiZArg("", "mz", - "multiplier in z direction", false, 1, "real"); + TCLAP::ValueArg<double> multiZArg("", "mz", "multiplier in z direction", + false, 1, "real"); cmd.add(multiZArg); // parse arguments cmd.parse(argc, argv); const std::string eleTypeName(eleTypeArg.getValue()); - const MeshLib::MeshElemType eleType = MeshLib::String2MeshElemType(eleTypeName); + const MeshLib::MeshElemType eleType = + MeshLib::String2MeshElemType(eleTypeName); const unsigned dim = getDimension(eleType); bool dim_used[3] = {false}; @@ -151,15 +155,22 @@ int main (int argc, char* argv[]) dim_used[i] = true; } - std::vector<TCLAP::ValueArg<double>*> vec_lengthArg = {&lengthXArg, &lengthYArg, &lengthZArg}; - std::vector<TCLAP::ValueArg<unsigned>*> vec_ndivArg = {&nsubdivXArg, &nsubdivYArg, &nsubdivZArg}; - std::vector<TCLAP::ValueArg<double>*> vec_d0Arg = {&d0XArg, &d0YArg, &d0ZArg}; - std::vector<TCLAP::ValueArg<double>*> vec_dMaxArg = {&dmaxXArg, &dmaxYArg, &dmaxZArg}; - std::vector<TCLAP::ValueArg<double>*> vec_multiArg = {&multiXArg, &multiYArg, &multiZArg}; + std::vector<TCLAP::ValueArg<double>*> vec_lengthArg = { + &lengthXArg, &lengthYArg, &lengthZArg}; + std::vector<TCLAP::ValueArg<unsigned>*> vec_ndivArg = { + &nsubdivXArg, &nsubdivYArg, &nsubdivZArg}; + std::vector<TCLAP::ValueArg<double>*> vec_d0Arg = {&d0XArg, &d0YArg, + &d0ZArg}; + std::vector<TCLAP::ValueArg<double>*> vec_dMaxArg = {&dmaxXArg, &dmaxYArg, + &dmaxZArg}; + std::vector<TCLAP::ValueArg<double>*> vec_multiArg = { + &multiXArg, &multiYArg, &multiZArg}; - const bool isLengthSet = std::any_of(vec_lengthArg.begin(), vec_lengthArg.end(), - [&](TCLAP::ValueArg<double> *arg){return arg->isSet();}); - if (!isLengthSet) { + const bool isLengthSet = + std::any_of(vec_lengthArg.begin(), vec_lengthArg.end(), + [&](TCLAP::ValueArg<double>* arg) { return arg->isSet(); }); + if (!isLengthSet) + { ERR("Missing input: Length information is not provided at all."); return EXIT_FAILURE; } @@ -177,7 +188,7 @@ int main (int argc, char* argv[]) std::vector<double> length(dim); std::vector<unsigned> n_subdivision(dim); std::vector<double> vec_dx(dim); - for (unsigned i=0; i<dim; i++) + for (unsigned i = 0; i < dim; i++) { length[i] = vec_lengthArg[i]->getValue(); n_subdivision[i] = vec_ndivArg[i]->getValue(); @@ -186,12 +197,15 @@ int main (int argc, char* argv[]) std::vector<std::unique_ptr<BaseLib::ISubdivision>> vec_div; vec_div.reserve(dim); - for (unsigned i=0; i<dim; i++) + for (unsigned i = 0; i < dim; i++) { - if (vec_multiArg[i]->isSet()) { - if (vec_ndivArg[i]->isSet()) { + if (vec_multiArg[i]->isSet()) + { + if (vec_ndivArg[i]->isSet()) + { // number of partitions in direction is specified - if (vec_d0Arg[i]->isSet()) { + if (vec_d0Arg[i]->isSet()) + { OGS_FATAL( "Specifying all of --m?, --d?0 and --n? for coordinate " "'?' is not supported."); @@ -199,13 +213,16 @@ int main (int argc, char* argv[]) vec_div.emplace_back(new BaseLib::GradualSubdivisionFixedNum( length[i], vec_ndivArg[i]->getValue(), vec_multiArg[i]->getValue())); - - } else { + } + else + { vec_div.emplace_back(new BaseLib::GradualSubdivision( length[i], vec_d0Arg[i]->getValue(), vec_dMaxArg[i]->getValue(), vec_multiArg[i]->getValue())); } - } else { + } + else + { vec_div.emplace_back( new BaseLib::UniformSubdivision(length[i], n_subdivision[i])); } @@ -215,33 +232,37 @@ int main (int argc, char* argv[]) std::unique_ptr<MeshLib::Mesh> mesh; switch (eleType) { - case MeshLib::MeshElemType::LINE: - mesh.reset(MeshLib::MeshGenerator::generateLineMesh(*vec_div[0])); - break; - case MeshLib::MeshElemType::TRIANGLE: - mesh.reset(MeshLib::MeshGenerator::generateRegularTriMesh(*vec_div[0], *vec_div[1])); - break; - case MeshLib::MeshElemType::QUAD: - mesh.reset(MeshLib::MeshGenerator::generateRegularQuadMesh(*vec_div[0], *vec_div[1])); - break; - case MeshLib::MeshElemType::HEXAHEDRON: - mesh.reset(MeshLib::MeshGenerator::generateRegularHexMesh(*vec_div[0], *vec_div[1], *vec_div[2])); - break; - case MeshLib::MeshElemType::PRISM: - mesh.reset(MeshLib::MeshGenerator::generateRegularPrismMesh( - length[0], length[1], length[2], n_subdivision[0], n_subdivision[1], - n_subdivision[2])); - break; - case MeshLib::MeshElemType::TETRAHEDRON: - mesh.reset(MeshLib::MeshGenerator::generateRegularTetMesh(*vec_div[0], *vec_div[1], *vec_div[2])); - break; - case MeshLib::MeshElemType::PYRAMID: - mesh.reset(MeshLib::MeshGenerator::generateRegularPyramidMesh( - *vec_div[0], *vec_div[1], *vec_div[2])); - break; - default: - ERR("Given element type is not supported."); - break; + case MeshLib::MeshElemType::LINE: + mesh.reset(MeshLib::MeshGenerator::generateLineMesh(*vec_div[0])); + break; + case MeshLib::MeshElemType::TRIANGLE: + mesh.reset(MeshLib::MeshGenerator::generateRegularTriMesh( + *vec_div[0], *vec_div[1])); + break; + case MeshLib::MeshElemType::QUAD: + mesh.reset(MeshLib::MeshGenerator::generateRegularQuadMesh( + *vec_div[0], *vec_div[1])); + break; + case MeshLib::MeshElemType::HEXAHEDRON: + mesh.reset(MeshLib::MeshGenerator::generateRegularHexMesh( + *vec_div[0], *vec_div[1], *vec_div[2])); + break; + case MeshLib::MeshElemType::PRISM: + mesh.reset(MeshLib::MeshGenerator::generateRegularPrismMesh( + length[0], length[1], length[2], n_subdivision[0], + n_subdivision[1], n_subdivision[2])); + break; + case MeshLib::MeshElemType::TETRAHEDRON: + mesh.reset(MeshLib::MeshGenerator::generateRegularTetMesh( + *vec_div[0], *vec_div[1], *vec_div[2])); + break; + case MeshLib::MeshElemType::PYRAMID: + mesh.reset(MeshLib::MeshGenerator::generateRegularPyramidMesh( + *vec_div[0], *vec_div[1], *vec_div[2])); + break; + default: + ERR("Given element type is not supported."); + break; } if (mesh) diff --git a/BaseLib/ConfigTree.cpp b/BaseLib/ConfigTree.cpp index bc7be50d3365e52f7f236de7e18c55935b4dcffe..ab87cca03bd5a1fbb27dfbf4f5da5a5d3b3dd3d7 100644 --- a/BaseLib/ConfigTree.cpp +++ b/BaseLib/ConfigTree.cpp @@ -12,9 +12,9 @@ #include <forward_list> #include <utility> -#include "Logging.h" #include "Error.h" +#include "Logging.h" // Explicitly instantiate the boost::property_tree::ptree which is a typedef to // the following basic_ptree. @@ -27,7 +27,6 @@ static std::forward_list<std::string> configtree_destructor_error_messages; namespace BaseLib { - const char ConfigTree::pathseparator = '/'; const std::string ConfigTree::key_chars_start = "abcdefghijklmnopqrstuvwxyz"; const std::string ConfigTree::key_chars = key_chars_start + "_0123456789"; @@ -84,17 +83,18 @@ ConfigTree::~ConfigTree() return; } - try { + try + { checkAndInvalidate(); - } catch (std::exception& e) { + } + catch (std::exception& e) + { ERR("{:s}", e.what()); configtree_destructor_error_messages.push_front(e.what()); } } -ConfigTree& -ConfigTree:: -operator=(ConfigTree&& other) +ConfigTree& ConfigTree::operator=(ConfigTree&& other) { checkAndInvalidate(); @@ -110,9 +110,7 @@ operator=(ConfigTree&& other) return *this; } -ConfigTree -ConfigTree:: -getConfigParameter(std::string const& root) const +ConfigTree ConfigTree::getConfigParameter(std::string const& root) const { auto ct = getConfigSubtree(root); if (ct.hasChildren()) @@ -133,25 +131,22 @@ std::optional<ConfigTree> ConfigTree::getConfigParameterOptional( return ct; } -Range<ConfigTree::ParameterIterator> -ConfigTree:: -getConfigParameterList(const std::string ¶m) const +Range<ConfigTree::ParameterIterator> ConfigTree::getConfigParameterList( + const std::string& param) const { checkUnique(param); markVisited(param, Attr::TAG, true); auto p = tree_->equal_range(param); - return Range<ParameterIterator>( - ParameterIterator(p.first, param, *this), - ParameterIterator(p.second, param, *this)); + return Range<ParameterIterator>(ParameterIterator(p.first, param, *this), + ParameterIterator(p.second, param, *this)); } -ConfigTree -ConfigTree:: -getConfigSubtree(std::string const& root) const +ConfigTree ConfigTree::getConfigSubtree(std::string const& root) const { - if (auto t = getConfigSubtreeOptional(root)) { + if (auto t = getConfigSubtreeOptional(root)) + { return std::move(*t); } error("Key <" + root + "> has not been found."); @@ -171,21 +166,19 @@ std::optional<ConfigTree> ConfigTree::getConfigSubtreeOptional( return std::nullopt; } -Range<ConfigTree::SubtreeIterator> -ConfigTree:: -getConfigSubtreeList(std::string const& root) const +Range<ConfigTree::SubtreeIterator> ConfigTree::getConfigSubtreeList( + std::string const& root) const { checkUnique(root); markVisited(root, Attr::TAG, true); auto p = tree_->equal_range(root); - return Range<SubtreeIterator>( - SubtreeIterator(p.first, root, *this), - SubtreeIterator(p.second, root, *this)); + return Range<SubtreeIterator>(SubtreeIterator(p.first, root, *this), + SubtreeIterator(p.second, root, *this)); } -void ConfigTree::ignoreConfigParameter(const std::string ¶m) const +void ConfigTree::ignoreConfigParameter(const std::string& param) const { checkUnique(param); // if not found, peek only @@ -193,7 +186,7 @@ void ConfigTree::ignoreConfigParameter(const std::string ¶m) const markVisited(param, Attr::TAG, peek_only); } -void ConfigTree::ignoreConfigAttribute(const std::string &attr) const +void ConfigTree::ignoreConfigAttribute(const std::string& attr) const { checkUniqueAttr(attr); @@ -204,18 +197,18 @@ void ConfigTree::ignoreConfigAttribute(const std::string &attr) const markVisited(attr, Attr::ATTR, peek_only); } -void ConfigTree::ignoreConfigParameterAll(const std::string ¶m) const +void ConfigTree::ignoreConfigParameterAll(const std::string& param) const { checkUnique(param); auto& ct = markVisited(param, Attr::TAG, true); auto p = tree_->equal_range(param); - for (auto it = p.first; it != p.second; ++it) { + for (auto it = p.first; it != p.second; ++it) + { ++ct.count; } } - void ConfigTree::error(const std::string& message) const { onerror_(filename_, path_, message); @@ -229,16 +222,15 @@ void ConfigTree::warning(const std::string& message) const onwarning_(filename_, path_, message); } - void ConfigTree::onerror(const std::string& filename, const std::string& path, - const std::string& message) + const std::string& message) { OGS_FATAL("ConfigTree: In file `{:s}' at path <{:s}>: {:s}", filename, path, message); } void ConfigTree::onwarning(const std::string& filename, const std::string& path, - const std::string& message) + const std::string& message) { WARN("ConfigTree: In file `{:s}' at path <{:s}>: {:s}", filename, path, message); @@ -254,14 +246,15 @@ void ConfigTree::assertNoSwallowedErrors() ERR("ConfigTree: There have been errors when parsing the configuration " "file(s):"); - for (auto const& msg : configtree_destructor_error_messages) { + for (auto const& msg : configtree_destructor_error_messages) + { ERR("{:s}", msg); } OGS_FATAL("There have been errors when parsing the configuration file(s)."); } -std::string ConfigTree::shortString(const std::string &s) +std::string ConfigTree::shortString(const std::string& s) { const std::size_t maxlen = 100; @@ -270,19 +263,25 @@ std::string ConfigTree::shortString(const std::string &s) return s; } - return s.substr(0, maxlen-3) + "..."; + return s.substr(0, maxlen - 3) + "..."; } - void ConfigTree::checkKeyname(std::string const& key) const { - if (key.empty()) { + if (key.empty()) + { error("Search for empty key."); - } else if (key_chars_start.find(key.front()) == std::string::npos) { + } + else if (key_chars_start.find(key.front()) == std::string::npos) + { error("Key <" + key + "> starts with an illegal character."); - } else if (key.find_first_not_of(key_chars, 1) != std::string::npos) { + } + else if (key.find_first_not_of(key_chars, 1) != std::string::npos) + { error("Key <" + key + "> contains illegal characters."); - } else if (key.find("__") != std::string::npos) { + } + else if (key.find("__") != std::string::npos) + { // This is illegal because we use parameter names to generate doxygen // page names. Thereby "__" acts as a separator character. Choosing // other separators is not possible because of observed limitations @@ -291,10 +290,11 @@ void ConfigTree::checkKeyname(std::string const& key) const } } -std::string ConfigTree:: -joinPaths( const std::string &p1, const std::string &p2) const +std::string ConfigTree::joinPaths(const std::string& p1, + const std::string& p2) const { - if (p2.empty()) { + if (p2.empty()) + { error("Second path to be joined is empty."); } @@ -306,7 +306,7 @@ joinPaths( const std::string &p1, const std::string &p2) const return p1 + pathseparator + p2; } -void ConfigTree::checkUnique(const std::string &key) const +void ConfigTree::checkUnique(const std::string& key) const { checkKeyname(key); @@ -316,9 +316,10 @@ void ConfigTree::checkUnique(const std::string &key) const } } -void ConfigTree::checkUniqueAttr(const std::string &attr) const +void ConfigTree::checkUniqueAttr(const std::string& attr) const { - // Workaround for handling attributes with xml namespaces and uppercase letters. + // Workaround for handling attributes with xml namespaces and uppercase + // letters. if (attr.find(':') != std::string::npos) { auto pos = decltype(std::string::npos){0}; @@ -327,7 +328,8 @@ void ConfigTree::checkUniqueAttr(const std::string &attr) const // That means, attributes containing a colon are also allowed to contain // uppercase letters. auto attr2 = attr; - do { + do + { pos = attr2.find_first_of(":ABCDEFGHIJKLMNOPQRSTUVWXYZ", pos); if (pos != std::string::npos) { @@ -348,30 +350,29 @@ void ConfigTree::checkUniqueAttr(const std::string &attr) const } } -ConfigTree::CountType& -ConfigTree:: -markVisited(std::string const& key, Attr const is_attr, bool const peek_only) const +ConfigTree::CountType& ConfigTree::markVisited(std::string const& key, + Attr const is_attr, + bool const peek_only) const { return markVisited<ConfigTree>(key, is_attr, peek_only); } -void -ConfigTree:: -markVisitedDecrement(Attr const is_attr, std::string const& key) const +void ConfigTree::markVisitedDecrement(Attr const is_attr, + std::string const& key) const { auto const type = std::type_index(typeid(nullptr)); auto p = visited_params_.emplace(std::make_pair(is_attr, key), CountType{-1, type}); - if (!p.second) { // no insertion happened + if (!p.second) + { // no insertion happened auto& v = p.first->second; --v.count; } } -bool -ConfigTree::hasChildren() const +bool ConfigTree::hasChildren() const { auto const& tree = *tree_; if (tree.begin() == tree.end()) @@ -386,8 +387,7 @@ ConfigTree::hasChildren() const return true; } -void -ConfigTree::checkAndInvalidate() +void ConfigTree::checkAndInvalidate() { if (!tree_) { @@ -415,48 +415,59 @@ ConfigTree::checkAndInvalidate() // iterate over attributes if (auto attrs = tree_->get_child_optional("<xmlattr>")) { - for (auto const& p : *attrs) { + for (auto const& p : *attrs) + { markVisitedDecrement(Attr::ATTR, p.first); } } for (auto const& p : visited_params_) { - auto const& tag = p.first.second; + auto const& tag = p.first.second; auto const& count = p.second.count; - switch (p.first.first) { - case Attr::ATTR: - if (count > 0) { - warning("XML attribute '" + tag + "' has been read " + - std::to_string(count) + - " time(s) more than it was present in the " - "configuration tree."); - } else if (count < 0) { - warning("XML attribute '" + tag + "' has been read " + - std::to_string(-count) + - " time(s) less than it was present in the " - "configuration tree."); - } - break; - case Attr::TAG: - if (count > 0) { - warning("Key <" + tag + "> has been read " + std::to_string(count) - + " time(s) more than it was present in the configuration tree."); - } else if (count < 0) { - warning("Key <" + tag + "> has been read " + std::to_string(-count) - + " time(s) less than it was present in the configuration tree."); - } + switch (p.first.first) + { + case Attr::ATTR: + if (count > 0) + { + warning("XML attribute '" + tag + "' has been read " + + std::to_string(count) + + " time(s) more than it was present in the " + "configuration tree."); + } + else if (count < 0) + { + warning("XML attribute '" + tag + "' has been read " + + std::to_string(-count) + + " time(s) less than it was present in the " + "configuration tree."); + } + break; + case Attr::TAG: + if (count > 0) + { + warning("Key <" + tag + "> has been read " + + std::to_string(count) + + " time(s) more than it was present in the " + "configuration tree."); + } + else if (count < 0) + { + warning("Key <" + tag + "> has been read " + + std::to_string(-count) + + " time(s) less than it was present in the " + "configuration tree."); + } } } - // The following invalidates this instance, s.t. it can not be read from it anymore, - // but it also prevents double-checking. + // The following invalidates this instance, s.t. it can not be read from it + // anymore, but it also prevents double-checking. tree_ = nullptr; } - -void checkAndInvalidate(ConfigTree &conf) +void checkAndInvalidate(ConfigTree& conf) { conf.checkAndInvalidate(); } diff --git a/BaseLib/DateTools.cpp b/BaseLib/DateTools.cpp index 3558de5977e934b47ad3832b18e400c4b42f4535..28ddc226a87e88f758280e8837e54324264f3431 100644 --- a/BaseLib/DateTools.cpp +++ b/BaseLib/DateTools.cpp @@ -25,7 +25,7 @@ namespace BaseLib { int date2int(int y, int m, int d) { - if ( (y < 1000 || y > 9999) || (m < 1 || m > 12) || (d < 1 || d > 31) ) + if ((y < 1000 || y > 9999) || (m < 1 || m > 12) || (d < 1 || d > 31)) { WARN("date2int(): Input not in expected range."); return 0; @@ -95,40 +95,40 @@ std::string date2string(double ddate) { month = "0" + month; } - std::string s = std::to_string(y) + "-" + month + "-" + day; + std::string s = std::to_string(y) + "-" + month + "-" + day; return s; } -int strDate2int(const std::string &s) +int strDate2int(const std::string& s) { std::string str(s); if (s.length() > 10) { str = s.substr(0, 10); } - std::size_t sep ( str.find('.',0) ); - int d ( atoi(str.substr(0, sep).c_str()) ); - std::size_t sep2 ( str.find('.', sep + 1) ); - int m ( atoi(str.substr(sep + 1,sep2 - (sep + 1)).c_str()) ); - int y ( atoi(str.substr(sep2 + 1, s.length() - (sep2 + 1)).c_str()) ); + std::size_t sep(str.find('.', 0)); + int d(atoi(str.substr(0, sep).c_str())); + std::size_t sep2(str.find('.', sep + 1)); + int m(atoi(str.substr(sep + 1, sep2 - (sep + 1)).c_str())); + int y(atoi(str.substr(sep2 + 1, s.length() - (sep2 + 1)).c_str())); return date2int(y, m, d); } -int xmlDate2int(const std::string &s) +int xmlDate2int(const std::string& s) { if (s.length() == 10) { - int d = atoi(s.substr(8,2).c_str()); + int d = atoi(s.substr(8, 2).c_str()); if (d < 1 || d > 31) { WARN("xmlDate2double(): day not in [1:31]."); } - int m = atoi(s.substr(5,2).c_str()); + int m = atoi(s.substr(5, 2).c_str()); if (m < 1 || m > 12) { WARN("xmlDate2double(): month not in [1:12]."); } - int y = atoi(s.substr(0,4).c_str()); + int y = atoi(s.substr(0, 4).c_str()); return date2int(y, m, d); } return 0; @@ -140,9 +140,10 @@ std::string formatDate( auto const time_t = std::chrono::system_clock::to_time_t(time); char time_str[100]; if (std::strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S%z", - std::localtime(&time_t))) { + std::localtime(&time_t))) + { return time_str; } return "FAILED FORMATTING THE GIVEN TIME POINT."; } -} // end namespace BaseLib +} // end namespace BaseLib diff --git a/BaseLib/FileTools.cpp b/BaseLib/FileTools.cpp index a70cd564db3c97cf03e5ff7a9e614572d420af1a..2cb4c7bb0990e2f6a94c782ec56af7c815015fa4 100644 --- a/BaseLib/FileTools.cpp +++ b/BaseLib/FileTools.cpp @@ -12,15 +12,15 @@ * */ -#include <unordered_map> +#include "FileTools.h" + +#include <boost/algorithm/string.hpp> #include <typeindex> +#include <unordered_map> -#include "FileTools.h" #include "Error.h" #include "filesystem.h" -#include <boost/algorithm/string.hpp> - namespace { /// The directory where the prj file resides. @@ -35,7 +35,7 @@ namespace BaseLib /** * Returns true if given file exists. */ -bool IsFileExisting(const std::string &strFilename) +bool IsFileExisting(const std::string& strFilename) { return fs::exists(fs::path(strFilename)); } @@ -88,7 +88,7 @@ bool substituteKeyword(std::string& result, std::string& parenthesized_string, std::unordered_map<std::type_index, char> type_specification; type_specification[std::type_index(typeid(int))] = 'd'; - type_specification[std::type_index(typeid(double))] = 'f'; // default + type_specification[std::type_index(typeid(double))] = 'f'; // default type_specification[std::type_index(typeid(std::string))] = 's'; auto const& b = precision_specification.back(); @@ -145,7 +145,7 @@ double swapEndianness(double const& v) { double v; char c[sizeof(double)]; - } a {}, b {}; + } a{}, b{}; a.v = v; for (unsigned short i = 0; i < sizeof(double) / 2; i++) @@ -178,7 +178,7 @@ std::string extractBaseNameWithoutExtension(std::string const& pathname) return dropFileExtension(basename); } -std::string getFileExtension(const std::string &path) +std::string getFileExtension(const std::string& path) { return fs::path(path).extension().string(); } @@ -188,11 +188,11 @@ bool hasFileExtension(std::string const& extension, std::string const& filename) return boost::iequals(extension, getFileExtension(filename)); } -std::string copyPathToFileName(const std::string &file_name, - const std::string &source) +std::string copyPathToFileName(const std::string& file_name, + const std::string& source) { auto filePath = fs::path(file_name); - if(filePath.has_parent_path()) + if (filePath.has_parent_path()) { return filePath.string(); } @@ -244,4 +244,4 @@ void removeFiles(std::vector<std::string> const& files) removeFile(file); } } -} // end namespace BaseLib +} // end namespace BaseLib diff --git a/BaseLib/IO/Writer.cpp b/BaseLib/IO/Writer.cpp index be8c08e720e888ddfb3fccdb598c3098835077dd..a686743c2342457c8a277b5e2137688728d6125e 100644 --- a/BaseLib/IO/Writer.cpp +++ b/BaseLib/IO/Writer.cpp @@ -23,7 +23,6 @@ namespace BaseLib { namespace IO { - Writer::Writer() { out.precision(std::numeric_limits<double>::digits10); diff --git a/BaseLib/IO/XmlIO/Qt/XMLQtInterface.cpp b/BaseLib/IO/XmlIO/Qt/XMLQtInterface.cpp index 6564e5c028447801d3a311df411d8f3e5f18888b..46e68abad28f75b71e845766a3ea474290392c47 100644 --- a/BaseLib/IO/XmlIO/Qt/XMLQtInterface.cpp +++ b/BaseLib/IO/XmlIO/Qt/XMLQtInterface.cpp @@ -31,9 +31,10 @@ namespace IO { XMLQtInterface::XMLQtInterface(QString schemaFile) : schemaFile_(std::move(schemaFile)) -{} +{ +} -int XMLQtInterface::readFile(const QString &fileName) +int XMLQtInterface::readFile(const QString& fileName) { fileName_ = fileName; QFile file(fileName); @@ -64,9 +65,9 @@ int XMLQtInterface::isValid() const auto url = QUrl::fromLocalFile(path); schema.load(url); } - if ( schema.isValid() ) + if (schema.isValid()) { - QXmlSchemaValidator validator( schema ); + QXmlSchemaValidator validator(schema); if (validator.validate(fileData_)) { return 1; @@ -119,7 +120,7 @@ bool XMLQtInterface::checkHash() const } QFile fileMD5(md5FileName); - if(fileMD5.open(QIODevice::WriteOnly)) + if (fileMD5.open(QIODevice::WriteOnly)) { fileMD5.write(fileHash); fileMD5.close(); diff --git a/BaseLib/Logging.cpp b/BaseLib/Logging.cpp index f8e94466809061256dde29fcd22d2880a355a76a..3142046ed90792ec566f5df91d38e695fc6ac948 100644 --- a/BaseLib/Logging.cpp +++ b/BaseLib/Logging.cpp @@ -11,8 +11,8 @@ #include "Logging.h" -#include <spdlog/spdlog.h> #include <spdlog/sinks/stdout_color_sinks.h> +#include <spdlog/spdlog.h> #include <map> diff --git a/BaseLib/MemWatch.cpp b/BaseLib/MemWatch.cpp index 379338a9090a3c92cd7661909cba87b7ab4ca397..216451b274362b8483b3f115645b54c7e466b8bc 100644 --- a/BaseLib/MemWatch.cpp +++ b/BaseLib/MemWatch.cpp @@ -15,51 +15,51 @@ #include "MemWatch.h" #if !defined(_WIN32) && !defined(__APPLE__) && !defined(__MINGW32__) -#include <fstream> -#include <string> -#include <sstream> #include <sys/types.h> #include <unistd.h> -#endif -namespace BaseLib { +#include <fstream> +#include <sstream> +#include <string> +#endif -MemWatch::MemWatch () +namespace BaseLib { - updateMemUsage (); +MemWatch::MemWatch() +{ + updateMemUsage(); } -unsigned MemWatch::updateMemUsage () +unsigned MemWatch::updateMemUsage() { #if !defined(_WIN32) && !defined(__APPLE__) && !defined(__MINGW32__) - std::string fname ("/proc/"); - std::stringstream str_pid; - str_pid << static_cast<unsigned> (getpid()); - fname += str_pid.str(); - fname += "/statm"; - unsigned pages; + std::string fname("/proc/"); + std::stringstream str_pid; + str_pid << static_cast<unsigned>(getpid()); + fname += str_pid.str(); + fname += "/statm"; + unsigned pages; - std::ifstream in (fname.c_str(), std::ios::in); - if (!in.is_open()) - { - perror( "open" ); - return 1; - } + std::ifstream in(fname.c_str(), std::ios::in); + if (!in.is_open()) + { + perror("open"); + return 1; + } - in >> pages; - vmem_size_ = static_cast<unsigned long>(pages) * - static_cast<unsigned long>(getpagesize()); - in.close (); + in >> pages; + vmem_size_ = static_cast<unsigned long>(pages) * + static_cast<unsigned long>(getpagesize()); + in.close(); #endif - return 0; + return 0; } -unsigned long MemWatch::getVirtMemUsage () +unsigned long MemWatch::getVirtMemUsage() { - updateMemUsage (); - return vmem_size_; + updateMemUsage(); + return vmem_size_; } -} // end namespace BaseLib - +} // end namespace BaseLib diff --git a/BaseLib/StringTools.cpp b/BaseLib/StringTools.cpp index 269cab3ad5c15c11574dc78bf4e49b11063707d7..b8f4ed5ae2bb9b9236d148fb3c8d1ca04df97af2 100644 --- a/BaseLib/StringTools.cpp +++ b/BaseLib/StringTools.cpp @@ -30,12 +30,12 @@ std::vector<std::string> splitString(std::string const& str) std::istringstream str_stream(str); std::vector<std::string> items; std::copy(std::istream_iterator<std::string>(str_stream), - std::istream_iterator<std::string>(), - std::back_inserter(items)); + std::istream_iterator<std::string>(), + std::back_inserter(items)); return items; } -std::list<std::string> splitString(const std::string &str, char delim) +std::list<std::string> splitString(const std::string& str, char delim) { std::list<std::string> strList; std::stringstream ss(str); @@ -47,18 +47,18 @@ std::list<std::string> splitString(const std::string &str, char delim) return strList; } -std::string replaceString(const std::string &searchString, - const std::string &replaceString, +std::string replaceString(const std::string& searchString, + const std::string& replaceString, std::string stringToReplace) { boost::replace_all(stringToReplace, searchString, replaceString); return stringToReplace; } -void trim(std::string &str, char ch) +void trim(std::string& str, char ch) { std::string::size_type pos = str.find_last_not_of(ch); - if(pos != std::string::npos) + if (pos != std::string::npos) { str.erase(pos + 1); pos = str.find_first_not_of(ch); @@ -73,16 +73,16 @@ void trim(std::string &str, char ch) } } -void simplify(std::string &str) +void simplify(std::string& str) { - trim (str); - str.erase( - std::unique(str.begin(), str.end(), [](char a, char b) { return a == ' ' && b == ' '; }), - str.end() - ); + trim(str); + str.erase(std::unique(str.begin(), + str.end(), + [](char a, char b) { return a == ' ' && b == ' '; }), + str.end()); } -std::string format(const char* format_str, ... ) +std::string format(const char* format_str, ...) { va_list args; va_start(args, format_str); @@ -92,7 +92,7 @@ std::string format(const char* format_str, ... ) int char_length = std::vsnprintf(nullptr, 0, format_str, args_tmp); va_end(args_tmp); // allocate buffer and store formatted output there - std::vector<char> buffer(char_length + 1); // note +1 for null terminator + std::vector<char> buffer(char_length + 1); // note +1 for null terminator vsnprintf(buffer.data(), buffer.size(), format_str, args); va_end(args); @@ -102,9 +102,7 @@ std::string format(const char* format_str, ... ) std::string randomString(std::size_t const length) { static constexpr char charset[] = - "0123456789" - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz"; + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; static const auto seed = static_cast<std::mt19937::result_type>( std::chrono::system_clock::now().time_since_epoch().count()); diff --git a/BaseLib/Subdivision.cpp b/BaseLib/Subdivision.cpp index bac3c58e49050bd98702d31ac84d057e796970d2..ed06417b3ee38a5414eb5a5538abb4a8fb7ad0a0 100644 --- a/BaseLib/Subdivision.cpp +++ b/BaseLib/Subdivision.cpp @@ -13,7 +13,7 @@ #include <algorithm> #include <cmath> -#include <BaseLib/Error.h> +#include "BaseLib/Error.h" namespace BaseLib { @@ -25,7 +25,8 @@ GradualSubdivision::GradualSubdivision(const double L, { // Check if accumulated subdivisions can ever sum up to length. // Cf. geometric series formula. - if (multiplier < 1.0 && dL0 / (1.0 - multiplier) < L) { + if (multiplier < 1.0 && dL0 / (1.0 - multiplier) < L) + { OGS_FATAL( "Using dL0={:g} and multiplier={:g} the generated subdivisions can " "not sum up to a total length of {:g}.", @@ -41,7 +42,8 @@ std::vector<double> GradualSubdivision::operator()() const double x = 0; unsigned i = 0; - do { + do + { vec_x.push_back(x); x += std::min(max_dL_, dL0_ * std::pow(multiplier_, static_cast<double>(i))); @@ -76,14 +78,17 @@ std::vector<double> GradualSubdivisionFixedNum::operator()() const subdivisions.push_back(0.0); auto const q = multiplier_; - if (q == 1.0) { + if (q == 1.0) + { double const dx = length_ / num_subdivisions_; for (std::size_t i = 1; i < num_subdivisions_; ++i) { subdivisions.push_back(dx * i); } - } else { + } + else + { // compute initial subdivision size auto const a = length_ * (q - 1.0) / (std::pow(q, num_subdivisions_) - 1.0); diff --git a/ChemistryLib/Common/CreateChargeBalance.cpp b/ChemistryLib/Common/CreateChargeBalance.cpp index 71f9109d502e19e4dcd86356aebb5876eb84e1c9..8bd7656505bbd3343c3ec3e1fad0aa8c29b9ae58 100644 --- a/ChemistryLib/Common/CreateChargeBalance.cpp +++ b/ChemistryLib/Common/CreateChargeBalance.cpp @@ -9,6 +9,7 @@ */ #include "CreateChargeBalance.h" + #include "BaseLib/ConfigTree.h" #include "BaseLib/Error.h" #include "ChargeBalance.h" diff --git a/ChemistryLib/PhreeqcIO.cpp b/ChemistryLib/PhreeqcIO.cpp index c7a94b23b9aecec52e13be41e3f7008b45e7c541..7bd943b1ec8c42d41db07dd60cb8b71b25d34fad 100644 --- a/ChemistryLib/PhreeqcIO.cpp +++ b/ChemistryLib/PhreeqcIO.cpp @@ -243,14 +243,14 @@ void PhreeqcIO::initializeChemicalSystemConcrete( for (auto& kinetic_reactant : _chemical_system->kinetic_reactants) { - initializeReactantMolality(kinetic_reactant, chemical_system_id, medium, pos, - t); + initializeReactantMolality(kinetic_reactant, chemical_system_id, medium, + pos, t); } for (auto& equilibrium_reactant : _chemical_system->equilibrium_reactants) { - initializeReactantMolality(equilibrium_reactant, chemical_system_id, medium, - pos, t); + initializeReactantMolality(equilibrium_reactant, chemical_system_id, + medium, pos, t); } } @@ -516,8 +516,7 @@ std::istream& operator>>(std::istream& in, PhreeqcIO& phreeqc_io) { OGS_FATAL( "Error when reading calculation result of Solution {:d} " - "after " - "the reaction.", + "after the reaction.", chemical_system_id); } @@ -540,8 +539,8 @@ std::istream& operator>>(std::istream& in, PhreeqcIO& phreeqc_io) catch (const std::invalid_argument& e) { OGS_FATAL( - "Invalid argument. Could not convert string '{:s}' " - "to double for chemical system {:d}, column {:d}. " + "Invalid argument. Could not convert string '{:s}' to " + "double for chemical system {:d}, column {:d}. " "Exception '{:s}' was thrown.", items[item_id], chemical_system_id + 1, item_id, e.what()); diff --git a/ChemistryLib/PhreeqcIOData/AqueousSolution.cpp b/ChemistryLib/PhreeqcIOData/AqueousSolution.cpp index 21e5c260affabc701f2a7d8d49c403a8f37dc620..71cd09cdb1b900209d6d51c898331decd3734e8c 100644 --- a/ChemistryLib/PhreeqcIOData/AqueousSolution.cpp +++ b/ChemistryLib/PhreeqcIOData/AqueousSolution.cpp @@ -8,10 +8,11 @@ * */ +#include "AqueousSolution.h" + #include <cmath> #include <ostream> -#include "AqueousSolution.h" #include "ChemistryLib/Common/ChargeBalance.h" #include "MeshLib/PropertyVector.h" diff --git a/ChemistryLib/PhreeqcIOData/ChemicalSystem.cpp b/ChemistryLib/PhreeqcIOData/ChemicalSystem.cpp index 1382ba202359b5fd0fc9316c5a2da996de6b35f3..c75360983d062a7df1ea19b962672315df389a05 100644 --- a/ChemistryLib/PhreeqcIOData/ChemicalSystem.cpp +++ b/ChemistryLib/PhreeqcIOData/ChemicalSystem.cpp @@ -9,8 +9,8 @@ */ #include "ChemicalSystem.h" -#include "AqueousSolution.h" +#include "AqueousSolution.h" #include "MathLib/LinAlg/MatrixVectorTraits.h" #include "MathLib/LinAlg/UnifiedMatrixSetters.h" diff --git a/ChemistryLib/PhreeqcIOData/CreateAqueousSolution.cpp b/ChemistryLib/PhreeqcIOData/CreateAqueousSolution.cpp index 3260c28cab8c6076860518802eae42d29c9c2707..10ce53a98deb0dd0e27d4a58f29ace085f97f067 100644 --- a/ChemistryLib/PhreeqcIOData/CreateAqueousSolution.cpp +++ b/ChemistryLib/PhreeqcIOData/CreateAqueousSolution.cpp @@ -9,6 +9,7 @@ */ #include "CreateAqueousSolution.h" + #include "AqueousSolution.h" #include "BaseLib/ConfigTree.h" #include "ChemistryLib/Common/CreateChargeBalance.h" diff --git a/ChemistryLib/PhreeqcIOData/CreateChemicalSystem.cpp b/ChemistryLib/PhreeqcIOData/CreateChemicalSystem.cpp index 0de89dbe61961f055a7aa022d572e22c26f7a4ca..eebaf94479355c98c4d3d0bad5592ff973ae9e22 100644 --- a/ChemistryLib/PhreeqcIOData/CreateChemicalSystem.cpp +++ b/ChemistryLib/PhreeqcIOData/CreateChemicalSystem.cpp @@ -9,6 +9,7 @@ */ #include "CreateChemicalSystem.h" + #include "BaseLib/ConfigTree.h" #include "ChemicalSystem.h" #include "CreateAqueousSolution.h" diff --git a/ChemistryLib/PhreeqcIOData/CreateEquilibriumReactants.cpp b/ChemistryLib/PhreeqcIOData/CreateEquilibriumReactants.cpp index 366c3e0a75015f31fbe4275b7fce8416c97cb46b..142a66c9fc816e930d89f0465108dce810eaf1be 100644 --- a/ChemistryLib/PhreeqcIOData/CreateEquilibriumReactants.cpp +++ b/ChemistryLib/PhreeqcIOData/CreateEquilibriumReactants.cpp @@ -53,8 +53,11 @@ std::vector<EquilibriumReactant> createEquilibriumReactants( mesh, name + "_avg", MeshLib::MeshItemType::Cell, 1); mesh_prop_molality->resize(mesh.getNumberOfElements()); - equilibrium_reactants.emplace_back( - std::move(name), molality, volume_fraction, mesh_prop_molality, saturation_index); + equilibrium_reactants.emplace_back(std::move(name), + molality, + volume_fraction, + mesh_prop_molality, + saturation_index); } return equilibrium_reactants; diff --git a/ChemistryLib/PhreeqcIOData/CreateKnobs.cpp b/ChemistryLib/PhreeqcIOData/CreateKnobs.cpp index 067d1587788bc099e06707a615c151fd9c6fd6b3..5fd589c6bc759cd6f066755ef2ee8ad6e5c6bd3f 100644 --- a/ChemistryLib/PhreeqcIOData/CreateKnobs.cpp +++ b/ChemistryLib/PhreeqcIOData/CreateKnobs.cpp @@ -9,6 +9,7 @@ */ #include "CreateKnobs.h" + #include "BaseLib/ConfigTree.h" #include "Knobs.h" diff --git a/ChemistryLib/PhreeqcIOData/CreateOutput.cpp b/ChemistryLib/PhreeqcIOData/CreateOutput.cpp index 260e22bc626b75bd534d7f6b6e4f8484e5c93052..7e96d01617b691874d622d5e61899643ea96d590 100644 --- a/ChemistryLib/PhreeqcIOData/CreateOutput.cpp +++ b/ChemistryLib/PhreeqcIOData/CreateOutput.cpp @@ -8,12 +8,13 @@ * */ +#include "CreateOutput.h" + #include <algorithm> #include <numeric> #include "AqueousSolution.h" #include "ChemicalSystem.h" -#include "CreateOutput.h" #include "KineticReactant.h" #include "UserPunch.h" diff --git a/ChemistryLib/PhreeqcIOData/CreateSolutionComponent.cpp b/ChemistryLib/PhreeqcIOData/CreateSolutionComponent.cpp index 6a0c67fdcc088a709bec65b7a73c8dff67d688ab..eb57be82916abd3e071c24c1be754ec29f557e52 100644 --- a/ChemistryLib/PhreeqcIOData/CreateSolutionComponent.cpp +++ b/ChemistryLib/PhreeqcIOData/CreateSolutionComponent.cpp @@ -9,6 +9,7 @@ */ #include "CreateSolutionComponent.h" + #include "AqueousSolution.h" #include "BaseLib/ConfigTree.h" diff --git a/ChemistryLib/PhreeqcIOData/Dump.cpp b/ChemistryLib/PhreeqcIOData/Dump.cpp index 87181623b9f78a7ba75af239cb869936aa074dea..b950113563ed4931e9d052a7890463453f1a5d74 100644 --- a/ChemistryLib/PhreeqcIOData/Dump.cpp +++ b/ChemistryLib/PhreeqcIOData/Dump.cpp @@ -8,21 +8,24 @@ * */ -#include <iostream> - #include "Dump.h" +#include <iostream> + namespace ChemistryLib { namespace PhreeqcIOData { void Dump::print(std::ostream& os, std::size_t const num_chemical_systems) const { - os << "DUMP" << "\n"; + os << "DUMP" + << "\n"; os << "-file " << dump_file << "\n"; - os << "-append false" << "\n"; + os << "-append false" + << "\n"; os << "-solution 1-" << num_chemical_systems << "\n"; - os << "END" << "\n"; + os << "END" + << "\n"; } void Dump::readDumpFile(std::istream& in, diff --git a/ChemistryLib/PhreeqcIOData/EquilibriumReactant.cpp b/ChemistryLib/PhreeqcIOData/EquilibriumReactant.cpp index e48e452afc1b017c67cb12d58ac564c24defcb3e..185403dc8a2297ba970e77dac00907070fe94eb9 100644 --- a/ChemistryLib/PhreeqcIOData/EquilibriumReactant.cpp +++ b/ChemistryLib/PhreeqcIOData/EquilibriumReactant.cpp @@ -8,10 +8,10 @@ * */ -#include <ostream> - #include "EquilibriumReactant.h" +#include <ostream> + namespace ChemistryLib { namespace PhreeqcIOData diff --git a/ChemistryLib/PhreeqcIOData/KineticReactant.cpp b/ChemistryLib/PhreeqcIOData/KineticReactant.cpp index 173635e2ebcdc11c343e1f6b1a2180aff34b9367..7c1d5288b555ba23320cacb0c1fac48fb4d5eb0e 100644 --- a/ChemistryLib/PhreeqcIOData/KineticReactant.cpp +++ b/ChemistryLib/PhreeqcIOData/KineticReactant.cpp @@ -8,10 +8,10 @@ * */ -#include <ostream> - #include "KineticReactant.h" +#include <ostream> + namespace ChemistryLib { namespace PhreeqcIOData diff --git a/ChemistryLib/PhreeqcIOData/Knobs.cpp b/ChemistryLib/PhreeqcIOData/Knobs.cpp index c717452ea312f0e6bcc3f88e63219113eedc0a84..66230d2ba6b63827180b0e8520131472ddfa8c33 100644 --- a/ChemistryLib/PhreeqcIOData/Knobs.cpp +++ b/ChemistryLib/PhreeqcIOData/Knobs.cpp @@ -8,17 +8,18 @@ * */ -#include <ostream> - #include "Knobs.h" +#include <ostream> + namespace ChemistryLib { namespace PhreeqcIOData { std::ostream& operator<<(std::ostream& os, Knobs const& knobs) { - os << "KNOBS" << "\n"; + os << "KNOBS" + << "\n"; os << "-iterations " << knobs.max_iterations << "\n"; os << "-convergence_tolerance " << knobs.relative_convergence_tolerance << "\n"; diff --git a/ChemistryLib/PhreeqcIOData/Output.cpp b/ChemistryLib/PhreeqcIOData/Output.cpp index 2b68617d76fae7d853fc148392d0a46bfdcab8c1..522ab2352556af5b9b20df54b597a0c657d6388b 100644 --- a/ChemistryLib/PhreeqcIOData/Output.cpp +++ b/ChemistryLib/PhreeqcIOData/Output.cpp @@ -8,10 +8,10 @@ * */ -#include <ostream> - #include "Output.h" +#include <ostream> + namespace ChemistryLib { namespace PhreeqcIOData @@ -19,7 +19,8 @@ namespace PhreeqcIOData std::ostream& operator<<(std::ostream& os, BasicOutputSetups const& basic_output_setups) { - os << "SELECTED_OUTPUT" << "\n"; + os << "SELECTED_OUTPUT" + << "\n"; os << "-file " << basic_output_setups.output_file << "\n"; os << "-high_precision " << std::boolalpha << basic_output_setups.use_high_precision << "\n"; diff --git a/ChemistryLib/PhreeqcIOData/ReactionRate.cpp b/ChemistryLib/PhreeqcIOData/ReactionRate.cpp index 91b786fc3d493c93681957b7e43c10867460f418..386840ff039b883c2f0858e0f06e59f1e15955e0 100644 --- a/ChemistryLib/PhreeqcIOData/ReactionRate.cpp +++ b/ChemistryLib/PhreeqcIOData/ReactionRate.cpp @@ -8,10 +8,10 @@ * */ -#include <ostream> - #include "ReactionRate.h" +#include <ostream> + namespace ChemistryLib { namespace PhreeqcIOData @@ -19,14 +19,16 @@ namespace PhreeqcIOData std::ostream& operator<<(std::ostream& os, ReactionRate const& reaction_rate) { os << reaction_rate.kinetic_reactant << "\n"; - os << "-start" << "\n"; + os << "-start" + << "\n"; int line_number = 1; for (auto const& expression_statement : reaction_rate.expression_statements) { os << line_number << " " << expression_statement << "\n"; ++line_number; } - os << "-end" << "\n"; + os << "-end" + << "\n"; return os; } diff --git a/ChemistryLib/PhreeqcIOData/Surface.cpp b/ChemistryLib/PhreeqcIOData/Surface.cpp index f7466b5b0b38d96b760181fcf083b0c9d347f20f..53fbafc54beebdd4be65db7bfc49b74eecd8da74 100644 --- a/ChemistryLib/PhreeqcIOData/Surface.cpp +++ b/ChemistryLib/PhreeqcIOData/Surface.cpp @@ -8,10 +8,10 @@ * */ -#include <ostream> - #include "Surface.h" +#include <ostream> + namespace ChemistryLib { namespace PhreeqcIOData diff --git a/ChemistryLib/PhreeqcIOData/UserPunch.cpp b/ChemistryLib/PhreeqcIOData/UserPunch.cpp index 0475d4327e5e49aff1e046bd86fe5477f1bb30ed..a42c56b6123047ace66b66e94ad50039785c53f4 100644 --- a/ChemistryLib/PhreeqcIOData/UserPunch.cpp +++ b/ChemistryLib/PhreeqcIOData/UserPunch.cpp @@ -9,6 +9,7 @@ */ #include "UserPunch.h" + #include "BaseLib/ConfigTreeUtil.h" namespace ChemistryLib @@ -25,7 +26,8 @@ void UserPunch::initialize(std::size_t const num_chemical_systems) std::ostream& operator<<(std::ostream& os, UserPunch const& user_punch) { - os << "USER_PUNCH" << "\n"; + os << "USER_PUNCH" + << "\n"; os << "-headings "; auto const& secondary_variables = user_punch.secondary_variables; for (auto& secondary_variable : secondary_variables) @@ -34,14 +36,16 @@ std::ostream& operator<<(std::ostream& os, UserPunch const& user_punch) } os << "\n"; - os << "-start" << "\n"; + os << "-start" + << "\n"; int line_number = 1; for (auto const& statement : user_punch.statements) { os << line_number << " " << statement << "\n"; ++line_number; } - os << "-end" << "\n"; + os << "-end" + << "\n"; return os; } diff --git a/ChemistryLib/PhreeqcKernelData/CreateInitialAqueousSolution.cpp b/ChemistryLib/PhreeqcKernelData/CreateInitialAqueousSolution.cpp index 1ea75b05eaa5fa14ec5a4ddf5145d3371d51a933..f5c54b4ac51a96aa9ce1838acbde6900e0476d60 100644 --- a/ChemistryLib/PhreeqcKernelData/CreateInitialAqueousSolution.cpp +++ b/ChemistryLib/PhreeqcKernelData/CreateInitialAqueousSolution.cpp @@ -9,6 +9,7 @@ */ #include "CreateInitialAqueousSolution.h" + #include "BaseLib/ConfigTree.h" #include "BaseLib/Error.h" #include "ChemistryLib/Common/ChargeBalance.h" @@ -51,8 +52,7 @@ InitialAqueousSolution createInitialAqueousSolution( { OGS_FATAL( "Component {:s} given in <solution>/<components> is not found " - "in " - "specified coupled processes (see " + "in specified coupled processes (see " "<process>/<process_variables>/<concentration>).", component.first); } diff --git a/ChemistryLib/PhreeqcKernelData/KineticReactant.cpp b/ChemistryLib/PhreeqcKernelData/KineticReactant.cpp index ec835592f044b5065e266931a4d3e56f982f9697..64a42fe208fc6e435ed599630f2a4a1d3dea593c 100644 --- a/ChemistryLib/PhreeqcKernelData/KineticReactant.cpp +++ b/ChemistryLib/PhreeqcKernelData/KineticReactant.cpp @@ -8,10 +8,10 @@ * */ -#include <algorithm> - #include "KineticReactant.h" +#include <algorithm> + namespace ChemistryLib { namespace PhreeqcKernelData diff --git a/ChemistryLib/PhreeqcKernelData/ReactionRate.cpp b/ChemistryLib/PhreeqcKernelData/ReactionRate.cpp index 8be0544682e3adc3d922c0214363badddd9db978..fd2f055eb5e2aa3192cb0a5270e3d609e0a4807e 100644 --- a/ChemistryLib/PhreeqcKernelData/ReactionRate.cpp +++ b/ChemistryLib/PhreeqcKernelData/ReactionRate.cpp @@ -14,8 +14,8 @@ namespace ChemistryLib { namespace PhreeqcKernelData { -ReactionRate::ReactionRate(std::string kinetic_reactant_, - std::vector<std::string> statements) +ReactionRate::ReactionRate( + std::string kinetic_reactant_, std::vector<std::string> statements) : kinetic_reactant(std::move(kinetic_reactant_)) { int line_number = 1; diff --git a/GeoLib/AnalyticalGeometry.cpp b/GeoLib/AnalyticalGeometry.cpp index 8d1b5d3530d860e5d713429ffa9565f9aa347927..011835cc159c415b119b23065e60cf62f22fb30d 100644 --- a/GeoLib/AnalyticalGeometry.cpp +++ b/GeoLib/AnalyticalGeometry.cpp @@ -14,31 +14,27 @@ #include "AnalyticalGeometry.h" +#include <Eigen/Dense> #include <algorithm> #include <cmath> #include <limits> - -#include <Eigen/Dense> - #include "BaseLib/StringTools.h" - -#include "Polyline.h" -#include "PointVec.h" - #include "MathLib/GeometricBasics.h" +#include "PointVec.h" +#include "Polyline.h" -extern double orient2d(double *, double *, double *); +extern double orient2d(double*, double*, double*); extern double orient2dfast(double*, double*, double*); namespace ExactPredicates { -double getOrientation2d(MathLib::Point3d const& a, - MathLib::Point3d const& b, MathLib::Point3d const& c) +double getOrientation2d(MathLib::Point3d const& a, MathLib::Point3d const& b, + MathLib::Point3d const& c) { return orient2d(const_cast<double*>(a.getCoords()), - const_cast<double*>(b.getCoords()), - const_cast<double*>(c.getCoords())); + const_cast<double*>(b.getCoords()), + const_cast<double*>(c.getCoords())); } double getOrientation2dFast(MathLib::Point3d const& a, @@ -119,7 +115,8 @@ bool parallel(Eigen::Vector3d v, Eigen::Vector3d w) parallel = false; } - if (! parallel) { + if (!parallel) + { parallel = true; // change sense of direction of v_normalised v *= -1.0; @@ -185,14 +182,15 @@ bool lineSegmentIntersect(GeoLib::LineSegment const& s0, } auto isLineSegmentIntersectingAB = [&v](Eigen::Vector3d const& ap, - std::size_t i) - { + std::size_t i) { // check if p is located at v=(a,b): (ap = t*v, t in [0,1]) return 0.0 <= ap[i] / v[i] && ap[i] / v[i] <= 1.0; }; - if (parallel(v,w)) { // original line segments (a,b) and (c,d) are parallel - if (parallel(pq,v)) { // line segment (a,b) and (a,c) are also parallel + if (parallel(v, w)) + { // original line segments (a,b) and (c,d) are parallel + if (parallel(pq, v)) + { // line segment (a,b) and (a,c) are also parallel // Here it is already checked that the line segments (a,b) and (c,d) // are parallel. At this point it is also known that the line // segment (a,c) is also parallel to (a,b). In that case it is @@ -207,7 +205,8 @@ bool lineSegmentIntersect(GeoLib::LineSegment const& s0, // coordinate axis. std::size_t i_max(std::abs(v[0]) <= std::abs(v[1]) ? 1 : 0); i_max = std::abs(v[i_max]) <= std::abs(v[2]) ? 2 : i_max; - if (isLineSegmentIntersectingAB(qp, i_max)) { + if (isLineSegmentIntersectingAB(qp, i_max)) + { s = pc; return true; } @@ -227,10 +226,10 @@ bool lineSegmentIntersect(GeoLib::LineSegment const& s0, const double sqr_len_w(w.squaredNorm()); Eigen::Matrix2d mat; - mat(0,0) = sqr_len_v; - mat(0,1) = -v.dot(w); - mat(1,1) = sqr_len_w; - mat(1,0) = mat(0,1); + mat(0, 0) = sqr_len_v; + mat(0, 1) = -v.dot(w); + mat(1, 1) = sqr_len_w; + mat(1, 0) = mat(0, 1); Eigen::Vector2d rhs{v.dot(qp), w.dot(pq)}; @@ -238,21 +237,25 @@ bool lineSegmentIntersect(GeoLib::LineSegment const& s0, // no theory for the following tolerances, determined by testing // lower tolerance: little bit smaller than zero - const double l(-1.0*std::numeric_limits<float>::epsilon()); + const double l(-1.0 * std::numeric_limits<float>::epsilon()); // upper tolerance a little bit greater than one - const double u(1.0+std::numeric_limits<float>::epsilon()); - if (rhs[0] < l || u < rhs[0] || rhs[1] < l || u < rhs[1]) { + const double u(1.0 + std::numeric_limits<float>::epsilon()); + if (rhs[0] < l || u < rhs[0] || rhs[1] < l || u < rhs[1]) + { return false; } // compute points along line segments with minimal distance - GeoLib::Point const p0(a[0]+rhs[0]*v[0], a[1]+rhs[0]*v[1], a[2]+rhs[0]*v[2]); - GeoLib::Point const p1(c[0]+rhs[1]*w[0], c[1]+rhs[1]*w[1], c[2]+rhs[1]*w[2]); + GeoLib::Point const p0(a[0] + rhs[0] * v[0], a[1] + rhs[0] * v[1], + a[2] + rhs[0] * v[2]); + GeoLib::Point const p1(c[0] + rhs[1] * w[0], c[1] + rhs[1] * w[1], + c[2] + rhs[1] * w[2]); double const min_dist(std::sqrt(MathLib::sqrDist(p0, p1))); double const min_seg_len( std::min(std::sqrt(sqr_len_v), std::sqrt(sqr_len_w))); - if (min_dist < min_seg_len * 1e-6) { + if (min_dist < min_seg_len * 1e-6) + { s[0] = 0.5 * (p0[0] + p1[0]); s[1] = 0.5 * (p0[1] + p1[1]); s[2] = 0.5 * (p0[2] + p1[2]); @@ -263,8 +266,8 @@ bool lineSegmentIntersect(GeoLib::LineSegment const& s0, } bool lineSegmentsIntersect(const GeoLib::Polyline* ply, - GeoLib::Polyline::SegmentIterator &seg_it0, - GeoLib::Polyline::SegmentIterator &seg_it1, + GeoLib::Polyline::SegmentIterator& seg_it0, + GeoLib::Polyline::SegmentIterator& seg_it1, GeoLib::Point& intersection_pnt) { std::size_t const n_segs(ply->getNumberOfSegments()); @@ -272,13 +275,16 @@ bool lineSegmentsIntersect(const GeoLib::Polyline* ply, // checks for intersections of non-neighbouring segments. for (seg_it0 = ply->begin(); seg_it0 != ply->end() - 2; ++seg_it0) { - seg_it1 = seg_it0+2; + seg_it1 = seg_it0 + 2; std::size_t const seg_num_0 = seg_it0.getSegmentNumber(); - for ( ; seg_it1 != ply->end(); ++seg_it1) { + for (; seg_it1 != ply->end(); ++seg_it1) + { // Do not check first and last segment, because they are // neighboured. - if (!(seg_num_0 == 0 && seg_it1.getSegmentNumber() == n_segs - 1)) { - if (lineSegmentIntersect(*seg_it0, *seg_it1, intersection_pnt)) { + if (!(seg_num_0 == 0 && seg_it1.getSegmentNumber() == n_segs - 1)) + { + if (lineSegmentIntersect(*seg_it0, *seg_it1, intersection_pnt)) + { return true; } } @@ -402,12 +408,11 @@ std::unique_ptr<GeoLib::Point> triangleLineIntersection( u * a[2] + v * b[2] + w * c[2]); } -void computeAndInsertAllIntersectionPoints(GeoLib::PointVec &pnt_vec, - std::vector<GeoLib::Polyline*> & plys) +void computeAndInsertAllIntersectionPoints(GeoLib::PointVec& pnt_vec, + std::vector<GeoLib::Polyline*>& plys) { auto computeSegmentIntersections = [&pnt_vec](GeoLib::Polyline& poly0, - GeoLib::Polyline& poly1) - { + GeoLib::Polyline& poly1) { for (auto seg0_it(poly0.begin()); seg0_it != poly0.end(); ++seg0_it) { for (auto seg1_it(poly1.begin()); seg1_it != poly1.end(); ++seg1_it) @@ -424,10 +429,12 @@ void computeAndInsertAllIntersectionPoints(GeoLib::PointVec &pnt_vec, } }; - for (auto it0(plys.begin()); it0 != plys.end(); ++it0) { + for (auto it0(plys.begin()); it0 != plys.end(); ++it0) + { auto it1(it0); ++it1; - for (; it1 != plys.end(); ++it1) { + for (; it1 != plys.end(); ++it1) + { computeSegmentIntersections(*(*it0), *(*it1)); } } @@ -452,8 +459,7 @@ GeoLib::Polygon rotatePolygonToXY(GeoLib::Polygon const& polygon_in, // 3 set z coord to zero std::for_each(polygon_pnts->begin(), polygon_pnts->end(), - [] (GeoLib::Point* p) { (*p)[2] = 0.0; } - ); + [](GeoLib::Point* p) { (*p)[2] = 0.0; }); // 4 create new polygon GeoLib::Polyline rot_polyline(*polygon_pnts); @@ -477,12 +483,15 @@ std::vector<MathLib::Point3d> lineSegmentIntersect2d( double const orient_abd(getOrientation(a, b, d)); // check if the segment (cd) lies on the left or on the right of (ab) - if ((orient_abc > 0 && orient_abd > 0) || (orient_abc < 0 && orient_abd < 0)) { + if ((orient_abc > 0 && orient_abd > 0) || + (orient_abc < 0 && orient_abd < 0)) + { return std::vector<MathLib::Point3d>(); } // check: (cd) and (ab) are on the same line - if (orient_abc == 0.0 && orient_abd == 0.0) { + if (orient_abc == 0.0 && orient_abd == 0.0) + { double const eps(std::numeric_limits<double>::epsilon()); if (MathLib::sqrDist2d(a, c) < eps && MathLib::sqrDist2d(b, d) < eps) { @@ -495,28 +504,32 @@ std::vector<MathLib::Point3d> lineSegmentIntersect2d( // Since orient_ab and orient_abd vanish, a, b, c, d are on the same // line and for this reason it is enough to check the x-component. - auto isPointOnSegment = [](double q, double p0, double p1) - { + auto isPointOnSegment = [](double q, double p0, double p1) { double const t((q - p0) / (p1 - p0)); return 0 <= t && t <= 1; }; // check if c in (ab) - if (isPointOnSegment(c[0], a[0], b[0])) { + if (isPointOnSegment(c[0], a[0], b[0])) + { // check if a in (cd) - if (isPointOnSegment(a[0], c[0], d[0])) { + if (isPointOnSegment(a[0], c[0], d[0])) + { return {{a, c}}; } // check b == c - if (MathLib::sqrDist2d(b,c) < eps) { + if (MathLib::sqrDist2d(b, c) < eps) + { return {{b}}; } // check if b in (cd) - if (isPointOnSegment(b[0], c[0], d[0])) { + if (isPointOnSegment(b[0], c[0], d[0])) + { return {{b, c}}; } // check d in (ab) - if (isPointOnSegment(d[0], a[0], b[0])) { + if (isPointOnSegment(d[0], a[0], b[0])) + { return {{c, d}}; } std::stringstream err; @@ -529,21 +542,26 @@ std::vector<MathLib::Point3d> lineSegmentIntersect2d( } // check if d in (ab) - if (isPointOnSegment(d[0], a[0], b[0])) { + if (isPointOnSegment(d[0], a[0], b[0])) + { // check if a in (cd) - if (isPointOnSegment(a[0], c[0], d[0])) { + if (isPointOnSegment(a[0], c[0], d[0])) + { return {{a, d}}; } // check if b==d - if (MathLib::sqrDist2d(b, d) < eps) { + if (MathLib::sqrDist2d(b, d) < eps) + { return {{b}}; } // check if b in (cd) - if (isPointOnSegment(b[0], c[0], d[0])) { + if (isPointOnSegment(b[0], c[0], d[0])) + { return {{b, d}}; } // d in (ab), b not in (cd): check c in (ab) - if (isPointOnSegment(c[0], a[0], b[0])) { + if (isPointOnSegment(c[0], a[0], b[0])) + { return {{c, d}}; } @@ -551,8 +569,8 @@ std::vector<MathLib::Point3d> lineSegmentIntersect2d( err.precision(std::numeric_limits<double>::digits10); err << ab << " x " << cd; OGS_FATAL( - "The case of parallel line segments ({:s}) " - "is not handled yet. Aborting.", + "The case of parallel line segments ({:s}) is not handled yet. " + "Aborting.", err.str()); } return std::vector<MathLib::Point3d>(); @@ -581,7 +599,8 @@ std::vector<MathLib::Point3d> lineSegmentIntersect2d( return false; }; - if (orient_abc == 0.0) { + if (orient_abc == 0.0) + { if (isCollinearPointOntoLineSegment(a, b, c)) { return {{c}}; @@ -589,7 +608,8 @@ std::vector<MathLib::Point3d> lineSegmentIntersect2d( return std::vector<MathLib::Point3d>(); } - if (orient_abd == 0.0) { + if (orient_abd == 0.0) + { if (isCollinearPointOntoLineSegment(a, b, d)) { return {{d}}; @@ -600,7 +620,9 @@ std::vector<MathLib::Point3d> lineSegmentIntersect2d( // check if the segment (ab) lies on the left or on the right of (cd) double const orient_cda(getOrientation(c, d, a)); double const orient_cdb(getOrientation(c, d, b)); - if ((orient_cda > 0 && orient_cdb > 0) || (orient_cda < 0 && orient_cdb < 0)) { + if ((orient_cda > 0 && orient_cdb > 0) || + (orient_cda < 0 && orient_cdb < 0)) + { return std::vector<MathLib::Point3d>(); } @@ -608,63 +630,64 @@ std::vector<MathLib::Point3d> lineSegmentIntersect2d( // linear equations will be invertible // solve the two linear equations (b-a, c-d) (t, s)^T = (c-a) simultaneously Eigen::Matrix2d mat; - mat(0,0) = b[0]-a[0]; - mat(0,1) = c[0]-d[0]; - mat(1,0) = b[1]-a[1]; - mat(1,1) = c[1]-d[1]; + mat(0, 0) = b[0] - a[0]; + mat(0, 1) = c[0] - d[0]; + mat(1, 0) = b[1] - a[1]; + mat(1, 1) = c[1] - d[1]; Eigen::Vector2d rhs{c[0] - a[0], c[1] - a[1]}; rhs = mat.partialPivLu().solve(rhs); - if (0 <= rhs[1] && rhs[1] <= 1.0) { - return { MathLib::Point3d{std::array<double,3>{{ - c[0]+rhs[1]*(d[0]-c[0]), c[1]+rhs[1]*(d[1]-c[1]), - c[2]+rhs[1]*(d[2]-c[2])}} } }; + if (0 <= rhs[1] && rhs[1] <= 1.0) + { + return {MathLib::Point3d{std::array<double, 3>{ + {c[0] + rhs[1] * (d[0] - c[0]), c[1] + rhs[1] * (d[1] - c[1]), + c[2] + rhs[1] * (d[2] - c[2])}}}}; } return std::vector<MathLib::Point3d>(); // parameter s not in the valid // range } -void sortSegments( - MathLib::Point3d const& seg_beg_pnt, - std::vector<GeoLib::LineSegment>& sub_segments) +void sortSegments(MathLib::Point3d const& seg_beg_pnt, + std::vector<GeoLib::LineSegment>& sub_segments) { double const eps(std::numeric_limits<double>::epsilon()); - auto findNextSegment = [&eps]( - MathLib::Point3d const& seg_beg_pnt, - std::vector<GeoLib::LineSegment>& sub_segments, - std::vector<GeoLib::LineSegment>::iterator& - sub_seg_it) { - if (sub_seg_it == sub_segments.end()) - { - return; - } - // find appropriate segment for the given segment begin point - auto act_beg_seg_it = std::find_if( - sub_seg_it, sub_segments.end(), - [&seg_beg_pnt, &eps](GeoLib::LineSegment const& seg) + auto findNextSegment = + [&eps](MathLib::Point3d const& seg_beg_pnt, + std::vector<GeoLib::LineSegment>& sub_segments, + std::vector<GeoLib::LineSegment>::iterator& sub_seg_it) { + if (sub_seg_it == sub_segments.end()) { - return MathLib::sqrDist(seg_beg_pnt, seg.getBeginPoint()) < eps || - MathLib::sqrDist(seg_beg_pnt, seg.getEndPoint()) < eps; - }); - if (act_beg_seg_it == sub_segments.end()) - { - return; - } - // if necessary correct orientation of segment, i.e. swap beg and end - if (MathLib::sqrDist(seg_beg_pnt, act_beg_seg_it->getEndPoint()) < - MathLib::sqrDist(seg_beg_pnt, act_beg_seg_it->getBeginPoint())) - { - std::swap(act_beg_seg_it->getBeginPoint(), - act_beg_seg_it->getEndPoint()); - } - assert(sub_seg_it != sub_segments.end()); - // exchange segments within the container - if (sub_seg_it != act_beg_seg_it) - { - std::swap(*sub_seg_it, *act_beg_seg_it); - } - }; + return; + } + // find appropriate segment for the given segment begin point + auto act_beg_seg_it = std::find_if( + sub_seg_it, sub_segments.end(), + [&seg_beg_pnt, &eps](GeoLib::LineSegment const& seg) { + return MathLib::sqrDist(seg_beg_pnt, seg.getBeginPoint()) < + eps || + MathLib::sqrDist(seg_beg_pnt, seg.getEndPoint()) < + eps; + }); + if (act_beg_seg_it == sub_segments.end()) + { + return; + } + // if necessary correct orientation of segment, i.e. swap beg and + // end + if (MathLib::sqrDist(seg_beg_pnt, act_beg_seg_it->getEndPoint()) < + MathLib::sqrDist(seg_beg_pnt, act_beg_seg_it->getBeginPoint())) + { + std::swap(act_beg_seg_it->getBeginPoint(), + act_beg_seg_it->getEndPoint()); + } + assert(sub_seg_it != sub_segments.end()); + // exchange segments within the container + if (sub_seg_it != act_beg_seg_it) + { + std::swap(*sub_seg_it, *act_beg_seg_it); + } + }; // find start segment auto seg_it = sub_segments.begin(); @@ -672,7 +695,7 @@ void sortSegments( while (seg_it != sub_segments.end()) { - MathLib::Point3d & new_seg_beg_pnt(seg_it->getEndPoint()); + MathLib::Point3d& new_seg_beg_pnt(seg_it->getEndPoint()); seg_it++; if (seg_it != sub_segments.end()) { @@ -686,10 +709,10 @@ Eigen::Matrix3d compute2DRotationMatrixToX(Eigen::Vector3d const& v) Eigen::Matrix3d rot_mat = Eigen::Matrix3d::Zero(); const double cos_theta = v[0]; const double sin_theta = v[1]; - rot_mat(0,0) = rot_mat(1,1) = cos_theta; - rot_mat(0,1) = sin_theta; - rot_mat(1,0) = -sin_theta; - rot_mat(2,2) = 1.0; + rot_mat(0, 0) = rot_mat(1, 1) = cos_theta; + rot_mat(0, 1) = sin_theta; + rot_mat(1, 0) = -sin_theta; + rot_mat(2, 2) = 1.0; return rot_mat; } @@ -733,4 +756,4 @@ Eigen::Matrix3d compute3DRotationMatrixToX(Eigen::Vector3d const& v) return rot_mat; } -} // end namespace GeoLib +} // end namespace GeoLib diff --git a/GeoLib/DuplicateGeometry.cpp b/GeoLib/DuplicateGeometry.cpp index 92313db2e49d88e07ade53a540e07202e080f14f..45d40cb609e7a1ba94447931998457eea57f18cf 100644 --- a/GeoLib/DuplicateGeometry.cpp +++ b/GeoLib/DuplicateGeometry.cpp @@ -12,15 +12,14 @@ #include <map> #include <utility> -#include "BaseLib/Logging.h" +#include "BaseLib/Logging.h" #include "GeoLib/GEOObjects.h" #include "GeoLib/Point.h" #include "GeoLib/Polyline.h" #include "GeoLib/Surface.h" #include "GeoLib/Triangle.h" - namespace GeoLib { DuplicateGeometry::DuplicateGeometry(GeoLib::GEOObjects& geo_objects, @@ -33,7 +32,8 @@ DuplicateGeometry::DuplicateGeometry(GeoLib::GEOObjects& geo_objects, void DuplicateGeometry::duplicate(std::string const& input_name) { - std::vector<GeoLib::Point*> const*const pnts (_geo_objects.getPointVec(input_name)); + std::vector<GeoLib::Point*> const* const pnts( + _geo_objects.getPointVec(input_name)); if (pnts == nullptr) { ERR("Geometry '{:s}' not found.", input_name); @@ -42,7 +42,8 @@ void DuplicateGeometry::duplicate(std::string const& input_name) auto new_pnts = std::make_unique<std::vector<GeoLib::Point*>>(); new_pnts->reserve(pnts->size()); - std::transform(pnts->cbegin(), pnts->cend(), std::back_inserter(*new_pnts), + std::transform( + pnts->cbegin(), pnts->cend(), std::back_inserter(*new_pnts), [](GeoLib::Point* point) { return new GeoLib::Point(*point); }); auto pnt_name_id_map = std::make_unique<std::map<std::string, std::size_t>>( _geo_objects.getPointVecObj(input_name)->getNameIDMapBegin(), @@ -50,7 +51,8 @@ void DuplicateGeometry::duplicate(std::string const& input_name) _geo_objects.addPointVec(std::move(new_pnts), _output_name, std::move(pnt_name_id_map)); - std::vector<GeoLib::Polyline*> const* plys (_geo_objects.getPolylineVec(input_name)); + std::vector<GeoLib::Polyline*> const* plys( + _geo_objects.getPolylineVec(input_name)); if (plys) { auto new_plys = copyPolylinesVector(*plys); @@ -62,7 +64,8 @@ void DuplicateGeometry::duplicate(std::string const& input_name) std::move(ply_name_id_map)); } - std::vector<GeoLib::Surface*> const* sfcs (_geo_objects.getSurfaceVec(input_name)); + std::vector<GeoLib::Surface*> const* sfcs( + _geo_objects.getSurfaceVec(input_name)); if (sfcs) { auto new_sfcs = copySurfacesVector(*sfcs); @@ -75,21 +78,23 @@ void DuplicateGeometry::duplicate(std::string const& input_name) } } -std::unique_ptr<std::vector<GeoLib::Polyline*>> DuplicateGeometry::copyPolylinesVector( +std::unique_ptr<std::vector<GeoLib::Polyline*>> +DuplicateGeometry::copyPolylinesVector( std::vector<GeoLib::Polyline*> const& polylines) const { std::size_t const n_plys = polylines.size(); auto new_lines = std::make_unique<std::vector<GeoLib::Polyline*>>(n_plys, nullptr); - for (std::size_t i=0; i<n_plys; ++i) + for (std::size_t i = 0; i < n_plys; ++i) { if (polylines[i] == nullptr) { continue; } - (*new_lines)[i] = new GeoLib::Polyline(*_geo_objects.getPointVec(_output_name)); - std::size_t const nLinePnts (polylines[i]->getNumberOfPoints()); + (*new_lines)[i] = + new GeoLib::Polyline(*_geo_objects.getPointVec(_output_name)); + std::size_t const nLinePnts(polylines[i]->getNumberOfPoints()); for (std::size_t j = 0; j < nLinePnts; ++j) { (*new_lines)[i]->addPoint(polylines[i]->getPointID(j)); @@ -105,20 +110,22 @@ std::unique_ptr<std::vector<Surface*>> DuplicateGeometry::copySurfacesVector( auto new_surfaces = std::make_unique<std::vector<GeoLib::Surface*>>(n_sfc, nullptr); - for (std::size_t i=0; i<n_sfc; ++i) + for (std::size_t i = 0; i < n_sfc; ++i) { if (surfaces[i] == nullptr) { continue; } - (*new_surfaces)[i] = new GeoLib::Surface(*_geo_objects.getPointVec(_output_name)); + (*new_surfaces)[i] = + new GeoLib::Surface(*_geo_objects.getPointVec(_output_name)); - std::size_t const n_tris (surfaces[i]->getNumberOfTriangles()); - for (std::size_t j=0; j<n_tris; ++j) + std::size_t const n_tris(surfaces[i]->getNumberOfTriangles()); + for (std::size_t j = 0; j < n_tris; ++j) { GeoLib::Triangle const* t = (*surfaces[i])[j]; - (*new_surfaces)[i]->addTriangle( - t->getPoint(0)->getID(), t->getPoint(1)->getID(), t->getPoint(2)->getID()); + (*new_surfaces)[i]->addTriangle(t->getPoint(0)->getID(), + t->getPoint(1)->getID(), + t->getPoint(2)->getID()); } } return new_surfaces; @@ -126,17 +133,20 @@ std::unique_ptr<std::vector<Surface*>> DuplicateGeometry::copySurfacesVector( std::vector<GeoLib::Point*>& DuplicateGeometry::getPointVectorCopy() { - return const_cast<std::vector<GeoLib::Point*>&>(*_geo_objects.getPointVec(_output_name)); + return const_cast<std::vector<GeoLib::Point*>&>( + *_geo_objects.getPointVec(_output_name)); } std::vector<GeoLib::Polyline*>& DuplicateGeometry::getPolylineVectorCopy() { - return const_cast<std::vector<GeoLib::Polyline*>&>(*_geo_objects.getPolylineVec(_output_name)); + return const_cast<std::vector<GeoLib::Polyline*>&>( + *_geo_objects.getPolylineVec(_output_name)); } std::vector<GeoLib::Surface*>& DuplicateGeometry::getSurfaceVectorCopy() { - return const_cast<std::vector<GeoLib::Surface*>&>(*_geo_objects.getSurfaceVec(_output_name)); + return const_cast<std::vector<GeoLib::Surface*>&>( + *_geo_objects.getSurfaceVec(_output_name)); } } // namespace GeoLib diff --git a/GeoLib/GEOObjects.cpp b/GeoLib/GEOObjects.cpp index d45a6eb65a5351fbac3d355e165ce6d4eb2ba524..d831f6b1a05ac6b839062fe439ceaaa97f7a8020 100644 --- a/GeoLib/GEOObjects.cpp +++ b/GeoLib/GEOObjects.cpp @@ -15,9 +15,9 @@ #include "GEOObjects.h" #include <fstream> -#include "BaseLib/StringTools.h" -#include "BaseLib/Logging.h" +#include "BaseLib/Logging.h" +#include "BaseLib/StringTools.h" #include "Triangle.h" namespace GeoLib @@ -50,8 +50,10 @@ void GEOObjects::addPointVec(std::unique_ptr<std::vector<Point*>> points, double eps) { isUniquePointVecName(name); - if (!points || points->empty()) { - DBUG("GEOObjects::addPointVec(): Failed to create PointVec, because " + if (!points || points->empty()) + { + DBUG( + "GEOObjects::addPointVec(): Failed to create PointVec, because " "there aren't any points in the given vector."); return; } @@ -61,7 +63,8 @@ void GEOObjects::addPointVec(std::unique_ptr<std::vector<Point*>> points, _callbacks->addPointVec(name); } -const std::vector<Point*>* GEOObjects::getPointVec(const std::string &name) const +const std::vector<Point*>* GEOObjects::getPointVec( + const std::string& name) const { std::size_t const idx = this->exists(name); if (idx != std::numeric_limits<std::size_t>::max()) @@ -73,7 +76,7 @@ const std::vector<Point*>* GEOObjects::getPointVec(const std::string &name) cons return nullptr; } -const PointVec* GEOObjects::getPointVecObj(const std::string &name) const +const PointVec* GEOObjects::getPointVecObj(const std::string& name) const { std::size_t const idx = this->exists(name); if (idx != std::numeric_limits<std::size_t>::max()) @@ -88,9 +91,11 @@ const PointVec* GEOObjects::getPointVecObj(const std::string &name) const bool GEOObjects::removePointVec(std::string const& name) { - if (isPntVecUsed (name)) + if (isPntVecUsed(name)) { - DBUG("GEOObjects::removePointVec() - There are still Polylines or Surfaces depending on these points."); + DBUG( + "GEOObjects::removePointVec() - There are still Polylines or " + "Surfaces depending on these points."); return false; } @@ -113,7 +118,8 @@ void GEOObjects::addStationVec(std::unique_ptr<std::vector<Point*>> stations, std::string& name) { isUniquePointVecName(name); - _pnt_vecs.push_back(new PointVec(name, std::move(stations), nullptr, PointVec::PointType::STATION)); + _pnt_vecs.push_back(new PointVec(name, std::move(stations), nullptr, + PointVec::PointType::STATION)); _callbacks->addStationVec(name); } @@ -146,7 +152,7 @@ void GEOObjects::addPolylineVec( if ((*it)->getNumberOfPoints() < 2) { auto it_erase(it); - it = lines->erase (it_erase); + it = lines->erase(it_erase); } else { @@ -168,8 +174,8 @@ bool GEOObjects::appendPolylineVec(const std::vector<Polyline*>& polylines, const std::string& name) { // search vector - std::size_t idx (0); - bool nfound (true); + std::size_t idx(0); + bool nfound(true); for (idx = 0; idx < _ply_vecs.size() && nfound; idx++) { if (_ply_vecs[idx]->getName() == name) @@ -181,7 +187,7 @@ bool GEOObjects::appendPolylineVec(const std::vector<Polyline*>& polylines, if (!nfound) { idx--; - std::size_t n_plys (polylines.size()); + std::size_t n_plys(polylines.size()); // append lines for (std::size_t k(0); k < n_plys; k++) { @@ -194,9 +200,10 @@ bool GEOObjects::appendPolylineVec(const std::vector<Polyline*>& polylines, return false; } -const std::vector<Polyline*>* GEOObjects::getPolylineVec(const std::string &name) const +const std::vector<Polyline*>* GEOObjects::getPolylineVec( + const std::string& name) const { - std::size_t size (_ply_vecs.size()); + std::size_t size(_ply_vecs.size()); for (std::size_t i = 0; i < size; i++) { if (_ply_vecs[i]->getName() == name) @@ -210,9 +217,9 @@ const std::vector<Polyline*>* GEOObjects::getPolylineVec(const std::string &name return nullptr; } -const PolylineVec* GEOObjects::getPolylineVecObj(const std::string &name) const +const PolylineVec* GEOObjects::getPolylineVecObj(const std::string& name) const { - std::size_t size (_ply_vecs.size()); + std::size_t size(_ply_vecs.size()); for (std::size_t i = 0; i < size; i++) { if (_ply_vecs[i]->getName() == name) @@ -259,8 +266,8 @@ bool GEOObjects::appendSurfaceVec(const std::vector<Surface*>& surfaces, const std::string& name) { // search vector - std::size_t idx (0); - bool nfound (true); + std::size_t idx(0); + bool nfound(true); for (idx = 0; idx < _sfc_vecs.size() && nfound; idx++) { if (_sfc_vecs[idx]->getName() == name) @@ -272,7 +279,7 @@ bool GEOObjects::appendSurfaceVec(const std::vector<Surface*>& surfaces, if (!nfound) { idx--; - std::size_t n_sfcs (surfaces.size()); + std::size_t n_sfcs(surfaces.size()); // append surfaces for (std::size_t k(0); k < n_sfcs; k++) { @@ -290,9 +297,10 @@ bool GEOObjects::appendSurfaceVec(const std::vector<Surface*>& surfaces, return false; } -const std::vector<Surface*>* GEOObjects::getSurfaceVec(const std::string &name) const +const std::vector<Surface*>* GEOObjects::getSurfaceVec( + const std::string& name) const { - std::size_t size (_sfc_vecs.size()); + std::size_t size(_sfc_vecs.size()); for (std::size_t i = 0; i < size; i++) { if (_sfc_vecs[i]->getName() == name) @@ -305,7 +313,7 @@ const std::vector<Surface*>* GEOObjects::getSurfaceVec(const std::string &name) return nullptr; } -bool GEOObjects::removeSurfaceVec(const std::string &name) +bool GEOObjects::removeSurfaceVec(const std::string& name) { _callbacks->removeSurfaceVec(name); for (auto it(_sfc_vecs.begin()); it != _sfc_vecs.end(); ++it) @@ -313,7 +321,7 @@ bool GEOObjects::removeSurfaceVec(const std::string &name) if ((*it)->getName() == name) { delete *it; - _sfc_vecs.erase (it); + _sfc_vecs.erase(it); return true; } } @@ -323,9 +331,9 @@ bool GEOObjects::removeSurfaceVec(const std::string &name) return false; } -const SurfaceVec* GEOObjects::getSurfaceVecObj(const std::string &name) const +const SurfaceVec* GEOObjects::getSurfaceVecObj(const std::string& name) const { - std::size_t size (_sfc_vecs.size()); + std::size_t size(_sfc_vecs.size()); for (std::size_t i = 0; i < size; i++) { if (_sfc_vecs[i]->getName() == name) @@ -351,7 +359,7 @@ bool GEOObjects::isUniquePointVecName(std::string& name) const return true; } -bool GEOObjects::isPntVecUsed (const std::string &name) const +bool GEOObjects::isPntVecUsed(const std::string& name) const { // search dependent data structures (Polyline) for (auto polyline : _ply_vecs) @@ -407,10 +415,12 @@ std::string GEOObjects::getElementNameByID(const std::string& geometry_name, this->getPointVecObj(geometry_name)->getNameOfElementByID(id, name); break; case GeoLib::GEOTYPE::POLYLINE: - this->getPolylineVecObj(geometry_name)->getNameOfElementByID(id, name); + this->getPolylineVecObj(geometry_name) + ->getNameOfElementByID(id, name); break; case GeoLib::GEOTYPE::SURFACE: - this->getSurfaceVecObj(geometry_name)->getNameOfElementByID(id, name); + this->getSurfaceVecObj(geometry_name) + ->getNameOfElementByID(id, name); } return name; } @@ -439,8 +449,9 @@ int GEOObjects::mergeGeometries(std::vector<std::string> const& geo_names, return 0; } -bool GEOObjects::mergePoints(std::vector<std::string> const & geo_names, - std::string & merged_geo_name, std::vector<std::size_t> &pnt_offsets) +bool GEOObjects::mergePoints(std::vector<std::string> const& geo_names, + std::string& merged_geo_name, + std::vector<std::size_t>& pnt_offsets) { const std::size_t n_geo_names(geo_names.size()); @@ -448,33 +459,40 @@ bool GEOObjects::mergePoints(std::vector<std::string> const & geo_names, auto merged_pnt_names = std::make_unique<std::map<std::string, std::size_t>>(); - for (std::size_t j(0); j < n_geo_names; ++j) { - GeoLib::PointVec const*const pnt_vec(this->getPointVecObj(geo_names[j])); + for (std::size_t j(0); j < n_geo_names; ++j) + { + GeoLib::PointVec const* const pnt_vec( + this->getPointVecObj(geo_names[j])); if (pnt_vec == nullptr) { continue; } const std::vector<GeoLib::Point*>* pnts(pnt_vec->getVector()); - if (pnts == nullptr) { + if (pnts == nullptr) + { return false; } // do not consider stations - if (dynamic_cast<GeoLib::Station*>((*pnts)[0])) { + if (dynamic_cast<GeoLib::Station*>((*pnts)[0])) + { continue; } std::size_t const n_pnts(pnts->size()); - for (std::size_t k(0); k < n_pnts; ++k) { + for (std::size_t k(0); k < n_pnts; ++k) + { merged_points->push_back( - new GeoLib::Point(*(*pnts)[k], pnt_offsets[j]+k)); + new GeoLib::Point(*(*pnts)[k], pnt_offsets[j] + k)); std::string const& item_name(pnt_vec->getItemNameByID(k)); - if (! item_name.empty()) { + if (!item_name.empty()) + { merged_pnt_names->insert( std::make_pair(item_name, pnt_offsets[j] + k)); } } - if (n_geo_names - 1 > j) { + if (n_geo_names - 1 > j) + { pnt_offsets[j + 1] = n_pnts + pnt_offsets[j]; } } @@ -495,34 +513,49 @@ void GEOObjects::mergePolylines(std::vector<std::string> const& geo_names, auto merged_ply_names = std::make_unique<std::map<std::string, std::size_t>>(); - std::vector<GeoLib::Point*> const* merged_points(this->getPointVecObj(merged_geo_name)->getVector()); - std::vector<std::size_t> const& id_map (this->getPointVecObj(merged_geo_name)->getIDMap ()); + std::vector<GeoLib::Point*> const* merged_points( + this->getPointVecObj(merged_geo_name)->getVector()); + std::vector<std::size_t> const& id_map( + this->getPointVecObj(merged_geo_name)->getIDMap()); - for (std::size_t j(0); j < n_geo_names; j++) { - const std::vector<GeoLib::Polyline*>* plys (this->getPolylineVec(geo_names[j])); - if (plys) { + for (std::size_t j(0); j < n_geo_names; j++) + { + const std::vector<GeoLib::Polyline*>* plys( + this->getPolylineVec(geo_names[j])); + if (plys) + { std::string tmp_name; - for (std::size_t k(0); k < plys->size(); k++) { + for (std::size_t k(0); k < plys->size(); k++) + { auto* kth_ply_new(new GeoLib::Polyline(*merged_points)); - GeoLib::Polyline const* const kth_ply_old ((*plys)[k]); - const std::size_t size_of_kth_ply (kth_ply_old->getNumberOfPoints()); - // copy point ids from old ply to new ply (considering the offset) - for (std::size_t i(0); i < size_of_kth_ply; i++) { - kth_ply_new->addPoint (id_map[pnt_offsets[j] + - kth_ply_old->getPointID(i)]); + GeoLib::Polyline const* const kth_ply_old((*plys)[k]); + const std::size_t size_of_kth_ply( + kth_ply_old->getNumberOfPoints()); + // copy point ids from old ply to new ply (considering the + // offset) + for (std::size_t i(0); i < size_of_kth_ply; i++) + { + kth_ply_new->addPoint( + id_map[pnt_offsets[j] + kth_ply_old->getPointID(i)]); } - merged_polylines->push_back (kth_ply_new); - if (this->getPolylineVecObj(geo_names[j])->getNameOfElementByID(k, tmp_name)) { - merged_ply_names->insert(std::pair<std::string, std::size_t>(tmp_name, ply_offsets[j] + k)); + merged_polylines->push_back(kth_ply_new); + if (this->getPolylineVecObj(geo_names[j]) + ->getNameOfElementByID(k, tmp_name)) + { + merged_ply_names->insert( + std::pair<std::string, std::size_t>( + tmp_name, ply_offsets[j] + k)); } } - if (n_geo_names - 1 > j) { + if (n_geo_names - 1 > j) + { ply_offsets[j + 1] = plys->size() + ply_offsets[j]; } } } - if (! merged_polylines->empty()) { + if (!merged_polylines->empty()) + { this->addPolylineVec(std::move(merged_polylines), merged_geo_name, std::move(merged_ply_names)); } @@ -532,42 +565,56 @@ void GEOObjects::mergeSurfaces(std::vector<std::string> const& geo_names, std::string const& merged_geo_name, std::vector<std::size_t> const& pnt_offsets) { - std::vector<GeoLib::Point*> const* merged_points(this->getPointVecObj(merged_geo_name)->getVector()); - std::vector<std::size_t> const& id_map (this->getPointVecObj(merged_geo_name)->getIDMap ()); + std::vector<GeoLib::Point*> const* merged_points( + this->getPointVecObj(merged_geo_name)->getVector()); + std::vector<std::size_t> const& id_map( + this->getPointVecObj(merged_geo_name)->getIDMap()); const std::size_t n_geo_names(geo_names.size()); std::vector<std::size_t> sfc_offsets(n_geo_names, 0); auto merged_sfcs = std::make_unique<std::vector<GeoLib::Surface*>>(); auto merged_sfc_names = std::make_unique<std::map<std::string, std::size_t>>(); - for (std::size_t j(0); j < n_geo_names; j++) { - const std::vector<GeoLib::Surface*>* sfcs (this->getSurfaceVec(geo_names[j])); - if (sfcs) { + for (std::size_t j(0); j < n_geo_names; j++) + { + const std::vector<GeoLib::Surface*>* sfcs( + this->getSurfaceVec(geo_names[j])); + if (sfcs) + { std::string tmp_name; - for (std::size_t k(0); k < sfcs->size(); k++) { + for (std::size_t k(0); k < sfcs->size(); k++) + { auto* kth_sfc_new(new GeoLib::Surface(*merged_points)); - GeoLib::Surface const* const kth_sfc_old ((*sfcs)[k]); - const std::size_t size_of_kth_sfc (kth_sfc_old->getNumberOfTriangles()); + GeoLib::Surface const* const kth_sfc_old((*sfcs)[k]); + const std::size_t size_of_kth_sfc( + kth_sfc_old->getNumberOfTriangles()); // clone surface elements using new ids - for (std::size_t i(0); i < size_of_kth_sfc; i++) { - const GeoLib::Triangle* tri ((*kth_sfc_old)[i]); - const std::size_t id0 (id_map[pnt_offsets[j] + (*tri)[0]]); - const std::size_t id1 (id_map[pnt_offsets[j] + (*tri)[1]]); - const std::size_t id2 (id_map[pnt_offsets[j] + (*tri)[2]]); - kth_sfc_new->addTriangle (id0, id1, id2); + for (std::size_t i(0); i < size_of_kth_sfc; i++) + { + const GeoLib::Triangle* tri((*kth_sfc_old)[i]); + const std::size_t id0(id_map[pnt_offsets[j] + (*tri)[0]]); + const std::size_t id1(id_map[pnt_offsets[j] + (*tri)[1]]); + const std::size_t id2(id_map[pnt_offsets[j] + (*tri)[2]]); + kth_sfc_new->addTriangle(id0, id1, id2); } - merged_sfcs->push_back (kth_sfc_new); - - if (this->getSurfaceVecObj(geo_names[j])->getNameOfElementByID(k, tmp_name)) { - merged_sfc_names->insert(std::pair<std::string, std::size_t>(tmp_name, sfc_offsets[j] + k)); + merged_sfcs->push_back(kth_sfc_new); + + if (this->getSurfaceVecObj(geo_names[j]) + ->getNameOfElementByID(k, tmp_name)) + { + merged_sfc_names->insert( + std::pair<std::string, std::size_t>( + tmp_name, sfc_offsets[j] + k)); } } - if (n_geo_names - 1 > j) { + if (n_geo_names - 1 > j) + { sfc_offsets[j + 1] = sfcs->size() + sfc_offsets[j]; } } } - if (! merged_sfcs->empty()) { + if (!merged_sfcs->empty()) + { this->addSurfaceVec(std::move(merged_sfcs), merged_geo_name, std::move(merged_sfc_names)); } @@ -692,44 +739,49 @@ const GeoLib::GeoObject* GEOObjects::getGeoObject( GeoLib::GEOTYPE type, const std::string& geo_obj_name) const { - GeoLib::GeoObject *geo_obj(nullptr); - switch (type) { - case GeoLib::GEOTYPE::POINT: { - GeoLib::PointVec const* pnt_vec(getPointVecObj(geo_name)); - if (pnt_vec) + GeoLib::GeoObject* geo_obj(nullptr); + switch (type) + { + case GeoLib::GEOTYPE::POINT: { - geo_obj = const_cast<GeoLib::GeoObject*>( - dynamic_cast<GeoLib::GeoObject const*>( - pnt_vec->getElementByName(geo_obj_name))); + GeoLib::PointVec const* pnt_vec(getPointVecObj(geo_name)); + if (pnt_vec) + { + geo_obj = const_cast<GeoLib::GeoObject*>( + dynamic_cast<GeoLib::GeoObject const*>( + pnt_vec->getElementByName(geo_obj_name))); + } + break; } - break; - } - case GeoLib::GEOTYPE::POLYLINE: { - GeoLib::PolylineVec const* ply_vec(getPolylineVecObj(geo_name)); - if (ply_vec) + case GeoLib::GEOTYPE::POLYLINE: { - geo_obj = const_cast<GeoLib::GeoObject*>( - dynamic_cast<GeoLib::GeoObject const*>( - ply_vec->getElementByName(geo_obj_name))); + GeoLib::PolylineVec const* ply_vec(getPolylineVecObj(geo_name)); + if (ply_vec) + { + geo_obj = const_cast<GeoLib::GeoObject*>( + dynamic_cast<GeoLib::GeoObject const*>( + ply_vec->getElementByName(geo_obj_name))); + } + break; } - break; - } - case GeoLib::GEOTYPE::SURFACE: { - GeoLib::SurfaceVec const* sfc_vec(getSurfaceVecObj(geo_name)); - if (sfc_vec) + case GeoLib::GEOTYPE::SURFACE: { - geo_obj = const_cast<GeoLib::GeoObject*>( - dynamic_cast<GeoLib::GeoObject const*>( - sfc_vec->getElementByName(geo_obj_name))); + GeoLib::SurfaceVec const* sfc_vec(getSurfaceVecObj(geo_name)); + if (sfc_vec) + { + geo_obj = const_cast<GeoLib::GeoObject*>( + dynamic_cast<GeoLib::GeoObject const*>( + sfc_vec->getElementByName(geo_obj_name))); + } + break; } - break; - } - default: - ERR("GEOObjects::getGeoObject(): geometric type not handled."); - return nullptr; + default: + ERR("GEOObjects::getGeoObject(): geometric type not handled."); + return nullptr; }; - if (!geo_obj) { + if (!geo_obj) + { DBUG( "GEOObjects::getGeoObject(): Could not find {:s} '{:s}' in " "geometry.", @@ -740,12 +792,10 @@ const GeoLib::GeoObject* GEOObjects::getGeoObject( } GeoLib::GeoObject const* GEOObjects::getGeoObject( - const std::string &geo_name, - const std::string &geo_obj_name) const + const std::string& geo_name, const std::string& geo_obj_name) const { GeoLib::GeoObject const* geo_obj( - getGeoObject(geo_name, GeoLib::GEOTYPE::POINT, geo_obj_name) - ); + getGeoObject(geo_name, GeoLib::GEOTYPE::POINT, geo_obj_name)); if (!geo_obj) { @@ -759,7 +809,8 @@ GeoLib::GeoObject const* GEOObjects::getGeoObject( getGeoObject(geo_name, GeoLib::GEOTYPE::SURFACE, geo_obj_name); } - if (!geo_obj) { + if (!geo_obj) + { DBUG( "GEOObjects::getGeoObject(): Could not find '{:s}' in geometry " "{:s}.", @@ -768,9 +819,9 @@ GeoLib::GeoObject const* GEOObjects::getGeoObject( return geo_obj; } -std::size_t GEOObjects::exists(const std::string &geometry_name) const +std::size_t GEOObjects::exists(const std::string& geometry_name) const { - std::size_t const size (_pnt_vecs.size()); + std::size_t const size(_pnt_vecs.size()); for (std::size_t i = 0; i < size; i++) { if (_pnt_vecs[i]->getName() == geometry_name) @@ -779,7 +830,8 @@ std::size_t GEOObjects::exists(const std::string &geometry_name) const } } - // HACK for enabling conversion of files without loading the associated geometry + // HACK for enabling conversion of files without loading the associated + // geometry if (size > 0 && _pnt_vecs[0]->getName() == "conversionTestRun#1") { return 1; diff --git a/GeoLib/GeoType.cpp b/GeoLib/GeoType.cpp index 21d82576304c597a6ed28a50f54ac1378f8f9f93..2d4bb326c056d61ac033000464e1164fa29c6f56 100644 --- a/GeoLib/GeoType.cpp +++ b/GeoLib/GeoType.cpp @@ -20,14 +20,16 @@ namespace GeoLib { - -std::string convertGeoTypeToString (GEOTYPE geo_type) +std::string convertGeoTypeToString(GEOTYPE geo_type) { switch (geo_type) { - case GEOTYPE::POINT: return "POINT"; - case GEOTYPE::POLYLINE: return "POLYLINE"; - case GEOTYPE::SURFACE: return "SURFACE"; + case GEOTYPE::POINT: + return "POINT"; + case GEOTYPE::POLYLINE: + return "POLYLINE"; + case GEOTYPE::SURFACE: + return "SURFACE"; } // Cannot happen, because switch covers all cases. @@ -35,4 +37,4 @@ std::string convertGeoTypeToString (GEOTYPE geo_type) OGS_FATAL("convertGeoTypeToString(): Given geo type is not supported"); } -} // end namespace GeoLib +} // end namespace GeoLib diff --git a/GeoLib/IO/TINInterface.cpp b/GeoLib/IO/TINInterface.cpp index 11535e56263d4107d867431e6a842b113579decb..dd89c6952889cb88d1dc91092471703902d3df4a 100644 --- a/GeoLib/IO/TINInterface.cpp +++ b/GeoLib/IO/TINInterface.cpp @@ -11,29 +11,26 @@ #include <fstream> #include <limits> -#include "BaseLib/Logging.h" - #include "BaseLib/FileTools.h" +#include "BaseLib/Logging.h" #include "BaseLib/StringTools.h" - #include "GeoLib/AnalyticalGeometry.h" #include "GeoLib/Surface.h" #include "GeoLib/Triangle.h" - #include "MathLib/GeometricBasics.h" namespace GeoLib { namespace IO { - GeoLib::Surface* TINInterface::readTIN(std::string const& fname, - GeoLib::PointVec &pnt_vec, - std::vector<std::string>* errors) + GeoLib::PointVec& pnt_vec, + std::vector<std::string>* errors) { // open file std::ifstream in(fname.c_str()); - if (!in) { + if (!in) + { WARN("readTIN(): could not open stream from {:s}.", fname); if (errors) { @@ -59,13 +56,15 @@ GeoLib::Surface* TINInterface::readTIN(std::string const& fname, // parse line std::stringstream input(line); // read id - if (!(input >> id)) { + if (!(input >> id)) + { in.close(); delete sfc; return nullptr; } // read first point - if (!(input >> p0[0] >> p0[1] >> p0[2])) { + if (!(input >> p0[0] >> p0[1] >> p0[2])) + { ERR("Could not read coords of 1st point of triangle {:d}.", id); if (errors) { @@ -80,7 +79,8 @@ GeoLib::Surface* TINInterface::readTIN(std::string const& fname, return nullptr; } // read second point - if (!(input >> p1[0] >> p1[1] >> p1[2])) { + if (!(input >> p1[0] >> p1[1] >> p1[2])) + { ERR("Could not read coords of 2nd point of triangle {:d}.", id); if (errors) { @@ -95,7 +95,8 @@ GeoLib::Surface* TINInterface::readTIN(std::string const& fname, return nullptr; } // read third point - if (!(input >> p2[0] >> p2[1] >> p2[2])) { + if (!(input >> p2[0] >> p2[1] >> p2[2])) + { ERR("Could not read coords of 3rd point of triangle {:d}.", id); if (errors) { @@ -112,7 +113,8 @@ GeoLib::Surface* TINInterface::readTIN(std::string const& fname, // check area of triangle double const d_eps(std::numeric_limits<double>::epsilon()); - if (MathLib::calcTriangleArea(p0, p1, p2) < d_eps) { + if (MathLib::calcTriangleArea(p0, p1, p2) < d_eps) + { ERR("readTIN: Triangle {:d} has zero area.", id); if (errors) { @@ -127,9 +129,12 @@ GeoLib::Surface* TINInterface::readTIN(std::string const& fname, // determine size pnt_vec to insert the correct ids std::size_t const s(pnt_vec.getVector()->size()); - std::size_t const pnt_pos_0(pnt_vec.push_back(new GeoLib::Point(p0, s))); - std::size_t const pnt_pos_1(pnt_vec.push_back(new GeoLib::Point(p1, s+1))); - std::size_t const pnt_pos_2(pnt_vec.push_back(new GeoLib::Point(p2, s+2))); + std::size_t const pnt_pos_0( + pnt_vec.push_back(new GeoLib::Point(p0, s))); + std::size_t const pnt_pos_1( + pnt_vec.push_back(new GeoLib::Point(p1, s + 1))); + std::size_t const pnt_pos_2( + pnt_vec.push_back(new GeoLib::Point(p2, s + 2))); // create new Triangle if (pnt_pos_0 != std::numeric_limits<std::size_t>::max() && pnt_pos_1 != std::numeric_limits<std::size_t>::max() && @@ -139,7 +144,8 @@ GeoLib::Surface* TINInterface::readTIN(std::string const& fname, } } - if (sfc->getNumberOfTriangles() == 0) { + if (sfc->getNumberOfTriangles() == 0) + { WARN("readTIN(): No triangle found.", fname); if (errors) { @@ -152,20 +158,24 @@ GeoLib::Surface* TINInterface::readTIN(std::string const& fname, return sfc; } -void TINInterface::writeSurfaceAsTIN(GeoLib::Surface const& surface, std::string const& file_name) +void TINInterface::writeSurfaceAsTIN(GeoLib::Surface const& surface, + std::string const& file_name) { - std::ofstream os (file_name.c_str()); - if (!os) { + std::ofstream os(file_name.c_str()); + if (!os) + { WARN("writeSurfaceAsTIN(): could not open stream to {:s}.", file_name); return; } os.precision(std::numeric_limits<double>::digits10); - const std::size_t n_tris (surface.getNumberOfTriangles()); - for (std::size_t l(0); l < n_tris; l++) { - GeoLib::Triangle const& tri (*(surface[l])); - os << l << " " << *(tri.getPoint(0)) << " " << *(tri.getPoint(1)) << " " << *(tri.getPoint(2)) << "\n"; + const std::size_t n_tris(surface.getNumberOfTriangles()); + for (std::size_t l(0); l < n_tris; l++) + { + GeoLib::Triangle const& tri(*(surface[l])); + os << l << " " << *(tri.getPoint(0)) << " " << *(tri.getPoint(1)) << " " + << *(tri.getPoint(2)) << "\n"; } os.close(); } -} // end namespace IO -} // end namespace GeoLib +} // end namespace IO +} // end namespace GeoLib diff --git a/GeoLib/IO/XmlIO/Boost/BoostXmlGmlInterface.cpp b/GeoLib/IO/XmlIO/Boost/BoostXmlGmlInterface.cpp index 93c4c7ccd3153d90d87b3c7a055c2c770f3ec09b..e39cdc06254983fbf04944df3f40da6144b15615 100644 --- a/GeoLib/IO/XmlIO/Boost/BoostXmlGmlInterface.cpp +++ b/GeoLib/IO/XmlIO/Boost/BoostXmlGmlInterface.cpp @@ -15,10 +15,10 @@ #include "BoostXmlGmlInterface.h" #include <boost/property_tree/xml_parser.hpp> -#include "BaseLib/Logging.h" #include "BaseLib/Algorithm.h" #include "BaseLib/ConfigTreeUtil.h" +#include "BaseLib/Logging.h" #include "GeoLib/GEOObjects.h" #include "GeoLib/Point.h" #include "GeoLib/PointVec.h" @@ -30,12 +30,12 @@ namespace GeoLib { namespace IO { +BoostXmlGmlInterface::BoostXmlGmlInterface(GeoLib::GEOObjects& geo_objs) + : _geo_objects(geo_objs) +{ +} -BoostXmlGmlInterface::BoostXmlGmlInterface(GeoLib::GEOObjects& geo_objs) : - _geo_objects(geo_objs) -{} - -bool BoostXmlGmlInterface::readFile(const std::string &fname) +bool BoostXmlGmlInterface::readFile(const std::string& fname) { //! \todo Reading geometries is always strict. auto doc = BaseLib::makeConfigTree(fname, true, "OpenGeoSysGLI"); @@ -89,12 +89,14 @@ bool BoostXmlGmlInterface::readFile(const std::string &fname) *sfc_names); } - if (!polylines->empty()) { + if (!polylines->empty()) + { _geo_objects.addPolylineVec(std::move(polylines), geo_name, std::move(ply_names)); } - if (!surfaces->empty()) { + if (!surfaces->empty()) + { _geo_objects.addSurfaceVec(std::move(surfaces), geo_name, std::move(sfc_names)); } @@ -102,9 +104,10 @@ bool BoostXmlGmlInterface::readFile(const std::string &fname) return true; } -void BoostXmlGmlInterface::readPoints(BaseLib::ConfigTree const& pointsRoot, - std::vector<GeoLib::Point*>& points, - std::map<std::string, std::size_t>& pnt_names ) +void BoostXmlGmlInterface::readPoints( + BaseLib::ConfigTree const& pointsRoot, + std::vector<GeoLib::Point*>& points, + std::map<std::string, std::size_t>& pnt_names) { //! \ogs_file_param{gml__points__point} for (auto const pt : pointsRoot.getConfigParameterList("point")) @@ -112,26 +115,28 @@ void BoostXmlGmlInterface::readPoints(BaseLib::ConfigTree const& pointsRoot, //! \ogs_file_attr{gml__points__point__id} auto const p_id = pt.getConfigAttribute<std::size_t>("id"); //! \ogs_file_attr{gml__points__point__x} - auto const p_x = pt.getConfigAttribute<double>("x"); + auto const p_x = pt.getConfigAttribute<double>("x"); //! \ogs_file_attr{gml__points__point__y} - auto const p_y = pt.getConfigAttribute<double>("y"); + auto const p_y = pt.getConfigAttribute<double>("y"); //! \ogs_file_attr{gml__points__point__z} - auto const p_z = pt.getConfigAttribute<double>("z"); + auto const p_z = pt.getConfigAttribute<double>("z"); auto const p_size = points.size(); BaseLib::insertIfKeyUniqueElseError(_idx_map, p_id, p_size, - "The point id is not unique."); + "The point id is not unique."); points.push_back(new GeoLib::Point(p_x, p_y, p_z, p_id)); //! \ogs_file_attr{gml__points__point__name} - if (auto const p_name = pt.getConfigAttributeOptional<std::string>("name")) + if (auto const p_name = + pt.getConfigAttributeOptional<std::string>("name")) { - if (p_name->empty()) { + if (p_name->empty()) + { OGS_FATAL("Empty point name found in geometry file."); } - BaseLib::insertIfKeyUniqueElseError(pnt_names, *p_name, p_size, - "The point name is not unique."); + BaseLib::insertIfKeyUniqueElseError( + pnt_names, *p_name, p_size, "The point name is not unique."); } } } @@ -150,18 +155,21 @@ void BoostXmlGmlInterface::readPolylines( auto const id = pl.getConfigAttribute<std::size_t>("id"); // The id is not used but must be present in the GML file. // That's why pl.ignore...() cannot be used. - (void) id; + (void)id; polylines.push_back(new GeoLib::Polyline(points)); //! \ogs_file_attr{gml__polylines__polyline__name} - if (auto const p_name = pl.getConfigAttributeOptional<std::string>("name")) + if (auto const p_name = + pl.getConfigAttributeOptional<std::string>("name")) { - if (p_name->empty()) { + if (p_name->empty()) + { OGS_FATAL("Empty polyline name found in geometry file."); } - BaseLib::insertIfKeyUniqueElseError(ply_names, *p_name, polylines.size()-1, + BaseLib::insertIfKeyUniqueElseError( + ply_names, *p_name, polylines.size() - 1, "The polyline name is not unique."); auto accessOrError = [this, &p_name](auto pt_idx) { @@ -191,7 +199,7 @@ void BoostXmlGmlInterface::readPolylines( } void BoostXmlGmlInterface::readSurfaces( - BaseLib::ConfigTree const& surfacesRoot, + BaseLib::ConfigTree const& surfacesRoot, std::vector<GeoLib::Surface*>& surfaces, std::vector<GeoLib::Point*> const& points, const std::vector<std::size_t>& pnt_id_map, @@ -204,27 +212,34 @@ void BoostXmlGmlInterface::readSurfaces( auto const id = sfc.getConfigAttribute<std::size_t>("id"); // The id is not used but must be present in the GML file. // That's why sfc.ignore...() cannot be used. - (void) id; + (void)id; surfaces.push_back(new GeoLib::Surface(points)); //! \ogs_file_attr{gml__surfaces__surface__name} - if (auto const s_name = sfc.getConfigAttributeOptional<std::string>("name")) + if (auto const s_name = + sfc.getConfigAttributeOptional<std::string>("name")) { - if (s_name->empty()) { + if (s_name->empty()) + { OGS_FATAL("Empty surface name found in geometry file."); } - BaseLib::insertIfKeyUniqueElseError(sfc_names, *s_name, surfaces.size()-1, + BaseLib::insertIfKeyUniqueElseError( + sfc_names, *s_name, surfaces.size() - 1, "The surface name is not unique."); //! \ogs_file_param{gml__surfaces__surface__element} - for (auto const& element : sfc.getConfigParameterList("element")) { + for (auto const& element : sfc.getConfigParameterList("element")) + { //! \ogs_file_attr{gml__surfaces__surface__element__p1} - auto const p1_attr = element.getConfigAttribute<std::size_t>("p1"); + auto const p1_attr = + element.getConfigAttribute<std::size_t>("p1"); //! \ogs_file_attr{gml__surfaces__surface__element__p2} - auto const p2_attr = element.getConfigAttribute<std::size_t>("p2"); + auto const p2_attr = + element.getConfigAttribute<std::size_t>("p2"); //! \ogs_file_attr{gml__surfaces__surface__element__p3} - auto const p3_attr = element.getConfigAttribute<std::size_t>("p3"); + auto const p3_attr = + element.getConfigAttribute<std::size_t>("p3"); auto accessOrError = [this, &s_name](std::size_t pt_idx) { auto search = _idx_map.find(pt_idx); @@ -232,8 +247,7 @@ void BoostXmlGmlInterface::readSurfaces( { OGS_FATAL( "The element list of the surface `{:s}' contains " - "the " - "invalid point id `{:d}'.", + "the invalid point id `{:d}'.", s_name->c_str(), pt_idx); } return search->second; @@ -242,7 +256,7 @@ void BoostXmlGmlInterface::readSurfaces( auto const p1 = pnt_id_map[accessOrError(p1_attr)]; auto const p2 = pnt_id_map[accessOrError(p2_attr)]; auto const p3 = pnt_id_map[accessOrError(p3_attr)]; - surfaces.back()->addTriangle(p1,p2,p3); + surfaces.back()->addTriangle(p1, p2, p3); } } else @@ -263,21 +277,24 @@ bool BoostXmlGmlInterface::write() GeoLib::PointVec const* const pnt_vec( _geo_objects.getPointVecObj(export_name)); - if (! pnt_vec) { + if (!pnt_vec) + { ERR("BoostXmlGmlInterface::write(): No PointVec within the geometry " "'{:s}'.", export_name); return false; } - std::vector<GeoLib::Point*> const*const pnts(pnt_vec->getVector()); - if (! pnts) { + std::vector<GeoLib::Point*> const* const pnts(pnt_vec->getVector()); + if (!pnts) + { ERR("BoostXmlGmlInterface::write(): No vector of points within the " "geometry '{:s}'.", export_name); return false; } - if (pnts->empty()) { + if (pnts->empty()) + { ERR("BoostXmlGmlInterface::write(): No points within the geometry " "'{:s}'.", export_name); @@ -294,7 +311,8 @@ bool BoostXmlGmlInterface::write() geometry_set.add("name", export_name); auto& pnts_tag = geometry_set.add("points", ""); - for (std::size_t k(0); k<pnts->size(); k++) { + for (std::size_t k(0); k < pnts->size(); k++) + { auto& pnt_tag = pnts_tag.add("point", ""); pnt_tag.put("<xmlattr>.id", k); pnt_tag.put("<xmlattr>.x", (*((*pnts)[k]))[0]); @@ -316,31 +334,33 @@ bool BoostXmlGmlInterface::write() } void BoostXmlGmlInterface::addSurfacesToPropertyTree( - boost::property_tree::ptree & geometry_set) + boost::property_tree::ptree& geometry_set) { GeoLib::SurfaceVec const* const sfc_vec( _geo_objects.getSurfaceVecObj(export_name)); - if (!sfc_vec) { + if (!sfc_vec) + { INFO( - "BoostXmlGmlInterface::addSurfacesToPropertyTree(): " - "No surfaces within the geometry '{:s}'.", + "BoostXmlGmlInterface::addSurfacesToPropertyTree(): No surfaces " + "within the geometry '{:s}'.", export_name); return; } - std::vector<GeoLib::Surface*> const*const surfaces(sfc_vec->getVector()); + std::vector<GeoLib::Surface*> const* const surfaces(sfc_vec->getVector()); if (!surfaces || surfaces->empty()) { INFO( - "BoostXmlGmlInterface::addSurfacesToPropertyTree(): " - "No surfaces within the geometry '{:s}'.", + "BoostXmlGmlInterface::addSurfacesToPropertyTree(): No surfaces " + "within the geometry '{:s}'.", export_name); return; } auto& surfaces_tag = geometry_set.add("surfaces", ""); - for (std::size_t i=0; i<surfaces->size(); ++i) { - GeoLib::Surface const*const surface((*surfaces)[i]); + for (std::size_t i = 0; i < surfaces->size(); ++i) + { + GeoLib::Surface const* const surface((*surfaces)[i]); std::string sfc_name; sfc_vec->getNameOfElement(surface, sfc_name); auto& surface_tag = surfaces_tag.add("surface", ""); @@ -349,7 +369,8 @@ void BoostXmlGmlInterface::addSurfacesToPropertyTree( { surface_tag.put("<xmlattr>.name", sfc_name); } - for (std::size_t j=0; j<surface->getNumberOfTriangles(); ++j) { + for (std::size_t j = 0; j < surface->getNumberOfTriangles(); ++j) + { auto& element_tag = surface_tag.add("element", ""); element_tag.put("<xmlattr>.p1", (*(*surface)[j])[0]); element_tag.put("<xmlattr>.p2", (*(*surface)[j])[1]); @@ -359,31 +380,33 @@ void BoostXmlGmlInterface::addSurfacesToPropertyTree( } void BoostXmlGmlInterface::addPolylinesToPropertyTree( - boost::property_tree::ptree & geometry_set) + boost::property_tree::ptree& geometry_set) { GeoLib::PolylineVec const* const vec( _geo_objects.getPolylineVecObj(export_name)); - if (!vec) { + if (!vec) + { INFO( - "BoostXmlGmlInterface::addPolylinesToPropertyTree(): " - "No polylines within the geometry '{:s}'.", + "BoostXmlGmlInterface::addPolylinesToPropertyTree(): No polylines " + "within the geometry '{:s}'.", export_name); return; } - std::vector<GeoLib::Polyline*> const*const polylines(vec->getVector()); + std::vector<GeoLib::Polyline*> const* const polylines(vec->getVector()); if (!polylines || polylines->empty()) { INFO( - "BoostXmlGmlInterface::addPolylinesToPropertyTree(): " - "No polylines within the geometry '{:s}'.", + "BoostXmlGmlInterface::addPolylinesToPropertyTree(): No polylines " + "within the geometry '{:s}'.", export_name); return; } auto& polylines_tag = geometry_set.add("polylines", ""); - for (std::size_t i=0; i<polylines->size(); ++i) { - GeoLib::Polyline const*const polyline((*polylines)[i]); + for (std::size_t i = 0; i < polylines->size(); ++i) + { + GeoLib::Polyline const* const polyline((*polylines)[i]); std::string ply_name; vec->getNameOfElement(polyline, ply_name); auto& polyline_tag = polylines_tag.add("polyline", ""); @@ -392,11 +415,12 @@ void BoostXmlGmlInterface::addPolylinesToPropertyTree( { polyline_tag.put("<xmlattr>.name", ply_name); } - for (std::size_t j=0; j<polyline->getNumberOfPoints(); ++j) { + for (std::size_t j = 0; j < polyline->getNumberOfPoints(); ++j) + { polyline_tag.add("pnt", polyline->getPointID(j)); } } } -} // end namespace IO -} // end namespace GeoLib +} // end namespace IO +} // end namespace GeoLib diff --git a/GeoLib/IO/XmlIO/Qt/XmlGmlInterface.cpp b/GeoLib/IO/XmlIO/Qt/XmlGmlInterface.cpp index b0274052f6dc94895e05e44c8a01f6dc45ec94f5..9b1fb214e5e421aac8098411fb6ae4cb793e98a8 100644 --- a/GeoLib/IO/XmlIO/Qt/XmlGmlInterface.cpp +++ b/GeoLib/IO/XmlIO/Qt/XmlGmlInterface.cpp @@ -19,7 +19,6 @@ #include <QtXml/QDomDocument> #include "BaseLib/Logging.h" - #include "GeoLib/Triangle.h" namespace @@ -63,7 +62,7 @@ XmlGmlInterface::XmlGmlInterface(GeoLib::GEOObjects& geo_objs) { } -int XmlGmlInterface::readFile(const QString &fileName) +int XmlGmlInterface::readFile(const QString& fileName) { if (XMLQtInterface::readFile(fileName) == 0) { @@ -72,7 +71,7 @@ int XmlGmlInterface::readFile(const QString &fileName) QDomDocument doc("OGS-GLI-DOM"); doc.setContent(getContent()); - QDomElement docElement = doc.documentElement(); //OpenGeoSysGLI + QDomElement docElement = doc.documentElement(); // OpenGeoSysGLI if (docElement.nodeName().compare("OpenGeoSysGLI")) { ERR("XmlGmlInterface::readFile() - Unexpected XML root."); @@ -105,7 +104,7 @@ int XmlGmlInterface::readFile(const QString &fileName) return 0; } - gliName = type_node.toElement().text().toStdString(); + gliName = type_node.toElement().text().toStdString(); } else if (nodeName.compare("points") == 0) { @@ -187,8 +186,9 @@ void XmlGmlInterface::readPoints(const QDomNode& pointsRoot, QDomElement point = pointsRoot.firstChildElement(); while (!point.isNull()) { - _idx_map.insert (std::pair<std::size_t, std::size_t>( - strtol((point.attribute("id")).toStdString().c_str(), &pEnd, 10), points->size())); + _idx_map.insert(std::pair<std::size_t, std::size_t>( + strtol((point.attribute("id")).toStdString().c_str(), &pEnd, 10), + points->size())); GeoLib::Point* p = new GeoLib::Point(point.attribute("x").toDouble(), point.attribute("y").toDouble(), point.attribute("z").toDouble(), @@ -217,16 +217,19 @@ void XmlGmlInterface::readPolylines( std::size_t const idx = polylines->size(); polylines->push_back(new GeoLib::Polyline(points)); - if (polyline.hasAttribute("name")) { + if (polyline.hasAttribute("name")) + { std::string const ply_name( - polyline.attribute("name").toStdString() - ); + polyline.attribute("name").toStdString()); std::map<std::string, std::size_t>::const_iterator it( - ply_names->find(ply_name) - ); - if (it == ply_names->end()) { - ply_names->insert(std::pair<std::string, std::size_t>(ply_name, idx)); - } else { + ply_names->find(ply_name)); + if (it == ply_names->end()) + { + ply_names->insert( + std::pair<std::string, std::size_t>(ply_name, idx)); + } + else + { WARN( "Polyline '{:s}' exists already. Polyline {:d} will be " "inserted without a name.", @@ -235,24 +238,22 @@ void XmlGmlInterface::readPolylines( } QDomElement point = polyline.firstChildElement(); - auto accessOrError = - [this, &polyline](auto pt_idx) { - auto search = _idx_map.find(pt_idx); - if (search == _idx_map.end()) + auto accessOrError = [this, &polyline](auto pt_idx) { + auto search = _idx_map.find(pt_idx); + if (search == _idx_map.end()) + { + std::string polyline_name; + if (polyline.hasAttribute("name")) { - std::string polyline_name; - if (polyline.hasAttribute("name")) - { - polyline_name = - polyline.attribute("name").toStdString(); - } - OGS_FATAL( - "Polyline `{:s}' contains the point id `{:d}' which is " - "not in the point list.", - polyline_name, pt_idx); + polyline_name = polyline.attribute("name").toStdString(); } - return search->second; - }; + OGS_FATAL( + "Polyline `{:s}' contains the point id `{:d}' which is not " + "in the point list.", + polyline_name, pt_idx); + } + return search->second; + }; while (!point.isNull()) { @@ -283,23 +284,22 @@ void XmlGmlInterface::readSurfaces( surface.attribute("name").toStdString(), surfaces->size() - 1)); } - auto accessOrError = - [this, &surface](auto pt_idx) { - auto search = _idx_map.find(pt_idx); - if (search == _idx_map.end()) + auto accessOrError = [this, &surface](auto pt_idx) { + auto search = _idx_map.find(pt_idx); + if (search == _idx_map.end()) + { + std::string surface_name; + if (surface.hasAttribute("name")) { - std::string surface_name; - if (surface.hasAttribute("name")) - { - surface_name = surface.attribute("name").toStdString(); - } - OGS_FATAL( - "Surface `{:s}' contains the point id `{:d}', which is " - "not in the point list.", - surface_name, pt_idx); + surface_name = surface.attribute("name").toStdString(); } - return search->second; - }; + OGS_FATAL( + "Surface `{:s}' contains the point id `{:d}', which is not " + "in the point list.", + surface_name, pt_idx); + } + return search->second; + }; QDomElement element = surface.firstChildElement(); while (!element.isNull()) @@ -310,7 +310,7 @@ void XmlGmlInterface::readSurfaces( pnt_id_map[accessOrError(element.attribute("p2").toInt())]; std::size_t p3 = pnt_id_map[accessOrError(element.attribute("p3").toInt())]; - surfaces->back()->addTriangle(p1,p2,p3); + surfaces->back()->addTriangle(p1, p2, p3); element = element.nextSiblingElement(); } @@ -330,8 +330,8 @@ bool XmlGmlInterface::write() QDomDocument doc("OGS-GML-DOM"); QDomElement root = doc.createElement("OpenGeoSysGLI"); - root.setAttribute( "xmlns:ogs", "http://www.opengeosys.org" ); - root.setAttribute( "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance" ); + root.setAttribute("xmlns:ogs", "http://www.opengeosys.org"); + root.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); doc.appendChild(root); @@ -348,7 +348,7 @@ bool XmlGmlInterface::write() const GeoLib::PointVec* pnt_vec(_geo_objs.getPointVecObj(export_name)); if (pnt_vec) { - const std::vector<GeoLib::Point*>* points (pnt_vec->getVector()); + const std::vector<GeoLib::Point*>* points(pnt_vec->getVector()); if (!points->empty()) { @@ -382,13 +382,15 @@ bool XmlGmlInterface::write() } else { - ERR("XmlGmlInterface::write(): Point vector is empty, abort writing geometry."); + ERR("XmlGmlInterface::write(): Point vector is empty, abort " + "writing geometry."); return false; } } else { - ERR("XmlGmlInterface::write(): No point vector found, abort writing geometry."); + ERR("XmlGmlInterface::write(): No point vector found, abort writing " + "geometry."); return false; } @@ -397,7 +399,7 @@ bool XmlGmlInterface::write() _geo_objs.getPolylineVecObj(export_name)); if (ply_vec) { - const std::vector<GeoLib::Polyline*>* polylines (ply_vec->getVector()); + const std::vector<GeoLib::Polyline*>* polylines(ply_vec->getVector()); if (polylines) { @@ -412,11 +414,16 @@ bool XmlGmlInterface::write() polylineTag.setAttribute("id", QString::number(i)); std::string ply_name; - if (ply_vec->getNameOfElementByID(i, ply_name)) { - polylineTag.setAttribute("name", QString::fromStdString(ply_name)); - } else { + if (ply_vec->getNameOfElementByID(i, ply_name)) + { + polylineTag.setAttribute( + "name", QString::fromStdString(ply_name)); + } + else + { ply_name = std::to_string(i); - polylineTag.setAttribute("name", QString::fromStdString(ply_name)); + polylineTag.setAttribute( + "name", QString::fromStdString(ply_name)); } plyListTag.appendChild(polylineTag); @@ -426,27 +433,32 @@ bool XmlGmlInterface::write() { QDomElement plyPointTag = doc.createElement("pnt"); polylineTag.appendChild(plyPointTag); - QDomText plyPointText = doc.createTextNode(QString::number(((*polylines)[i])->getPointID(j))); + QDomText plyPointText = doc.createTextNode( + QString::number(((*polylines)[i])->getPointID(j))); plyPointTag.appendChild(plyPointText); } } } else { - INFO("XmlGmlInterface::write(): Polyline vector is empty, no polylines written to file."); + INFO( + "XmlGmlInterface::write(): Polyline vector is empty, no " + "polylines written to file."); } } } else { - INFO("XmlGmlInterface::write(): Polyline vector is empty, no polylines written to file."); + INFO( + "XmlGmlInterface::write(): Polyline vector is empty, no polylines " + "written to file."); } // SURFACES const GeoLib::SurfaceVec* sfc_vec(_geo_objs.getSurfaceVecObj(export_name)); if (sfc_vec) { - const std::vector<GeoLib::Surface*>* surfaces (sfc_vec->getVector()); + const std::vector<GeoLib::Surface*>* surfaces(sfc_vec->getVector()); if (surfaces) { @@ -470,26 +482,34 @@ bool XmlGmlInterface::write() sfcListTag.appendChild(surfaceTag); // writing the elements compromising the surface - std::size_t nElements = ((*surfaces)[i])->getNumberOfTriangles(); + std::size_t nElements = + ((*surfaces)[i])->getNumberOfTriangles(); for (std::size_t j = 0; j < nElements; j++) { QDomElement elementTag = doc.createElement("element"); - elementTag.setAttribute("p1", QString::number((*(*(*surfaces)[i])[j])[0])); - elementTag.setAttribute("p2", QString::number((*(*(*surfaces)[i])[j])[1])); - elementTag.setAttribute("p3", QString::number((*(*(*surfaces)[i])[j])[2])); + elementTag.setAttribute( + "p1", QString::number((*(*(*surfaces)[i])[j])[0])); + elementTag.setAttribute( + "p2", QString::number((*(*(*surfaces)[i])[j])[1])); + elementTag.setAttribute( + "p3", QString::number((*(*(*surfaces)[i])[j])[2])); surfaceTag.appendChild(elementTag); } } } else { - INFO("XmlGmlInterface::write(): Surface vector is empty, no surfaces written to file."); + INFO( + "XmlGmlInterface::write(): Surface vector is empty, no " + "surfaces written to file."); } } } else { - INFO("XmlGmlInterface::write(): Surface vector is empty, no surfaces written to file."); + INFO( + "XmlGmlInterface::write(): Surface vector is empty, no surfaces " + "written to file."); } std::string xml = doc.toString().toStdString(); diff --git a/GeoLib/IO/XmlIO/Qt/XmlStnInterface.cpp b/GeoLib/IO/XmlIO/Qt/XmlStnInterface.cpp index 59e15aa4e112582d3e2d29478f9803149f9680b5..5321bb8351cc9cb0cc60c3c9d85ae54467eaced2 100644 --- a/GeoLib/IO/XmlIO/Qt/XmlStnInterface.cpp +++ b/GeoLib/IO/XmlIO/Qt/XmlStnInterface.cpp @@ -14,18 +14,16 @@ #include "XmlStnInterface.h" -#include <limits> - #include <QFile> #include <QtXml/QDomDocument> +#include <limits> #include <rapidxml.hpp> -#include "BaseLib/Logging.h" #include "BaseLib/DateTools.h" #include "BaseLib/FileTools.h" - -#include "GeoLib/StationBorehole.h" +#include "BaseLib/Logging.h" #include "GeoLib/GEOObjects.h" +#include "GeoLib/StationBorehole.h" namespace GeoLib { @@ -36,7 +34,7 @@ XmlStnInterface::XmlStnInterface(GeoLib::GEOObjects& geo_objs) { } -int XmlStnInterface::readFile(const QString &fileName) +int XmlStnInterface::readFile(const QString& fileName) { if (XMLQtInterface::readFile(fileName) == 0) { @@ -45,7 +43,8 @@ int XmlStnInterface::readFile(const QString &fileName) QDomDocument doc("OGS-STN-DOM"); doc.setContent(getContent()); - QDomElement docElement = doc.documentElement(); //root element, used for identifying file-type + QDomElement docElement = + doc.documentElement(); // root element, used for identifying file-type if (docElement.nodeName().compare("OpenGeoSysSTN")) { ERR("XmlStnInterface::readFile(): Unexpected XML root."); @@ -70,7 +69,8 @@ int XmlStnInterface::readFile(const QString &fileName) } else if (station_type.compare("stations") == 0) { - readStations(station_node, stations.get(), fileName.toStdString()); + readStations(station_node, stations.get(), + fileName.toStdString()); } else if (station_type.compare("boreholes") == 0) { @@ -88,9 +88,9 @@ int XmlStnInterface::readFile(const QString &fileName) return 1; } -void XmlStnInterface::readStations( const QDomNode &stationsRoot, - std::vector<GeoLib::Point*>* stations, - const std::string &station_file_name ) +void XmlStnInterface::readStations(const QDomNode& stationsRoot, + std::vector<GeoLib::Point*>* stations, + const std::string& station_file_name) { QDomElement station = stationsRoot.firstChildElement(); while (!station.isNull()) @@ -105,12 +105,12 @@ void XmlStnInterface::readStations( const QDomNode &stationsRoot, double stationValue(0.0); QDomNodeList stationFeatures = station.childNodes(); - for(int i = 0; i < stationFeatures.count(); i++) + for (int i = 0; i < stationFeatures.count(); i++) { // check for general station features - const QDomNode feature_node (stationFeatures.at(i)); - const QString feature_name (feature_node.nodeName()); - const QString element_text (feature_node.toElement().text()); + const QDomNode feature_node(stationFeatures.at(i)); + const QString feature_name(feature_node.nodeName()); + const QString element_text(feature_node.toElement().text()); if (feature_name.compare("name") == 0) { stationName = element_text.toStdString(); @@ -118,9 +118,9 @@ void XmlStnInterface::readStations( const QDomNode &stationsRoot, if (feature_name.compare("sensordata") == 0) { sensor_data_file_name = element_text.toStdString(); - /* add other station features here */ + /* add other station features here */ - // check for general borehole features + // check for general borehole features } else if (feature_name.compare("value") == 0) { @@ -137,14 +137,17 @@ void XmlStnInterface::readStations( const QDomNode &stationsRoot, /* add other borehole features here */ } - double zVal = (station.hasAttribute("z")) ? station.attribute("z").toDouble() : 0.0; + double zVal = (station.hasAttribute("z")) + ? station.attribute("z").toDouble() + : 0.0; if (station.nodeName().compare("station") == 0) { - GeoLib::Station* s = new GeoLib::Station(station.attribute("x").toDouble(), - station.attribute("y").toDouble(), - zVal, - stationName); + GeoLib::Station* s = + new GeoLib::Station(station.attribute("x").toDouble(), + station.attribute("y").toDouble(), + zVal, + stationName); s->setStationValue(stationValue); if (!sensor_data_file_name.empty()) { @@ -155,7 +158,8 @@ void XmlStnInterface::readStations( const QDomNode &stationsRoot, } else if (station.nodeName().compare("borehole") == 0) { - GeoLib::StationBorehole* s = GeoLib::StationBorehole::createStation( + GeoLib::StationBorehole* s = + GeoLib::StationBorehole::createStation( stationName, station.attribute("x").toDouble(), station.attribute("y").toDouble(), @@ -177,16 +181,19 @@ void XmlStnInterface::readStations( const QDomNode &stationsRoot, } else { - WARN("XmlStnInterface::readStations(): Attribute missing in <station> tag."); + WARN( + "XmlStnInterface::readStations(): Attribute missing in " + "<station> tag."); } station = station.nextSiblingElement(); } } -void XmlStnInterface::readStratigraphy( const QDomNode &stratRoot, - GeoLib::StationBorehole* borehole ) +void XmlStnInterface::readStratigraphy(const QDomNode& stratRoot, + GeoLib::StationBorehole* borehole) { - //borehole->addSoilLayer((*borehole)[0], (*borehole)[1], (*borehole)[2], ""); + // borehole->addSoilLayer((*borehole)[0], (*borehole)[1], (*borehole)[2], + // ""); double depth_check((*borehole)[2]); QDomElement horizon = stratRoot.firstChildElement(); while (!horizon.isNull()) @@ -207,7 +214,7 @@ void XmlStnInterface::readStratigraphy( const QDomNode &stratRoot, } /* add other horizon features here */ - double depth (horizon.attribute("z").toDouble()); + double depth(horizon.attribute("z").toDouble()); if (std::abs(depth - depth_check) > std::numeric_limits<double>:: epsilon()) // skip soil-layer if its thickness is zero @@ -228,7 +235,9 @@ void XmlStnInterface::readStratigraphy( const QDomNode &stratRoot, } else { - WARN("XmlStnInterface::readStratigraphy(): Attribute missing in <horizon> tag."); + WARN( + "XmlStnInterface::readStratigraphy(): Attribute missing in " + "<horizon> tag."); } horizon = horizon.nextSiblingElement(); } @@ -249,13 +258,14 @@ bool XmlStnInterface::write() QDomDocument doc("OGS-STN-DOM"); QDomElement root = doc.createElement("OpenGeoSysSTN"); - root.setAttribute( "xmlns:ogs", "http://www.opengeosys.org" ); - root.setAttribute( "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance" ); + root.setAttribute("xmlns:ogs", "http://www.opengeosys.org"); + root.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); const std::vector<GeoLib::Point*>* stations( _geo_objs.getStationVec(export_name)); - bool const is_borehole = static_cast<GeoLib::Station*>((*stations)[0])->type() == - GeoLib::Station::StationType::BOREHOLE; + bool const is_borehole = + static_cast<GeoLib::Station*>((*stations)[0])->type() == + GeoLib::Station::StationType::BOREHOLE; doc.appendChild(root); QDomElement stationListTag = doc.createElement("stationlist"); @@ -271,12 +281,13 @@ bool XmlStnInterface::write() stationListTag.appendChild(stationsTag); bool useStationValue(false); - double sValue = static_cast<GeoLib::Station*>((*stations)[0])->getStationValue(); + double sValue = + static_cast<GeoLib::Station*>((*stations)[0])->getStationValue(); std::size_t nStations(stations->size()); for (std::size_t i = 1; i < nStations; i++) { - if ((static_cast<GeoLib::Station*>((*stations)[i])->getStationValue() - sValue) < - std::numeric_limits<double>::epsilon()) + if ((static_cast<GeoLib::Station*>((*stations)[i])->getStationValue() - + sValue) < std::numeric_limits<double>::epsilon()) { useStationValue = true; break; @@ -285,29 +296,33 @@ bool XmlStnInterface::write() for (std::size_t i = 0; i < nStations; i++) { - QString stationType = is_borehole ? "borehole" : "station"; + QString stationType = is_borehole ? "borehole" : "station"; QDomElement stationTag = doc.createElement(stationType); - stationTag.setAttribute( "id", QString::number(i) ); - stationTag.setAttribute( "x", QString::number((*(*stations)[i])[0], 'f', - std::numeric_limits<double>::digits10)); - stationTag.setAttribute( "y", QString::number((*(*stations)[i])[1], 'f', - std::numeric_limits<double>::digits10)); - stationTag.setAttribute( "z", QString::number((*(*stations)[i])[2], 'f', - std::numeric_limits<double>::digits10)); + stationTag.setAttribute("id", QString::number(i)); + stationTag.setAttribute( + "x", QString::number((*(*stations)[i])[0], 'f', + std::numeric_limits<double>::digits10)); + stationTag.setAttribute( + "y", QString::number((*(*stations)[i])[1], 'f', + std::numeric_limits<double>::digits10)); + stationTag.setAttribute( + "z", QString::number((*(*stations)[i])[2], 'f', + std::numeric_limits<double>::digits10)); stationsTag.appendChild(stationTag); QDomElement stationNameTag = doc.createElement("name"); stationTag.appendChild(stationNameTag); - QDomText stationNameText = - doc.createTextNode(QString::fromStdString(static_cast<GeoLib::Station*>((*stations)[i])->getName())); + QDomText stationNameText = doc.createTextNode(QString::fromStdString( + static_cast<GeoLib::Station*>((*stations)[i])->getName())); stationNameTag.appendChild(stationNameText); if (useStationValue) { QDomElement stationValueTag = doc.createElement("value"); stationTag.appendChild(stationValueTag); - QDomText stationValueText = - doc.createTextNode(QString::number(static_cast<GeoLib::Station*>((*stations)[i])->getStationValue())); + QDomText stationValueText = doc.createTextNode( + QString::number(static_cast<GeoLib::Station*>((*stations)[i]) + ->getStationValue())); stationValueTag.appendChild(stationValueText); } @@ -324,21 +339,21 @@ bool XmlStnInterface::write() return true; } -void XmlStnInterface::writeBoreholeData(QDomDocument &doc, - QDomElement &boreholeTag, +void XmlStnInterface::writeBoreholeData(QDomDocument& doc, + QDomElement& boreholeTag, GeoLib::StationBorehole* borehole) const { QDomElement stationDepthTag = doc.createElement("bdepth"); boreholeTag.appendChild(stationDepthTag); - QDomText stationDepthText = doc.createTextNode(QString::number(borehole->getDepth(), 'f')); + QDomText stationDepthText = + doc.createTextNode(QString::number(borehole->getDepth(), 'f')); stationDepthTag.appendChild(stationDepthText); if (std::abs(borehole->getDate()) > 0) { QDomElement stationDateTag = doc.createElement("bdate"); boreholeTag.appendChild(stationDateTag); - QDomText stationDateText = - doc.createTextNode(QString::fromStdString(BaseLib::date2string(borehole-> - getDate()))); + QDomText stationDateText = doc.createTextNode( + QString::fromStdString(BaseLib::date2string(borehole->getDate()))); stationDateTag.appendChild(stationDateText); } @@ -351,18 +366,23 @@ void XmlStnInterface::writeBoreholeData(QDomDocument &doc, QDomElement stratTag = doc.createElement("strat"); boreholeTag.appendChild(stratTag); - for (std::size_t j = 1; j < nHorizons; j++) /// the first entry in the profile vector is just the position of the borehole + for (std::size_t j = 1; j < nHorizons; + j++) /// the first entry in the profile vector is just the + /// position of the borehole { QDomElement horizonTag = doc.createElement("horizon"); - horizonTag.setAttribute( "id", QString::number(j) ); - horizonTag.setAttribute( "x", QString::number((*profile[j])[0], 'f') ); - horizonTag.setAttribute( "y", QString::number((*profile[j])[1], 'f') ); - horizonTag.setAttribute( "z", QString::number((*profile[j])[2], 'f') ); + horizonTag.setAttribute("id", QString::number(j)); + horizonTag.setAttribute("x", + QString::number((*profile[j])[0], 'f')); + horizonTag.setAttribute("y", + QString::number((*profile[j])[1], 'f')); + horizonTag.setAttribute("z", + QString::number((*profile[j])[2], 'f')); stratTag.appendChild(horizonTag); QDomElement horizonNameTag = doc.createElement("name"); horizonTag.appendChild(horizonNameTag); QDomText horizonNameText = - doc.createTextNode(QString::fromStdString(soilNames[j])); + doc.createTextNode(QString::fromStdString(soilNames[j])); horizonNameTag.appendChild(horizonNameText); } } diff --git a/GeoLib/LineSegment.cpp b/GeoLib/LineSegment.cpp index 20962f9de6451091dc72a393317e0ffdb37b32e5..0978b23fd16fabf8408341504212caac24bf0d2e 100644 --- a/GeoLib/LineSegment.cpp +++ b/GeoLib/LineSegment.cpp @@ -17,13 +17,15 @@ LineSegment::LineSegment(Point* const a, Point* const b, _b(b), _point_mem_management_by_line_segment( point_mem_management_by_line_segment) -{} +{ +} LineSegment::LineSegment(LineSegment const& line_segment) : _a(new Point(line_segment.getBeginPoint())), _b(new Point(line_segment.getEndPoint())), _point_mem_management_by_line_segment(true) -{} +{ +} LineSegment::LineSegment(LineSegment&& line_segment) : _a(line_segment._a), @@ -38,7 +40,8 @@ LineSegment::LineSegment(LineSegment&& line_segment) LineSegment::~LineSegment() { - if (_point_mem_management_by_line_segment) { + if (_point_mem_management_by_line_segment) + { delete _b; delete _a; } @@ -65,7 +68,7 @@ Point const& LineSegment::getBeginPoint() const return *_a; } -Point & LineSegment::getBeginPoint() +Point& LineSegment::getBeginPoint() { return *_a; } @@ -75,12 +78,12 @@ Point const& LineSegment::getEndPoint() const return *_b; } -Point & LineSegment::getEndPoint() +Point& LineSegment::getEndPoint() { return *_b; } -std::ostream& operator<< (std::ostream& os, LineSegment const& s) +std::ostream& operator<<(std::ostream& os, LineSegment const& s) { os << "{(" << s.getBeginPoint() << "), (" << s.getEndPoint() << ")}"; return os; @@ -98,8 +101,8 @@ bool operator==(LineSegment const& s0, LineSegment const& s1) { double const tol(std::numeric_limits<double>::epsilon()); return (MathLib::sqrDist(s0.getBeginPoint(), s1.getBeginPoint()) < tol && - MathLib::sqrDist(s0.getEndPoint(), s1.getEndPoint()) < tol) || - (MathLib::sqrDist(s0.getBeginPoint(), s1.getEndPoint()) < tol && - MathLib::sqrDist(s0.getEndPoint(), s1.getBeginPoint()) < tol); + MathLib::sqrDist(s0.getEndPoint(), s1.getEndPoint()) < tol) || + (MathLib::sqrDist(s0.getBeginPoint(), s1.getEndPoint()) < tol && + MathLib::sqrDist(s0.getEndPoint(), s1.getBeginPoint()) < tol); } } // namespace GeoLib diff --git a/GeoLib/MinimalBoundingSphere.cpp b/GeoLib/MinimalBoundingSphere.cpp index 3e989cfab3a66843ce766b6864828b9022e3db3e..f1424620adada5e24ad1a14c049de864e8a1ff06 100644 --- a/GeoLib/MinimalBoundingSphere.cpp +++ b/GeoLib/MinimalBoundingSphere.cpp @@ -16,22 +16,23 @@ #include <ctime> -#include "MathLib/Point3d.h" #include "MathLib/GeometricBasics.h" #include "MathLib/MathTools.h" +#include "MathLib/Point3d.h" -namespace GeoLib { +namespace GeoLib +{ MinimalBoundingSphere::MinimalBoundingSphere() = default; -MinimalBoundingSphere::MinimalBoundingSphere( - MathLib::Point3d const& p, double radius) -: _radius(radius), _center(p) +MinimalBoundingSphere::MinimalBoundingSphere(MathLib::Point3d const& p, + double radius) + : _radius(radius), _center(p) { } -MinimalBoundingSphere::MinimalBoundingSphere( - MathLib::Point3d const& p, MathLib::Point3d const& q) -: _radius(std::numeric_limits<double>::epsilon()), _center(p) +MinimalBoundingSphere::MinimalBoundingSphere(MathLib::Point3d const& p, + MathLib::Point3d const& q) + : _radius(std::numeric_limits<double>::epsilon()), _center(p) { auto const vp = Eigen::Map<Eigen::Vector3d const>(p.getCoords()); auto const vq = Eigen::Map<Eigen::Vector3d const>(q.getCoords()); @@ -44,7 +45,8 @@ MinimalBoundingSphere::MinimalBoundingSphere( } MinimalBoundingSphere::MinimalBoundingSphere(MathLib::Point3d const& p, - MathLib::Point3d const& q, MathLib::Point3d const& r) + MathLib::Point3d const& q, + MathLib::Point3d const& r) { auto const vp = Eigen::Map<Eigen::Vector3d const>(p.getCoords()); auto const vq = Eigen::Map<Eigen::Vector3d const>(q.getCoords()); @@ -67,7 +69,7 @@ MinimalBoundingSphere::MinimalBoundingSphere(MathLib::Point3d const& p, MinimalBoundingSphere two_pnts_sphere; if (a.squaredNorm() > b.squaredNorm()) { - two_pnts_sphere = MinimalBoundingSphere(p,r); + two_pnts_sphere = MinimalBoundingSphere(p, r); } else { @@ -79,9 +81,9 @@ MinimalBoundingSphere::MinimalBoundingSphere(MathLib::Point3d const& p, } MinimalBoundingSphere::MinimalBoundingSphere(MathLib::Point3d const& p, - MathLib::Point3d const& q, - MathLib::Point3d const& r, - MathLib::Point3d const& s) + MathLib::Point3d const& q, + MathLib::Point3d const& r, + MathLib::Point3d const& s) { auto const vp = Eigen::Map<Eigen::Vector3d const>(p.getCoords()); auto const vq = Eigen::Map<Eigen::Vector3d const>(q.getCoords()); @@ -106,10 +108,10 @@ MinimalBoundingSphere::MinimalBoundingSphere(MathLib::Point3d const& p, } else { - MinimalBoundingSphere const pqr(p, q , r); - MinimalBoundingSphere const pqs(p, q , s); - MinimalBoundingSphere const prs(p, r , s); - MinimalBoundingSphere const qrs(q, r , s); + MinimalBoundingSphere const pqr(p, q, r); + MinimalBoundingSphere const pqs(p, q, s); + MinimalBoundingSphere const prs(p, r, s); + MinimalBoundingSphere const qrs(q, r, s); _radius = pqr.getRadius(); _center = pqr.getCenter(); if (_radius < pqs.getRadius()) @@ -135,62 +137,72 @@ MinimalBoundingSphere::MinimalBoundingSphere( : _radius(-1), _center({0, 0, 0}) { const std::vector<MathLib::Point3d*>& sphere_points(points); - MinimalBoundingSphere const bounding_sphere = recurseCalculation(sphere_points, 0, sphere_points.size(), 0); + MinimalBoundingSphere const bounding_sphere = + recurseCalculation(sphere_points, 0, sphere_points.size(), 0); _center = bounding_sphere.getCenter(); _radius = bounding_sphere.getRadius(); } -MinimalBoundingSphere -MinimalBoundingSphere::recurseCalculation( +MinimalBoundingSphere MinimalBoundingSphere::recurseCalculation( std::vector<MathLib::Point3d*> sphere_points, std::size_t start_idx, std::size_t length, std::size_t n_boundary_points) { MinimalBoundingSphere sphere; - switch(n_boundary_points) + switch (n_boundary_points) { - case 0: - sphere = MinimalBoundingSphere(); - break; - case 1: - sphere = MinimalBoundingSphere(*sphere_points[start_idx-1]); - break; - case 2: - sphere = MinimalBoundingSphere(*sphere_points[start_idx-1], *sphere_points[start_idx-2]); - break; - case 3: - sphere = MinimalBoundingSphere(*sphere_points[start_idx-1], *sphere_points[start_idx-2], *sphere_points[start_idx-3]); - break; - case 4: - sphere = MinimalBoundingSphere(*sphere_points[start_idx-1], *sphere_points[start_idx-2], *sphere_points[start_idx-3], *sphere_points[start_idx-4]); - return sphere; + case 0: + sphere = MinimalBoundingSphere(); + break; + case 1: + sphere = MinimalBoundingSphere(*sphere_points[start_idx - 1]); + break; + case 2: + sphere = MinimalBoundingSphere(*sphere_points[start_idx - 1], + *sphere_points[start_idx - 2]); + break; + case 3: + sphere = MinimalBoundingSphere(*sphere_points[start_idx - 1], + *sphere_points[start_idx - 2], + *sphere_points[start_idx - 3]); + break; + case 4: + sphere = MinimalBoundingSphere( + *sphere_points[start_idx - 1], *sphere_points[start_idx - 2], + *sphere_points[start_idx - 3], *sphere_points[start_idx - 4]); + return sphere; } - for(std::size_t i=0; i<length; ++i) + for (std::size_t i = 0; i < length; ++i) { // current point is located outside of sphere - if (sphere.pointDistanceSquared(*sphere_points[start_idx+i]) > 0) + if (sphere.pointDistanceSquared(*sphere_points[start_idx + i]) > 0) { - if (i>start_idx) + if (i > start_idx) { - using DiffType = std::vector<MathLib::Point3d*>::iterator::difference_type; + using DiffType = + std::vector<MathLib::Point3d*>::iterator::difference_type; std::vector<MathLib::Point3d*> const tmp_ps( sphere_points.cbegin() + static_cast<DiffType>(start_idx), - sphere_points.cbegin() + static_cast<DiffType>(start_idx + i + 1)); + sphere_points.cbegin() + + static_cast<DiffType>(start_idx + i + 1)); std::copy(tmp_ps.cbegin(), --tmp_ps.cend(), - sphere_points.begin() + static_cast<DiffType>(start_idx + 1)); + sphere_points.begin() + + static_cast<DiffType>(start_idx + 1)); sphere_points[start_idx] = tmp_ps.back(); } - sphere = recurseCalculation(sphere_points, start_idx+1, i, n_boundary_points+1); + sphere = recurseCalculation(sphere_points, start_idx + 1, i, + n_boundary_points + 1); } } return sphere; } -double MinimalBoundingSphere::pointDistanceSquared(MathLib::Point3d const& pnt) const +double MinimalBoundingSphere::pointDistanceSquared( + MathLib::Point3d const& pnt) const { - return MathLib::sqrDist(_center, pnt)-(_radius*_radius); + return MathLib::sqrDist(_center, pnt) - (_radius * _radius); } } // namespace GeoLib diff --git a/GeoLib/PointVec.cpp b/GeoLib/PointVec.cpp index 5889627f03075d33e3d09b8814cfc4990cc583ec..6822171f434cd1f1a421e3b177deed1a24649ff9 100644 --- a/GeoLib/PointVec.cpp +++ b/GeoLib/PointVec.cpp @@ -12,12 +12,11 @@ * */ +#include "PointVec.h" + #include <numeric> #include "BaseLib/Logging.h" - -#include "PointVec.h" - #include "MathLib/MathTools.h" namespace GeoLib diff --git a/GeoLib/Polygon.cpp b/GeoLib/Polygon.cpp index 5c55877ec65acaf42e070521a15c6ed3279096d9..07dba6090bb16f5ba1a0e9e83e15ffeac8f53559 100644 --- a/GeoLib/Polygon.cpp +++ b/GeoLib/Polygon.cpp @@ -16,14 +16,13 @@ #include <boost/math/constants/constants.hpp> -#include "BaseLib/quicksort.h" - #include "AnalyticalGeometry.h" +#include "BaseLib/quicksort.h" namespace GeoLib { -Polygon::Polygon(const Polyline &ply, bool init) : - Polyline(ply), _aabb(ply.getPointsVec(), ply._ply_pnt_ids) +Polygon::Polygon(const Polyline& ply, bool init) + : Polyline(ply), _aabb(ply.getPointsVec(), ply._ply_pnt_ids) { if (init) { @@ -32,8 +31,7 @@ Polygon::Polygon(const Polyline &ply, bool init) : _simple_polygon_list.push_back(this); } -Polygon::Polygon(Polygon const& other) - : Polyline(other), _aabb(other._aabb) +Polygon::Polygon(Polygon const& other) : Polyline(other), _aabb(other._aabb) { _simple_polygon_list.push_back(this); auto sub_polygon_it(other._simple_polygon_list.begin()); @@ -59,9 +57,10 @@ Polygon::~Polygon() } } -bool Polygon::initialise () +bool Polygon::initialise() { - if (this->isClosed()) { + if (this->isClosed()) + { ensureCCWOrientation(); return true; } @@ -128,18 +127,19 @@ bool Polygon::isPntInPolygon(GeoLib::Point const& pnt) const bool Polygon::isPntInPolygon(double x, double y, double z) const { - const GeoLib::Point pnt(x,y,z); + const GeoLib::Point pnt(x, y, z); return isPntInPolygon(pnt); } std::vector<GeoLib::Point> Polygon::getAllIntersectionPoints( - GeoLib::LineSegment const& segment) const + GeoLib::LineSegment const& segment) const { std::vector<GeoLib::Point> intersections; GeoLib::Point s; for (auto&& seg_it : *this) { - if (GeoLib::lineSegmentIntersect(seg_it, segment, s)) { + if (GeoLib::lineSegmentIntersect(seg_it, segment, s)) + { intersections.push_back(s); } } @@ -154,21 +154,25 @@ bool Polygon::containsSegment(GeoLib::LineSegment const& segment) const GeoLib::Point const& a{segment.getBeginPoint()}; GeoLib::Point const& b{segment.getEndPoint()}; // no intersections -> check if at least one point of segment is in polygon - if (s.empty()) { + if (s.empty()) + { return (isPntInPolygon(a)); } const double tol(std::numeric_limits<float>::epsilon()); // one intersection, intersection in line segment end point - if (s.size() == 1) { - const double sqr_dist_as(MathLib::sqrDist(a,s[0])); - if (sqr_dist_as < tol) { + if (s.size() == 1) + { + const double sqr_dist_as(MathLib::sqrDist(a, s[0])); + if (sqr_dist_as < tol) + { return (isPntInPolygon(b)); } - const double sqr_dist_bs(MathLib::sqrDist(b,s[0])); - if (sqr_dist_bs < tol) { + const double sqr_dist_bs(MathLib::sqrDist(b, s[0])); + if (sqr_dist_bs < tol) + { return (isPntInPolygon(a)); } } @@ -176,16 +180,19 @@ bool Polygon::containsSegment(GeoLib::LineSegment const& segment) const // Sorting the intersection with respect to the distance to the point a. // This induces a partition of the line segment into sub segments. std::sort(s.begin(), s.end(), - [&a] (GeoLib::Point const& p0, GeoLib::Point const& p1) { - return MathLib::sqrDist(a, p0) < MathLib::sqrDist(a, p1); - } - ); + [&a](GeoLib::Point const& p0, GeoLib::Point const& p1) { + return MathLib::sqrDist(a, p0) < MathLib::sqrDist(a, p1); + }); // remove sub segments with almost zero length - for (std::size_t k(0); k<s.size()-1; ) { - if (MathLib::sqrDist(s[k], s[k+1]) < tol) { - s.erase(s.begin()+k+1); - } else { + for (std::size_t k(0); k < s.size() - 1;) + { + if (MathLib::sqrDist(s[k], s[k + 1]) < tol) + { + s.erase(s.begin() + k + 1); + } + else + { k++; } } @@ -197,8 +204,9 @@ bool Polygon::containsSegment(GeoLib::LineSegment const& segment) const { return false; } - const std::size_t n_sub_segs(s.size()-1); - for (std::size_t k(0); k<n_sub_segs; k++) { + const std::size_t n_sub_segs(s.size() - 1); + for (std::size_t k(0); k < n_sub_segs; k++) + { if (!isPntInPolygon(GeoLib::Point(0.5 * (s[k][0] + s[k + 1][0]), 0.5 * (s[k][1] + s[k + 1][1]), 0.5 * (s[k][2] + s[k + 1][2])))) @@ -220,7 +228,7 @@ bool Polygon::isPolylineInPolygon(const Polyline& ply) const bool Polygon::isPartOfPolylineInPolygon(const Polyline& ply) const { - const std::size_t ply_size (ply.getNumberOfPoints()); + const std::size_t ply_size(ply.getNumberOfPoints()); // check points for (std::size_t k(0); k < ply_size; k++) { @@ -247,15 +255,19 @@ bool Polygon::getNextIntersectionPointPolygonLine( GeoLib::LineSegment const& seg, GeoLib::Point& intersection_pnt, std::size_t& seg_num) const { - if (_simple_polygon_list.size() == 1) { - for (auto seg_it(begin()+seg_num); seg_it != end(); ++seg_it) { + if (_simple_polygon_list.size() == 1) + { + for (auto seg_it(begin() + seg_num); seg_it != end(); ++seg_it) + { if (GeoLib::lineSegmentIntersect(*seg_it, seg, intersection_pnt)) { seg_num = seg_it.getSegmentNumber(); return true; } } - } else { + } + else + { for (auto polygon : _simple_polygon_list) { for (auto seg_it(polygon->begin()); seg_it != polygon->end(); @@ -277,40 +289,42 @@ EdgeType Polygon::getEdgeType(std::size_t k, GeoLib::Point const& pnt) const { switch (getLocationOfPoint(k, pnt)) { - case Location::LEFT: { - const GeoLib::Point & v (*(getPoint(k))); - const GeoLib::Point & w (*(getPoint(k + 1))); - if (v[1] < pnt[1] && pnt[1] <= w[1]) + case Location::LEFT: { - return EdgeType::CROSSING; - } + const GeoLib::Point& v(*(getPoint(k))); + const GeoLib::Point& w(*(getPoint(k + 1))); + if (v[1] < pnt[1] && pnt[1] <= w[1]) + { + return EdgeType::CROSSING; + } - return EdgeType::INESSENTIAL; - } - case Location::RIGHT: { - const GeoLib::Point & v (*(getPoint(k))); - const GeoLib::Point & w (*(getPoint(k + 1))); - if (w[1] < pnt[1] && pnt[1] <= v[1]) - { - return EdgeType::CROSSING; + return EdgeType::INESSENTIAL; } + case Location::RIGHT: + { + const GeoLib::Point& v(*(getPoint(k))); + const GeoLib::Point& w(*(getPoint(k + 1))); + if (w[1] < pnt[1] && pnt[1] <= v[1]) + { + return EdgeType::CROSSING; + } - return EdgeType::INESSENTIAL; - } - case Location::BETWEEN: - case Location::SOURCE: - case Location::DESTINATION: - return EdgeType::TOUCHING; - default: - return EdgeType::INESSENTIAL; + return EdgeType::INESSENTIAL; + } + case Location::BETWEEN: + case Location::SOURCE: + case Location::DESTINATION: + return EdgeType::TOUCHING; + default: + return EdgeType::INESSENTIAL; } } -void Polygon::ensureCCWOrientation () +void Polygon::ensureCCWOrientation() { // *** pre processing: rotate points to xy-plan // *** copy points to vector - last point is identical to the first - std::size_t n_pnts (this->getNumberOfPoints() - 1); + std::size_t n_pnts(this->getNumberOfPoints() - 1); std::vector<GeoLib::Point*> tmp_polygon_pnts; for (std::size_t k(0); k < n_pnts; k++) { @@ -327,10 +341,11 @@ void Polygon::ensureCCWOrientation () } // *** get the left most upper point - std::size_t min_x_max_y_idx (0); // for orientation check + std::size_t min_x_max_y_idx(0); // for orientation check for (std::size_t k(0); k < n_pnts; k++) { - if ((*(tmp_polygon_pnts[k]))[0] <= (*(tmp_polygon_pnts[min_x_max_y_idx]))[0]) + if ((*(tmp_polygon_pnts[k]))[0] <= + (*(tmp_polygon_pnts[min_x_max_y_idx]))[0]) { if ((*(tmp_polygon_pnts[k]))[0] < (*(tmp_polygon_pnts[min_x_max_y_idx]))[0]) @@ -371,8 +386,9 @@ void Polygon::ensureCCWOrientation () if (orient != GeoLib::CCW) { // switch orientation - std::size_t tmp_n_pnts (n_pnts); - tmp_n_pnts++; // include last point of polygon (which is identical to the first) + std::size_t tmp_n_pnts(n_pnts); + tmp_n_pnts++; // include last point of polygon (which is identical to + // the first) for (std::size_t k(0); k < tmp_n_pnts / 2; k++) { std::swap(_ply_pnt_ids[k], _ply_pnt_ids[tmp_n_pnts - 1 - k]); @@ -405,9 +421,9 @@ void Polygon::splitPolygonAtIntersection( std::size_t idx0(seg_it0.getSegmentNumber()); std::size_t idx1(seg_it1.getSegmentNumber()); // adding intersection point to pnt_vec - std::size_t const intersection_pnt_id (_ply_pnts.size()); - const_cast<std::vector<Point*>&>(_ply_pnts) - .push_back(new GeoLib::Point(intersection_pnt)); + std::size_t const intersection_pnt_id(_ply_pnts.size()); + const_cast<std::vector<Point*>&>(_ply_pnts).push_back( + new GeoLib::Point(intersection_pnt)); // split Polygon if (idx0 > idx1) @@ -449,18 +465,19 @@ void Polygon::splitPolygonAtIntersection( splitPolygonAtIntersection(polygon1_it); } -void Polygon::splitPolygonAtPoint (const std::list<GeoLib::Polygon*>::iterator& polygon_it) +void Polygon::splitPolygonAtPoint( + const std::list<GeoLib::Polygon*>::iterator& polygon_it) { std::size_t const n((*polygon_it)->getNumberOfPoints() - 1); std::vector<std::size_t> id_vec(n); std::vector<std::size_t> perm(n); for (std::size_t k(0); k < n; k++) { - id_vec[k] = (*polygon_it)->getPointID (k); + id_vec[k] = (*polygon_it)->getPointID(k); perm[k] = k; } - BaseLib::quicksort (id_vec, 0, n, perm); + BaseLib::quicksort(id_vec, 0, n, perm); for (std::size_t k(0); k < n - 1; k++) { @@ -525,8 +542,10 @@ bool operator==(Polygon const& lhs, Polygon const& rhs) // search start point of first polygon in second polygon bool nfound(true); std::size_t k(0); - for (; k < n-1 && nfound; k++) { - if (start_pnt == rhs.getPointID(k)) { + for (; k < n - 1 && nfound; k++) + { + if (start_pnt == rhs.getPointID(k)) + { nfound = false; break; } @@ -540,26 +559,35 @@ bool operator==(Polygon const& lhs, Polygon const& rhs) // *** determine direction // opposite direction - if (k == n-2) { - for (k=1; k<n-1; k++) { - if (lhs.getPointID(k) != rhs.getPointID(n-1-k)) { + if (k == n - 2) + { + for (k = 1; k < n - 1; k++) + { + if (lhs.getPointID(k) != rhs.getPointID(n - 1 - k)) + { return false; } } return true; } - // same direction - start point of first polygon at arbitrary position in second polygon - if (lhs.getPointID(1) == rhs.getPointID(k+1)) { - std::size_t j(k+2); - for (; j<n-1; j++) { - if (lhs.getPointID(j-k) != rhs.getPointID(j)) { + // same direction - start point of first polygon at arbitrary position in + // second polygon + if (lhs.getPointID(1) == rhs.getPointID(k + 1)) + { + std::size_t j(k + 2); + for (; j < n - 1; j++) + { + if (lhs.getPointID(j - k) != rhs.getPointID(j)) + { return false; } } - j=0; // new start point at second polygon - for (; j<k+1; j++) { - if (lhs.getPointID(n-(k+2)+j+1) != rhs.getPointID(j)) { + j = 0; // new start point at second polygon + for (; j < k + 1; j++) + { + if (lhs.getPointID(n - (k + 2) + j + 1) != rhs.getPointID(j)) + { return false; } } @@ -598,4 +626,4 @@ bool operator==(Polygon const& lhs, Polygon const& rhs) return false; } -} // end namespace GeoLib +} // end namespace GeoLib diff --git a/GeoLib/PolygonWithSegmentMarker.cpp b/GeoLib/PolygonWithSegmentMarker.cpp index fd7d85bb6a0fe0bdd8370af49abe25980a10921f..707cfad4b140563783e78d7e6a1494af991d70ee 100644 --- a/GeoLib/PolygonWithSegmentMarker.cpp +++ b/GeoLib/PolygonWithSegmentMarker.cpp @@ -9,7 +9,8 @@ #include "PolygonWithSegmentMarker.h" -namespace GeoLib { +namespace GeoLib +{ PolygonWithSegmentMarker::PolygonWithSegmentMarker( GeoLib::Polyline const& polyline) : GeoLib::Polygon(polyline, true), @@ -29,7 +30,8 @@ bool PolygonWithSegmentMarker::isSegmentMarked(std::size_t seg_num) const bool PolygonWithSegmentMarker::addPoint(std::size_t pnt_id) { - if (Polyline::addPoint(pnt_id)) { + if (Polyline::addPoint(pnt_id)) + { _marker.push_back(false); return true; } @@ -38,8 +40,9 @@ bool PolygonWithSegmentMarker::addPoint(std::size_t pnt_id) bool PolygonWithSegmentMarker::insertPoint(std::size_t pos, std::size_t pnt_id) { - if (Polyline::insertPoint(pos, pnt_id)) { - _marker.insert(_marker.begin()+pos, _marker[pos]); + if (Polyline::insertPoint(pos, pnt_id)) + { + _marker.insert(_marker.begin() + pos, _marker[pos]); return true; } return false; diff --git a/GeoLib/Polyline.cpp b/GeoLib/Polyline.cpp index 5f9ecd222a98a45ff8e78b70aa063432b7f1a810..c6feec89399eed3fbc1b38cb42507de0cbc62824 100644 --- a/GeoLib/Polyline.cpp +++ b/GeoLib/Polyline.cpp @@ -15,6 +15,7 @@ #include "Polyline.h" #include <algorithm> + #include "AnalyticalGeometry.h" #include "BaseLib/Error.h" #include "BaseLib/Logging.h" @@ -24,16 +25,17 @@ namespace GeoLib { Polyline::Polyline(const std::vector<Point*>& pnt_vec) : _ply_pnts(pnt_vec) { - _length.push_back (0.0); + _length.push_back(0.0); } Polyline::Polyline(const Polyline& ply) : _ply_pnts(ply._ply_pnts), _ply_pnt_ids(ply._ply_pnt_ids), _length(ply._length) -{} +{ +} -void Polyline::write(std::ostream &os) const +void Polyline::write(std::ostream& os) const { std::size_t size(_ply_pnt_ids.size()); for (std::size_t k(0); k < size; k++) @@ -47,7 +49,8 @@ bool Polyline::addPoint(std::size_t pnt_id) assert(pnt_id < _ply_pnts.size()); std::size_t const n_pnts(_ply_pnt_ids.size()); - // don't insert point if this would result in identical IDs for two adjacent points + // don't insert point if this would result in identical IDs for two adjacent + // points if (n_pnts > 0 && _ply_pnt_ids.back() == pnt_id) { return false; @@ -58,7 +61,7 @@ bool Polyline::addPoint(std::size_t pnt_id) if (n_pnts > 0) { double const act_dist(std::sqrt(MathLib::sqrDist( - *_ply_pnts[_ply_pnt_ids[n_pnts-1]], *_ply_pnts[pnt_id]))); + *_ply_pnts[_ply_pnt_ids[n_pnts - 1]], *_ply_pnts[pnt_id]))); double dist_until_now(0.0); if (n_pnts > 1) { @@ -75,12 +78,15 @@ bool Polyline::insertPoint(std::size_t pos, std::size_t pnt_id) assert(pnt_id < _ply_pnts.size()); assert(pos <= _ply_pnt_ids.size()); - if (pos == _ply_pnt_ids.size()) { + if (pos == _ply_pnt_ids.size()) + { return addPoint(pnt_id); } - // check if inserting pnt_id would result in two identical IDs for adjacent points - if (pos == 0 && pnt_id == _ply_pnt_ids[0]) { + // check if inserting pnt_id would result in two identical IDs for adjacent + // points + if (pos == 0 && pnt_id == _ply_pnt_ids[0]) + { return false; } if (pos != 0) @@ -93,16 +99,18 @@ bool Polyline::insertPoint(std::size_t pos, std::size_t pnt_id) { return false; } - } + } auto const pos_dt( static_cast<std::vector<std::size_t>::difference_type>(pos)); auto it(_ply_pnt_ids.begin() + pos_dt); _ply_pnt_ids.insert(it, pnt_id); - if (_ply_pnt_ids.size() > 1) { + if (_ply_pnt_ids.size() > 1) + { // update the _length vector - if (pos == 0) { + if (pos == 0) + { // insert at first position double const act_dist(std::sqrt(MathLib::sqrDist( *_ply_pnts[_ply_pnt_ids[1]], *_ply_pnts[pnt_id]))); @@ -112,13 +120,16 @@ bool Polyline::insertPoint(std::size_t pos, std::size_t pnt_id) { _length[k] += _length[1]; } - } else { - if (pos == _ply_pnt_ids.size() - 1) { + } + else + { + if (pos == _ply_pnt_ids.size() - 1) + { // insert at last position double const act_dist(std::sqrt(MathLib::sqrDist( *_ply_pnts[_ply_pnt_ids[_ply_pnt_ids.size() - 2]], *_ply_pnts[pnt_id]))); - double dist_until_now (0.0); + double dist_until_now(0.0); if (_ply_pnt_ids.size() > 2) { dist_until_now = _length[_ply_pnt_ids.size() - 2]; @@ -126,21 +137,21 @@ bool Polyline::insertPoint(std::size_t pos, std::size_t pnt_id) _length.insert(_length.begin() + pos_dt, dist_until_now + act_dist); - } else { + } + else + { // insert at arbitrary position within the vector - double dist_until_now (0.0); + double dist_until_now(0.0); if (pos > 1) { dist_until_now = _length[pos - 1]; } double len_seg0(std::sqrt(MathLib::sqrDist( - *_ply_pnts[_ply_pnt_ids[pos - 1]], - *_ply_pnts[pnt_id]))); + *_ply_pnts[_ply_pnt_ids[pos - 1]], *_ply_pnts[pnt_id]))); double len_seg1(std::sqrt(MathLib::sqrDist( - *_ply_pnts[_ply_pnt_ids[pos + 1]], - *_ply_pnts[pnt_id]))); - double update_dist( - len_seg0 + len_seg1 - (_length[pos] - dist_until_now)); + *_ply_pnts[_ply_pnt_ids[pos + 1]], *_ply_pnts[pnt_id]))); + double update_dist(len_seg0 + len_seg1 - + (_length[pos] - dist_until_now)); _length[pos] = dist_until_now + len_seg0; auto it1(_length.begin() + pos_dt + 1); _length.insert(it1, _length[pos] + len_seg1); @@ -173,19 +184,22 @@ void Polyline::removePoint(std::size_t pos) } const std::size_t n_ply_pnt_ids(_ply_pnt_ids.size()); - if (pos == 0) { + if (pos == 0) + { double seg_length(_length[0]); for (std::size_t k(0); k < n_ply_pnt_ids; k++) { _length[k] = _length[k + 1] - seg_length; } _length.pop_back(); - } else { + } + else + { const double len_seg0(_length[pos] - _length[pos - 1]); const double len_seg1(_length[pos + 1] - _length[pos]); _length.erase(_length.begin() + pos_dt); - const double len_new_seg(std::sqrt(MathLib::sqrDist(*_ply_pnts[_ply_pnt_ids[pos - 1]], - *_ply_pnts[_ply_pnt_ids[pos]]))); + const double len_new_seg(std::sqrt(MathLib::sqrDist( + *_ply_pnts[_ply_pnt_ids[pos - 1]], *_ply_pnts[_ply_pnt_ids[pos]]))); double seg_length_diff(len_new_seg - len_seg0 - len_seg1); for (std::size_t k(pos); k < n_ply_pnt_ids; k++) @@ -202,7 +216,7 @@ std::size_t Polyline::getNumberOfPoints() const std::size_t Polyline::getNumberOfSegments() const { - return _ply_pnt_ids.empty() ? 0 : _ply_pnt_ids.size()-1; + return _ply_pnt_ids.empty() ? 0 : _ply_pnt_ids.size() - 1; } bool Polyline::isClosed() const @@ -217,16 +231,16 @@ bool Polyline::isClosed() const bool Polyline::isCoplanar() const { - std::size_t const n_points (_ply_pnt_ids.size()); + std::size_t const n_points(_ply_pnt_ids.size()); if (n_points < 4) { return true; } - GeoLib::Point const& p0 (*this->getPoint(0)); - GeoLib::Point const& p1 (*this->getPoint(1)); - GeoLib::Point const& p2 (*this->getPoint(2)); - for (std::size_t i=3; i<n_points; ++i) + GeoLib::Point const& p0(*this->getPoint(0)); + GeoLib::Point const& p1(*this->getPoint(1)); + GeoLib::Point const& p2(*this->getPoint(2)); + for (std::size_t i = 3; i < n_points; ++i) { if (!MathLib::isCoplanar(p0, p1, p2, *this->getPoint(i))) { @@ -242,7 +256,8 @@ bool Polyline::isCoplanar() const bool Polyline::isPointIDInPolyline(std::size_t pnt_id) const { - return std::find(_ply_pnt_ids.begin(), _ply_pnt_ids.end(), pnt_id) != _ply_pnt_ids.end(); + return std::find(_ply_pnt_ids.begin(), _ply_pnt_ids.end(), pnt_id) != + _ply_pnt_ids.end(); } std::size_t Polyline::getPointID(std::size_t i) const @@ -277,19 +292,19 @@ const Point* Polyline::getPoint(std::size_t i) const return _ply_pnts[_ply_pnt_ids[i]]; } -std::vector<Point*> const& Polyline::getPointsVec () const +std::vector<Point*> const& Polyline::getPointsVec() const { return _ply_pnts; } -double Polyline::getLength (std::size_t k) const +double Polyline::getLength(std::size_t k) const { assert(k < _length.size()); return _length[k]; } -Polyline* Polyline::constructPolylineFromSegments(const std::vector<Polyline*> &ply_vec, - double prox) +Polyline* Polyline::constructPolylineFromSegments( + const std::vector<Polyline*>& ply_vec, double prox) { std::size_t nLines = ply_vec.size(); @@ -305,14 +320,14 @@ Polyline* Polyline::constructPolylineFromSegments(const std::vector<Polyline*> & while (!local_ply_vec.empty()) { bool ply_found(false); - prox *= prox; // square distance once to save time later + prox *= prox; // square distance once to save time later for (auto it = local_ply_vec.begin(); it != local_ply_vec.end(); ++it) { if (pnt_vec == (*it)->getPointsVec()) { std::size_t nPoints((*it)->getNumberOfPoints()); - //if (new_ply->getPointID(0) == (*it)->getPointID(0)) + // if (new_ply->getPointID(0) == (*it)->getPointID(0)) if (pointsAreIdentical(pnt_vec, new_ply->getPointID(0), (*it)->getPointID(0), prox)) { @@ -331,9 +346,11 @@ Polyline* Polyline::constructPolylineFromSegments(const std::vector<Polyline*> & new_ply = tmp; ply_found = true; } - //else if (new_ply->getPointID(0) == (*it)->getPointID(nPoints-1)) + // else if (new_ply->getPointID(0) == + // (*it)->getPointID(nPoints-1)) else if (pointsAreIdentical(pnt_vec, new_ply->getPointID(0), - (*it)->getPointID(nPoints - 1), prox)) + (*it)->getPointID(nPoints - 1), + prox)) { auto* tmp = new Polyline(**it); std::size_t new_ply_size(new_ply->getNumberOfPoints()); @@ -345,12 +362,13 @@ Polyline* Polyline::constructPolylineFromSegments(const std::vector<Polyline*> & new_ply = tmp; ply_found = true; } - //else if (new_ply->getPointID(new_ply->getNumberOfPoints()-1) == (*it)->getPointID(0)) - else if (pointsAreIdentical(pnt_vec, - new_ply->getPointID(new_ply-> - getNumberOfPoints() - - 1), - (*it)->getPointID(0), prox)) + // else if (new_ply->getPointID(new_ply->getNumberOfPoints()-1) + // == (*it)->getPointID(0)) + else if (pointsAreIdentical( + pnt_vec, + new_ply->getPointID(new_ply->getNumberOfPoints() - + 1), + (*it)->getPointID(0), prox)) { for (std::size_t k = 1; k < nPoints; k++) { @@ -358,12 +376,13 @@ Polyline* Polyline::constructPolylineFromSegments(const std::vector<Polyline*> & } ply_found = true; } - //else if (new_ply->getPointID(new_ply->getNumberOfPoints()-1) == (*it)->getPointID(nPoints-1)) - else if (pointsAreIdentical(pnt_vec, - new_ply->getPointID(new_ply-> - getNumberOfPoints() - - 1), - (*it)->getPointID(nPoints - 1), prox)) + // else if (new_ply->getPointID(new_ply->getNumberOfPoints()-1) + // == (*it)->getPointID(nPoints-1)) + else if (pointsAreIdentical( + pnt_vec, + new_ply->getPointID(new_ply->getNumberOfPoints() - + 1), + (*it)->getPointID(nPoints - 1), prox)) { for (std::size_t k = 1; k < nPoints; k++) { @@ -379,13 +398,15 @@ Polyline* Polyline::constructPolylineFromSegments(const std::vector<Polyline*> & } else { - ERR("Error in Polyline::contructPolylineFromSegments() - Line segments use different point vectors."); + ERR("Error in Polyline::contructPolylineFromSegments() - Line " + "segments use different point vectors."); } } if (!ply_found) { - ERR("Error in Polyline::contructPolylineFromSegments() - Not all segments are connected."); + ERR("Error in Polyline::contructPolylineFromSegments() - Not all " + "segments are connected."); delete new_ply; new_ply = nullptr; break; @@ -396,24 +417,28 @@ Polyline* Polyline::constructPolylineFromSegments(const std::vector<Polyline*> & void Polyline::closePolyline() { - if (getNumberOfPoints() < 2) { - ERR("Polyline::closePolyline(): Input polyline needs to be composed of at least three points."); + if (getNumberOfPoints() < 2) + { + ERR("Polyline::closePolyline(): Input polyline needs to be composed of " + "at least three points."); } - if (! isClosed()) { + if (!isClosed()) + { addPoint(getPointID(0)); } } -Location Polyline::getLocationOfPoint (std::size_t k, GeoLib::Point const & pnt) const +Location Polyline::getLocationOfPoint(std::size_t k, + GeoLib::Point const& pnt) const { - assert (k < _ply_pnt_ids.size() - 1); + assert(k < _ply_pnt_ids.size() - 1); - GeoLib::Point const& source (*(_ply_pnts[_ply_pnt_ids[k]])); - GeoLib::Point const& dest (*(_ply_pnts[_ply_pnt_ids[k + 1]])); - long double a[2] = {dest[0] - source[0], dest[1] - source[1]}; // vector - long double b[2] = {pnt[0] - source[0], pnt[1] - source[1]}; // vector + GeoLib::Point const& source(*(_ply_pnts[_ply_pnt_ids[k]])); + GeoLib::Point const& dest(*(_ply_pnts[_ply_pnt_ids[k + 1]])); + long double a[2] = {dest[0] - source[0], dest[1] - source[1]}; // vector + long double b[2] = {pnt[0] - source[0], pnt[1] - source[1]}; // vector - long double det_2x2 (a[0] * b[1] - a[1] * b[0]); + long double det_2x2(a[0] * b[1] - a[1] * b[0]); if (det_2x2 > std::numeric_limits<double>::epsilon()) { @@ -445,16 +470,18 @@ Location Polyline::getLocationOfPoint (std::size_t k, GeoLib::Point const & pnt) } double Polyline::getDistanceAlongPolyline(const MathLib::Point3d& pnt, - const double epsilon_radius) const + const double epsilon_radius) const { double dist(-1.0); double lambda; bool found = false; // loop over all line segments of the polyline - for (std::size_t k = 0; k < getNumberOfSegments(); k++) { + for (std::size_t k = 0; k < getNumberOfSegments(); k++) + { // is the orthogonal projection of the j-th node to the - // line g(lambda) = _ply->getPoint(k) + lambda * (_ply->getPoint(k+1) - _ply->getPoint(k)) - // at the k-th line segment of the polyline, i.e. 0 <= lambda <= 1? + // line g(lambda) = _ply->getPoint(k) + lambda * (_ply->getPoint(k+1) - + // _ply->getPoint(k)) at the k-th line segment of the polyline, i.e. 0 + // <= lambda <= 1? if (MathLib::calcProjPntToLineAndDists(pnt, *getPoint(k), *getPoint(k + 1), lambda, dist) <= epsilon_radius) @@ -471,7 +498,7 @@ double Polyline::getDistanceAlongPolyline(const MathLib::Point3d& pnt, break; } // end if lambda } - } // end line segment loop + } // end line segment loop if (!found) { @@ -485,11 +512,13 @@ Polyline::SegmentIterator::SegmentIterator(Polyline const& polyline, : _polyline(&polyline), _segment_number( static_cast<std::vector<GeoLib::Point*>::size_type>(segment_number)) -{} +{ +} Polyline::SegmentIterator::SegmentIterator(SegmentIterator const& src) : _polyline(src._polyline), _segment_number(src._segment_number) -{} +{ +} Polyline::SegmentIterator& Polyline::SegmentIterator::operator=( SegmentIterator const& rhs) @@ -539,10 +568,13 @@ bool Polyline::SegmentIterator::operator!=(SegmentIterator const& other) const Polyline::SegmentIterator& Polyline::SegmentIterator::operator+=( std::vector<GeoLib::Point>::difference_type n) { - if (n < 0) { + if (n < 0) + { _segment_number -= static_cast<std::vector<GeoLib::Point>::size_type>(-n); - } else { + } + else + { _segment_number += static_cast<std::vector<GeoLib::Point>::size_type>(n); } @@ -564,10 +596,13 @@ Polyline::SegmentIterator Polyline::SegmentIterator::operator+( Polyline::SegmentIterator& Polyline::SegmentIterator::operator-=( std::vector<GeoLib::Point>::difference_type n) { - if (n >= 0) { + if (n >= 0) + { _segment_number -= static_cast<std::vector<GeoLib::Point>::size_type>(n); - } else { + } + else + { _segment_number += static_cast<std::vector<GeoLib::Point>::size_type>(-n); } @@ -586,13 +621,13 @@ Polyline::SegmentIterator Polyline::SegmentIterator::operator-( return t; } -std::ostream& operator<< (std::ostream &os, const Polyline &pl) +std::ostream& operator<<(std::ostream& os, const Polyline& pl) { - pl.write (os); + pl.write(os); return os; } -bool containsEdge (const Polyline& ply, std::size_t id0, std::size_t id1) +bool containsEdge(const Polyline& ply, std::size_t id0, std::size_t id1) { if (id0 == id1) { @@ -603,11 +638,11 @@ bool containsEdge (const Polyline& ply, std::size_t id0, std::size_t id1) { std::swap(id0, id1); } - const std::size_t n (ply.getNumberOfPoints() - 1); + const std::size_t n(ply.getNumberOfPoints() - 1); for (std::size_t k(0); k < n; k++) { - std::size_t ply_pnt0 (ply.getPointID (k)); - std::size_t ply_pnt1 (ply.getPointID (k + 1)); + std::size_t ply_pnt0(ply.getPointID(k)); + std::size_t ply_pnt1(ply.getPointID(k + 1)); if (ply_pnt0 > ply_pnt1) { std::swap(ply_pnt0, ply_pnt1); @@ -639,7 +674,7 @@ bool operator==(Polyline const& lhs, Polyline const& rhs) return true; } -bool pointsAreIdentical(const std::vector<Point*> &pnt_vec, +bool pointsAreIdentical(const std::vector<Point*>& pnt_vec, std::size_t i, std::size_t j, double prox) @@ -650,4 +685,4 @@ bool pointsAreIdentical(const std::vector<Point*> &pnt_vec, } return MathLib::sqrDist(*pnt_vec[i], *pnt_vec[j]) < prox; } -} // end namespace GeoLib +} // end namespace GeoLib diff --git a/GeoLib/PolylineWithSegmentMarker.cpp b/GeoLib/PolylineWithSegmentMarker.cpp index a1debe18a18c081d0e7dd009f597c34b284bc531..67d22cfd00bfe48ddec88b9b57cf657f213dcd9c 100644 --- a/GeoLib/PolylineWithSegmentMarker.cpp +++ b/GeoLib/PolylineWithSegmentMarker.cpp @@ -14,7 +14,8 @@ #include "PolylineWithSegmentMarker.h" -namespace GeoLib { +namespace GeoLib +{ PolylineWithSegmentMarker::PolylineWithSegmentMarker( GeoLib::Polyline const& polyline) : GeoLib::Polyline(polyline), _marker(polyline.getNumberOfSegments(), false) @@ -33,7 +34,8 @@ bool PolylineWithSegmentMarker::isSegmentMarked(std::size_t seg_num) const bool PolylineWithSegmentMarker::addPoint(std::size_t pnt_id) { - if (Polyline::addPoint(pnt_id)) { + if (Polyline::addPoint(pnt_id)) + { _marker.push_back(false); return true; } @@ -42,8 +44,9 @@ bool PolylineWithSegmentMarker::addPoint(std::size_t pnt_id) bool PolylineWithSegmentMarker::insertPoint(std::size_t pos, std::size_t pnt_id) { - if (Polyline::insertPoint(pos, pnt_id)) { - _marker.insert(_marker.begin()+pos, _marker[pos]); + if (Polyline::insertPoint(pos, pnt_id)) + { + _marker.insert(_marker.begin() + pos, _marker[pos]); return true; } return false; diff --git a/GeoLib/Raster.cpp b/GeoLib/Raster.cpp index 456a935a8562a358d7d3cf043d4eb6e6f5a2eeaa..979f414e9c3627ae379e1be78e365a135606de2b 100644 --- a/GeoLib/Raster.cpp +++ b/GeoLib/Raster.cpp @@ -11,30 +11,37 @@ * http://www.opengeosys.org/project/license */ -#include <fstream> - #include "Raster.h" +#include <fstream> + // BaseLib #include "BaseLib/FileTools.h" #include "BaseLib/StringTools.h" - #include "Triangle.h" -namespace GeoLib { - +namespace GeoLib +{ void Raster::refineRaster(std::size_t scaling) { auto* new_raster_data( new double[_header.n_rows * _header.n_cols * scaling * scaling]); - for (std::size_t row(0); row<_header.n_rows; row++) { - for (std::size_t col(0); col<_header.n_cols; col++) { - const std::size_t idx(row*_header.n_cols+col); - for (std::size_t new_row(row*scaling); new_row<(row+1)*scaling; new_row++) { - const std::size_t idx0(new_row*_header.n_cols*scaling); - for (std::size_t new_col(col*scaling); new_col<(col+1)*scaling; new_col++) { - new_raster_data[idx0+new_col] = _raster_data[idx]; + for (std::size_t row(0); row < _header.n_rows; row++) + { + for (std::size_t col(0); col < _header.n_cols; col++) + { + const std::size_t idx(row * _header.n_cols + col); + for (std::size_t new_row(row * scaling); + new_row < (row + 1) * scaling; + new_row++) + { + const std::size_t idx0(new_row * _header.n_cols * scaling); + for (std::size_t new_col(col * scaling); + new_col < (col + 1) * scaling; + new_col++) + { + new_raster_data[idx0 + new_col] = _raster_data[idx]; } } } @@ -45,18 +52,20 @@ void Raster::refineRaster(std::size_t scaling) _header.n_cols *= scaling; _header.n_rows *= scaling; - delete [] new_raster_data; + delete[] new_raster_data; } Raster::~Raster() { - delete [] _raster_data; + delete[] _raster_data; } -double Raster::getValueAtPoint(const MathLib::Point3d &pnt) const +double Raster::getValueAtPoint(const MathLib::Point3d& pnt) const { - if (pnt[0]>=_header.origin[0] && pnt[0]<(_header.origin[0]+(_header.cell_size*_header.n_cols)) && - pnt[1]>=_header.origin[1] && pnt[1]<(_header.origin[1]+(_header.cell_size*_header.n_rows))) + if (pnt[0] >= _header.origin[0] && + pnt[0] < (_header.origin[0] + (_header.cell_size * _header.n_cols)) && + pnt[1] >= _header.origin[1] && + pnt[1] < (_header.origin[1] + (_header.cell_size * _header.n_rows))) { auto cell_x = static_cast<int>( std::floor((pnt[0] - _header.origin[0]) / _header.cell_size)); @@ -65,12 +74,14 @@ double Raster::getValueAtPoint(const MathLib::Point3d &pnt) const // use raster boundary values if node is outside raster due to rounding // errors or floating point arithmetic - cell_x = (cell_x < 0) ? 0 : ((cell_x > static_cast<int>(_header.n_cols)) - ? static_cast<int>(_header.n_cols - 1) - : cell_x); - cell_y = (cell_y < 0) ? 0 : ((cell_y > static_cast<int>(_header.n_rows)) - ? static_cast<int>(_header.n_rows - 1) - : cell_y); + cell_x = (cell_x < 0) ? 0 + : ((cell_x > static_cast<int>(_header.n_cols)) + ? static_cast<int>(_header.n_cols - 1) + : cell_x); + cell_y = (cell_y < 0) ? 0 + : ((cell_y > static_cast<int>(_header.n_rows)) + ? static_cast<int>(_header.n_rows - 1) + : cell_y); const std::size_t index = cell_y * _header.n_cols + cell_x; return _raster_data[index]; @@ -81,11 +92,11 @@ double Raster::getValueAtPoint(const MathLib::Point3d &pnt) const double Raster::interpolateValueAtPoint(MathLib::Point3d const& pnt) const { // position in raster - double const xPos ((pnt[0] - _header.origin[0]) / _header.cell_size); - double const yPos ((pnt[1] - _header.origin[1]) / _header.cell_size); + double const xPos((pnt[0] - _header.origin[0]) / _header.cell_size); + double const yPos((pnt[1] - _header.origin[1]) / _header.cell_size); // raster cell index - double const xIdx (std::floor(xPos)); //carry out computions in double - double const yIdx (std::floor(yPos)); // so not to over- or underflow. + double const xIdx(std::floor(xPos)); // carry out computions in double + double const yIdx(std::floor(yPos)); // so not to over- or underflow. // weights for bilinear interpolation double const xShift = std::abs((xPos - xIdx) - 0.5); @@ -97,13 +108,13 @@ double Raster::interpolateValueAtPoint(MathLib::Point3d const& pnt) const // neighbors to include in interpolation int const xShiftIdx = (xPos - xIdx >= 0.5) ? 1 : -1; int const yShiftIdx = (yPos - yIdx >= 0.5) ? 1 : -1; - std::array<int,4> const x_nb = {{ 0, xShiftIdx, xShiftIdx, 0 }}; - std::array<int,4> const y_nb = {{ 0, 0, yShiftIdx, yShiftIdx }}; + std::array<int, 4> const x_nb = {{0, xShiftIdx, xShiftIdx, 0}}; + std::array<int, 4> const y_nb = {{0, 0, yShiftIdx, yShiftIdx}}; // get pixel values - Eigen::Vector4d pix_val{}; - unsigned no_data_count (0); - for (unsigned j=0; j<4; ++j) + Eigen::Vector4d pix_val{}; + unsigned no_data_count(0); + for (unsigned j = 0; j < 4; ++j) { // check if neighbour pixel is still on the raster, otherwise substitute // a no data value. This also allows the cast to unsigned type. @@ -142,7 +153,7 @@ double Raster::interpolateValueAtPoint(MathLib::Point3d const& pnt) const // new value return weight.dot(pix_val); - } +} bool Raster::isPntOnRaster(MathLib::Point3d const& pnt) const { @@ -153,4 +164,4 @@ bool Raster::isPntOnRaster(MathLib::Point3d const& pnt) const (pnt[1] > _header.origin[1] + (_header.n_rows * _header.cell_size))); } -} // end namespace GeoLib +} // end namespace GeoLib diff --git a/GeoLib/SensorData.cpp b/GeoLib/SensorData.cpp index 728f75c5bdcd1973fecc7ce8b0e1be882d05f9a8..f2464ccc39f91874b95ae21ebbf00ed75cd021c4 100644 --- a/GeoLib/SensorData.cpp +++ b/GeoLib/SensorData.cpp @@ -17,21 +17,24 @@ #include <cstdlib> #include <fstream> +#include "BaseLib/DateTools.h" #include "BaseLib/Logging.h" - #include "BaseLib/StringTools.h" -#include "BaseLib/DateTools.h" -SensorData::SensorData(const std::string &file_name) -: _start(0), _end(0), _step_size(0), _time_unit(TimeStepType::NONE) +SensorData::SensorData(const std::string& file_name) + : _start(0), _end(0), _step_size(0), _time_unit(TimeStepType::NONE) { this->readDataFromFile(file_name); } SensorData::SensorData(std::vector<std::size_t> time_steps) -: _start(time_steps[0]), _end(time_steps[time_steps.size()-1]), _step_size(0), _time_unit(TimeStepType::NONE), _time_steps(time_steps) + : _start(time_steps[0]), + _end(time_steps[time_steps.size() - 1]), + _step_size(0), + _time_unit(TimeStepType::NONE), + _time_steps(time_steps) { - for (std::size_t i=1; i<time_steps.size(); i++) + for (std::size_t i = 1; i < time_steps.size(); i++) { if (time_steps[i - 1] >= time_steps[i]) { @@ -40,8 +43,13 @@ SensorData::SensorData(std::vector<std::size_t> time_steps) } } -SensorData::SensorData(std::size_t first_timestep, std::size_t last_timestep, std::size_t step_size) -: _start(first_timestep), _end(last_timestep), _step_size(step_size), _time_unit(TimeStepType::NONE) +SensorData::SensorData(std::size_t first_timestep, + std::size_t last_timestep, + std::size_t step_size) + : _start(first_timestep), + _end(last_timestep), + _step_size(step_size), + _time_unit(TimeStepType::NONE) { } @@ -53,22 +61,36 @@ SensorData::~SensorData() } } - -void SensorData::addTimeSeries( const std::string &data_name, std::vector<float> *data, const std::string &data_unit_string ) +void SensorData::addTimeSeries(const std::string& data_name, + std::vector<float>* data, + const std::string& data_unit_string) { - this->addTimeSeries(SensorData::convertString2SensorDataType(data_name), data, data_unit_string); + this->addTimeSeries(SensorData::convertString2SensorDataType(data_name), + data, + data_unit_string); } -void SensorData::addTimeSeries(SensorDataType data_name, std::vector<float> *data, const std::string &data_unit_string) +void SensorData::addTimeSeries(SensorDataType data_name, + std::vector<float>* data, + const std::string& data_unit_string) { - if (_step_size>0) { - if (((_end-_start)/_step_size) != data->size()) { - WARN("Warning in SensorData::addTimeSeries() - Lengths of time series does not match number of time steps."); + if (_step_size > 0) + { + if (((_end - _start) / _step_size) != data->size()) + { + WARN( + "Warning in SensorData::addTimeSeries() - Lengths of time " + "series does not match number of time steps."); return; } - } else { - if (data->size() != _time_steps.size()) { - WARN("Warning in SensorData::addTimeSeries() - Lengths of time series does not match number of time steps."); + } + else + { + if (data->size() != _time_steps.size()) + { + WARN( + "Warning in SensorData::addTimeSeries() - Lengths of time " + "series does not match number of time steps."); return; } } @@ -78,9 +100,10 @@ void SensorData::addTimeSeries(SensorDataType data_name, std::vector<float> *dat _data_unit_string.push_back(data_unit_string); } -const std::vector<float>* SensorData::getTimeSeries(SensorDataType time_series_name) const +const std::vector<float>* SensorData::getTimeSeries( + SensorDataType time_series_name) const { - for (std::size_t i=0; i<_vec_names.size(); i++) + for (std::size_t i = 0; i < _vec_names.size(); i++) { if (time_series_name == _vec_names[i]) { @@ -92,9 +115,9 @@ const std::vector<float>* SensorData::getTimeSeries(SensorDataType time_series_n return nullptr; } -int SensorData::readDataFromFile(const std::string &file_name) +int SensorData::readDataFromFile(const std::string& file_name) { - std::ifstream in( file_name.c_str() ); + std::ifstream in(file_name.c_str()); if (!in.is_open()) { @@ -108,7 +131,7 @@ int SensorData::readDataFromFile(const std::string &file_name) /* first line contains field names */ std::getline(in, line); std::list<std::string> fields = BaseLib::splitString(line, '\t'); - std::list<std::string>::const_iterator it (fields.begin()); + std::list<std::string>::const_iterator it(fields.begin()); std::size_t nFields = fields.size(); if (nFields < 2) @@ -116,12 +139,13 @@ int SensorData::readDataFromFile(const std::string &file_name) return 0; } - std::size_t nDataArrays(nFields-1); + std::size_t nDataArrays(nFields - 1); - //create vectors necessary to hold the data - for (std::size_t i=0; i<nDataArrays; i++) + // create vectors necessary to hold the data + for (std::size_t i = 0; i < nDataArrays; i++) { - this->_vec_names.push_back(SensorData::convertString2SensorDataType(*++it)); + this->_vec_names.push_back( + SensorData::convertString2SensorDataType(*++it)); this->_data_unit_string.emplace_back(""); auto* data = new std::vector<float>; this->_data_vecs.push_back(data); @@ -135,7 +159,9 @@ int SensorData::readDataFromFile(const std::string &file_name) { it = fields.begin(); std::size_t pos(it->rfind(".")); - std::size_t current_time_step = (pos == std::string::npos) ? atoi((it++)->c_str()) : BaseLib::strDate2int(*it++); + std::size_t current_time_step = (pos == std::string::npos) + ? atoi((it++)->c_str()) + : BaseLib::strDate2int(*it++); this->_time_steps.push_back(current_time_step); for (std::size_t i = 0; i < nDataArrays; i++) @@ -153,7 +179,7 @@ int SensorData::readDataFromFile(const std::string &file_name) in.close(); this->_start = this->_time_steps[0]; - this->_end = this->_time_steps[this->_time_steps.size()-1]; + this->_end = this->_time_steps[this->_time_steps.size() - 1]; return 1; } @@ -176,7 +202,7 @@ std::string SensorData::convertSensorDataType2String(SensorDataType t) return "Unknown"; } -SensorDataType SensorData::convertString2SensorDataType(const std::string &s) +SensorDataType SensorData::convertString2SensorDataType(const std::string& s) { if (s == "Evaporation" || s == "EVAPORATION") { @@ -192,4 +218,3 @@ SensorDataType SensorData::convertString2SensorDataType(const std::string &s) } return SensorDataType::OTHER; } - diff --git a/GeoLib/SimplePolygonTree.cpp b/GeoLib/SimplePolygonTree.cpp index ff4ef96db30734ae28a6877b2d7e4130aa8a60d5..5cb1fdf382fb804b7d5fc178448a47d15287758a 100644 --- a/GeoLib/SimplePolygonTree.cpp +++ b/GeoLib/SimplePolygonTree.cpp @@ -16,42 +16,52 @@ namespace GeoLib { -SimplePolygonTree::SimplePolygonTree(Polygon * polygon, SimplePolygonTree * parent) : - _node_polygon (polygon), _parent (parent) -{} +SimplePolygonTree::SimplePolygonTree(Polygon* polygon, + SimplePolygonTree* parent) + : _node_polygon(polygon), _parent(parent) +{ +} SimplePolygonTree::~SimplePolygonTree() { - for (auto * child : _children) { + for (auto* child : _children) + { delete child; } } -bool SimplePolygonTree::isPolygonInside (const SimplePolygonTree* polygon_hierarchy) const +bool SimplePolygonTree::isPolygonInside( + const SimplePolygonTree* polygon_hierarchy) const { - return _node_polygon->isPolylineInPolygon(*(polygon_hierarchy->getPolygon())); + return _node_polygon->isPolylineInPolygon( + *(polygon_hierarchy->getPolygon())); } -void SimplePolygonTree::insertSimplePolygonTree (SimplePolygonTree* polygon_hierarchy) +void SimplePolygonTree::insertSimplePolygonTree( + SimplePolygonTree* polygon_hierarchy) { - const Polygon* polygon (polygon_hierarchy->getPolygon()); - bool nfound (true); - for (std::list<SimplePolygonTree*>::const_iterator it (_children.begin()); - it != _children.end() && nfound; ++it) { - if (((*it)->getPolygon())->isPolylineInPolygon (*(polygon))) { - (*it)->insertSimplePolygonTree (polygon_hierarchy); + const Polygon* polygon(polygon_hierarchy->getPolygon()); + bool nfound(true); + for (std::list<SimplePolygonTree*>::const_iterator it(_children.begin()); + it != _children.end() && nfound; + ++it) + { + if (((*it)->getPolygon())->isPolylineInPolygon(*(polygon))) + { + (*it)->insertSimplePolygonTree(polygon_hierarchy); nfound = false; } } - if (nfound) { - _children.push_back (polygon_hierarchy); + if (nfound) + { + _children.push_back(polygon_hierarchy); polygon_hierarchy->setParent(this); } } -const Polygon* SimplePolygonTree::getPolygon () const +const Polygon* SimplePolygonTree::getPolygon() const { return _node_polygon; } -} // end namespace GeoLib +} // end namespace GeoLib diff --git a/GeoLib/Station.cpp b/GeoLib/Station.cpp index 0be09c81eb7945dbcc275fe165da615fb019c0aa..b32c38e8a497d631f3d08bc53402783bc4a6e7a5 100644 --- a/GeoLib/Station.cpp +++ b/GeoLib/Station.cpp @@ -18,7 +18,6 @@ #include <utility> #include "BaseLib/Logging.h" - #include "BaseLib/StringTools.h" namespace GeoLib @@ -26,25 +25,28 @@ namespace GeoLib Station::Station(double x, double y, double z, std::string name) : Point(x, y, z), _name(std::move(name)) -{} +{ +} Station::Station(Point* coords, std::string name) : Point(*coords), _name(std::move(name)) -{} +{ +} Station::Station(Station const& src) : Point(src), _name(src._name), _type(src._type), _station_value(src._station_value) -{} +{ +} Station::~Station() { delete this->_sensor_data; } -Station* Station::createStation(const std::string & line) +Station* Station::createStation(const std::string& line) { Station* station = new Station(); std::list<std::string> fields = BaseLib::splitString(line, '\t'); @@ -53,8 +55,10 @@ Station* Station::createStation(const std::string & line) { auto it = fields.begin(); station->_name = *it; - (*station)[0] = std::strtod((BaseLib::replaceString(",", ".", *(++it))).c_str(), nullptr); - (*station)[1] = std::strtod((BaseLib::replaceString(",", ".", *(++it))).c_str(), nullptr); + (*station)[0] = std::strtod( + (BaseLib::replaceString(",", ".", *(++it))).c_str(), nullptr); + (*station)[1] = std::strtod( + (BaseLib::replaceString(",", ".", *(++it))).c_str(), nullptr); if (++it != fields.end()) { (*station)[2] = std::strtod( diff --git a/GeoLib/StationBorehole.cpp b/GeoLib/StationBorehole.cpp index 43761f69c8b7e118576c46cb2c6a60cef0123bb7..ab69083709b35c286f9d31aeb50976bd5d71d5fb 100644 --- a/GeoLib/StationBorehole.cpp +++ b/GeoLib/StationBorehole.cpp @@ -19,14 +19,12 @@ #include <cstdlib> #include <fstream> +#include "BaseLib/DateTools.h" #include "BaseLib/Logging.h" - #include "BaseLib/StringTools.h" -#include "BaseLib/DateTools.h" namespace GeoLib { - //////////////////////// // The Borehole class // //////////////////////// @@ -54,7 +52,7 @@ StationBorehole::~StationBorehole() } } -StationBorehole* StationBorehole::createStation(const std::string &line) +StationBorehole* StationBorehole::createStation(const std::string& line) { StationBorehole* borehole = new StationBorehole(); std::list<std::string> fields = BaseLib::splitString(line, '\t'); @@ -63,13 +61,17 @@ StationBorehole* StationBorehole::createStation(const std::string &line) { borehole->_name = fields.front(); fields.pop_front(); - (*borehole)[0] = strtod(BaseLib::replaceString(",", ".", fields.front()).c_str(), nullptr); + (*borehole)[0] = strtod( + BaseLib::replaceString(",", ".", fields.front()).c_str(), nullptr); fields.pop_front(); - (*borehole)[1] = strtod(BaseLib::replaceString(",", ".", fields.front()).c_str(), nullptr); + (*borehole)[1] = strtod( + BaseLib::replaceString(",", ".", fields.front()).c_str(), nullptr); fields.pop_front(); - (*borehole)[2] = strtod(BaseLib::replaceString(",", ".", fields.front()).c_str(), nullptr); + (*borehole)[2] = strtod( + BaseLib::replaceString(",", ".", fields.front()).c_str(), nullptr); fields.pop_front(); - borehole->_depth = strtod(BaseLib::replaceString(",", ".", fields.front()).c_str(), nullptr); + borehole->_depth = strtod( + BaseLib::replaceString(",", ".", fields.front()).c_str(), nullptr); fields.pop_front(); if (fields.empty()) { @@ -90,18 +92,18 @@ StationBorehole* StationBorehole::createStation(const std::string &line) return borehole; } -StationBorehole* StationBorehole::createStation(const std::string &name, +StationBorehole* StationBorehole::createStation(const std::string& name, double x, double y, double z, double depth, - const std::string &date) + const std::string& date) { StationBorehole* station = new StationBorehole(); - station->_name = name; - (*station)[0] = x; - (*station)[1] = y; - (*station)[2] = z; + station->_name = name; + (*station)[0] = x; + (*station)[1] = y; + (*station)[2] = z; station->_depth = depth; if (date != "0000-00-00") { @@ -110,7 +112,8 @@ StationBorehole* StationBorehole::createStation(const std::string &name, return station; } -void StationBorehole::addSoilLayer ( double thickness, const std::string &soil_name) +void StationBorehole::addSoilLayer(double thickness, + const std::string& soil_name) { /* // TF - Altmark @@ -132,16 +135,19 @@ void StationBorehole::addSoilLayer ( double thickness, const std::string &soil_n addSoilLayer((*this)[0], (*this)[1], (*this)[2], ""); } - std::size_t idx (_profilePntVec.size()); + std::size_t idx(_profilePntVec.size()); double x((*_profilePntVec[idx - 1])[0]); double y((*_profilePntVec[idx - 1])[1]); double z((*_profilePntVec[0])[2] - thickness); - addSoilLayer (x, y, z, soil_name); + addSoilLayer(x, y, z, soil_name); } -void StationBorehole::addSoilLayer ( double x, double y, double z, const std::string &soil_name) +void StationBorehole::addSoilLayer(double x, + double y, + double z, + const std::string& soil_name) { - _profilePntVec.push_back (new Point (x, y, z)); + _profilePntVec.push_back(new Point(x, y, z)); _soilName.push_back(soil_name); } diff --git a/GeoLib/Surface.cpp b/GeoLib/Surface.cpp index 7fd2b5084342c63614521c276bd5575e5a5e1c60..92dd2b558d56f0eb6ddd5c2eef2b2278a79a477b 100644 --- a/GeoLib/Surface.cpp +++ b/GeoLib/Surface.cpp @@ -7,18 +7,17 @@ * http://www.opengeosys.org/project/license */ -#include <list> - #include "Surface.h" +#include <list> + // GeoLib #include "AABB.h" +#include "AnalyticalGeometry.h" #include "Polygon.h" +#include "Polyline.h" #include "SurfaceGrid.h" -#include "AnalyticalGeometry.h" - #include "Triangle.h" -#include "Polyline.h" namespace GeoLib { diff --git a/GeoLib/SurfaceGrid.cpp b/GeoLib/SurfaceGrid.cpp index c48462e66161f1258a235d516150e07f3b881919..c904e991d979ca1186f88fd83eef9772d5951f2e 100644 --- a/GeoLib/SurfaceGrid.cpp +++ b/GeoLib/SurfaceGrid.cpp @@ -14,47 +14,50 @@ #include <algorithm> #include <bitset> -#include "BaseLib/Logging.h" - #include "BaseLib/Error.h" - +#include "BaseLib/Logging.h" #include "MathLib/Point3d.h" - #include "Surface.h" #include "Triangle.h" -namespace GeoLib { - -SurfaceGrid::SurfaceGrid(Surface const*const sfc) : - AABB(sfc->getAABB()), _n_steps({{1,1,1}}) +namespace GeoLib +{ +SurfaceGrid::SurfaceGrid(Surface const* const sfc) + : AABB(sfc->getAABB()), _n_steps({{1, 1, 1}}) { // enlarge the bounding, such that the points with maximal coordinates // fits into the grid - for (std::size_t k(0); k<3; ++k) { + for (std::size_t k(0); k < 3; ++k) + { _max_pnt[k] += std::abs(_max_pnt[k]) * 1e-6; - if (std::abs(_max_pnt[k]) < std::numeric_limits<double>::epsilon()) { + if (std::abs(_max_pnt[k]) < std::numeric_limits<double>::epsilon()) + { _max_pnt[k] = (_max_pnt[k] - _min_pnt[k]) * (1.0 + 1e-6); } } - std::array<double, 3> delta{{ _max_pnt[0] - _min_pnt[0], - _max_pnt[1] - _min_pnt[1], _max_pnt[2] - _min_pnt[2] }}; + std::array<double, 3> delta{{_max_pnt[0] - _min_pnt[0], + _max_pnt[1] - _min_pnt[1], + _max_pnt[2] - _min_pnt[2]}}; - if (delta[0] < std::numeric_limits<double>::epsilon()) { + if (delta[0] < std::numeric_limits<double>::epsilon()) + { const double max_delta(std::max(delta[1], delta[2])); _min_pnt[0] -= max_delta * 0.5e-3; _max_pnt[0] += max_delta * 0.5e-3; delta[0] = _max_pnt[0] - _min_pnt[0]; } - if (delta[1] < std::numeric_limits<double>::epsilon()) { + if (delta[1] < std::numeric_limits<double>::epsilon()) + { const double max_delta(std::max(delta[0], delta[2])); _min_pnt[1] -= max_delta * 0.5e-3; _max_pnt[1] += max_delta * 0.5e-3; delta[1] = _max_pnt[1] - _min_pnt[1]; } - if (delta[2] < std::numeric_limits<double>::epsilon()) { + if (delta[2] < std::numeric_limits<double>::epsilon()) + { const double max_delta(std::max(delta[0], delta[1])); _min_pnt[2] -= max_delta * 0.5e-3; _max_pnt[2] += max_delta * 0.5e-3; @@ -64,7 +67,7 @@ SurfaceGrid::SurfaceGrid(Surface const*const sfc) : const std::size_t n_tris(sfc->getNumberOfTriangles()); const std::size_t n_tris_per_cell(5); - std::bitset<3> dim; // all bits are set to zero. + std::bitset<3> dim; // all bits are set to zero. for (std::size_t k(0); k < 3; ++k) { if (std::abs(delta[k]) >= std::numeric_limits<double>::epsilon()) @@ -75,61 +78,79 @@ SurfaceGrid::SurfaceGrid(Surface const*const sfc) : // *** condition: n_tris / n_cells < n_tris_per_cell // where n_cells = _n_steps[0] * _n_steps[1] * _n_steps[2] - // *** with _n_steps[0] = ceil(pow(n_tris*delta[0]*delta[0]/(n_tris_per_cell*delta[1]*delta[2]), 1/3.))); + // *** with _n_steps[0] = + // ceil(pow(n_tris*delta[0]*delta[0]/(n_tris_per_cell*delta[1]*delta[2]), + // 1/3.))); // _n_steps[1] = _n_steps[0] * delta[1]/delta[0], // _n_steps[2] = _n_steps[0] * delta[2]/delta[0] - auto sc_ceil = [](double v){ + auto sc_ceil = [](double v) { return static_cast<std::size_t>(std::ceil(v)); }; - switch (dim.count()) { - case 3: // 3d case - _n_steps[0] = sc_ceil(std::cbrt( - n_tris*delta[0]*delta[0]/(n_tris_per_cell*delta[1]*delta[2]))); - _n_steps[1] = sc_ceil(_n_steps[0] * std::min(delta[1] / delta[0], 100.0)); - _n_steps[2] = sc_ceil(_n_steps[0] * std::min(delta[2] / delta[0], 100.0)); - break; - case 2: // 2d cases - if (dim[0] && dim[2]) { // 2d case: xz plane, y = const - _n_steps[0] = sc_ceil(std::sqrt(n_tris*delta[0]/(n_tris_per_cell*delta[2]))); - _n_steps[2] = sc_ceil(_n_steps[0]*delta[2]/delta[0]); - } - else if (dim[0] && dim[1]) { // 2d case: xy plane, z = const - _n_steps[0] = sc_ceil(std::sqrt(n_tris*delta[0]/(n_tris_per_cell*delta[1]))); - _n_steps[1] = sc_ceil(_n_steps[0] * delta[1]/delta[0]); - } - else if (dim[1] && dim[2]) { // 2d case: yz plane, x = const - _n_steps[1] = sc_ceil(std::sqrt(n_tris*delta[1]/(n_tris_per_cell*delta[2]))); - _n_steps[2] = sc_ceil(n_tris * delta[2] / (n_tris_per_cell*delta[1])); - } - break; - case 1: // 1d cases - for (std::size_t k(0); k<3; ++k) { - if (dim[k]) { - _n_steps[k] = sc_ceil(static_cast<double>(n_tris)/n_tris_per_cell); + switch (dim.count()) + { + case 3: // 3d case + _n_steps[0] = + sc_ceil(std::cbrt(n_tris * delta[0] * delta[0] / + (n_tris_per_cell * delta[1] * delta[2]))); + _n_steps[1] = + sc_ceil(_n_steps[0] * std::min(delta[1] / delta[0], 100.0)); + _n_steps[2] = + sc_ceil(_n_steps[0] * std::min(delta[2] / delta[0], 100.0)); + break; + case 2: // 2d cases + if (dim[0] && dim[2]) + { // 2d case: xz plane, y = const + _n_steps[0] = sc_ceil(std::sqrt(n_tris * delta[0] / + (n_tris_per_cell * delta[2]))); + _n_steps[2] = sc_ceil(_n_steps[0] * delta[2] / delta[0]); + } + else if (dim[0] && dim[1]) + { // 2d case: xy plane, z = const + _n_steps[0] = sc_ceil(std::sqrt(n_tris * delta[0] / + (n_tris_per_cell * delta[1]))); + _n_steps[1] = sc_ceil(_n_steps[0] * delta[1] / delta[0]); + } + else if (dim[1] && dim[2]) + { // 2d case: yz plane, x = const + _n_steps[1] = sc_ceil(std::sqrt(n_tris * delta[1] / + (n_tris_per_cell * delta[2]))); + _n_steps[2] = + sc_ceil(n_tris * delta[2] / (n_tris_per_cell * delta[1])); + } + break; + case 1: // 1d cases + for (std::size_t k(0); k < 3; ++k) + { + if (dim[k]) + { + _n_steps[k] = + sc_ceil(static_cast<double>(n_tris) / n_tris_per_cell); + } } - } } // some frequently used expressions to fill the grid vectors - for (std::size_t k(0); k<3; k++) { + for (std::size_t k(0); k < 3; k++) + { _step_sizes[k] = delta[k] / _n_steps[k]; _inverse_step_sizes[k] = 1.0 / _step_sizes[k]; } - _triangles_in_grid_box.resize(_n_steps[0]*_n_steps[1]*_n_steps[2]); + _triangles_in_grid_box.resize(_n_steps[0] * _n_steps[1] * _n_steps[2]); sortTrianglesInGridCells(sfc); } -void SurfaceGrid::sortTrianglesInGridCells(Surface const*const sfc) +void SurfaceGrid::sortTrianglesInGridCells(Surface const* const sfc) { - for (std::size_t l(0); l<sfc->getNumberOfTriangles(); l++) { - if (! sortTriangleInGridCells((*sfc)[l])) { + for (std::size_t l(0); l < sfc->getNumberOfTriangles(); l++) + { + if (!sortTriangleInGridCells((*sfc)[l])) + { Point const& p0(*((*sfc)[l]->getPoint(0))); Point const& p1(*((*sfc)[l]->getPoint(1))); Point const& p2(*((*sfc)[l]->getPoint(2))); ERR("Sorting triangle {:d} [({:f},{:f},{:f}), ({:f},{:f},{:f}), " - "({:f},{:f},{:f}) into " - "grid.", + "({:f},{:f},{:f}) into grid.", l, p0[0], p0[1], p0[2], p1[0], p1[1], p1[2], p2[0], p2[1], p2[2]); OGS_FATAL(""); @@ -137,7 +158,7 @@ void SurfaceGrid::sortTrianglesInGridCells(Surface const*const sfc) } } -bool SurfaceGrid::sortTriangleInGridCells(Triangle const*const triangle) +bool SurfaceGrid::sortTriangleInGridCells(Triangle const* const triangle) { // compute grid coordinates for each triangle point std::optional<std::array<std::size_t, 3> const> c_p0( @@ -160,20 +181,30 @@ bool SurfaceGrid::sortTriangleInGridCells(Triangle const*const triangle) } // determine interval in grid (grid cells the triangle will be inserted) - std::size_t const i_min(std::min(std::min((*c_p0)[0], (*c_p1)[0]), (*c_p2)[0])); - std::size_t const i_max(std::max(std::max((*c_p0)[0], (*c_p1)[0]), (*c_p2)[0])); - std::size_t const j_min(std::min(std::min((*c_p0)[1], (*c_p1)[1]), (*c_p2)[1])); - std::size_t const j_max(std::max(std::max((*c_p0)[1], (*c_p1)[1]), (*c_p2)[1])); - std::size_t const k_min(std::min(std::min((*c_p0)[2], (*c_p1)[2]), (*c_p2)[2])); - std::size_t const k_max(std::max(std::max((*c_p0)[2], (*c_p1)[2]), (*c_p2)[2])); + std::size_t const i_min( + std::min(std::min((*c_p0)[0], (*c_p1)[0]), (*c_p2)[0])); + std::size_t const i_max( + std::max(std::max((*c_p0)[0], (*c_p1)[0]), (*c_p2)[0])); + std::size_t const j_min( + std::min(std::min((*c_p0)[1], (*c_p1)[1]), (*c_p2)[1])); + std::size_t const j_max( + std::max(std::max((*c_p0)[1], (*c_p1)[1]), (*c_p2)[1])); + std::size_t const k_min( + std::min(std::min((*c_p0)[2], (*c_p1)[2]), (*c_p2)[2])); + std::size_t const k_max( + std::max(std::max((*c_p0)[2], (*c_p1)[2]), (*c_p2)[2])); - const std::size_t n_plane(_n_steps[0]*_n_steps[1]); + const std::size_t n_plane(_n_steps[0] * _n_steps[1]); // insert the triangle into the grid cells - for (std::size_t i(i_min); i<=i_max; i++) { - for (std::size_t j(j_min); j<=j_max; j++) { - for (std::size_t k(k_min); k<=k_max; k++) { - _triangles_in_grid_box[i+j*_n_steps[0]+k*n_plane].push_back(triangle); + for (std::size_t i(i_min); i <= i_max; i++) + { + for (std::size_t j(j_min); j <= j_max; j++) + { + for (std::size_t k(k_min); k <= k_max; k++) + { + _triangles_in_grid_box[i + j * _n_steps[0] + k * n_plane] + .push_back(triangle); } } } @@ -184,13 +215,17 @@ bool SurfaceGrid::sortTriangleInGridCells(Triangle const*const triangle) std::optional<std::array<std::size_t, 3>> SurfaceGrid::getGridCellCoordinates( MathLib::Point3d const& p) const { - std::array<std::size_t, 3> coords{{ - static_cast<std::size_t>((p[0]-_min_pnt[0]) * _inverse_step_sizes[0]), - static_cast<std::size_t>((p[1]-_min_pnt[1]) * _inverse_step_sizes[1]), - static_cast<std::size_t>((p[2]-_min_pnt[2]) * _inverse_step_sizes[2]) - }}; + std::array<std::size_t, 3> coords{ + {static_cast<std::size_t>((p[0] - _min_pnt[0]) * + _inverse_step_sizes[0]), + static_cast<std::size_t>((p[1] - _min_pnt[1]) * + _inverse_step_sizes[1]), + static_cast<std::size_t>((p[2] - _min_pnt[2]) * + _inverse_step_sizes[2])}}; - if (coords[0]>=_n_steps[0] || coords[1]>=_n_steps[1] || coords[2]>=_n_steps[2]) { + if (coords[0] >= _n_steps[0] || coords[1] >= _n_steps[1] || + coords[2] >= _n_steps[2]) + { DBUG( "Computed indices ({:d},{:d},{:d}), max grid cell indices " "({:d},{:d},{:d})", @@ -206,13 +241,16 @@ bool SurfaceGrid::isPointInSurface(MathLib::Point3d const& pnt, { std::optional<std::array<std::size_t, 3>> optional_c( getGridCellCoordinates(pnt)); - if (!optional_c) { + if (!optional_c) + { return false; } std::array<std::size_t, 3> c(optional_c.value()); - std::size_t const grid_cell_idx(c[0]+c[1]*_n_steps[0]+c[2]*_n_steps[0]*_n_steps[1]); - std::vector<Triangle const*> const& triangles(_triangles_in_grid_box[grid_cell_idx]); + std::size_t const grid_cell_idx(c[0] + c[1] * _n_steps[0] + + c[2] * _n_steps[0] * _n_steps[1]); + std::vector<Triangle const*> const& triangles( + _triangles_in_grid_box[grid_cell_idx]); auto const it = std::find_if(triangles.begin(), triangles.end(), [eps, pnt](auto const* triangle) { return triangle->containsPoint(pnt, eps); @@ -220,4 +258,4 @@ bool SurfaceGrid::isPointInSurface(MathLib::Point3d const& pnt, return it != triangles.end(); } -} // end namespace GeoLib +} // end namespace GeoLib diff --git a/GeoLib/Triangle.cpp b/GeoLib/Triangle.cpp index 3de2c15894eb15efbaafc3a828ea67f4212f9de9..e6e37a1c5f91f4527d2f304515ec31d5b70e0aca 100644 --- a/GeoLib/Triangle.cpp +++ b/GeoLib/Triangle.cpp @@ -11,19 +11,19 @@ #include <Eigen/Dense> -#include "Point.h" #include "AnalyticalGeometry.h" - #include "MathLib/GeometricBasics.h" +#include "Point.h" -namespace GeoLib { - -Triangle::Triangle (std::vector<Point *> const &pnt_vec, - std::size_t pnt_a, std::size_t pnt_b, std::size_t pnt_c) : - _pnts(pnt_vec), _pnt_ids( {{pnt_a, pnt_b, pnt_c}} ) +namespace GeoLib +{ +Triangle::Triangle(std::vector<Point*> const& pnt_vec, std::size_t pnt_a, + std::size_t pnt_b, std::size_t pnt_c) + : _pnts(pnt_vec), _pnt_ids({{pnt_a, pnt_b, pnt_c}}) { assert(!_pnts.empty()); - assert (pnt_a < _pnts.size() && pnt_b < _pnts.size() && pnt_c < _pnts.size()); + assert(pnt_a < _pnts.size() && pnt_b < _pnts.size() && + pnt_c < _pnts.size()); } bool Triangle::containsPoint(MathLib::Point3d const& q, double eps) const diff --git a/MaterialLib/Adsorption/Adsorption.cpp b/MaterialLib/Adsorption/Adsorption.cpp index af782a26f2c5b3887c3724108f0020d5289b8a22..5bae191d3d30af28eb2e648fe02ac368f1a1f2d4 100644 --- a/MaterialLib/Adsorption/Adsorption.cpp +++ b/MaterialLib/Adsorption/Adsorption.cpp @@ -8,46 +8,54 @@ */ #include "Adsorption.h" + #include "BaseLib/Logging.h" #include "MaterialLib/PhysicalConstant.h" -namespace { - const double k_rate = 6.0e-3; // to be specified +namespace +{ +const double k_rate = 6.0e-3; // to be specified - template <typename T> - T square(const T& v) - { - return v * v; - } +template <typename T> +T square(const T& v) +{ + return v * v; } +} // namespace namespace Adsorption { - -//Saturation pressure for water used in Nunez +// Saturation pressure for water used in Nunez double AdsorptionReaction::getEquilibriumVapourPressure(const double T_Ads) { // critical T and p - const double Tc = 647.3; // K - const double pc = 221.2e5; // Pa + const double Tc = 647.3; // K + const double pc = 221.2e5; // Pa // dimensionless T - const double Tr = T_Ads/Tc; + const double Tr = T_Ads / Tc; const double theta = 1. - Tr; // empirical constants - const double c[] = {-7.69123,-26.08023,-168.17065,64.23285,-118.96462,4.16717,20.97506,1.0e9,6.0}; - const double K[] = {c[0]*theta + c[1]*pow(theta,2) + c[2]*pow(theta,3) + c[3]*pow(theta,4) + c[4]*pow(theta,5), - 1. + c[5]*theta + c[6]*pow(theta,2)}; - - const double exponent = K[0]/(K[1]*Tr) - theta/(c[7]*pow(theta,2) + c[8]); - return pc * exp(exponent); // in Pa + const double c[] = {-7.69123, -26.08023, -168.17065, 64.23285, -118.96462, + 4.16717, 20.97506, 1.0e9, 6.0}; + const double K[] = {c[0] * theta + c[1] * pow(theta, 2) + + c[2] * pow(theta, 3) + c[3] * pow(theta, 4) + + c[4] * pow(theta, 5), + 1. + c[5] * theta + c[6] * pow(theta, 2)}; + + const double exponent = + K[0] / (K[1] * Tr) - theta / (c[7] * pow(theta, 2) + c[8]); + return pc * exp(exponent); // in Pa } // Evaporation enthalpy of water from Nunez -double AdsorptionReaction::getEvaporationEnthalpy(double T_Ads) // in kJ/kg +double AdsorptionReaction::getEvaporationEnthalpy(double T_Ads) // in kJ/kg { T_Ads -= 273.15; - if (T_Ads <= 10.){ - const double c[] = {2.50052e3,-2.1068,-3.57500e-1,1.905843e-1,-5.11041e-2,7.52511e-3,-6.14313e-4,2.59674e-5,-4.421e-7}; + if (T_Ads <= 10.) + { + const double c[] = {2.50052e3, -2.1068, -3.57500e-1, + 1.905843e-1, -5.11041e-2, 7.52511e-3, + -6.14313e-4, 2.59674e-5, -4.421e-7}; double hv = 0.; for (size_t i = 0; i < sizeof(c) / sizeof(c[0]); i++) { @@ -57,7 +65,9 @@ double AdsorptionReaction::getEvaporationEnthalpy(double T_Ads) // in kJ/kg } if (T_Ads <= 300.) { - const double c[] = {2.50043e3,-2.35209,1.91685e-4,-1.94824e-5,2.89539e-7,-3.51199e-9,2.06926e-11,-6.4067e-14,8.518e-17,1.558e-20,-1.122e-22}; + const double c[] = {2.50043e3, -2.35209, 1.91685e-4, -1.94824e-5, + 2.89539e-7, -3.51199e-9, 2.06926e-11, -6.4067e-14, + 8.518e-17, 1.558e-20, -1.122e-22}; double hv = 0.; for (size_t i = 0; i < sizeof(c) / sizeof(c[0]); i++) { @@ -71,22 +81,22 @@ double AdsorptionReaction::getEvaporationEnthalpy(double T_Ads) // in kJ/kg (1. + c[1] * T_Ads + c[3] * pow(T_Ads, 2) + c[5] * pow(T_Ads, 3))); } - -double AdsorptionReaction::getMolarFraction(double xm, double M_this, double M_other) +double AdsorptionReaction::getMolarFraction(double xm, double M_this, + double M_other) { - return M_other*xm/(M_other*xm + M_this*(1.0-xm)); + return M_other * xm / (M_other * xm + M_this * (1.0 - xm)); } - -double AdsorptionReaction::dMolarFraction(double xm, double M_this, double M_other) +double AdsorptionReaction::dMolarFraction(double xm, double M_this, + double M_other) { - return M_other * M_this - / square(M_other * xm + M_this * (1.0 - xm)); + return M_other * M_this / square(M_other * xm + M_this * (1.0 - xm)); } - -double AdsorptionReaction::getReactionRate(const double p_Ads, const double T_Ads, - const double M_Ads, const double loading) const +double AdsorptionReaction::getReactionRate(const double p_Ads, + const double T_Ads, + const double M_Ads, + const double loading) const { const double A = getPotential(p_Ads, T_Ads, M_Ads); double C_eq = getAdsorbateDensity(T_Ads) * characteristicCurve(A); @@ -95,34 +105,35 @@ double AdsorptionReaction::getReactionRate(const double p_Ads, const double T_Ad C_eq = 0.0; } - return k_rate * (C_eq - loading); // scaled with mass fraction - // this the rate in terms of loading! + return k_rate * (C_eq - loading); // scaled with mass fraction + // this the rate in terms of loading! } // Evaluate adsorbtion potential A double AdsorptionReaction::getPotential(const double p_Ads, double T_Ads, const double M_Ads) { - double A = MaterialLib::PhysicalConstant::IdealGasConstant * T_Ads * log(getEquilibriumVapourPressure(T_Ads)/p_Ads) / (M_Ads*1.e3); // in kJ/kg = J/g + double A = MaterialLib::PhysicalConstant::IdealGasConstant * T_Ads * + log(getEquilibriumVapourPressure(T_Ads) / p_Ads) / + (M_Ads * 1.e3); // in kJ/kg = J/g return A; } - -double AdsorptionReaction::getLoading(const double rho_curr, const double rho_dry) +double AdsorptionReaction::getLoading(const double rho_curr, + const double rho_dry) { return rho_curr / rho_dry - 1.0; } - // Calculate sorption entropy double AdsorptionReaction::getEntropy(const double T_Ads, const double A) const { const double epsilon = 1.0e-8; //* // This change will also change simulation results. - const double W_p = characteristicCurve(A+epsilon); - const double W_m = characteristicCurve(A-epsilon); - const double dAdlnW = 2.0*epsilon/(log(W_p/W_m)); + const double W_p = characteristicCurve(A + epsilon); + const double W_m = characteristicCurve(A - epsilon); + const double dAdlnW = 2.0 * epsilon / (log(W_p / W_m)); // */ if (W_p <= 0.0 || W_m <= 0.0) @@ -135,19 +146,21 @@ double AdsorptionReaction::getEntropy(const double T_Ads, const double A) const return dAdlnW * getAlphaT(T_Ads); } - -//Calculate sorption enthalpy -double AdsorptionReaction::getEnthalpy(const double p_Ads, const double T_Ads, const double M_Ads) const +// Calculate sorption enthalpy +double AdsorptionReaction::getEnthalpy(const double p_Ads, const double T_Ads, + const double M_Ads) const { - // TODO [CL] consider using A as obtained from current loading (needs inverse CC A(W)) instead of p_Vapour, T_Vapour + // TODO [CL] consider using A as obtained from current loading (needs + // inverse CC A(W)) instead of p_Vapour, T_Vapour const double A = getPotential(p_Ads, T_Ads, M_Ads); - return (getEvaporationEnthalpy(T_Ads) + A - T_Ads * getEntropy(T_Ads,A))*1000.0; //in J/kg + return (getEvaporationEnthalpy(T_Ads) + A - T_Ads * getEntropy(T_Ads, A)) * + 1000.0; // in J/kg } - -double AdsorptionReaction::getEquilibriumLoading( - const double p_Ads, const double T_Ads, const double M_Ads) const +double AdsorptionReaction::getEquilibriumLoading(const double p_Ads, + const double T_Ads, + const double M_Ads) const { const double A = getPotential(p_Ads, T_Ads, M_Ads); return getAdsorbateDensity(T_Ads) * characteristicCurve(A); diff --git a/MaterialLib/Adsorption/Density100MPa.cpp b/MaterialLib/Adsorption/Density100MPa.cpp index 6267cda6a9c8964276403c6b44e57ce33a6d42fc..4b5d0bbb7eba7dfba9c2c114c7c53211ac73f792 100644 --- a/MaterialLib/Adsorption/Density100MPa.cpp +++ b/MaterialLib/Adsorption/Density100MPa.cpp @@ -11,48 +11,47 @@ namespace { - // NaX_HighP_polyfrac_CC.pickle // date extracted 2015-06-23 15:38:35 file mtime 2015-06-23 15:19:57 const double Density100MPa_c[] = { - 0.3490302932983226, /* a0 */ - -0.0014061345691831226, /* a1 */ - -0.0007399303393402753, /* a2 */ - 5.129318840267485e-09, /* a3 */ - 5.243619689772646e-07, /* a4 */ - 6.347011955956523e-10, /* a5 */ - -9.919599580166727e-11 /* a6 */ + 0.3490302932983226, /* a0 */ + -0.0014061345691831226, /* a1 */ + -0.0007399303393402753, /* a2 */ + 5.129318840267485e-09, /* a3 */ + 5.243619689772646e-07, /* a4 */ + 6.347011955956523e-10, /* a5 */ + -9.919599580166727e-11 /* a6 */ }; } // namespace namespace Adsorption { - double Density100MPa::getAdsorbateDensity(const double T_Ads) const { - return -0.0013*T_Ads*T_Ads + 0.3529*T_Ads + 1049.2; + return -0.0013 * T_Ads * T_Ads + 0.3529 * T_Ads + 1049.2; } // Thermal expansivity model for water found in the works of Hauer double Density100MPa::getAlphaT(const double T_Ads) const { - const double rho = -0.0013*T_Ads*T_Ads+0.3529*T_Ads+1049.2; - const double drhodT = -0.0026*T_Ads + 0.3529; + const double rho = -0.0013 * T_Ads * T_Ads + 0.3529 * T_Ads + 1049.2; + const double drhodT = -0.0026 * T_Ads + 0.3529; - return - drhodT / rho; + return -drhodT / rho; } // Characteristic curve. Return W (A) double Density100MPa::characteristicCurve(const double A) const { - double W = curvePolyfrac(Density100MPa_c, A); // cm^3/g + double W = curvePolyfrac(Density100MPa_c, A); // cm^3/g - if (W < 0.0) { - W = 0.0; // TODO [CL] debug output + if (W < 0.0) + { + W = 0.0; // TODO [CL] debug output } - return W/1.e3; // m^3/kg + return W / 1.e3; // m^3/kg } double Density100MPa::dCharacteristicCurve(const double A) const diff --git a/MaterialLib/Adsorption/DensityConst.cpp b/MaterialLib/Adsorption/DensityConst.cpp index 94f8e5c41b3ffb4d4c8c8fc77a5919efea910dee..986e9a72e27a5cf9acd7b8d8c228ff2bb14387f0 100644 --- a/MaterialLib/Adsorption/DensityConst.cpp +++ b/MaterialLib/Adsorption/DensityConst.cpp @@ -8,31 +8,30 @@ */ #include "DensityConst.h" + #include "DensityHauer.h" namespace { - // NaX_Constant_polyfrac_CC.pickle // date extracted 2015-06-23 15:38:35 file mtime 2015-06-23 15:20:05 const double DensityConst_c[] = { - 0.3824098506898007, /* a0 */ - -0.001316857559708455, /* a1 */ - -0.0007935756090263691, /* a2 */ - -1.1600036977157845e-07, /* a3 */ - 5.610354459181838e-07, /* a4 */ - 7.113664938298873e-10, /* a5 */ - -1.0668790477629686e-10 /* a6 */ + 0.3824098506898007, /* a0 */ + -0.001316857559708455, /* a1 */ + -0.0007935756090263691, /* a2 */ + -1.1600036977157845e-07, /* a3 */ + 5.610354459181838e-07, /* a4 */ + 7.113664938298873e-10, /* a5 */ + -1.0668790477629686e-10 /* a6 */ }; } // namespace namespace Adsorption { - double DensityConst::getAdsorbateDensity(const double /*T_Ads*/) const { - return rhoWaterHauer(150.0+273.15); + return rhoWaterHauer(150.0 + 273.15); } double DensityConst::getAlphaT(const double /*T_Ads*/) const @@ -43,13 +42,14 @@ double DensityConst::getAlphaT(const double /*T_Ads*/) const // Characteristic curve. Return W (A) double DensityConst::characteristicCurve(const double A) const { - double W = curvePolyfrac(DensityConst_c, A); //cm^3/g + double W = curvePolyfrac(DensityConst_c, A); // cm^3/g - if (W < 0.0) { - W = 0.0; // TODO [CL] debug output + if (W < 0.0) + { + W = 0.0; // TODO [CL] debug output } - return W/1.e3; // m^3/kg + return W / 1.e3; // m^3/kg } double DensityConst::dCharacteristicCurve(const double A) const diff --git a/MaterialLib/Adsorption/DensityCook.cpp b/MaterialLib/Adsorption/DensityCook.cpp index f51ccfcebe4bfd68bf49cc450c04828d912b95bf..a976ff90b13287da4e3919abc125c5aefecb8f8c 100644 --- a/MaterialLib/Adsorption/DensityCook.cpp +++ b/MaterialLib/Adsorption/DensityCook.cpp @@ -11,24 +11,22 @@ namespace { - // NaX_Dean_polyfrac_CC.pickle // date extracted 2015-06-23 15:38:35 file mtime 2015-06-23 15:19:42 const double DensityCook_c[] = { - 0.3632627555646154, /* a0 */ - -0.0014090624975800715, /* a1 */ - -0.0007717609035743321, /* a2 */ - 5.03634836561135e-09, /* a3 */ - 5.478509959282738e-07, /* a4 */ - 6.36458510620815e-10, /* a5 */ - -1.037977321231462e-10 /* a6 */ + 0.3632627555646154, /* a0 */ + -0.0014090624975800715, /* a1 */ + -0.0007717609035743321, /* a2 */ + 5.03634836561135e-09, /* a3 */ + 5.478509959282738e-07, /* a4 */ + 6.36458510620815e-10, /* a5 */ + -1.037977321231462e-10 /* a6 */ }; } // namespace namespace Adsorption { - double DensityCook::getAdsorbateDensity(const double T_Ads) const { return rhoWaterDean(T_Ads); @@ -42,13 +40,14 @@ double DensityCook::getAlphaT(const double T_Ads) const // Characteristic curve. Return W (A) double DensityCook::characteristicCurve(const double A) const { - double W = curvePolyfrac(DensityCook_c, A); //cm^3/g + double W = curvePolyfrac(DensityCook_c, A); // cm^3/g - if (W < 0.0) { - W = 0.0; // TODO [CL] debug output + if (W < 0.0) + { + W = 0.0; // TODO [CL] debug output } - return W/1.e3; //m^3/kg + return W / 1.e3; // m^3/kg } double DensityCook::dCharacteristicCurve(const double A) const diff --git a/MaterialLib/Adsorption/DensityDubinin.cpp b/MaterialLib/Adsorption/DensityDubinin.cpp index 6e972370fcb5c23eaa560f087bef5802a21635ea..52845cb452437a95af298e139ea71d7896458734 100644 --- a/MaterialLib/Adsorption/DensityDubinin.cpp +++ b/MaterialLib/Adsorption/DensityDubinin.cpp @@ -8,35 +8,35 @@ */ #include "DensityDubinin.h" -#include "MaterialLib/PhysicalConstant.h" -#include "DensityCook.h" + #include "Adsorption.h" +#include "DensityCook.h" +#include "MaterialLib/PhysicalConstant.h" namespace { - // NaX_Dubinin_polyfrac_CC.pickle // date extracted 2015-06-23 16:47:50 file mtime 2015-06-23 16:47:23 const double DensityDubinin_c[] = { - 0.3635538371322433, /* a0 */ - -0.0014521033261199435, /* a1 */ - -0.0007855160157616825, /* a2 */ - 4.385666000850253e-08, /* a3 */ - 5.567776459188524e-07, /* a4 */ - 6.026002134230559e-10, /* a5 */ - -1.0477401124006098e-10 /* a6 */ + 0.3635538371322433, /* a0 */ + -0.0014521033261199435, /* a1 */ + -0.0007855160157616825, /* a2 */ + 4.385666000850253e-08, /* a3 */ + 5.567776459188524e-07, /* a4 */ + 6.026002134230559e-10, /* a5 */ + -1.0477401124006098e-10 /* a6 */ }; } // namespace namespace Adsorption { - double DensityDubinin::getAdsorbateDensity(const double T_Ads) const { const double Tb = 373.1; - if (T_Ads < Tb) { + if (T_Ads < Tb) + { return rhoWaterDean(T_Ads); } const double Tc = 647.3; // K @@ -52,11 +52,12 @@ double DensityDubinin::getAdsorbateDensity(const double T_Ads) const return rho; } -//Thermal expansivity model for water found in the works of Hauer +// Thermal expansivity model for water found in the works of Hauer double DensityDubinin::getAlphaT(const double T_Ads) const { const double Tb = 373.1; - if (T_Ads <= Tb) { + if (T_Ads <= Tb) + { return alphaTWaterDean(T_Ads); } // critical T and p @@ -77,13 +78,14 @@ double DensityDubinin::getAlphaT(const double T_Ads) const // Characteristic curve. Return W (A) double DensityDubinin::characteristicCurve(const double A) const { - double W = curvePolyfrac(DensityDubinin_c, A); // cm^3/g + double W = curvePolyfrac(DensityDubinin_c, A); // cm^3/g - if (W < 0.0) { - W = 0.0; // TODO [CL] debug output + if (W < 0.0) + { + W = 0.0; // TODO [CL] debug output } - return W/1.e3; // m^3/kg + return W / 1.e3; // m^3/kg } double DensityDubinin::dCharacteristicCurve(const double A) const diff --git a/MaterialLib/Adsorption/DensityHauer.cpp b/MaterialLib/Adsorption/DensityHauer.cpp index 23b648e36c91c2623c18ce4554d31090d4856f8b..6d11e40078d8717a4ded1b6f1168781eb481c2cf 100644 --- a/MaterialLib/Adsorption/DensityHauer.cpp +++ b/MaterialLib/Adsorption/DensityHauer.cpp @@ -11,24 +11,22 @@ namespace { - // NaX_Hauer_polyfrac_CC.pickle // date extracted 2015-06-23 15:38:35 file mtime 2015-06-23 15:19:19 const double DensityHauer_c[] = { 0.36490158988356747, /* a0 */ - -0.0013723270478333963, /* a1 */ - -0.0007655780628099964, /* a2 */ - -3.353324854315774e-08, /* a3 */ - 5.424357157710913e-07, /* a4 */ - 6.613430586648678e-10, /* a5 */ - -1.0300151379421499e-10 /* a6 */ + -0.0013723270478333963, /* a1 */ + -0.0007655780628099964, /* a2 */ + -3.353324854315774e-08, /* a3 */ + 5.424357157710913e-07, /* a4 */ + 6.613430586648678e-10, /* a5 */ + -1.0300151379421499e-10 /* a6 */ }; } // namespace namespace Adsorption { - double DensityHauer::getAdsorbateDensity(const double T_Ads) const { return rhoWaterHauer(T_Ads); @@ -41,19 +39,20 @@ double DensityHauer::getAlphaT(const double T_Ads) const const double T0 = 283.15; const double alpha0 = 3.781e-4; // K; 1/K - return alpha0/(1. - alpha0 * (T_Ads-T0)); //in 1/K + return alpha0 / (1. - alpha0 * (T_Ads - T0)); // in 1/K } // Characteristic curve. Return W (A) double DensityHauer::characteristicCurve(const double A) const { - double W = curvePolyfrac(DensityHauer_c, A); // cm^3/g + double W = curvePolyfrac(DensityHauer_c, A); // cm^3/g - if (W < 0.0) { - W = 0.0; // TODO [CL] debug output + if (W < 0.0) + { + W = 0.0; // TODO [CL] debug output } - return W/1.e3; // m^3/kg + return W / 1.e3; // m^3/kg } double DensityHauer::dCharacteristicCurve(const double A) const diff --git a/MaterialLib/Adsorption/DensityLegacy.cpp b/MaterialLib/Adsorption/DensityLegacy.cpp index 3040dc9eb512d3e9a18d7198fcff7244bea5b075..4f628567c65b2f6de7fcc119a6837acb27165277 100644 --- a/MaterialLib/Adsorption/DensityLegacy.cpp +++ b/MaterialLib/Adsorption/DensityLegacy.cpp @@ -11,52 +11,47 @@ namespace { - -//parameters from least squares fit (experimental data) -const double DensityLegacy_c[] = { 0.34102920966608297, - -0.0013106032830951296, - -0.00060754147575378876, - 3.7843404172683339e-07, - 4.0107503869519016e-07, - 3.1274595098338057e-10, - -7.610441241719489e-11 - }; +// parameters from least squares fit (experimental data) +const double DensityLegacy_c[] = { + 0.34102920966608297, -0.0013106032830951296, -0.00060754147575378876, + 3.7843404172683339e-07, 4.0107503869519016e-07, 3.1274595098338057e-10, + -7.610441241719489e-11}; } // namespace namespace Adsorption { - double DensityLegacy::getAdsorbateDensity(const double T_Ads) const { - //set reference state for adsorbate EOS in Hauer + // set reference state for adsorbate EOS in Hauer const double T0 = 293.15; const double rho0 = 998.084; const double alpha0 = 2.06508e-4; // K; kg/m^3; 1/K - return (rho0 * (1. - alpha0 * (T_Ads-T0))); // in kg/m^3 + return (rho0 * (1. - alpha0 * (T_Ads - T0))); // in kg/m^3 } // Thermal expansivity model for water found in the works of Hauer double DensityLegacy::getAlphaT(const double T_Ads) const { - //set reference state for adsorbate EOS in Hauer + // set reference state for adsorbate EOS in Hauer const double T0 = 293.15; const double alpha0 = 2.06508e-4; // K; 1/K - return (alpha0/(1. - alpha0 * (T_Ads-T0))); // in 1/K + return (alpha0 / (1. - alpha0 * (T_Ads - T0))); // in 1/K } // Characteristic curve. Return W (A) double DensityLegacy::characteristicCurve(const double A) const { - double W = curvePolyfrac(DensityLegacy_c, A); // cm^3/g + double W = curvePolyfrac(DensityLegacy_c, A); // cm^3/g - if (W < 0.0) { - W = 0.0; // TODO [CL] debug output + if (W < 0.0) + { + W = 0.0; // TODO [CL] debug output } - return W/1.e3; // m^3/kg + return W / 1.e3; // m^3/kg } double DensityLegacy::dCharacteristicCurve(const double A) const diff --git a/MaterialLib/Adsorption/DensityMette.cpp b/MaterialLib/Adsorption/DensityMette.cpp index af34cc11ba51c8f1b2d0102eaaa7d7d26c9f8ff6..3f74a95714cb61efa67b45a345a3071fcc9fb491 100644 --- a/MaterialLib/Adsorption/DensityMette.cpp +++ b/MaterialLib/Adsorption/DensityMette.cpp @@ -8,6 +8,7 @@ */ #include "DensityMette.h" + #include "DensityCook.h" namespace @@ -16,46 +17,44 @@ namespace // date extracted 2015-06-23 15:38:35 file mtime 2015-06-23 15:19:26 const double DensityMette_c[] = { 0.36340572890087813, /* a0 */ - -0.0013449597038375108, /* a1 */ - -0.0007581210111121073, /* a2 */ - -7.331279615575401e-08, /* a3 */ - 5.365656973806218e-07, /* a4 */ - 6.854673678427112e-10, /* a5 */ - -1.0197050219481966e-10 /* a6 */ + -0.0013449597038375108, /* a1 */ + -0.0007581210111121073, /* a2 */ + -7.331279615575401e-08, /* a3 */ + 5.365656973806218e-07, /* a4 */ + 6.854673678427112e-10, /* a5 */ + -1.0197050219481966e-10 /* a6 */ }; } // namespace namespace Adsorption { - double DensityMette::getAdsorbateDensity(const double T_Ads) const { const double T0 = 293.15; const double rho0 = rhoWaterDean(T0); const double alpha20 = alphaTWaterDean(T0); - return rho0 / (1. + alpha20*(T_Ads-T0)); + return rho0 / (1. + alpha20 * (T_Ads - T0)); } - // Thermal expansivity model for water found in the works of Hauer double DensityMette::getAlphaT(const double T_Ads) const { const double T0 = 293.15; const double alpha20 = alphaTWaterDean(T0); - return alpha20 / (1. + alpha20 * (T_Ads-T0)); + return alpha20 / (1. + alpha20 * (T_Ads - T0)); } - // Characteristic curve. Return W (A) double DensityMette::characteristicCurve(const double A) const { - double W = curvePolyfrac(DensityMette_c, A); // cm^3/g + double W = curvePolyfrac(DensityMette_c, A); // cm^3/g - if (W < 0.0) { - W = 0.0; // TODO [CL] debug output + if (W < 0.0) + { + W = 0.0; // TODO [CL] debug output } - return W/1.e3; // m^3/kg + return W / 1.e3; // m^3/kg } double DensityMette::dCharacteristicCurve(const double A) const diff --git a/MaterialLib/Adsorption/DensityNunez.cpp b/MaterialLib/Adsorption/DensityNunez.cpp index f7cd20b34079302320b0305bf94beb46d5241320..fdc926dd207ab07b711a5aca208bee798b0b150a 100644 --- a/MaterialLib/Adsorption/DensityNunez.cpp +++ b/MaterialLib/Adsorption/DensityNunez.cpp @@ -11,59 +11,74 @@ namespace { - // NaX_Nunez_polyfrac_CC.pickle // date extracted 2015-06-23 15:38:35 file mtime 2015-06-23 15:19:34 const double DensityNunez_c[] = { - 0.3631900485031771, /* a0 */ - -0.0014242280940080726, /* a1 */ - -0.0007751726942386291, /* a2 */ - 2.1775655036811842e-08, /* a3 */ - 5.488166913667265e-07, /* a4 */ - 6.204064716725214e-10, /* a5 */ - -1.0345385018952998e-10 /* a6 */ + 0.3631900485031771, /* a0 */ + -0.0014242280940080726, /* a1 */ + -0.0007751726942386291, /* a2 */ + 2.1775655036811842e-08, /* a3 */ + 5.488166913667265e-07, /* a4 */ + 6.204064716725214e-10, /* a5 */ + -1.0345385018952998e-10 /* a6 */ }; } // namespace namespace Adsorption { - double DensityNunez::getAdsorbateDensity(const double T_Ads) const { // TODO admissible T range: 273.16 K <= T_Ads <= 633.15 K - const double a[] = { 1.0644e3,-8.01905,1.445348e-2,-4.19589e-6,-4.5294e-9 }; - const double b[] = { -8.039e-3,1.8698e-5,-2.3015e-8,2.3809e-11,-1.388e-14 }; - const double u = a[0] + T_Ads * (a[1] + T_Ads * (a[2] + T_Ads * (a[3] + T_Ads * a[4]) ) ); - const double v = 1.0 + T_Ads * (b[0] + T_Ads * (b[1] + T_Ads * (b[2] + T_Ads * (b[3] + T_Ads * b[4]) ) ) ); - return u/v; + const double a[] = {1.0644e3, -8.01905, 1.445348e-2, -4.19589e-6, + -4.5294e-9}; + const double b[] = {-8.039e-3, 1.8698e-5, -2.3015e-8, 2.3809e-11, + -1.388e-14}; + const double u = + a[0] + T_Ads * (a[1] + T_Ads * (a[2] + T_Ads * (a[3] + T_Ads * a[4]))); + const double v = + 1.0 + + T_Ads * + (b[0] + + T_Ads * (b[1] + T_Ads * (b[2] + T_Ads * (b[3] + T_Ads * b[4])))); + return u / v; } - // Thermal expansivity model for water found in the works of Hauer double DensityNunez::getAlphaT(const double T_Ads) const { // TODO admissible T range: 273.16 K <= T_Ads <= 633.15 K - const double a[] = { 1.0644e3,-8.01905,1.445348e-2,-4.19589e-6,-4.5294e-9 }; - const double b[] = { -8.039e-3,1.8698e-5,-2.3015e-8,2.3809e-11,-1.388e-14 }; - const double u = a[0] + T_Ads * (a[1] + T_Ads * (a[2] + T_Ads * (a[3] + T_Ads * a[4]) ) ); - const double v = 1.0 + T_Ads * (b[0] + T_Ads * (b[1] + T_Ads * (b[2] + T_Ads * (b[3] + T_Ads * b[4]) ) ) ); - const double du = a[1] + T_Ads * (2.0*a[2] + T_Ads * (3.0*a[3] + T_Ads * 4.0*a[4]) ); - const double dv = b[0] + T_Ads * (2.0*b[1] + T_Ads * (3.0*b[2] + T_Ads * (4.0*b[3] + T_Ads * 5.0*b[4]) ) ); - return dv/v - du/u; + const double a[] = {1.0644e3, -8.01905, 1.445348e-2, -4.19589e-6, + -4.5294e-9}; + const double b[] = {-8.039e-3, 1.8698e-5, -2.3015e-8, 2.3809e-11, + -1.388e-14}; + const double u = + a[0] + T_Ads * (a[1] + T_Ads * (a[2] + T_Ads * (a[3] + T_Ads * a[4]))); + const double v = + 1.0 + + T_Ads * + (b[0] + + T_Ads * (b[1] + T_Ads * (b[2] + T_Ads * (b[3] + T_Ads * b[4])))); + const double du = + a[1] + T_Ads * (2.0 * a[2] + T_Ads * (3.0 * a[3] + T_Ads * 4.0 * a[4])); + const double dv = + b[0] + T_Ads * (2.0 * b[1] + + T_Ads * (3.0 * b[2] + + T_Ads * (4.0 * b[3] + T_Ads * 5.0 * b[4]))); + return dv / v - du / u; } - // Characteristic curve. Return W (A) double DensityNunez::characteristicCurve(const double A) const { - double W = curvePolyfrac(DensityNunez_c, A); // cm^3/g + double W = curvePolyfrac(DensityNunez_c, A); // cm^3/g - if (W < 0.0) { - W = 0.0; // TODO [CL] debug output + if (W < 0.0) + { + W = 0.0; // TODO [CL] debug output } - return W/1.e3; // m^3/kg + return W / 1.e3; // m^3/kg } double DensityNunez::dCharacteristicCurve(const double A) const diff --git a/MaterialLib/Adsorption/Reaction.cpp b/MaterialLib/Adsorption/Reaction.cpp index 1756fc31110d800f16fc651cde3efdd11cc98808..52362747e98d52b8d18d89c18eaacd0fec40e163 100644 --- a/MaterialLib/Adsorption/Reaction.cpp +++ b/MaterialLib/Adsorption/Reaction.cpp @@ -7,11 +7,9 @@ * http://www.opengeosys.org/project/license */ - -#include "BaseLib/StringTools.h" - #include "Reaction.h" +#include "BaseLib/StringTools.h" #include "Density100MPa.h" #include "DensityConst.h" #include "DensityCook.h" @@ -20,18 +18,13 @@ #include "DensityLegacy.h" #include "DensityMette.h" #include "DensityNunez.h" - #include "ReactionCaOH2.h" #include "ReactionInert.h" #include "ReactionSinusoidal.h" - namespace Adsorption { - -std::unique_ptr<Reaction> -Reaction:: -newInstance(BaseLib::ConfigTree const& conf) +std::unique_ptr<Reaction> Reaction::newInstance(BaseLib::ConfigTree const& conf) { //! \ogs_file_param{material__adsorption__reaction__type} auto const type = conf.getConfigParameter<std::string>("type"); @@ -86,4 +79,4 @@ newInstance(BaseLib::ConfigTree const& conf) return nullptr; } -} // namespace Adsorption +} // namespace Adsorption diff --git a/MaterialLib/Adsorption/ReactionCaOH2.cpp b/MaterialLib/Adsorption/ReactionCaOH2.cpp index 7e32f6258b8e00e4cff51f0b001a2fc5e5fd0965..8d7e389c2d1ac3b5888c3ea58c98869b2f4b4007 100644 --- a/MaterialLib/Adsorption/ReactionCaOH2.cpp +++ b/MaterialLib/Adsorption/ReactionCaOH2.cpp @@ -8,23 +8,24 @@ */ #include "ReactionCaOH2.h" + #include <cassert> + #include "Adsorption.h" #include "BaseLib/Error.h" #include "MaterialLib/PhysicalConstant.h" namespace Adsorption { - const double ReactionCaOH2::_reaction_enthalpy = -1.12e+05; -const double ReactionCaOH2::_reaction_entropy = -143.5; +const double ReactionCaOH2::_reaction_entropy = -143.5; const double ReactionCaOH2::_M_carrier = MaterialLib::PhysicalConstant::MolarMass::N2; const double ReactionCaOH2::_M_react = MaterialLib::PhysicalConstant::MolarMass::Water; -const double ReactionCaOH2::_tol_l = 1e-4; -const double ReactionCaOH2::_tol_u = 1.0 - 1e-4; +const double ReactionCaOH2::_tol_l = 1e-4; +const double ReactionCaOH2::_tol_u = 1.0 - 1e-4; const double ReactionCaOH2::_tol_rho = 0.1; const double ReactionCaOH2::rho_low = 1656.0; @@ -34,7 +35,7 @@ double ReactionCaOH2::getEnthalpy(const double /*p_Ads*/, const double /*T_Ads*/, const double /*M_Ads*/) const { - return - _reaction_enthalpy/_M_react; + return -_reaction_enthalpy / _M_react; } double ReactionCaOH2::getReactionRate(const double /*p_Ads*/, @@ -45,7 +46,6 @@ double ReactionCaOH2::getReactionRate(const double /*p_Ads*/, OGS_FATAL("get_reaction_rate do not call directly"); } - double ReactionCaOH2::getReactionRate(double const solid_density) { _rho_s = solid_density; @@ -53,24 +53,24 @@ double ReactionCaOH2::getReactionRate(double const solid_density) return _qR; } -void ReactionCaOH2::updateParam( - double T_solid, - double p_gas, - double x_react, - double rho_s_initial) +void ReactionCaOH2::updateParam(double T_solid, + double p_gas, + double x_react, + double rho_s_initial) { - _T_s = T_solid; - _p_gas = p_gas / 1e5; // convert Pa to bar + _T_s = T_solid; + _p_gas = p_gas / 1e5; // convert Pa to bar _x_react = x_react; - _rho_s = rho_s_initial; + _rho_s = rho_s_initial; } void ReactionCaOH2::calculateQR() { // Convert mass fraction into mole fraction - const double mol_frac_react = AdsorptionReaction::getMolarFraction(_x_react, _M_react, _M_carrier); + const double mol_frac_react = + AdsorptionReaction::getMolarFraction(_x_react, _M_react, _M_carrier); - _p_r_g = std::max(mol_frac_react * _p_gas, 1.0e-3); // avoid illdefined log + _p_r_g = std::max(mol_frac_react * _p_gas, 1.0e-3); // avoid illdefined log setChemicalEquilibrium(); const double dXdt = CaHydration(); _qR = (rho_up - rho_low) * dXdt; @@ -81,41 +81,48 @@ void ReactionCaOH2::setChemicalEquilibrium() { const double R = MaterialLib::PhysicalConstant::IdealGasConstant; - _X_D = (_rho_s - rho_up - _tol_rho)/(rho_low - rho_up - 2.0*_tol_rho) ; - _X_D = (_X_D < 0.5) ? std::max(_tol_l,_X_D) : std::min(_X_D,_tol_u); // constrain to interval [tol_l;tol_u] + _X_D = (_rho_s - rho_up - _tol_rho) / (rho_low - rho_up - 2.0 * _tol_rho); + _X_D = (_X_D < 0.5) + ? std::max(_tol_l, _X_D) + : std::min(_X_D, _tol_u); // constrain to interval [tol_l;tol_u] _X_H = 1.0 - _X_D; // calculate equilibrium // using the p_eq to calculate the T_eq - Clausius-Clapeyron - _T_eq = (_reaction_enthalpy/R) / ((_reaction_entropy/R) + std::log(_p_r_g)); // unit of p in bar + _T_eq = (_reaction_enthalpy / R) / + ((_reaction_entropy / R) + std::log(_p_r_g)); // unit of p in bar // Alternative: Use T_s as T_eq and calculate p_eq - for Schaube kinetics - _p_eq = std::exp((_reaction_enthalpy/R)/_T_s - (_reaction_entropy/R)); + _p_eq = std::exp((_reaction_enthalpy / R) / _T_s - (_reaction_entropy / R)); } - double ReactionCaOH2::CaHydration() { const double R = MaterialLib::PhysicalConstant::IdealGasConstant; double dXdt; - // step 3, calculate dX/dt + // step 3, calculate dX/dt #ifdef SIMPLE_KINETICS - if ( T_s < T_eq ) // hydration - simple model + if (T_s < T_eq) // hydration - simple model #else - if ( _p_r_g > _p_eq ) // hydration - Schaube model + if (_p_r_g > _p_eq) // hydration - Schaube model #endif { - //X_H = max(tol_l,X_H); //lower tolerance to avoid oscillations at onset of hydration reaction. Set here so that no residual reaction rate occurs at end of hydration. -#ifdef SIMPLE_KINETICS // this is from P. Schmidt - dXdt = -1.0*(1.0-X_H) * (T_s - T_eq) / T_eq * 0.2 * conversion_rate::x_react; -#else //this is from Schaube + // X_H = max(tol_l,X_H); //lower tolerance to avoid oscillations at + // onset of hydration reaction. Set here so that no residual reaction + // rate occurs at end of hydration. +#ifdef SIMPLE_KINETICS // this is from P. Schmidt + dXdt = -1.0 * (1.0 - X_H) * (T_s - T_eq) / T_eq * 0.2 * + conversion_rate::x_react; +#else // this is from Schaube if (_X_H == _tol_u || _rho_s == rho_up) { dXdt = 0.0; } else if ((_T_eq - _T_s) >= 50.0) { - dXdt = 13945.0 * exp(-89486.0/R/_T_s) * std::pow(_p_r_g/_p_eq - 1.0,0.83) * 3.0 * (_X_D) * std::pow(-1.0*log(_X_D),0.666); + dXdt = 13945.0 * exp(-89486.0 / R / _T_s) * + std::pow(_p_r_g / _p_eq - 1.0, 0.83) * 3.0 * + (_X_D)*std::pow(-1.0 * log(_X_D), 0.666); } else { @@ -124,11 +131,13 @@ double ReactionCaOH2::CaHydration() } #endif } - else // dehydration + else // dehydration { - //X_D = max(tol_l,X_D); //lower tolerance to avoid oscillations at onset of dehydration reaction. Set here so that no residual reaction rate occurs at end of dehydration. -#ifdef SIMPLE_KINETICS // this is from P. Schmidt - dXdt = -1.0* (1.0-X_D) * (T_s - T_eq) / T_eq * 0.05; + // X_D = max(tol_l,X_D); //lower tolerance to avoid oscillations at + // onset of dehydration reaction. Set here so that no residual reaction + // rate occurs at end of dehydration. +#ifdef SIMPLE_KINETICS // this is from P. Schmidt + dXdt = -1.0 * (1.0 - X_D) * (T_s - T_eq) / T_eq * 0.05; #else if (_X_D == _tol_u || _rho_s == rho_low) { @@ -136,7 +145,8 @@ double ReactionCaOH2::CaHydration() } else if (_X_D < 0.2) { - dXdt = -1.9425e12 * exp( -1.8788e5/R/_T_s ) * std::pow(1.0-_p_r_g/_p_eq,3.0)*(_X_H); + dXdt = -1.9425e12 * exp(-1.8788e5 / R / _T_s) * + std::pow(1.0 - _p_r_g / _p_eq, 3.0) * (_X_H); } else { diff --git a/MaterialLib/Fluid/Density/CreateFluidDensityModel.cpp b/MaterialLib/Fluid/Density/CreateFluidDensityModel.cpp index 41c8e92ea7b7d79308d2cfd870bb32ef030eac26..6d9e696bc664b3a002760d7181d4124093a6682a 100644 --- a/MaterialLib/Fluid/Density/CreateFluidDensityModel.cpp +++ b/MaterialLib/Fluid/Density/CreateFluidDensityModel.cpp @@ -9,20 +9,18 @@ http://www.opengeosys.org/project/license */ -#include <array> - #include "CreateFluidDensityModel.h" -#include "BaseLib/Error.h" +#include <array> +#include "BaseLib/Error.h" #include "IdealGasLaw.h" #include "LinearConcentrationAndPressureDependentDensity.h" #include "LinearConcentrationDependentDensity.h" #include "LinearTemperatureDependentDensity.h" #include "LiquidDensity.h" -#include "WaterDensityIAPWSIF97Region1.h" - #include "MaterialLib/Fluid/ConstantFluidProperty.h" +#include "WaterDensityIAPWSIF97Region1.h" namespace MaterialLib { diff --git a/MaterialLib/Fluid/FluidProperties/CreateFluidProperties.cpp b/MaterialLib/Fluid/FluidProperties/CreateFluidProperties.cpp index 2076f3e8973181d1711b32ff60c74ca878a20779..d100d4414c618f06552252d4a66643d4fe34f62f 100644 --- a/MaterialLib/Fluid/FluidProperties/CreateFluidProperties.cpp +++ b/MaterialLib/Fluid/FluidProperties/CreateFluidProperties.cpp @@ -15,14 +15,12 @@ #include <string> #include "BaseLib/ConfigTree.h" - +#include "FluidProperties.h" +#include "FluidPropertiesWithDensityDependentModels.h" #include "MaterialLib/Fluid/FluidPropertyHeaders.h" #include "MaterialLib/Fluid/SpecificHeatCapacity/CreateSpecificFluidHeatCapacityModel.h" #include "MaterialLib/Fluid/ThermalConductivity/CreateFluidThermalConductivityModel.h" - -#include "FluidProperties.h" #include "PrimaryVariableDependentFluidProperties.h" -#include "FluidPropertiesWithDensityDependentModels.h" namespace MaterialLib { diff --git a/MaterialLib/Fluid/FluidProperties/FluidPropertiesWithDensityDependentModels.cpp b/MaterialLib/Fluid/FluidProperties/FluidPropertiesWithDensityDependentModels.cpp index ed870eddb33f4ce316753419431fd5b12059d75f..04432356972e459beba4596071bbdbe0bbda9a00 100644 --- a/MaterialLib/Fluid/FluidProperties/FluidPropertiesWithDensityDependentModels.cpp +++ b/MaterialLib/Fluid/FluidProperties/FluidPropertiesWithDensityDependentModels.cpp @@ -14,8 +14,8 @@ #include <string> -#include "MaterialLib/Fluid/FluidProperty.h" #include "FluidProperties.h" +#include "MaterialLib/Fluid/FluidProperty.h" namespace MaterialLib { diff --git a/MaterialLib/Fluid/GibbsFreeEnergy/DimensionLessGibbsFreeEnergyRegion1.cpp b/MaterialLib/Fluid/GibbsFreeEnergy/DimensionLessGibbsFreeEnergyRegion1.cpp index b562a7b5af21ce3bbc2cdd4b3582b2a4b53f11d5..ba8b6d275fcb1d453b29e82ab43bf35156d85ada 100644 --- a/MaterialLib/Fluid/GibbsFreeEnergy/DimensionLessGibbsFreeEnergyRegion1.cpp +++ b/MaterialLib/Fluid/GibbsFreeEnergy/DimensionLessGibbsFreeEnergyRegion1.cpp @@ -54,8 +54,8 @@ double DimensionLessGibbsFreeEnergyRegion1::get_gamma(const double tau, return val; } -double DimensionLessGibbsFreeEnergyRegion1::get_dgamma_dtau( - const double tau, const double pi) +double DimensionLessGibbsFreeEnergyRegion1::get_dgamma_dtau(const double tau, + const double pi) { double val = 0.; for (int i = 0; i < 34; i++) @@ -80,8 +80,8 @@ double DimensionLessGibbsFreeEnergyRegion1::get_dgamma_dtau_dtau( return val; } -double DimensionLessGibbsFreeEnergyRegion1::get_dgamma_dpi( - const double tau, const double pi) +double DimensionLessGibbsFreeEnergyRegion1::get_dgamma_dpi(const double tau, + const double pi) { double val = 0.; for (int i = 0; i < 34; i++) @@ -93,8 +93,8 @@ double DimensionLessGibbsFreeEnergyRegion1::get_dgamma_dpi( return val; } -double DimensionLessGibbsFreeEnergyRegion1::get_dgamma_dpi_dpi( - const double tau, const double pi) +double DimensionLessGibbsFreeEnergyRegion1::get_dgamma_dpi_dpi(const double tau, + const double pi) { double val = 0.; for (int i = 0; i < 34; i++) diff --git a/MaterialLib/Fluid/SpecificHeatCapacity/CreateSpecificFluidHeatCapacityModel.cpp b/MaterialLib/Fluid/SpecificHeatCapacity/CreateSpecificFluidHeatCapacityModel.cpp index 355297f9fffb967ec8d82e2953c8da511536b563..073f16b2ea72af2002fe32df3f9ccca8899a5f9d 100644 --- a/MaterialLib/Fluid/SpecificHeatCapacity/CreateSpecificFluidHeatCapacityModel.cpp +++ b/MaterialLib/Fluid/SpecificHeatCapacity/CreateSpecificFluidHeatCapacityModel.cpp @@ -12,11 +12,10 @@ #include "CreateSpecificFluidHeatCapacityModel.h" -#include "BaseLib/Error.h" #include "BaseLib/ConfigTree.h" - -#include "MaterialLib/Fluid/FluidProperty.h" +#include "BaseLib/Error.h" #include "MaterialLib/Fluid/ConstantFluidProperty.h" +#include "MaterialLib/Fluid/FluidProperty.h" namespace MaterialLib { diff --git a/MaterialLib/Fluid/ThermalConductivity/CreateFluidThermalConductivityModel.cpp b/MaterialLib/Fluid/ThermalConductivity/CreateFluidThermalConductivityModel.cpp index 87f456794842e8d3a6426e936415f833eb18823a..ff22cf712d04ac5aa588965bc9de1a59dcbd3089 100644 --- a/MaterialLib/Fluid/ThermalConductivity/CreateFluidThermalConductivityModel.cpp +++ b/MaterialLib/Fluid/ThermalConductivity/CreateFluidThermalConductivityModel.cpp @@ -12,11 +12,10 @@ #include "CreateFluidThermalConductivityModel.h" -#include "BaseLib/Error.h" #include "BaseLib/ConfigTree.h" - -#include "MaterialLib/Fluid/FluidProperty.h" +#include "BaseLib/Error.h" #include "MaterialLib/Fluid/ConstantFluidProperty.h" +#include "MaterialLib/Fluid/FluidProperty.h" namespace MaterialLib { diff --git a/MaterialLib/Fluid/Viscosity/CreateViscosityModel.cpp b/MaterialLib/Fluid/Viscosity/CreateViscosityModel.cpp index db4fe7f5da8f4028e91003b7afc73a176a729ef8..d1b7be54e7c151e1df56b24cee2de6a5cf635081 100644 --- a/MaterialLib/Fluid/Viscosity/CreateViscosityModel.cpp +++ b/MaterialLib/Fluid/Viscosity/CreateViscosityModel.cpp @@ -13,9 +13,8 @@ #include "CreateViscosityModel.h" #include "BaseLib/Error.h" - -#include "MaterialLib/Fluid/ConstantFluidProperty.h" #include "LinearPressureDependentViscosity.h" +#include "MaterialLib/Fluid/ConstantFluidProperty.h" #include "TemperatureDependentViscosity.h" #include "VogelsLiquidDynamicViscosity.h" #include "WaterViscosityIAPWS.h" diff --git a/MaterialLib/Fluid/WaterVaporProperties/WaterVaporProperties.cpp b/MaterialLib/Fluid/WaterVaporProperties/WaterVaporProperties.cpp index 9740e08c03f9223d6abc3e1657672e405abbd461..46095d19995059ea200d2d7cf1ec415037ec14ef 100644 --- a/MaterialLib/Fluid/WaterVaporProperties/WaterVaporProperties.cpp +++ b/MaterialLib/Fluid/WaterVaporProperties/WaterVaporProperties.cpp @@ -17,8 +17,8 @@ namespace MaterialLib { -using PhysicalConstant::IdealGasConstant; using PhysicalConstant::CelsiusZeroInKelvin; +using PhysicalConstant::IdealGasConstant; namespace Fluid { static const double temperature_0 = 373.15; /// reference temperature in [K] @@ -28,8 +28,8 @@ static const double h_wg = 2258000.0; /// latent heat of water evaporation double WaterVaporProperties::calculateSaturatedVaporPressure( const double T) const { - return p_0 * std::exp(((1 / temperature_0) - (1 / T)) * _water_mol_mass * h_wg / - IdealGasConstant); + return p_0 * std::exp(((1 / temperature_0) - (1 / T)) * _water_mol_mass * + h_wg / IdealGasConstant); } double WaterVaporProperties::calculateDerivativedPsatdT(const double T) const @@ -40,8 +40,7 @@ double WaterVaporProperties::calculateDerivativedPsatdT(const double T) const } double WaterVaporProperties::calculateVaporPressureNonwet( - const double pc, const double T, - const double mass_density_water) const + const double pc, const double T, const double mass_density_water) const { const double p_sat = calculateSaturatedVaporPressure(T); const double c_w = _water_mol_mass / IdealGasConstant / T; @@ -55,31 +54,34 @@ double WaterVaporProperties::calculateDerivativedPgwdT( const double dPsatdT = calculateDerivativedPsatdT(T); return dPsatdT * std::exp(-pc * c_w / mass_density_water) + p_sat * std::exp(-pc * c_w / mass_density_water) * - (pc * _water_mol_mass / mass_density_water / IdealGasConstant / T / T); + (pc * _water_mol_mass / mass_density_water / IdealGasConstant / + T / T); } double WaterVaporProperties::calculateDerivativedPgwdPC( const double pc, const double T, const double mass_density_water) const { const double c_w = _water_mol_mass / IdealGasConstant / T; const double p_sat = calculateSaturatedVaporPressure(T); - return p_sat * std::exp(-pc * c_w / mass_density_water) * (-c_w / mass_density_water); + return p_sat * std::exp(-pc * c_w / mass_density_water) * + (-c_w / mass_density_water); } double WaterVaporProperties::calculatedDensityNonwetdT( const double p_air_nonwet, const double p_vapor_nonwet, const double pc, const double T, const double mass_density_water) const { const double dPgwdT = calculateDerivativedPgwdT(pc, T, mass_density_water); - return -((p_air_nonwet * _air_mol_mass + p_vapor_nonwet * _water_mol_mass) / IdealGasConstant / - T / T) + + return -((p_air_nonwet * _air_mol_mass + p_vapor_nonwet * _water_mol_mass) / + IdealGasConstant / T / T) + (_water_mol_mass - _air_mol_mass) * dPgwdT / IdealGasConstant / T; } -double WaterVaporProperties::getWaterVaporEnthalpySimple(const double temperature, +double WaterVaporProperties::getWaterVaporEnthalpySimple( + const double temperature, const double heat_capacity_water_vapor, const double /*pressure*/, const double /*latent_heat_evaporation*/) { return heat_capacity_water_vapor * (temperature - CelsiusZeroInKelvin) + - h_wg; + h_wg; } } // namespace Fluid diff --git a/MaterialLib/FractureModels/CohesiveZoneModeI.cpp b/MaterialLib/FractureModels/CohesiveZoneModeI.cpp index 8246aa32e119ffa2d1eb667c0d62f18bdc018d1e..0cd0fa73feb57b0652df4de44bd8642644bb2265 100644 --- a/MaterialLib/FractureModels/CohesiveZoneModeI.cpp +++ b/MaterialLib/FractureModels/CohesiveZoneModeI.cpp @@ -8,8 +8,8 @@ */ #include "CohesiveZoneModeI.h" -#include "LogPenalty.h" +#include "LogPenalty.h" #include "MathLib/MathTools.h" namespace MaterialLib @@ -57,7 +57,7 @@ void CohesiveZoneModeI<DisplacementDim>::computeConstitutiveRelation( auto& state = static_cast<StateVariables<DisplacementDim>&>(material_state_variables); - //reset damage in each iteration + // reset damage in each iteration state.setInitialConditions(); auto const mp = evaluatedMaterialProperties(t, x); @@ -108,7 +108,7 @@ void CohesiveZoneModeI<DisplacementDim>::computeConstitutiveRelation( state.damage = computeDamage(state.damage_prev, w_n_effective, mp.w_np, mp.w_nf); degradation = ((1 - state.damage) * mp.w_np) / - (mp.w_np + state.damage * (mp.w_nf - mp.w_np)); + (mp.w_np + state.damage * (mp.w_nf - mp.w_np)); } // Degrade stiffness tensor in tension. diff --git a/MaterialLib/FractureModels/Coulomb.cpp b/MaterialLib/FractureModels/Coulomb.cpp index 2de40aa4918d0c3751b591e1f7be32eb06e23183..61bbbe0059b6a2ef1528e124588608d7d1fe17b6 100644 --- a/MaterialLib/FractureModels/Coulomb.cpp +++ b/MaterialLib/FractureModels/Coulomb.cpp @@ -22,13 +22,12 @@ namespace Fracture { namespace Coulomb { - struct MaterialPropertyValues { double Kn = 0.0; double Ks = 0.0; - double phi = 0.0; // friction angle - double psi = 0.0; // dilation angle + double phi = 0.0; // friction angle + double psi = 0.0; // dilation angle double c = 0.0; template <typename MaterialProperties> @@ -36,13 +35,13 @@ struct MaterialPropertyValues double const t, ParameterLib::SpatialPosition const& x) { - Kn = mp.normal_stiffness(t,x)[0]; - Ks = mp.shear_stiffness(t,x)[0]; + Kn = mp.normal_stiffness(t, x)[0]; + Ks = mp.shear_stiffness(t, x)[0]; auto constexpr degree = boost::math::constants::degree<double>(); // pi/180 phi = mp.friction_angle(t, x)[0] * degree; psi = mp.dilatancy_angle(t, x)[0] * degree; - c = mp.cohesion(t,x)[0]; + c = mp.cohesion(t, x)[0]; } }; diff --git a/MaterialLib/FractureModels/CreateCohesiveZoneModeI.cpp b/MaterialLib/FractureModels/CreateCohesiveZoneModeI.cpp index 2c74cfa633b64a3be0bc73dad3e840046dda261f..401f09fbdb38b1da60ad3cdf99ea49ef11957daf 100644 --- a/MaterialLib/FractureModels/CreateCohesiveZoneModeI.cpp +++ b/MaterialLib/FractureModels/CreateCohesiveZoneModeI.cpp @@ -9,9 +9,8 @@ #include "CreateCohesiveZoneModeI.h" -#include "ParameterLib/Utils.h" - #include "CohesiveZoneModeI.h" +#include "ParameterLib/Utils.h" namespace MaterialLib { diff --git a/MaterialLib/FractureModels/CreateLinearElasticIsotropic.cpp b/MaterialLib/FractureModels/CreateLinearElasticIsotropic.cpp index e420688ee43428aca090a0a698118cb624994598..eb51bd8a3866f8e960f790fd3ecf0a52a64c6261 100644 --- a/MaterialLib/FractureModels/CreateLinearElasticIsotropic.cpp +++ b/MaterialLib/FractureModels/CreateLinearElasticIsotropic.cpp @@ -9,9 +9,8 @@ #include "CreateLinearElasticIsotropic.h" -#include "ParameterLib/Utils.h" - #include "LinearElasticIsotropic.h" +#include "ParameterLib/Utils.h" namespace MaterialLib { @@ -43,8 +42,8 @@ createLinearElasticIsotropic( //! \ogs_file_param{material__fracture_model__LinearElasticIsotropic__tension_cutoff} config.getConfigParameter<bool>("tension_cutoff"); - typename LinearElasticIsotropic<DisplacementDim>::MaterialProperties mp{ - Kn, Ks}; + typename LinearElasticIsotropic<DisplacementDim>::MaterialProperties mp{Kn, + Ks}; return std::make_unique<LinearElasticIsotropic<DisplacementDim>>( penalty_aperture_cutoff, tension_cutoff, mp); diff --git a/MaterialLib/FractureModels/FractureIdentity2.cpp b/MaterialLib/FractureModels/FractureIdentity2.cpp index 5b2a6818e61c740585e8463c9d5e71e63643957b..b6d6fdf500a219c4db26d5b0eada7b796b908e7b 100644 --- a/MaterialLib/FractureModels/FractureIdentity2.cpp +++ b/MaterialLib/FractureModels/FractureIdentity2.cpp @@ -13,22 +13,22 @@ namespace MaterialLib { namespace Fracture { - namespace { template <typename VectorType, int DisplacementDim> VectorType initIdentity2() { VectorType ivec = VectorType::Zero(DisplacementDim); - ivec[DisplacementDim-1] = 1; + ivec[DisplacementDim - 1] = 1; return ivec; } -} // anonymous namespace +} // anonymous namespace template <int DisplacementDim> const typename FractureIdentity2<DisplacementDim>::VectorType - FractureIdentity2<DisplacementDim>::value = initIdentity2< - typename FractureIdentity2<DisplacementDim>::VectorType, DisplacementDim>(); + FractureIdentity2<DisplacementDim>::value = + initIdentity2<typename FractureIdentity2<DisplacementDim>::VectorType, + DisplacementDim>(); // template instantiation template struct FractureIdentity2<2>; @@ -36,4 +36,3 @@ template struct FractureIdentity2<3>; } // namespace Fracture } // namespace MaterialLib - diff --git a/MaterialLib/FractureModels/LinearElasticIsotropic.cpp b/MaterialLib/FractureModels/LinearElasticIsotropic.cpp index 00a3592b5035eb9045cf0e2f6e56d289a9285751..fe161b4a0067527809749cff70192c6308e5482f 100644 --- a/MaterialLib/FractureModels/LinearElasticIsotropic.cpp +++ b/MaterialLib/FractureModels/LinearElasticIsotropic.cpp @@ -70,6 +70,5 @@ void LinearElasticIsotropic<DisplacementDim>::computeConstitutiveRelation( template class LinearElasticIsotropic<2>; template class LinearElasticIsotropic<3>; - -} // namespace Fracture -} // namespace MaterialLib +} // namespace Fracture +} // namespace MaterialLib diff --git a/MaterialLib/FractureModels/Permeability/CreateConstantPermeability.cpp b/MaterialLib/FractureModels/Permeability/CreateConstantPermeability.cpp index 8c26cc5f551b6535a8badbd6d69f4ab2f1a4b1a4..1a21874281ae32789d9cc4a25e050717e971775e 100644 --- a/MaterialLib/FractureModels/Permeability/CreateConstantPermeability.cpp +++ b/MaterialLib/FractureModels/Permeability/CreateConstantPermeability.cpp @@ -8,9 +8,9 @@ */ #include "CreateConstantPermeability.h" + #include "BaseLib/ConfigTree.h" #include "BaseLib/Error.h" - #include "ConstantPermeability.h" namespace MaterialLib::Fracture::Permeability diff --git a/MaterialLib/FractureModels/Permeability/CreateCubicLaw.cpp b/MaterialLib/FractureModels/Permeability/CreateCubicLaw.cpp index 79e8c46bb9d24e5b8ef012bbcc9d9ca3539ea7f6..dd5bfa2307432e843d7a16654a7fed8d3cefc2ef 100644 --- a/MaterialLib/FractureModels/Permeability/CreateCubicLaw.cpp +++ b/MaterialLib/FractureModels/Permeability/CreateCubicLaw.cpp @@ -10,7 +10,6 @@ #include "CreateCubicLaw.h" #include "BaseLib/ConfigTree.h" - #include "CubicLaw.h" namespace MaterialLib::Fracture::Permeability diff --git a/MaterialLib/FractureModels/Permeability/CreatePermeabilityModel.cpp b/MaterialLib/FractureModels/Permeability/CreatePermeabilityModel.cpp index 7f2a586f2fec020d7c8a6ff7e27f84d4f3cdf953..a29dd7e3d8e99e10a7d8362b557cb90cc21e1daf 100644 --- a/MaterialLib/FractureModels/Permeability/CreatePermeabilityModel.cpp +++ b/MaterialLib/FractureModels/Permeability/CreatePermeabilityModel.cpp @@ -11,7 +11,6 @@ #include "BaseLib/ConfigTree.h" #include "BaseLib/Error.h" - #include "CreateConstantPermeability.h" #include "CreateCubicLaw.h" diff --git a/MaterialLib/MPL/Component.cpp b/MaterialLib/MPL/Component.cpp index aac90a511c14fced7e6fa7999d6dc156958134b4..83fa318835160dbc5e04cd86e9c993919adc8ec8 100644 --- a/MaterialLib/MPL/Component.cpp +++ b/MaterialLib/MPL/Component.cpp @@ -11,14 +11,13 @@ */ #include "Component.h" + #include "Components/Components.h" #include "Properties/Properties.h" namespace MaterialPropertyLib { -Component::Component() -{ -} +Component::Component() {} Component::Component(std::string const& component_name, std::unique_ptr<PropertyArray>&& properties) diff --git a/MaterialLib/MPL/Components/Water.cpp b/MaterialLib/MPL/Components/Water.cpp index 5b5ed09093b8fe9c81d8c5048407b5c29d35d3e1..8fd185e4e76931c87cf0dc990035918b828dc574 100644 --- a/MaterialLib/MPL/Components/Water.cpp +++ b/MaterialLib/MPL/Components/Water.cpp @@ -11,6 +11,7 @@ */ #include "Water.h" + #include "MaterialLib/MPL/Properties/Properties.h" namespace MaterialPropertyLib diff --git a/MaterialLib/MPL/CreateMaterialSpatialDistributionMap.cpp b/MaterialLib/MPL/CreateMaterialSpatialDistributionMap.cpp index db9b7fc9aad060bd483b77b9676aef362b8f17c7..8faac213709be7de47e4f38fa0cbfa54201f8908 100644 --- a/MaterialLib/MPL/CreateMaterialSpatialDistributionMap.cpp +++ b/MaterialLib/MPL/CreateMaterialSpatialDistributionMap.cpp @@ -9,6 +9,7 @@ * http://www.opengeosys.org/project/license */ #include "CreateMaterialSpatialDistributionMap.h" + #include "MaterialSpatialDistributionMap.h" #include "MeshLib/Mesh.h" @@ -31,9 +32,8 @@ createMaterialSpatialDistributionMap( WARN( "The maximum value of MaterialIDs in mesh is {:d}. As the given " "number of porous media definitions in the project file is {:d}, " - "the " - "maximum value of MaterialIDs in mesh must be {:d} (index starts " - "with zero).", + "the maximum value of MaterialIDs in mesh must be {:d} (index " + "starts with zero).", max_material_id, media.size(), max_material_id - 1); } @@ -42,8 +42,7 @@ createMaterialSpatialDistributionMap( WARN( "There are {:d} porous medium definitions in the project file but " "only {:d} different values in the MaterialIDs vector/data_array " - "in " - "the mesh.", + "in the mesh.", media.size(), max_material_id - 1); } return std::make_unique<MaterialSpatialDistributionMap>(media, diff --git a/MaterialLib/MPL/CreateMedium.cpp b/MaterialLib/MPL/CreateMedium.cpp index f12dfe0ee729bd7a80852073cfd5593656a6b0f1..388b910a249d5f34adac94595983cd8ad75e3597 100644 --- a/MaterialLib/MPL/CreateMedium.cpp +++ b/MaterialLib/MPL/CreateMedium.cpp @@ -12,15 +12,12 @@ #include "CreateMedium.h" -#include "Medium.h" - #include "BaseLib/ConfigTree.h" -#include "ParameterLib/Parameter.h" - -#include "Properties/Properties.h" - #include "CreatePhase.h" #include "CreateProperty.h" +#include "Medium.h" +#include "ParameterLib/Parameter.h" +#include "Properties/Properties.h" namespace MaterialPropertyLib { diff --git a/MaterialLib/MPL/CreatePhase.cpp b/MaterialLib/MPL/CreatePhase.cpp index 42e9585846ae4c5ea4ed83d7dff4af4a2bdc5ff6..fa4d9d4094da477294b6e30e84afc9ef6e90045b 100644 --- a/MaterialLib/MPL/CreatePhase.cpp +++ b/MaterialLib/MPL/CreatePhase.cpp @@ -82,8 +82,8 @@ std::unique_ptr<MaterialPropertyLib::Phase> createPhase( phase_type); } - return std::make_unique<Phase>( - std::move(phase_type), std::move(components), std::move(properties)); + return std::make_unique<Phase>(std::move(phase_type), std::move(components), + std::move(properties)); } } // namespace diff --git a/MaterialLib/MPL/MaterialSpatialDistributionMap.cpp b/MaterialLib/MPL/MaterialSpatialDistributionMap.cpp index 6518dd9e22540939a21a0ba262e25b418c54826d..7d9a44173b8938227e7f95c2b064629cadfacfb3 100644 --- a/MaterialLib/MPL/MaterialSpatialDistributionMap.cpp +++ b/MaterialLib/MPL/MaterialSpatialDistributionMap.cpp @@ -10,6 +10,7 @@ * */ #include "MaterialSpatialDistributionMap.h" + #include "MeshLib/Mesh.h" namespace MaterialPropertyLib diff --git a/MaterialLib/MPL/Phase.cpp b/MaterialLib/MPL/Phase.cpp index ab67feed1874581bcac88661f3fd6f67ca579f13..68921e4770c9dfd2162101eadb407c8379b3d822 100644 --- a/MaterialLib/MPL/Phase.cpp +++ b/MaterialLib/MPL/Phase.cpp @@ -11,10 +11,10 @@ */ #include "Phase.h" -#include "BaseLib/Algorithm.h" -#include "Properties/Properties.h" +#include "BaseLib/Algorithm.h" #include "Component.h" +#include "Properties/Properties.h" namespace MaterialPropertyLib { diff --git a/MaterialLib/MPL/Properties/AverageMolarMass.cpp b/MaterialLib/MPL/Properties/AverageMolarMass.cpp index 202f29f7b4c73a496e65bb87c1341c226b0dc549..4af19eb5c431e1b302b26bac31caa71ac1c83909 100644 --- a/MaterialLib/MPL/Properties/AverageMolarMass.cpp +++ b/MaterialLib/MPL/Properties/AverageMolarMass.cpp @@ -90,8 +90,8 @@ PropertyDataType AverageMolarMass::dValue( (void)primary_variable; assert(((primary_variable == Variable::phase_pressure) || (primary_variable == Variable::temperature)) && - "AverageMolarMass::dValue is implemented for " - " derivatives with respect to phase_pressure or temperature only."); + "AverageMolarMass::dValue is implemented for derivatives with " + "respect to phase_pressure or temperature only."); auto phase = std::get<Phase*>(scale_); diff --git a/MaterialLib/MPL/Properties/CapillaryPressureSaturation/CapillaryPressureRegularizedVanGenuchten.cpp b/MaterialLib/MPL/Properties/CapillaryPressureSaturation/CapillaryPressureRegularizedVanGenuchten.cpp index 049d49561435bc59ec77eb2a38214b0007dad67d..e594193ede867b60e7fc004edac87a14bafb1198 100644 --- a/MaterialLib/MPL/Properties/CapillaryPressureSaturation/CapillaryPressureRegularizedVanGenuchten.cpp +++ b/MaterialLib/MPL/Properties/CapillaryPressureSaturation/CapillaryPressureRegularizedVanGenuchten.cpp @@ -16,8 +16,8 @@ #include "BaseLib/Error.h" #include "MaterialLib/MPL/Medium.h" -#include "MaterialLib/MPL/VariableType.h" #include "MaterialLib/MPL/Utils/CheckVanGenuchtenExponentRange.h" +#include "MaterialLib/MPL/VariableType.h" namespace MaterialPropertyLib { @@ -74,10 +74,9 @@ PropertyDataType CapillaryPressureRegularizedVanGenuchten::dValue( double const /*dt*/) const { (void)primary_variable; - assert( - (primary_variable == Variable::liquid_saturation) && - "CapillaryPressureRegularizedVanGenuchten::dValue is implemented for " - "derivatives with respect to liquid saturation only."); + assert((primary_variable == Variable::liquid_saturation) && + "CapillaryPressureRegularizedVanGenuchten::dValue is implemented " + "for derivatives with respect to liquid saturation only."); const double Sl = std::get<double>( variable_array[static_cast<int>(Variable::liquid_saturation)]); diff --git a/MaterialLib/MPL/Properties/CapillaryPressureSaturation/CapillaryPressureVanGenuchten.cpp b/MaterialLib/MPL/Properties/CapillaryPressureSaturation/CapillaryPressureVanGenuchten.cpp index 423496c93a1ad7362220227f0831f3d3d5125984..abbb155f408b1124a409f5ca98397a87b7fb31da 100644 --- a/MaterialLib/MPL/Properties/CapillaryPressureSaturation/CapillaryPressureVanGenuchten.cpp +++ b/MaterialLib/MPL/Properties/CapillaryPressureSaturation/CapillaryPressureVanGenuchten.cpp @@ -36,47 +36,46 @@ CapillaryPressureVanGenuchten::CapillaryPressureVanGenuchten( if (S_L_res_ < 0 || S_L_res_ > 1) { OGS_FATAL( - "Van Genuchten capillary pressure model: " - "The residual liquid saturation value S_L_res = {:g} is out of " - "admissible range [0, 1].", + "Van Genuchten capillary pressure model: The residual liquid " + "saturation value S_L_res = {:g} is out of admissible range [0, " + "1].", S_L_res_); } if (S_L_max_ < 0 || S_L_max_ > 1) { OGS_FATAL( - "Van Genuchten capillary pressure model: " - "The maximum liquid saturation value S_L_max = {:g} is out of " - "admissible range [0, 1].", + "Van Genuchten capillary pressure model: The maximum liquid " + "saturation value S_L_max = {:g} is out of admissible range [0, " + "1].", S_L_max_); } if (S_L_res_ >= S_L_max_) { OGS_FATAL( - "Van Genuchten capillary pressure model: " - "The maximum liquid saturation S_L_max = {:g} must not be less or " - "equal to the residual liquid saturion S_L_res = { : g}.", + "Van Genuchten capillary pressure model: The maximum liquid " + "saturation S_L_max = {:g} must not be less or equal to the " + "residual liquid saturion S_L_res = { : g}.", S_L_max_, S_L_res_); } if (!(m_ > 0 && m_ < 1)) { OGS_FATAL( - "Van Genuchten capillary pressure model: " - "The exponent value m = {:g} is out of of admissible range (0, 1).", + "Van Genuchten capillary pressure model: The exponent value m = " + "{:g} is out of of admissible range (0, 1).", m_); } if (p_b_ <= 0) { OGS_FATAL( - "Van Genuchten capillary pressure model: " - "The pressure scaling value p_b = {:g} must be positive.", + "Van Genuchten capillary pressure model: The pressure scaling " + "value p_b = {:g} must be positive.", p_b_); } if (p_cap_max_ < 0) { OGS_FATAL( - "Van Genuchten capillary pressure model: " - "The maximum capillary pressure value p_cap_max = {:g} must be " - "non-negative.", + "Van Genuchten capillary pressure model: The maximum capillary " + "pressure value p_cap_max = {:g} must be non-negative.", p_cap_max_); } } diff --git a/MaterialLib/MPL/Properties/CapillaryPressureSaturation/SaturationLiakopoulos.cpp b/MaterialLib/MPL/Properties/CapillaryPressureSaturation/SaturationLiakopoulos.cpp index 65a254f31774fbf93f64d0a72709db4fbcb728d6..d8d0069aacb1f80daf4cf7517c2866ed8b2d312f 100644 --- a/MaterialLib/MPL/Properties/CapillaryPressureSaturation/SaturationLiakopoulos.cpp +++ b/MaterialLib/MPL/Properties/CapillaryPressureSaturation/SaturationLiakopoulos.cpp @@ -14,12 +14,12 @@ #include "SaturationLiakopoulos.h" -#include "MaterialLib/MPL/Medium.h" -#include "MathLib/MathTools.h" - #include <algorithm> #include <cmath> +#include "MaterialLib/MPL/Medium.h" +#include "MathLib/MathTools.h" + namespace MaterialPropertyLib { PropertyDataType SaturationLiakopoulos::value( @@ -44,8 +44,8 @@ PropertyDataType SaturationLiakopoulos::dValue( { (void)primary_variable; assert((primary_variable == Variable::capillary_pressure) && - "SaturationLiakopoulos::dvalue is implemented for " - " derivatives with respect to capillary pressure only."); + "SaturationLiakopoulos::dvalue is implemented for derivatives with " + "respect to capillary pressure only."); const double p_cap = std::get<double>( variable_array[static_cast<int>(Variable::capillary_pressure)]); @@ -69,8 +69,8 @@ PropertyDataType SaturationLiakopoulos::d2Value( (void)primary_variable2; assert((primary_variable1 == Variable::capillary_pressure) && (primary_variable2 == Variable::capillary_pressure) && - "SaturationLiakopoulos::ddvalue is implemented for " - " derivatives with respect to capillary pressure only."); + "SaturationLiakopoulos::ddvalue is implemented for derivatives " + "with respect to capillary pressure only."); const double p_cap = std::get<double>( variable_array[static_cast<int>(Variable::capillary_pressure)]); diff --git a/MaterialLib/MPL/Properties/CapillaryPressureSaturation/SaturationVanGenuchten.cpp b/MaterialLib/MPL/Properties/CapillaryPressureSaturation/SaturationVanGenuchten.cpp index c36e82caf72f83bce6742da73bbe333523169f9d..9e8154c2db020df454ce020a72fc40be23c8c449 100644 --- a/MaterialLib/MPL/Properties/CapillaryPressureSaturation/SaturationVanGenuchten.cpp +++ b/MaterialLib/MPL/Properties/CapillaryPressureSaturation/SaturationVanGenuchten.cpp @@ -107,8 +107,8 @@ PropertyDataType SaturationVanGenuchten::d2Value( (void)primary_variable2; assert((primary_variable1 == Variable::capillary_pressure) && (primary_variable2 == Variable::capillary_pressure) && - "SaturationVanGenuchten::d2Value is implemented for " - " derivatives with respect to capillary pressure only."); + "SaturationVanGenuchten::d2Value is implemented for derivatives " + "with respect to capillary pressure only."); const double p_cap = std::get<double>( variable_array[static_cast<int>(Variable::capillary_pressure)]); diff --git a/MaterialLib/MPL/Properties/ClausiusClapeyron.cpp b/MaterialLib/MPL/Properties/ClausiusClapeyron.cpp index e5b3bfc2feb1b093a749b6c4153a442962e2ea63..34c08fb2889f67da95d0c1374ef0e28fda58a915 100644 --- a/MaterialLib/MPL/Properties/ClausiusClapeyron.cpp +++ b/MaterialLib/MPL/Properties/ClausiusClapeyron.cpp @@ -138,8 +138,8 @@ PropertyDataType ClausiusClapeyron::dValue( return p_vap * dh / R * (1. / T_ref_ - 1. / T) * dM; } OGS_FATAL( - "ClausiusClapeyron::dValue is implemented for derivatives " - "with respect to phase pressure or temperature only."); + "ClausiusClapeyron::dValue is implemented for derivatives with respect " + "to phase pressure or temperature only."); } PropertyDataType ClausiusClapeyron::d2Value( diff --git a/MaterialLib/MPL/Properties/CreateEmbeddedFracturePermeability.cpp b/MaterialLib/MPL/Properties/CreateEmbeddedFracturePermeability.cpp index e3eef7f3a98947711fc8aa21543976ae79126a92..c30721ff28fc6890655d4a02dcbd0487651a81c9 100644 --- a/MaterialLib/MPL/Properties/CreateEmbeddedFracturePermeability.cpp +++ b/MaterialLib/MPL/Properties/CreateEmbeddedFracturePermeability.cpp @@ -9,8 +9,8 @@ */ #include "BaseLib/ConfigTree.h" -#include "ParameterLib/Parameter.h" #include "EmbeddedFracturePermeability.h" +#include "ParameterLib/Parameter.h" namespace MaterialPropertyLib { @@ -20,8 +20,8 @@ std::unique_ptr<Property> createEmbeddedFracturePermeability( if ((geometry_dimension != 2) && (geometry_dimension != 3)) { OGS_FATAL( - "The EmbeddedFracturePermeability is implemented only " - "for 2D or 3D problems"); + "The EmbeddedFracturePermeability is implemented only for 2D or 3D " + "problems"); } //! \ogs_file_param{properties__property__type} @@ -52,7 +52,7 @@ std::unique_ptr<Property> createEmbeddedFracturePermeability( bool n_const = false; Eigen::Matrix<double, 3, 1> n; if (auto const n_ptr = - //! \ogs_file_param{properties__property__EmbeddedFracturePermeability__fracture_normal} + //! \ogs_file_param{properties__property__EmbeddedFracturePermeability__fracture_normal} config.getConfigParameterOptional<std::vector<double>>( "fracture_normal")) { @@ -69,8 +69,9 @@ std::unique_ptr<Property> createEmbeddedFracturePermeability( } else { - DBUG("No constant fracture normal was given. By default it will be " - "determined as the third principal stress vector."); + DBUG( + "No constant fracture normal was given. By default it will be " + "determined as the third principal stress vector."); } if (geometry_dimension == 2) diff --git a/MaterialLib/MPL/Properties/CreateGasPressureDependentPermeability.cpp b/MaterialLib/MPL/Properties/CreateGasPressureDependentPermeability.cpp index 2cc3fcaf3ef398e3b0f554f1124f125cc2ae3489..c51eafe25bda78e82d0acccc8bbf94f7ed1226f0 100644 --- a/MaterialLib/MPL/Properties/CreateGasPressureDependentPermeability.cpp +++ b/MaterialLib/MPL/Properties/CreateGasPressureDependentPermeability.cpp @@ -32,8 +32,8 @@ std::unique_ptr<Property> createGasPressureDependentPermeability( if ((geometry_dimension != 2) && (geometry_dimension != 3)) { OGS_FATAL( - "The GasPressureDependentPermeability is implemented only " - "for 2D or 3D problems"); + "The GasPressureDependentPermeability is implemented only for 2D " + "or 3D problems"); } //! \ogs_file_param{properties__property__type} diff --git a/MaterialLib/MPL/Properties/CreateLinear.cpp b/MaterialLib/MPL/Properties/CreateLinear.cpp index 3be14b4374b7dccdd4b44ba76d4a47a625523d01..037f1aae4135577aa35d2a89951b128734a020c7 100644 --- a/MaterialLib/MPL/Properties/CreateLinear.cpp +++ b/MaterialLib/MPL/Properties/CreateLinear.cpp @@ -15,8 +15,7 @@ namespace MaterialPropertyLib { -std::unique_ptr<Linear> createLinear( - BaseLib::ConfigTree const& config) +std::unique_ptr<Linear> createLinear(BaseLib::ConfigTree const& config) { //! \ogs_file_param{properties__property__type} config.checkConfigParameter("type", "Linear"); @@ -31,10 +30,9 @@ std::unique_ptr<Linear> createLinear( config.getConfigParameter<double>("reference_value"); std::vector<MaterialPropertyLib::IndependentVariable> ivs; - for ( - auto const& independent_variable_config : - //! \ogs_file_param{properties__property__Linear__independent_variable} - config.getConfigSubtreeList("independent_variable")) + for (auto const& independent_variable_config : + //! \ogs_file_param{properties__property__Linear__independent_variable} + config.getConfigSubtreeList("independent_variable")) { auto const& variable_name = //! \ogs_file_param{properties__property__Linear__independent_variable__variable_name} diff --git a/MaterialLib/MPL/Properties/CreateParameter.cpp b/MaterialLib/MPL/Properties/CreateParameter.cpp index d77003c1f34f138a146701ae51cc309d25997e14..225685406887cfc79d2123d376e8d1a391fd4495 100644 --- a/MaterialLib/MPL/Properties/CreateParameter.cpp +++ b/MaterialLib/MPL/Properties/CreateParameter.cpp @@ -13,11 +13,10 @@ #include "CreateParameter.h" #include "BaseLib/ConfigTree.h" +#include "Parameter.h" #include "ParameterLib/Parameter.h" #include "ParameterLib/Utils.h" -#include "Parameter.h" - namespace MaterialPropertyLib { std::unique_ptr<Parameter> createParameterProperty( diff --git a/MaterialLib/MPL/Properties/CreatePermeabilityMohrCoulombFailureIndexModel.cpp b/MaterialLib/MPL/Properties/CreatePermeabilityMohrCoulombFailureIndexModel.cpp index ee981c205006a987d6215523ae8e817425827a36..35b6a925ea553b132ea746b7718abf101f9f3784 100644 --- a/MaterialLib/MPL/Properties/CreatePermeabilityMohrCoulombFailureIndexModel.cpp +++ b/MaterialLib/MPL/Properties/CreatePermeabilityMohrCoulombFailureIndexModel.cpp @@ -48,8 +48,7 @@ std::unique_ptr<Property> createPermeabilityMohrCoulombFailureIndexModel( std::string const& parameter_name = //! \ogs_file_param{properties__property__PermeabilityMohrCoulombFailureIndexModel__initial_permeability} - config.getConfigParameter<std::string>( - "initial_permeability"); + config.getConfigParameter<std::string>("initial_permeability"); auto const& parameter_k0 = ParameterLib::findParameter<double>( parameter_name, parameters, 0, nullptr); diff --git a/MaterialLib/MPL/Properties/CreatePermeabilityOrthotropicPowerLaw.cpp b/MaterialLib/MPL/Properties/CreatePermeabilityOrthotropicPowerLaw.cpp index 6620ea774b72cefb3ddfd43599ac568813fcec52..45dbf1befa1fb60f95eabb3e7160b3affa8848b3 100644 --- a/MaterialLib/MPL/Properties/CreatePermeabilityOrthotropicPowerLaw.cpp +++ b/MaterialLib/MPL/Properties/CreatePermeabilityOrthotropicPowerLaw.cpp @@ -33,7 +33,7 @@ std::unique_ptr<Property> createPermeabilityOrthotropicPowerLaw( "intrinsic_permeabilities"); if (!((intrinsic_permeabilities.size() == 3) || - (intrinsic_permeabilities.size() == 2))) + (intrinsic_permeabilities.size() == 2))) { OGS_FATAL( "The number of intrinsic permeabilities must be two or three, but " diff --git a/MaterialLib/MPL/Properties/CreateStrainDependentPermeability.cpp b/MaterialLib/MPL/Properties/CreateStrainDependentPermeability.cpp index 626accca9c9276f663e472ac418214102b7a19e7..aaad96dd2fc146cb0e6988bf7d83bd6f953bb910 100644 --- a/MaterialLib/MPL/Properties/CreateStrainDependentPermeability.cpp +++ b/MaterialLib/MPL/Properties/CreateStrainDependentPermeability.cpp @@ -32,8 +32,8 @@ std::unique_ptr<Property> createStrainDependentPermeability( if ((geometry_dimension != 2) && (geometry_dimension != 3)) { OGS_FATAL( - "The StrainDependentPermeability is implemented only " - "for 2D or 3D problems"); + "The StrainDependentPermeability is implemented only for 2D or 3D " + "problems"); } //! \ogs_file_param{properties__property__type} diff --git a/MaterialLib/MPL/Properties/EmbeddedFracturePermeability.cpp b/MaterialLib/MPL/Properties/EmbeddedFracturePermeability.cpp index 1188c40b1a590d5ef4dc1c6c3c5d094d50050395..d4edd046a14ce226e88c28207ce0bd8499f1c930 100644 --- a/MaterialLib/MPL/Properties/EmbeddedFracturePermeability.cpp +++ b/MaterialLib/MPL/Properties/EmbeddedFracturePermeability.cpp @@ -17,15 +17,14 @@ namespace MaterialPropertyLib { template <int DisplacementDim> -EmbeddedFracturePermeability<DisplacementDim>:: - EmbeddedFracturePermeability( - std::string name, - Eigen::Matrix<double, 3, 1> const fracture_normal, - bool const fracture_normal_is_constant, - double const intrinsic_permeability, - double const initial_aperture, - double const mean_fracture_distance, - double const threshold_strain) +EmbeddedFracturePermeability<DisplacementDim>::EmbeddedFracturePermeability( + std::string name, + Eigen::Matrix<double, 3, 1> const fracture_normal, + bool const fracture_normal_is_constant, + double const intrinsic_permeability, + double const initial_aperture, + double const mean_fracture_distance, + double const threshold_strain) : _n(fracture_normal), _n_const(fracture_normal_is_constant), _k(intrinsic_permeability), diff --git a/MaterialLib/MPL/Properties/Enthalpy/LinearWaterVapourLatentHeat.cpp b/MaterialLib/MPL/Properties/Enthalpy/LinearWaterVapourLatentHeat.cpp index e4250d201af1bbbf73e5d6a2a97a88d9683ec95f..a6456e00ad8dc1c879580b6781c1bfacadae3717 100644 --- a/MaterialLib/MPL/Properties/Enthalpy/LinearWaterVapourLatentHeat.cpp +++ b/MaterialLib/MPL/Properties/Enthalpy/LinearWaterVapourLatentHeat.cpp @@ -42,8 +42,8 @@ PropertyDataType LinearWaterVapourLatentHeat::dValue( } OGS_FATAL( - "LinearWaterVapourLatentHeat::dValue is implemented for " - "the derivative with respect to temperature only."); + "LinearWaterVapourLatentHeat::dValue is implemented for the derivative " + "with respect to temperature only."); } } // namespace MaterialPropertyLib diff --git a/MaterialLib/MPL/Properties/Exponential.cpp b/MaterialLib/MPL/Properties/Exponential.cpp index ceaf7059fe98e8b19e66aa5d09ad83dc96bcadd0..7adde4fc35701f226f5be4a9d8d83d5e49576cc0 100644 --- a/MaterialLib/MPL/Properties/Exponential.cpp +++ b/MaterialLib/MPL/Properties/Exponential.cpp @@ -8,11 +8,11 @@ * http://www.opengeosys.org/project/license */ +#include "MaterialLib/MPL/Properties/Exponential.h" + #include <boost/math/special_functions/pow.hpp> #include <cmath> -#include "MaterialLib/MPL/Properties/Exponential.h" - namespace MaterialPropertyLib { Exponential::Exponential(std::string name, diff --git a/MaterialLib/MPL/Properties/GasPressureDependentPermeability.cpp b/MaterialLib/MPL/Properties/GasPressureDependentPermeability.cpp index 5eb240d09bff72dbca066e810e4fa8ae4f19a503..c163598e75f9889e6f863ad7db9108b64ee86cf7 100644 --- a/MaterialLib/MPL/Properties/GasPressureDependentPermeability.cpp +++ b/MaterialLib/MPL/Properties/GasPressureDependentPermeability.cpp @@ -46,8 +46,8 @@ void GasPressureDependentPermeability<DisplacementDim>::checkScale() const if (!std::holds_alternative<Medium*>(scale_)) { OGS_FATAL( - "The property 'GasPressureDependentPermeability' is " - "implemented on the 'medium' scale only."); + "The property 'GasPressureDependentPermeability' is implemented on " + "the 'medium' scale only."); } } diff --git a/MaterialLib/MPL/Properties/IdealGasLaw.cpp b/MaterialLib/MPL/Properties/IdealGasLaw.cpp index 8059a2a049f7f364bd82595912b42b85e2569693..d362a23a1a63ccc93b756e51fb6f2f75e9fdab20 100644 --- a/MaterialLib/MPL/Properties/IdealGasLaw.cpp +++ b/MaterialLib/MPL/Properties/IdealGasLaw.cpp @@ -14,6 +14,7 @@ */ #include "MaterialLib/MPL/Properties/IdealGasLaw.h" + #include "MaterialLib/MPL/Medium.h" #include "MaterialLib/PhysicalConstant.h" @@ -77,8 +78,8 @@ PropertyDataType IdealGasLaw::dValue(VariableArray const& variable_array, } OGS_FATAL( - "IdealGasLaw::dValue is implemented for derivatives " - "with respect to phase pressure or temperature only."); + "IdealGasLaw::dValue is implemented for derivatives with respect to " + "phase pressure or temperature only."); return 0.; } @@ -119,8 +120,8 @@ PropertyDataType IdealGasLaw::d2Value(VariableArray const& variable_array, } OGS_FATAL( - "IdealGasLaw::d2Value is implemented for derivatives " - "with respect to phase pressure and temperature only."); + "IdealGasLaw::d2Value is implemented for derivatives with respect to " + "phase pressure and temperature only."); return 0.; } diff --git a/MaterialLib/MPL/Properties/KozenyCarmanModel.cpp b/MaterialLib/MPL/Properties/KozenyCarmanModel.cpp index 060f6e511b2fe5d2981ec2a89d6d8d2fed2e261a..46f58662733ec6f199b1b6dd7cb024dbfdd7410c 100644 --- a/MaterialLib/MPL/Properties/KozenyCarmanModel.cpp +++ b/MaterialLib/MPL/Properties/KozenyCarmanModel.cpp @@ -8,11 +8,11 @@ * http://www.opengeosys.org/project/license */ +#include "KozenyCarmanModel.h" + #include <algorithm> #include <cmath> -#include "KozenyCarmanModel.h" - namespace MaterialPropertyLib { PropertyDataType KozenyCarmanModel::value( diff --git a/MaterialLib/MPL/Properties/Linear.cpp b/MaterialLib/MPL/Properties/Linear.cpp index 9c192f19eeaacb88fa8d7ef27e9325e55eab1199..7bf9ee1f7d94b81b84e8b328c59b5bc942de7b6a 100644 --- a/MaterialLib/MPL/Properties/Linear.cpp +++ b/MaterialLib/MPL/Properties/Linear.cpp @@ -8,10 +8,10 @@ * http://www.opengeosys.org/project/license */ -#include <numeric> - #include "MaterialLib/MPL/Properties/Linear.h" +#include <numeric> + namespace MaterialPropertyLib { Linear::Linear(std::string name, diff --git a/MaterialLib/MPL/Properties/PermeabilityOrthotropicPowerLaw.cpp b/MaterialLib/MPL/Properties/PermeabilityOrthotropicPowerLaw.cpp index 4974f4544d681b6dc045ceba40fa85ba4ebf98ed..4affdb393cd59dc75bc0d0d768c2ae6229461123 100644 --- a/MaterialLib/MPL/Properties/PermeabilityOrthotropicPowerLaw.cpp +++ b/MaterialLib/MPL/Properties/PermeabilityOrthotropicPowerLaw.cpp @@ -40,8 +40,8 @@ void PermeabilityOrthotropicPowerLaw<DisplacementDim>::checkScale() const if (!std::holds_alternative<Medium*>(scale_)) { OGS_FATAL( - "The property 'PermeabilityOrthotropicPowerLaw' is " - "implemented on the 'medium' scales only."); + "The property 'PermeabilityOrthotropicPowerLaw' is implemented on " + "the 'medium' scales only."); } } template <int DisplacementDim> @@ -93,8 +93,8 @@ PropertyDataType PermeabilityOrthotropicPowerLaw<DisplacementDim>::dValue( { (void)primary_variable; assert((primary_variable == Variable::total_strain) && - "PermeabilityOrthotropicPowerLaw::dValue is implemented for " - " derivatives with respect to total strain only."); + "PermeabilityOrthotropicPowerLaw::dValue is implemented for " + "derivatives with respect to total strain only."); return 0.; } diff --git a/MaterialLib/MPL/Properties/RelativePermeability/RelPermNonWettingPhaseVanGenuchtenMualem.cpp b/MaterialLib/MPL/Properties/RelativePermeability/RelPermNonWettingPhaseVanGenuchtenMualem.cpp index 66fa669c89c6cfabcacaaaf7d26a5a7aa2689fb9..ca8bdbfd8de651dbd545c145026be2cb2138f8e3 100644 --- a/MaterialLib/MPL/Properties/RelativePermeability/RelPermNonWettingPhaseVanGenuchtenMualem.cpp +++ b/MaterialLib/MPL/Properties/RelativePermeability/RelPermNonWettingPhaseVanGenuchtenMualem.cpp @@ -118,9 +118,8 @@ double RelPermNonWettingPhaseVanGenuchtenMualem:: OGS_FATAL( "The given minimum relative permeability, {:g}, is not " - "associated with the saturation in the range of '('{:f}, " - "{:f}')'. Please try another one in '(0, 1)', which should be " - "close to zero", + "associated with the saturation in the range of '('{:f}, {:f}')'. " + "Please try another one in '(0, 1)', which should be close to zero", krel_min_, S_L_r_, S_L_max_); } } // namespace MaterialPropertyLib diff --git a/MaterialLib/MPL/Properties/RelativePermeability/RelPermUdellNonwettingPhase.cpp b/MaterialLib/MPL/Properties/RelativePermeability/RelPermUdellNonwettingPhase.cpp index f19e4d0da8f374796f51fbd25fb38c5a131271b4..bfc695e08d798eecfa89773ebc006bb4aefb90c5 100644 --- a/MaterialLib/MPL/Properties/RelativePermeability/RelPermUdellNonwettingPhase.cpp +++ b/MaterialLib/MPL/Properties/RelativePermeability/RelPermUdellNonwettingPhase.cpp @@ -74,8 +74,8 @@ PropertyDataType RelPermUdellNonwettingPhase::dValue( { (void)primary_variable; assert((primary_variable == Variable::liquid_saturation) && - "RelPermUdellNonwettingPhase::dValue is implemented for " - " derivatives with respect to liquid saturation only."); + "RelPermUdellNonwettingPhase::dValue is implemented for " + "derivatives with respect to liquid saturation only."); const double S_L = std::get<double>( variable_array[static_cast<int>(Variable::liquid_saturation)]); diff --git a/MaterialLib/MPL/Properties/SaturationDependentHeatConduction.cpp b/MaterialLib/MPL/Properties/SaturationDependentHeatConduction.cpp index f5d49d606fbe0e0c1b5e6b29f03bc4bb18f35c4b..a08c07fd062bf3bac36112bb4ca5cf6ef9981007 100644 --- a/MaterialLib/MPL/Properties/SaturationDependentHeatConduction.cpp +++ b/MaterialLib/MPL/Properties/SaturationDependentHeatConduction.cpp @@ -49,8 +49,7 @@ PropertyDataType SaturationDependentHeatConduction::dValue( (void)variable; assert((variable == Variable::liquid_saturation) && "SaturationDependentHeatConduction::dvalue is implemented for " - "derivatives with " - "respect to liquid saturation only."); + "derivatives with respect to liquid saturation only."); return K_wet_ - K_dry_; } diff --git a/MaterialLib/MPL/Properties/SaturationDependentSwelling.cpp b/MaterialLib/MPL/Properties/SaturationDependentSwelling.cpp index 1e0a1836389d7d98a0ab29afdf9b3c83db722321..e3b967f4c005bc7d2069e5dfa441e19dc4577a44 100644 --- a/MaterialLib/MPL/Properties/SaturationDependentSwelling.cpp +++ b/MaterialLib/MPL/Properties/SaturationDependentSwelling.cpp @@ -40,8 +40,8 @@ void SaturationDependentSwelling::checkScale() const if (!std::holds_alternative<Phase*>(scale_)) { OGS_FATAL( - "The property 'SaturationDependentSwelling' is " - "implemented on the 'phase' scales only."); + "The property 'SaturationDependentSwelling' is implemented on the " + "'phase' scales only."); } auto const phase = std::get<Phase*>(scale_); if (phase->name != "Solid") @@ -74,7 +74,7 @@ PropertyDataType SaturationDependentSwelling::value( if (S_L < S_min_) { - return delta_sigma_sw; // still being zero. + return delta_sigma_sw; // still being zero. } double const S_eff = std::clamp((S_L - S_min_) / (S_max_ - S_min_), 0., 1.); @@ -106,8 +106,8 @@ PropertyDataType SaturationDependentSwelling::dValue( { (void)primary_variable; assert((primary_variable == Variable::liquid_saturation) && - "SaturationDependentSwelling::dValue is implemented for " - " derivatives with respect to liquid saturation only."); + "SaturationDependentSwelling::dValue is implemented for " + "derivatives with respect to liquid saturation only."); auto const S_L = std::get<double>( variable_array[static_cast<int>(Variable::liquid_saturation)]); @@ -124,7 +124,7 @@ PropertyDataType SaturationDependentSwelling::dValue( if (S_L < S_min_) { - return delta_sigma_sw; // still being zero. + return delta_sigma_sw; // still being zero. } double const S_eff = std::clamp((S_L - S_min_) / (S_max_ - S_min_), 0., 1.); diff --git a/MaterialLib/MPL/Properties/StrainDependentPermeability.cpp b/MaterialLib/MPL/Properties/StrainDependentPermeability.cpp index 5769a7cf60c87d5ee1ec72a37d4b637c30bf3919..85ec9b4a4dd095ccdb73f09b081692bcd16d1e57 100644 --- a/MaterialLib/MPL/Properties/StrainDependentPermeability.cpp +++ b/MaterialLib/MPL/Properties/StrainDependentPermeability.cpp @@ -108,8 +108,7 @@ PropertyDataType StrainDependentPermeability<DisplacementDim>::dValue( OGS_FATAL( "The derivative of the intrinsic permeability of " - "StrainDependentPermeability" - "is not implemented."); + "StrainDependentPermeabilityis not implemented."); } template class StrainDependentPermeability<2>; template class StrainDependentPermeability<3>; diff --git a/MaterialLib/MPL/Properties/ThermalConductivity/SoilThermalConductivitySomerton.cpp b/MaterialLib/MPL/Properties/ThermalConductivity/SoilThermalConductivitySomerton.cpp index 217bed6dfbac0b962898fb72f1ec598bd30a80e5..474a47612f1a693f3f31d62cfb46557d287ddd03 100644 --- a/MaterialLib/MPL/Properties/ThermalConductivity/SoilThermalConductivitySomerton.cpp +++ b/MaterialLib/MPL/Properties/ThermalConductivity/SoilThermalConductivitySomerton.cpp @@ -54,8 +54,8 @@ SoilThermalConductivitySomerton<1>::SoilThermalConductivitySomerton( { OGS_FATAL( "In 'SoilThermalConductivitySomerton', " - "dry_thermal_conductivity of '{:g}' is " - "larger than wet_thermal_conductivity of '{:g}'.", + "dry_thermal_conductivity of '{:g}' is larger than " + "wet_thermal_conductivity of '{:g}'.", lambda_try, lambda_wet); } } @@ -134,9 +134,9 @@ SoilThermalConductivitySomerton<GlobalDimension>:: if (lambda_try.size() != lambda_wet.size()) { OGS_FATAL( - "In 'SoilThermalConductivitySomerton' input data, " - "the data size of dry_thermal_conductivity of '{:d}' is " - "different from that of dry_thermal_conductivity of '{:d}'.", + "In 'SoilThermalConductivitySomerton' input data, the data size of " + "dry_thermal_conductivity of '{:d}' is different from that of " + "dry_thermal_conductivity of '{:d}'.", lambda_try.size(), lambda_wet.size()); } @@ -146,8 +146,8 @@ SoilThermalConductivitySomerton<GlobalDimension>:: { OGS_FATAL( "In 'SoilThermalConductivitySomerton', " - "dry_thermal_conductivity of '{:g}' is " - "larger than wet_thermal_conductivity of '{:g}'.", + "dry_thermal_conductivity of '{:g}' is larger than " + "wet_thermal_conductivity of '{:g}'.", lambda_try[i], lambda_wet[i]); } } diff --git a/MaterialLib/MPL/Properties/VapourDiffusion/VapourDiffusionFEBEX.cpp b/MaterialLib/MPL/Properties/VapourDiffusion/VapourDiffusionFEBEX.cpp index be9b0d5f3eb02696ce82ed39a76c5541da63fbd0..4ab078db1ec631218ebea14da42516eec369c998 100644 --- a/MaterialLib/MPL/Properties/VapourDiffusion/VapourDiffusionFEBEX.cpp +++ b/MaterialLib/MPL/Properties/VapourDiffusion/VapourDiffusionFEBEX.cpp @@ -76,8 +76,8 @@ PropertyDataType VapourDiffusionFEBEX::dValue( } OGS_FATAL( - "VapourDiffusionFEBEX::dValue is implemented for " - "derivatives with respect to temperature or saturation only."); + "VapourDiffusionFEBEX::dValue is implemented for derivatives with " + "respect to temperature or saturation only."); } } // namespace MaterialPropertyLib diff --git a/MaterialLib/MPL/Utils/CheckVanGenuchtenExponentRange.cpp b/MaterialLib/MPL/Utils/CheckVanGenuchtenExponentRange.cpp index 27fee4cfedc7ba652131d55b4692c2a4c4bfce0b..b966a62216847981456ee7d50e22ae6bdf5d5469 100644 --- a/MaterialLib/MPL/Utils/CheckVanGenuchtenExponentRange.cpp +++ b/MaterialLib/MPL/Utils/CheckVanGenuchtenExponentRange.cpp @@ -20,8 +20,8 @@ void checkVanGenuchtenExponentRange(const double m) if (m <= 0 || m >= 1) { OGS_FATAL( - "The exponent value m = {:e} of van Genuchten saturation " - "model, is out of its range of(0, 1) ", + "The exponent value m = {:e} of van Genuchten saturation model, is " + "out of its range of(0, 1) ", m); } } diff --git a/MaterialLib/MPL/Utils/FormEigenTensor.cpp b/MaterialLib/MPL/Utils/FormEigenTensor.cpp index 28ad0fdc018d6f78e3222319567d1773d2bef446..596c339944ea11fb0bf438d8e3f46359156c9e2e 100644 --- a/MaterialLib/MPL/Utils/FormEigenTensor.cpp +++ b/MaterialLib/MPL/Utils/FormEigenTensor.cpp @@ -49,7 +49,8 @@ struct FormEigenTensor Eigen::Matrix<double, GlobalDim, GlobalDim> operator()( Eigen::Matrix<double, 2, 2> const& values) const { - if constexpr (GlobalDim == 2) { + if constexpr (GlobalDim == 2) + { return values; } OGS_FATAL("Cannot convert a 2d tensor to {:d}x{:d} matrix", GlobalDim, @@ -58,7 +59,8 @@ struct FormEigenTensor Eigen::Matrix<double, GlobalDim, GlobalDim> operator()( Eigen::Matrix<double, 3, 3> const& values) const { - if constexpr (GlobalDim == 3) { + if constexpr (GlobalDim == 3) + { return values; } OGS_FATAL("Cannot convert a 3d tensor to {:d}x{:d} matrix", GlobalDim, @@ -70,7 +72,7 @@ struct FormEigenTensor { Eigen::Matrix<double, GlobalDim, GlobalDim> result; if constexpr (GlobalDim == 2) - { // skip the z-direction in this case + { // skip the z-direction in this case result << values[0], values[3], values[3], values[1]; } if constexpr (GlobalDim == 3) diff --git a/MaterialLib/MPL/Utils/FormEigenVector.cpp b/MaterialLib/MPL/Utils/FormEigenVector.cpp index 372cd9c6d08fe4482a8d008ce2632e688eadbab6..c1936821ada0f29f1bc14c12d1442ac5e1d0e9a1 100644 --- a/MaterialLib/MPL/Utils/FormEigenVector.cpp +++ b/MaterialLib/MPL/Utils/FormEigenVector.cpp @@ -26,11 +26,11 @@ struct FormEigenVector } if constexpr (GlobalDim == 2) { - return Eigen::Matrix<double, 2, 1>{ value, value }; + return Eigen::Matrix<double, 2, 1>{value, value}; } if constexpr (GlobalDim == 3) { - return Eigen::Matrix<double, 3, 1>{ value, value, value }; + return Eigen::Matrix<double, 3, 1>{value, value, value}; } } diff --git a/MaterialLib/MPL/Utils/FormKelvinVectorFromThermalExpansivity.cpp b/MaterialLib/MPL/Utils/FormKelvinVectorFromThermalExpansivity.cpp index 20c10f18a5c20815234be4b8a641030702674ddf..1509f87aaff5a1f81c76c7077e349ccde0899c5a 100644 --- a/MaterialLib/MPL/Utils/FormKelvinVectorFromThermalExpansivity.cpp +++ b/MaterialLib/MPL/Utils/FormKelvinVectorFromThermalExpansivity.cpp @@ -16,9 +16,9 @@ namespace MaterialPropertyLib { static const char error_info[] = - "The thermal expansivity can only be either a scalar number for " - "isotropic thermal expansion or a three element array for anisotropic " - "thermal expansion."; + "The thermal expansivity can only be either a scalar number for isotropic " + "thermal expansion or a three element array for anisotropic thermal " + "expansion."; template <int GlobalDim> struct FormKelvinVectorFromThermalExpansivity diff --git a/MaterialLib/MPL/Utils/GetSymmetricTensor.cpp b/MaterialLib/MPL/Utils/GetSymmetricTensor.cpp index e5230dc18cd3a1a42b665cea61939fa3f4fe3c98..84eaf0b65bc88f8895d29fb89dd00810a3743465 100644 --- a/MaterialLib/MPL/Utils/GetSymmetricTensor.cpp +++ b/MaterialLib/MPL/Utils/GetSymmetricTensor.cpp @@ -55,8 +55,8 @@ struct GetSymmetricTensor if constexpr (GlobalDim == 3) { SymmetricTensor<GlobalDim> result; - result << values(0, 0), values(1, 1), values(2, 2), - values(0, 1), values(1, 2), values(0, 2); + result << values(0, 0), values(1, 1), values(2, 2), values(0, 1), + values(1, 2), values(0, 2); return result; } OGS_FATAL("Cannot convert 3d matrix to 2d symmetric Tensor."); diff --git a/MaterialLib/MPL/VariableType.cpp b/MaterialLib/MPL/VariableType.cpp index 5b5ddf27014330a28cecfca5664da9c88adef8e5..3a77a5f9fe08fee4ac117f715a9353cc203c012b 100644 --- a/MaterialLib/MPL/VariableType.cpp +++ b/MaterialLib/MPL/VariableType.cpp @@ -9,7 +9,9 @@ */ #include "VariableType.h" + #include <boost/algorithm/string/predicate.hpp> + #include "BaseLib/Error.h" namespace MaterialPropertyLib diff --git a/MaterialLib/PorousMedium/CreatePorousMediaProperties.cpp b/MaterialLib/PorousMedium/CreatePorousMediaProperties.cpp index f0105867a2016014bc98ddccd8b1b9f8c50e8a16..90c05fc7a75f3333eb4561e4316a1ca4ed919b66 100644 --- a/MaterialLib/PorousMedium/CreatePorousMediaProperties.cpp +++ b/MaterialLib/PorousMedium/CreatePorousMediaProperties.cpp @@ -12,7 +12,6 @@ #include "BaseLib/Algorithm.h" #include "MeshLib/Mesh.h" - #include "Permeability/createPermeabilityModel.h" #include "Porosity/createPorosityModel.h" #include "Storage/createStorageModel.h" @@ -43,7 +42,7 @@ PorousMediaProperties createPorousMediaProperties( //! \ogs_file_param{material__porous_medium__porous_medium} porous_medium_configs.getConfigSubtreeList("porous_medium")) { - //! \ogs_file_attr{material__porous_medium__porous_medium__id} + //! \ogs_file_attr{material__porous_medium__porous_medium__id} auto const id = porous_medium_config.getConfigAttribute<int>("id"); mat_ids.push_back(id); @@ -85,9 +84,9 @@ PorousMediaProperties createPorousMediaProperties( { OGS_FATAL( "The maximum value of MaterialIDs in mesh is {:d}. As the " - "given number of porous media definitions in the project " - "file is {:d}, the maximum value of MaterialIDs in mesh must be " - "{:d} (index starts with zero).", + "given number of porous media definitions in the project file is " + "{:d}, the maximum value of MaterialIDs in mesh must be {:d} " + "(index starts with zero).", max_material_id, mat_ids.size(), max_material_id - 1); } diff --git a/MaterialLib/PorousMedium/Permeability/createPermeabilityModel.cpp b/MaterialLib/PorousMedium/Permeability/createPermeabilityModel.cpp index fcc4094cef102065c07773915917520419117aa5..aaff3b77cd71d7ccb39574b3d287f37aabe2c32d 100644 --- a/MaterialLib/PorousMedium/Permeability/createPermeabilityModel.cpp +++ b/MaterialLib/PorousMedium/Permeability/createPermeabilityModel.cpp @@ -15,7 +15,6 @@ #include <cassert> #include "BaseLib/ConfigTree.h" - #include "BaseLib/Error.h" #include "MaterialLib/PorousMedium/Permeability/DupuitPermeability.h" #include "MathLib/LinAlg/Eigen/EigenMapTools.h" @@ -54,8 +53,8 @@ std::unique_ptr<Permeability> createPermeabilityModel( dimension); } - return std::make_unique<Permeability>( - permeability_parameter, dimension); + return std::make_unique<Permeability>(permeability_parameter, + dimension); } if (type == "Dupuit") diff --git a/MaterialLib/PorousMedium/Porosity/createPorosityModel.cpp b/MaterialLib/PorousMedium/Porosity/createPorosityModel.cpp index d5708ae5334a28afb6c0ee25ad6799da152b8db1..84ac1cf7543a4f6bd43be25a6c5169852aff4b29 100644 --- a/MaterialLib/PorousMedium/Porosity/createPorosityModel.cpp +++ b/MaterialLib/PorousMedium/Porosity/createPorosityModel.cpp @@ -15,7 +15,6 @@ #include "BaseLib/ConfigTree.h" #include "BaseLib/Error.h" #include "ParameterLib/Utils.h" - #include "Porosity.h" namespace MaterialLib diff --git a/MaterialLib/PorousMedium/Storage/createStorageModel.cpp b/MaterialLib/PorousMedium/Storage/createStorageModel.cpp index 36f5ed07605226d6bc0b3db224079bd7bead1035..42b6f2ddbad0be29c9132f43c7c367406e6841ac 100644 --- a/MaterialLib/PorousMedium/Storage/createStorageModel.cpp +++ b/MaterialLib/PorousMedium/Storage/createStorageModel.cpp @@ -12,11 +12,10 @@ #include "createStorageModel.h" -#include "BaseLib/Error.h" #include "BaseLib/ConfigTree.h" - -#include "Storage.h" +#include "BaseLib/Error.h" #include "ConstantStorage.h" +#include "Storage.h" namespace MaterialLib { diff --git a/MaterialLib/PorousMedium/UnsaturatedProperty/CapillaryPressure/CreateCapillaryPressureModel.cpp b/MaterialLib/PorousMedium/UnsaturatedProperty/CapillaryPressure/CreateCapillaryPressureModel.cpp index 8d79b41eb86eb40b773d273ae26f55b20c969b40..eb4fd1a9a48e3c8bc0486b1dedc94210945ffca6 100644 --- a/MaterialLib/PorousMedium/UnsaturatedProperty/CapillaryPressure/CreateCapillaryPressureModel.cpp +++ b/MaterialLib/PorousMedium/UnsaturatedProperty/CapillaryPressure/CreateCapillaryPressureModel.cpp @@ -14,13 +14,11 @@ #include "BaseLib/ConfigTree.h" #include "BaseLib/Error.h" - -#include "MathLib/Curve/CreatePiecewiseLinearCurve.h" -#include "MathLib/Curve/PiecewiseLinearMonotonicCurve.h" - #include "BrooksCoreyCapillaryPressureSaturation.h" #include "CapillaryPressureSaturation.h" #include "CapillaryPressureSaturationCurve.h" +#include "MathLib/Curve/CreatePiecewiseLinearCurve.h" +#include "MathLib/Curve/PiecewiseLinearMonotonicCurve.h" #include "VanGenuchtenCapillaryPressureSaturation.h" namespace MaterialLib @@ -157,8 +155,8 @@ std::unique_ptr<CapillaryPressureSaturation> createCapillaryPressureModel( } OGS_FATAL( - "The capillary pressure saturation models {:s} are unavailable.\n" - "The available types are: \n\tBrooksCorey, \n\tvanGenuchten,", + "The capillary pressure saturation models {:s} are unavailable.\nThe " + "available types are: \n\tBrooksCorey, \n\tvanGenuchten,", "\n\tCurve.\n", type.data()); } diff --git a/MaterialLib/PorousMedium/UnsaturatedProperty/RelativePermeability/CreateRelativePermeabilityModel.cpp b/MaterialLib/PorousMedium/UnsaturatedProperty/RelativePermeability/CreateRelativePermeabilityModel.cpp index d0d894d7467f0fda0cbf74cc3a21fa3dd21f900b..c01a268a8df76d0c2d5cf36bbeea1190b17c4bfc 100644 --- a/MaterialLib/PorousMedium/UnsaturatedProperty/RelativePermeability/CreateRelativePermeabilityModel.cpp +++ b/MaterialLib/PorousMedium/UnsaturatedProperty/RelativePermeability/CreateRelativePermeabilityModel.cpp @@ -19,10 +19,8 @@ #include "BaseLib/ConfigTree.h" #include "BaseLib/Error.h" - #include "MathLib/Curve/CreatePiecewiseLinearCurve.h" #include "MathLib/InterpolationAlgorithms/PiecewiseLinearInterpolation.h" - #include "NonWettingPhaseBrooksCoreyOilGas.h" #include "NonWettingPhaseVanGenuchten.h" #include "RelativePermeability.h" @@ -193,8 +191,8 @@ std::unique_ptr<RelativePermeability> createRelativePermeabilityModel( //! \ogs_file_param{material__porous_medium__relative_permeability__Curve__curve} auto const& curve_config = config.getConfigSubtree("curve"); - auto curve = MathLib::createPiecewiseLinearCurve<MathLib - ::PiecewiseLinearInterpolation>(curve_config); + auto curve = MathLib::createPiecewiseLinearCurve< + MathLib ::PiecewiseLinearInterpolation>(curve_config); return std::make_unique<RelativePermeabilityCurve>(std::move(curve)); } diff --git a/MaterialLib/PorousMedium/UnsaturatedProperty/RelativePermeability/NonWettingPhaseVanGenuchten.cpp b/MaterialLib/PorousMedium/UnsaturatedProperty/RelativePermeability/NonWettingPhaseVanGenuchten.cpp index 2d70fc279c9d65d6db42f9a97d6059c932f283ff..9c68eb7c2163b51038b867bb691260de63952027 100644 --- a/MaterialLib/PorousMedium/UnsaturatedProperty/RelativePermeability/NonWettingPhaseVanGenuchten.cpp +++ b/MaterialLib/PorousMedium/UnsaturatedProperty/RelativePermeability/NonWettingPhaseVanGenuchten.cpp @@ -25,8 +25,8 @@ double NonWettingPhaseVanGenuchten::getValue(const double saturation_w) const _saturation_r + _minor_offset, _saturation_max - _minor_offset); const double Se = (S - _saturation_r) / (_saturation_max - _saturation_r); - const double krel = std::cbrt(1.0 - Se) * - std::pow(1.0 - std::pow(Se, 1.0 / _m), 2.0 * _m); + const double krel = + std::cbrt(1.0 - Se) * std::pow(1.0 - std::pow(Se, 1.0 / _m), 2.0 * _m); return std::max(_krel_min, krel); } diff --git a/MaterialLib/SolidModels/CreateConstitutiveRelation.cpp b/MaterialLib/SolidModels/CreateConstitutiveRelation.cpp index 147571c3f6a67faa921e5e5b7f03f6a627c0400c..bd6b2f4a2e307bceca7fb8f067e47794e7cd30bf 100644 --- a/MaterialLib/SolidModels/CreateConstitutiveRelation.cpp +++ b/MaterialLib/SolidModels/CreateConstitutiveRelation.cpp @@ -20,11 +20,9 @@ #include "MFront/CreateMFront.h" #endif // OGS_USE_MFRONT -#include "MechanicsBase.h" - #include "BaseLib/ConfigTree.h" #include "BaseLib/Error.h" - +#include "MechanicsBase.h" #include "ParameterLib/Parameter.h" namespace MaterialLib diff --git a/MaterialLib/SolidModels/CreepBGRa.cpp b/MaterialLib/SolidModels/CreepBGRa.cpp index 7d7f9b7025d7b3b5ffccef15dd8ad2356676e93b..086951b640e9e018a2b15319716868198e327651 100644 --- a/MaterialLib/SolidModels/CreepBGRa.cpp +++ b/MaterialLib/SolidModels/CreepBGRa.cpp @@ -87,7 +87,8 @@ CreepBGRa<DisplacementDim>::integrateStress( double const G2b = 2.0 * b * this->_mp.mu(t, x); - auto const update_jacobian = [&solution, &G2b, &n](JacobianMatrix& jacobian) { + auto const update_jacobian = [&solution, &G2b, + &n](JacobianMatrix& jacobian) { auto const& D = Invariants::deviatoric_projection; KelvinVector const s_n1 = D * solution; double const norm_s_n1 = Invariants::FrobeniusNorm(s_n1); diff --git a/MaterialLib/SolidModels/Ehlers.cpp b/MaterialLib/SolidModels/Ehlers.cpp index 08aed7d4c742a90be37b102c3c9de471b95e6a02..efbc6a5d9f4fd338ffeb6c57b3ab55ed996b6073 100644 --- a/MaterialLib/SolidModels/Ehlers.cpp +++ b/MaterialLib/SolidModels/Ehlers.cpp @@ -111,7 +111,8 @@ double plasticFlowVolumetricPart( double const sqrtPhi, double const alpha_p, double const beta_p, double const delta_p, double const epsilon_p) { - return 3 * (alpha_p * s.I_1 + + return 3 * + (alpha_p * s.I_1 + 4 * boost::math::pow<2>(delta_p) * boost::math::pow<3>(s.I_1)) / (2 * sqrtPhi) + 3 * beta_p + 6 * epsilon_p * s.I_1; @@ -137,13 +138,12 @@ double yieldFunction(MaterialProperties const& mp, double const I_1_squared = boost::math::pow<2>(s.I_1); assert(s.J_2 != 0); - return std::sqrt( - s.J_2 * - std::pow(1 + mp.gamma * s.J_3 / (s.J_2 * std::sqrt(s.J_2)), - mp.m) + - mp.alpha / 2. * I_1_squared + - boost::math::pow<2>(mp.delta) * - boost::math::pow<2>(I_1_squared)) + + return std::sqrt(s.J_2 * std::pow(1 + mp.gamma * s.J_3 / + (s.J_2 * std::sqrt(s.J_2)), + mp.m) + + mp.alpha / 2. * I_1_squared + + boost::math::pow<2>(mp.delta) * + boost::math::pow<2>(I_1_squared)) + mp.beta * s.I_1 + mp.epsilon * I_1_squared - k; } @@ -332,9 +332,8 @@ typename SolidEhlers<DisplacementDim>::JacobianMatrix calculatePlasticJacobian( // derivative of flow_V w.r.t. sigma KelvinVector const dflow_V_dsigma = 3 * mp.G * - (-(mp.alpha_p * s.I_1 + - 4 * boost::math::pow<2>(mp.delta_p) * - boost::math::pow<3>(s.I_1)) / + (-(mp.alpha_p * s.I_1 + 4 * boost::math::pow<2>(mp.delta_p) * + boost::math::pow<3>(s.I_1)) / (4 * boost::math::pow<3>(sqrtPhi)) * dPhi_dsigma + (mp.alpha_p * identity2 + 12 * boost::math::pow<2>(mp.delta_p * s.I_1) * identity2) / @@ -388,11 +387,11 @@ typename SolidEhlers<DisplacementDim>::JacobianMatrix calculatePlasticJacobian( double const gm = mp.gamma * mp.m; // derivative of yield function w.r.t. sigma KelvinVector const dF_dsigma = - mp.G * (one_gt_pow_m * (s.D + gm * M0) + - (mp.alpha * s.I_1 + - 4 * boost::math::pow<2>(mp.delta) * - boost::math::pow<3>(s.I_1)) * - identity2) / + mp.G * + (one_gt_pow_m * (s.D + gm * M0) + + (mp.alpha * s.I_1 + 4 * boost::math::pow<2>(mp.delta) * + boost::math::pow<3>(s.I_1)) * + identity2) / (2. * sqrtPhi) + mp.G * (mp.beta + 2 * mp.epsilon_p * s.I_1) * identity2; @@ -595,7 +594,6 @@ SolidEhlers<DisplacementDim>::integrateStress( solution << sigma, state.eps_p.D, state.eps_p.V, state.eps_p.eff, 0; auto const update_residual = [&](ResidualVectorType& residual) { - auto const& eps_p_D = solution.template segment<KelvinVectorSize>( KelvinVectorSize); @@ -603,8 +601,7 @@ SolidEhlers<DisplacementDim>::integrateStress( (eps_p_D - state.eps_p_prev.D) / dt; double const& eps_p_V = solution[KelvinVectorSize * 2]; - double const eps_p_V_dot = - (eps_p_V - state.eps_p_prev.V) / dt; + double const eps_p_V_dot = (eps_p_V - state.eps_p_prev.V) / dt; double const& eps_p_eff = solution[KelvinVectorSize * 2 + 1]; double const eps_p_eff_dot = @@ -711,76 +708,75 @@ template <int DisplacementDim> std::vector<typename MechanicsBase<DisplacementDim>::InternalVariable> SolidEhlers<DisplacementDim>::getInternalVariables() const { - return { - {"damage.kappa_d", 1, - [](typename MechanicsBase< - DisplacementDim>::MaterialStateVariables const& state, - std::vector<double>& cache) -> std::vector<double> const& { - assert(dynamic_cast<StateVariables<DisplacementDim> const*>( - &state) != nullptr); - auto const& ehlers_state = - static_cast<StateVariables<DisplacementDim> const&>(state); - - cache.resize(1); - cache.front() = ehlers_state.damage.kappa_d(); - return cache; - }}, - {"damage.value", 1, - [](typename MechanicsBase< - DisplacementDim>::MaterialStateVariables const& state, - std::vector<double>& cache) -> std::vector<double> const& { - assert(dynamic_cast<StateVariables<DisplacementDim> const*>( - &state) != nullptr); - auto const& ehlers_state = - static_cast<StateVariables<DisplacementDim> const&>(state); - - cache.resize(1); - cache.front() = ehlers_state.damage.value(); - return cache; - }}, - {"eps_p.D", KelvinVector::RowsAtCompileTime, - [](typename MechanicsBase< - DisplacementDim>::MaterialStateVariables const& state, - std::vector<double>& cache) -> std::vector<double> const& { - assert(dynamic_cast<StateVariables<DisplacementDim> const*>( - &state) != nullptr); - auto const& ehlers_state = - static_cast<StateVariables<DisplacementDim> const&>(state); - - cache.resize(KelvinVector::RowsAtCompileTime); - MathLib::toVector<KelvinVector>(cache, - KelvinVector::RowsAtCompileTime) = - MathLib::KelvinVector::kelvinVectorToSymmetricTensor( - ehlers_state.eps_p.D); - - return cache; - }}, - {"eps_p.V", 1, - [](typename MechanicsBase< - DisplacementDim>::MaterialStateVariables const& state, - std::vector<double>& cache) -> std::vector<double> const& { - assert(dynamic_cast<StateVariables<DisplacementDim> const*>( - &state) != nullptr); - auto const& ehlers_state = - static_cast<StateVariables<DisplacementDim> const&>(state); - - cache.resize(1); - cache.front() = ehlers_state.eps_p.V; - return cache; - }}, - {"eps_p.eff", 1, - [](typename MechanicsBase< - DisplacementDim>::MaterialStateVariables const& state, - std::vector<double>& cache) -> std::vector<double> const& { - assert(dynamic_cast<StateVariables<DisplacementDim> const*>( - &state) != nullptr); - auto const& ehlers_state = - static_cast<StateVariables<DisplacementDim> const&>(state); - - cache.resize(1); - cache.front() = ehlers_state.eps_p.eff; - return cache; - }}}; + return {{"damage.kappa_d", 1, + [](typename MechanicsBase< + DisplacementDim>::MaterialStateVariables const& state, + std::vector<double>& cache) -> std::vector<double> const& { + assert(dynamic_cast<StateVariables<DisplacementDim> const*>( + &state) != nullptr); + auto const& ehlers_state = + static_cast<StateVariables<DisplacementDim> const&>(state); + + cache.resize(1); + cache.front() = ehlers_state.damage.kappa_d(); + return cache; + }}, + {"damage.value", 1, + [](typename MechanicsBase< + DisplacementDim>::MaterialStateVariables const& state, + std::vector<double>& cache) -> std::vector<double> const& { + assert(dynamic_cast<StateVariables<DisplacementDim> const*>( + &state) != nullptr); + auto const& ehlers_state = + static_cast<StateVariables<DisplacementDim> const&>(state); + + cache.resize(1); + cache.front() = ehlers_state.damage.value(); + return cache; + }}, + {"eps_p.D", KelvinVector::RowsAtCompileTime, + [](typename MechanicsBase< + DisplacementDim>::MaterialStateVariables const& state, + std::vector<double>& cache) -> std::vector<double> const& { + assert(dynamic_cast<StateVariables<DisplacementDim> const*>( + &state) != nullptr); + auto const& ehlers_state = + static_cast<StateVariables<DisplacementDim> const&>(state); + + cache.resize(KelvinVector::RowsAtCompileTime); + MathLib::toVector<KelvinVector>( + cache, KelvinVector::RowsAtCompileTime) = + MathLib::KelvinVector::kelvinVectorToSymmetricTensor( + ehlers_state.eps_p.D); + + return cache; + }}, + {"eps_p.V", 1, + [](typename MechanicsBase< + DisplacementDim>::MaterialStateVariables const& state, + std::vector<double>& cache) -> std::vector<double> const& { + assert(dynamic_cast<StateVariables<DisplacementDim> const*>( + &state) != nullptr); + auto const& ehlers_state = + static_cast<StateVariables<DisplacementDim> const&>(state); + + cache.resize(1); + cache.front() = ehlers_state.eps_p.V; + return cache; + }}, + {"eps_p.eff", 1, + [](typename MechanicsBase< + DisplacementDim>::MaterialStateVariables const& state, + std::vector<double>& cache) -> std::vector<double> const& { + assert(dynamic_cast<StateVariables<DisplacementDim> const*>( + &state) != nullptr); + auto const& ehlers_state = + static_cast<StateVariables<DisplacementDim> const&>(state); + + cache.resize(1); + cache.front() = ehlers_state.eps_p.eff; + return cache; + }}}; } template class SolidEhlers<2>; diff --git a/MaterialLib/SolidModels/LinearElasticIsotropic.cpp b/MaterialLib/SolidModels/LinearElasticIsotropic.cpp index 21f52e5f1931bc51bcb905d7ca822a627cccb797..8cbd67f4d480e1e13dcf1879b613adad07b33b5c 100644 --- a/MaterialLib/SolidModels/LinearElasticIsotropic.cpp +++ b/MaterialLib/SolidModels/LinearElasticIsotropic.cpp @@ -63,5 +63,5 @@ LinearElasticIsotropic<DisplacementDim>::getElasticTensor( template class LinearElasticIsotropic<2>; template class LinearElasticIsotropic<3>; -} // namespace Solids -} // namespace MaterialLib +} // namespace Solids +} // namespace MaterialLib diff --git a/MaterialLib/SolidModels/MFront/CreateMFront.cpp b/MaterialLib/SolidModels/MFront/CreateMFront.cpp index 2ada8d1e6a7e4013da35a23ace3391b8f75027b7..40165cc7541f4a36aebb297da9b4403cbf23b963 100644 --- a/MaterialLib/SolidModels/MFront/CreateMFront.cpp +++ b/MaterialLib/SolidModels/MFront/CreateMFront.cpp @@ -10,9 +10,8 @@ #include "CreateMFront.h" #include "BaseLib/FileTools.h" -#include "ParameterLib/Utils.h" - #include "MFront.h" +#include "ParameterLib/Utils.h" namespace { /// Prints info about MFront variables. diff --git a/MaterialLib/SolidModels/MFront/MFront.cpp b/MaterialLib/SolidModels/MFront/MFront.cpp index 0d6881ef40fe57145e936359f1c7c4f08ada1e2f..08a6d03445eb646c2ae2e3104f8462a5b6d82517 100644 --- a/MaterialLib/SolidModels/MFront/MFront.cpp +++ b/MaterialLib/SolidModels/MFront/MFront.cpp @@ -361,8 +361,9 @@ MFront<DisplacementDim>::integrateStress( auto const status = mgis::behaviour::integrate(v, _behaviour); if (status != 1) { - throw NumLib::AssemblyException("MFront: integration failed with status" - + std::to_string(status) + "."); + throw NumLib::AssemblyException( + "MFront: integration failed with status" + std::to_string(status) + + "."); } KelvinVector sigma; diff --git a/MaterialLib/TwoPhaseModels/CreateTwoPhaseFlowMaterialProperties.cpp b/MaterialLib/TwoPhaseModels/CreateTwoPhaseFlowMaterialProperties.cpp index 37b9faff0c817c6c4e3ab69fdcaa26a13ca67571..c5b58c8fdee0cb01463b064e1989d58c1569f807 100644 --- a/MaterialLib/TwoPhaseModels/CreateTwoPhaseFlowMaterialProperties.cpp +++ b/MaterialLib/TwoPhaseModels/CreateTwoPhaseFlowMaterialProperties.cpp @@ -9,9 +9,8 @@ #include "CreateTwoPhaseFlowMaterialProperties.h" -#include "BaseLib/Logging.h" - #include "BaseLib/Algorithm.h" +#include "BaseLib/Logging.h" #include "MaterialLib/Fluid/FluidProperty.h" #include "MaterialLib/PorousMedium/Porosity/Porosity.h" #include "MaterialLib/PorousMedium/Storage/Storage.h" @@ -22,7 +21,6 @@ #include "MeshLib/PropertyVector.h" #include "ParameterLib/Parameter.h" #include "ParameterLib/SpatialPosition.h" - #include "TwoPhaseFlowWithPPMaterialProperties.h" namespace MaterialLib diff --git a/MaterialLib/TwoPhaseModels/TwoPhaseFlowWithPPMaterialProperties.cpp b/MaterialLib/TwoPhaseModels/TwoPhaseFlowWithPPMaterialProperties.cpp index 3acf885375824533513caa5f0b33a2ba94026094..cba7fd7ca498eb282a1425e569474f256c7829e9 100644 --- a/MaterialLib/TwoPhaseModels/TwoPhaseFlowWithPPMaterialProperties.cpp +++ b/MaterialLib/TwoPhaseModels/TwoPhaseFlowWithPPMaterialProperties.cpp @@ -11,8 +11,8 @@ #include <boost/math/special_functions/pow.hpp> #include <utility> -#include "BaseLib/Logging.h" +#include "BaseLib/Logging.h" #include "MaterialLib/Fluid/FluidProperty.h" #include "MaterialLib/PorousMedium/Porosity/Porosity.h" #include "MaterialLib/PorousMedium/Storage/Storage.h" diff --git a/MathLib/GeometricBasics.cpp b/MathLib/GeometricBasics.cpp index d04f2059d81a2550a7eccfea190d9a455ae881f4..b9893d29205d357d602e98f32610ea908c033aca 100644 --- a/MathLib/GeometricBasics.cpp +++ b/MathLib/GeometricBasics.cpp @@ -7,14 +7,13 @@ * http://www.opengeosys.org/project/license */ -#include "BaseLib/Logging.h" +#include "GeometricBasics.h" #include <Eigen/Dense> +#include "BaseLib/Logging.h" #include "Point3d.h" -#include "GeometricBasics.h" - namespace MathLib { double orientation3d(MathLib::Point3d const& p, @@ -64,31 +63,31 @@ bool isPointInTetrahedron(MathLib::Point3d const& p, MathLib::Point3d const& a, MathLib::Point3d const& b, MathLib::Point3d const& c, MathLib::Point3d const& d, double eps) { - double const d0 (MathLib::orientation3d(d,a,b,c)); + double const d0(MathLib::orientation3d(d, a, b, c)); // if tetrahedron is not coplanar if (std::abs(d0) > std::numeric_limits<double>::epsilon()) { - bool const d0_sign (d0>0); + bool const d0_sign(d0 > 0); // if p is on the same side of bcd as a - double const d1 (MathLib::orientation3d(d, p, b, c)); + double const d1(MathLib::orientation3d(d, p, b, c)); if (!(d0_sign == (d1 >= 0) || std::abs(d1) < eps)) { return false; } // if p is on the same side of acd as b - double const d2 (MathLib::orientation3d(d, a, p, c)); + double const d2(MathLib::orientation3d(d, a, p, c)); if (!(d0_sign == (d2 >= 0) || std::abs(d2) < eps)) { return false; } // if p is on the same side of abd as c - double const d3 (MathLib::orientation3d(d, a, b, p)); + double const d3(MathLib::orientation3d(d, a, b, p)); if (!(d0_sign == (d3 >= 0) || std::abs(d3) < eps)) { return false; } // if p is on the same side of abc as d - double const d4 (MathLib::orientation3d(p, a, b, c)); + double const d4(MathLib::orientation3d(p, a, b, c)); return d0_sign == (d4 >= 0) || std::abs(d4) < eps; } return false; diff --git a/MathLib/Integration/GaussLegendre.cpp b/MathLib/Integration/GaussLegendre.cpp index 50d802f321aa69efe4422f4e524f6d3df3dc47cf..bde424f321e1d57e5acdc324194babb3aa40cb71 100644 --- a/MathLib/Integration/GaussLegendre.cpp +++ b/MathLib/Integration/GaussLegendre.cpp @@ -14,19 +14,27 @@ namespace MathLib { +template <> +double const GaussLegendre<1>::X[1] = {0.}; +template <> +double const GaussLegendre<1>::W[1] = {2.}; -template <> double const GaussLegendre<1>::X[1] = {0.}; -template <> double const GaussLegendre<1>::W[1] = {2.}; +template <> +double const GaussLegendre<2>::X[2] = {0.577350269189626, -0.577350269189626}; +template <> +double const GaussLegendre<2>::W[2] = {1., 1.}; -template <> double const GaussLegendre<2>::X[2] = {0.577350269189626, -0.577350269189626}; -template <> double const GaussLegendre<2>::W[2] = {1., 1.}; +template <> +double const GaussLegendre<3>::X[3] = {0.774596669241483, 0., + -0.774596669241483}; +template <> +double const GaussLegendre<3>::W[3] = {5. / 9, 8. / 9, 5. / 9}; -template <> double const GaussLegendre<3>::X[3] = {0.774596669241483, 0., -0.774596669241483}; -template <> double const GaussLegendre<3>::W[3] = {5./9, 8./9, 5./9}; +template <> +double const GaussLegendre<4>::X[4] = {-0.861136311594053, -0.339981043584856, + 0.339981043584856, 0.861136311594053}; +template <> +double const GaussLegendre<4>::W[4] = {0.347854845137454, 0.652145154862546, + 0.652145154862546, 0.347854845137454}; -template <> double const GaussLegendre<4>::X[4] = - {-0.861136311594053, -0.339981043584856, 0.339981043584856, 0.861136311594053}; -template <> double const GaussLegendre<4>::W[4] = - { 0.347854845137454, 0.652145154862546, 0.652145154862546, 0.347854845137454}; - -} // namespace MathLib +} // namespace MathLib diff --git a/MathLib/Integration/GaussLegendrePyramid.cpp b/MathLib/Integration/GaussLegendrePyramid.cpp index 3fa19342dd03b95685b78428d2437a8ec486f06e..19140b36baca7a0cf8739b0cff2cbe658091e7ac 100644 --- a/MathLib/Integration/GaussLegendrePyramid.cpp +++ b/MathLib/Integration/GaussLegendrePyramid.cpp @@ -12,50 +12,45 @@ namespace MathLib { - -template <> const std::array<std::array<double, 3>, GaussLegendrePyramid<1>::NPoints> -GaussLegendrePyramid<1>::X = {{{{1./3., 1./3., 1./3.}}}}; -template <> double const GaussLegendrePyramid<1>::W[1] = {1.0}; +template <> +const std::array<std::array<double, 3>, GaussLegendrePyramid<1>::NPoints> + GaussLegendrePyramid<1>::X = {{{{1. / 3., 1. / 3., 1. / 3.}}}}; +template <> +double const GaussLegendrePyramid<1>::W[1] = {1.0}; const std::array<std::array<double, 3>, GaussLegendrePyramid<2>::NPoints> -GaussLegendrePyramid<2>::X = {{ {{-0.584237394672177188, -0.584237394672177188, -2./3.}}, - {{ 0.584237394672177188, -0.584237394672177188, -2./3.}}, - {{ 0.584237394672177188, 0.584237394672177188, -2./3.}}, - {{-0.584237394672177188, 0.584237394672177188, -2./3.}}, - {{0., 0., 2./5.}} - }}; -double const GaussLegendrePyramid<2>::W[5] = {81./100., 81./100., 81./100., 81./100., 125./27.}; + GaussLegendrePyramid<2>::X = { + {{{-0.584237394672177188, -0.584237394672177188, -2. / 3.}}, + {{0.584237394672177188, -0.584237394672177188, -2. / 3.}}, + {{0.584237394672177188, 0.584237394672177188, -2. / 3.}}, + {{-0.584237394672177188, 0.584237394672177188, -2. / 3.}}, + {{0., 0., 2. / 5.}}}}; +double const GaussLegendrePyramid<2>::W[5] = { + 81. / 100., 81. / 100., 81. / 100., 81. / 100., 125. / 27.}; const std::array<std::array<double, 3>, GaussLegendrePyramid<3>::NPoints> -GaussLegendrePyramid<3>::X = {{ - {{-0.673931986207731726, -0.673931986207731726, -0.142857142857142857}}, - {{ 0.673931986207731726, -0.673931986207731726, -0.142857142857142857}}, - {{ 0.673931986207731726, 0.673931986207731726, -0.142857142857142857}}, - {{-0.673931986207731726, 0.673931986207731726, -0.142857142857142857}}, - {{-0.610639618865075532, 0.0, -0.321428571428571429}}, - {{ 0.610639618865075532, 0.0, -0.321428571428571429}}, - {{ 0.0, -0.610639618865075532, -0.321428571428571429}}, - {{ 0.0, 0.610639618865075532, -0.321428571428571429}}, - {{ 0.0, 0.0, 0.524394036075370072}}, - {{-0.580939660561084423, -0.580939660561084423, -0.830065359477124183}}, - {{ 0.580939660561084423, -0.580939660561084423, -0.830065359477124183}}, - {{ 0.580939660561084423, 0.580939660561084423, -0.830065359477124183}}, - {{-0.580939660561084423, 0.580939660561084423, -0.830065359477124183}} - }}; + GaussLegendrePyramid<3>::X = { + {{{-0.673931986207731726, -0.673931986207731726, + -0.142857142857142857}}, + {{0.673931986207731726, -0.673931986207731726, -0.142857142857142857}}, + {{0.673931986207731726, 0.673931986207731726, -0.142857142857142857}}, + {{-0.673931986207731726, 0.673931986207731726, -0.142857142857142857}}, + {{-0.610639618865075532, 0.0, -0.321428571428571429}}, + {{0.610639618865075532, 0.0, -0.321428571428571429}}, + {{0.0, -0.610639618865075532, -0.321428571428571429}}, + {{0.0, 0.610639618865075532, -0.321428571428571429}}, + {{0.0, 0.0, 0.524394036075370072}}, + {{-0.580939660561084423, -0.580939660561084423, + -0.830065359477124183}}, + {{0.580939660561084423, -0.580939660561084423, -0.830065359477124183}}, + {{0.580939660561084423, 0.580939660561084423, -0.830065359477124183}}, + {{-0.580939660561084423, 0.580939660561084423, + -0.830065359477124183}}}}; double const GaussLegendrePyramid<3>::W[13] = { - 0.515003019323671498, - 0.515003019323671498, - 0.515003019323671498, - 0.515003019323671498, - 0.257183745242064659, - 0.257183745242064659, - 0.257183745242064659, - 0.257183745242064659, - 2.474004977113405936, - 0.419515737191525950, - 0.419515737191525950, - 0.419515737191525950, - 0.419515737191525950 - }; + 0.515003019323671498, 0.515003019323671498, 0.515003019323671498, + 0.515003019323671498, 0.257183745242064659, 0.257183745242064659, + 0.257183745242064659, 0.257183745242064659, 2.474004977113405936, + 0.419515737191525950, 0.419515737191525950, 0.419515737191525950, + 0.419515737191525950}; } // namespace MathLib diff --git a/MathLib/Integration/GaussLegendreTet.cpp b/MathLib/Integration/GaussLegendreTet.cpp index fe8022430283475b14b9242e814b89a8f4c5ba7e..593b251cb16cbe6ccd800e817994150643729c3b 100644 --- a/MathLib/Integration/GaussLegendreTet.cpp +++ b/MathLib/Integration/GaussLegendreTet.cpp @@ -19,12 +19,13 @@ template <> double const GaussLegendreTet<1>::W[1] = {1. / 6.}; const std::array<std::array<double, 3>, GaussLegendreTet<2>::NPoints> -GaussLegendreTet<2>::X = {{ {{1./4., 1./4., 1./4.}}, - {{1./6., 1./6., 1./6.}}, - {{1./2., 1./6., 1./6.}}, - {{1./6., 1./2., 1./6.}}, - {{1./6., 1./6., 1./2.}} }}; -double const GaussLegendreTet<2>::W[5] = {-2./15., 0.075, 0.075, 0.075, 0.075}; + GaussLegendreTet<2>::X = {{{{1. / 4., 1. / 4., 1. / 4.}}, + {{1. / 6., 1. / 6., 1. / 6.}}, + {{1. / 2., 1. / 6., 1. / 6.}}, + {{1. / 6., 1. / 2., 1. / 6.}}, + {{1. / 6., 1. / 6., 1. / 2.}}}}; +double const GaussLegendreTet<2>::W[5] = {-2. / 15., 0.075, 0.075, 0.075, + 0.075}; static std::array<std::array<double, 3>, GaussLegendreTet<3>::NPoints> initGLTet3X() diff --git a/MathLib/Integration/GaussLegendreTri.cpp b/MathLib/Integration/GaussLegendreTri.cpp index 27e1b038474ad5ca9041762cdcc559391354eca2..efee648484e2e420bee89ec20f131836bc634b7f 100644 --- a/MathLib/Integration/GaussLegendreTri.cpp +++ b/MathLib/Integration/GaussLegendreTri.cpp @@ -16,23 +16,24 @@ namespace MathLib { - template <> const std::array<std::array<double, 2>, GaussLegendreTri<1>::NPoints> GaussLegendreTri<1>::X = {{{{1. / 3., 1. / 3.}}}}; -template <> double const GaussLegendreTri<1>::W[1] = {1.0}; +template <> +double const GaussLegendreTri<1>::W[1] = {1.0}; const std::array<std::array<double, 2>, GaussLegendreTri<2>::NPoints> GaussLegendreTri<2>::X = { {{{1. / 6., 1. / 6.}}, {{2. / 3., 1. / 6.}}, {{1. / 6., 2. / 3.}}}}; -double const GaussLegendreTri<2>::W[3] = {1./3., 1./3., 1./3.}; +double const GaussLegendreTri<2>::W[3] = {1. / 3., 1. / 3., 1. / 3.}; const std::array<std::array<double, 2>, GaussLegendreTri<3>::NPoints> GaussLegendreTri<3>::X = {{{{1. / 3., 1. / 3.}}, {{1. / 5., 3. / 5.}}, {{1. / 5., 1. / 5.}}, {{3. / 5., 1. / 5.}}}}; -double const GaussLegendreTri<3>::W[4] = {-27./48., 25./48., 25./48., 25./48.}; +double const GaussLegendreTri<3>::W[4] = {-27. / 48., 25. / 48., 25. / 48., + 25. / 48.}; const std::array<std::array<double, 2>, GaussLegendreTri<4>::NPoints> GaussLegendreTri<4>::X = {{{{1. / 3., 1. / 3.}}, @@ -42,8 +43,12 @@ const std::array<std::array<double, 2>, GaussLegendreTri<4>::NPoints> {{0.797426985353087, 0.101286507323456}}, {{0.101286507323456, 0.797426985353087}}, {{0.101286507323456, 0.101286507323456}}}}; -double const GaussLegendreTri<4>::W[7] = { - 0.225, 0.132394152788506, 0.132394152788506, 0.132394152788506, - 0.125939180544827, 0.125939180544827, 0.125939180544827}; +double const GaussLegendreTri<4>::W[7] = {0.225, + 0.132394152788506, + 0.132394152788506, + 0.132394152788506, + 0.125939180544827, + 0.125939180544827, + 0.125939180544827}; } // namespace MathLib diff --git a/MathLib/InterpolationAlgorithms/PiecewiseLinearInterpolation.cpp b/MathLib/InterpolationAlgorithms/PiecewiseLinearInterpolation.cpp index e8d4db27c1b57adacf1af7a52e510ad079332bbd..89e948342c3042da545a2d3699e4495a8270b58d 100644 --- a/MathLib/InterpolationAlgorithms/PiecewiseLinearInterpolation.cpp +++ b/MathLib/InterpolationAlgorithms/PiecewiseLinearInterpolation.cpp @@ -11,6 +11,8 @@ * http://www.opengeosys.org/project/license * */ +#include "PiecewiseLinearInterpolation.h" + #include <cmath> #include <limits> #include <utility> @@ -18,13 +20,12 @@ #include "BaseLib/Error.h" #include "BaseLib/quicksort.h" -#include "PiecewiseLinearInterpolation.h" - namespace MathLib { PiecewiseLinearInterpolation::PiecewiseLinearInterpolation( std::vector<double> supporting_points, - std::vector<double> values_at_supp_pnts, + std::vector<double> + values_at_supp_pnts, bool supp_pnts_sorted) : _supp_pnts(std::move(supporting_points)), _values_at_supp_pnts(std::move(values_at_supp_pnts)) @@ -41,8 +42,8 @@ PiecewiseLinearInterpolation::PiecewiseLinearInterpolation( { const std::size_t i = std::distance(_supp_pnts.begin(), it); OGS_FATAL( - "Variable {:d} and variable {:d} are the same. " - "Piecewise linear interpolation is not possible\n", + "Variable {:d} and variable {:d} are the same. Piecewise linear " + "interpolation is not possible\n", i, i + 1); } } diff --git a/MathLib/LinAlg/Eigen/EigenLinearSolver.cpp b/MathLib/LinAlg/Eigen/EigenLinearSolver.cpp index 6595a9ac30cfd3b19956a6c4ae7cb5cac999d355..d602dfbf9c869bda687ad0a298bedcc48ca928f8 100644 --- a/MathLib/LinAlg/Eigen/EigenLinearSolver.cpp +++ b/MathLib/LinAlg/Eigen/EigenLinearSolver.cpp @@ -10,28 +10,28 @@ #include "EigenLinearSolver.h" +#include <Eigen/Sparse> + #include "BaseLib/Logging.h" #ifdef USE_MKL #include <Eigen/PardisoSupport> #endif + #ifdef USE_EIGEN_UNSUPPORTED -#include <Eigen/Sparse> #include <unsupported/Eigen/src/IterativeSolvers/GMRES.h> #include <unsupported/Eigen/src/IterativeSolvers/Scaling.h> #endif #include "BaseLib/ConfigTree.h" -#include "EigenVector.h" #include "EigenMatrix.h" #include "EigenTools.h" - +#include "EigenVector.h" #include "MathLib/LinAlg/LinearSolverOptions.h" namespace MathLib { - // TODO change to LinearSolver class EigenLinearSolverBase { @@ -42,12 +42,12 @@ public: virtual ~EigenLinearSolverBase() = default; //! Solves the linear equation system \f$ A x = b \f$ for \f$ x \f$. - virtual bool solve(Matrix &A, Vector const& b, Vector &x, EigenOption &opt) = 0; + virtual bool solve(Matrix& A, Vector const& b, Vector& x, + EigenOption& opt) = 0; }; namespace details { - /// Template class for Eigen direct linear solvers template <class T_SOLVER> class EigenDirectLinearSolver final : public EigenLinearSolverBase @@ -62,13 +62,15 @@ public: } _solver.compute(A); - if(_solver.info()!=Eigen::Success) { + if (_solver.info() != Eigen::Success) + { ERR("Failed during Eigen linear solver initialization"); return false; } x = _solver.solve(b); - if(_solver.info()!=Eigen::Success) { + if (_solver.info() != Eigen::Success) + { ERR("Failed during Eigen linear solve"); return false; } @@ -92,7 +94,8 @@ public: EigenOption::getPreconName(opt.precon_type)); _solver.setTolerance(opt.error_tolerance); _solver.setMaxIterations(opt.max_iterations); - MathLib::details::EigenIterativeLinearSolver<T_SOLVER>::setRestart(opt.restart); + MathLib::details::EigenIterativeLinearSolver<T_SOLVER>::setRestart( + opt.restart); if (!A.isCompressed()) { @@ -100,7 +103,8 @@ public: } _solver.compute(A); - if(_solver.info()!=Eigen::Success) { + if (_solver.info() != Eigen::Success) + { ERR("Failed during Eigen linear solver initialization"); return false; } @@ -110,7 +114,8 @@ public: opt.max_iterations); INFO("\t residual: {:e}\n", _solver.error()); - if(_solver.info()!=Eigen::Success) { + if (_solver.info() != Eigen::Success) + { ERR("Failed during Eigen linear solve"); return false; } @@ -120,8 +125,7 @@ public: private: T_SOLVER _solver; - void setRestart(int const /*restart*/) { - } + void setRestart(int const /*restart*/) {} }; /// Specialization for (all) three preconditioners separately @@ -155,8 +159,8 @@ void EigenIterativeLinearSolver< template <template <typename, typename> class Solver, typename Precon> std::unique_ptr<EigenLinearSolverBase> createIterativeSolver() { - using Slv = EigenIterativeLinearSolver< - Solver<EigenMatrix::RawMatrixType, Precon>>; + using Slv = + EigenIterativeLinearSolver<Solver<EigenMatrix::RawMatrixType, Precon>>; return std::make_unique<Slv>(); } @@ -164,7 +168,8 @@ template <template <typename, typename> class Solver> std::unique_ptr<EigenLinearSolverBase> createIterativeSolver( EigenOption::PreconType precon_type) { - switch (precon_type) { + switch (precon_type) + { case EigenOption::PreconType::NONE: return createIterativeSolver<Solver, Eigen::IdentityPreconditioner>(); @@ -173,9 +178,10 @@ std::unique_ptr<EigenLinearSolverBase> createIterativeSolver( Solver, Eigen::DiagonalPreconditioner<double>>(); case EigenOption::PreconType::ILUT: // TODO for this preconditioner further options can be passed. - // see https://eigen.tuxfamily.org/dox/classEigen_1_1IncompleteLUT.html - return createIterativeSolver< - Solver, Eigen::IncompleteLUT<double>>(); + // see + // https://eigen.tuxfamily.org/dox/classEigen_1_1IncompleteLUT.html + return createIterativeSolver<Solver, + Eigen::IncompleteLUT<double>>(); default: OGS_FATAL("Invalid Eigen preconditioner type."); } @@ -187,14 +193,18 @@ using EigenCGSolver = Eigen::ConjugateGradient<Mat, Eigen::Lower, Precon>; std::unique_ptr<EigenLinearSolverBase> createIterativeSolver( EigenOption::SolverType solver_type, EigenOption::PreconType precon_type) { - switch (solver_type) { - case EigenOption::SolverType::BiCGSTAB: { + switch (solver_type) + { + case EigenOption::SolverType::BiCGSTAB: + { return createIterativeSolver<Eigen::BiCGSTAB>(precon_type); } - case EigenOption::SolverType::CG: { + case EigenOption::SolverType::CG: + { return createIterativeSolver<EigenCGSolver>(precon_type); } - case EigenOption::SolverType::GMRES: { + case EigenOption::SolverType::GMRES: + { #ifdef USE_EIGEN_UNSUPPORTED return createIterativeSolver<Eigen::GMRES>(precon_type); #else @@ -210,9 +220,8 @@ std::unique_ptr<EigenLinearSolverBase> createIterativeSolver( } // namespace details -EigenLinearSolver::EigenLinearSolver( - const std::string& /*solver_name*/, - const BaseLib::ConfigTree* const option) +EigenLinearSolver::EigenLinearSolver(const std::string& /*solver_name*/, + const BaseLib::ConfigTree* const option) { using Matrix = EigenMatrix::RawMatrixType; @@ -223,8 +232,10 @@ EigenLinearSolver::EigenLinearSolver( // TODO for my taste it is much too unobvious that the default solver type // currently is SparseLU. - switch (_option.solver_type) { - case EigenOption::SolverType::SparseLU: { + switch (_option.solver_type) + { + case EigenOption::SolverType::SparseLU: + { using SolverType = Eigen::SparseLU<Matrix, Eigen::COLAMDOrdering<int>>; _solver = std::make_unique< @@ -237,7 +248,8 @@ EigenLinearSolver::EigenLinearSolver( _solver = details::createIterativeSolver(_option.solver_type, _option.precon_type); return; - case EigenOption::SolverType::PardisoLU: { + case EigenOption::SolverType::PardisoLU: + { #ifdef USE_MKL using SolverType = Eigen::PardisoLU<EigenMatrix::RawMatrixType>; _solver.reset(new details::EigenDirectLinearSolver<SolverType>); @@ -267,27 +279,32 @@ void EigenLinearSolver::setOption(BaseLib::ConfigTree const& option) if (auto solver_type = //! \ogs_file_param{prj__linear_solvers__linear_solver__eigen__solver_type} - ptSolver->getConfigParameterOptional<std::string>("solver_type")) { + ptSolver->getConfigParameterOptional<std::string>("solver_type")) + { _option.solver_type = MathLib::EigenOption::getSolverType(*solver_type); } if (auto precon_type = //! \ogs_file_param{prj__linear_solvers__linear_solver__eigen__precon_type} - ptSolver->getConfigParameterOptional<std::string>("precon_type")) { + ptSolver->getConfigParameterOptional<std::string>("precon_type")) + { _option.precon_type = MathLib::EigenOption::getPreconType(*precon_type); } if (auto error_tolerance = //! \ogs_file_param{prj__linear_solvers__linear_solver__eigen__error_tolerance} - ptSolver->getConfigParameterOptional<double>("error_tolerance")) { + ptSolver->getConfigParameterOptional<double>("error_tolerance")) + { _option.error_tolerance = *error_tolerance; } if (auto max_iteration_step = //! \ogs_file_param{prj__linear_solvers__linear_solver__eigen__max_iteration_step} - ptSolver->getConfigParameterOptional<int>("max_iteration_step")) { + ptSolver->getConfigParameterOptional<int>("max_iteration_step")) + { _option.max_iterations = *max_iteration_step; } if (auto scaling = //! \ogs_file_param{prj__linear_solvers__linear_solver__eigen__scaling} - ptSolver->getConfigParameterOptional<bool>("scaling")) { + ptSolver->getConfigParameterOptional<bool>("scaling")) + { #ifdef USE_EIGEN_UNSUPPORTED _option.scaling = *scaling; #else @@ -298,7 +315,8 @@ void EigenLinearSolver::setOption(BaseLib::ConfigTree const& option) } if (auto restart = //! \ogs_file_param{prj__linear_solvers__linear_solver__eigen__restart} - ptSolver->getConfigParameterOptional<int>("restart")) { + ptSolver->getConfigParameterOptional<int>("restart")) + { #ifdef USE_EIGEN_UNSUPPORTED _option.restart = *restart; #else @@ -307,10 +325,9 @@ void EigenLinearSolver::setOption(BaseLib::ConfigTree const& option) "GMRES/GMRES option restart is not available."); #endif } - } -bool EigenLinearSolver::solve(EigenMatrix &A, EigenVector& b, EigenVector &x) +bool EigenLinearSolver::solve(EigenMatrix& A, EigenVector& b, EigenVector& x) { INFO("------------------------------------------------------------------"); INFO("*** Eigen solver computation"); diff --git a/MathLib/LinAlg/Eigen/EigenOption.cpp b/MathLib/LinAlg/Eigen/EigenOption.cpp index 80cc16cd6993773cbd8217e3bfa047f2475d38f2..dd722f7441b3a37471830b5e1531a92a37a74448 100644 --- a/MathLib/LinAlg/Eigen/EigenOption.cpp +++ b/MathLib/LinAlg/Eigen/EigenOption.cpp @@ -9,11 +9,11 @@ */ #include "EigenOption.h" + #include "BaseLib/Error.h" namespace MathLib { - EigenOption::EigenOption() { solver_type = SolverType::SparseLU; @@ -26,7 +26,8 @@ EigenOption::EigenOption() #endif } -EigenOption::SolverType EigenOption::getSolverType(const std::string &solver_name) +EigenOption::SolverType EigenOption::getSolverType( + const std::string& solver_name) { if (solver_name == "CG") { @@ -52,7 +53,8 @@ EigenOption::SolverType EigenOption::getSolverType(const std::string &solver_nam OGS_FATAL("Unknown Eigen solver type `{:s}'", solver_name); } -EigenOption::PreconType EigenOption::getPreconType(const std::string &precon_name) +EigenOption::PreconType EigenOption::getPreconType( + const std::string& precon_name) { if (precon_name == "NONE") { @@ -72,7 +74,8 @@ EigenOption::PreconType EigenOption::getPreconType(const std::string &precon_nam std::string EigenOption::getSolverName(SolverType const solver_type) { - switch (solver_type) { + switch (solver_type) + { case SolverType::CG: return "CG"; case SolverType::BiCGSTAB: @@ -89,7 +92,8 @@ std::string EigenOption::getSolverName(SolverType const solver_type) std::string EigenOption::getPreconName(PreconType const precon_type) { - switch (precon_type) { + switch (precon_type) + { case PreconType::NONE: return "NONE"; case PreconType::DIAGONAL: diff --git a/MathLib/LinAlg/Eigen/EigenTools.cpp b/MathLib/LinAlg/Eigen/EigenTools.cpp index 97f5b0f9d6d94bf5231e7b0ae03487de814e995b..5985fa16a839f9181e4f4eee83c903b1c7773438 100644 --- a/MathLib/LinAlg/Eigen/EigenTools.cpp +++ b/MathLib/LinAlg/Eigen/EigenTools.cpp @@ -10,27 +10,27 @@ #include "EigenTools.h" - #include "EigenVector.h" namespace MathLib { - -void applyKnownSolution(EigenMatrix &A, EigenVector &b, EigenVector &/*x*/, - const std::vector<EigenMatrix::IndexType> &vec_knownX_id, - const std::vector<double> &vec_knownX_x, double /*penalty_scaling*/) +void applyKnownSolution( + EigenMatrix& A, EigenVector& b, EigenVector& /*x*/, + const std::vector<EigenMatrix::IndexType>& vec_knownX_id, + const std::vector<double>& vec_knownX_x, double /*penalty_scaling*/) { using SpMat = EigenMatrix::RawMatrixType; static_assert(SpMat::IsRowMajor, "matrix is assumed to be row major!"); - auto &A_eigen = A.getRawMatrix(); - auto &b_eigen = b.getRawVector(); + auto& A_eigen = A.getRawMatrix(); + auto& b_eigen = b.getRawVector(); // A_eigen(k, j) = 0. // set row to zero for (auto row_id : vec_knownX_id) { - for (SpMat::InnerIterator it(A_eigen,row_id); it; ++it) { + for (SpMat::InnerIterator it(A_eigen, row_id); it; ++it) + { if (it.col() != decltype(it.col())(row_id)) { it.valueRef() = 0.0; @@ -40,7 +40,7 @@ void applyKnownSolution(EigenMatrix &A, EigenVector &b, EigenVector &/*x*/, SpMat AT = A_eigen.transpose(); - for (std::size_t ix=0; ix<vec_knownX_id.size(); ix++) + for (std::size_t ix = 0; ix < vec_knownX_id.size(); ix++) { SpMat::Index const row_id = vec_knownX_id[ix]; auto const x = vec_knownX_x[ix]; @@ -54,14 +54,17 @@ void applyKnownSolution(EigenMatrix &A, EigenVector &b, EigenVector &/*x*/, continue; } - b_eigen[it.col()] -= it.value()*x; + b_eigen[it.col()] -= it.value() * x; it.valueRef() = 0.0; } auto& c = AT.coeffRef(row_id, row_id); - if (c != 0.0) { + if (c != 0.0) + { b_eigen[row_id] = x * c; - } else { + } + else + { b_eigen[row_id] = x; c = 1.0; } diff --git a/MathLib/LinAlg/EigenLis/EigenLisLinearSolver.cpp b/MathLib/LinAlg/EigenLis/EigenLisLinearSolver.cpp index 05e30cdf91de49df877073a606f7d4f9f6416556..d2495cfd00157117aa1e49f5ce2be267dd058369 100644 --- a/MathLib/LinAlg/EigenLis/EigenLisLinearSolver.cpp +++ b/MathLib/LinAlg/EigenLis/EigenLisLinearSolver.cpp @@ -17,27 +17,26 @@ #include "BaseLib/ConfigTree.h" #include "MathLib/LinAlg/Eigen/EigenMatrix.h" #include "MathLib/LinAlg/Eigen/EigenVector.h" +#include "MathLib/LinAlg/Lis/LisLinearSolver.h" #include "MathLib/LinAlg/Lis/LisMatrix.h" #include "MathLib/LinAlg/Lis/LisVector.h" -#include "MathLib/LinAlg/Lis/LisLinearSolver.h" namespace MathLib { EigenLisLinearSolver::EigenLisLinearSolver( - const std::string /*solver_name*/, - BaseLib::ConfigTree const* const option) + const std::string /*solver_name*/, BaseLib::ConfigTree const* const option) : _lis_option(option) { } -bool EigenLisLinearSolver::solve(EigenMatrix &A_, EigenVector& b_, - EigenVector &x_) +bool EigenLisLinearSolver::solve(EigenMatrix& A_, EigenVector& b_, + EigenVector& x_) { static_assert(EigenMatrix::RawMatrixType::IsRowMajor, "Sparse matrix is required to be in row major storage."); - auto &A = A_.getRawMatrix(); - auto &b = b_.getRawVector(); - auto &x = x_.getRawVector(); + auto& A = A_.getRawMatrix(); + auto& b = b_.getRawVector(); + auto& x = x_.getRawVector(); if (!A.isCompressed()) A.makeCompressed(); @@ -49,14 +48,14 @@ bool EigenLisLinearSolver::solve(EigenMatrix &A_, EigenVector& b_, LisVector lisb(b.rows(), b.data()); LisVector lisx(x.rows(), x.data()); - LisLinearSolver lissol; // TODO not always create Lis solver here + LisLinearSolver lissol; // TODO not always create Lis solver here lissol.setOption(_lis_option); bool const status = lissol.solve(lisA, lisb, lisx); - for (std::size_t i=0; i<lisx.size(); i++) + for (std::size_t i = 0; i < lisx.size(); i++) x[i] = lisx[i]; return status; } -} //MathLib +} // namespace MathLib diff --git a/MathLib/LinAlg/LinAlg.cpp b/MathLib/LinAlg/LinAlg.cpp index 6489bff05d9a731fa65aff5abbb6415a899aab36..486601d02e81c3e070d88393392746f0130e5ea0 100644 --- a/MathLib/LinAlg/LinAlg.cpp +++ b/MathLib/LinAlg/LinAlg.cpp @@ -15,12 +15,13 @@ // Global PETScMatrix/PETScVector ////////////////////////////////////////// #ifdef USE_PETSC -#include "MathLib/LinAlg/PETSc/PETScVector.h" #include "MathLib/LinAlg/PETSc/PETScMatrix.h" +#include "MathLib/LinAlg/PETSc/PETScVector.h" -namespace MathLib { namespace LinAlg +namespace MathLib +{ +namespace LinAlg { - // Vector void setLocalAccessibleVector(PETScVector const& x) @@ -35,7 +36,8 @@ void set(PETScVector& x, double const a) void copy(PETScVector const& x, PETScVector& y) { - if (!y.getRawVector()) y.shallowCopy(x); + if (!y.getRawVector()) + y.shallowCopy(x); VecCopy(x.getRawVector(), y.getRawVector()); } @@ -67,16 +69,16 @@ void axpby(PETScVector& y, double const a, double const b, PETScVector const& x) // Explicit specialization // Computes w = x/y componentwise. -template<> -void componentwiseDivide(PETScVector& w, - PETScVector const& x, PETScVector const& y) +template <> +void componentwiseDivide(PETScVector& w, PETScVector const& x, + PETScVector const& y) { VecPointwiseDivide(w.getRawVector(), x.getRawVector(), y.getRawVector()); } // Explicit specialization // Computes the Manhattan norm of x -template<> +template <> double norm1(PETScVector const& x) { PetscScalar norm = 0.; @@ -86,7 +88,7 @@ double norm1(PETScVector const& x) // Explicit specialization // Computes the Euclidean norm of x -template<> +template <> double norm2(PETScVector const& x) { PetscScalar norm = 0.; @@ -96,7 +98,7 @@ double norm2(PETScVector const& x) // Explicit specialization // Computes the Maximum norm of x -template<> +template <> double normMax(PETScVector const& x) { PetscScalar norm = 0.; @@ -104,7 +106,6 @@ double normMax(PETScVector const& x) return norm; } - // Matrix void copy(PETScMatrix const& A, PETScMatrix& B) @@ -123,8 +124,7 @@ void aypx(PETScMatrix& Y, double const a, PETScMatrix const& X) { // TODO check sizes // TODO sparsity pattern, currently they are assumed to be different (slow) - MatAYPX(Y.getRawMatrix(), a, X.getRawMatrix(), - DIFFERENT_NONZERO_PATTERN); + MatAYPX(Y.getRawMatrix(), a, X.getRawMatrix(), DIFFERENT_NONZERO_PATTERN); } // Y = a*X + Y @@ -132,11 +132,9 @@ void axpy(PETScMatrix& Y, double const a, PETScMatrix const& X) { // TODO check sizes // TODO sparsity pattern, currently they are assumed to be different (slow) - MatAXPY(Y.getRawMatrix(), a, X.getRawMatrix(), - DIFFERENT_NONZERO_PATTERN); + MatAXPY(Y.getRawMatrix(), a, X.getRawMatrix(), DIFFERENT_NONZERO_PATTERN); } - // Matrix and Vector // v3 = A*v1 + v2 @@ -144,18 +142,21 @@ void matMult(PETScMatrix const& A, PETScVector const& x, PETScVector& y) { // TODO check sizes assert(&x != &y); - if (!y.getRawVector()) y.shallowCopy(x); + if (!y.getRawVector()) + y.shallowCopy(x); MatMult(A.getRawMatrix(), x.getRawVector(), y.getRawVector()); } // v3 = A*v1 + v2 void matMultAdd(PETScMatrix const& A, PETScVector const& v1, - PETScVector const& v2, PETScVector& v3) + PETScVector const& v2, PETScVector& v3) { // TODO check sizes assert(&v1 != &v3); - if (!v3.getRawVector()) v3.shallowCopy(v1); - MatMultAdd(A.getRawMatrix(), v1.getRawVector(), v2.getRawVector(), v3.getRawVector()); + if (!v3.getRawVector()) + v3.shallowCopy(v1); + MatMultAdd(A.getRawMatrix(), v1.getRawVector(), v2.getRawVector(), + v3.getRawVector()); } void finalizeAssembly(PETScMatrix& A) @@ -168,24 +169,23 @@ void finalizeAssembly(PETScVector& x) x.finalizeAssembly(); } -}} // namespaces - - +} // namespace LinAlg +} // namespace MathLib -// Sparse global EigenMatrix/EigenVector ////////////////////////////////////////// +// Sparse global EigenMatrix/EigenVector +// ////////////////////////////////////////// #else -#include "MathLib/LinAlg/Eigen/EigenVector.h" #include "MathLib/LinAlg/Eigen/EigenMatrix.h" +#include "MathLib/LinAlg/Eigen/EigenVector.h" -namespace MathLib { namespace LinAlg +namespace MathLib +{ +namespace LinAlg { - // Vector -void setLocalAccessibleVector(EigenVector const& /*x*/) -{ -} +void setLocalAccessibleVector(EigenVector const& /*x*/) {} void set(EigenVector& x, double const a) { @@ -225,17 +225,17 @@ void axpby(EigenVector& y, double const a, double const b, EigenVector const& x) // Explicit specialization // Computes w = x/y componentwise. -template<> -void componentwiseDivide(EigenVector& w, - EigenVector const& x, EigenVector const& y) +template <> +void componentwiseDivide(EigenVector& w, EigenVector const& x, + EigenVector const& y) { w.getRawVector().noalias() = - x.getRawVector().cwiseQuotient(y.getRawVector()); + x.getRawVector().cwiseQuotient(y.getRawVector()); } // Explicit specialization // Computes the Manhattan norm of x -template<> +template <> double norm1(EigenVector const& x) { return x.getRawVector().lpNorm<1>(); @@ -243,7 +243,7 @@ double norm1(EigenVector const& x) // Explicit specialization // Euclidean norm -template<> +template <> double norm2(EigenVector const& x) { return x.getRawVector().norm(); @@ -251,13 +251,12 @@ double norm2(EigenVector const& x) // Explicit specialization // Computes the Maximum norm of x -template<> +template <> double normMax(EigenVector const& x) { return x.getRawVector().lpNorm<Eigen::Infinity>(); } - // Matrix void copy(EigenMatrix const& A, EigenMatrix& B) @@ -276,17 +275,16 @@ void scale(EigenMatrix& A, double const a) void aypx(EigenMatrix& Y, double const a, EigenMatrix const& X) { // TODO: does that break anything? - Y.getRawMatrix() = a*Y.getRawMatrix() + X.getRawMatrix(); + Y.getRawMatrix() = a * Y.getRawMatrix() + X.getRawMatrix(); } // Y = a*X + Y void axpy(EigenMatrix& Y, double const a, EigenMatrix const& X) { // TODO: does that break anything? - Y.getRawMatrix() = a*X.getRawMatrix() + Y.getRawMatrix(); + Y.getRawMatrix() = a * X.getRawMatrix() + Y.getRawMatrix(); } - // Matrix and Vector // v3 = A*v1 + v2 @@ -297,11 +295,13 @@ void matMult(EigenMatrix const& A, EigenVector const& x, EigenVector& y) } // v3 = A*v1 + v2 -void matMultAdd(EigenMatrix const& A, EigenVector const& v1, EigenVector const& v2, EigenVector& v3) +void matMultAdd(EigenMatrix const& A, EigenVector const& v1, + EigenVector const& v2, EigenVector& v3) { assert(&v1 != &v3); // TODO: does that break anything? - v3.getRawVector() = v2.getRawVector() + A.getRawMatrix()*v1.getRawVector(); + v3.getRawVector() = + v2.getRawVector() + A.getRawMatrix() * v1.getRawVector(); } void finalizeAssembly(EigenMatrix& x) @@ -311,8 +311,8 @@ void finalizeAssembly(EigenMatrix& x) void finalizeAssembly(EigenVector& /*x*/) {} -} // namespace LinAlg +} // namespace LinAlg -} // namespace MathLib +} // namespace MathLib #endif diff --git a/MathLib/LinAlg/LinAlgEnums.cpp b/MathLib/LinAlg/LinAlgEnums.cpp index 282433ecb579d76edf2bd36fc5eeb7ff86cfa0cc..4a4331583d7f29e37b6b4398fd6ac1bd0f4910e0 100644 --- a/MathLib/LinAlg/LinAlgEnums.cpp +++ b/MathLib/LinAlg/LinAlgEnums.cpp @@ -14,19 +14,22 @@ namespace MathLib { - std::string convertVecNormTypeToString(VecNormType normType) { switch (normType) { - case VecNormType::NORM1: return "NORM1"; - case VecNormType::NORM2: return "NORM2"; - case VecNormType::INFINITY_N: return "INFINITY_N"; - default: return "INVALID"; + case VecNormType::NORM1: + return "NORM1"; + case VecNormType::NORM2: + return "NORM2"; + case VecNormType::INFINITY_N: + return "INFINITY_N"; + default: + return "INVALID"; } } -VecNormType convertStringToVecNormType(const std::string &str) +VecNormType convertStringToVecNormType(const std::string& str) { if (str == "NORM1") { @@ -43,4 +46,4 @@ VecNormType convertStringToVecNormType(const std::string &str) return VecNormType::INVALID; } -} // end namespace MathLib +} // end namespace MathLib diff --git a/MathLib/LinAlg/LinearSolverOptions.cpp b/MathLib/LinAlg/LinearSolverOptions.cpp index fc1e1b9a6341680b066f90d28a9113a9f112536f..2bb3381ed8743572390e4514f4a27e6c6936bb9b 100644 --- a/MathLib/LinAlg/LinearSolverOptions.cpp +++ b/MathLib/LinAlg/LinearSolverOptions.cpp @@ -5,19 +5,15 @@ //! Configuration tag names of all known linear solvers for their //! configuration in the project file. //! Add your tag name here when you add a new solver. -static -std::set<std::string> -known_linear_solvers { "eigen", "lis", "petsc" }; +static std::set<std::string> known_linear_solvers{"eigen", "lis", "petsc"}; namespace MathLib { - - -void -ignoreOtherLinearSolvers(const BaseLib::ConfigTree &config, - const std::string &solver_name) +void ignoreOtherLinearSolvers(const BaseLib::ConfigTree& config, + const std::string& solver_name) { - for (auto const& s : known_linear_solvers) { + for (auto const& s : known_linear_solvers) + { if (s != solver_name) { config.ignoreConfigParameter(s); diff --git a/MathLib/LinAlg/Lis/LisCheck.h b/MathLib/LinAlg/Lis/LisCheck.h index 48ca01e914f9d568cdd96eeabdfc054a6ceaa593..802a940e0ecd59de223d46b4137336202c56ac69 100644 --- a/MathLib/LinAlg/Lis/LisCheck.h +++ b/MathLib/LinAlg/Lis/LisCheck.h @@ -14,9 +14,11 @@ #pragma once +#include <lis.h> + #include <vector> + #include "BaseLib/Logging.h" -#include "lis.h" namespace MathLib { diff --git a/MathLib/LinAlg/Lis/LisLinearSolver.cpp b/MathLib/LinAlg/Lis/LisLinearSolver.cpp index c8a68d174b7ad192090ed279f1d1a6effa963a49..ff0548db2c6a27c319c2004567f3446342ca4001 100644 --- a/MathLib/LinAlg/Lis/LisLinearSolver.cpp +++ b/MathLib/LinAlg/Lis/LisLinearSolver.cpp @@ -16,25 +16,21 @@ #include <omp.h> #endif -#include "LisLinearSolver.h" - #include "BaseLib/Logging.h" - #include "LisCheck.h" +#include "LisLinearSolver.h" #include "LisMatrix.h" #include "LisVector.h" namespace MathLib { - -LisLinearSolver::LisLinearSolver( - const std::string /*solver_name*/, - const BaseLib::ConfigTree* const option) -: _lis_option(option) +LisLinearSolver::LisLinearSolver(const std::string /*solver_name*/, + const BaseLib::ConfigTree* const option) + : _lis_option(option) { } -bool LisLinearSolver::solve(LisMatrix &A, LisVector &b, LisVector &x) +bool LisLinearSolver::solve(LisMatrix& A, LisVector& b, LisVector& x) { finalizeMatrixAssembly(A); @@ -47,8 +43,8 @@ bool LisLinearSolver::solve(LisMatrix &A, LisVector &b, LisVector &x) if (!checkLisError(ierr)) return false; - lis_solver_set_option( - const_cast<char*>(_lis_option._option_string.c_str()), solver); + lis_solver_set_option(const_cast<char*>(_lis_option._option_string.c_str()), + solver); #ifdef _OPENMP INFO("-> number of threads: {:i}", (int)omp_get_max_threads()); #endif @@ -69,7 +65,8 @@ bool LisLinearSolver::solve(LisMatrix &A, LisVector &b, LisVector &x) // solve INFO("-> solve"); - ierr = lis_solve(A.getRawMatrix(), b.getRawVector(), x.getRawVector(), solver); + ierr = + lis_solve(A.getRawMatrix(), b.getRawVector(), x.getRawVector(), solver); if (!checkLisError(ierr)) return false; @@ -97,8 +94,8 @@ bool LisLinearSolver::solve(LisMatrix &A, LisVector &b, LisVector &x) } { double time, itime, ptime, p_ctime, p_itime; - ierr = lis_solver_get_timeex(solver, &time, &itime, - &ptime, &p_ctime, &p_itime); + ierr = lis_solver_get_timeex(solver, &time, &itime, &ptime, &p_ctime, + &p_itime); if (!checkLisError(ierr)) return false; INFO("-> time total (s): {:g}", time); @@ -117,4 +114,4 @@ bool LisLinearSolver::solve(LisMatrix &A, LisVector &b, LisVector &x) return linear_solver_status == LIS_SUCCESS; } -} //MathLib +} // namespace MathLib diff --git a/MathLib/LinAlg/Lis/LisMatrix.cpp b/MathLib/LinAlg/Lis/LisMatrix.cpp index e8c927aad2cfdc749db5e6302999ee3e719e728b..a1af8ba42158febbe482c02607298d2decd8d877 100644 --- a/MathLib/LinAlg/Lis/LisMatrix.cpp +++ b/MathLib/LinAlg/Lis/LisMatrix.cpp @@ -17,16 +17,17 @@ #include <cmath> #include <cstdlib> - #include "BaseLib/Error.h" -#include "LisVector.h" #include "LisCheck.h" +#include "LisVector.h" namespace MathLib { - LisMatrix::LisMatrix(std::size_t n_rows, MatrixType mat_type) - : _n_rows(n_rows), _mat_type(mat_type), _is_assembled(false), _use_external_arrays(false) + : _n_rows(n_rows), + _mat_type(mat_type), + _is_assembled(false), + _use_external_arrays(false) { int ierr = lis_matrix_create(0, &_AA); checkLisError(ierr); @@ -37,8 +38,8 @@ LisMatrix::LisMatrix(std::size_t n_rows, MatrixType mat_type) checkLisError(ierr); } -LisMatrix::LisMatrix(std::size_t n_rows, int nnz, IndexType *row_ptr, - IndexType *col_idx, double *data) +LisMatrix::LisMatrix(std::size_t n_rows, int nnz, IndexType* row_ptr, + IndexType* col_idx, double* data) : _n_rows(n_rows), _mat_type(MatrixType::CRS), _is_assembled(false), @@ -74,8 +75,8 @@ LisMatrix::~LisMatrix() void LisMatrix::setZero() { - // A matrix has to be destroyed and created again because Lis doesn't provide a - // function to set matrix entries to zero + // A matrix has to be destroyed and created again because Lis doesn't + // provide a function to set matrix entries to zero int ierr = lis_matrix_destroy(_AA); checkLisError(ierr); ierr = lis_matrix_create(0, &_AA); @@ -90,9 +91,10 @@ void LisMatrix::setZero() int LisMatrix::setValue(IndexType rowId, IndexType colId, double v) { - if (v == 0.0) return 0; + if (v == 0.0) + return 0; lis_matrix_set_value(LIS_INS_VALUE, rowId, colId, v, _AA); - if (rowId==colId) + if (rowId == colId) lis_vector_set_value(LIS_INS_VALUE, rowId, v, _diag); _is_assembled = false; return 0; @@ -100,15 +102,16 @@ int LisMatrix::setValue(IndexType rowId, IndexType colId, double v) int LisMatrix::add(IndexType rowId, IndexType colId, double v) { - if (v == 0.0) return 0; + if (v == 0.0) + return 0; lis_matrix_set_value(LIS_ADD_VALUE, rowId, colId, v, _AA); - if (rowId==colId) + if (rowId == colId) lis_vector_set_value(LIS_ADD_VALUE, rowId, v, _diag); _is_assembled = false; return 0; } -void LisMatrix::write(const std::string &filename) const +void LisMatrix::write(const std::string& filename) const { if (!_is_assembled) { @@ -117,12 +120,14 @@ void LisMatrix::write(const std::string &filename) const lis_output_matrix(_AA, LIS_FMT_MM, const_cast<char*>(filename.c_str())); } -bool finalizeMatrixAssembly(LisMatrix &mat) +bool finalizeMatrixAssembly(LisMatrix& mat) { - LIS_MATRIX &A = mat.getRawMatrix(); + LIS_MATRIX& A = mat.getRawMatrix(); - if (!mat.isAssembled()) { - int ierr = lis_matrix_set_type(A, static_cast<int>(mat.getMatrixType())); + if (!mat.isAssembled()) + { + int ierr = + lis_matrix_set_type(A, static_cast<int>(mat.getMatrixType())); checkLisError(ierr); ierr = lis_matrix_assemble(A); checkLisError(ierr); @@ -131,5 +136,4 @@ bool finalizeMatrixAssembly(LisMatrix &mat) return true; } - -} //MathLib +} // namespace MathLib diff --git a/MathLib/LinAlg/Lis/LisVector.cpp b/MathLib/LinAlg/Lis/LisVector.cpp index 37f758b388f1d4a3b452b6c3fb9524bcebdc5c2a..f5b68251bc9b47dc355896a9a4f9e5375bb20c7b 100644 --- a/MathLib/LinAlg/Lis/LisVector.cpp +++ b/MathLib/LinAlg/Lis/LisVector.cpp @@ -12,9 +12,10 @@ * */ +#include "LisVector.h" + #include <cassert> -#include "LisVector.h" #include "LisCheck.h" namespace MathLib @@ -59,4 +60,4 @@ void LisVector::write(const std::string& filename) const lis_output_vector(_vec, LIS_FMT_PLAIN, const_cast<char*>(filename)); } -} // MathLib +} // namespace MathLib diff --git a/MathLib/LinAlg/MatrixVectorTraits.cpp b/MathLib/LinAlg/MatrixVectorTraits.cpp index ff52b18cccd83d2a3b2fc248f082fdb1c6aee6e2..4d6a334b6c9a2e729848fdaa33793ee2c1f83e29 100644 --- a/MathLib/LinAlg/MatrixVectorTraits.cpp +++ b/MathLib/LinAlg/MatrixVectorTraits.cpp @@ -9,30 +9,26 @@ */ #include "MatrixVectorTraits.h" + #include "MatrixSpecifications.h" #ifdef USE_PETSC namespace MathLib { - -std::unique_ptr<PETScMatrix> -MatrixVectorTraits<PETScMatrix>:: -newInstance() +std::unique_ptr<PETScMatrix> MatrixVectorTraits<PETScMatrix>::newInstance() { return std::make_unique<PETScMatrix>(); } -std::unique_ptr<PETScMatrix> -MatrixVectorTraits<PETScMatrix>:: -newInstance(PETScMatrix const& A) +std::unique_ptr<PETScMatrix> MatrixVectorTraits<PETScMatrix>::newInstance( + PETScMatrix const& A) { return std::make_unique<PETScMatrix>(A); } -std::unique_ptr<PETScMatrix> -MatrixVectorTraits<PETScMatrix>:: -newInstance(MatrixSpecifications const& spec) +std::unique_ptr<PETScMatrix> MatrixVectorTraits<PETScMatrix>::newInstance( + MatrixSpecifications const& spec) { auto const nrows = spec.nrows; auto const ncols = spec.ncols; @@ -54,30 +50,29 @@ newInstance(MatrixSpecifications const& spec) return std::make_unique<PETScMatrix>(nrows, ncols); } -std::unique_ptr<PETScVector> -MatrixVectorTraits<PETScVector>:: -newInstance() +std::unique_ptr<PETScVector> MatrixVectorTraits<PETScVector>::newInstance() { return std::make_unique<PETScVector>(); } -std::unique_ptr<PETScVector> -MatrixVectorTraits<PETScVector>:: -newInstance(PETScVector const& x) +std::unique_ptr<PETScVector> MatrixVectorTraits<PETScVector>::newInstance( + PETScVector const& x) { return std::make_unique<PETScVector>(x); } -std::unique_ptr<PETScVector> -MatrixVectorTraits<PETScVector>:: -newInstance(MatrixSpecifications const& spec) +std::unique_ptr<PETScVector> MatrixVectorTraits<PETScVector>::newInstance( + MatrixSpecifications const& spec) { auto const is_global_size = false; - if (spec.ghost_indices != nullptr) { + if (spec.ghost_indices != nullptr) + { return std::make_unique<PETScVector>(spec.nrows, *spec.ghost_indices, is_global_size); - } else { + } + else + { return std::make_unique<PETScVector>(spec.nrows, is_global_size); } } @@ -89,31 +84,25 @@ std::unique_ptr<PETScVector> MatrixVectorTraits<PETScVector>::newInstance( return std::make_unique<PETScVector>(length, is_global_size); } -} // namespace MathLib - +} // namespace MathLib #else namespace MathLib { - -std::unique_ptr<EigenMatrix> -MatrixVectorTraits<EigenMatrix>:: -newInstance() +std::unique_ptr<EigenMatrix> MatrixVectorTraits<EigenMatrix>::newInstance() { return std::make_unique<EigenMatrix>(0, 0); // TODO default constructor } -std::unique_ptr<EigenMatrix> -MatrixVectorTraits<EigenMatrix>:: -newInstance(EigenMatrix const& A) +std::unique_ptr<EigenMatrix> MatrixVectorTraits<EigenMatrix>::newInstance( + EigenMatrix const& A) { return std::make_unique<EigenMatrix>(A); } -std::unique_ptr<EigenMatrix> -MatrixVectorTraits<EigenMatrix>:: -newInstance(MatrixSpecifications const& spec) +std::unique_ptr<EigenMatrix> MatrixVectorTraits<EigenMatrix>::newInstance( + MatrixSpecifications const& spec) { auto A = std::make_unique<EigenMatrix>(spec.nrows); @@ -125,23 +114,19 @@ newInstance(MatrixSpecifications const& spec) return A; } -std::unique_ptr<EigenVector> -MatrixVectorTraits<EigenVector>:: -newInstance() +std::unique_ptr<EigenVector> MatrixVectorTraits<EigenVector>::newInstance() { return std::make_unique<EigenVector>(); } -std::unique_ptr<EigenVector> -MatrixVectorTraits<EigenVector>:: -newInstance(EigenVector const& x) +std::unique_ptr<EigenVector> MatrixVectorTraits<EigenVector>::newInstance( + EigenVector const& x) { return std::make_unique<EigenVector>(x); } -std::unique_ptr<EigenVector> -MatrixVectorTraits<EigenVector>:: -newInstance(MatrixSpecifications const& spec) +std::unique_ptr<EigenVector> MatrixVectorTraits<EigenVector>::newInstance( + MatrixSpecifications const& spec) { return std::make_unique<EigenVector>(spec.nrows); } @@ -151,6 +136,6 @@ std::unique_ptr<EigenVector> MatrixVectorTraits<EigenVector>::newInstance( { return std::make_unique<EigenVector>(length); } -} // namespace MathLib +} // namespace MathLib #endif diff --git a/MathLib/LinAlg/PETSc/PETScMatrix.cpp b/MathLib/LinAlg/PETSc/PETScMatrix.cpp index 2445daa1d456ac7b2cb91332b73e6dea7ba0dab1..80fe3b42588a3bb80c49b1a88404c4f2c0ea8c16 100644 --- a/MathLib/LinAlg/PETSc/PETScMatrix.cpp +++ b/MathLib/LinAlg/PETSc/PETScMatrix.cpp @@ -155,4 +155,4 @@ bool finalizeMatrixAssembly(PETScMatrix& mat, const MatAssemblyType asm_type) return true; } -} // end of namespace +} // namespace MathLib diff --git a/MathLib/LinAlg/PETSc/PETScVector.cpp b/MathLib/LinAlg/PETSc/PETScVector.cpp index 34f908d3150afb96389b6154b5241f95ddbfe69b..4de8178a9dd9d0c8c40d46fe4ca51336e9425462 100644 --- a/MathLib/LinAlg/PETSc/PETScVector.cpp +++ b/MathLib/LinAlg/PETSc/PETScVector.cpp @@ -323,4 +323,4 @@ void finalizeVectorAssembly(PETScVector& vec) vec.finalizeAssembly(); } -} // end of namespace +} // namespace MathLib diff --git a/MathLib/LinAlg/UnifiedMatrixSetters.cpp b/MathLib/LinAlg/UnifiedMatrixSetters.cpp index 18985bf423958adccafdf34d4382d6d0591aea8b..2678cbcb5d319bc4ff3e84e058d927eaab44d367 100644 --- a/MathLib/LinAlg/UnifiedMatrixSetters.cpp +++ b/MathLib/LinAlg/UnifiedMatrixSetters.cpp @@ -8,21 +8,22 @@ * */ -#include <cassert> #include "UnifiedMatrixSetters.h" +#include <cassert> + #ifdef USE_PETSC // Global PETScMatrix/PETScVector ////////////////////////////////////////// #include <numeric> -#include "MathLib/LinAlg/PETSc/PETScVector.h" + #include "MathLib/LinAlg/PETSc/PETScMatrix.h" +#include "MathLib/LinAlg/PETSc/PETScVector.h" namespace MathLib { -void setVector(PETScVector& v, - std::initializer_list<double> values) +void setVector(PETScVector& v, std::initializer_list<double> values) { std::vector<double> const vals(values); std::vector<PETScVector::IndexType> idcs(vals.size()); @@ -31,14 +32,14 @@ void setVector(PETScVector& v, v.set(idcs, vals); } -void setVector(PETScVector& v, MatrixVectorTraits<PETScVector>::Index const index, +void setVector(PETScVector& v, + MatrixVectorTraits<PETScVector>::Index const index, double const value) { - v.set(index, value); // TODO handle negative indices + v.set(index, value); // TODO handle negative indices } -void setMatrix(PETScMatrix& m, - std::initializer_list<double> values) +void setMatrix(PETScMatrix& m, std::initializer_list<double> values) { m.setZero(); addToMatrix(m, values); @@ -61,26 +62,29 @@ void setMatrix(PETScMatrix& m, Eigen::MatrixXd const& tmp) std::iota(col_idcs.begin(), col_idcs.end(), 0); // PETSc wants row-major - Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> tmp_ = tmp; + Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> + tmp_ = tmp; m.add(row_idcs, col_idcs, tmp_); } -void addToMatrix(PETScMatrix& m, - std::initializer_list<double> values) +void addToMatrix(PETScMatrix& m, std::initializer_list<double> values) { using IndexType = PETScMatrix::IndexType; auto const rows = m.getNumberOfRows(); auto const cols = m.getNumberOfColumns(); - assert((IndexType) values.size() == rows*cols); + assert((IndexType)values.size() == rows * cols); - Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> tmp(rows, cols); + Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> tmp( + rows, cols); auto it = values.begin(); - for (IndexType r=0; r<rows; ++r) { - for (IndexType c=0; c<cols; ++c) { + for (IndexType r = 0; r < rows; ++r) + { + for (IndexType c = 0; c < cols; ++c) + { tmp(r, c) = *(it++); } } @@ -94,21 +98,19 @@ void addToMatrix(PETScMatrix& m, m.add(row_idcs, col_idcs, tmp); } -} // namespace MathLib - +} // namespace MathLib #else -// Sparse global EigenMatrix/EigenVector ////////////////////////////////////////// +// Sparse global EigenMatrix/EigenVector +// ////////////////////////////////////////// -#include "MathLib/LinAlg/Eigen/EigenVector.h" #include "MathLib/LinAlg/Eigen/EigenMatrix.h" +#include "MathLib/LinAlg/Eigen/EigenVector.h" namespace MathLib { - -void setVector(EigenVector& v_, - std::initializer_list<double> values) +void setVector(EigenVector& v_, std::initializer_list<double> values) { auto& v(v_.getRawVector()); assert((std::size_t)v.size() == values.size()); @@ -119,25 +121,26 @@ void setVector(EigenVector& v_, } } -void setVector(EigenVector& v, MatrixVectorTraits<EigenVector>::Index const index, +void setVector(EigenVector& v, + MatrixVectorTraits<EigenVector>::Index const index, double const value) { v.getRawVector()[index] = value; } - -void setMatrix(EigenMatrix& m, - std::initializer_list<double> values) +void setMatrix(EigenMatrix& m, std::initializer_list<double> values) { auto const rows = m.getNumberOfRows(); auto const cols = m.getNumberOfColumns(); - assert(static_cast<EigenMatrix::IndexType>(values.size()) == rows*cols); + assert(static_cast<EigenMatrix::IndexType>(values.size()) == rows * cols); Eigen::MatrixXd tmp(rows, cols); auto it = values.begin(); - for (GlobalIndexType r=0; r<rows; ++r) { - for (GlobalIndexType c=0; c<cols; ++c) { + for (GlobalIndexType r = 0; r < rows; ++r) + { + for (GlobalIndexType c = 0; c < cols; ++c) + { tmp(r, c) = *(it++); } } @@ -150,18 +153,20 @@ void setMatrix(EigenMatrix& m, Eigen::MatrixXd const& tmp) m.getRawMatrix() = tmp.sparseView(); } -void addToMatrix(EigenMatrix& m, - std::initializer_list<double> values) +void addToMatrix(EigenMatrix& m, std::initializer_list<double> values) { auto const rows = m.getNumberOfRows(); auto const cols = m.getNumberOfColumns(); - assert(static_cast<EigenMatrix::IndexType>(values.size()) == rows*cols); - Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> tmp(rows, cols); + assert(static_cast<EigenMatrix::IndexType>(values.size()) == rows * cols); + Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> tmp( + rows, cols); auto it = values.begin(); - for (GlobalIndexType r=0; r<rows; ++r) { - for (GlobalIndexType c=0; c<cols; ++c) { + for (GlobalIndexType r = 0; r < rows; ++r) + { + for (GlobalIndexType c = 0; c < cols; ++c) + { tmp(r, c) = *(it++); } } @@ -169,6 +174,6 @@ void addToMatrix(EigenMatrix& m, m.getRawMatrix() += tmp.sparseView(); } -} // namespace MathLib +} // namespace MathLib #endif diff --git a/MathLib/MathTools.cpp b/MathLib/MathTools.cpp index cb5b3d6f3c16e2018d3ac5491d87b57fef0cab4d..503445b3426579157a8e75ad6001e86781549451 100644 --- a/MathLib/MathTools.cpp +++ b/MathLib/MathTools.cpp @@ -16,7 +16,6 @@ namespace MathLib { - double calcProjPntToLineAndDists(Point3d const& pp, Point3d const& pa, Point3d const& pb, double& lambda, double& d0) { diff --git a/MathLib/ODE/CVodeSolver.cpp b/MathLib/ODE/CVodeSolver.cpp index c9a885f6ce50b9ba1d9b3f6326d2182a154c14a1..266b2e5d194eb5325ae136a74d1fcdcd9ef659ef 100644 --- a/MathLib/ODE/CVodeSolver.cpp +++ b/MathLib/ODE/CVodeSolver.cpp @@ -9,17 +9,17 @@ */ #include "CVodeSolver.h" -#include <cassert> -#include "BaseLib/Logging.h" - #include <cvode/cvode.h> /* prototypes for CVODE fcts., consts. */ -#include <nvector/nvector_serial.h> /* serial N_Vector types, fcts., macros */ #include <cvode/cvode_dense.h> /* prototype for CVDense */ +#include <nvector/nvector_serial.h> /* serial N_Vector types, fcts., macros */ #include <sundials/sundials_dense.h> /* definitions DlsMat DENSE_ELEM */ #include <sundials/sundials_types.h> /* definition of type realtype */ +#include <cassert> + #include "BaseLib/ConfigTree.h" #include "BaseLib/Error.h" +#include "BaseLib/Logging.h" //! \addtogroup ExternalODESolverInterface //! @{ @@ -132,8 +132,9 @@ CVodeSolverImpl::CVodeSolverImpl(const BaseLib::ConfigTree& config, const unsigned num_equations) { if (auto const param = - //! \ogs_file_param{ode_solver__CVODE__linear_multistep_method} - config.getConfigParameterOptional<std::string>("linear_multistep_method")) + //! \ogs_file_param{ode_solver__CVODE__linear_multistep_method} + config.getConfigParameterOptional<std::string>( + "linear_multistep_method")) { DBUG("setting linear multistep method (config: {:s})", param->c_str()); @@ -152,8 +153,9 @@ CVodeSolverImpl::CVodeSolverImpl(const BaseLib::ConfigTree& config, } if (auto const param = - //! \ogs_file_param{ode_solver__CVODE__nonlinear_solver_iteration} - config.getConfigParameterOptional<std::string>("nonlinear_solver_iteration")) + //! \ogs_file_param{ode_solver__CVODE__nonlinear_solver_iteration} + config.getConfigParameterOptional<std::string>( + "nonlinear_solver_iteration")) { DBUG("setting nonlinear solver iteration (config: {:s})", param->c_str()); @@ -186,8 +188,7 @@ CVodeSolverImpl::CVodeSolverImpl(const BaseLib::ConfigTree& config, } auto f_wrapped = [](const realtype t, const N_Vector y, N_Vector ydot, - void* function_handles) -> int - { + void* function_handles) -> int { bool successful = static_cast<detail::FunctionHandles*>(function_handles) ->call(t, NV_DATA_S(y), NV_DATA_S(ydot)); @@ -257,8 +258,7 @@ void CVodeSolverImpl::preSolve() const N_Vector ydot, const DlsMat jac, void* function_handles, N_Vector /*tmp1*/, N_Vector /*tmp2*/, N_Vector /*tmp3*/ - ) -> int - { + ) -> int { (void)N; // prevent warnings during non-debug build auto* fh = static_cast<detail::FunctionHandles*>(function_handles); assert(N == fh->getNumberOfEquations()); diff --git a/MathLib/Point3d.cpp b/MathLib/Point3d.cpp index 13873692de5549bc3541143519de685ae19533d6..9e131e186a6cb0da9020cc3c0795601f78f6f36e 100644 --- a/MathLib/Point3d.cpp +++ b/MathLib/Point3d.cpp @@ -12,5 +12,5 @@ namespace MathLib { -extern const Point3d ORIGIN{ {{0.0, 0.0, 0.0}} }; +extern const Point3d ORIGIN{{{0.0, 0.0, 0.0}}}; } diff --git a/MeshGeoToolsLib/AppendLinesAlongPolyline.cpp b/MeshGeoToolsLib/AppendLinesAlongPolyline.cpp index 23cad184be33104d56fcd79381246ccdf36fa329..6065ad11ef871b6d838ff0513680c9dd0553ecb4 100644 --- a/MeshGeoToolsLib/AppendLinesAlongPolyline.cpp +++ b/MeshGeoToolsLib/AppendLinesAlongPolyline.cpp @@ -10,18 +10,15 @@ #include "AppendLinesAlongPolyline.h" #include "BaseLib/Logging.h" - #include "GeoLib/Polyline.h" #include "GeoLib/PolylineVec.h" - -#include "MeshLib/Mesh.h" -#include "MeshLib/Node.h" -#include "MeshLib/Elements/Line.h" +#include "MeshGeoToolsLib/MeshNodesAlongPolyline.h" #include "MeshLib/Elements/Element.h" -#include "MeshLib/MeshEnums.h" +#include "MeshLib/Elements/Line.h" +#include "MeshLib/Mesh.h" #include "MeshLib/MeshEditing/DuplicateMeshComponents.h" - -#include "MeshGeoToolsLib/MeshNodesAlongPolyline.h" +#include "MeshLib/MeshEnums.h" +#include "MeshLib/Node.h" namespace MeshGeoToolsLib { @@ -29,8 +26,10 @@ std::unique_ptr<MeshLib::Mesh> appendLinesAlongPolylines( const MeshLib::Mesh& mesh, const GeoLib::PolylineVec& ply_vec) { // copy existing nodes and elements - std::vector<MeshLib::Node*> vec_new_nodes = MeshLib::copyNodeVector(mesh.getNodes()); - std::vector<MeshLib::Element*> vec_new_eles = MeshLib::copyElementVector(mesh.getElements(), vec_new_nodes); + std::vector<MeshLib::Node*> vec_new_nodes = + MeshLib::copyNodeVector(mesh.getNodes()); + std::vector<MeshLib::Element*> vec_new_eles = + MeshLib::copyElementVector(mesh.getElements(), vec_new_nodes); auto const material_ids = materialIDs(mesh); int const max_matID = @@ -39,7 +38,7 @@ std::unique_ptr<MeshLib::Mesh> appendLinesAlongPolylines( : 0; std::vector<int> new_mat_ids; - const std::size_t n_ply (ply_vec.size()); + const std::size_t n_ply(ply_vec.size()); // for each polyline for (std::size_t k(0); k < n_ply; k++) { @@ -49,8 +48,9 @@ std::unique_ptr<MeshLib::Mesh> appendLinesAlongPolylines( MeshGeoToolsLib::MeshNodesAlongPolyline mshNodesAlongPoly( mesh, *ply, mesh.getMinEdgeLength() * 0.5, MeshGeoToolsLib::SearchAllNodes::Yes); - auto &vec_nodes_on_ply = mshNodesAlongPoly.getNodeIDs(); - if (vec_nodes_on_ply.empty()) { + auto& vec_nodes_on_ply = mshNodesAlongPoly.getNodeIDs(); + if (vec_nodes_on_ply.empty()) + { std::string ply_name; ply_vec.getNameOfElementByID(k, ply_name); INFO("No nodes found on polyline {:s}", ply_name); @@ -58,13 +58,14 @@ std::unique_ptr<MeshLib::Mesh> appendLinesAlongPolylines( } // add line elements - for (std::size_t i=0; i<vec_nodes_on_ply.size()-1; i++) { + for (std::size_t i = 0; i < vec_nodes_on_ply.size() - 1; i++) + { std::array<MeshLib::Node*, 2> element_nodes; element_nodes[0] = vec_new_nodes[vec_nodes_on_ply[i]]; - element_nodes[1] = vec_new_nodes[vec_nodes_on_ply[i+1]]; + element_nodes[1] = vec_new_nodes[vec_nodes_on_ply[i + 1]]; vec_new_eles.push_back( new MeshLib::Line(element_nodes, vec_new_eles.size())); - new_mat_ids.push_back(max_matID+k+1); + new_mat_ids.push_back(max_matID + k + 1); } } diff --git a/MeshGeoToolsLib/BoundaryElementsAtPoint.cpp b/MeshGeoToolsLib/BoundaryElementsAtPoint.cpp index 75bab1c659ea5018601cc3d747790cfe555b3aff..9af0f991e76f96f24f9b6719070d5b99aa66fbd5 100644 --- a/MeshGeoToolsLib/BoundaryElementsAtPoint.cpp +++ b/MeshGeoToolsLib/BoundaryElementsAtPoint.cpp @@ -11,13 +11,12 @@ #include "GeoLib/Point.h" #include "MathLib/Point3d.h" +#include "MeshGeoToolsLib/MeshNodeSearcher.h" #include "MeshLib/Elements/Point.h" #include "MeshLib/Mesh.h" #include "MeshLib/MeshSearch/ElementSearch.h" #include "MeshLib/Node.h" -#include "MeshGeoToolsLib/MeshNodeSearcher.h" - namespace MeshGeoToolsLib { BoundaryElementsAtPoint::BoundaryElementsAtPoint( @@ -77,8 +76,7 @@ BoundaryElementsAtPoint::BoundaryElementsAtPoint( std::array<MeshLib::Node*, 1> const nodes = { {const_cast<MeshLib::Node*>(_mesh.getNode(nearest_node_id))}}; - _boundary_elements.push_back( - new MeshLib::Point{nodes, nearest_node_id}); + _boundary_elements.push_back(new MeshLib::Point{nodes, nearest_node_id}); } BoundaryElementsAtPoint::~BoundaryElementsAtPoint() diff --git a/MeshGeoToolsLib/BoundaryElementsOnSurface.cpp b/MeshGeoToolsLib/BoundaryElementsOnSurface.cpp index 5c9ca623821122bb5c94cd529950d978f674c9c1..49fa443a52390a3defeb4f647d1d488b695e1e5a 100644 --- a/MeshGeoToolsLib/BoundaryElementsOnSurface.cpp +++ b/MeshGeoToolsLib/BoundaryElementsOnSurface.cpp @@ -10,13 +10,11 @@ #include "BoundaryElementsOnSurface.h" #include "GeoLib/Surface.h" - -#include "MeshLib/Mesh.h" +#include "MeshGeoToolsLib/MeshNodeSearcher.h" #include "MeshLib/Elements/Element.h" +#include "MeshLib/Mesh.h" #include "MeshLib/MeshSearch/ElementSearch.h" -#include "MeshGeoToolsLib/MeshNodeSearcher.h" - namespace MeshGeoToolsLib { BoundaryElementsOnSurface::BoundaryElementsOnSurface( @@ -28,10 +26,11 @@ BoundaryElementsOnSurface::BoundaryElementsOnSurface( auto node_ids_on_sfc = mshNodeSearcher.getMeshNodeIDs(sfc); MeshLib::ElementSearch es(_mesh); es.searchByNodeIDs(node_ids_on_sfc); - auto &ele_ids_near_sfc = es.getSearchedElementIDs(); + auto& ele_ids_near_sfc = es.getSearchedElementIDs(); // get a list of faces made of the nodes - for (auto ele_id : ele_ids_near_sfc) { + for (auto ele_id : ele_ids_near_sfc) + { auto* e = _mesh.getElement(ele_id); // skip internal elements if (!e->isBoundaryElement()) @@ -39,11 +38,13 @@ BoundaryElementsOnSurface::BoundaryElementsOnSurface( continue; } // find faces on surface - for (unsigned i=0; i<e->getNumberOfFaces(); i++) { + for (unsigned i = 0; i < e->getNumberOfFaces(); i++) + { auto* face = e->getFace(i); // check std::size_t cnt_match = 0; - for (std::size_t j=0; j<face->getNumberOfBaseNodes(); j++) { + for (std::size_t j = 0; j < face->getNumberOfBaseNodes(); j++) + { if (std::find(node_ids_on_sfc.begin(), node_ids_on_sfc.end(), face->getNodeIndex(j)) != node_ids_on_sfc.end()) { @@ -55,9 +56,10 @@ BoundaryElementsOnSurface::BoundaryElementsOnSurface( } } // update the list - if (cnt_match==face->getNumberOfBaseNodes()) + if (cnt_match == face->getNumberOfBaseNodes()) { - _boundary_elements.push_back(const_cast<MeshLib::Element*>(face)); + _boundary_elements.push_back( + const_cast<MeshLib::Element*>(face)); } else { @@ -75,5 +77,4 @@ BoundaryElementsOnSurface::~BoundaryElementsOnSurface() } } -} // end namespace MeshGeoToolsLib - +} // end namespace MeshGeoToolsLib diff --git a/MeshGeoToolsLib/BoundaryElementsSearcher.cpp b/MeshGeoToolsLib/BoundaryElementsSearcher.cpp index 3f966b57e785e936d02a8178e0b75ec50f6a12bd..d54c54057ac922d15721ac3485c443995f04d051 100644 --- a/MeshGeoToolsLib/BoundaryElementsSearcher.cpp +++ b/MeshGeoToolsLib/BoundaryElementsSearcher.cpp @@ -12,24 +12,22 @@ #include "GeoLib/GeoObject.h" #include "GeoLib/Polyline.h" #include "GeoLib/Surface.h" - -#include "MeshLib/Mesh.h" -#include "MeshLib/Node.h" -#include "MeshLib/Elements/Element.h" -#include "MeshLib/Elements/Point.h" - -#include "MeshGeoToolsLib/MeshNodeSearcher.h" -#include "MeshGeoToolsLib/BoundaryElementsAtPoint.h" #include "MeshGeoToolsLib/BoundaryElementsAlongPolyline.h" +#include "MeshGeoToolsLib/BoundaryElementsAtPoint.h" #include "MeshGeoToolsLib/BoundaryElementsOnSurface.h" - +#include "MeshGeoToolsLib/MeshNodeSearcher.h" +#include "MeshLib/Elements/Element.h" +#include "MeshLib/Elements/Point.h" +#include "MeshLib/Mesh.h" +#include "MeshLib/Node.h" namespace MeshGeoToolsLib { BoundaryElementsSearcher::BoundaryElementsSearcher( MeshLib::Mesh const& mesh, MeshNodeSearcher const& mshNodeSearcher) : _mesh(mesh), _mshNodeSearcher(mshNodeSearcher) -{} +{ +} BoundaryElementsSearcher::~BoundaryElementsSearcher() { @@ -120,5 +118,4 @@ BoundaryElementsSearcher::getBoundaryElements(GeoLib::GeoObject const& geoObj, } } -} // end namespace MeshGeoToolsLib - +} // end namespace MeshGeoToolsLib diff --git a/MeshGeoToolsLib/ConstructMeshesFromGeometries.cpp b/MeshGeoToolsLib/ConstructMeshesFromGeometries.cpp index 3a9b74e47fe349fca96d6efeffb3f1ef9ea4ffcb..7989e3f3380fdcca49fe7ac28489e3bafe1f5aa8 100644 --- a/MeshGeoToolsLib/ConstructMeshesFromGeometries.cpp +++ b/MeshGeoToolsLib/ConstructMeshesFromGeometries.cpp @@ -10,12 +10,10 @@ #include "ConstructMeshesFromGeometries.h" #include "BaseLib/Logging.h" - +#include "BoundaryElementsSearcher.h" #include "MeshLib/Elements/Element.h" #include "MeshLib/MeshEditing/DuplicateMeshComponents.h" #include "MeshLib/Node.h" - -#include "BoundaryElementsSearcher.h" #include "MeshNodeSearcher.h" namespace MeshGeoToolsLib diff --git a/MeshGeoToolsLib/CreateSearchLength.cpp b/MeshGeoToolsLib/CreateSearchLength.cpp index 6115a1bf82c9bf76cb0817b4a7de3fb93efbb47b..ebeffa8286ad2bf6977049aaf83e85e7d2cbdd99 100644 --- a/MeshGeoToolsLib/CreateSearchLength.cpp +++ b/MeshGeoToolsLib/CreateSearchLength.cpp @@ -11,7 +11,6 @@ #include "BaseLib/ConfigTree.h" #include "BaseLib/Error.h" - #include "MeshGeoToolsLib/HeuristicSearchLength.h" #include "MeshGeoToolsLib/SearchLength.h" diff --git a/MeshGeoToolsLib/GeoMapper.cpp b/MeshGeoToolsLib/GeoMapper.cpp index 9ec3af6fc341f9f629c6260fde90f159ab100450..1cef01614cfa2b9f175b7a96e1bda88f4e65ce92 100644 --- a/MeshGeoToolsLib/GeoMapper.cpp +++ b/MeshGeoToolsLib/GeoMapper.cpp @@ -15,31 +15,32 @@ #include "GeoMapper.h" #include <algorithm> -#include <sstream> #include <numeric> - -#include "BaseLib/Logging.h" +#include <sstream> #include "BaseLib/Algorithm.h" - +#include "BaseLib/Logging.h" #include "GeoLib/AABB.h" #include "GeoLib/AnalyticalGeometry.h" #include "GeoLib/GEOObjects.h" #include "GeoLib/Raster.h" #include "GeoLib/StationBorehole.h" - -#include "MeshLib/Mesh.h" #include "MeshLib/Elements/Element.h" #include "MeshLib/Elements/FaceRule.h" -#include "MeshLib/Node.h" -#include "MeshLib/MeshSurfaceExtraction.h" +#include "MeshLib/Mesh.h" #include "MeshLib/MeshSearch/MeshElementGrid.h" +#include "MeshLib/MeshSurfaceExtraction.h" +#include "MeshLib/Node.h" -namespace MeshGeoToolsLib { - -GeoMapper::GeoMapper(GeoLib::GEOObjects &geo_objects, const std::string &geo_name) - : _geo_objects(geo_objects), _geo_name(const_cast<std::string&>(geo_name)), - _surface_mesh(nullptr), _grid(nullptr), _raster(nullptr) +namespace MeshGeoToolsLib +{ +GeoMapper::GeoMapper(GeoLib::GEOObjects& geo_objects, + const std::string& geo_name) + : _geo_objects(geo_objects), + _geo_name(const_cast<std::string&>(geo_name)), + _surface_mesh(nullptr), + _grid(nullptr), + _raster(nullptr) { } @@ -50,24 +51,31 @@ GeoMapper::~GeoMapper() void GeoMapper::mapOnDEM(std::unique_ptr<GeoLib::Raster const> raster) { - std::vector<GeoLib::Point*> const* pnts(_geo_objects.getPointVec(_geo_name)); - if (! pnts) { + std::vector<GeoLib::Point*> const* pnts( + _geo_objects.getPointVec(_geo_name)); + if (!pnts) + { ERR("Geometry '{:s}' does not exist.", _geo_name); return; } _raster = std::move(raster); - if (GeoLib::isStation((*pnts)[0])) { + if (GeoLib::isStation((*pnts)[0])) + { mapStationData(*pnts); - } else { + } + else + { mapPointDataToDEM(*pnts); } } -void GeoMapper::mapOnMesh(MeshLib::Mesh const*const mesh) +void GeoMapper::mapOnMesh(MeshLib::Mesh const* const mesh) { - std::vector<GeoLib::Point*> const* pnts(_geo_objects.getPointVec(_geo_name)); - if (! pnts) { + std::vector<GeoLib::Point*> const* pnts( + _geo_objects.getPointVec(_geo_name)); + if (!pnts) + { ERR("Geometry '{:s}' does not exist.", _geo_name); return; } @@ -82,26 +90,31 @@ void GeoMapper::mapOnMesh(MeshLib::Mesh const*const mesh) } else { - Eigen::Vector3d const dir(0,0,-1); + Eigen::Vector3d const dir(0, 0, -1); _surface_mesh = MeshLib::MeshSurfaceExtraction::getMeshSurface(*mesh, dir, 90); } // init grid - MathLib::Point3d origin(std::array<double,3>{{0,0,0}}); + MathLib::Point3d origin(std::array<double, 3>{{0, 0, 0}}); std::vector<MeshLib::Node> flat_nodes; flat_nodes.reserve(_surface_mesh->getNumberOfNodes()); // copy nodes and project the copied nodes to the x-y-plane, i.e. set // z-coordinate to zero - for (auto n_ptr : _surface_mesh->getNodes()) { + for (auto n_ptr : _surface_mesh->getNodes()) + { flat_nodes.emplace_back(*n_ptr); flat_nodes.back()[2] = 0.0; } - _grid = new GeoLib::Grid<MeshLib::Node>(flat_nodes.cbegin(), flat_nodes.cend()); + _grid = + new GeoLib::Grid<MeshLib::Node>(flat_nodes.cbegin(), flat_nodes.cend()); - if (GeoLib::isStation((*pnts)[0])) { + if (GeoLib::isStation((*pnts)[0])) + { mapStationData(*pnts); - } else { + } + else + { mapPointDataToMeshSurface(*pnts); } @@ -110,13 +123,15 @@ void GeoMapper::mapOnMesh(MeshLib::Mesh const*const mesh) void GeoMapper::mapToConstantValue(double value) { - std::vector<GeoLib::Point*> const* points (this->_geo_objects.getPointVec(this->_geo_name)); + std::vector<GeoLib::Point*> const* points( + this->_geo_objects.getPointVec(this->_geo_name)); if (points == nullptr) { ERR("Geometry '{:s}' not found.", this->_geo_name); return; } - std::for_each(points->begin(), points->end(), [value](GeoLib::Point* pnt){ (*pnt)[2] = value; }); + std::for_each(points->begin(), points->end(), + [value](GeoLib::Point* pnt) { (*pnt)[2] = value; }); } void GeoMapper::mapStationData(std::vector<GeoLib::Point*> const& points) @@ -125,13 +140,13 @@ void GeoMapper::mapStationData(std::vector<GeoLib::Point*> const& points) double max_val(0); if (_surface_mesh) { - GeoLib::AABB bounding_box( - _surface_mesh->getNodes().begin(), _surface_mesh->getNodes().end()); + GeoLib::AABB bounding_box(_surface_mesh->getNodes().begin(), + _surface_mesh->getNodes().end()); min_val = bounding_box.getMinPoint()[2]; max_val = bounding_box.getMaxPoint()[2]; } - for (auto * pnt : points) + for (auto* pnt : points) { double offset = (_grid) @@ -143,8 +158,10 @@ void GeoMapper::mapStationData(std::vector<GeoLib::Point*> const& points) { continue; } - auto const& layers = static_cast<GeoLib::StationBorehole*>(pnt)->getProfile(); - for (auto * layer_pnt : layers) { + auto const& layers = + static_cast<GeoLib::StationBorehole*>(pnt)->getProfile(); + for (auto* layer_pnt : layers) + { (*layer_pnt)[2] = (*layer_pnt)[2] + offset; } } @@ -153,24 +170,26 @@ void GeoMapper::mapStationData(std::vector<GeoLib::Point*> const& points) void GeoMapper::mapPointDataToDEM( std::vector<GeoLib::Point*> const& points) const { - for (auto * pnt : points) + for (auto* pnt : points) { - GeoLib::Point &p(*pnt); + GeoLib::Point& p(*pnt); p[2] = getDemElevation(p); } } -void GeoMapper::mapPointDataToMeshSurface(std::vector<GeoLib::Point*> const& pnts) +void GeoMapper::mapPointDataToMeshSurface( + std::vector<GeoLib::Point*> const& pnts) { - GeoLib::AABB const aabb( - _surface_mesh->getNodes().cbegin(), _surface_mesh->getNodes().cend()); + GeoLib::AABB const aabb(_surface_mesh->getNodes().cbegin(), + _surface_mesh->getNodes().cend()); double const min_val(aabb.getMinPoint()[2]); double const max_val(aabb.getMaxPoint()[2]); - for (auto * pnt : pnts) { + for (auto* pnt : pnts) + { // check if pnt is inside of the bounding box of the _surface_mesh // projected onto the y-x plane - GeoLib::Point &p(*pnt); + GeoLib::Point& p(*pnt); if (p[0] < aabb.getMinPoint()[0] || aabb.getMaxPoint()[0] < p[0]) { continue; @@ -186,7 +205,7 @@ void GeoMapper::mapPointDataToMeshSurface(std::vector<GeoLib::Point*> const& pnt float GeoMapper::getDemElevation(GeoLib::Point const& pnt) const { - double const elevation (_raster->getValueAtPoint(pnt)); + double const elevation(_raster->getValueAtPoint(pnt)); if (std::abs(elevation - _raster->getHeader().no_data) < std::numeric_limits<double>::epsilon()) { @@ -195,8 +214,8 @@ float GeoMapper::getDemElevation(GeoLib::Point const& pnt) const return static_cast<float>(elevation); } -double GeoMapper::getMeshElevation( - double x, double y, double min_val, double max_val) const +double GeoMapper::getMeshElevation(double x, double y, double min_val, + double max_val) const { const MeshLib::Node* pnt = _grid->getNearestPoint(MathLib::Point3d{{{x, y, 0}}}); @@ -204,7 +223,7 @@ double GeoMapper::getMeshElevation( _surface_mesh->getNode(pnt->getID())->getElements()); std::unique_ptr<GeoLib::Point> intersection; - for (auto const & element : elements) + for (auto const& element : elements) { if (intersection == nullptr && element->getGeomType() != MeshLib::MeshElemType::LINE) @@ -228,11 +247,13 @@ double GeoMapper::getMeshElevation( { return (*intersection)[2]; } - // if something goes wrong, simply take the elevation of the nearest mesh node + // if something goes wrong, simply take the elevation of the nearest mesh + // node return (*(_surface_mesh->getNode(pnt->getID())))[2]; } -/// Find the 2d-element within the \c elements that contains the given point \c p. +/// Find the 2d-element within the \c elements that contains the given point \c +/// p. /// /// The algorithm projects every element of the elements vector and the point /// \c p orthogonal to the \f$x\f$-\f$y\f$ plane. In the \f$x\f$-\f$y\f$ plane @@ -241,19 +262,24 @@ static MeshLib::Element const* findElementContainingPointXY( std::vector<MeshLib::Element const*> const& elements, MathLib::Point3d const& p) { - for (auto const elem : elements) { + for (auto const elem : elements) + { std::unique_ptr<MeshLib::Element> elem_2d(elem->clone()); // reset/copy the nodes - for (std::size_t k(0); k<elem_2d->getNumberOfNodes(); ++k) { + for (std::size_t k(0); k < elem_2d->getNumberOfNodes(); ++k) + { elem_2d->setNode(k, new MeshLib::Node(*elem_2d->getNode(k))); } // project to xy - for (std::size_t k(0); k<elem_2d->getNumberOfNodes(); ++k) { + for (std::size_t k(0); k < elem_2d->getNumberOfNodes(); ++k) + { (*const_cast<MeshLib::Node*>(elem_2d->getNode(k)))[2] = 0.0; } - if (elem_2d->isPntInElement(MathLib::Point3d{ {{p[0], p[1], 0.0}} })) { + if (elem_2d->isPntInElement(MathLib::Point3d{{{p[0], p[1], 0.0}}})) + { // clean up the copied nodes - for (std::size_t k(0); k<elem_2d->getNumberOfNodes(); ++k) { + for (std::size_t k(0); k < elem_2d->getNumberOfNodes(); ++k) + { delete elem_2d->getNode(k); } return elem; @@ -277,9 +303,11 @@ static std::vector<MathLib::Point3d> computeElementSegmentIntersections( std::unique_ptr<MeshLib::Element const>(elem.getEdge(k)); GeoLib::LineSegment elem_segment{ new GeoLib::Point(*dynamic_cast<MathLib::Point3d*>( - const_cast<MeshLib::Node*>(edge->getNode(0))), 0), + const_cast<MeshLib::Node*>(edge->getNode(0))), + 0), new GeoLib::Point(*dynamic_cast<MathLib::Point3d*>( - const_cast<MeshLib::Node*>(edge->getNode(1))), 0), + const_cast<MeshLib::Node*>(edge->getNode(1))), + 0), true}; std::vector<MathLib::Point3d> const intersections( GeoLib::lineSegmentIntersect2d(segment, elem_segment)); @@ -296,10 +324,11 @@ static std::vector<GeoLib::LineSegment> createSubSegmentsForElement( MathLib::Point3d const& end_pnt, MeshLib::Element const* const elem) { std::vector<GeoLib::LineSegment> sub_segments; - if (intersections.size() > 2) { + if (intersections.size() > 2) + { std::stringstream out; out << "element with id " << elem->getID() << " and seg " - << " intersecting at more than two edges\n"; + << " intersecting at more than two edges\n"; for (std::size_t k(0); k < intersections.size(); ++k) { out << k << " " << intersections[k] << "\n"; @@ -361,7 +390,8 @@ static std::vector<GeoLib::LineSegment> mapLineSegment( MathLib::Point3d const& beg_pnt(segment.getBeginPoint()); MathLib::Point3d const& end_pnt(segment.getEndPoint()); - for (auto const elem : surface_elements) { + for (auto const elem : surface_elements) + { // compute element-segment-intersections (2d in x-y-plane) std::vector<MathLib::Point3d> element_intersections( computeElementSegmentIntersections(*elem, segment)); @@ -387,8 +417,7 @@ static std::vector<GeoLib::LineSegment> mapLineSegment( auto min_dist_segment = std::min_element( sub_segments.begin(), sub_segments.end(), [&beg_pnt](GeoLib::LineSegment const& seg0, - GeoLib::LineSegment const& seg1) - { + GeoLib::LineSegment const& seg1) { // min dist for segment 0 const double d0( std::min(MathLib::sqrDist(beg_pnt, seg0.getBeginPoint()), @@ -399,7 +428,7 @@ static std::vector<GeoLib::LineSegment> mapLineSegment( MathLib::sqrDist(beg_pnt, seg1.getEndPoint()))); return d0 < d1; }); - GeoLib::Point * pnt{ + GeoLib::Point* pnt{ MathLib::sqrDist(beg_pnt, min_dist_segment->getBeginPoint()) < MathLib::sqrDist(beg_pnt, min_dist_segment->getEndPoint()) ? new GeoLib::Point{min_dist_segment->getBeginPoint()} @@ -422,11 +451,14 @@ static void mapPointOnSurfaceElement(MeshLib::Element const& elem, auto const p = Eigen::Map<Eigen::Vector3d const>(elem.getNode(0)->getCoords()); Eigen::Vector3d const n(MeshLib::FaceRule::getSurfaceNormal(&elem)); - if (n[2] == 0.0) { // vertical plane, z coordinate is arbitrary + if (n[2] == 0.0) + { // vertical plane, z coordinate is arbitrary q[2] = p[2]; - } else { + } + else + { double const d(n.dot(p)); - q[2] = (d - n[0]*q[0] - n[1]*q[1])/n[2]; + q[2] = (d - n[0] * q[0] - n[1] * q[1]) / n[2]; } } @@ -461,11 +493,13 @@ static bool snapPointToElementNode(MathLib::Point3d& p, // values will be initialized within computeSqrNodeDistanceRange auto const [sqr_min, sqr_max] = MeshLib::computeSqrNodeDistanceRange(elem); - double const sqr_eps(rel_eps*rel_eps * sqr_min); - for (std::size_t k(0); k<elem.getNumberOfNodes(); ++k) { + double const sqr_eps(rel_eps * rel_eps * sqr_min); + for (std::size_t k(0); k < elem.getNumberOfNodes(); ++k) + { auto const& node(*elem.getNode(k)); double const sqr_dist_2d(MathLib::sqrDist2d(p, node)); - if (sqr_dist_2d < sqr_eps) { + if (sqr_dist_2d < sqr_eps) + { #ifdef DEBUG_GEOMAPPER std::stringstream out; out.precision(std::numeric_limits<double>::digits10); @@ -540,7 +574,8 @@ static void mapPolylineOnSurfaceMesh( // invalid and hence it is necessary to re-create them. orig_points.resetInternalDataStructures(); - if (beg_elem == end_elem) { + if (beg_elem == end_elem) + { // TODO: handle cases: beg_elem == end_elem == nullptr // There are further checks necessary to determine which case we are // in: @@ -575,12 +610,15 @@ void GeoMapper::advancedMapOnMesh(MeshLib::Mesh const& mesh) // 1. extract surface delete _surface_mesh; - if (mesh.getDimension()<3) { + if (mesh.getDimension() < 3) + { _surface_mesh = new MeshLib::Mesh(mesh); - } else { + } + else + { Eigen::Vector3d const dir({0, 0, -1}); - _surface_mesh = - MeshLib::MeshSurfaceExtraction::getMeshSurface(mesh, dir, 90+1e-6); + _surface_mesh = MeshLib::MeshSurfaceExtraction::getMeshSurface( + mesh, dir, 90 + 1e-6); } // 2. compute mesh grid for surface @@ -595,4 +633,4 @@ void GeoMapper::advancedMapOnMesh(MeshLib::Mesh const& mesh) } } -} // end namespace MeshGeoToolsLib +} // end namespace MeshGeoToolsLib diff --git a/MeshGeoToolsLib/HeuristicSearchLength.cpp b/MeshGeoToolsLib/HeuristicSearchLength.cpp index 318ae2c34523367824df1762b635e8c190ff8a62..096d7aa3c273fae8345c1d4b38eb99d52e7133a7 100644 --- a/MeshGeoToolsLib/HeuristicSearchLength.cpp +++ b/MeshGeoToolsLib/HeuristicSearchLength.cpp @@ -13,36 +13,39 @@ #include "HeuristicSearchLength.h" #include "BaseLib/Logging.h" - #include "MeshLib/Elements/Element.h" namespace MeshGeoToolsLib { - -HeuristicSearchLength::HeuristicSearchLength(MeshLib::Mesh const& mesh, LengthType length_type) -: _mesh(mesh) +HeuristicSearchLength::HeuristicSearchLength(MeshLib::Mesh const& mesh, + LengthType length_type) + : _mesh(mesh) { - double sum (0.0); - double sum_of_sqr (0.0); // total length of edges + double sum(0.0); + double sum_of_sqr(0.0); // total length of edges - std::size_t n_sampling(0); // total length of edges squared + std::size_t n_sampling(0); // total length of edges squared std::vector<MeshLib::Element*> const& elements(_mesh.getElements()); - if (length_type==LengthType::Edge) { + if (length_type == LengthType::Edge) + { for (auto element : elements) { std::size_t const n_edges(element->getNumberOfEdges()); - for (std::size_t k(0); k<n_edges; k++) { + for (std::size_t k(0); k < n_edges; k++) + { auto edge = element->getEdge(k); // allocation inside getEdge(). double const len = edge->getContent(); delete edge; sum += len; - sum_of_sqr += len*len; + sum_of_sqr += len * len; } n_sampling += n_edges; } - } else { + } + else + { for (const MeshLib::Element* e : elements) { auto const [min, max] = @@ -53,14 +56,16 @@ HeuristicSearchLength::HeuristicSearchLength(MeshLib::Mesh const& mesh, LengthTy n_sampling = _mesh.getNumberOfElements(); } - const double mean (sum/n_sampling); - const double variance ((sum_of_sqr - (sum*sum)/n_sampling)/(n_sampling-1)); + const double mean(sum / n_sampling); + const double variance((sum_of_sqr - (sum * sum) / n_sampling) / + (n_sampling - 1)); // Set the search length for the case of non-positive variance (which can // happen due to numerics). - _search_length = mean/2; + _search_length = mean / 2; - if (variance > 0) { + if (variance > 0) + { if (variance < mean * mean / 4) { _search_length -= std::sqrt(variance); @@ -77,4 +82,4 @@ HeuristicSearchLength::HeuristicSearchLength(MeshLib::Mesh const& mesh, LengthTy _mesh.getName(), _search_length); } -} // end namespace MeshGeoToolsLib +} // end namespace MeshGeoToolsLib diff --git a/MeshGeoToolsLib/IdentifySubdomainMesh.cpp b/MeshGeoToolsLib/IdentifySubdomainMesh.cpp index 5246b2382a4235058122fd2dfb89f5e4fd2ca156..bf9ca67a1ea34984278f02c099ad87fcfe1b5ed3 100644 --- a/MeshGeoToolsLib/IdentifySubdomainMesh.cpp +++ b/MeshGeoToolsLib/IdentifySubdomainMesh.cpp @@ -13,7 +13,6 @@ #include "MeshLib/Elements/Element.h" #include "MeshLib/Mesh.h" #include "MeshLib/Node.h" - #include "MeshNodeSearcher.h" namespace diff --git a/MeshGeoToolsLib/MeshNodeSearcher.cpp b/MeshGeoToolsLib/MeshNodeSearcher.cpp index cd3c90f89e2e578bf442c3c4b6a066e18c13ea33..7af112eb6b31b40c5927849d7483002534d572ef 100644 --- a/MeshGeoToolsLib/MeshNodeSearcher.cpp +++ b/MeshGeoToolsLib/MeshNodeSearcher.cpp @@ -11,22 +11,19 @@ #include "MeshNodeSearcher.h" -#include <typeinfo> #include <sstream> - -#include "HeuristicSearchLength.h" -#include "MeshNodesAlongPolyline.h" -#include "MeshNodesAlongSurface.h" -#include "MeshNodesOnPoint.h" +#include <typeinfo> #include "BaseLib/Logging.h" - #include "GeoLib/Point.h" #include "GeoLib/Polyline.h" - +#include "HeuristicSearchLength.h" #include "MeshLib/Elements/Element.h" #include "MeshLib/Mesh.h" #include "MeshLib/Node.h" +#include "MeshNodesAlongPolyline.h" +#include "MeshNodesAlongSurface.h" +#include "MeshNodesOnPoint.h" namespace MeshGeoToolsLib { @@ -67,8 +64,7 @@ std::vector<std::size_t> const& getMeshNodeIDs( std::vector<CacheType*>& cached_elements, std::function<GeometryType(CacheType const&)> getCachedItem, GeometryType const& item, MeshLib::Mesh const& mesh, - GeoLib::Grid<MeshLib::Node> const& mesh_grid, - double const search_length, + GeoLib::Grid<MeshLib::Node> const& mesh_grid, double const search_length, SearchAllNodes const search_all_nodes) { if (auto const it = find_if(cbegin(cached_elements), cend(cached_elements), diff --git a/MeshGeoToolsLib/MeshNodesAlongPolyline.cpp b/MeshGeoToolsLib/MeshNodesAlongPolyline.cpp index 2c2765d394b94120318a12e1d71808d790bc7631..bc5e16aca4e025c7851f4ecefa3a3b21fd59a8f4 100644 --- a/MeshGeoToolsLib/MeshNodesAlongPolyline.cpp +++ b/MeshGeoToolsLib/MeshNodesAlongPolyline.cpp @@ -14,8 +14,8 @@ #include <algorithm> #include "BaseLib/quicksort.h" -#include "MathLib/MathTools.h" #include "GeoLib/Polyline.h" +#include "MathLib/MathTools.h" #include "MeshLib/Mesh.h" #include "MeshLib/Node.h" @@ -31,32 +31,36 @@ MeshNodesAlongPolyline::MeshNodesAlongPolyline(MeshLib::Mesh const& mesh, const std::size_t n_nodes(search_all_nodes == SearchAllNodes::Yes ? _mesh.getNumberOfNodes() : _mesh.getNumberOfBaseNodes()); - auto &mesh_nodes = _mesh.getNodes(); + auto& mesh_nodes = _mesh.getNodes(); // loop over all nodes - for (std::size_t i = 0; i < n_nodes; i++) { - double dist = _ply.getDistanceAlongPolyline(*mesh_nodes[i], epsilon_radius); - if (dist >= 0.0) { + for (std::size_t i = 0; i < n_nodes; i++) + { + double dist = + _ply.getDistanceAlongPolyline(*mesh_nodes[i], epsilon_radius); + if (dist >= 0.0) + { _msh_node_ids.push_back(mesh_nodes[i]->getID()); _dist_of_proj_node_from_ply_start.push_back(dist); } } // sort the nodes along the polyline according to their distances - BaseLib::quicksort<double> (_dist_of_proj_node_from_ply_start, 0, - _dist_of_proj_node_from_ply_start.size(), _msh_node_ids); + BaseLib::quicksort<double>(_dist_of_proj_node_from_ply_start, 0, + _dist_of_proj_node_from_ply_start.size(), + _msh_node_ids); } -MeshLib::Mesh const& MeshNodesAlongPolyline::getMesh () const +MeshLib::Mesh const& MeshNodesAlongPolyline::getMesh() const { return _mesh; } -std::vector<std::size_t> const& MeshNodesAlongPolyline::getNodeIDs () const +std::vector<std::size_t> const& MeshNodesAlongPolyline::getNodeIDs() const { return _msh_node_ids; } -GeoLib::Polyline const& MeshNodesAlongPolyline::getPolyline () const +GeoLib::Polyline const& MeshNodesAlongPolyline::getPolyline() const { return _ply; } diff --git a/MeshGeoToolsLib/MeshNodesAlongSurface.cpp b/MeshGeoToolsLib/MeshNodesAlongSurface.cpp index bafc4c2548641727d6d589ee86ddeea90bcd947d..2c39e13650cd09ad7cd1071a02f194372275606e 100644 --- a/MeshGeoToolsLib/MeshNodesAlongSurface.cpp +++ b/MeshGeoToolsLib/MeshNodesAlongSurface.cpp @@ -15,8 +15,8 @@ #include <algorithm> #include "BaseLib/quicksort.h" -#include "MathLib/MathTools.h" #include "GeoLib/Surface.h" +#include "MathLib/MathTools.h" #include "MeshLib/Mesh.h" #include "MeshLib/Node.h" @@ -33,31 +33,33 @@ MeshNodesAlongSurface::MeshNodesAlongSurface(MeshLib::Mesh const& mesh, ? _mesh.getNumberOfNodes() : _mesh.getNumberOfBaseNodes()); // loop over all nodes - for (std::size_t i = 0; i < n_nodes; i++) { + for (std::size_t i = 0; i < n_nodes; i++) + { auto* node = mesh_nodes[i]; if (!sfc.isPntInBoundingVolume(*node, epsilon_radius)) { continue; } - if (sfc.isPntInSfc(*node, epsilon_radius)) { + if (sfc.isPntInSfc(*node, epsilon_radius)) + { _msh_node_ids.push_back(node->getID()); } } } -MeshLib::Mesh const& MeshNodesAlongSurface::getMesh () const +MeshLib::Mesh const& MeshNodesAlongSurface::getMesh() const { return _mesh; } -std::vector<std::size_t> const& MeshNodesAlongSurface::getNodeIDs () const +std::vector<std::size_t> const& MeshNodesAlongSurface::getNodeIDs() const { return _msh_node_ids; } -GeoLib::Surface const& MeshNodesAlongSurface::getSurface () const +GeoLib::Surface const& MeshNodesAlongSurface::getSurface() const { return _sfc; } -} // end namespace MeshGeoToolsLib +} // end namespace MeshGeoToolsLib diff --git a/MeshGeoToolsLib/MeshNodesOnPoint.cpp b/MeshGeoToolsLib/MeshNodesOnPoint.cpp index d6b8d9fb1cdbb7bd4be04966d955310c989c50c5..30d0e93113fd8cd6606672f7e796d9fde8045f2a 100644 --- a/MeshGeoToolsLib/MeshNodesOnPoint.cpp +++ b/MeshGeoToolsLib/MeshNodesOnPoint.cpp @@ -39,4 +39,3 @@ MeshNodesOnPoint::MeshNodesOnPoint(MeshLib::Mesh const& mesh, } } // end namespace MeshGeoToolsLib - diff --git a/MeshLib/CoordinateSystem.cpp b/MeshLib/CoordinateSystem.cpp index 2cf10443648eed0a62c475d8cef54adec5da674a..f50feec578f1b11459e04253eface2949041c4a7 100644 --- a/MeshLib/CoordinateSystem.cpp +++ b/MeshLib/CoordinateSystem.cpp @@ -9,19 +9,22 @@ #include "CoordinateSystem.h" -#include "MeshLib/Node.h" #include "MeshLib/Elements/Element.h" +#include "MeshLib/Node.h" namespace MeshLib { - -CoordinateSystem::CoordinateSystem(const Element &ele) +CoordinateSystem::CoordinateSystem(const Element& ele) { - GeoLib::AABB const aabb(ele.getNodes(), ele.getNodes() + ele.getNumberOfNodes()); + GeoLib::AABB const aabb(ele.getNodes(), + ele.getNodes() + ele.getNumberOfNodes()); CoordinateSystem const bboxCoordSys(getCoordinateSystem(aabb)); - if (bboxCoordSys.getDimension() >= ele.getDimension()) { + if (bboxCoordSys.getDimension() >= ele.getDimension()) + { _type = bboxCoordSys.getType(); - } else { // e.g. zero volume elements + } + else + { // e.g. zero volume elements if (ele.getDimension() >= 1) { _type = CoordinateSystemType::X; @@ -37,7 +40,8 @@ CoordinateSystem::CoordinateSystem(const Element &ele) } } -unsigned char CoordinateSystem::getCoordinateSystem(const GeoLib::AABB &bbox) const +unsigned char CoordinateSystem::getCoordinateSystem( + const GeoLib::AABB& bbox) const { unsigned char coords = 0; diff --git a/MeshLib/ElementCoordinatesMappingLocal.cpp b/MeshLib/ElementCoordinatesMappingLocal.cpp index 730cdfe732dddf4c3763a0ef857e3fc5e4fc4459..34692d62cae34d5191a76ddd56b6b519296b536e 100644 --- a/MeshLib/ElementCoordinatesMappingLocal.cpp +++ b/MeshLib/ElementCoordinatesMappingLocal.cpp @@ -9,15 +9,14 @@ #include "ElementCoordinatesMappingLocal.h" -#include <limits> #include <cassert> +#include <limits> #include "GeoLib/AnalyticalGeometry.h" - -#include "MeshLib/Elements/Element.h" -#include "MeshLib/Node.h" #include "MathLib/MathTools.h" #include "MathLib/Point3d.h" +#include "MeshLib/Elements/Element.h" +#include "MeshLib/Node.h" namespace detail { diff --git a/MeshLib/ElementStatus.cpp b/MeshLib/ElementStatus.cpp index 5747a9851196f649ca76669b66768546e7a063b8..b82094acd83f99a1c5c3b27a1615075cd46904ed 100644 --- a/MeshLib/ElementStatus.cpp +++ b/MeshLib/ElementStatus.cpp @@ -14,12 +14,12 @@ #include "ElementStatus.h" +#include "Elements/Element.h" #include "Mesh.h" #include "MeshLib/Node.h" -#include "Elements/Element.h" - -namespace MeshLib { +namespace MeshLib +{ ElementStatus::ElementStatus(Mesh const* const mesh, bool hasAnyInactive) : _mesh(mesh), _element_status(mesh->getNumberOfElements(), true), @@ -39,9 +39,12 @@ ElementStatus::ElementStatus(Mesh const* const mesh, { auto* const materialIds = mesh->getProperties().getPropertyVector<int>("MaterialIDs"); - for (auto material_id : vec_inactive_matIDs) { - for (auto e : _mesh->getElements()) { - if ((*materialIds)[e->getID()] == material_id) { + for (auto material_id : vec_inactive_matIDs) + { + for (auto e : _mesh->getElements()) + { + if ((*materialIds)[e->getID()] == material_id) + { setElementStatus(e->getID(), false); } } @@ -49,7 +52,7 @@ ElementStatus::ElementStatus(Mesh const* const mesh, } _vec_active_eles.reserve(getNumberOfActiveElements()); - const std::size_t nElems (_mesh->getNumberOfElements()); + const std::size_t nElems(_mesh->getNumberOfElements()); for (std::size_t i = 0; i < nElems; ++i) { if (_element_status[i]) @@ -60,7 +63,7 @@ ElementStatus::ElementStatus(Mesh const* const mesh, } _vec_active_nodes.reserve(this->getNumberOfActiveNodes()); - const std::size_t nNodes (_mesh->getNumberOfNodes()); + const std::size_t nNodes(_mesh->getNumberOfNodes()); for (std::size_t i = 0; i < nNodes; ++i) { if (_active_nodes[i] > 0) @@ -100,7 +103,8 @@ std::vector<MeshLib::Node*> const& ElementStatus::getActiveNodes() const std::size_t ElementStatus::getNumberOfActiveNodes() const { - return _active_nodes.size() - std::count(_active_nodes.cbegin(), _active_nodes.cend(), 0); + return _active_nodes.size() - + std::count(_active_nodes.cbegin(), _active_nodes.cend(), 0); } std::size_t ElementStatus::getNumberOfActiveElements() const @@ -115,9 +119,10 @@ void ElementStatus::setElementStatus(std::size_t i, bool status) { const int change = (status) ? 1 : -1; _element_status[i] = status; - const unsigned nElemNodes (_mesh->getElement(i)->getNumberOfNodes()); - MeshLib::Node const*const*const nodes = _mesh->getElement(i)->getNodes(); - for (unsigned j=0; j<nElemNodes; ++j) + const unsigned nElemNodes(_mesh->getElement(i)->getNumberOfNodes()); + MeshLib::Node const* const* const nodes = + _mesh->getElement(i)->getNodes(); + for (unsigned j = 0; j < nElemNodes; ++j) { assert(_active_nodes[j] < 255); // if one node has >255 connected // elements the data type is too @@ -129,7 +134,7 @@ void ElementStatus::setElementStatus(std::size_t i, bool status) bool ElementStatus::isActiveNode(MeshLib::Node const* node) const { - return _active_nodes[node->getID()]>0; + return _active_nodes[node->getID()] > 0; } } // namespace MeshLib diff --git a/MeshLib/Elements/CellRule.cpp b/MeshLib/Elements/CellRule.cpp index bce43895fee919c95ef8ab7e08af7518b3279783..17e0a3fd4b17d88180b1f59bf03ba08a383625e7 100644 --- a/MeshLib/Elements/CellRule.cpp +++ b/MeshLib/Elements/CellRule.cpp @@ -10,12 +10,12 @@ #include "CellRule.h" -#include "MeshLib/Node.h" #include "Element.h" #include "FaceRule.h" +#include "MeshLib/Node.h" -namespace MeshLib { - +namespace MeshLib +{ bool CellRule::testElementNodeOrder(const Element* e) { Eigen::Vector3d const cc = @@ -24,10 +24,10 @@ bool CellRule::testElementNodeOrder(const Element* e) for (unsigned j = 0; j < nFaces; ++j) { MeshLib::Element const* const face(e->getFace(j)); - // Node 1 is checked below because that way all nodes are used for the test - // at some point, while for node 0 at least one node in every element - // type would be used for checking twice and one wouldn't be checked at - // all. (based on the definition of the _face_nodes variable) + // Node 1 is checked below because that way all nodes are used for the + // test at some point, while for node 0 at least one node in every + // element type would be used for checking twice and one wouldn't be + // checked at all. (based on the definition of the _face_nodes variable) auto const x = Eigen::Map<Eigen::Vector3d const>(face->getNode(1)->getCoords()); Eigen::Vector3d const cx = x - cc; diff --git a/MeshLib/Elements/EdgeReturn.cpp b/MeshLib/Elements/EdgeReturn.cpp index fa94ff5d60910c9628ac20c2e9bad5c1dbf97b81..500ef0e14e25f4322facc11dddf8a548c2020183 100644 --- a/MeshLib/Elements/EdgeReturn.cpp +++ b/MeshLib/Elements/EdgeReturn.cpp @@ -11,21 +11,19 @@ #include "EdgeReturn.h" #include "BaseLib/Logging.h" - -#include "MeshLib/Node.h" #include "Element.h" #include "Line.h" +#include "MeshLib/Node.h" namespace MeshLib { - const Element* LinearEdgeReturn::getEdge(const Element* e, unsigned i) { if (i < e->getNumberOfEdges()) { auto** nodes = new Node*[2]; - nodes[0] = const_cast<Node*>(e->getEdgeNode(i,0)); - nodes[1] = const_cast<Node*>(e->getEdgeNode(i,1)); + nodes[0] = const_cast<Node*>(e->getEdgeNode(i, 0)); + nodes[1] = const_cast<Node*>(e->getEdgeNode(i, 1)); return new Line(nodes, e->getID()); } ERR("Error in MeshLib::Element::getEdge() - Index does not exist."); @@ -37,9 +35,9 @@ const Element* QuadraticEdgeReturn::getEdge(const Element* e, unsigned i) if (i < e->getNumberOfEdges()) { auto** nodes = new Node*[3]; - nodes[0] = const_cast<Node*>(e->getEdgeNode(i,0)); - nodes[1] = const_cast<Node*>(e->getEdgeNode(i,1)); - nodes[2] = const_cast<Node*>(e->getEdgeNode(i,2)); + nodes[0] = const_cast<Node*>(e->getEdgeNode(i, 0)); + nodes[1] = const_cast<Node*>(e->getEdgeNode(i, 1)); + nodes[2] = const_cast<Node*>(e->getEdgeNode(i, 2)); return new Line3(nodes, e->getID()); } ERR("Error in MeshLib::Element::getEdge() - Index does not exist."); diff --git a/MeshLib/Elements/Element.cpp b/MeshLib/Elements/Element.cpp index f73cfa6ce9523a3af2d071f1b84c3e211177441c..95490314afb8d29773f4cf62b010608c46f7b2e6 100644 --- a/MeshLib/Elements/Element.cpp +++ b/MeshLib/Elements/Element.cpp @@ -15,15 +15,13 @@ #include "Element.h" #include "BaseLib/Logging.h" - +#include "Line.h" #include "MathLib/GeometricBasics.h" #include "MathLib/MathTools.h" #include "MeshLib/Node.h" -#include "Line.h" - -namespace MeshLib { - +namespace MeshLib +{ Element::Element(std::size_t id) : _nodes(nullptr), _id(id), _content(-1.0), _neighbors(nullptr) { @@ -31,8 +29,8 @@ Element::Element(std::size_t id) Element::~Element() { - delete [] this->_nodes; - delete [] this->_neighbors; + delete[] this->_nodes; + delete[] this->_neighbors; } void Element::setNeighbor(Element* neighbor, unsigned const face_id) @@ -58,11 +56,11 @@ std::optional<unsigned> Element::addNeighbor(Element* e) } Node* face_nodes[3]; - const unsigned nNodes (this->getNumberOfBaseNodes()); - const unsigned eNodes (e->getNumberOfBaseNodes()); + const unsigned nNodes(this->getNumberOfBaseNodes()); + const unsigned eNodes(e->getNumberOfBaseNodes()); const Node* const* e_nodes = e->getNodes(); unsigned count(0); - const unsigned dim (this->getDimension()); + const unsigned dim(this->getDimension()); for (unsigned i(0); i < nNodes; i++) { for (unsigned j(0); j < eNodes; j++) @@ -70,10 +68,11 @@ std::optional<unsigned> Element::addNeighbor(Element* e) if (_nodes[i] == e_nodes[j]) { face_nodes[count] = _nodes[i]; - // increment shared nodes counter and check if enough nodes are similar to be sure e is a neighbour of this - if ((++count)>=dim) + // increment shared nodes counter and check if enough nodes are + // similar to be sure e is a neighbour of this + if ((++count) >= dim) { - _neighbors[ this->identifyFace(face_nodes) ] = e; + _neighbors[this->identifyFace(face_nodes)] = e; return std::optional<unsigned>(e->identifyFace(face_nodes)); } } @@ -99,7 +98,7 @@ const Element* Element::getNeighbor(unsigned i) const unsigned Element::getNodeIDinElement(const MeshLib::Node* node) const { - const unsigned nNodes (this->getNumberOfNodes()); + const unsigned nNodes(this->getNumberOfNodes()); for (unsigned i(0); i < nNodes; i++) { if (node == _nodes[i]) @@ -151,21 +150,22 @@ std::size_t Element::getNodeIndex(unsigned i) const bool Element::isBoundaryElement() const { - return std::any_of(_neighbors, _neighbors + this->getNumberOfNeighbors(), - [](MeshLib::Element const*const e){ return e == nullptr; }); + return std::any_of( + _neighbors, _neighbors + this->getNumberOfNeighbors(), + [](MeshLib::Element const* const e) { return e == nullptr; }); } #ifndef NDEBUG std::ostream& operator<<(std::ostream& os, Element const& e) { - os << "Element #" << e._id << " @ " << &e << " with " << e.getNumberOfNeighbors() - << " neighbours\n"; + os << "Element #" << e._id << " @ " << &e << " with " + << e.getNumberOfNeighbors() << " neighbours\n"; unsigned const nnodes = e.getNumberOfNodes(); MeshLib::Node* const* const nodes = e.getNodes(); os << "MeshElemType: " - << static_cast<std::underlying_type<MeshElemType>::type>(e.getGeomType()) - << " with " << nnodes << " nodes: { "; + << static_cast<std::underlying_type<MeshElemType>::type>(e.getGeomType()) + << " with " << nnodes << " nodes: { "; for (unsigned n = 0; n < nnodes; ++n) { os << nodes[n]->getID() << " @ " << nodes[n] << " "; @@ -246,7 +246,8 @@ std::pair<double, double> computeSqrEdgeLengthRange(Element const& element) bool isPointInElementXY(MathLib::Point3d const& p, Element const& e) { - for(std::size_t i(0); i<e.getNumberOfBaseNodes(); ++i) { + for (std::size_t i(0); i < e.getNumberOfBaseNodes(); ++i) + { if (MathLib::sqrDist2d(p, *e.getNode(i)) < std::numeric_limits<double>::epsilon()) { diff --git a/MeshLib/Elements/FaceRule.cpp b/MeshLib/Elements/FaceRule.cpp index 5a56c3902df69c26751177e38a21eb021ff69542..7471c4a3457d72bef27414281a3447601ca4290b 100644 --- a/MeshLib/Elements/FaceRule.cpp +++ b/MeshLib/Elements/FaceRule.cpp @@ -10,9 +10,9 @@ #include "FaceRule.h" +#include "Element.h" #include "MathLib/MathTools.h" #include "MeshLib/Node.h" -#include "Element.h" namespace MeshLib { diff --git a/MeshLib/Elements/HexRule20.cpp b/MeshLib/Elements/HexRule20.cpp index 71bbd5625921374e1c4c3a00d12a554581edf260..0f815d33779e6acb2aca1c81296f433e6ba144f8 100644 --- a/MeshLib/Elements/HexRule20.cpp +++ b/MeshLib/Elements/HexRule20.cpp @@ -13,12 +13,12 @@ #include <array> #include "BaseLib/Logging.h" - +#include "Line.h" #include "MeshLib/Node.h" #include "Quad.h" -#include "Line.h" -namespace MeshLib { +namespace MeshLib +{ const unsigned HexRule20::face_nodes[6][8] = { {0, 3, 2, 1, 11, 10, 9, 8}, // Face 0 {0, 1, 5, 4, 8, 17, 12, 16}, // Face 1 @@ -28,20 +28,19 @@ const unsigned HexRule20::face_nodes[6][8] = { {4, 5, 6, 7, 12, 13, 14, 15} // Face 5 }; -const unsigned HexRule20::edge_nodes[12][3] = -{ - {0, 1, 8}, // Edge 0 - {1, 2, 9}, // Edge 1 - {2, 3, 10}, // Edge 2 - {0, 3, 11}, // Edge 3 - {4, 5, 12}, // Edge 4 - {5, 6, 13}, // Edge 5 - {6, 7, 14}, // Edge 6 - {4, 7, 15}, // Edge 7 - {0, 4, 16}, // Edge 8 - {1, 5, 17}, // Edge 9 - {2, 6, 18}, // Edge 10 - {3, 7, 19} // Edge 11 +const unsigned HexRule20::edge_nodes[12][3] = { + {0, 1, 8}, // Edge 0 + {1, 2, 9}, // Edge 1 + {2, 3, 10}, // Edge 2 + {0, 3, 11}, // Edge 3 + {4, 5, 12}, // Edge 4 + {5, 6, 13}, // Edge 5 + {6, 7, 14}, // Edge 6 + {4, 7, 15}, // Edge 7 + {0, 4, 16}, // Edge 8 + {1, 5, 17}, // Edge 9 + {2, 6, 18}, // Edge 10 + {3, 7, 19} // Edge 11 }; const Element* HexRule20::getFace(const Element* e, unsigned i) @@ -59,4 +58,4 @@ const Element* HexRule20::getFace(const Element* e, unsigned i) return nullptr; } -} // end namespace MeshLib +} // end namespace MeshLib diff --git a/MeshLib/Elements/HexRule8.cpp b/MeshLib/Elements/HexRule8.cpp index 63bb68b7dbaca8ae56288ad515f3a8cdf4f0df95..394bcabeca1a929bf3ba51d13fcc823ed31d203e 100644 --- a/MeshLib/Elements/HexRule8.cpp +++ b/MeshLib/Elements/HexRule8.cpp @@ -13,39 +13,35 @@ #include <array> #include "BaseLib/Logging.h" - +#include "Line.h" #include "MathLib/GeometricBasics.h" - #include "MeshLib/Node.h" #include "Quad.h" -#include "Line.h" - -namespace MeshLib { -const unsigned HexRule8::face_nodes[6][4] = +namespace MeshLib { - {0, 3, 2, 1}, // Face 0 - {0, 1, 5, 4}, // Face 1 - {1, 2, 6, 5}, // Face 2 - {2, 3, 7, 6}, // Face 3 - {3, 0, 4, 7}, // Face 4 - {4, 5, 6, 7} // Face 5 +const unsigned HexRule8::face_nodes[6][4] = { + {0, 3, 2, 1}, // Face 0 + {0, 1, 5, 4}, // Face 1 + {1, 2, 6, 5}, // Face 2 + {2, 3, 7, 6}, // Face 3 + {3, 0, 4, 7}, // Face 4 + {4, 5, 6, 7} // Face 5 }; -const unsigned HexRule8::edge_nodes[12][2] = -{ - {0, 1}, // Edge 0 - {1, 2}, // Edge 1 - {2, 3}, // Edge 2 - {0, 3}, // Edge 3 - {4, 5}, // Edge 4 - {5, 6}, // Edge 5 - {6, 7}, // Edge 6 - {4, 7}, // Edge 7 - {0, 4}, // Edge 8 - {1, 5}, // Edge 9 - {2, 6}, // Edge 10 - {3, 7} // Edge 11 +const unsigned HexRule8::edge_nodes[12][2] = { + {0, 1}, // Edge 0 + {1, 2}, // Edge 1 + {2, 3}, // Edge 2 + {0, 3}, // Edge 3 + {4, 5}, // Edge 4 + {5, 6}, // Edge 5 + {6, 7}, // Edge 6 + {4, 7}, // Edge 7 + {0, 4}, // Edge 8 + {1, 5}, // Edge 9 + {2, 6}, // Edge 10 + {3, 7} // Edge 11 }; const Element* HexRule8::getFace(const Element* e, unsigned i) @@ -65,12 +61,18 @@ const Element* HexRule8::getFace(const Element* e, unsigned i) double HexRule8::computeVolume(Node const* const* _nodes) { - return MathLib::calcTetrahedronVolume(*_nodes[4], *_nodes[7], *_nodes[5], *_nodes[0]) - + MathLib::calcTetrahedronVolume(*_nodes[5], *_nodes[3], *_nodes[1], *_nodes[0]) - + MathLib::calcTetrahedronVolume(*_nodes[5], *_nodes[7], *_nodes[3], *_nodes[0]) - + MathLib::calcTetrahedronVolume(*_nodes[5], *_nodes[7], *_nodes[6], *_nodes[2]) - + MathLib::calcTetrahedronVolume(*_nodes[1], *_nodes[3], *_nodes[5], *_nodes[2]) - + MathLib::calcTetrahedronVolume(*_nodes[3], *_nodes[7], *_nodes[5], *_nodes[2]); + return MathLib::calcTetrahedronVolume( + *_nodes[4], *_nodes[7], *_nodes[5], *_nodes[0]) + + MathLib::calcTetrahedronVolume( + *_nodes[5], *_nodes[3], *_nodes[1], *_nodes[0]) + + MathLib::calcTetrahedronVolume( + *_nodes[5], *_nodes[7], *_nodes[3], *_nodes[0]) + + MathLib::calcTetrahedronVolume( + *_nodes[5], *_nodes[7], *_nodes[6], *_nodes[2]) + + MathLib::calcTetrahedronVolume( + *_nodes[1], *_nodes[3], *_nodes[5], *_nodes[2]) + + MathLib::calcTetrahedronVolume( + *_nodes[3], *_nodes[7], *_nodes[5], *_nodes[2]); } bool HexRule8::isPntInElement(Node const* const* nodes, @@ -93,7 +95,7 @@ bool HexRule8::isPntInElement(Node const* const* nodes, unsigned HexRule8::identifyFace(Node const* const* _nodes, Node* nodes[3]) { - for (unsigned i=0; i<6; i++) + for (unsigned i = 0; i < 6; i++) { unsigned flag(0); for (unsigned j = 0; j < 4; j++) @@ -119,19 +121,19 @@ ElementErrorCode HexRule8::validate(const Element* e) ElementErrorCode error_code; error_code[ElementErrorFlag::ZeroVolume] = hasZeroVolume(*e); - for (unsigned i=0; i<6; ++i) + for (unsigned i = 0; i < 6; ++i) { if (error_code.all()) { break; } - const MeshLib::Element* quad (e->getFace(i)); + const MeshLib::Element* quad(e->getFace(i)); error_code |= quad->validate(); delete quad; } - error_code[ElementErrorFlag::NodeOrder] = !e->testElementNodeOrder(); + error_code[ElementErrorFlag::NodeOrder] = !e->testElementNodeOrder(); return error_code; } -} // end namespace MeshLib +} // end namespace MeshLib diff --git a/MeshLib/Elements/LineRule2.cpp b/MeshLib/Elements/LineRule2.cpp index 6f3fa78e2e09dd0916c450237907ffff37e5ad55..5fc4ad6588a762e16bbb9b0a2be6de80e6330036 100644 --- a/MeshLib/Elements/LineRule2.cpp +++ b/MeshLib/Elements/LineRule2.cpp @@ -13,11 +13,10 @@ #include "MathLib/MathTools.h" #include "MeshLib/Node.h" -namespace MeshLib { - -const unsigned LineRule2::edge_nodes[1][2] = +namespace MeshLib { - {0, 1} // Edge 0 +const unsigned LineRule2::edge_nodes[1][2] = { + {0, 1} // Edge 0 }; double LineRule2::computeVolume(Node const* const* _nodes) @@ -55,4 +54,4 @@ ElementErrorCode LineRule2::validate(const Element* e) return error_code; } -} // end namespace MeshLib +} // end namespace MeshLib diff --git a/MeshLib/Elements/MapBulkElementPoint.cpp b/MeshLib/Elements/MapBulkElementPoint.cpp index a3cfcc73d9c0b8d8ed786dee6cc05a183f5ca72d..d2039ee084fb86c1355c4d72aca10b8d10d6fc09 100644 --- a/MeshLib/Elements/MapBulkElementPoint.cpp +++ b/MeshLib/Elements/MapBulkElementPoint.cpp @@ -8,10 +8,10 @@ * */ -#include <array> - #include "MapBulkElementPoint.h" +#include <array> + namespace MeshLib { MathLib::Point3d getBulkElementPoint(MeshLib::Tri const& /*tri*/, @@ -37,17 +37,20 @@ MathLib::Point3d getBulkElementPoint(MeshLib::Quad const& /*quad*/, std::size_t const face_id, MathLib::WeightedPoint1D const& wp) { - switch (face_id) { - case 0: - return MathLib::Point3d{std::array<double, 3>{{wp[0], 0.0, 0.0}}}; - case 1: - return MathLib::Point3d{std::array<double, 3>{{1.0, wp[0], 0.0}}}; - case 2: - return MathLib::Point3d{std::array<double, 3>{{1.0 - wp[0], 1.0, 0.0}}}; - case 3: - return MathLib::Point3d{std::array<double, 3>{{0.0, 1.0 - wp[0], 0.0}}}; - default: - OGS_FATAL("Invalid face id '{:d}' for the quad.", face_id); + switch (face_id) + { + case 0: + return MathLib::Point3d{std::array<double, 3>{{wp[0], 0.0, 0.0}}}; + case 1: + return MathLib::Point3d{std::array<double, 3>{{1.0, wp[0], 0.0}}}; + case 2: + return MathLib::Point3d{ + std::array<double, 3>{{1.0 - wp[0], 1.0, 0.0}}}; + case 3: + return MathLib::Point3d{ + std::array<double, 3>{{0.0, 1.0 - wp[0], 0.0}}}; + default: + OGS_FATAL("Invalid face id '{:d}' for the quad.", face_id); } } @@ -89,16 +92,15 @@ MathLib::Point3d getBulkElementPoint(MeshLib::Prism const& /*prism*/, std::array<double, 3>{{wp[1], wp[0], -1.0}}}; case 1: return MathLib::Point3d{ - std::array<double, 3>{{wp[0]/2.0 + 0.5, 0.0, wp[1]}}}; + std::array<double, 3>{{wp[0] / 2.0 + 0.5, 0.0, wp[1]}}}; case 2: - return MathLib::Point3d{ - std::array<double, 3>{{0.5 - wp[0]/2.0, 0.5 + wp[0]/2.0, wp[1]}}}; + return MathLib::Point3d{std::array<double, 3>{ + {0.5 - wp[0] / 2.0, 0.5 + wp[0] / 2.0, wp[1]}}}; case 3: return MathLib::Point3d{ - std::array<double, 3>{{0, -wp[0]/2.0 + 0.5, wp[1]}}}; + std::array<double, 3>{{0, -wp[0] / 2.0 + 0.5, wp[1]}}}; case 4: - return MathLib::Point3d{ - std::array<double, 3>{{wp[0], wp[1], 1.0}}}; + return MathLib::Point3d{std::array<double, 3>{{wp[0], wp[1], 1.0}}}; default: OGS_FATAL("Invalid face id '{:d}' for the prism.", face_id); } @@ -120,8 +122,8 @@ MathLib::Point3d getBulkElementPoint(MeshLib::Pyramid const& /*pyramid*/, return MathLib::Point3d{ std::array<double, 3>{{1 - 2 * wp[0], 1.0, 2 * wp[1] - 1}}}; case 3: - return MathLib::Point3d{std::array<double, 3>{ - {-1.0, 2 * wp[1] - 1, 2 * wp[0] - 1}}}; + return MathLib::Point3d{ + std::array<double, 3>{{-1.0, 2 * wp[1] - 1, 2 * wp[0] - 1}}}; case 4: return MathLib::Point3d{ std::array<double, 3>{{-wp[0], wp[1], -1.0}}}; @@ -144,8 +146,7 @@ MathLib::Point3d getBulkElementPoint(MeshLib::Tet const& /*tet*/, return MathLib::Point3d{ std::array<double, 3>{{1 - wp[0] - wp[1], wp[0], wp[1]}}}; case 3: - return MathLib::Point3d{ - std::array<double, 3>{{0, wp[1], wp[0]}}}; + return MathLib::Point3d{std::array<double, 3>{{0, wp[1], wp[0]}}}; default: OGS_FATAL("Invalid face id '{:d}' for the tetrahedron.", face_id); } diff --git a/MeshLib/Elements/PointRule1.cpp b/MeshLib/Elements/PointRule1.cpp index dd13cf1adb5b15695a21b227a21dc7862a4928be..e812fb9372578117147ee8841b5ed986299b9e90 100644 --- a/MeshLib/Elements/PointRule1.cpp +++ b/MeshLib/Elements/PointRule1.cpp @@ -13,12 +13,9 @@ #include "MathLib/Point3d.h" #include "MeshLib/Node.h" -namespace MeshLib { - -const unsigned PointRule1::edge_nodes[1][1] = +namespace MeshLib { - {0} -}; +const unsigned PointRule1::edge_nodes[1][1] = {{0}}; double PointRule1::computeVolume(Node const* const* /*_nodes*/) { @@ -48,4 +45,4 @@ ElementErrorCode PointRule1::validate(const Element* e) return error_code; } -} // end namespace MeshLib +} // end namespace MeshLib diff --git a/MeshLib/Elements/PrismRule15.cpp b/MeshLib/Elements/PrismRule15.cpp index 6ecd50b88045f8576b1698dbf5c037b008f04180..7d1d6c37bb1ccfdb582d0bde54e323ab5ddf5479 100644 --- a/MeshLib/Elements/PrismRule15.cpp +++ b/MeshLib/Elements/PrismRule15.cpp @@ -11,36 +11,33 @@ #include "PrismRule15.h" #include "BaseLib/Logging.h" - #include "MeshLib/Node.h" #include "Quad.h" #include "Tri.h" -namespace MeshLib { - -const unsigned PrismRule15::face_nodes[5][8] = +namespace MeshLib { - {0, 2, 1, 8, 7, 6, 99, 99}, // Face 0 - {0, 1, 4, 3, 6, 10, 12, 9}, // Face 1 - {1, 2, 5, 4, 7, 11, 13, 10}, // Face 2 - {2, 0, 3, 5, 8, 9, 14, 11}, // Face 3 +const unsigned PrismRule15::face_nodes[5][8] = { + {0, 2, 1, 8, 7, 6, 99, 99}, // Face 0 + {0, 1, 4, 3, 6, 10, 12, 9}, // Face 1 + {1, 2, 5, 4, 7, 11, 13, 10}, // Face 2 + {2, 0, 3, 5, 8, 9, 14, 11}, // Face 3 {3, 4, 5, 12, 13, 14, 99, 99} // Face 4 }; -const unsigned PrismRule15::edge_nodes[9][3] = -{ - {0, 1, 6}, // Edge 0 - {1, 2, 7}, // Edge 1 - {0, 2, 8}, // Edge 2 - {0, 3, 9}, // Edge 3 - {1, 4, 10}, // Edge 4 - {2, 5, 11}, // Edge 5 - {3, 4, 12}, // Edge 6 - {4, 5, 13}, // Edge 7 - {3, 5, 14} // Edge 8 +const unsigned PrismRule15::edge_nodes[9][3] = { + {0, 1, 6}, // Edge 0 + {1, 2, 7}, // Edge 1 + {0, 2, 8}, // Edge 2 + {0, 3, 9}, // Edge 3 + {1, 4, 10}, // Edge 4 + {2, 5, 11}, // Edge 5 + {3, 4, 12}, // Edge 6 + {4, 5, 13}, // Edge 7 + {3, 5, 14} // Edge 8 }; -const unsigned PrismRule15::n_face_nodes[5] = { 6, 8, 8, 8, 6 }; +const unsigned PrismRule15::n_face_nodes[5] = {6, 8, 8, 8, 6}; const Element* PrismRule15::getFace(const Element* e, unsigned i) { @@ -64,4 +61,4 @@ const Element* PrismRule15::getFace(const Element* e, unsigned i) return nullptr; } -} // end namespace MeshLib +} // end namespace MeshLib diff --git a/MeshLib/Elements/PrismRule6.cpp b/MeshLib/Elements/PrismRule6.cpp index b46fef3ff361983c31ae3b2338accad9b4eb172e..5bc0de116276cb5913e1012b263637efcf5f0747 100644 --- a/MeshLib/Elements/PrismRule6.cpp +++ b/MeshLib/Elements/PrismRule6.cpp @@ -11,38 +11,34 @@ #include "PrismRule6.h" #include "BaseLib/Logging.h" - #include "MathLib/GeometricBasics.h" - #include "MeshLib/Node.h" #include "Quad.h" #include "Tri.h" -namespace MeshLib { - -const unsigned PrismRule6::face_nodes[5][4] = +namespace MeshLib { - {0, 2, 1, 99}, // Face 0 - {0, 1, 4, 3}, // Face 1 - {1, 2, 5, 4}, // Face 2 - {2, 0, 3, 5}, // Face 3 - {3, 4, 5, 99} // Face 4 +const unsigned PrismRule6::face_nodes[5][4] = { + {0, 2, 1, 99}, // Face 0 + {0, 1, 4, 3}, // Face 1 + {1, 2, 5, 4}, // Face 2 + {2, 0, 3, 5}, // Face 3 + {3, 4, 5, 99} // Face 4 }; -const unsigned PrismRule6::edge_nodes[9][2] = -{ - {0, 1}, // Edge 0 - {1, 2}, // Edge 1 - {0, 2}, // Edge 2 - {0, 3}, // Edge 3 - {1, 4}, // Edge 4 - {2, 5}, // Edge 5 - {3, 4}, // Edge 6 - {4, 5}, // Edge 7 - {3, 5} // Edge 8 +const unsigned PrismRule6::edge_nodes[9][2] = { + {0, 1}, // Edge 0 + {1, 2}, // Edge 1 + {0, 2}, // Edge 2 + {0, 3}, // Edge 3 + {1, 4}, // Edge 4 + {2, 5}, // Edge 5 + {3, 4}, // Edge 6 + {4, 5}, // Edge 7 + {3, 5} // Edge 8 }; -const unsigned PrismRule6::n_face_nodes[5] = { 3, 4, 4, 4, 3 }; +const unsigned PrismRule6::n_face_nodes[5] = {3, 4, 4, 4, 3}; const Element* PrismRule6::getFace(const Element* e, unsigned i) { @@ -68,9 +64,12 @@ const Element* PrismRule6::getFace(const Element* e, unsigned i) double PrismRule6::computeVolume(Node const* const* _nodes) { - return MathLib::calcTetrahedronVolume(*_nodes[0], *_nodes[1], *_nodes[2], *_nodes[3]) - + MathLib::calcTetrahedronVolume(*_nodes[1], *_nodes[4], *_nodes[2], *_nodes[3]) - + MathLib::calcTetrahedronVolume(*_nodes[2], *_nodes[4], *_nodes[5], *_nodes[3]); + return MathLib::calcTetrahedronVolume( + *_nodes[0], *_nodes[1], *_nodes[2], *_nodes[3]) + + MathLib::calcTetrahedronVolume( + *_nodes[1], *_nodes[4], *_nodes[2], *_nodes[3]) + + MathLib::calcTetrahedronVolume( + *_nodes[2], *_nodes[4], *_nodes[5], *_nodes[3]); } bool PrismRule6::isPntInElement(Node const* const* nodes, @@ -87,7 +86,7 @@ bool PrismRule6::isPntInElement(Node const* const* nodes, unsigned PrismRule6::identifyFace(Node const* const* _nodes, Node* nodes[3]) { - for (unsigned i=0; i<5; i++) + for (unsigned i = 0; i < 5; i++) { unsigned flag(0); for (unsigned j = 0; j < 4; j++) @@ -114,7 +113,7 @@ ElementErrorCode PrismRule6::validate(const Element* e) ElementErrorCode error_code; error_code[ElementErrorFlag::ZeroVolume] = hasZeroVolume(*e); - for (unsigned i=1; i<4; ++i) + for (unsigned i = 1; i < 4; ++i) { const auto* quad(dynamic_cast<const MeshLib::Quad*>(e->getFace(i))); if (quad) @@ -131,4 +130,4 @@ ElementErrorCode PrismRule6::validate(const Element* e) return error_code; } -} // end namespace MeshLib +} // end namespace MeshLib diff --git a/MeshLib/Elements/PyramidRule13.cpp b/MeshLib/Elements/PyramidRule13.cpp index 02ecd73baa9e3c8f0f0da22d3640dac12978b3fc..9d76fac3e951fe2d2a7c6780c5e77bdb2f0d4d36 100644 --- a/MeshLib/Elements/PyramidRule13.cpp +++ b/MeshLib/Elements/PyramidRule13.cpp @@ -11,39 +11,36 @@ #include "PyramidRule13.h" #include "BaseLib/Logging.h" - #include "MeshLib/Node.h" #include "Quad.h" #include "Tri.h" -namespace MeshLib { - -const unsigned PyramidRule13::face_nodes[5][8] = +namespace MeshLib { - {0, 1, 4, 5, 10, 9, 99, 99}, // Face 0 - {1, 2, 4, 6, 11, 10, 99, 99}, // Face 1 - {2, 3, 4, 7, 12, 11, 99, 99}, // Face 2 - {3, 0, 4, 8, 9, 12, 99, 99}, // Face 3 - {0, 3, 2, 1, 8, 7, 6, 5} // Face 4 +const unsigned PyramidRule13::face_nodes[5][8] = { + {0, 1, 4, 5, 10, 9, 99, 99}, // Face 0 + {1, 2, 4, 6, 11, 10, 99, 99}, // Face 1 + {2, 3, 4, 7, 12, 11, 99, 99}, // Face 2 + {3, 0, 4, 8, 9, 12, 99, 99}, // Face 3 + {0, 3, 2, 1, 8, 7, 6, 5} // Face 4 }; -const unsigned PyramidRule13::edge_nodes[8][3] = -{ - {0, 1, 5}, // Edge 0 - {1, 2, 6}, // Edge 1 - {2, 3, 7}, // Edge 2 - {0, 3, 8}, // Edge 3 - {0, 4, 9}, // Edge 4 - {1, 4, 10}, // Edge 5 - {2, 4, 11}, // Edge 6 - {3, 4, 12} // Edge 7 +const unsigned PyramidRule13::edge_nodes[8][3] = { + {0, 1, 5}, // Edge 0 + {1, 2, 6}, // Edge 1 + {2, 3, 7}, // Edge 2 + {0, 3, 8}, // Edge 3 + {0, 4, 9}, // Edge 4 + {1, 4, 10}, // Edge 5 + {2, 4, 11}, // Edge 6 + {3, 4, 12} // Edge 7 }; -const unsigned PyramidRule13::n_face_nodes[5] = { 6, 6, 6, 6, 8 }; +const unsigned PyramidRule13::n_face_nodes[5] = {6, 6, 6, 6, 8}; const Element* PyramidRule13::getFace(const Element* e, unsigned i) { - if (i<e->getNumberOfFaces()) + if (i < e->getNumberOfFaces()) { unsigned nFaceNodes(PyramidRule13::n_face_nodes[i]); auto** nodes = new Node*[nFaceNodes]; @@ -63,4 +60,4 @@ const Element* PyramidRule13::getFace(const Element* e, unsigned i) return nullptr; } -} // end namespace MeshLib +} // end namespace MeshLib diff --git a/MeshLib/Elements/PyramidRule5.cpp b/MeshLib/Elements/PyramidRule5.cpp index dbc56555705955337d5d14dffe90690b7d1a6dfc..7b6486da71bf606014816c26fa9e2a7639d3cec9 100644 --- a/MeshLib/Elements/PyramidRule5.cpp +++ b/MeshLib/Elements/PyramidRule5.cpp @@ -11,41 +11,37 @@ #include "PyramidRule5.h" #include "BaseLib/Logging.h" - #include "MathLib/GeometricBasics.h" - #include "MeshLib/Node.h" #include "Quad.h" #include "Tri.h" -namespace MeshLib { - -const unsigned PyramidRule5::face_nodes[5][4] = +namespace MeshLib { - {0, 1, 4, 99}, // Face 0 - {1, 2, 4, 99}, // Face 1 - {2, 3, 4, 99}, // Face 2 - {3, 0, 4, 99}, // Face 3 - {0, 3, 2, 1} // Face 4 +const unsigned PyramidRule5::face_nodes[5][4] = { + {0, 1, 4, 99}, // Face 0 + {1, 2, 4, 99}, // Face 1 + {2, 3, 4, 99}, // Face 2 + {3, 0, 4, 99}, // Face 3 + {0, 3, 2, 1} // Face 4 }; -const unsigned PyramidRule5::edge_nodes[8][2] = -{ - {0, 1}, // Edge 0 - {1, 2}, // Edge 1 - {2, 3}, // Edge 2 - {0, 3}, // Edge 3 - {0, 4}, // Edge 4 - {1, 4}, // Edge 5 - {2, 4}, // Edge 6 - {3, 4} // Edge 7 +const unsigned PyramidRule5::edge_nodes[8][2] = { + {0, 1}, // Edge 0 + {1, 2}, // Edge 1 + {2, 3}, // Edge 2 + {0, 3}, // Edge 3 + {0, 4}, // Edge 4 + {1, 4}, // Edge 5 + {2, 4}, // Edge 6 + {3, 4} // Edge 7 }; -const unsigned PyramidRule5::n_face_nodes[5] = { 3, 3, 3, 3, 4 }; +const unsigned PyramidRule5::n_face_nodes[5] = {3, 3, 3, 3, 4}; const Element* PyramidRule5::getFace(const Element* e, unsigned i) { - if (i<e->getNumberOfFaces()) + if (i < e->getNumberOfFaces()) { unsigned nFaceNodes(PyramidRule5::n_face_nodes[i]); auto** nodes = new Node*[nFaceNodes]; @@ -67,8 +63,10 @@ const Element* PyramidRule5::getFace(const Element* e, unsigned i) double PyramidRule5::computeVolume(Node const* const* _nodes) { - return MathLib::calcTetrahedronVolume(*_nodes[0], *_nodes[1], *_nodes[2], *_nodes[4]) - + MathLib::calcTetrahedronVolume(*_nodes[2], *_nodes[3], *_nodes[0], *_nodes[4]); + return MathLib::calcTetrahedronVolume( + *_nodes[0], *_nodes[1], *_nodes[2], *_nodes[4]) + + MathLib::calcTetrahedronVolume( + *_nodes[2], *_nodes[3], *_nodes[0], *_nodes[4]); } bool PyramidRule5::isPntInElement(Node const* const* nodes, @@ -83,7 +81,7 @@ bool PyramidRule5::isPntInElement(Node const* const* nodes, unsigned PyramidRule5::identifyFace(Node const* const* _nodes, Node* nodes[3]) { - for (unsigned i=0; i<5; i++) + for (unsigned i = 0; i < 5; i++) { unsigned flag(0); for (unsigned j = 0; j < 4; j++) @@ -125,4 +123,4 @@ ElementErrorCode PyramidRule5::validate(const Element* e) return error_code; } -} // end namespace MeshLib +} // end namespace MeshLib diff --git a/MeshLib/Elements/QuadRule4.cpp b/MeshLib/Elements/QuadRule4.cpp index b98b106435871af36293b6a558429c061f267ea6..2dd61e0d3c75714c63cad2f65727692f3430fd2a 100644 --- a/MeshLib/Elements/QuadRule4.cpp +++ b/MeshLib/Elements/QuadRule4.cpp @@ -11,23 +11,21 @@ #include "QuadRule4.h" #include "MathLib/GeometricBasics.h" - #include "MeshLib/Node.h" -namespace MeshLib { - -const unsigned QuadRule4::edge_nodes[4][2] = +namespace MeshLib { - {0, 1}, // Edge 0 - {1, 2}, // Edge 1 - {2, 3}, // Edge 2 - {3, 0} // Edge 3 +const unsigned QuadRule4::edge_nodes[4][2] = { + {0, 1}, // Edge 0 + {1, 2}, // Edge 1 + {2, 3}, // Edge 2 + {3, 0} // Edge 3 }; double QuadRule4::computeVolume(Node const* const* _nodes) { - return MathLib::calcTriangleArea(*_nodes[0], *_nodes[1], *_nodes[2]) - + MathLib::calcTriangleArea(*_nodes[2], *_nodes[3], *_nodes[0]); + return MathLib::calcTriangleArea(*_nodes[0], *_nodes[1], *_nodes[2]) + + MathLib::calcTriangleArea(*_nodes[2], *_nodes[3], *_nodes[0]); } bool QuadRule4::isPntInElement(Node const* const* nodes, @@ -41,7 +39,7 @@ bool QuadRule4::isPntInElement(Node const* const* nodes, unsigned QuadRule4::identifyFace(Node const* const* _nodes, Node* nodes[3]) { - for (unsigned i=0; i<4; i++) + for (unsigned i = 0; i < 4; i++) { unsigned flag(0); for (unsigned j = 0; j < 2; j++) @@ -83,4 +81,4 @@ ElementErrorCode QuadRule4::validate(const Element* e) return error_code; } -} // end namespace MeshLib +} // end namespace MeshLib diff --git a/MeshLib/Elements/QuadRule8.cpp b/MeshLib/Elements/QuadRule8.cpp index 7c4949b8c1c50349bccc9370908cb8317cba93bc..f4c4643bea72252e581a407dbaa0c22c104b3ab1 100644 --- a/MeshLib/Elements/QuadRule8.cpp +++ b/MeshLib/Elements/QuadRule8.cpp @@ -10,14 +10,13 @@ #include "QuadRule8.h" -namespace MeshLib { - -const unsigned QuadRule8::edge_nodes[4][3] = +namespace MeshLib { - {0, 1, 4}, // Edge 0 - {1, 2, 5}, // Edge 1 - {2, 3, 6}, // Edge 2 - {0, 3, 7} // Edge 3 +const unsigned QuadRule8::edge_nodes[4][3] = { + {0, 1, 4}, // Edge 0 + {1, 2, 5}, // Edge 1 + {2, 3, 6}, // Edge 2 + {0, 3, 7} // Edge 3 }; -} // end namespace MeshLib +} // end namespace MeshLib diff --git a/MeshLib/Elements/TemplateElement.cpp b/MeshLib/Elements/TemplateElement.cpp index 5c3237f20b1b9f0118611130df9e679adac996fc..18e766856170b8801e58fc42e783649307ef88cd 100644 --- a/MeshLib/Elements/TemplateElement.cpp +++ b/MeshLib/Elements/TemplateElement.cpp @@ -11,8 +11,8 @@ #include "TemplateElement.h" #include "MeshLib/Elements/Hex.h" -#include "MeshLib/Elements/Point.h" #include "MeshLib/Elements/Line.h" +#include "MeshLib/Elements/Point.h" #include "MeshLib/Elements/Prism.h" #include "MeshLib/Elements/Pyramid.h" #include "MeshLib/Elements/Quad.h" @@ -30,7 +30,7 @@ const unsigned MeshLib::TemplateElement<ELEMENT_RULE>::n_base_nodes; template <class ELEMENT_RULE> const unsigned MeshLib::TemplateElement<ELEMENT_RULE>::dimension; -#endif // WIN32 +#endif // WIN32 template class MeshLib::TemplateElement<MeshLib::HexRule20>; template class MeshLib::TemplateElement<MeshLib::HexRule8>; diff --git a/MeshLib/Elements/TetRule10.cpp b/MeshLib/Elements/TetRule10.cpp index adea61c103f569151c6ab2e03c1e476017c048fc..103929d820ca1857fd6fbb0599b53820afb4800b 100644 --- a/MeshLib/Elements/TetRule10.cpp +++ b/MeshLib/Elements/TetRule10.cpp @@ -13,36 +13,32 @@ #include <array> #include "BaseLib/Logging.h" - #include "MeshLib/Node.h" #include "Tri.h" namespace MeshLib { - -const unsigned TetRule10::face_nodes[4][6] = -{ - {0, 2, 1, 6, 5, 4}, // Face 0 - {0, 1, 3, 4, 8, 7}, // Face 1 - {1, 2, 3, 5, 9, 8}, // Face 2 - {2, 0, 3, 6, 7, 9} // Face 3 +const unsigned TetRule10::face_nodes[4][6] = { + {0, 2, 1, 6, 5, 4}, // Face 0 + {0, 1, 3, 4, 8, 7}, // Face 1 + {1, 2, 3, 5, 9, 8}, // Face 2 + {2, 0, 3, 6, 7, 9} // Face 3 }; -const unsigned TetRule10::edge_nodes[6][3] = -{ - {0, 1, 4}, // Edge 0 - {1, 2, 5}, // Edge 1 - {0, 2, 6}, // Edge 2 - {0, 3, 7}, // Edge 3 - {1, 3, 8}, // Edge 4 - {2, 3, 9} // Edge 5 +const unsigned TetRule10::edge_nodes[6][3] = { + {0, 1, 4}, // Edge 0 + {1, 2, 5}, // Edge 1 + {0, 2, 6}, // Edge 2 + {0, 3, 7}, // Edge 3 + {1, 3, 8}, // Edge 4 + {2, 3, 9} // Edge 5 }; const Element* TetRule10::getFace(const Element* e, unsigned i) { - if (i<n_faces) + if (i < n_faces) { - std::array<Node*,6> nodes{}; + std::array<Node*, 6> nodes{}; for (unsigned j = 0; j < 6; j++) { nodes[j] = const_cast<Node*>(e->getNode(face_nodes[i][j])); @@ -53,4 +49,4 @@ const Element* TetRule10::getFace(const Element* e, unsigned i) return nullptr; } -} // end namespace MeshLib +} // end namespace MeshLib diff --git a/MeshLib/Elements/TetRule4.cpp b/MeshLib/Elements/TetRule4.cpp index 769a26bf72b7cddb862af261904b6e345e6b8901..f43a17ff3859bf24ae6198fc1a65a8f4f3e952dc 100644 --- a/MeshLib/Elements/TetRule4.cpp +++ b/MeshLib/Elements/TetRule4.cpp @@ -13,38 +13,34 @@ #include <array> #include "BaseLib/Logging.h" - +#include "Line.h" #include "MathLib/GeometricBasics.h" - #include "MeshLib/Node.h" #include "Tri.h" -#include "Line.h" - -namespace MeshLib { -const unsigned TetRule4::face_nodes[4][3] = +namespace MeshLib { - {0, 2, 1}, // Face 0 - {0, 1, 3}, // Face 1 - {1, 2, 3}, // Face 2 - {2, 0, 3} // Face 3 +const unsigned TetRule4::face_nodes[4][3] = { + {0, 2, 1}, // Face 0 + {0, 1, 3}, // Face 1 + {1, 2, 3}, // Face 2 + {2, 0, 3} // Face 3 }; -const unsigned TetRule4::edge_nodes[6][2] = -{ - {0, 1}, // Edge 0 - {1, 2}, // Edge 1 - {0, 2}, // Edge 2 - {0, 3}, // Edge 3 - {1, 3}, // Edge 4 - {2, 3} // Edge 5 +const unsigned TetRule4::edge_nodes[6][2] = { + {0, 1}, // Edge 0 + {1, 2}, // Edge 1 + {0, 2}, // Edge 2 + {0, 3}, // Edge 3 + {1, 3}, // Edge 4 + {2, 3} // Edge 5 }; const Element* TetRule4::getFace(const Element* e, unsigned i) { - if (i<n_faces) + if (i < n_faces) { - std::array<Node*,3> nodes{}; + std::array<Node*, 3> nodes{}; for (unsigned j = 0; j < 3; j++) { nodes[j] = const_cast<Node*>(e->getNode(face_nodes[i][j])); @@ -57,7 +53,8 @@ const Element* TetRule4::getFace(const Element* e, unsigned i) double TetRule4::computeVolume(Node const* const* _nodes) { - return MathLib::calcTetrahedronVolume(*_nodes[0], *_nodes[1], *_nodes[2], *_nodes[3]); + return MathLib::calcTetrahedronVolume(*_nodes[0], *_nodes[1], *_nodes[2], + *_nodes[3]); } bool TetRule4::isPntInElement(Node const* const* nodes, @@ -69,7 +66,7 @@ bool TetRule4::isPntInElement(Node const* const* nodes, unsigned TetRule4::identifyFace(Node const* const* _nodes, Node* nodes[3]) { - for (unsigned i=0; i<4; i++) + for (unsigned i = 0; i < 4; i++) { unsigned flag(0); for (unsigned j = 0; j < 3; j++) @@ -94,8 +91,8 @@ ElementErrorCode TetRule4::validate(const Element* e) { ElementErrorCode error_code; error_code[ElementErrorFlag::ZeroVolume] = hasZeroVolume(*e); - error_code[ElementErrorFlag::NodeOrder] = !e->testElementNodeOrder(); + error_code[ElementErrorFlag::NodeOrder] = !e->testElementNodeOrder(); return error_code; } -} // end namespace MeshLib +} // end namespace MeshLib diff --git a/MeshLib/Elements/TriRule3.cpp b/MeshLib/Elements/TriRule3.cpp index 0d363301128f262011c7f7770f67f416cfab86ec..a7fb1c9814f94946214b8131e969eff1e48e8651 100644 --- a/MeshLib/Elements/TriRule3.cpp +++ b/MeshLib/Elements/TriRule3.cpp @@ -11,16 +11,14 @@ #include "TriRule3.h" #include "MathLib/GeometricBasics.h" - #include "MeshLib/Node.h" -namespace MeshLib { - -const unsigned TriRule3::edge_nodes[3][2] = +namespace MeshLib { - {0, 1}, // Edge 0 - {1, 2}, // Edge 1 - {2, 0}, // Edge 2 +const unsigned TriRule3::edge_nodes[3][2] = { + {0, 1}, // Edge 0 + {1, 2}, // Edge 1 + {2, 0}, // Edge 2 }; double TriRule3::computeVolume(Node const* const* _nodes) @@ -37,7 +35,7 @@ bool TriRule3::isPntInElement(Node const* const* nodes, unsigned TriRule3::identifyFace(Node const* const* _nodes, Node* nodes[3]) { - for (unsigned i=0; i<3; i++) + for (unsigned i = 0; i < 3; i++) { unsigned flag(0); for (unsigned j = 0; j < 2; j++) @@ -62,8 +60,8 @@ ElementErrorCode TriRule3::validate(const Element* e) { ElementErrorCode error_code; error_code[ElementErrorFlag::ZeroVolume] = hasZeroVolume(*e); - error_code[ElementErrorFlag::NodeOrder] = !e->testElementNodeOrder(); + error_code[ElementErrorFlag::NodeOrder] = !e->testElementNodeOrder(); return error_code; } -} // end namespace MeshLib +} // end namespace MeshLib diff --git a/MeshLib/Elements/TriRule6.cpp b/MeshLib/Elements/TriRule6.cpp index da31e180f20cdab609ca1f3358725efa5226d070..8c0f1bcd5f4f62eaf05e112d6c8811114e958456 100644 --- a/MeshLib/Elements/TriRule6.cpp +++ b/MeshLib/Elements/TriRule6.cpp @@ -10,13 +10,12 @@ #include "TriRule6.h" -namespace MeshLib { - -const unsigned TriRule6::edge_nodes[3][3] = +namespace MeshLib { - {0, 1, 3}, // Edge 0 - {1, 2, 4}, // Edge 1 - {2, 0, 5}, // Edge 2 +const unsigned TriRule6::edge_nodes[3][3] = { + {0, 1, 3}, // Edge 0 + {1, 2, 4}, // Edge 1 + {2, 0, 5}, // Edge 2 }; -} // end namespace MeshLib +} // end namespace MeshLib diff --git a/MeshLib/IO/Legacy/MeshIO.cpp b/MeshLib/IO/Legacy/MeshIO.cpp index d42080c38ce5f2f0de7c5e2a8e062d96a1ace253..c0b77823e960abae9407c0fca1d5be9965b1be69 100644 --- a/MeshLib/IO/Legacy/MeshIO.cpp +++ b/MeshLib/IO/Legacy/MeshIO.cpp @@ -22,11 +22,9 @@ #include <memory> #include <sstream> -#include "BaseLib/Logging.h" - #include "BaseLib/FileTools.h" +#include "BaseLib/Logging.h" #include "BaseLib/StringTools.h" - #include "MeshLib/Elements/Elements.h" #include "MeshLib/Location.h" #include "MeshLib/Node.h" @@ -36,14 +34,15 @@ namespace MeshLib { namespace IO { -namespace Legacy { +namespace Legacy +{ MeshIO::MeshIO() = default; MeshLib::Mesh* MeshIO::loadMeshFromFile(const std::string& file_name) { INFO("Reading OGS legacy mesh ... "); - std::ifstream in (file_name.c_str(),std::ios::in); + std::ifstream in(file_name.c_str(), std::ios::in); if (!in.is_open()) { WARN("MeshIO::loadMeshFromFile() - Could not open file {:s}.", @@ -58,7 +57,7 @@ MeshLib::Mesh* MeshIO::loadMeshFromFile(const std::string& file_name) std::vector<MeshLib::Element*> elements; std::vector<std::size_t> materials; - if(line_string.find("#FEM_MSH") != std::string::npos) // OGS mesh file + if (line_string.find("#FEM_MSH") != std::string::npos) // OGS mesh file { while (!in.eof()) { @@ -104,17 +103,18 @@ MeshLib::Mesh* MeshIO::loadMeshFromFile(const std::string& file_name) getline(in, line_string); std::stringstream ss(line_string); materials.push_back(readMaterialID(ss)); - MeshLib::Element *elem(readElement(ss,nodes)); - if (elem == nullptr) { + MeshLib::Element* elem(readElement(ss, nodes)); + if (elem == nullptr) + { ERR("Reading mesh element {:d} from file '{:s}' " "failed.", i, file_name); // clean up the elements vector std::for_each(elements.begin(), elements.end(), - std::default_delete<MeshLib::Element>()); + std::default_delete<MeshLib::Element>()); // clean up the nodes vector std::for_each(nodes.begin(), nodes.end(), - std::default_delete<MeshLib::Node>()); + std::default_delete<MeshLib::Node>()); return nullptr; } elements.push_back(elem); @@ -124,7 +124,8 @@ MeshLib::Mesh* MeshIO::loadMeshFromFile(const std::string& file_name) if (elements.empty()) { - ERR ("MeshIO::loadMeshFromFile() - File did not contain element information."); + ERR("MeshIO::loadMeshFromFile() - File did not contain element " + "information."); for (auto& node : nodes) { delete node; @@ -132,8 +133,9 @@ MeshLib::Mesh* MeshIO::loadMeshFromFile(const std::string& file_name) return nullptr; } - MeshLib::Mesh* mesh (new MeshLib::Mesh(BaseLib::extractBaseNameWithoutExtension( - file_name), nodes, elements)); + MeshLib::Mesh* mesh(new MeshLib::Mesh( + BaseLib::extractBaseNameWithoutExtension(file_name), nodes, + elements)); auto* const material_ids = mesh->getProperties().createNewPropertyVector<int>( @@ -159,7 +161,7 @@ MeshLib::Mesh* MeshIO::loadMeshFromFile(const std::string& file_name) return nullptr; } -std::size_t MeshIO::readMaterialID(std::istream & in) +std::size_t MeshIO::readMaterialID(std::istream& in) { unsigned index; unsigned material_id; @@ -170,13 +172,14 @@ std::size_t MeshIO::readMaterialID(std::istream & in) return material_id; } -MeshLib::Element* MeshIO::readElement(std::istream& in, - const std::vector<MeshLib::Node*> &nodes) const +MeshLib::Element* MeshIO::readElement( + std::istream& in, const std::vector<MeshLib::Node*>& nodes) const { std::string elem_type_str; - MeshLib::MeshElemType elem_type (MeshLib::MeshElemType::INVALID); + MeshLib::MeshElemType elem_type(MeshLib::MeshElemType::INVALID); - do { + do + { if (!(in >> elem_type_str)) { return nullptr; @@ -187,134 +190,142 @@ MeshLib::Element* MeshIO::readElement(std::istream& in, auto* idx = new unsigned[8]; MeshLib::Element* elem; - switch(elem_type) + switch (elem_type) { - case MeshLib::MeshElemType::LINE: { - for (int i = 0; i < 2; ++i) + case MeshLib::MeshElemType::LINE: { - if (!(in >> idx[i])) + for (int i = 0; i < 2; ++i) { - return nullptr; + if (!(in >> idx[i])) + { + return nullptr; + } } - } - // edge_nodes array will be deleted from Line object - auto** edge_nodes = new MeshLib::Node*[2]; - for (unsigned k(0); k < 2; ++k) - { - edge_nodes[k] = nodes[idx[k]]; - } - elem = new MeshLib::Line(edge_nodes); - break; - } - case MeshLib::MeshElemType::TRIANGLE: { - for (int i = 0; i < 3; ++i) - { - if (!(in >> idx[i])) + // edge_nodes array will be deleted from Line object + auto** edge_nodes = new MeshLib::Node*[2]; + for (unsigned k(0); k < 2; ++k) { - return nullptr; + edge_nodes[k] = nodes[idx[k]]; } + elem = new MeshLib::Line(edge_nodes); + break; } - auto** tri_nodes = new MeshLib::Node*[3]; - for (unsigned k(0); k < 3; ++k) - { - tri_nodes[k] = nodes[idx[k]]; - } - elem = new MeshLib::Tri(tri_nodes); - break; - } - case MeshLib::MeshElemType::QUAD: { - for (int i = 0; i < 4; ++i) + case MeshLib::MeshElemType::TRIANGLE: { - if (!(in >> idx[i])) + for (int i = 0; i < 3; ++i) { - return nullptr; + if (!(in >> idx[i])) + { + return nullptr; + } } - } - auto** quad_nodes = new MeshLib::Node*[4]; - for (unsigned k(0); k < 4; ++k) - { - quad_nodes[k] = nodes[idx[k]]; - } - elem = new MeshLib::Quad(quad_nodes); - break; - } - case MeshLib::MeshElemType::TETRAHEDRON: { - for (int i = 0; i < 4; ++i) - { - if (!(in >> idx[i])) + auto** tri_nodes = new MeshLib::Node*[3]; + for (unsigned k(0); k < 3; ++k) { - return nullptr; + tri_nodes[k] = nodes[idx[k]]; } + elem = new MeshLib::Tri(tri_nodes); + break; } - auto** tet_nodes = new MeshLib::Node*[4]; - for (unsigned k(0); k < 4; ++k) - { - tet_nodes[k] = nodes[idx[k]]; - } - elem = new MeshLib::Tet(tet_nodes); - break; - } - case MeshLib::MeshElemType::HEXAHEDRON: { - for (int i = 0; i < 8; ++i) + case MeshLib::MeshElemType::QUAD: { - if (!(in >> idx[i])) + for (int i = 0; i < 4; ++i) { - return nullptr; + if (!(in >> idx[i])) + { + return nullptr; + } } + auto** quad_nodes = new MeshLib::Node*[4]; + for (unsigned k(0); k < 4; ++k) + { + quad_nodes[k] = nodes[idx[k]]; + } + elem = new MeshLib::Quad(quad_nodes); + break; } - auto** hex_nodes = new MeshLib::Node*[8]; - for (unsigned k(0); k < 8; ++k) - { - hex_nodes[k] = nodes[idx[k]]; - } - elem = new MeshLib::Hex(hex_nodes); - break; - } - case MeshLib::MeshElemType::PYRAMID: { - for (int i = 0; i < 5; ++i) + case MeshLib::MeshElemType::TETRAHEDRON: { - if (!(in >> idx[i])) + for (int i = 0; i < 4; ++i) + { + if (!(in >> idx[i])) + { + return nullptr; + } + } + auto** tet_nodes = new MeshLib::Node*[4]; + for (unsigned k(0); k < 4; ++k) { - return nullptr; + tet_nodes[k] = nodes[idx[k]]; } + elem = new MeshLib::Tet(tet_nodes); + break; } - auto** pyramid_nodes = new MeshLib::Node*[5]; - for (unsigned k(0); k < 5; ++k) + case MeshLib::MeshElemType::HEXAHEDRON: { - pyramid_nodes[k] = nodes[idx[k]]; + for (int i = 0; i < 8; ++i) + { + if (!(in >> idx[i])) + { + return nullptr; + } + } + auto** hex_nodes = new MeshLib::Node*[8]; + for (unsigned k(0); k < 8; ++k) + { + hex_nodes[k] = nodes[idx[k]]; + } + elem = new MeshLib::Hex(hex_nodes); + break; } - elem = new MeshLib::Pyramid(pyramid_nodes); - break; - } - case MeshLib::MeshElemType::PRISM: { - for (int i = 0; i < 6; ++i) + case MeshLib::MeshElemType::PYRAMID: { - if (!(in >> idx[i])) + for (int i = 0; i < 5; ++i) { - return nullptr; + if (!(in >> idx[i])) + { + return nullptr; + } + } + auto** pyramid_nodes = new MeshLib::Node*[5]; + for (unsigned k(0); k < 5; ++k) + { + pyramid_nodes[k] = nodes[idx[k]]; } + elem = new MeshLib::Pyramid(pyramid_nodes); + break; } - auto** prism_nodes = new MeshLib::Node*[6]; - for (unsigned k(0); k < 6; ++k) + case MeshLib::MeshElemType::PRISM: { - prism_nodes[k] = nodes[idx[k]]; + for (int i = 0; i < 6; ++i) + { + if (!(in >> idx[i])) + { + return nullptr; + } + } + auto** prism_nodes = new MeshLib::Node*[6]; + for (unsigned k(0); k < 6; ++k) + { + prism_nodes[k] = nodes[idx[k]]; + } + elem = new MeshLib::Prism(prism_nodes); + break; } - elem = new MeshLib::Prism(prism_nodes); - break; - } - default: - elem = nullptr; - break; + default: + elem = nullptr; + break; } - delete [] idx; + delete[] idx; return elem; } bool MeshIO::write() { - if(!_mesh) { + if (!_mesh) + { WARN("MeshIO::write(): Cannot write: no mesh object specified."); return false; } @@ -326,7 +337,8 @@ bool MeshIO::write() << " "; const std::size_t n_nodes(_mesh->getNumberOfNodes()); out << n_nodes << "\n"; - for (std::size_t i(0); i < n_nodes; ++i) { + for (std::size_t i(0); i < n_nodes; ++i) + { out << i << " " << *(_mesh->getNode(i)) << "\n"; } @@ -358,10 +370,11 @@ void MeshIO::writeElements( MeshLib::PropertyVector<int> const* const material_ids, std::ostream& out) const { - const std::size_t ele_vector_size (ele_vec.size()); + const std::size_t ele_vector_size(ele_vec.size()); out << ele_vector_size << "\n"; - for (std::size_t i(0); i < ele_vector_size; ++i) { + for (std::size_t i(0); i < ele_vector_size; ++i) + { out << i << " "; if (!material_ids) { @@ -372,7 +385,7 @@ void MeshIO::writeElements( out << (*material_ids)[i] << " "; } out << this->ElemType2StringOutput(ele_vec[i]->getGeomType()) << " "; - unsigned nElemNodes (ele_vec[i]->getNumberOfBaseNodes()); + unsigned nElemNodes(ele_vec[i]->getNumberOfBaseNodes()); for (std::size_t j = 0; j < nElemNodes; ++j) { out << ele_vec[i]->getNode(j)->getID() << " "; @@ -414,6 +427,6 @@ std::string MeshIO::ElemType2StringOutput(const MeshLib::MeshElemType t) return "none"; } -} // end namespace Legacy -} // end namespace IO +} // end namespace Legacy +} // end namespace IO } // namespace MeshLib diff --git a/MeshLib/IO/MPI_IO/NodePartitionedMeshReader.cpp b/MeshLib/IO/MPI_IO/NodePartitionedMeshReader.cpp index da59dafdb821f26aaa914848613ea0f9429a70f2..ce247aa73e54598697d359a9e297436d020dd9c2 100644 --- a/MeshLib/IO/MPI_IO/NodePartitionedMeshReader.cpp +++ b/MeshLib/IO/MPI_IO/NodePartitionedMeshReader.cpp @@ -29,8 +29,7 @@ // Check if the value can by converted to given type without overflow. template <typename VALUE, typename TYPE> -bool -is_safely_convertable(VALUE const& value) +bool is_safely_convertable(VALUE const& value) { bool const result = value <= std::numeric_limits<TYPE>::max(); if (!result) @@ -67,12 +66,13 @@ void NodePartitionedMeshReader::registerNodeDataMpiType() MPI_Datatype types[count] = {MPI_UNSIGNED_LONG, MPI_DOUBLE}; MPI_Aint displacements[count] = {0, sizeof(NodeData::index)}; - MPI_Type_create_struct(count, blocks, displacements, types, &_mpi_node_type); + MPI_Type_create_struct(count, blocks, displacements, types, + &_mpi_node_type); MPI_Type_commit(&_mpi_node_type); } MeshLib::NodePartitionedMesh* NodePartitionedMeshReader::read( - const std::string &file_name_base) + const std::string& file_name_base) { BaseLib::RunTime timer; timer.start(); @@ -81,9 +81,9 @@ MeshLib::NodePartitionedMesh* NodePartitionedMeshReader::read( // Always try binary file first std::string const fname_new = file_name_base + "_partitioned_msh_cfg" + - std::to_string(_mpi_comm_size) + ".bin"; + std::to_string(_mpi_comm_size) + ".bin"; - if(!BaseLib::IsFileExisting(fname_new)) // binary file does not exist. + if (!BaseLib::IsFileExisting(fname_new)) // binary file does not exist. { OGS_FATAL( "Required binary file {:s} does not exist.\n" @@ -103,9 +103,10 @@ MeshLib::NodePartitionedMesh* NodePartitionedMeshReader::read( } template <typename DATA> -bool -NodePartitionedMeshReader::readDataFromFile(std::string const& filename, - MPI_Offset offset, MPI_Datatype type, DATA& data) const +bool NodePartitionedMeshReader::readDataFromFile(std::string const& filename, + MPI_Offset offset, + MPI_Datatype type, + DATA& data) const { // Check container size if (!is_safely_convertable<std::size_t, int>(data.size())) @@ -118,10 +119,10 @@ NodePartitionedMeshReader::readDataFromFile(std::string const& filename, MPI_File file; char* filename_char = const_cast<char*>(filename.data()); - int const file_status = MPI_File_open(_mpi_comm, filename_char, - MPI_MODE_RDONLY, MPI_INFO_NULL, &file); + int const file_status = MPI_File_open( + _mpi_comm, filename_char, MPI_MODE_RDONLY, MPI_INFO_NULL, &file); - if(file_status != 0) + if (file_status != 0) { ERR("Error opening file {:s}. MPI error code {:d}", filename, file_status); @@ -133,24 +134,25 @@ NodePartitionedMeshReader::readDataFromFile(std::string const& filename, MPI_File_set_view(file, offset, type, type, file_mode, MPI_INFO_NULL); // The static cast is checked above. MPI_File_read(file, data.data(), static_cast<int>(data.size()), type, - MPI_STATUS_IGNORE); + MPI_STATUS_IGNORE); MPI_File_close(&file); return true; } MeshLib::NodePartitionedMesh* NodePartitionedMeshReader::readMesh( - const std::string &file_name_base) + const std::string& file_name_base) { //---------------------------------------------------------------------------------- // Read headers - const std::string fname_header = file_name_base + "_partitioned_msh_"; + const std::string fname_header = file_name_base + "_partitioned_msh_"; const std::string fname_num_p_ext = std::to_string(_mpi_comm_size) + ".bin"; - if (!readDataFromFile(fname_header + "cfg" + fname_num_p_ext, - static_cast<MPI_Offset>( - static_cast<unsigned>(_mpi_rank) * sizeof(_mesh_info)), - MPI_LONG, _mesh_info)) + if (!readDataFromFile( + fname_header + "cfg" + fname_num_p_ext, + static_cast<MPI_Offset>(static_cast<unsigned>(_mpi_rank) * + sizeof(_mesh_info)), + MPI_LONG, _mesh_info)) return nullptr; //---------------------------------------------------------------------------------- @@ -158,7 +160,8 @@ MeshLib::NodePartitionedMesh* NodePartitionedMeshReader::readMesh( std::vector<NodeData> nodes(_mesh_info.nodes); if (!readDataFromFile(fname_header + "nod" + fname_num_p_ext, - static_cast<MPI_Offset>(_mesh_info.offset[2]), _mpi_node_type, nodes)) + static_cast<MPI_Offset>(_mesh_info.offset[2]), + _mpi_node_type, nodes)) return nullptr; std::vector<MeshLib::Node*> mesh_nodes; @@ -167,23 +170,25 @@ MeshLib::NodePartitionedMesh* NodePartitionedMeshReader::readMesh( //---------------------------------------------------------------------------------- // Read non-ghost elements - std::vector<unsigned long> elem_data( - _mesh_info.regular_elements + _mesh_info.offset[0]); + std::vector<unsigned long> elem_data(_mesh_info.regular_elements + + _mesh_info.offset[0]); if (!readDataFromFile(fname_header + "ele" + fname_num_p_ext, - static_cast<MPI_Offset>(_mesh_info.offset[3]), MPI_LONG, elem_data)) + static_cast<MPI_Offset>(_mesh_info.offset[3]), + MPI_LONG, elem_data)) return nullptr; - std::vector<MeshLib::Element*> mesh_elems( - _mesh_info.regular_elements + _mesh_info.ghost_elements); + std::vector<MeshLib::Element*> mesh_elems(_mesh_info.regular_elements + + _mesh_info.ghost_elements); setElements(mesh_nodes, elem_data, mesh_elems); //---------------------------------------------------------------------------------- - //Read ghost element - std::vector<unsigned long> ghost_elem_data( - _mesh_info.ghost_elements + _mesh_info.offset[1]); + // Read ghost element + std::vector<unsigned long> ghost_elem_data(_mesh_info.ghost_elements + + _mesh_info.offset[1]); if (!readDataFromFile(fname_header + "ele_g" + fname_num_p_ext, - static_cast<MPI_Offset>(_mesh_info.offset[4]), MPI_LONG, ghost_elem_data)) + static_cast<MPI_Offset>(_mesh_info.offset[4]), + MPI_LONG, ghost_elem_data)) return nullptr; const bool process_ghost = true; @@ -226,7 +231,8 @@ void NodePartitionedMeshReader::readProperties( return; } std::size_t number_of_properties = 0; - is.read(reinterpret_cast<char*>(&number_of_properties), sizeof(std::size_t)); + is.read(reinterpret_cast<char*>(&number_of_properties), + sizeof(std::size_t)); std::vector<std::optional<MeshLib::IO::PropertyVectorMetaData>> vec_pvmd( number_of_properties); for (std::size_t i(0); i < number_of_properties; ++i) @@ -381,14 +387,15 @@ MeshLib::NodePartitionedMesh* NodePartitionedMeshReader::newMesh( _mesh_info.active_nodes); } -void NodePartitionedMeshReader::setNodes(const std::vector<NodeData> &node_data, - std::vector<MeshLib::Node*> &mesh_node, - std::vector<unsigned long> &glb_node_ids) const +void NodePartitionedMeshReader::setNodes( + const std::vector<NodeData>& node_data, + std::vector<MeshLib::Node*>& mesh_node, + std::vector<unsigned long>& glb_node_ids) const { mesh_node.resize(_mesh_info.nodes); glb_node_ids.resize(_mesh_info.nodes); - for(std::size_t i = 0; i < mesh_node.size(); i++) + for (std::size_t i = 0; i < mesh_node.size(); i++) { NodeData const& nd = node_data[i]; glb_node_ids[i] = nd.index; @@ -397,9 +404,9 @@ void NodePartitionedMeshReader::setNodes(const std::vector<NodeData> &node_data, } void NodePartitionedMeshReader::setElements( - const std::vector<MeshLib::Node*> &mesh_nodes, - const std::vector<unsigned long> &elem_data, - std::vector<MeshLib::Element*> &mesh_elems, const bool ghost) const + const std::vector<MeshLib::Node*>& mesh_nodes, + const std::vector<unsigned long>& elem_data, + std::vector<MeshLib::Element*>& mesh_elems, const bool ghost) const { // Number of elements, either ghost or regular unsigned long const ne = @@ -407,7 +414,7 @@ void NodePartitionedMeshReader::setElements( unsigned long const id_offset_ghost = ghost ? _mesh_info.regular_elements : 0; - for(unsigned long i = 0; i < ne; i++) + for (unsigned long i = 0; i < ne; i++) { unsigned long id_offset_elem = elem_data[i]; @@ -421,8 +428,8 @@ void NodePartitionedMeshReader::setElements( unsigned long const nnodes = elem_data[id_offset_elem++]; MeshLib::Node** elem_nodes = new MeshLib::Node*[nnodes]; - for(unsigned long k = 0; k < nnodes; k++) - elem_nodes[k] = mesh_nodes[ elem_data[id_offset_elem++] ]; + for (unsigned long k = 0; k < nnodes; k++) + elem_nodes[k] = mesh_nodes[elem_data[id_offset_elem++]]; // The element types below are defined by the MeshLib::CellType. switch (static_cast<CellType>(e_type)) @@ -505,5 +512,5 @@ void NodePartitionedMeshReader::setElements( } } } -} // namespace IO -} // namespace MeshLib +} // namespace IO +} // namespace MeshLib diff --git a/MeshLib/IO/VtkIO/PVDFile.cpp b/MeshLib/IO/VtkIO/PVDFile.cpp index 5ba3868dd53c7362de4136644adcf678eceb8ccd..f2be2d4c6bc6d4e5f0088433ef90efdab41ff5e2 100644 --- a/MeshLib/IO/VtkIO/PVDFile.cpp +++ b/MeshLib/IO/VtkIO/PVDFile.cpp @@ -13,6 +13,7 @@ #include <fstream> #include <iomanip> #include <limits> + #include "BaseLib/Error.h" #include "MeshLib/IO/VtkIO/VtuInterface.h" diff --git a/MeshLib/IO/XDMF/HdfData.cpp b/MeshLib/IO/XDMF/HdfData.cpp index 86f6809f8ae2a5dfa0574e870e1f5ff0cc7cad82..0103c67a18e1183112103485998fbf549116bf3c 100644 --- a/MeshLib/IO/XDMF/HdfData.cpp +++ b/MeshLib/IO/XDMF/HdfData.cpp @@ -48,8 +48,10 @@ HdfData::HdfData(void const* data_start, std::size_t const size_partitioned_dim, name(name) { auto const& partition_info = getPartitionInfo(size_partitioned_dim); - DBUG("HdfData: The partition of dataset {:s} has dimension {:d} and offset {:d}.", - name, size_partitioned_dim, partition_info.first); + DBUG( + "HdfData: The partition of dataset {:s} has dimension {:d} and offset " + "{:d}.", + name, size_partitioned_dim, partition_info.first); auto const& offset_partitioned_dim = partition_info.first; offsets = {offset_partitioned_dim, 0}; file_space = {partition_info.second, size_tuple}; diff --git a/MeshLib/IO/XDMF/mpi/fileIO.cpp b/MeshLib/IO/XDMF/mpi/fileIO.cpp index a99d4b0e79f175096c6f8bd95e150c8ecde2065c..c7d02ee25270fde901eb321d592de340780bcf89 100644 --- a/MeshLib/IO/XDMF/mpi/fileIO.cpp +++ b/MeshLib/IO/XDMF/mpi/fileIO.cpp @@ -11,7 +11,7 @@ * */ -#include "../fileIO.h" +#include "MeshLib/IO/XDMF/fileIO.h" #include <hdf5.h> #include <mpi.h> diff --git a/MeshLib/IO/XDMF/mpi/partition.cpp b/MeshLib/IO/XDMF/mpi/partition.cpp index ae0a6db43c56e8bb0ce5f5ef33798123943707b4..a9588320e6d058ba55075a33cf09bebad2d8e841 100644 --- a/MeshLib/IO/XDMF/mpi/partition.cpp +++ b/MeshLib/IO/XDMF/mpi/partition.cpp @@ -16,8 +16,8 @@ #include <deque> #include <numeric> -#include "../fileIO.h" #include "BaseLib/Logging.h" +#include "MeshLib/IO/XDMF/fileIO.h" namespace MeshLib::IO { diff --git a/MeshLib/IO/XDMF/posix/fileIO.cpp b/MeshLib/IO/XDMF/posix/fileIO.cpp index 013cde03a577fc765e054976835c2c40eeb54616..2f7d081a8417d82729a41a5e0bb161e593a1fd6c 100644 --- a/MeshLib/IO/XDMF/posix/fileIO.cpp +++ b/MeshLib/IO/XDMF/posix/fileIO.cpp @@ -11,7 +11,7 @@ * */ -#include "../fileIO.h" +#include "MeshLib/IO/XDMF/fileIO.h" #include <hdf5.h> namespace MeshLib::IO diff --git a/MeshLib/IO/XDMF/posix/partition.cpp b/MeshLib/IO/XDMF/posix/partition.cpp index e5e2c5c7e8e1c4409bd53b1480788d67e95c6c90..76dee6fc05ae865179c513c80f5ee6db98b6676e 100644 --- a/MeshLib/IO/XDMF/posix/partition.cpp +++ b/MeshLib/IO/XDMF/posix/partition.cpp @@ -8,7 +8,7 @@ * */ -#include "../partition.h" +#include "MeshLib/IO/XDMF/partition.h" namespace MeshLib::IO { @@ -21,4 +21,4 @@ std::pair<std::size_t, std::size_t> getPartitionInfo(std::size_t const size) { return {0, size}; } -} // namespace MeshLib::IO \ No newline at end of file +} // namespace MeshLib::IO diff --git a/MeshLib/IO/readMeshFromFile.cpp b/MeshLib/IO/readMeshFromFile.cpp index d0e67283b2515be0feb9c43f3c4700f2878a60fb..6c60dd6dc98dd7a6d35cd1fbcecab73b901c2807 100644 --- a/MeshLib/IO/readMeshFromFile.cpp +++ b/MeshLib/IO/readMeshFromFile.cpp @@ -23,15 +23,12 @@ #include <boost/algorithm/string/erase.hpp> -#include "BaseLib/Logging.h" - #include "BaseLib/FileTools.h" +#include "BaseLib/Logging.h" #include "BaseLib/StringTools.h" - -#include "MeshLib/Mesh.h" - #include "MeshLib/IO/Legacy/MeshIO.h" #include "MeshLib/IO/VtkIO/VtuInterface.h" +#include "MeshLib/Mesh.h" #ifdef USE_PETSC #include "MeshLib/IO/MPI_IO/NodePartitionedMeshReader.h" @@ -42,7 +39,7 @@ namespace MeshLib { namespace IO { -MeshLib::Mesh* readMeshFromFile(const std::string &file_name) +MeshLib::Mesh* readMeshFromFile(const std::string& file_name) { #ifdef USE_PETSC int world_size; @@ -50,14 +47,15 @@ MeshLib::Mesh* readMeshFromFile(const std::string &file_name) if (world_size > 1) { MeshLib::IO::NodePartitionedMeshReader read_pmesh(PETSC_COMM_WORLD); - const std::string file_name_base = BaseLib::dropFileExtension(file_name); + const std::string file_name_base = + BaseLib::dropFileExtension(file_name); return read_pmesh.read(file_name_base); } else if (world_size == 1) { MeshLib::Mesh* mesh = readMeshFromFileSerial(file_name); - MeshLib::NodePartitionedMesh* part_mesh - = new MeshLib::NodePartitionedMesh(*mesh); + MeshLib::NodePartitionedMesh* part_mesh = + new MeshLib::NodePartitionedMesh(*mesh); delete mesh; return part_mesh; } @@ -67,7 +65,7 @@ MeshLib::Mesh* readMeshFromFile(const std::string &file_name) #endif } -MeshLib::Mesh* readMeshFromFileSerial(const std::string &file_name) +MeshLib::Mesh* readMeshFromFileSerial(const std::string& file_name) { if (BaseLib::hasFileExtension(".msh", file_name)) { @@ -90,6 +88,5 @@ MeshLib::Mesh* readMeshFromFileSerial(const std::string &file_name) return nullptr; } - -} // end namespace IO -} // end namespace MeshLib +} // end namespace IO +} // end namespace MeshLib diff --git a/MeshLib/IO/writeMeshToFile.cpp b/MeshLib/IO/writeMeshToFile.cpp index 1adb694ad0d2418fc0d3bdc795d171fe041c3cec..3f899d0d015575f34d7c4f15bb6953ac13e737bc 100644 --- a/MeshLib/IO/writeMeshToFile.cpp +++ b/MeshLib/IO/writeMeshToFile.cpp @@ -44,9 +44,8 @@ int writeMeshToFile(const MeshLib::Mesh& mesh, #ifdef OGS_USE_XDMF if (file_path.extension().string() == ".xdmf") { - auto writer = - std::make_unique<MeshLib::IO::XdmfHdfWriter>(MeshLib::IO::XdmfHdfWriter( - mesh, file_path, 0)); + auto writer = std::make_unique<MeshLib::IO::XdmfHdfWriter>( + MeshLib::IO::XdmfHdfWriter(mesh, file_path, 0)); // \TODO Errorhandling, Change data model into static and time depended, // then is is not necessary to give time step 0 a special treatment // here diff --git a/MeshLib/Location.cpp b/MeshLib/Location.cpp index e8d1c459be58bc5a864127785d5b5fedce857fec..b0617f62a7e3d5c3147fa5bac9ab69ff3fb761bf 100644 --- a/MeshLib/Location.cpp +++ b/MeshLib/Location.cpp @@ -9,30 +9,33 @@ */ #include "Location.h" + #include <ostream> namespace MeshLib { - std::ostream& operator<<(std::ostream& os, MeshItemType const& t) { switch (t) { - case MeshItemType::Node: return os << "N"; - case MeshItemType::Edge: return os << "E"; - case MeshItemType::Face: return os << "F"; - case MeshItemType::Cell: return os << "C"; - case MeshItemType::IntegrationPoint: return os << "I"; + case MeshItemType::Node: + return os << "N"; + case MeshItemType::Edge: + return os << "E"; + case MeshItemType::Face: + return os << "F"; + case MeshItemType::Cell: + return os << "C"; + case MeshItemType::IntegrationPoint: + return os << "I"; }; return os; } std::ostream& operator<<(std::ostream& os, Location const& l) { - return os << "(" << l.mesh_id - << ", " << l.item_type - << ", " << l.item_id - << ")"; + return os << "(" << l.mesh_id << ", " << l.item_type << ", " << l.item_id + << ")"; } -} // namespace MeshLib +} // namespace MeshLib diff --git a/MeshLib/Mesh.cpp b/MeshLib/Mesh.cpp index 35805ad4a6ce41dafe586fbb7f91d5e499e69545..ee5c3ac50c9484084166e45c03010766a128146b 100644 --- a/MeshLib/Mesh.cpp +++ b/MeshLib/Mesh.cpp @@ -19,14 +19,13 @@ #include <utility> #include "BaseLib/RunTime.h" - #include "Elements/Element.h" -#include "Elements/Tri.h" -#include "Elements/Quad.h" -#include "Elements/Tet.h" #include "Elements/Hex.h" -#include "Elements/Pyramid.h" #include "Elements/Prism.h" +#include "Elements/Pyramid.h" +#include "Elements/Quad.h" +#include "Elements/Tet.h" +#include "Elements/Tri.h" /// Mesh counter used to uniquely identify meshes by id. static std::size_t global_mesh_counter = 0; @@ -80,16 +79,16 @@ Mesh::Mesh(const Mesh& mesh) _n_base_nodes(mesh.getNumberOfBaseNodes()), _properties(mesh._properties) { - const std::vector<Node*>& nodes (mesh.getNodes()); - const std::size_t nNodes (nodes.size()); + const std::vector<Node*>& nodes(mesh.getNodes()); + const std::size_t nNodes(nodes.size()); for (unsigned i = 0; i < nNodes; ++i) { _nodes[i] = new Node(*nodes[i]); } - const std::vector<Element*>& elements (mesh.getElements()); - const std::size_t nElements (elements.size()); - for (unsigned i=0; i<nElements; ++i) + const std::vector<Element*>& elements(mesh.getElements()); + const std::size_t nElements(elements.size()); + for (unsigned i = 0; i < nElements; ++i) { const std::size_t nElemNodes = elements[i]->getNumberOfNodes(); _elements[i] = elements[i]->clone(); @@ -104,19 +103,19 @@ Mesh::Mesh(const Mesh& mesh) this->setDimension(); } this->setElementsConnectedToNodes(); - //this->setNodesConnectedByElements(); + // this->setNodesConnectedByElements(); this->setElementNeighbors(); } Mesh::~Mesh() { - const std::size_t nElements (_elements.size()); + const std::size_t nElements(_elements.size()); for (std::size_t i = 0; i < nElements; ++i) { delete _elements[i]; } - const std::size_t nNodes (_nodes.size()); + const std::size_t nNodes(_nodes.size()); for (std::size_t i = 0; i < nNodes; ++i) { delete _nodes[i]; @@ -128,7 +127,7 @@ void Mesh::addElement(Element* elem) _elements.push_back(elem); // add element information to nodes - unsigned nNodes (elem->getNumberOfNodes()); + unsigned nNodes(elem->getNumberOfNodes()); for (unsigned i = 0; i < nNodes; ++i) { elem->_nodes[i]->addElement(elem); @@ -159,7 +158,7 @@ void Mesh::recalculateMaxBaseNodeId() void Mesh::resetElementIDs() { - const std::size_t nElements (this->_elements.size()); + const std::size_t nElements(this->_elements.size()); for (unsigned i = 0; i < nElements; ++i) { _elements[i]->setID(i); @@ -168,7 +167,7 @@ void Mesh::resetElementIDs() void Mesh::setDimension() { - const std::size_t nElements (_elements.size()); + const std::size_t nElements(_elements.size()); for (unsigned i = 0; i < nElements; ++i) { if (_elements[i]->getDimension() > _mesh_dimension) @@ -209,17 +208,22 @@ void Mesh::setElementNeighbors() std::vector<Element*> neighbors; for (auto element : _elements) { - // create vector with all elements connected to current element (includes lots of doubles!) - const std::size_t nNodes (element->getNumberOfBaseNodes()); - for (unsigned n(0); n<nNodes; ++n) + // create vector with all elements connected to current element + // (includes lots of doubles!) + const std::size_t nNodes(element->getNumberOfBaseNodes()); + for (unsigned n(0); n < nNodes; ++n) { - std::vector<Element*> const& conn_elems ((element->getNode(n)->getElements())); - neighbors.insert(neighbors.end(), conn_elems.begin(), conn_elems.end()); + std::vector<Element*> const& conn_elems( + (element->getNode(n)->getElements())); + neighbors.insert(neighbors.end(), conn_elems.begin(), + conn_elems.end()); } std::sort(neighbors.begin(), neighbors.end()); - auto const neighbors_new_end = std::unique(neighbors.begin(), neighbors.end()); + auto const neighbors_new_end = + std::unique(neighbors.begin(), neighbors.end()); - for (auto neighbor = neighbors.begin(); neighbor != neighbors_new_end; ++neighbor) + for (auto neighbor = neighbors.begin(); neighbor != neighbors_new_end; + ++neighbor) { std::optional<unsigned> const opposite_face_id = element->addNeighbor(*neighbor); @@ -257,8 +261,9 @@ void Mesh::setNodesConnectedByElements() // Make nodes unique and sorted by their ids. // This relies on the node's id being equivalent to it's address. std::sort(adjacent_nodes.begin(), adjacent_nodes.end(), - [](Node* a, Node* b) { return a->getID() < b->getID(); }); - auto const last = std::unique(adjacent_nodes.begin(), adjacent_nodes.end()); + [](Node* a, Node* b) { return a->getID() < b->getID(); }); + auto const last = + std::unique(adjacent_nodes.begin(), adjacent_nodes.end()); adjacent_nodes.erase(last, adjacent_nodes.end()); node->setConnectedNodes(adjacent_nodes); @@ -269,7 +274,8 @@ void Mesh::checkNonlinearNodeIDs() const { for (MeshLib::Element const* e : _elements) { - for (unsigned i=e->getNumberOfBaseNodes(); i<e->getNumberOfNodes(); i++) + for (unsigned i = e->getNumberOfBaseNodes(); i < e->getNumberOfNodes(); + i++) { if (e->getNodeIndex(i) >= getNumberOfBaseNodes()) { @@ -288,13 +294,13 @@ void Mesh::checkNonlinearNodeIDs() const bool Mesh::hasNonlinearElement() const { - return std::any_of(std::begin(_elements), std::end(_elements), - [](Element const* const e) { + return std::any_of( + std::begin(_elements), std::end(_elements), [](Element const* const e) { return e->getNumberOfNodes() != e->getNumberOfBaseNodes(); }); } -void scaleMeshPropertyVector(MeshLib::Mesh & mesh, +void scaleMeshPropertyVector(MeshLib::Mesh& mesh, std::string const& property_name, double factor) { @@ -303,7 +309,7 @@ void scaleMeshPropertyVector(MeshLib::Mesh & mesh, WARN("Did not find PropertyVector '{:s}' for scaling.", property_name); return; } - auto & pv = *mesh.getProperties().getPropertyVector<double>(property_name); + auto& pv = *mesh.getProperties().getPropertyVector<double>(property_name); std::transform(pv.begin(), pv.end(), pv.begin(), [factor](auto const& v) { return v * factor; }); } diff --git a/MeshLib/MeshEditing/AddLayerToMesh.cpp b/MeshLib/MeshEditing/AddLayerToMesh.cpp index 89af403f11cbe72292416582515a62557d28e299..f332139ab25556935d4912cf920bd0430f6d97cd 100644 --- a/MeshLib/MeshEditing/AddLayerToMesh.cpp +++ b/MeshLib/MeshEditing/AddLayerToMesh.cpp @@ -19,17 +19,15 @@ #include <vector> #include "BaseLib/Logging.h" - -#include "MeshLib/Mesh.h" -#include "MeshLib/Node.h" #include "MeshLib/Elements/Elements.h" -#include "MeshLib/MeshSurfaceExtraction.h" +#include "MeshLib/Mesh.h" #include "MeshLib/MeshEditing/DuplicateMeshComponents.h" #include "MeshLib/MeshEditing/FlipElements.h" +#include "MeshLib/MeshSurfaceExtraction.h" +#include "MeshLib/Node.h" namespace MeshLib { - /** Extrudes point, line, triangle or quad elements to its higher dimensional * versions, i.e. line, quad, prism, hexahedron. * @@ -42,8 +40,9 @@ namespace MeshLib * * @return extruded element (point -> line, line -> quad, tri -> prism, quad -> * hexahedron) -*/ -MeshLib::Element* extrudeElement(std::vector<MeshLib::Node*> const& subsfc_nodes, + */ +MeshLib::Element* extrudeElement( + std::vector<MeshLib::Node*> const& subsfc_nodes, MeshLib::Element const& sfc_elem, MeshLib::PropertyVector<std::size_t> const& sfc_to_subsfc_id_map, std::map<std::size_t, std::size_t> const& subsfc_sfc_id_map) @@ -58,12 +57,12 @@ MeshLib::Element* extrudeElement(std::vector<MeshLib::Node*> const& subsfc_nodes new MeshLib::Node*[2 * nElemNodes] }; - for (unsigned j=0; j<nElemNodes; ++j) + for (unsigned j = 0; j < nElemNodes; ++j) { std::size_t const subsfc_id( sfc_to_subsfc_id_map[sfc_elem.getNode(j)->getID()]); new_nodes[j] = subsfc_nodes[subsfc_id]; - std::size_t new_idx = (nElemNodes==2) ? (3-j) : (nElemNodes+j); + std::size_t new_idx = (nElemNodes == 2) ? (3 - j) : (nElemNodes + j); new_nodes[new_idx] = subsfc_nodes[subsfc_sfc_id_map.at(subsfc_id)]; } @@ -91,7 +90,7 @@ MeshLib::Mesh* addLayerToMesh(MeshLib::Mesh const& mesh, double thickness, double const flag = on_top ? -1.0 : 1.0; Eigen::Vector3d const dir({0, 0, flag}); double const angle(90); - std::unique_ptr<MeshLib::Mesh> sfc_mesh (nullptr); + std::unique_ptr<MeshLib::Mesh> sfc_mesh(nullptr); std::string const prop_name("bulk_node_ids"); @@ -169,8 +168,8 @@ MeshLib::Mesh* addLayerToMesh(MeshLib::Mesh const& mesh, double thickness, if (!mesh.getProperties().existsPropertyVector<int>("MaterialIDs")) { - ERR("Could not copy the property 'MaterialIDs' since the original " - "mesh does not contain such a property."); + ERR("Could not copy the property 'MaterialIDs' since the original mesh " + "does not contain such a property."); return new_mesh; } auto const* const materials = @@ -210,4 +209,4 @@ MeshLib::Mesh* addLayerToMesh(MeshLib::Mesh const& mesh, double thickness, return new_mesh; } -} // namespace MeshLib +} // namespace MeshLib diff --git a/MeshLib/MeshEditing/DuplicateMeshComponents.cpp b/MeshLib/MeshEditing/DuplicateMeshComponents.cpp index fc4863a5c29dffc2f24c89ea6b56c1d0a880bb5f..14b4884c450c77aab57171f22a26a8990beb072c 100644 --- a/MeshLib/MeshEditing/DuplicateMeshComponents.cpp +++ b/MeshLib/MeshEditing/DuplicateMeshComponents.cpp @@ -14,8 +14,8 @@ #include "DuplicateMeshComponents.h" -#include "MeshLib/Mesh.h" #include "MeshLib/Elements/Elements.h" +#include "MeshLib/Mesh.h" namespace MeshLib { @@ -74,10 +74,9 @@ MeshLib::Element* copyElement(MeshLib::Element const* const element, return new E(new_nodes); } -MeshLib::Element* copyElement( - MeshLib::Element const* const element, - const std::vector<MeshLib::Node*>& nodes, - std::vector<std::size_t> const* const id_map) +MeshLib::Element* copyElement(MeshLib::Element const* const element, + const std::vector<MeshLib::Node*>& nodes, + std::vector<std::size_t> const* const id_map) { switch (element->getCellType()) { diff --git a/MeshLib/MeshEditing/ElementValueModification.cpp b/MeshLib/MeshEditing/ElementValueModification.cpp index 4a727c233eade11a1f0f44d531b8f35666cbf4b3..d1d06baaa2cfaa61caeed093025dfe4903d18536 100644 --- a/MeshLib/MeshEditing/ElementValueModification.cpp +++ b/MeshLib/MeshEditing/ElementValueModification.cpp @@ -17,16 +17,16 @@ #include <algorithm> #include "BaseLib/Logging.h" - #include "MeshLib/Elements/Element.h" #include "MeshLib/Mesh.h" #include "MeshLib/PropertyVector.h" -namespace MeshLib { - -bool ElementValueModification::replace(MeshLib::Mesh &mesh, - std::string const& property_name, int const old_value, int const new_value, - bool replace_if_exists) +namespace MeshLib +{ +bool ElementValueModification::replace(MeshLib::Mesh& mesh, + std::string const& property_name, + int const old_value, int const new_value, + bool replace_if_exists) { MeshLib::PropertyVector<int>* property_value_vec = nullptr; try @@ -50,9 +50,9 @@ bool ElementValueModification::replace(MeshLib::Mesh &mesh, if ((*property_value_vec)[i] == new_value) { WARN( - "ElementValueModification::replaceElementValue() " - "- Replacement value '{:d}' is already taken, " - "no changes have been made.", + "ElementValueModification::replaceElementValue() - " + "Replacement value '{:d}' is already taken, no changes " + "have been made.", new_value); return false; } @@ -70,13 +70,15 @@ bool ElementValueModification::replace(MeshLib::Mesh &mesh, return true; } -bool ElementValueModification::replace(MeshLib::Mesh &mesh, - int const old_value, int const new_value, bool replace_if_exists) +bool ElementValueModification::replace(MeshLib::Mesh& mesh, int const old_value, + int const new_value, + bool replace_if_exists) { - return replace(mesh, "MaterialIDs", old_value, new_value, replace_if_exists); + return replace(mesh, "MaterialIDs", old_value, new_value, + replace_if_exists); } -std::size_t ElementValueModification::condense(MeshLib::Mesh &mesh) +std::size_t ElementValueModification::condense(MeshLib::Mesh& mesh) { MeshLib::PropertyVector<int>* property_value_vector = nullptr; try @@ -110,7 +112,9 @@ std::size_t ElementValueModification::condense(MeshLib::Mesh &mesh) return nValues; } -std::size_t ElementValueModification::setByElementType(MeshLib::Mesh &mesh, MeshElemType ele_type, int const new_value) +std::size_t ElementValueModification::setByElementType(MeshLib::Mesh& mesh, + MeshElemType ele_type, + int const new_value) { MeshLib::PropertyVector<int>* property_value_vector = nullptr; try @@ -139,4 +143,4 @@ std::size_t ElementValueModification::setByElementType(MeshLib::Mesh &mesh, Mesh return cnt; } -} // end namespace MeshLib +} // end namespace MeshLib diff --git a/MeshLib/MeshEditing/FlipElements.cpp b/MeshLib/MeshEditing/FlipElements.cpp index b2b3ec1f1f299a41547a51bab370ab47582c7a6b..59cf46ee38ed8fefc19ff423f22be0034a98d72d 100644 --- a/MeshLib/MeshEditing/FlipElements.cpp +++ b/MeshLib/MeshEditing/FlipElements.cpp @@ -10,12 +10,12 @@ #include "FlipElements.h" +#include "DuplicateMeshComponents.h" #include "MeshLib/Elements/Element.h" -#include "MeshLib/Node.h" #include "MeshLib/Elements/Line.h" -#include "MeshLib/Elements/Tri.h" #include "MeshLib/Elements/Quad.h" -#include "DuplicateMeshComponents.h" +#include "MeshLib/Elements/Tri.h" +#include "MeshLib/Node.h" namespace MeshLib { diff --git a/MeshLib/MeshEditing/Mesh2MeshPropertyInterpolation.cpp b/MeshLib/MeshEditing/Mesh2MeshPropertyInterpolation.cpp index 9729f8da8b24eb9d16c874c4a424041e96af0b65..5c31760f63b915e15b2350ad00bd782aea36c921 100644 --- a/MeshLib/MeshEditing/Mesh2MeshPropertyInterpolation.cpp +++ b/MeshLib/MeshEditing/Mesh2MeshPropertyInterpolation.cpp @@ -12,31 +12,31 @@ * */ -#include <vector> -#include <fstream> - #include "Mesh2MeshPropertyInterpolation.h" -#include "BaseLib/Logging.h" +#include <fstream> +#include <vector> +#include "BaseLib/Logging.h" #include "GeoLib/AABB.h" #include "GeoLib/Grid.h" - -#include "MeshLib/MeshEnums.h" +#include "MeshLib/Elements/Element.h" #include "MeshLib/Mesh.h" +#include "MeshLib/MeshEnums.h" #include "MeshLib/Node.h" -#include "MeshLib/Elements/Element.h" - -namespace MeshLib { +namespace MeshLib +{ Mesh2MeshPropertyInterpolation::Mesh2MeshPropertyInterpolation( Mesh const& src_mesh, std::string const& property_name) : _src_mesh(src_mesh), _property_name(property_name) -{} +{ +} bool Mesh2MeshPropertyInterpolation::setPropertiesForMesh(Mesh& dest_mesh) const { - if (_src_mesh.getDimension() != dest_mesh.getDimension()) { + if (_src_mesh.getDimension() != dest_mesh.getDimension()) + { ERR("MeshLib::Mesh2MeshPropertyInterpolation::setPropertiesForMesh() " "dimension of source (dim = {:d}) and destination (dim = {:d}) " "mesh does not match.", @@ -44,7 +44,8 @@ bool Mesh2MeshPropertyInterpolation::setPropertiesForMesh(Mesh& dest_mesh) const return false; } - if (_src_mesh.getDimension() != 2) { + if (_src_mesh.getDimension() != 2) + { WARN( "MeshLib::Mesh2MeshPropertyInterpolation::setPropertiesForMesh() " "implemented only for 2D case at the moment."); @@ -67,8 +68,8 @@ bool Mesh2MeshPropertyInterpolation::setPropertiesForMesh(Mesh& dest_mesh) const if (!dest_properties) { WARN( - "Could not get or create a PropertyVector of type double" - " using the given name '{:s}'.", + "Could not get or create a PropertyVector of type double using " + "the given name '{:s}'.", _property_name); return false; } @@ -147,8 +148,9 @@ void Mesh2MeshPropertyInterpolation::interpolatePropertiesForMesh( } } -void Mesh2MeshPropertyInterpolation::interpolateElementPropertiesToNodeProperties( - std::vector<double> &interpolated_properties) const +void Mesh2MeshPropertyInterpolation:: + interpolateElementPropertiesToNodeProperties( + std::vector<double>& interpolated_properties) const { // fetch the source of property values if (!_src_mesh.getProperties().existsPropertyVector<double>(_property_name)) @@ -175,4 +177,4 @@ void Mesh2MeshPropertyInterpolation::interpolateElementPropertiesToNodePropertie } } -} // end namespace MeshLib +} // end namespace MeshLib diff --git a/MeshLib/MeshEditing/ProjectPointOnMesh.cpp b/MeshLib/MeshEditing/ProjectPointOnMesh.cpp index 0dce76e23c9beadff2aa7615bd8919d907d52383..88930006e5858debe69454c5bdd90ce73414dcf0 100644 --- a/MeshLib/MeshEditing/ProjectPointOnMesh.cpp +++ b/MeshLib/MeshEditing/ProjectPointOnMesh.cpp @@ -10,7 +10,6 @@ #include "GeoLib/AnalyticalGeometry.h" #include "MathLib/Point3d.h" - #include "MeshLib/Elements/Quad.h" #include "MeshLib/Elements/Tri.h" #include "MeshLib/MeshSearch/MeshElementGrid.h" @@ -19,7 +18,6 @@ namespace MeshLib { namespace ProjectPointOnMesh { - MeshLib::Element const* getProjectedElement( std::vector<const MeshLib::Element*> const& elements, MeshLib::Node const& node) diff --git a/MeshLib/MeshEditing/RasterDataToMesh.cpp b/MeshLib/MeshEditing/RasterDataToMesh.cpp index c2f426286b50a028c843238bae53c4de8f6b44b1..64d7977f3f1e30a2377994a458561a00a5b06a36 100644 --- a/MeshLib/MeshEditing/RasterDataToMesh.cpp +++ b/MeshLib/MeshEditing/RasterDataToMesh.cpp @@ -11,12 +11,11 @@ #include "RasterDataToMesh.h" #include "BaseLib/StringTools.h" -#include "MeshLib/Node.h" #include "MeshLib/Elements/Element.h" +#include "MeshLib/Node.h" namespace MeshLib { - namespace RasterDataToMesh { static bool checkMesh(MeshLib::Mesh const& mesh) diff --git a/MeshLib/MeshEditing/RemoveMeshComponents.cpp b/MeshLib/MeshEditing/RemoveMeshComponents.cpp index e05da29001a7b6980cdef92e71d90603cdd00648..f9fe696ca2b0cbc7ab1f1676cfd520ea409c156a 100644 --- a/MeshLib/MeshEditing/RemoveMeshComponents.cpp +++ b/MeshLib/MeshEditing/RemoveMeshComponents.cpp @@ -10,11 +10,11 @@ #include "RemoveMeshComponents.h" +#include "DuplicateMeshComponents.h" #include "MeshLib/Elements/Element.h" -#include "MeshLib/Node.h" #include "MeshLib/MeshSearch/ElementSearch.h" #include "MeshLib/MeshSearch/NodeSearch.h" -#include "DuplicateMeshComponents.h" +#include "MeshLib/Node.h" namespace MeshLib { @@ -174,4 +174,3 @@ MeshLib::Mesh* removeNodes(const MeshLib::Mesh& mesh, return nullptr; } } // end namespace MeshLib - diff --git a/MeshLib/MeshEnums.cpp b/MeshLib/MeshEnums.cpp index b6dcd5729bf9f7095e6946af2ada6f77c2032481..d36438b0b2bcabe58fb77c09a533d2ffaf2cdbbc 100644 --- a/MeshLib/MeshEnums.cpp +++ b/MeshLib/MeshEnums.cpp @@ -16,7 +16,8 @@ #include <boost/algorithm/string/predicate.hpp> -namespace MeshLib { +namespace MeshLib +{ std::string MeshElemType2String(const MeshElemType t) { if (t == MeshElemType::POINT) @@ -91,7 +92,7 @@ std::string MeshElemType2StringShort(const MeshElemType t) return "none"; } -MeshElemType String2MeshElemType(const std::string &s) +MeshElemType String2MeshElemType(const std::string& s) { if (boost::iequals(s, "point")) { @@ -155,8 +156,8 @@ std::vector<std::string> getMeshElemTypeStringsShort() std::string CellType2String(const CellType t) { -#define RETURN_CELL_TYPE_STR(t, type)\ - if ((t) == CellType::type)\ +#define RETURN_CELL_TYPE_STR(t, type) \ + if ((t) == CellType::type) \ return #type; RETURN_CELL_TYPE_STR(t, POINT1); diff --git a/MeshLib/MeshGenerators/LayeredMeshGenerator.cpp b/MeshLib/MeshGenerators/LayeredMeshGenerator.cpp index c47bbce05c6d68c937d4ee9b30fbcd30110e973c..584d1be408bd35ceb6a42b2e3845b62797ceaa53 100644 --- a/MeshLib/MeshGenerators/LayeredMeshGenerator.cpp +++ b/MeshLib/MeshGenerators/LayeredMeshGenerator.cpp @@ -14,21 +14,19 @@ #include "LayeredMeshGenerator.h" -#include <vector> #include <fstream> +#include <vector> #include "BaseLib/Logging.h" - #include "GeoLib/Raster.h" - -#include "MeshLib/Mesh.h" -#include "MeshLib/Node.h" #include "MeshLib/Elements/Element.h" +#include "MeshLib/Mesh.h" +#include "MeshLib/MeshEditing/RemoveMeshComponents.h" #include "MeshLib/MeshInformation.h" -#include "MeshLib/PropertyVector.h" -#include "MeshLib/Properties.h" #include "MeshLib/MeshSearch/NodeSearch.h" -#include "MeshLib/MeshEditing/RemoveMeshComponents.h" +#include "MeshLib/Node.h" +#include "MeshLib/Properties.h" +#include "MeshLib/PropertyVector.h" bool LayeredMeshGenerator::createLayers( MeshLib::Mesh const& mesh, @@ -41,7 +39,8 @@ bool LayeredMeshGenerator::createLayers( return false; } - auto const elem_count = MeshLib::MeshInformation::getNumberOfElementTypes(mesh); + auto const elem_count = + MeshLib::MeshInformation::getNumberOfElementTypes(mesh); if (elem_count.find(MeshLib::MeshElemType::QUAD) != elem_count.end()) { ERR("Input mesh contains QUAD-elements. Please use input mesh " @@ -49,13 +48,16 @@ bool LayeredMeshGenerator::createLayers( return false; } - bool result = createRasterLayers(mesh, rasters, minimum_thickness, noDataReplacementValue); - std::for_each(rasters.begin(), rasters.end(), [](GeoLib::Raster const*const raster){ delete raster; }); + bool result = createRasterLayers( + mesh, rasters, minimum_thickness, noDataReplacementValue); + std::for_each(rasters.begin(), + rasters.end(), + [](GeoLib::Raster const* const raster) { delete raster; }); return result; } -std::unique_ptr<MeshLib::Mesh> -LayeredMeshGenerator::getMesh(std::string const& mesh_name) const +std::unique_ptr<MeshLib::Mesh> LayeredMeshGenerator::getMesh( + std::string const& mesh_name) const { if (_nodes.empty()) { @@ -86,9 +88,11 @@ LayeredMeshGenerator::getMesh(std::string const& mesh_name) const "element number"); } - std::unique_ptr<MeshLib::Mesh> result(new MeshLib::Mesh(mesh_name, _nodes, _elements, properties)); + std::unique_ptr<MeshLib::Mesh> result( + new MeshLib::Mesh(mesh_name, _nodes, _elements, properties)); MeshLib::NodeSearch ns(*result); - if (ns.searchUnused() > 0) { + if (ns.searchUnused() > 0) + { std::unique_ptr<MeshLib::Mesh> new_mesh( MeshLib::removeNodes(*result, ns.getSearchedNodeIDs(), mesh_name)); return new_mesh; @@ -96,19 +100,22 @@ LayeredMeshGenerator::getMesh(std::string const& mesh_name) const return result; } -double LayeredMeshGenerator::calcEpsilon(GeoLib::Raster const& low, GeoLib::Raster const& high) +double LayeredMeshGenerator::calcEpsilon(GeoLib::Raster const& low, + GeoLib::Raster const& high) { - const double max (*std::max_element(high.begin(), high.end())); - const double min (*std::min_element( low.begin(), low.end())); - return ((max-min)*1e-07); + const double max(*std::max_element(high.begin(), high.end())); + const double min(*std::min_element(low.begin(), low.end())); + return ((max - min) * 1e-07); } -MeshLib::Node* LayeredMeshGenerator::getNewLayerNode(MeshLib::Node const& dem_node, - MeshLib::Node const& last_layer_node, - GeoLib::Raster const& raster, - std::size_t new_node_id) const +MeshLib::Node* LayeredMeshGenerator::getNewLayerNode( + MeshLib::Node const& dem_node, + MeshLib::Node const& last_layer_node, + GeoLib::Raster const& raster, + std::size_t new_node_id) const { - double const elevation = std::min(raster.interpolateValueAtPoint(dem_node), dem_node[2]); + double const elevation = + std::min(raster.interpolateValueAtPoint(dem_node), dem_node[2]); if ((std::abs(elevation - raster.getHeader().no_data) < std::numeric_limits<double>::epsilon()) || diff --git a/MeshLib/MeshGenerators/LayeredVolume.cpp b/MeshLib/MeshGenerators/LayeredVolume.cpp index 569b547ae043286b002cd16e04bf9517da403b8b..254f5b89aff2c0260db3f86063cc23bb42ffe922 100644 --- a/MeshLib/MeshGenerators/LayeredVolume.cpp +++ b/MeshLib/MeshGenerators/LayeredVolume.cpp @@ -15,20 +15,19 @@ #include "LayeredVolume.h" #include "GeoLib/Raster.h" - -#include "MeshLib/Elements/Tri.h" #include "MeshLib/Elements/Quad.h" -#include "MeshLib/Properties.h" +#include "MeshLib/Elements/Tri.h" #include "MeshLib/MeshEditing/DuplicateMeshComponents.h" #include "MeshLib/MeshEditing/RemoveMeshComponents.h" #include "MeshLib/MeshGenerators/MeshLayerMapper.h" #include "MeshLib/MeshSearch/ElementSearch.h" +#include "MeshLib/Properties.h" - -bool LayeredVolume::createRasterLayers(const MeshLib::Mesh &mesh, - const std::vector<GeoLib::Raster const*> &rasters, - double minimum_thickness, - double noDataReplacementValue) +bool LayeredVolume::createRasterLayers( + const MeshLib::Mesh& mesh, + const std::vector<GeoLib::Raster const*>& rasters, + double minimum_thickness, + double noDataReplacementValue) { if (mesh.getDimension() != 2) { @@ -74,7 +73,7 @@ bool LayeredVolume::createRasterLayers(const MeshLib::Mesh &mesh, _materials.resize(_elements.size(), 0); // map each layer and attach to subsurface mesh - const std::size_t nRasters (rasters.size()); + const std::size_t nRasters(rasters.size()); for (std::size_t i = 1; i < nRasters; ++i) { this->addLayerToMesh(*top, i, *rasters[i]); @@ -87,12 +86,14 @@ bool LayeredVolume::createRasterLayers(const MeshLib::Mesh &mesh, return true; } -void LayeredVolume::addLayerToMesh(const MeshLib::Mesh &dem_mesh, unsigned layer_id, GeoLib::Raster const& raster) +void LayeredVolume::addLayerToMesh(const MeshLib::Mesh& dem_mesh, + unsigned layer_id, + GeoLib::Raster const& raster) { - const std::size_t nNodes (dem_mesh.getNumberOfNodes()); - const std::vector<MeshLib::Node*> &nodes (dem_mesh.getNodes()); - const std::size_t node_id_offset (_nodes.size()); - const std::size_t last_layer_node_offset (node_id_offset-nNodes); + const std::size_t nNodes(dem_mesh.getNumberOfNodes()); + const std::vector<MeshLib::Node*>& nodes(dem_mesh.getNodes()); + const std::size_t node_id_offset(_nodes.size()); + const std::size_t last_layer_node_offset(node_id_offset - nNodes); for (std::size_t i = 0; i < nNodes; ++i) { @@ -102,48 +103,57 @@ void LayeredVolume::addLayerToMesh(const MeshLib::Mesh &dem_mesh, unsigned layer _nodes.size())); } - const std::vector<MeshLib::Element*> &layer_elements (dem_mesh.getElements()); + const std::vector<MeshLib::Element*>& layer_elements( + dem_mesh.getElements()); for (MeshLib::Element* elem : layer_elements) { if (elem->getGeomType() == MeshLib::MeshElemType::TRIANGLE) { - std::array<MeshLib::Node*,3> tri_nodes = {{ _nodes[node_id_offset+elem->getNodeIndex(0)], - _nodes[node_id_offset+elem->getNodeIndex(1)], - _nodes[node_id_offset+elem->getNodeIndex(2)] }}; + std::array<MeshLib::Node*, 3> tri_nodes = { + {_nodes[node_id_offset + elem->getNodeIndex(0)], + _nodes[node_id_offset + elem->getNodeIndex(1)], + _nodes[node_id_offset + elem->getNodeIndex(2)]}}; _elements.push_back(new MeshLib::Tri(tri_nodes)); _materials.push_back(layer_id); } else if (elem->getGeomType() == MeshLib::MeshElemType::QUAD) { - std::array<MeshLib::Node*,4> quad_nodes = {{ _nodes[node_id_offset+elem->getNodeIndex(0)], - _nodes[node_id_offset+elem->getNodeIndex(1)], - _nodes[node_id_offset+elem->getNodeIndex(2)], - _nodes[node_id_offset+elem->getNodeIndex(3)] }}; + std::array<MeshLib::Node*, 4> quad_nodes = { + {_nodes[node_id_offset + elem->getNodeIndex(0)], + _nodes[node_id_offset + elem->getNodeIndex(1)], + _nodes[node_id_offset + elem->getNodeIndex(2)], + _nodes[node_id_offset + elem->getNodeIndex(3)]}}; _elements.push_back(new MeshLib::Quad(quad_nodes)); _materials.push_back(layer_id); } } } -void LayeredVolume::addLayerBoundaries(const MeshLib::Mesh &layer, std::size_t nLayers) +void LayeredVolume::addLayerBoundaries(const MeshLib::Mesh& layer, + std::size_t nLayers) { - const unsigned nLayerBoundaries (nLayers-1); - const std::size_t nNodes (layer.getNumberOfNodes()); - const std::vector<MeshLib::Element*> &layer_elements (layer.getElements()); + const unsigned nLayerBoundaries(nLayers - 1); + const std::size_t nNodes(layer.getNumberOfNodes()); + const std::vector<MeshLib::Element*>& layer_elements(layer.getElements()); for (MeshLib::Element* elem : layer_elements) { - const std::size_t nElemNodes (elem->getNumberOfBaseNodes()); + const std::size_t nElemNodes(elem->getNumberOfBaseNodes()); for (unsigned i = 0; i < nElemNodes; ++i) { if (elem->getNeighbor(i) == nullptr) { - for (unsigned j=0; j<nLayerBoundaries; ++j) + for (unsigned j = 0; j < nLayerBoundaries; ++j) { - const std::size_t offset (j*nNodes); + const std::size_t offset(j * nNodes); MeshLib::Node* n0 = _nodes[offset + elem->getNodeIndex(i)]; - MeshLib::Node* n1 = _nodes[offset + elem->getNodeIndex((i+1)%nElemNodes)]; - MeshLib::Node* n2 = _nodes[offset + nNodes + elem->getNodeIndex((i+1)%nElemNodes)]; - MeshLib::Node* n3 = _nodes[offset + nNodes + elem->getNodeIndex(i)]; + MeshLib::Node* n1 = + _nodes[offset + + elem->getNodeIndex((i + 1) % nElemNodes)]; + MeshLib::Node* n2 = + _nodes[offset + nNodes + + elem->getNodeIndex((i + 1) % nElemNodes)]; + MeshLib::Node* n3 = + _nodes[offset + nNodes + elem->getNodeIndex(i)]; auto const v0 = Eigen::Map<Eigen::Vector3d const>(n0->getCoords()); @@ -159,13 +169,13 @@ void LayeredVolume::addLayerBoundaries(const MeshLib::Mesh &layer, std::size_t n { const std::array tri_nodes = {n0, n2, n1}; _elements.push_back(new MeshLib::Tri(tri_nodes)); - _materials.push_back(nLayers+j); + _materials.push_back(nLayers + j); } if ((v3 - v0).norm() > eps) { const std::array tri_nodes = {n0, n3, n2}; _elements.push_back(new MeshLib::Tri(tri_nodes)); - _materials.push_back(nLayers+j); + _materials.push_back(nLayers + j); } } } @@ -173,19 +183,20 @@ void LayeredVolume::addLayerBoundaries(const MeshLib::Mesh &layer, std::size_t n } } -void LayeredVolume::removeCongruentElements(std::size_t nLayers, std::size_t nElementsPerLayer) +void LayeredVolume::removeCongruentElements(std::size_t nLayers, + std::size_t nElementsPerLayer) { - for (std::size_t i=nLayers-1; i>0; --i) + for (std::size_t i = nLayers - 1; i > 0; --i) { - const std::size_t lower_offset ((i-1) * nElementsPerLayer); - const std::size_t upper_offset ( i * nElementsPerLayer); - for (std::size_t j=0; j<nElementsPerLayer; ++j) + const std::size_t lower_offset((i - 1) * nElementsPerLayer); + const std::size_t upper_offset(i * nElementsPerLayer); + for (std::size_t j = 0; j < nElementsPerLayer; ++j) { - MeshLib::Element const*const high (_elements[upper_offset+j]); - MeshLib::Element *const low (_elements[lower_offset+j]); + MeshLib::Element const* const high(_elements[upper_offset + j]); + MeshLib::Element* const low(_elements[lower_offset + j]); unsigned count(0); - const std::size_t nElemNodes (low->getNumberOfBaseNodes()); + const std::size_t nElemNodes(low->getNumberOfBaseNodes()); for (std::size_t k = 0; k < nElemNodes; ++k) { if (high->getNodeIndex(k) == low->getNodeIndex(k)) @@ -197,10 +208,10 @@ void LayeredVolume::removeCongruentElements(std::size_t nLayers, std::size_t nEl if (count == nElemNodes) { - delete _elements[upper_offset+j]; + delete _elements[upper_offset + j]; // mark element and material entries for deletion - _elements[upper_offset+j] = nullptr; - _materials[upper_offset+j] = -1; + _elements[upper_offset + j] = nullptr; + _materials[upper_offset + j] = -1; } else { @@ -214,7 +225,8 @@ void LayeredVolume::removeCongruentElements(std::size_t nLayers, std::size_t nEl } } // delete marked entries - auto elem_vec_end = std::remove(_elements.begin(), _elements.end(), nullptr); + auto elem_vec_end = + std::remove(_elements.begin(), _elements.end(), nullptr); _elements.erase(elem_vec_end, _elements.end()); auto mat_vec_end = std::remove(_materials.begin(), _materials.end(), -1); _materials.erase(mat_vec_end, _materials.end()); diff --git a/MeshLib/MeshGenerators/MeshGenerator.cpp b/MeshLib/MeshGenerators/MeshGenerator.cpp index 6143f2c8633d514769197f84cf642ce4a60acdb9..b85b549b977168427d208fd5c67e7df207f82cc1 100644 --- a/MeshLib/MeshGenerators/MeshGenerator.cpp +++ b/MeshLib/MeshGenerators/MeshGenerator.cpp @@ -25,9 +25,8 @@ namespace MeshLib { - std::vector<MeshLib::Node*> MeshGenerator::generateRegularNodes( - const std::vector<const std::vector<double>*> &vec_xyz_coords, + const std::vector<const std::vector<double>*>& vec_xyz_coords, const MathLib::Point3d& origin) { auto const shift_coordinates = [](auto const& in, auto& out, @@ -58,12 +57,11 @@ std::vector<MeshLib::Node*> MeshGenerator::generateRegularNodes( } std::vector<MeshLib::Node*> MeshGenerator::generateRegularNodes( - const std::vector<double> &vec_x_coords, - const MathLib::Point3d& origin) + const std::vector<double>& vec_x_coords, const MathLib::Point3d& origin) { std::vector<const std::vector<double>*> vec_xyz_coords; vec_xyz_coords.push_back(&vec_x_coords); - std::vector<double> dummy(1,0.0); + std::vector<double> dummy(1, 0.0); for (unsigned i = vec_xyz_coords.size() - 1; i < 3u; i++) { vec_xyz_coords.push_back(&dummy); @@ -72,14 +70,14 @@ std::vector<MeshLib::Node*> MeshGenerator::generateRegularNodes( } std::vector<MeshLib::Node*> MeshGenerator::generateRegularNodes( - std::vector<double> &vec_x_coords, - std::vector<double> &vec_y_coords, + std::vector<double>& vec_x_coords, + std::vector<double>& vec_y_coords, const MathLib::Point3d& origin) { std::vector<const std::vector<double>*> vec_xyz_coords; vec_xyz_coords.push_back(&vec_x_coords); vec_xyz_coords.push_back(&vec_y_coords); - std::vector<double> dummy(1,0.0); + std::vector<double> dummy(1, 0.0); for (unsigned i = vec_xyz_coords.size() - 1; i < 3u; i++) { vec_xyz_coords.push_back(&dummy); @@ -88,9 +86,9 @@ std::vector<MeshLib::Node*> MeshGenerator::generateRegularNodes( } std::vector<MeshLib::Node*> MeshGenerator::generateRegularNodes( - std::vector<double> &vec_x_coords, - std::vector<double> &vec_y_coords, - std::vector<double> &vec_z_coords, + std::vector<double>& vec_x_coords, + std::vector<double>& vec_y_coords, + std::vector<double>& vec_z_coords, const MathLib::Point3d& origin) { std::vector<const std::vector<double>*> vec_xyz_coords; @@ -101,22 +99,22 @@ std::vector<MeshLib::Node*> MeshGenerator::generateRegularNodes( } std::vector<MeshLib::Node*> MeshGenerator::generateRegularNodes( - const std::array<unsigned,3> &n_cells, - const std::array<double,3> &cell_size, + const std::array<unsigned, 3>& n_cells, + const std::array<double, 3>& cell_size, const MathLib::Point3d& origin) { std::vector<Node*> nodes; - nodes.reserve((n_cells[0]+1)*(n_cells[1]+1)*(n_cells[2]+1)); + nodes.reserve((n_cells[0] + 1) * (n_cells[1] + 1) * (n_cells[2] + 1)); - for (std::size_t i = 0; i < n_cells[2]+1; i++) + for (std::size_t i = 0; i < n_cells[2] + 1; i++) { - const double z (origin[2] + cell_size[2] * i); - for (std::size_t j = 0; j < n_cells[1]+1; j++) + const double z(origin[2] + cell_size[2] * i); + for (std::size_t j = 0; j < n_cells[1] + 1; j++) { - const double y (origin[1] + cell_size[1] * j); - for (std::size_t k = 0; k < n_cells[0]+1; k++) + const double y(origin[1] + cell_size[1] * j); + for (std::size_t k = 0; k < n_cells[0] + 1; k++) { - nodes.push_back (new Node(origin[0] + cell_size[0] * k, y, z)); + nodes.push_back(new Node(origin[0] + cell_size[0] * k, y, z)); } } } @@ -156,34 +154,34 @@ std::vector<MeshLib::Node*> generateRegularPyramidTopNodes( } } // end namespace MeshGenerator -Mesh* MeshGenerator::generateLineMesh( - const double length, - const std::size_t subdivision, - const MathLib::Point3d& origin, - std::string const& mesh_name) +Mesh* MeshGenerator::generateLineMesh(const double length, + const std::size_t subdivision, + const MathLib::Point3d& origin, + std::string const& mesh_name) { - return generateLineMesh(subdivision, length/subdivision, origin, mesh_name); + return generateLineMesh(subdivision, length / subdivision, origin, + mesh_name); } -Mesh* MeshGenerator::generateLineMesh( - const unsigned n_cells, - const double cell_size, - MathLib::Point3d const& origin, - std::string const& mesh_name) +Mesh* MeshGenerator::generateLineMesh(const unsigned n_cells, + const double cell_size, + MathLib::Point3d const& origin, + std::string const& mesh_name) { - return generateLineMesh(BaseLib::UniformSubdivision(n_cells*cell_size, n_cells), origin, mesh_name); + return generateLineMesh( + BaseLib::UniformSubdivision(n_cells * cell_size, n_cells), origin, + mesh_name); } -Mesh* MeshGenerator::generateLineMesh( - const BaseLib::ISubdivision &div, - MathLib::Point3d const& origin, - std::string const& mesh_name) +Mesh* MeshGenerator::generateLineMesh(const BaseLib::ISubdivision& div, + MathLib::Point3d const& origin, + std::string const& mesh_name) { const std::vector<double> vec_x(div()); std::vector<Node*> nodes(generateRegularNodes(vec_x, origin)); - //elements - const std::size_t n_cells = nodes.size()-1; + // elements + const std::size_t n_cells = nodes.size() - 1; std::vector<Element*> elements; elements.reserve(n_cells); @@ -195,65 +193,65 @@ Mesh* MeshGenerator::generateLineMesh( return new Mesh(mesh_name, nodes, elements); } -Mesh* MeshGenerator::generateRegularQuadMesh( - const double length, - const std::size_t subdivision, - const MathLib::Point3d& origin, - std::string const& mesh_name) +Mesh* MeshGenerator::generateRegularQuadMesh(const double length, + const std::size_t subdivision, + const MathLib::Point3d& origin, + std::string const& mesh_name) { return generateRegularQuadMesh(subdivision, subdivision, - length/subdivision, length/subdivision, origin, mesh_name); + length / subdivision, length / subdivision, + origin, mesh_name); } -Mesh* MeshGenerator::generateRegularQuadMesh( - const double x_length, - const double y_length, - const std::size_t x_subdivision, - const std::size_t y_subdivision, - const MathLib::Point3d& origin, - std::string const& mesh_name) +Mesh* MeshGenerator::generateRegularQuadMesh(const double x_length, + const double y_length, + const std::size_t x_subdivision, + const std::size_t y_subdivision, + const MathLib::Point3d& origin, + std::string const& mesh_name) { return generateRegularQuadMesh(x_subdivision, y_subdivision, - x_length/x_subdivision, y_length/y_subdivision, origin, mesh_name); + x_length / x_subdivision, + y_length / y_subdivision, origin, mesh_name); } -Mesh* MeshGenerator::generateRegularQuadMesh( - const unsigned n_x_cells, - const unsigned n_y_cells, - const double cell_size, - MathLib::Point3d const& origin, - std::string const& mesh_name) +Mesh* MeshGenerator::generateRegularQuadMesh(const unsigned n_x_cells, + const unsigned n_y_cells, + const double cell_size, + MathLib::Point3d const& origin, + std::string const& mesh_name) { - return generateRegularQuadMesh(n_x_cells, n_y_cells, cell_size, cell_size, origin, mesh_name); + return generateRegularQuadMesh(n_x_cells, n_y_cells, cell_size, cell_size, + origin, mesh_name); } -Mesh* MeshGenerator::generateRegularQuadMesh( - const unsigned n_x_cells, - const unsigned n_y_cells, - const double cell_size_x, - const double cell_size_y, - MathLib::Point3d const& origin, - std::string const& mesh_name) +Mesh* MeshGenerator::generateRegularQuadMesh(const unsigned n_x_cells, + const unsigned n_y_cells, + const double cell_size_x, + const double cell_size_y, + MathLib::Point3d const& origin, + std::string const& mesh_name) { - return generateRegularQuadMesh(BaseLib::UniformSubdivision(n_x_cells*cell_size_x, n_x_cells), - BaseLib::UniformSubdivision(n_y_cells*cell_size_y, n_y_cells), origin, mesh_name); + return generateRegularQuadMesh( + BaseLib::UniformSubdivision(n_x_cells * cell_size_x, n_x_cells), + BaseLib::UniformSubdivision(n_y_cells * cell_size_y, n_y_cells), origin, + mesh_name); } -Mesh* MeshGenerator::generateRegularQuadMesh( - const BaseLib::ISubdivision &div_x, - const BaseLib::ISubdivision &div_y, - MathLib::Point3d const& origin, - std::string const& mesh_name) +Mesh* MeshGenerator::generateRegularQuadMesh(const BaseLib::ISubdivision& div_x, + const BaseLib::ISubdivision& div_y, + MathLib::Point3d const& origin, + std::string const& mesh_name) { std::vector<double> vec_x(div_x()); std::vector<double> vec_y(div_y()); std::vector<Node*> nodes(generateRegularNodes(vec_x, vec_y, origin)); - const unsigned n_x_nodes (vec_x.size()); + const unsigned n_x_nodes(vec_x.size()); - //elements + // elements std::vector<Element*> elements; - const unsigned n_x_cells (vec_x.size()-1); - const unsigned n_y_cells (vec_y.size()-1); + const unsigned n_x_cells(vec_x.size() - 1); + const unsigned n_y_cells(vec_y.size() - 1); elements.reserve(n_x_cells * n_y_cells); for (std::size_t j = 0; j < n_y_cells; j++) @@ -271,85 +269,83 @@ Mesh* MeshGenerator::generateRegularQuadMesh( return new Mesh(mesh_name, nodes, elements); } -Mesh* MeshGenerator::generateRegularHexMesh( - const double length, - const std::size_t subdivision, - const MathLib::Point3d& origin, - std::string const& mesh_name) +Mesh* MeshGenerator::generateRegularHexMesh(const double length, + const std::size_t subdivision, + const MathLib::Point3d& origin, + std::string const& mesh_name) { - return MeshGenerator::generateRegularHexMesh(subdivision, subdivision, - subdivision, length/subdivision, origin, mesh_name); + return MeshGenerator::generateRegularHexMesh( + subdivision, subdivision, subdivision, length / subdivision, origin, + mesh_name); } -Mesh* MeshGenerator::generateRegularHexMesh( - const double x_length, - const double y_length, - const double z_length, - const std::size_t x_subdivision, - const std::size_t y_subdivision, - const std::size_t z_subdivision, - const MathLib::Point3d& origin, - std::string const& mesh_name) +Mesh* MeshGenerator::generateRegularHexMesh(const double x_length, + const double y_length, + const double z_length, + const std::size_t x_subdivision, + const std::size_t y_subdivision, + const std::size_t z_subdivision, + const MathLib::Point3d& origin, + std::string const& mesh_name) { - return MeshGenerator::generateRegularHexMesh(x_subdivision, y_subdivision, z_subdivision, - x_length/x_subdivision, y_length/y_subdivision, z_length/z_subdivision, origin, mesh_name); + return MeshGenerator::generateRegularHexMesh( + x_subdivision, y_subdivision, z_subdivision, x_length / x_subdivision, + y_length / y_subdivision, z_length / z_subdivision, origin, mesh_name); } -Mesh* MeshGenerator::generateRegularHexMesh( - const unsigned n_x_cells, - const unsigned n_y_cells, - const unsigned n_z_cells, - const double cell_size, - MathLib::Point3d const& origin, - std::string const& mesh_name) +Mesh* MeshGenerator::generateRegularHexMesh(const unsigned n_x_cells, + const unsigned n_y_cells, + const unsigned n_z_cells, + const double cell_size, + MathLib::Point3d const& origin, + std::string const& mesh_name) { - return MeshGenerator::generateRegularHexMesh(n_x_cells, n_y_cells, n_z_cells, - cell_size, cell_size, cell_size, origin, mesh_name); + return MeshGenerator::generateRegularHexMesh( + n_x_cells, n_y_cells, n_z_cells, cell_size, cell_size, cell_size, + origin, mesh_name); } -Mesh* MeshGenerator::generateRegularHexMesh( - const unsigned n_x_cells, - const unsigned n_y_cells, - const unsigned n_z_cells, - const double cell_size_x, - const double cell_size_y, - const double cell_size_z, - MathLib::Point3d const& origin, - std::string const& mesh_name) +Mesh* MeshGenerator::generateRegularHexMesh(const unsigned n_x_cells, + const unsigned n_y_cells, + const unsigned n_z_cells, + const double cell_size_x, + const double cell_size_y, + const double cell_size_z, + MathLib::Point3d const& origin, + std::string const& mesh_name) { return generateRegularHexMesh( - BaseLib::UniformSubdivision(n_x_cells*cell_size_x, n_x_cells), - BaseLib::UniformSubdivision(n_y_cells*cell_size_y, n_y_cells), - BaseLib::UniformSubdivision(n_z_cells*cell_size_z, n_z_cells), - origin, mesh_name); + BaseLib::UniformSubdivision(n_x_cells * cell_size_x, n_x_cells), + BaseLib::UniformSubdivision(n_y_cells * cell_size_y, n_y_cells), + BaseLib::UniformSubdivision(n_z_cells * cell_size_z, n_z_cells), origin, + mesh_name); } -Mesh* MeshGenerator::generateRegularHexMesh( - const BaseLib::ISubdivision &div_x, - const BaseLib::ISubdivision &div_y, - const BaseLib::ISubdivision &div_z, - MathLib::Point3d const& origin, - std::string const& mesh_name) +Mesh* MeshGenerator::generateRegularHexMesh(const BaseLib::ISubdivision& div_x, + const BaseLib::ISubdivision& div_y, + const BaseLib::ISubdivision& div_z, + MathLib::Point3d const& origin, + std::string const& mesh_name) { std::vector<double> vec_x(div_x()); std::vector<double> vec_y(div_y()); std::vector<double> vec_z(div_z()); std::vector<Node*> nodes(generateRegularNodes(vec_x, vec_y, vec_z, origin)); - const unsigned n_x_nodes (vec_x.size()); - const unsigned n_y_nodes (vec_y.size()); - const unsigned n_x_cells (vec_x.size()-1); - const unsigned n_y_cells (vec_y.size()-1); - const unsigned n_z_cells (vec_z.size()-1); + const unsigned n_x_nodes(vec_x.size()); + const unsigned n_y_nodes(vec_y.size()); + const unsigned n_x_cells(vec_x.size() - 1); + const unsigned n_y_cells(vec_y.size() - 1); + const unsigned n_z_cells(vec_z.size() - 1); - //elements + // elements std::vector<Element*> elements; elements.reserve(n_x_cells * n_y_cells * n_z_cells); for (std::size_t i = 0; i < n_z_cells; i++) { - const std::size_t offset_z1 = i * n_x_nodes * n_y_nodes; // bottom - const std::size_t offset_z2 = (i + 1) * n_x_nodes * n_y_nodes; // top + const std::size_t offset_z1 = i * n_x_nodes * n_y_nodes; // bottom + const std::size_t offset_z2 = (i + 1) * n_x_nodes * n_y_nodes; // top for (std::size_t j = 0; j < n_y_cells; j++) { const std::size_t offset_y1 = j * n_x_nodes; @@ -470,62 +466,63 @@ Mesh* MeshGenerator::generateRegularPyramidMesh( return new Mesh(mesh_name, nodes, elements); } -Mesh* MeshGenerator::generateRegularTriMesh( - const double length, - const std::size_t subdivision, - const MathLib::Point3d& origin, - std::string const& mesh_name) +Mesh* MeshGenerator::generateRegularTriMesh(const double length, + const std::size_t subdivision, + const MathLib::Point3d& origin, + std::string const& mesh_name) { - return generateRegularTriMesh(subdivision, subdivision, length/subdivision, origin, mesh_name); + return generateRegularTriMesh(subdivision, subdivision, + length / subdivision, origin, mesh_name); } -Mesh* MeshGenerator::generateRegularTriMesh( - const double x_length, - const double y_length, - const std::size_t x_subdivision, - const std::size_t y_subdivision, - const MathLib::Point3d& origin, - std::string const& mesh_name) +Mesh* MeshGenerator::generateRegularTriMesh(const double x_length, + const double y_length, + const std::size_t x_subdivision, + const std::size_t y_subdivision, + const MathLib::Point3d& origin, + std::string const& mesh_name) { - return generateRegularTriMesh(x_subdivision, y_subdivision, x_length/x_subdivision, y_length/y_subdivision, origin, mesh_name); + return generateRegularTriMesh(x_subdivision, y_subdivision, + x_length / x_subdivision, + y_length / y_subdivision, origin, mesh_name); } -Mesh* MeshGenerator::generateRegularTriMesh( - const unsigned n_x_cells, - const unsigned n_y_cells, - const double cell_size, - MathLib::Point3d const& origin, - std::string const& mesh_name) +Mesh* MeshGenerator::generateRegularTriMesh(const unsigned n_x_cells, + const unsigned n_y_cells, + const double cell_size, + MathLib::Point3d const& origin, + std::string const& mesh_name) { - return generateRegularTriMesh(n_x_cells, n_y_cells, cell_size, cell_size, origin, mesh_name); + return generateRegularTriMesh(n_x_cells, n_y_cells, cell_size, cell_size, + origin, mesh_name); } -Mesh* MeshGenerator::generateRegularTriMesh( - const unsigned n_x_cells, - const unsigned n_y_cells, - const double cell_size_x, - const double cell_size_y, - MathLib::Point3d const& origin, - std::string const& mesh_name) +Mesh* MeshGenerator::generateRegularTriMesh(const unsigned n_x_cells, + const unsigned n_y_cells, + const double cell_size_x, + const double cell_size_y, + MathLib::Point3d const& origin, + std::string const& mesh_name) { - return generateRegularTriMesh(BaseLib::UniformSubdivision(n_x_cells*cell_size_x, n_x_cells), - BaseLib::UniformSubdivision(n_y_cells*cell_size_y, n_y_cells), origin, mesh_name); + return generateRegularTriMesh( + BaseLib::UniformSubdivision(n_x_cells * cell_size_x, n_x_cells), + BaseLib::UniformSubdivision(n_y_cells * cell_size_y, n_y_cells), origin, + mesh_name); } -Mesh* MeshGenerator::generateRegularTriMesh( - const BaseLib::ISubdivision &div_x, - const BaseLib::ISubdivision &div_y, - MathLib::Point3d const& origin, - std::string const& mesh_name) +Mesh* MeshGenerator::generateRegularTriMesh(const BaseLib::ISubdivision& div_x, + const BaseLib::ISubdivision& div_y, + MathLib::Point3d const& origin, + std::string const& mesh_name) { std::vector<double> vec_x(div_x()); std::vector<double> vec_y(div_y()); std::vector<Node*> nodes(generateRegularNodes(vec_x, vec_y, origin)); - const unsigned n_x_nodes (vec_x.size()); - const unsigned n_x_cells (vec_x.size()-1); - const unsigned n_y_cells (vec_y.size()-1); + const unsigned n_x_nodes(vec_x.size()); + const unsigned n_x_cells(vec_x.size() - 1); + const unsigned n_y_cells(vec_y.size() - 1); - //elements + // elements std::vector<Element*> elements; elements.reserve(n_x_cells * n_y_cells * 2); @@ -548,115 +545,109 @@ Mesh* MeshGenerator::generateRegularTriMesh( return new Mesh(mesh_name, nodes, elements); } -Mesh* MeshGenerator::generateRegularPrismMesh( - const double x_length, - const double y_length, - const double z_length, - const std::size_t x_subdivision, - const std::size_t y_subdivision, - const std::size_t z_subdivision, - const MathLib::Point3d& origin, - std::string const& mesh_name) +Mesh* MeshGenerator::generateRegularPrismMesh(const double x_length, + const double y_length, + const double z_length, + const std::size_t x_subdivision, + const std::size_t y_subdivision, + const std::size_t z_subdivision, + const MathLib::Point3d& origin, + std::string const& mesh_name) { - return generateRegularPrismMesh(x_subdivision, y_subdivision, z_subdivision, - x_length/x_subdivision, y_length/y_subdivision, z_length/z_subdivision, - origin, mesh_name); + return generateRegularPrismMesh( + x_subdivision, y_subdivision, z_subdivision, x_length / x_subdivision, + y_length / y_subdivision, z_length / z_subdivision, origin, mesh_name); } -Mesh* MeshGenerator::generateRegularPrismMesh( - const unsigned n_x_cells, - const unsigned n_y_cells, - const unsigned n_z_cells, - const double cell_size, - MathLib::Point3d const& origin, - std::string const& mesh_name) +Mesh* MeshGenerator::generateRegularPrismMesh(const unsigned n_x_cells, + const unsigned n_y_cells, + const unsigned n_z_cells, + const double cell_size, + MathLib::Point3d const& origin, + std::string const& mesh_name) { - return generateRegularPrismMesh(n_x_cells, n_y_cells, n_z_cells, - cell_size, cell_size, cell_size, origin, mesh_name); + return generateRegularPrismMesh(n_x_cells, n_y_cells, n_z_cells, cell_size, + cell_size, cell_size, origin, mesh_name); } -Mesh* MeshGenerator::generateRegularPrismMesh( - const unsigned n_x_cells, - const unsigned n_y_cells, - const unsigned n_z_cells, - const double cell_size_x, - const double cell_size_y, - const double cell_size_z, - MathLib::Point3d const& origin, - std::string const& mesh_name) +Mesh* MeshGenerator::generateRegularPrismMesh(const unsigned n_x_cells, + const unsigned n_y_cells, + const unsigned n_z_cells, + const double cell_size_x, + const double cell_size_y, + const double cell_size_z, + MathLib::Point3d const& origin, + std::string const& mesh_name) { - std::unique_ptr<MeshLib::Mesh> mesh ( - generateRegularTriMesh(n_x_cells, n_y_cells, cell_size_x, cell_size_y, origin, mesh_name)); - std::size_t const n_tris (mesh->getNumberOfElements()); + std::unique_ptr<MeshLib::Mesh> mesh(generateRegularTriMesh( + n_x_cells, n_y_cells, cell_size_x, cell_size_y, origin, mesh_name)); + std::size_t const n_tris(mesh->getNumberOfElements()); bool const copy_material_ids = false; for (std::size_t i = 0; i < n_z_cells; ++i) { mesh.reset(MeshLib::addLayerToMesh(*mesh, cell_size_z, mesh_name, true, copy_material_ids)); } - std::vector<std::size_t> elem_ids (n_tris); + std::vector<std::size_t> elem_ids(n_tris); std::iota(elem_ids.begin(), elem_ids.end(), 0); return MeshLib::removeElements(*mesh, elem_ids, mesh_name); } -Mesh* MeshGenerator::generateRegularTetMesh( - const double x_length, - const double y_length, - const double z_length, - const std::size_t x_subdivision, - const std::size_t y_subdivision, - const std::size_t z_subdivision, - const MathLib::Point3d& origin, - std::string const& mesh_name) +Mesh* MeshGenerator::generateRegularTetMesh(const double x_length, + const double y_length, + const double z_length, + const std::size_t x_subdivision, + const std::size_t y_subdivision, + const std::size_t z_subdivision, + const MathLib::Point3d& origin, + std::string const& mesh_name) { - return generateRegularTetMesh(x_subdivision, y_subdivision, z_subdivision, - x_length/x_subdivision, y_length/y_subdivision, z_length/z_subdivision, - origin, mesh_name); + return generateRegularTetMesh( + x_subdivision, y_subdivision, z_subdivision, x_length / x_subdivision, + y_length / y_subdivision, z_length / z_subdivision, origin, mesh_name); } -Mesh* MeshGenerator::generateRegularTetMesh( - const unsigned n_x_cells, - const unsigned n_y_cells, - const unsigned n_z_cells, - const double cell_size_x, - const double cell_size_y, - const double cell_size_z, - MathLib::Point3d const& origin, - std::string const& mesh_name) +Mesh* MeshGenerator::generateRegularTetMesh(const unsigned n_x_cells, + const unsigned n_y_cells, + const unsigned n_z_cells, + const double cell_size_x, + const double cell_size_y, + const double cell_size_z, + MathLib::Point3d const& origin, + std::string const& mesh_name) { return generateRegularTetMesh( - BaseLib::UniformSubdivision(n_x_cells*cell_size_x, n_x_cells), - BaseLib::UniformSubdivision(n_y_cells*cell_size_y, n_y_cells), - BaseLib::UniformSubdivision(n_z_cells*cell_size_z, n_z_cells), - origin, mesh_name); + BaseLib::UniformSubdivision(n_x_cells * cell_size_x, n_x_cells), + BaseLib::UniformSubdivision(n_y_cells * cell_size_y, n_y_cells), + BaseLib::UniformSubdivision(n_z_cells * cell_size_z, n_z_cells), origin, + mesh_name); } -Mesh* MeshGenerator::generateRegularTetMesh( - const BaseLib::ISubdivision &div_x, - const BaseLib::ISubdivision &div_y, - const BaseLib::ISubdivision &div_z, - MathLib::Point3d const& origin, - std::string const& mesh_name) +Mesh* MeshGenerator::generateRegularTetMesh(const BaseLib::ISubdivision& div_x, + const BaseLib::ISubdivision& div_y, + const BaseLib::ISubdivision& div_z, + MathLib::Point3d const& origin, + std::string const& mesh_name) { std::vector<double> vec_x(div_x()); std::vector<double> vec_y(div_y()); std::vector<double> vec_z(div_z()); std::vector<Node*> nodes(generateRegularNodes(vec_x, vec_y, vec_z, origin)); - const unsigned n_x_nodes (vec_x.size()); - const unsigned n_y_nodes (vec_y.size()); - const unsigned n_x_cells (vec_x.size()-1); - const unsigned n_y_cells (vec_y.size()-1); - const unsigned n_z_cells (vec_z.size()-1); + const unsigned n_x_nodes(vec_x.size()); + const unsigned n_y_nodes(vec_y.size()); + const unsigned n_x_cells(vec_x.size() - 1); + const unsigned n_y_cells(vec_y.size() - 1); + const unsigned n_z_cells(vec_z.size() - 1); - //elements + // elements std::vector<Element*> elements; elements.reserve(n_x_cells * n_y_cells * n_z_cells * 6); for (std::size_t i = 0; i < n_z_cells; i++) { - const std::size_t offset_z1 = i * n_x_nodes * n_y_nodes; // bottom - const std::size_t offset_z2 = (i + 1) * n_x_nodes * n_y_nodes; // top + const std::size_t offset_z1 = i * n_x_nodes * n_y_nodes; // bottom + const std::size_t offset_z2 = (i + 1) * n_x_nodes * n_y_nodes; // top for (std::size_t j = 0; j < n_y_cells; j++) { const std::size_t offset_y1 = j * n_x_nodes; @@ -718,18 +709,19 @@ Mesh* MeshGenerator::generateRegularTetMesh( return new Mesh(mesh_name, nodes, elements); } -MeshLib::Mesh* -MeshGenerator::createSurfaceMesh(std::string const& mesh_name, - MathLib::Point3d const& ll, MathLib::Point3d const& ur, - std::array<std::size_t, 2> const& n_steps, - const std::function<double(double,double)>& f) +MeshLib::Mesh* MeshGenerator::createSurfaceMesh( + std::string const& mesh_name, MathLib::Point3d const& ll, + MathLib::Point3d const& ur, std::array<std::size_t, 2> const& n_steps, + const std::function<double(double, double)>& f) { - std::array<double, 2> step_size{{ - (ur[0]-ll[0])/(n_steps[0]-1), (ur[1]-ll[1])/(n_steps[1]-1)}}; + std::array<double, 2> step_size{{(ur[0] - ll[0]) / (n_steps[0] - 1), + (ur[1] - ll[1]) / (n_steps[1] - 1)}}; std::vector<MeshLib::Node*> nodes; - for (std::size_t j(0); j<n_steps[1]; ++j) { - for (std::size_t i(0); i<n_steps[0]; ++i) { + for (std::size_t j(0); j < n_steps[1]; ++j) + { + for (std::size_t i(0); i < n_steps[0]; ++i) + { std::size_t const id = i + j * n_steps[1]; double const x = ll[0] + i * step_size[0]; double const y = ll[1] + j * step_size[1]; @@ -739,12 +731,14 @@ MeshGenerator::createSurfaceMesh(std::string const& mesh_name, } std::vector<MeshLib::Element*> sfc_eles; - for (std::size_t j(0); j<n_steps[1]-1; ++j) { - for (std::size_t i(0); i<n_steps[0]-1; ++i) { - std::size_t id_ll(i+j*n_steps[0]); - std::size_t id_lr(i+1+j*n_steps[0]); - std::size_t id_ul(i+(j+1)*n_steps[0]); - std::size_t id_ur(i+1+(j+1)*n_steps[0]); + for (std::size_t j(0); j < n_steps[1] - 1; ++j) + { + for (std::size_t i(0); i < n_steps[0] - 1; ++i) + { + std::size_t id_ll(i + j * n_steps[0]); + std::size_t id_lr(i + 1 + j * n_steps[0]); + std::size_t id_ul(i + (j + 1) * n_steps[0]); + std::size_t id_ur(i + 1 + (j + 1) * n_steps[0]); sfc_eles.push_back( new MeshLib::Tri({nodes[id_ll], nodes[id_lr], nodes[id_ur]})); sfc_eles.push_back( diff --git a/MeshLib/MeshGenerators/MeshLayerMapper.cpp b/MeshLib/MeshGenerators/MeshLayerMapper.cpp index 893af8178d9325a38d7cbf7c7fd4f66615d7e2ec..1c7f87437852e44568239164252a20efcd0298e4 100644 --- a/MeshLib/MeshGenerators/MeshLayerMapper.cpp +++ b/MeshLib/MeshGenerators/MeshLayerMapper.cpp @@ -17,22 +17,20 @@ #include <algorithm> #include "BaseLib/Logging.h" - #include "GeoLib/Raster.h" - #include "MathLib/MathTools.h" - -#include "MeshLib/Elements/Tet.h" #include "MeshLib/Elements/Hex.h" -#include "MeshLib/Elements/Pyramid.h" #include "MeshLib/Elements/Prism.h" +#include "MeshLib/Elements/Pyramid.h" +#include "MeshLib/Elements/Tet.h" #include "MeshLib/MeshSurfaceExtraction.h" #include "MeshLib/Properties.h" namespace MeshLib { - -MeshLib::Mesh* MeshLayerMapper::createStaticLayers(MeshLib::Mesh const& mesh, std::vector<float> const& layer_thickness_vector, std::string const& mesh_name) +MeshLib::Mesh* MeshLayerMapper::createStaticLayers( + MeshLib::Mesh const& mesh, std::vector<float> const& layer_thickness_vector, + std::string const& mesh_name) { std::vector<float> thickness; for (std::size_t i = 0; i < layer_thickness_vector.size(); ++i) @@ -51,18 +49,22 @@ MeshLib::Mesh* MeshLayerMapper::createStaticLayers(MeshLib::Mesh const& mesh, st const std::size_t nLayers(thickness.size()); if (nLayers < 1 || mesh.getDimension() != 2) { - ERR("MeshLayerMapper::createStaticLayers(): A 2D mesh with nLayers > 0 is required as input."); + ERR("MeshLayerMapper::createStaticLayers(): A 2D mesh with nLayers > 0 " + "is required as input."); return nullptr; } const std::size_t nNodes = mesh.getNumberOfNodes(); // count number of 2d elements in the original mesh - const std::size_t nElems (std::count_if(mesh.getElements().begin(), mesh.getElements().end(), - [](MeshLib::Element const* elem) { return (elem->getDimension() == 2);})); - - const std::size_t nOrgElems (mesh.getNumberOfElements()); - const std::vector<MeshLib::Node*> &nodes = mesh.getNodes(); - const std::vector<MeshLib::Element*> &elems = mesh.getElements(); + const std::size_t nElems( + std::count_if(mesh.getElements().begin(), mesh.getElements().end(), + [](MeshLib::Element const* elem) { + return (elem->getDimension() == 2); + })); + + const std::size_t nOrgElems(mesh.getNumberOfElements()); + const std::vector<MeshLib::Node*>& nodes = mesh.getNodes(); + const std::vector<MeshLib::Element*>& elems = mesh.getElements(); std::vector<MeshLib::Node*> new_nodes(nNodes + (nLayers * nNodes)); std::vector<MeshLib::Element*> new_elems; new_elems.reserve(nElems * nLayers); @@ -76,32 +78,37 @@ MeshLib::Mesh* MeshLayerMapper::createStaticLayers(MeshLib::Mesh const& mesh, st } materials->reserve(nElems * nLayers); - double z_offset (0.0); + double z_offset(0.0); for (unsigned layer_id = 0; layer_id <= nLayers; ++layer_id) { // add nodes for new layer - unsigned node_offset (nNodes * layer_id); + unsigned node_offset(nNodes * layer_id); if (layer_id > 0) { z_offset += thickness[layer_id - 1]; } - std::transform(nodes.cbegin(), nodes.cend(), new_nodes.begin() + node_offset, - [&z_offset](MeshLib::Node* node){ return new MeshLib::Node((*node)[0], (*node)[1], (*node)[2]-z_offset); }); + std::transform(nodes.cbegin(), nodes.cend(), + new_nodes.begin() + node_offset, + [&z_offset](MeshLib::Node* node) { + return new MeshLib::Node((*node)[0], (*node)[1], + (*node)[2] - z_offset); + }); - // starting with 2nd layer create prism or hex elements connecting the last layer with the current one + // starting with 2nd layer create prism or hex elements connecting the + // last layer with the current one if (layer_id == 0) { continue; } node_offset -= nNodes; - const unsigned mat_id (nLayers - layer_id); + const unsigned mat_id(nLayers - layer_id); for (unsigned i = 0; i < nOrgElems; ++i) { - const MeshLib::Element* sfc_elem( elems[i] ); + const MeshLib::Element* sfc_elem(elems[i]); if (sfc_elem->getDimension() < 2) { // ignore line-elements continue; @@ -110,11 +117,12 @@ MeshLib::Mesh* MeshLayerMapper::createStaticLayers(MeshLib::Mesh const& mesh, st const unsigned nElemNodes(sfc_elem->getNumberOfBaseNodes()); auto** e_nodes = new MeshLib::Node*[2 * nElemNodes]; - for (unsigned j=0; j<nElemNodes; ++j) + for (unsigned j = 0; j < nElemNodes; ++j) { - const unsigned node_id = sfc_elem->getNode(j)->getID() + node_offset; - e_nodes[j] = new_nodes[node_id+nNodes]; - e_nodes[j+nElemNodes] = new_nodes[node_id]; + const unsigned node_id = + sfc_elem->getNode(j)->getID() + node_offset; + e_nodes[j] = new_nodes[node_id + nNodes]; + e_nodes[j + nElemNodes] = new_nodes[node_id]; } if (sfc_elem->getGeomType() == MeshLib::MeshElemType::TRIANGLE) { @@ -145,7 +153,8 @@ bool MeshLayerMapper::createRasterLayers( const std::size_t nLayers(rasters.size()); if (nLayers < 2 || mesh.getDimension() != 2) { - ERR("MeshLayerMapper::createRasterLayers(): A 2D mesh and at least two rasters required as input."); + ERR("MeshLayerMapper::createRasterLayers(): A 2D mesh and at least two " + "rasters required as input."); return false; } @@ -166,11 +175,13 @@ bool MeshLayerMapper::createRasterLayers( _nodes.reserve(nLayers * nNodes); // number of triangles in the original mesh - std::size_t const nElems (std::count_if(mesh.getElements().begin(), mesh.getElements().end(), - [](MeshLib::Element const* elem) - { return (elem->getGeomType() == MeshLib::MeshElemType::TRIANGLE);})); - _elements.reserve(nElems * (nLayers-1)); - _materials.reserve(nElems * (nLayers-1)); + std::size_t const nElems(std::count_if( + mesh.getElements().begin(), mesh.getElements().end(), + [](MeshLib::Element const* elem) { + return (elem->getGeomType() == MeshLib::MeshElemType::TRIANGLE); + })); + _elements.reserve(nElems * (nLayers - 1)); + _materials.reserve(nElems * (nLayers - 1)); // add bottom layer std::vector<MeshLib::Node*> const& nodes = bottom->getNodes(); @@ -186,13 +197,14 @@ bool MeshLayerMapper::createRasterLayers( return true; } -void MeshLayerMapper::addLayerToMesh(const MeshLib::Mesh &dem_mesh, unsigned layer_id, GeoLib::Raster const& raster) +void MeshLayerMapper::addLayerToMesh(const MeshLib::Mesh& dem_mesh, + unsigned layer_id, + GeoLib::Raster const& raster) { - const unsigned pyramid_base[3][4] = - { - {1, 3, 4, 2}, // Point 4 missing - {2, 4, 3, 0}, // Point 5 missing - {0, 3, 4, 1}, // Point 6 missing + const unsigned pyramid_base[3][4] = { + {1, 3, 4, 2}, // Point 4 missing + {2, 4, 3, 0}, // Point 5 missing + {0, 3, 4, 1}, // Point 6 missing }; std::size_t const nNodes = dem_mesh.getNumberOfNodes(); @@ -208,11 +220,11 @@ void MeshLayerMapper::addLayerToMesh(const MeshLib::Mesh &dem_mesh, unsigned lay } std::vector<MeshLib::Element*> const& elems = dem_mesh.getElements(); - std::size_t const nElems (dem_mesh.getNumberOfElements()); + std::size_t const nElems(dem_mesh.getNumberOfElements()); - for (std::size_t i=0; i<nElems; ++i) + for (std::size_t i = 0; i < nElems; ++i) { - MeshLib::Element* elem (elems[i]); + MeshLib::Element* elem(elems[i]); if (elem->getGeomType() != MeshLib::MeshElemType::TRIANGLE) { continue; @@ -220,10 +232,14 @@ void MeshLayerMapper::addLayerToMesh(const MeshLib::Mesh &dem_mesh, unsigned lay unsigned node_counter(3); unsigned missing_idx(0); std::array<MeshLib::Node*, 6> new_elem_nodes{}; - for (unsigned j=0; j<3; ++j) + for (unsigned j = 0; j < 3; ++j) { - new_elem_nodes[j] = _nodes[_nodes[last_layer_node_offset + elem->getNodeIndex(j)]->getID()]; - new_elem_nodes[node_counter] = (_nodes[last_layer_node_offset + elem->getNodeIndex(j) + nNodes]); + new_elem_nodes[j] = + _nodes[_nodes[last_layer_node_offset + elem->getNodeIndex(j)] + ->getID()]; + new_elem_nodes[node_counter] = + (_nodes[last_layer_node_offset + elem->getNodeIndex(j) + + nNodes]); if (new_elem_nodes[j]->getID() != new_elem_nodes[node_counter]->getID()) { @@ -237,32 +253,34 @@ void MeshLayerMapper::addLayerToMesh(const MeshLib::Mesh &dem_mesh, unsigned lay switch (node_counter) { - case 6: - _elements.push_back(new MeshLib::Prism(new_elem_nodes)); - _materials.push_back(layer_id); - break; - case 5: - { - std::array<MeshLib::Node*, 5> pyramid_nodes; - pyramid_nodes[0] = new_elem_nodes[pyramid_base[missing_idx][0]]; - pyramid_nodes[1] = new_elem_nodes[pyramid_base[missing_idx][1]]; - pyramid_nodes[2] = new_elem_nodes[pyramid_base[missing_idx][2]]; - pyramid_nodes[3] = new_elem_nodes[pyramid_base[missing_idx][3]]; - pyramid_nodes[4] = new_elem_nodes[missing_idx]; - _elements.push_back(new MeshLib::Pyramid(pyramid_nodes)); - _materials.push_back(layer_id); - break; - } - case 4: - { - std::array<MeshLib::Node*, 4> tet_nodes; - std::copy(new_elem_nodes.begin(), new_elem_nodes.begin() + node_counter, tet_nodes.begin()); - _elements.push_back(new MeshLib::Tet(tet_nodes)); - _materials.push_back(layer_id); - break; - } - default: - continue; + case 6: + _elements.push_back(new MeshLib::Prism(new_elem_nodes)); + _materials.push_back(layer_id); + break; + case 5: + { + std::array<MeshLib::Node*, 5> pyramid_nodes; + pyramid_nodes[0] = new_elem_nodes[pyramid_base[missing_idx][0]]; + pyramid_nodes[1] = new_elem_nodes[pyramid_base[missing_idx][1]]; + pyramid_nodes[2] = new_elem_nodes[pyramid_base[missing_idx][2]]; + pyramid_nodes[3] = new_elem_nodes[pyramid_base[missing_idx][3]]; + pyramid_nodes[4] = new_elem_nodes[missing_idx]; + _elements.push_back(new MeshLib::Pyramid(pyramid_nodes)); + _materials.push_back(layer_id); + break; + } + case 4: + { + std::array<MeshLib::Node*, 4> tet_nodes; + std::copy(new_elem_nodes.begin(), + new_elem_nodes.begin() + node_counter, + tet_nodes.begin()); + _elements.push_back(new MeshLib::Tet(tet_nodes)); + _materials.push_back(layer_id); + break; + } + default: + continue; } } } @@ -272,23 +290,24 @@ bool MeshLayerMapper::layerMapping(MeshLib::Mesh const& mesh, double const nodata_replacement, bool const ignore_nodata) { - if (mesh.getDimension() != 2) { ERR("MshLayerMapper::layerMapping() - requires 2D mesh"); return false; } - GeoLib::RasterHeader const& header (raster.getHeader()); + GeoLib::RasterHeader const& header(raster.getHeader()); const double x0(header.origin[0]); const double y0(header.origin[1]); const double delta(header.cell_size); - const std::pair<double, double> xDim(x0, x0 + header.n_cols * delta); // extension in x-dimension - const std::pair<double, double> yDim(y0, y0 + header.n_rows * delta); // extension in y-dimension + const std::pair<double, double> xDim( + x0, x0 + header.n_cols * delta); // extension in x-dimension + const std::pair<double, double> yDim( + y0, y0 + header.n_rows * delta); // extension in y-dimension - const std::size_t nNodes (mesh.getNumberOfNodes()); - const std::vector<MeshLib::Node*> &nodes = mesh.getNodes(); + const std::size_t nNodes(mesh.getNumberOfNodes()); + const std::vector<MeshLib::Node*>& nodes = mesh.getNodes(); for (unsigned i = 0; i < nNodes; ++i) { if (!ignore_nodata && !raster.isPntOnRaster(*nodes[i])) @@ -299,7 +318,7 @@ bool MeshLayerMapper::layerMapping(MeshLib::Mesh const& mesh, continue; } - double elevation (raster.getValueAtPoint(*nodes[i])); + double elevation(raster.getValueAtPoint(*nodes[i])); constexpr double eps = std::numeric_limits<double>::epsilon(); if (std::abs(elevation - header.no_data) < eps) { @@ -328,7 +347,7 @@ bool MeshLayerMapper::mapToStaticValue(MeshLib::Mesh const& mesh, return false; } - std::vector<MeshLib::Node*> const& nodes (mesh.getNodes()); + std::vector<MeshLib::Node*> const& nodes(mesh.getNodes()); for (MeshLib::Node* node : nodes) { node->updateCoordinates((*node)[0], (*node)[1], value); @@ -336,4 +355,4 @@ bool MeshLayerMapper::mapToStaticValue(MeshLib::Mesh const& mesh, return true; } -} // end namespace MeshLib +} // end namespace MeshLib diff --git a/MeshLib/MeshGenerators/RasterToMesh.cpp b/MeshLib/MeshGenerators/RasterToMesh.cpp index e010688f0ee4efe2a8591be7841b3750823a8786..4599e8b32ab917509dab8eed87d95ea9e990e58a 100644 --- a/MeshLib/MeshGenerators/RasterToMesh.cpp +++ b/MeshLib/MeshGenerators/RasterToMesh.cpp @@ -10,21 +10,20 @@ #include "RasterToMesh.h" -#include "BaseLib/Logging.h" +#include <vtkCell.h> +#include <vtkCellData.h> +#include <vtkDataArray.h> +#include <vtkImageData.h> +#include <vtkPointData.h> +#include <vtkSmartPointer.h> +#include "BaseLib/Logging.h" #include "MeshLib/Elements/Elements.h" #include "MeshLib/Mesh.h" -#include "MeshLib/Node.h" #include "MeshLib/MeshEditing/RemoveMeshComponents.h" #include "MeshLib/MeshGenerators/MeshGenerator.h" #include "MeshLib/MeshSearch/ElementSearch.h" - -#include <vtkImageData.h> -#include <vtkDataArray.h> -#include <vtkCell.h> -#include <vtkCellData.h> -#include <vtkSmartPointer.h> -#include <vtkPointData.h> +#include "MeshLib/Node.h" namespace MeshLib { @@ -34,7 +33,11 @@ std::unique_ptr<MeshLib::Mesh> RasterToMesh::convert( UseIntensityAs intensity_type, std::string const& array_name) { - return convert(raster.begin(), raster.getHeader(), elem_type, intensity_type, array_name); + return convert(raster.begin(), + raster.getHeader(), + elem_type, + intensity_type, + array_name); } std::unique_ptr<MeshLib::Mesh> RasterToMesh::convert( @@ -55,10 +58,12 @@ std::unique_ptr<MeshLib::Mesh> RasterToMesh::convert( } int* dims = img->GetDimensions(); - if (((elem_type == MeshElemType::TRIANGLE) || (elem_type == MeshElemType::QUAD)) && + if (((elem_type == MeshElemType::TRIANGLE) || + (elem_type == MeshElemType::QUAD)) && dims[2] != 1) { - ERR("Triangle or Quad elements cannot be used to construct meshes from 3D rasters."); + ERR("Triangle or Quad elements cannot be used to construct meshes from " + "3D rasters."); return nullptr; } @@ -67,7 +72,8 @@ std::unique_ptr<MeshLib::Mesh> RasterToMesh::convert( int nTuple = pixelData->GetNumberOfComponents(); if (nTuple < 1 || nTuple > 4) { - ERR("VtkMeshConverter::convertImgToMesh(): Unsupported pixel composition!"); + ERR("VtkMeshConverter::convertImgToMesh(): Unsupported pixel " + "composition!"); return nullptr; } @@ -84,14 +90,16 @@ std::unique_ptr<MeshLib::Mesh> RasterToMesh::convert( std::vector<double> pix(header.n_cols * header.n_rows * header.n_depth, 0); for (std::size_t k = 0; k < header.n_depth; k++) { - std::size_t const layer_idx = (k*header.n_rows*header.n_cols); + std::size_t const layer_idx = (k * header.n_rows * header.n_cols); for (std::size_t i = 0; i < header.n_rows; i++) { std::size_t const idx = i * header.n_cols + layer_idx; for (std::size_t j = 0; j < header.n_cols; j++) { double* colour = pixelData->GetTuple(idx + j); - bool const visible = (nTuple == 2 || nTuple == 4) ? (colour[nTuple - 1] != 0) : true; + bool const visible = (nTuple == 2 || nTuple == 4) + ? (colour[nTuple - 1] != 0) + : true; if (!visible) { pix[idx + j] = header.no_data; @@ -110,7 +118,7 @@ std::unique_ptr<MeshLib::Mesh> RasterToMesh::convert( } std::unique_ptr<MeshLib::Mesh> RasterToMesh::convert( - double const*const img, + double const* const img, GeoLib::RasterHeader const& header, MeshElemType elem_type, UseIntensityAs intensity_type, @@ -125,15 +133,18 @@ std::unique_ptr<MeshLib::Mesh> RasterToMesh::convert( return nullptr; } - if (((elem_type == MeshElemType::TRIANGLE) || (elem_type == MeshElemType::QUAD)) && + if (((elem_type == MeshElemType::TRIANGLE) || + (elem_type == MeshElemType::QUAD)) && header.n_depth != 1) { - ERR("Triangle or Quad elements cannot be used to construct meshes from 3D rasters."); + ERR("Triangle or Quad elements cannot be used to construct meshes from " + "3D rasters."); return nullptr; } if (intensity_type == UseIntensityAs::ELEVATION && - ((elem_type == MeshElemType::PRISM) || (elem_type == MeshElemType::HEXAHEDRON))) + ((elem_type == MeshElemType::PRISM) || + (elem_type == MeshElemType::HEXAHEDRON))) { ERR("Elevation mapping can only be performed for 2D meshes."); return nullptr; @@ -186,11 +197,12 @@ std::unique_ptr<MeshLib::Mesh> RasterToMesh::convert( std::vector<MeshLib::Node*> const& nodes(mesh->getNodes()); std::vector<MeshLib::Element*> const& elems(mesh->getElements()); std::size_t const n_nodes(elems[0]->getNumberOfNodes()); - bool const double_idx = (elem_type == MeshElemType::TRIANGLE) || (elem_type == MeshElemType::PRISM); + bool const double_idx = (elem_type == MeshElemType::TRIANGLE) || + (elem_type == MeshElemType::PRISM); std::size_t const m = (double_idx) ? 2 : 1; for (std::size_t k = 0; k < header.n_depth; k++) { - std::size_t const layer_idx = (k*header.n_rows*header.n_cols); + std::size_t const layer_idx = (k * header.n_rows * header.n_cols); for (std::size_t i = 0; i < header.n_cols; i++) { std::size_t const idx(i * header.n_rows + layer_idx); @@ -208,7 +220,8 @@ std::unique_ptr<MeshLib::Mesh> RasterToMesh::convert( } for (std::size_t n = 0; n < n_nodes; ++n) { - (*(nodes[elems[m * (idx + j)]->getNodeIndex(n)]))[2] = val; + (*(nodes[elems[m * (idx + j)]->getNodeIndex(n)]))[2] = + val; if (double_idx) { (*(nodes[elems[m * (idx + j) + 1]->getNodeIndex( @@ -221,14 +234,15 @@ std::unique_ptr<MeshLib::Mesh> RasterToMesh::convert( } else { - MeshLib::Properties &properties = mesh->getProperties(); + MeshLib::Properties& properties = mesh->getProperties(); MeshLib::ElementSearch ex(*mesh); if (array_name == "MaterialIDs") { auto* const prop_vec = properties.createNewPropertyVector<int>( array_name, MeshLib::MeshItemType::Cell, 1); fillPropertyVector<int>(*prop_vec, img, header, elem_type); - ex.searchByPropertyValue<int>(array_name, static_cast<int>(header.no_data)); + ex.searchByPropertyValue<int>(array_name, + static_cast<int>(header.no_data)); } else { @@ -257,4 +271,4 @@ std::unique_ptr<MeshLib::Mesh> RasterToMesh::convert( return new_mesh; } -} // end namespace MeshLib +} // end namespace MeshLib diff --git a/MeshLib/MeshGenerators/VtkMeshConverter.cpp b/MeshLib/MeshGenerators/VtkMeshConverter.cpp index 8204821ae995282b13303bc61b528e8951ec90fd..8c97daef1efe0a30350dc01bd2f501bfcd999650 100644 --- a/MeshLib/MeshGenerators/VtkMeshConverter.cpp +++ b/MeshLib/MeshGenerators/VtkMeshConverter.cpp @@ -322,15 +322,14 @@ void VtkMeshConverter::convertArray(vtkDataArray& array, if (vtkLongLongArray::SafeDownCast(&array)) { - VtkMeshConverter::convertTypedArray<long long>( - array, properties, type); + VtkMeshConverter::convertTypedArray<long long>(array, properties, type); return; } if (vtkUnsignedLongArray::SafeDownCast(&array)) { - VtkMeshConverter::convertTypedArray<unsigned long>( - array, properties, type); + VtkMeshConverter::convertTypedArray<unsigned long>(array, properties, + type); return; } diff --git a/MeshLib/MeshQuality/AngleSkewMetric.cpp b/MeshLib/MeshQuality/AngleSkewMetric.cpp index a52b0b0f1c6ef3a2de17c75e56b650a3ed6c6678..a8f77e37c2b5fa7c8b8edd4b77fc774bd5780468 100644 --- a/MeshLib/MeshQuality/AngleSkewMetric.cpp +++ b/MeshLib/MeshQuality/AngleSkewMetric.cpp @@ -14,18 +14,16 @@ #include "AngleSkewMetric.h" -#include <cmath> #include <boost/math/constants/constants.hpp> - -#include "MeshLib/Node.h" +#include <cmath> #include "MathLib/MathTools.h" +#include "MeshLib/Node.h" using namespace boost::math::double_constants; namespace MeshLib { - namespace { template <unsigned long N> @@ -144,9 +142,9 @@ double checkPrism(Element const& elem) } // end unnamed namespace -AngleSkewMetric::AngleSkewMetric(Mesh const& mesh) : - ElementQualityMetric(mesh) -{} +AngleSkewMetric::AngleSkewMetric(Mesh const& mesh) : ElementQualityMetric(mesh) +{ +} void AngleSkewMetric::calculateQuality() { @@ -178,4 +176,4 @@ void AngleSkewMetric::calculateQuality() } } -} // end namespace MeshLib +} // end namespace MeshLib diff --git a/MeshLib/MeshQuality/EdgeRatioMetric.cpp b/MeshLib/MeshQuality/EdgeRatioMetric.cpp index 4e24c4b9c8647d7bbd1fb3ddc852ca8ae0a3ff3b..7ad4a89ba67612d945f435282adc826e7c0a02fa 100644 --- a/MeshLib/MeshQuality/EdgeRatioMetric.cpp +++ b/MeshLib/MeshQuality/EdgeRatioMetric.cpp @@ -19,8 +19,7 @@ namespace MeshLib { -EdgeRatioMetric::EdgeRatioMetric(Mesh const& mesh) : - ElementQualityMetric(mesh) +EdgeRatioMetric::EdgeRatioMetric(Mesh const& mesh) : ElementQualityMetric(mesh) { } @@ -55,4 +54,4 @@ void EdgeRatioMetric::calculateQuality() } } -} // end namespace MeshLib +} // end namespace MeshLib diff --git a/MeshLib/MeshQuality/ElementSizeMetric.cpp b/MeshLib/MeshQuality/ElementSizeMetric.cpp index 29daa1c3731390f5acef61220b75e69a97f59118..3e6cd80225def3b0d375c7e8e8bc08c37055a164 100644 --- a/MeshLib/MeshQuality/ElementSizeMetric.cpp +++ b/MeshLib/MeshQuality/ElementSizeMetric.cpp @@ -19,8 +19,9 @@ namespace MeshLib { ElementSizeMetric::ElementSizeMetric(Mesh const& mesh) -: ElementQualityMetric(mesh) -{} + : ElementQualityMetric(mesh) +{ +} void ElementSizeMetric::calculateQuality() { @@ -50,7 +51,7 @@ void ElementSizeMetric::calculateQuality() std::size_t ElementSizeMetric::calc1dQuality() { - const std::vector<MeshLib::Element*> &elements(_mesh.getElements()); + const std::vector<MeshLib::Element*>& elements(_mesh.getElements()); const std::size_t nElems(elements.size()); std::size_t error_count(0); @@ -79,13 +80,13 @@ std::size_t ElementSizeMetric::calc1dQuality() std::size_t ElementSizeMetric::calc2dQuality() { - const std::vector<MeshLib::Element*> &elements(_mesh.getElements()); + const std::vector<MeshLib::Element*>& elements(_mesh.getElements()); const std::size_t nElems(elements.size()); std::size_t error_count(0); for (std::size_t k(0); k < nElems; k++) { - Element const& elem (*elements[k]); + Element const& elem(*elements[k]); if (elem.getDimension() == 1) { @@ -120,14 +121,14 @@ std::size_t ElementSizeMetric::calc3dQuality() for (std::size_t k(0); k < nElems; k++) { - Element const& elem (*elements[k]); - if (elem.getDimension()<3) + Element const& elem(*elements[k]); + if (elem.getDimension() < 3) { _element_quality_metric[k] = 0.0; continue; } - double const volume (elem.getContent()); + double const volume(elem.getContent()); if (volume < sqrt(std::abs(std::numeric_limits<double>::epsilon()))) { error_count++; @@ -146,4 +147,4 @@ std::size_t ElementSizeMetric::calc3dQuality() return error_count; } -} // end namespace MeshLib +} // end namespace MeshLib diff --git a/MeshLib/MeshQuality/MeshValidation.cpp b/MeshLib/MeshQuality/MeshValidation.cpp index 46b5e64b0b9c94a3dc05cb9e1dbbb5e3656e76d3..daa85d534c708d94f725e77614c4fef6d6a3187c 100644 --- a/MeshLib/MeshQuality/MeshValidation.cpp +++ b/MeshLib/MeshQuality/MeshValidation.cpp @@ -14,28 +14,28 @@ #include "MeshValidation.h" -#include <numeric> #include <algorithm> +#include <numeric> #include <stack> #include "BaseLib/Logging.h" - -#include "MeshLib/Mesh.h" -#include "MeshLib/Node.h" #include "MeshLib/Elements/Element.h" +#include "MeshLib/Mesh.h" #include "MeshLib/MeshEditing/MeshRevision.h" #include "MeshLib/MeshSearch/NodeSearch.h" #include "MeshLib/MeshSurfaceExtraction.h" +#include "MeshLib/Node.h" -namespace MeshLib { - -MeshValidation::MeshValidation(MeshLib::Mesh &mesh) +namespace MeshLib { - INFO ("Mesh Quality Control:"); - INFO ("Looking for unused nodes..."); +MeshValidation::MeshValidation(MeshLib::Mesh& mesh) +{ + INFO("Mesh Quality Control:"); + INFO("Looking for unused nodes..."); NodeSearch ns(mesh); ns.searchUnused(); - if (!ns.getSearchedNodeIDs().empty()) { + if (!ns.getSearchedNodeIDs().empty()) + { INFO("{:d} unused mesh nodes found.", ns.getSearchedNodeIDs().size()); } MeshRevision rev(mesh); @@ -53,19 +53,20 @@ MeshValidation::MeshValidation(MeshLib::Mesh &mesh) } } -std::vector<ElementErrorCode> MeshValidation::testElementGeometry(const MeshLib::Mesh &mesh, double min_volume) +std::vector<ElementErrorCode> MeshValidation::testElementGeometry( + const MeshLib::Mesh& mesh, double min_volume) { - INFO ("Testing mesh element geometry:"); + INFO("Testing mesh element geometry:"); const auto nErrorCodes( static_cast<std::size_t>(ElementErrorFlag::MaxValue)); unsigned error_count[nErrorCodes]; std::fill_n(error_count, 4, 0); - const std::size_t nElements (mesh.getNumberOfElements()); - const std::vector<MeshLib::Element*> &elements (mesh.getElements()); + const std::size_t nElements(mesh.getNumberOfElements()); + const std::vector<MeshLib::Element*>& elements(mesh.getElements()); std::vector<ElementErrorCode> error_code_vector; error_code_vector.reserve(nElements); - for (std::size_t i=0; i<nElements; ++i) + for (std::size_t i = 0; i < nElements; ++i) { const ElementErrorCode e = elements[i]->validate(); error_code_vector.push_back(e); @@ -75,14 +76,17 @@ std::vector<ElementErrorCode> MeshValidation::testElementGeometry(const MeshLib: } // increment error statistics - const std::bitset< static_cast<std::size_t>(ElementErrorFlag::MaxValue) > flags (static_cast< std::bitset<static_cast<std::size_t>(ElementErrorFlag::MaxValue)> >(e)); + const std::bitset<static_cast<std::size_t>(ElementErrorFlag::MaxValue)> + flags(static_cast<std::bitset<static_cast<std::size_t>( + ElementErrorFlag::MaxValue)>>(e)); for (unsigned j = 0; j < nErrorCodes; ++j) { error_count[j] += flags[j]; } } - // if a larger volume threshold is given, evaluate elements again to add them even if they are formally okay + // if a larger volume threshold is given, evaluate elements again to add + // them even if they are formally okay if (min_volume > std::numeric_limits<double>::epsilon()) { for (std::size_t i = 0; i < nElements; ++i) @@ -99,8 +103,9 @@ std::vector<ElementErrorCode> MeshValidation::testElementGeometry(const MeshLib: std::accumulate(error_count, error_count + nErrorCodes, 0.0))); if (error_sum != 0) { - ElementErrorFlag flags[nErrorCodes] = { ElementErrorFlag::ZeroVolume, ElementErrorFlag::NonCoplanar, - ElementErrorFlag::NonConvex, ElementErrorFlag::NodeOrder }; + ElementErrorFlag flags[nErrorCodes] = { + ElementErrorFlag::ZeroVolume, ElementErrorFlag::NonCoplanar, + ElementErrorFlag::NonConvex, ElementErrorFlag::NodeOrder}; for (std::size_t i = 0; i < nErrorCodes; ++i) { if (error_count[i]) @@ -113,13 +118,14 @@ std::vector<ElementErrorCode> MeshValidation::testElementGeometry(const MeshLib: } else { - INFO ("No errors found."); + INFO("No errors found."); } return error_code_vector; } std::array<std::string, static_cast<std::size_t>(ElementErrorFlag::MaxValue)> -MeshValidation::ElementErrorCodeOutput(const std::vector<ElementErrorCode> &error_codes) +MeshValidation::ElementErrorCodeOutput( + const std::vector<ElementErrorCode>& error_codes) { const auto nErrorFlags( static_cast<std::size_t>(ElementErrorFlag::MaxValue)); @@ -188,19 +194,21 @@ unsigned MeshValidation::detectHoles(MeshLib::Mesh const& mesh) return (--current_surface_id); } -void MeshValidation::trackSurface(MeshLib::Element const* element, std::vector<unsigned> &sfc_idx, unsigned const current_index) +void MeshValidation::trackSurface(MeshLib::Element const* element, + std::vector<unsigned>& sfc_idx, + unsigned const current_index) { std::stack<MeshLib::Element const*> elem_stack; elem_stack.push(element); while (!elem_stack.empty()) { - MeshLib::Element const*const elem = elem_stack.top(); + MeshLib::Element const* const elem = elem_stack.top(); elem_stack.pop(); sfc_idx[elem->getID()] = current_index; - std::size_t const n_neighbors (elem->getNumberOfNeighbors()); - for (std::size_t i=0; i<n_neighbors; ++i) + std::size_t const n_neighbors(elem->getNumberOfNeighbors()); + for (std::size_t i = 0; i < n_neighbors; ++i) { - MeshLib::Element const* neighbor (elem->getNeighbor(i)); + MeshLib::Element const* neighbor(elem->getNeighbor(i)); if (neighbor != nullptr && sfc_idx[neighbor->getID()] == std::numeric_limits<unsigned>::max()) { @@ -210,4 +218,4 @@ void MeshValidation::trackSurface(MeshLib::Element const* element, std::vector<u } } -} // end namespace MeshLib +} // end namespace MeshLib diff --git a/MeshLib/MeshQuality/RadiusEdgeRatioMetric.cpp b/MeshLib/MeshQuality/RadiusEdgeRatioMetric.cpp index 4bf3257f3fefeb425f511164d710b2186a29ba90..97edcf556754a03700e13e7fe0837e4665e1f624 100644 --- a/MeshLib/MeshQuality/RadiusEdgeRatioMetric.cpp +++ b/MeshLib/MeshQuality/RadiusEdgeRatioMetric.cpp @@ -19,19 +19,19 @@ namespace MeshLib { - RadiusEdgeRatioMetric::RadiusEdgeRatioMetric(Mesh const& mesh) -: ElementQualityMetric(mesh) -{} + : ElementQualityMetric(mesh) +{ +} -void RadiusEdgeRatioMetric::calculateQuality () +void RadiusEdgeRatioMetric::calculateQuality() { std::vector<MeshLib::Element*> const& elements(_mesh.getElements()); - std::size_t const nElements (_mesh.getNumberOfElements()); + std::size_t const nElements(_mesh.getNumberOfElements()); for (std::size_t k(0); k < nElements; k++) { - Element const& elem (*elements[k]); - std::size_t const n_nodes (elem.getNumberOfBaseNodes()); + Element const& elem(*elements[k]); + std::size_t const n_nodes(elem.getNumberOfBaseNodes()); std::vector<MathLib::Point3d*> pnts(n_nodes); std::copy_n(elem.getNodes(), n_nodes, pnts.begin()); GeoLib::MinimalBoundingSphere const s(pnts); @@ -40,4 +40,4 @@ void RadiusEdgeRatioMetric::calculateQuality () } } -} // end namespace MeshLib +} // end namespace MeshLib diff --git a/MeshLib/MeshQuality/SizeDifferenceMetric.cpp b/MeshLib/MeshQuality/SizeDifferenceMetric.cpp index 645a7d7e0cbf5f2ca93c93f943008542d3937d6d..84965d1714f9d69193245390888596dbb0932fc9 100644 --- a/MeshLib/MeshQuality/SizeDifferenceMetric.cpp +++ b/MeshLib/MeshQuality/SizeDifferenceMetric.cpp @@ -18,39 +18,40 @@ namespace MeshLib { - -SizeDifferenceMetric::SizeDifferenceMetric(Mesh const& mesh) : -ElementQualityMetric(mesh) -{ } +SizeDifferenceMetric::SizeDifferenceMetric(Mesh const& mesh) + : ElementQualityMetric(mesh) +{ +} void SizeDifferenceMetric::calculateQuality() { std::vector<MeshLib::Element*> const& elements(_mesh.getElements()); - std::size_t const nElements (_mesh.getNumberOfElements()); - std::size_t const mesh_dim (_mesh.getDimension()); + std::size_t const nElements(_mesh.getNumberOfElements()); + std::size_t const mesh_dim(_mesh.getDimension()); - for (std::size_t k=0; k < nElements; ++k) + for (std::size_t k = 0; k < nElements; ++k) { - Element const& elem (*elements[k]); + Element const& elem(*elements[k]); if (elem.getDimension() < mesh_dim) { _element_quality_metric[k] = 0; continue; } - std::size_t const n_neighbors (elem.getNumberOfNeighbors()); - double const vol_a (elem.getContent()); + std::size_t const n_neighbors(elem.getNumberOfNeighbors()); + double const vol_a(elem.getContent()); double worst_ratio(1.0); - for (std::size_t i=0; i < n_neighbors; ++i) + for (std::size_t i = 0; i < n_neighbors; ++i) { - MeshLib::Element const*const neighbor (elem.getNeighbor(i)); + MeshLib::Element const* const neighbor(elem.getNeighbor(i)); if (neighbor == nullptr) { continue; } - double const vol_b (neighbor->getContent()); - double const ratio = (vol_a > vol_b) ? vol_b / vol_a : vol_a / vol_b; + double const vol_b(neighbor->getContent()); + double const ratio = + (vol_a > vol_b) ? vol_b / vol_a : vol_a / vol_b; if (ratio < worst_ratio) { worst_ratio = ratio; @@ -60,4 +61,4 @@ void SizeDifferenceMetric::calculateQuality() } } -} // end namespace MeshLib +} // end namespace MeshLib diff --git a/MeshLib/MeshSearch/ElementSearch.cpp b/MeshLib/MeshSearch/ElementSearch.cpp index 025460c8c58eb7f3f512fb6612a50a40b56e8528..7e5c8874790392bf3db578605f7347b03501cdfe 100644 --- a/MeshLib/MeshSearch/ElementSearch.cpp +++ b/MeshLib/MeshSearch/ElementSearch.cpp @@ -14,19 +14,17 @@ #include "MeshLib/Elements/Element.h" #include "MeshLib/Node.h" -namespace MeshLib { - -ElementSearch::ElementSearch(const MeshLib::Mesh &mesh) - : _mesh(mesh) +namespace MeshLib { -} +ElementSearch::ElementSearch(const MeshLib::Mesh& mesh) : _mesh(mesh) {} template <typename Container, typename Predicate> std::vector<std::size_t> filter(Container const& container, Predicate const& p) { std::vector<std::size_t> matchedIDs; std::size_t i = 0; - for (auto value : container) { + for (auto value : container) + { if (p(value)) { matchedIDs.push_back(i); @@ -38,8 +36,9 @@ std::vector<std::size_t> filter(Container const& container, Predicate const& p) std::size_t ElementSearch::searchByElementType(MeshElemType eleType) { - auto matchedIDs = filter(_mesh.getElements(), - [&](MeshLib::Element* e) { return e->getGeomType()==eleType; }); + auto matchedIDs = filter(_mesh.getElements(), [&](MeshLib::Element* e) { + return e->getGeomType() == eleType; + }); this->updateUnion(matchedIDs); return matchedIDs.size(); @@ -47,34 +46,34 @@ std::size_t ElementSearch::searchByElementType(MeshElemType eleType) std::size_t ElementSearch::searchByContent(double eps) { - auto matchedIDs = filter(_mesh.getElements(), - [&eps](MeshLib::Element* e) { return e->getContent() < eps; }); + auto matchedIDs = filter(_mesh.getElements(), [&eps](MeshLib::Element* e) { + return e->getContent() < eps; + }); this->updateUnion(matchedIDs); return matchedIDs.size(); } -std::size_t ElementSearch::searchByBoundingBox( - GeoLib::AABB const& aabb) +std::size_t ElementSearch::searchByBoundingBox(GeoLib::AABB const& aabb) { - auto matchedIDs = filter(_mesh.getElements(), - [&aabb](MeshLib::Element* e) { - std::size_t const nElemNodes (e->getNumberOfBaseNodes()); - for (std::size_t n = 0; n < nElemNodes; ++n) + auto matchedIDs = filter(_mesh.getElements(), [&aabb](MeshLib::Element* e) { + std::size_t const nElemNodes(e->getNumberOfBaseNodes()); + for (std::size_t n = 0; n < nElemNodes; ++n) + { + if (aabb.containsPoint(*e->getNode(n), 0)) { - if (aabb.containsPoint(*e->getNode(n), 0)) - { - return true; // any node of element is in aabb. - } + return true; // any node of element is in aabb. } - return false; // no nodes of element are in aabb. - }); + } + return false; // no nodes of element are in aabb. + }); this->updateUnion(matchedIDs); return matchedIDs.size(); } -std::size_t ElementSearch::searchByNodeIDs(const std::vector<std::size_t> &nodes) +std::size_t ElementSearch::searchByNodeIDs( + const std::vector<std::size_t>& nodes) { std::vector<std::size_t> connected_elements; for (std::size_t node_id : nodes) @@ -91,12 +90,13 @@ std::size_t ElementSearch::searchByNodeIDs(const std::vector<std::size_t> &nodes return connected_elements.size(); } -void ElementSearch::updateUnion(const std::vector<std::size_t> &vec) +void ElementSearch::updateUnion(const std::vector<std::size_t>& vec) { std::vector<std::size_t> vec_temp(vec.size() + _marked_elements.size()); - auto it = std::set_union(vec.begin(), vec.end(), _marked_elements.begin(), _marked_elements.end(), vec_temp.begin()); + auto it = std::set_union(vec.begin(), vec.end(), _marked_elements.begin(), + _marked_elements.end(), vec_temp.begin()); vec_temp.resize(it - vec_temp.begin()); _marked_elements.assign(vec_temp.begin(), vec_temp.end()); } -} // end namespace MeshLib +} // end namespace MeshLib diff --git a/MeshLib/MeshSearch/MeshElementGrid.cpp b/MeshLib/MeshSearch/MeshElementGrid.cpp index 0aa33c7554d144958547a50a731861ce8151b4d1..1599a65ff50fe006b34da9b5ec00bc56eab8a688 100644 --- a/MeshLib/MeshSearch/MeshElementGrid.cpp +++ b/MeshLib/MeshSearch/MeshElementGrid.cpp @@ -15,11 +15,10 @@ #include <cmath> #include <memory> -#include "../Mesh.h" -#include "../Node.h" -#include "../Elements/Element.h" - #include "GeoLib/GEOObjects.h" +#include "MeshLib/Elements/Element.h" +#include "MeshLib/Mesh.h" +#include "MeshLib/Node.h" namespace MeshLib { @@ -27,13 +26,14 @@ MeshElementGrid::MeshElementGrid(MeshLib::Mesh const& mesh) : _aabb{mesh.getNodes().cbegin(), mesh.getNodes().cend()}, _n_steps({{1, 1, 1}}) { - auto getDimensions = - [](MathLib::Point3d const& min, MathLib::Point3d const& max) - { + auto getDimensions = [](MathLib::Point3d const& min, + MathLib::Point3d const& max) { std::bitset<3> dim; // all bits are set to zero. - for (std::size_t k(0); k < 3; ++k) { + for (std::size_t k(0); k < 3; ++k) + { double const tolerance( - std::nexttoward(max[k],std::numeric_limits<double>::max())-max[k]); + std::nexttoward(max[k], std::numeric_limits<double>::max()) - + max[k]); if (std::abs(max[k] - min[k]) > tolerance) { dim[k] = true; @@ -46,58 +46,76 @@ MeshElementGrid::MeshElementGrid(MeshLib::Mesh const& mesh) MathLib::Point3d const& max_pnt(_aabb.getMaxPoint()); auto const dim = getDimensions(min_pnt, max_pnt); - std::array<double, 3> delta{{ max_pnt[0] - min_pnt[0], - max_pnt[1] - min_pnt[1], max_pnt[2] - min_pnt[2] }}; + std::array<double, 3> delta{{max_pnt[0] - min_pnt[0], + max_pnt[1] - min_pnt[1], + max_pnt[2] - min_pnt[2]}}; const std::size_t n_eles(mesh.getNumberOfElements()); const std::size_t n_eles_per_cell(100); // *** condition: n_eles / n_cells < n_eles_per_cell // where n_cells = _n_steps[0] * _n_steps[1] * _n_steps[2] - // *** with _n_steps[0] = ceil(pow(n_eles*delta[0]*delta[0]/(n_eles_per_cell*delta[1]*delta[2]), 1/3.))); + // *** with _n_steps[0] = + // ceil(pow(n_eles*delta[0]*delta[0]/(n_eles_per_cell*delta[1]*delta[2]), + // 1/3.))); // _n_steps[1] = _n_steps[0] * delta[1]/delta[0], // _n_steps[2] = _n_steps[0] * delta[2]/delta[0] - auto sc_ceil = [](double v){ + auto sc_ceil = [](double v) { return static_cast<std::size_t>(std::ceil(v)); }; - switch (dim.count()) { - case 3: // 3d case - _n_steps[0] = sc_ceil(std::cbrt( - n_eles*delta[0]*delta[0]/(n_eles_per_cell*delta[1]*delta[2]))); - _n_steps[1] = sc_ceil(_n_steps[0] * std::min(delta[1] / delta[0], 100.0)); - _n_steps[2] = sc_ceil(_n_steps[0] * std::min(delta[2] / delta[0], 100.0)); - break; - case 2: // 2d cases - if (dim[0] && dim[2]) { // 2d case: xz plane, y = const - _n_steps[0] = sc_ceil(std::sqrt(n_eles*delta[0]/(n_eles_per_cell*delta[2]))); - _n_steps[2] = sc_ceil(_n_steps[0]*delta[2]/delta[0]); - } - else if (dim[0] && dim[1]) { // 2d case: xy plane, z = const - _n_steps[0] = sc_ceil(std::sqrt(n_eles*delta[0]/(n_eles_per_cell*delta[1]))); - _n_steps[1] = sc_ceil(_n_steps[0] * delta[1]/delta[0]); - } - else if (dim[1] && dim[2]) { // 2d case: yz plane, x = const - _n_steps[1] = sc_ceil(std::sqrt(n_eles*delta[1]/(n_eles_per_cell*delta[2]))); - _n_steps[2] = sc_ceil(n_eles * delta[2] / (n_eles_per_cell*delta[1])); - } - break; - case 1: // 1d cases - for (std::size_t k(0); k<3; ++k) { - if (dim[k]) { - _n_steps[k] = sc_ceil(static_cast<double>(n_eles)/n_eles_per_cell); + switch (dim.count()) + { + case 3: // 3d case + _n_steps[0] = + sc_ceil(std::cbrt(n_eles * delta[0] * delta[0] / + (n_eles_per_cell * delta[1] * delta[2]))); + _n_steps[1] = + sc_ceil(_n_steps[0] * std::min(delta[1] / delta[0], 100.0)); + _n_steps[2] = + sc_ceil(_n_steps[0] * std::min(delta[2] / delta[0], 100.0)); + break; + case 2: // 2d cases + if (dim[0] && dim[2]) + { // 2d case: xz plane, y = const + _n_steps[0] = sc_ceil(std::sqrt(n_eles * delta[0] / + (n_eles_per_cell * delta[2]))); + _n_steps[2] = sc_ceil(_n_steps[0] * delta[2] / delta[0]); + } + else if (dim[0] && dim[1]) + { // 2d case: xy plane, z = const + _n_steps[0] = sc_ceil(std::sqrt(n_eles * delta[0] / + (n_eles_per_cell * delta[1]))); + _n_steps[1] = sc_ceil(_n_steps[0] * delta[1] / delta[0]); + } + else if (dim[1] && dim[2]) + { // 2d case: yz plane, x = const + _n_steps[1] = sc_ceil(std::sqrt(n_eles * delta[1] / + (n_eles_per_cell * delta[2]))); + _n_steps[2] = + sc_ceil(n_eles * delta[2] / (n_eles_per_cell * delta[1])); + } + break; + case 1: // 1d cases + for (std::size_t k(0); k < 3; ++k) + { + if (dim[k]) + { + _n_steps[k] = + sc_ceil(static_cast<double>(n_eles) / n_eles_per_cell); + } } - } } // some frequently used expressions to fill the vector of elements per grid // cell - for (std::size_t k(0); k<3; k++) { + for (std::size_t k(0); k < 3; k++) + { _step_sizes[k] = delta[k] / _n_steps[k]; _inverse_step_sizes[k] = 1.0 / _step_sizes[k]; } - _elements_in_grid_box.resize(_n_steps[0]*_n_steps[1]*_n_steps[2]); + _elements_in_grid_box.resize(_n_steps[0] * _n_steps[1] * _n_steps[2]); sortElementsInGridCells(mesh); } @@ -115,7 +133,8 @@ void MeshElementGrid::sortElementsInGridCells(MeshLib::Mesh const& mesh) { for (auto const element : mesh.getElements()) { - if (! sortElementInGridCells(*element)) { + if (!sortElementInGridCells(*element)) + { OGS_FATAL("Sorting element (id={:d}) into mesh element grid.", element->getID()); } @@ -124,20 +143,25 @@ void MeshElementGrid::sortElementsInGridCells(MeshLib::Mesh const& mesh) bool MeshElementGrid::sortElementInGridCells(MeshLib::Element const& element) { - std::array<std::size_t,3> min{}; - std::array<std::size_t,3> max{}; - std::pair<bool, std::array<std::size_t, 3>> c( - getGridCellCoordinates(*(static_cast<MathLib::Point3d const*>(element.getNode(0))))); - if (c.first) { + std::array<std::size_t, 3> min{}; + std::array<std::size_t, 3> max{}; + std::pair<bool, std::array<std::size_t, 3>> c(getGridCellCoordinates( + *(static_cast<MathLib::Point3d const*>(element.getNode(0))))); + if (c.first) + { min = c.second; max = min; - } else { + } + else + { return false; } - for (std::size_t k(1); k<element.getNumberOfNodes(); ++k) { + for (std::size_t k(1); k < element.getNumberOfNodes(); ++k) + { // compute coordinates of the grid for each node of the element - c = getGridCellCoordinates(*(static_cast<MathLib::Point3d const*>(element.getNode(k)))); + c = getGridCellCoordinates( + *(static_cast<MathLib::Point3d const*>(element.getNode(k)))); if (!c.first) { return false; @@ -156,7 +180,7 @@ bool MeshElementGrid::sortElementInGridCells(MeshLib::Element const& element) } } - const std::size_t n_plane(_n_steps[0]*_n_steps[1]); + const std::size_t n_plane(_n_steps[0] * _n_steps[1]); // If a node of an element is almost equal to the upper right point of the // AABB the grid cell coordinates computed by getGridCellCoordintes() could @@ -168,10 +192,14 @@ bool MeshElementGrid::sortElementInGridCells(MeshLib::Element const& element) } // insert the element into the grid cells - for (std::size_t i(min[0]); i<=max[0]; i++) { - for (std::size_t j(min[1]); j<=max[1]; j++) { - for (std::size_t k(min[2]); k<=max[2]; k++) { - _elements_in_grid_box[i+j*_n_steps[0]+k*n_plane].push_back(&element); + for (std::size_t i(min[0]); i <= max[0]; i++) + { + for (std::size_t j(min[1]); j <= max[1]; j++) + { + for (std::size_t k(min[2]); k <= max[2]; k++) + { + _elements_in_grid_box[i + j * _n_steps[0] + k * n_plane] + .push_back(&element); } } } @@ -185,15 +213,21 @@ MeshElementGrid::getGridCellCoordinates(MathLib::Point3d const& p) const bool valid(true); std::array<std::size_t, 3> coords{}; - for (std::size_t k(0); k<3; ++k) { - const double d(p[k]-_aabb.getMinPoint()[k]); - if (d < 0.0) { + for (std::size_t k(0); k < 3; ++k) + { + const double d(p[k] - _aabb.getMinPoint()[k]); + if (d < 0.0) + { valid = false; coords[k] = 0; - } else if (_aabb.getMaxPoint()[k] <= p[k]) { + } + else if (_aabb.getMaxPoint()[k] <= p[k]) + { valid = false; - coords[k] = _n_steps[k]-1; - } else { + coords[k] = _n_steps[k] - 1; + } + else + { coords[k] = static_cast<std::size_t>(d * _inverse_step_sizes[k]); } } diff --git a/MeshLib/MeshSearch/NodeSearch.cpp b/MeshLib/MeshSearch/NodeSearch.cpp index 68f5034f75250921a16fed7fd3d431b6b5e8158e..d5d5b58c7db5f29150460cfefb0f6a3c242f0274 100644 --- a/MeshLib/MeshSearch/NodeSearch.cpp +++ b/MeshLib/MeshSearch/NodeSearch.cpp @@ -13,19 +13,16 @@ #include <memory> #include <set> +#include "MeshLib/Elements/Element.h" #include "MeshLib/Mesh.h" #include "MeshLib/Node.h" -#include "MeshLib/Elements/Element.h" -namespace MeshLib { - -NodeSearch::NodeSearch(const MeshLib::Mesh &mesh) - : _mesh(mesh) +namespace MeshLib { -} +NodeSearch::NodeSearch(const MeshLib::Mesh& mesh) : _mesh(mesh) {} std::size_t NodeSearch::searchNodesConnectedToOnlyGivenElements( - const std::vector<std::size_t> &elements) + const std::vector<std::size_t>& elements) { // Find out by how many elements a node would be removed. // @@ -33,19 +30,19 @@ std::size_t NodeSearch::searchNodesConnectedToOnlyGivenElements( // algorithm might be more memory efficient. std::vector<std::size_t> node_marked_counts(_mesh.getNumberOfNodes(), 0); - for(std::size_t eid : elements) + for (std::size_t eid : elements) { auto* e = _mesh.getElement(eid); - for (unsigned i=0; i<e->getNumberOfNodes(); i++) { + for (unsigned i = 0; i < e->getNumberOfNodes(); i++) + { node_marked_counts[e->getNodeIndex(i)]++; } } - // Push back nodes which counts are equal to number of connected elements to // that node. std::vector<std::size_t> connected_nodes; - for (std::size_t i=0; i<node_marked_counts.size(); i++) + for (std::size_t i = 0; i < node_marked_counts.size(); i++) { if (node_marked_counts[i] == _mesh.getNode(i)->getElements().size()) { @@ -59,8 +56,8 @@ std::size_t NodeSearch::searchNodesConnectedToOnlyGivenElements( std::size_t NodeSearch::searchUnused() { - const std::size_t nNodes (_mesh.getNumberOfNodes()); - const std::vector<MeshLib::Node*> &nodes (_mesh.getNodes()); + const std::size_t nNodes(_mesh.getNumberOfNodes()); + const std::vector<MeshLib::Node*>& nodes(_mesh.getNodes()); std::vector<std::size_t> del_node_idx; for (unsigned i = 0; i < nNodes; ++i) @@ -101,8 +98,8 @@ std::size_t NodeSearch::searchBoundaryNodes() continue; } - std::size_t const n_edges (elem->getNumberOfEdges()); - for (std::size_t i=0; i<n_edges; ++i) + std::size_t const n_edges(elem->getNumberOfEdges()); + for (std::size_t i = 0; i < n_edges; ++i) { if (elem->getNeighbor(i) != nullptr) { @@ -129,8 +126,8 @@ std::size_t NodeSearch::searchBoundaryNodes() continue; } - std::size_t const n_faces (elem->getNumberOfFaces()); - for (std::size_t i=0; i<n_faces; ++i) + std::size_t const n_faces(elem->getNumberOfFaces()); + for (std::size_t i = 0; i < n_faces; ++i) { if (elem->getNeighbor(i) != nullptr) { @@ -145,17 +142,19 @@ std::size_t NodeSearch::searchBoundaryNodes() } } std::sort(vec_boundary_nodes.begin(), vec_boundary_nodes.end()); - vec_boundary_nodes.erase(std::unique(vec_boundary_nodes.begin(), vec_boundary_nodes.end()), vec_boundary_nodes.end()); - + vec_boundary_nodes.erase( + std::unique(vec_boundary_nodes.begin(), vec_boundary_nodes.end()), + vec_boundary_nodes.end()); this->updateUnion(vec_boundary_nodes); return vec_boundary_nodes.size(); } -void NodeSearch::updateUnion(const std::vector<std::size_t> &vec) +void NodeSearch::updateUnion(const std::vector<std::size_t>& vec) { std::vector<std::size_t> vec_temp(vec.size() + _marked_nodes.size()); - auto it = std::set_union(vec.begin(), vec.end(), _marked_nodes.begin(), _marked_nodes.end(), vec_temp.begin()); + auto it = std::set_union(vec.begin(), vec.end(), _marked_nodes.begin(), + _marked_nodes.end(), vec_temp.begin()); vec_temp.resize(it - vec_temp.begin()); _marked_nodes.assign(vec_temp.begin(), vec_temp.end()); } @@ -173,10 +172,9 @@ std::vector<Node*> getUniqueNodes(std::vector<Element*> const& elements) std::vector<Node*> nodes; nodes.reserve(nodes_set.size()); - std::move(nodes_set.cbegin(), nodes_set.cend(), - std::back_inserter(nodes)); + std::move(nodes_set.cbegin(), nodes_set.cend(), std::back_inserter(nodes)); return nodes; } -} // end namespace MeshLib +} // end namespace MeshLib diff --git a/MeshLib/MeshSurfaceExtraction.cpp b/MeshLib/MeshSurfaceExtraction.cpp index 13939a2f9743f219bda400d5dbc7877e5170f79c..6ff19b802c755449659a89c8afbd9ed98800f02d 100644 --- a/MeshLib/MeshSurfaceExtraction.cpp +++ b/MeshLib/MeshSurfaceExtraction.cpp @@ -15,9 +15,9 @@ #include "MeshSurfaceExtraction.h" #include <boost/math/constants/constants.hpp> -#include "BaseLib/Logging.h" #include <memory> +#include "BaseLib/Logging.h" #include "MeshLib/Elements/Line.h" #include "MeshLib/Elements/Point.h" #include "MeshLib/Elements/Quad.h" @@ -146,8 +146,8 @@ bool createSfcMeshProperties(MeshLib::Mesh& sfc_mesh, else { WARN( - "Skipping property vector '{:s}' - no matching data type '{:s}'" - "found.", + "Skipping property vector '{:s}' - no matching data type " + "'{:s}' found.", name, typeid(*property).name()); vectors_skipped++; } diff --git a/MeshLib/Node.cpp b/MeshLib/Node.cpp index 886d16de7b7874c2cdbc249edd32d610bad07390..df1d730dde44220affa41c4bbabf6a53b0cf930a 100644 --- a/MeshLib/Node.cpp +++ b/MeshLib/Node.cpp @@ -13,13 +13,14 @@ */ #include "MeshLib/Node.h" -#include "Elements/Element.h" -namespace MeshLib { +#include "Elements/Element.h" +namespace MeshLib +{ Node::Node(const double coords[3], std::size_t id) : MathLib::Point3dWithID( - std::array<double,3>{{coords[0], coords[1], coords[2]}}, id) + std::array<double, 3>{{coords[0], coords[1], coords[2]}}, id) { } @@ -29,14 +30,11 @@ Node::Node(std::array<double, 3> const& coords, std::size_t id) } Node::Node(double x, double y, double z, std::size_t id) - : MathLib::Point3dWithID(std::array<double,3>({{x, y, z}}), id) + : MathLib::Point3dWithID(std::array<double, 3>({{x, y, z}}), id) { } -Node::Node(const Node &node) - : MathLib::Point3dWithID(node._x, node.getID()) -{ -} +Node::Node(const Node& node) : MathLib::Point3dWithID(node._x, node.getID()) {} void Node::updateCoordinates(double x, double y, double z) { @@ -44,7 +42,7 @@ void Node::updateCoordinates(double x, double y, double z) _x[1] = y; _x[2] = z; - const std::size_t nElements (this->_elements.size()); + const std::size_t nElements(this->_elements.size()); for (std::size_t i = 0; i < nElements; i++) { _elements[i]->computeVolume(); diff --git a/MeshLib/Properties.cpp b/MeshLib/Properties.cpp index ef5ae723f2a8b319fa8339df485be05edadc4013..1def95c05236d0fcdbf4f8db8d2eb68ed57ce9c2 100644 --- a/MeshLib/Properties.cpp +++ b/MeshLib/Properties.cpp @@ -14,13 +14,12 @@ namespace MeshLib { - void Properties::removePropertyVector(std::string const& name) { std::map<std::string, PropertyVectorBase*>::const_iterator it( - _properties.find(name) - ); - if (it == _properties.end()) { + _properties.find(name)); + if (it == _properties.end()) + { WARN("A property of the name '{:s}' does not exist.", name); return; } diff --git a/MeshLib/Vtk/VtkMappedMeshSource.cpp b/MeshLib/Vtk/VtkMappedMeshSource.cpp index b24b321cd45322cc97cdfa12a51b88a315451f3a..f99251321bdf855dbb2cd2768f246271d7d33c42 100644 --- a/MeshLib/Vtk/VtkMappedMeshSource.cpp +++ b/MeshLib/Vtk/VtkMappedMeshSource.cpp @@ -13,8 +13,6 @@ */ #include "VtkMappedMeshSource.h" -#include <vector> - #include <vtkCellType.h> #include <vtkDemandDrivenPipeline.h> #include <vtkInformation.h> @@ -22,6 +20,8 @@ #include <vtkSmartPointer.h> #include <vtkStreamingDemandDrivenPipeline.h> +#include <vector> + #include "MeshLib/Elements/Element.h" #include "MeshLib/Mesh.h" #include "MeshLib/VtkOGSEnum.h" @@ -172,8 +172,8 @@ int VtkMappedMeshSource::RequestData(vtkInformation* /*request*/, { addProperty(*p); } - else if (auto p = - dynamic_cast<PropertyVector<unsigned long long>*>(property)) + else if (auto p = dynamic_cast<PropertyVector<unsigned long long>*>( + property)) { addProperty(*p); } diff --git a/MeshLib/VtkOGSEnum.cpp b/MeshLib/VtkOGSEnum.cpp index 55ed23e1cec7b8fe4d729dcd211d7dd5fdcfd3d9..55d91c3c340774c02482ef81d11fe239cd9c596e 100644 --- a/MeshLib/VtkOGSEnum.cpp +++ b/MeshLib/VtkOGSEnum.cpp @@ -10,10 +10,10 @@ #include "VtkOGSEnum.h" -#include "BaseLib/Error.h" - #include <vtkCellType.h> +#include "BaseLib/Error.h" + int OGSToVtkCellType(MeshLib::CellType ogs) { switch (ogs) @@ -63,5 +63,3 @@ int OGSToVtkCellType(MeshLib::CellType ogs) ogs); } } - - diff --git a/MeshLib/convertMeshToGeo.cpp b/MeshLib/convertMeshToGeo.cpp index 65ff3b149bcc91229600b26f96f42281df93345a..c3fde08fffacbd81bb25f6b266e60d7ac1f79e90 100644 --- a/MeshLib/convertMeshToGeo.cpp +++ b/MeshLib/convertMeshToGeo.cpp @@ -15,13 +15,11 @@ #include "convertMeshToGeo.h" #include "BaseLib/Logging.h" - +#include "Elements/Quad.h" +#include "Elements/Tri.h" #include "GeoLib/GEOObjects.h" #include "GeoLib/Surface.h" #include "GeoLib/Triangle.h" - -#include "Elements/Quad.h" -#include "Elements/Tri.h" #include "Mesh.h" #include "MeshEditing/MeshRevision.h" #include "MeshInformation.h" diff --git a/MeshLib/findElementsWithinRadius.cpp b/MeshLib/findElementsWithinRadius.cpp index 36dd45ef9ff0703fcbb4c460348b0a346692d442..e40a104524d1acd36f208c0922758b4ff056152e 100644 --- a/MeshLib/findElementsWithinRadius.cpp +++ b/MeshLib/findElementsWithinRadius.cpp @@ -14,12 +14,12 @@ #include <unordered_set> #include <vector> -#include "MathLib/MathTools.h" - #include "Elements/Element.h" +#include "MathLib/MathTools.h" #include "Node.h" -namespace MeshLib { +namespace MeshLib +{ std::vector<std::size_t> findElementsWithinRadius(Element const& start_element, double const radius_squared) { diff --git a/NumLib/DOF/ComputeSparsityPattern.cpp b/NumLib/DOF/ComputeSparsityPattern.cpp index 4bcbcb62562fe596652cf90da833a8fb81529477..166ecc0efe8654b430e0df43e723ec777ea0819d 100644 --- a/NumLib/DOF/ComputeSparsityPattern.cpp +++ b/NumLib/DOF/ComputeSparsityPattern.cpp @@ -19,8 +19,7 @@ #include "MeshLib/NodePartitionedMesh.h" GlobalSparsityPattern computeSparsityPatternPETSc( - NumLib::LocalToGlobalIndexMap const& dof_table, - MeshLib::Mesh const& mesh) + NumLib::LocalToGlobalIndexMap const& dof_table, MeshLib::Mesh const& mesh) { assert(dynamic_cast<MeshLib::NodePartitionedMesh const*>(&mesh)); auto const& npmesh = diff --git a/NumLib/DOF/DOFTableUtil.cpp b/NumLib/DOF/DOFTableUtil.cpp index 1364d5b9b116b21821f7593776c19cb4ae76df30..7879eb2c5c5f5b43e478d44e2acb40baeb87d85e 100644 --- a/NumLib/DOF/DOFTableUtil.cpp +++ b/NumLib/DOF/DOFTableUtil.cpp @@ -9,6 +9,7 @@ */ #include "DOFTableUtil.h" + #include <cassert> namespace NumLib @@ -97,7 +98,7 @@ double getNonGhostNodalValue(GlobalVector const& x, MeshLib::Mesh const& mesh, node_id}; auto const index = dof_table.getGlobalIndex(l, global_component_id); - assert (index != NumLib::MeshComponentMap::nop); + assert(index != NumLib::MeshComponentMap::nop); if (index < 0) { // ghost node value @@ -116,7 +117,7 @@ double getNodalValue(GlobalVector const& x, MeshLib::Mesh const& mesh, node_id}; auto const index = dof_table.getGlobalIndex(l, global_component_id); - assert (index != NumLib::MeshComponentMap::nop); + assert(index != NumLib::MeshComponentMap::nop); return x.get(index); } diff --git a/NumLib/DOF/GlobalMatrixProviders.cpp b/NumLib/DOF/GlobalMatrixProviders.cpp index 10c8628513530bda39ce8e3ddad39fc3d181d5bc..690ddf851eb03183c3fc0fa9a367adcc92f76ba8 100644 --- a/NumLib/DOF/GlobalMatrixProviders.cpp +++ b/NumLib/DOF/GlobalMatrixProviders.cpp @@ -14,26 +14,25 @@ #include "SimpleMatrixVectorProvider.h" - // Initializes the static members of the structs in the header file // associated with this file. -#define INITIALIZE_GLOBAL_MATRIX_VECTOR_PROVIDER(VARNAME) \ +#define INITIALIZE_GLOBAL_MATRIX_VECTOR_PROVIDER(VARNAME) \ static std::unique_ptr<NumLib::SimpleMatrixVectorProvider> VARNAME{ \ - new NumLib::SimpleMatrixVectorProvider}; \ - \ - namespace NumLib { \ - VectorProvider& GlobalVectorProvider::provider = *(VARNAME); \ - \ - MatrixProvider& GlobalMatrixProvider::provider = *(VARNAME); \ + new NumLib::SimpleMatrixVectorProvider}; \ + \ + namespace NumLib \ + { \ + VectorProvider& GlobalVectorProvider::provider = *(VARNAME); \ + \ + MatrixProvider& GlobalMatrixProvider::provider = *(VARNAME); \ } INITIALIZE_GLOBAL_MATRIX_VECTOR_PROVIDER(globalSetupGlobalMatrixVectorProvider) - namespace NumLib { void cleanupGlobalMatrixProviders() { globalSetupGlobalMatrixVectorProvider.reset(); } -} +} // namespace NumLib diff --git a/NumLib/DOF/LocalToGlobalIndexMap.cpp b/NumLib/DOF/LocalToGlobalIndexMap.cpp index 1ef6b39636184fc61603b78e0b169b886116e129..cd1c61e4d77036e137896affeb936f33c260c4f6 100644 --- a/NumLib/DOF/LocalToGlobalIndexMap.cpp +++ b/NumLib/DOF/LocalToGlobalIndexMap.cpp @@ -16,16 +16,14 @@ namespace NumLib { - namespace { - // Make the cumulative sum of an array, which starts with zero template <typename T> std::vector<T> to_cumulative(std::vector<T> const& vec) { - std::vector<T> result(vec.size()+1, 0); - std::partial_sum(vec.begin(), vec.end(), result.begin()+1); + std::vector<T> result(vec.size() + 1, 0); + std::partial_sum(vec.begin(), vec.end(), result.begin() + 1); return result; } @@ -44,7 +42,8 @@ void LocalToGlobalIndexMap::findGlobalIndicesWithElementID( std::vector<MeshLib::Node*> const& nodes, std::size_t const mesh_id, const int comp_id, const int comp_id_write) { - std::unordered_set<MeshLib::Node*> const set_nodes(nodes.begin(), nodes.end()); + std::unordered_set<MeshLib::Node*> const set_nodes(nodes.begin(), + nodes.end()); // For each element find the global indices for node/element // components. @@ -54,15 +53,16 @@ void LocalToGlobalIndexMap::findGlobalIndicesWithElementID( indices.reserve((*e)->getNumberOfNodes()); for (auto* n = (*e)->getNodes(); - n < (*e)->getNodes()+(*e)->getNumberOfNodes(); ++n) + n < (*e)->getNodes() + (*e)->getNumberOfNodes(); + ++n) { // Check if the element's node is in the given list of nodes. if (set_nodes.find(*n) == set_nodes.end()) { continue; } - MeshLib::Location l( - mesh_id, MeshLib::MeshItemType::Node, (*n)->getID()); + MeshLib::Location l(mesh_id, MeshLib::MeshItemType::Node, + (*n)->getID()); indices.push_back(_mesh_component_map.getGlobalIndex(l, comp_id)); } @@ -79,7 +79,8 @@ void LocalToGlobalIndexMap::findGlobalIndices( { _rows.resize(std::distance(first, last), _mesh_subsets.size()); - std::unordered_set<MeshLib::Node*> const set_nodes(nodes.begin(), nodes.end()); + std::unordered_set<MeshLib::Node*> const set_nodes(nodes.begin(), + nodes.end()); // For each element find the global indices for node/element // components. @@ -90,15 +91,16 @@ void LocalToGlobalIndexMap::findGlobalIndices( indices.reserve((*e)->getNumberOfNodes()); for (auto* n = (*e)->getNodes(); - n < (*e)->getNodes() + (*e)->getNumberOfNodes(); ++n) + n < (*e)->getNodes() + (*e)->getNumberOfNodes(); + ++n) { // Check if the element's node is in the given list of nodes. if (set_nodes.find(*n) == set_nodes.end()) { continue; } - MeshLib::Location l( - mesh_id, MeshLib::MeshItemType::Node, (*n)->getID()); + MeshLib::Location l(mesh_id, MeshLib::MeshItemType::Node, + (*n)->getID()); auto const global_index = _mesh_component_map.getGlobalIndex(l, comp_id); if (global_index == std::numeric_limits<GlobalIndexType>::max()) @@ -130,10 +132,12 @@ LocalToGlobalIndexMap::LocalToGlobalIndexMap( _variable_component_offsets(to_cumulative(vec_var_n_components)) { // For each element of that MeshSubset save a line of global indices. - for (int variable_id = 0; variable_id < static_cast<int>(vec_var_n_components.size()); + for (int variable_id = 0; + variable_id < static_cast<int>(vec_var_n_components.size()); ++variable_id) { - for (int component_id = 0; component_id < static_cast<int>(vec_var_n_components[variable_id]); + for (int component_id = 0; + component_id < static_cast<int>(vec_var_n_components[variable_id]); ++component_id) { auto const global_component_id = @@ -164,7 +168,7 @@ LocalToGlobalIndexMap::LocalToGlobalIndexMap( // _rows should be resized based on an element ID std::size_t max_elem_id = 0; - for (std::vector<MeshLib::Element*>const* elements : vec_var_elements) + for (std::vector<MeshLib::Element*> const* elements : vec_var_elements) { for (auto e : *elements) { @@ -173,11 +177,14 @@ LocalToGlobalIndexMap::LocalToGlobalIndexMap( } _rows.resize(max_elem_id + 1, _mesh_subsets.size()); - for (int variable_id = 0; variable_id < static_cast<int>(vec_var_n_components.size()); + for (int variable_id = 0; + variable_id < static_cast<int>(vec_var_n_components.size()); ++variable_id) { - std::vector<MeshLib::Element*> const& var_elements = *vec_var_elements[variable_id]; - for (int component_id = 0; component_id < static_cast<int>(vec_var_n_components[variable_id]); + std::vector<MeshLib::Element*> const& var_elements = + *vec_var_elements[variable_id]; + for (int component_id = 0; + component_id < static_cast<int>(vec_var_n_components[variable_id]); ++component_id) { auto const global_component_id = @@ -344,8 +351,8 @@ LocalToGlobalIndexMap::RowColumnIndices LocalToGlobalIndexMap::operator()( _columns(mesh_item_id, component_id)); } -std::size_t -LocalToGlobalIndexMap::getNumberOfElementDOF(std::size_t const mesh_item_id) const +std::size_t LocalToGlobalIndexMap::getNumberOfElementDOF( + std::size_t const mesh_item_id) const { std::size_t ndof = 0; @@ -357,8 +364,8 @@ LocalToGlobalIndexMap::getNumberOfElementDOF(std::size_t const mesh_item_id) con return ndof; } -std::size_t -LocalToGlobalIndexMap::getNumberOfElementComponents(std::size_t const mesh_item_id) const +std::size_t LocalToGlobalIndexMap::getNumberOfElementComponents( + std::size_t const mesh_item_id) const { std::size_t n = 0; for (Table::Index c = 0; c < _rows.cols(); ++c) @@ -377,7 +384,7 @@ std::vector<int> LocalToGlobalIndexMap::getElementVariableIDs( std::vector<int> vec; for (int i = 0; i < getNumberOfVariables(); i++) { - for (int j=0; j<getNumberOfVariableComponents(i); j++) + for (int j = 0; j < getNumberOfVariableComponents(i); j++) { auto comp_id = getGlobalComponent(i, j); if (!_rows(mesh_item_id, comp_id).empty()) @@ -450,8 +457,8 @@ std::ostream& operator<<(std::ostream& os, LocalToGlobalIndexMap const& map) std::size_t lines_printed = 0; os << "Rows of the local to global index map; " << map._rows.size() - << " rows\n"; - for (std::size_t e=0; e<map.size(); ++e) + << " rows\n"; + for (std::size_t e = 0; e < map.size(); ++e) { os << "== e " << e << " ==\n"; for (int c = 0; c < map.getNumberOfGlobalComponents(); ++c) @@ -460,7 +467,7 @@ std::ostream& operator<<(std::ostream& os, LocalToGlobalIndexMap const& map) os << "c" << c << " { "; std::copy(line.cbegin(), line.cend(), - std::ostream_iterator<std::size_t>(os, " ")); + std::ostream_iterator<std::size_t>(os, " ")); os << " }\n"; } @@ -476,4 +483,4 @@ std::ostream& operator<<(std::ostream& os, LocalToGlobalIndexMap const& map) } #endif // NDEBUG -} // namespace NumLib +} // namespace NumLib diff --git a/NumLib/DOF/MeshComponentMap.cpp b/NumLib/DOF/MeshComponentMap.cpp index 63cf25a6e8ebc5d4dc46b1c61c0f1ec024a17479..28de99718149cf560940db5c76c5cba32f1d3dc9 100644 --- a/NumLib/DOF/MeshComponentMap.cpp +++ b/NumLib/DOF/MeshComponentMap.cpp @@ -74,8 +74,8 @@ MeshComponentMap::MeshComponentMap( // a rank in the parallel computing. OGS_FATAL( "Global index in the system of equations" - " can only be numbered by the order type" - " of ComponentOrder::BY_LOCATION"); + " can only be numbered by the order type of " + "ComponentOrder::BY_LOCATION"); } global_id = static_cast<GlobalIndexType>( components.size() * p_mesh.getGlobalNodeID(j) + comp_id); @@ -124,8 +124,8 @@ MeshComponentMap MeshComponentMap::getSubset( if (first_mismatch != end(bulk_mesh_subsets)) { OGS_FATAL( - "Assumption in the MeshComponentMap violated. Expecting " - "all of mesh ids to be the same, but it is not true for " + "Assumption in the MeshComponentMap violated. Expecting all of " + "mesh ids to be the same, but it is not true for " "the mesh '{:s}' with id {:d}.", first_mismatch->getMesh().getName(), first_mismatch->getMeshID()); diff --git a/NumLib/DOF/SimpleMatrixVectorProvider.cpp b/NumLib/DOF/SimpleMatrixVectorProvider.cpp index 67fe93e71545deeaa79bc6d978f9f34e984d8e5b..9a0590099796995398ef789e296396c98f91def7 100644 --- a/NumLib/DOF/SimpleMatrixVectorProvider.cpp +++ b/NumLib/DOF/SimpleMatrixVectorProvider.cpp @@ -11,9 +11,9 @@ #include "SimpleMatrixVectorProvider.h" #include <cassert> -#include "BaseLib/Logging.h" #include "BaseLib/Error.h" +#include "BaseLib/Logging.h" #include "MathLib/LinAlg/LinAlg.h" #include "MathLib/LinAlg/MatrixVectorTraits.h" @@ -21,12 +21,10 @@ namespace LinAlg = MathLib::LinAlg; namespace detail { - -template<typename MatVec> -MatVec* -transfer(std::map<std::size_t, MatVec*>& from_unused, - std::map<MatVec*, std::size_t>& to_used, - typename std::map<std::size_t, MatVec*>::iterator it) +template <typename MatVec> +MatVec* transfer(std::map<std::size_t, MatVec*>& from_unused, + std::map<MatVec*, std::size_t>& to_used, + typename std::map<std::size_t, MatVec*>::iterator it) { auto const id = it->first; auto& ptr = it->second; @@ -37,18 +35,17 @@ transfer(std::map<std::size_t, MatVec*>& from_unused, return res.first->first; } -template<typename MatVec> -void -transfer(std::map<MatVec*, std::size_t>& from_used, - std::map<std::size_t, MatVec*>& to_unused, - typename std::map<MatVec*, std::size_t>::iterator it) +template <typename MatVec> +void transfer(std::map<MatVec*, std::size_t>& from_used, + std::map<std::size_t, MatVec*>& to_unused, + typename std::map<MatVec*, std::size_t>::iterator it) { auto& ptr = it->first; auto const id = it->second; auto res = to_unused.emplace(id, ptr); assert(res.second && "Emplacement failed."); - (void) res; // res unused if NDEBUG + (void)res; // res unused if NDEBUG from_used.erase(it); } @@ -56,17 +53,17 @@ transfer(std::map<MatVec*, std::size_t>& from_used, namespace NumLib { - -template<bool do_search, typename MatVec, typename... Args> -std::pair<MatVec*, bool> -SimpleMatrixVectorProvider:: -get_(std::size_t& id, - std::map<std::size_t, MatVec*>& unused_map, - std::map<MatVec*, std::size_t>& used_map, - Args&&... args) +template <bool do_search, typename MatVec, typename... Args> +std::pair<MatVec*, bool> SimpleMatrixVectorProvider::get_( + std::size_t& id, + std::map<std::size_t, MatVec*>& unused_map, + std::map<MatVec*, std::size_t>& used_map, + Args&&... args) { - if (id >= _next_id) { - OGS_FATAL("An obviously uninitialized id argument has been passed." + if (id >= _next_id) + { + OGS_FATAL( + "An obviously uninitialized id argument has been passed." " This might not be a serious error for the current implementation," " but it might become one in the future." " Hence, I will abort now."); @@ -83,57 +80,50 @@ get_(std::size_t& id, // not searched or not found, so create a new one id = _next_id++; - auto res = used_map.emplace( - MathLib::MatrixVectorTraits<MatVec>::newInstance(std::forward<Args>(args)...).release(), - id); + auto res = + used_map.emplace(MathLib::MatrixVectorTraits<MatVec>::newInstance( + std::forward<Args>(args)...) + .release(), + id); assert(res.second && "Emplacement failed."); - return { res.first->first, true }; + return {res.first->first, true}; } -template<bool do_search, typename... Args> -std::pair<GlobalMatrix*, bool> -SimpleMatrixVectorProvider:: -getMatrix_(std::size_t& id, Args&&... args) +template <bool do_search, typename... Args> +std::pair<GlobalMatrix*, bool> SimpleMatrixVectorProvider::getMatrix_( + std::size_t& id, Args&&... args) { - return get_<do_search>(id, _unused_matrices, _used_matrices, std::forward<Args>(args)...); + return get_<do_search>( + id, _unused_matrices, _used_matrices, std::forward<Args>(args)...); } - -GlobalMatrix& -SimpleMatrixVectorProvider:: -getMatrix() +GlobalMatrix& SimpleMatrixVectorProvider::getMatrix() { std::size_t id = 0u; return *getMatrix_<false>(id).first; } -GlobalMatrix& -SimpleMatrixVectorProvider:: -getMatrix(std::size_t& id) +GlobalMatrix& SimpleMatrixVectorProvider::getMatrix(std::size_t& id) { return *getMatrix_<true>(id).first; } -GlobalMatrix& -SimpleMatrixVectorProvider:: -getMatrix(MathLib::MatrixSpecifications const& ms) +GlobalMatrix& SimpleMatrixVectorProvider::getMatrix( + MathLib::MatrixSpecifications const& ms) { std::size_t id = 0u; return *getMatrix_<false>(id, ms).first; // TODO assert that the returned object always is of the right size } -GlobalMatrix& -SimpleMatrixVectorProvider:: -getMatrix(MathLib::MatrixSpecifications const& ms, std::size_t& id) +GlobalMatrix& SimpleMatrixVectorProvider::getMatrix( + MathLib::MatrixSpecifications const& ms, std::size_t& id) { return *getMatrix_<true>(id, ms).first; // TODO assert that the returned object always is of the right size } -GlobalMatrix& -SimpleMatrixVectorProvider:: -getMatrix(GlobalMatrix const& A) +GlobalMatrix& SimpleMatrixVectorProvider::getMatrix(GlobalMatrix const& A) { std::size_t id = 0u; auto const& res = getMatrix_<false>(id, A); @@ -144,9 +134,8 @@ getMatrix(GlobalMatrix const& A) return *res.first; } -GlobalMatrix& -SimpleMatrixVectorProvider:: -getMatrix(GlobalMatrix const& A, std::size_t& id) +GlobalMatrix& SimpleMatrixVectorProvider::getMatrix(GlobalMatrix const& A, + std::size_t& id) { auto const& res = getMatrix_<true>(id, A); if (!res.second) @@ -156,53 +145,50 @@ getMatrix(GlobalMatrix const& A, std::size_t& id) return *res.first; } -void -SimpleMatrixVectorProvider:: -releaseMatrix(GlobalMatrix const& A) +void SimpleMatrixVectorProvider::releaseMatrix(GlobalMatrix const& A) { auto it = _used_matrices.find(const_cast<GlobalMatrix*>(&A)); - if (it == _used_matrices.end()) { - OGS_FATAL("The given matrix has not been found. Cannot release it. Aborting."); - } else { + if (it == _used_matrices.end()) + { + OGS_FATAL( + "The given matrix has not been found. Cannot release it. " + "Aborting."); + } + else + { ::detail::transfer(_used_matrices, _unused_matrices, it); } } -template<bool do_search, typename... Args> -std::pair<GlobalVector*, bool> -SimpleMatrixVectorProvider:: -getVector_(std::size_t& id, Args&&... args) +template <bool do_search, typename... Args> +std::pair<GlobalVector*, bool> SimpleMatrixVectorProvider::getVector_( + std::size_t& id, Args&&... args) { - return get_<do_search>(id, _unused_vectors, _used_vectors, std::forward<Args>(args)...); + return get_<do_search>( + id, _unused_vectors, _used_vectors, std::forward<Args>(args)...); } -GlobalVector& -SimpleMatrixVectorProvider:: -getVector(std::size_t& id) +GlobalVector& SimpleMatrixVectorProvider::getVector(std::size_t& id) { return *getVector_<true>(id).first; } -GlobalVector& -SimpleMatrixVectorProvider:: -getVector(MathLib::MatrixSpecifications const& ms) +GlobalVector& SimpleMatrixVectorProvider::getVector( + MathLib::MatrixSpecifications const& ms) { std::size_t id = 0u; return *getVector_<false>(id, ms).first; // TODO assert that the returned object always is of the right size } -GlobalVector& -SimpleMatrixVectorProvider:: -getVector(MathLib::MatrixSpecifications const& ms, std::size_t& id) +GlobalVector& SimpleMatrixVectorProvider::getVector( + MathLib::MatrixSpecifications const& ms, std::size_t& id) { return *getVector_<true>(id, ms).first; // TODO assert that the returned object always is of the right size } -GlobalVector& -SimpleMatrixVectorProvider:: -getVector(GlobalVector const& x) +GlobalVector& SimpleMatrixVectorProvider::getVector(GlobalVector const& x) { std::size_t id = 0u; auto const& res = getVector_<false>(id, x); @@ -213,9 +199,8 @@ getVector(GlobalVector const& x) return *res.first; } -GlobalVector& -SimpleMatrixVectorProvider:: -getVector(GlobalVector const& x, std::size_t& id) +GlobalVector& SimpleMatrixVectorProvider::getVector(GlobalVector const& x, + std::size_t& id) { auto const& res = getVector_<true>(id, x); if (!res.second) @@ -225,20 +210,22 @@ getVector(GlobalVector const& x, std::size_t& id) return *res.first; } -void -SimpleMatrixVectorProvider:: -releaseVector(GlobalVector const& x) +void SimpleMatrixVectorProvider::releaseVector(GlobalVector const& x) { auto it = _used_vectors.find(const_cast<GlobalVector*>(&x)); - if (it == _used_vectors.end()) { - OGS_FATAL("The given vector has not been found. Cannot release it. Aborting."); - } else { + if (it == _used_vectors.end()) + { + OGS_FATAL( + "The given vector has not been found. Cannot release it. " + "Aborting."); + } + else + { ::detail::transfer(_used_vectors, _unused_vectors, it); } } -SimpleMatrixVectorProvider:: -~SimpleMatrixVectorProvider() +SimpleMatrixVectorProvider::~SimpleMatrixVectorProvider() { if (!_used_matrices.empty()) { diff --git a/NumLib/Extrapolation/LocalLinearLeastSquaresExtrapolator.cpp b/NumLib/Extrapolation/LocalLinearLeastSquaresExtrapolator.cpp index bf63356160281d163516b2272640d6f01c43d1fd..3b6c67cdd9b7fcf5e6a2e7e384bf90d439646a27 100644 --- a/NumLib/Extrapolation/LocalLinearLeastSquaresExtrapolator.cpp +++ b/NumLib/Extrapolation/LocalLinearLeastSquaresExtrapolator.cpp @@ -11,14 +11,14 @@ #include "LocalLinearLeastSquaresExtrapolator.h" #include <Eigen/SVD> -#include "BaseLib/Logging.h" +#include "BaseLib/Logging.h" +#include "ExtrapolatableElementCollection.h" #include "MathLib/LinAlg/Eigen/EigenMapTools.h" #include "MathLib/LinAlg/LinAlg.h" #include "MathLib/LinAlg/MatrixVectorTraits.h" #include "NumLib/Assembler/SerialExecutor.h" #include "NumLib/Function/Interpolation.h" -#include "ExtrapolatableElementCollection.h" namespace NumLib { @@ -36,8 +36,8 @@ LocalLinearLeastSquaresExtrapolator::LocalLinearLeastSquaresExtrapolator( if (dof_table.getNumberOfGlobalComponents() != 1) { OGS_FATAL( - "The d.o.f. table passed must be for one variable that has " - "only one component!"); + "The d.o.f. table passed must be for one variable that has only " + "one component!"); } } diff --git a/NumLib/Fem/CoordinatesMapping/NaturalCoordinatesMapping.cpp b/NumLib/Fem/CoordinatesMapping/NaturalCoordinatesMapping.cpp index 8d79c6cac55ee9a9b4353ab192ec8c83fcee39b2..b165dad5af2aea9a4bedc9bc11cea362258ace7c 100644 --- a/NumLib/Fem/CoordinatesMapping/NaturalCoordinatesMapping.cpp +++ b/NumLib/Fem/CoordinatesMapping/NaturalCoordinatesMapping.cpp @@ -16,9 +16,7 @@ #endif // NDEBUG #include "BaseLib/Error.h" - #include "MeshLib/ElementCoordinatesMappingLocal.h" -#include "MeshLib/Elements/TemplateElement.h" #include "MeshLib/Elements/HexRule20.h" #include "MeshLib/Elements/HexRule8.h" #include "MeshLib/Elements/LineRule2.h" @@ -31,38 +29,38 @@ #include "MeshLib/Elements/QuadRule4.h" #include "MeshLib/Elements/QuadRule8.h" #include "MeshLib/Elements/QuadRule9.h" +#include "MeshLib/Elements/TemplateElement.h" #include "MeshLib/Elements/TetRule10.h" #include "MeshLib/Elements/TetRule4.h" #include "MeshLib/Elements/TriRule3.h" #include "MeshLib/Elements/TriRule6.h" - -#include "NumLib/Fem/ShapeFunction/ShapePoint1.h" +#include "NumLib/Fem/ShapeFunction/ShapeHex20.h" +#include "NumLib/Fem/ShapeFunction/ShapeHex8.h" #include "NumLib/Fem/ShapeFunction/ShapeLine2.h" #include "NumLib/Fem/ShapeFunction/ShapeLine3.h" -#include "NumLib/Fem/ShapeFunction/ShapeTri3.h" -#include "NumLib/Fem/ShapeFunction/ShapeTri6.h" +#include "NumLib/Fem/ShapeFunction/ShapePoint1.h" +#include "NumLib/Fem/ShapeFunction/ShapePrism15.h" +#include "NumLib/Fem/ShapeFunction/ShapePrism6.h" +#include "NumLib/Fem/ShapeFunction/ShapePyra13.h" +#include "NumLib/Fem/ShapeFunction/ShapePyra5.h" #include "NumLib/Fem/ShapeFunction/ShapeQuad4.h" #include "NumLib/Fem/ShapeFunction/ShapeQuad8.h" #include "NumLib/Fem/ShapeFunction/ShapeQuad9.h" -#include "NumLib/Fem/ShapeFunction/ShapeHex8.h" -#include "NumLib/Fem/ShapeFunction/ShapeHex20.h" -#include "NumLib/Fem/ShapeFunction/ShapeTet4.h" #include "NumLib/Fem/ShapeFunction/ShapeTet10.h" -#include "NumLib/Fem/ShapeFunction/ShapePrism6.h" -#include "NumLib/Fem/ShapeFunction/ShapePrism15.h" -#include "NumLib/Fem/ShapeFunction/ShapePyra5.h" -#include "NumLib/Fem/ShapeFunction/ShapePyra13.h" +#include "NumLib/Fem/ShapeFunction/ShapeTet4.h" +#include "NumLib/Fem/ShapeFunction/ShapeTri3.h" +#include "NumLib/Fem/ShapeFunction/ShapeTri6.h" #include "NumLib/Fem/ShapeMatrixPolicy.h" - #include "ShapeMatrices.h" namespace NumLib { - namespace detail { - -template <ShapeMatrixType FIELD_TYPE> struct FieldType {}; +template <ShapeMatrixType FIELD_TYPE> +struct FieldType +{ +}; template <class T_MESH_ELEMENT, class T_SHAPE_FUNC, class T_SHAPE_MATRICES> inline void computeMappingMatrices( @@ -107,8 +105,9 @@ static void checkJacobianDeterminant(const double detJ, std::cerr << element << "\n"; #endif // NDEBUG OGS_FATAL( - "Please check whether the node numbering of the element is correct," - "or additional elements (like boundary elements) are still present in the mesh."); + "Please check whether the node numbering of the element is correct," + "or additional elements (like boundary elements) are still present " + "in the mesh."); } if (detJ == 0) @@ -180,10 +179,18 @@ inline void computeMappingMatrices( T_SHAPE_MATRICES& shapemat, FieldType<ShapeMatrixType::N_J> /*unused*/) { - computeMappingMatrices<T_MESH_ELEMENT, T_SHAPE_FUNC, T_SHAPE_MATRICES> - (ele, natural_pt, ele_local_coord, shapemat, FieldType<ShapeMatrixType::N>()); - computeMappingMatrices<T_MESH_ELEMENT, T_SHAPE_FUNC, T_SHAPE_MATRICES> - (ele, natural_pt, ele_local_coord, shapemat, FieldType<ShapeMatrixType::DNDR_J>()); + computeMappingMatrices<T_MESH_ELEMENT, T_SHAPE_FUNC, T_SHAPE_MATRICES>( + ele, + natural_pt, + ele_local_coord, + shapemat, + FieldType<ShapeMatrixType::N>()); + computeMappingMatrices<T_MESH_ELEMENT, T_SHAPE_FUNC, T_SHAPE_MATRICES>( + ele, + natural_pt, + ele_local_coord, + shapemat, + FieldType<ShapeMatrixType::DNDR_J>()); } template <class T_MESH_ELEMENT, class T_SHAPE_FUNC, class T_SHAPE_MATRICES> @@ -236,10 +243,18 @@ inline void computeMappingMatrices( T_SHAPE_MATRICES& shapemat, FieldType<ShapeMatrixType::ALL> /*unused*/) { - computeMappingMatrices<T_MESH_ELEMENT, T_SHAPE_FUNC, T_SHAPE_MATRICES> - (ele, natural_pt, ele_local_coord, shapemat, FieldType<ShapeMatrixType::N>()); - computeMappingMatrices<T_MESH_ELEMENT, T_SHAPE_FUNC, T_SHAPE_MATRICES> - (ele, natural_pt, ele_local_coord, shapemat, FieldType<ShapeMatrixType::DNDX>()); + computeMappingMatrices<T_MESH_ELEMENT, T_SHAPE_FUNC, T_SHAPE_MATRICES>( + ele, + natural_pt, + ele_local_coord, + shapemat, + FieldType<ShapeMatrixType::N>()); + computeMappingMatrices<T_MESH_ELEMENT, T_SHAPE_FUNC, T_SHAPE_MATRICES>( + ele, + natural_pt, + ele_local_coord, + shapemat, + FieldType<ShapeMatrixType::DNDX>()); } template <class T_MESH_ELEMENT, @@ -251,17 +266,16 @@ void naturalCoordinatesMappingComputeShapeMatrices(const T_MESH_ELEMENT& ele, T_SHAPE_MATRICES& shapemat, const unsigned global_dim) { - const MeshLib::ElementCoordinatesMappingLocal ele_local_coord(ele, global_dim); + const MeshLib::ElementCoordinatesMappingLocal ele_local_coord(ele, + global_dim); - detail::computeMappingMatrices< - T_MESH_ELEMENT, - T_SHAPE_FUNC, - T_SHAPE_MATRICES> - (ele, - natural_pt, - ele_local_coord, - shapemat, - detail::FieldType<T_SHAPE_MATRIX_TYPE>()); + detail:: + computeMappingMatrices<T_MESH_ELEMENT, T_SHAPE_FUNC, T_SHAPE_MATRICES>( + ele, + natural_pt, + ele_local_coord, + shapemat, + detail::FieldType<T_SHAPE_MATRIX_TYPE>()); } #define OGS_INSTANTIATE_NATURAL_COORDINATES_MAPPING_PART( \ diff --git a/NumLib/Fem/ShapeFunction/ShapeStaticConsts.cpp b/NumLib/Fem/ShapeFunction/ShapeStaticConsts.cpp index 3956551c193d942c0f98bee0c1264389b6358dc7..a25830b9ab499bb6949c44c8ce2da3941ce82a8e 100644 --- a/NumLib/Fem/ShapeFunction/ShapeStaticConsts.cpp +++ b/NumLib/Fem/ShapeFunction/ShapeStaticConsts.cpp @@ -47,7 +47,6 @@ namespace NumLib { - const unsigned ShapeHex20::DIM; const unsigned ShapeHex20::NPOINTS; const unsigned ShapeHex8::DIM; diff --git a/NumLib/Function/Interpolation.h b/NumLib/Function/Interpolation.h index 1cec844bdf4770eaf05ce8076a2d16bed67868b1..b41c30eb7d41fe03f49393a3ace4b0d3a001a51b 100644 --- a/NumLib/Function/Interpolation.h +++ b/NumLib/Function/Interpolation.h @@ -10,8 +10,8 @@ #pragma once -#include<array> -#include<cassert> +#include <array> +#include <cassert> #include "NumLib/Fem/CoordinatesMapping/NaturalNodeCoordinates.h" #include "NumLib/Fem/FiniteElement/TemplateIsoparametric.h" diff --git a/NumLib/ODESolver/ConvergenceCriterion.cpp b/NumLib/ODESolver/ConvergenceCriterion.cpp index a09c416f98d6923b8a02cc1f8379fd950bee9eaa..ab09bec442e21f301c25306469be4d74abffed7a 100644 --- a/NumLib/ODESolver/ConvergenceCriterion.cpp +++ b/NumLib/ODESolver/ConvergenceCriterion.cpp @@ -9,13 +9,13 @@ */ #include "ConvergenceCriterion.h" + #include "BaseLib/ConfigTree.h" #include "BaseLib/Error.h" - #include "ConvergenceCriterionDeltaX.h" -#include "ConvergenceCriterionResidual.h" #include "ConvergenceCriterionPerComponentDeltaX.h" #include "ConvergenceCriterionPerComponentResidual.h" +#include "ConvergenceCriterionResidual.h" namespace NumLib { @@ -25,7 +25,8 @@ std::unique_ptr<ConvergenceCriterion> createConvergenceCriterion( //! \ogs_file_param{prj__time_loop__processes__process__convergence_criterion__type} auto const type = config.peekConfigParameter<std::string>("type"); - if (type == "DeltaX") { + if (type == "DeltaX") + { return createConvergenceCriterionDeltaX(config); } if (type == "Residual") diff --git a/NumLib/ODESolver/ConvergenceCriterionDeltaX.cpp b/NumLib/ODESolver/ConvergenceCriterionDeltaX.cpp index 24074d10e6ac3465178cf615c9f5e4f517d38821..20f2e03b938f19cfbd0d5e7c1c0a41084b084828 100644 --- a/NumLib/ODESolver/ConvergenceCriterionDeltaX.cpp +++ b/NumLib/ODESolver/ConvergenceCriterionDeltaX.cpp @@ -9,9 +9,9 @@ */ #include "ConvergenceCriterionDeltaX.h" -#include "BaseLib/Logging.h" #include "BaseLib/ConfigTree.h" +#include "BaseLib/Logging.h" #include "MathLib/LinAlg/LinAlg.h" namespace NumLib @@ -46,10 +46,12 @@ void ConvergenceCriterionDeltaX::checkDeltaX(const GlobalVector& minus_delta_x, bool satisfied_abs = false; bool satisfied_rel = false; - if (_abstol) { + if (_abstol) + { satisfied_abs = error_dx < *_abstol; } - if (_reltol) { + if (_reltol) + { satisfied_rel = checkRelativeTolerance(*_reltol, error_dx, norm_x); } diff --git a/NumLib/ODESolver/ConvergenceCriterionPerComponentDeltaX.cpp b/NumLib/ODESolver/ConvergenceCriterionPerComponentDeltaX.cpp index 56b6724eab3c6f9d5c0348f2e6c64e10effc58b6..25f875333dbfe984d825bf6ad140c1f81ff373e5 100644 --- a/NumLib/ODESolver/ConvergenceCriterionPerComponentDeltaX.cpp +++ b/NumLib/ODESolver/ConvergenceCriterionPerComponentDeltaX.cpp @@ -9,12 +9,13 @@ */ #include "ConvergenceCriterionPerComponentDeltaX.h" + #include <limits> -#include "BaseLib/Logging.h" #include "BaseLib/ConfigTree.h" -#include "NumLib/DOF/LocalToGlobalIndexMap.h" +#include "BaseLib/Logging.h" #include "NumLib/DOF/DOFTableUtil.h" +#include "NumLib/DOF/LocalToGlobalIndexMap.h" namespace NumLib { @@ -112,9 +113,12 @@ createConvergenceCriterionPerComponentDeltaX(const BaseLib::ConfigTree& config) "At least one of absolute or relative tolerance has to be " "specified."); } - if (!abstols) { + if (!abstols) + { abstols = std::vector<double>(reltols->size()); - } else if (!reltols) { + } + else if (!reltols) + { reltols = std::vector<double>(abstols->size()); } diff --git a/NumLib/ODESolver/ConvergenceCriterionPerComponentResidual.cpp b/NumLib/ODESolver/ConvergenceCriterionPerComponentResidual.cpp index db24a3b2c57b41ffd95be90aa7ea85fd75fcc37e..6a1e6e13d2c3fc3e0c2bf39c47dfe24c2390ddb4 100644 --- a/NumLib/ODESolver/ConvergenceCriterionPerComponentResidual.cpp +++ b/NumLib/ODESolver/ConvergenceCriterionPerComponentResidual.cpp @@ -9,9 +9,9 @@ */ #include "ConvergenceCriterionPerComponentResidual.h" -#include "BaseLib/Logging.h" #include "BaseLib/ConfigTree.h" +#include "BaseLib/Logging.h" #include "NumLib/DOF/DOFTableUtil.h" #include "NumLib/DOF/LocalToGlobalIndexMap.h" @@ -40,7 +40,6 @@ ConvergenceCriterionPerComponentResidual:: } } - void ConvergenceCriterionPerComponentResidual::checkDeltaX( const GlobalVector& minus_delta_x, GlobalVector const& x) { @@ -67,7 +66,6 @@ void ConvergenceCriterionPerComponentResidual::checkDeltaX( } } - void ConvergenceCriterionPerComponentResidual::checkResidual( const GlobalVector& residual) { @@ -85,19 +83,21 @@ void ConvergenceCriterionPerComponentResidual::checkResidual( ++global_component) { // TODO short cut if tol <= 0.0 - auto norm_res = norm(residual, global_component, _norm_type, - *_dof_table, *_mesh); + auto norm_res = + norm(residual, global_component, _norm_type, *_dof_table, *_mesh); - if (_is_first_iteration) { + if (_is_first_iteration) + { INFO("Convergence criterion, component {:d}: |r0|={:.4e}", global_component, norm_res); _residual_norms_0[global_component] = norm_res; - } else { + } + else + { auto const norm_res0 = _residual_norms_0[global_component]; INFO( "Convergence criterion, component {:d}: |r|={:.4e}, " - "|r0|={:.4e}, " - "|r|/|r0|={:.4e}", + "|r0|={:.4e}, |r|/|r0|={:.4e}", global_component, norm_res, norm_res0, (norm_res0 == 0. ? std::numeric_limits<double>::quiet_NaN() : (norm_res / norm_res0))); @@ -151,9 +151,12 @@ createConvergenceCriterionPerComponentResidual( "At least one of absolute or relative tolerance has to be " "specified."); } - if (!abstols) { + if (!abstols) + { abstols = std::vector<double>(reltols->size()); - } else if (!reltols) { + } + else if (!reltols) + { reltols = std::vector<double>(abstols->size()); } diff --git a/NumLib/ODESolver/ConvergenceCriterionResidual.cpp b/NumLib/ODESolver/ConvergenceCriterionResidual.cpp index 08de36c59ab5dd72bb8b599ec816627656a9846f..125d62eceaf0f463c35c9ed03e8b5656562e6a67 100644 --- a/NumLib/ODESolver/ConvergenceCriterionResidual.cpp +++ b/NumLib/ODESolver/ConvergenceCriterionResidual.cpp @@ -9,9 +9,9 @@ */ #include "ConvergenceCriterionResidual.h" -#include "BaseLib/Logging.h" #include "BaseLib/ConfigTree.h" +#include "BaseLib/Logging.h" #include "MathLib/LinAlg/LinAlg.h" namespace NumLib diff --git a/NumLib/ODESolver/MatrixTranslator.cpp b/NumLib/ODESolver/MatrixTranslator.cpp index 76d1cebe2bd3e2a309dd61df57c832ab5156c1a8..81f68482cbe8c15ece7390bd5368bcfbc9b9686c 100644 --- a/NumLib/ODESolver/MatrixTranslator.cpp +++ b/NumLib/ODESolver/MatrixTranslator.cpp @@ -52,7 +52,7 @@ void MatrixTranslatorGeneral<ODESystemTag::FirstOrderImplicitQuasilinear>:: // res = M * x_dot + K * x_curr - b LinAlg::matMult(M, xdot, res); // the local vector x_dot seems to be - // necessary because of this multiplication + // necessary because of this multiplication LinAlg::matMultAdd(K, x_curr, res, res); LinAlg::axpy(res, -1.0, b); } diff --git a/NumLib/ODESolver/NonlinearSolver.cpp b/NumLib/ODESolver/NonlinearSolver.cpp index 6a8ffcd420afcdd6813fc01fbe47eb3e62127571..5e07e66615c5a0c5169715203b6df1777cccf335 100644 --- a/NumLib/ODESolver/NonlinearSolver.cpp +++ b/NumLib/ODESolver/NonlinearSolver.cpp @@ -56,10 +56,8 @@ NonlinearSolverStatus NonlinearSolver<NonlinearSolverTag::Picard>::solve( namespace LinAlg = MathLib::LinAlg; auto& sys = *_equation_system; - auto& A = - NumLib::GlobalMatrixProvider::provider.getMatrix(_A_id); - auto& rhs = NumLib::GlobalVectorProvider::provider.getVector( - _rhs_id); + auto& A = NumLib::GlobalMatrixProvider::provider.getMatrix(_A_id); + auto& rhs = NumLib::GlobalVectorProvider::provider.getVector(_rhs_id); std::vector<GlobalVector*> x_new{x}; x_new[process_id] = @@ -71,8 +69,7 @@ NonlinearSolverStatus NonlinearSolver<NonlinearSolverTag::Picard>::solve( _convergence_criterion->preFirstIteration(); int iteration = 1; - for (; iteration <= _maxiter; - ++iteration, _convergence_criterion->reset()) + for (; iteration <= _maxiter; ++iteration, _convergence_criterion->reset()) { BaseLib::RunTime timer_dirichlet; double time_dirichlet = 0.0; @@ -105,10 +102,11 @@ NonlinearSolverStatus NonlinearSolver<NonlinearSolverTag::Picard>::solve( time_dirichlet += timer_dirichlet.elapsed(); INFO("[time] Applying Dirichlet BCs took {:g} s.", time_dirichlet); - if (!sys.isLinear() && _convergence_criterion->hasResidualCheck()) { + if (!sys.isLinear() && _convergence_criterion->hasResidualCheck()) + { GlobalVector res; LinAlg::matMult(A, *x_new[process_id], res); // res = A * x_new - LinAlg::axpy(res, -1.0, rhs); // res -= rhs + LinAlg::axpy(res, -1.0, rhs); // res -= rhs _convergence_criterion->checkResidual(res); } @@ -162,10 +160,14 @@ NonlinearSolverStatus NonlinearSolver<NonlinearSolverTag::Picard>::solve( break; } - if (sys.isLinear()) { + if (sys.isLinear()) + { error_norms_met = true; - } else { - if (_convergence_criterion->hasDeltaXCheck()) { + } + else + { + if (_convergence_criterion->hasDeltaXCheck()) + { GlobalVector minus_delta_x(*x[process_id]); LinAlg::axpy(minus_delta_x, -1.0, *x_new[process_id]); // minus_delta_x = x - x_new @@ -234,13 +236,10 @@ NonlinearSolverStatus NonlinearSolver<NonlinearSolverTag::Newton>::solve( namespace LinAlg = MathLib::LinAlg; auto& sys = *_equation_system; - auto& res = NumLib::GlobalVectorProvider::provider.getVector( - _res_id); + auto& res = NumLib::GlobalVectorProvider::provider.getVector(_res_id); auto& minus_delta_x = - NumLib::GlobalVectorProvider::provider.getVector( - _minus_delta_x_id); - auto& J = - NumLib::GlobalMatrixProvider::provider.getMatrix(_J_id); + NumLib::GlobalVectorProvider::provider.getVector(_minus_delta_x_id); + auto& J = NumLib::GlobalMatrixProvider::provider.getMatrix(_J_id); bool error_norms_met = false; @@ -251,8 +250,7 @@ NonlinearSolverStatus NonlinearSolver<NonlinearSolverTag::Newton>::solve( _convergence_criterion->preFirstIteration(); int iteration = 1; - for (; iteration <= _maxiter; - ++iteration, _convergence_criterion->reset()) + for (; iteration <= _maxiter; ++iteration, _convergence_criterion->reset()) { BaseLib::RunTime timer_dirichlet; double time_dirichlet = 0.0; @@ -340,8 +338,7 @@ NonlinearSolverStatus NonlinearSolver<NonlinearSolverTag::Newton>::solve( case IterationResult::REPEAT_ITERATION: INFO( "Newton: The postIteration() hook decided that this " - "iteration" - " has to be repeated."); + "iteration has to be repeated."); // TODO introduce some onDestroy hook. NumLib::GlobalVectorProvider::provider.releaseVector( *x_new[process_id]); @@ -361,10 +358,14 @@ NonlinearSolverStatus NonlinearSolver<NonlinearSolverTag::Newton>::solve( break; } - if (sys.isLinear()) { + if (sys.isLinear()) + { error_norms_met = true; - } else { - if (_convergence_criterion->hasDeltaXCheck()) { + } + else + { + if (_convergence_criterion->hasDeltaXCheck()) + { // Note: x contains the new solution! _convergence_criterion->checkDeltaX(minus_delta_x, *x[process_id]); @@ -398,8 +399,7 @@ NonlinearSolverStatus NonlinearSolver<NonlinearSolverTag::Newton>::solve( NumLib::GlobalMatrixProvider::provider.releaseMatrix(J); NumLib::GlobalVectorProvider::provider.releaseVector(res); - NumLib::GlobalVectorProvider::provider.releaseVector( - minus_delta_x); + NumLib::GlobalVectorProvider::provider.releaseVector(minus_delta_x); return {error_norms_met, iteration}; } @@ -413,7 +413,8 @@ createNonlinearSolver(GlobalLinearSolver& linear_solver, //! \ogs_file_param{prj__nonlinear_solvers__nonlinear_solver__max_iter} auto const max_iter = config.getConfigParameter<int>("max_iter"); - if (type == "Picard") { + if (type == "Picard") + { auto const tag = NonlinearSolverTag::Picard; using ConcreteNLS = NonlinearSolver<tag>; return std::make_pair( diff --git a/NumLib/ODESolver/TimeDiscretizedODESystem.cpp b/NumLib/ODESolver/TimeDiscretizedODESystem.cpp index d28ea348a1c45f9a2e17e8b815ddb70edc619b3d..3d941cd584d6ada88e5e5b9fc4c51d67439af991 100644 --- a/NumLib/ODESolver/TimeDiscretizedODESystem.cpp +++ b/NumLib/ODESolver/TimeDiscretizedODESystem.cpp @@ -12,8 +12,8 @@ #include "MathLib/LinAlg/ApplyKnownSolution.h" #include "MathLib/LinAlg/UnifiedMatrixSetters.h" -#include "NumLib/IndexValueVector.h" #include "NumLib/Exceptions.h" +#include "NumLib/IndexValueVector.h" namespace detail { @@ -87,7 +87,8 @@ void TimeDiscretizedODESystem<ODESystemTag::FirstOrderImplicitQuasilinear, _xdot_ids.resize(x_new_timestep.size()); for (std::size_t i = 0; i < xdot.size(); i++) { - xdot[i] = &NumLib::GlobalVectorProvider::provider.getVector(_xdot_ids[i]); + xdot[i] = + &NumLib::GlobalVectorProvider::provider.getVector(_xdot_ids[i]); _time_disc.getXdot(*x_new_timestep[i], *x_prev[i], *xdot[i]); } @@ -225,7 +226,8 @@ void TimeDiscretizedODESystem<ODESystemTag::FirstOrderImplicitQuasilinear, for (std::size_t i = 0; i < xdot.size(); i++) { - xdot[i] = &NumLib::GlobalVectorProvider::provider.getVector(_xdot_ids[i]); + xdot[i] = + &NumLib::GlobalVectorProvider::provider.getVector(_xdot_ids[i]); _time_disc.getXdot(*x_new_timestep[i], *x_prev[i], *xdot[i]); } diff --git a/NumLib/TimeStepping/Algorithms/CreateEvolutionaryPIDcontroller.cpp b/NumLib/TimeStepping/Algorithms/CreateEvolutionaryPIDcontroller.cpp index ed5a03ccbefe1624ee679ad365d719f398fc9651..c079d88b56479bdaba02102e678f2e8830603316 100644 --- a/NumLib/TimeStepping/Algorithms/CreateEvolutionaryPIDcontroller.cpp +++ b/NumLib/TimeStepping/Algorithms/CreateEvolutionaryPIDcontroller.cpp @@ -13,7 +13,6 @@ #include "BaseLib/Algorithm.h" #include "BaseLib/ConfigTree.h" - #include "EvolutionaryPIDcontroller.h" #include "TimeStepAlgorithm.h" diff --git a/NumLib/TimeStepping/Algorithms/CreateFixedTimeStepping.cpp b/NumLib/TimeStepping/Algorithms/CreateFixedTimeStepping.cpp index d4ea86361e44624f4a87f4f5271365afbc87960f..32c1d34142614071fd35e99611605524980cb9af 100644 --- a/NumLib/TimeStepping/Algorithms/CreateFixedTimeStepping.cpp +++ b/NumLib/TimeStepping/Algorithms/CreateFixedTimeStepping.cpp @@ -10,11 +10,11 @@ */ #include "CreateFixedTimeStepping.h" + #include <string> #include "BaseLib/ConfigTree.h" #include "BaseLib/Error.h" - #include "FixedTimeStepping.h" #include "TimeStepAlgorithm.h" diff --git a/NumLib/TimeStepping/Algorithms/EvolutionaryPIDcontroller.cpp b/NumLib/TimeStepping/Algorithms/EvolutionaryPIDcontroller.cpp index 89463aef6d662aa140c713853e0fb730bda064d4..05feeda9b6acc8ce2260354e91c3f78748b58b89 100644 --- a/NumLib/TimeStepping/Algorithms/EvolutionaryPIDcontroller.cpp +++ b/NumLib/TimeStepping/Algorithms/EvolutionaryPIDcontroller.cpp @@ -14,9 +14,9 @@ #include <functional> #include <limits> #include <vector> -#include "BaseLib/Logging.h" #include "BaseLib/Algorithm.h" +#include "BaseLib/Logging.h" namespace NumLib { diff --git a/NumLib/TimeStepping/Algorithms/FixedTimeStepping.cpp b/NumLib/TimeStepping/Algorithms/FixedTimeStepping.cpp index e1a1a463c976d5750cc60d4cbf1ee1c9d9fb8b68..038c84e1249a1b7508ec4e9129deacbaa7be75ae 100644 --- a/NumLib/TimeStepping/Algorithms/FixedTimeStepping.cpp +++ b/NumLib/TimeStepping/Algorithms/FixedTimeStepping.cpp @@ -13,9 +13,9 @@ #include "FixedTimeStepping.h" #include <algorithm> -#include <numeric> -#include <limits> #include <cassert> +#include <limits> +#include <numeric> namespace NumLib { diff --git a/NumLib/TimeStepping/CreateTimeStepper.cpp b/NumLib/TimeStepping/CreateTimeStepper.cpp index 384cda3c5a77eb8b09bc97e078924c1a02617d28..4074160c5695e2ba17824db00635aa05642c31ba 100644 --- a/NumLib/TimeStepping/CreateTimeStepper.cpp +++ b/NumLib/TimeStepping/CreateTimeStepper.cpp @@ -16,7 +16,6 @@ #include "BaseLib/ConfigTree.h" #include "BaseLib/Error.h" - #include "NumLib/TimeStepping/Algorithms/CreateEvolutionaryPIDcontroller.h" #include "NumLib/TimeStepping/Algorithms/CreateFixedTimeStepping.h" #include "NumLib/TimeStepping/Algorithms/CreateIterationNumberBasedTimeStepping.h" diff --git a/ParameterLib/ConstantParameter.cpp b/ParameterLib/ConstantParameter.cpp index 0df4d9caf1d7118d6b55c4ca244a48062ac4ecc7..819100c7c58f01da798724b2180c7efaa6e78248 100644 --- a/ParameterLib/ConstantParameter.cpp +++ b/ParameterLib/ConstantParameter.cpp @@ -9,6 +9,7 @@ */ #include "ConstantParameter.h" + #include "BaseLib/ConfigTree.h" #include "BaseLib/Error.h" #include "BaseLib/Logging.h" diff --git a/ParameterLib/CoordinateSystem.cpp b/ParameterLib/CoordinateSystem.cpp index 397fc394a8b452310de4505f5adb77c7a5b7cee9..ea59706a49185987753205db9f04cc7b49d060a4 100644 --- a/ParameterLib/CoordinateSystem.cpp +++ b/ParameterLib/CoordinateSystem.cpp @@ -17,10 +17,10 @@ namespace ParameterLib { static double const tolerance = 1.e-15; -static const char*const error_info = - "The determinant of the coordinate system transformation matrix is " - "'{:g}', which is not sufficiently close to unity with the tolerance of " - "'{:g}'. Please adjust the accuracy of the local system bases"; +static const char* const error_info = + "The determinant of the coordinate system transformation matrix is '{:g}', " + "which is not sufficiently close to unity with the tolerance of '{:g}'. " + "Please adjust the accuracy of the local system bases"; CoordinateSystem::CoordinateSystem(Parameter<double> const& e0, Parameter<double> const& e1) @@ -30,8 +30,7 @@ CoordinateSystem::CoordinateSystem(Parameter<double> const& e0, { OGS_FATAL( "The parameter types for the basis must be equal but they are " - "'{:s}' " - "and '{:s}'.", + "'{:s}' and '{:s}'.", typeid(_base[0]).name(), typeid(_base[1]).name()); } diff --git a/ParameterLib/CurveScaledParameter.cpp b/ParameterLib/CurveScaledParameter.cpp index 2a6c4f380bfd27e406d61a459f42b94893148090..5169e46def0ad0ebe104591bd0066c0a655522b8 100644 --- a/ParameterLib/CurveScaledParameter.cpp +++ b/ParameterLib/CurveScaledParameter.cpp @@ -9,6 +9,7 @@ */ #include "CurveScaledParameter.h" + #include "Utils.h" namespace ParameterLib diff --git a/ParameterLib/MeshElementParameter.cpp b/ParameterLib/MeshElementParameter.cpp index 56b8e0d423bd3cec1c27bc900147d9265fa00d23..ed75cb9e2f60c25fd97a7a830790f0b0fa0edd75 100644 --- a/ParameterLib/MeshElementParameter.cpp +++ b/ParameterLib/MeshElementParameter.cpp @@ -9,6 +9,7 @@ */ #include "MeshElementParameter.h" + #include "BaseLib/ConfigTree.h" #include "MeshLib/Mesh.h" diff --git a/ParameterLib/MeshNodeParameter.cpp b/ParameterLib/MeshNodeParameter.cpp index a51001e35637fcde3a65c1b9aa29fc8001510317..a8c859c1ca526a40370679152eb8ef2d2d2e2019 100644 --- a/ParameterLib/MeshNodeParameter.cpp +++ b/ParameterLib/MeshNodeParameter.cpp @@ -9,6 +9,7 @@ */ #include "MeshNodeParameter.h" + #include "BaseLib/ConfigTree.h" #include "MeshLib/Mesh.h" diff --git a/ParameterLib/Parameter.cpp b/ParameterLib/Parameter.cpp index 0cc7332faaa583c8a8af6585f1da47ef625f9c03..decebbda548c3509f886c5ae144959600ab592a0 100644 --- a/ParameterLib/Parameter.cpp +++ b/ParameterLib/Parameter.cpp @@ -9,9 +9,9 @@ */ #include "Parameter.h" + #include "BaseLib/ConfigTree.h" #include "BaseLib/Error.h" - #include "ConstantParameter.h" #include "CurveScaledParameter.h" #include "FunctionParameter.h" diff --git a/ParameterLib/RandomFieldMeshElementParameter.cpp b/ParameterLib/RandomFieldMeshElementParameter.cpp index 511b701237d008f0da74147c28a6b1c3afaf20a5..3f40f49536e1abd39176c52c0237c611487cc2e4 100644 --- a/ParameterLib/RandomFieldMeshElementParameter.cpp +++ b/ParameterLib/RandomFieldMeshElementParameter.cpp @@ -10,10 +10,11 @@ #include "RandomFieldMeshElementParameter.h" +#include <functional> +#include <random> + #include "BaseLib/ConfigTree.h" #include "MeshLib/Mesh.h" -#include <random> -#include <functional> namespace ParameterLib { diff --git a/ParameterLib/TimeDependentHeterogeneousParameter.cpp b/ParameterLib/TimeDependentHeterogeneousParameter.cpp index 3c251a3fdb6132d1be9b5339a99d615d04c8ad34..c998f469ab0f9fc953c74070a02629304c44a190 100644 --- a/ParameterLib/TimeDependentHeterogeneousParameter.cpp +++ b/ParameterLib/TimeDependentHeterogeneousParameter.cpp @@ -121,7 +121,7 @@ std::unique_ptr<ParameterBase> createTimeDependentHeterogeneousParameter( //! \ogs_file_param{prj__parameters__parameter__TimeDependentHeterogeneousParameter__time_series__pair__time} auto time = p.getConfigParameter<double>("time"); auto parameter_name = - //! \ogs_file_param{prj__parameters__parameter__TimeDependentHeterogeneousParameter__time_series__pair__parameter_name} + //! \ogs_file_param{prj__parameters__parameter__TimeDependentHeterogeneousParameter__time_series__pair__parameter_name} p.getConfigParameter<std::string>("parameter_name"); time_series.emplace_back(time, parameter_name); } diff --git a/ProcessLib/AnalyticalJacobianAssembler.cpp b/ProcessLib/AnalyticalJacobianAssembler.cpp index d560ce3bf2d27640f845d2b1ee266b393d4f4a46..6767a405da1f1eb3a4614981bb6233a26cdd9d4c 100644 --- a/ProcessLib/AnalyticalJacobianAssembler.cpp +++ b/ProcessLib/AnalyticalJacobianAssembler.cpp @@ -9,6 +9,7 @@ */ #include "AnalyticalJacobianAssembler.h" + #include "CoupledSolutionsForStaggeredScheme.h" #include "LocalAssemblerInterface.h" diff --git a/ProcessLib/BoundaryCondition/ConstraintDirichletBoundaryCondition.cpp b/ProcessLib/BoundaryCondition/ConstraintDirichletBoundaryCondition.cpp index 64a0bfeeac4a587f2b1388850f3e0bd9b9f8f4d6..406c38c7e3abf8ab6ce3eafdec4ac14cc97aa132 100644 --- a/ProcessLib/BoundaryCondition/ConstraintDirichletBoundaryCondition.cpp +++ b/ProcessLib/BoundaryCondition/ConstraintDirichletBoundaryCondition.cpp @@ -12,8 +12,8 @@ #include <algorithm> #include <vector> -#include "BaseLib/Logging.h" +#include "BaseLib/Logging.h" #include "MeshLib/MeshSearch/NodeSearch.h" // for getUniqueNodes #include "MeshLib/Node.h" #include "ParameterLib/Utils.h" @@ -78,15 +78,15 @@ ConstraintDirichletBoundaryCondition::ConstraintDirichletBoundaryCondition( "bulk_node_ids", MeshLib::MeshItemType::Node, 1); auto const& bulk_nodes = bulk_mesh.getNodes(); - auto get_bulk_element_face_id = - [&](auto const bulk_element_id, MeshLib::Element const* bc_elem) { - auto const* bulk_elem = _bulk_mesh.getElement(bulk_element_id); - std::array<MeshLib::Node*, 3> nodes{ - {bulk_nodes[(*bulk_node_ids)[bc_elem->getNode(0)->getID()]], - bulk_nodes[(*bulk_node_ids)[bc_elem->getNode(1)->getID()]], - bulk_nodes[(*bulk_node_ids)[bc_elem->getNode(2)->getID()]]}}; - return bulk_elem->identifyFace(nodes.data()); - }; + auto get_bulk_element_face_id = [&](auto const bulk_element_id, + MeshLib::Element const* bc_elem) { + auto const* bulk_elem = _bulk_mesh.getElement(bulk_element_id); + std::array<MeshLib::Node*, 3> nodes{ + {bulk_nodes[(*bulk_node_ids)[bc_elem->getNode(0)->getID()]], + bulk_nodes[(*bulk_node_ids)[bc_elem->getNode(1)->getID()]], + bulk_nodes[(*bulk_node_ids)[bc_elem->getNode(2)->getID()]]}}; + return bulk_elem->identifyFace(nodes.data()); + }; _bulk_ids.reserve(bc_elements.size()); std::transform(begin(bc_elements), end(bc_elements), @@ -210,7 +210,7 @@ void ConstraintDirichletBoundaryCondition::getEssentialBCValues( else { bc_values.ids.emplace_back(current_id); - bc_values.values.emplace_back(sum/cnt); + bc_values.values.emplace_back(sum / cnt); cnt = 1; sum = tmp_bc_value.second; current_id = tmp_bc_value.first; @@ -236,7 +236,7 @@ createConstraintDirichletBoundaryCondition( config.checkConfigParameter("type", "ConstraintDirichlet"); auto const constraint_type = - //! \ogs_file_param{prj__process_variables__process_variable__boundary_conditions__boundary_condition__ConstraintDirichletBoundaryCondition__constraint_type} + //! \ogs_file_param{prj__process_variables__process_variable__boundary_conditions__boundary_condition__ConstraintDirichletBoundaryCondition__constraint_type} config.getConfigParameter<std::string>("constraint_type"); if (constraint_type != "Flux") { @@ -247,7 +247,7 @@ createConstraintDirichletBoundaryCondition( // Todo (TF) Open question: How to specify which getFlux function should be // used for the constraint calculation? auto const constraining_process_variable = - //! \ogs_file_param{prj__process_variables__process_variable__boundary_conditions__boundary_condition__ConstraintDirichletBoundaryCondition__constraining_process_variable} + //! \ogs_file_param{prj__process_variables__process_variable__boundary_conditions__boundary_condition__ConstraintDirichletBoundaryCondition__constraining_process_variable} config.getConfigParameter<std::string>("constraining_process_variable"); if (!constraining_process.isMonolithicSchemeUsed()) @@ -259,11 +259,11 @@ createConstraintDirichletBoundaryCondition( const int process_id = 0; auto process_variables = constraining_process.getProcessVariables(process_id); - auto constraining_pv = - std::find_if(process_variables.cbegin(), process_variables.cend(), - [&constraining_process_variable](ProcessVariable const& pv) { - return pv.getName() == constraining_process_variable; - }); + auto constraining_pv = std::find_if( + process_variables.cbegin(), process_variables.cend(), + [&constraining_process_variable](ProcessVariable const& pv) { + return pv.getName() == constraining_process_variable; + }); if (constraining_pv == std::end(process_variables)) { auto const& constraining_process_variable_name = @@ -277,11 +277,11 @@ createConstraintDirichletBoundaryCondition( } auto const constraint_threshold = - //! \ogs_file_param{prj__process_variables__process_variable__boundary_conditions__boundary_condition__ConstraintDirichletBoundaryCondition__constraint_threshold} + //! \ogs_file_param{prj__process_variables__process_variable__boundary_conditions__boundary_condition__ConstraintDirichletBoundaryCondition__constraint_threshold} config.getConfigParameter<double>("constraint_threshold"); auto const constraint_direction_string = - //! \ogs_file_param{prj__process_variables__process_variable__boundary_conditions__boundary_condition__ConstraintDirichletBoundaryCondition__constraint_direction} + //! \ogs_file_param{prj__process_variables__process_variable__boundary_conditions__boundary_condition__ConstraintDirichletBoundaryCondition__constraint_direction} config.getConfigParameter<std::string>("constraint_direction"); if (constraint_direction_string != "greater" && constraint_direction_string != "lower") @@ -293,7 +293,6 @@ createConstraintDirichletBoundaryCondition( } bool const lower = constraint_direction_string == "lower"; - //! \ogs_file_param{prj__process_variables__process_variable__boundary_conditions__boundary_condition__ConstraintDirichletBoundaryCondition__parameter} auto const param_name = config.getConfigParameter<std::string>("parameter"); DBUG("Using parameter {:s}", param_name); diff --git a/ProcessLib/BoundaryCondition/CreateDirichletBoundaryConditionWithinTimeInterval.cpp b/ProcessLib/BoundaryCondition/CreateDirichletBoundaryConditionWithinTimeInterval.cpp index 90ef7229614f500256e7a4b62c52b5e36e0e2a79..8bfd85d69d9ca77e1034768f71e7ccfa81b3a8c5 100644 --- a/ProcessLib/BoundaryCondition/CreateDirichletBoundaryConditionWithinTimeInterval.cpp +++ b/ProcessLib/BoundaryCondition/CreateDirichletBoundaryConditionWithinTimeInterval.cpp @@ -16,7 +16,6 @@ namespace ProcessLib { - std::unique_ptr<BoundaryCondition> createDirichletBoundaryConditionWithinTimeInterval( BaseLib::ConfigTree const& config, MeshLib::Mesh const& bc_mesh, @@ -57,7 +56,7 @@ createDirichletBoundaryConditionWithinTimeInterval( #endif // USE_PETSC return std::make_unique<DirichletBoundaryConditionWithinTimeInterval>( - std::move(time_interval), param, bc_mesh, dof_table_bulk, - variable_id, component_id); + std::move(time_interval), param, bc_mesh, dof_table_bulk, variable_id, + component_id); } } // namespace ProcessLib diff --git a/ProcessLib/BoundaryCondition/DeactivatedSubdomainDirichlet.cpp b/ProcessLib/BoundaryCondition/DeactivatedSubdomainDirichlet.cpp index 8848b9d6116ed1efe7ad3e66fab17f6a18393e99..cfa16eb3179d09f08f9f7ba9e081eb864e62f489 100644 --- a/ProcessLib/BoundaryCondition/DeactivatedSubdomainDirichlet.cpp +++ b/ProcessLib/BoundaryCondition/DeactivatedSubdomainDirichlet.cpp @@ -37,8 +37,8 @@ DeactivatedSubdomainDirichlet::DeactivatedSubdomainDirichlet( void DeactivatedSubdomainDirichlet::config( NumLib::LocalToGlobalIndexMap const& dof_table_bulk) { - checkParametersOfDirichletBoundaryCondition(*_subdomain.mesh, dof_table_bulk, - _variable_id, _component_id); + checkParametersOfDirichletBoundaryCondition( + *_subdomain.mesh, dof_table_bulk, _variable_id, _component_id); std::vector<MeshLib::Node*> const& bc_nodes = _subdomain.mesh->getNodes(); MeshLib::MeshSubset subdomain_mesh_subset(*_subdomain.mesh, bc_nodes); @@ -80,9 +80,9 @@ void DeactivatedSubdomainDirichlet::getEssentialBCValues( }; if (time_interval_contains(t)) { - getEssentialBCValuesLocal(_parameter, *_subdomain.mesh, - inactive_nodes_in_bc_mesh, *_dof_table_boundary, - _variable_id, _component_id, t, x, bc_values); + getEssentialBCValuesLocal( + _parameter, *_subdomain.mesh, inactive_nodes_in_bc_mesh, + *_dof_table_boundary, _variable_id, _component_id, t, x, bc_values); return; } diff --git a/ProcessLib/BoundaryCondition/DirichletBoundaryCondition.cpp b/ProcessLib/BoundaryCondition/DirichletBoundaryCondition.cpp index f526cd53ef2587505911c3262c05f38c63e1984a..61c37a656f17076f03b72c6c59d45c682217f198 100644 --- a/ProcessLib/BoundaryCondition/DirichletBoundaryCondition.cpp +++ b/ProcessLib/BoundaryCondition/DirichletBoundaryCondition.cpp @@ -12,11 +12,10 @@ #include <algorithm> #include <vector> -#include "BaseLib/Logging.h" - -#include "DirichletBoundaryConditionAuxiliaryFunctions.h" #include "BaseLib/ConfigTree.h" +#include "BaseLib/Logging.h" +#include "DirichletBoundaryConditionAuxiliaryFunctions.h" #include "NumLib/DOF/LocalToGlobalIndexMap.h" #include "NumLib/IndexValueVector.h" #include "ParameterLib/Parameter.h" diff --git a/ProcessLib/BoundaryCondition/DirichletBoundaryConditionAuxiliaryFunctions.cpp b/ProcessLib/BoundaryCondition/DirichletBoundaryConditionAuxiliaryFunctions.cpp index d564e66eb5a6900c1f5a493ed255516ee4eb82c8..928e1709c6a55a09f6eb2cd9ffa5bb843ab31be3 100644 --- a/ProcessLib/BoundaryCondition/DirichletBoundaryConditionAuxiliaryFunctions.cpp +++ b/ProcessLib/BoundaryCondition/DirichletBoundaryConditionAuxiliaryFunctions.cpp @@ -14,7 +14,6 @@ #include "MeshLib/Mesh.h" #include "MeshLib/Node.h" - #include "NumLib/DOF/LocalToGlobalIndexMap.h" #include "NumLib/IndexValueVector.h" #include "ParameterLib/Parameter.h" diff --git a/ProcessLib/BoundaryCondition/HCNonAdvectiveFreeComponentFlowBoundaryCondition.cpp b/ProcessLib/BoundaryCondition/HCNonAdvectiveFreeComponentFlowBoundaryCondition.cpp index 6c155b761f9f4e2e152f0109b89476c50afc7361..660a510a53afab10aea991348a588b346a80d32e 100644 --- a/ProcessLib/BoundaryCondition/HCNonAdvectiveFreeComponentFlowBoundaryCondition.cpp +++ b/ProcessLib/BoundaryCondition/HCNonAdvectiveFreeComponentFlowBoundaryCondition.cpp @@ -9,6 +9,7 @@ */ #include "HCNonAdvectiveFreeComponentFlowBoundaryCondition.h" + #include "MeshLib/Elements/Element.h" #include "ParameterLib/Utils.h" @@ -34,8 +35,7 @@ createHCNonAdvectiveFreeComponentFlowBoundaryCondition( { OGS_FATAL( "The dimension ({:d}) of the given boundary mesh '{:s}' is not by " - "one " - "lower than the bulk dimension ({:d}).", + "one lower than the bulk dimension ({:d}).", bc_mesh.getDimension(), bc_mesh.getName(), global_dim); } diff --git a/ProcessLib/BoundaryCondition/NeumannBoundaryCondition.cpp b/ProcessLib/BoundaryCondition/NeumannBoundaryCondition.cpp index 084273cadfc6279b54fdcc4629783c81f3f30565..9bd8de32794d2241527935fe540dba0ade1a25a3 100644 --- a/ProcessLib/BoundaryCondition/NeumannBoundaryCondition.cpp +++ b/ProcessLib/BoundaryCondition/NeumannBoundaryCondition.cpp @@ -9,6 +9,7 @@ */ #include "NeumannBoundaryCondition.h" + #include "ParameterLib/Utils.h" namespace ProcessLib diff --git a/ProcessLib/BoundaryCondition/Python/BHEInflowPythonBoundaryConditionModule.cpp b/ProcessLib/BoundaryCondition/Python/BHEInflowPythonBoundaryConditionModule.cpp index 3c396b23298fc2223075cd4127b854233d68029d..9bba328b4b0913134d4979094e1706211bc903b1 100644 --- a/ProcessLib/BoundaryCondition/Python/BHEInflowPythonBoundaryConditionModule.cpp +++ b/ProcessLib/BoundaryCondition/Python/BHEInflowPythonBoundaryConditionModule.cpp @@ -38,12 +38,12 @@ public: } std::tuple<bool, bool, std::vector<double>, std::vector<double>> - tespySolver( - double t, - std::vector<double> const& Tin_val, - std::vector<double> const& Tout_val) const override + tespySolver(double t, + std::vector<double> const& Tin_val, + std::vector<double> const& Tout_val) const override { - using Ret = std::tuple<bool, bool, std::vector<double>, std::vector<double>>; + using Ret = + std::tuple<bool, bool, std::vector<double>, std::vector<double>>; PYBIND11_OVERLOAD(Ret, BHEInflowPythonBoundaryConditionPythonSideInterface, tespySolver, t, Tin_val, Tout_val); @@ -64,8 +64,7 @@ void bheInflowpythonBindBoundaryCondition(pybind11::module& m) &BHEInflowPythonBoundaryConditionPythonSideInterface:: initializeDataContainer); pybc.def("tespySolver", - &BHEInflowPythonBoundaryConditionPythonSideInterface:: - tespySolver); + &BHEInflowPythonBoundaryConditionPythonSideInterface::tespySolver); } } // namespace ProcessLib diff --git a/ProcessLib/BoundaryCondition/Python/PythonBoundaryCondition.cpp b/ProcessLib/BoundaryCondition/Python/PythonBoundaryCondition.cpp index 976dee9705b8bf8094e5fd4deeb45def05df2841..1ba9c7ecad38e2ce295978192dcc288fe9d47f0c 100644 --- a/ProcessLib/BoundaryCondition/Python/PythonBoundaryCondition.cpp +++ b/ProcessLib/BoundaryCondition/Python/PythonBoundaryCondition.cpp @@ -128,11 +128,10 @@ void PythonBoundaryCondition::getEssentialBCValues( // TODO extend Python BC to mixed FEM ansatz functions OGS_FATAL( "No d.o.f. found for (node={:d}, var={:d}, comp={:d}). " - " " - "That might be due to the use of mixed FEM ansatz " - "functions, which is currently not supported by " - "the implementation of Python BCs. That excludes, " - "e.g., the HM process.", + " That might be due to the use of mixed FEM ansatz " + "functions, which is currently not supported by the " + "implementation of Python BCs. That excludes, e.g., " + "the HM process.", bulk_node_id, var, comp); } diff --git a/ProcessLib/BoundaryCondition/SolutionDependentDirichletBoundaryCondition.cpp b/ProcessLib/BoundaryCondition/SolutionDependentDirichletBoundaryCondition.cpp index 4d8f5bc29920fa56f19eaa2a78538d60bebce755..07aa6d68218a79764c25834350821d34cdbf5018 100644 --- a/ProcessLib/BoundaryCondition/SolutionDependentDirichletBoundaryCondition.cpp +++ b/ProcessLib/BoundaryCondition/SolutionDependentDirichletBoundaryCondition.cpp @@ -47,8 +47,7 @@ SolutionDependentDirichletBoundaryCondition:: OGS_FATAL( "Found mesh property '{:s}' in the mesh '{:s}' which is for " "boundary assignment. This mesh property is the built-in property " - "of the " - "class SolutionDependentDirichletBoundaryCondition.", + "of the class SolutionDependentDirichletBoundaryCondition.", property_name, bc_mesh.getName()); } diff --git a/ProcessLib/BoundaryCondition/VariableDependentNeumannBoundaryCondition.cpp b/ProcessLib/BoundaryCondition/VariableDependentNeumannBoundaryCondition.cpp index c870a106cdc459930f32d09901c02f31c0591a13..861b2e963a7f9083f31464f7dfdfa3254d5c3331 100644 --- a/ProcessLib/BoundaryCondition/VariableDependentNeumannBoundaryCondition.cpp +++ b/ProcessLib/BoundaryCondition/VariableDependentNeumannBoundaryCondition.cpp @@ -28,8 +28,8 @@ createVariableDependentNeumannBoundaryCondition( if (dof_table.getNumberOfVariables() != 2) { OGS_FATAL( - "VariableDependentNeumann BC only implemented for 2 " - "variable processes."); + "VariableDependentNeumann BC only implemented for 2 variable " + "processes."); } assert(variable_id == 0 || variable_id == 1); diff --git a/ProcessLib/CentralDifferencesJacobianAssembler.cpp b/ProcessLib/CentralDifferencesJacobianAssembler.cpp index bd01dc7d50b7da3069b47c6ea736cf33a9320585..7d8f4d54e011bcdeb5da0d083ee2aa5d8442cf35 100644 --- a/ProcessLib/CentralDifferencesJacobianAssembler.cpp +++ b/ProcessLib/CentralDifferencesJacobianAssembler.cpp @@ -36,7 +36,8 @@ void CentralDifferencesJacobianAssembler::assembleWithJacobian( std::vector<double>& local_Jac_data) { // TODO do not check in every call. - if (local_x_data.size() % _absolute_epsilons.size() != 0) { + if (local_x_data.size() % _absolute_epsilons.size() != 0) + { OGS_FATAL( "The number of specified epsilons ({:d}) and the number of local " "d.o.f.s ({:d}) do not match, i.e., the latter is not divisible by " @@ -52,8 +53,8 @@ void CentralDifferencesJacobianAssembler::assembleWithJacobian( auto const local_xdot = MathLib::toVector<Eigen::VectorXd>(local_xdot_data, num_r_c); - auto local_Jac = MathLib::createZeroedMatrix(local_Jac_data, - num_r_c, num_r_c); + auto local_Jac = + MathLib::createZeroedMatrix(local_Jac_data, num_r_c, num_r_c); _local_x_perturbed_data = local_x_data; _local_xdot_perturbed_data = local_xdot_data; @@ -88,7 +89,8 @@ void CentralDifferencesJacobianAssembler::assembleWithJacobian( _local_x_perturbed_data[i] = local_x_data[i]; _local_xdot_perturbed_data[i] = local_xdot_data[i]; - if (!local_M_data.empty()) { + if (!local_M_data.empty()) + { auto const local_M_p = MathLib::toMatrix(local_M_data, num_r_c, num_r_c); auto const local_M_m = @@ -99,7 +101,8 @@ void CentralDifferencesJacobianAssembler::assembleWithJacobian( local_M_data.clear(); _local_M_data.clear(); } - if (!local_K_data.empty()) { + if (!local_K_data.empty()) + { auto const local_K_p = MathLib::toMatrix(local_K_data, num_r_c, num_r_c); auto const local_K_m = @@ -110,7 +113,8 @@ void CentralDifferencesJacobianAssembler::assembleWithJacobian( local_K_data.clear(); _local_K_data.clear(); } - if (!local_b_data.empty()) { + if (!local_b_data.empty()) + { auto const local_b_p = MathLib::toVector<Eigen::VectorXd>(local_b_data, num_r_c); auto const local_b_m = @@ -128,11 +132,13 @@ void CentralDifferencesJacobianAssembler::assembleWithJacobian( local_K_data, local_b_data); // Compute remaining terms of the Jacobian. - if (dxdot_dx != 0.0 && !local_M_data.empty()) { + if (dxdot_dx != 0.0 && !local_M_data.empty()) + { auto local_M = MathLib::toMatrix(local_M_data, num_r_c, num_r_c); local_Jac.noalias() += local_M * dxdot_dx; } - if (dx_dx != 0.0 && !local_K_data.empty()) { + if (dx_dx != 0.0 && !local_K_data.empty()) + { auto local_K = MathLib::toMatrix(local_K_data, num_r_c, num_r_c); local_Jac.noalias() += local_K * dx_dx; } @@ -152,7 +158,8 @@ createCentralDifferencesJacobianAssembler(BaseLib::ConfigTree const& config) auto comp_mag = config.getConfigParameterOptional<std::vector<double>>( "component_magnitudes"); - if (!!rel_eps != !!comp_mag) { + if (!!rel_eps != !!comp_mag) + { OGS_FATAL( "Either both or none of <relative_epsilons> and " "<component_magnitudes> have to be specified."); @@ -160,18 +167,23 @@ createCentralDifferencesJacobianAssembler(BaseLib::ConfigTree const& config) std::vector<double> abs_eps; - if (rel_eps) { - if (rel_eps->size() != comp_mag->size()) { + if (rel_eps) + { + if (rel_eps->size() != comp_mag->size()) + { OGS_FATAL( "The numbers of components of <relative_epsilons> and " "<component_magnitudes> do not match."); } abs_eps.resize(rel_eps->size()); - for (std::size_t i=0; i<rel_eps->size(); ++i) { + for (std::size_t i = 0; i < rel_eps->size(); ++i) + { abs_eps[i] = (*rel_eps)[i] * (*comp_mag)[i]; } - } else { + } + else + { // By default 1e-8 is used as epsilon for all components. // TODO: remove this default value. abs_eps.emplace_back(1e-8); diff --git a/ProcessLib/CompareJacobiansJacobianAssembler.cpp b/ProcessLib/CompareJacobiansJacobianAssembler.cpp index 5ef330d06cbe1c5bc22d60e81e2f8d2b01a9f34d..2eab4201b7699dc72d8d54f447f8ec78f465e1a2 100644 --- a/ProcessLib/CompareJacobiansJacobianAssembler.cpp +++ b/ProcessLib/CompareJacobiansJacobianAssembler.cpp @@ -12,9 +12,8 @@ #include <sstream> -#include "MathLib/LinAlg/Eigen/EigenMapTools.h" - #include "CreateJacobianAssembler.h" +#include "MathLib/LinAlg/Eigen/EigenMapTools.h" namespace { diff --git a/ProcessLib/ComponentTransport/CreateComponentTransportProcess.cpp b/ProcessLib/ComponentTransport/CreateComponentTransportProcess.cpp index 23a075d8b566bedeabd4d180b164ccae3a316622..4fc9bf55b24d6ec39f9b1745888d6089fe0beff1 100644 --- a/ProcessLib/ComponentTransport/CreateComponentTransportProcess.cpp +++ b/ProcessLib/ComponentTransport/CreateComponentTransportProcess.cpp @@ -11,15 +11,14 @@ #include "CreateComponentTransportProcess.h" #include "ChemistryLib/ChemicalSolverInterface.h" +#include "ComponentTransportProcess.h" +#include "ComponentTransportProcessData.h" #include "MaterialLib/MPL/CreateMaterialSpatialDistributionMap.h" #include "MeshLib/IO/readMeshFromFile.h" #include "ProcessLib/Output/CreateSecondaryVariables.h" #include "ProcessLib/SurfaceFlux/SurfaceFluxData.h" #include "ProcessLib/Utils/ProcessUtils.h" -#include "ComponentTransportProcess.h" -#include "ComponentTransportProcessData.h" - namespace ProcessLib { namespace ComponentTransport diff --git a/ProcessLib/CreateDeactivatedSubdomain.cpp b/ProcessLib/CreateDeactivatedSubdomain.cpp index 74fb1ef0429cc44d6cb5101bbda80d63d4611ab2..469c84cba75ded34dc573ed2161887dff9ef2c06 100644 --- a/ProcessLib/CreateDeactivatedSubdomain.cpp +++ b/ProcessLib/CreateDeactivatedSubdomain.cpp @@ -143,8 +143,8 @@ static std::pair<Eigen::Vector3d, Eigen::Vector3d> parseLineSegment( if (start.size() != 3) { OGS_FATAL( - "For construction of a line segment the start point must be a " - "3D point. Got a vector of size {}.", + "For construction of a line segment the start point must be a 3D " + "point. Got a vector of size {}.", start.size()); } @@ -155,8 +155,8 @@ static std::pair<Eigen::Vector3d, Eigen::Vector3d> parseLineSegment( if (end.size() != 3) { OGS_FATAL( - "For construction of a line segment the end point must be a " - "3D point. Got a vector of size {}.", + "For construction of a line segment the end point must be a 3D " + "point. Got a vector of size {}.", end.size()); } return {Eigen::Vector3d{start[0], start[1], start[2]}, diff --git a/ProcessLib/CreateJacobianAssembler.cpp b/ProcessLib/CreateJacobianAssembler.cpp index 4dd325d39bffe8ab8497ef1751c3165d0fe95c09..2c1322625e7c1d75fad77f185a403d2403e978cf 100644 --- a/ProcessLib/CreateJacobianAssembler.cpp +++ b/ProcessLib/CreateJacobianAssembler.cpp @@ -9,9 +9,9 @@ */ #include "CreateJacobianAssembler.h" -#include "BaseLib/Error.h" #include "AnalyticalJacobianAssembler.h" +#include "BaseLib/Error.h" #include "CentralDifferencesJacobianAssembler.h" #include "CompareJacobiansJacobianAssembler.h" @@ -28,7 +28,8 @@ std::unique_ptr<AbstractJacobianAssembler> createJacobianAssembler( //! \ogs_file_param{prj__processes__process__jacobian_assembler__type} auto const type = config->peekConfigParameter<std::string>("type"); - if (type == "Analytical") { + if (type == "Analytical") + { config->ignoreConfigParameter("type"); return std::make_unique<AnalyticalJacobianAssembler>(); } diff --git a/ProcessLib/CreateProcessData.cpp b/ProcessLib/CreateProcessData.cpp index 9319f67d7dd7bf8483ed88ce6fbebfe38f53b2cf..27737e26b632a45b4efed23a298154db724032bc 100644 --- a/ProcessLib/CreateProcessData.cpp +++ b/ProcessLib/CreateProcessData.cpp @@ -9,14 +9,12 @@ */ #include "BaseLib/Algorithm.h" - #include "NumLib/ODESolver/TimeDiscretizationBuilder.h" #ifdef USE_PETSC #include "NumLib/ODESolver/PETScNonlinearSolver.h" #endif // USE_PETSC -#include "NumLib/TimeStepping/CreateTimeStepper.h" - #include "CreateProcessData.h" +#include "NumLib/TimeStepping/CreateTimeStepper.h" namespace ProcessLib { @@ -117,8 +115,8 @@ std::vector<std::unique_ptr<ProcessData>> createPerProcessData( "In order to make the specification of output in the project " "file consistent, the variables output tags were moved from " "xpath " - "'//OpenGeoSysProject/time_loop/processes/process/output' " - "to the global output section, i.e., to the xpath " + "'//OpenGeoSysProject/time_loop/processes/process/output' to " + "the global output section, i.e., to the xpath " "'//OpenGeoSysProject/time_loop/output'. This has to be done " "in the current project file!"); } @@ -135,8 +133,8 @@ std::vector<std::unique_ptr<ProcessData>> createPerProcessData( if (processes.size() > 1) { OGS_FATAL( - "Some processes have not been configured to be solved by this " - " time loop."); + "Some processes have not been configured to be solved by this " + "time loop."); } else { diff --git a/ProcessLib/CreateTimeLoop.cpp b/ProcessLib/CreateTimeLoop.cpp index 15e677bc60fd92e0413e729811b551e807933202..44138a4d5a427444693a2a8035d5052d8df75279 100644 --- a/ProcessLib/CreateTimeLoop.cpp +++ b/ProcessLib/CreateTimeLoop.cpp @@ -14,7 +14,6 @@ #include "ProcessLib/CreateProcessData.h" #include "ProcessLib/Output/CreateOutput.h" #include "ProcessLib/Output/Output.h" - #include "TimeLoop.h" namespace ProcessLib diff --git a/ProcessLib/HT/CreateHTProcess.cpp b/ProcessLib/HT/CreateHTProcess.cpp index abc76f0be750b1e658d657f9483d7cc523b3f501..7b412b43550a9c9c52d73e487407734e1c169086 100644 --- a/ProcessLib/HT/CreateHTProcess.cpp +++ b/ProcessLib/HT/CreateHTProcess.cpp @@ -10,6 +10,9 @@ #include "CreateHTProcess.h" +#include "HTLocalAssemblerInterface.h" +#include "HTProcess.h" +#include "HTProcessData.h" #include "MaterialLib/MPL/CheckMaterialSpatialDistributionMap.h" #include "MaterialLib/MPL/CreateMaterialSpatialDistributionMap.h" #include "MeshLib/IO/readMeshFromFile.h" @@ -19,10 +22,6 @@ #include "ProcessLib/SurfaceFlux/SurfaceFluxData.h" #include "ProcessLib/Utils/ProcessUtils.h" -#include "HTProcess.h" -#include "HTProcessData.h" -#include "HTLocalAssemblerInterface.h" - namespace ProcessLib { namespace HT @@ -46,8 +45,8 @@ void checkMPLProperties( MaterialPropertyLib::PropertyType::storage}; MaterialPropertyLib::checkMaterialSpatialDistributionMap( - mesh, media_map, required_property_medium, required_property_solid_phase, - required_property_liquid_phase); + mesh, media_map, required_property_medium, + required_property_solid_phase, required_property_liquid_phase); } std::unique_ptr<Process> createHTProcess( diff --git a/ProcessLib/HT/HTProcess.cpp b/ProcessLib/HT/HTProcess.cpp index 13acb43a21fc087eef9db5fcf07884223ffa4067..d4b80bef82c498a6bb18b59b9fe8a3732cc6680f 100644 --- a/ProcessLib/HT/HTProcess.cpp +++ b/ProcessLib/HT/HTProcess.cpp @@ -12,12 +12,11 @@ #include <cassert> +#include "MonolithicHTFEM.h" #include "NumLib/DOF/DOFTableUtil.h" #include "NumLib/DOF/LocalToGlobalIndexMap.h" #include "ProcessLib/SurfaceFlux/SurfaceFluxData.h" #include "ProcessLib/Utils/CreateLocalAssemblers.h" - -#include "MonolithicHTFEM.h" #include "StaggeredHTFEM.h" namespace ProcessLib @@ -207,8 +206,8 @@ void HTProcess::postTimestepConcreteProcess(std::vector<GlobalVector*> const& x, if (_use_monolithic_scheme && process_id != 0) { OGS_FATAL( - "The condition of process_id = 0 must be satisfied for " - "monolithic HTProcess, which is a single process."); + "The condition of process_id = 0 must be satisfied for monolithic " + "HTProcess, which is a single process."); } if (!_use_monolithic_scheme && process_id != _process_data.hydraulic_process_id) diff --git a/ProcessLib/HeatConduction/HeatConductionProcess.cpp b/ProcessLib/HeatConduction/HeatConductionProcess.cpp index 13f0fe54d4bde56d6d2e042647d74c8718adcde1..2cab6d4bb1b10e77f1bea375bdb4498477ca96b7 100644 --- a/ProcessLib/HeatConduction/HeatConductionProcess.cpp +++ b/ProcessLib/HeatConduction/HeatConductionProcess.cpp @@ -13,8 +13,8 @@ #include <cassert> #include "NumLib/DOF/DOFTableUtil.h" -#include "ProcessLib/Utils/CreateLocalAssemblers.h" #include "ProcessLib/Utils/ComputeResiduum.h" +#include "ProcessLib/Utils/CreateLocalAssemblers.h" namespace ProcessLib { diff --git a/ProcessLib/HeatTransportBHE/BHE/BHE_1P.cpp b/ProcessLib/HeatTransportBHE/BHE/BHE_1P.cpp index f8015e89efc4db19e8ab8082c721d0fc74b39cb3..80e41d3b300488f5310d1253d029ee50b05a8d32 100644 --- a/ProcessLib/HeatTransportBHE/BHE/BHE_1P.cpp +++ b/ProcessLib/HeatTransportBHE/BHE/BHE_1P.cpp @@ -11,6 +11,7 @@ #include "BHE_1P.h" #include <boost/math/constants/constants.hpp> + #include "FlowAndTemperatureControl.h" #include "Physics.h" #include "ThermoMechanicalFlowProperties.h" diff --git a/ProcessLib/HeatTransportBHE/BHE/BHE_1U.cpp b/ProcessLib/HeatTransportBHE/BHE/BHE_1U.cpp index 2ef82cbe6b649f3039adc7a35e9d1c90d51b5ab8..1f0fc430c97209317aeeef4c79a4de26fae42b96 100644 --- a/ProcessLib/HeatTransportBHE/BHE/BHE_1U.cpp +++ b/ProcessLib/HeatTransportBHE/BHE/BHE_1U.cpp @@ -11,6 +11,7 @@ #include "BHE_1U.h" #include <boost/math/constants/constants.hpp> + #include "FlowAndTemperatureControl.h" #include "Physics.h" #include "ThermoMechanicalFlowProperties.h" diff --git a/ProcessLib/HeatTransportBHE/BHE/BHE_2U.cpp b/ProcessLib/HeatTransportBHE/BHE/BHE_2U.cpp index 99555a2ea541cb02815d5efbc62664e8c1db6ba5..0a9255667c931a6d2337b2c720d914bcf0905f6b 100644 --- a/ProcessLib/HeatTransportBHE/BHE/BHE_2U.cpp +++ b/ProcessLib/HeatTransportBHE/BHE/BHE_2U.cpp @@ -11,6 +11,7 @@ #include "BHE_2U.h" #include <boost/math/constants/constants.hpp> + #include "FlowAndTemperatureControl.h" #include "Physics.h" #include "ThermoMechanicalFlowProperties.h" diff --git a/ProcessLib/HeatTransportBHE/BHE/BoreholeGeometry.cpp b/ProcessLib/HeatTransportBHE/BHE/BoreholeGeometry.cpp index 494a444874bdd7bbf1782bfa88ef9194230f54c0..509dd1b6e6603ceba7e3efa4e4b866ddc3566ffe 100644 --- a/ProcessLib/HeatTransportBHE/BHE/BoreholeGeometry.cpp +++ b/ProcessLib/HeatTransportBHE/BHE/BoreholeGeometry.cpp @@ -9,6 +9,7 @@ */ #include "BoreholeGeometry.h" + #include "BaseLib/ConfigTree.h" namespace ProcessLib diff --git a/ProcessLib/HeatTransportBHE/BHE/CreateBHE1PType.cpp b/ProcessLib/HeatTransportBHE/BHE/CreateBHE1PType.cpp index 0cd2ef56f9fb076c37c73eb9682471c4ea40b247..66cb35c65f3c8cd338a85818f84eeaa61cca5589 100644 --- a/ProcessLib/HeatTransportBHE/BHE/CreateBHE1PType.cpp +++ b/ProcessLib/HeatTransportBHE/BHE/CreateBHE1PType.cpp @@ -8,10 +8,9 @@ * http://www.opengeosys.org/project/license */ +#include "BHE_1P.h" #include "BaseLib/ConfigTree.h" #include "CreateBHEUType.h" - -#include "BHE_1P.h" #include "CreateFlowAndTemperatureControl.h" namespace ProcessLib diff --git a/ProcessLib/HeatTransportBHE/BHE/CreateBHECoaxial.cpp b/ProcessLib/HeatTransportBHE/BHE/CreateBHECoaxial.cpp index d540924517d7a58ea96c8f68eaff3046253850b8..a75151c65f0f5fec85a37101478b52b737248218 100644 --- a/ProcessLib/HeatTransportBHE/BHE/CreateBHECoaxial.cpp +++ b/ProcessLib/HeatTransportBHE/BHE/CreateBHECoaxial.cpp @@ -9,10 +9,10 @@ */ #include "CreateBHECoaxial.h" -#include "BaseLib/ConfigTree.h" #include "BHE_CXA.h" #include "BHE_CXC.h" +#include "BaseLib/ConfigTree.h" #include "CreateFlowAndTemperatureControl.h" namespace ProcessLib { diff --git a/ProcessLib/HeatTransportBHE/BHE/CreateBHEUType.cpp b/ProcessLib/HeatTransportBHE/BHE/CreateBHEUType.cpp index 3cc75827c89654f0dadd6de8b7a26b635b2bb51c..af5408736887d11accbf65627d1ac911fbba8447 100644 --- a/ProcessLib/HeatTransportBHE/BHE/CreateBHEUType.cpp +++ b/ProcessLib/HeatTransportBHE/BHE/CreateBHEUType.cpp @@ -9,11 +9,11 @@ */ #include "CreateBHEUType.h" -#include "BaseLib/ConfigTree.h" #include "BHE_1P.h" #include "BHE_1U.h" #include "BHE_2U.h" +#include "BaseLib/ConfigTree.h" #include "CreateFlowAndTemperatureControl.h" namespace ProcessLib { diff --git a/ProcessLib/HeatTransportBHE/BHE/CreateFlowAndTemperatureControl.cpp b/ProcessLib/HeatTransportBHE/BHE/CreateFlowAndTemperatureControl.cpp index 7c389e7f5b610a9c58345ac6f837e9330f3a479c..b90fc9f6ec16c5dd95bae40816e00704d63d582d 100644 --- a/ProcessLib/HeatTransportBHE/BHE/CreateFlowAndTemperatureControl.cpp +++ b/ProcessLib/HeatTransportBHE/BHE/CreateFlowAndTemperatureControl.cpp @@ -8,12 +8,12 @@ * http://www.opengeosys.org/project/license */ +#include "CreateFlowAndTemperatureControl.h" + #include "BaseLib/Algorithm.h" #include "BaseLib/ConfigTree.h" -#include "MathLib/InterpolationAlgorithms/PiecewiseLinearInterpolation.h" - #include "BuildingPowerCurves.h" -#include "CreateFlowAndTemperatureControl.h" +#include "MathLib/InterpolationAlgorithms/PiecewiseLinearInterpolation.h" #include "RefrigerantProperties.h" namespace ProcessLib diff --git a/ProcessLib/HeatTransportBHE/BHE/GroutParameters.cpp b/ProcessLib/HeatTransportBHE/BHE/GroutParameters.cpp index 951d539429f6e4e4db8c6b47d9e8b06da2473047..f49dd9a15140c9fa552470a0045604daa8385a83 100644 --- a/ProcessLib/HeatTransportBHE/BHE/GroutParameters.cpp +++ b/ProcessLib/HeatTransportBHE/BHE/GroutParameters.cpp @@ -9,6 +9,7 @@ */ #include "GroutParameters.h" + #include "BaseLib/ConfigTree.h" namespace ProcessLib diff --git a/ProcessLib/HeatTransportBHE/BHE/Pipe.cpp b/ProcessLib/HeatTransportBHE/BHE/Pipe.cpp index 44c3249f71b36963ce2afdab5d6670f9ccacd22c..ec2f036a3089d97013d8b9897ee181ab1c5ac081 100644 --- a/ProcessLib/HeatTransportBHE/BHE/Pipe.cpp +++ b/ProcessLib/HeatTransportBHE/BHE/Pipe.cpp @@ -9,6 +9,7 @@ */ #include "Pipe.h" + #include "BaseLib/ConfigTree.h" namespace ProcessLib diff --git a/ProcessLib/HeatTransportBHE/BHE/RefrigerantProperties.cpp b/ProcessLib/HeatTransportBHE/BHE/RefrigerantProperties.cpp index e29a201a5282d141edc23ddd6cd7dce1c8439f17..e1fdf5a5bf72c2bd29f039c9d4d1a0018e6fb487 100644 --- a/ProcessLib/HeatTransportBHE/BHE/RefrigerantProperties.cpp +++ b/ProcessLib/HeatTransportBHE/BHE/RefrigerantProperties.cpp @@ -9,6 +9,7 @@ */ #include "RefrigerantProperties.h" + #include "BaseLib/ConfigTree.h" namespace ProcessLib diff --git a/ProcessLib/HeatTransportBHE/BoundaryConditions/BHEBottomDirichletBoundaryCondition.cpp b/ProcessLib/HeatTransportBHE/BoundaryConditions/BHEBottomDirichletBoundaryCondition.cpp index ffac298e87fec7c454907c4d7a13dca7ce112c4e..bd5fd16eeee18f4551f6349767b199981517e419 100644 --- a/ProcessLib/HeatTransportBHE/BoundaryConditions/BHEBottomDirichletBoundaryCondition.cpp +++ b/ProcessLib/HeatTransportBHE/BoundaryConditions/BHEBottomDirichletBoundaryCondition.cpp @@ -9,6 +9,7 @@ */ #include "BHEBottomDirichletBoundaryCondition.h" + #include "BaseLib/Error.h" namespace ProcessLib::HeatTransportBHE diff --git a/ProcessLib/HeatTransportBHE/CreateHeatTransportBHEProcess.cpp b/ProcessLib/HeatTransportBHE/CreateHeatTransportBHEProcess.cpp index ffd05169237fdcc5514d3c57d05579a19b0a7c1d..b0ef6a9d7c6f19e9b1cf0acc69a71f3dbbb16cd5 100644 --- a/ProcessLib/HeatTransportBHE/CreateHeatTransportBHEProcess.cpp +++ b/ProcessLib/HeatTransportBHE/CreateHeatTransportBHEProcess.cpp @@ -12,15 +12,14 @@ #include <vector> -#include "ParameterLib/Utils.h" -#include "ProcessLib/Output/CreateSecondaryVariables.h" - #include "BHE/BHETypes.h" +#include "BHE/CreateBHE1PType.h" #include "BHE/CreateBHECoaxial.h" #include "BHE/CreateBHEUType.h" -#include "BHE/CreateBHE1PType.h" #include "HeatTransportBHEProcess.h" #include "HeatTransportBHEProcessData.h" +#include "ParameterLib/Utils.h" +#include "ProcessLib/Output/CreateSecondaryVariables.h" #ifdef OGS_USE_PYTHON #include <pybind11/pybind11.h> #endif // OGS_USE_PYTHON @@ -79,8 +78,7 @@ std::unique_ptr<Process> createHeatTransportBHEProcess( { OGS_FATAL( "Could not find process variable '{:s}' in the provided " - "variables " - "list for config tag <{:s}>.", + "variables list for config tag <{:s}>.", pv_name, "process_variable"); } DBUG("Found process variable '{:s}' for config tag <{:s}>.", @@ -168,8 +166,7 @@ std::unique_ptr<Process> createHeatTransportBHEProcess( if (!scope.contains("bc_bhe")) OGS_FATAL( "Function 'bc_bhe' is not defined in the python script file, " - "or there " - "was no python script file specified."); + "or there was no python script file specified."); py_object = scope["bc_bhe"] @@ -220,9 +217,8 @@ std::unique_ptr<Process> createHeatTransportBHEProcess( #endif // OGS_USE_PYTHON } - HeatTransportBHEProcessData process_data(std::move(media_map), - std::move(bhes), - py_object); + HeatTransportBHEProcessData process_data( + std::move(media_map), std::move(bhes), py_object); SecondaryVariableCollection secondary_variables; diff --git a/ProcessLib/HeatTransportBHE/HeatTransportBHEProcess.cpp b/ProcessLib/HeatTransportBHE/HeatTransportBHEProcess.cpp index 415f190d070010c15195d280c744bae00ae660f9..0f54e4aff5e9b0c071f2251d71b632d7bdcdbde8 100644 --- a/ProcessLib/HeatTransportBHE/HeatTransportBHEProcess.cpp +++ b/ProcessLib/HeatTransportBHE/HeatTransportBHEProcess.cpp @@ -112,7 +112,7 @@ void HeatTransportBHEProcess::constructDofTable() // Here the number of components equals to the // number of unknowns on the BHE number_of_unknowns, - [& ms = _mesh_subset_BHE_nodes.back()]() { return *ms; }); + [&ms = _mesh_subset_BHE_nodes.back()]() { return *ms; }); vec_n_components.push_back(number_of_unknowns); vec_var_elements.push_back(&bhe_elements); @@ -239,9 +239,7 @@ NumLib::IterationResult HeatTransportBHEProcess::postIterationConcreteProcess( std::get<2>(_process_data.py_bc_object->dataframe_network)); if (!_process_data.py_bc_object->isOverriddenTespy()) { - DBUG( - "Method `tespySolver' not overridden in Python " - "script."); + DBUG("Method `tespySolver' not overridden in Python script."); } // update the Tin and flow rate @@ -320,8 +318,8 @@ void HeatTransportBHEProcess::createBHEBoundaryConditionTopBottom( { INFO( "For 1P-type BHE, the BHE inflow and outflow " - "nodes are identified according to their mesh node " - "id in ascending order"); + "nodes are identified according to their mesh node id in " + "ascending order"); } // for 1U, 2U, CXC, CXA type BHE else @@ -335,12 +333,12 @@ void HeatTransportBHEProcess::createBHEBoundaryConditionTopBottom( } } - auto get_global_index = - [&](std::size_t const node_id, int const component) { - return _local_to_global_index_map->getGlobalIndex( - {_mesh.getID(), MeshLib::MeshItemType::Node, node_id}, - variable_id, component); - }; + auto get_global_index = [&](std::size_t const node_id, + int const component) { + return _local_to_global_index_map->getGlobalIndex( + {_mesh.getID(), MeshLib::MeshItemType::Node, node_id}, + variable_id, component); + }; auto get_global_bhe_bc_indices = [&](std::array< @@ -413,11 +411,11 @@ void HeatTransportBHEProcess::createBHEBoundaryConditionTopBottom( bcs.addBoundaryCondition( createBHEBottomDirichletBoundaryCondition( get_global_bhe_bc_indices( - {{{bc_bottom_node_id, in_out_component_id.first}, + {{{bc_bottom_node_id, + in_out_component_id.first}, {bc_bottom_node_id, in_out_component_id.second}}}))); } - } }; visit(createBCs, _process_data._vec_BHE_property[bhe_i]); diff --git a/ProcessLib/HydroMechanics/CreateHydroMechanicsProcess.cpp b/ProcessLib/HydroMechanics/CreateHydroMechanicsProcess.cpp index e66ac8e3cc21c5f63ae3b182dd3b75459e37608f..aec517c09e33b7bc6768b2eff0964eddb99322e8 100644 --- a/ProcessLib/HydroMechanics/CreateHydroMechanicsProcess.cpp +++ b/ProcessLib/HydroMechanics/CreateHydroMechanicsProcess.cpp @@ -12,19 +12,17 @@ #include <cassert> +#include "HydroMechanicsProcess.h" +#include "HydroMechanicsProcessData.h" #include "MaterialLib/MPL/CreateMaterialSpatialDistributionMap.h" #include "MaterialLib/MPL/MaterialSpatialDistributionMap.h" #include "MaterialLib/MPL/Medium.h" - #include "MaterialLib/SolidModels/CreateConstitutiveRelation.h" #include "MaterialLib/SolidModels/MechanicsBase.h" #include "ParameterLib/Utils.h" #include "ProcessLib/Output/CreateSecondaryVariables.h" #include "ProcessLib/Utils/ProcessUtils.h" -#include "HydroMechanicsProcess.h" -#include "HydroMechanicsProcessData.h" - namespace ProcessLib { namespace HydroMechanics @@ -68,9 +66,9 @@ std::unique_ptr<Process> createHydroMechanicsProcess( auto per_process_variables = findProcessVariables( variables, pv_config, {//! \ogs_file_param_special{prj__processes__process__HYDRO_MECHANICS__process_variables__pressure} - "pressure", - //! \ogs_file_param_special{prj__processes__process__HYDRO_MECHANICS__process_variables__displacement} - "displacement"}); + "pressure", + //! \ogs_file_param_special{prj__processes__process__HYDRO_MECHANICS__process_variables__displacement} + "displacement"}); variable_p = &per_process_variables[0].get(); variable_u = &per_process_variables[1].get(); process_variables.push_back(std::move(per_process_variables)); @@ -144,13 +142,11 @@ std::unique_ptr<Process> createHydroMechanicsProcess( std::array const requiredMediumProperties = { MaterialPropertyLib::reference_temperature, - MaterialPropertyLib::permeability, - MaterialPropertyLib::porosity, MaterialPropertyLib::biot_coefficient - }; - std::array const requiredFluidProperties = { - MaterialPropertyLib::viscosity, MaterialPropertyLib::density}; - std::array const requiredSolidProperties = { - MaterialPropertyLib::density}; + MaterialPropertyLib::permeability, MaterialPropertyLib::porosity, + MaterialPropertyLib::biot_coefficient}; + std::array const requiredFluidProperties = {MaterialPropertyLib::viscosity, + MaterialPropertyLib::density}; + std::array const requiredSolidProperties = {MaterialPropertyLib::density}; for (auto const& element : mesh.getElements()) { diff --git a/ProcessLib/HydroMechanics/HydroMechanicsProcess.cpp b/ProcessLib/HydroMechanics/HydroMechanicsProcess.cpp index 5187d5d3152ce21ea723a38b84c575b2256fe61e..c304174a32f80ac67623e02a042ae7bb040a0a8e 100644 --- a/ProcessLib/HydroMechanics/HydroMechanicsProcess.cpp +++ b/ProcessLib/HydroMechanics/HydroMechanicsProcess.cpp @@ -228,9 +228,8 @@ void HydroMechanicsProcess<DisplacementDim>::initializeConcreteProcess( DisplacementDim>::RowsAtCompileTime, &LocalAssemblerIF::getIntPtEpsilon); - add_secondary_variable("velocity", - DisplacementDim, - &LocalAssemblerIF::getIntPtDarcyVelocity); + add_secondary_variable( + "velocity", DisplacementDim, &LocalAssemblerIF::getIntPtDarcyVelocity); // // enable output of internal variables defined by material models @@ -383,8 +382,8 @@ void HydroMechanicsProcess<DisplacementDim>:: if (_use_monolithic_scheme) { DBUG( - "Assemble the Jacobian of HydroMechanics for the monolithic" - " scheme."); + "Assemble the Jacobian of HydroMechanics for the monolithic " + "scheme."); dof_tables.emplace_back(*_local_to_global_index_map); } else diff --git a/ProcessLib/LIE/Common/PostUtils.cpp b/ProcessLib/LIE/Common/PostUtils.cpp index 2cb3c9ce64cb4f571051d4e64e1f6053be7efc37..f5934f92ebbe3e2ee4d44fdb376243b1ea9a9d49 100644 --- a/ProcessLib/LIE/Common/PostUtils.cpp +++ b/ProcessLib/LIE/Common/PostUtils.cpp @@ -235,8 +235,8 @@ PostProcessTool::PostProcessTool( { copyPropertyValues(*p, createProperty(*p)); } - else if (auto p = - dynamic_cast<MeshLib::PropertyVector<long long>*>(property)) + else if (auto p = dynamic_cast<MeshLib::PropertyVector<long long>*>( + property)) { copyPropertyValues(*p, createProperty(*p)); } diff --git a/ProcessLib/LIE/HydroMechanics/CreateHydroMechanicsProcess.cpp b/ProcessLib/LIE/HydroMechanics/CreateHydroMechanicsProcess.cpp index 466082801e3759e546e77d9cb625898b211ea05a..4f79279a69aa37e0189fcd06f32bdce9dcb181ec 100644 --- a/ProcessLib/LIE/HydroMechanics/CreateHydroMechanicsProcess.cpp +++ b/ProcessLib/LIE/HydroMechanics/CreateHydroMechanicsProcess.cpp @@ -78,8 +78,7 @@ std::unique_ptr<Process> createHydroMechanicsProcess( { OGS_FATAL( "Could not find process variable '{:s}' in the provided " - "variables " - "list for config tag <{:s}>.", + "variables list for config tag <{:s}>.", pv_name, "process_variable"); } DBUG("Found process variable '{:s}' for config tag <{:s}>.", @@ -90,8 +89,8 @@ std::unique_ptr<Process> createHydroMechanicsProcess( { OGS_FATAL( "Number of components of the process variable '{:s}' is " - "different " - "from the displacement dimension: got {:d}, expected {:d}", + "different from the displacement dimension: got {:d}, expected " + "{:d}", variable->getName(), variable->getNumberOfGlobalComponents(), GlobalDim); diff --git a/ProcessLib/LIE/HydroMechanics/HydroMechanicsProcess.cpp b/ProcessLib/LIE/HydroMechanics/HydroMechanicsProcess.cpp index 880b3dd55603ff3f52245a497292659479034cd2..9f74d56d3a48cc537ffbb7290d5dc44291be86ed 100644 --- a/ProcessLib/LIE/HydroMechanics/HydroMechanicsProcess.cpp +++ b/ProcessLib/LIE/HydroMechanics/HydroMechanicsProcess.cpp @@ -10,26 +10,23 @@ #include "HydroMechanicsProcess.h" +#include "LocalAssembler/CreateLocalAssemblers.h" +#include "LocalAssembler/HydroMechanicsLocalAssemblerFracture.h" +#include "LocalAssembler/HydroMechanicsLocalAssemblerMatrix.h" +#include "LocalAssembler/HydroMechanicsLocalAssemblerMatrixNearFracture.h" #include "MeshLib/ElementCoordinatesMappingLocal.h" #include "MeshLib/ElementStatus.h" #include "MeshLib/Elements/Utils.h" #include "MeshLib/Mesh.h" #include "MeshLib/MeshInformation.h" #include "MeshLib/Properties.h" - #include "NumLib/DOF/DOFTableUtil.h" #include "NumLib/DOF/LocalToGlobalIndexMap.h" - #include "ParameterLib/MeshElementParameter.h" #include "ProcessLib/LIE/Common/BranchProperty.h" #include "ProcessLib/LIE/Common/JunctionProperty.h" #include "ProcessLib/LIE/Common/MeshUtils.h" -#include "LocalAssembler/CreateLocalAssemblers.h" -#include "LocalAssembler/HydroMechanicsLocalAssemblerFracture.h" -#include "LocalAssembler/HydroMechanicsLocalAssemblerMatrix.h" -#include "LocalAssembler/HydroMechanicsLocalAssemblerMatrixNearFracture.h" - namespace ProcessLib { namespace LIE @@ -213,10 +210,11 @@ void HydroMechanicsProcess<GlobalDim>::initializeConcreteProcess( HydroMechanicsLocalAssemblerFracture>( mesh.getElements(), dof_table, // use displacement process variable for shapefunction order - getProcessVariables( - monolithic_process_id)[1].get().getShapeFunctionOrder(), - _local_assemblers, mesh.isAxiallySymmetric(), integration_order, - _process_data); + getProcessVariables(monolithic_process_id)[1] + .get() + .getShapeFunctionOrder(), + _local_assemblers, mesh.isAxiallySymmetric(), integration_order, + _process_data); auto mesh_prop_sigma_xx = MeshLib::getOrCreateMeshProperty<double>( const_cast<MeshLib::Mesh&>(mesh), "stress_xx", @@ -496,8 +494,7 @@ void HydroMechanicsProcess<GlobalDim>::postTimestepConcreteProcess( if (it == pvs.end()) { OGS_FATAL( - "Didn't find expected 'displacement_jump1' process " - "variable."); + "Didn't find expected 'displacement_jump1' process variable."); } g_variable_id = static_cast<int>(std::distance(pvs.begin(), it)); } @@ -512,8 +509,8 @@ void HydroMechanicsProcess<GlobalDim>::postTimestepConcreteProcess( _mesh, pv_g.getName(), MeshLib::MeshItemType::Node, num_comp); for (int component_id = 0; component_id < num_comp; ++component_id) { - auto const& mesh_subset = dof_table.getMeshSubset( - g_variable_id, component_id); + auto const& mesh_subset = + dof_table.getMeshSubset(g_variable_id, component_id); auto const mesh_id = mesh_subset.getMeshID(); for (auto const* node : mesh_subset.getNodes()) { @@ -604,7 +601,7 @@ void HydroMechanicsProcess<GlobalDim>::assembleWithJacobianConcreteProcess( // Call global assembler for each local assembly item. std::vector<std::reference_wrapper<NumLib::LocalToGlobalIndexMap>> - dof_table = {std::ref(*_local_to_global_index_map)}; + dof_table = {std::ref(*_local_to_global_index_map)}; GlobalExecutor::executeSelectedMemberDereferenced( _global_assembler, &VectorMatrixAssembler::assembleWithJacobian, _local_assemblers, pv.getActiveElementIDs(), dof_table, t, dt, x, xdot, diff --git a/ProcessLib/LIE/SmallDeformation/CreateSmallDeformationProcess.cpp b/ProcessLib/LIE/SmallDeformation/CreateSmallDeformationProcess.cpp index 89b644f2b78178a76d4a0079ff785ee18cb1e1fd..fdf824e41270e73d25b4c27707a1a28ba8a3d5c2 100644 --- a/ProcessLib/LIE/SmallDeformation/CreateSmallDeformationProcess.cpp +++ b/ProcessLib/LIE/SmallDeformation/CreateSmallDeformationProcess.cpp @@ -169,8 +169,7 @@ std::unique_ptr<Process> createSmallDeformationProcess( { OGS_FATAL( "The number of displacement jumps and the number of " - "<fracture_properties> " - "are not consistent"); + "<fracture_properties> are not consistent"); } // Reference temperature diff --git a/ProcessLib/LIE/SmallDeformation/SmallDeformationProcess.cpp b/ProcessLib/LIE/SmallDeformation/SmallDeformationProcess.cpp index e0fd6d8183de4d9592b5cd496c4fe411ccf142a2..a6186f4f64352a2523d45dc59acabaaa5a99697d 100644 --- a/ProcessLib/LIE/SmallDeformation/SmallDeformationProcess.cpp +++ b/ProcessLib/LIE/SmallDeformation/SmallDeformationProcess.cpp @@ -13,9 +13,7 @@ #include "MeshLib/ElementCoordinatesMappingLocal.h" #include "MeshLib/Mesh.h" #include "MeshLib/Properties.h" - #include "NumLib/DOF/LocalToGlobalIndexMap.h" - #include "ProcessLib/LIE/Common/BranchProperty.h" #include "ProcessLib/LIE/Common/MeshUtils.h" #include "ProcessLib/LIE/SmallDeformation/LocalAssembler/CreateLocalAssemblers.h" @@ -60,8 +58,7 @@ SmallDeformationProcess<DisplacementDim>::SmallDeformationProcess( { OGS_FATAL( "The number of the given fracture properties ({:d}) are not " - "consistent" - " with the number of fracture groups in a mesh ({:d}).", + "consistent with the number of fracture groups in a mesh ({:d}).", _process_data.fracture_properties.size(), _vec_fracture_mat_IDs.size()); } diff --git a/ProcessLib/LiquidFlow/CreateLiquidFlowProcess.cpp b/ProcessLib/LiquidFlow/CreateLiquidFlowProcess.cpp index d1af03e1d201fdc0c51b90dfdb9c6f7dd3e2009c..a9869bcfc276eb0c2ca8dbcfafb8ede1fc536973 100644 --- a/ProcessLib/LiquidFlow/CreateLiquidFlowProcess.cpp +++ b/ProcessLib/LiquidFlow/CreateLiquidFlowProcess.cpp @@ -13,6 +13,7 @@ #include <algorithm> +#include "LiquidFlowProcess.h" #include "MaterialLib/MPL/CheckMaterialSpatialDistributionMap.h" #include "MaterialLib/MPL/CreateMaterialSpatialDistributionMap.h" #include "MaterialLib/PhysicalConstant.h" @@ -20,8 +21,6 @@ #include "ProcessLib/Output/CreateSecondaryVariables.h" #include "ProcessLib/Utils/ProcessUtils.h" -#include "LiquidFlowProcess.h" - namespace ProcessLib { namespace LiquidFlow @@ -79,7 +78,6 @@ std::unique_ptr<Process> createLiquidFlowProcess( SecondaryVariableCollection secondary_variables; - ProcessLib::createSecondaryVariables(config, secondary_variables); // Get the gravity vector for the Darcy velocity diff --git a/ProcessLib/LocalAssemblerInterface.cpp b/ProcessLib/LocalAssemblerInterface.cpp index 367691ea752d834bc62681ea6f0dd5610b4a6f4f..e83130a6db342727f622efc19ee8a05e68cecb34 100644 --- a/ProcessLib/LocalAssemblerInterface.cpp +++ b/ProcessLib/LocalAssemblerInterface.cpp @@ -67,8 +67,8 @@ void LocalAssemblerInterface::assembleWithJacobianForStaggeredScheme( std::vector<double>& /*local_Jac_data*/) { OGS_FATAL( - "The assembleWithJacobianForStaggeredScheme() function is not implemented in" - " the local assembler."); + "The assembleWithJacobianForStaggeredScheme() function is not " + "implemented in the local assembler."); } void LocalAssemblerInterface::computeSecondaryVariable( diff --git a/ProcessLib/Output/CreateOutput.cpp b/ProcessLib/Output/CreateOutput.cpp index f3e44068b5eed2692f82aa0142f96ce0e91f01fb..c93ad98f6baa5a096f8bb92fa6d80d1d427c2436 100644 --- a/ProcessLib/Output/CreateOutput.cpp +++ b/ProcessLib/Output/CreateOutput.cpp @@ -12,14 +12,12 @@ #include <memory> #include <tuple> -#include "BaseLib/Logging.h" #include "BaseLib/Algorithm.h" #include "BaseLib/ConfigTree.h" #include "BaseLib/FileTools.h" - +#include "BaseLib/Logging.h" #include "MeshLib/Mesh.h" - #include "Output.h" namespace ProcessLib @@ -30,8 +28,7 @@ std::unique_ptr<Output> createOutput( std::vector<std::unique_ptr<MeshLib::Mesh>> const& meshes) { DBUG("Parse output configuration:"); - OutputType const output_type = [](auto output_type) - { + OutputType const output_type = [](auto output_type) { try { const std::map<std::string, OutputType> outputType_to_enum = { @@ -42,17 +39,17 @@ std::unique_ptr<Output> createOutput( } catch (std::out_of_range&) { - OGS_FATAL("No supported file type provided. Read `{:s}' from <output><type> \ + OGS_FATAL( + "No supported file type provided. Read `{:s}' from <output><type> \ in prj File. Supported: VTK, XDMF.", output_type); } - //! \ogs_file_param{prj__time_loop__output__type} + //! \ogs_file_param{prj__time_loop__output__type} }(config.getConfigParameter<std::string>("type")); auto const prefix = //! \ogs_file_param{prj__time_loop__output__prefix} - config.getConfigParameter<std::string>("prefix", - "{:meshname}"); + config.getConfigParameter<std::string>("prefix", "{:meshname}"); auto const suffix = //! \ogs_file_param{prj__time_loop__output__suffix} @@ -89,8 +86,8 @@ std::unique_ptr<Output> createOutput( { OGS_FATAL( "You have not given any pair (<repeat/>, <each_steps/>) that " - "defines" - " at which timesteps output shall be written. Aborting."); + "defines at which timesteps output shall be written. " + "Aborting."); } } else @@ -127,7 +124,7 @@ std::unique_ptr<Output> createOutput( //! \ogs_file_param{prj__time_loop__output__meshes} if (auto const meshes_config = config.getConfigSubtreeOptional("meshes")) { - if(prefix.find("{:meshname}") == std::string::npos) + if (prefix.find("{:meshname}") == std::string::npos) { OGS_FATAL( "There are multiple meshes defined in the output section of " @@ -158,8 +155,8 @@ std::unique_ptr<Output> createOutput( config.getConfigParameter<bool>("output_iteration_results", false); return std::make_unique<Output>( - output_directory, output_type, prefix, suffix, compress_output, data_mode, - output_iteration_results, std::move(repeats_each_steps), + output_directory, output_type, prefix, suffix, compress_output, + data_mode, output_iteration_results, std::move(repeats_each_steps), std::move(fixed_output_times), std::move(output_data_specification), std::move(mesh_names_for_output), meshes); } diff --git a/ProcessLib/Output/IntegrationPointWriter.cpp b/ProcessLib/Output/IntegrationPointWriter.cpp index 7e4f5d75b1dd1dacbbf15c3dbcde3ee0b278ed74..4494b4a53468b9e4044fd0941302cdff9290c892 100644 --- a/ProcessLib/Output/IntegrationPointWriter.cpp +++ b/ProcessLib/Output/IntegrationPointWriter.cpp @@ -8,12 +8,12 @@ * http://www.opengeosys.org/project/license */ +#include "IntegrationPointWriter.h" + #include <nlohmann/json.hpp> #include "MeshLib/Mesh.h" -#include "IntegrationPointWriter.h" - using nlohmann::json; /// Adds the integration point data and creates meta data for it. @@ -112,9 +112,9 @@ IntegrationPointMetaData getIntegrationPointMetaData(MeshLib::Mesh const& mesh, "IntegrationPointMetaData")) { OGS_FATAL( - "Integration point data '{:s}' is present in the vtk field " - "data but the required 'IntegrationPointMetaData' array " - "is not available.", + "Integration point data '{:s}' is present in the vtk field data " + "but the required 'IntegrationPointMetaData' array is not " + "available.", name); } auto const& mesh_property_ip_meta_data = diff --git a/ProcessLib/Output/Output.cpp b/ProcessLib/Output/Output.cpp index cdcb7990876e26f2710c2d8aabe25b338977d784..8249b314ba9b03025343c87d2579fe1ab0dae992 100644 --- a/ProcessLib/Output/Output.cpp +++ b/ProcessLib/Output/Output.cpp @@ -40,8 +40,8 @@ int convertVtkDataMode(std::string const& data_mode) return 2; } OGS_FATAL( - "Unsupported vtk output file data mode '{:s}'. Expected Ascii, " - "Binary, or Appended.", + "Unsupported vtk output file data mode '{:s}'. Expected Ascii, Binary, " + "or Appended.", data_mode); } @@ -166,8 +166,8 @@ MeshLib::IO::PVDFile* Output::findPVDFile( if (pvd_file == nullptr) { OGS_FATAL( - "The given process is not contained in the output" - " configuration. Aborting."); + "The given process is not contained in the output configuration. " + "Aborting."); } return pvd_file; @@ -240,9 +240,8 @@ void Output::outputMeshXdmf(OutputFile const& output_file, if (!_mesh_xdmf_hdf_writer) { std::filesystem::path path(output_file.path); - _mesh_xdmf_hdf_writer = - std::make_unique<MeshLib::IO::XdmfHdfWriter>(MeshLib::IO::XdmfHdfWriter( - mesh, path, timestep)); + _mesh_xdmf_hdf_writer = std::make_unique<MeshLib::IO::XdmfHdfWriter>( + MeshLib::IO::XdmfHdfWriter(mesh, path, timestep)); } _mesh_xdmf_hdf_writer->writeStep(timestep, t); } @@ -317,10 +316,10 @@ void Output::doOutputAlways(Process const& process, else if (_output_file_type == ProcessLib::OutputType::xdmf) { #ifdef OGS_USE_XDMF - OutputFile const file(_output_directory, _output_file_type, - _output_file_prefix, "", mesh.getName(), - timestep, t, iteration, _output_file_data_mode, - _output_file_compression); + OutputFile const file( + _output_directory, _output_file_type, _output_file_prefix, "", + mesh.getName(), timestep, t, iteration, _output_file_data_mode, + _output_file_compression); outputMeshXdmf(file, mesh, timestep, t); #else diff --git a/ProcessLib/Output/ProcessOutput.cpp b/ProcessLib/Output/ProcessOutput.cpp index d3d5b4a46d0f48603330243436c845078a80b0a7..1a82f4e16ba29da2c9a4860eec5f0f2feff941a2 100644 --- a/ProcessLib/Output/ProcessOutput.cpp +++ b/ProcessLib/Output/ProcessOutput.cpp @@ -71,8 +71,8 @@ static void addSecondaryVariableNodes( if (nodal_values_mesh.size() != global_vector_size) { OGS_FATAL( - "Secondary variable `{:s}' did not evaluate to the right " - "number of components. Expected: {:d}, actual: {:d}.", + "Secondary variable `{:s}' did not evaluate to the right number of " + "components. Expected: {:d}, actual: {:d}.", var.name, nodal_values_mesh.size(), global_vector_size); } @@ -104,8 +104,7 @@ static void addSecondaryVariableResiduals( { OGS_FATAL( "Cell property `{:s}' does not have the right number of " - "components. " - "Expected: {:d}, actual: {:d}", + "components. Expected: {:d}, actual: {:d}", property_name_res, mesh.getNumberOfElements() * var.fcts.num_components, residuals_mesh.size()); @@ -269,8 +268,8 @@ void makeOutput(std::string const& file_name, MeshLib::Mesh const& mesh, fegetenv(&fe_env); fesetenv(FE_DFL_ENV); // Set default environment effectively disabling // exceptions. -#endif //_WIN32 -#endif //__APPLE__ +#endif //_WIN32 +#endif //__APPLE__ switch (file_type) { @@ -285,8 +284,7 @@ void makeOutput(std::string const& file_name, MeshLib::Mesh const& mesh, case OutputType::xdmf: { #ifdef OGS_USE_XDMF - MeshLib::IO::XdmfHdfWriter writer( - mesh, file_name, time_step); + MeshLib::IO::XdmfHdfWriter writer(mesh, file_name, time_step); writer.writeStep(time_step, time); #else // silence compiler warnings diff --git a/ProcessLib/PhaseField/CreatePhaseFieldProcess.cpp b/ProcessLib/PhaseField/CreatePhaseFieldProcess.cpp index dc4ce24bf4d074d052bb808700c426b114ad06ae..77cad62bb234b87f58b23a2f9ecd69ed1315912f 100644 --- a/ProcessLib/PhaseField/CreatePhaseFieldProcess.cpp +++ b/ProcessLib/PhaseField/CreatePhaseFieldProcess.cpp @@ -15,11 +15,10 @@ #include "MaterialLib/SolidModels/CreateConstitutiveRelation.h" #include "MaterialLib/SolidModels/MechanicsBase.h" #include "ParameterLib/Utils.h" -#include "ProcessLib/Output/CreateSecondaryVariables.h" -#include "ProcessLib/Utils/ProcessUtils.h" - #include "PhaseFieldProcess.h" #include "PhaseFieldProcessData.h" +#include "ProcessLib/Output/CreateSecondaryVariables.h" +#include "ProcessLib/Utils/ProcessUtils.h" namespace ProcessLib { @@ -97,8 +96,7 @@ std::unique_ptr<Process> createPhaseFieldProcess( { OGS_FATAL( "Phasefield process variable '{:s}' is not a scalar variable but " - "has " - "{:d} components.", + "has {:d} components.", variable_ph->getName(), variable_ph->getNumberOfGlobalComponents()); } @@ -179,8 +177,8 @@ std::unique_ptr<Process> createPhaseFieldProcess( ((*crack_scheme != "propagating") && (*crack_scheme != "static"))) { OGS_FATAL( - "hydro_crack_scheme must be 'propagating' or 'static' but " - "'{:s}' was given", + "hydro_crack_scheme must be 'propagating' or 'static' but '{:s}' " + "was given", crack_scheme->c_str()); } diff --git a/ProcessLib/PhaseField/PhaseFieldProcess.cpp b/ProcessLib/PhaseField/PhaseFieldProcess.cpp index 30c1e98aaaa13c874ecb509abb5506e18080193c..837c02429b1f3aefbdceba043ffd3500e4c99be9 100644 --- a/ProcessLib/PhaseField/PhaseFieldProcess.cpp +++ b/ProcessLib/PhaseField/PhaseFieldProcess.cpp @@ -13,12 +13,10 @@ #include <cassert> #include "NumLib/DOF/ComputeSparsityPattern.h" - +#include "PhaseFieldFEM.h" #include "ProcessLib/Process.h" #include "ProcessLib/SmallDeformation/CreateLocalAssemblers.h" -#include "PhaseFieldFEM.h" - namespace ProcessLib { namespace PhaseField diff --git a/ProcessLib/Process.cpp b/ProcessLib/Process.cpp index 60f58a75a6b5eb1e4bf3ec842450abdc179aed03..e147a8aa0e789f1148951f3e699ca763caf6427d 100644 --- a/ProcessLib/Process.cpp +++ b/ProcessLib/Process.cpp @@ -10,13 +10,12 @@ #include "Process.h" +#include "CoupledSolutionsForStaggeredScheme.h" #include "NumLib/DOF/ComputeSparsityPattern.h" #include "NumLib/Extrapolation/LocalLinearLeastSquaresExtrapolator.h" #include "NumLib/ODESolver/ConvergenceCriterionPerComponent.h" #include "ParameterLib/Parameter.h" - #include "ProcessVariable.h" -#include "CoupledSolutionsForStaggeredScheme.h" namespace ProcessLib { diff --git a/ProcessLib/RichardsComponentTransport/CreatePorousMediaProperties.cpp b/ProcessLib/RichardsComponentTransport/CreatePorousMediaProperties.cpp index aad61ef1bc31346cd7defc18fee20497cb08d89d..b5baad1c71ced0a21bf95fec2a2889854ee35455 100644 --- a/ProcessLib/RichardsComponentTransport/CreatePorousMediaProperties.cpp +++ b/ProcessLib/RichardsComponentTransport/CreatePorousMediaProperties.cpp @@ -16,7 +16,6 @@ #include "MaterialLib/PorousMedium/Storage/createStorageModel.h" #include "MaterialLib/PorousMedium/UnsaturatedProperty/CapillaryPressure/CreateCapillaryPressureModel.h" #include "MaterialLib/PorousMedium/UnsaturatedProperty/RelativePermeability/CreateRelativePermeabilityModel.h" - #include "MeshLib/Mesh.h" namespace ProcessLib @@ -43,11 +42,12 @@ PorousMediaProperties createPorousMediaProperties( relative_permeability_models; std::vector<int> mat_ids; - for (auto const& porous_medium_config : - //! \ogs_file_param{prj__processes__process__RichardsComponentTransport__porous_medium__porous_medium} - porous_medium_configs.getConfigSubtreeList("porous_medium")) + for ( + auto const& porous_medium_config : + //! \ogs_file_param{prj__processes__process__RichardsComponentTransport__porous_medium__porous_medium} + porous_medium_configs.getConfigSubtreeList("porous_medium")) { - //! \ogs_file_attr{prj__processes__process__RichardsComponentTransport__porous_medium__porous_medium__id} + //! \ogs_file_attr{prj__processes__process__RichardsComponentTransport__porous_medium__porous_medium__id} auto const id = porous_medium_config.getConfigAttribute<int>("id"); mat_ids.push_back(id); @@ -76,8 +76,9 @@ PorousMediaProperties createPorousMediaProperties( auto const& capillary_pressure_config = //! \ogs_file_param{prj__processes__process__RichardsComponentTransport__porous_medium__porous_medium__capillary_pressure} porous_medium_config.getConfigSubtree("capillary_pressure"); - auto capillary_pressure = MaterialLib::PorousMedium::createCapillaryPressureModel( - capillary_pressure_config); + auto capillary_pressure = + MaterialLib::PorousMedium::createCapillaryPressureModel( + capillary_pressure_config); capillary_pressure_models.emplace_back(std::move(capillary_pressure)); auto const& krel_config = diff --git a/ProcessLib/RichardsComponentTransport/CreateRichardsComponentTransportProcess.cpp b/ProcessLib/RichardsComponentTransport/CreateRichardsComponentTransportProcess.cpp index 719f557ea8654ad523ce553958140a5e3c020833..b0decfb7f26e23209dfb8633f0d30762fd07d969 100644 --- a/ProcessLib/RichardsComponentTransport/CreateRichardsComponentTransportProcess.cpp +++ b/ProcessLib/RichardsComponentTransport/CreateRichardsComponentTransportProcess.cpp @@ -10,13 +10,12 @@ #include "CreateRichardsComponentTransportProcess.h" +#include "CreatePorousMediaProperties.h" #include "MaterialLib/Fluid/FluidProperties/CreateFluidProperties.h" #include "ParameterLib/ConstantParameter.h" #include "ParameterLib/Utils.h" #include "ProcessLib/Output/CreateSecondaryVariables.h" #include "ProcessLib/Utils/ProcessUtils.h" - -#include "CreatePorousMediaProperties.h" #include "RichardsComponentTransportProcess.h" #include "RichardsComponentTransportProcessData.h" @@ -55,11 +54,10 @@ std::unique_ptr<Process> createRichardsComponentTransportProcess( { auto per_process_variables = findProcessVariables( variables, pv_config, - { - //! \ogs_file_param_special{prj__processes__process__RichardsComponentTransport__process_variables__concentration} - "concentration", - //! \ogs_file_param_special{prj__processes__process__RichardsComponentTransport__process_variables__pressure} - "pressure"}); + {//! \ogs_file_param_special{prj__processes__process__RichardsComponentTransport__process_variables__concentration} + "concentration", + //! \ogs_file_param_special{prj__processes__process__RichardsComponentTransport__process_variables__pressure} + "pressure"}); process_variables.push_back(std::move(per_process_variables)); } else // staggered scheme. diff --git a/ProcessLib/RichardsComponentTransport/RichardsComponentTransportProcess.cpp b/ProcessLib/RichardsComponentTransport/RichardsComponentTransportProcess.cpp index 40e062e2b0e34491912c738f1fc738c765aab333..eed7ba8752911c2cda200d8a1907877c0268ad45 100644 --- a/ProcessLib/RichardsComponentTransport/RichardsComponentTransportProcess.cpp +++ b/ProcessLib/RichardsComponentTransport/RichardsComponentTransportProcess.cpp @@ -71,7 +71,7 @@ void RichardsComponentTransportProcess::assembleConcreteProcess( DBUG("Assemble RichardsComponentTransportProcess."); std::vector<std::reference_wrapper<NumLib::LocalToGlobalIndexMap>> - dof_table = {std::ref(*_local_to_global_index_map)}; + dof_table = {std::ref(*_local_to_global_index_map)}; ProcessLib::ProcessVariable const& pv = getProcessVariables(process_id)[0]; // Call global assembler for each local assembly item. @@ -102,4 +102,3 @@ void RichardsComponentTransportProcess::assembleWithJacobianConcreteProcess( } // namespace RichardsComponentTransport } // namespace ProcessLib - diff --git a/ProcessLib/RichardsFlow/CreateRichardsFlowProcess.cpp b/ProcessLib/RichardsFlow/CreateRichardsFlowProcess.cpp index 652b7c7d5c637a4827589e6afa7bc0813f36be91..f402d9c3255e3ee191f23da4611c2c12e0741cbd 100644 --- a/ProcessLib/RichardsFlow/CreateRichardsFlowProcess.cpp +++ b/ProcessLib/RichardsFlow/CreateRichardsFlowProcess.cpp @@ -16,7 +16,6 @@ #include "ParameterLib/Utils.h" #include "ProcessLib/Output/CreateSecondaryVariables.h" #include "ProcessLib/Utils/ProcessUtils.h" - #include "RichardsFlowProcess.h" #include "RichardsFlowProcessData.h" @@ -58,7 +57,7 @@ std::unique_ptr<Process> createRichardsFlowProcess( BaseLib::ConfigTree const& config, std::map<std::string, std::unique_ptr<MathLib::PiecewiseLinearInterpolation>> const& - /*curves*/, + /*curves*/, std::map<int, std::shared_ptr<MaterialPropertyLib::Medium>> const& media) { //! \ogs_file_param{prj__processes__process__type} diff --git a/ProcessLib/RichardsFlow/RichardsFlowProcess.cpp b/ProcessLib/RichardsFlow/RichardsFlowProcess.cpp index bbadab154e5a73ddbcc3a11caf92f3157a3f9966..50ec9b46e4bb3c28be2306e244431f698d0a3da4 100644 --- a/ProcessLib/RichardsFlow/RichardsFlowProcess.cpp +++ b/ProcessLib/RichardsFlow/RichardsFlowProcess.cpp @@ -68,7 +68,7 @@ void RichardsFlowProcess::assembleConcreteProcess( DBUG("Assemble RichardsFlowProcess."); std::vector<std::reference_wrapper<NumLib::LocalToGlobalIndexMap>> - dof_table = {std::ref(*_local_to_global_index_map)}; + dof_table = {std::ref(*_local_to_global_index_map)}; ProcessLib::ProcessVariable const& pv = getProcessVariables(process_id)[0]; // Call global assembler for each local assembly item. @@ -87,7 +87,7 @@ void RichardsFlowProcess::assembleWithJacobianConcreteProcess( DBUG("AssembleWithJacobian RichardsFlowProcess."); std::vector<std::reference_wrapper<NumLib::LocalToGlobalIndexMap>> - dof_table = {std::ref(*_local_to_global_index_map)}; + dof_table = {std::ref(*_local_to_global_index_map)}; ProcessLib::ProcessVariable const& pv = getProcessVariables(process_id)[0]; // Call global assembler for each local assembly item. diff --git a/ProcessLib/RichardsMechanics/CreateRichardsMechanicsProcess.cpp b/ProcessLib/RichardsMechanics/CreateRichardsMechanicsProcess.cpp index 3fe0730a5f89ccd0dee5462de120186db519db9c..6450d47382a452ea4468fe7e2bf678f8795d30ac 100644 --- a/ProcessLib/RichardsMechanics/CreateRichardsMechanicsProcess.cpp +++ b/ProcessLib/RichardsMechanics/CreateRichardsMechanicsProcess.cpp @@ -36,12 +36,11 @@ void checkMPLProperties( MaterialPropertyLib::bishops_effective_stress, MaterialPropertyLib::relative_permeability, MaterialPropertyLib::saturation, - MaterialPropertyLib::porosity, MaterialPropertyLib::biot_coefficient - }; + MaterialPropertyLib::porosity, + MaterialPropertyLib::biot_coefficient}; std::array const required_liquid_properties = { MaterialPropertyLib::viscosity, MaterialPropertyLib::density}; - std::array const required_solid_properties = { - MaterialPropertyLib::density}; + std::array const required_solid_properties = {MaterialPropertyLib::density}; for (auto const& m : media) { @@ -191,7 +190,8 @@ std::unique_ptr<Process> createRichardsMechanicsProcess( auto const explicit_hm_coupling_in_unsaturated_zone = //! \ogs_file_param{prj__processes__process__RICHARDS_MECHANICS__explicit_hm_coupling_in_unsaturated_zone} - config.getConfigParameter<bool>("explicit_hm_coupling_in_unsaturated_zone", false); + config.getConfigParameter<bool>( + "explicit_hm_coupling_in_unsaturated_zone", false); RichardsMechanicsProcessData<DisplacementDim> process_data{ materialIDs(mesh), diff --git a/ProcessLib/RichardsMechanics/RichardsMechanicsProcess.cpp b/ProcessLib/RichardsMechanics/RichardsMechanicsProcess.cpp index ef66ec6f20eebe3cf3a5386dcbbbe0a2711c79ca..8a46bc59e803b51fee2d9f7b81dfcc4521a82ad8 100644 --- a/ProcessLib/RichardsMechanics/RichardsMechanicsProcess.cpp +++ b/ProcessLib/RichardsMechanics/RichardsMechanicsProcess.cpp @@ -307,9 +307,8 @@ void RichardsMechanicsProcess<DisplacementDim>::initializeConcreteProcess( DisplacementDim>::RowsAtCompileTime, &LocalAssemblerIF::getIntPtEpsilon); - add_secondary_variable("velocity", - DisplacementDim, - &LocalAssemblerIF::getIntPtDarcyVelocity); + add_secondary_variable( + "velocity", DisplacementDim, &LocalAssemblerIF::getIntPtDarcyVelocity); add_secondary_variable("saturation", 1, &LocalAssemblerIF::getIntPtSaturation); @@ -320,8 +319,7 @@ void RichardsMechanicsProcess<DisplacementDim>::initializeConcreteProcess( add_secondary_variable("micro_pressure", 1, &LocalAssemblerIF::getIntPtMicroPressure); - add_secondary_variable("porosity", 1, - &LocalAssemblerIF::getIntPtPorosity); + add_secondary_variable("porosity", 1, &LocalAssemblerIF::getIntPtPorosity); add_secondary_variable("transport_porosity", 1, &LocalAssemblerIF::getIntPtTransportPorosity); @@ -334,7 +332,7 @@ void RichardsMechanicsProcess<DisplacementDim>::initializeConcreteProcess( // ProcessLib::Deformation::solidMaterialInternalToSecondaryVariables< LocalAssemblerIF>(_process_data.solid_materials, - add_secondary_variable); + add_secondary_variable); _process_data.element_saturation = MeshLib::getOrCreateMeshProperty<double>( const_cast<MeshLib::Mesh&>(mesh), "saturation_avg", @@ -406,11 +404,10 @@ void RichardsMechanicsProcess<DisplacementDim>::initializeConcreteProcess( } } - // Initialize local assemblers after all variables have been set. - GlobalExecutor::executeMemberOnDereferenced( - &LocalAssemblerIF::initialize, _local_assemblers, - *_local_to_global_index_map); + GlobalExecutor::executeMemberOnDereferenced(&LocalAssemblerIF::initialize, + _local_assemblers, + *_local_to_global_index_map); } template <int DisplacementDim> diff --git a/ProcessLib/SmallDeformation/CreateSmallDeformationProcess.cpp b/ProcessLib/SmallDeformation/CreateSmallDeformationProcess.cpp index 108b3cded52ca20707eed9ceecc7528127a31ab0..bfad7f4d154e8a660766c1abcb4190fae5ebcad5 100644 --- a/ProcessLib/SmallDeformation/CreateSmallDeformationProcess.cpp +++ b/ProcessLib/SmallDeformation/CreateSmallDeformationProcess.cpp @@ -16,7 +16,6 @@ #include "ParameterLib/Utils.h" #include "ProcessLib/Output/CreateSecondaryVariables.h" #include "ProcessLib/Utils/ProcessUtils.h" - #include "SmallDeformationProcess.h" #include "SmallDeformationProcessData.h" diff --git a/ProcessLib/SmallDeformationNonlocal/CreateSmallDeformationNonlocalProcess.cpp b/ProcessLib/SmallDeformationNonlocal/CreateSmallDeformationNonlocalProcess.cpp index 75510a4d2d8adab1342f33b343377b017e4647bf..73287a2212c4b2e8714cad326001ad95ebd916b2 100644 --- a/ProcessLib/SmallDeformationNonlocal/CreateSmallDeformationNonlocalProcess.cpp +++ b/ProcessLib/SmallDeformationNonlocal/CreateSmallDeformationNonlocalProcess.cpp @@ -16,7 +16,6 @@ #include "ParameterLib/Utils.h" #include "ProcessLib/Output/CreateSecondaryVariables.h" #include "ProcessLib/Utils/ProcessUtils.h" - #include "SmallDeformationNonlocalProcess.h" #include "SmallDeformationNonlocalProcessData.h" diff --git a/ProcessLib/SmallDeformationNonlocal/SmallDeformationNonlocalProcess.cpp b/ProcessLib/SmallDeformationNonlocal/SmallDeformationNonlocalProcess.cpp index 6b5e360521a3a0241d57eacfe7760d287af02471..e931b4f186eb625c399542b3d0a8fd76ea5ddaab 100644 --- a/ProcessLib/SmallDeformationNonlocal/SmallDeformationNonlocalProcess.cpp +++ b/ProcessLib/SmallDeformationNonlocal/SmallDeformationNonlocalProcess.cpp @@ -10,8 +10,8 @@ #include "SmallDeformationNonlocalProcess.h" -#include <nlohmann/json.hpp> #include <iostream> +#include <nlohmann/json.hpp> #include "ProcessLib/Output/IntegrationPointWriter.h" @@ -168,8 +168,7 @@ void SmallDeformationNonlocalProcess<DisplacementDim>:: { OGS_FATAL( "Different number of components in meta data ({:d}) than " - "in " - "the integration point field data for '{:s}': {:d}.", + "in the integration point field data for '{:s}': {:d}.", ip_meta_data.n_components, name, mesh_property.getNumberOfGlobalComponents()); } diff --git a/ProcessLib/SourceTerms/CreateNodalSourceTerm.cpp b/ProcessLib/SourceTerms/CreateNodalSourceTerm.cpp index dc3a0e193bd02f29ce6129751055ebb87164f469..72d29b6caeb116f4bc67d5a2f87b758d1b9d5171 100644 --- a/ProcessLib/SourceTerms/CreateNodalSourceTerm.cpp +++ b/ProcessLib/SourceTerms/CreateNodalSourceTerm.cpp @@ -10,12 +10,10 @@ #include "CreateNodalSourceTerm.h" -#include "BaseLib/Logging.h" - #include "BaseLib/ConfigTree.h" -#include "ParameterLib/Utils.h" - +#include "BaseLib/Logging.h" #include "NodalSourceTerm.h" +#include "ParameterLib/Utils.h" namespace ProcessLib { diff --git a/ProcessLib/SourceTerms/CreateSourceTerm.cpp b/ProcessLib/SourceTerms/CreateSourceTerm.cpp index 70f87a1881f3db905d4848e9f1136c65d3926cf0..a31c1ce3770de9e43a31fe2d0e6db947f0eabea5 100644 --- a/ProcessLib/SourceTerms/CreateSourceTerm.cpp +++ b/ProcessLib/SourceTerms/CreateSourceTerm.cpp @@ -48,23 +48,21 @@ std::unique_ptr<SourceTerm> createSourceTerm( .template existsPropertyVector<std::size_t>("bulk_node_ids")) { OGS_FATAL( - "The required bulk node ids map does not exist in the " - "source term mesh '{:s}'.", + "The required bulk node ids map does not exist in the source term " + "mesh '{:s}'.", source_term_mesh.getName()); } std::vector<MeshLib::Node*> const& source_term_nodes = source_term_mesh.getNodes(); DBUG( "Found {:d} nodes for source term at mesh '{:s}' for the variable {:d} " - "and " - "component {:d}", + "and component {:d}", source_term_nodes.size(), source_term_mesh.getName(), variable_id, *config.component_id); MeshLib::MeshSubset source_term_mesh_subset(source_term_mesh, source_term_nodes); - if (type == "Nodal") { std::unique_ptr<NumLib::LocalToGlobalIndexMap> dof_table_source_term( diff --git a/ProcessLib/SourceTerms/Python/CreatePythonSourceTerm.cpp b/ProcessLib/SourceTerms/Python/CreatePythonSourceTerm.cpp index 4de799992bf8a8823939fb51671784b0f108419d..b795463fb0940286775cebcd6792676b15764103 100644 --- a/ProcessLib/SourceTerms/Python/CreatePythonSourceTerm.cpp +++ b/ProcessLib/SourceTerms/Python/CreatePythonSourceTerm.cpp @@ -32,7 +32,7 @@ std::unique_ptr<SourceTerm> createPythonSourceTerm( config.checkConfigParameter("type", "Python"); auto const source_term_object = - //! \ogs_file_param{prj__process_variables__process_variable__source_terms__source_term__Python__source_term_object} + //! \ogs_file_param{prj__process_variables__process_variable__source_terms__source_term__Python__source_term_object} config.getConfigParameter<std::string>("source_term_object"); //! \ogs_file_param{prj__process_variables__process_variable__source_terms__source_term__Python__flush_stdout} auto const flush_stdout = config.getConfigParameter("flush_stdout", false); @@ -45,8 +45,7 @@ std::unique_ptr<SourceTerm> createPythonSourceTerm( { OGS_FATAL( "Function `{:s}' is not defined in the python script file, or " - "there " - "was no python script file specified.", + "there was no python script file specified.", source_term_object); } diff --git a/ProcessLib/SourceTerms/Python/PythonSourceTerm.cpp b/ProcessLib/SourceTerms/Python/PythonSourceTerm.cpp index 6c4c69aee3a8081c162bfcad3783aa65a683bff8..35b4bbc35fa7ba89d60e52854a07c2f097a108fb 100644 --- a/ProcessLib/SourceTerms/Python/PythonSourceTerm.cpp +++ b/ProcessLib/SourceTerms/Python/PythonSourceTerm.cpp @@ -11,6 +11,7 @@ #include "PythonSourceTerm.h" #include <pybind11/pybind11.h> + #include <iostream> #include "MeshLib/MeshSearch/NodeSearch.h" diff --git a/ProcessLib/SourceTerms/Python/PythonSourceTermModule.cpp b/ProcessLib/SourceTerms/Python/PythonSourceTermModule.cpp index 34c3998d03193e711958e0c669e52cf4b2a87c72..b233e9c49fb77700dd3db6a910deb1408f074f9b 100644 --- a/ProcessLib/SourceTerms/Python/PythonSourceTermModule.cpp +++ b/ProcessLib/SourceTerms/Python/PythonSourceTermModule.cpp @@ -12,6 +12,7 @@ #include <pybind11/pybind11.h> #include <pybind11/stl.h> + #include "PythonSourceTermPythonSideInterface.h" namespace ProcessLib diff --git a/ProcessLib/SourceTerms/VolumetricSourceTerm.cpp b/ProcessLib/SourceTerms/VolumetricSourceTerm.cpp index aa8e07e504bb4c35070d3dd630c072c627647b07..6901d7537c80e74beacb3b324772d3c2e847b254 100644 --- a/ProcessLib/SourceTerms/VolumetricSourceTerm.cpp +++ b/ProcessLib/SourceTerms/VolumetricSourceTerm.cpp @@ -41,4 +41,4 @@ void VolumetricSourceTerm::integrate(const double t, GlobalVector const& /*x*/, _local_assemblers, *_source_term_dof_table, t, b); } -} // namespace ProcessLib +} // namespace ProcessLib diff --git a/ProcessLib/SteadyStateDiffusion/CreateSteadyStateDiffusion.cpp b/ProcessLib/SteadyStateDiffusion/CreateSteadyStateDiffusion.cpp index 60b1ade2cc70b61c37b17b9eacc0014c93398454..a4bf05c8625b8cfc1165ca296d8ef317088fd1a1 100644 --- a/ProcessLib/SteadyStateDiffusion/CreateSteadyStateDiffusion.cpp +++ b/ProcessLib/SteadyStateDiffusion/CreateSteadyStateDiffusion.cpp @@ -11,8 +11,6 @@ #include "CreateSteadyStateDiffusion.h" #include "BaseLib/FileTools.h" -#include "SteadyStateDiffusion.h" -#include "SteadyStateDiffusionData.h" #include "MaterialLib/MPL/CheckMaterialSpatialDistributionMap.h" #include "MaterialLib/MPL/CreateMaterialSpatialDistributionMap.h" #include "MaterialLib/MPL/MaterialSpatialDistributionMap.h" @@ -20,6 +18,8 @@ #include "ParameterLib/Utils.h" #include "ProcessLib/Output/CreateSecondaryVariables.h" #include "ProcessLib/Utils/ProcessUtils.h" +#include "SteadyStateDiffusion.h" +#include "SteadyStateDiffusionData.h" namespace ProcessLib { diff --git a/ProcessLib/SteadyStateDiffusion/SteadyStateDiffusion.cpp b/ProcessLib/SteadyStateDiffusion/SteadyStateDiffusion.cpp index f3ab036911eff979c276b2a9cc3986320bab0189..208a10404b0475a8d1efcd43c59f1a71d70ddb46 100644 --- a/ProcessLib/SteadyStateDiffusion/SteadyStateDiffusion.cpp +++ b/ProcessLib/SteadyStateDiffusion/SteadyStateDiffusion.cpp @@ -93,4 +93,4 @@ void SteadyStateDiffusion::assembleWithJacobianConcreteProcess( } } // namespace SteadyStateDiffusion -} // namespace ProcessLib +} // namespace ProcessLib diff --git a/ProcessLib/SurfaceFlux/SurfaceFlux.cpp b/ProcessLib/SurfaceFlux/SurfaceFlux.cpp index 8c6a79cb7b1aed85e8e83bb952e0e125a73112f2..88fed1e28f60d60500af24fd257c40366fbe2504 100644 --- a/ProcessLib/SurfaceFlux/SurfaceFlux.cpp +++ b/ProcessLib/SurfaceFlux/SurfaceFlux.cpp @@ -16,10 +16,9 @@ namespace ProcessLib { -SurfaceFlux::SurfaceFlux( - MeshLib::Mesh& boundary_mesh, - std::size_t bulk_property_number_of_components, - unsigned const integration_order) +SurfaceFlux::SurfaceFlux(MeshLib::Mesh& boundary_mesh, + std::size_t bulk_property_number_of_components, + unsigned const integration_order) { DBUG("Create local balance assemblers."); // Populate the vector of local assemblers. @@ -66,8 +65,8 @@ void SurfaceFlux::integrate( DBUG("Integrate SurfaceFlux."); GlobalExecutor::executeSelectedMemberOnDereferenced( - &SurfaceFluxLocalAssemblerInterface::integrate, - _local_assemblers, active_element_ids, x, balance, t, bulk_mesh, getFlux); + &SurfaceFluxLocalAssemblerInterface::integrate, _local_assemblers, + active_element_ids, x, balance, t, bulk_mesh, getFlux); } } // namespace ProcessLib diff --git a/ProcessLib/TES/CreateTESProcess.cpp b/ProcessLib/TES/CreateTESProcess.cpp index 6b5110822033fd0965c803582793d7273c76246b..fbda50fbdf07689c838a29d921cfe46c3e4c8907 100644 --- a/ProcessLib/TES/CreateTESProcess.cpp +++ b/ProcessLib/TES/CreateTESProcess.cpp @@ -9,6 +9,7 @@ */ #include "CreateTESProcess.h" + #include "ProcessLib/Output/CreateSecondaryVariables.h" #include "ProcessLib/Utils/ProcessUtils.h" #include "TESProcess.h" @@ -36,13 +37,12 @@ std::unique_ptr<Process> createTESProcess( auto per_process_variables = findProcessVariables( variables, pv_config, - { - //! \ogs_file_param_special{prj__processes__process__TES__process_variables__fluid_pressure} - "fluid_pressure", - //! \ogs_file_param_special{prj__processes__process__TES__process_variables__temperature} - "temperature", - //! \ogs_file_param_special{prj__processes__process__TES__process_variables__vapour_mass_fraction} - "vapour_mass_fraction"}); + {//! \ogs_file_param_special{prj__processes__process__TES__process_variables__fluid_pressure} + "fluid_pressure", + //! \ogs_file_param_special{prj__processes__process__TES__process_variables__temperature} + "temperature", + //! \ogs_file_param_special{prj__processes__process__TES__process_variables__vapour_mass_fraction} + "vapour_mass_fraction"}); std::vector<std::vector<std::reference_wrapper<ProcessVariable>>> process_variables; process_variables.push_back(std::move(per_process_variables)); diff --git a/ProcessLib/TES/TESLocalAssemblerData.cpp b/ProcessLib/TES/TESLocalAssemblerData.cpp index 53c46faf5852ecf32d4dac3cd56b3f2fd42981f0..04097a61b526a3bea65a8cb24e6044f376a52af6 100644 --- a/ProcessLib/TES/TESLocalAssemblerData.cpp +++ b/ProcessLib/TES/TESLocalAssemblerData.cpp @@ -8,6 +8,7 @@ */ #include "TESLocalAssemblerData.h" + #include "TESReactionAdaptor.h" namespace ProcessLib diff --git a/ProcessLib/TES/TESProcess.cpp b/ProcessLib/TES/TESProcess.cpp index ac25bca5cb572bc39bf1dbf89a6be03e41f7b062..aa10eb083b7b242828fab104c8d4f79db7f60db7 100644 --- a/ProcessLib/TES/TESProcess.cpp +++ b/ProcessLib/TES/TESProcess.cpp @@ -9,6 +9,7 @@ */ #include "TESProcess.h" + #include "NumLib/DOF/DOFTableUtil.h" #include "ProcessLib/Utils/CreateLocalAssemblers.h" @@ -63,7 +64,7 @@ TESProcess::TESProcess( { if (auto const par = //! \ogs_file_special - config.getConfigParameterOptional<double>(p.first)) + config.getConfigParameterOptional<double>(p.first)) { DBUG("setting parameter `{:s}' to value `{:g}'", p.first, *par); *p.second = *par; @@ -85,7 +86,7 @@ TESProcess::TESProcess( { if (auto const par = //! \ogs_file_special - config.getConfigParameterOptional<double>(p.first)) + config.getConfigParameterOptional<double>(p.first)) { INFO("setting parameter `{:s}' to value `{:g}'", p.first, *par); *p.second = Trafo{*par}; @@ -96,7 +97,8 @@ TESProcess::TESProcess( // permeability if (auto par = //! \ogs_file_param{prj__processes__process__TES__solid_hydraulic_permeability} - config.getConfigParameterOptional<double>("solid_hydraulic_permeability")) + config.getConfigParameterOptional<double>( + "solid_hydraulic_permeability")) { DBUG( "setting parameter `solid_hydraulic_permeability' to isotropic " @@ -115,7 +117,7 @@ TESProcess::TESProcess( // debug output if (auto const param = //! \ogs_file_param{prj__processes__process__TES__output_element_matrices} - config.getConfigParameterOptional<bool>("output_element_matrices")) + config.getConfigParameterOptional<bool>("output_element_matrices")) { DBUG("output_element_matrices: {:s}", (*param) ? "true" : "false"); @@ -216,7 +218,7 @@ void TESProcess::assembleConcreteProcess(const double t, double const dt, DBUG("Assemble TESProcess."); std::vector<std::reference_wrapper<NumLib::LocalToGlobalIndexMap>> - dof_table = {std::ref(*_local_to_global_index_map)}; + dof_table = {std::ref(*_local_to_global_index_map)}; ProcessLib::ProcessVariable const& pv = getProcessVariables(process_id)[0]; // Call global assembler for each local assembly item. @@ -233,7 +235,7 @@ void TESProcess::assembleWithJacobianConcreteProcess( GlobalVector& b, GlobalMatrix& Jac) { std::vector<std::reference_wrapper<NumLib::LocalToGlobalIndexMap>> - dof_table = {std::ref(*_local_to_global_index_map)}; + dof_table = {std::ref(*_local_to_global_index_map)}; ProcessLib::ProcessVariable const& pv = getProcessVariables(process_id)[0]; // Call global assembler for each local assembly item. @@ -296,7 +298,7 @@ NumLib::IterationResult TESProcess::postIterationConcreteProcess( }; GlobalExecutor::executeDereferenced(check_variable_bounds, - _local_assemblers); + _local_assemblers); } if (!check_passed) diff --git a/ProcessLib/TES/TESReactionAdaptor.cpp b/ProcessLib/TES/TESReactionAdaptor.cpp index a03dce6d319f7ca9153e604673f7fe3cfad9f672..e1c65999d7ce53ebb5dc241ebd52f3448b9bd3eb 100644 --- a/ProcessLib/TES/TESReactionAdaptor.cpp +++ b/ProcessLib/TES/TESReactionAdaptor.cpp @@ -8,18 +8,16 @@ * */ -#include <cassert> - +#include "TESReactionAdaptor.h" -#include "MathLib/Nonlinear/Root1D.h" -#include "MathLib/ODE/ODESolverBuilder.h" +#include <cassert> #include "MaterialLib/Adsorption/Adsorption.h" #include "MaterialLib/Adsorption/ReactionInert.h" #include "MaterialLib/Adsorption/ReactionSinusoidal.h" - +#include "MathLib/Nonlinear/Root1D.h" +#include "MathLib/ODE/ODESolverBuilder.h" #include "TESLocalAssemblerInner.h" -#include "TESReactionAdaptor.h" namespace ProcessLib { @@ -54,8 +52,7 @@ TESFEMReactionAdaptorAdsorption::TESFEMReactionAdaptorAdsorption( TESLocalAssemblerData const& data) // caution fragile: this relies in this constructor b eing called __after__ // data.solid_density has been properly set up! - : _bounds_violation(data.solid_density.size(), false), - _d(data) + : _bounds_violation(data.solid_density.size(), false), _d(data) { assert(dynamic_cast<Adsorption::AdsorptionReaction const*>( data.ap.react_sys.get()) != nullptr && @@ -104,8 +101,7 @@ TESFEMReactionAdaptorAdsorption::initReaction_slowDownUndershootStrategy( const double delta_pV = pV_eq - _d.p_V; const double delta_rhoV = delta_pV * _d.ap.M_react / - MaterialLib::PhysicalConstant::IdealGasConstant / _d.T * - _d.ap.poro; + MaterialLib::PhysicalConstant::IdealGasConstant / _d.T * _d.ap.poro; const double delta_rhoSR = delta_rhoV / (_d.ap.poro - 1.0); double react_rate_R2 = delta_rhoSR / _d.ap.delta_t; diff --git a/ProcessLib/ThermalTwoPhaseFlowWithPP/CreateThermalTwoPhaseFlowWithPPMaterialProperties.cpp b/ProcessLib/ThermalTwoPhaseFlowWithPP/CreateThermalTwoPhaseFlowWithPPMaterialProperties.cpp index 2a71658fc56972673a7fc71514442c4ae53409ea..237a7c633370f65ddbd2cbbcaa8598ce0afca570 100644 --- a/ProcessLib/ThermalTwoPhaseFlowWithPP/CreateThermalTwoPhaseFlowWithPPMaterialProperties.cpp +++ b/ProcessLib/ThermalTwoPhaseFlowWithPP/CreateThermalTwoPhaseFlowWithPPMaterialProperties.cpp @@ -11,8 +11,8 @@ #include "CreateThermalTwoPhaseFlowWithPPMaterialProperties.h" #include <tuple> -#include "BaseLib/Logging.h" +#include "BaseLib/Logging.h" #include "MaterialLib/Fluid/FluidProperty.h" #include "MaterialLib/Fluid/SpecificHeatCapacity/CreateSpecificFluidHeatCapacityModel.h" #include "MaterialLib/Fluid/ThermalConductivity/CreateFluidThermalConductivityModel.h" @@ -28,7 +28,6 @@ #include "MeshLib/PropertyVector.h" #include "ParameterLib/Parameter.h" #include "ParameterLib/SpatialPosition.h" - #include "ThermalTwoPhaseFlowWithPPMaterialProperties.h" namespace ProcessLib diff --git a/ProcessLib/ThermalTwoPhaseFlowWithPP/CreateThermalTwoPhaseFlowWithPPProcess.cpp b/ProcessLib/ThermalTwoPhaseFlowWithPP/CreateThermalTwoPhaseFlowWithPPProcess.cpp index 8ad8fca48f736490f024131ea11c3933a590e187..6abdc6408373b818394f6eb25bb605af8dd43a20 100644 --- a/ProcessLib/ThermalTwoPhaseFlowWithPP/CreateThermalTwoPhaseFlowWithPPProcess.cpp +++ b/ProcessLib/ThermalTwoPhaseFlowWithPP/CreateThermalTwoPhaseFlowWithPPProcess.cpp @@ -17,7 +17,6 @@ #include "ProcessLib/ThermalTwoPhaseFlowWithPP/CreateThermalTwoPhaseFlowWithPPMaterialProperties.h" #include "ProcessLib/ThermalTwoPhaseFlowWithPP/ThermalTwoPhaseFlowWithPPMaterialProperties.h" #include "ProcessLib/Utils/ProcessUtils.h" - #include "ThermalTwoPhaseFlowWithPPProcess.h" #include "ThermalTwoPhaseFlowWithPPProcessData.h" diff --git a/ProcessLib/ThermalTwoPhaseFlowWithPP/ThermalTwoPhaseFlowWithPPMaterialProperties.cpp b/ProcessLib/ThermalTwoPhaseFlowWithPP/ThermalTwoPhaseFlowWithPPMaterialProperties.cpp index 184ad125ec44c1ff14ff46c2b854af8c2cc9e471..4137546b72664f6ac06a9255bbff24bdd8d0e22f 100644 --- a/ProcessLib/ThermalTwoPhaseFlowWithPP/ThermalTwoPhaseFlowWithPPMaterialProperties.cpp +++ b/ProcessLib/ThermalTwoPhaseFlowWithPP/ThermalTwoPhaseFlowWithPPMaterialProperties.cpp @@ -11,7 +11,6 @@ #include "ThermalTwoPhaseFlowWithPPMaterialProperties.h" #include "BaseLib/Logging.h" - #include "MaterialLib/Fluid/FluidProperty.h" #include "MaterialLib/PorousMedium/Porosity/Porosity.h" #include "MaterialLib/PorousMedium/Storage/Storage.h" @@ -154,8 +153,8 @@ double ThermalTwoPhaseFlowWithPPMaterialProperties::calculateVaporPressureNonwet( const double pc, const double T, const double mass_density_water) const { - return _water_vapor_properties->calculateVaporPressureNonwet(pc, T, - mass_density_water); + return _water_vapor_properties->calculateVaporPressureNonwet( + pc, T, mass_density_water); } double ThermalTwoPhaseFlowWithPPMaterialProperties::calculateDerivativedPsatdT( const double T) const @@ -165,14 +164,14 @@ double ThermalTwoPhaseFlowWithPPMaterialProperties::calculateDerivativedPsatdT( double ThermalTwoPhaseFlowWithPPMaterialProperties::calculateDerivativedPgwdT( const double pc, const double T, const double mass_density_water) const { - return _water_vapor_properties->calculateDerivativedPgwdT(pc, T, - mass_density_water); + return _water_vapor_properties->calculateDerivativedPgwdT( + pc, T, mass_density_water); } double ThermalTwoPhaseFlowWithPPMaterialProperties::calculateDerivativedPgwdPC( const double pc, const double T, const double mass_density_water) const { - return _water_vapor_properties->calculateDerivativedPgwdPC(pc, T, - mass_density_water); + return _water_vapor_properties->calculateDerivativedPgwdPC( + pc, T, mass_density_water); } double ThermalTwoPhaseFlowWithPPMaterialProperties::calculatedDensityNonwetdT( const double p_air_nonwet, const double p_vapor_nonwet, const double pc, @@ -196,7 +195,8 @@ double ThermalTwoPhaseFlowWithPPMaterialProperties::getAirEnthalpySimple( const double /*pg*/) const { return heat_capacity_dry_air * (temperature - CelsiusZeroInKelvin) + - IdealGasConstant * (temperature - CelsiusZeroInKelvin) / _air_mol_mass; + IdealGasConstant * (temperature - CelsiusZeroInKelvin) / + _air_mol_mass; } double diff --git a/ProcessLib/ThermalTwoPhaseFlowWithPP/ThermalTwoPhaseFlowWithPPProcess.cpp b/ProcessLib/ThermalTwoPhaseFlowWithPP/ThermalTwoPhaseFlowWithPPProcess.cpp index e5081998e166bf68c8b987a6e80d7a3f5df5864c..373de1c4cdf8fd1ffc337aa240ebe478082e9b82 100644 --- a/ProcessLib/ThermalTwoPhaseFlowWithPP/ThermalTwoPhaseFlowWithPPProcess.cpp +++ b/ProcessLib/ThermalTwoPhaseFlowWithPP/ThermalTwoPhaseFlowWithPPProcess.cpp @@ -12,15 +12,13 @@ #include <cassert> -#include "MathLib/InterpolationAlgorithms/PiecewiseLinearInterpolation.h" -#include "MeshLib/PropertyVector.h" #include "MaterialLib/PorousMedium/Porosity/Porosity.h" #include "MaterialLib/PorousMedium/Storage/Storage.h" +#include "MathLib/InterpolationAlgorithms/PiecewiseLinearInterpolation.h" +#include "MeshLib/PropertyVector.h" #include "ProcessLib/Utils/CreateLocalAssemblers.h" - #include "ThermalTwoPhaseFlowWithPPLocalAssembler.h" - namespace ProcessLib { namespace ThermalTwoPhaseFlowWithPP @@ -81,7 +79,7 @@ void ThermalTwoPhaseFlowWithPPProcess::assembleConcreteProcess( DBUG("Assemble ThermalTwoPhaseFlowWithPPProcess."); std::vector<std::reference_wrapper<NumLib::LocalToGlobalIndexMap>> - dof_table = {std::ref(*_local_to_global_index_map)}; + dof_table = {std::ref(*_local_to_global_index_map)}; ProcessLib::ProcessVariable const& pv = getProcessVariables(process_id)[0]; // Call global assembler for each local assembly item. @@ -100,7 +98,7 @@ void ThermalTwoPhaseFlowWithPPProcess::assembleWithJacobianConcreteProcess( DBUG("AssembleWithJacobian ThermalTwoPhaseFlowWithPPProcess."); std::vector<std::reference_wrapper<NumLib::LocalToGlobalIndexMap>> - dof_table = {std::ref(*_local_to_global_index_map)}; + dof_table = {std::ref(*_local_to_global_index_map)}; ProcessLib::ProcessVariable const& pv = getProcessVariables(process_id)[0]; // Call global assembler for each local assembly item. diff --git a/ProcessLib/ThermoHydroMechanics/CreateThermoHydroMechanicsProcess.cpp b/ProcessLib/ThermoHydroMechanics/CreateThermoHydroMechanicsProcess.cpp index f445ed535545092259584df8bf161d356a2dae48..df5bf1db7bf2fe16eb0618fb55fcfd2dd037c914 100644 --- a/ProcessLib/ThermoHydroMechanics/CreateThermoHydroMechanicsProcess.cpp +++ b/ProcessLib/ThermoHydroMechanics/CreateThermoHydroMechanicsProcess.cpp @@ -14,13 +14,11 @@ #include "MaterialLib/MPL/CreateMaterialSpatialDistributionMap.h" #include "MaterialLib/MPL/MaterialSpatialDistributionMap.h" - #include "MaterialLib/SolidModels/CreateConstitutiveRelation.h" #include "MaterialLib/SolidModels/MechanicsBase.h" #include "ParameterLib/Utils.h" #include "ProcessLib/Output/CreateSecondaryVariables.h" #include "ProcessLib/Utils/ProcessUtils.h" - #include "ThermoHydroMechanicsProcess.h" #include "ThermoHydroMechanicsProcessData.h" diff --git a/ProcessLib/ThermoHydroMechanics/ThermoHydroMechanicsProcess.cpp b/ProcessLib/ThermoHydroMechanics/ThermoHydroMechanicsProcess.cpp index 2eac64af3d956bbb688d307afb22b36dbc633e51..c8b90137c515786a1a7858d5cc0f577dfce5f5ed 100644 --- a/ProcessLib/ThermoHydroMechanics/ThermoHydroMechanicsProcess.cpp +++ b/ProcessLib/ThermoHydroMechanics/ThermoHydroMechanicsProcess.cpp @@ -16,7 +16,6 @@ #include "NumLib/DOF/ComputeSparsityPattern.h" #include "ProcessLib/Process.h" #include "ProcessLib/ThermoHydroMechanics/CreateLocalAssemblers.h" - #include "ThermoHydroMechanicsFEM.h" #include "ThermoHydroMechanicsProcessData.h" @@ -271,8 +270,8 @@ void ThermoHydroMechanicsProcess<DisplacementDim>:: if (_use_monolithic_scheme) { DBUG( - "Assemble the Jacobian of ThermoHydroMechanics for the monolithic" - " scheme."); + "Assemble the Jacobian of ThermoHydroMechanics for the monolithic " + "scheme."); dof_tables.emplace_back(*_local_to_global_index_map); } else diff --git a/ProcessLib/ThermoMechanicalPhaseField/CreateThermoMechanicalPhaseFieldProcess.cpp b/ProcessLib/ThermoMechanicalPhaseField/CreateThermoMechanicalPhaseFieldProcess.cpp index 0c20e9b7b4bc182ccb0c60ecfee600ca2bbf6adb..d9b146d4f002dddc3340283659f38e0ce62410d4 100644 --- a/ProcessLib/ThermoMechanicalPhaseField/CreateThermoMechanicalPhaseFieldProcess.cpp +++ b/ProcessLib/ThermoMechanicalPhaseField/CreateThermoMechanicalPhaseFieldProcess.cpp @@ -17,7 +17,6 @@ #include "ParameterLib/Utils.h" #include "ProcessLib/Output/CreateSecondaryVariables.h" #include "ProcessLib/Utils/ProcessUtils.h" - #include "ThermoMechanicalPhaseFieldProcess.h" #include "ThermoMechanicalPhaseFieldProcessData.h" @@ -97,8 +96,7 @@ std::unique_ptr<Process> createThermoMechanicalPhaseFieldProcess( { OGS_FATAL( "Phasefield process variable '{:s}' is not a scalar variable but " - "has " - "{:d} components.", + "has {:d} components.", variable_ph->getName(), variable_ph->getNumberOfGlobalComponents()); } @@ -109,8 +107,7 @@ std::unique_ptr<Process> createThermoMechanicalPhaseFieldProcess( { OGS_FATAL( "Temperature process variable '{:s}' is not a scalar variable but " - "has " - "{:d} components.", + "has {:d} components.", variable_T->getName(), variable_T->getNumberOfGlobalComponents()); } @@ -163,11 +160,11 @@ std::unique_ptr<Process> createThermoMechanicalPhaseFieldProcess( DBUG("Use '{:s}' as solid density parameter.", solid_density.name); // Linear thermal expansion coefficient - auto const& linear_thermal_expansion_coefficient = ParameterLib::findParameter< - double>( - thermal_parameters_config, - //! \ogs_file_param_special{prj__processes__process__THERMO_MECHANICAL_PHASE_FIELD__thermal_parameters__linear_thermal_expansion_coefficient} - "linear_thermal_expansion_coefficient", parameters, 1, &mesh); + auto const& linear_thermal_expansion_coefficient = + ParameterLib::findParameter<double>( + thermal_parameters_config, + //! \ogs_file_param_special{prj__processes__process__THERMO_MECHANICAL_PHASE_FIELD__thermal_parameters__linear_thermal_expansion_coefficient} + "linear_thermal_expansion_coefficient", parameters, 1, &mesh); DBUG("Use '{:s}' as linear thermal expansion coefficient.", linear_thermal_expansion_coefficient.name); diff --git a/ProcessLib/ThermoMechanicalPhaseField/ThermoMechanicalPhaseFieldProcess.cpp b/ProcessLib/ThermoMechanicalPhaseField/ThermoMechanicalPhaseFieldProcess.cpp index 061be95782967ac97c16123223c931b8b8d0a921..d8d1a1cc85d5af4cf741c3287ca7fec21158cca4 100644 --- a/ProcessLib/ThermoMechanicalPhaseField/ThermoMechanicalPhaseFieldProcess.cpp +++ b/ProcessLib/ThermoMechanicalPhaseField/ThermoMechanicalPhaseFieldProcess.cpp @@ -8,15 +8,15 @@ * */ -#include "ThermoMechanicalPhaseFieldFEM.h" #include "ThermoMechanicalPhaseFieldProcess.h" -#include "ThermoMechanicalPhaseFieldProcessData.h" #include <cassert> #include "NumLib/DOF/ComputeSparsityPattern.h" #include "ProcessLib/Process.h" #include "ProcessLib/SmallDeformation/CreateLocalAssemblers.h" +#include "ThermoMechanicalPhaseFieldFEM.h" +#include "ThermoMechanicalPhaseFieldProcessData.h" namespace ProcessLib { @@ -222,26 +222,21 @@ void ThermoMechanicalPhaseFieldProcess<DisplacementDim>:: { DBUG( "Assemble the Jacobian equations of " - "temperature-deformation in " - "ThermoMechanicalPhaseFieldProcess for " + "temperature-deformation in ThermoMechanicalPhaseFieldProcess for " "the staggered scheme."); } if (process_id == _phase_field_process_id) { DBUG( - "Assemble the Jacobian equations of" - "phase field in " - "ThermoMechanicalPhaseFieldProcess for " - "the staggered scheme."); + "Assemble the Jacobian equations ofphase field in " + "ThermoMechanicalPhaseFieldProcess for the staggered scheme."); } else { DBUG( - "Assemble the Jacobian equations of " - "heat conduction in " - "ThermoMechanicalPhaseFieldProcess for " - "the staggered scheme."); + "Assemble the Jacobian equations of heat conduction in " + "ThermoMechanicalPhaseFieldProcess for the staggered scheme."); } dof_tables.emplace_back( getDOFTableByProcessID(_heat_conduction_process_id)); diff --git a/ProcessLib/ThermoRichardsMechanics/CreateThermoRichardsMechanicsProcess.cpp b/ProcessLib/ThermoRichardsMechanics/CreateThermoRichardsMechanicsProcess.cpp index 59631a74865fb2a7c3d7f121c2da24fed20b782a..d63703b41c14e969b0e022f409d5ebf0540bb98a 100644 --- a/ProcessLib/ThermoRichardsMechanics/CreateThermoRichardsMechanicsProcess.cpp +++ b/ProcessLib/ThermoRichardsMechanics/CreateThermoRichardsMechanicsProcess.cpp @@ -105,8 +105,7 @@ std::unique_ptr<Process> createThermoRichardsMechanicsProcess( { auto per_process_variables = findProcessVariables( variables, pv_config, - { - //! \ogs_file_param_special{prj__processes__process__THERMO_RICHARDS_MECHANICS__process_variables__temperature} + {//! \ogs_file_param_special{prj__processes__process__THERMO_RICHARDS_MECHANICS__process_variables__temperature} "temperature", //! \ogs_file_param_special{prj__processes__process__THERMO_RICHARDS_MECHANICS__process_variables__pressure} "pressure", diff --git a/ProcessLib/ThermoRichardsMechanics/ThermoRichardsMechanicsProcess.cpp b/ProcessLib/ThermoRichardsMechanics/ThermoRichardsMechanicsProcess.cpp index 20f982c1c81167ed136c23b94e6af52f1ad2a970..ca869e11e62dadcd365091c20294d8d57a0f0177 100644 --- a/ProcessLib/ThermoRichardsMechanics/ThermoRichardsMechanicsProcess.cpp +++ b/ProcessLib/ThermoRichardsMechanics/ThermoRichardsMechanicsProcess.cpp @@ -397,8 +397,8 @@ void ThermoRichardsMechanicsProcess<DisplacementDim>::assembleConcreteProcess( { OGS_FATAL( "The Picard method or the Newton-Raphson method with numerical " - "Jacobian is not implemented for ThermoRichardsMechanics with " - "the full monolithic coupling scheme"); + "Jacobian is not implemented for ThermoRichardsMechanics with the full " + "monolithic coupling scheme"); } template <int DisplacementDim> @@ -413,9 +413,8 @@ void ThermoRichardsMechanicsProcess<DisplacementDim>:: dof_tables; DBUG( - "Assemble the Jacobian of ThermoRichardsMechanics for the " - "monolithic" - " scheme."); + "Assemble the Jacobian of ThermoRichardsMechanics for the monolithic " + "scheme."); dof_tables.emplace_back(*_local_to_global_index_map); ProcessLib::ProcessVariable const& pv = getProcessVariables(process_id)[0]; @@ -457,9 +456,7 @@ void ThermoRichardsMechanicsProcess<DisplacementDim>:: GlobalVector const& x_dot, int const process_id) { - DBUG( - "Compute the secondary variables for " - "ThermoRichardsMechanicsProcess."); + DBUG("Compute the secondary variables for ThermoRichardsMechanicsProcess."); auto const dof_tables = getDOFTables(x.size()); diff --git a/ProcessLib/TimeLoop.cpp b/ProcessLib/TimeLoop.cpp index e6388e066076462a3d782b88db92df2cfd583e73..d7e5947d2c262cdda416623f6cc31c6a166854ba 100644 --- a/ProcessLib/TimeLoop.cpp +++ b/ProcessLib/TimeLoop.cpp @@ -242,7 +242,7 @@ setInitialConditions( process_id); auto& time_disc = *process_data->time_disc; - time_disc.setInitialState(t0); // push IC + time_disc.setInitialState(t0); // push IC } return {process_solutions, process_solutions_prev}; @@ -318,8 +318,7 @@ NumLib::NonlinearSolverStatus solveOneTimeStepOneProcess( time_disc.getXdot(*x[process_id], *x_prev[process_id], x_dot); - process.postNonLinearSolver(*x[process_id], x_dot, t, delta_t, - process_id); + process.postNonLinearSolver(*x[process_id], x_dot, t, delta_t, process_id); NumLib::GlobalVectorProvider::provider.releaseVector(x_dot); return nonlinear_solver_status; @@ -469,8 +468,8 @@ double TimeLoop::computeTimeStepping(const double prev_dt, double& t, OGS_FATAL( "The new step size of {:g} is the same as that of the previous " "rejected time step. \nPlease re-run ogs with a proper " - "adjustment in the numerical settings, \ne.g those for " - "time stepper, local or global non-linear solver.", + "adjustment in the numerical settings, \ne.g those for time " + "stepper, local or global non-linear solver.", dt); } else @@ -508,8 +507,8 @@ double TimeLoop::computeTimeStepping(const double prev_dt, double& t, std::numeric_limits<double>::epsilon()) { WARN( - "Time step {:d} was rejected {:d} times " - "and it will be repeated with a reduced step size.", + "Time step {:d} was rejected {:d} times and it will be " + "repeated with a reduced step size.", accepted_steps + 1, _repeating_times_of_rejected_step); MathLib::LinAlg::copy(x_prev, x); // popState } @@ -795,8 +794,8 @@ TimeLoop::solveCoupledEquationSystemsByStaggeredScheme( process_data->nonlinear_solver_status = nonlinear_solver_status; INFO( - "[time] Solving process #{:d} took {:g} s in time step #{:d} " - " coupling iteration #{:d}", + "[time] Solving process #{:d} took {:g} s in time step #{:d} " + "coupling iteration #{:d}", process_id, time_timestep_process.elapsed(), timestep_id, global_coupling_iteration); @@ -845,7 +844,7 @@ TimeLoop::solveCoupledEquationSystemsByStaggeredScheme( if (!coupling_iteration_converged) { WARN( - "The coupling iterations reaches its maximum number in time step" + "The coupling iterations reaches its maximum number in time step " "#{:d} at t = {:g} s", timestep_id, t); } diff --git a/ProcessLib/TwoPhaseFlowWithPP/CreateTwoPhaseFlowWithPPProcess.cpp b/ProcessLib/TwoPhaseFlowWithPP/CreateTwoPhaseFlowWithPPProcess.cpp index 0fdf26e5abf4207fc4ff0c0fd3e5df500cc4ac98..fb2110cbdbb1149cb3cb14ce5867aa02447d9acb 100644 --- a/ProcessLib/TwoPhaseFlowWithPP/CreateTwoPhaseFlowWithPPProcess.cpp +++ b/ProcessLib/TwoPhaseFlowWithPP/CreateTwoPhaseFlowWithPPProcess.cpp @@ -8,15 +8,14 @@ * */ #include "CreateTwoPhaseFlowWithPPProcess.h" + #include <cassert> #include "MaterialLib/MPL/CreateMaterialSpatialDistributionMap.h" #include "MaterialLib/MPL/MaterialSpatialDistributionMap.h" - #include "ParameterLib/Utils.h" #include "ProcessLib/Output/CreateSecondaryVariables.h" #include "ProcessLib/Utils/ProcessUtils.h" - #include "TwoPhaseFlowWithPPProcess.h" #include "TwoPhaseFlowWithPPProcessData.h" namespace ProcessLib diff --git a/ProcessLib/TwoPhaseFlowWithPP/TwoPhaseFlowWithPPProcess.cpp b/ProcessLib/TwoPhaseFlowWithPP/TwoPhaseFlowWithPPProcess.cpp index 2cb46eec54e90f688581afbc971729ceb9704d32..9c9567f6ad885fe6be8e79e83bfe7221bb63ec81 100644 --- a/ProcessLib/TwoPhaseFlowWithPP/TwoPhaseFlowWithPPProcess.cpp +++ b/ProcessLib/TwoPhaseFlowWithPP/TwoPhaseFlowWithPPProcess.cpp @@ -71,7 +71,7 @@ void TwoPhaseFlowWithPPProcess::assembleConcreteProcess( DBUG("Assemble TwoPhaseFlowWithPPProcess."); std::vector<std::reference_wrapper<NumLib::LocalToGlobalIndexMap>> - dof_table = {std::ref(*_local_to_global_index_map)}; + dof_table = {std::ref(*_local_to_global_index_map)}; ProcessLib::ProcessVariable const& pv = getProcessVariables(process_id)[0]; // Call global assembler for each local assembly item. @@ -90,7 +90,7 @@ void TwoPhaseFlowWithPPProcess::assembleWithJacobianConcreteProcess( DBUG("AssembleWithJacobian TwoPhaseFlowWithPPProcess."); std::vector<std::reference_wrapper<NumLib::LocalToGlobalIndexMap>> - dof_table = {std::ref(*_local_to_global_index_map)}; + dof_table = {std::ref(*_local_to_global_index_map)}; ProcessLib::ProcessVariable const& pv = getProcessVariables(process_id)[0]; // Call global assembler for each local assembly item. diff --git a/ProcessLib/TwoPhaseFlowWithPrho/CreateTwoPhaseFlowPrhoMaterialProperties.cpp b/ProcessLib/TwoPhaseFlowWithPrho/CreateTwoPhaseFlowPrhoMaterialProperties.cpp index 2121823653a9636aac2c30d7243dbc33e4be4a31..991c180cdded9ebd85eec7bf4204722701e33858 100644 --- a/ProcessLib/TwoPhaseFlowWithPrho/CreateTwoPhaseFlowPrhoMaterialProperties.cpp +++ b/ProcessLib/TwoPhaseFlowWithPrho/CreateTwoPhaseFlowPrhoMaterialProperties.cpp @@ -9,6 +9,7 @@ */ #include "CreateTwoPhaseFlowPrhoMaterialProperties.h" + #include "BaseLib/Algorithm.h" #include "BaseLib/Logging.h" #include "MaterialLib/Fluid/FluidProperty.h" diff --git a/ProcessLib/TwoPhaseFlowWithPrho/CreateTwoPhaseFlowWithPrhoProcess.cpp b/ProcessLib/TwoPhaseFlowWithPrho/CreateTwoPhaseFlowWithPrhoProcess.cpp index cc3383d47b8732afb05c400d121028fc59d66bab..08f6146658e8201eb56e35d0caf5e9f56f945171 100644 --- a/ProcessLib/TwoPhaseFlowWithPrho/CreateTwoPhaseFlowWithPrhoProcess.cpp +++ b/ProcessLib/TwoPhaseFlowWithPrho/CreateTwoPhaseFlowWithPrhoProcess.cpp @@ -8,7 +8,9 @@ * */ #include "CreateTwoPhaseFlowWithPrhoProcess.h" + #include <cassert> + #include "ParameterLib/Utils.h" #include "ProcessLib/Output/CreateSecondaryVariables.h" #include "ProcessLib/TwoPhaseFlowWithPrho/CreateTwoPhaseFlowPrhoMaterialProperties.h" diff --git a/ProcessLib/TwoPhaseFlowWithPrho/TwoPhaseFlowWithPrhoMaterialProperties.cpp b/ProcessLib/TwoPhaseFlowWithPrho/TwoPhaseFlowWithPrhoMaterialProperties.cpp index 6be25552319870b76ae2c2d828746162fd7d3f82..283b18134380f8bd0bcae0f11916cac79085e516 100644 --- a/ProcessLib/TwoPhaseFlowWithPrho/TwoPhaseFlowWithPrhoMaterialProperties.cpp +++ b/ProcessLib/TwoPhaseFlowWithPrho/TwoPhaseFlowWithPrhoMaterialProperties.cpp @@ -9,7 +9,9 @@ */ #include "TwoPhaseFlowWithPrhoMaterialProperties.h" + #include <utility> + #include "BaseLib/Logging.h" #include "MaterialLib/Fluid/FluidProperty.h" #include "MaterialLib/PorousMedium/Porosity/Porosity.h" @@ -25,9 +27,9 @@ #include "ParameterLib/Parameter.h" #include "ParameterLib/SpatialPosition.h" -using MaterialLib::PhysicalConstant::MolarMass::H2; using MaterialLib::PhysicalConstant::IdealGasConstant; using MaterialLib::PhysicalConstant::HenryConstant::HenryConstantH2; +using MaterialLib::PhysicalConstant::MolarMass::H2; namespace ProcessLib { namespace TwoPhaseFlowWithPrho @@ -270,8 +272,8 @@ void TwoPhaseFlowWithPrhoMaterialProperties::calculateJacobian( } /** Complementary condition 1 -* for calculating molar fraction of light component in the liquid phase -*/ + * for calculating molar fraction of light component in the liquid phase + */ double TwoPhaseFlowWithPrhoMaterialProperties::calculateEquilibiumRhoWetLight( double const pg, double const Sw, double const rho_wet_h2) { @@ -280,8 +282,8 @@ double TwoPhaseFlowWithPrhoMaterialProperties::calculateEquilibiumRhoWetLight( } /** Complementary condition 2 -* for calculating the saturation -*/ + * for calculating the saturation + */ double TwoPhaseFlowWithPrhoMaterialProperties::calculateSaturation( double /*PL*/, double X, double Sw, double rho_wet_h2, double rho_nonwet_h2, double /*T*/) @@ -290,8 +292,8 @@ double TwoPhaseFlowWithPrhoMaterialProperties::calculateSaturation( } /** -* Calculate the derivatives using the analytical way -*/ + * Calculate the derivatives using the analytical way + */ double TwoPhaseFlowWithPrhoMaterialProperties::calculatedSwdP( double pl, double S, double rho_wet_h2, double const T, int current_material_id) const @@ -316,8 +318,8 @@ double TwoPhaseFlowWithPrhoMaterialProperties::calculatedSwdP( return alpha / (beta - alpha * dPC_dSw); } /** -* Calculate the derivatives using the analytical way -*/ + * Calculate the derivatives using the analytical way + */ double TwoPhaseFlowWithPrhoMaterialProperties::calculatedSwdX( double const pl, const double /*X*/, const double S, const double rho_wet_h2, double const T, int current_material_id) const @@ -342,8 +344,8 @@ double TwoPhaseFlowWithPrhoMaterialProperties::calculatedSwdX( return -1 / (beta - alpha * dPC_dSw); } /** -* Calculate the derivatives using the analytical way -*/ + * Calculate the derivatives using the analytical way + */ double TwoPhaseFlowWithPrhoMaterialProperties::calculatedXmdX( double pl, double Sw, double rho_wet_h2, double dSwdX, int current_material_id) const @@ -362,8 +364,8 @@ double TwoPhaseFlowWithPrhoMaterialProperties::calculatedXmdX( return HenryConstantH2 * H2 * dPC_dSw * dSwdX; } /** -* Calculate the derivatives using the analytical way -*/ + * Calculate the derivatives using the analytical way + */ double TwoPhaseFlowWithPrhoMaterialProperties::calculatedXmdP( double pl, double Sw, double rho_wet_h2, double dSwdP, int current_material_id) const diff --git a/ProcessLib/TwoPhaseFlowWithPrho/TwoPhaseFlowWithPrhoProcess.cpp b/ProcessLib/TwoPhaseFlowWithPrho/TwoPhaseFlowWithPrhoProcess.cpp index 0b4d86be804a3acb9c1eda03f91f03cccc0c0c85..bf2c192884ac9bb97991f8cfb8512db473bd5480 100644 --- a/ProcessLib/TwoPhaseFlowWithPrho/TwoPhaseFlowWithPrhoProcess.cpp +++ b/ProcessLib/TwoPhaseFlowWithPrho/TwoPhaseFlowWithPrhoProcess.cpp @@ -72,7 +72,7 @@ void TwoPhaseFlowWithPrhoProcess::assembleConcreteProcess( DBUG("Assemble TwoPhaseFlowWithPrhoProcess."); std::vector<std::reference_wrapper<NumLib::LocalToGlobalIndexMap>> - dof_table = {std::ref(*_local_to_global_index_map)}; + dof_table = {std::ref(*_local_to_global_index_map)}; ProcessLib::ProcessVariable const& pv = getProcessVariables(process_id)[0]; // Call global assembler for each local assembly item. @@ -91,7 +91,7 @@ void TwoPhaseFlowWithPrhoProcess::assembleWithJacobianConcreteProcess( DBUG("AssembleWithJacobian TwoPhaseFlowWithPrhoProcess."); std::vector<std::reference_wrapper<NumLib::LocalToGlobalIndexMap>> - dof_table = {std::ref(*_local_to_global_index_map)}; + dof_table = {std::ref(*_local_to_global_index_map)}; ProcessLib::ProcessVariable const& pv = getProcessVariables(process_id)[0]; // Call global assembler for each local assembly item. diff --git a/ProcessLib/VectorMatrixAssembler.cpp b/ProcessLib/VectorMatrixAssembler.cpp index d911128d7d665a7aa7c027297a51932ab831c674..91810975a4cd6930c1789ebdff797758f879940a 100644 --- a/ProcessLib/VectorMatrixAssembler.cpp +++ b/ProcessLib/VectorMatrixAssembler.cpp @@ -13,11 +13,10 @@ #include <cassert> #include <functional> // for std::reference_wrapper. -#include "NumLib/DOF/DOFTableUtil.h" -#include "MathLib/LinAlg/Eigen/EigenMapTools.h" -#include "LocalAssemblerInterface.h" - #include "CoupledSolutionsForStaggeredScheme.h" +#include "LocalAssemblerInterface.h" +#include "MathLib/LinAlg/Eigen/EigenMapTools.h" +#include "NumLib/DOF/DOFTableUtil.h" #include "Process.h" namespace ProcessLib @@ -78,7 +77,6 @@ void VectorMatrixAssembler::assemble( getCoupledLocalSolutions(xdot, indices_of_processes); auto const local_xdot = MathLib::toVector(local_coupled_xdots); - local_assembler.assembleForStaggeredScheme( t, dt, local_x, local_xdot, process_id, _local_M_data, _local_K_data, _local_b_data); @@ -148,7 +146,6 @@ void VectorMatrixAssembler::assembleWithJacobian( getCoupledLocalSolutions(xdot, indices_of_processes); auto const local_xdot = MathLib::toVector(local_coupled_xdots); - _jacobian_assembler->assembleWithJacobianForStaggeredScheme( local_assembler, t, dt, local_x, local_xdot, dxdot_dx, dx_dx, process_id, _local_M_data, _local_K_data, _local_b_data, diff --git a/Tests/BaseLib/TestAlgorithm.cpp b/Tests/BaseLib/TestAlgorithm.cpp index dd9f6d3207786eb57ed8d0c981c1cb31733eb419..6304ad57b563a286062d2f5e467b7a141c1754a2 100644 --- a/Tests/BaseLib/TestAlgorithm.cpp +++ b/Tests/BaseLib/TestAlgorithm.cpp @@ -7,13 +7,13 @@ * http://www.opengeosys.org/project/license */ +#include <gtest/gtest.h> + #include <algorithm> #include <numeric> #include <random> #include <vector> -#include <gtest/gtest.h> - #include "BaseLib/Algorithm.h" TEST(BaseLibAlgorithm, testreorderVector) diff --git a/Tests/BaseLib/TestConfigTree.cpp b/Tests/BaseLib/TestConfigTree.cpp index 490c95ca54a38d0ab39ecb2a16dcf124c189a8f2..bd8828b9aff086b3a5c1a9127ec4cf4d2fe3f199 100644 --- a/Tests/BaseLib/TestConfigTree.cpp +++ b/Tests/BaseLib/TestConfigTree.cpp @@ -8,7 +8,6 @@ */ #include <gtest/gtest.h> -#include "BaseLib/Logging.h" #include <boost/property_tree/xml_parser.hpp> #include <numeric> @@ -16,29 +15,39 @@ #include <vector> #include "BaseLib/ConfigTree.h" +#include "BaseLib/Logging.h" #include "Tests/TestTools.h" // make useful line numbers appear in the output of gtest -#define EXPECT_ERR_WARN(cbs, error, warning) do { \ - if (error) EXPECT_TRUE((cbs).get_error()); else EXPECT_FALSE((cbs).get_error()); \ - if (warning) EXPECT_TRUE((cbs).get_warning()); else EXPECT_FALSE((cbs).get_warning()); \ - (cbs).reset(); \ - } while(false) +#define EXPECT_ERR_WARN(cbs, error, warning) \ + do \ + { \ + if (error) \ + EXPECT_TRUE((cbs).get_error()); \ + else \ + EXPECT_FALSE((cbs).get_error()); \ + if (warning) \ + EXPECT_TRUE((cbs).get_warning()); \ + else \ + EXPECT_FALSE((cbs).get_warning()); \ + (cbs).reset(); \ + } while (false) // Exception thrown by the error callback of the class below -class Exc {}; +class Exc +{ +}; // class that provides callback functions used with ConfigTree class Callbacks { public: - BaseLib::ConfigTree::Callback - get_error_cb() + BaseLib::ConfigTree::Callback get_error_cb() { return [this](std::string const& filename, std::string const& path, - std::string const& message) - { - (void) path; (void) message; + std::string const& message) { + (void)path; + (void)message; // check that filename is passed around properly, especially with // move construction/assignment @@ -46,17 +55,16 @@ public: DBUG("error <{:s}> : {:s}", path, message); _error = true; - throw Exc(); // throw in order to stop normal execution + throw Exc(); // throw in order to stop normal execution }; } - BaseLib::ConfigTree::Callback - get_warning_cb() + BaseLib::ConfigTree::Callback get_warning_cb() { return [this](std::string const& filename, std::string const& path, - std::string const& message) - { - (void) path; (void) message; + std::string const& message) { + (void)path; + (void)message; // check that filename is passed around properly, especially with // move construction/assignment @@ -67,23 +75,26 @@ public: }; } - bool get_error() const { return _error; } + bool get_error() const { return _error; } bool get_warning() const { return _warning; } - void reset() { _error = false; _warning = false; } + void reset() + { + _error = false; + _warning = false; + } private: bool _error = false; bool _warning = false; }; -BaseLib::ConfigTree -makeConfigTree(boost::property_tree::ptree const& ptree, Callbacks& cbs) +BaseLib::ConfigTree makeConfigTree(boost::property_tree::ptree const& ptree, + Callbacks& cbs) { - return BaseLib::ConfigTree(ptree, "FILENAME", - cbs.get_error_cb(), cbs.get_warning_cb()); + return BaseLib::ConfigTree(ptree, "FILENAME", cbs.get_error_cb(), + cbs.get_warning_cb()); } - TEST(BaseLibConfigTree, Empty) { boost::property_tree::ptree ptree; @@ -91,52 +102,51 @@ TEST(BaseLibConfigTree, Empty) { auto const conf = makeConfigTree(ptree, cbs); - (void) conf; - } // ConfigTree destroyed here + (void)conf; + } // ConfigTree destroyed here EXPECT_ERR_WARN(cbs, false, false); } - TEST(BaseLibConfigTree, Get) { const char xml[] = - "<double>5.6e-4</double>" - "<bool>true</bool>" - "<int>5</int>" - "<sub>" - " <float>6.1</float>" - " <float2>0.1</float2>" - " <bool1>false</bool1>" - " <bool2>false</bool2>" - " <bool3/>" - " <ignored/>" - " <ignored2/>" - " <ignored2/>" - "</sub>" - "<x>Y</x>" - "<z attr=\"0.5\" optattr=\"false\">32.0</z>" - "<vector>0 1 2 3 4</vector>" - "<vector_bad1>x 1 2a</vector_bad1>" - "<vector_bad2>0 1 2a</vector_bad2>" - ; + "<double>5.6e-4</double>" + "<bool>true</bool>" + "<int>5</int>" + "<sub>" + " <float>6.1</float>" + " <float2>0.1</float2>" + " <bool1>false</bool1>" + " <bool2>false</bool2>" + " <bool3/>" + " <ignored/>" + " <ignored2/>" + " <ignored2/>" + "</sub>" + "<x>Y</x>" + "<z attr=\"0.5\" optattr=\"false\">32.0</z>" + "<vector>0 1 2 3 4</vector>" + "<vector_bad1>x 1 2a</vector_bad1>" + "<vector_bad2>0 1 2a</vector_bad2>"; auto const ptree = Tests::readXml(xml); Callbacks cbs; { auto const conf = makeConfigTree(ptree, cbs); - EXPECT_EQ(5.6e-4, conf.getConfigParameter<double>("double")); // read certain types + EXPECT_EQ(5.6e-4, conf.getConfigParameter<double>( + "double")); // read certain types EXPECT_ERR_WARN(cbs, false, false); EXPECT_TRUE(conf.getConfigParameter<bool>("bool")); EXPECT_ERR_WARN(cbs, false, false); EXPECT_EQ(5, conf.getConfigParameter<int>("int")); EXPECT_ERR_WARN(cbs, false, false); - EXPECT_EQ(8, conf.getConfigParameter<int>("intx", 8)); // reading with default value + EXPECT_EQ(8, conf.getConfigParameter<int>( + "intx", 8)); // reading with default value EXPECT_ERR_WARN(cbs, false, false); - // Testing subtree { auto sub = conf.getConfigSubtree("sub"); @@ -145,83 +155,94 @@ TEST(BaseLibConfigTree, Get) EXPECT_EQ(6.1f, sub.getConfigParameter<float>("float")); EXPECT_ERR_WARN(cbs, false, false); - if (auto f2 = sub.getConfigParameterOptional<float>("float2")) { // read optional value + if (auto f2 = sub.getConfigParameterOptional<float>("float2")) + { // read optional value EXPECT_EQ(0.1f, *f2); } EXPECT_ERR_WARN(cbs, false, false); - auto f3 = sub.getConfigParameterOptional<float>("float3"); // optional value not existent + auto f3 = sub.getConfigParameterOptional<float>( + "float3"); // optional value not existent ASSERT_FALSE(f3); EXPECT_ERR_WARN(cbs, false, false); - - // Testing the getConfigParameter...() (non-template) / getValue() combination + // Testing the getConfigParameter...() (non-template) / getValue() + // combination auto bool1 = sub.getConfigSubtree("bool1"); EXPECT_ERR_WARN(cbs, false, false); EXPECT_FALSE(bool1.getValue<bool>()); EXPECT_ERR_WARN(cbs, false, false); - EXPECT_ANY_THROW(bool1.getValue<bool>()); // getting data twice + EXPECT_ANY_THROW(bool1.getValue<bool>()); // getting data twice EXPECT_ERR_WARN(cbs, true, false); - if (auto bool2 = sub.getConfigSubtreeOptional("bool2")) { + if (auto bool2 = sub.getConfigSubtreeOptional("bool2")) + { EXPECT_ERR_WARN(cbs, false, false); EXPECT_FALSE(bool2->getValue<bool>()); } EXPECT_ERR_WARN(cbs, false, false); - if (auto bool3 = sub.getConfigSubtreeOptional("bool3")) { + if (auto bool3 = sub.getConfigSubtreeOptional("bool3")) + { EXPECT_ERR_WARN(cbs, false, false); EXPECT_ANY_THROW(bool3->getValue<bool>()); - EXPECT_ERR_WARN(cbs, true, false); // error because of no data + EXPECT_ERR_WARN(cbs, true, false); // error because of no data } EXPECT_ERR_WARN(cbs, false, false); - EXPECT_FALSE(sub.getConfigSubtreeOptional("bool4")); // optional value not existent + EXPECT_FALSE(sub.getConfigSubtreeOptional( + "bool4")); // optional value not existent EXPECT_ERR_WARN(cbs, false, false); - // Testing ignore sub.ignoreConfigParameter("ignored"); EXPECT_ERR_WARN(cbs, false, false); sub.ignoreConfigParameterAll("ignored2"); EXPECT_ERR_WARN(cbs, false, false); - sub.ignoreConfigParameterAll("ignored4"); // I can ignore nonexistent stuff + sub.ignoreConfigParameterAll( + "ignored4"); // I can ignore nonexistent stuff EXPECT_ERR_WARN(cbs, false, false); // I can not ignore stuff that I already read - // this also makes sure that the subtree inherits the callbacks properly + // this also makes sure that the subtree inherits the callbacks + // properly EXPECT_ANY_THROW(sub.ignoreConfigParameter("float")); EXPECT_ERR_WARN(cbs, true, false); } - for (int i : {0, 1, 2}) { - (void) i; + for (int i : {0, 1, 2}) + { + (void)i; EXPECT_EQ("Y", conf.peekConfigParameter<std::string>("x")); EXPECT_ERR_WARN(cbs, false, false); } conf.checkConfigParameter<std::string>("x", "Y"); EXPECT_ERR_WARN(cbs, false, false); - // Testing attributes { auto z = conf.getConfigSubtree("z"); EXPECT_ERR_WARN(cbs, false, false); EXPECT_EQ(0.5, z.getConfigAttribute<double>("attr")); EXPECT_ERR_WARN(cbs, false, false); - EXPECT_ANY_THROW(z.getConfigAttribute<double>("attr")); // getting attribute twice + EXPECT_ANY_THROW(z.getConfigAttribute<double>( + "attr")); // getting attribute twice EXPECT_ERR_WARN(cbs, true, false); - EXPECT_ANY_THROW(z.getConfigAttribute<double>("not_an_attr")); // nonexistent attribute + EXPECT_ANY_THROW(z.getConfigAttribute<double>( + "not_an_attr")); // nonexistent attribute EXPECT_ERR_WARN(cbs, true, false); EXPECT_EQ(32.0, z.getValue<double>()); EXPECT_ERR_WARN(cbs, false, false); auto const opt = z.getConfigAttributeOptional<bool>("optattr"); - EXPECT_TRUE(!!opt); EXPECT_FALSE(*opt); + EXPECT_TRUE(!!opt); + EXPECT_FALSE(*opt); EXPECT_ERR_WARN(cbs, false, false); - EXPECT_ANY_THROW(z.getConfigAttributeOptional<bool>("optattr")); // getting attribute twice + EXPECT_ANY_THROW(z.getConfigAttributeOptional<bool>( + "optattr")); // getting attribute twice EXPECT_ERR_WARN(cbs, true, false); - EXPECT_FALSE(z.getConfigAttributeOptional<bool>("also_not_an_attr")); // nonexisting attribute + EXPECT_FALSE(z.getConfigAttributeOptional<bool>( + "also_not_an_attr")); // nonexisting attribute EXPECT_ERR_WARN(cbs, false, false); } @@ -242,20 +263,18 @@ TEST(BaseLibConfigTree, Get) EXPECT_ERR_WARN(cbs, true, false); } EXPECT_ERR_WARN(cbs, false, false); - } // ConfigTree destroyed here + } // ConfigTree destroyed here EXPECT_ERR_WARN(cbs, false, false); } - TEST(BaseLibConfigTree, IncompleteParse) { const char xml[] = - "<double>5.6</double>" - "<not_read>true</not_read>" - "<tag>this data won't be read</tag>" - "<pt x=\"0.5\">1</pt>" - "<pt2 x=\"0.5\" y=\"1.0\" z=\"2.0\" />" - ; + "<double>5.6</double>" + "<not_read>true</not_read>" + "<tag>this data won't be read</tag>" + "<pt x=\"0.5\">1</pt>" + "<pt2 x=\"0.5\" y=\"1.0\" z=\"2.0\" />"; auto const ptree = Tests::readXml(xml); Callbacks cbs; @@ -266,10 +285,10 @@ TEST(BaseLibConfigTree, IncompleteParse) EXPECT_ERR_WARN(cbs, false, false); conf.getConfigSubtree("tag"); - EXPECT_ERR_WARN(cbs, false, true); // data of <tag> has not been read + EXPECT_ERR_WARN(cbs, false, true); // data of <tag> has not been read EXPECT_EQ(1, conf.getConfigParameter<int>("pt")); - EXPECT_ERR_WARN(cbs, false, true); // attribute "x" has not been read + EXPECT_ERR_WARN(cbs, false, true); // attribute "x" has not been read { auto pt2 = conf.getConfigSubtree("pt2"); @@ -279,24 +298,24 @@ TEST(BaseLibConfigTree, IncompleteParse) EXPECT_ERR_WARN(cbs, false, false); BaseLib::checkAndInvalidate(pt2); - EXPECT_ERR_WARN(cbs, false, true); // attribute "z" not read + EXPECT_ERR_WARN(cbs, false, true); // attribute "z" not read } EXPECT_ERR_WARN(cbs, false, false); - } // ConfigTree destroyed here - EXPECT_ERR_WARN(cbs, false, true); // expect warning because I didn't read everything + } // ConfigTree destroyed here + EXPECT_ERR_WARN(cbs, false, + true); // expect warning because I didn't read everything } - TEST(BaseLibConfigTree, CheckRange) { const char xml[] = - "<val><int>0</int></val>" - "<val><int>1</int></val>" - "<val><int>2</int></val>" - "<int>0</int>" - "<int>1</int>" - "<int>2</int>"; + "<val><int>0</int></val>" + "<val><int>1</int></val>" + "<val><int>2</int></val>" + "<int>0</int>" + "<int>1</int>" + "<int>2</int>"; auto const ptree = Tests::readXml(xml); Callbacks cbs; @@ -323,19 +342,18 @@ TEST(BaseLibConfigTree, CheckRange) EXPECT_ERR_WARN(cbs, false, false); } - } // ConfigTree destroyed here + } // ConfigTree destroyed here // there will be warnings because I don't process the list entries EXPECT_ERR_WARN(cbs, false, true); } - TEST(BaseLibConfigTree, GetSubtreeList) { const char xml[] = - "<val><int>0</int></val>" - "<val><int>1</int></val>" - "<val><int>2</int></val>"; + "<val><int>0</int></val>" + "<val><int>1</int></val>" + "<val><int>2</int></val>"; auto const ptree = Tests::readXml(xml); Callbacks cbs; @@ -344,7 +362,7 @@ TEST(BaseLibConfigTree, GetSubtreeList) for (auto p : conf.getConfigSubtreeList("nonexistent_list")) { - (void) p; + (void)p; FAIL() << "Expected empty list"; } EXPECT_ERR_WARN(cbs, false, false); @@ -356,18 +374,18 @@ TEST(BaseLibConfigTree, GetSubtreeList) EXPECT_ERR_WARN(cbs, false, false); ++i; } - } // ConfigTree destroyed here + } // ConfigTree destroyed here EXPECT_ERR_WARN(cbs, false, false); } TEST(BaseLibConfigTree, GetParamList) { const char xml[] = - "<int>0</int>" - "<int>1</int>" - "<int>2</int>" - "<int2 a=\"b\">3</int2>" - "<int3>4<error/></int3>"; + "<int>0</int>" + "<int>1</int>" + "<int>2</int>" + "<int2 a=\"b\">3</int2>" + "<int3>4<error/></int3>"; auto const ptree = Tests::readXml(xml); Callbacks cbs; @@ -376,7 +394,7 @@ TEST(BaseLibConfigTree, GetParamList) for (auto p : conf.getConfigParameterList("nonexistent_list")) { - (void) p; + (void)p; FAIL() << "Expected empty list"; } EXPECT_ERR_WARN(cbs, false, false); @@ -395,7 +413,7 @@ TEST(BaseLibConfigTree, GetParamList) EXPECT_ERR_WARN(cbs, false, false); ++i; } - EXPECT_ERR_WARN(cbs, false, true); // attribute "a" not read + EXPECT_ERR_WARN(cbs, false, true); // attribute "a" not read { // get list of parameters, i.e., subtrees without children @@ -405,20 +423,19 @@ TEST(BaseLibConfigTree, GetParamList) EXPECT_ANY_THROW(*range.begin()); // error because of child tag <error/> EXPECT_ERR_WARN(cbs, true, false); - } // range destroyed here + } // range destroyed here EXPECT_ERR_WARN(cbs, false, false); - } // ConfigTree destroyed here + } // ConfigTree destroyed here EXPECT_ERR_WARN(cbs, false, false); } - TEST(BaseLibConfigTree, GetValueList) { const char xml[] = - "<int>0</int>" - "<int>1</int>" - "<int>2</int>"; + "<int>0</int>" + "<int>1</int>" + "<int>2</int>"; auto const ptree = Tests::readXml(xml); Callbacks cbs; @@ -427,7 +444,7 @@ TEST(BaseLibConfigTree, GetValueList) for (auto p : conf.getConfigParameterList<int>("nonexistent_list")) { - (void) p; + (void)p; FAIL() << "Expected empty list"; } EXPECT_ERR_WARN(cbs, false, false); @@ -439,21 +456,19 @@ TEST(BaseLibConfigTree, GetValueList) EXPECT_ERR_WARN(cbs, false, false); ++n; } - } // ConfigTree destroyed here + } // ConfigTree destroyed here EXPECT_ERR_WARN(cbs, false, false); } - TEST(BaseLibConfigTree, NoConversion) { const char xml[] = - "<int>5.6</int>" // not convertible to int - "<double>5.6tz</double>" // not convertible to double - "<non_double>0.1x</non_double>" // not either convertible to double - "<bool>true</bool>" - "<ign/>" - "<ign2/><ign2/><ign2/>" - ; + "<int>5.6</int>" // not convertible to int + "<double>5.6tz</double>" // not convertible to double + "<non_double>0.1x</non_double>" // not either convertible to double + "<bool>true</bool>" + "<ign/>" + "<ign2/><ign2/><ign2/>"; auto const ptree = Tests::readXml(xml); Callbacks cbs; @@ -462,7 +477,8 @@ TEST(BaseLibConfigTree, NoConversion) EXPECT_ANY_THROW(conf.getConfigParameter<int>("int")); EXPECT_ERR_WARN(cbs, true, false); - EXPECT_ANY_THROW(conf.ignoreConfigParameter("int")); // after failure I also cannot ignore something + EXPECT_ANY_THROW(conf.ignoreConfigParameter( + "int")); // after failure I also cannot ignore something EXPECT_ERR_WARN(cbs, true, false); EXPECT_ANY_THROW(conf.getConfigParameter<double>("double")); @@ -475,8 +491,7 @@ TEST(BaseLibConfigTree, NoConversion) // optional value existent but not convertible EXPECT_ANY_THROW( auto d = conf.getConfigParameterOptional<double>("non_double"); - ASSERT_FALSE(d); - ); + ASSERT_FALSE(d);); EXPECT_ERR_WARN(cbs, true, false); // assert that I can only ignore something once @@ -495,14 +510,13 @@ TEST(BaseLibConfigTree, NoConversion) EXPECT_ANY_THROW(conf.getConfigParameter<bool>("bool")); EXPECT_ERR_WARN(cbs, true, false); - } // ConfigTree destroyed here + } // ConfigTree destroyed here // There will bewarnings because I don't succeed in reading every setting, // and furthermore I read some setting too often. EXPECT_ERR_WARN(cbs, false, false); } - TEST(BaseLibConfigTree, BadKeynames) { const char xml[] = ""; @@ -512,7 +526,7 @@ TEST(BaseLibConfigTree, BadKeynames) { auto const conf = makeConfigTree(ptree, cbs); - for (auto tag : { "<", "Z", ".", "$", "0", "", "/", "_", "a__" }) + for (auto tag : {"<", "Z", ".", "$", "0", "", "/", "_", "a__"}) { EXPECT_ANY_THROW(conf.getConfigParameter<int>(tag)); EXPECT_ERR_WARN(cbs, true, false); @@ -539,7 +553,7 @@ TEST(BaseLibConfigTree, BadKeynames) EXPECT_ERR_WARN(cbs, true, false); } - } // ConfigTree destroyed here + } // ConfigTree destroyed here EXPECT_ERR_WARN(cbs, false, false); } @@ -548,8 +562,8 @@ TEST(BaseLibConfigTree, BadKeynames) TEST(BaseLibConfigTree, StringLiterals) { const char xml[] = - "<s>test</s>" - "<t>Test</t>"; + "<s>test</s>" + "<t>Test</t>"; auto const ptree = Tests::readXml(xml); Callbacks cbs; @@ -560,12 +574,12 @@ TEST(BaseLibConfigTree, StringLiterals) EXPECT_ERR_WARN(cbs, false, false); // <n> not present in the XML, so return the default value - EXPECT_EQ("XX", conf.getConfigParameter<std::string>("n", "XX")); + EXPECT_EQ("XX", conf.getConfigParameter<std::string>("n", "XX")); EXPECT_ERR_WARN(cbs, false, false); conf.checkConfigParameter("t", "Test"); EXPECT_ERR_WARN(cbs, false, false); - } // ConfigTree destroyed here + } // ConfigTree destroyed here EXPECT_ERR_WARN(cbs, false, false); } @@ -573,9 +587,9 @@ TEST(BaseLibConfigTree, StringLiterals) TEST(BaseLibConfigTree, MoveConstruct) { const char xml[] = - "<s>test</s>" - "<t>Test</t>" - "<u>data</u>"; + "<s>test</s>" + "<t>Test</t>" + "<u>data</u>"; auto const ptree = Tests::readXml(xml); Callbacks cbs; @@ -601,7 +615,7 @@ TEST(BaseLibConfigTree, MoveConstruct) // test that read status of children is transferred in move construction BaseLib::ConfigTree conf2(std::move(conf)); - EXPECT_EQ("XX", conf2.getConfigParameter<std::string>("n", "XX")); + EXPECT_EQ("XX", conf2.getConfigParameter<std::string>("n", "XX")); EXPECT_ERR_WARN(cbs, false, false); conf2.checkConfigParameter("t", "Test"); @@ -609,7 +623,7 @@ TEST(BaseLibConfigTree, MoveConstruct) BaseLib::checkAndInvalidate(conf2); EXPECT_ERR_WARN(cbs, false, false); - } // ConfigTree destroyed here + } // ConfigTree destroyed here EXPECT_ERR_WARN(cbs, false, false); } @@ -617,9 +631,9 @@ TEST(BaseLibConfigTree, MoveConstruct) TEST(BaseLibConfigTree, MoveAssign) { const char xml[] = - "<s>test</s>" - "<t>Test</t>" - "<u>data</u>"; + "<s>test</s>" + "<t>Test</t>" + "<u>data</u>"; auto const ptree = Tests::readXml(xml); Callbacks cbs; @@ -653,13 +667,13 @@ TEST(BaseLibConfigTree, MoveAssign) // entirely before assignment. EXPECT_ERR_WARN(cbs, false, true); - EXPECT_EQ("XX", conf2.getConfigParameter<std::string>("n", "XX")); + EXPECT_EQ("XX", conf2.getConfigParameter<std::string>("n", "XX")); EXPECT_ERR_WARN(cbs, false, false); conf2.checkConfigParameter("t", "Test"); EXPECT_ERR_WARN(cbs, false, false); } EXPECT_ERR_WARN(cbs, false, false); - } // ConfigTree destroyed here + } // ConfigTree destroyed here EXPECT_ERR_WARN(cbs, false, false); } diff --git a/Tests/BaseLib/TestConstructFormattedFileName.cpp b/Tests/BaseLib/TestConstructFormattedFileName.cpp index 2c6120dc84b315ce06ee9a2aaa4e7f1033df3980..cfcc99cb7ee6ef3296dd7a1aba2877064cc66634 100644 --- a/Tests/BaseLib/TestConstructFormattedFileName.cpp +++ b/Tests/BaseLib/TestConstructFormattedFileName.cpp @@ -7,6 +7,8 @@ * http://www.opengeosys.org/project/license */ +#include <gtest/gtest.h> + #include <algorithm> #include <array> #include <cstring> @@ -15,8 +17,6 @@ #include <random> #include <string> -#include <gtest/gtest.h> - #include "BaseLib/FileTools.h" TEST(BaseLib, constructFormattedFileName) @@ -33,9 +33,8 @@ TEST(BaseLib, constructFormattedFileName) ASSERT_EQ("test_0.20000", formatted_filename_time); } { - auto const formatted_filename = - BaseLib::constructFormattedFileName("test_{:iteration}", "mesh_name", - 2, 0.2, 3); + auto const formatted_filename = BaseLib::constructFormattedFileName( + "test_{:iteration}", "mesh_name", 2, 0.2, 3); ASSERT_EQ("test_3", formatted_filename); } { diff --git a/Tests/BaseLib/TestFilePathStringManipulation.cpp b/Tests/BaseLib/TestFilePathStringManipulation.cpp index 78551407c1b5a6e842deb4eb9dcf1537ff140e25..7987eac98c3292574742ae4e861affc5178aa0b2 100644 --- a/Tests/BaseLib/TestFilePathStringManipulation.cpp +++ b/Tests/BaseLib/TestFilePathStringManipulation.cpp @@ -11,7 +11,7 @@ * http://www.opengeosys.org/project/license */ -#include "gtest/gtest.h" +#include <gtest/gtest.h> #include "BaseLib/FileTools.h" @@ -33,8 +33,7 @@ TEST(BaseLib, CopyPathToFileNameWin) TEST(BaseLib, CopyPathToFileNameUnix) { ASSERT_EQ("extend/file", BaseLib::copyPathToFileName("file", "extend")); - ASSERT_EQ("path/file", - BaseLib::copyPathToFileName("path/file", "extend")); + ASSERT_EQ("path/file", BaseLib::copyPathToFileName("path/file", "extend")); ASSERT_EQ("extend/file", BaseLib::copyPathToFileName("file", "extend/")); ASSERT_EQ("path/file", BaseLib::copyPathToFileName("path/file", "extend/")); diff --git a/Tests/BaseLib/TestQuicksort.cpp b/Tests/BaseLib/TestQuicksort.cpp index 6030581ad0a6ce435ef889e317857bfdd30b10ec..914a32419f656b3b51bf7efbd9730aa18fee8be8 100644 --- a/Tests/BaseLib/TestQuicksort.cpp +++ b/Tests/BaseLib/TestQuicksort.cpp @@ -12,7 +12,10 @@ * */ +#include <gtest/gtest.h> + #include <algorithm> +#include <autocheck/autocheck.hpp> #include <numeric> #include <random> #include <sstream> @@ -20,9 +23,6 @@ #include <tuple> #include <vector> -#include <gtest/gtest.h> -#include <autocheck/autocheck.hpp> - #include "BaseLib/quicksort.h" namespace ac = autocheck; @@ -31,15 +31,11 @@ struct BaseLibQuicksort : public ::testing::Test { void SetUp() override { - cls.trivial([](const std::vector<int>& xs) - { - return xs.size() < 2; - }); - - cls.collect([](std::vector<int> const& xs) - { - return xs.size() < 10 ? "short" : "long"; - }); + cls.trivial([](const std::vector<int>& xs) { return xs.size() < 2; }); + + cls.collect([](std::vector<int> const& xs) { + return xs.size() < 10 ? "short" : "long"; + }); } ac::gtest_reporter gtest_reporter; @@ -50,14 +46,12 @@ struct BaseLibQuicksort : public ::testing::Test TEST_F(BaseLibQuicksort, SortsAsSTLSort) { cls.classify( - [](std::vector<int> const& xs) - { + [](std::vector<int> const& xs) { return std::is_sorted(xs.begin(), xs.end()); }, "sorted"); - auto quicksortSortsAsSTLSort = [](std::vector<int>& xs) -> bool - { + auto quicksortSortsAsSTLSort = [](std::vector<int>& xs) -> bool { std::vector<std::size_t> perm(xs.size()); if (!xs.empty()) { @@ -94,8 +88,7 @@ TEST_F(BaseLibQuicksort, ReportCorrectPermutations) { auto gen = ac::make_arbitrary(OrderedUniqueListGen<int>()); - auto quicksortCheckPermutations = [](std::vector<int>& xs) - { + auto quicksortCheckPermutations = [](std::vector<int>& xs) { std::vector<std::size_t> perm(xs.size()); std::iota(perm.begin(), perm.end(), 0); @@ -112,12 +105,10 @@ TEST_F(BaseLibQuicksort, ReportCorrectPermutations) return true; }; - ac::check<std::vector<int>>(quicksortCheckPermutations, 100, - gen.discard_if([](std::vector<int> xs) - { - return xs.empty(); - }), - gtest_reporter, cls); + ac::check<std::vector<int>>( + quicksortCheckPermutations, 100, + gen.discard_if([](std::vector<int> xs) { return xs.empty(); }), + gtest_reporter, cls); } // Permutations of non-empty, sorted, unique vector remain untouched. @@ -125,8 +116,7 @@ TEST_F(BaseLibQuicksort, ReportCorrectPermutationsWithPointer) { auto gen = ac::make_arbitrary(OrderedUniqueListGen<int>()); - auto quicksortCheckPermutations = [](std::vector<int>& xs) - { + auto quicksortCheckPermutations = [](std::vector<int>& xs) { std::vector<std::size_t> perm(xs.size()); std::iota(perm.begin(), perm.end(), 0); @@ -149,12 +139,10 @@ TEST_F(BaseLibQuicksort, ReportCorrectPermutationsWithPointer) return true; }; - ac::check<std::vector<int>>(quicksortCheckPermutations, 100, - gen.discard_if([](std::vector<int> xs) - { - return xs.empty(); - }), - gtest_reporter, cls); + ac::check<std::vector<int>>( + quicksortCheckPermutations, 100, + gen.discard_if([](std::vector<int> xs) { return xs.empty(); }), + gtest_reporter, cls); } // Permutations of non-empty, reverse sorted, unique vector is also reversed. @@ -169,8 +157,7 @@ TEST_F(BaseLibQuicksort, ReportCorrectPermutationsReverse) auto gen = ac::make_arbitrary(ac::map(reverse, OrderedUniqueListGen<int>())); - auto quicksortCheckPermutations = [](std::vector<int>& xs) - { + auto quicksortCheckPermutations = [](std::vector<int>& xs) { std::vector<std::size_t> perm(xs.size()); std::iota(perm.begin(), perm.end(), 0); @@ -186,12 +173,10 @@ TEST_F(BaseLibQuicksort, ReportCorrectPermutationsReverse) return true; }; - ac::check<std::vector<int>>(quicksortCheckPermutations, 100, - gen.discard_if([](std::vector<int> xs) - { - return xs.empty(); - }), - gtest_reporter, cls); + ac::check<std::vector<int>>( + quicksortCheckPermutations, 100, + gen.discard_if([](std::vector<int> xs) { return xs.empty(); }), + gtest_reporter, cls); } // Permutations of non-empty, reverse sorted, unique vector is also reversed. @@ -206,8 +191,7 @@ TEST_F(BaseLibQuicksort, ReportCorrectPermutationsReverseWithPointer) auto gen = ac::make_arbitrary(ac::map(reverse, OrderedUniqueListGen<int>())); - auto quicksortCheckPermutations = [](std::vector<int>& xs) - { + auto quicksortCheckPermutations = [](std::vector<int>& xs) { std::vector<std::size_t> perm(xs.size()); std::iota(perm.begin(), perm.end(), 0); @@ -229,12 +213,10 @@ TEST_F(BaseLibQuicksort, ReportCorrectPermutationsReverseWithPointer) return true; }; - ac::check<std::vector<int>>(quicksortCheckPermutations, 100, - gen.discard_if([](std::vector<int> xs) - { - return xs.empty(); - }), - gtest_reporter, cls); + ac::check<std::vector<int>>( + quicksortCheckPermutations, 100, + gen.discard_if([](std::vector<int> xs) { return xs.empty(); }), + gtest_reporter, cls); } template <typename T, typename Gen = ac::generator<T>> @@ -268,11 +250,11 @@ TEST_F(BaseLibQuicksort, SortsRangeAsSTLSort) std::vector<std::size_t> perm(xs.size()); std::iota(perm.begin(), perm.end(), 0); BaseLib::quicksort(xs, std::get<0>(range), std::get<1>(range), perm); - return - std::is_sorted( - xs.begin() + std::get<0>(range), xs.begin() + std::get<1>(range)) - && std::is_sorted(perm.begin(), perm.begin() + std::get<0>(range)) - && std::is_sorted(perm.begin() + std::get<1>(range), perm.end()); + return std::is_sorted(xs.begin() + std::get<0>(range), + xs.begin() + std::get<1>(range)) && + std::is_sorted(perm.begin(), + perm.begin() + std::get<0>(range)) && + std::is_sorted(perm.begin() + std::get<1>(range), perm.end()); }; ac::check<std::vector<int>, std::tuple<std::size_t, std::size_t>>( @@ -281,9 +263,8 @@ TEST_F(BaseLibQuicksort, SortsRangeAsSTLSort) ac::make_arbitrary(ac::generator<std::vector<int>>(), randomSortedPairGenerator<std::size_t>()) .discard_if([](std::vector<int> const& xs, - std::tuple<std::size_t, std::size_t> const& range) - { - return std::get<1>(range) >= xs.size(); - }), + std::tuple<std::size_t, std::size_t> const& range) { + return std::get<1>(range) >= xs.size(); + }), gtest_reporter); } diff --git a/Tests/BaseLib/TestReadStringListFromFile.cpp b/Tests/BaseLib/TestReadStringListFromFile.cpp index aa2376afbc3c864e1e4dd24a39a9103d228ff301..4856c4aac482663c327bb949b3ab4701ed52a493 100644 --- a/Tests/BaseLib/TestReadStringListFromFile.cpp +++ b/Tests/BaseLib/TestReadStringListFromFile.cpp @@ -7,11 +7,11 @@ * http://www.opengeosys.org/project/license */ +#include <gtest/gtest.h> + #include <string> #include <vector> -#include <gtest/gtest.h> - #include "BaseLib/IO/readStringListFromFile.h" #include "InfoLib/TestInfo.h" diff --git a/Tests/BaseLib/TestgetParenthesizedString.cpp b/Tests/BaseLib/TestgetParenthesizedString.cpp index 3ab3e665a18bb127c370034326d35387e745e352..b7b68c139ddaef41543ae0848d28000bd24eebc0 100644 --- a/Tests/BaseLib/TestgetParenthesizedString.cpp +++ b/Tests/BaseLib/TestgetParenthesizedString.cpp @@ -7,6 +7,8 @@ * http://www.opengeosys.org/project/license */ +#include <gtest/gtest.h> + #include <algorithm> #include <array> #include <cstring> @@ -15,8 +17,6 @@ #include <random> #include <string> -#include <gtest/gtest.h> - #include "BaseLib/FileTools.h" // https://stackoverflow.com/questions/440133/how-do-i-create-a-random-alpha-numeric-string-in-c @@ -36,9 +36,7 @@ auto random_generator() -> T auto generate_random_alphanumeric_string(std::size_t len) -> std::string { static constexpr auto chars = - "123456788" - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz"; + "123456788ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; thread_local auto rng = random_generator<>(); auto dist = std::uniform_int_distribution{{}, std::strlen(chars)}; @@ -51,16 +49,18 @@ TEST(BaseLib, getParenthesizedString) { { // {} return empty string std::string const test_string = "{}"; - ASSERT_TRUE(std::get<0>( - BaseLib::getParenthesizedString(test_string, '{', '}', 0)).empty()); + ASSERT_TRUE(std::get<0>(BaseLib::getParenthesizedString(test_string, + '{', '}', 0)) + .empty()); } { // a{}b return empty string std::string const pre = generate_random_alphanumeric_string(20); std::string const post = generate_random_alphanumeric_string(20); std::string const test_string = pre + "{}" + post; - ASSERT_TRUE(std::get<0>( - BaseLib::getParenthesizedString(test_string, '{', '}', 0)).empty()); + ASSERT_TRUE(std::get<0>(BaseLib::getParenthesizedString(test_string, + '{', '}', 0)) + .empty()); } // }a{ @@ -68,8 +68,9 @@ TEST(BaseLib, getParenthesizedString) { std::string const random = generate_random_alphanumeric_string(20); std::string const test_string = "}" + random + "{"; - ASSERT_TRUE(std::get<0>( - BaseLib::getParenthesizedString(test_string, '{', '}', 0)).empty()); + ASSERT_TRUE(std::get<0>(BaseLib::getParenthesizedString(test_string, + '{', '}', 0)) + .empty()); } // {a} @@ -80,8 +81,9 @@ TEST(BaseLib, getParenthesizedString) ASSERT_EQ(expected, std::get<0>(BaseLib::getParenthesizedString(test_string, '{', '}', 0))); - ASSERT_TRUE(std::get<0>( - BaseLib::getParenthesizedString(test_string, '{', '}', 1)).empty()); + ASSERT_TRUE(std::get<0>(BaseLib::getParenthesizedString(test_string, + '{', '}', 1)) + .empty()); } // a{b} @@ -108,10 +110,10 @@ TEST(BaseLib, getParenthesizedString) ASSERT_EQ(expected, std::get<0>(BaseLib::getParenthesizedString(test_string, '{', '}', 0))); - ASSERT_TRUE(std::get<0>( - BaseLib::getParenthesizedString( - test_string, '{', '}', pre.length() + expected.length() + 2)) - .empty()); + ASSERT_TRUE(std::get<0>(BaseLib::getParenthesizedString( + test_string, '{', '}', + pre.length() + expected.length() + 2)) + .empty()); } // a{b{c}" diff --git a/Tests/FileIO/TestBoostGmlInterface.cpp b/Tests/FileIO/TestBoostGmlInterface.cpp index 94e9591c016900359d79d0ef006aee2cf94e8b96..eacb84155c92152a35878bf6e57edd982b538870 100644 --- a/Tests/FileIO/TestBoostGmlInterface.cpp +++ b/Tests/FileIO/TestBoostGmlInterface.cpp @@ -12,6 +12,8 @@ * */ +#include <gtest/gtest.h> + #include <cstdio> #include "BaseLib/StringTools.h" @@ -20,13 +22,13 @@ #include "InfoLib/TestInfo.h" #include "Tests/FileIO/TestGmlInterface.h" #include "filesystem.h" -#include "gtest/gtest.h" TEST_F(TestGmlInterface, BoostXmlGmlWriterReaderTest) { // Writer test std::string test_data_file = - (fs::temp_directory_path() /= BaseLib::randomString(32) + ".gml").string(); + (fs::temp_directory_path() /= BaseLib::randomString(32) + ".gml") + .string(); GeoLib::IO::BoostXmlGmlInterface xml(geo_objects); xml.export_name = geo_name; diff --git a/Tests/FileIO/TestCsvReader.cpp b/Tests/FileIO/TestCsvReader.cpp index 84d86a38a02bcf737e196086c794d7022c1a0554..44b35aafe2085d8edfe6bb5f9cae279c9878b55e 100644 --- a/Tests/FileIO/TestCsvReader.cpp +++ b/Tests/FileIO/TestCsvReader.cpp @@ -12,14 +12,14 @@ * */ -#include <cstdio> +#include <gtest/gtest.h> -#include "gtest/gtest.h" +#include <cstdio> -#include "filesystem.h" -#include "InfoLib/TestInfo.h" #include "Applications/FileIO/CsvInterface.h" #include "GeoLib/Point.h" +#include "InfoLib/TestInfo.h" +#include "filesystem.h" class CsvInterfaceTest : public ::testing::Test { @@ -27,19 +27,26 @@ public: CsvInterfaceTest() { _file_name = - (fs::temp_directory_path() /= BaseLib::randomString(32) + ".csv").string(); + (fs::temp_directory_path() /= BaseLib::randomString(32) + ".csv") + .string(); std::ofstream out(_file_name); out << "id\tx\ty\tz\tname\tvalue1\tvalue_two\n"; - out << "0\t642015.538\t5724666.445\t391.759\ttest_a\t11.05303121\t436.913\t133\n"; + out << "0\t642015.538\t5724666.445\t391.759\ttest_a\t11.05303121\t436." + "913\t133\n"; out << "1\t642015.49\t724667.426\t391.85\ttest_b\t51.65503659\n"; out << "2\t642015.379\t5724668.424\t391.914\ttest_c\t437.068\t135\t2\n"; - out << "3\t642015.318\t5724669.411\t392.033\ttest_d\t51.65505447\t11.05302923\n"; - out << "4\t642015.275\t5724670.403\t392.172\ttest_e\t437.326\t137\t392.172\n"; + out << "3\t642015.318\t5724669.411\t392.033\ttest_d\t51.65505447\t11." + "05302923\n"; + out << "4\t642015.275\t5724670.403\t392.172\ttest_e\t437.326\t137\t392." + "172\n"; out << "5\t642015.288\t5724671.407\t392.232\ttest_f\n"; out << "6\t642015.231\t5724672.403\t392.281\ttest_g\t\t437.435\n"; - out << "7\t642015.232\t5724673.384\t392.385\ttest_h\t11.05302961\t437.539\n"; - out << "8\t642015.153\t5724674.372\t392.428\ttest_i\t51.65509909\t11.05302887\n"; - out << "9\t642015.137\t5724675.377\t392.485\ttest_j\t51.65510812\t11.05302905\n"; + out << "7\t642015.232\t5724673.384\t392.385\ttest_h\t11.05302961\t437." + "539\n"; + out << "8\t642015.153\t5724674.372\t392.428\ttest_i\t51.65509909\t11." + "05302887\n"; + out << "9\t642015.137\t5724675.377\t392.485\ttest_j\t51.65510812\t11." + "05302905\n"; out.close(); } @@ -57,11 +64,12 @@ TEST_F(CsvInterfaceTest, SimpleReadPoints) std::vector<GeoLib::Point*> points2; _result = FileIO::CsvInterface::readPoints(_file_name, '\t', points); ASSERT_EQ(0, _result); - _result = FileIO::CsvInterface::readPoints(_file_name, '\t', points2, "x", "y", "z"); + _result = FileIO::CsvInterface::readPoints(_file_name, '\t', points2, "x", + "y", "z"); ASSERT_EQ(0, _result); ASSERT_TRUE(points.size() == 10); ASSERT_TRUE(points2.size() == 10); - for (std::size_t i=0; i<points.size(); ++i) + for (std::size_t i = 0; i < points.size(); ++i) { ASSERT_TRUE((*points[i])[1] == (*points2[i])[0]); ASSERT_TRUE((*points[i])[2] == (*points2[i])[1]); @@ -80,7 +88,8 @@ TEST_F(CsvInterfaceTest, SimpleReadPoints) TEST_F(CsvInterfaceTest, StringInPointColumn) { std::vector<GeoLib::Point*> points; - _result = FileIO::CsvInterface::readPoints(_file_name, '\t', points, "x", "y", "name"); + _result = FileIO::CsvInterface::readPoints(_file_name, '\t', points, "x", + "y", "name"); ASSERT_EQ(10, _result); ASSERT_TRUE(points.empty()); } @@ -89,11 +98,13 @@ TEST_F(CsvInterfaceTest, StringInPointColumn) TEST_F(CsvInterfaceTest, WrongColumnName) { std::vector<GeoLib::Point*> points; - _result = FileIO::CsvInterface::readPoints(_file_name, '\t', points, "x", "y", "wrong_column_name"); + _result = FileIO::CsvInterface::readPoints(_file_name, '\t', points, "x", + "y", "wrong_column_name"); ASSERT_EQ(-1, _result); ASSERT_TRUE(points.empty()); - _result = FileIO::CsvInterface::readPoints(_file_name, '\t', points, "wrong_column_name", "y", "id"); + _result = FileIO::CsvInterface::readPoints(_file_name, '\t', points, + "wrong_column_name", "y", "id"); ASSERT_EQ(-1, _result); ASSERT_TRUE(points.empty()); } @@ -102,10 +113,12 @@ TEST_F(CsvInterfaceTest, WrongColumnName) TEST_F(CsvInterfaceTest, MissingValues) { std::vector<GeoLib::Point*> points; - _result = FileIO::CsvInterface::readPoints(_file_name, '\t', points, "z", "value1", "value_two"); + _result = FileIO::CsvInterface::readPoints(_file_name, '\t', points, "z", + "value1", "value_two"); ASSERT_EQ(3, _result); ASSERT_EQ(7, points.size()); - ASSERT_NEAR(437.539, (*points[4])[2], std::numeric_limits<double>::epsilon()); + ASSERT_NEAR(437.539, (*points[4])[2], + std::numeric_limits<double>::epsilon()); for (auto p : points) { delete p; @@ -116,7 +129,8 @@ TEST_F(CsvInterfaceTest, MissingValues) TEST_F(CsvInterfaceTest, Points2D) { std::vector<GeoLib::Point*> points; - _result = FileIO::CsvInterface::readPoints(_file_name, '\t', points, "x", "y"); + _result = + FileIO::CsvInterface::readPoints(_file_name, '\t', points, "x", "y"); ASSERT_EQ(0, _result); ASSERT_EQ(10, points.size()); for (auto& point : points) @@ -135,16 +149,19 @@ TEST_F(CsvInterfaceTest, CoordinateOrder) std::vector<GeoLib::Point*> points1; std::vector<GeoLib::Point*> points2; std::vector<GeoLib::Point*> points3; - _result = FileIO::CsvInterface::readPoints(_file_name, '\t', points1, "id", "y", "z"); + _result = FileIO::CsvInterface::readPoints(_file_name, '\t', points1, "id", + "y", "z"); ASSERT_EQ(0, _result); - _result = FileIO::CsvInterface::readPoints(_file_name, '\t', points2, "id", "z", "y"); + _result = FileIO::CsvInterface::readPoints(_file_name, '\t', points2, "id", + "z", "y"); ASSERT_EQ(0, _result); - _result = FileIO::CsvInterface::readPoints(_file_name, '\t', points3, "y", "id", "z"); + _result = FileIO::CsvInterface::readPoints(_file_name, '\t', points3, "y", + "id", "z"); ASSERT_EQ(0, _result); ASSERT_EQ(10, points1.size()); ASSERT_EQ(10, points2.size()); ASSERT_EQ(10, points3.size()); - for (std::size_t i=0; i<points1.size(); ++i) + for (std::size_t i = 0; i < points1.size(); ++i) { ASSERT_EQ((*points1[i])[1], (*points2[i])[2]); ASSERT_EQ((*points1[i])[2], (*points2[i])[1]); @@ -174,13 +191,15 @@ TEST_F(CsvInterfaceTest, GetColumn) FileIO::CsvInterface::getColumnNames(_file_name, '\t'); ASSERT_EQ(7, columns.size()); std::vector<std::string> names; - _result = FileIO::CsvInterface::readColumn<std::string>(_file_name, '\t', names, columns[4]); + _result = FileIO::CsvInterface::readColumn<std::string>(_file_name, '\t', + names, columns[4]); ASSERT_EQ(0, _result); ASSERT_EQ(10, names.size()); ASSERT_EQ("test_j", names[9]); std::vector<double> values; - _result = FileIO::CsvInterface::readColumn<double>(_file_name, '\t', values, columns[6]); + _result = FileIO::CsvInterface::readColumn<double>(_file_name, '\t', values, + columns[6]); ASSERT_EQ(2, _result); ASSERT_EQ(8, values.size()); ASSERT_NEAR(135, values[1], std::numeric_limits<double>::epsilon()); @@ -190,7 +209,8 @@ TEST_F(CsvInterfaceTest, GetColumn) TEST_F(CsvInterfaceTest, NonExistingColumn) { std::vector<double> values; - _result = FileIO::CsvInterface::readColumn<double>(_file_name, '\t', values, "value2"); + _result = FileIO::CsvInterface::readColumn<double>(_file_name, '\t', values, + "value2"); ASSERT_EQ(-1, _result); ASSERT_TRUE(values.empty()); } @@ -199,13 +219,14 @@ TEST_F(CsvInterfaceTest, NonExistingColumn) TEST_F(CsvInterfaceTest, WrongDataType) { std::vector<double> values; - _result = FileIO::CsvInterface::readColumn<double>(_file_name, '\t', values, "name"); + _result = FileIO::CsvInterface::readColumn<double>(_file_name, '\t', values, + "name"); ASSERT_EQ(10, _result); ASSERT_TRUE(values.empty()); std::vector<std::string> names; - _result = FileIO::CsvInterface::readColumn<std::string>(_file_name, '\t', names, "value1"); + _result = FileIO::CsvInterface::readColumn<std::string>(_file_name, '\t', + names, "value1"); ASSERT_EQ(2, _result); ASSERT_EQ(8, names.size()); } - diff --git a/Tests/FileIO/TestCsvWriter.cpp b/Tests/FileIO/TestCsvWriter.cpp index b37d9ed9fa440aabd0fa09bb2201e9762024769a..360a7ca5705fcdb3c6881082b12036f3ce065746 100644 --- a/Tests/FileIO/TestCsvWriter.cpp +++ b/Tests/FileIO/TestCsvWriter.cpp @@ -8,26 +8,26 @@ * */ -#include <cstdio> - -#include "gtest/gtest.h" +#include <gtest/gtest.h> +#include <cstdio> #include <string> #include <vector> -#include "filesystem.h" -#include "InfoLib/TestInfo.h" #include "Applications/FileIO/CsvInterface.h" +#include "InfoLib/TestInfo.h" +#include "filesystem.h" TEST(CsvWriter, WriteReadTest) { std::string const test_file( (fs::temp_directory_path() /= BaseLib::randomString(32)).string()); - std::vector<std::string> str_vec {"Red", "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet" }; - std::vector<int> int_vec { 1, 2, 4, 8, 16, 32, 64 }; + std::vector<std::string> str_vec{"Red", "Orange", "Yellow", "Green", + "Blue", "Indigo", "Violet"}; + std::vector<int> int_vec{1, 2, 4, 8, 16, 32, 64}; std::vector<double> dbl_vec; - std::srand ( static_cast<unsigned>(std::time(nullptr)) ); + std::srand(static_cast<unsigned>(std::time(nullptr))); for (std::size_t i = 0; i < int_vec.size(); ++i) { dbl_vec.push_back(static_cast<double>(std::rand()) / RAND_MAX); @@ -35,7 +35,8 @@ TEST(CsvWriter, WriteReadTest) FileIO::CsvInterface csv; bool added; - std::vector<std::string> vec_names { "String Vector", "Int Vector", "Double Vector"}; + std::vector<std::string> vec_names{"String Vector", "Int Vector", + "Double Vector"}; added = csv.addVectorForWriting(vec_names[0], str_vec); ASSERT_TRUE(added); added = csv.addVectorForWriting(vec_names[1], int_vec); @@ -52,34 +53,39 @@ TEST(CsvWriter, WriteReadTest) ASSERT_EQ(1, result); std::vector<std::string> str_result; - result = FileIO::CsvInterface::readColumn<std::string>(test_file, '\t', str_result, vec_names[0]); + result = FileIO::CsvInterface::readColumn<std::string>( + test_file, '\t', str_result, vec_names[0]); ASSERT_EQ(0, result); ASSERT_EQ(str_vec.size(), str_result.size()); std::vector<int> idx_result; - result = FileIO::CsvInterface::readColumn<int>(test_file, '\t', idx_result, "Index"); + result = FileIO::CsvInterface::readColumn<int>(test_file, '\t', idx_result, + "Index"); ASSERT_EQ(0, result); ASSERT_EQ(dbl_vec.size(), idx_result.size()); std::vector<int> int_result; - result = FileIO::CsvInterface::readColumn<int>(test_file, '\t', int_result, vec_names[1]); + result = FileIO::CsvInterface::readColumn<int>(test_file, '\t', int_result, + vec_names[1]); ASSERT_EQ(0, result); - // testing for vector length -1 because it had increased previously when testing size requirements - ASSERT_EQ(int_vec.size()-1, int_result.size()); + // testing for vector length -1 because it had increased previously when + // testing size requirements + ASSERT_EQ(int_vec.size() - 1, int_result.size()); std::vector<double> dbl_result; - result = FileIO::CsvInterface::readColumn<double>(test_file, '\t', dbl_result, vec_names[2]); + result = FileIO::CsvInterface::readColumn<double>(test_file, '\t', + dbl_result, vec_names[2]); ASSERT_EQ(0, result); ASSERT_EQ(dbl_vec.size(), dbl_result.size()); - for (std::size_t i=0; i<str_vec.size(); ++i) + for (std::size_t i = 0; i < str_vec.size(); ++i) { ASSERT_EQ(str_vec[i], str_result[i]); ASSERT_EQ(int_vec[i], int_result[i]); - ASSERT_NEAR(dbl_vec[i], dbl_result[i], 10 * std::numeric_limits<double>::epsilon()); + ASSERT_NEAR(dbl_vec[i], dbl_result[i], + 10 * std::numeric_limits<double>::epsilon()); ASSERT_EQ(static_cast<int>(i), idx_result[i]); } std::remove(test_file.c_str()); } - diff --git a/Tests/FileIO/TestGmlInterface.h b/Tests/FileIO/TestGmlInterface.h index 15a3a1b05f7f79f74c3a81d5c7a68a451818a66d..66e419bb79e4e37fd51f2305f1c3b717ee5a9d2c 100644 --- a/Tests/FileIO/TestGmlInterface.h +++ b/Tests/FileIO/TestGmlInterface.h @@ -12,9 +12,9 @@ * */ -#include <cstdio> +#include <gtest/gtest.h> -#include "gtest/gtest.h" +#include <cstdio> #include "GeoLib/GEOObjects.h" #include "GeoLib/Polyline.h" diff --git a/Tests/FileIO/TestGmsInterface.cpp b/Tests/FileIO/TestGmsInterface.cpp index e1483a71d129d9d3feaf2f222af8ce637416c3eb..1af5125114fd2c81495b20f4a5dcc4188a87b359 100644 --- a/Tests/FileIO/TestGmsInterface.cpp +++ b/Tests/FileIO/TestGmsInterface.cpp @@ -8,19 +8,21 @@ * */ -#include <memory> +#include <gtest/gtest.h> -#include "gtest/gtest.h" +#include <memory> -#include "InfoLib/TestInfo.h" #include "Applications/FileIO/GMSInterface.h" +#include "InfoLib/TestInfo.h" #include "MeshLib/Mesh.h" #include "MeshLib/MeshInformation.h" TEST(FileIO, TestGmsInterface) { - std::string const file_name (TestInfoLib::TestInfo::data_path + "/FileIO/3DMeshData.3dm"); - std::unique_ptr<MeshLib::Mesh> mesh (FileIO::GMSInterface::readGMS3DMMesh(file_name)); + std::string const file_name(TestInfoLib::TestInfo::data_path + + "/FileIO/3DMeshData.3dm"); + std::unique_ptr<MeshLib::Mesh> mesh( + FileIO::GMSInterface::readGMS3DMMesh(file_name)); ASSERT_TRUE(mesh != nullptr); ASSERT_EQ(11795, mesh->getNumberOfNodes()); ASSERT_EQ(19885, mesh->getNumberOfElements()); @@ -36,4 +38,3 @@ TEST(FileIO, TestGmsInterface) ASSERT_EQ(1, bounds->first); ASSERT_EQ(63, bounds->second); } - diff --git a/Tests/FileIO/TestTetGenInterface.cpp b/Tests/FileIO/TestTetGenInterface.cpp index 68923fb0fd460e1bcc0c86c79a83024e52a9b5ff..97a460a6f41a4b24949c93fc1ad18c587291f117 100644 --- a/Tests/FileIO/TestTetGenInterface.cpp +++ b/Tests/FileIO/TestTetGenInterface.cpp @@ -12,35 +12,37 @@ * */ +#include <gtest/gtest.h> + #include <limits> -#include <vector> #include <memory> +#include <vector> -#include "gtest/gtest.h" - -#include "filesystem.h" #include "Applications/FileIO/TetGenInterface.h" #include "BaseLib/StringTools.h" +#include "GeoLib/GEOObjects.h" #include "InfoLib/TestInfo.h" #include "MeshLib/IO/readMeshFromFile.h" -#include "GeoLib/GEOObjects.h" #include "MeshLib/Mesh.h" -#include "MeshLib/Node.h" #include "MeshLib/MeshInformation.h" +#include "MeshLib/Node.h" +#include "filesystem.h" // read TetGen geometry TEST(FileIO, TetGenSmeshReader) { - std::string const file_name( - TestInfoLib::TestInfo::data_path + "/FileIO/twolayermdl.smesh"); + std::string const file_name(TestInfoLib::TestInfo::data_path + + "/FileIO/twolayermdl.smesh"); GeoLib::GEOObjects geo_objects; FileIO::TetGenInterface tgi; - bool const result (tgi.readTetGenGeometry(file_name, geo_objects)); + bool const result(tgi.readTetGenGeometry(file_name, geo_objects)); ASSERT_TRUE(result); - std::vector<GeoLib::Point*> const& pnts (*geo_objects.getPointVec("twolayermdl")); + std::vector<GeoLib::Point*> const& pnts( + *geo_objects.getPointVec("twolayermdl")); ASSERT_EQ(744, pnts.size()); - std::vector<GeoLib::Surface*> const& sfcs (*geo_objects.getSurfaceVec("twolayermdl")); + std::vector<GeoLib::Surface*> const& sfcs( + *geo_objects.getSurfaceVec("twolayermdl")); ASSERT_EQ(5, sfcs.size()); ASSERT_EQ(468, sfcs[2]->getNumberOfTriangles()); ASSERT_EQ(191, sfcs[3]->getNumberOfTriangles()); @@ -53,32 +55,39 @@ TEST(FileIO, TetGenSmeshInterface) TEST(FileIO, DISABLED_TetGenSmeshInterface) #endif { - std::string const file_name (TestInfoLib::TestInfo::data_path + "/FileIO/AmmerSubsurfaceCoarse.vtu"); - std::unique_ptr<MeshLib::Mesh const> const mesh (MeshLib::IO::readMeshFromFile(file_name)); + std::string const file_name(TestInfoLib::TestInfo::data_path + + "/FileIO/AmmerSubsurfaceCoarse.vtu"); + std::unique_ptr<MeshLib::Mesh const> const mesh( + MeshLib::IO::readMeshFromFile(file_name)); ASSERT_NE(mesh, nullptr); - std::string const tg_new_name (BaseLib::randomString(32)); + std::string const tg_new_name(BaseLib::randomString(32)); std::string const output_name = (fs::temp_directory_path() /= tg_new_name + ".smesh").string(); std::cout << output_name << std::endl; std::vector<MeshLib::Node> attr_pnts; FileIO::TetGenInterface tgi; - bool result (tgi.writeTetGenSmesh(output_name, *mesh, attr_pnts)); + bool result(tgi.writeTetGenSmesh(output_name, *mesh, attr_pnts)); ASSERT_TRUE(result); GeoLib::GEOObjects geo_objects; result = tgi.readTetGenGeometry(output_name, geo_objects); ASSERT_TRUE(result); - std::string const ref_name(TestInfoLib::TestInfo::data_path + "/FileIO/AmmerSubsurfaceCoarse.smesh"); + std::string const ref_name(TestInfoLib::TestInfo::data_path + + "/FileIO/AmmerSubsurfaceCoarse.smesh"); result = tgi.readTetGenGeometry(ref_name, geo_objects); ASSERT_TRUE(result); - std::vector<GeoLib::Point*> const& ref_pnts (*geo_objects.getPointVec("AmmerSubsurfaceCoarse")); - std::vector<GeoLib::Point*> const& new_pnts (*geo_objects.getPointVec(tg_new_name)); + std::vector<GeoLib::Point*> const& ref_pnts( + *geo_objects.getPointVec("AmmerSubsurfaceCoarse")); + std::vector<GeoLib::Point*> const& new_pnts( + *geo_objects.getPointVec(tg_new_name)); ASSERT_EQ(ref_pnts.size(), new_pnts.size()); - std::vector<GeoLib::Surface*> const& ref_sfc (*geo_objects.getSurfaceVec("AmmerSubsurfaceCoarse")); - std::vector<GeoLib::Surface*> const& new_sfc (*geo_objects.getSurfaceVec(tg_new_name)); + std::vector<GeoLib::Surface*> const& ref_sfc( + *geo_objects.getSurfaceVec("AmmerSubsurfaceCoarse")); + std::vector<GeoLib::Surface*> const& new_sfc( + *geo_objects.getSurfaceVec(tg_new_name)); ASSERT_EQ(ref_sfc.size(), new_sfc.size()); for (std::size_t i = 0; i < ref_sfc.size(); ++i) @@ -93,10 +102,13 @@ TEST(FileIO, DISABLED_TetGenSmeshInterface) // TetGen mesh with material array TEST(FileIO, TetGenMeshReaderWithMaterials) { - std::string const node_name (TestInfoLib::TestInfo::data_path + "/FileIO/twolayermdl.node"); - std::string const ele_name (TestInfoLib::TestInfo::data_path + "/FileIO/twolayermdl.ele"); + std::string const node_name(TestInfoLib::TestInfo::data_path + + "/FileIO/twolayermdl.node"); + std::string const ele_name(TestInfoLib::TestInfo::data_path + + "/FileIO/twolayermdl.ele"); FileIO::TetGenInterface tgi; - std::unique_ptr<MeshLib::Mesh> mesh (tgi.readTetGenMesh(node_name, ele_name)); + std::unique_ptr<MeshLib::Mesh> mesh( + tgi.readTetGenMesh(node_name, ele_name)); ASSERT_TRUE(mesh != nullptr); ASSERT_EQ(1378, mesh->getNumberOfNodes()); ASSERT_EQ(5114, mesh->getNumberOfElements()); @@ -112,10 +124,13 @@ TEST(FileIO, TetGenMeshReaderWithMaterials) // TetGen mesh without additional information TEST(FileIO, TetGenMeshReaderWithoutMaterials) { - std::string const node_name (TestInfoLib::TestInfo::data_path + "/FileIO/tetgen_example.node"); - std::string const ele_name (TestInfoLib::TestInfo::data_path + "/FileIO/tetgen_example.ele"); + std::string const node_name(TestInfoLib::TestInfo::data_path + + "/FileIO/tetgen_example.node"); + std::string const ele_name(TestInfoLib::TestInfo::data_path + + "/FileIO/tetgen_example.ele"); FileIO::TetGenInterface tgi; - std::unique_ptr<MeshLib::Mesh> mesh (tgi.readTetGenMesh(node_name, ele_name)); + std::unique_ptr<MeshLib::Mesh> mesh( + tgi.readTetGenMesh(node_name, ele_name)); ASSERT_TRUE(mesh != nullptr); ASSERT_EQ(202, mesh->getNumberOfNodes()); ASSERT_EQ(650, mesh->getNumberOfElements()); diff --git a/Tests/FileIO_Qt/TestFEFLOWInterface.cpp b/Tests/FileIO_Qt/TestFEFLOWInterface.cpp index 03dfaab2705ee184dabbfd902c2f5188d6876d69..87d6ef2c0d5813df54a3b3de31a9e08041f75093 100644 --- a/Tests/FileIO_Qt/TestFEFLOWInterface.cpp +++ b/Tests/FileIO_Qt/TestFEFLOWInterface.cpp @@ -8,31 +8,32 @@ * */ +#include <gtest/gtest.h> + #include <memory> #include <string> -#include <gtest/gtest.h> - +#include "Applications/FileIO/FEFLOW/FEFLOWMeshInterface.h" #include "InfoLib/TestInfo.h" - #include "MeshLib/Elements/Element.h" #include "MeshLib/Mesh.h" #include "MeshLib/Properties.h" -#include "Applications/FileIO/FEFLOW/FEFLOWMeshInterface.h" - TEST(FileIO, TestFEFLOWMeshInterface) { - std::string const file_name (TestInfoLib::TestInfo::data_path + "/FileIO/small_cube_hex.fem"); + std::string const file_name(TestInfoLib::TestInfo::data_path + + "/FileIO/small_cube_hex.fem"); FileIO::FEFLOWMeshInterface feflowIO; - std::unique_ptr<MeshLib::Mesh const> mesh(feflowIO.readFEFLOWFile(file_name)); + std::unique_ptr<MeshLib::Mesh const> mesh( + feflowIO.readFEFLOWFile(file_name)); ASSERT_TRUE(static_cast<bool>(mesh)); ASSERT_EQ(144u, mesh->getNumberOfNodes()); ASSERT_EQ(75u, mesh->getNumberOfElements()); - auto opt_material_ids(mesh->getProperties().getPropertyVector<int>("MaterialIDs")); + auto opt_material_ids( + mesh->getProperties().getPropertyVector<int>("MaterialIDs")); ASSERT_TRUE(static_cast<bool>(opt_material_ids)); ASSERT_EQ(75u, opt_material_ids->size()); @@ -42,22 +43,20 @@ TEST(FileIO, TestFEFLOWMeshInterface) ASSERT_EQ(0, (*opt_material_ids)[6]); } - TEST(FileIO, TestFEFLOWReadHexMesh) { std::string const fname(TestInfoLib::TestInfo::data_path + "/FileIO/FEFLOW/hex.fem"); FileIO::FEFLOWMeshInterface feflowIO; - std::unique_ptr<MeshLib::Mesh const> mesh( - feflowIO.readFEFLOWFile(fname)); - - EXPECT_EQ(12, mesh->getNumberOfNodes()); - EXPECT_EQ(2, mesh->getNumberOfElements()); - for (std::size_t k(0); k < mesh->getNumberOfElements(); ++k) - { - EXPECT_EQ(MeshLib::MeshElemType::HEXAHEDRON, - mesh->getElement(k)->getGeomType()); - } + std::unique_ptr<MeshLib::Mesh const> mesh(feflowIO.readFEFLOWFile(fname)); + + EXPECT_EQ(12, mesh->getNumberOfNodes()); + EXPECT_EQ(2, mesh->getNumberOfElements()); + for (std::size_t k(0); k < mesh->getNumberOfElements(); ++k) + { + EXPECT_EQ(MeshLib::MeshElemType::HEXAHEDRON, + mesh->getElement(k)->getGeomType()); + } } TEST(FileIO, TestFEFLOWReadPrismMesh) @@ -65,16 +64,15 @@ TEST(FileIO, TestFEFLOWReadPrismMesh) std::string const fname(TestInfoLib::TestInfo::data_path + "/FileIO/FEFLOW/prism.fem"); FileIO::FEFLOWMeshInterface feflowIO; - std::unique_ptr<MeshLib::Mesh const> mesh( - feflowIO.readFEFLOWFile(fname)); - - EXPECT_EQ(12, mesh->getNumberOfNodes()); - EXPECT_EQ(4, mesh->getNumberOfElements()); - for (std::size_t k(0); k < mesh->getNumberOfElements(); ++k) - { - EXPECT_EQ(MeshLib::MeshElemType::PRISM, - mesh->getElement(k)->getGeomType()); - } + std::unique_ptr<MeshLib::Mesh const> mesh(feflowIO.readFEFLOWFile(fname)); + + EXPECT_EQ(12, mesh->getNumberOfNodes()); + EXPECT_EQ(4, mesh->getNumberOfElements()); + for (std::size_t k(0); k < mesh->getNumberOfElements(); ++k) + { + EXPECT_EQ(MeshLib::MeshElemType::PRISM, + mesh->getElement(k)->getGeomType()); + } } TEST(FileIO, TestFEFLOWReadHexPrismMesh) @@ -82,18 +80,17 @@ TEST(FileIO, TestFEFLOWReadHexPrismMesh) std::string const fname(TestInfoLib::TestInfo::data_path + "/FileIO/FEFLOW/hex_prism.fem"); FileIO::FEFLOWMeshInterface feflowIO; - std::unique_ptr<MeshLib::Mesh const> mesh( - feflowIO.readFEFLOWFile(fname)); - - EXPECT_EQ(12, mesh->getNumberOfNodes()); - EXPECT_EQ(3, mesh->getNumberOfElements()); - for (std::size_t k(0); k < 2; ++k) - { - EXPECT_EQ(MeshLib::MeshElemType::PRISM, - mesh->getElement(k)->getGeomType()); - } - EXPECT_EQ(MeshLib::MeshElemType::HEXAHEDRON, - mesh->getElement(2)->getGeomType()); + std::unique_ptr<MeshLib::Mesh const> mesh(feflowIO.readFEFLOWFile(fname)); + + EXPECT_EQ(12, mesh->getNumberOfNodes()); + EXPECT_EQ(3, mesh->getNumberOfElements()); + for (std::size_t k(0); k < 2; ++k) + { + EXPECT_EQ(MeshLib::MeshElemType::PRISM, + mesh->getElement(k)->getGeomType()); + } + EXPECT_EQ(MeshLib::MeshElemType::HEXAHEDRON, + mesh->getElement(2)->getGeomType()); } TEST(FileIO, TestFEFLOWReadTetMesh) @@ -101,16 +98,15 @@ TEST(FileIO, TestFEFLOWReadTetMesh) std::string const fname(TestInfoLib::TestInfo::data_path + "/FileIO/FEFLOW/tet.fem"); FileIO::FEFLOWMeshInterface feflowIO; - std::unique_ptr<MeshLib::Mesh const> mesh( - feflowIO.readFEFLOWFile(fname)); - - EXPECT_EQ(13, mesh->getNumberOfNodes()); - EXPECT_EQ(22, mesh->getNumberOfElements()); - for (std::size_t k(0); k < mesh->getNumberOfElements(); ++k) - { - EXPECT_EQ(MeshLib::MeshElemType::TETRAHEDRON, - mesh->getElement(k)->getGeomType()); - } + std::unique_ptr<MeshLib::Mesh const> mesh(feflowIO.readFEFLOWFile(fname)); + + EXPECT_EQ(13, mesh->getNumberOfNodes()); + EXPECT_EQ(22, mesh->getNumberOfElements()); + for (std::size_t k(0); k < mesh->getNumberOfElements(); ++k) + { + EXPECT_EQ(MeshLib::MeshElemType::TETRAHEDRON, + mesh->getElement(k)->getGeomType()); + } } TEST(FileIO, TestFEFLOWReadPrismTetMesh) @@ -118,19 +114,18 @@ TEST(FileIO, TestFEFLOWReadPrismTetMesh) std::string const fname(TestInfoLib::TestInfo::data_path + "/FileIO/FEFLOW/prism_tet.fem"); FileIO::FEFLOWMeshInterface feflowIO; - std::unique_ptr<MeshLib::Mesh const> mesh( - feflowIO.readFEFLOWFile(fname)); - - EXPECT_EQ(16, mesh->getNumberOfNodes()); - EXPECT_EQ(20, mesh->getNumberOfElements()); - for (std::size_t k(0); k < 4; ++k) - { - EXPECT_EQ(MeshLib::MeshElemType::PRISM, - mesh->getElement(k)->getGeomType()); - } - for (std::size_t k(4); k < mesh->getNumberOfElements(); ++k) - { - EXPECT_EQ(MeshLib::MeshElemType::TETRAHEDRON, - mesh->getElement(k)->getGeomType()); - } + std::unique_ptr<MeshLib::Mesh const> mesh(feflowIO.readFEFLOWFile(fname)); + + EXPECT_EQ(16, mesh->getNumberOfNodes()); + EXPECT_EQ(20, mesh->getNumberOfElements()); + for (std::size_t k(0); k < 4; ++k) + { + EXPECT_EQ(MeshLib::MeshElemType::PRISM, + mesh->getElement(k)->getGeomType()); + } + for (std::size_t k(4); k < mesh->getNumberOfElements(); ++k) + { + EXPECT_EQ(MeshLib::MeshElemType::TETRAHEDRON, + mesh->getElement(k)->getGeomType()); + } } diff --git a/Tests/FileIO_Qt/TestQtGmlInterface.cpp b/Tests/FileIO_Qt/TestQtGmlInterface.cpp index e45f337faf8a6ff354379d18ffd81815d752f603..70a9afaa1ff69f72ceb082a3fbbf7bd72f5ab46b 100644 --- a/Tests/FileIO_Qt/TestQtGmlInterface.cpp +++ b/Tests/FileIO_Qt/TestQtGmlInterface.cpp @@ -12,6 +12,8 @@ * */ +#include <gtest/gtest.h> + #include <cstdio> #include "BaseLib/StringTools.h" @@ -20,7 +22,6 @@ #include "InfoLib/TestInfo.h" #include "Tests/FileIO/TestGmlInterface.h" #include "filesystem.h" -#include "gtest/gtest.h" TEST_F(TestGmlInterface, QtXmlGmlWriterReaderTest) { diff --git a/Tests/FileIO_Qt/TestQtPrjInterface.cpp b/Tests/FileIO_Qt/TestQtPrjInterface.cpp index 0808fa9e899fed2045f18ac615461d9539e67c12..158c569f0bfeca1ed5f185e134eefc3a44671206 100644 --- a/Tests/FileIO_Qt/TestQtPrjInterface.cpp +++ b/Tests/FileIO_Qt/TestQtPrjInterface.cpp @@ -8,16 +8,16 @@ * */ -#include <cstdio> +#include <gtest/gtest.h> -#include "gtest/gtest.h" +#include <cstdio> #include "Applications/DataHolderLib/BoundaryCondition.h" #include "Applications/DataHolderLib/Project.h" #include "Applications/DataHolderLib/SourceTerm.h" #include "Applications/FileIO/XmlIO/Qt/XmlPrjInterface.h" -#include "InfoLib/TestInfo.h" #include "GeoLib/GEOObjects.h" +#include "InfoLib/TestInfo.h" TEST(TestQtPrjInterface, QtXmlPrjReader) { @@ -36,8 +36,9 @@ TEST(TestQtPrjInterface, QtXmlPrjReader) TestInfoLib::TestInfo::data_path + "/Elliptic/nonuniform_bc_SteadyStateDiffusion/neumann_nonuniform.prj"; test_files.push_back({name, 0, 3, 2, 0}); - name = TestInfoLib::TestInfo::data_path + - "/Elliptic/nonuniform_bc_SteadyStateDiffusion/neumann_nonuniform.prj"; + name = + TestInfoLib::TestInfo::data_path + + "/Elliptic/nonuniform_bc_SteadyStateDiffusion/neumann_nonuniform.prj"; test_files.push_back({name, 0, 3, 2, 0}); for (auto& test_file : test_files) diff --git a/Tests/FileIO_Qt/TestVtkRaster.cpp b/Tests/FileIO_Qt/TestVtkRaster.cpp index 4ea9aead66fe93d023d5b4f20f6ffd7615a2f4b4..665254937fd25fa5c905829d0cfb4c7de68e0454 100644 --- a/Tests/FileIO_Qt/TestVtkRaster.cpp +++ b/Tests/FileIO_Qt/TestVtkRaster.cpp @@ -8,23 +8,23 @@ * */ -#include <memory> - -#include "gtest/gtest.h" - +#include <gtest/gtest.h> #include <vtkImageAlgorithm.h> #include <vtkImageData.h> #include <vtkPNGReader.h> #include <vtkSmartPointer.h> +#include <memory> + #include "Applications/DataExplorer/VtkVis/VtkRaster.h" #include "Applications/FileIO/AsciiRasterInterface.h" -#include "InfoLib/TestInfo.h" #include "GeoLib/Raster.h" +#include "InfoLib/TestInfo.h" TEST(TestVtkRaster, TestPNGReader) { - std::string name = TestInfoLib::TestInfo::data_path + "/FileIO/testraster.png"; + std::string name = + TestInfoLib::TestInfo::data_path + "/FileIO/testraster.png"; double x0; double y0; double delta; @@ -51,8 +51,8 @@ TEST(TestVtkRaster, TestPNGReader) TEST(TestVtkRaster, TestASCReader) { - std::string name = - TestInfoLib::TestInfo::data_path + "/MeshGeoToolsLib/Hamburg/00-raster.asc"; + std::string name = TestInfoLib::TestInfo::data_path + + "/MeshGeoToolsLib/Hamburg/00-raster.asc"; double x0; double y0; double delta; @@ -60,7 +60,8 @@ TEST(TestVtkRaster, TestASCReader) img->Update(); EXPECT_TRUE(img != nullptr); EXPECT_TRUE(img->GetOutput() != nullptr); - std::unique_ptr<GeoLib::Raster> raster(FileIO::AsciiRasterInterface::getRasterFromASCFile(name)); + std::unique_ptr<GeoLib::Raster> raster( + FileIO::AsciiRasterInterface::getRasterFromASCFile(name)); EXPECT_EQ(298, raster->getHeader().n_cols); EXPECT_EQ(205, raster->getHeader().n_rows); EXPECT_NEAR(25, raster->getHeader().cell_size, diff --git a/Tests/FileIO_SWMM/TestSwmmInterface.cpp b/Tests/FileIO_SWMM/TestSwmmInterface.cpp index 668f2aaed8d5526096df10085242692f8e8ad98e..1b5269f1020cdba4b6e891b2168d638ff93a3196 100644 --- a/Tests/FileIO_SWMM/TestSwmmInterface.cpp +++ b/Tests/FileIO_SWMM/TestSwmmInterface.cpp @@ -8,62 +8,70 @@ * */ -#include <memory> +#include <gtest/gtest.h> -#include "gtest/gtest.h" +#include <memory> -#include "InfoLib/TestInfo.h" #include "Applications/FileIO/SWMM/SwmmInterface.h" #include "GeoLib/GeoObjects.h" +#include "InfoLib/TestInfo.h" #include "MeshLib/Mesh.h" #include "MeshLib/MeshInformation.h" TEST(FileIO, TestSwmmInterface) { - std::string const base_name ("swmm_input_example"); - std::string const file_name (TestInfoLib::TestInfo::data_path + "/FileIO/" + base_name + ".inp"); + std::string const base_name("swmm_input_example"); + std::string const file_name(TestInfoLib::TestInfo::data_path + "/FileIO/" + + base_name + ".inp"); // testing geo conversion GeoLib::GEOObjects geo_objects; - bool const result = - FileIO::SwmmInterface::convertSwmmInputToGeometry(file_name, geo_objects, true); + bool const result = FileIO::SwmmInterface::convertSwmmInputToGeometry( + file_name, geo_objects, true); ASSERT_TRUE(result); - std::vector<GeoLib::Point*> const*const pnts (geo_objects.getPointVec(base_name)); - std::size_t const n_pnts (259); + std::vector<GeoLib::Point*> const* const pnts( + geo_objects.getPointVec(base_name)); + std::size_t const n_pnts(259); ASSERT_EQ(n_pnts, pnts->size()); - for (std::size_t i=0; i<21; i++) + for (std::size_t i = 0; i < 21; i++) ASSERT_TRUE((*(*pnts)[i])[2] > 0); - for (std::size_t i=21; i<n_pnts; i++) - ASSERT_NEAR(0, (*(*pnts)[i])[2], std::numeric_limits<double>::epsilon()); + for (std::size_t i = 21; i < n_pnts; i++) + ASSERT_NEAR( + 0, (*(*pnts)[i])[2], std::numeric_limits<double>::epsilon()); - std::vector<GeoLib::Polyline*> const*const lines (geo_objects.getPolylineVec(base_name)); - std::size_t n_lines (79); + std::vector<GeoLib::Polyline*> const* const lines( + geo_objects.getPolylineVec(base_name)); + std::size_t n_lines(79); ASSERT_EQ(n_lines, lines->size()); - for (std::size_t i=0; i<58; ++i) - ASSERT_TRUE((*lines)[i]->getNumberOfPoints() > 3 && (*lines)[i]->getNumberOfPoints() < 7); - for (std::size_t i=58; i<n_lines; ++i) + for (std::size_t i = 0; i < 58; ++i) + ASSERT_TRUE((*lines)[i]->getNumberOfPoints() > 3 && + (*lines)[i]->getNumberOfPoints() < 7); + for (std::size_t i = 58; i < n_lines; ++i) ASSERT_TRUE(2 == (*lines)[i]->getNumberOfPoints()); // testing mesh conversion - std::unique_ptr<FileIO::SwmmInterface> swmm = FileIO::SwmmInterface::create(file_name); + std::unique_ptr<FileIO::SwmmInterface> swmm = + FileIO::SwmmInterface::create(file_name); ASSERT_TRUE(swmm != nullptr); - MeshLib::Mesh const& mesh (swmm->getMesh()); - std::size_t const n_nodes (22); - std::size_t const n_elems (21); + MeshLib::Mesh const& mesh(swmm->getMesh()); + std::size_t const n_nodes(22); + std::size_t const n_elems(21); ASSERT_EQ(n_nodes, mesh.getNumberOfNodes()); ASSERT_EQ(n_elems, mesh.getNumberOfElements()); auto const* const depth = mesh.getProperties().getPropertyVector<double>("Max Depth"); ASSERT_TRUE(n_nodes == depth->size()); - ASSERT_NEAR((*depth)[1], 2*(*depth)[0], std::numeric_limits<double>::epsilon()); - ASSERT_NEAR((*depth)[2], 2*(*depth)[1], std::numeric_limits<double>::epsilon()); - for (std::size_t i=3; i<n_nodes; ++i) + ASSERT_NEAR( + (*depth)[1], 2 * (*depth)[0], std::numeric_limits<double>::epsilon()); + ASSERT_NEAR( + (*depth)[2], 2 * (*depth)[1], std::numeric_limits<double>::epsilon()); + for (std::size_t i = 3; i < n_nodes; ++i) ASSERT_NEAR(0, (*depth)[i], std::numeric_limits<double>::epsilon()); auto const& types = MeshLib::MeshInformation::getNumberOfElementTypes(mesh); @@ -75,7 +83,6 @@ TEST(FileIO, TestSwmmInterface) ASSERT_EQ(0, bounds->first); ASSERT_EQ(0, bounds->second); - ASSERT_NEAR(186.06, mesh.getMinEdgeLength(), 0.01); + ASSERT_NEAR(186.06, mesh.getMinEdgeLength(), 0.01); ASSERT_NEAR(3171.42, mesh.getMaxEdgeLength(), 0.01); } - diff --git a/Tests/GeoLib/AutoCheckGenerators.cpp b/Tests/GeoLib/AutoCheckGenerators.cpp index 08d4bcf09a054db5b03b01ed926330d952775531..3a4949c80f84da1583d5a15573289527ffbe3cd2 100644 --- a/Tests/GeoLib/AutoCheckGenerators.cpp +++ b/Tests/GeoLib/AutoCheckGenerators.cpp @@ -11,7 +11,6 @@ namespace autocheck { - // reflect point p on the point c in x-y plane MathLib::Point3d reflect(MathLib::Point3d const& c, MathLib::Point3d const& p) { diff --git a/Tests/GeoLib/AutoCheckGenerators.h b/Tests/GeoLib/AutoCheckGenerators.h index 31ce490c78db22f47759691fe0f42ce6ede622a9..352b0d486ecffbd0d129e6e74b568c15584753cf 100644 --- a/Tests/GeoLib/AutoCheckGenerators.h +++ b/Tests/GeoLib/AutoCheckGenerators.h @@ -9,14 +9,14 @@ #pragma once +#include <autocheck/autocheck.hpp> #include <cmath> #include <memory> #include <random> #include <utility> -#include "autocheck/autocheck.hpp" -#include "MathLib/Point3d.h" #include "GeoLib/LineSegment.h" +#include "MathLib/Point3d.h" namespace autocheck { diff --git a/Tests/GeoLib/CreateTestPoints.cpp b/Tests/GeoLib/CreateTestPoints.cpp index 1bea008259172956ef0193506e8c1134c45dd200..35b37592ec87574b073b2fca8e220842c9c4a71f 100644 --- a/Tests/GeoLib/CreateTestPoints.cpp +++ b/Tests/GeoLib/CreateTestPoints.cpp @@ -7,12 +7,12 @@ * http://www.opengeosys.org/project/license */ +#include "CreateTestPoints.h" + #include <map> #include <memory> #include <vector> -#include "CreateTestPoints.h" - void createSetOfTestPointsAndAssociatedNames(GeoLib::GEOObjects& geo_objs, std::string& name, std::size_t const pnts_per_edge, @@ -42,4 +42,3 @@ void createSetOfTestPointsAndAssociatedNames(GeoLib::GEOObjects& geo_objs, geo_objs.addPointVec(std::move(pnts), name, std::move(pnt_name_map)); } - diff --git a/Tests/GeoLib/IO/TestGLIReader.cpp b/Tests/GeoLib/IO/TestGLIReader.cpp index 5df5fe737760205d7a4586a5c37bf55299931f11..5930a73b3985e158ef4ac4838d97aef201f42e63 100644 --- a/Tests/GeoLib/IO/TestGLIReader.cpp +++ b/Tests/GeoLib/IO/TestGLIReader.cpp @@ -10,6 +10,8 @@ * */ +#include <gtest/gtest.h> + #include <cstdio> #include <fstream> @@ -18,14 +20,14 @@ #include "GeoLib/GEOObjects.h" #include "InfoLib/TestInfo.h" #include "filesystem.h" -#include "gtest/gtest.h" class OGSIOVer4InterfaceTest : public ::testing::Test { public: OGSIOVer4InterfaceTest() : _test_path(fs::temp_directory_path() /= BaseLib::randomString(32)), - _gli_fname(_test_path), _surface_fname(_test_path) + _gli_fname(_test_path), + _surface_fname(_test_path) { fs::create_directory(_test_path); std::ofstream gli_out(_gli_fname /= "test.gli"); @@ -51,7 +53,7 @@ protected: TEST_F(OGSIOVer4InterfaceTest, SimpleTIN) { - std::ofstream tin_out (_surface_fname); + std::ofstream tin_out(_surface_fname); tin_out << "0 0.0 0.0 0.0 1.0 0.0.0 0.0 0.0 1.0\n"; tin_out << "1 0.0 0.0 0.0 1.0 0.0.0 0.0 1.0 1.0\n"; tin_out.close(); @@ -60,19 +62,21 @@ TEST_F(OGSIOVer4InterfaceTest, SimpleTIN) GeoLib::GEOObjects geometries; std::vector<std::string> errors; std::string geometry_name("TestGeometry"); - FileIO::Legacy::readGLIFileV4(_gli_fname.string(), geometries, geometry_name, - errors, "dummy_for_gmsh_path"); + FileIO::Legacy::readGLIFileV4(_gli_fname.string(), geometries, + geometry_name, errors, "dummy_for_gmsh_path"); - std::vector<GeoLib::Surface*> const* - sfcs(geometries.getSurfaceVec(geometry_name)); + std::vector<GeoLib::Surface*> const* sfcs( + geometries.getSurfaceVec(geometry_name)); ASSERT_TRUE(sfcs != nullptr); ASSERT_EQ(1u, geometries.getSurfaceVec(geometry_name)->size()); - ASSERT_EQ(2u, (*geometries.getSurfaceVec(geometry_name))[0]->getNumberOfTriangles()); + ASSERT_EQ( + 2u, + (*geometries.getSurfaceVec(geometry_name))[0]->getNumberOfTriangles()); } TEST_F(OGSIOVer4InterfaceTest, StillCorrectTINWihtAdditionalValueAtEndOfLine) { - std::ofstream tin_out (_surface_fname); + std::ofstream tin_out(_surface_fname); tin_out << "0 0.0 0.0 0.0 1.0 0.0.0 0.0 0.0 1.0 10\n"; tin_out << "1 0.0 0.0 0.0 1.0 0.0.0 0.0 0.0 1.0\n"; tin_out.close(); @@ -81,19 +85,21 @@ TEST_F(OGSIOVer4InterfaceTest, StillCorrectTINWihtAdditionalValueAtEndOfLine) GeoLib::GEOObjects geometries; std::vector<std::string> errors; std::string geometry_name("TestGeometry"); - FileIO::Legacy::readGLIFileV4(_gli_fname.string(), geometries, geometry_name, - errors, "dummy_for_gmsh_path"); + FileIO::Legacy::readGLIFileV4(_gli_fname.string(), geometries, + geometry_name, errors, "dummy_for_gmsh_path"); - std::vector<GeoLib::Surface*> const* - sfcs(geometries.getSurfaceVec(geometry_name)); + std::vector<GeoLib::Surface*> const* sfcs( + geometries.getSurfaceVec(geometry_name)); ASSERT_TRUE(sfcs != nullptr); ASSERT_EQ(1u, geometries.getSurfaceVec(geometry_name)->size()); - ASSERT_EQ(2u, (*geometries.getSurfaceVec(geometry_name))[0]->getNumberOfTriangles()); + ASSERT_EQ( + 2u, + (*geometries.getSurfaceVec(geometry_name))[0]->getNumberOfTriangles()); } TEST_F(OGSIOVer4InterfaceTest, InvalidTIN_ZeroAreaTri) { - std::ofstream tin_out (_surface_fname); + std::ofstream tin_out(_surface_fname); tin_out << "0 0.0 0.0 0.0 1.0 0.0.0 0.0 0.0 0.0\n"; tin_out.close(); @@ -101,18 +107,17 @@ TEST_F(OGSIOVer4InterfaceTest, InvalidTIN_ZeroAreaTri) GeoLib::GEOObjects geometries; std::vector<std::string> errors; std::string geometry_name("TestGeometry"); - FileIO::Legacy::readGLIFileV4(_gli_fname.string(), geometries, geometry_name, - errors, "dummy_for_gmsh_path"); + FileIO::Legacy::readGLIFileV4(_gli_fname.string(), geometries, + geometry_name, errors, "dummy_for_gmsh_path"); - std::vector<GeoLib::Surface*> const* - sfcs(geometries.getSurfaceVec(geometry_name)); + std::vector<GeoLib::Surface*> const* sfcs( + geometries.getSurfaceVec(geometry_name)); ASSERT_TRUE(sfcs == nullptr); } - TEST_F(OGSIOVer4InterfaceTest, InvalidTIN_LineDoesNotStartWithID) { - std::ofstream tin_out (_surface_fname); + std::ofstream tin_out(_surface_fname); tin_out << "0 0.0 0.0 0.0 1.0 0.0.0 0.0 0.0 1.0\n"; tin_out << "a\n"; tin_out << "1 0.0 0.0 0.0 1.0 0.0.0 0.0 0.0 1.0\n"; @@ -122,18 +127,17 @@ TEST_F(OGSIOVer4InterfaceTest, InvalidTIN_LineDoesNotStartWithID) GeoLib::GEOObjects geometries; std::vector<std::string> errors; std::string geometry_name("TestGeometry"); - FileIO::Legacy::readGLIFileV4(_gli_fname.string(), geometries, geometry_name, - errors, "dummy_for_gmsh_path"); + FileIO::Legacy::readGLIFileV4(_gli_fname.string(), geometries, + geometry_name, errors, "dummy_for_gmsh_path"); - std::vector<GeoLib::Surface*> const* - sfcs(geometries.getSurfaceVec(geometry_name)); + std::vector<GeoLib::Surface*> const* sfcs( + geometries.getSurfaceVec(geometry_name)); ASSERT_TRUE(sfcs == nullptr); } - TEST_F(OGSIOVer4InterfaceTest, InvalidTIN_PointIsMissing) { - std::ofstream tin_out (_surface_fname); + std::ofstream tin_out(_surface_fname); tin_out << "0 0.0 0.0 0.0 1.0 0.0.0 0.0 0.0 1.0\n"; tin_out << "1 0.0 0.0 0.0 1.0 0.0.0\n"; tin_out.close(); @@ -142,17 +146,17 @@ TEST_F(OGSIOVer4InterfaceTest, InvalidTIN_PointIsMissing) GeoLib::GEOObjects geometries; std::vector<std::string> errors; std::string geometry_name("TestGeometry"); - FileIO::Legacy::readGLIFileV4(_gli_fname.string(), geometries, geometry_name, - errors, "dummy_for_gmsh_path"); + FileIO::Legacy::readGLIFileV4(_gli_fname.string(), geometries, + geometry_name, errors, "dummy_for_gmsh_path"); - std::vector<GeoLib::Surface*> const* - sfcs(geometries.getSurfaceVec(geometry_name)); + std::vector<GeoLib::Surface*> const* sfcs( + geometries.getSurfaceVec(geometry_name)); ASSERT_TRUE(sfcs == nullptr); } TEST_F(OGSIOVer4InterfaceTest, InvalidTIN_CoordOfPointIsMissing) { - std::ofstream tin_out (_surface_fname); + std::ofstream tin_out(_surface_fname); tin_out << "0 0.0 0.0 0.0 1.0 0.0.0 0.0\n"; tin_out << "1 0.0 0.0 0.0 1.0 0.0.0\n"; tin_out.close(); @@ -161,17 +165,17 @@ TEST_F(OGSIOVer4InterfaceTest, InvalidTIN_CoordOfPointIsMissing) GeoLib::GEOObjects geometries; std::vector<std::string> errors; std::string geometry_name("TestGeometry"); - FileIO::Legacy::readGLIFileV4(_gli_fname.string(), geometries, geometry_name, - errors, "dummy_for_gmsh_path"); + FileIO::Legacy::readGLIFileV4(_gli_fname.string(), geometries, + geometry_name, errors, "dummy_for_gmsh_path"); - std::vector<GeoLib::Surface*> const* - sfcs(geometries.getSurfaceVec(geometry_name)); + std::vector<GeoLib::Surface*> const* sfcs( + geometries.getSurfaceVec(geometry_name)); ASSERT_TRUE(sfcs == nullptr); } TEST_F(OGSIOVer4InterfaceTest, SimpleTIN_AdditionalEmptyLinesAtEnd) { - std::ofstream tin_out (_surface_fname); + std::ofstream tin_out(_surface_fname); tin_out << "0 0.0 0.0 0.0 1.0 0.0.0 0.0 0.0 1.0 10\n"; tin_out << "1 0.0 0.0 0.0 1.0 0.0.0 0.0 0.0 1.0\n\n\n"; tin_out.close(); @@ -180,12 +184,14 @@ TEST_F(OGSIOVer4InterfaceTest, SimpleTIN_AdditionalEmptyLinesAtEnd) GeoLib::GEOObjects geometries; std::vector<std::string> errors; std::string geometry_name("TestGeometry"); - FileIO::Legacy::readGLIFileV4(_gli_fname.string(), geometries, geometry_name, - errors, "dummy_for_gmsh_path"); + FileIO::Legacy::readGLIFileV4(_gli_fname.string(), geometries, + geometry_name, errors, "dummy_for_gmsh_path"); - std::vector<GeoLib::Surface*> const* - sfcs(geometries.getSurfaceVec(geometry_name)); + std::vector<GeoLib::Surface*> const* sfcs( + geometries.getSurfaceVec(geometry_name)); ASSERT_TRUE(sfcs != nullptr); ASSERT_EQ(1u, geometries.getSurfaceVec(geometry_name)->size()); - ASSERT_EQ(2u, (*geometries.getSurfaceVec(geometry_name))[0]->getNumberOfTriangles()); + ASSERT_EQ( + 2u, + (*geometries.getSurfaceVec(geometry_name))[0]->getNumberOfTriangles()); } diff --git a/Tests/GeoLib/TestAABB.cpp b/Tests/GeoLib/TestAABB.cpp index bc52a9d5ed80be2a3cb90c5507e25379106fe8c3..e0c522edffcd9e3b15bc82a747b20b6f3b005038 100644 --- a/Tests/GeoLib/TestAABB.cpp +++ b/Tests/GeoLib/TestAABB.cpp @@ -12,13 +12,13 @@ * */ +#include <gtest/gtest.h> + #include <cstdlib> #include <ctime> #include <list> #include <random> -#include "gtest/gtest.h" - #include "GeoLib/AABB.h" #include "GeoLib/Point.h" #include "MathLib/Point3d.h" @@ -26,185 +26,232 @@ TEST(GeoLibAABB, RandomNumberOfPointersToRandomPoints) { /* initialize random seed: */ - srand ( static_cast<unsigned>(time(nullptr)) ); - int n (rand() % 100000); - int box_size (rand()); - double half_box_size(box_size/2); - double minus_half_box_size(-half_box_size); - - // fill list with points - std::list<GeoLib::Point*> pnts_list; - for (int k(0); k<n; k++) { - pnts_list.push_back(new GeoLib::Point(rand() % box_size - half_box_size, rand() % box_size - half_box_size, rand() % box_size - half_box_size)); - } + srand(static_cast<unsigned>(time(nullptr))); + int n(rand() % 100000); + int box_size(rand()); + double half_box_size(box_size / 2); + double minus_half_box_size(-half_box_size); + + // fill list with points + std::list<GeoLib::Point*> pnts_list; + for (int k(0); k < n; k++) + { + pnts_list.push_back( + new GeoLib::Point(rand() % box_size - half_box_size, + rand() % box_size - half_box_size, + rand() % box_size - half_box_size)); + } - // construct from list points a axis aligned bounding box - GeoLib::AABB aabb(pnts_list.begin(), pnts_list.end()); + // construct from list points a axis aligned bounding box + GeoLib::AABB aabb(pnts_list.begin(), pnts_list.end()); - MathLib::Point3d const& min_pnt(aabb.getMinPoint()); - MathLib::Point3d const& max_pnt(aabb.getMaxPoint()); + MathLib::Point3d const& min_pnt(aabb.getMinPoint()); + MathLib::Point3d const& max_pnt(aabb.getMaxPoint()); - ASSERT_LE(minus_half_box_size, min_pnt[0]) << "coordinate 0 of min_pnt is smaller than " << minus_half_box_size; - ASSERT_LE(minus_half_box_size, min_pnt[1]) << "coordinate 1 of min_pnt is smaller than " << minus_half_box_size; - ASSERT_LE(minus_half_box_size, min_pnt[2]) << "coordinate 2 of min_pnt is smaller than " << minus_half_box_size; + ASSERT_LE(minus_half_box_size, min_pnt[0]) + << "coordinate 0 of min_pnt is smaller than " << minus_half_box_size; + ASSERT_LE(minus_half_box_size, min_pnt[1]) + << "coordinate 1 of min_pnt is smaller than " << minus_half_box_size; + ASSERT_LE(minus_half_box_size, min_pnt[2]) + << "coordinate 2 of min_pnt is smaller than " << minus_half_box_size; // since the interval is half-open we have to move the upper bound also - half_box_size = std::nexttoward(half_box_size, std::numeric_limits<double>::max()); - ASSERT_GE(half_box_size, max_pnt[0]) << "coordinate 0 of max_pnt is greater than " << half_box_size; - ASSERT_GE(half_box_size, max_pnt[1]) << "coordinate 1 of max_pnt is greater than " << half_box_size; - ASSERT_GE(half_box_size, max_pnt[2]) << "coordinate 2 of max_pnt is greater than " << half_box_size; - - for (auto& point : pnts_list) - { - delete point; - } + half_box_size = + std::nexttoward(half_box_size, std::numeric_limits<double>::max()); + ASSERT_GE(half_box_size, max_pnt[0]) + << "coordinate 0 of max_pnt is greater than " << half_box_size; + ASSERT_GE(half_box_size, max_pnt[1]) + << "coordinate 1 of max_pnt is greater than " << half_box_size; + ASSERT_GE(half_box_size, max_pnt[2]) + << "coordinate 2 of max_pnt is greater than " << half_box_size; + + for (auto& point : pnts_list) + { + delete point; + } } TEST(GeoLibAABB, RandomNumberOfPointsRandomPointInAList) { /* initialize random seed: */ - srand ( static_cast<unsigned>(time(nullptr)) ); - int n (rand() % 1000000); - int box_size (rand()); - double half_box_size(box_size/2); - double minus_half_box_size(-half_box_size); - - // fill list with points - std::list<GeoLib::Point> pnts_list; - for (int k(0); k<n; k++) { - pnts_list.emplace_back(rand() % box_size - half_box_size, - rand() % box_size - half_box_size, - rand() % box_size - half_box_size); - } - - // construct from list points a axis aligned bounding box - GeoLib::AABB aabb(pnts_list.begin(), pnts_list.end()); - - MathLib::Point3d const& min_pnt(aabb.getMinPoint()); - MathLib::Point3d const& max_pnt(aabb.getMaxPoint()); - - ASSERT_LE(minus_half_box_size, min_pnt[0]) << "coordinate 0 of min_pnt is smaller than " << minus_half_box_size; - ASSERT_LE(minus_half_box_size, min_pnt[1]) << "coordinate 1 of min_pnt is smaller than " << minus_half_box_size; - ASSERT_LE(minus_half_box_size, min_pnt[2]) << "coordinate 2 of min_pnt is smaller than " << minus_half_box_size; + srand(static_cast<unsigned>(time(nullptr))); + int n(rand() % 1000000); + int box_size(rand()); + double half_box_size(box_size / 2); + double minus_half_box_size(-half_box_size); + + // fill list with points + std::list<GeoLib::Point> pnts_list; + for (int k(0); k < n; k++) + { + pnts_list.emplace_back(rand() % box_size - half_box_size, + rand() % box_size - half_box_size, + rand() % box_size - half_box_size); + } + + // construct from list points a axis aligned bounding box + GeoLib::AABB aabb(pnts_list.begin(), pnts_list.end()); + + MathLib::Point3d const& min_pnt(aabb.getMinPoint()); + MathLib::Point3d const& max_pnt(aabb.getMaxPoint()); + + ASSERT_LE(minus_half_box_size, min_pnt[0]) + << "coordinate 0 of min_pnt is smaller than " << minus_half_box_size; + ASSERT_LE(minus_half_box_size, min_pnt[1]) + << "coordinate 1 of min_pnt is smaller than " << minus_half_box_size; + ASSERT_LE(minus_half_box_size, min_pnt[2]) + << "coordinate 2 of min_pnt is smaller than " << minus_half_box_size; // since the interval is half-open we have to move the upper bound also - half_box_size = std::nexttoward(half_box_size, std::numeric_limits<double>::max()); - ASSERT_GE(half_box_size, max_pnt[0]) << "coordinate 0 of max_pnt is greater than " << half_box_size; - ASSERT_GE(half_box_size, max_pnt[1]) << "coordinate 1 of max_pnt is greater than " << half_box_size; - ASSERT_GE(half_box_size, max_pnt[2]) << "coordinate 2 of max_pnt is greater than " << half_box_size; + half_box_size = + std::nexttoward(half_box_size, std::numeric_limits<double>::max()); + ASSERT_GE(half_box_size, max_pnt[0]) + << "coordinate 0 of max_pnt is greater than " << half_box_size; + ASSERT_GE(half_box_size, max_pnt[1]) + << "coordinate 1 of max_pnt is greater than " << half_box_size; + ASSERT_GE(half_box_size, max_pnt[2]) + << "coordinate 2 of max_pnt is greater than " << half_box_size; } TEST(GeoLibAABB, RandomNumberOfPointersToRandomPointsInAVector) { /* initialize random seed: */ - srand ( static_cast<unsigned>(time(nullptr)) ); - int n (rand() % 100000); - int box_size (rand()); - double half_box_size(box_size/2); - double minus_half_box_size(-half_box_size); + srand(static_cast<unsigned>(time(nullptr))); + int n(rand() % 100000); + int box_size(rand()); + double half_box_size(box_size / 2); + double minus_half_box_size(-half_box_size); - // fill list with points - std::vector<GeoLib::Point*> pnts; - for (int k(0); k<n; k++) { - pnts.push_back(new GeoLib::Point(rand() % box_size - half_box_size, rand() % box_size - half_box_size, rand() % box_size - half_box_size)); - } + // fill list with points + std::vector<GeoLib::Point*> pnts; + for (int k(0); k < n; k++) + { + pnts.push_back(new GeoLib::Point(rand() % box_size - half_box_size, + rand() % box_size - half_box_size, + rand() % box_size - half_box_size)); + } - // construct from list points a axis aligned bounding box - GeoLib::AABB aabb(pnts.begin(), pnts.end()); + // construct from list points a axis aligned bounding box + GeoLib::AABB aabb(pnts.begin(), pnts.end()); - MathLib::Point3d const& min_pnt(aabb.getMinPoint()); - MathLib::Point3d const& max_pnt(aabb.getMaxPoint()); + MathLib::Point3d const& min_pnt(aabb.getMinPoint()); + MathLib::Point3d const& max_pnt(aabb.getMaxPoint()); - ASSERT_LE(minus_half_box_size, min_pnt[0]) << "coordinate 0 of min_pnt is smaller than " << minus_half_box_size; - ASSERT_LE(minus_half_box_size, min_pnt[1]) << "coordinate 1 of min_pnt is smaller than " << minus_half_box_size; - ASSERT_LE(minus_half_box_size, min_pnt[2]) << "coordinate 2 of min_pnt is smaller than " << minus_half_box_size; + ASSERT_LE(minus_half_box_size, min_pnt[0]) + << "coordinate 0 of min_pnt is smaller than " << minus_half_box_size; + ASSERT_LE(minus_half_box_size, min_pnt[1]) + << "coordinate 1 of min_pnt is smaller than " << minus_half_box_size; + ASSERT_LE(minus_half_box_size, min_pnt[2]) + << "coordinate 2 of min_pnt is smaller than " << minus_half_box_size; // since the interval is half-open we have to move the upper bound also - half_box_size = std::nexttoward(half_box_size, std::numeric_limits<double>::max()); - ASSERT_GE(half_box_size, max_pnt[0]) << "coordinate 0 of max_pnt is greater than " << half_box_size; - ASSERT_GE(half_box_size, max_pnt[1]) << "coordinate 1 of max_pnt is greater than " << half_box_size; - ASSERT_GE(half_box_size, max_pnt[2]) << "coordinate 2 of max_pnt is greater than " << half_box_size; - - for (auto& point : pnts) - { - delete point; - } + half_box_size = + std::nexttoward(half_box_size, std::numeric_limits<double>::max()); + ASSERT_GE(half_box_size, max_pnt[0]) + << "coordinate 0 of max_pnt is greater than " << half_box_size; + ASSERT_GE(half_box_size, max_pnt[1]) + << "coordinate 1 of max_pnt is greater than " << half_box_size; + ASSERT_GE(half_box_size, max_pnt[2]) + << "coordinate 2 of max_pnt is greater than " << half_box_size; + + for (auto& point : pnts) + { + delete point; + } } TEST(GeoLibAABB, RandomNumberOfPointsRandomPointInAVector) { /* initialize random seed: */ - srand ( static_cast<unsigned>(time(nullptr)) ); - int n (rand() % 1000000); - int box_size (rand()); - double half_box_size(box_size/2); - double minus_half_box_size(-half_box_size); - - // fill list with points - std::list<GeoLib::Point> pnts; - for (int k(0); k<n; k++) { - pnts.emplace_back(rand() % box_size - half_box_size, - rand() % box_size - half_box_size, - rand() % box_size - half_box_size); - } - - // construct from list points a axis aligned bounding box - GeoLib::AABB aabb(pnts.begin(), pnts.end()); - - MathLib::Point3d const& min_pnt(aabb.getMinPoint()); - MathLib::Point3d const& max_pnt(aabb.getMaxPoint()); - - ASSERT_LE(minus_half_box_size, min_pnt[0]) << "coordinate 0 of min_pnt is smaller than " << minus_half_box_size; - ASSERT_LE(minus_half_box_size, min_pnt[1]) << "coordinate 1 of min_pnt is smaller than " << minus_half_box_size; - ASSERT_LE(minus_half_box_size, min_pnt[2]) << "coordinate 2 of min_pnt is smaller than " << minus_half_box_size; + srand(static_cast<unsigned>(time(nullptr))); + int n(rand() % 1000000); + int box_size(rand()); + double half_box_size(box_size / 2); + double minus_half_box_size(-half_box_size); + + // fill list with points + std::list<GeoLib::Point> pnts; + for (int k(0); k < n; k++) + { + pnts.emplace_back(rand() % box_size - half_box_size, + rand() % box_size - half_box_size, + rand() % box_size - half_box_size); + } + + // construct from list points a axis aligned bounding box + GeoLib::AABB aabb(pnts.begin(), pnts.end()); + + MathLib::Point3d const& min_pnt(aabb.getMinPoint()); + MathLib::Point3d const& max_pnt(aabb.getMaxPoint()); + + ASSERT_LE(minus_half_box_size, min_pnt[0]) + << "coordinate 0 of min_pnt is smaller than " << minus_half_box_size; + ASSERT_LE(minus_half_box_size, min_pnt[1]) + << "coordinate 1 of min_pnt is smaller than " << minus_half_box_size; + ASSERT_LE(minus_half_box_size, min_pnt[2]) + << "coordinate 2 of min_pnt is smaller than " << minus_half_box_size; // since the interval is half-open we have to move the upper bound also - half_box_size = std::nexttoward(half_box_size, std::numeric_limits<double>::max()); - ASSERT_GE(half_box_size, max_pnt[0]) << "coordinate 0 of max_pnt is greater than " << half_box_size; - ASSERT_GE(half_box_size, max_pnt[1]) << "coordinate 1 of max_pnt is greater than " << half_box_size; - ASSERT_GE(half_box_size, max_pnt[2]) << "coordinate 2 of max_pnt is greater than " << half_box_size; + half_box_size = + std::nexttoward(half_box_size, std::numeric_limits<double>::max()); + ASSERT_GE(half_box_size, max_pnt[0]) + << "coordinate 0 of max_pnt is greater than " << half_box_size; + ASSERT_GE(half_box_size, max_pnt[1]) + << "coordinate 1 of max_pnt is greater than " << half_box_size; + ASSERT_GE(half_box_size, max_pnt[2]) + << "coordinate 2 of max_pnt is greater than " << half_box_size; } TEST(GeoLibAABB, RandomNumberOfPointsRandomBox) { /* initialize random seed: */ - srand (static_cast<unsigned>(time(nullptr))); - int n (rand() % 1000000); - int box_size_x (rand()); - int box_size_y (rand()); - int box_size_z (rand()); - double half_box_size_x(box_size_x/2); - double half_box_size_y(box_size_y/2); - double half_box_size_z(box_size_z/2); - auto minus_half_box_size_x(static_cast<int>(-half_box_size_x)); - auto minus_half_box_size_y(static_cast<int>(-half_box_size_y)); - auto minus_half_box_size_z(static_cast<int>(-half_box_size_z)); - - // fill list with points - std::list<GeoLib::Point> pnts; - for (int k(0); k<n; k++) { - pnts.emplace_back(rand() % box_size_x - half_box_size_x, - rand() % box_size_y - half_box_size_y, - rand() % box_size_z - half_box_size_z); - } - - // construct from list points a axis aligned bounding box - GeoLib::AABB aabb(pnts.begin(), pnts.end()); - - MathLib::Point3d const& min_pnt(aabb.getMinPoint()); - MathLib::Point3d const& max_pnt(aabb.getMaxPoint()); - - ASSERT_LE(minus_half_box_size_x, min_pnt[0]) << "coordinate 0 of min_pnt is smaller than " << minus_half_box_size_x; - ASSERT_LE(minus_half_box_size_y, min_pnt[1]) << "coordinate 1 of min_pnt is smaller than " << minus_half_box_size_y; - ASSERT_LE(minus_half_box_size_z, min_pnt[2]) << "coordinate 2 of min_pnt is smaller than " << minus_half_box_size_z; + srand(static_cast<unsigned>(time(nullptr))); + int n(rand() % 1000000); + int box_size_x(rand()); + int box_size_y(rand()); + int box_size_z(rand()); + double half_box_size_x(box_size_x / 2); + double half_box_size_y(box_size_y / 2); + double half_box_size_z(box_size_z / 2); + auto minus_half_box_size_x(static_cast<int>(-half_box_size_x)); + auto minus_half_box_size_y(static_cast<int>(-half_box_size_y)); + auto minus_half_box_size_z(static_cast<int>(-half_box_size_z)); + + // fill list with points + std::list<GeoLib::Point> pnts; + for (int k(0); k < n; k++) + { + pnts.emplace_back(rand() % box_size_x - half_box_size_x, + rand() % box_size_y - half_box_size_y, + rand() % box_size_z - half_box_size_z); + } + + // construct from list points a axis aligned bounding box + GeoLib::AABB aabb(pnts.begin(), pnts.end()); + + MathLib::Point3d const& min_pnt(aabb.getMinPoint()); + MathLib::Point3d const& max_pnt(aabb.getMaxPoint()); + + ASSERT_LE(minus_half_box_size_x, min_pnt[0]) + << "coordinate 0 of min_pnt is smaller than " << minus_half_box_size_x; + ASSERT_LE(minus_half_box_size_y, min_pnt[1]) + << "coordinate 1 of min_pnt is smaller than " << minus_half_box_size_y; + ASSERT_LE(minus_half_box_size_z, min_pnt[2]) + << "coordinate 2 of min_pnt is smaller than " << minus_half_box_size_z; // since the interval is half-open we have to move the upper bound also - half_box_size_x = std::nexttoward(half_box_size_x, std::numeric_limits<double>::max()); - half_box_size_y = std::nexttoward(half_box_size_y, std::numeric_limits<double>::max()); - half_box_size_z = std::nexttoward(half_box_size_z, std::numeric_limits<double>::max()); - ASSERT_GE(half_box_size_x, max_pnt[0]) << "coordinate 0 of max_pnt is greater than " << half_box_size_x; - ASSERT_GE(half_box_size_y, max_pnt[1]) << "coordinate 1 of max_pnt is greater than " << half_box_size_y; - ASSERT_GE(half_box_size_z, max_pnt[2]) << "coordinate 2 of max_pnt is greater than " << half_box_size_z; + half_box_size_x = + std::nexttoward(half_box_size_x, std::numeric_limits<double>::max()); + half_box_size_y = + std::nexttoward(half_box_size_y, std::numeric_limits<double>::max()); + half_box_size_z = + std::nexttoward(half_box_size_z, std::numeric_limits<double>::max()); + ASSERT_GE(half_box_size_x, max_pnt[0]) + << "coordinate 0 of max_pnt is greater than " << half_box_size_x; + ASSERT_GE(half_box_size_y, max_pnt[1]) + << "coordinate 1 of max_pnt is greater than " << half_box_size_y; + ASSERT_GE(half_box_size_z, max_pnt[2]) + << "coordinate 2 of max_pnt is greater than " << half_box_size_z; } TEST(GeoLib, AABBAllPointsWithNegativeCoordinatesI) @@ -248,16 +295,18 @@ TEST(GeoLib, AABBAllPointsWithNegativeCoordinatesII) } // This test creates an AABB containing a single point. -// This point is moved in every space direction to the next possible double value. -// It is checked that the AABB contains the point iff it has not been moved. +// This point is moved in every space direction to the next possible double +// value. It is checked that the AABB contains the point iff it has not been +// moved. TEST(GeoLib, AABBSinglePoint) { std::random_device rd; std::mt19937 random_number_generator(rd()); std::uniform_real_distribution<double> rnd(-1000000.0, 10000000.0); std::vector<GeoLib::Point> pnts; - GeoLib::Point p{{{rnd(random_number_generator), - rnd(random_number_generator),rnd(random_number_generator)}}}; + GeoLib::Point p{ + {{rnd(random_number_generator), rnd(random_number_generator), + rnd(random_number_generator)}}}; pnts.push_back(p); ASSERT_EQ(1u, pnts.size()); @@ -270,7 +319,8 @@ TEST(GeoLib, AABBSinglePoint) // Check the point within the aabb (i==j==k). The outer 26 (3 * 3 * 3 - 1) // points around the aabb are also checked. - for (int i(-1); i<2; ++i) { + for (int i(-1); i < 2; ++i) + { // Modify the first coordinate of p. if (i == -1) { @@ -284,7 +334,8 @@ TEST(GeoLib, AABBSinglePoint) { p[0] = std::nextafter(pnts.front()[0], to_max); } - for (int j(-1); j<2; ++j) { + for (int j(-1); j < 2; ++j) + { // Modify the second coordinate of p. if (j == -1) { @@ -298,7 +349,8 @@ TEST(GeoLib, AABBSinglePoint) { p[1] = std::nextafter(pnts.front()[1], to_max); } - for (int k(-1); k<2; ++k) { + for (int k(-1); k < 2; ++k) + { // Modify the third coordinate of p. if (k == -1) { @@ -324,4 +376,3 @@ TEST(GeoLib, AABBSinglePoint) } } } - diff --git a/Tests/GeoLib/TestBoundingSphere.cpp b/Tests/GeoLib/TestBoundingSphere.cpp index f6191780ccecc3e91f247bcd73a614ba9ded78b4..b738c0a8b6e70b27215ea1a22bd0dc8453287e7a 100644 --- a/Tests/GeoLib/TestBoundingSphere.cpp +++ b/Tests/GeoLib/TestBoundingSphere.cpp @@ -12,11 +12,11 @@ * */ +#include <gtest/gtest.h> + #include <memory> #include <random> -#include "gtest/gtest.h" - #include "GeoLib/MinimalBoundingSphere.h" #include "MathLib/Point3d.h" @@ -43,50 +43,51 @@ std::vector<MathLib::Point3d*>* getRandomSpherePoints( TEST(GeoLib, TestBoundingSphere) { std::vector<MathLib::Point3d*> pnts; - pnts.push_back(new MathLib::Point3d(std::array<double,3>({{0, 0 , 0}}))); - pnts.push_back(new MathLib::Point3d(std::array<double,3>({{2, 0 , 0}}))); - pnts.push_back(new MathLib::Point3d(std::array<double,3>({{1, 0.1 , 0}}))); - pnts.push_back(new MathLib::Point3d(std::array<double,3>({{1, -0.1 , 0}}))); + pnts.push_back(new MathLib::Point3d(std::array<double, 3>({{0, 0, 0}}))); + pnts.push_back(new MathLib::Point3d(std::array<double, 3>({{2, 0, 0}}))); + pnts.push_back(new MathLib::Point3d(std::array<double, 3>({{1, 0.1, 0}}))); + pnts.push_back(new MathLib::Point3d(std::array<double, 3>({{1, -0.1, 0}}))); { - /** - * Four points located like this: - * - * * - * * * - * * - * - * Tests if a smaller number of points than available is used if the resulting sphere is smaller. - * Expected result is C=(1,0,0), r=1 - */ - GeoLib::MinimalBoundingSphere s(pnts); - MathLib::Point3d center = s.getCenter(); - ASSERT_NEAR(1.0, center[0], std::numeric_limits<double>::epsilon()); - ASSERT_NEAR(0.0, center[1], std::numeric_limits<double>::epsilon()); - ASSERT_NEAR(0.0, center[2], std::numeric_limits<double>::epsilon()); - ASSERT_NEAR(1.0, s.getRadius(), std::numeric_limits<double>::epsilon()); + /** + * Four points located like this: + * + * * + * * * + * * + * + * Tests if a smaller number of points than available is used if the + * resulting sphere is smaller. Expected result is C=(1,0,0), r=1 + */ + GeoLib::MinimalBoundingSphere s(pnts); + MathLib::Point3d center = s.getCenter(); + ASSERT_NEAR(1.0, center[0], std::numeric_limits<double>::epsilon()); + ASSERT_NEAR(0.0, center[1], std::numeric_limits<double>::epsilon()); + ASSERT_NEAR(0.0, center[2], std::numeric_limits<double>::epsilon()); + ASSERT_NEAR(1.0, s.getRadius(), std::numeric_limits<double>::epsilon()); } { - /** - * Four points located like this: - * - * * - * * * - * - * - * * - * - * The smallest sphere has a diameter that is larger than the distance between any two points. - * Expected result is C=(1,0.0246,-0.3446), r=1.058 - */ - (*pnts[2])[2] -= 1.4; - GeoLib::MinimalBoundingSphere s(pnts); - MathLib::Point3d center = s.getCenter(); - ASSERT_NEAR(1.0, center[0], 0.0001); - ASSERT_NEAR(0.0246, center[1], 0.0001); - ASSERT_NEAR(-0.3446, center[2], 0.0001); - ASSERT_NEAR(1.0580, s.getRadius(), 0.0001); + /** + * Four points located like this: + * + * * + * * * + * + * + * * + * + * The smallest sphere has a diameter that is larger than the distance + * between any two points. Expected result is C=(1,0.0246,-0.3446), + * r=1.058 + */ + (*pnts[2])[2] -= 1.4; + GeoLib::MinimalBoundingSphere s(pnts); + MathLib::Point3d center = s.getCenter(); + ASSERT_NEAR(1.0, center[0], 0.0001); + ASSERT_NEAR(0.0246, center[1], 0.0001); + ASSERT_NEAR(-0.3446, center[2], 0.0001); + ASSERT_NEAR(1.0580, s.getRadius(), 0.0001); } (*pnts[0])[0] = 0.0; @@ -101,36 +102,36 @@ TEST(GeoLib, TestBoundingSphere) (*pnts[3])[0] = 0.0; (*pnts[3])[1] = 1.0; (*pnts[3])[2] = 0.0; - pnts.push_back(new MathLib::Point3d(std::array<double,3>({{0, 0, 1}}))); - pnts.push_back(new MathLib::Point3d(std::array<double,3>({{1, 0, 1}}))); - pnts.push_back(new MathLib::Point3d(std::array<double,3>({{1, 1, 1}}))); - pnts.push_back(new MathLib::Point3d(std::array<double,3>({{0, 1, 0.9}}))); + pnts.push_back(new MathLib::Point3d(std::array<double, 3>({{0, 0, 1}}))); + pnts.push_back(new MathLib::Point3d(std::array<double, 3>({{1, 0, 1}}))); + pnts.push_back(new MathLib::Point3d(std::array<double, 3>({{1, 1, 1}}))); + pnts.push_back(new MathLib::Point3d(std::array<double, 3>({{0, 1, 0.9}}))); { - /** - * A "cube" where one node is pushed slightly towards the centre (and should be ignored). - * Expected result is C=(0.5,0.5,0.5), r=0.866 - */ - GeoLib::MinimalBoundingSphere s(pnts); - MathLib::Point3d center = s.getCenter(); - ASSERT_NEAR(0.5, center[0], std::numeric_limits<double>::epsilon()); - ASSERT_NEAR(0.5, center[1], std::numeric_limits<double>::epsilon()); - ASSERT_NEAR(0.5, center[2], std::numeric_limits<double>::epsilon()); - ASSERT_NEAR(0.8660, s.getRadius(), 0.0001); + /** + * A "cube" where one node is pushed slightly towards the centre (and + * should be ignored). Expected result is C=(0.5,0.5,0.5), r=0.866 + */ + GeoLib::MinimalBoundingSphere s(pnts); + MathLib::Point3d center = s.getCenter(); + ASSERT_NEAR(0.5, center[0], std::numeric_limits<double>::epsilon()); + ASSERT_NEAR(0.5, center[1], std::numeric_limits<double>::epsilon()); + ASSERT_NEAR(0.5, center[2], std::numeric_limits<double>::epsilon()); + ASSERT_NEAR(0.8660, s.getRadius(), 0.0001); } /** - * A "cube" where one node is pulled away from the centre (making the resulting sphere larger). - * Expected result is C=(0.5,0.5,0.6), r=0.9273 + * A "cube" where one node is pulled away from the centre (making the + * resulting sphere larger). Expected result is C=(0.5,0.5,0.6), r=0.9273 */ (*pnts[7])[2] += 0.3; GeoLib::MinimalBoundingSphere s(pnts); { - MathLib::Point3d center = s.getCenter(); - ASSERT_NEAR(0.5, center[0], std::numeric_limits<double>::epsilon()); - ASSERT_NEAR(0.5, center[1], std::numeric_limits<double>::epsilon()); - ASSERT_NEAR(0.6, center[2], std::numeric_limits<double>::epsilon()); - ASSERT_NEAR(0.9273, s.getRadius(), 0.0001); + MathLib::Point3d center = s.getCenter(); + ASSERT_NEAR(0.5, center[0], std::numeric_limits<double>::epsilon()); + ASSERT_NEAR(0.5, center[1], std::numeric_limits<double>::epsilon()); + ASSERT_NEAR(0.6, center[2], std::numeric_limits<double>::epsilon()); + ASSERT_NEAR(0.9273, s.getRadius(), 0.0001); } /// Calculates the bounding sphere of points on a bounding sphere @@ -148,5 +149,5 @@ TEST(GeoLib, TestBoundingSphere) ASSERT_NEAR(0.9273, t.getRadius(), 0.0001); std::for_each(pnts.begin(), pnts.end(), - std::default_delete<MathLib::Point3d>()); + std::default_delete<MathLib::Point3d>()); } diff --git a/Tests/GeoLib/TestComputeAndInsertAllIntersectionPoints.cpp b/Tests/GeoLib/TestComputeAndInsertAllIntersectionPoints.cpp index b3d74684550761174fc3fa8bb2f0eeabef4c542e..dce6f7e446ff8c959e695bc8329e2e8974e07209 100644 --- a/Tests/GeoLib/TestComputeAndInsertAllIntersectionPoints.cpp +++ b/Tests/GeoLib/TestComputeAndInsertAllIntersectionPoints.cpp @@ -9,11 +9,11 @@ * http://www.opengeosys.org/project/license */ +#include <gtest/gtest.h> + #include <ctime> #include <tuple> -#include "gtest/gtest.h" - #include "GeoLib/AnalyticalGeometry.h" #include "GeoLib/GEOObjects.h" #include "GeoLib/Point.h" @@ -27,21 +27,21 @@ TEST(GeoLib, TestComputeAndInsertAllIntersectionPoints) { // *** insert points in vector auto pnts = std::make_unique<std::vector<GeoLib::Point*>>(); - pnts->push_back(new GeoLib::Point(0.0,0.0,0.0,0)); - pnts->push_back(new GeoLib::Point(11.0,0.0,0.0,1)); + pnts->push_back(new GeoLib::Point(0.0, 0.0, 0.0, 0)); + pnts->push_back(new GeoLib::Point(11.0, 0.0, 0.0, 1)); - pnts->push_back(new GeoLib::Point(0.0,1.0,0.0,2)); - pnts->push_back(new GeoLib::Point(1.0,-1.0,0.0,3)); - pnts->push_back(new GeoLib::Point(2.0, 1.0,0.0,4)); - pnts->push_back(new GeoLib::Point(3.0,-1.0,0.0,5)); - pnts->push_back(new GeoLib::Point(4.0, 1.0,0.0,6)); - pnts->push_back(new GeoLib::Point(5.0,-1.0,0.0,7)); - pnts->push_back(new GeoLib::Point(6.0, 1.0,0.0,8)); - pnts->push_back(new GeoLib::Point(7.0,-1.0,0.0,9)); - pnts->push_back(new GeoLib::Point(8.0, 1.0,0.0,10)); - pnts->push_back(new GeoLib::Point(9.0,-1.0,0.0,11)); - pnts->push_back(new GeoLib::Point(10.0, 1.0,0.0,12)); - pnts->push_back(new GeoLib::Point(11.0,-1.0,0.0,13)); + pnts->push_back(new GeoLib::Point(0.0, 1.0, 0.0, 2)); + pnts->push_back(new GeoLib::Point(1.0, -1.0, 0.0, 3)); + pnts->push_back(new GeoLib::Point(2.0, 1.0, 0.0, 4)); + pnts->push_back(new GeoLib::Point(3.0, -1.0, 0.0, 5)); + pnts->push_back(new GeoLib::Point(4.0, 1.0, 0.0, 6)); + pnts->push_back(new GeoLib::Point(5.0, -1.0, 0.0, 7)); + pnts->push_back(new GeoLib::Point(6.0, 1.0, 0.0, 8)); + pnts->push_back(new GeoLib::Point(7.0, -1.0, 0.0, 9)); + pnts->push_back(new GeoLib::Point(8.0, 1.0, 0.0, 10)); + pnts->push_back(new GeoLib::Point(9.0, -1.0, 0.0, 11)); + pnts->push_back(new GeoLib::Point(10.0, 1.0, 0.0, 12)); + pnts->push_back(new GeoLib::Point(11.0, -1.0, 0.0, 13)); geo_objs.addPointVec(std::move(pnts), geo_name); } @@ -60,7 +60,8 @@ TEST(GeoLib, TestComputeAndInsertAllIntersectionPoints) plys->push_back(ply0); plys->push_back(ply1); - GeoLib::PointVec &pnt_vec(*(const_cast<GeoLib::PointVec*>(geo_objs.getPointVecObj(geo_name)))); + GeoLib::PointVec& pnt_vec( + *(const_cast<GeoLib::PointVec*>(geo_objs.getPointVecObj(geo_name)))); GeoLib::computeAndInsertAllIntersectionPoints(pnt_vec, *plys); ASSERT_EQ(25u, pnt_vec.size()); @@ -111,4 +112,3 @@ TEST(GeoLib, TestComputeAndInsertAllIntersectionPoints) delete ply1; delete ply0; } - diff --git a/Tests/GeoLib/TestComputeRotationMatrix.cpp b/Tests/GeoLib/TestComputeRotationMatrix.cpp index f3e558ac835880d7ddf6459043a7d7860610802f..6c48002ec4df4371c8ff8d76115bad05f61eb81c 100644 --- a/Tests/GeoLib/TestComputeRotationMatrix.cpp +++ b/Tests/GeoLib/TestComputeRotationMatrix.cpp @@ -9,7 +9,7 @@ * http://www.opengeosys.org/project/license */ -#include "gtest/gtest.h" +#include <gtest/gtest.h> #include "GeoLib/AnalyticalGeometry.h" @@ -25,15 +25,15 @@ TEST(GeoLib, ComputeRotationMatrixToXYnegative) Eigen::Vector3d const n({0.0, -1.0, 0.0}); Eigen::Matrix3d const rot_mat = GeoLib::computeRotationMatrixToXY(n); - EXPECT_EQ(1.0, rot_mat(0,0)); - EXPECT_EQ(0.0, rot_mat(0,1)); - EXPECT_EQ(0.0, rot_mat(0,2)); - EXPECT_EQ(0.0, rot_mat(1,0)); - EXPECT_EQ(0.0, rot_mat(1,1)); - EXPECT_EQ(1.0, rot_mat(1,2)); - EXPECT_EQ(0.0, rot_mat(2,0)); - EXPECT_EQ(-1.0, rot_mat(2,1)); - EXPECT_EQ(0.0, rot_mat(2,2)); + EXPECT_EQ(1.0, rot_mat(0, 0)); + EXPECT_EQ(0.0, rot_mat(0, 1)); + EXPECT_EQ(0.0, rot_mat(0, 2)); + EXPECT_EQ(0.0, rot_mat(1, 0)); + EXPECT_EQ(0.0, rot_mat(1, 1)); + EXPECT_EQ(1.0, rot_mat(1, 2)); + EXPECT_EQ(0.0, rot_mat(2, 0)); + EXPECT_EQ(-1.0, rot_mat(2, 1)); + EXPECT_EQ(0.0, rot_mat(2, 2)); Eigen::Vector3d const x({0.0, 1.0, 0.0}); test3equal(0, 0, -1, rot_mat * x); @@ -50,15 +50,15 @@ TEST(GeoLib, ComputeRotationMatrixToXYpositive) Eigen::Vector3d const n{0.0, 1.0, 0.0}; Eigen::Matrix3d const rot_mat = GeoLib::computeRotationMatrixToXY(n); - EXPECT_EQ(1.0, rot_mat(0,0)); - EXPECT_EQ(0.0, rot_mat(0,1)); - EXPECT_EQ(0.0, rot_mat(0,2)); - EXPECT_EQ(0.0, rot_mat(1,0)); - EXPECT_EQ(0.0, rot_mat(1,1)); - EXPECT_EQ(-1.0, rot_mat(1,2)); - EXPECT_EQ(0.0, rot_mat(2,0)); - EXPECT_EQ(1.0, rot_mat(2,1)); - EXPECT_EQ(0.0, rot_mat(2,2)); + EXPECT_EQ(1.0, rot_mat(0, 0)); + EXPECT_EQ(0.0, rot_mat(0, 1)); + EXPECT_EQ(0.0, rot_mat(0, 2)); + EXPECT_EQ(0.0, rot_mat(1, 0)); + EXPECT_EQ(0.0, rot_mat(1, 1)); + EXPECT_EQ(-1.0, rot_mat(1, 2)); + EXPECT_EQ(0.0, rot_mat(2, 0)); + EXPECT_EQ(1.0, rot_mat(2, 1)); + EXPECT_EQ(0.0, rot_mat(2, 2)); Eigen::Vector3d const x(0.0, 1.0, 0.0); test3equal(0, 0, 1, rot_mat * x); @@ -69,4 +69,3 @@ TEST(GeoLib, ComputeRotationMatrixToXYpositive) Eigen::Vector3d const x1(10.0, 0.0, 10.0); test3equal(10, -10, 0, rot_mat * x1); } - diff --git a/Tests/GeoLib/TestDuplicateGeometry.cpp b/Tests/GeoLib/TestDuplicateGeometry.cpp index eba0f3a37f57d9ef39b41dfd7dcb1ceac712b400..772bd3064659f85607270b8ed6738e74ba5bc990 100644 --- a/Tests/GeoLib/TestDuplicateGeometry.cpp +++ b/Tests/GeoLib/TestDuplicateGeometry.cpp @@ -8,13 +8,13 @@ * */ +#include <gtest/gtest.h> + #include <cstdlib> #include <ctime> #include <random> #include <string> -#include "gtest/gtest.h" - #include "GeoLib/DuplicateGeometry.h" #include "GeoLib/GEOObjects.h" #include "GeoLib/Point.h" @@ -25,43 +25,47 @@ TEST(GeoLib, DuplicateGeometry) { GeoLib::GEOObjects geo; - std::string input_name ("input"); + std::string input_name("input"); // generate points - std::srand ( static_cast<unsigned>(std::time(nullptr)) ); - std::size_t n_pnts (rand() % 1000 + 100); - int box_size (std::rand()); - double half_box_size(box_size/2); + std::srand(static_cast<unsigned>(std::time(nullptr))); + std::size_t n_pnts(rand() % 1000 + 100); + int box_size(std::rand()); + double half_box_size(box_size / 2); auto pnts = std::make_unique<std::vector<GeoLib::Point*>>(); pnts->reserve(n_pnts); - for (int k(0); k<static_cast<int>(n_pnts); k++) { - pnts->push_back(new GeoLib::Point( - std::rand() % box_size - half_box_size, - std::rand() % box_size - half_box_size, - std::rand() % box_size - half_box_size)); + for (int k(0); k < static_cast<int>(n_pnts); k++) + { + pnts->push_back( + new GeoLib::Point(std::rand() % box_size - half_box_size, + std::rand() % box_size - half_box_size, + std::rand() % box_size - half_box_size)); } geo.addPointVec(std::move(pnts), input_name); - // update number of points in case because possibly non-unique points have been removed + // update number of points in case because possibly non-unique points have + // been removed n_pnts = geo.getPointVec(input_name)->size(); - std::string output ("output_geometry"); + std::string output("output_geometry"); // duplicate points { - GeoLib::DuplicateGeometry dup (geo, input_name, output); + GeoLib::DuplicateGeometry dup(geo, input_name, output); - std::vector<GeoLib::Point*> const*const pnts (geo.getPointVec(input_name)); - std::vector<GeoLib::Point*> const*const new_pnts (geo.getPointVec(output)); - std::vector<GeoLib::Point*>& mod_pnts (dup.getPointVectorCopy()); + std::vector<GeoLib::Point*> const* const pnts( + geo.getPointVec(input_name)); + std::vector<GeoLib::Point*> const* const new_pnts( + geo.getPointVec(output)); + std::vector<GeoLib::Point*>& mod_pnts(dup.getPointVectorCopy()); ASSERT_EQ(n_pnts, new_pnts->size()); ASSERT_EQ(n_pnts, mod_pnts.size()); - for (std::size_t i=0; i<n_pnts; ++i) + for (std::size_t i = 0; i < n_pnts; ++i) { ASSERT_EQ((*(*pnts)[i])[0], (*(*new_pnts)[i])[0]); ASSERT_EQ((*(*pnts)[i])[1], (*(*new_pnts)[i])[1]); ASSERT_EQ((*(*pnts)[i])[2], (*(*new_pnts)[i])[2]); } - mod_pnts.push_back(new GeoLib::Point(0,0,0)); + mod_pnts.push_back(new GeoLib::Point(0, 0, 0)); ASSERT_EQ(mod_pnts.size(), pnts->size() + 1); ASSERT_EQ(mod_pnts.size(), new_pnts->size()); } @@ -85,19 +89,22 @@ TEST(GeoLib, DuplicateGeometry) // duplicate polylines { - GeoLib::DuplicateGeometry dup (geo, input_name, output); + GeoLib::DuplicateGeometry dup(geo, input_name, output); std::string const& output2 = dup.getFinalizedOutputName(); ASSERT_FALSE(output == output2); - std::vector<GeoLib::Polyline*> const*const plys (geo.getPolylineVec(input_name)); - std::vector<GeoLib::Polyline*> const*const new_plys (geo.getPolylineVec(output2)); + std::vector<GeoLib::Polyline*> const* const plys( + geo.getPolylineVec(input_name)); + std::vector<GeoLib::Polyline*> const* const new_plys( + geo.getPolylineVec(output2)); ASSERT_EQ(plys->size(), new_plys->size()); for (std::size_t i = 0; i < plys->size(); ++i) { - std::size_t const n_ply_pnts ((*new_plys)[i]->getNumberOfPoints()); + std::size_t const n_ply_pnts((*new_plys)[i]->getNumberOfPoints()); ASSERT_EQ(n_ply_pnts, (*plys)[i]->getNumberOfPoints()); - ASSERT_EQ((*new_plys)[i]->getNumberOfSegments(), (*plys)[i]->getNumberOfSegments()); + ASSERT_EQ((*new_plys)[i]->getNumberOfSegments(), + (*plys)[i]->getNumberOfSegments()); for (std::size_t j = 0; j < n_ply_pnts; ++j) { ASSERT_EQ((*plys)[i]->getPointID(j), @@ -105,7 +112,7 @@ TEST(GeoLib, DuplicateGeometry) } } - std::vector<GeoLib::Polyline*>& mod_plys (dup.getPolylineVectorCopy()); + std::vector<GeoLib::Polyline*>& mod_plys(dup.getPolylineVectorCopy()); mod_plys.push_back(new GeoLib::Polyline(*(*new_plys)[0])); ASSERT_EQ(mod_plys.size(), plys->size() + 1); ASSERT_EQ(mod_plys.size(), new_plys->size()); @@ -119,7 +126,7 @@ TEST(GeoLib, DuplicateGeometry) { int const n_tris = std::rand() % 10 + 1; auto* sfc = new GeoLib::Surface(*geo.getPointVec(input_name)); - while(sfc->getNumberOfTriangles() <= n_tris) + while (sfc->getNumberOfTriangles() <= n_tris) { sfc->addTriangle(std::rand() % n_pnts, std::rand() % n_pnts, @@ -133,17 +140,19 @@ TEST(GeoLib, DuplicateGeometry) // duplicate surfaces { - GeoLib::DuplicateGeometry dup (geo, input_name, output); + GeoLib::DuplicateGeometry dup(geo, input_name, output); std::string const& output2 = dup.getFinalizedOutputName(); ASSERT_FALSE(output == output2); - std::vector<GeoLib::Surface*> const* sfcs (geo.getSurfaceVec(input_name)); - std::vector<GeoLib::Surface*> const* new_sfcs (geo.getSurfaceVec(output2)); + std::vector<GeoLib::Surface*> const* sfcs( + geo.getSurfaceVec(input_name)); + std::vector<GeoLib::Surface*> const* new_sfcs( + geo.getSurfaceVec(output2)); ASSERT_EQ(sfcs->size(), new_sfcs->size()); for (std::size_t i = 0; i < sfcs->size(); ++i) { - std::size_t const n_tris ((*new_sfcs)[i]->getNumberOfTriangles()); + std::size_t const n_tris((*new_sfcs)[i]->getNumberOfTriangles()); ASSERT_EQ(n_tris, (*sfcs)[i]->getNumberOfTriangles()); for (std::size_t j = 0; j < n_tris; ++j) { @@ -155,14 +164,14 @@ TEST(GeoLib, DuplicateGeometry) } } - std::vector<GeoLib::Point*>& mod_pnts (dup.getPointVectorCopy()); - std::vector<GeoLib::Surface*>& mod_sfcs (dup.getSurfaceVectorCopy()); + std::vector<GeoLib::Point*>& mod_pnts(dup.getPointVectorCopy()); + std::vector<GeoLib::Surface*>& mod_sfcs(dup.getSurfaceVectorCopy()); std::size_t n_pnts = mod_pnts.size(); - mod_pnts.push_back(new GeoLib::Point(1,0,0,n_pnts)); - mod_pnts.push_back(new GeoLib::Point(0,1,0,n_pnts+1)); - mod_pnts.push_back(new GeoLib::Point(0,0,1,n_pnts+2)); + mod_pnts.push_back(new GeoLib::Point(1, 0, 0, n_pnts)); + mod_pnts.push_back(new GeoLib::Point(0, 1, 0, n_pnts + 1)); + mod_pnts.push_back(new GeoLib::Point(0, 0, 1, n_pnts + 2)); auto* sfc = new GeoLib::Surface(mod_pnts); - sfc->addTriangle(n_pnts, n_pnts+1, n_pnts+2); + sfc->addTriangle(n_pnts, n_pnts + 1, n_pnts + 2); mod_sfcs.push_back(sfc); ASSERT_EQ(mod_sfcs.size(), sfcs->size() + 1); ASSERT_EQ(mod_sfcs.size(), new_sfcs->size()); diff --git a/Tests/GeoLib/TestGEOObjectsMerge.cpp b/Tests/GeoLib/TestGEOObjectsMerge.cpp index ad47412c4da808ca109a7e1c7f3b2df4c9dda327..1a9dd10128160d86f750caa65ca1da8d1fba0bc3 100644 --- a/Tests/GeoLib/TestGEOObjectsMerge.cpp +++ b/Tests/GeoLib/TestGEOObjectsMerge.cpp @@ -10,14 +10,13 @@ * http://www.opengeosys.org/project/license */ +#include <gtest/gtest.h> + #include <map> #include <string> #include <vector> -#include <gtest/gtest.h> - #include "CreateTestPoints.h" - #include "GeoLib/GEOObjects.h" TEST(GeoLib, GEOObjectsMergePoints) @@ -223,4 +222,3 @@ TEST(GeoLib, GEOObjectsMergePolylinesWithNames) ASSERT_TRUE(ply_vec_objs->getElementByName("Polyline1FromGeometry1") != nullptr); } - diff --git a/Tests/GeoLib/TestGrid.cpp b/Tests/GeoLib/TestGrid.cpp index 6c1ef4bc5b4a19d63f2b662bdb00f70a0928cd91..543848ec90bf28db97a9fbf6f9a70609209c29f7 100644 --- a/Tests/GeoLib/TestGrid.cpp +++ b/Tests/GeoLib/TestGrid.cpp @@ -11,27 +11,28 @@ * http://www.opengeosys.org/project/license */ -#include <memory> +#include <gtest/gtest.h> -#include "gtest/gtest.h" +#include <memory> -#include "GeoLib/Point.h" #include "GeoLib/Grid.h" - +#include "GeoLib/Point.h" #include "MathLib/MathTools.h" TEST(GeoLib, InsertZeroPointsInGrid) { std::vector<GeoLib::Point*> pnts; - ASSERT_THROW(GeoLib::Grid<GeoLib::Point> grid(pnts.begin(), pnts.end()), std::runtime_error); + ASSERT_THROW(GeoLib::Grid<GeoLib::Point> grid(pnts.begin(), pnts.end()), + std::runtime_error); } TEST(GeoLib, InsertOnePointInGrid) { std::vector<GeoLib::Point*> pnts; - pnts.push_back(new GeoLib::Point(0.0,0.0,0.0)); + pnts.push_back(new GeoLib::Point(0.0, 0.0, 0.0)); ASSERT_NO_THROW(GeoLib::Grid<GeoLib::Point> grid(pnts.begin(), pnts.end())); - std::for_each(pnts.begin(), pnts.end(), std::default_delete<GeoLib::Point>()); + std::for_each(pnts.begin(), pnts.end(), + std::default_delete<GeoLib::Point>()); } TEST(GeoLib, InsertTwoPointsInGrid) @@ -40,58 +41,67 @@ TEST(GeoLib, InsertTwoPointsInGrid) pnts.push_back(new GeoLib::Point(4.5, -400.0, 0.0)); pnts.push_back(new GeoLib::Point(50, -300.0, 0.0)); ASSERT_NO_THROW(GeoLib::Grid<GeoLib::Point> grid(pnts.begin(), pnts.end())); - std::for_each(pnts.begin(), pnts.end(), std::default_delete<GeoLib::Point>()); + std::for_each(pnts.begin(), pnts.end(), + std::default_delete<GeoLib::Point>()); } - TEST(GeoLib, InsertManyPointsInGrid) { const std::size_t i_max(100); const std::size_t j_max(100); const std::size_t k_max(100); - std::vector<GeoLib::Point*> pnts(i_max*j_max*k_max); + std::vector<GeoLib::Point*> pnts(i_max * j_max * k_max); // fill the vector with points - for (std::size_t i(0); i < i_max; i++) { + for (std::size_t i(0); i < i_max; i++) + { std::size_t offset0(i * j_max * k_max); - for (std::size_t j(0); j < j_max; j++) { + for (std::size_t j(0); j < j_max; j++) + { std::size_t offset1(j * k_max + offset0); - for (std::size_t k(0); k < k_max; k++) { - pnts[offset1 + k] = new GeoLib::Point(static_cast<double>(i) / i_max, - static_cast<double>(j) / j_max, static_cast<double>(k) / k_max); + for (std::size_t k(0); k < k_max; k++) + { + pnts[offset1 + k] = + new GeoLib::Point(static_cast<double>(i) / i_max, + static_cast<double>(j) / j_max, + static_cast<double>(k) / k_max); } } } ASSERT_NO_THROW(GeoLib::Grid<GeoLib::Point> grid(pnts.begin(), pnts.end())); - std::for_each(pnts.begin(), pnts.end(), std::default_delete<GeoLib::Point>()); + std::for_each(pnts.begin(), pnts.end(), + std::default_delete<GeoLib::Point>()); } TEST(GeoLib, InsertPointsWithSameXCoordinateInGrid) { std::vector<GeoLib::Point*> pnts; - pnts.push_back(new GeoLib::Point(0,0,0)); - pnts.push_back(new GeoLib::Point(0,1,0)); - pnts.push_back(new GeoLib::Point(0,1,0.1)); + pnts.push_back(new GeoLib::Point(0, 0, 0)); + pnts.push_back(new GeoLib::Point(0, 1, 0)); + pnts.push_back(new GeoLib::Point(0, 1, 0.1)); GeoLib::Grid<GeoLib::Point> grid(pnts.begin(), pnts.end()); - std::for_each(pnts.begin(), pnts.end(), std::default_delete<GeoLib::Point>()); + std::for_each(pnts.begin(), pnts.end(), + std::default_delete<GeoLib::Point>()); } TEST(GeoLib, SearchNearestPointInGrid) { std::vector<GeoLib::Point*> pnts; - pnts.push_back(new GeoLib::Point(0.0,0.0,0.0)); - GeoLib::Grid<GeoLib::Point> *grid(nullptr); - ASSERT_NO_THROW(grid = new GeoLib::Grid<GeoLib::Point>(pnts.begin(), pnts.end())); + pnts.push_back(new GeoLib::Point(0.0, 0.0, 0.0)); + GeoLib::Grid<GeoLib::Point>* grid(nullptr); + ASSERT_NO_THROW( + grid = new GeoLib::Grid<GeoLib::Point>(pnts.begin(), pnts.end())); ASSERT_NE(grid, nullptr); - GeoLib::Point p0(0,10,10); + GeoLib::Point p0(0, 10, 10); GeoLib::Point* res(grid->getNearestPoint(p0)); ASSERT_EQ(0.0, sqrt(MathLib::sqrDist(*res, *pnts[0]))); delete grid; - std::for_each(pnts.begin(), pnts.end(), std::default_delete<GeoLib::Point>()); + std::for_each(pnts.begin(), pnts.end(), + std::default_delete<GeoLib::Point>()); } TEST(GeoLib, SearchNearestPointsInDenseGrid) @@ -99,59 +109,72 @@ TEST(GeoLib, SearchNearestPointsInDenseGrid) const std::size_t i_max(50); const std::size_t j_max(50); const std::size_t k_max(50); - std::vector<GeoLib::Point*> pnts(i_max*j_max*k_max); + std::vector<GeoLib::Point*> pnts(i_max * j_max * k_max); // fill the vector with equi-distant points in the // cube [0,(i_max-1)/i_max] x [0,(j_max-1)/j_max] x [0,(k_max-1)/k_max] - for (std::size_t i(0); i < i_max; i++) { + for (std::size_t i(0); i < i_max; i++) + { std::size_t offset0(i * j_max * k_max); - for (std::size_t j(0); j < j_max; j++) { + for (std::size_t j(0); j < j_max; j++) + { std::size_t offset1(j * k_max + offset0); - for (std::size_t k(0); k < k_max; k++) { + for (std::size_t k(0); k < k_max; k++) + { pnts[offset1 + k] = new GeoLib::Point( - std::array<double,3>({{static_cast<double>(i) / i_max, - static_cast<double>(j) / j_max, - static_cast<double>(k) / k_max}}), offset1+k); + std::array<double, 3>({{static_cast<double>(i) / i_max, + static_cast<double>(j) / j_max, + static_cast<double>(k) / k_max}}), + offset1 + k); } } } // create the grid GeoLib::Grid<GeoLib::Point>* grid(nullptr); - ASSERT_NO_THROW(grid = new GeoLib::Grid<GeoLib::Point> (pnts.begin(), pnts.end())); + ASSERT_NO_THROW( + grid = new GeoLib::Grid<GeoLib::Point>(pnts.begin(), pnts.end())); // search point (1,1,1) is outside of the point set - GeoLib::Point search_pnt(std::array<double,3>({{1,1,1}}), 0); + GeoLib::Point search_pnt(std::array<double, 3>({{1, 1, 1}}), 0); GeoLib::Point* res(grid->getNearestPoint(search_pnt)); - ASSERT_EQ(i_max*j_max*k_max-1, res->getID()); - ASSERT_NEAR(sqrt(3.0)/50.0, sqrt(MathLib::sqrDist(*res, search_pnt)), std::numeric_limits<double>::epsilon()); + ASSERT_EQ(i_max * j_max * k_max - 1, res->getID()); + ASSERT_NEAR(sqrt(3.0) / 50.0, sqrt(MathLib::sqrDist(*res, search_pnt)), + std::numeric_limits<double>::epsilon()); // search point (0,1,1) is outside of the point set search_pnt[0] = 0; res = grid->getNearestPoint(search_pnt); - ASSERT_EQ(j_max*k_max - 1, res->getID()); - ASSERT_NEAR(sqrt(2.0)/50.0, sqrt(MathLib::sqrDist(*res, search_pnt)), std::numeric_limits<double>::epsilon()); + ASSERT_EQ(j_max * k_max - 1, res->getID()); + ASSERT_NEAR(sqrt(2.0) / 50.0, sqrt(MathLib::sqrDist(*res, search_pnt)), + std::numeric_limits<double>::epsilon()); // search point (0.5,1,1) is outside of the point set search_pnt[0] = 0.5; res = grid->getNearestPoint(search_pnt); - ASSERT_EQ(j_max*k_max*(i_max/2 + 1) - 1, res->getID()); - ASSERT_NEAR(sqrt(2.0)/50.0, sqrt(MathLib::sqrDist(*res, search_pnt)), std::numeric_limits<double>::epsilon()); + ASSERT_EQ(j_max * k_max * (i_max / 2 + 1) - 1, res->getID()); + ASSERT_NEAR(sqrt(2.0) / 50.0, sqrt(MathLib::sqrDist(*res, search_pnt)), + std::numeric_limits<double>::epsilon()); // checking only every fourth point per direction to reduce the run time of // the test - for (std::size_t i(0); i < i_max; i=i+4) { + for (std::size_t i(0); i < i_max; i = i + 4) + { std::size_t offset0(i * j_max * k_max); - for (std::size_t j(0); j < j_max; j=j+4) { + for (std::size_t j(0); j < j_max; j = j + 4) + { std::size_t offset1(j * k_max + offset0); - for (std::size_t k(0); k < k_max; k=k+4) { - res = grid->getNearestPoint(*pnts[offset1+k]); - ASSERT_EQ(offset1+k, res->getID()); - ASSERT_NEAR(sqrt(MathLib::sqrDist(*res, *pnts[offset1+k])), 0.0, std::numeric_limits<double>::epsilon()); + for (std::size_t k(0); k < k_max; k = k + 4) + { + res = grid->getNearestPoint(*pnts[offset1 + k]); + ASSERT_EQ(offset1 + k, res->getID()); + ASSERT_NEAR(sqrt(MathLib::sqrDist(*res, *pnts[offset1 + k])), + 0.0, std::numeric_limits<double>::epsilon()); } } } delete grid; - std::for_each(pnts.begin(), pnts.end(), std::default_delete<GeoLib::Point>()); + std::for_each(pnts.begin(), pnts.end(), + std::default_delete<GeoLib::Point>()); } diff --git a/Tests/GeoLib/TestLineSegmentIntersect.cpp b/Tests/GeoLib/TestLineSegmentIntersect.cpp index bb7c2ad1610a7a01f6ff2935697126d1f8306dd5..32b1c2e09fac23aa4db08ef52b37473c09fca2d8 100644 --- a/Tests/GeoLib/TestLineSegmentIntersect.cpp +++ b/Tests/GeoLib/TestLineSegmentIntersect.cpp @@ -9,13 +9,13 @@ * http://www.opengeosys.org/project/license */ +#include <gtest/gtest.h> + #include <ctime> #include <random> -#include "gtest/gtest.h" - -#include "GeoLib/Point.h" #include "GeoLib/AnalyticalGeometry.h" +#include "GeoLib/Point.h" TEST(GeoLib, TestXAxisParallelLineSegmentIntersection2d) { @@ -26,7 +26,7 @@ TEST(GeoLib, TestXAxisParallelLineSegmentIntersection2d) GeoLib::Point d(1.5, 0.0, 0.0); GeoLib::Point s; - EXPECT_TRUE(GeoLib::lineSegmentIntersect({&a,&b}, {&c,&d}, s)); + EXPECT_TRUE(GeoLib::lineSegmentIntersect({&a, &b}, {&c, &d}, s)); } TEST(GeoLib, TestParallelLineSegmentIntersection2d) @@ -38,7 +38,7 @@ TEST(GeoLib, TestParallelLineSegmentIntersection2d) GeoLib::Point d(1.5, 1.5, 0.0); GeoLib::Point s; - EXPECT_TRUE(GeoLib::lineSegmentIntersect({&a,&b}, {&c,&d}, s)); + EXPECT_TRUE(GeoLib::lineSegmentIntersect({&a, &b}, {&c, &d}, s)); } TEST(GeoLib, TestNonIntersectingParallelLineSegments2dCaseI) @@ -50,7 +50,7 @@ TEST(GeoLib, TestNonIntersectingParallelLineSegments2dCaseI) GeoLib::Point d(2.5, 2.5, 0.0); GeoLib::Point s; - EXPECT_FALSE(GeoLib::lineSegmentIntersect({&a,&b}, {&c,&d}, s)); + EXPECT_FALSE(GeoLib::lineSegmentIntersect({&a, &b}, {&c, &d}, s)); } TEST(GeoLib, TestNonIntersectingParallelLineSegments2dCaseII) @@ -62,7 +62,7 @@ TEST(GeoLib, TestNonIntersectingParallelLineSegments2dCaseII) GeoLib::Point d(-1.0, 0.0, 0.0); GeoLib::Point s; - EXPECT_FALSE(GeoLib::lineSegmentIntersect({&a,&b}, {&c,&d}, s)); + EXPECT_FALSE(GeoLib::lineSegmentIntersect({&a, &b}, {&c, &d}, s)); } TEST(GeoLib, TestIntersectingLineSegments2d) @@ -74,7 +74,7 @@ TEST(GeoLib, TestIntersectingLineSegments2d) GeoLib::Point d(1.0, 0.0, 0.0); GeoLib::Point s; - EXPECT_TRUE(GeoLib::lineSegmentIntersect({&a,&b}, {&c,&d}, s)); + EXPECT_TRUE(GeoLib::lineSegmentIntersect({&a, &b}, {&c, &d}, s)); } TEST(GeoLib, TestIntersectingLineSegments3d) @@ -86,18 +86,18 @@ TEST(GeoLib, TestIntersectingLineSegments3d) GeoLib::Point d(1.0, 0.0, 1.0); GeoLib::Point s; - EXPECT_TRUE(GeoLib::lineSegmentIntersect({&a,&b}, {&c,&d}, s)); + EXPECT_TRUE(GeoLib::lineSegmentIntersect({&a, &b}, {&c, &d}, s)); // disturb one point a little bit double const eps(std::numeric_limits<float>::epsilon()); d[2] += eps; - EXPECT_TRUE(GeoLib::lineSegmentIntersect({&a,&b}, {&c,&d}, s)); - d[2] = 1.0+1e-9; - EXPECT_TRUE(GeoLib::lineSegmentIntersect({&a,&b}, {&c,&d}, s)); - d[2] = 1.0+1e-8; - EXPECT_TRUE(GeoLib::lineSegmentIntersect({&a,&b}, {&c,&d}, s)); + EXPECT_TRUE(GeoLib::lineSegmentIntersect({&a, &b}, {&c, &d}, s)); + d[2] = 1.0 + 1e-9; + EXPECT_TRUE(GeoLib::lineSegmentIntersect({&a, &b}, {&c, &d}, s)); + d[2] = 1.0 + 1e-8; + EXPECT_TRUE(GeoLib::lineSegmentIntersect({&a, &b}, {&c, &d}, s)); d[2] = 1.0 + 5e-6; - EXPECT_FALSE(GeoLib::lineSegmentIntersect({&a,&b}, {&c,&d}, s)); + EXPECT_FALSE(GeoLib::lineSegmentIntersect({&a, &b}, {&c, &d}, s)); } TEST(GeoLib, TestParallelLineSegmentIntersection3d) @@ -109,7 +109,7 @@ TEST(GeoLib, TestParallelLineSegmentIntersection3d) GeoLib::Point d(1.5, 1.5, 1.5); GeoLib::Point s; - EXPECT_TRUE(GeoLib::lineSegmentIntersect({&a,&b}, {&c,&d}, s)); + EXPECT_TRUE(GeoLib::lineSegmentIntersect({&a, &b}, {&c, &d}, s)); } TEST(GeoLib, TestNonIntersectingParallelLineSegments3d) @@ -120,7 +120,7 @@ TEST(GeoLib, TestNonIntersectingParallelLineSegments3d) GeoLib::Point c(1.5, 1.5, 1.5); GeoLib::Point d(2.5, 2.5, 2.5); GeoLib::Point s; - EXPECT_FALSE(GeoLib::lineSegmentIntersect({&a,&b}, {&c,&d}, s)); + EXPECT_FALSE(GeoLib::lineSegmentIntersect({&a, &b}, {&c, &d}, s)); // two axis parallel line segments that do not intersect b[0] = 3.0; @@ -132,7 +132,7 @@ TEST(GeoLib, TestNonIntersectingParallelLineSegments3d) d[0] = 10.0; d[1] = 0.0; d[2] = 0.0; - EXPECT_FALSE(GeoLib::lineSegmentIntersect({&a,&b}, {&c,&d}, s)); + EXPECT_FALSE(GeoLib::lineSegmentIntersect({&a, &b}, {&c, &d}, s)); // two axis parallel line segments that do not intersect a[0] = 1000.0; @@ -147,7 +147,7 @@ TEST(GeoLib, TestNonIntersectingParallelLineSegments3d) d[0] = 0.0; d[1] = 0.0; d[2] = 100.0; - EXPECT_FALSE(GeoLib::lineSegmentIntersect({&a,&b}, {&c,&d}, s)); + EXPECT_FALSE(GeoLib::lineSegmentIntersect({&a, &b}, {&c, &d}, s)); } TEST(GeoLib, TestRandomLineSegments3d) @@ -156,26 +156,28 @@ TEST(GeoLib, TestRandomLineSegments3d) std::default_random_engine re; // line segments intersect each other in the middle - for (std::size_t k(0); k<1000; k++) { + for (std::size_t k(0); k < 1000; k++) + { // two intersecting line segments (a,b) and (c,d) GeoLib::Point a(distribution(re), distribution(re), distribution(re)); GeoLib::Point b(distribution(re), distribution(re), distribution(re)); // direction of (c,d) GeoLib::Point w(distribution(re), distribution(re), distribution(re)); // construct c and d such that (a,b) intersects with (c,d) - GeoLib::Point c(0.5*(b[0]+a[0]) + w[0], - 0.5*(b[1]+a[1]) + w[1], - 0.5*(b[2]+a[2]) + w[2]); - GeoLib::Point d(0.5*(b[0]+a[0]) - w[0], - 0.5*(b[1]+a[1]) - w[1], - 0.5*(b[2]+a[2]) - w[2]); + GeoLib::Point c(0.5 * (b[0] + a[0]) + w[0], + 0.5 * (b[1] + a[1]) + w[1], + 0.5 * (b[2] + a[2]) + w[2]); + GeoLib::Point d(0.5 * (b[0] + a[0]) - w[0], + 0.5 * (b[1] + a[1]) - w[1], + 0.5 * (b[2] + a[2]) - w[2]); GeoLib::Point s; - EXPECT_TRUE(GeoLib::lineSegmentIntersect({&a,&b}, {&c,&d}, s)); + EXPECT_TRUE(GeoLib::lineSegmentIntersect({&a, &b}, {&c, &d}, s)); } // line segment (c,d) intersects (a,b) at end point a - for (std::size_t k(0); k<1000; k++) { + for (std::size_t k(0); k < 1000; k++) + { // two intersecting line segments (a,b) and (c,d) GeoLib::Point a(distribution(re), distribution(re), distribution(re)); GeoLib::Point b(distribution(re), distribution(re), distribution(re)); @@ -186,12 +188,13 @@ TEST(GeoLib, TestRandomLineSegments3d) GeoLib::Point d(a[0] - w[0], a[1] - w[1], a[2] - w[2]); GeoLib::Point s; - EXPECT_TRUE(GeoLib::lineSegmentIntersect({&a,&b}, {&c,&d}, s)); - EXPECT_TRUE(GeoLib::lineSegmentIntersect({&c,&d}, {&a,&b}, s)); + EXPECT_TRUE(GeoLib::lineSegmentIntersect({&a, &b}, {&c, &d}, s)); + EXPECT_TRUE(GeoLib::lineSegmentIntersect({&c, &d}, {&a, &b}, s)); } // line segment (c,d) intersects (a,b) at end point b - for (std::size_t k(0); k<1000; k++) { + for (std::size_t k(0); k < 1000; k++) + { // two intersecting line segments (a,b) and (c,d) GeoLib::Point a(distribution(re), distribution(re), distribution(re)); GeoLib::Point b(distribution(re), distribution(re), distribution(re)); @@ -202,8 +205,7 @@ TEST(GeoLib, TestRandomLineSegments3d) GeoLib::Point d(b[0] - w[0], b[1] - w[1], b[2] - w[2]); GeoLib::Point s; - EXPECT_TRUE(GeoLib::lineSegmentIntersect({&a,&b}, {&c,&d}, s)); - EXPECT_TRUE(GeoLib::lineSegmentIntersect({&c,&d}, {&a,&b}, s)); + EXPECT_TRUE(GeoLib::lineSegmentIntersect({&a, &b}, {&c, &d}, s)); + EXPECT_TRUE(GeoLib::lineSegmentIntersect({&c, &d}, {&a, &b}, s)); } } - diff --git a/Tests/GeoLib/TestLineSegmentIntersect2d.cpp b/Tests/GeoLib/TestLineSegmentIntersect2d.cpp index 1f21bf4c6d81e1f918dd968f54aeaf299bee7be7..a0c25101657981ae4bfe2d8c3ce20ab701e7b070 100644 --- a/Tests/GeoLib/TestLineSegmentIntersect2d.cpp +++ b/Tests/GeoLib/TestLineSegmentIntersect2d.cpp @@ -7,36 +7,40 @@ * http://www.opengeosys.org/project/license */ -#include "gtest/gtest.h" +#include <gtest/gtest.h> + #include <array> #include <ctime> #include <functional> #include <memory> #include <random> -#include "Tests/GeoLib/AutoCheckGenerators.h" - -#include "MathLib/Point3d.h" #include "GeoLib/AnalyticalGeometry.h" +#include "MathLib/Point3d.h" +#include "Tests/GeoLib/AutoCheckGenerators.h" namespace ac = autocheck; class LineSegmentIntersect2dTest : public testing::Test { public: - using PointGenerator = ac::RandomCirclePointGeneratorXY<ac::generator<double>>; + using PointGenerator = + ac::RandomCirclePointGeneratorXY<ac::generator<double>>; using SymmSegmentGenerator = ac::SymmSegmentGeneratorXY<PointGenerator>; - using PairSegmentGenerator = ac::PairSegmentGeneratorXY<SymmSegmentGenerator>; + using PairSegmentGenerator = + ac::PairSegmentGeneratorXY<SymmSegmentGenerator>; PointGenerator point_generator1 = PointGenerator( MathLib::Point3d(std::array<double, 3>{{0.0, 0.0, 0.0}}), 1.0); - SymmSegmentGenerator segment_generator1 = SymmSegmentGenerator{point_generator1, - [&](auto p){ return ac::reflect(point_generator1.center, p); }}; + SymmSegmentGenerator segment_generator1 = SymmSegmentGenerator{ + point_generator1, + [&](auto p) { return ac::reflect(point_generator1.center, p); }}; PointGenerator point_generator2 = PointGenerator( MathLib::Point3d(std::array<double, 3>{{2.0, 0.0, 0.0}}), 1.0); - SymmSegmentGenerator segment_generator2 = SymmSegmentGenerator{point_generator2, - [&](auto p){ return ac::reflect(point_generator2.center, p); }}; + SymmSegmentGenerator segment_generator2 = SymmSegmentGenerator{ + point_generator2, + [&](auto p) { return ac::reflect(point_generator2.center, p); }}; Eigen::Vector3d const translation_vector1 = {2, 2, 0}; PairSegmentGenerator pair_segment_generator1 = PairSegmentGenerator{ @@ -57,8 +61,7 @@ public: TEST_F(LineSegmentIntersect2dTest, RandomSegmentOrientationIntersecting) { auto intersect = [](GeoLib::LineSegment const& s0, - GeoLib::LineSegment const& s1) - { + GeoLib::LineSegment const& s1) { auto ipnts = GeoLib::lineSegmentIntersect2d(s0, s1); if (ipnts.size() == 1) { @@ -82,8 +85,7 @@ TEST_F(LineSegmentIntersect2dTest, RandomSegmentOrientationIntersecting) TEST_F(LineSegmentIntersect2dTest, RandomSegmentOrientationNonIntersecting) { auto intersect = [](GeoLib::LineSegment const& s0, - GeoLib::LineSegment const& s1) - { + GeoLib::LineSegment const& s1) { auto ipnts = GeoLib::lineSegmentIntersect2d(s0, s1); return ipnts.empty(); }; @@ -99,37 +101,33 @@ TEST_F(LineSegmentIntersect2dTest, RandomSegmentOrientationNonIntersecting) // line segment is created by translating the first line segment. TEST_F(LineSegmentIntersect2dTest, ParallelNonIntersectingSegmentOrientation) { - auto intersect = []( - std::pair<GeoLib::LineSegment const&, GeoLib::LineSegment const&> const& - segment_pair) - { - auto ipnts = GeoLib::lineSegmentIntersect2d(segment_pair.first, - segment_pair.second); - return ipnts.empty(); - }; + auto intersect = + [](std::pair<GeoLib::LineSegment const&, + GeoLib::LineSegment const&> const& segment_pair) { + auto ipnts = GeoLib::lineSegmentIntersect2d(segment_pair.first, + segment_pair.second); + return ipnts.empty(); + }; // generate non-intersecting segments ac::check<std::pair<GeoLib::LineSegment, GeoLib::LineSegment>>( - intersect, 1000, - ac::make_arbitrary(pair_segment_generator1), + intersect, 1000, ac::make_arbitrary(pair_segment_generator1), gtest_reporter); } // Test the intersection of parallel, interfering line segments. TEST_F(LineSegmentIntersect2dTest, ParallelIntersectingSegmentOrientation) { - auto intersect = []( - std::pair<GeoLib::LineSegment const&, GeoLib::LineSegment const&> const& - segment_pair) - { - auto ipnts = GeoLib::lineSegmentIntersect2d(segment_pair.first, - segment_pair.second); - return ipnts.size() == 2; - }; + auto intersect = + [](std::pair<GeoLib::LineSegment const&, + GeoLib::LineSegment const&> const& segment_pair) { + auto ipnts = GeoLib::lineSegmentIntersect2d(segment_pair.first, + segment_pair.second); + return ipnts.size() == 2; + }; // generate non-intersecting segments ac::check<std::pair<GeoLib::LineSegment, GeoLib::LineSegment>>( - intersect, 1000, - ac::make_arbitrary(pair_segment_generator2), + intersect, 1000, ac::make_arbitrary(pair_segment_generator2), gtest_reporter); } diff --git a/Tests/GeoLib/TestOctTree.cpp b/Tests/GeoLib/TestOctTree.cpp index 5dbfceef497310c17b4addc79d2431658e3d71cb..62cb593011801e914b9adf5232471c75e442f3f9 100644 --- a/Tests/GeoLib/TestOctTree.cpp +++ b/Tests/GeoLib/TestOctTree.cpp @@ -7,13 +7,14 @@ * http://www.opengeosys.org/project/license */ -#include "gtest/gtest.h" +#include <gtest/gtest.h> + #include <ctime> -#include <random> #include <memory> +#include <random> -#include "GeoLib/OctTree.h" #include "GeoLib/AABB.h" +#include "GeoLib/OctTree.h" #include "GeoLib/Point.h" class GeoLibOctTree : public testing::Test @@ -24,14 +25,14 @@ public: GeoLibOctTree() = default; ~GeoLibOctTree() override { - for (auto p : ps_ptr) { + for (auto p : ps_ptr) + { delete p; } } #ifndef NDEBUG template <std::size_t MAX_POINTS> - void - checkOctTreeChildsNonNullptr( + void checkOctTreeChildsNonNullptr( GeoLib::OctTree<GeoLib::Point, MAX_POINTS> const& oct_tree) const { ASSERT_NE(nullptr, oct_tree.getChild(0)); @@ -47,8 +48,8 @@ public: #ifndef NDEBUG template <std::size_t MAX_POINTS> - void - checkOctTreeChildsNullptr(GeoLib::OctTree<GeoLib::Point, MAX_POINTS> const& oct_tree) const + void checkOctTreeChildsNullptr( + GeoLib::OctTree<GeoLib::Point, MAX_POINTS> const& oct_tree) const { ASSERT_EQ(nullptr, oct_tree.getChild(0)); ASSERT_EQ(nullptr, oct_tree.getChild(1)); @@ -62,15 +63,18 @@ public: #endif protected: - void - generateEquidistantPoints3d(std::size_t const n = 11) + void generateEquidistantPoints3d(std::size_t const n = 11) { - for (std::size_t k(0); k<n; ++k) { - double const z(k-(n-1)/2.0); - for (std::size_t j(0); j<n; ++j) { - double const y(j-(n-1)/2.0); - for (std::size_t i(0); i<n; ++i) { - ps_ptr.push_back(new GeoLib::Point(i-(n-1)/2.0, y, z)); + for (std::size_t k(0); k < n; ++k) + { + double const z(k - (n - 1) / 2.0); + for (std::size_t j(0); j < n; ++j) + { + double const y(j - (n - 1) / 2.0); + for (std::size_t i(0); i < n; ++i) + { + ps_ptr.push_back( + new GeoLib::Point(i - (n - 1) / 2.0, y, z)); } } } @@ -83,10 +87,10 @@ protected: TEST_F(GeoLibOctTree, TestWithEquidistantPoints3d) { generateEquidistantPoints3d(); - double const eps(10*std::numeric_limits<double>::epsilon()); + double const eps(10 * std::numeric_limits<double>::epsilon()); std::unique_ptr<GeoLib::OctTree<GeoLib::Point, 2>> oct_tree( GeoLib::OctTree<GeoLib::Point, 2>::createOctTree(*ps_ptr.front(), - *ps_ptr.back(), eps)); + *ps_ptr.back(), eps)); #ifndef NDEBUG MathLib::Point3d const& ll(oct_tree->getLowerLeftCornerPoint()); @@ -96,26 +100,26 @@ TEST_F(GeoLibOctTree, TestWithEquidistantPoints3d) EXPECT_EQ((*ps_ptr.front())[1], ll[1]); EXPECT_EQ((*ps_ptr.front())[2], ll[2]); - EXPECT_NEAR((*ps_ptr.back())[0], ur[0], (ur[0]-ll[0])*1e-6); - EXPECT_NEAR((*ps_ptr.back())[1], ur[1], (ur[1]-ll[1])*1e-6); - EXPECT_NEAR((*ps_ptr.back())[2], ur[2], (ur[2]-ll[2])*1e-6); + EXPECT_NEAR((*ps_ptr.back())[0], ur[0], (ur[0] - ll[0]) * 1e-6); + EXPECT_NEAR((*ps_ptr.back())[1], ur[1], (ur[1] - ll[1]) * 1e-6); + EXPECT_NEAR((*ps_ptr.back())[2], ur[2], (ur[2] - ll[2]) * 1e-6); checkOctTreeChildsNullptr<2>(*oct_tree); ASSERT_EQ(static_cast<std::size_t>(0), oct_tree->getPointVector().size()); #endif - GeoLib::Point * ret_pnt(nullptr); + GeoLib::Point* ret_pnt(nullptr); // insert the first point ASSERT_TRUE(oct_tree->addPoint(ps_ptr[0], ret_pnt)); // make a range query MathLib::Point3d const min( - std::array<double,3>{{(*(ps_ptr[0]))[0]-eps, - (*(ps_ptr[0]))[1]-eps, (*(ps_ptr[0]))[2]-eps}}); + std::array<double, 3>{{(*(ps_ptr[0]))[0] - eps, (*(ps_ptr[0]))[1] - eps, + (*(ps_ptr[0]))[2] - eps}}); MathLib::Point3d const max( - std::array<double,3>{{(*(ps_ptr[0]))[0]+eps, - (*(ps_ptr[0]))[1]+eps, (*(ps_ptr[0]))[2]+eps}}); + std::array<double, 3>{{(*(ps_ptr[0]))[0] + eps, (*(ps_ptr[0]))[1] + eps, + (*(ps_ptr[0]))[2] + eps}}); std::vector<GeoLib::Point*> query_pnts; oct_tree->getPointsInRange(min, max, query_pnts); ASSERT_EQ(1u, query_pnts.size()); @@ -160,19 +164,27 @@ TEST_F(GeoLibOctTree, TestWithEquidistantPoints3d) checkOctTreeChildsNullptr<2>(*(oct_tree->getChild(2)->getChild(7))); ASSERT_EQ(static_cast<std::size_t>(2), - oct_tree->getChild(2)->getChild(2)->getChild(2)->getPointVector().size()); + oct_tree->getChild(2) + ->getChild(2) + ->getChild(2) + ->getPointVector() + .size()); ASSERT_EQ(static_cast<std::size_t>(1), - oct_tree->getChild(2)->getChild(2)->getChild(3)->getPointVector().size()); + oct_tree->getChild(2) + ->getChild(2) + ->getChild(3) + ->getPointVector() + .size()); #endif ASSERT_TRUE(oct_tree->addPoint(ps_ptr[3], ret_pnt)); #ifndef NDEBUG ASSERT_EQ(static_cast<std::size_t>(1), - oct_tree->getChild(2)->getChild(3)->getPointVector().size()); + oct_tree->getChild(2)->getChild(3)->getPointVector().size()); #endif GeoLib::Point range_query_ll(*(ps_ptr.front())); - GeoLib::Point range_query_ur(*(ps_ptr[ps_ptr.size()/2])); + GeoLib::Point range_query_ur(*(ps_ptr[ps_ptr.size() / 2])); std::vector<GeoLib::Point*> result; oct_tree->getPointsInRange(range_query_ll, range_query_ur, result); ASSERT_EQ(static_cast<std::size_t>(4), result.size()); @@ -256,13 +268,13 @@ TEST_F(GeoLibOctTree, TestWithAlternatingPoints3d) // this case is not correctly handled by lexicographical sorting double const eps(1e-1); double const small_displacement(1e-2); - ps_ptr.push_back(new GeoLib::Point(0,0,0,0)); - ps_ptr.push_back(new GeoLib::Point(2*small_displacement,0,0,1)); - ps_ptr.push_back(new GeoLib::Point(small_displacement,1,0,2)); - ps_ptr.push_back(new GeoLib::Point(4*small_displacement,0,0,3)); - ps_ptr.push_back(new GeoLib::Point(3*small_displacement,1,0,4)); - ps_ptr.push_back(new GeoLib::Point(6*small_displacement,0,0,5)); - ps_ptr.push_back(new GeoLib::Point(5*small_displacement,1,0,6)); + ps_ptr.push_back(new GeoLib::Point(0, 0, 0, 0)); + ps_ptr.push_back(new GeoLib::Point(2 * small_displacement, 0, 0, 1)); + ps_ptr.push_back(new GeoLib::Point(small_displacement, 1, 0, 2)); + ps_ptr.push_back(new GeoLib::Point(4 * small_displacement, 0, 0, 3)); + ps_ptr.push_back(new GeoLib::Point(3 * small_displacement, 1, 0, 4)); + ps_ptr.push_back(new GeoLib::Point(6 * small_displacement, 0, 0, 5)); + ps_ptr.push_back(new GeoLib::Point(5 * small_displacement, 1, 0, 6)); GeoLib::AABB const aabb(ps_ptr.cbegin(), ps_ptr.cend()); const MathLib::Point3d& min(aabb.getMinPoint()); @@ -271,7 +283,7 @@ TEST_F(GeoLibOctTree, TestWithAlternatingPoints3d) GeoLib::OctTree<GeoLib::Point, 8>::createOctTree(min, max, eps)); // pt_ptr[0] should be inserted correctly - GeoLib::Point * ret_pnt(nullptr); + GeoLib::Point* ret_pnt(nullptr); ASSERT_TRUE(oct_tree->addPoint(ps_ptr[0], ret_pnt)); ASSERT_EQ(ps_ptr[0], ret_pnt); // ps_ptr[1] is in the eps-environment of ps_ptr[0] @@ -305,11 +317,15 @@ TEST_F(GeoLibOctTree, TestSmallDistanceDifferentLeaves) // case where two points with a small distance but different OctTree leaves // are inserted double const eps(0.5); - for (std::size_t k = 0; k < 21; ++k) { - for (std::size_t j = 0; j < 21; ++j) { - std::size_t id = k*21+j; - for (std::size_t i = 0; i < 21; ++i) { - ps_ptr.push_back(new GeoLib::Point(i-10., j-10., k-10., id+i)); + for (std::size_t k = 0; k < 21; ++k) + { + for (std::size_t j = 0; j < 21; ++j) + { + std::size_t id = k * 21 + j; + for (std::size_t i = 0; i < 21; ++i) + { + ps_ptr.push_back( + new GeoLib::Point(i - 10., j - 10., k - 10., id + i)); } } } @@ -322,15 +338,16 @@ TEST_F(GeoLibOctTree, TestSmallDistanceDifferentLeaves) GeoLib::OctTree<GeoLib::Point, 2>::createOctTree(min, max, eps)); // fill OctTree - for (auto p : ps_ptr) { - GeoLib::Point * ret_pnt(nullptr); + for (auto p : ps_ptr) + { + GeoLib::Point* ret_pnt(nullptr); ASSERT_TRUE(oct_tree->addPoint(p, ret_pnt)); ASSERT_EQ(p, ret_pnt); } // point near the GeoLib::Point (0, -10, -10, 10) (with id 10) std::unique_ptr<GeoLib::Point> p0(new GeoLib::Point(0.1, -10.0, -10.0)); - GeoLib::Point * ret_pnt(nullptr); + GeoLib::Point* ret_pnt(nullptr); ASSERT_FALSE(oct_tree->addPoint(p0.get(), ret_pnt)); ASSERT_EQ(10u, ret_pnt->getID()); @@ -342,8 +359,8 @@ TEST_F(GeoLibOctTree, TestSmallDistanceDifferentLeaves) TEST_F(GeoLibOctTree, TestOctTreeWithTwoEqualPoints) { - ps_ptr.push_back(new GeoLib::Point(0,0,0,0)); - ps_ptr.push_back(new GeoLib::Point(0,0,0,1)); + ps_ptr.push_back(new GeoLib::Point(0, 0, 0, 0)); + ps_ptr.push_back(new GeoLib::Point(0, 0, 0, 1)); double const eps(0.0); GeoLib::AABB aabb(ps_ptr.begin(), ps_ptr.end()); @@ -351,7 +368,7 @@ TEST_F(GeoLibOctTree, TestOctTreeWithTwoEqualPoints) GeoLib::OctTree<GeoLib::Point, 2>::createOctTree( aabb.getMinPoint(), aabb.getMaxPoint(), eps)); - GeoLib::Point * ret_pnt(nullptr); + GeoLib::Point* ret_pnt(nullptr); ASSERT_TRUE(oct_tree->addPoint(ps_ptr[0], ret_pnt)); ASSERT_EQ(ps_ptr[0], ret_pnt); ASSERT_FALSE(oct_tree->addPoint(ps_ptr[1], ret_pnt)); @@ -360,8 +377,8 @@ TEST_F(GeoLibOctTree, TestOctTreeWithTwoEqualPoints) TEST_F(GeoLibOctTree, TestOctTreeWithTwoEqualPointsOne) { - ps_ptr.push_back(new GeoLib::Point(1,1,1,0)); - ps_ptr.push_back(new GeoLib::Point(1,1,1,1)); + ps_ptr.push_back(new GeoLib::Point(1, 1, 1, 0)); + ps_ptr.push_back(new GeoLib::Point(1, 1, 1, 1)); double const eps(0.0); GeoLib::AABB aabb(ps_ptr.begin(), ps_ptr.end()); @@ -369,7 +386,7 @@ TEST_F(GeoLibOctTree, TestOctTreeWithTwoEqualPointsOne) GeoLib::OctTree<GeoLib::Point, 2>::createOctTree( aabb.getMinPoint(), aabb.getMaxPoint(), eps)); - GeoLib::Point * ret_pnt(nullptr); + GeoLib::Point* ret_pnt(nullptr); ASSERT_TRUE(oct_tree->addPoint(ps_ptr[0], ret_pnt)); ASSERT_EQ(ps_ptr[0], ret_pnt); ASSERT_FALSE(oct_tree->addPoint(ps_ptr[1], ret_pnt)); @@ -378,8 +395,8 @@ TEST_F(GeoLibOctTree, TestOctTreeWithTwoEqualPointsOne) TEST_F(GeoLibOctTree, TestOctTreeOnCubicDomain) { - ps_ptr.push_back(new GeoLib::Point(-1,-1,-1,0)); - ps_ptr.push_back(new GeoLib::Point(1,1,1,1)); + ps_ptr.push_back(new GeoLib::Point(-1, -1, -1, 0)); + ps_ptr.push_back(new GeoLib::Point(1, 1, 1, 1)); double const eps(0.0); GeoLib::AABB aabb(ps_ptr.begin(), ps_ptr.end()); @@ -387,11 +404,9 @@ TEST_F(GeoLibOctTree, TestOctTreeOnCubicDomain) GeoLib::OctTree<GeoLib::Point, 2>::createOctTree( aabb.getMinPoint(), aabb.getMaxPoint(), eps)); - GeoLib::Point * ret_pnt(nullptr); + GeoLib::Point* ret_pnt(nullptr); ASSERT_TRUE(oct_tree->addPoint(ps_ptr[0], ret_pnt)); ASSERT_EQ(ps_ptr[0], ret_pnt); ASSERT_TRUE(oct_tree->addPoint(ps_ptr[1], ret_pnt)); ASSERT_EQ(ps_ptr[1], ret_pnt); } - - diff --git a/Tests/GeoLib/TestParallel.cpp b/Tests/GeoLib/TestParallel.cpp index 2fd6c803aa51f078cf5d784976de011eed392bfb..7fabfb5645623bcaf6ec97dbc5e993de82ae9cb7 100644 --- a/Tests/GeoLib/TestParallel.cpp +++ b/Tests/GeoLib/TestParallel.cpp @@ -9,7 +9,7 @@ * http://www.opengeosys.org/project/license */ -#include "gtest/gtest.h" +#include <gtest/gtest.h> #include "GeoLib/AnalyticalGeometry.h" @@ -18,33 +18,36 @@ TEST(GeoLib, TestParallel) // parallel vectors Eigen::Vector3d v(0.0, 1.0, 2.0); Eigen::Vector3d w(0.0, 2.0, 4.0); - EXPECT_TRUE(GeoLib::parallel(v,w)); - EXPECT_TRUE(GeoLib::parallel(w,v)); + EXPECT_TRUE(GeoLib::parallel(v, w)); + EXPECT_TRUE(GeoLib::parallel(w, v)); v[1] = 0.0; w[1] = 0.0; - EXPECT_TRUE(GeoLib::parallel(v,w)); - EXPECT_TRUE(GeoLib::parallel(w,v)); + EXPECT_TRUE(GeoLib::parallel(v, w)); + EXPECT_TRUE(GeoLib::parallel(w, v)); // degenerate cases v[2] = 0.0; w[2] = 0.0; - EXPECT_FALSE(GeoLib::parallel(v,w)); - EXPECT_FALSE(GeoLib::parallel(w,v)); + EXPECT_FALSE(GeoLib::parallel(v, w)); + EXPECT_FALSE(GeoLib::parallel(w, v)); w[2] = 0.1; - EXPECT_FALSE(GeoLib::parallel(v,w)); - EXPECT_FALSE(GeoLib::parallel(w,v)); + EXPECT_FALSE(GeoLib::parallel(v, w)); + EXPECT_FALSE(GeoLib::parallel(w, v)); // non-parallel case v[1] = 0.1; - EXPECT_FALSE(GeoLib::parallel(v,w)); - EXPECT_FALSE(GeoLib::parallel(w,v)); + EXPECT_FALSE(GeoLib::parallel(v, w)); + EXPECT_FALSE(GeoLib::parallel(w, v)); // parallel vectors, opposite sense of direction - v[0] = 0.0; v[1] = 1.0; v[2] = 2.0; - w[0] = 0.0; w[1] = -2.0; w[2] = -4.0; - EXPECT_TRUE(GeoLib::parallel(v,w)); - EXPECT_TRUE(GeoLib::parallel(w,v)); + v[0] = 0.0; + v[1] = 1.0; + v[2] = 2.0; + w[0] = 0.0; + w[1] = -2.0; + w[2] = -4.0; + EXPECT_TRUE(GeoLib::parallel(v, w)); + EXPECT_TRUE(GeoLib::parallel(w, v)); } - diff --git a/Tests/GeoLib/TestPointToStationConversion.cpp b/Tests/GeoLib/TestPointToStationConversion.cpp index 22f8e7130304b403635c3c1fb3743bb1f6103af7..4be5acb588e9f9e98c667970280ff27089b46596 100644 --- a/Tests/GeoLib/TestPointToStationConversion.cpp +++ b/Tests/GeoLib/TestPointToStationConversion.cpp @@ -9,11 +9,11 @@ * http://www.opengeosys.org/project/license */ -#include "gtest/gtest.h" +#include <gtest/gtest.h> -#include "InfoLib/TestInfo.h" #include "GeoLib/GEOObjects.h" #include "GeoLib/IO/XmlIO/Boost/BoostXmlGmlInterface.h" +#include "InfoLib/TestInfo.h" TEST(GeoLib, PointToStationConversion) { diff --git a/Tests/GeoLib/TestPointVec.cpp b/Tests/GeoLib/TestPointVec.cpp index 48bb391b6c1e8a68a263360707896743d8e7af3d..e21a5ad1635a323206f15fc77eb574c0f7e99512 100644 --- a/Tests/GeoLib/TestPointVec.cpp +++ b/Tests/GeoLib/TestPointVec.cpp @@ -7,7 +7,8 @@ * http://www.opengeosys.org/project/license */ -#include "gtest/gtest.h" +#include <gtest/gtest.h> + #include <ctime> #include <random> @@ -18,22 +19,17 @@ class PointVecTest : public testing::Test public: using VectorOfPoints = std::vector<GeoLib::Point*>; - PointVecTest() - : gen(std::random_device() ()), name("JustAName") - { - } + PointVecTest() : gen(std::random_device()()), name("JustAName") {} protected: // Generates n new points according to given random number distribution, // which is uniform distribution in [-1, 1]^3. - void - generateRandomPoints(VectorOfPoints& ps, std::size_t const n = 1000) + void generateRandomPoints(VectorOfPoints& ps, std::size_t const n = 1000) { std::uniform_real_distribution<double> rnd(-1, 1); - std::generate_n(std::back_inserter(ps), n, - [&]() { - return new GeoLib::Point(rnd(gen), rnd(gen), rnd(gen), ps.size()); - }); + std::generate_n(std::back_inserter(ps), n, [&]() { + return new GeoLib::Point(rnd(gen), rnd(gen), rnd(gen), ps.size()); + }); } protected: @@ -58,7 +54,7 @@ TEST_F(PointVecTest, TestPointVecCtorEmpty) TEST_F(PointVecTest, TestPointVecCtorSinglePoint) { auto ps_ptr = std::make_unique<VectorOfPoints>(); - ps_ptr->push_back(new GeoLib::Point(0,0,0,0)); + ps_ptr->push_back(new GeoLib::Point(0, 0, 0, 0)); auto point_vec = std::make_unique<GeoLib::PointVec>(name, std::move(ps_ptr)); ASSERT_EQ(std::size_t(1), point_vec->size()); @@ -68,8 +64,8 @@ TEST_F(PointVecTest, TestPointVecCtorSinglePoint) TEST_F(PointVecTest, TestPointVecCtorTwoDiffPoints) { auto ps_ptr = std::make_unique<VectorOfPoints>(); - ps_ptr->push_back(new GeoLib::Point(0,0,0,0)); - ps_ptr->push_back(new GeoLib::Point(1,0,0,1)); + ps_ptr->push_back(new GeoLib::Point(0, 0, 0, 0)); + ps_ptr->push_back(new GeoLib::Point(1, 0, 0, 1)); auto point_vec = std::make_unique<GeoLib::PointVec>(name, std::move(ps_ptr)); @@ -80,8 +76,8 @@ TEST_F(PointVecTest, TestPointVecCtorTwoDiffPoints) TEST_F(PointVecTest, TestPointVecCtorTwoEqualPoints) { auto ps_ptr = std::make_unique<VectorOfPoints>(); - ps_ptr->push_back(new GeoLib::Point(0,0,0,0)); - ps_ptr->push_back(new GeoLib::Point(0,0,0,1)); + ps_ptr->push_back(new GeoLib::Point(0, 0, 0, 0)); + ps_ptr->push_back(new GeoLib::Point(0, 0, 0, 1)); auto point_vec = std::make_unique<GeoLib::PointVec>(name, std::move(ps_ptr)); @@ -92,10 +88,10 @@ TEST_F(PointVecTest, TestPointVecCtorTwoEqualPoints) TEST_F(PointVecTest, TestPointVecPushBack) { auto ps_ptr = std::make_unique<VectorOfPoints>(); - ps_ptr->push_back(new GeoLib::Point(0,0,0,0)); - ps_ptr->push_back(new GeoLib::Point(1,0,0,1)); - ps_ptr->push_back(new GeoLib::Point(0,1,0,2)); - ps_ptr->push_back(new GeoLib::Point(0,0,1,3)); + ps_ptr->push_back(new GeoLib::Point(0, 0, 0, 0)); + ps_ptr->push_back(new GeoLib::Point(1, 0, 0, 1)); + ps_ptr->push_back(new GeoLib::Point(0, 1, 0, 2)); + ps_ptr->push_back(new GeoLib::Point(0, 0, 1, 3)); GeoLib::PointVec point_vec(name, std::move(ps_ptr)); ASSERT_EQ(std::size_t(0), point_vec.getIDMap()[0]); @@ -104,10 +100,14 @@ TEST_F(PointVecTest, TestPointVecPushBack) ASSERT_EQ(std::size_t(3), point_vec.getIDMap()[3]); // Adding some points that are already existing. - ASSERT_EQ(std::size_t(0), point_vec.push_back(new GeoLib::Point(0,0,0,4))); - ASSERT_EQ(std::size_t(1), point_vec.push_back(new GeoLib::Point(1,0,0,5))); - ASSERT_EQ(std::size_t(2), point_vec.push_back(new GeoLib::Point(0,1,0,6))); - ASSERT_EQ(std::size_t(3), point_vec.push_back(new GeoLib::Point(0,0,1,7))); + ASSERT_EQ(std::size_t(0), + point_vec.push_back(new GeoLib::Point(0, 0, 0, 4))); + ASSERT_EQ(std::size_t(1), + point_vec.push_back(new GeoLib::Point(1, 0, 0, 5))); + ASSERT_EQ(std::size_t(2), + point_vec.push_back(new GeoLib::Point(0, 1, 0, 6))); + ASSERT_EQ(std::size_t(3), + point_vec.push_back(new GeoLib::Point(0, 0, 1, 7))); ASSERT_EQ(std::size_t(4), point_vec.size()); ASSERT_EQ(std::size_t(8), point_vec.getIDMap().size()); @@ -118,10 +118,14 @@ TEST_F(PointVecTest, TestPointVecPushBack) ASSERT_EQ(std::size_t(3), point_vec.getIDMap()[7]); // Adding again some already existing points. - ASSERT_EQ(std::size_t(0), point_vec.push_back(new GeoLib::Point(0,0,0,8))); - ASSERT_EQ(std::size_t(1), point_vec.push_back(new GeoLib::Point(1,0,0,9))); - ASSERT_EQ(std::size_t(2), point_vec.push_back(new GeoLib::Point(0,1,0,10))); - ASSERT_EQ(std::size_t(3), point_vec.push_back(new GeoLib::Point(0,0,1,11))); + ASSERT_EQ(std::size_t(0), + point_vec.push_back(new GeoLib::Point(0, 0, 0, 8))); + ASSERT_EQ(std::size_t(1), + point_vec.push_back(new GeoLib::Point(1, 0, 0, 9))); + ASSERT_EQ(std::size_t(2), + point_vec.push_back(new GeoLib::Point(0, 1, 0, 10))); + ASSERT_EQ(std::size_t(3), + point_vec.push_back(new GeoLib::Point(0, 0, 1, 11))); ASSERT_EQ(std::size_t(4), point_vec.size()); ASSERT_EQ(std::size_t(12), point_vec.getIDMap().size()); @@ -132,10 +136,14 @@ TEST_F(PointVecTest, TestPointVecPushBack) ASSERT_EQ(std::size_t(3), point_vec.getIDMap()[11]); // Adding some new points. - ASSERT_EQ(std::size_t(4), point_vec.push_back(new GeoLib::Point(0.1,0.1,0.1,12))); - ASSERT_EQ(std::size_t(5), point_vec.push_back(new GeoLib::Point(1.1,0.1,0.1,13))); - ASSERT_EQ(std::size_t(6), point_vec.push_back(new GeoLib::Point(0.1,1.1,0.1,14))); - ASSERT_EQ(std::size_t(7), point_vec.push_back(new GeoLib::Point(0.1,0.1,1.1,15))); + ASSERT_EQ(std::size_t(4), + point_vec.push_back(new GeoLib::Point(0.1, 0.1, 0.1, 12))); + ASSERT_EQ(std::size_t(5), + point_vec.push_back(new GeoLib::Point(1.1, 0.1, 0.1, 13))); + ASSERT_EQ(std::size_t(6), + point_vec.push_back(new GeoLib::Point(0.1, 1.1, 0.1, 14))); + ASSERT_EQ(std::size_t(7), + point_vec.push_back(new GeoLib::Point(0.1, 0.1, 1.1, 15))); ASSERT_EQ(std::size_t(8), point_vec.size()); ASSERT_EQ(std::size_t(16), point_vec.getIDMap().size()); @@ -146,10 +154,14 @@ TEST_F(PointVecTest, TestPointVecPushBack) ASSERT_EQ(std::size_t(7), point_vec.getIDMap()[15]); // Adding again some already existing points. - ASSERT_EQ(std::size_t(0), point_vec.push_back(new GeoLib::Point(0,0,0,16))); - ASSERT_EQ(std::size_t(1), point_vec.push_back(new GeoLib::Point(1,0,0,17))); - ASSERT_EQ(std::size_t(2), point_vec.push_back(new GeoLib::Point(0,1,0,18))); - ASSERT_EQ(std::size_t(3), point_vec.push_back(new GeoLib::Point(0,0,1,19))); + ASSERT_EQ(std::size_t(0), + point_vec.push_back(new GeoLib::Point(0, 0, 0, 16))); + ASSERT_EQ(std::size_t(1), + point_vec.push_back(new GeoLib::Point(1, 0, 0, 17))); + ASSERT_EQ(std::size_t(2), + point_vec.push_back(new GeoLib::Point(0, 1, 0, 18))); + ASSERT_EQ(std::size_t(3), + point_vec.push_back(new GeoLib::Point(0, 0, 1, 19))); ASSERT_EQ(std::size_t(8), point_vec.size()); ASSERT_EQ(std::size_t(20), point_vec.getIDMap().size()); diff --git a/Tests/GeoLib/TestPointsOnAPlane.cpp b/Tests/GeoLib/TestPointsOnAPlane.cpp index b2f937b9cc507ef2dce619a6fe494742f2cf5a60..9cb8fec056bf44dd449fdf4b005490c1d322bed7 100644 --- a/Tests/GeoLib/TestPointsOnAPlane.cpp +++ b/Tests/GeoLib/TestPointsOnAPlane.cpp @@ -12,20 +12,19 @@ * */ +#include <gtest/gtest.h> + #include <ctime> #include <random> -#include <gtest/gtest.h> - -#include "MathLib/GeometricBasics.h" #include "GeoLib/Point.h" +#include "MathLib/GeometricBasics.h" -void testAllPossibilities( - GeoLib::Point const& a, - GeoLib::Point const& b, - GeoLib::Point const& c, - GeoLib::Point const& d, - bool expected) +void testAllPossibilities(GeoLib::Point const& a, + GeoLib::Point const& b, + GeoLib::Point const& c, + GeoLib::Point const& d, + bool expected) { ASSERT_EQ(expected, MathLib::isCoplanar(a, b, c, d)); ASSERT_EQ(expected, MathLib::isCoplanar(a, b, d, c)); @@ -59,14 +58,14 @@ void testAllPossibilities( TEST(GeoLib, TestPointsOnAPlane) { // 2d case - GeoLib::Point a(0,0,0); - GeoLib::Point b(1,0,0); - GeoLib::Point c(0,1,0); - GeoLib::Point d(1,1,0); + GeoLib::Point a(0, 0, 0); + GeoLib::Point b(1, 0, 0); + GeoLib::Point c(0, 1, 0); + GeoLib::Point d(1, 1, 0); testAllPossibilities(a, b, c, d, true); // disturbe z coordinate of point d - d[2] = 1e6*std::numeric_limits<double>::epsilon(); + d[2] = 1e6 * std::numeric_limits<double>::epsilon(); testAllPossibilities(a, b, c, d, true); // disturbe z coordinate of point d @@ -99,17 +98,18 @@ TEST(GeoLib, TestPointsOnAPlane) // a,b,c with random coordinates, std::uniform_real_distribution<double> distri(-1e10, 1e10); std::default_random_engine re; - for (std::size_t k(0); k<1000; k++) { + for (std::size_t k(0); k < 1000; k++) + { a = GeoLib::Point(distri(re), distri(re), distri(re)); b = GeoLib::Point(distri(re), distri(re), distri(re)); c = GeoLib::Point(distri(re), distri(re), distri(re)); // d such that it is in the plane - d = GeoLib::Point(b[0]+c[0]-a[0], b[1]+c[1]-a[1], b[2]+c[2]-a[2]); + d = GeoLib::Point( + b[0] + c[0] - a[0], b[1] + c[1] - a[1], b[2] + c[2] - a[2]); testAllPossibilities(a, b, c, d, true); // d such that it is not in the plane d[2] = std::numeric_limits<double>::epsilon() + - (1 + std::numeric_limits<double>::epsilon())*(b[2]+c[2]); + (1 + std::numeric_limits<double>::epsilon()) * (b[2] + c[2]); testAllPossibilities(a, b, c, d, false); } } - diff --git a/Tests/GeoLib/TestPolygon.cpp b/Tests/GeoLib/TestPolygon.cpp index 141924e499925220c5d37725c7a7da422293c5f1..d2b4a1a20bc74a4ffd74ea348e4217beda0ee903 100644 --- a/Tests/GeoLib/TestPolygon.cpp +++ b/Tests/GeoLib/TestPolygon.cpp @@ -10,10 +10,10 @@ * http://www.opengeosys.org/project/license */ -#include "gtest/gtest.h" +#include <gtest/gtest.h> -#include "GeoLib/Point.h" #include "GeoLib/LineSegment.h" +#include "GeoLib/Point.h" #include "GeoLib/Polygon.h" /** @@ -30,21 +30,20 @@ * 0 */ - class PolygonTest : public testing::Test { public: PolygonTest() { // create points and construct polygon - _pnts.push_back(new GeoLib::Point( 0.0, 0.0,0.0)); // 0 - _pnts.push_back(new GeoLib::Point(-2.0, 2.0,0.0)); // 1 - _pnts.push_back(new GeoLib::Point(-2.0, 4.0,0.0)); // 2 - _pnts.push_back(new GeoLib::Point(-1.0, 2.0,0.0)); // 3 - _pnts.push_back(new GeoLib::Point( 0.0, 4.0,0.0)); // 4 - _pnts.push_back(new GeoLib::Point( 1.0, 2.0,0.0)); // 5 - _pnts.push_back(new GeoLib::Point( 2.0, 4.0,0.0)); // 6 - _pnts.push_back(new GeoLib::Point( 2.0, 2.0,0.0)); // 7 + _pnts.push_back(new GeoLib::Point(0.0, 0.0, 0.0)); // 0 + _pnts.push_back(new GeoLib::Point(-2.0, 2.0, 0.0)); // 1 + _pnts.push_back(new GeoLib::Point(-2.0, 4.0, 0.0)); // 2 + _pnts.push_back(new GeoLib::Point(-1.0, 2.0, 0.0)); // 3 + _pnts.push_back(new GeoLib::Point(0.0, 4.0, 0.0)); // 4 + _pnts.push_back(new GeoLib::Point(1.0, 2.0, 0.0)); // 5 + _pnts.push_back(new GeoLib::Point(2.0, 4.0, 0.0)); // 6 + _pnts.push_back(new GeoLib::Point(2.0, 2.0, 0.0)); // 7 // create closed polyline GeoLib::Polyline ply(_pnts); @@ -86,7 +85,8 @@ TEST_F(PolygonTest, isPntInPolygonCheckCorners) TEST_F(PolygonTest, isPntInPolygonCheckPointsRestOnPolygonEdges) { - for (std::size_t k(0); k<_pnts.size()-1; k++) { + for (std::size_t k(0); k < _pnts.size() - 1; k++) + { double t = 0; while (t < 1.0) { @@ -101,28 +101,28 @@ TEST_F(PolygonTest, isPntInPolygonCheckPointsRestOnPolygonEdges) TEST_F(PolygonTest, isPntInPolygonCheckInnerPoints) { - ASSERT_TRUE(_polygon->isPntInPolygon(GeoLib::Point(1.0,1.0,0.0))); - ASSERT_TRUE(_polygon->isPntInPolygon(GeoLib::Point(0.5,1.0,0.0))); + ASSERT_TRUE(_polygon->isPntInPolygon(GeoLib::Point(1.0, 1.0, 0.0))); + ASSERT_TRUE(_polygon->isPntInPolygon(GeoLib::Point(0.5, 1.0, 0.0))); } TEST_F(PolygonTest, isPntInPolygonCheckOuterPoints) { - ASSERT_FALSE(_polygon->isPntInPolygon(GeoLib::Point( - 0.0-std::numeric_limits<float>::epsilon(),0.0,0.0))); - ASSERT_FALSE(_polygon->isPntInPolygon(GeoLib::Point( - -2.0-std::numeric_limits<float>::epsilon(),2.0,0.0))); - ASSERT_FALSE(_polygon->isPntInPolygon(GeoLib::Point( - -2.0-std::numeric_limits<float>::epsilon(),4.0,0.0))); - ASSERT_FALSE(_polygon->isPntInPolygon(GeoLib::Point( - -1.0, 2.0+std::numeric_limits<float>::epsilon(),0.0))); - ASSERT_FALSE(_polygon->isPntInPolygon(GeoLib::Point( - 0.0-std::numeric_limits<float>::epsilon(),4.0,0.0))); - ASSERT_FALSE(_polygon->isPntInPolygon(GeoLib::Point( - 1.0,2.0+std::numeric_limits<float>::epsilon(),0.0))); - ASSERT_FALSE(_polygon->isPntInPolygon(GeoLib::Point( - 2.0-std::numeric_limits<float>::epsilon(),4.0,0.0))); - ASSERT_FALSE(_polygon->isPntInPolygon(GeoLib::Point( - 2.0+std::numeric_limits<float>::epsilon(),2.0,0.0))); + ASSERT_FALSE(_polygon->isPntInPolygon( + GeoLib::Point(0.0 - std::numeric_limits<float>::epsilon(), 0.0, 0.0))); + ASSERT_FALSE(_polygon->isPntInPolygon( + GeoLib::Point(-2.0 - std::numeric_limits<float>::epsilon(), 2.0, 0.0))); + ASSERT_FALSE(_polygon->isPntInPolygon( + GeoLib::Point(-2.0 - std::numeric_limits<float>::epsilon(), 4.0, 0.0))); + ASSERT_FALSE(_polygon->isPntInPolygon( + GeoLib::Point(-1.0, 2.0 + std::numeric_limits<float>::epsilon(), 0.0))); + ASSERT_FALSE(_polygon->isPntInPolygon( + GeoLib::Point(0.0 - std::numeric_limits<float>::epsilon(), 4.0, 0.0))); + ASSERT_FALSE(_polygon->isPntInPolygon( + GeoLib::Point(1.0, 2.0 + std::numeric_limits<float>::epsilon(), 0.0))); + ASSERT_FALSE(_polygon->isPntInPolygon( + GeoLib::Point(2.0 - std::numeric_limits<float>::epsilon(), 4.0, 0.0))); + ASSERT_FALSE(_polygon->isPntInPolygon( + GeoLib::Point(2.0 + std::numeric_limits<float>::epsilon(), 2.0, 0.0))); } /** @@ -140,7 +140,7 @@ TEST_F(PolygonTest, isPntInPolygonCheckOuterPoints) */ TEST_F(PolygonTest, containsSegment) { - { // test segment (2,6) + { // test segment (2,6) GeoLib::LineSegment const segment{ const_cast<GeoLib::Point*>(_polygon->getPoint(2)), const_cast<GeoLib::Point*>(_polygon->getPoint(6))}; @@ -148,33 +148,33 @@ TEST_F(PolygonTest, containsSegment) } // test all segments of polygon - for (auto && segment_it : *_polygon) + for (auto&& segment_it : *_polygon) { EXPECT_TRUE(_polygon->containsSegment(segment_it)); } - { // 70 + { // 70 GeoLib::LineSegment const segment{ const_cast<GeoLib::Point*>(_polygon->getPoint(7)), const_cast<GeoLib::Point*>(_polygon->getPoint(0))}; ASSERT_TRUE(_polygon->containsSegment(segment)); } - { // test segment (3,5) + { // test segment (3,5) GeoLib::LineSegment const segment{ const_cast<GeoLib::Point*>(_polygon->getPoint(3)), const_cast<GeoLib::Point*>(_polygon->getPoint(5))}; ASSERT_TRUE(_polygon->containsSegment(segment)); } - { // test segment (1,7) + { // test segment (1,7) GeoLib::LineSegment const segment{ const_cast<GeoLib::Point*>(_polygon->getPoint(1)), const_cast<GeoLib::Point*>(_polygon->getPoint(7))}; ASSERT_TRUE(_polygon->containsSegment(segment)); } - { // test segment (1,4) + { // test segment (1,4) GeoLib::LineSegment const segment{ const_cast<GeoLib::Point*>(_polygon->getPoint(1)), const_cast<GeoLib::Point*>(_polygon->getPoint(4))}; @@ -186,8 +186,8 @@ TEST_F(PolygonTest, isPolylineInPolygon) { // create a test polyline std::vector<GeoLib::Point*> pnts; - pnts.push_back(new GeoLib::Point(-2.0,4.0,0.0)); // 2 - pnts.push_back(new GeoLib::Point( 2.0,4.0,0.0)); // 6 + pnts.push_back(new GeoLib::Point(-2.0, 4.0, 0.0)); // 2 + pnts.push_back(new GeoLib::Point(2.0, 4.0, 0.0)); // 6 GeoLib::Polyline outer_ply(pnts); outer_ply.addPoint(0); outer_ply.addPoint(1); @@ -198,8 +198,8 @@ TEST_F(PolygonTest, isPolylineInPolygon) } pnts.clear(); - pnts.push_back(new GeoLib::Point(-1.0,2.0,0.0)); // 3 - pnts.push_back(new GeoLib::Point( 1.0,2.0,0.0)); // 5 + pnts.push_back(new GeoLib::Point(-1.0, 2.0, 0.0)); // 3 + pnts.push_back(new GeoLib::Point(1.0, 2.0, 0.0)); // 5 GeoLib::Polyline inner_ply(pnts); inner_ply.addPoint(0); inner_ply.addPoint(1); @@ -213,7 +213,8 @@ TEST_F(PolygonTest, isPolylineInPolygon) TEST_F(PolygonTest, CopyConstructor) { GeoLib::Polygon polygon_copy(*_polygon); - ASSERT_EQ(_polygon->getNumberOfSegments(), polygon_copy.getNumberOfSegments()); + ASSERT_EQ(_polygon->getNumberOfSegments(), + polygon_copy.getNumberOfSegments()); // Check if all line segments of the original polygon are contained in the // copy diff --git a/Tests/GeoLib/TestPolyline.cpp b/Tests/GeoLib/TestPolyline.cpp index ce8bfb6a43b0fa307b288f9e1bc882b9f7607c5a..721a56cbd2640b8547d76b82fe3e2d2384daa7a5 100644 --- a/Tests/GeoLib/TestPolyline.cpp +++ b/Tests/GeoLib/TestPolyline.cpp @@ -10,9 +10,9 @@ * http://www.opengeosys.org/project/license */ -#include <ctime> +#include <gtest/gtest.h> -#include "gtest/gtest.h" +#include <ctime> #include "GeoLib/Polyline.h" @@ -49,33 +49,37 @@ TEST(GeoLib, PolylineTest) ASSERT_EQ(std::size_t(3), ply.getNumberOfPoints()); ASSERT_FALSE(ply.isClosed()); ASSERT_TRUE(ply.isPointIDInPolyline(2)); - ASSERT_TRUE(fabs(ply.getLength(2) - (1.0 + sqrt(0.5))) < std::numeric_limits<double>::epsilon()); + ASSERT_TRUE(fabs(ply.getLength(2) - (1.0 + sqrt(0.5))) < + std::numeric_limits<double>::epsilon()); // checking remove ply.removePoint(1); ASSERT_EQ(std::size_t(2), ply.getNumberOfPoints()); ASSERT_FALSE(ply.isClosed()); ASSERT_FALSE(ply.isPointIDInPolyline(1)); - ASSERT_TRUE(fabs(ply.getLength(1) - sqrt(0.5)) < std::numeric_limits<double>::epsilon()); + ASSERT_TRUE(fabs(ply.getLength(1) - sqrt(0.5)) < + std::numeric_limits<double>::epsilon()); // inserting point in the middle - ply.insertPoint(1,1); + ply.insertPoint(1, 1); ASSERT_EQ(std::size_t(3), ply.getNumberOfPoints()); ASSERT_FALSE(ply.isClosed()); ASSERT_TRUE(ply.isPointIDInPolyline(2)); - ASSERT_TRUE(fabs(ply.getLength(2) - (1.0 + sqrt(0.5))) < std::numeric_limits<double>::epsilon()); + ASSERT_TRUE(fabs(ply.getLength(2) - (1.0 + sqrt(0.5))) < + std::numeric_limits<double>::epsilon()); // inserting point at the end ply_pnts.push_back(new GeoLib::Point(1.0, 0.5, 0.0)); - ply.insertPoint(3,3); + ply.insertPoint(3, 3); ASSERT_EQ(std::size_t(4), ply.getNumberOfPoints()); ASSERT_FALSE(ply.isClosed()); ASSERT_TRUE(ply.isPointIDInPolyline(3)); - ASSERT_TRUE(fabs(ply.getLength(3) - (1.0 + sqrt(0.5) + 0.5)) < std::numeric_limits<double>::epsilon()); + ASSERT_TRUE(fabs(ply.getLength(3) - (1.0 + sqrt(0.5) + 0.5)) < + std::numeric_limits<double>::epsilon()); // inserting point at the beginning ply_pnts.push_back(new GeoLib::Point(-1.0, 0.0, 0.0)); - ply.insertPoint(0,4); + ply.insertPoint(0, 4); ASSERT_EQ(std::size_t(5), ply.getNumberOfPoints()); ASSERT_FALSE(ply.isClosed()); ASSERT_TRUE(ply.isPointIDInPolyline(4)); @@ -84,11 +88,13 @@ TEST(GeoLib, PolylineTest) // inserting point in the middle ply_pnts.push_back(new GeoLib::Point(0.0, 0.5, 0.0)); - ply.insertPoint(2,5); + ply.insertPoint(2, 5); ASSERT_EQ(std::size_t(6), ply.getNumberOfPoints()); ASSERT_FALSE(ply.isClosed()); ASSERT_TRUE(ply.isPointIDInPolyline(5)); - ASSERT_TRUE(fabs(ply.getLength(5) - (1.0 + 0.5 + sqrt(1.25) + sqrt(0.5) + 0.5)) < std::numeric_limits<double>::epsilon()); + ASSERT_TRUE( + fabs(ply.getLength(5) - (1.0 + 0.5 + sqrt(1.25) + sqrt(0.5) + 0.5)) < + std::numeric_limits<double>::epsilon()); // close polyline ply.closePolyline(); diff --git a/Tests/GeoLib/TestSimplePolygonTree.cpp b/Tests/GeoLib/TestSimplePolygonTree.cpp index 147b7f57ff6cefb283533468b941d0d18388dc97..65a633e40c2ad35e6705d7ff8a622811665cf792 100644 --- a/Tests/GeoLib/TestSimplePolygonTree.cpp +++ b/Tests/GeoLib/TestSimplePolygonTree.cpp @@ -11,9 +11,9 @@ * http://www.opengeosys.org/project/license */ -#include <memory> +#include <gtest/gtest.h> -#include "gtest/gtest.h" +#include <memory> #include "GeoLib/Point.h" #include "GeoLib/Polygon.h" @@ -36,21 +36,20 @@ * P3: 4,5,6,4 */ - class CreatePolygonTreesTest : public testing::Test { public: CreatePolygonTreesTest() { // create points and construct polygon - _pnts.push_back(new GeoLib::Point(0.0,-1.0,0.0)); - _pnts.push_back(new GeoLib::Point(1.0,0.0,0.0)); - _pnts.push_back(new GeoLib::Point(0.0,1.0,0.0)); - _pnts.push_back(new GeoLib::Point(-1.0,0.0,0.0)); + _pnts.push_back(new GeoLib::Point(0.0, -1.0, 0.0)); + _pnts.push_back(new GeoLib::Point(1.0, 0.0, 0.0)); + _pnts.push_back(new GeoLib::Point(0.0, 1.0, 0.0)); + _pnts.push_back(new GeoLib::Point(-1.0, 0.0, 0.0)); - _pnts.push_back(new GeoLib::Point(-0.9,0.0,0.0)); - _pnts.push_back(new GeoLib::Point(0.75,-0.1,0.0)); - _pnts.push_back(new GeoLib::Point(-0.75,-0.1,0.0)); + _pnts.push_back(new GeoLib::Point(-0.9, 0.0, 0.0)); + _pnts.push_back(new GeoLib::Point(0.75, -0.1, 0.0)); + _pnts.push_back(new GeoLib::Point(-0.75, -0.1, 0.0)); // create closed polylines GeoLib::Polyline ply0(_pnts); @@ -117,7 +116,8 @@ TEST_F(CreatePolygonTreesTest, P0AndP1) createPolygonTrees(pt_list); ASSERT_EQ(2u, pt_list.size()); - std::for_each(pt_list.begin(), pt_list.end(), std::default_delete<GeoLib::SimplePolygonTree>()); + std::for_each(pt_list.begin(), pt_list.end(), + std::default_delete<GeoLib::SimplePolygonTree>()); } TEST_F(CreatePolygonTreesTest, P0AndP1AndP2) @@ -142,7 +142,8 @@ TEST_F(CreatePolygonTreesTest, P0AndP1AndP2) createPolygonTrees(pt_list); ASSERT_EQ(1u, pt_list.size()); ASSERT_EQ(2u, (*(pt_list.begin()))->getNumberOfChildren()); - std::for_each(pt_list.begin(), pt_list.end(), std::default_delete<GeoLib::SimplePolygonTree>()); + std::for_each(pt_list.begin(), pt_list.end(), + std::default_delete<GeoLib::SimplePolygonTree>()); } TEST_F(CreatePolygonTreesTest, P0AndP1AndP2AndP3) @@ -171,6 +172,6 @@ TEST_F(CreatePolygonTreesTest, P0AndP1AndP2AndP3) createPolygonTrees(pt_list); ASSERT_EQ(1u, pt_list.size()); ASSERT_EQ(2u, (*(pt_list.begin()))->getNumberOfChildren()); - std::for_each(pt_list.begin(), pt_list.end(), std::default_delete<GeoLib::SimplePolygonTree>()); + std::for_each(pt_list.begin(), pt_list.end(), + std::default_delete<GeoLib::SimplePolygonTree>()); } - diff --git a/Tests/GeoLib/TestSortSegments.cpp b/Tests/GeoLib/TestSortSegments.cpp index 3f74097efac947b1ed20e02c26dfe2998626d7e7..7c17a3af982c2cc1570803dd945392f1ab4f4ccc 100644 --- a/Tests/GeoLib/TestSortSegments.cpp +++ b/Tests/GeoLib/TestSortSegments.cpp @@ -8,18 +8,20 @@ */ #include <gtest/gtest.h> + #include <numeric> -#include "Tests/GeoLib/AutoCheckGenerators.h" #include "GeoLib/AnalyticalGeometry.h" #include "GeoLib/LineSegment.h" +#include "Tests/GeoLib/AutoCheckGenerators.h" namespace ac = autocheck; class GeoLibSortLineSegments : public testing::Test { public: - using PointGenerator = ac::RandomCirclePointGeneratorXY<ac::generator<double>>; + using PointGenerator = + ac::RandomCirclePointGeneratorXY<ac::generator<double>>; using SymmSegmentGenerator = ac::SymmSegmentGeneratorXY<PointGenerator>; PointGenerator point_generator = PointGenerator( @@ -39,8 +41,7 @@ TEST_F(GeoLibSortLineSegments, SortSubSegments) auto partitionSegment = [](GeoLib::LineSegment const& s0, std::vector<std::size_t> const& sub_seg_ids, double const dt, - std::vector<GeoLib::LineSegment>& sub_segments) - { + std::vector<GeoLib::LineSegment>& sub_segments) { for (auto sub_seg_id : sub_seg_ids) { double t(dt * sub_seg_id); @@ -58,35 +59,34 @@ TEST_F(GeoLibSortLineSegments, SortSubSegments) } }; - auto checkSortedSubSegments = []( - GeoLib::LineSegment const& s0, - std::vector<GeoLib::LineSegment> const& sub_segments) - { - double eps(std::numeric_limits<double>::epsilon()); - if (MathLib::sqrDist(s0.getBeginPoint(), - sub_segments.front().getBeginPoint()) >= eps) - { - return false; - } - if (MathLib::sqrDist(s0.getEndPoint(), - sub_segments.back().getEndPoint()) >= eps) - { - return false; - } - for (std::size_t k(0); k < sub_segments.size() - 1; ++k) - { - if (MathLib::sqrDist(sub_segments[k].getEndPoint(), - sub_segments[k + 1].getBeginPoint()) >= eps) + auto checkSortedSubSegments = + [](GeoLib::LineSegment const& s0, + std::vector<GeoLib::LineSegment> const& sub_segments) { + double eps(std::numeric_limits<double>::epsilon()); + if (MathLib::sqrDist(s0.getBeginPoint(), + sub_segments.front().getBeginPoint()) >= eps) { return false; } - } - return true; - }; + if (MathLib::sqrDist(s0.getEndPoint(), + sub_segments.back().getEndPoint()) >= eps) + { + return false; + } + for (std::size_t k(0); k < sub_segments.size() - 1; ++k) + { + if (MathLib::sqrDist(sub_segments[k].getEndPoint(), + sub_segments[k + 1].getBeginPoint()) >= + eps) + { + return false; + } + } + return true; + }; auto testSortSegments = [partitionSegment, checkSortedSubSegments]( - GeoLib::LineSegment const& s0) - { + GeoLib::LineSegment const& s0) { std::size_t const n_sub_segments(4); double const dt(1.0 / static_cast<double>(n_sub_segments)); std::vector<std::size_t> sub_seg_ids(n_sub_segments); @@ -104,8 +104,7 @@ TEST_F(GeoLibSortLineSegments, SortSubSegments) return true; }; - ac::check<GeoLib::LineSegment>( - testSortSegments, 100, - ac::make_arbitrary(segment_generator), - gtest_reporter); + ac::check<GeoLib::LineSegment>(testSortSegments, 100, + ac::make_arbitrary(segment_generator), + gtest_reporter); } diff --git a/Tests/GeoLib/TestSurfaceIsPointInSurface.cpp b/Tests/GeoLib/TestSurfaceIsPointInSurface.cpp index 3c0cdaf282d9bad6e92784fbff01900198b20e8b..cd960fff6802e6d132fbdf07eb75d6c57ad5e548 100644 --- a/Tests/GeoLib/TestSurfaceIsPointInSurface.cpp +++ b/Tests/GeoLib/TestSurfaceIsPointInSurface.cpp @@ -9,27 +9,24 @@ * http://www.opengeosys.org/project/license */ +#include <gtest/gtest.h> + #include <array> +#include <boost/math/constants/constants.hpp> #include <memory> #include <random> #include <vector> -#include "gtest/gtest.h" - -#include <boost/math/constants/constants.hpp> - +#include "GeoLib/AnalyticalGeometry.h" #include "GeoLib/GEOObjects.h" #include "GeoLib/Point.h" #include "GeoLib/Surface.h" #include "GeoLib/Triangle.h" -#include "GeoLib/AnalyticalGeometry.h" - #include "MathLib/Point3d.h" - #include "MeshLib/Mesh.h" +#include "MeshLib/MeshGenerators/MeshGenerator.h" #include "MeshLib/Node.h" #include "MeshLib/convertMeshToGeo.h" -#include "MeshLib/MeshGenerators/MeshGenerator.h" inline double constant(double /*unused*/, double /*unused*/) { @@ -41,11 +38,11 @@ inline double coscos(double x, double y) return std::cos(x) * std::cos(y); } -inline MathLib::Point3d -getEdgeMiddlePoint(MathLib::Point3d const&a, MathLib::Point3d const& b) +inline MathLib::Point3d getEdgeMiddlePoint(MathLib::Point3d const& a, + MathLib::Point3d const& b) { - return MathLib::Point3d(std::array<double,3>({{ - (a[0]+b[0])/2, (a[1]+b[1])/2, (a[2]+b[2])/2}})); + return MathLib::Point3d(std::array<double, 3>( + {{(a[0] + b[0]) / 2, (a[1] + b[1]) / 2, (a[2] + b[2]) / 2}})); } inline std::tuple<MathLib::Point3d, MathLib::Point3d, MathLib::Point3d> @@ -61,15 +58,19 @@ getEdgeMiddlePoints(GeoLib::Triangle const& tri) inline Eigen::Matrix3d getRotMat(double alpha, double beta, double gamma) { Eigen::Matrix3d rot_mat; - rot_mat(0,0) = cos(alpha)*cos(gamma) - sin(alpha)*cos(beta)*sin(gamma); - rot_mat(0,1) = sin(alpha)*cos(gamma) + cos(alpha)*cos(beta)*sin(gamma); - rot_mat(0,2) = sin(beta)*sin(gamma); - rot_mat(1,0) = -cos(alpha)*sin(gamma) - sin(alpha)*cos(beta)*cos(gamma); - rot_mat(1,1) = -sin(alpha)*sin(gamma) + cos(alpha)*cos(beta)*cos(gamma); - rot_mat(1,2) = sin(beta)*cos(gamma); - rot_mat(2,0) = sin(alpha)*sin(beta); - rot_mat(2,1) = -cos(alpha)*sin(beta); - rot_mat(2,2) = cos(beta); + rot_mat(0, 0) = + cos(alpha) * cos(gamma) - sin(alpha) * cos(beta) * sin(gamma); + rot_mat(0, 1) = + sin(alpha) * cos(gamma) + cos(alpha) * cos(beta) * sin(gamma); + rot_mat(0, 2) = sin(beta) * sin(gamma); + rot_mat(1, 0) = + -cos(alpha) * sin(gamma) - sin(alpha) * cos(beta) * cos(gamma); + rot_mat(1, 1) = + -sin(alpha) * sin(gamma) + cos(alpha) * cos(beta) * cos(gamma); + rot_mat(1, 2) = sin(beta) * cos(gamma); + rot_mat(2, 0) = sin(alpha) * sin(beta); + rot_mat(2, 1) = -cos(alpha) * sin(beta); + rot_mat(2, 2) = cos(beta); return rot_mat; } @@ -79,7 +80,8 @@ TEST(GeoLib, SurfaceIsPointInSurface) surface_functions.emplace_back(constant); surface_functions.emplace_back(coscos); - for (const auto& f : surface_functions) { + for (const auto& f : surface_functions) + { std::random_device rd; std::string name("Surface"); @@ -87,14 +89,12 @@ TEST(GeoLib, SurfaceIsPointInSurface) std::mt19937 random_engine_mt19937(rd()); std::normal_distribution<> normal_dist_ll(-10, 2); std::normal_distribution<> normal_dist_ur(10, 2); - MathLib::Point3d ll(std::array<double,3>({{ - normal_dist_ll(random_engine_mt19937), - normal_dist_ll(random_engine_mt19937), - 0.0}})); - MathLib::Point3d ur(std::array<double,3>({{ - normal_dist_ur(random_engine_mt19937), - normal_dist_ur(random_engine_mt19937), - 0.0}})); + MathLib::Point3d ll(std::array<double, 3>( + {{normal_dist_ll(random_engine_mt19937), + normal_dist_ll(random_engine_mt19937), 0.0}})); + MathLib::Point3d ur(std::array<double, 3>( + {{normal_dist_ur(random_engine_mt19937), + normal_dist_ur(random_engine_mt19937), 0.0}})); for (std::size_t k(0); k < 3; ++k) { if (ll[k] > ur[k]) @@ -106,22 +106,20 @@ TEST(GeoLib, SurfaceIsPointInSurface) // random discretization of the domain std::default_random_engine re(rd()); std::uniform_int_distribution<std::size_t> uniform_dist(2, 25); - std::array<std::size_t,2> n_steps = {{uniform_dist(re),uniform_dist(re)}}; + std::array<std::size_t, 2> n_steps = { + {uniform_dist(re), uniform_dist(re)}}; std::unique_ptr<MeshLib::Mesh> sfc_mesh( - MeshLib::MeshGenerator::createSurfaceMesh( - name, ll, ur, n_steps, f - ) - ); + MeshLib::MeshGenerator::createSurfaceMesh(name, ll, ur, n_steps, + f)); // random rotation angles std::normal_distribution<> normal_dist_angles( 0, boost::math::double_constants::two_pi); - std::array<double,3> euler_angles = {{ - normal_dist_angles(random_engine_mt19937), - normal_dist_angles(random_engine_mt19937), - normal_dist_angles(random_engine_mt19937) - }}; + std::array<double, 3> euler_angles = { + {normal_dist_angles(random_engine_mt19937), + normal_dist_angles(random_engine_mt19937), + normal_dist_angles(random_engine_mt19937)}}; Eigen::Matrix3d rot_mat( getRotMat(euler_angles[0], euler_angles[1], euler_angles[2])); @@ -137,14 +135,16 @@ TEST(GeoLib, SurfaceIsPointInSurface) GeoLib::GEOObjects geometries; MeshLib::convertMeshToGeo(*sfc_mesh, geometries); - std::vector<GeoLib::Surface*> const& sfcs(*geometries.getSurfaceVec(name)); - GeoLib::Surface const*const sfc(sfcs.front()); + std::vector<GeoLib::Surface*> const& sfcs( + *geometries.getSurfaceVec(name)); + GeoLib::Surface const* const sfc(sfcs.front()); std::vector<GeoLib::Point*> const& pnts(*geometries.getPointVec(name)); double const eps(std::numeric_limits<double>::epsilon()); // test triangle edge point of the surface triangles - for (auto const p : pnts) { + for (auto const p : pnts) + { EXPECT_TRUE(sfc->isPntInSfc(*p, eps)); MathLib::Point3d q(*p); for (std::size_t k(0); k < 3; ++k) @@ -154,11 +154,12 @@ TEST(GeoLib, SurfaceIsPointInSurface) EXPECT_FALSE(sfc->isPntInSfc(q, eps)); } // test edge middle points of the triangles - for (std::size_t k(0); k<sfc->getNumberOfTriangles(); ++k) { + for (std::size_t k(0); k < sfc->getNumberOfTriangles(); ++k) + { MathLib::Point3d p; MathLib::Point3d q; MathLib::Point3d r; - std::tie(p,q,r) = getEdgeMiddlePoints(*(*sfc)[k]); + std::tie(p, q, r) = getEdgeMiddlePoints(*(*sfc)[k]); EXPECT_TRUE(sfc->isPntInSfc(p, eps)); EXPECT_TRUE(sfc->isPntInSfc(q, eps)); EXPECT_TRUE(sfc->isPntInSfc(r, eps)); diff --git a/Tests/MaterialLib/TestCapillaryPressureSaturationModel.cpp b/Tests/MaterialLib/TestCapillaryPressureSaturationModel.cpp index f4a93f22572ae46c17791036bd4f7489e72092e2..46516f88929a2be2cb84abbf86915eae33c1bfcb 100644 --- a/Tests/MaterialLib/TestCapillaryPressureSaturationModel.cpp +++ b/Tests/MaterialLib/TestCapillaryPressureSaturationModel.cpp @@ -16,11 +16,9 @@ #include <vector> #include "BaseLib/ConfigTree.h" - -#include "Tests/TestTools.h" - #include "MaterialLib/PorousMedium/UnsaturatedProperty/CapillaryPressure/CapillaryPressureSaturation.h" #include "MaterialLib/PorousMedium/UnsaturatedProperty/CapillaryPressure/CreateCapillaryPressureModel.h" +#include "Tests/TestTools.h" using namespace MaterialLib; using namespace MaterialLib::PorousMedium; diff --git a/Tests/MaterialLib/TestDimensionLessGibbsFreeEnergy.cpp b/Tests/MaterialLib/TestDimensionLessGibbsFreeEnergy.cpp index ddc916a4c68d779328606f3a2bf010d1afd1bb24..ea5dd33fbce388886c948eccb8c436e27670803d 100644 --- a/Tests/MaterialLib/TestDimensionLessGibbsFreeEnergy.cpp +++ b/Tests/MaterialLib/TestDimensionLessGibbsFreeEnergy.cpp @@ -13,9 +13,8 @@ #include <memory> -#include "Tests/TestTools.h" - #include "MaterialLib/Fluid/GibbsFreeEnergy/DimensionLessGibbsFreeEnergyRegion1.h" +#include "Tests/TestTools.h" using namespace MaterialLib; using namespace MaterialLib::Fluid; diff --git a/Tests/MaterialLib/TestFluidDensity.cpp b/Tests/MaterialLib/TestFluidDensity.cpp index 32d77396b2fe8cc7aa9b93bd534659b7a94f076f..7b781fa664d3d1cf626554b8392d990d1055a949 100644 --- a/Tests/MaterialLib/TestFluidDensity.cpp +++ b/Tests/MaterialLib/TestFluidDensity.cpp @@ -15,10 +15,9 @@ #include <memory> -#include "Tests/TestTools.h" - #include "MaterialLib/Fluid/Density/CreateFluidDensityModel.h" #include "MaterialLib/PhysicalConstant.h" +#include "Tests/TestTools.h" using namespace MaterialLib; using namespace MaterialLib::Fluid; diff --git a/Tests/MaterialLib/TestFluidProperties.cpp b/Tests/MaterialLib/TestFluidProperties.cpp index bbc03b377427dcd9e617309f4f9e41f73a810ffd..60a3cc0aac330af2e796dca230ad81ede320ea4d 100644 --- a/Tests/MaterialLib/TestFluidProperties.cpp +++ b/Tests/MaterialLib/TestFluidProperties.cpp @@ -16,12 +16,10 @@ #include <cmath> #include <memory> -#include "Tests/TestTools.h" - #include "BaseLib/ConfigTree.h" - #include "MaterialLib/Fluid/FluidProperties/CreateFluidProperties.h" #include "MaterialLib/Fluid/FluidProperties/FluidProperties.h" +#include "Tests/TestTools.h" using namespace MaterialLib; using namespace MaterialLib::Fluid; @@ -64,7 +62,7 @@ TEST(MaterialFluidProperties, checkPrimaryVariableDependentFluidProperties) fluid_model->getValue(FluidPropertyType::Viscosity, vars), 1.e-10); const double dmu_dT_expected = - -1.e-3/368 * std::exp(-(vars[0] - 293) / 368); + -1.e-3 / 368 * std::exp(-(vars[0] - 293) / 368); ASSERT_NEAR( dmu_dT_expected, fluid_model->getdValue(FluidPropertyType::Viscosity, vars, @@ -117,7 +115,8 @@ TEST(MaterialFluidProperties, checkFluidPropertiesWithDensityDependentModels_T) const double perturbation = 1.e-6; vars[0] += perturbation; const double rho1 = fluid_model->getValue(FluidPropertyType::Density, vars); - const double mu1 = fluid_model->getValue(FluidPropertyType::Viscosity, vars); + const double mu1 = + fluid_model->getValue(FluidPropertyType::Viscosity, vars); ASSERT_NEAR((rho1 - rho) / perturbation, drho_dT, 1.e-7); ASSERT_NEAR((mu1 - mu) / perturbation, dmu_dT, 1.e-10); @@ -156,7 +155,8 @@ TEST(MaterialFluidProperties, checkFluidPropertiesWithDensityDependentModels_dp) const double perturbation = 1.e-6; vars[1] += perturbation; const double rho1 = fluid_model->getValue(FluidPropertyType::Density, vars); - const double mu1 = fluid_model->getValue(FluidPropertyType::Viscosity, vars); + const double mu1 = + fluid_model->getValue(FluidPropertyType::Viscosity, vars); // Only check d()/drho * drho/dp (FluidPropertiesWithDensityDependentModels) // The other functionalities of fluid property models are checked in other diff --git a/Tests/MaterialLib/TestFluidSpecificHeatCapacityModel.cpp b/Tests/MaterialLib/TestFluidSpecificHeatCapacityModel.cpp index 84e8965f0e63753e185c63a6a04bfc7948627f36..65ca9a09dbfa4af1789fbe678da3ac4ef97b8a01 100644 --- a/Tests/MaterialLib/TestFluidSpecificHeatCapacityModel.cpp +++ b/Tests/MaterialLib/TestFluidSpecificHeatCapacityModel.cpp @@ -13,14 +13,12 @@ #include <memory> -#include "Tests/TestTools.h" - #include "BaseLib/ConfigTree.h" - -#include "MaterialLib/PhysicalConstant.h" -#include "MaterialLib/Fluid/FluidProperty.h" #include "MaterialLib/Fluid/ConstantFluidProperty.h" +#include "MaterialLib/Fluid/FluidProperty.h" #include "MaterialLib/Fluid/SpecificHeatCapacity/CreateSpecificFluidHeatCapacityModel.h" +#include "MaterialLib/PhysicalConstant.h" +#include "Tests/TestTools.h" using namespace MaterialLib; using namespace MaterialLib::Fluid; diff --git a/Tests/MaterialLib/TestFluidThermalConductivityModel.cpp b/Tests/MaterialLib/TestFluidThermalConductivityModel.cpp index 03e2b9e541365ae988a4a9360068807bcde54f90..dfb45cdb58d9f5426c067a4e4ad566e6b30f0e08 100644 --- a/Tests/MaterialLib/TestFluidThermalConductivityModel.cpp +++ b/Tests/MaterialLib/TestFluidThermalConductivityModel.cpp @@ -13,15 +13,13 @@ #include <memory> -#include "Tests/TestTools.h" - #include "BaseLib/ConfigTree.h" - -#include "MaterialLib/PhysicalConstant.h" -#include "MaterialLib/Fluid/FluidProperty.h" #include "MaterialLib/Fluid/ConstantFluidProperty.h" -#include "MaterialLib/Fluid/ThermalConductivity/CreateFluidThermalConductivityModel.h" #include "MaterialLib/Fluid/Density/LiquidDensity.h" +#include "MaterialLib/Fluid/FluidProperty.h" +#include "MaterialLib/Fluid/ThermalConductivity/CreateFluidThermalConductivityModel.h" +#include "MaterialLib/PhysicalConstant.h" +#include "Tests/TestTools.h" using namespace MaterialLib; using namespace MaterialLib::Fluid; diff --git a/Tests/MaterialLib/TestFluidViscosity.cpp b/Tests/MaterialLib/TestFluidViscosity.cpp index f6b18e8ca61e7bedf1fd93deaefc469db9624d07..5609cc8a890f70a37ac50159485ce3a5850a1960 100644 --- a/Tests/MaterialLib/TestFluidViscosity.cpp +++ b/Tests/MaterialLib/TestFluidViscosity.cpp @@ -13,13 +13,12 @@ #include <gtest/gtest.h> -#include <memory> #include <cmath> - -#include "Tests/TestTools.h" +#include <memory> #include "MaterialLib/Fluid/Viscosity/CreateViscosityModel.h" #include "MaterialLib/PhysicalConstant.h" +#include "Tests/TestTools.h" using namespace MaterialLib; using namespace MaterialLib::Fluid; @@ -65,7 +64,7 @@ TEST(Material, checkTemperatureDependentViscosity) const double mu_expected = 1.e-3 * std::exp(-(vars[0] - 293) / 368); ASSERT_NEAR(mu_expected, mu->getValue(vars), 1.e-10); const double dmu_dT_expected = - -1.e-3/368 * std::exp(-(vars[0] - 293) / 368); + -1.e-3 / 368 * std::exp(-(vars[0] - 293) / 368); ASSERT_NEAR( dmu_dT_expected, mu->getdValue(vars, MaterialLib::Fluid::PropertyVariableType::T), diff --git a/Tests/MaterialLib/TestFractureModels.cpp b/Tests/MaterialLib/TestFractureModels.cpp index 3497c392b3a43f943af45cfb659370eecb3fab42..251899047ac2ebaca0030d49975dde3b7af825e8 100644 --- a/Tests/MaterialLib/TestFractureModels.cpp +++ b/Tests/MaterialLib/TestFractureModels.cpp @@ -373,7 +373,8 @@ TEST(MaterialLib_Fracture, Coulomb3D_negative_t1t2) Eigen::Vector3d const sigma0(-3.46e6 / std::sqrt(2), -3.46e6 / std::sqrt(2), -2e6); Eigen::Vector3d const sigma_prev = sigma0; - Eigen::Vector3d const w(-1.08e-5/std::sqrt(2), -1.08e-5/std::sqrt(2), -0.25e-5); + Eigen::Vector3d const w(-1.08e-5 / std::sqrt(2), -1.08e-5 / std::sqrt(2), + -0.25e-5); // Result vectors, not initialized. Eigen::Vector3d sigma; @@ -422,7 +423,8 @@ TEST(MaterialLib_Fracture, Coulomb3D_negative_t1_positive_t2) Eigen::Vector3d const sigma0(-3.46e6 / std::sqrt(2), 3.46e6 / std::sqrt(2), -2e6); Eigen::Vector3d const sigma_prev = sigma0; - Eigen::Vector3d const w(-1.08e-5/std::sqrt(2), 1.08e-5/std::sqrt(2), -0.25e-5); + Eigen::Vector3d const w(-1.08e-5 / std::sqrt(2), 1.08e-5 / std::sqrt(2), + -0.25e-5); // Result vectors, not initialized. Eigen::Vector3d sigma; @@ -447,4 +449,3 @@ TEST(MaterialLib_Fracture, Coulomb3D_negative_t1_positive_t2) EXPECT_NEAR(0, state->getShearYieldFunctionValue(), 1e-9); // same as newton tolerance } - diff --git a/Tests/MaterialLib/TestMPLCapillaryPressureRegularizedVanGenuchten.cpp b/Tests/MaterialLib/TestMPLCapillaryPressureRegularizedVanGenuchten.cpp index 0d2330d8dc81f93a532ff72c0330af3aa486943d..e06a8147ccc6a3374a36f10fef1d5d4e6464899e 100644 --- a/Tests/MaterialLib/TestMPLCapillaryPressureRegularizedVanGenuchten.cpp +++ b/Tests/MaterialLib/TestMPLCapillaryPressureRegularizedVanGenuchten.cpp @@ -17,11 +17,9 @@ #include <limits> #include "BaseLib/ConfigTree.h" - #include "MaterialLib/MPL/Medium.h" -#include "MaterialLib/MPL/Properties/CapillaryPressureSaturation/CreateCapillaryPressureRegularizedVanGenuchten.h" #include "MaterialLib/MPL/Properties/CapillaryPressureSaturation/CapillaryPressureRegularizedVanGenuchten.h" - +#include "MaterialLib/MPL/Properties/CapillaryPressureSaturation/CreateCapillaryPressureRegularizedVanGenuchten.h" #include "TestMPL.h" #include "Tests/TestTools.h" diff --git a/Tests/MaterialLib/TestMPLExponential.cpp b/Tests/MaterialLib/TestMPLExponential.cpp index c4515fc08b00ac5f27fffac58f21df929dbc8921..042f3659e8e2d0229b619d14069c1de1692b2ba0 100644 --- a/Tests/MaterialLib/TestMPLExponential.cpp +++ b/Tests/MaterialLib/TestMPLExponential.cpp @@ -61,7 +61,7 @@ TEST_F(MaterialPropertyLibExponentialProperty, TestNumericalDerivatives) return p->template value<double>(variable_array, pos, time, dt); }; - auto f = [&](double const T){ + auto f = [&](double const T) { MPL::VariableArray variable_array; variable_array[static_cast<int>(MPL::Variable::temperature)] = T; double const v = @@ -85,8 +85,7 @@ TEST_F(MaterialPropertyLibExponentialProperty, TestNumericalDerivatives) // Limit values to avoid +-inf. auto gen = ac::IntervalGenerator(-100., 100.); - ac::check<double>( - f, 10000, ac::make_arbitrary(gen), gtest_reporter); + ac::check<double>(f, 10000, ac::make_arbitrary(gen), gtest_reporter); } TEST(MaterialPropertyLib, Exponential) @@ -97,7 +96,8 @@ TEST(MaterialPropertyLib, Exponential) double const factor = 1 / 75.0; MPL::ExponentData const exp_data{MPL::Variable::temperature, reference_condition, factor}; - MPL::Property const& p = MPL::Exponential{"exponential", y_offset, y_ref, exp_data}; + MPL::Property const& p = + MPL::Exponential{"exponential", y_offset, y_ref, exp_data}; double const T = 20.; MPL::VariableArray variable_array; diff --git a/Tests/MaterialLib/TestMPLIdealGasLaw.cpp b/Tests/MaterialLib/TestMPLIdealGasLaw.cpp index ea8f908a9ce805262740af7e417e7c22b957b9e4..d23cf8a61f15114215b848668d93e2188f9bc61b 100644 --- a/Tests/MaterialLib/TestMPLIdealGasLaw.cpp +++ b/Tests/MaterialLib/TestMPLIdealGasLaw.cpp @@ -9,20 +9,20 @@ * */ #include <gtest/gtest.h> -#include <sstream> -#include "TestMPL.h" -#include "Tests/TestTools.h" +#include <sstream> #include "MaterialLib/MPL/Medium.h" #include "MaterialLib/MPL/Properties/IdealGasLaw.h" #include "MaterialLib/PhysicalConstant.h" +#include "TestMPL.h" +#include "Tests/TestTools.h" TEST(MaterialPropertyLib, IdealGasLawOfPurePhase) { - const double pressure_norm = 101325.0; // Pa - const double temperature_norm = 273.15; // K - const double molar_mass_air = 0.02905; // kg/mol + const double pressure_norm = 101325.0; // Pa + const double temperature_norm = 273.15; // K + const double molar_mass_air = 0.02905; // kg/mol const auto R = MaterialLib::PhysicalConstant::IdealGasConstant; const double density_norm_air = diff --git a/Tests/MaterialLib/TestMPLLinear.cpp b/Tests/MaterialLib/TestMPLLinear.cpp index 185b0ad36b488c9ade8e062f62444edd838eeff0..f6a5bef0b2a59f0d62073b77d4e78ddf5fa55d98 100644 --- a/Tests/MaterialLib/TestMPLLinear.cpp +++ b/Tests/MaterialLib/TestMPLLinear.cpp @@ -48,4 +48,3 @@ TEST(MaterialPropertyLib, Linear) MaterialPropertyLib::Variable::temperature, pos, time, dt)), 0.0); } - diff --git a/Tests/MaterialLib/TestMPLParseMaterial.cpp b/Tests/MaterialLib/TestMPLParseMaterial.cpp index 4c0646761aedf2687d608f53c618771ff9fdf5bb..be498ec7ef53374183313573888fcd2321664814 100644 --- a/Tests/MaterialLib/TestMPLParseMaterial.cpp +++ b/Tests/MaterialLib/TestMPLParseMaterial.cpp @@ -15,11 +15,10 @@ #include <sstream> +#include "MaterialLib/MPL/Medium.h" #include "TestMPL.h" #include "Tests/TestTools.h" -#include "MaterialLib/MPL/Medium.h" - namespace MPL = MaterialPropertyLib; /// A simple structure for a string-based component used to create diff --git a/Tests/MaterialLib/TestMPLPermeabilityMohrCoulombFailureIndexModel.cpp b/Tests/MaterialLib/TestMPLPermeabilityMohrCoulombFailureIndexModel.cpp index f200ff745e1afe6a59ba01b8a65182b385aa6b8e..a15e28ff2e34f4824c040e2a2dfabdcd3d561df0 100644 --- a/Tests/MaterialLib/TestMPLPermeabilityMohrCoulombFailureIndexModel.cpp +++ b/Tests/MaterialLib/TestMPLPermeabilityMohrCoulombFailureIndexModel.cpp @@ -49,8 +49,8 @@ TEST(MaterialPropertyLib, PermeabilityMohrCoulombFailureIndexModel) stress[5] = -1.39944e+7; MPL::VariableArray vars; - vars[static_cast<int>(MPL::Variable::total_stress)].emplace<SymmetricTensor>( - stress); + vars[static_cast<int>(MPL::Variable::total_stress)] + .emplace<SymmetricTensor>(stress); ParameterLib::SpatialPosition const pos; double const t = std::numeric_limits<double>::quiet_NaN(); diff --git a/Tests/MaterialLib/TestMPLRelPermBrooksCorey.cpp b/Tests/MaterialLib/TestMPLRelPermBrooksCorey.cpp index 506a624ef3d8bd63b3c742203692a110d5c72475..1382fc84b3533010bc782c5b1feb7a6ee58a8a04 100644 --- a/Tests/MaterialLib/TestMPLRelPermBrooksCorey.cpp +++ b/Tests/MaterialLib/TestMPLRelPermBrooksCorey.cpp @@ -9,13 +9,13 @@ * */ #include <gtest/gtest.h> -#include <sstream> -#include "TestMPL.h" -#include "Tests/TestTools.h" +#include <sstream> #include "MaterialLib/MPL/Medium.h" #include "MaterialLib/MPL/Properties/RelativePermeability/RelPermBrooksCorey.h" +#include "TestMPL.h" +#include "Tests/TestTools.h" TEST(MaterialPropertyLib, RelPermBrooksCorey) { diff --git a/Tests/MaterialLib/TestMPLRelPermLiakopoulos.cpp b/Tests/MaterialLib/TestMPLRelPermLiakopoulos.cpp index 240dcead842cfdcfd71971ac70e658594e3db5b8..71b96c0f16035abe8ae3a9d1f6bb51e9a00269ce 100644 --- a/Tests/MaterialLib/TestMPLRelPermLiakopoulos.cpp +++ b/Tests/MaterialLib/TestMPLRelPermLiakopoulos.cpp @@ -9,13 +9,13 @@ * */ #include <gtest/gtest.h> -#include <sstream> -#include "TestMPL.h" -#include "Tests/TestTools.h" +#include <sstream> #include "MaterialLib/MPL/Medium.h" #include "MaterialLib/MPL/Properties/RelativePermeability/RelPermLiakopoulos.h" +#include "TestMPL.h" +#include "Tests/TestTools.h" TEST(MaterialPropertyLib, RelPermLiakopoulos) { diff --git a/Tests/MaterialLib/TestMPLRelPermNonWettingPhaseVanGenuchtenMualem.cpp b/Tests/MaterialLib/TestMPLRelPermNonWettingPhaseVanGenuchtenMualem.cpp index 20fe5339e27ab3001a89638be5ef14afaed92c55..ac58c7dcb68c4c109c4a9f72ad6beb74738b00e4 100644 --- a/Tests/MaterialLib/TestMPLRelPermNonWettingPhaseVanGenuchtenMualem.cpp +++ b/Tests/MaterialLib/TestMPLRelPermNonWettingPhaseVanGenuchtenMualem.cpp @@ -63,8 +63,8 @@ TEST(MaterialPropertyLib, RelPermNonWettingPhaseVanGenuchtenMualem) const double S_n_r = 0.05; const double S_n_max = 0.9; - const double S_L_r = 0.1; //1.0 - S_n_max; - const double S_L_max = 0.95; //1.0 - S_n_r; + const double S_L_r = 0.1; // 1.0 - S_n_max; + const double S_L_max = 0.95; // 1.0 - S_n_r; for (std::size_t i = 0; i < S_L.size(); i++) { MPL::VariableArray variable_array; diff --git a/Tests/MaterialLib/TestMPLSaturationBrooksCorey.cpp b/Tests/MaterialLib/TestMPLSaturationBrooksCorey.cpp index 13bb9a942ecb4e38ca97731dd1d8595482d8556a..8fa663cbac3bb1ba0f807cc028fedf29201cfc83 100644 --- a/Tests/MaterialLib/TestMPLSaturationBrooksCorey.cpp +++ b/Tests/MaterialLib/TestMPLSaturationBrooksCorey.cpp @@ -9,13 +9,13 @@ * */ #include <gtest/gtest.h> -#include <sstream> -#include "TestMPL.h" -#include "Tests/TestTools.h" +#include <sstream> #include "MaterialLib/MPL/Medium.h" #include "MaterialLib/MPL/Properties/CapillaryPressureSaturation/SaturationBrooksCorey.h" +#include "TestMPL.h" +#include "Tests/TestTools.h" TEST(MaterialPropertyLib, SaturationBrooksCorey) { diff --git a/Tests/MaterialLib/TestMPLSaturationLiakopoulos.cpp b/Tests/MaterialLib/TestMPLSaturationLiakopoulos.cpp index 800ea117299570a77a101d20b077ab8b698362de..adf4faba3e0f1d444a7487a750d939dc194709fb 100644 --- a/Tests/MaterialLib/TestMPLSaturationLiakopoulos.cpp +++ b/Tests/MaterialLib/TestMPLSaturationLiakopoulos.cpp @@ -9,13 +9,13 @@ * */ #include <gtest/gtest.h> -#include <sstream> -#include "TestMPL.h" -#include "Tests/TestTools.h" +#include <sstream> #include "MaterialLib/MPL/Medium.h" #include "MaterialLib/MPL/Properties/CapillaryPressureSaturation/SaturationLiakopoulos.h" +#include "TestMPL.h" +#include "Tests/TestTools.h" TEST(MaterialPropertyLib, SaturationLiakopoulos) { diff --git a/Tests/MaterialLib/TestMPLSoilThermalConductivitySomerton.cpp b/Tests/MaterialLib/TestMPLSoilThermalConductivitySomerton.cpp index 00a4dde51273c0ed8400f06b55a47d16382cfb65..5e3992d62debd54023ac1501d835ff7e24a2f495 100644 --- a/Tests/MaterialLib/TestMPLSoilThermalConductivitySomerton.cpp +++ b/Tests/MaterialLib/TestMPLSoilThermalConductivitySomerton.cpp @@ -111,8 +111,8 @@ TEST(MaterialPropertyLib, SoilThermalConductivitySomerton1D) << "for expected derivative of thermal conductivity with " "respect to saturation " << 0.0 - << " and for computed derivative of thermal conductivity " - "with respect to saturation." + << " and for computed derivative of thermal conductivity with " + "respect to saturation." << computed_dk_T_dS; } } @@ -132,10 +132,11 @@ TEST(MaterialPropertyLib, SoilThermalConductivitySomerton1D) pos, t, dt); ASSERT_LE(std::fabs(0.0 - computed_dk_T_dS), 1e-10) - << "for expected derivative of thermal conductivity with " - "respect to saturation " - << 0.0 << " and for computed derivative of thermal conductivity " - "with respect to saturation." + << "for expected derivative of thermal conductivity with respect " + "to saturation " + << 0.0 + << " and for computed derivative of thermal conductivity with " + "respect to saturation." << computed_dk_T_dS; } @@ -175,11 +176,11 @@ TEST(MaterialPropertyLib, SoilThermalConductivitySomerton1D) pos, t, dt); ASSERT_LE(std::fabs(analytic_dk_T_dS - approximated_dk_T_dS), 1e-5) - << "for expected derivative of thermal conductivity with " - "respect to saturation " + << "for expected derivative of thermal conductivity with respect " + "to saturation " << analytic_dk_T_dS - << " and for computed derivative of thermal conductivity " - "with respect to saturation." + << " and for computed derivative of thermal conductivity with " + "respect to saturation." << approximated_dk_T_dS; } } @@ -281,8 +282,8 @@ TEST(MaterialPropertyLib, SoilThermalConductivitySomerton3D) << "for expected derivative of thermal conductivity with " "respect to saturation " << 0.0 - << " and for computed derivative of thermal conductivity " - "with respect to saturation." + << " and for computed derivative of thermal conductivity with " + "respect to saturation." << computed_dk_T_dS(k, k); } } @@ -334,8 +335,8 @@ TEST(MaterialPropertyLib, SoilThermalConductivitySomerton3D) << "for expected derivative of thermal conductivity with " "respect to saturation " << analytic_dk_T_dS(k, k) - << " and for computed derivative of thermal conductivity " - "with respect to saturation." + << " and for computed derivative of thermal conductivity with " + "respect to saturation." << approximated_dk_T_dS; } } diff --git a/Tests/MaterialLib/TestMPLWaterVapourDensity.cpp b/Tests/MaterialLib/TestMPLWaterVapourDensity.cpp index 113c1685d1f0b47be567727931a74043f64aef19..ad4c1fe8c454a1c40fc9da4d96542813cd17c889 100644 --- a/Tests/MaterialLib/TestMPLWaterVapourDensity.cpp +++ b/Tests/MaterialLib/TestMPLWaterVapourDensity.cpp @@ -87,8 +87,8 @@ TEST(MaterialPropertyLib, WaterVapourDensity) << "for expected derivative of water vapour density with " "respect to temperature " << approximated_drho_wv_dT - << " and for computed derivative of water vapour density " - "with respect to temperature." + << " and for computed derivative of water vapour density with " + "respect to temperature." << analytic_drho_wv_dT; } } diff --git a/Tests/MaterialLib/TestMPLWaterVapourLatentHeat.cpp b/Tests/MaterialLib/TestMPLWaterVapourLatentHeat.cpp index b07370e43108bc4617405e99bebb7472421c44bc..0e48936e1cde0fa034645a661a6003293f32e341 100644 --- a/Tests/MaterialLib/TestMPLWaterVapourLatentHeat.cpp +++ b/Tests/MaterialLib/TestMPLWaterVapourLatentHeat.cpp @@ -73,8 +73,8 @@ TEST(MaterialPropertyLib, LinearWaterVapourLatentHeat) << "for expected derivative of water vapour latent heat with " "respect to temperature " << approximated_dLw_dT - << " and for computed derivative of water vapour latent heat " - "with respect to temperature." + << " and for computed derivative of water vapour latent heat with " + "respect to temperature." << analytic_dLw_dT; } } diff --git a/Tests/MaterialLib/TestPorousMediumStorage.cpp b/Tests/MaterialLib/TestPorousMediumStorage.cpp index bc475ed885c79afd13c1c3fac3b87aeb40a12447..9af8efaa0af3e673dfdc54a55da8208524b12b5f 100644 --- a/Tests/MaterialLib/TestPorousMediumStorage.cpp +++ b/Tests/MaterialLib/TestPorousMediumStorage.cpp @@ -13,11 +13,10 @@ #include <memory> -#include "Tests/TestTools.h" #include "BaseLib/ConfigTree.h" - #include "MaterialLib/PorousMedium/Storage/ConstantStorage.h" #include "MaterialLib/PorousMedium/Storage/createStorageModel.h" +#include "Tests/TestTools.h" using namespace MaterialLib; using namespace MaterialLib::PorousMedium; @@ -43,4 +42,3 @@ TEST(Material, checkConstantStorage) const double var = 0; ASSERT_EQ(1.e-4, eta->getValue(var)); } - diff --git a/Tests/MaterialLib/TestRelativePermeabilityModel.cpp b/Tests/MaterialLib/TestRelativePermeabilityModel.cpp index d36b889f5bc6ed7470ec10ad2740d56d9930ee35..6b79119e64a494dd20c9a504ee03cc16067db973 100644 --- a/Tests/MaterialLib/TestRelativePermeabilityModel.cpp +++ b/Tests/MaterialLib/TestRelativePermeabilityModel.cpp @@ -16,11 +16,9 @@ #include <vector> #include "BaseLib/ConfigTree.h" - -#include "Tests/TestTools.h" - -#include "MaterialLib/PorousMedium/UnsaturatedProperty/RelativePermeability/RelativePermeability.h" #include "MaterialLib/PorousMedium/UnsaturatedProperty/RelativePermeability/CreateRelativePermeabilityModel.h" +#include "MaterialLib/PorousMedium/UnsaturatedProperty/RelativePermeability/RelativePermeability.h" +#include "Tests/TestTools.h" using namespace MaterialLib; using namespace MaterialLib::PorousMedium; diff --git a/Tests/MaterialLib/TestSaturationDependentHeatConduction.cpp b/Tests/MaterialLib/TestSaturationDependentHeatConduction.cpp index 3768fda51d295b10116ec19e2b77abda22ae397a..fd9bbd894722d23001f131b6d1d0abc565fa2f76 100644 --- a/Tests/MaterialLib/TestSaturationDependentHeatConduction.cpp +++ b/Tests/MaterialLib/TestSaturationDependentHeatConduction.cpp @@ -28,8 +28,7 @@ TEST(MaterialPropertyLib, SaturationDependentHeatConduction) double const k_wet = 1.5; auto const k_model_eff = MPL::SaturationDependentHeatConduction( - "thermal_conductivity", k_dry, k_wet); - + "thermal_conductivity", k_dry, k_wet); ParameterLib::SpatialPosition const pos; double const t = std::numeric_limits<double>::quiet_NaN(); diff --git a/Tests/MathLib/KelvinVector.cpp b/Tests/MathLib/KelvinVector.cpp index 51f0185b9661c0e6514260b33c3446b854a42131..6a8ed9cd7fa3b2508dff22f1e156bdad265d609e 100644 --- a/Tests/MathLib/KelvinVector.cpp +++ b/Tests/MathLib/KelvinVector.cpp @@ -7,10 +7,10 @@ * http://www.opengeosys.org/project/license */ -#include <gtest/gtest.h> - #include "MathLib/KelvinVector.h" +#include <gtest/gtest.h> + #include "Tests/AutoCheckTools.h" using namespace MathLib::KelvinVector; diff --git a/Tests/MathLib/TestDividedByPlane.cpp b/Tests/MathLib/TestDividedByPlane.cpp index 72213c938e38d2ced0660e0f2880b8785c331614..ec5a209065efecdee2190d9c6c565c2c0c5178f8 100644 --- a/Tests/MathLib/TestDividedByPlane.cpp +++ b/Tests/MathLib/TestDividedByPlane.cpp @@ -20,10 +20,10 @@ TEST(MathLib, TestDividedByPlane) { // xy plane - MathLib::Point3d a(std::array<double,3>{{0, 0, 0}}); - MathLib::Point3d b(std::array<double,3>{{1, 0, 0}}); - MathLib::Point3d c(std::array<double,3>{{0, 1, 0}}); - MathLib::Point3d d(std::array<double,3>{{1, 1, 0}}); + MathLib::Point3d a(std::array<double, 3>{{0, 0, 0}}); + MathLib::Point3d b(std::array<double, 3>{{1, 0, 0}}); + MathLib::Point3d c(std::array<double, 3>{{0, 1, 0}}); + MathLib::Point3d d(std::array<double, 3>{{1, 1, 0}}); bool result = MathLib::dividedByPlane(a, d, b, c); ASSERT_TRUE(result); @@ -31,19 +31,19 @@ TEST(MathLib, TestDividedByPlane) result = MathLib::dividedByPlane(b, c, a, d); ASSERT_TRUE(result); - d = MathLib::Point3d(std::array<double,3>{{0.1, 0.1, 0}}); + d = MathLib::Point3d(std::array<double, 3>{{0.1, 0.1, 0}}); result = MathLib::dividedByPlane(b, c, a, d); ASSERT_FALSE(result); // xz plane - c = MathLib::Point3d(std::array<double,3>{{0, 0, 1}}); - d = MathLib::Point3d(std::array<double,3>{{1, 0, 1}}); + c = MathLib::Point3d(std::array<double, 3>{{0, 0, 1}}); + d = MathLib::Point3d(std::array<double, 3>{{1, 0, 1}}); result = MathLib::dividedByPlane(a, d, b, c); ASSERT_TRUE(result); // yz plane - b = MathLib::Point3d(std::array<double,3>{{0, 1, 0}}); - d = MathLib::Point3d(std::array<double,3>{{0, 1, 1}}); + b = MathLib::Point3d(std::array<double, 3>{{0, 1, 0}}); + d = MathLib::Point3d(std::array<double, 3>{{0, 1, 1}}); result = MathLib::dividedByPlane(a, d, b, c); ASSERT_TRUE(result); } diff --git a/Tests/MathLib/TestEigenCSR.cpp b/Tests/MathLib/TestEigenCSR.cpp index 8f024df587398e6756efd4e1c3f786e6b2b246fe..fc1e54091bc598479def5dcc72cee9fd315099bf 100644 --- a/Tests/MathLib/TestEigenCSR.cpp +++ b/Tests/MathLib/TestEigenCSR.cpp @@ -9,16 +9,14 @@ #include <gtest/gtest.h> -#include <vector> -#include <numeric> - #include <Eigen/Sparse> - +#include <numeric> +#include <vector> /** - * This test case checks if the internal Eigen::SparseMatrix compressed storage format - * is a conventional CSR matrix. Currently this is the case, but it is not guaranteed - * for all time. + * This test case checks if the internal Eigen::SparseMatrix compressed storage + * format is a conventional CSR matrix. Currently this is the case, but it is + * not guaranteed for all time. * * Cf. section "Sparse matrix format" on page * http://eigen.tuxfamily.org/dox/group__TutorialSparse.html @@ -32,21 +30,24 @@ TEST(MathLibEigen, Eigen2CSR) // set up sparsity pattern std::vector<int> pat(nrows); - for (std::size_t i=0; i<nrows; ++i) + for (std::size_t i = 0; i < nrows; ++i) { - if (i==0 || i==nrows-1) { + if (i == 0 || i == nrows - 1) + { pat[i] = 2; - } else { + } + else + { pat[i] = 3; } } // CSR representation of the matrix std::vector<double> values; - std::vector<int> ia(nrows+1); // row offsets - std::vector<int> ja; // column indices + std::vector<int> ia(nrows + 1); // row offsets + std::vector<int> ja; // column indices - std::partial_sum(pat.begin(), pat.end(), ia.begin()+1); + std::partial_sum(pat.begin(), pat.end(), ia.begin() + 1); const int nnz = ia.back(); values.reserve(nnz); @@ -55,8 +56,10 @@ TEST(MathLibEigen, Eigen2CSR) mat.reserve(pat); // init matrix, build CSR matrix in parallel - for (int row=0; row<nrows; ++row) { - for (int col = -1; col<=1; ++col) { + for (int row = 0; row < nrows; ++row) + { + for (int col = -1; col <= 1; ++col) + { int cidx = row + col; if (cidx < 0 || cidx >= ncols) { @@ -71,8 +74,10 @@ TEST(MathLibEigen, Eigen2CSR) } // change matrix - for (int row=0; row<nrows; ++row) { - for (int col = -1; col<=1; ++col) { + for (int row = 0; row < nrows; ++row) + { + for (int col = -1; col <= 1; ++col) + { int cidx = row + col; if (cidx < 0 || cidx >= ncols) { @@ -103,9 +108,9 @@ TEST(MathLibEigen, Eigen2CSR) EXPECT_EQ(ia[r], ptr[r]); } - for (int i=0; i<nnz; ++i) { + for (int i = 0; i < nnz; ++i) + { EXPECT_EQ(values[i], data[i]); EXPECT_EQ(ja[i], col[i]); } } - diff --git a/Tests/MathLib/TestGaussLegendreIntegration.cpp b/Tests/MathLib/TestGaussLegendreIntegration.cpp index a96d90814a57aba8b27ccc75a5fcd94b93be6e19..3e2587e570fa0c1d0e8de9df894700362ac1c8c3 100644 --- a/Tests/MathLib/TestGaussLegendreIntegration.cpp +++ b/Tests/MathLib/TestGaussLegendreIntegration.cpp @@ -446,8 +446,8 @@ static double const eps = 10 * std::numeric_limits<double>::epsilon(); OGS_DONT_TEST_THIS_IF_PETSC(MathLib, IntegrationGaussLegendreTet) { std::unique_ptr<MeshLib::Mesh> mesh_tet( - MeshLib::IO::VtuInterface::readVTUFile(TestInfoLib::TestInfo::data_path + - "/MathLib/unit_cube_tet.vtu")); + MeshLib::IO::VtuInterface::readVTUFile( + TestInfoLib::TestInfo::data_path + "/MathLib/unit_cube_tet.vtu")); for (unsigned integration_order : {1, 2, 3}) { @@ -475,8 +475,8 @@ OGS_DONT_TEST_THIS_IF_PETSC(MathLib, IntegrationGaussLegendreTet) OGS_DONT_TEST_THIS_IF_PETSC(MathLib, IntegrationGaussLegendreHex) { std::unique_ptr<MeshLib::Mesh> mesh_hex( - MeshLib::IO::VtuInterface::readVTUFile(TestInfoLib::TestInfo::data_path + - "/MathLib/unit_cube_hex.vtu")); + MeshLib::IO::VtuInterface::readVTUFile( + TestInfoLib::TestInfo::data_path + "/MathLib/unit_cube_hex.vtu")); for (unsigned integration_order : {1, 2, 3}) { @@ -507,8 +507,8 @@ OGS_DONT_TEST_THIS_IF_PETSC( MathLib, DISABLED_IntegrationGaussLegendreTetSeparablePolynomial) { std::unique_ptr<MeshLib::Mesh> mesh_tet( - MeshLib::IO::VtuInterface::readVTUFile(TestInfoLib::TestInfo::data_path + - "/MathLib/unit_cube_tet.vtu")); + MeshLib::IO::VtuInterface::readVTUFile( + TestInfoLib::TestInfo::data_path + "/MathLib/unit_cube_tet.vtu")); for (unsigned integration_order : {1, 2, 3}) { @@ -535,8 +535,8 @@ OGS_DONT_TEST_THIS_IF_PETSC(MathLib, IntegrationGaussLegendreHexSeparablePolynomial) { std::unique_ptr<MeshLib::Mesh> mesh_hex( - MeshLib::IO::VtuInterface::readVTUFile(TestInfoLib::TestInfo::data_path + - "/MathLib/unit_cube_hex.vtu")); + MeshLib::IO::VtuInterface::readVTUFile( + TestInfoLib::TestInfo::data_path + "/MathLib/unit_cube_hex.vtu")); for (unsigned integration_order : {1, 2, 3, 4}) { @@ -563,8 +563,8 @@ OGS_DONT_TEST_THIS_IF_PETSC(MathLib, IntegrationGaussLegendreTetNonSeparablePolynomial) { std::unique_ptr<MeshLib::Mesh> mesh_tet( - MeshLib::IO::VtuInterface::readVTUFile(TestInfoLib::TestInfo::data_path + - "/MathLib/unit_cube_tet.vtu")); + MeshLib::IO::VtuInterface::readVTUFile( + TestInfoLib::TestInfo::data_path + "/MathLib/unit_cube_tet.vtu")); for (unsigned integration_order : {1, 2, 3}) { @@ -591,8 +591,8 @@ OGS_DONT_TEST_THIS_IF_PETSC(MathLib, IntegrationGaussLegendreHexNonSeparablePolynomial) { std::unique_ptr<MeshLib::Mesh> mesh_hex( - MeshLib::IO::VtuInterface::readVTUFile(TestInfoLib::TestInfo::data_path + - "/MathLib/unit_cube_hex.vtu")); + MeshLib::IO::VtuInterface::readVTUFile( + TestInfoLib::TestInfo::data_path + "/MathLib/unit_cube_hex.vtu")); for (unsigned integration_order : {1, 2, 3, 4}) { diff --git a/Tests/MathLib/TestGlobalMatrixInterface.cpp b/Tests/MathLib/TestGlobalMatrixInterface.cpp index 500aa32c4af8f4bc9aceafe0aaa1e7ee7ea71dff..c8b61ffd2cf2138fd02aa16af2d488139078d277 100644 --- a/Tests/MathLib/TestGlobalMatrixInterface.cpp +++ b/Tests/MathLib/TestGlobalMatrixInterface.cpp @@ -26,20 +26,18 @@ #endif #include "MathLib/LinAlg/FinalizeMatrixAssembly.h" - #include "NumLib/NumericsConfig.h" using namespace MathLib::LinAlg; namespace { - template <class T_MATRIX> -void checkGlobalMatrixInterface(T_MATRIX &m) +void checkGlobalMatrixInterface(T_MATRIX& m) { ASSERT_EQ(10u, m.getNumberOfRows()); ASSERT_EQ(10u, m.getNumberOfColumns()); - ASSERT_EQ(0u, m.getRangeBegin()); + ASSERT_EQ(0u, m.getRangeBegin()); ASSERT_EQ(10u, m.getRangeEnd()); m.setValue(0, 0, 1.0); @@ -56,9 +54,9 @@ void checkGlobalMatrixInterface(T_MATRIX &m) ASSERT_TRUE(finalizeMatrixAssembly(m)); } -#ifdef USE_PETSC // or MPI +#ifdef USE_PETSC // or MPI template <class T_MATRIX, class T_VECTOR> -void checkGlobalMatrixInterfaceMPI(T_MATRIX &m, T_VECTOR &v) +void checkGlobalMatrixInterfaceMPI(T_MATRIX& m, T_VECTOR& v) { int msize; MPI_Comm_size(PETSC_COMM_WORLD, &msize); @@ -66,16 +64,18 @@ void checkGlobalMatrixInterfaceMPI(T_MATRIX &m, T_VECTOR &v) MPI_Comm_rank(PETSC_COMM_WORLD, &mrank); ASSERT_EQ(3u, msize); - ASSERT_EQ(m.getRangeEnd()-m.getRangeBegin(), m.getNumberOfLocalRows()); + ASSERT_EQ(m.getRangeEnd() - m.getRangeBegin(), m.getNumberOfLocalRows()); int gathered_rows; int local_rows = m.getNumberOfLocalRows(); - MPI_Allreduce(&local_rows, &gathered_rows, 1, MPI_INT, MPI_SUM, PETSC_COMM_WORLD); + MPI_Allreduce(&local_rows, &gathered_rows, 1, MPI_INT, MPI_SUM, + PETSC_COMM_WORLD); ASSERT_EQ(m.getNumberOfRows(), gathered_rows); int gathered_cols; int local_cols = m.getNumberOfLocalColumns(); - MPI_Allreduce(&local_cols, &gathered_cols, 1, MPI_INT, MPI_SUM, PETSC_COMM_WORLD); + MPI_Allreduce(&local_cols, &gathered_cols, 1, MPI_INT, MPI_SUM, + PETSC_COMM_WORLD); ASSERT_EQ(m.getNumberOfColumns(), gathered_cols); // Add entries @@ -108,37 +108,39 @@ void checkGlobalMatrixInterfaceMPI(T_MATRIX &m, T_VECTOR &v) T_VECTOR y(v, deep_copy); matMult(m_c, v, y); - ASSERT_EQ(sqrt(3*(3*3 + 7*7)), norm2(y)); + ASSERT_EQ(sqrt(3 * (3 * 3 + 7 * 7)), norm2(y)); // set a value m_c.set(2 * mrank, 2 * mrank, 5.0); MathLib::finalizeMatrixAssembly(m); // add a value - m_c.add(2 * mrank+1, 2 * mrank+1, 5.0); + m_c.add(2 * mrank + 1, 2 * mrank + 1, 5.0); MathLib::finalizeMatrixAssembly(m_c); matMult(m_c, v, y); - ASSERT_EQ(sqrt((3*7*7 + 3*12*12)), norm2(y)); + ASSERT_EQ(sqrt((3 * 7 * 7 + 3 * 12 * 12)), norm2(y)); } // Rectanglular matrix template <class T_MATRIX, class T_VECTOR> -void checkGlobalRectangularMatrixInterfaceMPI(T_MATRIX &m, T_VECTOR &v) +void checkGlobalRectangularMatrixInterfaceMPI(T_MATRIX& m, T_VECTOR& v) { int mrank; MPI_Comm_rank(PETSC_COMM_WORLD, &mrank); - ASSERT_EQ(m.getRangeEnd()-m.getRangeBegin(), m.getNumberOfLocalRows()); + ASSERT_EQ(m.getRangeEnd() - m.getRangeBegin(), m.getNumberOfLocalRows()); int gathered_rows; int local_rows = m.getNumberOfLocalRows(); - MPI_Allreduce(&local_rows, &gathered_rows, 1, MPI_INT, MPI_SUM, PETSC_COMM_WORLD); + MPI_Allreduce(&local_rows, &gathered_rows, 1, MPI_INT, MPI_SUM, + PETSC_COMM_WORLD); ASSERT_EQ(m.getNumberOfRows(), gathered_rows); int gathered_cols; int local_cols = m.getNumberOfLocalColumns(); - MPI_Allreduce(&local_cols, &gathered_cols, 1, MPI_INT, MPI_SUM, PETSC_COMM_WORLD); + MPI_Allreduce(&local_cols, &gathered_cols, 1, MPI_INT, MPI_SUM, + PETSC_COMM_WORLD); ASSERT_EQ(m.getNumberOfColumns(), gathered_cols); // Add entries @@ -167,12 +169,12 @@ void checkGlobalRectangularMatrixInterfaceMPI(T_MATRIX &m, T_VECTOR &v) T_VECTOR y(m.getNumberOfRows()); matMult(m, v, y); - ASSERT_NEAR(6.*sqrt(6.), norm2(y), 1.e-10); + ASSERT_NEAR(6. * sqrt(6.), norm2(y), 1.e-10); } -#endif // end of: ifdef USE_PETSC // or MPI +#endif // end of: ifdef USE_PETSC // or MPI -} // end namespace +} // end namespace #if defined(USE_PETSC) TEST(MPITest_Math, CheckInterface_PETScMatrix_Local_Size) diff --git a/Tests/MathLib/TestGlobalVectorInterface.cpp b/Tests/MathLib/TestGlobalVectorInterface.cpp index e1bc1429fc3d5cccc2902933cc8c4715784602af..fd7ac7da12af8ab23f83c1e8c67b2553f47ff250 100644 --- a/Tests/MathLib/TestGlobalVectorInterface.cpp +++ b/Tests/MathLib/TestGlobalVectorInterface.cpp @@ -14,9 +14,9 @@ */ #include <gtest/gtest.h> -#include "Tests/TestTools.h" #include "MathLib/LinAlg/LinAlg.h" +#include "Tests/TestTools.h" #if defined(USE_PETSC) #include "MathLib/LinAlg/PETSc/PETScVector.h" @@ -31,7 +31,6 @@ using namespace MathLib::LinAlg; namespace { - template <class T_VECTOR> void checkGlobalVectorInterface() { @@ -58,10 +57,10 @@ void checkGlobalVectorInterface() axpy(y, 1., x); ASSERT_EQ(4.0, y.get(0)); - //y -= x; + // y -= x; axpy(y, -1., x); ASSERT_EQ(2.0, y.get(0)); - //y = 1.0; + // y = 1.0; set(y, 1.0); ASSERT_EQ(1.0, y.get(0)); // y = x; @@ -92,16 +91,15 @@ void checkGlobalVectorInterfacePETSc() T_VECTOR x(16); ASSERT_EQ(16u, x.size()); - ASSERT_EQ(x.getRangeEnd()-x.getRangeBegin(), x.getLocalSize()); + ASSERT_EQ(x.getRangeEnd() - x.getRangeBegin(), x.getLocalSize()); const int r0 = x.getRangeBegin(); - //x.get(0) is expensive, only get local value. Use it for test purpose + // x.get(0) is expensive, only get local value. Use it for test purpose x.setLocalAccessibleVector(); ASSERT_EQ(.0, x.get(r0)); set(x, 10.); - // Value of x is not copied to y const bool deep_copy = false; T_VECTOR y(x, deep_copy); @@ -127,35 +125,23 @@ void checkGlobalVectorInterfacePETSc() std::vector<double> local_vec(2, 10.0); std::vector<GlobalIndexType> vec_pos(2); - vec_pos[0] = r0; // any index in [0,15] - vec_pos[1] = r0+1; // any index in [0,15] + vec_pos[0] = r0; // any index in [0,15] + vec_pos[1] = r0 + 1; // any index in [0,15] y.add(vec_pos, local_vec); - double normy = std::sqrt(6.0*400+10.0*100); + double normy = std::sqrt(6.0 * 400 + 10.0 * 100); - ASSERT_NEAR(0.0, normy-norm2(y), 1.e-10); + ASSERT_NEAR(0.0, normy - norm2(y), 1.e-10); std::vector<double> x0(16); - double z[] = - { - 2.0000000000000000e+01, - 2.0000000000000000e+01, - 1.0000000000000000e+01, - 1.0000000000000000e+01, - 1.0000000000000000e+01, - 1.0000000000000000e+01, - 2.0000000000000000e+01, - 2.0000000000000000e+01, - 1.0000000000000000e+01, - 1.0000000000000000e+01, - 1.0000000000000000e+01, - 2.0000000000000000e+01, - 2.0000000000000000e+01, - 1.0000000000000000e+01, - 1.0000000000000000e+01, - 1.0000000000000000e+01 - }; + double z[] = { + 2.0000000000000000e+01, 2.0000000000000000e+01, 1.0000000000000000e+01, + 1.0000000000000000e+01, 1.0000000000000000e+01, 1.0000000000000000e+01, + 2.0000000000000000e+01, 2.0000000000000000e+01, 1.0000000000000000e+01, + 1.0000000000000000e+01, 1.0000000000000000e+01, 2.0000000000000000e+01, + 2.0000000000000000e+01, 1.0000000000000000e+01, 1.0000000000000000e+01, + 1.0000000000000000e+01}; y.getGlobalVector(x0); @@ -171,18 +157,18 @@ void checkGlobalVectorInterfacePETSc() int mrank; MPI_Comm_rank(PETSC_COMM_WORLD, &mrank); - ASSERT_EQ(2*mrank, x_fixed_p.getRangeBegin()); - ASSERT_EQ(2*mrank+2, x_fixed_p.getRangeEnd()); + ASSERT_EQ(2 * mrank, x_fixed_p.getRangeBegin()); + ASSERT_EQ(2 * mrank + 2, x_fixed_p.getRangeEnd()); vec_pos[0] = 2 * mrank; vec_pos[1] = vec_pos[0] + 1; local_vec[0] = 1.; local_vec[1] = 2.; - for(unsigned i=0; i<3; i++) + for (unsigned i = 0; i < 3; i++) { const unsigned j = 2 * i; z[j] = 1.0; - z[j+1] = 2.0; + z[j + 1] = 2.0; } x_fixed_p.set(vec_pos, local_vec); x_fixed_p.getGlobalVector(x0); @@ -190,8 +176,8 @@ void checkGlobalVectorInterfacePETSc() ASSERT_ARRAY_NEAR(z, x0, 6, 1e-10); // check local array - std::vector<double> loc_v( x_fixed_p.getLocalSize() - + x_fixed_p.getGhostSize() ); + std::vector<double> loc_v(x_fixed_p.getLocalSize() + + x_fixed_p.getGhostSize()); x_fixed_p.copyValues(loc_v); z[0] = 1.0; z[1] = 2.0; @@ -201,7 +187,7 @@ void checkGlobalVectorInterfacePETSc() // Deep copy MathLib::finalizeVectorAssembly(x_fixed_p); T_VECTOR x_deep_copied(x_fixed_p); - ASSERT_NEAR(sqrt(3.0*5), norm2(x_deep_copied), 1.e-10); + ASSERT_NEAR(sqrt(3.0 * 5), norm2(x_deep_copied), 1.e-10); // ----------------------------------------------------------------- // Vector with ghost entries @@ -240,22 +226,22 @@ void checkGlobalVectorInterfacePETSc() switch (mrank) { case 0: - non_ghost_ids = {0, 1, 2, 3}; + non_ghost_ids = {0, 1, 2, 3}; non_ghost_vals = {0., 1., 2., 3.}; - ghost_ids = {6, 8, 10}; - expected = {0., 1., 2., 3., 6., 8., 10.}; + ghost_ids = {6, 8, 10}; + expected = {0., 1., 2., 3., 6., 8., 10.}; break; case 1: - non_ghost_ids = {4, 5, 6, 7, 8}; + non_ghost_ids = {4, 5, 6, 7, 8}; non_ghost_vals = {4., 5., 6., 7., 8.}; - ghost_ids = {0, 9}; - expected = {4., 5., 6., 7., 8., 0., 9.}; + ghost_ids = {0, 9}; + expected = {4., 5., 6., 7., 8., 0., 9.}; break; case 2: - non_ghost_ids = {9, 10, 11}; + non_ghost_ids = {9, 10, 11}; non_ghost_vals = {9., 10., 11.}; - ghost_ids = {3, 5}; - expected = {9., 10., 11., 3., 5.}; + ghost_ids = {3, 5}; + expected = {9., 10., 11., 3., 5.}; break; } T_VECTOR x_with_ghosts(local_vec_size, ghost_ids, is_global_size); @@ -264,27 +250,27 @@ void checkGlobalVectorInterfacePETSc() ASSERT_EQ(12u, x_with_ghosts.size()); - std::vector<double> loc_v1( x_with_ghosts.getLocalSize() - + x_with_ghosts.getGhostSize() ); + std::vector<double> loc_v1(x_with_ghosts.getLocalSize() + + x_with_ghosts.getGhostSize()); x_with_ghosts.copyValues(loc_v1); - for (std::size_t i=0; i<expected.size(); i++) + for (std::size_t i = 0; i < expected.size(); i++) { - ASSERT_EQ(expected[i], loc_v1[i]); + ASSERT_EQ(expected[i], loc_v1[i]); } } #endif -} // end namespace +} // end namespace //-------------------------------------------- #if defined(USE_PETSC) TEST(MPITest_Math, CheckInterface_PETScVector) { - checkGlobalVectorInterfacePETSc<MathLib::PETScVector >(); + checkGlobalVectorInterfacePETSc<MathLib::PETScVector>(); } #else TEST(Math, CheckInterface_EigenVector) { - checkGlobalVectorInterface<MathLib::EigenVector >(); + checkGlobalVectorInterface<MathLib::EigenVector>(); } #endif diff --git a/Tests/MathLib/TestIntegration.cpp b/Tests/MathLib/TestIntegration.cpp index 8e48aba70001a93d572cc7776b725d81e88396d1..28dd1528e61996b3966c8d059a40a168c0a0e08b 100644 --- a/Tests/MathLib/TestIntegration.cpp +++ b/Tests/MathLib/TestIntegration.cpp @@ -19,23 +19,27 @@ namespace { - double square(double const x) - { - return x*x; - } +double square(double const x) +{ + return x * x; } +} // namespace TEST(MathLib, IntegrationGaussLegendre) { double const eps = 10 * std::numeric_limits<double>::epsilon(); - EXPECT_EQ(0.0, MathLib::WeightedSum<MathLib::GaussLegendre<1>>::add(square)); - EXPECT_NEAR(2./3, MathLib::WeightedSum<MathLib::GaussLegendre<2>>::add(square), - eps); - EXPECT_NEAR(2./3, MathLib::WeightedSum<MathLib::GaussLegendre<3>>::add(square), - eps); - EXPECT_NEAR(2./3, MathLib::WeightedSum<MathLib::GaussLegendre<4>>::add(square), - eps); + EXPECT_EQ(0.0, + MathLib::WeightedSum<MathLib::GaussLegendre<1>>::add(square)); + EXPECT_NEAR(2. / 3, + MathLib::WeightedSum<MathLib::GaussLegendre<2>>::add(square), + eps); + EXPECT_NEAR(2. / 3, + MathLib::WeightedSum<MathLib::GaussLegendre<3>>::add(square), + eps); + EXPECT_NEAR(2. / 3, + MathLib::WeightedSum<MathLib::GaussLegendre<4>>::add(square), + eps); auto const& cube = [](double const x) { return x * x * x; }; EXPECT_NEAR(0.0, MathLib::WeightedSum<MathLib::GaussLegendre<1>>::add(cube), @@ -47,5 +51,3 @@ TEST(MathLib, IntegrationGaussLegendre) EXPECT_NEAR(0.0, MathLib::WeightedSum<MathLib::GaussLegendre<4>>::add(cube), eps); } - - diff --git a/Tests/MathLib/TestIsPointInTriangle.cpp b/Tests/MathLib/TestIsPointInTriangle.cpp index 0af9d2e455382033b3ac90f38d4c15b3c0c07bbe..29b576789b09dcfbae5e2d3005ea1df6dfe2be31 100644 --- a/Tests/MathLib/TestIsPointInTriangle.cpp +++ b/Tests/MathLib/TestIsPointInTriangle.cpp @@ -11,8 +11,8 @@ #include <gtest/gtest.h> -#include "MathLib/Point3d.h" #include "MathLib/GeometricBasics.h" +#include "MathLib/Point3d.h" TEST(MathLib, IsPointInTriangle) { @@ -83,4 +83,3 @@ TEST(MathLib, IsPointInTriangle) EXPECT_FALSE(MathLib::gaussPointInTriangle(q, a, b, c)); EXPECT_FALSE(MathLib::barycentricPointInTriangle(q, a, b, c)); } - diff --git a/Tests/MathLib/TestLinearSolver.cpp b/Tests/MathLib/TestLinearSolver.cpp index d6c50f84e3e4312a640dd212b8d9f26b38185997..5cd4abd38d83074b7f3b1324bca67835172aa546 100644 --- a/Tests/MathLib/TestLinearSolver.cpp +++ b/Tests/MathLib/TestLinearSolver.cpp @@ -17,12 +17,11 @@ #include "BaseLib/ConfigTree.h" #include "MathLib/LinAlg/ApplyKnownSolution.h" -#include "MathLib/LinAlg/FinalizeMatrixAssembly.h" -#include "MathLib/LinAlg/LinAlg.h" - +#include "MathLib/LinAlg/Eigen/EigenLinearSolver.h" #include "MathLib/LinAlg/Eigen/EigenMatrix.h" #include "MathLib/LinAlg/Eigen/EigenVector.h" -#include "MathLib/LinAlg/Eigen/EigenLinearSolver.h" +#include "MathLib/LinAlg/FinalizeMatrixAssembly.h" +#include "MathLib/LinAlg/LinAlg.h" #if defined(USE_LIS) #include "MathLib/LinAlg/EigenLis/EigenLisLinearSolver.h" @@ -34,31 +33,99 @@ #endif #ifdef USE_PETSC +#include "MathLib/LinAlg/PETSc/PETScLinearSolver.h" #include "MathLib/LinAlg/PETSc/PETScMatrix.h" #include "MathLib/LinAlg/PETSc/PETScVector.h" -#include "MathLib/LinAlg/PETSc/PETScLinearSolver.h" #endif #include "Tests/TestTools.h" namespace { - -template<class T_Mat> -void setMatrix9x9(T_Mat &mat) +template <class T_Mat> +void setMatrix9x9(T_Mat& mat) { - double d_mat[] = - { - 6.66667e-012, -1.66667e-012, 0, -1.66667e-012, -3.33333e-012, 0, 0, 0, 0, - -1.66667e-012, 1.33333e-011, -1.66667e-012, -3.33333e-012, -3.33333e-012, -3.33333e-012, 0, 0, 0, - 0, -1.66667e-012, 6.66667e-012, 0, -3.33333e-012, -1.66667e-012, 0, 0, 0, - -1.66667e-012, -3.33333e-012, 0, 1.33333e-011, -3.33333e-012, 0, -1.66667e-012, -3.33333e-012, 0, - -3.33333e-012, -3.33333e-012, -3.33333e-012, -3.33333e-012, 2.66667e-011, -3.33333e-012, -3.33333e-012, -3.33333e-012, -3.33333e-012, - 0, -3.33333e-012, -1.66667e-012, 0, -3.33333e-012, 1.33333e-011, 0, -3.33333e-012, -1.66667e-012, - 0, 0, 0, -1.66667e-012, -3.33333e-012, 0, 6.66667e-012, -1.66667e-012, 0, - 0, 0, 0, -3.33333e-012, -3.33333e-012, -3.33333e-012, -1.66667e-012, 1.33333e-011, -1.66667e-012, - 0, 0, 0, 0, -3.33333e-012, -1.66667e-012, 0, -1.66667e-012, 6.66667e-012 - }; + double d_mat[] = {6.66667e-012, + -1.66667e-012, + 0, + -1.66667e-012, + -3.33333e-012, + 0, + 0, + 0, + 0, + -1.66667e-012, + 1.33333e-011, + -1.66667e-012, + -3.33333e-012, + -3.33333e-012, + -3.33333e-012, + 0, + 0, + 0, + 0, + -1.66667e-012, + 6.66667e-012, + 0, + -3.33333e-012, + -1.66667e-012, + 0, + 0, + 0, + -1.66667e-012, + -3.33333e-012, + 0, + 1.33333e-011, + -3.33333e-012, + 0, + -1.66667e-012, + -3.33333e-012, + 0, + -3.33333e-012, + -3.33333e-012, + -3.33333e-012, + -3.33333e-012, + 2.66667e-011, + -3.33333e-012, + -3.33333e-012, + -3.33333e-012, + -3.33333e-012, + 0, + -3.33333e-012, + -1.66667e-012, + 0, + -3.33333e-012, + 1.33333e-011, + 0, + -3.33333e-012, + -1.66667e-012, + 0, + 0, + 0, + -1.66667e-012, + -3.33333e-012, + 0, + 6.66667e-012, + -1.66667e-012, + 0, + 0, + 0, + 0, + -3.33333e-012, + -3.33333e-012, + -3.33333e-012, + -1.66667e-012, + 1.33333e-011, + -1.66667e-012, + 0, + 0, + 0, + 0, + -3.33333e-012, + -1.66667e-012, + 0, + -1.66667e-012, + 6.66667e-012}; for (unsigned i = 0; i < 9; i++) { for (unsigned j = 0; j < 9; j++) @@ -68,7 +135,8 @@ void setMatrix9x9(T_Mat &mat) } } -template<typename IntType> struct Example1 +template <typename IntType> +struct Example1 { MathLib::EigenMatrix mat; std::vector<IntType> vec_dirichlet_bc_id; @@ -76,16 +144,18 @@ template<typename IntType> struct Example1 static const std::size_t dim_eqs = 9; double* exH; - Example1() - : mat(dim_eqs, dim_eqs), exH(new double[dim_eqs]) + Example1() : mat(dim_eqs, dim_eqs), exH(new double[dim_eqs]) { setMatrix9x9(mat); - IntType int_dirichlet_bc_id[] = {2,5,8,0,3,6}; - vec_dirichlet_bc_id.assign(int_dirichlet_bc_id, int_dirichlet_bc_id+6); + IntType int_dirichlet_bc_id[] = {2, 5, 8, 0, 3, 6}; + vec_dirichlet_bc_id.assign(int_dirichlet_bc_id, + int_dirichlet_bc_id + 6); vec_dirichlet_bc_value.resize(6); - std::fill(vec_dirichlet_bc_value.begin(), vec_dirichlet_bc_value.begin()+3, .0); - std::fill(vec_dirichlet_bc_value.begin()+3, vec_dirichlet_bc_value.end(), 1.0); - for (std::size_t i=0; i<9; i++) + std::fill(vec_dirichlet_bc_value.begin(), + vec_dirichlet_bc_value.begin() + 3, .0); + std::fill(vec_dirichlet_bc_value.begin() + 3, + vec_dirichlet_bc_value.end(), 1.0); + for (std::size_t i = 0; i < 9; i++) { if (i % 3 == 0) { @@ -102,22 +172,21 @@ template<typename IntType> struct Example1 } } - ~Example1() - { - delete [] exH; - } + ~Example1() { delete[] exH; } }; -template <class T_MATRIX, class T_VECTOR, class T_LINEAR_SOVLER, typename IntType> -void checkLinearSolverInterface(T_MATRIX &A, BaseLib::ConfigTree const& ls_option) +template <class T_MATRIX, class T_VECTOR, class T_LINEAR_SOVLER, + typename IntType> +void checkLinearSolverInterface(T_MATRIX& A, + BaseLib::ConfigTree const& ls_option) { Example1<IntType> ex1; // set a coefficient matrix A.setZero(); - for (std::size_t i=0; i<ex1.dim_eqs; i++) + for (std::size_t i = 0; i < ex1.dim_eqs; i++) { - for (std::size_t j=0; j<ex1.dim_eqs; j++) + for (std::size_t j = 0; j < ex1.dim_eqs; j++) { double v = ex1.mat.get(i, j); if (v != .0) @@ -134,7 +203,8 @@ void checkLinearSolverInterface(T_MATRIX &A, BaseLib::ConfigTree const& ls_optio x.setZero(); // apply BC - MathLib::applyKnownSolution(A, rhs, x, ex1.vec_dirichlet_bc_id, ex1.vec_dirichlet_bc_value); + MathLib::applyKnownSolution(A, rhs, x, ex1.vec_dirichlet_bc_id, + ex1.vec_dirichlet_bc_value); MathLib::finalizeMatrixAssembly(A); @@ -143,7 +213,6 @@ void checkLinearSolverInterface(T_MATRIX &A, BaseLib::ConfigTree const& ls_optio ls.solve(A, rhs, x); ASSERT_ARRAY_NEAR(ex1.exH, x, ex1.dim_eqs, 1e-5); - } #ifdef USE_PETSC @@ -156,10 +225,10 @@ void checkLinearSolverInterface(T_MATRIX& A, T_VECTOR& b, MPI_Comm_rank(PETSC_COMM_WORLD, &mrank); // Add entries Eigen::Matrix2d loc_m; - loc_m(0, 0) = 1. + mrank; - loc_m(0, 1) = 2. + mrank; - loc_m(1, 0) = 3. + mrank; - loc_m(1, 1) = 4. + mrank; + loc_m(0, 0) = 1. + mrank; + loc_m(0, 1) = 2. + mrank; + loc_m(1, 0) = 3. + mrank; + loc_m(1, 1) = 4. + mrank; std::vector<int> row_pos(2); std::vector<int> col_pos(2); @@ -176,8 +245,8 @@ void checkLinearSolverInterface(T_MATRIX& A, T_VECTOR& b, T_VECTOR x(b, deep_copy); std::vector<double> local_vec(2); - local_vec[0] = mrank+1; - local_vec[1] = 2. * (mrank+1); + local_vec[0] = mrank + 1; + local_vec[1] = 2. * (mrank + 1); x.set(row_pos, local_vec); std::vector<double> x0(6); @@ -189,12 +258,12 @@ void checkLinearSolverInterface(T_MATRIX& A, T_VECTOR& b, std::vector<int> bc_id; // Type must be int to match Petsc_Int std::vector<double> bc_value; - if(mrank == 1) + if (mrank == 1) { bc_id.resize(1); bc_value.resize(1); bc_id[0] = 2 * mrank; - bc_value[0] = mrank+1; + bc_value[0] = mrank + 1; } MathLib::applyKnownSolution(A, b, x, bc_id, bc_value); @@ -215,7 +284,7 @@ void checkLinearSolverInterface(T_MATRIX& A, T_VECTOR& b, } #endif -} // end namespace +} // end namespace TEST(Math, CheckInterface_Eigen) { @@ -227,8 +296,8 @@ TEST(Math, CheckInterface_Eigen) t_solver.put("error_tolerance", 1e-15); t_solver.put("max_iteration_step", 1000); t_root.put_child("eigen", t_solver); - BaseLib::ConfigTree conf(t_root, "", - BaseLib::ConfigTree::onerror, BaseLib::ConfigTree::onwarning); + BaseLib::ConfigTree conf(t_root, "", BaseLib::ConfigTree::onerror, + BaseLib::ConfigTree::onwarning); using IntType = MathLib::EigenMatrix::IndexType; @@ -243,8 +312,8 @@ TEST(Math, CheckInterface_EigenLis) // set solver options using Boost property tree boost::property_tree::ptree t_root; t_root.put("lis", "-i cg -p none -tol 1e-15 -maxiter 1000"); - BaseLib::ConfigTree conf(t_root, "", - BaseLib::ConfigTree::onerror, BaseLib::ConfigTree::onwarning); + BaseLib::ConfigTree conf(t_root, "", BaseLib::ConfigTree::onerror, + BaseLib::ConfigTree::onwarning); using IntType = MathLib::EigenMatrix::IndexType; @@ -268,25 +337,23 @@ TEST(MPITest_Math, CheckInterface_PETSc_Linear_Solver_basic) MathLib::PETScVector b(2, is_global_size); const char xml[] = - "<petsc>" - " <parameters>" - " -ptest1_ksp_type bcgs " - " -ptest1_ksp_rtol 1.e-8 " - " -ptest1_ksp_atol 1.e-50 " - " -ptest1_ksp_max_it 1000 " - " -ptest1_pc_type bjacobi" - " </parameters>" - " <prefix>ptest1</prefix>" - "</petsc>"; + "<petsc>" + " <parameters>" + " -ptest1_ksp_type bcgs " + " -ptest1_ksp_rtol 1.e-8 " + " -ptest1_ksp_atol 1.e-50 " + " -ptest1_ksp_max_it 1000 " + " -ptest1_pc_type bjacobi" + " </parameters>" + " <prefix>ptest1</prefix>" + "</petsc>"; auto const ptree = Tests::readXml(xml); - checkLinearSolverInterface<MathLib::PETScMatrix, - MathLib::PETScVector, + checkLinearSolverInterface<MathLib::PETScMatrix, MathLib::PETScVector, MathLib::PETScLinearSolver>( A, b, "", BaseLib::ConfigTree(ptree, "", BaseLib::ConfigTree::onerror, - BaseLib::ConfigTree::onwarning) - ); + BaseLib::ConfigTree::onwarning)); } TEST(MPITest_Math, CheckInterface_PETSc_Linear_Solver_chebyshev_sor) @@ -302,25 +369,23 @@ TEST(MPITest_Math, CheckInterface_PETSc_Linear_Solver_chebyshev_sor) MathLib::PETScVector b(2, is_global_size); const char xml[] = - "<petsc>" - " <parameters>" - " -ptest2_ksp_type chebyshev " - " -ptest2_ksp_rtol 1.e-8 " - " -ptest2_ksp_atol 1.e-50" - " -ptest2_ksp_max_it 1000 " - " -ptest2_pc_type sor" - " </parameters>" - " <prefix>ptest2</prefix>" - "</petsc>"; + "<petsc>" + " <parameters>" + " -ptest2_ksp_type chebyshev " + " -ptest2_ksp_rtol 1.e-8 " + " -ptest2_ksp_atol 1.e-50" + " -ptest2_ksp_max_it 1000 " + " -ptest2_pc_type sor" + " </parameters>" + " <prefix>ptest2</prefix>" + "</petsc>"; auto const ptree = Tests::readXml(xml); - checkLinearSolverInterface<MathLib::PETScMatrix, - MathLib::PETScVector, + checkLinearSolverInterface<MathLib::PETScMatrix, MathLib::PETScVector, MathLib::PETScLinearSolver>( A, b, "", BaseLib::ConfigTree(ptree, "", BaseLib::ConfigTree::onerror, - BaseLib::ConfigTree::onwarning) - ); + BaseLib::ConfigTree::onwarning)); } TEST(MPITest_Math, CheckInterface_PETSc_Linear_Solver_gmres_amg) @@ -336,29 +401,25 @@ TEST(MPITest_Math, CheckInterface_PETSc_Linear_Solver_gmres_amg) MathLib::PETScVector b(2, is_global_size); const char xml[] = - "<petsc>" - " <parameters>" - " -ptest3_ksp_type gmres " - " -ptest3_ksp_rtol 1.e-8 " - " -ptest3_ksp_gmres_restart 20 " - " -ptest3_ksp_gmres_classicalgramschmidt " - " -ptest3_pc_type gamg " - " -ptest3_pc_gamg_type agg " - " -ptest3_pc_gamg_agg_nsmooths 2" - " </parameters>" - " <prefix>ptest3</prefix>" - "</petsc>"; + "<petsc>" + " <parameters>" + " -ptest3_ksp_type gmres " + " -ptest3_ksp_rtol 1.e-8 " + " -ptest3_ksp_gmres_restart 20 " + " -ptest3_ksp_gmres_classicalgramschmidt " + " -ptest3_pc_type gamg " + " -ptest3_pc_gamg_type agg " + " -ptest3_pc_gamg_agg_nsmooths 2" + " </parameters>" + " <prefix>ptest3</prefix>" + "</petsc>"; auto const ptree = Tests::readXml(xml); - checkLinearSolverInterface<MathLib::PETScMatrix, - MathLib::PETScVector, + checkLinearSolverInterface<MathLib::PETScMatrix, MathLib::PETScVector, MathLib::PETScLinearSolver>( A, b, "", BaseLib::ConfigTree(ptree, "", BaseLib::ConfigTree::onerror, - BaseLib::ConfigTree::onwarning) - ); + BaseLib::ConfigTree::onwarning)); } #endif - - diff --git a/Tests/MathLib/TestNonlinear1D.cpp b/Tests/MathLib/TestNonlinear1D.cpp index 2173c444da5b91e22c3a12ae92d62f9ef5bfe1f5..3a14f09d9f2b224155f12b2d7e58e753958e1f19 100644 --- a/Tests/MathLib/TestNonlinear1D.cpp +++ b/Tests/MathLib/TestNonlinear1D.cpp @@ -8,14 +8,16 @@ */ #include <gtest/gtest.h> + #include <limits> #include <type_traits> + #include "BaseLib/Logging.h" #include "MathLib/Nonlinear/Root1D.h" double f(double x) { - return x*x-1; + return x * x - 1; } template <typename T> @@ -24,7 +26,8 @@ class MathLibRegulaFalsi : public ::testing::Test }; namespace NL = MathLib::Nonlinear; -using RegulaFalsiTypes = ::testing::Types<NL::Unmodified, NL::Illinois, NL::Pegasus, NL::AndersonBjorck>; +using RegulaFalsiTypes = ::testing::Types<NL::Unmodified, NL::Illinois, + NL::Pegasus, NL::AndersonBjorck>; TYPED_TEST_SUITE(MathLibRegulaFalsi, RegulaFalsiTypes); @@ -35,7 +38,7 @@ TYPED_TEST(MathLibRegulaFalsi, QuadraticFunction) DBUG(" 0 -- x ~ {:23.16g}, range = {:23.16g}", rf.getResult(), old_range); - for (unsigned n=0; n<10; ++n) + for (unsigned n = 0; n < 10; ++n) { rf.step(1); double range = rf.getRange(); @@ -61,6 +64,6 @@ TYPED_TEST(MathLibRegulaFalsi, QuadraticFunction) else { // The unmodified regula falsi method converges very slowly. - EXPECT_GT(100.0*std::numeric_limits<double>::epsilon(), error); + EXPECT_GT(100.0 * std::numeric_limits<double>::epsilon(), error); } } diff --git a/Tests/MathLib/TestODESolver.cpp b/Tests/MathLib/TestODESolver.cpp index 94a7d0c142b34675784c922fa56894b338923cf5..91fc28af536fc8ed0c2bc7ddd83062af40bc7393 100644 --- a/Tests/MathLib/TestODESolver.cpp +++ b/Tests/MathLib/TestODESolver.cpp @@ -8,13 +8,13 @@ */ #include <gtest/gtest.h> -#include "BaseLib/Logging.h" #include "BaseLib/ConfigTree.h" +#include "BaseLib/Logging.h" #include "MathLib/ODE/ODESolverBuilder.h" -namespace TestODESolver { - +namespace TestODESolver +{ const double abs_tol = 1e-8; const double rel_tol = 1e-8; @@ -81,8 +81,7 @@ std::unique_ptr<MathLib::ODE::ODESolver<NumEquations>> make_ode_solver( // any external ODE solver lib. if (!any_ode_solver_libs_available()) { - ERR( - "I cannot create any ODE solver. This test therefore might be " + ERR("I cannot create any ODE solver. This test therefore might be " "skipped."); return nullptr; } @@ -184,8 +183,7 @@ TEST(MathLibCVodeTest, ExponentialExtraData) ExtraData data; auto f_lambda = [&](double t, MathLib::ODE::MappedConstVector<1> const& y, - MathLib::ODE::MappedVector<1>& ydot) - { + MathLib::ODE::MappedVector<1>& ydot) { return f_extra(t, y, ydot, data); }; @@ -318,4 +316,4 @@ TEST(MathLibCVodeTest, ExponentialWithJacobianNewton) } } -} // end namespace +} // namespace TestODESolver diff --git a/Tests/MathLib/TestPiecewiseLinearCurve.cpp b/Tests/MathLib/TestPiecewiseLinearCurve.cpp index 9bd4e0da0e424c1cdbcf740fee094e3e7cd7fd88..72c1348bcfe71faeb0e2bfe1efb120d85a69890f 100644 --- a/Tests/MathLib/TestPiecewiseLinearCurve.cpp +++ b/Tests/MathLib/TestPiecewiseLinearCurve.cpp @@ -10,16 +10,15 @@ * Created on November 11, 2016, 10:58 AM */ +#include <gtest/gtest.h> + #include <cmath> #include <limits> -#include "gtest/gtest.h" -#include "Tests/TestTools.h" - #include "BaseLib/ConfigTree.h" - #include "MathLib/Curve/CreatePiecewiseLinearCurve.h" #include "MathLib/Curve/PiecewiseLinearMonotonicCurve.h" +#include "Tests/TestTools.h" template <typename CurveType> std::unique_ptr<CurveType> createPiecewiseLinearCurve(const char xml[]) diff --git a/Tests/MathLib/TestPiecewiseLinearInterpolation.cpp b/Tests/MathLib/TestPiecewiseLinearInterpolation.cpp index acf3556c5efe5b52d2903ac83b5c737a32fd1fae..2fffcca6a72e0bf2c1a7cbdafe471ccb95d4b131 100644 --- a/Tests/MathLib/TestPiecewiseLinearInterpolation.cpp +++ b/Tests/MathLib/TestPiecewiseLinearInterpolation.cpp @@ -14,7 +14,7 @@ #include <limits> // google test -#include "gtest/gtest.h" +#include <gtest/gtest.h> #include "MathLib/InterpolationAlgorithms/PiecewiseLinearInterpolation.h" @@ -145,13 +145,13 @@ TEST(MathLibInterpolationAlgorithms, PiecewiseLinearInterpolationDerivative) interpolation.getDerivative(k + 0.5), std::numeric_limits<double>::epsilon()); } - //check, if a point is located between the first and second points + // check, if a point is located between the first and second points //(or last and second to last point), the derivative is calculated - //using linear interpolation. + // using linear interpolation. ASSERT_NEAR(2.6, interpolation.getDerivative(1.3), - std::numeric_limits<double>::epsilon()); + std::numeric_limits<double>::epsilon()); ASSERT_NEAR(1995, interpolation.getDerivative(997.3), - std::numeric_limits<double>::epsilon()); + std::numeric_limits<double>::epsilon()); // max and min value test ASSERT_NEAR(1, interpolation.getDerivative(0), std::numeric_limits<double>::epsilon()); diff --git a/Tests/MathLib/TestPoint3d.cpp b/Tests/MathLib/TestPoint3d.cpp index 7e102ad6d23e0d42bd8b0ed55674b89cbcc856f8..41d7bce39633af21af933a0141f8cfc9371d5d44 100644 --- a/Tests/MathLib/TestPoint3d.cpp +++ b/Tests/MathLib/TestPoint3d.cpp @@ -10,12 +10,12 @@ * http://www.opengeosys.org/project/license */ -#include <ctime> #include <gtest/gtest.h> + #include <autocheck/autocheck.hpp> +#include <ctime> #include "MathLib/Point3d.h" - #include "Tests/AutoCheckTools.h" using namespace MathLib; @@ -35,8 +35,7 @@ struct MathLibPoint3d : public ::testing::Test TEST_F(MathLibPoint3d, ComparisonOperatorLessEqSamePoint) { // A point is always less or equal to itself and its copy. - auto samePointLessEqualCompare = [](MathLib::Point3d const& p) - { + auto samePointLessEqualCompare = [](MathLib::Point3d const& p) { const auto& q = p; return lessEq(p, p) && lessEq(p, q) && lessEq(q, p); }; @@ -51,10 +50,9 @@ TEST_F(MathLibPoint3d, ComparisonOperatorLessEqualLargePerturbation) // A point with any big, positive value added to one of its coordinates is // never smaller or equal to the original point. // And the original point is always smaller or equal to the perturbed point. - auto pointWithLargeAddedValue = - [](MathLib::Point3d const& p, double const perturbation, - unsigned const coordinate) - { + auto pointWithLargeAddedValue = [](MathLib::Point3d const& p, + double const perturbation, + unsigned const coordinate) { auto q = p; q[coordinate] = q[coordinate] + perturbation; return !lessEq(q, p) && lessEq(p, q); @@ -78,10 +76,9 @@ TEST_F(MathLibPoint3d, ComparisonOperatorLessEqualSmallPerturbation) // A point with any non-zero value smaller than epsilon/2 added to one of // its // coordinates is always less or equal to the original point. - auto pointWithSmallAddedValue = - [](MathLib::Point3d const& p, double const perturbation, - unsigned const coordinate) - { + auto pointWithSmallAddedValue = [](MathLib::Point3d const& p, + double const perturbation, + unsigned const coordinate) { auto q = p; q[coordinate] = q[coordinate] + perturbation; return lessEq(p, q) && lessEq(q, p); @@ -100,8 +97,7 @@ TEST_F(MathLibPoint3d, ComparisonOperatorLessEqualSmallPerturbation) TEST_F(MathLibPoint3d, ComparisonOperatorEqualSamePoint) { // A point is always equal to itself and its copy. - auto samePointEqualCompare = [](MathLib::Point3d const& p) - { + auto samePointEqualCompare = [](MathLib::Point3d const& p) { const auto& q = p; return (p == p) && (p == q) && (q == p); }; @@ -115,10 +111,9 @@ TEST_F(MathLibPoint3d, ComparisonOperatorEqualLargePerturbation) { // A point with any big, non-zero value added to one of its coordinates is // never equal to the original point. - auto pointWithLargeAddedValue = - [](MathLib::Point3d const& p, double const perturbation, - unsigned const coordinate) - { + auto pointWithLargeAddedValue = [](MathLib::Point3d const& p, + double const perturbation, + unsigned const coordinate) { auto q = p; q[coordinate] = q[coordinate] + perturbation; return !(p == q) && !(q == p); @@ -141,10 +136,9 @@ TEST_F(MathLibPoint3d, ComparisonOperatorEqualSmallPerturbation) // A point with any non-zero value smaller than epsilon/2 added to one of // its // coordinates is always equal to the original point. - auto pointWithSmallAddedValue = - [](MathLib::Point3d const& p, double const perturbation, - unsigned const coordinate) - { + auto pointWithSmallAddedValue = [](MathLib::Point3d const& p, + double const perturbation, + unsigned const coordinate) { auto q = p; q[coordinate] = q[coordinate] + perturbation; return (p == q) && (q == p); @@ -164,8 +158,7 @@ TEST_F(MathLibPoint3d, ComparisonOperatorEqualSmallPerturbation) TEST_F(MathLibPoint3d, ComparisonOperatorLessSamePoint) { // A point is never less than itself or its copy. - auto samePointLessCompare = [](MathLib::Point3d const& p) - { + auto samePointLessCompare = [](MathLib::Point3d const& p) { const auto& q = p; return !(p < p) && !(p < q) && !(q < p); }; @@ -180,8 +173,7 @@ TEST_F(MathLibPoint3d, ComparisonOperatorLessLargePerturbation) // A point with any positive value added to one of its coordinates is // always larger then the original point. auto pointWithAddedValue = [](MathLib::Point3d const& p, double const eps, - unsigned const coordinate) - { + unsigned const coordinate) { auto q = p; q[coordinate] = q[coordinate] + eps; return (p < q) && !(q < p); @@ -201,9 +193,9 @@ TEST_F(MathLibPoint3d, ComparisonOperatorLessSmallPerturbation) { // A point with any positive value subtracted from one of its coordinates is // always smaller then the original point. - auto pointWithSubtractedValue = []( - MathLib::Point3d const& p, double const eps, unsigned const coordinate) - { + auto pointWithSubtractedValue = [](MathLib::Point3d const& p, + double const eps, + unsigned const coordinate) { auto q = p; q[coordinate] = q[coordinate] - eps; return (q < p) && !(p < q); diff --git a/Tests/MathLib/TestPoint3dWithID.cpp b/Tests/MathLib/TestPoint3dWithID.cpp index e40c86b8ddfd33cb67a246b0695b1fbf91e10ea7..d80a021d53b744dea1738c7a57ce1f5254b2d28d 100644 --- a/Tests/MathLib/TestPoint3dWithID.cpp +++ b/Tests/MathLib/TestPoint3dWithID.cpp @@ -9,9 +9,9 @@ * http://www.opengeosys.org/project/license */ -#include <ctime> +#include <gtest/gtest.h> -#include "gtest/gtest.h" +#include <ctime> #include "MathLib/Point3dWithID.h" @@ -19,11 +19,10 @@ using namespace MathLib; TEST(MathLib, Point3dWithID) { - Point3dWithID p0(0,0,0,1); - const Point3dWithID& p1(p0); // copy constructor - Point3dWithID p2(p0, 2); // constructor for resetting the id + Point3dWithID p0(0, 0, 0, 1); + const Point3dWithID& p1(p0); // copy constructor + Point3dWithID p2(p0, 2); // constructor for resetting the id EXPECT_EQ(p0.getID(), p1.getID()); EXPECT_NE(p0.getID(), p2.getID()); } - diff --git a/Tests/MathLib/TestTemplatePoint.cpp b/Tests/MathLib/TestTemplatePoint.cpp index 65cf5c3e782e84d730ff47ea9f8f0a7bbedc7242..5b0ec339b2fef5dd710901f46a55880a70a0c504 100644 --- a/Tests/MathLib/TestTemplatePoint.cpp +++ b/Tests/MathLib/TestTemplatePoint.cpp @@ -9,9 +9,9 @@ * http://www.opengeosys.org/project/license */ -#include <array> +#include <gtest/gtest.h> -#include "gtest/gtest.h" +#include <array> #include "MathLib/TemplatePoint.h" @@ -20,17 +20,17 @@ using namespace MathLib; TEST(MathLib, TemplatePointConstructors) { // *** test default constructors for different DIM values - TemplatePoint<double,3> p0; + TemplatePoint<double, 3> p0; // test coordinates of default constructed point ASSERT_EQ(0.0, p0[0]); ASSERT_EQ(0.0, p0[1]); ASSERT_EQ(0.0, p0[2]); - TemplatePoint<double,2> p1; + TemplatePoint<double, 2> p1; ASSERT_EQ(0.0, p1[0]); ASSERT_EQ(0.0, p1[1]); - TemplatePoint<double,5> p2; + TemplatePoint<double, 5> p2; ASSERT_EQ(0.0, p2[0]); ASSERT_EQ(0.0, p2[1]); ASSERT_EQ(0.0, p2[2]); @@ -38,14 +38,14 @@ TEST(MathLib, TemplatePointConstructors) ASSERT_EQ(0.0, p2[4]); // *** test copy constructor - TemplatePoint<double,3> p0_copy(p0); + TemplatePoint<double, 3> p0_copy(p0); // test equality of coordinates ASSERT_EQ(p0[0], p0_copy[0]); ASSERT_EQ(p0[1], p0_copy[1]); ASSERT_EQ(p0[2], p0_copy[2]); // *** test constructor taking std::array - std::array<double,3> array = {{0, 1, 2}}; + std::array<double, 3> array = {{0, 1, 2}}; TemplatePoint<double> p3(array); ASSERT_EQ(0.0, p3[0]); ASSERT_EQ(1.0, p3[1]); @@ -54,7 +54,7 @@ TEST(MathLib, TemplatePointConstructors) TEST(MathLib, TemplatePointOperators) { - TemplatePoint<double,3> p; + TemplatePoint<double, 3> p; // access operator p[0] = 1.0; p[1] = 3.0; @@ -63,4 +63,3 @@ TEST(MathLib, TemplatePointOperators) ASSERT_EQ(3.0, p[1]); ASSERT_EQ(5.0, p[2]); } - diff --git a/Tests/MathLib/TestWeightedPoint.cpp b/Tests/MathLib/TestWeightedPoint.cpp index 21465766fb64b1b22f0f65f593eb57e1d3281a50..e46590fd6b50fec5d14e3e72ea9e7edbd5a3ecd7 100644 --- a/Tests/MathLib/TestWeightedPoint.cpp +++ b/Tests/MathLib/TestWeightedPoint.cpp @@ -7,7 +7,7 @@ * http://www.opengeosys.org/project/license */ -#include "gtest/gtest.h" +#include <gtest/gtest.h> #include "MathLib/TemplateWeightedPoint.h" diff --git a/Tests/MeshGeoToolsLib/TestConstructAdditionalMeshesFromGeoObjects.cpp b/Tests/MeshGeoToolsLib/TestConstructAdditionalMeshesFromGeoObjects.cpp index e61cb23b323e3915cb767b6d8180aae71a4413c5..7b387d7277dd56bf0d3d151fbe52181da61d9d8c 100644 --- a/Tests/MeshGeoToolsLib/TestConstructAdditionalMeshesFromGeoObjects.cpp +++ b/Tests/MeshGeoToolsLib/TestConstructAdditionalMeshesFromGeoObjects.cpp @@ -8,6 +8,7 @@ */ #include <gtest/gtest.h> + #include <ctime> #include <memory> @@ -88,4 +89,3 @@ TEST(ConstructAdditionalMeshesFromGeoObjects, PointMeshLargeSearchRadius) ASSERT_EQ(geometries.getPointVec(geometry_name)->size(), meshes_from_multiple_nodes.size()); } - diff --git a/Tests/MeshGeoToolsLib/TestGeoMapper.cpp b/Tests/MeshGeoToolsLib/TestGeoMapper.cpp index 3505222adb22e8e82203b2cae1856d407fee4308..3a10444d911235870e721c1257355ee2098bf243 100644 --- a/Tests/MeshGeoToolsLib/TestGeoMapper.cpp +++ b/Tests/MeshGeoToolsLib/TestGeoMapper.cpp @@ -7,15 +7,16 @@ * http://www.opengeosys.org/project/license */ +#include <gtest/gtest.h> + #include <ctime> #include <memory> -#include <gtest/gtest.h> #include "GeoLib/GEOObjects.h" #include "GeoLib/Point.h" +#include "MeshGeoToolsLib/GeoMapper.h" #include "MeshLib/Mesh.h" #include "MeshLib/MeshGenerators/MeshGenerator.h" -#include "MeshGeoToolsLib/GeoMapper.h" #include "Tests/AutoCheckTools.h" namespace ac = autocheck; @@ -33,9 +34,9 @@ struct MeshGeoToolsLibGeoMapper : public ::testing::Test // by the given function, i.e., std::cos(x+y). std::unique_ptr<MeshLib::Mesh> _surface_mesh{ MeshLib::MeshGenerator::createSurfaceMesh( - "Test", MathLib::Point3d{ {{0.0, 0.0, 0.0}} }, - MathLib::Point3d{ {{1.0, 1.0, 0.0}} }, {{110,60}}, - [](double x, double y) { return std::cos(x+y); })}; + "Test", MathLib::Point3d{{{0.0, 0.0, 0.0}}}, + MathLib::Point3d{{{1.0, 1.0, 0.0}}}, {{110, 60}}, + [](double x, double y) { return std::cos(x + y); })}; ac::gtest_reporter gtest_reporter; }; @@ -47,9 +48,8 @@ struct MeshGeoToolsLibGeoMapper : public ::testing::Test // assumed that the mapping is correct. TEST_F(MeshGeoToolsLibGeoMapper, PointsOnSurfaceMesh) { - auto testMapPointsOnMeshSurface = [this]( - std::vector<GeoLib::Point>& pnts) -> bool - { + auto testMapPointsOnMeshSurface = + [this](std::vector<GeoLib::Point>& pnts) -> bool { GeoLib::GEOObjects geo_obj; std::string geo_name("TestGeoMapperPoints"); auto points = std::make_unique<std::vector<GeoLib::Point*>>(); @@ -69,7 +69,7 @@ TEST_F(MeshGeoToolsLibGeoMapper, PointsOnSurfaceMesh) GeoLib::Point const& p(*pnt); if (0.0 <= p[0] && p[0] <= 1.0 && 0.0 <= p[1] && p[1] <= 1.0) { - if (std::abs(std::cos(p[0]+p[1]) - p[2]) >= eps) + if (std::abs(std::cos(p[0] + p[1]) - p[2]) >= eps) { INFO("std::cos({:f} + {:f}) = {:f}, {:f}", p[0], p[1], cos(p[0] + p[1]), p[2]); @@ -83,7 +83,6 @@ TEST_F(MeshGeoToolsLibGeoMapper, PointsOnSurfaceMesh) ac::check<std::vector<GeoLib::Point>>( testMapPointsOnMeshSurface, 10, - ac::make_arbitrary(ac::fix(100,list_of(points_gen))), + ac::make_arbitrary(ac::fix(100, list_of(points_gen))), gtest_reporter); } - diff --git a/Tests/MeshLib/ConvertToLinearMesh.cpp b/Tests/MeshLib/ConvertToLinearMesh.cpp index 0ecfc479a38b756aaeff844e0a6a5b18ad3d846f..86850d43995c267f3789c8facde27a99f85378ec 100644 --- a/Tests/MeshLib/ConvertToLinearMesh.cpp +++ b/Tests/MeshLib/ConvertToLinearMesh.cpp @@ -7,7 +7,10 @@ * http://www.opengeosys.org/project/license */ +#include "MeshLib/MeshEditing/ConvertToLinearMesh.h" + #include <gtest/gtest.h> + #include <algorithm> #include <numeric> #include <random> @@ -15,7 +18,6 @@ #include "MeshLib/Elements/Element.h" #include "MeshLib/Mesh.h" -#include "MeshLib/MeshEditing/ConvertToLinearMesh.h" #include "MeshLib/MeshGenerators/MeshGenerator.h" #include "MeshLib/MeshGenerators/QuadraticMeshGenerator.h" #include "MeshLib/Node.h" diff --git a/Tests/MeshLib/MeshProperties.cpp b/Tests/MeshLib/MeshProperties.cpp index 29a51a9102a8ff34353a0307b475065bb6c1a65a..a0a1b668c9e8342a6800f95a844eedee2c02ef53 100644 --- a/Tests/MeshLib/MeshProperties.cpp +++ b/Tests/MeshLib/MeshProperties.cpp @@ -7,15 +7,14 @@ * http://www.opengeosys.org/project/license */ -#include <numeric> +#include <gtest/gtest.h> #include <Eigen/Eigen> +#include <numeric> -#include "gtest/gtest.h" - -#include "MeshLib/MeshGenerators/MeshGenerator.h" -#include "MeshLib/Mesh.h" #include "MeshLib/Elements/Element.h" +#include "MeshLib/Mesh.h" +#include "MeshLib/MeshGenerators/MeshGenerator.h" #include "MeshLib/PropertyVector.h" class MeshLibProperties : public ::testing::Test @@ -69,7 +68,7 @@ TEST_F(MeshLibProperties, PropertyVectorTestIntegrationPoint) p.resize(mesh->getNumberOfElements() * n_integration_points); std::vector<std::size_t> offsets(mesh->getNumberOfElements()); - std::size_t offset = 0; // last position in the property vector + std::size_t offset = 0; // last position in the property vector for (auto const& e : mesh->getElements()) { offsets[e->getID()] = offset; @@ -106,7 +105,7 @@ TEST_F(MeshLibProperties, PropertyVectorTestIntegrationPoint) TEST_F(MeshLibProperties, AddDoubleProperties) { ASSERT_TRUE(mesh != nullptr); - const std::size_t size(mesh_size*mesh_size*mesh_size); + const std::size_t size(mesh_size * mesh_size * mesh_size); std::string const prop_name("TestProperty"); auto* const double_properties = @@ -118,14 +117,16 @@ TEST_F(MeshLibProperties, AddDoubleProperties) ASSERT_EQ(size, double_properties->size()); std::iota(double_properties->begin(), double_properties->end(), 1); - for (std::size_t k(0); k<size; k++) { - ASSERT_EQ(static_cast<double>(k+1), (*double_properties)[k]); + for (std::size_t k(0); k < size; k++) + { + ASSERT_EQ(static_cast<double>(k + 1), (*double_properties)[k]); } ASSERT_TRUE(mesh->getProperties().existsPropertyVector<double>(prop_name)); auto* const double_properties_cpy = mesh->getProperties().getPropertyVector<double>(prop_name); - for (std::size_t k(0); k<size; k++) { + for (std::size_t k(0); k < size; k++) + { ASSERT_EQ((*double_properties)[k], (*double_properties_cpy)[k]); } @@ -141,10 +142,11 @@ TEST_F(MeshLibProperties, AddDoublePointerProperties) ASSERT_FALSE(mesh->getProperties().hasPropertyVector(prop_name)); // data needed for the property const std::size_t n_prop_val_groups(10); - const std::size_t n_items(mesh_size*mesh_size*mesh_size); + const std::size_t n_items(mesh_size * mesh_size * mesh_size); std::vector<std::size_t> prop_item2group_mapping(n_items); // create simple mat_group to index mapping - for (std::size_t j(0); j<n_prop_val_groups; j++) { + for (std::size_t j(0); j < n_prop_val_groups; j++) + { auto const lower(static_cast<std::size_t>( (static_cast<double>(j) / n_prop_val_groups) * n_items)); auto const upper(static_cast<std::size_t>( @@ -162,11 +164,13 @@ TEST_F(MeshLibProperties, AddDoublePointerProperties) ASSERT_EQ(prop_item2group_mapping.size(), group_properties->size()); // initialize the property values - for (std::size_t i(0); i<n_prop_val_groups; i++) { - group_properties->initPropertyValue(i, static_cast<double>(i+1)); + for (std::size_t i(0); i < n_prop_val_groups; i++) + { + group_properties->initPropertyValue(i, static_cast<double>(i + 1)); } // check mapping to values - for (std::size_t i(0); i<n_prop_val_groups; i++) { + for (std::size_t i(0); i < n_prop_val_groups; i++) + { auto const lower(static_cast<std::size_t>( (static_cast<double>(i) / n_prop_val_groups) * n_items)); auto const upper(static_cast<std::size_t>( @@ -185,7 +189,8 @@ TEST_F(MeshLibProperties, AddDoublePointerProperties) mesh->getProperties().getPropertyVector<double*>(prop_name); ASSERT_FALSE(!group_properties_cpy); - for (std::size_t k(0); k<n_items; k++) { + for (std::size_t k(0); k < n_items; k++) + { ASSERT_EQ((*group_properties)[k], (*group_properties_cpy)[k]); } @@ -199,10 +204,11 @@ TEST_F(MeshLibProperties, AddArrayPointerProperties) ASSERT_TRUE(mesh != nullptr); std::string const& prop_name("GroupPropertyWithArray"); const std::size_t n_prop_val_groups(10); - const std::size_t n_items(mesh_size*mesh_size*mesh_size); + const std::size_t n_items(mesh_size * mesh_size * mesh_size); std::vector<std::size_t> prop_item2group_mapping(n_items); // create simple mat_group to index mapping - for (std::size_t j(0); j<n_prop_val_groups; j++) { + for (std::size_t j(0); j < n_prop_val_groups; j++) + { auto const lower(static_cast<std::size_t>( (static_cast<double>(j) / n_prop_val_groups) * n_items)); auto const upper(static_cast<std::size_t>( @@ -219,16 +225,17 @@ TEST_F(MeshLibProperties, AddArrayPointerProperties) ASSERT_EQ(prop_item2group_mapping.size(), group_prop_vec->size()); // initialize the property values - for (std::size_t i(0); i<n_prop_val_groups; i++) { - group_prop_vec->initPropertyValue(i, - std::array<double,3>({{static_cast<double>(i), - static_cast<double>(i+1), - static_cast<double>(i+2)}} - ) - ); + for (std::size_t i(0); i < n_prop_val_groups; i++) + { + group_prop_vec->initPropertyValue( + i, + std::array<double, 3>( + {{static_cast<double>(i), static_cast<double>(i + 1), + static_cast<double>(i + 2)}})); } // check the mapping to values - for (std::size_t i(0); i<n_prop_val_groups; i++) { + for (std::size_t i(0); i < n_prop_val_groups; i++) + { auto const lower(static_cast<std::size_t>( (static_cast<double>(i) / n_prop_val_groups) * n_items)); auto const upper(static_cast<std::size_t>( @@ -249,13 +256,14 @@ TEST_F(MeshLibProperties, AddArrayPointerProperties) prop_name); ASSERT_FALSE(!group_properties_cpy); - for (std::size_t k(0); k<n_items; k++) { + for (std::size_t k(0); k < n_items; k++) + { ASSERT_EQ((*((*group_prop_vec)[k]))[0], - (*((*group_properties_cpy)[k]))[0]); + (*((*group_properties_cpy)[k]))[0]); ASSERT_EQ((*((*group_prop_vec)[k]))[1], - (*((*group_properties_cpy)[k]))[1]); + (*((*group_properties_cpy)[k]))[1]); ASSERT_EQ((*((*group_prop_vec)[k]))[2], - (*((*group_properties_cpy)[k]))[2]); + (*((*group_properties_cpy)[k]))[2]); } mesh->getProperties().removePropertyVector(prop_name); @@ -273,10 +281,11 @@ TEST_F(MeshLibProperties, AddVariousDifferentProperties) // check if the property is already assigned to the mesh ASSERT_FALSE(mesh->getProperties().hasPropertyVector(prop_name)); const std::size_t n_prop_val_groups(10); - const std::size_t n_items(mesh_size*mesh_size*mesh_size); + const std::size_t n_items(mesh_size * mesh_size * mesh_size); std::vector<std::size_t> prop_item2group_mapping(n_items); // create simple mat_group to index mapping - for (std::size_t j(0); j<n_prop_val_groups; j++) { + for (std::size_t j(0); j < n_prop_val_groups; j++) + { auto const lower(static_cast<std::size_t>( (static_cast<double>(j) / n_prop_val_groups) * n_items)); auto const upper(static_cast<std::size_t>( @@ -292,13 +301,13 @@ TEST_F(MeshLibProperties, AddVariousDifferentProperties) prop_name, n_prop_val_groups, prop_item2group_mapping, MeshLib::MeshItemType::Cell); // initialize the property values - for (std::size_t i(0); i<n_prop_val_groups; i++) { - group_properties->initPropertyValue(i, - std::array<double,3>({{static_cast<double>(i), - static_cast<double>(i+1), - static_cast<double>(i+2)}} - ) - ); + for (std::size_t i(0); i < n_prop_val_groups; i++) + { + group_properties->initPropertyValue( + i, + std::array<double, 3>( + {{static_cast<double>(i), static_cast<double>(i + 1), + static_cast<double>(i + 2)}})); } // the mesh should have the property assigned to cells @@ -310,21 +319,22 @@ TEST_F(MeshLibProperties, AddVariousDifferentProperties) prop_name); ASSERT_FALSE(!group_properties_cpy); // compare the content - const std::size_t n_elements(mesh_size*mesh_size*mesh_size); - for (std::size_t k(0); k<n_elements; k++) { + const std::size_t n_elements(mesh_size * mesh_size * mesh_size); + for (std::size_t k(0); k < n_elements; k++) + { ASSERT_EQ((*((*group_properties)[k]))[0], - (*((*group_properties_cpy)[k]))[0]); + (*((*group_properties_cpy)[k]))[0]); ASSERT_EQ((*((*group_properties)[k]))[1], - (*((*group_properties_cpy))[k])[1]); + (*((*group_properties_cpy))[k])[1]); ASSERT_EQ((*((*group_properties)[k]))[2], - (*((*group_properties_cpy)[k]))[2]); + (*((*group_properties_cpy)[k]))[2]); } // *** add a 2nd property *** std::string const& prop_name_2("ItemwiseMatrixProperties"); // check if the property is already assigned to the mesh ASSERT_FALSE(mesh->getProperties().hasPropertyVector(prop_name_2)); - const std::size_t n_items_2(mesh_size*mesh_size*mesh_size); + const std::size_t n_items_2(mesh_size * mesh_size * mesh_size); auto* const array_properties = mesh->getProperties().createNewPropertyVector<std::array<float, 9>>( prop_name_2, MeshLib::MeshItemType::Cell); @@ -332,10 +342,12 @@ TEST_F(MeshLibProperties, AddVariousDifferentProperties) array_properties->resize(n_items_2); // initialize the property values - for (std::size_t i(0); i<n_items_2; i++) { + for (std::size_t i(0); i < n_items_2; i++) + { // init property value - for (std::size_t k(0); k<(*array_properties)[i].size(); k++) { - (*array_properties)[i][k] = static_cast<float>(i+k); + for (std::size_t k(0); k < (*array_properties)[i].size(); k++) + { + (*array_properties)[i][k] = static_cast<float>(i + k); } } @@ -351,8 +363,10 @@ TEST_F(MeshLibProperties, AddVariousDifferentProperties) ASSERT_FALSE(!array_properties_cpy); // compare the values/matrices - for (std::size_t k(0); k<n_items_2; k++) { - for (std::size_t j(0); j<(*array_properties)[k].size(); j++) { + for (std::size_t k(0); k < n_items_2; k++) + { + for (std::size_t j(0); j < (*array_properties)[k].size(); j++) + { ASSERT_EQ((*array_properties)[k][j], (*array_properties_cpy)[k][j]); } } @@ -370,10 +384,13 @@ TEST_F(MeshLibProperties, AddVariousDifferentProperties) for (auto it = matrix_properties->begin(); it != matrix_properties->end(); it++) { - for (int r(0); r<it->rows(); r++) { - for (int c(0); c<it->cols(); c++) { - (*it)(r,c) = static_cast<double>( - std::distance(matrix_properties->begin(),it)+r*it->cols()+c+1); + for (int r(0); r < it->rows(); r++) + { + for (int c(0); c < it->cols(); c++) + { + (*it)(r, c) = static_cast<double>( + std::distance(matrix_properties->begin(), it) + + r * it->cols() + c + 1); } } } @@ -393,9 +410,11 @@ TEST_F(MeshLibProperties, AddVariousDifferentProperties) for (auto it = matrix_properties->begin(); it != matrix_properties->end(); it++, it_cpy++) { - for (int r(0); r<it->rows(); r++) { - for (int c(0); c<it->cols(); c++) { - ASSERT_EQ((*it)(r,c), (*it_cpy)(r,c)); + for (int r(0); r < it->rows(); r++) + { + for (int c(0); c < it->cols(); c++) + { + ASSERT_EQ((*it)(r, c), (*it_cpy)(r, c)); } } } @@ -407,10 +426,11 @@ TEST_F(MeshLibProperties, CopyConstructor) std::string const& prop_name("GroupProperty"); // data needed for the property const std::size_t n_prop_val_groups(10); - const std::size_t n_items(mesh_size*mesh_size*mesh_size); + const std::size_t n_items(mesh_size * mesh_size * mesh_size); std::vector<std::size_t> prop_item2group_mapping(n_items); // create simple mat_group to index mapping - for (std::size_t j(0); j<n_prop_val_groups; j++) { + for (std::size_t j(0); j < n_prop_val_groups; j++) + { auto const lower(static_cast<std::size_t>( (static_cast<double>(j) / n_prop_val_groups) * n_items)); auto const upper(static_cast<std::size_t>( @@ -424,11 +444,10 @@ TEST_F(MeshLibProperties, CopyConstructor) auto* const group_properties( mesh->getProperties().createNewPropertyVector<double*>( prop_name, n_prop_val_groups, prop_item2group_mapping, - MeshLib::MeshItemType::Cell - ) - ); + MeshLib::MeshItemType::Cell)); // initialize the property values - for (std::size_t i(0); i<n_prop_val_groups; i++) { + for (std::size_t i(0); i < n_prop_val_groups; i++) + { group_properties->initPropertyValue(i, static_cast<double>(i + 1)); } @@ -443,7 +462,8 @@ TEST_F(MeshLibProperties, CopyConstructor) // check if the values in the PropertyVector of the copy of the Properties // are the same - for (std::size_t k(0); k<n_items; k++) { + for (std::size_t k(0); k < n_items; k++) + { EXPECT_EQ(*(*group_properties)[k], *(*group_properties_cpy)[k]); } } @@ -451,7 +471,7 @@ TEST_F(MeshLibProperties, CopyConstructor) TEST_F(MeshLibProperties, AddDoublePropertiesTupleSize2) { ASSERT_TRUE(mesh != nullptr); - const std::size_t number_of_tuples(mesh_size*mesh_size*mesh_size); + const std::size_t number_of_tuples(mesh_size * mesh_size * mesh_size); std::string const prop_name("TestProperty"); auto* const pv = mesh->getProperties().createNewPropertyVector<double>( @@ -466,7 +486,8 @@ TEST_F(MeshLibProperties, AddDoublePropertiesTupleSize2) ASSERT_EQ(0u, pv->size()); // push some values (2 tuples) into the vector - for (std::size_t k(0); k<number_of_tuples; k++) { + for (std::size_t k(0); k < number_of_tuples; k++) + { pv->push_back(static_cast<double>(k)); pv->push_back(static_cast<double>(k)); } @@ -475,10 +496,9 @@ TEST_F(MeshLibProperties, AddDoublePropertiesTupleSize2) ASSERT_EQ(pv->getNumberOfTuples() * pv->getNumberOfGlobalComponents(), pv->size()); // check the values - for (std::size_t k(0); k<number_of_tuples; k++) { - ASSERT_EQ(static_cast<double>(k), (*pv)[2*k]); - ASSERT_EQ(static_cast<double>(k), (*pv)[2*k+1]); + for (std::size_t k(0); k < number_of_tuples; k++) + { + ASSERT_EQ(static_cast<double>(k), (*pv)[2 * k]); + ASSERT_EQ(static_cast<double>(k), (*pv)[2 * k + 1]); } } - - diff --git a/Tests/MeshLib/TestAddLayerToMesh.cpp b/Tests/MeshLib/TestAddLayerToMesh.cpp index ff7d442d2bf83f6d4d451ad3cdfb91e15b895c6a..37d0530c9ac07c458de9944ea013cb14a7f8f925 100644 --- a/Tests/MeshLib/TestAddLayerToMesh.cpp +++ b/Tests/MeshLib/TestAddLayerToMesh.cpp @@ -7,71 +7,78 @@ * http://www.opengeosys.org/project/license */ -#include <memory> +#include <gtest/gtest.h> -#include "gtest/gtest.h" +#include <memory> -#include "MeshLib/Mesh.h" -#include "MeshLib/Node.h" #include "MeshLib/Elements/Element.h" -#include "MeshLib/MeshInformation.h" -#include "MeshLib/MeshSurfaceExtraction.h" -#include "MeshLib/MeshGenerators/MeshGenerator.h" +#include "MeshLib/Mesh.h" #include "MeshLib/MeshEditing/AddLayerToMesh.h" +#include "MeshLib/MeshGenerators/MeshGenerator.h" +#include "MeshLib/MeshInformation.h" #include "MeshLib/MeshQuality/MeshValidation.h" +#include "MeshLib/MeshSurfaceExtraction.h" +#include "MeshLib/Node.h" namespace AddLayerValidation { - // validates mesh. for line meshes, node order tests will fail because vertical elements are - // created during the extrusion. Therefore node order tests are switched off for line meshes. - void validate(MeshLib::Mesh const& mesh, bool testNodeOrder) +// validates mesh. for line meshes, node order tests will fail because vertical +// elements are created during the extrusion. Therefore node order tests are +// switched off for line meshes. +void validate(MeshLib::Mesh const& mesh, bool testNodeOrder) +{ + int const reduce_tests = (testNodeOrder) ? 0 : 1; + + auto const nErrorFlags( + static_cast<std::size_t>(ElementErrorFlag::MaxValue)); + ElementErrorFlag const flags[nErrorFlags] = { + ElementErrorFlag::ZeroVolume, ElementErrorFlag::NonCoplanar, + ElementErrorFlag::NonConvex, ElementErrorFlag::NodeOrder}; + std::vector<ElementErrorCode> const codes( + MeshLib::MeshValidation::testElementGeometry(mesh)); + for (auto code : codes) { - int const reduce_tests = (testNodeOrder) ? 0 : 1; - - auto const nErrorFlags( - static_cast<std::size_t>(ElementErrorFlag::MaxValue)); - ElementErrorFlag const flags[nErrorFlags] = {ElementErrorFlag::ZeroVolume, - ElementErrorFlag::NonCoplanar, ElementErrorFlag::NonConvex, ElementErrorFlag::NodeOrder}; - std::vector<ElementErrorCode> const codes (MeshLib::MeshValidation::testElementGeometry(mesh)); - for (auto code : codes) + for (std::size_t j = 0; j < nErrorFlags - reduce_tests; ++j) { - for (std::size_t j = 0; j < nErrorFlags - reduce_tests; ++j) - { - ASSERT_FALSE(code[flags[j]]); - } + ASSERT_FALSE(code[flags[j]]); } } +} - void testZCoords2D(MeshLib::Mesh const& input, MeshLib::Mesh const& output, double height) +void testZCoords2D(MeshLib::Mesh const& input, MeshLib::Mesh const& output, + double height) +{ + std::size_t const nNodes(input.getNumberOfNodes()); + for (std::size_t i = 0; i < nNodes; ++i) { - std::size_t const nNodes (input.getNumberOfNodes()); - for (std::size_t i=0; i<nNodes; ++i) - { - ASSERT_EQ((*input.getNode(i))[2], (*output.getNode(i))[2]); - ASSERT_EQ((*input.getNode(i))[2] + height, (*output.getNode(nNodes+i))[2]); - } + ASSERT_EQ((*input.getNode(i))[2], (*output.getNode(i))[2]); + ASSERT_EQ((*input.getNode(i))[2] + height, + (*output.getNode(nNodes + i))[2]); } +} - void testZCoords3D(MeshLib::Mesh const& input, MeshLib::Mesh const& output, double height) +void testZCoords3D(MeshLib::Mesh const& input, MeshLib::Mesh const& output, + double height) +{ + std::size_t const nNodes(input.getNumberOfNodes()); + for (std::size_t i = 0; i < nNodes; ++i) { - std::size_t const nNodes (input.getNumberOfNodes()); - for (std::size_t i = 0; i < nNodes; ++i) - { - ASSERT_EQ((*input.getNode(i))[2] + height, (*output.getNode(i))[2]); - } + ASSERT_EQ((*input.getNode(i))[2] + height, (*output.getNode(i))[2]); } - } // namespace AddLayerValidation +} +} // namespace AddLayerValidation TEST(MeshLib, AddTopLayerToLineMesh) { - std::unique_ptr<MeshLib::Mesh> const mesh (MeshLib::MeshGenerator::generateLineMesh(1.0, 5)); - double const height (1); + std::unique_ptr<MeshLib::Mesh> const mesh( + MeshLib::MeshGenerator::generateLineMesh(1.0, 5)); + double const height(1); constexpr bool const copy_material_ids = false; std::unique_ptr<MeshLib::Mesh> const result(MeshLib::addLayerToMesh( *mesh, height, "mesh", true, copy_material_ids)); - ASSERT_EQ(2*mesh->getNumberOfNodes(), result->getNumberOfNodes()); - ASSERT_EQ(2*mesh->getNumberOfElements(), result->getNumberOfElements()); + ASSERT_EQ(2 * mesh->getNumberOfNodes(), result->getNumberOfNodes()); + ASSERT_EQ(2 * mesh->getNumberOfElements(), result->getNumberOfElements()); auto const& n_elems = MeshLib::MeshInformation::getNumberOfElementTypes(*result); @@ -84,14 +91,15 @@ TEST(MeshLib, AddTopLayerToLineMesh) TEST(MeshLib, AddBottomLayerToLineMesh) { - std::unique_ptr<MeshLib::Mesh> const mesh (MeshLib::MeshGenerator::generateLineMesh(1.0, 5)); - double const height (1); + std::unique_ptr<MeshLib::Mesh> const mesh( + MeshLib::MeshGenerator::generateLineMesh(1.0, 5)); + double const height(1); constexpr bool const copy_material_ids = false; std::unique_ptr<MeshLib::Mesh> const result(MeshLib::addLayerToMesh( *mesh, height, "mesh", false, copy_material_ids)); - ASSERT_EQ(2*mesh->getNumberOfNodes(), result->getNumberOfNodes()); - ASSERT_EQ(2*mesh->getNumberOfElements(), result->getNumberOfElements()); + ASSERT_EQ(2 * mesh->getNumberOfNodes(), result->getNumberOfNodes()); + ASSERT_EQ(2 * mesh->getNumberOfElements(), result->getNumberOfElements()); auto const& n_elems = MeshLib::MeshInformation::getNumberOfElementTypes(*result); @@ -104,8 +112,9 @@ TEST(MeshLib, AddBottomLayerToLineMesh) TEST(MeshLib, AddTopLayerToTriMesh) { - std::unique_ptr<MeshLib::Mesh> const mesh (MeshLib::MeshGenerator::generateRegularTriMesh(5, 5)); - std::string const& mat_name ("MaterialIDs"); + std::unique_ptr<MeshLib::Mesh> const mesh( + MeshLib::MeshGenerator::generateRegularTriMesh(5, 5)); + std::string const& mat_name("MaterialIDs"); auto* const mats = mesh->getProperties().createNewPropertyVector<int>( mat_name, MeshLib::MeshItemType::Cell); if (mats) @@ -119,13 +128,13 @@ TEST(MeshLib, AddTopLayerToTriMesh) test->resize(mesh->getNumberOfElements(), 0.1); } ASSERT_EQ(2, mesh->getProperties().size()); - double const height (1); + double const height(1); constexpr bool copy_material_ids = false; - std::unique_ptr<MeshLib::Mesh> const result (MeshLib::addLayerToMesh(*mesh, - height, "mesh", true, copy_material_ids)); + std::unique_ptr<MeshLib::Mesh> const result(MeshLib::addLayerToMesh( + *mesh, height, "mesh", true, copy_material_ids)); - ASSERT_EQ(2*mesh->getNumberOfNodes(), result->getNumberOfNodes()); - ASSERT_EQ(2*mesh->getNumberOfElements(), result->getNumberOfElements()); + ASSERT_EQ(2 * mesh->getNumberOfNodes(), result->getNumberOfNodes()); + ASSERT_EQ(2 * mesh->getNumberOfElements(), result->getNumberOfElements()); auto const& n_elems = MeshLib::MeshInformation::getNumberOfElementTypes(*result); @@ -138,22 +147,25 @@ TEST(MeshLib, AddTopLayerToTriMesh) auto const* const new_mats = result->getProperties().getPropertyVector<int>(mat_name); ASSERT_EQ(result->getNumberOfElements(), new_mats->size()); - ASSERT_EQ(mesh->getNumberOfElements(), std::count(new_mats->cbegin(), new_mats->cend(), 0)); - ASSERT_EQ(mesh->getNumberOfElements(), std::count(new_mats->cbegin(), new_mats->cend(), 1)); + ASSERT_EQ(mesh->getNumberOfElements(), + std::count(new_mats->cbegin(), new_mats->cend(), 0)); + ASSERT_EQ(mesh->getNumberOfElements(), + std::count(new_mats->cbegin(), new_mats->cend(), 1)); AddLayerValidation::testZCoords2D(*mesh, *result, height); AddLayerValidation::validate(*result, true); } TEST(MeshLib, AddBottomLayerToTriMesh) { - std::unique_ptr<MeshLib::Mesh> const mesh (MeshLib::MeshGenerator::generateRegularTriMesh(5, 5)); - double const height (1); + std::unique_ptr<MeshLib::Mesh> const mesh( + MeshLib::MeshGenerator::generateRegularTriMesh(5, 5)); + double const height(1); constexpr bool copy_material_ids = false; std::unique_ptr<MeshLib::Mesh> const result(MeshLib::addLayerToMesh( *mesh, height, "mesh", false, copy_material_ids)); - ASSERT_EQ(2*mesh->getNumberOfNodes(), result->getNumberOfNodes()); - ASSERT_EQ(2*mesh->getNumberOfElements(), result->getNumberOfElements()); + ASSERT_EQ(2 * mesh->getNumberOfNodes(), result->getNumberOfNodes()); + ASSERT_EQ(2 * mesh->getNumberOfElements(), result->getNumberOfElements()); auto const& n_elems = MeshLib::MeshInformation::getNumberOfElementTypes(*result); @@ -166,14 +178,15 @@ TEST(MeshLib, AddBottomLayerToTriMesh) TEST(MeshLib, AddTopLayerToQuadMesh) { - std::unique_ptr<MeshLib::Mesh> const mesh (MeshLib::MeshGenerator::generateRegularQuadMesh(5, 5)); - double const height (1); + std::unique_ptr<MeshLib::Mesh> const mesh( + MeshLib::MeshGenerator::generateRegularQuadMesh(5, 5)); + double const height(1); constexpr bool copy_material_ids = false; std::unique_ptr<MeshLib::Mesh> const result(MeshLib::addLayerToMesh( *mesh, height, "mesh", true, copy_material_ids)); - ASSERT_EQ(2*mesh->getNumberOfNodes(), result->getNumberOfNodes()); - ASSERT_EQ(2*mesh->getNumberOfElements(), result->getNumberOfElements()); + ASSERT_EQ(2 * mesh->getNumberOfNodes(), result->getNumberOfNodes()); + ASSERT_EQ(2 * mesh->getNumberOfElements(), result->getNumberOfElements()); auto const& n_elems = MeshLib::MeshInformation::getNumberOfElementTypes(*result); @@ -186,14 +199,15 @@ TEST(MeshLib, AddTopLayerToQuadMesh) TEST(MeshLib, AddBottomLayerToQuadMesh) { - std::unique_ptr<MeshLib::Mesh> const mesh (MeshLib::MeshGenerator::generateRegularQuadMesh(5, 5)); - double const height (1); + std::unique_ptr<MeshLib::Mesh> const mesh( + MeshLib::MeshGenerator::generateRegularQuadMesh(5, 5)); + double const height(1); constexpr bool copy_material_ids = false; std::unique_ptr<MeshLib::Mesh> const result(MeshLib::addLayerToMesh( *mesh, height, "mesh", false, copy_material_ids)); - ASSERT_EQ(2*mesh->getNumberOfNodes(), result->getNumberOfNodes()); - ASSERT_EQ(2*mesh->getNumberOfElements(), result->getNumberOfElements()); + ASSERT_EQ(2 * mesh->getNumberOfNodes(), result->getNumberOfNodes()); + ASSERT_EQ(2 * mesh->getNumberOfElements(), result->getNumberOfElements()); auto const& n_elems = MeshLib::MeshInformation::getNumberOfElementTypes(*result); @@ -206,23 +220,24 @@ TEST(MeshLib, AddBottomLayerToQuadMesh) TEST(MeshLib, AddTopLayerToHexMesh) { - std::unique_ptr<MeshLib::Mesh> const mesh (MeshLib::MeshGenerator::generateRegularHexMesh(5, 5)); - double const height (1); + std::unique_ptr<MeshLib::Mesh> const mesh( + MeshLib::MeshGenerator::generateRegularHexMesh(5, 5)); + double const height(1); constexpr bool copy_material_ids = false; std::unique_ptr<MeshLib::Mesh> const result(MeshLib::addLayerToMesh( *mesh, height, "mesh", true, copy_material_ids)); - ASSERT_EQ(mesh->getNumberOfNodes(), result->getNumberOfNodes()-36); - ASSERT_EQ(mesh->getNumberOfElements(), result->getNumberOfElements()-25); + ASSERT_EQ(mesh->getNumberOfNodes(), result->getNumberOfNodes() - 36); + ASSERT_EQ(mesh->getNumberOfElements(), result->getNumberOfElements() - 25); auto const& n_elems = MeshLib::MeshInformation::getNumberOfElementTypes(*result); ASSERT_EQ(150, n_elems.at(MeshLib::MeshElemType::HEXAHEDRON)); Eigen::Vector3d const dir({0, 0, -1}); - std::unique_ptr<MeshLib::Mesh> const test_input ( + std::unique_ptr<MeshLib::Mesh> const test_input( MeshLib::MeshSurfaceExtraction::getMeshSurface(*mesh, dir, 90)); - std::unique_ptr<MeshLib::Mesh> const test_output ( + std::unique_ptr<MeshLib::Mesh> const test_output( MeshLib::MeshSurfaceExtraction::getMeshSurface(*result, dir, 90)); AddLayerValidation::testZCoords3D(*test_input, *test_output, height); AddLayerValidation::validate(*result, true); @@ -230,23 +245,24 @@ TEST(MeshLib, AddTopLayerToHexMesh) TEST(MeshLib, AddBottomLayerToHexMesh) { - std::unique_ptr<MeshLib::Mesh> const mesh (MeshLib::MeshGenerator::generateRegularHexMesh(5, 5)); - double const height (1); + std::unique_ptr<MeshLib::Mesh> const mesh( + MeshLib::MeshGenerator::generateRegularHexMesh(5, 5)); + double const height(1); constexpr bool copy_material_ids = false; std::unique_ptr<MeshLib::Mesh> const result(MeshLib::addLayerToMesh( *mesh, height, "mesh", false, copy_material_ids)); - ASSERT_EQ(mesh->getNumberOfNodes(), result->getNumberOfNodes()-36); - ASSERT_EQ(mesh->getNumberOfElements(), result->getNumberOfElements()-25); + ASSERT_EQ(mesh->getNumberOfNodes(), result->getNumberOfNodes() - 36); + ASSERT_EQ(mesh->getNumberOfElements(), result->getNumberOfElements() - 25); auto const& n_elems = MeshLib::MeshInformation::getNumberOfElementTypes(*result); ASSERT_EQ(150, n_elems.at(MeshLib::MeshElemType::HEXAHEDRON)); Eigen::Vector3d const dir({0, 0, 1}); - std::unique_ptr<MeshLib::Mesh> const test_input ( + std::unique_ptr<MeshLib::Mesh> const test_input( MeshLib::MeshSurfaceExtraction::getMeshSurface(*mesh, dir, 90)); - std::unique_ptr<MeshLib::Mesh> const test_output ( + std::unique_ptr<MeshLib::Mesh> const test_output( MeshLib::MeshSurfaceExtraction::getMeshSurface(*result, dir, 90)); AddLayerValidation::testZCoords3D(*test_input, *test_output, -1 * height); AddLayerValidation::validate(*result, true); @@ -254,16 +270,18 @@ TEST(MeshLib, AddBottomLayerToHexMesh) TEST(MeshLib, AddTopLayerToPrismMesh) { - std::unique_ptr<MeshLib::Mesh> const mesh (MeshLib::MeshGenerator::generateRegularTriMesh(5, 5)); + std::unique_ptr<MeshLib::Mesh> const mesh( + MeshLib::MeshGenerator::generateRegularTriMesh(5, 5)); constexpr bool copy_material_ids = false; - std::unique_ptr<MeshLib::Mesh> const mesh2(MeshLib::addLayerToMesh( - *mesh, 5, "mesh", true, copy_material_ids)); - double const height (1); + std::unique_ptr<MeshLib::Mesh> const mesh2( + MeshLib::addLayerToMesh(*mesh, 5, "mesh", true, copy_material_ids)); + double const height(1); std::unique_ptr<MeshLib::Mesh> const result(MeshLib::addLayerToMesh( *mesh2, height, "mesh", true, copy_material_ids)); - ASSERT_EQ(mesh2->getNumberOfNodes()/2.0 * 3, result->getNumberOfNodes()); - ASSERT_EQ(mesh2->getNumberOfElements()/2.0 * 3, result->getNumberOfElements()); + ASSERT_EQ(mesh2->getNumberOfNodes() / 2.0 * 3, result->getNumberOfNodes()); + ASSERT_EQ(mesh2->getNumberOfElements() / 2.0 * 3, + result->getNumberOfElements()); auto const& n_elems = MeshLib::MeshInformation::getNumberOfElementTypes(*result); @@ -271,9 +289,9 @@ TEST(MeshLib, AddTopLayerToPrismMesh) ASSERT_EQ(100, n_elems.at(MeshLib::MeshElemType::PRISM)); Eigen::Vector3d const dir({0, 0, -1}); - std::unique_ptr<MeshLib::Mesh> test_input ( + std::unique_ptr<MeshLib::Mesh> test_input( MeshLib::MeshSurfaceExtraction::getMeshSurface(*mesh2, dir, 90)); - std::unique_ptr<MeshLib::Mesh> test_output ( + std::unique_ptr<MeshLib::Mesh> test_output( MeshLib::MeshSurfaceExtraction::getMeshSurface(*result, dir, 90)); AddLayerValidation::testZCoords3D(*test_input, *test_output, height); AddLayerValidation::validate(*result, true); @@ -281,12 +299,13 @@ TEST(MeshLib, AddTopLayerToPrismMesh) TEST(MeshLib, AddBottomLayerToPrismMesh) { - std::unique_ptr<MeshLib::Mesh> const mesh (MeshLib::MeshGenerator::generateRegularTriMesh(5, 5)); + std::unique_ptr<MeshLib::Mesh> const mesh( + MeshLib::MeshGenerator::generateRegularTriMesh(5, 5)); constexpr bool copy_material_ids = false; - std::unique_ptr<MeshLib::Mesh> const mesh2(MeshLib::addLayerToMesh( - *mesh, 5, "mesh", true, copy_material_ids)); - double const height (1); - std::string const& mat_name ("MaterialIDs"); + std::unique_ptr<MeshLib::Mesh> const mesh2( + MeshLib::addLayerToMesh(*mesh, 5, "mesh", true, copy_material_ids)); + double const height(1); + std::string const& mat_name("MaterialIDs"); auto* const mats = mesh2->getProperties().createNewPropertyVector<int>( mat_name, MeshLib::MeshItemType::Cell); if (mats) @@ -296,8 +315,9 @@ TEST(MeshLib, AddBottomLayerToPrismMesh) std::unique_ptr<MeshLib::Mesh> const result(MeshLib::addLayerToMesh( *mesh2, height, "mesh", false, copy_material_ids)); - ASSERT_EQ(mesh2->getNumberOfNodes()/2.0 * 3, result->getNumberOfNodes()); - ASSERT_EQ(mesh2->getNumberOfElements()/2.0 * 3, result->getNumberOfElements()); + ASSERT_EQ(mesh2->getNumberOfNodes() / 2.0 * 3, result->getNumberOfNodes()); + ASSERT_EQ(mesh2->getNumberOfElements() / 2.0 * 3, + result->getNumberOfElements()); auto const& n_elems = MeshLib::MeshInformation::getNumberOfElementTypes(*result); @@ -309,13 +329,15 @@ TEST(MeshLib, AddBottomLayerToPrismMesh) auto const* const new_mats = result->getProperties().getPropertyVector<int>(mat_name); ASSERT_EQ(result->getNumberOfElements(), new_mats->size()); - ASSERT_EQ(mesh2->getNumberOfElements(), std::count(new_mats->cbegin(), new_mats->cend(), 0)); - ASSERT_EQ(mesh->getNumberOfElements(), std::count(new_mats->cbegin(), new_mats->cend(), 1)); + ASSERT_EQ(mesh2->getNumberOfElements(), + std::count(new_mats->cbegin(), new_mats->cend(), 0)); + ASSERT_EQ(mesh->getNumberOfElements(), + std::count(new_mats->cbegin(), new_mats->cend(), 1)); Eigen::Vector3d const dir({0, 0, 1}); - std::unique_ptr<MeshLib::Mesh> test_input ( + std::unique_ptr<MeshLib::Mesh> test_input( MeshLib::MeshSurfaceExtraction::getMeshSurface(*mesh2, dir, 90)); - std::unique_ptr<MeshLib::Mesh> test_output ( + std::unique_ptr<MeshLib::Mesh> test_output( MeshLib::MeshSurfaceExtraction::getMeshSurface(*result, dir, 90)); AddLayerValidation::testZCoords3D(*test_input, *test_output, -1 * height); AddLayerValidation::validate(*result, true); diff --git a/Tests/MeshLib/TestBoundaryElementSearch.cpp b/Tests/MeshLib/TestBoundaryElementSearch.cpp index e09645b6de808f3d62d708edafadef6d95a17196..4974497b00406d4c9ec1fe2c2f91e313b226fc20 100644 --- a/Tests/MeshLib/TestBoundaryElementSearch.cpp +++ b/Tests/MeshLib/TestBoundaryElementSearch.cpp @@ -7,14 +7,13 @@ * http://www.opengeosys.org/project/license */ -#include "gtest/gtest.h" +#include <gtest/gtest.h> #include <memory> #include <numeric> #include "GeoLib/Polyline.h" #include "GeoLib/Surface.h" - #include "MeshGeoToolsLib/BoundaryElementsSearcher.h" #include "MeshGeoToolsLib/HeuristicSearchLength.h" #include "MeshGeoToolsLib/MeshNodeSearcher.h" @@ -33,7 +32,8 @@ public: MeshLibBoundaryElementSearchInSimpleQuadMesh() : _quad_mesh(MeshGenerator::generateRegularQuadMesh( _geometric_size, _number_of_subdivisions_per_direction)) - {} + { + } ~MeshLibBoundaryElementSearchInSimpleQuadMesh() override { diff --git a/Tests/MeshLib/TestCoordinatesMappingLocal.cpp b/Tests/MeshLib/TestCoordinatesMappingLocal.cpp index 181dce4eb712ef1ec73c026c0fb047c22b5a8b09..ed0c62987e1699ce0dc1fdfb6d9f16a09fb99731 100644 --- a/Tests/MeshLib/TestCoordinatesMappingLocal.cpp +++ b/Tests/MeshLib/TestCoordinatesMappingLocal.cpp @@ -9,29 +9,24 @@ #include <gtest/gtest.h> -#include <limits> +#include <Eigen/Eigen> #include <algorithm> -#include <vector> #include <cmath> +#include <limits> #include <memory> - -#include <Eigen/Eigen> +#include <vector> #include "GeoLib/AnalyticalGeometry.h" - #include "MeshLib/CoordinateSystem.h" -#include "MeshLib/Node.h" +#include "MeshLib/ElementCoordinatesMappingLocal.h" #include "MeshLib/Elements/Element.h" #include "MeshLib/Elements/Line.h" #include "MeshLib/Elements/Quad.h" -#include "MeshLib/ElementCoordinatesMappingLocal.h" - +#include "MeshLib/Node.h" #include "Tests/TestTools.h" - namespace { - namespace TestLine2 { using ElementType = MeshLib::Line; @@ -44,34 +39,35 @@ std::unique_ptr<MeshLib::Line> createLine(std::array<double, 3> const& a, nodes[0] = new MeshLib::Node(a); nodes[1] = new MeshLib::Node(b); return std::make_unique<MeshLib::Line>(nodes); - } +} - std::unique_ptr<MeshLib::Line> createY() - { - return createLine({{0.0, -1.0, 0.0}}, {{0.0, 1.0, 0.0}}); - } +std::unique_ptr<MeshLib::Line> createY() +{ + return createLine({{0.0, -1.0, 0.0}}, {{0.0, 1.0, 0.0}}); +} - std::unique_ptr<MeshLib::Line> createZ() - { - return createLine({{0.0, 0.0, -1.0}}, {{0.0, 0.0, 1.0}}); - } +std::unique_ptr<MeshLib::Line> createZ() +{ + return createLine({{0.0, 0.0, -1.0}}, {{0.0, 0.0, 1.0}}); +} - std::unique_ptr<MeshLib::Line> createXY() - { - // 45degree inclined - return createLine({{0.0, 0.0, 0.0}}, {{2./sqrt(2), 2./sqrt(2), 0.0}}); - } +std::unique_ptr<MeshLib::Line> createXY() +{ + // 45degree inclined + return createLine({{0.0, 0.0, 0.0}}, {{2. / sqrt(2), 2. / sqrt(2), 0.0}}); +} - std::unique_ptr<MeshLib::Line> createXYZ() - { - return createLine({{0.0, 0.0, 0.0}}, {{2./sqrt(3), 2./sqrt(3), 2./sqrt(3)}}); - } +std::unique_ptr<MeshLib::Line> createXYZ() +{ + return createLine({{0.0, 0.0, 0.0}}, + {{2. / sqrt(3), 2. / sqrt(3), 2. / sqrt(3)}}); +} - } // namespace TestLine2 +} // namespace TestLine2 namespace TestQuad4 { - // Element information +// Element information using ElementType = MeshLib::Quad; const unsigned e_nnodes = ElementType::n_all_nodes; @@ -86,39 +82,36 @@ std::unique_ptr<MeshLib::Quad> createQuad(std::array<double, 3> const& a, nodes[2] = new MeshLib::Node(c); nodes[3] = new MeshLib::Node(d); return std::make_unique<MeshLib::Quad>(nodes); - } +} - // 2.5D case: inclined - std::unique_ptr<MeshLib::Quad> createXYZ() - { - // rotate 45 degree around x axis - return createQuad( - {{ 1.0, 0.7071067811865475, 0.7071067811865475}}, - {{-1.0, 0.7071067811865475, 0.7071067811865475}}, - {{-1.0, -0.7071067811865475, -0.7071067811865475}}, - {{ 1.0, -0.7071067811865475, -0.7071067811865475}}); - } +// 2.5D case: inclined +std::unique_ptr<MeshLib::Quad> createXYZ() +{ + // rotate 45 degree around x axis + return createQuad({{1.0, 0.7071067811865475, 0.7071067811865475}}, + {{-1.0, 0.7071067811865475, 0.7071067811865475}}, + {{-1.0, -0.7071067811865475, -0.7071067811865475}}, + {{1.0, -0.7071067811865475, -0.7071067811865475}}); +} - // 2.5D case: inclined - std::unique_ptr<MeshLib::Quad> createXZ() - { - return createQuad( - {{ 1.0, 0.0, 1.0}}, - {{-1.0, 0.0, 1.0}}, - {{-1.0, 0.0, -1.0}}, - {{ 1.0, 0.0, -1.0}}); - } +// 2.5D case: inclined +std::unique_ptr<MeshLib::Quad> createXZ() +{ + return createQuad({{1.0, 0.0, 1.0}}, + {{-1.0, 0.0, 1.0}}, + {{-1.0, 0.0, -1.0}}, + {{1.0, 0.0, -1.0}}); +} - // 2.5D case: inclined - std::unique_ptr<MeshLib::Quad> createYZ() - { - return createQuad( - {{0.0, 1.0, 1.0}}, - {{0.0, -1.0, 1.0}}, - {{0.0, -1.0, -1.0}}, - {{0.0, 1.0, -1.0}}); - } - } // namespace TestQuad4 +// 2.5D case: inclined +std::unique_ptr<MeshLib::Quad> createYZ() +{ + return createQuad({{0.0, 1.0, 1.0}}, + {{0.0, -1.0, 1.0}}, + {{0.0, -1.0, -1.0}}, + {{0.0, 1.0, -1.0}}); +} +} // namespace TestQuad4 #if 0 // keep this function for debugging @@ -143,14 +136,16 @@ void debugOutput(MeshLib::Element *ele, MeshLib::ElementCoordinatesMappingLocal #endif // check if using the rotation matrix results in the original coordinates -#define CHECK_COORDS(ele, mapping)\ - for (unsigned ii=0; ii<(ele)->getNumberOfNodes(); ii++) {\ - MathLib::Point3d global(matR*(mapping).getMappedCoordinates(ii));\ - const double eps(std::numeric_limits<double>::epsilon());\ - ASSERT_ARRAY_NEAR(&(*(ele)->getNode(ii))[0], global.getCoords(), 3u, eps);\ +#define CHECK_COORDS(ele, mapping) \ + for (unsigned ii = 0; ii < (ele)->getNumberOfNodes(); ii++) \ + { \ + MathLib::Point3d global(matR*(mapping).getMappedCoordinates(ii)); \ + const double eps(std::numeric_limits<double>::epsilon()); \ + ASSERT_ARRAY_NEAR(&(*(ele)->getNode(ii))[0], global.getCoords(), 3u, \ + eps); \ } -} //namespace +} // namespace TEST(MeshLib, CoordinatesMappingLocalLowerDimLineY) { @@ -159,14 +154,12 @@ TEST(MeshLib, CoordinatesMappingLocalLowerDimLineY) *ele, MeshLib::CoordinateSystem(MeshLib::CoordinateSystemType::Y) .getDimension()); auto matR(mapping.getRotationMatrixToGlobal()); - //debugOutput(ele, mapping); + // debugOutput(ele, mapping); - double exp_R[3*3] = {0, -1, 0, - 1, 0, 0, - 0, 0, 1}; + double exp_R[3 * 3] = {0, -1, 0, 1, 0, 0, 0, 0, 1}; const double eps(std::numeric_limits<double>::epsilon()); ASSERT_ARRAY_NEAR(exp_R, matR.data(), matR.size(), eps); - CHECK_COORDS(ele,mapping); + CHECK_COORDS(ele, mapping); for (std::size_t n = 0; n < ele->getNumberOfNodes(); ++n) { @@ -182,12 +175,12 @@ TEST(MeshLib, CoordinatesMappingLocalLowerDimLineZ) MeshLib::CoordinateSystem(MeshLib::CoordinateSystemType::Z) .getDimension()); auto matR(mapping.getRotationMatrixToGlobal()); - //debugOutput(ele, mapping); + // debugOutput(ele, mapping); - double exp_R[3*3] = {0, 0, -1, 0, 1, 0, 1, 0, 0}; + double exp_R[3 * 3] = {0, 0, -1, 0, 1, 0, 1, 0, 0}; const double eps(std::numeric_limits<double>::epsilon()); ASSERT_ARRAY_NEAR(exp_R, matR.data(), matR.size(), eps); - CHECK_COORDS(ele,mapping); + CHECK_COORDS(ele, mapping); for (std::size_t n = 0; n < ele->getNumberOfNodes(); ++n) { @@ -201,14 +194,20 @@ TEST(MeshLib, CoordinatesMappingLocalLowerDimLineXY) MeshLib::ElementCoordinatesMappingLocal mapping( *ele, MeshLib::CoordinateSystem(*ele).getDimension()); auto matR(mapping.getRotationMatrixToGlobal()); - //debugOutput(ele, mapping); - - double exp_R[3*3] = {0.70710678118654757, -0.70710678118654757, 0, - 0.70710678118654757, 0.70710678118654757, 0, - 0, 0, 1}; + // debugOutput(ele, mapping); + + double exp_R[3 * 3] = {0.70710678118654757, + -0.70710678118654757, + 0, + 0.70710678118654757, + 0.70710678118654757, + 0, + 0, + 0, + 1}; const double eps(std::numeric_limits<double>::epsilon()); ASSERT_ARRAY_NEAR(exp_R, matR.data(), matR.size(), eps); - CHECK_COORDS(ele,mapping); + CHECK_COORDS(ele, mapping); for (std::size_t n = 0; n < ele->getNumberOfNodes(); ++n) { @@ -222,14 +221,15 @@ TEST(MeshLib, CoordinatesMappingLocalLowerDimLineXYZ) MeshLib::ElementCoordinatesMappingLocal mapping( *ele, MeshLib::CoordinateSystem(*ele).getDimension()); auto matR(mapping.getRotationMatrixToGlobal()); - //debugOutput(ele, mapping); + // debugOutput(ele, mapping); - double exp_R[3*3] = {0.57735026918962584, -0.81649658092772626, 0, - 0.57735026918962584, 0.40824829046386313, -0.70710678118654757, - 0.57735026918962584, 0.40824829046386313, 0.70710678118654757}; + double exp_R[3 * 3] = { + 0.57735026918962584, -0.81649658092772626, 0, + 0.57735026918962584, 0.40824829046386313, -0.70710678118654757, + 0.57735026918962584, 0.40824829046386313, 0.70710678118654757}; const double eps(std::numeric_limits<double>::epsilon()); ASSERT_ARRAY_NEAR(exp_R, matR.data(), matR.size(), eps); - CHECK_COORDS(ele,mapping); + CHECK_COORDS(ele, mapping); for (std::size_t n = 0; n < ele->getNumberOfNodes(); ++n) { @@ -243,16 +243,14 @@ TEST(MeshLib, CoordinatesMappingLocalLowerDimQuadXZ) MeshLib::ElementCoordinatesMappingLocal mapping( *ele, MeshLib::CoordinateSystem(*ele).getDimension()); auto matR(mapping.getRotationMatrixToGlobal()); - //debugOutput(ele, mapping); + // debugOutput(ele, mapping); // results when using GeoLib::ComputeRotationMatrixToXY() - double exp_R[3*3] = { 1, 0, 0, - 0, 0, -1, - 0, 1, 0}; + double exp_R[3 * 3] = {1, 0, 0, 0, 0, -1, 0, 1, 0}; const double eps(std::numeric_limits<double>::epsilon()); ASSERT_ARRAY_NEAR(exp_R, matR.data(), matR.size(), eps); - CHECK_COORDS(ele,mapping); + CHECK_COORDS(ele, mapping); for (std::size_t n = 0; n < ele->getNumberOfNodes(); ++n) { @@ -266,16 +264,14 @@ TEST(MeshLib, CoordinatesMappingLocalLowerDimQuadYZ) MeshLib::ElementCoordinatesMappingLocal mapping( *ele, MeshLib::CoordinateSystem(*ele).getDimension()); auto matR(mapping.getRotationMatrixToGlobal()); - //debugOutput(ele, mapping); + // debugOutput(ele, mapping); // results when using GeoLib::ComputeRotationMatrixToXY() - double exp_R[3*3] = { 0, 0, 1, - 0, 1, 0, - -1, 0, 0}; + double exp_R[3 * 3] = {0, 0, 1, 0, 1, 0, -1, 0, 0}; const double eps(std::numeric_limits<double>::epsilon()); ASSERT_ARRAY_NEAR(exp_R, matR.data(), matR.size(), eps); - CHECK_COORDS(ele,mapping); + CHECK_COORDS(ele, mapping); for (std::size_t n = 0; n < ele->getNumberOfNodes(); ++n) { @@ -289,20 +285,25 @@ TEST(MeshLib, CoordinatesMappingLocalLowerDimQuadXYZ) MeshLib::ElementCoordinatesMappingLocal mapping( *ele, MeshLib::CoordinateSystem(*ele).getDimension()); auto matR(mapping.getRotationMatrixToGlobal()); - //debugOutput(ele, mapping); + // debugOutput(ele, mapping); // results when using GeoLib::ComputeRotationMatrixToXY() - double exp_R[3*3] = { 1, 0, 0, - 0, 0.70710678118654757, -0.70710678118654757, - 0, 0.70710678118654757, 0.70710678118654757}; + double exp_R[3 * 3] = {1, + 0, + 0, + 0, + 0.70710678118654757, + -0.70710678118654757, + 0, + 0.70710678118654757, + 0.70710678118654757}; const double eps(std::numeric_limits<double>::epsilon()); ASSERT_ARRAY_NEAR(exp_R, matR.data(), matR.size(), eps); - CHECK_COORDS(ele,mapping); + CHECK_COORDS(ele, mapping); for (std::size_t n = 0; n < ele->getNumberOfNodes(); ++n) { delete ele->getNode(n); } } - diff --git a/Tests/MeshLib/TestDuplicate.cpp b/Tests/MeshLib/TestDuplicate.cpp index 8f697a67960328b7bf3de33df045afc05d4717da..16539557bdb0fee31b0dfe5a6e17cd658e5fb3c7 100644 --- a/Tests/MeshLib/TestDuplicate.cpp +++ b/Tests/MeshLib/TestDuplicate.cpp @@ -11,9 +11,9 @@ * http://www.opengeosys.org/project/license */ -#include <memory> +#include <gtest/gtest.h> -#include "gtest/gtest.h" +#include <memory> #include "MathLib/MathTools.h" #include "MeshLib/Elements/Element.h" @@ -29,23 +29,32 @@ TEST(MeshLib, Duplicate) auto mesh = std::unique_ptr<MeshLib::Mesh>{ MeshLib::MeshGenerator::generateRegularQuadMesh(10, 5, 1)}; - std::vector<MeshLib::Node*> new_nodes (MeshLib::copyNodeVector(mesh->getNodes())); - std::vector<MeshLib::Element*> new_elements (MeshLib::copyElementVector(mesh->getElements(), new_nodes)); + std::vector<MeshLib::Node*> new_nodes( + MeshLib::copyNodeVector(mesh->getNodes())); + std::vector<MeshLib::Element*> new_elements( + MeshLib::copyElementVector(mesh->getElements(), new_nodes)); - MeshLib::Mesh new_mesh ("new", new_nodes, new_elements); + MeshLib::Mesh new_mesh("new", new_nodes, new_elements); - ASSERT_EQ (mesh->getNumberOfElements(), new_mesh.getNumberOfElements()); - ASSERT_EQ (mesh->getNumberOfNodes(), new_mesh.getNumberOfNodes()); + ASSERT_EQ(mesh->getNumberOfElements(), new_mesh.getNumberOfElements()); + ASSERT_EQ(mesh->getNumberOfNodes(), new_mesh.getNumberOfNodes()); - std::vector<std::size_t> del_idx(1,1); - std::unique_ptr<MeshLib::Mesh> mesh2(MeshLib::removeNodes(*mesh, del_idx, "mesh2")); + std::vector<std::size_t> del_idx(1, 1); + std::unique_ptr<MeshLib::Mesh> mesh2( + MeshLib::removeNodes(*mesh, del_idx, "mesh2")); - ASSERT_EQ (mesh2->getNumberOfElements(), new_mesh.getNumberOfElements()-2); - ASSERT_EQ (mesh2->getNumberOfNodes(), new_mesh.getNumberOfNodes()-2); + ASSERT_EQ(mesh2->getNumberOfElements(), new_mesh.getNumberOfElements() - 2); + ASSERT_EQ(mesh2->getNumberOfNodes(), new_mesh.getNumberOfNodes() - 2); - ASSERT_DOUBLE_EQ (4.0, MathLib::sqrDist(*mesh2->getNode(0), *new_mesh.getNode(0))); - ASSERT_DOUBLE_EQ (0.0, MathLib::sqrDist(*mesh2->getNode(0), *new_mesh.getNode(2))); + ASSERT_DOUBLE_EQ( + 4.0, MathLib::sqrDist(*mesh2->getNode(0), *new_mesh.getNode(0))); + ASSERT_DOUBLE_EQ( + 0.0, MathLib::sqrDist(*mesh2->getNode(0), *new_mesh.getNode(2))); - ASSERT_DOUBLE_EQ (4.0, MathLib::sqrDist(*mesh2->getElement(0)->getNode(0), *new_mesh.getElement(0)->getNode(0))); - ASSERT_DOUBLE_EQ (0.0, MathLib::sqrDist(*mesh2->getElement(0)->getNode(0), *new_mesh.getElement(2)->getNode(0))); + ASSERT_DOUBLE_EQ(4.0, + MathLib::sqrDist(*mesh2->getElement(0)->getNode(0), + *new_mesh.getElement(0)->getNode(0))); + ASSERT_DOUBLE_EQ(0.0, + MathLib::sqrDist(*mesh2->getElement(0)->getNode(0), + *new_mesh.getElement(2)->getNode(0))); } diff --git a/Tests/MeshLib/TestElementConstants.cpp b/Tests/MeshLib/TestElementConstants.cpp index 9ab0bdd6e4ec952231c3a77518416bce8d96dcbd..b35cb957e7e72045cc2598eccde2603b63d56a28 100644 --- a/Tests/MeshLib/TestElementConstants.cpp +++ b/Tests/MeshLib/TestElementConstants.cpp @@ -7,10 +7,10 @@ * http://www.opengeosys.org/project/license */ -#include "gtest/gtest.h" +#include <gtest/gtest.h> -#include "MeshLib/Elements/Quad.h" #include "MeshLib/Elements/Hex.h" +#include "MeshLib/Elements/Quad.h" #include "MeshLib/Elements/Tet.h" using namespace MeshLib; @@ -126,9 +126,9 @@ TEST(MeshLib, ElementConstantsHex8) TEST(MeshLib, ElementConstantsHex20) { - ASSERT_EQ( 3u, Hex20::dimension); + ASSERT_EQ(3u, Hex20::dimension); ASSERT_EQ(20u, Hex20::n_all_nodes); - ASSERT_EQ( 8u, Hex20::n_base_nodes); + ASSERT_EQ(8u, Hex20::n_base_nodes); std::array<Node*, 20> nodes{}; nodes[0] = new Node(0.0, 0.0, 0.0); @@ -153,9 +153,9 @@ TEST(MeshLib, ElementConstantsHex20) nodes[19] = new Node(0.0, 1.0, 0.5); Hex20 ele(nodes); - ASSERT_EQ( 3u, ele.getDimension()); + ASSERT_EQ(3u, ele.getDimension()); ASSERT_EQ(20u, ele.getNumberOfNodes()); - ASSERT_EQ( 8u, ele.getNumberOfBaseNodes()); + ASSERT_EQ(8u, ele.getNumberOfBaseNodes()); for (auto n : nodes) { @@ -188,9 +188,9 @@ TEST(MeshLib, ElementConstantsTet4) TEST(MeshLib, ElementConstantsTet10) { - ASSERT_EQ( 3u, Tet10::dimension); + ASSERT_EQ(3u, Tet10::dimension); ASSERT_EQ(10u, Tet10::n_all_nodes); - ASSERT_EQ( 4u, Tet10::n_base_nodes); + ASSERT_EQ(4u, Tet10::n_base_nodes); std::array<Node*, 10> nodes{}; nodes[0] = new Node(0.0, 0.0, 0.0); @@ -206,13 +206,12 @@ TEST(MeshLib, ElementConstantsTet10) nodes[9] = new Node(0.0, 0.5, 0.5); Tet10 ele(nodes); - ASSERT_EQ( 3u, ele.getDimension()); + ASSERT_EQ(3u, ele.getDimension()); ASSERT_EQ(10u, ele.getNumberOfNodes()); - ASSERT_EQ( 4u, ele.getNumberOfBaseNodes()); + ASSERT_EQ(4u, ele.getNumberOfBaseNodes()); for (auto n : nodes) { delete n; } } - diff --git a/Tests/MeshLib/TestElementStatus.cpp b/Tests/MeshLib/TestElementStatus.cpp index 6e98f83a82674b740e9c9521bdd1bf2708361910..7cca831e311a9dacb5685046985cc45aafd50b36 100644 --- a/Tests/MeshLib/TestElementStatus.cpp +++ b/Tests/MeshLib/TestElementStatus.cpp @@ -11,23 +11,23 @@ * http://www.opengeosys.org/project/license */ -#include <memory> +#include <gtest/gtest.h> -#include "gtest/gtest.h" +#include <memory> -#include "MeshLib/Mesh.h" -#include "MeshLib/Node.h" -#include "MeshLib/Elements/Element.h" #include "MeshLib/ElementStatus.h" +#include "MeshLib/Elements/Element.h" +#include "MeshLib/Mesh.h" #include "MeshLib/MeshGenerators/MeshGenerator.h" - +#include "MeshLib/Node.h" TEST(MeshLib, ElementStatus) { - const unsigned width (100); - const unsigned elements_per_side (20); + const unsigned width(100); + const unsigned elements_per_side(20); auto const mesh = std::unique_ptr<MeshLib::Mesh>{ - MeshLib::MeshGenerator::generateRegularQuadMesh(width, elements_per_side)}; + MeshLib::MeshGenerator::generateRegularQuadMesh(width, + elements_per_side)}; auto* const material_id_properties = mesh->getProperties().createNewPropertyVector<int>( @@ -35,9 +35,9 @@ TEST(MeshLib, ElementStatus) ASSERT_NE(nullptr, material_id_properties); material_id_properties->resize(mesh->getNumberOfElements()); - const std::vector<MeshLib::Element*> elements (mesh->getElements()); + const std::vector<MeshLib::Element*> elements(mesh->getElements()); - for (unsigned i=0; i<elements_per_side; ++i) + for (unsigned i = 0; i < elements_per_side; ++i) { for (unsigned j = 0; j < elements_per_side; ++j) { @@ -49,29 +49,31 @@ TEST(MeshLib, ElementStatus) { // all elements and nodes active MeshLib::ElementStatus status(mesh.get()); - ASSERT_EQ (elements.size(), status.getNumberOfActiveElements()); - ASSERT_EQ (mesh->getNumberOfNodes(), status.getNumberOfActiveNodes()); + ASSERT_EQ(elements.size(), status.getNumberOfActiveElements()); + ASSERT_EQ(mesh->getNumberOfNodes(), status.getNumberOfActiveNodes()); } { // set material 1 to false std::vector<int> inactiveMat{1}; MeshLib::ElementStatus status(mesh.get(), inactiveMat); - ASSERT_EQ (elements.size()-elements_per_side, status.getNumberOfActiveElements()); + ASSERT_EQ(elements.size() - elements_per_side, + status.getNumberOfActiveElements()); } { // set material 0 and 1 to false std::vector<int> inactiveMat{0, 1}; MeshLib::ElementStatus status(mesh.get(), inactiveMat); - ASSERT_EQ (elements.size()-(2*elements_per_side), status.getNumberOfActiveElements()); + ASSERT_EQ(elements.size() - (2 * elements_per_side), + status.getNumberOfActiveElements()); // active elements - auto &active_elements (status.getActiveElements()); - ASSERT_EQ (active_elements.size(), status.getNumberOfActiveElements()); + auto& active_elements(status.getActiveElements()); + ASSERT_EQ(active_elements.size(), status.getNumberOfActiveElements()); // active nodes - auto& active_nodes (status.getActiveNodes()); - ASSERT_EQ (active_nodes.size(), status.getNumberOfActiveNodes()); + auto& active_nodes(status.getActiveNodes()); + ASSERT_EQ(active_nodes.size(), status.getNumberOfActiveNodes()); } } diff --git a/Tests/MeshLib/TestFindElementsWithinRadius.cpp b/Tests/MeshLib/TestFindElementsWithinRadius.cpp index 9163a6ec7cbb8b65d282723107b58d49a2464f9a..25accad7efaaf22593fbd43eb7a4eb38b42222b7 100644 --- a/Tests/MeshLib/TestFindElementsWithinRadius.cpp +++ b/Tests/MeshLib/TestFindElementsWithinRadius.cpp @@ -8,6 +8,7 @@ */ #include <gtest/gtest.h> + #include <autocheck/autocheck.hpp> #include <memory> @@ -17,7 +18,6 @@ #include "MeshLib/MeshGenerators/MeshGenerator.h" #include "MeshLib/Node.h" #include "MeshLib/findElementsWithinRadius.h" - #include "Tests/AutoCheckTools.h" using namespace MeshLib; diff --git a/Tests/MeshLib/TestFlipElements.cpp b/Tests/MeshLib/TestFlipElements.cpp index 37c0166f41e099a92f79cb4e77a2b4bfab1deea1..1cc9a27b8a21464446a9edf886520bab0cb58d42 100644 --- a/Tests/MeshLib/TestFlipElements.cpp +++ b/Tests/MeshLib/TestFlipElements.cpp @@ -7,25 +7,26 @@ * http://www.opengeosys.org/project/license */ -#include <memory> +#include <gtest/gtest.h> -#include "gtest/gtest.h" +#include <memory> -#include "MeshLib/Mesh.h" -#include "MeshLib/Node.h" #include "MeshLib/Elements/Element.h" #include "MeshLib/Elements/FaceRule.h" -#include "MeshLib/MeshGenerators/MeshGenerator.h" +#include "MeshLib/Mesh.h" #include "MeshLib/MeshEditing/FlipElements.h" +#include "MeshLib/MeshGenerators/MeshGenerator.h" +#include "MeshLib/Node.h" TEST(MeshLib, FlipLineMesh) { - std::unique_ptr<MeshLib::Mesh> mesh (MeshLib::MeshGenerator::generateLineMesh(1.0, 5)); - std::unique_ptr<MeshLib::Mesh> result (MeshLib::createFlippedMesh(*mesh)); + std::unique_ptr<MeshLib::Mesh> mesh( + MeshLib::MeshGenerator::generateLineMesh(1.0, 5)); + std::unique_ptr<MeshLib::Mesh> result(MeshLib::createFlippedMesh(*mesh)); ASSERT_EQ(mesh->getNumberOfNodes(), result->getNumberOfNodes()); ASSERT_EQ(mesh->getNumberOfElements(), result->getNumberOfElements()); - for (std::size_t i=0; i<result->getNumberOfElements(); ++i) + for (std::size_t i = 0; i < result->getNumberOfElements(); ++i) { ASSERT_EQ(mesh->getElement(i)->getNode(0)->getID(), result->getElement(i)->getNode(1)->getID()); @@ -36,12 +37,13 @@ TEST(MeshLib, FlipLineMesh) TEST(MeshLib, FlipTriMesh) { - std::unique_ptr<MeshLib::Mesh> mesh (MeshLib::MeshGenerator::generateRegularTriMesh(5, 5)); - std::unique_ptr<MeshLib::Mesh> result (MeshLib::createFlippedMesh(*mesh)); + std::unique_ptr<MeshLib::Mesh> mesh( + MeshLib::MeshGenerator::generateRegularTriMesh(5, 5)); + std::unique_ptr<MeshLib::Mesh> result(MeshLib::createFlippedMesh(*mesh)); ASSERT_EQ(mesh->getNumberOfNodes(), result->getNumberOfNodes()); ASSERT_EQ(mesh->getNumberOfElements(), result->getNumberOfElements()); - for (std::size_t i=0; i<result->getNumberOfElements(); ++i) + for (std::size_t i = 0; i < result->getNumberOfElements(); ++i) { ASSERT_EQ(mesh->getElement(i)->getNode(0)->getID(), result->getElement(i)->getNode(1)->getID()); @@ -49,18 +51,20 @@ TEST(MeshLib, FlipTriMesh) result->getElement(i)->getNode(0)->getID()); ASSERT_EQ(mesh->getElement(i)->getNode(2)->getID(), result->getElement(i)->getNode(2)->getID()); - ASSERT_EQ(1.0, MeshLib::FaceRule::getSurfaceNormal(result->getElement(i))[2]); + ASSERT_EQ( + 1.0, MeshLib::FaceRule::getSurfaceNormal(result->getElement(i))[2]); } } TEST(MeshLib, FlipQuadMesh) { - std::unique_ptr<MeshLib::Mesh> mesh(MeshLib::MeshGenerator::generateRegularQuadMesh(5, 5)); - std::unique_ptr<MeshLib::Mesh> result (MeshLib::createFlippedMesh(*mesh)); + std::unique_ptr<MeshLib::Mesh> mesh( + MeshLib::MeshGenerator::generateRegularQuadMesh(5, 5)); + std::unique_ptr<MeshLib::Mesh> result(MeshLib::createFlippedMesh(*mesh)); ASSERT_EQ(mesh->getNumberOfNodes(), result->getNumberOfNodes()); ASSERT_EQ(mesh->getNumberOfElements(), result->getNumberOfElements()); - for (std::size_t i=0; i<result->getNumberOfElements(); ++i) + for (std::size_t i = 0; i < result->getNumberOfElements(); ++i) { ASSERT_EQ(mesh->getElement(i)->getNode(0)->getID(), result->getElement(i)->getNode(1)->getID()); @@ -70,14 +74,16 @@ TEST(MeshLib, FlipQuadMesh) result->getElement(i)->getNode(3)->getID()); ASSERT_EQ(mesh->getElement(i)->getNode(3)->getID(), result->getElement(i)->getNode(2)->getID()); - ASSERT_EQ(1.0, MeshLib::FaceRule::getSurfaceNormal(result->getElement(i))[2]); + ASSERT_EQ( + 1.0, MeshLib::FaceRule::getSurfaceNormal(result->getElement(i))[2]); } } TEST(MeshLib, FlipHexMesh) { - std::unique_ptr<MeshLib::Mesh> mesh (MeshLib::MeshGenerator::generateRegularHexMesh(2, 2)); - std::unique_ptr<MeshLib::Mesh> result (MeshLib::createFlippedMesh(*mesh)); + std::unique_ptr<MeshLib::Mesh> mesh( + MeshLib::MeshGenerator::generateRegularHexMesh(2, 2)); + std::unique_ptr<MeshLib::Mesh> result(MeshLib::createFlippedMesh(*mesh)); ASSERT_EQ(nullptr, result); std::vector<MeshLib::Node*> nodes; @@ -85,7 +91,8 @@ TEST(MeshLib, FlipHexMesh) { nodes.push_back(new MeshLib::Node(*mesh->getNode(i))); } - std::unique_ptr<MeshLib::Element> elem (MeshLib::createFlippedElement(*mesh->getElement(0), nodes)); + std::unique_ptr<MeshLib::Element> elem( + MeshLib::createFlippedElement(*mesh->getElement(0), nodes)); ASSERT_EQ(nullptr, elem); for (MeshLib::Node* n : nodes) { @@ -95,9 +102,10 @@ TEST(MeshLib, FlipHexMesh) TEST(MeshLib, DoubleFlipQuadMesh) { - std::unique_ptr<MeshLib::Mesh> mesh(MeshLib::MeshGenerator::generateRegularQuadMesh(5, 5)); - std::unique_ptr<MeshLib::Mesh> result (MeshLib::createFlippedMesh(*mesh)); - std::unique_ptr<MeshLib::Mesh> result2 (MeshLib::createFlippedMesh(*result)); + std::unique_ptr<MeshLib::Mesh> mesh( + MeshLib::MeshGenerator::generateRegularQuadMesh(5, 5)); + std::unique_ptr<MeshLib::Mesh> result(MeshLib::createFlippedMesh(*mesh)); + std::unique_ptr<MeshLib::Mesh> result2(MeshLib::createFlippedMesh(*result)); ASSERT_EQ(mesh->getNumberOfNodes(), result2->getNumberOfNodes()); ASSERT_EQ(mesh->getNumberOfElements(), result2->getNumberOfElements()); @@ -110,4 +118,3 @@ TEST(MeshLib, DoubleFlipQuadMesh) } } } - diff --git a/Tests/MeshLib/TestHexQualityCriteria.cpp b/Tests/MeshLib/TestHexQualityCriteria.cpp index dcbbc69c10a0707b4c2330e4ac6b362e805a7547..fd0e9c6a899ddc7a364030fbdf5f29b97c7201c2 100644 --- a/Tests/MeshLib/TestHexQualityCriteria.cpp +++ b/Tests/MeshLib/TestHexQualityCriteria.cpp @@ -7,17 +7,17 @@ * http://www.opengeosys.org/project/license */ +#include <gtest/gtest.h> + #include <memory> #include <numeric> #include <random> -#include "gtest/gtest.h" - -#include "MeshLib/Mesh.h" -#include "MeshLib/Node.h" #include "MeshLib/Elements/Element.h" +#include "MeshLib/Mesh.h" #include "MeshLib/MeshGenerators/MeshGenerator.h" #include "MeshLib/MeshQuality/ElementQualityInterface.h" +#include "MeshLib/Node.h" class HexElementQuality : public ::testing::Test { @@ -106,6 +106,6 @@ TEST_F(HexElementQuality, EquiAngleSkew) for (auto const element_quality : element_quality_vector) { ASSERT_NEAR(expected_value, element_quality, - 2*std::numeric_limits<double>::epsilon()); + 2 * std::numeric_limits<double>::epsilon()); } } diff --git a/Tests/MeshLib/TestLineMesh.cpp b/Tests/MeshLib/TestLineMesh.cpp index acf8233fccb4fafd80b0c6ad61e564882cee3a48..a9f43ddcb038150e2448e5bf47caa7531f5e5570 100644 --- a/Tests/MeshLib/TestLineMesh.cpp +++ b/Tests/MeshLib/TestLineMesh.cpp @@ -7,16 +7,17 @@ * http://www.opengeosys.org/project/license */ +#include <gtest/gtest.h> + #include <ctime> -#include "gtest/gtest.h" -#include "MeshLib/MeshGenerators/MeshGenerator.h" -#include "MeshLib/Mesh.h" #include "MeshLib/Elements/Line.h" +#include "MeshLib/Mesh.h" +#include "MeshLib/MeshGenerators/MeshGenerator.h" class MeshLibLineMesh : public ::testing::Test { - public: +public: MeshLibLineMesh() { mesh = MeshLib::MeshGenerator::generateLineMesh(extent, mesh_size); @@ -37,7 +38,7 @@ TEST_F(MeshLibLineMesh, Construction) ASSERT_EQ(mesh_size, mesh->getNumberOfElements()); // There are mesh_size+1 nodes in the mesh. - ASSERT_EQ(mesh_size+1, mesh->getNumberOfNodes()); + ASSERT_EQ(mesh_size + 1, mesh->getNumberOfNodes()); // All elements have maximum two neighbors. std::vector<MeshLib::Element*> const& elements = mesh->getElements(); @@ -46,24 +47,25 @@ TEST_F(MeshLibLineMesh, Construction) ASSERT_EQ(2u, e->getNumberOfNeighbors()); } - ASSERT_NEAR(extent/mesh_size, mesh->getMinEdgeLength(),std::numeric_limits<double>::epsilon()); - ASSERT_NEAR(extent/mesh_size, mesh->getMaxEdgeLength(),std::numeric_limits<double>::epsilon()); + ASSERT_NEAR(extent / mesh_size, mesh->getMinEdgeLength(), + std::numeric_limits<double>::epsilon()); + ASSERT_NEAR(extent / mesh_size, mesh->getMaxEdgeLength(), + std::numeric_limits<double>::epsilon()); } TEST_F(MeshLibLineMesh, ElementNeigbors) { - auto count_neighbors = [](MeshLib::Element const* const e) + auto count_neighbors = [](MeshLib::Element const* const e) { + unsigned count = 0; + for (int i = 0; i < 2; i++) { - unsigned count = 0; - for (int i = 0; i < 2; i++) + if (e->getNeighbor(i) != nullptr) { - if (e->getNeighbor(i) != nullptr) - { - count++; - } + count++; } - return count; - }; + } + return count; + }; std::vector<MeshLib::Element*> const& elements = mesh->getElements(); @@ -72,13 +74,13 @@ TEST_F(MeshLibLineMesh, ElementNeigbors) ASSERT_EQ(1u, count_neighbors(elements.front())); ASSERT_EQ(1u, count_neighbors(elements.back())); ASSERT_TRUE(areNeighbors(elements.front(), elements[1])); - ASSERT_TRUE(areNeighbors(elements.back(), elements[elements.size()-2])); + ASSERT_TRUE(areNeighbors(elements.back(), elements[elements.size() - 2])); for (std::size_t i = 1; i < elements.size() - 1; ++i) { ASSERT_EQ(2u, count_neighbors(elements[i])); - ASSERT_TRUE(areNeighbors(elements[i], elements[i-1])); - ASSERT_TRUE(areNeighbors(elements[i], elements[i+1])); + ASSERT_TRUE(areNeighbors(elements[i], elements[i - 1])); + ASSERT_TRUE(areNeighbors(elements[i], elements[i + 1])); } } @@ -91,7 +93,7 @@ TEST_F(MeshLibLineMesh, ElementToNodeConnectivity) // An element consists of two nodes n and n+1 ASSERT_EQ(2u, elements[i]->getNumberOfBaseNodes()); ASSERT_EQ(i, elements[i]->getNode(0)->getID()); - ASSERT_EQ(i+1, elements[i]->getNode(1)->getID()); + ASSERT_EQ(i + 1, elements[i]->getNode(1)->getID()); } } @@ -111,7 +113,7 @@ TEST_F(MeshLibLineMesh, NodeToElementConnectivity) for (std::size_t i = 1; i < nodes.size() - 1; ++i) { ASSERT_EQ(2u, nodes[i]->getNumberOfElements()); - ASSERT_EQ(elements[i-1], nodes[i]->getElement(0)); + ASSERT_EQ(elements[i - 1], nodes[i]->getElement(0)); ASSERT_EQ(elements[i], nodes[i]->getElement(1)); } } diff --git a/Tests/MeshLib/TestMeshGenerator.cpp b/Tests/MeshLib/TestMeshGenerator.cpp index e8cc8477e1af3bfc7b6dd9748936a733ef11b69f..778bb7cf67d83a1b62843b9617b8a78ac6559d03 100644 --- a/Tests/MeshLib/TestMeshGenerator.cpp +++ b/Tests/MeshLib/TestMeshGenerator.cpp @@ -7,6 +7,8 @@ * http://www.opengeosys.org/project/license */ +#include <gtest/gtest.h> + #include <cmath> #include <memory> #include <numeric> @@ -17,7 +19,6 @@ #include "MeshLib/Mesh.h" #include "MeshLib/MeshGenerators/MeshGenerator.h" #include "MeshLib/Node.h" -#include "gtest/gtest.h" using namespace MeshLib; @@ -26,23 +27,24 @@ TEST(MeshLib, MeshGeneratorRegularHex) const double L = 10.0; const std::size_t n_subdivisions = 9; const double dL = L / static_cast<double>(n_subdivisions); - std::unique_ptr<Mesh> msh(MeshGenerator::generateRegularHexMesh(L, n_subdivisions)); + std::unique_ptr<Mesh> msh( + MeshGenerator::generateRegularHexMesh(L, n_subdivisions)); ASSERT_EQ(std::pow(n_subdivisions, 3), msh->getNumberOfElements()); - ASSERT_EQ(std::pow(n_subdivisions+1, 3), msh->getNumberOfNodes()); + ASSERT_EQ(std::pow(n_subdivisions + 1, 3), msh->getNumberOfNodes()); // check nodes const Node& node0 = *msh->getNode(0); const Node& node1 = *msh->getNode(1); - const Node& node_n = *msh->getNode(msh->getNumberOfNodes()-2); - const Node& node_n1 = *msh->getNode(msh->getNumberOfNodes()-1); + const Node& node_n = *msh->getNode(msh->getNumberOfNodes() - 2); + const Node& node_n1 = *msh->getNode(msh->getNumberOfNodes() - 1); ASSERT_DOUBLE_EQ(.0, node0[0]); ASSERT_DOUBLE_EQ(.0, node0[1]); ASSERT_DOUBLE_EQ(.0, node0[2]); ASSERT_DOUBLE_EQ(dL, node1[0]); ASSERT_DOUBLE_EQ(.0, node1[1]); ASSERT_DOUBLE_EQ(.0, node1[2]); - ASSERT_DOUBLE_EQ(L-dL, node_n[0]); + ASSERT_DOUBLE_EQ(L - dL, node_n[0]); ASSERT_DOUBLE_EQ(L, node_n[1]); ASSERT_DOUBLE_EQ(L, node_n[2]); ASSERT_DOUBLE_EQ(L, node_n1[0]); @@ -51,65 +53,80 @@ TEST(MeshLib, MeshGeneratorRegularHex) // check elements const Element& ele0 = *msh->getElement(0); - const Element& ele_n = *msh->getElement(msh->getNumberOfElements()-1); - const std::size_t offset_y0 = (n_subdivisions+1); - const std::size_t offset_z0 = (n_subdivisions+1)*(n_subdivisions+1); + const Element& ele_n = *msh->getElement(msh->getNumberOfElements() - 1); + const std::size_t offset_y0 = (n_subdivisions + 1); + const std::size_t offset_z0 = (n_subdivisions + 1) * (n_subdivisions + 1); ASSERT_EQ(0u, ele0.getNodeIndex(0)); ASSERT_EQ(1u, ele0.getNodeIndex(1)); - ASSERT_EQ(offset_y0+1, ele0.getNodeIndex(2)); + ASSERT_EQ(offset_y0 + 1, ele0.getNodeIndex(2)); ASSERT_EQ(offset_y0, ele0.getNodeIndex(3)); ASSERT_EQ(offset_z0, ele0.getNodeIndex(4)); - ASSERT_EQ(offset_z0+1, ele0.getNodeIndex(5)); - ASSERT_EQ(offset_z0+offset_y0+1, ele0.getNodeIndex(6)); - ASSERT_EQ(offset_z0+offset_y0, ele0.getNodeIndex(7)); - const std::size_t offset_yn0 = (n_subdivisions+1)*(n_subdivisions-1); - const std::size_t offset_yn1 = (n_subdivisions+1)*n_subdivisions; - const std::size_t offset_zn0 = (n_subdivisions+1)*(n_subdivisions+1)*(n_subdivisions-1); - const std::size_t offset_zn1 = (n_subdivisions+1)*(n_subdivisions+1)*n_subdivisions; - ASSERT_EQ(offset_zn0+offset_yn0+n_subdivisions-1, ele_n.getNodeIndex(0)); - ASSERT_EQ(offset_zn0+offset_yn0+n_subdivisions, ele_n.getNodeIndex(1)); - ASSERT_EQ(offset_zn0+offset_yn1+n_subdivisions, ele_n.getNodeIndex(2)); - ASSERT_EQ(offset_zn0+offset_yn1+n_subdivisions-1, ele_n.getNodeIndex(3)); - ASSERT_EQ(offset_zn1+offset_yn0+n_subdivisions-1, ele_n.getNodeIndex(4)); - ASSERT_EQ(offset_zn1+offset_yn0+n_subdivisions, ele_n.getNodeIndex(5)); - ASSERT_EQ(offset_zn1+offset_yn1+n_subdivisions, ele_n.getNodeIndex(6)); - ASSERT_EQ(offset_zn1+offset_yn1+n_subdivisions-1, ele_n.getNodeIndex(7)); - - std::unique_ptr<Mesh> msh2 (MeshGenerator::generateRegularHexMesh(n_subdivisions, n_subdivisions, n_subdivisions, L/n_subdivisions)); + ASSERT_EQ(offset_z0 + 1, ele0.getNodeIndex(5)); + ASSERT_EQ(offset_z0 + offset_y0 + 1, ele0.getNodeIndex(6)); + ASSERT_EQ(offset_z0 + offset_y0, ele0.getNodeIndex(7)); + const std::size_t offset_yn0 = (n_subdivisions + 1) * (n_subdivisions - 1); + const std::size_t offset_yn1 = (n_subdivisions + 1) * n_subdivisions; + const std::size_t offset_zn0 = + (n_subdivisions + 1) * (n_subdivisions + 1) * (n_subdivisions - 1); + const std::size_t offset_zn1 = + (n_subdivisions + 1) * (n_subdivisions + 1) * n_subdivisions; + ASSERT_EQ(offset_zn0 + offset_yn0 + n_subdivisions - 1, + ele_n.getNodeIndex(0)); + ASSERT_EQ(offset_zn0 + offset_yn0 + n_subdivisions, ele_n.getNodeIndex(1)); + ASSERT_EQ(offset_zn0 + offset_yn1 + n_subdivisions, ele_n.getNodeIndex(2)); + ASSERT_EQ(offset_zn0 + offset_yn1 + n_subdivisions - 1, + ele_n.getNodeIndex(3)); + ASSERT_EQ(offset_zn1 + offset_yn0 + n_subdivisions - 1, + ele_n.getNodeIndex(4)); + ASSERT_EQ(offset_zn1 + offset_yn0 + n_subdivisions, ele_n.getNodeIndex(5)); + ASSERT_EQ(offset_zn1 + offset_yn1 + n_subdivisions, ele_n.getNodeIndex(6)); + ASSERT_EQ(offset_zn1 + offset_yn1 + n_subdivisions - 1, + ele_n.getNodeIndex(7)); + + std::unique_ptr<Mesh> msh2(MeshGenerator::generateRegularHexMesh( + n_subdivisions, n_subdivisions, n_subdivisions, L / n_subdivisions)); ASSERT_EQ(msh->getNumberOfNodes(), msh2->getNumberOfNodes()); - ASSERT_DOUBLE_EQ(0, MathLib::sqrDist(*(msh->getNode(msh->getNumberOfNodes()-1)), *(msh2->getNode(msh->getNumberOfNodes()-1)))); - - unsigned n_x (10); - unsigned n_y (5); - unsigned n_z (2); - double delta (1.2); - std::unique_ptr<Mesh> hex_mesh (MeshGenerator::generateRegularHexMesh(n_x, n_y, n_z, delta)); + ASSERT_DOUBLE_EQ( + 0, MathLib::sqrDist(*(msh->getNode(msh->getNumberOfNodes() - 1)), + *(msh2->getNode(msh->getNumberOfNodes() - 1)))); + + unsigned n_x(10); + unsigned n_y(5); + unsigned n_z(2); + double delta(1.2); + std::unique_ptr<Mesh> hex_mesh( + MeshGenerator::generateRegularHexMesh(n_x, n_y, n_z, delta)); ASSERT_EQ(n_x * n_y * n_z, hex_mesh->getNumberOfElements()); - ASSERT_EQ((n_x+1) * (n_y+1) * (n_z+1), hex_mesh->getNumberOfNodes()); - const MeshLib::Node* node (hex_mesh->getNode(hex_mesh->getNumberOfNodes()-1)); - ASSERT_DOUBLE_EQ(n_x*delta, (*node)[0]); - ASSERT_DOUBLE_EQ(n_y*delta, (*node)[1]); - ASSERT_DOUBLE_EQ(n_z*delta, (*node)[2]); + ASSERT_EQ((n_x + 1) * (n_y + 1) * (n_z + 1), hex_mesh->getNumberOfNodes()); + const MeshLib::Node* node( + hex_mesh->getNode(hex_mesh->getNumberOfNodes() - 1)); + ASSERT_DOUBLE_EQ(n_x * delta, (*node)[0]); + ASSERT_DOUBLE_EQ(n_y * delta, (*node)[1]); + ASSERT_DOUBLE_EQ(n_z * delta, (*node)[2]); } TEST(MeshLib, MeshGeneratorRegularQuad) { - unsigned n_x (10); - unsigned n_y (5); - double delta (1.2); - std::unique_ptr<Mesh> quad_mesh (MeshGenerator::generateRegularQuadMesh(n_x, n_y,delta)); + unsigned n_x(10); + unsigned n_y(5); + double delta(1.2); + std::unique_ptr<Mesh> quad_mesh( + MeshGenerator::generateRegularQuadMesh(n_x, n_y, delta)); ASSERT_EQ(n_x * n_y, quad_mesh->getNumberOfElements()); - ASSERT_EQ((n_x+1) * (n_y+1), quad_mesh->getNumberOfNodes()); - const MeshLib::Node* node (quad_mesh->getNode(quad_mesh->getNumberOfNodes()-1)); - ASSERT_DOUBLE_EQ(n_x*delta, (*node)[0]); - ASSERT_DOUBLE_EQ(n_y*delta, (*node)[1]); + ASSERT_EQ((n_x + 1) * (n_y + 1), quad_mesh->getNumberOfNodes()); + const MeshLib::Node* node( + quad_mesh->getNode(quad_mesh->getNumberOfNodes() - 1)); + ASSERT_DOUBLE_EQ(n_x * delta, (*node)[0]); + ASSERT_DOUBLE_EQ(n_y * delta, (*node)[1]); ASSERT_DOUBLE_EQ(0, (*node)[2]); const double L = 10.0; const std::size_t n_subdivisions = 9; - std::unique_ptr<Mesh> quad_mesh2(MeshGenerator::generateRegularQuadMesh(L, n_subdivisions)); - ASSERT_EQ(n_subdivisions * n_subdivisions, quad_mesh2->getNumberOfElements()); - node = quad_mesh2->getNode(quad_mesh2->getNumberOfNodes()-1); + std::unique_ptr<Mesh> quad_mesh2( + MeshGenerator::generateRegularQuadMesh(L, n_subdivisions)); + ASSERT_EQ(n_subdivisions * n_subdivisions, + quad_mesh2->getNumberOfElements()); + node = quad_mesh2->getNode(quad_mesh2->getNumberOfNodes() - 1); ASSERT_DOUBLE_EQ(L, (*node)[0]); ASSERT_DOUBLE_EQ(L, (*node)[1]); } @@ -119,24 +136,25 @@ TEST(MeshLib, MeshGeneratorRegularPrism) double const l_x(10); double const l_y(10); double const l_z(8); - unsigned n_x (10); - unsigned n_y (5); - unsigned n_z (4); - std::unique_ptr<Mesh> mesh (MeshGenerator::generateRegularPrismMesh(l_x, l_y, l_z, n_x, n_y, n_z)); + unsigned n_x(10); + unsigned n_y(5); + unsigned n_z(4); + std::unique_ptr<Mesh> mesh( + MeshGenerator::generateRegularPrismMesh(l_x, l_y, l_z, n_x, n_y, n_z)); ASSERT_EQ(2 * n_x * n_y * n_z, mesh->getNumberOfElements()); - ASSERT_EQ((n_x+1) * (n_y+1) * (n_z+1), mesh->getNumberOfNodes()); + ASSERT_EQ((n_x + 1) * (n_y + 1) * (n_z + 1), mesh->getNumberOfNodes()); - std::size_t count (0); + std::size_t count(0); for (std::size_t k = 0; k < (n_z + 1); ++k) { for (std::size_t j = 0; j < (n_y + 1); ++j) { - for (std::size_t i=0; i<(n_x+1); ++i) + for (std::size_t i = 0; i < (n_x + 1); ++i) { - const MeshLib::Node* node (mesh->getNode(count++)); - ASSERT_DOUBLE_EQ(static_cast<double>(i), (*node)[0]); - ASSERT_DOUBLE_EQ(static_cast<double>(j*2), (*node)[1]); - ASSERT_DOUBLE_EQ(static_cast<double>(k*2), (*node)[2]); + const MeshLib::Node* node(mesh->getNode(count++)); + ASSERT_DOUBLE_EQ(static_cast<double>(i), (*node)[0]); + ASSERT_DOUBLE_EQ(static_cast<double>(j * 2), (*node)[1]); + ASSERT_DOUBLE_EQ(static_cast<double>(k * 2), (*node)[2]); } } } @@ -149,7 +167,7 @@ TEST(MeshLib, MeshGeneratorRegularPyramid) const double dL = L / static_cast<double>(n_subdivisions); std::vector<std::unique_ptr<BaseLib::ISubdivision>> vec_div; vec_div.reserve(3); - for (unsigned i=0; i<3; i++) + for (unsigned i = 0; i < 3; i++) { vec_div.emplace_back( new BaseLib::UniformSubdivision(L, n_subdivisions)); @@ -162,18 +180,19 @@ TEST(MeshLib, MeshGeneratorRegularPyramid) ASSERT_EQ(std::pow(n_subdivisions + 1, 3) + std::pow(n_subdivisions, 3), msh->getNumberOfNodes()); - // check the positions of the diagonal edge nodes (lower left front and upper right back) + // check the positions of the diagonal edge nodes (lower left front and + // upper right back) const Node& node0 = *msh->getNode(0); const Node& node1 = *msh->getNode(1); - const Node& node_n = *msh->getNode(L*L*L-2); - const Node& node_n1 = *msh->getNode(L*L*L-1); + const Node& node_n = *msh->getNode(L * L * L - 2); + const Node& node_n1 = *msh->getNode(L * L * L - 1); ASSERT_DOUBLE_EQ(.0, node0[0]); ASSERT_DOUBLE_EQ(.0, node0[1]); ASSERT_DOUBLE_EQ(.0, node0[2]); ASSERT_DOUBLE_EQ(dL, node1[0]); ASSERT_DOUBLE_EQ(.0, node1[1]); ASSERT_DOUBLE_EQ(.0, node1[2]); - ASSERT_DOUBLE_EQ(L-dL, node_n[0]); + ASSERT_DOUBLE_EQ(L - dL, node_n[0]); ASSERT_DOUBLE_EQ(L, node_n[1]); ASSERT_DOUBLE_EQ(L, node_n[2]); ASSERT_DOUBLE_EQ(L, node_n1[0]); @@ -187,7 +206,7 @@ TEST(MeshLib, MeshGeneratorRegularPyramid) return volume + element->computeVolume(); }); - EXPECT_NEAR(L*L*L, element_volumes, 1e-10); + EXPECT_NEAR(L * L * L, element_volumes, 1e-10); // test node order of the elements for (auto const element : msh->getElements()) diff --git a/Tests/MeshLib/TestMeshNodeSearch.cpp b/Tests/MeshLib/TestMeshNodeSearch.cpp index 16b571036ad30ca5d6ddfed67f1a66e5893fc527..c2ff9f682eae472af854a7216cd28842224d5abb 100644 --- a/Tests/MeshLib/TestMeshNodeSearch.cpp +++ b/Tests/MeshLib/TestMeshNodeSearch.cpp @@ -10,18 +10,17 @@ * http://www.opengeosys.org/project/license */ -#include "gtest/gtest.h" +#include <gtest/gtest.h> #include <memory> #include "GeoLib/Polyline.h" #include "GeoLib/Surface.h" - +#include "MeshGeoToolsLib/HeuristicSearchLength.h" +#include "MeshGeoToolsLib/MeshNodeSearcher.h" #include "MeshLib/Mesh.h" -#include "MeshLib/Node.h" #include "MeshLib/MeshGenerators/MeshGenerator.h" -#include "MeshGeoToolsLib/MeshNodeSearcher.h" -#include "MeshGeoToolsLib/HeuristicSearchLength.h" +#include "MeshLib/Node.h" using namespace MeshLib; @@ -31,7 +30,8 @@ public: MeshLibMeshNodeSearchInSimpleQuadMesh() : _quad_mesh(MeshGenerator::generateRegularQuadMesh( _geometric_size, _number_of_subdivisions_per_direction)) - {} + { + } ~MeshLibMeshNodeSearchInSimpleQuadMesh() override { delete _quad_mesh; } @@ -47,7 +47,8 @@ public: MeshLibMeshNodeSearchInSimpleHexMesh() : _hex_mesh(MeshGenerator::generateRegularHexMesh( _geometric_size, _number_of_subdivisions_per_direction)) - {} + { + } ~MeshLibMeshNodeSearchInSimpleHexMesh() override { delete _hex_mesh; } @@ -60,21 +61,22 @@ protected: TEST_F(MeshLibMeshNodeSearchInSimpleQuadMesh, PointSearchEpsHalfEdge) { double _dx = _geometric_size / _number_of_subdivisions_per_direction; - double dx_half = _dx*0.5; + double dx_half = _dx * 0.5; ASSERT_TRUE(_quad_mesh != nullptr); // 2 perform search and compare results with expected vals auto search_length = std::make_unique<MeshGeoToolsLib::SearchLength>(dx_half); - MeshGeoToolsLib::MeshNodeSearcher mesh_node_searcher(*_quad_mesh, - std::move(search_length), MeshGeoToolsLib::SearchAllNodes::Yes); + MeshGeoToolsLib::MeshNodeSearcher mesh_node_searcher( + *_quad_mesh, std::move(search_length), + MeshGeoToolsLib::SearchAllNodes::Yes); GeoLib::Point p1(0.0, 0.0, 0.0); EXPECT_EQ(1u, mesh_node_searcher.getMeshNodeIDs(p1).size()); EXPECT_EQ(0u, mesh_node_searcher.getMeshNodeIDs(p1)[0]); - GeoLib::Point p2(dx_half*0.99, 0.0, 0.0); + GeoLib::Point p2(dx_half * 0.99, 0.0, 0.0); EXPECT_EQ(1u, mesh_node_searcher.getMeshNodeIDs(p2).size()); EXPECT_EQ(0u, mesh_node_searcher.getMeshNodeIDs(p2)[0]); @@ -83,7 +85,7 @@ TEST_F(MeshLibMeshNodeSearchInSimpleQuadMesh, PointSearchEpsHalfEdge) EXPECT_EQ(0u, mesh_node_searcher.getMeshNodeIDs(p3)[0]); EXPECT_EQ(1u, mesh_node_searcher.getMeshNodeIDs(p3)[1]); - GeoLib::Point p4(dx_half*1.01, 0.0, 0.0); + GeoLib::Point p4(dx_half * 1.01, 0.0, 0.0); ASSERT_EQ(1u, mesh_node_searcher.getMeshNodeIDs(p4).size()); ASSERT_EQ(1u, mesh_node_searcher.getMeshNodeIDs(p4)[0]); } @@ -301,12 +303,14 @@ TEST_F(MeshLibMeshNodeSearchInSimpleHexMesh, SurfaceSearch) pnts.push_back(new GeoLib::Point(0.0, _geometric_size, 0.0)); pnts.push_back(new GeoLib::Point(0.0, 0.0, _geometric_size)); pnts.push_back(new GeoLib::Point(_geometric_size, 0.0, _geometric_size)); - pnts.push_back(new GeoLib::Point(_geometric_size, _geometric_size, _geometric_size)); + pnts.push_back( + new GeoLib::Point(_geometric_size, _geometric_size, _geometric_size)); pnts.push_back(new GeoLib::Point(0.0, _geometric_size, _geometric_size)); auto search_length = std::make_unique<MeshGeoToolsLib::SearchLength>(); - MeshGeoToolsLib::MeshNodeSearcher mesh_node_searcher(*_hex_mesh, - std::move(search_length), MeshGeoToolsLib::SearchAllNodes::Yes); + MeshGeoToolsLib::MeshNodeSearcher mesh_node_searcher( + *_hex_mesh, std::move(search_length), + MeshGeoToolsLib::SearchAllNodes::Yes); const std::size_t n_nodes_1d = _number_of_subdivisions_per_direction + 1; const std::size_t n_nodes_2d = n_nodes_1d * n_nodes_1d; @@ -347,8 +351,9 @@ TEST_F(MeshLibMeshNodeSearchInSimpleHexMesh, SurfaceSearch) std::vector<std::size_t> const& found_ids_sfc_f( mesh_node_searcher.getMeshNodeIDs(sfc_front)); ASSERT_EQ(n_nodes_2d, found_ids_sfc_f.size()); - std::size_t cnt=0; - for (std::size_t k(0); k<n_nodes_1d; k++) { + std::size_t cnt = 0; + for (std::size_t k(0); k < n_nodes_1d; k++) + { for (std::size_t i(0); i < n_nodes_1d; i++) { ASSERT_EQ(k * n_nodes_2d + i, found_ids_sfc_f[cnt++]); @@ -364,9 +369,10 @@ TEST_F(MeshLibMeshNodeSearchInSimpleHexMesh, SurfaceSearch) mesh_node_searcher.getMeshNodeIDs(sfc_back)); ASSERT_EQ(n_nodes_2d, found_ids_sfc_back.size()); cnt = 0; - const std::size_t y_offset = n_nodes_1d*(n_nodes_1d-1); - for (std::size_t k(0); k<n_nodes_1d; k++) { - const std::size_t z_offset = n_nodes_2d*k; + const std::size_t y_offset = n_nodes_1d * (n_nodes_1d - 1); + for (std::size_t k(0); k < n_nodes_1d; k++) + { + const std::size_t z_offset = n_nodes_2d * k; for (std::size_t i(0); i < n_nodes_1d; i++) { ASSERT_EQ(z_offset + y_offset + i, found_ids_sfc_back[cnt++]); @@ -382,8 +388,9 @@ TEST_F(MeshLibMeshNodeSearchInSimpleHexMesh, SurfaceSearch) mesh_node_searcher.getMeshNodeIDs(sfc_left)); ASSERT_EQ(n_nodes_2d, found_ids_sfc_left.size()); cnt = 0; - for (std::size_t k(0); k<n_nodes_1d; k++) { - const std::size_t z_offset = n_nodes_2d*k; + for (std::size_t k(0); k < n_nodes_1d; k++) + { + const std::size_t z_offset = n_nodes_2d * k; for (std::size_t j(0); j < n_nodes_1d; j++) { ASSERT_EQ(z_offset + j * n_nodes_1d, found_ids_sfc_left[cnt++]); @@ -399,8 +406,9 @@ TEST_F(MeshLibMeshNodeSearchInSimpleHexMesh, SurfaceSearch) mesh_node_searcher.getMeshNodeIDs(sfc_right)); ASSERT_EQ(n_nodes_2d, found_ids_sfc_right.size()); cnt = 0; - for (std::size_t k(0); k<n_nodes_1d; k++) { - const std::size_t z_offset = n_nodes_2d*k; + for (std::size_t k(0); k < n_nodes_1d; k++) + { + const std::size_t z_offset = n_nodes_2d * k; for (std::size_t j(0); j < n_nodes_1d; j++) { ASSERT_EQ(z_offset + (j + 1) * n_nodes_1d - 1, @@ -408,7 +416,6 @@ TEST_F(MeshLibMeshNodeSearchInSimpleHexMesh, SurfaceSearch) } } - - std::for_each(pnts.begin(), pnts.end(), [](GeoLib::Point* pnt) { delete pnt; }); + std::for_each(pnts.begin(), pnts.end(), + [](GeoLib::Point* pnt) { delete pnt; }); } - diff --git a/Tests/MeshLib/TestMeshRevision.cpp b/Tests/MeshLib/TestMeshRevision.cpp index b05563049b2b79312e87910c09d3cbcf89e68b18..ce803443701caf5bc6ce012b8091f40ff45e657f 100644 --- a/Tests/MeshLib/TestMeshRevision.cpp +++ b/Tests/MeshLib/TestMeshRevision.cpp @@ -11,7 +11,7 @@ * http://www.opengeosys.org/project/license */ -#include "gtest/gtest.h" +#include <gtest/gtest.h> #include "MeshLib/Elements/Element.h" #include "MeshLib/Elements/Hex.h" @@ -24,30 +24,32 @@ #include "MeshLib/MeshEditing/MeshRevision.h" #include "MeshLib/Node.h" - TEST(MeshEditing, Tri) { std::vector<MeshLib::Node*> nodes; - nodes.push_back(new MeshLib::Node(1,0,0)); - nodes.push_back(new MeshLib::Node(0,0,0)); - nodes.push_back(new MeshLib::Node(0,0,0.1)); + nodes.push_back(new MeshLib::Node(1, 0, 0)); + nodes.push_back(new MeshLib::Node(0, 0, 0)); + nodes.push_back(new MeshLib::Node(0, 0, 0.1)); - std::array<MeshLib::Node*, 3> nodes_array = {{nodes[0], nodes[1], nodes[2]}}; + std::array<MeshLib::Node*, 3> nodes_array = { + {nodes[0], nodes[1], nodes[2]}}; std::vector<MeshLib::Element*> elements; MeshLib::Element* elem(new MeshLib::Tri(nodes_array)); elements.push_back(elem); - MeshLib::Mesh mesh ("testmesh", nodes, elements); + MeshLib::Mesh mesh("testmesh", nodes, elements); MeshLib::MeshRevision rev(mesh); MeshLib::Mesh* result = rev.simplifyMesh("new_mesh", 0.2); - ASSERT_EQ(MeshLib::MeshElemType::LINE, result->getElement(0)->getGeomType()); + ASSERT_EQ(MeshLib::MeshElemType::LINE, + result->getElement(0)->getGeomType()); ASSERT_EQ(1, result->getElement(0)->getContent()); ASSERT_EQ(2u, result->getNumberOfNodes()); delete result; result = rev.simplifyMesh("new_mesh", 0.0999); - ASSERT_EQ(MeshLib::MeshElemType::TRIANGLE, result->getElement(0)->getGeomType()); + ASSERT_EQ(MeshLib::MeshElemType::TRIANGLE, + result->getElement(0)->getGeomType()); ASSERT_EQ(0.05, result->getElement(0)->getContent()); ASSERT_EQ(3u, result->getNumberOfNodes()); delete result; @@ -56,21 +58,23 @@ TEST(MeshEditing, Tri) TEST(MeshEditing, NonPlanarQuad) { std::vector<MeshLib::Node*> nodes; - nodes.push_back(new MeshLib::Node(0,0,0)); - nodes.push_back(new MeshLib::Node(0,1,0)); - nodes.push_back(new MeshLib::Node(1,1,0.1)); - nodes.push_back(new MeshLib::Node(1,0,0)); + nodes.push_back(new MeshLib::Node(0, 0, 0)); + nodes.push_back(new MeshLib::Node(0, 1, 0)); + nodes.push_back(new MeshLib::Node(1, 1, 0.1)); + nodes.push_back(new MeshLib::Node(1, 0, 0)); - std::array<MeshLib::Node*, 4> nodes_array = {{nodes[0], nodes[1], nodes[2], nodes[3]}}; + std::array<MeshLib::Node*, 4> nodes_array = { + {nodes[0], nodes[1], nodes[2], nodes[3]}}; std::vector<MeshLib::Element*> elements; - MeshLib::Element* elem (new MeshLib::Quad(nodes_array)); + MeshLib::Element* elem(new MeshLib::Quad(nodes_array)); elements.push_back(elem); MeshLib::Mesh mesh("testmesh", nodes, elements); MeshLib::MeshRevision rev(mesh); MeshLib::Mesh* result = rev.simplifyMesh("new_mesh", 0.2); ASSERT_EQ(2u, result->getNumberOfElements()); - ASSERT_EQ(MeshLib::MeshElemType::TRIANGLE, result->getElement(1)->getGeomType()); + ASSERT_EQ(MeshLib::MeshElemType::TRIANGLE, + result->getElement(1)->getGeomType()); delete result; } @@ -78,22 +82,25 @@ TEST(MeshEditing, NonPlanarQuad) TEST(MeshEditing, Quad2Line) { std::vector<MeshLib::Node*> nodes; - nodes.push_back(new MeshLib::Node(1,0,0)); - nodes.push_back(new MeshLib::Node(0,1,0)); - nodes.push_back(new MeshLib::Node(0,1,0.1)); - nodes.push_back(new MeshLib::Node(1,0,0.1)); + nodes.push_back(new MeshLib::Node(1, 0, 0)); + nodes.push_back(new MeshLib::Node(0, 1, 0)); + nodes.push_back(new MeshLib::Node(0, 1, 0.1)); + nodes.push_back(new MeshLib::Node(1, 0, 0.1)); - std::array<MeshLib::Node*, 4> nodes_array = {{nodes[0], nodes[1], nodes[2], nodes[3]}}; + std::array<MeshLib::Node*, 4> nodes_array = { + {nodes[0], nodes[1], nodes[2], nodes[3]}}; std::vector<MeshLib::Element*> elements; - MeshLib::Element* elem (new MeshLib::Quad(nodes_array)); + MeshLib::Element* elem(new MeshLib::Quad(nodes_array)); elements.push_back(elem); MeshLib::Mesh mesh("testmesh", nodes, elements); MeshLib::MeshRevision rev(mesh); MeshLib::Mesh* result = rev.simplifyMesh("new_mesh", 0.2); - ASSERT_EQ(MeshLib::MeshElemType::LINE, result->getElement(0)->getGeomType()); - ASSERT_NEAR(1.414213562373095, result->getElement(0)->getContent(), std::numeric_limits<double>::epsilon()); + ASSERT_EQ(MeshLib::MeshElemType::LINE, + result->getElement(0)->getGeomType()); + ASSERT_NEAR(1.414213562373095, result->getElement(0)->getContent(), + std::numeric_limits<double>::epsilon()); ASSERT_EQ(2u, result->getNumberOfNodes()); delete result; @@ -102,22 +109,25 @@ TEST(MeshEditing, Quad2Line) TEST(MeshEditing, Quad2Tri) { std::vector<MeshLib::Node*> nodes; - nodes.push_back(new MeshLib::Node(1,0,0)); - nodes.push_back(new MeshLib::Node(0,1,0)); - nodes.push_back(new MeshLib::Node(0,1,0.1)); - nodes.push_back(new MeshLib::Node(1,1,0.1)); + nodes.push_back(new MeshLib::Node(1, 0, 0)); + nodes.push_back(new MeshLib::Node(0, 1, 0)); + nodes.push_back(new MeshLib::Node(0, 1, 0.1)); + nodes.push_back(new MeshLib::Node(1, 1, 0.1)); - std::array<MeshLib::Node*, 4> nodes_array = {{nodes[0], nodes[1], nodes[2], nodes[3]}}; + std::array<MeshLib::Node*, 4> nodes_array = { + {nodes[0], nodes[1], nodes[2], nodes[3]}}; std::vector<MeshLib::Element*> elements; - MeshLib::Element* elem (new MeshLib::Quad(nodes_array)); + MeshLib::Element* elem(new MeshLib::Quad(nodes_array)); elements.push_back(elem); MeshLib::Mesh mesh("testmesh", nodes, elements); MeshLib::MeshRevision rev(mesh); MeshLib::Mesh* result = rev.simplifyMesh("new_mesh", 0.2); - ASSERT_EQ(MeshLib::MeshElemType::TRIANGLE, result->getElement(0)->getGeomType()); - ASSERT_NEAR(0.5049752469181039, result->getElement(0)->getContent(), std::numeric_limits<double>::epsilon()); + ASSERT_EQ(MeshLib::MeshElemType::TRIANGLE, + result->getElement(0)->getGeomType()); + ASSERT_NEAR(0.5049752469181039, result->getElement(0)->getContent(), + std::numeric_limits<double>::epsilon()); ASSERT_EQ(3u, result->getNumberOfNodes()); delete result; @@ -126,18 +136,20 @@ TEST(MeshEditing, Quad2Tri) TEST(MeshEditing, NonPlanarHex) { std::vector<MeshLib::Node*> nodes; - nodes.push_back(new MeshLib::Node(0,0,-0.5)); - nodes.push_back(new MeshLib::Node(1,0,0)); - nodes.push_back(new MeshLib::Node(1,1,0)); - nodes.push_back(new MeshLib::Node(0,1,0)); - nodes.push_back(new MeshLib::Node(0,0,1)); - nodes.push_back(new MeshLib::Node(1,0,1)); - nodes.push_back(new MeshLib::Node(1,1,1)); - nodes.push_back(new MeshLib::Node(0,1,1)); - - std::array<MeshLib::Node*, 8> nodes_array = {{nodes[0], nodes[1], nodes[2], nodes[3], nodes[4], nodes[5], nodes[6], nodes[7]}}; + nodes.push_back(new MeshLib::Node(0, 0, -0.5)); + nodes.push_back(new MeshLib::Node(1, 0, 0)); + nodes.push_back(new MeshLib::Node(1, 1, 0)); + nodes.push_back(new MeshLib::Node(0, 1, 0)); + nodes.push_back(new MeshLib::Node(0, 0, 1)); + nodes.push_back(new MeshLib::Node(1, 0, 1)); + nodes.push_back(new MeshLib::Node(1, 1, 1)); + nodes.push_back(new MeshLib::Node(0, 1, 1)); + + std::array<MeshLib::Node*, 8> nodes_array = {{nodes[0], nodes[1], nodes[2], + nodes[3], nodes[4], nodes[5], + nodes[6], nodes[7]}}; std::vector<MeshLib::Element*> elements; - MeshLib::Element* elem (new MeshLib::Hex(nodes_array)); + MeshLib::Element* elem(new MeshLib::Hex(nodes_array)); elements.push_back(elem); MeshLib::Mesh mesh("testmesh", nodes, elements); @@ -145,9 +157,12 @@ TEST(MeshEditing, NonPlanarHex) MeshLib::Mesh* result = rev.simplifyMesh("new_mesh", 0.2); ASSERT_EQ(6u, result->getNumberOfElements()); - ASSERT_EQ(MeshLib::MeshElemType::TETRAHEDRON, result->getElement(4)->getGeomType()); - ASSERT_NEAR(0.25, result->getElement(0)->getContent(), std::numeric_limits<double>::epsilon()); - ASSERT_NEAR(0.1666666666666667, result->getElement(5)->getContent(), std::numeric_limits<double>::epsilon()); + ASSERT_EQ(MeshLib::MeshElemType::TETRAHEDRON, + result->getElement(4)->getGeomType()); + ASSERT_NEAR(0.25, result->getElement(0)->getContent(), + std::numeric_limits<double>::epsilon()); + ASSERT_NEAR(0.1666666666666667, result->getElement(5)->getContent(), + std::numeric_limits<double>::epsilon()); delete result; } @@ -155,18 +170,20 @@ TEST(MeshEditing, NonPlanarHex) TEST(MeshEditing, Hex2PyramidPrism) { std::vector<MeshLib::Node*> nodes; - nodes.push_back(new MeshLib::Node(0,0,0)); - nodes.push_back(new MeshLib::Node(1,0,0)); - nodes.push_back(new MeshLib::Node(1,1,0)); - nodes.push_back(new MeshLib::Node(0,1,0)); - nodes.push_back(new MeshLib::Node(0,0,1)); - nodes.push_back(new MeshLib::Node(1,0,.1)); - nodes.push_back(new MeshLib::Node(1,1,1)); - nodes.push_back(new MeshLib::Node(0,1,1)); - - std::array<MeshLib::Node*, 8> nodes_array = {{nodes[0], nodes[1], nodes[2], nodes[3], nodes[4], nodes[5], nodes[6], nodes[7]}}; + nodes.push_back(new MeshLib::Node(0, 0, 0)); + nodes.push_back(new MeshLib::Node(1, 0, 0)); + nodes.push_back(new MeshLib::Node(1, 1, 0)); + nodes.push_back(new MeshLib::Node(0, 1, 0)); + nodes.push_back(new MeshLib::Node(0, 0, 1)); + nodes.push_back(new MeshLib::Node(1, 0, .1)); + nodes.push_back(new MeshLib::Node(1, 1, 1)); + nodes.push_back(new MeshLib::Node(0, 1, 1)); + + std::array<MeshLib::Node*, 8> nodes_array = {{nodes[0], nodes[1], nodes[2], + nodes[3], nodes[4], nodes[5], + nodes[6], nodes[7]}}; std::vector<MeshLib::Element*> elements; - MeshLib::Element* elem (new MeshLib::Hex(nodes_array)); + MeshLib::Element* elem(new MeshLib::Hex(nodes_array)); elements.push_back(elem); MeshLib::Mesh mesh("testmesh", nodes, elements); @@ -174,10 +191,14 @@ TEST(MeshEditing, Hex2PyramidPrism) MeshLib::Mesh* result = rev.simplifyMesh("new_mesh", 0.2); ASSERT_EQ(2u, result->getNumberOfElements()); - ASSERT_EQ(MeshLib::MeshElemType::PYRAMID, result->getElement(0)->getGeomType()); - ASSERT_EQ(MeshLib::MeshElemType::PRISM, result->getElement(1)->getGeomType()); - ASSERT_NEAR(0.3333333333333333, result->getElement(0)->getContent(), std::numeric_limits<double>::epsilon()); - ASSERT_NEAR(0.5, result->getElement(1)->getContent(), std::numeric_limits<double>::epsilon()); + ASSERT_EQ(MeshLib::MeshElemType::PYRAMID, + result->getElement(0)->getGeomType()); + ASSERT_EQ(MeshLib::MeshElemType::PRISM, + result->getElement(1)->getGeomType()); + ASSERT_NEAR(0.3333333333333333, result->getElement(0)->getContent(), + std::numeric_limits<double>::epsilon()); + ASSERT_NEAR(0.5, result->getElement(1)->getContent(), + std::numeric_limits<double>::epsilon()); delete result; } @@ -185,18 +206,20 @@ TEST(MeshEditing, Hex2PyramidPrism) TEST(MeshEditing, Hex2FourTets) { std::vector<MeshLib::Node*> nodes; - nodes.push_back(new MeshLib::Node(0,0,0)); - nodes.push_back(new MeshLib::Node(1,1,0)); - nodes.push_back(new MeshLib::Node(1,1,0)); - nodes.push_back(new MeshLib::Node(0,1,0)); - nodes.push_back(new MeshLib::Node(1,0,1)); - nodes.push_back(new MeshLib::Node(1,0,1)); - nodes.push_back(new MeshLib::Node(1,1,1)); - nodes.push_back(new MeshLib::Node(0,1,1)); - - std::array<MeshLib::Node*, 8> nodes_array = {{nodes[0], nodes[1], nodes[2], nodes[3], nodes[4], nodes[5], nodes[6], nodes[7]}}; + nodes.push_back(new MeshLib::Node(0, 0, 0)); + nodes.push_back(new MeshLib::Node(1, 1, 0)); + nodes.push_back(new MeshLib::Node(1, 1, 0)); + nodes.push_back(new MeshLib::Node(0, 1, 0)); + nodes.push_back(new MeshLib::Node(1, 0, 1)); + nodes.push_back(new MeshLib::Node(1, 0, 1)); + nodes.push_back(new MeshLib::Node(1, 1, 1)); + nodes.push_back(new MeshLib::Node(0, 1, 1)); + + std::array<MeshLib::Node*, 8> nodes_array = {{nodes[0], nodes[1], nodes[2], + nodes[3], nodes[4], nodes[5], + nodes[6], nodes[7]}}; std::vector<MeshLib::Element*> elements; - MeshLib::Element* elem (new MeshLib::Hex(nodes_array)); + MeshLib::Element* elem(new MeshLib::Hex(nodes_array)); elements.push_back(elem); MeshLib::Mesh mesh("testmesh", nodes, elements); @@ -204,11 +227,16 @@ TEST(MeshEditing, Hex2FourTets) MeshLib::Mesh* result = rev.simplifyMesh("new_mesh", 0.2); ASSERT_EQ(4u, result->getNumberOfElements()); - ASSERT_EQ(MeshLib::MeshElemType::TETRAHEDRON, result->getElement(1)->getGeomType()); - ASSERT_NEAR(0.1666666666666667, result->getElement(0)->getContent(), std::numeric_limits<double>::epsilon()); - ASSERT_NEAR(0.1666666666666667, result->getElement(1)->getContent(), std::numeric_limits<double>::epsilon()); - ASSERT_NEAR(0.1666666666666667, result->getElement(2)->getContent(), std::numeric_limits<double>::epsilon()); - ASSERT_NEAR(0.1666666666666667, result->getElement(3)->getContent(), std::numeric_limits<double>::epsilon()); + ASSERT_EQ(MeshLib::MeshElemType::TETRAHEDRON, + result->getElement(1)->getGeomType()); + ASSERT_NEAR(0.1666666666666667, result->getElement(0)->getContent(), + std::numeric_limits<double>::epsilon()); + ASSERT_NEAR(0.1666666666666667, result->getElement(1)->getContent(), + std::numeric_limits<double>::epsilon()); + ASSERT_NEAR(0.1666666666666667, result->getElement(2)->getContent(), + std::numeric_limits<double>::epsilon()); + ASSERT_NEAR(0.1666666666666667, result->getElement(3)->getContent(), + std::numeric_limits<double>::epsilon()); delete result; } @@ -216,18 +244,20 @@ TEST(MeshEditing, Hex2FourTets) TEST(MeshEditing, Hex2TwoTets) { std::vector<MeshLib::Node*> nodes; - nodes.push_back(new MeshLib::Node(0,0,0)); - nodes.push_back(new MeshLib::Node(1,0,0)); - nodes.push_back(new MeshLib::Node(1,1,0)); - nodes.push_back(new MeshLib::Node(0,1,0)); - nodes.push_back(new MeshLib::Node(1,1,1)); - nodes.push_back(new MeshLib::Node(1,1,1)); - nodes.push_back(new MeshLib::Node(1,1,1)); - nodes.push_back(new MeshLib::Node(1,1,1)); - - std::array<MeshLib::Node*, 8> nodes_array = {{nodes[0], nodes[1], nodes[2], nodes[3], nodes[4], nodes[5], nodes[6], nodes[7]}}; + nodes.push_back(new MeshLib::Node(0, 0, 0)); + nodes.push_back(new MeshLib::Node(1, 0, 0)); + nodes.push_back(new MeshLib::Node(1, 1, 0)); + nodes.push_back(new MeshLib::Node(0, 1, 0)); + nodes.push_back(new MeshLib::Node(1, 1, 1)); + nodes.push_back(new MeshLib::Node(1, 1, 1)); + nodes.push_back(new MeshLib::Node(1, 1, 1)); + nodes.push_back(new MeshLib::Node(1, 1, 1)); + + std::array<MeshLib::Node*, 8> nodes_array = {{nodes[0], nodes[1], nodes[2], + nodes[3], nodes[4], nodes[5], + nodes[6], nodes[7]}}; std::vector<MeshLib::Element*> elements; - MeshLib::Element* elem (new MeshLib::Hex(nodes_array)); + MeshLib::Element* elem(new MeshLib::Hex(nodes_array)); elements.push_back(elem); MeshLib::Mesh mesh("testmesh", nodes, elements); @@ -235,9 +265,12 @@ TEST(MeshEditing, Hex2TwoTets) MeshLib::Mesh* result = rev.simplifyMesh("new_mesh", 0.2); ASSERT_EQ(2u, result->getNumberOfElements()); - ASSERT_EQ(MeshLib::MeshElemType::TETRAHEDRON, result->getElement(1)->getGeomType()); - ASSERT_NEAR(0.1666666666666667, result->getElement(0)->getContent(), std::numeric_limits<double>::epsilon()); - ASSERT_NEAR(0.1666666666666667, result->getElement(1)->getContent(), std::numeric_limits<double>::epsilon()); + ASSERT_EQ(MeshLib::MeshElemType::TETRAHEDRON, + result->getElement(1)->getGeomType()); + ASSERT_NEAR(0.1666666666666667, result->getElement(0)->getContent(), + std::numeric_limits<double>::epsilon()); + ASSERT_NEAR(0.1666666666666667, result->getElement(1)->getContent(), + std::numeric_limits<double>::epsilon()); delete result; } @@ -245,15 +278,16 @@ TEST(MeshEditing, Hex2TwoTets) TEST(MeshEditing, NonPlanarPyramid) { std::vector<MeshLib::Node*> nodes; - nodes.push_back(new MeshLib::Node(0,0,0)); - nodes.push_back(new MeshLib::Node(1,0,-.5)); - nodes.push_back(new MeshLib::Node(1,1,0)); - nodes.push_back(new MeshLib::Node(0,1,0)); - nodes.push_back(new MeshLib::Node(1,0,1)); - - std::array<MeshLib::Node*, 5> nodes_array = {{nodes[0], nodes[1], nodes[2], nodes[3], nodes[4]}}; + nodes.push_back(new MeshLib::Node(0, 0, 0)); + nodes.push_back(new MeshLib::Node(1, 0, -.5)); + nodes.push_back(new MeshLib::Node(1, 1, 0)); + nodes.push_back(new MeshLib::Node(0, 1, 0)); + nodes.push_back(new MeshLib::Node(1, 0, 1)); + + std::array<MeshLib::Node*, 5> nodes_array = { + {nodes[0], nodes[1], nodes[2], nodes[3], nodes[4]}}; std::vector<MeshLib::Element*> elements; - MeshLib::Element* elem (new MeshLib::Pyramid(nodes_array)); + MeshLib::Element* elem(new MeshLib::Pyramid(nodes_array)); elements.push_back(elem); MeshLib::Mesh mesh("testmesh", nodes, elements); @@ -261,9 +295,12 @@ TEST(MeshEditing, NonPlanarPyramid) MeshLib::Mesh* result = rev.simplifyMesh("new_mesh", 0.2); ASSERT_EQ(2u, result->getNumberOfElements()); - ASSERT_EQ(MeshLib::MeshElemType::TETRAHEDRON, result->getElement(1)->getGeomType()); - ASSERT_NEAR(0.25, result->getElement(0)->getContent(), std::numeric_limits<double>::epsilon()); - ASSERT_NEAR(0.1666666666666667, result->getElement(1)->getContent(), std::numeric_limits<double>::epsilon()); + ASSERT_EQ(MeshLib::MeshElemType::TETRAHEDRON, + result->getElement(1)->getGeomType()); + ASSERT_NEAR(0.25, result->getElement(0)->getContent(), + std::numeric_limits<double>::epsilon()); + ASSERT_NEAR(0.1666666666666667, result->getElement(1)->getContent(), + std::numeric_limits<double>::epsilon()); delete result; } @@ -271,15 +308,16 @@ TEST(MeshEditing, NonPlanarPyramid) TEST(MeshEditing, Pyramid2Tet) { std::vector<MeshLib::Node*> nodes; - nodes.push_back(new MeshLib::Node(1,0,0)); - nodes.push_back(new MeshLib::Node(0,1,0)); - nodes.push_back(new MeshLib::Node(1,1,0)); - nodes.push_back(new MeshLib::Node(1,0,0)); - nodes.push_back(new MeshLib::Node(1,0,1)); - - std::array<MeshLib::Node*, 5> nodes_array = {{nodes[0], nodes[1], nodes[2], nodes[3], nodes[4]}}; + nodes.push_back(new MeshLib::Node(1, 0, 0)); + nodes.push_back(new MeshLib::Node(0, 1, 0)); + nodes.push_back(new MeshLib::Node(1, 1, 0)); + nodes.push_back(new MeshLib::Node(1, 0, 0)); + nodes.push_back(new MeshLib::Node(1, 0, 1)); + + std::array<MeshLib::Node*, 5> nodes_array = { + {nodes[0], nodes[1], nodes[2], nodes[3], nodes[4]}}; std::vector<MeshLib::Element*> elements; - MeshLib::Element* elem (new MeshLib::Pyramid(nodes_array)); + MeshLib::Element* elem(new MeshLib::Pyramid(nodes_array)); elements.push_back(elem); MeshLib::Mesh mesh("testmesh", nodes, elements); @@ -287,8 +325,10 @@ TEST(MeshEditing, Pyramid2Tet) MeshLib::Mesh* result = rev.simplifyMesh("new_mesh", 0.2); ASSERT_EQ(1u, result->getNumberOfElements()); - ASSERT_EQ(MeshLib::MeshElemType::TETRAHEDRON, result->getElement(0)->getGeomType()); - ASSERT_NEAR(0.16666666666666666, result->getElement(0)->getContent(), std::numeric_limits<double>::epsilon()); + ASSERT_EQ(MeshLib::MeshElemType::TETRAHEDRON, + result->getElement(0)->getGeomType()); + ASSERT_NEAR(0.16666666666666666, result->getElement(0)->getContent(), + std::numeric_limits<double>::epsilon()); delete result; } @@ -296,15 +336,16 @@ TEST(MeshEditing, Pyramid2Tet) TEST(MeshEditing, Pyramid2Quad) { std::vector<MeshLib::Node*> nodes; - nodes.push_back(new MeshLib::Node(1,0,0)); - nodes.push_back(new MeshLib::Node(1,1,0)); - nodes.push_back(new MeshLib::Node(0,1,0)); - nodes.push_back(new MeshLib::Node(0,0,0)); - nodes.push_back(new MeshLib::Node(1,0,0.1)); - - std::array<MeshLib::Node*, 5> nodes_array = {{nodes[0], nodes[1], nodes[2], nodes[3], nodes[4]}}; + nodes.push_back(new MeshLib::Node(1, 0, 0)); + nodes.push_back(new MeshLib::Node(1, 1, 0)); + nodes.push_back(new MeshLib::Node(0, 1, 0)); + nodes.push_back(new MeshLib::Node(0, 0, 0)); + nodes.push_back(new MeshLib::Node(1, 0, 0.1)); + + std::array<MeshLib::Node*, 5> nodes_array = { + {nodes[0], nodes[1], nodes[2], nodes[3], nodes[4]}}; std::vector<MeshLib::Element*> elements; - MeshLib::Element* elem (new MeshLib::Pyramid(nodes_array)); + MeshLib::Element* elem(new MeshLib::Pyramid(nodes_array)); elements.push_back(elem); MeshLib::Mesh mesh("testmesh", nodes, elements); @@ -312,8 +353,10 @@ TEST(MeshEditing, Pyramid2Quad) MeshLib::Mesh* result = rev.simplifyMesh("new_mesh", 0.2); ASSERT_EQ(1u, result->getNumberOfElements()); - ASSERT_EQ(MeshLib::MeshElemType::QUAD, result->getElement(0)->getGeomType()); - ASSERT_NEAR(1, result->getElement(0)->getContent(), std::numeric_limits<double>::epsilon()); + ASSERT_EQ(MeshLib::MeshElemType::QUAD, + result->getElement(0)->getGeomType()); + ASSERT_NEAR(1, result->getElement(0)->getContent(), + std::numeric_limits<double>::epsilon()); delete result; } @@ -321,15 +364,16 @@ TEST(MeshEditing, Pyramid2Quad) TEST(MeshEditing, Pyramid2Tri) { std::vector<MeshLib::Node*> nodes; - nodes.push_back(new MeshLib::Node(1,0,0)); - nodes.push_back(new MeshLib::Node(1,0.1,0)); - nodes.push_back(new MeshLib::Node(0,1,0)); - nodes.push_back(new MeshLib::Node(0,0,0)); - nodes.push_back(new MeshLib::Node(1,0,0.1)); - - std::array<MeshLib::Node*, 5> nodes_array = {{nodes[0], nodes[1], nodes[2], nodes[3], nodes[4]}}; + nodes.push_back(new MeshLib::Node(1, 0, 0)); + nodes.push_back(new MeshLib::Node(1, 0.1, 0)); + nodes.push_back(new MeshLib::Node(0, 1, 0)); + nodes.push_back(new MeshLib::Node(0, 0, 0)); + nodes.push_back(new MeshLib::Node(1, 0, 0.1)); + + std::array<MeshLib::Node*, 5> nodes_array = { + {nodes[0], nodes[1], nodes[2], nodes[3], nodes[4]}}; std::vector<MeshLib::Element*> elements; - MeshLib::Element* elem (new MeshLib::Pyramid(nodes_array)); + MeshLib::Element* elem(new MeshLib::Pyramid(nodes_array)); elements.push_back(elem); MeshLib::Mesh mesh("testmesh", nodes, elements); @@ -338,8 +382,10 @@ TEST(MeshEditing, Pyramid2Tri) ASSERT_EQ(3u, result->getNumberOfNodes()); ASSERT_EQ(1u, result->getNumberOfElements()); - ASSERT_EQ(MeshLib::MeshElemType::TRIANGLE, result->getElement(0)->getGeomType()); - ASSERT_NEAR(0.5, result->getElement(0)->getContent(), std::numeric_limits<double>::epsilon()); + ASSERT_EQ(MeshLib::MeshElemType::TRIANGLE, + result->getElement(0)->getGeomType()); + ASSERT_NEAR(0.5, result->getElement(0)->getContent(), + std::numeric_limits<double>::epsilon()); delete result; } @@ -347,16 +393,17 @@ TEST(MeshEditing, Pyramid2Tri) TEST(MeshEditing, NonPlanarPrism) { std::vector<MeshLib::Node*> nodes; - nodes.push_back(new MeshLib::Node(1,0,0)); - nodes.push_back(new MeshLib::Node(1,1,0)); - nodes.push_back(new MeshLib::Node(0,0,0)); - nodes.push_back(new MeshLib::Node(1,0,1)); - nodes.push_back(new MeshLib::Node(1,1,1)); - nodes.push_back(new MeshLib::Node(0,-0.5,2)); - - std::array<MeshLib::Node*, 6> nodes_array = {{nodes[0], nodes[1], nodes[2], nodes[3], nodes[4], nodes[5]}}; + nodes.push_back(new MeshLib::Node(1, 0, 0)); + nodes.push_back(new MeshLib::Node(1, 1, 0)); + nodes.push_back(new MeshLib::Node(0, 0, 0)); + nodes.push_back(new MeshLib::Node(1, 0, 1)); + nodes.push_back(new MeshLib::Node(1, 1, 1)); + nodes.push_back(new MeshLib::Node(0, -0.5, 2)); + + std::array<MeshLib::Node*, 6> nodes_array = { + {nodes[0], nodes[1], nodes[2], nodes[3], nodes[4], nodes[5]}}; std::vector<MeshLib::Element*> elements; - MeshLib::Element* elem (new MeshLib::Prism(nodes_array)); + MeshLib::Element* elem(new MeshLib::Prism(nodes_array)); elements.push_back(elem); MeshLib::Mesh mesh("testmesh", nodes, elements); @@ -364,8 +411,10 @@ TEST(MeshEditing, NonPlanarPrism) MeshLib::Mesh* result = rev.simplifyMesh("new_mesh", 0.2); ASSERT_EQ(3u, result->getNumberOfElements()); - ASSERT_EQ(MeshLib::MeshElemType::TETRAHEDRON, result->getElement(2)->getGeomType()); - ASSERT_NEAR(0.1666666666666667, result->getElement(0)->getContent(), std::numeric_limits<double>::epsilon()); + ASSERT_EQ(MeshLib::MeshElemType::TETRAHEDRON, + result->getElement(2)->getGeomType()); + ASSERT_NEAR(0.1666666666666667, result->getElement(0)->getContent(), + std::numeric_limits<double>::epsilon()); delete result; } @@ -373,16 +422,17 @@ TEST(MeshEditing, NonPlanarPrism) TEST(MeshEditing, Prism2TwoTets) { std::vector<MeshLib::Node*> nodes; - nodes.push_back(new MeshLib::Node(1,0,0)); - nodes.push_back(new MeshLib::Node(1,1,0)); - nodes.push_back(new MeshLib::Node(0,0,0)); - nodes.push_back(new MeshLib::Node(1,0.9,1)); - nodes.push_back(new MeshLib::Node(1,1,1)); - nodes.push_back(new MeshLib::Node(0,0,1)); - - std::array<MeshLib::Node*, 6> nodes_array = {{nodes[0], nodes[1], nodes[2], nodes[3], nodes[4], nodes[5]}}; + nodes.push_back(new MeshLib::Node(1, 0, 0)); + nodes.push_back(new MeshLib::Node(1, 1, 0)); + nodes.push_back(new MeshLib::Node(0, 0, 0)); + nodes.push_back(new MeshLib::Node(1, 0.9, 1)); + nodes.push_back(new MeshLib::Node(1, 1, 1)); + nodes.push_back(new MeshLib::Node(0, 0, 1)); + + std::array<MeshLib::Node*, 6> nodes_array = { + {nodes[0], nodes[1], nodes[2], nodes[3], nodes[4], nodes[5]}}; std::vector<MeshLib::Element*> elements; - MeshLib::Element* elem (new MeshLib::Prism(nodes_array)); + MeshLib::Element* elem(new MeshLib::Prism(nodes_array)); elements.push_back(elem); MeshLib::Mesh mesh("testmesh", nodes, elements); @@ -391,9 +441,12 @@ TEST(MeshEditing, Prism2TwoTets) ASSERT_EQ(5u, result->getNumberOfNodes()); ASSERT_EQ(2u, result->getNumberOfElements()); - ASSERT_EQ(MeshLib::MeshElemType::TETRAHEDRON, result->getElement(1)->getGeomType()); - ASSERT_NEAR(0.1666666666666667, result->getElement(0)->getContent(), std::numeric_limits<double>::epsilon()); - ASSERT_NEAR(0.15, result->getElement(1)->getContent(), std::numeric_limits<double>::epsilon()); + ASSERT_EQ(MeshLib::MeshElemType::TETRAHEDRON, + result->getElement(1)->getGeomType()); + ASSERT_NEAR(0.1666666666666667, result->getElement(0)->getContent(), + std::numeric_limits<double>::epsilon()); + ASSERT_NEAR(0.15, result->getElement(1)->getContent(), + std::numeric_limits<double>::epsilon()); delete result; } @@ -401,16 +454,17 @@ TEST(MeshEditing, Prism2TwoTets) TEST(MeshEditing, Prism2Quad) { std::vector<MeshLib::Node*> nodes; - nodes.push_back(new MeshLib::Node(1,0.9,0)); - nodes.push_back(new MeshLib::Node(1,1,0)); - nodes.push_back(new MeshLib::Node(0,0,0)); - nodes.push_back(new MeshLib::Node(1,0.9,1)); - nodes.push_back(new MeshLib::Node(1,1,1)); - nodes.push_back(new MeshLib::Node(0,0,1)); - - std::array<MeshLib::Node*, 6> nodes_array = {{nodes[0], nodes[1], nodes[2], nodes[3], nodes[4], nodes[5]}}; + nodes.push_back(new MeshLib::Node(1, 0.9, 0)); + nodes.push_back(new MeshLib::Node(1, 1, 0)); + nodes.push_back(new MeshLib::Node(0, 0, 0)); + nodes.push_back(new MeshLib::Node(1, 0.9, 1)); + nodes.push_back(new MeshLib::Node(1, 1, 1)); + nodes.push_back(new MeshLib::Node(0, 0, 1)); + + std::array<MeshLib::Node*, 6> nodes_array = { + {nodes[0], nodes[1], nodes[2], nodes[3], nodes[4], nodes[5]}}; std::vector<MeshLib::Element*> elements; - MeshLib::Element* elem (new MeshLib::Prism(nodes_array)); + MeshLib::Element* elem(new MeshLib::Prism(nodes_array)); elements.push_back(elem); MeshLib::Mesh mesh("testmesh", nodes, elements); @@ -418,8 +472,10 @@ TEST(MeshEditing, Prism2Quad) MeshLib::Mesh* result = rev.simplifyMesh("new_mesh", 0.2); ASSERT_EQ(1u, result->getNumberOfElements()); - ASSERT_EQ(MeshLib::MeshElemType::QUAD, result->getElement(0)->getGeomType()); - ASSERT_NEAR(1.345362404707371, result->getElement(0)->getContent(), std::numeric_limits<double>::epsilon()); + ASSERT_EQ(MeshLib::MeshElemType::QUAD, + result->getElement(0)->getGeomType()); + ASSERT_NEAR(1.345362404707371, result->getElement(0)->getContent(), + std::numeric_limits<double>::epsilon()); delete result; } @@ -427,16 +483,17 @@ TEST(MeshEditing, Prism2Quad) TEST(MeshEditing, Prism2Tet) { std::vector<MeshLib::Node*> nodes; - nodes.push_back(new MeshLib::Node(1,0,0)); - nodes.push_back(new MeshLib::Node(1,1,0)); - nodes.push_back(new MeshLib::Node(0.9,0,0)); - nodes.push_back(new MeshLib::Node(1,0.9,1)); - nodes.push_back(new MeshLib::Node(1,1,1)); - nodes.push_back(new MeshLib::Node(0,0,1)); - - std::array<MeshLib::Node*, 6> nodes_array = {{nodes[0], nodes[1], nodes[2], nodes[3], nodes[4], nodes[5]}}; + nodes.push_back(new MeshLib::Node(1, 0, 0)); + nodes.push_back(new MeshLib::Node(1, 1, 0)); + nodes.push_back(new MeshLib::Node(0.9, 0, 0)); + nodes.push_back(new MeshLib::Node(1, 0.9, 1)); + nodes.push_back(new MeshLib::Node(1, 1, 1)); + nodes.push_back(new MeshLib::Node(0, 0, 1)); + + std::array<MeshLib::Node*, 6> nodes_array = { + {nodes[0], nodes[1], nodes[2], nodes[3], nodes[4], nodes[5]}}; std::vector<MeshLib::Element*> elements; - MeshLib::Element* elem (new MeshLib::Prism(nodes_array)); + MeshLib::Element* elem(new MeshLib::Prism(nodes_array)); elements.push_back(elem); MeshLib::Mesh mesh("testmesh", nodes, elements); @@ -444,8 +501,10 @@ TEST(MeshEditing, Prism2Tet) MeshLib::Mesh* result = rev.simplifyMesh("new_mesh", 0.2); ASSERT_EQ(1u, result->getNumberOfElements()); - ASSERT_EQ(MeshLib::MeshElemType::TETRAHEDRON, result->getElement(0)->getGeomType()); - ASSERT_NEAR(0.1666666666666667, result->getElement(0)->getContent(), std::numeric_limits<double>::epsilon()); + ASSERT_EQ(MeshLib::MeshElemType::TETRAHEDRON, + result->getElement(0)->getGeomType()); + ASSERT_NEAR(0.1666666666666667, result->getElement(0)->getContent(), + std::numeric_limits<double>::epsilon()); delete result; } @@ -453,16 +512,17 @@ TEST(MeshEditing, Prism2Tet) TEST(MeshEditing, Prism2Tri) { std::vector<MeshLib::Node*> nodes; - nodes.push_back(new MeshLib::Node(1,0,0)); - nodes.push_back(new MeshLib::Node(1,1,0)); - nodes.push_back(new MeshLib::Node(1,1,0)); - nodes.push_back(new MeshLib::Node(1,1,1)); - nodes.push_back(new MeshLib::Node(1,1,1)); - nodes.push_back(new MeshLib::Node(0.9,0.9,1)); - - std::array<MeshLib::Node*, 6> nodes_array = {{nodes[0], nodes[1], nodes[2], nodes[3], nodes[4], nodes[5]}}; + nodes.push_back(new MeshLib::Node(1, 0, 0)); + nodes.push_back(new MeshLib::Node(1, 1, 0)); + nodes.push_back(new MeshLib::Node(1, 1, 0)); + nodes.push_back(new MeshLib::Node(1, 1, 1)); + nodes.push_back(new MeshLib::Node(1, 1, 1)); + nodes.push_back(new MeshLib::Node(0.9, 0.9, 1)); + + std::array<MeshLib::Node*, 6> nodes_array = { + {nodes[0], nodes[1], nodes[2], nodes[3], nodes[4], nodes[5]}}; std::vector<MeshLib::Element*> elements; - MeshLib::Element* elem (new MeshLib::Prism(nodes_array)); + MeshLib::Element* elem(new MeshLib::Prism(nodes_array)); elements.push_back(elem); MeshLib::Mesh mesh("testmesh", nodes, elements); @@ -470,8 +530,10 @@ TEST(MeshEditing, Prism2Tri) MeshLib::Mesh* result = rev.simplifyMesh("new_mesh", 0.2); ASSERT_EQ(1u, result->getNumberOfElements()); - ASSERT_EQ(MeshLib::MeshElemType::TRIANGLE, result->getElement(0)->getGeomType()); - ASSERT_NEAR(0.5, result->getElement(0)->getContent(), std::numeric_limits<double>::epsilon()); + ASSERT_EQ(MeshLib::MeshElemType::TRIANGLE, + result->getElement(0)->getGeomType()); + ASSERT_NEAR(0.5, result->getElement(0)->getContent(), + std::numeric_limits<double>::epsilon()); delete result; } diff --git a/Tests/MeshLib/TestMeshValidation.cpp b/Tests/MeshLib/TestMeshValidation.cpp index 0175298f7c0482c654d1691433053f7f770fd300..1d9f2e29b56c58e4cec2483ef057c44c51c06c6e 100644 --- a/Tests/MeshLib/TestMeshValidation.cpp +++ b/Tests/MeshLib/TestMeshValidation.cpp @@ -11,33 +11,33 @@ * http://www.opengeosys.org/project/license */ -#include "gtest/gtest.h" +#include <gtest/gtest.h> #include <memory> +#include "GeoLib/Raster.h" #include "MathLib/Point3d.h" - +#include "MeshLib/Elements/Element.h" #include "MeshLib/Mesh.h" -#include "MeshLib/Node.h" -#include "MeshLib/MeshQuality/MeshValidation.h" +#include "MeshLib/MeshEditing/DuplicateMeshComponents.h" #include "MeshLib/MeshGenerators/MeshGenerator.h" #include "MeshLib/MeshGenerators/RasterToMesh.h" -#include "MeshLib/MeshEditing/DuplicateMeshComponents.h" -#include "MeshLib/Elements/Element.h" - -#include "GeoLib/Raster.h" +#include "MeshLib/MeshQuality/MeshValidation.h" +#include "MeshLib/Node.h" -void -detectHoles(MeshLib::Mesh const& mesh, - std::vector<std::size_t> erase_elems, - std::size_t const expected_n_holes) +void detectHoles(MeshLib::Mesh const& mesh, + std::vector<std::size_t> + erase_elems, + std::size_t const expected_n_holes) { - std::vector<MeshLib::Node*> nodes = MeshLib::copyNodeVector(mesh.getNodes()); - std::vector<MeshLib::Element*> elems = MeshLib::copyElementVector(mesh.getElements(),nodes); + std::vector<MeshLib::Node*> nodes = + MeshLib::copyNodeVector(mesh.getNodes()); + std::vector<MeshLib::Element*> elems = + MeshLib::copyElementVector(mesh.getElements(), nodes); for (auto pos : erase_elems) { delete elems[pos]; - elems.erase(elems.begin()+pos); + elems.erase(elems.begin() + pos); } MeshLib::Mesh mesh2("mesh2", nodes, elems); ASSERT_EQ(expected_n_holes, MeshLib::MeshValidation::detectHoles(mesh2)); @@ -45,13 +45,16 @@ detectHoles(MeshLib::Mesh const& mesh, TEST(MeshValidation, DetectHolesTri) { - std::array<double, 12> pix = {{0,0.1,0.2,0.1,0,0,0.1,0,0,0,-0.1,0}}; + std::array<double, 12> pix = { + {0, 0.1, 0.2, 0.1, 0, 0, 0.1, 0, 0, 0, -0.1, 0}}; GeoLib::Raster const raster( {4, 3, 1, MathLib::Point3d(std::array<double, 3>{{0, 0, 0}}), 1, -9999}, pix.begin(), pix.end()); - std::unique_ptr<MeshLib::Mesh> mesh (MeshLib::RasterToMesh::convert( - raster, MeshLib::MeshElemType::TRIANGLE, MeshLib::UseIntensityAs::ELEVATION)); + std::unique_ptr<MeshLib::Mesh> mesh( + MeshLib::RasterToMesh::convert(raster, + MeshLib::MeshElemType::TRIANGLE, + MeshLib::UseIntensityAs::ELEVATION)); ASSERT_EQ(0, MeshLib::MeshValidation::detectHoles(*mesh)); detectHoles(*mesh, {12}, 1); @@ -70,7 +73,3 @@ TEST(MeshValidation, DetectHolesHex) detectHoles(*mesh, {28, 27}, 1); detectHoles(*mesh, {29, 27}, 1); } - - - - diff --git a/Tests/MeshLib/TestMoveMeshNodes.cpp b/Tests/MeshLib/TestMoveMeshNodes.cpp index 5b8c27d5cb5a61304a2fb383d70aab0389cb927b..df26cf0d27e6334cd348a971b7e21be1bb5d379a 100644 --- a/Tests/MeshLib/TestMoveMeshNodes.cpp +++ b/Tests/MeshLib/TestMoveMeshNodes.cpp @@ -6,13 +6,13 @@ * http://www.opengeosys.org/project/license */ +#include <gtest/gtest.h> + #include <cstdlib> #include <ctime> #include <numeric> #include <vector> -#include "gtest/gtest.h" - #include "MeshLib/MeshEditing/moveMeshNodes.h" #include "MeshLib/Node.h" @@ -21,7 +21,7 @@ TEST(MeshLib, moveMeshNodes) /* initialize random seed: */ srand(static_cast<unsigned>(time(nullptr))); - std::size_t const size (16384); + std::size_t const size(16384); std::vector<MeshLib::Node*> nodes; std::vector<MeshLib::Node*> nodes_copy; @@ -29,9 +29,10 @@ TEST(MeshLib, moveMeshNodes) nodes_copy.resize(size); /* put nodes with random coords into vectors */ - for (std::size_t k(0); k<size; k++) { + for (std::size_t k(0); k < size; k++) + { nodes[k] = new MeshLib::Node(rand(), rand(), rand()); - nodes_copy[k] = new MeshLib::Node(* nodes[k]); + nodes_copy[k] = new MeshLib::Node(*nodes[k]); } /* create random displacement */ @@ -50,7 +51,8 @@ TEST(MeshLib, moveMeshNodes) /* check the result */ double const eps(std::numeric_limits<double>::epsilon()); - for (std::size_t k(0); k<size; k++) { + for (std::size_t k(0); k < size; k++) + { EXPECT_NEAR((*nodes_copy[0])[0], (*nodes[0])[0], eps); EXPECT_NEAR((*nodes_copy[0])[1], (*nodes[0])[1], eps); EXPECT_NEAR((*nodes_copy[0])[2], (*nodes[0])[2], eps); @@ -65,4 +67,3 @@ TEST(MeshLib, moveMeshNodes) delete n; } } - diff --git a/Tests/MeshLib/TestNodeAdjacencyTable.cpp b/Tests/MeshLib/TestNodeAdjacencyTable.cpp index e6997d2b345f58f964bf50e1325d74d65e63cff0..c9c34f031cd3d2b9298deac4e0cd6ea86e59580b 100644 --- a/Tests/MeshLib/TestNodeAdjacencyTable.cpp +++ b/Tests/MeshLib/TestNodeAdjacencyTable.cpp @@ -7,7 +7,7 @@ * */ -#include "gtest/gtest.h" +#include <gtest/gtest.h> #include <memory> @@ -39,16 +39,16 @@ TEST(MeshLib, CreateNodeAdjacencyTable1D) std::size_t const n_elements = mesh->getNode(i)->getNumberOfElements(); switch (n_elements) { - case 1: // a corner node has 2 adjacent nodes. - ASSERT_EQ(2, n_connections) << " for boundary node " << i; - break; - case 2: // an interior node has 3 adjacent nodes. - ASSERT_EQ(3, n_connections) << " for interior node " << i; - break; - default: + case 1: // a corner node has 2 adjacent nodes. + ASSERT_EQ(2, n_connections) << " for boundary node " << i; + break; + case 2: // an interior node has 3 adjacent nodes. + ASSERT_EQ(3, n_connections) << " for interior node " << i; + break; + default: FAIL() << "The regular line mesh node has unexpected number " - << "of elements. Node " << i << " has " << n_elements - << " elements."; + << "of elements. Node " << i << " has " << n_elements + << " elements."; } } } @@ -73,19 +73,19 @@ TEST(MeshLib, CreateNodeAdjacencyTable2D) std::size_t const n_elements = mesh->getNode(i)->getNumberOfElements(); switch (n_elements) { - case 1: // a corner node has 4 adjacent nodes. + case 1: // a corner node has 4 adjacent nodes. ASSERT_EQ(4, n_connections) << " for corner node " << i; break; - case 2: // a boundary node has 6 adjacent nodes. + case 2: // a boundary node has 6 adjacent nodes. ASSERT_EQ(6, n_connections) << " for boundary node " << i; break; - case 4: // an interior node has 9 connections. + case 4: // an interior node has 9 connections. ASSERT_EQ(9, n_connections) << " for interior node " << i; break; - default: + default: FAIL() << "The regular quad mesh node has unexpected number " - << "of elements. Node " << i << " has " << n_elements - << " elements."; + << "of elements. Node " << i << " has " << n_elements + << " elements."; } } } @@ -94,9 +94,10 @@ TEST(MeshLib, CreateNodeAdjacencyTable3D) { using namespace MeshLib; - std::unique_ptr<Mesh> mesh(MeshGenerator::generateRegularHexMesh( - 1, 1, 1, 10.0, 10.0, 10.0)); - //double(1), double(1), double(1), std::size_t(10), std::size_t(10), std::size_t(10))); + std::unique_ptr<Mesh> mesh( + MeshGenerator::generateRegularHexMesh(1, 1, 1, 10.0, 10.0, 10.0)); + // double(1), double(1), double(1), std::size_t(10), std::size_t(10), + // std::size_t(10))); NodeAdjacencyTable table(mesh->getNodes()); @@ -111,22 +112,22 @@ TEST(MeshLib, CreateNodeAdjacencyTable3D) std::size_t const n_elements = mesh->getNode(i)->getNumberOfElements(); switch (n_elements) { - case 1: // a corner node has 8 adjacent nodes. + case 1: // a corner node has 8 adjacent nodes. ASSERT_EQ(8, n_connections) << " for corner node " << i; break; - case 2: // an edge node has 12 adjacent nodes. + case 2: // an edge node has 12 adjacent nodes. ASSERT_EQ(12, n_connections) << " for edge node " << i; break; - case 3: // a boundary node has 18 adjacent nodes. + case 3: // a boundary node has 18 adjacent nodes. ASSERT_EQ(18, n_connections) << " for boundary node " << i; break; - case 4: // an interior node has 27 connections. + case 4: // an interior node has 27 connections. ASSERT_EQ(27, n_connections) << " for interior node " << i; break; - default: + default: FAIL() << "The regular hex mesh node has unexpected number " - << "of elements. Node " << i << " has " << n_elements - << " elements."; + << "of elements. Node " << i << " has " << n_elements + << " elements."; } } } diff --git a/Tests/MeshLib/TestNodeSearch.cpp b/Tests/MeshLib/TestNodeSearch.cpp index 9635697c1e261566996c05cddce9f32a922f4029..45164f1fd0031ee707ecc596f900d6ad975ab18b 100644 --- a/Tests/MeshLib/TestNodeSearch.cpp +++ b/Tests/MeshLib/TestNodeSearch.cpp @@ -7,23 +7,23 @@ * http://www.opengeosys.org/project/license */ -#include "gtest/gtest.h" +#include <gtest/gtest.h> #include <memory> -#include "MeshLib/Mesh.h" -#include "MeshLib/Node.h" +#include "GeoLib/Raster.h" #include "MeshLib/Elements/Element.h" -#include "MeshLib/MeshSearch/NodeSearch.h" -#include "MeshLib/MeshGenerators/RasterToMesh.h" -#include "MeshLib/MeshGenerators/MeshGenerator.h" +#include "MeshLib/Mesh.h" #include "MeshLib/MeshEditing/DuplicateMeshComponents.h" - -#include "GeoLib/Raster.h" +#include "MeshLib/MeshGenerators/MeshGenerator.h" +#include "MeshLib/MeshGenerators/RasterToMesh.h" +#include "MeshLib/MeshSearch/NodeSearch.h" +#include "MeshLib/Node.h" TEST(NodeSearch, UnusedNodes) { - std::array<double, 12> pix = {{0,0.1,0.2,0.1,0,0,0.1,0,0,0,-0.1,0}}; + std::array<double, 12> pix = { + {0, 0.1, 0.2, 0.1, 0, 0, 0.1, 0, 0, 0, -0.1, 0}}; GeoLib::RasterHeader header = { 4, 3, 1, MathLib::Point3d(std::array<double, 3>{{0, 0, 0}}), 1, -9999}; GeoLib::Raster const raster(std::move(header), pix.begin(), pix.end()); @@ -35,9 +35,11 @@ TEST(NodeSearch, UnusedNodes) std::vector<std::size_t> u_nodes = ns.getSearchedNodeIDs(); ASSERT_EQ(0, u_nodes.size()); - std::vector<MeshLib::Node*> nodes = MeshLib::copyNodeVector(mesh->getNodes()); - nodes.push_back(new MeshLib::Node(-1,-1,-1)); - std::vector<MeshLib::Element*> elems = MeshLib::copyElementVector(mesh->getElements(),nodes); + std::vector<MeshLib::Node*> nodes = + MeshLib::copyNodeVector(mesh->getNodes()); + nodes.push_back(new MeshLib::Node(-1, -1, -1)); + std::vector<MeshLib::Element*> elems = + MeshLib::copyElementVector(mesh->getElements(), nodes); MeshLib::Mesh mesh2("mesh2", nodes, elems); MeshLib::NodeSearch ns2(mesh2); ns2.searchUnused(); @@ -46,10 +48,10 @@ TEST(NodeSearch, UnusedNodes) ASSERT_EQ(nodes.back()->getID(), u_nodes[0]); } - TEST(NodeSearch, BoundaryNodes1D) { - std::unique_ptr<MeshLib::Mesh> mesh (MeshLib::MeshGenerator::generateLineMesh(5, 1.0)); + std::unique_ptr<MeshLib::Mesh> mesh( + MeshLib::MeshGenerator::generateLineMesh(5, 1.0)); MeshLib::NodeSearch ns(*mesh); ns.searchBoundaryNodes(); std::vector<std::size_t> searched_nodes = ns.getSearchedNodeIDs(); @@ -60,18 +62,19 @@ TEST(NodeSearch, BoundaryNodes1D) TEST(NodeSearch, BoundaryNodes2D) { - std::unique_ptr<MeshLib::Mesh> mesh (MeshLib::MeshGenerator::generateRegularQuadMesh(5, 5, 1.0, 1.0)); + std::unique_ptr<MeshLib::Mesh> mesh( + MeshLib::MeshGenerator::generateRegularQuadMesh(5, 5, 1.0, 1.0)); MeshLib::NodeSearch ns(*mesh); ns.searchBoundaryNodes(); std::vector<std::size_t> searched_nodes = ns.getSearchedNodeIDs(); ASSERT_EQ(20, searched_nodes.size()); for (auto nodeid : searched_nodes) { - auto &node = *mesh->getNode(nodeid); + auto& node = *mesh->getNode(nodeid); bool isOnBnd = false; - for (unsigned i=0; i<mesh->getDimension(); i++) + for (unsigned i = 0; i < mesh->getDimension(); i++) { - if (node[i]==0.0 || node[i]==5.0) + if (node[i] == 0.0 || node[i] == 5.0) { isOnBnd = true; break; @@ -84,18 +87,19 @@ TEST(NodeSearch, BoundaryNodes2D) TEST(NodeSearch, BoundaryNodes3D) { - std::unique_ptr<MeshLib::Mesh> mesh (MeshLib::MeshGenerator::generateRegularHexMesh(5, 5, 5, 1.0, 1.0, 1.0)); + std::unique_ptr<MeshLib::Mesh> mesh( + MeshLib::MeshGenerator::generateRegularHexMesh(5, 5, 5, 1.0, 1.0, 1.0)); MeshLib::NodeSearch ns(*mesh); ns.searchBoundaryNodes(); std::vector<std::size_t> searched_nodes = ns.getSearchedNodeIDs(); ASSERT_EQ(152u, searched_nodes.size()); for (auto nodeid : searched_nodes) { - auto &node = *mesh->getNode(nodeid); + auto& node = *mesh->getNode(nodeid); bool isOnBnd = false; - for (unsigned i=0; i<mesh->getDimension(); i++) + for (unsigned i = 0; i < mesh->getDimension(); i++) { - if (node[i]==0.0 || node[i]==5.0) + if (node[i] == 0.0 || node[i] == 5.0) { isOnBnd = true; break; diff --git a/Tests/MeshLib/TestPntInElement.cpp b/Tests/MeshLib/TestPntInElement.cpp index 0977c7b29c7b4f1298c35b535a4da6a301e8628b..f9303aaf2dd9a483a6ec2f43064ecf7d08aadcb7 100644 --- a/Tests/MeshLib/TestPntInElement.cpp +++ b/Tests/MeshLib/TestPntInElement.cpp @@ -29,31 +29,32 @@ std::vector<MeshLib::Node*> createNodes() { std::vector<MeshLib::Node*> nodes; - nodes.push_back(new MeshLib::Node(0,0,0)); - nodes.push_back(new MeshLib::Node(1,0,0)); - nodes.push_back(new MeshLib::Node(1,1,0)); - nodes.push_back(new MeshLib::Node(0,1,0)); - nodes.push_back(new MeshLib::Node(0,0,1)); - nodes.push_back(new MeshLib::Node(1,0,1)); - nodes.push_back(new MeshLib::Node(1,1,1)); - nodes.push_back(new MeshLib::Node(0,1,1)); + nodes.push_back(new MeshLib::Node(0, 0, 0)); + nodes.push_back(new MeshLib::Node(1, 0, 0)); + nodes.push_back(new MeshLib::Node(1, 1, 0)); + nodes.push_back(new MeshLib::Node(0, 1, 0)); + nodes.push_back(new MeshLib::Node(0, 0, 1)); + nodes.push_back(new MeshLib::Node(1, 0, 1)); + nodes.push_back(new MeshLib::Node(1, 1, 1)); + nodes.push_back(new MeshLib::Node(0, 1, 1)); return nodes; } -void deleteNodes(std::vector<MeshLib::Node*> &nodes) +void deleteNodes(std::vector<MeshLib::Node*>& nodes) { - std::for_each(nodes.begin(), nodes.end(), [](MeshLib::Node* node){ delete node; }); + std::for_each(nodes.begin(), nodes.end(), + [](MeshLib::Node* node) { delete node; }); } TEST(IsPntInElement, Line) { GeoLib::Point pnt; - std::vector<MeshLib::Node*> nodes (createNodes()); - std::array<MeshLib::Node*, 2> line_nodes = {{ nodes[0], nodes[4] }}; + std::vector<MeshLib::Node*> nodes(createNodes()); + std::array<MeshLib::Node*, 2> line_nodes = {{nodes[0], nodes[4]}}; MeshLib::Line line(line_nodes); - pnt = GeoLib::Point(0,0,0.7); + pnt = GeoLib::Point(0, 0, 0.7); ASSERT_TRUE(line.isPntInElement(pnt)); - pnt = GeoLib::Point(0,0.1,0.7); + pnt = GeoLib::Point(0, 0.1, 0.7); ASSERT_FALSE(line.isPntInElement(pnt)); deleteNodes(nodes); } @@ -61,13 +62,13 @@ TEST(IsPntInElement, Line) TEST(IsPntInElement, Tri) { GeoLib::Point pnt; - std::vector<MeshLib::Node*> nodes (createNodes()); - std::array<MeshLib::Node*, 3> tri_nodes = {{ nodes[0], nodes[1], nodes[4] }}; + std::vector<MeshLib::Node*> nodes(createNodes()); + std::array<MeshLib::Node*, 3> tri_nodes = {{nodes[0], nodes[1], nodes[4]}}; MeshLib::Tri tri(tri_nodes); - pnt = GeoLib::Point(0.1,0,0.1); + pnt = GeoLib::Point(0.1, 0, 0.1); ASSERT_TRUE(tri.isPntInElement(pnt)); - pnt = GeoLib::Point(0.9,0,0.7); + pnt = GeoLib::Point(0.9, 0, 0.7); ASSERT_FALSE(tri.isPntInElement(pnt)); deleteNodes(nodes); } @@ -75,16 +76,16 @@ TEST(IsPntInElement, Tri) TEST(IsPntInElement, Quad) { GeoLib::Point pnt; - std::vector<MeshLib::Node*> nodes (createNodes()); - std::array<MeshLib::Node*, 4> quad_nodes = - {{ nodes[0], nodes[1], nodes[5], nodes[4] }}; + std::vector<MeshLib::Node*> nodes(createNodes()); + std::array<MeshLib::Node*, 4> quad_nodes = { + {nodes[0], nodes[1], nodes[5], nodes[4]}}; MeshLib::Quad quad(quad_nodes); - pnt = GeoLib::Point(0.1,0,0.1); + pnt = GeoLib::Point(0.1, 0, 0.1); ASSERT_TRUE(quad.isPntInElement(pnt)); - pnt = GeoLib::Point(0.999,0,0.001); + pnt = GeoLib::Point(0.999, 0, 0.001); ASSERT_TRUE(quad.isPntInElement(pnt)); - pnt = GeoLib::Point(0.5,0.00001,1); + pnt = GeoLib::Point(0.5, 0.00001, 1); ASSERT_FALSE(quad.isPntInElement(pnt)); ASSERT_TRUE(quad.isPntInElement(pnt, 0.001)); deleteNodes(nodes); @@ -93,14 +94,14 @@ TEST(IsPntInElement, Quad) TEST(IsPntInElement, Tet) { GeoLib::Point pnt; - std::vector<MeshLib::Node*> nodes (createNodes()); - std::array<MeshLib::Node*, 4> tet_nodes = - {{ nodes[0], nodes[1], nodes[2], nodes[4] }}; + std::vector<MeshLib::Node*> nodes(createNodes()); + std::array<MeshLib::Node*, 4> tet_nodes = { + {nodes[0], nodes[1], nodes[2], nodes[4]}}; MeshLib::Tet tet(tet_nodes); - pnt = GeoLib::Point(0.5,0.3,0.1); + pnt = GeoLib::Point(0.5, 0.3, 0.1); ASSERT_TRUE(tet.isPntInElement(pnt)); - pnt = GeoLib::Point(0.5,0.6,0.1); + pnt = GeoLib::Point(0.5, 0.6, 0.1); ASSERT_FALSE(tet.isPntInElement(pnt)); deleteNodes(nodes); } @@ -108,17 +109,17 @@ TEST(IsPntInElement, Tet) TEST(IsPntInElement, Pyramid) { GeoLib::Point pnt; - std::vector<MeshLib::Node*> nodes (createNodes()); + std::vector<MeshLib::Node*> nodes(createNodes()); std::array<MeshLib::Node*, 5> pyr_nodes{}; - std::copy(nodes.begin(), nodes.begin()+5, pyr_nodes.begin()); + std::copy(nodes.begin(), nodes.begin() + 5, pyr_nodes.begin()); MeshLib::Pyramid pyr(pyr_nodes); - pnt = GeoLib::Point(0.5,0.00001,-0.000001); + pnt = GeoLib::Point(0.5, 0.00001, -0.000001); ASSERT_FALSE(pyr.isPntInElement(pnt)); ASSERT_TRUE(pyr.isPntInElement(pnt, 0.0001)); - pnt = GeoLib::Point(0.5,0.5,0.1); + pnt = GeoLib::Point(0.5, 0.5, 0.1); ASSERT_TRUE(pyr.isPntInElement(pnt)); - pnt = GeoLib::Point(0.5,0.5,0.51); + pnt = GeoLib::Point(0.5, 0.5, 0.51); ASSERT_FALSE(pyr.isPntInElement(pnt)); ASSERT_TRUE(pyr.isPntInElement(pnt, 0.02)); deleteNodes(nodes); @@ -127,14 +128,14 @@ TEST(IsPntInElement, Pyramid) TEST(IsPntInElement, Prism) { GeoLib::Point pnt; - std::vector<MeshLib::Node*> nodes (createNodes()); - std::array<MeshLib::Node*, 6> prism_nodes = - {{ nodes[0], nodes[1], nodes[2], nodes[4], nodes[5], nodes[6] }}; + std::vector<MeshLib::Node*> nodes(createNodes()); + std::array<MeshLib::Node*, 6> prism_nodes = { + {nodes[0], nodes[1], nodes[2], nodes[4], nodes[5], nodes[6]}}; MeshLib::Prism prism(prism_nodes); - pnt = GeoLib::Point(0.5,0.5,0.1); + pnt = GeoLib::Point(0.5, 0.5, 0.1); ASSERT_TRUE(prism.isPntInElement(pnt)); - pnt = GeoLib::Point(0.49,0.51,0.1); + pnt = GeoLib::Point(0.49, 0.51, 0.1); ASSERT_FALSE(prism.isPntInElement(pnt)); ASSERT_TRUE(prism.isPntInElement(pnt, 0.03)); deleteNodes(nodes); @@ -143,18 +144,18 @@ TEST(IsPntInElement, Prism) TEST(IsPntInElement, Hex) { GeoLib::Point pnt; - std::vector<MeshLib::Node*> nodes (createNodes()); + std::vector<MeshLib::Node*> nodes(createNodes()); std::array<MeshLib::Node*, 8> hex_nodes{}; std::copy(nodes.begin(), nodes.end(), hex_nodes.begin()); MeshLib::Hex hex(hex_nodes); - pnt = GeoLib::Point(0.99,0.99,0.99); + pnt = GeoLib::Point(0.99, 0.99, 0.99); ASSERT_TRUE(hex.isPntInElement(pnt)); - pnt = GeoLib::Point(0.99,0,0); + pnt = GeoLib::Point(0.99, 0, 0); ASSERT_TRUE(hex.isPntInElement(pnt)); pnt = GeoLib::Point(0.0, 0.0, 0.0); ASSERT_TRUE(hex.isPntInElement(pnt)); - pnt = GeoLib::Point(1.01,0.99,0.99); + pnt = GeoLib::Point(1.01, 0.99, 0.99); ASSERT_FALSE(hex.isPntInElement(pnt)); ASSERT_TRUE(hex.isPntInElement(pnt, 0.02)); deleteNodes(nodes); diff --git a/Tests/MeshLib/TestPrismQualityCriteria.cpp b/Tests/MeshLib/TestPrismQualityCriteria.cpp index 8c2f7c4c6476849cf406addef9ff86a50af26a0d..64264f824b1a5295353dd25cd3ee41148baba5d6 100644 --- a/Tests/MeshLib/TestPrismQualityCriteria.cpp +++ b/Tests/MeshLib/TestPrismQualityCriteria.cpp @@ -7,17 +7,17 @@ * http://www.opengeosys.org/project/license */ +#include <gtest/gtest.h> + #include <memory> #include <numeric> #include <random> -#include "gtest/gtest.h" - -#include "MeshLib/Mesh.h" -#include "MeshLib/Node.h" #include "MeshLib/Elements/Element.h" +#include "MeshLib/Mesh.h" #include "MeshLib/MeshGenerators/MeshGenerator.h" #include "MeshLib/MeshQuality/ElementQualityInterface.h" +#include "MeshLib/Node.h" class PrismElementQuality : public ::testing::Test { @@ -105,6 +105,6 @@ TEST_F(PrismElementQuality, EquiAngleSkew) for (auto const element_quality : element_quality_vector) { ASSERT_NEAR(expected_value, element_quality, - 2*std::numeric_limits<double>::epsilon()); + 2 * std::numeric_limits<double>::epsilon()); } } diff --git a/Tests/MeshLib/TestPyramidQualityCriteria.cpp b/Tests/MeshLib/TestPyramidQualityCriteria.cpp index a1526becafc136b8d9884c9f3b4b43ffac51d4cb..3e3d8fb62dbac8f30f06edade27257c514ff4985 100644 --- a/Tests/MeshLib/TestPyramidQualityCriteria.cpp +++ b/Tests/MeshLib/TestPyramidQualityCriteria.cpp @@ -7,6 +7,8 @@ * http://www.opengeosys.org/project/license */ +#include <gtest/gtest.h> + #include <memory> #include <numeric> #include <random> @@ -16,7 +18,6 @@ #include "MeshLib/MeshGenerators/MeshGenerator.h" #include "MeshLib/MeshQuality/ElementQualityInterface.h" #include "MeshLib/Node.h" -#include "gtest/gtest.h" class PyramidElementQuality : public ::testing::Test { @@ -116,7 +117,7 @@ TEST_F(PyramidElementQuality, EdgeRatio) edge_lengths_front_back.begin(), edge_lengths_front_back.end()); auto const expected_value_front_back = *min_max_front_back.first / *min_max_front_back.second; - for (int i = 0; i<element_quality_vector.size(); i=i+6) + for (int i = 0; i < element_quality_vector.size(); i = i + 6) { ASSERT_NEAR(expected_value_top_bottom, element_quality_vector[i], 10 * std::numeric_limits<double>::epsilon()); diff --git a/Tests/MeshLib/TestQuadMesh.cpp b/Tests/MeshLib/TestQuadMesh.cpp index 7599e415c58c0272af7531943fc139ff7d5d1192..6fd6861c6fc2ab47ae46de22c6d0a081500f5505 100644 --- a/Tests/MeshLib/TestQuadMesh.cpp +++ b/Tests/MeshLib/TestQuadMesh.cpp @@ -7,19 +7,19 @@ * http://www.opengeosys.org/project/license */ +#include <gtest/gtest.h> + #include <ctime> #include <iterator> #include <list> -#include "gtest/gtest.h" - -#include "MeshLib/MeshGenerators/MeshGenerator.h" -#include "MeshLib/Mesh.h" #include "MeshLib/Elements/Quad.h" +#include "MeshLib/Mesh.h" +#include "MeshLib/MeshGenerators/MeshGenerator.h" class MeshLibQuadMesh : public ::testing::Test { - public: +public: MeshLibQuadMesh() { mesh = MeshLib::MeshGenerator::generateRegularQuadMesh(1.0, n_elements); @@ -50,34 +50,34 @@ public: Indices getNeighbor(std::size_t const i) const { std::list<std::size_t> result; - switch (i) { - case 0: - result.push_back(i + 1); - break; - case elements_stride: - result.push_back(i - 1); - break; - default: - result.push_back(i - 1); - result.push_back(i + 1); - break; + switch (i) + { + case 0: + result.push_back(i + 1); + break; + case elements_stride: + result.push_back(i - 1); + break; + default: + result.push_back(i - 1); + result.push_back(i + 1); + break; } return result; } template <typename F> - void - testCornerElements(F const&& f) + void testCornerElements(F const&& f) { - f(getElement(0, 0), 0, 0); // BL - f(getElement(0, elements_stride), 0, elements_stride); // BR - f(getElement(elements_stride, 0), elements_stride, 0); // BL - f(getElement(elements_stride, elements_stride), elements_stride, elements_stride);// BR + f(getElement(0, 0), 0, 0); // BL + f(getElement(0, elements_stride), 0, elements_stride); // BR + f(getElement(elements_stride, 0), elements_stride, 0); // BL + f(getElement(elements_stride, elements_stride), elements_stride, + elements_stride); // BR } template <typename F> - void - testBoundaryElements(F const&& f) + void testBoundaryElements(F const&& f) { // left for (std::size_t j = 1; j < elements_stride; ++j) @@ -102,8 +102,7 @@ public: } template <typename F> - void - testInsideElements(F const&& f) + void testInsideElements(F const&& f) { for (std::size_t i = 1; i < elements_stride; ++i) { @@ -115,8 +114,7 @@ public: } template <typename F> - void - testAllElements(F const&& f) + void testAllElements(F const&& f) { for (std::size_t i = 0; i < elements_stride; ++i) { @@ -128,19 +126,16 @@ public: } template <typename F> - void - testCornerNodes(F const&& f) + void testCornerNodes(F const&& f) { f(getNode(0, 0), 0, 0); f(getNode(0, nodes_stride), 0, nodes_stride); f(getNode(nodes_stride, 0), nodes_stride, 0); - f(getNode(nodes_stride, nodes_stride), - nodes_stride, nodes_stride); + f(getNode(nodes_stride, nodes_stride), nodes_stride, nodes_stride); } template <typename F> - void - testBoundaryNodes(F const&& f) + void testBoundaryNodes(F const&& f) { // left for (std::size_t j = 1; j < nodes_stride; ++j) @@ -165,8 +160,7 @@ public: } template <typename F> - void - testInsideNodes(F const&& f) + void testInsideNodes(F const&& f) { for (std::size_t i = 1; i < nodes_stride; ++i) { @@ -186,32 +180,29 @@ TEST_F(MeshLibQuadMesh, Construction) ASSERT_EQ(n_elements * n_elements, mesh->getNumberOfElements()); // There are n_nodes^2 nodes in the mesh. - ASSERT_EQ(n_nodes*n_nodes, mesh->getNumberOfNodes()); + ASSERT_EQ(n_nodes * n_nodes, mesh->getNumberOfNodes()); // All elements have maximum four neighbors. - testAllElements([](MeshLib::Element const* const e, ...) - { - ASSERT_EQ(4u, e->getNumberOfNeighbors()); - }); + testAllElements([](MeshLib::Element const* const e, ...) { + ASSERT_EQ(4u, e->getNumberOfNeighbors()); + }); } TEST_F(MeshLibQuadMesh, ElementNeighbors) { - auto count_neighbors = [](MeshLib::Element const* const e) + auto count_neighbors = [](MeshLib::Element const* const e) { + unsigned count = 0; + for (int i = 0; i < 4; i++) { - unsigned count = 0; - for (int i = 0; i < 4; i++) + if (e->getNeighbor(i) != nullptr) { - if (e->getNeighbor(i) != nullptr) - { - count++; - } + count++; } - return count; - }; + } + return count; + }; - auto getNeighborIndices = [this](std::size_t const i, std::size_t const j) - { + auto getNeighborIndices = [this](std::size_t const i, std::size_t const j) { return std::make_pair(getNeighbor(i), getNeighbor(j)); }; @@ -231,65 +222,63 @@ TEST_F(MeshLibQuadMesh, ElementNeighbors) }; // Two neighbors for corner elements. - testCornerElements([&](MeshLib::Element const* const e, - std::size_t const i, std::size_t const j) - { - EXPECT_EQ(2u, count_neighbors(e)); + testCornerElements([&](MeshLib::Element const* const e, std::size_t const i, + std::size_t const j) { + EXPECT_EQ(2u, count_neighbors(e)); - std::pair<Indices, Indices> const ij_neighbors = getNeighborIndices(i, j); - // Test the test - EXPECT_EQ(1u, ij_neighbors.first.size()); - EXPECT_EQ(1u, ij_neighbors.second.size()); - ASSERT_TRUE(e->isBoundaryElement()); + std::pair<Indices, Indices> const ij_neighbors = + getNeighborIndices(i, j); + // Test the test + EXPECT_EQ(1u, ij_neighbors.first.size()); + EXPECT_EQ(1u, ij_neighbors.second.size()); + ASSERT_TRUE(e->isBoundaryElement()); - testNeighbors(e, i, j, ij_neighbors); - }); + testNeighbors(e, i, j, ij_neighbors); + }); // Three neighbors for boundary elements. testBoundaryElements([&](MeshLib::Element const* const e, - std::size_t const i, std::size_t const j) - { - EXPECT_EQ(3u, count_neighbors(e)); + std::size_t const i, std::size_t const j) { + EXPECT_EQ(3u, count_neighbors(e)); - std::pair<Indices, Indices> const ij_neighbors = getNeighborIndices(i, j); - // Test the test - EXPECT_EQ(3u, ij_neighbors.first.size() + ij_neighbors.second.size()); - ASSERT_TRUE(e->isBoundaryElement()); + std::pair<Indices, Indices> const ij_neighbors = + getNeighborIndices(i, j); + // Test the test + EXPECT_EQ(3u, ij_neighbors.first.size() + ij_neighbors.second.size()); + ASSERT_TRUE(e->isBoundaryElement()); - testNeighbors(e, i, j, ij_neighbors); - }); + testNeighbors(e, i, j, ij_neighbors); + }); // Four neighbors inside mesh. - testInsideElements([&](MeshLib::Element const* const e, - std::size_t const i, std::size_t const j) - { - EXPECT_EQ(4u, count_neighbors(e)); - - std::pair<Indices, Indices> const ij_neighbors = getNeighborIndices(i, j); - // Test the test - EXPECT_EQ(2u, ij_neighbors.first.size()); - EXPECT_EQ(2u, ij_neighbors.second.size()); - ASSERT_FALSE(e->isBoundaryElement()); - - testNeighbors(e, i, j, ij_neighbors); - }); + testInsideElements([&](MeshLib::Element const* const e, std::size_t const i, + std::size_t const j) { + EXPECT_EQ(4u, count_neighbors(e)); + + std::pair<Indices, Indices> const ij_neighbors = + getNeighborIndices(i, j); + // Test the test + EXPECT_EQ(2u, ij_neighbors.first.size()); + EXPECT_EQ(2u, ij_neighbors.second.size()); + ASSERT_FALSE(e->isBoundaryElement()); + + testNeighbors(e, i, j, ij_neighbors); + }); } TEST_F(MeshLibQuadMesh, ElementToNodeConnectivity) { // An element (i,j) consists of four nodes (i,j), (i+1,j), (i+1, j+1), // and (i, j+1). - testAllElements([this]( - MeshLib::Element const* const e, - std::size_t const i, - std::size_t const j) - { - EXPECT_EQ(4u, e->getNumberOfBaseNodes()); - EXPECT_EQ(getNode(i, j), e->getNode(0)); - EXPECT_EQ(getNode(i, j+1), e->getNode(1)); - EXPECT_EQ(getNode(i+1, j+1), e->getNode(2)); - EXPECT_EQ(getNode(i+1, j), e->getNode(3)); - }); + testAllElements([this](MeshLib::Element const* const e, + std::size_t const i, + std::size_t const j) { + EXPECT_EQ(4u, e->getNumberOfBaseNodes()); + EXPECT_EQ(getNode(i, j), e->getNode(0)); + EXPECT_EQ(getNode(i, j + 1), e->getNode(1)); + EXPECT_EQ(getNode(i + 1, j + 1), e->getNode(2)); + EXPECT_EQ(getNode(i + 1, j), e->getNode(3)); + }); } // A node is connected to four elements inside the mesh, two on the boundary, @@ -297,10 +286,7 @@ TEST_F(MeshLibQuadMesh, ElementToNodeConnectivity) TEST_F(MeshLibQuadMesh, NodeToElementConnectivity) { testCornerNodes( - [this](MeshLib::Node const* const node, - std::size_t i, - std::size_t j) - { + [this](MeshLib::Node const* const node, std::size_t i, std::size_t j) { EXPECT_EQ(1u, node->getNumberOfElements()); if (i == nodes_stride) @@ -315,46 +301,42 @@ TEST_F(MeshLibQuadMesh, NodeToElementConnectivity) EXPECT_EQ(getElement(i, j), node->getElement(0)); }); - testBoundaryNodes([this]( - MeshLib::Node const* const node, - std::size_t i, - std::size_t j) - { + testBoundaryNodes( + [this](MeshLib::Node const* const node, std::size_t i, std::size_t j) { EXPECT_EQ(2u, node->getNumberOfElements()); if (i == 0) { - EXPECT_EQ(getElement(i, j-1), node->getElement(0)); + EXPECT_EQ(getElement(i, j - 1), node->getElement(0)); EXPECT_EQ(getElement(i, j), node->getElement(1)); } if (i == nodes_stride) { - EXPECT_EQ(getElement(elements_stride, j-1), node->getElement(0)); + EXPECT_EQ(getElement(elements_stride, j - 1), + node->getElement(0)); EXPECT_EQ(getElement(elements_stride, j), node->getElement(1)); } if (j == 0) { - EXPECT_EQ(getElement(i-1, j), node->getElement(0)); + EXPECT_EQ(getElement(i - 1, j), node->getElement(0)); EXPECT_EQ(getElement(i, j), node->getElement(1)); } if (j == nodes_stride) { j--; - EXPECT_EQ(getElement(i-1, j), node->getElement(0)); + EXPECT_EQ(getElement(i - 1, j), node->getElement(0)); EXPECT_EQ(getElement(i, j), node->getElement(1)); } }); - testInsideNodes([this]( - MeshLib::Node const* const node, - std::size_t const i, - std::size_t const j) - { - EXPECT_EQ(4u, node->getNumberOfElements()); + testInsideNodes([this](MeshLib::Node const* const node, + std::size_t const i, + std::size_t const j) { + EXPECT_EQ(4u, node->getNumberOfElements()); - EXPECT_EQ(getElement(i-1, j-1), node->getElement(0)); - EXPECT_EQ(getElement(i-1, j ), node->getElement(1)); - EXPECT_EQ(getElement(i, j-1), node->getElement(2)); - EXPECT_EQ(getElement(i, j ), node->getElement(3)); - }); + EXPECT_EQ(getElement(i - 1, j - 1), node->getElement(0)); + EXPECT_EQ(getElement(i - 1, j), node->getElement(1)); + EXPECT_EQ(getElement(i, j - 1), node->getElement(2)); + EXPECT_EQ(getElement(i, j), node->getElement(3)); + }); } diff --git a/Tests/MeshLib/TestQuadQualityCriteria.cpp b/Tests/MeshLib/TestQuadQualityCriteria.cpp index cb895e6d67a4918655deb91051eb07c3cdb9b515..07d063552ac737ae10a6fdb3b7877363768ce3d4 100644 --- a/Tests/MeshLib/TestQuadQualityCriteria.cpp +++ b/Tests/MeshLib/TestQuadQualityCriteria.cpp @@ -7,17 +7,17 @@ * http://www.opengeosys.org/project/license */ +#include <gtest/gtest.h> + #include <memory> #include <numeric> #include <random> -#include "gtest/gtest.h" - -#include "MeshLib/Mesh.h" -#include "MeshLib/Node.h" #include "MeshLib/Elements/Element.h" +#include "MeshLib/Mesh.h" #include "MeshLib/MeshGenerators/MeshGenerator.h" #include "MeshLib/MeshQuality/ElementQualityInterface.h" +#include "MeshLib/Node.h" class QuadElementQuality : public ::testing::Test { diff --git a/Tests/MeshLib/TestQuadraticMesh.cpp b/Tests/MeshLib/TestQuadraticMesh.cpp index 1baed4ea109865fc1082c44d1b7506e0ffd36fff..a151e270c24f3ddd5b94e665ae103789eb3e740f 100644 --- a/Tests/MeshLib/TestQuadraticMesh.cpp +++ b/Tests/MeshLib/TestQuadraticMesh.cpp @@ -7,26 +7,25 @@ * */ -#include "gtest/gtest.h" +#include <gtest/gtest.h> #include <memory> #include "GeoLib/Polyline.h" #include "GeoLib/PolylineVec.h" - +#include "MeshGeoToolsLib/AppendLinesAlongPolyline.h" #include "MeshLib/Elements/Element.h" #include "MeshLib/Mesh.h" #include "MeshLib/MeshGenerators/MeshGenerator.h" #include "MeshLib/MeshGenerators/QuadraticMeshGenerator.h" #include "MeshLib/Node.h" -#include "MeshGeoToolsLib/AppendLinesAlongPolyline.h" TEST(MeshLib, QuadraticOrderMesh_Line) { using namespace MeshLib; - std::unique_ptr<Mesh> linear_mesh(MeshGenerator::generateLineMesh( - 1, std::size_t(2))); + std::unique_ptr<Mesh> linear_mesh( + MeshGenerator::generateLineMesh(1, std::size_t(2))); std::unique_ptr<Mesh> mesh( createQuadraticOrderMesh(*linear_mesh, false /* add centre node*/)); ASSERT_EQ(5u, mesh->getNumberOfNodes()); @@ -180,18 +179,20 @@ TEST(MeshLib, QuadraticOrderMesh_LineQuad) { using namespace MeshLib; - std::unique_ptr<Mesh> linear_quad_mesh(MeshGenerator::generateRegularQuadMesh( - 1, 1, std::size_t(2), std::size_t(2))); + std::unique_ptr<Mesh> linear_quad_mesh( + MeshGenerator::generateRegularQuadMesh(1, 1, std::size_t(2), + std::size_t(2))); std::unique_ptr<Mesh> linear_mesh; { std::vector<GeoLib::Point*> pnts; - pnts.push_back(new GeoLib::Point(0,0.5,0,0)); - pnts.push_back(new GeoLib::Point(1,0.5,0,1)); + pnts.push_back(new GeoLib::Point(0, 0.5, 0, 0)); + pnts.push_back(new GeoLib::Point(1, 0.5, 0, 1)); auto* ply = new GeoLib::Polyline(pnts); ply->addPoint(0); ply->addPoint(1); - std::unique_ptr<std::vector<GeoLib::Polyline*>> plys(new std::vector<GeoLib::Polyline*>()); + std::unique_ptr<std::vector<GeoLib::Polyline*>> plys( + new std::vector<GeoLib::Polyline*>()); plys->push_back(ply); GeoLib::PolylineVec ply_vec("", std::move(plys)); diff --git a/Tests/MeshLib/TestRasterDataToMesh.cpp b/Tests/MeshLib/TestRasterDataToMesh.cpp index efbaba0580043494c3174a377df114c0a4dfd70c..6055fabfd0e8275359bcf5c66d894caa637fcad3 100644 --- a/Tests/MeshLib/TestRasterDataToMesh.cpp +++ b/Tests/MeshLib/TestRasterDataToMesh.cpp @@ -9,19 +9,18 @@ * */ +#include <gtest/gtest.h> + #include <algorithm> #include <cstdio> #include <memory> -#include "gtest/gtest.h" - -#include "InfoLib/TestInfo.h" - #include "Applications/FileIO/AsciiRasterInterface.h" #include "GeoLib/Raster.h" +#include "InfoLib/TestInfo.h" +#include "MeshLib/IO/VtkIO/VtuInterface.h" #include "MeshLib/Mesh.h" #include "MeshLib/MeshEditing/RasterDataToMesh.h" -#include "MeshLib/IO/VtkIO/VtuInterface.h" class RasterDataToMeshTest : public ::testing::Test { @@ -44,11 +43,12 @@ protected: TEST_F(RasterDataToMeshTest, readRasterValuesToNodes) { std::string const vec_name = "imgvalues"; - bool ret = MeshLib::RasterDataToMesh::projectToNodes(*_mesh, *_raster, 0, vec_name); + bool ret = MeshLib::RasterDataToMesh::projectToNodes(*_mesh, *_raster, 0, + vec_name); ASSERT_TRUE(ret); - std::string const compare_path = - TestInfoLib::TestInfo::data_path + "/MeshLib/RasterDataToMesh-Nodes.vtu"; + std::string const compare_path = TestInfoLib::TestInfo::data_path + + "/MeshLib/RasterDataToMesh-Nodes.vtu"; std::unique_ptr<MeshLib::Mesh> compare{ MeshLib::IO::VtuInterface::readVTUFile(compare_path)}; @@ -56,7 +56,8 @@ TEST_F(RasterDataToMeshTest, readRasterValuesToNodes) auto org_vec = compare->getProperties().getPropertyVector<double>("RasterValues"); - bool is_equal = std::equal(org_vec->cbegin(), org_vec->cend(), new_vec->cbegin()); + bool is_equal = + std::equal(org_vec->cbegin(), org_vec->cend(), new_vec->cbegin()); ASSERT_TRUE(is_equal); } @@ -64,7 +65,8 @@ TEST_F(RasterDataToMeshTest, readRasterValuesToNodes) TEST_F(RasterDataToMeshTest, readRasterValuesToElements) { std::string const vec_name = "imgvalues"; - bool ret = MeshLib::RasterDataToMesh::projectToElements(*_mesh, *_raster, 0, vec_name); + bool ret = MeshLib::RasterDataToMesh::projectToElements(*_mesh, *_raster, 0, + vec_name); ASSERT_TRUE(ret); std::string const compare_path = TestInfoLib::TestInfo::data_path + diff --git a/Tests/MeshLib/TestRasterToMesh.cpp b/Tests/MeshLib/TestRasterToMesh.cpp index d4151e7d33f7604cf5e0a3f41a92f36074d25d70..5e15dd24e7040b22e770c8ace5872b7e4dc780b2 100644 --- a/Tests/MeshLib/TestRasterToMesh.cpp +++ b/Tests/MeshLib/TestRasterToMesh.cpp @@ -8,33 +8,33 @@ * */ +#include <gtest/gtest.h> + #include <cstdio> #include <memory> -#include "gtest/gtest.h" - -#include "InfoLib/TestInfo.h" - #include "Applications/FileIO/AsciiRasterInterface.h" #include "GeoLib/Raster.h" +#include "InfoLib/TestInfo.h" +#include "MeshLib/IO/VtkIO/VtuInterface.h" #include "MeshLib/Mesh.h" #include "MeshLib/MeshGenerators/RasterToMesh.h" #include "MeshLib/MeshInformation.h" #include "MeshLib/Node.h" -#include "MeshLib/IO/VtkIO/VtuInterface.h" #ifdef OGS_BUILD_GUI +#include <vtkImageData.h> + #include "Applications/DataExplorer/VtkVis/VtkGeoImageSource.h" #include "Applications/DataExplorer/VtkVis/VtkRaster.h" - -#include <vtkImageData.h> #endif class RasterToMeshTest : public ::testing::Test { public: RasterToMeshTest() - : _file_name(TestInfoLib::TestInfo::data_path + "/MeshLib/testraster_selke.asc") + : _file_name(TestInfoLib::TestInfo::data_path + + "/MeshLib/testraster_selke.asc") { _raster.reset(FileIO::AsciiRasterInterface::readRaster(_file_name)); } diff --git a/Tests/MeshLib/TestRemove.cpp b/Tests/MeshLib/TestRemove.cpp index 832f734cef0e27c2c1afd4232db45da352d1c13d..89f82424efa273340e59053b243f133e7da71704 100644 --- a/Tests/MeshLib/TestRemove.cpp +++ b/Tests/MeshLib/TestRemove.cpp @@ -11,18 +11,17 @@ * http://www.opengeosys.org/project/license */ -#include <memory> +#include <gtest/gtest.h> -#include "gtest/gtest.h" +#include <memory> #include "MathLib/MathTools.h" - -#include "MeshLib/Mesh.h" -#include "MeshLib/Node.h" #include "MeshLib/Elements/Element.h" +#include "MeshLib/Mesh.h" #include "MeshLib/MeshEditing/RemoveMeshComponents.h" #include "MeshLib/MeshGenerators/MeshGenerator.h" #include "MeshLib/MeshQuality/MeshValidation.h" +#include "MeshLib/Node.h" TEST(MeshLib, RemoveNodes) { diff --git a/Tests/MeshLib/TestTetQualityCriteria.cpp b/Tests/MeshLib/TestTetQualityCriteria.cpp index ff40a9b4dfd17a0178d125be6115014808ea992a..34eed0b480d0594e24f58d1ec4eb0f2669178db6 100644 --- a/Tests/MeshLib/TestTetQualityCriteria.cpp +++ b/Tests/MeshLib/TestTetQualityCriteria.cpp @@ -7,6 +7,8 @@ * http://www.opengeosys.org/project/license */ +#include <gtest/gtest.h> + #include <Eigen/Eigen> #include <boost/math/constants/constants.hpp> #include <cmath> @@ -19,7 +21,6 @@ #include "MeshLib/MeshGenerators/MeshGenerator.h" #include "MeshLib/MeshQuality/ElementQualityInterface.h" #include "MeshLib/Node.h" -#include "gtest/gtest.h" class TetElementQuality : public ::testing::Test { @@ -106,19 +107,19 @@ TEST_F(TetElementQuality, EdgeRatio) auto const expected_value_tet4 = expected_value_tet1; auto const expected_value_tet5 = expected_value_tet0; - for (int i = 0; i<element_quality_vector.size(); i=i+6) + for (int i = 0; i < element_quality_vector.size(); i = i + 6) { ASSERT_NEAR(expected_value_tet0, element_quality_vector[i], 10 * std::numeric_limits<double>::epsilon()); - ASSERT_NEAR(expected_value_tet1, element_quality_vector[i+1], + ASSERT_NEAR(expected_value_tet1, element_quality_vector[i + 1], 10 * std::numeric_limits<double>::epsilon()); - ASSERT_NEAR(expected_value_tet2, element_quality_vector[i+2], + ASSERT_NEAR(expected_value_tet2, element_quality_vector[i + 2], 10 * std::numeric_limits<double>::epsilon()); - ASSERT_NEAR(expected_value_tet3, element_quality_vector[i+3], + ASSERT_NEAR(expected_value_tet3, element_quality_vector[i + 3], 10 * std::numeric_limits<double>::epsilon()); - ASSERT_NEAR(expected_value_tet4, element_quality_vector[i+4], + ASSERT_NEAR(expected_value_tet4, element_quality_vector[i + 4], 10 * std::numeric_limits<double>::epsilon()); - ASSERT_NEAR(expected_value_tet5, element_quality_vector[i+5], + ASSERT_NEAR(expected_value_tet5, element_quality_vector[i + 5], 10 * std::numeric_limits<double>::epsilon()); } } diff --git a/Tests/MeshLib/TestTriLineMesh.cpp b/Tests/MeshLib/TestTriLineMesh.cpp index 231d7e8f401d4198fb1c789ce74c820f969ffe42..776ec355a4ffa614781085272a5576c126dcec93 100644 --- a/Tests/MeshLib/TestTriLineMesh.cpp +++ b/Tests/MeshLib/TestTriLineMesh.cpp @@ -7,18 +7,18 @@ * http://www.opengeosys.org/project/license */ -#include "gtest/gtest.h" +#include <gtest/gtest.h> +#include "MeshLib/Elements/Line.h" +#include "MeshLib/Elements/Tri.h" #include "MeshLib/Mesh.h" #include "MeshLib/MeshEnums.h" -#include "MeshLib/Elements/Tri.h" -#include "MeshLib/Elements/Line.h" /// Creates a mesh consisiting of two triangles sharing a line element on their /// common edge. class MeshLibTriLineMesh : public ::testing::Test { - public: +public: MeshLibTriLineMesh() { nodes.push_back(new MeshLib::Node(0, 0, 0)); @@ -59,18 +59,14 @@ class MeshLibTriLineMesh : public ::testing::Test std::vector<MeshLib::Node*> nodes; std::vector<MeshLib::Element*> elements; - public: +public: // Helper functions to access elements and nodes. - - bool - isConnectedToNode(std::size_t const n, std::size_t const e) const + bool isConnectedToNode(std::size_t const n, std::size_t const e) const { - return std::find( - nodes[n]->getElements().cbegin(), - nodes[n]->getElements().cend(), - elements[e]) - != nodes[n]->getElements().cend(); + return std::find(nodes[n]->getElements().cbegin(), + nodes[n]->getElements().cend(), + elements[e]) != nodes[n]->getElements().cend(); } }; diff --git a/Tests/MeshLib/TestTriQualityCriteria.cpp b/Tests/MeshLib/TestTriQualityCriteria.cpp index b61cad6708fdf0512e8a485380ae0252402088e7..965825746e7bfefa875d62d9a02277ffa80fb9b5 100644 --- a/Tests/MeshLib/TestTriQualityCriteria.cpp +++ b/Tests/MeshLib/TestTriQualityCriteria.cpp @@ -7,6 +7,8 @@ * http://www.opengeosys.org/project/license */ +#include <gtest/gtest.h> + #include <boost/math/constants/constants.hpp> #include <cmath> #include <memory> @@ -18,7 +20,6 @@ #include "MeshLib/MeshGenerators/MeshGenerator.h" #include "MeshLib/MeshQuality/ElementQualityInterface.h" #include "MeshLib/Node.h" -#include "gtest/gtest.h" class TriElementQuality : public ::testing::Test { @@ -92,7 +93,7 @@ TEST_F(TriElementQuality, EdgeRatio) std::minmax_element(n_subdivisions.begin(), n_subdivisions.end()); auto const expected_value = double(*min_max.first) / std::sqrt(*min_max.first * *min_max.first + - *min_max.second * *min_max.second); + *min_max.second * *min_max.second); for (auto const element_quality : element_quality_vector) { ASSERT_NEAR(expected_value, element_quality, diff --git a/Tests/MeshLib/TestUniqueMeshId.cpp b/Tests/MeshLib/TestUniqueMeshId.cpp index 38e696a38efcf646eb78f608ddd8139b8a90b507..ca5caf40af26e1bcfdde76cbdc317a025d1eb5ba 100644 --- a/Tests/MeshLib/TestUniqueMeshId.cpp +++ b/Tests/MeshLib/TestUniqueMeshId.cpp @@ -7,7 +7,7 @@ * http://www.opengeosys.org/project/license */ -#include "gtest/gtest.h" +#include <gtest/gtest.h> #include "MeshLib/Mesh.h" @@ -40,6 +40,4 @@ TEST(MeshLib, UniqueMeshId) // Copy mesh keeps also increments the counter. Mesh m4 = m0; ASSERT_EQ(counter_value + std::size_t(4), m4.getID()); - } - diff --git a/Tests/MeshLib/TestVtkMappedMeshSource.cpp b/Tests/MeshLib/TestVtkMappedMeshSource.cpp index ecb3a4e3f56f56365ed949c39158bc5e4b5e470c..ea26874f3df812048e89f6d418f508f9fce2fc76 100644 --- a/Tests/MeshLib/TestVtkMappedMeshSource.cpp +++ b/Tests/MeshLib/TestVtkMappedMeshSource.cpp @@ -12,6 +12,7 @@ * */ +#include <gtest/gtest.h> #include <vtkCellData.h> #include <vtkNew.h> #include <vtkPointData.h> @@ -32,13 +33,12 @@ #include "MeshLib/MeshGenerators/VtkMeshConverter.h" #include "MeshLib/Vtk/VtkMappedMeshSource.h" #include "filesystem.h" -#include "gtest/gtest.h" // Creates a mesh with different types of data (double, int, etc.) and point, // cell, or integration point properties. class InSituMesh : public ::testing::Test { - public: +public: InSituMesh() { mesh = MeshLib::MeshGenerator::generateRegularHexMesh( @@ -66,8 +66,9 @@ class InSituMesh : public ::testing::Test mesh->getProperties().createNewPropertyVector<double>( field_prop_name, MeshLib::MeshItemType::IntegrationPoint); field_double_properties->resize(mesh->getNumberOfElements() * 2); - std::iota( - field_double_properties->begin(), field_double_properties->end(), 1); + std::iota(field_double_properties->begin(), + field_double_properties->end(), + 1); std::string const point_int_prop_name("PointIntProperty"); auto* const point_int_properties = @@ -89,7 +90,8 @@ class InSituMesh : public ::testing::Test mesh->getProperties().createNewPropertyVector<int>( field_int_prop_name, MeshLib::MeshItemType::IntegrationPoint); field_int_properties->resize(mesh->getNumberOfElements() * 2); - std::iota(field_int_properties->begin(), field_int_properties->end(), 1); + std::iota( + field_int_properties->begin(), field_int_properties->end(), 1); std::string const point_unsigned_prop_name("PointUnsignedProperty"); auto point_unsigned_properties = @@ -112,7 +114,8 @@ class InSituMesh : public ::testing::Test std::string const field_unsigned_prop_name("FieldUnsignedProperty"); auto field_unsigned_properties = mesh->getProperties().createNewPropertyVector<unsigned>( - field_unsigned_prop_name, MeshLib::MeshItemType::IntegrationPoint); + field_unsigned_prop_name, + MeshLib::MeshItemType::IntegrationPoint); field_unsigned_properties->resize(mesh->getNumberOfElements() * 2); std::iota(field_unsigned_properties->begin(), field_unsigned_properties->end(), @@ -137,7 +140,8 @@ class InSituMesh : public ::testing::Test TEST_F(InSituMesh, Construction) { ASSERT_TRUE(mesh != nullptr); - ASSERT_EQ((subdivisions+1)*(subdivisions+1)*(subdivisions+1), mesh->getNumberOfNodes()); + ASSERT_EQ((subdivisions + 1) * (subdivisions + 1) * (subdivisions + 1), + mesh->getNumberOfNodes()); } // Writes the mesh into a vtk file, reads the file back and converts it into a @@ -161,25 +165,30 @@ TEST_F(InSituMesh, DISABLED_MappedMeshSourceRoundtrip) vtkUnstructuredGrid* output = vtkSource->GetOutput(); // Point and cell numbers - ASSERT_EQ((subdivisions+1)*(subdivisions+1)*(subdivisions+1), output->GetNumberOfPoints()); - ASSERT_EQ(subdivisions*subdivisions*subdivisions, output->GetNumberOfCells()); + ASSERT_EQ((subdivisions + 1) * (subdivisions + 1) * (subdivisions + 1), + output->GetNumberOfPoints()); + ASSERT_EQ(subdivisions * subdivisions * subdivisions, + output->GetNumberOfCells()); // Point data arrays - vtkDataArray* pointDoubleArray = output->GetPointData()->GetScalars("PointDoubleProperty"); + vtkDataArray* pointDoubleArray = + output->GetPointData()->GetScalars("PointDoubleProperty"); ASSERT_EQ(pointDoubleArray->GetSize(), mesh->getNumberOfNodes()); ASSERT_EQ(pointDoubleArray->GetComponent(0, 0), 1.0); double* range = pointDoubleArray->GetRange(0); ASSERT_EQ(range[0], 1.0); ASSERT_EQ(range[1], 1.0 + mesh->getNumberOfNodes() - 1.0); - vtkDataArray* pointIntArray = output->GetPointData()->GetScalars("PointIntProperty"); + vtkDataArray* pointIntArray = + output->GetPointData()->GetScalars("PointIntProperty"); ASSERT_EQ(pointIntArray->GetSize(), mesh->getNumberOfNodes()); ASSERT_EQ(pointIntArray->GetComponent(0, 0), 1.0); range = pointIntArray->GetRange(0); ASSERT_EQ(range[0], 1.0); ASSERT_EQ(range[1], 1 + mesh->getNumberOfNodes() - 1); - vtkDataArray* pointUnsignedArray = output->GetPointData()->GetScalars("PointUnsignedProperty"); + vtkDataArray* pointUnsignedArray = + output->GetPointData()->GetScalars("PointUnsignedProperty"); ASSERT_EQ(pointUnsignedArray->GetSize(), mesh->getNumberOfNodes()); ASSERT_EQ(pointUnsignedArray->GetComponent(0, 0), 1.0); range = pointUnsignedArray->GetRange(0); @@ -187,21 +196,24 @@ TEST_F(InSituMesh, DISABLED_MappedMeshSourceRoundtrip) ASSERT_EQ(range[1], 1 + mesh->getNumberOfNodes() - 1); // Cell data arrays - vtkDataArray* cellDoubleArray = output->GetCellData()->GetScalars("CellDoubleProperty"); + vtkDataArray* cellDoubleArray = + output->GetCellData()->GetScalars("CellDoubleProperty"); ASSERT_EQ(cellDoubleArray->GetSize(), mesh->getNumberOfElements()); ASSERT_EQ(cellDoubleArray->GetComponent(0, 0), 1.0); range = cellDoubleArray->GetRange(0); ASSERT_EQ(range[0], 1.0); ASSERT_EQ(range[1], 1.0 + mesh->getNumberOfElements() - 1.0); - vtkDataArray* cellIntArray = output->GetCellData()->GetScalars("CellIntProperty"); + vtkDataArray* cellIntArray = + output->GetCellData()->GetScalars("CellIntProperty"); ASSERT_EQ(cellIntArray->GetSize(), mesh->getNumberOfElements()); ASSERT_EQ(cellIntArray->GetComponent(0, 0), 1.0); range = cellIntArray->GetRange(0); ASSERT_EQ(range[0], 1.0); ASSERT_EQ(range[1], 1 + mesh->getNumberOfElements() - 1); - vtkDataArray* cellUnsignedArray = output->GetCellData()->GetScalars("CellUnsignedProperty"); + vtkDataArray* cellUnsignedArray = + output->GetCellData()->GetScalars("CellUnsignedProperty"); ASSERT_EQ(cellUnsignedArray->GetSize(), mesh->getNumberOfElements()); ASSERT_EQ(cellUnsignedArray->GetComponent(0, 0), 1.0); range = cellUnsignedArray->GetRange(0); @@ -215,7 +227,7 @@ TEST_F(InSituMesh, DISABLED_MappedMeshSourceRoundtrip) ASSERT_EQ(fieldDoubleArray->GetComponent(0, 0), 1.0); range = fieldDoubleArray->GetRange(0); ASSERT_EQ(range[0], 1.0); - ASSERT_EQ(range[1], mesh->getNumberOfElements() * 2); + ASSERT_EQ(range[1], mesh->getNumberOfElements() * 2); vtkDataArray* fieldIntArray = vtkDataArray::SafeDownCast( output->GetFieldData()->GetAbstractArray("FieldIntProperty")); @@ -233,11 +245,12 @@ TEST_F(InSituMesh, DISABLED_MappedMeshSourceRoundtrip) ASSERT_EQ(range[0], 1.0); ASSERT_EQ(range[1], mesh->getNumberOfElements() * 2); - // -- Write VTK mesh to file (in all combinations of binary, appended and compressed) + // -- Write VTK mesh to file (in all combinations of binary, appended and + // compressed) // TODO: atm vtkXMLWriter::Ascii fails - for(int dataMode : { vtkXMLWriter::Appended, vtkXMLWriter::Binary }) + for (int dataMode : {vtkXMLWriter::Appended, vtkXMLWriter::Binary}) { - for(bool compressed : { true, false }) + for (bool compressed : {true, false}) { if (dataMode == vtkXMLWriter::Ascii && compressed) { @@ -251,23 +264,37 @@ TEST_F(InSituMesh, DISABLED_MappedMeshSourceRoundtrip) vtkSmartPointer<vtkXMLUnstructuredGridReader>::New(); reader->SetFileName(test_data_file.c_str()); reader->Update(); - vtkUnstructuredGrid *vtkMesh = reader->GetOutput(); + vtkUnstructuredGrid* vtkMesh = reader->GetOutput(); // Both VTK meshes should be identical - ASSERT_EQ(vtkMesh->GetNumberOfPoints(), output->GetNumberOfPoints()); + ASSERT_EQ(vtkMesh->GetNumberOfPoints(), + output->GetNumberOfPoints()); ASSERT_EQ(vtkMesh->GetNumberOfCells(), output->GetNumberOfCells()); - ASSERT_EQ(vtkMesh->GetFieldData()->GetNumberOfArrays(), output->GetFieldData()->GetNumberOfArrays()); - ASSERT_EQ(vtkMesh->GetPointData()->GetScalars("PointDoubleProperty")->GetNumberOfTuples(), - pointDoubleArray->GetNumberOfTuples()); - ASSERT_EQ(vtkMesh->GetPointData()->GetScalars("PointIntProperty")->GetNumberOfTuples(), - pointIntArray->GetNumberOfTuples()); - ASSERT_EQ(vtkMesh->GetPointData()->GetScalars("PointUnsignedProperty")->GetNumberOfTuples(), - pointUnsignedArray->GetNumberOfTuples()); - ASSERT_EQ(vtkMesh->GetCellData()->GetScalars("CellDoubleProperty")->GetNumberOfTuples(), - cellDoubleArray->GetNumberOfTuples()); - ASSERT_EQ(vtkMesh->GetCellData()->GetScalars("CellIntProperty")->GetNumberOfTuples(), - cellIntArray->GetNumberOfTuples()); - ASSERT_EQ(vtkMesh->GetCellData()->GetScalars("CellUnsignedProperty")->GetNumberOfTuples(), + ASSERT_EQ(vtkMesh->GetFieldData()->GetNumberOfArrays(), + output->GetFieldData()->GetNumberOfArrays()); + ASSERT_EQ(vtkMesh->GetPointData() + ->GetScalars("PointDoubleProperty") + ->GetNumberOfTuples(), + pointDoubleArray->GetNumberOfTuples()); + ASSERT_EQ(vtkMesh->GetPointData() + ->GetScalars("PointIntProperty") + ->GetNumberOfTuples(), + pointIntArray->GetNumberOfTuples()); + ASSERT_EQ(vtkMesh->GetPointData() + ->GetScalars("PointUnsignedProperty") + ->GetNumberOfTuples(), + pointUnsignedArray->GetNumberOfTuples()); + ASSERT_EQ(vtkMesh->GetCellData() + ->GetScalars("CellDoubleProperty") + ->GetNumberOfTuples(), + cellDoubleArray->GetNumberOfTuples()); + ASSERT_EQ(vtkMesh->GetCellData() + ->GetScalars("CellIntProperty") + ->GetNumberOfTuples(), + cellIntArray->GetNumberOfTuples()); + ASSERT_EQ(vtkMesh->GetCellData() + ->GetScalars("CellUnsignedProperty") + ->GetNumberOfTuples(), cellUnsignedArray->GetNumberOfTuples()); auto get_field_data = @@ -287,35 +314,42 @@ TEST_F(InSituMesh, DISABLED_MappedMeshSourceRoundtrip) fieldUnsignedArray->GetNumberOfTuples()); // Both OGS meshes should be identical - auto newMesh = std::unique_ptr<MeshLib::Mesh>{MeshLib::VtkMeshConverter::convertUnstructuredGrid(vtkMesh)}; + auto newMesh = std::unique_ptr<MeshLib::Mesh>{ + MeshLib::VtkMeshConverter::convertUnstructuredGrid(vtkMesh)}; ASSERT_EQ(mesh->getNumberOfNodes(), newMesh->getNumberOfNodes()); - ASSERT_EQ(mesh->getNumberOfElements(), newMesh->getNumberOfElements()); + ASSERT_EQ(mesh->getNumberOfElements(), + newMesh->getNumberOfElements()); // Both properties should be identical auto meshProperties = mesh->getProperties(); auto newMeshProperties = newMesh->getProperties(); - ASSERT_EQ(newMeshProperties.hasPropertyVector("PointDoubleProperty"), + ASSERT_EQ( + newMeshProperties.hasPropertyVector("PointDoubleProperty"), meshProperties.hasPropertyVector("PointDoubleProperty")); ASSERT_EQ(newMeshProperties.hasPropertyVector("PointIntProperty"), meshProperties.hasPropertyVector("PointIntProperty")); - ASSERT_EQ(newMeshProperties.hasPropertyVector("PointUnsignedProperty"), + ASSERT_EQ( + newMeshProperties.hasPropertyVector("PointUnsignedProperty"), meshProperties.hasPropertyVector("PointUnsignedProperty")); ASSERT_EQ(newMeshProperties.hasPropertyVector("CellDoubleProperty"), - meshProperties.hasPropertyVector("CellDoubleProperty")); + meshProperties.hasPropertyVector("CellDoubleProperty")); ASSERT_EQ(newMeshProperties.hasPropertyVector("CellIntProperty"), - meshProperties.hasPropertyVector("CellIntProperty")); - ASSERT_EQ(newMeshProperties.hasPropertyVector("CellUnsignedProperty"), + meshProperties.hasPropertyVector("CellIntProperty")); + ASSERT_EQ( + newMeshProperties.hasPropertyVector("CellUnsignedProperty"), meshProperties.hasPropertyVector("CellUnsignedProperty")); - ASSERT_EQ(newMeshProperties.hasPropertyVector("FieldDoubleProperty"), + ASSERT_EQ( + newMeshProperties.hasPropertyVector("FieldDoubleProperty"), meshProperties.hasPropertyVector("FieldDoubleProperty")); ASSERT_EQ(newMeshProperties.hasPropertyVector("FieldIntProperty"), - meshProperties.hasPropertyVector("FieldIntProperty")); - ASSERT_EQ(newMeshProperties.hasPropertyVector("FieldUnsignedProperty"), + meshProperties.hasPropertyVector("FieldIntProperty")); + ASSERT_EQ( + newMeshProperties.hasPropertyVector("FieldUnsignedProperty"), meshProperties.hasPropertyVector("FieldUnsignedProperty")); ASSERT_EQ(newMeshProperties.hasPropertyVector("MaterialIDs"), - meshProperties.hasPropertyVector("MaterialIDs")); + meshProperties.hasPropertyVector("MaterialIDs")); // Check some properties on equality auto const* const doubleProps = @@ -348,7 +382,7 @@ TEST_F(InSituMesh, DISABLED_MappedMeshSourceRoundtrip) ASSERT_EQ((*newUnsignedIds)[i], (*unsignedProps)[i]); } - { // Field data + { // Field data auto p = meshProperties.getPropertyVector<int>("FieldIntProperty"); auto new_p = newMeshProperties.getPropertyVector<int>( diff --git a/Tests/MeshLib/TestVtkMappedPropertyVector.cpp b/Tests/MeshLib/TestVtkMappedPropertyVector.cpp index 8bd1772d37f862d606b125bad800593561bd1712..2622ff6fe79d255259e5751936b48ed8ef313f37 100644 --- a/Tests/MeshLib/TestVtkMappedPropertyVector.cpp +++ b/Tests/MeshLib/TestVtkMappedPropertyVector.cpp @@ -11,15 +11,14 @@ * http://www.opengeosys.org/project/license * */ -#include <numeric> - +#include <gtest/gtest.h> #include <vtkDoubleArray.h> #include <vtkIntArray.h> #include <vtkNew.h> -#include <vtkUnstructuredGrid.h> #include <vtkUnsignedIntArray.h> +#include <vtkUnstructuredGrid.h> -#include "gtest/gtest.h" +#include <numeric> #include "MeshLib/Mesh.h" #include "MeshLib/MeshGenerators/MeshGenerator.h" @@ -30,10 +29,11 @@ TEST(MeshLibMappedPropertyVector, Double) const std::size_t mesh_size = 5; const double length = 1.0; - MeshLib::Mesh* mesh = MeshLib::MeshGenerator::generateRegularHexMesh(length, mesh_size); + MeshLib::Mesh* mesh = + MeshLib::MeshGenerator::generateRegularHexMesh(length, mesh_size); ASSERT_TRUE(mesh != nullptr); - const std::size_t number_of_tuples(mesh_size*mesh_size*mesh_size); + const std::size_t number_of_tuples(mesh_size * mesh_size * mesh_size); std::string const prop_name("TestProperty"); auto* const double_properties = @@ -45,7 +45,7 @@ TEST(MeshLibMappedPropertyVector, Double) vtkNew<vtkDoubleArray> dataArray; dataArray->SetNumberOfComponents(1); dataArray->SetArray(double_properties->data(), - static_cast<vtkIdType>(double_properties->size()), 1); + static_cast<vtkIdType>(double_properties->size()), 1); ASSERT_EQ(dataArray->GetNumberOfComponents(), 1); ASSERT_EQ(dataArray->GetNumberOfTuples(), number_of_tuples); @@ -64,10 +64,11 @@ TEST(MeshLibMappedPropertyVector, Int) const std::size_t mesh_size = 5; const double length = 1.0; - MeshLib::Mesh* mesh = MeshLib::MeshGenerator::generateRegularHexMesh(length, mesh_size); + MeshLib::Mesh* mesh = + MeshLib::MeshGenerator::generateRegularHexMesh(length, mesh_size); ASSERT_TRUE(mesh != nullptr); - const std::size_t number_of_tuples(mesh_size*mesh_size*mesh_size); + const std::size_t number_of_tuples(mesh_size * mesh_size * mesh_size); std::string const prop_name("TestProperty"); auto* const properties = mesh->getProperties().createNewPropertyVector<int>( @@ -78,7 +79,7 @@ TEST(MeshLibMappedPropertyVector, Int) vtkNew<vtkIntArray> dataArray; dataArray->SetNumberOfComponents(1); dataArray->SetArray(properties->data(), - static_cast<vtkIdType>(properties->size()), 1); + static_cast<vtkIdType>(properties->size()), 1); ASSERT_EQ(dataArray->GetNumberOfComponents(), 1); ASSERT_EQ(dataArray->GetNumberOfTuples(), number_of_tuples); @@ -86,7 +87,8 @@ TEST(MeshLibMappedPropertyVector, Int) ASSERT_EQ(dataArray->GetValue(0), -5); double* range = dataArray->GetRange(0); ASSERT_EQ(-5.0, range[0]); - ASSERT_EQ(-5.0 + static_cast<double>(mesh->getNumberOfElements()) - 1.0, range[1]); + ASSERT_EQ(-5.0 + static_cast<double>(mesh->getNumberOfElements()) - 1.0, + range[1]); delete mesh; } @@ -97,10 +99,11 @@ TEST(MeshLibMappedPropertyVector, Unsigned) const std::size_t mesh_size = 5; const double length = 1.0; - MeshLib::Mesh* mesh = MeshLib::MeshGenerator::generateRegularHexMesh(length, mesh_size); + MeshLib::Mesh* mesh = + MeshLib::MeshGenerator::generateRegularHexMesh(length, mesh_size); ASSERT_TRUE(mesh != nullptr); - const std::size_t number_of_tuples(mesh_size*mesh_size*mesh_size); + const std::size_t number_of_tuples(mesh_size * mesh_size * mesh_size); std::string const prop_name("TestProperty"); auto* const properties = @@ -112,7 +115,7 @@ TEST(MeshLibMappedPropertyVector, Unsigned) vtkNew<vtkUnsignedIntArray> dataArray; dataArray->SetNumberOfComponents(1); dataArray->SetArray(properties->data(), - static_cast<vtkIdType>(properties->size()), 1); + static_cast<vtkIdType>(properties->size()), 1); ASSERT_EQ(dataArray->GetNumberOfComponents(), 1); ASSERT_EQ(dataArray->GetNumberOfTuples(), number_of_tuples); diff --git a/Tests/MeshLib/TestVtkMeshConverter.cpp b/Tests/MeshLib/TestVtkMeshConverter.cpp index b79f06e5036e116a045a5d85c2be96c10ab86640..2a6986f1cf727dc582513eac1114018b462b1485 100644 --- a/Tests/MeshLib/TestVtkMeshConverter.cpp +++ b/Tests/MeshLib/TestVtkMeshConverter.cpp @@ -7,10 +7,7 @@ * http://www.opengeosys.org/project/license */ -#include <memory> - -#include "gtest/gtest.h" - +#include <gtest/gtest.h> #include <vtkCellArray.h> #include <vtkCellData.h> #include <vtkDoubleArray.h> @@ -20,6 +17,8 @@ #include <vtkUnsignedIntArray.h> #include <vtkUnstructuredGrid.h> +#include <memory> + #include "MeshLib/Elements/Element.h" #include "MeshLib/Mesh.h" #include "MeshLib/MeshGenerators/VtkMeshConverter.h" @@ -28,8 +27,7 @@ class TestVtkMeshConverter : public ::testing::Test { public: - TestVtkMeshConverter() - : vtu(nullptr) + TestVtkMeshConverter() : vtu(nullptr) { // Points and cells auto points = vtkSmartPointer<vtkPoints>::New(); diff --git a/Tests/MeshLib/TestVtkMeshNodalCoordinatesTemplate.cpp b/Tests/MeshLib/TestVtkMeshNodalCoordinatesTemplate.cpp index c5f83c2a9cb75ec69fd448cdeda4dd73450ce2a9..bf4455ccae862e9ba0a3eba4267d40f7c7cd5cb7 100644 --- a/Tests/MeshLib/TestVtkMeshNodalCoordinatesTemplate.cpp +++ b/Tests/MeshLib/TestVtkMeshNodalCoordinatesTemplate.cpp @@ -11,11 +11,10 @@ * http://www.opengeosys.org/project/license * */ +#include <gtest/gtest.h> #include <vtkNew.h> #include <vtkUnstructuredGrid.h> -#include "gtest/gtest.h" - #include "MeshLib/Mesh.h" #include "MeshLib/MeshGenerators/MeshGenerator.h" #include "MeshLib/Vtk/VtkMeshNodalCoordinatesTemplate.h" @@ -26,14 +25,15 @@ TEST(MeshLibdalCoordinates, Init) const double length = 10.0; const double dx = length / subdivisions; - MeshLib::Mesh* mesh = MeshLib::MeshGenerator::generateRegularQuadMesh(length, subdivisions); + MeshLib::Mesh* mesh = + MeshLib::MeshGenerator::generateRegularQuadMesh(length, subdivisions); - vtkNew<MeshLib::VtkMeshNodalCoordinatesTemplate<double> > nodeCoords; + vtkNew<MeshLib::VtkMeshNodalCoordinatesTemplate<double>> nodeCoords; nodeCoords->SetNodes(mesh->getNodes()); - //nodeCoords->PrintSelf(std::cout, vtkIndent()); + // nodeCoords->PrintSelf(std::cout, vtkIndent()); ASSERT_EQ(nodeCoords->GetNumberOfComponents(), 3); - const std::size_t numTuples = (subdivisions+1)*(subdivisions+1); + const std::size_t numTuples = (subdivisions + 1) * (subdivisions + 1); ASSERT_EQ(nodeCoords->GetNumberOfTuples(), numTuples); // First point @@ -42,9 +42,12 @@ TEST(MeshLibdalCoordinates, Init) ASSERT_EQ(nodeCoords->GetValueReference(2), 0.0); // First second - ASSERT_NEAR(nodeCoords->GetValueReference(3), dx, std::numeric_limits<double>::epsilon()); - ASSERT_NEAR(nodeCoords->GetValueReference(4), 0.0, std::numeric_limits<double>::epsilon()); - ASSERT_NEAR(nodeCoords->GetValueReference(5), 0.0, std::numeric_limits<double>::epsilon()); + ASSERT_NEAR(nodeCoords->GetValueReference(3), dx, + std::numeric_limits<double>::epsilon()); + ASSERT_NEAR(nodeCoords->GetValueReference(4), 0.0, + std::numeric_limits<double>::epsilon()); + ASSERT_NEAR(nodeCoords->GetValueReference(5), 0.0, + std::numeric_limits<double>::epsilon()); double* coords = nodeCoords->GetTuple(1); ASSERT_NEAR(coords[0], dx, std::numeric_limits<double>::epsilon()); diff --git a/Tests/NumLib/LocalToGlobalIndexMap.cpp b/Tests/NumLib/LocalToGlobalIndexMap.cpp index d5d8c121fe4098b03833f42ffe313c5af43616ce..8d6528da1576950e22b56ae99bbd5d3452b8c5e2 100644 --- a/Tests/NumLib/LocalToGlobalIndexMap.cpp +++ b/Tests/NumLib/LocalToGlobalIndexMap.cpp @@ -7,21 +7,20 @@ * */ -#include <memory> -#include <vector> +#include "NumLib/DOF/LocalToGlobalIndexMap.h" #include <gtest/gtest.h> -#include "NumLib/DOF/LocalToGlobalIndexMap.h" -#include "MeshLib/MeshGenerators/MeshGenerator.h" +#include <memory> +#include <vector> #include "MeshLib/Mesh.h" +#include "MeshLib/MeshGenerators/MeshGenerator.h" #include "MeshLib/MeshSearch/NodeSearch.h" #include "MeshLib/MeshSubset.h" class NumLibLocalToGlobalIndexMapTest : public ::testing::Test { - public: NumLibLocalToGlobalIndexMapTest() { @@ -43,7 +42,7 @@ protected: std::unique_ptr<MeshLib::Mesh const> mesh; std::unique_ptr<MeshLib::MeshSubset const> nodesSubset; - //data component 0 and 1 are assigned to all nodes in the mesh + // data component 0 and 1 are assigned to all nodes in the mesh static int const comp0_id = 0; static int const comp1_id = 1; std::vector<MeshLib::MeshSubset> components; @@ -66,7 +65,8 @@ TEST_F(NumLibLocalToGlobalIndexMapTest, DISABLED_NumberOfRowsByComponent) // There must be as many rows as nodes in the input times the number of // components. - ASSERT_EQ(mesh->getNumberOfNodes() * components_size, dof_map->dofSizeWithGhosts()); + ASSERT_EQ(mesh->getNumberOfNodes() * components_size, + dof_map->dofSizeWithGhosts()); } #ifndef USE_PETSC @@ -84,7 +84,8 @@ TEST_F(NumLibLocalToGlobalIndexMapTest, DISABLED_NumberOfRowsByLocation) // There must be as many rows as nodes in the input times the number of // components. - ASSERT_EQ(mesh->getNumberOfNodes() * components_size, dof_map->dofSizeWithGhosts()); + ASSERT_EQ(mesh->getNumberOfNodes() * components_size, + dof_map->dofSizeWithGhosts()); } #ifndef USE_PETSC @@ -97,7 +98,7 @@ TEST_F(NumLibLocalToGlobalIndexMapTest, DISABLED_SubsetByComponent) std::move(components), NumLib::ComponentOrder::BY_COMPONENT); // Select some elements from the full mesh. - std::array<std::size_t, 3> const ids = {{ 0, 5, 8 }}; + std::array<std::size_t, 3> const ids = {{0, 5, 8}}; std::vector<MeshLib::Element*> some_elements; for (std::size_t id : ids) { @@ -124,10 +125,12 @@ TEST_F(NumLibLocalToGlobalIndexMapTest, DISABLED_SubsetByComponent) #ifndef USE_PETSC TEST_F(NumLibLocalToGlobalIndexMapTest, MultipleVariablesMultipleComponents) #else -TEST_F(NumLibLocalToGlobalIndexMapTest, DISABLED_MultipleVariablesMultipleComponents) +TEST_F(NumLibLocalToGlobalIndexMapTest, + DISABLED_MultipleVariablesMultipleComponents) #endif { - // test 2 variables (1st variable with 1 component, 2nd variable with 2 components) + // test 2 variables (1st variable with 1 component, 2nd variable with 2 + // components) components.emplace_back(*nodesSubset); std::vector<int> vec_var_n_components{1, 2}; @@ -153,10 +156,12 @@ TEST_F(NumLibLocalToGlobalIndexMapTest, DISABLED_MultipleVariablesMultipleCompon #ifndef USE_PETSC TEST_F(NumLibLocalToGlobalIndexMapTest, MultipleVariablesMultipleComponents2) #else -TEST_F(NumLibLocalToGlobalIndexMapTest, DISABLED_MultipleVariablesMultipleComponents2) +TEST_F(NumLibLocalToGlobalIndexMapTest, + DISABLED_MultipleVariablesMultipleComponents2) #endif { - // test 2 variables (1st variable with 2 component, 2nd variable with 1 components) + // test 2 variables (1st variable with 2 component, 2nd variable with 1 + // components) components.emplace_back(*nodesSubset); std::vector<int> vec_var_n_components{2, 1}; @@ -179,24 +184,28 @@ TEST_F(NumLibLocalToGlobalIndexMapTest, DISABLED_MultipleVariablesMultipleCompon ASSERT_EQ(20, dof_map->getGlobalIndex(l_node0, 1, 0)); } - #ifndef USE_PETSC -TEST_F(NumLibLocalToGlobalIndexMapTest, MultipleVariablesMultipleComponentsHeterogeneousElements) +TEST_F(NumLibLocalToGlobalIndexMapTest, + MultipleVariablesMultipleComponentsHeterogeneousElements) #else -TEST_F(NumLibLocalToGlobalIndexMapTest, DISABLED_MultipleVariablesMultipleComponentsHeterogeneousElements) +TEST_F(NumLibLocalToGlobalIndexMapTest, + DISABLED_MultipleVariablesMultipleComponentsHeterogeneousElements) #endif { // test 2 variables // - 1st variable with 2 components for all nodes, elements // - 2nd variable with 1 component for nodes of element id 1 - std::vector<MeshLib::Node*> var2_nodes{const_cast<MeshLib::Node*>(mesh->getNode(1)), const_cast<MeshLib::Node*>(mesh->getNode(2))}; + std::vector<MeshLib::Node*> var2_nodes{ + const_cast<MeshLib::Node*>(mesh->getNode(1)), + const_cast<MeshLib::Node*>(mesh->getNode(2))}; MeshLib::MeshSubset var2_subset{*mesh, var2_nodes}; components.emplace_back(var2_subset); std::vector<int> vec_var_n_components{2, 1}; - std::vector<std::vector<MeshLib::Element*>const*> vec_var_elements; + std::vector<std::vector<MeshLib::Element*> const*> vec_var_elements; vec_var_elements.push_back(&mesh->getElements()); - std::vector<MeshLib::Element*> var2_elements{const_cast<MeshLib::Element*>(mesh->getElement(1))}; + std::vector<MeshLib::Element*> var2_elements{ + const_cast<MeshLib::Element*>(mesh->getElement(1))}; vec_var_elements.push_back(&var2_elements); dof_map = std::make_unique<NumLib::LocalToGlobalIndexMap>( @@ -215,7 +224,8 @@ TEST_F(NumLibLocalToGlobalIndexMapTest, DISABLED_MultipleVariablesMultipleCompon ASSERT_EQ(0, dof_map->getGlobalIndex(l_node0, 0, 0)); ASSERT_EQ(10, dof_map->getGlobalIndex(l_node0, 0, 1)); - ASSERT_EQ(std::numeric_limits<GlobalIndexType>::max(), dof_map->getGlobalIndex(l_node0, 1, 0)); + ASSERT_EQ(std::numeric_limits<GlobalIndexType>::max(), + dof_map->getGlobalIndex(l_node0, 1, 0)); MeshLib::Location l_node1(mesh->getID(), MeshLib::MeshItemType::Node, 1); ASSERT_EQ(1, dof_map->getGlobalIndex(l_node1, 0, 0)); @@ -231,24 +241,27 @@ TEST_F(NumLibLocalToGlobalIndexMapTest, DISABLED_MultipleVariablesMultipleCompon ASSERT_EQ(2u, ele1_c2_indices.rows.size()); } - #ifndef USE_PETSC -TEST_F(NumLibLocalToGlobalIndexMapTest, MultipleVariablesMultipleComponentsHeterogeneousWithinElement) +TEST_F(NumLibLocalToGlobalIndexMapTest, + MultipleVariablesMultipleComponentsHeterogeneousWithinElement) #else -TEST_F(NumLibLocalToGlobalIndexMapTest, DISABLED_MultipleVariablesMultipleComponentsHeterogeneousWithinElement) +TEST_F(NumLibLocalToGlobalIndexMapTest, + DISABLED_MultipleVariablesMultipleComponentsHeterogeneousWithinElement) #endif { // test 2 variables // - 1st variable with 2 components for all nodes, elements // - 2nd variable with 1 component for 1st node of element id 1 - std::vector<MeshLib::Node*> var2_nodes{const_cast<MeshLib::Node*>(mesh->getNode(1))}; + std::vector<MeshLib::Node*> var2_nodes{ + const_cast<MeshLib::Node*>(mesh->getNode(1))}; MeshLib::MeshSubset var2_subset = {*mesh, var2_nodes}; components.emplace_back(var2_subset); std::vector<int> vec_var_n_components{2, 1}; - std::vector<std::vector<MeshLib::Element*>const*> vec_var_elements; + std::vector<std::vector<MeshLib::Element*> const*> vec_var_elements; vec_var_elements.push_back(&mesh->getElements()); - std::vector<MeshLib::Element*> var2_elements{const_cast<MeshLib::Element*>(mesh->getElement(1))}; + std::vector<MeshLib::Element*> var2_elements{ + const_cast<MeshLib::Element*>(mesh->getElement(1))}; vec_var_elements.push_back(&var2_elements); dof_map = std::make_unique<NumLib::LocalToGlobalIndexMap>( @@ -267,7 +280,8 @@ TEST_F(NumLibLocalToGlobalIndexMapTest, DISABLED_MultipleVariablesMultipleCompon ASSERT_EQ(0, dof_map->getGlobalIndex(l_node0, 0, 0)); ASSERT_EQ(10, dof_map->getGlobalIndex(l_node0, 0, 1)); - ASSERT_EQ(std::numeric_limits<GlobalIndexType>::max(), dof_map->getGlobalIndex(l_node0, 1, 0)); + ASSERT_EQ(std::numeric_limits<GlobalIndexType>::max(), + dof_map->getGlobalIndex(l_node0, 1, 0)); MeshLib::Location l_node1(mesh->getID(), MeshLib::MeshItemType::Node, 1); ASSERT_EQ(1, dof_map->getGlobalIndex(l_node1, 0, 0)); diff --git a/Tests/NumLib/LocalToGlobalIndexMapMultiComponent.cpp b/Tests/NumLib/LocalToGlobalIndexMapMultiComponent.cpp index e43a30e787dfd6dc257852727ab9fc6734ed5e9f..7cfa268250df836357079d9ae82cea1aa84aaf6f 100644 --- a/Tests/NumLib/LocalToGlobalIndexMapMultiComponent.cpp +++ b/Tests/NumLib/LocalToGlobalIndexMapMultiComponent.cpp @@ -12,6 +12,8 @@ #include "GeoLib/GEOObjects.h" #include "GeoLib/Polyline.h" +#include "MeshGeoToolsLib/BoundaryElementsSearcher.h" +#include "MeshGeoToolsLib/MeshNodeSearcher.h" #include "MeshLib/Elements/Element.h" #include "MeshLib/Location.h" #include "MeshLib/Mesh.h" @@ -21,9 +23,6 @@ #include "MeshLib/MeshSubset.h" #include "NumLib/DOF/LocalToGlobalIndexMap.h" -#include "MeshGeoToolsLib/MeshNodeSearcher.h" -#include "MeshGeoToolsLib/BoundaryElementsSearcher.h" - namespace NL = NumLib; namespace MeL = MeshLib; namespace MGTL = MeshGeoToolsLib; @@ -34,7 +33,8 @@ public: static const std::size_t mesh_subdivs = 4; NumLibLocalToGlobalIndexMapMultiDOFTest() { - mesh.reset(MeL::MeshGenerator::generateRegularQuadMesh(2.0, mesh_subdivs)); + mesh.reset( + MeL::MeshGenerator::generateRegularQuadMesh(2.0, mesh_subdivs)); mesh_items_all_nodes = std::make_unique<MeL::MeshSubset>(*mesh, mesh->getNodes()); @@ -145,7 +145,6 @@ public: std::vector<MeshLib::Node*> nodes_subset; }; - struct ComputeGlobalIndexByComponent { std::size_t num_nodes; @@ -184,7 +183,7 @@ void NumLibLocalToGlobalIndexMapMultiDOFTest::test( ASSERT_EQ(dof_map_boundary->size(), boundary_mesh->getNumberOfElements()); // check mesh elements - for (unsigned e=0; e<dof_map->size(); ++e) + for (unsigned e = 0; e < dof_map->size(); ++e) { auto const element_nodes_size = mesh->getElement(e)->getNumberOfNodes(); auto const ptr_element_nodes = mesh->getElement(e)->getNodes(); @@ -204,7 +203,7 @@ void NumLibLocalToGlobalIndexMapMultiDOFTest::test( } // check boundary elements - for (unsigned e=0; e<dof_map_boundary->size(); ++e) + for (unsigned e = 0; e < dof_map_boundary->size(); ++e) { ASSERT_EQ(1, dof_map_boundary->getNumberOfGlobalComponents()); @@ -212,7 +211,9 @@ void NumLibLocalToGlobalIndexMapMultiDOFTest::test( { auto const& global_idcs = (*dof_map_boundary)(e, c).rows; - ASSERT_EQ(2, global_idcs.size()); // boundary of quad is line with two nodes + ASSERT_EQ( + 2, + global_idcs.size()); // boundary of quad is line with two nodes // e is the number of a boundary element (which is a line, so two // nodes) from 0 to something. e+n must be the node ids along the @@ -293,13 +294,14 @@ void NumLibLocalToGlobalIndexMapMultiDOFTest::test( } } -void assert_equal(NL::LocalToGlobalIndexMap const& dof1, NL::LocalToGlobalIndexMap const& dof2) +void assert_equal(NL::LocalToGlobalIndexMap const& dof1, + NL::LocalToGlobalIndexMap const& dof2) { ASSERT_EQ(dof1.size(), dof2.size()); ASSERT_EQ(dof1.getNumberOfGlobalComponents(), dof2.getNumberOfGlobalComponents()); - for (unsigned e=0; e<dof1.size(); ++e) + for (unsigned e = 0; e < dof1.size(); ++e) { for (int c = 0; c < dof1.getNumberOfGlobalComponents(); ++c) { @@ -334,7 +336,8 @@ TEST_F(NumLibLocalToGlobalIndexMapMultiDOFTest, DISABLED_Test1Comp) #ifndef USE_PETSC TEST_F(NumLibLocalToGlobalIndexMapMultiDOFTest, TestMultiCompByComponent) #else -TEST_F(NumLibLocalToGlobalIndexMapMultiDOFTest, DISABLED_TestMultiCompByComponent) +TEST_F(NumLibLocalToGlobalIndexMapMultiDOFTest, + DISABLED_TestMultiCompByComponent) #endif { int const num_components = 5; @@ -350,7 +353,8 @@ TEST_F(NumLibLocalToGlobalIndexMapMultiDOFTest, DISABLED_TestMultiCompByComponen #ifndef USE_PETSC TEST_F(NumLibLocalToGlobalIndexMapMultiDOFTest, TestMultiCompByLocation) #else -TEST_F(NumLibLocalToGlobalIndexMapMultiDOFTest, DISABLED_TestMultiCompByLocation) +TEST_F(NumLibLocalToGlobalIndexMapMultiDOFTest, + DISABLED_TestMultiCompByLocation) #endif { int const num_components = 5; diff --git a/Tests/NumLib/NewtonRaphson.cpp b/Tests/NumLib/NewtonRaphson.cpp index c1090d93948fbf6cf54549a1e842fd8b5ac1f780..967abc6898cfc60da198ef857b17227afad9852a 100644 --- a/Tests/NumLib/NewtonRaphson.cpp +++ b/Tests/NumLib/NewtonRaphson.cpp @@ -6,10 +6,11 @@ * http://www.opengeosys.org/project/license */ +#include "NumLib/NewtonRaphson.h" + #include <gtest/gtest.h> -#include <limits> -#include "NumLib/NewtonRaphson.h" +#include <limits> TEST(NumLibNewtonRaphson, Sqrt3) { static const int N = 1; // Problem's size. @@ -36,15 +37,18 @@ TEST(NumLibNewtonRaphson, Sqrt3) residual[0] = state * state - 3; }; - auto const update_solution = [&state]( - LocalResidualVector const& increment) { state += increment[0]; }; - - auto const newton_solver = NumLib::NewtonRaphson< - decltype(linear_solver), LocalJacobianMatrix, decltype(update_jacobian), - LocalResidualVector, decltype(update_residual), - decltype(update_solution)>(linear_solver, update_jacobian, - update_residual, update_solution, - {maximum_iterations, tolerance}); + auto const update_solution = + [&state](LocalResidualVector const& increment) { + state += increment[0]; + }; + + auto const newton_solver = + NumLib::NewtonRaphson<decltype(linear_solver), LocalJacobianMatrix, + decltype(update_jacobian), LocalResidualVector, + decltype(update_residual), + decltype(update_solution)>( + linear_solver, update_jacobian, update_residual, update_solution, + {maximum_iterations, tolerance}); auto const success_iterations = newton_solver.solve(jacobian); EXPECT_TRUE(static_cast<bool>(success_iterations)); diff --git a/Tests/NumLib/TestComponentNorms.cpp b/Tests/NumLib/TestComponentNorms.cpp index 396cdc7be73fa077fabaaeaeba76e3cbdd1451f5..ee4900c6cd8b0f2a7f058c0018acded1afdf1b9e 100644 --- a/Tests/NumLib/TestComponentNorms.cpp +++ b/Tests/NumLib/TestComponentNorms.cpp @@ -8,7 +8,9 @@ */ #include <gtest/gtest.h> + #include <limits> + #include "BaseLib/Logging.h" #ifdef USE_PETSC @@ -22,9 +24,9 @@ #else #include "MeshLib/MeshGenerators/MeshGenerator.h" #endif +#include "NumLib/DOF/DOFTableUtil.h" #include "NumLib/DOF/LocalToGlobalIndexMap.h" #include "NumLib/NumericsConfig.h" -#include "NumLib/DOF/DOFTableUtil.h" #include "Tests/VectorUtils.h" static std::vector<MeshLib::MeshSubset> createMeshSubsets( @@ -106,7 +108,8 @@ void do_test(unsigned const num_components, auto const total_norm = MathLib::LinAlg::norm(*x, norm_type); double compwise_total_norm = 0.0; - for (unsigned comp = 0; comp < num_components; ++comp) { + for (unsigned comp = 0; comp < num_components; ++comp) + { compwise_total_norm = accumulate_cb( compwise_total_norm, NumLib::norm(*x, comp, norm_type, dtd.dof_table, *dtd.mesh)); @@ -127,12 +130,14 @@ TEST(MPITest_NumLib, ComponentNormSingleComponent) auto const tolerance = 800 * std::numeric_limits<double>::epsilon(); using VNT = MathLib::VecNormType; - for (auto norm_type : {VNT::NORM1, VNT::NORM2, VNT::INFINITY_N}) { + for (auto norm_type : {VNT::NORM1, VNT::NORM2, VNT::INFINITY_N}) + { DBUG("norm type: {:s}.", MathLib::convertVecNormTypeToString(norm_type)); - do_test(num_components, norm_type, tolerance, - [](double /*n_total*/, double n) { return n; }, - [](double n_total) { return n_total; }); + do_test( + num_components, norm_type, tolerance, + [](double /*n_total*/, double n) { return n; }, + [](double n_total) { return n_total; }); } } @@ -147,9 +152,10 @@ TEST(MPITest_NumLib, ComponentNormMultiComponent1) auto const tolerance = num_components * 1700 * std::numeric_limits<double>::epsilon(); - do_test(num_components, norm_type, tolerance, - [](double n_total, double n) { return n_total + n; }, - [](double n_total) { return n_total; }); + do_test( + num_components, norm_type, tolerance, + [](double n_total, double n) { return n_total + n; }, + [](double n_total) { return n_total; }); } #ifndef USE_PETSC @@ -163,9 +169,10 @@ TEST(MPITest_NumLib, ComponentNormMultiComponent2) auto const tolerance = num_components * 40 * std::numeric_limits<double>::epsilon(); - do_test(num_components, norm_type, tolerance, - [](double n_total, double n) { return n_total + n*n; }, - [](double n_total) { return std::sqrt(n_total); }); + do_test( + num_components, norm_type, tolerance, + [](double n_total, double n) { return n_total + n * n; }, + [](double n_total) { return std::sqrt(n_total); }); } #ifndef USE_PETSC @@ -179,7 +186,8 @@ TEST(MPITest_NumLib, ComponentNormMultiComponentInfinity) auto const tolerance = num_components * 1 * std::numeric_limits<double>::epsilon(); - do_test(num_components, norm_type, tolerance, - [](double n_total, double n) { return std::max(n_total, n); }, - [](double n_total) { return n_total; }); + do_test( + num_components, norm_type, tolerance, + [](double n_total, double n) { return std::max(n_total, n); }, + [](double n_total) { return n_total; }); } diff --git a/Tests/NumLib/TestCoordinatesMapping.cpp b/Tests/NumLib/TestCoordinatesMapping.cpp index 663a6d455d36a131b796ed2df8107c70b0194416..d322439d05743777e586f99ed3c2a1a4ee05012c 100644 --- a/Tests/NumLib/TestCoordinatesMapping.cpp +++ b/Tests/NumLib/TestCoordinatesMapping.cpp @@ -9,22 +9,19 @@ #include <gtest/gtest.h> +#include <Eigen/Eigen> #include <algorithm> #include <limits> #include <vector> -#include <Eigen/Eigen> - -#include "NumLib/Fem/CoordinatesMapping/NaturalCoordinatesMapping.h" -#include "NumLib/Fem/CoordinatesMapping/ShapeMatrices.h" -#include "NumLib/Fem/ShapeMatrixPolicy.h" - #include "CoordinatesMappingTestData/TestHex8.h" #include "CoordinatesMappingTestData/TestLine2.h" #include "CoordinatesMappingTestData/TestLine3.h" #include "CoordinatesMappingTestData/TestQuad4.h" #include "CoordinatesMappingTestData/TestTri3.h" - +#include "NumLib/Fem/CoordinatesMapping/NaturalCoordinatesMapping.h" +#include "NumLib/Fem/CoordinatesMapping/ShapeMatrices.h" +#include "NumLib/Fem/ShapeMatrixPolicy.h" #include "Tests/TestTools.h" using namespace NumLib; @@ -35,7 +32,7 @@ namespace // Element types to be tested using TestTypes = ::testing::Types<TestLine2, TestLine3, TestTri3, TestQuad4, TestHex8>; -} +} // namespace template <class T_TEST> class NumLibFemNaturalCoordinatesMappingTest : public ::testing::Test, diff --git a/Tests/NumLib/TestFe.cpp b/Tests/NumLib/TestFe.cpp index 65b65c9dd23216fe3fe876a5d8848d79190785f1..7ef0ca7cd4537cce50d6f77494282cd3b1d57ebd 100644 --- a/Tests/NumLib/TestFe.cpp +++ b/Tests/NumLib/TestFe.cpp @@ -36,14 +36,15 @@ using namespace FeTestData; namespace { - // test cases -template <class TestFeType_, template <typename, unsigned> class ShapeMatrixPolicy_> +template <class TestFeType_, + template <typename, unsigned> class ShapeMatrixPolicy_> struct TestCase { using TestFeType = TestFeType_; static const unsigned GlobalDim = TestFeType::global_dim; - using ShapeMatrixTypes = ShapeMatrixPolicy_<typename TestFeType::ShapeFunction, GlobalDim>; + using ShapeMatrixTypes = + ShapeMatrixPolicy_<typename TestFeType::ShapeFunction, GlobalDim>; template <typename X> using ShapeMatrixPolicy = ShapeMatrixPolicy_<X, GlobalDim>; using ShapeFunction = typename TestFeType::ShapeFunction; @@ -74,68 +75,68 @@ using TestTypes = template <class T> class NumLibFemIsoTest : public ::testing::Test, public T::TestFeType { - public: - using ShapeMatrixTypes = typename T::ShapeMatrixTypes; - using ShapeFunction = typename T::ShapeFunction; - using TestFeType = typename T::TestFeType; - // Matrix types - using NodalMatrix = typename ShapeMatrixTypes::NodalMatrixType; - using NodalVector = typename ShapeMatrixTypes::NodalVectorType; - using DimNodalMatrix = typename ShapeMatrixTypes::DimNodalMatrixType; - using DimMatrix = typename ShapeMatrixTypes::DimMatrixType; - using GlobalDimMatrixType = typename ShapeMatrixTypes::GlobalDimMatrixType; - - // Finite element type - template <typename X> - using ShapeMatrixPolicy = typename T::template ShapeMatrixPolicy<X>; - using FeType = - typename TestFeType::template FeType<ShapeMatrixPolicy>::type; - - // Shape matrix data type - using ShapeMatricesType = typename ShapeMatrixTypes::ShapeMatrices; - using MeshElementType = typename TestFeType::MeshElementType; - - static const unsigned dim = TestFeType::dim; - static const unsigned e_nnodes = TestFeType::e_nnodes; - static const unsigned n_sample_pt_order2 = TestFeType::n_sample_pt_order2; - static const unsigned n_sample_pt_order3 = TestFeType::n_sample_pt_order3; - - using IntegrationMethod = typename NumLib::GaussLegendreIntegrationPolicy< - MeshElementType>::IntegrationMethod; - - public: - NumLibFemIsoTest() - : D(dim, dim), - expectedM(e_nnodes, e_nnodes), - expectedK(e_nnodes, e_nnodes), - integration_method(2) - { - // create a mesh element used for testing - mesh_element = this->createMeshElement(); - - // set a conductivity tensor - setIdentityMatrix(dim, D); - D *= conductivity; - MeshLib::ElementCoordinatesMappingLocal ele_local_coord( - *mesh_element, - MeshLib::CoordinateSystem(*mesh_element).getDimension()); - auto R = ele_local_coord.getRotationMatrixToGlobal().topLeftCorner( - TestFeType::dim, TestFeType::global_dim); - globalD.noalias() = R.transpose() * (D * R); - - // set expected matrices - this->setExpectedMassMatrix(expectedM); - this->setExpectedLaplaceMatrix(conductivity, expectedK); - - // for destructor - vec_eles.push_back(mesh_element); - for (auto e : vec_eles) - { - for (unsigned i = 0; i < e->getNumberOfNodes(); i++) - { - vec_nodes.push_back(e->getNode(i)); - } - } +public: + using ShapeMatrixTypes = typename T::ShapeMatrixTypes; + using ShapeFunction = typename T::ShapeFunction; + using TestFeType = typename T::TestFeType; + // Matrix types + using NodalMatrix = typename ShapeMatrixTypes::NodalMatrixType; + using NodalVector = typename ShapeMatrixTypes::NodalVectorType; + using DimNodalMatrix = typename ShapeMatrixTypes::DimNodalMatrixType; + using DimMatrix = typename ShapeMatrixTypes::DimMatrixType; + using GlobalDimMatrixType = typename ShapeMatrixTypes::GlobalDimMatrixType; + + // Finite element type + template <typename X> + using ShapeMatrixPolicy = typename T::template ShapeMatrixPolicy<X>; + using FeType = + typename TestFeType::template FeType<ShapeMatrixPolicy>::type; + + // Shape matrix data type + using ShapeMatricesType = typename ShapeMatrixTypes::ShapeMatrices; + using MeshElementType = typename TestFeType::MeshElementType; + + static const unsigned dim = TestFeType::dim; + static const unsigned e_nnodes = TestFeType::e_nnodes; + static const unsigned n_sample_pt_order2 = TestFeType::n_sample_pt_order2; + static const unsigned n_sample_pt_order3 = TestFeType::n_sample_pt_order3; + + using IntegrationMethod = typename NumLib::GaussLegendreIntegrationPolicy< + MeshElementType>::IntegrationMethod; + +public: + NumLibFemIsoTest() + : D(dim, dim), + expectedM(e_nnodes, e_nnodes), + expectedK(e_nnodes, e_nnodes), + integration_method(2) + { + // create a mesh element used for testing + mesh_element = this->createMeshElement(); + + // set a conductivity tensor + setIdentityMatrix(dim, D); + D *= conductivity; + MeshLib::ElementCoordinatesMappingLocal ele_local_coord( + *mesh_element, + MeshLib::CoordinateSystem(*mesh_element).getDimension()); + auto R = ele_local_coord.getRotationMatrixToGlobal().topLeftCorner( + TestFeType::dim, TestFeType::global_dim); + globalD.noalias() = R.transpose() * (D * R); + + // set expected matrices + this->setExpectedMassMatrix(expectedM); + this->setExpectedLaplaceMatrix(conductivity, expectedK); + + // for destructor + vec_eles.push_back(mesh_element); + for (auto e : vec_eles) + { + for (unsigned i = 0; i < e->getNumberOfNodes(); i++) + { + vec_nodes.push_back(e->getNode(i)); + } + } } ~NumLibFemIsoTest() override @@ -150,7 +151,6 @@ class NumLibFemIsoTest : public ::testing::Test, public T::TestFeType } } - static const double conductivity; static const double eps; DimMatrix D; @@ -163,15 +163,16 @@ class NumLibFemIsoTest : public ::testing::Test, public T::TestFeType std::vector<const MeshElementType*> vec_eles; MeshElementType* mesh_element; - public: +public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW; -}; // NumLibFemIsoTest +}; // NumLibFemIsoTest template <class T> const double NumLibFemIsoTest<T>::conductivity = 1e-11; template <class T> -const double NumLibFemIsoTest<T>::eps = 2*std::numeric_limits<double>::epsilon(); +const double NumLibFemIsoTest<T>::eps = 2 * + std::numeric_limits<double>::epsilon(); template <class T> const unsigned NumLibFemIsoTest<T>::dim; @@ -202,12 +203,15 @@ TYPED_TEST(NumLibFemIsoTest, CheckMassMatrix) // evaluate a mass matrix M = int{ N^T D N }dA_e NodalMatrix M = NodalMatrix::Zero(this->e_nnodes, this->e_nnodes); - for (std::size_t i=0; i < this->integration_method.getNumberOfPoints(); i++) { + for (std::size_t i = 0; i < this->integration_method.getNumberOfPoints(); + i++) + { auto const& shape = shape_matrices[i]; auto wp = this->integration_method.getWeightedPoint(i); - M.noalias() += shape.N.transpose() * shape.N * shape.detJ * wp.getWeight(); + M.noalias() += + shape.N.transpose() * shape.N * shape.detJ * wp.getWeight(); } - //std::cout << "M=\n" << M; + // std::cout << "M=\n" << M; ASSERT_ARRAY_NEAR(this->expectedM.data(), M.data(), M.size(), this->eps); } @@ -226,12 +230,15 @@ TYPED_TEST(NumLibFemIsoTest, CheckLaplaceMatrix) // evaluate a Laplace matrix K = int{ dNdx^T D dNdx }dA_e NodalMatrix K = NodalMatrix::Zero(this->e_nnodes, this->e_nnodes); - for (std::size_t i=0; i < this->integration_method.getNumberOfPoints(); i++) { + for (std::size_t i = 0; i < this->integration_method.getNumberOfPoints(); + i++) + { auto const& shape = shape_matrices[i]; auto wp = this->integration_method.getWeightedPoint(i); - K.noalias() += shape.dNdx.transpose() * this->globalD * shape.dNdx * shape.detJ * wp.getWeight(); + K.noalias() += shape.dNdx.transpose() * this->globalD * shape.dNdx * + shape.detJ * wp.getWeight(); } - //std::cout << "K=\n" << K << std::endl; + // std::cout << "K=\n" << K << std::endl; ASSERT_ARRAY_NEAR(this->expectedK.data(), K.data(), K.size(), this->eps); } @@ -250,11 +257,15 @@ TYPED_TEST(NumLibFemIsoTest, CheckMassLaplaceMatrices) // evaluate both mass and laplace matrices at once NodalMatrix M = NodalMatrix::Zero(this->e_nnodes, this->e_nnodes); NodalMatrix K = NodalMatrix::Zero(this->e_nnodes, this->e_nnodes); - for (std::size_t i=0; i < this->integration_method.getNumberOfPoints(); i++) { + for (std::size_t i = 0; i < this->integration_method.getNumberOfPoints(); + i++) + { auto const& shape = shape_matrices[i]; auto wp = this->integration_method.getWeightedPoint(i); - M.noalias() += shape.N.transpose() * shape.N * shape.detJ * wp.getWeight(); - K.noalias() += shape.dNdx.transpose() * (this->globalD * shape.dNdx) * shape.detJ * wp.getWeight(); + M.noalias() += + shape.N.transpose() * shape.N * shape.detJ * wp.getWeight(); + K.noalias() += shape.dNdx.transpose() * (this->globalD * shape.dNdx) * + shape.detJ * wp.getWeight(); } ASSERT_ARRAY_NEAR(this->expectedM.data(), M.data(), M.size(), this->eps); @@ -307,4 +318,3 @@ TYPED_TEST(NumLibFemIsoTest, CheckGaussLegendreIntegrationLevel) ASSERT_ARRAY_NEAR(this->expectedM.data(), M.data(), M.size(), this->eps); } #endif - diff --git a/Tests/NumLib/TestFemIntegration.cpp b/Tests/NumLib/TestFemIntegration.cpp index 1b5fa55d4cf4fe5e00b9bdb72d78ba9187fe25b0..54e131f7ac99b7774917a08f4650052cdb89f33e 100644 --- a/Tests/NumLib/TestFemIntegration.cpp +++ b/Tests/NumLib/TestFemIntegration.cpp @@ -14,9 +14,8 @@ #include <limits> -#include "Tests/TestTools.h" - #include "NumLib/Fem/Integration/IntegrationGaussLegendreRegular.h" +#include "Tests/TestTools.h" using namespace NumLib; @@ -28,7 +27,7 @@ TEST(NumLib, FemIntegrationGaussLegendreRegular) // check position indices // dim = 1 { - std::size_t expected[1] = { 0u }; + std::size_t expected[1] = {0u}; ASSERT_ARRAY_EQ(expected, IntegrationGaussLegendreRegular<1>::getPositionIndices( integrationOrder, 0), @@ -41,7 +40,7 @@ TEST(NumLib, FemIntegrationGaussLegendreRegular) } // dim = 2 { - std::size_t expected[2] = { 0u, 0u }; + std::size_t expected[2] = {0u, 0u}; ASSERT_ARRAY_EQ(expected, IntegrationGaussLegendreRegular<2>::getPositionIndices( integrationOrder, 0), @@ -66,12 +65,15 @@ TEST(NumLib, FemIntegrationGaussLegendreRegular) } // dim = 3 { - std::size_t expected[3] = { 0u, 0u, 0u }; - for (std::size_t i(0); i <= 1; i++) { + std::size_t expected[3] = {0u, 0u, 0u}; + for (std::size_t i(0); i <= 1; i++) + { expected[0] = i; - for (std::size_t j(0); j <= 1; j++) { + for (std::size_t j(0); j <= 1; j++) + { expected[1] = j; - for (std::size_t k(0); k <= 1; k++) { + for (std::size_t k(0); k <= 1; k++) + { expected[2] = k; const std::size_t l(i * 4 + j * 2 + k); ASSERT_ARRAY_EQ( @@ -186,5 +188,3 @@ TEST(NumLib, FemIntegrationGaussLegendreRegular) ASSERT_EQ(2u, q3.getIntegrationOrder()); ASSERT_EQ(8u, q3.getNumberOfPoints()); } - - diff --git a/Tests/NumLib/TestFunctionInterpolation.cpp b/Tests/NumLib/TestFunctionInterpolation.cpp index 905bf63ebb05e56f916fbcc445141e2a4c8d85bd..f0917f38ecee7a066f8b15876d59d8d616591abf 100644 --- a/Tests/NumLib/TestFunctionInterpolation.cpp +++ b/Tests/NumLib/TestFunctionInterpolation.cpp @@ -11,16 +11,12 @@ #include <array> -#include "NumLib/Function/Interpolation.h" - +#include "MeshLib/Elements/Element.h" #include "NumLib/Fem/FiniteElement/TemplateIsoparametric.h" +#include "NumLib/Fem/Integration/GaussLegendreIntegrationPolicy.h" #include "NumLib/Fem/ShapeFunction/ShapeLine2.h" - #include "NumLib/Fem/ShapeMatrixPolicy.h" - -#include "MeshLib/Elements/Element.h" - -#include "NumLib/Fem/Integration/GaussLegendreIntegrationPolicy.h" +#include "NumLib/Function/Interpolation.h" TEST(NumLibFunctionInterpolationTest, TwoVariablesTwoNodes) { @@ -34,14 +30,13 @@ TEST(NumLibFunctionInterpolationTest, TwoVariablesTwoNodes) const std::array<double, 2> shape_matrix = {{0.25, 0.75}}; - NumLib::shapeFunctionInterpolate(nodal_values, shape_matrix, - variable1, variable2); + NumLib::shapeFunctionInterpolate(nodal_values, shape_matrix, variable1, + variable2); ASSERT_EQ(0.75, variable1); - ASSERT_EQ(0.5, variable2); + ASSERT_EQ(0.5, variable2); } - TEST(NumLibFunctionInterpolationTest, Linear1DElement) { // typedefs @@ -70,8 +65,8 @@ TEST(NumLibFunctionInterpolationTest, Linear1DElement) ShapeFunction::DIM, ShapeFunction::DIM, ShapeFunction::NPOINTS); finite_element.computeShapeFunctions( - integration_method.getWeightedPoint(0).getCoords(), - shape_matrix, ShapeFunction::DIM, false); + integration_method.getWeightedPoint(0).getCoords(), shape_matrix, + ShapeFunction::DIM, false); ASSERT_EQ(2, shape_matrix.N.size()); // actual test @@ -83,14 +78,12 @@ TEST(NumLibFunctionInterpolationTest, Linear1DElement) -1.0, 1.0 // for variable2 }}; - NumLib::shapeFunctionInterpolate(nodal_values, shape_matrix.N, - variable1, variable2); + NumLib::shapeFunctionInterpolate(nodal_values, shape_matrix.N, variable1, + variable2); const double n0 = shape_matrix.N[0]; const double n1 = shape_matrix.N[1]; - ASSERT_EQ( 0.0 * n0 + 1.0 * n1, variable1); + ASSERT_EQ(0.0 * n0 + 1.0 * n1, variable1); ASSERT_EQ(-1.0 * n0 + 1.0 * n1, variable2); } - - diff --git a/Tests/NumLib/TestMeshComponentMap.cpp b/Tests/NumLib/TestMeshComponentMap.cpp index a3b86648727e29db60c844f9faff3332fd25d518..4248f571c501f4d965994d94a438e9491e822f85 100644 --- a/Tests/NumLib/TestMeshComponentMap.cpp +++ b/Tests/NumLib/TestMeshComponentMap.cpp @@ -11,41 +11,38 @@ */ #include <gtest/gtest.h> + #include <memory> #include <vector> -#include "NumLib/DOF/MeshComponentMap.h" - #include "MeshLib/MeshGenerators/MeshGenerator.h" #include "MeshLib/MeshSubset.h" +#include "NumLib/DOF/MeshComponentMap.h" class NumLibMeshComponentMapTest : public ::testing::Test { - public: - using MeshItemType = MeshLib::MeshItemType; - using Location = MeshLib::Location; - using MeshComponentMap = NumLib::MeshComponentMap; +public: + using MeshItemType = MeshLib::MeshItemType; + using Location = MeshLib::Location; + using MeshComponentMap = NumLib::MeshComponentMap; - public: - NumLibMeshComponentMapTest() - { - MeshLib::MeshSubset nodesSubset{*mesh, mesh->getNodes()}; +public: + NumLibMeshComponentMapTest() + { + MeshLib::MeshSubset nodesSubset{*mesh, mesh->getNodes()}; - // Add two components both based on the same nodesSubset. - components.emplace_back(nodesSubset); - components.emplace_back(nodesSubset); + // Add two components both based on the same nodesSubset. + components.emplace_back(nodesSubset); + components.emplace_back(nodesSubset); } - ~NumLibMeshComponentMapTest() override - { - delete cmap; - } + ~NumLibMeshComponentMapTest() override { delete cmap; } static std::size_t const mesh_size = 9; std::unique_ptr<MeshLib::Mesh> const mesh{ MeshLib::MeshGenerator::generateLineMesh(1.0, mesh_size)}; - //data component 0 and 1 are assigned to all nodes in the mesh + // data component 0 and 1 are assigned to all nodes in the mesh static std::size_t const comp0_id = 0; static std::size_t const comp1_id = 1; std::vector<MeshLib::MeshSubset> components; @@ -56,11 +53,12 @@ class NumLibMeshComponentMapTest : public ::testing::Test // // Returns global index of a node location and a component. - std::size_t giAtNodeForComponent(std::size_t const n, std::size_t const c) const + std::size_t giAtNodeForComponent(std::size_t const n, + std::size_t const c) const { - return cmap->getGlobalIndex(Location(mesh->getID(), MeshItemType::Node, n), c); + return cmap->getGlobalIndex( + Location(mesh->getID(), MeshItemType::Node, n), c); } - }; #ifndef USE_PETSC @@ -69,17 +67,19 @@ TEST_F(NumLibMeshComponentMapTest, CheckOrderByComponent) TEST_F(NumLibMeshComponentMapTest, DISABLED_CheckOrderByComponent) #endif { - // - Entries in the vector are arranged in the order of a component type and then node ID - // - For example, x=[(node 0, comp 0) (node 1, comp 0) ... (node n, comp0), (node 0, comp1) ... ] + // - Entries in the vector are arranged in the order of a component type and + // then node ID + // - For example, x=[(node 0, comp 0) (node 1, comp 0) ... (node n, comp0), + // (node 0, comp1) ... ] - cmap = new MeshComponentMap(components, - NumLib::ComponentOrder::BY_COMPONENT); + cmap = + new MeshComponentMap(components, NumLib::ComponentOrder::BY_COMPONENT); ASSERT_EQ(2 * mesh->getNumberOfNodes(), cmap->dofSizeWithGhosts()); for (std::size_t i = 0; i < mesh_size; i++) { // Test global indices for the different components of the node. - ASSERT_EQ(i , giAtNodeForComponent(i, comp0_id)); + ASSERT_EQ(i, giAtNodeForComponent(i, comp0_id)); ASSERT_EQ(mesh_size + 1 + i, giAtNodeForComponent(i, comp1_id)); // Test component ids of the node. @@ -97,17 +97,19 @@ TEST_F(NumLibMeshComponentMapTest, CheckOrderByLocation) TEST_F(NumLibMeshComponentMapTest, DISABLED_CheckOrderByLocation) #endif { - // - Entries in the vector are arranged in the order of node ID and then a component type - // - For example, x=[(node 0, comp 0) (node 0, comp 1) ... (node n, comp0), (node n, comp1) ] + // - Entries in the vector are arranged in the order of node ID and then a + // component type + // - For example, x=[(node 0, comp 0) (node 0, comp 1) ... (node n, comp0), + // (node n, comp1) ] - cmap = new MeshComponentMap(components, - NumLib::ComponentOrder::BY_LOCATION); + cmap = + new MeshComponentMap(components, NumLib::ComponentOrder::BY_LOCATION); ASSERT_EQ(2 * mesh->getNumberOfNodes(), cmap->dofSizeWithGhosts()); for (std::size_t i = 0; i < mesh_size; i++) { // Test global indices for the different components of the node. - ASSERT_EQ(2 * i , giAtNodeForComponent(i, comp0_id)); + ASSERT_EQ(2 * i, giAtNodeForComponent(i, comp0_id)); ASSERT_EQ(2 * i + 1, giAtNodeForComponent(i, comp1_id)); // Test component ids of the node. @@ -125,17 +127,23 @@ TEST_F(NumLibMeshComponentMapTest, OutOfRangeAccess) TEST_F(NumLibMeshComponentMapTest, DISABLED_OutOfRangeAccess) #endif { - cmap = new MeshComponentMap(components, - NumLib::ComponentOrder::BY_COMPONENT); - - ASSERT_EQ(MeshComponentMap::nop, cmap->getGlobalIndex( - Location(mesh->getID(), MeshItemType::Node, mesh_size + 1), comp0_id)); - ASSERT_EQ(MeshComponentMap::nop, cmap->getGlobalIndex( - Location(mesh->getID() + 1, MeshItemType::Node, 0), comp0_id)); - ASSERT_EQ(MeshComponentMap::nop, cmap->getGlobalIndex( - Location(mesh->getID(), MeshItemType::Cell, 0), comp0_id)); - ASSERT_EQ(MeshComponentMap::nop, cmap->getGlobalIndex( - Location(mesh->getID(), MeshItemType::Node, 0), 10)); + cmap = + new MeshComponentMap(components, NumLib::ComponentOrder::BY_COMPONENT); + + ASSERT_EQ(MeshComponentMap::nop, + cmap->getGlobalIndex( + Location(mesh->getID(), MeshItemType::Node, mesh_size + 1), + comp0_id)); + ASSERT_EQ( + MeshComponentMap::nop, + cmap->getGlobalIndex(Location(mesh->getID() + 1, MeshItemType::Node, 0), + comp0_id)); + ASSERT_EQ(MeshComponentMap::nop, + cmap->getGlobalIndex( + Location(mesh->getID(), MeshItemType::Cell, 0), comp0_id)); + ASSERT_EQ(MeshComponentMap::nop, + cmap->getGlobalIndex( + Location(mesh->getID(), MeshItemType::Node, 0), 10)); } MeshLib::Mesh createMeshFromSelectedNodes( @@ -162,8 +170,8 @@ TEST_F(NumLibMeshComponentMapTest, SubsetOfNodesByComponent) TEST_F(NumLibMeshComponentMapTest, DISABLED_SubsetOfNodesByComponent) #endif { - cmap = new MeshComponentMap(components, - NumLib::ComponentOrder::BY_COMPONENT); + cmap = + new MeshComponentMap(components, NumLib::ComponentOrder::BY_COMPONENT); // Select some nodes from the full mesh. std::vector<std::size_t> const ids = {0, 5, 9}; @@ -200,8 +208,8 @@ TEST_F(NumLibMeshComponentMapTest, SubsetOfNodesByLocation) TEST_F(NumLibMeshComponentMapTest, DISABLED_SubsetOfNodesByLocation) #endif { - cmap = new MeshComponentMap(components, - NumLib::ComponentOrder::BY_LOCATION); + cmap = + new MeshComponentMap(components, NumLib::ComponentOrder::BY_LOCATION); // Select some nodes from the full mesh. std::vector<std::size_t> const ids = {0, 5, 9}; diff --git a/Tests/NumLib/TestODEInt.cpp b/Tests/NumLib/TestODEInt.cpp index 5a1cd51bba5b5385d08bfddba11474a344f56ac7..1e8bbafbeb3d4c1fb1de2e7354b414c9c26b1d12 100644 --- a/Tests/NumLib/TestODEInt.cpp +++ b/Tests/NumLib/TestODEInt.cpp @@ -9,37 +9,34 @@ #include <gtest/gtest.h> +#include <boost/property_tree/xml_parser.hpp> #include <fstream> #include <memory> #include <typeinfo> -#include <boost/property_tree/xml_parser.hpp> #include "BaseLib/Logging.h" - #include "InfoLib/TestInfo.h" +#include "MathLib/LinAlg/LinAlg.h" #include "NumLib/NumericsConfig.h" #include "NumLib/ODESolver/ConvergenceCriterionDeltaX.h" -#include "MathLib/LinAlg/LinAlg.h" -#include "Tests/TestTools.h" #include "ODEs.h" - +#include "Tests/TestTools.h" #include "TimeLoopSingleODE.h" -namespace TestODEInt { - +namespace TestODEInt +{ #ifndef USE_PETSC -std::unique_ptr<GlobalLinearSolver> -createLinearSolver() +std::unique_ptr<GlobalLinearSolver> createLinearSolver() { return std::make_unique<GlobalLinearSolver>("", nullptr); } #else -std::unique_ptr<GlobalLinearSolver> -createLinearSolver() +std::unique_ptr<GlobalLinearSolver> createLinearSolver() { const char xml[] = "<petsc><parameters>" - "-ksp_type bcgs -pc_type sor -ksp_rtol 1e-24 -ksp_max_it 100 -ksp_initial_guess_nonzero false" + "-ksp_type bcgs -pc_type sor -ksp_rtol 1e-24 -ksp_max_it 100 " + "-ksp_initial_guess_nonzero false" "</parameters></petsc>"; auto const ptree = Tests::readXml(xml); BaseLib::ConfigTree config(ptree, "", BaseLib::ConfigTree::onerror, @@ -54,7 +51,7 @@ struct Solution std::vector<GlobalVector> solutions; }; -template<NumLib::NonlinearSolverTag NLTag> +template <NumLib::NonlinearSolverTag NLTag> class TestOutput { public: @@ -63,7 +60,7 @@ public: template <class ODE> Solution run_test(ODE& ode, TimeDisc& timeDisc, - const unsigned num_timesteps) + const unsigned num_timesteps) { using ODE_ = ODE; using ODET = ODETraits<ODE>; @@ -71,8 +68,8 @@ public: Solution sol; const int process_id = 0; - NumLib::TimeDiscretizedODESystem<ODE_::ODETag, NLTag> - ode_sys(process_id, ode, timeDisc); + NumLib::TimeDiscretizedODESystem<ODE_::ODETag, NLTag> ode_sys( + process_id, ode, timeDisc); auto linear_solver = createLinearSolver(); auto conv_crit = std::make_unique<NumLib::ConvergenceCriterionDeltaX>( @@ -84,10 +81,10 @@ public: std::move(nonlinear_solver), std::move(conv_crit)); - const double t0 = ODET::t0; - const double t_end = ODET::t_end; - const double delta_t = (num_timesteps == 0) ? -1.0 - : ((t_end-t0) / num_timesteps); + const double t0 = ODET::t0; + const double t_end = ODET::t_end; + const double delta_t = + (num_timesteps == 0) ? -1.0 : ((t_end - t0) / num_timesteps); DBUG("Running test with {:d} timesteps of size {:g} s.", num_timesteps, delta_t); @@ -146,7 +143,6 @@ struct TestCaseBase template <class ODE_, class TimeDisc_> struct TestCase; - // ///////////////////////////////////// // // Put new test cases to that list @@ -157,20 +153,21 @@ struct TestCase; // comparing the numerical to the analytical solution // // ///////////////////////////////////// -#define TESTCASESLIST \ - TCLITEM(ODE1, BackwardEuler , 1e-14 , 0.2) TCLSEP \ - TCLITEM(ODE2, BackwardEuler , 1.5e-10, 2e-3) TCLSEP \ - TCLITEM(ODE3, BackwardEuler , 1e-9 , 0.028) - -#define TCLITEM(ODE, TIMEDISC, TOL_PICARD_NEWTON, TOL_ANALYT) \ - template <> \ - struct TestCase<ODE, NumLib::TIMEDISC> \ - : TestCaseBase<ODE, NumLib::TIMEDISC> { \ - static const double tol_picard_newton; \ - static const double tol_analyt; \ - }; \ - const double TestCase<ODE, NumLib::TIMEDISC>::tol_picard_newton = \ - (TOL_PICARD_NEWTON); \ +#define TESTCASESLIST \ + TCLITEM(ODE1, BackwardEuler, 1e-14, 0.2) \ + TCLSEP TCLITEM(ODE2, BackwardEuler, 1.5e-10, 2e-3) \ + TCLSEP TCLITEM(ODE3, BackwardEuler, 1e-9, 0.028) + +#define TCLITEM(ODE, TIMEDISC, TOL_PICARD_NEWTON, TOL_ANALYT) \ + template <> \ + struct TestCase<ODE, NumLib::TIMEDISC> \ + : TestCaseBase<ODE, NumLib::TIMEDISC> \ + { \ + static const double tol_picard_newton; \ + static const double tol_analyt; \ + }; \ + const double TestCase<ODE, NumLib::TIMEDISC>::tol_picard_newton = \ + (TOL_PICARD_NEWTON); \ const double TestCase<ODE, NumLib::TIMEDISC>::tol_analyt = (TOL_ANALYT); #define TCLSEP @@ -189,12 +186,11 @@ using TestCases = ::testing::Types<TESTCASESLIST>; #undef TCLSEP #undef TCLITEM - -template<class TestParams> +template <class TestParams> class NumLibODEIntTyped : public ::testing::Test { public: - using ODE = typename TestParams::ODE; + using ODE = typename TestParams::ODE; using TimeDisc = typename TestParams::TimeDisc; static void test() @@ -246,11 +242,10 @@ TYPED_TEST(NumLibODEIntTyped, DISABLED_T1) TestFixture::test(); } - /* TODO Other possible test cases: * * * check that the order of time discretization scales correctly * with the timestep size */ -} // end namespace +} // namespace TestODEInt diff --git a/Tests/NumLib/TestSerialExecutor.cpp b/Tests/NumLib/TestSerialExecutor.cpp index b114c658751fa02f40eb5857b3a32d2b5fa236b0..36f9349cae567a6fb714fba7ae68226dc749964f 100644 --- a/Tests/NumLib/TestSerialExecutor.cpp +++ b/Tests/NumLib/TestSerialExecutor.cpp @@ -10,9 +10,10 @@ #include <gtest/gtest.h> #include <algorithm> -#include <vector> #include <functional> #include <numeric> +#include <vector> + #include "NumLib/Assembler/SerialExecutor.h" template <typename ContainerElement_> @@ -23,7 +24,7 @@ public: using Container = std::vector<ContainerElement>; using PtrContainer = std::vector<ContainerElement*>; - template<typename Callback> + template <typename Callback> void test(Callback const& cb) { Container reference(size); @@ -43,28 +44,26 @@ public: ASSERT_TRUE(referenceIsZero(reference)); } - static void subtractFromReferenceStatic( - ContainerElement const value, std::size_t const index, - Container& reference) + static void subtractFromReferenceStatic(ContainerElement const value, + std::size_t const index, + Container& reference) { reference[index] -= value; } - void subtractFromReference( - ContainerElement const value, std::size_t const index, - Container& reference) const + void subtractFromReference(ContainerElement const value, + std::size_t const index, + Container& reference) const { reference[index] -= value; } - static bool - referenceIsZero(Container const& reference) + static bool referenceIsZero(Container const& reference) { return std::all_of(reference.begin(), reference.end(), - [](ContainerElement const reference_value) - { - return reference_value == 0; - }); + [](ContainerElement const reference_value) { + return reference_value == 0; + }); } static std::size_t const size = 100; @@ -76,28 +75,22 @@ TYPED_TEST_SUITE(NumLibSerialExecutor, TestCases); TYPED_TEST(NumLibSerialExecutor, ContainerArgument) { - using Elem = typename TestFixture::ContainerElement; - using Container = typename TestFixture::Container; + using Elem = typename TestFixture::ContainerElement; + using Container = typename TestFixture::Container; using PtrContainer = typename TestFixture::PtrContainer; - TestFixture::test( - [](PtrContainer const& ctnr, Container& ref) { - auto cb_static = - [](Elem const value, std::size_t const index, Container& ref_inner) { - TestFixture::subtractFromReferenceStatic(value, index, ref_inner); - }; + TestFixture::test([](PtrContainer const& ctnr, Container& ref) { + auto cb_static = [](Elem const value, std::size_t const index, + Container& ref_inner) { + TestFixture::subtractFromReferenceStatic(value, index, ref_inner); + }; - NumLib::SerialExecutor::executeDereferenced( - cb_static, ctnr, ref); - } - ); - - TestFixture::test( - [this](PtrContainer const& ctnr, Container& ref) { - NumLib::SerialExecutor::executeMemberDereferenced( - *static_cast<TestFixture*>(this), &TestFixture::subtractFromReference, - ctnr, ref - ); - } - ); + NumLib::SerialExecutor::executeDereferenced(cb_static, ctnr, ref); + }); + + TestFixture::test([this](PtrContainer const& ctnr, Container& ref) { + NumLib::SerialExecutor::executeMemberDereferenced( + *static_cast<TestFixture*>(this), + &TestFixture::subtractFromReference, ctnr, ref); + }); } diff --git a/Tests/NumLib/TestSerialLinearSolver.cpp b/Tests/NumLib/TestSerialLinearSolver.cpp index 889ff52d0dee2f3daa6420aab0f1b829cf5b4288..4f9a64fc840bfe6893e57ed7c34769249a694b5c 100644 --- a/Tests/NumLib/TestSerialLinearSolver.cpp +++ b/Tests/NumLib/TestSerialLinearSolver.cpp @@ -57,10 +57,10 @@ TEST(NumLibSerialLinearSolver, Steady2DdiffusionQuadElem) // Construct a linear system //-------------------------------------------------------------------------- // allocate a vector and matrix - MathLib::MatrixSpecifications ms{local_to_global_index_map.dofSizeWithoutGhosts(), + MathLib::MatrixSpecifications ms{ local_to_global_index_map.dofSizeWithoutGhosts(), - &local_to_global_index_map.getGhostIndices(), - nullptr}; + local_to_global_index_map.dofSizeWithoutGhosts(), + &local_to_global_index_map.getGhostIndices(), nullptr}; auto A = MathLib::MatrixVectorTraits<GlobalMatrix>::newInstance(ms); A->setZero(); auto rhs = MathLib::MatrixVectorTraits<GlobalVector>::newInstance(ms); @@ -78,16 +78,15 @@ TEST(NumLibSerialLinearSolver, Steady2DdiffusionQuadElem) MeshLib::Element const& item) -> LocalAssembler* { assert(local_to_global_index_map.size() > id); - auto const num_local_dof = local_to_global_index_map.getNumberOfElementDOF(id); + auto const num_local_dof = + local_to_global_index_map.getNumberOfElementDOF(id); return Example::initializeLocalData(item, num_local_dof, ex1); }; // Call global initializer for each mesh element. GlobalExecutor::transformDereferenced( - local_asm_builder, - ex1.msh->getElements(), - local_assemblers); + local_asm_builder, ex1.msh->getElements(), local_assemblers); // Call global assembler for each mesh element. auto M_dummy = MathLib::MatrixVectorTraits<GlobalMatrix>::newInstance(ms); @@ -97,18 +96,18 @@ TEST(NumLibSerialLinearSolver, Steady2DdiffusionQuadElem) &LocalAssembler::assemble, local_assemblers, local_to_global_index_map, t, *x, *M_dummy, *A, *rhs); - //std::cout << "A=\n"; - //A->write(std::cout); - //std::cout << "rhs=\n"; - //rhs->write(std::cout); + // std::cout << "A=\n"; + // A->write(std::cout); + // std::cout << "rhs=\n"; + // rhs->write(std::cout); // apply Dirichlet BC MathLib::applyKnownSolution(*A, *rhs, *x, ex1.vec_DirichletBC_id, ex1.vec_DirichletBC_value); - //std::cout << "A=\n"; - //A->write(std::cout); - //std::cout << "rhs=\n"; - //rhs->write(std::cout); + // std::cout << "A=\n"; + // A->write(std::cout); + // std::cout << "rhs=\n"; + // rhs->write(std::cout); MathLib::finalizeMatrixAssembly(*A); //-------------------------------------------------------------------------- @@ -124,8 +123,7 @@ TEST(NumLibSerialLinearSolver, Steady2DdiffusionQuadElem) t_root.put_child("eigen", t_solver); } t_root.put("lis", "-i cg -p none -tol 1e-16 -maxiter 1000"); - BaseLib::ConfigTree conf(t_root, "", - BaseLib::ConfigTree::onerror, + BaseLib::ConfigTree conf(t_root, "", BaseLib::ConfigTree::onerror, BaseLib::ConfigTree::onwarning); GlobalLinearSolver ls("solver_name", &conf); @@ -138,7 +136,8 @@ TEST(NumLibSerialLinearSolver, Steady2DdiffusionQuadElem) solution[i] = (*x)[i]; } - ASSERT_ARRAY_NEAR(&ex1.exact_solutions[0], &solution[0], ex1.dim_eqs, 1.e-5); + ASSERT_ARRAY_NEAR(&ex1.exact_solutions[0], &solution[0], ex1.dim_eqs, + 1.e-5); for (auto p : local_assemblers) { diff --git a/Tests/NumLib/TestShapeFunctions.cpp b/Tests/NumLib/TestShapeFunctions.cpp index c6385761733b0f1b7c9bd9e671d590a6d19d9fd6..5bccfd9192b7960049b524a816dbb9a38b35baa2 100644 --- a/Tests/NumLib/TestShapeFunctions.cpp +++ b/Tests/NumLib/TestShapeFunctions.cpp @@ -13,9 +13,9 @@ #include <gtest/gtest.h> #include <algorithm> -#include <type_traits> #include <limits> #include <numeric> +#include <type_traits> #include <valarray> #include "MeshLib/Elements/Elements.h" @@ -35,7 +35,6 @@ namespace autocheck { - template <typename ShapeFunction, typename Gen = randomTupleGenerator<double, ShapeFunction::DIM>> struct NaturalPointGenerator @@ -114,7 +113,6 @@ TYPED_TEST(ShapeFunctionTest, PartitionOfUnity) auto isPartitionOfUnity = [](std::array<double, TypeParam::DIM>& natural_coordinates_point) -> bool { - // compute shape functions std::array<double, TypeParam::NPOINTS> N; TypeParam::computeShapeFunction(natural_coordinates_point, N); @@ -135,7 +133,6 @@ TYPED_TEST(ShapeFunctionTest, SumOfGradientsIsZero) auto isSumOfGradientsZero = [](std::array<double, TypeParam::DIM>& natural_coordinates_point) -> bool { - // compute shape functions std::array<double, TypeParam::DIM * TypeParam::NPOINTS> dNdr; TypeParam::computeGradShapeFunction(natural_coordinates_point, dNdr); @@ -159,25 +156,26 @@ TEST(NumLib, FemShapeQuad4) static const unsigned dim = 2; std::valarray<double> r(dim); std::valarray<double> N(NNodes); - std::valarray<double> dN(NNodes*dim); + std::valarray<double> dN(NNodes * dim); // check N, dN at specific location { - r = .5; // r = (0,5, 0.5) + r = .5; // r = (0,5, 0.5) ShapeQuad4::computeShapeFunction(r, N); ShapeQuad4::computeGradShapeFunction(r, dN); - double exp_N[]= {0.5625, 0.1875, 0.0625, 0.1875}; - double exp_dN[]= {0.375, -0.375, -0.125, 0.125, 0.375, 0.125, -0.125, -0.375}; + double exp_N[] = {0.5625, 0.1875, 0.0625, 0.1875}; + double exp_dN[] = {0.375, -0.375, -0.125, 0.125, + 0.375, 0.125, -0.125, -0.375}; ASSERT_ARRAY_NEAR(exp_N, N, N.size(), eps); ASSERT_ARRAY_NEAR(exp_dN, dN, dN.size(), eps); } std::valarray<double> exp_N(NNodes); // check N_i(r_j)= {i==j: 1, i!=j: 0} - for (unsigned i=0; i<NNodes; i++) + for (unsigned i = 0; i < NNodes; i++) { - r[0] = (i==0 || i==3) ? 1 : -1; - r[1] = i<2 ? 1 : -1; + r[0] = (i == 0 || i == 3) ? 1 : -1; + r[1] = i < 2 ? 1 : -1; exp_N = .0; exp_N[i] = 1.0; ShapeQuad4::computeShapeFunction(r, N); @@ -186,17 +184,14 @@ TEST(NumLib, FemShapeQuad4) // check sum_i[N_i(r)] = 1 const double dist = 0.5; - for (unsigned i=0; i<NNodes; i++) + for (unsigned i = 0; i < NNodes; i++) { - r[0] = (i==0 || i==3) ? dist : -dist; - r[1] = i<2 ? dist : -dist; + r[0] = (i == 0 || i == 3) ? dist : -dist; + r[1] = i < 2 ? dist : -dist; ShapeQuad4::computeShapeFunction(r, N); ASSERT_NEAR(1.0, N.sum(), eps); -// for(auto v: N) -// std::cout << v << " "; -// std::cout << "\n"; + // for(auto v: N) + // std::cout << v << " "; + // std::cout << "\n"; } - } - - diff --git a/Tests/NumLib/TestShapeMatrices.cpp b/Tests/NumLib/TestShapeMatrices.cpp index e7c254e6f829c8adb6dd613135d471399f1c2c8e..6ec85b400a15a588145e404e0c1f4ec19ddf7045 100644 --- a/Tests/NumLib/TestShapeMatrices.cpp +++ b/Tests/NumLib/TestShapeMatrices.cpp @@ -15,12 +15,10 @@ #include <Eigen/Eigen> #include "NumLib/Fem/CoordinatesMapping/ShapeMatrices.h" - #include "Tests/TestTools.h" using namespace NumLib; - TEST(NumLib, FemShapeMatricesWithEigen) { const static unsigned dim = 2; @@ -36,15 +34,14 @@ TEST(NumLib, FemShapeMatricesWithEigen) using ShapeMatricesType = ShapeMatrices<NodalVector, DimNodalMatrix, DimMatrix, DimNodalMatrix>; - auto setShapeDataToOnes = [](ShapeMatricesType &shape) - { - shape.N.setOnes(); - shape.dNdr.setOnes(); - shape.dNdx.setOnes(); - shape.J.setOnes(); - shape.invJ.setOnes(); - shape.detJ = 1.0; - }; + auto setShapeDataToOnes = [](ShapeMatricesType& shape) { + shape.N.setOnes(); + shape.dNdr.setOnes(); + shape.dNdx.setOnes(); + shape.J.setOnes(); + shape.invJ.setOnes(); + shape.detJ = 1.0; + }; ShapeMatricesType shape(dim, dim, e_nnodes); diff --git a/Tests/NumLib/TestSparsityPattern.cpp b/Tests/NumLib/TestSparsityPattern.cpp index bb5cfe869524c25ae9757943be68fa5423b7af23..67e307cd398e671e3f258ffd0359f422ce141c6a 100644 --- a/Tests/NumLib/TestSparsityPattern.cpp +++ b/Tests/NumLib/TestSparsityPattern.cpp @@ -13,12 +13,10 @@ #include "MeshLib/Mesh.h" #include "MeshLib/MeshGenerators/MeshGenerator.h" #include "MeshLib/MeshGenerators/QuadraticMeshGenerator.h" - -#include "NumLib/DOF/LocalToGlobalIndexMap.h" #include "NumLib/DOF/ComputeSparsityPattern.h" +#include "NumLib/DOF/LocalToGlobalIndexMap.h" #include "NumLib/NumericsConfig.h" - #ifndef USE_PETSC TEST(NumLib_SparsityPattern, SingleComponentLinearMesh) #else @@ -30,9 +28,8 @@ TEST(NumLib_SparsityPattern, DISABLED_SingleComponentLinearMesh) MeshLib::MeshSubset nodesSubset{*mesh, mesh->getNodes()}; std::vector<MeshLib::MeshSubset> components{nodesSubset}; - NumLib::LocalToGlobalIndexMap dof_map( - std::move(components), - NumLib::ComponentOrder::BY_COMPONENT); + NumLib::LocalToGlobalIndexMap dof_map(std::move(components), + NumLib::ComponentOrder::BY_COMPONENT); GlobalSparsityPattern sp = NumLib::computeSparsityPattern(dof_map, *mesh); @@ -43,7 +40,6 @@ TEST(NumLib_SparsityPattern, DISABLED_SingleComponentLinearMesh) EXPECT_EQ(2u, sp[3]); } - #ifndef USE_PETSC TEST(NumLib_SparsityPattern, SingleComponentQuadraticMesh) #else @@ -57,9 +53,8 @@ TEST(NumLib_SparsityPattern, DISABLED_SingleComponentQuadraticMesh) MeshLib::MeshSubset nodesSubset{*mesh, mesh->getNodes()}; std::vector<MeshLib::MeshSubset> components{nodesSubset}; - NumLib::LocalToGlobalIndexMap dof_map( - std::move(components), - NumLib::ComponentOrder::BY_COMPONENT); + NumLib::LocalToGlobalIndexMap dof_map(std::move(components), + NumLib::ComponentOrder::BY_COMPONENT); GlobalSparsityPattern sp = NumLib::computeSparsityPattern(dof_map, *mesh); @@ -73,7 +68,6 @@ TEST(NumLib_SparsityPattern, DISABLED_SingleComponentQuadraticMesh) EXPECT_EQ(3u, sp[6]); } - #ifndef USE_PETSC TEST(NumLib_SparsityPattern, MultipleComponentsLinearMesh) #else @@ -85,23 +79,21 @@ TEST(NumLib_SparsityPattern, DISABLED_MultipleComponentsLinearMesh) MeshLib::MeshSubset nodesSubset{*mesh, mesh->getNodes()}; std::vector<MeshLib::MeshSubset> components{nodesSubset, nodesSubset}; - NumLib::LocalToGlobalIndexMap dof_map( - std::move(components), - NumLib::ComponentOrder::BY_COMPONENT); + NumLib::LocalToGlobalIndexMap dof_map(std::move(components), + NumLib::ComponentOrder::BY_COMPONENT); GlobalSparsityPattern sp = NumLib::computeSparsityPattern(dof_map, *mesh); ASSERT_EQ(8u, sp.size()); - for (int i=0; i<2; i++) + for (int i = 0; i < 2; i++) { - EXPECT_EQ(4u, sp[i*mesh->getNumberOfNodes() + 0]); - EXPECT_EQ(6u, sp[i*mesh->getNumberOfNodes() + 1]); - EXPECT_EQ(6u, sp[i*mesh->getNumberOfNodes() + 2]); - EXPECT_EQ(4u, sp[i*mesh->getNumberOfNodes() + 3]); + EXPECT_EQ(4u, sp[i * mesh->getNumberOfNodes() + 0]); + EXPECT_EQ(6u, sp[i * mesh->getNumberOfNodes() + 1]); + EXPECT_EQ(6u, sp[i * mesh->getNumberOfNodes() + 2]); + EXPECT_EQ(4u, sp[i * mesh->getNumberOfNodes() + 3]); } } - #ifndef USE_PETSC TEST(NumLib_SparsityPattern, MultipleComponentsLinearQuadraticMesh) #else @@ -120,9 +112,8 @@ TEST(NumLib_SparsityPattern, DISABLED_MultipleComponentsLinearQuadraticMesh) std::vector<MeshLib::MeshSubset> components{*baseNodesSubset, *allNodesSubset}; - NumLib::LocalToGlobalIndexMap dof_map( - std::move(components), - NumLib::ComponentOrder::BY_COMPONENT); + NumLib::LocalToGlobalIndexMap dof_map(std::move(components), + NumLib::ComponentOrder::BY_COMPONENT); GlobalSparsityPattern sp = NumLib::computeSparsityPattern(dof_map, *mesh); @@ -141,4 +132,3 @@ TEST(NumLib_SparsityPattern, DISABLED_MultipleComponentsLinearQuadraticMesh) EXPECT_EQ(5u, sp[9]); EXPECT_EQ(5u, sp[10]); } - diff --git a/Tests/NumLib/TestTimeSteppingFixed.cpp b/Tests/NumLib/TestTimeSteppingFixed.cpp index b8cb484091d0085efb18174a560f9dfbbfd627c1..3a43e9cfb689aab0a451d8ba728228efaa241322 100644 --- a/Tests/NumLib/TestTimeSteppingFixed.cpp +++ b/Tests/NumLib/TestTimeSteppingFixed.cpp @@ -13,10 +13,8 @@ #include <vector> - #include "NumLib/TimeStepping/Algorithms/FixedTimeStepping.h" #include "NumLib/TimeStepping/TimeStep.h" - #include "Tests/TestTools.h" #include "TimeSteppingTestingTools.h" diff --git a/Tests/NumLib/TestTimeSteppingIterationNumber.cpp b/Tests/NumLib/TestTimeSteppingIterationNumber.cpp index 1a5e1cef4b6447edd244d17eb6377ec539622d44..2a73cda25960ea13e8fb279ca5bf55f96b5f4594 100644 --- a/Tests/NumLib/TestTimeSteppingIterationNumber.cpp +++ b/Tests/NumLib/TestTimeSteppingIterationNumber.cpp @@ -131,7 +131,8 @@ TEST(NumLib, TimeSteppingIterationNumberBased2) std::vector<double> vec_t = timeStepping(alg, nr_iterations, {}); ASSERT_EQ(expected_vec_t.size(), vec_t.size()); - ASSERT_ARRAY_NEAR(expected_vec_t, vec_t, expected_vec_t.size(), std::numeric_limits<double>::epsilon()); + ASSERT_ARRAY_NEAR(expected_vec_t, vec_t, expected_vec_t.size(), + std::numeric_limits<double>::epsilon()); } TEST(NumLib, TimeSteppingIterationNumberBased2FixedOutputTimes) diff --git a/Tests/ParameterLib/Parameter.cpp b/Tests/ParameterLib/Parameter.cpp index 2ea7218ea0205c6081675147ca32658ffd463159..28e45c7b1b7a7653d08372f109a5a513bb5d8457 100644 --- a/Tests/ParameterLib/Parameter.cpp +++ b/Tests/ParameterLib/Parameter.cpp @@ -8,7 +8,6 @@ */ #include <gtest/gtest.h> -#include "BaseLib/Logging.h" #include <boost/property_tree/xml_parser.hpp> #include <numeric> @@ -16,15 +15,14 @@ #include <vector> #include "BaseLib/ConfigTree.h" -#include "Tests/TestTools.h" - +#include "BaseLib/Logging.h" #include "MeshLib/Mesh.h" #include "MeshLib/MeshGenerators/MeshGenerator.h" #include "MeshLib/Node.h" #include "MeshLib/PropertyVector.h" - #include "ParameterLib/CurveScaledParameter.h" #include "ParameterLib/GroupBasedParameter.h" +#include "Tests/TestTools.h" using namespace ParameterLib; @@ -139,8 +137,7 @@ bool testNodalValuesOfElement( if (expected_value != nodal_values(i, 0)) { ERR("Mismatch for element {:d}, node {:d}; Expected {:g}, " - "got " - "{:g}.", + "got {:g}.", e->getID(), i, expected_value, nodal_values(i, 0)); return false; } diff --git a/Tests/ProcessLib/LIE/TestLIE.cpp b/Tests/ProcessLib/LIE/TestLIE.cpp index 853e815660706cf80c510287865a4580d75ba813..5df0396e1a6c3537b9e887816f01fce8c1cceabe 100644 --- a/Tests/ProcessLib/LIE/TestLIE.cpp +++ b/Tests/ProcessLib/LIE/TestLIE.cpp @@ -7,20 +7,17 @@ * */ -#include <cmath> -#include <memory> - #include <gtest/gtest.h> #include <Eigen/Eigen> +#include <cmath> +#include <memory> #include "MeshLib/Elements/Line.h" #include "MeshLib/Elements/Tri.h" #include "MeshLib/Mesh.h" - #include "ProcessLib/LIE/Common/Utils.h" - namespace { std::unique_ptr<MeshLib::Mesh> createTriangle( @@ -117,13 +114,13 @@ TEST(LIE, rotationMatrixX) ASSERT_EQ(1., nv[1]); ASSERT_EQ(0., nv[2]); - Eigen::MatrixXd R(2,2); + Eigen::MatrixXd R(2, 2); ProcessLib::LIE::computeRotationMatrix(*e, nv, 2, R); - ASSERT_NEAR(1., R(0,0), eps); - ASSERT_NEAR(0., R(0,1), eps); - ASSERT_NEAR(0., R(1,0), eps); - ASSERT_NEAR(1., R(1,1), eps); + ASSERT_NEAR(1., R(0, 0), eps); + ASSERT_NEAR(0., R(0, 1), eps); + ASSERT_NEAR(0., R(1, 0), eps); + ASSERT_NEAR(1., R(1, 1), eps); } TEST(LIE, rotationMatrixY) @@ -136,13 +133,13 @@ TEST(LIE, rotationMatrixY) ASSERT_EQ(0., nv[1]); ASSERT_EQ(0., nv[2]); - Eigen::MatrixXd R(2,2); + Eigen::MatrixXd R(2, 2); ProcessLib::LIE::computeRotationMatrix(*e, nv, 2, R); - ASSERT_NEAR(0., R(0,0), eps); - ASSERT_NEAR(1., R(0,1), eps); - ASSERT_NEAR(-1., R(1,0), eps); - ASSERT_NEAR(0., R(1,1), eps); + ASSERT_NEAR(0., R(0, 0), eps); + ASSERT_NEAR(1., R(0, 1), eps); + ASSERT_NEAR(-1., R(1, 0), eps); + ASSERT_NEAR(0., R(1, 1), eps); } TEST(LIE, rotationMatrixXY) @@ -153,15 +150,15 @@ TEST(LIE, rotationMatrixXY) auto e(msh->getElement(0)); Eigen::Vector3d nv; ProcessLib::LIE::computeNormalVector(*e, 2, nv); - ASSERT_NEAR(-1./std::sqrt(2), nv[0], eps); - ASSERT_NEAR(1./std::sqrt(2), nv[1], eps); + ASSERT_NEAR(-1. / std::sqrt(2), nv[0], eps); + ASSERT_NEAR(1. / std::sqrt(2), nv[1], eps); ASSERT_EQ(0., nv[2]); - Eigen::MatrixXd R(2,2); + Eigen::MatrixXd R(2, 2); ProcessLib::LIE::computeRotationMatrix(*e, nv, 2, R); - ASSERT_NEAR(1./std::sqrt(2), R(0,0), eps); - ASSERT_NEAR(1./std::sqrt(2), R(0,1), eps); - ASSERT_NEAR(-1./std::sqrt(2), R(1,0), eps); - ASSERT_NEAR(1./std::sqrt(2), R(1,1), eps); + ASSERT_NEAR(1. / std::sqrt(2), R(0, 0), eps); + ASSERT_NEAR(1. / std::sqrt(2), R(0, 1), eps); + ASSERT_NEAR(-1. / std::sqrt(2), R(1, 0), eps); + ASSERT_NEAR(1. / std::sqrt(2), R(1, 1), eps); } diff --git a/Tests/ProcessLib/RichardsMechanics/MicroporosityComputation.cpp b/Tests/ProcessLib/RichardsMechanics/MicroporosityComputation.cpp index 62145face6053c469d7ce1ce5200911fd272903d..ba02d607a84565f07a8bb9dde5d44cddce3d8a81 100644 --- a/Tests/ProcessLib/RichardsMechanics/MicroporosityComputation.cpp +++ b/Tests/ProcessLib/RichardsMechanics/MicroporosityComputation.cpp @@ -170,7 +170,7 @@ TEST(RichardsMechanics, computeMicroPorosity) { double const p_L = pressure_M.getValue(t); double const S_L_m_prev = saturation(state_prev.p_L_m); - //auto const [delta_phi_m, delta_e_sw, delta_sigma_sw, delta_p_L_m] = + // auto const [delta_phi_m, delta_e_sw, delta_sigma_sw, delta_p_L_m] = auto const state_increment = computeMicroPorosity<DisplacementDim>( I_2_C_el_inverse, rho_LR_m, // for simplification equal to rho_LR_M diff --git a/Tests/ProcessLib/TestJacobianAssembler.cpp b/Tests/ProcessLib/TestJacobianAssembler.cpp index a2a1483ff4ac5301a1c38be59913e0b545a39438..14b056d8f19ac1f8dcf36641af1f24d757045a50 100644 --- a/Tests/ProcessLib/TestJacobianAssembler.cpp +++ b/Tests/ProcessLib/TestJacobianAssembler.cpp @@ -7,14 +7,15 @@ * */ +#include <gtest/gtest.h> + #include <limits> #include <random> -#include <gtest/gtest.h> #include "MathLib/LinAlg/Eigen/EigenMapTools.h" -#include "ProcessLib/LocalAssemblerInterface.h" #include "ProcessLib/AnalyticalJacobianAssembler.h" #include "ProcessLib/CentralDifferencesJacobianAssembler.h" +#include "ProcessLib/LocalAssemblerInterface.h" //! Fills a vector with values whose absolute value is between \c abs_min and //! \c abs_max. @@ -28,10 +29,12 @@ void fillRandomlyConstrainedAbsoluteValues(std::vector<double>& xs, std::uniform_real_distribution<double> rnd(abs_min, abs_min + 2.0 * abs_range); - for (auto& x : xs) { + for (auto& x : xs) + { // v in [ abs_min, abs_min + 2 abs_range ] auto v = rnd(random_number_generator); - if (v > abs_max) { + if (v > abs_max) + { // produce negative values // (v - abs_range) in [ abs_min, abs_max ] v = -(v - abs_range); @@ -57,8 +60,8 @@ struct MatDiagX std::vector<double> const& y_data, std::vector<double>& dMdxTy_data) { - auto dMdxTy = - MathLib::createZeroedMatrix(dMdxTy_data, x_data.size(), x_data.size()); + auto dMdxTy = MathLib::createZeroedMatrix(dMdxTy_data, x_data.size(), + x_data.size()); dMdxTy.diagonal().noalias() = MathLib::toVector<Eigen::VectorXd>(y_data, y_data.size()); } @@ -97,8 +100,10 @@ struct MatXY { auto mat = MathLib::createZeroedMatrix(mat_data, x_data.size(), x_data.size()); - for (std::size_t r=0; r<x_data.size(); ++r) { - for (std::size_t c=0; c<x_data.size(); ++c) { + for (std::size_t r = 0; r < x_data.size(); ++r) + { + for (std::size_t c = 0; c < x_data.size(); ++c) + { mat(r, c) = x_data[r] * x_data[c]; } } @@ -117,10 +122,11 @@ struct MatXY auto const N = x_data.size(); auto const x_dot_y = MathLib::toVector<Eigen::VectorXd>(x_data, N).dot( MathLib::toVector<Eigen::VectorXd>(y_data, N)); - auto dMdxTy = - MathLib::createZeroedMatrix(dMdxTy_data, N, N); - for (std::size_t r=0; r<N; ++r) { - for (std::size_t c=0; c<N; ++c) { + auto dMdxTy = MathLib::createZeroedMatrix(dMdxTy_data, N, N); + for (std::size_t r = 0; r < N; ++r) + { + for (std::size_t c = 0; c < N; ++c) + { dMdxTy(r, c) = x_data[r] * y_data[c]; } dMdxTy(r, r) += x_dot_y; @@ -136,8 +142,9 @@ struct VecXRevX { vec_data = x_data; auto const N = x_data.size(); - for (std::size_t i=0; i<N; ++i) { - vec_data[i] *= x_data[N-i-1]; + for (std::size_t i = 0; i < N; ++i) + { + vec_data[i] *= x_data[N - i - 1]; } } @@ -152,9 +159,10 @@ struct VecXRevX auto mat = MathLib::createZeroedMatrix(mat_data, x_data.size(), x_data.size()); auto const N = x_data.size(); - for (std::size_t i=0; i<N; ++i) { - mat(i, i) += x_data[N-i-1]; - mat(N-i-1, i) += x_data[N-i-1]; + for (std::size_t i = 0; i < N; ++i) + { + mat(i, i) += x_data[N - i - 1]; + mat(N - i - 1, i) += x_data[N - i - 1]; } } }; @@ -179,8 +187,8 @@ struct MatDiagXSquared std::vector<double> const& y_data, std::vector<double>& dMdxTy_data) { - auto dMdxTy = - MathLib::createZeroedMatrix(dMdxTy_data, x_data.size(), x_data.size()); + auto dMdxTy = MathLib::createZeroedMatrix(dMdxTy_data, x_data.size(), + x_data.size()); for (std::size_t i = 0; i < x_data.size(); ++i) { @@ -208,7 +216,8 @@ struct VecXSquared { auto mat = MathLib::createZeroedMatrix(mat_data, x_data.size(), x_data.size()); - for (std::size_t i=0; i< x_data.size(); ++i) { + for (std::size_t i = 0; i < x_data.size(); ++i) + { mat(i, i) = 2.0 * x_data[i]; } } @@ -226,10 +235,11 @@ struct MatXSquaredShifted std::vector<double>& mat_data) { auto const N = x_data.size(); - auto mat = - MathLib::createZeroedMatrix(mat_data, N, N); - for (std::size_t r=0; r<N; ++r) { - for (std::size_t c=0; c<N; ++c) { + auto mat = MathLib::createZeroedMatrix(mat_data, N, N); + for (std::size_t r = 0; r < N; ++r) + { + for (std::size_t c = 0; c < N; ++c) + { auto const i = (r + c) % N; mat(r, i) = x_data[c] * x_data[c]; } @@ -246,10 +256,11 @@ struct MatXSquaredShifted std::vector<double>& dMdxTy_data) { auto const N = x_data.size(); - auto dMdxTy = - MathLib::createZeroedMatrix(dMdxTy_data, N, N); - for (std::size_t r=0; r<N; ++r) { - for (std::size_t c=0; c<N; ++c) { + auto dMdxTy = MathLib::createZeroedMatrix(dMdxTy_data, N, N); + for (std::size_t r = 0; r < N; ++r) + { + for (std::size_t c = 0; c < N; ++c) + { auto const i = (r + c) % N; dMdxTy(r, c) = 2.0 * x_data[c] * y_data[i]; } @@ -459,7 +470,8 @@ public: local_Jac_data = local_JacM_data; auto const N = local_Jac_data.size(); - for (std::size_t i = 0; i < N; ++i) { + for (std::size_t i = 0; i < N; ++i) + { local_Jac_data[i] += local_JacK_data[i] - local_JacB_data[i]; } @@ -483,7 +495,7 @@ public: static const bool asmb = true; }; -template<class LocAsm> +template <class LocAsm> struct ProcessLibCentralDifferencesJacobianAssembler : public ::testing::Test { static void test() @@ -522,7 +534,7 @@ private: const double dxdot_dx, const double dx_dx) { ProcessLib::AnalyticalJacobianAssembler jac_asm_ana; - ProcessLib::CentralDifferencesJacobianAssembler jac_asm_cd({ 1e-8 }); + ProcessLib::CentralDifferencesJacobianAssembler jac_asm_cd({1e-8}); LocAsm loc_asm; double const eps = std::numeric_limits<double>::epsilon(); @@ -546,25 +558,28 @@ private: dx_dx, M_data_ana, K_data_ana, b_data_ana, Jac_data_ana); - if (LocAsm::asmM) { - ASSERT_EQ(x.size()*x.size(), M_data_cd.size()); - ASSERT_EQ(x.size()*x.size(), M_data_ana.size()); + if (LocAsm::asmM) + { + ASSERT_EQ(x.size() * x.size(), M_data_cd.size()); + ASSERT_EQ(x.size() * x.size(), M_data_ana.size()); for (std::size_t i = 0; i < x.size() * x.size(); ++i) { EXPECT_NEAR(M_data_ana[i], M_data_cd[i], eps); } } - if (LocAsm::asmK) { - ASSERT_EQ(x.size()*x.size(), K_data_cd.size()); - ASSERT_EQ(x.size()*x.size(), K_data_ana.size()); + if (LocAsm::asmK) + { + ASSERT_EQ(x.size() * x.size(), K_data_cd.size()); + ASSERT_EQ(x.size() * x.size(), K_data_ana.size()); for (std::size_t i = 0; i < x.size() * x.size(); ++i) { EXPECT_NEAR(K_data_ana[i], K_data_cd[i], eps); } } - if (LocAsm::asmb) { + if (LocAsm::asmb) + { ASSERT_EQ(x.size(), b_data_cd.size()); ASSERT_EQ(x.size(), b_data_ana.size()); for (std::size_t i = 0; i < x.size(); ++i) @@ -573,9 +588,10 @@ private: } } - ASSERT_EQ(x.size()*x.size(), Jac_data_cd.size()); - ASSERT_EQ(x.size()*x.size(), Jac_data_ana.size()); - for (std::size_t i=0; i<x.size()*x.size(); ++i) { + ASSERT_EQ(x.size() * x.size(), Jac_data_cd.size()); + ASSERT_EQ(x.size() * x.size(), Jac_data_ana.size()); + for (std::size_t i = 0; i < x.size() * x.size(); ++i) + { // DBUG("{:d}, {:g}, {:g}", i, Jac_data_ana[i], Jac_data_cd[i]); EXPECT_NEAR(Jac_data_ana[i], Jac_data_cd[i], LocAsm::getTol()); } diff --git a/Tests/TestTools.cpp b/Tests/TestTools.cpp index 06a5bdd150f273866a27970934dcc7a830e1b7b4..6d289db37eb48e2637536550ef6ab19a7a108ea6 100644 --- a/Tests/TestTools.cpp +++ b/Tests/TestTools.cpp @@ -7,10 +7,10 @@ * */ -#include <boost/property_tree/xml_parser.hpp> - #include "Tests/TestTools.h" +#include <boost/property_tree/xml_parser.hpp> + namespace Tests { boost::property_tree::ptree readXml(const char xml[]) @@ -20,7 +20,7 @@ boost::property_tree::ptree readXml(const char xml[]) boost::property_tree::read_xml( xml_str, ptree, boost::property_tree::xml_parser::no_comments | - boost::property_tree::xml_parser::trim_whitespace); + boost::property_tree::xml_parser::trim_whitespace); return ptree; } diff --git a/Tests/testrunner.cpp b/Tests/testrunner.cpp index 2277add78fb85aac39258441bc49662507020533..35e99d19d0a27beef5ae5f2c50b64d64c275aab9 100644 --- a/Tests/testrunner.cpp +++ b/Tests/testrunner.cpp @@ -12,6 +12,7 @@ * */ +#include <gtest/gtest.h> #include <spdlog/spdlog.h> #include <clocale> @@ -20,7 +21,6 @@ #include "BaseLib/Error.h" #include "BaseLib/Logging.h" #include "NumLib/DOF/GlobalMatrixProviders.h" -#include "gtest/gtest.h" #ifdef OGS_BUILD_GUI #include <QCoreApplication> @@ -51,8 +51,8 @@ int main(int argc, char* argv[]) QCoreApplication app(argc, argv, false); #endif - ApplicationsLib::LinearSolverLibrarySetup linear_solver_library_setup( - argc, argv); + ApplicationsLib::LinearSolverLibrarySetup linear_solver_library_setup(argc, + argv); BaseLib::setConsoleLogLevel(logLevel); spdlog::set_pattern("%^%l:%$ %v"); @@ -71,7 +71,7 @@ int main(int argc, char* argv[]) try { // start google test - testing::InitGoogleTest ( &argc, argv ); + testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } catch (char* e) diff --git a/Tests/xdmfdiff/CMakeLists.txt b/Tests/xdmfdiff/CMakeLists.txt index 7b947b010404e2d25de8b655049a1dea6e7c89db..b7b08968667fb787ae3bad9d9ba88b6a60ac08d5 100644 --- a/Tests/xdmfdiff/CMakeLists.txt +++ b/Tests/xdmfdiff/CMakeLists.txt @@ -1,3 +1,3 @@ add_executable(xdmfdiff xdmfdiff.cpp) -target_link_libraries(xdmfdiff OgsXdmf std::filesystem tclap) +target_link_libraries(xdmfdiff OgsXdmf GitInfoLib std::filesystem tclap) install(PROGRAMS $<TARGET_FILE:xdmfdiff> DESTINATION bin) diff --git a/Tests/xdmfdiff/xdmfdiff.cpp b/Tests/xdmfdiff/xdmfdiff.cpp index 16d2ac9d8493a2b2394c99f805b05fbcda9b6431..b7966fa3e3b8013f9a45d3aa225b8181539f30ee 100644 --- a/Tests/xdmfdiff/xdmfdiff.cpp +++ b/Tests/xdmfdiff/xdmfdiff.cpp @@ -1,12 +1,11 @@ /** * \file * \copyright - * Copyright (c) 2015-2021, OpenGeoSys Community (http://www.opengeosys.org) + * Copyright (c) 2012-2021, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license */ - #include <tclap/CmdLine.h> #include <Xdmf.hpp> @@ -24,6 +23,8 @@ #include <memory> #include <sstream> #include <tuple> + +#include "InfoLib/GitInfo.h" // See https://stackoverflow.com/a/8513803/2706707 template <typename... Containers> auto zip(Containers&&... containers) -> boost::iterator_range< @@ -54,14 +55,13 @@ struct Args auto parseCommandLine(int argc, char* argv[]) -> Args { TCLAP::CmdLine cmd( - "XdmfDiff software.\n" - "Copyright (c) 2015-2020, OpenGeoSys Community " - "(http://www.opengeosys.org) " - "Distributed under a Modified BSD License. " - "See accompanying file LICENSE.txt or " - "http://www.opengeosys.org/project/license", - ' ', - "0.1"); + "XdmfDiff software.\n\n" + "OpenGeoSys-6 software, version " + + GitInfoLib::GitInfo::ogs_version + + ".\n" + "Copyright (c) 2012-2021, OpenGeoSys Community " + "(http://www.opengeosys.org)", + ' ', GitInfoLib::GitInfo::ogs_version); TCLAP::UnlabeledValueArg<std::string> xdmf_input_a_arg( "input-file-a", "Path to the Xdmf input file.", true, "", "XDMF FILE"); @@ -299,4 +299,4 @@ int main(int argc, char* argv[]) } return EXIT_SUCCESS; -} \ No newline at end of file +}