From c9903490cafa8329ef6c208de936f4fdc40abdf9 Mon Sep 17 00:00:00 2001 From: Kursat Yurt Date: Thu, 16 Mar 2023 23:54:35 +0100 Subject: [PATCH 1/8] Add myself to authors --- AUTHORS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AUTHORS.md b/AUTHORS.md index 85b2334d5e6..2c2c9d7982e 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -94,6 +94,7 @@ Johannes Blühdorn JonathanSmith1936 Josy P. Pullockara Kedar Naik +Kürşat Yurt LaSerpe Lennaert Tol Lisa Kusch @@ -158,4 +159,3 @@ srcopela tobadavid vfrancesmolla ``` - From 2afab593b719e4030ca8e73558e1fad0284ddef6 Mon Sep 17 00:00:00 2001 From: Kursat Yurt Date: Thu, 16 Mar 2023 23:54:50 +0100 Subject: [PATCH 2/8] Add python style file --- .pep8 | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 .pep8 diff --git a/.pep8 b/.pep8 new file mode 100644 index 00000000000..998b0179c80 --- /dev/null +++ b/.pep8 @@ -0,0 +1,6 @@ +[pycodestyle] +max_line_length = 120 +ignore = E402 +in-place = true +aggressive = 2 +recursive = true From b48fe3e25aeb35b998b31bd5f4c771ddff6a8a90 Mon Sep 17 00:00:00 2001 From: Kursat Yurt Date: Thu, 16 Mar 2023 23:55:13 +0100 Subject: [PATCH 3/8] Never sort the includes --- .clang-format | 1 + 1 file changed, 1 insertion(+) diff --git a/.clang-format b/.clang-format index a0cdb6fc60c..cb363900eb6 100644 --- a/.clang-format +++ b/.clang-format @@ -2,3 +2,4 @@ BasedOnStyle: Google PointerAlignment: Left DerivePointerAlignment: false ColumnLimit: 120 +SortIncludes: Never From 1a832351364967c34579148d6b00ad2d0e22844d Mon Sep 17 00:00:00 2001 From: Kursat Yurt Date: Thu, 16 Mar 2023 23:55:32 +0100 Subject: [PATCH 4/8] Add pre-commit hooks --- .github/pull_request_template.md | 3 +- .github/workflows/code-style.yml | 30 ++++++++++++++++ .pre-commit-config.yaml | 62 ++++++++++++++++++++++++++++++++ 3 files changed, 94 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/code-style.yml create mode 100644 .pre-commit-config.yaml diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 6aab0240f56..129fb1c1723 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,6 +1,6 @@ ## Proposed Changes *Give a brief overview of your contribution here in a few sentences.* - + ## Related Work @@ -14,5 +14,6 @@ - [ ] I am submitting my contribution to the develop branch. - [ ] My contribution generates no new compiler warnings (try with --warnlevel=3 when using meson). - [ ] My contribution is commented and consistent with SU2 style (https://su2code.github.io/docs_v7/Style-Guide/). +- [ ] I used the pre-commit hook to prevent dirty commits and used `pre-commit run --all` to format old commits. - [ ] I have added a test case that demonstrates my contribution, if necessary. - [ ] I have updated appropriate documentation (Tutorials, Docs Page, config_template.cpp), if necessary. diff --git a/.github/workflows/code-style.yml b/.github/workflows/code-style.yml new file mode 100644 index 00000000000..a0080f08981 --- /dev/null +++ b/.github/workflows/code-style.yml @@ -0,0 +1,30 @@ +name: Code Style +on: + pull_request: + paths: + - "**.[ch]pp" + - "**.[ch]" + - "**.cfg" + - "**.py" + +jobs: + formatting: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v3 + - name: Setup python + uses: actions/setup-python@v4 + with: + python-version: '3.10' + check-latest: true + - name: Install pre-commit + run: pip install pre-commit + - name: Run checks + run: pre-commit run -a -v + - name: Git status + if: always() + run: git status + - name: Full diff + if: always() + run: git diff diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 00000000000..1e55bb83a10 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,62 @@ +repos: + # Official repo for the clang-format hook + - repo: https://github.com/pre-commit/mirrors-clang-format + rev: "v15.0.7" + hooks: + - id: clang-format + exclude: | + (?x)^( + ^Common/include/CConfig.hpp| + ^Common/include/option_structure.hpp| + ^Common/src/CConfig.cpp| + ^SU2_CFD| + ^externals| + ^subprojects| + ^TestCases| + ^legacy + ) + types_or: [c++, c] + # black repo for python formatting + - repo: https://github.com/ambv/black + rev: 22.6.0 + hooks: + - id: black + exclude: | + (?x)^( + ^SU2_CFD| + ^externals| + ^subprojects| + ^TestCases| + ^legacy + ) + # Official repo for default hooks + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: "v4.4.0" + hooks: + - id: mixed-line-ending + exclude: | + (?x)^( + ^SU2_CFD| + ^externals| + ^subprojects| + ^TestCases| + ^legacy + ) + - id: trailing-whitespace + exclude: | + (?x)^( + ^SU2_CFD| + ^externals| + ^subprojects| + ^TestCases| + ^legacy + ) + - id: end-of-file-fixer + exclude: | + (?x)^( + ^SU2_CFD| + ^externals| + ^subprojects| + ^TestCases| + ^legacy + ) From 7c27b228b7247a55cf82cd4f38955024f5148651 Mon Sep 17 00:00:00 2001 From: Kursat Yurt Date: Thu, 16 Mar 2023 23:56:03 +0100 Subject: [PATCH 5/8] Reformat files --- .github/ISSUE_TEMPLATE/bug_report.md | 1 - .github/release.yml | 1 - .github/workflows/release-management.yml | 1 - .lgtm.yml | 2 +- .travis.yml | 8 +- CODE_OF_CONDUCT.md | 5 +- COPYING | 18 +- Common/include/adt/CADTBaseClass.hpp | 30 +- Common/include/adt/CADTComparePointClass.hpp | 21 +- Common/include/adt/CADTElemClass.hpp | 162 +- Common/include/adt/CADTNodeClass.hpp | 19 +- Common/include/adt/CADTPointsOnlyClass.hpp | 33 +- Common/include/adt/CBBoxTargetClass.hpp | 33 +- Common/include/basic_types/ad_structure.hpp | 914 +- .../basic_types/datatype_structure.hpp | 218 +- Common/include/code_config.hpp | 36 +- Common/include/containers/C2DContainer.hpp | 507 +- .../containers/CFastFindAndEraseQueue.hpp | 23 +- Common/include/containers/CVertexMap.hpp | 24 +- .../containers/container_decorators.hpp | 126 +- Common/include/fem/fem_cgns_elements.hpp | 313 +- .../fem/fem_gauss_jacobi_quadrature.hpp | 25 +- Common/include/fem/fem_geometry_structure.hpp | 991 +- Common/include/fem/fem_standard_element.hpp | 1296 +- .../fem/geometry_structure_fem_part.hpp | 116 +- Common/include/geometry/CDummyGeometry.hpp | 9 +- Common/include/geometry/CGeometry.hpp | 760 +- .../include/geometry/CMultiGridGeometry.hpp | 59 +- Common/include/geometry/CMultiGridQueue.hpp | 23 +- Common/include/geometry/CPhysicalGeometry.hpp | 424 +- .../include/geometry/dual_grid/CDualGrid.hpp | 25 +- Common/include/geometry/dual_grid/CEdge.hpp | 57 +- Common/include/geometry/dual_grid/CPoint.hpp | 261 +- .../geometry/dual_grid/CTurboVertex.hpp | 49 +- Common/include/geometry/dual_grid/CVertex.hpp | 74 +- Common/include/geometry/elements/CElement.hpp | 519 +- .../geometry/elements/CElementProperty.hpp | 49 +- .../geometry/elements/CGaussVariable.hpp | 24 +- .../geometry/meshreader/CBoxMeshReaderFVM.hpp | 14 +- .../meshreader/CCGNSMeshReaderFVM.hpp | 69 +- .../geometry/meshreader/CMeshReaderFVM.hpp | 83 +- .../meshreader/CRectangularMeshReaderFVM.hpp | 14 +- .../meshreader/CSU2ASCIIMeshReaderFVM.hpp | 41 +- .../geometry/primal_grid/CHexahedron.hpp | 17 +- Common/include/geometry/primal_grid/CLine.hpp | 14 +- .../geometry/primal_grid/CPrimalGrid.hpp | 75 +- .../primal_grid/CPrimalGridBoundFEM.hpp | 75 +- .../geometry/primal_grid/CPrimalGridFEM.hpp | 74 +- .../include/geometry/primal_grid/CPrism.hpp | 16 +- .../include/geometry/primal_grid/CPyramid.hpp | 42 +- .../geometry/primal_grid/CQuadrilateral.hpp | 16 +- .../geometry/primal_grid/CTetrahedron.hpp | 16 +- .../geometry/primal_grid/CTriangle.hpp | 19 +- .../geometry/primal_grid/CVertexMPI.hpp | 6 +- Common/include/graph_coloring_structure.hpp | 10 +- .../grid_movement/CBSplineBlending.hpp | 21 +- .../include/grid_movement/CBezierBlending.hpp | 16 +- .../grid_movement/CFreeFormBlending.hpp | 20 +- .../include/grid_movement/CFreeFormDefBox.hpp | 298 +- .../include/grid_movement/CGridMovement.hpp | 12 +- .../grid_movement/CSurfaceMovement.hpp | 125 +- .../grid_movement/CVolumetricMovement.hpp | 109 +- .../interface_interpolation/CInterpolator.hpp | 52 +- .../CInterpolatorFactory.hpp | 8 +- .../CIsoparametric.hpp | 27 +- .../interface_interpolation/CMirror.hpp | 9 +- .../CNearestNeighbor.hpp | 11 +- .../CRadialBasisFunction.hpp | 33 +- .../interface_interpolation/CSlidingMesh.hpp | 11 +- .../linear_algebra/CMatrixVectorProduct.hpp | 32 +- .../include/linear_algebra/CPastixWrapper.hpp | 90 +- .../linear_algebra/CPreconditioner.hpp | 137 +- Common/include/linear_algebra/CSysMatrix.hpp | 429 +- Common/include/linear_algebra/CSysMatrix.inl | 160 +- Common/include/linear_algebra/CSysSolve.hpp | 136 +- Common/include/linear_algebra/CSysSolve_b.hpp | 7 +- Common/include/linear_algebra/CSysVector.hpp | 13 +- .../include/linear_algebra/blas_structure.hpp | 192 +- .../linear_algebra/vector_expressions.hpp | 142 +- Common/include/option_structure.inl | 1044 +- .../include/parallelization/mpi_structure.cpp | 76 +- .../include/parallelization/mpi_structure.hpp | 12 +- .../include/parallelization/omp_structure.hpp | 80 +- .../parallelization/special_vectorization.hpp | 93 +- .../include/parallelization/vectorization.hpp | 244 +- Common/include/toolboxes/C1DInterpolation.hpp | 75 +- .../include/toolboxes/CLinearPartitioner.hpp | 51 +- .../toolboxes/CQuasiNewtonInvLeastSquares.hpp | 100 +- Common/include/toolboxes/CSquareMatrixCM.hpp | 34 +- Common/include/toolboxes/CSymmetricMatrix.hpp | 24 +- .../include/toolboxes/MMS/CIncTGVSolution.hpp | 25 +- .../toolboxes/MMS/CInviscidVortexSolution.hpp | 43 +- .../toolboxes/MMS/CMMSIncEulerSolution.hpp | 39 +- .../toolboxes/MMS/CMMSIncNSSolution.hpp | 41 +- .../MMS/CMMSNSTwoHalfCirclesSolution.hpp | 53 +- .../MMS/CMMSNSTwoHalfSpheresSolution.hpp | 55 +- .../toolboxes/MMS/CMMSNSUnitQuadSolution.hpp | 87 +- .../MMS/CMMSNSUnitQuadSolutionWallBC.hpp | 44 +- .../toolboxes/MMS/CNSUnitQuadSolution.hpp | 29 +- .../toolboxes/MMS/CRinglebSolution.hpp | 31 +- Common/include/toolboxes/MMS/CTGVSolution.hpp | 29 +- .../toolboxes/MMS/CUserDefinedSolution.hpp | 23 +- .../toolboxes/MMS/CVerificationSolution.hpp | 61 +- .../include/toolboxes/allocation_toolbox.hpp | 31 +- Common/include/toolboxes/geometry_toolbox.hpp | 109 +- Common/include/toolboxes/graph_toolbox.hpp | 383 +- Common/include/toolboxes/ndflattener.hpp | 26 +- Common/include/toolboxes/printing_toolbox.hpp | 105 +- Common/include/wall_model.hpp | 103 +- Common/lib/Makefile.am | 1 - Common/src/adt/CADTBaseClass.cpp | 115 +- Common/src/adt/CADTElemClass.cpp | 2058 +-- Common/src/adt/CADTPointsOnlyClass.cpp | 130 +- Common/src/basic_types/ad_structure.cpp | 30 +- Common/src/containers/CFileReaderLUT.cpp | 7 +- Common/src/fem/fem_cgns_elements.cpp | 1474 +- .../src/fem/fem_gauss_jacobi_quadrature.cpp | 549 +- Common/src/fem/fem_geometry_structure.cpp | 5126 +++--- Common/src/fem/fem_integration_rules.cpp | 12950 ++++++++++++---- Common/src/fem/fem_standard_element.cpp | 2782 ++-- Common/src/fem/fem_wall_distance.cpp | 182 +- Common/src/fem/fem_work_estimate_metis.cpp | 22 +- .../src/fem/geometry_structure_fem_part.cpp | 2913 ++-- Common/src/geometry/CDummyGeometry.cpp | 10 +- Common/src/geometry/CGeometry.cpp | 2643 ++-- Common/src/geometry/CMultiGridGeometry.cpp | 423 +- Common/src/geometry/CMultiGridQueue.cpp | 50 +- Common/src/geometry/CPhysicalGeometry.cpp | 7524 +++++---- Common/src/geometry/dual_grid/CDualGrid.cpp | 2 +- Common/src/geometry/dual_grid/CEdge.cpp | 49 +- Common/src/geometry/dual_grid/CPoint.cpp | 46 +- .../src/geometry/dual_grid/CTurboVertex.cpp | 15 +- Common/src/geometry/dual_grid/CVertex.cpp | 22 +- Common/src/geometry/elements/CElement.cpp | 22 +- Common/src/geometry/elements/CHEXA8.cpp | 217 +- Common/src/geometry/elements/CLINE.cpp | 22 +- Common/src/geometry/elements/CPRISM6.cpp | 161 +- Common/src/geometry/elements/CPYRAM5.cpp | 119 +- Common/src/geometry/elements/CPYRAM6.cpp | 203 +- Common/src/geometry/elements/CQUAD4.cpp | 70 +- Common/src/geometry/elements/CTETRA1.cpp | 49 +- Common/src/geometry/elements/CTETRA4.cpp | 68 +- Common/src/geometry/elements/CTRIA1.cpp | 42 +- Common/src/geometry/elements/CTRIA3.cpp | 48 +- .../geometry/meshreader/CBoxMeshReaderFVM.cpp | 157 +- .../meshreader/CCGNSMeshReaderFVM.cpp | 530 +- .../geometry/meshreader/CMeshReaderFVM.cpp | 9 +- .../meshreader/CRectangularMeshReaderFVM.cpp | 81 +- .../meshreader/CSU2ASCIIMeshReaderFVM.cpp | 498 +- Common/src/geometry/meson.build | 1 - .../src/geometry/primal_grid/CHexahedron.cpp | 22 +- Common/src/geometry/primal_grid/CLine.cpp | 6 +- .../src/geometry/primal_grid/CPrimalGrid.cpp | 14 +- .../primal_grid/CPrimalGridBoundFEM.cpp | 60 +- .../geometry/primal_grid/CPrimalGridFEM.cpp | 224 +- Common/src/geometry/primal_grid/CPrism.cpp | 8 +- Common/src/geometry/primal_grid/CPyramid.cpp | 12 +- .../geometry/primal_grid/CQuadrilateral.cpp | 11 +- .../src/geometry/primal_grid/CTetrahedron.cpp | 11 +- Common/src/geometry/primal_grid/CTriangle.cpp | 6 +- .../src/geometry/primal_grid/CVertexMPI.cpp | 4 +- Common/src/graph_coloring_structure.cpp | 103 +- Common/src/grid_movement/CBSplineBlending.cpp | 96 +- Common/src/grid_movement/CBezierBlending.cpp | 86 +- .../src/grid_movement/CFreeFormBlending.cpp | 4 +- Common/src/grid_movement/CFreeFormDefBox.cpp | 955 +- Common/src/grid_movement/CGridMovement.cpp | 4 +- Common/src/grid_movement/CSurfaceMovement.cpp | 3226 ++-- .../src/grid_movement/CVolumetricMovement.cpp | 1589 +- .../interface_interpolation/CInterpolator.cpp | 6 +- .../CInterpolatorFactory.cpp | 46 +- .../CIsoparametric.cpp | 291 +- .../src/interface_interpolation/CMirror.cpp | 96 +- .../CNearestNeighbor.cpp | 143 +- .../CRadialBasisFunction.cpp | 393 +- .../interface_interpolation/CSlidingMesh.cpp | 746 +- Common/src/linear_algebra/CPastixWrapper.cpp | 230 +- Common/src/linear_algebra/CSysMatrix.cpp | 636 +- Common/src/linear_algebra/CSysSolve.cpp | 490 +- Common/src/linear_algebra/CSysSolve_b.cpp | 9 +- Common/src/linear_algebra/CSysVector.cpp | 2 +- Common/src/linear_algebra/blas_structure.cpp | 101 +- Common/src/meson.build | 22 +- Common/src/toolboxes/C1DInterpolation.cpp | 181 +- Common/src/toolboxes/CLinearPartitioner.cpp | 31 +- Common/src/toolboxes/CSquareMatrixCM.cpp | 54 +- Common/src/toolboxes/CSymmetricMatrix.cpp | 103 +- Common/src/toolboxes/MMS/CIncTGVSolution.cpp | 80 +- .../toolboxes/MMS/CInviscidVortexSolution.cpp | 131 +- .../toolboxes/MMS/CMMSIncEulerSolution.cpp | 94 +- .../src/toolboxes/MMS/CMMSIncNSSolution.cpp | 111 +- .../MMS/CMMSNSTwoHalfCirclesSolution.cpp | 205 +- .../MMS/CMMSNSTwoHalfSpheresSolution.cpp | 238 +- .../toolboxes/MMS/CMMSNSUnitQuadSolution.cpp | 265 +- .../MMS/CMMSNSUnitQuadSolutionWallBC.cpp | 147 +- .../src/toolboxes/MMS/CNSUnitQuadSolution.cpp | 103 +- Common/src/toolboxes/MMS/CRinglebSolution.cpp | 160 +- Common/src/toolboxes/MMS/CTGVSolution.cpp | 112 +- .../toolboxes/MMS/CUserDefinedSolution.cpp | 33 +- .../toolboxes/MMS/CVerificationSolution.cpp | 119 +- .../CMMSIncEulerSolution.py | 29 +- .../CreateMMSSourceTerms/CMMSIncNSSolution.py | 38 +- .../CMMSNSTwoHalfCirclesSolution.mw | 2 +- .../CMMSNSTwoHalfSpheresSolution.mw | 2 +- .../CMMSNSUnitQuadSolution.mw | 2 +- .../CMMSNSUnitQuadSolutionWallBC.mw | 2 +- Common/src/toolboxes/printing_toolbox.cpp | 65 +- Common/src/wall_model.cpp | 304 +- Docs/docmain.hpp | 2 +- QuickStart/inv_NACA0012.cfg | 8 +- SU2_DEF/src/SU2_DEF.cpp | 1 - SU2_DEF/src/drivers/CDeformationDriver.cpp | 90 +- .../src/drivers/CDiscAdjDeformationDriver.cpp | 32 +- SU2_DOT/src/SU2_DOT.cpp | 1 - SU2_GEO/include/SU2_GEO.hpp | 1 - SU2_GEO/src/SU2_GEO.cpp | 1363 +- SU2_GEO/src/meson.build | 2 +- SU2_IDE/Eclipse/README | 20 +- SU2_PY/FSI_tools/FSIInterface.py | 3555 +++-- SU2_PY/FSI_tools/FSI_config.py | 103 +- SU2_PY/OptimalPropeller.py | 245 +- SU2_PY/SU2/__init__.py | 10 +- SU2_PY/SU2/eval/__init__.py | 17 +- SU2_PY/SU2/eval/design.py | 520 +- SU2_PY/SU2/eval/functions.py | 750 +- SU2_PY/SU2/eval/gradients.py | 915 +- SU2_PY/SU2/io/__init__.py | 8 +- SU2_PY/SU2/io/config.py | 1190 +- SU2_PY/SU2/io/config_options.py | 187 +- SU2_PY/SU2/io/data.py | 403 +- SU2_PY/SU2/io/filelock.py | 81 +- SU2_PY/SU2/io/historyMap.py | 3491 +++-- SU2_PY/SU2/io/redirect.py | 221 +- SU2_PY/SU2/io/state.py | 385 +- SU2_PY/SU2/io/tools.py | 1164 +- SU2_PY/SU2/opt/project.py | 394 +- SU2_PY/SU2/opt/scipy_tools.py | 494 +- SU2_PY/SU2/run/__init__.py | 19 +- SU2_PY/SU2/run/adjoint.py | 83 +- SU2_PY/SU2/run/deform.py | 78 +- SU2_PY/SU2/run/direct.py | 133 +- SU2_PY/SU2/run/geometry.py | 86 +- SU2_PY/SU2/run/interface.py | 199 +- SU2_PY/SU2/run/merge.py | 60 +- SU2_PY/SU2/run/projection.py | 89 +- SU2_PY/SU2/util/__init__.py | 14 +- SU2_PY/SU2/util/bunch.py | 497 +- SU2_PY/SU2/util/filter_adjoint.py | 479 +- SU2_PY/SU2/util/lhc_unif.py | 112 +- SU2_PY/SU2/util/misc.py | 17 +- SU2_PY/SU2/util/mp_eval.py | 133 +- SU2_PY/SU2/util/ordered_bunch.py | 516 +- SU2_PY/SU2/util/ordered_dict.py | 82 +- SU2_PY/SU2/util/plot.py | 56 +- SU2_PY/SU2/util/polarSweepLib.py | 1620 +- SU2_PY/SU2/util/switch.py | 58 +- SU2_PY/SU2/util/which.py | 21 +- SU2_PY/SU2_CFD.py | 188 +- SU2_PY/SU2_Nastran/pysu2_nastran.py | 2013 +-- SU2_PY/change_version_number.py | 99 +- SU2_PY/compute_multipoint.py | 31 +- SU2_PY/compute_polar.py | 473 +- SU2_PY/compute_stability.py | 49 +- SU2_PY/compute_uncertainty.py | 96 +- SU2_PY/config_gui.py | 550 +- SU2_PY/continuous_adjoint.py | 113 +- SU2_PY/convert_to_csv.py | 31 +- SU2_PY/direct_differentiation.py | 131 +- SU2_PY/discrete_adjoint.py | 193 +- SU2_PY/documentation.txt | 50 +- SU2_PY/finite_differences.py | 107 +- SU2_PY/fsi_computation.py | 354 +- SU2_PY/merge_solution.py | 30 +- SU2_PY/mesh_deformation.py | 39 +- SU2_PY/package_tests.py | 216 +- SU2_PY/parallel_computation.py | 57 +- SU2_PY/parallel_computation_fsi.py | 57 +- SU2_PY/parse_config.py | 469 +- SU2_PY/profiling.py | 107 +- SU2_PY/pySU2/numpy.i | 1 - SU2_PY/set_ffd_design_var.py | 564 +- SU2_PY/shape_optimization.py | 328 +- SU2_PY/topology_optimization.py | 647 +- SU2_PY/updateHistoryMap.py | 89 +- SU2_SOL/include/SU2_SOL.hpp | 5 +- SU2_SOL/src/SU2_SOL.cpp | 558 +- .../Common/containers/CLookupTable_tests.cpp | 36 +- UnitTests/Common/geometry/CGeometry_test.cpp | 68 +- .../geometry/dual_grid/CDualGrid_tests.cpp | 26 +- .../primal_grid/CPrimalGrid_tests.cpp | 50 +- UnitTests/Common/simple_ad_test.cpp | 5 +- UnitTests/Common/simple_directdiff_test.cpp | 4 +- .../toolboxes/C1DInterpolation_tests.cpp | 18 +- .../CQuasiNewtonInvLeastSquares_tests.cpp | 32 +- .../Common/toolboxes/ndflattener_tests.cpp | 118 +- UnitTests/Common/vectorization.cpp | 35 +- UnitTests/SU2_CFD/gradients.cpp | 35 +- .../SU2_CFD/numerics/CNumerics_tests.cpp | 12 +- UnitTests/SU2_CFD/windowing.cpp | 8 +- UnitTests/UnitQuadTestCase.hpp | 6 +- UnitTests/test_driver.cpp | 3 +- docker/build/Dockerfile | 2 +- docker/build/compileSU2.sh | 8 +- docker/test/runTests.sh | 5 +- doxyfile | 4 +- meson.py | 45 +- meson_scripts/check_dir.py | 14 +- meson_scripts/extract_file.py | 106 +- meson_scripts/init.py | 463 +- preconfigure.py | 208 +- 310 files changed, 52115 insertions(+), 43626 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 4f53a6d0449..13c3dd26f57 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -26,4 +26,3 @@ assignees: '' - C++ compiler and version: [e.g., g++ (GCC) 4.8.5] - MPI implementation and version: [e.g., OpenMPI 3.0.0] - SU2 Version: [e.g., v6.2.0] - diff --git a/.github/release.yml b/.github/release.yml index 4ec929fc17c..09557097401 100644 --- a/.github/release.yml +++ b/.github/release.yml @@ -17,4 +17,3 @@ changelog: - title: 'Other Changes' labels: - "*" - diff --git a/.github/workflows/release-management.yml b/.github/workflows/release-management.yml index 0babf1c46b2..46a618f9a6c 100644 --- a/.github/workflows/release-management.yml +++ b/.github/workflows/release-management.yml @@ -65,4 +65,3 @@ jobs: asset_path: ${{matrix.os_bin}}.zip asset_name: SU2-${{ steps.update_release.outputs.tagname }}-${{matrix.os_bin}}.zip asset_content_type: application/zip - diff --git a/.lgtm.yml b/.lgtm.yml index 8489adfaea0..2179d4ea710 100644 --- a/.lgtm.yml +++ b/.lgtm.yml @@ -1,7 +1,7 @@ extraction: cpp: prepare: - packages: + packages: - libboost-all-dev configure: command: diff --git a/.travis.yml b/.travis.yml index 28481849073..f10e08bc47f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,10 +6,10 @@ sudo: required language: c++ -cache: +cache: - ccache - pip - - directories: + - directories: - $HOME/.pyenv_cache compiler: @@ -19,7 +19,7 @@ notifications: email: recipients: - su2code-dev@lists.stanford.edu - + branches: only: - develop @@ -81,7 +81,7 @@ before_script: # Get the tutorial cases - git clone --depth=1 -b develop https://github.com/su2code/su2code.github.io ./Tutorials - + # Enter the SU2/TestCases/ directory, which is now ready to run - cd TestCases/ diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 174a61f6120..c22c88372a9 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -28,7 +28,7 @@ Examples of unacceptable behavior by participants include: * Trolling, insulting/derogatory comments, and personal or political attacks. * Public or private harassment. * Publishing others' private information, such as a physical or electronic - address, without explicit permission. + address, without explicit permission. * Other conduct which could reasonably be considered inappropriate in a professional setting. @@ -67,7 +67,7 @@ faith may face temporary or permanent repercussions as determined by other members of the project's leadership. Consequences may include: -* Downgrade or removal of repository permissions such as admin and write +* Downgrade or removal of repository permissions such as admin and write permissions. * Removal from the su2code organization on Github. * Being blocked from the su2code repository. @@ -79,4 +79,3 @@ This Code of Conduct is adapted from the [Contributor Covenant][homepage], versi available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html [homepage]: https://www.contributor-covenant.org - diff --git a/COPYING b/COPYING index fe17b67bd4e..20fb9c7da21 100644 --- a/COPYING +++ b/COPYING @@ -55,7 +55,7 @@ modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. - + Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a @@ -111,7 +111,7 @@ modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. - + GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION @@ -158,7 +158,7 @@ Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. - + 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 @@ -216,7 +216,7 @@ instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. - + Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. @@ -267,7 +267,7 @@ Library will still fall under Section 6.) distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. - + 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work @@ -329,7 +329,7 @@ restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. - + 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined @@ -370,7 +370,7 @@ subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. - + 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or @@ -422,7 +422,7 @@ conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. - + 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is @@ -455,4 +455,4 @@ FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - END OF TERMS AND CONDITIONS \ No newline at end of file + END OF TERMS AND CONDITIONS diff --git a/Common/include/adt/CADTBaseClass.hpp b/Common/include/adt/CADTBaseClass.hpp index e1c95a5cc42..9a10f9fce54 100644 --- a/Common/include/adt/CADTBaseClass.hpp +++ b/Common/include/adt/CADTBaseClass.hpp @@ -43,10 +43,10 @@ using namespace std; * \author E. van der Weide */ class CADTBaseClass { -protected: - unsigned long nLeaves; /*!< \brief Number of leaves in the ADT. */ - unsigned short nDimADT; /*!< \brief Number of dimensions of the ADT. */ - bool isEmpty; /*!< \brief Whether or not the ADT is empty. */ + protected: + unsigned long nLeaves; /*!< \brief Number of leaves in the ADT. */ + unsigned short nDimADT; /*!< \brief Number of dimensions of the ADT. */ + bool isEmpty; /*!< \brief Whether or not the ADT is empty. */ vector leaves; /*!< \brief Vector, which contains all the leaves of the ADT. */ @@ -54,23 +54,23 @@ class CADTBaseClass { vector > FrontLeaves; /*!< \brief Vector used in the tree traversal. */ vector > FrontLeavesNew; /*!< \brief Vector used in the tree traversal. */ #else - array,1> FrontLeaves; - array,1> FrontLeavesNew; + array, 1> FrontLeaves; + array, 1> FrontLeavesNew; #endif -private: + private: vector coorMinLeaves; /*!< \brief Vector, which contains all the minimum coordinates of the leaves. */ vector coorMaxLeaves; /*!< \brief Vector, which contains all the maximum coordinates of the leaves. */ -protected: + protected: /*! * \brief Constructor of the class. Nothing to be done. */ CADTBaseClass() = default; /*--- Disable copy operations ---*/ - CADTBaseClass(const CADTBaseClass &) = delete; - CADTBaseClass& operator=(const CADTBaseClass &) = delete; + CADTBaseClass(const CADTBaseClass&) = delete; + CADTBaseClass& operator=(const CADTBaseClass&) = delete; /*! * \brief Function, which builds the ADT of the given coordinates. @@ -78,16 +78,12 @@ class CADTBaseClass { * \param[in] nPoints Number of points present in the ADT. * \param[in] coor Coordinates of the points. */ - void BuildADT(unsigned short nDim, - unsigned long nPoints, - const su2double *coor); - -public: + void BuildADT(unsigned short nDim, unsigned long nPoints, const su2double* coor); + public: /*! * \brief Function, which returns whether or not the ADT is empty. * \return Whether or not the ADT is empty. */ - inline bool IsEmpty(void) const { return isEmpty;} - + inline bool IsEmpty(void) const { return isEmpty; } }; diff --git a/Common/include/adt/CADTComparePointClass.hpp b/Common/include/adt/CADTComparePointClass.hpp index 542ab2612bc..5457241b839 100644 --- a/Common/include/adt/CADTComparePointClass.hpp +++ b/Common/include/adt/CADTComparePointClass.hpp @@ -35,35 +35,32 @@ * \author E. van der Weide */ class CADTComparePointClass { -private: - const su2double *pointCoor; /*!< \brief Pointer to the coordinates of the points. */ - const unsigned short splitDirection; /*!< \brief Split direction used in the sorting. */ - const unsigned short nDim; /*!< \brief Number of spatial dimensions stored in the coordinates. */ + private: + const su2double* pointCoor; /*!< \brief Pointer to the coordinates of the points. */ + const unsigned short splitDirection; /*!< \brief Split direction used in the sorting. */ + const unsigned short nDim; /*!< \brief Number of spatial dimensions stored in the coordinates. */ -public: + public: /*! * \brief Constructor of the class. The member variables are initialized. * \param[in] coor Pointer to the coordinates of the points. * \param[in] splitDir Direction that must be used to sort the coordinates. * \param[in] nDimADT Number of spatial dimensions of the ADT and coordinates. */ - CADTComparePointClass(const su2double *coor, - const unsigned short splitDir, - const unsigned short nDimADT) : pointCoor(coor), splitDirection(splitDir), nDim(nDimADT) {} + CADTComparePointClass(const su2double* coor, const unsigned short splitDir, const unsigned short nDimADT) + : pointCoor(coor), splitDirection(splitDir), nDim(nDimADT) {} /*! * \brief Operator used for the sorting of the points. * \param[in] p0 Index of the first point to be compared. * \param[in] p1 Index of the second point to be compared. */ - inline bool operator()(const unsigned long p0, - const unsigned long p1) const { - return pointCoor[nDim*p0+splitDirection] < pointCoor[nDim*p1+splitDirection]; + inline bool operator()(const unsigned long p0, const unsigned long p1) const { + return pointCoor[nDim * p0 + splitDirection] < pointCoor[nDim * p1 + splitDirection]; } /*! * \brief Default constructor of the class, disabled. */ CADTComparePointClass() = delete; - }; diff --git a/Common/include/adt/CADTElemClass.hpp b/Common/include/adt/CADTElemClass.hpp index 1537385ca51..dd0b862be60 100644 --- a/Common/include/adt/CADTElemClass.hpp +++ b/Common/include/adt/CADTElemClass.hpp @@ -39,13 +39,13 @@ * \version 7.5.1 "Blackbird" */ class CADTElemClass : public CADTBaseClass { -private: + private: unsigned short nDim; /*!< \brief Number of spatial dimensions. */ - vector coorPoints; /*!< \brief Vector, which contains the coordinates - of the points in the ADT. */ - vector BBoxCoor; /*!< \brief Vector, which contains the coordinates - of the bounding boxes of the elements. */ + vector coorPoints; /*!< \brief Vector, which contains the coordinates + of the points in the ADT. */ + vector BBoxCoor; /*!< \brief Vector, which contains the coordinates + of the bounding boxes of the elements. */ vector elemVTK_Type; /*!< \brief Vector, which the type of the elements using the VTK convention. */ @@ -58,15 +58,15 @@ class CADTElemClass : public CADTBaseClass { of the elements in the ADT. */ vector localElemIDs; /*!< \brief Vector, which contains the local element ID's of the elements in the ADT. */ - vector ranksOfElems; /*!< \brief Vector, which contains the ranks + vector ranksOfElems; /*!< \brief Vector, which contains the ranks of the elements in the ADT. */ #ifdef HAVE_OMP - vector >BBoxTargets; /*!< \brief Vector, used to store possible bounding box - candidates during the nearest element search. */ + vector > BBoxTargets; /*!< \brief Vector, used to store possible bounding box + candidates during the nearest element search. */ #else - array,1> BBoxTargets; + array, 1> BBoxTargets; #endif -public: + public: /*! * \brief Constructor of the class. * \param[in] val_nDim Number of spatial dimensions of the problem. @@ -80,13 +80,9 @@ class CADTElemClass : public CADTBaseClass { * \param[in] globalTree Whether or not a global tree must be built. If false a local ADT is built. */ - CADTElemClass(unsigned short val_nDim, - vector &val_coor, - vector &val_connElem, - vector &val_VTKElem, - vector &val_markerID, - vector &val_elemID, - const bool globalTree); + CADTElemClass(unsigned short val_nDim, vector& val_coor, vector& val_connElem, + vector& val_VTKElem, vector& val_markerID, + vector& val_elemID, const bool globalTree); /*! * \brief Function, which determines the element that contains the given coordinate. @@ -102,15 +98,11 @@ class CADTElemClass : public CADTBaseClass { which contains the coordinate. * \return True if an element is found, false if not. */ - inline bool DetermineContainingElement(const su2double *coor, - unsigned short &markerID, - unsigned long &elemID, - int &rankID, - su2double *parCoor, - su2double *weightsInterpol) { + inline bool DetermineContainingElement(const su2double* coor, unsigned short& markerID, unsigned long& elemID, + int& rankID, su2double* parCoor, su2double* weightsInterpol) { const auto iThread = omp_get_thread_num(); - return DetermineContainingElement_impl(FrontLeaves[iThread], FrontLeavesNew[iThread], - coor, markerID, elemID, rankID, parCoor, weightsInterpol); + return DetermineContainingElement_impl(FrontLeaves[iThread], FrontLeavesNew[iThread], coor, markerID, elemID, + rankID, parCoor, weightsInterpol); } /*! @@ -123,42 +115,29 @@ class CADTElemClass : public CADTBaseClass { * \param[out] elemID Local element ID of the nearest element in the ADT. * \param[out] rankID Rank on which the nearest element in the ADT is stored. */ - inline void DetermineNearestElement(const su2double *coor, - su2double &dist, - unsigned short &markerID, - unsigned long &elemID, - int &rankID) { + inline void DetermineNearestElement(const su2double* coor, su2double& dist, unsigned short& markerID, + unsigned long& elemID, int& rankID) { const auto iThread = omp_get_thread_num(); - DetermineNearestElement_impl(BBoxTargets[iThread], FrontLeaves[iThread], - FrontLeavesNew[iThread], coor, dist, markerID, elemID, rankID); + DetermineNearestElement_impl(BBoxTargets[iThread], FrontLeaves[iThread], FrontLeavesNew[iThread], coor, dist, + markerID, elemID, rankID); } -private: + private: /*! * \brief Implementation of DetermineContainingElement. * \note Working variables (first two) passed explicitly for thread safety. */ - bool DetermineContainingElement_impl(vector& frontLeaves, - vector& frontLeavesNew, - const su2double *coor, - unsigned short &markerID, - unsigned long &elemID, - int &rankID, - su2double *parCoor, - su2double *weightsInterpol) const; + bool DetermineContainingElement_impl(vector& frontLeaves, vector& frontLeavesNew, + const su2double* coor, unsigned short& markerID, unsigned long& elemID, + int& rankID, su2double* parCoor, su2double* weightsInterpol) const; /*! * \brief Implementation of DetermineNearestElement. * \note Working variables (first three) passed explicitly for thread safety. */ - void DetermineNearestElement_impl(vector& BBoxTargets, - vector& frontLeaves, - vector& frontLeavesNew, - const su2double *coor, - su2double &dist, - unsigned short &markerID, - unsigned long &elemID, - int &rankID) const; + void DetermineNearestElement_impl(vector& BBoxTargets, vector& frontLeaves, + vector& frontLeavesNew, const su2double* coor, su2double& dist, + unsigned short& markerID, unsigned long& elemID, int& rankID) const; /*! * \brief Function, which checks whether or not the given coordinate is @@ -172,10 +151,8 @@ class CADTElemClass : public CADTBaseClass { given element. * \return True if coor is inside the element and false otherwise. */ - bool CoorInElement(const unsigned long elemID, - const su2double *coor, - su2double *parCoor, - su2double *weightsInterpol) const; + bool CoorInElement(const unsigned long elemID, const su2double* coor, su2double* parCoor, + su2double* weightsInterpol) const; /*! * \brief Function, which checks whether or not the given coordinate is @@ -189,10 +166,8 @@ class CADTElemClass : public CADTBaseClass { given quadrilateral. * \return True if coor is inside the quadrilateral and false otherwise. */ - bool CoorInQuadrilateral(const unsigned long elemID, - const su2double *coor, - su2double *parCoor, - su2double *weightsInterpol) const; + bool CoorInQuadrilateral(const unsigned long elemID, const su2double* coor, su2double* parCoor, + su2double* weightsInterpol) const; /*! * \brief Function, which checks whether or not the given coordinate is @@ -206,10 +181,8 @@ class CADTElemClass : public CADTBaseClass { given triangle. * \return True if coor is inside the triangle and false otherwise. */ - bool CoorInTriangle(const unsigned long elemID, - const su2double *coor, - su2double *parCoor, - su2double *weightsInterpol) const; + bool CoorInTriangle(const unsigned long elemID, const su2double* coor, su2double* parCoor, + su2double* weightsInterpol) const; /*! * \brief Function, which checks whether or not the given coordinate is @@ -223,10 +196,8 @@ class CADTElemClass : public CADTBaseClass { given hexahedron. * \return True if coor is inside the hexahedron and false otherwise. */ - bool CoorInHexahedron(const unsigned long elemID, - const su2double *coor, - su2double *parCoor, - su2double *weightsInterpol) const; + bool CoorInHexahedron(const unsigned long elemID, const su2double* coor, su2double* parCoor, + su2double* weightsInterpol) const; /*! * \brief Function, which checks whether or not the given coordinate is @@ -240,10 +211,8 @@ class CADTElemClass : public CADTBaseClass { given prism. * \return True if coor is inside the prism and false otherwise. */ - bool CoorInPrism(const unsigned long elemID, - const su2double *coor, - su2double *parCoor, - su2double *weightsInterpol) const; + bool CoorInPrism(const unsigned long elemID, const su2double* coor, su2double* parCoor, + su2double* weightsInterpol) const; /*! * \brief Function, which checks whether or not the given coordinate is @@ -257,10 +226,8 @@ class CADTElemClass : public CADTBaseClass { given pyramid. * \return True if coor is inside the pyramid and false otherwise. */ - bool CoorInPyramid(const unsigned long elemID, - const su2double *coor, - su2double *parCoor, - su2double *weightsInterpol) const; + bool CoorInPyramid(const unsigned long elemID, const su2double* coor, su2double* parCoor, + su2double* weightsInterpol) const; /*! * \brief Function, which checks whether or not the given coordinate is @@ -274,10 +241,8 @@ class CADTElemClass : public CADTBaseClass { given tetrahedron. * \return True if coor is inside the tetrahedron and false otherwise. */ - bool CoorInTetrahedron(const unsigned long elemID, - const su2double *coor, - su2double *parCoor, - su2double *weightsInterpol) const; + bool CoorInTetrahedron(const unsigned long elemID, const su2double* coor, su2double* parCoor, + su2double* weightsInterpol) const; /*! * \brief Function, which provides an initial guess for the parametric coordinates @@ -290,9 +255,8 @@ class CADTElemClass : public CADTBaseClass { * \return True if the initial guess is within the hexahedron and false otherwise. */ - bool InitialGuessContainmentHexahedron(const su2double xRelC[3], - const su2double xRel[8][3], - su2double *parCoor) const; + bool InitialGuessContainmentHexahedron(const su2double xRelC[3], const su2double xRel[8][3], + su2double* parCoor) const; /*! * \brief Function, which provides an initial guess for the parametric coordinates @@ -305,9 +269,7 @@ class CADTElemClass : public CADTBaseClass { * \return True if the initial guess is within the prism and false otherwise. */ - bool InitialGuessContainmentPrism(const su2double xRelC[3], - const su2double xRel[6][3], - su2double *parCoor) const; + bool InitialGuessContainmentPrism(const su2double xRelC[3], const su2double xRel[6][3], su2double* parCoor) const; /*! * \brief Function, which provides an initial guess for the parametric coordinates @@ -320,9 +282,7 @@ class CADTElemClass : public CADTBaseClass { * \return True if the initial guess is within the pyramid and false otherwise. */ - bool InitialGuessContainmentPyramid(const su2double xRelC[3], - const su2double xRel[5][3], - su2double *parCoor) const; + bool InitialGuessContainmentPyramid(const su2double xRelC[3], const su2double xRel[5][3], su2double* parCoor) const; /*! * \brief Function, which computes the distance squared of the given coordinate @@ -331,9 +291,7 @@ class CADTElemClass : public CADTBaseClass { * \param[in] coor Coordinate for which the distance to the element must be determined. * \param[out] dist2Elem Distance squared from the coordinate to the element. */ - void Dist2ToElement(const unsigned long elemID, - const su2double *coor, - su2double &dist2Elem) const; + void Dist2ToElement(const unsigned long elemID, const su2double* coor, su2double& dist2Elem) const; /*! * \brief Function, which computes the distance squared of the given coordinate to a linear line element. @@ -344,10 +302,7 @@ class CADTElemClass : public CADTBaseClass { * \param[in] coor Coordinate for which the distance to the line must be determined. * \param[out] dist2Line Distance squared from the coordinate to the line. */ - void Dist2ToLine(const unsigned long i0, - const unsigned long i1, - const su2double *coor, - su2double &dist2Line) const; + void Dist2ToLine(const unsigned long i0, const unsigned long i1, const su2double* coor, su2double& dist2Line) const; /*! * \brief Function, which computes the distance squared of the given coordinate to a linear quadrilateral element if the projection is inside the quad. @@ -366,14 +321,9 @@ class CADTElemClass : public CADTBaseClass { * \param[out] dist2Quad Distance squared from the coordinate to the quadrilateral. * \return True if the projection is inside the quadrilateral and false otherwise. */ - bool Dist2ToQuadrilateral(const unsigned long i0, - const unsigned long i1, - const unsigned long i2, - const unsigned long i3, - const su2double *coor, - su2double &r, - su2double &s, - su2double &dist2Quad) const; + bool Dist2ToQuadrilateral(const unsigned long i0, const unsigned long i1, const unsigned long i2, + const unsigned long i3, const su2double* coor, su2double& r, su2double& s, + su2double& dist2Quad) const; /*! * \brief Function, which computes the distance squared of the given coordinate to a linear triangular element if the projection is inside the triangle. @@ -389,16 +339,10 @@ class CADTElemClass : public CADTBaseClass { * \param[out] s Parametric coordinate of the projection. * \return True if the projection is inside the triangle and false otherwise. */ - bool Dist2ToTriangle(const unsigned long i0, - const unsigned long i1, - const unsigned long i2, - const su2double *coor, - su2double &dist2Tria, - su2double &r, - su2double &s) const; + bool Dist2ToTriangle(const unsigned long i0, const unsigned long i1, const unsigned long i2, const su2double* coor, + su2double& dist2Tria, su2double& r, su2double& s) const; /*! * \brief Default constructor of the class, disabled. */ CADTElemClass() = delete; - }; diff --git a/Common/include/adt/CADTNodeClass.hpp b/Common/include/adt/CADTNodeClass.hpp index d6f1a30bcf2..28ac30696c6 100644 --- a/Common/include/adt/CADTNodeClass.hpp +++ b/Common/include/adt/CADTNodeClass.hpp @@ -35,15 +35,14 @@ * \author E. van der Weide */ struct CADTNodeClass { + bool childrenAreTerminal[2]; /*!< \brief Whether or not the child leaves are terminal. */ + unsigned long children[2]; /*!< \brief Child leaves. If childrenAreTerminal is true the children + contain the point ID's or bounding box ID's. Note that it + is allowed that one child is termimal and the other is not. */ + unsigned long centralNodeID; /*!< \brief ID of a node, which is near the center of the leaf. */ - bool childrenAreTerminal[2]; /*!< \brief Whether or not the child leaves are terminal. */ - unsigned long children[2]; /*!< \brief Child leaves. If childrenAreTerminal is true the children - contain the point ID's or bounding box ID's. Note that it - is allowed that one child is termimal and the other is not. */ - unsigned long centralNodeID; /*!< \brief ID of a node, which is near the center of the leaf. */ - - su2double *xMin; /*!< \brief The minimum coordinates of this leaf. It points to a position in the large - vector, which contains the coordinates of all leaves. */ - su2double *xMax; /*!< \brief The maximum coordinates of this leaf. It points to a position in the large - vector, which contains the coordinates of all leaves. */ + su2double* xMin; /*!< \brief The minimum coordinates of this leaf. It points to a position in the large + vector, which contains the coordinates of all leaves. */ + su2double* xMax; /*!< \brief The maximum coordinates of this leaf. It points to a position in the large + vector, which contains the coordinates of all leaves. */ }; diff --git a/Common/include/adt/CADTPointsOnlyClass.hpp b/Common/include/adt/CADTPointsOnlyClass.hpp index 68f7d3c26ed..ba5f38adc49 100644 --- a/Common/include/adt/CADTPointsOnlyClass.hpp +++ b/Common/include/adt/CADTPointsOnlyClass.hpp @@ -35,14 +35,14 @@ * \author E. van der Weide */ class CADTPointsOnlyClass : public CADTBaseClass { -private: - vector coorPoints; /*!< \brief Vector, which contains the coordinates + private: + vector coorPoints; /*!< \brief Vector, which contains the coordinates of the points in the ADT. */ vector localPointIDs; /*!< \brief Vector, which contains the local point ID's of the points in the ADT. */ - vector ranksOfPoints; /*!< \brief Vector, which contains the ranks + vector ranksOfPoints; /*!< \brief Vector, which contains the ranks of the points in the ADT. */ -public: + public: /*! * \brief Constructor of the class. * \param[in] nDim Number of spatial dimensions of the problem. @@ -52,11 +52,8 @@ class CADTPointsOnlyClass : public CADTBaseClass { * \param[in] globalTree Whether or not a global tree must be built. If false a local ADT is built. */ - CADTPointsOnlyClass(unsigned short nDim, - unsigned long nPoints, - const su2double *coor, - const unsigned long *pointID, - const bool globalTree); + CADTPointsOnlyClass(unsigned short nDim, unsigned long nPoints, const su2double* coor, const unsigned long* pointID, + const bool globalTree); /*! * \brief Function, which determines the nearest node in the ADT for the given coordinate. @@ -67,13 +64,9 @@ class CADTPointsOnlyClass : public CADTBaseClass { * \param[out] pointID Local point ID of the nearest node in the ADT. * \param[out] rankID Rank on which the nearest node in the ADT is stored. */ - inline void DetermineNearestNode(const su2double *coor, - su2double &dist, - unsigned long &pointID, - int &rankID) { + inline void DetermineNearestNode(const su2double* coor, su2double& dist, unsigned long& pointID, int& rankID) { const auto iThread = omp_get_thread_num(); - DetermineNearestNode_impl(FrontLeaves[iThread], FrontLeavesNew[iThread], - coor, dist, pointID, rankID); + DetermineNearestNode_impl(FrontLeaves[iThread], FrontLeavesNew[iThread], coor, dist, pointID, rankID); } /*! @@ -81,15 +74,11 @@ class CADTPointsOnlyClass : public CADTBaseClass { */ CADTPointsOnlyClass() = delete; -private: + private: /*! * \brief Implementation of DetermineNearestNode. * \note Working variables (first two) passed explicitly for thread safety. */ - void DetermineNearestNode_impl(vector& frontLeaves, - vector& frontLeavesNew, - const su2double *coor, - su2double &dist, - unsigned long &pointID, - int &rankID) const; + void DetermineNearestNode_impl(vector& frontLeaves, vector& frontLeavesNew, + const su2double* coor, su2double& dist, unsigned long& pointID, int& rankID) const; }; diff --git a/Common/include/adt/CBBoxTargetClass.hpp b/Common/include/adt/CBBoxTargetClass.hpp index 1a7cf37d132..405a9956e98 100644 --- a/Common/include/adt/CBBoxTargetClass.hpp +++ b/Common/include/adt/CBBoxTargetClass.hpp @@ -38,12 +38,11 @@ * \version 7.5.1 "Blackbird" */ struct CBBoxTargetClass { - - unsigned long boundingBoxID; /*!< \brief Corresponding bounding box ID. */ - su2double possibleMinDist2; /*!< \brief Possible minimimum distance squared to the - given coordinate. */ - su2double guaranteedMinDist2; /*!< \brief Guaranteed minimum distance squared to the - given coordinate. */ + unsigned long boundingBoxID; /*!< \brief Corresponding bounding box ID. */ + su2double possibleMinDist2; /*!< \brief Possible minimimum distance squared to the + given coordinate. */ + su2double guaranteedMinDist2; /*!< \brief Guaranteed minimum distance squared to the + given coordinate. */ /*! * \brief Constructor of the class. Nothing to be done. @@ -58,27 +57,21 @@ struct CBBoxTargetClass { * \param[in] val_guarDist2 - Guaranteed minimum distance squared to the target for this bounding box. */ - inline CBBoxTargetClass(const unsigned long val_BBoxID, - const su2double val_posDist2, - const su2double val_guarDist2) - : boundingBoxID(val_BBoxID), - possibleMinDist2(val_posDist2), - guaranteedMinDist2(val_guarDist2) {} + inline CBBoxTargetClass(const unsigned long val_BBoxID, const su2double val_posDist2, const su2double val_guarDist2) + : boundingBoxID(val_BBoxID), possibleMinDist2(val_posDist2), guaranteedMinDist2(val_guarDist2) {} /*! * \brief Less than operator. Needed for the sorting of the candidates. * \param[in] other Object to which the current object must be compared. */ - inline bool operator <(const CBBoxTargetClass &other) const{ - + inline bool operator<(const CBBoxTargetClass& other) const { /* Make sure that the bounding boxes with the smallest possible distances are stored first. */ - if(possibleMinDist2 < other.possibleMinDist2) return true; - if(possibleMinDist2 > other.possibleMinDist2) return false; - if(guaranteedMinDist2 < other.guaranteedMinDist2) return true; - if(guaranteedMinDist2 > other.guaranteedMinDist2) return false; - if(boundingBoxID < other.boundingBoxID) return true; + if (possibleMinDist2 < other.possibleMinDist2) return true; + if (possibleMinDist2 > other.possibleMinDist2) return false; + if (guaranteedMinDist2 < other.guaranteedMinDist2) return true; + if (guaranteedMinDist2 > other.guaranteedMinDist2) return false; + if (boundingBoxID < other.boundingBoxID) return true; return false; } - }; diff --git a/Common/include/basic_types/ad_structure.hpp b/Common/include/basic_types/ad_structure.hpp index 445cf7c2269..c3ba75d9204 100644 --- a/Common/include/basic_types/ad_structure.hpp +++ b/Common/include/basic_types/ad_structure.hpp @@ -36,542 +36,534 @@ * In case there is no reverse type configured, they have no effect at all, * and so the real versions of the routined are after #else. */ -namespace AD{ +namespace AD { #ifndef CODI_REVERSE_TYPE - /*! - * \brief Start the recording of the operations and involved variables. - * If called, the computational graph of all operations occuring after the call will be stored, - * starting with the variables registered with RegisterInput. - */ - inline void StartRecording() {} - - /*! - * \brief Stops the recording of the operations and variables. - */ - inline void StopRecording() {} - - /*! - * \brief Check if the tape is active - * \param[out] Boolean which determines whether the tape is active. - */ - inline bool TapeActive() {return false;} - - /*! - * \brief Prints out tape statistics. - */ - inline void PrintStatistics() {} - - /*! - * \brief Registers the variable as an input and saves internal data (indices). I.e. as a leaf of the computational graph. - * \param[in] data - The variable to be registered as input. - * \param[in] push_index - boolean whether we also want to push the index. - */ - inline void RegisterInput(su2double &data, bool push_index = true) {} - - /*! - * \brief Registers the variable as an output. I.e. as the root of the computational graph. - * \param[in] data - The variable to be registered as output. - */ - inline void RegisterOutput(su2double &data) {} - - /*! - * \brief Sets the adjoint value at index to val - * \param[in] index - Position in the adjoint vector. - * \param[in] val - adjoint value to be set. - */ - inline void SetDerivative(int index, const double val) {} - - /*! - * \brief Extracts the adjoint value at index - * \param[in] index - position in the adjoint vector where the derivative will be extracted. - * \return Derivative value. - */ - inline double GetDerivative(int index) {return 0.0;} - - /*! - * \brief Clears the currently stored adjoints but keeps the computational graph. - */ - inline void ClearAdjoints() {} - - /*! - * \brief Computes the adjoints, i.e. the derivatives of the output with respect to the input variables. - */ - inline void ComputeAdjoint() {} - - /*! - * \brief Computes the adjoints, i.e. the derivatives of the output with respect to the input variables. - * \param[in] enter - Position where we start evaluating the tape. - * \param[in] leave - Position where we stop evaluating the tape. - */ - inline void ComputeAdjoint(unsigned short enter, unsigned short leave) {} - - /*! - * \brief Computes the adjoints, i.e., the derivatives of the output with respect to the input variables, using forward tape evaluation. - */ - inline void ComputeAdjointForward() {} - - /*! - * \brief Reset the tape structure to be ready for a new recording. - */ - inline void Reset() {} - - /*! - * \brief Reset the variable (set index to zero). - * \param[in] data - the variable to be unregistered from the tape. - */ - inline void ResetInput(su2double &data) {} - - /*! - * \brief Sets the scalar inputs of a preaccumulation section. - * \param[in] data - the scalar input variables. - */ - template - inline void SetPreaccIn(Ts&&... data) {} - - /*! - * \brief Sets the input variables of a preaccumulation section using a 1D array. - * \param[in] data - the input 1D array. - * \param[in] size - size of the array. - */ - template - inline void SetPreaccIn(const T& data, const int size) {} - - /*! - * \brief Sets the input variables of a preaccumulation section using a 2D array. - * \param[in] data - the input 2D array. - * \param[in] size_x - size of the array in x dimension. - * \param[in] size_y - size of the array in y dimension. - */ - template - inline void SetPreaccIn(const T& data, const int size_x, const int size_y) {} - - /*! - * \brief Starts a new preaccumulation section and sets the input variables. - * - * The idea of preaccumulation is to store only the Jacobi matrix of a code section during - * the taping process instead of all operations. This decreases the tape size and reduces runtime. - * - * Input/Output of the section are set with several calls to SetPreaccIn()/SetPreaccOut(). - * - * Note: the call of this routine must be followed by a call of EndPreacc() and the end of the code section. - */ - inline void StartPreacc() {} - - /*! - * \brief Sets the scalar outputs of a preaccumulation section. - * \param[in] data - the scalar output variables. - */ - template - inline void SetPreaccOut(Ts&&... data) {} - - /*! - * \brief Sets the output variables of a preaccumulation section using a 1D array. - * \param[in] data - the output 1D array. - */ - template - inline void SetPreaccOut(T&& data, const int size) {} - - /*! - * \brief Sets the input variables of a preaccumulation section using a 2D array. - * \param[in] data - the output 1D array. - */ - template - inline void SetPreaccOut(T&& data, const int size_x, const int size_y) {} - - /*! - * \brief Ends a preaccumulation section and computes the local Jacobi matrix - * of a code section using the variables set with SetLocalInput(), SetLocalOutput() and pushes a statement - * for each output variable to the AD tape. - */ - inline void EndPreacc() {} - - /*! - * \brief Sets the scalar input of a externally differentiated function. - * \param[in] data - the scalar input variable. - */ - inline void SetExtFuncIn(su2double &data) {} - - /*! - * \brief Sets the input variables of a externally differentiated function using a 1D array. - * \param[in] data - the input 1D array. - * \param[in] size - number of rows. - */ - template - inline void SetExtFuncIn(const T& data, const int size) {} - - /*! - * \brief Sets the input variables of a externally differentiated function using a 2D array. - * \param[in] data - the input 2D array. - * \param[in] size_x - number of rows. - * \param[in] size_y - number of columns. - */ - template - inline void SetExtFuncIn(const T& data, const int size_x, const int size_y) {} - - /*! - * \brief Sets the scalar output of a externally differentiated function. - * \param[in] data - the scalar output variable. - */ - inline void SetExtFuncOut(su2double &data) {} - - /*! - * \brief Sets the output variables of a externally differentiated function using a 1D array. - * \param[in] data - the output 1D array. - * \param[in] size - number of rows. - */ - template - inline void SetExtFuncOut(T&& data, const int size) {} - - /*! - * \brief Sets the output variables of a externally differentiated function using a 2D array. - * \param[in] data - the output 2D array. - * \param[in] size_x - number of rows. - * \param[in] size_y - number of columns. - */ - template - inline void SetExtFuncOut(T&& data, const int size_x, const int size_y) {} - - /*! - * \brief Evaluates and saves gradient data from a variable. - * \param[in] data - variable whose gradient information will be extracted. - * \param[in] index - where obtained gradient information will be stored. - */ - inline void SetIndex(int &index, const su2double &data) {} - - /*! - * \brief Pushes back the current tape position to the tape position's vector. - */ - inline void Push_TapePosition() {} - - /*! - * \brief Start a passive region, i.e. stop recording. - * \return True if tape was active. - */ - inline bool BeginPassive() { return false; } - - /*! - * \brief End a passive region, i.e. start recording if we were recording before. - * \param[in] wasActive - Whether we were recording before entering the passive region. - */ - inline void EndPassive(bool wasActive) {} - - /*! - * \brief Pause the use of preaccumulation. - * \return True if preaccumulation was active. - */ - inline bool PausePreaccumulation() { return false; } - - /*! - * \brief Resume the use of preaccumulation. - * \param[in] wasActive - Whether preaccumulation was active before pausing. - */ - inline void ResumePreaccumulation(bool wasActive) {} - - /*! - * \brief Begin a hybrid parallel adjoint evaluation mode that assumes an inherently safe reverse path. - */ - inline void StartNoSharedReading() {} - - /*! - * \brief End the "no shared reading" adjoint evaluation mode. - */ - inline void EndNoSharedReading() {} +/*! + * \brief Start the recording of the operations and involved variables. + * If called, the computational graph of all operations occuring after the call will be stored, + * starting with the variables registered with RegisterInput. + */ +inline void StartRecording() {} + +/*! + * \brief Stops the recording of the operations and variables. + */ +inline void StopRecording() {} + +/*! + * \brief Check if the tape is active + * \param[out] Boolean which determines whether the tape is active. + */ +inline bool TapeActive() { return false; } + +/*! + * \brief Prints out tape statistics. + */ +inline void PrintStatistics() {} + +/*! + * \brief Registers the variable as an input and saves internal data (indices). I.e. as a leaf of the computational + * graph. \param[in] data - The variable to be registered as input. \param[in] push_index - boolean whether we also want + * to push the index. + */ +inline void RegisterInput(su2double& data, bool push_index = true) {} + +/*! + * \brief Registers the variable as an output. I.e. as the root of the computational graph. + * \param[in] data - The variable to be registered as output. + */ +inline void RegisterOutput(su2double& data) {} + +/*! + * \brief Sets the adjoint value at index to val + * \param[in] index - Position in the adjoint vector. + * \param[in] val - adjoint value to be set. + */ +inline void SetDerivative(int index, const double val) {} + +/*! + * \brief Extracts the adjoint value at index + * \param[in] index - position in the adjoint vector where the derivative will be extracted. + * \return Derivative value. + */ +inline double GetDerivative(int index) { return 0.0; } + +/*! + * \brief Clears the currently stored adjoints but keeps the computational graph. + */ +inline void ClearAdjoints() {} + +/*! + * \brief Computes the adjoints, i.e. the derivatives of the output with respect to the input variables. + */ +inline void ComputeAdjoint() {} + +/*! + * \brief Computes the adjoints, i.e. the derivatives of the output with respect to the input variables. + * \param[in] enter - Position where we start evaluating the tape. + * \param[in] leave - Position where we stop evaluating the tape. + */ +inline void ComputeAdjoint(unsigned short enter, unsigned short leave) {} + +/*! + * \brief Computes the adjoints, i.e., the derivatives of the output with respect to the input variables, using forward + * tape evaluation. + */ +inline void ComputeAdjointForward() {} + +/*! + * \brief Reset the tape structure to be ready for a new recording. + */ +inline void Reset() {} + +/*! + * \brief Reset the variable (set index to zero). + * \param[in] data - the variable to be unregistered from the tape. + */ +inline void ResetInput(su2double& data) {} + +/*! + * \brief Sets the scalar inputs of a preaccumulation section. + * \param[in] data - the scalar input variables. + */ +template +inline void SetPreaccIn(Ts&&... data) {} + +/*! + * \brief Sets the input variables of a preaccumulation section using a 1D array. + * \param[in] data - the input 1D array. + * \param[in] size - size of the array. + */ +template +inline void SetPreaccIn(const T& data, const int size) {} + +/*! + * \brief Sets the input variables of a preaccumulation section using a 2D array. + * \param[in] data - the input 2D array. + * \param[in] size_x - size of the array in x dimension. + * \param[in] size_y - size of the array in y dimension. + */ +template +inline void SetPreaccIn(const T& data, const int size_x, const int size_y) {} + +/*! + * \brief Starts a new preaccumulation section and sets the input variables. + * + * The idea of preaccumulation is to store only the Jacobi matrix of a code section during + * the taping process instead of all operations. This decreases the tape size and reduces runtime. + * + * Input/Output of the section are set with several calls to SetPreaccIn()/SetPreaccOut(). + * + * Note: the call of this routine must be followed by a call of EndPreacc() and the end of the code section. + */ +inline void StartPreacc() {} + +/*! + * \brief Sets the scalar outputs of a preaccumulation section. + * \param[in] data - the scalar output variables. + */ +template +inline void SetPreaccOut(Ts&&... data) {} + +/*! + * \brief Sets the output variables of a preaccumulation section using a 1D array. + * \param[in] data - the output 1D array. + */ +template +inline void SetPreaccOut(T&& data, const int size) {} + +/*! + * \brief Sets the input variables of a preaccumulation section using a 2D array. + * \param[in] data - the output 1D array. + */ +template +inline void SetPreaccOut(T&& data, const int size_x, const int size_y) {} + +/*! + * \brief Ends a preaccumulation section and computes the local Jacobi matrix + * of a code section using the variables set with SetLocalInput(), SetLocalOutput() and pushes a statement + * for each output variable to the AD tape. + */ +inline void EndPreacc() {} + +/*! + * \brief Sets the scalar input of a externally differentiated function. + * \param[in] data - the scalar input variable. + */ +inline void SetExtFuncIn(su2double& data) {} + +/*! + * \brief Sets the input variables of a externally differentiated function using a 1D array. + * \param[in] data - the input 1D array. + * \param[in] size - number of rows. + */ +template +inline void SetExtFuncIn(const T& data, const int size) {} + +/*! + * \brief Sets the input variables of a externally differentiated function using a 2D array. + * \param[in] data - the input 2D array. + * \param[in] size_x - number of rows. + * \param[in] size_y - number of columns. + */ +template +inline void SetExtFuncIn(const T& data, const int size_x, const int size_y) {} + +/*! + * \brief Sets the scalar output of a externally differentiated function. + * \param[in] data - the scalar output variable. + */ +inline void SetExtFuncOut(su2double& data) {} + +/*! + * \brief Sets the output variables of a externally differentiated function using a 1D array. + * \param[in] data - the output 1D array. + * \param[in] size - number of rows. + */ +template +inline void SetExtFuncOut(T&& data, const int size) {} + +/*! + * \brief Sets the output variables of a externally differentiated function using a 2D array. + * \param[in] data - the output 2D array. + * \param[in] size_x - number of rows. + * \param[in] size_y - number of columns. + */ +template +inline void SetExtFuncOut(T&& data, const int size_x, const int size_y) {} + +/*! + * \brief Evaluates and saves gradient data from a variable. + * \param[in] data - variable whose gradient information will be extracted. + * \param[in] index - where obtained gradient information will be stored. + */ +inline void SetIndex(int& index, const su2double& data) {} + +/*! + * \brief Pushes back the current tape position to the tape position's vector. + */ +inline void Push_TapePosition() {} + +/*! + * \brief Start a passive region, i.e. stop recording. + * \return True if tape was active. + */ +inline bool BeginPassive() { return false; } + +/*! + * \brief End a passive region, i.e. start recording if we were recording before. + * \param[in] wasActive - Whether we were recording before entering the passive region. + */ +inline void EndPassive(bool wasActive) {} + +/*! + * \brief Pause the use of preaccumulation. + * \return True if preaccumulation was active. + */ +inline bool PausePreaccumulation() { return false; } + +/*! + * \brief Resume the use of preaccumulation. + * \param[in] wasActive - Whether preaccumulation was active before pausing. + */ +inline void ResumePreaccumulation(bool wasActive) {} + +/*! + * \brief Begin a hybrid parallel adjoint evaluation mode that assumes an inherently safe reverse path. + */ +inline void StartNoSharedReading() {} + +/*! + * \brief End the "no shared reading" adjoint evaluation mode. + */ +inline void EndNoSharedReading() {} #else - using CheckpointHandler = codi::ExternalFunctionUserData; +using CheckpointHandler = codi::ExternalFunctionUserData; - using Tape = su2double::Tape; +using Tape = su2double::Tape; #ifdef HAVE_OPDI - using ExtFuncHelper = codi::OpenMPExternalFunctionHelper; +using ExtFuncHelper = codi::OpenMPExternalFunctionHelper; #else - using ExtFuncHelper = codi::ExternalFunctionHelper; +using ExtFuncHelper = codi::ExternalFunctionHelper; #endif - extern ExtFuncHelper FuncHelper; +extern ExtFuncHelper FuncHelper; - extern bool PreaccActive; +extern bool PreaccActive; #ifdef HAVE_OPDI - SU2_OMP(threadprivate(PreaccActive)) +SU2_OMP(threadprivate(PreaccActive)) #endif - extern bool PreaccEnabled; +extern bool PreaccEnabled; #ifdef HAVE_OPDI - using CoDiTapePosition = Tape::Position; - using OpDiState = void*; - using TapePosition = std::pair; +using CoDiTapePosition = Tape::Position; +using OpDiState = void*; +using TapePosition = std::pair; #else - using TapePosition = Tape::Position; +using TapePosition = Tape::Position; #endif - extern TapePosition StartPosition, EndPosition; +extern TapePosition StartPosition, EndPosition; - extern std::vector TapePositions; +extern std::vector TapePositions; - extern codi::PreaccumulationHelper PreaccHelper; +extern codi::PreaccumulationHelper PreaccHelper; #ifdef HAVE_OPDI - SU2_OMP(threadprivate(PreaccHelper)) +SU2_OMP(threadprivate(PreaccHelper)) #endif - /*--- Reference to the tape. ---*/ +/*--- Reference to the tape. ---*/ - FORCEINLINE Tape& getTape() {return su2double::getTape();} +FORCEINLINE Tape& getTape() { return su2double::getTape(); } - FORCEINLINE void RegisterInput(su2double &data) {AD::getTape().registerInput(data);} +FORCEINLINE void RegisterInput(su2double& data) { AD::getTape().registerInput(data); } - FORCEINLINE void RegisterOutput(su2double& data) {AD::getTape().registerOutput(data);} +FORCEINLINE void RegisterOutput(su2double& data) { AD::getTape().registerOutput(data); } - FORCEINLINE void ResetInput(su2double &data) {data = data.getValue();} +FORCEINLINE void ResetInput(su2double& data) { data = data.getValue(); } - FORCEINLINE void StartRecording() {AD::getTape().setActive();} +FORCEINLINE void StartRecording() { AD::getTape().setActive(); } - FORCEINLINE void StopRecording() {AD::getTape().setPassive();} +FORCEINLINE void StopRecording() { AD::getTape().setPassive(); } - FORCEINLINE bool TapeActive() { return AD::getTape().isActive(); } +FORCEINLINE bool TapeActive() { return AD::getTape().isActive(); } - FORCEINLINE void PrintStatistics() {AD::getTape().printStatistics();} +FORCEINLINE void PrintStatistics() { AD::getTape().printStatistics(); } - FORCEINLINE void ClearAdjoints() {AD::getTape().clearAdjoints(); } +FORCEINLINE void ClearAdjoints() { AD::getTape().clearAdjoints(); } - FORCEINLINE void ComputeAdjoint() { - #if defined(HAVE_OPDI) - opdi::logic->prepareEvaluate(); - #endif - AD::getTape().evaluate(); - } +FORCEINLINE void ComputeAdjoint() { +#if defined(HAVE_OPDI) + opdi::logic->prepareEvaluate(); +#endif + AD::getTape().evaluate(); +} - FORCEINLINE void ComputeAdjoint(unsigned short enter, unsigned short leave) { - #if defined(HAVE_OPDI) - opdi::logic->recoverState(TapePositions[enter].second); - opdi::logic->prepareEvaluate(); - AD::getTape().evaluate(TapePositions[enter].first, TapePositions[leave].first); - #else - AD::getTape().evaluate(TapePositions[enter], TapePositions[leave]); - #endif - } +FORCEINLINE void ComputeAdjoint(unsigned short enter, unsigned short leave) { +#if defined(HAVE_OPDI) + opdi::logic->recoverState(TapePositions[enter].second); + opdi::logic->prepareEvaluate(); + AD::getTape().evaluate(TapePositions[enter].first, TapePositions[leave].first); +#else + AD::getTape().evaluate(TapePositions[enter], TapePositions[leave]); +#endif +} - FORCEINLINE void ComputeAdjointForward() {AD::getTape().evaluateForward();} - - FORCEINLINE void Reset() { - AD::getTape().reset(); - #if defined(HAVE_OPDI) - opdi::logic->reset(); - #endif - if (TapePositions.size() != 0) { - #if defined(HAVE_OPDI) - for (TapePosition& pos : TapePositions) { - opdi::logic->freeState(pos.second); - } - #endif - TapePositions.clear(); +FORCEINLINE void ComputeAdjointForward() { AD::getTape().evaluateForward(); } + +FORCEINLINE void Reset() { + AD::getTape().reset(); +#if defined(HAVE_OPDI) + opdi::logic->reset(); +#endif + if (TapePositions.size() != 0) { +#if defined(HAVE_OPDI) + for (TapePosition& pos : TapePositions) { + opdi::logic->freeState(pos.second); } +#endif + TapePositions.clear(); } +} - FORCEINLINE void SetIndex(int &index, const su2double &data) { - index = data.getIdentifier(); - } +FORCEINLINE void SetIndex(int& index, const su2double& data) { index = data.getIdentifier(); } - FORCEINLINE void SetDerivative(int index, const double val) { - AD::getTape().setGradient(index, val); - } +FORCEINLINE void SetDerivative(int index, const double val) { AD::getTape().setGradient(index, val); } - FORCEINLINE double GetDerivative(int index) { - return AD::getTape().getGradient(index); - } +FORCEINLINE double GetDerivative(int index) { return AD::getTape().getGradient(index); } - FORCEINLINE bool IsIdentifierActive(su2double const& value) { - return getTape().isIdentifierActive(value.getIdentifier()); - } +FORCEINLINE bool IsIdentifierActive(su2double const& value) { + return getTape().isIdentifierActive(value.getIdentifier()); +} - /*--- Base case for parameter pack expansion. ---*/ - FORCEINLINE void SetPreaccIn() {} +/*--- Base case for parameter pack expansion. ---*/ +FORCEINLINE void SetPreaccIn() {} - template::value> = 0> - FORCEINLINE void SetPreaccIn(const T& data, Ts&&... moreData) { - if (!PreaccActive) return; - if (IsIdentifierActive(data)) - PreaccHelper.addInput(data); - SetPreaccIn(moreData...); - } +template ::value> = 0> +FORCEINLINE void SetPreaccIn(const T& data, Ts&&... moreData) { + if (!PreaccActive) return; + if (IsIdentifierActive(data)) PreaccHelper.addInput(data); + SetPreaccIn(moreData...); +} - template::value> = 0> - FORCEINLINE void SetPreaccIn(T&& data, Ts&&... moreData) { - static_assert(!std::is_same::value, "rvalues cannot be registered"); - } +template ::value> = 0> +FORCEINLINE void SetPreaccIn(T&& data, Ts&&... moreData) { + static_assert(!std::is_same::value, "rvalues cannot be registered"); +} - template - FORCEINLINE void SetPreaccIn(const T& data, const int size) { - if (PreaccActive) { - for (int i = 0; i < size; i++) { - if (IsIdentifierActive(data[i])) { - PreaccHelper.addInput(data[i]); - } +template +FORCEINLINE void SetPreaccIn(const T& data, const int size) { + if (PreaccActive) { + for (int i = 0; i < size; i++) { + if (IsIdentifierActive(data[i])) { + PreaccHelper.addInput(data[i]); } } } +} - template - FORCEINLINE void SetPreaccIn(const T& data, const int size_x, const int size_y) { - if (!PreaccActive) return; - for (int i = 0; i < size_x; i++) { - for (int j = 0; j < size_y; j++) { - if (IsIdentifierActive(data[i][j])) { - PreaccHelper.addInput(data[i][j]); - } +template +FORCEINLINE void SetPreaccIn(const T& data, const int size_x, const int size_y) { + if (!PreaccActive) return; + for (int i = 0; i < size_x; i++) { + for (int j = 0; j < size_y; j++) { + if (IsIdentifierActive(data[i][j])) { + PreaccHelper.addInput(data[i][j]); } } } +} - FORCEINLINE void StartPreacc() { - if (AD::getTape().isActive() && PreaccEnabled) { - PreaccHelper.start(); - PreaccActive = true; - } +FORCEINLINE void StartPreacc() { + if (AD::getTape().isActive() && PreaccEnabled) { + PreaccHelper.start(); + PreaccActive = true; } +} - /*--- Base case for parameter pack expansion. ---*/ - FORCEINLINE void SetPreaccOut() {} +/*--- Base case for parameter pack expansion. ---*/ +FORCEINLINE void SetPreaccOut() {} - template::value> = 0> - FORCEINLINE void SetPreaccOut(T& data, Ts&&... moreData) { - if (!PreaccActive) return; - if (IsIdentifierActive(data)) - PreaccHelper.addOutput(data); - SetPreaccOut(moreData...); - } +template ::value> = 0> +FORCEINLINE void SetPreaccOut(T& data, Ts&&... moreData) { + if (!PreaccActive) return; + if (IsIdentifierActive(data)) PreaccHelper.addOutput(data); + SetPreaccOut(moreData...); +} - template - FORCEINLINE void SetPreaccOut(T&& data, const int size) { - if (PreaccActive) { - for (int i = 0; i < size; i++) { - if (IsIdentifierActive(data[i])) { - PreaccHelper.addOutput(data[i]); - } +template +FORCEINLINE void SetPreaccOut(T&& data, const int size) { + if (PreaccActive) { + for (int i = 0; i < size; i++) { + if (IsIdentifierActive(data[i])) { + PreaccHelper.addOutput(data[i]); } } } +} - template - FORCEINLINE void SetPreaccOut(T&& data, const int size_x, const int size_y) { - if (!PreaccActive) return; - for (int i = 0; i < size_x; i++) { - for (int j = 0; j < size_y; j++) { - if (IsIdentifierActive(data[i][j])) { - PreaccHelper.addOutput(data[i][j]); - } +template +FORCEINLINE void SetPreaccOut(T&& data, const int size_x, const int size_y) { + if (!PreaccActive) return; + for (int i = 0; i < size_x; i++) { + for (int j = 0; j < size_y; j++) { + if (IsIdentifierActive(data[i][j])) { + PreaccHelper.addOutput(data[i][j]); } } } +} - FORCEINLINE void Push_TapePosition() { - #if defined(HAVE_OPDI) - TapePositions.push_back({AD::getTape().getPosition(), opdi::logic->exportState()}); - #else - TapePositions.push_back(AD::getTape().getPosition()); - #endif - } +FORCEINLINE void Push_TapePosition() { +#if defined(HAVE_OPDI) + TapePositions.push_back({AD::getTape().getPosition(), opdi::logic->exportState()}); +#else + TapePositions.push_back(AD::getTape().getPosition()); +#endif +} - FORCEINLINE void EndPreacc(){ - if (PreaccActive) { - PreaccHelper.finish(false); - PreaccActive = false; - } +FORCEINLINE void EndPreacc() { + if (PreaccActive) { + PreaccHelper.finish(false); + PreaccActive = false; } +} - FORCEINLINE void SetExtFuncIn(const su2double &data) { - FuncHelper.addInput(data); +FORCEINLINE void SetExtFuncIn(const su2double& data) { FuncHelper.addInput(data); } + +template +FORCEINLINE void SetExtFuncIn(const T& data, const int size) { + for (int i = 0; i < size; i++) { + FuncHelper.addInput(data[i]); } +} - template - FORCEINLINE void SetExtFuncIn(const T& data, const int size) { - for (int i = 0; i < size; i++) { - FuncHelper.addInput(data[i]); +template +FORCEINLINE void SetExtFuncIn(const T& data, const int size_x, const int size_y) { + for (int i = 0; i < size_x; i++) { + for (int j = 0; j < size_y; j++) { + FuncHelper.addInput(data[i][j]); } } +} - template - FORCEINLINE void SetExtFuncIn(const T& data, const int size_x, const int size_y) { - for (int i = 0; i < size_x; i++) { - for (int j = 0; j < size_y; j++) { - FuncHelper.addInput(data[i][j]); - } - } +FORCEINLINE void SetExtFuncOut(su2double& data) { + if (AD::getTape().isActive()) { + FuncHelper.addOutput(data); } +} - FORCEINLINE void SetExtFuncOut(su2double& data) { +template +FORCEINLINE void SetExtFuncOut(T&& data, const int size) { + for (int i = 0; i < size; i++) { if (AD::getTape().isActive()) { - FuncHelper.addOutput(data); + FuncHelper.addOutput(data[i]); } } +} - template - FORCEINLINE void SetExtFuncOut(T&& data, const int size) { - for (int i = 0; i < size; i++) { +template +FORCEINLINE void SetExtFuncOut(T&& data, const int size_x, const int size_y) { + for (int i = 0; i < size_x; i++) { + for (int j = 0; j < size_y; j++) { if (AD::getTape().isActive()) { - FuncHelper.addOutput(data[i]); - } - } - } - - template - FORCEINLINE void SetExtFuncOut(T&& data, const int size_x, const int size_y) { - for (int i = 0; i < size_x; i++) { - for (int j = 0; j < size_y; j++) { - if (AD::getTape().isActive()) { - FuncHelper.addOutput(data[i][j]); - } + FuncHelper.addOutput(data[i][j]); } } } +} - FORCEINLINE void delete_handler(void *handler) { - CheckpointHandler *checkpoint = static_cast(handler); - checkpoint->clear(); - } +FORCEINLINE void delete_handler(void* handler) { + CheckpointHandler* checkpoint = static_cast(handler); + checkpoint->clear(); +} - FORCEINLINE bool BeginPassive() { - if(AD::getTape().isActive()) { - StopRecording(); - return true; - } - return false; +FORCEINLINE bool BeginPassive() { + if (AD::getTape().isActive()) { + StopRecording(); + return true; } + return false; +} - FORCEINLINE void EndPassive(bool wasActive) { if(wasActive) StartRecording(); } +FORCEINLINE void EndPassive(bool wasActive) { + if (wasActive) StartRecording(); +} - FORCEINLINE bool PausePreaccumulation() { - const auto current = PreaccEnabled; - if (!current) return false; - SU2_OMP_SAFE_GLOBAL_ACCESS(PreaccEnabled = false;) - return true; - } +FORCEINLINE bool PausePreaccumulation() { + const auto current = PreaccEnabled; + if (!current) return false; + SU2_OMP_SAFE_GLOBAL_ACCESS(PreaccEnabled = false;) + return true; +} - FORCEINLINE void ResumePreaccumulation(bool wasActive) { - if (!wasActive) return; - SU2_OMP_SAFE_GLOBAL_ACCESS(PreaccEnabled = true;) - } +FORCEINLINE void ResumePreaccumulation(bool wasActive) { + if (!wasActive) return; + SU2_OMP_SAFE_GLOBAL_ACCESS(PreaccEnabled = true;) +} - FORCEINLINE void StartNoSharedReading() { +FORCEINLINE void StartNoSharedReading() { #ifdef HAVE_OPDI - opdi::logic->setAdjointAccessMode(opdi::LogicInterface::AdjointAccessMode::Classical); - opdi::logic->addReverseBarrier(); + opdi::logic->setAdjointAccessMode(opdi::LogicInterface::AdjointAccessMode::Classical); + opdi::logic->addReverseBarrier(); #endif - } +} - FORCEINLINE void EndNoSharedReading() { +FORCEINLINE void EndNoSharedReading() { #ifdef HAVE_OPDI - opdi::logic->setAdjointAccessMode(opdi::LogicInterface::AdjointAccessMode::Atomic); - opdi::logic->addReverseBarrier(); + opdi::logic->setAdjointAccessMode(opdi::LogicInterface::AdjointAccessMode::Atomic); + opdi::logic->addReverseBarrier(); #endif - } -#endif // CODI_REVERSE_TYPE - - void Initialize(); - void Finalize(); +} +#endif // CODI_REVERSE_TYPE -} // namespace AD +void Initialize(); +void Finalize(); +} // namespace AD /*--- If we compile under OSX we have to overload some of the operators for * complex numbers to avoid the use of the standard operators @@ -579,36 +571,28 @@ namespace AD{ #ifdef __APPLE__ -namespace std{ +namespace std { - template<> - inline su2double abs(const complex& x){ - - return sqrt(x.real()*x.real() + x.imag()*x.imag()); - - } - - template<> - inline complex operator/(const complex& x, - const complex& y){ - - su2double d = (y.real()*y.real() + y.imag()*y.imag()); - su2double real = (x.real()*y.real() + x.imag()*y.imag())/d; - su2double imag = (x.imag()*y.real() - x.real()*y.imag())/d; - - return complex(real, imag); - - } +template <> +inline su2double abs(const complex& x) { + return sqrt(x.real() * x.real() + x.imag() * x.imag()); +} - template<> - inline complex operator*(const complex& x, - const complex& y){ +template <> +inline complex operator/(const complex& x, const complex& y) { + su2double d = (y.real() * y.real() + y.imag() * y.imag()); + su2double real = (x.real() * y.real() + x.imag() * y.imag()) / d; + su2double imag = (x.imag() * y.real() - x.real() * y.imag()) / d; - su2double real = (x.real()*y.real() - x.imag()*y.imag()); - su2double imag = (x.imag()*y.real() + x.real()*y.imag()); + return complex(real, imag); +} - return complex(real, imag); +template <> +inline complex operator*(const complex& x, const complex& y) { + su2double real = (x.real() * y.real() - x.imag() * y.imag()); + su2double imag = (x.imag() * y.real() + x.real() * y.imag()); - } + return complex(real, imag); } +} // namespace std #endif diff --git a/Common/include/basic_types/datatype_structure.hpp b/Common/include/basic_types/datatype_structure.hpp index 1ee72ee70b7..b4bfbd47b1b 100644 --- a/Common/include/basic_types/datatype_structure.hpp +++ b/Common/include/basic_types/datatype_structure.hpp @@ -41,130 +41,132 @@ * \author T. Albring */ namespace SU2_TYPE { - /*! - * \brief Set the (primitive) value of the datatype (needs to be implemented for each new type). - * \param[in] data - The non-primitive datatype. - * \param[in] val - The primitive value. - */ - void SetValue(su2double& data, const passivedouble &val); - - /*! - * \brief Set the secondary value of the datatype (needs to be implemented for each new type). - * \param[in] data - The non-primitive datatype. - * \param[in] val - The primitive value. - */ - void SetSecondary(su2double& data, const passivedouble &val); - - /*! - * \brief Get the (primitive) value of the datatype (needs to be specialized for active types). - * \param[in] data - The non-primitive datatype. - * \return The primitive value. - */ - passivedouble GetValue(const su2double &data); - - /*! - * \brief Get the secondary value of the datatype (needs to be implemented for each new type). - * \param[in] data - The non-primitive datatype. - * \return The primitive value. - */ - passivedouble GetSecondary(const su2double &data); - - /*! - * \brief Get the derivative value of the datatype (needs to be implemented for each new type). - * \param[in] data - The non-primitive datatype. - * \return The derivative value. - */ - passivedouble GetDerivative(const su2double &data); - - /*! - * \brief Set the derivative value of the datatype (needs to be implemented for each new type). - * \param[in] data - The non-primitive datatype. - * \param[in] val - The value of the derivative. - */ - void SetDerivative(su2double &data, const passivedouble &val); - - /*--- Implementation of the above for the different types. ---*/ +/*! + * \brief Set the (primitive) value of the datatype (needs to be implemented for each new type). + * \param[in] data - The non-primitive datatype. + * \param[in] val - The primitive value. + */ +void SetValue(su2double& data, const passivedouble& val); + +/*! + * \brief Set the secondary value of the datatype (needs to be implemented for each new type). + * \param[in] data - The non-primitive datatype. + * \param[in] val - The primitive value. + */ +void SetSecondary(su2double& data, const passivedouble& val); + +/*! + * \brief Get the (primitive) value of the datatype (needs to be specialized for active types). + * \param[in] data - The non-primitive datatype. + * \return The primitive value. + */ +passivedouble GetValue(const su2double& data); + +/*! + * \brief Get the secondary value of the datatype (needs to be implemented for each new type). + * \param[in] data - The non-primitive datatype. + * \return The primitive value. + */ +passivedouble GetSecondary(const su2double& data); + +/*! + * \brief Get the derivative value of the datatype (needs to be implemented for each new type). + * \param[in] data - The non-primitive datatype. + * \return The derivative value. + */ +passivedouble GetDerivative(const su2double& data); + +/*! + * \brief Set the derivative value of the datatype (needs to be implemented for each new type). + * \param[in] data - The non-primitive datatype. + * \param[in] val - The value of the derivative. + */ +void SetDerivative(su2double& data, const passivedouble& val); + +/*--- Implementation of the above for the different types. ---*/ #if defined(CODI_REVERSE_TYPE) || defined(CODI_FORWARD_TYPE) - FORCEINLINE void SetValue(su2double& data, const passivedouble &val) {data.setValue(val);} +FORCEINLINE void SetValue(su2double& data, const passivedouble& val) { data.setValue(val); } - FORCEINLINE passivedouble GetValue(const su2double& data) {return data.getValue();} +FORCEINLINE passivedouble GetValue(const su2double& data) { return data.getValue(); } - FORCEINLINE void SetSecondary(su2double& data, const passivedouble &val) {data.setGradient(val);} +FORCEINLINE void SetSecondary(su2double& data, const passivedouble& val) { data.setGradient(val); } - FORCEINLINE void SetDerivative(su2double& data, const passivedouble &val) {data.setGradient(val);} +FORCEINLINE void SetDerivative(su2double& data, const passivedouble& val) { data.setGradient(val); } - FORCEINLINE passivedouble GetSecondary(const su2double& data) {return data.getGradient();} +FORCEINLINE passivedouble GetSecondary(const su2double& data) { return data.getGradient(); } - FORCEINLINE passivedouble GetDerivative(const su2double& data) {return data.getGradient();} +FORCEINLINE passivedouble GetDerivative(const su2double& data) { return data.getGradient(); } -#else // passive type, no AD +#else // passive type, no AD - FORCEINLINE void SetValue(su2double& data, const passivedouble &val) {data = val;} +FORCEINLINE void SetValue(su2double& data, const passivedouble& val) { data = val; } - FORCEINLINE passivedouble GetValue(const su2double& data) {return data;} +FORCEINLINE passivedouble GetValue(const su2double& data) { return data; } - FORCEINLINE void SetSecondary(su2double&, const passivedouble &) {} +FORCEINLINE void SetSecondary(su2double&, const passivedouble&) {} - FORCEINLINE passivedouble GetDerivative(const su2double&) {return 0.0;} +FORCEINLINE passivedouble GetDerivative(const su2double&) { return 0.0; } - FORCEINLINE passivedouble GetSecondary(const su2double&) {return 0.0;} +FORCEINLINE passivedouble GetSecondary(const su2double&) { return 0.0; } - FORCEINLINE void SetDerivative(su2double &, const passivedouble &) {} +FORCEINLINE void SetDerivative(su2double&, const passivedouble&) {} #endif - /*! - * \brief Get the passive value of any variable. For most types return directly, - * specialize for su2double to call GetValue. - * \note This is a struct instead of a function because the return type of the - * su2double specialization changes. - */ - template - struct Passive { - FORCEINLINE static T Value(const T& val) {return val;} - }; - template <> - struct Passive { - FORCEINLINE static passivedouble Value(const su2double& val) {return GetValue(val);} - }; - - /*! - * \brief Casts the primitive value to int (uses GetValue, already implemented for each type). - * \param[in] data - The non-primitive datatype. - * \return - The primary value casted to int. - */ - FORCEINLINE int Int(const su2double& data) {return static_cast(SU2_TYPE::GetValue(data));} - - /*! - * \brief Casts the primitive value to short (uses GetValue, already implemented for each type). - * \param[in] data - The non-primitive datatype. - * \return - The primary value casted to short. - */ - FORCEINLINE short Short(const su2double& data) {return static_cast(SU2_TYPE::GetValue(data));} - - /*--- Special handling of the sprintf routine for non-primitive types. ---*/ - /*--- Pass-through for built-in types. ---*/ - template::value> = 0> - FORCEINLINE const T& _printGetValue(const T& val) {return val;} - /*--- Overload for expressions of active types. ---*/ - template::value> = 0> - FORCEINLINE passivedouble _printGetValue(const T& val) { return val.getValue(); } - - /*! - * \brief Wrapper to sprintf to be able to print active types and AD expressions. - * \note This is for compatibility with old code, stringstreams should be the preferred way to build strings. - * \param[in] str - Target char buffer. - * \param[in] format - Format string. - * \param[in] args - Values to be printed to the string. - */ - template - FORCEINLINE void sprintf(char* str, const char* format, Ts&&... args) { - ::sprintf(str, format, SU2_TYPE::_printGetValue(args)...); - } - FORCEINLINE void sprintf(char* str, const char* literal) { - ::sprintf(str, "%s", literal); - } +/*! + * \brief Get the passive value of any variable. For most types return directly, + * specialize for su2double to call GetValue. + * \note This is a struct instead of a function because the return type of the + * su2double specialization changes. + */ +template +struct Passive { + FORCEINLINE static T Value(const T& val) { return val; } +}; +template <> +struct Passive { + FORCEINLINE static passivedouble Value(const su2double& val) { return GetValue(val); } +}; + +/*! + * \brief Casts the primitive value to int (uses GetValue, already implemented for each type). + * \param[in] data - The non-primitive datatype. + * \return - The primary value casted to int. + */ +FORCEINLINE int Int(const su2double& data) { return static_cast(SU2_TYPE::GetValue(data)); } + +/*! + * \brief Casts the primitive value to short (uses GetValue, already implemented for each type). + * \param[in] data - The non-primitive datatype. + * \return - The primary value casted to short. + */ +FORCEINLINE short Short(const su2double& data) { return static_cast(SU2_TYPE::GetValue(data)); } + +/*--- Special handling of the sprintf routine for non-primitive types. ---*/ +/*--- Pass-through for built-in types. ---*/ +template ::value> = 0> +FORCEINLINE const T& _printGetValue(const T& val) { + return val; +} +/*--- Overload for expressions of active types. ---*/ +template ::value> = 0> +FORCEINLINE passivedouble _printGetValue(const T& val) { + return val.getValue(); +} + +/*! + * \brief Wrapper to sprintf to be able to print active types and AD expressions. + * \note This is for compatibility with old code, stringstreams should be the preferred way to build strings. + * \param[in] str - Target char buffer. + * \param[in] format - Format string. + * \param[in] args - Values to be printed to the string. + */ +template +FORCEINLINE void sprintf(char* str, const char* format, Ts&&... args) { + ::sprintf(str, format, SU2_TYPE::_printGetValue(args)...); +} +FORCEINLINE void sprintf(char* str, const char* literal) { ::sprintf(str, "%s", literal); } #define SPRINTF SU2_TYPE::sprintf -} // namespace SU2_TYPE +} // namespace SU2_TYPE diff --git a/Common/include/code_config.hpp b/Common/include/code_config.hpp index ab5aa8017e2..bbc5eebb76e 100644 --- a/Common/include/code_config.hpp +++ b/Common/include/code_config.hpp @@ -56,18 +56,24 @@ /*--- Convenience SFINAE typedef to conditionally * enable/disable function template overloads. ---*/ -template -using su2enable_if = typename std::enable_if::type; +template +using su2enable_if = typename std::enable_if::type; /*--- Compile-time type selection. ---*/ -template struct su2conditional { using type = T; }; -template struct su2conditional { using type = F; }; - -template -using su2conditional_t = typename su2conditional::type; +template +struct su2conditional { + using type = T; +}; +template +struct su2conditional { + using type = F; +}; + +template +using su2conditional_t = typename su2conditional::type; /*! \brief Static cast "In" to "Out", in debug builds a dynamic cast is used. */ -template +template FORCEINLINE Out su2staticcast_p(In ptr) { static_assert(std::is_pointer::value, "This expects a pointer"); #ifndef NDEBUG @@ -85,7 +91,7 @@ FORCEINLINE Out su2staticcast_p(In ptr) { /*--- Depending on the datatype defined during the configuration, * include the correct definition, and create the main typedef. ---*/ -#if defined(CODI_REVERSE_TYPE) // reverse mode AD +#if defined(CODI_REVERSE_TYPE) // reverse mode AD #include "codi.hpp" #include "codi/tools/data/externalFunctionUserData.hpp" @@ -94,19 +100,19 @@ using su2double = codi::RealReverseIndexOpenMP; #else #if defined(CODI_INDEX_TAPE) using su2double = codi::RealReverseIndex; -//#elif defined(CODI_PRIMAL_TAPE) -//using su2double = codi::RealReversePrimal; -//#elif defined(CODI_PRIMAL_INDEX_TAPE) -//using su2double = codi::RealReversePrimalIndex; +// #elif defined(CODI_PRIMAL_TAPE) +// using su2double = codi::RealReversePrimal; +// #elif defined(CODI_PRIMAL_INDEX_TAPE) +// using su2double = codi::RealReversePrimalIndex; #else using su2double = codi::RealReverse; #endif #endif -#elif defined(CODI_FORWARD_TYPE) // forward mode AD +#elif defined(CODI_FORWARD_TYPE) // forward mode AD #include "codi.hpp" using su2double = codi::RealForward; -#else // primal / direct / no AD +#else // primal / direct / no AD using su2double = double; #endif diff --git a/Common/include/containers/C2DContainer.hpp b/Common/include/containers/C2DContainer.hpp index 119eed0b55a..8e726ee4ef9 100644 --- a/Common/include/containers/C2DContainer.hpp +++ b/Common/include/containers/C2DContainer.hpp @@ -42,19 +42,17 @@ * \brief Supported ways to flatten a matrix into an array. * Contiguous rows or contiguous columns respectively. */ -enum class StorageType {RowMajor=0, ColumnMajor=1}; +enum class StorageType { RowMajor = 0, ColumnMajor = 1 }; /*! * \enum SizeType * \brief Special value "DynamicSize" to indicate a dynamic size. */ -enum SizeType : size_t {DynamicSize=0}; - +enum SizeType : size_t { DynamicSize = 0 }; /*--- Namespace to "hide" helper classes and functions used by the container class. ---*/ -namespace container_details -{ +namespace container_details { /*! * \class AccessorImpl * \brief Base accessor class and version of template for both sizes known at compile time. @@ -62,25 +60,24 @@ namespace container_details * The actual container inherits from this class, this is to reduce the number of * methods that need to be redefined with each size specialization. */ -template -class AccessorImpl -{ - static_assert(!(StaticRows==1 && Store==StorageType::ColumnMajor), - "Row vector should have row-major storage."); - static_assert(!(StaticCols==1 && Store==StorageType::RowMajor), +template +class AccessorImpl { + static_assert(!(StaticRows == 1 && Store == StorageType::ColumnMajor), "Row vector should have row-major storage."); + static_assert(!(StaticCols == 1 && Store == StorageType::RowMajor), "Column vector should have column-major storage."); -protected: + + protected: /*! * For static specializations AlignSize will force the alignment * specification of the entire class, not just the data. */ - alignas(AlignSize) Scalar_t m_data[StaticRows*StaticCols]; + alignas(AlignSize) Scalar_t m_data[StaticRows * StaticCols]; /*! * Static size specializations use this do-nothing allocation macro. */ -#define DUMMY_ALLOCATOR \ - void m_allocate(size_t sz, Index_t rows, Index_t cols) noexcept {}\ +#define DUMMY_ALLOCATOR \ + void m_allocate(size_t sz, Index_t rows, Index_t cols) noexcept {} \ void m_destroy() noexcept {} /*! @@ -92,26 +89,25 @@ class AccessorImpl * default construct the elements of non-trivial type. Such types also * need to be destructed explicitly before freeing the memory. */ -#define REAL_ALLOCATOR(EXTRA) \ - static_assert(MemoryAllocation::is_power_of_two(AlignSize), \ - "AlignSize is not a power of two."); \ - \ - void m_allocate(size_t sz, Index_t rows, Index_t cols) noexcept { \ - EXTRA; \ - m_data = MemoryAllocation::aligned_alloc(AlignSize,sz); \ - if (!std::is_trivial::value) \ - for (size_t i = 0; i < size(); ++i) new (m_data+i) Scalar_t(); \ - } \ - \ - void m_destroy() noexcept { \ - if (!std::is_trivial::value) \ - for (size_t i = 0; i < size(); ++i) m_data[i].~Scalar_t(); \ - MemoryAllocation::aligned_free(m_data); \ +#define REAL_ALLOCATOR(EXTRA) \ + static_assert(MemoryAllocation::is_power_of_two(AlignSize), "AlignSize is not a power of two."); \ + \ + void m_allocate(size_t sz, Index_t rows, Index_t cols) noexcept { \ + EXTRA; \ + m_data = MemoryAllocation::aligned_alloc(AlignSize, sz); \ + if (!std::is_trivial::value) \ + for (size_t i = 0; i < size(); ++i) new (m_data + i) Scalar_t(); \ + } \ + \ + void m_destroy() noexcept { \ + if (!std::is_trivial::value) \ + for (size_t i = 0; i < size(); ++i) m_data[i].~Scalar_t(); \ + MemoryAllocation::aligned_free(m_data); \ } DUMMY_ALLOCATOR -public: + public: /*! * Dynamic types need to manage internal data as the derived class would * not compile if it tried to set m_data to null on static specializations. @@ -120,241 +116,226 @@ class AccessorImpl * The default ctor needs to "INIT" some fields. The move ctor/assign need * to "MOVE" those fields, i.e. copy and set "other" appropriately. */ -#define CUSTOM_CTOR_AND_DTOR_BASE(INIT,MOVE) \ - AccessorImpl() noexcept : m_data(nullptr) {INIT;} \ - \ - AccessorImpl(AccessorImpl&& other) noexcept \ - { \ - MOVE; m_data=other.m_data; other.m_data=nullptr; \ - } \ - \ - AccessorImpl& operator= (AccessorImpl&& other) noexcept \ - { \ - m_destroy(); \ - MOVE; m_data=other.m_data; other.m_data=nullptr; \ - return *this; \ - } \ - \ - ~AccessorImpl() noexcept {m_destroy();} +#define CUSTOM_CTOR_AND_DTOR_BASE(INIT, MOVE) \ + AccessorImpl() noexcept : m_data(nullptr) { INIT; } \ + \ + AccessorImpl(AccessorImpl&& other) noexcept { \ + MOVE; \ + m_data = other.m_data; \ + other.m_data = nullptr; \ + } \ + \ + AccessorImpl& operator=(AccessorImpl&& other) noexcept { \ + m_destroy(); \ + MOVE; \ + m_data = other.m_data; \ + other.m_data = nullptr; \ + return *this; \ + } \ + \ + ~AccessorImpl() noexcept { m_destroy(); } /*! * Shorthand for when specialization has only one more member than m_data. */ -#define CUSTOM_CTOR_AND_DTOR(X) \ - CUSTOM_CTOR_AND_DTOR_BASE(X=0, X=other.X; other.X=0) +#define CUSTOM_CTOR_AND_DTOR(X) CUSTOM_CTOR_AND_DTOR_BASE(X = 0, X = other.X; other.X = 0) /*! * Universal accessors return a raw pointer to the data. */ -#define UNIV_ACCESSORS \ - bool empty() const noexcept {return size()==0;} \ - Scalar_t* data() noexcept {return m_data;} \ - const Scalar_t* data() const noexcept {return m_data;} \ - Scalar_t* begin() noexcept {return data();} \ - const Scalar_t* begin() const noexcept {return data();} \ - Scalar_t* end() noexcept {return data()+size();} \ - const Scalar_t* end() const noexcept {return data()+size();} +#define UNIV_ACCESSORS \ + bool empty() const noexcept { return size() == 0; } \ + Scalar_t* data() noexcept { return m_data; } \ + const Scalar_t* data() const noexcept { return m_data; } \ + Scalar_t* begin() noexcept { return data(); } \ + const Scalar_t* begin() const noexcept { return data(); } \ + Scalar_t* end() noexcept { return data() + size(); } \ + const Scalar_t* end() const noexcept { return data() + size(); } /*! * Operator (,) gives pointwise access, operator [] returns a pointer to the * first element of the row/column of a row/column-major matrix respectively. */ -#define MATRIX_ACCESSORS(M,N) \ - UNIV_ACCESSORS \ - Index_t rows() const noexcept {return M;} \ - Index_t cols() const noexcept {return N;} \ - size_t size() const noexcept {return M*N;} \ - \ - const Scalar_t& operator() (const Index_t i, \ - const Index_t j) const noexcept \ - { \ - assert(i>=0 && i=0 && j( const_this(i,j) ); \ - } \ - \ - const Scalar_t* operator[] (const Index_t k) const noexcept \ - { \ - if(Store == StorageType::RowMajor) { \ - assert(k>=0 && k=0 && k( const_this[k] ); \ +#define MATRIX_ACCESSORS(M, N) \ + UNIV_ACCESSORS \ + Index_t rows() const noexcept { return M; } \ + Index_t cols() const noexcept { return N; } \ + size_t size() const noexcept { return M * N; } \ + \ + const Scalar_t& operator()(const Index_t i, const Index_t j) const noexcept { \ + assert(i >= 0 && i < M && j >= 0 && j < N); \ + return m_data[(Store == StorageType::RowMajor) ? i * N + j : i + j * M]; \ + } \ + \ + Scalar_t& operator()(const Index_t i, const Index_t j) noexcept { \ + const AccessorImpl& const_this = *this; \ + return const_cast(const_this(i, j)); \ + } \ + \ + const Scalar_t* operator[](const Index_t k) const noexcept { \ + if (Store == StorageType::RowMajor) { \ + assert(k >= 0 && k < M); \ + return &m_data[k * N]; \ + } else { \ + assert(k >= 0 && k < N); \ + return &m_data[k * M]; \ + } \ + } \ + \ + Scalar_t* operator[](const Index_t k) noexcept { \ + const AccessorImpl& const_this = *this; \ + return const_cast(const_this[k]); \ } /*! * Vectors provide both [] and () with the same behavior. */ -#define VECTOR_ACCESSORS(M,ROWMAJOR) \ - UNIV_ACCESSORS \ - Index_t rows() const noexcept {return ROWMAJOR? 1 : M;} \ - Index_t cols() const noexcept {return ROWMAJOR? M : 1;} \ - size_t size() const noexcept {return M;} \ - \ - Scalar_t& operator() (const Index_t i) noexcept \ - { \ - assert(i>=0 && i=0 && i=0 && i=0 && i= 0 && i < M); \ + return m_data[i]; \ + } \ + \ + const Scalar_t& operator()(const Index_t i) const noexcept { \ + assert(i >= 0 && i < M); \ + return m_data[i]; \ + } \ + \ + Scalar_t& operator[](const Index_t i) noexcept { \ + assert(i >= 0 && i < M); \ + return m_data[i]; \ + } \ + \ + const Scalar_t& operator[](const Index_t i) const noexcept { \ + assert(i >= 0 && i < M); \ + return m_data[i]; \ } - MATRIX_ACCESSORS(StaticRows,StaticCols) + MATRIX_ACCESSORS(StaticRows, StaticCols) }; /*! * Specialization for compile-time number of columns. */ -template -class AccessorImpl -{ - static_assert(!(StaticCols==1 && Store==StorageType::RowMajor), +template +class AccessorImpl { + static_assert(!(StaticCols == 1 && Store == StorageType::RowMajor), "Column vector should have column-major storage."); -protected: + + protected: Index_t m_rows; Scalar_t* m_data; - REAL_ALLOCATOR(m_rows=rows) + REAL_ALLOCATOR(m_rows = rows) -public: + public: CUSTOM_CTOR_AND_DTOR(m_rows) - MATRIX_ACCESSORS(m_rows,StaticCols) + MATRIX_ACCESSORS(m_rows, StaticCols) }; /*! * Specialization for compile-time number of columns. */ -template -class AccessorImpl -{ - static_assert(!(StaticRows==1 && Store==StorageType::ColumnMajor), - "Row vector should have row-major storage."); -protected: +template +class AccessorImpl { + static_assert(!(StaticRows == 1 && Store == StorageType::ColumnMajor), "Row vector should have row-major storage."); + + protected: Index_t m_cols; Scalar_t* m_data; - REAL_ALLOCATOR(m_cols=cols) + REAL_ALLOCATOR(m_cols = cols) -public: + public: CUSTOM_CTOR_AND_DTOR(m_cols) - MATRIX_ACCESSORS(StaticRows,m_cols) + MATRIX_ACCESSORS(StaticRows, m_cols) }; /*! * Specialization for fully dynamic sizes (generic matrix). */ -template -class AccessorImpl -{ -protected: +template +class AccessorImpl { + protected: Index_t m_rows, m_cols; Scalar_t* m_data; - REAL_ALLOCATOR(m_rows=rows; m_cols=cols) + REAL_ALLOCATOR(m_rows = rows; m_cols = cols) -public: - CUSTOM_CTOR_AND_DTOR_BASE(m_rows = 0; m_cols = 0, - m_rows = other.m_rows; other.m_rows = 0; - m_cols = other.m_cols; other.m_cols = 0) + public: + CUSTOM_CTOR_AND_DTOR_BASE(m_rows = 0; m_cols = 0, m_rows = other.m_rows; other.m_rows = 0; m_cols = other.m_cols; + other.m_cols = 0) - MATRIX_ACCESSORS(m_rows,m_cols) + MATRIX_ACCESSORS(m_rows, m_cols) }; /*! * Specialization for static column-vector. */ -template -class AccessorImpl -{ -protected: +template +class AccessorImpl { + protected: alignas(AlignSize) Scalar_t m_data[StaticRows]; DUMMY_ALLOCATOR -public: - VECTOR_ACCESSORS(StaticRows,false) + public: + VECTOR_ACCESSORS(StaticRows, false) }; /*! * Specialization for dynamic column-vector. */ -template -class AccessorImpl -{ -protected: +template +class AccessorImpl { + protected: Index_t m_rows; Scalar_t* m_data; - REAL_ALLOCATOR(m_rows=rows) + REAL_ALLOCATOR(m_rows = rows) -public: + public: CUSTOM_CTOR_AND_DTOR(m_rows) - VECTOR_ACCESSORS(m_rows,false) + VECTOR_ACCESSORS(m_rows, false) }; /*! * Specialization for static row-vector. */ -template -class AccessorImpl -{ -protected: +template +class AccessorImpl { + protected: alignas(AlignSize) Scalar_t m_data[StaticCols]; DUMMY_ALLOCATOR -public: - VECTOR_ACCESSORS(StaticCols,true) + public: + VECTOR_ACCESSORS(StaticCols, true) }; /*! * Specialization for dynamic row-vector. */ -template -class AccessorImpl -{ -protected: +template +class AccessorImpl { + protected: Index_t m_cols; Scalar_t* m_data; - REAL_ALLOCATOR(m_cols=cols) + REAL_ALLOCATOR(m_cols = cols) -public: + public: CUSTOM_CTOR_AND_DTOR(m_cols) - VECTOR_ACCESSORS(m_cols,true) + VECTOR_ACCESSORS(m_cols, true) }; #undef CUSTOM_CTOR_AND_DTOR_BASE @@ -364,7 +345,7 @@ class AccessorImpl -class C2DContainer : - public container_details::AccessorImpl -{ - static_assert(std::is_integral::value,""); - -private: - using Base = container_details::AccessorImpl; - using Base::m_data; +template +class C2DContainer + : public container_details::AccessorImpl { + static_assert(std::is_integral::value, ""); + + private: + using Base = container_details::AccessorImpl; using Base::m_allocate; + using Base::m_data; using Base::m_destroy; -public: - using Base::size; - using Base::rows; + + public: using Base::cols; + using Base::rows; + using Base::size; using Index = Index_t; using Scalar = Scalar_t; static constexpr StorageType Storage = Store; - static constexpr bool IsVector = (StaticRows==1) || (StaticCols==1); - static constexpr bool IsRowMajor = (Store==StorageType::RowMajor); - static constexpr bool IsColumnMajor = (Store==StorageType::ColumnMajor); - static constexpr size_t StaticSize = StaticRows*StaticCols; + static constexpr bool IsVector = (StaticRows == 1) || (StaticCols == 1); + static constexpr bool IsRowMajor = (Store == StorageType::RowMajor); + static constexpr bool IsColumnMajor = (Store == StorageType::ColumnMajor); + static constexpr size_t StaticSize = StaticRows * StaticCols; /*! * \brief Scalar iterator to the inner dimension of the container, read-only. @@ -416,18 +397,18 @@ class C2DContainer : private: const Index m_increment; const Scalar* m_ptr; + public: CInnerIter() = delete; - FORCEINLINE CInnerIter(const Scalar* ptr, Index increment) noexcept : - m_increment(increment), - m_ptr(ptr) { - } + FORCEINLINE CInnerIter(const Scalar* ptr, Index increment) noexcept : m_increment(increment), m_ptr(ptr) {} - FORCEINLINE Scalar operator* () const noexcept { return *m_ptr; } + FORCEINLINE Scalar operator*() const noexcept { return *m_ptr; } FORCEINLINE CInnerIter operator++(int) noexcept { - auto ret = *this; m_ptr += m_increment; return ret; + auto ret = *this; + m_ptr += m_increment; + return ret; } }; @@ -435,71 +416,72 @@ class C2DContainer : * \brief SIMD iterator to the inner dimension of the container, * read-only, generic non-contiguous access. */ - template + template class CInnerIterGather { private: - static_assert(std::is_integral::value,""); - enum {Size = IndexSIMD_t::Size}; + static_assert(std::is_integral::value, ""); + enum { Size = IndexSIMD_t::Size }; IndexSIMD_t m_offsets; const Index m_increment; const Scalar* const m_data; + public: CInnerIterGather() = delete; - FORCEINLINE CInnerIterGather(const Scalar* data, Index increment, IndexSIMD_t offsets) noexcept : - m_offsets(offsets), - m_increment(increment), - m_data(data) { - } + FORCEINLINE CInnerIterGather(const Scalar* data, Index increment, IndexSIMD_t offsets) noexcept + : m_offsets(offsets), m_increment(increment), m_data(data) {} - FORCEINLINE simd::Array operator* () const noexcept { - return simd::Array(m_data, m_offsets); + FORCEINLINE simd::Array operator*() const noexcept { + return simd::Array(m_data, m_offsets); } FORCEINLINE CInnerIterGather operator++(int) noexcept { - auto ret = *this; m_offsets += m_increment; return ret; + auto ret = *this; + m_offsets += m_increment; + return ret; } }; -private: + private: /*! * \brief Logic to resize data according to arguments, a non DynamicSize cannot be changed. */ - size_t m_resize(Index_t rows, Index_t cols) noexcept - { + size_t m_resize(Index_t rows, Index_t cols) noexcept { /*--- fully static, no allocation needed ---*/ - if(StaticSize!=DynamicSize) return StaticSize; + if (StaticSize != DynamicSize) return StaticSize; /*--- dynamic row vector, swap size specification ---*/ - if(StaticRows==1 && IsVector) {cols = rows; rows = 1;} + if (StaticRows == 1 && IsVector) { + cols = rows; + rows = 1; + } /*--- assert a static size is not being asked to change ---*/ - if(StaticRows!=DynamicSize) assert(rows==StaticRows && "A static size was asked to change."); - if(StaticCols!=DynamicSize) assert(cols==StaticCols && "A static size was asked to change."); + if (StaticRows != DynamicSize) assert(rows == StaticRows && "A static size was asked to change."); + if (StaticCols != DynamicSize) assert(cols == StaticCols && "A static size was asked to change."); /*--- "rectify" sizes before continuing as asserts are usually dissabled ---*/ - rows = (StaticRows!=DynamicSize)? StaticRows : rows; - cols = (StaticCols!=DynamicSize)? StaticCols : cols; + rows = (StaticRows != DynamicSize) ? StaticRows : rows; + cols = (StaticCols != DynamicSize) ? StaticCols : cols; /*--- number of requested elements ---*/ - size_t reqSize = rows*cols; + size_t reqSize = rows * cols; /*--- compare with current dimensions to determine if deallocation is needed, also makes the container safe against self assignment no need to check for 0 size as the allocators handle that ---*/ - if(rows==this->rows() && cols==this->cols()) - return reqSize; + if (rows == this->rows() && cols == this->cols()) return reqSize; m_destroy(); /*--- request actual allocation to base class as it needs specialization ---*/ - size_t bytes = reqSize*sizeof(Scalar_t); - m_allocate(bytes,rows,cols); + size_t bytes = reqSize * sizeof(Scalar_t); + m_allocate(bytes, rows, cols); return reqSize; } -public: + public: /*! * \brief Default ctor. */ @@ -509,27 +491,22 @@ class C2DContainer : * \brief Sizing ctor (no initialization of data). * For matrices size1 is rows and size2 columns, for vectors size1 is lenght and size2 is ignored. */ - C2DContainer(const Index_t size1, const Index_t size2 = 1) noexcept : Base() - { - m_resize(size1,size2); - } + C2DContainer(const Index_t size1, const Index_t size2 = 1) noexcept : Base() { m_resize(size1, size2); } /*! * \brief Copy ctor. */ - C2DContainer(const C2DContainer& other) noexcept : Base() - { - size_t sz = m_resize(other.rows(),other.cols()); - for(size_t i=0; i - FORCEINLINE CInnerIterGather > innerIter(simd::Array row) const noexcept - { - return CInnerIterGather >(m_data, IsRowMajor? 1 : rows(), IsRowMajor? row*cols() : row); + template + FORCEINLINE CInnerIterGather > innerIter(simd::Array row) const noexcept { + return CInnerIterGather >(m_data, IsRowMajor ? 1 : rows(), IsRowMajor ? row * cols() : row); } /*! @@ -594,33 +566,31 @@ class C2DContainer : * \param[in] row - Row of the matrix. * \param[in] start - Starting column to copy the data (amount determined by container size). */ - template - FORCEINLINE StaticContainer get(Index_t row, Index_t start = 0) const noexcept - { + template + FORCEINLINE StaticContainer get(Index_t row, Index_t start = 0) const noexcept { constexpr size_t Size = StaticContainer::StaticSize; static_assert(Size, "This method requires a static output type."); - assert(Size <= cols()-start); + assert(Size <= cols() - start); StaticContainer ret; SU2_OMP_SIMD - for (size_t i=0; i - FORCEINLINE StaticContainer get(simd::Array row, Index_t start = 0) const noexcept - { + template + FORCEINLINE StaticContainer get(simd::Array row, Index_t start = 0) const noexcept { constexpr size_t Size = StaticContainer::StaticSize; static_assert(Size, "This method requires a static output type."); - assert(Size <= cols()-start); + assert(Size <= cols() - start); StaticContainer ret; - for (size_t k=0; k using su2vector = C2DContainer; -template using su2matrix = C2DContainer; -template using ColMajorMatrix = C2DContainer; +template +using su2vector = C2DContainer; +template +using su2matrix = C2DContainer; +template +using ColMajorMatrix = C2DContainer; using su2activevector = su2vector; using su2activematrix = su2matrix; @@ -639,4 +612,4 @@ using su2activematrix = su2matrix; using su2passivevector = su2vector; using su2passivematrix = su2matrix; -/// @} \ No newline at end of file +/// @} diff --git a/Common/include/containers/CFastFindAndEraseQueue.hpp b/Common/include/containers/CFastFindAndEraseQueue.hpp index 01b24044e60..004500dcc86 100644 --- a/Common/include/containers/CFastFindAndEraseQueue.hpp +++ b/Common/include/containers/CFastFindAndEraseQueue.hpp @@ -43,19 +43,18 @@ * \param[in] CleanupThreshold - Number of marked items that triggers full cleanup. * \note It would not be a good idea to use non-trivial item types. */ -template::max(), - size_t CleanupThreshold = 8192> +template ::max(), + size_t CleanupThreshold = 8192> class CFastFindAndEraseQueue { -public: - enum {ErasedValue = ErasedValue_}; + public: + enum { ErasedValue = ErasedValue_ }; using ItemType = ItemType_; using Iterator = typename std::vector::const_iterator; -private: + private: size_t erasedCounter = 0; /*!< \brief How many items have been marked since last cleanup. */ std::vector items; /*!< \brief The stored items. */ - std::unordered_map indexes; /*!< \brief Map items to their location. */ + std::unordered_map indexes; /*!< \brief Map items to their location. */ /*! * \brief Cleanup, shifts non-erased items forward, re-mapping them. @@ -74,7 +73,7 @@ class CFastFindAndEraseQueue { erasedCounter = 0; } -public: + public: /*! * \brief Default construct. */ @@ -85,7 +84,7 @@ class CFastFindAndEraseQueue { */ CFastFindAndEraseQueue(size_t N) { items.resize(N); - for (size_t i=0; isecond; assert(items[idx] != ErasedValue && "The item was already erased?!"); @@ -139,5 +139,4 @@ class CFastFindAndEraseQueue { return true; } - }; diff --git a/Common/include/containers/CVertexMap.hpp b/Common/include/containers/CVertexMap.hpp index a0152d22881..54e5ee85da0 100644 --- a/Common/include/containers/CVertexMap.hpp +++ b/Common/include/containers/CVertexMap.hpp @@ -49,15 +49,15 @@ * * \note For efficiency use the smallest type that can fit the maximum number of vertices. */ -template +template class CVertexMap { static_assert(std::is_unsigned::value && std::is_integral::value, "Vertex map requires an unsigned integral type (e.g. unsigned)."); private: - su2vector Map; /*!< \brief Map from range 0-(nPoint-1) to 1-nVertex. */ - bool isValid = false; /*!< \brief Set to true when it is safe to use the accessors. */ - T nVertex = 0; /*!< \brief Number of vertices. */ + su2vector Map; /*!< \brief Map from range 0-(nPoint-1) to 1-nVertex. */ + bool isValid = false; /*!< \brief Set to true when it is safe to use the accessors. */ + T nVertex = 0; /*!< \brief Number of vertices. */ public: /*! @@ -94,9 +94,7 @@ class CVertexMap { /*! * \brief Get wheter a point is marked as vertex. */ - inline bool GetIsVertex(unsigned long iPoint) const { - return (Map(iPoint) != 0); - } + inline bool GetIsVertex(unsigned long iPoint) const { return (Map(iPoint) != 0); } /*! * \brief Build the point to vertex map. @@ -108,8 +106,7 @@ class CVertexMap { nVertex = 0; for (unsigned long iPoint = 0; iPoint < Map.size(); ++iPoint) - if (Map(iPoint)!=0) - Map(iPoint) = ++nVertex; + if (Map(iPoint) != 0) Map(iPoint) = ++nVertex; isValid = true; } @@ -121,12 +118,11 @@ class CVertexMap { * \param[in,out] iVertex - On entry point index, on exit vertex index. * \return True if conversion is successful (i.e. point is vertex). */ - inline bool GetVertexIndex(unsigned long &iVertex) const { + inline bool GetVertexIndex(unsigned long& iVertex) const { assert(isValid && "Vertex map is not in valid state."); iVertex = Map(iVertex); - if(iVertex==0) return false; // not a vertex - iVertex--; // decrement for 0 based - return true; // is a vertex + if (iVertex == 0) return false; // not a vertex + iVertex--; // decrement for 0 based + return true; // is a vertex } - }; diff --git a/Common/include/containers/container_decorators.hpp b/Common/include/containers/container_decorators.hpp index 5484a7e873e..c6c0f3f1201 100644 --- a/Common/include/containers/container_decorators.hpp +++ b/Common/include/containers/container_decorators.hpp @@ -36,49 +36,55 @@ /*! * \brief Class to represent a matrix (without owning the data, this just wraps a pointer). */ -template +template class CMatrixView { -public: + public: using Scalar = typename std::remove_const::type; using Index = unsigned long; -private: + private: T* m_ptr; Index m_cols; -public: + public: CMatrixView(T* ptr = nullptr, Index cols = 0) : m_ptr(ptr), m_cols(cols) {} - template friend class CMatrixView; - template + template + friend class CMatrixView; + template CMatrixView(const CMatrixView& other) : m_ptr(other.m_ptr), m_cols(other.m_cols) {} explicit CMatrixView(su2matrix& mat) : m_ptr(mat.data()), m_cols(mat.cols()) {} - template::value> = 0> + template ::value> = 0> explicit CMatrixView(const su2matrix& mat) : m_ptr(mat.data()), m_cols(mat.cols()) {} - const Scalar* operator[] (Index i) const noexcept { return &m_ptr[i*m_cols]; } - const Scalar& operator() (Index i, Index j) const noexcept { return m_ptr[i*m_cols + j]; } + const Scalar* operator[](Index i) const noexcept { return &m_ptr[i * m_cols]; } + const Scalar& operator()(Index i, Index j) const noexcept { return m_ptr[i * m_cols + j]; } - template::value> = 0> - Scalar* operator[] (Index i) noexcept { return &m_ptr[i*m_cols]; } + template ::value> = 0> + Scalar* operator[](Index i) noexcept { + return &m_ptr[i * m_cols]; + } - template::value> = 0> - Scalar& operator() (Index i, Index j) noexcept { return m_ptr[i*m_cols + j]; } + template ::value> = 0> + Scalar& operator()(Index i, Index j) noexcept { + return m_ptr[i * m_cols + j]; + } - friend CMatrixView operator+ (CMatrixView mv, Index incr) { return CMatrixView(mv[incr], mv.m_cols); } + friend CMatrixView operator+(CMatrixView mv, Index incr) { return CMatrixView(mv[incr], mv.m_cols); } }; /*! * \class C3DContainerDecorator * \brief Decorate a matrix type (Storage) with 3 dimensions. */ -template +template class C3DContainerDecorator { static_assert(!Storage::IsVector, "Storage type must be a matrix."); static_assert(Storage::IsRowMajor, "Storage type must be row major."); -public: + + public: using Scalar = typename Storage::Scalar; using Index = typename Storage::Index; static constexpr bool IsRowMajor = true; @@ -88,14 +94,14 @@ class C3DContainerDecorator { using ConstMatrix = CMatrixView; using CInnerIter = typename Storage::CInnerIter; - template - using CInnerIterGather = typename Storage::template CInnerIterGather >; + template + using CInnerIterGather = typename Storage::template CInnerIterGather >; -private: + private: Storage m_storage; Index m_innerSz; -public: + public: C3DContainerDecorator() = default; C3DContainerDecorator(Index length, Index rows, Index cols, Scalar value = 0) noexcept { @@ -104,7 +110,7 @@ class C3DContainerDecorator { void resize(Index length, Index rows, Index cols, Scalar value = 0) noexcept { m_innerSz = cols; - m_storage.resize(length, rows*cols) = value; + m_storage.resize(length, rows * cols) = value; } /*! @@ -118,34 +124,36 @@ class C3DContainerDecorator { /*! * \brief Element-wise access. */ - Scalar& operator() (Index i, Index j, Index k) noexcept { return m_storage(i, j*m_innerSz + k); } - const Scalar& operator() (Index i, Index j, Index k) const noexcept { return m_storage(i, j*m_innerSz + k); } + Scalar& operator()(Index i, Index j, Index k) noexcept { return m_storage(i, j * m_innerSz + k); } + const Scalar& operator()(Index i, Index j, Index k) const noexcept { return m_storage(i, j * m_innerSz + k); } /*! * \brief Matrix access. */ - Matrix operator[] (Index i) noexcept { return Matrix(m_storage[i], m_innerSz); } - ConstMatrix operator[] (Index i) const noexcept { return ConstMatrix(m_storage[i], m_innerSz); } + Matrix operator[](Index i) noexcept { return Matrix(m_storage[i], m_innerSz); } + ConstMatrix operator[](Index i) const noexcept { return ConstMatrix(m_storage[i], m_innerSz); } /*! * \brief Matrix access with an offset. */ - Matrix operator() (Index i, Index j) noexcept { return Matrix(m_storage[i]+j*m_innerSz, m_innerSz); } - ConstMatrix operator() (Index i, Index j) const noexcept { return ConstMatrix(m_storage[i]+j*m_innerSz, m_innerSz); } + Matrix operator()(Index i, Index j) noexcept { return Matrix(m_storage[i] + j * m_innerSz, m_innerSz); } + ConstMatrix operator()(Index i, Index j) const noexcept { + return ConstMatrix(m_storage[i] + j * m_innerSz, m_innerSz); + } /*! * \brief Get a scalar iterator to the inner-most dimension of the container. */ FORCEINLINE CInnerIter innerIter(Index i, Index j) const noexcept { - return CInnerIter(&m_storage(i, j*m_innerSz), 1); + return CInnerIter(&m_storage(i, j * m_innerSz), 1); } /*! * \brief Get a SIMD gather iterator to the inner-most dimension of the container. */ - template - FORCEINLINE CInnerIterGather innerIter(simd::Array i, Index j) const noexcept { - return CInnerIterGather(m_storage.data(), 1, i*m_storage.cols() + j*m_innerSz); + template + FORCEINLINE CInnerIterGather innerIter(simd::Array i, Index j) const noexcept { + return CInnerIterGather(m_storage.data(), 1, i * m_storage.cols() + j * m_innerSz); } /*! @@ -153,9 +161,9 @@ class C3DContainerDecorator { * \param[in] i - Outer index. * \param[in] j - Starting middle index for the copy (amount determined by container size). */ - template + template FORCEINLINE StaticContainer get(Int i, Index j = 0) const noexcept { - return m_storage.template get(i, j*m_innerSz); + return m_storage.template get(i, j * m_innerSz); } }; @@ -173,9 +181,8 @@ using CVectorOfMatrix = C3DDoubleMatrix; * \note The constness of the object is derived from the template type, but * we allways keep a reference, never a copy of the associated vector. */ -template -struct C2DDummyLastView -{ +template +struct C2DDummyLastView { static_assert(T::IsVector, "This class decorates vectors."); using Index = typename T::Index; using Scalar = typename T::Scalar; @@ -186,16 +193,12 @@ struct C2DDummyLastView C2DDummyLastView(T& ref) : data(ref) {} - template::value> = 0> - Scalar& operator() (Index i, Index) noexcept - { + template ::value> = 0> + Scalar& operator()(Index i, Index) noexcept { return data(i); } - const Scalar& operator() (Index i, Index) const noexcept - { - return data(i); - } + const Scalar& operator()(Index i, Index) const noexcept { return data(i); } }; /*! @@ -205,9 +208,8 @@ struct C2DDummyLastView * \note The constness of the object is derived from the template type, but * we allways keep a reference, never a copy of the associated matrix. */ -template -struct C3DDummyMiddleView -{ +template +struct C3DDummyMiddleView { static_assert(!T::IsVector, "This class decorates matrices."); using Index = typename T::Index; using Scalar = typename T::Scalar; @@ -218,16 +220,12 @@ struct C3DDummyMiddleView C3DDummyMiddleView(T& ref) : data(ref) {} - template::value> = 0> - Scalar& operator() (Index i, Index, Index k) noexcept - { - return data(i,k); + template ::value> = 0> + Scalar& operator()(Index i, Index, Index k) noexcept { + return data(i, k); } - const Scalar& operator() (Index i, Index, Index k) const noexcept - { - return data(i,k); - } + const Scalar& operator()(Index i, Index, Index k) const noexcept { return data(i, k); } }; /*--- Helper functions to allocate containers of containers. ---*/ @@ -241,10 +239,10 @@ struct C3DDummyMiddleView * \tparam IndexVector - type of N * \tparam VectorOfVector - type of X */ -template +template inline void AllocVectorOfVectors(size_t M, const IndexVector& N, VectorOfVector& X, Scalar val = 0) { X.resize(M); - for(size_t i = 0; i < M; ++i){ + for (size_t i = 0; i < M; ++i) { X[i].resize(N[i]); for (auto& x : X[i]) x = val; } @@ -253,7 +251,7 @@ inline void AllocVectorOfVectors(size_t M, const IndexVector& N, VectorOfVector& /*! * \overload Deduce outer size from index vector. */ -template +template inline void AllocVectorOfVectors(const IndexVector& N, VectorOfVector& X, Scalar val = 0) { auto M = N.size(); AllocVectorOfVectors(M, N, X, val); @@ -269,11 +267,11 @@ inline void AllocVectorOfVectors(const IndexVector& N, VectorOfVector& X, Scalar * \tparam IndexVector - type of N * \tparam VectorOfMatrix - type of X */ -template -inline void AllocVectorOfMatrices(size_t M, const IndexVector& N, size_t P, VectorOfMatrix& X, Scalar val=0) { +template +inline void AllocVectorOfMatrices(size_t M, const IndexVector& N, size_t P, VectorOfMatrix& X, Scalar val = 0) { X.resize(M); - for(size_t i = 0; i < M; ++i){ - X[i].resize(N[i],P); + for (size_t i = 0; i < M; ++i) { + X[i].resize(N[i], P); for (auto& x : X[i]) x = val; } } @@ -281,10 +279,10 @@ inline void AllocVectorOfMatrices(size_t M, const IndexVector& N, size_t P, Vect /*! * \overload Deduce outer size from index vector. */ -template -inline void AllocVectorOfMatrices(const IndexVector& N, size_t P, VectorOfMatrix& X, Scalar val=0) { +template +inline void AllocVectorOfMatrices(const IndexVector& N, size_t P, VectorOfMatrix& X, Scalar val = 0) { auto M = N.size(); AllocVectorOfMatrices(M, N, P, X, val); } -/// @} \ No newline at end of file +/// @} diff --git a/Common/include/fem/fem_cgns_elements.hpp b/Common/include/fem/fem_cgns_elements.hpp index 16af6f34ecc..8e9458d8d06 100644 --- a/Common/include/fem/fem_cgns_elements.hpp +++ b/Common/include/fem/fem_cgns_elements.hpp @@ -32,7 +32,7 @@ #include "../parallelization/mpi_structure.hpp" #ifdef HAVE_CGNS - #include "cgnslib.h" +#include "cgnslib.h" #endif #include "../geometry/primal_grid/CPrimalGridFEM.hpp" @@ -49,229 +49,148 @@ class CBoundaryFace; */ class CCGNSElementType { -public: - int connID; /*!< \brief CGNS connectivity ID of this connectivity. */ - ElementType_t elemType; /*!< \brief Element type according to the CGNS convention, - possibly MIXED. */ - cgsize_t indBeg; /*!< \brief Index of the first element in the CGNS connectivity. */ - cgsize_t indEnd; /*!< \brief Index of the last element in the CGNS connectivity. */ - cgsize_t nElem; /*!< \brief Number of elements present for this element type. */ + public: + int connID; /*!< \brief CGNS connectivity ID of this connectivity. */ + ElementType_t elemType; /*!< \brief Element type according to the CGNS convention, + possibly MIXED. */ + cgsize_t indBeg; /*!< \brief Index of the first element in the CGNS connectivity. */ + cgsize_t indEnd; /*!< \brief Index of the last element in the CGNS connectivity. */ + cgsize_t nElem; /*!< \brief Number of elements present for this element type. */ - std::string connName; /*!< \brief Name of this connectivity. */ + std::string connName; /*!< \brief Name of this connectivity. */ - bool volumeConn; /*!< \brief Whether or not this is a volume connectivity. */ - bool surfaceConn; /*!< \brief Whether or not this is a surface connectivity. */ + bool volumeConn; /*!< \brief Whether or not this is a volume connectivity. */ + bool surfaceConn; /*!< \brief Whether or not this is a surface connectivity. */ /* Standard constructor, nothing to be done. */ - CCGNSElementType(){} + CCGNSElementType() {} /* Destructor, nothing to be done. */ - ~CCGNSElementType(){} + ~CCGNSElementType() {} /*--- Member function, which determines the meta data for this element type. ---*/ - void DetermineMetaData(const unsigned short nDim, - const int fn, - const int iBase, - const int iZone, - const int iConn); + void DetermineMetaData(const unsigned short nDim, const int fn, const int iBase, const int iZone, const int iConn); /*--- Member function, which reads the required boundary connectivity range. ---*/ - void ReadBoundaryConnectivityRange(const int fn, - const int iBase, - const int iZone, - const unsigned long offsetRank, - const unsigned long nBoundElemRank, - const unsigned long startingBoundElemIDRank, - unsigned long &locBoundElemCount, - std::vector &boundElems); + void ReadBoundaryConnectivityRange(const int fn, const int iBase, const int iZone, const unsigned long offsetRank, + const unsigned long nBoundElemRank, const unsigned long startingBoundElemIDRank, + unsigned long& locBoundElemCount, std::vector& boundElems); /*--- Member function, which reads the required connectivity range. ---*/ - void ReadConnectivityRange(const int fn, - const int iBase, - const int iZone, - const unsigned long offsetRank, - const unsigned long nElemRank, - const unsigned long startingElemIDRank, - CPrimalGrid **&elem, - unsigned long &locElemCount, - unsigned long &nDOFsLoc); -private: + void ReadConnectivityRange(const int fn, const int iBase, const int iZone, const unsigned long offsetRank, + const unsigned long nElemRank, const unsigned long startingElemIDRank, CPrimalGrid**& elem, + unsigned long& locElemCount, unsigned long& nDOFsLoc); + + private: /*--- Member function, which creates the required data for the given element type. ---*/ - void CreateDataElementType(const ElementType_t typeElem, - unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - std::vector &SU2ToCGNS); + void CreateDataElementType(const ElementType_t typeElem, unsigned short& VTK_Type, unsigned short& nPoly, + unsigned short& nDOFs, std::vector& SU2ToCGNS); /*--- Member function, which determines the element dimension, i.e. the number of parametric coordinates. ---*/ - unsigned short DetermineElementDimension(const int fn, - const int iBase, - const int iZone); + unsigned short DetermineElementDimension(const int fn, const int iBase, const int iZone); /*--- Member function, which determines the element dimension when the connectivity is mixed. ---*/ - unsigned short DetermineElementDimensionMixed(const int fn, - const int iBase, - const int iZone); + unsigned short DetermineElementDimensionMixed(const int fn, const int iBase, const int iZone); /*--- Member function, which determines the corresponding index of the given element in the stored types. If not present, a new index is created. ---*/ - unsigned short IndexInStoredTypes(const ElementType_t typeElem, - std::vector &CGNS_Type, - std::vector &VTK_Type, - std::vector &nPoly, - std::vector &nDOFs, - std::vector > &SU2ToCGNS); + unsigned short IndexInStoredTypes(const ElementType_t typeElem, std::vector& CGNS_Type, + std::vector& VTK_Type, std::vector& nPoly, + std::vector& nDOFs, + std::vector >& SU2ToCGNS); /*--- Functions to create the conversion data from CGNS format to SU2 format for all the supported CGNS elements. ---*/ - void CreateDataNODE(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - std::vector &SU2ToCGNS); - - void CreateDataBAR_2(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - std::vector &SU2ToCGNS); - - void CreateDataBAR_3(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - std::vector &SU2ToCGNS); - - void CreateDataBAR_4(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - std::vector &SU2ToCGNS); - - void CreateDataBAR_5(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - std::vector &SU2ToCGNS); - - void CreateDataTRI_3(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - std::vector &SU2ToCGNS); - - void CreateDataTRI_6(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - std::vector &SU2ToCGNS); - - void CreateDataTRI_10(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - std::vector &SU2ToCGNS); - - void CreateDataTRI_15(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - std::vector &SU2ToCGNS); - - void CreateDataQUAD_4(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - std::vector &SU2ToCGNS); - - void CreateDataQUAD_9(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - std::vector &SU2ToCGNS); - - void CreateDataQUAD_16(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - std::vector &SU2ToCGNS); - - void CreateDataQUAD_25(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - std::vector &SU2ToCGNS); - - void CreateDataTETRA_4(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - std::vector &SU2ToCGNS); - - void CreateDataTETRA_10(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - std::vector &SU2ToCGNS); - - void CreateDataTETRA_20(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - std::vector &SU2ToCGNS); - - void CreateDataTETRA_35(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - std::vector &SU2ToCGNS); - - void CreateDataPYRA_5(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - std::vector &SU2ToCGNS); - - void CreateDataPYRA_14(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - std::vector &SU2ToCGNS); - - void CreateDataPYRA_30(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - std::vector &SU2ToCGNS); - - void CreateDataPYRA_55(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - std::vector &SU2ToCGNS); - - void CreateDataPENTA_6(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - std::vector &SU2ToCGNS); - - void CreateDataPENTA_18(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - std::vector &SU2ToCGNS); - - void CreateDataPENTA_40(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - std::vector &SU2ToCGNS); - - void CreateDataPENTA_75(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - std::vector &SU2ToCGNS); - - void CreateDataHEXA_8(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - std::vector &SU2ToCGNS); - - void CreateDataHEXA_27(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - std::vector &SU2ToCGNS); - - void CreateDataHEXA_64(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - std::vector &SU2ToCGNS); - - void CreateDataHEXA_125(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - std::vector &SU2ToCGNS); + void CreateDataNODE(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + std::vector& SU2ToCGNS); + + void CreateDataBAR_2(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + std::vector& SU2ToCGNS); + + void CreateDataBAR_3(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + std::vector& SU2ToCGNS); + + void CreateDataBAR_4(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + std::vector& SU2ToCGNS); + + void CreateDataBAR_5(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + std::vector& SU2ToCGNS); + + void CreateDataTRI_3(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + std::vector& SU2ToCGNS); + + void CreateDataTRI_6(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + std::vector& SU2ToCGNS); + + void CreateDataTRI_10(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + std::vector& SU2ToCGNS); + + void CreateDataTRI_15(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + std::vector& SU2ToCGNS); + + void CreateDataQUAD_4(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + std::vector& SU2ToCGNS); + + void CreateDataQUAD_9(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + std::vector& SU2ToCGNS); + + void CreateDataQUAD_16(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + std::vector& SU2ToCGNS); + + void CreateDataQUAD_25(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + std::vector& SU2ToCGNS); + + void CreateDataTETRA_4(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + std::vector& SU2ToCGNS); + + void CreateDataTETRA_10(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + std::vector& SU2ToCGNS); + + void CreateDataTETRA_20(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + std::vector& SU2ToCGNS); + + void CreateDataTETRA_35(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + std::vector& SU2ToCGNS); + + void CreateDataPYRA_5(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + std::vector& SU2ToCGNS); + + void CreateDataPYRA_14(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + std::vector& SU2ToCGNS); + + void CreateDataPYRA_30(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + std::vector& SU2ToCGNS); + + void CreateDataPYRA_55(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + std::vector& SU2ToCGNS); + + void CreateDataPENTA_6(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + std::vector& SU2ToCGNS); + + void CreateDataPENTA_18(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + std::vector& SU2ToCGNS); + + void CreateDataPENTA_40(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + std::vector& SU2ToCGNS); + + void CreateDataPENTA_75(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + std::vector& SU2ToCGNS); + + void CreateDataHEXA_8(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + std::vector& SU2ToCGNS); + + void CreateDataHEXA_27(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + std::vector& SU2ToCGNS); + + void CreateDataHEXA_64(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + std::vector& SU2ToCGNS); + + void CreateDataHEXA_125(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + std::vector& SU2ToCGNS); }; #endif #endif diff --git a/Common/include/fem/fem_gauss_jacobi_quadrature.hpp b/Common/include/fem/fem_gauss_jacobi_quadrature.hpp index d6ccbe227e3..04a450d8cce 100644 --- a/Common/include/fem/fem_gauss_jacobi_quadrature.hpp +++ b/Common/include/fem/fem_gauss_jacobi_quadrature.hpp @@ -98,7 +98,7 @@ using namespace std; * \version 7.5.1 "Blackbird" */ class CGaussJacobiQuadrature { -public: + public: /*! * \brief Function, which serves as the API to compute the integration points and weights. @@ -111,30 +111,29 @@ class CGaussJacobiQuadrature { * \param[in,out] GJPoints Location of the Gauss-Jacobi integration points. * \param[in,out] GJWeights Weights of the Gauss-Jacobi integration points. */ - void GetQuadraturePoints(const passivedouble alpha, const passivedouble beta, - const passivedouble a, const passivedouble b, - vector &GJPoints, vector &GJWeights); -private: + void GetQuadraturePoints(const passivedouble alpha, const passivedouble beta, const passivedouble a, + const passivedouble b, vector& GJPoints, vector& GJWeights); + + private: /*! * \brief Function in the original implementation of John Burkardt to compute the integration points of the Gauss-Jacobi quadrature rule. */ - void cdgqf(int nt, int kind, passivedouble alpha, passivedouble beta, passivedouble t[], - passivedouble wts[]); + void cdgqf(int nt, int kind, passivedouble alpha, passivedouble beta, passivedouble t[], passivedouble wts[]); /*! * \brief Function in the original implementation of John Burkardt to compute the integration points of the Gauss-Jacobi quadrature rule. */ - void cgqf(int nt, int kind, passivedouble alpha, passivedouble beta, passivedouble a, - passivedouble b, passivedouble t[], passivedouble wts[]); + void cgqf(int nt, int kind, passivedouble alpha, passivedouble beta, passivedouble a, passivedouble b, + passivedouble t[], passivedouble wts[]); /*! * \brief Function in the original implementation of John Burkardt to compute the integration points of the Gauss-Jacobi quadrature rule. */ - passivedouble class_matrix(int kind, int m, passivedouble alpha, passivedouble beta, - passivedouble aj[], passivedouble bj[]); + passivedouble class_matrix(int kind, int m, passivedouble alpha, passivedouble beta, passivedouble aj[], + passivedouble bj[]); /*! * \brief Function in the original implementation of John Burkardt to compute @@ -165,8 +164,8 @@ class CGaussJacobiQuadrature { the integration points of the Gauss-Jacobi quadrature rule. */ void scqf(int nt, const passivedouble t[], const int mlt[], const passivedouble wts[], int nwts, int ndx[], - passivedouble swts[], passivedouble st[], int kind, passivedouble alpha, - passivedouble beta, passivedouble a, passivedouble b); + passivedouble swts[], passivedouble st[], int kind, passivedouble alpha, passivedouble beta, + passivedouble a, passivedouble b); /*! * \brief Function in the original implementation of John Burkardt to compute diff --git a/Common/include/fem/fem_geometry_structure.hpp b/Common/include/fem/fem_geometry_structure.hpp index 4974a6fbbc9..a6b79f276cc 100644 --- a/Common/include/fem/fem_geometry_structure.hpp +++ b/Common/include/fem/fem_geometry_structure.hpp @@ -44,15 +44,19 @@ using namespace std; * \version 7.5.1 "Blackbird" */ struct CLong3T { - long long0 = 0; /*!< \brief First long to store in this class. */ - long long1 = 0; /*!< \brief Second long to store in this class. */ - long long2 = 0; /*!< \brief Third long to store in this class. */ + long long0 = 0; /*!< \brief First long to store in this class. */ + long long1 = 0; /*!< \brief Second long to store in this class. */ + long long2 = 0; /*!< \brief Third long to store in this class. */ CLong3T() = default; - CLong3T(const long a, const long b, const long c) {long0 = a; long1 = b; long2 = c;} + CLong3T(const long a, const long b, const long c) { + long0 = a; + long1 = b; + long2 = c; + } - bool operator<(const CLong3T &other) const; + bool operator<(const CLong3T& other) const; }; /*! @@ -62,26 +66,23 @@ struct CLong3T { * \version 7.5.1 "Blackbird" */ class CReorderElements { -private: - unsigned long globalElemID; /*!< \brief Global element ID of the element. */ - unsigned short timeLevel; /*!< \brief Time level of the element. Only relevant - for time accurate local time stepping. */ - bool commSolution; /*!< \brief Whether or not the solution must be - communicated to other ranks. */ - unsigned short elemType; /*!< \brief Short hand for the element type, Which - stored info of the VTK_Type, polynomial - degree of the solution and whether or - not the Jacobian is constant. */ -public: + private: + unsigned long globalElemID; /*!< \brief Global element ID of the element. */ + unsigned short timeLevel; /*!< \brief Time level of the element. Only relevant + for time accurate local time stepping. */ + bool commSolution; /*!< \brief Whether or not the solution must be + communicated to other ranks. */ + unsigned short elemType; /*!< \brief Short hand for the element type, Which + stored info of the VTK_Type, polynomial + degree of the solution and whether or + not the Jacobian is constant. */ + public: /*! * \brief Constructor of the class, set the member variables to the arguments. */ - CReorderElements(const unsigned long val_GlobalElemID, - const unsigned short val_TimeLevel, - const bool val_CommSolution, - const unsigned short val_VTK_Type, - const unsigned short val_nPolySol, - const bool val_JacConstant); + CReorderElements(const unsigned long val_GlobalElemID, const unsigned short val_TimeLevel, + const bool val_CommSolution, const unsigned short val_VTK_Type, const unsigned short val_nPolySol, + const bool val_JacConstant); /*! * \brief Default constructor of the class. Disabled. @@ -91,7 +92,7 @@ class CReorderElements { /*! * \brief Less than operator of the class. Needed for the sorting. */ - bool operator<(const CReorderElements &other) const; + bool operator<(const CReorderElements& other) const; /*! * \brief Function to make available the variable commSolution. @@ -123,7 +124,6 @@ class CReorderElements { * \param[in] val_CommSolution - value to which commSolution must be set. */ inline void SetCommSolution(const bool val_CommSolution) { commSolution = val_CommSolution; } - }; /*! @@ -133,21 +133,19 @@ class CReorderElements { * \author E. van der Weide * \version 7.5.1 "Blackbird" */ -class CVolumeElementFEM; // Forward declaration to avoid problems. +class CVolumeElementFEM; // Forward declaration to avoid problems. class CSortFaces { -private: + private: unsigned long nVolElemOwned; /*!< \brief Number of locally owned volume elements. */ unsigned long nVolElemTot; /*!< \brief Total number of local volume elements . */ - const CVolumeElementFEM *volElem; /*!< \brief The locally stored volume elements. */ + const CVolumeElementFEM* volElem; /*!< \brief The locally stored volume elements. */ -public: + public: /*! * \brief Constructor of the class. Set the values of the member variables. */ - CSortFaces(unsigned long val_nVolElemOwned, - unsigned long val_nVolElemTot, - const CVolumeElementFEM *val_volElem) { + CSortFaces(unsigned long val_nVolElemOwned, unsigned long val_nVolElemTot, const CVolumeElementFEM* val_volElem) { nVolElemOwned = val_nVolElemOwned; nVolElemTot = val_nVolElemTot; volElem = val_volElem; @@ -156,15 +154,14 @@ class CSortFaces { /*! * \brief Default constructor of the class. Disabled. */ - CSortFaces(void) = delete; + CSortFaces(void) = delete; - /*! - * \brief Operator used for the comparison. - * \param[in] f0 - First face in the comparison. - * \param[in] f1 - Second face in the comparison. - */ - bool operator()(const CFaceOfElement &f0, - const CFaceOfElement &f1); + /*! + * \brief Operator used for the comparison. + * \param[in] f0 - First face in the comparison. + * \param[in] f1 - Second face in the comparison. + */ + bool operator()(const CFaceOfElement& f0, const CFaceOfElement& f1); }; /*! @@ -174,15 +171,14 @@ class CSortFaces { * \author E. van der Weide * \version 7.5.1 "Blackbird" */ -struct CSurfaceElementFEM; // Forward declaration to avoid problems. +struct CSurfaceElementFEM; // Forward declaration to avoid problems. struct CSortBoundaryFaces { - /*! - * \brief Operator used for the comparison. - * \param[in] f0 - First boundary face in the comparison. - * \param[in] f1 - Second boundary face in the comparison. - */ - bool operator()(const CSurfaceElementFEM &f0, - const CSurfaceElementFEM &f1); + /*! + * \brief Operator used for the comparison. + * \param[in] f0 - First boundary face in the comparison. + * \param[in] f1 - Second boundary face in the comparison. + */ + bool operator()(const CSurfaceElementFEM& f0, const CSurfaceElementFEM& f1); }; /*! @@ -192,32 +188,32 @@ struct CSortBoundaryFaces { * \version 7.5.1 "Blackbird" */ class CVolumeElementFEM { -public: + public: bool elemIsOwned; /*!< \brief Whether or not this is an owned element. */ bool JacIsConsideredConstant; /*!< \brief Whether or not the Jacobian of the transformation to the standard element is considered constant. */ - int rankOriginal; /*!< \brief The rank where the original volume is stored. For - the owned volumes, this is simply the current rank. */ + int rankOriginal; /*!< \brief The rank where the original volume is stored. For + the owned volumes, this is simply the current rank. */ - short periodIndexToDonor; /*!< \brief The index of the periodic transformation to the donor - element. Only for halo elements. A -1 indicates no periodic - transformation. */ + short periodIndexToDonor; /*!< \brief The index of the periodic transformation to the donor + element. Only for halo elements. A -1 indicates no periodic + transformation. */ - unsigned short VTK_Type; /*!< \brief Element type using the VTK convention. */ - unsigned short nPolyGrid; /*!< \brief Polynomial degree for the geometry of the element. */ - unsigned short nPolySol; /*!< \brief Polynomial degree for the solution of the element. */ - unsigned short nDOFsGrid; /*!< \brief Number of DOFs for the geometry of the element. */ - unsigned short nDOFsSol; /*!< \brief Number of DOFs for the solution of the element. */ - unsigned short nFaces; /*!< \brief Number of faces of the element. */ - unsigned short timeLevel; /*!< \brief Time level of the element when time accurate local - time stepping is employed. */ + unsigned short VTK_Type; /*!< \brief Element type using the VTK convention. */ + unsigned short nPolyGrid; /*!< \brief Polynomial degree for the geometry of the element. */ + unsigned short nPolySol; /*!< \brief Polynomial degree for the solution of the element. */ + unsigned short nDOFsGrid; /*!< \brief Number of DOFs for the geometry of the element. */ + unsigned short nDOFsSol; /*!< \brief Number of DOFs for the solution of the element. */ + unsigned short nFaces; /*!< \brief Number of faces of the element. */ + unsigned short timeLevel; /*!< \brief Time level of the element when time accurate local + time stepping is employed. */ unsigned short indStandardElement; /*!< \brief Index in the vector of standard elements. */ - unsigned int factTimeLevel; /*!< \brief Number of local time steps for this element - compared to the largest time step when time - accurate local time stepping is employed. */ + unsigned int factTimeLevel; /*!< \brief Number of local time steps for this element + compared to the largest time step when time + accurate local time stepping is employed. */ unsigned long elemIDGlobal; /*!< \brief Global element ID of this element. */ unsigned long offsetDOFsSolGlobal; /*!< \brief Global offset of the solution DOFs of this element. */ @@ -236,35 +232,34 @@ class CVolumeElementFEM { vector nodeIDsGrid; /*!< \brief Vector with the node IDs of the grid for this element. */ - su2double lenScale; /*!< \brief Length scale of the element. */ - - su2double shockSensorValue; /*!< \brief Value for sensing a shock */ - su2double shockArtificialViscosity; /*!< \brief Artificial viscosity for a shock */ - - - vector metricTerms; /*!< \brief Vector of the metric terms in the - integration points of this element. */ - vector metricTermsSolDOFs; /*!< \brief Vector of the metric terms in the - solution DOFs of this element. */ - vector metricTerms2ndDer; /*!< \brief Vector of the metric terms needed for the - computation of the 2nd derivatives in the - integration points. Only determined when - needed (ADER-DG with non-aliased predictor - for the Navier-Stokes equations). */ - vector gridVelocities; /*!< \brief Vector of the grid velocities in the - integration points of this element. */ - vector gridVelocitiesSolDOFs; /*!< \brief Vector of the grid velocities in the - solution DOFs of this element. */ - vector massMatrix; /*!< \brief Mass matrix for this element. */ - vector invMassMatrix; /*!< \brief Inverse mass matrix for this element. */ - vector lumpedMassMatrix; /*!< \brief Lumped mass matrix for this element. */ - - vector coorIntegrationPoints; /*!< \brief The coordinates of the integration points of this element. */ - vector coorSolDOFs; /*!< \brief The coordinates of the solution DOFs of this element. */ - vector wallDistance; /*!< \brief The wall distance to the viscous walls for - the integration points of this element. */ - vector wallDistanceSolDOFs; /*!< \brief The wall distance to the viscous walls for - the solution DOFs of this element. */ + su2double lenScale; /*!< \brief Length scale of the element. */ + + su2double shockSensorValue; /*!< \brief Value for sensing a shock */ + su2double shockArtificialViscosity; /*!< \brief Artificial viscosity for a shock */ + + vector metricTerms; /*!< \brief Vector of the metric terms in the + integration points of this element. */ + vector metricTermsSolDOFs; /*!< \brief Vector of the metric terms in the + solution DOFs of this element. */ + vector metricTerms2ndDer; /*!< \brief Vector of the metric terms needed for the + computation of the 2nd derivatives in the + integration points. Only determined when + needed (ADER-DG with non-aliased predictor + for the Navier-Stokes equations). */ + vector gridVelocities; /*!< \brief Vector of the grid velocities in the + integration points of this element. */ + vector gridVelocitiesSolDOFs; /*!< \brief Vector of the grid velocities in the + solution DOFs of this element. */ + vector massMatrix; /*!< \brief Mass matrix for this element. */ + vector invMassMatrix; /*!< \brief Inverse mass matrix for this element. */ + vector lumpedMassMatrix; /*!< \brief Lumped mass matrix for this element. */ + + vector coorIntegrationPoints; /*!< \brief The coordinates of the integration points of this element. */ + vector coorSolDOFs; /*!< \brief The coordinates of the solution DOFs of this element. */ + vector wallDistance; /*!< \brief The wall distance to the viscous walls for + the integration points of this element. */ + vector wallDistanceSolDOFs; /*!< \brief The wall distance to the viscous walls for + the solution DOFs of this element. */ /*! * \brief Get all the corner points of all the faces of this element. It must be made sure @@ -274,9 +269,7 @@ class CVolumeElementFEM { * \param[out] nPointsPerFace - Number of corner points for each of the faces. * \param[out] faceConn - Global IDs of the corner points of the faces. */ - void GetCornerPointsAllFaces(unsigned short &numFaces, - unsigned short nPointsPerFace[], - unsigned long faceConn[6][4]); + void GetCornerPointsAllFaces(unsigned short& numFaces, unsigned short nPointsPerFace[], unsigned long faceConn[6][4]); }; /*! @@ -295,13 +288,12 @@ struct CPointFEM { /*! * \brief Less than operator of the class. Needed for the sorting. */ - bool operator<(const CPointFEM &other) const; + bool operator<(const CPointFEM& other) const; /*! * \brief Equal operator of the class. Needed for the removal of double entities. */ - bool operator==(const CPointFEM &other) const; - + bool operator==(const CPointFEM& other) const; }; /*! @@ -311,42 +303,41 @@ struct CPointFEM { * \version 7.5.1 "Blackbird" */ struct CInternalFaceElementFEM { - unsigned short VTK_Type; /*!< \brief Element type using the VTK convention. */ + unsigned short VTK_Type; /*!< \brief Element type using the VTK convention. */ unsigned short indStandardElement; /*!< \brief Index in the vector of standard face elements. */ - unsigned long elemID0; /*!< \brief Element ID adjacent to side 0 of the face. */ - unsigned long elemID1; /*!< \brief Element ID adjacent to side 1 of the face. */ + unsigned long elemID0; /*!< \brief Element ID adjacent to side 0 of the face. */ + unsigned long elemID1; /*!< \brief Element ID adjacent to side 1 of the face. */ - vector DOFsGridFaceSide0; /*!< \brief Vector of the grid DOFs of side 0 of the face. */ - vector DOFsGridFaceSide1; /*!< \brief Vector of the grid DOFs of side 1 of the face. */ - vector DOFsSolFaceSide0; /*!< \brief Vector of the solution DOFs of side 0 of the face. */ - vector DOFsSolFaceSide1; /*!< \brief Vector of the solution DOFs of side 1 of the face. */ + vector DOFsGridFaceSide0; /*!< \brief Vector of the grid DOFs of side 0 of the face. */ + vector DOFsGridFaceSide1; /*!< \brief Vector of the grid DOFs of side 1 of the face. */ + vector DOFsSolFaceSide0; /*!< \brief Vector of the solution DOFs of side 0 of the face. */ + vector DOFsSolFaceSide1; /*!< \brief Vector of the solution DOFs of side 1 of the face. */ - vector DOFsGridElementSide0; /*!< \brief Vector of the grid DOFs of the element of side 0. */ - vector DOFsGridElementSide1; /*!< \brief Vector of the grid DOFs of the element of side 1. */ - vector DOFsSolElementSide0; /*!< \brief Vector of the solution DOFs of the element of side 0. */ - vector DOFsSolElementSide1; /*!< \brief Vector of the solution DOFs of the element of side 1. */ + vector DOFsGridElementSide0; /*!< \brief Vector of the grid DOFs of the element of side 0. */ + vector DOFsGridElementSide1; /*!< \brief Vector of the grid DOFs of the element of side 1. */ + vector DOFsSolElementSide0; /*!< \brief Vector of the solution DOFs of the element of side 0. */ + vector DOFsSolElementSide1; /*!< \brief Vector of the solution DOFs of the element of side 1. */ - vector metricNormalsFace; /*!< \brief The normals in the integration points of the face. - The normals point from side 0 to side 1. */ - vector metricCoorDerivFace0; /*!< \brief The terms drdx, dsdx, etc. of side 0 in the - integration points of the face. */ - vector metricCoorDerivFace1; /*!< \brief The terms dxdr, dydr, etc. of side 1 in the - integration points of the face. */ + vector metricNormalsFace; /*!< \brief The normals in the integration points of the face. + The normals point from side 0 to side 1. */ + vector metricCoorDerivFace0; /*!< \brief The terms drdx, dsdx, etc. of side 0 in the + integration points of the face. */ + vector metricCoorDerivFace1; /*!< \brief The terms dxdr, dydr, etc. of side 1 in the + integration points of the face. */ - vector coorIntegrationPoints; /*!< \brief Coordinates for the integration points of this face. */ - vector gridVelocities; /*!< \brief Grid velocities in the integration points of this face. */ - vector wallDistance; /*!< \brief The wall distance to the viscous walls for - the integration points of this face. */ + vector coorIntegrationPoints; /*!< \brief Coordinates for the integration points of this face. */ + vector gridVelocities; /*!< \brief Grid velocities in the integration points of this face. */ + vector wallDistance; /*!< \brief The wall distance to the viscous walls for + the integration points of this face. */ /*! * \brief Less than operator of the class. Needed for the sorting. The criterion for comparison are the standard element and adjacent volume ID's. */ - bool operator<(const CInternalFaceElementFEM &other) const; - + bool operator<(const CInternalFaceElementFEM& other) const; }; /*! @@ -356,9 +347,9 @@ struct CInternalFaceElementFEM { * \version 7.5.1 "Blackbird" */ struct CSurfaceElementFEM { - unsigned short VTK_Type; /*!< \brief Element type using the VTK convention. */ - unsigned short nPolyGrid; /*!< \brief Polynomial degree for the geometry of the element. */ - unsigned short nDOFsGrid; /*!< \brief Number of DOFs for the geometry of the element. */ + unsigned short VTK_Type; /*!< \brief Element type using the VTK convention. */ + unsigned short nPolyGrid; /*!< \brief Polynomial degree for the geometry of the element. */ + unsigned short nDOFsGrid; /*!< \brief Number of DOFs for the geometry of the element. */ unsigned short indStandardElement; /*!< \brief Index in the vector of standard elements. */ @@ -370,45 +361,44 @@ struct CSurfaceElementFEM { In this vector the original sequence of the grid file is stored. */ - vector DOFsGridFace; /*!< \brief Vector of the grid DOFs of the face. In principle - the same information as nodeIDsGrid, but the sequence - could be different. */ - vector DOFsSolFace; /*!< \brief Vector of the solution DOFs of the face. */ + vector DOFsGridFace; /*!< \brief Vector of the grid DOFs of the face. In principle + the same information as nodeIDsGrid, but the sequence + could be different. */ + vector DOFsSolFace; /*!< \brief Vector of the solution DOFs of the face. */ - vector DOFsGridElement; /*!< \brief Vector of the grid DOFs of the adjacent element. */ - vector DOFsSolElement; /*!< \brief Vector of the solution DOFs of the adjacent element. */ + vector DOFsGridElement; /*!< \brief Vector of the grid DOFs of the adjacent element. */ + vector DOFsSolElement; /*!< \brief Vector of the solution DOFs of the adjacent element. */ vector metricNormalsFace; /*!< \brief The normals in the integration points of the face. The normals point out of the adjacent element. */ vector metricCoorDerivFace; /*!< \brief The terms drdx, dsdx, etc. in the integration points of the face. */ vector coorIntegrationPoints; /*!< \brief The coordinates of the integration points of the face. */ - vector gridVelocities; /*!< \brief Grid velocities in the integration points of this face. */ + vector gridVelocities; /*!< \brief Grid velocities in the integration points of this face. */ vector wallDistance; /*!< \brief The wall distances of the integration points of the face. */ - vector donorsWallFunction; /*!< \brief Local element IDs of the donors for the wall - function treatment. These donors can be halo's. */ - vector nIntPerWallFunctionDonor; /*!< \brief The number of integration points per donor - element for the wall function treatment. */ - vector intPerWallFunctionDonor; /*!< \brief The integration points per donor element - for the wall function treatment. */ - vector > matWallFunctionDonor; /*!< \brief Matrices, which store the interpolation coefficients - for the donors of the integration points.*/ + vector donorsWallFunction; /*!< \brief Local element IDs of the donors for the wall + function treatment. These donors can be halo's. */ + vector nIntPerWallFunctionDonor; /*!< \brief The number of integration points per donor + element for the wall function treatment. */ + vector intPerWallFunctionDonor; /*!< \brief The integration points per donor element + for the wall function treatment. */ + vector > matWallFunctionDonor; /*!< \brief Matrices, which store the interpolation coefficients + for the donors of the integration points.*/ /*! * \brief Less than operator of the class. Needed for the sorting. The criterion for comparison is the corresponding (local) volume ID. */ - bool operator<(const CSurfaceElementFEM &other) const { return volElemID < other.volElemID; } + bool operator<(const CSurfaceElementFEM& other) const { return volElemID < other.volElemID; } /*! * \brief Function, which determines the corner points of this surface element. * \param[out] nPointsPerFace - Number of corner points of the face. * \param[out] faceConn - The corner points of the face. */ - void GetCornerPointsFace(unsigned short &nPointsPerFace, - unsigned long faceConn[]); + void GetCornerPointsFace(unsigned short& nPointsPerFace, unsigned long faceConn[]); }; /*! @@ -418,18 +408,18 @@ struct CSurfaceElementFEM { * \version 7.5.1 "Blackbird" */ struct CBoundaryFEM { - string markerTag; /*!< \brief Marker tag of this boundary. */ + string markerTag; /*!< \brief Marker tag of this boundary. */ - bool periodicBoundary = false; /*!< \brief Whether or not this boundary is a periodic boundary. */ - bool haloInfoNeededForBC = false; /*!< \brief Whether or not information of halo elements - is needed to impose the boundary conditions. */ + bool periodicBoundary = false; /*!< \brief Whether or not this boundary is a periodic boundary. */ + bool haloInfoNeededForBC = false; /*!< \brief Whether or not information of halo elements + is needed to impose the boundary conditions. */ vector nSurfElem; /*!< \brief Number of surface elements per time level, cumulative storage format. */ vector surfElem; /*!< \brief Vector of the local surface elements. */ - CWallModel *wallModel = nullptr; /*!< \brief Wall model for LES. */ + CWallModel* wallModel = nullptr; /*!< \brief Wall model for LES. */ ~CBoundaryFEM(void) { delete wallModel; } }; @@ -440,205 +430,207 @@ struct CBoundaryFEM { * \author E. van der Weide * \version 7.5.1 "Blackbird" */ -class CMeshFEM: public CGeometry { -protected: - unsigned long nVolElemTot{0}; /*!< \brief Total number of local volume elements, including halos. */ - unsigned long nVolElemOwned{0}; /*!< \brief Number of owned local volume elements. */ +class CMeshFEM : public CGeometry { + protected: + unsigned long nVolElemTot{0}; /*!< \brief Total number of local volume elements, including halos. */ + unsigned long nVolElemOwned{0}; /*!< \brief Number of owned local volume elements. */ vector nVolElemOwnedPerTimeLevel; /*!< \brief Number of owned local volume elements per time level. Cumulative storage. */ vector nVolElemInternalPerTimeLevel; /*!< \brief Number of internal local volume elements per time level. Internal means that the solution data does not need to be communicated. */ - vector nVolElemHaloPerTimeLevel; /*!< \brief Number of local halo volume elements - per time level. Cumulative storage. */ + vector nVolElemHaloPerTimeLevel; /*!< \brief Number of local halo volume elements + per time level. Cumulative storage. */ vector > ownedElemAdjLowTimeLevel; /*!< \brief List of owned elements per time level that are adjacent to elements of the lower time level. */ - vector > haloElemAdjLowTimeLevel; /*!< \brief List of halo elements per time level that are - adjacent to elements of the lower time level. */ + vector > haloElemAdjLowTimeLevel; /*!< \brief List of halo elements per time level that are + adjacent to elements of the lower time level. */ vector volElem; /*!< \brief Vector of the local volume elements, including halos. */ - vector meshPoints; /*!< \brief Vector of the points of the FEM mesh. */ + vector meshPoints; /*!< \brief Vector of the points of the FEM mesh. */ - vector boundaries; /*!< \brief Vector of the boundaries of the FEM mesh. */ + vector boundaries; /*!< \brief Vector of the boundaries of the FEM mesh. */ - vector rotPerMarkers; /*!< \brief Vector, which contains the indices of the rotational - periodic markers. */ + vector rotPerMarkers; /*!< \brief Vector, which contains the indices of the rotational + periodic markers. */ vector > rotPerHalos; /*!< \brief Vector of vector, which contains the indices of the halo elements for which a rotationally periodic correction must be applied. */ - vector ranksRecv; /*!< \brief Vector of ranks, from which this rank will receive halo - information. Self communication is included. */ - vector ranksSend; /*!< \brief Vector of ranks, to which this rank will send halo - information. Self communication is included. */ + vector ranksRecv; /*!< \brief Vector of ranks, from which this rank will receive halo + information. Self communication is included. */ + vector ranksSend; /*!< \brief Vector of ranks, to which this rank will send halo + information. Self communication is included. */ - vector > entitiesSend; /*!< \brief Vector of vector, which contains the entities that - must be sent. Self communication is included. For DG - an entitity is an element, for regular FEM an entity - is a DOF. */ + vector > entitiesSend; /*!< \brief Vector of vector, which contains the entities that + must be sent. Self communication is included. For DG + an entitity is an element, for regular FEM an entity + is a DOF. */ vector > entitiesRecv; /*!< \brief Vector of vector, which contains the entities that must be received. Self communication is included. For DG an entity is an element, for regular FEM an entity is a DOF. */ - vector standardBoundaryFacesSol; /*!< \brief Vector that contains the standard boundary - faces used for the solution of the DG solver. */ - vector standardBoundaryFacesGrid; /*!< \brief Vector that contains the standard boundary - faces used for the geometry of the DG solver. */ + vector + standardBoundaryFacesSol; /*!< \brief Vector that contains the standard boundary + faces used for the solution of the DG solver. */ + vector + standardBoundaryFacesGrid; /*!< \brief Vector that contains the standard boundary + faces used for the geometry of the DG solver. */ - CBlasStructure *blasFunctions{nullptr}; /*!< \brief Pointer to the object to carry out the BLAS functionalities. */ + CBlasStructure* blasFunctions{nullptr}; /*!< \brief Pointer to the object to carry out the BLAS functionalities. */ -public: + public: /*! - * \brief Constructor of the class. - */ - CMeshFEM(void) : CGeometry() { } + * \brief Constructor of the class. + */ + CMeshFEM(void) : CGeometry() {} /*! - * \overload - * \brief Redistributes the grid over the ranks and creates the halo layer. - * \param[in] geometry - The linear distributed grid that must be redistributed. - * \param[in] config - Definition of the particular problem. - */ - CMeshFEM(CGeometry *geometry, CConfig *config); + * \overload + * \brief Redistributes the grid over the ranks and creates the halo layer. + * \param[in] geometry - The linear distributed grid that must be redistributed. + * \param[in] config - Definition of the particular problem. + */ + CMeshFEM(CGeometry* geometry, CConfig* config); /*! - * \brief Destructor of the class. - */ + * \brief Destructor of the class. + */ ~CMeshFEM(void) override { delete blasFunctions; } /*! - * \brief Function, which makes available the boundaries of the local FEM mesh. - * \return Pointer to the boundaries of the local FEM mesh. - */ - inline CBoundaryFEM* GetBoundaries(void) {return boundaries.data();} + * \brief Function, which makes available the boundaries of the local FEM mesh. + * \return Pointer to the boundaries of the local FEM mesh. + */ + inline CBoundaryFEM* GetBoundaries(void) { return boundaries.data(); } /*! - * \brief Function, which makes available the mesh points of the local FEM mesh. - * \return Pointer to the mesh points of the local FEM mesh. - */ - inline CPointFEM *GetMeshPoints(void) {return meshPoints.data();} + * \brief Function, which makes available the mesh points of the local FEM mesh. + * \return Pointer to the mesh points of the local FEM mesh. + */ + inline CPointFEM* GetMeshPoints(void) { return meshPoints.data(); } /*! - * \brief Function, which makes available the number of mesh points of the local FEM mesh. - * \return Number of mesh points of the local FEM mesh. - */ - inline unsigned long GetNMeshPoints(void) {return meshPoints.size();} + * \brief Function, which makes available the number of mesh points of the local FEM mesh. + * \return Number of mesh points of the local FEM mesh. + */ + inline unsigned long GetNMeshPoints(void) { return meshPoints.size(); } /*! - * \brief Function, which makes available the number of owned volume elements in the local FEM mesh. - * \return Number of owned volume elements of the local FEM mesh. - */ - inline unsigned long GetNVolElemOwned(void) const {return nVolElemOwned;} + * \brief Function, which makes available the number of owned volume elements in the local FEM mesh. + * \return Number of owned volume elements of the local FEM mesh. + */ + inline unsigned long GetNVolElemOwned(void) const { return nVolElemOwned; } /*! - * \brief Function, which makes available the total number of volume elements in the local FEM mesh. - * \return Total number of volume elements of the local FEM mesh. - */ - inline unsigned long GetNVolElemTot(void) const {return nVolElemTot;} + * \brief Function, which makes available the total number of volume elements in the local FEM mesh. + * \return Total number of volume elements of the local FEM mesh. + */ + inline unsigned long GetNVolElemTot(void) const { return nVolElemTot; } /*! - * \brief Function, which makes available the volume elements in the local FEM mesh. - * \return Pointer to the volume elements of the local FEM mesh. - */ - inline CVolumeElementFEM* GetVolElem(void) {return volElem.data();} + * \brief Function, which makes available the volume elements in the local FEM mesh. + * \return Pointer to the volume elements of the local FEM mesh. + */ + inline CVolumeElementFEM* GetVolElem(void) { return volElem.data(); } /*! - * \brief Function, which makes available the number of owned volume elements per time level. - * \return The pointer to the data of nVolElemOwnedPerTimeLevel. - */ - inline unsigned long* GetNVolElemOwnedPerTimeLevel(void) {return nVolElemOwnedPerTimeLevel.data();} + * \brief Function, which makes available the number of owned volume elements per time level. + * \return The pointer to the data of nVolElemOwnedPerTimeLevel. + */ + inline unsigned long* GetNVolElemOwnedPerTimeLevel(void) { return nVolElemOwnedPerTimeLevel.data(); } /*! - * \brief Function, which makes available the number of internal volume elements per time level. - * \return The pointer to the data of nVolElemInternalPerTimeLevel. - */ - inline unsigned long* GetNVolElemInternalPerTimeLevel(void) {return nVolElemInternalPerTimeLevel.data();} + * \brief Function, which makes available the number of internal volume elements per time level. + * \return The pointer to the data of nVolElemInternalPerTimeLevel. + */ + inline unsigned long* GetNVolElemInternalPerTimeLevel(void) { return nVolElemInternalPerTimeLevel.data(); } /*! - * \brief Function, which makes available the number of halo volume elements per time level. - * \return The pointer to the data of nVolElemHaloPerTimeLevel. - */ - inline unsigned long* GetNVolElemHaloPerTimeLevel(void) {return nVolElemHaloPerTimeLevel.data();} + * \brief Function, which makes available the number of halo volume elements per time level. + * \return The pointer to the data of nVolElemHaloPerTimeLevel. + */ + inline unsigned long* GetNVolElemHaloPerTimeLevel(void) { return nVolElemHaloPerTimeLevel.data(); } /*! * \brief Function, which makes available the vector of vectors containing the owned element IDs adjacent to elements of a lower time level. Note that a copy is made. * \return Copy of ownedElemAdjLowTimeLevel. */ - inline vector > GetOwnedElemAdjLowTimeLevel(void) {return ownedElemAdjLowTimeLevel;} + inline vector > GetOwnedElemAdjLowTimeLevel(void) { return ownedElemAdjLowTimeLevel; } /*! * \brief Function, which makes available the vector of vectors containing the halo element IDs adjacent to elements of a lower time level. Note that a copy is made. * \return Copy of haloElemAdjLowTimeLevel. */ - inline vector > GetHaloElemAdjLowTimeLevel(void) {return haloElemAdjLowTimeLevel;} + inline vector > GetHaloElemAdjLowTimeLevel(void) { return haloElemAdjLowTimeLevel; } /*! - * \brief Function, which makes available the number of standard boundary faces of the solution. - * \return Number of standard boundary faces of the solution. - */ - inline unsigned short GetNStandardBoundaryFacesSol(void) {return standardBoundaryFacesSol.size();} + * \brief Function, which makes available the number of standard boundary faces of the solution. + * \return Number of standard boundary faces of the solution. + */ + inline unsigned short GetNStandardBoundaryFacesSol(void) { return standardBoundaryFacesSol.size(); } /*! - * \brief Function, which makes available the standard boundary faces of the solution. - * \return Pointer to the standard boundary faces of the solution. - */ - inline CFEMStandardBoundaryFace* GetStandardBoundaryFacesSol(void) {return standardBoundaryFacesSol.data();} + * \brief Function, which makes available the standard boundary faces of the solution. + * \return Pointer to the standard boundary faces of the solution. + */ + inline CFEMStandardBoundaryFace* GetStandardBoundaryFacesSol(void) { return standardBoundaryFacesSol.data(); } /*! * \brief Function, which makes available the vector of receive ranks as a const reference. * \return Const reference to the vector of ranks. */ - inline const vector& GetRanksRecv(void) const {return ranksRecv;} + inline const vector& GetRanksRecv(void) const { return ranksRecv; } /*! * \brief Function, which makes available the vector of send ranks as a const reference. * \return Const reference to the vector of ranks. */ - inline const vector& GetRanksSend(void) const {return ranksSend;} + inline const vector& GetRanksSend(void) const { return ranksSend; } /*! * \brief Function, which makes available the vector of vectors containing the receive entities as a const reference. * \return Const reference to the vector of vectors of receive entities. */ - inline const vector >& GetEntitiesRecv(void) const {return entitiesRecv;} + inline const vector >& GetEntitiesRecv(void) const { return entitiesRecv; } /*! * \brief Function, which makes available the vector of vectors containing the send entities as a const reference. * \return Const reference to the vector of vectors of send entities. */ - inline const vector >& GetEntitiesSend(void) const {return entitiesSend;} + inline const vector >& GetEntitiesSend(void) const { return entitiesSend; } /*! * \brief Function, which makes available the vector of rotational periodic markers as a const reference. * \return Const reference to the vector with rotational periodic markers. */ - inline const vector& GetRotPerMarkers(void) const {return rotPerMarkers;} + inline const vector& GetRotPerMarkers(void) const { return rotPerMarkers; } /*! * \brief Function, which makes available the vector of vectors containing the rotational periodic halos as a const reference. * \return Const reference to the vector of vectors with rotational periodic halos. */ - inline const vector >& GetRotPerHalos(void) const {return rotPerHalos;} + inline const vector >& GetRotPerHalos(void) const { return rotPerHalos; } /*! - * \brief Compute surface area (positive z-direction) for force coefficient non-dimensionalization. - * \param[in] config - Definition of the particular problem. - */ - void SetPositive_ZArea(CConfig *config) override; + * \brief Compute surface area (positive z-direction) for force coefficient non-dimensionalization. + * \param[in] config - Definition of the particular problem. + */ + void SetPositive_ZArea(CConfig* config) override; -protected: + protected: /*! * \brief Function, which computes the gradients of the parametric coordinates w.r.t. the Cartesian coordinates in the integration points of a face, @@ -653,12 +645,9 @@ class CMeshFEM: public CGeometry { * \param[out] derivCoor - Storage for the derivatives of the coordinates. * \param[in] config - Definition of the particular problem. */ - void ComputeGradientsCoordinatesFace(const unsigned short nIntegration, - const unsigned short nDOFs, - const su2double *matDerBasisInt, - const unsigned long *DOFs, - su2double *derivCoor, - CConfig *config); + void ComputeGradientsCoordinatesFace(const unsigned short nIntegration, const unsigned short nDOFs, + const su2double* matDerBasisInt, const unsigned long* DOFs, su2double* derivCoor, + CConfig* config); /*! * \brief Function, which computes the gradients of the Cartesian coordinates w.r.t. the parametric coordinates in the given set of integration @@ -673,12 +662,9 @@ class CMeshFEM: public CGeometry { * \param[out] derivCoor - Storage for the derivatives of the coordinates. * \param[in] config - Definition of the particular problem. */ - void ComputeGradientsCoorWRTParam(const unsigned short nIntegration, - const unsigned short nDOFs, - const su2double *matDerBasisInt, - const unsigned long *DOFs, - su2double *derivCoor, - CConfig *config); + void ComputeGradientsCoorWRTParam(const unsigned short nIntegration, const unsigned short nDOFs, + const su2double* matDerBasisInt, const unsigned long* DOFs, su2double* derivCoor, + CConfig* config); /*! * \brief Function, which computes the information of the normals in the integration points of a face. @@ -690,12 +676,8 @@ class CMeshFEM: public CGeometry { * \param[in] DOFs - The DOFs of the grid associated with the face. * \param[out] normals - Storage for the normal information to be computed. */ - void ComputeNormalsFace(const unsigned short nIntegration, - const unsigned short nDOFs, - const su2double *dr, - const su2double *ds, - const unsigned long *DOFs, - su2double *normals); + void ComputeNormalsFace(const unsigned short nIntegration, const unsigned short nDOFs, const su2double* dr, + const su2double* ds, const unsigned long* DOFs, su2double* normals); /*! * \brief Function, which computes the metric terms of the faces of a @@ -704,8 +686,7 @@ class CMeshFEM: public CGeometry { terms must be computed. * \param[in] config - Definition of the particular problem. */ - void MetricTermsBoundaryFaces(CBoundaryFEM *boundary, - CConfig *config); + void MetricTermsBoundaryFaces(CBoundaryFEM* boundary, CConfig* config); }; /*! @@ -714,8 +695,8 @@ class CMeshFEM: public CGeometry { * \author E. van der Weide * \version 7.5.1 "Blackbird" */ -class CMeshFEM_DG: public CMeshFEM { -protected: +class CMeshFEM_DG : public CMeshFEM { + protected: vector standardElementsSol; /*!< \brief Vector that contains the standard volume elements used for the solution of the DG solver. */ vector standardElementsGrid; /*!< \brief Vector that contains the standard volume elements @@ -728,159 +709,160 @@ class CMeshFEM_DG: public CMeshFEM { internal faces used for the geometry of the DG solver. */ - vector timeCoefADER_DG; /*!< \brief The time coefficients in the iteration matrix of - the ADER-DG predictor step. */ - vector timeInterpolDOFToIntegrationADER_DG; /*!< \brief The interpolation matrix between the time DOFs and - the time integration points for ADER-DG. */ - vector timeInterpolAdjDOFToIntegrationADER_DG; /*!< \brief The interpolation matrix between the time DOFs of adjacent - elements of a higher time level and the time integration - points for ADER-DG. */ + vector timeCoefADER_DG; /*!< \brief The time coefficients in the iteration matrix of + the ADER-DG predictor step. */ + vector timeInterpolDOFToIntegrationADER_DG; /*!< \brief The interpolation matrix between the time DOFs and + the time integration points for ADER-DG. */ + vector timeInterpolAdjDOFToIntegrationADER_DG; /*!< \brief The interpolation matrix between the time DOFs + of adjacent elements of a higher time level and the time + integration points for ADER-DG. */ - vector nMatchingFacesInternal; /*!< \brief Number of matching faces between between two owned elements - per time level. Cumulative storage format. */ - vector nMatchingFacesWithHaloElem; /*!< \brief Number of matching faces between an owned element and a halo - element per time level. Cumulative storage format. */ - vector matchingFaces; /*!< \brief Vector of the local matching internal faces. */ + vector nMatchingFacesInternal; /*!< \brief Number of matching faces between between two owned elements + per time level. Cumulative storage format. */ + vector nMatchingFacesWithHaloElem; /*!< \brief Number of matching faces between an owned element and a + halo element per time level. Cumulative storage format. */ + vector matchingFaces; /*!< \brief Vector of the local matching internal faces. */ map Global_to_Local_Point; /*!< \brief Global-local mapping for the DOFs. */ -public: + public: /*! * \brief Constructor of the class. */ CMeshFEM_DG(void) : CMeshFEM() {} /*! - * \overload - * \brief Redistributes the grid over the ranks and creates the halo layer. - * \param[in] geometry - The linear distributed grid that must be redistributed. - * \param[in] config - Definition of the particular problem. - */ - CMeshFEM_DG(CGeometry *geometry, CConfig *config); + * \overload + * \brief Redistributes the grid over the ranks and creates the halo layer. + * \param[in] geometry - The linear distributed grid that must be redistributed. + * \param[in] config - Definition of the particular problem. + */ + CMeshFEM_DG(CGeometry* geometry, CConfig* config); - /*! - * \brief Function to compute the coordinates of the integration points. - */ + /*! + * \brief Function to compute the coordinates of the integration points. + */ void CoordinatesIntegrationPoints(void); - /*! - * \brief Function to compute the coordinates of solution DOFs. - */ + /*! + * \brief Function to compute the coordinates of solution DOFs. + */ void CoordinatesSolDOFs(void); - /*! - * \brief Function to create the faces used in the DG formulation. - * \param[in] config - Definition of the particular problem. - */ - void CreateFaces(CConfig *config); + /*! + * \brief Function to create the faces used in the DG formulation. + * \param[in] config - Definition of the particular problem. + */ + void CreateFaces(CConfig* config); - /*! - * \brief Function to create the standard volume elements. - * \param[in] config - Definition of the particular problem. - */ - void CreateStandardVolumeElements(CConfig *config); + /*! + * \brief Function to create the standard volume elements. + * \param[in] config - Definition of the particular problem. + */ + void CreateStandardVolumeElements(CConfig* config); - /*! - * \brief Function, which makes available the time coefficients in the - iteration matrix of the ADER-DG predictor step. - * \return The time coefficients in the iteration matrix of ADER-DG. - */ - inline su2double* GetTimeCoefADER_DG(void) {return timeCoefADER_DG.data();} + /*! + * \brief Function, which makes available the time coefficients in the + iteration matrix of the ADER-DG predictor step. + * \return The time coefficients in the iteration matrix of ADER-DG. + */ + inline su2double* GetTimeCoefADER_DG(void) { return timeCoefADER_DG.data(); } - /*! - * \brief Function, which makes available the time interpolation matrix between - the time DOFs and time integration points for ADER-DG. - * \return The time interpolation matrix for ADER-DG. - */ - inline su2double* GetTimeInterpolDOFToIntegrationADER_DG(void) {return timeInterpolDOFToIntegrationADER_DG.data();} + /*! + * \brief Function, which makes available the time interpolation matrix between + the time DOFs and time integration points for ADER-DG. + * \return The time interpolation matrix for ADER-DG. + */ + inline su2double* GetTimeInterpolDOFToIntegrationADER_DG(void) { return timeInterpolDOFToIntegrationADER_DG.data(); } - /*! - * \brief Function, which makes available the time interpolation matrix between - the adjacent time DOFs of the next time level and the time - integration points for ADER-DG. - * \return The time interpolation matrix of adjacent time DOFs for ADER-DG. - */ - inline su2double* GetTimeInterpolAdjDOFToIntegrationADER_DG(void) {return timeInterpolAdjDOFToIntegrationADER_DG.data();} + /*! + * \brief Function, which makes available the time interpolation matrix between + the adjacent time DOFs of the next time level and the time + integration points for ADER-DG. + * \return The time interpolation matrix of adjacent time DOFs for ADER-DG. + */ + inline su2double* GetTimeInterpolAdjDOFToIntegrationADER_DG(void) { + return timeInterpolAdjDOFToIntegrationADER_DG.data(); + } - /*! - * \brief Function, which makes available the number of matching internal faces - between an owned element and a halo element per time level. - * \return The number of matching internal faces between these elements per time level. - */ - inline unsigned long *GetNMatchingFacesWithHaloElem(void) {return nMatchingFacesWithHaloElem.data();} + /*! + * \brief Function, which makes available the number of matching internal faces + between an owned element and a halo element per time level. + * \return The number of matching internal faces between these elements per time level. + */ + inline unsigned long* GetNMatchingFacesWithHaloElem(void) { return nMatchingFacesWithHaloElem.data(); } - /*! - * \brief Function, which makes available the number of matching internal faces - between two owned elements per time level. - * \return The number of matching internal faces per time level. - */ - inline unsigned long *GetNMatchingFacesInternal(void) {return nMatchingFacesInternal.data();} + /*! + * \brief Function, which makes available the number of matching internal faces + between two owned elements per time level. + * \return The number of matching internal faces per time level. + */ + inline unsigned long* GetNMatchingFacesInternal(void) { return nMatchingFacesInternal.data(); } - /*! - * \brief Function, which makes available the matching internal faces. - * \return Pointer to the matching internal faces. - */ - inline CInternalFaceElementFEM* GetMatchingFaces(void) {return matchingFaces.data();} + /*! + * \brief Function, which makes available the matching internal faces. + * \return Pointer to the matching internal faces. + */ + inline CInternalFaceElementFEM* GetMatchingFaces(void) { return matchingFaces.data(); } - /*! - * \brief Function to compute the grid velocities for static problems. - * \param[in] config - Definition of the particular problem. - * \param[in] Kind_Grid_Movement - The type of prescribed grid motion. - * \param[in] iZone - The currently active zone number. - */ - void InitStaticMeshMovement(const CConfig *config, - const unsigned short Kind_Grid_Movement, + /*! + * \brief Function to compute the grid velocities for static problems. + * \param[in] config - Definition of the particular problem. + * \param[in] Kind_Grid_Movement - The type of prescribed grid motion. + * \param[in] iZone - The currently active zone number. + */ + void InitStaticMeshMovement(const CConfig* config, const unsigned short Kind_Grid_Movement, const unsigned short iZone); - /*! - * \brief Function, which makes available the number of standard volume elements of the solution. - * \return Number of standard volume elements of the solution. - */ - inline unsigned short GetNStandardElementsSol(void) {return standardElementsSol.size();} + /*! + * \brief Function, which makes available the number of standard volume elements of the solution. + * \return Number of standard volume elements of the solution. + */ + inline unsigned short GetNStandardElementsSol(void) { return standardElementsSol.size(); } - /*! - * \brief Function, which makes available the standard volume elements of the solution. - * \return Pointer to the standard volume elements of the solution. - */ - inline CFEMStandardElement* GetStandardElementsSol(void) {return standardElementsSol.data();} + /*! + * \brief Function, which makes available the standard volume elements of the solution. + * \return Pointer to the standard volume elements of the solution. + */ + inline CFEMStandardElement* GetStandardElementsSol(void) { return standardElementsSol.data(); } - /*! - * \brief Function, which makes available the number of standard internal matching faces of the solution. - * \return Number of standard internal matching faces of the solution. - */ - inline unsigned short GetNStandardMatchingFacesSol(void) {return standardMatchingFacesSol.size();} + /*! + * \brief Function, which makes available the number of standard internal matching faces of the solution. + * \return Number of standard internal matching faces of the solution. + */ + inline unsigned short GetNStandardMatchingFacesSol(void) { return standardMatchingFacesSol.size(); } - /*! - * \brief Function, which makes available the standard internal matching faces of the solution. - * \return Pointer to the standard internal matching faces of the solution. - */ - inline CFEMStandardInternalFace* GetStandardMatchingFacesSol(void) {return standardMatchingFacesSol.data();} + /*! + * \brief Function, which makes available the standard internal matching faces of the solution. + * \return Pointer to the standard internal matching faces of the solution. + */ + inline CFEMStandardInternalFace* GetStandardMatchingFacesSol(void) { return standardMatchingFacesSol.data(); } - /*! - * \brief Function, which computes a length scale of the volume elements. - * \param[in] config - Definition of the particular problem. - */ + /*! + * \brief Function, which computes a length scale of the volume elements. + * \param[in] config - Definition of the particular problem. + */ void LengthScaleVolumeElements(void); - /*! - * \brief Function, which computes the metric terms of the surface - elements, both internal faces and physical boundary faces. - * \param[in] config - Definition of the particular problem. - */ - void MetricTermsSurfaceElements(CConfig *config); + /*! + * \brief Function, which computes the metric terms of the surface + elements, both internal faces and physical boundary faces. + * \param[in] config - Definition of the particular problem. + */ + void MetricTermsSurfaceElements(CConfig* config); - /*! - * \brief Function, which computes the metric terms of the - volume elements. - * \param[in] config - Definition of the particular problem. - */ - void MetricTermsVolumeElements(CConfig *config); + /*! + * \brief Function, which computes the metric terms of the + volume elements. + * \param[in] config - Definition of the particular problem. + */ + void MetricTermsVolumeElements(CConfig* config); - /*! - * \brief Set the send receive boundaries of the grid. - * \param[in] config - Definition of the particular problem. - */ - void SetSendReceive(const CConfig *config) override; + /*! + * \brief Set the send receive boundaries of the grid. + * \param[in] config - Definition of the particular problem. + */ + void SetSendReceive(const CConfig* config) override; /*! * \brief Set the local index that correspond with the global numbering index. @@ -894,8 +876,7 @@ class CMeshFEM_DG: public CMeshFEM { */ inline long GetGlobal_to_Local_Point(unsigned long val_ipoint) const override { auto it = Global_to_Local_Point.find(val_ipoint); - if (it != Global_to_Local_Point.cend()) - return it->second; + if (it != Global_to_Local_Point.cend()) return it->second; return -1; } @@ -903,44 +884,39 @@ class CMeshFEM_DG: public CMeshFEM { * \brief Function, which carries out the preprocessing tasks when wall functions are used. * \param[in] config - Definition of the particular problem. */ - void WallFunctionPreprocessing(CConfig *config); + void WallFunctionPreprocessing(CConfig* config); -protected: - /*! - * \brief Function, which computes the correct sequence of the connectivities - of a face, such that it matches the sequence of the given corner points. - * \param[in] VTK_TypeFace - Type of the face using the VTK convention. - * \param[in] cornerPointsFace - The corner points of the face in the desired - sequence. - * \param[in] VTK_TypeElem - Type of the element using the VTK convention. - * \param[in] nPolyGrid - Polynomial degree used in the grid definition - for the face and the element. - * \param[in] elemNodeIDsGrid - The node IDs of the grid DOFs of the element, - i.e. the element connectivity. - * \param[in] nPolyConn - Polynomial degree of the connectivities to - be modified. - * \param[in] connElem - Connectivity of the adjacent volume element. - * \param[out] swapFaceInElement - Whether or not the connectivity of the face must - be swapped compared to the face of the corresponding - standard element. Only relevant for triangular faces - of a pyramid and quadrilateral faces of a prism. - corresponds to the top point of the adjacent pyramid. - * \param[out] modConnFace - Connectivity of the face after the renumbering. - * \param[out] modConnElem - Connectivity of the element after the renumbering. - This renumbering is such that the face corresponds - to the appropriate face of the element used in the - standard faces and also the corner points match. - */ - void CreateConnectivitiesFace(const unsigned short VTK_TypeFace, - const unsigned long *cornerPointsFace, - const unsigned short VTK_TypeElem, - const unsigned short nPolyGrid, - const vector &elemNodeIDsGrid, - const unsigned short nPolyConn, - const unsigned long *connElem, - bool &swapFaceInElement, - unsigned long *modConnFace, - unsigned long *modConnElem); + protected: + /*! + * \brief Function, which computes the correct sequence of the connectivities + of a face, such that it matches the sequence of the given corner points. + * \param[in] VTK_TypeFace - Type of the face using the VTK convention. + * \param[in] cornerPointsFace - The corner points of the face in the desired + sequence. + * \param[in] VTK_TypeElem - Type of the element using the VTK convention. + * \param[in] nPolyGrid - Polynomial degree used in the grid definition + for the face and the element. + * \param[in] elemNodeIDsGrid - The node IDs of the grid DOFs of the element, + i.e. the element connectivity. + * \param[in] nPolyConn - Polynomial degree of the connectivities to + be modified. + * \param[in] connElem - Connectivity of the adjacent volume element. + * \param[out] swapFaceInElement - Whether or not the connectivity of the face must + be swapped compared to the face of the corresponding + standard element. Only relevant for triangular faces + of a pyramid and quadrilateral faces of a prism. + corresponds to the top point of the adjacent pyramid. + * \param[out] modConnFace - Connectivity of the face after the renumbering. + * \param[out] modConnElem - Connectivity of the element after the renumbering. + This renumbering is such that the face corresponds + to the appropriate face of the element used in the + standard faces and also the corner points match. + */ + void CreateConnectivitiesFace(const unsigned short VTK_TypeFace, const unsigned long* cornerPointsFace, + const unsigned short VTK_TypeElem, const unsigned short nPolyGrid, + const vector& elemNodeIDsGrid, const unsigned short nPolyConn, + const unsigned long* connElem, bool& swapFaceInElement, unsigned long* modConnFace, + unsigned long* modConnElem); /*! * \brief Function, which computes the correct sequence of the connectivities @@ -960,14 +936,11 @@ class CMeshFEM_DG: public CMeshFEM { renumbering. This renumbering is such that the line corresponds to face 0 of the quadrilateral. */ - void CreateConnectivitiesLineAdjacentQuadrilateral( - const unsigned long *cornerPointsLine, - const unsigned short nPolyGrid, - const vector &quadNodeIDsGrid, - const unsigned short nPolyConn, - const unsigned long *connQuad, - unsigned long *modConnLine, - unsigned long *modConnQuad); + void CreateConnectivitiesLineAdjacentQuadrilateral(const unsigned long* cornerPointsLine, + const unsigned short nPolyGrid, + const vector& quadNodeIDsGrid, + const unsigned short nPolyConn, const unsigned long* connQuad, + unsigned long* modConnLine, unsigned long* modConnQuad); /*! * \brief Function, which computes the correct sequence of the connectivities @@ -987,14 +960,10 @@ class CMeshFEM_DG: public CMeshFEM { renumbering. This renumbering is such that the line corresponds to face 0 of the triangle. */ - void CreateConnectivitiesLineAdjacentTriangle( - const unsigned long *cornerPointsLine, - const unsigned short nPolyGrid, - const vector &triaNodeIDsGrid, - const unsigned short nPolyConn, - const unsigned long *connTria, - unsigned long *modConnLine, - unsigned long *modConnTria); + void CreateConnectivitiesLineAdjacentTriangle(const unsigned long* cornerPointsLine, const unsigned short nPolyGrid, + const vector& triaNodeIDsGrid, + const unsigned short nPolyConn, const unsigned long* connTria, + unsigned long* modConnLine, unsigned long* modConnTria); /*! * \brief Function, which computes the correct sequence of the connectivities @@ -1014,14 +983,12 @@ class CMeshFEM_DG: public CMeshFEM { renumbering. This renumbering is such that the quad corresponds to face 0 of the hexahedron. */ - void CreateConnectivitiesQuadrilateralAdjacentHexahedron( - const unsigned long *cornerPointsQuad, - const unsigned short nPolyGrid, - const vector &hexaNodeIDsGrid, - const unsigned short nPolyConn, - const unsigned long *connHexa, - unsigned long *modConnQuad, - unsigned long *modConnHexa); + void CreateConnectivitiesQuadrilateralAdjacentHexahedron(const unsigned long* cornerPointsQuad, + const unsigned short nPolyGrid, + const vector& hexaNodeIDsGrid, + const unsigned short nPolyConn, + const unsigned long* connHexa, unsigned long* modConnQuad, + unsigned long* modConnHexa); /*! * \brief Function, which computes the correct sequence of the connectivities @@ -1044,15 +1011,12 @@ class CMeshFEM_DG: public CMeshFEM { renumbering. This renumbering is such that the quad corresponds to face 3 of the prism. */ - void CreateConnectivitiesQuadrilateralAdjacentPrism( - const unsigned long *cornerPointsQuad, - const unsigned short nPolyGrid, - const vector &prismNodeIDsGrid, - const unsigned short nPolyConn, - const unsigned long *connPrism, - bool &swapFaceInElement, - unsigned long *modConnQuad, - unsigned long *modConnPrism); + void CreateConnectivitiesQuadrilateralAdjacentPrism(const unsigned long* cornerPointsQuad, + const unsigned short nPolyGrid, + const vector& prismNodeIDsGrid, + const unsigned short nPolyConn, const unsigned long* connPrism, + bool& swapFaceInElement, unsigned long* modConnQuad, + unsigned long* modConnPrism); /*! * \brief Function, which computes the correct sequence of the connectivities @@ -1072,14 +1036,11 @@ class CMeshFEM_DG: public CMeshFEM { renumbering. This renumbering is such that the quad corresponds to face 0 of the pyramid. */ - void CreateConnectivitiesQuadrilateralAdjacentPyramid( - const unsigned long *cornerPointsQuad, - const unsigned short nPolyGrid, - const vector &pyraNodeIDsGrid, - const unsigned short nPolyConn, - const unsigned long *connPyra, - unsigned long *modConnQuad, - unsigned long *modConnPyra); + void CreateConnectivitiesQuadrilateralAdjacentPyramid(const unsigned long* cornerPointsQuad, + const unsigned short nPolyGrid, + const vector& pyraNodeIDsGrid, + const unsigned short nPolyConn, const unsigned long* connPyra, + unsigned long* modConnQuad, unsigned long* modConnPyra); /*! * \brief Function, which computes the correct sequence of the connectivities @@ -1099,14 +1060,10 @@ class CMeshFEM_DG: public CMeshFEM { renumbering. This renumbering is such that the triangle corresponds to face 0 of the prism. */ - void CreateConnectivitiesTriangleAdjacentPrism( - const unsigned long *cornerPointsTria, - const unsigned short nPolyGrid, - const vector &prismNodeIDsGrid, - const unsigned short nPolyConn, - const unsigned long *connPrism, - unsigned long *modConnTria, - unsigned long *modConnPrism); + void CreateConnectivitiesTriangleAdjacentPrism(const unsigned long* cornerPointsTria, const unsigned short nPolyGrid, + const vector& prismNodeIDsGrid, + const unsigned short nPolyConn, const unsigned long* connPrism, + unsigned long* modConnTria, unsigned long* modConnPrism); /*! * \brief Function, which computes the correct sequence of the connectivities @@ -1129,15 +1086,12 @@ class CMeshFEM_DG: public CMeshFEM { renumbering. This renumbering is such that the triangle corresponds to face 3 of the pyramid. */ - void CreateConnectivitiesTriangleAdjacentPyramid( - const unsigned long *cornerPointsTria, - const unsigned short nPolyGrid, - const vector &pyraNodeIDsGrid, - const unsigned short nPolyConn, - const unsigned long *connPyra, - bool &swapFaceInElement, - unsigned long *modConnTria, - unsigned long *modConnPyra); + void CreateConnectivitiesTriangleAdjacentPyramid(const unsigned long* cornerPointsTria, + const unsigned short nPolyGrid, + const vector& pyraNodeIDsGrid, + const unsigned short nPolyConn, const unsigned long* connPyra, + bool& swapFaceInElement, unsigned long* modConnTria, + unsigned long* modConnPyra); /*! * \brief Function, which computes the correct sequence of the connectivities @@ -1157,48 +1111,42 @@ class CMeshFEM_DG: public CMeshFEM { renumbering. This renumbering is such that the triangle corresponds to face 0 of the tetrahedron. */ - void CreateConnectivitiesTriangleAdjacentTetrahedron( - const unsigned long *cornerPointsTria, - const unsigned short nPolyGrid, - const vector &tetNodeIDsGrid, - const unsigned short nPolyConn, - const unsigned long *connTet, - unsigned long *modConnTria, - unsigned long *modConnTet); - - /*! - * \brief Function, which computes the parametric coordinates of the given - Cartesian coordinates inside the given parent element. - * \param[in] coor - Cartesian coordinates for which the parametric - coordinates must be determined. - * \param[in] parElem - The high order parent element which contains - the point. - * \param[in] subElem - Low order sub element inside the parent element - which contains the point. - * \param[in] weightsSubElem - Interpolation weights inside subElem for the - coordinates. Used for an initial guess. - * \param[out] parCoor - Parametric coordinates inside the high order - parent element for the given coordinates. - These parametric coordinates must be computed. - */ - void HighOrderContainmentSearch(const su2double *coor, - const unsigned long parElem, - const unsigned short subElem, - const su2double *weightsSubElem, - su2double *parCoor); + void CreateConnectivitiesTriangleAdjacentTetrahedron(const unsigned long* cornerPointsTria, + const unsigned short nPolyGrid, + const vector& tetNodeIDsGrid, + const unsigned short nPolyConn, const unsigned long* connTet, + unsigned long* modConnTria, unsigned long* modConnTet); + + /*! + * \brief Function, which computes the parametric coordinates of the given + Cartesian coordinates inside the given parent element. + * \param[in] coor - Cartesian coordinates for which the parametric + coordinates must be determined. + * \param[in] parElem - The high order parent element which contains + the point. + * \param[in] subElem - Low order sub element inside the parent element + which contains the point. + * \param[in] weightsSubElem - Interpolation weights inside subElem for the + coordinates. Used for an initial guess. + * \param[out] parCoor - Parametric coordinates inside the high order + parent element for the given coordinates. + These parametric coordinates must be computed. + */ + void HighOrderContainmentSearch(const su2double* coor, const unsigned long parElem, const unsigned short subElem, + const su2double* weightsSubElem, su2double* parCoor); /*! * \brief Function, which computes the metric terms for internal matching faces. * \param[in] config - Definition of the particular problem. */ - void MetricTermsMatchingFaces(CConfig *config); + void MetricTermsMatchingFaces(CConfig* config); /*! - * \brief Function, which computes the time coefficients for the ADER-DG predictor step. - * \param[in] config - Definition of the particular problem. - */ - void TimeCoefficientsPredictorADER_DG(CConfig *config); + * \brief Function, which computes the time coefficients for the ADER-DG predictor step. + * \param[in] config - Definition of the particular problem. + */ + void TimeCoefficientsPredictorADER_DG(CConfig* config); /*! * \brief Function, which computes the volume metric terms for the given @@ -1210,16 +1158,15 @@ class CMeshFEM_DG: public CMeshFEM { terms must be computed. * \param[out] metricTerms - Vector in which the metric terms must be stored. */ - void VolumeMetricTermsFromCoorGradients(const unsigned short nEntities, - const su2double *gradCoor, - vector &metricTerms); + void VolumeMetricTermsFromCoorGradients(const unsigned short nEntities, const su2double* gradCoor, + vector& metricTerms); /*! * \brief Compute an ADT including the coordinates of all viscous markers * \param[in] config - Definition of the particular problem. * \return pointer to the ADT */ - std::unique_ptr ComputeViscousWallADT(const CConfig *config) const override; + std::unique_ptr ComputeViscousWallADT(const CConfig* config) const override; /*! * \brief Set wall distances a specific value @@ -1245,12 +1192,10 @@ class CMeshFEM_DG: public CMeshFEM { * \author T. Albring */ class CDummyMeshFEM_DG : public CMeshFEM_DG { - -public: + public: /*! * \brief Constructor of the class * \param[in] config - Definition of the particular problem. */ - CDummyMeshFEM_DG(CConfig *config); - + CDummyMeshFEM_DG(CConfig* config); }; diff --git a/Common/include/fem/fem_standard_element.hpp b/Common/include/fem/fem_standard_element.hpp index 6d871b0bee0..63869d7fff7 100644 --- a/Common/include/fem/fem_standard_element.hpp +++ b/Common/include/fem/fem_standard_element.hpp @@ -43,30 +43,32 @@ using namespace std; * \version 7.5.1 "Blackbird" */ class CFEMStandardElementBase { -protected: + protected: unsigned short VTK_Type; /*!< \brief Element type using the VTK convention. */ unsigned short orderExact; /*!< \brief Polynomial order that must be integrated exactly by the integration rule. */ unsigned short nIntegration; /*!< \brief Number of points used in the numerical integration. */ - bool constJacobian; /*!< \brief Whether or not the element has a constant Jacobian. */ + bool constJacobian; /*!< \brief Whether or not the element has a constant Jacobian. */ vector rIntegration; /*!< \brief r-location of the integration points for this standard element. */ - vector sIntegration; /*!< \brief s-location of the integration points for this standard element, if needed. */ - vector tIntegration; /*!< \brief t-location of the integration points for this standard element, if needed. */ + vector + sIntegration; /*!< \brief s-location of the integration points for this standard element, if needed. */ + vector + tIntegration; /*!< \brief t-location of the integration points for this standard element, if needed. */ vector wIntegration; /*!< \brief The weights of the integration points for this standard element. */ -public: + public: /*! - * \brief Constructor. Nothing to be done. - */ + * \brief Constructor. Nothing to be done. + */ CFEMStandardElementBase() = default; /*! - * \brief Destructor. Nothing to be done, because the vectors are deleted automatically. - */ + * \brief Destructor. Nothing to be done, because the vectors are deleted automatically. + */ virtual ~CFEMStandardElementBase() = default; -protected: + protected: /*! * \brief Alternative constructor. * \param[in] val_VTK_Type - Type of the element using the VTK convention. @@ -78,24 +80,21 @@ class CFEMStandardElementBase { be determined from the polynomial degree and the parameters in config. */ - CFEMStandardElementBase(unsigned short val_VTK_Type, - unsigned short val_nPoly, - bool val_constJac, - CConfig *config, + CFEMStandardElementBase(unsigned short val_VTK_Type, unsigned short val_nPoly, bool val_constJac, CConfig* config, unsigned short val_orderExact); -public: + public: /*! - * \brief Function, which makes available the type of the element. - * \return The type of the element using the VTK convention. - */ - inline unsigned short GetVTK_Type(void) const {return VTK_Type;} + * \brief Function, which makes available the type of the element. + * \return The type of the element using the VTK convention. + */ + inline unsigned short GetVTK_Type(void) const { return VTK_Type; } /*! - * \brief Function, which makes available the weights in the integration points. - * \return The const pointer to data, which stores the weights in the integration points. - */ - inline const su2double* GetWeightsIntegration(void) const {return wIntegration.data();} + * \brief Function, which makes available the weights in the integration points. + * \return The const pointer to data, which stores the weights in the integration points. + */ + inline const su2double* GetWeightsIntegration(void) const { return wIntegration.data(); } /*! * \brief Static function, which makes available the number of DOFs for an element @@ -105,51 +104,45 @@ class CFEMStandardElementBase { * \param[in] typeErrorMessage - Default argument used to write a good error message. * \return The number of DOFs */ - static unsigned short GetNDOFsStatic(unsigned short VTK_Type, - unsigned short nPoly, - unsigned long typeErrorMessage = 0); + static unsigned short GetNDOFsStatic(unsigned short VTK_Type, unsigned short nPoly, + unsigned long typeErrorMessage = 0); /*! - * \brief Function, which makes available the number of integration points for this standard element. - * \return The number of integration points of this standard element. - */ - inline unsigned short GetNIntegration(void) const {return nIntegration;} + * \brief Function, which makes available the number of integration points for this standard element. + * \return The number of integration points of this standard element. + */ + inline unsigned short GetNIntegration(void) const { return nIntegration; } /*! - * \brief Function, which makes available the polynomial order that must be integrated exactly. - * \return The polynomial order that must be integrated exactly. - */ - inline unsigned short GetOrderExact(void) const {return orderExact;} + * \brief Function, which makes available the polynomial order that must be integrated exactly. + * \return The polynomial order that must be integrated exactly. + */ + inline unsigned short GetOrderExact(void) const { return orderExact; } /*! - * \brief Static function, which computes the inverse of the given square matrix. - * \param[in] n - Number of rows/columns of the square matrix A. - * \param[in,out] A - On input the square matrix to be inverted. On output the inverse. - */ - static void InverseMatrix(unsigned short n, - vector &A); + * \brief Static function, which computes the inverse of the given square matrix. + * \param[in] n - Number of rows/columns of the square matrix A. + * \param[in,out] A - On input the square matrix to be inverted. On output the inverse. + */ + static void InverseMatrix(unsigned short n, vector& A); /*! - * \brief Function, which computes the gradient of the Vandermonde matrix for a standard 1D edge. - * \param[in] nDOFs - Number of DOFs, which in 1D is the polynomial degree + 1. - * \param[in] r - Parametric coordinates for which the gradient of the Vandermonde matrix must be computed. - * \param[out] VDr - Matrix to store the gradient of the Vandermonde matrix in all r-locations. - */ - void GradVandermonde1D(unsigned short nDOFs, - const vector &r, - vector &VDr); + * \brief Function, which computes the gradient of the Vandermonde matrix for a standard 1D edge. + * \param[in] nDOFs - Number of DOFs, which in 1D is the polynomial degree + 1. + * \param[in] r - Parametric coordinates for which the gradient of the Vandermonde matrix must be computed. + * \param[out] VDr - Matrix to store the gradient of the Vandermonde matrix in all r-locations. + */ + void GradVandermonde1D(unsigned short nDOFs, const vector& r, vector& VDr); /*! - * \brief Function, which computes the Vandermonde matrix for a standard 1D edge. - * \param[in] nDOFs - Number of DOFs, which in 1D is the polynomial degree + 1. - * \param[in] r - Parametric coordinates for which the Vandermonde matrix must be computed. - * \param[out] V - Matrix to store the Vandermonde matrix in all r-locations. - */ - void Vandermonde1D(unsigned short nDOFs, - const vector &r, - vector &V); + * \brief Function, which computes the Vandermonde matrix for a standard 1D edge. + * \param[in] nDOFs - Number of DOFs, which in 1D is the polynomial degree + 1. + * \param[in] r - Parametric coordinates for which the Vandermonde matrix must be computed. + * \param[out] V - Matrix to store the Vandermonde matrix in all r-locations. + */ + void Vandermonde1D(unsigned short nDOFs, const vector& r, vector& V); -protected: + protected: /*! * \brief Function, which checks if the sum of the given derivatives of the Lagrangian interpolation functions is 0 in the points. @@ -158,9 +151,8 @@ class CFEMStandardElementBase { * \param[in] dLagBasisPoints - Values of the derivatives of the Lagrangian interpolation functions in the given points. */ - void CheckSumDerivativesLagrangianBasisFunctions(const unsigned short nPoints, - const unsigned short nDOFs, - const vector &dLagBasisPoints); + void CheckSumDerivativesLagrangianBasisFunctions(const unsigned short nPoints, const unsigned short nDOFs, + const vector& dLagBasisPoints); /*! * \brief Function, which checks if the sum of the given Lagrangian interpolation @@ -170,15 +162,14 @@ class CFEMStandardElementBase { * \param[in,out] lagBasisPoints - Values of the Lagrangian interpolation functions in the given points. */ - void CheckSumLagrangianBasisFunctions(const unsigned short nPoints, - const unsigned short nDOFs, - vector &lagBasisPoints); + void CheckSumLagrangianBasisFunctions(const unsigned short nPoints, const unsigned short nDOFs, + vector& lagBasisPoints); /*! - * \brief Function, which copies the data of the given object into the current object. - * \param[in] other - Object, whose data is copied. - */ - void Copy(const CFEMStandardElementBase &other); + * \brief Function, which copies the data of the given object into the current object. + * \param[in] other - Object, whose data is copied. + */ + void Copy(const CFEMStandardElementBase& other); /*! * \brief Function, which computes the values of the derivatives of the basis functions @@ -196,125 +187,101 @@ class CFEMStandardElementBase { * \param[out] dtLagBasisIntegration - t-derivatives of the basis functions in the integration points of the face. */ - void DerivativesBasisFunctionsAdjacentElement(unsigned short VTK_TypeElem, - unsigned short nPolyElem, - const bool swapFaceInElement, - unsigned short &nDOFsElem, - vector &drLagBasisIntegration, - vector &dsLagBasisIntegration, - vector &dtLagBasisIntegration); - - /*! - * \brief Function, which computes the gradients of the Vandermonde matrix for a standard triangle. - * \param[in] nPoly - Polynomial degree of the triangle. - * \param[in] nDOFs - Number of DOFs of the triangle. - * \param[in] r - Parametric coordinate in r-direction for which the gradient of the Vandermonde matrix must be computed. - * \param[in] s - Parametric coordinate in s-direction for which the gradient of the Vandermonde matrix must be computed. - * \param[out] VDr - Matrix to store the gradient in r-direction of the Vandermonde matrix in all r- and s-locations. - * \param[out] VDs - Matrix to store the gradient in s-direction of the Vandermonde matrix in all r- and s-locations. - */ - void GradVandermonde2D_Triangle(unsigned short nPoly, - unsigned short nDOFs, - const vector &r, - const vector &s, - vector &VDr, - vector &VDs); - - /*! - * \brief Function, which computes the gradients of the Vandermonde matrix for a standard quadrilateral. - * \param[in] nPoly - Polynomial degree of the quadrilateral. - * \param[in] nDOFs - Number of DOFs of the quadrilateral. - * \param[in] r - Parametric coordinate in r-direction for which the gradient of the Vandermonde matrix must be computed. - * \param[in] s - Parametric coordinate in s-direction for which the gradient of the Vandermonde matrix must be computed. - * \param[out] VDr - Matrix to store the gradient in r-direction of the Vandermonde matrix in all r- and s-locations. - * \param[out] VDs - Matrix to store the gradient in s-direction of the Vandermonde matrix in all r- and s-locations. - */ - void GradVandermonde2D_Quadrilateral(unsigned short nPoly, - unsigned short nDOFs, - const vector &r, - const vector &s, - vector &VDr, - vector &VDs); - - /*! - * \brief Function, which computes the gradients of the Vandermonde matrix for a standard tetrahedron. - * \param[in] nPoly - Polynomial degree of the tetrahedron. - * \param[in] nDOFs - Number of DOFs of the tetrahedron. - * \param[in] r - Parametric coordinate in r-direction for which the gradient of the Vandermonde matrix must be computed. - * \param[in] s - Parametric coordinate in s-direction for which the gradient of the Vandermonde matrix must be computed. - * \param[in] t - Parametric coordinate in t-direction for which the gradient of the Vandermonde matrix must be computed. - * \param[out] VDr - Matrix to store the gradient in r-direction of the Vandermonde matrix in all r-, s- and t-locations. - * \param[out] VDs - Matrix to store the gradient in s-direction of the Vandermonde matrix in all r-, s- and t-locations. - * \param[out] VDt - Matrix to store the gradient in t-direction of the Vandermonde matrix in all r-, s- and t-locations. - */ - void GradVandermonde3D_Tetrahedron(unsigned short nPoly, - unsigned short nDOFs, - const vector &r, - const vector &s, - const vector &t, - vector &VDr, - vector &VDs, - vector &VDt); - - /*! - * \brief Function, which computes the gradients of the Vandermonde matrix for a standard pyramid. - * \param[in] nPoly - Polynomial degree of the pyramid. - * \param[in] nDOFs - Number of DOFs of the pyramid. - * \param[in] r - Parametric coordinate in r-direction for which the gradient of the Vandermonde matrix must be computed. - * \param[in] s - Parametric coordinate in s-direction for which the gradient of the Vandermonde matrix must be computed. - * \param[in] t - Parametric coordinate in t-direction for which the gradient of the Vandermonde matrix must be computed. - * \param[out] VDr - Matrix to store the gradient in r-direction of the Vandermonde matrix in all r-, s- and t-locations. - * \param[out] VDs - Matrix to store the gradient in s-direction of the Vandermonde matrix in all r-, s- and t-locations. - * \param[out] VDt - Matrix to store the gradient in t-direction of the Vandermonde matrix in all r-, s- and t-locations. - */ - void GradVandermonde3D_Pyramid(unsigned short nPoly, - unsigned short nDOFs, - const vector &r, - const vector &s, - const vector &t, - vector &VDr, - vector &VDs, - vector &VDt); - - /*! - * \brief Function, which computes the gradients of the Vandermonde matrix for a standard prism. - * \param[in] nPoly - Polynomial degree of the prism. - * \param[in] nDOFs - Number of DOFs of the prism. - * \param[in] r - Parametric coordinate in r-direction for which the gradient of the Vandermonde matrix must be computed. - * \param[in] s - Parametric coordinate in s-direction for which the gradient of the Vandermonde matrix must be computed. - * \param[in] t - Parametric coordinate in t-direction for which the gradient of the Vandermonde matrix must be computed. - * \param[out] VDr - Matrix to store the gradient in r-direction of the Vandermonde matrix in all r-, s- and t-locations. - * \param[out] VDs - Matrix to store the gradient in s-direction of the Vandermonde matrix in all r-, s- and t-locations. - * \param[out] VDt - Matrix to store the gradient in t-direction of the Vandermonde matrix in all r-, s- and t-locations. - */ - void GradVandermonde3D_Prism(unsigned short nPoly, - unsigned short nDOFs, - const vector &r, - const vector &s, - const vector &t, - vector &VDr, - vector &VDs, - vector &VDt); - - /*! - * \brief Function, which computes the gradients of the Vandermonde matrix for a standard hexahedron. - * \param[in] nPoly - Polynomial degree of the hexahedron. - * \param[in] nDOFs - Number of DOFs of the hexahedron. - * \param[in] r - Parametric coordinate in r-direction for which the gradient of the Vandermonde matrix must be computed. - * \param[in] s - Parametric coordinate in s-direction for which the gradient of the Vandermonde matrix must be computed. - * \param[in] t - Parametric coordinate in t-direction for which the gradient of the Vandermonde matrix must be computed. - * \param[out] VDr - Matrix to store the gradient in r-direction of the Vandermonde matrix in all r-, s- and t-locations. - * \param[out] VDs - Matrix to store the gradient in s-direction of the Vandermonde matrix in all r-, s- and t-locations. - * \param[out] VDt - Matrix to store the gradient in t-direction of the Vandermonde matrix in all r-, s- and t-locations. - */ - void GradVandermonde3D_Hexahedron(unsigned short nPoly, - unsigned short nDOFs, - const vector &r, - const vector &s, - const vector &t, - vector &VDr, - vector &VDs, - vector &VDt); + void DerivativesBasisFunctionsAdjacentElement(unsigned short VTK_TypeElem, unsigned short nPolyElem, + const bool swapFaceInElement, unsigned short& nDOFsElem, + vector& drLagBasisIntegration, + vector& dsLagBasisIntegration, + vector& dtLagBasisIntegration); + + /*! + * \brief Function, which computes the gradients of the Vandermonde matrix for a standard triangle. + * \param[in] nPoly - Polynomial degree of the triangle. + * \param[in] nDOFs - Number of DOFs of the triangle. + * \param[in] r - Parametric coordinate in r-direction for which the gradient of the Vandermonde matrix must be + * computed. \param[in] s - Parametric coordinate in s-direction for which the gradient of the Vandermonde matrix + * must be computed. \param[out] VDr - Matrix to store the gradient in r-direction of the Vandermonde matrix in all + * r- and s-locations. \param[out] VDs - Matrix to store the gradient in s-direction of the Vandermonde matrix in + * all r- and s-locations. + */ + void GradVandermonde2D_Triangle(unsigned short nPoly, unsigned short nDOFs, const vector& r, + const vector& s, vector& VDr, vector& VDs); + + /*! + * \brief Function, which computes the gradients of the Vandermonde matrix for a standard quadrilateral. + * \param[in] nPoly - Polynomial degree of the quadrilateral. + * \param[in] nDOFs - Number of DOFs of the quadrilateral. + * \param[in] r - Parametric coordinate in r-direction for which the gradient of the Vandermonde matrix must be + * computed. \param[in] s - Parametric coordinate in s-direction for which the gradient of the Vandermonde matrix + * must be computed. \param[out] VDr - Matrix to store the gradient in r-direction of the Vandermonde matrix in all + * r- and s-locations. \param[out] VDs - Matrix to store the gradient in s-direction of the Vandermonde matrix in + * all r- and s-locations. + */ + void GradVandermonde2D_Quadrilateral(unsigned short nPoly, unsigned short nDOFs, const vector& r, + const vector& s, vector& VDr, vector& VDs); + + /*! + * \brief Function, which computes the gradients of the Vandermonde matrix for a standard tetrahedron. + * \param[in] nPoly - Polynomial degree of the tetrahedron. + * \param[in] nDOFs - Number of DOFs of the tetrahedron. + * \param[in] r - Parametric coordinate in r-direction for which the gradient of the Vandermonde matrix must be + * computed. \param[in] s - Parametric coordinate in s-direction for which the gradient of the Vandermonde matrix + * must be computed. \param[in] t - Parametric coordinate in t-direction for which the gradient of the + * Vandermonde matrix must be computed. \param[out] VDr - Matrix to store the gradient in r-direction of the + * Vandermonde matrix in all r-, s- and t-locations. \param[out] VDs - Matrix to store the gradient in s-direction + * of the Vandermonde matrix in all r-, s- and t-locations. \param[out] VDt - Matrix to store the gradient in + * t-direction of the Vandermonde matrix in all r-, s- and t-locations. + */ + void GradVandermonde3D_Tetrahedron(unsigned short nPoly, unsigned short nDOFs, const vector& r, + const vector& s, const vector& t, vector& VDr, + vector& VDs, vector& VDt); + + /*! + * \brief Function, which computes the gradients of the Vandermonde matrix for a standard pyramid. + * \param[in] nPoly - Polynomial degree of the pyramid. + * \param[in] nDOFs - Number of DOFs of the pyramid. + * \param[in] r - Parametric coordinate in r-direction for which the gradient of the Vandermonde matrix must be + * computed. \param[in] s - Parametric coordinate in s-direction for which the gradient of the Vandermonde matrix + * must be computed. \param[in] t - Parametric coordinate in t-direction for which the gradient of the + * Vandermonde matrix must be computed. \param[out] VDr - Matrix to store the gradient in r-direction of the + * Vandermonde matrix in all r-, s- and t-locations. \param[out] VDs - Matrix to store the gradient in s-direction + * of the Vandermonde matrix in all r-, s- and t-locations. \param[out] VDt - Matrix to store the gradient in + * t-direction of the Vandermonde matrix in all r-, s- and t-locations. + */ + void GradVandermonde3D_Pyramid(unsigned short nPoly, unsigned short nDOFs, const vector& r, + const vector& s, const vector& t, vector& VDr, + vector& VDs, vector& VDt); + + /*! + * \brief Function, which computes the gradients of the Vandermonde matrix for a standard prism. + * \param[in] nPoly - Polynomial degree of the prism. + * \param[in] nDOFs - Number of DOFs of the prism. + * \param[in] r - Parametric coordinate in r-direction for which the gradient of the Vandermonde matrix must be + * computed. \param[in] s - Parametric coordinate in s-direction for which the gradient of the Vandermonde matrix + * must be computed. \param[in] t - Parametric coordinate in t-direction for which the gradient of the + * Vandermonde matrix must be computed. \param[out] VDr - Matrix to store the gradient in r-direction of the + * Vandermonde matrix in all r-, s- and t-locations. \param[out] VDs - Matrix to store the gradient in s-direction + * of the Vandermonde matrix in all r-, s- and t-locations. \param[out] VDt - Matrix to store the gradient in + * t-direction of the Vandermonde matrix in all r-, s- and t-locations. + */ + void GradVandermonde3D_Prism(unsigned short nPoly, unsigned short nDOFs, const vector& r, + const vector& s, const vector& t, vector& VDr, + vector& VDs, vector& VDt); + + /*! + * \brief Function, which computes the gradients of the Vandermonde matrix for a standard hexahedron. + * \param[in] nPoly - Polynomial degree of the hexahedron. + * \param[in] nDOFs - Number of DOFs of the hexahedron. + * \param[in] r - Parametric coordinate in r-direction for which the gradient of the Vandermonde matrix must be + * computed. \param[in] s - Parametric coordinate in s-direction for which the gradient of the Vandermonde matrix + * must be computed. \param[in] t - Parametric coordinate in t-direction for which the gradient of the + * Vandermonde matrix must be computed. \param[out] VDr - Matrix to store the gradient in r-direction of the + * Vandermonde matrix in all r-, s- and t-locations. \param[out] VDs - Matrix to store the gradient in s-direction + * of the Vandermonde matrix in all r-, s- and t-locations. \param[out] VDt - Matrix to store the gradient in + * t-direction of the Vandermonde matrix in all r-, s- and t-locations. + */ + void GradVandermonde3D_Hexahedron(unsigned short nPoly, unsigned short nDOFs, const vector& r, + const vector& s, const vector& t, vector& VDr, + vector& VDs, vector& VDt); /*! * \brief Function, which determines the values of the Lagrangian interpolation @@ -330,13 +297,11 @@ class CFEMStandardElementBase { * \param[out] drLagBasisPoints - Values of the r-derivatives of the Lagrangian interpolation functions in the given points. */ - void LagrangianBasisFunctionAndDerivativesLine(const unsigned short nPoly, - const vector &rPoints, - unsigned short &nDOFs, - vector &rDOFs, - vector &matVandermondeInv, - vector &lagBasisPoints, - vector &drLagBasisPoints); + void LagrangianBasisFunctionAndDerivativesLine(const unsigned short nPoly, const vector& rPoints, + unsigned short& nDOFs, vector& rDOFs, + vector& matVandermondeInv, + vector& lagBasisPoints, + vector& drLagBasisPoints); /*! * \brief Function, which determines the values of the Lagrangian interpolation @@ -357,16 +322,10 @@ class CFEMStandardElementBase { * \param[out] dsLagBasisPoints - Values of the s-derivatives of the Lagrangian interpolation functions in the given points. */ - void LagrangianBasisFunctionAndDerivativesTriangle(const unsigned short nPoly, - const vector &rPoints, - const vector &sPoints, - unsigned short &nDOFs, - vector &rDOFs, - vector &sDOFs, - vector &matVandermondeInv, - vector &lagBasisPoints, - vector &drLagBasisPoints, - vector &dsLagBasisPoints); + void LagrangianBasisFunctionAndDerivativesTriangle( + const unsigned short nPoly, const vector& rPoints, const vector& sPoints, + unsigned short& nDOFs, vector& rDOFs, vector& sDOFs, vector& matVandermondeInv, + vector& lagBasisPoints, vector& drLagBasisPoints, vector& dsLagBasisPoints); /*! * \brief Function, which determines the values of the Lagrangian interpolation @@ -387,16 +346,10 @@ class CFEMStandardElementBase { * \param[out] dsLagBasisPoints - Values of the s-derivatives of the Lagrangian interpolation functions in the given points. */ - void LagrangianBasisFunctionAndDerivativesQuadrilateral(const unsigned short nPoly, - const vector &rPoints, - const vector &sPoints, - unsigned short &nDOFs, - vector &rDOFs, - vector &sDOFs, - vector &matVandermondeInv, - vector &lagBasisPoints, - vector &drLagBasisPoints, - vector &dsLagBasisPoints); + void LagrangianBasisFunctionAndDerivativesQuadrilateral( + const unsigned short nPoly, const vector& rPoints, const vector& sPoints, + unsigned short& nDOFs, vector& rDOFs, vector& sDOFs, vector& matVandermondeInv, + vector& lagBasisPoints, vector& drLagBasisPoints, vector& dsLagBasisPoints); /*! * \brief Function, which determines the values of the Lagrangian interpolation @@ -422,19 +375,11 @@ class CFEMStandardElementBase { * \param[out] dtLagBasisPoints - Values of the t-derivatives of the Lagrangian interpolation functions in the given points. */ - void LagrangianBasisFunctionAndDerivativesTetrahedron(const unsigned short nPoly, - const vector &rPoints, - const vector &sPoints, - const vector &tPoints, - unsigned short &nDOFs, - vector &rDOFs, - vector &sDOFs, - vector &tDOFs, - vector &matVandermondeInv, - vector &lagBasisPoints, - vector &drLagBasisPoints, - vector &dsLagBasisPoints, - vector &dtLagBasisPoints); + void LagrangianBasisFunctionAndDerivativesTetrahedron( + const unsigned short nPoly, const vector& rPoints, const vector& sPoints, + const vector& tPoints, unsigned short& nDOFs, vector& rDOFs, vector& sDOFs, + vector& tDOFs, vector& matVandermondeInv, vector& lagBasisPoints, + vector& drLagBasisPoints, vector& dsLagBasisPoints, vector& dtLagBasisPoints); /*! * \brief Function, which determines the values of the Lagrangian interpolation @@ -460,19 +405,11 @@ class CFEMStandardElementBase { * \param[out] dtLagBasisPoints - Values of the t-derivatives of the Lagrangian interpolation functions in the given points. */ - void LagrangianBasisFunctionAndDerivativesPyramid(const unsigned short nPoly, - const vector &rPoints, - const vector &sPoints, - const vector &tPoints, - unsigned short &nDOFs, - vector &rDOFs, - vector &sDOFs, - vector &tDOFs, - vector &matVandermondeInv, - vector &lagBasisPoints, - vector &drLagBasisPoints, - vector &dsLagBasisPoints, - vector &dtLagBasisPoints); + void LagrangianBasisFunctionAndDerivativesPyramid( + const unsigned short nPoly, const vector& rPoints, const vector& sPoints, + const vector& tPoints, unsigned short& nDOFs, vector& rDOFs, vector& sDOFs, + vector& tDOFs, vector& matVandermondeInv, vector& lagBasisPoints, + vector& drLagBasisPoints, vector& dsLagBasisPoints, vector& dtLagBasisPoints); /*! * \brief Function, which determines the values of the Lagrangian interpolation @@ -498,19 +435,11 @@ class CFEMStandardElementBase { * \param[out] dtLagBasisPoints - Values of the t-derivatives of the Lagrangian interpolation functions in the given points. */ - void LagrangianBasisFunctionAndDerivativesPrism(const unsigned short nPoly, - const vector &rPoints, - const vector &sPoints, - const vector &tPoints, - unsigned short &nDOFs, - vector &rDOFs, - vector &sDOFs, - vector &tDOFs, - vector &matVandermondeInv, - vector &lagBasisPoints, - vector &drLagBasisPoints, - vector &dsLagBasisPoints, - vector &dtLagBasisPoints); + void LagrangianBasisFunctionAndDerivativesPrism( + const unsigned short nPoly, const vector& rPoints, const vector& sPoints, + const vector& tPoints, unsigned short& nDOFs, vector& rDOFs, vector& sDOFs, + vector& tDOFs, vector& matVandermondeInv, vector& lagBasisPoints, + vector& drLagBasisPoints, vector& dsLagBasisPoints, vector& dtLagBasisPoints); /*! * \brief Function, which determines the values of the Lagrangian interpolation @@ -536,19 +465,11 @@ class CFEMStandardElementBase { * \param[out] dtLagBasisPoints - Values of the t-derivatives of the Lagrangian interpolation functions in the given points. */ - void LagrangianBasisFunctionAndDerivativesHexahedron(const unsigned short nPoly, - const vector &rPoints, - const vector &sPoints, - const vector &tPoints, - unsigned short &nDOFs, - vector &rDOFs, - vector &sDOFs, - vector &tDOFs, - vector &matVandermondeInv, - vector &lagBasisPoints, - vector &drLagBasisPoints, - vector &dsLagBasisPoints, - vector &dtLagBasisPoints); + void LagrangianBasisFunctionAndDerivativesHexahedron( + const unsigned short nPoly, const vector& rPoints, const vector& sPoints, + const vector& tPoints, unsigned short& nDOFs, vector& rDOFs, vector& sDOFs, + vector& tDOFs, vector& matVandermondeInv, vector& lagBasisPoints, + vector& drLagBasisPoints, vector& dsLagBasisPoints, vector& dtLagBasisPoints); /*! * \brief Function, which carries out a matrix matrix multiplication to obtain @@ -564,11 +485,8 @@ class CFEMStandardElementBase { * \param[out] C - Result of A*B, dimension nPoints X nDOFs. The result is stored in row major order */ - void MatMulRowMajor(const unsigned short nDOFs, - const unsigned short nPoints, - const vector &A, - const vector &B, - vector &C); + void MatMulRowMajor(const unsigned short nDOFs, const unsigned short nPoints, const vector& A, + const vector& B, vector& C); /*! * \brief Function, which computes the local connectivity of linear subelements of @@ -576,8 +494,7 @@ class CFEMStandardElementBase { * \param[in] nPoly - Polynomial degree of the line. * \param[out] subConn - The local subconnectivity of a line element. */ - void SubConnForPlottingLine(const unsigned short nPoly, - vector &subConn); + void SubConnForPlottingLine(const unsigned short nPoly, vector& subConn); /*! * \brief Function, which computes the local connectivity of linear subelements of @@ -585,8 +502,7 @@ class CFEMStandardElementBase { * \param[in] nPoly - Polynomial degree of the quadrilateral. * \param[out] subConn - The local subconnectivity of a triangle element. */ - void SubConnForPlottingQuadrilateral(const unsigned short nPoly, - vector &subConn); + void SubConnForPlottingQuadrilateral(const unsigned short nPoly, vector& subConn); /*! * \brief Function, which computes the local connectivity of linear subelements of @@ -594,8 +510,7 @@ class CFEMStandardElementBase { * \param[in] nPoly - Polynomial degree of the triangle. * \param[out] subConn - The local subconnectivity of a triangle element. */ - void SubConnForPlottingTriangle(const unsigned short nPoly, - vector &subConn); + void SubConnForPlottingTriangle(const unsigned short nPoly, vector& subConn); /*! * \brief Function, which computes the Vandermonde matrix for a standard triangle. @@ -604,12 +519,9 @@ class CFEMStandardElementBase { * \param[in] r - Parametric coordinates in r-direction for which the Vandermonde matrix must be computed. * \param[in] s - Parametric coordinates in s-direction for which the Vandermonde matrix must be computed. * \param[out] V - Matrix to store the Vandermonde matrix in all r- and s-locations. - */ - void Vandermonde2D_Triangle(unsigned short nPoly, - unsigned short nDOFs, - const vector &r, - const vector &s, - vector &V); + */ + void Vandermonde2D_Triangle(unsigned short nPoly, unsigned short nDOFs, const vector& r, + const vector& s, vector& V); /*! * \brief Function, which computes the Vandermonde matrix for a standard quadrilateral. @@ -618,12 +530,9 @@ class CFEMStandardElementBase { * \param[in] r - Parametric coordinates in r-direction for which the Vandermonde matrix must be computed. * \param[in] s - Parametric coordinates in s-direction for which the Vandermonde matrix must be computed. * \param[out] V - Matrix to store the Vandermonde matrix in all r- and s-locations. - */ - void Vandermonde2D_Quadrilateral(unsigned short nPoly, - unsigned short nDOFs, - const vector &r, - const vector &s, - vector &V); + */ + void Vandermonde2D_Quadrilateral(unsigned short nPoly, unsigned short nDOFs, const vector& r, + const vector& s, vector& V); /*! * \brief Function, which computes the Vandermonde matrix for a standard tetrahedron. @@ -633,13 +542,9 @@ class CFEMStandardElementBase { * \param[in] s - Parametric coordinates in s-direction for which the Vandermonde matrix must be computed. * \param[in] t - Parametric coordinates in t-direction for which the Vandermonde matrix must be computed. * \param[out] V - Matrix to store the Vandermonde matrix in all r-, s- and t-locations. - */ - void Vandermonde3D_Tetrahedron(unsigned short nPoly, - unsigned short nDOFs, - const vector &r, - const vector &s, - const vector &t, - vector &V); + */ + void Vandermonde3D_Tetrahedron(unsigned short nPoly, unsigned short nDOFs, const vector& r, + const vector& s, const vector& t, vector& V); /*! * \brief Function, which computes the Vandermonde matrix for a standard pyramid. @@ -649,13 +554,9 @@ class CFEMStandardElementBase { * \param[in] s - Parametric coordinates in s-direction for which the Vandermonde matrix must be computed. * \param[in] t - Parametric coordinates in t-direction for which the Vandermonde matrix must be computed. * \param[out] V - Matrix to store the Vandermonde matrix in all r-, s- and t-locations. - */ - void Vandermonde3D_Pyramid(unsigned short nPoly, - unsigned short nDOFs, - const vector &r, - const vector &s, - const vector &t, - vector &V); + */ + void Vandermonde3D_Pyramid(unsigned short nPoly, unsigned short nDOFs, const vector& r, + const vector& s, const vector& t, vector& V); /*! * \brief Function, which computes the Vandermonde matrix for a standard prism. @@ -665,13 +566,9 @@ class CFEMStandardElementBase { * \param[in] s - Parametric coordinates in s-direction for which the Vandermonde matrix must be computed. * \param[in] t - Parametric coordinates in t-direction for which the Vandermonde matrix must be computed. * \param[out] V - Matrix to store the Vandermonde matrix in all r-, s- and t-locations. - */ - void Vandermonde3D_Prism(unsigned short nPoly, - unsigned short nDOFs, - const vector &r, - const vector &s, - const vector &t, - vector &V); + */ + void Vandermonde3D_Prism(unsigned short nPoly, unsigned short nDOFs, const vector& r, + const vector& s, const vector& t, vector& V); /*! * \brief Function, which computes the Vandermonde matrix for a standard hexahedron. @@ -681,13 +578,9 @@ class CFEMStandardElementBase { * \param[in] s - Parametric coordinates in s-direction for which the Vandermonde matrix must be computed. * \param[in] t - Parametric coordinates in t-direction for which the Vandermonde matrix must be computed. * \param[out] V - Matrix to store the Vandermonde matrix in all r-, s- and t-locations. - */ - void Vandermonde3D_Hexahedron(unsigned short nPoly, - unsigned short nDOFs, - const vector &r, - const vector &s, - const vector &t, - vector &V); + */ + void Vandermonde3D_Hexahedron(unsigned short nPoly, unsigned short nDOFs, const vector& r, + const vector& s, const vector& t, vector& V); /*! * \brief Function, which computes the constant in the penalty terms for a @@ -697,29 +590,26 @@ class CFEMStandardElementBase { * \param[in] nPolyElem - The polynomial degree of the adjacent element. * \return The value of the viscous penalty parameter. */ - su2double ViscousPenaltyParameter(const unsigned short VTK_TypeElem, - const unsigned short nPolyElem) const; -private: + su2double ViscousPenaltyParameter(const unsigned short VTK_TypeElem, const unsigned short nPolyElem) const; + + private: /*! - * \brief Function, which determines the 1D Gauss Legendre integration points and weights. - * \param[in,out] GLPoints - The location of the Gauss-Legendre integration points. - * \param[in,out] GLWeights - The weights of the Gauss-Legendre integration points. - */ - void GaussLegendrePoints1D(vector &GLPoints, - vector &GLWeights); + * \brief Function, which determines the 1D Gauss Legendre integration points and weights. + * \param[in,out] GLPoints - The location of the Gauss-Legendre integration points. + * \param[in,out] GLWeights - The weights of the Gauss-Legendre integration points. + */ + void GaussLegendrePoints1D(vector& GLPoints, vector& GLWeights); /*! - * \brief Function, which computes the value of the gradient of the Jacobi polynomial for the given x-coordinate. - * \param[in] n - Order of the Jacobi polynomial. - * \param[in] alpha - Alpha coefficient of the Jacobi polynomial. - * \param[in] beta - Beta coefficient of the Jacobi polynomial. - * \param[in] x - Coordinate (-1 <= x <= 1) for which the gradient of the Jacobi polynomial must be evaluated. - * \return The value of the gradient of the normalized Jacobi polynomial f order n for the given value of x. - */ - su2double GradNormJacobi(unsigned short n, - unsigned short alpha, - unsigned short beta, - su2double x); + * \brief Function, which computes the value of the gradient of the Jacobi polynomial for the given x-coordinate. + * \param[in] n - Order of the Jacobi polynomial. + * \param[in] alpha - Alpha coefficient of the Jacobi polynomial. + * \param[in] beta - Beta coefficient of the Jacobi polynomial. + * \param[in] x - Coordinate (-1 <= x <= 1) for which the gradient of the Jacobi polynomial must be evaluated. + * \return The value of the gradient of the normalized Jacobi polynomial f order n for the given value of + * x. + */ + su2double GradNormJacobi(unsigned short n, unsigned short alpha, unsigned short beta, su2double x); /*! * \brief Function, which determines the integration points for a line @@ -764,17 +654,14 @@ class CFEMStandardElementBase { void IntegrationPointsHexahedron(void); /*! - * \brief Function, which computes the value of the Jacobi polynomial for the given x-coordinate. - * \param[in] n - Order of the Jacobi polynomial. - * \param[in] alpha - Alpha coefficient of the Jacobi polynomial. - * \param[in] beta - Beta coefficient of the Jacobi polynomial. - * \param[in] x - Coordinate (-1 <= x <= 1) for which the Jacobi polynomial must be evaluated. - * \return The value of the normalized Jacobi polynomial f order n for the given value of x. - */ - su2double NormJacobi(unsigned short n, - unsigned short alpha, - unsigned short beta, - su2double x); + * \brief Function, which computes the value of the Jacobi polynomial for the given x-coordinate. + * \param[in] n - Order of the Jacobi polynomial. + * \param[in] alpha - Alpha coefficient of the Jacobi polynomial. + * \param[in] beta - Beta coefficient of the Jacobi polynomial. + * \param[in] x - Coordinate (-1 <= x <= 1) for which the Jacobi polynomial must be evaluated. + * \return The value of the normalized Jacobi polynomial f order n for the given value of x. + */ + su2double NormJacobi(unsigned short n, unsigned short alpha, unsigned short beta, su2double x); }; /*! @@ -784,50 +671,54 @@ class CFEMStandardElementBase { * \version 7.5.1 "Blackbird" */ class CFEMStandardElement : public CFEMStandardElementBase { -private: - - unsigned short nPoly; /*!< \brief Polynomial degree of the element. */ - unsigned short nDOFs; /*!< \brief Number of DOFs of the element. */ - - unsigned short VTK_Type1; /*!< \brief VTK type for elements of type 1 in subConn1ForPlotting. */ - unsigned short VTK_Type2; /*!< \brief VTK type for elements of type 2 in subConn2ForPlotting. */ - - vector rDOFs; /*!< \brief r-location of the DOFs for this standard element. */ - vector sDOFs; /*!< \brief s-location of the DOFs for this standard element, if needed. */ - vector tDOFs; /*!< \brief t-location of the DOFs for this standard element, if needed. */ - - vector lagBasisIntegration; /*!< \brief Lagrangian basis functions in the integration points. */ - vector lagBasisIntegrationTrans; /*!< \brief Transpose of lagBasisIntegration. It is stored such that - in the ADER-DG predictor step the residual is obtained - by one matrix multiplication. */ - vector lagBasisSolDOFs; /*!< \brief Lagrangian basis functions in the solution DOFs. Only different - from 1 if the polynomial degree of the grid and solution differs. */ - - vector drLagBasisIntegration; /*!< \brief r-derivatives of the Lagrangian basis functions in the integration points. */ - vector dsLagBasisIntegration; /*!< \brief s-derivatives of the Lagrangian basis functions in the integration points. */ - vector dtLagBasisIntegration; /*!< \brief t-derivatives of the Lagrangian basis functions in the integration points. */ - - vector matVandermondeInv; /*!< \brief Inverse matrix of Vandermonde matrix in the DOFs for this standard element. - This data is needed for the computation of shock sensing. */ - - vector matBasisIntegration; /*!< \brief Matrix of lagBasisIntegration, drLagBasisIntegration, dsLagBasisIntegration - and dtLagBasisIntegration combined for efficiency when using BLAS routines. */ - vector matDerBasisIntTrans; /*!< \brief Matrix of the transpose of the derivative part of matBasisIntegration. It is - stored such that the volume residual can be computed in one matrix multiplication. */ - vector matDerBasisSolDOFs; /*!< \brief Matrix of the derivatives of the Lagrangian basis functions in the solution - DOFs. Needed to compute the metric terms in the solution DOFs. */ - vector matDerBasisOwnDOFs; /*!< \brief Matrix of the derivatives of the Lagrangian basis functions in the owned - DOFs. This differs from matDerBasisSolDOFs when the grid DOFs and the - solution DOFs do not coincide. This data is needed for the computation - of the derivatives of the metric terms. */ - vector mat2ndDerBasisInt; /*!< \brief Matrix which contains all possible second derivatives of the basis functions - in the integration points. As such second derivatives can be computed - using one call to the BLAS routines. */ - - vector connFace0; /*!< \brief Local connectivity of face 0 of the element. The numbering of the DOFs is - such that the element is to the left of the face. */ - vector connFace1; /*!< \brief Local connectivity of face 1 of the element. The numbering of the DOFs is - such that the element is to the left of the face. */ + private: + unsigned short nPoly; /*!< \brief Polynomial degree of the element. */ + unsigned short nDOFs; /*!< \brief Number of DOFs of the element. */ + + unsigned short VTK_Type1; /*!< \brief VTK type for elements of type 1 in subConn1ForPlotting. */ + unsigned short VTK_Type2; /*!< \brief VTK type for elements of type 2 in subConn2ForPlotting. */ + + vector rDOFs; /*!< \brief r-location of the DOFs for this standard element. */ + vector sDOFs; /*!< \brief s-location of the DOFs for this standard element, if needed. */ + vector tDOFs; /*!< \brief t-location of the DOFs for this standard element, if needed. */ + + vector lagBasisIntegration; /*!< \brief Lagrangian basis functions in the integration points. */ + vector lagBasisIntegrationTrans; /*!< \brief Transpose of lagBasisIntegration. It is stored such that + in the ADER-DG predictor step the residual is obtained + by one matrix multiplication. */ + vector lagBasisSolDOFs; /*!< \brief Lagrangian basis functions in the solution DOFs. Only different + from 1 if the polynomial degree of the grid and solution differs. */ + + vector + drLagBasisIntegration; /*!< \brief r-derivatives of the Lagrangian basis functions in the integration points. */ + vector + dsLagBasisIntegration; /*!< \brief s-derivatives of the Lagrangian basis functions in the integration points. */ + vector + dtLagBasisIntegration; /*!< \brief t-derivatives of the Lagrangian basis functions in the integration points. */ + + vector matVandermondeInv; /*!< \brief Inverse matrix of Vandermonde matrix in the DOFs for this standard + element. This data is needed for the computation of shock sensing. */ + + vector + matBasisIntegration; /*!< \brief Matrix of lagBasisIntegration, drLagBasisIntegration, dsLagBasisIntegration + and dtLagBasisIntegration combined for efficiency when using BLAS routines. */ + vector matDerBasisIntTrans; /*!< \brief Matrix of the transpose of the derivative part of + matBasisIntegration. It is stored such that the volume residual can be + computed in one matrix multiplication. */ + vector matDerBasisSolDOFs; /*!< \brief Matrix of the derivatives of the Lagrangian basis functions in the + solution DOFs. Needed to compute the metric terms in the solution DOFs. */ + vector matDerBasisOwnDOFs; /*!< \brief Matrix of the derivatives of the Lagrangian basis functions in the + owned DOFs. This differs from matDerBasisSolDOFs when the grid DOFs and the + solution DOFs do not coincide. This data is needed for the + computation of the derivatives of the metric terms. */ + vector mat2ndDerBasisInt; /*!< \brief Matrix which contains all possible second derivatives of the basis + functions in the integration points. As such second derivatives can be + computed using one call to the BLAS routines. */ + + vector connFace0; /*!< \brief Local connectivity of face 0 of the element. The numbering of the DOFs + is such that the element is to the left of the face. */ + vector connFace1; /*!< \brief Local connectivity of face 1 of the element. The numbering of the DOFs + is such that the element is to the left of the face. */ vector connFace2; /*!< \brief Local connectivity of face 2 of the element, if present. The numbering of the DOFs is such that the element is to the left of the face. */ vector connFace3; /*!< \brief Local connectivity of face 3 of the element, if present. The numbering @@ -837,11 +728,11 @@ class CFEMStandardElement : public CFEMStandardElementBase { vector connFace5; /*!< \brief Local connectivity of face 5 of the element, if present. The numbering of the DOFs is such that the element is to the left of the face. */ - vector subConn1ForPlotting; /*!< \brief Local subconnectivity of element type 1 of the high order element. - Used for plotting. */ - vector subConn2ForPlotting; /*!< \brief Local subconnectivity of element type 2 of the high order element. - Used for plotting. */ -public: + vector subConn1ForPlotting; /*!< \brief Local subconnectivity of element type 1 of the high order + element. Used for plotting. */ + vector subConn2ForPlotting; /*!< \brief Local subconnectivity of element type 2 of the high order + element. Used for plotting. */ + public: /*! * \brief Alternative constructor. * \param[in] val_VTK_Type - Type of the element using the VTK convention. @@ -858,26 +749,24 @@ class CFEMStandardElement : public CFEMStandardElementBase { * \param[in] tLocSolDOFs - Default argument. If specified, it contains the parametric t location of the solution DOFs. */ - CFEMStandardElement(unsigned short val_VTK_Type, - unsigned short val_nPoly, - bool val_constJac, - CConfig *config, - unsigned short val_orderExact = 0, - const vector *rLocSolDOFs = nullptr, - const vector *sLocSolDOFs = nullptr, - const vector *tLocSolDOFs = nullptr); + CFEMStandardElement(unsigned short val_VTK_Type, unsigned short val_nPoly, bool val_constJac, CConfig* config, + unsigned short val_orderExact = 0, const vector* rLocSolDOFs = nullptr, + const vector* sLocSolDOFs = nullptr, const vector* tLocSolDOFs = nullptr); /*! - * \brief Copy constructor. - * \param[in] other - Object, whose data must be copied. - */ - CFEMStandardElement(const CFEMStandardElement &other) : CFEMStandardElementBase(other) {Copy(other);} + * \brief Copy constructor. + * \param[in] other - Object, whose data must be copied. + */ + CFEMStandardElement(const CFEMStandardElement& other) : CFEMStandardElementBase(other) { Copy(other); } /*! - * \brief Assignment operator. - * \param[in] other - Object, to which this object must be assigned. - * \return The current object, after the member variables were assigned the correct value. - */ - CFEMStandardElement& operator=(const CFEMStandardElement &other){Copy(other); return (*this);} + * \brief Assignment operator. + * \param[in] other - Object, to which this object must be assigned. + * \return The current object, after the member variables were assigned the correct value. + */ + CFEMStandardElement& operator=(const CFEMStandardElement& other) { + Copy(other); + return (*this); + } /*! * \brief Function, which computes the Lagrangian basis functions for the @@ -886,8 +775,7 @@ class CFEMStandardElement : public CFEMStandardElementBase { and derivatives must be computed. * \param[out] lagBasis - The values of the Lagrangian basis functions in parCoor. */ - void BasisFunctionsInPoint(const su2double *parCoor, - vector &lagBasis); + void BasisFunctionsInPoint(const su2double* parCoor, vector& lagBasis); /*! * \brief Function, which computes the Lagrangian basis functions and its derivatives for the given parametric coordinates. @@ -897,166 +785,169 @@ class CFEMStandardElement : public CFEMStandardElementBase { * \param[out] dLagBasis - The values of the derivatives of the basis functions in parCoor. */ - void BasisFunctionsAndDerivativesInPoint(const su2double *parCoor, - vector &lagBasis, - vector > &dLagBasis); + void BasisFunctionsAndDerivativesInPoint(const su2double* parCoor, vector& lagBasis, + vector >& dLagBasis); /*! - * \brief Function, which makes available the values of the basis functions in the integration points. - * \return The pointer to data, which stores the basis functions in the integration points. - */ - inline su2double* GetBasisFunctionsIntegration(void){return lagBasisIntegration.data();} + * \brief Function, which makes available the values of the basis functions in the integration points. + * \return The pointer to data, which stores the basis functions in the integration points. + */ + inline su2double* GetBasisFunctionsIntegration(void) { return lagBasisIntegration.data(); } /*! - * \brief Function, which makes available the transpose of the basis functions in the integration points. - * \return The pointer to data, which stores the transpose matrix of the basis functions. - */ - inline const su2double* GetBasisFunctionsIntegrationTrans(void) const {return lagBasisIntegrationTrans.data();} + * \brief Function, which makes available the transpose of the basis functions in the integration points. + * \return The pointer to data, which stores the transpose matrix of the basis functions. + */ + inline const su2double* GetBasisFunctionsIntegrationTrans(void) const { return lagBasisIntegrationTrans.data(); } /*! - * \brief Function, which makes available the values of the basis functions in the solution DOFs. - * \return The pointer to data, which stores the basis functions in the solution DOFs. - */ - inline const su2double* GetBasisFunctionsSolDOFs(void) const {return lagBasisSolDOFs.data();} + * \brief Function, which makes available the values of the basis functions in the solution DOFs. + * \return The pointer to data, which stores the basis functions in the solution DOFs. + */ + inline const su2double* GetBasisFunctionsSolDOFs(void) const { return lagBasisSolDOFs.data(); } /*! - * \brief Function, which makes available the r-derivatives of the basis functions in the integration points. - * \return The pointer to data, which stores the r-derivatives of the basis functions. - */ - inline su2double* GetDrBasisFunctionsIntegration(void){return drLagBasisIntegration.data();} + * \brief Function, which makes available the r-derivatives of the basis functions in the integration points. + * \return The pointer to data, which stores the r-derivatives of the basis functions. + */ + inline su2double* GetDrBasisFunctionsIntegration(void) { return drLagBasisIntegration.data(); } /*! - * \brief Function, which makes available the s-derivatives of the basis functions in the integration points. - * \return The pointer to data, which stores the s-derivatives of the basis functions. - */ - inline su2double* GetDsBasisFunctionsIntegration(void){return dsLagBasisIntegration.data();} + * \brief Function, which makes available the s-derivatives of the basis functions in the integration points. + * \return The pointer to data, which stores the s-derivatives of the basis functions. + */ + inline su2double* GetDsBasisFunctionsIntegration(void) { return dsLagBasisIntegration.data(); } /*! - * \brief Function, which makes available the t-derivatives of the basis functions in the integration points. - * \return The pointer to data, which stores the t-derivatives of the basis functions. - */ - inline su2double* GetDtBasisFunctionsIntegration(void){return dtLagBasisIntegration.data();} + * \brief Function, which makes available the t-derivatives of the basis functions in the integration points. + * \return The pointer to data, which stores the t-derivatives of the basis functions. + */ + inline su2double* GetDtBasisFunctionsIntegration(void) { return dtLagBasisIntegration.data(); } /*! - * \brief Function, which makes available the matrix storage of the inverse of Vandermonde matrix of solution DOFs. - * \return The pointer to matVandermondeInv. - */ - inline const su2double* GetMatVandermondeInv(void) const {return matVandermondeInv.data();} + * \brief Function, which makes available the matrix storage of the inverse of Vandermonde matrix of solution DOFs. + * \return The pointer to matVandermondeInv. + */ + inline const su2double* GetMatVandermondeInv(void) const { return matVandermondeInv.data(); } /*! - * \brief Function, which makes available the matrix storage of the basis functions in the integration points. - * \return The pointer to matBasisIntegration. - */ - inline const su2double* GetMatBasisFunctionsIntegration(void) const {return matBasisIntegration.data();} + * \brief Function, which makes available the matrix storage of the basis functions in the integration points. + * \return The pointer to matBasisIntegration. + */ + inline const su2double* GetMatBasisFunctionsIntegration(void) const { return matBasisIntegration.data(); } /*! - * \brief Function, which makes available the transpose matrix of the derivative of the basis functions in the integration points. - * \return The pointer to matDerBasisIntTrans; - */ - inline const su2double* GetDerMatBasisFunctionsIntTrans(void) const {return matDerBasisIntTrans.data();} + * \brief Function, which makes available the transpose matrix of the derivative of the basis functions in the + * integration points. \return The pointer to matDerBasisIntTrans; + */ + inline const su2double* GetDerMatBasisFunctionsIntTrans(void) const { return matDerBasisIntTrans.data(); } /*! - * \brief Function, which makes available the matrix storage of the derivative of the basis functions in the own DOFs. - * \return The pointer to matDerBasisOwnDOFs. - */ - inline const su2double *GetMatDerBasisFunctionsOwnDOFs(void) const {return matDerBasisOwnDOFs.data();} + * \brief Function, which makes available the matrix storage of the derivative of the basis functions in the own DOFs. + * \return The pointer to matDerBasisOwnDOFs. + */ + inline const su2double* GetMatDerBasisFunctionsOwnDOFs(void) const { return matDerBasisOwnDOFs.data(); } /*! - * \brief Function, which makes available the matrix storage of the derivative of the basis functions in the solution DOFs. - * \return The pointer to matDerBasisSolDOFs. - */ - inline const su2double *GetMatDerBasisFunctionsSolDOFs(void) const {return matDerBasisSolDOFs.data();} + * \brief Function, which makes available the matrix storage of the derivative of the basis functions in the solution + * DOFs. \return The pointer to matDerBasisSolDOFs. + */ + inline const su2double* GetMatDerBasisFunctionsSolDOFs(void) const { return matDerBasisSolDOFs.data(); } /*! * \brief Function, which makes available the matrix storage of the second derivativex of the basis functions in the integration points. * \return The pointer to mat2ndDerBasisInt. */ - inline const su2double *GetMat2ndDerBasisFunctionsInt(void) const {return mat2ndDerBasisInt.data();} + inline const su2double* GetMat2ndDerBasisFunctionsInt(void) const { return mat2ndDerBasisInt.data(); } /*! - * \brief Function, which makes available the connectivity of face 0. - * \return The pointer to data, which stores the connectivity of face 0. - */ - inline unsigned short *GetConnFace0(void) {return connFace0.data();} + * \brief Function, which makes available the connectivity of face 0. + * \return The pointer to data, which stores the connectivity of face 0. + */ + inline unsigned short* GetConnFace0(void) { return connFace0.data(); } /*! - * \brief Function, which makes available the connectivity of face 1. - * \return The pointer to data, which stores the connectivity of face 1. - */ - inline unsigned short *GetConnFace1(void) {return connFace1.data();} + * \brief Function, which makes available the connectivity of face 1. + * \return The pointer to data, which stores the connectivity of face 1. + */ + inline unsigned short* GetConnFace1(void) { return connFace1.data(); } /*! - * \brief Function, which makes available the connectivity of face 2. - * \return The pointer to data, which stores the connectivity of face 2. - */ - inline unsigned short *GetConnFace2(void) {return connFace2.data();} + * \brief Function, which makes available the connectivity of face 2. + * \return The pointer to data, which stores the connectivity of face 2. + */ + inline unsigned short* GetConnFace2(void) { return connFace2.data(); } /*! - * \brief Function, which makes available the connectivity of face 3. - * \return The pointer to data, which stores the connectivity of face 3. - */ - inline unsigned short *GetConnFace3(void) {return connFace3.data();} + * \brief Function, which makes available the connectivity of face 3. + * \return The pointer to data, which stores the connectivity of face 3. + */ + inline unsigned short* GetConnFace3(void) { return connFace3.data(); } /*! - * \brief Function, which makes available the connectivity of face 4. - * \return The pointer to data, which stores the connectivity of face 4. - */ - inline unsigned short *GetConnFace4(void) {return connFace4.data();} + * \brief Function, which makes available the connectivity of face 4. + * \return The pointer to data, which stores the connectivity of face 4. + */ + inline unsigned short* GetConnFace4(void) { return connFace4.data(); } /*! - * \brief Function, which makes available the connectivity of face 5. - * \return The pointer to data, which stores the connectivity of face 5. - */ - inline unsigned short *GetConnFace5(void) {return connFace5.data();} + * \brief Function, which makes available the connectivity of face 5. + * \return The pointer to data, which stores the connectivity of face 5. + */ + inline unsigned short* GetConnFace5(void) { return connFace5.data(); } /*! - * \brief Function, which makes available the number of DOFs for this standard element. - * \return The number of DOFs of this standard element. - */ - inline unsigned short GetNDOFs(void) const {return nDOFs;} + * \brief Function, which makes available the number of DOFs for this standard element. + * \return The number of DOFs of this standard element. + */ + inline unsigned short GetNDOFs(void) const { return nDOFs; } /*! - * \brief Function, which makes available the polynomial degree for this standard element. - * \return The polynomial degree of this standard element. - */ - inline unsigned short GetNPoly(void) const {return nPoly;} + * \brief Function, which makes available the polynomial degree for this standard element. + * \return The polynomial degree of this standard element. + */ + inline unsigned short GetNPoly(void) const { return nPoly; } /*! * \brief Function, which makes available the type of the element in subConn1ForPlotting. * \return The type of the elements in subConn1ForPlotting using the VTK convention. */ - inline unsigned short GetVTK_Type1(void) const {return VTK_Type1;} + inline unsigned short GetVTK_Type1(void) const { return VTK_Type1; } /*! * \brief Function, which makes available the number of sub-elements of type 1 for plotting. * \return The number of sub-elements of type 1 for plotting. */ - inline unsigned short GetNSubElemsType1(void) const {return subConn1ForPlotting.size()/GetNDOFsPerSubElem(GetVTK_Type1());} + inline unsigned short GetNSubElemsType1(void) const { + return subConn1ForPlotting.size() / GetNDOFsPerSubElem(GetVTK_Type1()); + } /*! * \brief Function, which makes available the the connectivity of the linear elements of type 1 as a const pointer. * \return The pointer to the local connectivity of the linear elements of type 1. */ - inline const unsigned short *GetSubConnType1(void) const {return subConn1ForPlotting.data();} + inline const unsigned short* GetSubConnType1(void) const { return subConn1ForPlotting.data(); } /*! * \brief Function, which makes available the type of the element in subConn2ForPlotting. * \return The type of the elements in subConn2ForPlotting using the VTK convention. */ - inline unsigned short GetVTK_Type2(void) const {return VTK_Type2;} + inline unsigned short GetVTK_Type2(void) const { return VTK_Type2; } /*! * \brief Function, which makes available the number of sub-elements of type 2 for plotting. * \return The number of sub-elements of type 2 for plotting. */ - inline unsigned short GetNSubElemsType2(void) const {return subConn2ForPlotting.size()/GetNDOFsPerSubElem(GetVTK_Type2());} + inline unsigned short GetNSubElemsType2(void) const { + return subConn2ForPlotting.size() / GetNDOFsPerSubElem(GetVTK_Type2()); + } /*! * \brief Function, which makes available the the connectivity of the linear elements of type 2 as a const pointer. * \return The pointer to the local connectivity of the linear elements of type 2. */ - inline const unsigned short *GetSubConnType2(void) const {return subConn2ForPlotting.data();} + inline const unsigned short* GetSubConnType2(void) const { return subConn2ForPlotting.data(); } /*! * \brief Function, which makes available the number of DOFs of a linear element, used for plotting. @@ -1069,41 +960,39 @@ class CFEMStandardElement : public CFEMStandardElementBase { const pointer to the vector. * \return The address of the vector, which stores the r-location of the DOFs. */ - inline const vector *GetRDOFs(void) const {return &rDOFs;} + inline const vector* GetRDOFs(void) const { return &rDOFs; } /*! * \brief Function, which makes available the s-location of the DOFs as a const pointer to the vector. * \return The address of the vector, which stores the s-location of the DOFs. */ - inline const vector *GetSDOFs(void) const {return &sDOFs;} + inline const vector* GetSDOFs(void) const { return &sDOFs; } /*! * \brief Function, which makes available the t-location of the DOFs as a const pointer to the vector. * \return The address of the vector, which stores the t-location of the DOFs. */ - inline const vector *GetTDOFs(void) const {return &tDOFs;} + inline const vector* GetTDOFs(void) const { return &tDOFs; } /*! - * \brief Function, which checks if the function arguments correspond to this standard element. - * \param[in] val_VTK_Type - Type of the element using the VTK convention. - * \param[in] val_nPoly - Polynomial degree of the element. - * \param[in] val_constJac - Whether or not the Jacobians are constant. - * \return Whether or not the function arguments correspond to this standard element. - */ - bool SameStandardElement(unsigned short val_VTK_Type, - unsigned short val_nPoly, - bool val_constJac); + * \brief Function, which checks if the function arguments correspond to this standard element. + * \param[in] val_VTK_Type - Type of the element using the VTK convention. + * \param[in] val_nPoly - Polynomial degree of the element. + * \param[in] val_constJac - Whether or not the Jacobians are constant. + * \return Whether or not the function arguments correspond to this standard element. + */ + bool SameStandardElement(unsigned short val_VTK_Type, unsigned short val_nPoly, bool val_constJac); /*! * \brief Function, which estimates the amount of work for an element of this type. This information is used to determine a well balanced partition. * \param[in] config - Object, which contains the input parameters. */ - su2double WorkEstimateMetis(CConfig *config); + su2double WorkEstimateMetis(CConfig* config); -private: + private: /*! * \brief Function, which changes the given quadrilateral connectivity, such that the direction coincides with the direction corresponding to corner vertices vert0, vert1, vert2, vert3. @@ -1113,11 +1002,8 @@ class CFEMStandardElement : public CFEMStandardElementBase { * \param[in] vert2 - Corner vertex 2 of the desired sequence. * \param[in] vert3 - Corner vertex 3 of the desired sequence. */ - void ChangeDirectionQuadConn(vector &connQuad, - unsigned short vert0, - unsigned short vert1, - unsigned short vert2, - unsigned short vert3) const; + void ChangeDirectionQuadConn(vector& connQuad, unsigned short vert0, unsigned short vert1, + unsigned short vert2, unsigned short vert3) const; /*! * \brief Function, which changes the given triangular connectivity, such that the direction coincides @@ -1127,16 +1013,14 @@ class CFEMStandardElement : public CFEMStandardElementBase { * \param[in] vert1 - Corner vertex 1 of the desired sequence. * \param[in] vert2 - Corner vertex 2 of the desired sequence. */ - void ChangeDirectionTriangleConn(vector &connTriangle, - unsigned short vert0, - unsigned short vert1, - unsigned short vert2) const; + void ChangeDirectionTriangleConn(vector& connTriangle, unsigned short vert0, unsigned short vert1, + unsigned short vert2) const; /*! - * \brief Function, which copies the data of the given object into the current object. - * \param[in] other - Object, whose data is copied. - */ - void Copy(const CFEMStandardElement &other); + * \brief Function, which copies the data of the given object into the current object. + * \param[in] other - Object, whose data is copied. + */ + void Copy(const CFEMStandardElement& other); /*! * \brief Function, which creates the basis functions and the matrix containing @@ -1150,45 +1034,42 @@ class CFEMStandardElement : public CFEMStandardElementBase { * \param[out] matDerBasis - Matrix to store the derivatives of the basis functions. */ - void CreateBasisFunctionsAndMatrixDerivatives(const vector &rLoc, - const vector &sLoc, - const vector &tLoc, - vector &matVandermondeInv, - vector &lagBasis, - vector &matDerBasis); + void CreateBasisFunctionsAndMatrixDerivatives(const vector& rLoc, const vector& sLoc, + const vector& tLoc, vector& matVandermondeInv, + vector& lagBasis, vector& matDerBasis); /*! - * \brief Function, which creates all the data for a line element. - */ + * \brief Function, which creates all the data for a line element. + */ void DataStandardLine(void); /*! - * \brief Function, which creates all the data for a triangular element. - */ + * \brief Function, which creates all the data for a triangular element. + */ void DataStandardTriangle(void); /*! - * \brief Function, which creates all the data for a quadrilateral element. - */ + * \brief Function, which creates all the data for a quadrilateral element. + */ void DataStandardQuadrilateral(void); /*! - * \brief Function, which creates all the data for a tetrahedral element. - */ + * \brief Function, which creates all the data for a tetrahedral element. + */ void DataStandardTetrahedron(void); /*! - * \brief Function, which creates all the data for a pyramid element. - */ + * \brief Function, which creates all the data for a pyramid element. + */ void DataStandardPyramid(void); /*! - * \brief Function, which creates all the data for a prism element. - */ + * \brief Function, which creates all the data for a prism element. + */ void DataStandardPrism(void); /*! - * \brief Function, which creates all the data for a hexahedral element. - */ + * \brief Function, which creates all the data for a hexahedral element. + */ void DataStandardHexahedron(void); /*! @@ -1223,9 +1104,9 @@ class CFEMStandardElement : public CFEMStandardElementBase { * \version 7.5.1 "Blackbird" */ class CFEMStandardInternalFace : public CFEMStandardElementBase { -private: - unsigned short nDOFsFaceSide0; /*!< \brief Number of DOFs on side 0 of the face. */ - unsigned short nDOFsFaceSide1; /*!< \brief Number of DOFs on side 1 of the face. */ + private: + unsigned short nDOFsFaceSide0; /*!< \brief Number of DOFs on side 0 of the face. */ + unsigned short nDOFsFaceSide1; /*!< \brief Number of DOFs on side 1 of the face. */ unsigned short nPolyElemSide0; /*!< \brief Polynomial degree of the element on side 0 of the face. */ unsigned short nPolyElemSide1; /*!< \brief Polynomial degree of the element on side 1 of the face. */ @@ -1234,20 +1115,20 @@ class CFEMStandardInternalFace : public CFEMStandardElementBase { unsigned short VTK_TypeElemSide0; /*!< \brief Type of the element on side 0 of the face using the VTK convention. */ unsigned short VTK_TypeElemSide1; /*!< \brief Type of the element on side 1 of the face using the VTK convention. */ - bool swapFaceInElementSide0; /*!< \brief Whether or not the connectivity of the face must - be swapped compared to the face of the corresponding - standard element on side 0 of the face. */ - bool swapFaceInElementSide1; /*!< \brief Whether or not the connectivity of the face must - be swapped compared to the face of the corresponding - standard element on side 1 of the face. */ + bool swapFaceInElementSide0; /*!< \brief Whether or not the connectivity of the face must + be swapped compared to the face of the corresponding + standard element on side 0 of the face. */ + bool swapFaceInElementSide1; /*!< \brief Whether or not the connectivity of the face must + be swapped compared to the face of the corresponding + standard element on side 1 of the face. */ - su2double penaltyConstantFace; /*!< \brief The constant of the penalty parameter of the face, - which is used in the viscous discretization. */ + su2double penaltyConstantFace; /*!< \brief The constant of the penalty parameter of the face, + which is used in the viscous discretization. */ - vector rDOFsFaceSide0; /*!< \brief r-location of the DOFs on side 0 of the face. */ - vector rDOFsFaceSide1; /*!< \brief r-location of the DOFs on side 1 of the face. */ - vector sDOFsFaceSide0; /*!< \brief s-location of the DOFs on side 0 of the face, if needed. */ - vector sDOFsFaceSide1; /*!< \brief s-location of the DOFs on side 1 of the face, if needed. */ + vector rDOFsFaceSide0; /*!< \brief r-location of the DOFs on side 0 of the face. */ + vector rDOFsFaceSide1; /*!< \brief r-location of the DOFs on side 1 of the face. */ + vector sDOFsFaceSide0; /*!< \brief s-location of the DOFs on side 0 of the face, if needed. */ + vector sDOFsFaceSide1; /*!< \brief s-location of the DOFs on side 1 of the face, if needed. */ vector lagBasisFaceIntegrationSide0; /*!< \brief Lagrangian basis functions in the integration points of side0 of the face. */ @@ -1279,20 +1160,22 @@ class CFEMStandardInternalFace : public CFEMStandardElementBase { vector dtLagBasisElemIntegrationSide1; /*!< \brief t-derivatives of the element Lagrangian basis functions of side 1 in the integration points. */ - vector matDerBasisElemIntegrationSide0; /*!< \brief Matrix of drLagBasisElemIntegrationSide0, dsLagBasisElemIntegrationSide0 - and dtLagBasisElemIntegrationSide0 combined for efficiency - when using BLAS routines. */ - vector matDerBasisElemIntegrationSide1; /*!< \brief Matrix of drLagBasisElemIntegrationSide1, dsLagBasisElemIntegrationSide1 - and dtLagBasisElemIntegrationSide1 combined for efficiency - when using BLAS routines. */ - - vector matDerBasisElemIntegrationTransposeSide0; /*!< \brief Transpose of matDerBasisElemIntegrationSide0, such that - the residuals of the symmetrizing terms can be computed - with a single matrix multiplication. */ - vector matDerBasisElemIntegrationTransposeSide1; /*!< \brief Transpose of matDerBasisElemIntegrationSide1, such that - the residuals of the symmetrizing terms can be computed - with a single matrix multiplication. */ -public: + vector + matDerBasisElemIntegrationSide0; /*!< \brief Matrix of drLagBasisElemIntegrationSide0, + dsLagBasisElemIntegrationSide0 and dtLagBasisElemIntegrationSide0 combined for + efficiency when using BLAS routines. */ + vector + matDerBasisElemIntegrationSide1; /*!< \brief Matrix of drLagBasisElemIntegrationSide1, + dsLagBasisElemIntegrationSide1 and dtLagBasisElemIntegrationSide1 combined for + efficiency when using BLAS routines. */ + + vector matDerBasisElemIntegrationTransposeSide0; /*!< \brief Transpose of matDerBasisElemIntegrationSide0, + such that the residuals of the symmetrizing terms can + be computed with a single matrix multiplication. */ + vector matDerBasisElemIntegrationTransposeSide1; /*!< \brief Transpose of matDerBasisElemIntegrationSide1, + such that the residuals of the symmetrizing terms can + be computed with a single matrix multiplication. */ + public: /*! * \brief Alternative constructor. * \param[in] val_VTK_TypeFace - The type of the face using the VTK convention. @@ -1316,84 +1199,85 @@ class CFEMStandardInternalFace : public CFEMStandardElementBase { order of the polynomials that must be integrated exactly by the integration rule. */ - CFEMStandardInternalFace(unsigned short val_VTK_TypeFace, - unsigned short val_VTK_TypeSide0, - unsigned short val_nPolySide0, - unsigned short val_VTK_TypeSide1, - unsigned short val_nPolySide1, - bool val_constJac, - bool val_swapFaceInElementSide0, - bool val_swapFaceInElementSide1, - CConfig *config, - unsigned short val_orderExact = 0); + CFEMStandardInternalFace(unsigned short val_VTK_TypeFace, unsigned short val_VTK_TypeSide0, + unsigned short val_nPolySide0, unsigned short val_VTK_TypeSide1, + unsigned short val_nPolySide1, bool val_constJac, bool val_swapFaceInElementSide0, + bool val_swapFaceInElementSide1, CConfig* config, unsigned short val_orderExact = 0); /*! - * \brief Copy constructor. - * \param[in] other - Object, whose data must be copied. - */ - CFEMStandardInternalFace(const CFEMStandardInternalFace &other) : CFEMStandardElementBase(other) {Copy(other);} + * \brief Copy constructor. + * \param[in] other - Object, whose data must be copied. + */ + CFEMStandardInternalFace(const CFEMStandardInternalFace& other) : CFEMStandardElementBase(other) { Copy(other); } /*! - * \brief Assignment operator. - * \param[in] other - Object, to which this object must be assigned. - * \return The current object, after the member variables were assigned the correct value. - */ - CFEMStandardInternalFace& operator=(const CFEMStandardInternalFace &other){Copy(other); return (*this);} + * \brief Assignment operator. + * \param[in] other - Object, to which this object must be assigned. + * \return The current object, after the member variables were assigned the correct value. + */ + CFEMStandardInternalFace& operator=(const CFEMStandardInternalFace& other) { + Copy(other); + return (*this); + } /*! * \brief Function, which makes available the r-derivatives of the elements basis functions of side 0 in the integration points. * \return The pointer to data, which stores this information. */ - inline su2double *GetDrBasisElemIntegrationSide0(void) {return drLagBasisElemIntegrationSide0.data();} + inline su2double* GetDrBasisElemIntegrationSide0(void) { return drLagBasisElemIntegrationSide0.data(); } /*! * \brief Function, which makes available the r-derivatives of the elements basis functions of side 1 in the integration points. * \return The pointer to data, which stores this information. */ - inline su2double *GetDrBasisElemIntegrationSide1(void) {return drLagBasisElemIntegrationSide1.data();} + inline su2double* GetDrBasisElemIntegrationSide1(void) { return drLagBasisElemIntegrationSide1.data(); } /*! * \brief Function, which makes available the s-derivatives of the elements basis functions of side 0 in the integration points. * \return The pointer to data, which stores this information. */ - inline su2double *GetDsBasisElemIntegrationSide0(void) {return dsLagBasisElemIntegrationSide0.data();} + inline su2double* GetDsBasisElemIntegrationSide0(void) { return dsLagBasisElemIntegrationSide0.data(); } /*! * \brief Function, which makes available the s-derivatives of the elements basis functions of side 1 in the integration points. * \return The pointer to data, which stores this information. */ - inline su2double *GetDsBasisElemIntegrationSide1(void) {return dsLagBasisElemIntegrationSide1.data();} + inline su2double* GetDsBasisElemIntegrationSide1(void) { return dsLagBasisElemIntegrationSide1.data(); } /*! * \brief Function, which makes available the t-derivatives of the elements basis functions of side 0 in the integration points. * \return The pointer to data, which stores this information. */ - inline su2double *GetDtBasisElemIntegrationSide0(void) {return dtLagBasisElemIntegrationSide0.data();} + inline su2double* GetDtBasisElemIntegrationSide0(void) { return dtLagBasisElemIntegrationSide0.data(); } /*! * \brief Function, which makes available the t-derivatives of the elements basis functions of side 1 in the integration points. * \return The pointer to data, which stores this information. */ - inline su2double *GetDtBasisElemIntegrationSide1(void) {return dtLagBasisElemIntegrationSide1.data();} + inline su2double* GetDtBasisElemIntegrationSide1(void) { return dtLagBasisElemIntegrationSide1.data(); } /*! * \brief Function, which makes available the matrix with the derivatives of the element basis functions of side 0 in the integration points. * \return The const pointer to data, which stores this information. */ - inline const su2double* GetMatDerBasisElemIntegrationSide0(void) const {return matDerBasisElemIntegrationSide0.data();} + inline const su2double* GetMatDerBasisElemIntegrationSide0(void) const { + return matDerBasisElemIntegrationSide0.data(); + } /*! * \brief Function, which makes available the matrix with the derivatives of the element basis functions of side 1 in the integration points. * \return The const pointer to data, which stores this information. */ - inline const su2double* GetMatDerBasisElemIntegrationSide1(void) const {return matDerBasisElemIntegrationSide1.data();} + inline const su2double* GetMatDerBasisElemIntegrationSide1(void) const { + return matDerBasisElemIntegrationSide1.data(); + } /*! * \brief Function, which makes available the transpose of the matrix with @@ -1401,7 +1285,9 @@ class CFEMStandardInternalFace : public CFEMStandardElementBase { integration points. * \return The const pointer to data, which stores this information. */ - inline const su2double* GetMatDerBasisElemIntegrationTransposeSide0(void) const {return matDerBasisElemIntegrationTransposeSide0.data();} + inline const su2double* GetMatDerBasisElemIntegrationTransposeSide0(void) const { + return matDerBasisElemIntegrationTransposeSide0.data(); + } /*! * \brief Function, which makes available the transpose of the matrix with @@ -1409,95 +1295,101 @@ class CFEMStandardInternalFace : public CFEMStandardElementBase { integration points. * \return The const pointer to data, which stores this information. */ - inline const su2double* GetMatDerBasisElemIntegrationTransposeSide1(void) const {return matDerBasisElemIntegrationTransposeSide1.data();} + inline const su2double* GetMatDerBasisElemIntegrationTransposeSide1(void) const { + return matDerBasisElemIntegrationTransposeSide1.data(); + } /*! * \brief Function, which makes available the face basis functions of side 0 in the integration points. * \return The pointer to data, which stores this information. */ - inline const su2double* GetBasisFaceIntegrationSide0(void) const {return lagBasisFaceIntegrationSide0.data();} + inline const su2double* GetBasisFaceIntegrationSide0(void) const { return lagBasisFaceIntegrationSide0.data(); } /*! * \brief Function, which makes available the face basis functions of side 1 in the integration points. * \return The pointer to data, which stores this information. */ - inline const su2double* GetBasisFaceIntegrationSide1(void) const {return lagBasisFaceIntegrationSide1.data();} + inline const su2double* GetBasisFaceIntegrationSide1(void) const { return lagBasisFaceIntegrationSide1.data(); } /*! * \brief Function, which makes available transpose matrix of the face basis functions of side 0 in the integration points. * \return The pointer to data, which stores this information. */ - inline const su2double* GetBasisFaceIntegrationTransposeSide0(void) const {return lagBasisFaceIntegrationTransposeSide0.data();} + inline const su2double* GetBasisFaceIntegrationTransposeSide0(void) const { + return lagBasisFaceIntegrationTransposeSide0.data(); + } /*! * \brief Function, which makes available transpose matrix of the face basis functions of side 1 in the integration points. * \return The pointer to data, which stores this information. */ - inline const su2double* GetBasisFaceIntegrationTransposeSide1(void) const {return lagBasisFaceIntegrationTransposeSide1.data();} + inline const su2double* GetBasisFaceIntegrationTransposeSide1(void) const { + return lagBasisFaceIntegrationTransposeSide1.data(); + } /*! * \brief Function, which makes available the r-derivatives of the face basis functions of side 0 in the integration points. * \return The pointer to data, which stores this information. */ - inline su2double* GetDrBasisFaceIntegrationSide0(void) {return drLagBasisFaceIntegrationSide0.data();} + inline su2double* GetDrBasisFaceIntegrationSide0(void) { return drLagBasisFaceIntegrationSide0.data(); } /*! * \brief Function, which makes available the r-derivatives of the face basis functions of side 1 in the integration points. * \return The pointer to data, which stores this information. */ - inline su2double* GetDrBasisFaceIntegrationSide1(void) {return drLagBasisFaceIntegrationSide1.data();} + inline su2double* GetDrBasisFaceIntegrationSide1(void) { return drLagBasisFaceIntegrationSide1.data(); } /*! * \brief Function, which makes available the s-derivatives of the face basis functions of side 0 in the integration points. * \return The pointer to data, which stores this information. */ - inline su2double* GetDsBasisFaceIntegrationSide0(void) {return dsLagBasisFaceIntegrationSide0.data();} + inline su2double* GetDsBasisFaceIntegrationSide0(void) { return dsLagBasisFaceIntegrationSide0.data(); } /*! * \brief Function, which makes available the s-derivatives of the face basis functions of side 1 in the integration points. * \return The pointer to data, which stores this information. */ - inline su2double* GetDsBasisFaceIntegrationSide1(void) {return dsLagBasisFaceIntegrationSide1.data();} + inline su2double* GetDsBasisFaceIntegrationSide1(void) { return dsLagBasisFaceIntegrationSide1.data(); } /*! * \brief Function, which makes available the number of DOFs of the element on side 0 of the face. * \return The number of DOFs of the element on side 0. */ - inline unsigned short GetNDOFsElemSide0(void) const {return nDOFsElemSide0;} + inline unsigned short GetNDOFsElemSide0(void) const { return nDOFsElemSide0; } /*! * \brief Function, which makes available the number of DOFs of the element on side 1 of the face. * \return The number of DOFs on side 1. */ - inline unsigned short GetNDOFsElemSide1(void) const {return nDOFsElemSide1;} + inline unsigned short GetNDOFsElemSide1(void) const { return nDOFsElemSide1; } /*! - * \brief Function, which makes available the number of DOFs on side 0 of the face. - * \return The number of DOFs on side 0. - */ - inline unsigned short GetNDOFsFaceSide0(void) const {return nDOFsFaceSide0;} + * \brief Function, which makes available the number of DOFs on side 0 of the face. + * \return The number of DOFs on side 0. + */ + inline unsigned short GetNDOFsFaceSide0(void) const { return nDOFsFaceSide0; } /*! - * \brief Function, which makes available the number of DOFs on side 1 of the face. - * \return The number of DOFs on side 1. - */ - inline unsigned short GetNDOFsFaceSide1(void) const {return nDOFsFaceSide1;} + * \brief Function, which makes available the number of DOFs on side 1 of the face. + * \return The number of DOFs on side 1. + */ + inline unsigned short GetNDOFsFaceSide1(void) const { return nDOFsFaceSide1; } /*! - * \brief Function, which makes available the penalty constant for this standard face. - * \return The penalty constant. - */ - inline su2double GetPenaltyConstant(void) const {return penaltyConstantFace;} + * \brief Function, which makes available the penalty constant for this standard face. + * \return The penalty constant. + */ + inline su2double GetPenaltyConstant(void) const { return penaltyConstantFace; } /*! * \brief Function, which checks if the function arguments correspond to this standard face. @@ -1518,28 +1410,24 @@ class CFEMStandardInternalFace : public CFEMStandardElementBase { be swapped w.r.t. the connectivity of face of the element on side 1. */ - bool SameStandardMatchingFace(unsigned short val_VTK_TypeFace, - bool val_constJac, - unsigned short val_VTK_TypeSide0, - unsigned short val_nPolySide0, - unsigned short val_VTK_TypeSide1, - unsigned short val_nPolySide1, - bool val_swapFaceInElementSide0, - bool val_swapFaceInElementSide1); + bool SameStandardMatchingFace(unsigned short val_VTK_TypeFace, bool val_constJac, unsigned short val_VTK_TypeSide0, + unsigned short val_nPolySide0, unsigned short val_VTK_TypeSide1, + unsigned short val_nPolySide1, bool val_swapFaceInElementSide0, + bool val_swapFaceInElementSide1); /*! * \brief Function, which estimates the amount of work for an element of this type. This information is used to determine a well balanced partition. * \param[in] config - Object, which contains the input parameters. */ - su2double WorkEstimateMetis(CConfig *config); + su2double WorkEstimateMetis(CConfig* config); -private: + private: /*! - * \brief Function, which copies the data of the given object into the current object. - * \param[in] other - Object, whose data is copied. - */ - void Copy(const CFEMStandardInternalFace &other); + * \brief Function, which copies the data of the given object into the current object. + * \param[in] other - Object, whose data is copied. + */ + void Copy(const CFEMStandardInternalFace& other); }; /*! @@ -1549,21 +1437,21 @@ class CFEMStandardInternalFace : public CFEMStandardElementBase { * \version 7.5.1 "Blackbird" */ class CFEMStandardBoundaryFace : public CFEMStandardElementBase { -private: - unsigned short nDOFsFace; /*!< \brief Number of DOFs of the face. */ + private: + unsigned short nDOFsFace; /*!< \brief Number of DOFs of the face. */ unsigned short nPolyElem; /*!< \brief Polynomial degree of the element adjacent to the face. */ unsigned short nDOFsElem; /*!< \brief Number of DOFs of the element adjacent element to the face. */ unsigned short VTK_TypeElem; /*!< \brief Type of the element adjacent to the face using the VTK convention. */ - bool swapFaceInElement; /*!< \brief Whether or not the connectivity of the face must be swapped compared - to the face of the corresponding standard element adjacent to the face. */ + bool swapFaceInElement; /*!< \brief Whether or not the connectivity of the face must be swapped compared + to the face of the corresponding standard element adjacent to the face. */ - su2double penaltyConstantFace; /*!< \brief The constant of the penalty parameter of the face, - which is used in the viscous discretization. */ + su2double penaltyConstantFace; /*!< \brief The constant of the penalty parameter of the face, + which is used in the viscous discretization. */ - vector rDOFsFace; /*!< \brief r-location of the DOFs of the face. */ - vector sDOFsFace; /*!< \brief s-location of the DOFs of the face, if needed. */ + vector rDOFsFace; /*!< \brief r-location of the DOFs of the face. */ + vector sDOFsFace; /*!< \brief s-location of the DOFs of the face, if needed. */ vector lagBasisFaceIntegration; /*!< \brief Lagrangian basis functions in the integration points of the face. */ @@ -1581,18 +1469,17 @@ class CFEMStandardBoundaryFace : public CFEMStandardElementBase { vector dtLagBasisElemIntegration; /*!< \brief t-derivatives of the Lagrangian basis functions in the integration points of the element adjacent to the face. */ - vector matDerBasisElemIntegration; /*!< \brief Matrix of drLagBasisElemIntegration, dsLagBasisElemIntegration - and dtLagBasisElemIntegration combined for efficiency - when using BLAS routines. */ + vector matDerBasisElemIntegration; /*!< \brief Matrix of drLagBasisElemIntegration, + dsLagBasisElemIntegration and dtLagBasisElemIntegration combined for + efficiency when using BLAS routines. */ vector matDerBasisElemIntegrationTranspose; /*!< \brief Transpose of matDerBasisElemIntegration, such that - the residuals of the symmetrizing terms can be computed - with a single matrix multiplication. */ - + the residuals of the symmetrizing terms can be + computed with a single matrix multiplication. */ vector subConnForPlotting; /*!< \brief Local subconnectivity of the high order element. Used for plotting. */ -public: + public: /*! * \brief Alternative constructor. * \param[in] val_VTK_TypeFace - The type of the face using the VTK convention. @@ -1605,54 +1492,53 @@ class CFEMStandardBoundaryFace : public CFEMStandardElementBase { * \param[in] val_orderExact - Default argument. If specified, it contains the order of the polynomials that must be integrated exactly by the integration rule. */ - CFEMStandardBoundaryFace(unsigned short val_VTK_TypeFace, - unsigned short val_VTK_TypeElem, - unsigned short val_nPolyElem, - bool val_constJac, - bool val_swapFaceInElement, - CConfig *config, + CFEMStandardBoundaryFace(unsigned short val_VTK_TypeFace, unsigned short val_VTK_TypeElem, + unsigned short val_nPolyElem, bool val_constJac, bool val_swapFaceInElement, CConfig* config, unsigned short val_orderExact = 0); /*! - * \brief Copy constructor. - * \param[in] other - Object, whose data must be copied. - */ - CFEMStandardBoundaryFace(const CFEMStandardBoundaryFace &other) : CFEMStandardElementBase(other) {Copy(other);} + * \brief Copy constructor. + * \param[in] other - Object, whose data must be copied. + */ + CFEMStandardBoundaryFace(const CFEMStandardBoundaryFace& other) : CFEMStandardElementBase(other) { Copy(other); } /*! - * \brief Assignment operator. - * \param[in] other - Object, to which this object must be assigned. - * \return The current object, after the member variables were assigned the correct value. - */ - CFEMStandardBoundaryFace& operator=(const CFEMStandardBoundaryFace &other){Copy(other); return (*this);} + * \brief Assignment operator. + * \param[in] other - Object, to which this object must be assigned. + * \return The current object, after the member variables were assigned the correct value. + */ + CFEMStandardBoundaryFace& operator=(const CFEMStandardBoundaryFace& other) { + Copy(other); + return (*this); + } /*! * \brief Function, which makes available the r-derivatives of the element basis functions in the integration points. * \return The pointer to data, which stores this information. */ - inline const su2double* GetDrBasisElemIntegration(void) const {return drLagBasisElemIntegration.data();} + inline const su2double* GetDrBasisElemIntegration(void) const { return drLagBasisElemIntegration.data(); } /*! * \brief Function, which makes available the s-derivatives of the element basis functions in the integration points. * \return The pointer to data, which stores this information. */ - inline const su2double* GetDsBasisElemIntegration(void) const {return dsLagBasisElemIntegration.data();} + inline const su2double* GetDsBasisElemIntegration(void) const { return dsLagBasisElemIntegration.data(); } /*! * \brief Function, which makes available the t-derivatives of the element basis functions in the integration points. * \return The pointer to data, which stores this information. */ - inline const su2double* GetDtBasisElemIntegration(void) const {return dtLagBasisElemIntegration.data();} + inline const su2double* GetDtBasisElemIntegration(void) const { return dtLagBasisElemIntegration.data(); } /*! * \brief Function, which makes available the matrix with the derivatives of the element basis functions in the integration points. * \return The pointer to data, which stores this information. */ - inline const su2double* GetMatDerBasisElemIntegration(void) const {return matDerBasisElemIntegration.data();} + inline const su2double* GetMatDerBasisElemIntegration(void) const { return matDerBasisElemIntegration.data(); } /*! * \brief Function, which makes available the transpose of the matrix with @@ -1660,55 +1546,59 @@ class CFEMStandardBoundaryFace : public CFEMStandardElementBase { points. * \return The const pointer to data, which stores this information. */ - inline const su2double* GetMatDerBasisElemIntegrationTranspose(void) const {return matDerBasisElemIntegrationTranspose.data();} + inline const su2double* GetMatDerBasisElemIntegrationTranspose(void) const { + return matDerBasisElemIntegrationTranspose.data(); + } /*! * \brief Function, which makes available the face basis functions in the integration points. * \return The pointer to data, which stores this information. */ - inline const su2double* GetBasisFaceIntegration(void) const {return lagBasisFaceIntegration.data();} + inline const su2double* GetBasisFaceIntegration(void) const { return lagBasisFaceIntegration.data(); } /*! * \brief Function, which makes available transpose matrix of the face basis functions in the integration points. * \return The pointer to data, which stores this information. */ - inline const su2double* GetBasisFaceIntegrationTranspose(void) const {return lagBasisFaceIntegrationTranspose.data();} + inline const su2double* GetBasisFaceIntegrationTranspose(void) const { + return lagBasisFaceIntegrationTranspose.data(); + } /*! * \brief Function, which makes available the r-derivatives of the face basis functions in the integration points. * \return The pointer to data, which stores this information. */ - inline const su2double* GetDrBasisFaceIntegration(void) const {return drLagBasisFaceIntegration.data();} + inline const su2double* GetDrBasisFaceIntegration(void) const { return drLagBasisFaceIntegration.data(); } /*! * \brief Function, which makes available the s-derivatives of the face basis functions in the integration points. * \return The pointer to data, which stores this information. */ - inline const su2double* GetDsBasisFaceIntegration(void) const {return dsLagBasisFaceIntegration.data();} + inline const su2double* GetDsBasisFaceIntegration(void) const { return dsLagBasisFaceIntegration.data(); } /*! * \brief Function, which makes available the number of DOFs of the adjacent element. * \return The number of DOFs of the element. */ - inline unsigned short GetNDOFsElem(void) const {return nDOFsElem;} + inline unsigned short GetNDOFsElem(void) const { return nDOFsElem; } /*! - * \brief Function, which makes available the number of DOFs of the face. - * \return The number of DOFs of the face. - */ - inline unsigned short GetNDOFsFace(void) const {return nDOFsFace;} + * \brief Function, which makes available the number of DOFs of the face. + * \return The number of DOFs of the face. + */ + inline unsigned short GetNDOFsFace(void) const { return nDOFsFace; } /*! * \brief Function, which makes available the number of linear subfaces used for plotting, among others. * \return The number of linear subfaces of the face. */ - inline unsigned short GetNSubFaces(void) const {return subConnForPlotting.size()/GetNDOFsPerSubFace();} + inline unsigned short GetNSubFaces(void) const { return subConnForPlotting.size() / GetNDOFsPerSubFace(); } /*! * \brief Function, which makes available the number of DOFs of a linear subface, used @@ -1718,17 +1608,17 @@ class CFEMStandardBoundaryFace : public CFEMStandardElementBase { unsigned short GetNDOFsPerSubFace(void) const; /*! - * \brief Function, which makes available the penalty constant for this standard face. - * \return The penalty constant. - */ - inline su2double GetPenaltyConstant(void) const {return penaltyConstantFace;} + * \brief Function, which makes available the penalty constant for this standard face. + * \return The penalty constant. + */ + inline su2double GetPenaltyConstant(void) const { return penaltyConstantFace; } /*! * \brief Function, which makes available the the connectivity of the linear subfaces as a const pointer. * \return The pointer to the local connectivity of the linear subfaces. */ - inline const unsigned short* GetSubFaceConn(void) const {return subConnForPlotting.data();} + inline const unsigned short* GetSubFaceConn(void) const { return subConnForPlotting.data(); } /*! * \brief Function, which checks if the function arguments correspond to this standard face. @@ -1739,17 +1629,14 @@ class CFEMStandardBoundaryFace : public CFEMStandardElementBase { * \param[in] val_swapFaceInElem - Whether or not the connectivity of the face must be swapped w.r.t. the connectivity of face of the adjacent element. */ - bool SameStandardBoundaryFace(unsigned short val_VTK_TypeFace, - bool val_constJac, - unsigned short val_VTK_TypeElem, - unsigned short val_nPolyElem, - bool val_swapFaceInElem); + bool SameStandardBoundaryFace(unsigned short val_VTK_TypeFace, bool val_constJac, unsigned short val_VTK_TypeElem, + unsigned short val_nPolyElem, bool val_swapFaceInElem); /*! * \brief Function, which estimates the amount of work for an element of this type. This information is used to determine a well balanced partition. * \param[in] config - Object, which contains the input parameters. */ - su2double WorkEstimateMetis(CConfig *config); + su2double WorkEstimateMetis(CConfig* config); /*! * \brief Function, which estimates the additional amount of work for an element @@ -1758,13 +1645,12 @@ class CFEMStandardBoundaryFace : public CFEMStandardElementBase { * \param[in] config - Object, which contains the input parameters. * \param[in] nPointsWF - Number of points to discretize the wall model. */ - su2double WorkEstimateMetisWallFunctions(CConfig *config, - const unsigned short nPointsWF); + su2double WorkEstimateMetisWallFunctions(CConfig* config, const unsigned short nPointsWF); -private: + private: /*! - * \brief Function, which copies the data of the given object into the current object. - * \param[in] other - Object, whose data is copied. - */ - void Copy(const CFEMStandardBoundaryFace &other); + * \brief Function, which copies the data of the given object into the current object. + * \param[in] other - Object, whose data is copied. + */ + void Copy(const CFEMStandardBoundaryFace& other); }; diff --git a/Common/include/fem/geometry_structure_fem_part.hpp b/Common/include/fem/geometry_structure_fem_part.hpp index 332d66d3560..0791d9bfe0b 100644 --- a/Common/include/fem/geometry_structure_fem_part.hpp +++ b/Common/include/fem/geometry_structure_fem_part.hpp @@ -37,19 +37,17 @@ * \brief Helper struct used to store two integral types as one entity. */ struct CUnsignedLong2T { - - unsigned long long0; /*!< \brief First integer to store in this class. */ - unsigned long long1; /*!< \brief Second integer to store in this class. */ + unsigned long long0; /*!< \brief First integer to store in this class. */ + unsigned long long1; /*!< \brief Second integer to store in this class. */ CUnsignedLong2T(unsigned long a = 0, unsigned long b = 0) : long0(a), long1(b) {} - inline bool operator<(const CUnsignedLong2T &other) const { - if(long0 != other.long0) - return (long0 < other.long0); + inline bool operator<(const CUnsignedLong2T& other) const { + if (long0 != other.long0) return (long0 < other.long0); return (long1 < other.long1); } - inline bool operator==(const CUnsignedLong2T &other) const { + inline bool operator==(const CUnsignedLong2T& other) const { return (long0 == other.long0) && (long1 == other.long1); } }; @@ -59,19 +57,17 @@ struct CUnsignedLong2T { * \brief Help struct used to store two integral types as one entity. */ struct CUnsignedShort2T { - - unsigned short short0; /*!< \brief First integer to store in this class. */ - unsigned short short1; /*!< \brief Second integer to store in this class. */ + unsigned short short0; /*!< \brief First integer to store in this class. */ + unsigned short short1; /*!< \brief Second integer to store in this class. */ CUnsignedShort2T(unsigned short a = 0, unsigned short b = 0) : short0(a), short1(b) {} - inline bool operator<(const CUnsignedShort2T &other) const { - if(short0 != other.short0) - return (short0 < other.short0); + inline bool operator<(const CUnsignedShort2T& other) const { + if (short0 != other.short0) return (short0 < other.short0); return (short1 < other.short1); } - inline bool operator==(const CUnsignedShort2T &other) const { + inline bool operator==(const CUnsignedShort2T& other) const { return (short0 == other.short0) && (short1 == other.short1); } }; @@ -82,16 +78,16 @@ struct CUnsignedShort2T { the faces of DG. It stores a face of an element. */ class CFaceOfElement { -public: + public: unsigned short nCornerPoints; /*!< \brief Number of corner points of the face. */ - unsigned long cornerPoints[4]; /*!< \brief Global ID's of ther corner points. */ - unsigned long elemID0, elemID1; /*!< \brief Element ID's to the left and right. */ + unsigned long cornerPoints[4]; /*!< \brief Global ID's of ther corner points. */ + unsigned long elemID0, elemID1; /*!< \brief Element ID's to the left and right. */ unsigned short nPolyGrid0, nPolyGrid1; /*!< \brief Polynomial degrees of the grid of the elements to the left and right. */ - unsigned short nPolySol0, nPolySol1; /*!< \brief Polynomial degrees of the solution of the elements + unsigned short nPolySol0, nPolySol1; /*!< \brief Polynomial degrees of the solution of the elements to the left and right. */ unsigned short nDOFsElem0, nDOFsElem1; /*!< \brief Number of DOFs of the elements to the left and right. */ - unsigned short elemType0, elemType1; /*!< \brief Type of the elements to the left and right. */ + unsigned short elemType0, elemType1; /*!< \brief Type of the elements to the left and right. */ unsigned short faceID0, faceID1; /*!< \brief The local face ID in the corresponding elements to the left and right of the face. */ unsigned short periodicIndex; /*!< \brief Periodic indicator of the face. A value of 0 means no @@ -110,35 +106,36 @@ class CFaceOfElement { /* Standard constructor and destructor. */ CFaceOfElement(); - ~CFaceOfElement(){} + ~CFaceOfElement() {} /* Alternative constructor to set the corner points. */ - CFaceOfElement(const unsigned short VTK_Type, - const unsigned short nPoly, - const unsigned long *Nodes); + CFaceOfElement(const unsigned short VTK_Type, const unsigned short nPoly, const unsigned long* Nodes); /* Copy constructor and assignment operator. */ - inline CFaceOfElement(const CFaceOfElement &other) { Copy(other); } + inline CFaceOfElement(const CFaceOfElement& other) { Copy(other); } - inline CFaceOfElement& operator=(const CFaceOfElement &other) { Copy(other); return (*this); } + inline CFaceOfElement& operator=(const CFaceOfElement& other) { + Copy(other); + return (*this); + } /* Less than operator. Needed for the sorting and searching. */ - bool operator<(const CFaceOfElement &other) const; + bool operator<(const CFaceOfElement& other) const; /* Equal operator. Needed for removing double entities. */ - bool operator ==(const CFaceOfElement &other) const; + bool operator==(const CFaceOfElement& other) const; /*--- Member function, which creates a unique numbering for the corner points. A sort in increasing order is OK for this purpose. ---*/ - inline void CreateUniqueNumbering(void) { std::sort(cornerPoints, cornerPoints+nCornerPoints); } + inline void CreateUniqueNumbering(void) { std::sort(cornerPoints, cornerPoints + nCornerPoints); } /*--- Member function, which creates a unique numbering for the corner points while the orientation is taken into account. ---*/ void CreateUniqueNumberingWithOrientation(void); -private: + private: /*--- Copy function, which copies the data of the given object into the current object. ---*/ - void Copy(const CFaceOfElement &other); + void Copy(const CFaceOfElement& other); }; /*! @@ -147,28 +144,29 @@ class CFaceOfElement { It stores a boundary element. */ class CBoundaryFace { -public: + public: unsigned short VTK_Type, nPolyGrid, nDOFsGrid; - unsigned long globalBoundElemID, domainElementID; - std::vector Nodes; + unsigned long globalBoundElemID, domainElementID; + std::vector Nodes; /* Standard constructor and destructor. Nothing to be done. */ - CBoundaryFace(){} - ~CBoundaryFace(){} + CBoundaryFace() {} + ~CBoundaryFace() {} /* Copy constructor and assignment operator. */ - inline CBoundaryFace(const CBoundaryFace &other) { Copy(other); } + inline CBoundaryFace(const CBoundaryFace& other) { Copy(other); } - inline CBoundaryFace& operator=(const CBoundaryFace &other) { Copy(other); return (*this); } + inline CBoundaryFace& operator=(const CBoundaryFace& other) { + Copy(other); + return (*this); + } /* Less than operator. Needed for the sorting. */ - inline bool operator<(const CBoundaryFace &other) const { - return (globalBoundElemID < other.globalBoundElemID); - } + inline bool operator<(const CBoundaryFace& other) const { return (globalBoundElemID < other.globalBoundElemID); } -private: + private: /*--- Copy function, which copies the data of the given object into the current object. ---*/ - void Copy(const CBoundaryFace &other); + void Copy(const CBoundaryFace& other); }; /*! @@ -176,35 +174,37 @@ class CBoundaryFace { * \brief Help class used to determine whether or not (periodic) faces match. */ class CMatchingFace { -public: - unsigned short nCornerPoints; /*!< \brief Number of corner points of the face. */ - unsigned short nDim; /*!< \brief Number of spatial dimensions. */ - unsigned short nPoly; /*!< \brief Polynomial degree of the face. */ - unsigned short nDOFsElem; /*!< \brief Number of DOFs of the relevant adjacent element. */ - unsigned short elemType; /*!< \brief Type of the adjacent element. */ - unsigned long elemID; /*!< \brief The relevant adjacent element ID. */ - su2double cornerCoor[4][3]; /*!< \brief Coordinates of the corner points of the face. */ - su2double tolForMatching; /*!< \brief Tolerance for this face for matching points. */ + public: + unsigned short nCornerPoints; /*!< \brief Number of corner points of the face. */ + unsigned short nDim; /*!< \brief Number of spatial dimensions. */ + unsigned short nPoly; /*!< \brief Polynomial degree of the face. */ + unsigned short nDOFsElem; /*!< \brief Number of DOFs of the relevant adjacent element. */ + unsigned short elemType; /*!< \brief Type of the adjacent element. */ + unsigned long elemID; /*!< \brief The relevant adjacent element ID. */ + su2double cornerCoor[4][3]; /*!< \brief Coordinates of the corner points of the face. */ + su2double tolForMatching; /*!< \brief Tolerance for this face for matching points. */ /* Standard constructor. */ CMatchingFace(); /* Destructor, nothing to be done. */ - ~CMatchingFace(){} + ~CMatchingFace() {} /* Copy constructor and assignment operator. */ - inline CMatchingFace(const CMatchingFace &other) { Copy(other); } + inline CMatchingFace(const CMatchingFace& other) { Copy(other); } - inline CMatchingFace& operator=(const CMatchingFace &other) { Copy(other); return (*this); } + inline CMatchingFace& operator=(const CMatchingFace& other) { + Copy(other); + return (*this); + } /* Less than operator. Needed for the sorting and searching. */ - bool operator<(const CMatchingFace &other) const; + bool operator<(const CMatchingFace& other) const; /*--- Member function, which sorts the coordinates of the face. ---*/ void SortFaceCoordinates(void); -private: + private: /*--- Copy function, which copies the data of the given object into the current object. ---*/ - void Copy(const CMatchingFace &other); + void Copy(const CMatchingFace& other); }; - diff --git a/Common/include/geometry/CDummyGeometry.hpp b/Common/include/geometry/CDummyGeometry.hpp index e5ec401057e..73028f7f957 100644 --- a/Common/include/geometry/CDummyGeometry.hpp +++ b/Common/include/geometry/CDummyGeometry.hpp @@ -36,14 +36,11 @@ * going through the time-consuming mesh initialization and paritioning. * \author T. Albring */ -class CDummyGeometry final : public CGeometry{ - -public: +class CDummyGeometry final : public CGeometry { + public: /*! * \brief Constructor of the class * \param[in] config - Definition of the particular problem. */ - CDummyGeometry(CConfig *config); - + CDummyGeometry(CConfig* config); }; - diff --git a/Common/include/geometry/CGeometry.hpp b/Common/include/geometry/CGeometry.hpp index c4e5067245c..dd5f936fe49 100644 --- a/Common/include/geometry/CGeometry.hpp +++ b/Common/include/geometry/CGeometry.hpp @@ -74,125 +74,141 @@ using namespace std; */ class CGeometry { protected: - enum : size_t {OMP_MIN_SIZE = 32}; /*!< \brief Chunk size for small loops. */ - enum : size_t {MAXNDIM = 3}; - - const int size{SINGLE_NODE}; /*!< \brief MPI Size. */ - const int rank{MASTER_NODE}; /*!< \brief MPI Rank. */ - - unsigned long nPoint{0}, /*!< \brief Number of points of the mesh. */ - nPointDomain{0}, /*!< \brief Number of real points of the mesh. */ - nPointGhost{0}, /*!< \brief Number of ghost points of the mesh. */ - Global_nPoint{0}, /*!< \brief Total number of nodes in a simulation across all processors (including halos). */ - Global_nPointDomain{0}, /*!< \brief Total number of nodes in a simulation across all processors (excluding halos). */ - nElem{0}, /*!< \brief Number of elements of the mesh. */ - Global_nElem{0}, /*!< \brief Total number of elements in a simulation across all processors (all types). */ - Global_nElemDomain{0}, /*!< \brief Total number of elements in a simulation across all processors (excluding halos). */ - nEdge{0}, /*!< \brief Number of edges of the mesh. */ - nFace{0}, /*!< \brief Number of faces of the mesh. */ - nelem_edge{0}, /*!< \brief Number of edges in the mesh. */ - Global_nelem_edge{0}, /*!< \brief Total number of edges in the mesh across all processors. */ - nelem_triangle{0}, /*!< \brief Number of triangles in the mesh. */ - Global_nelem_triangle{0}, /*!< \brief Total number of triangles in the mesh across all processors. */ - nelem_quad{0}, /*!< \brief Number of quadrangles in the mesh. */ - Global_nelem_quad{0}, /*!< \brief Total number of quadrangles in the mesh across all processors. */ - nelem_tetra{0}, /*!< \brief Number of tetrahedra in the mesh. */ - Global_nelem_tetra{0}, /*!< \brief Total number of tetrahedra in the mesh across all processors. */ - nelem_hexa{0}, /*!< \brief Number of hexahedra in the mesh. */ - Global_nelem_hexa{0}, /*!< \brief Total number of hexahedra in the mesh across all processors. */ - nelem_prism{0}, /*!< \brief Number of prisms in the mesh. */ - Global_nelem_prism{0}, /*!< \brief Total number of prisms in the mesh across all processors. */ - nelem_pyramid{0}, /*!< \brief Number of pyramids in the mesh. */ - Global_nelem_pyramid{0}, /*!< \brief Total number of pyramids in the mesh across all processors. */ - nelem_edge_bound{0}, /*!< \brief Number of edges on the mesh boundaries. */ - Global_nelem_edge_bound{0}, /*!< \brief Total number of edges on the mesh boundaries across all processors. */ - nelem_triangle_bound{0}, /*!< \brief Number of triangles on the mesh boundaries. */ - Global_nelem_triangle_bound{0}, /*!< \brief Total number of triangles on the mesh boundaries across all processors. */ - nelem_quad_bound{0}, /*!< \brief Number of quads on the mesh boundaries. */ - Global_nelem_quad_bound{0}, /*!< \brief Total number of quads on the mesh boundaries across all processors. */ - nNonconvexElements{0}; /*!< \brief Number of nonconvex elements in the mesh. */ - - unsigned short nDim{0}; /*!< \brief Number of dimension of the problem. */ - unsigned short nZone{0}; /*!< \brief Number of zones in the problem. */ - unsigned short nMarker{0}; /*!< \brief Number of different markers of the mesh. */ - unsigned short nCommLevel{0}; /*!< \brief Number of non-blocking communication levels. */ + enum : size_t { OMP_MIN_SIZE = 32 }; /*!< \brief Chunk size for small loops. */ + enum : size_t { MAXNDIM = 3 }; + + const int size{SINGLE_NODE}; /*!< \brief MPI Size. */ + const int rank{MASTER_NODE}; /*!< \brief MPI Rank. */ + + unsigned long nPoint{0}, /*!< \brief Number of points of the mesh. */ + nPointDomain{0}, /*!< \brief Number of real points of the mesh. */ + nPointGhost{0}, /*!< \brief Number of ghost points of the mesh. */ + Global_nPoint{0}, /*!< \brief Total number of nodes in a simulation across all processors (including halos). */ + Global_nPointDomain{ + 0}, /*!< \brief Total number of nodes in a simulation across all processors (excluding halos). */ + nElem{0}, /*!< \brief Number of elements of the mesh. */ + Global_nElem{0}, /*!< \brief Total number of elements in a simulation across all processors (all types). */ + Global_nElemDomain{ + 0}, /*!< \brief Total number of elements in a simulation across all processors (excluding halos). */ + nEdge{0}, /*!< \brief Number of edges of the mesh. */ + nFace{0}, /*!< \brief Number of faces of the mesh. */ + nelem_edge{0}, /*!< \brief Number of edges in the mesh. */ + Global_nelem_edge{0}, /*!< \brief Total number of edges in the mesh across all processors. */ + nelem_triangle{0}, /*!< \brief Number of triangles in the mesh. */ + Global_nelem_triangle{0}, /*!< \brief Total number of triangles in the mesh across all processors. */ + nelem_quad{0}, /*!< \brief Number of quadrangles in the mesh. */ + Global_nelem_quad{0}, /*!< \brief Total number of quadrangles in the mesh across all processors. */ + nelem_tetra{0}, /*!< \brief Number of tetrahedra in the mesh. */ + Global_nelem_tetra{0}, /*!< \brief Total number of tetrahedra in the mesh across all processors. */ + nelem_hexa{0}, /*!< \brief Number of hexahedra in the mesh. */ + Global_nelem_hexa{0}, /*!< \brief Total number of hexahedra in the mesh across all processors. */ + nelem_prism{0}, /*!< \brief Number of prisms in the mesh. */ + Global_nelem_prism{0}, /*!< \brief Total number of prisms in the mesh across all processors. */ + nelem_pyramid{0}, /*!< \brief Number of pyramids in the mesh. */ + Global_nelem_pyramid{0}, /*!< \brief Total number of pyramids in the mesh across all processors. */ + nelem_edge_bound{0}, /*!< \brief Number of edges on the mesh boundaries. */ + Global_nelem_edge_bound{0}, /*!< \brief Total number of edges on the mesh boundaries across all processors. */ + nelem_triangle_bound{0}, /*!< \brief Number of triangles on the mesh boundaries. */ + Global_nelem_triangle_bound{ + 0}, /*!< \brief Total number of triangles on the mesh boundaries across all processors. */ + nelem_quad_bound{0}, /*!< \brief Number of quads on the mesh boundaries. */ + Global_nelem_quad_bound{0}, /*!< \brief Total number of quads on the mesh boundaries across all processors. */ + nNonconvexElements{0}; /*!< \brief Number of nonconvex elements in the mesh. */ + + unsigned short nDim{0}; /*!< \brief Number of dimension of the problem. */ + unsigned short nZone{0}; /*!< \brief Number of zones in the problem. */ + unsigned short nMarker{0}; /*!< \brief Number of different markers of the mesh. */ + unsigned short nCommLevel{0}; /*!< \brief Number of non-blocking communication levels. */ unsigned short MGLevel{0}; /*!< \brief The mesh level index for the current geometry container. */ unsigned long Max_GlobalPoint{0}; /*!< \brief Greater global point in the domain local structure. */ /*--- Boundary information. ---*/ - short *Marker_All_SendRecv{nullptr}; /*!< \brief MPI Marker. */ - su2double **CustomBoundaryTemperature{nullptr}; - su2double **CustomBoundaryHeatFlux{nullptr}; + short* Marker_All_SendRecv{nullptr}; /*!< \brief MPI Marker. */ + su2double** CustomBoundaryTemperature{nullptr}; + su2double** CustomBoundaryHeatFlux{nullptr}; /*--- Create vectors and distribute the values among the different planes queues ---*/ - vector > Xcoord_plane; /*!< \brief Vector containing x coordinates of new points appearing on a single plane */ - vector > Ycoord_plane; /*!< \brief Vector containing y coordinates of new points appearing on a single plane */ - vector > Zcoord_plane; /*!< \brief Vector containing z coordinates of new points appearing on a single plane */ - vector > FaceArea_plane; /*!< \brief Vector containing area/volume associated with new points appearing on a single plane */ - vector > Plane_points; /*!< \brief Vector containing points appearing on a single plane */ + vector> + Xcoord_plane; /*!< \brief Vector containing x coordinates of new points appearing on a single plane */ + vector> + Ycoord_plane; /*!< \brief Vector containing y coordinates of new points appearing on a single plane */ + vector> + Zcoord_plane; /*!< \brief Vector containing z coordinates of new points appearing on a single plane */ + vector> FaceArea_plane; /*!< \brief Vector containing area/volume associated with new points + appearing on a single plane */ + vector> Plane_points; /*!< \brief Vector containing points appearing on a single plane */ - vector XCoordList; /*!< \brief Vector containing points appearing on a single plane */ + vector XCoordList; /*!< \brief Vector containing points appearing on a single plane */ #if defined(HAVE_MPI) && defined(HAVE_PARMETIS) - vector > adj_nodes; /*!< \brief Vector of vectors holding each node's adjacency during preparation for ParMETIS. */ - vector adjacency; /*!< \brief Local adjacency array to be input into ParMETIS for partitioning (idx_t is a ParMETIS type defined in their headers). */ - vector xadj; /*!< \brief Index array that points to the start of each node's adjacency in CSR format (needed to interpret the adjacency array). */ + vector> + adj_nodes; /*!< \brief Vector of vectors holding each node's adjacency during preparation for ParMETIS. */ + vector adjacency; /*!< \brief Local adjacency array to be input into ParMETIS for partitioning (idx_t is a + ParMETIS type defined in their headers). */ + vector xadj; /*!< \brief Index array that points to the start of each node's adjacency in CSR format (needed to + interpret the adjacency array). */ #endif /*--- Turbomachinery variables ---*/ - unsigned short *nSpanWiseSections{nullptr}; /*!< \brief Number of Span wise section for each turbo marker, indexed by inflow/outflow */ - unsigned short *nSpanSectionsByMarker{nullptr}; /*!< \brief Number of Span wise section for each turbo marker, indexed by marker. Needed for deallocation.*/ + unsigned short* nSpanWiseSections{ + nullptr}; /*!< \brief Number of Span wise section for each turbo marker, indexed by inflow/outflow */ + unsigned short* nSpanSectionsByMarker{nullptr}; /*!< \brief Number of Span wise section for each turbo marker, indexed + by marker. Needed for deallocation.*/ unsigned short nTurboPerf{0}; /*!< \brief Number of Span wise section for each turbo marker. */ - su2double **SpanWiseValue{nullptr}; /*!< \brief Span wise values for each turbo marker. */ - long **nVertexSpan{nullptr}; /*!< \brief number of vertexes for span wise section for each marker. */ - unsigned long **nTotVertexSpan{nullptr}; /*!< \brief number of vertexes at each span wise section for each marker. */ - unsigned long nVertexSpanMax[3] = {0}; /*!< \brief max number of vertexes for each span section for each marker flag. */ - su2double ***AverageTurboNormal{nullptr}; /*!< \brief Average boundary normal at each span wise section for each marker in the turbomachinery frame of reference.*/ - su2double ***AverageNormal{nullptr}; /*!< \brief Average boundary normal at each span wise section for each marker.*/ - su2double ***AverageGridVel{nullptr}; /*!< \brief Average boundary grid velocity at each span wise section for each marker.*/ - su2double **AverageTangGridVel{nullptr}; /*!< \brief Average tangential rotational speed at each span wise section for each marker.*/ - su2double **SpanArea{nullptr}; /*!< \brief Area at each span wise section for each marker.*/ - su2double **MaxAngularCoord{nullptr}; /*!< \brief Max angular pitch at each span wise section for each marker.*/ - su2double **MinAngularCoord{nullptr}; /*!< \brief Max angular pitch at each span wise section for each marker.*/ - su2double **MinRelAngularCoord{nullptr}; /*!< \brief Min relative angular coord at each span wise section for each marker.*/ - su2double **TurboRadius{nullptr}; /*!< \brief Radius at each span wise section for each marker.*/ - su2double **TangGridVelIn{nullptr}; - su2double **TangGridVelOut{nullptr}; /*!< \brief Average tangential rotational speed at each span wise section for each turbomachinery marker.*/ - su2double **SpanAreaIn{nullptr}; - su2double **SpanAreaOut{nullptr}; /*!< \brief Area at each span wise section for each turbomachinery marker.*/ - su2double **TurboRadiusIn{nullptr}; - su2double **TurboRadiusOut{nullptr}; /*!< \brief Radius at each span wise section for each turbomachinery marker*/ + su2double** SpanWiseValue{nullptr}; /*!< \brief Span wise values for each turbo marker. */ + long** nVertexSpan{nullptr}; /*!< \brief number of vertexes for span wise section for each marker. */ + unsigned long** nTotVertexSpan{nullptr}; /*!< \brief number of vertexes at each span wise section for each marker. */ + unsigned long nVertexSpanMax[3] = { + 0}; /*!< \brief max number of vertexes for each span section for each marker flag. */ + su2double*** AverageTurboNormal{nullptr}; /*!< \brief Average boundary normal at each span wise section for each + marker in the turbomachinery frame of reference.*/ + su2double*** AverageNormal{nullptr}; /*!< \brief Average boundary normal at each span wise section for each marker.*/ + su2double*** AverageGridVel{ + nullptr}; /*!< \brief Average boundary grid velocity at each span wise section for each marker.*/ + su2double** AverageTangGridVel{ + nullptr}; /*!< \brief Average tangential rotational speed at each span wise section for each marker.*/ + su2double** SpanArea{nullptr}; /*!< \brief Area at each span wise section for each marker.*/ + su2double** MaxAngularCoord{nullptr}; /*!< \brief Max angular pitch at each span wise section for each marker.*/ + su2double** MinAngularCoord{nullptr}; /*!< \brief Max angular pitch at each span wise section for each marker.*/ + su2double** MinRelAngularCoord{ + nullptr}; /*!< \brief Min relative angular coord at each span wise section for each marker.*/ + su2double** TurboRadius{nullptr}; /*!< \brief Radius at each span wise section for each marker.*/ + su2double** TangGridVelIn{nullptr}; + su2double** TangGridVelOut{nullptr}; /*!< \brief Average tangential rotational speed at each span wise section for + each turbomachinery marker.*/ + su2double** SpanAreaIn{nullptr}; + su2double** SpanAreaOut{nullptr}; /*!< \brief Area at each span wise section for each turbomachinery marker.*/ + su2double** TurboRadiusIn{nullptr}; + su2double** TurboRadiusOut{nullptr}; /*!< \brief Radius at each span wise section for each turbomachinery marker*/ /*--- Sparsity patterns associated with the geometry. ---*/ - CCompressedSparsePatternUL - finiteVolumeCSRFill0, /*!< \brief 0-fill FVM sparsity. */ - finiteVolumeCSRFillN, /*!< \brief N-fill FVM sparsity (e.g. for ILUn preconditioner). */ - finiteElementCSRFill0, /*!< \brief 0-fill FEM sparsity. */ - finiteElementCSRFillN; /*!< \brief N-fill FEM sparsity (e.g. for ILUn preconditioner). */ + CCompressedSparsePatternUL finiteVolumeCSRFill0, /*!< \brief 0-fill FVM sparsity. */ + finiteVolumeCSRFillN, /*!< \brief N-fill FVM sparsity (e.g. for ILUn preconditioner). */ + finiteElementCSRFill0, /*!< \brief 0-fill FEM sparsity. */ + finiteElementCSRFillN; /*!< \brief N-fill FEM sparsity (e.g. for ILUn preconditioner). */ - CEdgeToNonZeroMapUL edgeToCSRMap; /*!< \brief Map edges to CSR entries referenced by them (i,j) and (j,i). */ + CEdgeToNonZeroMapUL edgeToCSRMap; /*!< \brief Map edges to CSR entries referenced by them (i,j) and (j,i). */ /*--- Edge and element colorings. ---*/ - CCompressedSparsePatternUL - edgeColoring, /*!< \brief Edge coloring structure for thread-based parallelization. */ - elemColoring; /*!< \brief Element coloring structure for thread-based parallelization. */ - unsigned long edgeColorGroupSize{1}; /*!< \brief Size of the edge groups within each color. */ - unsigned long elemColorGroupSize{1}; /*!< \brief Size of the element groups within each color. */ + CCompressedSparsePatternUL edgeColoring, /*!< \brief Edge coloring structure for thread-based parallelization. */ + elemColoring; /*!< \brief Element coloring structure for thread-based parallelization. */ + unsigned long edgeColorGroupSize{1}; /*!< \brief Size of the edge groups within each color. */ + unsigned long elemColorGroupSize{1}; /*!< \brief Size of the element groups within each color. */ - ColMajorMatrix CoarseGridColor_; /*!< \brief Coarse grid levels, colorized. */ + ColMajorMatrix CoarseGridColor_; /*!< \brief Coarse grid levels, colorized. */ public: /*!< \brief Linelets (mesh lines perpendicular to stretching direction). */ struct CLineletInfo { /*!< \brief Detect isotropic mesh region. */ static passivedouble ALPHA_ISOTROPIC() { return 0.8; } - enum : unsigned long {MAX_LINELET_POINTS = 32}; /*!< \brief Maximum points per linelet. */ + enum : unsigned long { MAX_LINELET_POINTS = 32 }; /*!< \brief Maximum points per linelet. */ std::vector> linelets; /*!< \brief Point indices for each linelet. */ @@ -200,90 +216,115 @@ class CGeometry { std::vector lineletIdx; /*!< \brief Signals that a point is not on a linelet. */ - enum : unsigned {NO_LINELET = std::numeric_limits::max()}; + enum : unsigned { NO_LINELET = std::numeric_limits::max() }; /*!< \brief Coloring for OpenMP parallelization, "linelets" is sorted by color. */ std::vector colorOffsets; - std::vector lineletColor; /*!< \brief Coloring transfered to points, for visualization. */ + std::vector lineletColor; /*!< \brief Coloring transfered to points, for visualization. */ }; + protected: mutable CLineletInfo lineletInfo; public: /*--- Main geometric elements of the grid. ---*/ - CPrimalGrid** elem{nullptr}; /*!< \brief Element vector (primal grid information). */ - CPrimalGrid*** bound{nullptr}; /*!< \brief Boundary vector (primal grid information). */ - CPoint* nodes{nullptr}; /*!< \brief Node vector (dual grid information). */ - CEdge* edges{nullptr}; /*!< \brief Edge vector (dual grid information). */ - CVertex*** vertex{nullptr}; /*!< \brief Boundary Vertex vector (dual grid information). */ - CTurboVertex**** turbovertex{nullptr}; /*!< \brief Boundary Vertex vector ordered for turbomachinery calculation(dual grid information). */ - unsigned long *nVertex{nullptr}; /*!< \brief Number of vertex for each marker. */ - unsigned long *nElem_Bound{nullptr}; /*!< \brief Number of elements of the boundary. */ - string *Tag_to_Marker{nullptr}; /*!< \brief Names of boundary markers. */ - vector bound_is_straight; /*!< \brief Bool if boundary-marker is straight(2D)/plane(3D) for each local marker. */ - vector SurfaceAreaCfgFile; /*!< \brief Total Surface area for all markers. */ + CPrimalGrid** elem{nullptr}; /*!< \brief Element vector (primal grid information). */ + CPrimalGrid*** bound{nullptr}; /*!< \brief Boundary vector (primal grid information). */ + CPoint* nodes{nullptr}; /*!< \brief Node vector (dual grid information). */ + CEdge* edges{nullptr}; /*!< \brief Edge vector (dual grid information). */ + CVertex*** vertex{nullptr}; /*!< \brief Boundary Vertex vector (dual grid information). */ + CTurboVertex**** turbovertex{ + nullptr}; /*!< \brief Boundary Vertex vector ordered for turbomachinery calculation(dual grid information). */ + unsigned long* nVertex{nullptr}; /*!< \brief Number of vertex for each marker. */ + unsigned long* nElem_Bound{nullptr}; /*!< \brief Number of elements of the boundary. */ + string* Tag_to_Marker{nullptr}; /*!< \brief Names of boundary markers. */ + vector + bound_is_straight; /*!< \brief Bool if boundary-marker is straight(2D)/plane(3D) for each local marker. */ + vector SurfaceAreaCfgFile; /*!< \brief Total Surface area for all markers. */ /*--- Partitioning-specific variables ---*/ - unordered_map Global_to_Local_Elem; /*!< \brief Mapping of global to local index for elements. */ - unsigned long *beg_node{nullptr}; /*!< \brief Array containing the first node on each rank due to a linear partitioning by global index. */ - unsigned long *end_node{nullptr}; /*!< \brief Array containing the last node on each rank due to a linear partitioning by global index. */ - unsigned long *nPointLinear{nullptr}; /*!< \brief Array containing the total number of nodes on each rank due to a linear partioning by global index. */ - unsigned long *nPointCumulative{nullptr}; /*!< \brief Cumulative storage array containing the total number of points on all prior ranks in the linear partitioning. */ + unordered_map + Global_to_Local_Elem; /*!< \brief Mapping of global to local index for elements. */ + unsigned long* beg_node{nullptr}; /*!< \brief Array containing the first node on each rank due to a linear + partitioning by global index. */ + unsigned long* end_node{ + nullptr}; /*!< \brief Array containing the last node on each rank due to a linear partitioning by global index. */ + unsigned long* nPointLinear{nullptr}; /*!< \brief Array containing the total number of nodes on each rank due to a + linear partioning by global index. */ + unsigned long* nPointCumulative{nullptr}; /*!< \brief Cumulative storage array containing the total number of points + on all prior ranks in the linear partitioning. */ /*--- Data structures for point-to-point MPI communications. ---*/ - int maxCountPerPoint{0}; /*!< \brief Maximum number of pieces of data sent per vertex in point-to-point comms. */ - int nP2PSend{0}; /*!< \brief Number of sends during point-to-point comms. */ - int nP2PRecv{0}; /*!< \brief Number of receives during point-to-point comms. */ - int *nPoint_P2PSend{nullptr}; /*!< \brief Data structure holding number of vertices for each send in point-to-point comms. */ - int *nPoint_P2PRecv{nullptr}; /*!< \brief Data structure holding number of vertices for each recv in point-to-point comms. */ - int *Neighbors_P2PSend{nullptr}; /*!< \brief Data structure holding the ranks of the neighbors for point-to-point send comms. */ - int *Neighbors_P2PRecv{nullptr}; /*!< \brief Data structure holding the ranks of the neighbors for point-to-point recv comms. */ - map P2PSend2Neighbor; /*!< \brief Data structure holding the reverse mapping of the ranks of the neighbors for point-to-point send comms. */ - map P2PRecv2Neighbor; /*!< \brief Data structure holding the reverse mapping of the ranks of the neighbors for point-to-point recv comms. */ - unsigned long - *Local_Point_P2PSend{nullptr}, /*!< \brief Data structure holding the local index of all vertices to be sent in point-to-point comms. */ - *Local_Point_P2PRecv{nullptr}; /*!< \brief Data structure holding the local index of all vertices to be received in point-to-point comms. */ - su2double *bufD_P2PRecv{nullptr}; /*!< \brief Data structure for su2double point-to-point receive. */ - su2double *bufD_P2PSend{nullptr}; /*!< \brief Data structure for su2double point-to-point send. */ - unsigned short *bufS_P2PRecv{nullptr}; /*!< \brief Data structure for unsigned long point-to-point receive. */ - unsigned short *bufS_P2PSend{nullptr}; /*!< \brief Data structure for unsigned long point-to-point send. */ - SU2_MPI::Request *req_P2PSend{nullptr}; /*!< \brief Data structure for point-to-point send requests. */ - SU2_MPI::Request *req_P2PRecv{nullptr}; /*!< \brief Data structure for point-to-point recv requests. */ + int maxCountPerPoint{0}; /*!< \brief Maximum number of pieces of data sent per vertex in point-to-point comms. */ + int nP2PSend{0}; /*!< \brief Number of sends during point-to-point comms. */ + int nP2PRecv{0}; /*!< \brief Number of receives during point-to-point comms. */ + int* nPoint_P2PSend{ + nullptr}; /*!< \brief Data structure holding number of vertices for each send in point-to-point comms. */ + int* nPoint_P2PRecv{ + nullptr}; /*!< \brief Data structure holding number of vertices for each recv in point-to-point comms. */ + int* Neighbors_P2PSend{ + nullptr}; /*!< \brief Data structure holding the ranks of the neighbors for point-to-point send comms. */ + int* Neighbors_P2PRecv{ + nullptr}; /*!< \brief Data structure holding the ranks of the neighbors for point-to-point recv comms. */ + map P2PSend2Neighbor; /*!< \brief Data structure holding the reverse mapping of the ranks of the neighbors + for point-to-point send comms. */ + map P2PRecv2Neighbor; /*!< \brief Data structure holding the reverse mapping of the ranks of the neighbors + for point-to-point recv comms. */ + unsigned long *Local_Point_P2PSend{nullptr}, /*!< \brief Data structure holding the local index of all vertices to be + sent in point-to-point comms. */ + *Local_Point_P2PRecv{nullptr}; /*!< \brief Data structure holding the local index of all vertices to be received + in point-to-point comms. */ + su2double* bufD_P2PRecv{nullptr}; /*!< \brief Data structure for su2double point-to-point receive. */ + su2double* bufD_P2PSend{nullptr}; /*!< \brief Data structure for su2double point-to-point send. */ + unsigned short* bufS_P2PRecv{nullptr}; /*!< \brief Data structure for unsigned long point-to-point receive. */ + unsigned short* bufS_P2PSend{nullptr}; /*!< \brief Data structure for unsigned long point-to-point send. */ + SU2_MPI::Request* req_P2PSend{nullptr}; /*!< \brief Data structure for point-to-point send requests. */ + SU2_MPI::Request* req_P2PRecv{nullptr}; /*!< \brief Data structure for point-to-point recv requests. */ /*--- Data structures for periodic communications. ---*/ - int maxCountPerPeriodicPoint{0}; /*!< \brief Maximum number of pieces of data sent per vertex in periodic comms. */ - int nPeriodicSend{0}; /*!< \brief Number of sends during periodic comms. */ - int nPeriodicRecv{0}; /*!< \brief Number of receives during periodic comms. */ - int *nPoint_PeriodicSend{nullptr}; /*!< \brief Data structure holding number of vertices for each send in periodic comms. */ - int *nPoint_PeriodicRecv{nullptr}; /*!< \brief Data structure holding number of vertices for each recv in periodic comms. */ - int *Neighbors_PeriodicSend{nullptr}; /*!< \brief Data structure holding the ranks of the neighbors for periodic send comms. */ - int *Neighbors_PeriodicRecv{nullptr}; /*!< \brief Data structure holding the ranks of the neighbors for periodic recv comms. */ - map PeriodicSend2Neighbor; /*!< \brief Data structure holding the reverse mapping of the ranks of the neighbors for periodic send comms. */ - map PeriodicRecv2Neighbor; /*!< \brief Data structure holding the reverse mapping of the ranks of the neighbors for periodic recv comms. */ - unsigned long - *Local_Point_PeriodicSend{nullptr}, /*!< \brief Data structure holding the local index of all vertices to be sent in periodic comms. */ - *Local_Point_PeriodicRecv{nullptr}, /*!< \brief Data structure holding the local index of all vertices to be received in periodic comms. */ - *Local_Marker_PeriodicSend{nullptr}, /*!< \brief Data structure holding the local index of the periodic marker for a particular vertex to be sent in periodic comms. */ - *Local_Marker_PeriodicRecv{nullptr}; /*!< \brief Data structure holding the local index of the periodic marker for a particular vertex to be received in periodic comms. */ - su2double *bufD_PeriodicRecv{nullptr}; /*!< \brief Data structure for su2double periodic receive. */ - su2double *bufD_PeriodicSend{nullptr}; /*!< \brief Data structure for su2double periodic send. */ - unsigned short *bufS_PeriodicRecv{nullptr}; /*!< \brief Data structure for unsigned long periodic receive. */ - unsigned short *bufS_PeriodicSend{nullptr}; /*!< \brief Data structure for unsigned long periodic send. */ - SU2_MPI::Request *req_PeriodicSend{nullptr}; /*!< \brief Data structure for periodic send requests. */ - SU2_MPI::Request *req_PeriodicRecv{nullptr}; /*!< \brief Data structure for periodic recv requests. */ + int maxCountPerPeriodicPoint{0}; /*!< \brief Maximum number of pieces of data sent per vertex in periodic comms. */ + int nPeriodicSend{0}; /*!< \brief Number of sends during periodic comms. */ + int nPeriodicRecv{0}; /*!< \brief Number of receives during periodic comms. */ + int* nPoint_PeriodicSend{ + nullptr}; /*!< \brief Data structure holding number of vertices for each send in periodic comms. */ + int* nPoint_PeriodicRecv{ + nullptr}; /*!< \brief Data structure holding number of vertices for each recv in periodic comms. */ + int* Neighbors_PeriodicSend{ + nullptr}; /*!< \brief Data structure holding the ranks of the neighbors for periodic send comms. */ + int* Neighbors_PeriodicRecv{ + nullptr}; /*!< \brief Data structure holding the ranks of the neighbors for periodic recv comms. */ + map PeriodicSend2Neighbor; /*!< \brief Data structure holding the reverse mapping of the ranks of the + neighbors for periodic send comms. */ + map PeriodicRecv2Neighbor; /*!< \brief Data structure holding the reverse mapping of the ranks of the + neighbors for periodic recv comms. */ + unsigned long *Local_Point_PeriodicSend{ + nullptr}, /*!< \brief Data structure holding the local index of all vertices to be sent in periodic comms. */ + *Local_Point_PeriodicRecv{nullptr}, /*!< \brief Data structure holding the local index of all vertices to be + received in periodic comms. */ + *Local_Marker_PeriodicSend{nullptr}, /*!< \brief Data structure holding the local index of the periodic marker for + a particular vertex to be sent in periodic comms. */ + *Local_Marker_PeriodicRecv{nullptr}; /*!< \brief Data structure holding the local index of the periodic marker for + a particular vertex to be received in periodic comms. */ + su2double* bufD_PeriodicRecv{nullptr}; /*!< \brief Data structure for su2double periodic receive. */ + su2double* bufD_PeriodicSend{nullptr}; /*!< \brief Data structure for su2double periodic send. */ + unsigned short* bufS_PeriodicRecv{nullptr}; /*!< \brief Data structure for unsigned long periodic receive. */ + unsigned short* bufS_PeriodicSend{nullptr}; /*!< \brief Data structure for unsigned long periodic send. */ + SU2_MPI::Request* req_PeriodicSend{nullptr}; /*!< \brief Data structure for periodic send requests. */ + SU2_MPI::Request* req_PeriodicRecv{nullptr}; /*!< \brief Data structure for periodic recv requests. */ /*--- Mesh quality metrics. ---*/ - vector Orthogonality; /*!< \brief Measure of dual CV orthogonality angle (0 to 90 deg., 90 being best). */ - vector Aspect_Ratio; /*!< \brief Measure of dual CV aspect ratio (max face area / min face area). */ - vector Volume_Ratio; /*!< \brief Measure of dual CV volume ratio (max sub-element volume / min sub-element volume). */ + vector Orthogonality; /*!< \brief Measure of dual CV orthogonality angle (0 to 90 deg., 90 being best). */ + vector Aspect_Ratio; /*!< \brief Measure of dual CV aspect ratio (max face area / min face area). */ + vector + Volume_Ratio; /*!< \brief Measure of dual CV volume ratio (max sub-element volume / min sub-element volume). */ - const ColMajorMatrix& CoarseGridColor = CoarseGridColor_; /*!< \brief Coarse grid levels, colorized. */ + const ColMajorMatrix& CoarseGridColor = CoarseGridColor_; /*!< \brief Coarse grid levels, colorized. */ /*! * \brief Constructor of the class. @@ -293,7 +334,7 @@ class CGeometry { /*! * \brief Constructor of the class. */ - CGeometry(CConfig *config, unsigned short nDim); + CGeometry(CConfig* config, unsigned short nDim); /*! * \brief Destructor of the class. @@ -307,11 +348,12 @@ class CGeometry { * \param[in] geometry - Geometrical definition of the problem. * \param[in] config - Definition of the particular problem. */ - void PreprocessP2PComms(CGeometry *geometry, CConfig *config); + void PreprocessP2PComms(CGeometry* geometry, CConfig* config); /*! - * \brief Routine to allocate buffers for point-to-point MPI communications. Also called to dynamically reallocate if not enough memory is found for comms during runtime. - * \param[in] val_countPerPoint - Maximum count of the data type per vertex in point-to-point comms, e.g., nPrimvarGrad*nDim. + * \brief Routine to allocate buffers for point-to-point MPI communications. Also called to dynamically reallocate if + * not enough memory is found for comms during runtime. \param[in] val_countPerPoint - Maximum count of the data type + * per vertex in point-to-point comms, e.g., nPrimvarGrad*nDim. */ void AllocateP2PComms(unsigned short val_countPerPoint); @@ -324,8 +366,8 @@ class CGeometry { * \param[in] countPerPoint - Number of variables per point. * \param[in] val_reverse - Boolean controlling forward or reverse communication between neighbors. */ - void PostP2PRecvs(CGeometry *geometry, const CConfig *config, unsigned short commType, - unsigned short countPerPoint, bool val_reverse) const; + void PostP2PRecvs(CGeometry* geometry, const CConfig* config, unsigned short commType, unsigned short countPerPoint, + bool val_reverse) const; /*! * \brief Routine to launch a single non-blocking send once the buffer is loaded for a point-to-point commucation. @@ -337,19 +379,20 @@ class CGeometry { * \param[in] val_iMessage - Index of the message in the order they are stored. * \param[in] val_reverse - Boolean controlling forward or reverse communication between neighbors. */ - void PostP2PSends(CGeometry *geometry, const CConfig *config, unsigned short commType, - unsigned short countPerPoint, int val_iMessage, bool val_reverse) const; + void PostP2PSends(CGeometry* geometry, const CConfig* config, unsigned short commType, unsigned short countPerPoint, + int val_iMessage, bool val_reverse) const; /*! * \brief Routine to set up persistent data structures for periodic communications. * \param[in] geometry - Geometrical definition of the problem. * \param[in] config - Definition of the particular problem. */ - void PreprocessPeriodicComms(CGeometry *geometry, CConfig *config); + void PreprocessPeriodicComms(CGeometry* geometry, CConfig* config); /*! - * \brief Routine to allocate buffers for periodic communications. Also called to dynamically reallocate if not enough memory is found for comms during runtime. - * \param[in] val_countPerPeriodicPoint - Maximum count of the data type per vertex in periodic comms, e.g., nPrimvarGrad*nDim. + * \brief Routine to allocate buffers for periodic communications. Also called to dynamically reallocate if not enough + * memory is found for comms during runtime. \param[in] val_countPerPeriodicPoint - Maximum count of the data type per + * vertex in periodic comms, e.g., nPrimvarGrad*nDim. */ void AllocatePeriodicComms(unsigned short val_countPerPeriodicPoint); @@ -361,7 +404,7 @@ class CGeometry { * \param[in] commType - Enumerated type for the quantity to be communicated. * \param[in] countPerPeriodicPoint - Number of variables per point. */ - void PostPeriodicRecvs(CGeometry *geometry, const CConfig *config, unsigned short commType, + void PostPeriodicRecvs(CGeometry* geometry, const CConfig* config, unsigned short commType, unsigned short countPerPeriodicPoint); /*! @@ -373,7 +416,7 @@ class CGeometry { * \param[in] countPerPeriodicPoint - Number of variables per point. * \param[in] val_iMessage - Index of the message in the order they are stored. */ - void PostPeriodicSends(CGeometry *geometry, const CConfig *config, unsigned short commType, + void PostPeriodicSends(CGeometry* geometry, const CConfig* config, unsigned short commType, unsigned short countPerPeriodicPoint, int val_iMessage) const; /*! @@ -383,10 +426,8 @@ class CGeometry { * \param[out] COUNT_PER_POINT - Number of communicated variables per point. * \param[out] MPI_TYPE - Enumerated type for the datatype of the quantity to be communicated. */ - void GetCommCountAndType(const CConfig* config, - unsigned short commType, - unsigned short &COUNT_PER_POINT, - unsigned short &MPI_TYPE) const; + void GetCommCountAndType(const CConfig* config, unsigned short commType, unsigned short& COUNT_PER_POINT, + unsigned short& MPI_TYPE) const; /*! * \brief Routine to load a geometric quantity into the data structures for MPI point-to-point communication and to @@ -395,39 +436,38 @@ class CGeometry { * \param[in] config - Definition of the particular problem. * \param[in] commType - Enumerated type for the quantity to be communicated. */ - void InitiateComms(CGeometry *geometry, const CConfig *config, unsigned short commType) const; + void InitiateComms(CGeometry* geometry, const CConfig* config, unsigned short commType) const; /*! - * \brief Routine to complete the set of non-blocking communications launched by InitiateComms() and unpacking of the data into the geometry class. - * \param[in] geometry - Geometrical definition of the problem. - * \param[in] config - Definition of the particular problem. - * \param[in] commType - Enumerated type for the quantity to be unpacked. + * \brief Routine to complete the set of non-blocking communications launched by InitiateComms() and unpacking of the + * data into the geometry class. \param[in] geometry - Geometrical definition of the problem. \param[in] config - + * Definition of the particular problem. \param[in] commType - Enumerated type for the quantity to be unpacked. */ - void CompleteComms(CGeometry *geometry, const CConfig *config, unsigned short commType); + void CompleteComms(CGeometry* geometry, const CConfig* config, unsigned short commType); /*! * \brief Get number of coordinates. * \return Number of coordinates. */ - inline unsigned short GetnDim() const {return nDim;} + inline unsigned short GetnDim() const { return nDim; } /*! * \brief Get number of zones. * \return Number of zones. */ - inline unsigned short GetnZone() const {return nZone;} + inline unsigned short GetnZone() const { return nZone; } /*! * \brief Get number of points. * \return Number of points. */ - inline unsigned long GetnPoint() const {return nPoint;} + inline unsigned long GetnPoint() const { return nPoint; } /*! * \brief Get number of real points (that belong to the domain). * \return Number of real points. */ - inline unsigned long GetnPointDomain() const {return nPointDomain;} + inline unsigned long GetnPointDomain() const { return nPointDomain; } /*! * \brief Retrieve total number of nodes in a simulation across all processors (including halos). @@ -445,26 +485,26 @@ class CGeometry { * \brief Get number of elements. * \return Number of elements. */ - inline unsigned long GetnElem() const {return nElem;} + inline unsigned long GetnElem() const { return nElem; } /*! * \brief Get number of edges. * \return Number of edges. */ - inline unsigned long GetnEdge() const {return nEdge;} + inline unsigned long GetnEdge() const { return nEdge; } /*! * \brief Get number of markers. * \return Number of markers. */ - inline unsigned short GetnMarker() const {return nMarker;} + inline unsigned short GetnMarker() const { return nMarker; } /*! * \brief Get number of vertices. * \param[in] val_marker - Marker of the boundary. * \return Number of vertices. */ - inline const su2double* GetSpanWiseValue(unsigned short val_marker) const { return SpanWiseValue[val_marker-1]; } + inline const su2double* GetSpanWiseValue(unsigned short val_marker) const { return SpanWiseValue[val_marker - 1]; } /*! * \brief Get number of vertices. @@ -478,21 +518,27 @@ class CGeometry { * \param[in] marker_flag - flag of the turbomachinery boundary. * \return Number of span wise section. */ - inline unsigned short GetnSpanWiseSections(unsigned short marker_flag) const { return nSpanWiseSections[marker_flag -1]; } + inline unsigned short GetnSpanWiseSections(unsigned short marker_flag) const { + return nSpanWiseSections[marker_flag - 1]; + } /*! * \brief Get number of vertices. * \param[in] val_marker - Marker of the boundary. * \return Number of vertices. */ - inline unsigned long GetnVertexSpan(unsigned short val_marker, unsigned short val_span) const { return nVertexSpan[val_marker][val_span]; } + inline unsigned long GetnVertexSpan(unsigned short val_marker, unsigned short val_span) const { + return nVertexSpan[val_marker][val_span]; + } /*! * \brief Get number of frequencies per span for NRBC. * \param[in] val_marker - Marker of the boundary. * \return Number of frequencies for NRBC. */ - inline unsigned long GetnFreqSpan(unsigned short val_marker, unsigned short val_span) const { return (nTotVertexSpan[val_marker][val_span]/2 -1); } + inline unsigned long GetnFreqSpan(unsigned short val_marker, unsigned short val_span) const { + return (nTotVertexSpan[val_marker][val_span] / 2 - 1); + } /*! * \brief Get number of vertices. @@ -506,14 +552,18 @@ class CGeometry { * \param[in] marker_flag - Marker of the boundary. * \return Number of frequencies. */ - inline unsigned long GetnFreqSpanMax(unsigned short marker_flag) const { return (nVertexSpanMax[marker_flag]/2 -1); } + inline unsigned long GetnFreqSpanMax(unsigned short marker_flag) const { + return (nVertexSpanMax[marker_flag] / 2 - 1); + } /*! * \brief Get number of vertices. * \param[in] val_marker - Marker of the boundary. * \return Number of vertices. */ - inline void SetnVertexSpanMax(unsigned short marker_flag, unsigned long nVertMax) {nVertexSpanMax[marker_flag] = nVertMax;} + inline void SetnVertexSpanMax(unsigned short marker_flag, unsigned long nVertMax) { + nVertexSpanMax[marker_flag] = nVertMax; + } /*! * \brief Get the edge index from using the nodes of the edge. @@ -553,7 +603,8 @@ class CGeometry { * \param[in] kCoord - Coordinates of the third point that defines the plane. * \return Signed distance. */ - su2double Point2Plane_Distance(const su2double *Coord, const su2double *iCoord, const su2double *jCoord, const su2double *kCoord); + su2double Point2Plane_Distance(const su2double* Coord, const su2double* iCoord, const su2double* jCoord, + const su2double* kCoord); /*! * \brief Create a file for testing the geometry. @@ -584,7 +635,9 @@ class CGeometry { * \param[in] val_marker - Marker of the boundary. * \param[in] val_index - Index of the marker. */ - inline void SetMarker_Tag(unsigned short val_marker, string val_index) { Tag_to_Marker[val_marker] = std::move(val_index); } + inline void SetMarker_Tag(unsigned short val_marker, string val_index) { + Tag_to_Marker[val_marker] = std::move(val_index); + } /*! * \brief Set the number of boundary elements. @@ -592,7 +645,7 @@ class CGeometry { * \param[in] val_nelem_bound - Number of boundary elements. */ inline void SetnElem_Bound(unsigned short val_marker, unsigned long val_nelem_bound) { - nElem_Bound[val_marker]= val_nelem_bound; + nElem_Bound[val_marker] = val_nelem_bound; } /*! @@ -637,14 +690,16 @@ class CGeometry { * \param[in] face_first_elem - Index of the common face for the first element. * \param[in] face_second_elem - Index of the common face for the second element. */ - inline virtual bool FindFace(unsigned long first_elem, unsigned long second_elem, unsigned short &face_first_elem, - unsigned short &face_second_elem) {return false;} + inline virtual bool FindFace(unsigned long first_elem, unsigned long second_elem, unsigned short& face_first_elem, + unsigned short& face_second_elem) { + return false; + } /*! * \brief Sets area to be positive in Z direction. * \param[in] config - Definition of the particular problem. */ - inline virtual void SetPositive_ZArea(CConfig *config) {} + inline virtual void SetPositive_ZArea(CConfig* config) {} /*! * \brief Set connectivity between points. @@ -655,7 +710,7 @@ class CGeometry { * \brief Orders the RCM. * \param[in] config - Definition of the particular problem. */ - inline virtual void SetRCM_Ordering(CConfig *config) {} + inline virtual void SetRCM_Ordering(CConfig* config) {} /*! * \brief Connects elements . @@ -681,7 +736,7 @@ class CGeometry { * \brief Sets the vertices. * \param[in] config - Definition of the particular problem. */ - inline virtual void SetVertex(const CConfig *config) {} + inline virtual void SetVertex(const CConfig* config) {} /*! * \brief Computes the N span. @@ -690,7 +745,8 @@ class CGeometry { * \param[in] marker_flag - Marker being used * \param[in] allocate */ - inline virtual void ComputeNSpan(CConfig *config, unsigned short val_iZone, unsigned short marker_flag, bool allocate) {} + inline virtual void ComputeNSpan(CConfig* config, unsigned short val_iZone, unsigned short marker_flag, + bool allocate) {} /*! * \brief Set vertices for turbomachinery problems. @@ -699,7 +755,8 @@ class CGeometry { * \param[in] marker_flag - Marker being used * \param[in] allocate */ - inline virtual void SetTurboVertex(CConfig *config, unsigned short val_iZone, unsigned short marker_flag, bool allocate) {} + inline virtual void SetTurboVertex(CConfig* config, unsigned short val_iZone, unsigned short marker_flag, + bool allocate) {} /*! * \brief A virtual member. @@ -707,7 +764,7 @@ class CGeometry { * \param[in] val_iZone - Zone of the problem * \param[in] marker_flag - Marker being used */ - inline virtual void UpdateTurboVertex(CConfig *config, unsigned short val_iZone, unsigned short marker_flag) {} + inline virtual void UpdateTurboVertex(CConfig* config, unsigned short val_iZone, unsigned short marker_flag) {} /*! * \brief A virtual member. @@ -716,14 +773,15 @@ class CGeometry { * \param[in] marker_flag - Marker being used * \param[in] allocate */ - inline virtual void SetAvgTurboValue(CConfig *config, unsigned short val_iZone, unsigned short marker_flag, bool allocate) {} + inline virtual void SetAvgTurboValue(CConfig* config, unsigned short val_iZone, unsigned short marker_flag, + bool allocate) {} /*! * \brief A virtual member. * \param[in] config - Definition of the particular problem. * \param[in] allocate */ - inline virtual void GatherInOutAverageValues(CConfig *config, bool allocate) {} + inline virtual void GatherInOutAverageValues(CConfig* config, bool allocate) {} /*! * \brief Set max length. @@ -736,32 +794,32 @@ class CGeometry { * \param[in] config - Definition of the particular problem. * \param[in] action - Allocate or not the new elements. */ - inline virtual void SetControlVolume(CConfig *config, unsigned short action) {} + inline virtual void SetControlVolume(CConfig* config, unsigned short action) {} /*! * \brief A virtual member. * \param[in] config - Definition of the particular problem. */ - inline virtual void VisualizeControlVolume(const CConfig *config) const {} + inline virtual void VisualizeControlVolume(const CConfig* config) const {} /*! * \brief A virtual member. * \param[in] config - Definition of the particular problem. */ - inline virtual void MatchActuator_Disk(const CConfig *config) {} + inline virtual void MatchActuator_Disk(const CConfig* config) {} /*! * \brief A virtual member. * \param[in] config - Definition of the particular problem. */ - inline virtual void MatchPeriodic(const CConfig *config, unsigned short val_periodic) {} + inline virtual void MatchPeriodic(const CConfig* config, unsigned short val_periodic) {} /*! * \brief A virtual member. * \param[in] config - Definition of the particular problem. * \param[in] action - Allocate or not the new elements. */ - inline virtual void SetBoundControlVolume(const CConfig *config, unsigned short action) {} + inline virtual void SetBoundControlVolume(const CConfig* config, unsigned short action) {} /*! * \brief A virtual member. @@ -775,43 +833,43 @@ class CGeometry { * \param[in] new_file - Boolean to decide if aopen a new file or add to a old one * \param[in] config - Definition of the particular problem. */ - inline virtual void SetBoundTecPlot(char mesh_filename[MAX_STRING_SIZE], bool new_file, CConfig *config) {} + inline virtual void SetBoundTecPlot(char mesh_filename[MAX_STRING_SIZE], bool new_file, CConfig* config) {} /*! * \brief A virtual member. * \param[in] config - Definition of the particular problem. */ - inline virtual void Check_IntElem_Orientation(const CConfig *config) {} + inline virtual void Check_IntElem_Orientation(const CConfig* config) {} /*! * \brief A virtual member. * \param[in] config - Definition of the particular problem. */ - inline virtual void Check_BoundElem_Orientation(const CConfig *config) {} + inline virtual void Check_BoundElem_Orientation(const CConfig* config) {} /*! * \brief A virtual member. * \param[in] config - Definition of the particular problem. */ - inline virtual void SetColorGrid(CConfig *config) {} + inline virtual void SetColorGrid(CConfig* config) {} /*! * \brief A virtual member. * \param[in] config - Definition of the particular problem. */ - inline virtual void SetColorGrid_Parallel(const CConfig *config) {} + inline virtual void SetColorGrid_Parallel(const CConfig* config) {} /*! * \brief A virtual member. * \param[in] config - Definition of the particular problem. */ - inline virtual void SetColorFEMGrid_Parallel(CConfig *config) {} + inline virtual void SetColorFEMGrid_Parallel(CConfig* config) {} /*! * \brief A virtual member. * \param[in] config - Definition of the particular problem. */ - inline virtual void DivideConnectivity(CConfig *config, unsigned short Elem_Type) {} + inline virtual void DivideConnectivity(CConfig* config, unsigned short Elem_Type) {} /*! * \brief A virtual member. @@ -819,7 +877,7 @@ class CGeometry { * \param[in] config - Definition of the particular problem. * \param[in] val_domain - Number of domains for parallelization purposes. */ - inline virtual void SetSendReceive(const CConfig *config) {} + inline virtual void SetSendReceive(const CConfig* config) {} /*! * \brief A virtual member. @@ -827,27 +885,27 @@ class CGeometry { * \param[in] config - Definition of the particular problem. * \param[in] val_domain - Number of domains for parallelization purposes. */ - inline virtual void SetBoundaries(CConfig *config) {} + inline virtual void SetBoundaries(CConfig* config) {} /*! * \brief A virtual member. * \param[in] fine_grid - Geometrical definition of the problem. */ - inline virtual void SetCoord(const CGeometry *fine_grid) {} + inline virtual void SetCoord(const CGeometry* fine_grid) {} /*! * \brief A virtual member. * \param[in] fine_grid - Geometrical definition of the problem. * \param[in] val_marker - Index of the boundary marker. */ - inline virtual void SetMultiGridWallHeatFlux(const CGeometry *fine_grid, unsigned short val_marker) {} + inline virtual void SetMultiGridWallHeatFlux(const CGeometry* fine_grid, unsigned short val_marker) {} /*! * \brief A virtual member. * \param[in] fine_grid - Geometrical definition of the problem. * \param[in] val_marker - Index of the boundary marker. */ - inline virtual void SetMultiGridWallTemperature(const CGeometry *fine_grid, unsigned short val_marker) {} + inline virtual void SetMultiGridWallTemperature(const CGeometry* fine_grid, unsigned short val_marker) {} /*! * \brief A virtual member. @@ -855,99 +913,99 @@ class CGeometry { * \param[in] val_smooth_coeff - Relaxation factor. * \param[in] config - Definition of the particular problem. */ - inline virtual void SetCoord_Smoothing(unsigned short val_nSmooth, su2double val_smooth_coeff, CConfig *config) {} + inline virtual void SetCoord_Smoothing(unsigned short val_nSmooth, su2double val_smooth_coeff, CConfig* config) {} /*! * \brief A virtual member. * \param[in] fine_grid - Geometrical definition of the child grid (for multigrid). */ - inline virtual void SetPoint_Connectivity(const CGeometry *fine_grid) {} + inline virtual void SetPoint_Connectivity(const CGeometry* fine_grid) {} /*! * \brief A virtual member. * \param[in] fine_grid - Geometrical definition of the problem. * \param[in] config - Definition of the particular problem. */ - inline virtual void SetVertex(const CGeometry *fine_grid, const CConfig *config) {} + inline virtual void SetVertex(const CGeometry* fine_grid, const CConfig* config) {} /*! * \brief A virtual member. * \param[in] fine_grid - Geometrical definition of the problem. * \param[in] action - Allocate or not the new elements. */ - inline virtual void SetControlVolume(const CGeometry *fine_grid, unsigned short action) {} + inline virtual void SetControlVolume(const CGeometry* fine_grid, unsigned short action) {} /*! * \brief A virtual member. * \param[in] fine_grid - Geometrical definition of the problem. * \param[in] action - Allocate or not the new elements. */ - inline virtual void SetBoundControlVolume(const CGeometry *fine_grid, unsigned short action) {} + inline virtual void SetBoundControlVolume(const CGeometry* fine_grid, unsigned short action) {} /*! * \brief A virtual member. * \param[in] config - Definition of the particular problem. */ - inline virtual void SetBoundSensitivity(CConfig *config) {} + inline virtual void SetBoundSensitivity(CConfig* config) {} /*! * \brief Set the data containers for customized boundary conditions. * \param[in] config - Definition of the particular problem. */ - void SetCustomBoundary(CConfig *config); + void SetCustomBoundary(CConfig* config); /*! * \brief Set cartesian grid velocity based on rotational speed and axis. * \param[in] config - Definition of the particular problem. * \param[in] print - Display information on screen. */ - void SetRotationalVelocity(const CConfig *config, bool print = false); + void SetRotationalVelocity(const CConfig* config, bool print = false); /*! * \brief Set the rotational velocity of the points on the shroud markers to 0. * \param[in] config - Definition of the particular problem. */ - void SetShroudVelocity(const CConfig *config); + void SetShroudVelocity(const CConfig* config); /*! * \brief Set the translational velocity at each node. * \param[in] config - Definition of the particular problem. * \param[in] print - Display information on screen. */ - void SetTranslationalVelocity(const CConfig *config, bool print = false); + void SetTranslationalVelocity(const CConfig* config, bool print = false); /*! * \brief Set the translational/rotational velocity for all moving walls. * \param[in] config - Definition of the particular problem. * \param[in] print - Display information on screen. */ - void SetWallVelocity(const CConfig *config, bool print = false); + void SetWallVelocity(const CConfig* config, bool print = false); /*! * \brief Set the grid velocity via finite differencing at each node. * \param[in] config - Definition of the particular problem. */ - void SetGridVelocity(const CConfig *config); + void SetGridVelocity(const CConfig* config); /*! * \brief A virtual member. * \param[in] fine_grid - Geometry of the fine mesh. */ - inline virtual void SetRestricted_GridVelocity(const CGeometry *fine_grid) {} + inline virtual void SetRestricted_GridVelocity(const CGeometry* fine_grid) {} /*! * \brief Compute the surface area of all global markers. * \param[in] config - Definition of the particular problem. */ - void ComputeSurfaceAreaCfgFile(const CConfig *config); + void ComputeSurfaceAreaCfgFile(const CConfig* config); /*! - * \brief Get global Surface Area to a local marker. - * \param[in] config - Definition of the particular problem. - * \param[in] val_marker - Local surface marker. - * \return Global Surface Area to the local marker - */ - su2double GetSurfaceArea(const CConfig *config, unsigned short val_marker) const; + * \brief Get global Surface Area to a local marker. + * \param[in] config - Definition of the particular problem. + * \param[in] val_marker - Local surface marker. + * \return Global Surface Area to the local marker + */ + su2double GetSurfaceArea(const CConfig* config, unsigned short val_marker) const; /*! * \brief Check if a boundary is straight(2D) / plane(3D) for EULER_WALL and SYMMETRY_PLANE @@ -956,147 +1014,172 @@ class CGeometry { * \param[in] config - Definition of the particular problem. * \param[in] print_on_screen - Boolean whether to print result on screen. */ - void ComputeSurf_Straightness(CConfig *config, bool print_on_screen); + void ComputeSurf_Straightness(CConfig* config, bool print_on_screen); /*! * \brief Find and store all vertices on a sharp corner in the geometry. * \param[in] config - Definition of the particular problem. */ - void ComputeSurf_Curvature(CConfig *config); + void ComputeSurf_Curvature(CConfig* config); /*! * \brief A virtual member. * \param[in] config - Definition of the particular problem. */ - void ComputeAirfoil_Section(su2double *Plane_P0, su2double *Plane_Normal, - su2double MinXCoord, su2double MaxXCoord, - su2double MinYCoord, su2double MaxYCoord, - su2double MinZCoord, su2double MaxZCoord, - const su2double *FlowVariable, - vector &Xcoord_Airfoil, vector &Ycoord_Airfoil, - vector &Zcoord_Airfoil, vector &Variable_Airfoil, - bool original_surface, CConfig *config); + void ComputeAirfoil_Section(su2double* Plane_P0, su2double* Plane_Normal, su2double MinXCoord, su2double MaxXCoord, + su2double MinYCoord, su2double MaxYCoord, su2double MinZCoord, su2double MaxZCoord, + const su2double* FlowVariable, vector& Xcoord_Airfoil, + vector& Ycoord_Airfoil, vector& Zcoord_Airfoil, + vector& Variable_Airfoil, bool original_surface, CConfig* config); /*! * \brief A virtual member. */ - virtual su2double Compute_MaxThickness(su2double *Plane_P0, su2double *Plane_Normal, CConfig *config, vector &Xcoord_Airfoil, - vector &Ycoord_Airfoil, vector &Zcoord_Airfoil) {return 0.0;} + virtual su2double Compute_MaxThickness(su2double* Plane_P0, su2double* Plane_Normal, CConfig* config, + vector& Xcoord_Airfoil, vector& Ycoord_Airfoil, + vector& Zcoord_Airfoil) { + return 0.0; + } /*! * \brief A virtual member. */ - virtual su2double Compute_Twist(su2double *Plane_P0, su2double *Plane_Normal, vector &Xcoord_Airfoil, - vector &Ycoord_Airfoil, vector &Zcoord_Airfoil) {return 0.0;} + virtual su2double Compute_Twist(su2double* Plane_P0, su2double* Plane_Normal, vector& Xcoord_Airfoil, + vector& Ycoord_Airfoil, vector& Zcoord_Airfoil) { + return 0.0; + } /*! * \brief A virtual member. */ - virtual su2double Compute_Chord(su2double *Plane_P0, su2double *Plane_Normal, vector &Xcoord_Airfoil, - vector &Ycoord_Airfoil, vector &Zcoord_Airfoil) {return 0.0;} + virtual su2double Compute_Chord(su2double* Plane_P0, su2double* Plane_Normal, vector& Xcoord_Airfoil, + vector& Ycoord_Airfoil, vector& Zcoord_Airfoil) { + return 0.0; + } /*! * \brief A virtual member. */ - virtual su2double Compute_Width(su2double *Plane_P0, su2double *Plane_Normal, vector &Xcoord_Airfoil, - vector &Ycoord_Airfoil, vector &Zcoord_Airfoil) {return 0.0;} + virtual su2double Compute_Width(su2double* Plane_P0, su2double* Plane_Normal, vector& Xcoord_Airfoil, + vector& Ycoord_Airfoil, vector& Zcoord_Airfoil) { + return 0.0; + } /*! * \brief A virtual member. */ - virtual su2double Compute_WaterLineWidth(su2double *Plane_P0, su2double *Plane_Normal, CConfig *config, vector &Xcoord_Airfoil, - vector &Ycoord_Airfoil, vector &Zcoord_Airfoil) {return 0.0;} + virtual su2double Compute_WaterLineWidth(su2double* Plane_P0, su2double* Plane_Normal, CConfig* config, + vector& Xcoord_Airfoil, vector& Ycoord_Airfoil, + vector& Zcoord_Airfoil) { + return 0.0; + } /*! * \brief A virtual member. */ - virtual su2double Compute_Height(su2double *Plane_P0, su2double *Plane_Normal, vector &Xcoord_Airfoil, - vector &Ycoord_Airfoil, vector &Zcoord_Airfoil) {return 0.0;} + virtual su2double Compute_Height(su2double* Plane_P0, su2double* Plane_Normal, vector& Xcoord_Airfoil, + vector& Ycoord_Airfoil, vector& Zcoord_Airfoil) { + return 0.0; + } /*! * \brief A virtual member. */ - virtual su2double Compute_LERadius(su2double *Plane_P0, su2double *Plane_Normal, vector &Xcoord_Airfoil, - vector &Ycoord_Airfoil, vector &Zcoord_Airfoil) {return 0.0;} + virtual su2double Compute_LERadius(su2double* Plane_P0, su2double* Plane_Normal, vector& Xcoord_Airfoil, + vector& Ycoord_Airfoil, vector& Zcoord_Airfoil) { + return 0.0; + } /*! * \brief A virtual member. */ - virtual su2double Compute_Thickness(su2double *Plane_P0, su2double *Plane_Normal, su2double Location, CConfig *config, - vector &Xcoord_Airfoil, vector &Ycoord_Airfoil, - vector &Zcoord_Airfoil, su2double &ZLoc) {return 0.0;} + virtual su2double Compute_Thickness(su2double* Plane_P0, su2double* Plane_Normal, su2double Location, CConfig* config, + vector& Xcoord_Airfoil, vector& Ycoord_Airfoil, + vector& Zcoord_Airfoil, su2double& ZLoc) { + return 0.0; + } /*! * \brief A virtual member. */ - virtual su2double Compute_Area(su2double *Plane_P0, su2double *Plane_Normal, CConfig *config, vector &Xcoord_Airfoil, - vector &Ycoord_Airfoil, vector &Zcoord_Airfoil) {return 0.0;} + virtual su2double Compute_Area(su2double* Plane_P0, su2double* Plane_Normal, CConfig* config, + vector& Xcoord_Airfoil, vector& Ycoord_Airfoil, + vector& Zcoord_Airfoil) { + return 0.0; + } /*! * \brief A virtual member. */ - virtual su2double Compute_Length(su2double *Plane_P0, su2double *Plane_Normal, CConfig *config, vector &Xcoord_Airfoil, - vector &Ycoord_Airfoil, vector &Zcoord_Airfoil) {return 0.0;} + virtual su2double Compute_Length(su2double* Plane_P0, su2double* Plane_Normal, CConfig* config, + vector& Xcoord_Airfoil, vector& Ycoord_Airfoil, + vector& Zcoord_Airfoil) { + return 0.0; + } /*! * \brief A virtual member. */ - virtual void Compute_Wing_LeadingTrailing(su2double *LeadingEdge, su2double *TrailingEdge, su2double *Plane_P0, su2double *Plane_Normal, vector - &Xcoord_Airfoil, vector &Ycoord_Airfoil, vector &Zcoord_Airfoil) {} + virtual void Compute_Wing_LeadingTrailing(su2double* LeadingEdge, su2double* TrailingEdge, su2double* Plane_P0, + su2double* Plane_Normal, vector& Xcoord_Airfoil, + vector& Ycoord_Airfoil, vector& Zcoord_Airfoil) {} /*! * \brief A virtual member. */ - virtual void Compute_Fuselage_LeadingTrailing(su2double *LeadingEdge, su2double *TrailingEdge, su2double *Plane_P0, su2double *Plane_Normal, vector - &Xcoord_Airfoil, vector &Ycoord_Airfoil, vector &Zcoord_Airfoil) {} + virtual void Compute_Fuselage_LeadingTrailing(su2double* LeadingEdge, su2double* TrailingEdge, su2double* Plane_P0, + su2double* Plane_Normal, vector& Xcoord_Airfoil, + vector& Ycoord_Airfoil, vector& Zcoord_Airfoil) {} /*! * \brief A virtual member. */ - virtual su2double Compute_Dihedral(su2double *LeadingEdge_im1, su2double *TrailingEdge_im1, - su2double *LeadingEdge_i, su2double *TrailingEdge_i) {return 0.0;} + virtual su2double Compute_Dihedral(su2double* LeadingEdge_im1, su2double* TrailingEdge_im1, su2double* LeadingEdge_i, + su2double* TrailingEdge_i) { + return 0.0; + } /*! * \brief A virtual member. */ - virtual su2double Compute_Curvature(su2double *LeadingEdge_im1, su2double *TrailingEdge_im1, - su2double *LeadingEdge_i, su2double *TrailingEdge_i, - su2double *LeadingEdge_ip1, su2double *TrailingEdge_ip1) {return 0.0;} + virtual su2double Compute_Curvature(su2double* LeadingEdge_im1, su2double* TrailingEdge_im1, su2double* LeadingEdge_i, + su2double* TrailingEdge_i, su2double* LeadingEdge_ip1, + su2double* TrailingEdge_ip1) { + return 0.0; + } /*! * \brief A virtual member. */ - virtual void Compute_Wing(CConfig *config, bool original_surface, - su2double &Wing_Volume, su2double &Wing_MinMaxThickness, su2double &Wing_MaxMaxThickness, su2double &Wing_MinChord, su2double &Wing_MaxChord, - su2double &Wing_MinLERadius, su2double &Wing_MaxLERadius, - su2double &Wing_MinToC, su2double &Wing_MaxToC, su2double &Wing_ObjFun_MinToC, su2double &Wing_MaxTwist, su2double &Wing_MaxCurvature, - su2double &Wing_MaxDihedral) {} + virtual void Compute_Wing(CConfig* config, bool original_surface, su2double& Wing_Volume, + su2double& Wing_MinMaxThickness, su2double& Wing_MaxMaxThickness, su2double& Wing_MinChord, + su2double& Wing_MaxChord, su2double& Wing_MinLERadius, su2double& Wing_MaxLERadius, + su2double& Wing_MinToC, su2double& Wing_MaxToC, su2double& Wing_ObjFun_MinToC, + su2double& Wing_MaxTwist, su2double& Wing_MaxCurvature, su2double& Wing_MaxDihedral) {} /*! * \brief A virtual member. */ - virtual void Compute_Fuselage(CConfig *config, bool original_surface, - su2double &Fuselage_Volume, su2double &Fuselage_WettedArea, - su2double &Fuselage_MinWidth, su2double &Fuselage_MaxWidth, - su2double &Fuselage_MinWaterLineWidth, su2double &Fuselage_MaxWaterLineWidth, - su2double &Fuselage_MinHeight, su2double &Fuselage_MaxHeight, - su2double &Fuselage_MaxCurvature) {} + virtual void Compute_Fuselage(CConfig* config, bool original_surface, su2double& Fuselage_Volume, + su2double& Fuselage_WettedArea, su2double& Fuselage_MinWidth, + su2double& Fuselage_MaxWidth, su2double& Fuselage_MinWaterLineWidth, + su2double& Fuselage_MaxWaterLineWidth, su2double& Fuselage_MinHeight, + su2double& Fuselage_MaxHeight, su2double& Fuselage_MaxCurvature) {} /*! * \brief A virtual member. */ - virtual void Compute_Nacelle(CConfig *config, bool original_surface, - su2double &Nacelle_Volume, su2double &Nacelle_MinMaxThickness, su2double &Nacelle_MaxMaxThickness, - su2double &Nacelle_MinChord, su2double &Nacelle_MaxChord, - su2double &Nacelle_MinLERadius, su2double &Nacelle_MaxLERadius, - su2double &Nacelle_MinToC, su2double &Nacelle_MaxToC, - su2double &Nacelle_ObjFun_MinToC, su2double &Nacelle_MaxTwist) {} + virtual void Compute_Nacelle(CConfig* config, bool original_surface, su2double& Nacelle_Volume, + su2double& Nacelle_MinMaxThickness, su2double& Nacelle_MaxMaxThickness, + su2double& Nacelle_MinChord, su2double& Nacelle_MaxChord, su2double& Nacelle_MinLERadius, + su2double& Nacelle_MaxLERadius, su2double& Nacelle_MinToC, su2double& Nacelle_MaxToC, + su2double& Nacelle_ObjFun_MinToC, su2double& Nacelle_MaxTwist) {} /*! * \brief A virtual member. * \param[in] config - Definition of the particular problem. */ - inline virtual void FindNormal_Neighbor(const CConfig *config) {} + inline virtual void FindNormal_Neighbor(const CConfig* config) {} /*! * \brief A virtual member. @@ -1209,22 +1292,22 @@ class CGeometry { /*! * \brief Get x coords of geometrical planes in the mesh */ - inline vector > GetXCoord() const {return Xcoord_plane;} + inline vector> GetXCoord() const { return Xcoord_plane; } /*! * \brief Get y coords of geometrical planes in the mesh */ - inline vector > GetYCoord() const {return Ycoord_plane;} + inline vector> GetYCoord() const { return Ycoord_plane; } /*! * \brief Get z coords of geometrical planes in the mesh */ - inline vector > GetZCoord() const {return Zcoord_plane;} + inline vector> GetZCoord() const { return Zcoord_plane; } /*! * \brief Get all points on a geometrical plane in the mesh */ - inline vector > GetPlanarPoints() const {return Plane_points;} + inline vector> GetPlanarPoints() const { return Plane_points; } /*! * \brief Compute the intersection between a segment and a plane. @@ -1235,26 +1318,27 @@ class CGeometry { * \param[in] Intersection - Definition of the particular problem. * \return If the intersection has has been successful. */ - bool SegmentIntersectsPlane(const su2double *Segment_P0, const su2double *Segment_P1, su2double Variable_P0, su2double Variable_P1, - const su2double *Plane_P0, const su2double *Plane_Normal, su2double *Intersection, su2double &Variable_Interp); + bool SegmentIntersectsPlane(const su2double* Segment_P0, const su2double* Segment_P1, su2double Variable_P0, + su2double Variable_P1, const su2double* Plane_P0, const su2double* Plane_Normal, + su2double* Intersection, su2double& Variable_Interp); /*! * \brief Ray Intersects Triangle (Moller and Trumbore algorithm) */ - bool RayIntersectsTriangle(const su2double orig[3], const su2double dir[3], - const su2double vert0[3], const su2double vert1[3], const su2double vert2[3], - su2double *intersect); + bool RayIntersectsTriangle(const su2double orig[3], const su2double dir[3], const su2double vert0[3], + const su2double vert1[3], const su2double vert2[3], su2double* intersect); /*! * \brief Segment Intersects Triangle */ - bool SegmentIntersectsTriangle(su2double point0[3], const su2double point1[3], - su2double vert0[3], su2double vert1[3], su2double vert2[3]); + bool SegmentIntersectsTriangle(su2double point0[3], const su2double point1[3], su2double vert0[3], su2double vert1[3], + su2double vert2[3]); /*! * \brief Segment Intersects Line (for 2D FFD Intersection) */ - bool SegmentIntersectsLine(const su2double point0[2], const su2double point1[2], const su2double vert0[2], const su2double vert1[2]); + bool SegmentIntersectsLine(const su2double point0[2], const su2double point1[2], const su2double vert0[2], + const su2double vert1[2]); /*! * \brief Register the coordinates of the mesh nodes. @@ -1266,33 +1350,33 @@ class CGeometry { * \param geometry_container - Geometrical definition. * \param config - Config */ - static void UpdateGeometry(CGeometry **geometry_container, CConfig *config); + static void UpdateGeometry(CGeometry** geometry_container, CConfig* config); /*! * \brief Update the multi-grid structure for the customized boundary conditions * \param geometry_container - Geometrical definition. * \param config - Definition of the particular problem. */ - void UpdateCustomBoundaryConditions(CGeometry **geometry_container, CConfig *config); + void UpdateCustomBoundaryConditions(CGeometry** geometry_container, CConfig* config); /*! * \brief A virtual member. * \param config - Config */ - inline virtual void SetSensitivity(CConfig *config) {} + inline virtual void SetSensitivity(CConfig* config) {} /*! * \brief A virtual member. * \param config - Config */ - inline virtual void ReadUnorderedSensitivity(CConfig *config) {} + inline virtual void ReadUnorderedSensitivity(CConfig* config) {} /*! * \brief A virtual member. * \param iPoint - Point * \param iDim - Dimension */ - inline virtual su2double GetSensitivity(unsigned long iPoint, unsigned short iDim) const {return 0.0;} + inline virtual su2double GetSensitivity(unsigned long iPoint, unsigned short iDim) const { return 0.0; } /*! * \brief A virtual member. @@ -1515,7 +1599,7 @@ class CGeometry { * \brief A virtual member. * \param config - Config */ - inline virtual void Check_Periodicity(CConfig *config) {} + inline virtual void Check_Periodicity(CConfig* config) {} /*! * \brief Get the value of the customized temperature at a specified vertex on a specified marker. @@ -1532,7 +1616,8 @@ class CGeometry { * \param[in] val_vertex - Boundary vertex value * \param[in] val_customBoundaryTemperature - Value of the temperature. */ - inline void SetCustomBoundaryTemperature(unsigned short val_marker, unsigned long val_vertex, su2double val_customBoundaryTemperature) { + inline void SetCustomBoundaryTemperature(unsigned short val_marker, unsigned long val_vertex, + su2double val_customBoundaryTemperature) { CustomBoundaryTemperature[val_marker][val_vertex] = val_customBoundaryTemperature; } @@ -1551,7 +1636,8 @@ class CGeometry { * \param[in] val_vertex - Boundary vertex value * \param[in] val_customBoundaryHeatFlux - Value of the normal heat flux. */ - inline void SetCustomBoundaryHeatFlux(unsigned short val_marker, unsigned long val_vertex, su2double val_customBoundaryHeatFlux) { + inline void SetCustomBoundaryHeatFlux(unsigned short val_marker, unsigned long val_vertex, + su2double val_customBoundaryHeatFlux) { CustomBoundaryHeatFlux[val_marker][val_vertex] = val_customBoundaryHeatFlux; } @@ -1559,12 +1645,12 @@ class CGeometry { * \brief Filter values given at the element CG by performing a weighted average over a radial neighbourhood. * \param[in] filter_radius - Parameter defining the size of the neighbourhood. * \param[in] kernels - Kernel types and respective parameter, size of vector defines number of filter recursions. - * \param[in] search_limit - Max degree of neighborhood considered for neighbor search, avoids excessive work in fine regions. - * \param[in,out] values - On entry, the "raw" values, on exit, the filtered values. + * \param[in] search_limit - Max degree of neighborhood considered for neighbor search, avoids excessive work in fine + * regions. \param[in,out] values - On entry, the "raw" values, on exit, the filtered values. */ - void FilterValuesAtElementCG(const vector &filter_radius, - const vector > &kernels, - const unsigned short search_limit, su2double *values) const; + void FilterValuesAtElementCG(const vector& filter_radius, + const vector>& kernels, + const unsigned short search_limit, su2double* values) const; /*! * \brief Build the global (entire mesh!) adjacency matrix for the elements in compressed format. @@ -1573,23 +1659,21 @@ class CGeometry { * neighbours of global element "i". Size nElemDomain+1 * \param[out] neighbour_idx - Global index of the neighbours, mush be NULL on entry and free'd by calling function. */ - void GetGlobalElementAdjacencyMatrix(vector &neighbour_start, long *&neighbour_idx) const; + void GetGlobalElementAdjacencyMatrix(vector& neighbour_start, long*& neighbour_idx) const; /*! - * \brief Get the neighbours of the global element in the first position of "neighbours" that are within "radius" of it. - * \param[in] iElem_global - Element of interest. - * \param[in] radius - Parameter defining the size of the neighbourhood. - * \param[in] search_limit - Maximum "logical radius" to consider, limits cost in refined regions, use 0 for unlimited. - * \param[in] neighbour_start - See GetGlobalElementAdjacencyMatrix. - * \param[in] neighbour_idx - See GetGlobalElementAdjacencyMatrix. - * \param[in] cg_elem - Global element centroid coordinates in row major format {x0,y0,x1,y1,...}. Size nDim*nElemDomain. - * \param[in,out] neighbours - The neighbours of iElem_global. - * \param[in,out] is_neighbor - Working vector of size nElemGlobal, MUST be all false on entry (if so, on exit it will be the same). - * \return true if the search was successful, i.e. not limited. + * \brief Get the neighbours of the global element in the first position of "neighbours" that are within "radius" of + * it. \param[in] iElem_global - Element of interest. \param[in] radius - Parameter defining the size of the + * neighbourhood. \param[in] search_limit - Maximum "logical radius" to consider, limits cost in refined regions, use + * 0 for unlimited. \param[in] neighbour_start - See GetGlobalElementAdjacencyMatrix. \param[in] neighbour_idx - See + * GetGlobalElementAdjacencyMatrix. \param[in] cg_elem - Global element centroid coordinates in row major format + * {x0,y0,x1,y1,...}. Size nDim*nElemDomain. \param[in,out] neighbours - The neighbours of iElem_global. + * \param[in,out] is_neighbor - Working vector of size nElemGlobal, MUST be all false on entry (if so, on exit it will + * be the same). \return true if the search was successful, i.e. not limited. */ bool GetRadialNeighbourhood(const unsigned long iElem_global, const passivedouble radius, size_t search_limit, - const vector &neighbour_start, const long *neighbour_idx, - const su2double *cg_elem, vector &neighbours, vector &is_neighbor) const; + const vector& neighbour_start, const long* neighbour_idx, + const su2double* cg_elem, vector& neighbours, vector& is_neighbor) const; /*! * \brief Compute and store the volume of the primal elements. @@ -1612,7 +1696,7 @@ class CGeometry { * \brief A virtual member. * \param config - Config */ - inline virtual void ComputeMeshQualityStatistics(const CConfig *config) {} + inline virtual void ComputeMeshQualityStatistics(const CConfig* config) {} /*! * \brief Color multigrid levels for visualization. @@ -1692,7 +1776,7 @@ class CGeometry { * \param[in] config - Definition of the particular problem. * \return pointer to the ADT */ - virtual std::unique_ptr ComputeViscousWallADT(const CConfig *config) const { return nullptr; } + virtual std::unique_ptr ComputeViscousWallADT(const CConfig* config) const { return nullptr; } /*! * \brief Reduce the wall distance based on an previously constructed ADT. @@ -1702,7 +1786,8 @@ class CGeometry { * \param[in] config - Config of this geometry (not the ADT zone's geometry) * \param[in] iZone - Zone whose markers made the ADT */ - virtual void SetWallDistance(CADTElemClass* WallADT, const CConfig* config, unsigned short iZone = numeric_limits::max()) {} + virtual void SetWallDistance(CADTElemClass* WallADT, const CConfig* config, + unsigned short iZone = numeric_limits::max()) {} /*! * \brief Set wall distances a specific value @@ -1715,25 +1800,25 @@ class CGeometry { * \param[in] config_container - Definition of the particular problem. * \param[in] geometry_container - Geometrical definition of the problem. */ - static void ComputeWallDistance(const CConfig * const *config_container, CGeometry ****geometry_container); + static void ComputeWallDistance(const CConfig* const* config_container, CGeometry**** geometry_container); /*! * \brief Set the amount of nonconvex elements in the mesh. * \param[in] nonconvex_elems - amount of nonconvex elements in the mesh */ - void SetnNonconvexElements(unsigned long nonconvex_elems) {nNonconvexElements = nonconvex_elems;} + void SetnNonconvexElements(unsigned long nonconvex_elems) { nNonconvexElements = nonconvex_elems; } /*! * \brief Get the amount of nonconvex elements in the mesh. * \param[out] nNonconvexElements- amount of nonconvex elements in the mesh */ - unsigned long GetnNonconvexElements() const {return nNonconvexElements;} + unsigned long GetnNonconvexElements() const { return nNonconvexElements; } /*! * \brief For streamwise periodicity, find & store a unique reference node on the designated periodic inlet. * \param[in] config - Definition of the particular problem. */ - inline virtual void FindUniqueNode_PeriodicBound(const CConfig *config) {} + inline virtual void FindUniqueNode_PeriodicBound(const CConfig* config) {} /*! * \brief Get a pointer to the reference node coordinate vector. @@ -1741,4 +1826,3 @@ class CGeometry { */ inline virtual const su2double* GetStreamwise_Periodic_RefNode() const { return nullptr; } }; - diff --git a/Common/include/geometry/CMultiGridGeometry.hpp b/Common/include/geometry/CMultiGridGeometry.hpp index ab65300c5ca..6c875cc6f57 100644 --- a/Common/include/geometry/CMultiGridGeometry.hpp +++ b/Common/include/geometry/CMultiGridGeometry.hpp @@ -36,7 +36,7 @@ * \author F. Palacios */ class CMultiGridGeometry final : public CGeometry { -private: + private: /*! * \brief Determine if a CVPoint van be agglomerated, if it have the same marker point as the seed. * \param[in] CVPoint - Control volume to be agglomerated. @@ -45,8 +45,8 @@ class CMultiGridGeometry final : public CGeometry { * \param[in] config - Definition of the particular problem. * \return TRUE or FALSE depending if the control volume can be agglomerated. */ - bool SetBoundAgglomeration(unsigned long CVPoint, short marker_seed, const CGeometry *fine_grid, - const CConfig *config) const; + bool SetBoundAgglomeration(unsigned long CVPoint, short marker_seed, const CGeometry* fine_grid, + const CConfig* config) const; /*! * \brief Determine if a can be agglomerated using geometrical criteria. @@ -54,7 +54,7 @@ class CMultiGridGeometry final : public CGeometry { * \param[in] fine_grid - Geometrical definition of the problem. * \param[in] config - Definition of the particular problem. */ - bool GeometricalCheck(unsigned long iPoint, const CGeometry *fine_grid, const CConfig *config) const; + bool GeometricalCheck(unsigned long iPoint, const CGeometry* fine_grid, const CConfig* config) const; /*! * \brief Determine if a CVPoint van be agglomerated, if it have the same marker point as the seed. @@ -64,7 +64,7 @@ class CMultiGridGeometry final : public CGeometry { * \param[in] fine_grid - Geometrical definition of the problem. */ void SetSuitableNeighbors(vector& Suitable_Indirect_Neighbors, unsigned long iPoint, - unsigned long Index_CoarseCV, const CGeometry *fine_grid) const; + unsigned long Index_CoarseCV, const CGeometry* fine_grid) const; /*! * \brief Set a representative wall value of the agglomerated control volumes on a particular boundary marker. @@ -73,8 +73,7 @@ class CMultiGridGeometry final : public CGeometry { * \param[in] wall_quantity - Object with methods Get(iVertex_fine) and Set(iVertex_coarse, val). */ template - void SetMultiGridWallQuantity(const CGeometry *fine_grid, unsigned short val_marker, T& wall_quantity) { - + void SetMultiGridWallQuantity(const CGeometry* fine_grid, unsigned short val_marker, T& wall_quantity) { for (auto iVertex = 0ul; iVertex < nVertex[val_marker]; iVertex++) { const auto Point_Coarse = vertex[val_marker][iVertex]->GetNode(); @@ -85,8 +84,8 @@ class CMultiGridGeometry final : public CGeometry { /*--- Compute area parent by taking into account only volumes that are on the marker. ---*/ for (auto iChildren = 0u; iChildren < nodes->GetnChildren_CV(Point_Coarse); iChildren++) { const auto Point_Fine = nodes->GetChildren_CV(Point_Coarse, iChildren); - const auto isVertex = fine_grid->nodes->GetDomain(Point_Fine) && - (fine_grid->nodes->GetVertex(Point_Fine, val_marker) != -1); + const auto isVertex = + fine_grid->nodes->GetDomain(Point_Fine) && (fine_grid->nodes->GetVertex(Point_Fine, val_marker) != -1); if (isVertex) { Area_Parent += fine_grid->nodes->GetVolume(Point_Fine); } @@ -97,8 +96,8 @@ class CMultiGridGeometry final : public CGeometry { /*--- Loop again to average coarser value. ---*/ for (auto iChildren = 0u; iChildren < nodes->GetnChildren_CV(Point_Coarse); iChildren++) { const auto Point_Fine = nodes->GetChildren_CV(Point_Coarse, iChildren); - const auto isVertex = fine_grid->nodes->GetDomain(Point_Fine) && - (fine_grid->nodes->GetVertex(Point_Fine, val_marker) != -1); + const auto isVertex = + fine_grid->nodes->GetDomain(Point_Fine) && (fine_grid->nodes->GetVertex(Point_Fine, val_marker) != -1); if (isVertex) { const auto Vertex_Fine = fine_grid->nodes->GetVertex(Point_Fine, val_marker); const auto Area_Children = fine_grid->nodes->GetVolume(Point_Fine); @@ -109,15 +108,14 @@ class CMultiGridGeometry final : public CGeometry { /*--- Set the value at the coarse level. ---*/ wall_quantity.Set(iVertex, Quantity_Coarse); } - } -public: + public: /*--- This is to suppress Woverloaded-virtual, omitting it has no negative impact. ---*/ - using CGeometry::SetVertex; - using CGeometry::SetControlVolume; using CGeometry::SetBoundControlVolume; + using CGeometry::SetControlVolume; using CGeometry::SetPoint_Connectivity; + using CGeometry::SetVertex; /*! * \brief Constructor of the class. @@ -125,79 +123,78 @@ class CMultiGridGeometry final : public CGeometry { * \param[in] config - Definition of the particular problem. * \param[in] iMesh - Level of the multigrid. */ - CMultiGridGeometry(CGeometry *fine_grid, CConfig *config, unsigned short iMesh); + CMultiGridGeometry(CGeometry* fine_grid, CConfig* config, unsigned short iMesh); /*! * \brief Set boundary vertex. * \param[in] fine_grid - Geometrical definition of the problem. * \param[in] config - Definition of the particular problem. */ - void SetVertex(const CGeometry *fine_grid, const CConfig *config) override; + void SetVertex(const CGeometry* fine_grid, const CConfig* config) override; /*! * \brief Set points which surround a point. * \param[in] fine_grid - Geometrical definition of the child grid. */ - void SetPoint_Connectivity(const CGeometry *fine_grid) override; + void SetPoint_Connectivity(const CGeometry* fine_grid) override; /*! * \brief Set the edge structure of the agglomerated control volume. * \param[in] fine_grid - Geometrical definition of the problem. * \param[in] action - Allocate or not the new elements. */ - void SetControlVolume(const CGeometry *fine_grid, unsigned short action) override; + void SetControlVolume(const CGeometry* fine_grid, unsigned short action) override; /*! * \brief Set boundary vertex structure of the agglomerated control volume. * \param[in] fine_grid - Geometrical definition of the problem. * \param[in] action - Allocate or not the new elements. */ - void SetBoundControlVolume(const CGeometry *fine_grid, unsigned short action) override; + void SetBoundControlVolume(const CGeometry* fine_grid, unsigned short action) override; /*! * \brief Set a representative coordinates of the agglomerated control volume. * \param[in] fine_grid - Geometrical definition of the problem. */ - void SetCoord(const CGeometry *fine_grid) override; + void SetCoord(const CGeometry* fine_grid) override; /*! * \brief Set the grid velocity at each node in the coarse mesh level based * on a restriction from a finer mesh. * \param[in] fine_grid - Geometry container for the finer mesh level. */ - void SetRestricted_GridVelocity(const CGeometry *fine_grid) override; + void SetRestricted_GridVelocity(const CGeometry* fine_grid) override; /*! * \brief Find and store the closest neighbor to a vertex. * \param[in] config - Definition of the particular problem. */ - void FindNormal_Neighbor(const CConfig *config) override; + void FindNormal_Neighbor(const CConfig* config) override; /*! * \brief Mach the near field boundary condition. * \param[in] config - Definition of the particular problem. */ - void MatchActuator_Disk(const CConfig *config) override; + void MatchActuator_Disk(const CConfig* config) override; /*! * \brief Mach the periodic boundary conditions. * \param[in] config - Definition of the particular problem. * \param[in] val_periodic - Index of the first periodic face in a pair. */ - void MatchPeriodic(const CConfig *config, unsigned short val_periodic) override; + void MatchPeriodic(const CConfig* config, unsigned short val_periodic) override; /*! - * \brief Set a representative wall normal heat flux of the agglomerated control volume on a particular boundary marker. - * \param[in] fine_grid - Geometrical definition of the problem. - * \param[in] val_marker - Index of the boundary marker. + * \brief Set a representative wall normal heat flux of the agglomerated control volume on a particular boundary + * marker. \param[in] fine_grid - Geometrical definition of the problem. \param[in] val_marker - Index of the boundary + * marker. */ - void SetMultiGridWallHeatFlux(const CGeometry *fine_grid, unsigned short val_marker) override; + void SetMultiGridWallHeatFlux(const CGeometry* fine_grid, unsigned short val_marker) override; /*! * \brief Set a representative wall temperature of the agglomerated control volume on a particular boundary marker. * \param[in] fine_grid - Geometrical definition of the problem. * \param[in] val_marker - Index of the boundary marker. */ - void SetMultiGridWallTemperature(const CGeometry *fine_grid, unsigned short val_marker) override; - + void SetMultiGridWallTemperature(const CGeometry* fine_grid, unsigned short val_marker) override; }; diff --git a/Common/include/geometry/CMultiGridQueue.hpp b/Common/include/geometry/CMultiGridQueue.hpp index 5865c36b687..3e75e80af1a 100644 --- a/Common/include/geometry/CMultiGridQueue.hpp +++ b/Common/include/geometry/CMultiGridQueue.hpp @@ -40,19 +40,21 @@ using namespace std; * \author F. Palacios */ class CMultiGridQueue { -private: + private: using QueueType = CFastFindAndEraseQueue<>; - vector QueueCV; /*!< \brief Queue structure to choose the next control volume in the agglomeration process. */ - vector Priority; /*!< \brief The priority is based on the number of pre-agglomerated neighbors. */ - vector RightCV; /*!< \brief In the lowest priority there are some CV that can not be agglomerated, this is the way to identify them. */ - const unsigned long nPoint = 0; /*!< \brief Total number of points. */ + vector + QueueCV; /*!< \brief Queue structure to choose the next control volume in the agglomeration process. */ + vector Priority; /*!< \brief The priority is based on the number of pre-agglomerated neighbors. */ + vector RightCV; /*!< \brief In the lowest priority there are some CV that can not be agglomerated, this is the + way to identify them. */ + const unsigned long nPoint = 0; /*!< \brief Total number of points. */ /*! * \brief Throw error with error message that the point is not in the priority list. */ void ThrowPointNotInListError(unsigned long iPoint) const; -public: + public: /*! * \brief Constructor of the class. * \param[in] npoint - Number of control volumes. @@ -111,8 +113,10 @@ class CMultiGridQueue { * \return Index of the new control volume. */ inline long NextCV(void) const { - if (!QueueCV.empty()) return QueueCV.back().front(); - else return -1; + if (!QueueCV.empty()) + return QueueCV.back().front(); + else + return -1; } /*! @@ -133,6 +137,5 @@ class CMultiGridQueue { * \param[in] updatePoint - Index of the new point. * \param[in] fineGrid - Fine grid geometry. */ - void Update(unsigned long updatePoint, CGeometry *fineGrid); - + void Update(unsigned long updatePoint, CGeometry* fineGrid); }; diff --git a/Common/include/geometry/CPhysicalGeometry.hpp b/Common/include/geometry/CPhysicalGeometry.hpp index b69bc67da78..b02db55c0a4 100644 --- a/Common/include/geometry/CPhysicalGeometry.hpp +++ b/Common/include/geometry/CPhysicalGeometry.hpp @@ -31,87 +31,71 @@ #include "meshreader/CMeshReaderFVM.hpp" #include "../containers/C2DContainer.hpp" - /*! * \class CPhysicalGeometry * \brief Class for reading a defining the primal grid which is read from the grid file in .su2 or .cgns format. * \author F. Palacios, T. Economon, J. Alonso */ class CPhysicalGeometry final : public CGeometry { - unordered_map - Global_to_Local_Point; /*!< \brief Global-local indexation for the points. */ - long *Local_to_Global_Point{nullptr}; /*!< \brief Local-global indexation for the points. */ - unsigned long *adj_counter{nullptr}; /*!< \brief Adjacency counter. */ - unsigned long **adjacent_elem{nullptr}; /*!< \brief Adjacency element list. */ - su2activematrix Sensitivity; /*!< \brief Matrix holding the sensitivities at each point. */ + Global_to_Local_Point; /*!< \brief Global-local indexation for the points. */ + long* Local_to_Global_Point{nullptr}; /*!< \brief Local-global indexation for the points. */ + unsigned long* adj_counter{nullptr}; /*!< \brief Adjacency counter. */ + unsigned long** adjacent_elem{nullptr}; /*!< \brief Adjacency element list. */ + su2activematrix Sensitivity; /*!< \brief Matrix holding the sensitivities at each point. */ vector > Neighbors; unordered_map Color_List; vector Marker_Tags; - unsigned long nLocal_Point{0}, - nLocal_PointDomain{0}, - nLocal_PointGhost{0}, - nLocal_PointPeriodic{0}, - nLocal_Elem{0}, - nLocal_Bound_Elem{0}, - nGlobal_Elem{0}, - nGlobal_Bound_Elem{0}, - nLocal_Line{0}, - nLocal_BoundTria{0}, - nLocal_BoundQuad{0}, - nLinear_Line{0}, - nLinear_BoundTria{0}, - nLinear_BoundQuad{0}, - nLocal_Tria{0}, - nLocal_Quad{0}, - nLocal_Tetr{0}, - nLocal_Hexa{0}, - nLocal_Pris{0}, - nLocal_Pyra{0}; + unsigned long nLocal_Point{0}, nLocal_PointDomain{0}, nLocal_PointGhost{0}, nLocal_PointPeriodic{0}, nLocal_Elem{0}, + nLocal_Bound_Elem{0}, nGlobal_Elem{0}, nGlobal_Bound_Elem{0}, nLocal_Line{0}, nLocal_BoundTria{0}, + nLocal_BoundQuad{0}, nLinear_Line{0}, nLinear_BoundTria{0}, nLinear_BoundQuad{0}, nLocal_Tria{0}, nLocal_Quad{0}, + nLocal_Tetr{0}, nLocal_Hexa{0}, nLocal_Pris{0}, nLocal_Pyra{0}; unsigned long nMarker_Global{0}; - su2double *Local_Coords{nullptr}; - unsigned long *Local_Points{nullptr}; - unsigned long *Local_Colors{nullptr}; - unsigned long *Conn_Line{nullptr}; - unsigned long *Conn_BoundTria{nullptr}; - unsigned long *Conn_BoundQuad{nullptr}; - unsigned long *Conn_Line_Linear{nullptr}; - unsigned long *Conn_BoundTria_Linear{nullptr}; - unsigned long *Conn_BoundQuad_Linear{nullptr}; - unsigned long *Conn_Tria{nullptr}; - unsigned long *Conn_Quad{nullptr}; - unsigned long *Conn_Tetr{nullptr}; - unsigned long *Conn_Hexa{nullptr}; - unsigned long *Conn_Pris{nullptr}; - unsigned long *Conn_Pyra{nullptr}; - unsigned long *ID_Line{nullptr}; - unsigned long *ID_BoundTria{nullptr}; - unsigned long *ID_BoundQuad{nullptr}; - unsigned long *ID_Line_Linear{nullptr}; - unsigned long *ID_BoundTria_Linear{nullptr}; - unsigned long *ID_BoundQuad_Linear{nullptr}; - unsigned long *ID_Tria{nullptr}; - unsigned long *ID_Quad{nullptr}; - unsigned long *ID_Tetr{nullptr}; - unsigned long *ID_Hexa{nullptr}; - unsigned long *ID_Pris{nullptr}; - unsigned long *ID_Pyra{nullptr}; - unsigned long *Elem_ID_Line{nullptr}; - unsigned long *Elem_ID_BoundTria{nullptr}; - unsigned long *Elem_ID_BoundQuad{nullptr}; - unsigned long *Elem_ID_Line_Linear{nullptr}; - unsigned long *Elem_ID_BoundTria_Linear{nullptr}; - unsigned long *Elem_ID_BoundQuad_Linear{nullptr}; - - su2double Streamwise_Periodic_RefNode[MAXNDIM] = {0}; /*!< \brief Coordinates of the reference node [m] on the receiving periodic marker, for recovered pressure/temperature computation only.*/ - -public: + su2double* Local_Coords{nullptr}; + unsigned long* Local_Points{nullptr}; + unsigned long* Local_Colors{nullptr}; + unsigned long* Conn_Line{nullptr}; + unsigned long* Conn_BoundTria{nullptr}; + unsigned long* Conn_BoundQuad{nullptr}; + unsigned long* Conn_Line_Linear{nullptr}; + unsigned long* Conn_BoundTria_Linear{nullptr}; + unsigned long* Conn_BoundQuad_Linear{nullptr}; + unsigned long* Conn_Tria{nullptr}; + unsigned long* Conn_Quad{nullptr}; + unsigned long* Conn_Tetr{nullptr}; + unsigned long* Conn_Hexa{nullptr}; + unsigned long* Conn_Pris{nullptr}; + unsigned long* Conn_Pyra{nullptr}; + unsigned long* ID_Line{nullptr}; + unsigned long* ID_BoundTria{nullptr}; + unsigned long* ID_BoundQuad{nullptr}; + unsigned long* ID_Line_Linear{nullptr}; + unsigned long* ID_BoundTria_Linear{nullptr}; + unsigned long* ID_BoundQuad_Linear{nullptr}; + unsigned long* ID_Tria{nullptr}; + unsigned long* ID_Quad{nullptr}; + unsigned long* ID_Tetr{nullptr}; + unsigned long* ID_Hexa{nullptr}; + unsigned long* ID_Pris{nullptr}; + unsigned long* ID_Pyra{nullptr}; + unsigned long* Elem_ID_Line{nullptr}; + unsigned long* Elem_ID_BoundTria{nullptr}; + unsigned long* Elem_ID_BoundQuad{nullptr}; + unsigned long* Elem_ID_Line_Linear{nullptr}; + unsigned long* Elem_ID_BoundTria_Linear{nullptr}; + unsigned long* Elem_ID_BoundQuad_Linear{nullptr}; + + su2double Streamwise_Periodic_RefNode[MAXNDIM] = { + 0}; /*!< \brief Coordinates of the reference node [m] on the receiving periodic marker, for recovered + pressure/temperature computation only.*/ + + public: /*--- This is to suppress Woverloaded-virtual, omitting it has no negative impact. ---*/ - using CGeometry::SetVertex; - using CGeometry::SetControlVolume; using CGeometry::SetBoundControlVolume; + using CGeometry::SetControlVolume; using CGeometry::SetPoint_Connectivity; + using CGeometry::SetVertex; /*! * \brief Constructor of the class. @@ -128,27 +112,27 @@ class CPhysicalGeometry final : public CGeometry { * \param[in] val_iZone - Domain to be read from the grid file. * \param[in] val_nZone - Total number of domains in the grid file. */ - CPhysicalGeometry(CConfig *config, unsigned short val_iZone, unsigned short val_nZone); + CPhysicalGeometry(CConfig* config, unsigned short val_iZone, unsigned short val_nZone); /*! * \overload * \brief Accepts a geometry container holding a linearly partitioned grid * with coloring performed by ParMETIS, and this routine distributes * the points and cells to all partitions based on the coloring. - * \param[in] geometry - Definition of the geometry container holding the initial linear partitions of the grid + coloring. - * \param[in] config - Definition of the particular problem. + * \param[in] geometry - Definition of the geometry container holding the initial linear partitions of the grid + + * coloring. \param[in] config - Definition of the particular problem. */ - CPhysicalGeometry(CGeometry *geometry, CConfig *config); + CPhysicalGeometry(CGeometry* geometry, CConfig* config); /*! * \overload * \brief Accepts a geometry container holding a linearly partitioned grid * with coloring performed by ParMETIS, and this routine distributes * the points and cells to all partitions based on the coloring. - * \param[in] geometry - Definition of the geometry container holding the initial linear partitions of the grid + coloring. - * \param[in] config - Definition of the particular problem. + * \param[in] geometry - Definition of the geometry container holding the initial linear partitions of the grid + + * coloring. \param[in] config - Definition of the particular problem. */ - CPhysicalGeometry(CGeometry *geometry, CConfig *config, bool val_flag); + CPhysicalGeometry(CGeometry* geometry, CConfig* config, bool val_flag); /*! * \brief Destructor of the class. @@ -156,18 +140,18 @@ class CPhysicalGeometry final : public CGeometry { ~CPhysicalGeometry(void) override; /*! - * \brief Distributes the coloring from ParMETIS so that each rank has complete information about the local grid points. - * \param[in] geometry - Definition of the geometry container holding the initial linear partitions of the grid + coloring. - * \param[in] config - Definition of the particular problem. + * \brief Distributes the coloring from ParMETIS so that each rank has complete information about the local grid + * points. \param[in] geometry - Definition of the geometry container holding the initial linear partitions of the + * grid + coloring. \param[in] config - Definition of the particular problem. */ - void DistributeColoring(const CConfig *config, CGeometry *geometry); + void DistributeColoring(const CConfig* config, CGeometry* geometry); /*! * \brief Distribute the grid points, including ghost points, across all ranks based on a ParMETIS coloring. * \param[in] config - Definition of the particular problem. * \param[in] geometry - Geometrical definition of the problem. */ - void DistributePoints(const CConfig *config, CGeometry *geometry); + void DistributePoints(const CConfig* config, CGeometry* geometry); /*! * \brief Distribute the connectivity for a single volume element type across all ranks based on a ParMETIS coloring. @@ -175,22 +159,21 @@ class CPhysicalGeometry final : public CGeometry { * \param[in] geometry - Geometrical definition of the problem. * \param[in] Elem_Type - VTK index of the element type being distributed. */ - void DistributeVolumeConnectivity(const CConfig *config, CGeometry *geometry, unsigned short Elem_Type); + void DistributeVolumeConnectivity(const CConfig* config, CGeometry* geometry, unsigned short Elem_Type); /*! - * \brief Distribute the connectivity for a single surface element type in all markers across all ranks based on a ParMETIS coloring. - * \param[in] config - Definition of the particular problem. - * \param[in] geometry - Geometrical definition of the problem. - * \param[in] Elem_Type - VTK index of the element type being distributed. + * \brief Distribute the connectivity for a single surface element type in all markers across all ranks based on a + * ParMETIS coloring. \param[in] config - Definition of the particular problem. \param[in] geometry - Geometrical + * definition of the problem. \param[in] Elem_Type - VTK index of the element type being distributed. */ - void DistributeSurfaceConnectivity(CConfig *config, CGeometry *geometry, unsigned short Elem_Type); + void DistributeSurfaceConnectivity(CConfig* config, CGeometry* geometry, unsigned short Elem_Type); /*! * \brief Broadcast the marker tags for all boundaries from the master rank to all other ranks. * \param[in] config - Definition of the particular problem. * \param[in] geometry - Geometrical definition of the problem. */ - void DistributeMarkerTags(CConfig *config, CGeometry *geometry); + void DistributeMarkerTags(CConfig* config, CGeometry* geometry); /*! * \brief Partition the marker connectivity held on the master rank according to a linear partitioning. @@ -198,46 +181,40 @@ class CPhysicalGeometry final : public CGeometry { * \param[in] geometry - Geometrical definition of the problem. * \param[in] Elem_Type - VTK index of the element type being distributed. */ - void PartitionSurfaceConnectivity(CConfig *config, CGeometry *geometry, unsigned short Elem_Type); + void PartitionSurfaceConnectivity(CConfig* config, CGeometry* geometry, unsigned short Elem_Type); /*! * \brief Load the local grid points after partitioning (owned and ghost) into the geometry class objects. * \param[in] config - Definition of the particular problem. * \param[in] geometry - Geometrical definition of the problem. */ - void LoadPoints(CConfig *config, CGeometry *geometry); + void LoadPoints(CConfig* config, CGeometry* geometry); /*! * \brief Load the local volume elements after partitioning (owned and ghost) into the geometry class objects. * \param[in] config - Definition of the particular problem. * \param[in] geometry - Geometrical definition of the problem. */ - void LoadVolumeElements(CConfig *config, CGeometry *geometry); + void LoadVolumeElements(CConfig* config, CGeometry* geometry); /*! * \brief Load the local surface elements after partitioning (owned and ghost) into the geometry class objects. * \param[in] config - Definition of the particular problem. * \param[in] geometry - Geometrical definition of the problem. */ - void LoadSurfaceElements(CConfig *config, CGeometry *geometry); + void LoadSurfaceElements(CConfig* config, CGeometry* geometry); /*! * \brief Routine to launch non-blocking sends and recvs amongst all processors. * \param[in] bufSend - Buffer of data to be sent. - * \param[in] nElemSend - Array containing the number of elements to send to other processors in cumulative storage format. - * \param[in] sendReq - Array of MPI send requests. - * \param[in] bufRecv - Buffer of data to be received. - * \param[in] nElemSend - Array containing the number of elements to receive from other processors in cumulative storage format. - * \param[in] sendReq - Array of MPI recv requests. - * \param[in] countPerElem - Pieces of data per element communicated. - */ - void InitiateCommsAll(void *bufSend, - const int *nElemSend, - SU2_MPI::Request *sendReq, - void *bufRecv, - const int *nElemRecv, - SU2_MPI::Request *recvReq, - unsigned short countPerElem, + * \param[in] nElemSend - Array containing the number of elements to send to other processors in cumulative storage + * format. \param[in] sendReq - Array of MPI send requests. \param[in] bufRecv - Buffer of data to be received. + * \param[in] nElemSend - Array containing the number of elements to receive from other processors in cumulative + * storage format. \param[in] sendReq - Array of MPI recv requests. \param[in] countPerElem - Pieces of data per + * element communicated. + */ + void InitiateCommsAll(void* bufSend, const int* nElemSend, SU2_MPI::Request* sendReq, void* bufRecv, + const int* nElemRecv, SU2_MPI::Request* recvReq, unsigned short countPerElem, unsigned short commType); /*! @@ -247,10 +224,7 @@ class CPhysicalGeometry final : public CGeometry { * \param[in] nRecvs - Number of receives to be completed. * \param[in] sendReq - Array of MPI recv requests. */ - void CompleteCommsAll(int nSends, - SU2_MPI::Request *sendReq, - int nRecvs, - SU2_MPI::Request *recvReq); + void CompleteCommsAll(int nSends, SU2_MPI::Request* sendReq, int nRecvs, SU2_MPI::Request* recvReq); /*! * \brief Routine to compute the initial linear partitioning offset counts and store in persistent data structures. @@ -269,19 +243,19 @@ class CPhysicalGeometry final : public CGeometry { * \brief Routine to sort the adjacency for ParMETIS for graph partitioning in parallel. * \param[in] config - Definition of the particular problem. */ - void SortAdjacency(const CConfig *config); + void SortAdjacency(const CConfig* config); /*! * \brief Set the send receive boundaries of the grid. * \param[in] config - Definition of the particular problem. */ - void SetSendReceive(const CConfig *config) override; + void SetSendReceive(const CConfig* config) override; /*! * \brief Set the send receive boundaries of the grid. * \param[in] config - Definition of the particular problem. */ - void SetBoundaries(CConfig *config) override; + void SetBoundaries(CConfig* config) override; /*! * \brief Set the local index that correspond with the global numbering index. @@ -295,8 +269,7 @@ class CPhysicalGeometry final : public CGeometry { */ inline long GetGlobal_to_Local_Point(unsigned long val_ipoint) const override { auto it = Global_to_Local_Point.find(val_ipoint); - if (it != Global_to_Local_Point.cend()) - return it->second; + if (it != Global_to_Local_Point.cend()) return it->second; return -1; } @@ -309,7 +282,7 @@ class CPhysicalGeometry final : public CGeometry { * \param[in] val_iZone - Domain to be read from the grid file. * \param[in] val_nZone - Total number of domains in the grid file. */ - void Read_Mesh_FVM(CConfig *config, string val_mesh_filename, unsigned short val_iZone, unsigned short val_nZone); + void Read_Mesh_FVM(CConfig* config, string val_mesh_filename, unsigned short val_iZone, unsigned short val_nZone); /*! * \brief Reads for the FEM solver the geometry of the grid and adjust the boundary @@ -319,7 +292,8 @@ class CPhysicalGeometry final : public CGeometry { * \param[in] val_iZone - Domain to be read from the grid file. * \param[in] val_nZone - Total number of domains in the grid file. */ - void Read_SU2_Format_Parallel_FEM(CConfig *config, string val_mesh_filename, unsigned short val_iZone, unsigned short val_nZone); + void Read_SU2_Format_Parallel_FEM(CConfig* config, string val_mesh_filename, unsigned short val_iZone, + unsigned short val_nZone); /*! * \brief Reads for the FEM solver the geometry of the grid and adjust the boundary @@ -329,34 +303,35 @@ class CPhysicalGeometry final : public CGeometry { * \param[in] val_iZone - Domain to be read from the grid file. * \param[in] val_nZone - Total number of domains in the grid file. */ - void Read_CGNS_Format_Parallel_FEM(CConfig *config, string val_mesh_filename, unsigned short val_iZone, unsigned short val_nZone); + void Read_CGNS_Format_Parallel_FEM(CConfig* config, string val_mesh_filename, unsigned short val_iZone, + unsigned short val_nZone); /*! * \brief Routine to load the CGNS grid points from a single zone into the proper SU2 data structures. * \param[in] config - definition of the particular problem. * \param[in] mesh - mesh reader object containing the current zone data. */ - void LoadLinearlyPartitionedPoints(CConfig *config, CMeshReaderFVM *mesh); + void LoadLinearlyPartitionedPoints(CConfig* config, CMeshReaderFVM* mesh); /*! * \brief Loads the interior volume elements from the mesh reader object into the primal element data structures. * \param[in] config - definition of the particular problem. * \param[in] mesh - mesh reader object containing the current zone data. */ - void LoadLinearlyPartitionedVolumeElements(CConfig *config, CMeshReaderFVM *mesh); + void LoadLinearlyPartitionedVolumeElements(CConfig* config, CMeshReaderFVM* mesh); /*! * \brief Loads the boundary elements (markers) from the mesh reader object into the primal element data structures. * \param[in] config - definition of the particular problem. * \param[in] mesh - mesh reader object containing the current zone data. */ - void LoadUnpartitionedSurfaceElements(CConfig *config, CMeshReaderFVM *mesh); + void LoadUnpartitionedSurfaceElements(CConfig* config, CMeshReaderFVM* mesh); /*! - * \brief Prepares the grid point adjacency based on a linearly partitioned mesh object needed by ParMETIS for graph partitioning in parallel. - * \param[in] config - Definition of the particular problem. + * \brief Prepares the grid point adjacency based on a linearly partitioned mesh object needed by ParMETIS for graph + * partitioning in parallel. \param[in] config - Definition of the particular problem. */ - void PrepareAdjacency(const CConfig *config); + void PrepareAdjacency(const CConfig* config); /*! * \brief Find repeated nodes between two elements to identify the common face. @@ -366,14 +341,14 @@ class CPhysicalGeometry final : public CGeometry { * \param[in] face_second_elem - Index of the common face for the second element. * \return It provides 0 or 1 depending if there is a common face or not. */ - bool FindFace(unsigned long first_elem, unsigned long second_elem, unsigned short &face_first_elem, - unsigned short &face_second_elem) override; + bool FindFace(unsigned long first_elem, unsigned long second_elem, unsigned short& face_first_elem, + unsigned short& face_second_elem) override; /*! * \brief Compute surface area (positive z-direction) for force coefficient non-dimensionalization. * \param[in] config - Definition of the particular problem. */ - void SetPositive_ZArea(CConfig *config) override; + void SetPositive_ZArea(CConfig* config) override; /*! * \brief Set points which surround a point. @@ -384,7 +359,7 @@ class CPhysicalGeometry final : public CGeometry { * \brief Set a renumbering using a Reverse Cuthill-McKee Algorithm * \param[in] config - Definition of the particular problem. */ - void SetRCM_Ordering(CConfig *config) override; + void SetRCM_Ordering(CConfig* config) override; /*! * \brief Set elements which surround an element. @@ -400,70 +375,70 @@ class CPhysicalGeometry final : public CGeometry { * \brief Set boundary vertex. * \param[in] config - Definition of the particular problem. */ - void SetVertex(const CConfig *config) override; + void SetVertex(const CConfig* config) override; /*! * \brief Set number of span wise level for turbomachinery computation. * \param[in] config - Definition of the particular problem. */ - void ComputeNSpan(CConfig *config, unsigned short val_iZone, unsigned short marker_flag, bool allocate) override; + void ComputeNSpan(CConfig* config, unsigned short val_iZone, unsigned short marker_flag, bool allocate) override; /*! * \brief Set turbo boundary vertex. * \param[in] config - Definition of the particular problem. */ - void SetTurboVertex(CConfig *config,unsigned short val_iZone, unsigned short marker_flag, bool allocate) override; + void SetTurboVertex(CConfig* config, unsigned short val_iZone, unsigned short marker_flag, bool allocate) override; /*! - * \brief update turbo boundary vertex. - * \param[in] config - Definition of the particular problem. - */ - void UpdateTurboVertex(CConfig *config,unsigned short val_iZone, unsigned short marker_flag) override; + * \brief update turbo boundary vertex. + * \param[in] config - Definition of the particular problem. + */ + void UpdateTurboVertex(CConfig* config, unsigned short val_iZone, unsigned short marker_flag) override; /*! * \brief Set turbo boundary vertex. * \param[in] config - Definition of the particular problem. */ - void SetAvgTurboValue(CConfig *config, unsigned short val_iZone, unsigned short marker_flag, bool allocate) override; + void SetAvgTurboValue(CConfig* config, unsigned short val_iZone, unsigned short marker_flag, bool allocate) override; /*! * \brief Set turbo boundary vertex. * \param[in] config - Definition of the particular problem. */ - void GatherInOutAverageValues(CConfig *config, bool allocate) override; + void GatherInOutAverageValues(CConfig* config, bool allocate) override; /*! * \brief Set the edge structure of the control volume. * \param[in] config - Definition of the particular problem. * \param[in] action - Allocate or not the new elements. */ - void SetControlVolume(CConfig *config, unsigned short action) override; + void SetControlVolume(CConfig* config, unsigned short action) override; /*! * \brief Visualize the structure of the control volume(s). * \param[in] config - Definition of the particular problem. */ - void VisualizeControlVolume(const CConfig *config) const override; + void VisualizeControlVolume(const CConfig* config) const override; /*! * \brief Mach the near field boundary condition. * \param[in] config - Definition of the particular problem. */ - void MatchActuator_Disk(const CConfig *config) override; + void MatchActuator_Disk(const CConfig* config) override; /*! * \brief Mach the periodic boundary conditions. * \param[in] config - Definition of the particular problem. * \param[in] val_periodic - Index of the first periodic face in a pair. */ - void MatchPeriodic(const CConfig *config, unsigned short val_periodic) override; + void MatchPeriodic(const CConfig* config, unsigned short val_periodic) override; /*! * \brief Set boundary vertex structure of the control volume. * \param[in] config - Definition of the particular problem. * \param[in] action - Allocate or not the new elements. */ - void SetBoundControlVolume(const CConfig *config, unsigned short action) override; + void SetBoundControlVolume(const CConfig* config, unsigned short action) override; /*! * \brief Set the maximum cell-center to cell-center distance for CVs. @@ -486,31 +461,31 @@ class CPhysicalGeometry final : public CGeometry { * information is going to be stored. * \param[in] new_file - Create a new file. */ - void SetBoundTecPlot(char mesh_filename[MAX_STRING_SIZE], bool new_file, CConfig *config) override; + void SetBoundTecPlot(char mesh_filename[MAX_STRING_SIZE], bool new_file, CConfig* config) override; /*! * \brief Check the volume element orientation. * \param[in] config - Definition of the particular problem. */ - void Check_IntElem_Orientation(const CConfig *config) override; + void Check_IntElem_Orientation(const CConfig* config) override; /*! * \brief Check the volume element orientation. * \param[in] config - Definition of the particular problem. */ - void Check_BoundElem_Orientation(const CConfig *config) override; + void Check_BoundElem_Orientation(const CConfig* config) override; /*! * \brief Set the domains for grid grid partitioning using ParMETIS. * \param[in] config - Definition of the particular problem. */ - void SetColorGrid_Parallel(const CConfig *config) override; + void SetColorGrid_Parallel(const CConfig* config) override; /*! * \brief Set the domains for FEM grid partitioning using ParMETIS. * \param[in] config - Definition of the particular problem. */ - void SetColorFEMGrid_Parallel(CConfig *config) override; + void SetColorFEMGrid_Parallel(CConfig* config) override; /*! * \brief Compute the weights of the FEM graph for ParMETIS. @@ -522,45 +497,41 @@ class CPhysicalGeometry final : public CGeometry { * \param[out] vwgt - Weights of the vertices of the graph, i.e. the elements. * \param[out] adjwgt - Weights of the edges of the graph. */ - void ComputeFEMGraphWeights( - CConfig *config, - const vector &localFaces, - const vector > &adjacency, - const map &mapExternalElemIDToTimeLevel, - vector &vwgt, - vector > &adjwgt); + void ComputeFEMGraphWeights(CConfig* config, const vector& localFaces, + const vector >& adjacency, + const map& mapExternalElemIDToTimeLevel, + vector& vwgt, vector >& adjwgt); /*! * \brief Determine the donor elements for the boundary elements on viscous wall boundaries when wall functions are used. * \param[in] config - Definition of the particular problem. */ - void DetermineDonorElementsWallFunctions(CConfig *config); + void DetermineDonorElementsWallFunctions(CConfig* config); /*! * \brief Determine whether or not the Jacobians of the elements and faces are constant and a length scale of the elements. * \param[in] config - Definition of the particular problem. */ - void DetermineFEMConstantJacobiansAndLenScale(CConfig *config); + void DetermineFEMConstantJacobiansAndLenScale(CConfig* config); /*! * \brief Determine the neighboring information for periodic faces of a FEM grid. * \param[in] config - Definition of the particular problem. * \param[in,out] localFaces - Vector, which contains the element faces of this rank. */ - void DeterminePeriodicFacesFEMGrid(CConfig *config, - vector &localFaces); + void DeterminePeriodicFacesFEMGrid(CConfig* config, vector& localFaces); /*! * \brief Determine the time level of the elements when time accurate local time stepping is employed. * \param[in] config - Definition of the particular problem. * \param[in] localFaces - Vector, which contains the element faces of this rank. - * \param[out] mapExternalElemIDToTimeLevel - Map from the external element ID's to their time level and number of DOFs. + * \param[out] mapExternalElemIDToTimeLevel - Map from the external element ID's to their time level and number of + * DOFs. */ - void DetermineTimeLevelElements(CConfig *config, - const vector &localFaces, - map &mapExternalElemIDToTimeLevel); + void DetermineTimeLevelElements(CConfig* config, const vector& localFaces, + map& mapExternalElemIDToTimeLevel); /*! * \brief Do an implicit smoothing of the grid coordinates. @@ -568,165 +539,166 @@ class CPhysicalGeometry final : public CGeometry { * \param[in] val_smooth_coeff - Relaxation factor. * \param[in] config - Definition of the particular problem. */ - void SetCoord_Smoothing(unsigned short val_nSmooth, su2double val_smooth_coeff, CConfig *config) override; + void SetCoord_Smoothing(unsigned short val_nSmooth, su2double val_smooth_coeff, CConfig* config) override; /*! * \brief Compute 3 grid quality metrics: orthogonality angle, dual cell aspect ratio, and dual cell volume ratio. * \param[in] config - Definition of the particular problem. */ - void ComputeMeshQualityStatistics(const CConfig *config) override; + void ComputeMeshQualityStatistics(const CConfig* config) override; /*! * \brief Find and store the closest neighbor to a vertex. * \param[in] config - Definition of the particular problem. */ - void FindNormal_Neighbor(const CConfig *config) override; + void FindNormal_Neighbor(const CConfig* config) override; /*! * \brief Read the sensitivity from an input file. * \param[in] config - Definition of the particular problem. */ - void SetBoundSensitivity(CConfig *config) override; + void SetBoundSensitivity(CConfig* config) override; /*! * \brief Compute the maximum thickness of an airfoil. * \return Maximum thickness at a particular seccion. */ - su2double Compute_MaxThickness(su2double *Plane_P0, su2double *Plane_Normal, CConfig *config, vector &Xcoord_Airfoil, - vector &Ycoord_Airfoil, vector &Zcoord_Airfoil) override; + su2double Compute_MaxThickness(su2double* Plane_P0, su2double* Plane_Normal, CConfig* config, + vector& Xcoord_Airfoil, vector& Ycoord_Airfoil, + vector& Zcoord_Airfoil) override; /*! * \brief Compute the twist of an airfoil. * \return Twist at a particular seccion. */ - su2double Compute_Twist(su2double *Plane_P0, su2double *Plane_Normal, vector &Xcoord_Airfoil, - vector &Ycoord_Airfoil, vector &Zcoord_Airfoil) override; + su2double Compute_Twist(su2double* Plane_P0, su2double* Plane_Normal, vector& Xcoord_Airfoil, + vector& Ycoord_Airfoil, vector& Zcoord_Airfoil) override; /*! * \brief Compute the leading/trailing edge location of an airfoil. */ - void Compute_Wing_LeadingTrailing(su2double *LeadingEdge, su2double *TrailingEdge, su2double *Plane_P0, - su2double *Plane_Normal, vector &Xcoord_Airfoil, - vector &Ycoord_Airfoil, vector &Zcoord_Airfoil) override; + void Compute_Wing_LeadingTrailing(su2double* LeadingEdge, su2double* TrailingEdge, su2double* Plane_P0, + su2double* Plane_Normal, vector& Xcoord_Airfoil, + vector& Ycoord_Airfoil, vector& Zcoord_Airfoil) override; /*! - * \brief Compute the leading/trailing edge location of a fuselage. - */ - void Compute_Fuselage_LeadingTrailing(su2double *LeadingEdge, su2double *TrailingEdge, su2double *Plane_P0, - su2double *Plane_Normal, vector &Xcoord_Airfoil, - vector &Ycoord_Airfoil, vector &Zcoord_Airfoil) override; + * \brief Compute the leading/trailing edge location of a fuselage. + */ + void Compute_Fuselage_LeadingTrailing(su2double* LeadingEdge, su2double* TrailingEdge, su2double* Plane_P0, + su2double* Plane_Normal, vector& Xcoord_Airfoil, + vector& Ycoord_Airfoil, vector& Zcoord_Airfoil) override; /*! * \brief Compute the chord of an airfoil. * \return Chord of an airfoil. */ - su2double Compute_Chord(su2double *Plane_P0, su2double *Plane_Normal, vector &Xcoord_Airfoil, - vector &Ycoord_Airfoil, vector &Zcoord_Airfoil) override; + su2double Compute_Chord(su2double* Plane_P0, su2double* Plane_Normal, vector& Xcoord_Airfoil, + vector& Ycoord_Airfoil, vector& Zcoord_Airfoil) override; /*! * \brief Compute the chord of an airfoil. * \return Chord of an airfoil. */ - su2double Compute_Width(su2double *Plane_P0, su2double *Plane_Normal, vector &Xcoord_Airfoil, - vector &Ycoord_Airfoil, vector &Zcoord_Airfoil) override; + su2double Compute_Width(su2double* Plane_P0, su2double* Plane_Normal, vector& Xcoord_Airfoil, + vector& Ycoord_Airfoil, vector& Zcoord_Airfoil) override; /*! * \brief Compute the chord of an airfoil. * \return Chord of an airfoil. */ - su2double Compute_WaterLineWidth(su2double *Plane_P0, su2double *Plane_Normal, CConfig *config, vector &Xcoord_Airfoil, - vector &Ycoord_Airfoil, vector &Zcoord_Airfoil) override; + su2double Compute_WaterLineWidth(su2double* Plane_P0, su2double* Plane_Normal, CConfig* config, + vector& Xcoord_Airfoil, vector& Ycoord_Airfoil, + vector& Zcoord_Airfoil) override; /*! * \brief Compute the chord of an airfoil. * \return Chord of an airfoil. */ - su2double Compute_Height(su2double *Plane_P0, su2double *Plane_Normal, vector &Xcoord_Airfoil, - vector &Ycoord_Airfoil, vector &Zcoord_Airfoil) override; + su2double Compute_Height(su2double* Plane_P0, su2double* Plane_Normal, vector& Xcoord_Airfoil, + vector& Ycoord_Airfoil, vector& Zcoord_Airfoil) override; /*! * \brief Compute the chord of an airfoil. * \return Chord of an airfoil. */ - su2double Compute_LERadius(su2double *Plane_P0, su2double *Plane_Normal, vector &Xcoord_Airfoil, - vector &Ycoord_Airfoil, vector &Zcoord_Airfoil) override; + su2double Compute_LERadius(su2double* Plane_P0, su2double* Plane_Normal, vector& Xcoord_Airfoil, + vector& Ycoord_Airfoil, vector& Zcoord_Airfoil) override; /*! * \brief Compute the thickness of an airfoil. */ - su2double Compute_Thickness(su2double *Plane_P0, su2double *Plane_Normal, su2double Location, CConfig *config, vector &Xcoord_Airfoil, - vector &Ycoord_Airfoil, vector &Zcoord_Airfoil, su2double &ZLoc) override; + su2double Compute_Thickness(su2double* Plane_P0, su2double* Plane_Normal, su2double Location, CConfig* config, + vector& Xcoord_Airfoil, vector& Ycoord_Airfoil, + vector& Zcoord_Airfoil, su2double& ZLoc) override; /*! * \brief Compute the area of an airfoil. * \return Area of an airfoil. */ - su2double Compute_Area(su2double *Plane_P0, su2double *Plane_Normal, CConfig *config, vector &Xcoord_Airfoil, - vector &Ycoord_Airfoil, vector &Zcoord_Airfoil) override; + su2double Compute_Area(su2double* Plane_P0, su2double* Plane_Normal, CConfig* config, + vector& Xcoord_Airfoil, vector& Ycoord_Airfoil, + vector& Zcoord_Airfoil) override; /*! * \brief Compute the length of an airfoil. * \return Area of an airfoil. */ - su2double Compute_Length(su2double *Plane_P0, su2double *Plane_Normal, CConfig *config, vector &Xcoord_Airfoil, - vector &Ycoord_Airfoil, vector &Zcoord_Airfoil) override; + su2double Compute_Length(su2double* Plane_P0, su2double* Plane_Normal, CConfig* config, + vector& Xcoord_Airfoil, vector& Ycoord_Airfoil, + vector& Zcoord_Airfoil) override; /*! * \brief Compute the dihedral of a wing. * \return Dihedral at a particular seccion. */ - su2double Compute_Dihedral(su2double *LeadingEdge_im1, su2double *TrailingEdge_im1, - su2double *LeadingEdge_i, su2double *TrailingEdge_i) override; + su2double Compute_Dihedral(su2double* LeadingEdge_im1, su2double* TrailingEdge_im1, su2double* LeadingEdge_i, + su2double* TrailingEdge_i) override; /*! * \brief Compute the curvature of a wing. */ - su2double Compute_Curvature(su2double *LeadingEdge_im1, su2double *TrailingEdge_im1, - su2double *LeadingEdge_i, su2double *TrailingEdge_i, - su2double *LeadingEdge_ip1, su2double *TrailingEdge_ip1) override; + su2double Compute_Curvature(su2double* LeadingEdge_im1, su2double* TrailingEdge_im1, su2double* LeadingEdge_i, + su2double* TrailingEdge_i, su2double* LeadingEdge_ip1, + su2double* TrailingEdge_ip1) override; /*! * \brief Evaluate geometrical parameters of a wing. */ - void Compute_Wing(CConfig *config, bool original_surface, - su2double &Wing_Volume, su2double &Wing_MinMaxThickness, su2double &Wing_MaxMaxThickness, - su2double &Wing_MinChord, su2double &Wing_MaxChord, - su2double &Wing_MinLERadius, su2double &Wing_MaxLERadius, - su2double &Wing_MinToC, su2double &Wing_MaxToC, - su2double &Wing_ObjFun_MinToC, su2double &Wing_MaxTwist, - su2double &Wing_MaxCurvature, su2double &Wing_MaxDihedral) override; + void Compute_Wing(CConfig* config, bool original_surface, su2double& Wing_Volume, su2double& Wing_MinMaxThickness, + su2double& Wing_MaxMaxThickness, su2double& Wing_MinChord, su2double& Wing_MaxChord, + su2double& Wing_MinLERadius, su2double& Wing_MaxLERadius, su2double& Wing_MinToC, + su2double& Wing_MaxToC, su2double& Wing_ObjFun_MinToC, su2double& Wing_MaxTwist, + su2double& Wing_MaxCurvature, su2double& Wing_MaxDihedral) override; /*! * \brief Evaluate geometrical parameters of a wing. */ - void Compute_Fuselage(CConfig *config, bool original_surface, - su2double &Fuselage_Volume, su2double &Fuselage_WettedArea, - su2double &Fuselage_MinWidth, su2double &Fuselage_MaxWidth, - su2double &Fuselage_MinWaterLineWidth, su2double &Fuselage_MaxWaterLineWidth, - su2double &Fuselage_MinHeight, su2double &Fuselage_MaxHeight, - su2double &Fuselage_MaxCurvature) override; + void Compute_Fuselage(CConfig* config, bool original_surface, su2double& Fuselage_Volume, + su2double& Fuselage_WettedArea, su2double& Fuselage_MinWidth, su2double& Fuselage_MaxWidth, + su2double& Fuselage_MinWaterLineWidth, su2double& Fuselage_MaxWaterLineWidth, + su2double& Fuselage_MinHeight, su2double& Fuselage_MaxHeight, + su2double& Fuselage_MaxCurvature) override; /*! * \brief Evaluate geometrical parameters of a wing. */ - void Compute_Nacelle(CConfig *config, bool original_surface, - su2double &Nacelle_Volume, su2double &Nacelle_MinMaxThickness, su2double &Nacelle_MaxMaxThickness, - su2double &Nacelle_MinChord, su2double &Nacelle_MaxChord, - su2double &Nacelle_MinLERadius, su2double &Nacelle_MaxLERadius, - su2double &Nacelle_MinToC, su2double &Nacelle_MaxToC, - su2double &Nacelle_ObjFun_MinToC, su2double &Nacelle_MaxTwist) override; + void Compute_Nacelle(CConfig* config, bool original_surface, su2double& Nacelle_Volume, + su2double& Nacelle_MinMaxThickness, su2double& Nacelle_MaxMaxThickness, + su2double& Nacelle_MinChord, su2double& Nacelle_MaxChord, su2double& Nacelle_MinLERadius, + su2double& Nacelle_MaxLERadius, su2double& Nacelle_MinToC, su2double& Nacelle_MaxToC, + su2double& Nacelle_ObjFun_MinToC, su2double& Nacelle_MaxTwist) override; /*! * \brief Read the sensitivity from adjoint solution file and store it. * \param[in] config - Definition of the particular problem. */ - void SetSensitivity(CConfig *config) override; + void SetSensitivity(CConfig* config) override; /*! * \brief Read the sensitivity from unordered ASCII adjoint solution file and store it. * \param[in] config - Definition of the particular problem. */ - void ReadUnorderedSensitivity(CConfig *config) override; + void ReadUnorderedSensitivity(CConfig* config) override; /*! * \brief Get the Sensitivity at a specific point. @@ -734,7 +706,9 @@ class CPhysicalGeometry final : public CGeometry { * \param[in] iDim - The component of the dim. vector. * \return The sensitivity at point iPoint and dim. iDim. */ - inline su2double GetSensitivity(unsigned long iPoint, unsigned short iDim) const override { return Sensitivity(iPoint,iDim); } + inline su2double GetSensitivity(unsigned long iPoint, unsigned short iDim) const override { + return Sensitivity(iPoint, iDim); + } /*! * \brief Set the Sensitivity at a specific point. @@ -742,20 +716,22 @@ class CPhysicalGeometry final : public CGeometry { * \param[in] iDim - The component of the dim. vector. * \param[in] val - Value of the sensitivity. */ - inline void SetSensitivity(unsigned long iPoint, unsigned short iDim, su2double val) override { Sensitivity(iPoint,iDim) = val; } + inline void SetSensitivity(unsigned long iPoint, unsigned short iDim, su2double val) override { + Sensitivity(iPoint, iDim) = val; + } /*! * \brief Check the mesh for periodicity and deactivate multigrid if periodicity is found. * \param[in] config - Definition of the particular problem. */ - void Check_Periodicity(CConfig *config) override; + void Check_Periodicity(CConfig* config) override; /*! * \brief Compute an ADT including the coordinates of all viscous markers * \param[in] config - Definition of the particular problem. * \return pointer to the ADT */ - std::unique_ptr ComputeViscousWallADT(const CConfig *config) const override; + std::unique_ptr ComputeViscousWallADT(const CConfig* config) const override; /*! * \brief Reduce the wall distance based on an previously constructed ADT. @@ -771,7 +747,7 @@ class CPhysicalGeometry final : public CGeometry { * \brief Set wall distances a specific value */ void SetWallDistance(su2double val) override { - for (unsigned long iPoint = 0; iPoint < GetnPoint(); iPoint++){ + for (unsigned long iPoint = 0; iPoint < GetnPoint(); iPoint++) { nodes->SetWall_Distance(iPoint, val); } } @@ -780,11 +756,11 @@ class CPhysicalGeometry final : public CGeometry { * \brief For streamwise periodicity, find & store a unique reference node on the designated periodic inlet. * \param[in] config - Definition of the particular problem. */ - void FindUniqueNode_PeriodicBound(const CConfig *config) final; + void FindUniqueNode_PeriodicBound(const CConfig* config) final; /*! * \brief Get a pointer to the reference node coordinate vector. * \return A pointer to the reference node coordinate vector. */ - inline const su2double* GetStreamwise_Periodic_RefNode(void) const final { return Streamwise_Periodic_RefNode;} + inline const su2double* GetStreamwise_Periodic_RefNode(void) const final { return Streamwise_Periodic_RefNode; } }; diff --git a/Common/include/geometry/dual_grid/CDualGrid.hpp b/Common/include/geometry/dual_grid/CDualGrid.hpp index b99e9d4a8e7..1e96d519e2c 100644 --- a/Common/include/geometry/dual_grid/CDualGrid.hpp +++ b/Common/include/geometry/dual_grid/CDualGrid.hpp @@ -41,12 +41,11 @@ * three main elements: points, edges, and vertices. * \author F. Palacios */ -class CDualGrid{ -protected: +class CDualGrid { + protected: static unsigned short nDim; /*!< \brief Number of dimensions of the problem. */ -public: - + public: /*! * \brief Constructor of the class. * \param[in] val_nDim - Number of dimensions of the problem. @@ -61,13 +60,13 @@ class CDualGrid{ /*! * \brief A pure virtual member. */ - virtual su2double *GetCoord(void) = 0; + virtual su2double* GetCoord(void) = 0; /*! * \brief A pure virtual member. * \param[in] val_coord - Coordinate of the point. */ - virtual void SetCoord(const su2double *val_coord) = 0; + virtual void SetCoord(const su2double* val_coord) = 0; /*! * \brief A pure virtual member. @@ -75,32 +74,32 @@ class CDualGrid{ * \param[in] val_coord_FaceElem_CG - Coordinates of the centre of gravity of the face of an element. * \param[in] val_coord_Elem_CG - Coordinates of the centre of gravity of the element. */ - virtual void SetNodes_Coord(const su2double *val_coord_Edge_CG, const su2double *val_coord_FaceElem_CG, - const su2double *val_coord_Elem_CG) = 0; + virtual void SetNodes_Coord(const su2double* val_coord_Edge_CG, const su2double* val_coord_FaceElem_CG, + const su2double* val_coord_Elem_CG) = 0; /*! * \overload * \param[in] val_coord_Edge_CG - Coordinates of the centre of gravity of the edge. * \param[in] val_coord_Elem_CG - Coordinates of the centre of gravity of the element. */ - virtual void SetNodes_Coord(const su2double *val_coord_Edge_CG, const su2double *val_coord_Elem_CG) = 0; + virtual void SetNodes_Coord(const su2double* val_coord_Edge_CG, const su2double* val_coord_Elem_CG) = 0; /*! * \brief A pure virtual member. * \param[out] val_normal - Coordinates of the normal. */ - virtual void GetNormal(su2double *val_normal) const = 0; + virtual void GetNormal(su2double* val_normal) const = 0; /*! * \brief A pure virtual member. */ - virtual su2double *GetNormal(void) = 0; + virtual su2double* GetNormal(void) = 0; /*! * \brief A pure virtual member. * \param[in] val_face_normal - Coordinates of the normal. */ - virtual void SetNormal(const su2double *val_face_normal) = 0; + virtual void SetNormal(const su2double* val_face_normal) = 0; /*! * \brief A pure virtual member. @@ -116,5 +115,5 @@ class CDualGrid{ * \brief A pure virtual member. * \param[in] val_face_normal - Normal vector to be added. */ - virtual void AddNormal(const su2double *val_face_normal) = 0; + virtual void AddNormal(const su2double* val_face_normal) = 0; }; diff --git a/Common/include/geometry/dual_grid/CEdge.hpp b/Common/include/geometry/dual_grid/CEdge.hpp index 84bb425cbbb..c3fbd76449b 100644 --- a/Common/include/geometry/dual_grid/CEdge.hpp +++ b/Common/include/geometry/dual_grid/CEdge.hpp @@ -38,17 +38,18 @@ class CPhysicalGeometry; */ class CEdge { static_assert(su2activematrix::IsRowMajor, "Needed to return normal as pointer."); -private: + + private: using Index = unsigned long; using NodeArray = C2DContainer; - NodeArray Nodes; /*!< \brief Vector to store the node indices of the edge. */ - su2activematrix Normal; /*!< \brief Normal (area) of the edge. */ + NodeArray Nodes; /*!< \brief Vector to store the node indices of the edge. */ + su2activematrix Normal; /*!< \brief Normal (area) of the edge. */ const Index nEdge, nEdgeSIMD; friend class CPhysicalGeometry; -public: - enum NodePosition : unsigned long {LEFT = 0, RIGHT = 1}; + public: + enum NodePosition : unsigned long { LEFT = 0, RIGHT = 1 }; /*! * \brief Constructor of the class. @@ -68,14 +69,14 @@ class CEdge { * \param[in] iNode - Node index 0 or 1, LEFT or RIGHT. * \return Index of the node that composes the edge. */ - inline unsigned long GetNode(unsigned long iEdge, unsigned long iNode) const { return Nodes(iEdge,iNode); } + inline unsigned long GetNode(unsigned long iEdge, unsigned long iNode) const { return Nodes(iEdge, iNode); } /*! * \brief SIMD version of GetNode, iNode returned for contiguous iEdges. */ - template - FORCEINLINE simd::Array GetNode(simd::Array iEdge, unsigned long iNode) const { - return simd::Array(&Nodes(iEdge[0],iNode)); + template + FORCEINLINE simd::Array GetNode(simd::Array iEdge, unsigned long iNode) const { + return simd::Array(&Nodes(iEdge[0], iNode)); } /*! @@ -116,10 +117,8 @@ class CEdge { * \param[in] coord_Point - Coordinates of the point that form the control volume. * \return Local volume associated to the edge. */ - static su2double GetVolume(const su2double* coord_Edge_CG, - const su2double* coord_FaceElem_CG, - const su2double* coord_Elem_CG, - const su2double* coord_Point); + static su2double GetVolume(const su2double* coord_Edge_CG, const su2double* coord_FaceElem_CG, + const su2double* coord_Elem_CG, const su2double* coord_Point); /*! * \brief Compute the volume associated with an edge (2D version). @@ -128,8 +127,7 @@ class CEdge { * \param[in] coord_Point - Coordinates of the point that form the control volume. * \return Local volume associated to the edge. */ - static su2double GetVolume(const su2double* coord_Edge_CG, - const su2double* coord_Elem_CG, + static su2double GetVolume(const su2double* coord_Edge_CG, const su2double* coord_Elem_CG, const su2double* coord_Point); /*! @@ -141,9 +139,7 @@ class CEdge { * \param[in] config - Definition of the particular problem. * \return Compute the normal (dimensional) to the face that makes the control volume boundaries. */ - void SetNodes_Coord(unsigned long iEdge, - const su2double* coord_Edge_CG, - const su2double* coord_FaceElem_CG, + void SetNodes_Coord(unsigned long iEdge, const su2double* coord_Edge_CG, const su2double* coord_FaceElem_CG, const su2double* coord_Elem_CG); /*! @@ -154,19 +150,16 @@ class CEdge { * \param[in] config - Definition of the particular problem. * \return Compute the normal (dimensional) to the face that makes the contorl volume boundaries. */ - void SetNodes_Coord(unsigned long iEdge, - const su2double* coord_Edge_CG, - const su2double* coord_Elem_CG); + void SetNodes_Coord(unsigned long iEdge, const su2double* coord_Edge_CG, const su2double* coord_Elem_CG); /*! * \brief Copy the the normal vector of a face. * \param[in] iEdge - Edge index. * \param[out] normal - Object into which the normal (dimensional) will be copied. */ - template + template inline void GetNormal(unsigned long iEdge, T& normal) const { - for (auto iDim = 0ul; iDim < Normal.cols(); iDim++) - normal[iDim] = Normal(iEdge,iDim); + for (auto iDim = 0ul; iDim < Normal.cols(); iDim++) normal[iDim] = Normal(iEdge, iDim); } /*! @@ -192,10 +185,9 @@ class CEdge { * \param[in] normal - Vector to initialize the normal vector. * \return Value of the normal vector. */ - template + template void SetNormal(unsigned long iEdge, const T& normal) { - for (auto iDim = 0ul; iDim < Normal.cols(); ++iDim) - Normal(iEdge,iDim) = normal[iDim]; + for (auto iDim = 0ul; iDim < Normal.cols(); ++iDim) Normal(iEdge, iDim) = normal[iDim]; } /*! @@ -203,10 +195,9 @@ class CEdge { * \param[in] iEdge - Edge index. * \param[in] normal - Vector to add to the normal vector. */ - template + template void AddNormal(unsigned long iEdge, const T& normal) { - for (auto iDim = 0ul; iDim < Normal.cols(); ++iDim) - Normal(iEdge,iDim) += normal[iDim]; + for (auto iDim = 0ul; iDim < Normal.cols(); ++iDim) Normal(iEdge, iDim) += normal[iDim]; } /*! @@ -214,10 +205,8 @@ class CEdge { * \param[in] iEdge - Edge index. * \param[in] normal - Vector to add to the normal vector. */ - template + template void SubNormal(unsigned long iEdge, const T& normal) { - for (auto iDim = 0ul; iDim < Normal.cols(); ++iDim) - Normal(iEdge,iDim) -= normal[iDim]; + for (auto iDim = 0ul; iDim < Normal.cols(); ++iDim) Normal(iEdge, iDim) -= normal[iDim]; } - }; diff --git a/Common/include/geometry/dual_grid/CPoint.hpp b/Common/include/geometry/dual_grid/CPoint.hpp index 470dad563fd..4e78f588bfa 100644 --- a/Common/include/geometry/dual_grid/CPoint.hpp +++ b/Common/include/geometry/dual_grid/CPoint.hpp @@ -45,73 +45,84 @@ class CPhysicalGeometry; * \author F. Palacios */ class CPoint { -private: + private: friend class CPhysicalGeometry; const unsigned long nDim = 0; - su2vector GlobalIndex; /*!< \brief Global index in the parallel simulation. */ - su2vector Color; /*!< \brief Color of the point in the partitioning strategy. */ - - CCompressedSparsePatternUL Point; /*!< \brief Points surrounding the central node of the control volume. */ - CCompressedSparsePatternL Edge; /*!< \brief Edges that set up a control volume (same sparse structure as Point). */ - CCompressedSparsePatternL Elem; /*!< \brief Elements that set up a control volume around a node. */ - vector > Vertex; /*!< \brief Index of the vertex that correspond which the control volume (we need one for each marker in the same node). */ - - su2activevector Volume; /*!< \brief Volume or Area of the control volume in 3D and 2D. */ - su2activevector Volume_n; /*!< \brief Volume at time n. */ - su2activevector Volume_nM1; /*!< \brief Volume at time n-1. */ - su2activevector Volume_Old; /*!< \brief Old containers for Volume. */ - su2activevector Volume_n_Old; /*!< \brief Old containers for Volume at time n. */ - su2activevector Volume_nM1_Old; /*!< \brief Old containers for Volume at time n-1. */ - su2activevector Periodic_Volume; /*!< \brief Missing component of volume or area of a control volume on a periodic marker in 3D and 2D. */ - - su2vector Domain; /*!< \brief Indicates if a point must be computed or belong to another boundary */ - su2vector Boundary; /*!< \brief To see if a point belong to the boundary (including MPI). */ - su2vector PhysicalBoundary; /*!< \brief To see if a point belong to the physical boundary (without includin MPI). */ - su2vector SolidBoundary; /*!< \brief To see if a point belong to the physical boundary (without includin MPI). */ - su2vector ViscousBoundary; /*!< \brief To see if a point belong to the physical boundary (without includin MPI). */ - su2vector PeriodicBoundary; /*!< \brief To see if a point belongs to a periodic boundary (without including MPI). */ - - su2activematrix Coord; /*!< \brief vector with the coordinates of the node. */ - su2activematrix Coord_Old; /*!< \brief Old coordinates vector for primal solution reloading for Disc.Adj. with dynamic grid. */ - su2activematrix Coord_Sum; /*!< \brief Sum of coordinates vector for geometry smoothing. */ - su2activematrix Coord_n; /*!< \brief Coordinates at time n for use with dynamic meshes. */ - su2activematrix Coord_n1; /*!< \brief Coordinates at time n-1 for use with dynamic meshes. */ - su2activematrix Coord_p1; /*!< \brief Coordinates at time n+1 for use with dynamic meshes. */ - - su2activematrix GridVel; /*!< \brief Velocity of the grid for dynamic mesh cases. */ - CVectorOfMatrix GridVel_Grad; /*!< \brief Gradient of the grid velocity for dynamic meshes. */ - - su2vector Parent_CV; /*!< \brief Index of the parent control volume in the agglomeration process. */ - su2vector nChildren_CV; /*!< \brief Number of children in the agglomeration process. */ - vector > Children_CV; /*!< \brief Index of the children control volumes in the agglomeration process. */ - su2vector Agglomerate_Indirect; /*!< \brief This flag indicates if the indirect points can be agglomerated. */ - su2vector Agglomerate; /*!< \brief This flag indicates if the element has been agglomerated. */ - - su2vector nNeighbor; /*!< \brief Number of neighbors, needed by some numerical methods. */ + su2vector GlobalIndex; /*!< \brief Global index in the parallel simulation. */ + su2vector Color; /*!< \brief Color of the point in the partitioning strategy. */ + + CCompressedSparsePatternUL Point; /*!< \brief Points surrounding the central node of the control volume. */ + CCompressedSparsePatternL Edge; /*!< \brief Edges that set up a control volume (same sparse structure as Point). */ + CCompressedSparsePatternL Elem; /*!< \brief Elements that set up a control volume around a node. */ + vector > Vertex; /*!< \brief Index of the vertex that correspond which the control volume (we need one + for each marker in the same node). */ + + su2activevector Volume; /*!< \brief Volume or Area of the control volume in 3D and 2D. */ + su2activevector Volume_n; /*!< \brief Volume at time n. */ + su2activevector Volume_nM1; /*!< \brief Volume at time n-1. */ + su2activevector Volume_Old; /*!< \brief Old containers for Volume. */ + su2activevector Volume_n_Old; /*!< \brief Old containers for Volume at time n. */ + su2activevector Volume_nM1_Old; /*!< \brief Old containers for Volume at time n-1. */ + su2activevector Periodic_Volume; /*!< \brief Missing component of volume or area of a control volume on a periodic + marker in 3D and 2D. */ + + su2vector Domain; /*!< \brief Indicates if a point must be computed or belong to another boundary */ + su2vector Boundary; /*!< \brief To see if a point belong to the boundary (including MPI). */ + su2vector + PhysicalBoundary; /*!< \brief To see if a point belong to the physical boundary (without includin MPI). */ + su2vector + SolidBoundary; /*!< \brief To see if a point belong to the physical boundary (without includin MPI). */ + su2vector + ViscousBoundary; /*!< \brief To see if a point belong to the physical boundary (without includin MPI). */ + su2vector + PeriodicBoundary; /*!< \brief To see if a point belongs to a periodic boundary (without including MPI). */ + + su2activematrix Coord; /*!< \brief vector with the coordinates of the node. */ + su2activematrix + Coord_Old; /*!< \brief Old coordinates vector for primal solution reloading for Disc.Adj. with dynamic grid. */ + su2activematrix Coord_Sum; /*!< \brief Sum of coordinates vector for geometry smoothing. */ + su2activematrix Coord_n; /*!< \brief Coordinates at time n for use with dynamic meshes. */ + su2activematrix Coord_n1; /*!< \brief Coordinates at time n-1 for use with dynamic meshes. */ + su2activematrix Coord_p1; /*!< \brief Coordinates at time n+1 for use with dynamic meshes. */ + + su2activematrix GridVel; /*!< \brief Velocity of the grid for dynamic mesh cases. */ + CVectorOfMatrix GridVel_Grad; /*!< \brief Gradient of the grid velocity for dynamic meshes. */ + + su2vector Parent_CV; /*!< \brief Index of the parent control volume in the agglomeration process. */ + su2vector nChildren_CV; /*!< \brief Number of children in the agglomeration process. */ + vector > + Children_CV; /*!< \brief Index of the children control volumes in the agglomeration process. */ + su2vector Agglomerate_Indirect; /*!< \brief This flag indicates if the indirect points can be agglomerated. */ + su2vector Agglomerate; /*!< \brief This flag indicates if the element has been agglomerated. */ + + su2vector nNeighbor; /*!< \brief Number of neighbors, needed by some numerical methods. */ /*--- Closest element on a viscous wall, and distance to it. ---*/ - su2activevector Wall_Distance; /*!< \brief Distance to the nearest wall. */ - su2vector ClosestWall_Rank; /*!< \brief Rank of process holding the closest wall element. */ + su2activevector Wall_Distance; /*!< \brief Distance to the nearest wall. */ + su2vector ClosestWall_Rank; /*!< \brief Rank of process holding the closest wall element. */ su2vector ClosestWall_Zone; /*!< \brief Zone index of closest wall element. */ - su2vector ClosestWall_Marker; /*!< \brief Marker index of closest wall element, for given rank and zone index. */ - su2vector ClosestWall_Elem; /*!< \brief Element index of closest wall element, for givenrank, zone and marker index. */ + su2vector + ClosestWall_Marker; /*!< \brief Marker index of closest wall element, for given rank and zone index. */ + su2vector + ClosestWall_Elem; /*!< \brief Element index of closest wall element, for givenrank, zone and marker index. */ - su2activevector SharpEdge_Distance; /*!< \brief Distance to a sharp edge. */ - su2activevector Curvature; /*!< \brief Value of the surface curvature (SU2_GEO). */ - su2activevector MaxLength; /*!< \brief The maximum cell-center to cell-center length. */ - su2activevector RoughnessHeight; /*!< \brief Roughness of the nearest wall. */ + su2activevector SharpEdge_Distance; /*!< \brief Distance to a sharp edge. */ + su2activevector Curvature; /*!< \brief Value of the surface curvature (SU2_GEO). */ + su2activevector MaxLength; /*!< \brief The maximum cell-center to cell-center length. */ + su2activevector RoughnessHeight; /*!< \brief Roughness of the nearest wall. */ - su2matrix AD_InputIndex; /*!< \brief Indices of Coord variables in the adjoint vector. */ - su2matrix AD_OutputIndex; /*!< \brief Indices of Coord variables in the adjoint vector after having been updated. */ + su2matrix AD_InputIndex; /*!< \brief Indices of Coord variables in the adjoint vector. */ + su2matrix + AD_OutputIndex; /*!< \brief Indices of Coord variables in the adjoint vector after having been updated. */ /*! * \brief Allocate fields required by the minimal constructor. */ void MinimalAllocation(unsigned long npoint); -public: + public: /*! * \brief "Full" constructor of the class. * \param[in] npoint - Number of points (dual volumes) in the problem. @@ -144,14 +155,14 @@ class CPoint { * \param[in] iDim - Number of dimensions of the problem. * \return Coordinate that correspond with iDim. */ - inline su2double GetCoord(unsigned long iPoint, unsigned long iDim) const { return Coord(iPoint,iDim); } + inline su2double GetCoord(unsigned long iPoint, unsigned long iDim) const { return Coord(iPoint, iDim); } /*! * \brief Get the coordinates of the control volume. * \param[in] iPoint - Index of the point. * \return pointer to the coordinate of the point. */ - inline su2double *GetCoord(unsigned long iPoint) { return Coord[iPoint]; } + inline su2double* GetCoord(unsigned long iPoint) { return Coord[iPoint]; } /*! * \brief Get the entire matrix of coordinates of the control volumes. @@ -164,7 +175,7 @@ class CPoint { * \param[in] iDim - Position to store the coordinate. * \param[in] coord - Coordinate for iDim. */ - inline void SetCoord(unsigned long iPoint, unsigned long iDim, su2double coord) { Coord(iPoint,iDim) = coord; } + inline void SetCoord(unsigned long iPoint, unsigned long iDim, su2double coord) { Coord(iPoint, iDim) = coord; } /*! * \brief Set the coordinates for the control volume. @@ -172,16 +183,15 @@ class CPoint { * \param[in] iDim - Position to store the coordinate. * \param[in] coord - Coordinate for iDim. */ - inline void AddCoord(unsigned long iPoint, unsigned long iDim, su2double coord) { Coord(iPoint,iDim) += coord; } + inline void AddCoord(unsigned long iPoint, unsigned long iDim, su2double coord) { Coord(iPoint, iDim) += coord; } /*! * \brief Set the point coordinates. * \param[in] iPoint - Index of the point. * \param[in] coord - Coordinate of the point. */ - inline void SetCoord(unsigned long iPoint, const su2double *coord) { - for (unsigned long iDim = 0; iDim < nDim; iDim++) - Coord(iPoint,iDim) = coord[iDim]; + inline void SetCoord(unsigned long iPoint, const su2double* coord) { + for (unsigned long iDim = 0; iDim < nDim; iDim++) Coord(iPoint, iDim) = coord[iDim]; } /*! @@ -208,12 +218,16 @@ class CPoint { * \param[in] nelem - Position where the element is stored. * \return Index of the element. */ - inline unsigned long GetElem(unsigned long iPoint, unsigned long nelem) const { return Elem.getInnerIdx(iPoint,nelem); } + inline unsigned long GetElem(unsigned long iPoint, unsigned long nelem) const { + return Elem.getInnerIdx(iPoint, nelem); + } /*! * \brief Get inner iterator to loop over neighbor elements. */ - inline CCompressedSparsePatternL::CInnerIter GetElems(unsigned long iPoint) const { return Elem.getInnerIter(iPoint); } + inline CCompressedSparsePatternL::CInnerIter GetElems(unsigned long iPoint) const { + return Elem.getInnerIter(iPoint); + } /*! * \brief Set the points that compose the control volume. @@ -229,7 +243,10 @@ class CPoint { /*! * \brief Reset the points that compose the control volume. */ - inline void ResetPoints() { Point = CCompressedSparsePatternUL(); Edge = CCompressedSparsePatternL(); } + inline void ResetPoints() { + Point = CCompressedSparsePatternUL(); + Edge = CCompressedSparsePatternL(); + } /*! * \brief Get the number of points that compose the control volume. @@ -244,12 +261,16 @@ class CPoint { * \param[in] point - Position where the point is stored. * \return Index of the point. */ - inline unsigned long GetPoint(unsigned long iPoint, unsigned long npoint) const { return Point.getInnerIdx(iPoint,npoint); } + inline unsigned long GetPoint(unsigned long iPoint, unsigned long npoint) const { + return Point.getInnerIdx(iPoint, npoint); + } /*! * \brief Get inner iterator to loop over neighbor points. */ - inline CCompressedSparsePatternUL::CInnerIter GetPoints(unsigned long iPoint) const { return Point.getInnerIter(iPoint); } + inline CCompressedSparsePatternUL::CInnerIter GetPoints(unsigned long iPoint) const { + return Point.getInnerIter(iPoint); + } /*! * \brief Set the edges that compose the control volume. @@ -257,7 +278,9 @@ class CPoint { * \param[in] iedge - Edge to be added. * \param[in] nedge - Position in which is going to be stored the edge for each control volume. */ - inline void SetEdge(unsigned long iPoint, long iedge, unsigned long nedge) { Edge.getInnerIdx(iPoint,nedge) = iedge; } + inline void SetEdge(unsigned long iPoint, long iedge, unsigned long nedge) { + Edge.getInnerIdx(iPoint, nedge) = iedge; + } /*! * \brief Get all the edges that compose the control volume. @@ -265,12 +288,14 @@ class CPoint { * \param[in] nedge - Position where the edge is stored. * \return Index of the edge. */ - inline long GetEdge(unsigned long iPoint, unsigned long nedge) const { return Edge.getInnerIdx(iPoint,nedge); } + inline long GetEdge(unsigned long iPoint, unsigned long nedge) const { return Edge.getInnerIdx(iPoint, nedge); } /*! * \brief Get inner iterator to loop over neighbor edges. */ - inline CCompressedSparsePatternL::CInnerIter GetEdges(unsigned long iPoint) const { return Edge.getInnerIter(iPoint); } + inline CCompressedSparsePatternL::CInnerIter GetEdges(unsigned long iPoint) const { + return Edge.getInnerIter(iPoint); + } /*! * \brief Set the boundary vertex that compose the control volume. @@ -289,8 +314,10 @@ class CPoint { * \return Index of the vertex. */ inline long GetVertex(unsigned long iPoint, unsigned long iMarker) const { - if (Boundary(iPoint)) return Vertex[iPoint][iMarker]; - else return -1; + if (Boundary(iPoint)) + return Vertex[iPoint][iMarker]; + else + return -1; } /*! @@ -300,7 +327,7 @@ class CPoint { * \param[in] nMarker - Max number of marker. */ inline void SetBoundary(unsigned long iPoint, unsigned short nMarker) { - if (!Boundary(iPoint)) Vertex[iPoint].resize(nMarker,-1); + if (!Boundary(iPoint)) Vertex[iPoint].resize(nMarker, -1); Boundary(iPoint) = true; } @@ -308,7 +335,10 @@ class CPoint { * \brief Reset the boundary of a control volume. * \param[in] iPoint - Index of the point. */ - inline void ResetBoundary(unsigned long iPoint) { Vertex[iPoint].clear(); Boundary(iPoint) = false; } + inline void ResetBoundary(unsigned long iPoint) { + Vertex[iPoint].clear(); + Boundary(iPoint) = false; + } /*! * \brief Mark the point as boundary. @@ -602,7 +632,7 @@ class CPoint { */ void SetVolume_n_Old(); - /*! + /*! * \brief Set the Volume_nM1 to Volume_nM1_Old. */ void SetVolume_nM1_Old(); @@ -613,7 +643,8 @@ class CPoint { * \param[in] parent_CV - Index of the parent control volume. */ inline void SetParent_CV(unsigned long iPoint, unsigned long parent_CV) { - Parent_CV(iPoint) = parent_CV; Agglomerate(iPoint) = true; + Parent_CV(iPoint) = parent_CV; + Agglomerate(iPoint) = true; } /*! @@ -623,7 +654,7 @@ class CPoint { * \param[in] children_CV - Index of the children control volume. */ inline void SetChildren_CV(unsigned long iPoint, unsigned long nchildren_CV, unsigned long children_CV) { - Children_CV[iPoint].resize(nchildren_CV+1); + Children_CV[iPoint].resize(nchildren_CV + 1); Children_CV[iPoint][nchildren_CV] = children_CV; } @@ -663,7 +694,9 @@ class CPoint { * \param[in] iPoint - Index of the point. * \param[in] agglomerate - The indirect neigbors can be agglomerated. */ - inline void SetAgglomerate_Indirect(unsigned long iPoint, bool agglomerate) { Agglomerate_Indirect(iPoint) = agglomerate; }; + inline void SetAgglomerate_Indirect(unsigned long iPoint, bool agglomerate) { + Agglomerate_Indirect(iPoint) = agglomerate; + }; /*! * \brief Get the number of children of an agglomerated control volume. @@ -677,28 +710,30 @@ class CPoint { * \param[in] iPoint - Index of the point. * \param[in] nchildren_CV - Number of children of the control volume. */ - inline void SetnChildren_CV(unsigned long iPoint, unsigned short nchildren_CV) { nChildren_CV(iPoint) = nchildren_CV; } + inline void SetnChildren_CV(unsigned long iPoint, unsigned short nchildren_CV) { + nChildren_CV(iPoint) = nchildren_CV; + } /*! * \brief Get the coordinates of the control volume at time n. * \param[in] iPoint - Index of the point. * \return Coordinates of the control volume at time n. */ - inline su2double *GetCoord_n(unsigned long iPoint) { return Coord_n[iPoint]; } + inline su2double* GetCoord_n(unsigned long iPoint) { return Coord_n[iPoint]; } /*! * \brief Get the coordinates of the control volume at time n-1. * \param[in] iPoint - Index of the point. * \return Volume of the control volume at time n-1 */ - inline su2double *GetCoord_n1(unsigned long iPoint) { return Coord_n1[iPoint]; } + inline su2double* GetCoord_n1(unsigned long iPoint) { return Coord_n1[iPoint]; } /*! * \brief Get the coordinates of the control volume at time n+1. * \param[in] iPoint - Index of the point. * \return Volume of the control volume at time n+1 */ - inline su2double *GetCoord_p1(unsigned long iPoint) { return Coord_p1[iPoint]; } + inline su2double* GetCoord_p1(unsigned long iPoint) { return Coord_p1[iPoint]; } /*! * \brief Set the coordinates of the control volume at time n to the ones in Coord. @@ -715,9 +750,8 @@ class CPoint { * \param[in] iPoint - Index of the point. * \param[in] coord - Value of the grid coordinates at time n. */ - inline void SetCoord_n(unsigned long iPoint, const su2double *coord) { - for (unsigned long iDim = 0; iDim < nDim; iDim++) - Coord_n(iPoint,iDim) = coord[iDim]; + inline void SetCoord_n(unsigned long iPoint, const su2double* coord) { + for (unsigned long iDim = 0; iDim < nDim; iDim++) Coord_n(iPoint, iDim) = coord[iDim]; } /*! @@ -725,9 +759,8 @@ class CPoint { * \param[in] iPoint - Index of the point. * \param[in] coord - Value of the grid coordinates at time n-1. */ - inline void SetCoord_n1(unsigned long iPoint, const su2double *coord) { - for (unsigned long iDim = 0; iDim < nDim; iDim++) - Coord_n1(iPoint,iDim) = coord[iDim]; + inline void SetCoord_n1(unsigned long iPoint, const su2double* coord) { + for (unsigned long iDim = 0; iDim < nDim; iDim++) Coord_n1(iPoint, iDim) = coord[iDim]; } /*! @@ -735,9 +768,8 @@ class CPoint { * \param[in] iPoint - Index of the point. * \param[in] coord - Value of the grid coordinates at time n+1. */ - inline void SetCoord_p1(unsigned long iPoint, const su2double *coord) { - for (unsigned long iDim = 0; iDim < nDim; iDim++) - Coord_p1(iPoint,iDim) = coord[iDim]; + inline void SetCoord_p1(unsigned long iPoint, const su2double* coord) { + for (unsigned long iDim = 0; iDim < nDim; iDim++) Coord_p1(iPoint, iDim) = coord[iDim]; } /*! @@ -745,16 +777,15 @@ class CPoint { * \param[in] iPoint - Index of the point. * \return Old coordinates at a point. */ - inline su2double *GetCoord_Old(unsigned long iPoint) { return Coord_Old[iPoint]; } + inline su2double* GetCoord_Old(unsigned long iPoint) { return Coord_Old[iPoint]; } /*! * \brief Set the value of the vector Coord_Old for implicit smoothing. * \param[in] iPoint - Index of the point. * \param[in] coord_old - Value of the coordinates. */ - inline void SetCoord_Old(unsigned long iPoint, const su2double *coord_old) { - for (unsigned long iDim = 0; iDim < nDim; iDim++) - Coord_Old(iPoint,iDim) = coord_old[iDim]; + inline void SetCoord_Old(unsigned long iPoint, const su2double* coord_old) { + for (unsigned long iDim = 0; iDim < nDim; iDim++) Coord_Old(iPoint, iDim) = coord_old[iDim]; } /*! @@ -767,16 +798,15 @@ class CPoint { * \param[in] iPoint - Index of the point. * \return Sum of coordinates at a point. */ - inline su2double *GetCoord_Sum(unsigned long iPoint) { return Coord_Sum[iPoint]; } + inline su2double* GetCoord_Sum(unsigned long iPoint) { return Coord_Sum[iPoint]; } /*! * \brief Add the value of the coordinates to the Coord_Sum vector for implicit smoothing. * \param[in] iPoint - Index of the point. * \param[in] coord_sum - Value of the coordinates to add. */ - inline void AddCoord_Sum(unsigned long iPoint, const su2double *coord_sum) { - for (unsigned long iDim = 0; iDim < nDim; iDim++) - Coord_Sum(iPoint,iDim) += coord_sum[iDim]; + inline void AddCoord_Sum(unsigned long iPoint, const su2double* coord_sum) { + for (unsigned long iDim = 0; iDim < nDim; iDim++) Coord_Sum(iPoint, iDim) += coord_sum[iDim]; } /*! @@ -789,7 +819,7 @@ class CPoint { * \param[in] iPoint - Index of the point. * \return Grid velocity at the point. */ - inline su2double *GetGridVel(unsigned long iPoint) { return GridVel[iPoint]; } + inline su2double* GetGridVel(unsigned long iPoint) { return GridVel[iPoint]; } /*! * \brief Get the grid velocity matrix for the entire domain. @@ -802,16 +832,17 @@ class CPoint { * \param[in] iDim - Index of the coordinate. * \param[in] gridvel - Value of the grid velocity. */ - inline void SetGridVel(unsigned long iPoint, unsigned long iDim, su2double gridvel) { GridVel(iPoint,iDim) = gridvel; } + inline void SetGridVel(unsigned long iPoint, unsigned long iDim, su2double gridvel) { + GridVel(iPoint, iDim) = gridvel; + } /*! * \brief Set the value of the grid velocity at the point. * \param[in] iPoint - Index of the point. * \param[in] gridvel - Value of the grid velocity. */ - inline void SetGridVel(unsigned long iPoint, const su2double *gridvel) { - for (unsigned long iDim = 0; iDim < nDim; iDim++) - GridVel(iPoint,iDim) = gridvel[iDim]; + inline void SetGridVel(unsigned long iPoint, const su2double* gridvel) { + for (unsigned long iDim = 0; iDim < nDim; iDim++) GridVel(iPoint, iDim) = gridvel[iDim]; } /*! @@ -831,9 +862,9 @@ class CPoint { * \param[in] iPoint - Index of the point. * \param[in] adj_sol - Adjoint values of the Coord variables. */ - inline void SetAdjointSolution(unsigned long iPoint, const su2double *adj_sol) { + inline void SetAdjointSolution(unsigned long iPoint, const su2double* adj_sol) { for (unsigned long iDim = 0; iDim < nDim; iDim++) - AD::SetDerivative(AD_OutputIndex(iPoint,iDim), SU2_TYPE::GetValue(adj_sol[iDim])); + AD::SetDerivative(AD_OutputIndex(iPoint, iDim), SU2_TYPE::GetValue(adj_sol[iDim])); } /*! @@ -842,7 +873,7 @@ class CPoint { * \param[in] iDim - Dimension. */ inline su2double GetAdjointSolution(unsigned long iPoint, unsigned long iDim) const { - return AD::GetDerivative(AD_InputIndex(iPoint,iDim)); + return AD::GetDerivative(AD_InputIndex(iPoint, iDim)); } /*! @@ -852,13 +883,12 @@ class CPoint { */ inline void RegisterCoordinates(unsigned long iPoint, bool input) { for (unsigned long iDim = 0; iDim < nDim; iDim++) { - if(input) { - AD::RegisterInput(Coord(iPoint,iDim)); - AD::SetIndex(AD_InputIndex(iPoint,iDim), Coord(iPoint,iDim)); - } - else { - AD::RegisterOutput(Coord(iPoint,iDim)); - AD::SetIndex(AD_OutputIndex(iPoint,iDim), Coord(iPoint,iDim)); + if (input) { + AD::RegisterInput(Coord(iPoint, iDim)); + AD::SetIndex(AD_InputIndex(iPoint, iDim), Coord(iPoint, iDim)); + } else { + AD::RegisterOutput(Coord(iPoint, iDim)); + AD::SetIndex(AD_OutputIndex(iPoint, iDim), Coord(iPoint, iDim)); } } } @@ -867,16 +897,15 @@ class CPoint { * \brief Set wall roughnesses according to stored closest wall information. * \param[in] roughness - Mapping [rank][zone][marker] -> roughness */ - template - void SetWallRoughness(Roughness_type const& roughness){ - for (unsigned long iPoint=0; iPoint + void SetWallRoughness(Roughness_type const& roughness) { + for (unsigned long iPoint = 0; iPoint < GlobalIndex.size(); ++iPoint) { auto rankID = ClosestWall_Rank[iPoint]; auto zoneID = ClosestWall_Zone[iPoint]; auto markerID = ClosestWall_Marker[iPoint]; - if(rankID >= 0){ + if (rankID >= 0) { SetRoughnessHeight(iPoint, roughness[rankID][zoneID][markerID]); } } } - }; diff --git a/Common/include/geometry/dual_grid/CTurboVertex.hpp b/Common/include/geometry/dual_grid/CTurboVertex.hpp index 6b65d208179..47a88bfb5fd 100644 --- a/Common/include/geometry/dual_grid/CTurboVertex.hpp +++ b/Common/include/geometry/dual_grid/CTurboVertex.hpp @@ -36,19 +36,19 @@ * \author S. Vitale */ class CTurboVertex final : public CVertex { -private: - su2double *TurboNormal; /*!< \brief Normal for computing correct turbomachinery quantities. */ - su2double Area; /*!< \brief Value of the face area associated to the vertex */ + private: + su2double* TurboNormal; /*!< \brief Normal for computing correct turbomachinery quantities. */ + su2double Area; /*!< \brief Value of the face area associated to the vertex */ // su2double PitchCoord; /*!< \brief Value of the abscissa pitch wise */ - su2double AngularCoord; /*!< \brief Value of the angular coordinate */ - su2double DeltaAngularCoord; /*!< \brief Value of the angular coordinate w.r.t. the minimum pitch point */ - su2double RelAngularCoord; /*!< \brief Value of the angular coordinate w.r.t. the minimum pitch point */ + su2double AngularCoord; /*!< \brief Value of the angular coordinate */ + su2double DeltaAngularCoord; /*!< \brief Value of the angular coordinate w.r.t. the minimum pitch point */ + su2double RelAngularCoord; /*!< \brief Value of the angular coordinate w.r.t. the minimum pitch point */ - unsigned long OldVertex; /*!< \brief Value of the vertex numeration before the ordering */ - int GlobalIndex; /*!< \brief Value of the vertex numeration after the ordering and global with respect to MPI partinioning */ - -public: + unsigned long OldVertex; /*!< \brief Value of the vertex numeration before the ordering */ + int GlobalIndex; /*!< \brief Value of the vertex numeration after the ordering and global with respect to MPI + partinioning */ + public: /*! * \brief Constructor of the class. * \param[in] val_point - Node of the vertex. @@ -65,17 +65,16 @@ class CTurboVertex final : public CVertex { * \brief set Normal in the turbomachinery frame of reference. * \param[in] val_normal - normal vector. */ - inline void SetTurboNormal(const su2double *val_normal) { + inline void SetTurboNormal(const su2double* val_normal) { unsigned short iDim; - for(iDim= 0; iDim < nDim; iDim++) - TurboNormal[iDim] = val_normal[iDim]; + for (iDim = 0; iDim < nDim; iDim++) TurboNormal[iDim] = val_normal[iDim]; } /*! * \brief set face Area. * \param[in] val_area - value of the face area. */ - inline void SetArea(su2double val_area){Area = val_area;} + inline void SetArea(su2double val_area) { Area = val_area; } /*! * \brief get face Area associate to the vertex. @@ -86,22 +85,21 @@ class CTurboVertex final : public CVertex { * \brief Copy the the turbo normal vector of a face. * \param[in] val_normal - Vector where the subroutine is goint to copy the normal (dimensionaless). */ - inline void GetTurboNormal(su2double *val_normal) const { - for (unsigned short iDim = 0; iDim < nDim; iDim++) - val_normal[iDim] = TurboNormal[iDim]; + inline void GetTurboNormal(su2double* val_normal) const { + for (unsigned short iDim = 0; iDim < nDim; iDim++) val_normal[iDim] = TurboNormal[iDim]; } /*! * \brief Get the turbo normal to a face where turboperformance are computed . * \return Dimensionaless normal vector, the modulus is the area of the face. */ - inline su2double *GetTurboNormal(void) { return TurboNormal; } + inline su2double* GetTurboNormal(void) { return TurboNormal; } /*! * \brief set vertex value not ordered. * \param[in] val_vertex - value of the vertex before ordering. */ - inline void SetOldVertex(unsigned long val_vertex){OldVertex = val_vertex;} + inline void SetOldVertex(unsigned long val_vertex) { OldVertex = val_vertex; } /*! * \brief retrieve vertex value not ordered. @@ -111,17 +109,17 @@ class CTurboVertex final : public CVertex { /*! * \brief set global index for ordered span-wise turbovertex. */ - inline void SetGlobalVertexIndex(int globalindex) { GlobalIndex = globalindex;} + inline void SetGlobalVertexIndex(int globalindex) { GlobalIndex = globalindex; } /*! * \brief get global index for ordered span-wise turbovertex. */ - inline int GetGlobalVertexIndex(void) const {return GlobalIndex;} + inline int GetGlobalVertexIndex(void) const { return GlobalIndex; } /*! * \brief set angular coord. */ - inline void SetAngularCoord(su2double angCoord) {AngularCoord = angCoord;} + inline void SetAngularCoord(su2double angCoord) { AngularCoord = angCoord; } /*! * \brief get angular coord. @@ -131,7 +129,7 @@ class CTurboVertex final : public CVertex { /*! * \brief set angular coord. */ - inline void SetDeltaAngularCoord(su2double deltaAngCoord){DeltaAngularCoord = deltaAngCoord;} + inline void SetDeltaAngularCoord(su2double deltaAngCoord) { DeltaAngularCoord = deltaAngCoord; } /*! * \brief get angular coord. @@ -141,11 +139,10 @@ class CTurboVertex final : public CVertex { /*! * \brief set angular coord. */ - inline void SetRelAngularCoord(su2double minAngCoord) {RelAngularCoord = AngularCoord - minAngCoord;} + inline void SetRelAngularCoord(su2double minAngCoord) { RelAngularCoord = AngularCoord - minAngCoord; } /*! * \brief get angular coord. */ - inline su2double GetRelAngularCoord(void) const {return RelAngularCoord;} - + inline su2double GetRelAngularCoord(void) const { return RelAngularCoord; } }; diff --git a/Common/include/geometry/dual_grid/CVertex.hpp b/Common/include/geometry/dual_grid/CVertex.hpp index d2baf9c387b..3d18f439eef 100644 --- a/Common/include/geometry/dual_grid/CVertex.hpp +++ b/Common/include/geometry/dual_grid/CVertex.hpp @@ -36,19 +36,19 @@ * \author F. Palacios */ class CVertex : public CDualGrid { -protected: - unsigned long Nodes[1]; /*!< \brief Vector to store the global nodes of an element. */ - su2double Normal[3] = {0.0}; /*!< \brief Normal coordinates of the element and its center of gravity. */ - su2double Aux_Var; /*!< \brief Auxiliar variable defined only on the surface. */ - su2double CartCoord[3] = {0.0}; /*!< \brief Vertex cartesians coordinates. */ - su2double VarCoord[3] = {0.0}; /*!< \brief Used for storing the coordinate variation due to a surface modification. */ - long PeriodicPoint[5] = {-1}; /*!< \brief Store the periodic point of a boundary (iProcessor, iPoint) */ - bool ActDisk_Perimeter = false; /*!< \brief Identify nodes at the perimeter of the actuator disk */ - short Rotation_Type; /*!< \brief Type of rotation associated with the vertex (MPI and periodic) */ - unsigned long Normal_Neighbor; /*!< \brief Index of the closest neighbor. */ - su2double Basis_Function[3] = {0.0}; /*!< \brief Basis function values for interpolation across zones. */ - -public: + protected: + unsigned long Nodes[1]; /*!< \brief Vector to store the global nodes of an element. */ + su2double Normal[3] = {0.0}; /*!< \brief Normal coordinates of the element and its center of gravity. */ + su2double Aux_Var; /*!< \brief Auxiliar variable defined only on the surface. */ + su2double CartCoord[3] = {0.0}; /*!< \brief Vertex cartesians coordinates. */ + su2double VarCoord[3] = {0.0}; /*!< \brief Used for storing the coordinate variation due to a surface modification. */ + long PeriodicPoint[5] = {-1}; /*!< \brief Store the periodic point of a boundary (iProcessor, iPoint) */ + bool ActDisk_Perimeter = false; /*!< \brief Identify nodes at the perimeter of the actuator disk */ + short Rotation_Type; /*!< \brief Type of rotation associated with the vertex (MPI and periodic) */ + unsigned long Normal_Neighbor; /*!< \brief Index of the closest neighbor. */ + su2double Basis_Function[3] = {0.0}; /*!< \brief Basis function values for interpolation across zones. */ + + public: /*! * \brief Constructor of the class. * \param[in] val_point - Node of the vertex. @@ -75,8 +75,8 @@ class CVertex : public CDualGrid { * \param[in] val_coord_Elem_CG - Coordinates of the centre of gravity of the element. * \return Compute the normal (dimensional) to the face that makes the vertex. */ - void SetNodes_Coord(const su2double *val_coord_Edge_CG, const su2double *val_coord_FaceElem_CG, - const su2double *val_coord_Elem_CG) override; + void SetNodes_Coord(const su2double* val_coord_Edge_CG, const su2double* val_coord_FaceElem_CG, + const su2double* val_coord_Elem_CG) override; /*! * \overload @@ -84,22 +84,21 @@ class CVertex : public CDualGrid { * \param[in] val_coord_Elem_CG - Coordinates of the centre of gravity of the element. * \return Compute the normal (dimensional) to the face that makes the vertex. */ - void SetNodes_Coord(const su2double *val_coord_Edge_CG, const su2double *val_coord_Elem_CG) override; + void SetNodes_Coord(const su2double* val_coord_Edge_CG, const su2double* val_coord_Elem_CG) override; /*! * \brief Copy the the normal vector of a face. * \param[in] val_normal - Vector where the subroutine is goint to copy the normal (dimensional). */ - inline void GetNormal(su2double *val_normal) const override { - for (unsigned short iDim = 0; iDim < nDim; iDim++) - val_normal[iDim] = Normal[iDim]; + inline void GetNormal(su2double* val_normal) const override { + for (unsigned short iDim = 0; iDim < nDim; iDim++) val_normal[iDim] = Normal[iDim]; } /*! * \brief Get the normal to a face of the control volume asociated with a vertex. * \return Dimensional normal vector, the modulus is the area of the face. */ - inline su2double *GetNormal(void) override { return Normal; } + inline su2double* GetNormal(void) override { return Normal; } /*! * \brief Get the ith component of the normal. @@ -110,8 +109,7 @@ class CVertex : public CDualGrid { * \brief Initialize normal vector. */ inline void SetZeroValues(void) override { - for (unsigned short iDim = 0; iDim < nDim; iDim ++) - Normal[iDim] = 0.0; + for (unsigned short iDim = 0; iDim < nDim; iDim++) Normal[iDim] = 0.0; } /*! @@ -137,58 +135,53 @@ class CVertex : public CDualGrid { * \param[in] val_face_normal - Vector to initialize the normal vector. * \return Value of the normal vector. */ - inline void SetNormal(const su2double *val_face_normal) override { - for (unsigned short iDim = 0; iDim < nDim; iDim++) - Normal[iDim]=val_face_normal[iDim]; + inline void SetNormal(const su2double* val_face_normal) override { + for (unsigned short iDim = 0; iDim < nDim; iDim++) Normal[iDim] = val_face_normal[iDim]; } /*! * \brief Add a vector to the normal vector. * \param[in] val_face_normal - Vector to add to the normal vector. */ - inline void AddNormal(const su2double *val_face_normal) override { - for(unsigned short iDim = 0; iDim < nDim; iDim++) - Normal[iDim] += val_face_normal[iDim]; + inline void AddNormal(const su2double* val_face_normal) override { + for (unsigned short iDim = 0; iDim < nDim; iDim++) Normal[iDim] += val_face_normal[iDim]; } /*! * \brief Set the value of the coordinate variation due to a surface modification. * \param[in] val_varcoord - Variation of the coordinate. */ - inline void SetVarCoord(const su2double *val_varcoord) { - for (unsigned short iDim = 0; iDim < nDim; iDim++) - VarCoord[iDim] = val_varcoord[iDim]; + inline void SetVarCoord(const su2double* val_varcoord) { + for (unsigned short iDim = 0; iDim < nDim; iDim++) VarCoord[iDim] = val_varcoord[iDim]; } /*! * \brief Add the value of the coordinate variation due to a surface modification. * \param[in] val_varcoord - Variation of the coordinate. */ - inline void AddVarCoord(const su2double *val_varcoord) { - for (unsigned short iDim = 0; iDim < nDim; iDim++) - VarCoord[iDim] += val_varcoord[iDim]; + inline void AddVarCoord(const su2double* val_varcoord) { + for (unsigned short iDim = 0; iDim < nDim; iDim++) VarCoord[iDim] += val_varcoord[iDim]; } /*! * \brief Get the value of the coordinate variation due to a surface modification. * \return Variation of the coordinate. */ - inline su2double *GetVarCoord(void) { return VarCoord; } + inline su2double* GetVarCoord(void) { return VarCoord; } /*! * \brief Set the value of the cartesian coordinate for the vertex. * \param[in] val_coord - Value of the cartesian coordinate. */ - inline void SetCoord(const su2double *val_coord) override { - for (unsigned short iDim = 0; iDim < nDim; iDim++) - CartCoord[iDim] = val_coord[iDim]; + inline void SetCoord(const su2double* val_coord) override { + for (unsigned short iDim = 0; iDim < nDim; iDim++) CartCoord[iDim] = val_coord[iDim]; } /*! * \brief Get the value of the cartesian coordinate for the vertex. * \return Value of the cartesian coordinate of the vertex. */ - inline su2double *GetCoord(void) override { return CartCoord; } + inline su2double* GetCoord(void) override { return CartCoord; } /*! * \brief Get the value of the cartesian coordinate for the vertex. @@ -293,7 +286,7 @@ class CVertex : public CDualGrid { * \brief Get the value of the periodic point of a vertex, and its somain * \return Value of the periodic point of a vertex, and the domain. */ - inline long *GetPeriodicPointDomain(void) { return PeriodicPoint; } + inline long* GetPeriodicPointDomain(void) { return PeriodicPoint; } /*! * \brief Get the value of the periodic point of a vertex, and its somain @@ -326,5 +319,4 @@ class CVertex : public CDualGrid { * \return Index of the closest neighbor. */ inline unsigned long GetNormal_Neighbor(void) const { return Normal_Neighbor; } - }; diff --git a/Common/include/geometry/elements/CElement.hpp b/Common/include/geometry/elements/CElement.hpp index e69e1e586e6..4c057ba59b2 100644 --- a/Common/include/geometry/elements/CElement.hpp +++ b/Common/include/geometry/elements/CElement.hpp @@ -56,39 +56,40 @@ * \author R. Sanchez */ class CElement { -protected: - enum : size_t {MAXNDIM = 3}; + protected: + enum : size_t { MAXNDIM = 3 }; - std::vector GaussPoint; /*!< \brief Vector of Gaussian Points. */ + std::vector GaussPoint; /*!< \brief Vector of Gaussian Points. */ - su2activematrix CurrentCoord; /*!< \brief Coordinates in the current frame. */ - su2activematrix RefCoord; /*!< \brief Coordinates in the reference frame. */ - su2activevector GaussWeight; /*!< \brief Weight of the Gaussian Points for the integration. */ - su2activematrix NodalExtrap; /*!< \brief Coordinates of the nodal points for Gaussian extrapolation. */ - su2activematrix NodalStress; /*!< \brief Stress at the nodes. */ + su2activematrix CurrentCoord; /*!< \brief Coordinates in the current frame. */ + su2activematrix RefCoord; /*!< \brief Coordinates in the reference frame. */ + su2activevector GaussWeight; /*!< \brief Weight of the Gaussian Points for the integration. */ + su2activematrix NodalExtrap; /*!< \brief Coordinates of the nodal points for Gaussian extrapolation. */ + su2activematrix NodalStress; /*!< \brief Stress at the nodes. */ /*--- Stiffness and load matrices. ---*/ - std::vector Kab; /*!< \brief Structure for the constitutive component of the tangent matrix. */ - su2activematrix Mab; /*!< \brief Structure for the nodal components of the mass matrix. */ - su2activematrix Ks_ab; /*!< \brief Structure for the stress component of the tangent matrix. */ - su2activematrix Kt_a; /*!< \brief Matrix of nodal stress terms for residual computation. */ - su2activematrix FDL_a; /*!< \brief Matrix of dead loads for residual computation. */ + std::vector Kab; /*!< \brief Structure for the constitutive component of the tangent matrix. */ + su2activematrix Mab; /*!< \brief Structure for the nodal components of the mass matrix. */ + su2activematrix Ks_ab; /*!< \brief Structure for the stress component of the tangent matrix. */ + su2activematrix Kt_a; /*!< \brief Matrix of nodal stress terms for residual computation. */ + su2activematrix FDL_a; /*!< \brief Matrix of dead loads for residual computation. */ - su2double el_Pressure = 0.0; /*!< \brief Pressure in the element. */ + su2double el_Pressure = 0.0; /*!< \brief Pressure in the element. */ - unsigned long iProp = 0; /*!< \brief ID of the Element Property. */ - unsigned long iDV = 0; /*!< \brief ID of the Design Variable (if it is element based). */ - unsigned long iDe = 0; /*!< \brief ID of the dielectric elastomer. */ + unsigned long iProp = 0; /*!< \brief ID of the Element Property. */ + unsigned long iDV = 0; /*!< \brief ID of the Design Variable (if it is element based). */ + unsigned long iDe = 0; /*!< \brief ID of the dielectric elastomer. */ - unsigned short nGaussPoints; /*!< \brief Number of gaussian points. */ - unsigned short nNodes; /*!< \brief Number of geometric points. */ - unsigned short nDim; /*!< \brief Number of dimension of the problem. */ + unsigned short nGaussPoints; /*!< \brief Number of gaussian points. */ + unsigned short nNodes; /*!< \brief Number of geometric points. */ + unsigned short nDim; /*!< \brief Number of dimension of the problem. */ - su2activematrix HiHj = 0.0; /*!< \brief Scalar product of 2 ansatz functions. */ - std::vector> DHiDHj; /*!< \brief Scalar product of the gradients of 2 ansatz functions. */ + su2activematrix HiHj = 0.0; /*!< \brief Scalar product of 2 ansatz functions. */ + std::vector> + DHiDHj; /*!< \brief Scalar product of the gradients of 2 ansatz functions. */ -public: - enum FrameType {REFERENCE=1, CURRENT=2}; /*!< \brief Type of nodal coordinates. */ + public: + enum FrameType { REFERENCE = 1, CURRENT = 2 }; /*!< \brief Type of nodal coordinates. */ /*! * \brief Default constructor of the class, deleted to make sure derived @@ -136,13 +137,13 @@ class CElement { * \brief Retrieve the number of nodes of the element. * \return Number of nodes of the element. */ - inline unsigned short GetnNodes(void) const {return nNodes;} + inline unsigned short GetnNodes(void) const { return nNodes; } /*! * \brief Retrieve the number of nodes of the element. * \return Number of Gaussian Points of the element. */ - inline unsigned short GetnGaussPoints(void) const {return nGaussPoints;} + inline unsigned short GetnGaussPoints(void) const { return nGaussPoints; } /*! * \brief Set the value of the coordinate of the nodes in the reference configuration. @@ -151,7 +152,7 @@ class CElement { * \param[in] val_CoordRef - Value of the coordinate. */ inline void SetRef_Coord(unsigned short iNode, unsigned short iDim, su2double val_CoordRef) { - RefCoord(iNode,iDim) = val_CoordRef; + RefCoord(iNode, iDim) = val_CoordRef; } /*! @@ -161,7 +162,7 @@ class CElement { * \param[in] val_CoordRef - Value of the coordinate. */ inline void SetCurr_Coord(unsigned short iNode, unsigned short iDim, su2double val_CoordCurr) { - CurrentCoord(iNode,iDim) = val_CoordCurr; + CurrentCoord(iNode, iDim) = val_CoordCurr; } /*! @@ -170,9 +171,7 @@ class CElement { * \param[in] iDim - Dimension. * \return Reference coordinate. */ - inline su2double GetRef_Coord(unsigned short iNode, unsigned short iDim) const { - return RefCoord(iNode,iDim); - } + inline su2double GetRef_Coord(unsigned short iNode, unsigned short iDim) const { return RefCoord(iNode, iDim); } /*! * \brief Get the value of the coordinate of the nodes in the current configuration. @@ -180,36 +179,28 @@ class CElement { * \param[in] iDim - Dimension. * \return Current coordinate. */ - inline su2double GetCurr_Coord(unsigned short iNode, unsigned short iDim) const { - return CurrentCoord(iNode,iDim); - } + inline su2double GetCurr_Coord(unsigned short iNode, unsigned short iDim) const { return CurrentCoord(iNode, iDim); } /*! * \brief Get the weight of the corresponding Gaussian Point. * \param[in] iGauss - index of the Gaussian point. * \return Weight. */ - inline su2double GetWeight(unsigned short iGauss) const { - return GaussWeight(iGauss); - } + inline su2double GetWeight(unsigned short iGauss) const { return GaussWeight(iGauss); } /*! * \brief Get the Jacobian respect to the reference configuration for the Gaussian Point iGauss. * \param[in] iGauss - index of the Gaussian point. * \return Jacobian. */ - inline su2double GetJ_X(unsigned short iGauss) const { - return GaussPoint[iGauss].GetJ_X(); - } + inline su2double GetJ_X(unsigned short iGauss) const { return GaussPoint[iGauss].GetJ_X(); } /*! * \brief Get the jacobian respect to the current configuration for the Gaussian Point iGauss. * \param[in] iGauss - index of the Gaussian point. * \return Jacobian. */ - inline su2double GetJ_x(unsigned short iGauss) const { - return GaussPoint[iGauss].GetJ_x(); - } + inline su2double GetJ_x(unsigned short iGauss) const { return GaussPoint[iGauss].GetJ_x(); } /*! * \brief Retrieve the value of the pressure in the element for incompressible materials. @@ -223,9 +214,7 @@ class CElement { * \param[in] nodeB - index of Node b. * \param[in] val_Ks_ab - value of the term that will constitute the diagonal of the stress contribution. */ - inline void Add_Mab(unsigned short nodeA, unsigned short nodeB, su2double val_Mab) { - Mab(nodeA,nodeB) += val_Mab; - } + inline void Add_Mab(unsigned short nodeA, unsigned short nodeB, su2double val_Mab) { Mab(nodeA, nodeB) += val_Mab; } /*! * \brief Add the value of a submatrix K relating nodes a and b, for the constitutive term. @@ -233,22 +222,19 @@ class CElement { * \param[in] nodeB - index of Node b. * \param[in] val_Kab - value of the matrix K. */ - inline void Add_Kab(unsigned short nodeA, unsigned short nodeB, su2double **val_Kab) { + inline void Add_Kab(unsigned short nodeA, unsigned short nodeB, su2double** val_Kab) { for (unsigned short iDim = 0; iDim < nDim; iDim++) - for (unsigned short jDim = 0; jDim < nDim; jDim++) - Kab[nodeA](nodeB, iDim*nDim+jDim) += val_Kab[iDim][jDim]; + for (unsigned short jDim = 0; jDim < nDim; jDim++) Kab[nodeA](nodeB, iDim * nDim + jDim) += val_Kab[iDim][jDim]; } /*! - * \brief Add the value of a submatrix K relating nodes a and b, for the constitutive term (symmetric terms need transpose) - * \param[in] nodeA - index of Node a. - * \param[in] nodeB - index of Node b. - * \param[in] val_Kab - value of the matrix K. + * \brief Add the value of a submatrix K relating nodes a and b, for the constitutive term (symmetric terms need + * transpose) \param[in] nodeA - index of Node a. \param[in] nodeB - index of Node b. \param[in] val_Kab - value of + * the matrix K. */ - inline void Add_Kab_T(unsigned short nodeA, unsigned short nodeB, su2double **val_Kab) { + inline void Add_Kab_T(unsigned short nodeA, unsigned short nodeB, su2double** val_Kab) { for (unsigned short iDim = 0; iDim < nDim; iDim++) - for (unsigned short jDim = 0; jDim < nDim; jDim++) - Kab[nodeA](nodeB, iDim*nDim+jDim) += val_Kab[jDim][iDim]; + for (unsigned short jDim = 0; jDim < nDim; jDim++) Kab[nodeA](nodeB, iDim * nDim + jDim) += val_Kab[jDim][iDim]; } /*! @@ -258,7 +244,7 @@ class CElement { * \param[in] val_Ks_ab - value of the term that will constitute the diagonal of the stress contribution. */ inline void Add_Ks_ab(unsigned short nodeA, unsigned short nodeB, su2double val_Ks_ab) { - Ks_ab(nodeA,nodeB) += val_Ks_ab; + Ks_ab(nodeA, nodeB) += val_Ks_ab; } /*! @@ -266,9 +252,8 @@ class CElement { * \param[in] nodeA - index of Node a. * \param[in] val_Kt_a - value of the term that will constitute the diagonal of the stress contribution. */ - inline void Add_Kt_a(unsigned short nodeA, const su2double *val_Kt_a) { - for(unsigned short iDim = 0; iDim < nDim; iDim++) - Kt_a(nodeA,iDim) += val_Kt_a[iDim]; + inline void Add_Kt_a(unsigned short nodeA, const su2double* val_Kt_a) { + for (unsigned short iDim = 0; iDim < nDim; iDim++) Kt_a(nodeA, iDim) += val_Kt_a[iDim]; } /*! @@ -276,15 +261,14 @@ class CElement { * \param[in] nodeA - index of Node a. * \param[in] val_FDL_a - value of the term that will constitute the diagonal of the stress contribution. */ - inline void Add_FDL_a(unsigned short nodeA, const su2double *val_FDL_a) { - for(unsigned short iDim = 0; iDim < nDim; iDim++) - FDL_a(nodeA,iDim) += val_FDL_a[iDim]; + inline void Add_FDL_a(unsigned short nodeA, const su2double* val_FDL_a) { + for (unsigned short iDim = 0; iDim < nDim; iDim++) FDL_a(nodeA, iDim) += val_FDL_a[iDim]; } /*! * \brief Restarts the values of stress in the element. */ - inline void ClearStress(void) {NodalStress.setConstant(0.0);} + inline void ClearStress(void) { NodalStress.setConstant(0.0); } /*! * \brief Return the value of the diagonal term for the mass matrix, relating nodes a and b. @@ -292,9 +276,7 @@ class CElement { * \param[in] nodeB - index of Node b. * \return Value of the diagonal term of Mab. */ - inline su2double Get_Mab(unsigned short nodeA, unsigned short nodeB) const { - return Mab(nodeA,nodeB); - } + inline su2double Get_Mab(unsigned short nodeA, unsigned short nodeB) const { return Mab(nodeA, nodeB); } /*! * \brief Return the value of the submatrix K relating nodes a and b. @@ -302,9 +284,7 @@ class CElement { * \param[in] nodeB - index of Node b. * \return Values of the matrix K. */ - inline const su2double *Get_Kab(unsigned short nodeA, unsigned short nodeB) const { - return Kab[nodeA][nodeB]; - } + inline const su2double* Get_Kab(unsigned short nodeA, unsigned short nodeB) const { return Kab[nodeA][nodeB]; } /*! * \brief Return the value of the diagonal term for the stress contribution, relating nodes a and b. @@ -312,27 +292,21 @@ class CElement { * \param[in] nodeB - index of Node b. * \return Value of the matrix Ks. */ - inline su2double Get_Ks_ab(unsigned short nodeA, unsigned short nodeB) const { - return Ks_ab(nodeA,nodeB); - } + inline su2double Get_Ks_ab(unsigned short nodeA, unsigned short nodeB) const { return Ks_ab(nodeA, nodeB); } /*! * \brief Return the values of the nodal stress components of the residual for node a. * \param[in] nodeA - index of Node a. * \return Values of the stress term. */ - inline const su2double *Get_Kt_a(unsigned short nodeA) const { - return Kt_a[nodeA]; - } + inline const su2double* Get_Kt_a(unsigned short nodeA) const { return Kt_a[nodeA]; } /*! * \brief Return the values of the dead load components of the residual for node a. * \param[in] nodeA - index of Node a. * \return Value of the dead loads. */ - inline const su2double *Get_FDL_a(unsigned short nodeA) const { - return FDL_a[nodeA]; - } + inline const su2double* Get_FDL_a(unsigned short nodeA) const { return FDL_a[nodeA]; } /*! * \brief Retrieve the value of the shape functions. @@ -340,9 +314,7 @@ class CElement { * \param[in] iGauss - Index of the Gaussian Point. * \return Gradient of the shape function related to node iNode and evaluated at Gaussian Point iGauss */ - inline su2double GetNi(unsigned short iNode, unsigned short iGauss) const { - return GaussPoint[iGauss].GetNi(iNode); - } + inline su2double GetNi(unsigned short iNode, unsigned short iGauss) const { return GaussPoint[iGauss].GetNi(iNode); } /*! * \brief Retrieve the value of the gradient of the shape functions respect to the reference configuration. @@ -352,7 +324,7 @@ class CElement { * \return Gradient of the shape function related to node iNode and evaluated at Gaussian Point iGauss */ inline su2double GetGradNi_X(unsigned short iNode, unsigned short iGauss, unsigned short iDim) const { - return GaussPoint[iGauss].GetGradNi_Xj(iNode,iDim); + return GaussPoint[iGauss].GetGradNi_Xj(iNode, iDim); } /*! @@ -363,7 +335,7 @@ class CElement { * \return Gradient of the shape function related to node iNode and evaluated at Gaussian Point iGauss */ inline su2double GetGradNi_x(unsigned short iNode, unsigned short iGauss, unsigned short iDim) const { - return GaussPoint[iGauss].GetGradNi_xj(iNode,iDim); + return GaussPoint[iGauss].GetGradNi_xj(iNode, iDim); } /*! @@ -373,7 +345,7 @@ class CElement { * \return Value of the shape function at the nodes for extrapolation purposes */ inline su2double GetNi_Extrap(unsigned short iNode, unsigned short iGauss) const { - return NodalExtrap(iNode,iGauss); + return NodalExtrap(iNode, iGauss); } /*! @@ -383,7 +355,7 @@ class CElement { * \param[in] val_Stress - Value of the stress added. */ inline void Add_NodalStress(unsigned short iNode, unsigned short iVar, su2double val_Stress) { - NodalStress(iNode,iVar) += val_Stress; + NodalStress(iNode, iVar) += val_Stress; } /*! @@ -392,76 +364,74 @@ class CElement { * \param[in] iVar - Variable index. * \return Value of the stress. */ - inline su2double Get_NodalStress(unsigned short iNode, unsigned short iVar) const { - return NodalStress(iNode,iVar); - } + inline su2double Get_NodalStress(unsigned short iNode, unsigned short iVar) const { return NodalStress(iNode, iVar); } /*! * \brief Store the values of the identifiers for element properties. * \param[in] element_property - element properties container. */ - inline void Set_ElProperties(const CProperty *element_property) { - iDV = element_property->GetDV(); + inline void Set_ElProperties(const CProperty* element_property) { + iDV = element_property->GetDV(); iProp = element_property->GetMat_Prop(); - iDe = element_property->GetElectric_Prop(); + iDe = element_property->GetElectric_Prop(); } /*! * \brief Store the value of the identifier for the Dielectric Elastomers. * \param[in] val_iDe - identifier of the DE property. */ - inline void Set_iDe(unsigned long val_iDe) {iDe = val_iDe;} + inline void Set_iDe(unsigned long val_iDe) { iDe = val_iDe; } /*! * \brief Return the value of the identifier for the Dielectric Elastomers. * \return Identifier of the DE property. */ - inline unsigned long Get_iDe(void) const {return iDe;} + inline unsigned long Get_iDe(void) const { return iDe; } /*! * \brief Return the value of the identifier for the Design Variable. * \return Identifier of the DV. */ - inline unsigned long Get_iDV(void) const {return iDV;} + inline unsigned long Get_iDV(void) const { return iDV; } /*! * \brief Return the value of the identifier for the Element Property. * \return Identifier of the property. */ - inline unsigned long Get_iProp(void) const {return iProp;} + inline unsigned long Get_iProp(void) const { return iProp; } /*! * \brief Compute the value of the length of the element. * \param[in] mode - Type of coordinates to consider in the computation. * \return Length of the (1D) element. */ - inline virtual su2double ComputeLength(const FrameType mode = REFERENCE) const {return 0.0;} + inline virtual su2double ComputeLength(const FrameType mode = REFERENCE) const { return 0.0; } /*! * \brief Compute the value of the area of the element. * \param[in] mode - Type of coordinates to consider in the computation. * \return Area of the (2D) element. */ - inline virtual su2double ComputeArea(const FrameType mode = REFERENCE) const {return 0.0;} + inline virtual su2double ComputeArea(const FrameType mode = REFERENCE) const { return 0.0; } /*! * \brief Compute the value of the volume of the element. * \param[in] mode - Type of coordinates to consider in the computation. * \return Volume of the (3D) element. */ - inline virtual su2double ComputeVolume(const FrameType mode = REFERENCE) const {return 0.0;} + inline virtual su2double ComputeVolume(const FrameType mode = REFERENCE) const { return 0.0; } /*! * \brief Compute the value of the area of the element in current coordinates (wrapper to ComputeArea(CURRENT)). * \return Current area of the (2D) element. */ - inline su2double ComputeCurrentArea(void) const {return ComputeArea(CURRENT);} + inline su2double ComputeCurrentArea(void) const { return ComputeArea(CURRENT); } /*! * \brief Compute the value of the volume of the element in current coordinates (wrapper to ComputeVolume(CURRENT)). * \return Current volume of the (3D) element. */ - inline su2double ComputeCurrentVolume(void) const {return ComputeVolume(CURRENT);} + inline su2double ComputeCurrentVolume(void) const { return ComputeVolume(CURRENT); } /*! * \brief Register the current and reference coordinates of the element as pre-accumulation inputs @@ -469,39 +439,32 @@ class CElement { * because inactive variables are ignored. */ inline void SetPreaccIn_Coords(bool nonlinear = true) { - AD::SetPreaccIn(RefCoord.data(), nNodes*MAXNDIM); - if (nonlinear) - AD::SetPreaccIn(CurrentCoord.data(), nNodes*MAXNDIM); + AD::SetPreaccIn(RefCoord.data(), nNodes * MAXNDIM); + if (nonlinear) AD::SetPreaccIn(CurrentCoord.data(), nNodes * MAXNDIM); } /*! * \brief Register the stress residual as a pre-accumulation output. When computing the element * stiffness matrix this is the only term that sees its way into the RHS of the system. */ - inline void SetPreaccOut_Kt_a(void) { - AD::SetPreaccOut(Kt_a.data(), nNodes*nDim); - } + inline void SetPreaccOut_Kt_a(void) { AD::SetPreaccOut(Kt_a.data(), nNodes * nDim); } /*! * \brief Register the mass matrix as a pre-accumulation output. */ - inline void SetPreaccOut_Mab(void) { - AD::SetPreaccOut(Mab.data(), nNodes*nNodes); - } + inline void SetPreaccOut_Mab(void) { AD::SetPreaccOut(Mab.data(), nNodes * nNodes); } /*! * \brief Register the dead load as a pre-accumulation output. */ - inline void SetPreaccOut_FDL_a(void) { - AD::SetPreaccOut(FDL_a.data(), nNodes*nDim); - } + inline void SetPreaccOut_FDL_a(void) { AD::SetPreaccOut(FDL_a.data(), nNodes * nDim); } - /*! - * \brief Add the scalar product of the shape functions to the tangent matrix. - * \param[in] nodeA - index of Node a. - * \param[in] nodeB - index of Node b. - * \param[in] val - value of the scalar product of ansatz function. - */ + /*! + * \brief Add the scalar product of the shape functions to the tangent matrix. + * \param[in] nodeA - index of Node a. + * \param[in] nodeB - index of Node b. + * \param[in] val - value of the scalar product of ansatz function. + */ inline void Add_HiHj(su2double val, unsigned short nodeA, unsigned short nodeB) { HiHj[nodeA][nodeB] += val; } /*! @@ -520,12 +483,12 @@ class CElement { } } - /*! - * \brief Add the transposed scalar product of the gradients of shape functions to the tangent matrix. - * \param[in] nodeA - index of Node a. - * \param[in] nodeB - index of Node b. - * \param[in] val - value of the term that will contribute. - */ + /*! + * \brief Add the transposed scalar product of the gradients of shape functions to the tangent matrix. + * \param[in] nodeA - index of Node a. + * \param[in] nodeB - index of Node b. + * \param[in] val - value of the term that will contribute. + */ template inline void Add_DHiDHj_T(const MatrixType& val, unsigned short nodeA, unsigned short nodeB) { unsigned short iDim, jDim; @@ -536,22 +499,21 @@ class CElement { } } - /*! - * \brief Get the scalar product of the shape functions to the tangent matrix. - * \param[in] nodeA - index of Node a. - * \param[in] nodeB - index of Node b. - * \param[out] val - value of the scalar product of ansatz function. - */ - inline su2double Get_HiHj(unsigned short nodeA, unsigned short nodeB) { return HiHj[nodeA][nodeB]; } - - /*! - * \brief Get the scalar product of the gradients of shape functions to the tangent matrix. - * \param[in] nodeA - index of Node a. - * \param[in] nodeB - index of Node b. - * \return val - value of the scalar product of gradients of ansatz function. - */ - inline su2activematrix& Get_DHiDHj(unsigned short nodeA, unsigned short nodeB) { return DHiDHj[nodeA][nodeB];} + /*! + * \brief Get the scalar product of the shape functions to the tangent matrix. + * \param[in] nodeA - index of Node a. + * \param[in] nodeB - index of Node b. + * \param[out] val - value of the scalar product of ansatz function. + */ + inline su2double Get_HiHj(unsigned short nodeA, unsigned short nodeB) { return HiHj[nodeA][nodeB]; } + /*! + * \brief Get the scalar product of the gradients of shape functions to the tangent matrix. + * \param[in] nodeA - index of Node a. + * \param[in] nodeB - index of Node b. + * \return val - value of the scalar product of gradients of ansatz function. + */ + inline su2activematrix& Get_DHiDHj(unsigned short nodeA, unsigned short nodeB) { return DHiDHj[nodeA][nodeB]; } }; /*! @@ -560,10 +522,9 @@ class CElement { * \brief Templated class to implement the computation of gradients for specific element sizes. * \author P. Gomes, R. Sanchez */ -template +template class CElementWithKnownSizes : public CElement { -private: - + private: FORCEINLINE static su2double JacobianAdjoint(const su2double Jacobian[][1], su2double ad[][1]) { /*--- Adjoint to Jacobian, we put 1.0 here so that ad/detJac is the inverse later ---*/ ad[0][0] = 1.0; @@ -572,28 +533,30 @@ class CElementWithKnownSizes : public CElement { } FORCEINLINE static su2double JacobianAdjoint(const su2double Jacobian[][2], su2double ad[][2]) { - ad[0][0] = Jacobian[1][1]; ad[0][1] = -Jacobian[0][1]; - ad[1][0] = -Jacobian[1][0]; ad[1][1] = Jacobian[0][0]; + ad[0][0] = Jacobian[1][1]; + ad[0][1] = -Jacobian[0][1]; + ad[1][0] = -Jacobian[1][0]; + ad[1][1] = Jacobian[0][0]; /*--- Determinant of Jacobian ---*/ - return ad[0][0]*ad[1][1]-ad[0][1]*ad[1][0]; + return ad[0][0] * ad[1][1] - ad[0][1] * ad[1][0]; } FORCEINLINE static su2double JacobianAdjoint(const su2double Jacobian[][3], su2double ad[][3]) { - ad[0][0] = Jacobian[1][1]*Jacobian[2][2]-Jacobian[1][2]*Jacobian[2][1]; - ad[0][1] = Jacobian[0][2]*Jacobian[2][1]-Jacobian[0][1]*Jacobian[2][2]; - ad[0][2] = Jacobian[0][1]*Jacobian[1][2]-Jacobian[0][2]*Jacobian[1][1]; - ad[1][0] = Jacobian[1][2]*Jacobian[2][0]-Jacobian[1][0]*Jacobian[2][2]; - ad[1][1] = Jacobian[0][0]*Jacobian[2][2]-Jacobian[0][2]*Jacobian[2][0]; - ad[1][2] = Jacobian[0][2]*Jacobian[1][0]-Jacobian[0][0]*Jacobian[1][2]; - ad[2][0] = Jacobian[1][0]*Jacobian[2][1]-Jacobian[1][1]*Jacobian[2][0]; - ad[2][1] = Jacobian[0][1]*Jacobian[2][0]-Jacobian[0][0]*Jacobian[2][1]; - ad[2][2] = Jacobian[0][0]*Jacobian[1][1]-Jacobian[0][1]*Jacobian[1][0]; + ad[0][0] = Jacobian[1][1] * Jacobian[2][2] - Jacobian[1][2] * Jacobian[2][1]; + ad[0][1] = Jacobian[0][2] * Jacobian[2][1] - Jacobian[0][1] * Jacobian[2][2]; + ad[0][2] = Jacobian[0][1] * Jacobian[1][2] - Jacobian[0][2] * Jacobian[1][1]; + ad[1][0] = Jacobian[1][2] * Jacobian[2][0] - Jacobian[1][0] * Jacobian[2][2]; + ad[1][1] = Jacobian[0][0] * Jacobian[2][2] - Jacobian[0][2] * Jacobian[2][0]; + ad[1][2] = Jacobian[0][2] * Jacobian[1][0] - Jacobian[0][0] * Jacobian[1][2]; + ad[2][0] = Jacobian[1][0] * Jacobian[2][1] - Jacobian[1][1] * Jacobian[2][0]; + ad[2][1] = Jacobian[0][1] * Jacobian[2][0] - Jacobian[0][0] * Jacobian[2][1]; + ad[2][2] = Jacobian[0][0] * Jacobian[1][1] - Jacobian[0][1] * Jacobian[1][0]; /*--- Determinant of Jacobian ---*/ - return Jacobian[0][0]*ad[0][0]+Jacobian[0][1]*ad[1][0]+Jacobian[0][2]*ad[2][0]; + return Jacobian[0][0] * ad[0][0] + Jacobian[0][1] * ad[1][0] + Jacobian[0][2] * ad[2][0]; } -protected: - static_assert(NDIM==1 || NDIM==2 || NDIM==3, "ComputeGrad_impl expects 1D, 2D or 3D"); + protected: + static_assert(NDIM == 1 || NDIM == 2 || NDIM == 3, "ComputeGrad_impl expects 1D, 2D or 3D"); su2double GaussCoord[NGAUSS][NDIM]; /*!< \brief Coordinates of the integration points. */ su2double dNiXj[NGAUSS][NNODE][NDIM]; /*!< \brief Shape function derivatives evaluated at the Gauss points. */ @@ -609,31 +572,27 @@ class CElementWithKnownSizes : public CElement { * \brief Implementation of gradient computation leveraging the static sizes. * \param[in] FRAME - template, REFERENCE or CURRENT coordinates. */ - template + template void ComputeGrad_impl(void) { - su2double Jacobian[NDIM][NDIM], ad[NDIM][NDIM]; unsigned short iNode, iDim, jDim, iGauss; /*--- Select the appropriate source for the nodal coordinates depending on the frame requested for the gradient computation, REFERENCE (undeformed) or CURRENT (deformed) ---*/ - const su2activematrix& Coord = (FRAME==REFERENCE) ? RefCoord : CurrentCoord; + const su2activematrix& Coord = (FRAME == REFERENCE) ? RefCoord : CurrentCoord; for (iGauss = 0; iGauss < NGAUSS; iGauss++) { - /*--- Jacobian transformation ---*/ /*--- This does dX/dXi transpose ---*/ for (iDim = 0; iDim < NDIM; iDim++) - for (jDim = 0; jDim < NDIM; jDim++) - Jacobian[iDim][jDim] = 0.0; + for (jDim = 0; jDim < NDIM; jDim++) Jacobian[iDim][jDim] = 0.0; for (iNode = 0; iNode < NNODE; iNode++) for (iDim = 0; iDim < NDIM; iDim++) - for (jDim = 0; jDim < NDIM; jDim++) - Jacobian[iDim][jDim] += Coord(iNode,jDim) * dNiXj[iGauss][iNode][iDim]; + for (jDim = 0; jDim < NDIM; jDim++) Jacobian[iDim][jDim] += Coord(iNode, jDim) * dNiXj[iGauss][iNode][iDim]; - if (NDIM==1) { + if (NDIM == 1) { /*--- Obviously the Jacobian is the slope of the line ---*/ Jacobian[0][0] = (Coord[1][0] - Coord[0][0]); } @@ -642,7 +601,7 @@ class CElementWithKnownSizes : public CElement { auto detJac = JacobianAdjoint(Jacobian, ad); - if (FRAME==REFERENCE) + if (FRAME == REFERENCE) GaussPoint[iGauss].SetJ_X(detJac); else GaussPoint[iGauss].SetJ_x(detJac); @@ -650,92 +609,84 @@ class CElementWithKnownSizes : public CElement { /*--- Jacobian inverse (it was already computed as transpose) ---*/ for (iDim = 0; iDim < NDIM; iDim++) - for (jDim = 0; jDim < NDIM; jDim++) - Jacobian[iDim][jDim] = ad[iDim][jDim]/detJac; + for (jDim = 0; jDim < NDIM; jDim++) Jacobian[iDim][jDim] = ad[iDim][jDim] / detJac; /*--- Derivatives with respect to global coordinates ---*/ for (iNode = 0; iNode < NNODE; iNode++) { for (iDim = 0; iDim < NDIM; iDim++) { su2double GradNi_Xj = 0.0; - for (jDim = 0; jDim < NDIM; jDim++) - GradNi_Xj += Jacobian[iDim][jDim] * dNiXj[iGauss][iNode][jDim]; + for (jDim = 0; jDim < NDIM; jDim++) GradNi_Xj += Jacobian[iDim][jDim] * dNiXj[iGauss][iNode][jDim]; - if (FRAME==REFERENCE) + if (FRAME == REFERENCE) GaussPoint[iGauss].SetGradNi_Xj(GradNi_Xj, iDim, iNode); else GaussPoint[iGauss].SetGradNi_xj(GradNi_Xj, iDim, iNode); } } - } - } - template + template void ComputeGrad_impl_surf_embedded() { - /*--- Select the appropriate source for the nodal coordinates depending on the frame requested for the gradient computation, REFERENCE (undeformed) or CURRENT (deformed) ---*/ - const su2activematrix& Coord = (FRAME==REFERENCE) ? RefCoord : CurrentCoord; + const su2activematrix& Coord = (FRAME == REFERENCE) ? RefCoord : CurrentCoord; - if (NDIM==1) { + if (NDIM == 1) { unsigned short iNode, iDim, iGauss; su2double Jacobian[2]; su2double val_grad; Jacobian[0] = (Coord[1][0] - Coord[0][0]); Jacobian[1] = (Coord[1][1] - Coord[0][1]); - const su2double JTJ = Jacobian[0]*Jacobian[0]+Jacobian[1]*Jacobian[1]; + const su2double JTJ = Jacobian[0] * Jacobian[0] + Jacobian[1] * Jacobian[1]; const su2double volJacobian = sqrt(JTJ); for (iGauss = 0; iGauss < NGAUSS; iGauss++) { - GaussPoint[iGauss].SetJ_X(volJacobian); for (iNode = 0; iNode < NNODE; iNode++) { - for (iDim=0; iDim(); } - }; /*! @@ -799,13 +748,13 @@ class CElementWithKnownSizes : public CElement { * \brief Tria element with 1 Gauss Points * \author R. Sanchez */ -class CTRIA1 final : public CElementWithKnownSizes<1,3,2> { -private: - enum : unsigned short {NGAUSS = 1}; - enum : unsigned short {NNODE = 3}; - enum : unsigned short {NDIM = 2}; +class CTRIA1 final : public CElementWithKnownSizes<1, 3, 2> { + private: + enum : unsigned short { NGAUSS = 1 }; + enum : unsigned short { NNODE = 3 }; + enum : unsigned short { NDIM = 2 }; -public: + public: /*! * \brief Constructor of the class. */ @@ -817,7 +766,6 @@ class CTRIA1 final : public CElementWithKnownSizes<1,3,2> { * \return Area of the element. */ su2double ComputeArea(const FrameType mode = REFERENCE) const override; - }; /*! @@ -826,13 +774,13 @@ class CTRIA1 final : public CElementWithKnownSizes<1,3,2> { * \brief Quadrilateral element with 4 Gauss Points * \author R. Sanchez */ -class CQUAD4 final : public CElementWithKnownSizes<4,4,2> { -private: - enum : unsigned short {NGAUSS = 4}; - enum : unsigned short {NNODE = 4}; - enum : unsigned short {NDIM = 2}; +class CQUAD4 final : public CElementWithKnownSizes<4, 4, 2> { + private: + enum : unsigned short { NGAUSS = 4 }; + enum : unsigned short { NNODE = 4 }; + enum : unsigned short { NDIM = 2 }; -public: + public: /*! * \brief Constructor of the class. */ @@ -842,20 +790,24 @@ class CQUAD4 final : public CElementWithKnownSizes<4,4,2> { * \brief Shape functions (Ni) evaluated at point Xi,Eta. */ inline static void ShapeFunctions(su2double Xi, su2double Eta, su2double* Ni) { - Ni[0] = 0.25*(1.0-Xi)*(1.0-Eta); - Ni[1] = 0.25*(1.0+Xi)*(1.0-Eta); - Ni[2] = 0.25*(1.0+Xi)*(1.0+Eta); - Ni[3] = 0.25*(1.0-Xi)*(1.0+Eta); + Ni[0] = 0.25 * (1.0 - Xi) * (1.0 - Eta); + Ni[1] = 0.25 * (1.0 + Xi) * (1.0 - Eta); + Ni[2] = 0.25 * (1.0 + Xi) * (1.0 + Eta); + Ni[3] = 0.25 * (1.0 - Xi) * (1.0 + Eta); } /*! * \brief Shape function Jacobian (dNi) evaluated at point Xi,Eta. */ inline static void ShapeFunctionJacobian(su2double Xi, su2double Eta, su2double dNi[][2]) { - dNi[0][0] = -0.25*(1.0-Eta); dNi[0][1] = -0.25*(1.0-Xi); - dNi[1][0] = 0.25*(1.0-Eta); dNi[1][1] = -0.25*(1.0+Xi); - dNi[2][0] = 0.25*(1.0+Eta); dNi[2][1] = 0.25*(1.0+Xi); - dNi[3][0] = -0.25*(1.0+Eta); dNi[3][1] = 0.25*(1.0-Xi); + dNi[0][0] = -0.25 * (1.0 - Eta); + dNi[0][1] = -0.25 * (1.0 - Xi); + dNi[1][0] = 0.25 * (1.0 - Eta); + dNi[1][1] = -0.25 * (1.0 + Xi); + dNi[2][0] = 0.25 * (1.0 + Eta); + dNi[2][1] = 0.25 * (1.0 + Xi); + dNi[3][0] = -0.25 * (1.0 + Eta); + dNi[3][1] = 0.25 * (1.0 - Xi); } /*! @@ -864,7 +816,6 @@ class CQUAD4 final : public CElementWithKnownSizes<4,4,2> { * \return Area of the element. */ su2double ComputeArea(const FrameType mode = REFERENCE) const override; - }; /*! @@ -873,13 +824,13 @@ class CQUAD4 final : public CElementWithKnownSizes<4,4,2> { * \brief Tetrahedral element with 1 Gauss Point * \author R. Sanchez */ -class CTETRA1 final : public CElementWithKnownSizes<1,4,3> { -private: - enum : unsigned short {NGAUSS = 1}; - enum : unsigned short {NNODE = 4}; - enum : unsigned short {NDIM = 3}; +class CTETRA1 final : public CElementWithKnownSizes<1, 4, 3> { + private: + enum : unsigned short { NGAUSS = 1 }; + enum : unsigned short { NNODE = 4 }; + enum : unsigned short { NDIM = 3 }; -public: + public: /*! * \brief Constructor of the class. */ @@ -890,7 +841,6 @@ class CTETRA1 final : public CElementWithKnownSizes<1,4,3> { * \return Volume of the element. */ su2double ComputeVolume(const FrameType mode = REFERENCE) const override; - }; /*! @@ -899,13 +849,13 @@ class CTETRA1 final : public CElementWithKnownSizes<1,4,3> { * \brief Hexahedral element with 8 Gauss Points * \author R. Sanchez */ -class CHEXA8 final : public CElementWithKnownSizes<8,8,3> { -private: - enum : unsigned short {NGAUSS = 8}; - enum : unsigned short {NNODE = 8}; - enum : unsigned short {NDIM = 3}; +class CHEXA8 final : public CElementWithKnownSizes<8, 8, 3> { + private: + enum : unsigned short { NGAUSS = 8 }; + enum : unsigned short { NNODE = 8 }; + enum : unsigned short { NDIM = 3 }; -public: + public: /*! * \brief Constructor of the class. */ @@ -917,7 +867,6 @@ class CHEXA8 final : public CElementWithKnownSizes<8,8,3> { * \return Volume of the element. */ su2double ComputeVolume(const FrameType mode = REFERENCE) const override; - }; /*! @@ -926,13 +875,13 @@ class CHEXA8 final : public CElementWithKnownSizes<8,8,3> { * \brief Pyramid element with 5 Gauss Points * \author R. Sanchez, F. Palacios, A. Bueno, T. Economon, S. Padron. */ -class CPYRAM5 final : public CElementWithKnownSizes<5,5,3> { -private: - enum : unsigned short {NGAUSS = 5}; - enum : unsigned short {NNODE = 5}; - enum : unsigned short {NDIM = 3}; +class CPYRAM5 final : public CElementWithKnownSizes<5, 5, 3> { + private: + enum : unsigned short { NGAUSS = 5 }; + enum : unsigned short { NNODE = 5 }; + enum : unsigned short { NDIM = 3 }; -public: + public: /*! * \brief Constructor of the class. */ @@ -944,7 +893,6 @@ class CPYRAM5 final : public CElementWithKnownSizes<5,5,3> { * \return Volume of the element. */ su2double ComputeVolume(const FrameType mode = REFERENCE) const override; - }; /*! @@ -954,13 +902,13 @@ class CPYRAM5 final : public CElementWithKnownSizes<5,5,3> { * \author R. Sanchez, F. Palacios, A. Bueno, T. Economon, S. Padron. * \version 7.5.1 "Blackbird" */ -class CPRISM6 final : public CElementWithKnownSizes<6,6,3> { -private: - enum : unsigned short {NGAUSS = 6}; - enum : unsigned short {NNODE = 6}; - enum : unsigned short {NDIM = 3}; +class CPRISM6 final : public CElementWithKnownSizes<6, 6, 3> { + private: + enum : unsigned short { NGAUSS = 6 }; + enum : unsigned short { NNODE = 6 }; + enum : unsigned short { NDIM = 3 }; -public: + public: /*! * \brief Constructor of the class. */ @@ -972,7 +920,6 @@ class CPRISM6 final : public CElementWithKnownSizes<6,6,3> { * \return Volume of the element. */ su2double ComputeVolume(const FrameType mode = REFERENCE) const override; - }; /*! @@ -981,13 +928,13 @@ class CPRISM6 final : public CElementWithKnownSizes<6,6,3> { * \brief Tria element with 3 Gauss Points * \author T.Dick */ -class CTRIA3 final : public CElementWithKnownSizes<3,3,2> { -private: - enum : unsigned short {NGAUSS = 3}; - enum : unsigned short {NNODE = 3}; - enum : unsigned short {NDIM = 2}; +class CTRIA3 final : public CElementWithKnownSizes<3, 3, 2> { + private: + enum : unsigned short { NGAUSS = 3 }; + enum : unsigned short { NNODE = 3 }; + enum : unsigned short { NDIM = 2 }; -public: + public: /*! * \brief Constructor of the class. */ @@ -999,7 +946,6 @@ class CTRIA3 final : public CElementWithKnownSizes<3,3,2> { * \return Area of the element. */ su2double ComputeArea(const FrameType mode = REFERENCE) const override; - }; /*! @@ -1008,13 +954,13 @@ class CTRIA3 final : public CElementWithKnownSizes<3,3,2> { * \brief Tetrahedral element with 4 Gauss Points * \author T.Dick */ -class CTETRA4 final : public CElementWithKnownSizes<4,4,3> { -private: - enum : unsigned short {NGAUSS = 4}; - enum : unsigned short {NNODE = 4}; - enum : unsigned short {NDIM = 3}; +class CTETRA4 final : public CElementWithKnownSizes<4, 4, 3> { + private: + enum : unsigned short { NGAUSS = 4 }; + enum : unsigned short { NNODE = 4 }; + enum : unsigned short { NDIM = 3 }; -public: + public: /*! * \brief Constructor of the class. */ @@ -1026,7 +972,6 @@ class CTETRA4 final : public CElementWithKnownSizes<4,4,3> { * \return Area of the element. */ su2double ComputeVolume(const FrameType mode = REFERENCE) const override; - }; /*! @@ -1035,13 +980,13 @@ class CTETRA4 final : public CElementWithKnownSizes<4,4,3> { * \brief Pyramid element with 6 Gauss Points * \author T.Dick */ -class CPYRAM6 final : public CElementWithKnownSizes<6,5,3> { -private: - enum : unsigned short {NGAUSS = 6}; - enum : unsigned short {NNODE = 5}; - enum : unsigned short {NDIM = 3}; +class CPYRAM6 final : public CElementWithKnownSizes<6, 5, 3> { + private: + enum : unsigned short { NGAUSS = 6 }; + enum : unsigned short { NNODE = 5 }; + enum : unsigned short { NDIM = 3 }; -public: + public: /*! * \brief Constructor of the class. */ @@ -1053,7 +998,6 @@ class CPYRAM6 final : public CElementWithKnownSizes<6,5,3> { * \return Volume of the element. */ su2double ComputeVolume(const FrameType mode = REFERENCE) const override; - }; /*! @@ -1062,13 +1006,13 @@ class CPYRAM6 final : public CElementWithKnownSizes<6,5,3> { * \brief Line element with 2 Gauss Points * \author T.Dick */ -class CLINE final : public CElementWithKnownSizes<2,2,1> { -private: - enum : unsigned short {NGAUSS = 2}; - enum : unsigned short {NNODE = 2}; - enum : unsigned short {NDIM = 1}; +class CLINE final : public CElementWithKnownSizes<2, 2, 1> { + private: + enum : unsigned short { NGAUSS = 2 }; + enum : unsigned short { NNODE = 2 }; + enum : unsigned short { NDIM = 1 }; -public: + public: /*! * \brief Constructor of the class. */ @@ -1080,5 +1024,4 @@ class CLINE final : public CElementWithKnownSizes<2,2,1> { * \return Area of the element. */ su2double ComputeLength(const FrameType mode = REFERENCE) const override; - }; diff --git a/Common/include/geometry/elements/CElementProperty.hpp b/Common/include/geometry/elements/CElementProperty.hpp index 4646ba0a7ce..fce7425694e 100644 --- a/Common/include/geometry/elements/CElementProperty.hpp +++ b/Common/include/geometry/elements/CElementProperty.hpp @@ -35,11 +35,10 @@ * \version 7.5.1 "Blackbird" */ class CProperty { -protected: + protected: + unsigned long iMat_Prop = 0; /*!< \brief Index of the properties (E, Nu) for the structural model used. */ - unsigned long iMat_Prop = 0; /*!< \brief Index of the properties (E, Nu) for the structural model used. */ - -public: + public: /*! * \brief Constructor of the class. * \param[in] valMat_Prop - Index of the physical properties (E,nu,rho,rho_dead_load) assigned to the element. @@ -102,7 +101,6 @@ class CProperty { inline virtual void RegisterDensity(void) {} }; - /*! * \class CElementProperty * \ingroup Elasticity_Equations @@ -111,29 +109,30 @@ class CProperty { * \version 7.5.1 "Blackbird" */ class CElementProperty final : public CProperty { -private: - - unsigned long iMat_Mod = 0; /*!< \brief Index of the material model used. */ - unsigned long iElectric_Prop = 0; /*!< \brief Index of the electric properties (Em) for the structural model used. */ - unsigned long iDV = 0; /*!< \brief Index of the group of design variables to which the element belongs. */ - su2double design_rho = 1.0; /*!< \brief Value of the design density for material-based topology optimization. */ - su2double physical_rho = 1.0; /*!< \brief Value of the physical density for material-based topology optimization. */ - -public: + private: + unsigned long iMat_Mod = 0; /*!< \brief Index of the material model used. */ + unsigned long iElectric_Prop = 0; /*!< \brief Index of the electric properties (Em) for the structural model used. */ + unsigned long iDV = 0; /*!< \brief Index of the group of design variables to which the element belongs. */ + su2double design_rho = 1.0; /*!< \brief Value of the design density for material-based topology optimization. */ + su2double physical_rho = 1.0; /*!< \brief Value of the physical density for material-based topology optimization. */ + public: /*! * \brief Constructor of the class. - * \param[in] valMat_Model - Type of material model (i.e. numerics) for the element, see FEA_TERM etc. in option_structure.hpp. - * \param[in] valMat_Prop - Index of the physical properties (E,nu,rho,rho_dead_load) assigned to the element. - * \param[in] valElectric_Prop - Index of the electric properties. - * \param[in] valDV - Index of the design variable assigned to the element (bound to a material property by "DESIGN_VARIABLE_FEA"). - * \param[in] valDensity - Value for Design and Physical densities (topology optimization variables). - */ - CElementProperty(unsigned long valMat_Model, unsigned long valMat_Prop, - unsigned long valElectric_Prop, unsigned long valDV, - su2double valDensity = 1.0) : CProperty(valMat_Prop), - iMat_Mod(valMat_Model), iElectric_Prop(valElectric_Prop), - iDV(valDV), design_rho(valDensity), physical_rho(valDensity) {} + * \param[in] valMat_Model - Type of material model (i.e. numerics) for the element, see FEA_TERM etc. in + * option_structure.hpp. \param[in] valMat_Prop - Index of the physical properties (E,nu,rho,rho_dead_load) assigned + * to the element. \param[in] valElectric_Prop - Index of the electric properties. \param[in] valDV - Index of the + * design variable assigned to the element (bound to a material property by "DESIGN_VARIABLE_FEA"). \param[in] + * valDensity - Value for Design and Physical densities (topology optimization variables). + */ + CElementProperty(unsigned long valMat_Model, unsigned long valMat_Prop, unsigned long valElectric_Prop, + unsigned long valDV, su2double valDensity = 1.0) + : CProperty(valMat_Prop), + iMat_Mod(valMat_Model), + iElectric_Prop(valElectric_Prop), + iDV(valDV), + design_rho(valDensity), + physical_rho(valDensity) {} /*! * \brief Destructor of the class. diff --git a/Common/include/geometry/elements/CGaussVariable.hpp b/Common/include/geometry/elements/CGaussVariable.hpp index d547d2de6a1..3ce313403b6 100644 --- a/Common/include/geometry/elements/CGaussVariable.hpp +++ b/Common/include/geometry/elements/CGaussVariable.hpp @@ -36,16 +36,15 @@ * \version 7.5.1 "Blackbird" */ class CGaussVariable { -protected: - - su2activematrix GradNi_Xj; /*!< \brief Gradient of the shape functions N[i] wrt the reference configuration. */ - su2activematrix GradNi_xj; /*!< \brief Gradient of the shape functions N[i] wrt the current configuration. */ - su2activevector Ni; /*!< \brief Shape functions N[i] at the gaussian point. */ - su2double J_X = 0.0; /*!< \brief Element Jacobian evaluated at this Gauss Point wrt the reference configuration. */ - su2double J_x = 0.0; /*!< \brief Element Jacobian evaluated at this Gauss Point wrt the current configuration. */ + protected: + su2activematrix GradNi_Xj; /*!< \brief Gradient of the shape functions N[i] wrt the reference configuration. */ + su2activematrix GradNi_xj; /*!< \brief Gradient of the shape functions N[i] wrt the current configuration. */ + su2activevector Ni; /*!< \brief Shape functions N[i] at the gaussian point. */ + su2double J_X = 0.0; /*!< \brief Element Jacobian evaluated at this Gauss Point wrt the reference configuration. */ + su2double J_x = 0.0; /*!< \brief Element Jacobian evaluated at this Gauss Point wrt the current configuration. */ unsigned short iGaussPoint = 0; /*!< \brief Identifier of the Gauss point considered. */ -public: + public: /*! * \brief Deleted default constructor as this class does not allow resizing once created. */ @@ -58,13 +57,11 @@ class CGaussVariable { * \param[in] config - Definition of the particular problem. */ CGaussVariable(unsigned short val_iGauss, unsigned short val_nDim, unsigned short val_nNodes) - : J_X(0.0), J_x(0.0), iGaussPoint(val_iGauss) - { - + : J_X(0.0), J_x(0.0), iGaussPoint(val_iGauss) { /* --- For the structural mechanics solver the dimensions (nNodes x nDim) are sufficient. * For the Sobolev smoothing solver dimensions (nNodes x (nDim+1)) are necessary * when working on a curved design surface embedded in 3D. ---*/ - GradNi_Xj.resize(val_nNodes,val_nDim+1) = su2double(0.0); + GradNi_Xj.resize(val_nNodes, val_nDim + 1) = su2double(0.0); GradNi_xj = GradNi_Xj; Ni.resize(val_nNodes) = su2double(0.0); @@ -89,7 +86,6 @@ class CGaussVariable { inline void SetJ_x(su2double valJ_x) { J_x = valJ_x; } - inline su2double GetGradNi_Xj(unsigned short val_Ni, unsigned short val_iDim) const { return GradNi_Xj(val_Ni, val_iDim); } @@ -105,6 +101,4 @@ class CGaussVariable { inline su2double GetJ_x(void) const { return J_x; } inline unsigned short Get_iGauss(void) const { return iGaussPoint; } - }; - diff --git a/Common/include/geometry/meshreader/CBoxMeshReaderFVM.hpp b/Common/include/geometry/meshreader/CBoxMeshReaderFVM.hpp index a9863e424d9..58ab28752b4 100644 --- a/Common/include/geometry/meshreader/CBoxMeshReaderFVM.hpp +++ b/Common/include/geometry/meshreader/CBoxMeshReaderFVM.hpp @@ -35,10 +35,8 @@ * \brief Reads a 3D box grid into linear partitions for the finite volume solver (FVM). * \author: T. Economon */ -class CBoxMeshReaderFVM: public CMeshReaderFVM { - -private: - +class CBoxMeshReaderFVM : public CMeshReaderFVM { + private: unsigned long nNode; /*!< \brief Number of grid nodes in the x-direction. */ unsigned long mNode; /*!< \brief Number of grid nodes in the y-direction. */ unsigned long pNode; /*!< \brief Number of grid nodes in the z-direction. */ @@ -69,18 +67,14 @@ class CBoxMeshReaderFVM: public CMeshReaderFVM { */ void ComputeBoxSurfaceConnectivity(); -public: - + public: /*! * \brief Constructor of the CBoxMeshReaderFVM class. */ - CBoxMeshReaderFVM(CConfig *val_config, - unsigned short val_iZone, - unsigned short val_nZone); + CBoxMeshReaderFVM(CConfig* val_config, unsigned short val_iZone, unsigned short val_nZone); /*! * \brief Destructor of the CBoxMeshReaderFVM class. */ ~CBoxMeshReaderFVM(void); - }; diff --git a/Common/include/geometry/meshreader/CCGNSMeshReaderFVM.hpp b/Common/include/geometry/meshreader/CCGNSMeshReaderFVM.hpp index c5448dfa9a0..5b65f4d925b 100644 --- a/Common/include/geometry/meshreader/CCGNSMeshReaderFVM.hpp +++ b/Common/include/geometry/meshreader/CCGNSMeshReaderFVM.hpp @@ -39,21 +39,24 @@ * \brief Reads a CGNS zone into linear partitions for the finite volume solver (FVM). * \author: T. Economon */ -class CCGNSMeshReaderFVM: public CMeshReaderFVM { - -private: - +class CCGNSMeshReaderFVM : public CMeshReaderFVM { + private: #ifdef HAVE_CGNS - int cgnsFileID; /*!< \brief CGNS file identifier. */ + int cgnsFileID; /*!< \brief CGNS file identifier. */ const int cgnsBase = 1; /*!< \brief CGNS database index (the CGNS reader currently assumes a single database). */ const int cgnsZone = 1; /*!< \brief CGNS zone index (and 1 zone in that database). */ - int nSections; /*!< \brief Total number of sections in the CGNS file. */ - - vector isInterior; /*!< \brief Vector of booleans to store whether each section in the CGNS file is an interior or boundary section. */ - vector nElems; /*!< \brief Vector containing the local number of elements found within each CGNS section. */ - vector elemOffset; /*!< \brief Global ID offset for each interior section (i.e., the total number of global elements that came before it). */ - vector > connElems; /*!< \brief Vector containing the local element connectivity found within each CGNS section. First index is the section, second contains the connectivity in format [globalID VTK n1 n2 n3 n4 n5 n6 n7 n8] for each element. */ + int nSections; /*!< \brief Total number of sections in the CGNS file. */ + + vector isInterior; /*!< \brief Vector of booleans to store whether each section in the CGNS file is an interior + or boundary section. */ + vector + nElems; /*!< \brief Vector containing the local number of elements found within each CGNS section. */ + vector elemOffset; /*!< \brief Global ID offset for each interior section (i.e., the total number of + global elements that came before it). */ + vector > connElems; /*!< \brief Vector containing the local element connectivity found within each + CGNS section. First index is the section, second contains the connectivity in + format [globalID VTK n1 n2 n3 n4 n5 n6 n7 n8] for each element. */ vector > sectionNames; /*!< \brief Vector for storing the names of each boundary section (marker). */ /*! @@ -78,7 +81,8 @@ class CCGNSMeshReaderFVM: public CMeshReaderFVM { void ReadCGNSPointCoordinates(); /*! - * \brief Reads the metadata for each CGNS section in a zone and collect information, including the size and whether it is an interior or boundary section. + * \brief Reads the metadata for each CGNS section in a zone and collect information, including the size and whether + * it is an interior or boundary section. */ void ReadCGNSSectionMetadata(); @@ -89,8 +93,8 @@ class CCGNSMeshReaderFVM: public CMeshReaderFVM { void ReadCGNSVolumeSection(int val_section); /*! - * \brief Reads the surface (boundary) elements from the CGNS zone. Only the master rank currently reads and stores the connectivity, which is linearly partitioned later. - * \param[in] val_section - CGNS section index. + * \brief Reads the surface (boundary) elements from the CGNS zone. Only the master rank currently reads and stores + * the connectivity, which is linearly partitioned later. \param[in] val_section - CGNS section index. */ void ReadCGNSSurfaceSection(int val_section); @@ -110,27 +114,20 @@ class CCGNSMeshReaderFVM: public CMeshReaderFVM { * \param[out] val_vtk_type - VTK type identifier index. * \returns String containing the name of the element type. */ - string GetCGNSElementType(ElementType_t val_elem_type, - int &val_vtk_type); + string GetCGNSElementType(ElementType_t val_elem_type, int& val_vtk_type); #endif /*! * \brief Routine to launch non-blocking sends and recvs amongst all processors. * \param[in] bufSend - Buffer of data to be sent. - * \param[in] nElemSend - Array containing the number of elements to send to other processors in cumulative storage format. - * \param[in] sendReq - Array of MPI send requests. - * \param[in] bufRecv - Buffer of data to be received. - * \param[in] nElemSend - Array containing the number of elements to receive from other processors in cumulative storage format. - * \param[in] sendReq - Array of MPI recv requests. - * \param[in] countPerElem - Pieces of data per element communicated. + * \param[in] nElemSend - Array containing the number of elements to send to other processors in cumulative storage + * format. \param[in] sendReq - Array of MPI send requests. \param[in] bufRecv - Buffer of data to be received. + * \param[in] nElemSend - Array containing the number of elements to receive from other processors in cumulative + * storage format. \param[in] sendReq - Array of MPI recv requests. \param[in] countPerElem - Pieces of data per + * element communicated. */ - void InitiateCommsAll(void *bufSend, - const int *nElemSend, - SU2_MPI::Request *sendReq, - void *bufRecv, - const int *nElemRecv, - SU2_MPI::Request *recvReq, - unsigned short countPerElem, + void InitiateCommsAll(void* bufSend, const int* nElemSend, SU2_MPI::Request* sendReq, void* bufRecv, + const int* nElemRecv, SU2_MPI::Request* recvReq, unsigned short countPerElem, unsigned short commType); /*! @@ -140,24 +137,16 @@ class CCGNSMeshReaderFVM: public CMeshReaderFVM { * \param[in] nRecvs - Number of receives to be completed. * \param[in] sendReq - Array of MPI recv requests. */ - void CompleteCommsAll(int nSends, - SU2_MPI::Request *sendReq, - int nRecvs, - SU2_MPI::Request *recvReq); - - -public: + void CompleteCommsAll(int nSends, SU2_MPI::Request* sendReq, int nRecvs, SU2_MPI::Request* recvReq); + public: /*! * \brief Constructor of the CCGNSMeshReaderFVM class. */ - CCGNSMeshReaderFVM(CConfig *val_config, - unsigned short val_iZone, - unsigned short val_nZone); + CCGNSMeshReaderFVM(CConfig* val_config, unsigned short val_iZone, unsigned short val_nZone); /*! * \brief Destructor of the CCGNSMeshReaderFVM class. */ ~CCGNSMeshReaderFVM(void); - }; diff --git a/Common/include/geometry/meshreader/CMeshReaderFVM.hpp b/Common/include/geometry/meshreader/CMeshReaderFVM.hpp index 000dd0cf1e8..f4a46384e3d 100644 --- a/Common/include/geometry/meshreader/CMeshReaderFVM.hpp +++ b/Common/include/geometry/meshreader/CMeshReaderFVM.hpp @@ -40,62 +40,60 @@ * \author T. Economon */ class CMeshReaderFVM { - -protected: - - const int rank; /*!< \brief MPI Rank. */ - const int size; /*!< \brief MPI Size. */ + protected: + const int rank; /*!< \brief MPI Rank. */ + const int size; /*!< \brief MPI Size. */ const CConfig* config = nullptr; /*!< \brief Local pointer to the config parameter object. */ unsigned short dimension = 0; /*!< \brief Dimension of the problem (2 or 3). */ - unsigned long numberOfLocalPoints = 0; /*!< \brief Number of local grid points within the linear partition on this rank. */ - unsigned long numberOfGlobalPoints = 0; /*!< \brief Number of global grid points within the mesh file. */ - vector > localPointCoordinates; /*!< \brief Vector holding the coordinates from the mesh file for the local grid points. First index is dimension, second is point index. */ + unsigned long numberOfLocalPoints = + 0; /*!< \brief Number of local grid points within the linear partition on this rank. */ + unsigned long numberOfGlobalPoints = 0; /*!< \brief Number of global grid points within the mesh file. */ + vector > + localPointCoordinates; /*!< \brief Vector holding the coordinates from the mesh file for the local grid points. + First index is dimension, second is point index. */ - unsigned long numberOfLocalElements = 0; /*!< \brief Number of local elements within the linear partition on this rank. */ + unsigned long numberOfLocalElements = + 0; /*!< \brief Number of local elements within the linear partition on this rank. */ unsigned long numberOfGlobalElements = 0; /*!< \brief Number of global elements within the mesh file. */ - vector localVolumeElementConnectivity; /*!< \brief Vector containing the element connectivity from the mesh file for the local elements. */ + vector localVolumeElementConnectivity; /*!< \brief Vector containing the element connectivity from the + mesh file for the local elements. */ - unsigned long numberOfMarkers = 0; /*!< \brief Total number of markers contained within the mesh file. */ - vector markerNames; /*!< \brief String names for all markers in the mesh file. */ - vector > surfaceElementConnectivity; /*!< \brief Vector containing the surface element connectivity from the mesh file on a per-marker basis. Only the master node reads and stores this connectivity. */ - -public: + unsigned long numberOfMarkers = 0; /*!< \brief Total number of markers contained within the mesh file. */ + vector markerNames; /*!< \brief String names for all markers in the mesh file. */ + vector > + surfaceElementConnectivity; /*!< \brief Vector containing the surface element connectivity from the mesh file on a + per-marker basis. Only the master node reads and stores this connectivity. */ + public: /*! * \brief Constructor of the CMeshReaderFVM class. * \param[in] val_config - config object for the current zone. * \param[in] val_iZone - Current zone index. * \param[in] val_nZone - Total number of zones. */ - CMeshReaderFVM(const CConfig *val_config, - unsigned short val_iZone, - unsigned short val_nZone); + CMeshReaderFVM(const CConfig* val_config, unsigned short val_iZone, unsigned short val_nZone); /*! * \brief Get the physical dimension of the problem (2 or 3). * \returns Physical dimension of the problem. */ - inline unsigned short GetDimension() const { - return dimension; - } + inline unsigned short GetDimension() const { return dimension; } /*! * \brief Get the local point coordinates (linearly partitioned). * \returns Local point coordinates (linear partitioned). */ - inline const vector > &GetLocalPointCoordinates() const { - return localPointCoordinates; - } + inline const vector >& GetLocalPointCoordinates() const { return localPointCoordinates; } /*! - * \brief Get the surface element connectivity for the specified marker. Only the master node owns the surface connectivity. - * \param[in] val_iMarker - current marker index. - * \returns Surface element connecitivity for a marker from the master rank. + * \brief Get the surface element connectivity for the specified marker. Only the master node owns the surface + * connectivity. \param[in] val_iMarker - current marker index. \returns Surface element connecitivity for a marker + * from the master rank. */ - inline const vector &GetSurfaceElementConnectivityForMarker(int val_iMarker) const { + inline const vector& GetSurfaceElementConnectivityForMarker(int val_iMarker) const { return surfaceElementConnectivity[val_iMarker]; } @@ -105,14 +103,14 @@ class CMeshReaderFVM { * \returns Number of surface elements for a marker. */ inline unsigned long GetNumberOfSurfaceElementsForMarker(int val_iMarker) const { - return (unsigned long)surfaceElementConnectivity[val_iMarker].size()/SU2_CONN_SIZE; + return (unsigned long)surfaceElementConnectivity[val_iMarker].size() / SU2_CONN_SIZE; } /*! * \brief Get the local volume element connectivity (linearly partitioned). * \returns Local volume element connectivity (linearly partitioned). */ - inline const vector &GetLocalVolumeElementConnectivity() const { + inline const vector& GetLocalVolumeElementConnectivity() const { return localVolumeElementConnectivity; } @@ -120,48 +118,35 @@ class CMeshReaderFVM { * \brief Get the total number of markers in the mesh zone. * \returns Total number of markers in the mesh zone. */ - inline unsigned long GetNumberOfMarkers() const { - return numberOfMarkers; - } + inline unsigned long GetNumberOfMarkers() const { return numberOfMarkers; } /*! * \brief Get the vector of string names for all markers in the mesh zone. * \returns Vector of string names for all markers in the mesh zone. */ - inline const vector &GetMarkerNames() const { - return markerNames; - } + inline const vector& GetMarkerNames() const { return markerNames; } /*! * \brief Get the number of local grid points within the linear partition on this rank. * \returns Number of local grid points within the linear partition on this rank. */ - inline unsigned long GetNumberOfLocalPoints() const { - return numberOfLocalPoints; - } + inline unsigned long GetNumberOfLocalPoints() const { return numberOfLocalPoints; } /*! * \brief Get the number of global grid points within the mesh file. * \returns Number of global grid points within the mesh file. */ - inline unsigned long GetNumberOfGlobalPoints() const { - return numberOfGlobalPoints; - } + inline unsigned long GetNumberOfGlobalPoints() const { return numberOfGlobalPoints; } /*! * \brief Get the number of local elements within the linear partition on this rank. * \returns Number of local elements within the linear partition on this rank. */ - inline unsigned long GetNumberOfLocalElements() const { - return numberOfLocalElements; - } + inline unsigned long GetNumberOfLocalElements() const { return numberOfLocalElements; } /*! * \brief Get the number of global elements within the mesh file. * \returns Number of global elements within the mesh file. */ - inline unsigned long GetNumberOfGlobalElements() const { - return numberOfGlobalElements; - } - + inline unsigned long GetNumberOfGlobalElements() const { return numberOfGlobalElements; } }; diff --git a/Common/include/geometry/meshreader/CRectangularMeshReaderFVM.hpp b/Common/include/geometry/meshreader/CRectangularMeshReaderFVM.hpp index f20cf26a702..ed040f4c6b4 100644 --- a/Common/include/geometry/meshreader/CRectangularMeshReaderFVM.hpp +++ b/Common/include/geometry/meshreader/CRectangularMeshReaderFVM.hpp @@ -35,10 +35,8 @@ * \brief Reads a 2D rectangular grid into linear partitions for the finite volume solver (FVM). * \author: T. Economon */ -class CRectangularMeshReaderFVM: public CMeshReaderFVM { - -private: - +class CRectangularMeshReaderFVM : public CMeshReaderFVM { + private: unsigned long nNode; /*!< \brief Number of grid nodes in the x-direction. */ unsigned long mNode; /*!< \brief Number of grid nodes in the y-direction. */ @@ -66,13 +64,9 @@ class CRectangularMeshReaderFVM: public CMeshReaderFVM { */ void ComputeRectangularSurfaceConnectivity(); -public: - + public: /*! * \brief Constructor of the CRectangularMeshReaderFVM class. */ - CRectangularMeshReaderFVM(const CConfig *val_config, - unsigned short val_iZone, - unsigned short val_nZone); - + CRectangularMeshReaderFVM(const CConfig* val_config, unsigned short val_iZone, unsigned short val_nZone); }; diff --git a/Common/include/geometry/meshreader/CSU2ASCIIMeshReaderFVM.hpp b/Common/include/geometry/meshreader/CSU2ASCIIMeshReaderFVM.hpp index 6be7697534f..a63f07a75d4 100644 --- a/Common/include/geometry/meshreader/CSU2ASCIIMeshReaderFVM.hpp +++ b/Common/include/geometry/meshreader/CSU2ASCIIMeshReaderFVM.hpp @@ -37,9 +37,8 @@ * \brief Reads a native SU2 ASCII grid into linear partitions for the finite volume solver (FVM). * \author T. Economon */ -class CSU2ASCIIMeshReaderFVM: public CMeshReaderFVM { - -private: +class CSU2ASCIIMeshReaderFVM : public CMeshReaderFVM { + private: enum class FileSection { POINTS, ELEMENTS, MARKERS }; /*!< \brief Different sections of the file. */ std::array SectionOrder{}; /*!< \brief Order of the sections in the file. */ @@ -47,11 +46,12 @@ class CSU2ASCIIMeshReaderFVM: public CMeshReaderFVM { const unsigned short nZones; /*!< \brief Total number of zones in the SU2 file. */ const string meshFilename; /*!< \brief Name of the SU2 ASCII mesh file being read. */ - ifstream mesh_file; /*!< \brief File object for the SU2 ASCII mesh file. */ + ifstream mesh_file; /*!< \brief File object for the SU2 ASCII mesh file. */ bool actuator_disk; /*!< \brief Boolean for whether we have an actuator disk to split. */ - unsigned long ActDiskNewPoints = 0; /*!< \brief Total number of new grid points to add due to actuator disk splitting. */ + unsigned long ActDiskNewPoints = + 0; /*!< \brief Total number of new grid points to add due to actuator disk splitting. */ su2double Xloc = 0.0; /*!< \brief X-coordinate of the CG of the actuator disk surface. */ su2double Yloc = 0.0; /*!< \brief X-coordinate of the CG of the actuator disk surface. */ @@ -59,12 +59,17 @@ class CSU2ASCIIMeshReaderFVM: public CMeshReaderFVM { vector ActDisk_Bool; /*!< \brief Flag to identify the grid points on the actuator disk. */ - vector ActDiskPoint_Back; /*!< \brief Vector containing the global index for the new grid points added to the back of the actuator disk. */ - vector VolumePoint_Inv; /*!< \brief Vector containing the inverse mapping from the global index to the added point index for the actuator disk. */ + vector ActDiskPoint_Back; /*!< \brief Vector containing the global index for the new grid points added + to the back of the actuator disk. */ + vector VolumePoint_Inv; /*!< \brief Vector containing the inverse mapping from the global index to the + added point index for the actuator disk. */ - vector CoordXActDisk; /*!< \brief X-coordinates of the new grid points added by splitting the actuator disk (size = ActDiskNewPoints). */ - vector CoordYActDisk; /*!< \brief Y-coordinates of the new grid points added by splitting the actuator disk (size = ActDiskNewPoints). */ - vector CoordZActDisk; /*!< \brief Z-coordinates of the new grid points added by splitting the actuator disk (size = ActDiskNewPoints). */ + vector CoordXActDisk; /*!< \brief X-coordinates of the new grid points added by splitting the actuator disk + (size = ActDiskNewPoints). */ + vector CoordYActDisk; /*!< \brief Y-coordinates of the new grid points added by splitting the actuator disk + (size = ActDiskNewPoints). */ + vector CoordZActDisk; /*!< \brief Z-coordinates of the new grid points added by splitting the actuator disk + (size = ActDiskNewPoints). */ vector CoordXVolumePoint; /*!< \brief X-coordinates of the volume elements touching the actuator disk. */ vector CoordYVolumePoint; /*!< \brief Y-coordinates of the volume elements touching the actuator disk. */ @@ -72,11 +77,11 @@ class CSU2ASCIIMeshReaderFVM: public CMeshReaderFVM { /*! * \brief Reads all SU2 ASCII mesh metadata and checks for errors. - * \param[in] single_pass - Try to read the contents together with the metadata if the order allows (points before elements). - * \param[in,out] config - Problem configuration where some metadata is updated (e.g. AoA). - * \returns True if single_pass was successful. + * \param[in] single_pass - Try to read the contents together with the metadata if the order allows (points before + * elements). \param[in,out] config - Problem configuration where some metadata is updated (e.g. AoA). \returns True + * if single_pass was successful. */ - bool ReadMetadata(const bool single_pass, CConfig *config); + bool ReadMetadata(const bool single_pass, CConfig* config); /*! * \brief Splits a single surface actuator disk boundary into two separate markers (repeated points). @@ -103,13 +108,9 @@ class CSU2ASCIIMeshReaderFVM: public CMeshReaderFVM { */ void FastForwardToMyZone(); -public: - + public: /*! * \brief Constructor of the CSU2ASCIIMeshReaderFVM class. */ - CSU2ASCIIMeshReaderFVM(CConfig *val_config, - unsigned short val_iZone, - unsigned short val_nZone); - + CSU2ASCIIMeshReaderFVM(CConfig* val_config, unsigned short val_iZone, unsigned short val_nZone); }; diff --git a/Common/include/geometry/primal_grid/CHexahedron.hpp b/Common/include/geometry/primal_grid/CHexahedron.hpp index b249559e683..b6d2da966d1 100644 --- a/Common/include/geometry/primal_grid/CHexahedron.hpp +++ b/Common/include/geometry/primal_grid/CHexahedron.hpp @@ -39,10 +39,12 @@ struct CHexahedronConnectivity { enum { nFaces = N_FACES_HEXAHEDRON }; enum { maxNodesFace = N_POINTS_QUADRILATERAL }; enum { VTK_Type = HEXAHEDRON }; - static constexpr unsigned short nNodesFace[6] = {4,4,4,4,4,4}; - static constexpr unsigned short Faces[6][4] = {{0,1,5,4},{1,2,6,5},{2,3,7,6},{3,0,4,7},{0,3,2,1},{4,5,6,7}}; - static constexpr unsigned short nNeighbor_Nodes[8] = {3,3,3,3,3,3,3,3}; - static constexpr unsigned short Neighbor_Nodes[8][3] = {{1,3,4},{0,2,5},{1,3,6},{0,2,7},{0,5,7},{4,6,1},{2,5,7},{4,3,6}}; + static constexpr unsigned short nNodesFace[6] = {4, 4, 4, 4, 4, 4}; + static constexpr unsigned short Faces[6][4] = {{0, 1, 5, 4}, {1, 2, 6, 5}, {2, 3, 7, 6}, + {3, 0, 4, 7}, {0, 3, 2, 1}, {4, 5, 6, 7}}; + static constexpr unsigned short nNeighbor_Nodes[8] = {3, 3, 3, 3, 3, 3, 3, 3}; + static constexpr unsigned short Neighbor_Nodes[8][3] = {{1, 3, 4}, {0, 2, 5}, {1, 3, 6}, {0, 2, 7}, + {0, 5, 7}, {4, 6, 1}, {2, 5, 7}, {4, 3, 6}}; }; /*! @@ -51,7 +53,7 @@ struct CHexahedronConnectivity { * \author F. Palacios */ class CHexahedron : public CPrimalGridWithConnectivity { -public: + public: /*! * \brief Constructor using the nodes and index. * \param[in] val_point_0 - Index of the 1st point read from the grid file. @@ -63,9 +65,8 @@ class CHexahedron : public CPrimalGridWithConnectivity * \param[in] val_point_6 - Index of the 7th point read from the grid file. * \param[in] val_point_7 - Index of the 8th point read from the grid file. */ - CHexahedron(unsigned long val_point_0, unsigned long val_point_1, - unsigned long val_point_2, unsigned long val_point_3, - unsigned long val_point_4, unsigned long val_point_5, + CHexahedron(unsigned long val_point_0, unsigned long val_point_1, unsigned long val_point_2, + unsigned long val_point_3, unsigned long val_point_4, unsigned long val_point_5, unsigned long val_point_6, unsigned long val_point_7); /*! diff --git a/Common/include/geometry/primal_grid/CLine.hpp b/Common/include/geometry/primal_grid/CLine.hpp index 26c786e534b..49281694bc1 100644 --- a/Common/include/geometry/primal_grid/CLine.hpp +++ b/Common/include/geometry/primal_grid/CLine.hpp @@ -39,10 +39,10 @@ struct CLineConnectivity { enum { nFaces = N_FACES_LINE }; enum { maxNodesFace = N_POINTS_LINE }; enum { VTK_Type = LINE }; - static constexpr unsigned short nNodesFace[1]={2}; - static constexpr unsigned short Faces[1][2]={{0,1}}; - static constexpr unsigned short nNeighbor_Nodes[2]={1,1}; - static constexpr unsigned short Neighbor_Nodes[2][1]={{1},{0}}; + static constexpr unsigned short nNodesFace[1] = {2}; + static constexpr unsigned short Faces[1][2] = {{0, 1}}; + static constexpr unsigned short nNeighbor_Nodes[2] = {1, 1}; + static constexpr unsigned short Neighbor_Nodes[2][1] = {{1}, {0}}; }; /*! @@ -51,7 +51,7 @@ struct CLineConnectivity { * \author F. Palacios */ class CLine final : public CPrimalGridWithConnectivity { -public: + public: /*! * \brief Constructor using the nodes and index. * \param[in] val_point_0 - Index of the 1st triangle point read from the grid file. @@ -62,7 +62,5 @@ class CLine final : public CPrimalGridWithConnectivity { /*! * \brief Change the orientation of an element. */ - inline void Change_Orientation() override { - std::swap(Nodes[0], Nodes[1]); - } + inline void Change_Orientation() override { std::swap(Nodes[0], Nodes[1]); } }; diff --git a/Common/include/geometry/primal_grid/CPrimalGrid.hpp b/Common/include/geometry/primal_grid/CPrimalGrid.hpp index 33f10270bf6..5b5e2cdf9d3 100644 --- a/Common/include/geometry/primal_grid/CPrimalGrid.hpp +++ b/Common/include/geometry/primal_grid/CPrimalGrid.hpp @@ -43,29 +43,30 @@ * \author F. Palacios, T. Economon, M. Aehle. */ class CPrimalGrid { -protected: + protected: /* If this is a domain element, stores the global index. * If this is a boundary element, stores the index of the adjacent domain element. */ unsigned long GlobalIndex_DomainElement; - std::unique_ptr Nodes; /*!< \brief Global node indices of the element. */ - std::unique_ptr Neighbor_Elements; /*!< \brief Vector to store the elements surronding this element. */ + std::unique_ptr Nodes; /*!< \brief Global node indices of the element. */ + std::unique_ptr Neighbor_Elements; /*!< \brief Vector to store the elements surronding this element. */ - su2double Coord_CG[3] = {0.0}; /*!< \brief Coordinates of the center-of-gravity of the element. */ - su2double Volume; /*!< \brief Volume of the element. */ - su2double LenScale; /*!< \brief Length scale of the element. */ + su2double Coord_CG[3] = {0.0}; /*!< \brief Coordinates of the center-of-gravity of the element. */ + su2double Volume; /*!< \brief Volume of the element. */ + su2double LenScale; /*!< \brief Length scale of the element. */ unsigned short TimeLevel; /*!< \brief Time level of the element for time accurate local time stepping. */ - /*!< \brief Vector to store the periodic index of a neighbor, -1 indicates no periodic transformation to the neighbor. */ + /*!< \brief Vector to store the periodic index of a neighbor, -1 indicates no periodic transformation to the neighbor. + */ int8_t PeriodIndexNeighbors[N_FACES_MAXIMUM]; /*! \brief Whether or not the Jacobian of the faces can be considered * constant in the transformation to the standard element. */ bool JacobianFaceIsConstant[N_FACES_MAXIMUM]; - bool ElementOwnsFace[N_FACES_MAXIMUM]; /*!< \brief Whether or not the element owns each face. */ - const bool FEM; /*!< \brief Whether this is a FEM element. */ + bool ElementOwnsFace[N_FACES_MAXIMUM]; /*!< \brief Whether or not the element owns each face. */ + const bool FEM; /*!< \brief Whether this is a FEM element. */ -public: + public: CPrimalGrid() = delete; /*! @@ -110,7 +111,9 @@ class CPrimalGrid { * \param[in] val_elem - Global index of the element. * \param[in] val_face - Local index of the face. */ - inline void SetNeighbor_Elements(unsigned long val_elem, unsigned short val_face) { Neighbor_Elements[val_face] = val_elem; } + inline void SetNeighbor_Elements(unsigned long val_elem, unsigned short val_face) { + Neighbor_Elements[val_face] = val_elem; + } /*! * \brief Make available the length scale of the element. @@ -190,12 +193,12 @@ class CPrimalGrid { * \param[in] nDim - Number of dimensions (2 or 3). * \param[in] val_coord - Coordinates of the element. */ - template + template inline su2double* SetCoord_CG(unsigned short nDim, const T& val_coord) { for (unsigned short iDim = 0; iDim < nDim; iDim++) { Coord_CG[iDim] = 0.0; for (unsigned short iNode = 0; iNode < GetnNodes(); iNode++) - Coord_CG[iDim] += val_coord[iNode][iDim]/su2double(GetnNodes()); + Coord_CG[iDim] += val_coord[iNode][iDim] / su2double(GetnNodes()); } return Coord_CG; } @@ -238,7 +241,7 @@ class CPrimalGrid { * \brief A virtual member. * \param[in] val_color - New color of the element. */ - inline virtual void SetColor(unsigned long val_color) { } + inline virtual void SetColor(unsigned long val_color) {} /*! * \brief A virtual member. @@ -267,7 +270,7 @@ class CPrimalGrid { /*! * \brief Get the index of the domain element of which this boundary element is a face. */ - inline unsigned long GetDomainElement() const{ return GlobalIndex_DomainElement; } + inline unsigned long GetDomainElement() const { return GlobalIndex_DomainElement; } /*! * \brief A pure virtual member. @@ -278,13 +281,13 @@ class CPrimalGrid { * \brief A pure virtual member. * \return Type of the element using VTK nomenclature. */ - inline virtual unsigned short GetRotation_Type() const{ return 0; } + inline virtual unsigned short GetRotation_Type() const { return 0; } /*! * \brief A pure virtual member. * \param[in] val_rotation_type - Kind of rotation/traslation that must be applied. */ - inline virtual void SetRotation_Type(unsigned short val_rotation_type) { } + inline virtual void SetRotation_Type(unsigned short val_rotation_type) {} /*-- The following pure virtual functions are overridden in * CPrimalGridWithConnectivity, except for the FEM classes. --*/ @@ -351,9 +354,8 @@ class CPrimalGrid { * \param[out] nPointsPerFace - Number of corner points for each of the faces. * \param[out] faceConn - Global IDs of the corner points of the faces. */ - inline virtual void GetCornerPointsAllFaces(unsigned short &nFaces, - unsigned short nPointsPerFace[], - unsigned long faceConn[6][4]) const { } + inline virtual void GetCornerPointsAllFaces(unsigned short& nFaces, unsigned short nPointsPerFace[], + unsigned long faceConn[6][4]) const {} /*! * \brief Virtual function to make available the global ID of this element. @@ -377,7 +379,7 @@ class CPrimalGrid { * \brief Virtual function to make available the polynomial degree of the solution. * \return The polynomial degree of the solution. */ - inline virtual unsigned short GetNPolySol() const{ return 0; } + inline virtual unsigned short GetNPolySol() const { return 0; } /*! * \brief Virtual function to make available the number of DOFs of the grid in the element. @@ -419,21 +421,21 @@ class CPrimalGrid { * \brief Virtual function to make available the number of donor elements for the wall function treatment. * \return The number of donor elements. */ - inline virtual unsigned short GetNDonorsWallFunctions() const {return 0;} + inline virtual unsigned short GetNDonorsWallFunctions() const { return 0; } /*! * \brief Virtual function to make available the pointer to the vector for the donor elements for the wall function treatment. * \return The pointer to the data of donorElementsWallFunctions. */ - inline virtual unsigned long *GetDonorsWallFunctions() {return nullptr;} - inline virtual const unsigned long *GetDonorsWallFunctions() const {return nullptr;} + inline virtual unsigned long* GetDonorsWallFunctions() { return nullptr; } + inline virtual const unsigned long* GetDonorsWallFunctions() const { return nullptr; } /*! * \brief Virtual function to set the global ID's of the donor elements for the wall function treatment. * \param[in] donorElements - Vector, which contain the donor elements. */ - inline virtual void SetDonorsWallFunctions(const std::vector &donorElements) {} + inline virtual void SetDonorsWallFunctions(const std::vector& donorElements) {} /*! * \brief Virtual function to remove the multiple donors for the wall function treatment. @@ -462,28 +464,21 @@ class CPrimalGrid { * * \tparam Connectivity - class defining the connectivity structure */ -template +template class CPrimalGridWithConnectivity : public CPrimalGrid { -public: - + public: CPrimalGridWithConnectivity(bool FEM) : CPrimalGrid(FEM, Connectivity::nNodes, Connectivity::nFaces) {} - inline unsigned short GetnNodes() const final { - return Connectivity::nNodes; - } + inline unsigned short GetnNodes() const final { return Connectivity::nNodes; } - inline unsigned short GetnFaces() const final { - return Connectivity::nFaces; - } + inline unsigned short GetnFaces() const final { return Connectivity::nFaces; } inline unsigned short GetnNodesFace(unsigned short val_face) const final { assert(val_face < Connectivity::nFaces); return Connectivity::nNodesFace[val_face]; } - inline unsigned short GetMaxNodesFace() const final { - return Connectivity::maxNodesFace; - } + inline unsigned short GetMaxNodesFace() const final { return Connectivity::maxNodesFace; } inline unsigned short GetFaces(unsigned short val_face, unsigned short val_index) const final { assert(val_face < GetnFaces() && val_index < GetnNodesFace(val_face)); @@ -500,9 +495,5 @@ class CPrimalGridWithConnectivity : public CPrimalGrid { return Connectivity::Neighbor_Nodes[val_node][val_index]; } - inline unsigned short GetVTK_Type() const final { - return Connectivity::VTK_Type; - } - + inline unsigned short GetVTK_Type() const final { return Connectivity::VTK_Type; } }; - diff --git a/Common/include/geometry/primal_grid/CPrimalGridBoundFEM.hpp b/Common/include/geometry/primal_grid/CPrimalGridBoundFEM.hpp index 2356c8a442c..e6dcf964fe9 100644 --- a/Common/include/geometry/primal_grid/CPrimalGridBoundFEM.hpp +++ b/Common/include/geometry/primal_grid/CPrimalGridBoundFEM.hpp @@ -35,20 +35,20 @@ * \brief Class to define primal grid boundary element for the FEM solver. * \version 7.5.1 "Blackbird" */ -class CPrimalGridBoundFEM final: public CPrimalGrid { -private: - unsigned long boundElemIDGlobal; /*!< \brief Global boundary element ID of this element. */ +class CPrimalGridBoundFEM final : public CPrimalGrid { + private: + unsigned long boundElemIDGlobal; /*!< \brief Global boundary element ID of this element. */ std::vector donorElementsWallFunctions; /*!< \brief The global ID's of the donor elements for the wall function treatment. */ - unsigned short VTK_Type; /*!< \brief Element type using the VTK convention. */ - unsigned short nPolyGrid; /*!< \brief Polynomial degree for the geometry of the element. */ - unsigned short nDOFsGrid; /*!< \brief Number of DOFs for the geometry of the element. */ + unsigned short VTK_Type; /*!< \brief Element type using the VTK convention. */ + unsigned short nPolyGrid; /*!< \brief Polynomial degree for the geometry of the element. */ + unsigned short nDOFsGrid; /*!< \brief Number of DOFs for the geometry of the element. */ - bool JacobianConsideredConstant; /*!< \brief Whether or not the Jacobian of the transformation to - is (almost) constant. */ -public: + bool JacobianConsideredConstant; /*!< \brief Whether or not the Jacobian of the transformation to + is (almost) constant. */ + public: /*! * \brief Constructor using data to initialize the boundary element. * \param[in] val_elemGlobalID - Global boundary element ID of this element. @@ -58,19 +58,18 @@ class CPrimalGridBoundFEM final: public CPrimalGrid { * \param[in] val_nDOFsGrid - Number of DOFs used to describe the geometry of the element. * \param[in] val_nodes - Vector, which contains the global node IDs of the element. */ - CPrimalGridBoundFEM(unsigned long val_elemGlobalID, - unsigned long val_domainElementID, - unsigned short val_VTK_Type, - unsigned short val_nPolyGrid, - unsigned short val_nDOFsGrid, - std::vector &val_nodes); + CPrimalGridBoundFEM(unsigned long val_elemGlobalID, unsigned long val_domainElementID, unsigned short val_VTK_Type, + unsigned short val_nPolyGrid, unsigned short val_nDOFsGrid, + std::vector& val_nodes); /*! * \brief Get the number of nodes that composes a face of an element. * \param[in] val_face - Local index of the face. * \return Number of nodes that composes a face of an element. */ - inline unsigned short GetnNodesFace(unsigned short val_face) const override { return std::numeric_limits::max(); } + inline unsigned short GetnNodesFace(unsigned short val_face) const override { + return std::numeric_limits::max(); + } /*! * \brief Get the face index of an element. @@ -78,7 +77,9 @@ class CPrimalGridBoundFEM final: public CPrimalGrid { * \param[in] val_index - Local (to the face) index of the nodes that compose the face. * \return Local (to the element) index of the nodes that compose the face. */ - inline unsigned short GetFaces(unsigned short val_face, unsigned short val_index) const override { return std::numeric_limits::max(); } + inline unsigned short GetFaces(unsigned short val_face, unsigned short val_index) const override { + return std::numeric_limits::max(); + } /*! * \brief Get the local index of the neighbors to a node (given the local index). @@ -86,7 +87,9 @@ class CPrimalGridBoundFEM final: public CPrimalGrid { * \param[in] val_index - Local (to the neighbor nodes of val_node) index of the nodes that are neighbor to val_node. * \return Local (to the element) index of the nodes that are neighbor to val_node. */ - inline unsigned short GetNeighbor_Nodes(unsigned short val_node, unsigned short val_index) const override { return std::numeric_limits::max(); } + inline unsigned short GetNeighbor_Nodes(unsigned short val_node, unsigned short val_index) const override { + return std::numeric_limits::max(); + } /*! * \brief Get the number of nodes of an element. @@ -105,7 +108,9 @@ class CPrimalGridBoundFEM final: public CPrimalGrid { * \param[in] val_node - Local (to the element) index of a node. * \return Number if neighbors of a node val_node. */ - inline unsigned short GetnNeighbor_Nodes(unsigned short val_node) const override { return std::numeric_limits::max(); } + inline unsigned short GetnNeighbor_Nodes(unsigned short val_node) const override { + return std::numeric_limits::max(); + } /*! * \brief Change the orientation of an element. @@ -142,9 +147,8 @@ class CPrimalGridBoundFEM final: public CPrimalGrid { * \param[out] nPointsPerFace - Number of corner points for each of the faces. * \param[out] faceConn - Global IDs of the corner points of the faces. */ - void GetCornerPointsAllFaces(unsigned short &nFaces, - unsigned short nPointsPerFace[], - unsigned long faceConn[6][4]) const override; + void GetCornerPointsAllFaces(unsigned short& nFaces, unsigned short nPointsPerFace[], + unsigned long faceConn[6][4]) const override; /*! * \brief Static member function to get the local the corner points of all the face @@ -155,11 +159,8 @@ class CPrimalGridBoundFEM final: public CPrimalGrid { * \param[out] nPointsPerFace - Number of corner points of the face. * \param[out] faceConn - Global IDs of the corner points of the face. */ - static void GetLocalCornerPointsFace(unsigned short elementType, - unsigned short nPoly, - unsigned short nDOFs, - unsigned short &nPointsPerFace, - unsigned long faceConn[]); + static void GetLocalCornerPointsFace(unsigned short elementType, unsigned short nPoly, unsigned short nDOFs, + unsigned short& nPointsPerFace, unsigned long faceConn[]); /*! * \brief Make available the global ID of this element. @@ -171,39 +172,45 @@ class CPrimalGridBoundFEM final: public CPrimalGrid { * \brief Function to get whether or not the Jacobian is considered constant. * \return True if the Jacobian is (almost) constant and false otherwise. */ - inline bool GetJacobianConsideredConstant(void) const override {return JacobianConsideredConstant;} + inline bool GetJacobianConsideredConstant(void) const override { return JacobianConsideredConstant; } /*! * \brief Function to set the value of JacobianConsideredConstant. * \param[in] val_JacobianConsideredConstant - The value to be set for JacobianConsideredConstant. */ - inline void SetJacobianConsideredConstant(bool val_JacobianConsideredConstant) override {JacobianConsideredConstant = val_JacobianConsideredConstant;} + inline void SetJacobianConsideredConstant(bool val_JacobianConsideredConstant) override { + JacobianConsideredConstant = val_JacobianConsideredConstant; + } /*! * \brief Add the given donor ID to the donor elements for the wall function treatment. * \param[in] donorElement - Element to be added to donor elements. */ - inline void AddDonorWallFunctions(const unsigned long donorElement) override {donorElementsWallFunctions.push_back(donorElement);} + inline void AddDonorWallFunctions(const unsigned long donorElement) override { + donorElementsWallFunctions.push_back(donorElement); + } /*! * \brief Make available the number of donor elements for the wall function treatment. * \return The number of donor elements. */ - inline unsigned short GetNDonorsWallFunctions(void) const override {return donorElementsWallFunctions.size();} + inline unsigned short GetNDonorsWallFunctions(void) const override { return donorElementsWallFunctions.size(); } /*! * \brief Make available the pointer to the vector for the donor elements for the wall function treatment. * \return The pointer to the data of donorElementsWallFunctions. */ - inline unsigned long *GetDonorsWallFunctions(void) override {return donorElementsWallFunctions.data();} - inline const unsigned long *GetDonorsWallFunctions(void) const override {return donorElementsWallFunctions.data();} + inline unsigned long* GetDonorsWallFunctions(void) override { return donorElementsWallFunctions.data(); } + inline const unsigned long* GetDonorsWallFunctions(void) const override { return donorElementsWallFunctions.data(); } /*! * \brief Set the global ID's of the donor elements for the wall function treatment. * \param[in] donorElements - Vector, which contain the donor elements. */ - inline void SetDonorsWallFunctions(const std::vector &donorElements) override {donorElementsWallFunctions = donorElements;} + inline void SetDonorsWallFunctions(const std::vector& donorElements) override { + donorElementsWallFunctions = donorElements; + } /*! * \brief Function to remove the multiple donors for the wall function treatment. diff --git a/Common/include/geometry/primal_grid/CPrimalGridFEM.hpp b/Common/include/geometry/primal_grid/CPrimalGridFEM.hpp index 622e7915069..8a12511c2fc 100644 --- a/Common/include/geometry/primal_grid/CPrimalGridFEM.hpp +++ b/Common/include/geometry/primal_grid/CPrimalGridFEM.hpp @@ -36,23 +36,23 @@ * \brief Class to define primal grid element for the FEM solver. * \version 7.5.1 "Blackbird" */ -class CPrimalGridFEM final: public CPrimalGrid { -private: +class CPrimalGridFEM final : public CPrimalGrid { + private: unsigned long elemIDGlobal; /*!< \brief Global element ID of this element. */ unsigned long offsetDOFsSolGlobal; /*!< \brief Global offset of the solution DOFs of this element. */ unsigned long color; /*!< \brief Color of the element in the partitioning strategy. */ - unsigned short VTK_Type; /*!< \brief Element type using the VTK convention. */ - unsigned short nPolyGrid; /*!< \brief Polynomial degree for the geometry of the element. */ - unsigned short nPolySol; /*!< \brief Polynomial degree for the solution of the element. */ - unsigned short nDOFsGrid; /*!< \brief Number of DOFs for the geometry of the element. */ - unsigned short nDOFsSol; /*!< \brief Number of DOFs for the solution of the element. */ - unsigned short nFaces; /*!< \brief Number of faces of the element. */ + unsigned short VTK_Type; /*!< \brief Element type using the VTK convention. */ + unsigned short nPolyGrid; /*!< \brief Polynomial degree for the geometry of the element. */ + unsigned short nPolySol; /*!< \brief Polynomial degree for the solution of the element. */ + unsigned short nDOFsGrid; /*!< \brief Number of DOFs for the geometry of the element. */ + unsigned short nDOFsSol; /*!< \brief Number of DOFs for the solution of the element. */ + unsigned short nFaces; /*!< \brief Number of faces of the element. */ - bool JacobianConsideredConstant; /*!< \brief Whether or not the Jacobian of the transformation to - is (almost) constant. */ + bool JacobianConsideredConstant; /*!< \brief Whether or not the Jacobian of the transformation to + is (almost) constant. */ -public: + public: /*! * \brief Constructor using data to initialize the element. * \param[in] val_elemGlobalID - Global element ID of this element. @@ -64,10 +64,9 @@ class CPrimalGridFEM final: public CPrimalGrid { * \param[in] val_offDOfsSol - Global offset of the solution DOFs of the element. * \param[in] elem_line - istringstream, which contains the grid node numbers of the element. */ - CPrimalGridFEM(unsigned long val_elemGlobalID, unsigned short val_VTK_Type, - unsigned short val_nPolyGrid, unsigned short val_nPolySol, - unsigned short val_nDOFsGrid, unsigned short val_nDOFsSol, - unsigned long val_offDOfsSol, std::istringstream &elem_line); + CPrimalGridFEM(unsigned long val_elemGlobalID, unsigned short val_VTK_Type, unsigned short val_nPolyGrid, + unsigned short val_nPolySol, unsigned short val_nDOFsGrid, unsigned short val_nDOFsSol, + unsigned long val_offDOfsSol, std::istringstream& elem_line); /*! * \brief Constructor using data to initialize the element. @@ -80,17 +79,18 @@ class CPrimalGridFEM final: public CPrimalGrid { * \param[in] val_offDOfsSol - Global offset of the solution DOFs of the element. * \param[in] connGrid - Array, which contains the grid node numbers of the element. */ - CPrimalGridFEM(unsigned long val_elemGlobalID, unsigned short val_VTK_Type, - unsigned short val_nPolyGrid, unsigned short val_nPolySol, - unsigned short val_nDOFsGrid, unsigned short val_nDOFsSol, - unsigned long val_offDOfsSol, const unsigned long *connGrid); + CPrimalGridFEM(unsigned long val_elemGlobalID, unsigned short val_VTK_Type, unsigned short val_nPolyGrid, + unsigned short val_nPolySol, unsigned short val_nDOFsGrid, unsigned short val_nDOFsSol, + unsigned long val_offDOfsSol, const unsigned long* connGrid); /*! * \brief Get the number of nodes that composes a face of an element. * \param[in] val_face - Local index of the face. * \return Number of nodes that composes a face of an element. */ - inline unsigned short GetnNodesFace(unsigned short val_face) const override { return std::numeric_limits::max(); } + inline unsigned short GetnNodesFace(unsigned short val_face) const override { + return std::numeric_limits::max(); + } /*! * \brief Get the face index of an element. @@ -98,7 +98,9 @@ class CPrimalGridFEM final: public CPrimalGrid { * \param[in] val_index - Local (to the face) index of the nodes that compose the face. * \return Local (to the element) index of the nodes that compose the face. */ - inline unsigned short GetFaces(unsigned short val_face, unsigned short val_index) const override { return std::numeric_limits::max(); } + inline unsigned short GetFaces(unsigned short val_face, unsigned short val_index) const override { + return std::numeric_limits::max(); + } /*! * \brief Get the local index of the neighbors to a node (given the local index). @@ -106,7 +108,9 @@ class CPrimalGridFEM final: public CPrimalGrid { * \param[in] val_index - Local (to the neighbor nodes of val_node) index of the nodes that are neighbor to val_node. * \return Local (to the element) index of the nodes that are neighbor to val_node. */ - inline unsigned short GetNeighbor_Nodes(unsigned short val_node, unsigned short val_index) const override { return std::numeric_limits::max(); } + inline unsigned short GetNeighbor_Nodes(unsigned short val_node, unsigned short val_index) const override { + return std::numeric_limits::max(); + } /*! * \brief Get the number of nodes of an element. @@ -125,7 +129,9 @@ class CPrimalGridFEM final: public CPrimalGrid { * \param[in] val_node - Local (to the element) index of a node. * \return Number if neighbors of a node val_node. */ - inline unsigned short GetnNeighbor_Nodes(unsigned short val_node) const override { return std::numeric_limits::max(); } + inline unsigned short GetnNeighbor_Nodes(unsigned short val_node) const override { + return std::numeric_limits::max(); + } /*! * \brief Change the orientation of an element. @@ -188,9 +194,8 @@ class CPrimalGridFEM final: public CPrimalGrid { * \param[out] nPointsPerFace - Number of corner points for each of the faces. * \param[out] faceConn - Global IDs of the corner points of the faces. */ - void GetCornerPointsAllFaces(unsigned short &numFaces, - unsigned short nPointsPerFace[], - unsigned long faceConn[6][4]) const override; + void GetCornerPointsAllFaces(unsigned short& numFaces, unsigned short nPointsPerFace[], + unsigned long faceConn[6][4]) const override; /*! * \brief Static member function to get the local the corner points of all the faces @@ -203,12 +208,9 @@ class CPrimalGridFEM final: public CPrimalGrid { * \param[out] nPointsPerFace - Number of corner points for each of the faces. * \param[out] faceConn - Global IDs of the corner points of the faces. */ - static void GetLocalCornerPointsAllFaces(unsigned short elementType, - unsigned short nPoly, - unsigned short nDOFs, - unsigned short &numFaces, - unsigned short nPointsPerFace[], - unsigned long faceConn[6][4]); + static void GetLocalCornerPointsAllFaces(unsigned short elementType, unsigned short nPoly, unsigned short nDOFs, + unsigned short& numFaces, unsigned short nPointsPerFace[], + unsigned long faceConn[6][4]); /*! * \brief Function to get whether or not the Jacobian is considered constant. * \return True if the Jacobian is (almost) constant and false otherwise. @@ -231,11 +233,15 @@ class CPrimalGridFEM final: public CPrimalGrid { * \brief Function to set the value of JacobianConsideredConstant. * \param[in] val_JacobianConsideredConstant - The value to be set for JacobianConsideredConstant. */ - inline void SetJacobianConsideredConstant(bool val_JacobianConsideredConstant) override {JacobianConsideredConstant = val_JacobianConsideredConstant;} + inline void SetJacobianConsideredConstant(bool val_JacobianConsideredConstant) override { + JacobianConsideredConstant = val_JacobianConsideredConstant; + } /*! * \brief Function to correct the offset of the global DOFs. * \param[in] val_offsetRank - The offset that must be added for this rank. */ - inline void AddOffsetGlobalDOFs(const unsigned long val_offsetRank) override {offsetDOFsSolGlobal += val_offsetRank;} + inline void AddOffsetGlobalDOFs(const unsigned long val_offsetRank) override { + offsetDOFsSolGlobal += val_offsetRank; + } }; diff --git a/Common/include/geometry/primal_grid/CPrism.hpp b/Common/include/geometry/primal_grid/CPrism.hpp index 1631aee0067..75322f6005c 100644 --- a/Common/include/geometry/primal_grid/CPrism.hpp +++ b/Common/include/geometry/primal_grid/CPrism.hpp @@ -39,10 +39,11 @@ struct CPrismConnectivity { enum { nFaces = N_FACES_PRISM }; enum { maxNodesFace = N_POINTS_QUADRILATERAL }; enum { VTK_Type = PRISM }; - static constexpr unsigned short nNodesFace[5] = {4,4,4,3,3}; - static constexpr unsigned short Faces[5][4] = {{3,4,1,0},{5,2,1,4},{2,5,3,0},{0,1,2,2},{5,4,3,3}}; - static constexpr unsigned short nNeighbor_Nodes[6] = {3,3,3,3,3,3}; - static constexpr unsigned short Neighbor_Nodes[6][3] = {{1,2,3},{0,2,4},{1,0,5},{0,4,5},{3,5,1},{4,3,2}}; + static constexpr unsigned short nNodesFace[5] = {4, 4, 4, 3, 3}; + static constexpr unsigned short Faces[5][4] = {{3, 4, 1, 0}, {5, 2, 1, 4}, {2, 5, 3, 0}, {0, 1, 2, 2}, {5, 4, 3, 3}}; + static constexpr unsigned short nNeighbor_Nodes[6] = {3, 3, 3, 3, 3, 3}; + static constexpr unsigned short Neighbor_Nodes[6][3] = {{1, 2, 3}, {0, 2, 4}, {1, 0, 5}, + {0, 4, 5}, {3, 5, 1}, {4, 3, 2}}; }; /*! @@ -50,8 +51,8 @@ struct CPrismConnectivity { * \brief Class for prism element definition. * \author F. Palacios */ -class CPrism final: public CPrimalGridWithConnectivity { -public: +class CPrism final : public CPrimalGridWithConnectivity { + public: /*! * \brief Constructor using the nodes and index. * \param[in] val_point_0 - Index of the 1st point read from the grid file. @@ -61,8 +62,7 @@ class CPrism final: public CPrimalGridWithConnectivity { * \param[in] val_point_4 - Index of the 5th point read from the grid file. * \param[in] val_point_5 - Index of the 6th point read from the grid file. */ - CPrism(unsigned long val_point_0, unsigned long val_point_1, - unsigned long val_point_2, unsigned long val_point_3, + CPrism(unsigned long val_point_0, unsigned long val_point_1, unsigned long val_point_2, unsigned long val_point_3, unsigned long val_point_4, unsigned long val_point_5); /*! diff --git a/Common/include/geometry/primal_grid/CPyramid.hpp b/Common/include/geometry/primal_grid/CPyramid.hpp index 64722e8dc3b..d3da90aa269 100644 --- a/Common/include/geometry/primal_grid/CPyramid.hpp +++ b/Common/include/geometry/primal_grid/CPyramid.hpp @@ -39,10 +39,11 @@ struct CPyramidConnectivity { enum { nFaces = N_FACES_PYRAMID }; enum { maxNodesFace = N_POINTS_QUADRILATERAL }; enum { VTK_Type = PYRAMID }; - static constexpr unsigned short nNodesFace[5] = {4,3,3,3,3}; - static constexpr unsigned short Faces[5][4] = {{0,3,2,1},{4,3,0,0},{4,0,1,1},{2,4,1,1},{3,4,2,2}}; - static constexpr unsigned short nNeighbor_Nodes[5] = {3,3,3,3,4}; - static constexpr unsigned short Neighbor_Nodes[5][4] = {{1,3,4,4},{0,2,4,4},{1,3,4,4},{2,0,4,4},{0,1,2,3}}; + static constexpr unsigned short nNodesFace[5] = {4, 3, 3, 3, 3}; + static constexpr unsigned short Faces[5][4] = {{0, 3, 2, 1}, {4, 3, 0, 0}, {4, 0, 1, 1}, {2, 4, 1, 1}, {3, 4, 2, 2}}; + static constexpr unsigned short nNeighbor_Nodes[5] = {3, 3, 3, 3, 4}; + static constexpr unsigned short Neighbor_Nodes[5][4] = { + {1, 3, 4, 4}, {0, 2, 4, 4}, {1, 3, 4, 4}, {2, 0, 4, 4}, {0, 1, 2, 3}}; }; /*! @@ -50,22 +51,21 @@ struct CPyramidConnectivity { * \brief Class for pyramid element definition. * \author F. Palacios */ -class CPyramid final: public CPrimalGridWithConnectivity { -public: - /*! - * \brief Constructor using the nodes and index. - * \param[in] val_point_0 - Index of the 1st point read from the grid file. - * \param[in] val_point_1 - Index of the 2nd point read from the grid file. - * \param[in] val_point_2 - Index of the 3th point read from the grid file. - * \param[in] val_point_3 - Index of the 4th point read from the grid file. - * \param[in] val_point_4 - Index of the 5th point read from the grid file. - */ - CPyramid(unsigned long val_point_0, unsigned long val_point_1, - unsigned long val_point_2, unsigned long val_point_3, - unsigned long val_point_4); +class CPyramid final : public CPrimalGridWithConnectivity { + public: + /*! + * \brief Constructor using the nodes and index. + * \param[in] val_point_0 - Index of the 1st point read from the grid file. + * \param[in] val_point_1 - Index of the 2nd point read from the grid file. + * \param[in] val_point_2 - Index of the 3th point read from the grid file. + * \param[in] val_point_3 - Index of the 4th point read from the grid file. + * \param[in] val_point_4 - Index of the 5th point read from the grid file. + */ + CPyramid(unsigned long val_point_0, unsigned long val_point_1, unsigned long val_point_2, unsigned long val_point_3, + unsigned long val_point_4); - /*! - * \brief Change the orientation of an element. - */ - void Change_Orientation() override; + /*! + * \brief Change the orientation of an element. + */ + void Change_Orientation() override; }; diff --git a/Common/include/geometry/primal_grid/CQuadrilateral.hpp b/Common/include/geometry/primal_grid/CQuadrilateral.hpp index f87ff807ed8..8d96240e3d3 100644 --- a/Common/include/geometry/primal_grid/CQuadrilateral.hpp +++ b/Common/include/geometry/primal_grid/CQuadrilateral.hpp @@ -39,10 +39,10 @@ struct CQuadrilateralConnectivity { enum { nFaces = N_FACES_QUADRILATERAL }; enum { maxNodesFace = N_POINTS_LINE }; enum { VTK_Type = QUADRILATERAL }; - static constexpr unsigned short nNodesFace[4] = {2,2,2,2}; - static constexpr unsigned short Faces[4][2] = {{0,1},{1,2},{2,3},{3,0}}; - static constexpr unsigned short nNeighbor_Nodes[4] = {2,2,2,2}; - static constexpr unsigned short Neighbor_Nodes[4][2] = {{1,3},{2,0},{3,1},{0,2}}; + static constexpr unsigned short nNodesFace[4] = {2, 2, 2, 2}; + static constexpr unsigned short Faces[4][2] = {{0, 1}, {1, 2}, {2, 3}, {3, 0}}; + static constexpr unsigned short nNeighbor_Nodes[4] = {2, 2, 2, 2}; + static constexpr unsigned short Neighbor_Nodes[4][2] = {{1, 3}, {2, 0}, {3, 1}, {0, 2}}; }; /*! @@ -50,8 +50,8 @@ struct CQuadrilateralConnectivity { * \brief Class for quadrilateral element definition. * \author F. Palacios */ -class CQuadrilateral final: public CPrimalGridWithConnectivity { -public: +class CQuadrilateral final : public CPrimalGridWithConnectivity { + public: /*! * \brief Constructor using the nodes and index. * \param[in] val_point_0 - Index of the 1st point read from the grid file. @@ -59,8 +59,8 @@ class CQuadrilateral final: public CPrimalGridWithConnectivity { -public: +class CTetrahedron final : public CPrimalGridWithConnectivity { + public: /*! * \brief Constructor using the nodes and index. * \param[in] val_point_0 - Index of the 1st point read from the grid file. @@ -59,8 +59,8 @@ class CTetrahedron final: public CPrimalGridWithConnectivity { -public: +class CTriangle final : public CPrimalGridWithConnectivity { + public: /*! * \brief Constructor using the nodes and index. * \param[in] val_point_0 - Index of the 1st triangle point read from the grid file. * \param[in] val_point_1 - Index of the 2nd triangle point read from the grid file. * \param[in] val_point_2 - Index of the 3th triangle point read from the grid file. */ - CTriangle(unsigned long val_point_0, unsigned long val_point_1, - unsigned long val_point_2); + CTriangle(unsigned long val_point_0, unsigned long val_point_1, unsigned long val_point_2); /*! * \brief Change the orientation of an element. */ - inline void Change_Orientation() override { - std::swap(Nodes[0], Nodes[2]); - } + inline void Change_Orientation() override { std::swap(Nodes[0], Nodes[2]); } }; diff --git a/Common/include/geometry/primal_grid/CVertexMPI.hpp b/Common/include/geometry/primal_grid/CVertexMPI.hpp index 4d3c1fc3df2..04d55760940 100644 --- a/Common/include/geometry/primal_grid/CVertexMPI.hpp +++ b/Common/include/geometry/primal_grid/CVertexMPI.hpp @@ -52,12 +52,12 @@ struct CVertexMPIConnectivity { * of element is used in the parallelization stuff. * \author F. Palacios */ -class CVertexMPI final: public CPrimalGridWithConnectivity { -private: +class CVertexMPI final : public CPrimalGridWithConnectivity { + private: /*! \brief Definition of the rotation, translation of the solution at the vertex. */ unsigned short Rotation_Type; -public: + public: /*! * \brief Constructor using the nodes and index. * \param[in] val_point - Index of the 1st triangle point read from the grid file. diff --git a/Common/include/graph_coloring_structure.hpp b/Common/include/graph_coloring_structure.hpp index 39810948ece..1ad5103cf71 100644 --- a/Common/include/graph_coloring_structure.hpp +++ b/Common/include/graph_coloring_structure.hpp @@ -44,7 +44,7 @@ using namespace std; * \version 7.5.1 "Blackbird" */ class CGraphColoringStructure { -public: + public: /*! * \brief Function, which determines the colors for the vertices of the given graph. * \param[in] config - Definition of the particular problem. @@ -55,9 +55,7 @@ class CGraphColoringStructure { * \param[out] nGlobalColors - Global number of colors in the graph. * \param[out] colorLocalVertices - The color of the local vertices of the graph. */ - void GraphVertexColoring(CConfig *config, - const vector &nVerticesPerRank, - const vector > &entriesVertices, - int &nGlobalColors, - vector &colorLocalVertices); + void GraphVertexColoring(CConfig* config, const vector& nVerticesPerRank, + const vector >& entriesVertices, int& nGlobalColors, + vector& colorLocalVertices); }; diff --git a/Common/include/grid_movement/CBSplineBlending.hpp b/Common/include/grid_movement/CBSplineBlending.hpp index c93607f3d0c..6965d3d3965 100644 --- a/Common/include/grid_movement/CBSplineBlending.hpp +++ b/Common/include/grid_movement/CBSplineBlending.hpp @@ -38,15 +38,13 @@ using namespace std; * \brief Class that defines the blending using uniform BSplines. * \author T. Albring */ -class CBSplineBlending : public CFreeFormBlending{ - -private: - vector U; /*!< \brief The knot vector for uniform BSplines on the interval [0,1]. */ - vector > N; /*!< \brief The temporary matrix holding the j+p basis functions up to order p. */ - unsigned short KnotSize; /*!< \brief The size of the knot vector. */ - -public: +class CBSplineBlending : public CFreeFormBlending { + private: + vector U; /*!< \brief The knot vector for uniform BSplines on the interval [0,1]. */ + vector > N; /*!< \brief The temporary matrix holding the j+p basis functions up to order p. */ + unsigned short KnotSize; /*!< \brief The size of the knot vector. */ + public: /*! * \brief Constructor of the class. */ @@ -58,9 +56,9 @@ class CBSplineBlending : public CFreeFormBlending{ ~CBSplineBlending() override; /*! - * \brief Returns the value of the i-th basis function and stores the values of the i+p basis functions in the matrix N. - * \param[in] val_i - index of the basis function. - * \param[in] val_t - Point at which we want to evaluate the i-th basis. + * \brief Returns the value of the i-th basis function and stores the values of the i+p basis functions in the matrix + * N. \param[in] val_i - index of the basis function. \param[in] val_t - Point at which we want to evaluate the i-th + * basis. */ su2double GetBasis(short val_i, su2double val_t) override; @@ -78,5 +76,4 @@ class CBSplineBlending : public CFreeFormBlending{ * \param[in] n_controlpoints - the new number of control points. */ void SetOrder(short val_order, short n_controlpoints) override; - }; diff --git a/Common/include/grid_movement/CBezierBlending.hpp b/Common/include/grid_movement/CBezierBlending.hpp index 51c80d2233c..dba2d8a9749 100644 --- a/Common/include/grid_movement/CBezierBlending.hpp +++ b/Common/include/grid_movement/CBezierBlending.hpp @@ -38,10 +38,8 @@ using namespace std; * \brief Class that defines the blending using Bernsteinpolynomials (Bezier Curves). * \author F. Palacios, T. Albring */ -class CBezierBlending : public CFreeFormBlending{ - -private: - +class CBezierBlending : public CFreeFormBlending { + private: vector binomial; /*!< \brief Temporary vector for the Bernstein evaluation. */ /*! @@ -70,8 +68,7 @@ class CBezierBlending : public CFreeFormBlending{ */ su2double Binomial(unsigned short n, unsigned short m); -public: - + public: /*! * \brief Constructor of the class. * \param[in] val_order - Max. order of the basis functions. @@ -85,9 +82,9 @@ class CBezierBlending : public CFreeFormBlending{ ~CBezierBlending() override; /*! - * \brief Returns the value of the i-th basis function and stores the values of the i+p basis functions in the matrix N. - * \param[in] val_i - index of the basis function. - * \param[in] val_t - Point at which we want to evaluate the i-th basis. + * \brief Returns the value of the i-th basis function and stores the values of the i+p basis functions in the matrix + * N. \param[in] val_i - index of the basis function. \param[in] val_t - Point at which we want to evaluate the i-th + * basis. */ su2double GetBasis(short val_i, su2double val_t) override; @@ -105,5 +102,4 @@ class CBezierBlending : public CFreeFormBlending{ * \param[in] n_controlpoints - the new number of control points. */ void SetOrder(short val_order, short n_controlpoints) override; - }; diff --git a/Common/include/grid_movement/CFreeFormBlending.hpp b/Common/include/grid_movement/CFreeFormBlending.hpp index 1cda93ff33b..f8e71ae2e68 100644 --- a/Common/include/grid_movement/CFreeFormBlending.hpp +++ b/Common/include/grid_movement/CFreeFormBlending.hpp @@ -37,14 +37,12 @@ #include "../basic_types/datatype_structure.hpp" class CFreeFormBlending { - -protected: + protected: unsigned short Order, /*!< \brief Order of the polynomial basis. */ - Degree, /*!< \brief Degree (Order - 1) of the polynomial basis. */ - nControl; /*!< \brief Number of control points. */ - -public: + Degree, /*!< \brief Degree (Order - 1) of the polynomial basis. */ + nControl; /*!< \brief Number of control points. */ + public: /*! * \brief Constructor of the class. */ @@ -60,7 +58,7 @@ class CFreeFormBlending { * \param[in] val_i - index of the basis function. * \param[in] val_t - Point at which we want to evaluate the i-th basis. */ - inline virtual su2double GetBasis(short val_i, su2double val_t){return 0.0;} + inline virtual su2double GetBasis(short val_i, su2double val_t) { return 0.0; } /*! * \brief A pure virtual member. @@ -68,22 +66,22 @@ class CFreeFormBlending { * \param[in] val_t - Point at which we want to evaluate the derivative of the i-th basis. * \param[in] val_order - Order of the derivative. */ - inline virtual su2double GetDerivative(short val_i, su2double val_t, short val_order){return 0.0;} + inline virtual su2double GetDerivative(short val_i, su2double val_t, short val_order) { return 0.0; } /*! * \brief A pure virtual member. * \param[in] val_order - The new order of the function. * \param[in] n_controlpoints - the new number of control points. */ - inline virtual void SetOrder(short val_order, short n_controlpoints) { } + inline virtual void SetOrder(short val_order, short n_controlpoints) {} /*! * \brief Returns the current order of the function. */ - inline su2double GetOrder() const{return Order;} + inline su2double GetOrder() const { return Order; } /*! * \brief Returns the current degree of the function. */ - inline su2double GetDegree() const{return Degree;} + inline su2double GetDegree() const { return Degree; } }; diff --git a/Common/include/grid_movement/CFreeFormDefBox.hpp b/Common/include/grid_movement/CFreeFormDefBox.hpp index 7bb489cc911..70a1d3adcec 100644 --- a/Common/include/grid_movement/CFreeFormDefBox.hpp +++ b/Common/include/grid_movement/CFreeFormDefBox.hpp @@ -36,48 +36,46 @@ * \author F. Palacios & A. Galdran. */ class CFreeFormDefBox : public CGridMovement { -public: - unsigned short nDim; /*!< \brief Number of dimensions of the problem. */ - unsigned short nCornerPoints, /*!< \brief Number of corner points of the FFDBox. */ - nControlPoints, nControlPoints_Copy; /*!< \brief Number of control points of the FFDBox. */ - su2double **Coord_Corner_Points, /*!< \brief Coordinates of the corner points. */ - ****Coord_Control_Points, /*!< \brief Coordinates of the control points. */ - ****ParCoord_Control_Points, /*!< \brief Coordinates of the control points. */ - ****Coord_Control_Points_Copy, /*!< \brief Coordinates of the control points (copy). */ - ****Coord_SupportCP{nullptr}; /*!< \brief Coordinates of the support control points. */ - unsigned short lOrder, lOrder_Copy, /*!< \brief Order of the FFDBox in the i direction. */ - mOrder, mOrder_Copy, /*!< \brief Order of the FFDBox in the j direction. */ - nOrder, nOrder_Copy; /*!< \brief Order of the FFDBox in the k direction. */ - unsigned short lDegree, lDegree_Copy, /*!< \brief Degree of the FFDBox in the i direction. (lOrder - 1)*/ - mDegree, mDegree_Copy, /*!< \brief Degree of the FFDBox in the j direction. (mOrder - 1)*/ - nDegree, nDegree_Copy; /*!< \brief Degree of the FFDBox in the k direction. (nOrder - 1)*/ - su2double *ParamCoord, *ParamCoord_, /*!< \brief Parametric coordinates of a point. */ - *cart_coord, *cart_coord_; /*!< \brief Cartesian coordinates of a point. */ - su2double ObjFunc; /*!< \brief Objective function of the point inversion process. */ - su2double *Gradient; /*!< \brief Gradient of the point inversion process. */ - su2double **Hessian; /*!< \brief Hessian of the point inversion process. */ - su2double MaxCoord[3]; /*!< \brief Maximum coordinates of the FFDBox. */ - su2double MinCoord[3]; /*!< \brief Minimum coordinates of the FFDBox. */ - string Tag; /*!< \brief Tag to identify the FFDBox. */ - unsigned short Level; /*!< \brief Nested level of the FFD box. */ + public: + unsigned short nDim; /*!< \brief Number of dimensions of the problem. */ + unsigned short nCornerPoints, /*!< \brief Number of corner points of the FFDBox. */ + nControlPoints, nControlPoints_Copy; /*!< \brief Number of control points of the FFDBox. */ + su2double **Coord_Corner_Points, /*!< \brief Coordinates of the corner points. */ + ****Coord_Control_Points, /*!< \brief Coordinates of the control points. */ + ****ParCoord_Control_Points, /*!< \brief Coordinates of the control points. */ + ****Coord_Control_Points_Copy, /*!< \brief Coordinates of the control points (copy). */ + ****Coord_SupportCP{nullptr}; /*!< \brief Coordinates of the support control points. */ + unsigned short lOrder, lOrder_Copy, /*!< \brief Order of the FFDBox in the i direction. */ + mOrder, mOrder_Copy, /*!< \brief Order of the FFDBox in the j direction. */ + nOrder, nOrder_Copy; /*!< \brief Order of the FFDBox in the k direction. */ + unsigned short lDegree, lDegree_Copy, /*!< \brief Degree of the FFDBox in the i direction. (lOrder - 1)*/ + mDegree, mDegree_Copy, /*!< \brief Degree of the FFDBox in the j direction. (mOrder - 1)*/ + nDegree, nDegree_Copy; /*!< \brief Degree of the FFDBox in the k direction. (nOrder - 1)*/ + su2double *ParamCoord, *ParamCoord_, /*!< \brief Parametric coordinates of a point. */ + *cart_coord, *cart_coord_; /*!< \brief Cartesian coordinates of a point. */ + su2double ObjFunc; /*!< \brief Objective function of the point inversion process. */ + su2double* Gradient; /*!< \brief Gradient of the point inversion process. */ + su2double** Hessian; /*!< \brief Hessian of the point inversion process. */ + su2double MaxCoord[3]; /*!< \brief Maximum coordinates of the FFDBox. */ + su2double MinCoord[3]; /*!< \brief Minimum coordinates of the FFDBox. */ + string Tag; /*!< \brief Tag to identify the FFDBox. */ + unsigned short Level; /*!< \brief Nested level of the FFD box. */ vector CartesianCoord[3]; /*!< \brief Vector with all the cartesian coordinates in the FFD FFDBox. */ vector ParametricCoord[3]; /*!< \brief Vector with all the parametrics coordinates in the FFD FFDBox. */ - vector MarkerIndex; /*!< \brief Vector with all markers in the FFD FFDBox. */ - vector VertexIndex; /*!< \brief Vector with all vertex index in the FFD FFDBox. */ - vector PointIndex; /*!< \brief Vector with all points index in the FFD FFDBox. */ - unsigned long nSurfacePoint; /*!< \brief Number of surfaces in the FFD FFDBox. */ - vector ParentFFDBox; /*!< \brief Vector with all the parent FFD FFDBox. */ - vector ChildFFDBox; /*!< \brief Vector with all the child FFD FFDBox. */ - vector Fix_IPlane; /*!< \brief Fix FFD I plane. */ - vector Fix_JPlane; /*!< \brief Fix FFD J plane. */ - vector Fix_KPlane; /*!< \brief Fix FFD K plane. */ + vector MarkerIndex; /*!< \brief Vector with all markers in the FFD FFDBox. */ + vector VertexIndex; /*!< \brief Vector with all vertex index in the FFD FFDBox. */ + vector PointIndex; /*!< \brief Vector with all points index in the FFD FFDBox. */ + unsigned long nSurfacePoint; /*!< \brief Number of surfaces in the FFD FFDBox. */ + vector ParentFFDBox; /*!< \brief Vector with all the parent FFD FFDBox. */ + vector ChildFFDBox; /*!< \brief Vector with all the child FFD FFDBox. */ + vector Fix_IPlane; /*!< \brief Fix FFD I plane. */ + vector Fix_JPlane; /*!< \brief Fix FFD J plane. */ + vector Fix_KPlane; /*!< \brief Fix FFD K plane. */ CFreeFormBlending** BlendingFunction; - -public: - + public: /*! * \brief Constructor of the class. */ @@ -172,29 +170,32 @@ class CFreeFormDefBox : public CGridMovement { * \brief Add to the vector of cartesian coordinates a new coordinate. * \param[in] val_coord - New coordinate inside the FFD box. */ - inline void Set_CartesianCoord(su2double *val_coord) { CartesianCoord[0].push_back(val_coord[0]); - CartesianCoord[1].push_back(val_coord[1]); - CartesianCoord[2].push_back(val_coord[2]); } - + inline void Set_CartesianCoord(su2double* val_coord) { + CartesianCoord[0].push_back(val_coord[0]); + CartesianCoord[1].push_back(val_coord[1]); + CartesianCoord[2].push_back(val_coord[2]); + } /*! * \brief Adds to the vector of cartesian coordinates. * \param[in] val_coord - New coord inside FFD box. * \param[in] val_iSurfacePoints - Surface points of FFD box. */ - inline void Set_CartesianCoord(const su2double *val_coord, unsigned long val_iSurfacePoints) { CartesianCoord[0][val_iSurfacePoints] = val_coord[0]; - CartesianCoord[1][val_iSurfacePoints] = val_coord[1]; - CartesianCoord[2][val_iSurfacePoints] = val_coord[2]; } - + inline void Set_CartesianCoord(const su2double* val_coord, unsigned long val_iSurfacePoints) { + CartesianCoord[0][val_iSurfacePoints] = val_coord[0]; + CartesianCoord[1][val_iSurfacePoints] = val_coord[1]; + CartesianCoord[2][val_iSurfacePoints] = val_coord[2]; + } /*! * \brief Add to the vector of parametric coordinates a new coordinate. * \param[in] val_coord - New coordinate inside the FFD box. */ - inline void Set_ParametricCoord(su2double *val_coord) { ParametricCoord[0].push_back(val_coord[0]); - ParametricCoord[1].push_back(val_coord[1]); - ParametricCoord[2].push_back(val_coord[2]); } - + inline void Set_ParametricCoord(su2double* val_coord) { + ParametricCoord[0].push_back(val_coord[0]); + ParametricCoord[1].push_back(val_coord[1]); + ParametricCoord[2].push_back(val_coord[2]); + } /*! * \brief Add to the vector of parent FFDBoxes a new FFD FFDBox. @@ -213,10 +214,11 @@ class CFreeFormDefBox : public CGridMovement { * \param[in] val_coord - New coord inside FFD box. * \param[in] val_iSurfacePoints - Surface points of FFD box. */ - inline void Set_ParametricCoord(const su2double *val_coord, unsigned long val_iSurfacePoints) { ParametricCoord[0][val_iSurfacePoints] = val_coord[0]; - ParametricCoord[1][val_iSurfacePoints] = val_coord[1]; - ParametricCoord[2][val_iSurfacePoints] = val_coord[2]; } - + inline void Set_ParametricCoord(const su2double* val_coord, unsigned long val_iSurfacePoints) { + ParametricCoord[0][val_iSurfacePoints] = val_coord[0]; + ParametricCoord[1][val_iSurfacePoints] = val_coord[1]; + ParametricCoord[2][val_iSurfacePoints] = val_coord[2]; + } /*! * \brief Get index of the marker. @@ -240,7 +242,7 @@ class CFreeFormDefBox : public CGridMovement { * \brief Get Cartesian coordinates. * \param[in] Get_VertexIndex - Surface points of FFD box. */ - inline su2double *Get_CartesianCoord(unsigned long val_iSurfacePoints) { + inline su2double* Get_CartesianCoord(unsigned long val_iSurfacePoints) { cart_coord_[0] = CartesianCoord[0][val_iSurfacePoints]; cart_coord_[1] = CartesianCoord[1][val_iSurfacePoints]; cart_coord_[2] = CartesianCoord[2][val_iSurfacePoints]; @@ -251,7 +253,7 @@ class CFreeFormDefBox : public CGridMovement { * \brief Get parametric coordinates. * \param[in] Get_VertexIndex - Surface points of FFD box. */ - inline su2double *Get_ParametricCoord(unsigned long val_iSurfacePoints) { + inline su2double* Get_ParametricCoord(unsigned long val_iSurfacePoints) { ParamCoord_[0] = ParametricCoord[0][val_iSurfacePoints]; ParamCoord_[1] = ParametricCoord[1][val_iSurfacePoints]; ParamCoord_[2] = ParametricCoord[2][val_iSurfacePoints]; @@ -265,7 +267,7 @@ class CFreeFormDefBox : public CGridMovement { /*! * \brief Get number of parent FFD boxes. - */ + */ inline unsigned short GetnParentFFDBox(void) const { return ParentFFDBox.size(); } /*! @@ -290,7 +292,7 @@ class CFreeFormDefBox : public CGridMovement { * and find the position of the control points for the FFDBox * \param[in] FFDBox - Original FFDBox where we want to compute the control points. */ - void SetSupportCPChange(CFreeFormDefBox *FFDBox); + void SetSupportCPChange(CFreeFormDefBox* FFDBox); /*! * \brief Set the number of corner points. @@ -314,7 +316,7 @@ class CFreeFormDefBox : public CGridMovement { * \brief Get the number of control points. * \return Number of control points. */ - inline void SetnControlPoints(void) { nControlPoints = lOrder*mOrder*nOrder; } + inline void SetnControlPoints(void) { nControlPoints = lOrder * mOrder * nOrder; } /*! * \brief Get the number of numerical points on the surface. @@ -332,12 +334,10 @@ class CFreeFormDefBox : public CGridMovement { * \param[in] val_coord - Coordinates of the corner point with index val_icornerpoints. * \param[in] val_icornerpoints - Index of the corner point. */ - inline void SetCoordCornerPoints(const su2double *val_coord, unsigned short val_icornerpoints) { - for (unsigned short iDim = 0; iDim < nDim; iDim++) - Coord_Corner_Points[val_icornerpoints][iDim] = val_coord[iDim]; + inline void SetCoordCornerPoints(const su2double* val_coord, unsigned short val_icornerpoints) { + for (unsigned short iDim = 0; iDim < nDim; iDim++) Coord_Corner_Points[val_icornerpoints][iDim] = val_coord[iDim]; } - /*! * \overload * \param[in] val_xcoord - X coordinate of the corner point with index val_icornerpoints. @@ -345,13 +345,13 @@ class CFreeFormDefBox : public CGridMovement { * \param[in] val_zcoord - Z coordinate of the corner point with index val_icornerpoints. * \param[in] val_icornerpoints - Index of the corner point. */ - inline void SetCoordCornerPoints(su2double val_xcoord, su2double val_ycoord, su2double val_zcoord, unsigned short val_icornerpoints) { + inline void SetCoordCornerPoints(su2double val_xcoord, su2double val_ycoord, su2double val_zcoord, + unsigned short val_icornerpoints) { Coord_Corner_Points[val_icornerpoints][0] = val_xcoord; Coord_Corner_Points[val_icornerpoints][1] = val_ycoord; Coord_Corner_Points[val_icornerpoints][2] = val_zcoord; } - /*! * \brief Set the coordinates of the control points. * \param[in] val_coord - Coordinates of the control point. @@ -359,13 +359,13 @@ class CFreeFormDefBox : public CGridMovement { * \param[in] jDegree - Index of the FFDBox, j direction. * \param[in] kDegree - Index of the FFDBox, k direction. */ - inline void SetCoordControlPoints(const su2double *val_coord, unsigned short iDegree, unsigned short jDegree, unsigned short kDegree) { + inline void SetCoordControlPoints(const su2double* val_coord, unsigned short iDegree, unsigned short jDegree, + unsigned short kDegree) { for (unsigned short iDim = 0; iDim < nDim; iDim++) { Coord_Control_Points[iDegree][jDegree][kDegree][iDim] = val_coord[iDim]; } } - /*! * \brief Set the coordinates of the control points. * \param[in] val_coord - Coordinates of the control point. @@ -373,10 +373,11 @@ class CFreeFormDefBox : public CGridMovement { * \param[in] jDegree - Index of the FFDBox, j direction. * \param[in] kDegree - Index of the FFDBox, k direction. */ - inline void SetCoordControlPoints_Copy(const su2double *val_coord, unsigned short iDegree, unsigned short jDegree, unsigned short kDegree) { + inline void SetCoordControlPoints_Copy(const su2double* val_coord, unsigned short iDegree, unsigned short jDegree, + unsigned short kDegree) { for (unsigned short iDim = 0; iDim < nDim; iDim++) { - Coord_Control_Points_Copy[iDegree][jDegree][kDegree][iDim] = val_coord[iDim]; - } + Coord_Control_Points_Copy[iDegree][jDegree][kDegree][iDim] = val_coord[iDim]; + } } /*! @@ -386,9 +387,10 @@ class CFreeFormDefBox : public CGridMovement { * \param[in] jDegree - Index of the FFDBox, j direction. * \param[in] kDegree - Index of the FFDBox, k direction. */ - inline void SetParCoordControlPoints(const su2double *val_coord, unsigned short iDegree, unsigned short jDegree, unsigned short kDegree) { + inline void SetParCoordControlPoints(const su2double* val_coord, unsigned short iDegree, unsigned short jDegree, + unsigned short kDegree) { for (unsigned short iDim = 0; iDim < nDim; iDim++) - ParCoord_Control_Points[iDegree][jDegree][kDegree][iDim] = val_coord[iDim]; + ParCoord_Control_Points[iDegree][jDegree][kDegree][iDim] = val_coord[iDim]; } /*! @@ -397,14 +399,18 @@ class CFreeFormDefBox : public CGridMovement { * \param[in] val_icornerpoints - Index of the corner point. * \return Coordinate val_dim of the corner point val_icornerpoints. */ - inline su2double GetCoordCornerPoints(unsigned short val_dim, unsigned short val_icornerpoints) const { return Coord_Corner_Points[val_icornerpoints][val_dim]; } + inline su2double GetCoordCornerPoints(unsigned short val_dim, unsigned short val_icornerpoints) const { + return Coord_Corner_Points[val_icornerpoints][val_dim]; + } /*! * \brief Get the coordinates of the corner points. * \param[in] val_icornerpoints - Index of the corner point. * \return Pointer to the coordinate vector of the corner point val_icornerpoints. */ - inline su2double *GetCoordCornerPoints(unsigned short val_icornerpoints) const { return Coord_Corner_Points[val_icornerpoints]; } + inline su2double* GetCoordCornerPoints(unsigned short val_icornerpoints) const { + return Coord_Corner_Points[val_icornerpoints]; + } /*! * \brief Get the coordinates of the control point. @@ -413,7 +419,10 @@ class CFreeFormDefBox : public CGridMovement { * \param[in] val_kindex - Value of the local k index of the control point. * \return Pointer to the coordinate vector of the control point with local index (i, j, k). */ - inline su2double *GetCoordControlPoints(unsigned short val_iindex, unsigned short val_jindex, unsigned short val_kindex) const { return Coord_Control_Points[val_iindex][val_jindex][val_kindex]; } + inline su2double* GetCoordControlPoints(unsigned short val_iindex, unsigned short val_jindex, + unsigned short val_kindex) const { + return Coord_Control_Points[val_iindex][val_jindex][val_kindex]; + } /*! * \brief Get the parametric coordinates of the control point. @@ -422,7 +431,10 @@ class CFreeFormDefBox : public CGridMovement { * \param[in] val_kindex - Value of the local k index of the control point. * \return Pointer to the coordinate vector of the control point with local index (i, j, k). */ - inline su2double *GetParCoordControlPoints(unsigned short val_iindex, unsigned short val_jindex, unsigned short val_kindex) const { return ParCoord_Control_Points[val_iindex][val_jindex][val_kindex]; } + inline su2double* GetParCoordControlPoints(unsigned short val_iindex, unsigned short val_jindex, + unsigned short val_kindex) const { + return ParCoord_Control_Points[val_iindex][val_jindex][val_kindex]; + } /*! * \brief Set the control points in a parallelepiped (hexahedron). @@ -433,14 +445,14 @@ class CFreeFormDefBox : public CGridMovement { * \brief Set the control points of the final chuck in a unitary hexahedron free form. * \param[in] FFDBox - Original FFDBox where we want to compute the control points. */ - void SetSupportCP(CFreeFormDefBox *FFDBox); + void SetSupportCP(CFreeFormDefBox* FFDBox); /*! * \brief Set the new value of the coordinates of the control points. * \param[in] val_index - Local index (i, j, k) of the control point. * \param[in] movement - Movement of the control point. */ - inline void SetControlPoints(const unsigned short *val_index, const su2double *movement) { + inline void SetControlPoints(const unsigned short* val_index, const su2double* movement) { for (unsigned short iDim = 0; iDim < nDim; iDim++) Coord_Control_Points[val_index[0]][val_index[1]][val_index[2]][iDim] += movement[iDim]; } @@ -453,10 +465,15 @@ class CFreeFormDefBox : public CGridMovement { for (unsigned short jDegree = 0; jDegree <= mDegree_Copy; jDegree++) for (unsigned short kDegree = 0; kDegree <= nDegree_Copy; kDegree++) for (unsigned short iDim = 0; iDim < nDim; iDim++) - Coord_Control_Points[iDegree][jDegree][kDegree][iDim] = Coord_Control_Points_Copy[iDegree][jDegree][kDegree][iDim]; - - lDegree = lDegree_Copy; mDegree = mDegree_Copy; nDegree = nDegree_Copy; - lOrder = lOrder_Copy; mOrder = mOrder_Copy; nOrder = nOrder_Copy; + Coord_Control_Points[iDegree][jDegree][kDegree][iDim] = + Coord_Control_Points_Copy[iDegree][jDegree][kDegree][iDim]; + + lDegree = lDegree_Copy; + mDegree = mDegree_Copy; + nDegree = nDegree_Copy; + lOrder = lOrder_Copy; + mOrder = mOrder_Copy; + nOrder = nOrder_Copy; nControlPoints = nControlPoints_Copy; } @@ -465,69 +482,69 @@ class CFreeFormDefBox : public CGridMovement { * \param[in] iFFDBox - Index of the FFD box. * \param[in] original - Original box (before deformation). */ - void SetTecplot(CGeometry *geometry, unsigned short iFFDBox, bool original); + void SetTecplot(CGeometry* geometry, unsigned short iFFDBox, bool original); /*! * \brief Set the paraview file of the FFD chuck structure. * \param[in] iFFDBox - Index of the FFD box. * \param[in] original - Original box (before deformation). */ - void SetParaview(CGeometry *geometry, unsigned short iFFDBox, bool original); + void SetParaview(CGeometry* geometry, unsigned short iFFDBox, bool original); /*! * \brief Set the CGNS file of the FFD chuck structure. * \param[in] iFFDBox - Index of the FFD box. * \param[in] original - Original box (before deformation). */ - void SetCGNS(CGeometry *geometry, unsigned short iFFDBox, bool original); + void SetCGNS(CGeometry* geometry, unsigned short iFFDBox, bool original); /*! * \brief Set Cylindrical to Cartesians_ControlPoints. * \param[in] config - Definition of the particular problem. */ - void SetCyl2Cart_ControlPoints(CConfig *config); + void SetCyl2Cart_ControlPoints(CConfig* config); /*! * \brief Set Cartesians to Cylindrical ControlPoints. * \param[in] config - Definition of the particular problem. */ - void SetCart2Cyl_ControlPoints(CConfig *config); + void SetCart2Cyl_ControlPoints(CConfig* config); /*! * \brief Set Cylindrical to Cartesians_CornerPoints. * \param[in] config - Definition of the particular problem. */ - void SetCyl2Cart_CornerPoints(CConfig *config); + void SetCyl2Cart_CornerPoints(CConfig* config); /*! * \brief Set Cartesians to Cylindrical CornerPoints. * \param[in] config - Definition of the particular problem. */ - void SetCart2Cyl_CornerPoints(CConfig *config); + void SetCart2Cyl_CornerPoints(CConfig* config); /*! * \brief Set Spherical to Cartesians ControlPoints. * \param[in] config - Definition of the particular problem. */ - void SetSphe2Cart_ControlPoints(CConfig *config); + void SetSphe2Cart_ControlPoints(CConfig* config); /*! * \brief SetCartesians to Spherical ControlPoints. * \param[in] config - Definition of the particular problem. */ - void SetCart2Sphe_ControlPoints(CConfig *config); + void SetCart2Sphe_ControlPoints(CConfig* config); /*! * \brief Set Spherical to Cartesians_CornerPoints. * \param[in] config - Definition of the particular problem. */ - void SetSphe2Cart_CornerPoints(CConfig *config); + void SetSphe2Cart_CornerPoints(CConfig* config); /*! * \brief Set Cartesians to Spherical Corner Points. * \param[in] config - Definition of the particular problem. */ - void SetCart2Sphe_CornerPoints(CConfig *config); + void SetCart2Sphe_CornerPoints(CConfig* config); /*! * \brief Set the cartesian coords of a point in R^3 and convert them to the parametric coords of @@ -535,7 +552,7 @@ class CFreeFormDefBox : public CGridMovement { * \param[in] cart_coord - Cartesian coordinates of a point. * \return Pointer to the parametric coordinates of a point. */ - su2double *GetParametricCoord_Analytical(const su2double *cart_coord); + su2double* GetParametricCoord_Analytical(const su2double* cart_coord); /*! * \brief Iterative strategy for computing the parametric coordinates. @@ -545,7 +562,8 @@ class CFreeFormDefBox : public CGridMovement { * \param[in] it_max - Maximal number of iterations. * \return Parametric coordinates of the point. */ - su2double *GetParametricCoord_Iterative(unsigned long iPoint, su2double *xyz, const su2double *guess, CConfig *config); + su2double* GetParametricCoord_Iterative(unsigned long iPoint, su2double* xyz, const su2double* guess, + CConfig* config); /*! * \brief Compute the cross product. @@ -553,10 +571,10 @@ class CFreeFormDefBox : public CGridMovement { * \param[in] v2 - Second input vector. * \param[out] v3 - Output vector wuth the cross product. */ - inline void CrossProduct(const su2double *v1, const su2double *v2, su2double *v3) { - v3[0] = v1[1]*v2[2]-v1[2]*v2[1]; - v3[1] = v1[2]*v2[0]-v1[0]*v2[2]; - v3[2] = v1[0]*v2[1]-v1[1]*v2[0]; + inline void CrossProduct(const su2double* v1, const su2double* v2, su2double* v3) { + v3[0] = v1[1] * v2[2] - v1[2] * v2[1]; + v3[1] = v1[2] * v2[0] - v1[0] * v2[2]; + v3[2] = v1[0] * v2[1] - v1[1] * v2[0]; } /*! @@ -565,7 +583,10 @@ class CFreeFormDefBox : public CGridMovement { * \param[in] v2 - Sencond input vector. * \return Dot product between v1, and v2. */ - inline su2double DotProduct(const su2double *v1, const su2double *v2) { su2double scalar = v1[0]*v2[0]+v1[1]*v2[1]+v1[2]*v2[2]; return scalar; } + inline su2double DotProduct(const su2double* v1, const su2double* v2) { + su2double scalar = v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2]; + return scalar; + } /*! * \brief Here we take the parametric coords of a point in the box and we convert them to the @@ -573,7 +594,7 @@ class CFreeFormDefBox : public CGridMovement { * \param[in] ParamCoord - Parametric coordinates of a point. * \return Pointer to the cartesian coordinates of a point. */ - su2double *EvalCartesianCoord(su2double *ParamCoord) const; + su2double* EvalCartesianCoord(su2double* ParamCoord) const; /*! * \brief Get the order in the l direction of the FFD FFDBox. @@ -597,19 +618,28 @@ class CFreeFormDefBox : public CGridMovement { * \brief Get the order in the l direction of the FFD FFDBox. * \return Order in the l direction of the FFD FFDBox. */ - inline void SetlOrder(unsigned short val_lOrder) { lOrder = val_lOrder; lDegree = lOrder-1; } + inline void SetlOrder(unsigned short val_lOrder) { + lOrder = val_lOrder; + lDegree = lOrder - 1; + } /*! * \brief Get the order in the m direction of the FFD FFDBox. * \return Order in the m direction of the FFD FFDBox. */ - inline void SetmOrder(unsigned short val_mOrder) { mOrder = val_mOrder; mDegree = mOrder-1; } + inline void SetmOrder(unsigned short val_mOrder) { + mOrder = val_mOrder; + mDegree = mOrder - 1; + } /*! * \brief Get the order in the n direction of the FFD FFDBox. * \return Order in the n direction of the FFD FFDBox. */ - inline void SetnOrder(unsigned short val_nOrder) { nOrder = val_nOrder; nDegree = nOrder-1;} + inline void SetnOrder(unsigned short val_nOrder) { + nOrder = val_nOrder; + nDegree = nOrder - 1; + } /*! * \brief Set, at each vertex, the index of the free form FFDBox that contains the vertex. @@ -617,7 +647,7 @@ class CFreeFormDefBox : public CGridMovement { * \param[in] config - Definition of the particular problem. * \param[in] iFFDBox - Index of the FFDBox. */ - bool GetPointFFD(CGeometry *geometry, CConfig *config, unsigned long iPoint) const; + bool GetPointFFD(CGeometry* geometry, CConfig* config, unsigned long iPoint) const; /*! * \brief Set the zone of the computational domain that is going to be deformed. @@ -626,7 +656,7 @@ class CFreeFormDefBox : public CGridMovement { * \param[in] iFFDBox - Index of the FFDBox. */ // this routine is not used. We should consider deleting it. - void SetDeformationZone(CGeometry *geometry, CConfig *config, unsigned short iFFDBox) const; + void SetDeformationZone(CGeometry* geometry, CConfig* config, unsigned short iFFDBox) const; /*! * \brief The routine computes the gradient of F(u, v, w) = ||X(u, v, w)-(x, y, z)||^2 evaluated at (u, v, w). @@ -635,7 +665,7 @@ class CFreeFormDefBox : public CGridMovement { * \param[in] analytical - Compute the analytical gradient. * \return Value of the analytical gradient. */ - su2double *GetFFDGradient(su2double *val_coord, su2double *xyz); + su2double* GetFFDGradient(su2double* val_coord, su2double* xyz); /*! * \brief The routine that computes the Hessian of F(u, v, w) = ||X(u, v, w)-(x, y, z)||^2 evaluated at (u, v, w) @@ -645,35 +675,28 @@ class CFreeFormDefBox : public CGridMovement { * \param[in] xyz - Cartesians coordinates of the target point to compose the functional. * \param[in] val_Hessian - Value of the hessian. */ - void GetFFDHessian(su2double *uvw, su2double *xyz, su2double **val_Hessian); + void GetFFDHessian(su2double* uvw, su2double* xyz, su2double** val_Hessian); /*! * \brief An auxiliary routine to help us compute the gradient of F(u, v, w) = ||X(u, v, w)-(x, y, z)||^2 = * (Sum_ijk^lmn P1_ijk Bi Bj Bk -x)^2+(Sum_ijk^lmn P2_ijk Bi Bj Bk -y)^2+(Sum_ijk^lmn P3_ijk Bi Bj Bk -z)^2 - * Input: val_t, val_diff (to identify the index of the Bernstein polynomail we differentiate), the i, j, k , l, m, n - * E.G.: val_diff=2 => we differentiate w.r.t. w (val_diff=0,1, or 2) Output: d [B_i^l*B_j^m *B_k^n] / d val_diff - * (val_u, val_v, val_w). - * \param[in] uvw - __________. - * \param[in] val_diff - __________. - * \param[in] ijk - __________. - * \param[in] lmn - Degree of the FFD box. - * \return __________. + * Input: val_t, val_diff (to identify the index of the Bernstein polynomail we differentiate), the i, j, k , + * l, m, n E.G.: val_diff=2 => we differentiate w.r.t. w (val_diff=0,1, or 2) Output: d [B_i^l*B_j^m *B_k^n] / d + * val_diff (val_u, val_v, val_w). \param[in] uvw - __________. \param[in] val_diff - __________. \param[in] ijk - + * __________. \param[in] lmn - Degree of the FFD box. \return __________. */ - su2double GetDerivative1(su2double *uvw, unsigned short val_diff, unsigned short *ijk, unsigned short *lmn) const; + su2double GetDerivative1(su2double* uvw, unsigned short val_diff, unsigned short* ijk, unsigned short* lmn) const; /*! * \brief An auxiliary routine to help us compute the gradient of F(u, v, w) = ||X(u, v, w)-(x, y, z)||^2 = * (Sum_ijk^lmn P1_ijk Bi Bj Bk -x)^2+(Sum_ijk^lmn P2_ijk Bi Bj Bk -y)^2+(Sum_ijk^lmn P3_ijk Bi Bj Bk -z)^2 - * Input: (u, v, w), dim , xyz=(x, y, z), l, m, n E.G.: dim=2 => we use the third coordinate of the control points, - * and the z-coordinate of xyz (0<=dim<=2) Output: 2* ( (Sum_{i, j, k}^l, m, n P_{ijk}[dim] B_i^l[u] B_j^m[v] B_k^n[w]) - - * xyz[dim]). - * \param[in] uvw - __________. - * \param[in] dim - __________. - * \param[in] xyz - __________. + * Input: (u, v, w), dim , xyz=(x, y, z), l, m, n E.G.: dim=2 => we use the third coordinate of the control + * points, and the z-coordinate of xyz (0<=dim<=2) Output: 2* ( (Sum_{i, j, k}^l, m, n P_{ijk}[dim] B_i^l[u] B_j^m[v] + * B_k^n[w]) - xyz[dim]). \param[in] uvw - __________. \param[in] dim - __________. \param[in] xyz - __________. * \param[in] lmn - Degree of the FFD box. * \return __________. */ - su2double GetDerivative2(su2double *uvw, unsigned short dim, const su2double *xyz, const unsigned short *lmn) const; + su2double GetDerivative2(su2double* uvw, unsigned short dim, const su2double* xyz, const unsigned short* lmn) const; /*! * \brief An auxiliary routine to help us compute the gradient of F(u, v, w) = ||X(u, v, w)-(x, y, z)||^2 = @@ -687,25 +710,20 @@ class CFreeFormDefBox : public CGridMovement { * which? diff_thiss will tell us ; E.G.: dim=2, diff_this=1 => we use the third coordinate of the control * points, and derivate de v-Bersntein polynomial (use m-1 when summing!!). */ - su2double GetDerivative3(su2double *uvw, unsigned short dim, unsigned short diff_this, - unsigned short *lmn); + su2double GetDerivative3(su2double* uvw, unsigned short dim, unsigned short diff_this, unsigned short* lmn); /*! * \brief An auxiliary routine to help us compute the Hessian of F(u, v, w) = ||X(u, v, w)-(x, y, z)||^2 = * (Sum_ijk^lmn P1_ijk Bi Bj Bk -x)^2+(Sum_ijk^lmn P2_ijk Bi Bj Bk -y)+(Sum_ijk^lmn P3_ijk Bi Bj Bk -z) - * Input: val_t, val_diff, val_diff2 (to identify the index of the Bernstein polynomials we differentiate), the i, j, k , l, m, n - * E.G.: val_diff=1, val_diff2=2 => we differentiate w.r.t. v and w (val_diff=0,1, or 2) - * E.G.: val_diff=0, val_diff2=0 => we differentiate w.r.t. u two times - * Output: [d [B_i^l*B_j^m *B_k^n]/d val_diff *d [B_i^l*B_j^m *B_k^n]/d val_diff2] (val_u, val_v, val_w) . - * \param[in] uvw - __________. - * \param[in] val_diff - __________. - * \param[in] val_diff2 - __________. - * \param[in] ijk - __________. - * \param[in] lmn - Degree of the FFD box. + * Input: val_t, val_diff, val_diff2 (to identify the index of the Bernstein polynomials we differentiate), the + * i, j, k , l, m, n E.G.: val_diff=1, val_diff2=2 => we differentiate w.r.t. v and w (val_diff=0,1, or 2) E.G.: + * val_diff=0, val_diff2=0 => we differentiate w.r.t. u two times Output: [d [B_i^l*B_j^m *B_k^n]/d val_diff *d + * [B_i^l*B_j^m *B_k^n]/d val_diff2] (val_u, val_v, val_w) . \param[in] uvw - __________. \param[in] val_diff - + * __________. \param[in] val_diff2 - __________. \param[in] ijk - __________. \param[in] lmn - Degree of the FFD box. * \return __________. */ - su2double GetDerivative4(su2double *uvw, unsigned short val_diff, unsigned short val_diff2, - unsigned short *ijk, unsigned short *lmn) const; + su2double GetDerivative4(su2double* uvw, unsigned short val_diff, unsigned short val_diff2, unsigned short* ijk, + unsigned short* lmn) const; /*! * \brief An auxiliary routine to help us compute the Hessian of F(u, v, w) = ||X(u, v, w)-(x, y, z)||^2 = @@ -723,15 +741,18 @@ class CFreeFormDefBox : public CGridMovement { * \param[in] lmn - Degree of the FFD box. * \return __________. */ - su2double GetDerivative5(su2double *uvw, unsigned short dim, unsigned short diff_this, unsigned short diff_this_also, - unsigned short *lmn); + su2double GetDerivative5(su2double* uvw, unsigned short dim, unsigned short diff_this, unsigned short diff_this_also, + unsigned short* lmn); /*! * \brief Euclidean norm of a vector. * \param[in] a - _______. * \return __________. */ - inline su2double GetNorm(const su2double *a) { su2double norm = sqrt(a[0]*a[0] + a[1]*a[1]+ a[2]*a[2]); return norm; } + inline su2double GetNorm(const su2double* a) { + su2double norm = sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2]); + return norm; + } /*! * \brief Set the tag that identify a FFDBox. @@ -756,5 +777,4 @@ class CFreeFormDefBox : public CGridMovement { * \return Value of the nested level of the the FFDBox. */ inline unsigned short GetLevel() const { return Level; } - }; diff --git a/Common/include/grid_movement/CGridMovement.hpp b/Common/include/grid_movement/CGridMovement.hpp index a382b58fd0f..e167dd58133 100644 --- a/Common/include/grid_movement/CGridMovement.hpp +++ b/Common/include/grid_movement/CGridMovement.hpp @@ -37,13 +37,11 @@ * \author F. Palacios */ class CGridMovement { + protected: + int rank, /*!< \brief MPI Rank. */ + size; /*!< \brief MPI Size. */ -protected: - int rank, /*!< \brief MPI Rank. */ - size; /*!< \brief MPI Size. */ - -public: - + public: /*! * \brief Constructor of the class. */ @@ -60,7 +58,7 @@ class CGridMovement { * \param[in] config - Definition of the particular problem. * \return Total deformation applied, which may be less than target if intersection prevention is used. */ - inline virtual vector > SetSurface_Deformation(CGeometry *geometry, CConfig *config) { + inline virtual vector > SetSurface_Deformation(CGeometry* geometry, CConfig* config) { return vector >(); } }; diff --git a/Common/include/grid_movement/CSurfaceMovement.hpp b/Common/include/grid_movement/CSurfaceMovement.hpp index 564071e9338..28eca93c343 100644 --- a/Common/include/grid_movement/CSurfaceMovement.hpp +++ b/Common/include/grid_movement/CSurfaceMovement.hpp @@ -36,13 +36,13 @@ * \author F. Palacios, T. Economon. */ class CSurfaceMovement : public CGridMovement { -protected: + protected: CFreeFormDefBox** FFDBox; /*!< \brief Definition of the Free Form Deformation Box. */ - unsigned short nFFDBox; /*!< \brief Number of FFD FFDBoxes. */ - unsigned short nLevel; /*!< \brief Level of the FFD FFDBoxes (parent/child). */ - bool FFDBoxDefinition; /*!< \brief If the FFD FFDBox has been defined in the input file. */ + unsigned short nFFDBox; /*!< \brief Number of FFD FFDBoxes. */ + unsigned short nLevel; /*!< \brief Level of the FFD FFDBoxes (parent/child). */ + bool FFDBoxDefinition; /*!< \brief If the FFD FFDBox has been defined in the input file. */ -public: + public: vector GlobalCoordX[MAX_NUMBER_FFD]; vector GlobalCoordY[MAX_NUMBER_FFD]; vector GlobalCoordZ[MAX_NUMBER_FFD]; @@ -66,7 +66,7 @@ class CSurfaceMovement : public CGridMovement { * \param[in] iDV - Index of the design variable. * \param[in] ResetDef - Reset the deformation before starting a new one. */ - void SetHicksHenne(CGeometry *boundary, CConfig *config, unsigned short iDV, bool ResetDef); + void SetHicksHenne(CGeometry* boundary, CConfig* config, unsigned short iDV, bool ResetDef); /*! * \brief Set a Hicks-Henne deformation bump functions on an airfoil. @@ -75,7 +75,7 @@ class CSurfaceMovement : public CGridMovement { * \param[in] iDV - Index of the design variable. * \param[in] ResetDef - Reset the deformation before starting a new one. */ - void SetSurface_Bump(CGeometry *boundary, CConfig *config, unsigned short iDV, bool ResetDef); + void SetSurface_Bump(CGeometry* boundary, CConfig* config, unsigned short iDV, bool ResetDef); /*! * \brief Set a Hicks-Henne deformation bump functions on an airfoil. @@ -84,7 +84,7 @@ class CSurfaceMovement : public CGridMovement { * \param[in] iDV - Index of the design variable. * \param[in] ResetDef - Reset the deformation before starting a new one. */ - void SetAngleOfAttack(CGeometry *boundary, CConfig *config, unsigned short iDV, bool ResetDef); + void SetAngleOfAttack(CGeometry* boundary, CConfig* config, unsigned short iDV, bool ResetDef); /*! * \brief Set a deformation based on a change in the Kulfan parameters for an airfoil. @@ -93,28 +93,28 @@ class CSurfaceMovement : public CGridMovement { * \param[in] iDV - Index of the design variable. * \param[in] ResetDef - Reset the deformation before starting a new one. */ - void SetCST(CGeometry *boundary, CConfig *config, unsigned short iDV, bool ResetDef); + void SetCST(CGeometry* boundary, CConfig* config, unsigned short iDV, bool ResetDef); /*! * \brief Set a NACA 4 digits airfoil family for airfoil deformation. * \param[in] boundary - Geometry of the boundary. * \param[in] config - Definition of the particular problem. */ - void SetNACA_4Digits(CGeometry *boundary, CConfig *config); + void SetNACA_4Digits(CGeometry* boundary, CConfig* config); /*! * \brief Set a parabolic family for airfoil deformation. * \param[in] boundary - Geometry of the boundary. * \param[in] config - Definition of the particular problem. */ - void SetParabolic(CGeometry *boundary, CConfig *config); + void SetParabolic(CGeometry* boundary, CConfig* config); /*! * \brief Set a obstacle in a channel. * \param[in] boundary - Geometry of the boundary. * \param[in] config - Definition of the particular problem. */ - void SetAirfoil(CGeometry *boundary, CConfig *config); + void SetAirfoil(CGeometry* boundary, CConfig* config); /*! * \brief Set a rotation for surface movement. @@ -123,7 +123,7 @@ class CSurfaceMovement : public CGridMovement { * \param[in] iDV - Index of the design variable. * \param[in] ResetDef - Reset the deformation before starting a new one. */ - void SetRotation(CGeometry *boundary, CConfig *config, unsigned short iDV, bool ResetDef); + void SetRotation(CGeometry* boundary, CConfig* config, unsigned short iDV, bool ResetDef); /*! * \brief Computes the displacement of a rotating surface for a dynamic mesh simulation. @@ -132,8 +132,7 @@ class CSurfaceMovement : public CGridMovement { * \param[in] iter - Current physical time iteration. * \param[in] iZone - Zone number in the mesh. */ - void HTP_Rotation(CGeometry *geometry, CConfig *config, - unsigned long iter, unsigned short iZone); + void HTP_Rotation(CGeometry* geometry, CConfig* config, unsigned long iter, unsigned short iZone); /*! * \brief Unsteady aeroelastic grid movement by deforming the mesh. @@ -144,7 +143,8 @@ class CSurfaceMovement : public CGridMovement { * \param[in] iMarker_Monitoring - Marker we are monitoring. * \param[in] displacements - solution of typical section wing model. */ - void AeroelasticDeform(CGeometry *geometry, CConfig *config, unsigned long TimeIter, unsigned short iMarker, unsigned short iMarker_Monitoring, vector& displacements); + void AeroelasticDeform(CGeometry* geometry, CConfig* config, unsigned long TimeIter, unsigned short iMarker, + unsigned short iMarker_Monitoring, vector& displacements); /*! * \brief Deforms a 3-D flutter/pitching surface during an unsteady simulation. @@ -153,15 +153,15 @@ class CSurfaceMovement : public CGridMovement { * \param[in] iter - Current physical time iteration. * \param[in] iZone - Zone number in the mesh. */ - void SetBoundary_Flutter3D(CGeometry *geometry, CConfig *config, - CFreeFormDefBox **FFDBox, unsigned long iter, unsigned short iZone); + void SetBoundary_Flutter3D(CGeometry* geometry, CConfig* config, CFreeFormDefBox** FFDBox, unsigned long iter, + unsigned short iZone); /*! * \brief Set the collective pitch for a blade surface movement. * \param[in] geometry - Geometrical definition of the problem. * \param[in] config - Definition of the particular problem. */ - void SetCollective_Pitch(CGeometry *geometry, CConfig *config); + void SetCollective_Pitch(CGeometry* geometry, CConfig* config); /*! * \brief Set any surface deformationsbased on an input file. @@ -170,7 +170,7 @@ class CSurfaceMovement : public CGridMovement { * \param[in] iZone - Zone number in the mesh. * \param[in] iter - Current physical time iteration. */ - void SetExternal_Deformation(CGeometry *geometry, CConfig *config, unsigned short iZone, unsigned long iter); + void SetExternal_Deformation(CGeometry* geometry, CConfig* config, unsigned short iZone, unsigned long iter); /*! * \brief Set a displacement for surface movement. @@ -179,7 +179,7 @@ class CSurfaceMovement : public CGridMovement { * \param[in] iDV - Index of the design variable. * \param[in] ResetDef - Reset the deformation before starting a new one. */ - void SetTranslation(CGeometry *boundary, CConfig *config, unsigned short iDV, bool ResetDef); + void SetTranslation(CGeometry* boundary, CConfig* config, unsigned short iDV, bool ResetDef); /*! * \brief Set a displacement for surface movement. @@ -188,14 +188,14 @@ class CSurfaceMovement : public CGridMovement { * \param[in] iDV - Index of the design variable. * \param[in] ResetDef - Reset the deformation before starting a new one. */ - void SetScale(CGeometry *boundary, CConfig *config, unsigned short iDV, bool ResetDef); + void SetScale(CGeometry* boundary, CConfig* config, unsigned short iDV, bool ResetDef); /*! * \brief Copy the boundary coordinates to each vertex. * \param[in] geometry - Geometrical definition of the problem. * \param[in] config - Definition of the particular problem. */ - void CopyBoundary(CGeometry *geometry, CConfig *config); + void CopyBoundary(CGeometry* geometry, CConfig* config); /*! * \brief Set the surface/boundary deformation. @@ -203,7 +203,7 @@ class CSurfaceMovement : public CGridMovement { * \param[in] config - Definition of the particular problem. * \return Total deformation applied, which may be less than target if intersection prevention is used. */ - vector > SetSurface_Deformation(CGeometry *geometry, CConfig *config) override; + vector > SetSurface_Deformation(CGeometry* geometry, CConfig* config) override; /*! * \brief Compute the parametric coordinates of a grid point using a point inversion strategy @@ -212,7 +212,7 @@ class CSurfaceMovement : public CGridMovement { * \param[in] config - Definition of the particular problem. * \param[in] FFDBox - Array with all the free forms FFDBoxes of the computation. */ - void SetParametricCoord(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox, unsigned short iFFDBox); + void SetParametricCoord(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBox, unsigned short iFFDBox); /*! * \brief Update the parametric coordinates of a grid point using a point inversion strategy @@ -222,7 +222,7 @@ class CSurfaceMovement : public CGridMovement { * \param[in] FFDBox - Array with all the free forms FFDBoxes of the computation. * \param[in] iFFDBox - Index of FFD box. */ - void UpdateParametricCoord(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox, unsigned short iFFDBox); + void UpdateParametricCoord(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBox, unsigned short iFFDBox); /*! * \brief Check the intersections of the FFD with the surface @@ -231,7 +231,7 @@ class CSurfaceMovement : public CGridMovement { * \param[in] FFDBox - Array with all the free forms FFDBoxes of the computation. * \param[in] iFFDBox - Index of FFD box. */ - void CheckFFDIntersections(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox, unsigned short iFFDBox); + void CheckFFDIntersections(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBox, unsigned short iFFDBox); /*! * \brief Check the intersections of the FFD with the surface @@ -240,7 +240,7 @@ class CSurfaceMovement : public CGridMovement { * \param[in] FFDBox - Array with all the free forms FFDBoxes of the computation. * \param[in] iFFDBox - Index of FFD box. */ - void CheckFFDDimension(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox, unsigned short iFFDBox); + void CheckFFDDimension(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBox, unsigned short iFFDBox); /*! * \brief Set the Parametric coordinates. @@ -249,7 +249,8 @@ class CSurfaceMovement : public CGridMovement { * \param[in] FFDBoxParent - Array with parent FFDBoxes of the computation. * \param[in] FFDBoxChild - Array with child FFDBoxes of the computation. */ - void SetParametricCoordCP(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBoxParent, CFreeFormDefBox *FFDBoxChild); + void SetParametricCoordCP(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBoxParent, + CFreeFormDefBox* FFDBoxChild); /*! * \brief Get the cartes. @@ -258,7 +259,8 @@ class CSurfaceMovement : public CGridMovement { * \param[in] FFDBoxParent - Array with parent FFDBoxes of the computation. * \param[in] FFDBoxChild - Array with child FFDBoxes of the computation. */ - void GetCartesianCoordCP(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBoxParent, CFreeFormDefBox *FFDBoxChild); + void GetCartesianCoordCP(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBoxParent, + CFreeFormDefBox* FFDBoxChild); /*! * \brief Apply the design variables to the control point position @@ -267,7 +269,7 @@ class CSurfaceMovement : public CGridMovement { * \param[in] FFDBox - Array with all the free forms FFDBoxes of the computation. * \param[in] iFFDBox - Index of FFD box. */ - void ApplyDesignVariables(CGeometry *geometry, CConfig *config, CFreeFormDefBox **FFDBox, unsigned short iFFDBox); + void ApplyDesignVariables(CGeometry* geometry, CConfig* config, CFreeFormDefBox** FFDBox, unsigned short iFFDBox); /*! * \brief Recompute the cartesian coordinates using the control points position. @@ -276,7 +278,8 @@ class CSurfaceMovement : public CGridMovement { * \param[in] FFDBox - Array with all the free forms FFDBoxes of the computation. * \param[in] iFFDBox - Index of FFD box. */ - su2double SetCartesianCoord(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox, unsigned short iFFDBox, bool ResetDef); + su2double SetCartesianCoord(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBox, unsigned short iFFDBox, + bool ResetDef); /*! * \brief Set the deformation of the Free From box using the control point position. @@ -286,7 +289,8 @@ class CSurfaceMovement : public CGridMovement { * \param[in] iDV - Index of the design variable. * \param[in] ResetDef - Reset the deformation before starting a new one. */ - bool SetFFDCPChange_2D(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox, CFreeFormDefBox **ResetFFDBox, unsigned short iDV, bool ResetDef) const; + bool SetFFDCPChange_2D(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBox, CFreeFormDefBox** ResetFFDBox, + unsigned short iDV, bool ResetDef) const; /*! * \brief Set the deformation of the Free From box using the control point position. @@ -296,7 +300,8 @@ class CSurfaceMovement : public CGridMovement { * \param[in] iDV - Index of the design variable. * \param[in] ResetDef - Reset the deformation before starting a new one. */ - bool SetFFDCPChange(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox, CFreeFormDefBox **ResetFFDBox, unsigned short iDV, bool ResetDef) const; + bool SetFFDCPChange(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBox, CFreeFormDefBox** ResetFFDBox, + unsigned short iDV, bool ResetDef) const; /*! * \brief Set the deformation of the Free From box using the control point position. @@ -306,7 +311,8 @@ class CSurfaceMovement : public CGridMovement { * \param[in] iDV - Index of the design variable. * \param[in] ResetDef - Reset the deformation before starting a new one. */ - bool SetFFDGull(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox, CFreeFormDefBox **ResetFFDBox, unsigned short iDV, bool ResetDef) const; + bool SetFFDGull(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBox, CFreeFormDefBox** ResetFFDBox, + unsigned short iDV, bool ResetDef) const; /*! * \brief Set the deformation of the Free From box using the control point position. @@ -316,7 +322,8 @@ class CSurfaceMovement : public CGridMovement { * \param[in] iDV - Index of the design variable. * \param[in] ResetDef - Reset the deformation before starting a new one. */ - bool SetFFDNacelle(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox, CFreeFormDefBox **ResetFFDBox, unsigned short iDV, bool ResetDef) const; + bool SetFFDNacelle(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBox, CFreeFormDefBox** ResetFFDBox, + unsigned short iDV, bool ResetDef) const; /*! * \brief Set a camber deformation of the Free From box using the control point position. @@ -326,7 +333,8 @@ class CSurfaceMovement : public CGridMovement { * \param[in] iDV - Index of the design variable. * \param[in] ResetDef - Reset the deformation before starting a new one. */ - bool SetFFDCamber_2D(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox, CFreeFormDefBox **ResetFFDBox, unsigned short iDV, bool ResetDef) const; + bool SetFFDCamber_2D(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBox, CFreeFormDefBox** ResetFFDBox, + unsigned short iDV, bool ResetDef) const; /*! * \brief Set a camber deformation of the Free From box using the control point position. @@ -336,7 +344,8 @@ class CSurfaceMovement : public CGridMovement { * \param[in] iDV - Index of the design variable. * \param[in] ResetDef - Reset the deformation before starting a new one. */ - bool SetFFDTwist_2D(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox, CFreeFormDefBox **ResetFFDBox, unsigned short iDV, bool ResetDef); + bool SetFFDTwist_2D(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBox, CFreeFormDefBox** ResetFFDBox, + unsigned short iDV, bool ResetDef); /*! * \brief Set a thickness deformation of the Free From box using the control point position. @@ -346,7 +355,8 @@ class CSurfaceMovement : public CGridMovement { * \param[in] iDV - Index of the design variable. * \param[in] ResetDef - Reset the deformation before starting a new one. */ - bool SetFFDThickness_2D(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox, CFreeFormDefBox **ResetFFDBox, unsigned short iDV, bool ResetDef) const; + bool SetFFDThickness_2D(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBox, CFreeFormDefBox** ResetFFDBox, + unsigned short iDV, bool ResetDef) const; /*! * \brief Set a camber deformation of the Free From box using the control point position. @@ -356,7 +366,8 @@ class CSurfaceMovement : public CGridMovement { * \param[in] iDV - Index of the design variable. * \param[in] ResetDef - Reset the deformation before starting a new one. */ - bool SetFFDCamber(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox, CFreeFormDefBox **ResetFFDBox, unsigned short iDV, bool ResetDef) const; + bool SetFFDCamber(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBox, CFreeFormDefBox** ResetFFDBox, + unsigned short iDV, bool ResetDef) const; /*! * \brief Set a thickness deformation of the Free From box using the control point position. @@ -366,7 +377,8 @@ class CSurfaceMovement : public CGridMovement { * \param[in] iDV - Index of the design variable. * \param[in] ResetDef - Reset the deformation before starting a new one. */ - bool SetFFDThickness(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox, CFreeFormDefBox **ResetFFDBox, unsigned short iDV, bool ResetDef) const; + bool SetFFDThickness(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBox, CFreeFormDefBox** ResetFFDBox, + unsigned short iDV, bool ResetDef) const; /*! * \brief Set a thickness deformation of the Free From box using the control point position. @@ -376,7 +388,8 @@ class CSurfaceMovement : public CGridMovement { * \param[in] iDV - Index of the design variable. * \param[in] ResetDef - Reset the deformation before starting a new one. */ - void SetFFDAngleOfAttack(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox, CFreeFormDefBox **ResetFFDBox, unsigned short iDV, bool ResetDef); + void SetFFDAngleOfAttack(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBox, CFreeFormDefBox** ResetFFDBox, + unsigned short iDV, bool ResetDef); /*! * \brief Set a twist angle deformation of the Free From box using the control point position. @@ -386,7 +399,8 @@ class CSurfaceMovement : public CGridMovement { * \param[in] iDV - Index of the design variable. * \param[in] ResetDef - Reset the deformation before starting a new one. */ - bool SetFFDTwist(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox, CFreeFormDefBox **ResetFFDBox, unsigned short iDV, bool ResetDef) const; + bool SetFFDTwist(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBox, CFreeFormDefBox** ResetFFDBox, + unsigned short iDV, bool ResetDef) const; /*! * \brief Set a rotation angle deformation of the Free From box using the control point position. @@ -396,7 +410,8 @@ class CSurfaceMovement : public CGridMovement { * \param[in] iDV - Index of the design variable. * \param[in] ResetDef - Reset the deformation before starting a new one. */ - bool SetFFDRotation(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox,CFreeFormDefBox **ResetFFDBox, unsigned short iDV, bool ResetDef) const; + bool SetFFDRotation(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBox, CFreeFormDefBox** ResetFFDBox, + unsigned short iDV, bool ResetDef) const; /*! * \brief Set a rotation angle deformation in a control surface of the Free From box using the control point position. @@ -406,7 +421,8 @@ class CSurfaceMovement : public CGridMovement { * \param[in] iDV - Index of the design variable. * \param[in] ResetDef - Reset the deformation before starting a new one. */ - bool SetFFDControl_Surface(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox, CFreeFormDefBox **ResetFFDBox, unsigned short iDV, bool ResetDef) const; + bool SetFFDControl_Surface(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBox, + CFreeFormDefBox** ResetFFDBox, unsigned short iDV, bool ResetDef) const; /*! * \brief Read the free form information from the grid input file. @@ -417,7 +433,7 @@ class CSurfaceMovement : public CGridMovement { * \param[in] FFDBox - Array with all the free forms FFDBoxes of the computation. * \param[in] val_mesh_filename - Name of the grid input file. */ - void ReadFFDInfo(CGeometry *geometry, CConfig *config, CFreeFormDefBox **FFDBox, string val_mesh_filename); + void ReadFFDInfo(CGeometry* geometry, CConfig* config, CFreeFormDefBox** FFDBox, string val_mesh_filename); /*! * \brief Read the free form information from the grid input file. @@ -427,7 +443,7 @@ class CSurfaceMovement : public CGridMovement { * \param[in] geometry - Geometrical definition of the problem. * \param[in] FFDBox - Array with all the free forms FFDBoxes of the computation. */ - void ReadFFDInfo(CGeometry *geometry, CConfig *config, CFreeFormDefBox **FFDBox); + void ReadFFDInfo(CGeometry* geometry, CConfig* config, CFreeFormDefBox** FFDBox); /*! * \brief Merge the Free Form information in the SU2 file. @@ -435,7 +451,7 @@ class CSurfaceMovement : public CGridMovement { * \param[in] geometry - Geometrical definition of the problem. * \param[in] val_mesh_filename - Name of the grid output file. */ - void MergeFFDInfo(CGeometry *geometry, CConfig *config); + void MergeFFDInfo(CGeometry* geometry, CConfig* config); /*! * \brief Write the Free Form information in the SU2 file. @@ -443,7 +459,7 @@ class CSurfaceMovement : public CGridMovement { * \param[in] geometry - Geometrical definition of the problem. * \param[in] val_mesh_filename - Name of the grid output file. */ - void WriteFFDInfo(CSurfaceMovement **surface_movement, CGeometry ****geometry, CConfig **config); + void WriteFFDInfo(CSurfaceMovement** surface_movement, CGeometry**** geometry, CConfig** config); /*! * \brief Get information about if there is a complete FFDBox definition, or it is necessary to @@ -459,14 +475,15 @@ class CSurfaceMovement : public CGridMovement { * \return TRUE if the FFD box name referenced with DV_PARAM can be found in the FFD box definition; * otherwise FALSE. */ - inline bool CheckFFDBoxDefinition(CConfig *config, unsigned short iDV) { + inline bool CheckFFDBoxDefinition(CConfig* config, unsigned short iDV) { for (unsigned short iFFDBox = 0; iFFDBox < GetnFFDBox(); iFFDBox++) { - if (FFDBox[iFFDBox]->GetTag() == config->GetFFDTag(iDV)) { return true;} + if (FFDBox[iFFDBox]->GetTag() == config->GetFFDTag(iDV)) { + return true; + } } return false; } - /*! * \brief Obtain the number of FFDBoxes. * \return Number of FFD FFDBoxes. @@ -484,7 +501,7 @@ class CSurfaceMovement : public CGridMovement { * \param[in] geometry - Geometrical definition of the problem. * \param[in] config - Definition of the particular problem. */ - void SetSurface_Derivative(CGeometry *geometry, CConfig *config); + void SetSurface_Derivative(CGeometry* geometry, CConfig* config); /*! * \brief Calculate the determinant of the Jacobian matrix for the FFD problem. @@ -493,5 +510,5 @@ class CSurfaceMovement : public CGridMovement { * \param[in] FFDBox - Free form deformation box. * \return Number of points with negative Jacobian determinant. */ - unsigned long calculateJacobianDeterminant(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox) const; + unsigned long calculateJacobianDeterminant(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBox) const; }; diff --git a/Common/include/grid_movement/CVolumetricMovement.hpp b/Common/include/grid_movement/CVolumetricMovement.hpp index 0a1503f6402..489f330d792 100644 --- a/Common/include/grid_movement/CVolumetricMovement.hpp +++ b/Common/include/grid_movement/CVolumetricMovement.hpp @@ -38,28 +38,26 @@ * \author F. Palacios, A. Bueno, T. Economon, S. Padron. */ class CVolumetricMovement : public CGridMovement { -protected: + protected: + unsigned short nDim; /*!< \brief Number of dimensions. */ + unsigned short nVar; /*!< \brief Number of variables. */ - unsigned short nDim; /*!< \brief Number of dimensions. */ - unsigned short nVar; /*!< \brief Number of variables. */ + unsigned long nPoint; /*!< \brief Number of points. */ + unsigned long nPointDomain; /*!< \brief Number of points in the domain. */ - unsigned long nPoint; /*!< \brief Number of points. */ - unsigned long nPointDomain; /*!< \brief Number of points in the domain. */ - - unsigned long nIterMesh; /*!< \brief Number of iterations in the mesh update. +*/ + unsigned long nIterMesh; /*!< \brief Number of iterations in the mesh update. +*/ #ifndef CODI_FORWARD_TYPE CSysMatrix StiffMatrix; /*!< \brief Stiffness matrix of the elasticity problem. */ - CSysSolve System; /*!< \brief Linear solver/smoother. */ + CSysSolve System; /*!< \brief Linear solver/smoother. */ #else CSysMatrix StiffMatrix; - CSysSolve System; + CSysSolve System; #endif CSysVector LinSysSol; CSysVector LinSysRes; -public: - + public: /*! * \brief Constructor of the class. */ @@ -68,7 +66,7 @@ class CVolumetricMovement : public CGridMovement { /*! * \brief Constructor of the class. */ - CVolumetricMovement(CGeometry *geometry, CConfig *config); + CVolumetricMovement(CGeometry* geometry, CConfig* config); /*! * \brief Destructor of the class. @@ -80,21 +78,21 @@ class CVolumetricMovement : public CGridMovement { * \param[in] geometry - Geometrical definition of the problem. * \param[in] config - Definition of the particular problem. */ - void UpdateGridCoord(CGeometry *geometry, CConfig *config); + void UpdateGridCoord(CGeometry* geometry, CConfig* config); /*! * \brief Update the dual grid after the grid movement (edges and control volumes). * \param[in] geometry - Geometrical definition of the problem. * \param[in] config - Definition of the particular problem. */ - void UpdateDualGrid(CGeometry *geometry, CConfig *config); + void UpdateDualGrid(CGeometry* geometry, CConfig* config); /*! * \brief Update the coarse multigrid levels after the grid movement. * \param[in] geometry - Geometrical definition of the problem. * \param[in] config - Definition of the particular problem. */ - void UpdateMultiGrid(CGeometry **geometry, CConfig *config); + void UpdateMultiGrid(CGeometry** geometry, CConfig* config); /*! * \brief Compute the stiffness matrix for grid deformation using spring analogy. @@ -102,7 +100,7 @@ class CVolumetricMovement : public CGridMovement { * \param[in] config - Definition of the particular problem. * \return Value of the length of the smallest edge of the grid. */ - su2double SetFEAMethodContributions_Elem(CGeometry *geometry, CConfig *config); + su2double SetFEAMethodContributions_Elem(CGeometry* geometry, CConfig* config); /*! * \brief Build the stiffness matrix for a 3-D hexahedron element. The result will be placed in StiffMatrix_Elem. @@ -114,8 +112,9 @@ class CVolumetricMovement : public CGridMovement { * \param[in] nNodes - Number of nodes defining the element. * \param[in] scale */ - void SetFEA_StiffMatrix3D(CGeometry *geometry, CConfig *config, su2double **StiffMatrix_Elem, unsigned long PointCorners[8], su2double CoordCorners[8][3], - unsigned short nNodes, su2double ElemVolume, su2double ElemDistance); + void SetFEA_StiffMatrix3D(CGeometry* geometry, CConfig* config, su2double** StiffMatrix_Elem, + unsigned long PointCorners[8], su2double CoordCorners[8][3], unsigned short nNodes, + su2double ElemVolume, su2double ElemDistance); /*! * \brief Build the stiffness matrix for a 3-D hexahedron element. The result will be placed in StiffMatrix_Elem. @@ -127,8 +126,9 @@ class CVolumetricMovement : public CGridMovement { * \param[in] nNodes - Number of nodes defining the element. * \param[in] scale */ - void SetFEA_StiffMatrix2D(CGeometry *geometry, CConfig *config, su2double **StiffMatrix_Elem, unsigned long PointCorners[8], su2double CoordCorners[8][3], - unsigned short nNodes, su2double ElemVolume, su2double ElemDistance); + void SetFEA_StiffMatrix2D(CGeometry* geometry, CConfig* config, su2double** StiffMatrix_Elem, + unsigned long PointCorners[8], su2double CoordCorners[8][3], unsigned short nNodes, + su2double ElemVolume, su2double ElemDistance); /*! * \brief Shape functions and derivative of the shape functions @@ -138,7 +138,8 @@ class CVolumetricMovement : public CGridMovement { * \param[in] CoordCorners - Coordiantes of the corners. * \param[in] DShapeFunction - Shape function information */ - su2double ShapeFunc_Hexa(su2double Xi, su2double Eta, su2double Zeta, su2double CoordCorners[8][3], su2double DShapeFunction[8][4]); + su2double ShapeFunc_Hexa(su2double Xi, su2double Eta, su2double Zeta, su2double CoordCorners[8][3], + su2double DShapeFunction[8][4]); /*! * \brief Shape functions and derivative of the shape functions @@ -148,7 +149,8 @@ class CVolumetricMovement : public CGridMovement { * \param[in] CoordCorners - Coordiantes of the corners. * \param[in] DShapeFunction - Shape function information */ - su2double ShapeFunc_Tetra(su2double Xi, su2double Eta, su2double Zeta, su2double CoordCorners[8][3], su2double DShapeFunction[8][4]); + su2double ShapeFunc_Tetra(su2double Xi, su2double Eta, su2double Zeta, su2double CoordCorners[8][3], + su2double DShapeFunction[8][4]); /*! * \brief Shape functions and derivative of the shape functions @@ -158,7 +160,8 @@ class CVolumetricMovement : public CGridMovement { * \param[in] CoordCorners - Coordiantes of the corners. * \param[in] DShapeFunction - Shape function information */ - su2double ShapeFunc_Pyram(su2double Xi, su2double Eta, su2double Zeta, su2double CoordCorners[8][3], su2double DShapeFunction[8][4]); + su2double ShapeFunc_Pyram(su2double Xi, su2double Eta, su2double Zeta, su2double CoordCorners[8][3], + su2double DShapeFunction[8][4]); /*! * \brief Shape functions and derivative of the shape functions @@ -168,7 +171,8 @@ class CVolumetricMovement : public CGridMovement { * \param[in] CoordCorners - Coordiantes of the corners. * \param[in] DShapeFunction - Shape function information */ - su2double ShapeFunc_Prism(su2double Xi, su2double Eta, su2double Zeta, su2double CoordCorners[8][3], su2double DShapeFunction[8][4]); + su2double ShapeFunc_Prism(su2double Xi, su2double Eta, su2double Zeta, su2double CoordCorners[8][3], + su2double DShapeFunction[8][4]); /*! * \brief Shape functions and derivative of the shape functions @@ -177,7 +181,8 @@ class CVolumetricMovement : public CGridMovement { * \param[in] CoordCorners - Coordiantes of the corners. * \param[in] DShapeFunction - Shape function information */ - su2double ShapeFunc_Triangle(su2double Xi, su2double Eta, su2double CoordCorners[8][3], su2double DShapeFunction[8][4]); + su2double ShapeFunc_Triangle(su2double Xi, su2double Eta, su2double CoordCorners[8][3], + su2double DShapeFunction[8][4]); /*! * \brief Shape functions and derivative of the shape functions @@ -186,7 +191,8 @@ class CVolumetricMovement : public CGridMovement { * \param[in] CoordCorners - Coordiantes of the corners. * \param[in] DShapeFunction - Shape function information */ - su2double ShapeFunc_Quadrilateral(su2double Xi, su2double Eta, su2double CoordCorners[8][3], su2double DShapeFunction[8][4]); + su2double ShapeFunc_Quadrilateral(su2double Xi, su2double Eta, su2double CoordCorners[8][3], + su2double DShapeFunction[8][4]); /*! * \brief Compute the shape functions for hexahedron @@ -225,49 +231,50 @@ class CVolumetricMovement : public CGridMovement { su2double GetQuadrilateral_Area(su2double CoordCorners[8][3]) const; /*! - * \brief Add the stiffness matrix for a 2-D triangular element to the global stiffness matrix for the entire mesh (node-based). - * \param[in] geometry - Geometrical definition of the problem. - * \param[in] StiffMatrix_Elem - Element stiffness matrix to be filled. - * \param[in] PointCorners - Index values for element corners - * \param[in] nNodes - Number of nodes defining the element. + * \brief Add the stiffness matrix for a 2-D triangular element to the global stiffness matrix for the entire mesh + * (node-based). \param[in] geometry - Geometrical definition of the problem. \param[in] StiffMatrix_Elem - Element + * stiffness matrix to be filled. \param[in] PointCorners - Index values for element corners \param[in] nNodes - + * Number of nodes defining the element. */ - void AddFEA_StiffMatrix(CGeometry *geometry, su2double **StiffMatrix_Elem, unsigned long PointCorners[8], unsigned short nNodes); + void AddFEA_StiffMatrix(CGeometry* geometry, su2double** StiffMatrix_Elem, unsigned long PointCorners[8], + unsigned short nNodes); /*! * \brief Check for negative volumes (all elements) after performing grid deformation. * \param[in] geometry - Geometrical definition of the problem. * \param[in] Screen_Output - determines if text is written to screen */ - void ComputeDeforming_Element_Volume(CGeometry *geometry, su2double &MinVolume, su2double &MaxVolume, bool Screen_Output); + void ComputeDeforming_Element_Volume(CGeometry* geometry, su2double& MinVolume, su2double& MaxVolume, + bool Screen_Output); /*! * \brief Compute amount of nonconvex elements * \param[in] geometry - Geometrical definition of the problem. * \param[in] Screen_Output - determines if text is written to screen */ - void ComputenNonconvexElements(CGeometry *geometry, bool Screen_Output); - + void ComputenNonconvexElements(CGeometry* geometry, bool Screen_Output); /*! * \brief Compute the minimum distance to the nearest solid surface. * \param[in] geometry - Geometrical definition of the problem. * \param[in] config - Definition of the particular problem. */ - void ComputeSolid_Wall_Distance(CGeometry *geometry, CConfig *config, su2double &MinDistance, su2double &MaxDistance) const; + void ComputeSolid_Wall_Distance(CGeometry* geometry, CConfig* config, su2double& MinDistance, + su2double& MaxDistance) const; /*! * \brief Check the boundary vertex that are going to be moved. * \param[in] geometry - Geometrical definition of the problem. * \param[in] config - Definition of the particular problem. */ - void SetBoundaryDisplacements(CGeometry *geometry, CConfig *config); + void SetBoundaryDisplacements(CGeometry* geometry, CConfig* config); /*! * \brief Check the domain points vertex that are going to be moved. * \param[in] geometry - Geometrical definition of the problem. * \param[in] config - Definition of the particular problem. */ - void SetDomainDisplacements(CGeometry *geometry, CConfig *config); + void SetDomainDisplacements(CGeometry* geometry, CConfig* config); /*! * \brief Unsteady grid movement using rigid mesh rotation. @@ -276,7 +283,7 @@ class CVolumetricMovement : public CGridMovement { * \param[in] iZone - Zone number in the mesh. * \param[in] iter - Physical time iteration number. */ - void Rigid_Rotation(CGeometry *geometry, CConfig *config, unsigned short iZone, unsigned long iter); + void Rigid_Rotation(CGeometry* geometry, CConfig* config, unsigned short iZone, unsigned long iter); /*! * \brief Unsteady pitching grid movement using rigid mesh motion. @@ -285,7 +292,7 @@ class CVolumetricMovement : public CGridMovement { * \param[in] iZone - Zone number in the mesh. * \param[in] iter - Physical time iteration number. */ - void Rigid_Pitching(CGeometry *geometry, CConfig *config, unsigned short iZone, unsigned long iter); + void Rigid_Pitching(CGeometry* geometry, CConfig* config, unsigned short iZone, unsigned long iter); /*! * \brief Unsteady plunging grid movement using rigid mesh motion. @@ -294,7 +301,7 @@ class CVolumetricMovement : public CGridMovement { * \param[in] iZone - Zone number in the mesh. * \param[in] iter - Physical time iteration number. */ - void Rigid_Plunging(CGeometry *geometry, CConfig *config, unsigned short iZone, unsigned long iter); + void Rigid_Plunging(CGeometry* geometry, CConfig* config, unsigned short iZone, unsigned long iter); /*! * \brief Unsteady translational grid movement using rigid mesh motion. @@ -303,7 +310,7 @@ class CVolumetricMovement : public CGridMovement { * \param[in] iZone - Zone number in the mesh. * \param[in] iter - Physical time iteration number. */ - void Rigid_Translation(CGeometry *geometry, CConfig *config, unsigned short iZone, unsigned long iter); + void Rigid_Translation(CGeometry* geometry, CConfig* config, unsigned short iZone, unsigned long iter); /*! * \brief Scale the volume grid by a multiplicative factor. @@ -311,7 +318,7 @@ class CVolumetricMovement : public CGridMovement { * \param[in] config - Definition of the particular problem. * \param[in] UpdateGeo - Update geometry. */ - void SetVolume_Scaling(CGeometry *geometry, CConfig *config, bool UpdateGeo); + void SetVolume_Scaling(CGeometry* geometry, CConfig* config, bool UpdateGeo); /*! * \brief Translate the volume grid by a specified displacement vector. @@ -319,7 +326,7 @@ class CVolumetricMovement : public CGridMovement { * \param[in] config - Definition of the particular problem. * \param[in] UpdateGeo - Update geometry. */ - void SetVolume_Translation(CGeometry *geometry, CConfig *config, bool UpdateGeo); + void SetVolume_Translation(CGeometry* geometry, CConfig* config, bool UpdateGeo); /*! * \brief Rotate the volume grid around a specified axis and angle. @@ -327,7 +334,7 @@ class CVolumetricMovement : public CGridMovement { * \param[in] config - Definition of the particular problem. * \param[in] UpdateGeo - Update geometry. */ - void SetVolume_Rotation(CGeometry *geometry, CConfig *config, bool UpdateGeo); + void SetVolume_Rotation(CGeometry* geometry, CConfig* config, bool UpdateGeo); /*! * \brief Grid deformation using the spring analogy method. @@ -336,7 +343,8 @@ class CVolumetricMovement : public CGridMovement { * \param[in] UpdateGeo - Update geometry. * \param[in] Derivative - Compute the derivative (disabled by default). Does not actually deform the grid if enabled. */ - void SetVolume_Deformation(CGeometry *geometry, CConfig *config, bool UpdateGeo, bool Derivative = false, bool ForwardProjectionDerivative = false); + void SetVolume_Deformation(CGeometry* geometry, CConfig* config, bool UpdateGeo, bool Derivative = false, + bool ForwardProjectionDerivative = false); /*! * \brief Grid deformation using the spring analogy method. @@ -345,21 +353,22 @@ class CVolumetricMovement : public CGridMovement { * \param[in] UpdateGeo - Update geometry. * \param[in] Derivative - Compute the derivative (disabled by default). Does not actually deform the grid if enabled. */ - inline virtual void SetVolume_Deformation_Elas(CGeometry *geometry, CConfig *config, bool UpdateGeo, bool screen_output, bool Derivative = false) { } + inline virtual void SetVolume_Deformation_Elas(CGeometry* geometry, CConfig* config, bool UpdateGeo, + bool screen_output, bool Derivative = false) {} /*! * \brief Set the derivatives of the boundary nodes. * \param[in] geometry - Geometrical definition of the problem. * \param[in] config - Definition of the particular problem. */ - void SetBoundaryDerivatives(CGeometry *geometry, CConfig *config, bool ForwardProjectionDerivative); + void SetBoundaryDerivatives(CGeometry* geometry, CConfig* config, bool ForwardProjectionDerivative); /*! * \brief Update the derivatives of the coordinates after the grid movement. * \param[in] geometry - Geometrical definition of the problem. * \param[in] config - Definition of the particular problem. */ - void UpdateGridCoord_Derivatives(CGeometry *geometry, CConfig *config, bool ForwardProjectionDerivative); + void UpdateGridCoord_Derivatives(CGeometry* geometry, CConfig* config, bool ForwardProjectionDerivative); /*! * \brief Store the number of iterations when moving the mesh. @@ -378,5 +387,5 @@ class CVolumetricMovement : public CGridMovement { * \param[in] geometry - Geometrical definition of the problem. * \param[in] config - Definition of the particular problem. */ - inline virtual void Boundary_Dependencies(CGeometry **geometry, CConfig *config) { } + inline virtual void Boundary_Dependencies(CGeometry** geometry, CConfig* config) {} }; diff --git a/Common/include/interface_interpolation/CInterpolator.hpp b/Common/include/interface_interpolation/CInterpolator.hpp index 5d953f14255..e3853ae91d9 100644 --- a/Common/include/interface_interpolation/CInterpolator.hpp +++ b/Common/include/interface_interpolation/CInterpolator.hpp @@ -45,46 +45,47 @@ using namespace std; * \author H. Kline */ class CInterpolator { -protected: + protected: const int rank; /*!< \brief MPI Rank. */ const int size; /*!< \brief MPI Size. */ const unsigned donorZone; /*!< \brief Index of donor zone. */ const unsigned targetZone; /*!< \brief Index of target zone. */ - unsigned long - MaxLocalVertex_Donor, /*!< \brief Maximum vertices per processor. */ - Buffer_Send_nVertex_Donor[1], /*!< \brief Buffer to send number of vertices on the local processor. */ - *Buffer_Receive_nVertex_Donor; /*!< \brief Buffer to store the number of vertices per processor on the Donor domain. */ + unsigned long MaxLocalVertex_Donor, /*!< \brief Maximum vertices per processor. */ + Buffer_Send_nVertex_Donor[1], /*!< \brief Buffer to send number of vertices on the local processor. */ + *Buffer_Receive_nVertex_Donor; /*!< \brief Buffer to store the number of vertices per processor on the Donor + domain. */ - su2vector Buffer_Send_GlobalPoint; /*!< \brief Buffer to send global point indices. */ - su2vector Buffer_Receive_GlobalPoint; /*!< \brief Buffer to receive global point indices. */ + su2vector Buffer_Send_GlobalPoint; /*!< \brief Buffer to send global point indices. */ + su2vector Buffer_Receive_GlobalPoint; /*!< \brief Buffer to receive global point indices. */ - su2activematrix Buffer_Send_Coord; /*!< \brief Buffer to send coordinate values. */ - su2activematrix Buffer_Receive_Coord; /*!< \brief Buffer to receive coordinate values. */ + su2activematrix Buffer_Send_Coord; /*!< \brief Buffer to send coordinate values. */ + su2activematrix Buffer_Receive_Coord; /*!< \brief Buffer to receive coordinate values. */ /*! \brief Buffer to receive the number of surface-connected edges, for each vertex. */ su2vector Buffer_Receive_nLinkedNodes; - /*! \brief Buffer to receive the index of the Receive_LinkedNodes buffer where corresponding list of linked nodes begins. */ + /*! \brief Buffer to receive the index of the Receive_LinkedNodes buffer where corresponding list of linked nodes + * begins. */ su2vector Buffer_Receive_StartLinkedNodes; /*! \brief Buffer to receive the list of surface-connected nodes, for each vertex. - * \details The vertices are ordered as in Buffer_Receive_nLinkedNodes and Buffer_Receive_StartLinkedNodes, but for each*/ + * \details The vertices are ordered as in Buffer_Receive_nLinkedNodes and Buffer_Receive_StartLinkedNodes, but for + * each*/ su2vector Buffer_Receive_LinkedNodes; /*! \brief Buffer to receive the rank that owns the vertex. */ su2vector Buffer_Receive_Proc; - unsigned long - nGlobalVertex_Target, /*!< \brief Global number of vertex of the target boundary. */ - nLocalVertex_Target, /*!< \brief Number of vertex of the target boundary owned by the thread. */ - nGlobalVertex_Donor, /*!< \brief Global number of vertex of the donor boundary. */ - nLocalVertex_Donor, /*!< \brief Number of vertex of the donor boundary owned by the thread. */ - nGlobalVertex, /*!< \brief Dummy variable to temporarily store the global number of vertex of a boundary. */ - nLocalLinkedNodes; /*!< \brief Dummy variable to temporarily store the number of vertex of a boundary. */ + unsigned long nGlobalVertex_Target, /*!< \brief Global number of vertex of the target boundary. */ + nLocalVertex_Target, /*!< \brief Number of vertex of the target boundary owned by the thread. */ + nGlobalVertex_Donor, /*!< \brief Global number of vertex of the donor boundary. */ + nLocalVertex_Donor, /*!< \brief Number of vertex of the donor boundary owned by the thread. */ + nGlobalVertex, /*!< \brief Dummy variable to temporarily store the global number of vertex of a boundary. */ + nLocalLinkedNodes; /*!< \brief Dummy variable to temporarily store the number of vertex of a boundary. */ - CGeometry**** const Geometry; /*! \brief Vector which stores n zones of geometry. */ - CGeometry* const donor_geometry; /*! \brief Donor geometry. */ - CGeometry* const target_geometry; /*! \brief Target geometry. */ + CGeometry**** const Geometry; /*! \brief Vector which stores n zones of geometry. */ + CGeometry* const donor_geometry; /*! \brief Donor geometry. */ + CGeometry* const target_geometry; /*! \brief Target geometry. */ -public: + public: struct CDonorInfo { vector processor; vector globalPoint; @@ -107,8 +108,7 @@ class CInterpolator { * \param[in] iZone - index of the donor zone. * \param[in] jZone - index of the target zone. */ - CInterpolator(CGeometry ****geometry_container, const CConfig* const* config, - unsigned int iZone, unsigned int jZone); + CInterpolator(CGeometry**** geometry_container, const CConfig* const* config, unsigned int iZone, unsigned int jZone); /*! * \brief No default construction allowed to force zones and geometry to always be set. @@ -130,7 +130,7 @@ class CInterpolator { /*! * \brief Print information about the interpolation. */ - virtual void PrintStatistics(void) const { } + virtual void PrintStatistics(void) const {} /*! * \brief Check whether an interface should be processed or not, i.e. if it is part of the zones. @@ -146,7 +146,7 @@ class CInterpolator { */ static bool CheckZonesInterface(const CConfig* donor, const CConfig* target); -protected: + protected: /*! * \brief Reconstruct the boundary connectivity from parallel partitioning and broadcasts it to all threads. * \param[in] val_zone - index of the zone diff --git a/Common/include/interface_interpolation/CInterpolatorFactory.hpp b/Common/include/interface_interpolation/CInterpolatorFactory.hpp index a9749015ec1..f5382127232 100644 --- a/Common/include/interface_interpolation/CInterpolatorFactory.hpp +++ b/Common/include/interface_interpolation/CInterpolatorFactory.hpp @@ -41,9 +41,7 @@ namespace CInterpolatorFactory { * \param[in] verbose - If true, print information to screen. * \return Pointer to interpolator on the heap, caller is responsible for deletion. */ -CInterpolator* CreateInterpolator(CGeometry ****geometry_container, - const CConfig* const* config, - const CInterpolator* transpInterpolator, - unsigned iZone, unsigned jZone, +CInterpolator* CreateInterpolator(CGeometry**** geometry_container, const CConfig* const* config, + const CInterpolator* transpInterpolator, unsigned iZone, unsigned jZone, bool verbose = true); -} +} // namespace CInterpolatorFactory diff --git a/Common/include/interface_interpolation/CIsoparametric.hpp b/Common/include/interface_interpolation/CIsoparametric.hpp index 7584e61c505..7f1fc5e591a 100644 --- a/Common/include/interface_interpolation/CIsoparametric.hpp +++ b/Common/include/interface_interpolation/CIsoparametric.hpp @@ -33,23 +33,23 @@ * \ingroup Interfaces */ class CIsoparametric final : public CInterpolator { -private: + private: /*--- Statistics. ---*/ su2double MaxDistance = 0.0, ErrorRate = 0.0; unsigned long ErrorCounter = 0; /*! \brief Helper struct to store information about candidate donor elements. */ struct DonorInfo { - su2double isoparams[4] = {0.0}; /*!< \brief Interpolation coefficients. */ - su2double distance = 0.0; /*!< \brief Distance from target to final mapped point on donor plane. */ - unsigned iElem = 0; /*!< \brief Identification of the element. */ - int error = 0; /*!< \brief If the mapped point is "outside" of the donor. */ + su2double isoparams[4] = {0.0}; /*!< \brief Interpolation coefficients. */ + su2double distance = 0.0; /*!< \brief Distance from target to final mapped point on donor plane. */ + unsigned iElem = 0; /*!< \brief Identification of the element. */ + int error = 0; /*!< \brief If the mapped point is "outside" of the donor. */ /*--- Best donor is one for which the mapped point is closest to target. ---*/ - bool operator< (const DonorInfo& other) const { return distance < other.distance; } + bool operator<(const DonorInfo& other) const { return distance < other.distance; } }; -public: + public: /*! * \brief Constructor of the class. * \param[in] geometry - Geometrical definition of the problem. @@ -57,8 +57,8 @@ class CIsoparametric final : public CInterpolator { * \param[in] iZone - index of the donor zone. * \param[in] jZone - index of the target zone. */ - CIsoparametric(CGeometry ****geometry_container, const CConfig* const* config, - unsigned int iZone, unsigned int jZone); + CIsoparametric(CGeometry**** geometry_container, const CConfig* const* config, unsigned int iZone, + unsigned int jZone); /*! * \brief Set up transfer matrix defining relation between two meshes @@ -71,7 +71,7 @@ class CIsoparametric final : public CInterpolator { */ void PrintStatistics(void) const override; -private: + private: /*! * \brief Compute the isoparametric interpolation coefficients for a 2D line element. * \param[in] X - Coordinate matrix defining the line. @@ -79,7 +79,7 @@ class CIsoparametric final : public CInterpolator { * \param[out] isoparams - Isoparametric coefficients. * \return 0 on success, 1 if xj is too far outside element bounds. */ - static int LineIsoparameters(const su2double X[][3], const su2double *xj, su2double* isoparams); + static int LineIsoparameters(const su2double X[][3], const su2double* xj, su2double* isoparams); /*! * \brief Compute the isoparametric interpolation coefficients for a 3D triangle element. @@ -88,7 +88,7 @@ class CIsoparametric final : public CInterpolator { * \param[out] isoparams - Isoparametric coefficients. * \return 0 on success, 1 if xj is too far outside element bounds. */ - static int TriangleIsoparameters(const su2double X[][3], const su2double *xj, su2double* isoparams); + static int TriangleIsoparameters(const su2double X[][3], const su2double* xj, su2double* isoparams); /*! * \brief Compute the isoparametric interpolation coefficients for a 3D quadrilateral element. @@ -97,6 +97,5 @@ class CIsoparametric final : public CInterpolator { * \param[out] isoparams - Isoparametric coefficients. * \return 0 on success, 1 if xj is too far outside element bounds. */ - static int QuadrilateralIsoparameters(const su2double X[][3], const su2double *xj, su2double* isoparams); - + static int QuadrilateralIsoparameters(const su2double X[][3], const su2double* xj, su2double* isoparams); }; diff --git a/Common/include/interface_interpolation/CMirror.hpp b/Common/include/interface_interpolation/CMirror.hpp index a23626b852f..c514d2097a6 100644 --- a/Common/include/interface_interpolation/CMirror.hpp +++ b/Common/include/interface_interpolation/CMirror.hpp @@ -34,10 +34,10 @@ * \ingroup Interfaces */ class CMirror final : public CInterpolator { -private: + private: const CInterpolator* const transpInterpolator; /*! \brief The transpose interpolator (from j to i). */ -public: + public: /*! * \brief Constructor of the class. * \note Data is set in geometry[targetZone]. @@ -47,13 +47,12 @@ class CMirror final : public CInterpolator { * \param[in] iZone - First zone * \param[in] jZone - Second zone */ - CMirror(CGeometry ****geometry_container, const CConfig* const* config, - const CInterpolator* interpolator, unsigned int iZone, unsigned int jZone); + CMirror(CGeometry**** geometry_container, const CConfig* const* config, const CInterpolator* interpolator, + unsigned int iZone, unsigned int jZone); /*! * \brief Set up transfer matrix defining relation between two meshes * \param[in] config - Definition of the particular problem. */ void SetTransferCoeff(const CConfig* const* config) override; - }; diff --git a/Common/include/interface_interpolation/CNearestNeighbor.hpp b/Common/include/interface_interpolation/CNearestNeighbor.hpp index be97794c60f..14c12a08e07 100644 --- a/Common/include/interface_interpolation/CNearestNeighbor.hpp +++ b/Common/include/interface_interpolation/CNearestNeighbor.hpp @@ -36,7 +36,7 @@ * \ingroup Interfaces */ class CNearestNeighbor final : public CInterpolator { -private: + private: su2double AvgDistance = 0.0, MaxDistance = 0.0; /*! \brief Helper struct to (partially) sort neighbours according to distance while @@ -45,10 +45,10 @@ class CNearestNeighbor final : public CInterpolator { su2double dist; unsigned pidx; int proc; - DonorInfo(su2double d = 0.0, unsigned i = 0, int p = 0) : dist(d), pidx(i), proc(p) { } + DonorInfo(su2double d = 0.0, unsigned i = 0, int p = 0) : dist(d), pidx(i), proc(p) {} }; -public: + public: /*! * \brief Constructor of the class. * \param[in] geometry - Geometrical definition of the problem. @@ -56,8 +56,8 @@ class CNearestNeighbor final : public CInterpolator { * \param[in] iZone - index of the donor zone. * \param[in] jZone - index of the target zone. */ - CNearestNeighbor(CGeometry ****geometry_container, const CConfig* const* config, - unsigned int iZone, unsigned int jZone); + CNearestNeighbor(CGeometry**** geometry_container, const CConfig* const* config, unsigned int iZone, + unsigned int jZone); /*! * \brief Set up transfer matrix defining relation between two meshes. @@ -69,5 +69,4 @@ class CNearestNeighbor final : public CInterpolator { * \brief Print interpolation statistics. */ void PrintStatistics(void) const override; - }; diff --git a/Common/include/interface_interpolation/CRadialBasisFunction.hpp b/Common/include/interface_interpolation/CRadialBasisFunction.hpp index 2c65cca5f18..601c96a232e 100644 --- a/Common/include/interface_interpolation/CRadialBasisFunction.hpp +++ b/Common/include/interface_interpolation/CRadialBasisFunction.hpp @@ -36,11 +36,12 @@ */ class CRadialBasisFunction final : public CInterpolator { static_assert(su2passivematrix::IsRowMajor, "This class relies on row major storage throughout."); -private: + + private: unsigned long MinDonors = 0, AvgDonors = 0, MaxDonors = 0; passivedouble Density = 0.0, AvgCorrection = 0.0, MaxCorrection = 0.0; -public: + public: /*! * \brief Constructor of the class. * \param[in] geometry - Geometrical definition of the problem. @@ -48,8 +49,8 @@ class CRadialBasisFunction final : public CInterpolator { * \param[in] iZone - index of the donor zone. * \param[in] jZone - index of the target zone. */ - CRadialBasisFunction(CGeometry ****geometry_container, const CConfig* const* config, - unsigned int iZone, unsigned int jZone); + CRadialBasisFunction(CGeometry**** geometry_container, const CConfig* const* config, unsigned int iZone, + unsigned int jZone); /*! * \brief Set up transfer matrix defining relation between two meshes @@ -85,8 +86,8 @@ class CRadialBasisFunction final : public CInterpolator { * \param[out] C_inv_trunc - The generator matrix as described above. */ static void ComputeGeneratorMatrix(RADIAL_BASIS type, bool usePolynomial, su2double radius, - const su2activematrix& coords, int& nPolynomial, - vector& keepPolynomialRow, su2passivematrix& C_inv_trunc); + const su2activematrix& coords, int& nPolynomial, vector& keepPolynomialRow, + su2passivematrix& C_inv_trunc); /*! * \brief If the polynomial term is included in the interpolation, and the points lie on a plane, the matrix @@ -97,9 +98,9 @@ class CRadialBasisFunction final : public CInterpolator { * \param[in,out] P - Polynomial part of the interpolation matrix, one row may be eliminated. * \return n_polynomial - Size of the polynomial part on exit (in practice nDim or nDim-1). */ - static int CheckPolynomialTerms(su2double max_diff_tol, vector& keep_row, su2passivematrix &P); + static int CheckPolynomialTerms(su2double max_diff_tol, vector& keep_row, su2passivematrix& P); -private: + private: /*! * \brief Helper function, prunes (by setting to zero) small interpolation coefficients, * i.e. <= tolerance*max(abs(coeffs)). The vector is re-scaled such that sum(coeffs)==1. @@ -108,25 +109,24 @@ class CRadialBasisFunction final : public CInterpolator { * \param[in,out] coeffs - Iterator to start of vector of interpolation coefficients. * \return Number of non-zero coefficients after pruning and correction factor. */ - template - static pair PruneSmallCoefficients(Float tolerance, Int size, ForwardIt coeffs) { - + template + static pair PruneSmallCoefficients(Float tolerance, Int size, ForwardIt coeffs) { /*--- Determine the pruning threshold. ---*/ Float thresh = 0.0; auto end = coeffs; - for (Int i = 0; i < size; ++i) - thresh = max(thresh, fabs(*(end++))); + for (Int i = 0; i < size; ++i) thresh = max(thresh, fabs(*(end++))); thresh *= tolerance; /*--- Prune and count non-zeros. ---*/ Int numNonZeros = 0; Float coeffSum = 0.0; for (auto it = coeffs; it != end; ++it) { - if (fabs(*it) > thresh) { // keep + if (fabs(*it) > thresh) { // keep coeffSum += *it; ++numNonZeros; - } - else { *it = 0.0; } // prune + } else { + *it = 0.0; + } // prune } /*--- Correct remaining coefficients, sum must be 1 for conservation. ---*/ @@ -135,5 +135,4 @@ class CRadialBasisFunction final : public CInterpolator { return make_pair(numNonZeros, correction); } - }; diff --git a/Common/include/interface_interpolation/CSlidingMesh.hpp b/Common/include/interface_interpolation/CSlidingMesh.hpp index b07dcef36f4..571948870ff 100644 --- a/Common/include/interface_interpolation/CSlidingMesh.hpp +++ b/Common/include/interface_interpolation/CSlidingMesh.hpp @@ -35,7 +35,7 @@ * \ingroup Interfaces */ class CSlidingMesh final : public CInterpolator { -public: + public: /*! * \brief Constructor of the class. * \param[in] geometry - Geometrical definition of the problem. @@ -43,8 +43,7 @@ class CSlidingMesh final : public CInterpolator { * \param[in] iZone - index of the donor zone. * \param[in] jZone - index of the target zone. */ - CSlidingMesh(CGeometry ****geometry_container, const CConfig* const* config, - unsigned int iZone, unsigned int jZone); + CSlidingMesh(CGeometry**** geometry_container, const CConfig* const* config, unsigned int iZone, unsigned int jZone); /*! * \brief Set up transfer matrix defining relation between two meshes @@ -52,7 +51,7 @@ class CSlidingMesh final : public CInterpolator { */ void SetTransferCoeff(const CConfig* const* config) override; -private: + private: /*! * \brief For 3-Dimensional grids, build the dual surface element * \param[in] map - array containing the index of the boundary points connected to the node @@ -125,6 +124,6 @@ class CSlidingMesh final : public CInterpolator { * \param[in] T2 - second point of triangle T * \param[in] T3 - third point of triangle T */ - static bool CheckPointInsideTriangle(const su2double* Point, const su2double* T1, - const su2double* T2, const su2double* T3); + static bool CheckPointInsideTriangle(const su2double* Point, const su2double* T1, const su2double* T2, + const su2double* T3); }; diff --git a/Common/include/linear_algebra/CMatrixVectorProduct.hpp b/Common/include/linear_algebra/CMatrixVectorProduct.hpp index cc48bb4670f..a3052d70d9b 100644 --- a/Common/include/linear_algebra/CMatrixVectorProduct.hpp +++ b/Common/include/linear_algebra/CMatrixVectorProduct.hpp @@ -26,7 +26,6 @@ * License along with SU2. If not, see . */ - #pragma once #include "../CConfig.hpp" @@ -52,40 +51,37 @@ * passed to a single implementation of the Krylov solvers. * This abstraction may also be used to define matrix-free products. */ -template +template class CMatrixVectorProduct { -public: + public: virtual ~CMatrixVectorProduct() = 0; - virtual void operator()(const CSysVector & u, CSysVector & v) const = 0; + virtual void operator()(const CSysVector& u, CSysVector& v) const = 0; }; -template +template CMatrixVectorProduct::~CMatrixVectorProduct() {} - /*! * \class CSysMatrixVectorProduct * \ingroup SpLinSys * \brief Specialization of matrix-vector product that uses CSysMatrix class */ -template +template class CSysMatrixVectorProduct final : public CMatrixVectorProduct { -private: - const CSysMatrix& matrix; /*!< \brief pointer to matrix that defines the product. */ - CGeometry* geometry; /*!< \brief geometry associated with the matrix. */ - const CConfig *config; /*!< \brief config of the problem. */ + private: + const CSysMatrix& matrix; /*!< \brief pointer to matrix that defines the product. */ + CGeometry* geometry; /*!< \brief geometry associated with the matrix. */ + const CConfig* config; /*!< \brief config of the problem. */ -public: + public: /*! * \brief constructor of the class * \param[in] matrix_ref - matrix reference that will be used to define the products * \param[in] geometry_ref - geometry associated with the problem * \param[in] config_ref - config of the problem */ - inline CSysMatrixVectorProduct(const CSysMatrix & matrix_ref, - CGeometry *geometry_ref, const CConfig *config_ref) : - matrix(matrix_ref), - geometry(geometry_ref), - config(config_ref) {} + inline CSysMatrixVectorProduct(const CSysMatrix& matrix_ref, CGeometry* geometry_ref, + const CConfig* config_ref) + : matrix(matrix_ref), geometry(geometry_ref), config(config_ref) {} /*! * \note This class cannot be default constructed as that would leave us with invalid pointers. @@ -97,7 +93,7 @@ class CSysMatrixVectorProduct final : public CMatrixVectorProduct { * \param[in] u - CSysVector that is being multiplied by the sparse matrix * \param[out] v - CSysVector that is the result of the product */ - inline void operator()(const CSysVector & u, CSysVector & v) const override { + inline void operator()(const CSysVector& u, CSysVector& v) const override { matrix.MatrixVectorProduct(u, v, geometry, config); } }; diff --git a/Common/include/linear_algebra/CPastixWrapper.hpp b/Common/include/linear_algebra/CPastixWrapper.hpp index 72ed9629e61..6001ec97e38 100644 --- a/Common/include/linear_algebra/CPastixWrapper.hpp +++ b/Common/include/linear_algebra/CPastixWrapper.hpp @@ -31,14 +31,14 @@ #ifdef HAVE_PASTIX #ifdef CODI_FORWARD_TYPE - #error Cannot use PaStiX with forward mode AD +#error Cannot use PaStiX with forward mode AD #endif namespace PaStiX { extern "C" { #include } -} +} // namespace PaStiX #include using namespace std; @@ -52,33 +52,31 @@ class CGeometry; * \brief Wrapper class that converts between SU2 sparse format and PaStiX * format and simplifies calls to the external solver. */ -template -class CPastixWrapper -{ -private: - PaStiX::pastix_data_t *state; /*!< \brief Internal state of the solver. */ - PaStiX::pastix_int_t nCols; /*!< \brief Local number of columns. */ +template +class CPastixWrapper { + private: + PaStiX::pastix_data_t* state; /*!< \brief Internal state of the solver. */ + PaStiX::pastix_int_t nCols; /*!< \brief Local number of columns. */ vector colptr; /*!< \brief Equiv. to our "row_ptr". */ vector rowidx; /*!< \brief Equiv. to our "col_ind". */ - vector values; /*!< \brief Equiv. to our "matrix". */ + vector values; /*!< \brief Equiv. to our "matrix". */ vector loc2glb; /*!< \brief Global index of the columns held by this rank. */ vector perm; /*!< \brief Ordering computed by PaStiX. */ - vector workvec; /*!< \brief RHS vector which then becomes the solution. */ + vector workvec; /*!< \brief RHS vector which then becomes the solution. */ PaStiX::pastix_int_t iparm[PaStiX::IPARM_SIZE]; /*!< \brief Integer parameters for PaStiX. */ - passivedouble dparm[PaStiX::DPARM_SIZE]; /*!< \brief Floating point parameters for PaStiX. */ + passivedouble dparm[PaStiX::DPARM_SIZE]; /*!< \brief Floating point parameters for PaStiX. */ struct { unsigned long nVar = 0; unsigned long nPoint = 0; unsigned long nPointDomain = 0; - const unsigned long *rowptr = nullptr; - const unsigned long *colidx = nullptr; - const ScalarType *values = nullptr; + const unsigned long* rowptr = nullptr; + const unsigned long* colidx = nullptr; + const ScalarType* values = nullptr; - unsigned long size_rhs() const {return nPointDomain*nVar;} - } - matrix; /*!< \brief Pointers and sizes of the input matrix. */ + unsigned long size_rhs() const { return nPointDomain * nVar; } + } matrix; /*!< \brief Pointers and sizes of the input matrix. */ bool issetup; /*!< \brief Signals that the matrix data has been provided. */ bool isinitialized; /*!< \brief Signals that the sparsity pattern has been set. */ @@ -87,15 +85,15 @@ class CPastixWrapper unsigned short verb; /*!< \brief Verbosity level. */ const int mpi_size, mpi_rank; - vector sort_rows; /*!< \brief List of rows with halo points. */ + vector sort_rows; /*!< \brief List of rows with halo points. */ vector > sort_order; /*!< \brief How each of those rows needs to be sorted. */ /*! * \brief Run the external solver for the task it is currently setup to execute. */ void Run() { - dpastix(&state, SU2_MPI::GetComm(), nCols, colptr.data(), rowidx.data(), values.data(), - loc2glb.data(), perm.data(), NULL, workvec.data(), 1, iparm, dparm); + dpastix(&state, SU2_MPI::GetComm(), nCols, colptr.data(), rowidx.data(), values.data(), loc2glb.data(), perm.data(), + NULL, workvec.data(), 1, iparm, dparm); } /*! @@ -103,10 +101,10 @@ class CPastixWrapper */ void Clean() { using namespace PaStiX; - if(isfactorized) { + if (isfactorized) { iparm[IPARM_VERBOSE] = (verb > 0) ? API_VERBOSE_NO : API_VERBOSE_NOT; iparm[IPARM_START_TASK] = API_TASK_CLEAN; - iparm[IPARM_END_TASK] = API_TASK_CLEAN; + iparm[IPARM_END_TASK] = API_TASK_CLEAN; Run(); isfactorized = false; } @@ -115,22 +113,27 @@ class CPastixWrapper /*! * \brief Initialize the matrix format that PaStiX requires. */ - void Initialize(CGeometry *geometry, const CConfig *config); + void Initialize(CGeometry* geometry, const CConfig* config); -public: + public: /*! * \brief Class constructor. */ - CPastixWrapper() : state(nullptr), issetup(false), isinitialized(false), - isfactorized(false), iter(0), verb(0), - mpi_size(SU2_MPI::GetSize()), mpi_rank(SU2_MPI::GetRank()) { - } + CPastixWrapper() + : state(nullptr), + issetup(false), + isinitialized(false), + isfactorized(false), + iter(0), + verb(0), + mpi_size(SU2_MPI::GetSize()), + mpi_rank(SU2_MPI::GetRank()) {} /*--- Move or copy is not allowed. ---*/ CPastixWrapper(CPastixWrapper&&) = delete; CPastixWrapper(const CPastixWrapper&) = delete; - CPastixWrapper& operator= (CPastixWrapper&&) = delete; - CPastixWrapper& operator= (const CPastixWrapper&) = delete; + CPastixWrapper& operator=(CPastixWrapper&&) = delete; + CPastixWrapper& operator=(const CPastixWrapper&) = delete; /*! * \brief Class destructor. @@ -146,13 +149,8 @@ class CPastixWrapper * \param[in] colidx - Non zeros column indices. * \param[in] values - Matrix coefficients. */ - void SetMatrix(unsigned long nVar, - unsigned long nPoint, - unsigned long nPointDomain, - const unsigned long *rowptr, - const unsigned long *colidx, - const ScalarType *values) { - + void SetMatrix(unsigned long nVar, unsigned long nPoint, unsigned long nPointDomain, const unsigned long* rowptr, + const unsigned long* colidx, const ScalarType* values) { if (issetup) return; matrix.nVar = nVar; matrix.nPoint = nPoint; @@ -169,7 +167,7 @@ class CPastixWrapper * \param[in] config - Definition of the particular problem. * \param[in] kind_fact - Type of factorization. */ - void Factorize(CGeometry *geometry, const CConfig *config, unsigned short kind_fact); + void Factorize(CGeometry* geometry, const CConfig* config, unsigned short kind_fact); /*! * \brief Request solves with the transposed matrix. @@ -178,7 +176,7 @@ class CPastixWrapper void SetTransposedSolve(bool transposed = true) { using namespace PaStiX; if (iparm[IPARM_SYM] == API_SYM_NO) - iparm[IPARM_TRANSPOSE_SOLVE] = pastix_int_t(!transposed); // negated due to CSR to CSC copy + iparm[IPARM_TRANSPOSE_SOLVE] = pastix_int_t(!transposed); // negated due to CSR to CSC copy } /*! @@ -186,24 +184,22 @@ class CPastixWrapper * \param[in] rhs - Right hand side of the linear system. * \param[out] sol - Solution of the system. */ - template + template void Solve(const T& rhs, T& sol) { using namespace PaStiX; - if (!isfactorized) - SU2_MPI::Error("The factorization has not been computed yet.", CURRENT_FUNCTION); + if (!isfactorized) SU2_MPI::Error("The factorization has not been computed yet.", CURRENT_FUNCTION); unsigned long i; - for (i=0; i < matrix.size_rhs(); ++i) workvec[i] = rhs[i]; + for (i = 0; i < matrix.size_rhs(); ++i) workvec[i] = rhs[i]; - iparm[IPARM_VERBOSE] = API_VERBOSE_NOT; + iparm[IPARM_VERBOSE] = API_VERBOSE_NOT; iparm[IPARM_START_TASK] = API_TASK_SOLVE; - iparm[IPARM_END_TASK] = API_TASK_SOLVE; + iparm[IPARM_END_TASK] = API_TASK_SOLVE; Run(); - for (i=0; i < matrix.size_rhs(); ++i) sol[i] = workvec[i]; + for (i = 0; i < matrix.size_rhs(); ++i) sol[i] = workvec[i]; } - }; #endif diff --git a/Common/include/linear_algebra/CPreconditioner.hpp b/Common/include/linear_algebra/CPreconditioner.hpp index a2ebaf8ba39..b142645ff1f 100644 --- a/Common/include/linear_algebra/CPreconditioner.hpp +++ b/Common/include/linear_algebra/CPreconditioner.hpp @@ -44,9 +44,9 @@ * See the remarks regarding the CMatrixVectorProduct class. The same * idea applies here to the preconditioning operation. */ -template +template class CPreconditioner { -public: + public: /*! * \brief Destructor of the class */ @@ -55,7 +55,7 @@ class CPreconditioner { /*! * \brief Overload of operator (), applies the preconditioner to "u" storing the result in "v". */ - virtual void operator()(const CSysVector & u, CSysVector & v) const = 0; + virtual void operator()(const CSysVector& u, CSysVector& v) const = 0; /*! * \brief Generic "preprocessing" hook derived classes may implement to build the preconditioner. @@ -70,36 +70,33 @@ class CPreconditioner { /*! * \brief Factory method. */ - static CPreconditioner* Create(ENUM_LINEAR_SOLVER_PREC kind, CSysMatrix& jacobian, - CGeometry* geometry, const CConfig* config); + static CPreconditioner* Create(ENUM_LINEAR_SOLVER_PREC kind, CSysMatrix& jacobian, CGeometry* geometry, + const CConfig* config); }; -template +template CPreconditioner::~CPreconditioner() {} - /*! * \class CJacobiPreconditioner * \brief Specialization of preconditioner that uses CSysMatrix class. */ -template +template class CJacobiPreconditioner final : public CPreconditioner { -private: + private: CSysMatrix& sparse_matrix; /*!< \brief Pointer to matrix that defines the preconditioner. */ CGeometry* geometry; /*!< \brief Pointer to geometry associated with the matrix. */ - const CConfig *config; /*!< \brief Pointer to problem configuration. */ + const CConfig* config; /*!< \brief Pointer to problem configuration. */ -public: + public: /*! * \brief Constructor of the class. * \param[in] matrix_ref - Matrix reference that will be used to define the preconditioner. * \param[in] geometry_ref - Geometry associated with the problem. * \param[in] config_ref - Config of the problem. */ - inline CJacobiPreconditioner(CSysMatrix & matrix_ref, - CGeometry *geometry_ref, const CConfig *config_ref) : - sparse_matrix(matrix_ref) - { - if((geometry_ref == nullptr) || (config_ref == nullptr)) + inline CJacobiPreconditioner(CSysMatrix& matrix_ref, CGeometry* geometry_ref, const CConfig* config_ref) + : sparse_matrix(matrix_ref) { + if ((geometry_ref == nullptr) || (config_ref == nullptr)) SU2_MPI::Error("Preconditioner needs to be built with valid references.", CURRENT_FUNCTION); geometry = geometry_ref; config = config_ref; @@ -115,42 +112,37 @@ class CJacobiPreconditioner final : public CPreconditioner { * \param[in] u - CSysVector that is being preconditioned * \param[out] v - CSysVector that is the result of the preconditioning */ - inline void operator()(const CSysVector & u, CSysVector & v) const override { + inline void operator()(const CSysVector& u, CSysVector& v) const override { sparse_matrix.ComputeJacobiPreconditioner(u, v, geometry, config); } /*! * \note Request the associated matrix to build the preconditioner. */ - inline void Build() override { - sparse_matrix.BuildJacobiPreconditioner(); - } + inline void Build() override { sparse_matrix.BuildJacobiPreconditioner(); } }; - /*! * \class CILUPreconditioner * \brief Specialization of preconditioner that uses CSysMatrix class */ -template +template class CILUPreconditioner final : public CPreconditioner { -private: + private: CSysMatrix& sparse_matrix; /*!< \brief Pointer to matrix that defines the preconditioner. */ CGeometry* geometry; /*!< \brief Pointer to geometry associated with the matrix. */ - const CConfig *config; /*!< \brief Pointer to problem configuration. */ + const CConfig* config; /*!< \brief Pointer to problem configuration. */ -public: + public: /*! * \brief Constructor of the class. * \param[in] matrix_ref - Matrix reference that will be used to define the preconditioner. * \param[in] geometry_ref - Geometry associated with the problem. * \param[in] config_ref - Config of the problem. */ - inline CILUPreconditioner(CSysMatrix & matrix_ref, - CGeometry *geometry_ref, const CConfig *config_ref) : - sparse_matrix(matrix_ref) - { - if((geometry_ref == nullptr) || (config_ref == nullptr)) + inline CILUPreconditioner(CSysMatrix& matrix_ref, CGeometry* geometry_ref, const CConfig* config_ref) + : sparse_matrix(matrix_ref) { + if ((geometry_ref == nullptr) || (config_ref == nullptr)) SU2_MPI::Error("Preconditioner needs to be built with valid references.", CURRENT_FUNCTION); geometry = geometry_ref; config = config_ref; @@ -166,43 +158,37 @@ class CILUPreconditioner final : public CPreconditioner { * \param[in] u - CSysVector that is being preconditioned. * \param[out] v - CSysVector that is the result of the preconditioning. */ - inline void operator()(const CSysVector & u, CSysVector & v) const override { + inline void operator()(const CSysVector& u, CSysVector& v) const override { sparse_matrix.ComputeILUPreconditioner(u, v, geometry, config); } /*! * \note Request the associated matrix to build the preconditioner. */ - inline void Build() override { - sparse_matrix.BuildILUPreconditioner(); - } + inline void Build() override { sparse_matrix.BuildILUPreconditioner(); } }; - /*! * \class CLU_SGSPreconditioner * \brief Specialization of preconditioner that uses CSysMatrix class. */ -template +template class CLU_SGSPreconditioner final : public CPreconditioner { -private: + private: CSysMatrix& sparse_matrix; /*!< \brief Pointer to matrix that defines the preconditioner. */ CGeometry* geometry; /*!< \brief Pointer to geometry associated with the matrix. */ - const CConfig *config; /*!< \brief Pointer to problem configuration. */ - -public: + const CConfig* config; /*!< \brief Pointer to problem configuration. */ + public: /*! * \brief Constructor of the class. * \param[in] matrix_ref - Matrix reference that will be used to define the preconditioner. * \param[in] geometry_ref - Geometry associated with the problem. * \param[in] config_ref - Config of the problem. */ - inline CLU_SGSPreconditioner(CSysMatrix & matrix_ref, - CGeometry *geometry_ref, const CConfig *config_ref) : - sparse_matrix(matrix_ref) - { - if((geometry_ref == nullptr) || (config_ref == nullptr)) + inline CLU_SGSPreconditioner(CSysMatrix& matrix_ref, CGeometry* geometry_ref, const CConfig* config_ref) + : sparse_matrix(matrix_ref) { + if ((geometry_ref == nullptr) || (config_ref == nullptr)) SU2_MPI::Error("Preconditioner needs to be built with valid references.", CURRENT_FUNCTION); geometry = geometry_ref; config = config_ref; @@ -218,35 +204,32 @@ class CLU_SGSPreconditioner final : public CPreconditioner { * \param[in] u - CSysVector that is being preconditioned. * \param[out] v - CSysVector that is the result of the preconditioning. */ - inline void operator()(const CSysVector & u, CSysVector & v) const override { + inline void operator()(const CSysVector& u, CSysVector& v) const override { sparse_matrix.ComputeLU_SGSPreconditioner(u, v, geometry, config); } }; - /*! * \class CLineletPreconditioner * \brief Specialization of preconditioner that uses CSysMatrix class. */ -template +template class CLineletPreconditioner final : public CPreconditioner { -private: + private: CSysMatrix& sparse_matrix; /*!< \brief Pointer to matrix that defines the preconditioner. */ CGeometry* geometry; /*!< \brief Pointer to geometry associated with the matrix. */ - const CConfig *config; /*!< \brief Pointer to problem configuration. */ + const CConfig* config; /*!< \brief Pointer to problem configuration. */ -public: + public: /*! * \brief Constructor of the class. * \param[in] matrix_ref - Matrix reference that will be used to define the preconditioner. * \param[in] geometry_ref - Geometry associated with the problem. * \param[in] config_ref - Config of the problem. */ - inline CLineletPreconditioner(CSysMatrix & matrix_ref, - CGeometry *geometry_ref, const CConfig *config_ref) : - sparse_matrix(matrix_ref) - { - if((geometry_ref == nullptr) || (config_ref == nullptr)) + inline CLineletPreconditioner(CSysMatrix& matrix_ref, CGeometry* geometry_ref, const CConfig* config_ref) + : sparse_matrix(matrix_ref) { + if ((geometry_ref == nullptr) || (config_ref == nullptr)) SU2_MPI::Error("Preconditioner needs to be built with valid references.", CURRENT_FUNCTION); geometry = geometry_ref; config = config_ref; @@ -262,32 +245,29 @@ class CLineletPreconditioner final : public CPreconditioner { * \param[in] u - CSysVector that is being preconditioned. * \param[out] v - CSysVector that is the result of the preconditioning. */ - inline void operator()(const CSysVector & u, CSysVector & v) const override { + inline void operator()(const CSysVector& u, CSysVector& v) const override { sparse_matrix.ComputeLineletPreconditioner(u, v, geometry, config); } /*! * \note Request the associated matrix to build the preconditioner. */ - inline void Build() override { - sparse_matrix.BuildLineletPreconditioner(geometry, config); - } + inline void Build() override { sparse_matrix.BuildLineletPreconditioner(geometry, config); } }; - /*! * \class CPastixPreconditioner * \brief Specialization of preconditioner that uses PaStiX to factorize a CSysMatrix. */ -template +template class CPastixPreconditioner final : public CPreconditioner { -private: + private: CSysMatrix& sparse_matrix; /*!< \brief Pointer to the matrix. */ CGeometry* geometry; /*!< \brief Geometry associated with the problem. */ - const CConfig *config; /*!< \brief Configuration of the problem. */ + const CConfig* config; /*!< \brief Configuration of the problem. */ unsigned short kind_fact; /*!< \brief The type of factorization desired. */ -public: + public: /*! * \brief Constructor of the class * \param[in] matrix_ref - Matrix reference that will be used to define the preconditioner. @@ -295,11 +275,10 @@ class CPastixPreconditioner final : public CPreconditioner { * \param[in] config_ref - Problem configuration. * \param[in] kind_factorization - Type of factorization required. */ - inline CPastixPreconditioner(CSysMatrix & matrix_ref, CGeometry *geometry_ref, - const CConfig *config_ref, unsigned short kind_factorization) : - sparse_matrix(matrix_ref) - { - if((geometry_ref == nullptr) || (config_ref == nullptr)) + inline CPastixPreconditioner(CSysMatrix& matrix_ref, CGeometry* geometry_ref, const CConfig* config_ref, + unsigned short kind_factorization) + : sparse_matrix(matrix_ref) { + if ((geometry_ref == nullptr) || (config_ref == nullptr)) SU2_MPI::Error("Preconditioner needs to be built with valid references.", CURRENT_FUNCTION); geometry = geometry_ref; config = config_ref; @@ -316,23 +295,19 @@ class CPastixPreconditioner final : public CPreconditioner { * \param[in] u - CSysVector that is being preconditioned. * \param[out] v - CSysVector that is the result of the preconditioning. */ - inline void operator()(const CSysVector & u, CSysVector & v) const override { + inline void operator()(const CSysVector& u, CSysVector& v) const override { sparse_matrix.ComputePastixPreconditioner(u, v, geometry, config); } /*! * \note Request the associated matrix to build the preconditioner. */ - inline void Build() override { - sparse_matrix.BuildPastixPreconditioner(geometry, config, kind_fact); - } + inline void Build() override { sparse_matrix.BuildPastixPreconditioner(geometry, config, kind_fact); } }; - -template +template CPreconditioner* CPreconditioner::Create(ENUM_LINEAR_SOLVER_PREC kind, - CSysMatrix& jacobian, - CGeometry* geometry, + CSysMatrix& jacobian, CGeometry* geometry, const CConfig* config) { CPreconditioner* prec = nullptr; @@ -349,7 +324,9 @@ CPreconditioner* CPreconditioner::Create(ENUM_LINEAR_SOL case ILU: prec = new CILUPreconditioner(jacobian, geometry, config); break; - case PASTIX_ILU: case PASTIX_LU_P: case PASTIX_LDLT_P: + case PASTIX_ILU: + case PASTIX_LU_P: + case PASTIX_LDLT_P: prec = new CPastixPreconditioner(jacobian, geometry, config, kind); break; } @@ -357,4 +334,4 @@ CPreconditioner* CPreconditioner::Create(ENUM_LINEAR_SOL return prec; } -/// @} \ No newline at end of file +/// @} diff --git a/Common/include/linear_algebra/CSysMatrix.hpp b/Common/include/linear_algebra/CSysMatrix.hpp index d140fc1e6a1..3609c260f8f 100644 --- a/Common/include/linear_algebra/CSysMatrix.hpp +++ b/Common/include/linear_algebra/CSysMatrix.hpp @@ -40,7 +40,7 @@ #if defined(HAVE_MKL) && !defined(CODI_FORWARD_TYPE) #include "mkl.h" #ifndef __INTEL_MKL__ - #error Could not determine the MKL version +#error Could not determine the MKL version #endif /*--- JIT is only available since 2019. ---*/ #if __INTEL_MKL__ >= 2019 @@ -50,24 +50,28 @@ making "getrf" and "getrs" compatible with AD since they are not used as often as "gemm". ---*/ #if defined(__INTEL_COMPILER) && defined(MKL_DIRECT_CALL_SEQ) && !defined(CODI_REVERSE_TYPE) - #define USE_MKL_LAPACK +#define USE_MKL_LAPACK #endif -template +template struct mkl_jit_wrapper { using gemm_t = dgemm_jit_kernel_t; - template - static void create_gemm(Ts&&... args) { mkl_jit_create_dgemm(args...); } + template + static void create_gemm(Ts&&... args) { + mkl_jit_create_dgemm(args...); + } static gemm_t get_gemm(void* jitter) { return mkl_jit_get_dgemm_ptr(jitter); } }; -template<> +template <> struct mkl_jit_wrapper { using gemm_t = sgemm_jit_kernel_t; - template - static void create_gemm(Ts&&... args) { mkl_jit_create_sgemm(args...); } + template + static void create_gemm(Ts&&... args) { + mkl_jit_create_sgemm(args...); + } static gemm_t get_gemm(void* jitter) { return mkl_jit_get_sgemm_ptr(jitter); } }; #else - #warning The current version of MKL does not support JIT gemm kernels +#warning The current version of MKL does not support JIT gemm kernels #endif #endif @@ -86,8 +90,8 @@ struct CSysMatrixComms { * \param[in] config - Definition of the particular problem. * \param[in] commType - Enumerated type for the quantity to be communicated. */ - template - static void Initiate(const CSysVector& x, CGeometry *geometry, const CConfig *config, + template + static void Initiate(const CSysVector& x, CGeometry* geometry, const CConfig* config, unsigned short commType = SOLUTION_MATRIX); /*! @@ -98,8 +102,8 @@ struct CSysMatrixComms { * \param[in] config - Definition of the particular problem. * \param[in] commType - Enumerated type for the quantity to be unpacked. */ - template - static void Complete(CSysVector& x, CGeometry *geometry, const CConfig *config, + template + static void Complete(CSysVector& x, CGeometry* geometry, const CConfig* config, unsigned short commType = SOLUTION_MATRIX); }; @@ -108,60 +112,66 @@ struct CSysMatrixComms { * \ingroup SpLinSys * \brief Main class for defining block-compressed-row-storage sparse matrices. */ -template +template class CSysMatrix { -private: + private: friend struct CSysMatrixComms; - const int rank; /*!< \brief MPI Rank. */ - const int size; /*!< \brief MPI Size. */ - - enum : size_t { MAXNVAR = 20 }; /*!< \brief Maximum number of variables the matrix can handle. The static - size is needed for fast, per-thread, static memory allocation. */ - - enum { OMP_MAX_SIZE_L = 8192 }; /*!< \brief Max. chunk size used in light parallel for loops. */ - enum { OMP_MAX_SIZE_H = 512 }; /*!< \brief Max. chunk size used in heavy parallel for loops. */ - enum { OMP_MIN_SIZE = 32 }; /*!< \brief Chunk size for finer grain operations. */ - unsigned long omp_light_size; /*!< \brief Actual chunk size used in light loops (e.g. over non zeros). */ - unsigned long omp_heavy_size; /*!< \brief Actual chunk size used in heavy loops (e.g. over rows). */ - unsigned long omp_num_parts; /*!< \brief Number of threads used in thread-parallel LU_SGS and ILU. */ - unsigned long *omp_partitions; /*!< \brief Point indexes of LU_SGS and ILU thread-parallel sub partitioning. */ - - unsigned long nPoint; /*!< \brief Number of points in the grid. */ - unsigned long nPointDomain; /*!< \brief Number of points in the grid (excluding halos). */ - unsigned long nVar; /*!< \brief Number of variables (and rows of the blocks). */ - unsigned long nEqn; /*!< \brief Number of equations (and columns of the blocks). */ - - ScalarType *matrix; /*!< \brief Entries of the sparse matrix. */ - unsigned long nnz; /*!< \brief Number of possible nonzero entries in the matrix. */ - const unsigned long *row_ptr; /*!< \brief Pointers to the first element in each row. */ - const unsigned long *dia_ptr; /*!< \brief Pointers to the diagonal element in each row. */ - const unsigned long *col_ind; /*!< \brief Column index for each of the elements in val(). */ - const unsigned long *col_ptr; /*!< \brief The transpose of col_ind, pointer to blocks with the same column index. */ - - ScalarType *ILU_matrix; /*!< \brief Entries of the ILU sparse matrix. */ + const int rank; /*!< \brief MPI Rank. */ + const int size; /*!< \brief MPI Size. */ + + enum : size_t { + MAXNVAR = 20 + }; /*!< \brief Maximum number of variables the matrix can handle. The static + size is needed for fast, per-thread, static memory allocation. */ + + enum { OMP_MAX_SIZE_L = 8192 }; /*!< \brief Max. chunk size used in light parallel for loops. */ + enum { OMP_MAX_SIZE_H = 512 }; /*!< \brief Max. chunk size used in heavy parallel for loops. */ + enum { OMP_MIN_SIZE = 32 }; /*!< \brief Chunk size for finer grain operations. */ + unsigned long omp_light_size; /*!< \brief Actual chunk size used in light loops (e.g. over non zeros). */ + unsigned long omp_heavy_size; /*!< \brief Actual chunk size used in heavy loops (e.g. over rows). */ + unsigned long omp_num_parts; /*!< \brief Number of threads used in thread-parallel LU_SGS and ILU. */ + unsigned long* omp_partitions; /*!< \brief Point indexes of LU_SGS and ILU thread-parallel sub partitioning. */ + + unsigned long nPoint; /*!< \brief Number of points in the grid. */ + unsigned long nPointDomain; /*!< \brief Number of points in the grid (excluding halos). */ + unsigned long nVar; /*!< \brief Number of variables (and rows of the blocks). */ + unsigned long nEqn; /*!< \brief Number of equations (and columns of the blocks). */ + + ScalarType* matrix; /*!< \brief Entries of the sparse matrix. */ + unsigned long nnz; /*!< \brief Number of possible nonzero entries in the matrix. */ + const unsigned long* row_ptr; /*!< \brief Pointers to the first element in each row. */ + const unsigned long* dia_ptr; /*!< \brief Pointers to the diagonal element in each row. */ + const unsigned long* col_ind; /*!< \brief Column index for each of the elements in val(). */ + const unsigned long* col_ptr; /*!< \brief The transpose of col_ind, pointer to blocks with the same column index. */ + + ScalarType* ILU_matrix; /*!< \brief Entries of the ILU sparse matrix. */ unsigned long nnz_ilu; /*!< \brief Number of possible nonzero entries in the matrix (ILU). */ - const unsigned long *row_ptr_ilu; /*!< \brief Pointers to the first element in each row (ILU). */ - const unsigned long *dia_ptr_ilu; /*!< \brief Pointers to the diagonal element in each row (ILU). */ - const unsigned long *col_ind_ilu; /*!< \brief Column index for each of the elements in val() (ILU). */ + const unsigned long* row_ptr_ilu; /*!< \brief Pointers to the first element in each row (ILU). */ + const unsigned long* dia_ptr_ilu; /*!< \brief Pointers to the diagonal element in each row (ILU). */ + const unsigned long* col_ind_ilu; /*!< \brief Column index for each of the elements in val() (ILU). */ unsigned short ilu_fill_in; /*!< \brief Fill in level for the ILU preconditioner. */ - ScalarType *invM; /*!< \brief Inverse of (Jacobi) preconditioner, or diagonal of ILU. */ + ScalarType* invM; /*!< \brief Inverse of (Jacobi) preconditioner, or diagonal of ILU. */ /*--- Temporary (hence mutable) working memory used in the Linelet preconditioner, outer vector is for threads ---*/ - mutable vector > LineletUpper; /*!< \brief Pointers to the upper blocks of the tri-diag system (working memory). */ - mutable vector > LineletInvDiag; /*!< \brief Inverse of the diagonal blocks of the tri-diag system (working memory). */ - mutable vector > LineletVector; /*!< \brief Solution and RHS of the tri-diag system (working memory). */ + mutable vector > + LineletUpper; /*!< \brief Pointers to the upper blocks of the tri-diag system (working memory). */ + mutable vector > + LineletInvDiag; /*!< \brief Inverse of the diagonal blocks of the tri-diag system (working memory). */ + mutable vector > + LineletVector; /*!< \brief Solution and RHS of the tri-diag system (working memory). */ #ifdef USE_MKL using gemm_t = typename mkl_jit_wrapper::gemm_t; - void * MatrixMatrixProductJitter; /*!< \brief Jitter handle for MKL JIT based GEMM. */ + void* MatrixMatrixProductJitter; /*!< \brief Jitter handle for MKL JIT based GEMM. */ gemm_t MatrixMatrixProductKernel; /*!< \brief MKL JIT based GEMM kernel. */ - void * MatrixVectorProductJitterBetaZero; /*!< \brief Jitter handle for MKL JIT based GEMV. */ + void* MatrixVectorProductJitterBetaZero; /*!< \brief Jitter handle for MKL JIT based GEMV. */ gemm_t MatrixVectorProductKernelBetaZero; /*!< \brief MKL JIT based GEMV kernel. */ - void * MatrixVectorProductJitterBetaOne; /*!< \brief Jitter handle for MKL JIT based GEMV with BETA=1.0. */ + void* MatrixVectorProductJitterBetaOne; /*!< \brief Jitter handle for MKL JIT based GEMV with BETA=1.0. */ gemm_t MatrixVectorProductKernelBetaOne; /*!< \brief MKL JIT based GEMV kernel with BETA=1.0. */ - void * MatrixVectorProductJitterAlphaMinusOne; /*!< \brief Jitter handle for MKL JIT based GEMV with ALPHA=-1.0 and BETA=1.0. */ + void* MatrixVectorProductJitterAlphaMinusOne; /*!< \brief Jitter handle for MKL JIT based GEMV with ALPHA=-1.0 and + BETA=1.0. */ gemm_t MatrixVectorProductKernelAlphaMinusOne; /*!< \brief MKL JIT based GEMV kernel with ALPHA=-1.0 and BETA=1.0. */ #endif @@ -173,33 +183,38 @@ class CSysMatrix { * \brief Auxilary object to wrap the edge map pointer used in fast block updates, i.e. without linear searches. */ struct { - const unsigned long *ptr = nullptr; + const unsigned long* ptr = nullptr; unsigned long nEdge = 0; operator bool() { return nEdge != 0; } - inline unsigned long operator() (unsigned long edge, unsigned long node) const { - return ptr[2*edge+node]; - } - inline unsigned long ij(unsigned long edge) const { return ptr[2*edge]; } - inline unsigned long ji(unsigned long edge) const { return ptr[2*edge+1]; } + inline unsigned long operator()(unsigned long edge, unsigned long node) const { return ptr[2 * edge + node]; } + inline unsigned long ij(unsigned long edge) const { return ptr[2 * edge]; } + inline unsigned long ji(unsigned long edge) const { return ptr[2 * edge + 1]; } } edge_ptr; /*! - * \brief Handle type conversion for when we Set, Add, etc. blocks, preserving derivative information (if supported by types). + * \brief Handle type conversion for when we Set, Add, etc. blocks, preserving derivative information (if supported by + * types). */ - template::value> = 0> - FORCEINLINE static DstType ActiveAssign(const SrcType& val) { return SU2_TYPE::GetValue(val); } + template ::value> = 0> + FORCEINLINE static DstType ActiveAssign(const SrcType& val) { + return SU2_TYPE::GetValue(val); + } - template::value> = 0> - FORCEINLINE static DstType ActiveAssign(const SrcType& val) { return val; } + template ::value> = 0> + FORCEINLINE static DstType ActiveAssign(const SrcType& val) { + return val; + } /*! * \brief Handle type conversion for when we Set, Add, etc. blocks, discarding derivative information. */ - template - FORCEINLINE static ScalarType PassiveAssign(const SrcType& val) { return SU2_TYPE::GetValue(val); } + template + FORCEINLINE static ScalarType PassiveAssign(const SrcType& val) { + return SU2_TYPE::GetValue(val); + } /*! * \brief Calculates the matrix-vector product: product = matrix*vector @@ -207,7 +222,7 @@ class CSysMatrix { * \param[in] vector * \param[out] product */ - void MatrixVectorProduct(const ScalarType *matrix, const ScalarType *vector, ScalarType *product) const; + void MatrixVectorProduct(const ScalarType* matrix, const ScalarType* vector, ScalarType* product) const; /*! * \brief Calculates the matrix-vector product: product += matrix*vector @@ -215,7 +230,7 @@ class CSysMatrix { * \param[in] vector * \param[in,out] product */ - void MatrixVectorProductAdd(const ScalarType *matrix, const ScalarType *vector, ScalarType *product) const; + void MatrixVectorProductAdd(const ScalarType* matrix, const ScalarType* vector, ScalarType* product) const; /*! * \brief Calculates the matrix-vector product: product -= matrix*vector @@ -223,37 +238,34 @@ class CSysMatrix { * \param[in] vector * \param[in,out] product */ - void MatrixVectorProductSub(const ScalarType *matrix, const ScalarType *vector, ScalarType *product) const; + void MatrixVectorProductSub(const ScalarType* matrix, const ScalarType* vector, ScalarType* product) const; /*! * \brief Calculates the matrix-matrix product */ - void MatrixMatrixProduct(const ScalarType *matrix_a, const ScalarType *matrix_b, ScalarType *product) const; + void MatrixMatrixProduct(const ScalarType* matrix_a, const ScalarType* matrix_b, ScalarType* product) const; /*! * \brief Subtract b from a and store the result in c. */ - FORCEINLINE void VectorSubtraction(const ScalarType *a, const ScalarType *b, ScalarType *c) const { - for(unsigned long iVar = 0; iVar < nVar; iVar++) - c[iVar] = a[iVar] - b[iVar]; + FORCEINLINE void VectorSubtraction(const ScalarType* a, const ScalarType* b, ScalarType* c) const { + for (unsigned long iVar = 0; iVar < nVar; iVar++) c[iVar] = a[iVar] - b[iVar]; } /*! * \brief Subtract b from a and store the result in c. */ - FORCEINLINE void MatrixSubtraction(const ScalarType *a, const ScalarType *b, ScalarType *c) const { + FORCEINLINE void MatrixSubtraction(const ScalarType* a, const ScalarType* b, ScalarType* c) const { SU2_OMP_SIMD - for(unsigned long iVar = 0; iVar < nVar*nEqn; iVar++) - c[iVar] = a[iVar] - b[iVar]; + for (unsigned long iVar = 0; iVar < nVar * nEqn; iVar++) c[iVar] = a[iVar] - b[iVar]; } /*! * \brief Copy matrix src into dst, transpose if required. */ - FORCEINLINE void MatrixCopy(const ScalarType *src, ScalarType *dst) const { + FORCEINLINE void MatrixCopy(const ScalarType* src, ScalarType* dst) const { SU2_OMP_SIMD - for(auto iVar = 0ul; iVar < nVar*nEqn; ++iVar) - dst[iVar] = src[iVar]; + for (auto iVar = 0ul; iVar < nVar * nEqn; ++iVar) dst[iVar] = src[iVar]; } /*! @@ -268,7 +280,7 @@ class CSysMatrix { * \param[in,out] matrix - On entry the system matrix, on exit the factorized matrix. * \param[out] inverse - the matrix inverse. */ - void MatrixInverse(ScalarType *matrix, ScalarType *inverse) const; + void MatrixInverse(ScalarType* matrix, ScalarType* inverse) const; /*! * \brief Performs the Gauss Elimination algorithm to solve the linear subsystem of the (i,i) subblock and rhs. @@ -283,21 +295,21 @@ class CSysMatrix { * \param[in] block_i - Indexes of the block in the matrix-by-blocks structure. * \param[out] invBlock - Inverse block. */ - inline void InverseDiagonalBlock(unsigned long block_i, ScalarType *invBlock) const; + inline void InverseDiagonalBlock(unsigned long block_i, ScalarType* invBlock) const; /*! * \brief Inverse diagonal block. * \param[in] block_i - Indexes of the block in the matrix-by-blocks structure. * \param[out] invBlock - Inverse block. */ - inline void InverseDiagonalBlock_ILUMatrix(unsigned long block_i, ScalarType *invBlock) const; + inline void InverseDiagonalBlock_ILUMatrix(unsigned long block_i, ScalarType* invBlock) const; /*! * \brief Copies the block (i, j) of the matrix-by-blocks structure in the internal variable *block. * \param[in] block_i - Indexes of the block in the matrix-by-blocks structure. * \param[in] block_j - Indexes of the block in the matrix-by-blocks structure. */ - inline ScalarType *GetBlock_ILUMatrix(unsigned long block_i, unsigned long block_j); + inline ScalarType* GetBlock_ILUMatrix(unsigned long block_i, unsigned long block_j); /*! * \brief Set the value of a block in the sparse matrix. @@ -305,7 +317,7 @@ class CSysMatrix { * \param[in] block_j - Indexes of the block in the matrix-by-blocks structure. * \param[in] **val_block - Block to set to A(i, j). */ - inline void SetBlock_ILUMatrix(unsigned long block_i, unsigned long block_j, ScalarType *val_block); + inline void SetBlock_ILUMatrix(unsigned long block_i, unsigned long block_j, ScalarType* val_block); /*! * \brief Performs the product of i-th row of the upper part of a sparse matrix by a vector. @@ -314,8 +326,8 @@ class CSysMatrix { * \param[in] col_ub - Exclusive upper bound for column indices considered in multiplication. * \param[out] prod - Result of the product U(A)*vec. */ - inline void UpperProduct(const CSysVector & vec, unsigned long row_i, - unsigned long col_ub, ScalarType *prod) const; + inline void UpperProduct(const CSysVector& vec, unsigned long row_i, unsigned long col_ub, + ScalarType* prod) const; /*! * \brief Performs the product of i-th row of the lower part of a sparse matrix by a vector. @@ -324,8 +336,8 @@ class CSysMatrix { * \param[in] col_lb - Inclusive lower bound for column indices considered in multiplication. * \param[out] prod - Result of the product L(A)*vec. */ - inline void LowerProduct(const CSysVector & vec, unsigned long row_i, - unsigned long col_lb, ScalarType *prod) const; + inline void LowerProduct(const CSysVector& vec, unsigned long row_i, unsigned long col_lb, + ScalarType* prod) const; /*! * \brief Performs the product of i-th row of the diagonal part of a sparse matrix by a vector. @@ -333,7 +345,7 @@ class CSysMatrix { * \param[in] row_i - Row of the matrix to be multiplied by vector vec. * \return prod Result of the product D(A)*vec (stored at *prod_row_vector). */ - inline void DiagonalProduct(const CSysVector & vec, unsigned long row_i, ScalarType *prod) const; + inline void DiagonalProduct(const CSysVector& vec, unsigned long row_i, ScalarType* prod) const; /*! * \brief Performs the product of i-th row of a sparse matrix by a vector. @@ -341,10 +353,9 @@ class CSysMatrix { * \param[in] row_i - Row of the matrix to be multiplied by vector vec. * \return Result of the product (stored at *prod_row_vector). */ - void RowProduct(const CSysVector & vec, unsigned long row_i, ScalarType *prod) const; - -public: + void RowProduct(const CSysVector& vec, unsigned long row_i, ScalarType* prod) const; + public: /*! * \brief Constructor of the class. */ @@ -366,10 +377,9 @@ class CSysMatrix { * \param[in] config - Definition of the particular problem. * \param[in] needTranspPtr - If "col_ptr" should be created, used for "SetDiagonalAsColumnSum". */ - void Initialize(unsigned long npoint, unsigned long npointdomain, - unsigned short nvar, unsigned short neqn, - bool EdgeConnect, CGeometry *geometry, - const CConfig *config, bool needTranspPtr = false, bool grad_mode = false); + void Initialize(unsigned long npoint, unsigned long npointdomain, unsigned short nvar, unsigned short neqn, + bool EdgeConnect, CGeometry* geometry, const CConfig* config, bool needTranspPtr = false, + bool grad_mode = false); /*! * \brief Sets to zero all the entries of the sparse matrix. @@ -387,21 +397,20 @@ class CSysMatrix { * \param[in] block_j - Column index. * \return Pointer to location in memory where the block starts. */ - FORCEINLINE const ScalarType *GetBlock(unsigned long block_i, unsigned long block_j) const { + FORCEINLINE const ScalarType* GetBlock(unsigned long block_i, unsigned long block_j) const { /*--- The position of the diagonal block is known which allows halving the search space. ---*/ - const auto end = (block_j( const_this.GetBlock(block_i, block_j) ); + return const_cast(const_this.GetBlock(block_i, block_j)); } /*! @@ -412,11 +421,11 @@ class CSysMatrix { * \param[in] jVar - Column of the block. * \return Value of the block entry. */ - FORCEINLINE ScalarType GetBlock(unsigned long block_i, unsigned long block_j, - unsigned short iVar, unsigned short jVar) const { + FORCEINLINE ScalarType GetBlock(unsigned long block_i, unsigned long block_j, unsigned short iVar, + unsigned short jVar) const { auto mat_ij = GetBlock(block_i, block_j); if (!mat_ij) return 0.0; - return mat_ij[iVar*nEqn+jVar]; + return mat_ij[iVar * nEqn + jVar]; } /*! @@ -427,16 +436,14 @@ class CSysMatrix { * \param[in] val_block - Block to set to A(i, j). * \param[in] alpha - Scale factor. */ - template::value> = 0> - inline void SetBlock(unsigned long block_i, unsigned long block_j, - const OtherType *val_block, OtherType alpha = 1.0) { - + template ::value> = 0> + inline void SetBlock(unsigned long block_i, unsigned long block_j, const OtherType* val_block, + OtherType alpha = 1.0) { auto mat_ij = GetBlock(block_i, block_j); if (!mat_ij) return; SU2_OMP_SIMD - for (auto iVar = 0ul; iVar < nVar*nEqn; ++iVar) { - mat_ij[iVar] = (Overwrite? ScalarType(0) : mat_ij[iVar]) + PassiveAssign(alpha * val_block[iVar]); + for (auto iVar = 0ul; iVar < nVar * nEqn; ++iVar) { + mat_ij[iVar] = (Overwrite ? ScalarType(0) : mat_ij[iVar]) + PassiveAssign(alpha * val_block[iVar]); } } @@ -447,10 +454,10 @@ class CSysMatrix { * \param[in] val_block - Block to set to A(i, j). * \param[in] alpha - Scale factor. */ - template::value> = 0> - inline void AddBlock(unsigned long block_i, unsigned long block_j, - const OtherType *val_block, OtherType alpha = 1.0) { - SetBlock(block_i, block_j, val_block, alpha); + template ::value> = 0> + inline void AddBlock(unsigned long block_i, unsigned long block_j, const OtherType* val_block, + OtherType alpha = 1.0) { + SetBlock(block_i, block_j, val_block, alpha); } /*! @@ -461,15 +468,14 @@ class CSysMatrix { * \param[in] val_block - Block to set to A(i, j). * \param[in] alpha - Scale factor. */ - template - inline void SetBlock(unsigned long block_i, unsigned long block_j, - const OtherType* const* val_block, OtherType alpha = 1.0) { - + template + inline void SetBlock(unsigned long block_i, unsigned long block_j, const OtherType* const* val_block, + OtherType alpha = 1.0) { auto mat_ij = GetBlock(block_i, block_j); if (!mat_ij) return; for (auto iVar = 0ul; iVar < nVar; ++iVar) { for (auto jVar = 0ul; jVar < nEqn; ++jVar) { - *mat_ij = (Overwrite? ScalarType(0) : *mat_ij) + PassiveAssign(alpha * val_block[iVar][jVar]); + *mat_ij = (Overwrite ? ScalarType(0) : *mat_ij) + PassiveAssign(alpha * val_block[iVar][jVar]); ++mat_ij; } } @@ -482,10 +488,10 @@ class CSysMatrix { * \param[in] val_block - Block to add to A(i, j). * \param[in] alpha - Scale factor. */ - template - inline void AddBlock(unsigned long block_i, unsigned long block_j, - const OtherType* const* val_block, OtherType alpha = 1.0) { - SetBlock(block_i, block_j, val_block, alpha); + template + inline void AddBlock(unsigned long block_i, unsigned long block_j, const OtherType* const* val_block, + OtherType alpha = 1.0) { + SetBlock(block_i, block_j, val_block, alpha); } /*! @@ -494,7 +500,7 @@ class CSysMatrix { * \param[in] block_j - Column index. * \param[in] val_block - Block to subtract to A(i, j). */ - template + template inline void SubtractBlock(unsigned long block_i, unsigned long block_j, const OtherType* const* val_block) { AddBlock(block_i, block_j, val_block, OtherType(-1)); } @@ -545,14 +551,13 @@ class CSysMatrix { * \param[in] block_j - Adds to ij, subs from jj. * \param[in] scale - Scale blocks during update (axpy type op). */ - template - inline void UpdateBlocks(unsigned long iEdge, unsigned long iPoint, unsigned long jPoint, - const MatrixType& block_i, const MatrixType& block_j, OtherType scale = 1) { - - ScalarType *bii = &matrix[dia_ptr[iPoint]*nVar*nEqn]; - ScalarType *bjj = &matrix[dia_ptr[jPoint]*nVar*nEqn]; - ScalarType *bij = &matrix[edge_ptr(iEdge,0)*nVar*nEqn]; - ScalarType *bji = &matrix[edge_ptr(iEdge,1)*nVar*nEqn]; + template + inline void UpdateBlocks(unsigned long iEdge, unsigned long iPoint, unsigned long jPoint, const MatrixType& block_i, + const MatrixType& block_j, OtherType scale = 1) { + ScalarType* bii = &matrix[dia_ptr[iPoint] * nVar * nEqn]; + ScalarType* bjj = &matrix[dia_ptr[jPoint] * nVar * nEqn]; + ScalarType* bij = &matrix[edge_ptr(iEdge, 0) * nVar * nEqn]; + ScalarType* bji = &matrix[edge_ptr(iEdge, 1) * nVar * nEqn]; unsigned long iVar, jVar, offset = 0; @@ -570,51 +575,50 @@ class CSysMatrix { /*! * \brief Short-hand for the "subtractive" version (sub from i* add to j*) of UpdateBlocks. */ - template + template inline void UpdateBlocksSub(unsigned long iEdge, unsigned long iPoint, unsigned long jPoint, const MatrixType& block_i, const MatrixType& block_j) { - UpdateBlocks(iEdge, iPoint, jPoint, block_i, block_j, -1); + UpdateBlocks(iEdge, iPoint, jPoint, block_i, block_j, -1); } /*! * \brief SIMD version, does the update for multiple edges and points. * \note Nothing is updated if the mask is 0. */ - template - FORCEINLINE void UpdateBlocks(simd::Array iEdge, simd::Array iPoint, simd::Array jPoint, - const MatTypeSIMD& block_i, const MatTypeSIMD& block_j, simd::Array mask = 1) { - + template + FORCEINLINE void UpdateBlocks(simd::Array iEdge, simd::Array iPoint, simd::Array jPoint, + const MatTypeSIMD& block_i, const MatTypeSIMD& block_j, simd::Array mask = 1) { static_assert(MatTypeSIMD::StaticSize, "This method requires static size blocks."); static_assert(MatTypeSIMD::IsRowMajor, "Block storage is not compatible with matrix."); constexpr size_t blkSz = MatTypeSIMD::StaticSize; - assert(blkSz == nVar*nEqn); + assert(blkSz == nVar * nEqn); /*--- "Transpose" the blocks, scale, and possibly convert types, * giving the compiler the chance to vectorize all of these. ---*/ ScalarType blk_i[N][blkSz], blk_j[N][blkSz]; - for (size_t i=0; i - inline void SetBlocks(unsigned long iEdge, const MatrixType& block_i, - const MatrixType& block_j, OtherType scale = 1) { - - ScalarType *bij = &matrix[edge_ptr(iEdge,0)*nVar*nEqn]; - ScalarType *bji = &matrix[edge_ptr(iEdge,1)*nVar*nEqn]; + template + inline void SetBlocks(unsigned long iEdge, const MatrixType& block_i, const MatrixType& block_j, + OtherType scale = 1) { + ScalarType* bij = &matrix[edge_ptr(iEdge, 0) * nVar * nEqn]; + ScalarType* bji = &matrix[edge_ptr(iEdge, 1) * nVar * nEqn]; unsigned long iVar, jVar, offset = 0; for (iVar = 0; iVar < nVar; iVar++) { for (jVar = 0; jVar < nEqn; jVar++) { - bij[offset] = (Overwrite? ScalarType(0) : bij[offset]) + PassiveAssign(block_j[iVar][jVar] * scale); - bji[offset] = (Overwrite? ScalarType(0) : bji[offset]) - PassiveAssign(block_i[iVar][jVar] * scale); + bij[offset] = (Overwrite ? ScalarType(0) : bij[offset]) + PassiveAssign(block_j[iVar][jVar] * scale); + bji[offset] = (Overwrite ? ScalarType(0) : bji[offset]) - PassiveAssign(block_i[iVar][jVar] * scale); ++offset; } } @@ -654,57 +657,56 @@ class CSysMatrix { /*! * \brief Short-hand for the "additive overwrite" version of SetBlocks. */ - template - inline void UpdateBlocks(unsigned long iEdge, const MatrixType& block_i, - const MatrixType& block_j, OtherType scale = 1) { - SetBlocks(iEdge, block_i, block_j, scale); + template + inline void UpdateBlocks(unsigned long iEdge, const MatrixType& block_i, const MatrixType& block_j, + OtherType scale = 1) { + SetBlocks(iEdge, block_i, block_j, scale); } /*! * \brief Short-hand for the "subtractive" version (sub from i* add to j*) of SetBlocks. */ - template + template inline void UpdateBlocksSub(unsigned long iEdge, const MatrixType& block_i, const MatrixType& block_j) { - SetBlocks(iEdge, block_i, block_j, -1); + SetBlocks(iEdge, block_i, block_j, -1); } /*! * \brief SIMD version, does the update for multiple edges. * \note Nothing is updated if the mask is 0. */ - template - FORCEINLINE void SetBlocks(simd::Array iEdge, const MatTypeSIMD& block_i, - const MatTypeSIMD& block_j, simd::Array mask = 1) { - + template + FORCEINLINE void SetBlocks(simd::Array iEdge, const MatTypeSIMD& block_i, const MatTypeSIMD& block_j, + simd::Array mask = 1) { static_assert(MatTypeSIMD::StaticSize, "This method requires static size blocks."); static_assert(MatTypeSIMD::IsRowMajor, "Block storage is not compatible with matrix."); constexpr size_t blkSz = MatTypeSIMD::StaticSize; - assert(blkSz == nVar*nEqn); + assert(blkSz == nVar * nEqn); /*--- "Transpose" the blocks, scale, and possibly convert types, * giving the compiler the chance to vectorize all of these. ---*/ ScalarType blk_i[N][blkSz], blk_j[N][blkSz]; - for (size_t i=0; i + template inline void SetBlock2Diag(unsigned long block_i, const OtherType& val_block, T alpha = 1.0) { - - auto mat_ii = &matrix[dia_ptr[block_i]*nVar*nEqn]; + auto mat_ii = &matrix[dia_ptr[block_i] * nVar * nEqn]; for (auto iVar = 0ul; iVar < nVar; iVar++) for (auto jVar = 0ul; jVar < nEqn; jVar++) { - *mat_ii = (Overwrite? ScalarType(0) : *mat_ii) + PassiveAssign(alpha * val_block[iVar][jVar]); + *mat_ii = (Overwrite ? ScalarType(0) : *mat_ii) + PassiveAssign(alpha * val_block[iVar][jVar]); ++mat_ii; } } @@ -734,15 +735,15 @@ class CSysMatrix { /*! * \brief Non overwrite version of SetBlock2Diag, also with scaling. */ - template + template inline void AddBlock2Diag(unsigned long block_i, const OtherType& val_block, T alpha = 1.0) { - SetBlock2Diag(block_i, val_block, alpha); + SetBlock2Diag(block_i, val_block, alpha); } /*! * \brief Short-hand to AddBlock2Diag with alpha = -1, i.e. subtracts from the current diagonal. */ - template + template inline void SubtractBlock2Diag(unsigned long block_i, const OtherType& val_block) { AddBlock2Diag(block_i, val_block, -1.0); } @@ -753,10 +754,10 @@ class CSysMatrix { * \param[in] block_i - Diagonal index. * \param[in] val_matrix - Value to add to the diagonal elements of A(i, i). */ - template + template inline void AddVal2Diag(unsigned long block_i, OtherType val_matrix) { for (auto iVar = 0ul; iVar < nVar; iVar++) - matrix[dia_ptr[block_i]*nVar*nVar + iVar*(nVar+1)] += PassiveAssign(val_matrix); + matrix[dia_ptr[block_i] * nVar * nVar + iVar * (nVar + 1)] += PassiveAssign(val_matrix); } /*! @@ -766,9 +767,9 @@ class CSysMatrix { * \param[in] iVar - Variable index. * \param[in] val - Value to add to the diagonal elements of A(i, i). */ - template + template inline void AddVal2Diag(unsigned long block_i, unsigned long iVar, OtherType val) { - matrix[dia_ptr[block_i]*nVar*nVar + iVar*(nVar+1)] += PassiveAssign(val); + matrix[dia_ptr[block_i] * nVar * nVar + iVar * (nVar + 1)] += PassiveAssign(val); } /*! @@ -777,18 +778,15 @@ class CSysMatrix { * \param[in] block_i - Diagonal index. * \param[in] val_matrix - Value to add to the diagonal elements of A(i, i). */ - template + template inline void SetVal2Diag(unsigned long block_i, OtherType val_matrix) { - - unsigned long iVar, index = dia_ptr[block_i]*nVar*nVar; + unsigned long iVar, index = dia_ptr[block_i] * nVar * nVar; /*--- Clear entire block before setting its diagonal. ---*/ SU2_OMP_SIMD - for (iVar = 0; iVar < nVar*nVar; iVar++) - matrix[index+iVar] = 0.0; + for (iVar = 0; iVar < nVar * nVar; iVar++) matrix[index + iVar] = 0.0; - for (iVar = 0; iVar < nVar; iVar++) - matrix[index+iVar*(nVar+1)] = PassiveAssign(val_matrix); + for (iVar = 0; iVar < nVar; iVar++) matrix[index + iVar * (nVar + 1)] = PassiveAssign(val_matrix); } /*! @@ -803,14 +801,14 @@ class CSysMatrix { * \param[in] x_i - Values to enforce (nVar sized). * \param[in,out] b - The rhs vector (b := b - A_{*,i} * x_i; b_i = x_i). */ - template - void EnforceSolutionAtNode(unsigned long node_i, const OtherType *x_i, CSysVector & b); + template + void EnforceSolutionAtNode(unsigned long node_i, const OtherType* x_i, CSysVector& b); /*! * \brief Version of EnforceSolutionAtNode for a single degree of freedom. */ - template - void EnforceSolutionAtDOF(unsigned long node_i, unsigned long iVar, OtherType x_i, CSysVector & b); + template + void EnforceSolutionAtDOF(unsigned long node_i, unsigned long iVar, OtherType x_i, CSysVector& b); /*! * \brief Sets the diagonal entries of the matrix as the sum of the blocks in the corresponding column. @@ -837,8 +835,8 @@ class CSysMatrix { * \param[in] config - Definition of the particular problem. * \param[out] prod - Result of the product. */ - void MatrixVectorProduct(const CSysVector & vec, CSysVector & prod, - CGeometry *geometry, const CConfig *config) const; + void MatrixVectorProduct(const CSysVector& vec, CSysVector& prod, CGeometry* geometry, + const CConfig* config) const; /*! * \brief Build the Jacobi preconditioner. @@ -852,8 +850,8 @@ class CSysMatrix { * \param[in] geometry - Geometrical definition of the problem. * \param[in] config - Definition of the particular problem. */ - void ComputeJacobiPreconditioner(const CSysVector & vec, CSysVector & prod, - CGeometry *geometry, const CConfig *config) const; + void ComputeJacobiPreconditioner(const CSysVector& vec, CSysVector& prod, CGeometry* geometry, + const CConfig* config) const; /*! * \brief Build the ILU preconditioner. @@ -867,31 +865,31 @@ class CSysMatrix { * \param[in] geometry - Geometrical definition of the problem. * \param[in] config - Definition of the particular problem. */ - void ComputeILUPreconditioner(const CSysVector & vec, CSysVector & prod, - CGeometry *geometry, const CConfig *config) const; + void ComputeILUPreconditioner(const CSysVector& vec, CSysVector& prod, CGeometry* geometry, + const CConfig* config) const; /*! * \brief Multiply CSysVector by the preconditioner * \param[in] vec - CSysVector to be multiplied by the preconditioner. * \param[out] prod - Result of the product A*vec. */ - void ComputeLU_SGSPreconditioner(const CSysVector & vec, CSysVector & prod, - CGeometry *geometry, const CConfig *config) const; + void ComputeLU_SGSPreconditioner(const CSysVector& vec, CSysVector& prod, CGeometry* geometry, + const CConfig* config) const; /*! * \brief Build the Linelet preconditioner. * \param[in] geometry - Geometrical definition of the problem. * \param[in] config - Definition of the particular problem. */ - void BuildLineletPreconditioner(const CGeometry *geometry, const CConfig *config); + void BuildLineletPreconditioner(const CGeometry* geometry, const CConfig* config); /*! * \brief Multiply CSysVector by the preconditioner * \param[in] vec - CSysVector to be multiplied by the preconditioner. * \param[out] prod - Result of the product A*vec. */ - void ComputeLineletPreconditioner(const CSysVector & vec, CSysVector & prod, - CGeometry *geometry, const CConfig *config) const; + void ComputeLineletPreconditioner(const CSysVector& vec, CSysVector& prod, + CGeometry* geometry, const CConfig* config) const; /*! * \brief Compute the linear residual. @@ -899,8 +897,8 @@ class CSysMatrix { * \param[in] f - Right hand side (b). * \param[out] res - Residual (Ax-b). */ - void ComputeResidual(const CSysVector & sol, const CSysVector & f, - CSysVector & res) const; + void ComputeResidual(const CSysVector& sol, const CSysVector& f, + CSysVector& res) const; /*! * \brief Factorize matrix using PaStiX. @@ -908,7 +906,7 @@ class CSysMatrix { * \param[in] config - Definition of the particular problem. * \param[in] kind_fact - Type of factorization. */ - void BuildPastixPreconditioner(CGeometry *geometry, const CConfig *config, unsigned short kind_fact); + void BuildPastixPreconditioner(CGeometry* geometry, const CConfig* config, unsigned short kind_fact); /*! * \brief Apply the PaStiX factorization to CSysVec. @@ -917,7 +915,6 @@ class CSysMatrix { * \param[in] geometry - Geometrical definition of the problem. * \param[in] config - Definition of the particular problem. */ - void ComputePastixPreconditioner(const CSysVector & vec, CSysVector & prod, - CGeometry *geometry, const CConfig *config) const; - + void ComputePastixPreconditioner(const CSysVector& vec, CSysVector& prod, CGeometry* geometry, + const CConfig* config) const; }; diff --git a/Common/include/linear_algebra/CSysMatrix.inl b/Common/include/linear_algebra/CSysMatrix.inl index 139a6b0f45b..9fe0626119c 100644 --- a/Common/include/linear_algebra/CSysMatrix.inl +++ b/Common/include/linear_algebra/CSysMatrix.inl @@ -32,19 +32,18 @@ #include "CSysMatrix.hpp" -template -FORCEINLINE ScalarType *CSysMatrix::GetBlock_ILUMatrix(unsigned long block_i, unsigned long block_j) { +template +FORCEINLINE ScalarType* CSysMatrix::GetBlock_ILUMatrix(unsigned long block_i, unsigned long block_j) { /*--- The position of the diagonal block is known which allows halving the search space. ---*/ - const auto end = (block_j -FORCEINLINE void CSysMatrix::SetBlock_ILUMatrix(unsigned long block_i, unsigned long block_j, ScalarType *val_block) { - +template +FORCEINLINE void CSysMatrix::SetBlock_ILUMatrix(unsigned long block_i, unsigned long block_j, + ScalarType* val_block) { auto ilu_ij = GetBlock_ILUMatrix(block_i, block_j); if (!ilu_ij) return; MatrixCopy(val_block, ilu_ij); @@ -52,8 +51,8 @@ FORCEINLINE void CSysMatrix::SetBlock_ILUMatrix(unsigned long block_ namespace { -template -FORCEINLINE void gemv_impl(unsigned long n, unsigned long m, const T *a, const T *b, T *c) { +template +FORCEINLINE void gemv_impl(unsigned long n, unsigned long m, const T* a, const T* b, T* c) { /*--- This is a templated version of GEMV with the constants as boolean template parameters so that they can be optimized away at compilation. @@ -62,158 +61,151 @@ FORCEINLINE void gemv_impl(unsigned long n, unsigned long m, const T *a, const T if (!transp) { for (auto i = 0ul; i < n; i++) { if (!beta) c[i] = 0.0; - for (auto j = 0ul; j < m; j++) - c[i] += (alpha? 1 : -1) * a[i*m+j] * b[j]; + for (auto j = 0ul; j < m; j++) c[i] += (alpha ? 1 : -1) * a[i * m + j] * b[j]; } } else { - if (!beta) for (auto j = 0ul; j < m; j++) c[j] = 0.0; + if (!beta) + for (auto j = 0ul; j < m; j++) c[j] = 0.0; for (auto i = 0ul; i < n; i++) - for (auto j = 0ul; j < m; j++) - c[j] += (alpha? 1 : -1) * a[i*n+j] * b[i]; + for (auto j = 0ul; j < m; j++) c[j] += (alpha ? 1 : -1) * a[i * n + j] * b[i]; } } -template -FORCEINLINE void gemm_impl(unsigned long n, const T *a, const T *b, T *c) { +template +FORCEINLINE void gemm_impl(unsigned long n, const T* a, const T* b, T* c) { /*--- Same deal as for GEMV but here only the type is templated. ---*/ unsigned long i, j, k; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { - c[i*n+j] = 0.0; - for (k = 0; k < n; k++) - c[i*n+j] += a[i*n+k] * b[k*n+j]; + c[i * n + j] = 0.0; + for (k = 0; k < n; k++) c[i * n + j] += a[i * n + k] * b[k * n + j]; } } } -} // namespace +} // namespace -#define __MATVECPROD_SIGNATURE__(TYPE,NAME) \ -FORCEINLINE void CSysMatrix::NAME(const TYPE *matrix, const TYPE *vector, TYPE *product) const +#define __MATVECPROD_SIGNATURE__(TYPE, NAME) \ + FORCEINLINE void CSysMatrix::NAME(const TYPE* matrix, const TYPE* vector, TYPE* product) const -#define MATVECPROD_SIGNATURE(NAME) template __MATVECPROD_SIGNATURE__(ScalarType,NAME) +#define MATVECPROD_SIGNATURE(NAME) \ + template \ + __MATVECPROD_SIGNATURE__(ScalarType, NAME) #if !defined(USE_MKL) -MATVECPROD_SIGNATURE( MatrixVectorProduct ) { +MATVECPROD_SIGNATURE(MatrixVectorProduct) { /*--- Without MKL (default) picture copying the body of gemv_impl here and resolving the conditionals at compilation. ---*/ - gemv_impl(nVar, nEqn, matrix, vector, product); + gemv_impl(nVar, nEqn, matrix, vector, product); } -MATVECPROD_SIGNATURE( MatrixVectorProductAdd ) { - gemv_impl(nVar, nEqn, matrix, vector, product); +MATVECPROD_SIGNATURE(MatrixVectorProductAdd) { + gemv_impl(nVar, nEqn, matrix, vector, product); } -MATVECPROD_SIGNATURE( MatrixVectorProductSub ) { - gemv_impl(nVar, nEqn, matrix, vector, product); +MATVECPROD_SIGNATURE(MatrixVectorProductSub) { + gemv_impl(nVar, nEqn, matrix, vector, product); } -template -FORCEINLINE void CSysMatrix::MatrixMatrixProduct(const ScalarType *matrix_a, - const ScalarType *matrix_b, ScalarType *product) const { +template +FORCEINLINE void CSysMatrix::MatrixMatrixProduct(const ScalarType* matrix_a, const ScalarType* matrix_b, + ScalarType* product) const { gemm_impl(nVar, matrix_a, matrix_b, product); } #else -MATVECPROD_SIGNATURE( MatrixVectorProduct ) { +MATVECPROD_SIGNATURE(MatrixVectorProduct) { /*--- With MKL we use the just-in-time kernels instead of the naive implementation. ---*/ MatrixVectorProductKernelBetaZero(MatrixVectorProductJitterBetaZero, const_cast(vector), - const_cast(matrix), product ); + const_cast(matrix), product); } -MATVECPROD_SIGNATURE( MatrixVectorProductAdd ) { +MATVECPROD_SIGNATURE(MatrixVectorProductAdd) { MatrixVectorProductKernelBetaOne(MatrixVectorProductJitterBetaOne, const_cast(vector), - const_cast(matrix), product ); + const_cast(matrix), product); } -MATVECPROD_SIGNATURE( MatrixVectorProductSub ) { +MATVECPROD_SIGNATURE(MatrixVectorProductSub) { MatrixVectorProductKernelAlphaMinusOne(MatrixVectorProductJitterAlphaMinusOne, const_cast(vector), - const_cast(matrix), product ); + const_cast(matrix), product); } -template -FORCEINLINE void CSysMatrix::MatrixMatrixProduct(const ScalarType *matrix_a, - const ScalarType *matrix_b, ScalarType *product) const { +template +FORCEINLINE void CSysMatrix::MatrixMatrixProduct(const ScalarType* matrix_a, const ScalarType* matrix_b, + ScalarType* product) const { MatrixMatrixProductKernel(MatrixMatrixProductJitter, const_cast(matrix_a), - const_cast(matrix_b), product ); + const_cast(matrix_b), product); } #endif #undef MATVECPROD_SIGNATURE #undef __MATVECPROD_SIGNATURE__ -template +template FORCEINLINE void CSysMatrix::Gauss_Elimination(unsigned long block_i, ScalarType* rhs) const { - /*--- Copy block, as the algorithm modifies the matrix ---*/ - ScalarType block[MAXNVAR*MAXNVAR]; - MatrixCopy(&matrix[dia_ptr[block_i]*nVar*nVar], block); + ScalarType block[MAXNVAR * MAXNVAR]; + MatrixCopy(&matrix[dia_ptr[block_i] * nVar * nVar], block); Gauss_Elimination(block, rhs); } -template -FORCEINLINE void CSysMatrix::InverseDiagonalBlock(unsigned long block_i, ScalarType *invBlock) const { - +template +FORCEINLINE void CSysMatrix::InverseDiagonalBlock(unsigned long block_i, ScalarType* invBlock) const { /*--- Copy block, as the algorithm modifies the matrix ---*/ - ScalarType block[MAXNVAR*MAXNVAR]; - MatrixCopy(&matrix[dia_ptr[block_i]*nVar*nVar], block); + ScalarType block[MAXNVAR * MAXNVAR]; + MatrixCopy(&matrix[dia_ptr[block_i] * nVar * nVar], block); MatrixInverse(block, invBlock); } -template -FORCEINLINE void CSysMatrix::InverseDiagonalBlock_ILUMatrix(unsigned long block_i, ScalarType *invBlock) const { - +template +FORCEINLINE void CSysMatrix::InverseDiagonalBlock_ILUMatrix(unsigned long block_i, + ScalarType* invBlock) const { /*--- Copy block, as the algorithm modifies the matrix ---*/ - ScalarType block[MAXNVAR*MAXNVAR]; - MatrixCopy(&ILU_matrix[dia_ptr_ilu[block_i]*nVar*nVar], block); + ScalarType block[MAXNVAR * MAXNVAR]; + MatrixCopy(&ILU_matrix[dia_ptr_ilu[block_i] * nVar * nVar], block); MatrixInverse(block, invBlock); } -template -FORCEINLINE void CSysMatrix::RowProduct(const CSysVector & vec, - unsigned long row_i, ScalarType *prod) const { - for (auto iVar = 0ul; iVar < nVar; iVar++) - prod[iVar] = 0.0; +template +FORCEINLINE void CSysMatrix::RowProduct(const CSysVector& vec, unsigned long row_i, + ScalarType* prod) const { + for (auto iVar = 0ul; iVar < nVar; iVar++) prod[iVar] = 0.0; - for (auto index = row_ptr[row_i]; index < row_ptr[row_i+1]; index++) { + for (auto index = row_ptr[row_i]; index < row_ptr[row_i + 1]; index++) { auto col_j = col_ind[index]; - MatrixVectorProductAdd(&matrix[index*nVar*nEqn], &vec[col_j*nEqn], prod); + MatrixVectorProductAdd(&matrix[index * nVar * nEqn], &vec[col_j * nEqn], prod); } } -template -FORCEINLINE void CSysMatrix::UpperProduct(const CSysVector & vec, unsigned long row_i, - unsigned long col_ub, ScalarType *prod) const { - for (auto iVar = 0ul; iVar < nVar; iVar++) - prod[iVar] = 0.0; +template +FORCEINLINE void CSysMatrix::UpperProduct(const CSysVector& vec, unsigned long row_i, + unsigned long col_ub, ScalarType* prod) const { + for (auto iVar = 0ul; iVar < nVar; iVar++) prod[iVar] = 0.0; - for (auto index = dia_ptr[row_i]+1; index < row_ptr[row_i+1]; index++) { + for (auto index = dia_ptr[row_i] + 1; index < row_ptr[row_i + 1]; index++) { auto col_j = col_ind[index]; /*--- Always include halos. ---*/ if (col_j < col_ub || col_j >= nPointDomain) - MatrixVectorProductAdd(&matrix[index*nVar*nEqn], &vec[col_j*nEqn], prod); + MatrixVectorProductAdd(&matrix[index * nVar * nEqn], &vec[col_j * nEqn], prod); } } -template -FORCEINLINE void CSysMatrix::LowerProduct(const CSysVector & vec, unsigned long row_i, - unsigned long col_lb, ScalarType *prod) const { - for (auto iVar = 0ul; iVar < nVar; iVar++) - prod[iVar] = 0.0; +template +FORCEINLINE void CSysMatrix::LowerProduct(const CSysVector& vec, unsigned long row_i, + unsigned long col_lb, ScalarType* prod) const { + for (auto iVar = 0ul; iVar < nVar; iVar++) prod[iVar] = 0.0; for (auto index = row_ptr[row_i]; index < dia_ptr[row_i]; index++) { auto col_j = col_ind[index]; - if (col_j >= col_lb) - MatrixVectorProductAdd(&matrix[index*nVar*nEqn], &vec[col_j*nEqn], prod); + if (col_j >= col_lb) MatrixVectorProductAdd(&matrix[index * nVar * nEqn], &vec[col_j * nEqn], prod); } } -template -FORCEINLINE void CSysMatrix::DiagonalProduct(const CSysVector & vec, - unsigned long row_i, ScalarType *prod) const { - - MatrixVectorProduct(&matrix[dia_ptr[row_i]*nVar*nEqn], &vec[row_i*nEqn], prod); +template +FORCEINLINE void CSysMatrix::DiagonalProduct(const CSysVector& vec, unsigned long row_i, + ScalarType* prod) const { + MatrixVectorProduct(&matrix[dia_ptr[row_i] * nVar * nEqn], &vec[row_i * nEqn], prod); } diff --git a/Common/include/linear_algebra/CSysSolve.hpp b/Common/include/linear_algebra/CSysSolve.hpp index 6c214ee4b29..0a5ed8f52a0 100644 --- a/Common/include/linear_algebra/CSysSolve.hpp +++ b/Common/include/linear_algebra/CSysSolve.hpp @@ -42,13 +42,16 @@ class CConfig; class CGeometry; -template class CSysMatrix; -template class CMatrixVectorProduct; -template class CPreconditioner; +template +class CSysMatrix; +template +class CMatrixVectorProduct; +template +class CPreconditioner; /*--- Relative tolerance, target residual is tol*||b-Ax||, * Absolute tolerance, target residual is tol*||b||. ---*/ -enum class LinearToleranceType {RELATIVE, ABSOLUTE}; +enum class LinearToleranceType { RELATIVE, ABSOLUTE }; /*! * \class CSysSolve @@ -64,10 +67,9 @@ enum class LinearToleranceType {RELATIVE, ABSOLUTE}; * Beware of writes to class member variables, for example "Residual" should only * be modified by one thread. */ -template +template class CSysSolve { - -public: + public: /*--- Some aliases for simplicity. ---*/ using Scalar = ScalarType; using VectorType = CSysVector; @@ -75,37 +77,43 @@ class CSysSolve { using ProductType = CMatrixVectorProduct; using PrecondType = CPreconditioner; -private: - const ScalarType eps; /*!< \brief Machine epsilon used in this class. */ - ScalarType Residual=1e-20; /*!< \brief Residual at the end of a call to Solve or Solve_b. */ - unsigned long Iterations=0;/*!< \brief Iterations done in Solve or Solve_b. */ + private: + const ScalarType eps; /*!< \brief Machine epsilon used in this class. */ + ScalarType Residual = 1e-20; /*!< \brief Residual at the end of a call to Solve or Solve_b. */ + unsigned long Iterations = 0; /*!< \brief Iterations done in Solve or Solve_b. */ - LINEAR_SOLVER_MODE lin_sol_mode; /*!< \brief Type of operation for the linear system solver, changes the source of solver options. */ + LINEAR_SOLVER_MODE + lin_sol_mode; /*!< \brief Type of operation for the linear system solver, changes the source of solver options. */ mutable bool cg_ready; /*!< \brief Indicate if memory used by CG is allocated. */ mutable bool bcg_ready; /*!< \brief Indicate if memory used by BCGSTAB is allocated. */ mutable bool smooth_ready; /*!< \brief Indicate if memory used by SMOOTHER is allocated. */ - mutable VectorType r; /*!< \brief Residual in CG and BCGSTAB. */ - mutable VectorType A_x; /*!< \brief Result of matrix-vector product in CG and BCGSTAB. */ - mutable VectorType p; /*!< \brief Direction in CG and BCGSTAB. */ - mutable VectorType z; /*!< \brief Preconditioned residual/direction in CG/BCGSTAB. */ + mutable VectorType r; /*!< \brief Residual in CG and BCGSTAB. */ + mutable VectorType A_x; /*!< \brief Result of matrix-vector product in CG and BCGSTAB. */ + mutable VectorType p; /*!< \brief Direction in CG and BCGSTAB. */ + mutable VectorType z; /*!< \brief Preconditioned residual/direction in CG/BCGSTAB. */ - mutable VectorType r_0; /*!< \brief The "arbitrary" vector in BCGSTAB. */ - mutable VectorType v; /*!< \brief BCGSTAB "v" vector (v = A * M^-1 * p). */ + mutable VectorType r_0; /*!< \brief The "arbitrary" vector in BCGSTAB. */ + mutable VectorType v; /*!< \brief BCGSTAB "v" vector (v = A * M^-1 * p). */ - mutable std::vector W; /*!< \brief Large matrix used by FGMRES, w^i+1 = A * z^i. */ - mutable std::vector Z; /*!< \brief Large matrix used by FGMRES, preconditioned W. */ + mutable std::vector W; /*!< \brief Large matrix used by FGMRES, w^i+1 = A * z^i. */ + mutable std::vector Z; /*!< \brief Large matrix used by FGMRES, preconditioned W. */ - VectorType LinSysSol_tmp; /*!< \brief Temporary used when it is necessary to interface between active and passive types. */ - VectorType LinSysRes_tmp; /*!< \brief Temporary used when it is necessary to interface between active and passive types. */ - VectorType* LinSysSol_ptr; /*!< \brief Pointer to appropriate LinSysSol (set to original or temporary in call to Solve). */ - const VectorType* LinSysRes_ptr; /*!< \brief Pointer to appropriate LinSysRes (set to original or temporary in call to Solve). */ + VectorType + LinSysSol_tmp; /*!< \brief Temporary used when it is necessary to interface between active and passive types. */ + VectorType + LinSysRes_tmp; /*!< \brief Temporary used when it is necessary to interface between active and passive types. */ + VectorType* + LinSysSol_ptr; /*!< \brief Pointer to appropriate LinSysSol (set to original or temporary in call to Solve). */ + const VectorType* + LinSysRes_ptr; /*!< \brief Pointer to appropriate LinSysRes (set to original or temporary in call to Solve). */ - LinearToleranceType tol_type = LinearToleranceType::ABSOLUTE; /*!< \brief How the linear solvers interpret the tolerance. */ - bool xIsZero = false; /*!< \brief If true assume the initial solution is always 0. */ - bool recomputeRes = false; /*!< \brief Recompute the residual after inner iterations, if monitoring. */ - unsigned long monitorFreq = 10; /*!< \brief Monitoring frequency. */ + LinearToleranceType tol_type = + LinearToleranceType::ABSOLUTE; /*!< \brief How the linear solvers interpret the tolerance. */ + bool xIsZero = false; /*!< \brief If true assume the initial solution is always 0. */ + bool recomputeRes = false; /*!< \brief Recompute the residual after inner iterations, if monitoring. */ + unsigned long monitorFreq = 10; /*!< \brief Monitoring frequency. */ /*! * \brief sign transfer function @@ -128,7 +136,7 @@ class CSysSolve { * \param[in,out] h1 - first element of 2x1 vector being transformed * \param[in,out] h2 - second element of 2x1 vector being transformed */ - void ApplyGivens(ScalarType s, ScalarType c, ScalarType & h1, ScalarType & h2) const; + void ApplyGivens(ScalarType s, ScalarType c, ScalarType& h1, ScalarType& h2) const; /*! * \brief generates the Givens rotation matrix for a given 2-vector @@ -140,7 +148,7 @@ class CSysSolve { * Based on givens() of SPARSKIT, which is based on p.202 of * "Matrix Computations" by Golub and van Loan. */ - void GenerateGivens(ScalarType & dx, ScalarType & dy, ScalarType & s, ScalarType & c) const; + void GenerateGivens(ScalarType& dx, ScalarType& dy, ScalarType& s, ScalarType& c) const; /*! * \brief finds the solution of the upper triangular system Hsbg*x = rhs @@ -153,8 +161,8 @@ class CSysSolve { * \pre the upper Hessenberg matrix has been transformed into a * triangular matrix. */ - void SolveReduced(int n, const su2matrix& Hsbg, - const su2vector& rhs, su2vector& x) const; + void SolveReduced(int n, const su2matrix& Hsbg, const su2vector& rhs, + su2vector& x) const; /*! * \brief Modified Gram-Schmidt orthogonalization @@ -173,7 +181,7 @@ class CSysSolve { * vector is kept in nrm0 and updated after operating with each vector * */ - void ModGramSchmidt(int i, su2matrix& Hsbg, std::vector & w) const; + void ModGramSchmidt(int i, su2matrix& Hsbg, std::vector& w) const; /*! * \brief writes header information for a CSysSolve residual history @@ -216,9 +224,8 @@ class CSysSolve { * \param[in] LinSysRes - Linear system residual * \param[in,out] LinSysSol - Linear system solution */ - template::value> = 0> + template ::value> = 0> void HandleTemporariesIn(const CSysVector& LinSysRes, CSysVector& LinSysSol) { - /*--- Set the pointers. ---*/ BEGIN_SU2_OMP_SAFE_GLOBAL_ACCESS { LinSysRes_ptr = &LinSysRes; @@ -233,9 +240,8 @@ class CSysSolve { * \param[in] LinSysRes - Linear system residual * \param[in,out] LinSysSol - Linear system solution */ - template::value> = 0> + template ::value> = 0> void HandleTemporariesIn(const CSysVector& LinSysRes, CSysVector& LinSysSol) { - /*--- Copy data, the solution is also copied as it serves as initial condition. ---*/ LinSysRes_tmp.PassiveCopy(LinSysRes); LinSysSol_tmp.PassiveCopy(LinSysSol); @@ -253,9 +259,8 @@ class CSysSolve { * \note Same type specialization, temporary variables are not required. * \param[out] LinSysSol - Linear system solution */ - template::value> = 0> + template ::value> = 0> void HandleTemporariesOut(CSysVector& LinSysSol) { - /*--- Reset the pointers. ---*/ BEGIN_SU2_OMP_SAFE_GLOBAL_ACCESS { LinSysRes_ptr = nullptr; @@ -269,9 +274,8 @@ class CSysSolve { * \note Different type specialization, copy data from the temporary solution vector. * \param[out] LinSysSol - Linear system solution */ - template::value> = 0> + template ::value> = 0> void HandleTemporariesOut(CSysVector& LinSysSol) { - /*--- Copy data, only the temporary solution needs to be copied. ---*/ LinSysSol.PassiveCopy(LinSysSol_tmp); @@ -283,8 +287,7 @@ class CSysSolve { END_SU2_OMP_SAFE_GLOBAL_ACCESS } -public: - + public: /*! * \brief default constructor of the class. * \param[in] linear_solver_mode - enum, to let CSysSolve know in what context it is @@ -302,9 +305,9 @@ class CSysSolve { * \param[in] monitoring - turn on priting residuals from solver to screen. * \param[in] config - Definition of the particular problem. */ - unsigned long CG_LinSolver(const VectorType & b, VectorType & x, const ProductType & mat_vec, - const PrecondType & precond, ScalarType tol, unsigned long m, - ScalarType & residual, bool monitoring, const CConfig *config) const; + unsigned long CG_LinSolver(const VectorType& b, VectorType& x, const ProductType& mat_vec, const PrecondType& precond, + ScalarType tol, unsigned long m, ScalarType& residual, bool monitoring, + const CConfig* config) const; /*! * \brief Flexible Generalized Minimal Residual method @@ -318,16 +321,16 @@ class CSysSolve { * \param[in] monitoring - turn on priting residuals from solver to screen. * \param[in] config - Definition of the particular problem. */ - unsigned long FGMRES_LinSolver(const VectorType & b, VectorType & x, const ProductType & mat_vec, - const PrecondType & precond, ScalarType tol, unsigned long m, - ScalarType & residual, bool monitoring, const CConfig *config) const; + unsigned long FGMRES_LinSolver(const VectorType& b, VectorType& x, const ProductType& mat_vec, + const PrecondType& precond, ScalarType tol, unsigned long m, ScalarType& residual, + bool monitoring, const CConfig* config) const; /*! * \brief Flexible Generalized Minimal Residual method with restarts (frequency comes from config). */ - unsigned long RFGMRES_LinSolver(const VectorType & b, VectorType & x, const ProductType & mat_vec, - const PrecondType & precond, ScalarType tol, unsigned long m, - ScalarType & residual, bool monitoring, const CConfig *config); + unsigned long RFGMRES_LinSolver(const VectorType& b, VectorType& x, const ProductType& mat_vec, + const PrecondType& precond, ScalarType tol, unsigned long m, ScalarType& residual, + bool monitoring, const CConfig* config); /*! * \brief Biconjugate Gradient Stabilized Method (BCGSTAB) @@ -341,9 +344,9 @@ class CSysSolve { * \param[in] monitoring - turn on priting residuals from solver to screen. * \param[in] config - Definition of the particular problem. */ - unsigned long BCGSTAB_LinSolver(const VectorType & b, VectorType & x, const ProductType & mat_vec, - const PrecondType & precond, ScalarType tol, unsigned long m, - ScalarType & residual, bool monitoring, const CConfig *config) const; + unsigned long BCGSTAB_LinSolver(const VectorType& b, VectorType& x, const ProductType& mat_vec, + const PrecondType& precond, ScalarType tol, unsigned long m, ScalarType& residual, + bool monitoring, const CConfig* config) const; /*! * \brief Generic smoother (modified Richardson iteration with preconditioner) @@ -357,9 +360,9 @@ class CSysSolve { * \param[in] monitoring - turn on priting residuals from solver to screen. * \param[in] config - Definition of the particular problem. */ - unsigned long Smoother_LinSolver(const VectorType & b, VectorType & x, const ProductType & mat_vec, - const PrecondType & precond, ScalarType tol, unsigned long m, - ScalarType & residual, bool monitoring, const CConfig *config) const; + unsigned long Smoother_LinSolver(const VectorType& b, VectorType& x, const ProductType& mat_vec, + const PrecondType& precond, ScalarType tol, unsigned long m, ScalarType& residual, + bool monitoring, const CConfig* config) const; /*! * \brief Solve the linear system using a Krylov subspace method @@ -369,8 +372,8 @@ class CSysSolve { * \param[in] geometry - Geometrical definition of the problem. * \param[in] config - Definition of the particular problem. */ - unsigned long Solve(MatrixType & Jacobian, const CSysVector & LinSysRes, CSysVector & LinSysSol, - CGeometry *geometry, const CConfig *config); + unsigned long Solve(MatrixType& Jacobian, const CSysVector& LinSysRes, CSysVector& LinSysSol, + CGeometry* geometry, const CConfig* config); /*! * \brief Solve the adjoint linear system using a Krylov subspace method @@ -381,8 +384,8 @@ class CSysSolve { * \param[in] config - Definition of the particular problem. * \param[in] directCall - If this method is called directly, or in AD context. */ - unsigned long Solve_b(MatrixType & Jacobian, const CSysVector & LinSysRes, CSysVector & LinSysSol, - CGeometry *geometry, const CConfig *config, const bool directCall = true); + unsigned long Solve_b(MatrixType& Jacobian, const CSysVector& LinSysRes, CSysVector& LinSysSol, + CGeometry* geometry, const CConfig* config, const bool directCall = true); /*! * \brief Get the number of iterations. @@ -399,21 +402,20 @@ class CSysSolve { /*! * \brief Set the type of the tolerance for stoping the linear solvers (RELATIVE or ABSOLUTE). */ - inline void SetToleranceType(LinearToleranceType type) {tol_type = type;} + inline void SetToleranceType(LinearToleranceType type) { tol_type = type; } /*! * \brief Assume the initial solution is 0 to save one product, or don't. */ - inline void SetxIsZero(bool isZero) {xIsZero = isZero;} + inline void SetxIsZero(bool isZero) { xIsZero = isZero; } /*! * \brief Set whether to recompute residuals at the end (while monitoring only). */ - inline void SetRecomputeResidual(bool recompRes) {recomputeRes = recompRes;} + inline void SetRecomputeResidual(bool recompRes) { recomputeRes = recompRes; } /*! * \brief Set the screen output frequency during monitoring. */ - inline void SetMonitoringFrequency(bool frequency) {monitorFreq = frequency;} - + inline void SetMonitoringFrequency(bool frequency) { monitorFreq = frequency; } }; diff --git a/Common/include/linear_algebra/CSysSolve_b.hpp b/Common/include/linear_algebra/CSysSolve_b.hpp index 7827942f14a..22a91391a32 100644 --- a/Common/include/linear_algebra/CSysSolve_b.hpp +++ b/Common/include/linear_algebra/CSysSolve_b.hpp @@ -30,10 +30,9 @@ #include "../basic_types/datatype_structure.hpp" #ifdef CODI_REVERSE_TYPE -template +template struct CSysSolve_b { - static void Solve_b(const su2double::Real* x, su2double::Real* x_b, size_t m, - const su2double::Real* y, const su2double::Real* y_b, size_t n, - codi::ExternalFunctionUserData* d); + static void Solve_b(const su2double::Real* x, su2double::Real* x_b, size_t m, const su2double::Real* y, + const su2double::Real* y_b, size_t n, codi::ExternalFunctionUserData* d); }; #endif diff --git a/Common/include/linear_algebra/CSysVector.hpp b/Common/include/linear_algebra/CSysVector.hpp index ea6755adeae..2c20e1317b6 100644 --- a/Common/include/linear_algebra/CSysVector.hpp +++ b/Common/include/linear_algebra/CSysVector.hpp @@ -45,9 +45,9 @@ */ #ifdef HAVE_OMP #ifdef HAVE_OMP_SIMD -#define CSYSVEC_PARFOR SU2_OMP_FOR_(simd schedule(static,omp_chunk_size) SU2_NOWAIT) +#define CSYSVEC_PARFOR SU2_OMP_FOR_(simd schedule(static, omp_chunk_size) SU2_NOWAIT) #else -#define CSYSVEC_PARFOR SU2_OMP_FOR_(schedule(static,omp_chunk_size) SU2_NOWAIT) +#define CSYSVEC_PARFOR SU2_OMP_FOR_(schedule(static, omp_chunk_size) SU2_NOWAIT) #endif #define END_CSYSVEC_PARFOR END_SU2_OMP_FOR #else @@ -67,9 +67,9 @@ class CSysVector : public VecExpr::CVecExpr, ScalarType> unsigned long omp_chunk_size = OMP_MAX_SIZE; /*!< \brief Static chunk size used in loops. */ ScalarType* vec_val = nullptr; /*!< \brief Storage, 64 byte aligned (do not use normal new/delete). */ - unsigned long nElm = 0; /*!< \brief Total number of elements (or number elements on this processor). */ - unsigned long nElmDomain = 0; /*!< \brief Total number of elements without Ghost cells. */ - unsigned long nVar = 1; /*!< \brief Number of elements in a block. */ + unsigned long nElm = 0; /*!< \brief Total number of elements (or number elements on this processor). */ + unsigned long nElmDomain = 0; /*!< \brief Total number of elements without Ghost cells. */ + unsigned long nVar = 1; /*!< \brief Number of elements in a block. */ /*! * \brief Generic initialization from a scalar or array. @@ -187,7 +187,8 @@ class CSysVector : public VecExpr::CVecExpr, ScalarType> /*--- check if self-assignment, otherwise perform deep copy ---*/ if ((const void*)this == (const void*)&other) return; - SU2_OMP_SAFE_GLOBAL_ACCESS(Initialize(other.GetNBlk(), other.GetNBlkDomain(), other.GetNVar(), nullptr, true, false);) + SU2_OMP_SAFE_GLOBAL_ACCESS( + Initialize(other.GetNBlk(), other.GetNBlkDomain(), other.GetNVar(), nullptr, true, false);) CSYSVEC_PARFOR for (auto i = 0ul; i < nElm; i++) vec_val[i] = SU2_TYPE::GetValue(other[i]); diff --git a/Common/include/linear_algebra/blas_structure.hpp b/Common/include/linear_algebra/blas_structure.hpp index 48358bc2ee2..3cf8142e184 100644 --- a/Common/include/linear_algebra/blas_structure.hpp +++ b/Common/include/linear_algebra/blas_structure.hpp @@ -44,7 +44,7 @@ class CConfig; * \version 7.5.1 "Blackbird" */ class CBlasStructure { -public: + public: /*! * \brief Constructor of the class. Initialize the constant member variables. */ @@ -60,9 +60,8 @@ class CBlasStructure { * \param[in] B - Input matrix in the multiplication. * \param[out] C - Result of the matrix product A*B. */ - void gemm(const int M, const int N, const int K, - const su2double *A, const su2double *B, su2double *C, - const CConfig *config); + void gemm(const int M, const int N, const int K, const su2double* A, const su2double* B, su2double* C, + const CConfig* config); /*! * \brief Function, which carries out a dense matrix vector product @@ -73,8 +72,7 @@ class CBlasStructure { * \param[in] x - Input vector in the multiplication. * \param[out] y - Result of the product A x. */ - void gemv(const int M, const int N, const su2double *A, - const su2double *x, su2double *y); + void gemv(const int M, const int N, const su2double* A, const su2double* x, su2double* y); /*! * \brief Function, to carry out the axpy operation, i.e y += a*x. @@ -87,55 +85,53 @@ class CBlasStructure { at least 1 + (n-1)*abs(incy). * param[in] incy - Specifies the increment of y. */ - void axpy(const int n, const su2double a, const su2double *x, - const int incx, su2double *y, const int incy); + void axpy(const int n, const su2double a, const su2double* x, const int incx, su2double* y, const int incy); /*! * \brief Invert a square matrix. * \param[in] M - Size. * \param[in,out] mat - Matrix, and inverse on exit. */ - template + template static void inverse(const int M, Mat& mat) { using Scalar = typename Mat::Scalar; /*--- Copy the data from A into the augmented matrix and initialize mat with the identity. ---*/ Mat aug = mat; mat = Scalar(0); - for(int j=0; j valMax){ + Scalar valMax = fabs(aug(j, j)); + for (int i = j + 1; i < M; ++i) { + Scalar val = fabs(aug(i, j)); + if (val > valMax) { jj = i; valMax = val; } } /*--- Swap the rows j and jj, if needed. ---*/ - if(jj > j) { - for(int k=j; k j) { + for (int k = j; k < M; ++k) std::swap(aug(j, k), aug(jj, k)); + for (int k = 0; k < M; ++k) std::swap(mat(j, k), mat(jj, k)); } /*--- Performing row operations to form required identity matrix out of the input matrix. ---*/ - for(int i=0; i + template static void tred2(Mat& V, Vec& d, W& e, int n) { using Scalar = typename std::decay::type; - int i,j,k; + int i, j, k; for (j = 0; j < n; j++) { - d[j] = V[n-1][j]; + d[j] = V[n - 1][j]; } /* Householder reduction to tridiagonal form. */ - for (i = n-1; i > 0; i--) { - + for (i = n - 1; i > 0; i--) { /* Scale to avoid under/overflow. */ Scalar scale = 0.0; @@ -196,29 +191,27 @@ class CBlasStructure { scale = scale + fabs(d[k]); } if (scale == 0.0) { - e[i] = d[i-1]; + e[i] = d[i - 1]; for (j = 0; j < i; j++) { - d[j] = V[i-1][j]; + d[j] = V[i - 1][j]; V[i][j] = 0.0; V[j][i] = 0.0; } - } - else { - + } else { /* Generate Householder vector. */ for (k = 0; k < i; k++) { d[k] /= scale; h += d[k] * d[k]; } - Scalar f = d[i-1]; + Scalar f = d[i - 1]; Scalar g = sqrt(h); if (f > 0) { g = -g; } e[i] = scale * g; h = h - f * g; - d[i-1] = f - g; + d[i - 1] = f - g; for (j = 0; j < i; j++) { e[j] = 0.0; } @@ -229,7 +222,7 @@ class CBlasStructure { f = d[j]; V[j][i] = f; g = e[j] + V[j][j] * f; - for (k = j+1; k <= i-1; k++) { + for (k = j + 1; k <= i - 1; k++) { g += V[k][j] * d[k]; e[k] += V[k][j] * f; } @@ -247,10 +240,10 @@ class CBlasStructure { for (j = 0; j < i; j++) { f = d[j]; g = e[j]; - for (k = j; k <= i-1; k++) { - V[k][j] -= (f * e[k] + g * d[k]); + for (k = j; k <= i - 1; k++) { + V[k][j] -= (f * e[k] + g * d[k]); } - d[j] = V[i-1][j]; + d[j] = V[i - 1][j]; V[i][j] = 0.0; } } @@ -259,18 +252,18 @@ class CBlasStructure { /* Accumulate transformations. */ - for (i = 0; i < n-1; i++) { - V[n-1][i] = V[i][i]; + for (i = 0; i < n - 1; i++) { + V[n - 1][i] = V[i][i]; V[i][i] = 1.0; - Scalar h = d[i+1]; + Scalar h = d[i + 1]; if (h != 0.0) { for (k = 0; k <= i; k++) { - d[k] = V[k][i+1] / h; + d[k] = V[k][i + 1] / h; } for (j = 0; j <= i; j++) { Scalar g = 0.0; for (k = 0; k <= i; k++) { - g += V[k][i+1] * V[k][j]; + g += V[k][i + 1] * V[k][j]; } for (k = 0; k <= i; k++) { V[k][j] -= g * d[k]; @@ -278,14 +271,14 @@ class CBlasStructure { } } for (k = 0; k <= i; k++) { - V[k][i+1] = 0.0; + V[k][i + 1] = 0.0; } } for (j = 0; j < n; j++) { - d[j] = V[n-1][j]; - V[n-1][j] = 0.0; + d[j] = V[n - 1][j]; + V[n - 1][j] = 0.0; } - V[n-1][n-1] = 1.0; + V[n - 1][n - 1] = 1.0; e[0] = 0.0; } @@ -324,27 +317,26 @@ class CBlasStructure { * \param[in,out] e: work vector * \param[in] n: order of matrix V */ - template + template static void tql2(Mat& V, Vec& d, W& e, int n) { using Scalar = typename std::decay::type; - int i,j,k,l; + int i, j, k, l; for (i = 1; i < n; i++) { - e[i-1] = e[i]; + e[i - 1] = e[i]; } - e[n-1] = 0.0; + e[n - 1] = 0.0; Scalar f = 0.0; Scalar tst1 = 0.0; - Scalar eps = pow(2.0,-52.0); + Scalar eps = pow(2.0, -52.0); for (l = 0; l < n; l++) { - /* Find small subdiagonal element */ - tst1 = max(tst1,(fabs(d[l]) + fabs(e[l]))); + tst1 = max(tst1, (fabs(d[l]) + fabs(e[l]))); int m = l; while (m < n) { - if (fabs(e[m]) <= eps*tst1) { + if (fabs(e[m]) <= eps * tst1) { break; } m++; @@ -356,21 +348,21 @@ class CBlasStructure { if (m > l) { int iter = 0; do { - iter = iter + 1; /* (Could check iteration count here.) */ + iter = iter + 1; /* (Could check iteration count here.) */ /* Compute implicit shift */ Scalar g = d[l]; - Scalar p = (d[l+1] - g) / (2.0 * e[l]); - Scalar r = sqrt(p*p+1.0); + Scalar p = (d[l + 1] - g) / (2.0 * e[l]); + Scalar r = sqrt(p * p + 1.0); if (p < 0) { r = -r; } d[l] = e[l] / (p + r); - d[l+1] = e[l] * (p + r); - Scalar dl1 = d[l+1]; + d[l + 1] = e[l] * (p + r); + Scalar dl1 = d[l + 1]; Scalar h = g - d[l]; - for (i = l+2; i < n; i++) { + for (i = l + 2; i < n; i++) { d[i] -= h; } f = f + h; @@ -381,27 +373,27 @@ class CBlasStructure { Scalar c = 1.0; Scalar c2 = c; Scalar c3 = c; - Scalar el1 = e[l+1]; + Scalar el1 = e[l + 1]; Scalar s = 0.0; Scalar s2 = 0.0; - for (i = m-1; i >= l; i--) { + for (i = m - 1; i >= l; i--) { c3 = c2; c2 = c; s2 = s; g = c * e[i]; h = c * p; - r = sqrt(p*p+e[i]*e[i]); - e[i+1] = s * r; + r = sqrt(p * p + e[i] * e[i]); + e[i + 1] = s * r; s = e[i] / r; c = p / r; p = c * d[i] - s * g; - d[i+1] = h + s * (c * g + s * d[i]); + d[i + 1] = h + s * (c * g + s * d[i]); /* Accumulate transformation. */ for (k = 0; k < n; k++) { - h = V[k][i+1]; - V[k][i+1] = s * V[k][i] + c * h; + h = V[k][i + 1]; + V[k][i + 1] = s * V[k][i] + c * h; V[k][i] = c * V[k][i] - s * h; } } @@ -411,7 +403,7 @@ class CBlasStructure { /* Check for convergence. */ - } while (fabs(e[l]) > eps*tst1); + } while (fabs(e[l]) > eps * tst1); } d[l] = d[l] + f; e[l] = 0.0; @@ -419,10 +411,10 @@ class CBlasStructure { /* Sort eigenvalues and corresponding vectors. */ - for (i = 0; i < n-1; i++) { + for (i = 0; i < n - 1; i++) { k = i; Scalar p = d[i]; - for (j = i+1; j < n; j++) { + for (j = i + 1; j < n; j++) { if (d[j] < p) { k = j; p = d[j]; @@ -448,11 +440,11 @@ class CBlasStructure { * \param[in] n: order of matrix A_ij * \param[in,out] e: work vector */ - template + template static void EigenDecomposition(const Mat& A_ij, Mat& Eig_Vec, Vec& Eig_Val, int n, W& e) { - for (int iDim = 0; iDim < n; iDim++){ + for (int iDim = 0; iDim < n; iDim++) { e[iDim] = 0.0; - for (int jDim = 0; jDim < n; jDim++){ + for (int jDim = 0; jDim < n; jDim++) { Eig_Vec[iDim][jDim] = A_ij[iDim][jDim]; } } @@ -467,13 +459,12 @@ class CBlasStructure { * \param[in] Eig_Val: eigenvalues * \param[in] n: order of matrix A_ij */ - template + template static void EigenRecomposition(Mat& A_ij, const Mat& Eig_Vec, const Vec& Eig_Val, int n) { - for (int i = 0; i < n; i++){ - for (int j = 0; j < n; j++){ + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { A_ij[i][j] = 0.0; - for (int k = 0; k < n; k++) - A_ij[i][j] += Eig_Vec[i][k] * Eig_Val[k] * Eig_Vec[j][k]; + for (int k = 0; k < n; k++) A_ij[i][j] += Eig_Vec[i][k] * Eig_Val[k] * Eig_Vec[j][k]; } } } @@ -486,29 +477,28 @@ class CBlasStructure { * \param[in,out] rhs - right hand side on entry, solution on exit * \note Same size for all vectors. Use row index for lower and upper vector (e.g. lower[0] does not matter). */ - template + template static void tdma(const Vec& lower, const Vec& main, Vec& upper, Vec& rhs) { const int N = main.size(); upper[0] /= main[0]; rhs[0] /= main[0]; - for (int i=1; i=0; i--) - rhs[i] -= upper[i]*rhs[i+1]; + for (int i = N - 2; i >= 0; i--) rhs[i] -= upper[i] * rhs[i + 1]; } -private: - -#if !(defined(HAVE_LIBXSMM) || defined(HAVE_BLAS) || defined(HAVE_MKL)) || (defined(CODI_REVERSE_TYPE) || defined(CODI_FORWARD_TYPE)) - /* Blocking parameters for the outer kernel. We multiply mc x kc blocks of - the matrix A with kc x nc panels of the matrix B (this approach is referred - to as `gebp` in the literature). */ + private: +#if !(defined(HAVE_LIBXSMM) || defined(HAVE_BLAS) || defined(HAVE_MKL)) || \ + (defined(CODI_REVERSE_TYPE) || defined(CODI_FORWARD_TYPE)) + /* Blocking parameters for the outer kernel. We multiply mc x kc blocks of + the matrix A with kc x nc panels of the matrix B (this approach is referred + to as `gebp` in the literature). */ const int mc; const int kc; const int nc; @@ -522,8 +512,7 @@ class CBlasStructure { * \param[in] b - Input matrix in the multiplication. * \param[out] c - Result of the matrix product a*b. */ - void gemm_imp(const int m, const int n, const int k, - const su2double *a, const su2double *b, su2double *c); + void gemm_imp(const int m, const int n, const int k, const su2double* a, const su2double* b, su2double* c); /*! * \brief Compute a portion of the c matrix one block at a time. @@ -538,8 +527,7 @@ class CBlasStructure { * \param[out] c - Result of the matrix product a*b. * \param[in] ldc - Leading dimension of the matrix c. */ - void gemm_inner(int m, int n, int k, const su2double *a, int lda, - const su2double *b, int ldb, su2double *c, int ldc); + void gemm_inner(int m, int n, int k, const su2double* a, int lda, const su2double* b, int ldb, su2double* c, int ldc); /*! * \brief Naive gemm implementation to handle arbitrary sized matrices. @@ -553,7 +541,7 @@ class CBlasStructure { * \param[out] c - Result of the matrix product a*b. * \param[in] ldc - Leading dimension of the matrix c. */ - void gemm_arbitrary(int m, int n, int k, const su2double *a, int lda, - const su2double *b, int ldb, su2double *c, int ldc); + void gemm_arbitrary(int m, int n, int k, const su2double* a, int lda, const su2double* b, int ldb, su2double* c, + int ldc); #endif }; diff --git a/Common/include/linear_algebra/vector_expressions.hpp b/Common/include/linear_algebra/vector_expressions.hpp index 6164d019982..000ce3cb2d0 100644 --- a/Common/include/linear_algebra/vector_expressions.hpp +++ b/Common/include/linear_algebra/vector_expressions.hpp @@ -53,9 +53,9 @@ namespace VecExpr { * Vector classes should be stored by reference to avoid copies, especially if they * allocate memory dynamically. */ -template +template class CVecExpr { -public: + public: /*! * \brief Cast the expression to Derived, usually to allow evaluation via operator[]. */ @@ -63,35 +63,45 @@ class CVecExpr { // Allowed from C++14, allows nested expression propagation without // manually calling derived() on the expression being evaluated. - //FORCEINLINE auto operator[] (size_t i) const { return derived()[i]; } + // FORCEINLINE auto operator[] (size_t i) const { return derived()[i]; } }; /*! * \brief Expression class to broadcast a scalar value. Allows implementing * "vector-scalar" operations re-using "vector-vector" expressions. */ -template +template class Bcast : public CVecExpr, Scalar> { Scalar x; -public: + + public: static constexpr bool StoreAsRef = false; FORCEINLINE Bcast(const Scalar& x_) : x(x_) {} - FORCEINLINE const Scalar& operator[] (size_t) const { return x; } + FORCEINLINE const Scalar& operator[](size_t) const { return x; } }; /*! * \brief std::decay_t from C++14, used to allow implicit conversions * between scalar types, e.g. "CVecExpr" + "int/double/etc.". */ -template using decay_t = typename std::decay::type; +template +using decay_t = typename std::decay::type; /*! \brief std::remove_reference_t from C++14, removes references from some type. */ -template using remove_reference_t = typename std::remove_reference::type; +template +using remove_reference_t = typename std::remove_reference::type; /*! \brief Mechanism to conditionally (based on "StoreAsRef") add lvalue reference to a type. */ -template struct add_lref_if { using type = remove_reference_t; }; -template struct add_lref_if { using type = remove_reference_t &; }; -template using store_t = typename add_lref_if::type; +template +struct add_lref_if { + using type = remove_reference_t; +}; +template +struct add_lref_if { + using type = remove_reference_t&; +}; +template +using store_t = typename add_lref_if::type; /*--- Namespace from which the math function implementations come. ---*/ @@ -104,26 +114,28 @@ namespace math = ::std; /*--- Macro to simplify auto return type deduction in C++11, operator[] needs * it to allow inner expressions to propagate as the outer is evaluated. ---*/ -#define RETURNS(...) ->decltype(__VA_ARGS__) { return __VA_ARGS__; } +#define RETURNS(...) \ + ->decltype(__VA_ARGS__) { return __VA_ARGS__; } /*--- Macro to create expression classes (EXPR) and overloads (FUN) for unary * functions, based on their coefficient-wise implementation (IMPL). ---*/ -#define MAKE_UNARY_FUN(FUN, EXPR, IMPL) \ -/*!--- Expression class. ---*/ \ -template \ -class EXPR : public CVecExpr, Scalar> { \ - store_t u; \ -public: \ - static constexpr bool StoreAsRef = false; \ - FORCEINLINE EXPR(const U& u_) : u(u_) {} \ - FORCEINLINE auto operator[] (size_t i) const RETURNS( IMPL(u[i]) ) \ -}; \ -/*!--- Function overload, returns an expression object. ---*/ \ -template \ -FORCEINLINE auto FUN(const CVecExpr& u) RETURNS( EXPR(u.derived()) ) - -#define sign_impl(x) Scalar(1-2*(x<0)) +#define MAKE_UNARY_FUN(FUN, EXPR, IMPL) \ + /*!--- Expression class. ---*/ \ + template \ + class EXPR : public CVecExpr, Scalar> { \ + store_t u; \ + \ + public: \ + static constexpr bool StoreAsRef = false; \ + FORCEINLINE EXPR(const U& u_) : u(u_) {} \ + FORCEINLINE auto operator[](size_t i) const RETURNS(IMPL(u[i])) \ + }; \ + /*!--- Function overload, returns an expression object. ---*/ \ + template \ + FORCEINLINE auto FUN(const CVecExpr& u) RETURNS(EXPR(u.derived())) + +#define sign_impl(x) Scalar(1 - 2 * (x < 0)) MAKE_UNARY_FUN(operator-, minus_, -) MAKE_UNARY_FUN(abs, abs_, math::abs) MAKE_UNARY_FUN(sqrt, sqrt_, math::sqrt) @@ -134,32 +146,28 @@ MAKE_UNARY_FUN(sign, sign_, sign_impl) /*--- Macro to create expressions and overloads for binary functions. ---*/ -#define MAKE_BINARY_FUN(FUN, EXPR, IMPL) \ -/*!--- Expression class. ---*/ \ -template \ -class EXPR : public CVecExpr, Scalar> { \ - store_t u; \ - store_t v; \ -public: \ - static constexpr bool StoreAsRef = false; \ - FORCEINLINE EXPR(const U& u_, const V& v_) : u(u_), v(v_) {} \ - FORCEINLINE auto operator[] (size_t i) const RETURNS( IMPL(u[i], v[i]) ) \ -}; \ -/*!--- Vector with vector function overload. ---*/ \ -template \ -FORCEINLINE auto FUN(const CVecExpr& u, const CVecExpr& v) \ - RETURNS( EXPR(u.derived(), v.derived()) \ -) \ -/*!--- Vector with scalar function overload. ---*/ \ -template \ -FORCEINLINE auto FUN(const CVecExpr& u, decay_t v) \ - RETURNS( EXPR,S>(u.derived(), Bcast(v)) \ -) \ -/*!--- Scalar with vector function overload. ---*/ \ -template \ -FORCEINLINE auto FUN(decay_t u, const CVecExpr& v) \ - RETURNS( EXPR,V,S>(Bcast(u), v.derived()) \ -) \ +#define MAKE_BINARY_FUN(FUN, EXPR, IMPL) \ + /*!--- Expression class. ---*/ \ + template \ + class EXPR : public CVecExpr, Scalar> { \ + store_t u; \ + store_t v; \ + \ + public: \ + static constexpr bool StoreAsRef = false; \ + FORCEINLINE EXPR(const U& u_, const V& v_) : u(u_), v(v_) {} \ + FORCEINLINE auto operator[](size_t i) const RETURNS(IMPL(u[i], v[i])) \ + }; \ + /*!--- Vector with vector function overload. ---*/ \ + template \ + FORCEINLINE auto FUN(const CVecExpr& u, const CVecExpr& v) \ + RETURNS(EXPR(u.derived(), v.derived())) /*!--- Vector with scalar function overload. ---*/ \ + template \ + FORCEINLINE auto FUN(const CVecExpr& u, decay_t v) \ + RETURNS(EXPR, S>(u.derived(), Bcast(v))) /*!--- Scalar with vector function overload. ---*/ \ + template \ + FORCEINLINE auto FUN(decay_t u, const CVecExpr& v) \ + RETURNS(EXPR, V, S>(Bcast(u), v.derived())) /*--- std::max/min have issues (because they return by reference). * fmin and fmax return by value and thus are fine, but they would force @@ -167,9 +175,9 @@ FORCEINLINE auto FUN(decay_t u, const CVecExpr& v) \ * We use int32/64 instead of int/long to avoid issues with Windows, * where long is 32 bits (instead of 64 bits). ---*/ -#define MAKE_FMINMAX_OVERLOADS(TYPE) \ -FORCEINLINE TYPE fmax(TYPE a, TYPE b) { return a::Value(IMPL) -#define le_impl(a,b) TO_PASSIVE(a<=b) -#define ge_impl(a,b) TO_PASSIVE(a>=b) -#define eq_impl(a,b) TO_PASSIVE(a==b) -#define ne_impl(a,b) TO_PASSIVE(a!=b) -#define lt_impl(a,b) TO_PASSIVE(ab) +#define le_impl(a, b) TO_PASSIVE(a <= b) +#define ge_impl(a, b) TO_PASSIVE(a >= b) +#define eq_impl(a, b) TO_PASSIVE(a == b) +#define ne_impl(a, b) TO_PASSIVE(a != b) +#define lt_impl(a, b) TO_PASSIVE(a < b) +#define gt_impl(a, b) TO_PASSIVE(a > b) MAKE_BINARY_FUN(operator<=, le_, le_impl) MAKE_BINARY_FUN(operator>=, ge_, ge_impl) MAKE_BINARY_FUN(operator==, eq_, eq_impl) @@ -230,4 +238,4 @@ MAKE_BINARY_FUN(operator>, gt_, gt_impl) #undef MAKE_BINARY_FUN /// @} -} // end namespace +} // namespace VecExpr diff --git a/Common/include/option_structure.inl b/Common/include/option_structure.inl index 758033da153..f017aa65e2c 100644 --- a/Common/include/option_structure.inl +++ b/Common/include/option_structure.inl @@ -31,21 +31,16 @@ using namespace std; template class COptionEnum final : public COptionBase { - const map& m; - TField& field; // Reference to the fieldname - const Tenum def; // Default value - const string name; // identifier for the option + TField& field; // Reference to the fieldname + const Tenum def; // Default value + const string name; // identifier for the option -public: + public: COptionEnum() = delete; - COptionEnum(string option_field_name, const map& m_, TField& option_field, Tenum default_value) : - m(m_), - field(option_field), - def(default_value), - name(std::move(option_field_name)) { - } + COptionEnum(string option_field_name, const map& m_, TField& option_field, Tenum default_value) + : m(m_), field(option_field), def(default_value), name(std::move(option_field_name)) {} string SetValue(const vector& option_value) override { COptionBase::SetValue(option_value); @@ -73,26 +68,19 @@ public: void SetDefault() override { field = def; } }; -template +template class COptionScalar : public COptionBase { -protected: - Scalar& field; // Reference to the fieldname - const Scalar def; // Default value - const string name; // identifier for the option - const string typeName; // name for the scalar type + protected: + Scalar& field; // Reference to the fieldname + const Scalar def; // Default value + const string name; // identifier for the option + const string typeName; // name for the scalar type -public: + public: COptionScalar() = delete; - COptionScalar(const string& type_name, - const string& option_field_name, - Scalar& option_field, - Scalar default_value) : - field(option_field), - def(default_value), - name(option_field_name), - typeName(type_name) { - } + COptionScalar(const string& type_name, const string& option_field_name, Scalar& option_field, Scalar default_value) + : field(option_field), def(default_value), name(option_field_name), typeName(type_name) {} string SetValue(const vector& option_value) override { COptionBase::SetValue(option_value); @@ -106,63 +94,49 @@ public: return badValue(typeName, name); } - void SetDefault() final { - field = def; - } + void SetDefault() final { field = def; } }; class COptionDouble final : public COptionScalar { -public: - template - COptionDouble(Ts&&... args) : - COptionScalar("su2double", args...) { - } + public: + template + COptionDouble(Ts&&... args) : COptionScalar("su2double", args...) {} }; class COptionInt final : public COptionScalar { -public: - template - COptionInt(Ts&&... args) : - COptionScalar("int", args...) { - } + public: + template + COptionInt(Ts&&... args) : COptionScalar("int", args...) {} }; class COptionULong final : public COptionScalar { -public: - template - COptionULong(Ts&&... args) : - COptionScalar("unsigned long", args...) { - } + public: + template + COptionULong(Ts&&... args) : COptionScalar("unsigned long", args...) {} }; class COptionUShort final : public COptionScalar { -public: - template - COptionUShort(Ts&&... args) : - COptionScalar("unsigned short", args...) { - } + public: + template + COptionUShort(Ts&&... args) : COptionScalar("unsigned short", args...) {} }; class COptionLong final : public COptionScalar { -public: - template - COptionLong(Ts&&... args) : - COptionScalar("long", args...) { - } + public: + template + COptionLong(Ts&&... args) : COptionScalar("long", args...) {} }; class COptionBool final : public COptionScalar { -public: - template - COptionBool(Ts&&... args) : - COptionScalar("bool", args...) { - } + public: + template + COptionBool(Ts&&... args) : COptionScalar("bool", args...) {} string SetValue(const vector& option_value) override { COptionBase::SetValue(option_value); string result; - auto msg = COptionScalar("bool",name,result,"").SetValue(option_value); + auto msg = COptionScalar("bool", name, result, "").SetValue(option_value); if (!msg.empty()) return msg; @@ -180,21 +154,16 @@ public: }; class COptionString final : public COptionBase { -protected: - string& field; // Reference to the fieldname - const string def; // Default value - const string name; // identifier for the option + protected: + string& field; // Reference to the fieldname + const string def; // Default value + const string name; // identifier for the option -public: + public: COptionString() = delete; - COptionString(const string& option_field_name, - string& option_field, - string default_value) : - field(option_field), - def(default_value), - name(option_field_name) { - } + COptionString(const string& option_field_name, string& option_field, string default_value) + : field(option_field), def(default_value), name(option_field_name) {} string SetValue(const vector& option_value) override { COptionBase::SetValue(option_value); @@ -206,32 +175,27 @@ public: return ""; } - void SetDefault() override { - field = def; - } + void SetDefault() override { field = def; } }; template class COptionEnumList final : public COptionBase { - const map& m; TField*& field; unsigned short& mySize; const string name; -public: + public: COptionEnumList() = delete; - COptionEnumList(string option_field_name, const map& m_, TField*& option_field, unsigned short& list_size) : - m(m_), - field(option_field), - mySize(list_size), - name(option_field_name) { + COptionEnumList(string option_field_name, const map& m_, TField*& option_field, + unsigned short& list_size) + : m(m_), field(option_field), mySize(list_size), name(option_field_name) { field = nullptr; } ~COptionEnumList() { - delete [] field; + delete[] field; field = nullptr; } @@ -266,18 +230,15 @@ public: void SetDefault() override { mySize = 0; } }; -template +template class COptionArray final : public COptionBase { - string name; // Identifier for the option - const int size; // Number of elements - Type* field; // Reference to the field - -public: - COptionArray(string option_field_name, const int list_size, Type* option_field) : - name(option_field_name), - size(list_size), - field(option_field) { - } + string name; // Identifier for the option + const int size; // Number of elements + Type* field; // Reference to the field + + public: + COptionArray(string option_field_name, const int list_size, Type* option_field) + : name(option_field_name), size(list_size), field(option_field) {} string SetValue(const vector& option_value) override { COptionBase::SetValue(option_value); @@ -296,7 +257,7 @@ public: newstring.append(" found"); return newstring; } - for (int i = 0; i < this->size; i++) { + for (int i = 0; i < this->size; i++) { istringstream is(option_value[i]); if (!(is >> field[i])) { return badValue(" array", this->name); @@ -308,29 +269,24 @@ public: void SetDefault() override {} }; -template +template class COptionScalarList : public COptionBase { - Scalar*& field; // reference to the field - const string name; // identifier for the option - unsigned short& mySize; // size of the list - const string typeName; // name of the scalar type + Scalar*& field; // reference to the field + const string name; // identifier for the option + unsigned short& mySize; // size of the list + const string typeName; // name of the scalar type -public: + public: COptionScalarList() = delete; - COptionScalarList(const string& type_name, - const string& option_field_name, - unsigned short& list_size, - Scalar*& option_field) : - field(option_field), - name(option_field_name), - mySize(list_size), - typeName(type_name) { + COptionScalarList(const string& type_name, const string& option_field_name, unsigned short& list_size, + Scalar*& option_field) + : field(option_field), name(option_field_name), mySize(list_size), typeName(type_name) { field = nullptr; } ~COptionScalarList() { - delete [] field; + delete[] field; // prevent double free field = nullptr; } @@ -351,7 +307,7 @@ public: istringstream is(option_value[i]); Scalar val; if (!(is >> val)) { - return badValue(typeName+" list", name); + return badValue(typeName + " list", name); } field[i] = std::move(val); } @@ -359,59 +315,49 @@ public: } void SetDefault() final { - mySize = 0; // There is no default value for list + mySize = 0; // There is no default value for list } }; class COptionDoubleList final : public COptionScalarList { -public: - template - COptionDoubleList(Ts&&... args) : - COptionScalarList("su2double", args...) { - } + public: + template + COptionDoubleList(Ts&&... args) : COptionScalarList("su2double", args...) {} }; class COptionShortList final : public COptionScalarList { -public: - template - COptionShortList(Ts&&... args) : - COptionScalarList("short", args...) { - } + public: + template + COptionShortList(Ts&&... args) : COptionScalarList("short", args...) {} }; class COptionUShortList final : public COptionScalarList { -public: - template - COptionUShortList(Ts&&... args) : - COptionScalarList("unsigned short", args...) { - } + public: + template + COptionUShortList(Ts&&... args) : COptionScalarList("unsigned short", args...) {} }; class COptionULongList final : public COptionScalarList { -public: - template - COptionULongList(Ts&&... args) : - COptionScalarList("unsigned long", args...) { - } + public: + template + COptionULongList(Ts&&... args) : COptionScalarList("unsigned long", args...) {} }; class COptionStringList final : public COptionScalarList { -public: - template - COptionStringList(Ts&&... args) : - COptionScalarList("string", args...) { - } + public: + template + COptionStringList(Ts&&... args) : COptionScalarList("string", args...) {} }; class COptionConvect : public COptionBase { - string name; // identifier for the option - unsigned short & space; - CENTERED & centered; - UPWIND & upwind; + string name; // identifier for the option + unsigned short& space; + CENTERED& centered; + UPWIND& upwind; -public: - COptionConvect(string option_field_name, unsigned short & space_field, CENTERED & centered_field, UPWIND & upwind_field) - : name(option_field_name), space(space_field), centered(centered_field), upwind(upwind_field) { } + public: + COptionConvect(string option_field_name, unsigned short& space_field, CENTERED& centered_field, UPWIND& upwind_field) + : name(option_field_name), space(space_field), centered(centered_field), upwind(upwind_field) {} string SetValue(const vector& option_value) override { COptionBase::SetValue(option_value); @@ -436,7 +382,6 @@ public: // Make them defined in case something weird happens SetDefault(); return badValue("convect", this->name); - } void SetDefault() override { @@ -446,17 +391,18 @@ public: } }; -class COptionFEMConvect : public COptionBase{ - string name; // identifier for the option - unsigned short & space; - unsigned short & fem; +class COptionFEMConvect : public COptionBase { + string name; // identifier for the option + unsigned short& space; + unsigned short& fem; -public: - COptionFEMConvect(string option_field_name, unsigned short & space_field, unsigned short & fem_field) : space(space_field), fem(fem_field) { + public: + COptionFEMConvect(string option_field_name, unsigned short& space_field, unsigned short& fem_field) + : space(space_field), fem(fem_field) { this->name = option_field_name; } - ~COptionFEMConvect() override {}; + ~COptionFEMConvect() override{}; string SetValue(const vector& option_value) override { COptionBase::SetValue(option_value); @@ -474,56 +420,51 @@ public: // Make them defined in case something weird happens this->fem = NO_FEM; return badValue("convect", this->name); - } - void SetDefault() override { - this->fem = NO_FEM; - } + void SetDefault() override { this->fem = NO_FEM; } }; class COptionMathProblem : public COptionBase { - string name; // identifier for the option - bool & cont_adjoint; + string name; // identifier for the option + bool& cont_adjoint; bool cont_adjoint_def; - bool & disc_adjoint; + bool& disc_adjoint; bool disc_adjoint_def; - bool & restart; + bool& restart; bool restart_def; -public: - COptionMathProblem(string option_field_name, bool & cont_adjoint_field, bool cont_adjoint_default, bool & disc_adjoint_field, bool disc_adjoint_default, bool & restart_field, bool restart_default) : cont_adjoint(cont_adjoint_field), disc_adjoint(disc_adjoint_field), restart(restart_field) { + public: + COptionMathProblem(string option_field_name, bool& cont_adjoint_field, bool cont_adjoint_default, + bool& disc_adjoint_field, bool disc_adjoint_default, bool& restart_field, bool restart_default) + : cont_adjoint(cont_adjoint_field), disc_adjoint(disc_adjoint_field), restart(restart_field) { name = option_field_name; cont_adjoint_def = cont_adjoint_default; disc_adjoint_def = disc_adjoint_default; restart_def = restart_default; } - ~COptionMathProblem() override {}; + ~COptionMathProblem() override{}; string SetValue(const vector& option_value) override { COptionBase::SetValue(option_value); string out = optionCheckMultipleValues(option_value, "unsigned short", name); if (out.compare("") != 0) { return out; - } - else if (option_value[0] == "ADJOINT") { + } else if (option_value[0] == "ADJOINT") { return badValue("math problem (try CONTINUOUS_ADJOINT)", name); - } - else if (option_value[0] == "DIRECT") { + } else if (option_value[0] == "DIRECT") { cont_adjoint = false; disc_adjoint = false; restart = false; return ""; - } - else if (option_value[0] == "CONTINUOUS_ADJOINT") { - cont_adjoint= true; + } else if (option_value[0] == "CONTINUOUS_ADJOINT") { + cont_adjoint = true; disc_adjoint = false; - restart= true; + restart = true; return ""; - } - else if (option_value[0] == "DISCRETE_ADJOINT") { + } else if (option_value[0] == "DISCRETE_ADJOINT") { disc_adjoint = true; - cont_adjoint= false; + cont_adjoint = false; restart = true; return ""; } @@ -535,22 +476,23 @@ public: disc_adjoint = disc_adjoint_def; restart = restart_def; } - }; class COptionDVParam : public COptionBase { - string name; // identifier for the option - unsigned short & nDV; - su2double ** & paramDV; - string * & FFDTag; - unsigned short* & design_variable; - -public: - COptionDVParam(string option_field_name, unsigned short & nDV_field, su2double** & paramDV_field, string* & FFDTag_field, unsigned short * & design_variable_field) : nDV(nDV_field), paramDV(paramDV_field), FFDTag(FFDTag_field), design_variable(design_variable_field) { + string name; // identifier for the option + unsigned short& nDV; + su2double**& paramDV; + string*& FFDTag; + unsigned short*& design_variable; + + public: + COptionDVParam(string option_field_name, unsigned short& nDV_field, su2double**& paramDV_field, string*& FFDTag_field, + unsigned short*& design_variable_field) + : nDV(nDV_field), paramDV(paramDV_field), FFDTag(FFDTag_field), design_variable(design_variable_field) { this->name = option_field_name; } - ~COptionDVParam() override {}; + ~COptionDVParam() override{}; string SetValue(const vector& option_value) override { COptionBase::SetValue(option_value); @@ -566,18 +508,17 @@ public: newstring.append(": may not have beginning semicolon"); return newstring; } - if (option_value[option_value.size()-1].compare(";") == 0) { + if (option_value[option_value.size() - 1].compare(";") == 0) { string newstring; newstring.append(this->name); newstring.append(": may not have ending semicolon"); return newstring; } - // use the ";" token to determine the number of design variables // This works because semicolon is not one of the delimiters in tokenize string this->nDV = 0; - //unsigned int num_semi = 0; + // unsigned int num_semi = 0; for (unsigned int i = 0; i < static_cast(option_value.size()); i++) { if (option_value[i].compare(";") == 0) { this->nDV++; @@ -588,10 +529,12 @@ public: // One more design variable than semicolon this->nDV++; - if ( (this->nDV > 0) && (this->design_variable == nullptr) ) { + if ((this->nDV > 0) && (this->design_variable == nullptr)) { string newstring; newstring.append(this->name); - newstring.append(": Design_Variable array has not been allocated. Check that DV_KIND appears before DV_PARAM in configuration file."); + newstring.append( + ": Design_Variable array has not been allocated. Check that DV_KIND appears before DV_PARAM in configuration " + "file."); return newstring; } @@ -602,48 +545,116 @@ public: this->FFDTag = new string[this->nDV]; - vector nParamDV(nDV, 0); - unsigned short totalnParamDV = 0; - stringstream ss; - unsigned int i = 0; + vector nParamDV(nDV, 0); + unsigned short totalnParamDV = 0; + stringstream ss; + unsigned int i = 0; for (unsigned short iDV = 0; iDV < this->nDV; iDV++) { switch (this->design_variable[iDV]) { - case NO_DEFORMATION: nParamDV[iDV] = 0; break; - case FFD_SETTING: nParamDV[iDV] = 0; break; - case FFD_CONTROL_POINT_2D: nParamDV[iDV] = 5; break; - case FFD_CAMBER_2D: nParamDV[iDV] = 2; break; - case FFD_THICKNESS_2D: nParamDV[iDV] = 2; break; - case FFD_TWIST_2D: nParamDV[iDV] = 3; break; - case HICKS_HENNE: nParamDV[iDV] = 2; break; - case SURFACE_BUMP: nParamDV[iDV] = 3; break; - case CST: nParamDV[iDV] = 3; break; - case ANGLE_OF_ATTACK: nParamDV[iDV] = 1; break; - case SCALE: nParamDV[iDV] = 0; break; - case TRANSLATION: nParamDV[iDV] = 3; break; - case ROTATION: nParamDV[iDV] = 6; break; - case NACA_4DIGITS: nParamDV[iDV] = 3; break; - case PARABOLIC: nParamDV[iDV] = 2; break; - case AIRFOIL: nParamDV[iDV] = 2; break; - case FFD_CONTROL_POINT: nParamDV[iDV] = 7; break; - case FFD_NACELLE: nParamDV[iDV] = 6; break; - case FFD_GULL: nParamDV[iDV] = 2; break; - case FFD_TWIST: nParamDV[iDV] = 8; break; - case FFD_ROTATION: nParamDV[iDV] = 7; break; - case FFD_CONTROL_SURFACE: nParamDV[iDV] = 7; break; - case FFD_CAMBER: nParamDV[iDV] = 3; break; - case FFD_THICKNESS: nParamDV[iDV] = 3; break; - case FFD_ANGLE_OF_ATTACK: nParamDV[iDV] = 2; break; - case SURFACE_FILE: nParamDV[iDV] = 0; break; - case DV_EFIELD: nParamDV[iDV] = 2; break; - case DV_YOUNG: nParamDV[iDV] = 0; break; - case DV_POISSON: nParamDV[iDV] = 0; break; - case DV_RHO: nParamDV[iDV] = 0; break; - case DV_RHO_DL: nParamDV[iDV] = 0; break; - case SCALE_GRID: nParamDV[iDV] = 0; break; - case TRANSLATE_GRID: nParamDV[iDV] = 3; break; - case ROTATE_GRID: nParamDV[iDV] = 6; break; - default : { + case NO_DEFORMATION: + nParamDV[iDV] = 0; + break; + case FFD_SETTING: + nParamDV[iDV] = 0; + break; + case FFD_CONTROL_POINT_2D: + nParamDV[iDV] = 5; + break; + case FFD_CAMBER_2D: + nParamDV[iDV] = 2; + break; + case FFD_THICKNESS_2D: + nParamDV[iDV] = 2; + break; + case FFD_TWIST_2D: + nParamDV[iDV] = 3; + break; + case HICKS_HENNE: + nParamDV[iDV] = 2; + break; + case SURFACE_BUMP: + nParamDV[iDV] = 3; + break; + case CST: + nParamDV[iDV] = 3; + break; + case ANGLE_OF_ATTACK: + nParamDV[iDV] = 1; + break; + case SCALE: + nParamDV[iDV] = 0; + break; + case TRANSLATION: + nParamDV[iDV] = 3; + break; + case ROTATION: + nParamDV[iDV] = 6; + break; + case NACA_4DIGITS: + nParamDV[iDV] = 3; + break; + case PARABOLIC: + nParamDV[iDV] = 2; + break; + case AIRFOIL: + nParamDV[iDV] = 2; + break; + case FFD_CONTROL_POINT: + nParamDV[iDV] = 7; + break; + case FFD_NACELLE: + nParamDV[iDV] = 6; + break; + case FFD_GULL: + nParamDV[iDV] = 2; + break; + case FFD_TWIST: + nParamDV[iDV] = 8; + break; + case FFD_ROTATION: + nParamDV[iDV] = 7; + break; + case FFD_CONTROL_SURFACE: + nParamDV[iDV] = 7; + break; + case FFD_CAMBER: + nParamDV[iDV] = 3; + break; + case FFD_THICKNESS: + nParamDV[iDV] = 3; + break; + case FFD_ANGLE_OF_ATTACK: + nParamDV[iDV] = 2; + break; + case SURFACE_FILE: + nParamDV[iDV] = 0; + break; + case DV_EFIELD: + nParamDV[iDV] = 2; + break; + case DV_YOUNG: + nParamDV[iDV] = 0; + break; + case DV_POISSON: + nParamDV[iDV] = 0; + break; + case DV_RHO: + nParamDV[iDV] = 0; + break; + case DV_RHO_DL: + nParamDV[iDV] = 0; + break; + case SCALE_GRID: + nParamDV[iDV] = 0; + break; + case TRANSLATE_GRID: + nParamDV[iDV] = 3; + break; + case ROTATE_GRID: + nParamDV[iDV] = 6; + break; + default: { string newstring; newstring.append(this->name); newstring.append(": undefined design variable type found in configuration file."); @@ -653,40 +664,31 @@ public: totalnParamDV += nParamDV[iDV]; } - if (totalnParamDV > option_value.size()){ + if (totalnParamDV > option_value.size()) { SU2_MPI::Error("Wrong number of arguments for DV_PARAM!", CURRENT_FUNCTION); } for (unsigned short iDV = 0; iDV < this->nDV; iDV++) { for (unsigned short iParamDV = 0; iParamDV < nParamDV[iDV]; iParamDV++) { - ss << option_value[i] << " "; if ((iParamDV == 0) && - ((this->design_variable[iDV] == NO_DEFORMATION) || - (this->design_variable[iDV] == FFD_SETTING) || - (this->design_variable[iDV] == FFD_ANGLE_OF_ATTACK)|| - (this->design_variable[iDV] == FFD_CONTROL_POINT_2D) || - (this->design_variable[iDV] == FFD_CAMBER_2D) || - (this->design_variable[iDV] == FFD_TWIST_2D) || - (this->design_variable[iDV] == FFD_THICKNESS_2D) || - (this->design_variable[iDV] == FFD_CONTROL_POINT) || - (this->design_variable[iDV] == FFD_NACELLE) || - (this->design_variable[iDV] == FFD_GULL) || - (this->design_variable[iDV] == FFD_TWIST) || - (this->design_variable[iDV] == FFD_ROTATION) || - (this->design_variable[iDV] == FFD_CONTROL_SURFACE) || - (this->design_variable[iDV] == FFD_CAMBER) || - (this->design_variable[iDV] == FFD_THICKNESS))) { - ss >> this->FFDTag[iDV]; - this->paramDV[iDV][iParamDV] = 0; - } - else + ((this->design_variable[iDV] == NO_DEFORMATION) || (this->design_variable[iDV] == FFD_SETTING) || + (this->design_variable[iDV] == FFD_ANGLE_OF_ATTACK) || + (this->design_variable[iDV] == FFD_CONTROL_POINT_2D) || (this->design_variable[iDV] == FFD_CAMBER_2D) || + (this->design_variable[iDV] == FFD_TWIST_2D) || (this->design_variable[iDV] == FFD_THICKNESS_2D) || + (this->design_variable[iDV] == FFD_CONTROL_POINT) || (this->design_variable[iDV] == FFD_NACELLE) || + (this->design_variable[iDV] == FFD_GULL) || (this->design_variable[iDV] == FFD_TWIST) || + (this->design_variable[iDV] == FFD_ROTATION) || (this->design_variable[iDV] == FFD_CONTROL_SURFACE) || + (this->design_variable[iDV] == FFD_CAMBER) || (this->design_variable[iDV] == FFD_THICKNESS))) { + ss >> this->FFDTag[iDV]; + this->paramDV[iDV][iParamDV] = 0; + } else ss >> this->paramDV[iDV][iParamDV]; i++; } - if (iDV < (this->nDV-1)) { + if (iDV < (this->nDV - 1)) { if (option_value[i].compare(";") != 0) { string newstring; newstring.append(this->name); @@ -710,19 +712,25 @@ public: }; class COptionDVValue : public COptionBase { - string name; // identifier for the option - unsigned short* & nDV_Value; - su2double ** & valueDV; - unsigned short & nDV; - su2double ** & paramDV; - unsigned short* & design_variable; - -public: - COptionDVValue(string option_field_name, unsigned short* & nDVValue_field, su2double** & valueDV_field, unsigned short & nDV_field, su2double** & paramDV_field, unsigned short * & design_variable_field) : nDV_Value(nDVValue_field), valueDV(valueDV_field), nDV(nDV_field), paramDV(paramDV_field), design_variable(design_variable_field) { + string name; // identifier for the option + unsigned short*& nDV_Value; + su2double**& valueDV; + unsigned short& nDV; + su2double**& paramDV; + unsigned short*& design_variable; + + public: + COptionDVValue(string option_field_name, unsigned short*& nDVValue_field, su2double**& valueDV_field, + unsigned short& nDV_field, su2double**& paramDV_field, unsigned short*& design_variable_field) + : nDV_Value(nDVValue_field), + valueDV(valueDV_field), + nDV(nDV_field), + paramDV(paramDV_field), + design_variable(design_variable_field) { this->name = option_field_name; } - ~COptionDVValue() override {}; + ~COptionDVValue() override{}; string SetValue(const vector& option_value) override { COptionBase::SetValue(option_value); @@ -731,16 +739,20 @@ public: return ""; } - if ( (this->nDV > 0) && (this->design_variable == nullptr) ) { + if ((this->nDV > 0) && (this->design_variable == nullptr)) { string newstring; newstring.append(this->name); - newstring.append(": Design_Variable array has not been allocated. Check that DV_KIND appears before DV_VALUE in configuration file."); + newstring.append( + ": Design_Variable array has not been allocated. Check that DV_KIND appears before DV_VALUE in configuration " + "file."); return newstring; } - if ( (this->nDV > 0) && (this->paramDV == nullptr) ) { + if ((this->nDV > 0) && (this->paramDV == nullptr)) { string newstring; newstring.append(this->name); - newstring.append(": Design_Parameter array has not been allocated. Check that DV_PARAM appears before DV_VALUE in configuration file."); + newstring.append( + ": Design_Parameter array has not been allocated. Check that DV_PARAM appears before DV_VALUE in " + "configuration file."); return newstring; } @@ -758,23 +770,20 @@ public: for (unsigned short iDV = 0; iDV < this->nDV; iDV++) { switch (this->design_variable[iDV]) { case FFD_CONTROL_POINT: - if((this->paramDV[iDV][4] == 0) && - (this->paramDV[iDV][5] == 0) && - (this->paramDV[iDV][6] == 0)) { + if ((this->paramDV[iDV][4] == 0) && (this->paramDV[iDV][5] == 0) && (this->paramDV[iDV][6] == 0)) { nValueDV = 3; } else { nValueDV = 1; } break; case FFD_CONTROL_POINT_2D: - if((this->paramDV[iDV][3] == 0) && - (this->paramDV[iDV][4] == 0)) { + if ((this->paramDV[iDV][3] == 0) && (this->paramDV[iDV][4] == 0)) { nValueDV = 2; } else { nValueDV = 1; } break; - default : + default: nValueDV = 1; } @@ -783,7 +792,6 @@ public: totalnValueDV += nValueDV; for (unsigned short iValueDV = 0; iValueDV < nValueDV; iValueDV++) { - if (i >= option_value.size()) { string newstring; newstring.append(this->name); @@ -823,12 +831,10 @@ class COptionFFDDef : public COptionBase { su2double**& CoordFFD; string*& FFDTag; -public: - COptionFFDDef(string option_field_name, unsigned short& nFFD_field, su2double**& coordFFD_field, string*& FFDTag_field) - : name(option_field_name), - nFFD(nFFD_field), - CoordFFD(coordFFD_field), - FFDTag(FFDTag_field) { + public: + COptionFFDDef(string option_field_name, unsigned short& nFFD_field, su2double**& coordFFD_field, + string*& FFDTag_field) + : name(option_field_name), nFFD(nFFD_field), CoordFFD(coordFFD_field), FFDTag(FFDTag_field) { nFFD = 0; CoordFFD = nullptr; FFDTag = nullptr; @@ -853,11 +859,10 @@ public: if (option_value[0].compare(";") == 0) { return name + ": may not have beginning semicolon"; } - if (option_value[option_value.size()-1].compare(";") == 0) { + if (option_value[option_value.size() - 1].compare(";") == 0) { return name + ": may not have ending semicolon"; } - // use the ";" token to determine the number of design variables // This works because semicolon is not one of the delimiters in tokenize string this->nFFD = 0; @@ -882,20 +887,20 @@ public: unsigned int i = 0; for (unsigned short iFFD = 0; iFFD < this->nFFD; iFFD++) { - nCoordFFD = 25; for (unsigned short iCoordFFD = 0; iCoordFFD < nCoordFFD; iCoordFFD++) { - ss << option_value[i] << " "; - if (iCoordFFD == 0) ss >> this->FFDTag[iFFD]; - else ss >> this->CoordFFD[iFFD][iCoordFFD-1]; + if (iCoordFFD == 0) + ss >> this->FFDTag[iFFD]; + else + ss >> this->CoordFFD[iFFD][iCoordFFD - 1]; i++; } - if (iFFD < (this->nFFD-1)) { + if (iFFD < (this->nFFD - 1)) { if (option_value[i].compare(";") != 0) { string newstring; newstring.append(this->name); @@ -904,7 +909,6 @@ public: } i++; } - } // Need to return something... @@ -919,11 +923,9 @@ class COptionFFDDegree : public COptionBase { unsigned short& nFFD; unsigned short**& DegreeFFD; -public: + public: COptionFFDDegree(string option_field_name, unsigned short& nFFD_field, unsigned short**& degreeFFD_field) - : name(option_field_name), - nFFD(nFFD_field), - DegreeFFD(degreeFFD_field) { + : name(option_field_name), nFFD(nFFD_field), DegreeFFD(degreeFFD_field) { nFFD = 0; DegreeFFD = nullptr; } @@ -945,11 +947,10 @@ public: if (option_value[0].compare(";") == 0) { return name + ": may not have beginning semicolon"; } - if (option_value[option_value.size()-1].compare(";") == 0) { + if (option_value[option_value.size() - 1].compare(";") == 0) { return name + ": may not have ending semicolon"; } - // use the ";" token to determine the number of design variables // This works because semicolon is not one of the delimiters in tokenize string this->nFFD = 0; @@ -972,7 +973,6 @@ public: unsigned int i = 0; for (unsigned short iFFD = 0; iFFD < this->nFFD; iFFD++) { - nDegreeFFD = 3; for (unsigned short iDegreeFFD = 0; iDegreeFFD < nDegreeFFD; iDegreeFFD++) { @@ -981,7 +981,7 @@ public: i++; } - if (iFFD < (this->nFFD-1)) { + if (iFFD < (this->nFFD - 1)) { if (option_value[i].compare(";") != 0) { string newstring; newstring.append(this->name); @@ -990,7 +990,6 @@ public: } i++; } - } // Need to return something... @@ -1001,22 +1000,22 @@ public: }; class COptionInlet : public COptionBase { - string name; // identifier for the option + string name; // identifier for the option unsigned short& size; string*& marker; su2double*& ttotal; su2double*& ptotal; su2double**& flowdir; -public: + public: COptionInlet(string option_field_name, unsigned short& nMarker_Inlet, string*& Marker_Inlet, su2double*& Ttotal, su2double*& Ptotal, su2double**& FlowDir) - : name(option_field_name), - size(nMarker_Inlet), - marker(Marker_Inlet), - ttotal(Ttotal), - ptotal(Ptotal), - flowdir(FlowDir) { + : name(option_field_name), + size(nMarker_Inlet), + marker(Marker_Inlet), + ttotal(Ttotal), + ptotal(Ptotal), + flowdir(FlowDir) { size = 0; marker = nullptr; ttotal = nullptr; @@ -1061,14 +1060,14 @@ public: bool err = false; auto getval = [&](unsigned short i, unsigned short j) { - istringstream ss(option_value[6*i + j]); + istringstream ss(option_value[6 * i + j]); su2double val; if (!(ss >> val)) err = true; return val; }; for (unsigned short i = 0; i < nVals; i++) { - marker[i].assign(option_value[6*i]); + marker[i].assign(option_value[6 * i]); ttotal[i] = getval(i, 1); ptotal[i] = getval(i, 2); flowdir[i][0] = getval(i, 3); @@ -1096,40 +1095,40 @@ template struct CStringValuesListHelper { static T* resize(unsigned short n) { return new T[n]; } static T& access(T* ptr, unsigned short i) { return ptr[i]; } - static void clear(T* ptr) { delete [] ptr; } + static void clear(T* ptr) { delete[] ptr; } }; // Class where the option is represented by (string, N * "some type", string, N * "some type", ...) template class COptionStringValuesList final : public COptionBase { - const string name; // identifier for the option - unsigned short& size; // number of string-value pairs - string*& strings; // the strings in the option - Type*& values; // the values per string - unsigned short& num_vals; // how many values per string - unsigned short optional_num_vals = 0; // num_vals points to this when it is not provided in the ctor. - -public: - COptionStringValuesList(string name_, unsigned short& size_, string*& strings_, - Type*& values_, unsigned short& num_vals_) : - name(name_), size(size_), strings(strings_), values(values_), num_vals(num_vals_) { + const string name; // identifier for the option + unsigned short& size; // number of string-value pairs + string*& strings; // the strings in the option + Type*& values; // the values per string + unsigned short& num_vals; // how many values per string + unsigned short optional_num_vals = 0; // num_vals points to this when it is not provided in the ctor. + + public: + COptionStringValuesList(string name_, unsigned short& size_, string*& strings_, Type*& values_, + unsigned short& num_vals_) + : name(name_), size(size_), strings(strings_), values(values_), num_vals(num_vals_) { strings = nullptr; values = nullptr; } - COptionStringValuesList(string name_, unsigned short& size_, string*& strings_, Type*& values_) : - name(name_), size(size_), strings(strings_), values(values_), num_vals(optional_num_vals) { + COptionStringValuesList(string name_, unsigned short& size_, string*& strings_, Type*& values_) + : name(name_), size(size_), strings(strings_), values(values_), num_vals(optional_num_vals) { strings = nullptr; values = nullptr; } ~COptionStringValuesList() { - delete [] strings; + delete[] strings; strings = nullptr; for (unsigned short i = 0; i < size; ++i) { CStringValuesListHelper::clear(values[i]); } - delete [] values; + delete[] values; values = nullptr; } @@ -1188,32 +1187,32 @@ public: } void SetDefault() override { - size = 0; // There is no default value for lists + size = 0; // There is no default value for lists num_vals = 0; } }; - template class COptionRiemann : public COptionBase { - -protected: + protected: map m; - string name; // identifier for the option - unsigned short & size; - string * & marker; - unsigned short* & field; // Reference to the field name - su2double * & var1; - su2double * & var2; - su2double ** & flowdir; - -public: - COptionRiemann(string option_field_name, unsigned short & nMarker_Riemann, string* & Marker_Riemann, unsigned short* & option_field, const map m, su2double* & var1, su2double* & var2, su2double** & FlowDir) : size(nMarker_Riemann), - marker(Marker_Riemann), field(option_field), var1(var1), var2(var2), flowdir(FlowDir) { + string name; // identifier for the option + unsigned short& size; + string*& marker; + unsigned short*& field; // Reference to the field name + su2double*& var1; + su2double*& var2; + su2double**& flowdir; + + public: + COptionRiemann(string option_field_name, unsigned short& nMarker_Riemann, string*& Marker_Riemann, + unsigned short*& option_field, const map m, su2double*& var1, su2double*& var2, + su2double**& FlowDir) + : size(nMarker_Riemann), marker(Marker_Riemann), field(option_field), var1(var1), var2(var2), flowdir(FlowDir) { this->name = option_field_name; this->m = m; } - ~COptionRiemann() override {}; + ~COptionRiemann() override{}; string SetValue(const vector& option_value) override { COptionBase::SetValue(option_value); @@ -1254,36 +1253,36 @@ public: } for (unsigned long i = 0; i < nVals; i++) { - this->marker[i].assign(option_value[7*i]); - // Check to see if the enum value is in the map - if (this->m.find(option_value[7*i + 1]) == m.end()) { - string str; - str.append(this->name); - str.append(": invalid option value "); - str.append(option_value[0]); - str.append(". Check current SU2 options in config_template.cfg."); - return str; - } - Tenum val = this->m[option_value[7*i + 1]]; + this->marker[i].assign(option_value[7 * i]); + // Check to see if the enum value is in the map + if (this->m.find(option_value[7 * i + 1]) == m.end()) { + string str; + str.append(this->name); + str.append(": invalid option value "); + str.append(option_value[0]); + str.append(". Check current SU2 options in config_template.cfg."); + return str; + } + Tenum val = this->m[option_value[7 * i + 1]]; this->field[i] = val; - istringstream ss_1st(option_value[7*i + 2]); + istringstream ss_1st(option_value[7 * i + 2]); if (!(ss_1st >> this->var1[i])) { return badValue("Riemann", this->name); } - istringstream ss_2nd(option_value[7*i + 3]); + istringstream ss_2nd(option_value[7 * i + 3]); if (!(ss_2nd >> this->var2[i])) { return badValue("Riemann", this->name); } - istringstream ss_3rd(option_value[7*i + 4]); + istringstream ss_3rd(option_value[7 * i + 4]); if (!(ss_3rd >> this->flowdir[i][0])) { return badValue("Riemann", this->name); } - istringstream ss_4th(option_value[7*i + 5]); + istringstream ss_4th(option_value[7 * i + 5]); if (!(ss_4th >> this->flowdir[i][1])) { return badValue("Riemann", this->name); } - istringstream ss_5th(option_value[7*i + 6]); + istringstream ss_5th(option_value[7 * i + 6]); if (!(ss_5th >> this->flowdir[i][2])) { return badValue("Riemann", this->name); } @@ -1297,31 +1296,39 @@ public: this->var1 = nullptr; this->var2 = nullptr; this->flowdir = nullptr; - this->size = 0; // There is no default value for list + this->size = 0; // There is no default value for list } }; template -class COptionGiles : public COptionBase{ - +class COptionGiles : public COptionBase { map m; - unsigned short & size; - string * & marker; - unsigned short* & field; // Reference to the fieldname - string name; // identifier for the option - su2double * & var1; - su2double * & var2; - su2double ** & flowdir; - su2double * & relfac1; - su2double * & relfac2; - -public: - COptionGiles(string option_field_name, unsigned short & nMarker_Giles, string* & Marker_Giles, unsigned short* & option_field, const map m, su2double* & var1, su2double* & var2, su2double** & FlowDir, su2double* & relfac1, su2double* & relfac2) : size(nMarker_Giles), - marker(Marker_Giles), field(option_field), var1(var1), var2(var2), flowdir(FlowDir), relfac1(relfac1), relfac2(relfac2) { + unsigned short& size; + string*& marker; + unsigned short*& field; // Reference to the fieldname + string name; // identifier for the option + su2double*& var1; + su2double*& var2; + su2double**& flowdir; + su2double*& relfac1; + su2double*& relfac2; + + public: + COptionGiles(string option_field_name, unsigned short& nMarker_Giles, string*& Marker_Giles, + unsigned short*& option_field, const map m, su2double*& var1, su2double*& var2, + su2double**& FlowDir, su2double*& relfac1, su2double*& relfac2) + : size(nMarker_Giles), + marker(Marker_Giles), + field(option_field), + var1(var1), + var2(var2), + flowdir(FlowDir), + relfac1(relfac1), + relfac2(relfac2) { this->name = option_field_name; this->m = m; } - ~COptionGiles() override {}; + ~COptionGiles() override{}; string SetValue(const vector& option_value) override { COptionBase::SetValue(option_value); @@ -1368,44 +1375,44 @@ public: } for (unsigned int i = 0; i < nVals; i++) { - this->marker[i].assign(option_value[9*i]); - // Check to see if the enum value is in the map - if (this->m.find(option_value[9*i + 1]) == m.end()) { - string str; - str.append(this->name); - str.append(": invalid option value "); - str.append(option_value[0]); - str.append(". Check current SU2 options in config_template.cfg."); - return str; - } - Tenum val = this->m[option_value[9*i + 1]]; + this->marker[i].assign(option_value[9 * i]); + // Check to see if the enum value is in the map + if (this->m.find(option_value[9 * i + 1]) == m.end()) { + string str; + str.append(this->name); + str.append(": invalid option value "); + str.append(option_value[0]); + str.append(". Check current SU2 options in config_template.cfg."); + return str; + } + Tenum val = this->m[option_value[9 * i + 1]]; this->field[i] = val; - istringstream ss_1st(option_value[9*i + 2]); + istringstream ss_1st(option_value[9 * i + 2]); if (!(ss_1st >> this->var1[i])) { return badValue("Giles BC", this->name); } - istringstream ss_2nd(option_value[9*i + 3]); + istringstream ss_2nd(option_value[9 * i + 3]); if (!(ss_2nd >> this->var2[i])) { return badValue("Giles BC", this->name); } - istringstream ss_3rd(option_value[9*i + 4]); + istringstream ss_3rd(option_value[9 * i + 4]); if (!(ss_3rd >> this->flowdir[i][0])) { return badValue("Giles BC", this->name); } - istringstream ss_4th(option_value[9*i + 5]); + istringstream ss_4th(option_value[9 * i + 5]); if (!(ss_4th >> this->flowdir[i][1])) { return badValue("Giles BC", this->name); } - istringstream ss_5th(option_value[9*i + 6]); + istringstream ss_5th(option_value[9 * i + 6]); if (!(ss_5th >> this->flowdir[i][2])) { return badValue("Giles BC", this->name); } - istringstream ss_6th(option_value[9*i + 7]); + istringstream ss_6th(option_value[9 * i + 7]); if (!(ss_6th >> this->relfac1[i])) { return badValue("Giles BC", this->name); } - istringstream ss_7th(option_value[9*i + 8]); + istringstream ss_7th(option_value[9 * i + 8]); if (!(ss_7th >> this->relfac2[i])) { return badValue("Giles BC", this->name); } @@ -1421,25 +1428,21 @@ public: this->relfac1 = nullptr; this->relfac2 = nullptr; this->flowdir = nullptr; - this->size = 0; // There is no default value for list + this->size = 0; // There is no default value for list } }; class COptionExhaust : public COptionBase { - string name; // identifier for the option + string name; // identifier for the option unsigned short& size; string*& marker; su2double*& ttotal; su2double*& ptotal; -public: - COptionExhaust(string option_field_name, unsigned short& nMarker_Exhaust, string*& Marker_Exhaust, - su2double*& Ttotal, su2double*& Ptotal) - : name(option_field_name), - size(nMarker_Exhaust), - marker(Marker_Exhaust), - ttotal(Ttotal), - ptotal(Ptotal) { + public: + COptionExhaust(string option_field_name, unsigned short& nMarker_Exhaust, string*& Marker_Exhaust, su2double*& Ttotal, + su2double*& Ptotal) + : name(option_field_name), size(nMarker_Exhaust), marker(Marker_Exhaust), ttotal(Ttotal), ptotal(Ptotal) { size = 0; marker = nullptr; ttotal = nullptr; @@ -1472,12 +1475,12 @@ public: ptotal = new su2double[nVals]; for (unsigned short i = 0; i < nVals; i++) { - this->marker[i].assign(option_value[3*i]); + this->marker[i].assign(option_value[3 * i]); - istringstream ss_1st(option_value[3*i + 1]); + istringstream ss_1st(option_value[3 * i + 1]); if (!(ss_1st >> ttotal[i])) return badValue("exhaust fixed", name); - istringstream ss_2nd(option_value[3*i + 2]); + istringstream ss_2nd(option_value[3 * i + 2]); if (!(ss_2nd >> ptotal[i])) return badValue("exhaust fixed", name); } return ""; @@ -1487,7 +1490,7 @@ public: }; class COptionPeriodic : public COptionBase { - string name; // identifier for the option + string name; // identifier for the option unsigned short& size; string*& marker_bound; string*& marker_donor; @@ -1495,16 +1498,16 @@ class COptionPeriodic : public COptionBase { su2double**& rot_angles; su2double**& translation; -public: + public: COptionPeriodic(const string option_field_name, unsigned short& nMarker_PerBound, string*& Marker_PerBound, string*& Marker_PerDonor, su2double**& RotCenter, su2double**& RotAngles, su2double**& Translation) - : name(option_field_name), - size(nMarker_PerBound), - marker_bound(Marker_PerBound), - marker_donor(Marker_PerDonor), - rot_center(RotCenter), - rot_angles(RotAngles), - translation(Translation) { + : name(option_field_name), + size(nMarker_PerBound), + marker_bound(Marker_PerBound), + marker_donor(Marker_PerDonor), + rot_center(RotCenter), + rot_angles(RotAngles), + translation(Translation) { size = 0; COptionPeriodic::SetDefault(); } @@ -1535,7 +1538,7 @@ public: return name + ": must have a number of entries divisible by 11"; } - const unsigned short nVals = 2 * (totalVals / mod_num); // "2" to account for periodic and donor + const unsigned short nVals = 2 * (totalVals / mod_num); // "2" to account for periodic and donor size = nVals; marker_bound = new string[nVals]; marker_donor = new string[nVals]; @@ -1548,43 +1551,43 @@ public: translation[i] = new su2double[3]; } - const su2double deg2rad = PI_NUMBER/180.0; + const su2double deg2rad = PI_NUMBER / 180.0; bool err = false; auto getval = [&](unsigned short i, unsigned short j) { - istringstream ss(option_value[mod_num*i + j]); + istringstream ss(option_value[mod_num * i + j]); su2double val; if (!(ss >> val)) err = true; return val; }; for (unsigned short i = 0; i < nVals / 2; i++) { - marker_bound[i].assign(option_value[mod_num*i]); - marker_donor[i].assign(option_value[mod_num*i+1]); + marker_bound[i].assign(option_value[mod_num * i]); + marker_donor[i].assign(option_value[mod_num * i + 1]); /*--- Mirror the connection between markers. ---*/ - marker_bound[i+nVals/2] = marker_donor[i]; - marker_donor[i+nVals/2] = marker_bound[i]; + marker_bound[i + nVals / 2] = marker_donor[i]; + marker_donor[i + nVals / 2] = marker_bound[i]; - rot_center[i][0] = rot_center[i+nVals/2][0] = getval(i, 2); - rot_center[i][1] = rot_center[i+nVals/2][1] = getval(i, 3); - rot_center[i][2] = rot_center[i+nVals/2][2] = getval(i, 4); + rot_center[i][0] = rot_center[i + nVals / 2][0] = getval(i, 2); + rot_center[i][1] = rot_center[i + nVals / 2][1] = getval(i, 3); + rot_center[i][2] = rot_center[i + nVals / 2][2] = getval(i, 4); - rot_angles[i][0] = rot_angles[i+nVals/2][0] = getval(i, 5) * deg2rad; - rot_angles[i][1] = rot_angles[i+nVals/2][1] = getval(i, 6) * deg2rad; - rot_angles[i][2] = rot_angles[i+nVals/2][2] = getval(i, 7) * deg2rad; + rot_angles[i][0] = rot_angles[i + nVals / 2][0] = getval(i, 5) * deg2rad; + rot_angles[i][1] = rot_angles[i + nVals / 2][1] = getval(i, 6) * deg2rad; + rot_angles[i][2] = rot_angles[i + nVals / 2][2] = getval(i, 7) * deg2rad; - translation[i][0] = translation[i+nVals/2][0] = getval(i, 8); - translation[i][1] = translation[i+nVals/2][1] = getval(i, 9); - translation[i][2] = translation[i+nVals/2][2] = getval(i, 10); + translation[i][0] = translation[i + nVals / 2][0] = getval(i, 8); + translation[i][1] = translation[i + nVals / 2][1] = getval(i, 9); + translation[i][2] = translation[i + nVals / 2][2] = getval(i, 10); /*--- Mirror the rotational angles and translation vector (rotational center does not need to move). ---*/ - rot_angles[i+nVals/2][0] *= -1; - rot_angles[i+nVals/2][1] *= -1; - rot_angles[i+nVals/2][2] *= -1; - translation[i+nVals/2][0] *= -1; - translation[i+nVals/2][1] *= -1; - translation[i+nVals/2][2] *= -1; + rot_angles[i + nVals / 2][0] *= -1; + rot_angles[i + nVals / 2][1] *= -1; + rot_angles[i + nVals / 2][2] *= -1; + translation[i + nVals / 2][0] *= -1; + translation[i + nVals / 2][1] *= -1; + translation[i + nVals / 2][2] *= -1; if (err) return badValue("periodic", name); } @@ -1602,18 +1605,19 @@ public: }; class COptionTurboPerformance : public COptionBase { - string name; // identifier for the option - unsigned short & size; - string * & marker_turboIn; - string * & marker_turboOut; - -public: - COptionTurboPerformance(const string option_field_name, unsigned short & nMarker_TurboPerf, - string* & Marker_TurboBoundIn, string* & Marker_TurboBoundOut) : size(nMarker_TurboPerf), marker_turboIn(Marker_TurboBoundIn), marker_turboOut(Marker_TurboBoundOut){ + string name; // identifier for the option + unsigned short& size; + string*& marker_turboIn; + string*& marker_turboOut; + + public: + COptionTurboPerformance(const string option_field_name, unsigned short& nMarker_TurboPerf, + string*& Marker_TurboBoundIn, string*& Marker_TurboBoundOut) + : size(nMarker_TurboPerf), marker_turboIn(Marker_TurboBoundIn), marker_turboOut(Marker_TurboBoundOut) { this->name = option_field_name; } - ~COptionTurboPerformance() override {}; + ~COptionTurboPerformance() override{}; string SetValue(const vector& option_value) override { COptionBase::SetValue(option_value); const int mod_num = 2; @@ -1621,7 +1625,7 @@ public: unsigned long totalVals = option_value.size(); if ((totalVals == 1) && (option_value[0].compare("NONE") == 0)) { this->size = 0; - this->marker_turboIn= nullptr; + this->marker_turboIn = nullptr; this->marker_turboOut = nullptr; return ""; } @@ -1631,8 +1635,9 @@ public: newstring.append(this->name); newstring.append(": must have a number of entries divisible by 2"); this->size = 0; - this->marker_turboIn= nullptr; - this->marker_turboOut = nullptr;; + this->marker_turboIn = nullptr; + this->marker_turboOut = nullptr; + ; return newstring; } @@ -1641,59 +1646,60 @@ public: this->marker_turboIn = new string[nVals]; this->marker_turboOut = new string[nVals]; for (unsigned long i = 0; i < nVals; i++) { - this->marker_turboIn[i].assign(option_value[mod_num*i]); - this->marker_turboOut[i].assign(option_value[mod_num*i+1]); - } - + this->marker_turboIn[i].assign(option_value[mod_num * i]); + this->marker_turboOut[i].assign(option_value[mod_num * i + 1]); + } return ""; } void SetDefault() override { this->size = 0; - this->marker_turboIn= nullptr; + this->marker_turboIn = nullptr; this->marker_turboOut = nullptr; } }; class COptionPython : public COptionBase { string name; -public: - COptionPython(const string name) { - this->name = name; - } - ~COptionPython() override {}; + + public: + COptionPython(const string name) { this->name = name; } + ~COptionPython() override{}; // No checking happens with python options string SetValue(const vector& option_value) override { COptionBase::SetValue(option_value); return ""; } // No defaults with python options - void SetDefault() override { - return; - }; + void SetDefault() override { return; }; }; class COptionActDisk : public COptionBase { - string name; // identifier for the option - unsigned short & inlet_size; - unsigned short & outlet_size; - string * & marker_inlet; - string * & marker_outlet; - su2double ** & press_jump; - su2double ** & temp_jump; - su2double ** & omega; - -public: - COptionActDisk(const string name, - unsigned short & nMarker_ActDiskInlet, unsigned short & nMarker_ActDiskOutlet, string * & Marker_ActDiskInlet, string * & Marker_ActDiskOutlet, - su2double ** & ActDisk_PressJump, su2double ** & ActDisk_TempJump, su2double ** & ActDisk_Omega) : - inlet_size(nMarker_ActDiskInlet), outlet_size(nMarker_ActDiskOutlet), marker_inlet(Marker_ActDiskInlet), marker_outlet(Marker_ActDiskOutlet), - press_jump(ActDisk_PressJump), temp_jump(ActDisk_TempJump), omega(ActDisk_Omega) { + string name; // identifier for the option + unsigned short& inlet_size; + unsigned short& outlet_size; + string*& marker_inlet; + string*& marker_outlet; + su2double**& press_jump; + su2double**& temp_jump; + su2double**& omega; + + public: + COptionActDisk(const string name, unsigned short& nMarker_ActDiskInlet, unsigned short& nMarker_ActDiskOutlet, + string*& Marker_ActDiskInlet, string*& Marker_ActDiskOutlet, su2double**& ActDisk_PressJump, + su2double**& ActDisk_TempJump, su2double**& ActDisk_Omega) + : inlet_size(nMarker_ActDiskInlet), + outlet_size(nMarker_ActDiskOutlet), + marker_inlet(Marker_ActDiskInlet), + marker_outlet(Marker_ActDiskOutlet), + press_jump(ActDisk_PressJump), + temp_jump(ActDisk_TempJump), + omega(ActDisk_Omega) { this->name = name; } - ~COptionActDisk() override {}; + ~COptionActDisk() override{}; string SetValue(const vector& option_value) override { COptionBase::SetValue(option_value); const int mod_num = 8; @@ -1729,29 +1735,29 @@ public: string tname = "actuator disk"; for (int i = 0; i < this->inlet_size; i++) { - this->marker_inlet[i].assign(option_value[mod_num*i]); - this->marker_outlet[i].assign(option_value[mod_num*i+1]); - istringstream ss_1st(option_value[mod_num*i + 2]); + this->marker_inlet[i].assign(option_value[mod_num * i]); + this->marker_outlet[i].assign(option_value[mod_num * i + 1]); + istringstream ss_1st(option_value[mod_num * i + 2]); if (!(ss_1st >> this->press_jump[i][0])) { return badValue(tname, this->name); } - istringstream ss_2nd(option_value[mod_num*i + 3]); + istringstream ss_2nd(option_value[mod_num * i + 3]); if (!(ss_2nd >> this->temp_jump[i][0])) { return badValue(tname, this->name); } - istringstream ss_3rd(option_value[mod_num*i + 4]); + istringstream ss_3rd(option_value[mod_num * i + 4]); if (!(ss_3rd >> this->omega[i][0])) { return badValue(tname, this->name); } - istringstream ss_4th(option_value[mod_num*i + 5]); + istringstream ss_4th(option_value[mod_num * i + 5]); if (!(ss_4th >> this->press_jump[i][1])) { return badValue(tname, this->name); } - istringstream ss_5th(option_value[mod_num*i + 6]); + istringstream ss_5th(option_value[mod_num * i + 6]); if (!(ss_5th >> this->temp_jump[i][1])) { return badValue(tname, this->name); } - istringstream ss_6th(option_value[mod_num*i + 7]); + istringstream ss_6th(option_value[mod_num * i + 7]); if (!(ss_6th >> this->omega[i][1])) { return badValue(tname, this->name); } @@ -1770,22 +1776,22 @@ public: }; class COptionWallFunction : public COptionBase { - string name; // identifier for the option + string name; // identifier for the option unsigned short& nMarkers; string*& markers; WALL_FUNCTIONS*& walltype; unsigned short**& intInfo; su2double**& doubleInfo; -public: + public: COptionWallFunction(const string name_WF, unsigned short& nMarker_WF, string*& Marker_WF, WALL_FUNCTIONS*& type_WF, unsigned short**& intInfo_WF, su2double**& doubleInfo_WF) - : name(name_WF), - nMarkers(nMarker_WF), - markers(Marker_WF), - walltype(type_WF), - intInfo(intInfo_WF), - doubleInfo(doubleInfo_WF) { + : name(name_WF), + nMarkers(nMarker_WF), + markers(Marker_WF), + walltype(type_WF), + intInfo(intInfo_WF), + doubleInfo(doubleInfo_WF) { nMarkers = 0; COptionWallFunction::SetDefault(); } @@ -1813,8 +1819,7 @@ public: /*--- Determine the number of markers, for which a wall function treatment has been specified. ---*/ unsigned short counter = 0, nVals = 0; - while (counter < totalSize ) { - + while (counter < totalSize) { /* Update the counter for the number of markers specified and store the current index for possible error messages. */ ++nVals; @@ -1826,17 +1831,18 @@ public: const unsigned short indWallType = counter; auto typeWF = WALL_FUNCTIONS::NONE; bool validWF = true; - if (counter == totalSize) validWF = false; + if (counter == totalSize) + validWF = false; else { map::const_iterator it; it = Wall_Functions_Map.find(option_value[counter]); - if(it == Wall_Functions_Map.end()) + if (it == Wall_Functions_Map.end()) validWF = false; else - typeWF = it->second; + typeWF = it->second; } - if (!validWF ) { + if (!validWF) { string newstring; newstring.append(this->name); newstring.append(": Invalid wall function type, "); @@ -1852,11 +1858,18 @@ public: /*--- For some wall function types some additional info must be specified. Hence the counter must be updated accordingly. ---*/ - switch( typeWF ) { - case WALL_FUNCTIONS::EQUILIBRIUM_MODEL: counter += 3; break; - case WALL_FUNCTIONS::NONEQUILIBRIUM_MODEL: counter += 2; break; - case WALL_FUNCTIONS::LOGARITHMIC_MODEL: counter += 3; break; - default: break; + switch (typeWF) { + case WALL_FUNCTIONS::EQUILIBRIUM_MODEL: + counter += 3; + break; + case WALL_FUNCTIONS::NONEQUILIBRIUM_MODEL: + counter += 2; + break; + case WALL_FUNCTIONS::LOGARITHMIC_MODEL: + counter += 3; + break; + default: + break; } /* In case the counter is larger than totalSize, the data for @@ -1874,17 +1887,16 @@ public: } /* Allocate the memory to store the data for the wall function markers. */ - this->nMarkers = nVals; - this->markers = new string[nVals]; - this->walltype = new WALL_FUNCTIONS[nVals]; - this->intInfo = new unsigned short*[nVals](); + this->nMarkers = nVals; + this->markers = new string[nVals]; + this->walltype = new WALL_FUNCTIONS[nVals]; + this->intInfo = new unsigned short*[nVals](); this->doubleInfo = new su2double*[nVals](); /*--- Loop over the wall markers and store the info in the appropriate arrays. ---*/ counter = 0; - for (unsigned short i=0; imarkers[i].assign(option_value[counter++]); @@ -1897,13 +1909,11 @@ public: /*--- For some wall function types, some additional info is needed, which is extracted from option_value. ---*/ - switch( this->walltype[i] ) { - + switch (this->walltype[i]) { case WALL_FUNCTIONS::EQUILIBRIUM_MODEL: { - /* LES equilibrium wall model. The exchange distance, stretching factor and number of points in the wall model must be specified. */ - this->intInfo[i] = new unsigned short[1]; + this->intInfo[i] = new unsigned short[1]; this->doubleInfo[i] = new su2double[2]; istringstream ss_1st(option_value[counter++]); @@ -1925,24 +1935,23 @@ public: } case WALL_FUNCTIONS::NONEQUILIBRIUM_MODEL: { - /* LES non-equilibrium model. The RANS turbulence model and the exchange distance need to be specified. */ - this->intInfo[i] = new unsigned short[1]; + this->intInfo[i] = new unsigned short[1]; this->doubleInfo[i] = new su2double[1]; /* Check for a valid RANS turbulence model. */ map::const_iterator iit; iit = Turb_Model_Map.find(option_value[counter++]); - if(iit == Turb_Model_Map.end()) { + if (iit == Turb_Model_Map.end()) { string newstring; newstring.append(this->name); newstring.append(", marker "); newstring.append(this->markers[i]); newstring.append(", wall function type "); - newstring.append(option_value[counter-2]); + newstring.append(option_value[counter - 2]); newstring.append(": Invalid RANS turbulence model, "); - newstring.append(option_value[counter-1]); + newstring.append(option_value[counter - 1]); newstring.append(", specified"); return newstring; } @@ -1956,10 +1965,9 @@ public: break; } case WALL_FUNCTIONS::LOGARITHMIC_MODEL: { - /* LES Logarithmic law-of-the-wall model. The exchange distance, stretching factor and number of points in the wall model must be specified. */ - this->intInfo[i] = new unsigned short[1]; + this->intInfo[i] = new unsigned short[1]; this->doubleInfo[i] = new su2double[2]; istringstream ss_1st(option_value[counter++]); @@ -1980,7 +1988,7 @@ public: break; } - default: // Just to avoid a compiler warning. + default: // Just to avoid a compiler warning. break; } } diff --git a/Common/include/parallelization/mpi_structure.cpp b/Common/include/parallelization/mpi_structure.cpp index cd8eae4d5f0..43b2c86a239 100644 --- a/Common/include/parallelization/mpi_structure.cpp +++ b/Common/include/parallelization/mpi_structure.cpp @@ -26,8 +26,7 @@ */ #include "mpi_structure.hpp" -#include // memcpy - +#include // memcpy /* Initialise the MPI Communicator Rank and Size */ int CBaseMPIWrapper::Rank = 0; @@ -41,12 +40,11 @@ CBaseMPIWrapper::Comm CBaseMPIWrapper::currentComm = 0; // dummy value #endif #ifdef HAVE_MPI -int CBaseMPIWrapper::MinRankError; +int CBaseMPIWrapper::MinRankError; bool CBaseMPIWrapper::winMinRankErrorInUse = false; CBaseMPIWrapper::Win CBaseMPIWrapper::winMinRankError; -void CBaseMPIWrapper::Error(std::string ErrorMsg, std::string FunctionName){ - +void CBaseMPIWrapper::Error(std::string ErrorMsg, std::string FunctionName) { /* Set MinRankError to Rank, as the error message is called on this rank. */ MinRankError = Rank; int flag = 0; @@ -58,13 +56,12 @@ void CBaseMPIWrapper::Error(std::string ErrorMsg, std::string FunctionName){ /* Try to complete the non-blocking barrier call for a second. */ double startTime = SU2_MPI::Wtime(); - while( true ) { - + while (true) { MPI_Test(&barrierRequest, &flag, MPI_STATUS_IGNORE); - if( flag ) break; + if (flag) break; double currentTime = SU2_MPI::Wtime(); - if(currentTime > startTime + 1.0) break; + if (currentTime > startTime + 1.0) break; } #else /* MPI_Ibarrier function is not supported. Simply wait for one @@ -76,23 +73,21 @@ void CBaseMPIWrapper::Error(std::string ErrorMsg, std::string FunctionName){ #endif #endif - if( flag ) { + if (flag) { /* The barrier is completed and hence the error call is collective. Set MinRankError to 0. */ MinRankError = 0; - } - else { + } else { /* The error call is not collective and the minimum rank must be determined by one sided communication. Loop over the lower numbered ranks to check if they participate in the error message. */ - for(int i=0; i(recvbuf)[i+recvshift] = static_cast(sendbuf)[i+sendshift]; + static_cast(recvbuf)[i + recvshift] = static_cast(sendbuf)[i + sendshift]; } } else { int scalarsize; MPI_Type_size(datatype, &scalarsize); - const char* src = static_cast(sendbuf) + sendshift*static_cast(scalarsize); - char* dest = static_cast(recvbuf) + recvshift*static_cast(scalarsize); - std::memcpy(static_cast(dest), static_cast(src), size*static_cast(scalarsize)); + const char* src = static_cast(sendbuf) + sendshift * static_cast(scalarsize); + char* dest = static_cast(recvbuf) + recvshift * static_cast(scalarsize); + std::memcpy(static_cast(dest), static_cast(src), size * static_cast(scalarsize)); } } -#else // HAVE_MPI +#else // HAVE_MPI -void CBaseMPIWrapper::Error(std::string ErrorMsg, std::string FunctionName){ - if (Rank == 0){ +void CBaseMPIWrapper::Error(std::string ErrorMsg, std::string FunctionName) { + if (Rank == 0) { std::cout << std::endl << std::endl; std::cout << "Error in \"" << FunctionName << "\": " << std::endl; - std::cout << "-------------------------------------------------------------------------" << std::endl; + std::cout << "-------------------------------------------------------------------------" << std::endl; std::cout << ErrorMsg << std::endl; - std::cout << "------------------------------ Error Exit -------------------------------" << std::endl; + std::cout << "------------------------------ Error Exit -------------------------------" << std::endl; std::cout << std::endl << std::endl; } Abort(currentComm, 0); } -void CBaseMPIWrapper::CopyData(const void* sendbuf, void* recvbuf, int size, Datatype datatype, int recvshift, int sendshift) { +void CBaseMPIWrapper::CopyData(const void* sendbuf, void* recvbuf, int size, Datatype datatype, int recvshift, + int sendshift) { switch (datatype) { case MPI_DOUBLE: for (int i = 0; i < size; i++) { - static_cast(recvbuf)[i+recvshift] = static_cast(sendbuf)[i+sendshift]; + static_cast(recvbuf)[i + recvshift] = static_cast(sendbuf)[i + sendshift]; } break; case MPI_UNSIGNED_LONG: for (int i = 0; i < size; i++) { - static_cast(recvbuf)[i+recvshift] = static_cast(sendbuf)[i+sendshift]; + static_cast(recvbuf)[i + recvshift] = static_cast(sendbuf)[i + sendshift]; } break; case MPI_LONG: for (int i = 0; i < size; i++) { - static_cast(recvbuf)[i+recvshift] = static_cast(sendbuf)[i+sendshift]; + static_cast(recvbuf)[i + recvshift] = static_cast(sendbuf)[i + sendshift]; } break; case MPI_UNSIGNED_SHORT: for (int i = 0; i < size; i++) { - static_cast(recvbuf)[i+recvshift] = static_cast(sendbuf)[i+sendshift]; + static_cast(recvbuf)[i + recvshift] = + static_cast(sendbuf)[i + sendshift]; } break; case MPI_CHAR: for (int i = 0; i < size; i++) { - static_cast(recvbuf)[i+recvshift] = static_cast(sendbuf)[i+sendshift]; + static_cast(recvbuf)[i + recvshift] = static_cast(sendbuf)[i + sendshift]; } break; case MPI_SHORT: for (int i = 0; i < size; i++) { - static_cast(recvbuf)[i+recvshift] = static_cast(sendbuf)[i+sendshift]; + static_cast(recvbuf)[i + recvshift] = static_cast(sendbuf)[i + sendshift]; } break; case MPI_INT: for (int i = 0; i < size; i++) { - static_cast(recvbuf)[i+recvshift] = static_cast(sendbuf)[i+sendshift]; + static_cast(recvbuf)[i + recvshift] = static_cast(sendbuf)[i + sendshift]; } break; default: @@ -186,6 +184,6 @@ void CBaseMPIWrapper::CopyData(const void* sendbuf, void* recvbuf, int size, Dat #if defined CODI_REVERSE_TYPE || defined CODI_FORWARD_TYPE MediTypes* mediTypes; #include -#endif // defined CODI_REVERSE_TYPE || defined CODI_FORWARD_TYPE +#endif // defined CODI_REVERSE_TYPE || defined CODI_FORWARD_TYPE -#endif // HAVE_MPI +#endif // HAVE_MPI diff --git a/Common/include/parallelization/mpi_structure.hpp b/Common/include/parallelization/mpi_structure.hpp index a18ac7bb97d..1df7281ccbd 100644 --- a/Common/include/parallelization/mpi_structure.hpp +++ b/Common/include/parallelization/mpi_structure.hpp @@ -105,7 +105,8 @@ class CBaseMPIWrapper { static Win winMinRankError; public: - static void CopyData(const void* sendbuf, void* recvbuf, int size, Datatype datatype, int recvshift=0, int sendshift=0); + static void CopyData(const void* sendbuf, void* recvbuf, int size, Datatype datatype, int recvshift = 0, + int sendshift = 0); static void Error(std::string ErrorMsg, std::string FunctionName); @@ -174,7 +175,7 @@ class CBaseMPIWrapper { static inline void Wait(Request* request, Status* status) { MPI_Wait(request, status); } - static inline int Request_free(Request *request) { return MPI_Request_free(request); } + static inline int Request_free(Request* request) { return MPI_Request_free(request); } static inline void Testall(int count, Request* array_of_requests, int* flag, Status* array_of_statuses) { MPI_Testall(count, array_of_requests, flag, array_of_statuses); @@ -377,7 +378,7 @@ class CMediMPIWrapper : public CBaseMPIWrapper { static inline void Wait(SU2_MPI::Request* request, Status* status) { AMPI_Wait(request, status); } - static inline int Request_free(Request *request) { return AMPI_Request_free(request); } + static inline int Request_free(Request* request) { return AMPI_Request_free(request); } static inline void Testall(int count, Request* array_of_requests, int* flag, Status* array_of_statuses) { AMPI_Testall(count, array_of_requests, flag, array_of_statuses); @@ -506,7 +507,8 @@ class CBaseMPIWrapper { static Comm currentComm; public: - static void CopyData(const void* sendbuf, void* recvbuf, int size, Datatype datatype, int recvshift=0, int sendshift=0); + static void CopyData(const void* sendbuf, void* recvbuf, int size, Datatype datatype, int recvshift = 0, + int sendshift = 0); static void Error(std::string ErrorMsg, std::string FunctionName); @@ -539,7 +541,7 @@ class CBaseMPIWrapper { static inline void Wait(Request* request, Status* status) {} - static inline int Request_free(Request *request) { return 0; } + static inline int Request_free(Request* request) { return 0; } static inline void Waitall(int nrequests, Request* request, Status* status) {} diff --git a/Common/include/parallelization/omp_structure.hpp b/Common/include/parallelization/omp_structure.hpp index 90470a0c800..de19ec1e544 100644 --- a/Common/include/parallelization/omp_structure.hpp +++ b/Common/include/parallelization/omp_structure.hpp @@ -63,7 +63,7 @@ /*--- The generic start of OpenMP constructs. ---*/ #define SU2_OMP(ARGS) PRAGMIZE(omp ARGS) -#else // Compile without OpenMP +#else // Compile without OpenMP #include /*--- Disable pragmas to quiet compilation warnings. ---*/ @@ -72,32 +72,32 @@ /*! * \brief Maximum number of threads available. */ -inline constexpr int omp_get_max_threads() {return 1;} +inline constexpr int omp_get_max_threads() { return 1; } /*! * \brief Number of threads in current team. */ -inline constexpr int omp_get_num_threads() {return 1;} +inline constexpr int omp_get_num_threads() { return 1; } /*! * \brief Set the maximum number of threads. */ -inline void omp_set_num_threads(int) { } +inline void omp_set_num_threads(int) {} /*! * \brief Index of current thread, akin to MPI rank. */ -inline constexpr int omp_get_thread_num() {return 0;} +inline constexpr int omp_get_thread_num() { return 0; } /*! * \brief Returns true if inside a parallel section. */ -inline constexpr bool omp_in_parallel() {return false;} +inline constexpr bool omp_in_parallel() { return false; } /*! * \brief Return the wall time. */ -inline passivedouble omp_get_wtime() {return passivedouble(clock()) / CLOCKS_PER_SEC;} +inline passivedouble omp_get_wtime() { return passivedouble(clock()) / CLOCKS_PER_SEC; } /*! * \brief Dummy lock type and associated functions. @@ -105,14 +105,14 @@ inline passivedouble omp_get_wtime() {return passivedouble(clock()) / CLOCKS_PER struct omp_lock_t {}; struct DummyVectorOfLocks { omp_lock_t l; - inline omp_lock_t& operator[](int) {return l;} + inline omp_lock_t& operator[](int) { return l; } }; -inline void omp_init_lock(omp_lock_t*){} -inline void omp_set_lock(omp_lock_t*){} -inline void omp_unset_lock(omp_lock_t*){} -inline void omp_destroy_lock(omp_lock_t*){} +inline void omp_init_lock(omp_lock_t*) {} +inline void omp_set_lock(omp_lock_t*) {} +inline void omp_unset_lock(omp_lock_t*) {} +inline void omp_destroy_lock(omp_lock_t*) {} -#endif // end OpenMP detection +#endif // end OpenMP detection /*--- Initialization and finalization ---*/ @@ -172,8 +172,8 @@ void omp_finalize(); #define SU2_OMP_PARALLEL_ON(NTHREADS) OPDI_PARALLEL(num_threads(NTHREADS)) #define SU2_OMP_FOR_(ARGS) OPDI_FOR(ARGS) -#define SU2_OMP_FOR_DYN(CHUNK) OPDI_FOR(schedule(dynamic,CHUNK)) -#define SU2_OMP_FOR_STAT(CHUNK) OPDI_FOR(schedule(static,CHUNK)) +#define SU2_OMP_FOR_DYN(CHUNK) OPDI_FOR(schedule(dynamic, CHUNK)) +#define SU2_OMP_FOR_STAT(CHUNK) OPDI_FOR(schedule(static, CHUNK)) #define SU2_NOWAIT OPDI_NOWAIT @@ -189,35 +189,28 @@ void omp_finalize(); */ #define BEGIN_SU2_OMP_SAFE_GLOBAL_ACCESS \ - SU2_OMP_BARRIER \ + SU2_OMP_BARRIER \ SU2_OMP_MASTER #define END_SU2_OMP_SAFE_GLOBAL_ACCESS \ - END_SU2_OMP_MASTER \ + END_SU2_OMP_MASTER \ SU2_OMP_BARRIER -#define SU2_OMP_SAFE_GLOBAL_ACCESS(...) \ - BEGIN_SU2_OMP_SAFE_GLOBAL_ACCESS \ - { \ - __VA_ARGS__ \ - } \ - END_SU2_OMP_SAFE_GLOBAL_ACCESS +#define SU2_OMP_SAFE_GLOBAL_ACCESS(...) BEGIN_SU2_OMP_SAFE_GLOBAL_ACCESS{__VA_ARGS__} END_SU2_OMP_SAFE_GLOBAL_ACCESS /*--- Convenience functions (e.g. to compute chunk sizes). ---*/ /*! * \brief Integer division rounding up. */ -inline constexpr size_t roundUpDiv(size_t numerator, size_t denominator) -{ - return (numerator+denominator-1)/denominator; +inline constexpr size_t roundUpDiv(size_t numerator, size_t denominator) { + return (numerator + denominator - 1) / denominator; } /*! * \brief Round up to next multiple. */ -inline constexpr size_t nextMultiple(size_t argument, size_t multiple) -{ +inline constexpr size_t nextMultiple(size_t argument, size_t multiple) { return roundUpDiv(argument, multiple) * multiple; } @@ -229,11 +222,8 @@ inline constexpr size_t nextMultiple(size_t argument, size_t multiple) * \param[in] maxChunkSize - Upper bound for chunk size. * \return The chunkSize. */ -inline size_t computeStaticChunkSize(size_t totalWork, - size_t numThreads, - size_t maxChunkSize) -{ - if(!totalWork) return maxChunkSize; +inline size_t computeStaticChunkSize(size_t totalWork, size_t numThreads, size_t maxChunkSize) { + if (!totalWork) return maxChunkSize; size_t workPerThread = roundUpDiv(totalWork, numThreads); size_t chunksPerThread = roundUpDiv(workPerThread, maxChunkSize); return roundUpDiv(workPerThread, chunksPerThread); @@ -245,11 +235,10 @@ inline size_t computeStaticChunkSize(size_t totalWork, * \param[in] src - Source array. * \param[in] dst - Destination array. */ -template -void parallelCopy(size_t size, const T* src, U* dst) -{ +template +void parallelCopy(size_t size, const T* src, U* dst) { SU2_OMP_FOR_STAT(2048) - for(size_t i=0; i -void parallelSet(size_t size, T val, U* dst) -{ +template +void parallelSet(size_t size, T val, U* dst) { SU2_OMP_FOR_STAT(2048) - for(size_t i=0; i::value> = 0> -inline void atomicAdd(T rhs, T& lhs) -{ +template ::value> = 0> +inline void atomicAdd(T rhs, T& lhs) { SU2_OMP_CRITICAL lhs += rhs; END_SU2_OMP_CRITICAL } -template::value> = 0> -inline void atomicAdd(T rhs, T& lhs) -{ +template ::value> = 0> +inline void atomicAdd(T rhs, T& lhs) { SU2_OMP_ATOMIC lhs += rhs; } diff --git a/Common/include/parallelization/special_vectorization.hpp b/Common/include/parallelization/special_vectorization.hpp index 5ab1830dd9e..1c980fd7229 100644 --- a/Common/include/parallelization/special_vectorization.hpp +++ b/Common/include/parallelization/special_vectorization.hpp @@ -42,16 +42,19 @@ * overload resolution will do the rest. The first four symbols are * undefined once we are done using them. */ -template<> +template <> class ARRAY_T { -#define FOREACH SU2_OMP_SIMD for(size_t k=0; k - FORCEINLINE static S second(F, S s) { return s; } -public: +#define FOREACH SU2_OMP_SIMD for (size_t k = 0; k < Size; ++k) + template + FORCEINLINE static S second(F, S s) { + return s; + } + + public: using Scalar = SCALAR_T; using Register = REGISTER_T; - enum : size_t {Align = alignof(Register)}; - enum : size_t {Size = sizeof(Register) / sizeof(Scalar)}; + enum : size_t { Align = alignof(Register) }; + enum : size_t { Size = sizeof(Register) / sizeof(Scalar) }; /*--- The infamous union "hack", sue me. ---*/ union { @@ -76,14 +79,22 @@ class ARRAY_T { FORCEINLINE void store(Scalar* ptr) const { storeu_p(ptr, reg); } FORCEINLINE void storea(Scalar* ptr) const { store_p(ptr, reg); } FORCEINLINE void stream(Scalar* ptr) const { stream_p(ptr, reg); } - template - FORCEINLINE void gather(const Scalar* begin, const T& offsets) { FOREACH x_[k] = begin[offsets[k]]; } + template + FORCEINLINE void gather(const Scalar* begin, const T& offsets) { + FOREACH x_[k] = begin[offsets[k]]; + } /*--- Compound assignement operators. ---*/ -#define MAKE_COMPOUND(OP,IMPL)\ - FORCEINLINE Array& operator OP (Scalar x) { reg = IMPL(reg, set1_p(SIZE_TAG, x)); return *this; }\ - FORCEINLINE Array& operator OP (const Array& other) noexcept { reg = IMPL(reg, other.reg); return *this; } +#define MAKE_COMPOUND(OP, IMPL) \ + FORCEINLINE Array& operator OP(Scalar x) { \ + reg = IMPL(reg, set1_p(SIZE_TAG, x)); \ + return *this; \ + } \ + FORCEINLINE Array& operator OP(const Array& other) noexcept { \ + reg = IMPL(reg, other.reg); \ + return *this; \ + } MAKE_COMPOUND(=, second) MAKE_COMPOUND(+=, add_p) MAKE_COMPOUND(-=, sub_p) @@ -98,8 +109,8 @@ class ARRAY_T { * SIMD overloads, NAME is the operator or function, * IMPL the intrinsic function that implements it. */ -#define MAKE_UNARY_FUN(NAME,IMPL)\ -FORCEINLINE ARRAY_T NAME(const ARRAY_T& x) {return IMPL(x.reg);} +#define MAKE_UNARY_FUN(NAME, IMPL) \ + FORCEINLINE ARRAY_T NAME(const ARRAY_T& x) { return IMPL(x.reg); } MAKE_UNARY_FUN(operator-, neg_p) MAKE_UNARY_FUN(sqrt, sqrt_p) @@ -108,16 +119,10 @@ MAKE_UNARY_FUN(sign, sign_p) #undef MAKE_UNARY_FUN -#define MAKE_BINARY_FUN(NAME,IMPL) \ -FORCEINLINE ARRAY_T NAME (const ARRAY_T& a, const ARRAY_T& b) { \ - return IMPL(a.reg, b.reg); \ -} \ -FORCEINLINE ARRAY_T NAME (const ARRAY_T& a, SCALAR_T b) { \ - return IMPL(a.reg, set1_p(SIZE_TAG, b)); \ -} \ -FORCEINLINE ARRAY_T NAME (SCALAR_T b, const ARRAY_T& a) { \ - return IMPL(set1_p(SIZE_TAG, b), a.reg); \ -} +#define MAKE_BINARY_FUN(NAME, IMPL) \ + FORCEINLINE ARRAY_T NAME(const ARRAY_T& a, const ARRAY_T& b) { return IMPL(a.reg, b.reg); } \ + FORCEINLINE ARRAY_T NAME(const ARRAY_T& a, SCALAR_T b) { return IMPL(a.reg, set1_p(SIZE_TAG, b)); } \ + FORCEINLINE ARRAY_T NAME(SCALAR_T b, const ARRAY_T& a) { return IMPL(set1_p(SIZE_TAG, b), a.reg); } MAKE_BINARY_FUN(operator+, add_p) MAKE_BINARY_FUN(operator-, sub_p) @@ -137,29 +142,37 @@ MAKE_BINARY_FUN(fmin, min_p) /*! * Compatibility mode overloads, element-wise implementation. */ -#define FOREACH SU2_OMP_SIMD for(size_t k=0; k -constexpr size_t preferredLen() { return PREFERRED_SIZE / sizeof(T); } +template +constexpr size_t preferredLen() { + return PREFERRED_SIZE / sizeof(T); +} -template<> +template <> constexpr size_t preferredLen() { #ifdef CODI_REVERSE_TYPE /*--- Use a SIMD size of 1 for reverse AD, larger sizes increase @@ -80,54 +82,72 @@ constexpr size_t preferredLen() { * specializations do not use expression templates, IF YOU NEED A NEW FUNCTION, * define it both in vector_expressions.hpp and in special_vectorization.hpp. */ -template()> -class Array : public CVecExpr, Scalar_t> { -#define FOREACH for(size_t k=0; k()> +class Array : public CVecExpr, Scalar_t> { +#define FOREACH for (size_t k = 0; k < N; ++k) static_assert(N > 0, "Invalid SIMD size"); -public: + + public: using Scalar = Scalar_t; - enum : size_t {Size = N}; - enum : size_t {Align = Size*sizeof(Scalar)}; + enum : size_t { Size = N }; + enum : size_t { Align = Size * sizeof(Scalar) }; static constexpr bool StoreAsRef = true; -private: - alignas(Size*sizeof(Scalar)) Scalar x_[N]; - -public: -#define ARRAY_BOILERPLATE \ - /*!--- Access elements ---*/ \ - FORCEINLINE Scalar& operator[] (size_t k) { return x_[k]; } \ - FORCEINLINE const Scalar& operator[] (size_t k) const { return x_[k]; } \ - /*!--- Constructors ---*/ \ - FORCEINLINE Array() = default; \ - FORCEINLINE Array(Scalar x) { bcast(x); } \ - FORCEINLINE Array(std::initializer_list vals) { \ - auto it = vals.begin(); FOREACH { x_[k] = *it; ++it; } \ - } \ - FORCEINLINE Array(Scalar x0, Scalar dx) { FOREACH x_[k] = x0 + k*dx; } \ - FORCEINLINE Array(const Scalar* ptr) { load(ptr); } \ - template \ - FORCEINLINE Array(const Scalar* beg, const T& off) { gather(beg,off); } \ - /*!--- Reduction operations ---*/ \ - FORCEINLINE Scalar sum() const { Scalar s(0); FOREACH { s+=x_[k]; } return s; } \ - FORCEINLINE Scalar dot(const Array& other) const { \ - Scalar s(0); FOREACH { s += x_[k] * other[k]; } return s; \ + private: + alignas(Size * sizeof(Scalar)) Scalar x_[N]; + + public: +#define ARRAY_BOILERPLATE \ + /*!--- Access elements ---*/ \ + FORCEINLINE Scalar& operator[](size_t k) { return x_[k]; } \ + FORCEINLINE const Scalar& operator[](size_t k) const { return x_[k]; } \ + /*!--- Constructors ---*/ \ + FORCEINLINE Array() = default; \ + FORCEINLINE Array(Scalar x) { bcast(x); } \ + FORCEINLINE Array(std::initializer_list vals) { \ + auto it = vals.begin(); \ + FOREACH { \ + x_[k] = *it; \ + ++it; \ + } \ + } \ + FORCEINLINE Array(Scalar x0, Scalar dx) { FOREACH x_[k] = x0 + k * dx; } \ + FORCEINLINE Array(const Scalar* ptr) { load(ptr); } \ + template \ + FORCEINLINE Array(const Scalar* beg, const T& off) { \ + gather(beg, off); \ + } \ + /*!--- Reduction operations ---*/ \ + FORCEINLINE Scalar sum() const { \ + Scalar s(0); \ + FOREACH { s += x_[k]; } \ + return s; \ + } \ + FORCEINLINE Scalar dot(const Array& other) const { \ + Scalar s(0); \ + FOREACH { s += x_[k] * other[k]; } \ + return s; \ } #if defined(CODI_REVERSE_TYPE) || defined(CODI_FORWARD_TYPE) /*--- These are not very nice but without them it would not be * possible to assign literals to Arrays of active types. ---*/ - template::value> = 0> - FORCEINLINE Array(passivedouble x) { bcast(x); } - template::value> = 0> - FORCEINLINE Array& operator= (passivedouble x) { bcast(x); return *this; } + template ::value> = 0> + FORCEINLINE Array(passivedouble x) { + bcast(x); + } + template ::value> = 0> + FORCEINLINE Array& operator=(passivedouble x) { + bcast(x); + return *this; + } #endif ARRAY_BOILERPLATE /*! \brief Copy construct from expression. */ - template - FORCEINLINE Array(const CVecExpr& expr) { + template + FORCEINLINE Array(const CVecExpr& expr) { FOREACH x_[k] = expr.derived()[k]; } @@ -139,16 +159,22 @@ class Array : public CVecExpr, Scalar_t> { FORCEINLINE void store(Scalar* ptr) const { FOREACH ptr[k] = x_[k]; } FORCEINLINE void storea(Scalar* ptr) const { store(ptr); } FORCEINLINE void stream(Scalar* ptr) const { store(ptr); } - template - FORCEINLINE void gather(const Scalar* begin, const T& offsets) { FOREACH x_[k] = begin[offsets[k]]; } + template + FORCEINLINE void gather(const Scalar* begin, const T& offsets) { + FOREACH x_[k] = begin[offsets[k]]; + } /*--- Compound assignment operators. ---*/ -#define MAKE_COMPOUND(OP) \ - FORCEINLINE Array& operator OP (Scalar x) { FOREACH { x_[k] OP x; } return *this; } \ - template \ - FORCEINLINE Array& operator OP (const CVecExpr& expr) { \ - FOREACH { x_[k] OP expr.derived()[k]; } return *this; \ +#define MAKE_COMPOUND(OP) \ + FORCEINLINE Array& operator OP(Scalar x) { \ + FOREACH { x_[k] OP x; } \ + return *this; \ + } \ + template \ + FORCEINLINE Array& operator OP(const CVecExpr& expr) { \ + FOREACH { x_[k] OP expr.derived()[k]; } \ + return *this; \ } MAKE_COMPOUND(=) MAKE_COMPOUND(+=) @@ -166,11 +192,11 @@ class Array : public CVecExpr, Scalar_t> { /*--- Size tags for overload resolution of some wrapper functions. ---*/ namespace SizeTag { - struct TWO {}; - struct FOUR {}; - struct EIGHT {}; - struct SIXTEEN {}; -} +struct TWO {}; +struct FOUR {}; +struct EIGHT {}; +struct SIXTEEN {}; +} // namespace SizeTag /*--- Constants for bitwise implementations. ---*/ /*--- abs forces the sign bit to 0 ("x" & 0b0111...). ---*/ @@ -182,7 +208,7 @@ constexpr auto sign_mask_d = 0x8000000000000000L; /*! * Create specialization for array of 2 doubles (this should be always available). */ -#define ARRAY_T Array +#define ARRAY_T Array #define SCALAR_T double #define REGISTER_T __m128d #define SIZE_TAG SizeTag::TWO() @@ -194,23 +220,23 @@ static const __m128d ones_2d = _mm_set1_pd(1); FORCEINLINE __m128d set1_p(SizeTag::TWO, double p) { return _mm_set1_pd(p); } FORCEINLINE __m128d load_p(SizeTag::TWO, const double* p) { return _mm_load_pd(p); } FORCEINLINE __m128d loadu_p(SizeTag::TWO, const double* p) { return _mm_loadu_pd(p); } -FORCEINLINE void store_p(double* p, __m128d x) { _mm_store_pd(p,x); } -FORCEINLINE void storeu_p(double* p, __m128d x) { _mm_storeu_pd(p,x); } -FORCEINLINE void stream_p(double* p, __m128d x) { _mm_stream_pd(p,x); } - -FORCEINLINE __m128d add_p(__m128d a, __m128d b) { return _mm_add_pd(a,b); } -FORCEINLINE __m128d sub_p(__m128d a, __m128d b) { return _mm_sub_pd(a,b); } -FORCEINLINE __m128d mul_p(__m128d a, __m128d b) { return _mm_mul_pd(a,b); } -FORCEINLINE __m128d div_p(__m128d a, __m128d b) { return _mm_div_pd(a,b); } -FORCEINLINE __m128d max_p(__m128d a, __m128d b) { return _mm_max_pd(a,b); } -FORCEINLINE __m128d min_p(__m128d a, __m128d b) { return _mm_min_pd(a,b); } - -FORCEINLINE __m128d eq_p(__m128d a, __m128d b) { return _mm_and_pd(ones_2d, _mm_cmpeq_pd(a,b)); } -FORCEINLINE __m128d lt_p(__m128d a, __m128d b) { return _mm_and_pd(ones_2d, _mm_cmplt_pd(a,b)); } -FORCEINLINE __m128d le_p(__m128d a, __m128d b) { return _mm_and_pd(ones_2d, _mm_cmple_pd(a,b)); } -FORCEINLINE __m128d ne_p(__m128d a, __m128d b) { return _mm_and_pd(ones_2d, _mm_cmpneq_pd(a,b)); } -FORCEINLINE __m128d ge_p(__m128d a, __m128d b) { return _mm_and_pd(ones_2d, _mm_cmpge_pd(a,b)); } -FORCEINLINE __m128d gt_p(__m128d a, __m128d b) { return _mm_and_pd(ones_2d, _mm_cmpgt_pd(a,b)); } +FORCEINLINE void store_p(double* p, __m128d x) { _mm_store_pd(p, x); } +FORCEINLINE void storeu_p(double* p, __m128d x) { _mm_storeu_pd(p, x); } +FORCEINLINE void stream_p(double* p, __m128d x) { _mm_stream_pd(p, x); } + +FORCEINLINE __m128d add_p(__m128d a, __m128d b) { return _mm_add_pd(a, b); } +FORCEINLINE __m128d sub_p(__m128d a, __m128d b) { return _mm_sub_pd(a, b); } +FORCEINLINE __m128d mul_p(__m128d a, __m128d b) { return _mm_mul_pd(a, b); } +FORCEINLINE __m128d div_p(__m128d a, __m128d b) { return _mm_div_pd(a, b); } +FORCEINLINE __m128d max_p(__m128d a, __m128d b) { return _mm_max_pd(a, b); } +FORCEINLINE __m128d min_p(__m128d a, __m128d b) { return _mm_min_pd(a, b); } + +FORCEINLINE __m128d eq_p(__m128d a, __m128d b) { return _mm_and_pd(ones_2d, _mm_cmpeq_pd(a, b)); } +FORCEINLINE __m128d lt_p(__m128d a, __m128d b) { return _mm_and_pd(ones_2d, _mm_cmplt_pd(a, b)); } +FORCEINLINE __m128d le_p(__m128d a, __m128d b) { return _mm_and_pd(ones_2d, _mm_cmple_pd(a, b)); } +FORCEINLINE __m128d ne_p(__m128d a, __m128d b) { return _mm_and_pd(ones_2d, _mm_cmpneq_pd(a, b)); } +FORCEINLINE __m128d ge_p(__m128d a, __m128d b) { return _mm_and_pd(ones_2d, _mm_cmpge_pd(a, b)); } +FORCEINLINE __m128d gt_p(__m128d a, __m128d b) { return _mm_and_pd(ones_2d, _mm_cmpgt_pd(a, b)); } FORCEINLINE __m128d sqrt_p(__m128d x) { return _mm_sqrt_pd(x); } FORCEINLINE __m128d abs_p(__m128d x) { return _mm_and_pd(x, abs_mask_2d); } @@ -222,13 +248,13 @@ FORCEINLINE __m128d sign_p(__m128d x) { return _mm_or_pd(ones_2d, _mm_and_pd(x, #include "special_vectorization.hpp" -#endif // __SSE2__ +#endif // __SSE2__ #ifdef __AVX__ /*! * Create specialization for array of 4 doubles. */ -#define ARRAY_T Array +#define ARRAY_T Array #define SCALAR_T double #define REGISTER_T __m256d #define SIZE_TAG SizeTag::FOUR() @@ -240,23 +266,23 @@ static const __m256d ones_4d = _mm256_set1_pd(1); FORCEINLINE __m256d set1_p(SizeTag::FOUR, double p) { return _mm256_set1_pd(p); } FORCEINLINE __m256d load_p(SizeTag::FOUR, const double* p) { return _mm256_load_pd(p); } FORCEINLINE __m256d loadu_p(SizeTag::FOUR, const double* p) { return _mm256_loadu_pd(p); } -FORCEINLINE void store_p(double* p, __m256d x) { _mm256_store_pd(p,x); } -FORCEINLINE void storeu_p(double* p, __m256d x) { _mm256_storeu_pd(p,x); } -FORCEINLINE void stream_p(double* p, __m256d x) { _mm256_stream_pd(p,x); } - -FORCEINLINE __m256d add_p(__m256d a, __m256d b) { return _mm256_add_pd(a,b); } -FORCEINLINE __m256d sub_p(__m256d a, __m256d b) { return _mm256_sub_pd(a,b); } -FORCEINLINE __m256d mul_p(__m256d a, __m256d b) { return _mm256_mul_pd(a,b); } -FORCEINLINE __m256d div_p(__m256d a, __m256d b) { return _mm256_div_pd(a,b); } -FORCEINLINE __m256d max_p(__m256d a, __m256d b) { return _mm256_max_pd(a,b); } -FORCEINLINE __m256d min_p(__m256d a, __m256d b) { return _mm256_min_pd(a,b); } - -FORCEINLINE __m256d eq_p(__m256d a, __m256d b) { return _mm256_and_pd(ones_4d, _mm256_cmp_pd(a,b,0)); } -FORCEINLINE __m256d lt_p(__m256d a, __m256d b) { return _mm256_and_pd(ones_4d, _mm256_cmp_pd(a,b,1)); } -FORCEINLINE __m256d le_p(__m256d a, __m256d b) { return _mm256_and_pd(ones_4d, _mm256_cmp_pd(a,b,2)); } -FORCEINLINE __m256d ne_p(__m256d a, __m256d b) { return _mm256_and_pd(ones_4d, _mm256_cmp_pd(a,b,4)); } -FORCEINLINE __m256d ge_p(__m256d a, __m256d b) { return _mm256_and_pd(ones_4d, _mm256_cmp_pd(a,b,13)); } -FORCEINLINE __m256d gt_p(__m256d a, __m256d b) { return _mm256_and_pd(ones_4d, _mm256_cmp_pd(a,b,14)); } +FORCEINLINE void store_p(double* p, __m256d x) { _mm256_store_pd(p, x); } +FORCEINLINE void storeu_p(double* p, __m256d x) { _mm256_storeu_pd(p, x); } +FORCEINLINE void stream_p(double* p, __m256d x) { _mm256_stream_pd(p, x); } + +FORCEINLINE __m256d add_p(__m256d a, __m256d b) { return _mm256_add_pd(a, b); } +FORCEINLINE __m256d sub_p(__m256d a, __m256d b) { return _mm256_sub_pd(a, b); } +FORCEINLINE __m256d mul_p(__m256d a, __m256d b) { return _mm256_mul_pd(a, b); } +FORCEINLINE __m256d div_p(__m256d a, __m256d b) { return _mm256_div_pd(a, b); } +FORCEINLINE __m256d max_p(__m256d a, __m256d b) { return _mm256_max_pd(a, b); } +FORCEINLINE __m256d min_p(__m256d a, __m256d b) { return _mm256_min_pd(a, b); } + +FORCEINLINE __m256d eq_p(__m256d a, __m256d b) { return _mm256_and_pd(ones_4d, _mm256_cmp_pd(a, b, 0)); } +FORCEINLINE __m256d lt_p(__m256d a, __m256d b) { return _mm256_and_pd(ones_4d, _mm256_cmp_pd(a, b, 1)); } +FORCEINLINE __m256d le_p(__m256d a, __m256d b) { return _mm256_and_pd(ones_4d, _mm256_cmp_pd(a, b, 2)); } +FORCEINLINE __m256d ne_p(__m256d a, __m256d b) { return _mm256_and_pd(ones_4d, _mm256_cmp_pd(a, b, 4)); } +FORCEINLINE __m256d ge_p(__m256d a, __m256d b) { return _mm256_and_pd(ones_4d, _mm256_cmp_pd(a, b, 13)); } +FORCEINLINE __m256d gt_p(__m256d a, __m256d b) { return _mm256_and_pd(ones_4d, _mm256_cmp_pd(a, b, 14)); } FORCEINLINE __m256d sqrt_p(__m256d x) { return _mm256_sqrt_pd(x); } FORCEINLINE __m256d abs_p(__m256d x) { return _mm256_and_pd(x, abs_mask_4d); } @@ -265,13 +291,13 @@ FORCEINLINE __m256d sign_p(__m256d x) { return _mm256_or_pd(ones_4d, _mm256_and_ #include "special_vectorization.hpp" -#endif // __AVX__ +#endif // __AVX__ #ifdef __AVX512F__ /*! * Create specialization for array of 8 doubles. */ -#define ARRAY_T Array +#define ARRAY_T Array #define SCALAR_T double #define REGISTER_T __m512d #define SIZE_TAG SizeTag::EIGHT() @@ -283,27 +309,27 @@ static const __m512d ones_8d = _mm512_set1_pd(1); FORCEINLINE __m512d set1_p(SizeTag::EIGHT, double p) { return _mm512_set1_pd(p); } FORCEINLINE __m512d load_p(SizeTag::EIGHT, const double* p) { return _mm512_load_pd(p); } FORCEINLINE __m512d loadu_p(SizeTag::EIGHT, const double* p) { return _mm512_loadu_pd(p); } -FORCEINLINE void store_p(double* p, __m512d x) { _mm512_store_pd(p,x); } -FORCEINLINE void storeu_p(double* p, __m512d x) { _mm512_storeu_pd(p,x); } -FORCEINLINE void stream_p(double* p, __m512d x) { _mm512_stream_pd(p,x); } - -FORCEINLINE __m512d add_p(__m512d a, __m512d b) { return _mm512_add_pd(a,b); } -FORCEINLINE __m512d sub_p(__m512d a, __m512d b) { return _mm512_sub_pd(a,b); } -FORCEINLINE __m512d mul_p(__m512d a, __m512d b) { return _mm512_mul_pd(a,b); } -FORCEINLINE __m512d div_p(__m512d a, __m512d b) { return _mm512_div_pd(a,b); } -FORCEINLINE __m512d max_p(__m512d a, __m512d b) { return _mm512_max_pd(a,b); } -FORCEINLINE __m512d min_p(__m512d a, __m512d b) { return _mm512_min_pd(a,b); } - -template +FORCEINLINE void store_p(double* p, __m512d x) { _mm512_store_pd(p, x); } +FORCEINLINE void storeu_p(double* p, __m512d x) { _mm512_storeu_pd(p, x); } +FORCEINLINE void stream_p(double* p, __m512d x) { _mm512_stream_pd(p, x); } + +FORCEINLINE __m512d add_p(__m512d a, __m512d b) { return _mm512_add_pd(a, b); } +FORCEINLINE __m512d sub_p(__m512d a, __m512d b) { return _mm512_sub_pd(a, b); } +FORCEINLINE __m512d mul_p(__m512d a, __m512d b) { return _mm512_mul_pd(a, b); } +FORCEINLINE __m512d div_p(__m512d a, __m512d b) { return _mm512_div_pd(a, b); } +FORCEINLINE __m512d max_p(__m512d a, __m512d b) { return _mm512_max_pd(a, b); } +FORCEINLINE __m512d min_p(__m512d a, __m512d b) { return _mm512_min_pd(a, b); } + +template FORCEINLINE __m512d cmp_p(__m512d a, __m512d b) { - return _mm512_mask_blend_pd(_mm512_cmp_pd_mask(a,b,opCode), _mm512_setzero_pd(), ones_8d); + return _mm512_mask_blend_pd(_mm512_cmp_pd_mask(a, b, opCode), _mm512_setzero_pd(), ones_8d); } -FORCEINLINE __m512d eq_p(__m512d a, __m512d b) { return cmp_p<0>(a,b); } -FORCEINLINE __m512d lt_p(__m512d a, __m512d b) { return cmp_p<1>(a,b); } -FORCEINLINE __m512d le_p(__m512d a, __m512d b) { return cmp_p<2>(a,b); } -FORCEINLINE __m512d ne_p(__m512d a, __m512d b) { return cmp_p<4>(a,b); } -FORCEINLINE __m512d ge_p(__m512d a, __m512d b) { return cmp_p<13>(a,b); } -FORCEINLINE __m512d gt_p(__m512d a, __m512d b) { return cmp_p<14>(a,b); } +FORCEINLINE __m512d eq_p(__m512d a, __m512d b) { return cmp_p<0>(a, b); } +FORCEINLINE __m512d lt_p(__m512d a, __m512d b) { return cmp_p<1>(a, b); } +FORCEINLINE __m512d le_p(__m512d a, __m512d b) { return cmp_p<2>(a, b); } +FORCEINLINE __m512d ne_p(__m512d a, __m512d b) { return cmp_p<4>(a, b); } +FORCEINLINE __m512d ge_p(__m512d a, __m512d b) { return cmp_p<13>(a, b); } +FORCEINLINE __m512d gt_p(__m512d a, __m512d b) { return cmp_p<14>(a, b); } FORCEINLINE __m512d sqrt_p(__m512d x) { return _mm512_sqrt_pd(x); } FORCEINLINE __m512d abs_p(__m512d x) { return _mm512_and_pd(x, abs_mask_8d); } @@ -312,9 +338,9 @@ FORCEINLINE __m512d sign_p(__m512d x) { return _mm512_or_pd(ones_8d, _mm512_and_ #include "special_vectorization.hpp" -#endif // __AVX512F__ +#endif // __AVX512F__ #undef ARRAY_BOILERPLATE /// @} -} // namespace +} // namespace simd diff --git a/Common/include/toolboxes/C1DInterpolation.hpp b/Common/include/toolboxes/C1DInterpolation.hpp index 2b627f68cb2..aa00b3f2999 100644 --- a/Common/include/toolboxes/C1DInterpolation.hpp +++ b/Common/include/toolboxes/C1DInterpolation.hpp @@ -37,8 +37,8 @@ * \ingroup LookUpInterp */ class C1DInterpolation { -protected: - std::vector x, y; /*!< \brief Data points. */ + protected: + std::vector x, y; /*!< \brief Data points. */ /*! * \brief Find containing interval. @@ -46,20 +46,19 @@ class C1DInterpolation { * \return The start index of the interval, or the size if the coordinate is out of bounds. */ inline size_t lower_bound(su2double xi) const { - if (xi <= x.front() || xi >= x.back()) return x.size(); - size_t lb = 0, ub = x.size()-1; + size_t lb = 0, ub = x.size() - 1; - while (ub-lb > 1) { - size_t mid = (lb+ub)/2; - auto& change = (xi < x[mid])? ub : lb; + while (ub - lb > 1) { + size_t mid = (lb + ub) / 2; + auto& change = (xi < x[mid]) ? ub : lb; change = mid; } return lb; } -public: + public: /*! * \brief Virtual destructor of the C1DInterpolation class. */ @@ -70,7 +69,7 @@ class C1DInterpolation { * \param[in] X - the x values. * \param[in] Data - the f(x) values. */ - virtual void SetSpline(const std::vector &X, const std::vector &Data) { + virtual void SetSpline(const std::vector& X, const std::vector& Data) { assert(X.size() == Data.size()); x = X; y = Data; @@ -80,19 +79,18 @@ class C1DInterpolation { * \brief Evaluate the value of the spline at a point. */ virtual su2double EvaluateSpline(su2double Point_Interp) const = 0; - inline su2double operator() (su2double Point_Interp) const { return EvaluateSpline(Point_Interp); } - + inline su2double operator()(su2double Point_Interp) const { return EvaluateSpline(Point_Interp); } }; /*! * \brief Akima 1D interpolation. * \ingroup LookUpInterp */ -class CAkimaInterpolation: public C1DInterpolation{ -protected: - std::vector b,c,d; /*!< \brief local variables for Akima spline cooefficients */ +class CAkimaInterpolation : public C1DInterpolation { + protected: + std::vector b, c, d; /*!< \brief local variables for Akima spline cooefficients */ -public: + public: CAkimaInterpolation() = default; /*! @@ -100,14 +98,14 @@ class CAkimaInterpolation: public C1DInterpolation{ * \param[in] X - the x values (sorted low to high). * \param[in] Data - the f(x) values. */ - CAkimaInterpolation(const std::vector &X, const std::vector &Data) { - CAkimaInterpolation::SetSpline(X,Data); + CAkimaInterpolation(const std::vector& X, const std::vector& Data) { + CAkimaInterpolation::SetSpline(X, Data); } /*! * \brief Build the spline. */ - void SetSpline(const std::vector &X, const std::vector &Data) override; + void SetSpline(const std::vector& X, const std::vector& Data) override; /*! * \brief Evaluate the value of the spline at a point. @@ -119,15 +117,15 @@ class CAkimaInterpolation: public C1DInterpolation{ * \brief Cubic spline interpolation. * \ingroup LookUpInterp */ -class CCubicSpline final: public CAkimaInterpolation { -public: - enum END_TYPE {SECOND, FIRST}; +class CCubicSpline final : public CAkimaInterpolation { + public: + enum END_TYPE { SECOND, FIRST }; -private: + private: const su2double startVal, endVal; /*!< \brief "boundary" values. */ const END_TYPE startDer, endDer; /*!< \brief 1st or 2nd derivative "boundary" conditions. */ -public: + public: CCubicSpline() = default; /*! @@ -139,28 +137,24 @@ class CCubicSpline final: public CAkimaInterpolation { * \param[in] endCondition - 1st or 2nd derivative imposed at the end. * \param[in] endValue - value of the derivative imposed at the end. */ - CCubicSpline(const std::vector &X, const std::vector &Data, - END_TYPE startCondition = SECOND, su2double startValue = 0.0, - END_TYPE endCondition = SECOND, su2double endValue = 0.0) : - startVal(startValue), - endVal(endValue), - startDer(startCondition), - endDer(endCondition) { - SetSpline(X,Data); + CCubicSpline(const std::vector& X, const std::vector& Data, END_TYPE startCondition = SECOND, + su2double startValue = 0.0, END_TYPE endCondition = SECOND, su2double endValue = 0.0) + : startVal(startValue), endVal(endValue), startDer(startCondition), endDer(endCondition) { + SetSpline(X, Data); } /*! * \brief Build the spline. */ - void SetSpline(const std::vector &X, const std::vector &Data) override; + void SetSpline(const std::vector& X, const std::vector& Data) override; }; /*! * \brief Linear interpolation. * \ingroup LookUpInterp */ -class CLinearInterpolation final: public C1DInterpolation { -public: +class CLinearInterpolation final : public C1DInterpolation { + public: CLinearInterpolation() = default; /*! @@ -168,9 +162,7 @@ class CLinearInterpolation final: public C1DInterpolation { * \param[in] X - the x values (sorted low to high). * \param[in] Data - the f(x) values. */ - CLinearInterpolation(const std::vector &X, const std::vector &Data) { - SetSpline(X,Data); - } + CLinearInterpolation(const std::vector& X, const std::vector& Data) { SetSpline(X, Data); } /*! * \brief Evaluate the value of the spline at a point. @@ -188,12 +180,9 @@ class CLinearInterpolation final: public C1DInterpolation { * \param[in] ENUM_INLET_INTERPOLATIONTYPE - enum of the interpolation type to be done * \returns the corrected Inlet Interpolated Data. */ -std::vector CorrectedInletValues(const std::vector &Inlet_Interpolated, - su2double Theta , - unsigned short nDim, - const su2double *Coord, - unsigned short nVar_Turb, - INLET_INTERP_TYPE Interpolation_Type); +std::vector CorrectedInletValues(const std::vector& Inlet_Interpolated, su2double Theta, + unsigned short nDim, const su2double* Coord, unsigned short nVar_Turb, + INLET_INTERP_TYPE Interpolation_Type); /*! * \brief Prints the Inlet Interpolated Data diff --git a/Common/include/toolboxes/CLinearPartitioner.hpp b/Common/include/toolboxes/CLinearPartitioner.hpp index ec9ee4e6470..befb327c15a 100644 --- a/Common/include/toolboxes/CLinearPartitioner.hpp +++ b/Common/include/toolboxes/CLinearPartitioner.hpp @@ -41,25 +41,25 @@ using namespace std; * \author T. Economon */ class CLinearPartitioner { - -protected: - - int size; /*!< \brief MPI Size. */ - - vector firstIndex; /*!< \brief Vector containing the first index on each rank due to a linear partitioning by global count. */ - vector lastIndex; /*!< \brief Vector containing the last index on each rank due to a linear partitioning by global count. */ - vector sizeOnRank; /*!< \brief Vector containing the total size of the current rank's linear partition. */ - vector cumulativeSizeBeforeRank; /*!< \brief Vector containing the cumulative size of all linear partitions before the current rank. */ - -public: + protected: + int size; /*!< \brief MPI Size. */ + + vector firstIndex; /*!< \brief Vector containing the first index on each rank due to a linear + partitioning by global count. */ + vector lastIndex; /*!< \brief Vector containing the last index on each rank due to a linear + partitioning by global count. */ + vector + sizeOnRank; /*!< \brief Vector containing the total size of the current rank's linear partition. */ + vector cumulativeSizeBeforeRank; /*!< \brief Vector containing the cumulative size of all linear + partitions before the current rank. */ + + public: CLinearPartitioner() = default; /*! * \brief Constructor of the CLinearPartitioner class, see Initialize. */ - CLinearPartitioner(unsigned long global_count, - unsigned long offset, - bool isDisjoint = false) { + CLinearPartitioner(unsigned long global_count, unsigned long offset, bool isDisjoint = false) { Initialize(global_count, offset, isDisjoint); } @@ -69,9 +69,7 @@ class CLinearPartitioner { * \param[in] offset - offset from 0 for the first index on rank 0 (typically 0). * \param[in] isDisjoint - boolean controlling whether the linear partitions should be disjoint (default is false). */ - void Initialize(unsigned long global_count, - unsigned long offset, - bool isDisjoint = false); + void Initialize(unsigned long global_count, unsigned long offset, bool isDisjoint = false); /*! * \brief Get the rank that owns the index based on the linear partitioning. @@ -85,36 +83,28 @@ class CLinearPartitioner { * \param[in] rank - MPI rank identifier. * \returns First index of the current rank's linear partition. */ - inline unsigned long GetFirstIndexOnRank(int rank) const { - return firstIndex[rank]; - } + inline unsigned long GetFirstIndexOnRank(int rank) const { return firstIndex[rank]; } /*! * \brief Get the last index of the current rank's linear partition. * \param[in] rank - MPI rank identifier. * \returns Last index of the current rank's linear partition. */ - inline unsigned long GetLastIndexOnRank(int rank) const { - return lastIndex[rank]; - } + inline unsigned long GetLastIndexOnRank(int rank) const { return lastIndex[rank]; } /*! * \brief Get the total size of the current rank's linear partition. * \param[in] rank - MPI rank identifier. * \returns Size of the current rank's linear partition. */ - inline unsigned long GetSizeOnRank(int rank) const { - return sizeOnRank[rank]; - } + inline unsigned long GetSizeOnRank(int rank) const { return sizeOnRank[rank]; } /*! * \brief Get the cumulative size of all linear partitions before the current rank. * \param[in] rank - MPI rank identifier. * \returns Cumulative size of all linear partitions before the current rank. */ - inline unsigned long GetCumulativeSizeBeforeRank(int rank) const { - return cumulativeSizeBeforeRank[rank]; - } + inline unsigned long GetCumulativeSizeBeforeRank(int rank) const { return cumulativeSizeBeforeRank[rank]; } /*! * \brief Checks if an index belongs to a rank. @@ -123,7 +113,6 @@ class CLinearPartitioner { * \returns True if index is owned by rank. */ bool IndexBelongsToRank(unsigned long index, int rank) const { - return index >= cumulativeSizeBeforeRank[rank] && index < cumulativeSizeBeforeRank[rank+1]; + return index >= cumulativeSizeBeforeRank[rank] && index < cumulativeSizeBeforeRank[rank + 1]; } - }; diff --git a/Common/include/toolboxes/CQuasiNewtonInvLeastSquares.hpp b/Common/include/toolboxes/CQuasiNewtonInvLeastSquares.hpp index e481d77935b..e82b41298b9 100644 --- a/Common/include/toolboxes/CQuasiNewtonInvLeastSquares.hpp +++ b/Common/include/toolboxes/CQuasiNewtonInvLeastSquares.hpp @@ -46,17 +46,17 @@ * as the new input of the FP, run the FP, etc. * \ingroup BLAS */ -template +template class CQuasiNewtonInvLeastSquares { -public: + public: using Scalar = Scalar_t; using Index = typename su2matrix::Index; - static_assert(std::is_floating_point::value,""); + static_assert(std::is_floating_point::value, ""); -private: + private: using MPI_Wrapper = typename SelectMPIWrapper::W; - enum: size_t {BLOCK_SIZE = 1024}; /*!< \brief Loop tiling parameter. */ + enum : size_t { BLOCK_SIZE = 1024 }; /*!< \brief Loop tiling parameter. */ std::vector > X, R; /*!< \brief Input and residual history of the FP. */ su2matrix work; /*!< \brief Work matrix (FP result, correction, and approx solution). */ su2vector mat, rhs, sol; /*!< \brief Matrix, rhs, and solution of the normal equations. */ @@ -67,67 +67,63 @@ class CQuasiNewtonInvLeastSquares { for (Index i = 1; i < X.size(); ++i) { /*--- Swap instead of moving to re-use the memory of the first sample. * This is why X and R are not stored as contiguous blocks of mem. ---*/ - std::swap(X[i-1], X[i]); - std::swap(R[i-1], R[i]); + std::swap(X[i - 1], X[i]); + std::swap(R[i - 1], R[i]); } } void computeNormalEquations() { /*--- Size for the dot products. ---*/ - const auto end = std::min(nPtDomain,work.rows())*work.cols(); + const auto end = std::min(nPtDomain, work.rows()) * work.cols(); - mat = Scalar(0); rhs = Scalar(0); + mat = Scalar(0); + rhs = Scalar(0); /*--- Tiled part of the loop. ---*/ Index begin = 0; - while (end-begin >= BLOCK_SIZE) { + while (end - begin >= BLOCK_SIZE) { computeNormalEquations(mat, rhs, begin); begin += BLOCK_SIZE; } /*--- Remainder of the loop. ---*/ if (begin != end) { - computeNormalEquations<0>(mat, rhs, begin, end-begin); + computeNormalEquations<0>(mat, rhs, begin, end - begin); } /*--- MPI reduction of the dot products. ---*/ if (WithMPI) { - const auto type = (sizeof(Scalar) < sizeof(double))? MPI_FLOAT : MPI_DOUBLE; + const auto type = (sizeof(Scalar) < sizeof(double)) ? MPI_FLOAT : MPI_DOUBLE; su2vector tmp(mat.size()); - MPI_Wrapper::Allreduce(mat.data(), tmp.data(), iSample*(iSample+1)/2, - type, MPI_SUM, SU2_MPI::GetComm()); + MPI_Wrapper::Allreduce(mat.data(), tmp.data(), iSample * (iSample + 1) / 2, type, MPI_SUM, SU2_MPI::GetComm()); mat = std::move(tmp); - MPI_Wrapper::Allreduce(rhs.data(), sol.data(), iSample, - type, MPI_SUM, SU2_MPI::GetComm()); + MPI_Wrapper::Allreduce(rhs.data(), sol.data(), iSample, type, MPI_SUM, SU2_MPI::GetComm()); std::swap(rhs, sol); } } - template - void computeNormalEquations(su2vector& mat, - su2vector& vec, - Index start, - Index dynSize = 0) const { + template + void computeNormalEquations(su2vector& mat, su2vector& vec, Index start, Index dynSize = 0) const { /*--- Select either the static or dynamic size, optimizes inner loop. ---*/ - const auto blkSize = StaticSize? StaticSize : dynSize; + const auto blkSize = StaticSize ? StaticSize : dynSize; for (Index i = 0; i < iSample; ++i) { - const auto ri1 = R[i+1].data() + start; + const auto ri1 = R[i + 1].data() + start; const auto ri0 = R[i].data() + start; /*--- Off-diagonal coefficients. ---*/ for (Index j = 0; j < i; ++j) { - const auto rj1 = R[j+1].data() + start; + const auto rj1 = R[j + 1].data() + start; const auto rj0 = R[j].data() + start; /*--- Sum of partial sums to reduce trunc. error. ---*/ Scalar sum = 0; SU2_OMP_SIMD for (Index k = 0; k < blkSize; ++k) { - sum += (ri1[k]-ri0[k]) * (rj1[k]-rj0[k]); + sum += (ri1[k] - ri0[k]) * (rj1[k] - rj0[k]); } /*--- 1D index of (i,j) in lower triangular storage. ---*/ - const auto iCoeff = i*(i+1)/2 + j; + const auto iCoeff = i * (i + 1) / 2 + j; mat(iCoeff) += sum; } /*--- Diagonal coeff and residual fused. ---*/ @@ -135,15 +131,15 @@ class CQuasiNewtonInvLeastSquares { const auto r = R[iSample].data() + start; SU2_OMP_SIMD for (Index k = 0; k < blkSize; ++k) { - diag += pow(ri1[k]-ri0[k], 2); - res += (ri1[k]-ri0[k]) * r[k]; + diag += pow(ri1[k] - ri0[k], 2); + res += (ri1[k] - ri0[k]) * r[k]; } - mat(i*(i+3)/2) += diag; + mat(i * (i + 3) / 2) += diag; vec(i) -= res; } } -public: + public: /*! \brief Default construction without allocation. */ CQuasiNewtonInvLeastSquares() = default; @@ -160,29 +156,31 @@ class CQuasiNewtonInvLeastSquares { * \param[in] nptdomain - Local size (<= npt), if 0 it defaults to npt. */ void resize(Index nsample, Index npt, Index nvar, Index nptdomain = 0) { - if (nptdomain > npt || nsample < 2) - SU2_MPI::Error("Invalid quasi-Newton parameters", CURRENT_FUNCTION); + if (nptdomain > npt || nsample < 2) SU2_MPI::Error("Invalid quasi-Newton parameters", CURRENT_FUNCTION); iSample = 0; - nPtDomain = nptdomain? nptdomain : npt; - work.resize(npt,nvar); + nPtDomain = nptdomain ? nptdomain : npt; + work.resize(npt, nvar); X.clear(); R.clear(); for (Index i = 0; i < nsample; ++i) { - X.emplace_back(npt,nvar); - R.emplace_back(npt,nvar); + X.emplace_back(npt, nvar); + R.emplace_back(npt, nvar); } X[0] = Scalar(0); /*--- Lower triangular packed storage. ---*/ - mat.resize(nsample*(nsample-1)/2); - rhs.resize(nsample-1); - sol.resize(nsample-1); + mat.resize(nsample * (nsample - 1) / 2); + rhs.resize(nsample - 1); + sol.resize(nsample - 1); } /*! \brief Size of the object, the number of samples. */ Index size() const { return X.size(); } /*! \brief Discard all history, keeping the current solution. */ - void reset() { std::swap(X[0], X[iSample]); iSample = 0; } + void reset() { + std::swap(X[0], X[iSample]); + iSample = 0; + } /*! * \brief Access the current fixed-point result. @@ -190,8 +188,8 @@ class CQuasiNewtonInvLeastSquares { */ su2matrix& FPresult() { return work; } const su2matrix& FPresult() const { return work; } - Scalar& FPresult(Index iPt, Index iVar) { return work(iPt,iVar); } - const Scalar& FPresult(Index iPt, Index iVar) const { return work(iPt,iVar); } + Scalar& FPresult(Index iPt, Index iVar) { return work(iPt, iVar); } + const Scalar& FPresult(Index iPt, Index iVar) const { return work(iPt, iVar); } /*! * \brief Access the current solution approximation. @@ -199,8 +197,8 @@ class CQuasiNewtonInvLeastSquares { */ su2matrix& solution() { return X[iSample]; } const su2matrix& solution() const { return X[iSample]; } - Scalar& operator() (Index iPt, Index iVar) { return X[iSample](iPt,iVar); } - const Scalar& operator() (Index iPt, Index iVar) const { return X[iSample](iPt,iVar); } + Scalar& operator()(Index iPt, Index iVar) { return X[iSample](iPt, iVar); } + const Scalar& operator()(Index iPt, Index iVar) const { return X[iSample](iPt, iVar); } /*! * \brief Compute and return a new approximation. @@ -219,35 +217,33 @@ class CQuasiNewtonInvLeastSquares { computeNormalEquations(); CSymmetricMatrix pseudoInv(iSample); for (Index i = 0, k = 0; i < iSample; ++i) - for (Index j = 0; j <= i; ++j) - pseudoInv(i,j) = mat(k++); + for (Index j = 0; j <= i; ++j) pseudoInv(i, j) = mat(k++); pseudoInv.Invert(true); pseudoInv.MatVecMult(rhs.data(), sol.data()); /*--- Compute correction, cleared before for less trunc. error. ---*/ for (Index k = 0; k < iSample; ++k) { - const auto x1 = X[k+1].data(); - const auto r1 = R[k+1].data(); + const auto x1 = X[k + 1].data(); + const auto r1 = R[k + 1].data(); const auto x0 = X[k].data(); const auto r0 = R[k].data(); SU2_OMP_SIMD for (Index i = 0; i < work.size(); ++i) { - Scalar dy = r1[i]-r0[i] + x1[i]-x0[i]; + Scalar dy = r1[i] - r0[i] + x1[i] - x0[i]; work.data()[i] += sol(k) * dy; } } } /*--- Check for need to shift left. ---*/ - if (iSample+1 == X.size()) { + if (iSample + 1 == X.size()) { shiftHistoryLeft(); iSample--; } /*--- Set new solution. ---*/ SU2_OMP_SIMD - for (Index i = 0; i < work.size(); ++i) - work.data()[i] += R[iSample].data()[i] + X[iSample].data()[i]; + for (Index i = 0; i < work.size(); ++i) work.data()[i] += R[iSample].data()[i] + X[iSample].data()[i]; std::swap(X[++iSample], work); return solution(); diff --git a/Common/include/toolboxes/CSquareMatrixCM.hpp b/Common/include/toolboxes/CSquareMatrixCM.hpp index 35dd27e15f3..178417fe92f 100644 --- a/Common/include/toolboxes/CSquareMatrixCM.hpp +++ b/Common/include/toolboxes/CSquareMatrixCM.hpp @@ -39,11 +39,11 @@ class CSquareMatrixCM { static_assert(ColMajorMatrix::Storage == StorageType::ColumnMajor, "Column major storage is assumed for LAPACK."); -private: - ColMajorMatrix mat; /*!< \brief Storage of the actual matrix. */ -public: + private: + ColMajorMatrix mat; /*!< \brief Storage of the actual matrix. */ + public: /*! * \brief Default constructor. Nothing to be done. */ @@ -55,7 +55,7 @@ class CSquareMatrixCM { * the matrix. * \param[in] N - Number of rows and colums of the matrix. */ - CSquareMatrixCM(int N) {Initialize(N);} + CSquareMatrixCM(int N) { Initialize(N); } /*! * \brief Operator, which makes available the given matrix element as a reference. @@ -63,7 +63,7 @@ class CSquareMatrixCM { * \param[in] j - Column index of the matrix element. * \return Reference to element (i,j). */ - inline passivedouble& operator() (int i, int j) {return mat(i,j);} + inline passivedouble& operator()(int i, int j) { return mat(i, j); } /*! * \brief Operator, which makes available the given matrix element as a const reference. @@ -71,31 +71,31 @@ class CSquareMatrixCM { * \param[in] j - Column index of the matrix element. * \return Constant reference to element (i,j). */ - inline const passivedouble& operator() (int i, int j) const {return mat(i,j);} + inline const passivedouble& operator()(int i, int j) const { return mat(i, j); } /*! * \brief Function, which makes available a reference to the actual matrix. * \return A reference to mat. */ - inline ColMajorMatrix& GetMat() {return mat;} + inline ColMajorMatrix& GetMat() { return mat; } /*! * \brief Function, which makes available a const reference to the actual matrix. * \return A const reference to mat. */ - inline const ColMajorMatrix& GetMat() const {return mat;} + inline const ColMajorMatrix& GetMat() const { return mat; } /*! * \brief Function, which allocates the memory for the matrix. * \param[in] N - Number of rows and colums of the matrix. */ - inline void Initialize(int N) {mat.resize(N,N);} + inline void Initialize(int N) { mat.resize(N, N); } /*! * \brief Function, which makes available the size of the matrix. * \return The number of rows, columns of the matrix. */ - inline int Size() const {return mat.rows();} + inline int Size() const { return mat.rows(); } /*! * \brief Function, which carries out the matrix produc of the current matrix @@ -104,21 +104,18 @@ class CSquareMatrixCM { * \param[in] mat_in - Matrix to be multiplied by the current matrix. * \param[out] mat_out - Matrix to store the result of the multiplication. */ - void MatMatMult(const char side, - const ColMajorMatrix &mat_in, - ColMajorMatrix &mat_out) const; + void MatMatMult(const char side, const ColMajorMatrix& mat_in, + ColMajorMatrix& mat_out) const; /*! * \brief Naive matrix-vector multiplication with general type. */ - template - void MatVecMult(ForwardIt vec_in, ForwardIt vec_out) const - { + template + void MatVecMult(ForwardIt vec_in, ForwardIt vec_out) const { for (int i = 0; i < Size(); ++i) { *vec_out = 0.0; auto vec = vec_in; - for (int k = 0; k < Size(); ++k) - *vec_out += *(vec++) * mat(i,k); + for (int k = 0; k < Size(); ++k) *vec_out += *(vec++) * mat(i, k); ++vec_out; } } @@ -132,5 +129,4 @@ class CSquareMatrixCM { * \brief Function, which transposes the matrix in-place. */ void Transpose(); - }; diff --git a/Common/include/toolboxes/CSymmetricMatrix.hpp b/Common/include/toolboxes/CSymmetricMatrix.hpp index 717b7a45259..2dee2893e34 100644 --- a/Common/include/toolboxes/CSymmetricMatrix.hpp +++ b/Common/include/toolboxes/CSymmetricMatrix.hpp @@ -37,7 +37,8 @@ */ class CSymmetricMatrix { static_assert(su2passivematrix::IsRowMajor, "Row major storage is assumed for LAPACK."); -private: + + private: su2passivematrix mat; // Not optimized dense matrix factorization and inversion for portability. @@ -47,30 +48,28 @@ class CSymmetricMatrix { void CalcInv_sytri(); void CalcInv_potri(); -public: + public: CSymmetricMatrix() = default; - CSymmetricMatrix(int N) {Initialize(N);} + CSymmetricMatrix(int N) { Initialize(N); } void Initialize(int N); inline int Size() const { return mat.rows(); } - inline passivedouble Get(int i, int j) const { return mat(std::min(i,j),std::max(i,j)); } + inline passivedouble Get(int i, int j) const { return mat(std::min(i, j), std::max(i, j)); } - inline void Set(int i, int j, passivedouble val) { mat(std::min(i,j),std::max(i,j)) = val; } + inline void Set(int i, int j, passivedouble val) { mat(std::min(i, j), std::max(i, j)) = val; } - inline passivedouble& operator() (int i, int j) { return mat(std::min(i,j),std::max(i,j)); } + inline passivedouble& operator()(int i, int j) { return mat(std::min(i, j), std::max(i, j)); } - inline const passivedouble& operator() (int i, int j) const { return mat(std::min(i,j),std::max(i,j)); } + inline const passivedouble& operator()(int i, int j) const { return mat(std::min(i, j), std::max(i, j)); } - template - void MatVecMult(ForwardIt vec_in, ForwardIt vec_out) const - { + template + void MatVecMult(ForwardIt vec_in, ForwardIt vec_out) const { for (int i = 0; i < Size(); ++i) { *vec_out = 0.0; auto vec = vec_in; - for (int k = 0; k < Size(); ++k) - *vec_out += *(vec++) * Get(i,k); + for (int k = 0; k < Size(); ++k) *vec_out += *(vec++) * Get(i, k); ++vec_out; } } @@ -80,5 +79,4 @@ class CSymmetricMatrix { void Invert(bool is_spd = false); su2passivematrix StealData(); - }; diff --git a/Common/include/toolboxes/MMS/CIncTGVSolution.hpp b/Common/include/toolboxes/MMS/CIncTGVSolution.hpp index 972b6d4075c..2885cf863f0 100644 --- a/Common/include/toolboxes/MMS/CIncTGVSolution.hpp +++ b/Common/include/toolboxes/MMS/CIncTGVSolution.hpp @@ -26,7 +26,6 @@ * License along with SU2. If not, see . */ - #pragma once #include @@ -37,10 +36,8 @@ * \brief Class to define the required data for the incompressible Taylor Green Vortex. * \author T. Economon, E. van der Weide */ -class CIncTGVSolution final: public CVerificationSolution { - -protected: - +class CIncTGVSolution final : public CVerificationSolution { + protected: /*--- TGV specific conditions. ---*/ su2double tgvLength; /*!< \brief Taylor-Green length scale. */ @@ -48,10 +45,9 @@ class CIncTGVSolution final: public CVerificationSolution { su2double tgvDensity; /*!< \brief Taylor-Green density. */ su2double tgvViscosity; /*!< \brief Taylor-Green viscosity. */ - su2double Temperature; /*!< \brief Temperature, just to be safe. */ - -public: + su2double Temperature; /*!< \brief Temperature, just to be safe. */ + public: /*! * \brief Constructor of the class. */ @@ -64,10 +60,7 @@ class CIncTGVSolution final: public CVerificationSolution { * \param[in] val_iMesh - Multigrid level of the solver. * \param[in] config - Configuration of the particular problem. */ - CIncTGVSolution(unsigned short val_nDim, - unsigned short val_nvar, - unsigned short val_iMesh, - CConfig* config); + CIncTGVSolution(unsigned short val_nDim, unsigned short val_nvar, unsigned short val_iMesh, CConfig* config); /*! * \brief Destructor of the class. @@ -80,9 +73,7 @@ class CIncTGVSolution final: public CVerificationSolution { * \param[in] val_t - Current physical time. * \param[in] val_solution - Array where the exact solution is stored. */ - void GetSolution(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const override; + void GetSolution(const su2double* val_coords, const su2double val_t, su2double* val_solution) const override; /*! * \brief Get the boundary conditions state for an exact solution. @@ -90,7 +81,5 @@ class CIncTGVSolution final: public CVerificationSolution { * \param[in] val_t - Current physical time. * \param[in] val_solution - Array where the exact solution is stored. */ - void GetBCState(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const override; + void GetBCState(const su2double* val_coords, const su2double val_t, su2double* val_solution) const override; }; diff --git a/Common/include/toolboxes/MMS/CInviscidVortexSolution.hpp b/Common/include/toolboxes/MMS/CInviscidVortexSolution.hpp index 4e2b733eeeb..f440ad9aac0 100644 --- a/Common/include/toolboxes/MMS/CInviscidVortexSolution.hpp +++ b/Common/include/toolboxes/MMS/CInviscidVortexSolution.hpp @@ -26,7 +26,6 @@ * License along with SU2. If not, see . */ - #pragma once #include @@ -37,26 +36,23 @@ * \brief Class to define the required data for the Inviscid Vortex. * \author E. van der Weide, T. Economon */ -class CInviscidVortexSolution final: public CVerificationSolution { - -protected: - +class CInviscidVortexSolution final : public CVerificationSolution { + protected: /*--- Specific conditions for the inviscid vortex. ---*/ - su2double MachVortex; /*!< \brief Mach number of the undisturbed flow. */ - su2double x0Vortex; /*!< \brief Initial x-coordinate of the vortex center. */ - su2double y0Vortex; /*!< \brief Initial y-coordinate of the vortex center. */ - su2double RVortex; /*!< \brief Radius of the vortex. */ - su2double epsVortex; /*!< \brief Strength of the vortex. */ - su2double thetaVortex; /*!< \brief Advection angle (in degrees) of the vortex. */ + su2double MachVortex; /*!< \brief Mach number of the undisturbed flow. */ + su2double x0Vortex; /*!< \brief Initial x-coordinate of the vortex center. */ + su2double y0Vortex; /*!< \brief Initial y-coordinate of the vortex center. */ + su2double RVortex; /*!< \brief Radius of the vortex. */ + su2double epsVortex; /*!< \brief Strength of the vortex. */ + su2double thetaVortex; /*!< \brief Advection angle (in degrees) of the vortex. */ /*--- Variables involving gamma. */ - su2double Gamma; /*!< \brief Gamma */ - su2double Gm1; /*!< \brief Gamma minus 1 */ - su2double ovGm1; /*!< \brief 1 over Gamma minus 1 */ - su2double gamOvGm1; /*!< \brief Gamma over Gamma minus 1 */ - -public: + su2double Gamma; /*!< \brief Gamma */ + su2double Gm1; /*!< \brief Gamma minus 1 */ + su2double ovGm1; /*!< \brief 1 over Gamma minus 1 */ + su2double gamOvGm1; /*!< \brief Gamma over Gamma minus 1 */ + public: /*! * \brief Constructor of the class. */ @@ -69,10 +65,7 @@ class CInviscidVortexSolution final: public CVerificationSolution { * \param[in] val_iMesh - Multigrid level of the solver. * \param[in] config - Configuration of the particular problem. */ - CInviscidVortexSolution(unsigned short val_nDim, - unsigned short val_nvar, - unsigned short val_iMesh, - CConfig* config); + CInviscidVortexSolution(unsigned short val_nDim, unsigned short val_nvar, unsigned short val_iMesh, CConfig* config); /*! * \brief Destructor of the class. @@ -85,9 +78,7 @@ class CInviscidVortexSolution final: public CVerificationSolution { * \param[in] val_t - Current physical time. * \param[in] val_solution - Array where the exact solution is stored. */ - void GetSolution(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const override; + void GetSolution(const su2double* val_coords, const su2double val_t, su2double* val_solution) const override; /*! * \brief Get the boundary conditions state for an exact solution. @@ -95,7 +86,5 @@ class CInviscidVortexSolution final: public CVerificationSolution { * \param[in] val_t - Current physical time. * \param[in] val_solution - Array where the exact solution is stored. */ - void GetBCState(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const override; + void GetBCState(const su2double* val_coords, const su2double val_t, su2double* val_solution) const override; }; diff --git a/Common/include/toolboxes/MMS/CMMSIncEulerSolution.hpp b/Common/include/toolboxes/MMS/CMMSIncEulerSolution.hpp index 0af37d51bd6..eb71b4c5a61 100644 --- a/Common/include/toolboxes/MMS/CMMSIncEulerSolution.hpp +++ b/Common/include/toolboxes/MMS/CMMSIncEulerSolution.hpp @@ -26,7 +26,6 @@ * License along with SU2. If not, see . */ - #pragma once #include @@ -38,13 +37,11 @@ * incompressible Euler equations. * \author T. Economon, E. van der Weide */ -class CMMSIncEulerSolution final: public CVerificationSolution { - -protected: - +class CMMSIncEulerSolution final : public CVerificationSolution { + protected: /*--- Variables that define the solution and MMS source term. ---*/ - su2double Density; /*!< \brief Density, must be constant. */ - su2double Temperature; /*!< \brief Temperature, just to be safe. */ + su2double Density; /*!< \brief Density, must be constant. */ + su2double Temperature; /*!< \brief Temperature, just to be safe. */ /*--- Constants, which describe this manufactured solution. This is a solution where the primitive variables vary as a combination @@ -52,13 +49,12 @@ class CMMSIncEulerSolution final: public CVerificationSolution { Knupp P, "Code verification by the method of manufactured solutions," SAND 2000-1444, Sandia National Laboratories, Albuquerque, NM, 2000. ---*/ - su2double P_0; /*!< \brief Parameter for the pressure solution. */ - su2double u_0; /*!< \brief Parameter for the x-velocity solution. */ - su2double v_0; /*!< \brief Parameter for the y-velocity solution. */ - su2double epsilon; /*!< \brief Parameter for the velocity solutions. */ - -public: + su2double P_0; /*!< \brief Parameter for the pressure solution. */ + su2double u_0; /*!< \brief Parameter for the x-velocity solution. */ + su2double v_0; /*!< \brief Parameter for the y-velocity solution. */ + su2double epsilon; /*!< \brief Parameter for the velocity solutions. */ + public: /*! * \brief Constructor of the class. */ @@ -71,10 +67,7 @@ class CMMSIncEulerSolution final: public CVerificationSolution { * \param[in] val_iMesh - Multigrid level of the solver. * \param[in] config - Configuration of the particular problem. */ - CMMSIncEulerSolution(unsigned short val_nDim, - unsigned short val_nvar, - unsigned short val_iMesh, - CConfig* config); + CMMSIncEulerSolution(unsigned short val_nDim, unsigned short val_nvar, unsigned short val_iMesh, CConfig* config); /*! * \brief Destructor of the class. @@ -87,9 +80,7 @@ class CMMSIncEulerSolution final: public CVerificationSolution { * \param[in] val_t - Current physical time. * \param[in] val_solution - Array where the exact solution is stored. */ - void GetSolution(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const override; + void GetSolution(const su2double* val_coords, const su2double val_t, su2double* val_solution) const override; /*! * \brief Get the boundary conditions state for an exact solution. @@ -97,9 +88,7 @@ class CMMSIncEulerSolution final: public CVerificationSolution { * \param[in] val_t - Current physical time. * \param[in] val_solution - Array where the exact solution is stored. */ - void GetBCState(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const override; + void GetBCState(const su2double* val_coords, const su2double val_t, su2double* val_solution) const override; /*! * \brief Get the source term for the manufactured solution (MMS). @@ -107,9 +96,7 @@ class CMMSIncEulerSolution final: public CVerificationSolution { * \param[in] val_t - Current physical time. * \param[in] val_solution - Array where the exact solution is stored. */ - void GetMMSSourceTerm(const su2double *val_coords, - const su2double val_t, - su2double *val_source) const override; + void GetMMSSourceTerm(const su2double* val_coords, const su2double val_t, su2double* val_source) const override; /*! * \brief Whether or not this verification solution is a manufactured solution. diff --git a/Common/include/toolboxes/MMS/CMMSIncNSSolution.hpp b/Common/include/toolboxes/MMS/CMMSIncNSSolution.hpp index 19f58034a49..51cc3e630d9 100644 --- a/Common/include/toolboxes/MMS/CMMSIncNSSolution.hpp +++ b/Common/include/toolboxes/MMS/CMMSIncNSSolution.hpp @@ -26,7 +26,6 @@ * License along with SU2. If not, see . */ - #pragma once #include @@ -38,14 +37,12 @@ * laminar incompressible Navier-Stokes equations. * \author T. Economon, E. van der Weide */ -class CMMSIncNSSolution final: public CVerificationSolution { - -protected: - +class CMMSIncNSSolution final : public CVerificationSolution { + protected: /*--- Variables that define the solution and MMS source term. ---*/ - su2double Viscosity; /*!< \brief Viscosity, must be constant. */ - su2double Density; /*!< \brief Density, must be constant. */ - su2double Temperature; /*!< \brief Temperature, just to be safe. */ + su2double Viscosity; /*!< \brief Viscosity, must be constant. */ + su2double Density; /*!< \brief Density, must be constant. */ + su2double Temperature; /*!< \brief Temperature, just to be safe. */ /*--- Constants, which describe this manufactured solution. This is a viscous solution where the primitive variables vary as a combination @@ -53,13 +50,12 @@ class CMMSIncNSSolution final: public CVerificationSolution { Knupp P, "Code verification by the method of manufactured solutions," SAND 2000-1444, Sandia National Laboratories, Albuquerque, NM, 2000. ---*/ - su2double P_0; /*!< \brief Parameter for the pressure solution. */ - su2double u_0; /*!< \brief Parameter for the x-velocity solution. */ - su2double v_0; /*!< \brief Parameter for the y-velocity solution. */ - su2double epsilon; /*!< \brief Parameter for the velocity solutions. */ - -public: + su2double P_0; /*!< \brief Parameter for the pressure solution. */ + su2double u_0; /*!< \brief Parameter for the x-velocity solution. */ + su2double v_0; /*!< \brief Parameter for the y-velocity solution. */ + su2double epsilon; /*!< \brief Parameter for the velocity solutions. */ + public: /*! * \brief Constructor of the class. */ @@ -72,10 +68,7 @@ class CMMSIncNSSolution final: public CVerificationSolution { * \param[in] val_iMesh - Multigrid level of the solver. * \param[in] config - Configuration of the particular problem. */ - CMMSIncNSSolution(unsigned short val_nDim, - unsigned short val_nvar, - unsigned short val_iMesh, - CConfig* config); + CMMSIncNSSolution(unsigned short val_nDim, unsigned short val_nvar, unsigned short val_iMesh, CConfig* config); /*! * \brief Destructor of the class. @@ -88,9 +81,7 @@ class CMMSIncNSSolution final: public CVerificationSolution { * \param[in] val_t - Current physical time. * \param[in] val_solution - Array where the exact solution is stored. */ - void GetSolution(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const override; + void GetSolution(const su2double* val_coords, const su2double val_t, su2double* val_solution) const override; /*! * \brief Get the boundary conditions state for an exact solution. @@ -98,9 +89,7 @@ class CMMSIncNSSolution final: public CVerificationSolution { * \param[in] val_t - Current physical time. * \param[in] val_solution - Array where the exact solution is stored. */ - void GetBCState(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const override; + void GetBCState(const su2double* val_coords, const su2double val_t, su2double* val_solution) const override; /*! * \brief Get the source term for the manufactured solution (MMS). @@ -108,9 +97,7 @@ class CMMSIncNSSolution final: public CVerificationSolution { * \param[in] val_t - Current physical time. * \param[in] val_solution - Array where the exact solution is stored. */ - void GetMMSSourceTerm(const su2double *val_coords, - const su2double val_t, - su2double *val_source) const override; + void GetMMSSourceTerm(const su2double* val_coords, const su2double val_t, su2double* val_source) const override; /*! * \brief Whether or not this verification solution is a manufactured solution. diff --git a/Common/include/toolboxes/MMS/CMMSNSTwoHalfCirclesSolution.hpp b/Common/include/toolboxes/MMS/CMMSNSTwoHalfCirclesSolution.hpp index 3977986f43b..acb9fa3a796 100644 --- a/Common/include/toolboxes/MMS/CMMSNSTwoHalfCirclesSolution.hpp +++ b/Common/include/toolboxes/MMS/CMMSNSTwoHalfCirclesSolution.hpp @@ -26,7 +26,6 @@ * License along with SU2. If not, see . */ - #pragma once #include @@ -38,33 +37,31 @@ laminar Navier-Stokes equations on the domain between two half circles. * \author E. van der Weide, T. Economon */ -class CMMSNSTwoHalfCirclesSolution final: public CVerificationSolution { - -protected: +class CMMSNSTwoHalfCirclesSolution final : public CVerificationSolution { + protected: /*--- Variables that define the solution and MMS source term. ---*/ - su2double Gamma; /*!< \brief Specific heat ratio. */ - su2double RGas; /*!< \brief Gas constant. */ - su2double Viscosity; /*!< \brief Constant viscosity. */ - su2double Conductivity; /*!< \brief Constant thermal conductivity. */ - su2double TWall; /*!< \brief Prescribed wall temperature at the outer wall. */ + su2double Gamma; /*!< \brief Specific heat ratio. */ + su2double RGas; /*!< \brief Gas constant. */ + su2double Viscosity; /*!< \brief Constant viscosity. */ + su2double Conductivity; /*!< \brief Constant thermal conductivity. */ + su2double TWall; /*!< \brief Prescribed wall temperature at the outer wall. */ - su2double Pressure_Ref; /*!< \brief Reference pressure for non-dimensionalization. */ - su2double Density_Ref; /*!< \brief Reference density for non-dimensionalization. */ - su2double Velocity_Ref; /*!< \brief Reference velocity for non-dimensionalization. */ + su2double Pressure_Ref; /*!< \brief Reference pressure for non-dimensionalization. */ + su2double Density_Ref; /*!< \brief Reference density for non-dimensionalization. */ + su2double Velocity_Ref; /*!< \brief Reference velocity for non-dimensionalization. */ /*--- Constants, which describe this manufactured solution. The primitive variables rho, T, u, v and w are described by analytical functions in such a way that the inner wall is an adiabatic no-slip wall and the outer wall is an isothermal no-slip wall. ---*/ - su2double rho_0; /*!< \brief Constant density. */ - su2double u_0; /*!< \brief Maximum x-velocity in the domain. */ - su2double v_0; /*!< \brief Maximum y-velocity in the domain. */ - - su2double a_T1; /*!< \brief Parameter for the temperature solution. */ - su2double a_T2; /*!< \brief Parameter for the temperature solution. */ + su2double rho_0; /*!< \brief Constant density. */ + su2double u_0; /*!< \brief Maximum x-velocity in the domain. */ + su2double v_0; /*!< \brief Maximum y-velocity in the domain. */ -public: + su2double a_T1; /*!< \brief Parameter for the temperature solution. */ + su2double a_T2; /*!< \brief Parameter for the temperature solution. */ + public: /*! * \brief Constructor of the class. */ @@ -77,10 +74,8 @@ class CMMSNSTwoHalfCirclesSolution final: public CVerificationSolution { * \param[in] val_iMesh - Multigrid level of the solver. * \param[in] config - Configuration of the particular problem. */ - CMMSNSTwoHalfCirclesSolution(unsigned short val_nDim, - unsigned short val_nvar, - unsigned short val_iMesh, - CConfig* config); + CMMSNSTwoHalfCirclesSolution(unsigned short val_nDim, unsigned short val_nvar, unsigned short val_iMesh, + CConfig* config); /*! * \brief Destructor of the class. @@ -93,9 +88,7 @@ class CMMSNSTwoHalfCirclesSolution final: public CVerificationSolution { * \param[in] val_t - Current physical time. * \param[in] val_solution - Array where the exact solution is stored. */ - void GetSolution(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const override; + void GetSolution(const su2double* val_coords, const su2double val_t, su2double* val_solution) const override; /*! * \brief Get the boundary conditions state for an exact solution. @@ -103,9 +96,7 @@ class CMMSNSTwoHalfCirclesSolution final: public CVerificationSolution { * \param[in] val_t - Current physical time. * \param[in] val_solution - Array where the exact solution is stored. */ - void GetBCState(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const override; + void GetBCState(const su2double* val_coords, const su2double val_t, su2double* val_solution) const override; /*! * \brief Get the source term for the manufactured solution (MMS). @@ -113,9 +104,7 @@ class CMMSNSTwoHalfCirclesSolution final: public CVerificationSolution { * \param[in] val_t - Current physical time. * \param[in] val_solution - Array where the exact solution is stored. */ - void GetMMSSourceTerm(const su2double *val_coords, - const su2double val_t, - su2double *val_source) const override; + void GetMMSSourceTerm(const su2double* val_coords, const su2double val_t, su2double* val_source) const override; /*! * \brief Whether or not this verification solution is a manufactured solution. diff --git a/Common/include/toolboxes/MMS/CMMSNSTwoHalfSpheresSolution.hpp b/Common/include/toolboxes/MMS/CMMSNSTwoHalfSpheresSolution.hpp index 5ae529d2251..f879b3dc177 100644 --- a/Common/include/toolboxes/MMS/CMMSNSTwoHalfSpheresSolution.hpp +++ b/Common/include/toolboxes/MMS/CMMSNSTwoHalfSpheresSolution.hpp @@ -26,7 +26,6 @@ * License along with SU2. If not, see . */ - #pragma once #include @@ -38,34 +37,32 @@ laminar Navier-Stokes equations on the domain between two half spheres. * \author E. van der Weide, T. Economon */ -class CMMSNSTwoHalfSpheresSolution final: public CVerificationSolution { - -protected: +class CMMSNSTwoHalfSpheresSolution final : public CVerificationSolution { + protected: /*--- Variables that define the solution and MMS source term. ---*/ - su2double Gamma; /*!< \brief Specific heat ratio. */ - su2double RGas; /*!< \brief Gas constant. */ - su2double Viscosity; /*!< \brief Constant viscosity. */ - su2double Conductivity; /*!< \brief Constant thermal conductivity. */ - su2double TWall; /*!< \brief Prescribed wall temperature at the outer wall. */ + su2double Gamma; /*!< \brief Specific heat ratio. */ + su2double RGas; /*!< \brief Gas constant. */ + su2double Viscosity; /*!< \brief Constant viscosity. */ + su2double Conductivity; /*!< \brief Constant thermal conductivity. */ + su2double TWall; /*!< \brief Prescribed wall temperature at the outer wall. */ - su2double Pressure_Ref; /*!< \brief Reference pressure for non-dimensionalization. */ - su2double Density_Ref; /*!< \brief Reference density for non-dimensionalization. */ - su2double Velocity_Ref; /*!< \brief Reference velocity for non-dimensionalization. */ + su2double Pressure_Ref; /*!< \brief Reference pressure for non-dimensionalization. */ + su2double Density_Ref; /*!< \brief Reference density for non-dimensionalization. */ + su2double Velocity_Ref; /*!< \brief Reference velocity for non-dimensionalization. */ /*--- Constants, which describe this manufactured solution. The primitive variables rho, T, u, v and w are described by analytical functions in such a way that the inner wall is an adiabatic no-slip wall and the outer wall is an isothermal no-slip wall. ---*/ - su2double rho_0; /*!< \brief Constant density. */ - su2double u_0; /*!< \brief Maximum x-velocity in the domain. */ - su2double v_0; /*!< \brief Maximum y-velocity in the domain. */ - su2double w_0; /*!< \brief Maximum z-velocity in the domain. */ - - su2double a_T1; /*!< \brief Parameter for the temperature solution. */ - su2double a_T2; /*!< \brief Parameter for the temperature solution. */ + su2double rho_0; /*!< \brief Constant density. */ + su2double u_0; /*!< \brief Maximum x-velocity in the domain. */ + su2double v_0; /*!< \brief Maximum y-velocity in the domain. */ + su2double w_0; /*!< \brief Maximum z-velocity in the domain. */ -public: + su2double a_T1; /*!< \brief Parameter for the temperature solution. */ + su2double a_T2; /*!< \brief Parameter for the temperature solution. */ + public: /*! * \brief Constructor of the class. */ @@ -78,10 +75,8 @@ class CMMSNSTwoHalfSpheresSolution final: public CVerificationSolution { * \param[in] val_iMesh - Multigrid level of the solver. * \param[in] config - Configuration of the particular problem. */ - CMMSNSTwoHalfSpheresSolution(unsigned short val_nDim, - unsigned short val_nvar, - unsigned short val_iMesh, - CConfig* config); + CMMSNSTwoHalfSpheresSolution(unsigned short val_nDim, unsigned short val_nvar, unsigned short val_iMesh, + CConfig* config); /*! * \brief Destructor of the class. @@ -94,9 +89,7 @@ class CMMSNSTwoHalfSpheresSolution final: public CVerificationSolution { * \param[in] val_t - Current physical time. * \param[in] val_solution - Array where the exact solution is stored. */ - void GetSolution(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const override; + void GetSolution(const su2double* val_coords, const su2double val_t, su2double* val_solution) const override; /*! * \brief Get the boundary conditions state for an exact solution. @@ -104,9 +97,7 @@ class CMMSNSTwoHalfSpheresSolution final: public CVerificationSolution { * \param[in] val_t - Current physical time. * \param[in] val_solution - Array where the exact solution is stored. */ - void GetBCState(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const override; + void GetBCState(const su2double* val_coords, const su2double val_t, su2double* val_solution) const override; /*! * \brief Get the source term for the manufactured solution (MMS). @@ -114,9 +105,7 @@ class CMMSNSTwoHalfSpheresSolution final: public CVerificationSolution { * \param[in] val_t - Current physical time. * \param[in] val_solution - Array where the exact solution is stored. */ - void GetMMSSourceTerm(const su2double *val_coords, - const su2double val_t, - su2double *val_source) const override; + void GetMMSSourceTerm(const su2double* val_coords, const su2double val_t, su2double* val_source) const override; /*! * \brief Whether or not this verification solution is a manufactured solution. diff --git a/Common/include/toolboxes/MMS/CMMSNSUnitQuadSolution.hpp b/Common/include/toolboxes/MMS/CMMSNSUnitQuadSolution.hpp index c74ec885101..387fa5c78b7 100644 --- a/Common/include/toolboxes/MMS/CMMSNSUnitQuadSolution.hpp +++ b/Common/include/toolboxes/MMS/CMMSNSUnitQuadSolution.hpp @@ -26,7 +26,6 @@ * License along with SU2. If not, see . */ - #pragma once #include @@ -38,10 +37,8 @@ laminar Navier-Stokes equations on a unit quad. * \author E. van der Weide, T. Economon */ -class CMMSNSUnitQuadSolution final: public CVerificationSolution { - -protected: - +class CMMSNSUnitQuadSolution final : public CVerificationSolution { + protected: /*--- Variables that define the solution and MMS source term. ---*/ su2double Gamma; /*!< \brief Specific heat ratio. */ su2double RGas; /*!< \brief Gas constant. */ @@ -53,38 +50,37 @@ class CMMSNSUnitQuadSolution final: public CVerificationSolution { combination of sine and cosine functions. The unit quad is probably not necessary, and an arbitrary domain should work as well. ---*/ - su2double L; /*!< \brief Length scale. */ - su2double a_Px; /*!< \brief Parameter for the pressure solution. */ - su2double a_Pxy; /*!< \brief Parameter for the pressure solution. */ - su2double a_Py; /*!< \brief Parameter for the pressure solution. */ - su2double a_rhox; /*!< \brief Parameter for the density solution. */ - su2double a_rhoxy; /*!< \brief Parameter for the density solution. */ - su2double a_rhoy; /*!< \brief Parameter for the density solution. */ - su2double a_ux; /*!< \brief Parameter for the x-velocity solution. */ - su2double a_uxy; /*!< \brief Parameter for the x-velocity solution. */ - su2double a_uy; /*!< \brief Parameter for the x-velocity solution. */ - su2double a_vx; /*!< \brief Parameter for the y-velocity solution. */ - su2double a_vxy; /*!< \brief Parameter for the y-velocity solution. */ - su2double a_vy; /*!< \brief Parameter for the y-velocity solution. */ - su2double P_0; /*!< \brief Parameter for the pressure solution. */ - su2double P_x; /*!< \brief Parameter for the pressure solution. */ - su2double P_xy; /*!< \brief Parameter for the pressure solution. */ - su2double P_y; /*!< \brief Parameter for the pressure solution. */ - su2double rho_0; /*!< \brief Parameter for the density solution. */ - su2double rho_x; /*!< \brief Parameter for the density solution. */ - su2double rho_xy; /*!< \brief Parameter for the density solution. */ - su2double rho_y; /*!< \brief Parameter for the density solution. */ - su2double u_0; /*!< \brief Parameter for the x-velocity solution. */ - su2double u_x; /*!< \brief Parameter for the x-velocity solution. */ - su2double u_xy; /*!< \brief Parameter for the x-velocity solution. */ - su2double u_y; /*!< \brief Parameter for the x-velocity solution. */ - su2double v_0; /*!< \brief Parameter for the y-velocity solution. */ - su2double v_x; /*!< \brief Parameter for the y-velocity solution. */ - su2double v_xy; /*!< \brief Parameter for the y-velocity solution. */ - su2double v_y; /*!< \brief Parameter for the y-velocity solution. */ - -public: - + su2double L; /*!< \brief Length scale. */ + su2double a_Px; /*!< \brief Parameter for the pressure solution. */ + su2double a_Pxy; /*!< \brief Parameter for the pressure solution. */ + su2double a_Py; /*!< \brief Parameter for the pressure solution. */ + su2double a_rhox; /*!< \brief Parameter for the density solution. */ + su2double a_rhoxy; /*!< \brief Parameter for the density solution. */ + su2double a_rhoy; /*!< \brief Parameter for the density solution. */ + su2double a_ux; /*!< \brief Parameter for the x-velocity solution. */ + su2double a_uxy; /*!< \brief Parameter for the x-velocity solution. */ + su2double a_uy; /*!< \brief Parameter for the x-velocity solution. */ + su2double a_vx; /*!< \brief Parameter for the y-velocity solution. */ + su2double a_vxy; /*!< \brief Parameter for the y-velocity solution. */ + su2double a_vy; /*!< \brief Parameter for the y-velocity solution. */ + su2double P_0; /*!< \brief Parameter for the pressure solution. */ + su2double P_x; /*!< \brief Parameter for the pressure solution. */ + su2double P_xy; /*!< \brief Parameter for the pressure solution. */ + su2double P_y; /*!< \brief Parameter for the pressure solution. */ + su2double rho_0; /*!< \brief Parameter for the density solution. */ + su2double rho_x; /*!< \brief Parameter for the density solution. */ + su2double rho_xy; /*!< \brief Parameter for the density solution. */ + su2double rho_y; /*!< \brief Parameter for the density solution. */ + su2double u_0; /*!< \brief Parameter for the x-velocity solution. */ + su2double u_x; /*!< \brief Parameter for the x-velocity solution. */ + su2double u_xy; /*!< \brief Parameter for the x-velocity solution. */ + su2double u_y; /*!< \brief Parameter for the x-velocity solution. */ + su2double v_0; /*!< \brief Parameter for the y-velocity solution. */ + su2double v_x; /*!< \brief Parameter for the y-velocity solution. */ + su2double v_xy; /*!< \brief Parameter for the y-velocity solution. */ + su2double v_y; /*!< \brief Parameter for the y-velocity solution. */ + + public: /*! * \brief Constructor of the class. */ @@ -97,10 +93,7 @@ class CMMSNSUnitQuadSolution final: public CVerificationSolution { * \param[in] val_iMesh - Multigrid level of the solver. * \param[in] config - Configuration of the particular problem. */ - CMMSNSUnitQuadSolution(unsigned short val_nDim, - unsigned short val_nvar, - unsigned short val_iMesh, - CConfig* config); + CMMSNSUnitQuadSolution(unsigned short val_nDim, unsigned short val_nvar, unsigned short val_iMesh, CConfig* config); /*! * \brief Destructor of the class. @@ -113,9 +106,7 @@ class CMMSNSUnitQuadSolution final: public CVerificationSolution { * \param[in] val_t - Current physical time. * \param[in] val_solution - Array where the exact solution is stored. */ - void GetSolution(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const override; + void GetSolution(const su2double* val_coords, const su2double val_t, su2double* val_solution) const override; /*! * \brief Get the boundary conditions state for an exact solution. @@ -123,9 +114,7 @@ class CMMSNSUnitQuadSolution final: public CVerificationSolution { * \param[in] val_t - Current physical time. * \param[in] val_solution - Array where the exact solution is stored. */ - void GetBCState(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const override; + void GetBCState(const su2double* val_coords, const su2double val_t, su2double* val_solution) const override; /*! * \brief Get the source term for the manufactured solution (MMS). @@ -133,9 +122,7 @@ class CMMSNSUnitQuadSolution final: public CVerificationSolution { * \param[in] val_t - Current physical time. * \param[in] val_solution - Array where the exact solution is stored. */ - void GetMMSSourceTerm(const su2double *val_coords, - const su2double val_t, - su2double *val_source) const override; + void GetMMSSourceTerm(const su2double* val_coords, const su2double val_t, su2double* val_source) const override; /*! * \brief Whether or not this verification solution is a manufactured solution. diff --git a/Common/include/toolboxes/MMS/CMMSNSUnitQuadSolutionWallBC.hpp b/Common/include/toolboxes/MMS/CMMSNSUnitQuadSolutionWallBC.hpp index 5aa25502f09..ba2135bb343 100644 --- a/Common/include/toolboxes/MMS/CMMSNSUnitQuadSolutionWallBC.hpp +++ b/Common/include/toolboxes/MMS/CMMSNSUnitQuadSolutionWallBC.hpp @@ -26,7 +26,6 @@ * License along with SU2. If not, see . */ - #pragma once #include @@ -38,10 +37,8 @@ laminar Navier-Stokes equations on a unit quad with wall boundary conditions. * \author E. van der Weide, T. Economon */ -class CMMSNSUnitQuadSolutionWallBC final: public CVerificationSolution { - -protected: - +class CMMSNSUnitQuadSolutionWallBC final : public CVerificationSolution { + protected: /*--- Variables that define the solution and MMS source term. ---*/ su2double Gamma; /*!< \brief Specific heat ratio. */ su2double RGas; /*!< \brief Gas constant. */ @@ -49,23 +46,22 @@ class CMMSNSUnitQuadSolutionWallBC final: public CVerificationSolution { su2double Conductivity; /*!< \brief Thermal conductivity, must be constant. */ su2double TWall; /*!< \brief Prescribed wall temperature at the upper wall. */ - su2double Pressure_Ref; /*!< \brief Reference pressure for non-dimensionalization. */ - su2double Density_Ref; /*!< \brief Reference density for non-dimensionalization. */ - su2double Velocity_Ref; /*!< \brief Reference velocity for non-dimensionalization. */ + su2double Pressure_Ref; /*!< \brief Reference pressure for non-dimensionalization. */ + su2double Density_Ref; /*!< \brief Reference density for non-dimensionalization. */ + su2double Velocity_Ref; /*!< \brief Reference velocity for non-dimensionalization. */ /*--- Constants, which describe this manufactured solution. The primitive variables rho, T, u and v are described by analytical functions in such a way that the lower wall is an adiabatic no-slip wall and the upper wall is an isothermal no-slip wall. ---*/ - su2double rho_0; /*!< \brief Constant density. */ - su2double u_0; /*!< \brief Maximum x-velocity in the domain. */ - su2double v_0; /*!< \brief Maximum y-velocity in the domain. */ - - su2double a_T1; /*!< \brief Parameter for the temperature solution. */ - su2double a_T2; /*!< \brief Parameter for the temperature solution. */ + su2double rho_0; /*!< \brief Constant density. */ + su2double u_0; /*!< \brief Maximum x-velocity in the domain. */ + su2double v_0; /*!< \brief Maximum y-velocity in the domain. */ -public: + su2double a_T1; /*!< \brief Parameter for the temperature solution. */ + su2double a_T2; /*!< \brief Parameter for the temperature solution. */ + public: /*! * \brief Constructor of the class. */ @@ -78,10 +74,8 @@ class CMMSNSUnitQuadSolutionWallBC final: public CVerificationSolution { * \param[in] val_iMesh - Multigrid level of the solver. * \param[in] config - Configuration of the particular problem. */ - CMMSNSUnitQuadSolutionWallBC(unsigned short val_nDim, - unsigned short val_nvar, - unsigned short val_iMesh, - CConfig* config); + CMMSNSUnitQuadSolutionWallBC(unsigned short val_nDim, unsigned short val_nvar, unsigned short val_iMesh, + CConfig* config); /*! * \brief Destructor of the class. @@ -94,9 +88,7 @@ class CMMSNSUnitQuadSolutionWallBC final: public CVerificationSolution { * \param[in] val_t - Current physical time. * \param[in] val_solution - Array where the exact solution is stored. */ - void GetSolution(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const override; + void GetSolution(const su2double* val_coords, const su2double val_t, su2double* val_solution) const override; /*! * \brief Get the boundary conditions state for an exact solution. @@ -104,9 +96,7 @@ class CMMSNSUnitQuadSolutionWallBC final: public CVerificationSolution { * \param[in] val_t - Current physical time. * \param[in] val_solution - Array where the exact solution is stored. */ - void GetBCState(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const override; + void GetBCState(const su2double* val_coords, const su2double val_t, su2double* val_solution) const override; /*! * \brief Get the source term for the manufactured solution (MMS). @@ -114,9 +104,7 @@ class CMMSNSUnitQuadSolutionWallBC final: public CVerificationSolution { * \param[in] val_t - Current physical time. * \param[in] val_solution - Array where the exact solution is stored. */ - void GetMMSSourceTerm(const su2double *val_coords, - const su2double val_t, - su2double *val_source) const override; + void GetMMSSourceTerm(const su2double* val_coords, const su2double val_t, su2double* val_source) const override; /*! * \brief Whether or not this verification solution is a manufactured solution. diff --git a/Common/include/toolboxes/MMS/CNSUnitQuadSolution.hpp b/Common/include/toolboxes/MMS/CNSUnitQuadSolution.hpp index 5bd57b60045..2d5bd8eac48 100644 --- a/Common/include/toolboxes/MMS/CNSUnitQuadSolution.hpp +++ b/Common/include/toolboxes/MMS/CNSUnitQuadSolution.hpp @@ -26,7 +26,6 @@ * License along with SU2. If not, see . */ - #pragma once #include @@ -38,17 +37,14 @@ on a unit quad, heat conduction is neglected. * \author E. van der Weide, T. Economon */ -class CNSUnitQuadSolution final: public CVerificationSolution { - -protected: - +class CNSUnitQuadSolution final : public CVerificationSolution { + protected: /*--- Variables that define the soltion. ---*/ - su2double Gm1; /*!< \brief Gamma minus 1 */ - su2double flowAngle; /*!< \brief Angle of the velocity vector in radians. */ - su2double Viscosity; /*!< \brief Viscosity, must be constant. */ - -public: + su2double Gm1; /*!< \brief Gamma minus 1 */ + su2double flowAngle; /*!< \brief Angle of the velocity vector in radians. */ + su2double Viscosity; /*!< \brief Viscosity, must be constant. */ + public: /*! * \brief Constructor of the class. */ @@ -61,10 +57,7 @@ class CNSUnitQuadSolution final: public CVerificationSolution { * \param[in] val_iMesh - Multigrid level of the solver. * \param[in] config - Configuration of the particular problem. */ - CNSUnitQuadSolution(unsigned short val_nDim, - unsigned short val_nvar, - unsigned short val_iMesh, - CConfig* config); + CNSUnitQuadSolution(unsigned short val_nDim, unsigned short val_nvar, unsigned short val_iMesh, CConfig* config); /*! * \brief Destructor of the class. @@ -77,9 +70,7 @@ class CNSUnitQuadSolution final: public CVerificationSolution { * \param[in] val_t - Current physical time. * \param[in] val_solution - Array where the exact solution is stored. */ - void GetSolution(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const override; + void GetSolution(const su2double* val_coords, const su2double val_t, su2double* val_solution) const override; /*! * \brief Get the boundary conditions state for an exact solution. @@ -87,7 +78,5 @@ class CNSUnitQuadSolution final: public CVerificationSolution { * \param[in] val_t - Current physical time. * \param[in] val_solution - Array where the exact solution is stored. */ - void GetBCState(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const override; + void GetBCState(const su2double* val_coords, const su2double val_t, su2double* val_solution) const override; }; diff --git a/Common/include/toolboxes/MMS/CRinglebSolution.hpp b/Common/include/toolboxes/MMS/CRinglebSolution.hpp index ff9a63fd62f..889b9729801 100644 --- a/Common/include/toolboxes/MMS/CRinglebSolution.hpp +++ b/Common/include/toolboxes/MMS/CRinglebSolution.hpp @@ -26,7 +26,6 @@ * License along with SU2. If not, see . */ - #pragma once #include @@ -37,18 +36,15 @@ * \brief Class to define the required data for the Ringleb flow. * \author E. van der Weide, T. Economon */ -class CRinglebSolution final: public CVerificationSolution { - -protected: - +class CRinglebSolution final : public CVerificationSolution { + protected: /*--- Variables involving gamma. ---*/ - su2double Gamma; /*!< \brief Gamma */ - su2double Gm1; /*!< \brief Gamma minus 1 */ - su2double tovGm1; /*!< \brief 2 over Gamma minus 1 */ - su2double tGamOvGm1; /*!< \brief 2 Gamma over Gamma minus 1 */ - -public: + su2double Gamma; /*!< \brief Gamma */ + su2double Gm1; /*!< \brief Gamma minus 1 */ + su2double tovGm1; /*!< \brief 2 over Gamma minus 1 */ + su2double tGamOvGm1; /*!< \brief 2 Gamma over Gamma minus 1 */ + public: /*! * \brief Constructor of the class. */ @@ -61,10 +57,7 @@ class CRinglebSolution final: public CVerificationSolution { * \param[in] val_iMesh - Multigrid level of the solver. * \param[in] config - Configuration of the particular problem. */ - CRinglebSolution(unsigned short val_nDim, - unsigned short val_nvar, - unsigned short val_iMesh, - CConfig* config); + CRinglebSolution(unsigned short val_nDim, unsigned short val_nvar, unsigned short val_iMesh, CConfig* config); /*! * \brief Destructor of the class. @@ -77,9 +70,7 @@ class CRinglebSolution final: public CVerificationSolution { * \param[in] val_t - Current physical time. * \param[in] val_solution - Array where the exact solution is stored. */ - void GetSolution(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const override; + void GetSolution(const su2double* val_coords, const su2double val_t, su2double* val_solution) const override; /*! * \brief Get the boundary conditions state for an exact solution. @@ -87,7 +78,5 @@ class CRinglebSolution final: public CVerificationSolution { * \param[in] val_t - Current physical time. * \param[in] val_solution - Array where the exact solution is stored. */ - void GetBCState(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const override; + void GetBCState(const su2double* val_coords, const su2double val_t, su2double* val_solution) const override; }; diff --git a/Common/include/toolboxes/MMS/CTGVSolution.hpp b/Common/include/toolboxes/MMS/CTGVSolution.hpp index de8537a8846..f40b22fe530 100644 --- a/Common/include/toolboxes/MMS/CTGVSolution.hpp +++ b/Common/include/toolboxes/MMS/CTGVSolution.hpp @@ -26,7 +26,6 @@ * License along with SU2. If not, see . */ - #pragma once #include @@ -37,20 +36,17 @@ * \brief Class to define the required data for the Taylor Green Vortex. * \author E. van der Weide, T. Economon */ -class CTGVSolution final: public CVerificationSolution { - -protected: - +class CTGVSolution final : public CVerificationSolution { + protected: /*--- TGV specific conditions. ---*/ - su2double tgvLength; /*!< \brief Taylor-Green length scale. */ - su2double tgvVelocity; /*!< \brief Taylor-Green velocity. */ - su2double tgvDensity; /*!< \brief Taylor-Green density. */ - su2double tgvPressure; /*!< \brief Taylor-Green pressure. */ - su2double ovGm1; /*!< \brief 1 over Gamma minus 1 */ - -public: + su2double tgvLength; /*!< \brief Taylor-Green length scale. */ + su2double tgvVelocity; /*!< \brief Taylor-Green velocity. */ + su2double tgvDensity; /*!< \brief Taylor-Green density. */ + su2double tgvPressure; /*!< \brief Taylor-Green pressure. */ + su2double ovGm1; /*!< \brief 1 over Gamma minus 1 */ + public: /*! * \brief Constructor of the class. */ @@ -63,10 +59,7 @@ class CTGVSolution final: public CVerificationSolution { * \param[in] val_iMesh - Multigrid level of the solver. * \param[in] config - Configuration of the particular problem. */ - CTGVSolution(unsigned short val_nDim, - unsigned short val_nvar, - unsigned short val_iMesh, - CConfig* config); + CTGVSolution(unsigned short val_nDim, unsigned short val_nvar, unsigned short val_iMesh, CConfig* config); /*! * \brief Destructor of the class. @@ -79,9 +72,7 @@ class CTGVSolution final: public CVerificationSolution { * \param[in] val_t - Current physical time. * \param[in] val_solution - Array where the exact solution is stored. */ - void GetSolution(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const override; + void GetSolution(const su2double* val_coords, const su2double val_t, su2double* val_solution) const override; /*! * \brief Whether or not the exact solution is known for this verification solution. diff --git a/Common/include/toolboxes/MMS/CUserDefinedSolution.hpp b/Common/include/toolboxes/MMS/CUserDefinedSolution.hpp index b6c2d1be6f5..d2b28861e0f 100644 --- a/Common/include/toolboxes/MMS/CUserDefinedSolution.hpp +++ b/Common/include/toolboxes/MMS/CUserDefinedSolution.hpp @@ -36,10 +36,8 @@ * \brief Class to define the required data for a user defined solution. * \author E. van der Weide, T. Economon */ -class CUserDefinedSolution final: public CVerificationSolution { - -public: - +class CUserDefinedSolution final : public CVerificationSolution { + public: /*! * \brief Constructor of the class. */ @@ -52,10 +50,7 @@ class CUserDefinedSolution final: public CVerificationSolution { * \param[in] val_iMesh - Multigrid level of the solver. * \param[in] config - Configuration of the particular problem. */ - CUserDefinedSolution(unsigned short val_nDim, - unsigned short val_nvar, - unsigned short val_iMesh, - CConfig* config); + CUserDefinedSolution(unsigned short val_nDim, unsigned short val_nvar, unsigned short val_iMesh, CConfig* config); /*! * \brief Destructor of the class. @@ -68,9 +63,7 @@ class CUserDefinedSolution final: public CVerificationSolution { * \param[in] val_t - Current physical time. * \param[in] val_solution - Array where the exact solution is stored. */ - void GetSolution(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const override; + void GetSolution(const su2double* val_coords, const su2double val_t, su2double* val_solution) const override; /*! * \brief Get the boundary conditions state for an exact solution. @@ -78,9 +71,7 @@ class CUserDefinedSolution final: public CVerificationSolution { * \param[in] val_t - Current physical time. * \param[in] val_solution - Array where the exact solution is stored. */ - void GetBCState(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const override; + void GetBCState(const su2double* val_coords, const su2double val_t, su2double* val_solution) const override; /*! * \brief Get the source term for the manufactured solution (MMS). @@ -88,9 +79,7 @@ class CUserDefinedSolution final: public CVerificationSolution { * \param[in] val_t - Current physical time. * \param[in] val_solution - Array where the exact solution is stored. */ - void GetMMSSourceTerm(const su2double *val_coords, - const su2double val_t, - su2double *val_source) const override; + void GetMMSSourceTerm(const su2double* val_coords, const su2double val_t, su2double* val_source) const override; /*! * \brief Whether or not this verification solution is a manufactured solution. diff --git a/Common/include/toolboxes/MMS/CVerificationSolution.hpp b/Common/include/toolboxes/MMS/CVerificationSolution.hpp index c3308307b37..0802409dbc4 100644 --- a/Common/include/toolboxes/MMS/CVerificationSolution.hpp +++ b/Common/include/toolboxes/MMS/CVerificationSolution.hpp @@ -38,25 +38,22 @@ * \author T. Economon, E. van der Weide */ class CVerificationSolution { + protected: + int rank; /*!< \brief MPI Rank. */ + int size; /*!< \brief MPI Size. */ -protected: - int rank; /*!< \brief MPI Rank. */ - int size; /*!< \brief MPI Size. */ + unsigned short nDim; /*!< \brief Number of dimension of the problem. */ + unsigned short nVar; /*!< \brief Number of variables of the problem */ - unsigned short nDim; /*!< \brief Number of dimension of the problem. */ - unsigned short nVar; /*!< \brief Number of variables of the problem */ + MAIN_SOLVER Kind_Solver; /*!< \brief The kind of solver we are running. */ - MAIN_SOLVER Kind_Solver; /*!< \brief The kind of solver we are running. */ - -private: - - su2double *Error_RMS; /*!< \brief Vector with the global RMS error for each variable in a verification case. */ - su2double *Error_Max; /*!< \brief Vector with the global max error for each variable in a verification case. */ - unsigned long *Error_Point_Max; /*!< \brief Global index for the node with the max error in a verification case. */ - su2double **Error_Point_Max_Coord; /*!< \brief Coordinates for the node with the max error in a verification case. */ - -public: + private: + su2double* Error_RMS; /*!< \brief Vector with the global RMS error for each variable in a verification case. */ + su2double* Error_Max; /*!< \brief Vector with the global max error for each variable in a verification case. */ + unsigned long* Error_Point_Max; /*!< \brief Global index for the node with the max error in a verification case. */ + su2double** Error_Point_Max_Coord; /*!< \brief Coordinates for the node with the max error in a verification case. */ + public: /*! * \brief Constructor of the class. */ @@ -69,10 +66,7 @@ class CVerificationSolution { * \param[in] val_iMesh - Multigrid level of the solver. * \param[in] config - Definition of the particular problem. */ - CVerificationSolution(unsigned short val_nDim, - unsigned short val_nvar, - unsigned short val_iMesh, - CConfig *config); + CVerificationSolution(unsigned short val_nDim, unsigned short val_nvar, unsigned short val_iMesh, CConfig* config); /*! * \brief Destructor of the class. @@ -85,17 +79,14 @@ class CVerificationSolution { * \param[in] val_t - Current physical time. * \param[in] val_solution - Array where the exact solution is stored. */ - virtual void GetSolution(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const; + virtual void GetSolution(const su2double* val_coords, const su2double val_t, su2double* val_solution) const; /*! * \brief Get the exact solution at the current position and t = 0. * \param[in] val_coords - Cartesian coordinates of the current position. * \param[in] val_solution - Array where the exact solution is stored. */ - void GetInitialCondition(const su2double *val_coords, - su2double *val_solution) const; + void GetInitialCondition(const su2double* val_coords, su2double* val_solution) const; /*! * \brief Get the boundary conditions state for an exact solution. @@ -103,9 +94,7 @@ class CVerificationSolution { * \param[in] val_t - Current physical time. * \param[in] val_solution - Array where the exact solution is stored. */ - virtual void GetBCState(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const; + virtual void GetBCState(const su2double* val_coords, const su2double val_t, su2double* val_solution) const; /*! * \brief Get the source term for the manufactured solution (MMS). @@ -113,9 +102,7 @@ class CVerificationSolution { * \param[in] val_t - Current physical time. * \param[in] val_solution - Array where the exact solution is stored. */ - virtual void GetMMSSourceTerm(const su2double *val_coords, - const su2double val_t, - su2double *val_source) const; + virtual void GetMMSSourceTerm(const su2double* val_coords, const su2double val_t, su2double* val_source) const; /*! * \brief Whether or not this verification solution is a manufactured solution. @@ -137,10 +124,8 @@ class CVerificationSolution { * \param[in] val_solution - Array where the exact solution is stored. * \param[out] val_error - Array where the local error is stored. */ - void GetLocalError(const su2double *val_coords, - const su2double val_t, - const su2double *GetLocalErrorval_solution, - su2double *val_error) const; + void GetLocalError(const su2double* val_coords, const su2double val_t, const su2double* GetLocalErrorval_solution, + su2double* val_error) const; /*! * \brief Set the global RMS error for verification cases. @@ -169,7 +154,7 @@ class CVerificationSolution { * \param[in] val_error - Value of the maximum error to store in the position val_var. */ void SetError_Max(unsigned short val_var, su2double val_error, unsigned long val_point) { - Error_Max[val_var] = val_error; + Error_Max[val_var] = val_error; Error_Point_Max[val_var] = val_point; } @@ -184,8 +169,7 @@ class CVerificationSolution { if (val_error > Error_Max[val_var]) { Error_Max[val_var] = val_error; Error_Point_Max[val_var] = val_point; - for (unsigned short iDim = 0; iDim < nDim; iDim++) - Error_Point_Max_Coord[val_var][iDim] = val_coord[iDim]; + for (unsigned short iDim = 0; iDim < nDim; iDim++) Error_Point_Max_Coord[val_var][iDim] = val_coord[iDim]; } } @@ -215,6 +199,5 @@ class CVerificationSolution { * \param[in] nDOFsGlobal - Global number of degrees of freedom for the current problem. * \param[in] config - Definition of the particular problem. */ - void SetVerificationError(unsigned long nDOFsGlobal, - CConfig *config); + void SetVerificationError(unsigned long nDOFsGlobal, CConfig* config); }; diff --git a/Common/include/toolboxes/allocation_toolbox.hpp b/Common/include/toolboxes/allocation_toolbox.hpp index ce02fd8f857..2b0adb1f31a 100644 --- a/Common/include/toolboxes/allocation_toolbox.hpp +++ b/Common/include/toolboxes/allocation_toolbox.hpp @@ -40,18 +40,11 @@ #include -namespace MemoryAllocation -{ +namespace MemoryAllocation { -inline constexpr bool is_power_of_two(size_t x) -{ - return x && !(x & (x-1)); -} +inline constexpr bool is_power_of_two(size_t x) { return x && !(x & (x - 1)); } -inline constexpr size_t round_up(size_t multiple, size_t x) -{ - return ((x+multiple-1)/multiple)*multiple; -} +inline constexpr size_t round_up(size_t multiple, size_t x) { return ((x + multiple - 1) / multiple) * multiple; } /*! * \brief Aligned memory allocation compatible across platforms. @@ -60,20 +53,18 @@ inline constexpr size_t round_up(size_t multiple, size_t x) * \tparam ZeroInit, initialize memory to 0. * \return Pointer to memory, always use su2::aligned_free to deallocate. */ -template -inline T* aligned_alloc(size_t alignment, size_t size) noexcept -{ +template +inline T* aligned_alloc(size_t alignment, size_t size) noexcept { assert(is_power_of_two(alignment)); - if(alignment < alignof(void*)) alignment = alignof(void*); + if (alignment < alignof(void*)) alignment = alignof(void*); size = round_up(alignment, size); void* ptr = nullptr; #if defined(__APPLE__) - if(::posix_memalign(&ptr, alignment, size) != 0) - { + if (::posix_memalign(&ptr, alignment, size) != 0) { ptr = nullptr; } #elif defined(_WIN32) @@ -89,9 +80,8 @@ inline T* aligned_alloc(size_t alignment, size_t size) noexcept * \brief Free memory allocated with su2::aligned_alloc. * \param[in] ptr, pointer to memory we want to release. */ -template -inline void aligned_free(T* ptr) noexcept -{ +template +inline void aligned_free(T* ptr) noexcept { #if defined(_WIN32) _aligned_free(ptr); #else @@ -99,5 +89,4 @@ inline void aligned_free(T* ptr) noexcept #endif } -} // namespace - +} // namespace MemoryAllocation diff --git a/Common/include/toolboxes/geometry_toolbox.hpp b/Common/include/toolboxes/geometry_toolbox.hpp index 430bc62a39d..8cb1d988df3 100644 --- a/Common/include/toolboxes/geometry_toolbox.hpp +++ b/Common/include/toolboxes/geometry_toolbox.hpp @@ -33,58 +33,58 @@ namespace GeometryToolbox { /// @{ /*! \return ||a-b||^2 */ -template +template inline T SquaredDistance(Int nDim, const T* a, const U* b) { T d(0); - for(Int i = 0; i < nDim; i++) d += pow(a[i]-b[i], 2); + for (Int i = 0; i < nDim; i++) d += pow(a[i] - b[i], 2); return d; } /*! \return ||a-b|| */ -template +template inline T Distance(Int nDim, const T* a, const U* b) { return sqrt(SquaredDistance(nDim, a, b)); } /*! \brief d = a-b */ -template +template inline void Distance(Int nDim, const T* a, const T* b, T* d) { - for(Int i = 0; i < nDim; i++) d[i] = a[i] - b[i]; + for (Int i = 0; i < nDim; i++) d[i] = a[i] - b[i]; } /*! \brief Reflect a at b: c = 2*b - a */ -template -inline void PointPointReflect(Int nDim, const T* a, const T* b, T* d){ - for(Int i = 0; i < nDim; i++) d[i] = 2 * b[i] - a[i]; +template +inline void PointPointReflect(Int nDim, const T* a, const T* b, T* d) { + for (Int i = 0; i < nDim; i++) d[i] = 2 * b[i] - a[i]; } /*! \return a.b */ -template +template inline T DotProduct(Int nDim, const T* a, const T* b) { T d(0); - for (Int i = 0; i < nDim; ++i) d += a[i]*b[i]; + for (Int i = 0; i < nDim; ++i) d += a[i] * b[i]; return d; } /*! \return ||a||^2 */ -template +template inline T SquaredNorm(Int nDim, const T* a) { return DotProduct(nDim, a, a); } /*! \return ||a|| */ -template +template inline T Norm(Int nDim, const T* a) { return sqrt(SquaredNorm(nDim, a)); } /*! \brief c = a x b */ -template +template inline void CrossProduct(const T* a, const T* b, T* c) { - c[0] = a[1]*b[2] - a[2]*b[1]; - c[1] = a[2]*b[0] - a[0]*b[2]; - c[2] = a[0]*b[1] - a[1]*b[0]; + c[0] = a[1] * b[2] - a[2] * b[1]; + c[1] = a[2] * b[0] - a[0] * b[2]; + c[2] = a[0] * b[1] - a[1] * b[0]; } /*! @@ -92,14 +92,13 @@ inline void CrossProduct(const T* a, const T* b, T* c) { * direction d intersects the plane defined by point p0 and normal n. * \return The intersection distance. */ -template +template inline T LinePlaneIntersection(const T* l0, const T* d, const T* p0, const T* n, T* c) { T dist[nDim] = {0.0}; Distance(nDim, p0, l0, dist); T alpha = DotProduct(nDim, dist, n) / DotProduct(nDim, d, n); - for (int iDim = 0; iDim < nDim; ++iDim) - c[iDim] = l0[iDim] + alpha * d[iDim]; - return fabs(alpha) * Norm(nDim,d); + for (int iDim = 0; iDim < nDim; ++iDim) c[iDim] = l0[iDim] + alpha * d[iDim]; + return fabs(alpha) * Norm(nDim, d); } /*! @@ -107,22 +106,21 @@ inline T LinePlaneIntersection(const T* l0, const T* d, const T* p0, const T* n, * by point p0 and normal n if projected perpendicular to it. * \return The normal distance. */ -template +template inline T PointPlaneProjection(const T* p1, const T* p0, const T* n, T* c) { - return LinePlaneIntersection(p1, n, p0, n, c); + return LinePlaneIntersection(p1, n, p0, n, c); } /*! \brief Set U as the normal to a 2D line defined by coords[iPoint][iDim]. */ -template +template inline void LineNormal(const T& coords, U* normal) { normal[0] = coords[0][1] - coords[1][1]; normal[1] = coords[1][0] - coords[0][0]; } /*! \brief Normal vector of a triangle, cross product of two sides. */ -template +template inline void TriangleNormal(const T& coords, U* normal) { - U a[3], b[3]; for (int iDim = 0; iDim < 3; iDim++) { @@ -131,13 +129,14 @@ inline void TriangleNormal(const T& coords, U* normal) { } CrossProduct(a, b, normal); - normal[0] *= 0.5; normal[1] *= 0.5; normal[2] *= 0.5; + normal[0] *= 0.5; + normal[1] *= 0.5; + normal[2] *= 0.5; } /*! \brief Normal vector of a quadrilateral, cross product of the two diagonals. */ -template +template inline void QuadrilateralNormal(const T& coords, U* normal) { - U a[3], b[3]; for (int iDim = 0; iDim < 3; iDim++) { @@ -146,48 +145,53 @@ inline void QuadrilateralNormal(const T& coords, U* normal) { } CrossProduct(a, b, normal); - normal[0] *= 0.5; normal[1] *= 0.5; normal[2] *= 0.5; + normal[0] *= 0.5; + normal[1] *= 0.5; + normal[2] *= 0.5; } /*! * \brief Compute a 3D rotation matrix. * \note The implicit ordering is rotation about the x, y, and then z axis. */ -template +template inline void RotationMatrix(Scalar theta, Scalar phi, Scalar psi, Matrix& mat) { + Scalar cosTheta = cos(theta); + Scalar cosPhi = cos(phi); + Scalar cosPsi = cos(psi); + Scalar sinTheta = sin(theta); + Scalar sinPhi = sin(phi); + Scalar sinPsi = sin(psi); - Scalar cosTheta = cos(theta); Scalar cosPhi = cos(phi); Scalar cosPsi = cos(psi); - Scalar sinTheta = sin(theta); Scalar sinPhi = sin(phi); Scalar sinPsi = sin(psi); - - mat[0][0] = cosPhi*cosPsi; - mat[1][0] = cosPhi*sinPsi; + mat[0][0] = cosPhi * cosPsi; + mat[1][0] = cosPhi * sinPsi; mat[2][0] = -sinPhi; - mat[0][1] = sinTheta*sinPhi*cosPsi - cosTheta*sinPsi; - mat[1][1] = sinTheta*sinPhi*sinPsi + cosTheta*cosPsi; - mat[2][1] = sinTheta*cosPhi; + mat[0][1] = sinTheta * sinPhi * cosPsi - cosTheta * sinPsi; + mat[1][1] = sinTheta * sinPhi * sinPsi + cosTheta * cosPsi; + mat[2][1] = sinTheta * cosPhi; - mat[0][2] = cosTheta*sinPhi*cosPsi + sinTheta*sinPsi; - mat[1][2] = cosTheta*sinPhi*sinPsi - sinTheta*cosPsi; - mat[2][2] = cosTheta*cosPhi; + mat[0][2] = cosTheta * sinPhi * cosPsi + sinTheta * sinPsi; + mat[1][2] = cosTheta * sinPhi * sinPsi - sinTheta * cosPsi; + mat[2][2] = cosTheta * cosPhi; } /*! \brief Compute a 2D rotation matrix. */ -template +template inline void RotationMatrix(Scalar psi, Matrix& mat) { - Scalar cosPsi = cos(psi); Scalar sinPsi = sin(psi); - mat[0][0] = cosPsi; mat[0][1] =-sinPsi; - mat[1][0] = sinPsi; mat[1][1] = cosPsi; + mat[0][0] = cosPsi; + mat[0][1] = -sinPsi; + mat[1][0] = sinPsi; + mat[1][1] = cosPsi; } /*! \brief Apply a rotation matrix (R) about origin (O) to a point at * distance (d) from it to obtain new coordinate (c). */ -template +template inline void Rotate(const Scalar R[][nDim], const Scalar* O, const Scalar* d, Scalar* c) { - for (int iDim = 0; iDim < nDim; ++iDim) { c[iDim] = O[iDim]; for (int k = 0; k < nDim; ++k) c[iDim] += R[iDim][k] * d[k]; @@ -195,16 +199,13 @@ inline void Rotate(const Scalar R[][nDim], const Scalar* O, const Scalar* d, Sca } /*! \brief Tangent projection */ -template +template inline void TangentProjection(Int nDim, const Mat& tensor, const Scalar* vector, Scalar* proj) { - - for (Int iDim = 0; iDim < nDim; iDim++) - proj[iDim] = DotProduct(nDim, tensor[iDim], vector); + for (Int iDim = 0; iDim < nDim; iDim++) proj[iDim] = DotProduct(nDim, tensor[iDim], vector); auto normalProj = DotProduct(nDim, proj, vector); - for (Int iDim = 0; iDim < nDim; iDim++) - proj[iDim] -= normalProj * vector[iDim]; + for (Int iDim = 0; iDim < nDim; iDim++) proj[iDim] -= normalProj * vector[iDim]; } /// @} -} +} // namespace GeometryToolbox diff --git a/Common/include/toolboxes/graph_toolbox.hpp b/Common/include/toolboxes/graph_toolbox.hpp index ef39ffaf80a..0a57ec21fd0 100644 --- a/Common/include/toolboxes/graph_toolbox.hpp +++ b/Common/include/toolboxes/graph_toolbox.hpp @@ -45,8 +45,7 @@ * \brief In FVM points are connected by the edges (faces) of the grid. * In FEM, two points are connected if they have an element in common. */ -enum class ConnectivityType {FiniteVolume=0, FiniteElement=1}; - +enum class ConnectivityType { FiniteVolume = 0, FiniteElement = 1 }; /*! * \class CCompressedSparsePattern @@ -55,17 +54,17 @@ enum class ConnectivityType {FiniteVolume=0, FiniteElement=1}; * If built for row-major storage the inner indices are column indices * and the pattern should be used as (row,icol), otherwise as (col,irow). */ -template +template class CCompressedSparsePattern { - static_assert(std::is_integral::value,""); + static_assert(std::is_integral::value, ""); -private: - su2vector m_outerPtr; /*!< \brief Start positions of the inner indices for each outer index. */ - su2vector m_innerIdx; /*!< \brief Inner indices of the non zero entries. */ - su2vector m_diagPtr; /*!< \brief Position of the diagonal entry. */ + private: + su2vector m_outerPtr; /*!< \brief Start positions of the inner indices for each outer index. */ + su2vector m_innerIdx; /*!< \brief Inner indices of the non zero entries. */ + su2vector m_diagPtr; /*!< \brief Position of the diagonal entry. */ su2vector m_innerIdxTransp; /*!< \brief Position of the transpose non zero entries, requires symmetry. */ -public: + public: using IndexType = Index_t; /*! @@ -74,9 +73,7 @@ class CCompressedSparsePattern { struct CInnerIter { const IndexType* const m_first = nullptr; const IndexType* const m_last = nullptr; - CInnerIter(const IndexType* first, const IndexType* last) : - m_first(first), m_last(last) { - } + CInnerIter(const IndexType* first, const IndexType* last) : m_first(first), m_last(last) {} const IndexType* begin() const { return m_first; } const IndexType* end() const { return m_last; } }; @@ -92,16 +89,14 @@ class CCompressedSparsePattern { * \param[in] outerPtrEnd - End of outer pointers. * \param[in] defaultInnerIdx - Default value for inner indices. */ - template - CCompressedSparsePattern(Iterator outerPtrBegin, Iterator outerPtrEnd, Index_t defaultInnerIdx) - { + template + CCompressedSparsePattern(Iterator outerPtrBegin, Iterator outerPtrEnd, Index_t defaultInnerIdx) { const auto size = outerPtrEnd - outerPtrBegin; m_outerPtr.resize(size); Index_t k = 0; - for(auto it = outerPtrBegin; it != outerPtrEnd; ++it) - m_outerPtr(k++) = *it; + for (auto it = outerPtrBegin; it != outerPtrEnd; ++it) m_outerPtr(k++) = *it; - m_innerIdx.resize(m_outerPtr(size-1)) = defaultInnerIdx; + m_innerIdx.resize(m_outerPtr(size - 1)) = defaultInnerIdx; } /*! @@ -110,12 +105,10 @@ class CCompressedSparsePattern { * \param[in] outerPtr - Outer index pointers. * \param[in] innerIdx - Inner indices. */ - CCompressedSparsePattern(su2vector&& outerPtr, - su2vector&& innerIdx) : - m_outerPtr(outerPtr), m_innerIdx(innerIdx) - { + CCompressedSparsePattern(su2vector&& outerPtr, su2vector&& innerIdx) + : m_outerPtr(outerPtr), m_innerIdx(innerIdx) { /*--- perform a basic sanity check ---*/ - assert(m_innerIdx.size() == m_outerPtr(m_outerPtr.size()-1)); + assert(m_innerIdx.size() == m_outerPtr(m_outerPtr.size() - 1)); } /*! @@ -124,51 +117,44 @@ class CCompressedSparsePattern { * \param[in] outerPtr - Outer index pointers. * \param[in] innerIdx - Inner indices. */ - template - CCompressedSparsePattern(const T& outerPtr, const T& innerIdx) - { + template + CCompressedSparsePattern(const T& outerPtr, const T& innerIdx) { m_outerPtr.resize(outerPtr.size()); - for(Index_t i=0; i >. */ - template - CCompressedSparsePattern(const T& lil) - { - m_outerPtr.resize(lil.size()+1); + template + CCompressedSparsePattern(const T& lil) { + m_outerPtr.resize(lil.size() + 1); m_outerPtr(0) = 0; - for(Index_t i=1; i < Index_t(m_outerPtr.size()); ++i) - m_outerPtr(i) = m_outerPtr(i-1) + lil[i-1].size(); + for (Index_t i = 1; i < Index_t(m_outerPtr.size()); ++i) m_outerPtr(i) = m_outerPtr(i - 1) + lil[i - 1].size(); m_innerIdx.resize(m_outerPtr(lil.size())); Index_t k = 0; - for(Index_t i=0; i < Index_t(lil.size()); ++i) - for(Index_t j=0; j < Index_t(lil[i].size()); ++j) - m_innerIdx(k++) = lil[i][j]; + for (Index_t i = 0; i < Index_t(lil.size()); ++i) + for (Index_t j = 0; j < Index_t(lil[i].size()); ++j) m_innerIdx(k++) = lil[i][j]; } /*! * \brief Build a list of pointers to the diagonal entries of the pattern. */ void buildDiagPtr() { - if(!m_diagPtr.empty()) return; + if (!m_diagPtr.empty()) return; m_diagPtr.resize(getOuterSize()); SU2_OMP_PARALLEL_(for schedule(static,roundUpDiv(getOuterSize(),omp_get_max_threads()))) - for(Index_t k = 0; k < getOuterSize(); ++k) - m_diagPtr(k) = findInnerIdx(k,k); + for (Index_t k = 0; k < getOuterSize(); ++k) m_diagPtr(k) = findInnerIdx(k, k); END_SU2_OMP_PARALLEL } @@ -176,15 +162,15 @@ class CCompressedSparsePattern { * \brief Build a list of pointers to the transpose entries of the pattern, requires symmetry. */ void buildTransposePtr() { - if(!m_innerIdxTransp.empty()) return; + if (!m_innerIdxTransp.empty()) return; m_innerIdxTransp.resize(getNumNonZeros()); SU2_OMP_PARALLEL_(for schedule(static,roundUpDiv(getOuterSize(),omp_get_max_threads()))) - for(Index_t i = 0; i < getOuterSize(); ++i) { - for(Index_t k = m_outerPtr(i); k < m_outerPtr(i+1); ++k) { + for (Index_t i = 0; i < getOuterSize(); ++i) { + for (Index_t k = m_outerPtr(i); k < m_outerPtr(i + 1); ++k) { auto j = m_innerIdx(k); - m_innerIdxTransp(k) = findInnerIdx(j,i); + m_innerIdxTransp(k) = findInnerIdx(j, i); assert(m_innerIdxTransp(k) != m_innerIdx.size() && "The pattern is not symmetric."); } } @@ -194,31 +180,23 @@ class CCompressedSparsePattern { /*! * \return True if the pattern is empty, i.e. has not been built yet. */ - inline bool empty() const { - return m_outerPtr.empty() || m_innerIdx.empty(); - } + inline bool empty() const { return m_outerPtr.empty() || m_innerIdx.empty(); } /*! * \return Number of rows/columns. */ - inline Index_t getOuterSize() const { - return m_outerPtr.size()-1; - } + inline Index_t getOuterSize() const { return m_outerPtr.size() - 1; } /*! * \return Number of non zero entries. */ - inline Index_t getNumNonZeros() const { - return m_innerIdx.size(); - } + inline Index_t getNumNonZeros() const { return m_innerIdx.size(); } /*! * \param[in] iOuterIdx - Outer index. * \return Number of inner indices associated with the outer index. */ - inline Index_t getNumNonZeros(Index_t iOuterIdx) const { - return m_outerPtr(iOuterIdx+1) - m_outerPtr(iOuterIdx); - } + inline Index_t getNumNonZeros(Index_t iOuterIdx) const { return m_outerPtr(iOuterIdx + 1) - m_outerPtr(iOuterIdx); } /*! * \param[in] iOuterIdx - Outer index. @@ -245,8 +223,7 @@ class CCompressedSparsePattern { * \return Iterator to inner dimension to use in range for loops. */ inline CInnerIter getInnerIter(Index_t iOuterIdx) const { - return CInnerIter(m_innerIdx.data()+m_outerPtr(iOuterIdx), - m_innerIdx.data()+m_outerPtr(iOuterIdx+1)); + return CInnerIter(m_innerIdx.data() + m_outerPtr(iOuterIdx), m_innerIdx.data() + m_outerPtr(iOuterIdx + 1)); } /*! @@ -256,8 +233,8 @@ class CCompressedSparsePattern { * or NNZ if position does not belong to the pattern. */ inline Index_t findInnerIdx(Index_t iOuterIdx, Index_t iInnerIdx) const { - for(Index_t k = m_outerPtr(iOuterIdx); k < m_outerPtr(iOuterIdx+1); ++k) - if(m_innerIdx(k) == iInnerIdx) return k; + for (Index_t k = m_outerPtr(iOuterIdx); k < m_outerPtr(iOuterIdx + 1); ++k) + if (m_innerIdx(k) == iInnerIdx) return k; return m_innerIdx.size(); } @@ -279,7 +256,7 @@ class CCompressedSparsePattern { inline Index_t quickFindInnerIdx(Index_t iOuterIdx, Index_t iInnerIdx) const { assert(isNonZero(iOuterIdx, iInnerIdx) && "Error, j does not belong to NZ(i)."); Index_t k = m_outerPtr(iOuterIdx); - while(m_innerIdx(k) != iInnerIdx) ++k; + while (m_innerIdx(k) != iInnerIdx) ++k; return k; } @@ -287,9 +264,7 @@ class CCompressedSparsePattern { * \param[in] iDiagIdx - Diagonal index (row == col). * \return Absolute position of the diagonal entry. */ - inline Index_t getDiagPtr(Index_t iDiagIdx) const { - return m_diagPtr(iDiagIdx); - } + inline Index_t getDiagPtr(Index_t iDiagIdx) const { return m_diagPtr(iDiagIdx); } /*! * \return Raw pointer to the outer pointer vector. @@ -336,8 +311,7 @@ class CCompressedSparsePattern { */ Index_t getMinInnerIdx() const { Index_t idx = std::numeric_limits::max(); - for(Index_t k=0; k::min(); - for(Index_t k=0; k +template using CEdgeToNonZeroMap = C2DContainer; - using CCompressedSparsePatternUL = CCompressedSparsePattern; using CCompressedSparsePatternL = CCompressedSparsePattern; using CEdgeToNonZeroMapUL = CEdgeToNonZeroMap; - /*! * \brief Build a sparse pattern from geometry information, of type FVM or FEM, * for a given fill-level. At fill-level N, the immediate neighbors of the @@ -379,19 +350,15 @@ using CEdgeToNonZeroMapUL = CEdgeToNonZeroMap; * \param[in] fillLvl - Target degree of neighborhood (immediate neighbors always added). * \return Compressed-Storage-Row sparse pattern. */ -template -CCompressedSparsePattern buildCSRPattern(Geometry_t& geometry, - ConnectivityType type, - Index_t fillLvl) -{ +template +CCompressedSparsePattern buildCSRPattern(Geometry_t& geometry, ConnectivityType type, Index_t fillLvl) { Index_t nPoint = geometry.GetnPoint(); - std::vector outerPtr(nPoint+1); + std::vector outerPtr(nPoint + 1); std::vector innerIdx; - innerIdx.reserve(nPoint); // at least this much space is needed + innerIdx.reserve(nPoint); // at least this much space is needed - for(Index_t iPoint = 0; iPoint < nPoint; ++iPoint) - { + for (Index_t iPoint = 0; iPoint < nPoint; ++iPoint) { /*--- Inner indices for iPoint start here. ---*/ outerPtr[iPoint] = innerIdx.size(); @@ -404,34 +371,28 @@ CCompressedSparsePattern buildCSRPattern(Geometry_t& geometry, /*--- Neighbors added in previous level. ---*/ std::set addedNeighbors(neighbors); - for(Index_t iLevel = 0; ; ++iLevel) - { + for (Index_t iLevel = 0;; ++iLevel) { /*--- New points added in this level. ---*/ std::set newNeighbors; /*--- For each point previously added, add its level 0 * neighbors, not duplicating any existing neighbor. ---*/ - for(auto jPoint : addedNeighbors) - { - if(type == ConnectivityType::FiniteVolume) - { + for (auto jPoint : addedNeighbors) { + if (type == ConnectivityType::FiniteVolume) { /*--- For FVM we know the neighbors of point j directly. ---*/ - for(Index_t kPoint : geometry.nodes->GetPoints(jPoint)) - if(neighbors.count(kPoint) == 0) // no duplication + for (Index_t kPoint : geometry.nodes->GetPoints(jPoint)) + if (neighbors.count(kPoint) == 0) // no duplication newNeighbors.insert(kPoint); - } - else // FiniteElement + } else // FiniteElement { /*--- For FEM we need the nodes of all elements that contain point j. ---*/ - for(auto iElem : geometry.nodes->GetElems(jPoint)) - { + for (auto iElem : geometry.nodes->GetElems(jPoint)) { auto elem = geometry.elem[iElem]; - for(unsigned short iNode = 0; iNode < elem->GetnNodes(); ++iNode) - { + for (unsigned short iNode = 0; iNode < elem->GetnNodes(); ++iNode) { Index_t kPoint = elem->GetNode(iNode); - if(neighbors.count(kPoint) == 0) // no duplication + if (neighbors.count(kPoint) == 0) // no duplication newNeighbors.insert(kPoint); } } @@ -440,7 +401,7 @@ CCompressedSparsePattern buildCSRPattern(Geometry_t& geometry, neighbors.insert(newNeighbors.begin(), newNeighbors.end()); - if(iLevel >= fillLvl) break; + if (iLevel >= fillLvl) break; /*--- For the next level we get the neighbours of the new points. ---*/ addedNeighbors = newNeighbors; @@ -455,7 +416,6 @@ CCompressedSparsePattern buildCSRPattern(Geometry_t& geometry, return CCompressedSparsePattern(outerPtr, innerIdx); } - /*! * \brief Build a lookup table of the absolute positions of the non zero entries * of a compressed sparse pattern, accessed when visiting the FVM edges @@ -465,27 +425,24 @@ CCompressedSparsePattern buildCSRPattern(Geometry_t& geometry, * \param[in] pattern - Sparse pattern. * \return nEdge by 2 matrix. */ -template +template CEdgeToNonZeroMap mapEdgesToSparsePattern(Geometry_t& geometry, - const CCompressedSparsePattern& pattern) -{ + const CCompressedSparsePattern& pattern) { assert(!pattern.empty()); - CEdgeToNonZeroMap edgeMap(geometry.GetnEdge(),2); + CEdgeToNonZeroMap edgeMap(geometry.GetnEdge(), 2); - for(Index_t iEdge = 0; iEdge < geometry.GetnEdge(); ++iEdge) - { - Index_t iPoint = geometry.edges->GetNode(iEdge,0); - Index_t jPoint = geometry.edges->GetNode(iEdge,1); + for (Index_t iEdge = 0; iEdge < geometry.GetnEdge(); ++iEdge) { + Index_t iPoint = geometry.edges->GetNode(iEdge, 0); + Index_t jPoint = geometry.edges->GetNode(iEdge, 1); - edgeMap(iEdge,0) = pattern.quickFindInnerIdx(iPoint,jPoint); - edgeMap(iEdge,1) = pattern.quickFindInnerIdx(jPoint,iPoint); + edgeMap(iEdge, 0) = pattern.quickFindInnerIdx(iPoint, jPoint); + edgeMap(iEdge, 1) = pattern.quickFindInnerIdx(jPoint, iPoint); } return edgeMap; } - /*! * \brief Create the natural coloring (equivalent to the normal sequential loop * order) for a given number of inner indexes. @@ -493,10 +450,8 @@ CEdgeToNonZeroMap mapEdgesToSparsePattern(Geometry_t& geometry, * \param[in] numInnerIndexes - Number of indexes that are to be colored. * \return Natural (sequential) coloring of the inner indices. */ -template -T createNaturalColoring(Index_t numInnerIndexes) -{ +template +T createNaturalColoring(Index_t numInnerIndexes) { /*--- One color. ---*/ su2vector outerPtr(2); outerPtr(0) = 0; @@ -504,12 +459,11 @@ T createNaturalColoring(Index_t numInnerIndexes) /*--- Containing all indexes in ascending order. ---*/ su2vector innerIdx(numInnerIndexes); - std::iota(innerIdx.data(), innerIdx.data()+numInnerIndexes, 0); + std::iota(innerIdx.data(), innerIdx.data() + numInnerIndexes, 0); return T(std::move(outerPtr), std::move(innerIdx)); } - /*! * \brief Color contiguous groups of outer indices of a sparse pattern such that * within each color, any two groups do not have inner indices in common. @@ -530,12 +484,11 @@ T createNaturalColoring(Index_t numInnerIndexes) * \param[out] indexColor - Optional, vector with colors given to the outer indices. * \return Coloring in the same type of the input pattern. */ -template +template T colorSparsePattern(const T& pattern, size_t groupSize = 1, bool balanceColors = false, - std::vector* indexColor = nullptr) -{ - static_assert(std::is_integral::value,""); - static_assert(std::numeric_limits::max() >= MaxColors,""); + std::vector* indexColor = nullptr) { + static_assert(std::is_integral::value, ""); + static_assert(std::numeric_limits::max() >= MaxColors, ""); using Index_t = typename T::IndexType; @@ -543,171 +496,161 @@ T colorSparsePattern(const T& pattern, size_t groupSize = 1, bool balanceColors const Index_t nOuter = pattern.getOuterSize(); /*--- Trivial case. ---*/ - if(groupSize >= nOuter) return createNaturalColoring(nOuter); + if (groupSize >= nOuter) return createNaturalColoring(nOuter); const Index_t minIdx = pattern.getMinInnerIdx(); - const Index_t nInner = pattern.getMaxInnerIdx()+1-minIdx; + const Index_t nInner = pattern.getMaxInnerIdx() + 1 - minIdx; /*--- Check the max memory condition (<< 23 is to count bits). ---*/ - if(size_t(nInner) > (MaxMB << 23)) return T(); + if (size_t(nInner) > (MaxMB << 23)) return T(); /*--- Vector with the color given to each outer index. ---*/ std::vector idxColor(nOuter); /*--- Start with one color, with no indices assigned. ---*/ - std::vector colorSize(1,0); + std::vector colorSize(1, 0); Color_t nColor = 1; { - /*--- For each color keep track of the inner indices that are in it. ---*/ - std::vector > innerInColor; - innerInColor.emplace_back(nInner, false); + /*--- For each color keep track of the inner indices that are in it. ---*/ + std::vector > innerInColor; + innerInColor.emplace_back(nInner, false); - /*--- Order in which we look for space in the colors to insert a new group. ---*/ - std::vector searchOrder(MaxColors); + /*--- Order in which we look for space in the colors to insert a new group. ---*/ + std::vector searchOrder(MaxColors); - auto outerPtr = pattern.outerPtr(); - auto innerIdx = pattern.innerIdx(); + auto outerPtr = pattern.outerPtr(); + auto innerIdx = pattern.innerIdx(); - for(Index_t iOuter = 0; iOuter < nOuter; iOuter += grpSz) - { - Index_t grpEnd = std::min(iOuter+grpSz, nOuter); + for (Index_t iOuter = 0; iOuter < nOuter; iOuter += grpSz) { + Index_t grpEnd = std::min(iOuter + grpSz, nOuter); - searchOrder.resize(nColor); - std::iota(searchOrder.begin(), searchOrder.end(), 0); + searchOrder.resize(nColor); + std::iota(searchOrder.begin(), searchOrder.end(), 0); - /*--- Balance sizes by looking for space in smaller colors first. ---*/ - if(balanceColors) { - std::sort(searchOrder.begin(), searchOrder.end(), - [&colorSize](Color_t a, Color_t b){return colorSize[a] < colorSize[b];}); - } + /*--- Balance sizes by looking for space in smaller colors first. ---*/ + if (balanceColors) { + std::sort(searchOrder.begin(), searchOrder.end(), + [&colorSize](Color_t a, Color_t b) { return colorSize[a] < colorSize[b]; }); + } - auto it = searchOrder.begin(); + auto it = searchOrder.begin(); - for(; it != searchOrder.end(); ++it) - { - bool free = true; - /*--- Traverse entire group as a large outer index. ---*/ - for(Index_t k = outerPtr[iOuter]; k < outerPtr[grpEnd] && free; ++k) - { - free = !innerInColor[*it][innerIdx[k]-minIdx]; + for (; it != searchOrder.end(); ++it) { + bool free = true; + /*--- Traverse entire group as a large outer index. ---*/ + for (Index_t k = outerPtr[iOuter]; k < outerPtr[grpEnd] && free; ++k) { + free = !innerInColor[*it][innerIdx[k] - minIdx]; + } + /*--- If none of the inner indices in the group appears in + * this color yet, it is assigned to the group. ---*/ + if (free) break; } - /*--- If none of the inner indices in the group appears in - * this color yet, it is assigned to the group. ---*/ - if(free) break; - } - Color_t color; + Color_t color; + + if (it != searchOrder.end()) { + /*--- Found a free color. ---*/ + color = *it; + } else { + /*--- No color was free, make space for a new one. ---*/ + color = nColor++; + if (nColor == MaxColors) return T(); + colorSize.push_back(0); + innerInColor.emplace_back(nInner, false); + } - if(it != searchOrder.end()) - { - /*--- Found a free color. ---*/ - color = *it; - } - else { - /*--- No color was free, make space for a new one. ---*/ - color = nColor++; - if(nColor == MaxColors) return T(); - colorSize.push_back(0); - innerInColor.emplace_back(nInner, false); - } + /*--- Assign color to group. ---*/ + for (Index_t k = iOuter; k < grpEnd; ++k) idxColor[k] = color; - /*--- Assign color to group. ---*/ - for(Index_t k = iOuter; k < grpEnd; ++k) idxColor[k] = color; + /*--- Mark the inner indices of the group as belonging to the color. ---*/ + for (Index_t k = outerPtr[iOuter]; k < outerPtr[grpEnd]; ++k) { + innerInColor[color][innerIdx[k] - minIdx] = true; + } - /*--- Mark the inner indices of the group as belonging to the color. ---*/ - for(Index_t k = outerPtr[iOuter]; k < outerPtr[grpEnd]; ++k) - { - innerInColor[color][innerIdx[k]-minIdx] = true; + /*--- Update count for the assigned color. ---*/ + colorSize[color] += grpEnd - iOuter; } - - /*--- Update count for the assigned color. ---*/ - colorSize[color] += grpEnd - iOuter; - } - } // matrix of bools goes out of scope - + } // matrix of bools goes out of scope /*--- Compress the coloring information. ---*/ - su2vector colorPtr(nColor+1); colorPtr(0) = 0; + su2vector colorPtr(nColor + 1); + colorPtr(0) = 0; su2vector outerIdx(nOuter); Index_t k = 0; - for(Color_t color = 0; color < nColor; ++color) - { - colorPtr(color+1) = colorPtr(color)+colorSize[color]; + for (Color_t color = 0; color < nColor; ++color) { + colorPtr(color + 1) = colorPtr(color) + colorSize[color]; - for(Index_t iOuter = 0; iOuter < nOuter; ++iOuter) - if(idxColor[iOuter] == color) - outerIdx(k++) = iOuter; + for (Index_t iOuter = 0; iOuter < nOuter; ++iOuter) + if (idxColor[iOuter] == color) outerIdx(k++) = iOuter; } /*--- Optional return of the direct color information. ---*/ - if(indexColor) *indexColor = std::move(idxColor); + if (indexColor) *indexColor = std::move(idxColor); /*--- Move compressed coloring into result pattern instance. ---*/ return T(std::move(colorPtr), std::move(outerIdx)); } - /*! * \brief A way to represent one grid color that allows range-for syntax. */ -template -struct GridColor -{ - static_assert(std::is_integral::value,""); +template +struct GridColor { + static_assert(std::is_integral::value, ""); const T size; T groupSize; const T* const indices; - GridColor(const T* idx = nullptr, T sz = 0, T grp = 0) : - size(sz), groupSize(grp), indices(idx) { } + GridColor(const T* idx = nullptr, T sz = 0, T grp = 0) : size(sz), groupSize(grp), indices(idx) {} - inline const T* begin() const {return indices;} - inline const T* end() const {return indices+size;} + inline const T* begin() const { return indices; } + inline const T* end() const { return indices + size; } }; - /*! * \brief A way to represent natural coloring {0,1,2,...,size-1} with zero * overhead (behaves like looping with an integer index, after optimization...). */ -template -struct DummyGridColor -{ - static_assert(std::is_integral::value,""); +template +struct DummyGridColor { + static_assert(std::is_integral::value, ""); T size; struct { - inline T operator[] (T i) const {return i;} - } - indices; + inline T operator[](T i) const { return i; } + } indices; - DummyGridColor(T sz = 0) : size(sz) { } + DummyGridColor(T sz = 0) : size(sz) {} struct IteratorLikeInt { T i; inline IteratorLikeInt(T pos = 0) : i(pos) {} - inline IteratorLikeInt& operator++ () {++i; return *this;} - inline IteratorLikeInt operator++ (int) {auto j=i++; return IteratorLikeInt(j);} - inline T operator* () const {return i;} - inline T operator-> () const {return i;} - inline bool operator==(const IteratorLikeInt& other) const {return i==other.i;} - inline bool operator!=(const IteratorLikeInt& other) const {return i!=other.i;} + inline IteratorLikeInt& operator++() { + ++i; + return *this; + } + inline IteratorLikeInt operator++(int) { + auto j = i++; + return IteratorLikeInt(j); + } + inline T operator*() const { return i; } + inline T operator->() const { return i; } + inline bool operator==(const IteratorLikeInt& other) const { return i == other.i; } + inline bool operator!=(const IteratorLikeInt& other) const { return i != other.i; } }; - inline IteratorLikeInt begin() const {return IteratorLikeInt(0);} - inline IteratorLikeInt end() const {return IteratorLikeInt(size);} + inline IteratorLikeInt begin() const { return IteratorLikeInt(0); } + inline IteratorLikeInt end() const { return IteratorLikeInt(size); } }; - /*! * \brief Computes the efficiency of a grid coloring for given number of threads and chunk size. */ -template -su2double coloringEfficiency(const SparsePattern& coloring, int numThreads, int chunkSize) -{ +template +su2double coloringEfficiency(const SparsePattern& coloring, int numThreads, int chunkSize) { using Index_t = typename SparsePattern::IndexType; /*--- Ideally compute time is proportional to total work over number of threads. ---*/ @@ -715,10 +658,10 @@ su2double coloringEfficiency(const SparsePattern& coloring, int numThreads, int /*--- In practice the total work is quantized first by colors and then by chunks. ---*/ Index_t real = 0; - for(Index_t color = 0; color < coloring.getOuterSize(); ++color) + for (Index_t color = 0; color < coloring.getOuterSize(); ++color) real += chunkSize * roundUpDiv(roundUpDiv(coloring.getNumNonZeros(color), chunkSize), numThreads); return ideal / real; } -/// @} \ No newline at end of file +/// @} diff --git a/Common/include/toolboxes/ndflattener.hpp b/Common/include/toolboxes/ndflattener.hpp index d6c3f5c28e4..6e9a616a0e2 100644 --- a/Common/include/toolboxes/ndflattener.hpp +++ b/Common/include/toolboxes/ndflattener.hpp @@ -212,8 +212,9 @@ class NdFlattener; * Introducing this was necessary because MPICH's Allgatherv behaved unexpectedly if there * is only one MPI rank (seemingly ignoring displs[0] != 0). */ -static inline void SU2_MPI_Allgatherv_safe(const void* sendbuf, int sendcount, SU2_MPI::Datatype sendtype, void* recvbuf, - const int* recvcounts, const int* displs, SU2_MPI::Datatype recvtype, SU2_MPI::Comm comm) { +static inline void SU2_MPI_Allgatherv_safe(const void* sendbuf, int sendcount, SU2_MPI::Datatype sendtype, + void* recvbuf, const int* recvcounts, const int* displs, + SU2_MPI::Datatype recvtype, SU2_MPI::Comm comm) { if (SU2_MPI::GetSize() == 1) { SU2_MPI::CopyData(sendbuf, recvbuf, sendcount, sendtype, displs[0]); } else { @@ -242,8 +243,7 @@ struct Nd_MPI_Environment { const int rank; const int size; - Nd_MPI_Environment(MPI_Datatype_t mpi_data = MPI_DOUBLE, - MPI_Datatype_t mpi_index = MPI_UNSIGNED_LONG, + Nd_MPI_Environment(MPI_Datatype_t mpi_data = MPI_DOUBLE, MPI_Datatype_t mpi_index = MPI_UNSIGNED_LONG, MPI_Communicator_t comm = SU2_MPI::GetComm(), MPI_Allgather_t MPI_Allgather_fun = &(SU2_MPI::Allgather), MPI_Allgatherv_t MPI_Allgatherv_fun = &(SU2_MPI_Allgatherv_safe)) @@ -311,19 +311,15 @@ class IndexAccumulator : public IndexAccumulator_Base { /*! The Base of NdFlattener is NdFlattener, but do also preserve constness. */ - using Nd_Base_t = su2conditional_t< - std::is_const::value, - const typename Nd_t::Base, - typename Nd_t::Base - >; + using Nd_Base_t = su2conditional_t::value, const typename Nd_t::Base, typename Nd_t::Base>; /*! Return type of operator[]. */ using LookupType = IndexAccumulator; /*! Return type of operator[] const. */ using LookupType_const = IndexAccumulator; + using Base::CheckBound; using Base::nd; using Base::offset; using Base::size; - using Base::CheckBound; /*! \brief Read one more index, checking whether it is in the range dictated by the NdFlattener and * previous indices. Non-const version. @@ -359,16 +355,12 @@ class IndexAccumulator<1, Nd_t_, Check> : public IndexAccumulator_Base<1, Nd_t_, /*! Return type of operator[]. * \details Data type of NdFlattener, but do also preserve constness. */ - using LookupType = su2conditional_t< - std::is_const::value, - const typename Nd_t::Data_t, - typename Nd_t::Data_t - >; + using LookupType = su2conditional_t::value, const typename Nd_t::Data_t, typename Nd_t::Data_t>; using LookupType_const = const typename Nd_t::Data_t; + using Base::CheckBound; using Base::nd; using Base::offset; using Base::size; - using Base::CheckBound; /*! \brief Return (possibly const) reference to the corresponding data element, checking if the index is in its range. * Non-const version. @@ -672,7 +664,7 @@ class NdFlattener : public NdFlattener { void set_g(Nd_MPI_Environment const& mpi_env, su2matrix const& Nodes_all, CurrentLayer const& local_version) { std::vector Nodes_all_K_as_int(mpi_env.size); - std::vector Nodes_all_k_cumulated( mpi_env.size + 1); + std::vector Nodes_all_k_cumulated(mpi_env.size + 1); //< [r] is the number of nodes in the current layer, summed over all processes with rank below r, **plus one**. // Used as displacements in Allgatherv, as we do not want to transfer the initial zeros, but we want to transfer the // last element of indices, which is the local nNodes of the layer below. Note that MPI needs indices of type 'int'. diff --git a/Common/include/toolboxes/printing_toolbox.hpp b/Common/include/toolboxes/printing_toolbox.hpp index 7461f0465de..58c66ad4fd5 100644 --- a/Common/include/toolboxes/printing_toolbox.hpp +++ b/Common/include/toolboxes/printing_toolbox.hpp @@ -68,15 +68,11 @@ namespace PrintingToolbox { * * \author T. Albring */ -class CTablePrinter{ -public: - CTablePrinter(std::ostream * output, const std::string & separator = "|"); +class CTablePrinter { + public: + CTablePrinter(std::ostream* output, const std::string& separator = "|"); - enum alignment { - CENTER, - LEFT, - RIGHT - }; + enum alignment { CENTER, LEFT, RIGHT }; /*! * \brief Get number of columns of the table @@ -94,13 +90,13 @@ class CTablePrinter{ * \brief Set the separator between columns (outer decoration) * \param[in] separator - The separation character. */ - void SetSeparator(const std::string & separator); + void SetSeparator(const std::string& separator); /*! * \brief Set the separator between columns (inner decoration) * \param[in] separator - The separation character. */ - void SetInnerSeparator(const std::string & inner_separator); + void SetInnerSeparator(const std::string& inner_separator); /*! * \brief Set the alignment of the table entries (CENTER only works for the header at the moment). @@ -120,13 +116,12 @@ class CTablePrinter{ */ void SetPrintHeaderTopLine(bool print); - /*! * \brief Add a column to the table by specifiying the header name and the width. * \param[in] header_name - The name printed in the header. * \param[in] column_width - The width of the column. */ - void AddColumn(const std::string & header_name, int column_width); + void AddColumn(const std::string& header_name, int column_width); /*! * \brief Print the header. @@ -143,160 +138,152 @@ class CTablePrinter{ */ void SetPrecision(int precision); - template CTablePrinter& operator<<(T input){ - + template + CTablePrinter& operator<<(T input) { int indent = 0; /* --- Set the left separator --- */ - if (j_ == 0) - *out_stream_ << separator_; + if (j_ == 0) *out_stream_ << separator_; /* --- Determine and set the current alignment in the stream --- */ - if(align_ == LEFT) + if (align_ == LEFT) *out_stream_ << std::left; else if (align_ == RIGHT || align_ == CENTER) *out_stream_ << std::right; /*--- Print the current column value to the stream --- */ - *out_stream_ << std::setw(column_widths_.at(j_) - indent) - << std::setprecision(precision_) << input; + *out_stream_ << std::setw(column_widths_.at(j_) - indent) << std::setprecision(precision_) << input; /*--- Reset the column counter and if it is the last column, * add also a line break ---*/ - if (j_ == GetNumColumns()-1){ - *out_stream_ << std::setw(indent+1+(int)separator_.size()) << separator_ + "\n"; + if (j_ == GetNumColumns() - 1) { + *out_stream_ << std::setw(indent + 1 + (int)separator_.size()) << separator_ + "\n"; i_ = i_ + 1; j_ = 0; } else { - *out_stream_ << std::setw(indent+(int)inner_separator_.size()) << inner_separator_; + *out_stream_ << std::setw(indent + (int)inner_separator_.size()) << inner_separator_; j_ = j_ + 1; } return *this; } -private: - + private: /*! * \brief Print a horizontal line. */ void PrintHorizontalLine(); - std::ostream * out_stream_; /*< \brief The output stream. */ + std::ostream* out_stream_; /*< \brief The output stream. */ std::vector column_headers_; /*< \brief Vector of column header names. */ std::vector column_widths_; /*< \brief Vector of column widths. */ std::string separator_; /*< \brief Column separator char. */ std::string inner_separator_; /*< \brief Inner column separator char. */ - int precision_; /*< \brief Floating point precision */ + int precision_; /*< \brief Floating point precision */ int i_; /*< \brief Index of the current row. */ int j_; /*< \brief Index of the current column. */ - int table_width_; /*< \brief The total width of the table. */ - int align_; /*< \brief The current alignment. */ - bool print_header_top_line_, /*< \brief Printing the header top line. */ - print_header_bottom_line_; /*< \brief Printing the header bottom line. */ + int table_width_; /*< \brief The total width of the table. */ + int align_; /*< \brief The current alignment. */ + bool print_header_top_line_, /*< \brief Printing the header top line. */ + print_header_bottom_line_; /*< \brief Printing the header bottom line. */ }; - - -inline void PrintScreenFixed(std::ostream &stream, su2double val, unsigned short field_width) { - stream.precision(6); stream.setf(std::ios::fixed, std::ios::floatfield); stream.width(field_width); +inline void PrintScreenFixed(std::ostream& stream, su2double val, unsigned short field_width) { + stream.precision(6); + stream.setf(std::ios::fixed, std::ios::floatfield); + stream.width(field_width); stream << std::right << val; stream.unsetf(std::ios::fixed); } -inline void PrintScreenScientific(std::ostream &stream, su2double val, unsigned short field_width) { - stream.precision(4); stream.setf(std::ios::scientific, std::ios::floatfield); stream.width(field_width); +inline void PrintScreenScientific(std::ostream& stream, su2double val, unsigned short field_width) { + stream.precision(4); + stream.setf(std::ios::scientific, std::ios::floatfield); + stream.width(field_width); stream << std::right << val; stream.unsetf(std::ios::scientific); } -inline void PrintScreenInteger(std::ostream &stream, unsigned long val, unsigned short field_width){ +inline void PrintScreenInteger(std::ostream& stream, unsigned long val, unsigned short field_width) { stream.width(field_width); stream << std::right << val; } -inline void PrintScreenPercent(std::ostream &stream, su2double val, unsigned short field_width){ - stream.precision(2); stream.setf(std::ios::fixed, std::ios::floatfield); stream.width(field_width-1); +inline void PrintScreenPercent(std::ostream& stream, su2double val, unsigned short field_width) { + stream.precision(2); + stream.setf(std::ios::fixed, std::ios::floatfield); + stream.width(field_width - 1); stream << std::right << val << "%"; stream.unsetf(std::ios::fixed); } - -inline std::vector split(const std::string& s, char delimiter) -{ +inline std::vector split(const std::string& s, char delimiter) { std::vector tokens; std::string token; std::istringstream tokenStream(s); - while (std::getline(tokenStream, token, delimiter)) - { + while (std::getline(tokenStream, token, delimiter)) { tokens.push_back(token); } return tokens; } -inline int stoi(const std::string s){ +inline int stoi(const std::string s) { std::istringstream ss(s); int number; ss >> number; return number; } -inline su2double stod(const std::string s){ +inline su2double stod(const std::string s) { std::istringstream ss(s); su2double number; ss >> number; return number; } -inline std::string to_string(const su2double number){ - +inline std::string to_string(const su2double number) { std::stringstream ss; ss << number; return ss.str(); - } const static char* ws = " \t\n\r\f\v"; // trim from end of string (right) -inline std::string& rtrim(std::string& s, const char* t = ws){ +inline std::string& rtrim(std::string& s, const char* t = ws) { s.erase(s.find_last_not_of(t) + 1); return s; } // trim from beginning of string (left) -inline std::string& ltrim(std::string& s, const char* t = ws){ +inline std::string& ltrim(std::string& s, const char* t = ws) { s.erase(0, s.find_first_not_of(t)); return s; } // trim from both ends of string (right then left) -inline std::string& trim(std::string& s, const char* t = ws){ - return ltrim(rtrim(s, t), t); -} +inline std::string& trim(std::string& s, const char* t = ws) { return ltrim(rtrim(s, t), t); } /*! * \brief utility function for converting strings to uppercase * \param[in,out] str - string we want to convert */ -inline void StringToUpperCase(std::string & str) { - std::transform(str.begin(), str.end(), str.begin(), ::toupper); -} +inline void StringToUpperCase(std::string& str) { std::transform(str.begin(), str.end(), str.begin(), ::toupper); } /*! * \brief utility function for converting strings to uppercase * \param[in] str - string we want a copy of converted to uppercase * \return a copy of str in uppercase */ -inline std::string StringToUpperCase(const std::string & str) { +inline std::string StringToUpperCase(const std::string& str) { std::string upp_str(str); std::transform(upp_str.begin(), upp_str.end(), upp_str.begin(), ::toupper); return upp_str; } -} +} // namespace PrintingToolbox diff --git a/Common/include/wall_model.hpp b/Common/include/wall_model.hpp index 6369c970b11..b80f9dfcedd 100644 --- a/Common/include/wall_model.hpp +++ b/Common/include/wall_model.hpp @@ -45,14 +45,12 @@ class CFluidModel; * \version 7.5.1 "Blackbird" */ class CWallModel { - -public: - + public: /*! * \brief Constructor of the class. * \param[in] config - Definition of the particular problem. */ - CWallModel(CConfig *config); + CWallModel(CConfig* config); /*! * \brief Destructor of the class. @@ -77,27 +75,20 @@ class CWallModel { * \param[out] OverCvWall - Thermal conductivity divided by Cv at the wall, to be computed. */ - virtual void WallShearStressAndHeatFlux(const su2double tExchange, - const su2double velExchange, - const su2double muExchange, - const su2double pExchange, - const su2double Wall_HeatFlux, - const bool HeatFlux_Prescribed, - const su2double TWall, - const bool Temperature_Prescribed, - CFluidModel *FluidModel, - su2double &tauWall, - su2double &qWall, - su2double &ViscosityWall, - su2double &kOverCvWall); -protected: - + virtual void WallShearStressAndHeatFlux(const su2double tExchange, const su2double velExchange, + const su2double muExchange, const su2double pExchange, + const su2double Wall_HeatFlux, const bool HeatFlux_Prescribed, + const su2double TWall, const bool Temperature_Prescribed, + CFluidModel* FluidModel, su2double& tauWall, su2double& qWall, + su2double& ViscosityWall, su2double& kOverCvWall); + + protected: su2double h_wm; /*!< \brief The thickness of the wall model. This is also basically the exchange location */ su2double Pr_lam; /*!< \brief Laminar Prandtl number. */ su2double Pr_turb; /*!< \brief Turbulent Prandtl number. */ su2double karman; /*!< \brief von Karman constant. */ -private: + private: /*! * \brief Default constructor of the class, disabled. */ @@ -105,17 +96,14 @@ class CWallModel { }; class CWallModel1DEQ : public CWallModel { - -public: - + public: /*! * \brief Constructor of the class. * \param[in] config - Definition of the particular problem. * \param[in] Marker_Tag - String, which identifies the boundary marker for which the wall model is used. */ - CWallModel1DEQ(CConfig *config, - const string &Marker_Tag); + CWallModel1DEQ(CConfig* config, const string& Marker_Tag); /*! * \brief Function, which computes the wall shear stress and heat flux @@ -135,27 +123,18 @@ class CWallModel1DEQ : public CWallModel { * \param[out] kOverCvWall - Thermal conductivity divided by Cv at the wall, to be computed. */ - void WallShearStressAndHeatFlux(const su2double tExchange, - const su2double velExchange, - const su2double muExchange, - const su2double pExchange, - const su2double Wall_HeatFlux, - const bool HeatFlux_Prescribed, - const su2double Wall_Temperature, - const bool Temperature_Prescribed, - CFluidModel *FluidModel, - su2double &tauWall, - su2double &qWall, - su2double &ViscosityWall, - su2double &kOverCvWall) override; - -private: - - su2double expansionRatio; /*!< \brief Stretching factor used for the wall model grid. */ - int numPoints; /*!< \brief Number of points used in the wall model grid. */ - - vector y_cv; /*!< \brief The coordinates in normal direction of the wall model grid (control volumes). */ - vector y_fa; /*!< \brief The coordinates in normal direction of the wall model grid (faces of CV). */ + void WallShearStressAndHeatFlux(const su2double tExchange, const su2double velExchange, const su2double muExchange, + const su2double pExchange, const su2double Wall_HeatFlux, + const bool HeatFlux_Prescribed, const su2double Wall_Temperature, + const bool Temperature_Prescribed, CFluidModel* FluidModel, su2double& tauWall, + su2double& qWall, su2double& ViscosityWall, su2double& kOverCvWall) override; + + private: + su2double expansionRatio; /*!< \brief Stretching factor used for the wall model grid. */ + int numPoints; /*!< \brief Number of points used in the wall model grid. */ + + vector y_cv; /*!< \brief The coordinates in normal direction of the wall model grid (control volumes). */ + vector y_fa; /*!< \brief The coordinates in normal direction of the wall model grid (faces of CV). */ /*! * \brief Default constructor of the class, disabled. @@ -164,17 +143,14 @@ class CWallModel1DEQ : public CWallModel { }; class CWallModelLogLaw : public CWallModel { - -public: - + public: /*! * \brief Constructor of the class, which initializes the object. * \param[in] config - Definition of the particular problem. * \param[in] Marker_Tag - String, which identifies the boundary marker for which the wall model is used. */ - CWallModelLogLaw(CConfig *config, - const string &Marker_Tag); + CWallModelLogLaw(CConfig* config, const string& Marker_Tag); /*! * \brief Function, which computes the wall shear stress and heat flux @@ -194,23 +170,14 @@ class CWallModelLogLaw : public CWallModel { * \param[out] kOverCvWall - Thermal conductivity divided by Cv at the wall, to be computed. */ - void WallShearStressAndHeatFlux(const su2double tExchange, - const su2double velExchange, - const su2double muExchange, - const su2double pExchange, - const su2double Wall_HeatFlux, - const bool HeatFlux_Prescribed, - const su2double Wall_Temperature, - const bool Temperature_Prescribed, - CFluidModel *FluidModel, - su2double &tauWall, - su2double &qWall, - su2double &ViscosityWall, - su2double &kOverCvWall) override; - -private: - - su2double C; /*!< \brief Constant to match the Reichardt BL profile. */ + void WallShearStressAndHeatFlux(const su2double tExchange, const su2double velExchange, const su2double muExchange, + const su2double pExchange, const su2double Wall_HeatFlux, + const bool HeatFlux_Prescribed, const su2double Wall_Temperature, + const bool Temperature_Prescribed, CFluidModel* FluidModel, su2double& tauWall, + su2double& qWall, su2double& ViscosityWall, su2double& kOverCvWall) override; + + private: + su2double C; /*!< \brief Constant to match the Reichardt BL profile. */ /*! * \brief Default constructor of the class, disabled. diff --git a/Common/lib/Makefile.am b/Common/lib/Makefile.am index 4323382ceea..1ead93f2ca7 100644 --- a/Common/lib/Makefile.am +++ b/Common/lib/Makefile.am @@ -166,4 +166,3 @@ libSU2_AD_a_SOURCES = $(lib_sources) libSU2_AD_a_CXXFLAGS = @REVERSE_CXX@ ${lib_cxxflags} libSU2_AD_a_LIBADD = ${lib_ldadd} endif - diff --git a/Common/src/adt/CADTBaseClass.cpp b/Common/src/adt/CADTBaseClass.cpp index 6be2c3f6769..0a063275541 100644 --- a/Common/src/adt/CADTBaseClass.cpp +++ b/Common/src/adt/CADTBaseClass.cpp @@ -31,32 +31,32 @@ #include -void CADTBaseClass::BuildADT(unsigned short nDim, - unsigned long nPoints, - const su2double *coor) { - +void CADTBaseClass::BuildADT(unsigned short nDim, unsigned long nPoints, const su2double* coor) { /*--- Determine the number of leaves. It can be proved that nLeaves equals nPoints-1 for an optimally balanced tree. Take the exceptional case of nPoints == 1 into account and return if the tree is empty. ---*/ nDimADT = nDim; isEmpty = false; - nLeaves = nPoints -1; - if(nPoints <= 1) ++nLeaves; - if(nLeaves == 0) {isEmpty = true; return;} + nLeaves = nPoints - 1; + if (nPoints <= 1) ++nLeaves; + if (nLeaves == 0) { + isEmpty = true; + return; + } /*--- Allocate the memory for the leaves of the ADT and the minimum and maximum coordinates of the leaves. Note that these coordinates are stored in one vector, rather than that memory is allocated for the individual leaves. ---*/ leaves.resize(nLeaves); - coorMinLeaves.resize(nDim*nLeaves); - coorMaxLeaves.resize(nDim*nLeaves); + coorMinLeaves.resize(nDim * nLeaves); + coorMaxLeaves.resize(nDim * nLeaves); /*--- Define the vectors, which control the subdivision of the leaves. ---*/ - unsigned long nn = (nPoints+1)/2; + unsigned long nn = (nPoints + 1) / 2; vector pointIDs(nPoints), pointIDsNew(nPoints); - vector nPointIDs(nn+1), nPointIDsNew(nn+1); - vector curLeaf(nn), curLeafNew(nn); + vector nPointIDs(nn + 1), nPointIDsNew(nn + 1); + vector curLeaf(nn), curLeafNew(nn); /*--------------------------------------------------------------------------*/ /*--- Building of the actual ADT ---*/ @@ -65,47 +65,45 @@ void CADTBaseClass::BuildADT(unsigned short nDim, /*--- Initialize the arrays pointIDs, nPointIDs and curLeaf such that all points belong to the root leaf. Also set the counters nLeavesToDivide and nLeavesTot. ---*/ - nPointIDs[0] = 0; nPointIDs[1] = nPoints; + nPointIDs[0] = 0; + nPointIDs[1] = nPoints; curLeaf[0] = 0; - for(unsigned long i=0; i distMax) {distMax = dist; splitDir = l;} + if (dist > distMax) { + distMax = dist; + splitDir = l; + } } /* Sort the points of the current leaf in increasing order. The sorting is based on the coordinate in the split direction, for which the functor CADTComparePointClass is used. */ - sort(pointIDs.data() + nPointIDs[i], pointIDs.data() + nPointIDs[i+1], + sort(pointIDs.data() + nPointIDs[i], pointIDs.data() + nPointIDs[i + 1], CADTComparePointClass(coor, splitDir, nDim)); /* Determine the index of the node, which is approximately central in this leave. */ - leaves[mm].centralNodeID = pointIDs[nPointIDs[i] + nn/2]; + leaves[mm].centralNodeID = pointIDs[nPointIDs[i] + nn / 2]; /*--- Determine the situation of the leaf. It is either a terminal leaf or a leaf that must be subdivided. ---*/ - if(nn <= 2) { - + if (nn <= 2) { /* Terminal leaf. Store the ID's of the points as children and indicate that the children are terminal. */ leaves[mm].children[0] = pointIDs[nPointIDs[i]]; - leaves[mm].children[1] = pointIDs[nPointIDs[i+1]-1]; + leaves[mm].children[1] = pointIDs[nPointIDs[i + 1] - 1]; leaves[mm].childrenAreTerminal[0] = true; leaves[mm].childrenAreTerminal[1] = true; - } - else { - + } else { /* The leaf must be divided. Determine the number of points in the left leaf. This number is at least 2. The actual number stored in kk is this number plus an offset. Also initialize the counter nfl, which is used to store the bounding boxes in the arrays for the new round. */ - unsigned long kk = (nn+1)/2 + nPointIDs[i]; + unsigned long kk = (nn + 1) / 2 + nPointIDs[i]; unsigned long nfl = nPointIDsNew[nLeavesToDivideNew]; /* Copy the ID's of the left points into pointIDsNew. Also update the corresponding entry in nPointIDsNew. */ - for(unsigned long k=nPointIDs[i]; k &val_coor, - vector &val_connElem, - vector &val_VTKElem, - vector &val_markerID, - vector &val_elemID, - const bool globalTree) { +const su2double paramUpperBound = 1.0 + tolInsideElem; +CADTElemClass::CADTElemClass(unsigned short val_nDim, vector& val_coor, vector& val_connElem, + vector& val_VTKElem, vector& val_markerID, + vector& val_elemID, const bool globalTree) { /* Copy the dimension of the problem into nDim. */ nDim = val_nDim; @@ -66,8 +61,7 @@ CADTElemClass::CADTElemClass(unsigned short val_nDim, #ifdef HAVE_MPI /* Parallel mode. Check whether a global or a local tree must be built. */ - if( globalTree ) { - + if (globalTree) { /*--- The local grids are gathered on all ranks. For very large cases this could become a serious memory bottleneck and a parallel version may be needed. ---*/ @@ -79,35 +73,32 @@ CADTElemClass::CADTElemClass(unsigned short val_nDim, SU2_MPI::Comm_size(SU2_MPI::GetComm(), &size); vector recvCounts(size), displs(size); - int sizeLocal = (int) val_coor.size(); + int sizeLocal = (int)val_coor.size(); - SU2_MPI::Allgather(&sizeLocal, 1, MPI_INT, recvCounts.data(), 1, - MPI_INT, SU2_MPI::GetComm()); + SU2_MPI::Allgather(&sizeLocal, 1, MPI_INT, recvCounts.data(), 1, MPI_INT, SU2_MPI::GetComm()); displs[0] = 0; - for(int i=1; i& frontLeaves, - vector& frontLeavesNew, - const su2double *coor, - unsigned short &markerID, - unsigned long &elemID, - int &rankID, - su2double *parCoor, - su2double *weightsInterpol) const { - + vector& frontLeavesNew, const su2double* coor, + unsigned short& markerID, unsigned long& elemID, int& rankID, + su2double* parCoor, su2double* weightsInterpol) const { /* Start at the root leaf of the ADT, i.e. initialize frontLeaves such that it only contains the root leaf. Make sure to wipe out any data from a previous search. */ @@ -278,61 +271,54 @@ bool CADTElemClass::DetermineContainingElement_impl(vector& front frontLeaves.push_back(0); /* Infinite loop of the tree traversal. */ - for(;;) { - + for (;;) { /* Initialize the new front, i.e. the front for the next round, to empty. */ frontLeavesNew.clear(); /* Loop over the leaves of the current front. */ - for(unsigned long i=0; i coorBBMax[k]) coorIsInside = false; + for (unsigned short k = 0; k < nDim; ++k) { + if (coor[k] < coorBBMin[k]) coorIsInside = false; + if (coor[k] > coorBBMax[k]) coorIsInside = false; } - if( coorIsInside ) { - + if (coorIsInside) { /* Coordinate is inside the bounding box. Check if it is also inside the corresponding element. If so, set the required information and return true. */ - if( CoorInElement(kk, coor, parCoor, weightsInterpol) ) { + if (CoorInElement(kk, coor, parCoor, weightsInterpol)) { markerID = localMarkers[kk]; - elemID = localElemIDs[kk]; - rankID = ranksOfElems[kk]; + elemID = localElemIDs[kk]; + rankID = ranksOfElems[kk]; return true; } } - } - else { - + } else { /* Child contains a leaf. If the coordinate is inside the leaf store the leaf for the next round. */ - const su2double *coorBBMin = leaves[kk].xMin; - const su2double *coorBBMax = leaves[kk].xMax + nDim; + const su2double* coorBBMin = leaves[kk].xMin; + const su2double* coorBBMax = leaves[kk].xMax + nDim; bool coorIsInside = true; - for(unsigned short k=0; k coorBBMax[k]) coorIsInside = false; + for (unsigned short k = 0; k < nDim; ++k) { + if (coor[k] < coorBBMin[k]) coorIsInside = false; + if (coor[k] > coorBBMax[k]) coorIsInside = false; } - if( coorIsInside ) frontLeavesNew.push_back(kk); + if (coorIsInside) frontLeavesNew.push_back(kk); } } } @@ -342,7 +328,7 @@ bool CADTElemClass::DetermineContainingElement_impl(vector& front is empty the entire tree has been traversed and a break can be made from the infinite loop. ---*/ frontLeaves = frontLeavesNew; - if(frontLeaves.size() == 0) break; + if (frontLeaves.size() == 0) break; } /* If this point is reached, no element is found that contains the coordinate @@ -352,13 +338,9 @@ bool CADTElemClass::DetermineContainingElement_impl(vector& front void CADTElemClass::DetermineNearestElement_impl(vector& BBoxTargets, vector& frontLeaves, - vector& frontLeavesNew, - const su2double *coor, - su2double &dist, - unsigned short &markerID, - unsigned long &elemID, - int &rankID) const { - + vector& frontLeavesNew, const su2double* coor, + su2double& dist, unsigned short& markerID, unsigned long& elemID, + int& rankID) const { const bool wasActive = AD::BeginPassive(); /*----------------------------------------------------------------------------*/ @@ -367,16 +349,20 @@ void CADTElemClass::DetermineNearestElement_impl(vector& BBoxT /*----------------------------------------------------------------------------*/ unsigned long kk = leaves[0].centralNodeID; - const su2double *coorBBMin = BBoxCoor.data() + nDimADT*kk; - const su2double *coorBBMax = coorBBMin + nDim; + const su2double* coorBBMin = BBoxCoor.data() + nDimADT * kk; + const su2double* coorBBMax = coorBBMin + nDim; unsigned long jj = 0; dist = 0.0; su2double ds; - ds = max(fabs(coor[0]-coorBBMin[0]), fabs(coor[0]-coorBBMax[0])); dist += ds*ds; - ds = max(fabs(coor[1]-coorBBMin[1]), fabs(coor[1]-coorBBMax[1])); dist += ds*ds; - if(nDim==3) { - ds = max(fabs(coor[2]-coorBBMin[2]), fabs(coor[2]-coorBBMax[2])); dist += ds*ds;} + ds = max(fabs(coor[0] - coorBBMin[0]), fabs(coor[0] - coorBBMax[0])); + dist += ds * ds; + ds = max(fabs(coor[1] - coorBBMin[1]), fabs(coor[1] - coorBBMax[1])); + dist += ds * ds; + if (nDim == 3) { + ds = max(fabs(coor[2] - coorBBMin[2]), fabs(coor[2] - coorBBMax[2])); + dist += ds * ds; + } /*----------------------------------------------------------------------------*/ /*--- Step 2: Traverse the tree and store the bounding boxes for which the ---*/ @@ -393,83 +379,92 @@ void CADTElemClass::DetermineNearestElement_impl(vector& BBoxT frontLeaves.push_back(0); /* Infinite loop of the tree traversal. */ - for(;;) { - + for (;;) { /* Initialize the new front, i.e. the front for the next round, to empty. */ frontLeavesNew.clear(); /* Loop over the leaves of the current front. */ - for(unsigned long i=0; i& BBoxT is empty the entire tree has been traversed and a break can be made from the infinite loop. ---*/ frontLeaves = frontLeavesNew; - if(frontLeaves.size() == 0) break; + if (frontLeaves.size() == 0) break; } /*----------------------------------------------------------------------------*/ @@ -496,14 +491,13 @@ void CADTElemClass::DetermineNearestElement_impl(vector& BBoxT sort(BBoxTargets.begin(), BBoxTargets.end()); /* Loop over the candidate bounding boxes. */ - for(unsigned long i=0; i dist) break; + if (BBoxTargets[i].possibleMinDist2 > dist) break; /*--- Compute the distance squared to the element that corresponds to the current bounding box. If this distance is less than or equal to @@ -513,12 +507,12 @@ void CADTElemClass::DetermineNearestElement_impl(vector& BBoxT su2double dist2Elem; Dist2ToElement(ii, coor, dist2Elem); - if(dist2Elem <= dist) { - jj = ii; - dist = dist2Elem; + if (dist2Elem <= dist) { + jj = ii; + dist = dist2Elem; markerID = localMarkers[ii]; - elemID = localElemIDs[ii]; - rankID = ranksOfElems[ii]; + elemID = localElemIDs[ii]; + rankID = ranksOfElems[ii]; } } @@ -530,20 +524,22 @@ void CADTElemClass::DetermineNearestElement_impl(vector& BBoxT dist = sqrt(dist); } -bool CADTElemClass::CoorInElement(const unsigned long elemID, - const su2double *coor, - su2double *parCoor, - su2double *weightsInterpol) const { - +bool CADTElemClass::CoorInElement(const unsigned long elemID, const su2double* coor, su2double* parCoor, + su2double* weightsInterpol) const { /*--- Make a distinction between the element types. ---*/ - switch( elemVTK_Type[elemID] ) { - - case TRIANGLE: return CoorInTriangle(elemID, coor, parCoor, weightsInterpol); - case QUADRILATERAL: return CoorInQuadrilateral(elemID, coor, parCoor, weightsInterpol); - case TETRAHEDRON: return CoorInTetrahedron(elemID, coor, parCoor, weightsInterpol); - case PYRAMID: return CoorInPyramid(elemID, coor, parCoor, weightsInterpol); - case PRISM: return CoorInPrism(elemID, coor, parCoor, weightsInterpol); - case HEXAHEDRON: return CoorInHexahedron(elemID, coor, parCoor, weightsInterpol); + switch (elemVTK_Type[elemID]) { + case TRIANGLE: + return CoorInTriangle(elemID, coor, parCoor, weightsInterpol); + case QUADRILATERAL: + return CoorInQuadrilateral(elemID, coor, parCoor, weightsInterpol); + case TETRAHEDRON: + return CoorInTetrahedron(elemID, coor, parCoor, weightsInterpol); + case PYRAMID: + return CoorInPyramid(elemID, coor, parCoor, weightsInterpol); + case PRISM: + return CoorInPrism(elemID, coor, parCoor, weightsInterpol); + case HEXAHEDRON: + return CoorInHexahedron(elemID, coor, parCoor, weightsInterpol); default: /* This should not happen. */ @@ -552,21 +548,17 @@ bool CADTElemClass::CoorInElement(const unsigned long elemID, } } -void CADTElemClass::Dist2ToElement(const unsigned long elemID, - const su2double *coor, - su2double &dist2Elem) const { - +void CADTElemClass::Dist2ToElement(const unsigned long elemID, const su2double* coor, su2double& dist2Elem) const { /*--- Make a distinction between the element types. ---*/ - switch( elemVTK_Type[elemID] ) { - + switch (elemVTK_Type[elemID]) { case LINE: { - /*--- Element is a line. The number of space dimensions can be either 1, 2 or 3. Store the indices where the coordinates of the vertices are stored in i0 and i1. ---*/ unsigned long i0 = nDOFsPerElem[elemID]; unsigned long i1 = i0 + 1; - i0 = nDim*elemConns[i0]; i1 = nDim*elemConns[i1]; + i0 = nDim * elemConns[i0]; + i1 = nDim * elemConns[i1]; /*--- Call the function Dist2ToLine to do the actual work. ---*/ Dist2ToLine(i0, i1, coor, dist2Elem); @@ -574,16 +566,17 @@ void CADTElemClass::Dist2ToElement(const unsigned long elemID, break; } - /*------------------------------------------------------------------------*/ + /*------------------------------------------------------------------------*/ case TRIANGLE: { - /*--- Element is a triangle. The number of space dimensions can be either 2 or 3. Store the indices where the coordinates of the vertices are stored in i0, i1 and i2. ---*/ unsigned long i0 = nDOFsPerElem[elemID]; unsigned long i1 = i0 + 1, i2 = i0 + 2; - i0 = nDim*elemConns[i0]; i1 = nDim*elemConns[i1]; i2 = nDim*elemConns[i2]; + i0 = nDim * elemConns[i0]; + i1 = nDim * elemConns[i1]; + i2 = nDim * elemConns[i2]; /*--- Call the function Dist2ToTriangle to compute the distance to the triangle if the projection is inside the triangle. In that case the @@ -591,28 +584,31 @@ void CADTElemClass::Dist2ToElement(const unsigned long elemID, false is returned and the distance to each of the lines of the triangle is computed and the minimum is taken. ---*/ su2double r, s; - if( !Dist2ToTriangle(i0, i1, i2, coor, dist2Elem, r, s) ) { + if (!Dist2ToTriangle(i0, i1, i2, coor, dist2Elem, r, s)) { Dist2ToLine(i0, i1, coor, dist2Elem); su2double dist2Line; - Dist2ToLine(i1, i2, coor, dist2Line); dist2Elem = min(dist2Elem, dist2Line); - Dist2ToLine(i2, i0, coor, dist2Line); dist2Elem = min(dist2Elem, dist2Line); + Dist2ToLine(i1, i2, coor, dist2Line); + dist2Elem = min(dist2Elem, dist2Line); + Dist2ToLine(i2, i0, coor, dist2Line); + dist2Elem = min(dist2Elem, dist2Line); } break; } - /*------------------------------------------------------------------------*/ + /*------------------------------------------------------------------------*/ case QUADRILATERAL: { - /*--- Element is a quadrilateral. The number of space dimensions can be either 2 or 3. Store the indices where the coordinates of the vertices are stored in i0, i1, i2 and i3. ---*/ unsigned long i0 = nDOFsPerElem[elemID]; unsigned long i1 = i0 + 1, i2 = i0 + 2, i3 = i0 + 3; - i0 = nDim*elemConns[i0]; i1 = nDim*elemConns[i1]; - i2 = nDim*elemConns[i2]; i3 = nDim*elemConns[i3]; + i0 = nDim * elemConns[i0]; + i1 = nDim * elemConns[i1]; + i2 = nDim * elemConns[i2]; + i3 = nDim * elemConns[i3]; /*--- Call the function Dist2ToQuadrilateral to compute the distance to the quadrilateral if the projection is inside the quadrilateral. In that @@ -620,19 +616,22 @@ void CADTElemClass::Dist2ToElement(const unsigned long elemID, quadrilateral, false is returned and the distance to each of the lines of the quadrilateral is computed and the minimum is taken. ---*/ su2double r, s; - if( !Dist2ToQuadrilateral(i0, i1, i2, i3, coor, r, s, dist2Elem) ) { + if (!Dist2ToQuadrilateral(i0, i1, i2, i3, coor, r, s, dist2Elem)) { Dist2ToLine(i0, i1, coor, dist2Elem); su2double dist2Line; - Dist2ToLine(i1, i2, coor, dist2Line); dist2Elem = min(dist2Elem, dist2Line); - Dist2ToLine(i2, i3, coor, dist2Line); dist2Elem = min(dist2Elem, dist2Line); - Dist2ToLine(i3, i0, coor, dist2Line); dist2Elem = min(dist2Elem, dist2Line); + Dist2ToLine(i1, i2, coor, dist2Line); + dist2Elem = min(dist2Elem, dist2Line); + Dist2ToLine(i2, i3, coor, dist2Line); + dist2Elem = min(dist2Elem, dist2Line); + Dist2ToLine(i3, i0, coor, dist2Line); + dist2Elem = min(dist2Elem, dist2Line); } break; } - /*------------------------------------------------------------------------*/ + /*------------------------------------------------------------------------*/ case TETRAHEDRON: case PYRAMID: @@ -643,83 +642,81 @@ void CADTElemClass::Dist2ToElement(const unsigned long elemID, } } -bool CADTElemClass::CoorInTriangle(const unsigned long elemID, - const su2double *coor, - su2double *parCoor, - su2double *weightsInterpol) const { - +bool CADTElemClass::CoorInTriangle(const unsigned long elemID, const su2double* coor, su2double* parCoor, + su2double* weightsInterpol) const { /* Determine the indices of the three vertices of the triangle, multiplied by nDim (which is 2). This gives the position in the coordinate array where the coordinates of these points are stored. */ unsigned long i0 = nDOFsPerElem[elemID]; unsigned long i1 = i0 + 1, i2 = i0 + 2; - i0 = nDim*elemConns[i0]; i1 = nDim*elemConns[i1]; i2 = nDim*elemConns[i2]; + i0 = nDim * elemConns[i0]; + i1 = nDim * elemConns[i1]; + i2 = nDim * elemConns[i2]; /* Determine the coordinates relative to the vertex 0. */ const su2double xc = coor[0] - coorPoints[i0]; - const su2double yc = coor[1] - coorPoints[i0+1]; + const su2double yc = coor[1] - coorPoints[i0 + 1]; - const su2double x1 = coorPoints[i1] - coorPoints[i0]; - const su2double y1 = coorPoints[i1+1] - coorPoints[i0+1]; + const su2double x1 = coorPoints[i1] - coorPoints[i0]; + const su2double y1 = coorPoints[i1 + 1] - coorPoints[i0 + 1]; - const su2double x2 = coorPoints[i2] - coorPoints[i0]; - const su2double y2 = coorPoints[i2+1] - coorPoints[i0+1]; + const su2double x2 = coorPoints[i2] - coorPoints[i0]; + const su2double y2 = coorPoints[i2 + 1] - coorPoints[i0 + 1]; /* The triangle is parametrized by X-X0 = (r+1)*(X1-X0)/2 + (s+1)*(X2-X0)/2, r, s >= -1, r+s <= 0. As this is a containment search, the number of dimesions is 2. As a consequence, the parametric coordinates r and s can be solved easily. Note that X0 is 0 in the above expression, because the coordinates are relative to node 0. */ - const su2double detInv = 2.0/(x1*y2 - x2*y1); - parCoor[0] = detInv*(xc*y2 - yc*x2) - 1.0; - parCoor[1] = detInv*(yc*x1 - xc*y1) - 1.0; + const su2double detInv = 2.0 / (x1 * y2 - x2 * y1); + parCoor[0] = detInv * (xc * y2 - yc * x2) - 1.0; + parCoor[1] = detInv * (yc * x1 - xc * y1) - 1.0; /* Check if the point resides within the triangle and compute the interpolation weights if it is. */ bool coorIsInside = false; - if((parCoor[0] >= paramLowerBound) && (parCoor[1] >= paramLowerBound) && - ((parCoor[0]+parCoor[1]) <= tolInsideElem)) { + if ((parCoor[0] >= paramLowerBound) && (parCoor[1] >= paramLowerBound) && + ((parCoor[0] + parCoor[1]) <= tolInsideElem)) { coorIsInside = true; - weightsInterpol[0] = -0.5*(parCoor[0] + parCoor[1]); - weightsInterpol[1] = 0.5*(parCoor[0] + 1.0); - weightsInterpol[2] = 0.5*(parCoor[1] + 1.0); + weightsInterpol[0] = -0.5 * (parCoor[0] + parCoor[1]); + weightsInterpol[1] = 0.5 * (parCoor[0] + 1.0); + weightsInterpol[2] = 0.5 * (parCoor[1] + 1.0); } /* Return the value of coorIsInside. */ return coorIsInside; } -bool CADTElemClass::CoorInQuadrilateral(const unsigned long elemID, - const su2double *coor, - su2double *parCoor, - su2double *weightsInterpol) const { - +bool CADTElemClass::CoorInQuadrilateral(const unsigned long elemID, const su2double* coor, su2double* parCoor, + su2double* weightsInterpol) const { /* Definition of the maximum number of iterations in the Newton solver and the tolerance level. */ const unsigned short maxIt = 50; - const su2double tolNewton = 1.e-10; + const su2double tolNewton = 1.e-10; /* Determine the indices of the four vertices of the quadrilatral, multiplied by nDim (which is 2). This gives the position in the coordinate array where the coordinates of these points are stored. */ unsigned long i0 = nDOFsPerElem[elemID]; - unsigned long i1 = i0 + 1, i2 = i0 + 2, i3 = i0+3; - i0 = nDim*elemConns[i0]; i1 = nDim*elemConns[i1]; - i2 = nDim*elemConns[i2]; i3 = nDim*elemConns[i3]; + unsigned long i1 = i0 + 1, i2 = i0 + 2, i3 = i0 + 3; + i0 = nDim * elemConns[i0]; + i1 = nDim * elemConns[i1]; + i2 = nDim * elemConns[i2]; + i3 = nDim * elemConns[i3]; /* Determine the coordinates relative to the vertex 0. */ const su2double xc = coor[0] - coorPoints[i0]; - const su2double yc = coor[1] - coorPoints[i0+1]; + const su2double yc = coor[1] - coorPoints[i0 + 1]; - const su2double x1 = coorPoints[i1] - coorPoints[i0]; - const su2double y1 = coorPoints[i1+1] - coorPoints[i0+1]; + const su2double x1 = coorPoints[i1] - coorPoints[i0]; + const su2double y1 = coorPoints[i1 + 1] - coorPoints[i0 + 1]; - const su2double x2 = coorPoints[i2] - coorPoints[i0]; - const su2double y2 = coorPoints[i2+1] - coorPoints[i0+1]; + const su2double x2 = coorPoints[i2] - coorPoints[i0]; + const su2double y2 = coorPoints[i2 + 1] - coorPoints[i0 + 1]; - const su2double x3 = coorPoints[i3] - coorPoints[i0]; - const su2double y3 = coorPoints[i3+1] - coorPoints[i0+1]; + const su2double x3 = coorPoints[i3] - coorPoints[i0]; + const su2double y3 = coorPoints[i3 + 1] - coorPoints[i0 + 1]; /* The parametrization of the quadrilatral is nonlinear, which requires an iterative algorithm. Especially for highly skewed quadrilaterals, this @@ -727,29 +724,30 @@ bool CADTElemClass::CoorInQuadrilateral(const unsigned long elemID, linear triangles to check if the point is actually within the quad. First check the triangle i0-i1-i3. See CoorInTriangle for more details on this test. */ - su2double detInv = 2.0/(x1*y3 - x3*y1); - parCoor[0] = detInv*(xc*y3 - yc*x3) - 1.0; - parCoor[1] = detInv*(yc*x1 - xc*y1) - 1.0; + su2double detInv = 2.0 / (x1 * y3 - x3 * y1); + parCoor[0] = detInv * (xc * y3 - yc * x3) - 1.0; + parCoor[1] = detInv * (yc * x1 - xc * y1) - 1.0; bool coorIsInside = false; - if((parCoor[0] >= paramLowerBound) && (parCoor[1] >= paramLowerBound) && - ((parCoor[0]+parCoor[1]) <= tolInsideElem)) coorIsInside = true; + if ((parCoor[0] >= paramLowerBound) && (parCoor[1] >= paramLowerBound) && + ((parCoor[0] + parCoor[1]) <= tolInsideElem)) + coorIsInside = true; /* Check triangle i2-i3-i1 if the coordinate is not inside i0-i1-i3. */ - if( !coorIsInside ) { - + if (!coorIsInside) { /* Define the coordinates w.r.t. vertex 2 using the numbering i2-i3-i1. */ const su2double xxc = xc - x2, yyc = yc - y2; const su2double xx1 = x3 - x2, yy1 = y3 - y2; const su2double xx3 = x1 - x2, yy3 = y1 - y2; /* Check if the coordinate is inside this triangle. */ - detInv = 2.0/(xx1*yy3 - xx3*yy1); - parCoor[0] = detInv*(xxc*yy3 - yyc*xx3) - 1.0; - parCoor[1] = detInv*(yyc*xx1 - xxc*yy1) - 1.0; + detInv = 2.0 / (xx1 * yy3 - xx3 * yy1); + parCoor[0] = detInv * (xxc * yy3 - yyc * xx3) - 1.0; + parCoor[1] = detInv * (yyc * xx1 - xxc * yy1) - 1.0; - if((parCoor[0] >= paramLowerBound) && (parCoor[1] >= paramLowerBound) && - ((parCoor[0]+parCoor[1]) <= tolInsideElem)) coorIsInside = true; + if ((parCoor[0] >= paramLowerBound) && (parCoor[1] >= paramLowerBound) && + ((parCoor[0] + parCoor[1]) <= tolInsideElem)) + coorIsInside = true; /* Convert the parametric coordinates to the ones used by the quadrilatral i0-i1-i2-i3. They serve as initial guess below. */ @@ -758,7 +756,7 @@ bool CADTElemClass::CoorInQuadrilateral(const unsigned long elemID, } /* If the coordinate is in neither triangle, return false. */ - if( !coorIsInside ) return false; + if (!coorIsInside) return false; /* The coordinate is inside the quadrilatral and an initial guess has been obtained by splitting the quad into two triangles. Carry out a Newton @@ -770,27 +768,26 @@ bool CADTElemClass::CoorInQuadrilateral(const unsigned long elemID, V0 - r*V1 - s*V2 - r*s*V3 = 0, where V0 = xc - (x1+x2+x3)/4, V1 = (x1+x2-x3)/4, V2 = (x2+x3-X1)/4, V3 = (x2-x1-x3)/4. First construct the vectors V0, V1, V2 and V3. */ - const su2double V0x = xc - 0.25*(x1+x2+x3), V0y = yc - 0.25*(y1+y2+y3); - const su2double V1x = 0.25*(x1+x2-x3), V1y = 0.25*(y1+y2-y3); - const su2double V2x = 0.25*(x2+x3-x1), V2y = 0.25*(y2+y3-y1); - const su2double V3x = 0.25*(x2-x1-x3), V3y = 0.25*(y2-y1-y3); + const su2double V0x = xc - 0.25 * (x1 + x2 + x3), V0y = yc - 0.25 * (y1 + y2 + y3); + const su2double V1x = 0.25 * (x1 + x2 - x3), V1y = 0.25 * (y1 + y2 - y3); + const su2double V2x = 0.25 * (x2 + x3 - x1), V2y = 0.25 * (y2 + y3 - y1); + const su2double V3x = 0.25 * (x2 - x1 - x3), V3y = 0.25 * (y2 - y1 - y3); /* Loop over the maximum number of iterations. */ unsigned short itCount; - for(itCount=0; itCount paramUpperBound || - parCoor[1] < paramLowerBound || parCoor[1] > paramUpperBound) + if (parCoor[0] < paramLowerBound || parCoor[0] > paramUpperBound || parCoor[1] < paramLowerBound || + parCoor[1] > paramUpperBound) SU2_MPI::Error("Point not inside the quadrilateral.", CURRENT_FUNCTION); /* Compute the interpolation weights. */ - const su2double omr = 0.5*(1.0-parCoor[0]), opr = 0.5*(1.0+parCoor[0]); - const su2double oms = 0.5*(1.0-parCoor[1]), ops = 0.5*(1.0+parCoor[1]); + const su2double omr = 0.5 * (1.0 - parCoor[0]), opr = 0.5 * (1.0 + parCoor[0]); + const su2double oms = 0.5 * (1.0 - parCoor[1]), ops = 0.5 * (1.0 + parCoor[1]); - weightsInterpol[0] = omr*oms; - weightsInterpol[1] = opr*oms; - weightsInterpol[2] = opr*ops; - weightsInterpol[3] = omr*ops; + weightsInterpol[0] = omr * oms; + weightsInterpol[1] = opr * oms; + weightsInterpol[2] = opr * ops; + weightsInterpol[3] = omr * ops; /* Return true, because the search was successful. */ return true; } -bool CADTElemClass::CoorInTetrahedron(const unsigned long elemID, - const su2double *coor, - su2double *parCoor, - su2double *weightsInterpol) const { - +bool CADTElemClass::CoorInTetrahedron(const unsigned long elemID, const su2double* coor, su2double* parCoor, + su2double* weightsInterpol) const { /* Determine the indices of the four vertices of the tetrahedron, multiplied by nDim (which is 3). This gives the position in the coordinate array where the coordinates of these points are stored. */ unsigned long i0 = nDOFsPerElem[elemID]; - unsigned long i1 = i0 + 1, i2 = i0 + 2, i3 = i0+3; - i0 = nDim*elemConns[i0]; i1 = nDim*elemConns[i1]; - i2 = nDim*elemConns[i2]; i3 = nDim*elemConns[i3]; + unsigned long i1 = i0 + 1, i2 = i0 + 2, i3 = i0 + 3; + i0 = nDim * elemConns[i0]; + i1 = nDim * elemConns[i1]; + i2 = nDim * elemConns[i2]; + i3 = nDim * elemConns[i3]; /* Determine the coordinates relative to the vertex 0. */ const su2double xc = coor[0] - coorPoints[i0]; - const su2double yc = coor[1] - coorPoints[i0+1]; - const su2double zc = coor[2] - coorPoints[i0+2]; + const su2double yc = coor[1] - coorPoints[i0 + 1]; + const su2double zc = coor[2] - coorPoints[i0 + 2]; - const su2double x1 = coorPoints[i1] - coorPoints[i0]; - const su2double y1 = coorPoints[i1+1] - coorPoints[i0+1]; - const su2double z1 = coorPoints[i1+2] - coorPoints[i0+2]; + const su2double x1 = coorPoints[i1] - coorPoints[i0]; + const su2double y1 = coorPoints[i1 + 1] - coorPoints[i0 + 1]; + const su2double z1 = coorPoints[i1 + 2] - coorPoints[i0 + 2]; - const su2double x2 = coorPoints[i2] - coorPoints[i0]; - const su2double y2 = coorPoints[i2+1] - coorPoints[i0+1]; - const su2double z2 = coorPoints[i2+2] - coorPoints[i0+2]; + const su2double x2 = coorPoints[i2] - coorPoints[i0]; + const su2double y2 = coorPoints[i2 + 1] - coorPoints[i0 + 1]; + const su2double z2 = coorPoints[i2 + 2] - coorPoints[i0 + 2]; - const su2double x3 = coorPoints[i3] - coorPoints[i0]; - const su2double y3 = coorPoints[i3+1] - coorPoints[i0+1]; - const su2double z3 = coorPoints[i3+2] - coorPoints[i0+2]; + const su2double x3 = coorPoints[i3] - coorPoints[i0]; + const su2double y3 = coorPoints[i3 + 1] - coorPoints[i0 + 1]; + const su2double z3 = coorPoints[i3 + 2] - coorPoints[i0 + 2]; /* The tetrahedron is parametrized by X-X0 = (r+1)*(X1-X0)/2 + (s+1)*(X2-X0)/2 + (t+1)*(X3-X0)/2, r, s, t >= -1, r+s+t <= -1. As a consequence, the parametric coordinates r, s and t can be solved easily. Note that X0 is 0 in the above expression, because the coordinates are relative to node 0. */ - const su2double detInv = 2.0/(x1*y2*z3 - x1*y3*z2 - x2*y1*z3 + x2*y3*z1 + x3*y1*z2 - x3*y2*z1); - parCoor[0] = detInv*(x2*y3*zc - x2*yc*z3 - x3*y2*zc + x3*yc*z2 + xc*y2*z3 - xc*y3*z2) - 1.0; - parCoor[1] = -detInv*(x1*y3*zc - x1*yc*z3 - x3*y1*zc + x3*yc*z1 + xc*y1*z3 - xc*y3*z1) - 1.0; - parCoor[2] = detInv*(x1*y2*zc - x1*yc*z2 - x2*y1*zc + x2*yc*z1 + xc*y1*z2 - xc*y2*z1) - 1.0; + const su2double detInv = + 2.0 / (x1 * y2 * z3 - x1 * y3 * z2 - x2 * y1 * z3 + x2 * y3 * z1 + x3 * y1 * z2 - x3 * y2 * z1); + parCoor[0] = detInv * (x2 * y3 * zc - x2 * yc * z3 - x3 * y2 * zc + x3 * yc * z2 + xc * y2 * z3 - xc * y3 * z2) - 1.0; + parCoor[1] = + -detInv * (x1 * y3 * zc - x1 * yc * z3 - x3 * y1 * zc + x3 * yc * z1 + xc * y1 * z3 - xc * y3 * z1) - 1.0; + parCoor[2] = detInv * (x1 * y2 * zc - x1 * yc * z2 - x2 * y1 * zc + x2 * yc * z1 + xc * y1 * z2 - xc * y2 * z1) - 1.0; /* Check if the point resides within the tetrahedron and compute the interpolation weights if it is. */ bool coorIsInside = false; - if((parCoor[0] >= paramLowerBound) && (parCoor[1] >= paramLowerBound) && - (parCoor[2] >= paramLowerBound) && - ((parCoor[0]+parCoor[1]+parCoor[2]) <= paramLowerBound)) { + if ((parCoor[0] >= paramLowerBound) && (parCoor[1] >= paramLowerBound) && (parCoor[2] >= paramLowerBound) && + ((parCoor[0] + parCoor[1] + parCoor[2]) <= paramLowerBound)) { coorIsInside = true; - weightsInterpol[0] = -0.5*(parCoor[0] + parCoor[1] + parCoor[2] + 1.0); - weightsInterpol[1] = 0.5*(parCoor[0] + 1.0); - weightsInterpol[2] = 0.5*(parCoor[1] + 1.0); - weightsInterpol[3] = 0.5*(parCoor[2] + 1.0); + weightsInterpol[0] = -0.5 * (parCoor[0] + parCoor[1] + parCoor[2] + 1.0); + weightsInterpol[1] = 0.5 * (parCoor[0] + 1.0); + weightsInterpol[2] = 0.5 * (parCoor[1] + 1.0); + weightsInterpol[3] = 0.5 * (parCoor[2] + 1.0); } /* Return the value of coorIsInside. */ return coorIsInside; } -bool CADTElemClass::CoorInPyramid(const unsigned long elemID, - const su2double *coor, - su2double *parCoor, - su2double *weightsInterpol) const { - +bool CADTElemClass::CoorInPyramid(const unsigned long elemID, const su2double* coor, su2double* parCoor, + su2double* weightsInterpol) const { /* Definition of the maximum number of iterations in the Newton solver and the tolerance level. */ const unsigned short maxIt = 50; - const su2double tolNewton = 1.e-10; + const su2double tolNewton = 1.e-10; /* Determine the indices of the five vertices of the pyramid, multiplied by nDim (which is 3). This gives the position in the coordinate array where the coordinates of these points are stored. */ unsigned long i0 = nDOFsPerElem[elemID]; - unsigned long i1 = i0 + 1, i2 = i0 + 2, i3 = i0+3, i4 = i0+4; - i0 = nDim*elemConns[i0]; i1 = nDim*elemConns[i1]; - i2 = nDim*elemConns[i2]; i3 = nDim*elemConns[i3]; - i4 = nDim*elemConns[i4]; + unsigned long i1 = i0 + 1, i2 = i0 + 2, i3 = i0 + 3, i4 = i0 + 4; + i0 = nDim * elemConns[i0]; + i1 = nDim * elemConns[i1]; + i2 = nDim * elemConns[i2]; + i3 = nDim * elemConns[i3]; + i4 = nDim * elemConns[i4]; /* Determine the coordinates relative to the vertex 0. */ su2double xRel[5][3], xc[3]; xc[0] = coor[0] - coorPoints[i0]; - xc[1] = coor[1] - coorPoints[i0+1]; - xc[2] = coor[2] - coorPoints[i0+2]; + xc[1] = coor[1] - coorPoints[i0 + 1]; + xc[2] = coor[2] - coorPoints[i0 + 2]; xRel[0][0] = xRel[0][1] = xRel[0][2] = 0.0; - xRel[1][0] = coorPoints[i1] - coorPoints[i0]; - xRel[1][1] = coorPoints[i1+1] - coorPoints[i0+1]; - xRel[1][2] = coorPoints[i1+2] - coorPoints[i0+2]; + xRel[1][0] = coorPoints[i1] - coorPoints[i0]; + xRel[1][1] = coorPoints[i1 + 1] - coorPoints[i0 + 1]; + xRel[1][2] = coorPoints[i1 + 2] - coorPoints[i0 + 2]; - xRel[2][0] = coorPoints[i2] - coorPoints[i0]; - xRel[2][1] = coorPoints[i2+1] - coorPoints[i0+1]; - xRel[2][2] = coorPoints[i2+2] - coorPoints[i0+2]; + xRel[2][0] = coorPoints[i2] - coorPoints[i0]; + xRel[2][1] = coorPoints[i2 + 1] - coorPoints[i0 + 1]; + xRel[2][2] = coorPoints[i2 + 2] - coorPoints[i0 + 2]; - xRel[3][0] = coorPoints[i3] - coorPoints[i0]; - xRel[3][1] = coorPoints[i3+1] - coorPoints[i0+1]; - xRel[3][2] = coorPoints[i3+2] - coorPoints[i0+2]; + xRel[3][0] = coorPoints[i3] - coorPoints[i0]; + xRel[3][1] = coorPoints[i3 + 1] - coorPoints[i0 + 1]; + xRel[3][2] = coorPoints[i3 + 2] - coorPoints[i0 + 2]; - xRel[4][0] = coorPoints[i4] - coorPoints[i0]; - xRel[4][1] = coorPoints[i4+1] - coorPoints[i0+1]; - xRel[4][2] = coorPoints[i4+2] - coorPoints[i0+2]; + xRel[4][0] = coorPoints[i4] - coorPoints[i0]; + xRel[4][1] = coorPoints[i4 + 1] - coorPoints[i0 + 1]; + xRel[4][2] = coorPoints[i4 + 2] - coorPoints[i0 + 2]; /* Obtain an initial guess of the parametric coordinates by splitting the pyramid into tetrahedra. If this approach is not successful, this means that the point is not inside the true pyramid and false can be returned. */ - if( !InitialGuessContainmentPyramid(xc, xRel, parCoor) ) return false; + if (!InitialGuessContainmentPyramid(xc, xRel, parCoor)) return false; /* The pyramid is parametrized by X-X0 = (Xi-X0)*li, where the sum runs over i = 0..4, although i = 0 does not give a contribution. The Lagrangian @@ -943,67 +938,68 @@ bool CADTElemClass::CoorInPyramid(const unsigned long elemID, V0 - V1*r - V2*s - V3*t - V4*r*s/(1-t) = 0, where V0 = xc - (4*x4+x1+x2+x3)/8, V1 = (x1+x2-x3)/4, V2 = (x2+x3-X1)/4, V3 = (4*X4-x1-x2-x3)/8, V4 = (x2-x1-x3)/2. First construct these vectors. */ - const su2double V0x = xc[0] - 0.5*xRel[4][0] - 0.125*(xRel[1][0]+xRel[2][0]+xRel[3][0]); - const su2double V0y = xc[1] - 0.5*xRel[4][1] - 0.125*(xRel[1][1]+xRel[2][1]+xRel[3][1]); - const su2double V0z = xc[2] - 0.5*xRel[4][2] - 0.125*(xRel[1][2]+xRel[2][2]+xRel[3][2]); + const su2double V0x = xc[0] - 0.5 * xRel[4][0] - 0.125 * (xRel[1][0] + xRel[2][0] + xRel[3][0]); + const su2double V0y = xc[1] - 0.5 * xRel[4][1] - 0.125 * (xRel[1][1] + xRel[2][1] + xRel[3][1]); + const su2double V0z = xc[2] - 0.5 * xRel[4][2] - 0.125 * (xRel[1][2] + xRel[2][2] + xRel[3][2]); - const su2double V1x = 0.25*(xRel[1][0]+xRel[2][0]-xRel[3][0]); - const su2double V1y = 0.25*(xRel[1][1]+xRel[2][1]-xRel[3][1]); - const su2double V1z = 0.25*(xRel[1][2]+xRel[2][2]-xRel[3][2]); + const su2double V1x = 0.25 * (xRel[1][0] + xRel[2][0] - xRel[3][0]); + const su2double V1y = 0.25 * (xRel[1][1] + xRel[2][1] - xRel[3][1]); + const su2double V1z = 0.25 * (xRel[1][2] + xRel[2][2] - xRel[3][2]); - const su2double V2x = 0.25*(xRel[2][0]+xRel[3][0]-xRel[1][0]); - const su2double V2y = 0.25*(xRel[2][1]+xRel[3][1]-xRel[1][1]); - const su2double V2z = 0.25*(xRel[2][2]+xRel[3][2]-xRel[1][2]); + const su2double V2x = 0.25 * (xRel[2][0] + xRel[3][0] - xRel[1][0]); + const su2double V2y = 0.25 * (xRel[2][1] + xRel[3][1] - xRel[1][1]); + const su2double V2z = 0.25 * (xRel[2][2] + xRel[3][2] - xRel[1][2]); - const su2double V3x = 0.5*xRel[4][0] - 0.125*(xRel[1][0]+xRel[2][0]+xRel[3][0]); - const su2double V3y = 0.5*xRel[4][1] - 0.125*(xRel[1][1]+xRel[2][1]+xRel[3][1]); - const su2double V3z = 0.5*xRel[4][2] - 0.125*(xRel[1][2]+xRel[2][2]+xRel[3][2]); + const su2double V3x = 0.5 * xRel[4][0] - 0.125 * (xRel[1][0] + xRel[2][0] + xRel[3][0]); + const su2double V3y = 0.5 * xRel[4][1] - 0.125 * (xRel[1][1] + xRel[2][1] + xRel[3][1]); + const su2double V3z = 0.5 * xRel[4][2] - 0.125 * (xRel[1][2] + xRel[2][2] + xRel[3][2]); - const su2double V4x = 0.5*(xRel[2][0]-xRel[1][0]-xRel[3][0]); - const su2double V4y = 0.5*(xRel[2][1]-xRel[1][1]-xRel[3][1]); - const su2double V4z = 0.5*(xRel[2][2]-xRel[1][2]-xRel[3][2]); + const su2double V4x = 0.5 * (xRel[2][0] - xRel[1][0] - xRel[3][0]); + const su2double V4y = 0.5 * (xRel[2][1] - xRel[1][1] - xRel[3][1]); + const su2double V4z = 0.5 * (xRel[2][2] - xRel[1][2] - xRel[3][2]); /* Loop over the maximum number of iterations. */ unsigned short itCount; - for(itCount=0; itCount= paramLowerBound) && (parCoor[2] <= paramUpperBound)) { - const su2double lowRSBound = 0.5*(parCoor[2]-1.0) - tolInsideElem; + if ((parCoor[2] >= paramLowerBound) && (parCoor[2] <= paramUpperBound)) { + const su2double lowRSBound = 0.5 * (parCoor[2] - 1.0) - tolInsideElem; const su2double uppRSBound = -lowRSBound; - if((parCoor[0] >= lowRSBound) && (parCoor[0] <= uppRSBound) && - (parCoor[1] >= lowRSBound) && (parCoor[1] <= uppRSBound)) { + if ((parCoor[0] >= lowRSBound) && (parCoor[0] <= uppRSBound) && (parCoor[1] >= lowRSBound) && + (parCoor[1] <= uppRSBound)) { coorIsInside = true; su2double oneMinT = 1.0 - parCoor[2]; - if(fabs(oneMinT) < 1.e-10) { - if(oneMinT < 0.0) oneMinT = -1.e-10; - else oneMinT = 1.e-10; + if (fabs(oneMinT) < 1.e-10) { + if (oneMinT < 0.0) + oneMinT = -1.e-10; + else + oneMinT = 1.e-10; } - const su2double oneMinTInv = 1.0/oneMinT; - - const su2double omr = (1.0-parCoor[2]-2.0*parCoor[0]); - const su2double opr = (1.0-parCoor[2]+2.0*parCoor[0]); - const su2double oms = (1.0-parCoor[2]-2.0*parCoor[1]); - const su2double ops = (1.0-parCoor[2]+2.0*parCoor[1]); - - weightsInterpol[0] = 0.125*oneMinTInv*omr*oms; - weightsInterpol[1] = 0.125*oneMinTInv*opr*oms; - weightsInterpol[2] = 0.125*oneMinTInv*opr*ops; - weightsInterpol[3] = 0.125*oneMinTInv*omr*ops; - weightsInterpol[4] = 0.5*(1.0+parCoor[2]); + const su2double oneMinTInv = 1.0 / oneMinT; + + const su2double omr = (1.0 - parCoor[2] - 2.0 * parCoor[0]); + const su2double opr = (1.0 - parCoor[2] + 2.0 * parCoor[0]); + const su2double oms = (1.0 - parCoor[2] - 2.0 * parCoor[1]); + const su2double ops = (1.0 - parCoor[2] + 2.0 * parCoor[1]); + + weightsInterpol[0] = 0.125 * oneMinTInv * omr * oms; + weightsInterpol[1] = 0.125 * oneMinTInv * opr * oms; + weightsInterpol[2] = 0.125 * oneMinTInv * opr * ops; + weightsInterpol[3] = 0.125 * oneMinTInv * omr * ops; + weightsInterpol[4] = 0.5 * (1.0 + parCoor[2]); } } @@ -1054,9 +1051,8 @@ bool CADTElemClass::CoorInPyramid(const unsigned long elemID, return coorIsInside; } -bool CADTElemClass::InitialGuessContainmentPyramid(const su2double xRelC[3], - const su2double xRel[5][3], - su2double *parCoor) const { +bool CADTElemClass::InitialGuessContainmentPyramid(const su2double xRelC[3], const su2double xRel[5][3], + su2double* parCoor) const { /* Tetrahedron, 0-1-3-4. Create the coordinates of the tetrahedron and of the point. */ su2double x1 = xRel[1][0], y1 = xRel[1][1], z1 = xRel[1][2]; @@ -1066,35 +1062,44 @@ bool CADTElemClass::InitialGuessContainmentPyramid(const su2double xRelC[3], su2double xc = xRelC[0], yc = xRelC[1], zc = xRelC[2]; /* Determine the parametric coordinates inside this tetrahedron. */ - su2double detInv = 2.0/(x1*y2*z3 - x1*y3*z2 - x2*y1*z3 + x2*y3*z1 + x3*y1*z2 - x3*y2*z1); - parCoor[0] = detInv*(x2*y3*zc - x2*yc*z3 - x3*y2*zc + x3*yc*z2 + xc*y2*z3 - xc*y3*z2) - 1.0; - parCoor[1] = -detInv*(x1*y3*zc - x1*yc*z3 - x3*y1*zc + x3*yc*z1 + xc*y1*z3 - xc*y3*z1) - 1.0; - parCoor[2] = detInv*(x1*y2*zc - x1*yc*z2 - x2*y1*zc + x2*yc*z1 + xc*y1*z2 - xc*y2*z1) - 1.0; + su2double detInv = 2.0 / (x1 * y2 * z3 - x1 * y3 * z2 - x2 * y1 * z3 + x2 * y3 * z1 + x3 * y1 * z2 - x3 * y2 * z1); + parCoor[0] = detInv * (x2 * y3 * zc - x2 * yc * z3 - x3 * y2 * zc + x3 * yc * z2 + xc * y2 * z3 - xc * y3 * z2) - 1.0; + parCoor[1] = + -detInv * (x1 * y3 * zc - x1 * yc * z3 - x3 * y1 * zc + x3 * yc * z1 + xc * y1 * z3 - xc * y3 * z1) - 1.0; + parCoor[2] = detInv * (x1 * y2 * zc - x1 * yc * z2 - x2 * y1 * zc + x2 * yc * z1 + xc * y1 * z2 - xc * y2 * z1) - 1.0; /* If the point is inside this tetrahedron, return true. */ - if((parCoor[0] >= paramLowerBound) && (parCoor[1] >= paramLowerBound) && - (parCoor[2] >= paramLowerBound) && - ((parCoor[0]+parCoor[1]+parCoor[2]) <= paramLowerBound)) return true; + if ((parCoor[0] >= paramLowerBound) && (parCoor[1] >= paramLowerBound) && (parCoor[2] >= paramLowerBound) && + ((parCoor[0] + parCoor[1] + parCoor[2]) <= paramLowerBound)) + return true; /* Tetrahedron, 2-3-1-4. Create the coordinates of the tetrahedron and of the point. */ - x1 = xRel[3][0]-xRel[2][0]; y1 = xRel[3][1]-xRel[2][1]; z1 = xRel[3][2]-xRel[2][2]; - x2 = xRel[1][0]-xRel[2][0]; y2 = xRel[1][1]-xRel[2][1]; z2 = xRel[1][2]-xRel[2][2]; - x3 = xRel[4][0]-xRel[2][0]; y3 = xRel[4][1]-xRel[2][1]; z3 = xRel[4][2]-xRel[2][2]; - - xc = xRelC[0]-xRel[2][0]; yc = xRelC[1]-xRel[2][1]; zc = xRelC[2]-xRel[2][2]; + x1 = xRel[3][0] - xRel[2][0]; + y1 = xRel[3][1] - xRel[2][1]; + z1 = xRel[3][2] - xRel[2][2]; + x2 = xRel[1][0] - xRel[2][0]; + y2 = xRel[1][1] - xRel[2][1]; + z2 = xRel[1][2] - xRel[2][2]; + x3 = xRel[4][0] - xRel[2][0]; + y3 = xRel[4][1] - xRel[2][1]; + z3 = xRel[4][2] - xRel[2][2]; + + xc = xRelC[0] - xRel[2][0]; + yc = xRelC[1] - xRel[2][1]; + zc = xRelC[2] - xRel[2][2]; /* Determine the parametric coordinates inside this tetrahedron. */ - detInv = 2.0/(x1*y2*z3 - x1*y3*z2 - x2*y1*z3 + x2*y3*z1 + x3*y1*z2 - x3*y2*z1); - parCoor[0] = detInv*(x2*y3*zc - x2*yc*z3 - x3*y2*zc + x3*yc*z2 + xc*y2*z3 - xc*y3*z2) - 1.0; - parCoor[1] = -detInv*(x1*y3*zc - x1*yc*z3 - x3*y1*zc + x3*yc*z1 + xc*y1*z3 - xc*y3*z1) - 1.0; - parCoor[2] = detInv*(x1*y2*zc - x1*yc*z2 - x2*y1*zc + x2*yc*z1 + xc*y1*z2 - xc*y2*z1) - 1.0; + detInv = 2.0 / (x1 * y2 * z3 - x1 * y3 * z2 - x2 * y1 * z3 + x2 * y3 * z1 + x3 * y1 * z2 - x3 * y2 * z1); + parCoor[0] = detInv * (x2 * y3 * zc - x2 * yc * z3 - x3 * y2 * zc + x3 * yc * z2 + xc * y2 * z3 - xc * y3 * z2) - 1.0; + parCoor[1] = + -detInv * (x1 * y3 * zc - x1 * yc * z3 - x3 * y1 * zc + x3 * yc * z1 + xc * y1 * z3 - xc * y3 * z1) - 1.0; + parCoor[2] = detInv * (x1 * y2 * zc - x1 * yc * z2 - x2 * y1 * zc + x2 * yc * z1 + xc * y1 * z2 - xc * y2 * z1) - 1.0; /* If the point is inside this tetrahedron, adapt the parametric coordinates to the real pyramid and return true. */ - if((parCoor[0] >= paramLowerBound) && (parCoor[1] >= paramLowerBound) && - (parCoor[2] >= paramLowerBound) && - ((parCoor[0]+parCoor[1]+parCoor[2]) <= paramLowerBound)) { + if ((parCoor[0] >= paramLowerBound) && (parCoor[1] >= paramLowerBound) && (parCoor[2] >= paramLowerBound) && + ((parCoor[0] + parCoor[1] + parCoor[2]) <= paramLowerBound)) { parCoor[0] = 1.0 - parCoor[0]; parCoor[1] = 1.0 - parCoor[1]; return true; @@ -1102,23 +1107,31 @@ bool CADTElemClass::InitialGuessContainmentPyramid(const su2double xRelC[3], /* Tetrahedron, 1-2-0-4. Create the coordinates of the tetrahedron and of the point. */ - x1 = xRel[2][0]-xRel[1][0]; y1 = xRel[2][1]-xRel[1][1]; z1 = xRel[2][2]-xRel[1][2]; - x2 = xRel[0][0]-xRel[1][0]; y2 = xRel[0][1]-xRel[1][1]; z2 = xRel[0][2]-xRel[1][2]; - x3 = xRel[4][0]-xRel[1][0]; y3 = xRel[4][1]-xRel[1][1]; z3 = xRel[4][2]-xRel[1][2]; - - xc = xRelC[0]-xRel[1][0]; yc = xRelC[1]-xRel[1][1]; zc = xRelC[2]-xRel[1][2]; + x1 = xRel[2][0] - xRel[1][0]; + y1 = xRel[2][1] - xRel[1][1]; + z1 = xRel[2][2] - xRel[1][2]; + x2 = xRel[0][0] - xRel[1][0]; + y2 = xRel[0][1] - xRel[1][1]; + z2 = xRel[0][2] - xRel[1][2]; + x3 = xRel[4][0] - xRel[1][0]; + y3 = xRel[4][1] - xRel[1][1]; + z3 = xRel[4][2] - xRel[1][2]; + + xc = xRelC[0] - xRel[1][0]; + yc = xRelC[1] - xRel[1][1]; + zc = xRelC[2] - xRel[1][2]; /* Determine the parametric coordinates inside this tetrahedron. */ - detInv = 2.0/(x1*y2*z3 - x1*y3*z2 - x2*y1*z3 + x2*y3*z1 + x3*y1*z2 - x3*y2*z1); - parCoor[0] = detInv*(x2*y3*zc - x2*yc*z3 - x3*y2*zc + x3*yc*z2 + xc*y2*z3 - xc*y3*z2) - 1.0; - parCoor[1] = -detInv*(x1*y3*zc - x1*yc*z3 - x3*y1*zc + x3*yc*z1 + xc*y1*z3 - xc*y3*z1) - 1.0; - parCoor[2] = detInv*(x1*y2*zc - x1*yc*z2 - x2*y1*zc + x2*yc*z1 + xc*y1*z2 - xc*y2*z1) - 1.0; + detInv = 2.0 / (x1 * y2 * z3 - x1 * y3 * z2 - x2 * y1 * z3 + x2 * y3 * z1 + x3 * y1 * z2 - x3 * y2 * z1); + parCoor[0] = detInv * (x2 * y3 * zc - x2 * yc * z3 - x3 * y2 * zc + x3 * yc * z2 + xc * y2 * z3 - xc * y3 * z2) - 1.0; + parCoor[1] = + -detInv * (x1 * y3 * zc - x1 * yc * z3 - x3 * y1 * zc + x3 * yc * z1 + xc * y1 * z3 - xc * y3 * z1) - 1.0; + parCoor[2] = detInv * (x1 * y2 * zc - x1 * yc * z2 - x2 * y1 * zc + x2 * yc * z1 + xc * y1 * z2 - xc * y2 * z1) - 1.0; /* If the point is inside this tetrahedron, adapt the parametric coordinates to the real pyramid and return true. */ - if((parCoor[0] >= paramLowerBound) && (parCoor[1] >= paramLowerBound) && - (parCoor[2] >= paramLowerBound) && - ((parCoor[0]+parCoor[1]+parCoor[2]) <= paramLowerBound)) { + if ((parCoor[0] >= paramLowerBound) && (parCoor[1] >= paramLowerBound) && (parCoor[2] >= paramLowerBound) && + ((parCoor[0] + parCoor[1] + parCoor[2]) <= paramLowerBound)) { const su2double r = parCoor[0]; parCoor[0] = 1.0 - parCoor[1]; parCoor[1] = r; @@ -1127,23 +1140,31 @@ bool CADTElemClass::InitialGuessContainmentPyramid(const su2double xRelC[3], /* Tetrahedron, 3-0-2-4. Create the coordinates of the tetrahedron and of the point. */ - x1 = xRel[0][0]-xRel[3][0]; y1 = xRel[0][1]-xRel[3][1]; z1 = xRel[0][2]-xRel[3][2]; - x2 = xRel[2][0]-xRel[3][0]; y2 = xRel[2][1]-xRel[3][1]; z2 = xRel[2][2]-xRel[3][2]; - x3 = xRel[4][0]-xRel[3][0]; y3 = xRel[4][1]-xRel[3][1]; z3 = xRel[4][2]-xRel[3][2]; - - xc = xRelC[0]-xRel[3][0]; yc = xRelC[1]-xRel[3][1]; zc = xRelC[2]-xRel[3][2]; + x1 = xRel[0][0] - xRel[3][0]; + y1 = xRel[0][1] - xRel[3][1]; + z1 = xRel[0][2] - xRel[3][2]; + x2 = xRel[2][0] - xRel[3][0]; + y2 = xRel[2][1] - xRel[3][1]; + z2 = xRel[2][2] - xRel[3][2]; + x3 = xRel[4][0] - xRel[3][0]; + y3 = xRel[4][1] - xRel[3][1]; + z3 = xRel[4][2] - xRel[3][2]; + + xc = xRelC[0] - xRel[3][0]; + yc = xRelC[1] - xRel[3][1]; + zc = xRelC[2] - xRel[3][2]; /* Determine the parametric coordinates inside this tetrahedron. */ - detInv = 2.0/(x1*y2*z3 - x1*y3*z2 - x2*y1*z3 + x2*y3*z1 + x3*y1*z2 - x3*y2*z1); - parCoor[0] = detInv*(x2*y3*zc - x2*yc*z3 - x3*y2*zc + x3*yc*z2 + xc*y2*z3 - xc*y3*z2) - 1.0; - parCoor[1] = -detInv*(x1*y3*zc - x1*yc*z3 - x3*y1*zc + x3*yc*z1 + xc*y1*z3 - xc*y3*z1) - 1.0; - parCoor[2] = detInv*(x1*y2*zc - x1*yc*z2 - x2*y1*zc + x2*yc*z1 + xc*y1*z2 - xc*y2*z1) - 1.0; + detInv = 2.0 / (x1 * y2 * z3 - x1 * y3 * z2 - x2 * y1 * z3 + x2 * y3 * z1 + x3 * y1 * z2 - x3 * y2 * z1); + parCoor[0] = detInv * (x2 * y3 * zc - x2 * yc * z3 - x3 * y2 * zc + x3 * yc * z2 + xc * y2 * z3 - xc * y3 * z2) - 1.0; + parCoor[1] = + -detInv * (x1 * y3 * zc - x1 * yc * z3 - x3 * y1 * zc + x3 * yc * z1 + xc * y1 * z3 - xc * y3 * z1) - 1.0; + parCoor[2] = detInv * (x1 * y2 * zc - x1 * yc * z2 - x2 * y1 * zc + x2 * yc * z1 + xc * y1 * z2 - xc * y2 * z1) - 1.0; /* If the point is inside this tetrahedron, adapt the parametric coordinates to the real pyramid and return true. */ - if((parCoor[0] >= paramLowerBound) && (parCoor[1] >= paramLowerBound) && - (parCoor[2] >= paramLowerBound) && - ((parCoor[0]+parCoor[1]+parCoor[2]) <= paramLowerBound)) { + if ((parCoor[0] >= paramLowerBound) && (parCoor[1] >= paramLowerBound) && (parCoor[2] >= paramLowerBound) && + ((parCoor[0] + parCoor[1] + parCoor[2]) <= paramLowerBound)) { const su2double r = parCoor[0]; parCoor[0] = parCoor[1]; parCoor[1] = 1.0 - r; @@ -1156,57 +1177,57 @@ bool CADTElemClass::InitialGuessContainmentPyramid(const su2double xRelC[3], return false; } -bool CADTElemClass::CoorInPrism(const unsigned long elemID, - const su2double *coor, - su2double *parCoor, - su2double *weightsInterpol) const { - +bool CADTElemClass::CoorInPrism(const unsigned long elemID, const su2double* coor, su2double* parCoor, + su2double* weightsInterpol) const { /* Definition of the maximum number of iterations in the Newton solver and the tolerance level. */ const unsigned short maxIt = 50; - const su2double tolNewton = 1.e-10; + const su2double tolNewton = 1.e-10; /* Determine the indices of the six vertices of the prism, multiplied by nDim (which is 3). This gives the position in the coordinate array where the coordinates of these points are stored. */ unsigned long i0 = nDOFsPerElem[elemID]; - unsigned long i1 = i0 + 1, i2 = i0 + 2, i3 = i0+3, i4 = i0+4, i5 = i0+5; - i0 = nDim*elemConns[i0]; i1 = nDim*elemConns[i1]; - i2 = nDim*elemConns[i2]; i3 = nDim*elemConns[i3]; - i4 = nDim*elemConns[i4]; i5 = nDim*elemConns[i5]; + unsigned long i1 = i0 + 1, i2 = i0 + 2, i3 = i0 + 3, i4 = i0 + 4, i5 = i0 + 5; + i0 = nDim * elemConns[i0]; + i1 = nDim * elemConns[i1]; + i2 = nDim * elemConns[i2]; + i3 = nDim * elemConns[i3]; + i4 = nDim * elemConns[i4]; + i5 = nDim * elemConns[i5]; /* Determine the coordinates relative to the vertex 0. */ su2double xRel[6][3], xc[3]; xc[0] = coor[0] - coorPoints[i0]; - xc[1] = coor[1] - coorPoints[i0+1]; - xc[2] = coor[2] - coorPoints[i0+2]; + xc[1] = coor[1] - coorPoints[i0 + 1]; + xc[2] = coor[2] - coorPoints[i0 + 2]; xRel[0][0] = xRel[0][1] = xRel[0][2] = 0.0; - xRel[1][0] = coorPoints[i1] - coorPoints[i0]; - xRel[1][1] = coorPoints[i1+1] - coorPoints[i0+1]; - xRel[1][2] = coorPoints[i1+2] - coorPoints[i0+2]; + xRel[1][0] = coorPoints[i1] - coorPoints[i0]; + xRel[1][1] = coorPoints[i1 + 1] - coorPoints[i0 + 1]; + xRel[1][2] = coorPoints[i1 + 2] - coorPoints[i0 + 2]; - xRel[2][0] = coorPoints[i2] - coorPoints[i0]; - xRel[2][1] = coorPoints[i2+1] - coorPoints[i0+1]; - xRel[2][2] = coorPoints[i2+2] - coorPoints[i0+2]; + xRel[2][0] = coorPoints[i2] - coorPoints[i0]; + xRel[2][1] = coorPoints[i2 + 1] - coorPoints[i0 + 1]; + xRel[2][2] = coorPoints[i2 + 2] - coorPoints[i0 + 2]; - xRel[3][0] = coorPoints[i3] - coorPoints[i0]; - xRel[3][1] = coorPoints[i3+1] - coorPoints[i0+1]; - xRel[3][2] = coorPoints[i3+2] - coorPoints[i0+2]; + xRel[3][0] = coorPoints[i3] - coorPoints[i0]; + xRel[3][1] = coorPoints[i3 + 1] - coorPoints[i0 + 1]; + xRel[3][2] = coorPoints[i3 + 2] - coorPoints[i0 + 2]; - xRel[4][0] = coorPoints[i4] - coorPoints[i0]; - xRel[4][1] = coorPoints[i4+1] - coorPoints[i0+1]; - xRel[4][2] = coorPoints[i4+2] - coorPoints[i0+2]; + xRel[4][0] = coorPoints[i4] - coorPoints[i0]; + xRel[4][1] = coorPoints[i4 + 1] - coorPoints[i0 + 1]; + xRel[4][2] = coorPoints[i4 + 2] - coorPoints[i0 + 2]; - xRel[5][0] = coorPoints[i5] - coorPoints[i0]; - xRel[5][1] = coorPoints[i5+1] - coorPoints[i0+1]; - xRel[5][2] = coorPoints[i5+2] - coorPoints[i0+2]; + xRel[5][0] = coorPoints[i5] - coorPoints[i0]; + xRel[5][1] = coorPoints[i5 + 1] - coorPoints[i0 + 1]; + xRel[5][2] = coorPoints[i5 + 2] - coorPoints[i0 + 2]; /* Obtain an initial guess of the parametric coordinates by splitting the prism into tetrahedra. If this approach is not successful, this means that the point is not inside the true prism and false can be returned. */ - if( !InitialGuessContainmentPrism(xc, xRel, parCoor) ) return false; + if (!InitialGuessContainmentPrism(xc, xRel, parCoor)) return false; /* The prism is parametrized by X-X0 = (Xi-X0)*li, where the sum runs over i = 0..5, although i = 0 does not give a contribution. The Lagrangian @@ -1220,63 +1241,62 @@ bool CADTElemClass::CoorInPrism(const unsigned long elemID, V0 = xc - (x1+x2+x4+x5)/4, V1 = (x1+x4-x3)/4, V2 = (x2+x5-x3)/4, V3 = (x4+x5-x1-x2)/4, V4 = (x4-x1-x3)/4, V5 = (x5-x2-x3)/4. First construct these vectors. */ - const su2double V0x = xc[0] - 0.25*(xRel[1][0]+xRel[2][0]+xRel[4][0]+xRel[5][0]); - const su2double V0y = xc[1] - 0.25*(xRel[1][1]+xRel[2][1]+xRel[4][1]+xRel[5][1]); - const su2double V0z = xc[2] - 0.25*(xRel[1][2]+xRel[2][2]+xRel[4][2]+xRel[5][2]); + const su2double V0x = xc[0] - 0.25 * (xRel[1][0] + xRel[2][0] + xRel[4][0] + xRel[5][0]); + const su2double V0y = xc[1] - 0.25 * (xRel[1][1] + xRel[2][1] + xRel[4][1] + xRel[5][1]); + const su2double V0z = xc[2] - 0.25 * (xRel[1][2] + xRel[2][2] + xRel[4][2] + xRel[5][2]); - const su2double V1x = 0.25*(xRel[1][0]+xRel[4][0]-xRel[3][0]); - const su2double V1y = 0.25*(xRel[1][1]+xRel[4][1]-xRel[3][1]); - const su2double V1z = 0.25*(xRel[1][2]+xRel[4][2]-xRel[3][2]); + const su2double V1x = 0.25 * (xRel[1][0] + xRel[4][0] - xRel[3][0]); + const su2double V1y = 0.25 * (xRel[1][1] + xRel[4][1] - xRel[3][1]); + const su2double V1z = 0.25 * (xRel[1][2] + xRel[4][2] - xRel[3][2]); - const su2double V2x = 0.25*(xRel[2][0]+xRel[5][0]-xRel[3][0]); - const su2double V2y = 0.25*(xRel[2][1]+xRel[5][1]-xRel[3][1]); - const su2double V2z = 0.25*(xRel[2][2]+xRel[5][2]-xRel[3][2]); + const su2double V2x = 0.25 * (xRel[2][0] + xRel[5][0] - xRel[3][0]); + const su2double V2y = 0.25 * (xRel[2][1] + xRel[5][1] - xRel[3][1]); + const su2double V2z = 0.25 * (xRel[2][2] + xRel[5][2] - xRel[3][2]); - const su2double V3x = 0.25*(xRel[4][0]+xRel[5][0]-xRel[1][0]-xRel[2][0]); - const su2double V3y = 0.25*(xRel[4][1]+xRel[5][1]-xRel[1][1]-xRel[2][1]); - const su2double V3z = 0.25*(xRel[4][2]+xRel[5][2]-xRel[1][2]-xRel[2][2]); + const su2double V3x = 0.25 * (xRel[4][0] + xRel[5][0] - xRel[1][0] - xRel[2][0]); + const su2double V3y = 0.25 * (xRel[4][1] + xRel[5][1] - xRel[1][1] - xRel[2][1]); + const su2double V3z = 0.25 * (xRel[4][2] + xRel[5][2] - xRel[1][2] - xRel[2][2]); - const su2double V4x = 0.25*(xRel[4][0]-xRel[1][0]-xRel[3][0]); - const su2double V4y = 0.25*(xRel[4][1]-xRel[1][1]-xRel[3][1]); - const su2double V4z = 0.25*(xRel[4][2]-xRel[1][2]-xRel[3][2]); + const su2double V4x = 0.25 * (xRel[4][0] - xRel[1][0] - xRel[3][0]); + const su2double V4y = 0.25 * (xRel[4][1] - xRel[1][1] - xRel[3][1]); + const su2double V4z = 0.25 * (xRel[4][2] - xRel[1][2] - xRel[3][2]); - const su2double V5x = 0.25*(xRel[5][0]-xRel[2][0]-xRel[3][0]); - const su2double V5y = 0.25*(xRel[5][1]-xRel[2][1]-xRel[3][1]); - const su2double V5z = 0.25*(xRel[5][2]-xRel[2][2]-xRel[3][2]); + const su2double V5x = 0.25 * (xRel[5][0] - xRel[2][0] - xRel[3][0]); + const su2double V5y = 0.25 * (xRel[5][1] - xRel[2][1] - xRel[3][1]); + const su2double V5z = 0.25 * (xRel[5][2] - xRel[2][2] - xRel[3][2]); /* Loop over the maximum number of iterations. */ unsigned short itCount; - for(itCount=0; itCount= paramLowerBound) && (parCoor[1] >= paramLowerBound) && - ((parCoor[0]+parCoor[1]) <= tolInsideElem) && - (parCoor[2] >= paramLowerBound) && (parCoor[2] <= paramUpperBound)) { + if ((parCoor[0] >= paramLowerBound) && (parCoor[1] >= paramLowerBound) && + ((parCoor[0] + parCoor[1]) <= tolInsideElem) && (parCoor[2] >= paramLowerBound) && + (parCoor[2] <= paramUpperBound)) { coorIsInside = true; - const su2double omt = 0.25*(1.0-parCoor[2]), opt = 0.25*(1.0+parCoor[2]); + const su2double omt = 0.25 * (1.0 - parCoor[2]), opt = 0.25 * (1.0 + parCoor[2]); - weightsInterpol[0] = -omt*(parCoor[0]+parCoor[1]); - weightsInterpol[1] = omt*(parCoor[0]+1.0); - weightsInterpol[2] = omt*(parCoor[1]+1.0); - weightsInterpol[3] = -opt*(parCoor[0]+parCoor[1]); - weightsInterpol[4] = opt*(parCoor[0]+1.0); - weightsInterpol[5] = opt*(parCoor[1]+1.0); + weightsInterpol[0] = -omt * (parCoor[0] + parCoor[1]); + weightsInterpol[1] = omt * (parCoor[0] + 1.0); + weightsInterpol[2] = omt * (parCoor[1] + 1.0); + weightsInterpol[3] = -opt * (parCoor[0] + parCoor[1]); + weightsInterpol[4] = opt * (parCoor[0] + 1.0); + weightsInterpol[5] = opt * (parCoor[1] + 1.0); } /* Return the value of coorIsInside. */ return coorIsInside; } -bool CADTElemClass::InitialGuessContainmentPrism(const su2double xRelC[3], - const su2double xRel[6][3], - su2double *parCoor) const { - +bool CADTElemClass::InitialGuessContainmentPrism(const su2double xRelC[3], const su2double xRel[6][3], + su2double* parCoor) const { /* Tetrahedron, 0-1-2-3. Create the coordinates of the tetrahedron and of the point. */ su2double x1 = xRel[1][0], y1 = xRel[1][1], z1 = xRel[1][2]; @@ -1327,126 +1344,175 @@ bool CADTElemClass::InitialGuessContainmentPrism(const su2double xRelC[3], su2double xc = xRelC[0], yc = xRelC[1], zc = xRelC[2]; /* Determine the parametric coordinates inside this tetrahedron. */ - su2double detInv = 2.0/(x1*y2*z3 - x1*y3*z2 - x2*y1*z3 + x2*y3*z1 + x3*y1*z2 - x3*y2*z1); - su2double r = detInv*(x2*y3*zc - x2*yc*z3 - x3*y2*zc + x3*yc*z2 + xc*y2*z3 - xc*y3*z2) - 1.0; - su2double s = -detInv*(x1*y3*zc - x1*yc*z3 - x3*y1*zc + x3*yc*z1 + xc*y1*z3 - xc*y3*z1) - 1.0; - su2double t = detInv*(x1*y2*zc - x1*yc*z2 - x2*y1*zc + x2*yc*z1 + xc*y1*z2 - xc*y2*z1) - 1.0; + su2double detInv = 2.0 / (x1 * y2 * z3 - x1 * y3 * z2 - x2 * y1 * z3 + x2 * y3 * z1 + x3 * y1 * z2 - x3 * y2 * z1); + su2double r = + detInv * (x2 * y3 * zc - x2 * yc * z3 - x3 * y2 * zc + x3 * yc * z2 + xc * y2 * z3 - xc * y3 * z2) - 1.0; + su2double s = + -detInv * (x1 * y3 * zc - x1 * yc * z3 - x3 * y1 * zc + x3 * yc * z1 + xc * y1 * z3 - xc * y3 * z1) - 1.0; + su2double t = + detInv * (x1 * y2 * zc - x1 * yc * z2 - x2 * y1 * zc + x2 * yc * z1 + xc * y1 * z2 - xc * y2 * z1) - 1.0; /* If the point is inside this tetrahedron, set the parametric coordinates for the real prism and return true. */ - if((r >= paramLowerBound) && (s >= paramLowerBound) && (t >= paramLowerBound) && - ((r+s+t) <= paramLowerBound)) { - parCoor[0] = r; parCoor[1] = s; parCoor[2] = t; + if ((r >= paramLowerBound) && (s >= paramLowerBound) && (t >= paramLowerBound) && ((r + s + t) <= paramLowerBound)) { + parCoor[0] = r; + parCoor[1] = s; + parCoor[2] = t; return true; } /* Tetrahedron, 4-1-3-2. Create the coordinates of the tetrahedron and of the point. */ - x1 = xRel[1][0]-xRel[4][0]; y1 = xRel[1][1]-xRel[4][1]; z1 = xRel[1][2]-xRel[4][2]; - x2 = xRel[3][0]-xRel[4][0]; y2 = xRel[3][1]-xRel[4][1]; z2 = xRel[3][2]-xRel[4][2]; - x3 = xRel[2][0]-xRel[4][0]; y3 = xRel[2][1]-xRel[4][1]; z3 = xRel[2][2]-xRel[4][2]; - - xc = xRelC[0]-xRel[4][0]; yc = xRelC[1]-xRel[4][1]; zc = xRelC[2]-xRel[4][2]; + x1 = xRel[1][0] - xRel[4][0]; + y1 = xRel[1][1] - xRel[4][1]; + z1 = xRel[1][2] - xRel[4][2]; + x2 = xRel[3][0] - xRel[4][0]; + y2 = xRel[3][1] - xRel[4][1]; + z2 = xRel[3][2] - xRel[4][2]; + x3 = xRel[2][0] - xRel[4][0]; + y3 = xRel[2][1] - xRel[4][1]; + z3 = xRel[2][2] - xRel[4][2]; + + xc = xRelC[0] - xRel[4][0]; + yc = xRelC[1] - xRel[4][1]; + zc = xRelC[2] - xRel[4][2]; /* Determine the parametric coordinates inside this tetrahedron. */ - detInv = 2.0/(x1*y2*z3 - x1*y3*z2 - x2*y1*z3 + x2*y3*z1 + x3*y1*z2 - x3*y2*z1); - r = detInv*(x2*y3*zc - x2*yc*z3 - x3*y2*zc + x3*yc*z2 + xc*y2*z3 - xc*y3*z2) - 1.0; - s = -detInv*(x1*y3*zc - x1*yc*z3 - x3*y1*zc + x3*yc*z1 + xc*y1*z3 - xc*y3*z1) - 1.0; - t = detInv*(x1*y2*zc - x1*yc*z2 - x2*y1*zc + x2*yc*z1 + xc*y1*z2 - xc*y2*z1) - 1.0; + detInv = 2.0 / (x1 * y2 * z3 - x1 * y3 * z2 - x2 * y1 * z3 + x2 * y3 * z1 + x3 * y1 * z2 - x3 * y2 * z1); + r = detInv * (x2 * y3 * zc - x2 * yc * z3 - x3 * y2 * zc + x3 * yc * z2 + xc * y2 * z3 - xc * y3 * z2) - 1.0; + s = -detInv * (x1 * y3 * zc - x1 * yc * z3 - x3 * y1 * zc + x3 * yc * z1 + xc * y1 * z3 - xc * y3 * z1) - 1.0; + t = detInv * (x1 * y2 * zc - x1 * yc * z2 - x2 * y1 * zc + x2 * yc * z1 + xc * y1 * z2 - xc * y2 * z1) - 1.0; /* If the point is inside this tetrahedron, set the parametric coordinates for the real prism and return true. */ - if((r >= paramLowerBound) && (s >= paramLowerBound) && (t >= paramLowerBound) && - ((r+s+t) <= paramLowerBound)) { - parCoor[0] = 1.0 - s; parCoor[1] = t; parCoor[2] = 1.0 - r; + if ((r >= paramLowerBound) && (s >= paramLowerBound) && (t >= paramLowerBound) && ((r + s + t) <= paramLowerBound)) { + parCoor[0] = 1.0 - s; + parCoor[1] = t; + parCoor[2] = 1.0 - r; return true; } /* Tetrahedron, 3-5-4-2. Create the coordinates of the tetrahedron and of the point. */ - x1 = xRel[5][0]-xRel[3][0]; y1 = xRel[5][1]-xRel[3][1]; z1 = xRel[5][2]-xRel[3][2]; - x2 = xRel[4][0]-xRel[3][0]; y2 = xRel[4][1]-xRel[3][1]; z2 = xRel[4][2]-xRel[3][2]; - x3 = xRel[2][0]-xRel[3][0]; y3 = xRel[2][1]-xRel[3][1]; z3 = xRel[2][2]-xRel[3][2]; - - xc = xRelC[0]-xRel[3][0]; yc = xRelC[1]-xRel[3][1]; zc = xRelC[2]-xRel[3][2]; + x1 = xRel[5][0] - xRel[3][0]; + y1 = xRel[5][1] - xRel[3][1]; + z1 = xRel[5][2] - xRel[3][2]; + x2 = xRel[4][0] - xRel[3][0]; + y2 = xRel[4][1] - xRel[3][1]; + z2 = xRel[4][2] - xRel[3][2]; + x3 = xRel[2][0] - xRel[3][0]; + y3 = xRel[2][1] - xRel[3][1]; + z3 = xRel[2][2] - xRel[3][2]; + + xc = xRelC[0] - xRel[3][0]; + yc = xRelC[1] - xRel[3][1]; + zc = xRelC[2] - xRel[3][2]; /* Determine the parametric coordinates inside this tetrahedron. */ - detInv = 2.0/(x1*y2*z3 - x1*y3*z2 - x2*y1*z3 + x2*y3*z1 + x3*y1*z2 - x3*y2*z1); - r = detInv*(x2*y3*zc - x2*yc*z3 - x3*y2*zc + x3*yc*z2 + xc*y2*z3 - xc*y3*z2) - 1.0; - s = -detInv*(x1*y3*zc - x1*yc*z3 - x3*y1*zc + x3*yc*z1 + xc*y1*z3 - xc*y3*z1) - 1.0; - t = detInv*(x1*y2*zc - x1*yc*z2 - x2*y1*zc + x2*yc*z1 + xc*y1*z2 - xc*y2*z1) - 1.0; + detInv = 2.0 / (x1 * y2 * z3 - x1 * y3 * z2 - x2 * y1 * z3 + x2 * y3 * z1 + x3 * y1 * z2 - x3 * y2 * z1); + r = detInv * (x2 * y3 * zc - x2 * yc * z3 - x3 * y2 * zc + x3 * yc * z2 + xc * y2 * z3 - xc * y3 * z2) - 1.0; + s = -detInv * (x1 * y3 * zc - x1 * yc * z3 - x3 * y1 * zc + x3 * yc * z1 + xc * y1 * z3 - xc * y3 * z1) - 1.0; + t = detInv * (x1 * y2 * zc - x1 * yc * z2 - x2 * y1 * zc + x2 * yc * z1 + xc * y1 * z2 - xc * y2 * z1) - 1.0; /* If the point is inside this tetrahedron, set the parametric coordinates for the real prism and return true. */ - if((r >= paramLowerBound) && (s >= paramLowerBound) && (t >= paramLowerBound) && - ((r+s+t) <= paramLowerBound)) { - parCoor[0] = s; parCoor[1] = r; parCoor[2] = 1.0 - t; + if ((r >= paramLowerBound) && (s >= paramLowerBound) && (t >= paramLowerBound) && ((r + s + t) <= paramLowerBound)) { + parCoor[0] = s; + parCoor[1] = r; + parCoor[2] = 1.0 - t; return true; } /* Tetrahedron, 3-5-4-0. Create the coordinates of the tetrahedron and of the point. */ - x1 = xRel[5][0]-xRel[3][0]; y1 = xRel[5][1]-xRel[3][1]; z1 = xRel[5][2]-xRel[3][2]; - x2 = xRel[4][0]-xRel[3][0]; y2 = xRel[4][1]-xRel[3][1]; z2 = xRel[4][2]-xRel[3][2]; - x3 = xRel[0][0]-xRel[3][0]; y3 = xRel[0][1]-xRel[3][1]; z3 = xRel[0][2]-xRel[3][2]; - - xc = xRelC[0]-xRel[3][0]; yc = xRelC[1]-xRel[3][1]; zc = xRelC[2]-xRel[3][2]; + x1 = xRel[5][0] - xRel[3][0]; + y1 = xRel[5][1] - xRel[3][1]; + z1 = xRel[5][2] - xRel[3][2]; + x2 = xRel[4][0] - xRel[3][0]; + y2 = xRel[4][1] - xRel[3][1]; + z2 = xRel[4][2] - xRel[3][2]; + x3 = xRel[0][0] - xRel[3][0]; + y3 = xRel[0][1] - xRel[3][1]; + z3 = xRel[0][2] - xRel[3][2]; + + xc = xRelC[0] - xRel[3][0]; + yc = xRelC[1] - xRel[3][1]; + zc = xRelC[2] - xRel[3][2]; /* Determine the parametric coordinates inside this tetrahedron. */ - detInv = 2.0/(x1*y2*z3 - x1*y3*z2 - x2*y1*z3 + x2*y3*z1 + x3*y1*z2 - x3*y2*z1); - r = detInv*(x2*y3*zc - x2*yc*z3 - x3*y2*zc + x3*yc*z2 + xc*y2*z3 - xc*y3*z2) - 1.0; - s = -detInv*(x1*y3*zc - x1*yc*z3 - x3*y1*zc + x3*yc*z1 + xc*y1*z3 - xc*y3*z1) - 1.0; - t = detInv*(x1*y2*zc - x1*yc*z2 - x2*y1*zc + x2*yc*z1 + xc*y1*z2 - xc*y2*z1) - 1.0; + detInv = 2.0 / (x1 * y2 * z3 - x1 * y3 * z2 - x2 * y1 * z3 + x2 * y3 * z1 + x3 * y1 * z2 - x3 * y2 * z1); + r = detInv * (x2 * y3 * zc - x2 * yc * z3 - x3 * y2 * zc + x3 * yc * z2 + xc * y2 * z3 - xc * y3 * z2) - 1.0; + s = -detInv * (x1 * y3 * zc - x1 * yc * z3 - x3 * y1 * zc + x3 * yc * z1 + xc * y1 * z3 - xc * y3 * z1) - 1.0; + t = detInv * (x1 * y2 * zc - x1 * yc * z2 - x2 * y1 * zc + x2 * yc * z1 + xc * y1 * z2 - xc * y2 * z1) - 1.0; /* If the point is inside this tetrahedron, set the parametric coordinates for the real prism and return true. */ - if((r >= paramLowerBound) && (s >= paramLowerBound) && (t >= paramLowerBound) && - ((r+s+t) <= paramLowerBound)) { - parCoor[0] = s; parCoor[1] = r; parCoor[2] = 1.0 - t; + if ((r >= paramLowerBound) && (s >= paramLowerBound) && (t >= paramLowerBound) && ((r + s + t) <= paramLowerBound)) { + parCoor[0] = s; + parCoor[1] = r; + parCoor[2] = 1.0 - t; return true; } /* Tetrahedron, 1-0-4-5. Create the coordinates of the tetrahedron and of the point. */ - x1 = xRel[0][0]-xRel[1][0]; y1 = xRel[0][1]-xRel[1][1]; z1 = xRel[0][2]-xRel[1][2]; - x2 = xRel[4][0]-xRel[1][0]; y2 = xRel[4][1]-xRel[1][1]; z2 = xRel[4][2]-xRel[1][2]; - x3 = xRel[5][0]-xRel[1][0]; y3 = xRel[5][1]-xRel[1][1]; z3 = xRel[5][2]-xRel[1][2]; - - xc = xRelC[0]-xRel[1][0]; yc = xRelC[1]-xRel[1][1]; zc = xRelC[2]-xRel[1][2]; + x1 = xRel[0][0] - xRel[1][0]; + y1 = xRel[0][1] - xRel[1][1]; + z1 = xRel[0][2] - xRel[1][2]; + x2 = xRel[4][0] - xRel[1][0]; + y2 = xRel[4][1] - xRel[1][1]; + z2 = xRel[4][2] - xRel[1][2]; + x3 = xRel[5][0] - xRel[1][0]; + y3 = xRel[5][1] - xRel[1][1]; + z3 = xRel[5][2] - xRel[1][2]; + + xc = xRelC[0] - xRel[1][0]; + yc = xRelC[1] - xRel[1][1]; + zc = xRelC[2] - xRel[1][2]; /* Determine the parametric coordinates inside this tetrahedron. */ - detInv = 2.0/(x1*y2*z3 - x1*y3*z2 - x2*y1*z3 + x2*y3*z1 + x3*y1*z2 - x3*y2*z1); - r = detInv*(x2*y3*zc - x2*yc*z3 - x3*y2*zc + x3*yc*z2 + xc*y2*z3 - xc*y3*z2) - 1.0; - s = -detInv*(x1*y3*zc - x1*yc*z3 - x3*y1*zc + x3*yc*z1 + xc*y1*z3 - xc*y3*z1) - 1.0; - t = detInv*(x1*y2*zc - x1*yc*z2 - x2*y1*zc + x2*yc*z1 + xc*y1*z2 - xc*y2*z1) - 1.0; + detInv = 2.0 / (x1 * y2 * z3 - x1 * y3 * z2 - x2 * y1 * z3 + x2 * y3 * z1 + x3 * y1 * z2 - x3 * y2 * z1); + r = detInv * (x2 * y3 * zc - x2 * yc * z3 - x3 * y2 * zc + x3 * yc * z2 + xc * y2 * z3 - xc * y3 * z2) - 1.0; + s = -detInv * (x1 * y3 * zc - x1 * yc * z3 - x3 * y1 * zc + x3 * yc * z1 + xc * y1 * z3 - xc * y3 * z1) - 1.0; + t = detInv * (x1 * y2 * zc - x1 * yc * z2 - x2 * y1 * zc + x2 * yc * z1 + xc * y1 * z2 - xc * y2 * z1) - 1.0; /* If the point is inside this tetrahedron, set the parametric coordinates for the real prism and return true. */ - if((r >= paramLowerBound) && (s >= paramLowerBound) && (t >= paramLowerBound) && - ((r+s+t) <= paramLowerBound)) { - parCoor[0] = 1.0 - r; parCoor[1] = t; parCoor[2] = s; + if ((r >= paramLowerBound) && (s >= paramLowerBound) && (t >= paramLowerBound) && ((r + s + t) <= paramLowerBound)) { + parCoor[0] = 1.0 - r; + parCoor[1] = t; + parCoor[2] = s; return true; } /* Tetrahedron, 0-1-2-5. Create the coordinates of the tetrahedron and of the point. */ - x1 = xRel[1][0]; y1 = xRel[1][1]; z1 = xRel[1][2]; - x2 = xRel[2][0]; y2 = xRel[2][1]; z2 = xRel[2][2]; - x3 = xRel[5][0]; y3 = xRel[5][1]; z3 = xRel[5][2]; - - xc = xRelC[0]; yc = xRelC[1]; zc = xRelC[2]; + x1 = xRel[1][0]; + y1 = xRel[1][1]; + z1 = xRel[1][2]; + x2 = xRel[2][0]; + y2 = xRel[2][1]; + z2 = xRel[2][2]; + x3 = xRel[5][0]; + y3 = xRel[5][1]; + z3 = xRel[5][2]; + + xc = xRelC[0]; + yc = xRelC[1]; + zc = xRelC[2]; /* Determine the parametric coordinates inside this tetrahedron. */ - detInv = 2.0/(x1*y2*z3 - x1*y3*z2 - x2*y1*z3 + x2*y3*z1 + x3*y1*z2 - x3*y2*z1); - r = detInv*(x2*y3*zc - x2*yc*z3 - x3*y2*zc + x3*yc*z2 + xc*y2*z3 - xc*y3*z2) - 1.0; - s = -detInv*(x1*y3*zc - x1*yc*z3 - x3*y1*zc + x3*yc*z1 + xc*y1*z3 - xc*y3*z1) - 1.0; - t = detInv*(x1*y2*zc - x1*yc*z2 - x2*y1*zc + x2*yc*z1 + xc*y1*z2 - xc*y2*z1) - 1.0; + detInv = 2.0 / (x1 * y2 * z3 - x1 * y3 * z2 - x2 * y1 * z3 + x2 * y3 * z1 + x3 * y1 * z2 - x3 * y2 * z1); + r = detInv * (x2 * y3 * zc - x2 * yc * z3 - x3 * y2 * zc + x3 * yc * z2 + xc * y2 * z3 - xc * y3 * z2) - 1.0; + s = -detInv * (x1 * y3 * zc - x1 * yc * z3 - x3 * y1 * zc + x3 * yc * z1 + xc * y1 * z3 - xc * y3 * z1) - 1.0; + t = detInv * (x1 * y2 * zc - x1 * yc * z2 - x2 * y1 * zc + x2 * yc * z1 + xc * y1 * z2 - xc * y2 * z1) - 1.0; /* If the point is inside this tetrahedron, set the parametric coordinates for the real prism and return true. */ - if((r >= paramLowerBound) && (s >= paramLowerBound) && (t >= paramLowerBound) && - ((r+s+t) <= paramLowerBound)) { - parCoor[0] = r; parCoor[1] = s; parCoor[2] = t; + if ((r >= paramLowerBound) && (s >= paramLowerBound) && (t >= paramLowerBound) && ((r + s + t) <= paramLowerBound)) { + parCoor[0] = r; + parCoor[1] = s; + parCoor[2] = t; return true; } @@ -1456,66 +1522,67 @@ bool CADTElemClass::InitialGuessContainmentPrism(const su2double xRelC[3], return false; } -bool CADTElemClass::CoorInHexahedron(const unsigned long elemID, - const su2double *coor, - su2double *parCoor, - su2double *weightsInterpol) const { - +bool CADTElemClass::CoorInHexahedron(const unsigned long elemID, const su2double* coor, su2double* parCoor, + su2double* weightsInterpol) const { /* Definition of the maximum number of iterations in the Newton solver and the tolerance level. */ const unsigned short maxIt = 50; - const su2double tolNewton = 1.e-10; + const su2double tolNewton = 1.e-10; /* Determine the indices of the eight vertices of the hexahedron, multiplied by nDim (which is 3). This gives the position in the coordinate array where the coordinates of these points are stored. */ unsigned long i0 = nDOFsPerElem[elemID]; - unsigned long i1 = i0 + 1, i2 = i0 + 2, i3 = i0+3, i4 = i0+4, i5 = i0+5, i6 = i0+6, i7 = i0+7; - i0 = nDim*elemConns[i0]; i1 = nDim*elemConns[i1]; - i2 = nDim*elemConns[i2]; i3 = nDim*elemConns[i3]; - i4 = nDim*elemConns[i4]; i5 = nDim*elemConns[i5]; - i6 = nDim*elemConns[i6]; i7 = nDim*elemConns[i7]; + unsigned long i1 = i0 + 1, i2 = i0 + 2, i3 = i0 + 3, i4 = i0 + 4, i5 = i0 + 5, i6 = i0 + 6, i7 = i0 + 7; + i0 = nDim * elemConns[i0]; + i1 = nDim * elemConns[i1]; + i2 = nDim * elemConns[i2]; + i3 = nDim * elemConns[i3]; + i4 = nDim * elemConns[i4]; + i5 = nDim * elemConns[i5]; + i6 = nDim * elemConns[i6]; + i7 = nDim * elemConns[i7]; /* Determine the coordinates relative to the vertex 0. */ su2double xRel[8][3], xc[3]; xc[0] = coor[0] - coorPoints[i0]; - xc[1] = coor[1] - coorPoints[i0+1]; - xc[2] = coor[2] - coorPoints[i0+2]; + xc[1] = coor[1] - coorPoints[i0 + 1]; + xc[2] = coor[2] - coorPoints[i0 + 2]; xRel[0][0] = xRel[0][1] = xRel[0][2] = 0.0; - xRel[1][0] = coorPoints[i1] - coorPoints[i0]; - xRel[1][1] = coorPoints[i1+1] - coorPoints[i0+1]; - xRel[1][2] = coorPoints[i1+2] - coorPoints[i0+2]; + xRel[1][0] = coorPoints[i1] - coorPoints[i0]; + xRel[1][1] = coorPoints[i1 + 1] - coorPoints[i0 + 1]; + xRel[1][2] = coorPoints[i1 + 2] - coorPoints[i0 + 2]; - xRel[2][0] = coorPoints[i2] - coorPoints[i0]; - xRel[2][1] = coorPoints[i2+1] - coorPoints[i0+1]; - xRel[2][2] = coorPoints[i2+2] - coorPoints[i0+2]; + xRel[2][0] = coorPoints[i2] - coorPoints[i0]; + xRel[2][1] = coorPoints[i2 + 1] - coorPoints[i0 + 1]; + xRel[2][2] = coorPoints[i2 + 2] - coorPoints[i0 + 2]; - xRel[3][0] = coorPoints[i3] - coorPoints[i0]; - xRel[3][1] = coorPoints[i3+1] - coorPoints[i0+1]; - xRel[3][2] = coorPoints[i3+2] - coorPoints[i0+2]; + xRel[3][0] = coorPoints[i3] - coorPoints[i0]; + xRel[3][1] = coorPoints[i3 + 1] - coorPoints[i0 + 1]; + xRel[3][2] = coorPoints[i3 + 2] - coorPoints[i0 + 2]; - xRel[4][0] = coorPoints[i4] - coorPoints[i0]; - xRel[4][1] = coorPoints[i4+1] - coorPoints[i0+1]; - xRel[4][2] = coorPoints[i4+2] - coorPoints[i0+2]; + xRel[4][0] = coorPoints[i4] - coorPoints[i0]; + xRel[4][1] = coorPoints[i4 + 1] - coorPoints[i0 + 1]; + xRel[4][2] = coorPoints[i4 + 2] - coorPoints[i0 + 2]; - xRel[5][0] = coorPoints[i5] - coorPoints[i0]; - xRel[5][1] = coorPoints[i5+1] - coorPoints[i0+1]; - xRel[5][2] = coorPoints[i5+2] - coorPoints[i0+2]; + xRel[5][0] = coorPoints[i5] - coorPoints[i0]; + xRel[5][1] = coorPoints[i5 + 1] - coorPoints[i0 + 1]; + xRel[5][2] = coorPoints[i5 + 2] - coorPoints[i0 + 2]; - xRel[6][0] = coorPoints[i6] - coorPoints[i0]; - xRel[6][1] = coorPoints[i6+1] - coorPoints[i0+1]; - xRel[6][2] = coorPoints[i6+2] - coorPoints[i0+2]; + xRel[6][0] = coorPoints[i6] - coorPoints[i0]; + xRel[6][1] = coorPoints[i6 + 1] - coorPoints[i0 + 1]; + xRel[6][2] = coorPoints[i6 + 2] - coorPoints[i0 + 2]; - xRel[7][0] = coorPoints[i7] - coorPoints[i0]; - xRel[7][1] = coorPoints[i7+1] - coorPoints[i0+1]; - xRel[7][2] = coorPoints[i7+2] - coorPoints[i0+2]; + xRel[7][0] = coorPoints[i7] - coorPoints[i0]; + xRel[7][1] = coorPoints[i7 + 1] - coorPoints[i0 + 1]; + xRel[7][2] = coorPoints[i7 + 2] - coorPoints[i0 + 2]; /* Obtain an initial guess of the parametric coordinates by splitting the hexahedron into tetrahedra. If this approach is not successful, this means that the point is not inside the true hexahedron and false can be returned. */ - if( !InitialGuessContainmentHexahedron(xc, xRel, parCoor) ) return false; + if (!InitialGuessContainmentHexahedron(xc, xRel, parCoor)) return false; /* The hexahedron is parametrized by X-X0 = (Xi-X0)*li, where the sum runs over i = 0..7, although i = 0 does not give a contribution. The Lagrangian @@ -1533,74 +1600,97 @@ bool CADTElemClass::CoorInHexahedron(const unsigned long elemID, V4 = (x2+x4+x6-x1-x3-x5-x7)/8, V5 = (x3+x5+x6-x1-x2-x4-x7)/8, V6 = (x1+x6+x7-x2-x3-x4-x5)/8, V7 = (x1+x3+x4+x6-x2-x5-x7)/8. First construct these vectors. */ - const su2double V0x = xc[0] - 0.125*(xRel[1][0]+xRel[2][0]+xRel[3][0]+xRel[4][0]+xRel[5][0]+xRel[6][0]+xRel[7][0]); - const su2double V0y = xc[1] - 0.125*(xRel[1][1]+xRel[2][1]+xRel[3][1]+xRel[4][1]+xRel[5][1]+xRel[6][1]+xRel[7][1]); - const su2double V0z = xc[2] - 0.125*(xRel[1][2]+xRel[2][2]+xRel[3][2]+xRel[4][2]+xRel[5][2]+xRel[6][2]+xRel[7][2]); - - const su2double V1x = 0.125*(xRel[1][0]+xRel[2][0]-xRel[3][0]-xRel[4][0]+xRel[5][0]+xRel[6][0]-xRel[7][0]); - const su2double V1y = 0.125*(xRel[1][1]+xRel[2][1]-xRel[3][1]-xRel[4][1]+xRel[5][1]+xRel[6][1]-xRel[7][1]); - const su2double V1z = 0.125*(xRel[1][2]+xRel[2][2]-xRel[3][2]-xRel[4][2]+xRel[5][2]+xRel[6][2]-xRel[7][2]); - - const su2double V2x = 0.125*(xRel[2][0]+xRel[3][0]-xRel[1][0]-xRel[4][0]-xRel[5][0]+xRel[6][0]+xRel[7][0]); - const su2double V2y = 0.125*(xRel[2][1]+xRel[3][1]-xRel[1][1]-xRel[4][1]-xRel[5][1]+xRel[6][1]+xRel[7][1]); - const su2double V2z = 0.125*(xRel[2][2]+xRel[3][2]-xRel[1][2]-xRel[4][2]-xRel[5][2]+xRel[6][2]+xRel[7][2]); - - const su2double V3x = 0.125*(xRel[4][0]+xRel[5][0]+xRel[6][0]+xRel[7][0]-xRel[1][0]-xRel[2][0]-xRel[3][0]); - const su2double V3y = 0.125*(xRel[4][1]+xRel[5][1]+xRel[6][1]+xRel[7][1]-xRel[1][1]-xRel[2][1]-xRel[3][1]); - const su2double V3z = 0.125*(xRel[4][2]+xRel[5][2]+xRel[6][2]+xRel[7][2]-xRel[1][2]-xRel[2][2]-xRel[3][2]); - - const su2double V4x = 0.125*(xRel[2][0]+xRel[4][0]+xRel[6][0]-xRel[1][0]-xRel[3][0]-xRel[5][0]-xRel[7][0]); - const su2double V4y = 0.125*(xRel[2][1]+xRel[4][1]+xRel[6][1]-xRel[1][1]-xRel[3][1]-xRel[5][1]-xRel[7][1]); - const su2double V4z = 0.125*(xRel[2][2]+xRel[4][2]+xRel[6][2]-xRel[1][2]-xRel[3][2]-xRel[5][2]-xRel[7][2]); - - const su2double V5x = 0.125*(xRel[3][0]+xRel[5][0]+xRel[6][0]-xRel[1][0]-xRel[2][0]-xRel[4][0]-xRel[7][0]); - const su2double V5y = 0.125*(xRel[3][1]+xRel[5][1]+xRel[6][1]-xRel[1][1]-xRel[2][1]-xRel[4][1]-xRel[7][1]); - const su2double V5z = 0.125*(xRel[3][2]+xRel[5][2]+xRel[6][2]-xRel[1][2]-xRel[2][2]-xRel[4][2]-xRel[7][2]); - - const su2double V6x = 0.125*(xRel[1][0]+xRel[6][0]+xRel[7][0]-xRel[2][0]-xRel[3][0]-xRel[4][0]-xRel[5][0]); - const su2double V6y = 0.125*(xRel[1][1]+xRel[6][1]+xRel[7][1]-xRel[2][1]-xRel[3][1]-xRel[4][1]-xRel[5][1]); - const su2double V6z = 0.125*(xRel[1][2]+xRel[6][2]+xRel[7][2]-xRel[2][2]-xRel[3][2]-xRel[4][2]-xRel[5][2]); - - const su2double V7x = 0.125*(xRel[1][0]+xRel[3][0]+xRel[4][0]+xRel[6][0]-xRel[2][0]-xRel[5][0]-xRel[7][0]); - const su2double V7y = 0.125*(xRel[1][1]+xRel[3][1]+xRel[4][1]+xRel[6][1]-xRel[2][1]-xRel[5][1]-xRel[7][1]); - const su2double V7z = 0.125*(xRel[1][2]+xRel[3][2]+xRel[4][2]+xRel[6][2]-xRel[2][2]-xRel[5][2]-xRel[7][2]); + const su2double V0x = + xc[0] - 0.125 * (xRel[1][0] + xRel[2][0] + xRel[3][0] + xRel[4][0] + xRel[5][0] + xRel[6][0] + xRel[7][0]); + const su2double V0y = + xc[1] - 0.125 * (xRel[1][1] + xRel[2][1] + xRel[3][1] + xRel[4][1] + xRel[5][1] + xRel[6][1] + xRel[7][1]); + const su2double V0z = + xc[2] - 0.125 * (xRel[1][2] + xRel[2][2] + xRel[3][2] + xRel[4][2] + xRel[5][2] + xRel[6][2] + xRel[7][2]); + + const su2double V1x = + 0.125 * (xRel[1][0] + xRel[2][0] - xRel[3][0] - xRel[4][0] + xRel[5][0] + xRel[6][0] - xRel[7][0]); + const su2double V1y = + 0.125 * (xRel[1][1] + xRel[2][1] - xRel[3][1] - xRel[4][1] + xRel[5][1] + xRel[6][1] - xRel[7][1]); + const su2double V1z = + 0.125 * (xRel[1][2] + xRel[2][2] - xRel[3][2] - xRel[4][2] + xRel[5][2] + xRel[6][2] - xRel[7][2]); + + const su2double V2x = + 0.125 * (xRel[2][0] + xRel[3][0] - xRel[1][0] - xRel[4][0] - xRel[5][0] + xRel[6][0] + xRel[7][0]); + const su2double V2y = + 0.125 * (xRel[2][1] + xRel[3][1] - xRel[1][1] - xRel[4][1] - xRel[5][1] + xRel[6][1] + xRel[7][1]); + const su2double V2z = + 0.125 * (xRel[2][2] + xRel[3][2] - xRel[1][2] - xRel[4][2] - xRel[5][2] + xRel[6][2] + xRel[7][2]); + + const su2double V3x = + 0.125 * (xRel[4][0] + xRel[5][0] + xRel[6][0] + xRel[7][0] - xRel[1][0] - xRel[2][0] - xRel[3][0]); + const su2double V3y = + 0.125 * (xRel[4][1] + xRel[5][1] + xRel[6][1] + xRel[7][1] - xRel[1][1] - xRel[2][1] - xRel[3][1]); + const su2double V3z = + 0.125 * (xRel[4][2] + xRel[5][2] + xRel[6][2] + xRel[7][2] - xRel[1][2] - xRel[2][2] - xRel[3][2]); + + const su2double V4x = + 0.125 * (xRel[2][0] + xRel[4][0] + xRel[6][0] - xRel[1][0] - xRel[3][0] - xRel[5][0] - xRel[7][0]); + const su2double V4y = + 0.125 * (xRel[2][1] + xRel[4][1] + xRel[6][1] - xRel[1][1] - xRel[3][1] - xRel[5][1] - xRel[7][1]); + const su2double V4z = + 0.125 * (xRel[2][2] + xRel[4][2] + xRel[6][2] - xRel[1][2] - xRel[3][2] - xRel[5][2] - xRel[7][2]); + + const su2double V5x = + 0.125 * (xRel[3][0] + xRel[5][0] + xRel[6][0] - xRel[1][0] - xRel[2][0] - xRel[4][0] - xRel[7][0]); + const su2double V5y = + 0.125 * (xRel[3][1] + xRel[5][1] + xRel[6][1] - xRel[1][1] - xRel[2][1] - xRel[4][1] - xRel[7][1]); + const su2double V5z = + 0.125 * (xRel[3][2] + xRel[5][2] + xRel[6][2] - xRel[1][2] - xRel[2][2] - xRel[4][2] - xRel[7][2]); + + const su2double V6x = + 0.125 * (xRel[1][0] + xRel[6][0] + xRel[7][0] - xRel[2][0] - xRel[3][0] - xRel[4][0] - xRel[5][0]); + const su2double V6y = + 0.125 * (xRel[1][1] + xRel[6][1] + xRel[7][1] - xRel[2][1] - xRel[3][1] - xRel[4][1] - xRel[5][1]); + const su2double V6z = + 0.125 * (xRel[1][2] + xRel[6][2] + xRel[7][2] - xRel[2][2] - xRel[3][2] - xRel[4][2] - xRel[5][2]); + + const su2double V7x = + 0.125 * (xRel[1][0] + xRel[3][0] + xRel[4][0] + xRel[6][0] - xRel[2][0] - xRel[5][0] - xRel[7][0]); + const su2double V7y = + 0.125 * (xRel[1][1] + xRel[3][1] + xRel[4][1] + xRel[6][1] - xRel[2][1] - xRel[5][1] - xRel[7][1]); + const su2double V7z = + 0.125 * (xRel[1][2] + xRel[3][2] + xRel[4][2] + xRel[6][2] - xRel[2][2] - xRel[5][2] - xRel[7][2]); /* Loop over the maximum number of iterations. */ unsigned short itCount; - for(itCount=0; itCount= paramLowerBound) && (parCoor[0] <= paramUpperBound) && - (parCoor[1] >= paramLowerBound) && (parCoor[1] <= paramUpperBound) && - (parCoor[2] >= paramLowerBound) && (parCoor[2] <= paramUpperBound)) { + if ((parCoor[0] >= paramLowerBound) && (parCoor[0] <= paramUpperBound) && (parCoor[1] >= paramLowerBound) && + (parCoor[1] <= paramUpperBound) && (parCoor[2] >= paramLowerBound) && (parCoor[2] <= paramUpperBound)) { coorIsInside = true; - const su2double omr = 0.5*(1.0-parCoor[0]), opr = 0.5*(1.0+parCoor[0]); - const su2double oms = 0.5*(1.0-parCoor[1]), ops = 0.5*(1.0+parCoor[1]); - const su2double omt = 0.5*(1.0-parCoor[2]), opt = 0.5*(1.0+parCoor[2]); - - weightsInterpol[0] = omr*oms*omt; - weightsInterpol[1] = opr*oms*omt; - weightsInterpol[2] = opr*ops*omt; - weightsInterpol[3] = omr*ops*omt; - weightsInterpol[4] = omr*oms*opt; - weightsInterpol[5] = opr*oms*opt; - weightsInterpol[6] = opr*ops*opt; - weightsInterpol[7] = omr*ops*opt; + const su2double omr = 0.5 * (1.0 - parCoor[0]), opr = 0.5 * (1.0 + parCoor[0]); + const su2double oms = 0.5 * (1.0 - parCoor[1]), ops = 0.5 * (1.0 + parCoor[1]); + const su2double omt = 0.5 * (1.0 - parCoor[2]), opt = 0.5 * (1.0 + parCoor[2]); + + weightsInterpol[0] = omr * oms * omt; + weightsInterpol[1] = opr * oms * omt; + weightsInterpol[2] = opr * ops * omt; + weightsInterpol[3] = omr * ops * omt; + weightsInterpol[4] = omr * oms * opt; + weightsInterpol[5] = opr * oms * opt; + weightsInterpol[6] = opr * ops * opt; + weightsInterpol[7] = omr * ops * opt; } /* Return the value of coorIsInside. */ return coorIsInside; } -bool CADTElemClass::InitialGuessContainmentHexahedron(const su2double xRelC[3], - const su2double xRel[8][3], - su2double *parCoor) const { +bool CADTElemClass::InitialGuessContainmentHexahedron(const su2double xRelC[3], const su2double xRel[8][3], + su2double* parCoor) const { /* Tetrahedron, 0-1-2-5. Create the coordinates of the tetrahedron and of the point. */ su2double x1 = xRel[1][0], y1 = xRel[1][1], z1 = xRel[1][2]; @@ -1654,214 +1741,299 @@ bool CADTElemClass::InitialGuessContainmentHexahedron(const su2double xRelC[3], su2double xc = xRelC[0], yc = xRelC[1], zc = xRelC[2]; /* Determine the parametric coordinates inside this tetrahedron. */ - su2double detInv = 2.0/(x1*y2*z3 - x1*y3*z2 - x2*y1*z3 + x2*y3*z1 + x3*y1*z2 - x3*y2*z1); - su2double r = detInv*(x2*y3*zc - x2*yc*z3 - x3*y2*zc + x3*yc*z2 + xc*y2*z3 - xc*y3*z2) - 1.0; - su2double s = -detInv*(x1*y3*zc - x1*yc*z3 - x3*y1*zc + x3*yc*z1 + xc*y1*z3 - xc*y3*z1) - 1.0; - su2double t = detInv*(x1*y2*zc - x1*yc*z2 - x2*y1*zc + x2*yc*z1 + xc*y1*z2 - xc*y2*z1) - 1.0; + su2double detInv = 2.0 / (x1 * y2 * z3 - x1 * y3 * z2 - x2 * y1 * z3 + x2 * y3 * z1 + x3 * y1 * z2 - x3 * y2 * z1); + su2double r = + detInv * (x2 * y3 * zc - x2 * yc * z3 - x3 * y2 * zc + x3 * yc * z2 + xc * y2 * z3 - xc * y3 * z2) - 1.0; + su2double s = + -detInv * (x1 * y3 * zc - x1 * yc * z3 - x3 * y1 * zc + x3 * yc * z1 + xc * y1 * z3 - xc * y3 * z1) - 1.0; + su2double t = + detInv * (x1 * y2 * zc - x1 * yc * z2 - x2 * y1 * zc + x2 * yc * z1 + xc * y1 * z2 - xc * y2 * z1) - 1.0; /* If the point is inside this tetrahedron, set the parametric coordinates for the real hexahedron and return true. */ - if((r >= paramLowerBound) && (s >= paramLowerBound) && (t >= paramLowerBound) && - ((r+s+t) <= paramLowerBound)) { - parCoor[0] = r; parCoor[1] = s; parCoor[2] = t; + if ((r >= paramLowerBound) && (s >= paramLowerBound) && (t >= paramLowerBound) && ((r + s + t) <= paramLowerBound)) { + parCoor[0] = r; + parCoor[1] = s; + parCoor[2] = t; return true; } /* Tetrahedron, 4-7-5-0. Create the coordinates of the tetrahedron and of the point. */ - x1 = xRel[7][0]-xRel[4][0]; y1 = xRel[7][1]-xRel[4][1]; z1 = xRel[7][2]-xRel[4][2]; - x2 = xRel[5][0]-xRel[4][0]; y2 = xRel[5][1]-xRel[4][1]; z2 = xRel[5][2]-xRel[4][2]; - x3 = xRel[0][0]-xRel[4][0]; y3 = xRel[0][1]-xRel[4][1]; z3 = xRel[0][2]-xRel[4][2]; - - xc = xRelC[0]-xRel[4][0]; yc = xRelC[1]-xRel[4][1]; zc = xRelC[2]-xRel[4][2]; + x1 = xRel[7][0] - xRel[4][0]; + y1 = xRel[7][1] - xRel[4][1]; + z1 = xRel[7][2] - xRel[4][2]; + x2 = xRel[5][0] - xRel[4][0]; + y2 = xRel[5][1] - xRel[4][1]; + z2 = xRel[5][2] - xRel[4][2]; + x3 = xRel[0][0] - xRel[4][0]; + y3 = xRel[0][1] - xRel[4][1]; + z3 = xRel[0][2] - xRel[4][2]; + + xc = xRelC[0] - xRel[4][0]; + yc = xRelC[1] - xRel[4][1]; + zc = xRelC[2] - xRel[4][2]; /* Determine the parametric coordinates inside this tetrahedron. */ - detInv = 2.0/(x1*y2*z3 - x1*y3*z2 - x2*y1*z3 + x2*y3*z1 + x3*y1*z2 - x3*y2*z1); - r = detInv*(x2*y3*zc - x2*yc*z3 - x3*y2*zc + x3*yc*z2 + xc*y2*z3 - xc*y3*z2) - 1.0; - s = -detInv*(x1*y3*zc - x1*yc*z3 - x3*y1*zc + x3*yc*z1 + xc*y1*z3 - xc*y3*z1) - 1.0; - t = detInv*(x1*y2*zc - x1*yc*z2 - x2*y1*zc + x2*yc*z1 + xc*y1*z2 - xc*y2*z1) - 1.0; + detInv = 2.0 / (x1 * y2 * z3 - x1 * y3 * z2 - x2 * y1 * z3 + x2 * y3 * z1 + x3 * y1 * z2 - x3 * y2 * z1); + r = detInv * (x2 * y3 * zc - x2 * yc * z3 - x3 * y2 * zc + x3 * yc * z2 + xc * y2 * z3 - xc * y3 * z2) - 1.0; + s = -detInv * (x1 * y3 * zc - x1 * yc * z3 - x3 * y1 * zc + x3 * yc * z1 + xc * y1 * z3 - xc * y3 * z1) - 1.0; + t = detInv * (x1 * y2 * zc - x1 * yc * z2 - x2 * y1 * zc + x2 * yc * z1 + xc * y1 * z2 - xc * y2 * z1) - 1.0; /* If the point is inside this tetrahedron, set the parametric coordinates for the real hexahedron and return true. */ - if((r >= paramLowerBound) && (s >= paramLowerBound) && (t >= paramLowerBound) && - ((r+s+t) <= paramLowerBound)) { - parCoor[0] = s; parCoor[1] = r; parCoor[2] = 1.0 - t; + if ((r >= paramLowerBound) && (s >= paramLowerBound) && (t >= paramLowerBound) && ((r + s + t) <= paramLowerBound)) { + parCoor[0] = s; + parCoor[1] = r; + parCoor[2] = 1.0 - t; return true; } /* Tetrahedron, 6-7-5-2. Create the coordinates of the tetrahedron and of the point. */ - x1 = xRel[7][0]-xRel[6][0]; y1 = xRel[7][1]-xRel[6][1]; z1 = xRel[7][2]-xRel[6][2]; - x2 = xRel[5][0]-xRel[6][0]; y2 = xRel[5][1]-xRel[6][1]; z2 = xRel[5][2]-xRel[6][2]; - x3 = xRel[2][0]-xRel[6][0]; y3 = xRel[2][1]-xRel[6][1]; z3 = xRel[2][2]-xRel[6][2]; - - xc = xRelC[0]-xRel[6][0]; yc = xRelC[1]-xRel[6][1]; zc = xRelC[2]-xRel[6][2]; + x1 = xRel[7][0] - xRel[6][0]; + y1 = xRel[7][1] - xRel[6][1]; + z1 = xRel[7][2] - xRel[6][2]; + x2 = xRel[5][0] - xRel[6][0]; + y2 = xRel[5][1] - xRel[6][1]; + z2 = xRel[5][2] - xRel[6][2]; + x3 = xRel[2][0] - xRel[6][0]; + y3 = xRel[2][1] - xRel[6][1]; + z3 = xRel[2][2] - xRel[6][2]; + + xc = xRelC[0] - xRel[6][0]; + yc = xRelC[1] - xRel[6][1]; + zc = xRelC[2] - xRel[6][2]; /* Determine the parametric coordinates inside this tetrahedron. */ - detInv = 2.0/(x1*y2*z3 - x1*y3*z2 - x2*y1*z3 + x2*y3*z1 + x3*y1*z2 - x3*y2*z1); - r = detInv*(x2*y3*zc - x2*yc*z3 - x3*y2*zc + x3*yc*z2 + xc*y2*z3 - xc*y3*z2) - 1.0; - s = -detInv*(x1*y3*zc - x1*yc*z3 - x3*y1*zc + x3*yc*z1 + xc*y1*z3 - xc*y3*z1) - 1.0; - t = detInv*(x1*y2*zc - x1*yc*z2 - x2*y1*zc + x2*yc*z1 + xc*y1*z2 - xc*y2*z1) - 1.0; + detInv = 2.0 / (x1 * y2 * z3 - x1 * y3 * z2 - x2 * y1 * z3 + x2 * y3 * z1 + x3 * y1 * z2 - x3 * y2 * z1); + r = detInv * (x2 * y3 * zc - x2 * yc * z3 - x3 * y2 * zc + x3 * yc * z2 + xc * y2 * z3 - xc * y3 * z2) - 1.0; + s = -detInv * (x1 * y3 * zc - x1 * yc * z3 - x3 * y1 * zc + x3 * yc * z1 + xc * y1 * z3 - xc * y3 * z1) - 1.0; + t = detInv * (x1 * y2 * zc - x1 * yc * z2 - x2 * y1 * zc + x2 * yc * z1 + xc * y1 * z2 - xc * y2 * z1) - 1.0; /* If the point is inside this tetrahedron, set the parametric coordinates for the real hexahedron and return true. */ - if((r >= paramLowerBound) && (s >= paramLowerBound) && (t >= paramLowerBound) && - ((r+s+t) <= paramLowerBound)) { - parCoor[0] = 1.0 - s; parCoor[1] = 1.0 - r; parCoor[2] = 1.0 - t; + if ((r >= paramLowerBound) && (s >= paramLowerBound) && (t >= paramLowerBound) && ((r + s + t) <= paramLowerBound)) { + parCoor[0] = 1.0 - s; + parCoor[1] = 1.0 - r; + parCoor[2] = 1.0 - t; return true; } /* Tetrahedron, 3-0-2-7. Create the coordinates of the tetrahedron and of the point. */ - x1 = xRel[0][0]-xRel[3][0]; y1 = xRel[0][1]-xRel[3][1]; z1 = xRel[0][2]-xRel[3][2]; - x2 = xRel[2][0]-xRel[3][0]; y2 = xRel[2][1]-xRel[3][1]; z2 = xRel[2][2]-xRel[3][2]; - x3 = xRel[7][0]-xRel[3][0]; y3 = xRel[7][1]-xRel[3][1]; z3 = xRel[7][2]-xRel[3][2]; - - xc = xRelC[0]-xRel[3][0]; yc = xRelC[1]-xRel[3][1]; zc = xRelC[2]-xRel[3][2]; + x1 = xRel[0][0] - xRel[3][0]; + y1 = xRel[0][1] - xRel[3][1]; + z1 = xRel[0][2] - xRel[3][2]; + x2 = xRel[2][0] - xRel[3][0]; + y2 = xRel[2][1] - xRel[3][1]; + z2 = xRel[2][2] - xRel[3][2]; + x3 = xRel[7][0] - xRel[3][0]; + y3 = xRel[7][1] - xRel[3][1]; + z3 = xRel[7][2] - xRel[3][2]; + + xc = xRelC[0] - xRel[3][0]; + yc = xRelC[1] - xRel[3][1]; + zc = xRelC[2] - xRel[3][2]; /* Determine the parametric coordinates inside this tetrahedron. */ - detInv = 2.0/(x1*y2*z3 - x1*y3*z2 - x2*y1*z3 + x2*y3*z1 + x3*y1*z2 - x3*y2*z1); - r = detInv*(x2*y3*zc - x2*yc*z3 - x3*y2*zc + x3*yc*z2 + xc*y2*z3 - xc*y3*z2) - 1.0; - s = -detInv*(x1*y3*zc - x1*yc*z3 - x3*y1*zc + x3*yc*z1 + xc*y1*z3 - xc*y3*z1) - 1.0; - t = detInv*(x1*y2*zc - x1*yc*z2 - x2*y1*zc + x2*yc*z1 + xc*y1*z2 - xc*y2*z1) - 1.0; + detInv = 2.0 / (x1 * y2 * z3 - x1 * y3 * z2 - x2 * y1 * z3 + x2 * y3 * z1 + x3 * y1 * z2 - x3 * y2 * z1); + r = detInv * (x2 * y3 * zc - x2 * yc * z3 - x3 * y2 * zc + x3 * yc * z2 + xc * y2 * z3 - xc * y3 * z2) - 1.0; + s = -detInv * (x1 * y3 * zc - x1 * yc * z3 - x3 * y1 * zc + x3 * yc * z1 + xc * y1 * z3 - xc * y3 * z1) - 1.0; + t = detInv * (x1 * y2 * zc - x1 * yc * z2 - x2 * y1 * zc + x2 * yc * z1 + xc * y1 * z2 - xc * y2 * z1) - 1.0; /* If the point is inside this tetrahedron, set the parametric coordinates for the real hexahedron and return true. */ - if((r >= paramLowerBound) && (s >= paramLowerBound) && (t >= paramLowerBound) && - ((r+s+t) <= paramLowerBound)) { - parCoor[0] = 1.0 - s; parCoor[1] = r; parCoor[2] = 1.0 - t; + if ((r >= paramLowerBound) && (s >= paramLowerBound) && (t >= paramLowerBound) && ((r + s + t) <= paramLowerBound)) { + parCoor[0] = 1.0 - s; + parCoor[1] = r; + parCoor[2] = 1.0 - t; return true; } /* Tetrahedron, 0-5-2-7. Create the coordinates of the tetrahedron and of the point. */ - x1 = xRel[5][0]; y1 = xRel[5][1]; z1 = xRel[5][2]; - x2 = xRel[2][0]; y2 = xRel[2][1]; z2 = xRel[2][2]; - x3 = xRel[7][0]; y3 = xRel[7][1]; z3 = xRel[7][2]; - - xc = xRelC[0]; yc = xRelC[1]; zc = xRelC[2]; + x1 = xRel[5][0]; + y1 = xRel[5][1]; + z1 = xRel[5][2]; + x2 = xRel[2][0]; + y2 = xRel[2][1]; + z2 = xRel[2][2]; + x3 = xRel[7][0]; + y3 = xRel[7][1]; + z3 = xRel[7][2]; + + xc = xRelC[0]; + yc = xRelC[1]; + zc = xRelC[2]; /* Determine the parametric coordinates inside this tetrahedron. */ - detInv = 2.0/(x1*y2*z3 - x1*y3*z2 - x2*y1*z3 + x2*y3*z1 + x3*y1*z2 - x3*y2*z1); - r = detInv*(x2*y3*zc - x2*yc*z3 - x3*y2*zc + x3*yc*z2 + xc*y2*z3 - xc*y3*z2) - 1.0; - s = -detInv*(x1*y3*zc - x1*yc*z3 - x3*y1*zc + x3*yc*z1 + xc*y1*z3 - xc*y3*z1) - 1.0; - t = detInv*(x1*y2*zc - x1*yc*z2 - x2*y1*zc + x2*yc*z1 + xc*y1*z2 - xc*y2*z1) - 1.0; + detInv = 2.0 / (x1 * y2 * z3 - x1 * y3 * z2 - x2 * y1 * z3 + x2 * y3 * z1 + x3 * y1 * z2 - x3 * y2 * z1); + r = detInv * (x2 * y3 * zc - x2 * yc * z3 - x3 * y2 * zc + x3 * yc * z2 + xc * y2 * z3 - xc * y3 * z2) - 1.0; + s = -detInv * (x1 * y3 * zc - x1 * yc * z3 - x3 * y1 * zc + x3 * yc * z1 + xc * y1 * z3 - xc * y3 * z1) - 1.0; + t = detInv * (x1 * y2 * zc - x1 * yc * z2 - x2 * y1 * zc + x2 * yc * z1 + xc * y1 * z2 - xc * y2 * z1) - 1.0; /* If the point is inside this tetrahedron, set the parametric coordinates for the real hexahedron and return true. */ - if((r >= paramLowerBound) && (s >= paramLowerBound) && (t >= paramLowerBound) && - ((r+s+t) <= paramLowerBound)) { - parCoor[0] = 1.0+r+s; parCoor[1] = 1.0+s+t; parCoor[2] = 1.0+r+t; + if ((r >= paramLowerBound) && (s >= paramLowerBound) && (t >= paramLowerBound) && ((r + s + t) <= paramLowerBound)) { + parCoor[0] = 1.0 + r + s; + parCoor[1] = 1.0 + s + t; + parCoor[2] = 1.0 + r + t; return true; } /* Tetrahedron, 0-1-3-4. Create the coordinates of the tetrahedron and of the point. */ - x1 = xRel[1][0]; y1 = xRel[1][1]; z1 = xRel[1][2]; - x2 = xRel[3][0]; y2 = xRel[3][1]; z2 = xRel[3][2]; - x3 = xRel[4][0]; y3 = xRel[4][1]; z3 = xRel[4][2]; - - xc = xRelC[0]; yc = xRelC[1]; zc = xRelC[2]; + x1 = xRel[1][0]; + y1 = xRel[1][1]; + z1 = xRel[1][2]; + x2 = xRel[3][0]; + y2 = xRel[3][1]; + z2 = xRel[3][2]; + x3 = xRel[4][0]; + y3 = xRel[4][1]; + z3 = xRel[4][2]; + + xc = xRelC[0]; + yc = xRelC[1]; + zc = xRelC[2]; /* Determine the parametric coordinates inside this tetrahedron. */ - detInv = 2.0/(x1*y2*z3 - x1*y3*z2 - x2*y1*z3 + x2*y3*z1 + x3*y1*z2 - x3*y2*z1); - r = detInv*(x2*y3*zc - x2*yc*z3 - x3*y2*zc + x3*yc*z2 + xc*y2*z3 - xc*y3*z2) - 1.0; - s = -detInv*(x1*y3*zc - x1*yc*z3 - x3*y1*zc + x3*yc*z1 + xc*y1*z3 - xc*y3*z1) - 1.0; - t = detInv*(x1*y2*zc - x1*yc*z2 - x2*y1*zc + x2*yc*z1 + xc*y1*z2 - xc*y2*z1) - 1.0; + detInv = 2.0 / (x1 * y2 * z3 - x1 * y3 * z2 - x2 * y1 * z3 + x2 * y3 * z1 + x3 * y1 * z2 - x3 * y2 * z1); + r = detInv * (x2 * y3 * zc - x2 * yc * z3 - x3 * y2 * zc + x3 * yc * z2 + xc * y2 * z3 - xc * y3 * z2) - 1.0; + s = -detInv * (x1 * y3 * zc - x1 * yc * z3 - x3 * y1 * zc + x3 * yc * z1 + xc * y1 * z3 - xc * y3 * z1) - 1.0; + t = detInv * (x1 * y2 * zc - x1 * yc * z2 - x2 * y1 * zc + x2 * yc * z1 + xc * y1 * z2 - xc * y2 * z1) - 1.0; /* If the point is inside this tetrahedron, set the parametric coordinates for the real hexahedron and return true. */ - if((r >= paramLowerBound) && (s >= paramLowerBound) && (t >= paramLowerBound) && - ((r+s+t) <= paramLowerBound)) { - parCoor[0] = r; parCoor[1] = s; parCoor[2] = t; + if ((r >= paramLowerBound) && (s >= paramLowerBound) && (t >= paramLowerBound) && ((r + s + t) <= paramLowerBound)) { + parCoor[0] = r; + parCoor[1] = s; + parCoor[2] = t; return true; } /* Tetrahedron, 7-6-4-3. Create the coordinates of the tetrahedron and of the point. */ - x1 = xRel[6][0]-xRel[7][0]; y1 = xRel[6][1]-xRel[7][1]; z1 = xRel[6][2]-xRel[7][2]; - x2 = xRel[4][0]-xRel[7][0]; y2 = xRel[4][1]-xRel[7][1]; z2 = xRel[4][2]-xRel[7][2]; - x3 = xRel[3][0]-xRel[7][0]; y3 = xRel[3][1]-xRel[7][1]; z3 = xRel[3][2]-xRel[7][2]; - - xc = xRelC[0]-xRel[7][0]; yc = xRelC[1]-xRel[7][1]; zc = xRelC[2]-xRel[7][2]; + x1 = xRel[6][0] - xRel[7][0]; + y1 = xRel[6][1] - xRel[7][1]; + z1 = xRel[6][2] - xRel[7][2]; + x2 = xRel[4][0] - xRel[7][0]; + y2 = xRel[4][1] - xRel[7][1]; + z2 = xRel[4][2] - xRel[7][2]; + x3 = xRel[3][0] - xRel[7][0]; + y3 = xRel[3][1] - xRel[7][1]; + z3 = xRel[3][2] - xRel[7][2]; + + xc = xRelC[0] - xRel[7][0]; + yc = xRelC[1] - xRel[7][1]; + zc = xRelC[2] - xRel[7][2]; /* Determine the parametric coordinates inside this tetrahedron. */ - detInv = 2.0/(x1*y2*z3 - x1*y3*z2 - x2*y1*z3 + x2*y3*z1 + x3*y1*z2 - x3*y2*z1); - r = detInv*(x2*y3*zc - x2*yc*z3 - x3*y2*zc + x3*yc*z2 + xc*y2*z3 - xc*y3*z2) - 1.0; - s = -detInv*(x1*y3*zc - x1*yc*z3 - x3*y1*zc + x3*yc*z1 + xc*y1*z3 - xc*y3*z1) - 1.0; - t = detInv*(x1*y2*zc - x1*yc*z2 - x2*y1*zc + x2*yc*z1 + xc*y1*z2 - xc*y2*z1) - 1.0; + detInv = 2.0 / (x1 * y2 * z3 - x1 * y3 * z2 - x2 * y1 * z3 + x2 * y3 * z1 + x3 * y1 * z2 - x3 * y2 * z1); + r = detInv * (x2 * y3 * zc - x2 * yc * z3 - x3 * y2 * zc + x3 * yc * z2 + xc * y2 * z3 - xc * y3 * z2) - 1.0; + s = -detInv * (x1 * y3 * zc - x1 * yc * z3 - x3 * y1 * zc + x3 * yc * z1 + xc * y1 * z3 - xc * y3 * z1) - 1.0; + t = detInv * (x1 * y2 * zc - x1 * yc * z2 - x2 * y1 * zc + x2 * yc * z1 + xc * y1 * z2 - xc * y2 * z1) - 1.0; /* If the point is inside this tetrahedron, set the parametric coordinates for the real hexahedron and return true. */ - if((r >= paramLowerBound) && (s >= paramLowerBound) && (t >= paramLowerBound) && - ((r+s+t) <= paramLowerBound)) { - parCoor[0] = r; parCoor[1] = 1.0 - s; parCoor[2] = 1.0 - t; + if ((r >= paramLowerBound) && (s >= paramLowerBound) && (t >= paramLowerBound) && ((r + s + t) <= paramLowerBound)) { + parCoor[0] = r; + parCoor[1] = 1.0 - s; + parCoor[2] = 1.0 - t; return true; } /* Tetrahedron, 5-4-6-1. Create the coordinates of the tetrahedron and of the point. */ - x1 = xRel[4][0]-xRel[5][0]; y1 = xRel[4][1]-xRel[5][1]; z1 = xRel[4][2]-xRel[5][2]; - x2 = xRel[6][0]-xRel[5][0]; y2 = xRel[6][1]-xRel[5][1]; z2 = xRel[6][2]-xRel[5][2]; - x3 = xRel[1][0]-xRel[5][0]; y3 = xRel[1][1]-xRel[5][1]; z3 = xRel[1][2]-xRel[5][2]; - - xc = xRelC[0]-xRel[5][0]; yc = xRelC[1]-xRel[5][1]; zc = xRelC[2]-xRel[5][2]; + x1 = xRel[4][0] - xRel[5][0]; + y1 = xRel[4][1] - xRel[5][1]; + z1 = xRel[4][2] - xRel[5][2]; + x2 = xRel[6][0] - xRel[5][0]; + y2 = xRel[6][1] - xRel[5][1]; + z2 = xRel[6][2] - xRel[5][2]; + x3 = xRel[1][0] - xRel[5][0]; + y3 = xRel[1][1] - xRel[5][1]; + z3 = xRel[1][2] - xRel[5][2]; + + xc = xRelC[0] - xRel[5][0]; + yc = xRelC[1] - xRel[5][1]; + zc = xRelC[2] - xRel[5][2]; /* Determine the parametric coordinates inside this tetrahedron. */ - detInv = 2.0/(x1*y2*z3 - x1*y3*z2 - x2*y1*z3 + x2*y3*z1 + x3*y1*z2 - x3*y2*z1); - r = detInv*(x2*y3*zc - x2*yc*z3 - x3*y2*zc + x3*yc*z2 + xc*y2*z3 - xc*y3*z2) - 1.0; - s = -detInv*(x1*y3*zc - x1*yc*z3 - x3*y1*zc + x3*yc*z1 + xc*y1*z3 - xc*y3*z1) - 1.0; - t = detInv*(x1*y2*zc - x1*yc*z2 - x2*y1*zc + x2*yc*z1 + xc*y1*z2 - xc*y2*z1) - 1.0; + detInv = 2.0 / (x1 * y2 * z3 - x1 * y3 * z2 - x2 * y1 * z3 + x2 * y3 * z1 + x3 * y1 * z2 - x3 * y2 * z1); + r = detInv * (x2 * y3 * zc - x2 * yc * z3 - x3 * y2 * zc + x3 * yc * z2 + xc * y2 * z3 - xc * y3 * z2) - 1.0; + s = -detInv * (x1 * y3 * zc - x1 * yc * z3 - x3 * y1 * zc + x3 * yc * z1 + xc * y1 * z3 - xc * y3 * z1) - 1.0; + t = detInv * (x1 * y2 * zc - x1 * yc * z2 - x2 * y1 * zc + x2 * yc * z1 + xc * y1 * z2 - xc * y2 * z1) - 1.0; /* If the point is inside this tetrahedron, set the parametric coordinates for the real hexahedron and return true. */ - if((r >= paramLowerBound) && (s >= paramLowerBound) && (t >= paramLowerBound) && - ((r+s+t) <= paramLowerBound)) { - parCoor[0] = 1.0 - r; parCoor[1] = s; parCoor[2] = 1.0 - t; + if ((r >= paramLowerBound) && (s >= paramLowerBound) && (t >= paramLowerBound) && ((r + s + t) <= paramLowerBound)) { + parCoor[0] = 1.0 - r; + parCoor[1] = s; + parCoor[2] = 1.0 - t; return true; } /* Tetrahedron, 2-3-1-6. Create the coordinates of the tetrahedron and of the point. */ - x1 = xRel[3][0]-xRel[2][0]; y1 = xRel[3][1]-xRel[2][1]; z1 = xRel[3][2]-xRel[2][2]; - x2 = xRel[1][0]-xRel[2][0]; y2 = xRel[1][1]-xRel[2][1]; z2 = xRel[1][2]-xRel[2][2]; - x3 = xRel[6][0]-xRel[2][0]; y3 = xRel[6][1]-xRel[2][1]; z3 = xRel[6][2]-xRel[2][2]; - - xc = xRelC[0]-xRel[2][0]; yc = xRelC[1]-xRel[2][1]; zc = xRelC[2]-xRel[2][2]; + x1 = xRel[3][0] - xRel[2][0]; + y1 = xRel[3][1] - xRel[2][1]; + z1 = xRel[3][2] - xRel[2][2]; + x2 = xRel[1][0] - xRel[2][0]; + y2 = xRel[1][1] - xRel[2][1]; + z2 = xRel[1][2] - xRel[2][2]; + x3 = xRel[6][0] - xRel[2][0]; + y3 = xRel[6][1] - xRel[2][1]; + z3 = xRel[6][2] - xRel[2][2]; + + xc = xRelC[0] - xRel[2][0]; + yc = xRelC[1] - xRel[2][1]; + zc = xRelC[2] - xRel[2][2]; /* Determine the parametric coordinates inside this tetrahedron. */ - detInv = 2.0/(x1*y2*z3 - x1*y3*z2 - x2*y1*z3 + x2*y3*z1 + x3*y1*z2 - x3*y2*z1); - r = detInv*(x2*y3*zc - x2*yc*z3 - x3*y2*zc + x3*yc*z2 + xc*y2*z3 - xc*y3*z2) - 1.0; - s = -detInv*(x1*y3*zc - x1*yc*z3 - x3*y1*zc + x3*yc*z1 + xc*y1*z3 - xc*y3*z1) - 1.0; - t = detInv*(x1*y2*zc - x1*yc*z2 - x2*y1*zc + x2*yc*z1 + xc*y1*z2 - xc*y2*z1) - 1.0; + detInv = 2.0 / (x1 * y2 * z3 - x1 * y3 * z2 - x2 * y1 * z3 + x2 * y3 * z1 + x3 * y1 * z2 - x3 * y2 * z1); + r = detInv * (x2 * y3 * zc - x2 * yc * z3 - x3 * y2 * zc + x3 * yc * z2 + xc * y2 * z3 - xc * y3 * z2) - 1.0; + s = -detInv * (x1 * y3 * zc - x1 * yc * z3 - x3 * y1 * zc + x3 * yc * z1 + xc * y1 * z3 - xc * y3 * z1) - 1.0; + t = detInv * (x1 * y2 * zc - x1 * yc * z2 - x2 * y1 * zc + x2 * yc * z1 + xc * y1 * z2 - xc * y2 * z1) - 1.0; /* If the point is inside this tetrahedron, set the parametric coordinates for the real hexahedron and return true. */ - if((r >= paramLowerBound) && (s >= paramLowerBound) && (t >= paramLowerBound) && - ((r+s+t) <= paramLowerBound)) { - parCoor[0] = 1.0 - r; parCoor[1] = 1.0 - s; parCoor[2] = t; + if ((r >= paramLowerBound) && (s >= paramLowerBound) && (t >= paramLowerBound) && ((r + s + t) <= paramLowerBound)) { + parCoor[0] = 1.0 - r; + parCoor[1] = 1.0 - s; + parCoor[2] = t; return true; } /* Tetrahedron, 3-4-1-6. Create the coordinates of the tetrahedron and of the point. */ - x1 = xRel[4][0]-xRel[3][0]; y1 = xRel[4][1]-xRel[3][1]; z1 = xRel[4][2]-xRel[3][2]; - x2 = xRel[1][0]-xRel[3][0]; y2 = xRel[1][1]-xRel[3][1]; z2 = xRel[1][2]-xRel[3][2]; - x3 = xRel[6][0]-xRel[3][0]; y3 = xRel[6][1]-xRel[3][1]; z3 = xRel[6][2]-xRel[3][2]; - - xc = xRelC[0]-xRel[3][0]; yc = xRelC[1]-xRel[3][1]; zc = xRelC[2]-xRel[3][2]; + x1 = xRel[4][0] - xRel[3][0]; + y1 = xRel[4][1] - xRel[3][1]; + z1 = xRel[4][2] - xRel[3][2]; + x2 = xRel[1][0] - xRel[3][0]; + y2 = xRel[1][1] - xRel[3][1]; + z2 = xRel[1][2] - xRel[3][2]; + x3 = xRel[6][0] - xRel[3][0]; + y3 = xRel[6][1] - xRel[3][1]; + z3 = xRel[6][2] - xRel[3][2]; + + xc = xRelC[0] - xRel[3][0]; + yc = xRelC[1] - xRel[3][1]; + zc = xRelC[2] - xRel[3][2]; /* Determine the parametric coordinates inside this tetrahedron. */ - detInv = 2.0/(x1*y2*z3 - x1*y3*z2 - x2*y1*z3 + x2*y3*z1 + x3*y1*z2 - x3*y2*z1); - r = detInv*(x2*y3*zc - x2*yc*z3 - x3*y2*zc + x3*yc*z2 + xc*y2*z3 - xc*y3*z2) - 1.0; - s = -detInv*(x1*y3*zc - x1*yc*z3 - x3*y1*zc + x3*yc*z1 + xc*y1*z3 - xc*y3*z1) - 1.0; - t = detInv*(x1*y2*zc - x1*yc*z2 - x2*y1*zc + x2*yc*z1 + xc*y1*z2 - xc*y2*z1) - 1.0; + detInv = 2.0 / (x1 * y2 * z3 - x1 * y3 * z2 - x2 * y1 * z3 + x2 * y3 * z1 + x3 * y1 * z2 - x3 * y2 * z1); + r = detInv * (x2 * y3 * zc - x2 * yc * z3 - x3 * y2 * zc + x3 * yc * z2 + xc * y2 * z3 - xc * y3 * z2) - 1.0; + s = -detInv * (x1 * y3 * zc - x1 * yc * z3 - x3 * y1 * zc + x3 * yc * z1 + xc * y1 * z3 - xc * y3 * z1) - 1.0; + t = detInv * (x1 * y2 * zc - x1 * yc * z2 - x2 * y1 * zc + x2 * yc * z1 + xc * y1 * z2 - xc * y2 * z1) - 1.0; /* If the point is inside this tetrahedron, set the parametric coordinates for the real hexahedron and return true. */ - if((r >= paramLowerBound) && (s >= paramLowerBound) && (t >= paramLowerBound) && - ((r+s+t) <= paramLowerBound)) { - parCoor[0] = 1.0+s+t; parCoor[1] = -1.0-r-s; parCoor[2] = 1.0+r+t; + if ((r >= paramLowerBound) && (s >= paramLowerBound) && (t >= paramLowerBound) && ((r + s + t) <= paramLowerBound)) { + parCoor[0] = 1.0 + s + t; + parCoor[1] = -1.0 - r - s; + parCoor[2] = 1.0 + r + t; return true; } @@ -1871,20 +2043,17 @@ bool CADTElemClass::InitialGuessContainmentHexahedron(const su2double xRelC[3], return false; } -void CADTElemClass::Dist2ToLine(const unsigned long i0, - const unsigned long i1, - const su2double *coor, - su2double &dist2Line) const { - +void CADTElemClass::Dist2ToLine(const unsigned long i0, const unsigned long i1, const su2double* coor, + su2double& dist2Line) const { /*--- The line is parametrized by X = X0 + (r+1)*(X1-X0)/2, -1 <= r <= 1. As a consequence the minimum distance is found where the expression |V0 - r*V1| has a minimum, where the vectors V0 and V1 are defined as: V0 = coor - (X1+X0)/2, V1 = (X1-X0)/2. First construct the vectors V0 and V1. ---*/ su2double V0[3], V1[3]; - for(unsigned short k=0; k= -1, r+s <= 0. As a consequence the minimum distance is found where @@ -1923,38 +2086,37 @@ bool CADTElemClass::Dist2ToTriangle(const unsigned long i0, and V2 are defined as: V0 = coor - (X1+X2)/2, V1 = (X1-X0)/2, V2 = (X2-X0)/2. First construct the vectors V0, V1 and V2. ---*/ su2double V0[3], V1[3], V2[3]; - for(unsigned short k=0; k= paramLowerBound) && (s >= paramLowerBound) && ((r+s) <= tolInsideElem)) { - + if ((r >= paramLowerBound) && (s >= paramLowerBound) && ((r + s) <= tolInsideElem)) { /*--- The projection of the coordinate is inside the triangle. Compute the minimum distance squared and return true. ---*/ dist2Tria = 0.0; - for(unsigned short k=0; k 10) return false; + if (itCount > 10) return false; /* Newtons algorithm did not converge, but there is a root. Do a crude approximation of the root using bisection. */ - s -= 0.5*ds; + s -= 0.5 * ds; } /* Check if s is inside the quadrilateral. If not, return false. */ - if(s < paramLowerBound || s > paramUpperBound) return false; + if (s < paramLowerBound || s > paramUpperBound) return false; /* Compute the corresponding value of r and check if it is inside the quadrilateral. If not return false. */ - const su2double s2 = s*s; + const su2double s2 = s * s; - r = (V0V1 + (V0V3-V1V2)*s - V2V3*s2)/(V1V1 + 2.0*V1V3*s + V3V3*s2); - if(r < paramLowerBound || r > paramUpperBound) return false; + r = (V0V1 + (V0V3 - V1V2) * s - V2V3 * s2) / (V1V1 + 2.0 * V1V3 * s + V3V3 * s2); + if (r < paramLowerBound || r > paramUpperBound) return false; /*--- The projection is inside the quadrilateral. Determine the minimum distance squared and return true to indicate that the projection is inside. ---*/ dist2Quad = 0.0; - for(unsigned short k=0; k recvCounts(size), displs(size); - int sizeLocal = (int) nPoints; + int sizeLocal = (int)nPoints; - SU2_MPI::Allgather(&sizeLocal, 1, MPI_INT, recvCounts.data(), 1, - MPI_INT, SU2_MPI::GetComm()); + SU2_MPI::Allgather(&sizeLocal, 1, MPI_INT, recvCounts.data(), 1, MPI_INT, SU2_MPI::GetComm()); displs[0] = 0; - for(int i=1; i rankLocal(sizeLocal, rank); - SU2_MPI::Allgatherv(rankLocal.data(), sizeLocal, MPI_INT, ranksOfPoints.data(), - recvCounts.data(), displs.data(), MPI_INT, SU2_MPI::GetComm()); + SU2_MPI::Allgatherv(rankLocal.data(), sizeLocal, MPI_INT, ranksOfPoints.data(), recvCounts.data(), displs.data(), + MPI_INT, SU2_MPI::GetComm()); /*--- Gather the coordinates of the points on all ranks. ---*/ - for(int i=0; i& frontLeaves, - vector& frontLeavesNew, - const su2double *coor, - su2double &dist, - unsigned long &pointID, - int &rankID) const { - + vector& frontLeavesNew, const su2double* coor, + su2double& dist, unsigned long& pointID, int& rankID) const { const bool wasActive = AD::BeginPassive(); /*--------------------------------------------------------------------------*/ @@ -130,15 +120,15 @@ void CADTPointsOnlyClass::DetermineNearestNode_impl(vector& front /*--------------------------------------------------------------------------*/ unsigned long kk = leaves[0].centralNodeID, minIndex; - const su2double *coorTarget = coorPoints.data() + nDimADT*kk; + const su2double* coorTarget = coorPoints.data() + nDimADT * kk; - pointID = localPointIDs[kk]; - rankID = ranksOfPoints[kk]; + pointID = localPointIDs[kk]; + rankID = ranksOfPoints[kk]; minIndex = kk; dist = 0.0; - for(unsigned short l=0; l& front frontLeaves.push_back(0); /* Infinite loop of the tree traversal. */ - for(;;) { - + for (;;) { /* Initialize the new front, i.e. the front for the next round, to empty. */ frontLeavesNew.clear(); /* Loop over the leaves of the current front. */ - for(unsigned long i=0; i leaves[kk].xMax[l]) ds = coor[l] - leaves[kk].xMax[l]; + if (coor[l] < leaves[kk].xMin[l]) + ds = coor[l] - leaves[kk].xMin[l]; + else if (coor[l] > leaves[kk].xMax[l]) + ds = coor[l] - leaves[kk].xMax[l]; - posDist += ds*ds; + posDist += ds * ds; } /*--- Check if the possible minimum distance is less than the currently stored minimum distance. If so this leaf must be stored for the next round. In that case the distance squared to the central node is determined, which is used to update the currently stored value. ---*/ - if(posDist < dist) { + if (posDist < dist) { frontLeavesNew.push_back(kk); const unsigned long jj = leaves[kk].centralNodeID; - coorTarget = coorPoints.data() + nDimADT*jj; + coorTarget = coorPoints.data() + nDimADT * jj; su2double distTarget = 0; - for(unsigned short l=0; l& front is empty the entire tree has been traversed and a break can be made from the infinite loop. ---*/ frontLeaves = frontLeavesNew; - if(frontLeaves.size() == 0) break; + if (frontLeaves.size() == 0) break; } AD::EndPassive(wasActive); /* Recompute the distance to get the correct dependency if we use AD */ - coorTarget = coorPoints.data() + nDimADT*minIndex; + coorTarget = coorPoints.data() + nDimADT * minIndex; dist = 0.0; - for(unsigned short l=0; l TapePositions; +TapePosition StartPosition, EndPosition; +std::vector TapePositions; - bool PreaccActive = false; +bool PreaccActive = false; #ifdef HAVE_OPDI - SU2_OMP(threadprivate(PreaccActive)) +SU2_OMP(threadprivate(PreaccActive)) #endif - bool PreaccEnabled = true; +bool PreaccEnabled = true; - codi::PreaccumulationHelper PreaccHelper; +codi::PreaccumulationHelper PreaccHelper; #ifdef HAVE_OPDI - SU2_OMP(threadprivate(PreaccHelper)) +SU2_OMP(threadprivate(PreaccHelper)) #endif - ExtFuncHelper FuncHelper; +ExtFuncHelper FuncHelper; #endif - void Initialize() { +void Initialize() { #ifdef CODI_REVERSE_TYPE - FuncHelper.disableInputPrimalStore(); - FuncHelper.disableOutputPrimalStore(); + FuncHelper.disableInputPrimalStore(); + FuncHelper.disableOutputPrimalStore(); #endif - } - - void Finalize() {} } + +void Finalize() {} +} // namespace AD diff --git a/Common/src/containers/CFileReaderLUT.cpp b/Common/src/containers/CFileReaderLUT.cpp index ba3f19841ee..5362a81406f 100644 --- a/Common/src/containers/CFileReaderLUT.cpp +++ b/Common/src/containers/CFileReaderLUT.cpp @@ -135,12 +135,9 @@ void CFileReaderLUT::ReadRawLUT(const string& file_name) { SU2_MPI::Error("Table levels are not provided in ascending order.", CURRENT_FUNCTION); } auto duplicate = adjacent_find(table_levels.begin(), table_levels.end()) != table_levels.end(); - if (duplicate) - SU2_MPI::Error("Duplicate table levels are present in LUT file", CURRENT_FUNCTION); + if (duplicate) SU2_MPI::Error("Duplicate table levels are present in LUT file", CURRENT_FUNCTION); } - - /*--- number of variables in LUT ---*/ if (line.compare("[Number of variables]") == 0) { GetNextNonEmptyLine(file_stream, line); @@ -367,4 +364,4 @@ bool CFileReaderLUT::GetStrippedLine(ifstream& file_stream, string& line) const /*--- return true if line is not empty, else return false ---*/ return !line.empty(); -} \ No newline at end of file +} diff --git a/Common/src/fem/fem_cgns_elements.cpp b/Common/src/fem/fem_cgns_elements.cpp index 15f1e49256f..4069b164321 100644 --- a/Common/src/fem/fem_cgns_elements.cpp +++ b/Common/src/fem/fem_cgns_elements.cpp @@ -38,20 +38,16 @@ using namespace std; #if CGNS_VERSION >= 3300 -void CCGNSElementType::DetermineMetaData(const unsigned short nDim, - const int fn, - const int iBase, - const int iZone, - const int iConn) { - +void CCGNSElementType::DetermineMetaData(const unsigned short nDim, const int fn, const int iBase, const int iZone, + const int iConn) { /* Store the connectivity ID. */ connID = iConn; /* Read the element type and range from the CGNS file. */ char cgnsname[CGNS_STRING_SIZE]; int nBndry, parentFlag; - if(cg_section_read(fn, iBase, iZone, iConn, cgnsname, &elemType, - &indBeg, &indEnd, &nBndry, &parentFlag) != CG_OK) cg_error_exit(); + if (cg_section_read(fn, iBase, iZone, iConn, cgnsname, &elemType, &indBeg, &indEnd, &nBndry, &parentFlag) != CG_OK) + cg_error_exit(); /* Store the name of this connectivity. */ connName = cgnsname; @@ -65,46 +61,40 @@ void CCGNSElementType::DetermineMetaData(const unsigned short nDim, e.g. line elements for 3D. This information is not needed for the DG flow solver and is therefore ignored. */ const unsigned short nDimElem = DetermineElementDimension(fn, iBase, iZone); - volumeConn = (nDimElem == nDim); - surfaceConn = (nDimElem == nDim-1); + volumeConn = (nDimElem == nDim); + surfaceConn = (nDimElem == nDim - 1); } -void CCGNSElementType::ReadBoundaryConnectivityRange( - const int fn, - const int iBase, - const int iZone, - const unsigned long offsetRank, - const unsigned long nBoundElemRank, - const unsigned long startingBoundElemIDRank, - unsigned long &locBoundElemCount, - vector &boundElems) { - +void CCGNSElementType::ReadBoundaryConnectivityRange(const int fn, const int iBase, const int iZone, + const unsigned long offsetRank, const unsigned long nBoundElemRank, + const unsigned long startingBoundElemIDRank, + unsigned long& locBoundElemCount, + vector& boundElems) { /* Determine the index range to be read for this rank. */ const cgsize_t iBeg = indBeg + offsetRank; - const cgsize_t iEnd = iBeg + nBoundElemRank -1; + const cgsize_t iEnd = iBeg + nBoundElemRank - 1; /* Determine the size of the vector needed to read the connectivity data from the CGNS file. */ cgsize_t sizeNeeded; - if(cg_ElementPartialSize(fn, iBase, iZone, connID, iBeg, iEnd, - &sizeNeeded) != CG_OK) cg_error_exit(); + if (cg_ElementPartialSize(fn, iBase, iZone, connID, iBeg, iEnd, &sizeNeeded) != CG_OK) cg_error_exit(); /* Allocate the memory for the connectivity and read the data. */ vector connCGNSVec(sizeNeeded); - if(elemType == MIXED){ - vector connCGNSOffsetVec(iEnd-iBeg+2); - if(cg_poly_elements_partial_read(fn, iBase, iZone, connID, iBeg, iEnd, - connCGNSVec.data(), connCGNSOffsetVec.data(), NULL) != CG_OK) + if (elemType == MIXED) { + vector connCGNSOffsetVec(iEnd - iBeg + 2); + if (cg_poly_elements_partial_read(fn, iBase, iZone, connID, iBeg, iEnd, connCGNSVec.data(), + connCGNSOffsetVec.data(), NULL) != CG_OK) cg_error_exit(); } else { - if(cg_elements_partial_read(fn, iBase, iZone, connID, iBeg, iEnd, - connCGNSVec.data(), NULL) != CG_OK) cg_error_exit(); + if (cg_elements_partial_read(fn, iBase, iZone, connID, iBeg, iEnd, connCGNSVec.data(), NULL) != CG_OK) + cg_error_exit(); } /* Define the variables needed to convert the connectivities from CGNS to SU2 format. Note that the vectors are needed to support a connectivity section with mixed element types. */ - vector CGNS_Type; + vector CGNS_Type; vector VTK_Type; vector nPoly; vector nDOFs; @@ -112,25 +102,23 @@ void CCGNSElementType::ReadBoundaryConnectivityRange( vector > SU2ToCGNS; /* Definition of variables used in the loop below. */ - cgsize_t *connCGNS = connCGNSVec.data(); + cgsize_t* connCGNS = connCGNSVec.data(); ElementType_t typeElem = elemType; vector connSU2; /* Loop over the elements just read. */ - for(unsigned long i=0; i connCGNSVec(sizeNeeded); if (elemType == MIXED) { - vector connCGNSOffsetVec(iEnd-iBeg+2); - if(cg_poly_elements_partial_read(fn, iBase, iZone, connID, iBeg, iEnd, - connCGNSVec.data(), connCGNSOffsetVec.data(), NULL) != CG_OK) + vector connCGNSOffsetVec(iEnd - iBeg + 2); + if (cg_poly_elements_partial_read(fn, iBase, iZone, connID, iBeg, iEnd, connCGNSVec.data(), + connCGNSOffsetVec.data(), NULL) != CG_OK) cg_error_exit(); } else { - if(cg_elements_partial_read(fn, iBase, iZone, connID, iBeg, iEnd, - connCGNSVec.data(), NULL) != CG_OK) cg_error_exit(); + if (cg_elements_partial_read(fn, iBase, iZone, connID, iBeg, iEnd, connCGNSVec.data(), NULL) != CG_OK) + cg_error_exit(); } /* Define the variables needed to convert the connectivities from CGNS to SU2 format. Note that the vectors are needed to support a connectivity section with mixed element types. */ - vector CGNS_Type; + vector CGNS_Type; vector VTK_Type; vector nPoly; vector nDOFs; @@ -207,25 +186,23 @@ void CCGNSElementType::ReadConnectivityRange(const int fn, vector > SU2ToCGNS; /* Definition of variables used in the loop below. */ - cgsize_t *connCGNS = connCGNSVec.data(); + cgsize_t* connCGNS = connCGNSVec.data(); ElementType_t typeElem = elemType; vector connSU2; /* Loop over the elements just read. */ - for(unsigned long i=0; i buf(sizeNeeded); vector buf_offset(2, 0); - if(cg_poly_elements_partial_read(fn, iBase, iZone, connID, indBeg, indBeg, - buf.data(), buf_offset.data(), NULL) != CG_OK) cg_error_exit(); + if (cg_poly_elements_partial_read(fn, iBase, iZone, connID, indBeg, indBeg, buf.data(), buf_offset.data(), NULL) != + CG_OK) + cg_error_exit(); /* The first entry of buf contains the element type. Copy this value temporarily into the member variable elemType and determine the element dimension of this element. */ - elemType = (ElementType_t) buf[0]; + elemType = (ElementType_t)buf[0]; unsigned short nDimElem = DetermineElementDimension(fn, iBase, iZone); @@ -329,24 +336,19 @@ unsigned short CCGNSElementType::DetermineElementDimensionMixed(const int fn, return nDimElem; } -unsigned short CCGNSElementType::IndexInStoredTypes( - const ElementType_t typeElem, - vector &CGNS_Type, - vector &VTK_Type, - vector &nPoly, - vector &nDOFs, - vector > &SU2ToCGNS) { - +unsigned short CCGNSElementType::IndexInStoredTypes(const ElementType_t typeElem, vector& CGNS_Type, + vector& VTK_Type, vector& nPoly, + vector& nDOFs, + vector >& SU2ToCGNS) { /* Loop over the available types and check if the current type is present. If so, break the loop, such that the correct index is stored. */ unsigned short ind; - for(ind=0; ind SU2ToCGNSElem; CreateDataElementType(typeElem, VTKElem, nPolyElem, nDOFsElem, SU2ToCGNSElem); @@ -362,46 +364,99 @@ unsigned short CCGNSElementType::IndexInStoredTypes( return ind; } -void CCGNSElementType::CreateDataElementType( - const ElementType_t typeElem, - unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - vector &SU2ToCGNS) { - +void CCGNSElementType::CreateDataElementType(const ElementType_t typeElem, unsigned short& VTK_Type, + unsigned short& nPoly, unsigned short& nDOFs, + vector& SU2ToCGNS) { /*--- Determine the element type and call the corresponding function to determine the actual data. ---*/ - switch( typeElem ) { - - case NODE: CreateDataNODE(VTK_Type, nPoly, nDOFs, SU2ToCGNS); break; - case BAR_2: CreateDataBAR_2(VTK_Type, nPoly, nDOFs, SU2ToCGNS); break; - case BAR_3: CreateDataBAR_3(VTK_Type, nPoly, nDOFs, SU2ToCGNS); break; - case BAR_4: CreateDataBAR_4(VTK_Type, nPoly, nDOFs, SU2ToCGNS); break; - case BAR_5: CreateDataBAR_5(VTK_Type, nPoly, nDOFs, SU2ToCGNS); break; - case TRI_3: CreateDataTRI_3(VTK_Type, nPoly, nDOFs, SU2ToCGNS); break; - case TRI_6: CreateDataTRI_6(VTK_Type, nPoly, nDOFs, SU2ToCGNS); break; - case TRI_10: CreateDataTRI_10(VTK_Type, nPoly, nDOFs, SU2ToCGNS); break; - case TRI_15: CreateDataTRI_15(VTK_Type, nPoly, nDOFs, SU2ToCGNS); break; - case QUAD_4: CreateDataQUAD_4(VTK_Type, nPoly, nDOFs, SU2ToCGNS); break; - case QUAD_9: CreateDataQUAD_9(VTK_Type, nPoly, nDOFs, SU2ToCGNS); break; - case QUAD_16: CreateDataQUAD_16(VTK_Type, nPoly, nDOFs, SU2ToCGNS); break; - case QUAD_25: CreateDataQUAD_25(VTK_Type, nPoly, nDOFs, SU2ToCGNS); break; - case TETRA_4: CreateDataTETRA_4(VTK_Type, nPoly, nDOFs, SU2ToCGNS); break; - case TETRA_10: CreateDataTETRA_10(VTK_Type, nPoly, nDOFs, SU2ToCGNS); break; - case TETRA_20: CreateDataTETRA_20(VTK_Type, nPoly, nDOFs, SU2ToCGNS); break; - case TETRA_35: CreateDataTETRA_35(VTK_Type, nPoly, nDOFs, SU2ToCGNS); break; - case PYRA_5: CreateDataPYRA_5(VTK_Type, nPoly, nDOFs, SU2ToCGNS); break; - case PYRA_14: CreateDataPYRA_14(VTK_Type, nPoly, nDOFs, SU2ToCGNS); break; - case PYRA_30: CreateDataPYRA_30(VTK_Type, nPoly, nDOFs, SU2ToCGNS); break; - case PYRA_55: CreateDataPYRA_55(VTK_Type, nPoly, nDOFs, SU2ToCGNS); break; - case PENTA_6: CreateDataPENTA_6(VTK_Type, nPoly, nDOFs, SU2ToCGNS); break; - case PENTA_18: CreateDataPENTA_18(VTK_Type, nPoly, nDOFs, SU2ToCGNS); break; - case PENTA_40: CreateDataPENTA_40(VTK_Type, nPoly, nDOFs, SU2ToCGNS); break; - case PENTA_75: CreateDataPENTA_75(VTK_Type, nPoly, nDOFs, SU2ToCGNS); break; - case HEXA_8: CreateDataHEXA_8(VTK_Type, nPoly, nDOFs, SU2ToCGNS); break; - case HEXA_27: CreateDataHEXA_27(VTK_Type, nPoly, nDOFs, SU2ToCGNS); break; - case HEXA_64: CreateDataHEXA_64(VTK_Type, nPoly, nDOFs, SU2ToCGNS); break; - case HEXA_125: CreateDataHEXA_125(VTK_Type, nPoly, nDOFs, SU2ToCGNS); break; + switch (typeElem) { + case NODE: + CreateDataNODE(VTK_Type, nPoly, nDOFs, SU2ToCGNS); + break; + case BAR_2: + CreateDataBAR_2(VTK_Type, nPoly, nDOFs, SU2ToCGNS); + break; + case BAR_3: + CreateDataBAR_3(VTK_Type, nPoly, nDOFs, SU2ToCGNS); + break; + case BAR_4: + CreateDataBAR_4(VTK_Type, nPoly, nDOFs, SU2ToCGNS); + break; + case BAR_5: + CreateDataBAR_5(VTK_Type, nPoly, nDOFs, SU2ToCGNS); + break; + case TRI_3: + CreateDataTRI_3(VTK_Type, nPoly, nDOFs, SU2ToCGNS); + break; + case TRI_6: + CreateDataTRI_6(VTK_Type, nPoly, nDOFs, SU2ToCGNS); + break; + case TRI_10: + CreateDataTRI_10(VTK_Type, nPoly, nDOFs, SU2ToCGNS); + break; + case TRI_15: + CreateDataTRI_15(VTK_Type, nPoly, nDOFs, SU2ToCGNS); + break; + case QUAD_4: + CreateDataQUAD_4(VTK_Type, nPoly, nDOFs, SU2ToCGNS); + break; + case QUAD_9: + CreateDataQUAD_9(VTK_Type, nPoly, nDOFs, SU2ToCGNS); + break; + case QUAD_16: + CreateDataQUAD_16(VTK_Type, nPoly, nDOFs, SU2ToCGNS); + break; + case QUAD_25: + CreateDataQUAD_25(VTK_Type, nPoly, nDOFs, SU2ToCGNS); + break; + case TETRA_4: + CreateDataTETRA_4(VTK_Type, nPoly, nDOFs, SU2ToCGNS); + break; + case TETRA_10: + CreateDataTETRA_10(VTK_Type, nPoly, nDOFs, SU2ToCGNS); + break; + case TETRA_20: + CreateDataTETRA_20(VTK_Type, nPoly, nDOFs, SU2ToCGNS); + break; + case TETRA_35: + CreateDataTETRA_35(VTK_Type, nPoly, nDOFs, SU2ToCGNS); + break; + case PYRA_5: + CreateDataPYRA_5(VTK_Type, nPoly, nDOFs, SU2ToCGNS); + break; + case PYRA_14: + CreateDataPYRA_14(VTK_Type, nPoly, nDOFs, SU2ToCGNS); + break; + case PYRA_30: + CreateDataPYRA_30(VTK_Type, nPoly, nDOFs, SU2ToCGNS); + break; + case PYRA_55: + CreateDataPYRA_55(VTK_Type, nPoly, nDOFs, SU2ToCGNS); + break; + case PENTA_6: + CreateDataPENTA_6(VTK_Type, nPoly, nDOFs, SU2ToCGNS); + break; + case PENTA_18: + CreateDataPENTA_18(VTK_Type, nPoly, nDOFs, SU2ToCGNS); + break; + case PENTA_40: + CreateDataPENTA_40(VTK_Type, nPoly, nDOFs, SU2ToCGNS); + break; + case PENTA_75: + CreateDataPENTA_75(VTK_Type, nPoly, nDOFs, SU2ToCGNS); + break; + case HEXA_8: + CreateDataHEXA_8(VTK_Type, nPoly, nDOFs, SU2ToCGNS); + break; + case HEXA_27: + CreateDataHEXA_27(VTK_Type, nPoly, nDOFs, SU2ToCGNS); + break; + case HEXA_64: + CreateDataHEXA_64(VTK_Type, nPoly, nDOFs, SU2ToCGNS); + break; + case HEXA_125: + CreateDataHEXA_125(VTK_Type, nPoly, nDOFs, SU2ToCGNS); + break; default: /* Print an error message that this element type is not supported and exit. */ @@ -416,102 +471,92 @@ void CCGNSElementType::CreateDataElementType( /*--- CGNS and SU2 format for the specific elements. ---*/ /*------------------------------------------------------------------------*/ -void CCGNSElementType::CreateDataNODE(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - vector &SU2ToCGNS) { - +void CCGNSElementType::CreateDataNODE(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + vector& SU2ToCGNS) { /* Set the required data for a NODE. */ VTK_Type = VERTEX; - nPoly = 0; - nDOFs = 1; + nPoly = 0; + nDOFs = 1; SU2ToCGNS.push_back(0); } -void CCGNSElementType::CreateDataBAR_2(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - vector &SU2ToCGNS) { - +void CCGNSElementType::CreateDataBAR_2(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + vector& SU2ToCGNS) { /* The BAR_2 element is a linear element. The numbering of the nodes is the same for CGNS and SU2. */ VTK_Type = LINE; - nPoly = 1; - nDOFs = 2; + nPoly = 1; + nDOFs = 2; SU2ToCGNS.resize(nDOFs); - SU2ToCGNS[0] = 0; SU2ToCGNS[1] = 1; + SU2ToCGNS[0] = 0; + SU2ToCGNS[1] = 1; } -void CCGNSElementType::CreateDataBAR_3(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - vector &SU2ToCGNS) { - +void CCGNSElementType::CreateDataBAR_3(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + vector& SU2ToCGNS) { /* The BAR_3 element is a quadratic element. SU2 numbers to nodes with increasing parametric value, while in CGNS the internal node is numbered last. */ VTK_Type = LINE; - nPoly = 2; - nDOFs = 3; + nPoly = 2; + nDOFs = 3; SU2ToCGNS.resize(nDOFs); - SU2ToCGNS[0] = 0; SU2ToCGNS[1] = 2; SU2ToCGNS[2] = 1; + SU2ToCGNS[0] = 0; + SU2ToCGNS[1] = 2; + SU2ToCGNS[2] = 1; } -void CCGNSElementType::CreateDataBAR_4(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - vector &SU2ToCGNS) { - +void CCGNSElementType::CreateDataBAR_4(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + vector& SU2ToCGNS) { /* The BAR_4 element is a cubic element. SU2 numbers to nodes with increasing parametric value, while in CGNS the internal nodes are numbered last. */ VTK_Type = LINE; - nPoly = 3; - nDOFs = 4; + nPoly = 3; + nDOFs = 4; SU2ToCGNS.resize(nDOFs); - SU2ToCGNS[0] = 0; SU2ToCGNS[1] = 2; SU2ToCGNS[2] = 3; SU2ToCGNS[3] = 1; + SU2ToCGNS[0] = 0; + SU2ToCGNS[1] = 2; + SU2ToCGNS[2] = 3; + SU2ToCGNS[3] = 1; } -void CCGNSElementType::CreateDataBAR_5(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - vector &SU2ToCGNS) { - +void CCGNSElementType::CreateDataBAR_5(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + vector& SU2ToCGNS) { /* The BAR_5 element is a quartic element. SU2 numbers to nodes with increasing parametric value, while in CGNS the internal nodes are numbered last. */ VTK_Type = LINE; - nPoly = 4; - nDOFs = 5; + nPoly = 4; + nDOFs = 5; SU2ToCGNS.resize(nDOFs); - SU2ToCGNS[0] = 0; SU2ToCGNS[1] = 2; SU2ToCGNS[2] = 3; - SU2ToCGNS[3] = 4; SU2ToCGNS[4] = 1; + SU2ToCGNS[0] = 0; + SU2ToCGNS[1] = 2; + SU2ToCGNS[2] = 3; + SU2ToCGNS[3] = 4; + SU2ToCGNS[4] = 1; } -void CCGNSElementType::CreateDataTRI_3(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - vector &SU2ToCGNS) { - +void CCGNSElementType::CreateDataTRI_3(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + vector& SU2ToCGNS) { /* The TRI_3 element is a linear triangle. The node numbering is the same in SU2 and CGNS. */ VTK_Type = TRIANGLE; - nPoly = 1; - nDOFs = 3; + nPoly = 1; + nDOFs = 3; SU2ToCGNS.resize(nDOFs); - SU2ToCGNS[0] = 0; SU2ToCGNS[1] = 1; SU2ToCGNS[2] = 2; + SU2ToCGNS[0] = 0; + SU2ToCGNS[1] = 1; + SU2ToCGNS[2] = 2; } -void CCGNSElementType::CreateDataTRI_6(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - vector &SU2ToCGNS) { - +void CCGNSElementType::CreateDataTRI_6(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + vector& SU2ToCGNS) { /* The TRI_6 element is a quadratic triangle. In CGNS the nodes are numbered as follows: - First the vertex nodes. - Second the edge nodes. @@ -520,19 +565,20 @@ void CCGNSElementType::CreateDataTRI_6(unsigned short &VTK_Type, where the i-direction is defined from node 0 to 1 and the j-direction from node 0 along the other edge. */ VTK_Type = TRIANGLE; - nPoly = 2; - nDOFs = 6; + nPoly = 2; + nDOFs = 6; SU2ToCGNS.resize(nDOFs); - SU2ToCGNS[0] = 0; SU2ToCGNS[1] = 3; SU2ToCGNS[2] = 1; - SU2ToCGNS[3] = 5; SU2ToCGNS[4] = 4; SU2ToCGNS[5] = 2; + SU2ToCGNS[0] = 0; + SU2ToCGNS[1] = 3; + SU2ToCGNS[2] = 1; + SU2ToCGNS[3] = 5; + SU2ToCGNS[4] = 4; + SU2ToCGNS[5] = 2; } -void CCGNSElementType::CreateDataTRI_10(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - vector &SU2ToCGNS) { - +void CCGNSElementType::CreateDataTRI_10(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + vector& SU2ToCGNS) { /* The TRI_10 element is a cubic triangle. In CGNS the nodes are numbered as follows: - First the vertex nodes. - Second the edge nodes. @@ -541,20 +587,24 @@ void CCGNSElementType::CreateDataTRI_10(unsigned short &VTK_Type, where the i-direction is defined from node 0 to 1 and the j-direction from node 0 along the other edge. */ VTK_Type = TRIANGLE; - nPoly = 3; - nDOFs = 10; + nPoly = 3; + nDOFs = 10; SU2ToCGNS.resize(nDOFs); - SU2ToCGNS[0] = 0; SU2ToCGNS[1] = 3; SU2ToCGNS[2] = 4; SU2ToCGNS[3] = 1; - SU2ToCGNS[4] = 8; SU2ToCGNS[5] = 9; SU2ToCGNS[6] = 5; SU2ToCGNS[7] = 7; - SU2ToCGNS[8] = 6; SU2ToCGNS[9] = 2; + SU2ToCGNS[0] = 0; + SU2ToCGNS[1] = 3; + SU2ToCGNS[2] = 4; + SU2ToCGNS[3] = 1; + SU2ToCGNS[4] = 8; + SU2ToCGNS[5] = 9; + SU2ToCGNS[6] = 5; + SU2ToCGNS[7] = 7; + SU2ToCGNS[8] = 6; + SU2ToCGNS[9] = 2; } -void CCGNSElementType::CreateDataTRI_15(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - vector &SU2ToCGNS) { - +void CCGNSElementType::CreateDataTRI_15(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + vector& SU2ToCGNS) { /* The TRI_15 element is a quartic triangle. In CGNS the nodes are numbered as follows: - First the vertex nodes. - Second the edge nodes. @@ -566,21 +616,29 @@ void CCGNSElementType::CreateDataTRI_15(unsigned short &VTK_Type, the location for uniform spacing. This effect is currently ignored, i.e. it is assumed that the spacing in parameter space is uniform. */ VTK_Type = TRIANGLE; - nPoly = 4; - nDOFs = 15; + nPoly = 4; + nDOFs = 15; SU2ToCGNS.resize(nDOFs); - SU2ToCGNS[0] = 0; SU2ToCGNS[1] = 3; SU2ToCGNS[2] = 4; SU2ToCGNS[3] = 5; - SU2ToCGNS[4] = 1; SU2ToCGNS[5] = 11; SU2ToCGNS[6] = 12; SU2ToCGNS[7] = 13; - SU2ToCGNS[8] = 6; SU2ToCGNS[9] = 10; SU2ToCGNS[10] = 14; SU2ToCGNS[11] = 7; - SU2ToCGNS[12] = 9; SU2ToCGNS[13] = 8; SU2ToCGNS[14] = 2; + SU2ToCGNS[0] = 0; + SU2ToCGNS[1] = 3; + SU2ToCGNS[2] = 4; + SU2ToCGNS[3] = 5; + SU2ToCGNS[4] = 1; + SU2ToCGNS[5] = 11; + SU2ToCGNS[6] = 12; + SU2ToCGNS[7] = 13; + SU2ToCGNS[8] = 6; + SU2ToCGNS[9] = 10; + SU2ToCGNS[10] = 14; + SU2ToCGNS[11] = 7; + SU2ToCGNS[12] = 9; + SU2ToCGNS[13] = 8; + SU2ToCGNS[14] = 2; } -void CCGNSElementType::CreateDataQUAD_4(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - vector &SU2ToCGNS) { - +void CCGNSElementType::CreateDataQUAD_4(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + vector& SU2ToCGNS) { /* The QUAD_4 element is a linear quadrilateral. In CGNS the nodes are numbered as follows: - First the vertex nodes. - Second the edge nodes (not present for QUAD_4). @@ -589,18 +647,18 @@ void CCGNSElementType::CreateDataQUAD_4(unsigned short &VTK_Type, where the i-direction is defined from node 0 to 1 and the j-direction from node 0 along the other edge. */ VTK_Type = QUADRILATERAL; - nPoly = 1; - nDOFs = 4; + nPoly = 1; + nDOFs = 4; SU2ToCGNS.resize(nDOFs); - SU2ToCGNS[0] = 0; SU2ToCGNS[1] = 1; SU2ToCGNS[2] = 3; SU2ToCGNS[3] = 2; + SU2ToCGNS[0] = 0; + SU2ToCGNS[1] = 1; + SU2ToCGNS[2] = 3; + SU2ToCGNS[3] = 2; } -void CCGNSElementType::CreateDataQUAD_9(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - vector &SU2ToCGNS) { - +void CCGNSElementType::CreateDataQUAD_9(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + vector& SU2ToCGNS) { /* The QUAD_9 element is a quadratic quadrilateral. In CGNS the nodes are numbered as follows: - First the vertex nodes. - Second the edge nodes. @@ -609,20 +667,23 @@ void CCGNSElementType::CreateDataQUAD_9(unsigned short &VTK_Type, where the i-direction is defined from node 0 to 1 and the j-direction from node 0 along the other edge. */ VTK_Type = QUADRILATERAL; - nPoly = 2; - nDOFs = 9; + nPoly = 2; + nDOFs = 9; SU2ToCGNS.resize(nDOFs); - SU2ToCGNS[0] = 0; SU2ToCGNS[1] = 4; SU2ToCGNS[2] = 1; SU2ToCGNS[3] = 7; - SU2ToCGNS[4] = 8; SU2ToCGNS[5] = 5; SU2ToCGNS[6] = 3; SU2ToCGNS[7] = 6; + SU2ToCGNS[0] = 0; + SU2ToCGNS[1] = 4; + SU2ToCGNS[2] = 1; + SU2ToCGNS[3] = 7; + SU2ToCGNS[4] = 8; + SU2ToCGNS[5] = 5; + SU2ToCGNS[6] = 3; + SU2ToCGNS[7] = 6; SU2ToCGNS[8] = 2; } -void CCGNSElementType::CreateDataQUAD_16(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - vector &SU2ToCGNS) { - +void CCGNSElementType::CreateDataQUAD_16(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + vector& SU2ToCGNS) { /* The QUAD_16 element is a cubic quadrilateral. In CGNS the nodes are numbered as follows: - First the vertex nodes. - Second the edge nodes. @@ -631,21 +692,30 @@ void CCGNSElementType::CreateDataQUAD_16(unsigned short &VTK_Type, where the i-direction is defined from node 0 to 1 and the j-direction from node 0 along the other edge. */ VTK_Type = QUADRILATERAL; - nPoly = 3; - nDOFs = 16; + nPoly = 3; + nDOFs = 16; SU2ToCGNS.resize(nDOFs); - SU2ToCGNS[0] = 0; SU2ToCGNS[1] = 4; SU2ToCGNS[2] = 5; SU2ToCGNS[3] = 1; - SU2ToCGNS[4] = 11; SU2ToCGNS[5] = 12; SU2ToCGNS[6] = 13; SU2ToCGNS[7] = 6; - SU2ToCGNS[8] = 10; SU2ToCGNS[9] = 15; SU2ToCGNS[10] = 14; SU2ToCGNS[11] = 7; - SU2ToCGNS[12] = 3; SU2ToCGNS[13] = 9; SU2ToCGNS[14] = 8; SU2ToCGNS[15] = 2; + SU2ToCGNS[0] = 0; + SU2ToCGNS[1] = 4; + SU2ToCGNS[2] = 5; + SU2ToCGNS[3] = 1; + SU2ToCGNS[4] = 11; + SU2ToCGNS[5] = 12; + SU2ToCGNS[6] = 13; + SU2ToCGNS[7] = 6; + SU2ToCGNS[8] = 10; + SU2ToCGNS[9] = 15; + SU2ToCGNS[10] = 14; + SU2ToCGNS[11] = 7; + SU2ToCGNS[12] = 3; + SU2ToCGNS[13] = 9; + SU2ToCGNS[14] = 8; + SU2ToCGNS[15] = 2; } -void CCGNSElementType::CreateDataQUAD_25(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - vector &SU2ToCGNS) { - +void CCGNSElementType::CreateDataQUAD_25(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + vector& SU2ToCGNS) { /* The QUAD_25 element is a quartic quadrilateral. In CGNS the nodes are numbered as follows: - First the vertex nodes. - Second the edge nodes. @@ -654,39 +724,54 @@ void CCGNSElementType::CreateDataQUAD_25(unsigned short &VTK_Type, where the i-direction is defined from node 0 to 1 and the j-direction from node 0 along the other edge. */ VTK_Type = QUADRILATERAL; - nPoly = 4; - nDOFs = 25; + nPoly = 4; + nDOFs = 25; SU2ToCGNS.resize(nDOFs); - SU2ToCGNS[0] = 0; SU2ToCGNS[1] = 4; SU2ToCGNS[2] = 5; SU2ToCGNS[3] = 6; - SU2ToCGNS[4] = 1; SU2ToCGNS[5] = 15; SU2ToCGNS[6] = 16; SU2ToCGNS[7] = 17; - SU2ToCGNS[8] = 18; SU2ToCGNS[9] = 7; SU2ToCGNS[10] = 14; SU2ToCGNS[11] = 23; - SU2ToCGNS[12] = 24; SU2ToCGNS[13] = 19; SU2ToCGNS[14] = 8; SU2ToCGNS[15] = 13; - SU2ToCGNS[16] = 22; SU2ToCGNS[17] = 21; SU2ToCGNS[18] = 20; SU2ToCGNS[19] = 9; - SU2ToCGNS[20] = 3; SU2ToCGNS[21] = 12; SU2ToCGNS[22] = 11; SU2ToCGNS[23] = 10; - SU2ToCGNS[24] = 2; + SU2ToCGNS[0] = 0; + SU2ToCGNS[1] = 4; + SU2ToCGNS[2] = 5; + SU2ToCGNS[3] = 6; + SU2ToCGNS[4] = 1; + SU2ToCGNS[5] = 15; + SU2ToCGNS[6] = 16; + SU2ToCGNS[7] = 17; + SU2ToCGNS[8] = 18; + SU2ToCGNS[9] = 7; + SU2ToCGNS[10] = 14; + SU2ToCGNS[11] = 23; + SU2ToCGNS[12] = 24; + SU2ToCGNS[13] = 19; + SU2ToCGNS[14] = 8; + SU2ToCGNS[15] = 13; + SU2ToCGNS[16] = 22; + SU2ToCGNS[17] = 21; + SU2ToCGNS[18] = 20; + SU2ToCGNS[19] = 9; + SU2ToCGNS[20] = 3; + SU2ToCGNS[21] = 12; + SU2ToCGNS[22] = 11; + SU2ToCGNS[23] = 10; + SU2ToCGNS[24] = 2; } -void CCGNSElementType::CreateDataTETRA_4(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - vector &SU2ToCGNS) { - +void CCGNSElementType::CreateDataTETRA_4(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + vector& SU2ToCGNS) { /* The TETRA_4 element is a linear tetrahedron. The node numbering is the same in SU2 and CGNS. */ VTK_Type = TETRAHEDRON; - nPoly = 1; - nDOFs = 4; + nPoly = 1; + nDOFs = 4; SU2ToCGNS.resize(nDOFs); - SU2ToCGNS[0] = 0; SU2ToCGNS[1] = 1; SU2ToCGNS[2] = 2; SU2ToCGNS[3] = 3; + SU2ToCGNS[0] = 0; + SU2ToCGNS[1] = 1; + SU2ToCGNS[2] = 2; + SU2ToCGNS[3] = 3; } -void CCGNSElementType::CreateDataTETRA_10(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - vector &SU2ToCGNS) { - +void CCGNSElementType::CreateDataTETRA_10(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + vector& SU2ToCGNS) { /* The TETRA_10 element is a quadratic tetrahedron. In CGNS the nodes are numbered as follows: - First the vertex nodes. - Second the edge nodes. @@ -697,20 +782,24 @@ void CCGNSElementType::CreateDataTETRA_10(unsigned short &VTK_Type, from node 0 along the second edge and the k-direction from node 0 along the third edge. */ VTK_Type = TETRAHEDRON; - nPoly = 2; - nDOFs = 10; + nPoly = 2; + nDOFs = 10; SU2ToCGNS.resize(nDOFs); - SU2ToCGNS[0] = 0; SU2ToCGNS[1] = 4; SU2ToCGNS[2] = 1; SU2ToCGNS[3] = 6; - SU2ToCGNS[4] = 5; SU2ToCGNS[5] = 2; SU2ToCGNS[6] = 7; SU2ToCGNS[7] = 8; - SU2ToCGNS[8] = 9; SU2ToCGNS[9] = 3; + SU2ToCGNS[0] = 0; + SU2ToCGNS[1] = 4; + SU2ToCGNS[2] = 1; + SU2ToCGNS[3] = 6; + SU2ToCGNS[4] = 5; + SU2ToCGNS[5] = 2; + SU2ToCGNS[6] = 7; + SU2ToCGNS[7] = 8; + SU2ToCGNS[8] = 9; + SU2ToCGNS[9] = 3; } -void CCGNSElementType::CreateDataTETRA_20(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - vector &SU2ToCGNS) { - +void CCGNSElementType::CreateDataTETRA_20(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + vector& SU2ToCGNS) { /* The TETRA_20 element is a cubic tetrahedron. In CGNS the nodes are numbered as follows: - First the vertex nodes. - Second the edge nodes. @@ -721,22 +810,34 @@ void CCGNSElementType::CreateDataTETRA_20(unsigned short &VTK_Type, from node 0 along the second edge and the k-direction from node 0 along the third edge. */ VTK_Type = TETRAHEDRON; - nPoly = 3; - nDOFs = 20; + nPoly = 3; + nDOFs = 20; SU2ToCGNS.resize(nDOFs); - SU2ToCGNS[0] = 0; SU2ToCGNS[1] = 4; SU2ToCGNS[2] = 5; SU2ToCGNS[3] = 1; - SU2ToCGNS[4] = 9; SU2ToCGNS[5] = 16; SU2ToCGNS[6] = 6; SU2ToCGNS[7] = 8; - SU2ToCGNS[8] = 7; SU2ToCGNS[9] = 2; SU2ToCGNS[10] = 10; SU2ToCGNS[11] = 17; - SU2ToCGNS[12] = 12; SU2ToCGNS[13] = 19; SU2ToCGNS[14] = 18; SU2ToCGNS[15] = 14; - SU2ToCGNS[16] = 11; SU2ToCGNS[17] = 13; SU2ToCGNS[18] = 15; SU2ToCGNS[19] = 3; + SU2ToCGNS[0] = 0; + SU2ToCGNS[1] = 4; + SU2ToCGNS[2] = 5; + SU2ToCGNS[3] = 1; + SU2ToCGNS[4] = 9; + SU2ToCGNS[5] = 16; + SU2ToCGNS[6] = 6; + SU2ToCGNS[7] = 8; + SU2ToCGNS[8] = 7; + SU2ToCGNS[9] = 2; + SU2ToCGNS[10] = 10; + SU2ToCGNS[11] = 17; + SU2ToCGNS[12] = 12; + SU2ToCGNS[13] = 19; + SU2ToCGNS[14] = 18; + SU2ToCGNS[15] = 14; + SU2ToCGNS[16] = 11; + SU2ToCGNS[17] = 13; + SU2ToCGNS[18] = 15; + SU2ToCGNS[19] = 3; } -void CCGNSElementType::CreateDataTETRA_35(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - vector &SU2ToCGNS) { - +void CCGNSElementType::CreateDataTETRA_35(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + vector& SU2ToCGNS) { /* The TETRA_35 element is a quartic tetrahedron. In CGNS the nodes are numbered as follows: - First the vertex nodes. - Second the edge nodes. @@ -750,26 +851,49 @@ void CCGNSElementType::CreateDataTETRA_35(unsigned short &VTK_Type, currently ignored, i.e. it is assumed that the spacing in parameter space is uniform. */ VTK_Type = TETRAHEDRON; - nPoly = 4; - nDOFs = 35; + nPoly = 4; + nDOFs = 35; SU2ToCGNS.resize(nDOFs); - SU2ToCGNS[0] = 0; SU2ToCGNS[1] = 4; SU2ToCGNS[2] = 5; SU2ToCGNS[3] = 6; - SU2ToCGNS[4] = 1; SU2ToCGNS[5] = 12; SU2ToCGNS[6] = 22; SU2ToCGNS[7] = 23; - SU2ToCGNS[8] = 7; SU2ToCGNS[9] = 11; SU2ToCGNS[10] = 24; SU2ToCGNS[11] = 8; - SU2ToCGNS[12] = 10; SU2ToCGNS[13] = 9; SU2ToCGNS[14] = 2; SU2ToCGNS[15] = 13; - SU2ToCGNS[16] = 25; SU2ToCGNS[17] = 26; SU2ToCGNS[18] = 16; SU2ToCGNS[19] = 32; - SU2ToCGNS[20] = 34; SU2ToCGNS[21] = 28; SU2ToCGNS[22] = 31; SU2ToCGNS[23] = 29; - SU2ToCGNS[24] = 19; SU2ToCGNS[25] = 14; SU2ToCGNS[26] = 27; SU2ToCGNS[27] = 17; - SU2ToCGNS[28] = 33; SU2ToCGNS[29] = 30; SU2ToCGNS[30] = 20; SU2ToCGNS[31] = 15; - SU2ToCGNS[32] = 18; SU2ToCGNS[33] = 21; SU2ToCGNS[34] = 3; + SU2ToCGNS[0] = 0; + SU2ToCGNS[1] = 4; + SU2ToCGNS[2] = 5; + SU2ToCGNS[3] = 6; + SU2ToCGNS[4] = 1; + SU2ToCGNS[5] = 12; + SU2ToCGNS[6] = 22; + SU2ToCGNS[7] = 23; + SU2ToCGNS[8] = 7; + SU2ToCGNS[9] = 11; + SU2ToCGNS[10] = 24; + SU2ToCGNS[11] = 8; + SU2ToCGNS[12] = 10; + SU2ToCGNS[13] = 9; + SU2ToCGNS[14] = 2; + SU2ToCGNS[15] = 13; + SU2ToCGNS[16] = 25; + SU2ToCGNS[17] = 26; + SU2ToCGNS[18] = 16; + SU2ToCGNS[19] = 32; + SU2ToCGNS[20] = 34; + SU2ToCGNS[21] = 28; + SU2ToCGNS[22] = 31; + SU2ToCGNS[23] = 29; + SU2ToCGNS[24] = 19; + SU2ToCGNS[25] = 14; + SU2ToCGNS[26] = 27; + SU2ToCGNS[27] = 17; + SU2ToCGNS[28] = 33; + SU2ToCGNS[29] = 30; + SU2ToCGNS[30] = 20; + SU2ToCGNS[31] = 15; + SU2ToCGNS[32] = 18; + SU2ToCGNS[33] = 21; + SU2ToCGNS[34] = 3; } -void CCGNSElementType::CreateDataPYRA_5(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - vector &SU2ToCGNS) { - +void CCGNSElementType::CreateDataPYRA_5(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + vector& SU2ToCGNS) { /* The PYRA_5 element is a linear pyramid. In CGNS the nodes are numbered as follows: - First the vertex nodes. - Second the edge nodes (not present in PYRA_5). @@ -780,19 +904,19 @@ void CCGNSElementType::CreateDataPYRA_5(unsigned short &VTK_Type, from node 0 along the second edge and the k-direction from node 0 along the third edge. */ VTK_Type = PYRAMID; - nPoly = 1; - nDOFs = 5; + nPoly = 1; + nDOFs = 5; SU2ToCGNS.resize(nDOFs); - SU2ToCGNS[0] = 0; SU2ToCGNS[1] = 1; SU2ToCGNS[2] = 3; SU2ToCGNS[3] = 2; + SU2ToCGNS[0] = 0; + SU2ToCGNS[1] = 1; + SU2ToCGNS[2] = 3; + SU2ToCGNS[3] = 2; SU2ToCGNS[4] = 4; } -void CCGNSElementType::CreateDataPYRA_14(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - vector &SU2ToCGNS) { - +void CCGNSElementType::CreateDataPYRA_14(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + vector& SU2ToCGNS) { /* The PYRA_14 element is a quadratic pyramid. In CGNS the nodes are numbered as follows: - First the vertex nodes. - Second the edge nodes. @@ -803,21 +927,28 @@ void CCGNSElementType::CreateDataPYRA_14(unsigned short &VTK_Type, from node 0 along the second edge and the k-direction from node 0 along the third edge. */ VTK_Type = PYRAMID; - nPoly = 2; - nDOFs = 14; + nPoly = 2; + nDOFs = 14; SU2ToCGNS.resize(nDOFs); - SU2ToCGNS[0] = 0; SU2ToCGNS[1] = 5; SU2ToCGNS[2] = 1; SU2ToCGNS[3] = 8; - SU2ToCGNS[4] = 13; SU2ToCGNS[5] = 6; SU2ToCGNS[6] = 3; SU2ToCGNS[7] = 7; - SU2ToCGNS[8] = 2; SU2ToCGNS[9] = 9; SU2ToCGNS[10] = 10; SU2ToCGNS[11] = 12; - SU2ToCGNS[12] = 11; SU2ToCGNS[13] = 4; + SU2ToCGNS[0] = 0; + SU2ToCGNS[1] = 5; + SU2ToCGNS[2] = 1; + SU2ToCGNS[3] = 8; + SU2ToCGNS[4] = 13; + SU2ToCGNS[5] = 6; + SU2ToCGNS[6] = 3; + SU2ToCGNS[7] = 7; + SU2ToCGNS[8] = 2; + SU2ToCGNS[9] = 9; + SU2ToCGNS[10] = 10; + SU2ToCGNS[11] = 12; + SU2ToCGNS[12] = 11; + SU2ToCGNS[13] = 4; } -void CCGNSElementType::CreateDataPYRA_30(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - vector &SU2ToCGNS) { - +void CCGNSElementType::CreateDataPYRA_30(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + vector& SU2ToCGNS) { /* The PYRA_30 element is a cubic pyramid. In CGNS the nodes are numbered as follows: - First the vertex nodes. - Second the edge nodes. @@ -828,25 +959,44 @@ void CCGNSElementType::CreateDataPYRA_30(unsigned short &VTK_Type, from node 0 along the second edge and the k-direction from node 0 along the third edge. */ VTK_Type = PYRAMID; - nPoly = 3; - nDOFs = 30; + nPoly = 3; + nDOFs = 30; SU2ToCGNS.resize(nDOFs); - SU2ToCGNS[0] = 0; SU2ToCGNS[1] = 5; SU2ToCGNS[2] = 6; SU2ToCGNS[3] = 1; - SU2ToCGNS[4] = 12; SU2ToCGNS[5] = 21; SU2ToCGNS[6] = 22; SU2ToCGNS[7] = 7; - SU2ToCGNS[8] = 11; SU2ToCGNS[9] = 24; SU2ToCGNS[10] = 23; SU2ToCGNS[11] = 8; - SU2ToCGNS[12] = 3; SU2ToCGNS[13] = 20; SU2ToCGNS[14] = 9; SU2ToCGNS[15] = 3; - SU2ToCGNS[16] = 13; SU2ToCGNS[17] = 25; SU2ToCGNS[18] = 15; SU2ToCGNS[19] = 28; - SU2ToCGNS[20] = 29; SU2ToCGNS[21] = 26; SU2ToCGNS[22] = 19; SU2ToCGNS[23] = 27; - SU2ToCGNS[24] = 17; SU2ToCGNS[25] = 14; SU2ToCGNS[26] = 16; SU2ToCGNS[27] = 20; - SU2ToCGNS[28] = 18; SU2ToCGNS[29] = 4; + SU2ToCGNS[0] = 0; + SU2ToCGNS[1] = 5; + SU2ToCGNS[2] = 6; + SU2ToCGNS[3] = 1; + SU2ToCGNS[4] = 12; + SU2ToCGNS[5] = 21; + SU2ToCGNS[6] = 22; + SU2ToCGNS[7] = 7; + SU2ToCGNS[8] = 11; + SU2ToCGNS[9] = 24; + SU2ToCGNS[10] = 23; + SU2ToCGNS[11] = 8; + SU2ToCGNS[12] = 3; + SU2ToCGNS[13] = 20; + SU2ToCGNS[14] = 9; + SU2ToCGNS[15] = 3; + SU2ToCGNS[16] = 13; + SU2ToCGNS[17] = 25; + SU2ToCGNS[18] = 15; + SU2ToCGNS[19] = 28; + SU2ToCGNS[20] = 29; + SU2ToCGNS[21] = 26; + SU2ToCGNS[22] = 19; + SU2ToCGNS[23] = 27; + SU2ToCGNS[24] = 17; + SU2ToCGNS[25] = 14; + SU2ToCGNS[26] = 16; + SU2ToCGNS[27] = 20; + SU2ToCGNS[28] = 18; + SU2ToCGNS[29] = 4; } -void CCGNSElementType::CreateDataPYRA_55(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - vector &SU2ToCGNS) { - +void CCGNSElementType::CreateDataPYRA_55(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + vector& SU2ToCGNS) { /* The PYRA_55 element is a quartic pyramid. In CGNS the nodes are numbered as follows: - First the vertex nodes. - Second the edge nodes. @@ -860,47 +1010,86 @@ void CCGNSElementType::CreateDataPYRA_55(unsigned short &VTK_Type, effect is currently ignored, i.e. it is assumed that the spacing in parameter space is uniform.*/ VTK_Type = PYRAMID; - nPoly = 4; - nDOFs = 55; + nPoly = 4; + nDOFs = 55; SU2ToCGNS.resize(nDOFs); - SU2ToCGNS[0] = 0; SU2ToCGNS[1] = 5; SU2ToCGNS[2] = 6; SU2ToCGNS[3] = 7; - SU2ToCGNS[4] = 1; SU2ToCGNS[5] = 16; SU2ToCGNS[6] = 29; SU2ToCGNS[7] = 30; - SU2ToCGNS[8] = 31; SU2ToCGNS[9] = 8; SU2ToCGNS[10] = 15; SU2ToCGNS[11] = 36; - SU2ToCGNS[12] = 37; SU2ToCGNS[13] = 32; SU2ToCGNS[14] = 9; SU2ToCGNS[15] = 14; - SU2ToCGNS[16] = 35; SU2ToCGNS[17] = 34; SU2ToCGNS[18] = 33; SU2ToCGNS[19] = 10; - SU2ToCGNS[20] = 3; SU2ToCGNS[21] = 13; SU2ToCGNS[22] = 12; SU2ToCGNS[23] = 11; - SU2ToCGNS[24] = 2; SU2ToCGNS[25] = 17; SU2ToCGNS[26] = 38; SU2ToCGNS[27] = 39; - SU2ToCGNS[28] = 20; SU2ToCGNS[29] = 48; SU2ToCGNS[30] = 50; SU2ToCGNS[31] = 51; - SU2ToCGNS[32] = 41; SU2ToCGNS[33] = 47; SU2ToCGNS[34] = 53; SU2ToCGNS[35] = 52; - SU2ToCGNS[36] = 42; SU2ToCGNS[37] = 26; SU2ToCGNS[38] = 45; SU2ToCGNS[39] = 44; - SU2ToCGNS[40] = 23; SU2ToCGNS[41] = 18; SU2ToCGNS[42] = 40; SU2ToCGNS[43] = 21; - SU2ToCGNS[44] = 49; SU2ToCGNS[45] = 54; SU2ToCGNS[46] = 43; SU2ToCGNS[47] = 27; - SU2ToCGNS[48] = 46; SU2ToCGNS[49] = 24; SU2ToCGNS[50] = 19; SU2ToCGNS[51] = 22; - SU2ToCGNS[52] = 28; SU2ToCGNS[53] = 25; SU2ToCGNS[54] = 4; + SU2ToCGNS[0] = 0; + SU2ToCGNS[1] = 5; + SU2ToCGNS[2] = 6; + SU2ToCGNS[3] = 7; + SU2ToCGNS[4] = 1; + SU2ToCGNS[5] = 16; + SU2ToCGNS[6] = 29; + SU2ToCGNS[7] = 30; + SU2ToCGNS[8] = 31; + SU2ToCGNS[9] = 8; + SU2ToCGNS[10] = 15; + SU2ToCGNS[11] = 36; + SU2ToCGNS[12] = 37; + SU2ToCGNS[13] = 32; + SU2ToCGNS[14] = 9; + SU2ToCGNS[15] = 14; + SU2ToCGNS[16] = 35; + SU2ToCGNS[17] = 34; + SU2ToCGNS[18] = 33; + SU2ToCGNS[19] = 10; + SU2ToCGNS[20] = 3; + SU2ToCGNS[21] = 13; + SU2ToCGNS[22] = 12; + SU2ToCGNS[23] = 11; + SU2ToCGNS[24] = 2; + SU2ToCGNS[25] = 17; + SU2ToCGNS[26] = 38; + SU2ToCGNS[27] = 39; + SU2ToCGNS[28] = 20; + SU2ToCGNS[29] = 48; + SU2ToCGNS[30] = 50; + SU2ToCGNS[31] = 51; + SU2ToCGNS[32] = 41; + SU2ToCGNS[33] = 47; + SU2ToCGNS[34] = 53; + SU2ToCGNS[35] = 52; + SU2ToCGNS[36] = 42; + SU2ToCGNS[37] = 26; + SU2ToCGNS[38] = 45; + SU2ToCGNS[39] = 44; + SU2ToCGNS[40] = 23; + SU2ToCGNS[41] = 18; + SU2ToCGNS[42] = 40; + SU2ToCGNS[43] = 21; + SU2ToCGNS[44] = 49; + SU2ToCGNS[45] = 54; + SU2ToCGNS[46] = 43; + SU2ToCGNS[47] = 27; + SU2ToCGNS[48] = 46; + SU2ToCGNS[49] = 24; + SU2ToCGNS[50] = 19; + SU2ToCGNS[51] = 22; + SU2ToCGNS[52] = 28; + SU2ToCGNS[53] = 25; + SU2ToCGNS[54] = 4; } -void CCGNSElementType::CreateDataPENTA_6(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - vector &SU2ToCGNS) { - +void CCGNSElementType::CreateDataPENTA_6(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + vector& SU2ToCGNS) { /* The PENTA_6 element is a linear prism. The node numbering is the same in SU2 and CGNS. */ VTK_Type = PRISM; - nPoly = 1; - nDOFs = 6; + nPoly = 1; + nDOFs = 6; SU2ToCGNS.resize(nDOFs); - SU2ToCGNS[0] = 0; SU2ToCGNS[1] = 1; SU2ToCGNS[2] = 2; - SU2ToCGNS[3] = 3; SU2ToCGNS[4] = 4; SU2ToCGNS[5] = 5; + SU2ToCGNS[0] = 0; + SU2ToCGNS[1] = 1; + SU2ToCGNS[2] = 2; + SU2ToCGNS[3] = 3; + SU2ToCGNS[4] = 4; + SU2ToCGNS[5] = 5; } -void CCGNSElementType::CreateDataPENTA_18(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - vector &SU2ToCGNS) { - +void CCGNSElementType::CreateDataPENTA_18(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + vector& SU2ToCGNS) { /* The PENTA_18 element is a quadratic prism. In CGNS the nodes are numbered as follows: - First the vertex nodes. - Second the edge nodes. @@ -911,22 +1100,32 @@ void CCGNSElementType::CreateDataPENTA_18(unsigned short &VTK_Type, from node 0 along the second edge and the k-direction from node 0 along the third edge. */ VTK_Type = PRISM; - nPoly = 2; - nDOFs = 18; + nPoly = 2; + nDOFs = 18; SU2ToCGNS.resize(nDOFs); - SU2ToCGNS[0] = 0; SU2ToCGNS[1] = 6; SU2ToCGNS[2] = 1; SU2ToCGNS[3] = 8; - SU2ToCGNS[4] = 7; SU2ToCGNS[5] = 2; SU2ToCGNS[6] = 9; SU2ToCGNS[7] = 15; - SU2ToCGNS[8] = 10; SU2ToCGNS[9] = 17; SU2ToCGNS[10] = 16; SU2ToCGNS[11] = 11; - SU2ToCGNS[12] = 3; SU2ToCGNS[13] = 12; SU2ToCGNS[14] = 4; SU2ToCGNS[15] = 14; - SU2ToCGNS[16] = 13; SU2ToCGNS[17] = 5; + SU2ToCGNS[0] = 0; + SU2ToCGNS[1] = 6; + SU2ToCGNS[2] = 1; + SU2ToCGNS[3] = 8; + SU2ToCGNS[4] = 7; + SU2ToCGNS[5] = 2; + SU2ToCGNS[6] = 9; + SU2ToCGNS[7] = 15; + SU2ToCGNS[8] = 10; + SU2ToCGNS[9] = 17; + SU2ToCGNS[10] = 16; + SU2ToCGNS[11] = 11; + SU2ToCGNS[12] = 3; + SU2ToCGNS[13] = 12; + SU2ToCGNS[14] = 4; + SU2ToCGNS[15] = 14; + SU2ToCGNS[16] = 13; + SU2ToCGNS[17] = 5; } -void CCGNSElementType::CreateDataPENTA_40(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - vector &SU2ToCGNS) { - +void CCGNSElementType::CreateDataPENTA_40(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + vector& SU2ToCGNS) { /* The PENTA_40 element is a cubic prism. In CGNS the nodes are numbered as follows: - First the vertex nodes. - Second the edge nodes. @@ -937,27 +1136,54 @@ void CCGNSElementType::CreateDataPENTA_40(unsigned short &VTK_Type, from node 0 along the second edge and the k-direction from node 0 along the third edge. */ VTK_Type = PRISM; - nPoly = 3; - nDOFs = 40; + nPoly = 3; + nDOFs = 40; SU2ToCGNS.resize(nDOFs); - SU2ToCGNS[0] = 0; SU2ToCGNS[1] = 6; SU2ToCGNS[2] = 7; SU2ToCGNS[3] = 1; - SU2ToCGNS[4] = 11; SU2ToCGNS[5] = 24; SU2ToCGNS[6] = 8; SU2ToCGNS[7] = 10; - SU2ToCGNS[8] = 9; SU2ToCGNS[9] = 2; SU2ToCGNS[10] = 12; SU2ToCGNS[11] = 25; - SU2ToCGNS[12] = 26; SU2ToCGNS[13] = 14; SU2ToCGNS[14] = 34; SU2ToCGNS[15] = 38; - SU2ToCGNS[16] = 29; SU2ToCGNS[17] = 33; SU2ToCGNS[18] = 30; SU2ToCGNS[19] = 16; - SU2ToCGNS[20] = 13; SU2ToCGNS[21] = 28; SU2ToCGNS[22] = 27; SU2ToCGNS[23] = 15; - SU2ToCGNS[24] = 35; SU2ToCGNS[25] = 39; SU2ToCGNS[26] = 32; SU2ToCGNS[27] = 36; - SU2ToCGNS[28] = 31; SU2ToCGNS[29] = 17; SU2ToCGNS[30] = 3; SU2ToCGNS[31] = 18; - SU2ToCGNS[32] = 19; SU2ToCGNS[33] = 4; SU2ToCGNS[34] = 23; SU2ToCGNS[35] = 37; - SU2ToCGNS[36] = 20; SU2ToCGNS[37] = 22; SU2ToCGNS[38] = 21; SU2ToCGNS[39] = 5; + SU2ToCGNS[0] = 0; + SU2ToCGNS[1] = 6; + SU2ToCGNS[2] = 7; + SU2ToCGNS[3] = 1; + SU2ToCGNS[4] = 11; + SU2ToCGNS[5] = 24; + SU2ToCGNS[6] = 8; + SU2ToCGNS[7] = 10; + SU2ToCGNS[8] = 9; + SU2ToCGNS[9] = 2; + SU2ToCGNS[10] = 12; + SU2ToCGNS[11] = 25; + SU2ToCGNS[12] = 26; + SU2ToCGNS[13] = 14; + SU2ToCGNS[14] = 34; + SU2ToCGNS[15] = 38; + SU2ToCGNS[16] = 29; + SU2ToCGNS[17] = 33; + SU2ToCGNS[18] = 30; + SU2ToCGNS[19] = 16; + SU2ToCGNS[20] = 13; + SU2ToCGNS[21] = 28; + SU2ToCGNS[22] = 27; + SU2ToCGNS[23] = 15; + SU2ToCGNS[24] = 35; + SU2ToCGNS[25] = 39; + SU2ToCGNS[26] = 32; + SU2ToCGNS[27] = 36; + SU2ToCGNS[28] = 31; + SU2ToCGNS[29] = 17; + SU2ToCGNS[30] = 3; + SU2ToCGNS[31] = 18; + SU2ToCGNS[32] = 19; + SU2ToCGNS[33] = 4; + SU2ToCGNS[34] = 23; + SU2ToCGNS[35] = 37; + SU2ToCGNS[36] = 20; + SU2ToCGNS[37] = 22; + SU2ToCGNS[38] = 21; + SU2ToCGNS[39] = 5; } -void CCGNSElementType::CreateDataPENTA_75(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - vector &SU2ToCGNS) { - +void CCGNSElementType::CreateDataPENTA_75(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + vector& SU2ToCGNS) { /* The PENTA_75 element is a quartic prism. In CGNS the nodes are numbered as follows: - First the vertex nodes. - Second the edge nodes. @@ -971,36 +1197,89 @@ void CCGNSElementType::CreateDataPENTA_75(unsigned short &VTK_Type, effect is currently ignored, i.e. it is assumed that the spacing in parameter space is uniform. */ VTK_Type = PRISM; - nPoly = 4; - nDOFs = 75; + nPoly = 4; + nDOFs = 75; SU2ToCGNS.resize(nDOFs); - SU2ToCGNS[0] = 0; SU2ToCGNS[1] = 6; SU2ToCGNS[2] = 7; SU2ToCGNS[3] = 8; - SU2ToCGNS[4] = 1; SU2ToCGNS[5] = 14; SU2ToCGNS[6] = 33; SU2ToCGNS[7] = 34; - SU2ToCGNS[8] = 9; SU2ToCGNS[9] = 13; SU2ToCGNS[10] = 35; SU2ToCGNS[11] = 10; - SU2ToCGNS[12] = 12; SU2ToCGNS[13] = 11; SU2ToCGNS[14] = 2; SU2ToCGNS[15] = 15; - SU2ToCGNS[16] = 36; SU2ToCGNS[17] = 37; SU2ToCGNS[18] = 38; SU2ToCGNS[19] = 18; - SU2ToCGNS[20] = 56; SU2ToCGNS[21] = 66; SU2ToCGNS[22] = 67; SU2ToCGNS[23] = 45; - SU2ToCGNS[24] = 55; SU2ToCGNS[25] = 68; SU2ToCGNS[26] = 46; SU2ToCGNS[27] = 54; - SU2ToCGNS[28] = 47; SU2ToCGNS[29] = 21; SU2ToCGNS[30] = 16; SU2ToCGNS[31] = 43; - SU2ToCGNS[32] = 44; SU2ToCGNS[33] = 39; SU2ToCGNS[34] = 19; SU2ToCGNS[35] = 57; - SU2ToCGNS[36] = 69; SU2ToCGNS[37] = 70; SU2ToCGNS[38] = 52; SU2ToCGNS[39] = 62; - SU2ToCGNS[40] = 71; SU2ToCGNS[41] = 53; SU2ToCGNS[42] = 61; SU2ToCGNS[43] = 48; - SU2ToCGNS[44] = 22; SU2ToCGNS[45] = 17; SU2ToCGNS[46] = 42; SU2ToCGNS[47] = 41; - SU2ToCGNS[48] = 40; SU2ToCGNS[49] = 20; SU2ToCGNS[50] = 58; SU2ToCGNS[51] = 72; - SU2ToCGNS[52] = 73; SU2ToCGNS[53] = 51; SU2ToCGNS[54] = 59; SU2ToCGNS[55] = 74; - SU2ToCGNS[56] = 50; SU2ToCGNS[57] = 60; SU2ToCGNS[58] = 49; SU2ToCGNS[59] = 23; - SU2ToCGNS[60] = 3; SU2ToCGNS[61] = 24; SU2ToCGNS[62] = 25; SU2ToCGNS[63] = 26; - SU2ToCGNS[64] = 4; SU2ToCGNS[65] = 32; SU2ToCGNS[66] = 63; SU2ToCGNS[67] = 64; - SU2ToCGNS[68] = 27; SU2ToCGNS[69] = 31; SU2ToCGNS[70] = 65; SU2ToCGNS[71] = 28; - SU2ToCGNS[72] = 30; SU2ToCGNS[73] = 29; SU2ToCGNS[74] = 5; + SU2ToCGNS[0] = 0; + SU2ToCGNS[1] = 6; + SU2ToCGNS[2] = 7; + SU2ToCGNS[3] = 8; + SU2ToCGNS[4] = 1; + SU2ToCGNS[5] = 14; + SU2ToCGNS[6] = 33; + SU2ToCGNS[7] = 34; + SU2ToCGNS[8] = 9; + SU2ToCGNS[9] = 13; + SU2ToCGNS[10] = 35; + SU2ToCGNS[11] = 10; + SU2ToCGNS[12] = 12; + SU2ToCGNS[13] = 11; + SU2ToCGNS[14] = 2; + SU2ToCGNS[15] = 15; + SU2ToCGNS[16] = 36; + SU2ToCGNS[17] = 37; + SU2ToCGNS[18] = 38; + SU2ToCGNS[19] = 18; + SU2ToCGNS[20] = 56; + SU2ToCGNS[21] = 66; + SU2ToCGNS[22] = 67; + SU2ToCGNS[23] = 45; + SU2ToCGNS[24] = 55; + SU2ToCGNS[25] = 68; + SU2ToCGNS[26] = 46; + SU2ToCGNS[27] = 54; + SU2ToCGNS[28] = 47; + SU2ToCGNS[29] = 21; + SU2ToCGNS[30] = 16; + SU2ToCGNS[31] = 43; + SU2ToCGNS[32] = 44; + SU2ToCGNS[33] = 39; + SU2ToCGNS[34] = 19; + SU2ToCGNS[35] = 57; + SU2ToCGNS[36] = 69; + SU2ToCGNS[37] = 70; + SU2ToCGNS[38] = 52; + SU2ToCGNS[39] = 62; + SU2ToCGNS[40] = 71; + SU2ToCGNS[41] = 53; + SU2ToCGNS[42] = 61; + SU2ToCGNS[43] = 48; + SU2ToCGNS[44] = 22; + SU2ToCGNS[45] = 17; + SU2ToCGNS[46] = 42; + SU2ToCGNS[47] = 41; + SU2ToCGNS[48] = 40; + SU2ToCGNS[49] = 20; + SU2ToCGNS[50] = 58; + SU2ToCGNS[51] = 72; + SU2ToCGNS[52] = 73; + SU2ToCGNS[53] = 51; + SU2ToCGNS[54] = 59; + SU2ToCGNS[55] = 74; + SU2ToCGNS[56] = 50; + SU2ToCGNS[57] = 60; + SU2ToCGNS[58] = 49; + SU2ToCGNS[59] = 23; + SU2ToCGNS[60] = 3; + SU2ToCGNS[61] = 24; + SU2ToCGNS[62] = 25; + SU2ToCGNS[63] = 26; + SU2ToCGNS[64] = 4; + SU2ToCGNS[65] = 32; + SU2ToCGNS[66] = 63; + SU2ToCGNS[67] = 64; + SU2ToCGNS[68] = 27; + SU2ToCGNS[69] = 31; + SU2ToCGNS[70] = 65; + SU2ToCGNS[71] = 28; + SU2ToCGNS[72] = 30; + SU2ToCGNS[73] = 29; + SU2ToCGNS[74] = 5; } -void CCGNSElementType::CreateDataHEXA_8(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - vector &SU2ToCGNS) { - +void CCGNSElementType::CreateDataHEXA_8(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + vector& SU2ToCGNS) { /* The HEXA_8 element is a linear hexahedron. In CGNS the nodes are numbered as follows: - First the vertex nodes. - Second the edge nodes (not present in HEXA_8). @@ -1011,19 +1290,22 @@ void CCGNSElementType::CreateDataHEXA_8(unsigned short &VTK_Type, from node 0 along the second edge and the k-direction from node 0 along the third edge. */ VTK_Type = HEXAHEDRON; - nPoly = 1; - nDOFs = 8; + nPoly = 1; + nDOFs = 8; SU2ToCGNS.resize(nDOFs); - SU2ToCGNS[0] = 0; SU2ToCGNS[1] = 1; SU2ToCGNS[2] = 3; SU2ToCGNS[3] = 2; - SU2ToCGNS[4] = 4; SU2ToCGNS[5] = 5; SU2ToCGNS[6] = 7; SU2ToCGNS[7] = 6; + SU2ToCGNS[0] = 0; + SU2ToCGNS[1] = 1; + SU2ToCGNS[2] = 3; + SU2ToCGNS[3] = 2; + SU2ToCGNS[4] = 4; + SU2ToCGNS[5] = 5; + SU2ToCGNS[6] = 7; + SU2ToCGNS[7] = 6; } -void CCGNSElementType::CreateDataHEXA_27(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - vector &SU2ToCGNS) { - +void CCGNSElementType::CreateDataHEXA_27(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + vector& SU2ToCGNS) { /* The HEXA_27 element is a quadratic hexahedron. In CGNS the nodes are numbered as follows: - First the vertex nodes. - Second the edge nodes. @@ -1034,24 +1316,41 @@ void CCGNSElementType::CreateDataHEXA_27(unsigned short &VTK_Type, from node 0 along the second edge and the k-direction from node 0 along the third edge. */ VTK_Type = HEXAHEDRON; - nPoly = 2; - nDOFs = 27; + nPoly = 2; + nDOFs = 27; SU2ToCGNS.resize(nDOFs); - SU2ToCGNS[0] = 0; SU2ToCGNS[1] = 8; SU2ToCGNS[2] = 1; SU2ToCGNS[3] = 11; - SU2ToCGNS[4] = 20; SU2ToCGNS[5] = 9; SU2ToCGNS[6] = 3; SU2ToCGNS[7] = 10; - SU2ToCGNS[8] = 2; SU2ToCGNS[9] = 12; SU2ToCGNS[10] = 21; SU2ToCGNS[11] = 13; - SU2ToCGNS[12] = 24; SU2ToCGNS[13] = 26; SU2ToCGNS[14] = 22; SU2ToCGNS[15] = 15; - SU2ToCGNS[16] = 23; SU2ToCGNS[17] = 14; SU2ToCGNS[18] = 4; SU2ToCGNS[19] = 16; - SU2ToCGNS[20] = 5; SU2ToCGNS[21] = 19; SU2ToCGNS[22] = 25; SU2ToCGNS[23] = 17; - SU2ToCGNS[24] = 7; SU2ToCGNS[25] = 18; SU2ToCGNS[26] = 6; + SU2ToCGNS[0] = 0; + SU2ToCGNS[1] = 8; + SU2ToCGNS[2] = 1; + SU2ToCGNS[3] = 11; + SU2ToCGNS[4] = 20; + SU2ToCGNS[5] = 9; + SU2ToCGNS[6] = 3; + SU2ToCGNS[7] = 10; + SU2ToCGNS[8] = 2; + SU2ToCGNS[9] = 12; + SU2ToCGNS[10] = 21; + SU2ToCGNS[11] = 13; + SU2ToCGNS[12] = 24; + SU2ToCGNS[13] = 26; + SU2ToCGNS[14] = 22; + SU2ToCGNS[15] = 15; + SU2ToCGNS[16] = 23; + SU2ToCGNS[17] = 14; + SU2ToCGNS[18] = 4; + SU2ToCGNS[19] = 16; + SU2ToCGNS[20] = 5; + SU2ToCGNS[21] = 19; + SU2ToCGNS[22] = 25; + SU2ToCGNS[23] = 17; + SU2ToCGNS[24] = 7; + SU2ToCGNS[25] = 18; + SU2ToCGNS[26] = 6; } -void CCGNSElementType::CreateDataHEXA_64(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - vector &SU2ToCGNS) { - +void CCGNSElementType::CreateDataHEXA_64(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + vector& SU2ToCGNS) { /* The HEXA_64 element is a cubic hexahedron. In CGNS the nodes are numbered as follows: - First the vertex nodes. - Second the edge nodes. @@ -1062,33 +1361,78 @@ void CCGNSElementType::CreateDataHEXA_64(unsigned short &VTK_Type, from node 0 along the second edge and the k-direction from node 0 along the third edge. */ VTK_Type = HEXAHEDRON; - nPoly = 3; - nDOFs = 64; + nPoly = 3; + nDOFs = 64; SU2ToCGNS.resize(nDOFs); - SU2ToCGNS[0] = 0; SU2ToCGNS[1] = 8; SU2ToCGNS[2] = 9; SU2ToCGNS[3] = 1; - SU2ToCGNS[4] = 15; SU2ToCGNS[5] = 32; SU2ToCGNS[6] = 33; SU2ToCGNS[7] = 10; - SU2ToCGNS[8] = 14; SU2ToCGNS[9] = 35; SU2ToCGNS[10] = 34; SU2ToCGNS[11] = 11; - SU2ToCGNS[12] = 3; SU2ToCGNS[13] = 13; SU2ToCGNS[14] = 12; SU2ToCGNS[15] = 2; - SU2ToCGNS[16] = 16; SU2ToCGNS[17] = 36; SU2ToCGNS[18] = 37; SU2ToCGNS[19] = 18; - SU2ToCGNS[20] = 49; SU2ToCGNS[21] = 56; SU2ToCGNS[22] = 57; SU2ToCGNS[23] = 40; - SU2ToCGNS[24] = 48; SU2ToCGNS[25] = 59; SU2ToCGNS[26] = 58; SU2ToCGNS[27] = 41; - SU2ToCGNS[28] = 22; SU2ToCGNS[29] = 45; SU2ToCGNS[30] = 44; SU2ToCGNS[31] = 20; - SU2ToCGNS[32] = 17; SU2ToCGNS[33] = 39; SU2ToCGNS[34] = 38; SU2ToCGNS[35] = 19; - SU2ToCGNS[36] = 50; SU2ToCGNS[37] = 60; SU2ToCGNS[38] = 61; SU2ToCGNS[39] = 43; - SU2ToCGNS[40] = 51; SU2ToCGNS[41] = 63; SU2ToCGNS[42] = 62; SU2ToCGNS[43] = 42; - SU2ToCGNS[44] = 23; SU2ToCGNS[45] = 46; SU2ToCGNS[46] = 47; SU2ToCGNS[47] = 21; - SU2ToCGNS[48] = 4; SU2ToCGNS[49] = 24; SU2ToCGNS[50] = 25; SU2ToCGNS[51] = 5; - SU2ToCGNS[52] = 31; SU2ToCGNS[53] = 52; SU2ToCGNS[54] = 53; SU2ToCGNS[55] = 26; - SU2ToCGNS[56] = 30; SU2ToCGNS[57] = 55; SU2ToCGNS[58] = 54; SU2ToCGNS[59] = 27; - SU2ToCGNS[60] = 7; SU2ToCGNS[61] = 29; SU2ToCGNS[62] = 28; SU2ToCGNS[63] = 6; + SU2ToCGNS[0] = 0; + SU2ToCGNS[1] = 8; + SU2ToCGNS[2] = 9; + SU2ToCGNS[3] = 1; + SU2ToCGNS[4] = 15; + SU2ToCGNS[5] = 32; + SU2ToCGNS[6] = 33; + SU2ToCGNS[7] = 10; + SU2ToCGNS[8] = 14; + SU2ToCGNS[9] = 35; + SU2ToCGNS[10] = 34; + SU2ToCGNS[11] = 11; + SU2ToCGNS[12] = 3; + SU2ToCGNS[13] = 13; + SU2ToCGNS[14] = 12; + SU2ToCGNS[15] = 2; + SU2ToCGNS[16] = 16; + SU2ToCGNS[17] = 36; + SU2ToCGNS[18] = 37; + SU2ToCGNS[19] = 18; + SU2ToCGNS[20] = 49; + SU2ToCGNS[21] = 56; + SU2ToCGNS[22] = 57; + SU2ToCGNS[23] = 40; + SU2ToCGNS[24] = 48; + SU2ToCGNS[25] = 59; + SU2ToCGNS[26] = 58; + SU2ToCGNS[27] = 41; + SU2ToCGNS[28] = 22; + SU2ToCGNS[29] = 45; + SU2ToCGNS[30] = 44; + SU2ToCGNS[31] = 20; + SU2ToCGNS[32] = 17; + SU2ToCGNS[33] = 39; + SU2ToCGNS[34] = 38; + SU2ToCGNS[35] = 19; + SU2ToCGNS[36] = 50; + SU2ToCGNS[37] = 60; + SU2ToCGNS[38] = 61; + SU2ToCGNS[39] = 43; + SU2ToCGNS[40] = 51; + SU2ToCGNS[41] = 63; + SU2ToCGNS[42] = 62; + SU2ToCGNS[43] = 42; + SU2ToCGNS[44] = 23; + SU2ToCGNS[45] = 46; + SU2ToCGNS[46] = 47; + SU2ToCGNS[47] = 21; + SU2ToCGNS[48] = 4; + SU2ToCGNS[49] = 24; + SU2ToCGNS[50] = 25; + SU2ToCGNS[51] = 5; + SU2ToCGNS[52] = 31; + SU2ToCGNS[53] = 52; + SU2ToCGNS[54] = 53; + SU2ToCGNS[55] = 26; + SU2ToCGNS[56] = 30; + SU2ToCGNS[57] = 55; + SU2ToCGNS[58] = 54; + SU2ToCGNS[59] = 27; + SU2ToCGNS[60] = 7; + SU2ToCGNS[61] = 29; + SU2ToCGNS[62] = 28; + SU2ToCGNS[63] = 6; } -void CCGNSElementType::CreateDataHEXA_125(unsigned short &VTK_Type, - unsigned short &nPoly, - unsigned short &nDOFs, - vector &SU2ToCGNS) { - +void CCGNSElementType::CreateDataHEXA_125(unsigned short& VTK_Type, unsigned short& nPoly, unsigned short& nDOFs, + vector& SU2ToCGNS) { /* The HEXA_125 element is a quartic hexahedron. In CGNS the nodes are numbered as follows: - First the vertex nodes. - Second the edge nodes. @@ -1099,35 +1443,135 @@ void CCGNSElementType::CreateDataHEXA_125(unsigned short &VTK_Type, from node 0 along the second edge and the k-direction from node 0 along the third edge. */ VTK_Type = HEXAHEDRON; - nPoly = 4; - nDOFs = 125; + nPoly = 4; + nDOFs = 125; SU2ToCGNS.resize(nDOFs); - SU2ToCGNS[0] = 0; SU2ToCGNS[1] = 8; SU2ToCGNS[2] = 9; SU2ToCGNS[3] = 10; SU2ToCGNS[4] = 1; - SU2ToCGNS[5] = 19; SU2ToCGNS[6] = 44; SU2ToCGNS[7] = 45; SU2ToCGNS[8] = 46; SU2ToCGNS[9] = 11; - SU2ToCGNS[10] = 18; SU2ToCGNS[11] = 51; SU2ToCGNS[12] = 52; SU2ToCGNS[13] = 47; SU2ToCGNS[14] = 12; - SU2ToCGNS[15] = 17; SU2ToCGNS[16] = 50; SU2ToCGNS[17] = 49; SU2ToCGNS[18] = 48; SU2ToCGNS[19] = 13; - SU2ToCGNS[20] = 3; SU2ToCGNS[21] = 16; SU2ToCGNS[22] = 15; SU2ToCGNS[23] = 14; SU2ToCGNS[24] = 2; - SU2ToCGNS[25] = 20; SU2ToCGNS[26] = 53; SU2ToCGNS[27] = 54; SU2ToCGNS[28] = 55; SU2ToCGNS[29] = 23; - SU2ToCGNS[30] = 82; SU2ToCGNS[31] = 98; SU2ToCGNS[32] = 99; SU2ToCGNS[33] = 100; SU2ToCGNS[34] = 62; - SU2ToCGNS[35] = 81; SU2ToCGNS[36] = 105; SU2ToCGNS[37] = 106; SU2ToCGNS[38] = 101; SU2ToCGNS[39] = 63; - SU2ToCGNS[40] = 80; SU2ToCGNS[41] = 104; SU2ToCGNS[42] = 103; SU2ToCGNS[43] = 102; SU2ToCGNS[44] = 64; - SU2ToCGNS[45] = 29; SU2ToCGNS[46] = 73; SU2ToCGNS[47] = 72; SU2ToCGNS[48] = 71; SU2ToCGNS[49] = 26; - SU2ToCGNS[50] = 21; SU2ToCGNS[51] = 60; SU2ToCGNS[52] = 61; SU2ToCGNS[53] = 56; SU2ToCGNS[54] = 24; - SU2ToCGNS[55] = 83; SU2ToCGNS[56] = 107; SU2ToCGNS[57] = 108; SU2ToCGNS[58] = 109; SU2ToCGNS[59] = 69; - SU2ToCGNS[60] = 88; SU2ToCGNS[61] = 114; SU2ToCGNS[62] = 115; SU2ToCGNS[63] = 110; SU2ToCGNS[64] = 70; - SU2ToCGNS[65] = 87; SU2ToCGNS[66] = 113; SU2ToCGNS[67] = 112; SU2ToCGNS[68] = 111; SU2ToCGNS[69] = 65; - SU2ToCGNS[70] = 30; SU2ToCGNS[71] = 74; SU2ToCGNS[72] = 79; SU2ToCGNS[73] = 78; SU2ToCGNS[74] = 27; - SU2ToCGNS[75] = 22; SU2ToCGNS[76] = 59; SU2ToCGNS[77] = 58; SU2ToCGNS[78] = 57; SU2ToCGNS[79] = 25; - SU2ToCGNS[80] = 84; SU2ToCGNS[81] = 116; SU2ToCGNS[82] = 117; SU2ToCGNS[83] = 118; SU2ToCGNS[84] = 68; - SU2ToCGNS[85] = 85; SU2ToCGNS[86] = 123; SU2ToCGNS[87] = 124; SU2ToCGNS[88] = 119; SU2ToCGNS[89] = 67; - SU2ToCGNS[90] = 86; SU2ToCGNS[91] = 122; SU2ToCGNS[92] = 121; SU2ToCGNS[93] = 120; SU2ToCGNS[94] = 66; - SU2ToCGNS[95] = 31; SU2ToCGNS[96] = 75; SU2ToCGNS[97] = 76; SU2ToCGNS[98] = 77; SU2ToCGNS[99] = 28; - SU2ToCGNS[100] = 4; SU2ToCGNS[101] = 32; SU2ToCGNS[102] = 33; SU2ToCGNS[103] = 34; SU2ToCGNS[104] = 5; - SU2ToCGNS[105] = 43; SU2ToCGNS[106] = 89; SU2ToCGNS[107] = 90; SU2ToCGNS[108] = 91; SU2ToCGNS[109] = 35; - SU2ToCGNS[110] = 42; SU2ToCGNS[111] = 96; SU2ToCGNS[112] = 97; SU2ToCGNS[113] = 92; SU2ToCGNS[114] = 36; - SU2ToCGNS[115] = 41; SU2ToCGNS[116] = 95; SU2ToCGNS[117] = 94; SU2ToCGNS[118] = 93; SU2ToCGNS[119] = 37; - SU2ToCGNS[120] = 7; SU2ToCGNS[121] = 40; SU2ToCGNS[122] = 39; SU2ToCGNS[123] = 38; SU2ToCGNS[124] = 6; + SU2ToCGNS[0] = 0; + SU2ToCGNS[1] = 8; + SU2ToCGNS[2] = 9; + SU2ToCGNS[3] = 10; + SU2ToCGNS[4] = 1; + SU2ToCGNS[5] = 19; + SU2ToCGNS[6] = 44; + SU2ToCGNS[7] = 45; + SU2ToCGNS[8] = 46; + SU2ToCGNS[9] = 11; + SU2ToCGNS[10] = 18; + SU2ToCGNS[11] = 51; + SU2ToCGNS[12] = 52; + SU2ToCGNS[13] = 47; + SU2ToCGNS[14] = 12; + SU2ToCGNS[15] = 17; + SU2ToCGNS[16] = 50; + SU2ToCGNS[17] = 49; + SU2ToCGNS[18] = 48; + SU2ToCGNS[19] = 13; + SU2ToCGNS[20] = 3; + SU2ToCGNS[21] = 16; + SU2ToCGNS[22] = 15; + SU2ToCGNS[23] = 14; + SU2ToCGNS[24] = 2; + SU2ToCGNS[25] = 20; + SU2ToCGNS[26] = 53; + SU2ToCGNS[27] = 54; + SU2ToCGNS[28] = 55; + SU2ToCGNS[29] = 23; + SU2ToCGNS[30] = 82; + SU2ToCGNS[31] = 98; + SU2ToCGNS[32] = 99; + SU2ToCGNS[33] = 100; + SU2ToCGNS[34] = 62; + SU2ToCGNS[35] = 81; + SU2ToCGNS[36] = 105; + SU2ToCGNS[37] = 106; + SU2ToCGNS[38] = 101; + SU2ToCGNS[39] = 63; + SU2ToCGNS[40] = 80; + SU2ToCGNS[41] = 104; + SU2ToCGNS[42] = 103; + SU2ToCGNS[43] = 102; + SU2ToCGNS[44] = 64; + SU2ToCGNS[45] = 29; + SU2ToCGNS[46] = 73; + SU2ToCGNS[47] = 72; + SU2ToCGNS[48] = 71; + SU2ToCGNS[49] = 26; + SU2ToCGNS[50] = 21; + SU2ToCGNS[51] = 60; + SU2ToCGNS[52] = 61; + SU2ToCGNS[53] = 56; + SU2ToCGNS[54] = 24; + SU2ToCGNS[55] = 83; + SU2ToCGNS[56] = 107; + SU2ToCGNS[57] = 108; + SU2ToCGNS[58] = 109; + SU2ToCGNS[59] = 69; + SU2ToCGNS[60] = 88; + SU2ToCGNS[61] = 114; + SU2ToCGNS[62] = 115; + SU2ToCGNS[63] = 110; + SU2ToCGNS[64] = 70; + SU2ToCGNS[65] = 87; + SU2ToCGNS[66] = 113; + SU2ToCGNS[67] = 112; + SU2ToCGNS[68] = 111; + SU2ToCGNS[69] = 65; + SU2ToCGNS[70] = 30; + SU2ToCGNS[71] = 74; + SU2ToCGNS[72] = 79; + SU2ToCGNS[73] = 78; + SU2ToCGNS[74] = 27; + SU2ToCGNS[75] = 22; + SU2ToCGNS[76] = 59; + SU2ToCGNS[77] = 58; + SU2ToCGNS[78] = 57; + SU2ToCGNS[79] = 25; + SU2ToCGNS[80] = 84; + SU2ToCGNS[81] = 116; + SU2ToCGNS[82] = 117; + SU2ToCGNS[83] = 118; + SU2ToCGNS[84] = 68; + SU2ToCGNS[85] = 85; + SU2ToCGNS[86] = 123; + SU2ToCGNS[87] = 124; + SU2ToCGNS[88] = 119; + SU2ToCGNS[89] = 67; + SU2ToCGNS[90] = 86; + SU2ToCGNS[91] = 122; + SU2ToCGNS[92] = 121; + SU2ToCGNS[93] = 120; + SU2ToCGNS[94] = 66; + SU2ToCGNS[95] = 31; + SU2ToCGNS[96] = 75; + SU2ToCGNS[97] = 76; + SU2ToCGNS[98] = 77; + SU2ToCGNS[99] = 28; + SU2ToCGNS[100] = 4; + SU2ToCGNS[101] = 32; + SU2ToCGNS[102] = 33; + SU2ToCGNS[103] = 34; + SU2ToCGNS[104] = 5; + SU2ToCGNS[105] = 43; + SU2ToCGNS[106] = 89; + SU2ToCGNS[107] = 90; + SU2ToCGNS[108] = 91; + SU2ToCGNS[109] = 35; + SU2ToCGNS[110] = 42; + SU2ToCGNS[111] = 96; + SU2ToCGNS[112] = 97; + SU2ToCGNS[113] = 92; + SU2ToCGNS[114] = 36; + SU2ToCGNS[115] = 41; + SU2ToCGNS[116] = 95; + SU2ToCGNS[117] = 94; + SU2ToCGNS[118] = 93; + SU2ToCGNS[119] = 37; + SU2ToCGNS[120] = 7; + SU2ToCGNS[121] = 40; + SU2ToCGNS[122] = 39; + SU2ToCGNS[123] = 38; + SU2ToCGNS[124] = 6; } #endif diff --git a/Common/src/fem/fem_gauss_jacobi_quadrature.cpp b/Common/src/fem/fem_gauss_jacobi_quadrature.cpp index 47492b728e9..124a90d166b 100644 --- a/Common/src/fem/fem_gauss_jacobi_quadrature.cpp +++ b/Common/src/fem/fem_gauss_jacobi_quadrature.cpp @@ -79,13 +79,12 @@ Tom #include "../../include/fem/fem_gauss_jacobi_quadrature.hpp" -void CGaussJacobiQuadrature::GetQuadraturePoints(const passivedouble alpha, const passivedouble beta, - const passivedouble a, const passivedouble b, - vector &GJPoints, vector &GJWeights) { - +void CGaussJacobiQuadrature::GetQuadraturePoints(const passivedouble alpha, const passivedouble beta, + const passivedouble a, const passivedouble b, + vector& GJPoints, vector& GJWeights) { /*--- Determine the number of integration points. Check if the number makes sense. ---*/ unsigned int nIntPoints = (unsigned int)GJPoints.size(); - if(nIntPoints < 1 || nIntPoints > 100) + if (nIntPoints < 1 || nIntPoints > 100) SU2_MPI::Error("Invalid number of Gauss Jacobi integration points", CURRENT_FUNCTION); /*--- Call the function cgqf to do the actual work. ---*/ @@ -95,8 +94,8 @@ void CGaussJacobiQuadrature::GetQuadraturePoints(const passivedouble alpha, //****************************************************************************80 -void CGaussJacobiQuadrature::cdgqf(int nt, int kind, passivedouble alpha, passivedouble beta, - passivedouble t[], passivedouble wts[]) +void CGaussJacobiQuadrature::cdgqf(int nt, int kind, passivedouble alpha, passivedouble beta, passivedouble t[], + passivedouble wts[]) //****************************************************************************80 // @@ -158,32 +157,32 @@ void CGaussJacobiQuadrature::cdgqf(int nt, int kind, passivedouble alpha, passiv // Output, passivedouble WTS[NT], the weights. // { - passivedouble *aj; - passivedouble *bj; + passivedouble* aj; + passivedouble* bj; passivedouble zemu; - parchk ( kind, 2 * nt, alpha, beta ); -// -// Get the Jacobi matrix and zero-th moment. -// + parchk(kind, 2 * nt, alpha, beta); + // + // Get the Jacobi matrix and zero-th moment. + // aj = new passivedouble[nt]; bj = new passivedouble[nt]; - zemu = class_matrix ( kind, nt, alpha, beta, aj, bj ); -// -// Compute the knots and weights. -// - sgqf ( nt, aj, bj, zemu, t, wts ); + zemu = class_matrix(kind, nt, alpha, beta, aj, bj); + // + // Compute the knots and weights. + // + sgqf(nt, aj, bj, zemu, t, wts); - delete [] aj; - delete [] bj; + delete[] aj; + delete[] bj; return; } //****************************************************************************80 -void CGaussJacobiQuadrature::cgqf(int nt, int kind, passivedouble alpha, passivedouble beta, - passivedouble a, passivedouble b, passivedouble t[], passivedouble wts[]) +void CGaussJacobiQuadrature::cgqf(int nt, int kind, passivedouble alpha, passivedouble beta, passivedouble a, + passivedouble b, passivedouble t[], passivedouble wts[]) //****************************************************************************80 // @@ -248,38 +247,35 @@ void CGaussJacobiQuadrature::cgqf(int nt, int kind, passivedouble alpha, passive // { int i; - int *mlt; - int *ndx; -// -// Compute the Gauss quadrature formula for default values of A and B. -// - cdgqf ( nt, kind, alpha, beta, t, wts ); -// -// Prepare to scale the quadrature formula to other weight function with -// valid A and B. -// + int* mlt; + int* ndx; + // + // Compute the Gauss quadrature formula for default values of A and B. + // + cdgqf(nt, kind, alpha, beta, t, wts); + // + // Prepare to scale the quadrature formula to other weight function with + // valid A and B. + // mlt = new int[nt]; - for ( i = 0; i < nt; i++ ) - { + for (i = 0; i < nt; i++) { mlt[i] = 1; } ndx = new int[nt]; - for ( i = 0; i < nt; i++ ) - { + for (i = 0; i < nt; i++) { ndx[i] = i + 1; } - scqf ( nt, t, mlt, wts, nt, ndx, wts, t, kind, alpha, beta, a, b ); + scqf(nt, t, mlt, wts, nt, ndx, wts, t, kind, alpha, beta, a, b); - delete [] mlt; - delete [] ndx; + delete[] mlt; + delete[] ndx; return; } //****************************************************************************80 -passivedouble CGaussJacobiQuadrature::class_matrix(int kind, int m, passivedouble alpha, - passivedouble beta, passivedouble aj[], - passivedouble bj[]) +passivedouble CGaussJacobiQuadrature::class_matrix(int kind, int m, passivedouble alpha, passivedouble beta, + passivedouble aj[], passivedouble bj[]) //****************************************************************************80 // @@ -358,157 +354,121 @@ passivedouble CGaussJacobiQuadrature::class_matrix(int kind, int m, passivedoubl passivedouble temp2; passivedouble zemu; - temp = r8_epsilon ( ); + temp = r8_epsilon(); - parchk ( kind, 2 * m - 1, alpha, beta ); + parchk(kind, 2 * m - 1, alpha, beta); temp2 = 0.5; - if ( 500.0 * temp < fabs ( pow ( tgamma ( temp2 ), 2 ) - pi ) ) - { + if (500.0 * temp < fabs(pow(tgamma(temp2), 2) - pi)) { cout << "\n"; cout << "CLASS_MATRIX - Fatal error!\n"; cout << " Gamma function does not match machine parameters.\n"; - exit ( 1 ); + exit(1); } - if ( kind == 1 ) - { + if (kind == 1) { ab = 0.0; - zemu = 2.0 / ( ab + 1.0 ); + zemu = 2.0 / (ab + 1.0); - for ( i = 0; i < m; i++ ) - { + for (i = 0; i < m; i++) { aj[i] = 0.0; } - for ( i = 1; i <= m; i++ ) - { - abi = i + ab * ( i % 2 ); + for (i = 1; i <= m; i++) { + abi = i + ab * (i % 2); abj = 2 * i + ab; - bj[i-1] = sqrt ( abi * abi / ( abj * abj - 1.0 ) ); + bj[i - 1] = sqrt(abi * abi / (abj * abj - 1.0)); } - } - else if ( kind == 2 ) - { + } else if (kind == 2) { zemu = pi; - for ( i = 0; i < m; i++ ) - { + for (i = 0; i < m; i++) { aj[i] = 0.0; } - bj[0] = sqrt ( 0.5 ); - for ( i = 1; i < m; i++ ) - { + bj[0] = sqrt(0.5); + for (i = 1; i < m; i++) { bj[i] = 0.5; } - } - else if ( kind == 3 ) - { + } else if (kind == 3) { ab = alpha * 2.0; - zemu = pow ( 2.0, ab + 1.0 ) * pow ( tgamma ( alpha + 1.0 ), 2 ) - / tgamma ( ab + 2.0 ); + zemu = pow(2.0, ab + 1.0) * pow(tgamma(alpha + 1.0), 2) / tgamma(ab + 2.0); - for ( i = 0; i < m; i++ ) - { + for (i = 0; i < m; i++) { aj[i] = 0.0; } - bj[0] = sqrt ( 1.0 / ( 2.0 * alpha + 3.0 ) ); - for ( i = 2; i <= m; i++ ) - { - bj[i-1] = sqrt ( i * ( i + ab ) / ( 4.0 * pow ( i + alpha, 2 ) - 1.0 ) ); + bj[0] = sqrt(1.0 / (2.0 * alpha + 3.0)); + for (i = 2; i <= m; i++) { + bj[i - 1] = sqrt(i * (i + ab) / (4.0 * pow(i + alpha, 2) - 1.0)); } - } - else if ( kind == 4 ) - { + } else if (kind == 4) { ab = alpha + beta; abi = 2.0 + ab; - zemu = pow ( 2.0, ab + 1.0 ) * tgamma ( alpha + 1.0 ) - * tgamma ( beta + 1.0 ) / tgamma ( abi ); - aj[0] = ( beta - alpha ) / abi; - bj[0] = sqrt ( 4.0 * ( 1.0 + alpha ) * ( 1.0 + beta ) - / ( ( abi + 1.0 ) * abi * abi ) ); + zemu = pow(2.0, ab + 1.0) * tgamma(alpha + 1.0) * tgamma(beta + 1.0) / tgamma(abi); + aj[0] = (beta - alpha) / abi; + bj[0] = sqrt(4.0 * (1.0 + alpha) * (1.0 + beta) / ((abi + 1.0) * abi * abi)); a2b2 = beta * beta - alpha * alpha; - for ( i = 2; i <= m; i++ ) - { + for (i = 2; i <= m; i++) { abi = 2.0 * i + ab; - aj[i-1] = a2b2 / ( ( abi - 2.0 ) * abi ); + aj[i - 1] = a2b2 / ((abi - 2.0) * abi); abi = abi * abi; - bj[i-1] = sqrt ( 4.0 * i * ( i + alpha ) * ( i + beta ) * ( i + ab ) - / ( ( abi - 1.0 ) * abi ) ); + bj[i - 1] = sqrt(4.0 * i * (i + alpha) * (i + beta) * (i + ab) / ((abi - 1.0) * abi)); } - } - else if ( kind == 5 ) - { - zemu = tgamma ( alpha + 1.0 ); + } else if (kind == 5) { + zemu = tgamma(alpha + 1.0); - for ( i = 1; i <= m; i++ ) - { - aj[i-1] = 2.0 * i - 1.0 + alpha; - bj[i-1] = sqrt ( i * ( i + alpha ) ); + for (i = 1; i <= m; i++) { + aj[i - 1] = 2.0 * i - 1.0 + alpha; + bj[i - 1] = sqrt(i * (i + alpha)); } - } - else if ( kind == 6 ) - { - zemu = tgamma ( ( alpha + 1.0 ) / 2.0 ); + } else if (kind == 6) { + zemu = tgamma((alpha + 1.0) / 2.0); - for ( i = 0; i < m; i++ ) - { + for (i = 0; i < m; i++) { aj[i] = 0.0; } - for ( i = 1; i <= m; i++ ) - { - bj[i-1] = sqrt ( ( i + alpha * ( i % 2 ) ) / 2.0 ); + for (i = 1; i <= m; i++) { + bj[i - 1] = sqrt((i + alpha * (i % 2)) / 2.0); } - } - else if ( kind == 7 ) - { + } else if (kind == 7) { ab = alpha; - zemu = 2.0 / ( ab + 1.0 ); + zemu = 2.0 / (ab + 1.0); - for ( i = 0; i < m; i++ ) - { + for (i = 0; i < m; i++) { aj[i] = 0.0; } - for ( i = 1; i <= m; i++ ) - { - abi = i + ab * ( i % 2 ); + for (i = 1; i <= m; i++) { + abi = i + ab * (i % 2); abj = 2 * i + ab; - bj[i-1] = sqrt ( abi * abi / ( abj * abj - 1.0 ) ); + bj[i - 1] = sqrt(abi * abi / (abj * abj - 1.0)); } - } - else // if ( kind == 8 ) + } else // if ( kind == 8 ) { ab = alpha + beta; - zemu = tgamma ( alpha + 1.0 ) * tgamma ( - ( ab + 1.0 ) ) - / tgamma ( - beta ); + zemu = tgamma(alpha + 1.0) * tgamma(-(ab + 1.0)) / tgamma(-beta); apone = alpha + 1.0; aba = ab * apone; - aj[0] = - apone / ( ab + 2.0 ); - bj[0] = - aj[0] * ( beta + 1.0 ) / ( ab + 2.0 ) / ( ab + 3.0 ); - for ( i = 2; i <= m; i++ ) - { + aj[0] = -apone / (ab + 2.0); + bj[0] = -aj[0] * (beta + 1.0) / (ab + 2.0) / (ab + 3.0); + for (i = 2; i <= m; i++) { abti = ab + 2.0 * i; - aj[i-1] = aba + 2.0 * ( ab + i ) * ( i - 1 ); - aj[i-1] = - aj[i-1] / abti / ( abti - 2.0 ); + aj[i - 1] = aba + 2.0 * (ab + i) * (i - 1); + aj[i - 1] = -aj[i - 1] / abti / (abti - 2.0); } - for ( i = 2; i <= m - 1; i++ ) - { + for (i = 2; i <= m - 1; i++) { abti = ab + 2.0 * i; - bj[i-1] = i * ( alpha + i ) / ( abti - 1.0 ) * ( beta + i ) - / ( abti * abti ) * ( ab + i ) / ( abti + 1.0 ); + bj[i - 1] = i * (alpha + i) / (abti - 1.0) * (beta + i) / (abti * abti) * (ab + i) / (abti + 1.0); } - bj[m-1] = 0.0; - for ( i = 0; i < m; i++ ) - { - bj[i] = sqrt ( bj[i] ); + bj[m - 1] = 0.0; + for (i = 0; i < m; i++) { + bj[i] = sqrt(bj[i]); } } @@ -596,114 +556,98 @@ void CGaussJacobiQuadrature::imtqlx(int n, passivedouble d[], passivedouble e[], passivedouble r; passivedouble s; - prec = r8_epsilon ( ); + prec = r8_epsilon(); - if ( n == 1 ) - { + if (n == 1) { return; } - e[n-1] = 0.0; + e[n - 1] = 0.0; - for ( l = 1; l <= n; l++ ) - { + for (l = 1; l <= n; l++) { j = 0; - for ( ; ; ) - { - for ( m = l; m <= n; m++ ) - { - if ( m == n ) - { + for (;;) { + for (m = l; m <= n; m++) { + if (m == n) { break; } - if ( fabs ( e[m-1] ) <= prec * ( fabs ( d[m-1] ) + fabs ( d[m] ) ) ) - { + if (fabs(e[m - 1]) <= prec * (fabs(d[m - 1]) + fabs(d[m]))) { break; } } - p = d[l-1]; - if ( m == l ) - { + p = d[l - 1]; + if (m == l) { break; } - if ( itn <= j ) - { + if (itn <= j) { cout << "\n"; cout << "IMTQLX - Fatal error!\n"; cout << " Iteration limit exceeded\n"; - exit ( 1 ); + exit(1); } j = j + 1; - g = ( d[l] - p ) / ( 2.0 * e[l-1] ); - r = sqrt ( g * g + 1.0 ); - g = d[m-1] - p + e[l-1] / ( g + fabs ( r ) * r8_sign ( g ) ); + g = (d[l] - p) / (2.0 * e[l - 1]); + r = sqrt(g * g + 1.0); + g = d[m - 1] - p + e[l - 1] / (g + fabs(r) * r8_sign(g)); s = 1.0; c = 1.0; p = 0.0; mml = m - l; - for ( ii = 1; ii <= mml; ii++ ) - { + for (ii = 1; ii <= mml; ii++) { i = m - ii; - f = s * e[i-1]; - b = c * e[i-1]; + f = s * e[i - 1]; + b = c * e[i - 1]; - if ( fabs ( g ) <= fabs ( f ) ) - { + if (fabs(g) <= fabs(f)) { c = g / f; - r = sqrt ( c * c + 1.0 ); + r = sqrt(c * c + 1.0); e[i] = f * r; s = 1.0 / r; c = c * s; - } - else - { + } else { s = f / g; - r = sqrt ( s * s + 1.0 ); + r = sqrt(s * s + 1.0); e[i] = g * r; c = 1.0 / r; s = s * c; } g = d[i] - p; - r = ( d[i-1] - g ) * s + 2.0 * c * b; + r = (d[i - 1] - g) * s + 2.0 * c * b; p = s * r; d[i] = g + p; g = c * r - b; f = z[i]; - z[i] = s * z[i-1] + c * f; - z[i-1] = c * z[i-1] - s * f; + z[i] = s * z[i - 1] + c * f; + z[i - 1] = c * z[i - 1] - s * f; } - d[l-1] = d[l-1] - p; - e[l-1] = g; - e[m-1] = 0.0; + d[l - 1] = d[l - 1] - p; + e[l - 1] = g; + e[m - 1] = 0.0; } } -// -// Sorting. -// - for ( ii = 2; ii <= m; ii++ ) - { + // + // Sorting. + // + for (ii = 2; ii <= m; ii++) { i = ii - 1; k = i; - p = d[i-1]; - - for ( j = ii; j <= n; j++ ) - { - if ( d[j-1] < p ) - { - k = j; - p = d[j-1]; + p = d[i - 1]; + + for (j = ii; j <= n; j++) { + if (d[j - 1] < p) { + k = j; + p = d[j - 1]; } } - if ( k != i ) - { - d[k-1] = d[i-1]; - d[i-1] = p; - p = z[i-1]; - z[i-1] = z[k-1]; - z[k-1] = p; + if (k != i) { + d[k - 1] = d[i - 1]; + d[i - 1] = p; + p = z[i - 1]; + z[i - 1] = z[k - 1]; + z[k - 1] = p; } } return; @@ -760,52 +704,47 @@ void CGaussJacobiQuadrature::parchk(int kind, int m, passivedouble alpha, passiv { passivedouble tmp; - if ( kind <= 0 ) - { + if (kind <= 0) { cout << "\n"; cout << "PARCHK - Fatal error!\n"; cout << " KIND <= 0.\n"; - exit ( 1 ); + exit(1); } -// -// Check ALPHA for Gegenbauer, Jacobi, Laguerre, Hermite, Exponential. -// - if ( 3 <= kind && alpha <= -1.0 ) - { + // + // Check ALPHA for Gegenbauer, Jacobi, Laguerre, Hermite, Exponential. + // + if (3 <= kind && alpha <= -1.0) { cout << "\n"; cout << "PARCHK - Fatal error!\n"; cout << " 3 <= KIND and ALPHA <= -1.\n"; - exit ( 1 ); + exit(1); } -// -// Check BETA for Jacobi. -// - if ( kind == 4 && beta <= -1.0 ) - { + // + // Check BETA for Jacobi. + // + if (kind == 4 && beta <= -1.0) { cout << "\n"; cout << "PARCHK - Fatal error!\n"; cout << " KIND == 4 and BETA <= -1.0.\n"; - exit ( 1 ); + exit(1); } -// -// Check ALPHA and BETA for rational. -// - if ( kind == 8 ) - { + // + // Check ALPHA and BETA for rational. + // + if (kind == 8) { tmp = alpha + beta + m + 1.0; - if ( 0.0 <= tmp || tmp <= beta ) - { + if (0.0 <= tmp || tmp <= beta) { cout << "\n"; cout << "PARCHK - Fatal error!\n"; cout << " KIND == 8 but condition on ALPHA and BETA fails.\n"; - exit ( 1 ); + exit(1); } } return; } //****************************************************************************80 -passivedouble CGaussJacobiQuadrature::r8_epsilon( ) +passivedouble CGaussJacobiQuadrature::r8_epsilon() //****************************************************************************80 // @@ -873,22 +812,18 @@ passivedouble CGaussJacobiQuadrature::r8_sign(passivedouble x) { passivedouble value; - if ( x < 0.0 ) - { + if (x < 0.0) { value = -1.0; - } - else - { + } else { value = 1.0; } return value; } //****************************************************************************80 -void CGaussJacobiQuadrature::scqf(int nt, const passivedouble t[], const int mlt[], const passivedouble wts[], - int nwts, int ndx[], passivedouble swts[], passivedouble st[], - int kind, passivedouble alpha, passivedouble beta, passivedouble a, - passivedouble b) +void CGaussJacobiQuadrature::scqf(int nt, const passivedouble t[], const int mlt[], const passivedouble wts[], int nwts, + int ndx[], passivedouble swts[], passivedouble st[], int kind, passivedouble alpha, + passivedouble beta, passivedouble a, passivedouble b) //****************************************************************************80 // @@ -971,150 +906,122 @@ void CGaussJacobiQuadrature::scqf(int nt, const passivedouble t[], const int mlt passivedouble temp; passivedouble tmp; - temp = r8_epsilon ( ); + temp = r8_epsilon(); - parchk ( kind, 1, alpha, beta ); + parchk(kind, 1, alpha, beta); - if ( kind == 1 ) - { + if (kind == 1) { al = 0.0; be = 0.0; - if ( fabs ( b - a ) <= temp ) - { + if (fabs(b - a) <= temp) { cout << "\n"; cout << "SCQF - Fatal error!\n"; cout << " |B - A| too small.\n"; - exit ( 1 ); + exit(1); } - shft = ( a + b ) / 2.0; - slp = ( b - a ) / 2.0; - } - else if ( kind == 2 ) - { + shft = (a + b) / 2.0; + slp = (b - a) / 2.0; + } else if (kind == 2) { al = -0.5; be = -0.5; - if ( fabs ( b - a ) <= temp ) - { + if (fabs(b - a) <= temp) { cout << "\n"; cout << "SCQF - Fatal error!\n"; cout << " |B - A| too small.\n"; - exit ( 1 ); + exit(1); } - shft = ( a + b ) / 2.0; - slp = ( b - a ) / 2.0; - } - else if ( kind == 3 ) - { + shft = (a + b) / 2.0; + slp = (b - a) / 2.0; + } else if (kind == 3) { al = alpha; be = alpha; - if ( fabs ( b - a ) <= temp ) - { + if (fabs(b - a) <= temp) { cout << "\n"; cout << "SCQF - Fatal error!\n"; cout << " |B - A| too small.\n"; - exit ( 1 ); + exit(1); } - shft = ( a + b ) / 2.0; - slp = ( b - a ) / 2.0; - } - else if ( kind == 4 ) - { + shft = (a + b) / 2.0; + slp = (b - a) / 2.0; + } else if (kind == 4) { al = alpha; be = beta; - if ( fabs ( b - a ) <= temp ) - { + if (fabs(b - a) <= temp) { cout << "\n"; cout << "SCQF - Fatal error!\n"; cout << " |B - A| too small.\n"; - exit ( 1 ); + exit(1); } - shft = ( a + b ) / 2.0; - slp = ( b - a ) / 2.0; - } - else if ( kind == 5 ) - { - if ( b <= 0.0 ) - { + shft = (a + b) / 2.0; + slp = (b - a) / 2.0; + } else if (kind == 5) { + if (b <= 0.0) { cout << "\n"; cout << "SCQF - Fatal error!\n"; cout << " B <= 0\n"; - exit ( 1 ); + exit(1); } shft = a; slp = 1.0 / b; al = alpha; be = 0.0; - } - else if ( kind == 6 ) - { - if ( b <= 0.0 ) - { + } else if (kind == 6) { + if (b <= 0.0) { cout << "\n"; cout << "SCQF - Fatal error!\n"; cout << " B <= 0.\n"; - exit ( 1 ); + exit(1); } shft = a; - slp = 1.0 / sqrt ( b ); + slp = 1.0 / sqrt(b); al = alpha; be = 0.0; - } - else if ( kind == 7 ) - { + } else if (kind == 7) { al = alpha; be = 0.0; - if ( fabs ( b - a ) <= temp ) - { + if (fabs(b - a) <= temp) { cout << "\n"; cout << "SCQF - Fatal error!\n"; cout << " |B - A| too small.\n"; - exit ( 1 ); + exit(1); } - shft = ( a + b ) / 2.0; - slp = ( b - a ) / 2.0; - } - else if ( kind == 8 ) - { - if ( a + b <= 0.0 ) - { + shft = (a + b) / 2.0; + slp = (b - a) / 2.0; + } else if (kind == 8) { + if (a + b <= 0.0) { cout << "\n"; cout << "SCQF - Fatal error!\n"; cout << " A + B <= 0.\n"; - exit ( 1 ); + exit(1); } shft = a; slp = a + b; al = alpha; be = beta; - } - else // if ( kind == 9 ) + } else // if ( kind == 9 ) { al = 0.5; be = 0.5; - if ( fabs ( b - a ) <= temp ) - { + if (fabs(b - a) <= temp) { cout << "\n"; cout << "SCQF - Fatal error!\n"; cout << " |B - A| too small.\n"; - exit ( 1 ); + exit(1); } - shft = ( a + b ) / 2.0; - slp = ( b - a ) / 2.0; + shft = (a + b) / 2.0; + slp = (b - a) / 2.0; } - p = pow ( slp, al + be + 1.0 ); + p = pow(slp, al + be + 1.0); - for ( k = 0; k < nt; k++ ) - { + for (k = 0; k < nt; k++) { st[k] = shft + slp * t[k]; - l = abs ( ndx[k] ); + l = abs(ndx[k]); - if ( l != 0 ) - { + if (l != 0) { tmp = p; - for ( i = l - 1; i <= l - 1 + mlt[k] - 1; i++ ) - { + for (i = l - 1; i <= l - 1 + mlt[k] - 1; i++) { swts[i] = wts[i] * tmp; tmp = tmp * slp; } @@ -1124,8 +1031,8 @@ void CGaussJacobiQuadrature::scqf(int nt, const passivedouble t[], const int mlt } //****************************************************************************80 -void CGaussJacobiQuadrature::sgqf(int nt, const passivedouble aj[], passivedouble bj[], - passivedouble zemu, passivedouble t[], passivedouble wts[]) +void CGaussJacobiQuadrature::sgqf(int nt, const passivedouble aj[], passivedouble bj[], passivedouble zemu, + passivedouble t[], passivedouble wts[]) //****************************************************************************80 // @@ -1177,35 +1084,31 @@ void CGaussJacobiQuadrature::sgqf(int nt, const passivedouble aj[], passivedoubl // { int i; -// -// Exit if the zero-th moment is not positive. -// - if ( zemu <= 0.0 ) - { + // + // Exit if the zero-th moment is not positive. + // + if (zemu <= 0.0) { cout << "\n"; cout << "SGQF - Fatal error!\n"; cout << " ZEMU <= 0.\n"; - exit ( 1 ); + exit(1); } -// -// Set up vectors for IMTQLX. -// - for ( i = 0; i < nt; i++ ) - { + // + // Set up vectors for IMTQLX. + // + for (i = 0; i < nt; i++) { t[i] = aj[i]; } - wts[0] = sqrt ( zemu ); - for ( i = 1; i < nt; i++ ) - { + wts[0] = sqrt(zemu); + for (i = 1; i < nt; i++) { wts[i] = 0.0; } -// -// Diagonalize the Jacobi matrix. -// - imtqlx ( nt, t, bj, wts ); + // + // Diagonalize the Jacobi matrix. + // + imtqlx(nt, t, bj, wts); - for ( i = 0; i < nt; i++ ) - { + for (i = 0; i < nt; i++) { wts[i] = wts[i] * wts[i]; } diff --git a/Common/src/fem/fem_geometry_structure.cpp b/Common/src/fem/fem_geometry_structure.cpp index b274989268c..375f7fefd39 100644 --- a/Common/src/fem/fem_geometry_structure.cpp +++ b/Common/src/fem/fem_geometry_structure.cpp @@ -32,30 +32,26 @@ #include "../../include/adt/CADTPointsOnlyClass.hpp" /* Prototypes for Lapack functions, if MKL or LAPACK is used. */ -#if defined (HAVE_MKL) || defined(HAVE_LAPACK) -extern "C" void dpotrf_(char *, int*, passivedouble*, int*, int*); -extern "C" void dpotri_(char *, int*, passivedouble*, int*, int*); +#if defined(HAVE_MKL) || defined(HAVE_LAPACK) +extern "C" void dpotrf_(char*, int*, passivedouble*, int*, int*); +extern "C" void dpotri_(char*, int*, passivedouble*, int*, int*); #endif -bool CLong3T::operator<(const CLong3T &other) const { - if(long0 != other.long0) return (long0 < other.long0); - if(long1 != other.long1) return (long1 < other.long1); - if(long2 != other.long2) return (long2 < other.long2); +bool CLong3T::operator<(const CLong3T& other) const { + if (long0 != other.long0) return (long0 < other.long0); + if (long1 != other.long1) return (long1 < other.long1); + if (long2 != other.long2) return (long2 < other.long2); return false; } -CReorderElements::CReorderElements(const unsigned long val_GlobalElemID, - const unsigned short val_TimeLevel, - const bool val_CommSolution, - const unsigned short val_VTK_Type, - const unsigned short val_nPolySol, - const bool val_JacConstant) { - +CReorderElements::CReorderElements(const unsigned long val_GlobalElemID, const unsigned short val_TimeLevel, + const bool val_CommSolution, const unsigned short val_VTK_Type, + const unsigned short val_nPolySol, const bool val_JacConstant) { /* Copy the global elment ID, time level and whether or not this element must be communicated. */ globalElemID = val_GlobalElemID; - timeLevel = val_TimeLevel; + timeLevel = val_TimeLevel; commSolution = val_CommSolution; /* Create the element type used in this class, which stores information of @@ -63,38 +59,34 @@ CReorderElements::CReorderElements(const unsigned long val_GlobalElemID, Jacobian of the transformation is constant. As it is possible that the polynomial degree of the solution is zero, this convention is different from the convention used in the SU2 grid file. */ - elemType = val_VTK_Type + 100*val_nPolySol; - if( !val_JacConstant ) elemType += 50; + elemType = val_VTK_Type + 100 * val_nPolySol; + if (!val_JacConstant) elemType += 50; } -bool CReorderElements::operator< (const CReorderElements &other) const { - +bool CReorderElements::operator<(const CReorderElements& other) const { /* Elements with the lowest time level are stored first. */ - if(timeLevel != other.timeLevel) return timeLevel < other.timeLevel; + if (timeLevel != other.timeLevel) return timeLevel < other.timeLevel; /* Next comparison is whether or not the element must communicate its solution data to other ranks. Elements which do not need to do this are stored first. */ - if(commSolution != other.commSolution) return other.commSolution; + if (commSolution != other.commSolution) return other.commSolution; /* Elements of the same element type must be stored as contiguously as possible to allow for the simultaneous treatment of elements in the matrix multiplications. */ - if(elemType != other.elemType) return elemType < other.elemType; + if (elemType != other.elemType) return elemType < other.elemType; /* The final comparison is based on the global element ID. */ return globalElemID < other.globalElemID; } -bool CSortFaces::operator()(const CFaceOfElement &f0, - const CFaceOfElement &f1) { - +bool CSortFaces::operator()(const CFaceOfElement& f0, const CFaceOfElement& f1) { /*--- Comparison in case both faces are boundary faces. ---*/ - if(f0.faceIndicator >= 0 && f1.faceIndicator >= 0) { - + if (f0.faceIndicator >= 0 && f1.faceIndicator >= 0) { /* Both faces are boundary faces. The first comparison is the boundary marker, which is stored in faceIndicator. */ - if(f0.faceIndicator != f1.faceIndicator) return f0.faceIndicator < f1.faceIndicator; + if (f0.faceIndicator != f1.faceIndicator) return f0.faceIndicator < f1.faceIndicator; /* Both faces belong to the same boundary marker. The second comparison is based on the on the local volume ID's of the adjacent elements. As the @@ -107,8 +99,7 @@ bool CSortFaces::operator()(const CFaceOfElement &f0, } /*--- Comparison in case both faces are internal faces. ---*/ - if(f0.faceIndicator == -1 && f1.faceIndicator == -1) { - + if (f0.faceIndicator == -1 && f1.faceIndicator == -1) { /* Both faces are internal faces. First determine the minimum and maximum ID of its adjacent elements. */ unsigned long elemIDMin0 = min(f0.elemID0, f0.elemID1); @@ -118,8 +109,7 @@ bool CSortFaces::operator()(const CFaceOfElement &f0, unsigned long elemIDMax1 = max(f1.elemID0, f1.elemID1); /* Determine the situation. */ - if(elemIDMax0 < nVolElemTot && elemIDMax1 < nVolElemTot) { - + if (elemIDMax0 < nVolElemTot && elemIDMax1 < nVolElemTot) { /* Both faces are matching internal faces. Determine whether or not these faces are local faces, i.e. faces between locally owned elements. */ const bool face0IsLocal = elemIDMax0 < nVolElemOwned; @@ -127,45 +117,38 @@ bool CSortFaces::operator()(const CFaceOfElement &f0, /* Check if both faces have the same status, i.e. either local or not local. */ - if(face0IsLocal == face1IsLocal) { - + if (face0IsLocal == face1IsLocal) { /* Both faces are either local or not local. Determine the time level of the faces, which is the minimum value of the adjacent volume elements. */ - const unsigned short timeLevel0 = min(volElem[elemIDMin0].timeLevel, - volElem[elemIDMax0].timeLevel); - const unsigned short timeLevel1 = min(volElem[elemIDMin1].timeLevel, - volElem[elemIDMax1].timeLevel); + const unsigned short timeLevel0 = min(volElem[elemIDMin0].timeLevel, volElem[elemIDMax0].timeLevel); + const unsigned short timeLevel1 = min(volElem[elemIDMin1].timeLevel, volElem[elemIDMax1].timeLevel); /* Internal faces with the same status are first sorted according to their time level. Faces with the smallest time level are numbered first. Note this is only relevant for time accurate local time stepping. */ - if(timeLevel0 != timeLevel1) return timeLevel0 < timeLevel1; + if (timeLevel0 != timeLevel1) return timeLevel0 < timeLevel1; /* The faces belong to the same time level. They are sorted according to their element ID's in order to increase cache performance. */ - if(elemIDMin0 != elemIDMin1) return elemIDMin0 < elemIDMin1; + if (elemIDMin0 != elemIDMin1) return elemIDMin0 < elemIDMin1; return elemIDMax0 < elemIDMax1; - } - else { - + } else { /* One face is a local face and the other is not. Make sure that the local faces are numbered first. */ - if( face0IsLocal ) return true; - else return false; + if (face0IsLocal) + return true; + else + return false; } - } - else if(elemIDMax0 >= nVolElemTot && elemIDMax1 >= nVolElemTot) { - + } else if (elemIDMax0 >= nVolElemTot && elemIDMax1 >= nVolElemTot) { /* Both faces are non-matching internal faces. Sort them according to their relevant element ID. The time level is not taken into account yet, because non-matching faces are not possible at the moment with time accurate local time stepping. */ return elemIDMin0 < elemIDMin1; - } - else { - + } else { /* One face is a matching internal face and the other face is a non-matching internal face. Make sure that the non-matching face is numbered after the matching face. This is accomplished by comparing @@ -180,84 +163,70 @@ bool CSortFaces::operator()(const CFaceOfElement &f0, return f0.faceIndicator > f1.faceIndicator; } -bool CSortBoundaryFaces::operator()(const CSurfaceElementFEM &f0, - const CSurfaceElementFEM &f1) { - +bool CSortBoundaryFaces::operator()(const CSurfaceElementFEM& f0, const CSurfaceElementFEM& f1) { /* First sorting criterion is the index of the standard element. The boundary faces should be sorted per standard element. Note that the time level is not taken into account here, because it is assumed that the surface elements to be sorted belong to one time level. */ - if(f0.indStandardElement != f1.indStandardElement) - return f0.indStandardElement < f1.indStandardElement; + if (f0.indStandardElement != f1.indStandardElement) return f0.indStandardElement < f1.indStandardElement; /* The standard elements are the same. The second criterion is the corresponding volume IDs of the surface elements. */ return f0.volElemID < f1.volElemID; } -bool CPointFEM::operator< (const CPointFEM &other) const { - if(periodIndexToDonor != other.periodIndexToDonor) - return periodIndexToDonor < other.periodIndexToDonor; +bool CPointFEM::operator<(const CPointFEM& other) const { + if (periodIndexToDonor != other.periodIndexToDonor) return periodIndexToDonor < other.periodIndexToDonor; return globalID < other.globalID; - } - -bool CPointFEM::operator==(const CPointFEM &other) const { - return (globalID == other.globalID && - periodIndexToDonor == other.periodIndexToDonor); } -void CVolumeElementFEM::GetCornerPointsAllFaces(unsigned short &numFaces, - unsigned short nPointsPerFace[], - unsigned long faceConn[6][4]) { +bool CPointFEM::operator==(const CPointFEM& other) const { + return (globalID == other.globalID && periodIndexToDonor == other.periodIndexToDonor); +} +void CVolumeElementFEM::GetCornerPointsAllFaces(unsigned short& numFaces, unsigned short nPointsPerFace[], + unsigned long faceConn[6][4]) { /*--- Get the corner connectivities of the faces, local to the element. ---*/ - CPrimalGridFEM::GetLocalCornerPointsAllFaces(VTK_Type, nPolyGrid, nDOFsGrid, - numFaces, nPointsPerFace, faceConn); + CPrimalGridFEM::GetLocalCornerPointsAllFaces(VTK_Type, nPolyGrid, nDOFsGrid, numFaces, nPointsPerFace, faceConn); /*--- Convert the local values of faceConn to global values. ---*/ - for(unsigned short i=0; iGetnDim(); + nDim = geometry->GetnDim(); nZone = geometry->GetnZone(); /*--- Determine the number of variables stored per DOF. ---*/ @@ -267,18 +236,19 @@ CMeshFEM::CMeshFEM(CGeometry *geometry, CConfig *config) { /*--- for this purpose. ---*/ MAIN_SOLVER Kind_Solver = config->GetKind_Solver(); const bool compressible = (Kind_Solver == MAIN_SOLVER::FEM_EULER) || - (Kind_Solver == MAIN_SOLVER::FEM_NAVIER_STOKES) || - (Kind_Solver == MAIN_SOLVER::FEM_RANS) || + (Kind_Solver == MAIN_SOLVER::FEM_NAVIER_STOKES) || (Kind_Solver == MAIN_SOLVER::FEM_RANS) || (Kind_Solver == MAIN_SOLVER::FEM_LES); unsigned short nVar; - if( compressible ) nVar = nDim + 2; - else nVar = nDim + 1; + if (compressible) + nVar = nDim + 2; + else + nVar = nDim + 1; /*--- Determine a mapping from the global point ID to the local index of the points. ---*/ - map globalPointIDToLocalInd; - for(unsigned long i=0; iGetnPoint(); ++i) + map globalPointIDToLocalInd; + for (unsigned long i = 0; i < geometry->GetnPoint(); ++i) globalPointIDToLocalInd[geometry->nodes->GetGlobalIndex(i)] = i; /*----------------------------------------------------------------------------*/ @@ -289,13 +259,13 @@ CMeshFEM::CMeshFEM(CGeometry *geometry, CConfig *config) { /*--- Determine the ranks to which I have to send my elements. ---*/ vector sendToRank(size, 0); - for(unsigned long i=0; iGetnElem(); ++i) { + for (unsigned long i = 0; i < geometry->GetnElem(); ++i) { sendToRank[geometry->elem[i]->GetColor()] = 1; } - map rankToIndCommBuf; - for(int i=0; i rankToIndCommBuf; + for (int i = 0; i < size; ++i) { + if (sendToRank[i]) { int ind = (int)rankToIndCommBuf.size(); rankToIndCommBuf[i] = ind; } @@ -304,13 +274,13 @@ CMeshFEM::CMeshFEM(CGeometry *geometry, CConfig *config) { /*--- Definition of the communication buffers, used to send the element data to the correct ranks. ---*/ int nRankSend = (int)rankToIndCommBuf.size(); - vector > shortSendBuf(nRankSend, vector(0)); - vector > longSendBuf(nRankSend, vector(0)); + vector > shortSendBuf(nRankSend, vector(0)); + vector > longSendBuf(nRankSend, vector(0)); vector > doubleSendBuf(nRankSend, vector(0)); /*--- The first element of longSendBuf will contain the number of elements, which are stored in the communication buffers. Initialize this value to 0. ---*/ - for(int i=0; i sizeRecv(size, 1); - SU2_MPI::Reduce_scatter(sendToRank.data(), &nRankRecv, sizeRecv.data(), - MPI_INT, MPI_SUM, SU2_MPI::GetComm()); + SU2_MPI::Reduce_scatter(sendToRank.data(), &nRankRecv, sizeRecv.data(), MPI_INT, MPI_SUM, SU2_MPI::GetComm()); #endif /*--- Loop over the local elements to fill the communication buffers with element data. ---*/ - for(unsigned long i=0; iGetnElem(); ++i) { + for (unsigned long i = 0; i < geometry->GetnElem(); ++i) { int ind = (int)geometry->elem[i]->GetColor(); - map::const_iterator MI = rankToIndCommBuf.find(ind); + map::const_iterator MI = rankToIndCommBuf.find(ind); ind = MI->second; - ++longSendBuf[ind][0]; /* The number of elements in the buffers must be incremented. */ + ++longSendBuf[ind][0]; /* The number of elements in the buffers must be incremented. */ shortSendBuf[ind].push_back(geometry->elem[i]->GetVTK_Type()); shortSendBuf[ind].push_back(geometry->elem[i]->GetNPolyGrid()); @@ -337,21 +306,21 @@ CMeshFEM::CMeshFEM(CGeometry *geometry, CConfig *config) { shortSendBuf[ind].push_back(geometry->elem[i]->GetNDOFsSol()); shortSendBuf[ind].push_back(geometry->elem[i]->GetnFaces()); shortSendBuf[ind].push_back(geometry->elem[i]->GetTimeLevel()); - shortSendBuf[ind].push_back( (short) geometry->elem[i]->GetJacobianConsideredConstant()); + shortSendBuf[ind].push_back((short)geometry->elem[i]->GetJacobianConsideredConstant()); longSendBuf[ind].push_back(geometry->elem[i]->GetGlobalElemID()); longSendBuf[ind].push_back(geometry->elem[i]->GetGlobalOffsetDOFsSol()); - for(unsigned short j=0; jelem[i]->GetNDOFsGrid(); ++j) + for (unsigned short j = 0; j < geometry->elem[i]->GetNDOFsGrid(); ++j) longSendBuf[ind].push_back(geometry->elem[i]->GetNode(j)); - for(unsigned short j=0; jelem[i]->GetnFaces(); ++j) + for (unsigned short j = 0; j < geometry->elem[i]->GetnFaces(); ++j) longSendBuf[ind].push_back(geometry->elem[i]->GetNeighbor_Elements(j)); - for(unsigned short j=0; jelem[i]->GetnFaces(); ++j) { + for (unsigned short j = 0; j < geometry->elem[i]->GetnFaces(); ++j) { shortSendBuf[ind].push_back(geometry->elem[i]->GetPeriodicIndex(j)); - shortSendBuf[ind].push_back( (short) geometry->elem[i]->GetJacobianConstantFace(j)); - shortSendBuf[ind].push_back( (short) geometry->elem[i]->GetOwnerFace(j)); + shortSendBuf[ind].push_back((short)geometry->elem[i]->GetJacobianConstantFace(j)); + shortSendBuf[ind].push_back((short)geometry->elem[i]->GetOwnerFace(j)); } doubleSendBuf[ind].push_back(geometry->elem[i]->GetLengthScale()); @@ -359,21 +328,19 @@ CMeshFEM::CMeshFEM(CGeometry *geometry, CConfig *config) { /*--- Determine for each rank to which I have to send elements the data of the corresponding nodes. ---*/ - for(int i=0; i nodeIDs; unsigned long indL = 3; unsigned long indS = 3; - for(long j=0; j::const_iterator LMI; + for (unsigned long j = 0; j < nodeIDs.size(); ++j) { + map::const_iterator LMI; LMI = globalPointIDToLocalInd.find(nodeIDs[j]); - if(LMI == globalPointIDToLocalInd.end()) - SU2_MPI::Error("Entry not found in map", CURRENT_FUNCTION); + if (LMI == globalPointIDToLocalInd.end()) SU2_MPI::Error("Entry not found in map", CURRENT_FUNCTION); unsigned long ind = LMI->second; - for(unsigned short l=0; lnodes->GetCoord(ind, l)); + for (unsigned short l = 0; l < nDim; ++l) doubleSendBuf[i].push_back(geometry->nodes->GetCoord(ind, l)); } } /*--- Loop over the boundaries to send the boundary data to the appropriate rank. ---*/ nMarker = geometry->GetnMarker(); - for(unsigned short iMarker=0; iMarker indLongBuf(nRankSend); - for(int i=0; iGetnElem_Bound(iMarker); ++i) { - + for (unsigned long i = 0; i < geometry->GetnElem_Bound(iMarker); ++i) { /* Determine the local ID of the corresponding domain element. */ - unsigned long elemID = geometry->bound[iMarker][i]->GetDomainElement() - - geometry->beg_node[rank]; + unsigned long elemID = geometry->bound[iMarker][i]->GetDomainElement() - geometry->beg_node[rank]; /* Determine to which rank this boundary element must be sent. That is the same as its corresponding domain element. Update the corresponding index in longSendBuf. */ int ind = (int)geometry->elem[elemID]->GetColor(); - map::const_iterator MI = rankToIndCommBuf.find(ind); + map::const_iterator MI = rankToIndCommBuf.find(ind); ind = MI->second; ++longSendBuf[ind][indLongBuf[ind]]; /* Get the donor information for the wall function treatment. */ const unsigned short nDonors = geometry->bound[iMarker][i]->GetNDonorsWallFunctions(); - const unsigned long *donors = geometry->bound[iMarker][i]->GetDonorsWallFunctions(); + const unsigned long* donors = geometry->bound[iMarker][i]->GetDonorsWallFunctions(); /* Store the data for this boundary element in the communication buffers. */ shortSendBuf[ind].push_back(geometry->bound[iMarker][i]->GetVTK_Type()); @@ -440,44 +402,41 @@ CMeshFEM::CMeshFEM(CGeometry *geometry, CConfig *config) { longSendBuf[ind].push_back(geometry->bound[iMarker][i]->GetDomainElement()); longSendBuf[ind].push_back(geometry->bound[iMarker][i]->GetGlobalElemID()); - for(unsigned short j=0; jbound[iMarker][i]->GetNDOFsGrid(); ++j) + for (unsigned short j = 0; j < geometry->bound[iMarker][i]->GetNDOFsGrid(); ++j) longSendBuf[ind].push_back(geometry->bound[iMarker][i]->GetNode(j)); - for(unsigned short j=0; j > shortRecvBuf(nRankRecv, vector(0)); - vector > longRecvBuf(nRankRecv, vector(0)); + vector > shortRecvBuf(nRankRecv, vector(0)); + vector > longRecvBuf(nRankRecv, vector(0)); vector > doubleRecvBuf(nRankRecv, vector(0)); /*--- Communicate the data to the correct ranks. Make a distinction between parallel and sequential mode. ---*/ - map::const_iterator MI; + map::const_iterator MI; #ifdef HAVE_MPI /*--- Parallel mode. Send all the data using non-blocking sends. ---*/ - vector commReqs(3*nRankSend); + vector commReqs(3 * nRankSend); MI = rankToIndCommBuf.begin(); - for(int i=0; ifirst; - SU2_MPI::Isend(shortSendBuf[i].data(), shortSendBuf[i].size(), MPI_SHORT, - dest, dest, SU2_MPI::GetComm(), &commReqs[3*i]); - SU2_MPI::Isend(longSendBuf[i].data(), longSendBuf[i].size(), MPI_LONG, - dest, dest+1, SU2_MPI::GetComm(), &commReqs[3*i+1]); - SU2_MPI::Isend(doubleSendBuf[i].data(), doubleSendBuf[i].size(), MPI_DOUBLE, - dest, dest+2, SU2_MPI::GetComm(), &commReqs[3*i+2]); + SU2_MPI::Isend(shortSendBuf[i].data(), shortSendBuf[i].size(), MPI_SHORT, dest, dest, SU2_MPI::GetComm(), + &commReqs[3 * i]); + SU2_MPI::Isend(longSendBuf[i].data(), longSendBuf[i].size(), MPI_LONG, dest, dest + 1, SU2_MPI::GetComm(), + &commReqs[3 * i + 1]); + SU2_MPI::Isend(doubleSendBuf[i].data(), doubleSendBuf[i].size(), MPI_DOUBLE, dest, dest + 2, SU2_MPI::GetComm(), + &commReqs[3 * i + 2]); } /* Loop over the number of ranks from which I receive data. */ - for(int i=0; i().swap(shortSendBuf[i]); vector().swap(longSendBuf[i]); vector().swap(doubleSendBuf[i]); @@ -537,41 +493,41 @@ CMeshFEM::CMeshFEM(CGeometry *geometry, CConfig *config) { /*--- Allocate the memory for the number of elements for every boundary marker and initialize them to zero. ---*/ nElem_Bound = new unsigned long[nMarker]; - for(unsigned short i=0; i globalElemID; globalElemID.reserve(nElem); - for(int i=0; i haloElements; + vector haloElements; vector ownedElements; unsigned short maxTimeLevelLoc = 0; - for(int i=0; iGetQuadrature_Factor_Straight()); - const unsigned short orderExactCurved = - (unsigned short) ceil(nPolySol*config->GetQuadrature_Factor_Curved()); - if(orderExactStraight == orderExactCurved) JacConstant = false; + (unsigned short)ceil(nPolySol * config->GetQuadrature_Factor_Straight()); + const unsigned short orderExactCurved = (unsigned short)ceil(nPolySol * config->GetQuadrature_Factor_Curved()); + if (orderExactStraight == orderExactCurved) JacConstant = false; } /* Update the local value of the maximum time level. */ @@ -622,32 +577,27 @@ CMeshFEM::CMeshFEM(CGeometry *geometry, CConfig *config) { and the information needed to reorder the owned elements. ---*/ indS += 8; indL += nDOFsGrid + 2; - for(unsigned short k=0; kSetnLevels_TimeAccurateLTS(nTimeLevels); /*----------------------------------------------------------------------------*/ @@ -714,40 +661,37 @@ CMeshFEM::CMeshFEM(CGeometry *geometry, CConfig *config) { /* Determine the number of owned elements and the total number of elements stored on this rank. */ nVolElemOwned = globalElemID.size(); - nVolElemTot = nVolElemOwned + haloElements.size(); + nVolElemTot = nVolElemOwned + haloElements.size(); /* Determine the map from the global element ID to the current storage sequence of ownedElements. */ map mapGlobalElemIDToInd; - for(unsigned long i=0; i nElemPerRankOr(size+1); + vector nElemPerRankOr(size + 1); - for(int i=0; ibeg_node[i]; - nElemPerRankOr[size] = geometry->end_node[size-1]; + for (int i = 0; i < size; ++i) nElemPerRankOr[i] = geometry->beg_node[i]; + nElemPerRankOr[size] = geometry->end_node[size - 1]; /* Determine to which ranks I have to send messages to find out the information of the halos stored on this rank. */ sendToRank.assign(size, 0); - for(unsigned long i=0; i::iterator low; - low = lower_bound(nElemPerRankOr.begin(), nElemPerRankOr.end(), - haloElements[i].long0); + low = lower_bound(nElemPerRankOr.begin(), nElemPerRankOr.end(), haloElements[i].long0); unsigned long rankHalo = low - nElemPerRankOr.begin(); - if(*low > haloElements[i].long0) --rankHalo; + if (*low > haloElements[i].long0) --rankHalo; sendToRank[rankHalo] = 1; } rankToIndCommBuf.clear(); - for(int i=0; i::iterator low; - low = lower_bound(nElemPerRankOr.begin(), nElemPerRankOr.end(), - haloElements[i].long0); + low = lower_bound(nElemPerRankOr.begin(), nElemPerRankOr.end(), haloElements[i].long0); unsigned long ind = low - nElemPerRankOr.begin(); - if(*low > haloElements[i].long0) --ind; + if (*low > haloElements[i].long0) --ind; /* Convert this rank to the index in the send buffer. */ MI = rankToIndCommBuf.find((int)ind); @@ -784,7 +725,7 @@ CMeshFEM::CMeshFEM(CGeometry *geometry, CConfig *config) { The subtraction of 1 is there to obtain the correct periodic index. In haloElements a +1 is added, because this variable is of unsigned long, which cannot handle negative numbers. */ - long perIndex = haloElements[i].long1 -1; + long perIndex = haloElements[i].long1 - 1; longSendBuf[ind].push_back(haloElements[i].long0); longSendBuf[ind].push_back(perIndex); @@ -805,15 +746,14 @@ CMeshFEM::CMeshFEM(CGeometry *geometry, CConfig *config) { commReqs.resize(nRankSend); MI = rankToIndCommBuf.begin(); - for(int i=0; ifirst; - SU2_MPI::Isend(longSendBuf[i].data(), longSendBuf[i].size(), MPI_LONG, - dest, dest, SU2_MPI::GetComm(), &commReqs[i]); + SU2_MPI::Isend(longSendBuf[i].data(), longSendBuf[i].size(), MPI_LONG, dest, dest, SU2_MPI::GetComm(), + &commReqs[i]); } /* Loop over the number of ranks from which I receive data. */ - for(int i=0; i().swap(longSendBuf[i]); } @@ -856,24 +794,22 @@ CMeshFEM::CMeshFEM(CGeometry *geometry, CConfig *config) { #endif /*--- Loop over the receive buffers to fill and send the send buffers again. ---*/ - for(int i=0; ibeg_node[rank]; - if(localID < 0 || localID >= (long) geometry->nPointLinear[rank]) { + if (localID < 0 || localID >= (long)geometry->nPointLinear[rank]) { ostringstream message; message << localID << " " << geometry->nPointLinear[rank] << endl; message << "Invalid local element ID"; @@ -887,15 +823,15 @@ CMeshFEM::CMeshFEM(CGeometry *geometry, CConfig *config) { longSendBuf[i].push_back(geometry->elem[localID]->GetColor()); } - /* Release the memory of this receive buffer. */ + /* Release the memory of this receive buffer. */ vector().swap(longSecondRecvBuf[i]); /*--- Send the send buffer back to the calling rank. Only in parallel mode of course. ---*/ #ifdef HAVE_MPI int dest = sourceRank[i]; - SU2_MPI::Isend(longSendBuf[i].data(), longSendBuf[i].size(), MPI_LONG, - dest, dest+1, SU2_MPI::GetComm(), &commReqs[i]); + SU2_MPI::Isend(longSendBuf[i].data(), longSendBuf[i].size(), MPI_LONG, dest, dest + 1, SU2_MPI::GetComm(), + &commReqs[i]); #endif } @@ -909,12 +845,11 @@ CMeshFEM::CMeshFEM(CGeometry *geometry, CConfig *config) { /* Parallel mode. Loop over the number of ranks from which I receive data in the return communication, i.e. nRankSend. */ - for(int i=0; i().swap(longSendBuf[i]); + for (int i = 0; i < nRankRecv; ++i) vector().swap(longSendBuf[i]); /* Copy the data from the receive buffers into a class of CLong3T, such that it can be sorted in increasing order. Note that the rank of the element is stored first, followed by its global ID and last the periodic index. */ vector haloData; - for(int i=0; i nHaloElemPerRank(size+1, 0); - for(unsigned long i=0; i nHaloElemPerRank(size + 1, 0); + for (unsigned long i = 0; i < haloData.size(); ++i) ++nHaloElemPerRank[haloData[i].long0 + 1]; nHaloElemPerRank[0] = nVolElemOwned; - for(int i=0; i nHaloElemPerRank[i]) { + for (int i = 0; i < size; ++i) { + if (nHaloElemPerRank[i + 1] > nHaloElemPerRank[i]) { sendToRank[i] = 1; int ind = (int)rankToIndCommBuf.size(); rankToIndCommBuf[i] = ind; @@ -999,17 +927,16 @@ CMeshFEM::CMeshFEM(CGeometry *geometry, CConfig *config) { nRankRecv = nRankSend; #ifdef HAVE_MPI - SU2_MPI::Reduce_scatter(sendToRank.data(), &nRankRecv, sizeRecv.data(), - MPI_INT, MPI_SUM, SU2_MPI::GetComm()); + SU2_MPI::Reduce_scatter(sendToRank.data(), &nRankRecv, sizeRecv.data(), MPI_INT, MPI_SUM, SU2_MPI::GetComm()); #endif /* Copy the data to be sent to the send buffers. */ longSendBuf.resize(nRankSend); MI = rankToIndCommBuf.begin(); - for(int i=0; ifirst; - for(unsigned long j=nHaloElemPerRank[dest]; jfirst; - SU2_MPI::Isend(longSendBuf[i].data(), longSendBuf[i].size(), MPI_LONG, - dest, dest, SU2_MPI::GetComm(), &commReqs[i]); + SU2_MPI::Isend(longSendBuf[i].data(), longSendBuf[i].size(), MPI_LONG, dest, dest, SU2_MPI::GetComm(), + &commReqs[i]); } /* Resize the vector to store the ranks from which the message came. */ sourceRank.resize(nRankRecv); /* Loop over the number of ranks from which I receive data. */ - for(int i=0; i().swap(longSendBuf[i]); } @@ -1077,14 +1001,13 @@ CMeshFEM::CMeshFEM(CGeometry *geometry, CConfig *config) { do this when ownedElements are constructed, elements that are donors for the wall function treatment and are not direct neighbors may have been missed. ---*/ - for(int i=0; i::iterator MMI = mapGlobalElemIDToInd.find(elemID); - if(MMI == mapGlobalElemIDToInd.end()) + if (MMI == mapGlobalElemIDToInd.end()) SU2_MPI::Error("Entry not found in mapGlobalElemIDToInd", CURRENT_FUNCTION); ownedElements[MMI->second].SetCommSolution(true); @@ -1121,15 +1044,14 @@ CMeshFEM::CMeshFEM(CGeometry *geometry, CConfig *config) { /* Determine the number of elements/faces that are treated simultaneously */ /* in the matrix products to obtain good gemm performance. */ - const unsigned short nElemSimul = config->GetSizeMatMulPadding()/nVar; + const unsigned short nElemSimul = config->GetSizeMatMulPadding() / nVar; /* Determine the number of different element types present. */ map mapElemTypeToInd; - for(vector::iterator OEI =ownedElements.begin(); - OEI!=ownedElements.end(); ++OEI) { + for (vector::iterator OEI = ownedElements.begin(); OEI != ownedElements.end(); ++OEI) { const unsigned short elType = OEI->GetElemType(); - if(mapElemTypeToInd.find(elType) == mapElemTypeToInd.end()) { + if (mapElemTypeToInd.find(elType) == mapElemTypeToInd.end()) { const unsigned short ind = mapElemTypeToInd.size(); mapElemTypeToInd[elType] = ind; } @@ -1140,25 +1062,21 @@ CMeshFEM::CMeshFEM(CGeometry *geometry, CConfig *config) { communicated) and elements that are communicated. Later on these vectors will be put in cumulative storage format, which explains the +1 for the second index. */ - vector > nInternalElem(nTimeLevels, - vector(mapElemTypeToInd.size()+1)); - vector > nCommElem(nTimeLevels, - vector(mapElemTypeToInd.size()+1)); - for(unsigned short i=0; i > nInternalElem(nTimeLevels, vector(mapElemTypeToInd.size() + 1)); + vector > nCommElem(nTimeLevels, vector(mapElemTypeToInd.size() + 1)); + for (unsigned short i = 0; i < nTimeLevels; ++i) { + for (unsigned long j = 0; j <= mapElemTypeToInd.size(); ++j) { nInternalElem[i][j] = 0; nCommElem[i][j] = 0; } } - for(vector::iterator OEI =ownedElements.begin(); - OEI!=ownedElements.end(); ++OEI) { + for (vector::iterator OEI = ownedElements.begin(); OEI != ownedElements.end(); ++OEI) { const unsigned short elType = OEI->GetElemType(); map::const_iterator MI = mapElemTypeToInd.find(elType); - unsigned short ind = MI->second +1; + unsigned short ind = MI->second + 1; - if( OEI->GetCommSolution() ) + if (OEI->GetCommSolution()) ++nCommElem[OEI->GetTimeLevel()][ind]; else ++nInternalElem[OEI->GetTimeLevel()][ind]; @@ -1167,24 +1085,21 @@ CMeshFEM::CMeshFEM(CGeometry *geometry, CConfig *config) { /* Loop again over the owned elements and check if elements, which do not have to send their solution, should be flagged as such in order to improve the gemm performance. */ - for(vector::iterator OEI =ownedElements.begin(); - OEI!=ownedElements.end(); ++OEI) { - + for (vector::iterator OEI = ownedElements.begin(); OEI != ownedElements.end(); ++OEI) { /* Check for an internal element, i.e. an element for which the solution does not need to be communicated. */ - if( !OEI->GetCommSolution() ) { - + if (!OEI->GetCommSolution()) { /* Determine the time level and the index of the element type. */ const unsigned short tLev = OEI->GetTimeLevel(); const unsigned short elType = OEI->GetElemType(); map::const_iterator MI = mapElemTypeToInd.find(elType); - const unsigned short ind = MI->second +1; + const unsigned short ind = MI->second + 1; /* Determine whether or not this element must be moved from internal to comm elements to improve performance. Change the appropriate data when this must happen. */ - if(nInternalElem[tLev][ind]%nElemSimul && nCommElem[tLev][ind]%nElemSimul) { + if (nInternalElem[tLev][ind] % nElemSimul && nCommElem[tLev][ind] % nElemSimul) { OEI->SetCommSolution(true); --nInternalElem[tLev][ind]; ++nCommElem[tLev][ind]; @@ -1195,30 +1110,30 @@ CMeshFEM::CMeshFEM(CGeometry *geometry, CConfig *config) { /* Check whether there are enough elements in every partition for every time level to guarantee a good gemm performance. */ unsigned long nFullChunks = 0, nPartialChunks = 0; - for(unsigned short tLev=0; tLev= (nPartialChunks+nFullChunks)) tooManyPartChunksLoc = 1; + if (5 * nPartialChunks >= (nPartialChunks + nFullChunks)) tooManyPartChunksLoc = 1; /* Determine the number of ranks which contain too many partial chunks. The result only needs to be known on the master node. */ unsigned long nRanksTooManyPartChunks = tooManyPartChunksLoc; #ifdef HAVE_MPI - SU2_MPI::Reduce(&tooManyPartChunksLoc, &nRanksTooManyPartChunks, 1, - MPI_UNSIGNED_LONG, MPI_SUM, MASTER_NODE, SU2_MPI::GetComm()); + SU2_MPI::Reduce(&tooManyPartChunksLoc, &nRanksTooManyPartChunks, 1, MPI_UNSIGNED_LONG, MPI_SUM, MASTER_NODE, + SU2_MPI::GetComm()); #endif - if((rank == MASTER_NODE) && (nRanksTooManyPartChunks != 0) && (size > 1)) { + if ((rank == MASTER_NODE) && (nRanksTooManyPartChunks != 0) && (size > 1)) { cout << endl << " WARNING" << endl; cout << "There are " << nRanksTooManyPartChunks << " partitions for which " << " the simultaneous treatment of volume elements is not optimal." << endl; @@ -1226,14 +1141,12 @@ CMeshFEM::CMeshFEM(CGeometry *geometry, CConfig *config) { } /* Put nInternalElem and nCommElem in cumulative storage format. */ - for(unsigned short tLev=0; tLev > neighElem(nVolElemOwned, vector(0)); - nRankRecv = (int) longRecvBuf.size(); - for(int i=0; i::iterator MMI = mapGlobalElemIDToInd.find(globalID); unsigned long ind = MMI->second; indS += 8; indL += nDOFsGrid + 2; - for(unsigned short k=0; ksecond); + if (MMI != mapGlobalElemIDToInd.end()) neighElem[ind].push_back(MMI->second); } } } } /* Sort the neighbors of each element in increasing order. */ - for(unsigned long i=0; i::const_iterator MI = mapElemTypeToInd.find(elType); unsigned short ind = MI->second; unsigned long indEnd; - if( ownedElements[indBeg].GetCommSolution() ) - indEnd = nCommElem[timeLevel][ind+1]; + if (ownedElements[indBeg].GetCommSolution()) + indEnd = nCommElem[timeLevel][ind + 1]; else - indEnd = nInternalElem[timeLevel][ind+1]; + indEnd = nInternalElem[timeLevel][ind + 1]; /* Determine the element in the range [indBeg,indEnd) with the least number of neighbors that has not been renumbered yet. This is the starting element for the current renumbering round. */ - for(unsigned long i=(indBeg+1); i frontElements(1, indBeg); - while( frontElements.size() ) { - + while (frontElements.size()) { /* Vector, which stores the front for the next round. */ vector frontElementsNew; /* Loop over the elements of the current front. */ - for(unsigned long i=0; isecond; - if( ownedElements[iFront].GetCommSolution() ) + if (ownedElements[iFront].GetCommSolution()) oldElemToNewElem[iFront] = nCommElem[timeLevel][ind]++; else oldElemToNewElem[iFront] = nInternalElem[timeLevel][ind]++; @@ -1362,8 +1268,8 @@ CMeshFEM::CMeshFEM(CGeometry *geometry, CConfig *config) { /* Store the neighbors that have not been renumbered yet in the front for the next round. Set its index to -2 to indicate that the element is already on the new front. */ - for(unsigned long j=0; jGetMarker_All_TagBound(iMarker); + for (unsigned short iMarker = 0; iMarker < nMarker; ++iMarker) { + boundaries[iMarker].markerTag = config->GetMarker_All_TagBound(iMarker); boundaries[iMarker].periodicBoundary = config->GetMarker_All_KindBC(iMarker) == PERIODIC_BOUNDARY; boundaries[iMarker].surfElem.reserve(nElem_Bound[iMarker]); } /*--- Copy the data from the communication buffers. ---*/ - for(int i=0; i::iterator MMI = mapGlobalElemIDToInd.find(elemID); unsigned long ind = MMI->second; /* Store the data. */ - volElem[ind].elemIsOwned = true; - volElem[ind].rankOriginal = rank; + volElem[ind].elemIsOwned = true; + volElem[ind].rankOriginal = rank; volElem[ind].periodIndexToDonor = -1; - volElem[ind].VTK_Type = shortRecvBuf[i][indS++]; + volElem[ind].VTK_Type = shortRecvBuf[i][indS++]; volElem[ind].nPolyGrid = shortRecvBuf[i][indS++]; - volElem[ind].nPolySol = shortRecvBuf[i][indS++]; + volElem[ind].nPolySol = shortRecvBuf[i][indS++]; volElem[ind].nDOFsGrid = shortRecvBuf[i][indS++]; - volElem[ind].nDOFsSol = shortRecvBuf[i][indS++]; - volElem[ind].nFaces = shortRecvBuf[i][indS++]; + volElem[ind].nDOFsSol = shortRecvBuf[i][indS++]; + volElem[ind].nFaces = shortRecvBuf[i][indS++]; volElem[ind].timeLevel = shortRecvBuf[i][indS++]; - volElem[ind].JacIsConsideredConstant = (bool) shortRecvBuf[i][indS++]; + volElem[ind].JacIsConsideredConstant = (bool)shortRecvBuf[i][indS++]; - volElem[ind].elemIDGlobal = elemID; + volElem[ind].elemIDGlobal = elemID; volElem[ind].offsetDOFsSolGlobal = longRecvBuf[i][indL++]; volElem[ind].nodeIDsGrid.resize(volElem[ind].nDOFsGrid); volElem[ind].JacFacesIsConsideredConstant.resize(volElem[ind].nFaces); volElem[ind].ElementOwnsFaces.resize(volElem[ind].nFaces); - for(unsigned short k=0; k().swap(shortRecvBuf[i]); vector().swap(longRecvBuf[i]); vector().swap(doubleRecvBuf[i]); } /*--- Sort the surface elements of the boundaries in increasing order. ---*/ - for(unsigned short iMarker=0; iMarker elemBuf(nElemBuf); - for(unsigned long j=0; j::iterator MMI = mapGlobalElemIDToInd.find(elemID); - if(MMI == mapGlobalElemIDToInd.end()) + if (MMI == mapGlobalElemIDToInd.end()) SU2_MPI::Error("Entry not found in mapGlobalElemIDToInd", CURRENT_FUNCTION); elemBuf[j].long0 = MMI->second; - elemBuf[j].long1 = longSecondRecvBuf[i][j2+1] + 1; + elemBuf[j].long1 = longSecondRecvBuf[i][j2 + 1] + 1; } /* Release the memory of the long receive buffer via the swap function @@ -1604,15 +1501,14 @@ CMeshFEM::CMeshFEM(CGeometry *geometry, CConfig *config) { vector nodeIDs; /* Loop over the elements to fill the send buffers. */ - for(unsigned long j=0; j::const_iterator LMI; + for (unsigned long j = 0; j < nodeIDs.size(); ++j) { + map::const_iterator LMI; LMI = globalPointIDToLocalInd.find(nodeIDs[j].long0); - if(LMI == globalPointIDToLocalInd.end()) - SU2_MPI::Error("Entry not found in map", CURRENT_FUNCTION); + if (LMI == globalPointIDToLocalInd.end()) SU2_MPI::Error("Entry not found in map", CURRENT_FUNCTION); unsigned long ind = LMI->second; - for(unsigned short l=0; l().swap(shortSendBuf[i]); vector().swap(longSendBuf[i]); vector().swap(doubleSendBuf[i]); @@ -1768,12 +1657,12 @@ CMeshFEM::CMeshFEM(CGeometry *geometry, CConfig *config) { vector haloElemInfo; haloElemInfo.reserve(nVolElemTot - nVolElemOwned); - for(int i=0; i haloPoints; - for(int i=0; i::iterator low; low = lower_bound(haloElemInfo.begin(), haloElemInfo.end(), thisElem); @@ -1806,27 +1693,27 @@ CMeshFEM::CMeshFEM(CGeometry *geometry, CConfig *config) { volElem[indV].rankOriginal = sourceRank[i]; volElem[indV].periodIndexToDonor = shortRecvBuf[i][indS++]; - volElem[indV].VTK_Type = shortRecvBuf[i][indS++]; - volElem[indV].nPolyGrid = shortRecvBuf[i][indS++]; - volElem[indV].nPolySol = shortRecvBuf[i][indS++]; - volElem[indV].nDOFsGrid = shortRecvBuf[i][indS++]; - volElem[indV].nDOFsSol = shortRecvBuf[i][indS++]; - volElem[indV].nFaces = shortRecvBuf[i][indS++]; - volElem[indV].timeLevel = shortRecvBuf[i][indS++]; + volElem[indV].VTK_Type = shortRecvBuf[i][indS++]; + volElem[indV].nPolyGrid = shortRecvBuf[i][indS++]; + volElem[indV].nPolySol = shortRecvBuf[i][indS++]; + volElem[indV].nDOFsGrid = shortRecvBuf[i][indS++]; + volElem[indV].nDOFsSol = shortRecvBuf[i][indS++]; + volElem[indV].nFaces = shortRecvBuf[i][indS++]; + volElem[indV].timeLevel = shortRecvBuf[i][indS++]; volElem[indV].nodeIDsGrid.resize(volElem[indV].nDOFsGrid); - for(unsigned short k=0; kGetGlobal_nPoint(); unsigned long InvalidPointID = Global_nPoint + 10; - short InvalidPerInd = SHRT_MAX; + short InvalidPerInd = SHRT_MAX; /*--- Search for the nonperiodic halo points in the local points to see if these points are already stored on this rank. If this is the case invalidate this halo and decrease the number of halo points. Afterwards remove the invalid halos from the vector. ---*/ unsigned long nHaloPoints = haloPoints.size(); - for(unsigned long i=0; i mapGlobalPointIDToInd; - for(unsigned long i=0; i::const_iterator LLMI; LLMI = mapGlobalPointIDToInd.find(searchItem); @@ -1924,53 +1809,46 @@ CMeshFEM::CMeshFEM(CGeometry *geometry, CConfig *config) { /*--- The only halo points that must be added to meshPoints are the periodic halo points. It must be checked whether or not the periodic points in haloPoints match with points in meshPoints. This is done below. ---*/ - for(unsigned long iLow=0; iLow &surfElem = boundaries[perIndex].surfElem; + vector& surfElem = boundaries[perIndex].surfElem; /*--- In the loop below the coordinates of the points of this local periodic boundary as well as a matching tolerance are determined. A vector of point ID's is also created, which is needed later on when it is checked whether or not a matching point is already stored in meshPoints. ---*/ - vector indInPoints(meshPoints.size(), -1); + vector indInPoints(meshPoints.size(), -1); vector IDsPoints; - vector coordPoints; - vector tolPoints; - - for(unsigned long j=0; j coordPoints; + vector tolPoints; + for (unsigned long j = 0; j < surfElem.size(); ++j) { /* Determine the tolerance for equal points, which is a small value times the length scale of the adjacent volume element. */ - const su2double tolElem = 1.e-2*volElem[surfElem[j].volElemID].lenScale; + const su2double tolElem = 1.e-2 * volElem[surfElem[j].volElemID].lenScale; /* Loop over the nodes of this surface grid and update the points on this periodic boundary. */ - for(unsigned short k=0; kGetPeriodicRotCenter(config->GetMarker_All_TagBound(perIndex)); auto angles = config->GetPeriodicRotAngles(config->GetMarker_All_TagBound(perIndex)); - auto trans = config->GetPeriodicTranslation(config->GetMarker_All_TagBound(perIndex)); + auto trans = config->GetPeriodicTranslation(config->GetMarker_All_TagBound(perIndex)); /*--- Compute the rotation matrix and translation vector for the transformation from the donor. This is the transpose of the transformation to the donor. ---*/ /* Store (center-trans) as it is constant and will be added on. */ - su2double translation[] = {center[0] - trans[0], - center[1] - trans[1], - center[2] - trans[2]}; + su2double translation[] = {center[0] - trans[0], center[1] - trans[1], center[2] - trans[2]}; /* Store angles separately for clarity. Compute sines/cosines. */ su2double theta = angles[0]; - su2double phi = angles[1]; - su2double psi = angles[2]; + su2double phi = angles[1]; + su2double psi = angles[2]; su2double cosTheta = cos(theta), cosPhi = cos(phi), cosPsi = cos(psi); su2double sinTheta = sin(theta), sinPhi = sin(phi), sinPsi = sin(psi); @@ -2007,65 +1882,57 @@ CMeshFEM::CMeshFEM(CGeometry *geometry, CConfig *config) { /* Compute the rotation matrix. Note that the implicit ordering is rotation about the x-axis, y-axis, then z-axis. */ su2double rotMatrix[3][3]; - rotMatrix[0][0] = cosPhi*cosPsi; - rotMatrix[0][1] = cosPhi*sinPsi; + rotMatrix[0][0] = cosPhi * cosPsi; + rotMatrix[0][1] = cosPhi * sinPsi; rotMatrix[0][2] = -sinPhi; - rotMatrix[1][0] = sinTheta*sinPhi*cosPsi - cosTheta*sinPsi; - rotMatrix[1][1] = sinTheta*sinPhi*sinPsi + cosTheta*cosPsi; - rotMatrix[1][2] = sinTheta*cosPhi; + rotMatrix[1][0] = sinTheta * sinPhi * cosPsi - cosTheta * sinPsi; + rotMatrix[1][1] = sinTheta * sinPhi * sinPsi + cosTheta * cosPsi; + rotMatrix[1][2] = sinTheta * cosPhi; - rotMatrix[2][0] = cosTheta*sinPhi*cosPsi + sinTheta*sinPsi; - rotMatrix[2][1] = cosTheta*sinPhi*sinPsi - sinTheta*cosPsi; - rotMatrix[2][2] = cosTheta*cosPhi; + rotMatrix[2][0] = cosTheta * sinPhi * cosPsi + sinTheta * sinPsi; + rotMatrix[2][1] = cosTheta * sinPhi * sinPsi - sinTheta * cosPsi; + rotMatrix[2][2] = cosTheta * cosPhi; /* Loop over the halo points for this periodic transformation. */ - for(unsigned long i=iLow; i::const_iterator LLMI; LLMI = mapGlobalPointIDToInd.find(searchItem); volElem[i].nodeIDsGrid[j] = LLMI->second; @@ -2097,91 +1964,83 @@ CMeshFEM::CMeshFEM(CGeometry *geometry, CConfig *config) { /* Determine the number of halo elements per time level in cumulative storage format. */ - nVolElemHaloPerTimeLevel.assign(nTimeLevels+1, 0); - for(unsigned long i=nVolElemOwned; i helpDxdrVec(nIntegration*nDim*nDim); - su2double *dxdrVec = helpDxdrVec.data(); + vector helpDxdrVec(nIntegration * nDim * nDim); + su2double* dxdrVec = helpDxdrVec.data(); /* Determine the gradients of the Cartesian coordinates w.r.t. the parametric coordinates. */ - ComputeGradientsCoorWRTParam(nIntegration, nDOFs, matDerBasisInt, DOFs, - dxdrVec, config); + ComputeGradientsCoorWRTParam(nIntegration, nDOFs, matDerBasisInt, DOFs, dxdrVec, config); /* Make a distinction between 2D and 3D to compute the derivatives drdx, drdy, etc. */ - switch( nDim ) { + switch (nDim) { case 2: { /* 2D computation. Store the offset between the r and s derivatives. */ - const unsigned short off = 2*nIntegration; + const unsigned short off = 2 * nIntegration; /* Loop over the integration points. */ unsigned short ii = 0; - for(unsigned short j=0; j vecRHS(nDOFs*nDim); + vector vecRHS(nDOFs * nDim); /* Loop over the grid DOFs of the element and copy the coordinates in vecRHS in row major order. */ unsigned long ic = 0; - for(unsigned short j=0; jgemm(nDim*nIntegration, nDim, nDOFs, matDerBasisInt, - vecRHS.data(), derivCoor, nullptr); + blasFunctions->gemm(nDim * nIntegration, nDim, nDOFs, matDerBasisInt, vecRHS.data(), derivCoor, nullptr); } -void CMeshFEM::ComputeNormalsFace(const unsigned short nIntegration, - const unsigned short nDOFs, - const su2double *dr, - const su2double *ds, - const unsigned long *DOFs, - su2double *normals) { - +void CMeshFEM::ComputeNormalsFace(const unsigned short nIntegration, const unsigned short nDOFs, const su2double* dr, + const su2double* ds, const unsigned long* DOFs, su2double* normals) { /* Initialize the counter ii to 0. ii is the index in normals where the information is stored. */ unsigned int ii = 0; /* Make a distinction between 2D and 3D. */ - switch( nDim ) { + switch (nDim) { case 2: { /* 2D computation. Loop over the integration points of the face. */ - for(unsigned short j=0; jGetKind_Solver() != MAIN_SOLVER::FEM_EULER && config->GetKind_Solver() != MAIN_SOLVER::DISC_ADJ_FEM_EULER); + const bool viscousTerms = (config->GetKind_Solver() != MAIN_SOLVER::FEM_EULER && + config->GetKind_Solver() != MAIN_SOLVER::DISC_ADJ_FEM_EULER); /*--- Loop over the boundary faces stored on this rank. ---*/ - for(unsigned long i=0; isurfElem.size(); ++i) { - + for (unsigned long i = 0; i < boundary->surfElem.size(); ++i) { /*--------------------------------------------------------------------------*/ /*--- Step 1: Allocate the memory for the face metric terms. ---*/ /*--- Depending on the case, not all of this memory is needed. ---*/ @@ -2323,18 +2166,17 @@ void CMeshFEM::MetricTermsBoundaryFaces(CBoundaryFEM *boundary, /* Determine the corresponding standard face element and get the relevant information from it. */ - const unsigned short ind = boundary->surfElem[i].indStandardElement; + const unsigned short ind = boundary->surfElem[i].indStandardElement; const unsigned short nInt = standardBoundaryFacesSol[ind].GetNIntegration(); /*--- Allocate the several metric terms. ---*/ - boundary->surfElem[i].metricNormalsFace.resize(nInt*(nDim+1)); + boundary->surfElem[i].metricNormalsFace.resize(nInt * (nDim + 1)); - if( viscousTerms ) - boundary->surfElem[i].metricCoorDerivFace.resize(nInt*nDim*nDim); + if (viscousTerms) boundary->surfElem[i].metricCoorDerivFace.resize(nInt * nDim * nDim); /* Allocate the memory for the grid velocities and initialize them to the default value of zero. */ - boundary->surfElem[i].gridVelocities.assign(nInt*nDim, 0.0); + boundary->surfElem[i].gridVelocities.assign(nInt * nDim, 0.0); /*--------------------------------------------------------------------------*/ /*--- Step 2: Determine the actual metric data in the integration points ---*/ @@ -2344,8 +2186,8 @@ void CMeshFEM::MetricTermsBoundaryFaces(CBoundaryFEM *boundary, /* Call the function ComputeNormalsFace to compute the unit normals and its corresponding area in the integration points. */ unsigned short nDOFs = standardBoundaryFacesGrid[ind].GetNDOFsFace(); - const su2double *dr = standardBoundaryFacesGrid[ind].GetDrBasisFaceIntegration(); - const su2double *ds = standardBoundaryFacesGrid[ind].GetDsBasisFaceIntegration(); + const su2double* dr = standardBoundaryFacesGrid[ind].GetDrBasisFaceIntegration(); + const su2double* ds = standardBoundaryFacesGrid[ind].GetDsBasisFaceIntegration(); ComputeNormalsFace(nInt, nDOFs, dr, ds, boundary->surfElem[i].DOFsGridFace.data(), boundary->surfElem[i].metricNormalsFace.data()); @@ -2353,61 +2195,51 @@ void CMeshFEM::MetricTermsBoundaryFaces(CBoundaryFEM *boundary, /* Compute the derivatives of the parametric coordinates w.r.t. the Cartesian coordinates, i.e. drdx, drdy, etc. in the integration points of the face, if needed. */ - if( viscousTerms ) { + if (viscousTerms) { nDOFs = standardBoundaryFacesGrid[ind].GetNDOFsElem(); - dr = standardBoundaryFacesGrid[ind].GetMatDerBasisElemIntegration(); + dr = standardBoundaryFacesGrid[ind].GetMatDerBasisElemIntegration(); - ComputeGradientsCoordinatesFace(nInt, nDOFs, dr, - boundary->surfElem[i].DOFsGridElement.data(), - boundary->surfElem[i].metricCoorDerivFace.data(), - config); + ComputeGradientsCoordinatesFace(nInt, nDOFs, dr, boundary->surfElem[i].DOFsGridElement.data(), + boundary->surfElem[i].metricCoorDerivFace.data(), config); } } } -void CMeshFEM::SetPositive_ZArea(CConfig *config) { - +void CMeshFEM::SetPositive_ZArea(CConfig* config) { /*---------------------------------------------------------------------------*/ /*--- Step 1: Determine the local contribution to the positive z area. ---*/ /*---------------------------------------------------------------------------*/ /* Loop over the boundary markers. */ su2double PositiveZArea = 0.0; - for(unsigned short iMarker=0; iMarkerGetMarker_All_KindBC(iMarker); + const unsigned short Boundary = config->GetMarker_All_KindBC(iMarker); const unsigned short Monitoring = config->GetMarker_All_Monitoring(iMarker); - if( ((Boundary == EULER_WALL) || - (Boundary == HEAT_FLUX) || - (Boundary == ISOTHERMAL) || - (Boundary == LOAD_BOUNDARY) || - (Boundary == DISPLACEMENT_BOUNDARY)) && (Monitoring == YES) ) { - + if (((Boundary == EULER_WALL) || (Boundary == HEAT_FLUX) || (Boundary == ISOTHERMAL) || + (Boundary == LOAD_BOUNDARY) || (Boundary == DISPLACEMENT_BOUNDARY)) && + (Monitoring == YES)) { /* Easier storage of the surface elements for this marker. */ - const vector &surfElem = boundaries[iMarker].surfElem; + const vector& surfElem = boundaries[iMarker].surfElem; /* Loop over the surface elements. */ - for(unsigned long i=0; iGetRefArea() == 0.0) - config->SetRefArea(PositiveZArea); + if (config->GetRefArea() == 0.0) config->SetRefArea(PositiveZArea); if (rank == MASTER_NODE) { - if (nDim == 2) cout << "Area projection in the y-plane = "<< PositiveZArea << "." << endl; - else cout << "Area projection in the z-plane = "<< PositiveZArea << "." << endl; + if (nDim == 2) + cout << "Area projection in the y-plane = " << PositiveZArea << "." << endl; + else + cout << "Area projection in the z-plane = " << PositiveZArea << "." << endl; } } -CMeshFEM_DG::CMeshFEM_DG(CGeometry *geometry, CConfig *config) - : CMeshFEM(geometry, config) { -} +CMeshFEM_DG::CMeshFEM_DG(CGeometry* geometry, CConfig* config) : CMeshFEM(geometry, config) {} void CMeshFEM_DG::SetGlobal_to_Local_Point(void) { Global_to_Local_Point.clear(); unsigned long ii = 0; - for(unsigned long i=0; i &surfElem = boundaries[iMarker].surfElem; + vector& surfElem = boundaries[iMarker].surfElem; /* Loop over the boundary faces and determine the coordinates in the integration points. */ - for(unsigned long l=0; l localFaces; - for(unsigned long k=0; kGetQuadrature_Factor_Straight()); + (unsigned short)ceil(thisFace.nPolyGrid0 * config->GetQuadrature_Factor_Straight()); unsigned short orderExactCurved = - (unsigned short) ceil(thisFace.nPolyGrid0*config->GetQuadrature_Factor_Curved()); - - if(orderExactStraight == orderExactCurved) { - orderExactStraight = - (unsigned short) ceil(thisFace.nPolySol0*config->GetQuadrature_Factor_Straight()); - orderExactCurved = - (unsigned short) ceil(thisFace.nPolySol0*config->GetQuadrature_Factor_Curved()); - if(orderExactStraight == orderExactCurved) - thisFace.JacFaceIsConsideredConstant = false; + (unsigned short)ceil(thisFace.nPolyGrid0 * config->GetQuadrature_Factor_Curved()); + + if (orderExactStraight == orderExactCurved) { + orderExactStraight = (unsigned short)ceil(thisFace.nPolySol0 * config->GetQuadrature_Factor_Straight()); + orderExactCurved = (unsigned short)ceil(thisFace.nPolySol0 * config->GetQuadrature_Factor_Curved()); + if (orderExactStraight == orderExactCurved) thisFace.JacFaceIsConsideredConstant = false; } } @@ -2672,47 +2481,42 @@ void CMeshFEM_DG::CreateFaces(CConfig *config) { sort(localFaces.begin(), localFaces.end()); /*--- Loop over the faces to merge the matching faces. ---*/ - for(unsigned long i=1; ifaceIndicator = iMarker; /* A few additional checks. */ bool side0IsBoundary = low->elemID0 < nVolElemTot; - unsigned long elemID = side0IsBoundary ? low->elemID0 : low->elemID1; + unsigned long elemID = side0IsBoundary ? low->elemID0 : low->elemID1; unsigned short nPoly = side0IsBoundary ? low->nPolyGrid0 : low->nPolyGrid1; - if(elemID != boundaries[iMarker].surfElem[k].volElemID || - nPoly != boundaries[iMarker].surfElem[k].nPolyGrid) + if (elemID != boundaries[iMarker].surfElem[k].volElemID || nPoly != boundaries[iMarker].surfElem[k].nPolyGrid) SU2_MPI::Error(string("Element ID and/or polynomial degree do not match ") + - string("for this boundary element. This should not happen."), + string("for this boundary element. This should not happen."), CURRENT_FUNCTION); - } - else - SU2_MPI::Error("Boundary face not found in localFaces. This should not happen.", - CURRENT_FUNCTION); + } else + SU2_MPI::Error("Boundary face not found in localFaces. This should not happen.", CURRENT_FUNCTION); } } } @@ -2773,9 +2571,8 @@ void CMeshFEM_DG::CreateFaces(CConfig *config) { These faces are indicated by an owned face and a faceIndicator of -2. To avoid that these faces are removed afterwards, set their faceIndicator to -1. ---*/ - for(unsigned long i=0; i= nVolElemOwned || - localFaces[i].elemID1 >= nVolElemOwned) { - + if (localFaces[i].elemID0 >= nVolElemOwned || localFaces[i].elemID1 >= nVolElemOwned) { /* One of the element is not owned. Make sure that the owned element is on side 0. */ swapElements = localFaces[i].elemID0 > localFaces[i].elemID1; - } - else if(localFaces[i].elemType0 == localFaces[i].elemType1) { - + } else if (localFaces[i].elemType0 == localFaces[i].elemType1) { /* The same element type on both sides. Make sure that the element with the smallest ID is stored on side 0 of the face. */ swapElements = localFaces[i].elemID0 > localFaces[i].elemID1; - } - else { + } else { /* Different element types. Make sure that the lowest element type will be stored on side 0 of the face. */ swapElements = localFaces[i].elemType0 > localFaces[i].elemType1; } - } - else { - + } else { /* Either a boundary face or a non-matching face. It must be swapped if the element is currently on side 1 of the face. */ swapElements = localFaces[i].elemID1 < nVolElemTot; @@ -2862,15 +2648,15 @@ void CMeshFEM_DG::CreateFaces(CConfig *config) { /* Swap the adjacent elements of the face, if needed. Note that also the sequence of the corner points must be altered in order to obey the right hand rule. */ - if( swapElements ) { - swap(localFaces[i].elemID0, localFaces[i].elemID1); + if (swapElements) { + swap(localFaces[i].elemID0, localFaces[i].elemID1); swap(localFaces[i].nPolyGrid0, localFaces[i].nPolyGrid1); - swap(localFaces[i].nPolySol0, localFaces[i].nPolySol1); + swap(localFaces[i].nPolySol0, localFaces[i].nPolySol1); swap(localFaces[i].nDOFsElem0, localFaces[i].nDOFsElem1); - swap(localFaces[i].elemType0, localFaces[i].elemType1); - swap(localFaces[i].faceID0, localFaces[i].faceID1); + swap(localFaces[i].elemType0, localFaces[i].elemType1); + swap(localFaces[i].faceID0, localFaces[i].faceID1); - if(localFaces[i].nCornerPoints == 2) + if (localFaces[i].nCornerPoints == 2) swap(localFaces[i].cornerPoints[0], localFaces[i].cornerPoints[1]); else swap(localFaces[i].cornerPoints[0], localFaces[i].cornerPoints[2]); @@ -2883,64 +2669,54 @@ void CMeshFEM_DG::CreateFaces(CConfig *config) { made sure that the first corner point does not coincide with the top of the pyramid. Otherwise it is impossible to carry the transformation to the standard pyramid element. ---*/ - for(unsigned long i=0; iGetnLevels_TimeAccurateLTS(); - nMatchingFacesInternal.assign(nTimeLevels+1, 0); - nMatchingFacesWithHaloElem.assign(nTimeLevels+1, 0); + nMatchingFacesInternal.assign(nTimeLevels + 1, 0); + nMatchingFacesWithHaloElem.assign(nTimeLevels + 1, 0); unsigned long nNonMatchingFaces = 0; - for(unsigned long i=0; i elemAdjLowTimeLevel(nVolElemTot, false); - for(unsigned long i=0; i volElem[e1].timeLevel) elemAdjLowTimeLevel[e0] = true; - if(volElem[e1].timeLevel > volElem[e0].timeLevel) elemAdjLowTimeLevel[e1] = true; + if (volElem[e0].timeLevel > volElem[e1].timeLevel) elemAdjLowTimeLevel[e0] = true; + if (volElem[e1].timeLevel > volElem[e0].timeLevel) elemAdjLowTimeLevel[e1] = true; } /* Determine the list of elements per time level, which share one or more @@ -3205,14 +2942,12 @@ void CMeshFEM_DG::CreateFaces(CConfig *config) { ownedElemAdjLowTimeLevel.resize(nTimeLevels); haloElemAdjLowTimeLevel.resize(nTimeLevels); - for(unsigned long i=0; i counterDOFs(nTimeLevels, 0); - for(unsigned long i=0; i &surfElem = boundaries[iMarker].surfElem; + vector& surfElem = boundaries[iMarker].surfElem; /*--- Loop over range in localFaces for this boundary marker and create the connectivity information, which is stored in surfElem. ---*/ - for(unsigned long i=indBegMarker; i recvFromRank(size, 0); - for(unsigned long i=nVolElemOwned; i rankToIndRecvBuf; - for(int i=0; i rankToIndRecvBuf; + for (int i = 0; i < size; ++i) { + if (recvFromRank[i]) { int ind = (int)rankToIndRecvBuf.size(); rankToIndRecvBuf[i] = ind; } } ranksRecv.resize(rankToIndRecvBuf.size()); - map::const_iterator MI = rankToIndRecvBuf.begin(); - for(unsigned long i=0; ifirst; + map::const_iterator MI = rankToIndRecvBuf.begin(); + for (unsigned long i = 0; i < rankToIndRecvBuf.size(); ++i, ++MI) ranksRecv[i] = MI->first; /* Define and determine the buffers to send the global indices of my halo elements to the appropriate ranks and the vectors which store the @@ -3484,7 +3179,7 @@ void CMeshFEM_DG::SetSendReceive(const CConfig *config) { vector > longBuf(rankToIndRecvBuf.size(), vector(0)); entitiesRecv.resize(rankToIndRecvBuf.size()); - for(unsigned long i=nVolElemOwned; isecond].push_back(volElem[i].elemIDGlobal); @@ -3492,9 +3187,8 @@ void CMeshFEM_DG::SetSendReceive(const CConfig *config) { } /* Determine the mapping from global element ID to local owned element ID. */ - map globalElemIDToLocalInd; - for(unsigned long i=0; i globalElemIDToLocalInd; + for (unsigned long i = 0; i < nVolElemOwned; ++i) globalElemIDToLocalInd[volElem[i].elemIDGlobal] = i; #ifdef HAVE_MPI @@ -3503,8 +3197,7 @@ void CMeshFEM_DG::SetSendReceive(const CConfig *config) { int nRankSend; vector sizeReduce(size, 1); - SU2_MPI::Reduce_scatter(recvFromRank.data(), &nRankSend, sizeReduce.data(), - MPI_INT, MPI_SUM, SU2_MPI::GetComm()); + SU2_MPI::Reduce_scatter(recvFromRank.data(), &nRankSend, sizeReduce.data(), MPI_INT, MPI_SUM, SU2_MPI::GetComm()); /* Resize ranksSend and the first index of entitiesSend to the number of ranks to which this rank has to send data. */ @@ -3514,16 +3207,15 @@ void CMeshFEM_DG::SetSendReceive(const CConfig *config) { /*--- Send all the data using non-blocking sends. ---*/ vector commReqs(ranksRecv.size()); - for(unsigned long i=0; i::const_iterator LMI; + for (int j = 0; j < sizeMess; ++j) { + map::const_iterator LMI; LMI = globalElemIDToLocalInd.find(entitiesSend[i][j]); - if(LMI == globalElemIDToLocalInd.end()) - SU2_MPI::Error("This should not happen", CURRENT_FUNCTION); + if (LMI == globalElemIDToLocalInd.end()) SU2_MPI::Error("This should not happen", CURRENT_FUNCTION); entitiesSend[i][j] = LMI->second; } @@ -3566,16 +3256,14 @@ void CMeshFEM_DG::SetSendReceive(const CConfig *config) { /* Convert the global element ID's of longBuf to local indices, which are stored in entitiesSend[0]. Note that an additional test for longBuf.size() is necessary to avoid problems. */ - if( longBuf.size() ) { - + if (longBuf.size()) { entitiesSend[0].resize(longBuf[0].size()); - for(unsigned long i=0; i::const_iterator LMI; + for (unsigned long i = 0; i < longBuf[0].size(); ++i) { + map::const_iterator LMI; LMI = globalElemIDToLocalInd.find(longBuf[0][i]); - if(LMI == globalElemIDToLocalInd.end()) - SU2_MPI::Error("This should not happen", CURRENT_FUNCTION); + if (LMI == globalElemIDToLocalInd.end()) SU2_MPI::Error("This should not happen", CURRENT_FUNCTION); entitiesSend[0][i] = LMI->second; } @@ -3591,14 +3279,12 @@ void CMeshFEM_DG::SetSendReceive(const CConfig *config) { /*--- Loop over the markers and determine the mapping for the rotationally periodic transformations. The mapping is from the marker to the first index in the vectors to store the rotationally periodic halo elements. ---*/ - map mapRotationalPeriodicToInd; - - for(unsigned short iMarker=0; iMarkerGetMarker_All_KindBC(iMarker) == PERIODIC_BOUNDARY) { + map mapRotationalPeriodicToInd; + for (unsigned short iMarker = 0; iMarker < nMarker; ++iMarker) { + if (config->GetMarker_All_KindBC(iMarker) == PERIODIC_BOUNDARY) { auto angles = config->GetPeriodicRotAngles(config->GetMarker_All_TagBound(iMarker)); - if(fabs(angles[0]) > 1.e-5 || fabs(angles[1]) > 1.e-5 || fabs(angles[2]) > 1.e-5) { - + if (fabs(angles[0]) > 1.e-5 || fabs(angles[1]) > 1.e-5 || fabs(angles[2]) > 1.e-5) { unsigned short curSize = mapRotationalPeriodicToInd.size(); mapRotationalPeriodicToInd[iMarker] = curSize; } @@ -3607,8 +3293,8 @@ void CMeshFEM_DG::SetSendReceive(const CConfig *config) { /* Store the rotationally periodic indices in rotPerMarkers. */ rotPerMarkers.reserve(mapRotationalPeriodicToInd.size()); - for(map::iterator SMI =mapRotationalPeriodicToInd.begin(); - SMI!=mapRotationalPeriodicToInd.end(); ++SMI) + for (map::iterator SMI = mapRotationalPeriodicToInd.begin(); + SMI != mapRotationalPeriodicToInd.end(); ++SMI) rotPerMarkers.push_back(SMI->first); /* Resize the first index of rotPerHalos to the correct size. */ @@ -3616,29 +3302,21 @@ void CMeshFEM_DG::SetSendReceive(const CConfig *config) { /*--- Loop over the volume elements and store the indices of the rotationally periodic halo elements in rotPerHalos. ---*/ - for(unsigned long i=nVolElemOwned; i -1) { - map::const_iterator SMI; + for (unsigned long i = nVolElemOwned; i < nVolElemTot; ++i) { + if (volElem[i].periodIndexToDonor > -1) { + map::const_iterator SMI; SMI = mapRotationalPeriodicToInd.find(volElem[i].periodIndexToDonor); - if(SMI != mapRotationalPeriodicToInd.end()) - rotPerHalos[SMI->second].push_back(i); + if (SMI != mapRotationalPeriodicToInd.end()) rotPerHalos[SMI->second].push_back(i); } } } -void CMeshFEM_DG::CreateConnectivitiesFace( - const unsigned short VTK_TypeFace, - const unsigned long *cornerPointsFace, - const unsigned short VTK_TypeElem, - const unsigned short nPolyGrid, - const vector &elemNodeIDsGrid, - const unsigned short nPolyConn, - const unsigned long *connElem, - bool &swapFaceInElement, - unsigned long *modConnFace, - unsigned long *modConnElem) { - +void CMeshFEM_DG::CreateConnectivitiesFace(const unsigned short VTK_TypeFace, const unsigned long* cornerPointsFace, + const unsigned short VTK_TypeElem, const unsigned short nPolyGrid, + const vector& elemNodeIDsGrid, const unsigned short nPolyConn, + const unsigned long* connElem, bool& swapFaceInElement, + unsigned long* modConnFace, unsigned long* modConnElem) { /*--- Set swapFaceInElement to false. This variable is only relevant for triangular faces of a pyramid and quadrilateral faces of a prism. Only for these situations this variable will be passed to the @@ -3647,42 +3325,32 @@ void CMeshFEM_DG::CreateConnectivitiesFace( /*--- Make a distinction between the types of the volume element and call the appropriate function to do the actual job. ---*/ - switch( VTK_TypeElem ) { + switch (VTK_TypeElem) { case TRIANGLE: - CreateConnectivitiesLineAdjacentTriangle(cornerPointsFace, nPolyGrid, - elemNodeIDsGrid, nPolyConn, - connElem, modConnFace, - modConnElem); + CreateConnectivitiesLineAdjacentTriangle(cornerPointsFace, nPolyGrid, elemNodeIDsGrid, nPolyConn, connElem, + modConnFace, modConnElem); break; case QUADRILATERAL: - CreateConnectivitiesLineAdjacentQuadrilateral(cornerPointsFace, nPolyGrid, - elemNodeIDsGrid, nPolyConn, - connElem, modConnFace, - modConnElem); + CreateConnectivitiesLineAdjacentQuadrilateral(cornerPointsFace, nPolyGrid, elemNodeIDsGrid, nPolyConn, connElem, + modConnFace, modConnElem); break; case TETRAHEDRON: - CreateConnectivitiesTriangleAdjacentTetrahedron(cornerPointsFace, nPolyGrid, - elemNodeIDsGrid, nPolyConn, - connElem, modConnFace, - modConnElem); + CreateConnectivitiesTriangleAdjacentTetrahedron(cornerPointsFace, nPolyGrid, elemNodeIDsGrid, nPolyConn, connElem, + modConnFace, modConnElem); break; case PYRAMID: { - switch( VTK_TypeFace ) { + switch (VTK_TypeFace) { case TRIANGLE: - CreateConnectivitiesTriangleAdjacentPyramid(cornerPointsFace, nPolyGrid, - elemNodeIDsGrid, nPolyConn, - connElem, swapFaceInElement, - modConnFace, modConnElem); + CreateConnectivitiesTriangleAdjacentPyramid(cornerPointsFace, nPolyGrid, elemNodeIDsGrid, nPolyConn, connElem, + swapFaceInElement, modConnFace, modConnElem); break; case QUADRILATERAL: - CreateConnectivitiesQuadrilateralAdjacentPyramid(cornerPointsFace, nPolyGrid, - elemNodeIDsGrid, nPolyConn, - connElem, modConnFace, - modConnElem); + CreateConnectivitiesQuadrilateralAdjacentPyramid(cornerPointsFace, nPolyGrid, elemNodeIDsGrid, nPolyConn, + connElem, modConnFace, modConnElem); break; } @@ -3690,19 +3358,15 @@ void CMeshFEM_DG::CreateConnectivitiesFace( } case PRISM: { - switch( VTK_TypeFace ) { + switch (VTK_TypeFace) { case TRIANGLE: - CreateConnectivitiesTriangleAdjacentPrism(cornerPointsFace, nPolyGrid, - elemNodeIDsGrid, nPolyConn, - connElem, modConnFace, - modConnElem); + CreateConnectivitiesTriangleAdjacentPrism(cornerPointsFace, nPolyGrid, elemNodeIDsGrid, nPolyConn, connElem, + modConnFace, modConnElem); break; case QUADRILATERAL: - CreateConnectivitiesQuadrilateralAdjacentPrism(cornerPointsFace, nPolyGrid, - elemNodeIDsGrid, nPolyConn, - connElem, swapFaceInElement, - modConnFace, modConnElem); + CreateConnectivitiesQuadrilateralAdjacentPrism(cornerPointsFace, nPolyGrid, elemNodeIDsGrid, nPolyConn, + connElem, swapFaceInElement, modConnFace, modConnElem); break; } @@ -3710,27 +3374,20 @@ void CMeshFEM_DG::CreateConnectivitiesFace( } case HEXAHEDRON: - CreateConnectivitiesQuadrilateralAdjacentHexahedron(cornerPointsFace, nPolyGrid, - elemNodeIDsGrid, nPolyConn, - connElem, modConnFace, - modConnElem); + CreateConnectivitiesQuadrilateralAdjacentHexahedron(cornerPointsFace, nPolyGrid, elemNodeIDsGrid, nPolyConn, + connElem, modConnFace, modConnElem); break; } } void CMeshFEM_DG::CreateConnectivitiesLineAdjacentQuadrilateral( - const unsigned long *cornerPointsLine, - const unsigned short nPolyGrid, - const vector &quadNodeIDsGrid, - const unsigned short nPolyConn, - const unsigned long *connQuad, - unsigned long *modConnLine, - unsigned long *modConnQuad) { - + const unsigned long* cornerPointsLine, const unsigned short nPolyGrid, const vector& quadNodeIDsGrid, + const unsigned short nPolyConn, const unsigned long* connQuad, unsigned long* modConnLine, + unsigned long* modConnQuad) { /* Determine the indices of the four corner points of the quadrilateral. */ const unsigned short ind0 = 0; const unsigned short ind1 = nPolyGrid; - const unsigned short ind2 = (nPolyGrid+1)*(nPolyGrid+1) -1; + const unsigned short ind2 = (nPolyGrid + 1) * (nPolyGrid + 1) - 1; const unsigned short ind3 = ind2 - nPolyGrid; /* Easier storage of the two corner points of the line in the new numbering. */ @@ -3746,96 +3403,106 @@ void CMeshFEM_DG::CreateConnectivitiesLineAdjacentQuadrilateral( of the quad. This is determined below. The bool verticesDontMatch is there to check if vertices do not match. This should not happen, but it is checked for security. ---*/ - signed short a=0, b=0, c=0, d=0, e=0, f=0; + signed short a = 0, b = 0, c = 0, d = 0, e = 0, f = 0; bool verticesDontMatch = false; - if(vert0 == quadNodeIDsGrid[ind0]) { + if (vert0 == quadNodeIDsGrid[ind0]) { /* Vert0 coincides with vertex 0 of the quad connectivity. Determine the situation for vert1. */ - if(vert1 == quadNodeIDsGrid[ind1]){ + if (vert1 == quadNodeIDsGrid[ind1]) { /* The new numbering is the same as the original numbering. */ - a = d = 0; b = f = 1; c = e = 0; - } - else if(vert1 == quadNodeIDsGrid[ind3]) { + a = d = 0; + b = f = 1; + c = e = 0; + } else if (vert1 == quadNodeIDsGrid[ind3]) { /* The i and j numbering are swapped. This is a left handed transformation. */ - a = d = 0; b = f = 0; c = e = 1; - } - else { + a = d = 0; + b = f = 0; + c = e = 1; + } else { verticesDontMatch = true; // Vert1 does not match with a neigbor. } - } - else if(vert0 == quadNodeIDsGrid[ind1]) { + } else if (vert0 == quadNodeIDsGrid[ind1]) { /* Vert0 coincides with vertex 1 of the quad connectivity. Determine the situation for vert1. */ - if(vert1 == quadNodeIDsGrid[ind2]){ + if (vert1 == quadNodeIDsGrid[ind2]) { /* The i-direction of the new numbering corresponds to the j-direction of the original numbering, while the new j-direction is the negative i-direction of the original numbering. */ - a = 0; d = nPolyConn; b = f = 0; c = 1; e = -1; - } - else if(vert1 == quadNodeIDsGrid[ind0]) { + a = 0; + d = nPolyConn; + b = f = 0; + c = 1; + e = -1; + } else if (vert1 == quadNodeIDsGrid[ind0]) { /* The i-direction is negated, while the j-direction coincides. This is a left handed transformation. */ - a = nPolyConn; d = 0; b = -1; f = 1; c = e = 0; - } - else { + a = nPolyConn; + d = 0; + b = -1; + f = 1; + c = e = 0; + } else { verticesDontMatch = true; // Vert1 does not match with a neigbor. } - } - else if(vert0 == quadNodeIDsGrid[ind2]) { + } else if (vert0 == quadNodeIDsGrid[ind2]) { /* Vert0 coincides with vertex 2 of the quad connectivity. Determine the situation for vert1. */ - if(vert1 == quadNodeIDsGrid[ind3]){ + if (vert1 == quadNodeIDsGrid[ind3]) { /* Both the i- and j-direction are negated. */ - a = d = nPolyConn; b = f = -1; c = e = 0; - } - else if(vert1 == quadNodeIDsGrid[ind1]) { + a = d = nPolyConn; + b = f = -1; + c = e = 0; + } else if (vert1 == quadNodeIDsGrid[ind1]) { /* The new i-direction is the original negative j-direction, while the new j-direction is the original negative i-direction. This is a left handed transformation. */ - a = d = nPolyConn; b = f = 0; c = e = -1; - } - else { + a = d = nPolyConn; + b = f = 0; + c = e = -1; + } else { verticesDontMatch = true; // Vert1 does not match with a neigbor. } - } - else if(vert0 == quadNodeIDsGrid[ind3]) { + } else if (vert0 == quadNodeIDsGrid[ind3]) { /* Vert0 coincides with vertex 3 of the quad connectivity. Determine the situation for vert1. */ - if(vert1 == quadNodeIDsGrid[ind0]){ + if (vert1 == quadNodeIDsGrid[ind0]) { /* The new i-direction is the original negative j-direction, while the new j-direction is the original i-direction. */ - a = nPolyConn; d = 0; b = f = 0; c = -1; e = 1; - } - else if(vert1 == quadNodeIDsGrid[ind2]){ + a = nPolyConn; + d = 0; + b = f = 0; + c = -1; + e = 1; + } else if (vert1 == quadNodeIDsGrid[ind2]) { /* The i-directions coincide while the j-direction is negated. This is a left handed transformation. */ - a = 0; d = nPolyConn; b = 1; f = -1; c = e = 0; - } - else { + a = 0; + d = nPolyConn; + b = 1; + f = -1; + c = e = 0; + } else { verticesDontMatch = true; // Vert1 does not match with a neigbor. } - } - else { + } else { /* Vert0 does not match with any of the corner vertices of the quad. */ verticesDontMatch = true; } /*--- If non-matching vertices have been found, terminate with an error message. ---*/ - if( verticesDontMatch ) - SU2_MPI::Error("Corner vertices do not match. This should not happen.", CURRENT_FUNCTION); + if (verticesDontMatch) SU2_MPI::Error("Corner vertices do not match. This should not happen.", CURRENT_FUNCTION); /*--- Loop over the DOFs of the original quad to create the connectivity of the quad that corresponds to the new numbering. ---*/ unsigned short ind = 0; - for(unsigned short j=0; j<=nPolyConn; ++j) { - for(unsigned short i=0; i<=nPolyConn; ++i, ++ind) { - + for (unsigned short j = 0; j <= nPolyConn; ++j) { + for (unsigned short i = 0; i <= nPolyConn; ++i, ++ind) { /*--- Determine the ii and jj indices of the new numbering, convert it to a 1D index and shore the modified index in modConnQuad. ---*/ - unsigned short ii = a + i*b + j*c; - unsigned short jj = d + i*e + j*f; - unsigned short iind = jj*(nPolyConn+1) + ii; + unsigned short ii = a + i * b + j * c; + unsigned short jj = d + i * e + j * f; + unsigned short iind = jj * (nPolyConn + 1) + ii; modConnQuad[iind] = connQuad[ind]; } @@ -3844,23 +3511,19 @@ void CMeshFEM_DG::CreateConnectivitiesLineAdjacentQuadrilateral( /*--- The line corresponds to face 0 of the quadrilateral. Hence the first nPolyConn+1 entries in modConnQuad are the DOFs of the line. Copy these entries from modConnQuad. ---*/ - for(unsigned short i=0; i<=nPolyConn; ++i) - modConnLine[i] = modConnQuad[i]; + for (unsigned short i = 0; i <= nPolyConn; ++i) modConnLine[i] = modConnQuad[i]; } -void CMeshFEM_DG::CreateConnectivitiesLineAdjacentTriangle( - const unsigned long *cornerPointsLine, - const unsigned short nPolyGrid, - const vector &triaNodeIDsGrid, - const unsigned short nPolyConn, - const unsigned long *connTria, - unsigned long *modConnLine, - unsigned long *modConnTria) { - +void CMeshFEM_DG::CreateConnectivitiesLineAdjacentTriangle(const unsigned long* cornerPointsLine, + const unsigned short nPolyGrid, + const vector& triaNodeIDsGrid, + const unsigned short nPolyConn, + const unsigned long* connTria, unsigned long* modConnLine, + unsigned long* modConnTria) { /* Determine the indices of the 3 corner vertices of the triangle. */ const unsigned short ind0 = 0; const unsigned short ind1 = nPolyGrid; - const unsigned short ind2 = (nPolyGrid+1)*(nPolyGrid+2)/2 -1; + const unsigned short ind2 = (nPolyGrid + 1) * (nPolyGrid + 2) / 2 - 1; /* Easier storage of the two corner points of the line in the new numbering. */ const unsigned long vert0 = cornerPointsLine[0]; @@ -3875,81 +3538,101 @@ void CMeshFEM_DG::CreateConnectivitiesLineAdjacentTriangle( of the triangle. This is determined below. The bool verticesDontMatch is there to check if vertices do not match. This should not happen, but it is checked for security. ---*/ - signed short a=0, b=0, c=0, d=0, e=0, f=0; + signed short a = 0, b = 0, c = 0, d = 0, e = 0, f = 0; bool verticesDontMatch = false; - if(vert0 == triaNodeIDsGrid[ind0]) { + if (vert0 == triaNodeIDsGrid[ind0]) { /* Vert0 coincides with vertex 0 of the triangle connectivity. Determine the situation for vert1. */ - if(vert1 == triaNodeIDsGrid[ind1]){ + if (vert1 == triaNodeIDsGrid[ind1]) { /* The new numbering is the same as the original numbering. */ - a = 0; b = 1; c = 0; d = 0; e = 0; f = 1; - } - else if(vert1 == triaNodeIDsGrid[ind2]) { + a = 0; + b = 1; + c = 0; + d = 0; + e = 0; + f = 1; + } else if (vert1 == triaNodeIDsGrid[ind2]) { /* The i and j numbering are swapped. This is a left handed transformation. */ - a = 0; b = 0; c = 1; d = 0; e = 1; f = 0; - } - else { + a = 0; + b = 0; + c = 1; + d = 0; + e = 1; + f = 0; + } else { verticesDontMatch = true; // Vert1 does not match with a neigbor. } - } - else if(vert0 == triaNodeIDsGrid[ind1]) { + } else if (vert0 == triaNodeIDsGrid[ind1]) { /* Vert0 coincides with vertex 1 of the triangle connectivity. Determine the situation for vert1. */ - if(vert1 == triaNodeIDsGrid[ind2]){ + if (vert1 == triaNodeIDsGrid[ind2]) { /* The i-direction of the new numbering corresponds to the j-direction of the original numbering, while the new j-direction corresponds to a combination of the original i- and j-direction. */ - a = 0; b = 0; c = 1; d = nPolyConn; e = -1; f = -1; - } - else if(vert1 == triaNodeIDsGrid[ind0]) { + a = 0; + b = 0; + c = 1; + d = nPolyConn; + e = -1; + f = -1; + } else if (vert1 == triaNodeIDsGrid[ind0]) { /* The i-direction of the new numbering corresponds to a combination of the original i- and j-direction, while the new j-direction corresponds to the j-direction of the original numbering. This is a left handed transformation. */ - a = nPolyConn; b = -1; c = -1; d = 0; e = 0; f = 1; - } - else { + a = nPolyConn; + b = -1; + c = -1; + d = 0; + e = 0; + f = 1; + } else { verticesDontMatch = true; // Vert1 does not match with a neigbor. } - } - else if(vert0 == triaNodeIDsGrid[ind2]) { + } else if (vert0 == triaNodeIDsGrid[ind2]) { /* Vert0 coincides with vertex 2 of the triangle connectivity. Determine the situation for vert1. */ - if(vert1 == triaNodeIDsGrid[ind0]){ + if (vert1 == triaNodeIDsGrid[ind0]) { /* The i-direction of the new numbering corresponds to a combination of the original i- and j-direction, while the new j-direction corresponds to the i-direction of the original numbering. */ - a = nPolyConn; b = -1; c = -1; d = 0; e = 1; f = 0; - } - else if(vert1 == triaNodeIDsGrid[ind1]) { + a = nPolyConn; + b = -1; + c = -1; + d = 0; + e = 1; + f = 0; + } else if (vert1 == triaNodeIDsGrid[ind1]) { /* The i-direction of the new numbering corresponds to the i-direction of the original numbering, while the new j-direction corresponds to a combination of the original i- and j-direction. This is a left handed transformation. */ - a = 0; b = 1; c = 0; d = nPolyConn; e = -1; f = -1; - } - else { + a = 0; + b = 1; + c = 0; + d = nPolyConn; + e = -1; + f = -1; + } else { verticesDontMatch = true; // Vert1 does not match with a neigbor. } } /*--- If non-matching vertices have been found, terminate with an error message. ---*/ - if( verticesDontMatch ) - SU2_MPI::Error("Corner vertices do not match. This should not happen.", CURRENT_FUNCTION); + if (verticesDontMatch) SU2_MPI::Error("Corner vertices do not match. This should not happen.", CURRENT_FUNCTION); /*--- Loop over the DOFs of the original triangle to create the connectivity of the triangle that corresponds to the new numbering. ---*/ unsigned short ind = 0; - for(unsigned short j=0; j<=nPolyConn; ++j) { - for(unsigned short i=0; i<=(nPolyConn-j); ++i, ++ind) { - + for (unsigned short j = 0; j <= nPolyConn; ++j) { + for (unsigned short i = 0; i <= (nPolyConn - j); ++i, ++ind) { /*--- Determine the ii and jj indices of the new numbering, convert it to a 1D index and shore the modified index in modConnTria. ---*/ - unsigned short ii = a + i*b + j*c; - unsigned short jj = d + i*e + j*f; + unsigned short ii = a + i * b + j * c; + unsigned short jj = d + i * e + j * f; - unsigned short iind = jj*(nPolyConn+1) + ii - jj*(jj-1)/2; + unsigned short iind = jj * (nPolyConn + 1) + ii - jj * (jj - 1) / 2; modConnTria[iind] = connTria[ind]; } @@ -3958,25 +3641,19 @@ void CMeshFEM_DG::CreateConnectivitiesLineAdjacentTriangle( /*--- The line corresponds to face 0 of the triangle. Hence the first nPolyConn+1 entries in modConnTria are the DOFs of the line. Copy these entries from modConnTria. ---*/ - for(unsigned short i=0; i<=nPolyConn; ++i) - modConnLine[i] = modConnTria[i]; + for (unsigned short i = 0; i <= nPolyConn; ++i) modConnLine[i] = modConnTria[i]; } void CMeshFEM_DG::CreateConnectivitiesQuadrilateralAdjacentHexahedron( - const unsigned long *cornerPointsQuad, - const unsigned short nPolyGrid, - const vector &hexaNodeIDsGrid, - const unsigned short nPolyConn, - const unsigned long *connHexa, - unsigned long *modConnQuad, - unsigned long *modConnHexa) { - + const unsigned long* cornerPointsQuad, const unsigned short nPolyGrid, const vector& hexaNodeIDsGrid, + const unsigned short nPolyConn, const unsigned long* connHexa, unsigned long* modConnQuad, + unsigned long* modConnHexa) { /* Determine the indices of the eight corner points of the hexahedron. */ const unsigned short ind0 = 0; const unsigned short ind1 = nPolyGrid; - const unsigned short ind2 = (nPolyGrid+1)*(nPolyGrid+1) -1; + const unsigned short ind2 = (nPolyGrid + 1) * (nPolyGrid + 1) - 1; const unsigned short ind3 = ind2 - nPolyGrid; - const unsigned short ind4 = (nPolyGrid+1)*(nPolyGrid+1)*nPolyGrid; + const unsigned short ind4 = (nPolyGrid + 1) * (nPolyGrid + 1) * nPolyGrid; const unsigned short ind5 = ind1 + ind4; const unsigned short ind6 = ind2 + ind4; const unsigned short ind7 = ind3 + ind4; @@ -3997,208 +3674,245 @@ void CMeshFEM_DG::CreateConnectivitiesQuadrilateralAdjacentHexahedron( of the hexahedron. This is determined below. The bool verticesDontMatch is there to check if vertices do not match. This should not happen, but it is checked for security. ---*/ - signed short a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0, - l = 0, m = 0, n = 0, o = 0; + signed short a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0, l = 0, m = 0, n = 0, o = 0; bool verticesDontMatch = false; - if(vert0 == hexaNodeIDsGrid[ind0] && vert1 == hexaNodeIDsGrid[ind1] && // ii = i. - vert2 == hexaNodeIDsGrid[ind2] && vert3 == hexaNodeIDsGrid[ind3]) { // jj = j. - b = g = o = 1; // kk = k. - } - else if(vert0 == hexaNodeIDsGrid[ind0] && vert1 == hexaNodeIDsGrid[ind3] && // ii = j. - vert2 == hexaNodeIDsGrid[ind2] && vert3 == hexaNodeIDsGrid[ind1]) { // jj = i. - c = f = o = 1; // kk = k. - } - else if(vert0 == hexaNodeIDsGrid[ind0] && vert1 == hexaNodeIDsGrid[ind1] && // ii = i. - vert2 == hexaNodeIDsGrid[ind5] && vert3 == hexaNodeIDsGrid[ind4]) { // jj = k. - b = h = n = 1; // kk = j. - } - else if(vert0 == hexaNodeIDsGrid[ind0] && vert1 == hexaNodeIDsGrid[ind4] && // ii = k. - vert2 == hexaNodeIDsGrid[ind5] && vert3 == hexaNodeIDsGrid[ind1]) { // jj = i. - d = f = n = 1; // kk = j. - } - else if(vert0 == hexaNodeIDsGrid[ind0] && vert1 == hexaNodeIDsGrid[ind3] && // ii = j. - vert2 == hexaNodeIDsGrid[ind7] && vert3 == hexaNodeIDsGrid[ind4]) { // jj = k. - c = h = m = 1; // kk = i. - } - else if(vert0 == hexaNodeIDsGrid[ind0] && vert1 == hexaNodeIDsGrid[ind4] && // ii = k. - vert2 == hexaNodeIDsGrid[ind7] && vert3 == hexaNodeIDsGrid[ind3]) { // jj = j. - d = g = m = 1; // kk = i. - } - - else if(vert0 == hexaNodeIDsGrid[ind1] && vert1 == hexaNodeIDsGrid[ind0] && // ii = nPoly-i. - vert2 == hexaNodeIDsGrid[ind3] && vert3 == hexaNodeIDsGrid[ind2]) { // jj = j. - a = nPolyConn; b = -1; g = o = 1; // kk = k. - } - else if(vert0 == hexaNodeIDsGrid[ind1] && vert1 == hexaNodeIDsGrid[ind2] && // ii = j. - vert2 == hexaNodeIDsGrid[ind3] && vert3 == hexaNodeIDsGrid[ind0]) { // jj = nPoly-i. - e = nPolyConn; f = -1; c = o = 1; // kk = k. - } - else if(vert0 == hexaNodeIDsGrid[ind1] && vert1 == hexaNodeIDsGrid[ind0] && // ii = nPoly-i. - vert2 == hexaNodeIDsGrid[ind4] && vert3 == hexaNodeIDsGrid[ind5]) { // jj = k. - a = nPolyConn; b = -1; h = n = 1; // kk = j. - } - else if(vert0 == hexaNodeIDsGrid[ind1] && vert1 == hexaNodeIDsGrid[ind5] && // ii = k. - vert2 == hexaNodeIDsGrid[ind4] && vert3 == hexaNodeIDsGrid[ind0]) { // jj = nPoly-i. - e = nPolyConn; f = -1; d = n = 1; // kk = j. - } - else if(vert0 == hexaNodeIDsGrid[ind1] && vert1 == hexaNodeIDsGrid[ind2] && // ii = j. - vert2 == hexaNodeIDsGrid[ind6] && vert3 == hexaNodeIDsGrid[ind5]) { // jj = k. - l = nPolyConn; m = -1; c = h = 1; // kk = nPoly-i. - } - else if(vert0 == hexaNodeIDsGrid[ind1] && vert1 == hexaNodeIDsGrid[ind5] && // ii = k. - vert2 == hexaNodeIDsGrid[ind6] && vert3 == hexaNodeIDsGrid[ind2]) { // jj = j. - l = nPolyConn; m = -1; d = g = 1; // kk = nPoly-i. - } - - else if(vert0 == hexaNodeIDsGrid[ind2] && vert1 == hexaNodeIDsGrid[ind1] && // ii = nPoly-j. - vert2 == hexaNodeIDsGrid[ind0] && vert3 == hexaNodeIDsGrid[ind3]) { // jj = nPoly-i. - a = e = nPolyConn; c = f = -1; o = 1; // kk = k. - } - else if(vert0 == hexaNodeIDsGrid[ind2] && vert1 == hexaNodeIDsGrid[ind3] && // ii = nPoly-i. - vert2 == hexaNodeIDsGrid[ind0] && vert3 == hexaNodeIDsGrid[ind1]) { // jj = nPoly-j. - a = e = nPolyConn; b = g = -1; o = 1; // kk = k. - } - else if(vert0 == hexaNodeIDsGrid[ind2] && vert1 == hexaNodeIDsGrid[ind1] && // ii = nPoly-j. - vert2 == hexaNodeIDsGrid[ind5] && vert3 == hexaNodeIDsGrid[ind6]) { // jj = k. - a = l = nPolyConn; c = m = -1; h = 1; // kk = nPoly-i. - } - else if(vert0 == hexaNodeIDsGrid[ind2] && vert1 == hexaNodeIDsGrid[ind6] && // ii = k. - vert2 == hexaNodeIDsGrid[ind5] && vert3 == hexaNodeIDsGrid[ind1]) { // jj = nPoly-j. - e = l = nPolyConn; g = m = -1; d = 1; // kk = nPoly-i. - } - else if(vert0 == hexaNodeIDsGrid[ind2] && vert1 == hexaNodeIDsGrid[ind3] && // ii = nPoly-i. - vert2 == hexaNodeIDsGrid[ind7] && vert3 == hexaNodeIDsGrid[ind6]) { // jj = k. - a = l = nPolyConn; b = n = -1; h = 1; // kk = nPoly-j. - } - else if(vert0 == hexaNodeIDsGrid[ind2] && vert1 == hexaNodeIDsGrid[ind6] && // ii = k. - vert2 == hexaNodeIDsGrid[ind7] && vert3 == hexaNodeIDsGrid[ind3]) { // jj = nPoly-i. - e = l = nPolyConn; f = n = -1; d = 1; // kk = nPoly-j. - } - - else if(vert0 == hexaNodeIDsGrid[ind3] && vert1 == hexaNodeIDsGrid[ind0] && // ii = nPoly-j. - vert2 == hexaNodeIDsGrid[ind1] && vert3 == hexaNodeIDsGrid[ind2]) { // jj = i. - a = nPolyConn; c = -1; f = o = 1; // kk = k. - } - else if(vert0 == hexaNodeIDsGrid[ind3] && vert1 == hexaNodeIDsGrid[ind2] && // ii = i. - vert2 == hexaNodeIDsGrid[ind1] && vert3 == hexaNodeIDsGrid[ind0]) { // jj = nPoly-j. - e = nPolyConn; g = -1; b = o = 1; // kk = k. - } - else if(vert0 == hexaNodeIDsGrid[ind3] && vert1 == hexaNodeIDsGrid[ind0] && // ii = nPoly-j. - vert2 == hexaNodeIDsGrid[ind4] && vert3 == hexaNodeIDsGrid[ind7]) { // jj = k. - a = nPolyConn; c = -1; h = m = 1; // kk = i. - } - else if(vert0 == hexaNodeIDsGrid[ind3] && vert1 == hexaNodeIDsGrid[ind7] && // ii = k. - vert2 == hexaNodeIDsGrid[ind4] && vert3 == hexaNodeIDsGrid[ind0]) { // jj = nPoly-j. - e = nPolyConn; g = -1; d = m = 1; // kk = i. - } - else if(vert0 == hexaNodeIDsGrid[ind3] && vert1 == hexaNodeIDsGrid[ind2] && // ii = i. - vert2 == hexaNodeIDsGrid[ind6] && vert3 == hexaNodeIDsGrid[ind7]) { // jj = k. - l = nPolyConn; n = -1; b = h = 1; // kk = nPoly-j. - } - else if(vert0 == hexaNodeIDsGrid[ind3] && vert1 == hexaNodeIDsGrid[ind7] && // ii = k. - vert2 == hexaNodeIDsGrid[ind6] && vert3 == hexaNodeIDsGrid[ind2]) { // jj = i. - l = nPolyConn; n = -1; d = f = 1; // kk = nPoly-j. - } - - else if(vert0 == hexaNodeIDsGrid[ind4] && vert1 == hexaNodeIDsGrid[ind5] && // ii = i. - vert2 == hexaNodeIDsGrid[ind6] && vert3 == hexaNodeIDsGrid[ind7]) { // jj = j. - l = nPolyConn; o = -1; b = g = 1; // kk = nPoly-k. - } - else if(vert0 == hexaNodeIDsGrid[ind4] && vert1 == hexaNodeIDsGrid[ind7] && // ii = j. - vert2 == hexaNodeIDsGrid[ind6] && vert3 == hexaNodeIDsGrid[ind5]) { // jj = i. - l = nPolyConn; o = -1; c = f = 1; // kk = nPoly-k. - } - else if(vert0 == hexaNodeIDsGrid[ind4] && vert1 == hexaNodeIDsGrid[ind5] && // ii = i. - vert2 == hexaNodeIDsGrid[ind1] && vert3 == hexaNodeIDsGrid[ind0]) { // jj = nPoly-k. - e = nPolyConn; h = -1; b = n = 1; // kk = j. - } - else if(vert0 == hexaNodeIDsGrid[ind4] && vert1 == hexaNodeIDsGrid[ind0] && // ii = nPoly-k. - vert2 == hexaNodeIDsGrid[ind1] && vert3 == hexaNodeIDsGrid[ind5]) { // jj = i. - a = nPolyConn; d = -1; f = n = 1; // kk = j. - } - else if(vert0 == hexaNodeIDsGrid[ind4] && vert1 == hexaNodeIDsGrid[ind7] && // ii = j. - vert2 == hexaNodeIDsGrid[ind3] && vert3 == hexaNodeIDsGrid[ind0]) { // jj = nPoly-k. - e = nPolyConn; h = -1; c = m = 1; // kk = i. - } - else if(vert0 == hexaNodeIDsGrid[ind4] && vert1 == hexaNodeIDsGrid[ind0] && // ii = nPoly-k. - vert2 == hexaNodeIDsGrid[ind3] && vert3 == hexaNodeIDsGrid[ind7]) { // jj = j. - a = nPolyConn; d = -1; g = m = 1; // kk = i. - } - - else if(vert0 == hexaNodeIDsGrid[ind5] && vert1 == hexaNodeIDsGrid[ind6] && // ii = j. - vert2 == hexaNodeIDsGrid[ind7] && vert3 == hexaNodeIDsGrid[ind4]) { // jj = nPoly-i. - e = l = nPolyConn; f = o = -1; c = 1; // kk = nPoly-k. - } - else if(vert0 == hexaNodeIDsGrid[ind5] && vert1 == hexaNodeIDsGrid[ind4] && // ii = nPoly-i. - vert2 == hexaNodeIDsGrid[ind7] && vert3 == hexaNodeIDsGrid[ind6]) { // jj = j. - a = l = nPolyConn; b = o = -1; g = 1; // kk = nPoly-k. - } - else if(vert0 == hexaNodeIDsGrid[ind5] && vert1 == hexaNodeIDsGrid[ind6] && // ii = j. - vert2 == hexaNodeIDsGrid[ind2] && vert3 == hexaNodeIDsGrid[ind1]) { // jj = nPoly-k. - e = l = nPolyConn; h = m = -1; c = 1; // kk = nPoly-i. - } - else if(vert0 == hexaNodeIDsGrid[ind5] && vert1 == hexaNodeIDsGrid[ind1] && // ii = nPoly-k. - vert2 == hexaNodeIDsGrid[ind2] && vert3 == hexaNodeIDsGrid[ind6]) { // jj = j. - a = l = nPolyConn; d = m = -1; g = 1; // kk = nPoly-i. - } - else if(vert0 == hexaNodeIDsGrid[ind5] && vert1 == hexaNodeIDsGrid[ind1] && // ii = nPoly-k. - vert2 == hexaNodeIDsGrid[ind0] && vert3 == hexaNodeIDsGrid[ind4]) { // jj = nPoly-i. - a = e = nPolyConn; d = f = -1; n = 1; // kk = j. - } - else if(vert0 == hexaNodeIDsGrid[ind5] && vert1 == hexaNodeIDsGrid[ind4] && // ii = nPoly-i. - vert2 == hexaNodeIDsGrid[ind0] && vert3 == hexaNodeIDsGrid[ind1]) { // jj = nPoly-k. - a = e = nPolyConn; b = h = -1; n = 1; // kk = j. - } - - else if(vert0 == hexaNodeIDsGrid[ind6] && vert1 == hexaNodeIDsGrid[ind7] && // ii = nPoly-i. - vert2 == hexaNodeIDsGrid[ind4] && vert3 == hexaNodeIDsGrid[ind5]) { // jj = nPoly-j. - a = e = l = nPolyConn; b = g = o = -1; // kk = nPoly-k. - } - else if(vert0 == hexaNodeIDsGrid[ind6] && vert1 == hexaNodeIDsGrid[ind5] && // ii = nPoly-j. - vert2 == hexaNodeIDsGrid[ind4] && vert3 == hexaNodeIDsGrid[ind7]) { // jj = nPoly-i. - a = e = l = nPolyConn; c = f = o = -1; // kk = nPoly-k. - } - else if(vert0 == hexaNodeIDsGrid[ind6] && vert1 == hexaNodeIDsGrid[ind7] && // ii = nPoly-i. - vert2 == hexaNodeIDsGrid[ind3] && vert3 == hexaNodeIDsGrid[ind2]) { // jj = nPoly-k. - a = e = l = nPolyConn; b = h = n = -1; // kk = nPoly-j. - } - else if(vert0 == hexaNodeIDsGrid[ind6] && vert1 == hexaNodeIDsGrid[ind2] && // ii = nPoly-k. - vert2 == hexaNodeIDsGrid[ind3] && vert3 == hexaNodeIDsGrid[ind7]) { // jj = nPoly-i. - a = e = l = nPolyConn; d = f = n = -1; // kk = nPoly-j. - } - else if(vert0 == hexaNodeIDsGrid[ind6] && vert1 == hexaNodeIDsGrid[ind2] && // ii = nPoly-k. - vert2 == hexaNodeIDsGrid[ind1] && vert3 == hexaNodeIDsGrid[ind5]) { // jj = nPoly-j. - a = e = l = nPolyConn; d = g = m = -1; // kk = nPoly-i. - } - else if(vert0 == hexaNodeIDsGrid[ind6] && vert1 == hexaNodeIDsGrid[ind5] && // ii = nPoly-j. - vert2 == hexaNodeIDsGrid[ind1] && vert3 == hexaNodeIDsGrid[ind2]) { // jj = nPoly-k. - a = e = l = nPolyConn; c = h = m = -1; // kk = nPoly-i. - } - - else if(vert0 == hexaNodeIDsGrid[ind7] && vert1 == hexaNodeIDsGrid[ind4] && // ii = nPoly-j. - vert2 == hexaNodeIDsGrid[ind5] && vert3 == hexaNodeIDsGrid[ind6]) { // jj = i. - a = l = nPolyConn; c = o = -1; f = 1; // kk = nPoly-k. - } - else if(vert0 == hexaNodeIDsGrid[ind7] && vert1 == hexaNodeIDsGrid[ind6] && // ii = i. - vert2 == hexaNodeIDsGrid[ind5] && vert3 == hexaNodeIDsGrid[ind4]) { // jj = nPoly-j. - e = l = nPolyConn; g = o = -1; b = 1; // kk = nPoly-k. - } - else if(vert0 == hexaNodeIDsGrid[ind7] && vert1 == hexaNodeIDsGrid[ind4] && // ii = nPoly-j. - vert2 == hexaNodeIDsGrid[ind0] && vert3 == hexaNodeIDsGrid[ind3]) { // jj = nPoly-k. - a = e = nPolyConn; c = h = -1; m = 1; // kk = i. - } - else if(vert0 == hexaNodeIDsGrid[ind7] && vert1 == hexaNodeIDsGrid[ind3] && // ii = nPoly-k. - vert2 == hexaNodeIDsGrid[ind0] && vert3 == hexaNodeIDsGrid[ind4]) { // jj = nPoly-j. - a = e = nPolyConn; d = g = -1; m = 1; // kk = i. - } - else if(vert0 == hexaNodeIDsGrid[ind7] && vert1 == hexaNodeIDsGrid[ind6] && // ii = i. - vert2 == hexaNodeIDsGrid[ind2] && vert3 == hexaNodeIDsGrid[ind3]) { // jj = nPoly-k. - e = l = nPolyConn; h = n = -1; b = 1; // kk = nPoly-j. - } - else if(vert0 == hexaNodeIDsGrid[ind7] && vert1 == hexaNodeIDsGrid[ind3] && // ii = nPoly-k. - vert2 == hexaNodeIDsGrid[ind2] && vert3 == hexaNodeIDsGrid[ind6]) { // jj = i. - a = l = nPolyConn; d = n = -1; f = 1; // kk = nPoly-j. + if (vert0 == hexaNodeIDsGrid[ind0] && vert1 == hexaNodeIDsGrid[ind1] && // ii = i. + vert2 == hexaNodeIDsGrid[ind2] && vert3 == hexaNodeIDsGrid[ind3]) { // jj = j. + b = g = o = 1; // kk = k. + } else if (vert0 == hexaNodeIDsGrid[ind0] && vert1 == hexaNodeIDsGrid[ind3] && // ii = j. + vert2 == hexaNodeIDsGrid[ind2] && vert3 == hexaNodeIDsGrid[ind1]) { // jj = i. + c = f = o = 1; // kk = k. + } else if (vert0 == hexaNodeIDsGrid[ind0] && vert1 == hexaNodeIDsGrid[ind1] && // ii = i. + vert2 == hexaNodeIDsGrid[ind5] && vert3 == hexaNodeIDsGrid[ind4]) { // jj = k. + b = h = n = 1; // kk = j. + } else if (vert0 == hexaNodeIDsGrid[ind0] && vert1 == hexaNodeIDsGrid[ind4] && // ii = k. + vert2 == hexaNodeIDsGrid[ind5] && vert3 == hexaNodeIDsGrid[ind1]) { // jj = i. + d = f = n = 1; // kk = j. + } else if (vert0 == hexaNodeIDsGrid[ind0] && vert1 == hexaNodeIDsGrid[ind3] && // ii = j. + vert2 == hexaNodeIDsGrid[ind7] && vert3 == hexaNodeIDsGrid[ind4]) { // jj = k. + c = h = m = 1; // kk = i. + } else if (vert0 == hexaNodeIDsGrid[ind0] && vert1 == hexaNodeIDsGrid[ind4] && // ii = k. + vert2 == hexaNodeIDsGrid[ind7] && vert3 == hexaNodeIDsGrid[ind3]) { // jj = j. + d = g = m = 1; // kk = i. + } + + else if (vert0 == hexaNodeIDsGrid[ind1] && vert1 == hexaNodeIDsGrid[ind0] && // ii = nPoly-i. + vert2 == hexaNodeIDsGrid[ind3] && vert3 == hexaNodeIDsGrid[ind2]) { // jj = j. + a = nPolyConn; + b = -1; + g = o = 1; // kk = k. + } else if (vert0 == hexaNodeIDsGrid[ind1] && vert1 == hexaNodeIDsGrid[ind2] && // ii = j. + vert2 == hexaNodeIDsGrid[ind3] && vert3 == hexaNodeIDsGrid[ind0]) { // jj = nPoly-i. + e = nPolyConn; + f = -1; + c = o = 1; // kk = k. + } else if (vert0 == hexaNodeIDsGrid[ind1] && vert1 == hexaNodeIDsGrid[ind0] && // ii = nPoly-i. + vert2 == hexaNodeIDsGrid[ind4] && vert3 == hexaNodeIDsGrid[ind5]) { // jj = k. + a = nPolyConn; + b = -1; + h = n = 1; // kk = j. + } else if (vert0 == hexaNodeIDsGrid[ind1] && vert1 == hexaNodeIDsGrid[ind5] && // ii = k. + vert2 == hexaNodeIDsGrid[ind4] && vert3 == hexaNodeIDsGrid[ind0]) { // jj = nPoly-i. + e = nPolyConn; + f = -1; + d = n = 1; // kk = j. + } else if (vert0 == hexaNodeIDsGrid[ind1] && vert1 == hexaNodeIDsGrid[ind2] && // ii = j. + vert2 == hexaNodeIDsGrid[ind6] && vert3 == hexaNodeIDsGrid[ind5]) { // jj = k. + l = nPolyConn; + m = -1; + c = h = 1; // kk = nPoly-i. + } else if (vert0 == hexaNodeIDsGrid[ind1] && vert1 == hexaNodeIDsGrid[ind5] && // ii = k. + vert2 == hexaNodeIDsGrid[ind6] && vert3 == hexaNodeIDsGrid[ind2]) { // jj = j. + l = nPolyConn; + m = -1; + d = g = 1; // kk = nPoly-i. + } + + else if (vert0 == hexaNodeIDsGrid[ind2] && vert1 == hexaNodeIDsGrid[ind1] && // ii = nPoly-j. + vert2 == hexaNodeIDsGrid[ind0] && vert3 == hexaNodeIDsGrid[ind3]) { // jj = nPoly-i. + a = e = nPolyConn; + c = f = -1; + o = 1; // kk = k. + } else if (vert0 == hexaNodeIDsGrid[ind2] && vert1 == hexaNodeIDsGrid[ind3] && // ii = nPoly-i. + vert2 == hexaNodeIDsGrid[ind0] && vert3 == hexaNodeIDsGrid[ind1]) { // jj = nPoly-j. + a = e = nPolyConn; + b = g = -1; + o = 1; // kk = k. + } else if (vert0 == hexaNodeIDsGrid[ind2] && vert1 == hexaNodeIDsGrid[ind1] && // ii = nPoly-j. + vert2 == hexaNodeIDsGrid[ind5] && vert3 == hexaNodeIDsGrid[ind6]) { // jj = k. + a = l = nPolyConn; + c = m = -1; + h = 1; // kk = nPoly-i. + } else if (vert0 == hexaNodeIDsGrid[ind2] && vert1 == hexaNodeIDsGrid[ind6] && // ii = k. + vert2 == hexaNodeIDsGrid[ind5] && vert3 == hexaNodeIDsGrid[ind1]) { // jj = nPoly-j. + e = l = nPolyConn; + g = m = -1; + d = 1; // kk = nPoly-i. + } else if (vert0 == hexaNodeIDsGrid[ind2] && vert1 == hexaNodeIDsGrid[ind3] && // ii = nPoly-i. + vert2 == hexaNodeIDsGrid[ind7] && vert3 == hexaNodeIDsGrid[ind6]) { // jj = k. + a = l = nPolyConn; + b = n = -1; + h = 1; // kk = nPoly-j. + } else if (vert0 == hexaNodeIDsGrid[ind2] && vert1 == hexaNodeIDsGrid[ind6] && // ii = k. + vert2 == hexaNodeIDsGrid[ind7] && vert3 == hexaNodeIDsGrid[ind3]) { // jj = nPoly-i. + e = l = nPolyConn; + f = n = -1; + d = 1; // kk = nPoly-j. + } + + else if (vert0 == hexaNodeIDsGrid[ind3] && vert1 == hexaNodeIDsGrid[ind0] && // ii = nPoly-j. + vert2 == hexaNodeIDsGrid[ind1] && vert3 == hexaNodeIDsGrid[ind2]) { // jj = i. + a = nPolyConn; + c = -1; + f = o = 1; // kk = k. + } else if (vert0 == hexaNodeIDsGrid[ind3] && vert1 == hexaNodeIDsGrid[ind2] && // ii = i. + vert2 == hexaNodeIDsGrid[ind1] && vert3 == hexaNodeIDsGrid[ind0]) { // jj = nPoly-j. + e = nPolyConn; + g = -1; + b = o = 1; // kk = k. + } else if (vert0 == hexaNodeIDsGrid[ind3] && vert1 == hexaNodeIDsGrid[ind0] && // ii = nPoly-j. + vert2 == hexaNodeIDsGrid[ind4] && vert3 == hexaNodeIDsGrid[ind7]) { // jj = k. + a = nPolyConn; + c = -1; + h = m = 1; // kk = i. + } else if (vert0 == hexaNodeIDsGrid[ind3] && vert1 == hexaNodeIDsGrid[ind7] && // ii = k. + vert2 == hexaNodeIDsGrid[ind4] && vert3 == hexaNodeIDsGrid[ind0]) { // jj = nPoly-j. + e = nPolyConn; + g = -1; + d = m = 1; // kk = i. + } else if (vert0 == hexaNodeIDsGrid[ind3] && vert1 == hexaNodeIDsGrid[ind2] && // ii = i. + vert2 == hexaNodeIDsGrid[ind6] && vert3 == hexaNodeIDsGrid[ind7]) { // jj = k. + l = nPolyConn; + n = -1; + b = h = 1; // kk = nPoly-j. + } else if (vert0 == hexaNodeIDsGrid[ind3] && vert1 == hexaNodeIDsGrid[ind7] && // ii = k. + vert2 == hexaNodeIDsGrid[ind6] && vert3 == hexaNodeIDsGrid[ind2]) { // jj = i. + l = nPolyConn; + n = -1; + d = f = 1; // kk = nPoly-j. + } + + else if (vert0 == hexaNodeIDsGrid[ind4] && vert1 == hexaNodeIDsGrid[ind5] && // ii = i. + vert2 == hexaNodeIDsGrid[ind6] && vert3 == hexaNodeIDsGrid[ind7]) { // jj = j. + l = nPolyConn; + o = -1; + b = g = 1; // kk = nPoly-k. + } else if (vert0 == hexaNodeIDsGrid[ind4] && vert1 == hexaNodeIDsGrid[ind7] && // ii = j. + vert2 == hexaNodeIDsGrid[ind6] && vert3 == hexaNodeIDsGrid[ind5]) { // jj = i. + l = nPolyConn; + o = -1; + c = f = 1; // kk = nPoly-k. + } else if (vert0 == hexaNodeIDsGrid[ind4] && vert1 == hexaNodeIDsGrid[ind5] && // ii = i. + vert2 == hexaNodeIDsGrid[ind1] && vert3 == hexaNodeIDsGrid[ind0]) { // jj = nPoly-k. + e = nPolyConn; + h = -1; + b = n = 1; // kk = j. + } else if (vert0 == hexaNodeIDsGrid[ind4] && vert1 == hexaNodeIDsGrid[ind0] && // ii = nPoly-k. + vert2 == hexaNodeIDsGrid[ind1] && vert3 == hexaNodeIDsGrid[ind5]) { // jj = i. + a = nPolyConn; + d = -1; + f = n = 1; // kk = j. + } else if (vert0 == hexaNodeIDsGrid[ind4] && vert1 == hexaNodeIDsGrid[ind7] && // ii = j. + vert2 == hexaNodeIDsGrid[ind3] && vert3 == hexaNodeIDsGrid[ind0]) { // jj = nPoly-k. + e = nPolyConn; + h = -1; + c = m = 1; // kk = i. + } else if (vert0 == hexaNodeIDsGrid[ind4] && vert1 == hexaNodeIDsGrid[ind0] && // ii = nPoly-k. + vert2 == hexaNodeIDsGrid[ind3] && vert3 == hexaNodeIDsGrid[ind7]) { // jj = j. + a = nPolyConn; + d = -1; + g = m = 1; // kk = i. + } + + else if (vert0 == hexaNodeIDsGrid[ind5] && vert1 == hexaNodeIDsGrid[ind6] && // ii = j. + vert2 == hexaNodeIDsGrid[ind7] && vert3 == hexaNodeIDsGrid[ind4]) { // jj = nPoly-i. + e = l = nPolyConn; + f = o = -1; + c = 1; // kk = nPoly-k. + } else if (vert0 == hexaNodeIDsGrid[ind5] && vert1 == hexaNodeIDsGrid[ind4] && // ii = nPoly-i. + vert2 == hexaNodeIDsGrid[ind7] && vert3 == hexaNodeIDsGrid[ind6]) { // jj = j. + a = l = nPolyConn; + b = o = -1; + g = 1; // kk = nPoly-k. + } else if (vert0 == hexaNodeIDsGrid[ind5] && vert1 == hexaNodeIDsGrid[ind6] && // ii = j. + vert2 == hexaNodeIDsGrid[ind2] && vert3 == hexaNodeIDsGrid[ind1]) { // jj = nPoly-k. + e = l = nPolyConn; + h = m = -1; + c = 1; // kk = nPoly-i. + } else if (vert0 == hexaNodeIDsGrid[ind5] && vert1 == hexaNodeIDsGrid[ind1] && // ii = nPoly-k. + vert2 == hexaNodeIDsGrid[ind2] && vert3 == hexaNodeIDsGrid[ind6]) { // jj = j. + a = l = nPolyConn; + d = m = -1; + g = 1; // kk = nPoly-i. + } else if (vert0 == hexaNodeIDsGrid[ind5] && vert1 == hexaNodeIDsGrid[ind1] && // ii = nPoly-k. + vert2 == hexaNodeIDsGrid[ind0] && vert3 == hexaNodeIDsGrid[ind4]) { // jj = nPoly-i. + a = e = nPolyConn; + d = f = -1; + n = 1; // kk = j. + } else if (vert0 == hexaNodeIDsGrid[ind5] && vert1 == hexaNodeIDsGrid[ind4] && // ii = nPoly-i. + vert2 == hexaNodeIDsGrid[ind0] && vert3 == hexaNodeIDsGrid[ind1]) { // jj = nPoly-k. + a = e = nPolyConn; + b = h = -1; + n = 1; // kk = j. + } + + else if (vert0 == hexaNodeIDsGrid[ind6] && vert1 == hexaNodeIDsGrid[ind7] && // ii = nPoly-i. + vert2 == hexaNodeIDsGrid[ind4] && vert3 == hexaNodeIDsGrid[ind5]) { // jj = nPoly-j. + a = e = l = nPolyConn; + b = g = o = -1; // kk = nPoly-k. + } else if (vert0 == hexaNodeIDsGrid[ind6] && vert1 == hexaNodeIDsGrid[ind5] && // ii = nPoly-j. + vert2 == hexaNodeIDsGrid[ind4] && vert3 == hexaNodeIDsGrid[ind7]) { // jj = nPoly-i. + a = e = l = nPolyConn; + c = f = o = -1; // kk = nPoly-k. + } else if (vert0 == hexaNodeIDsGrid[ind6] && vert1 == hexaNodeIDsGrid[ind7] && // ii = nPoly-i. + vert2 == hexaNodeIDsGrid[ind3] && vert3 == hexaNodeIDsGrid[ind2]) { // jj = nPoly-k. + a = e = l = nPolyConn; + b = h = n = -1; // kk = nPoly-j. + } else if (vert0 == hexaNodeIDsGrid[ind6] && vert1 == hexaNodeIDsGrid[ind2] && // ii = nPoly-k. + vert2 == hexaNodeIDsGrid[ind3] && vert3 == hexaNodeIDsGrid[ind7]) { // jj = nPoly-i. + a = e = l = nPolyConn; + d = f = n = -1; // kk = nPoly-j. + } else if (vert0 == hexaNodeIDsGrid[ind6] && vert1 == hexaNodeIDsGrid[ind2] && // ii = nPoly-k. + vert2 == hexaNodeIDsGrid[ind1] && vert3 == hexaNodeIDsGrid[ind5]) { // jj = nPoly-j. + a = e = l = nPolyConn; + d = g = m = -1; // kk = nPoly-i. + } else if (vert0 == hexaNodeIDsGrid[ind6] && vert1 == hexaNodeIDsGrid[ind5] && // ii = nPoly-j. + vert2 == hexaNodeIDsGrid[ind1] && vert3 == hexaNodeIDsGrid[ind2]) { // jj = nPoly-k. + a = e = l = nPolyConn; + c = h = m = -1; // kk = nPoly-i. + } + + else if (vert0 == hexaNodeIDsGrid[ind7] && vert1 == hexaNodeIDsGrid[ind4] && // ii = nPoly-j. + vert2 == hexaNodeIDsGrid[ind5] && vert3 == hexaNodeIDsGrid[ind6]) { // jj = i. + a = l = nPolyConn; + c = o = -1; + f = 1; // kk = nPoly-k. + } else if (vert0 == hexaNodeIDsGrid[ind7] && vert1 == hexaNodeIDsGrid[ind6] && // ii = i. + vert2 == hexaNodeIDsGrid[ind5] && vert3 == hexaNodeIDsGrid[ind4]) { // jj = nPoly-j. + e = l = nPolyConn; + g = o = -1; + b = 1; // kk = nPoly-k. + } else if (vert0 == hexaNodeIDsGrid[ind7] && vert1 == hexaNodeIDsGrid[ind4] && // ii = nPoly-j. + vert2 == hexaNodeIDsGrid[ind0] && vert3 == hexaNodeIDsGrid[ind3]) { // jj = nPoly-k. + a = e = nPolyConn; + c = h = -1; + m = 1; // kk = i. + } else if (vert0 == hexaNodeIDsGrid[ind7] && vert1 == hexaNodeIDsGrid[ind3] && // ii = nPoly-k. + vert2 == hexaNodeIDsGrid[ind0] && vert3 == hexaNodeIDsGrid[ind4]) { // jj = nPoly-j. + a = e = nPolyConn; + d = g = -1; + m = 1; // kk = i. + } else if (vert0 == hexaNodeIDsGrid[ind7] && vert1 == hexaNodeIDsGrid[ind6] && // ii = i. + vert2 == hexaNodeIDsGrid[ind2] && vert3 == hexaNodeIDsGrid[ind3]) { // jj = nPoly-k. + e = l = nPolyConn; + h = n = -1; + b = 1; // kk = nPoly-j. + } else if (vert0 == hexaNodeIDsGrid[ind7] && vert1 == hexaNodeIDsGrid[ind3] && // ii = nPoly-k. + vert2 == hexaNodeIDsGrid[ind2] && vert3 == hexaNodeIDsGrid[ind6]) { // jj = i. + a = l = nPolyConn; + d = n = -1; + f = 1; // kk = nPoly-j. } else { @@ -4206,23 +3920,21 @@ void CMeshFEM_DG::CreateConnectivitiesQuadrilateralAdjacentHexahedron( } /*--- If non-matching vertices have been found, terminate with an error message. ---*/ - if( verticesDontMatch ) - SU2_MPI::Error("Corner vertices do not match. This should not happen.", CURRENT_FUNCTION); + if (verticesDontMatch) SU2_MPI::Error("Corner vertices do not match. This should not happen.", CURRENT_FUNCTION); /*--- Loop over the DOFs of the original hexahedron to create the connectivity of the hexahedron that corresponds to the new numbering. ---*/ - const unsigned short nn2 = (nPolyConn+1)*(nPolyConn+1); + const unsigned short nn2 = (nPolyConn + 1) * (nPolyConn + 1); unsigned short ind = 0; - for(unsigned short k=0; k<=nPolyConn; ++k) { - for(unsigned short j=0; j<=nPolyConn; ++j) { - for(unsigned short i=0; i<=nPolyConn; ++i, ++ind) { - + for (unsigned short k = 0; k <= nPolyConn; ++k) { + for (unsigned short j = 0; j <= nPolyConn; ++j) { + for (unsigned short i = 0; i <= nPolyConn; ++i, ++ind) { /*--- Determine the ii, jj and kk indices of the new numbering, convert it to a 1D index and shore the modified index in modConnHexa. ---*/ - unsigned short ii = a + i*b + j*c + k*d; - unsigned short jj = e + i*f + j*g + k*h; - unsigned short kk = l + i*m + j*n + k*o; - unsigned short iind = kk*nn2 + jj*(nPolyConn+1) + ii; + unsigned short ii = a + i * b + j * c + k * d; + unsigned short jj = e + i * f + j * g + k * h; + unsigned short kk = l + i * m + j * n + k * o; + unsigned short iind = kk * nn2 + jj * (nPolyConn + 1) + ii; modConnHexa[iind] = connHexa[ind]; } @@ -4232,25 +3944,18 @@ void CMeshFEM_DG::CreateConnectivitiesQuadrilateralAdjacentHexahedron( /*--- The quad corresponds to face 0 of the hexahedron. Hence the first nn2 entries in modConnHexa are the DOFs of the quad. Copy these entries from modConnHexa. ---*/ - for(unsigned short i=0; i &prismNodeIDsGrid, - const unsigned short nPolyConn, - const unsigned long *connPrism, - bool &swapFaceInElement, - unsigned long *modConnQuad, - unsigned long *modConnPrism) { - + const unsigned long* cornerPointsQuad, const unsigned short nPolyGrid, + const vector& prismNodeIDsGrid, const unsigned short nPolyConn, const unsigned long* connPrism, + bool& swapFaceInElement, unsigned long* modConnQuad, unsigned long* modConnPrism) { /* Determine the indices of the six corner points of the prism. */ const unsigned short ind0 = 0; const unsigned short ind1 = nPolyGrid; - const unsigned short ind2 = (nPolyGrid+1)*(nPolyGrid+2)/2 -1; - const unsigned short ind3 = (nPolyGrid+1)*(nPolyGrid+2)*nPolyGrid/2; + const unsigned short ind2 = (nPolyGrid + 1) * (nPolyGrid + 2) / 2 - 1; + const unsigned short ind3 = (nPolyGrid + 1) * (nPolyGrid + 2) * nPolyGrid / 2; const unsigned short ind4 = ind1 + ind3; const unsigned short ind5 = ind2 + ind3; @@ -4276,106 +3981,152 @@ void CMeshFEM_DG::CreateConnectivitiesQuadrilateralAdjacentPrism( signed short a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0; bool verticesDontMatch = false; - if(vert0 == prismNodeIDsGrid[ind0] && vert1 == prismNodeIDsGrid[ind1] && // ii = i. - vert2 == prismNodeIDsGrid[ind4] && vert3 == prismNodeIDsGrid[ind3]) { // jj = j. - b = f = h = 1; swapFaceInElement = false; // kk = k. - } - else if(vert0 == prismNodeIDsGrid[ind0] && vert1 == prismNodeIDsGrid[ind3] && // ii = i. - vert2 == prismNodeIDsGrid[ind4] && vert3 == prismNodeIDsGrid[ind1]) { // jj = j. - b = f = h = 1; swapFaceInElement = true; // kk = k. Plus swap. - } - else if(vert0 == prismNodeIDsGrid[ind0] && vert1 == prismNodeIDsGrid[ind2] && // ii = j. - vert2 == prismNodeIDsGrid[ind5] && vert3 == prismNodeIDsGrid[ind3]) { // jj = i. - c = e = h = 1; swapFaceInElement = false; // kk = k. - } - else if(vert0 == prismNodeIDsGrid[ind0] && vert1 == prismNodeIDsGrid[ind3] && // ii = j. - vert2 == prismNodeIDsGrid[ind5] && vert3 == prismNodeIDsGrid[ind2]) { // jj = i. - c = e = h = 1; swapFaceInElement = true; // kk = k. Plus swap. - } - - else if(vert0 == prismNodeIDsGrid[ind1] && vert1 == prismNodeIDsGrid[ind0] && // ii = nPoly-i-j. - vert2 == prismNodeIDsGrid[ind3] && vert3 == prismNodeIDsGrid[ind4]) { // jj = j. - a = nPolyConn; b = c = -1; f = h = 1; swapFaceInElement = false; // kk = k. - } - else if(vert0 == prismNodeIDsGrid[ind1] && vert1 == prismNodeIDsGrid[ind4] && // ii = nPoly-i-j. - vert2 == prismNodeIDsGrid[ind3] && vert3 == prismNodeIDsGrid[ind0]) { // jj = j. - a = nPolyConn; b = c = -1; f = h = 1; swapFaceInElement = true; // kk = k. Plus swap. - } - else if(vert0 == prismNodeIDsGrid[ind1] && vert1 == prismNodeIDsGrid[ind2] && // ii = j. - vert2 == prismNodeIDsGrid[ind5] && vert3 == prismNodeIDsGrid[ind4]) { // jj = nPoly-i-j. - d = nPolyConn; e = f = -1; c = h = 1; swapFaceInElement = false; // kk = k. - } - else if(vert0 == prismNodeIDsGrid[ind1] && vert1 == prismNodeIDsGrid[ind4] && // ii = j. - vert2 == prismNodeIDsGrid[ind5] && vert3 == prismNodeIDsGrid[ind2]) { // jj = nPoly-i-j. - d = nPolyConn; e = f = -1; c = h = 1; swapFaceInElement = true; // kk = k. Plus swap. - } - - else if(vert0 == prismNodeIDsGrid[ind2] && vert1 == prismNodeIDsGrid[ind0] && // ii = nPoly-i-j. - vert2 == prismNodeIDsGrid[ind3] && vert3 == prismNodeIDsGrid[ind5]) { // jj = i. - a = nPolyConn; b = c = -1; e = h = 1; swapFaceInElement = false; // kk = k. - } - else if(vert0 == prismNodeIDsGrid[ind2] && vert1 == prismNodeIDsGrid[ind5] && // ii = nPoly-i-j. - vert2 == prismNodeIDsGrid[ind3] && vert3 == prismNodeIDsGrid[ind0]) { // jj = i. - a = nPolyConn; b = c = -1; e = h = 1; swapFaceInElement = true; // kk = k. Plus swap. - } - else if(vert0 == prismNodeIDsGrid[ind2] && vert1 == prismNodeIDsGrid[ind1] && // ii = i. - vert2 == prismNodeIDsGrid[ind4] && vert3 == prismNodeIDsGrid[ind5]) { // jj = nPoly-i-j. - d = nPolyConn; e = f = -1; b = h = 1; swapFaceInElement = false; // kk = k. - } - else if(vert0 == prismNodeIDsGrid[ind2] && vert1 == prismNodeIDsGrid[ind5] && // ii = i. - vert2 == prismNodeIDsGrid[ind4] && vert3 == prismNodeIDsGrid[ind1]) { // jj = nPoly-i-j. - d = nPolyConn; e = f = -1; b = h = 1; swapFaceInElement = true; // kk = k. Plus swap. - } - - else if(vert0 == prismNodeIDsGrid[ind3] && vert1 == prismNodeIDsGrid[ind4] && // ii = i. - vert2 == prismNodeIDsGrid[ind1] && vert3 == prismNodeIDsGrid[ind0]) { // jj = j. - g = nPolyConn; b = f = 1; h = -1; swapFaceInElement = false; // kk = nPoly-k. - } - else if(vert0 == prismNodeIDsGrid[ind3] && vert1 == prismNodeIDsGrid[ind0] && // ii = i. - vert2 == prismNodeIDsGrid[ind1] && vert3 == prismNodeIDsGrid[ind4]) { // jj = j. - g = nPolyConn; b = f = 1; h = -1; swapFaceInElement = true; // kk = nPoly-k. Plus swap. - } - else if(vert0 == prismNodeIDsGrid[ind3] && vert1 == prismNodeIDsGrid[ind5] && // ii = j. - vert2 == prismNodeIDsGrid[ind2] && vert3 == prismNodeIDsGrid[ind0]) { // jj = i. - g = nPolyConn; c = e = 1; h = -1; swapFaceInElement = false; // kk = nPoly-k. - } - else if(vert0 == prismNodeIDsGrid[ind3] && vert1 == prismNodeIDsGrid[ind0] && // ii = j. - vert2 == prismNodeIDsGrid[ind2] && vert3 == prismNodeIDsGrid[ind5]) { // jj = i. - g = nPolyConn; c = e = 1; h = -1; swapFaceInElement = true; // kk = nPoly-k. Plus swap. - } - - else if(vert0 == prismNodeIDsGrid[ind4] && vert1 == prismNodeIDsGrid[ind3] && // ii = nPoly-i-j. - vert2 == prismNodeIDsGrid[ind0] && vert3 == prismNodeIDsGrid[ind1]) { // jj = j. - a = g = nPolyConn; b = c = h = -1; f = 1; swapFaceInElement = false; // kk = nPoly-k. - } - else if(vert0 == prismNodeIDsGrid[ind4] && vert1 == prismNodeIDsGrid[ind1] && // ii = nPoly-i-j. - vert2 == prismNodeIDsGrid[ind0] && vert3 == prismNodeIDsGrid[ind3]) { // jj = j. - a = g = nPolyConn; b = c = h = -1; f = 1; swapFaceInElement = true; // kk = nPoly-k. Plus swap. - } - else if(vert0 == prismNodeIDsGrid[ind4] && vert1 == prismNodeIDsGrid[ind5] && // ii = j. - vert2 == prismNodeIDsGrid[ind2] && vert3 == prismNodeIDsGrid[ind1]) { // jj = nPoly-i-j. - d = g = nPolyConn; e = f = h = -1; c = 1; swapFaceInElement = false; // kk = nPoly-k. - } - else if(vert0 == prismNodeIDsGrid[ind4] && vert1 == prismNodeIDsGrid[ind1] && // ii = j. - vert2 == prismNodeIDsGrid[ind2] && vert3 == prismNodeIDsGrid[ind5]) { // jj = nPoly-i-j. - d = g = nPolyConn; e = f = h = -1; c = 1; swapFaceInElement = true; // kk = nPoly-k. Plus swap. - } - - else if(vert0 == prismNodeIDsGrid[ind5] && vert1 == prismNodeIDsGrid[ind3] && // ii = nPoly-i-j. - vert2 == prismNodeIDsGrid[ind0] && vert3 == prismNodeIDsGrid[ind2]) { // jj = i. - a = g = nPolyConn; b = c = h = -1; e = 1; swapFaceInElement = false; // kk = nPoly-k. - } - else if(vert0 == prismNodeIDsGrid[ind5] && vert1 == prismNodeIDsGrid[ind2] && // ii = nPoly-i-j. - vert2 == prismNodeIDsGrid[ind0] && vert3 == prismNodeIDsGrid[ind3]) { // jj = i. - a = g = nPolyConn; b = c = h = -1; e = 1; swapFaceInElement = true; // kk = nPoly-k. Plus swap. - } - else if(vert0 == prismNodeIDsGrid[ind5] && vert1 == prismNodeIDsGrid[ind4] && // ii = i. - vert2 == prismNodeIDsGrid[ind1] && vert3 == prismNodeIDsGrid[ind2]) { // jj = nPoly-i-j. - d = g = nPolyConn; e = f = h = -1; b = 1; swapFaceInElement = false; // kk = nPoly-k. - } - else if(vert0 == prismNodeIDsGrid[ind5] && vert1 == prismNodeIDsGrid[ind2] && // ii = i. - vert2 == prismNodeIDsGrid[ind1] && vert3 == prismNodeIDsGrid[ind4]) { // jj = nPoly-i-j. - d = g = nPolyConn; e = f = h = -1; b = 1; swapFaceInElement = true; // kk = nPoly-k. Plus swap. + if (vert0 == prismNodeIDsGrid[ind0] && vert1 == prismNodeIDsGrid[ind1] && // ii = i. + vert2 == prismNodeIDsGrid[ind4] && vert3 == prismNodeIDsGrid[ind3]) { // jj = j. + b = f = h = 1; + swapFaceInElement = false; // kk = k. + } else if (vert0 == prismNodeIDsGrid[ind0] && vert1 == prismNodeIDsGrid[ind3] && // ii = i. + vert2 == prismNodeIDsGrid[ind4] && vert3 == prismNodeIDsGrid[ind1]) { // jj = j. + b = f = h = 1; + swapFaceInElement = true; // kk = k. Plus swap. + } else if (vert0 == prismNodeIDsGrid[ind0] && vert1 == prismNodeIDsGrid[ind2] && // ii = j. + vert2 == prismNodeIDsGrid[ind5] && vert3 == prismNodeIDsGrid[ind3]) { // jj = i. + c = e = h = 1; + swapFaceInElement = false; // kk = k. + } else if (vert0 == prismNodeIDsGrid[ind0] && vert1 == prismNodeIDsGrid[ind3] && // ii = j. + vert2 == prismNodeIDsGrid[ind5] && vert3 == prismNodeIDsGrid[ind2]) { // jj = i. + c = e = h = 1; + swapFaceInElement = true; // kk = k. Plus swap. + } + + else if (vert0 == prismNodeIDsGrid[ind1] && vert1 == prismNodeIDsGrid[ind0] && // ii = nPoly-i-j. + vert2 == prismNodeIDsGrid[ind3] && vert3 == prismNodeIDsGrid[ind4]) { // jj = j. + a = nPolyConn; + b = c = -1; + f = h = 1; + swapFaceInElement = false; // kk = k. + } else if (vert0 == prismNodeIDsGrid[ind1] && vert1 == prismNodeIDsGrid[ind4] && // ii = nPoly-i-j. + vert2 == prismNodeIDsGrid[ind3] && vert3 == prismNodeIDsGrid[ind0]) { // jj = j. + a = nPolyConn; + b = c = -1; + f = h = 1; + swapFaceInElement = true; // kk = k. Plus swap. + } else if (vert0 == prismNodeIDsGrid[ind1] && vert1 == prismNodeIDsGrid[ind2] && // ii = j. + vert2 == prismNodeIDsGrid[ind5] && vert3 == prismNodeIDsGrid[ind4]) { // jj = nPoly-i-j. + d = nPolyConn; + e = f = -1; + c = h = 1; + swapFaceInElement = false; // kk = k. + } else if (vert0 == prismNodeIDsGrid[ind1] && vert1 == prismNodeIDsGrid[ind4] && // ii = j. + vert2 == prismNodeIDsGrid[ind5] && vert3 == prismNodeIDsGrid[ind2]) { // jj = nPoly-i-j. + d = nPolyConn; + e = f = -1; + c = h = 1; + swapFaceInElement = true; // kk = k. Plus swap. + } + + else if (vert0 == prismNodeIDsGrid[ind2] && vert1 == prismNodeIDsGrid[ind0] && // ii = nPoly-i-j. + vert2 == prismNodeIDsGrid[ind3] && vert3 == prismNodeIDsGrid[ind5]) { // jj = i. + a = nPolyConn; + b = c = -1; + e = h = 1; + swapFaceInElement = false; // kk = k. + } else if (vert0 == prismNodeIDsGrid[ind2] && vert1 == prismNodeIDsGrid[ind5] && // ii = nPoly-i-j. + vert2 == prismNodeIDsGrid[ind3] && vert3 == prismNodeIDsGrid[ind0]) { // jj = i. + a = nPolyConn; + b = c = -1; + e = h = 1; + swapFaceInElement = true; // kk = k. Plus swap. + } else if (vert0 == prismNodeIDsGrid[ind2] && vert1 == prismNodeIDsGrid[ind1] && // ii = i. + vert2 == prismNodeIDsGrid[ind4] && vert3 == prismNodeIDsGrid[ind5]) { // jj = nPoly-i-j. + d = nPolyConn; + e = f = -1; + b = h = 1; + swapFaceInElement = false; // kk = k. + } else if (vert0 == prismNodeIDsGrid[ind2] && vert1 == prismNodeIDsGrid[ind5] && // ii = i. + vert2 == prismNodeIDsGrid[ind4] && vert3 == prismNodeIDsGrid[ind1]) { // jj = nPoly-i-j. + d = nPolyConn; + e = f = -1; + b = h = 1; + swapFaceInElement = true; // kk = k. Plus swap. + } + + else if (vert0 == prismNodeIDsGrid[ind3] && vert1 == prismNodeIDsGrid[ind4] && // ii = i. + vert2 == prismNodeIDsGrid[ind1] && vert3 == prismNodeIDsGrid[ind0]) { // jj = j. + g = nPolyConn; + b = f = 1; + h = -1; + swapFaceInElement = false; // kk = nPoly-k. + } else if (vert0 == prismNodeIDsGrid[ind3] && vert1 == prismNodeIDsGrid[ind0] && // ii = i. + vert2 == prismNodeIDsGrid[ind1] && vert3 == prismNodeIDsGrid[ind4]) { // jj = j. + g = nPolyConn; + b = f = 1; + h = -1; + swapFaceInElement = true; // kk = nPoly-k. Plus swap. + } else if (vert0 == prismNodeIDsGrid[ind3] && vert1 == prismNodeIDsGrid[ind5] && // ii = j. + vert2 == prismNodeIDsGrid[ind2] && vert3 == prismNodeIDsGrid[ind0]) { // jj = i. + g = nPolyConn; + c = e = 1; + h = -1; + swapFaceInElement = false; // kk = nPoly-k. + } else if (vert0 == prismNodeIDsGrid[ind3] && vert1 == prismNodeIDsGrid[ind0] && // ii = j. + vert2 == prismNodeIDsGrid[ind2] && vert3 == prismNodeIDsGrid[ind5]) { // jj = i. + g = nPolyConn; + c = e = 1; + h = -1; + swapFaceInElement = true; // kk = nPoly-k. Plus swap. + } + + else if (vert0 == prismNodeIDsGrid[ind4] && vert1 == prismNodeIDsGrid[ind3] && // ii = nPoly-i-j. + vert2 == prismNodeIDsGrid[ind0] && vert3 == prismNodeIDsGrid[ind1]) { // jj = j. + a = g = nPolyConn; + b = c = h = -1; + f = 1; + swapFaceInElement = false; // kk = nPoly-k. + } else if (vert0 == prismNodeIDsGrid[ind4] && vert1 == prismNodeIDsGrid[ind1] && // ii = nPoly-i-j. + vert2 == prismNodeIDsGrid[ind0] && vert3 == prismNodeIDsGrid[ind3]) { // jj = j. + a = g = nPolyConn; + b = c = h = -1; + f = 1; + swapFaceInElement = true; // kk = nPoly-k. Plus swap. + } else if (vert0 == prismNodeIDsGrid[ind4] && vert1 == prismNodeIDsGrid[ind5] && // ii = j. + vert2 == prismNodeIDsGrid[ind2] && vert3 == prismNodeIDsGrid[ind1]) { // jj = nPoly-i-j. + d = g = nPolyConn; + e = f = h = -1; + c = 1; + swapFaceInElement = false; // kk = nPoly-k. + } else if (vert0 == prismNodeIDsGrid[ind4] && vert1 == prismNodeIDsGrid[ind1] && // ii = j. + vert2 == prismNodeIDsGrid[ind2] && vert3 == prismNodeIDsGrid[ind5]) { // jj = nPoly-i-j. + d = g = nPolyConn; + e = f = h = -1; + c = 1; + swapFaceInElement = true; // kk = nPoly-k. Plus swap. + } + + else if (vert0 == prismNodeIDsGrid[ind5] && vert1 == prismNodeIDsGrid[ind3] && // ii = nPoly-i-j. + vert2 == prismNodeIDsGrid[ind0] && vert3 == prismNodeIDsGrid[ind2]) { // jj = i. + a = g = nPolyConn; + b = c = h = -1; + e = 1; + swapFaceInElement = false; // kk = nPoly-k. + } else if (vert0 == prismNodeIDsGrid[ind5] && vert1 == prismNodeIDsGrid[ind2] && // ii = nPoly-i-j. + vert2 == prismNodeIDsGrid[ind0] && vert3 == prismNodeIDsGrid[ind3]) { // jj = i. + a = g = nPolyConn; + b = c = h = -1; + e = 1; + swapFaceInElement = true; // kk = nPoly-k. Plus swap. + } else if (vert0 == prismNodeIDsGrid[ind5] && vert1 == prismNodeIDsGrid[ind4] && // ii = i. + vert2 == prismNodeIDsGrid[ind1] && vert3 == prismNodeIDsGrid[ind2]) { // jj = nPoly-i-j. + d = g = nPolyConn; + e = f = h = -1; + b = 1; + swapFaceInElement = false; // kk = nPoly-k. + } else if (vert0 == prismNodeIDsGrid[ind5] && vert1 == prismNodeIDsGrid[ind2] && // ii = i. + vert2 == prismNodeIDsGrid[ind1] && vert3 == prismNodeIDsGrid[ind4]) { // jj = nPoly-i-j. + d = g = nPolyConn; + e = f = h = -1; + b = 1; + swapFaceInElement = true; // kk = nPoly-k. Plus swap. } else { @@ -4383,24 +4134,22 @@ void CMeshFEM_DG::CreateConnectivitiesQuadrilateralAdjacentPrism( } /*--- If non-matching vertices have been found, terminate with an error message. ---*/ - if( verticesDontMatch ) - SU2_MPI::Error("Corner vertices do not match. This should not happen.", CURRENT_FUNCTION); + if (verticesDontMatch) SU2_MPI::Error("Corner vertices do not match. This should not happen.", CURRENT_FUNCTION); /*--- Loop over the DOFs of the original prism to create the connectivity of the prism that corresponds to the new numbering. ---*/ - const unsigned short kOff = (nPolyConn+1)*(nPolyConn+2)/2; + const unsigned short kOff = (nPolyConn + 1) * (nPolyConn + 2) / 2; unsigned short ind = 0; - for(unsigned short k=0; k<=nPolyConn; ++k) { - for(unsigned short j=0; j<=nPolyConn; ++j) { + for (unsigned short k = 0; k <= nPolyConn; ++k) { + for (unsigned short j = 0; j <= nPolyConn; ++j) { unsigned short uppBoundI = nPolyConn - j; - for(unsigned short i=0; i<=uppBoundI; ++i, ++ind) { - + for (unsigned short i = 0; i <= uppBoundI; ++i, ++ind) { /*--- Determine the ii, jj and kk indices of the new numbering, convert it to a 1D index and shore the modified index in modConnPrism. ---*/ - unsigned short ii = a + i*b + j*c; - unsigned short jj = d + i*e + j*f; - unsigned short kk = g + h*k; - unsigned short iind = kk*kOff + jj*(nPolyConn+1) + ii - jj*(jj-1)/2; + unsigned short ii = a + i * b + j * c; + unsigned short jj = d + i * e + j * f; + unsigned short kk = g + h * k; + unsigned short iind = kk * kOff + jj * (nPolyConn + 1) + ii - jj * (jj - 1) / 2; modConnPrism[iind] = connPrism[ind]; } @@ -4408,49 +4157,42 @@ void CMeshFEM_DG::CreateConnectivitiesQuadrilateralAdjacentPrism( } /*--- Determine the connectivity of the quadrilateral face. ---*/ - if( swapFaceInElement ) { - + if (swapFaceInElement) { /*--- The parametric coordinates r and s of the quad must be swapped w.r.t. to the parametric coordinates of the face of the prism. This means that the coordinate r of the quad runs from the base triangle to the top triangle of the prism. This corresponds to the k-direction of the prism. Hence the s-direction of the quad corresponds to the i-direction of the prism. ---*/ - for(unsigned short k=0; k<=nPolyConn; ++k) { - for(unsigned short i=0; i<=nPolyConn; ++i) { - const unsigned short iind = i*(nPolyConn+1) + k; - modConnQuad[iind] = modConnPrism[k*kOff+i]; + for (unsigned short k = 0; k <= nPolyConn; ++k) { + for (unsigned short i = 0; i <= nPolyConn; ++i) { + const unsigned short iind = i * (nPolyConn + 1) + k; + modConnQuad[iind] = modConnPrism[k * kOff + i]; } } - } - else { + } else { /*--- The parametric coordinates r and s of the quad correspond to the parametric coordinates in i- and k-direction of the face of the prism. So an easy copy can be made. ---*/ unsigned short iind = 0; - for(unsigned short k=0; k<=nPolyConn; ++k) { - for(unsigned short i=0; i<=nPolyConn; ++i, ++iind) { - modConnQuad[iind] = modConnPrism[k*kOff+i]; + for (unsigned short k = 0; k <= nPolyConn; ++k) { + for (unsigned short i = 0; i <= nPolyConn; ++i, ++iind) { + modConnQuad[iind] = modConnPrism[k * kOff + i]; } } } } void CMeshFEM_DG::CreateConnectivitiesQuadrilateralAdjacentPyramid( - const unsigned long *cornerPointsQuad, - const unsigned short nPolyGrid, - const vector &pyraNodeIDsGrid, - const unsigned short nPolyConn, - const unsigned long *connPyra, - unsigned long *modConnQuad, - unsigned long *modConnPyra) { - + const unsigned long* cornerPointsQuad, const unsigned short nPolyGrid, const vector& pyraNodeIDsGrid, + const unsigned short nPolyConn, const unsigned long* connPyra, unsigned long* modConnQuad, + unsigned long* modConnPyra) { /* Determine the indices of the four corner points of the quadrilateral base of the pyramid. Note that the top of the pyramid is not needed in the comparison, because only triangular faces are attached to it. */ const unsigned short ind0 = 0; const unsigned short ind1 = nPolyGrid; - const unsigned short ind2 = (nPolyGrid+1)*(nPolyGrid+1) -1; + const unsigned short ind2 = (nPolyGrid + 1) * (nPolyGrid + 1) - 1; const unsigned short ind3 = ind2 - nPolyGrid; /* Easier storage of the four corner points of the quad in the new numbering. */ @@ -4474,40 +4216,46 @@ void CMeshFEM_DG::CreateConnectivitiesQuadrilateralAdjacentPyramid( signed short a = 0, b = 0, c = 0, d = 0, e = 0, f = 0; bool verticesDontMatch = false; - if(vert0 == pyraNodeIDsGrid[ind0] && vert1 == pyraNodeIDsGrid[ind1] && // ii = i. - vert2 == pyraNodeIDsGrid[ind2] && vert3 == pyraNodeIDsGrid[ind3]) { // jj = j. + if (vert0 == pyraNodeIDsGrid[ind0] && vert1 == pyraNodeIDsGrid[ind1] && // ii = i. + vert2 == pyraNodeIDsGrid[ind2] && vert3 == pyraNodeIDsGrid[ind3]) { // jj = j. b = f = 1; - } - else if(vert0 == pyraNodeIDsGrid[ind0] && vert1 == pyraNodeIDsGrid[ind3] && // ii = j. - vert2 == pyraNodeIDsGrid[ind2] && vert3 == pyraNodeIDsGrid[ind1]) { // jj = i. + } else if (vert0 == pyraNodeIDsGrid[ind0] && vert1 == pyraNodeIDsGrid[ind3] && // ii = j. + vert2 == pyraNodeIDsGrid[ind2] && vert3 == pyraNodeIDsGrid[ind1]) { // jj = i. c = e = 1; } - else if(vert0 == pyraNodeIDsGrid[ind1] && vert1 == pyraNodeIDsGrid[ind2] && // ii = j. - vert2 == pyraNodeIDsGrid[ind3] && vert3 == pyraNodeIDsGrid[ind0]) { // jj = nPoly-i. - d = nPolyConn; c = 1; e = -1; - } - else if(vert0 == pyraNodeIDsGrid[ind1] && vert1 == pyraNodeIDsGrid[ind0] && // ii = nPoly-i. - vert2 == pyraNodeIDsGrid[ind3] && vert3 == pyraNodeIDsGrid[ind2]) { // jj = j. - a = nPolyConn; b = -1; f = 1; - } - - else if(vert0 == pyraNodeIDsGrid[ind2] && vert1 == pyraNodeIDsGrid[ind3] && // ii = nPoly-i. - vert2 == pyraNodeIDsGrid[ind0] && vert3 == pyraNodeIDsGrid[ind1]) { // jj = nPoly-j. - a = d = nPolyConn; b = f = -1; - } - else if(vert0 == pyraNodeIDsGrid[ind2] && vert1 == pyraNodeIDsGrid[ind1] && // ii = nPoly-j. - vert2 == pyraNodeIDsGrid[ind0] && vert3 == pyraNodeIDsGrid[ind3]) { // jj = nPoly-i. - a = d = nPolyConn; c = e = -1; - } - - else if(vert0 == pyraNodeIDsGrid[ind3] && vert1 == pyraNodeIDsGrid[ind0] && // ii = nPoly-j. - vert2 == pyraNodeIDsGrid[ind1] && vert3 == pyraNodeIDsGrid[ind2]) { // jj = i. - a = nPolyConn; c = -1; e = 1; - } - else if(vert0 == pyraNodeIDsGrid[ind3] && vert1 == pyraNodeIDsGrid[ind2] && // ii = i. - vert2 == pyraNodeIDsGrid[ind1] && vert3 == pyraNodeIDsGrid[ind0]) { // jj = nPoly-j. - d = nPolyConn; b = 1; f = -1; + else if (vert0 == pyraNodeIDsGrid[ind1] && vert1 == pyraNodeIDsGrid[ind2] && // ii = j. + vert2 == pyraNodeIDsGrid[ind3] && vert3 == pyraNodeIDsGrid[ind0]) { // jj = nPoly-i. + d = nPolyConn; + c = 1; + e = -1; + } else if (vert0 == pyraNodeIDsGrid[ind1] && vert1 == pyraNodeIDsGrid[ind0] && // ii = nPoly-i. + vert2 == pyraNodeIDsGrid[ind3] && vert3 == pyraNodeIDsGrid[ind2]) { // jj = j. + a = nPolyConn; + b = -1; + f = 1; + } + + else if (vert0 == pyraNodeIDsGrid[ind2] && vert1 == pyraNodeIDsGrid[ind3] && // ii = nPoly-i. + vert2 == pyraNodeIDsGrid[ind0] && vert3 == pyraNodeIDsGrid[ind1]) { // jj = nPoly-j. + a = d = nPolyConn; + b = f = -1; + } else if (vert0 == pyraNodeIDsGrid[ind2] && vert1 == pyraNodeIDsGrid[ind1] && // ii = nPoly-j. + vert2 == pyraNodeIDsGrid[ind0] && vert3 == pyraNodeIDsGrid[ind3]) { // jj = nPoly-i. + a = d = nPolyConn; + c = e = -1; + } + + else if (vert0 == pyraNodeIDsGrid[ind3] && vert1 == pyraNodeIDsGrid[ind0] && // ii = nPoly-j. + vert2 == pyraNodeIDsGrid[ind1] && vert3 == pyraNodeIDsGrid[ind2]) { // jj = i. + a = nPolyConn; + c = -1; + e = 1; + } else if (vert0 == pyraNodeIDsGrid[ind3] && vert1 == pyraNodeIDsGrid[ind2] && // ii = i. + vert2 == pyraNodeIDsGrid[ind1] && vert3 == pyraNodeIDsGrid[ind0]) { // jj = nPoly-j. + d = nPolyConn; + b = 1; + f = -1; } else { @@ -4515,16 +4263,15 @@ void CMeshFEM_DG::CreateConnectivitiesQuadrilateralAdjacentPyramid( } /*--- If non-matching vertices have been found, terminate with an error message. ---*/ - if( verticesDontMatch ) - SU2_MPI::Error("Corner vertices do not match. This should not happen.", CURRENT_FUNCTION); + if (verticesDontMatch) SU2_MPI::Error("Corner vertices do not match. This should not happen.", CURRENT_FUNCTION); /*--- Loop over the DOFs of the original pyramid to create the connectivity of the pyramid that corresponds to the new numbering. Note that the outer k-loop is the same for both numberings. ---*/ - unsigned short mPoly = nPolyConn; + unsigned short mPoly = nPolyConn; unsigned short offLevel = 0; - for(unsigned short k=0; k<=nPolyConn; ++k, --mPoly) { + for (unsigned short k = 0; k <= nPolyConn; ++k, --mPoly) { unsigned short ind = offLevel; /* The variables of a and d in the transformation are actually flexible. */ @@ -4533,45 +4280,40 @@ void CMeshFEM_DG::CreateConnectivitiesQuadrilateralAdjacentPyramid( const signed short dd = d ? mPoly : 0; /* Loop over the DOFs of the current quadrilateral. */ - for(unsigned short j=0; j<=mPoly; ++j) { - for(unsigned short i=0; i<=mPoly; ++i, ++ind) { - + for (unsigned short j = 0; j <= mPoly; ++j) { + for (unsigned short i = 0; i <= mPoly; ++i, ++ind) { /*--- Determine the ii and jj indices of the new numbering, convert it to a 1D index and shore the modified index in modConnPyra. ---*/ - unsigned short ii = aa + i*b + j*c; - unsigned short jj = dd + i*e + j*f; - unsigned short iind = offLevel + jj*(mPoly+1) + ii; + unsigned short ii = aa + i * b + j * c; + unsigned short jj = dd + i * e + j * f; + unsigned short iind = offLevel + jj * (mPoly + 1) + ii; modConnPyra[iind] = connPyra[ind]; } } /* Update offLevel for the next quadrilateral level of the pyramid. */ - offLevel += (mPoly+1)*(mPoly+1); + offLevel += (mPoly + 1) * (mPoly + 1); } /*--- The quad corresponds to face 0 of the pyramid. Hence the first nn2 entries in modConnPyra are the DOFs of the quad. Copy these entries from modConnPyra. ---*/ - const unsigned short nn2 = (nPolyConn+1)*(nPolyConn+1); - for(unsigned short i=0; i &prismNodeIDsGrid, - const unsigned short nPolyConn, - const unsigned long *connPrism, - unsigned long *modConnTria, - unsigned long *modConnPrism) { - +void CMeshFEM_DG::CreateConnectivitiesTriangleAdjacentPrism(const unsigned long* cornerPointsTria, + const unsigned short nPolyGrid, + const vector& prismNodeIDsGrid, + const unsigned short nPolyConn, + const unsigned long* connPrism, unsigned long* modConnTria, + unsigned long* modConnPrism) { /* Determine the indices of the six corner points of the prism. */ const unsigned short ind0 = 0; const unsigned short ind1 = nPolyGrid; - const unsigned short ind2 = (nPolyGrid+1)*(nPolyGrid+2)/2 -1; - const unsigned short ind3 = (nPolyGrid+1)*(nPolyGrid+2)*nPolyGrid/2; + const unsigned short ind2 = (nPolyGrid + 1) * (nPolyGrid + 2) / 2 - 1; + const unsigned short ind3 = (nPolyGrid + 1) * (nPolyGrid + 2) * nPolyGrid / 2; const unsigned short ind4 = ind1 + ind3; const unsigned short ind5 = ind2 + ind3; @@ -4594,58 +4336,72 @@ void CMeshFEM_DG::CreateConnectivitiesTriangleAdjacentPrism( signed short a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0; bool verticesDontMatch = false; - if(vert0 == prismNodeIDsGrid[ind0] && vert1 == prismNodeIDsGrid[ind1] && // ii = i. - vert2 == prismNodeIDsGrid[ind2]) { // jj = j. - b = f = h = 1; // kk = k. - } - else if(vert0 == prismNodeIDsGrid[ind0] && vert1 == prismNodeIDsGrid[ind2] && // ii = j. - vert2 == prismNodeIDsGrid[ind1]) { // jj = i. - c = e = h = 1; // kk = k. - } - - else if(vert0 == prismNodeIDsGrid[ind1] && vert1 == prismNodeIDsGrid[ind0] && // ii = nPoly-i-j. - vert2 == prismNodeIDsGrid[ind2]) { // jj = j. - a = nPolyConn; b = c = -1; f = h = 1; // kk = k. - } - else if(vert0 == prismNodeIDsGrid[ind1] && vert1 == prismNodeIDsGrid[ind2] && // ii = j. - vert2 == prismNodeIDsGrid[ind0]) { // jj = nPoly-i-j. - d = nPolyConn; e = f = -1; c = h = 1; // kk = k. - } - - else if(vert0 == prismNodeIDsGrid[ind2] && vert1 == prismNodeIDsGrid[ind0] && // ii = nPoly-i-j. - vert2 == prismNodeIDsGrid[ind1]) { // jj = i. - a = nPolyConn; b = c = -1; e = h = 1; // kk = k. - } - else if(vert0 == prismNodeIDsGrid[ind2] && vert1 == prismNodeIDsGrid[ind1] && // ii = i. - vert2 == prismNodeIDsGrid[ind0]) { // jj = nPoly-i-j. - d = nPolyConn; e = f = -1; b = h = 1; // kk = k. - } - - else if(vert0 == prismNodeIDsGrid[ind3] && vert1 == prismNodeIDsGrid[ind4] && // ii = i. - vert2 == prismNodeIDsGrid[ind5]) { // jj = j. - g = nPolyConn; b = f = 1; h = -1; // kk = nPoly-k. - } - else if(vert0 == prismNodeIDsGrid[ind3] && vert1 == prismNodeIDsGrid[ind5] && // ii = j. - vert2 == prismNodeIDsGrid[ind4]) { // jj = i. - g = nPolyConn; c = e = 1; h = -1; // kk = nPoly-k. + if (vert0 == prismNodeIDsGrid[ind0] && vert1 == prismNodeIDsGrid[ind1] && // ii = i. + vert2 == prismNodeIDsGrid[ind2]) { // jj = j. + b = f = h = 1; // kk = k. + } else if (vert0 == prismNodeIDsGrid[ind0] && vert1 == prismNodeIDsGrid[ind2] && // ii = j. + vert2 == prismNodeIDsGrid[ind1]) { // jj = i. + c = e = h = 1; // kk = k. + } + + else if (vert0 == prismNodeIDsGrid[ind1] && vert1 == prismNodeIDsGrid[ind0] && // ii = nPoly-i-j. + vert2 == prismNodeIDsGrid[ind2]) { // jj = j. + a = nPolyConn; + b = c = -1; + f = h = 1; // kk = k. + } else if (vert0 == prismNodeIDsGrid[ind1] && vert1 == prismNodeIDsGrid[ind2] && // ii = j. + vert2 == prismNodeIDsGrid[ind0]) { // jj = nPoly-i-j. + d = nPolyConn; + e = f = -1; + c = h = 1; // kk = k. + } + + else if (vert0 == prismNodeIDsGrid[ind2] && vert1 == prismNodeIDsGrid[ind0] && // ii = nPoly-i-j. + vert2 == prismNodeIDsGrid[ind1]) { // jj = i. + a = nPolyConn; + b = c = -1; + e = h = 1; // kk = k. + } else if (vert0 == prismNodeIDsGrid[ind2] && vert1 == prismNodeIDsGrid[ind1] && // ii = i. + vert2 == prismNodeIDsGrid[ind0]) { // jj = nPoly-i-j. + d = nPolyConn; + e = f = -1; + b = h = 1; // kk = k. + } + + else if (vert0 == prismNodeIDsGrid[ind3] && vert1 == prismNodeIDsGrid[ind4] && // ii = i. + vert2 == prismNodeIDsGrid[ind5]) { // jj = j. + g = nPolyConn; + b = f = 1; + h = -1; // kk = nPoly-k. + } else if (vert0 == prismNodeIDsGrid[ind3] && vert1 == prismNodeIDsGrid[ind5] && // ii = j. + vert2 == prismNodeIDsGrid[ind4]) { // jj = i. + g = nPolyConn; + c = e = 1; + h = -1; // kk = nPoly-k. } - else if(vert0 == prismNodeIDsGrid[ind4] && vert1 == prismNodeIDsGrid[ind3] && // ii = nPoly-i-j. - vert2 == prismNodeIDsGrid[ind5]) { // jj = j. - a = g = nPolyConn; b = c = h = -1; f = 1; // kk = nPoly-k. - } - else if(vert0 == prismNodeIDsGrid[ind4] && vert1 == prismNodeIDsGrid[ind5] && // ii = j. - vert2 == prismNodeIDsGrid[ind3]) { // jj = nPoly-i-j. - d = g = nPolyConn; e = f = h = -1; c = 1; // kk = nPoly-k. + else if (vert0 == prismNodeIDsGrid[ind4] && vert1 == prismNodeIDsGrid[ind3] && // ii = nPoly-i-j. + vert2 == prismNodeIDsGrid[ind5]) { // jj = j. + a = g = nPolyConn; + b = c = h = -1; + f = 1; // kk = nPoly-k. + } else if (vert0 == prismNodeIDsGrid[ind4] && vert1 == prismNodeIDsGrid[ind5] && // ii = j. + vert2 == prismNodeIDsGrid[ind3]) { // jj = nPoly-i-j. + d = g = nPolyConn; + e = f = h = -1; + c = 1; // kk = nPoly-k. } - else if(vert0 == prismNodeIDsGrid[ind5] && vert1 == prismNodeIDsGrid[ind3] && // ii = nPoly-i-j. - vert2 == prismNodeIDsGrid[ind4]) { // jj = i. - a = g = nPolyConn; b = c = h = -1; e = 1; // kk = nPoly-k. - } - else if(vert0 == prismNodeIDsGrid[ind5] && vert1 == prismNodeIDsGrid[ind4] && // ii = i. - vert2 == prismNodeIDsGrid[ind3]) { // jj = nPoly-i-j. - d = g = nPolyConn; e = f = h = -1; b = 1; // kk = nPoly-k. + else if (vert0 == prismNodeIDsGrid[ind5] && vert1 == prismNodeIDsGrid[ind3] && // ii = nPoly-i-j. + vert2 == prismNodeIDsGrid[ind4]) { // jj = i. + a = g = nPolyConn; + b = c = h = -1; + e = 1; // kk = nPoly-k. + } else if (vert0 == prismNodeIDsGrid[ind5] && vert1 == prismNodeIDsGrid[ind4] && // ii = i. + vert2 == prismNodeIDsGrid[ind3]) { // jj = nPoly-i-j. + d = g = nPolyConn; + e = f = h = -1; + b = 1; // kk = nPoly-k. } else { @@ -4653,24 +4409,22 @@ void CMeshFEM_DG::CreateConnectivitiesTriangleAdjacentPrism( } /*--- If non-matching vertices have been found, terminate with an error message. ---*/ - if( verticesDontMatch ) - SU2_MPI::Error("Corner vertices do not match. This should not happen.", CURRENT_FUNCTION); + if (verticesDontMatch) SU2_MPI::Error("Corner vertices do not match. This should not happen.", CURRENT_FUNCTION); /*--- Loop over the DOFs of the original prism to create the connectivity of the prism that corresponds to the new numbering. ---*/ - const unsigned short kOff = (nPolyConn+1)*(nPolyConn+2)/2; + const unsigned short kOff = (nPolyConn + 1) * (nPolyConn + 2) / 2; unsigned short ind = 0; - for(unsigned short k=0; k<=nPolyConn; ++k) { - for(unsigned short j=0; j<=nPolyConn; ++j) { + for (unsigned short k = 0; k <= nPolyConn; ++k) { + for (unsigned short j = 0; j <= nPolyConn; ++j) { unsigned short uppBoundI = nPolyConn - j; - for(unsigned short i=0; i<=uppBoundI; ++i, ++ind) { - + for (unsigned short i = 0; i <= uppBoundI; ++i, ++ind) { /*--- Determine the ii, jj and kk indices of the new numbering, convert it to a 1D index and shore the modified index in modConnPrism. ---*/ - unsigned short ii = a + i*b + j*c; - unsigned short jj = d + i*e + j*f; - unsigned short kk = g + h*k; - unsigned short iind = kk*kOff + jj*(nPolyConn+1) + ii - jj*(jj-1)/2; + unsigned short ii = a + i * b + j * c; + unsigned short jj = d + i * e + j * f; + unsigned short kk = g + h * k; + unsigned short iind = kk * kOff + jj * (nPolyConn + 1) + ii - jj * (jj - 1) / 2; modConnPrism[iind] = connPrism[ind]; } @@ -4680,34 +4434,32 @@ void CMeshFEM_DG::CreateConnectivitiesTriangleAdjacentPrism( /*--- The triangle corresponds to face 0 of the prism. Hence the first kOff entries in modConnPrism are the DOFs of the triangle. Copy these entries from modConnPrism. ---*/ - for(unsigned short i=0; i &pyraNodeIDsGrid, - const unsigned short nPolyConn, - const unsigned long *connPyra, - bool &swapFaceInElement, - unsigned long *modConnTria, - unsigned long *modConnPyra) { - +void CMeshFEM_DG::CreateConnectivitiesTriangleAdjacentPyramid(const unsigned long* cornerPointsTria, + const unsigned short nPolyGrid, + const vector& pyraNodeIDsGrid, + const unsigned short nPolyConn, + const unsigned long* connPyra, bool& swapFaceInElement, + unsigned long* modConnTria, unsigned long* modConnPyra) { /* Determine the indices of the five corner points of the pyramid. */ const unsigned short ind0 = 0; const unsigned short ind1 = nPolyGrid; - const unsigned short ind2 = (nPolyGrid+1)*(nPolyGrid+1) -1; + const unsigned short ind2 = (nPolyGrid + 1) * (nPolyGrid + 1) - 1; const unsigned short ind3 = ind2 - nPolyGrid; - const unsigned short ind4 = (nPolyGrid+1)*(nPolyGrid+2)*(2*nPolyGrid+3)/6 -1; + const unsigned short ind4 = (nPolyGrid + 1) * (nPolyGrid + 2) * (2 * nPolyGrid + 3) / 6 - 1; /* Check if the top of the pyramid coincides with either corner point 1 or corner point 2 of the triangle. Set swapFaceInElement accordingly. */ - if( cornerPointsTria[1] == pyraNodeIDsGrid[ind4]) swapFaceInElement = true; - else if(cornerPointsTria[2] == pyraNodeIDsGrid[ind4]) swapFaceInElement = false; + if (cornerPointsTria[1] == pyraNodeIDsGrid[ind4]) + swapFaceInElement = true; + else if (cornerPointsTria[2] == pyraNodeIDsGrid[ind4]) + swapFaceInElement = false; else SU2_MPI::Error(string("Top of the pyramid does not coincide with either corner point 1 or 2.\n") + - string("This should not happen"), CURRENT_FUNCTION); + string("This should not happen"), + CURRENT_FUNCTION); /* Easier storage of the two other corner points of the triangle in the new numbering. vert0 always corresponds to cornerPointsTria[0], while vert1 contains the other @@ -4728,32 +4480,38 @@ void CMeshFEM_DG::CreateConnectivitiesTriangleAdjacentPyramid( signed short a = 0, b = 0, c = 0, d = 0, e = 0, f = 0; bool verticesDontMatch = false; - if(vert0 == pyraNodeIDsGrid[ind0] && vert1 == pyraNodeIDsGrid[ind1]) { // ii = i. - b = f = 1; // jj = j. - } - else if(vert0 == pyraNodeIDsGrid[ind0] && vert1 == pyraNodeIDsGrid[ind3]) { // ii = j. - c = e = 1; // jj = i. + if (vert0 == pyraNodeIDsGrid[ind0] && vert1 == pyraNodeIDsGrid[ind1]) { // ii = i. + b = f = 1; // jj = j. + } else if (vert0 == pyraNodeIDsGrid[ind0] && vert1 == pyraNodeIDsGrid[ind3]) { // ii = j. + c = e = 1; // jj = i. } - else if(vert0 == pyraNodeIDsGrid[ind1] && vert1 == pyraNodeIDsGrid[ind2]) { // ii = j. - d = nPolyConn; c = 1; e = -1; // jj = nPoly-i. - } - else if(vert0 == pyraNodeIDsGrid[ind1] && vert1 == pyraNodeIDsGrid[ind0]) { // ii = nPoly-i. - a = nPolyConn; b = -1; f = 1; // jj = j. + else if (vert0 == pyraNodeIDsGrid[ind1] && vert1 == pyraNodeIDsGrid[ind2]) { // ii = j. + d = nPolyConn; + c = 1; + e = -1; // jj = nPoly-i. + } else if (vert0 == pyraNodeIDsGrid[ind1] && vert1 == pyraNodeIDsGrid[ind0]) { // ii = nPoly-i. + a = nPolyConn; + b = -1; + f = 1; // jj = j. } - else if(vert0 == pyraNodeIDsGrid[ind2] && vert1 == pyraNodeIDsGrid[ind3]) { // ii = nPoly-i. - a = d = nPolyConn; b = f = -1; // jj = nPoly-j. - } - else if(vert0 == pyraNodeIDsGrid[ind2] && vert1 == pyraNodeIDsGrid[ind1]) { // ii = nPoly-j. - a = d = nPolyConn; c = e = -1; // jj = nPoly-i. + else if (vert0 == pyraNodeIDsGrid[ind2] && vert1 == pyraNodeIDsGrid[ind3]) { // ii = nPoly-i. + a = d = nPolyConn; + b = f = -1; // jj = nPoly-j. + } else if (vert0 == pyraNodeIDsGrid[ind2] && vert1 == pyraNodeIDsGrid[ind1]) { // ii = nPoly-j. + a = d = nPolyConn; + c = e = -1; // jj = nPoly-i. } - else if(vert0 == pyraNodeIDsGrid[ind3] && vert1 == pyraNodeIDsGrid[ind0]) { // ii = nPoly-j. - a = nPolyConn; c = -1; e = 1; // jj = i. - } - else if(vert0 == pyraNodeIDsGrid[ind3] && vert1 == pyraNodeIDsGrid[ind2]) { // ii = i. - d = nPolyConn; b = 1; f = -1; // jj = nPoly-j. + else if (vert0 == pyraNodeIDsGrid[ind3] && vert1 == pyraNodeIDsGrid[ind0]) { // ii = nPoly-j. + a = nPolyConn; + c = -1; + e = 1; // jj = i. + } else if (vert0 == pyraNodeIDsGrid[ind3] && vert1 == pyraNodeIDsGrid[ind2]) { // ii = i. + d = nPolyConn; + b = 1; + f = -1; // jj = nPoly-j. } else { @@ -4761,16 +4519,15 @@ void CMeshFEM_DG::CreateConnectivitiesTriangleAdjacentPyramid( } /*--- If non-matching vertices have been found, terminate with an error message. ---*/ - if( verticesDontMatch ) - SU2_MPI::Error("Corner vertices do not match. This should not happen.", CURRENT_FUNCTION); + if (verticesDontMatch) SU2_MPI::Error("Corner vertices do not match. This should not happen.", CURRENT_FUNCTION); /*--- Loop over the DOFs of the original pyramid to create the connectivity of the pyramid that corresponds to the new numbering. Note that the outer k-loop is the same for both numberings. ---*/ - unsigned short mPoly = nPolyConn; + unsigned short mPoly = nPolyConn; unsigned short offLevel = 0; - for(unsigned short k=0; k<=nPolyConn; ++k, --mPoly) { + for (unsigned short k = 0; k <= nPolyConn; ++k, --mPoly) { unsigned short ind = offLevel; /* The variables of a and d in the transformation are actually flexible. */ @@ -4779,72 +4536,64 @@ void CMeshFEM_DG::CreateConnectivitiesTriangleAdjacentPyramid( const signed short dd = d ? mPoly : 0; /* Loop over the DOFs of the current quadrilateral. */ - for(unsigned short j=0; j<=mPoly; ++j) { - for(unsigned short i=0; i<=mPoly; ++i, ++ind) { - + for (unsigned short j = 0; j <= mPoly; ++j) { + for (unsigned short i = 0; i <= mPoly; ++i, ++ind) { /*--- Determine the ii and jj indices of the new numbering, convert it to a 1D index and shore the modified index in modConnPyra. ---*/ - unsigned short ii = aa + i*b + j*c; - unsigned short jj = dd + i*e + j*f; - unsigned short iind = offLevel + jj*(mPoly+1) + ii; + unsigned short ii = aa + i * b + j * c; + unsigned short jj = dd + i * e + j * f; + unsigned short iind = offLevel + jj * (mPoly + 1) + ii; modConnPyra[iind] = connPyra[ind]; } } /* Update offLevel for the next quadrilateral level of the pyramid. */ - offLevel += (mPoly+1)*(mPoly+1); + offLevel += (mPoly + 1) * (mPoly + 1); } /*--- Determine the connectivity of the triangular face. ---*/ - if( swapFaceInElement ) { - + if (swapFaceInElement) { /*--- The parametric coordinates r and s of the triangle must be swapped w.r.t. to the parametric coordinates of the face of the pyramid. This means that the coordinate r of the triangle runs from the base to the top of the pyramid. This corresponds to the k-direction of the pyramid. Hence the s-direction of the triangle corresponds to the i-direction of the pyramid. ---*/ - mPoly = nPolyConn; + mPoly = nPolyConn; offLevel = 0; - for(unsigned short k=0; k<=nPolyConn; ++k, --mPoly) { - for(unsigned short i=0; i<=mPoly; ++i) { - unsigned short iind = i*(nPolyConn+1) + k - i*(i-1)/2; - modConnTria[iind] = modConnPyra[offLevel+i]; + for (unsigned short k = 0; k <= nPolyConn; ++k, --mPoly) { + for (unsigned short i = 0; i <= mPoly; ++i) { + unsigned short iind = i * (nPolyConn + 1) + k - i * (i - 1) / 2; + modConnTria[iind] = modConnPyra[offLevel + i]; } - offLevel += (mPoly+1)*(mPoly+1); + offLevel += (mPoly + 1) * (mPoly + 1); } - } - else { + } else { /*--- The parametric coordinates r and s of the triangle correspond to the parametric coordinates in i- and k-direction of the face of the pyramid. So an easy copy can be made. ---*/ - mPoly = nPolyConn; + mPoly = nPolyConn; offLevel = 0; unsigned short iind = 0; - for(unsigned short k=0; k<=nPolyConn; ++k, --mPoly) { - for(unsigned short i=0; i<=mPoly; ++i, ++iind) { - modConnTria[iind] = modConnPyra[offLevel+i]; + for (unsigned short k = 0; k <= nPolyConn; ++k, --mPoly) { + for (unsigned short i = 0; i <= mPoly; ++i, ++iind) { + modConnTria[iind] = modConnPyra[offLevel + i]; } - offLevel += (mPoly+1)*(mPoly+1); + offLevel += (mPoly + 1) * (mPoly + 1); } } } void CMeshFEM_DG::CreateConnectivitiesTriangleAdjacentTetrahedron( - const unsigned long *cornerPointsTria, - const unsigned short nPolyGrid, - const vector &tetNodeIDsGrid, - const unsigned short nPolyConn, - const unsigned long *connTet, - unsigned long *modConnTria, - unsigned long *modConnTet) { - + const unsigned long* cornerPointsTria, const unsigned short nPolyGrid, const vector& tetNodeIDsGrid, + const unsigned short nPolyConn, const unsigned long* connTet, unsigned long* modConnTria, + unsigned long* modConnTet) { /* Determine the indices of the four corner points of the tetrahedron. */ const unsigned short ind0 = 0; const unsigned short ind1 = nPolyGrid; - const unsigned short ind2 = (nPolyGrid+1)*(nPolyGrid+2)/2 -1; - const unsigned short ind3 = (nPolyGrid+1)*(nPolyGrid+2)*(nPolyGrid+3)/6 -1; + const unsigned short ind2 = (nPolyGrid + 1) * (nPolyGrid + 2) / 2 - 1; + const unsigned short ind3 = (nPolyGrid + 1) * (nPolyGrid + 2) * (nPolyGrid + 3) / 6 - 1; /* Easier storage of the three corner points of the triangle in the new numbering. */ const unsigned long vert0 = cornerPointsTria[0]; @@ -4861,112 +4610,128 @@ void CMeshFEM_DG::CreateConnectivitiesTriangleAdjacentTetrahedron( of the tetrahedron. This is determined below. The bool verticesDontMatch is there to check if vertices do not match. This should not happen, but it is checked for security. ---*/ - signed short a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0, - l = 0, m = 0, n = 0, o = 0; + signed short a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0, l = 0, m = 0, n = 0, o = 0; bool verticesDontMatch = false; - if(vert0 == tetNodeIDsGrid[ind0] && vert1 == tetNodeIDsGrid[ind1] && // ii = i. - vert2 == tetNodeIDsGrid[ind2]) { // jj = j. - b = g = o = 1; // kk = k. - } - else if(vert0 == tetNodeIDsGrid[ind0] && vert1 == tetNodeIDsGrid[ind2] && // ii = j. - vert2 == tetNodeIDsGrid[ind1]) { // jj = i. - c = f = o = 1; // kk = k. - } - else if(vert0 == tetNodeIDsGrid[ind0] && vert1 == tetNodeIDsGrid[ind1] && // ii = i. - vert2 == tetNodeIDsGrid[ind3]) { // jj = k. - b = h = n = 1; // kk = j. - } - else if(vert0 == tetNodeIDsGrid[ind0] && vert1 == tetNodeIDsGrid[ind3] && // ii = k. - vert2 == tetNodeIDsGrid[ind1]) { // jj = i. - d = f = n = 1; // kk = j. - } - else if(vert0 == tetNodeIDsGrid[ind0] && vert1 == tetNodeIDsGrid[ind2] && // ii = j. - vert2 == tetNodeIDsGrid[ind3]) { // jj = k. - c = h = m = 1; // kk = i. - } - else if(vert0 == tetNodeIDsGrid[ind0] && vert1 == tetNodeIDsGrid[ind3] && // ii = k. - vert2 == tetNodeIDsGrid[ind2]) { // jj = j. - d = g = m = 1; // kk = i. - } - - else if(vert0 == tetNodeIDsGrid[ind1] && vert1 == tetNodeIDsGrid[ind0] && // ii = nPoly-i-j-k. - vert2 == tetNodeIDsGrid[ind2]) { // jj = j. - a = nPolyConn; b = c = d = -1; g = o = 1; // kk = k. - } - else if(vert0 == tetNodeIDsGrid[ind1] && vert1 == tetNodeIDsGrid[ind2] && // ii = j. - vert2 == tetNodeIDsGrid[ind0]) { // jj = nPoly-i-j-k. - e = nPolyConn; f = g = h = -1; c = o = 1; // kk = k. - } - else if(vert0 == tetNodeIDsGrid[ind1] && vert1 == tetNodeIDsGrid[ind0] && // ii = nPoly-i-j-k. - vert2 == tetNodeIDsGrid[ind3]) { // jj = k. - a = nPolyConn; b = c = d = -1; h = n = 1; // kk = j. - } - else if(vert0 == tetNodeIDsGrid[ind1] && vert1 == tetNodeIDsGrid[ind3] && // ii = k. - vert2 == tetNodeIDsGrid[ind0]) { // jj = nPoly-i-j-k. - e = nPolyConn; f = g = h = -1; d = n = 1; // kk = j. - } - else if(vert0 == tetNodeIDsGrid[ind1] && vert1 == tetNodeIDsGrid[ind2] && // ii = j. - vert2 == tetNodeIDsGrid[ind3]) { // jj = k. - l = nPolyConn; m = n = o = -1; c = h = 1; // kk = nPoly-i-j-k. - } - else if(vert0 == tetNodeIDsGrid[ind1] && vert1 == tetNodeIDsGrid[ind3] && // ii = k. - vert2 == tetNodeIDsGrid[ind2]) { // jj = j. - l = nPolyConn; m = n = o = -1; d = g = 1; // kk = nPoly-i-j-k. - } - - else if(vert0 == tetNodeIDsGrid[ind2] && vert1 == tetNodeIDsGrid[ind0] && // ii = nPoly-i-j-k. - vert2 == tetNodeIDsGrid[ind1]) { // jj = i. - a = nPolyConn; b = c = d = -1; f = o = 1; // kk = k. - } - else if(vert0 == tetNodeIDsGrid[ind2] && vert1 == tetNodeIDsGrid[ind1] && // ii = i. - vert2 == tetNodeIDsGrid[ind0]) { // jj = nPoly-i-j-k. - e = nPolyConn; f = g = h = -1; b = o = 1; // kk = k. - } - else if(vert0 == tetNodeIDsGrid[ind2] && vert1 == tetNodeIDsGrid[ind0] && // ii = nPoly-i-j-k. - vert2 == tetNodeIDsGrid[ind3]) { // jj = k. - a = nPolyConn; b = c = d = -1; h = m = 1; // kk = i. - } - else if(vert0 == tetNodeIDsGrid[ind2] && vert1 == tetNodeIDsGrid[ind3] && // ii = k. - vert2 == tetNodeIDsGrid[ind0]) { // jj = nPoly-i-j-k. - e = nPolyConn; f = g = h = -1; d = m = 1; // kk = i. - } - else if(vert0 == tetNodeIDsGrid[ind2] && vert1 == tetNodeIDsGrid[ind0] && // ii = nPoly-i-j-k. - vert2 == tetNodeIDsGrid[ind3]) { // jj = k. - a = nPolyConn; b = c = d = -1; h = m = 1; // kk = i. - } - else if(vert0 == tetNodeIDsGrid[ind2] && vert1 == tetNodeIDsGrid[ind1] && // ii = i. - vert2 == tetNodeIDsGrid[ind3]) { // jj = k. - l = nPolyConn; m = n = o = -1; b = h = 1; // kk = nPoly-i-j-k. - } - else if(vert0 == tetNodeIDsGrid[ind2] && vert1 == tetNodeIDsGrid[ind3] && // ii = k. - vert2 == tetNodeIDsGrid[ind1]) { // jj = i. - l = nPolyConn; m = n = o = -1; d = f = 1; // kk = nPoly-i-j-k. - } - - else if(vert0 == tetNodeIDsGrid[ind3] && vert1 == tetNodeIDsGrid[ind0] && // ii = nPoly-i-j-k. - vert2 == tetNodeIDsGrid[ind1]) { // jj = i. - a = nPolyConn; b = c = d = -1; f = n = 1; // kk = j. - } - else if(vert0 == tetNodeIDsGrid[ind3] && vert1 == tetNodeIDsGrid[ind1] && // ii = i. - vert2 == tetNodeIDsGrid[ind0]) { // jj = nPoly-i-j-k. - e = nPolyConn; f = g = h = -1; b = n = 1; // kk = j. - } - else if(vert0 == tetNodeIDsGrid[ind3] && vert1 == tetNodeIDsGrid[ind0] && // ii = nPoly-i-j-k. - vert2 == tetNodeIDsGrid[ind2]) { // jj = j. - a = nPolyConn; b = c = d = -1; g = m = 1; // kk = i. - } - else if(vert0 == tetNodeIDsGrid[ind3] && vert1 == tetNodeIDsGrid[ind2] && // ii = j. - vert2 == tetNodeIDsGrid[ind0]) { // jj = nPoly-i-j-k. - e = nPolyConn; f = g = h = -1; c = m = 1; // kk = i. - } - else if(vert0 == tetNodeIDsGrid[ind3] && vert1 == tetNodeIDsGrid[ind1] && // ii = i. - vert2 == tetNodeIDsGrid[ind2]) { // jj = j. - l = nPolyConn; m = n = o = -1; b = g = 1; // kk = nPoly-i-j-k. - } - else if(vert0 == tetNodeIDsGrid[ind3] && vert1 == tetNodeIDsGrid[ind2] && // ii = j. - vert2 == tetNodeIDsGrid[ind1]) { // jj = i. - l = nPolyConn; m = n = o = -1; c = f = 1; // kk = nPoly-i-j-k. + if (vert0 == tetNodeIDsGrid[ind0] && vert1 == tetNodeIDsGrid[ind1] && // ii = i. + vert2 == tetNodeIDsGrid[ind2]) { // jj = j. + b = g = o = 1; // kk = k. + } else if (vert0 == tetNodeIDsGrid[ind0] && vert1 == tetNodeIDsGrid[ind2] && // ii = j. + vert2 == tetNodeIDsGrid[ind1]) { // jj = i. + c = f = o = 1; // kk = k. + } else if (vert0 == tetNodeIDsGrid[ind0] && vert1 == tetNodeIDsGrid[ind1] && // ii = i. + vert2 == tetNodeIDsGrid[ind3]) { // jj = k. + b = h = n = 1; // kk = j. + } else if (vert0 == tetNodeIDsGrid[ind0] && vert1 == tetNodeIDsGrid[ind3] && // ii = k. + vert2 == tetNodeIDsGrid[ind1]) { // jj = i. + d = f = n = 1; // kk = j. + } else if (vert0 == tetNodeIDsGrid[ind0] && vert1 == tetNodeIDsGrid[ind2] && // ii = j. + vert2 == tetNodeIDsGrid[ind3]) { // jj = k. + c = h = m = 1; // kk = i. + } else if (vert0 == tetNodeIDsGrid[ind0] && vert1 == tetNodeIDsGrid[ind3] && // ii = k. + vert2 == tetNodeIDsGrid[ind2]) { // jj = j. + d = g = m = 1; // kk = i. + } + + else if (vert0 == tetNodeIDsGrid[ind1] && vert1 == tetNodeIDsGrid[ind0] && // ii = nPoly-i-j-k. + vert2 == tetNodeIDsGrid[ind2]) { // jj = j. + a = nPolyConn; + b = c = d = -1; + g = o = 1; // kk = k. + } else if (vert0 == tetNodeIDsGrid[ind1] && vert1 == tetNodeIDsGrid[ind2] && // ii = j. + vert2 == tetNodeIDsGrid[ind0]) { // jj = nPoly-i-j-k. + e = nPolyConn; + f = g = h = -1; + c = o = 1; // kk = k. + } else if (vert0 == tetNodeIDsGrid[ind1] && vert1 == tetNodeIDsGrid[ind0] && // ii = nPoly-i-j-k. + vert2 == tetNodeIDsGrid[ind3]) { // jj = k. + a = nPolyConn; + b = c = d = -1; + h = n = 1; // kk = j. + } else if (vert0 == tetNodeIDsGrid[ind1] && vert1 == tetNodeIDsGrid[ind3] && // ii = k. + vert2 == tetNodeIDsGrid[ind0]) { // jj = nPoly-i-j-k. + e = nPolyConn; + f = g = h = -1; + d = n = 1; // kk = j. + } else if (vert0 == tetNodeIDsGrid[ind1] && vert1 == tetNodeIDsGrid[ind2] && // ii = j. + vert2 == tetNodeIDsGrid[ind3]) { // jj = k. + l = nPolyConn; + m = n = o = -1; + c = h = 1; // kk = nPoly-i-j-k. + } else if (vert0 == tetNodeIDsGrid[ind1] && vert1 == tetNodeIDsGrid[ind3] && // ii = k. + vert2 == tetNodeIDsGrid[ind2]) { // jj = j. + l = nPolyConn; + m = n = o = -1; + d = g = 1; // kk = nPoly-i-j-k. + } + + else if (vert0 == tetNodeIDsGrid[ind2] && vert1 == tetNodeIDsGrid[ind0] && // ii = nPoly-i-j-k. + vert2 == tetNodeIDsGrid[ind1]) { // jj = i. + a = nPolyConn; + b = c = d = -1; + f = o = 1; // kk = k. + } else if (vert0 == tetNodeIDsGrid[ind2] && vert1 == tetNodeIDsGrid[ind1] && // ii = i. + vert2 == tetNodeIDsGrid[ind0]) { // jj = nPoly-i-j-k. + e = nPolyConn; + f = g = h = -1; + b = o = 1; // kk = k. + } else if (vert0 == tetNodeIDsGrid[ind2] && vert1 == tetNodeIDsGrid[ind0] && // ii = nPoly-i-j-k. + vert2 == tetNodeIDsGrid[ind3]) { // jj = k. + a = nPolyConn; + b = c = d = -1; + h = m = 1; // kk = i. + } else if (vert0 == tetNodeIDsGrid[ind2] && vert1 == tetNodeIDsGrid[ind3] && // ii = k. + vert2 == tetNodeIDsGrid[ind0]) { // jj = nPoly-i-j-k. + e = nPolyConn; + f = g = h = -1; + d = m = 1; // kk = i. + } else if (vert0 == tetNodeIDsGrid[ind2] && vert1 == tetNodeIDsGrid[ind0] && // ii = nPoly-i-j-k. + vert2 == tetNodeIDsGrid[ind3]) { // jj = k. + a = nPolyConn; + b = c = d = -1; + h = m = 1; // kk = i. + } else if (vert0 == tetNodeIDsGrid[ind2] && vert1 == tetNodeIDsGrid[ind1] && // ii = i. + vert2 == tetNodeIDsGrid[ind3]) { // jj = k. + l = nPolyConn; + m = n = o = -1; + b = h = 1; // kk = nPoly-i-j-k. + } else if (vert0 == tetNodeIDsGrid[ind2] && vert1 == tetNodeIDsGrid[ind3] && // ii = k. + vert2 == tetNodeIDsGrid[ind1]) { // jj = i. + l = nPolyConn; + m = n = o = -1; + d = f = 1; // kk = nPoly-i-j-k. + } + + else if (vert0 == tetNodeIDsGrid[ind3] && vert1 == tetNodeIDsGrid[ind0] && // ii = nPoly-i-j-k. + vert2 == tetNodeIDsGrid[ind1]) { // jj = i. + a = nPolyConn; + b = c = d = -1; + f = n = 1; // kk = j. + } else if (vert0 == tetNodeIDsGrid[ind3] && vert1 == tetNodeIDsGrid[ind1] && // ii = i. + vert2 == tetNodeIDsGrid[ind0]) { // jj = nPoly-i-j-k. + e = nPolyConn; + f = g = h = -1; + b = n = 1; // kk = j. + } else if (vert0 == tetNodeIDsGrid[ind3] && vert1 == tetNodeIDsGrid[ind0] && // ii = nPoly-i-j-k. + vert2 == tetNodeIDsGrid[ind2]) { // jj = j. + a = nPolyConn; + b = c = d = -1; + g = m = 1; // kk = i. + } else if (vert0 == tetNodeIDsGrid[ind3] && vert1 == tetNodeIDsGrid[ind2] && // ii = j. + vert2 == tetNodeIDsGrid[ind0]) { // jj = nPoly-i-j-k. + e = nPolyConn; + f = g = h = -1; + c = m = 1; // kk = i. + } else if (vert0 == tetNodeIDsGrid[ind3] && vert1 == tetNodeIDsGrid[ind1] && // ii = i. + vert2 == tetNodeIDsGrid[ind2]) { // jj = j. + l = nPolyConn; + m = n = o = -1; + b = g = 1; // kk = nPoly-i-j-k. + } else if (vert0 == tetNodeIDsGrid[ind3] && vert1 == tetNodeIDsGrid[ind2] && // ii = j. + vert2 == tetNodeIDsGrid[ind1]) { // jj = i. + l = nPolyConn; + m = n = o = -1; + c = f = 1; // kk = nPoly-i-j-k. } else { @@ -4974,30 +4739,28 @@ void CMeshFEM_DG::CreateConnectivitiesTriangleAdjacentTetrahedron( } /*--- If non-matching vertices have been found, terminate with an error message. ---*/ - if( verticesDontMatch ) - SU2_MPI::Error("Corner vertices do not match. This should not happen.", CURRENT_FUNCTION); + if (verticesDontMatch) SU2_MPI::Error("Corner vertices do not match. This should not happen.", CURRENT_FUNCTION); /*--- Some constants to convert the (ii,jj,kk) indices to a 1D index. ---*/ - const unsigned short abv1 = (11 + 12*nPolyConn + 3*nPolyConn*nPolyConn); - const unsigned short abv2 = (2*nPolyConn + 3)*3; - const unsigned short abv3 = (nPolyConn + 2)*3; + const unsigned short abv1 = (11 + 12 * nPolyConn + 3 * nPolyConn * nPolyConn); + const unsigned short abv2 = (2 * nPolyConn + 3) * 3; + const unsigned short abv3 = (nPolyConn + 2) * 3; /*--- Loop over the DOFs of the original tetrahedron to create the connectivity of the tetrahedron that corresponds to the new numbering. ---*/ unsigned short ind = 0; - for(unsigned short k=0; k<=nPolyConn; ++k) { + for (unsigned short k = 0; k <= nPolyConn; ++k) { unsigned short uppBoundJ = nPolyConn - k; - for(unsigned short j=0; j<=uppBoundJ; ++j) { + for (unsigned short j = 0; j <= uppBoundJ; ++j) { unsigned short uppBoundI = nPolyConn - k - j; - for(unsigned short i=0; i<=uppBoundI; ++i, ++ind) { - + for (unsigned short i = 0; i <= uppBoundI; ++i, ++ind) { /*--- Determine the ii, jj and kk indices of the new numbering, convert it to a 1D index and shore the modified index in modConnTet. ---*/ - unsigned short ii = a + i*b + j*c + k*d; - unsigned short jj = e + i*f + j*g + k*h; - unsigned short kk = l + i*m + j*n + k*o; - unsigned short iind = (abv1*kk + abv2*jj + 6*ii - abv3*kk*kk - - 6*kk*jj - 3*jj*jj + kk*kk*kk)/6; + unsigned short ii = a + i * b + j * c + k * d; + unsigned short jj = e + i * f + j * g + k * h; + unsigned short kk = l + i * m + j * n + k * o; + unsigned short iind = + (abv1 * kk + abv2 * jj + 6 * ii - abv3 * kk * kk - 6 * kk * jj - 3 * jj * jj + kk * kk * kk) / 6; modConnTet[iind] = connTet[ind]; } @@ -5007,19 +4770,17 @@ void CMeshFEM_DG::CreateConnectivitiesTriangleAdjacentTetrahedron( /*--- The triangle corresponds to face 0 of the tetrahedron. Hence the first nn2 entries in modConnTet are the DOFs of the triangle. Copy these entries from modConnTet. ---*/ - const unsigned short nn2 = (nPolyConn+1)*(nPolyConn+2)/2; - for(unsigned short i=0; iGetKind_Solver() != MAIN_SOLVER::FEM_EULER && config->GetKind_Solver() != MAIN_SOLVER::DISC_ADJ_FEM_EULER); + bool viscousTerms = (config->GetKind_Solver() != MAIN_SOLVER::FEM_EULER && + config->GetKind_Solver() != MAIN_SOLVER::DISC_ADJ_FEM_EULER); /* Loop over the internal matching faces. */ - for(unsigned long i=0; iGetUse_Lumped_MassMatrix_DGFEM(); - bool FullMassMatrix = false, FullInverseMassMatrix = false; + bool FullMassMatrix = false, FullInverseMassMatrix = false; bool LumpedMassMatrix = false, DerMetricTerms = false; - if(config->GetTime_Marching() == TIME_MARCHING::STEADY || - config->GetTime_Marching() == TIME_MARCHING::ROTATIONAL_FRAME) { - if( UseLumpedMassMatrix) LumpedMassMatrix = true; - else FullInverseMassMatrix = true; - } - else if(config->GetTime_Marching() == TIME_MARCHING::DT_STEPPING_1ST || - config->GetTime_Marching() == TIME_MARCHING::DT_STEPPING_2ND || - config->GetTime_Marching() == TIME_MARCHING::HARMONIC_BALANCE) { - if( UseLumpedMassMatrix ) FullMassMatrix = LumpedMassMatrix = true; - else FullInverseMassMatrix = true; - } - else { - + if (config->GetTime_Marching() == TIME_MARCHING::STEADY || + config->GetTime_Marching() == TIME_MARCHING::ROTATIONAL_FRAME) { + if (UseLumpedMassMatrix) + LumpedMassMatrix = true; + else + FullInverseMassMatrix = true; + } else if (config->GetTime_Marching() == TIME_MARCHING::DT_STEPPING_1ST || + config->GetTime_Marching() == TIME_MARCHING::DT_STEPPING_2ND || + config->GetTime_Marching() == TIME_MARCHING::HARMONIC_BALANCE) { + if (UseLumpedMassMatrix) + FullMassMatrix = LumpedMassMatrix = true; + else + FullInverseMassMatrix = true; + } else { /* Time accurate explicit time integration scheme. */ - FullMassMatrix = LumpedMassMatrix = false; + FullMassMatrix = LumpedMassMatrix = false; FullInverseMassMatrix = true; /* For ADER-DG, check if the derivative of the metric terms are needed. */ - if(config->GetKind_TimeIntScheme_Flow() == ADER_DG) { + if (config->GetKind_TimeIntScheme_Flow() == ADER_DG) { MAIN_SOLVER solver = config->GetKind_Solver(); - if(solver == MAIN_SOLVER::FEM_NAVIER_STOKES || solver == MAIN_SOLVER::FEM_RANS || solver == MAIN_SOLVER::FEM_LES) { - if(config->GetKind_ADER_Predictor() == ADER_NON_ALIASED_PREDICTOR) - DerMetricTerms = true; + if (solver == MAIN_SOLVER::FEM_NAVIER_STOKES || solver == MAIN_SOLVER::FEM_RANS || + solver == MAIN_SOLVER::FEM_LES) { + if (config->GetKind_ADER_Predictor() == ADER_NON_ALIASED_PREDICTOR) DerMetricTerms = true; } } } @@ -5401,8 +5137,8 @@ void CMeshFEM_DG::MetricTermsVolumeElements(CConfig *config) { This depends on the number of spatial dimensions of the problem. Also determine the additional number of metric terms per integration point for the computation of the second derivatives. */ - const unsigned short nMetricPerPoint = nDim*nDim + 1; - const unsigned short nMetric2ndDerPerPoint = nDim*(nDim + nDim*(nDim-1)/2); + const unsigned short nMetricPerPoint = nDim * nDim + 1; + const unsigned short nMetric2ndDerPerPoint = nDim * (nDim + nDim * (nDim - 1) / 2); /*--------------------------------------------------------------------------*/ /*--- Step 1: Determine the metric terms, drdx, drdy, drdz, dsdx, etc. ---*/ @@ -5411,75 +5147,68 @@ void CMeshFEM_DG::MetricTermsVolumeElements(CConfig *config) { /*--------------------------------------------------------------------------*/ /* Loop over the owned volume elements. */ - for(unsigned long i=0; i helpVecResultInt(nInt*nDim*nDim); - vector helpVecResultDOFsSol(nDOFsSol*nDim*nDim); - su2double *vecResultInt = helpVecResultInt.data(); - su2double *vecResultDOFsSol = helpVecResultDOFsSol.data(); + vector helpVecResultInt(nInt * nDim * nDim); + vector helpVecResultDOFsSol(nDOFsSol * nDim * nDim); + su2double* vecResultInt = helpVecResultInt.data(); + su2double* vecResultDOFsSol = helpVecResultDOFsSol.data(); /* Compute the gradient of the coordinates w.r.t. the parametric coordinates for this element in the integration points. */ - ComputeGradientsCoorWRTParam(nInt, nDOFsGrid, matDerBasisInt, - volElem[i].nodeIDsGrid.data(), - vecResultInt, config); + ComputeGradientsCoorWRTParam(nInt, nDOFsGrid, matDerBasisInt, volElem[i].nodeIDsGrid.data(), vecResultInt, config); /* Compute the gradient of the coordinates w.r.t. the parametric coordinates for this element in the solution DOFs. */ - ComputeGradientsCoorWRTParam(nDOFsSol, nDOFsGrid, matDerBasisSolDOFs, - volElem[i].nodeIDsGrid.data(), + ComputeGradientsCoorWRTParam(nDOFsSol, nDOFsGrid, matDerBasisSolDOFs, volElem[i].nodeIDsGrid.data(), vecResultDOFsSol, config); /* Convert the values of dxdr, dydr, etc. to the required metric terms for both the integration points and the solution DOFs. */ - VolumeMetricTermsFromCoorGradients(nInt, vecResultInt, - volElem[i].metricTerms); + VolumeMetricTermsFromCoorGradients(nInt, vecResultInt, volElem[i].metricTerms); - VolumeMetricTermsFromCoorGradients(nDOFsSol, vecResultDOFsSol, - volElem[i].metricTermsSolDOFs); + VolumeMetricTermsFromCoorGradients(nDOFsSol, vecResultDOFsSol, volElem[i].metricTermsSolDOFs); /* Check for negative Jacobians in the integrations points and at the location of the solution DOFs. */ bool negJacobian = false; - for(unsigned short j=0; j helpVecResultGridDOFs(nDOFsGrid*nDim*nDim); - su2double *vecResultGridDOFs = helpVecResultGridDOFs.data(); + vector helpVecResultGridDOFs(nDOFsGrid * nDim * nDim); + su2double* vecResultGridDOFs = helpVecResultGridDOFs.data(); - ComputeGradientsCoorWRTParam(nDOFsGrid, nDOFsGrid, matDerBasisGridDOFs, - volElem[i].nodeIDsGrid.data(), + ComputeGradientsCoorWRTParam(nDOFsGrid, nDOFsGrid, matDerBasisGridDOFs, volElem[i].nodeIDsGrid.data(), vecResultGridDOFs, config); /* Convert the values of dxdr, dydr, etc. to the required metric terms in the grid DOFs. */ - vector metricGridDOFs(nDOFsGrid*nMetricPerPoint); - VolumeMetricTermsFromCoorGradients(nDOFsGrid, vecResultGridDOFs, - metricGridDOFs); + vector metricGridDOFs(nDOFsGrid * nMetricPerPoint); + VolumeMetricTermsFromCoorGradients(nDOFsGrid, vecResultGridDOFs, metricGridDOFs); /*--- The metric terms currently stored in metricGridDOFs are scaled with the Jacobian and also the Jacobian is part of the metric terms. For the derivatives of the metric terms, the Jacobian is not needed, but the original unscaled terms are needed. This is done in the loop below. ---*/ - for(unsigned short j=0; j helpVecDerMetrics(nDim*nInt*(nMetricPerPoint-1)); - su2double *vecDerMetrics = helpVecDerMetrics.data(); + vector helpVecDerMetrics(nDim * nInt * (nMetricPerPoint - 1)); + su2double* vecDerMetrics = helpVecDerMetrics.data(); /* Carry out the matrix multiplication. The last argument is NULL, such that this gemm call is ignored in the profiling. Replace by config if it should be included. */ - blasFunctions->gemm(nDim*nInt, nMetricPerPoint-1, nDOFsGrid, matDerBasisInt, - metricGridDOFs.data(), vecDerMetrics, nullptr); + blasFunctions->gemm(nDim * nInt, nMetricPerPoint - 1, nDOFsGrid, matDerBasisInt, metricGridDOFs.data(), + vecDerMetrics, nullptr); /* Allocate the memory for the additional metric terms needed to compute the second derivatives. */ - volElem[i].metricTerms2ndDer.resize(nInt*nMetric2ndDerPerPoint); + volElem[i].metricTerms2ndDer.resize(nInt * nMetric2ndDerPerPoint); /*--- Loop over the integration points to compute the additional metric terms needed for the second derivatives. This is a combination of the original metric terms and derivatives of these terms. Make a distinction between 2D and 3D. ---*/ - switch( nDim ) { + switch (nDim) { case 2: { - /* 2D computation. Loop over the integration points. */ - for(unsigned short j=0; jGetKind_TimeIntScheme_Flow() == ADER_DG) - TimeCoefficientsPredictorADER_DG(config); + if (config->GetKind_TimeIntScheme_Flow() == ADER_DG) TimeCoefficientsPredictorADER_DG(config); /* Define the double vector to define the values of the mass matrix contributions of the standard element in the integration points. */ @@ -5697,44 +5410,41 @@ void CMeshFEM_DG::MetricTermsVolumeElements(CConfig *config) { valMMInt.resize(standardElementsSol.size()); /* Loop over the different standard elements. */ - for(unsigned long i=0; i JacVec(nInt); - su2double *Jac = JacVec.data(); + su2double* Jac = JacVec.data(); - for(unsigned short l=0; lgemv(nDOFs2, nInt, valInt, Jac, massMat.data()); /* Store the full mass matrix in volElem[i], if needed. */ - if( FullMassMatrix ) volElem[i].massMatrix = massMat; + if (FullMassMatrix) volElem[i].massMatrix = massMat; /*--- Check if the lumped mass matrix is needed. ---*/ - if( LumpedMassMatrix ) { - + if (LumpedMassMatrix) { /* Allocate the memory for the lumped mass matrix and initialize them to zero.. */ volElem[i].lumpedMassMatrix.assign(nDOFs, 0.0); /* Loop over the DOFs to compute the elements of the local lumped mass matrix. It is the sum of the absolute values of the row. */ - for(unsigned short j=0; jGetnTimeDOFsADER_DG(); - const su2double *TimeDOFs = config->GetTimeDOFsADER_DG(); + const su2double* TimeDOFs = config->GetTimeDOFsADER_DG(); /* Compute the Vandermonde matrix and its inverse in the time DOFs. */ vector rTimeDOFs(nTimeDOFs); - for(unsigned short i=0; i V(nTimeDOFs*nTimeDOFs); + vector V(nTimeDOFs * nTimeDOFs); CFEMStandardElementBase timeElement; timeElement.Vandermonde1D(nTimeDOFs, rTimeDOFs, V); @@ -5850,75 +5552,71 @@ void CMeshFEM_DG::TimeCoefficientsPredictorADER_DG(CConfig *config) { timeElement.InverseMatrix(nTimeDOFs, VInv); /* Compute the Vandermonde matrix for r = 1, i.e. the end of the interval. */ - vector rEnd(1); rEnd[0] = 1.0; + vector rEnd(1); + rEnd[0] = 1.0; vector VEnd(nTimeDOFs); timeElement.Vandermonde1D(nTimeDOFs, rEnd, VEnd); /*--- Determine the matrix products VEnd*VInv to get the correct expression for the values of the Lagrangian interpolation functions for r = 1. ---*/ vector lEnd(nTimeDOFs, 0.0); - for(unsigned short j=0; j 1.e-6) - SU2_MPI::Error( "Difference is too large to be caused by roundoff", CURRENT_FUNCTION); + if (fabs(val - 1.0) > 1.e-6) SU2_MPI::Error("Difference is too large to be caused by roundoff", CURRENT_FUNCTION); - val = 1.0/val; - for(unsigned short j=0; j MassTime(nTimeDOFs*nTimeDOFs, 0.0); - for(unsigned short j=0; j MassTime(nTimeDOFs * nTimeDOFs, 0.0); + for (unsigned short j = 0; j < nTimeDOFs; ++j) { + for (unsigned short i = 0; i < nTimeDOFs; ++i) { + const unsigned short ji = j * nTimeDOFs + i; + for (unsigned short k = 0; k < nTimeDOFs; ++k) MassTime[ji] += V[k * nTimeDOFs + j] * V[k * nTimeDOFs + i]; } } timeElement.InverseMatrix(nTimeDOFs, MassTime); /* Compute the gradient of the Vandermonde matrix in the time DOFs. */ - vector VDr(nTimeDOFs*nTimeDOFs); + vector VDr(nTimeDOFs * nTimeDOFs); timeElement.GradVandermonde1D(nTimeDOFs, rTimeDOFs, VDr); /* Compute the product VDr VInv. Store the result in V. Note that in both matrices the transpose is stored compared to the definition of Hesthaven. */ - for(unsigned short j=0; j S(nTimeDOFs*nTimeDOFs, 0.0); - for(unsigned short j=0; j S(nTimeDOFs * nTimeDOFs, 0.0); + for (unsigned short j = 0; j < nTimeDOFs; ++j) { + for (unsigned short i = 0; i < nTimeDOFs; ++i) { + const unsigned short ji = j * nTimeDOFs + i; + for (unsigned short k = 0; k < nTimeDOFs; ++k) S[ji] += MassTime[j * nTimeDOFs + k] * V[k * nTimeDOFs + i]; } } /* Compute the time coefficients of the iteration matrix in the predictor step. */ - timeCoefADER_DG.assign(nTimeDOFs*nTimeDOFs, 0.0); - for(unsigned short j=0; jGetnTimeIntegrationADER_DG(); - const su2double *TimeIntegrationPoints = config->GetTimeIntegrationADER_DG(); + unsigned short nTimeIntegrationPoints = config->GetnTimeIntegrationADER_DG(); + const su2double* TimeIntegrationPoints = config->GetTimeIntegrationADER_DG(); /* Compute the Vandermonde matrix for the time integration points. */ vector rTimeIntPoints(nTimeIntegrationPoints); - for(unsigned short i=0; i 1.e-6) - SU2_MPI::Error( "Difference is too large to be caused by roundoff", CURRENT_FUNCTION); + if (fabs(val - 1.0) > 1.e-6) SU2_MPI::Error("Difference is too large to be caused by roundoff", CURRENT_FUNCTION); - val = 1.0/val; - for(unsigned short i=0; i 1.e-6) - SU2_MPI::Error( "Difference is too large to be caused by roundoff", CURRENT_FUNCTION); + if (fabs(val - 1.0) > 1.e-6) SU2_MPI::Error("Difference is too large to be caused by roundoff", CURRENT_FUNCTION); - val = 1.0/val; - for(unsigned short i=0; i &metricTerms) { - +void CMeshFEM_DG::VolumeMetricTermsFromCoorGradients(const unsigned short nEntities, const su2double* gradCoor, + vector& metricTerms) { /*--- Convert the dxdr, dydr, etc., stored in coorGradients, to the required metric terms. Make a distinction between 2D and 3D. ---*/ - switch( nDim ) { + switch (nDim) { case 2: { - /* 2D computation. Store the offset between the r and s derivatives. */ - const unsigned short off = 2*nEntities; + const unsigned short off = 2 * nEntities; /* Loop over the entities and store the metric terms. */ unsigned short ii = 0; - for(unsigned short j=0; jGetMarker_All_KindBC(iMarker)) { case ISOTHERMAL: case HEAT_FLUX: { const string Marker_Tag = config->GetMarker_All_TagBound(iMarker); - if(config->GetWallFunction_Treatment(Marker_Tag) != WALL_FUNCTIONS::NONE) - wallFunctions = true; + if (config->GetWallFunction_Treatment(Marker_Tag) != WALL_FUNCTIONS::NONE) wallFunctions = true; break; } - default: /* Just to avoid a compiler warning. */ + default: /* Just to avoid a compiler warning. */ break; } } /* If no wall functions are used, nothing needs to be done and a return can be made. */ - if( !wallFunctions ) return; + if (!wallFunctions) return; /*--------------------------------------------------------------------------*/ /*--- Step 2. Build the local ADT of the volume elements. The halo ---*/ @@ -6153,66 +5838,61 @@ void CMeshFEM_DG::WallFunctionPreprocessing(CConfig *config) { /* Define the vectors, which store the mapping from the subelement to the parent element, subelement ID within the parent element, the element type and the connectivity of the subelements. */ - vector parentElement; + vector parentElement; vector subElementIDInParent; vector VTK_TypeElem; - vector elemConn; + vector elemConn; /* Loop over the locally stored volume elements (including halo elements) to create the connectivity of the subelements. */ - for(unsigned long l=0; l volCoor; - volCoor.reserve(nDim*meshPoints.size()); + volCoor.reserve(nDim * meshPoints.size()); - for(unsigned long l=0; lGetMarker_All_KindBC(iMarker)) { case ISOTHERMAL: case HEAT_FLUX: { const string Marker_Tag = config->GetMarker_All_TagBound(iMarker); - if(config->GetWallFunction_Treatment(Marker_Tag) != WALL_FUNCTIONS::NONE) { - + if (config->GetWallFunction_Treatment(Marker_Tag) != WALL_FUNCTIONS::NONE) { /* An LES wall model is used for this boundary marker. Determine which wall model and allocate the memory for the member variable. */ - switch (config->GetWallFunction_Treatment(Marker_Tag) ) { + switch (config->GetWallFunction_Treatment(Marker_Tag)) { case WALL_FUNCTIONS::EQUILIBRIUM_MODEL: { - if(rank == MASTER_NODE) - cout << "Marker " << Marker_Tag << " uses an Equilibrium Wall Model." << endl; + if (rank == MASTER_NODE) cout << "Marker " << Marker_Tag << " uses an Equilibrium Wall Model." << endl; boundaries[iMarker].wallModel = new CWallModel1DEQ(config, Marker_Tag); break; } case WALL_FUNCTIONS::LOGARITHMIC_MODEL: { - if(rank == MASTER_NODE) - cout << "Marker " << Marker_Tag << " uses the Reichardt and Kader analytical laws for the Wall Model." << endl; + if (rank == MASTER_NODE) + cout << "Marker " << Marker_Tag << " uses the Reichardt and Kader analytical laws for the Wall Model." + << endl; boundaries[iMarker].wallModel = new CWallModelLogLaw(config, Marker_Tag); break; @@ -6261,68 +5939,57 @@ void CMeshFEM_DG::WallFunctionPreprocessing(CConfig *config) { /* Retrieve the double information for this wall model. The height of the exchange location is the first element of this array. */ - const su2double *doubleInfo = config->GetWallFunction_DoubleInfo(Marker_Tag); + const su2double* doubleInfo = config->GetWallFunction_DoubleInfo(Marker_Tag); /* Easier storage of the surface elements and loop over them. */ - vector &surfElem = boundaries[iMarker].surfElem; - for(unsigned long l=0; l& surfElem = boundaries[iMarker].surfElem; + for (unsigned long l = 0; l < surfElem.size(); ++l) { /* Determine the corresponding standard face element and get the relevant information from it. Note that the standard element of the solution must be taken and not of the grid. */ - const unsigned short ind = surfElem[l].indStandardElement; + const unsigned short ind = surfElem[l].indStandardElement; const unsigned short nInt = standardBoundaryFacesSol[ind].GetNIntegration(); /* Allocate the memory for the memory to store the donors and the parametric weights. The donor elements are stored in an CUnsignedLong2T, such that they can be sorted. */ vector donorElements(nInt); - vector parCoorInDonor(nInt*nDim); + vector parCoorInDonor(nInt * nDim); /* Loop over the integration points. */ - for(unsigned short i=0; i= nVolElemOwned) - boundaries[iMarker].haloInfoNeededForBC = true; + if (surfElem[l].donorsWallFunction.back() >= nVolElemOwned) boundaries[iMarker].haloInfoNeededForBC = true; /* Allocate the memory of the first index of the interpolation matrices for the donordata. */ surfElem[l].matWallFunctionDonor.resize(surfElem[l].donorsWallFunction.size()); /* Loop over the different donors for the wall function data. */ - for(unsigned long j=0; j &matDonor = surfElem[l].matWallFunctionDonor[j]; + const unsigned long donor = surfElem[l].donorsWallFunction[j]; + vector& matDonor = surfElem[l].matWallFunctionDonor[j]; /* Determine the number of DOFs in the donor element. Note that the standard element of the solution must be used for this purpose. */ - const unsigned short ind = volElem[donor].indStandardElement; + const unsigned short ind = volElem[donor].indStandardElement; const unsigned short nDOFs = standardElementsSol[ind].GetNDOFs(); /* Allocate the memory for the vector used to compute the Lagrangian interpolation functions in the parametric coordinates, i.e. the interpolation weights, and for matDonor, which stores all these weights. */ - const unsigned short nIntThisDonor = surfElem[l].nIntPerWallFunctionDonor[j+1] - - surfElem[l].nIntPerWallFunctionDonor[j]; + const unsigned short nIntThisDonor = + surfElem[l].nIntPerWallFunctionDonor[j + 1] - surfElem[l].nIntPerWallFunctionDonor[j]; vector lagBasis(nDOFs); - matDonor.reserve(nIntThisDonor*nDOFs); + matDonor.reserve(nIntThisDonor * nDOFs); /* Loop over the integration points for this donor element. */ - for(unsigned short i=surfElem[l].nIntPerWallFunctionDonor[j]; - i *locDOFs[] = {standardElementsGrid[ind].GetRDOFs(), - standardElementsGrid[ind].GetSDOFs(), + const vector* locDOFs[] = {standardElementsGrid[ind].GetRDOFs(), standardElementsGrid[ind].GetSDOFs(), standardElementsGrid[ind].GetTDOFs()}; /* Create the initial guess of the parametric coordinates by interpolation in the sub-element. */ - for(unsigned short iDim=0; iDimdata(); - for(unsigned short i=0; idata(); + for (unsigned short i = 0; i < nDOFsPerSubElem; ++i) parCoor[iDim] += weightsSubElem[i] * coorDOFs[connSubElems[i]]; } /*--------------------------------------------------------------------------*/ @@ -6495,47 +6175,48 @@ void CMeshFEM_DG::HighOrderContainmentSearch(const su2double *coor, vector > dLagBasis(nDim, vector(nDOFs)); /* Abbreviate the grid DOFs of this element a bit easier. */ - const unsigned long *DOFs = volElem[parElem].nodeIDsGrid.data(); + const unsigned long* DOFs = volElem[parElem].nodeIDsGrid.data(); /* Loop over the maximum number of iterations. */ unsigned short itCount; - for(itCount=0; itCountGetLength_Ref(); + const su2double L_Ref = config->GetLength_Ref(); const su2double Omega_Ref = config->GetOmega_Ref(); - const su2double Vel_Ref = config->GetVelocity_Ref(); + const su2double Vel_Ref = config->GetVelocity_Ref(); /*--- Make a distinction between the possibilities. ---*/ - switch( Kind_Grid_Movement ) { - - /*-------------------------------------------------------------------------------------*/ + switch (Kind_Grid_Movement) { + /*-------------------------------------------------------------------------------------*/ case ROTATING_FRAME: { - /* Get the rotation rate and rotation center from config. */ - const su2double Center[] = {config->GetMotion_Origin(0), - config->GetMotion_Origin(1), - config->GetMotion_Origin(2)}; - const su2double Omega[] = {config->GetRotation_Rate(0)/Omega_Ref, - config->GetRotation_Rate(1)/Omega_Ref, - config->GetRotation_Rate(2)/Omega_Ref}; + const su2double Center[] = {config->GetMotion_Origin(0), config->GetMotion_Origin(1), + config->GetMotion_Origin(2)}; + const su2double Omega[] = {config->GetRotation_Rate(0) / Omega_Ref, config->GetRotation_Rate(1) / Omega_Ref, + config->GetRotation_Rate(2) / Omega_Ref}; /* Array used to store the distance to the rotation center. */ su2double dist[] = {0.0, 0.0, 0.0}; /* Loop over the owned volume elements. */ - for(unsigned long l=0; l &surfElem = boundaries[iMarker].surfElem; + vector& surfElem = boundaries[iMarker].surfElem; /* Check if this is a shroud boundary. */ bool shroudBoundary = false; - for(unsigned short iShroud=0; iShroudGetnMarker_Shroud(); ++iShroud) { - if(boundaries[iMarker].markerTag == config->GetMarker_Shroud(iShroud)) { + for (unsigned short iShroud = 0; iShroud < config->GetnMarker_Shroud(); ++iShroud) { + if (boundaries[iMarker].markerTag == config->GetMarker_Shroud(iShroud)) { shroudBoundary = true; break; } } /* Loop over the boundary faces of this marker. */ - for(unsigned long l=0; lGetTranslation_Rate(0)/Vel_Ref, - config->GetTranslation_Rate(1)/Vel_Ref, - config->GetTranslation_Rate(2)/Vel_Ref}; + const su2double vTrans[] = {config->GetTranslation_Rate(0) / Vel_Ref, config->GetTranslation_Rate(1) / Vel_Ref, + config->GetTranslation_Rate(2) / Vel_Ref}; /* Loop over the owned volume elements. */ - for(unsigned long l=0; l &surfElem = boundaries[iMarker].surfElem; + vector& surfElem = boundaries[iMarker].surfElem; /* Loop over the boundary faces of this marker. */ - for(unsigned long l=0; lGetSurface_Movement(MOVING_WALL)){ + if (config->GetSurface_Movement(MOVING_WALL)) { /*--- Loop over the physical boundaries. Skip the periodic boundaries. ---*/ - for(unsigned short i=0; iGetMarker_All_Moving(i) == YES) { - /* Determine the prescribed translation velocity, rotation rate and rotation center. */ - const su2double Center[] = {config->GetMotion_Origin(0), - config->GetMotion_Origin(1), + const su2double Center[] = {config->GetMotion_Origin(0), config->GetMotion_Origin(1), config->GetMotion_Origin(2)}; - const su2double Omega[] = {config->GetRotation_Rate(0)/Omega_Ref, - config->GetRotation_Rate(1)/Omega_Ref, - config->GetRotation_Rate(2)/Omega_Ref}; - const su2double vTrans[] = {config->GetTranslation_Rate(0)/Vel_Ref, - config->GetTranslation_Rate(1)/Vel_Ref, - config->GetTranslation_Rate(2)/Vel_Ref}; + const su2double Omega[] = {config->GetRotation_Rate(0) / Omega_Ref, config->GetRotation_Rate(1) / Omega_Ref, + config->GetRotation_Rate(2) / Omega_Ref}; + const su2double vTrans[] = {config->GetTranslation_Rate(0) / Vel_Ref, + config->GetTranslation_Rate(1) / Vel_Ref, + config->GetTranslation_Rate(2) / Vel_Ref}; /* Easier storage of the surface elements and loop over them. */ - vector &surfElem = boundaries[i].surfElem; - - for(unsigned long l=0; l& surfElem = boundaries[i].surfElem; + for (unsigned long l = 0; l < surfElem.size(); ++l) { /* Determine the corresponding standard face element and get the relevant information from it. Note that the standard element of the solution must be taken and not of the grid. */ - const unsigned short ind = surfElem[l].indStandardElement; + const unsigned short ind = surfElem[l].indStandardElement; const unsigned short nInt = standardBoundaryFacesSol[ind].GetNIntegration(); /* Loop over the number of integration points. */ - for(unsigned short j=0; jGetnZone(); - nPoint_P2PSend = new int[size] (); - nPoint_P2PRecv = new int[size] (); + nPoint_P2PSend = new int[size](); + nPoint_P2PRecv = new int[size](); - nVertex = new unsigned long[config->GetnMarker_All()] (); + nVertex = new unsigned long[config->GetnMarker_All()](); Tag_to_Marker = new string[config->GetnMarker_All()]; - for (unsigned short i=0; i <= config->GetnLevels_TimeAccurateLTS(); i++){ + for (unsigned short i = 0; i <= config->GetnLevels_TimeAccurateLTS(); i++) { nMatchingFacesWithHaloElem.push_back(0); } boundaries.resize(config->GetnMarker_All()); nDim = CConfig::GetnDim(config->GetMesh_FileName(), config->GetMesh_FileFormat()); - } diff --git a/Common/src/fem/fem_integration_rules.cpp b/Common/src/fem/fem_integration_rules.cpp index 6f80ee16bf7..0335b3f62cc 100644 --- a/Common/src/fem/fem_integration_rules.cpp +++ b/Common/src/fem/fem_integration_rules.cpp @@ -33,10 +33,9 @@ /*----------------------------------------------------------------------------------*/ void CFEMStandardElementBase::IntegrationPointsLine(void) { - /*--- Allocate the memory for the integration points and weights and determine them. ---*/ - nIntegration = orderExact/2 + 1; + nIntegration = orderExact / 2 + 1; rIntegration.resize(nIntegration); wIntegration.resize(nIntegration); @@ -44,39 +43,37 @@ void CFEMStandardElementBase::IntegrationPointsLine(void) { } void CFEMStandardElementBase::IntegrationPointsQuadrilateral(void) { - /*--- The 2D quadrature rule is a tensor product of the 1D Gauss-Legendre quadrature rule. First determine the number of integration points in 1D, which is stored in M, and determine them. ---*/ - unsigned short M = orderExact/2 + 1; + unsigned short M = orderExact / 2 + 1; vector GLPoints(M), GLWeights(M); GaussLegendrePoints1D(GLPoints, GLWeights); /*--- Allocate the memory for the integration points and weights and determine them. ---*/ - nIntegration = M*M; + nIntegration = M * M; rIntegration.resize(nIntegration); sIntegration.resize(nIntegration); wIntegration.resize(nIntegration); unsigned int ii = 0; - for(unsigned short j=0; j GLPoints(M), GLWeights(M); GaussLegendrePoints1D(GLPoints, GLWeights); @@ -84,95 +81,147 @@ void CFEMStandardElementBase::IntegrationPointsPrism(void) { /*--- Also determine the integration rule for a triangle. ---*/ IntegrationPointsTriangle(); - unsigned short nIntTriangle = nIntegration; - vector rTriangle = rIntegration; - vector sTriangle = sIntegration; - vector wTriangle = wIntegration; + unsigned short nIntTriangle = nIntegration; + vector rTriangle = rIntegration; + vector sTriangle = sIntegration; + vector wTriangle = wIntegration; /*--- Allocate the memory for the integration points and weights of the prism and determine them. ---*/ - nIntegration = M*nIntTriangle; + nIntegration = M * nIntTriangle; rIntegration.resize(nIntegration); sIntegration.resize(nIntegration); tIntegration.resize(nIntegration); wIntegration.resize(nIntegration); unsigned int ii = 0; - for(unsigned short k=0; k GLPoints(M), GLWeights(M); GaussLegendrePoints1D(GLPoints, GLWeights); /*--- Allocate the memory for the integration points and weights of the hexahedron and determine them. ---*/ - nIntegration = M*M*M; + nIntegration = M * M * M; rIntegration.resize(nIntegration); sIntegration.resize(nIntegration); tIntegration.resize(nIntegration); wIntegration.resize(nIntegration); unsigned int ii = 0; - for(unsigned short k=0; k GLPoints(M), GLWeights(M); GaussLegendrePoints1D(GLPoints, GLWeights); @@ -3305,23 +10279,23 @@ void CFEMStandardElementBase::IntegrationPointsPyramid(void) { /*--- Allocate the memory for the integration points and weights of the pyramid and determine them. ---*/ - nIntegration = M*M*M; + nIntegration = M * M * M; rIntegration.resize(nIntegration); sIntegration.resize(nIntegration); tIntegration.resize(nIntegration); wIntegration.resize(nIntegration); unsigned int ii = 0; - for(unsigned short k=0; k &A) { - - /*--- Check the dimensions of A. ---*/ - unsigned long nEntities = n*n; - if(A.size() != nEntities) - SU2_MPI::Error("Wrong size of the A matrix in InverseMatrix", CURRENT_FUNCTION); +void CFEMStandardElementBase::InverseMatrix(unsigned short n, vector& A) { + /*--- Check the dimensions of A. ---*/ + unsigned long nEntities = n * n; + if (A.size() != nEntities) SU2_MPI::Error("Wrong size of the A matrix in InverseMatrix", CURRENT_FUNCTION); /*--- Create a local matrix to carry out the actual inversion. ---*/ - vector > augmentedmatrix(n, vector(2*n)); + vector > augmentedmatrix(n, vector(2 * n)); /*--- Copy the data from A into the first part of augmentedmatrix. Note that A is stored in column major order, such that also Lapack routines can be used to invert the matrix. ---*/ unsigned int ii = 0; - for(unsigned short j=0; j valMax){ + if (val > valMax) { jj = i; valMax = val; } } /* Swap the rows j and jj, if needed. */ - if(jj > j) { - for(unsigned short k=j; k<2*n; ++k) { - su2double valTmp = augmentedmatrix[j][k]; - augmentedmatrix[j][k] = augmentedmatrix[jj][k]; + if (jj > j) { + for (unsigned short k = j; k < 2 * n; ++k) { + su2double valTmp = augmentedmatrix[j][k]; + augmentedmatrix[j][k] = augmentedmatrix[jj][k]; augmentedmatrix[jj][k] = valTmp; } } /*--- Performing row operations to form required identity matrix out of the input matrix. ---*/ - for(unsigned short i=0; i &r, - vector &V) { - +void CFEMStandardElementBase::Vandermonde1D(unsigned short nDOFs, const vector& r, vector& V) { /*--- Determine the number or rows of the Vandermonde matrix and check if the dimension of V is correct. ---*/ unsigned short nRows = r.size(); - unsigned long nEntities = nRows*nDOFs; - if(V.size() != nEntities) - SU2_MPI::Error("Wrong size of the V matrix", CURRENT_FUNCTION); + unsigned long nEntities = nRows * nDOFs; + if (V.size() != nEntities) SU2_MPI::Error("Wrong size of the V matrix", CURRENT_FUNCTION); /*--- Compute the Vandermonde matrix. ---*/ unsigned int ii = 0; - for(unsigned short i=0; i &r, - vector &VDr) { - +void CFEMStandardElementBase::GradVandermonde1D(unsigned short nDOFs, const vector& r, + vector& VDr) { /*--- Determine the number or rows of the gradient of the Vandermonde matrix and check if the dimension of VDr is correct. ---*/ unsigned short nRows = r.size(); - unsigned long nEntities = nRows*nDOFs; - if(VDr.size() != nEntities) - SU2_MPI::Error("Wrong size of the VDr matrix", CURRENT_FUNCTION); + unsigned long nEntities = nRows * nDOFs; + if (VDr.size() != nEntities) SU2_MPI::Error("Wrong size of the VDr matrix", CURRENT_FUNCTION); /*--- Compute the gradient of the Vandermonde matrix. ---*/ unsigned int ii = 0; - for(unsigned short i=0; i 0) { + if (val_orderExact > 0) { orderExact = val_orderExact; - } - else { - if( constJacobian ) - orderExact = (unsigned short) ceil(val_nPoly*config->GetQuadrature_Factor_Straight()); + } else { + if (constJacobian) + orderExact = (unsigned short)ceil(val_nPoly * config->GetQuadrature_Factor_Straight()); else - orderExact = (unsigned short) ceil(val_nPoly*config->GetQuadrature_Factor_Curved()); + orderExact = (unsigned short)ceil(val_nPoly * config->GetQuadrature_Factor_Curved()); } /*--- Determine the integration points. This depends on the element type. ---*/ - switch( VTK_Type ) { - case LINE: IntegrationPointsLine(); break; - case TRIANGLE: IntegrationPointsTriangle(); break; - case QUADRILATERAL: IntegrationPointsQuadrilateral(); break; - case TETRAHEDRON: IntegrationPointsTetrahedron(); break; - case PYRAMID: IntegrationPointsPyramid(); break; - case PRISM: IntegrationPointsPrism(); break; - case HEXAHEDRON: IntegrationPointsHexahedron(); break; + switch (VTK_Type) { + case LINE: + IntegrationPointsLine(); + break; + case TRIANGLE: + IntegrationPointsTriangle(); + break; + case QUADRILATERAL: + IntegrationPointsQuadrilateral(); + break; + case TETRAHEDRON: + IntegrationPointsTetrahedron(); + break; + case PYRAMID: + IntegrationPointsPyramid(); + break; + case PRISM: + IntegrationPointsPrism(); + break; + case HEXAHEDRON: + IntegrationPointsHexahedron(); + break; } } -void CFEMStandardElementBase::CheckSumDerivativesLagrangianBasisFunctions( - const unsigned short nPoints, - const unsigned short nDOFs, - const vector &dLagBasisPoints) { - +void CFEMStandardElementBase::CheckSumDerivativesLagrangianBasisFunctions(const unsigned short nPoints, + const unsigned short nDOFs, + const vector& dLagBasisPoints) { /*--- Check for a zero sum of the derivatives in the given points. ---*/ - for(unsigned short j=0; j 1.e-6) - SU2_MPI::Error("Difference is too large to be caused by roundoff", CURRENT_FUNCTION); + if (fabs(val) > 1.e-6) SU2_MPI::Error("Difference is too large to be caused by roundoff", CURRENT_FUNCTION); } } -void CFEMStandardElementBase::CheckSumLagrangianBasisFunctions( - const unsigned short nPoints, - const unsigned short nDOFs, - vector &lagBasisPoints) { - +void CFEMStandardElementBase::CheckSumLagrangianBasisFunctions(const unsigned short nPoints, const unsigned short nDOFs, + vector& lagBasisPoints) { /*--- To reduce the error due to round off in the Lagrangian basis functions, make sure that the row sum is 1. Also check if the difference is not too large to be solely caused by roundoff. ---*/ - for(unsigned short j=0; j 1.e-6) - SU2_MPI::Error("Difference is too large to be caused by roundoff", CURRENT_FUNCTION); + if (fabs(val - 1.0) > 1.e-6) SU2_MPI::Error("Difference is too large to be caused by roundoff", CURRENT_FUNCTION); - val = 1.0/val; - for(unsigned short i=0; i &drLagBasisIntegration, - vector &dsLagBasisIntegration, - vector &dtLagBasisIntegration) { - + unsigned short VTK_TypeElem, unsigned short nPolyElem, const bool swapFaceInElement, unsigned short& nDOFsElem, + vector& drLagBasisIntegration, vector& dsLagBasisIntegration, + vector& dtLagBasisIntegration) { /*--- Define a number of dummy variables, such that the general functions to compute the gradients of the basis functions can be used. ---*/ vector rDOFsDummy, sDOFsDummy, tDOFsDummy, matVandermondeInvDummy, lagBasisPointsDummy; /*--- Determine the type of the face. ---*/ - switch( VTK_Type ) { - + switch (VTK_Type) { case LINE: { - /*--- The face element is a line. The adjacent element can be either a triangle or a quadrilateral. In order to use the member functions LagrangianBasisFunctionAndDerivativesTriangle and @@ -308,25 +279,17 @@ void CFEMStandardElementBase::DerivativesBasisFunctionsAdjacentElement( face is face 0 of standard element, which corresponds to s = -1. ---*/ vector sInt(nIntegration, -1.0); - switch( VTK_TypeElem ) { + switch (VTK_TypeElem) { case TRIANGLE: - LagrangianBasisFunctionAndDerivativesTriangle(nPolyElem, rIntegration, - sInt, nDOFsElem, - rDOFsDummy, sDOFsDummy, - matVandermondeInvDummy, - lagBasisPointsDummy, - drLagBasisIntegration, - dsLagBasisIntegration); + LagrangianBasisFunctionAndDerivativesTriangle(nPolyElem, rIntegration, sInt, nDOFsElem, rDOFsDummy, + sDOFsDummy, matVandermondeInvDummy, lagBasisPointsDummy, + drLagBasisIntegration, dsLagBasisIntegration); break; case QUADRILATERAL: - LagrangianBasisFunctionAndDerivativesQuadrilateral(nPolyElem, rIntegration, - sInt, nDOFsElem, - rDOFsDummy, sDOFsDummy, - matVandermondeInvDummy, - lagBasisPointsDummy, - drLagBasisIntegration, - dsLagBasisIntegration); + LagrangianBasisFunctionAndDerivativesQuadrilateral(nPolyElem, rIntegration, sInt, nDOFsElem, rDOFsDummy, + sDOFsDummy, matVandermondeInvDummy, lagBasisPointsDummy, + drLagBasisIntegration, dsLagBasisIntegration); break; } @@ -334,7 +297,6 @@ void CFEMStandardElementBase::DerivativesBasisFunctionsAdjacentElement( } case TRIANGLE: { - /*---- The face element is a triangle. The adjacent element can be a tetrahedron, a pyramid or a prism. For the tetrahedron and the prism the convention is that the face is face 0 of these elements, which corresponds to a @@ -345,64 +307,46 @@ void CFEMStandardElementBase::DerivativesBasisFunctionsAdjacentElement( case, also the parametric coordinates of the integration points must be swapped in order to get the correct behavior. ---*/ - switch( VTK_TypeElem ) { - + switch (VTK_TypeElem) { case TETRAHEDRON: { vector tInt(nIntegration, -1.0); - LagrangianBasisFunctionAndDerivativesTetrahedron(nPolyElem, rIntegration, - sIntegration, tInt, - nDOFsElem, rDOFsDummy, - sDOFsDummy, tDOFsDummy, - matVandermondeInvDummy, - lagBasisPointsDummy, - drLagBasisIntegration, - dsLagBasisIntegration, - dtLagBasisIntegration); + LagrangianBasisFunctionAndDerivativesTetrahedron(nPolyElem, rIntegration, sIntegration, tInt, nDOFsElem, + rDOFsDummy, sDOFsDummy, tDOFsDummy, matVandermondeInvDummy, + lagBasisPointsDummy, drLagBasisIntegration, + dsLagBasisIntegration, dtLagBasisIntegration); break; } case PRISM: { vector tInt(nIntegration, -1.0); - LagrangianBasisFunctionAndDerivativesPrism(nPolyElem, rIntegration, - sIntegration, tInt, - nDOFsElem, rDOFsDummy, - sDOFsDummy, tDOFsDummy, - matVandermondeInvDummy, - lagBasisPointsDummy, - drLagBasisIntegration, - dsLagBasisIntegration, + LagrangianBasisFunctionAndDerivativesPrism(nPolyElem, rIntegration, sIntegration, tInt, nDOFsElem, rDOFsDummy, + sDOFsDummy, tDOFsDummy, matVandermondeInvDummy, + lagBasisPointsDummy, drLagBasisIntegration, dsLagBasisIntegration, dtLagBasisIntegration); break; } case PYRAMID: { vector rInt(nIntegration), sInt(nIntegration), tInt(nIntegration); - if( swapFaceInElement ) { - for(unsigned short i=0; i tInt(nIntegration, -1.0); - LagrangianBasisFunctionAndDerivativesHexahedron(nPolyElem, rIntegration, - sIntegration, tInt, - nDOFsElem, rDOFsDummy, - sDOFsDummy, tDOFsDummy, - matVandermondeInvDummy, - lagBasisPointsDummy, - drLagBasisIntegration, - dsLagBasisIntegration, - dtLagBasisIntegration); + LagrangianBasisFunctionAndDerivativesHexahedron(nPolyElem, rIntegration, sIntegration, tInt, nDOFsElem, + rDOFsDummy, sDOFsDummy, tDOFsDummy, matVandermondeInvDummy, + lagBasisPointsDummy, drLagBasisIntegration, + dsLagBasisIntegration, dtLagBasisIntegration); break; } case PRISM: { vector sInt(nIntegration, -1.0), rInt, tInt; - if( swapFaceInElement ) {rInt = sIntegration; tInt = rIntegration;} - else {rInt = rIntegration; tInt = sIntegration;} - - LagrangianBasisFunctionAndDerivativesPrism(nPolyElem, rInt, - sInt, tInt, - nDOFsElem, rDOFsDummy, - sDOFsDummy, tDOFsDummy, - matVandermondeInvDummy, - lagBasisPointsDummy, - drLagBasisIntegration, - dsLagBasisIntegration, - dtLagBasisIntegration); + if (swapFaceInElement) { + rInt = sIntegration; + tInt = rIntegration; + } else { + rInt = rIntegration; + tInt = sIntegration; + } + + LagrangianBasisFunctionAndDerivativesPrism( + nPolyElem, rInt, sInt, tInt, nDOFsElem, rDOFsDummy, sDOFsDummy, tDOFsDummy, matVandermondeInvDummy, + lagBasisPointsDummy, drLagBasisIntegration, dsLagBasisIntegration, dtLagBasisIntegration); break; } case PYRAMID: { vector tInt(nIntegration, -1.0); - LagrangianBasisFunctionAndDerivativesPyramid(nPolyElem, rIntegration, - sIntegration, tInt, - nDOFsElem, rDOFsDummy, - sDOFsDummy, tDOFsDummy, - matVandermondeInvDummy, - lagBasisPointsDummy, - drLagBasisIntegration, - dsLagBasisIntegration, - dtLagBasisIntegration); + LagrangianBasisFunctionAndDerivativesPyramid(nPolyElem, rIntegration, sIntegration, tInt, nDOFsElem, + rDOFsDummy, sDOFsDummy, tDOFsDummy, matVandermondeInvDummy, + lagBasisPointsDummy, drLagBasisIntegration, + dsLagBasisIntegration, dtLagBasisIntegration); break; } } @@ -479,14 +410,8 @@ void CFEMStandardElementBase::DerivativesBasisFunctionsAdjacentElement( } void CFEMStandardElementBase::LagrangianBasisFunctionAndDerivativesLine( - const unsigned short nPoly, - const vector &rPoints, - unsigned short &nDOFs, - vector &rDOFs, - vector &matVandermondeInv, - vector &lagBasisPoints, - vector &drLagBasisPoints) { - + const unsigned short nPoly, const vector& rPoints, unsigned short& nDOFs, vector& rDOFs, + vector& matVandermondeInv, vector& lagBasisPoints, vector& drLagBasisPoints) { /*--- Determine the number of points in which the functions must be determined. ---*/ const unsigned short nPoints = rPoints.size(); @@ -495,14 +420,13 @@ void CFEMStandardElementBase::LagrangianBasisFunctionAndDerivativesLine( nDOFs = nPoly + 1; rDOFs.resize(nDOFs); - su2double dh = 2.0/nPoly; - for(unsigned i=0; i V(nDOFs*nPoints); - matVandermondeInv.resize(nDOFs*nDOFs); + vector V(nDOFs * nPoints); + matVandermondeInv.resize(nDOFs * nDOFs); Vandermonde1D(nDOFs, rDOFs, matVandermondeInv); InverseMatrix(nDOFs, matVandermondeInv); @@ -515,7 +439,7 @@ void CFEMStandardElementBase::LagrangianBasisFunctionAndDerivativesLine( obtained from the matrix product V*Vinv. Note that the result is stored in row major order, because in this way the interpolation data for a point is contiguous in memory. ---*/ - lagBasisPoints.resize(nDOFs*nPoints); + lagBasisPoints.resize(nDOFs * nPoints); MatMulRowMajor(nDOFs, nPoints, V, matVandermondeInv, lagBasisPoints); /*--- Compute the gradients of the 1D Vandermonde matrix in the @@ -528,48 +452,40 @@ void CFEMStandardElementBase::LagrangianBasisFunctionAndDerivativesLine( obtained from the matrix product V*Vinv. Note that the result is stored in row major order, because in this way the gradient data for a point is contiguous in memory. ---*/ - drLagBasisPoints.resize(nDOFs*nPoints); + drLagBasisPoints.resize(nDOFs * nPoints); MatMulRowMajor(nDOFs, nPoints, V, matVandermondeInv, drLagBasisPoints); } void CFEMStandardElementBase::LagrangianBasisFunctionAndDerivativesTriangle( - const unsigned short nPoly, - const vector &rPoints, - const vector &sPoints, - unsigned short &nDOFs, - vector &rDOFs, - vector &sDOFs, - vector &matVandermondeInv, - vector &lagBasisPoints, - vector &drLagBasisPoints, - vector &dsLagBasisPoints) { - + const unsigned short nPoly, const vector& rPoints, const vector& sPoints, + unsigned short& nDOFs, vector& rDOFs, vector& sDOFs, vector& matVandermondeInv, + vector& lagBasisPoints, vector& drLagBasisPoints, vector& dsLagBasisPoints) { /*--- Determine the number of points in which the functions must be determined. ---*/ const unsigned short nPoints = rPoints.size(); /*--- Determine the location of the DOFs of the standard triangle. ---*/ - nDOFs = (nPoly+1)*(nPoly+2)/2; + nDOFs = (nPoly + 1) * (nPoly + 2) / 2; rDOFs.resize(nDOFs); sDOFs.resize(nDOFs); - su2double dh = 2.0/nPoly; + su2double dh = 2.0 / nPoly; unsigned int ii = 0; - for(unsigned short j=0; j<=nPoly; ++j) { - su2double s = -1.0 + j*dh; + for (unsigned short j = 0; j <= nPoly; ++j) { + su2double s = -1.0 + j * dh; unsigned short uppBoundI = nPoly - j; - for(unsigned short i=0; i<=uppBoundI; ++i, ++ii) { - su2double r = -1.0 + i*dh; - rDOFs[ii] = r; - sDOFs[ii] = s; + for (unsigned short i = 0; i <= uppBoundI; ++i, ++ii) { + su2double r = -1.0 + i * dh; + rDOFs[ii] = r; + sDOFs[ii] = s; } } /*--- Compute the inverse of the Vandermonde matrix in the DOFs and compute the Vandermonde matrix in the points. ---*/ - vector V(nDOFs*nPoints); - matVandermondeInv.resize(nDOFs*nDOFs); + vector V(nDOFs * nPoints); + matVandermondeInv.resize(nDOFs * nDOFs); Vandermonde2D_Triangle(nPoly, nDOFs, rDOFs, sDOFs, matVandermondeInv); InverseMatrix(nDOFs, matVandermondeInv); @@ -581,11 +497,11 @@ void CFEMStandardElementBase::LagrangianBasisFunctionAndDerivativesTriangle( coefficients from the DOFs to the points and are obtained from the matrix product V*Vinv. Note that the result is stored in row major order, because in this way the interpolation data for a point is contiguous in memory. ---*/ - lagBasisPoints.resize(nDOFs*nPoints); + lagBasisPoints.resize(nDOFs * nPoints); MatMulRowMajor(nDOFs, nPoints, V, matVandermondeInv, lagBasisPoints); /*--- Compute the gradients of the 2D Vandermonde matrix in the points. ---*/ - vector VDr(nDOFs*nPoints), VDs(nDOFs*nPoints); + vector VDr(nDOFs * nPoints), VDs(nDOFs * nPoints); GradVandermonde2D_Triangle(nPoly, nDOFs, rPoints, sPoints, VDr, VDs); /*--- Allocate the memory to store the derivatives in r- and s-direction of the @@ -594,52 +510,42 @@ void CFEMStandardElementBase::LagrangianBasisFunctionAndDerivativesTriangle( product VDr*Vinv and VDs*Vinv. Note that the result is stored in row major order, because in this way the gradient data for a point is contiguous in memory. ---*/ - drLagBasisPoints.resize(nDOFs*nPoints); - dsLagBasisPoints.resize(nDOFs*nPoints); + drLagBasisPoints.resize(nDOFs * nPoints); + dsLagBasisPoints.resize(nDOFs * nPoints); MatMulRowMajor(nDOFs, nPoints, VDr, matVandermondeInv, drLagBasisPoints); MatMulRowMajor(nDOFs, nPoints, VDs, matVandermondeInv, dsLagBasisPoints); } void CFEMStandardElementBase::LagrangianBasisFunctionAndDerivativesQuadrilateral( - const unsigned short nPoly, - const vector &rPoints, - const vector &sPoints, - unsigned short &nDOFs, - vector &rDOFs, - vector &sDOFs, - vector &matVandermondeInv, - vector &lagBasisPoints, - vector &drLagBasisPoints, - vector &dsLagBasisPoints) { - + const unsigned short nPoly, const vector& rPoints, const vector& sPoints, + unsigned short& nDOFs, vector& rDOFs, vector& sDOFs, vector& matVandermondeInv, + vector& lagBasisPoints, vector& drLagBasisPoints, vector& dsLagBasisPoints) { /*--- Determine the number of points in which the functions must be determined. ---*/ const unsigned short nPoints = rPoints.size(); /*--- Determine the location of the DOFs of the standard quadrilateral. ---*/ - nDOFs = (nPoly+1)*(nPoly+1); + nDOFs = (nPoly + 1) * (nPoly + 1); rDOFs.resize(nDOFs); sDOFs.resize(nDOFs); - su2double dh = 2.0/nPoly; + su2double dh = 2.0 / nPoly; unsigned int ii = 0; - for(unsigned short j=0; j<=nPoly; ++j) - { - su2double s = -1.0 + j*dh; - for(unsigned short i=0; i<=nPoly; ++i, ++ii) - { - su2double r = -1.0 + i*dh; - rDOFs[ii] = r; - sDOFs[ii] = s; + for (unsigned short j = 0; j <= nPoly; ++j) { + su2double s = -1.0 + j * dh; + for (unsigned short i = 0; i <= nPoly; ++i, ++ii) { + su2double r = -1.0 + i * dh; + rDOFs[ii] = r; + sDOFs[ii] = s; } } /*--- Compute the inverse of the Vandermonde matrix in the DOFs and compute the Vandermonde matrix in the points. ---*/ - vector V(nDOFs*nPoints); - matVandermondeInv.resize(nDOFs*nDOFs); + vector V(nDOFs * nPoints); + matVandermondeInv.resize(nDOFs * nDOFs); Vandermonde2D_Quadrilateral(nPoly, nDOFs, rDOFs, sDOFs, matVandermondeInv); InverseMatrix(nDOFs, matVandermondeInv); @@ -651,11 +557,11 @@ void CFEMStandardElementBase::LagrangianBasisFunctionAndDerivativesQuadrilateral coefficients from the DOFs to the points and are obtained from the matrix product V*Vinv. Note that the result is stored in row major order, because in this way the interpolation data for a point is contiguous in memory. ---*/ - lagBasisPoints.resize(nDOFs*nPoints); + lagBasisPoints.resize(nDOFs * nPoints); MatMulRowMajor(nDOFs, nPoints, V, matVandermondeInv, lagBasisPoints); /*--- Compute the gradients of the 2D Vandermonde matrix in the points. ---*/ - vector VDr(nDOFs*nPoints), VDs(nDOFs*nPoints); + vector VDr(nDOFs * nPoints), VDs(nDOFs * nPoints); GradVandermonde2D_Quadrilateral(nPoly, nDOFs, rPoints, sPoints, VDr, VDs); /*--- Allocate the memory to store the derivatives in r- and s-direction of the @@ -664,49 +570,39 @@ void CFEMStandardElementBase::LagrangianBasisFunctionAndDerivativesQuadrilateral product VDr*Vinv and VDr*Vinv. Note that the result is stored in row major order, because in this way the gradient data for a point is contiguous in memory. ---*/ - drLagBasisPoints.resize(nDOFs*nPoints); - dsLagBasisPoints.resize(nDOFs*nPoints); + drLagBasisPoints.resize(nDOFs * nPoints); + dsLagBasisPoints.resize(nDOFs * nPoints); MatMulRowMajor(nDOFs, nPoints, VDr, matVandermondeInv, drLagBasisPoints); MatMulRowMajor(nDOFs, nPoints, VDs, matVandermondeInv, dsLagBasisPoints); } void CFEMStandardElementBase::LagrangianBasisFunctionAndDerivativesTetrahedron( - const unsigned short nPoly, - const vector &rPoints, - const vector &sPoints, - const vector &tPoints, - unsigned short &nDOFs, - vector &rDOFs, - vector &sDOFs, - vector &tDOFs, - vector &matVandermondeInv, - vector &lagBasisPoints, - vector &drLagBasisPoints, - vector &dsLagBasisPoints, - vector &dtLagBasisPoints) -{ + const unsigned short nPoly, const vector& rPoints, const vector& sPoints, + const vector& tPoints, unsigned short& nDOFs, vector& rDOFs, vector& sDOFs, + vector& tDOFs, vector& matVandermondeInv, vector& lagBasisPoints, + vector& drLagBasisPoints, vector& dsLagBasisPoints, vector& dtLagBasisPoints) { /*--- Determine the number of points in which the functions must be determined. ---*/ const unsigned short nPoints = rPoints.size(); /*--- Determine the location of the DOFs of the standard tetrahedron. ---*/ - nDOFs = (nPoly+1)*(nPoly+2)*(nPoly+3)/6; + nDOFs = (nPoly + 1) * (nPoly + 2) * (nPoly + 3) / 6; rDOFs.resize(nDOFs); sDOFs.resize(nDOFs); tDOFs.resize(nDOFs); - su2double dh = 2.0/nPoly; + su2double dh = 2.0 / nPoly; unsigned int ii = 0; - for(unsigned short k=0; k<=nPoly; ++k) { - su2double t = -1.0 + k*dh; + for (unsigned short k = 0; k <= nPoly; ++k) { + su2double t = -1.0 + k * dh; unsigned short uppBoundJ = nPoly - k; - for(unsigned short j=0; j<=uppBoundJ; ++j) { - su2double s = -1.0 + j*dh; + for (unsigned short j = 0; j <= uppBoundJ; ++j) { + su2double s = -1.0 + j * dh; unsigned short uppBoundI = nPoly - k - j; - for(unsigned short i=0; i<=uppBoundI; ++i, ++ii) { - su2double r = -1.0 + i*dh; + for (unsigned short i = 0; i <= uppBoundI; ++i, ++ii) { + su2double r = -1.0 + i * dh; rDOFs[ii] = r; sDOFs[ii] = s; tDOFs[ii] = t; @@ -716,10 +612,10 @@ void CFEMStandardElementBase::LagrangianBasisFunctionAndDerivativesTetrahedron( /*--- Compute the inverse of the Vandermonde matrix in the DOFs and compute the Vandermonde matrix in the points. ---*/ - vector V(nDOFs*nPoints); - matVandermondeInv.resize(nDOFs*nDOFs); + vector V(nDOFs * nPoints); + matVandermondeInv.resize(nDOFs * nDOFs); - Vandermonde3D_Tetrahedron(nPoly, nDOFs, rDOFs, sDOFs, tDOFs, matVandermondeInv ); + Vandermonde3D_Tetrahedron(nPoly, nDOFs, rDOFs, sDOFs, tDOFs, matVandermondeInv); InverseMatrix(nDOFs, matVandermondeInv); Vandermonde3D_Tetrahedron(nPoly, nDOFs, rPoints, sPoints, tPoints, V); @@ -729,13 +625,12 @@ void CFEMStandardElementBase::LagrangianBasisFunctionAndDerivativesTetrahedron( coefficients from the DOFs to the points and are obtained from the matrix product V*Vinv. Note that the result is stored in row major order, because in this way the interpolation data for a point is contiguous in memory. ---*/ - lagBasisPoints.resize(nDOFs*nPoints); + lagBasisPoints.resize(nDOFs * nPoints); MatMulRowMajor(nDOFs, nPoints, V, matVandermondeInv, lagBasisPoints); /*--- Compute the gradients of the 3D Vandermonde matrix in the points. ---*/ - vector VDr(nDOFs*nPoints), VDs(nDOFs*nPoints), VDt(nDOFs*nPoints); - GradVandermonde3D_Tetrahedron(nPoly, nDOFs, rPoints, sPoints, - tPoints, VDr, VDs, VDt); + vector VDr(nDOFs * nPoints), VDs(nDOFs * nPoints), VDt(nDOFs * nPoints); + GradVandermonde3D_Tetrahedron(nPoly, nDOFs, rPoints, sPoints, tPoints, VDr, VDs, VDt); /*--- Allocate the memory to store the derivatives in r-, s- and t-direction of the Lagrange basis functions in the points and determine them. The @@ -743,9 +638,9 @@ void CFEMStandardElementBase::LagrangianBasisFunctionAndDerivativesTetrahedron( from the matrix product VDr*Vinv, VDr*Vinv and VDt*Vinv. Note that the result is stored in row major order, because in this way the gradient data for a point is contiguous in memory. ---*/ - drLagBasisPoints.resize(nDOFs*nPoints); - dsLagBasisPoints.resize(nDOFs*nPoints); - dtLagBasisPoints.resize(nDOFs*nPoints); + drLagBasisPoints.resize(nDOFs * nPoints); + dsLagBasisPoints.resize(nDOFs * nPoints); + dtLagBasisPoints.resize(nDOFs * nPoints); MatMulRowMajor(nDOFs, nPoints, VDr, matVandermondeInv, drLagBasisPoints); MatMulRowMajor(nDOFs, nPoints, VDs, matVandermondeInv, dsLagBasisPoints); @@ -753,54 +648,43 @@ void CFEMStandardElementBase::LagrangianBasisFunctionAndDerivativesTetrahedron( } void CFEMStandardElementBase::LagrangianBasisFunctionAndDerivativesPyramid( - const unsigned short nPoly, - const vector &rPoints, - const vector &sPoints, - const vector &tPoints, - unsigned short &nDOFs, - vector &rDOFs, - vector &sDOFs, - vector &tDOFs, - vector &matVandermondeInv, - vector &lagBasisPoints, - vector &drLagBasisPoints, - vector &dsLagBasisPoints, - vector &dtLagBasisPoints) -{ + const unsigned short nPoly, const vector& rPoints, const vector& sPoints, + const vector& tPoints, unsigned short& nDOFs, vector& rDOFs, vector& sDOFs, + vector& tDOFs, vector& matVandermondeInv, vector& lagBasisPoints, + vector& drLagBasisPoints, vector& dsLagBasisPoints, vector& dtLagBasisPoints) { /*--- Determine the number of points in which the functions must be determined. ---*/ const unsigned short nPoints = rPoints.size(); /*--- Allocate the memory for the DOFs of the standard pyramid. ---*/ - unsigned short nDOFsEdge = nPoly+1; - nDOFs = nDOFsEdge*(nDOFsEdge+1)*(2*nDOFsEdge+1)/6; + unsigned short nDOFsEdge = nPoly + 1; + nDOFs = nDOFsEdge * (nDOFsEdge + 1) * (2 * nDOFsEdge + 1) / 6; rDOFs.resize(nDOFs); sDOFs.resize(nDOFs); tDOFs.resize(nDOFs); /*--- Determine the location of the DOFs of the standard pyramid. The outer loop is in the k-direction, which is from base to top. ---*/ - su2double dt = 2.0/nPoly; + su2double dt = 2.0 / nPoly; unsigned short mPoly = nPoly; - unsigned int ii = 0; - - for(unsigned short k=0; k<=nPoly; ++k, --mPoly) { + unsigned int ii = 0; + for (unsigned short k = 0; k <= nPoly; ++k, --mPoly) { /*--- Determine the minimum and maximum value for r and s for this t-value. ---*/ - su2double t = -1.0 + k*dt; - su2double rsMin = 0.5*(t-1.0); + su2double t = -1.0 + k * dt; + su2double rsMin = 0.5 * (t - 1.0); su2double rsMax = -rsMin; /*--- Determine the step size along the edges of the current quad. Take the exceptional situation mPoly == 0 into account to avoid a division by zero. ---*/ - su2double dh = mPoly ? (rsMax-rsMin)/mPoly : su2double(0.0); + su2double dh = mPoly ? (rsMax - rsMin) / mPoly : su2double(0.0); /*--- Loop over the vertices of the current quadrilateral. ---*/ - for(unsigned short j=0; j<=mPoly; ++j) { - su2double s = rsMin + j*dh; - for(unsigned short i=0; i<=mPoly; ++i, ++ii) { - su2double r = rsMin + i*dh; + for (unsigned short j = 0; j <= mPoly; ++j) { + su2double s = rsMin + j * dh; + for (unsigned short i = 0; i <= mPoly; ++i, ++ii) { + su2double r = rsMin + i * dh; rDOFs[ii] = r; sDOFs[ii] = s; tDOFs[ii] = t; @@ -810,8 +694,8 @@ void CFEMStandardElementBase::LagrangianBasisFunctionAndDerivativesPyramid( /*--- Compute the inverse of the Vandermonde matrix in the DOFs and compute the Vandermonde matrix in the points. ---*/ - vector V(nDOFs*nPoints); - matVandermondeInv.resize(nDOFs*nDOFs); + vector V(nDOFs * nPoints); + matVandermondeInv.resize(nDOFs * nDOFs); Vandermonde3D_Pyramid(nPoly, nDOFs, rDOFs, sDOFs, tDOFs, matVandermondeInv); InverseMatrix(nDOFs, matVandermondeInv); @@ -823,11 +707,11 @@ void CFEMStandardElementBase::LagrangianBasisFunctionAndDerivativesPyramid( coefficients from the DOFs to the points and are obtained from the matrix product V*Vinv. Note that the result is stored in row major order, because in this way the interpolation data for a point is contiguous in memory. ---*/ - lagBasisPoints.resize(nDOFs*nPoints); + lagBasisPoints.resize(nDOFs * nPoints); MatMulRowMajor(nDOFs, nPoints, V, matVandermondeInv, lagBasisPoints); /*--- Compute the gradients of the 3D Vandermonde matrix in the points. ---*/ - vector VDr(nDOFs*nPoints), VDs(nDOFs*nPoints), VDt(nDOFs*nPoints); + vector VDr(nDOFs * nPoints), VDs(nDOFs * nPoints), VDt(nDOFs * nPoints); GradVandermonde3D_Pyramid(nPoly, nDOFs, rPoints, sPoints, tPoints, VDr, VDs, VDt); /*--- Allocate the memory to store the derivatives in r-, s- and t-direction @@ -836,9 +720,9 @@ void CFEMStandardElementBase::LagrangianBasisFunctionAndDerivativesPyramid( from the matrix product VDr*Vinv, VDr*Vinv and VDt*Vinv. Note that the result is stored in row major order, because in this way the gradient data for a point is contiguous in memory. ---*/ - drLagBasisPoints.resize(nDOFs*nPoints); - dsLagBasisPoints.resize(nDOFs*nPoints); - dtLagBasisPoints.resize(nDOFs*nPoints); + drLagBasisPoints.resize(nDOFs * nPoints); + dsLagBasisPoints.resize(nDOFs * nPoints); + dtLagBasisPoints.resize(nDOFs * nPoints); MatMulRowMajor(nDOFs, nPoints, VDr, matVandermondeInv, drLagBasisPoints); MatMulRowMajor(nDOFs, nPoints, VDs, matVandermondeInv, dsLagBasisPoints); @@ -846,43 +730,33 @@ void CFEMStandardElementBase::LagrangianBasisFunctionAndDerivativesPyramid( } void CFEMStandardElementBase::LagrangianBasisFunctionAndDerivativesPrism( - const unsigned short nPoly, - const vector &rPoints, - const vector &sPoints, - const vector &tPoints, - unsigned short &nDOFs, - vector &rDOFs, - vector &sDOFs, - vector &tDOFs, - vector &matVandermondeInv, - vector &lagBasisPoints, - vector &drLagBasisPoints, - vector &dsLagBasisPoints, - vector &dtLagBasisPoints) -{ + const unsigned short nPoly, const vector& rPoints, const vector& sPoints, + const vector& tPoints, unsigned short& nDOFs, vector& rDOFs, vector& sDOFs, + vector& tDOFs, vector& matVandermondeInv, vector& lagBasisPoints, + vector& drLagBasisPoints, vector& dsLagBasisPoints, vector& dtLagBasisPoints) { /*--- Determine the number of points in which the functions must be determined. ---*/ const unsigned short nPoints = rPoints.size(); /*--- Allocate the memory for the DOFs of the standard prism and determine its locations. ---*/ - unsigned short nDOFsEdge = nPoly+1; - nDOFs = nDOFsEdge*nDOFsEdge*(nDOFsEdge+1)/2; + unsigned short nDOFsEdge = nPoly + 1; + nDOFs = nDOFsEdge * nDOFsEdge * (nDOFsEdge + 1) / 2; rDOFs.resize(nDOFs); sDOFs.resize(nDOFs); tDOFs.resize(nDOFs); - su2double dh = 2.0/nPoly; + su2double dh = 2.0 / nPoly; unsigned short ii = 0; - for(unsigned short k=0; k<=nPoly; ++k) { - const su2double t = -1.0 + k*dh; + for (unsigned short k = 0; k <= nPoly; ++k) { + const su2double t = -1.0 + k * dh; - for(unsigned short j=0; j<=nPoly; ++j) { - su2double s = -1.0 + j*dh; + for (unsigned short j = 0; j <= nPoly; ++j) { + su2double s = -1.0 + j * dh; unsigned short uppBoundI = nPoly - j; - for(unsigned short i=0; i<=uppBoundI; ++i, ++ii) { - su2double r = -1.0 + i*dh; + for (unsigned short i = 0; i <= uppBoundI; ++i, ++ii) { + su2double r = -1.0 + i * dh; rDOFs[ii] = r; sDOFs[ii] = s; tDOFs[ii] = t; @@ -892,8 +766,8 @@ void CFEMStandardElementBase::LagrangianBasisFunctionAndDerivativesPrism( /*--- Compute the inverse of the Vandermonde matrix in the DOFs and compute the Vandermonde matrix in the points. ---*/ - vector V(nDOFs*nPoints); - matVandermondeInv.resize(nDOFs*nDOFs); + vector V(nDOFs * nPoints); + matVandermondeInv.resize(nDOFs * nDOFs); Vandermonde3D_Prism(nPoly, nDOFs, rDOFs, sDOFs, tDOFs, matVandermondeInv); InverseMatrix(nDOFs, matVandermondeInv); @@ -905,12 +779,12 @@ void CFEMStandardElementBase::LagrangianBasisFunctionAndDerivativesPrism( coefficients from the DOFs to the points and are obtained from the matrix product V*Vinv. Note that the result is stored in row major order, because in this way the interpolation data for a point is contiguous in memory. ---*/ - lagBasisPoints.resize(nDOFs*nPoints); + lagBasisPoints.resize(nDOFs * nPoints); MatMulRowMajor(nDOFs, nPoints, V, matVandermondeInv, lagBasisPoints); /*--- Compute the gradients of the 3D Vandermonde matrix in the points. ---*/ - vector VDr(nDOFs*nPoints), VDs(nDOFs*nPoints), VDt(nDOFs*nPoints); - GradVandermonde3D_Prism(nPoly, nDOFs,rPoints, sPoints, tPoints, VDr, VDs, VDt); + vector VDr(nDOFs * nPoints), VDs(nDOFs * nPoints), VDt(nDOFs * nPoints); + GradVandermonde3D_Prism(nPoly, nDOFs, rPoints, sPoints, tPoints, VDr, VDs, VDt); /*--- Allocate the memory to store the derivatives in r-, s- and t-direction of the Lagrange basis functions in the points and determine them. The @@ -918,9 +792,9 @@ void CFEMStandardElementBase::LagrangianBasisFunctionAndDerivativesPrism( from the matrix product VDr*Vinv, VDr*Vinv and VDt*Vinv. Note that the the result is stored in row major order, because in this way the gradient data for a point is contiguous in memory. ---*/ - drLagBasisPoints.resize(nDOFs*nPoints); - dsLagBasisPoints.resize(nDOFs*nPoints); - dtLagBasisPoints.resize(nDOFs*nPoints); + drLagBasisPoints.resize(nDOFs * nPoints); + dsLagBasisPoints.resize(nDOFs * nPoints); + dtLagBasisPoints.resize(nDOFs * nPoints); MatMulRowMajor(nDOFs, nPoints, VDr, matVandermondeInv, drLagBasisPoints); MatMulRowMajor(nDOFs, nPoints, VDs, matVandermondeInv, dsLagBasisPoints); @@ -928,41 +802,31 @@ void CFEMStandardElementBase::LagrangianBasisFunctionAndDerivativesPrism( } void CFEMStandardElementBase::LagrangianBasisFunctionAndDerivativesHexahedron( - const unsigned short nPoly, - const vector &rPoints, - const vector &sPoints, - const vector &tPoints, - unsigned short &nDOFs, - vector &rDOFs, - vector &sDOFs, - vector &tDOFs, - vector &matVandermondeInv, - vector &lagBasisPoints, - vector &drLagBasisPoints, - vector &dsLagBasisPoints, - vector &dtLagBasisPoints) -{ + const unsigned short nPoly, const vector& rPoints, const vector& sPoints, + const vector& tPoints, unsigned short& nDOFs, vector& rDOFs, vector& sDOFs, + vector& tDOFs, vector& matVandermondeInv, vector& lagBasisPoints, + vector& drLagBasisPoints, vector& dsLagBasisPoints, vector& dtLagBasisPoints) { /*--- Determine the number of points in which the functions must be determined. ---*/ const unsigned short nPoints = rPoints.size(); /*--- Allocate the memory for the DOFs of the standard hexahedron and determine its locations. ---*/ - unsigned short nDOFsEdge = nPoly+1; - nDOFs = nDOFsEdge*nDOFsEdge*nDOFsEdge; + unsigned short nDOFsEdge = nPoly + 1; + nDOFs = nDOFsEdge * nDOFsEdge * nDOFsEdge; rDOFs.resize(nDOFs); sDOFs.resize(nDOFs); tDOFs.resize(nDOFs); - su2double dh = 2.0/nPoly; + su2double dh = 2.0 / nPoly; unsigned short ii = 0; - for(unsigned short k=0; k<=nPoly; ++k) { - su2double t = -1.0 + k*dh; - for(unsigned short j=0; j<=nPoly; ++j) { - su2double s = -1.0 + j*dh; - for(unsigned short i=0; i<=nPoly; ++i, ++ii) { - su2double r = -1.0 + i*dh; + for (unsigned short k = 0; k <= nPoly; ++k) { + su2double t = -1.0 + k * dh; + for (unsigned short j = 0; j <= nPoly; ++j) { + su2double s = -1.0 + j * dh; + for (unsigned short i = 0; i <= nPoly; ++i, ++ii) { + su2double r = -1.0 + i * dh; rDOFs[ii] = r; sDOFs[ii] = s; tDOFs[ii] = t; @@ -972,8 +836,8 @@ void CFEMStandardElementBase::LagrangianBasisFunctionAndDerivativesHexahedron( /*--- Compute the inverse of the Vandermonde matrix in the DOFs and compute the Vandermonde matrix in the points. ---*/ - vector V(nDOFs*nPoints); - matVandermondeInv.resize(nDOFs*nDOFs); + vector V(nDOFs * nPoints); + matVandermondeInv.resize(nDOFs * nDOFs); Vandermonde3D_Hexahedron(nPoly, nDOFs, rDOFs, sDOFs, tDOFs, matVandermondeInv); InverseMatrix(nDOFs, matVandermondeInv); @@ -985,11 +849,11 @@ void CFEMStandardElementBase::LagrangianBasisFunctionAndDerivativesHexahedron( coefficients from the DOFs to the points and are obtained from the matrix product V*Vinv. Note that the result is stored in row major order, because in this way the interpolation data for a point is contiguous in memory. ---*/ - lagBasisPoints.resize(nDOFs*nPoints); + lagBasisPoints.resize(nDOFs * nPoints); MatMulRowMajor(nDOFs, nPoints, V, matVandermondeInv, lagBasisPoints); /*--- Compute the gradients of the 3D Vandermonde matrix in the points. ---*/ - vector VDr(nDOFs*nPoints), VDs(nDOFs*nPoints), VDt(nDOFs*nPoints); + vector VDr(nDOFs * nPoints), VDs(nDOFs * nPoints), VDt(nDOFs * nPoints); GradVandermonde3D_Hexahedron(nPoly, nDOFs, rPoints, sPoints, tPoints, VDr, VDs, VDt); /*--- Allocate the memory to store the derivatives in r-, s- and t-direction @@ -998,97 +862,88 @@ void CFEMStandardElementBase::LagrangianBasisFunctionAndDerivativesHexahedron( from the matrix product VDr*Vinv, VDr*Vinv and VDt*Vinv. Note that the the result is stored in row major order, because in this way the gradient data for a point is contiguous in memory. ---*/ - drLagBasisPoints.resize(nDOFs*nPoints); - dsLagBasisPoints.resize(nDOFs*nPoints); - dtLagBasisPoints.resize(nDOFs*nPoints); + drLagBasisPoints.resize(nDOFs * nPoints); + dsLagBasisPoints.resize(nDOFs * nPoints); + dtLagBasisPoints.resize(nDOFs * nPoints); MatMulRowMajor(nDOFs, nPoints, VDr, matVandermondeInv, drLagBasisPoints); MatMulRowMajor(nDOFs, nPoints, VDs, matVandermondeInv, dsLagBasisPoints); MatMulRowMajor(nDOFs, nPoints, VDt, matVandermondeInv, dtLagBasisPoints); } -void CFEMStandardElementBase::MatMulRowMajor(const unsigned short nDOFs, - const unsigned short nPoints, - const vector &A, - const vector &B, - vector &C) { - +void CFEMStandardElementBase::MatMulRowMajor(const unsigned short nDOFs, const unsigned short nPoints, + const vector& A, const vector& B, + vector& C) { /*--- Check if the dimensions of the matrices correspond to the assumptions made in this function. ---*/ - const unsigned int dimA = nDOFs*nPoints; - const unsigned int dimB = nDOFs*nDOFs; + const unsigned int dimA = nDOFs * nPoints; + const unsigned int dimB = nDOFs * nDOFs; - if(A.size() != dimA || B.size() != dimB || C.size() != dimA) + if (A.size() != dimA || B.size() != dimB || C.size() != dimA) SU2_MPI::Error("Unexpected size of the matrices", CURRENT_FUNCTION); /*--- Carry out the actual matrix matrix multiplication and store the result in row major order (the matrices A and B are in column major order). ---*/ - for(unsigned short j=0; j &subConn) { - +void CFEMStandardElementBase::SubConnForPlottingLine(const unsigned short nPoly, vector& subConn) { /*--- Determine the local subconnectivity of the line element used for plotting purposes. This is rather trivial, because the line element is subdivided into nPoly linear line elements. ---*/ - unsigned short nnPoly = max(nPoly,(unsigned short) 1); - for(unsigned short i=0; i &subConn) { - +void CFEMStandardElementBase::SubConnForPlottingQuadrilateral(const unsigned short nPoly, + vector& subConn) { /*--- Determine the local subconnectivity of the quadrilateral element used for plotting purposes. Note that the connectivity of the linear subelements obey the VTK connectivity rule of a quadrilateral, which is different from the connectivity for the high order quadrilateral. ---*/ - unsigned short nnPoly = max(nPoly,(unsigned short) 1); - for(unsigned short j=0; j &subConn) { - +void CFEMStandardElementBase::SubConnForPlottingTriangle(const unsigned short nPoly, vector& subConn) { /*--- Determine the local subconnectivity of the triangular element used for plotting purposes. ---*/ unsigned short jj = 0; /*--- Loop over subedges of the left boundary of the standard triangle. ---*/ - for(unsigned short j=0; j &r, - const vector &s, - vector &V) { - +void CFEMStandardElementBase::Vandermonde2D_Triangle(unsigned short nPoly, unsigned short nDOFs, + const vector& r, const vector& s, + vector& V) { /*--- Determine the number or rows of the Vandermonde matrix and check if the dimension of V is correct. ---*/ unsigned short nRows = r.size(); - unsigned long nEntities = nRows*nDOFs; - if(V.size() != nEntities) - SU2_MPI::Error("Wrong size of the V matrix", CURRENT_FUNCTION); + unsigned long nEntities = nRows * nDOFs; + if (V.size() != nEntities) SU2_MPI::Error("Wrong size of the V matrix", CURRENT_FUNCTION); /*--- For a triangle the orthogonal basis for the reference element is obtained by a combination of a Jacobi polynomial and a Legendre polynomial. This is the result of the orthonormalization of the monomial basis. ---*/ unsigned int ii = 0; - for(unsigned short i=0; i<=nPoly; ++i) { - for(unsigned short j=0; j<=(nPoly-i); ++j) { - for(unsigned short k=0; k &r, - const vector &s, - vector &VDr, - vector &VDs) { - +void CFEMStandardElementBase::GradVandermonde2D_Triangle(unsigned short nPoly, unsigned short nDOFs, + const vector& r, const vector& s, + vector& VDr, vector& VDs) { /*--- Determine the number or rows of the gradient of the Vandermonde matrix and check if the dimensions of VDr and VDs are correct. ---*/ unsigned short nRows = r.size(); - unsigned long nEntities = nRows*nDOFs; - if(VDr.size() != nEntities || VDs.size() != nEntities) + unsigned long nEntities = nRows * nDOFs; + if (VDr.size() != nEntities || VDs.size() != nEntities) SU2_MPI::Error("Wrong size of the VDr and/or VDs matrices", CURRENT_FUNCTION); /*--- For a triangle the orthogonal basis for the reference element is obtained by a combination of a Jacobi polynomial and a Legendre polynomial. This is the result of the orthonormalization of the monomial basis. ---*/ unsigned int ii = 0; - for(unsigned short i=0; i<=nPoly; ++i) { - for(unsigned short j=0; j<=(nPoly-i); ++j) { - for(unsigned k=0; k 0) - { + if (i > 0) { su2double tmp = 1.0; - if( i-1 ) tmp = pow((1.0-b), (i-1)); + if (i - 1) tmp = pow((1.0 - b), (i - 1)); - VDr[ii] = 2.0*tmp*VDr[ii]; - VDs[ii] = (a+1.0)*tmp*VDs[ii] - i*tmp*sqrt(2.0)*fa*gb; + VDr[ii] = 2.0 * tmp * VDr[ii]; + VDs[ii] = (a + 1.0) * tmp * VDs[ii] - i * tmp * sqrt(2.0) * fa * gb; } su2double tmp = 1.0; - if( i ) tmp = pow((1.0-b), i); - VDs[ii] += sqrt(2.0)*fa*dgb*tmp; + if (i) tmp = pow((1.0 - b), i); + VDs[ii] += sqrt(2.0) * fa * dgb * tmp; } } } } -void CFEMStandardElementBase::Vandermonde2D_Quadrilateral(unsigned short nPoly, - unsigned short nDOFs, - const vector &r, - const vector &s, - vector &V) { - +void CFEMStandardElementBase::Vandermonde2D_Quadrilateral(unsigned short nPoly, unsigned short nDOFs, + const vector& r, const vector& s, + vector& V) { /*--- Determine the number or rows of the Vandermonde matrix and check if the dimension of V is correct. ---*/ unsigned short nRows = r.size(); - unsigned long nEntities = nRows*nDOFs; - if(V.size() != nEntities) - SU2_MPI::Error("Wrong size of the V matrix", CURRENT_FUNCTION); + unsigned long nEntities = nRows * nDOFs; + if (V.size() != nEntities) SU2_MPI::Error("Wrong size of the V matrix", CURRENT_FUNCTION); /*--- For a quadrilateral the basis functions are the product of the 1D basis functions, which are the normalized Legendre polynomials. The Legendre polynomials are implemented via Jacobi polynomials. ---*/ unsigned int ii = 0; - for(unsigned short i=0; i<=nPoly; ++i) { - for(unsigned short j=0; j<=nPoly; ++j) { - for(unsigned short k=0; k &r, - const vector &s, - vector &VDr, - vector &VDs) { - +void CFEMStandardElementBase::GradVandermonde2D_Quadrilateral(unsigned short nPoly, unsigned short nDOFs, + const vector& r, const vector& s, + vector& VDr, vector& VDs) { /*--- Determine the number or rows of the gradient of the Vandermonde matrix and check if the dimensions of VDr and VDs are correct. ---*/ unsigned short nRows = r.size(); - unsigned long nEntities = nRows*nDOFs; - if(VDr.size() != nEntities || VDs.size() != nEntities) + unsigned long nEntities = nRows * nDOFs; + if (VDr.size() != nEntities || VDs.size() != nEntities) SU2_MPI::Error("Wrong size of the VDr and/or VDs matrices", CURRENT_FUNCTION); /*--- For a quadrilateral the basis functions are the product of the 1D @@ -1260,80 +1099,73 @@ void CFEMStandardElementBase::GradVandermonde2D_Quadrilateral(unsigned short The Legendre polynomials are implemented via Jacobi polynomials. Hence the derivatives in r- and s-direction can be computed easily. ---*/ unsigned int ii = 0; - for(unsigned short i=0; i<=nPoly; ++i) { - for(unsigned short j=0; j<=nPoly; ++j) { - for(unsigned short k=0; k &r, - const vector &s, - const vector &t, - vector &V) { - +void CFEMStandardElementBase::Vandermonde3D_Tetrahedron(unsigned short nPoly, unsigned short nDOFs, + const vector& r, const vector& s, + const vector& t, vector& V) { /*--- Determine the number or rows of the Vandermonde matrix and check if the dimension of V is correct. ---*/ unsigned short nRows = r.size(); - unsigned long nEntities = nRows*nDOFs; - if(V.size() != nEntities) - SU2_MPI::Error("Wrong size of the V matrix", CURRENT_FUNCTION); + unsigned long nEntities = nRows * nDOFs; + if (V.size() != nEntities) SU2_MPI::Error("Wrong size of the V matrix", CURRENT_FUNCTION); /*--- For a tetrahedron the orthogonal basis for the reference element is obtained by a combination of Jacobi polynomials (of which the Legendre polynomials is a special case). This is the result of the orthonormalization of the monomial basis. ---*/ unsigned int ii = 0; - for(unsigned short i=0; i<=nPoly; ++i) { - for(unsigned short j=0; j<=(nPoly-i); ++j) { - for(unsigned short k=0; k<=(nPoly-i-j); ++k) { - for(unsigned short l=0; l &r, - const vector &s, - const vector &t, - vector &VDr, - vector &VDs, - vector &VDt) { - +void CFEMStandardElementBase::GradVandermonde3D_Tetrahedron(unsigned short nPoly, unsigned short nDOFs, + const vector& r, const vector& s, + const vector& t, vector& VDr, + vector& VDs, vector& VDt) { /*--- Determine the number or rows of the gradient of the Vandermonde matrix and check if the dimensions of VDr, VDs and VDt are correct. ---*/ unsigned short nRows = r.size(); - unsigned long nEntities = nRows*nDOFs; - if(VDr.size() != nEntities || VDs.size() != nEntities || VDt.size() != nEntities) + unsigned long nEntities = nRows * nDOFs; + if (VDr.size() != nEntities || VDs.size() != nEntities || VDt.size() != nEntities) SU2_MPI::Error("Wrong size of the VDr, VDs and VDt matrices", CURRENT_FUNCTION); /*--- For a tetrahedron the orthogonal basis for the reference element is obtained by a @@ -1342,43 +1174,46 @@ void CFEMStandardElementBase::GradVandermonde3D_Tetrahedron(unsigned short Note that the sequence of the i, j and k loop must be identical to the evaluation of the Vandermonde matrix itself. ---*/ unsigned int ii = 0; - for(unsigned short i=0; i<=nPoly; ++i) { - for(unsigned short j=0; j<=(nPoly-i); ++j) { - for(unsigned short k=0; k<=(nPoly-i-j); ++k) { - for(unsigned short l=0; l 0) { + VDr[ii] = sqrt(8.0) * dfa * gb * hc; + if (i > 0) { VDr[ii] *= 4.0; - if(i > 1 ) VDr[ii] *= pow((1.0-b), (i-1)); + if (i > 1) VDr[ii] *= pow((1.0 - b), (i - 1)); } - if(i+j > 1) VDr[ii] *= pow((1.0-c), (i+j-1)); + if (i + j > 1) VDr[ii] *= pow((1.0 - c), (i + j - 1)); /*--- Compute the derivative of the basis function w.r.t. s. As s is present in both the parameters a and b, both variables must be taken into account when the @@ -1387,24 +1222,24 @@ void CFEMStandardElementBase::GradVandermonde3D_Tetrahedron(unsigned short of the basis function w.r.t. b multiplied by dbds. This value is stored, because it is needed later on to compute the derivative w.r.t. t. ---*/ VDs[ii] = dgb; - if( i ) VDs[ii] *= pow((1.0-b), i); + if (i) VDs[ii] *= pow((1.0 - b), i); - if(i > 0) { - tmp = i*gb; - if(i > 1) tmp *= pow((1.0-b), (i-1)); + if (i > 0) { + tmp = i * gb; + if (i > 1) tmp *= pow((1.0 - b), (i - 1)); VDs[ii] -= tmp; } - if(i+j > 0) { - VDs[ii] *= 2.0*sqrt(8.0)*fa*hc; - if(i+j > 1) VDs[ii] *= pow((1.0-c), (i+j-1)); + if (i + j > 0) { + VDs[ii] *= 2.0 * sqrt(8.0) * fa * hc; + if (i + j > 1) VDs[ii] *= pow((1.0 - c), (i + j - 1)); } su2double dPsidbXdbds = VDs[ii]; /*--- Add the contribution from the derivative of the basis function w.r.t. a multiplied by dads. ---*/ - VDs[ii] += 0.5*(a+1.0)*VDr[ii]; + VDs[ii] += 0.5 * (a + 1.0) * VDr[ii]; /*--- Compute the derivative of the basis function w.r.t. t. As t is present in a, b and c, all parameters must be taken into account when the derivative is computed. Note that @@ -1412,60 +1247,55 @@ void CFEMStandardElementBase::GradVandermonde3D_Tetrahedron(unsigned short expression. The first part is the derivative of the basis function w.r.t. c, which is equal to t. ---*/ VDt[ii] = dhc; - if(i+j > 0) { - VDt[ii] *= pow((1.0-c), (i+j)); + if (i + j > 0) { + VDt[ii] *= pow((1.0 - c), (i + j)); - tmp = (i+j)*hc; - if(i+j > 1) tmp *= pow((1.0-c), (i+j-1)); + tmp = (i + j) * hc; + if (i + j > 1) tmp *= pow((1.0 - c), (i + j - 1)); VDt[ii] -= tmp; } - VDt[ii] *= sqrt(8.0)*fa*gb; - if( i) VDt[ii] *= pow((1.0-b), i); + VDt[ii] *= sqrt(8.0) * fa * gb; + if (i) VDt[ii] *= pow((1.0 - b), i); /*--- Add the contribution from the derivative of the basis function w.r.t. a multiplied by dadt and the derivative w.r.t. b multiplied by dbdt. ---*/ - VDt[ii] += 0.5*(a+1.0)*VDr[ii] + 0.5*(b+1.0)*dPsidbXdbds; + VDt[ii] += 0.5 * (a + 1.0) * VDr[ii] + 0.5 * (b + 1.0) * dPsidbXdbds; } } } } } -void CFEMStandardElementBase::Vandermonde3D_Pyramid(unsigned short nPoly, - unsigned short nDOFs, - const vector &r, - const vector &s, - const vector &t, - vector &V) { - +void CFEMStandardElementBase::Vandermonde3D_Pyramid(unsigned short nPoly, unsigned short nDOFs, + const vector& r, const vector& s, + const vector& t, vector& V) { /*--- Determine the number or rows of the Vandermonde matrix and check if the dimension of V is correct. ---*/ unsigned short nRows = r.size(); - unsigned long nEntities = nRows*nDOFs; - if(V.size() != nEntities) - SU2_MPI::Error("Wrong size of the V matrix", CURRENT_FUNCTION); + unsigned long nEntities = nRows * nDOFs; + if (V.size() != nEntities) SU2_MPI::Error("Wrong size of the V matrix", CURRENT_FUNCTION); /*--- For a pyramid the orthogonal basis for the reference element is obtained by a combination of Jacobi polynomials (of which the Legendre polynomials is a special case). This is the result of the orthonormalization of the monomial basis. ---*/ unsigned int ii = 0; - for(unsigned short i=0; i<=nPoly; ++i) { - for(unsigned short j=0; j<=nPoly; ++j) { - unsigned short muij = max(i,j); - const su2double scaleFact = pow(2,muij+1); - for(unsigned short k=0; k<=(nPoly-muij); ++k) { - for(unsigned short l=0; l &r, - const vector &s, - const vector &t, - vector &VDr, - vector &VDs, - vector &VDt) { - +void CFEMStandardElementBase::GradVandermonde3D_Pyramid(unsigned short nPoly, unsigned short nDOFs, + const vector& r, const vector& s, + const vector& t, vector& VDr, + vector& VDs, vector& VDt) { /*--- Determine the number or rows of the gradient of the Vandermonde matrix and check if the dimensions of VDr, VDs and VDt are correct. ---*/ unsigned short nRows = r.size(); - unsigned long nEntities = nRows*nDOFs; - if(VDr.size() != nEntities || VDs.size() != nEntities || VDt.size() != nEntities) + unsigned long nEntities = nRows * nDOFs; + if (VDr.size() != nEntities || VDs.size() != nEntities || VDt.size() != nEntities) SU2_MPI::Error("Wrong size of the VDr, VDs and VDt matrices", CURRENT_FUNCTION); /*--- For a pyramid the orthogonal basis for the reference element is @@ -1508,20 +1333,20 @@ void CFEMStandardElementBase::GradVandermonde3D_Pyramid(unsigned short Note that the sequence of the i, j and k loop must be identical to the evaluation of the Vandermonde matrix itself. ---*/ unsigned int ii = 0; - for(unsigned short i=0; i<=nPoly; ++i) { - for(unsigned short j=0; j<=nPoly; ++j) { - unsigned short muij = max(i,j); - const su2double scaleFact = pow(2,muij+1); - for(unsigned short k=0; k<=(nPoly-muij); ++k) { - for(unsigned short l=0; l 1) - { - su2double tmpt = pow(tmp, (muij-1)); + VDr[ii] = dfa * gb * hc; + VDs[ii] = fa * dgb * hc; + if (muij > 1) { + su2double tmpt = pow(tmp, (muij - 1)); VDr[ii] *= tmpt; VDs[ii] *= tmpt; } @@ -1559,20 +1383,20 @@ void CFEMStandardElementBase::GradVandermonde3D_Pyramid(unsigned short The first part is the derivative of the basis function w.r.t. c, which is equal to t. --*/ VDt[ii] = dhc; - if(muij > 0) VDt[ii] *= pow(tmp, muij); + if (muij > 0) VDt[ii] *= pow(tmp, muij); - if(muij > 0) { - su2double tmpt = 0.5*muij*hc; - if(muij > 1) tmpt *= pow(tmp, (muij-1)); + if (muij > 0) { + su2double tmpt = 0.5 * muij * hc; + if (muij > 1) tmpt *= pow(tmp, (muij - 1)); VDt[ii] -= tmpt; } - VDt[ii] *= fa*gb; + VDt[ii] *= fa * gb; /*--- Add the contribution from the derivative of the basis function w.r.t. a multiplied by dadt and the derivative w.r.t. b multiplied by dbdt. ---*/ - VDt[ii] += 0.5*a*VDr[ii] + 0.5*b*VDs[ii]; + VDt[ii] += 0.5 * a * VDr[ii] + 0.5 * b * VDs[ii]; /*--- Multiply the three derivatives with the scale factor to obtain the correct answers. See Vandermonde3D_Pyramid for @@ -1586,19 +1410,14 @@ void CFEMStandardElementBase::GradVandermonde3D_Pyramid(unsigned short } } -void CFEMStandardElementBase::Vandermonde3D_Prism(unsigned short nPoly, - unsigned short nDOFs, - const vector &r, - const vector &s, - const vector &t, - vector &V) { - +void CFEMStandardElementBase::Vandermonde3D_Prism(unsigned short nPoly, unsigned short nDOFs, + const vector& r, const vector& s, + const vector& t, vector& V) { /*--- Determine the number or rows of the Vandermonde matrix and check if the dimension of V is correct. ---*/ unsigned short nRows = r.size(); - unsigned long nEntities = nRows*nDOFs; - if(V.size() != nEntities) - SU2_MPI::Error("Wrong size of the V matrix", CURRENT_FUNCTION); + unsigned long nEntities = nRows * nDOFs; + if (V.size() != nEntities) SU2_MPI::Error("Wrong size of the V matrix", CURRENT_FUNCTION); /*--- For a prism the orthogonal basis for the reference element is a tensor product of the 1D basis functions in the structured direction of the prism @@ -1607,44 +1426,39 @@ void CFEMStandardElementBase::Vandermonde3D_Prism(unsigned short nPoly, polynomial. This is the result of the orthonormalization of the monomial basis. ---*/ unsigned int ii = 0; - for(unsigned short i=0; i<=nPoly; ++i) { - for(unsigned short j=0; j<=(nPoly-i); ++j) { - for(unsigned short k=0; k<=nPoly; ++k) { - for(unsigned short l=0; l &r, - const vector &s, - const vector &t, - vector &VDr, - vector &VDs, - vector &VDt) { - +void CFEMStandardElementBase::GradVandermonde3D_Prism(unsigned short nPoly, unsigned short nDOFs, + const vector& r, const vector& s, + const vector& t, vector& VDr, + vector& VDs, vector& VDt) { /*--- Determine the number or rows of the gradient of the Vandermonde matrix and check if the dimensions of VDr, VDs and VDt are correct. ---*/ unsigned short nRows = r.size(); - unsigned long nEntities = nRows*nDOFs; - if(VDr.size() != nEntities || VDs.size() != nEntities || VDt.size() != nEntities) + unsigned long nEntities = nRows * nDOFs; + if (VDr.size() != nEntities || VDs.size() != nEntities || VDt.size() != nEntities) SU2_MPI::Error("Wrong size of the VDr, VDs and VDt matrices", CURRENT_FUNCTION); /*--- For a prism the orthogonal basis for the reference element is a tensor @@ -1654,103 +1468,92 @@ void CFEMStandardElementBase::GradVandermonde3D_Prism(unsigned short nP Note that the sequence of the i, j and k loop must be identical to the evaluation of the Vandermonde matrix itself. ---*/ unsigned int ii = 0; - for(unsigned short i=0; i<=nPoly; ++i) { - for(unsigned short j=0; j<=(nPoly-i); ++j) { - for(unsigned short k=0; k<=nPoly; ++k) { - for(unsigned short l=0; l 0) - { + if (i > 0) { su2double tmp = 1.0; - if(i > 1) tmp = pow((1.0-b), (i-1)); + if (i > 1) tmp = pow((1.0 - b), (i - 1)); - VDr[ii] = 2.0*tmp*VDr[ii]; - VDs[ii] = (a+1.0)*tmp*VDs[ii] - i*tmp*sqrt(2.0)*fa*gb; + VDr[ii] = 2.0 * tmp * VDr[ii]; + VDs[ii] = (a + 1.0) * tmp * VDs[ii] - i * tmp * sqrt(2.0) * fa * gb; } su2double tmp = 1.0; - if(i > 0) tmp = pow((1.0-b), i); + if (i > 0) tmp = pow((1.0 - b), i); - VDs[ii] += sqrt(2.0)*fa*dgb*tmp; + VDs[ii] += sqrt(2.0) * fa * dgb * tmp; /*--- Multiply VDr and VDs with the contribution from the structured direction of the prism. ---*/ - VDr[ii] *= NormJacobi(k,0,0,t[l]); - VDs[ii] *= NormJacobi(k,0,0,t[l]); + VDr[ii] *= NormJacobi(k, 0, 0, t[l]); + VDs[ii] *= NormJacobi(k, 0, 0, t[l]); /*--- Compute the derivative of the basis function in the t-direction, which is the structured direction. ---*/ - VDt[ii] = sqrt(2.0)*tmp*fa*gb*GradNormJacobi(k,0,0,t[l]); + VDt[ii] = sqrt(2.0) * tmp * fa * gb * GradNormJacobi(k, 0, 0, t[l]); } } } } } -void CFEMStandardElementBase::Vandermonde3D_Hexahedron(unsigned short nPoly, - unsigned short nDOFs, - const vector &r, - const vector &s, - const vector &t, - vector &V) { - +void CFEMStandardElementBase::Vandermonde3D_Hexahedron(unsigned short nPoly, unsigned short nDOFs, + const vector& r, const vector& s, + const vector& t, vector& V) { /*--- Determine the number or rows of the Vandermonde matrix and check if the dimension of V is correct. ---*/ unsigned short nRows = r.size(); - unsigned long nEntities = nRows*nDOFs; - if(V.size() != nEntities) - SU2_MPI::Error("Wrong size of the V matrix", CURRENT_FUNCTION); + unsigned long nEntities = nRows * nDOFs; + if (V.size() != nEntities) SU2_MPI::Error("Wrong size of the V matrix", CURRENT_FUNCTION); /*--- For a hexahedron the basis functions are the tensor product of the 1D basis functions, which are the normalized Legendre polynomials. Note that the Legendre polynomials are a special kind of Jacobi polynomials. ---*/ unsigned int ii = 0; - for(unsigned short i=0; i<=nPoly; ++i) { - for(unsigned short j=0; j<=nPoly; ++j) { - for(unsigned short k=0; k<=nPoly; ++k) { - for(unsigned short l=0; l &r, - const vector &s, - const vector &t, - vector &VDr, - vector &VDs, - vector &VDt) { - +void CFEMStandardElementBase::GradVandermonde3D_Hexahedron(unsigned short nPoly, unsigned short nDOFs, + const vector& r, const vector& s, + const vector& t, vector& VDr, + vector& VDs, vector& VDt) { /*--- Determine the number or rows of the gradient of the Vandermonde matrix and check if the dimensions of VDr, VDs and VDt are correct. ---*/ unsigned short nRows = r.size(); - unsigned long nEntities = nRows*nDOFs; - if(VDr.size() != nEntities || VDs.size() != nEntities || VDt.size() != nEntities) + unsigned long nEntities = nRows * nDOFs; + if (VDr.size() != nEntities || VDs.size() != nEntities || VDt.size() != nEntities) SU2_MPI::Error("Wrong size of the VDr, VDs and VDt matrices", CURRENT_FUNCTION); /*--- For a hexahedron the basis functions are the tensor product of the 1D @@ -1760,50 +1563,49 @@ void CFEMStandardElementBase::GradVandermonde3D_Hexahedron(unsigned short Also note that the sequence of the i, j and k loop must be identical to the evaluation of the Vandermonde matrix itself. ---*/ unsigned int ii = 0; - for(unsigned short i=0; i<=nPoly; ++i) { - for(unsigned short j=0; j<=nPoly; ++j) { - for(unsigned short k=0; k<=nPoly; ++k) { - for(unsigned short l=0; l &GLPoints, - vector &GLWeights) { - +void CFEMStandardElementBase::GaussLegendrePoints1D(vector& GLPoints, vector& GLWeights) { /* The class used to determine the integration points operate on passivedoubles. Allocate the memory for the help vectors. */ vector GLPointsPas(GLPoints.size()); @@ -1829,61 +1629,56 @@ void CFEMStandardElementBase::GaussLegendrePoints1D(vector &GLPoints, GaussJacobi.GetQuadraturePoints(0.0, 0.0, -1.0, 1.0, GLPointsPas, GLWeightsPas); /* Copy the data back into GLPoints and GLWeights. */ - for(unsigned long i=0; i 0. For n == 0 the derivative is zero, because the polynomial itself is constant. ---*/ su2double grad; - if(n == 0) grad = 0.0; - else - { - su2double tmp = n*(n+alpha+beta+1.0); - grad = sqrt(tmp)*NormJacobi(n-1, alpha+1, beta+1, x); + if (n == 0) + grad = 0.0; + else { + su2double tmp = n * (n + alpha + beta + 1.0); + grad = sqrt(tmp) * NormJacobi(n - 1, alpha + 1, beta + 1, x); } /*--- Return the gradient. ---*/ @@ -1914,30 +1706,38 @@ su2double CFEMStandardElementBase::GradNormJacobi(unsigned short n, /* Public member functions of CFEMStandardElement. */ /*----------------------------------------------------------------------------------*/ -CFEMStandardElement::CFEMStandardElement(unsigned short val_VTK_Type, - unsigned short val_nPoly, - bool val_constJac, - CConfig *config, - unsigned short val_orderExact, - const vector *rLocSolDOFs, - const vector *sLocSolDOFs, - const vector *tLocSolDOFs) - - : CFEMStandardElementBase(val_VTK_Type, val_nPoly, val_constJac, - config, val_orderExact) { +CFEMStandardElement::CFEMStandardElement(unsigned short val_VTK_Type, unsigned short val_nPoly, bool val_constJac, + CConfig* config, unsigned short val_orderExact, + const vector* rLocSolDOFs, const vector* sLocSolDOFs, + const vector* tLocSolDOFs) + : CFEMStandardElementBase(val_VTK_Type, val_nPoly, val_constJac, config, val_orderExact) { /*--- Copy the function arguments to the member variables. ---*/ nPoly = val_nPoly; /*--- Determine the element type and compute the other member variables. ---*/ - switch( VTK_Type ) { - case LINE: DataStandardLine(); break; - case TRIANGLE: DataStandardTriangle(); break; - case QUADRILATERAL: DataStandardQuadrilateral(); break; - case TETRAHEDRON: DataStandardTetrahedron(); break; - case PYRAMID: DataStandardPyramid(); break; - case PRISM: DataStandardPrism(); break; - case HEXAHEDRON: DataStandardHexahedron(); break; + switch (VTK_Type) { + case LINE: + DataStandardLine(); + break; + case TRIANGLE: + DataStandardTriangle(); + break; + case QUADRILATERAL: + DataStandardQuadrilateral(); + break; + case TETRAHEDRON: + DataStandardTetrahedron(); + break; + case PYRAMID: + DataStandardPyramid(); + break; + case PRISM: + DataStandardPrism(); + break; + case HEXAHEDRON: + DataStandardHexahedron(); + break; } /*--------------------------------------------------------------------------*/ @@ -1949,24 +1749,21 @@ CFEMStandardElement::CFEMStandardElement(unsigned short val_VTK_Type, CheckSumLagrangianBasisFunctions(nIntegration, nDOFs, lagBasisIntegration); /*--- Check the sum of the derivatives of the Lagrangian basis functions. ---*/ - if( !drLagBasisIntegration.empty() ) - CheckSumDerivativesLagrangianBasisFunctions(nIntegration, nDOFs, - drLagBasisIntegration); - if( !dsLagBasisIntegration.empty() ) - CheckSumDerivativesLagrangianBasisFunctions(nIntegration, nDOFs, - dsLagBasisIntegration); - if( !dtLagBasisIntegration.empty() ) - CheckSumDerivativesLagrangianBasisFunctions(nIntegration, nDOFs, - dtLagBasisIntegration); + if (!drLagBasisIntegration.empty()) + CheckSumDerivativesLagrangianBasisFunctions(nIntegration, nDOFs, drLagBasisIntegration); + if (!dsLagBasisIntegration.empty()) + CheckSumDerivativesLagrangianBasisFunctions(nIntegration, nDOFs, dsLagBasisIntegration); + if (!dtLagBasisIntegration.empty()) + CheckSumDerivativesLagrangianBasisFunctions(nIntegration, nDOFs, dtLagBasisIntegration); /*--- Create the transpose of lagBasisIntegration. This is needed for the efficient residual computation for the ADER-DG predictor step. ---*/ lagBasisIntegrationTrans.resize(lagBasisIntegration.size()); unsigned int ii = 0; - for(unsigned short j=0; j dummyLagBasis; vector dummyMatVandermondeInv; - CreateBasisFunctionsAndMatrixDerivatives(rDOFs, sDOFs, tDOFs, - dummyMatVandermondeInv, dummyLagBasis, + CreateBasisFunctionsAndMatrixDerivatives(rDOFs, sDOFs, tDOFs, dummyMatVandermondeInv, dummyLagBasis, matDerBasisOwnDOFs); /*--------------------------------------------------------------------------*/ @@ -2056,19 +1853,18 @@ CFEMStandardElement::CFEMStandardElement(unsigned short val_VTK_Type, /* Easier storage of the offset between the derivatives for matBasisIntegration and matDerBasisSolDOFs. */ - const unsigned long offsetDerInt = nDOFs*nIntegration; - const unsigned long offsetDerDOFs = nDOFs*nDOFs; + const unsigned long offsetDerInt = nDOFs * nIntegration; + const unsigned long offsetDerDOFs = nDOFs * nDOFs; /* Determine the size of the vector to store the second derivatives of the basis functions in the integration points. */ - const unsigned long sizeMat2ndDer = offsetDerInt*nDim*(nDim+1)/2; + const unsigned long sizeMat2ndDer = offsetDerInt * nDim * (nDim + 1) / 2; mat2ndDerBasisInt.resize(sizeMat2ndDer); /* Loop over the number of dimensions to carry out the matrix multiplications. */ - const su2double *matDerBasisInt = matBasisIntegration.data(); - su2double *mat2ndDerBasisIntPoint = mat2ndDerBasisInt.data(); - for(unsigned short jDim=0; jDim &lagBasis) { - +void CFEMStandardElement::BasisFunctionsInPoint(const su2double* parCoor, vector& lagBasis) { /* Determine the number of parametric dimensions, depending on the element type. */ unsigned short nDimPar = 0; - switch(VTK_Type) { - case LINE: nDimPar = 1; break; + switch (VTK_Type) { + case LINE: + nDimPar = 1; + break; case TRIANGLE: - case QUADRILATERAL: nDimPar = 2; break; + case QUADRILATERAL: + nDimPar = 2; + break; case TETRAHEDRON: case PYRAMID: case PRISM: - case HEXAHEDRON: nDimPar = 3; break; + case HEXAHEDRON: + nDimPar = 3; + break; } /* Allocate the memory for the help vectors for computing the Vandermonde @@ -2115,12 +1913,11 @@ void CFEMStandardElement::BasisFunctionsInPoint(const su2double *parCoor, /* Copy the parametric coordinates in rPoints, such that the functions to compute the Vandermonde matrices can be used. */ - for(unsigned long i=0; i &lagBasis, - vector > &dLagBasis) { - +void CFEMStandardElement::BasisFunctionsAndDerivativesInPoint(const su2double* parCoor, vector& lagBasis, + vector >& dLagBasis) { /* Allocate the memory for the help vectors for computing the Vandermonde matrices and its derivatives. */ vector > rPoints(dLagBasis.size(), vector(1)); @@ -2169,12 +1963,11 @@ void CFEMStandardElement::BasisFunctionsAndDerivativesInPoint( /* Copy the parametric coordinates in rPoints, such that the functions to compute the Vandermonde matrices can be used. */ - for(unsigned long i=0; i &rLoc, - const vector &sLoc, - const vector &tLoc, - vector &matVandermondeInv, - vector &lagBasis, - vector &matDerBasis) { - + const vector& rLoc, const vector& sLoc, const vector& tLoc, + vector& matVandermondeInv, vector& lagBasis, vector& matDerBasis) { /* Define the variables, such that the general functions to compute the gradients of the basis functions can be used. Note that some of these variables are dummy variables. */ - unsigned short nDOFsDummy; + unsigned short nDOFsDummy; vector rDOFsDummy, sDOFsDummy, tDOFsDummy; vector drLagBasisLoc, dsLagBasisLoc, dtLagBasisLoc; /*--- Determine the element type and compute the basis functions and the gradients of the basis functions in the given DOFs. ---*/ - switch( VTK_Type ) { + switch (VTK_Type) { case LINE: - LagrangianBasisFunctionAndDerivativesLine(nPoly, rLoc, - nDOFsDummy, rDOFsDummy, - matVandermondeInv, - lagBasis, drLagBasisLoc); + LagrangianBasisFunctionAndDerivativesLine(nPoly, rLoc, nDOFsDummy, rDOFsDummy, matVandermondeInv, lagBasis, + drLagBasisLoc); break; case TRIANGLE: - LagrangianBasisFunctionAndDerivativesTriangle(nPoly, rLoc, - sLoc, nDOFsDummy, - rDOFsDummy, sDOFsDummy, - matVandermondeInv, - lagBasis, drLagBasisLoc, - dsLagBasisLoc); + LagrangianBasisFunctionAndDerivativesTriangle(nPoly, rLoc, sLoc, nDOFsDummy, rDOFsDummy, sDOFsDummy, + matVandermondeInv, lagBasis, drLagBasisLoc, dsLagBasisLoc); break; case QUADRILATERAL: - LagrangianBasisFunctionAndDerivativesQuadrilateral(nPoly, rLoc, - sLoc, nDOFsDummy, - rDOFsDummy, sDOFsDummy, - matVandermondeInv, - lagBasis, drLagBasisLoc, - dsLagBasisLoc); + LagrangianBasisFunctionAndDerivativesQuadrilateral(nPoly, rLoc, sLoc, nDOFsDummy, rDOFsDummy, sDOFsDummy, + matVandermondeInv, lagBasis, drLagBasisLoc, dsLagBasisLoc); break; case TETRAHEDRON: - LagrangianBasisFunctionAndDerivativesTetrahedron(nPoly, rLoc, - sLoc, tLoc, - nDOFsDummy, rDOFsDummy, - sDOFsDummy, tDOFsDummy, - matVandermondeInv, - lagBasis, drLagBasisLoc, - dsLagBasisLoc, - dtLagBasisLoc); + LagrangianBasisFunctionAndDerivativesTetrahedron(nPoly, rLoc, sLoc, tLoc, nDOFsDummy, rDOFsDummy, sDOFsDummy, + tDOFsDummy, matVandermondeInv, lagBasis, drLagBasisLoc, + dsLagBasisLoc, dtLagBasisLoc); break; case PYRAMID: - LagrangianBasisFunctionAndDerivativesPyramid(nPoly, rLoc, - sLoc, tLoc, - nDOFsDummy, rDOFsDummy, - sDOFsDummy, tDOFsDummy, - matVandermondeInv, - lagBasis, drLagBasisLoc, - dsLagBasisLoc, - dtLagBasisLoc); + LagrangianBasisFunctionAndDerivativesPyramid(nPoly, rLoc, sLoc, tLoc, nDOFsDummy, rDOFsDummy, sDOFsDummy, + tDOFsDummy, matVandermondeInv, lagBasis, drLagBasisLoc, + dsLagBasisLoc, dtLagBasisLoc); break; case PRISM: - LagrangianBasisFunctionAndDerivativesPrism(nPoly, rLoc, - sLoc, tLoc, - nDOFsDummy, rDOFsDummy, - sDOFsDummy, tDOFsDummy, - matVandermondeInv, - lagBasis, drLagBasisLoc, - dsLagBasisLoc, + LagrangianBasisFunctionAndDerivativesPrism(nPoly, rLoc, sLoc, tLoc, nDOFsDummy, rDOFsDummy, sDOFsDummy, + tDOFsDummy, matVandermondeInv, lagBasis, drLagBasisLoc, dsLagBasisLoc, dtLagBasisLoc); break; case HEXAHEDRON: - LagrangianBasisFunctionAndDerivativesHexahedron(nPoly, rLoc, - sLoc, tLoc, - nDOFsDummy, rDOFsDummy, - sDOFsDummy, tDOFsDummy, - matVandermondeInv, - lagBasis, drLagBasisLoc, - dsLagBasisLoc, - dtLagBasisLoc); + LagrangianBasisFunctionAndDerivativesHexahedron(nPoly, rLoc, sLoc, tLoc, nDOFsDummy, rDOFsDummy, sDOFsDummy, + tDOFsDummy, matVandermondeInv, lagBasis, drLagBasisLoc, + dsLagBasisLoc, dtLagBasisLoc); break; } @@ -2371,48 +2123,37 @@ void CFEMStandardElement::CreateBasisFunctionsAndMatrixDerivatives( CheckSumLagrangianBasisFunctions(nLoc, nDOFs, lagBasis); - if( !drLagBasisLoc.empty() ) - CheckSumDerivativesLagrangianBasisFunctions(nLoc, nDOFs, - drLagBasisLoc); - if( !dsLagBasisLoc.empty() ) - CheckSumDerivativesLagrangianBasisFunctions(nLoc, nDOFs, - dsLagBasisLoc); - if( !dtLagBasisLoc.empty() ) - CheckSumDerivativesLagrangianBasisFunctions(nLoc, nDOFs, - dtLagBasisLoc); + if (!drLagBasisLoc.empty()) CheckSumDerivativesLagrangianBasisFunctions(nLoc, nDOFs, drLagBasisLoc); + if (!dsLagBasisLoc.empty()) CheckSumDerivativesLagrangianBasisFunctions(nLoc, nDOFs, dsLagBasisLoc); + if (!dtLagBasisLoc.empty()) CheckSumDerivativesLagrangianBasisFunctions(nLoc, nDOFs, dtLagBasisLoc); /*--- For efficiency reasons drLagBasisLoc, dsLagBasisLoc and dtLagBasisLoc are stored in matDerBasis. ---*/ - const unsigned long sizeDerMat = drLagBasisLoc.size() + dsLagBasisLoc.size() - + dtLagBasisLoc.size(); + const unsigned long sizeDerMat = drLagBasisLoc.size() + dsLagBasisLoc.size() + dtLagBasisLoc.size(); matDerBasis.resize(sizeDerMat); unsigned int ii = 0; - for(unsigned long i=0; i matVandermondeInvDummy; - LagrangianBasisFunctionAndDerivativesLine(nPoly, rIntegration, nDOFs, rDOFs, - matVandermondeInvDummy, - lagBasisIntegration, - drLagBasisIntegration); + LagrangianBasisFunctionAndDerivativesLine(nPoly, rIntegration, nDOFs, rDOFs, matVandermondeInvDummy, + lagBasisIntegration, drLagBasisIntegration); /*--- Determine the local connectivity of the two "faces" of the line element. For a line element the faces are just points. ---*/ - connFace0.reserve(1); connFace0.push_back(0); - connFace1.reserve(1); connFace1.push_back(nPoly); + connFace0.reserve(1); + connFace0.push_back(0); + connFace1.reserve(1); + connFace1.push_back(nPoly); /*--- Determine the local subconnectivity used for plotting purposes. ---*/ SubConnForPlottingLine(nPoly, subConn1ForPlotting); @@ -2423,25 +2164,23 @@ void CFEMStandardElement::DataStandardLine(void) { } void CFEMStandardElement::DataStandardTriangle(void) { - /*--- Determine the Lagrangian basis functions and its derivatives in the integration points. ---*/ vector matVandermondeInvDummy; - LagrangianBasisFunctionAndDerivativesTriangle(nPoly, rIntegration, sIntegration, - nDOFs, rDOFs, sDOFs, - matVandermondeInvDummy, - lagBasisIntegration, - drLagBasisIntegration, + LagrangianBasisFunctionAndDerivativesTriangle(nPoly, rIntegration, sIntegration, nDOFs, rDOFs, sDOFs, + matVandermondeInvDummy, lagBasisIntegration, drLagBasisIntegration, dsLagBasisIntegration); /*--- Determine the local connectivity of the three "faces" of the triangle. For a triangular element the faces are just lines. Make sure that the element is to the left of the face. ---*/ - connFace0.reserve(nPoly+1); connFace1.reserve(nPoly+1); connFace2.reserve(nPoly+1); + connFace0.reserve(nPoly + 1); + connFace1.reserve(nPoly + 1); + connFace2.reserve(nPoly + 1); - for(signed short i=0; i<=nPoly; ++i) connFace0.push_back(i); - for(signed short i=0; i<=nPoly; ++i) connFace1.push_back((i+1)*(nPoly+1) - i*(i+1)/2 -1); - for(signed short i=nPoly; i>=0; --i) connFace2.push_back(i*(nPoly+1) - i*(i-1)/2); + for (signed short i = 0; i <= nPoly; ++i) connFace0.push_back(i); + for (signed short i = 0; i <= nPoly; ++i) connFace1.push_back((i + 1) * (nPoly + 1) - i * (i + 1) / 2 - 1); + for (signed short i = nPoly; i >= 0; --i) connFace2.push_back(i * (nPoly + 1) - i * (i - 1) / 2); /*--- Determine the local subconnectivity of the triangular element used for plotting purposes. ---*/ @@ -2453,30 +2192,27 @@ void CFEMStandardElement::DataStandardTriangle(void) { } void CFEMStandardElement::DataStandardQuadrilateral(void) { - /*--- Determine the Lagrangian basis functions and its derivatives in the integration points. ---*/ vector matVandermondeInvDummy; - LagrangianBasisFunctionAndDerivativesQuadrilateral(nPoly, rIntegration, - sIntegration, - nDOFs, rDOFs, sDOFs, - matVandermondeInvDummy, - lagBasisIntegration, - drLagBasisIntegration, + LagrangianBasisFunctionAndDerivativesQuadrilateral(nPoly, rIntegration, sIntegration, nDOFs, rDOFs, sDOFs, + matVandermondeInvDummy, lagBasisIntegration, drLagBasisIntegration, dsLagBasisIntegration); /*--- Determine the local connectivity of the four "faces" of the quad element. For a quad element the faces are just lines. Make sure that the element is to the left of the face. ---*/ - connFace0.reserve(nPoly+1); connFace1.reserve(nPoly+1); - connFace2.reserve(nPoly+1); connFace3.reserve(nPoly+1); + connFace0.reserve(nPoly + 1); + connFace1.reserve(nPoly + 1); + connFace2.reserve(nPoly + 1); + connFace3.reserve(nPoly + 1); - unsigned short n0 = 0, n1 = nPoly, n2 = nDOFs-1, n3 = nPoly*(nPoly+1); + unsigned short n0 = 0, n1 = nPoly, n2 = nDOFs - 1, n3 = nPoly * (nPoly + 1); - for(signed short i=n0; i<=n1; ++i) connFace0.push_back(i); - for(signed short i=n1; i<=n2; i+=(nPoly+1)) connFace1.push_back(i); - for(signed short i=n2; i>=n3; --i) connFace2.push_back(i); - for(signed short i=n3; i>=n0; i-=(nPoly+1)) connFace3.push_back(i); + for (signed short i = n0; i <= n1; ++i) connFace0.push_back(i); + for (signed short i = n1; i <= n2; i += (nPoly + 1)) connFace1.push_back(i); + for (signed short i = n2; i >= n3; --i) connFace2.push_back(i); + for (signed short i = n3; i >= n0; i -= (nPoly + 1)) connFace3.push_back(i); /*--- Determine the local subconnectivity of the quadrilateral element used for plotting purposes. ---*/ @@ -2488,35 +2224,31 @@ void CFEMStandardElement::DataStandardQuadrilateral(void) { } void CFEMStandardElement::DataStandardTetrahedron(void) { - /*--- Determine the Lagrangian basis functions and its derivatives in the integration points. ---*/ vector matVandermondeInvDummy; - LagrangianBasisFunctionAndDerivativesTetrahedron(nPoly, rIntegration, - sIntegration, tIntegration, - nDOFs, rDOFs, sDOFs, tDOFs, - matVandermondeInvDummy, - lagBasisIntegration, - drLagBasisIntegration, - dsLagBasisIntegration, - dtLagBasisIntegration); + LagrangianBasisFunctionAndDerivativesTetrahedron(nPoly, rIntegration, sIntegration, tIntegration, nDOFs, rDOFs, sDOFs, + tDOFs, matVandermondeInvDummy, lagBasisIntegration, + drLagBasisIntegration, dsLagBasisIntegration, dtLagBasisIntegration); /*--- Determine the local connectivity of the four faces of the tetrahedron. For a tetrahedron the faces are triangles. ---*/ - unsigned short nDOFsTriangle = (nPoly+1)*(nPoly+2)/2; - connFace0.reserve(nDOFsTriangle); connFace1.reserve(nDOFsTriangle); - connFace2.reserve(nDOFsTriangle); connFace3.reserve(nDOFsTriangle); + unsigned short nDOFsTriangle = (nPoly + 1) * (nPoly + 2) / 2; + connFace0.reserve(nDOFsTriangle); + connFace1.reserve(nDOFsTriangle); + connFace2.reserve(nDOFsTriangle); + connFace3.reserve(nDOFsTriangle); unsigned int ii = 0; - for(unsigned short k=0; k<=nPoly; ++k) { + for (unsigned short k = 0; k <= nPoly; ++k) { unsigned short uppBoundJ = nPoly - k; - for(unsigned short j=0; j<=uppBoundJ; ++j) { + for (unsigned short j = 0; j <= uppBoundJ; ++j) { unsigned short uppBoundI = nPoly - k - j; - for(unsigned short i=0; i<=uppBoundI; ++i, ++ii) { - if(k == 0) connFace0.push_back(ii); - if(j == 0) connFace1.push_back(ii); - if(i == 0) connFace2.push_back(ii); - if((i+j+k) == nPoly) connFace3.push_back(ii); + for (unsigned short i = 0; i <= uppBoundI; ++i, ++ii) { + if (k == 0) connFace0.push_back(ii); + if (j == 0) connFace1.push_back(ii); + if (i == 0) connFace2.push_back(ii); + if ((i + j + k) == nPoly) connFace3.push_back(ii); } } } @@ -2524,8 +2256,8 @@ void CFEMStandardElement::DataStandardTetrahedron(void) { /*--- Make sure that the element is to the left of the faces. ---*/ unsigned short n0 = 0; unsigned short n1 = nPoly; - unsigned short n2 = nDOFsTriangle -1; - unsigned short n3 = nDOFs -1; + unsigned short n2 = nDOFsTriangle - 1; + unsigned short n3 = nDOFs - 1; ChangeDirectionTriangleConn(connFace0, n0, n1, n2); ChangeDirectionTriangleConn(connFace1, n0, n3, n1); @@ -2543,23 +2275,17 @@ void CFEMStandardElement::DataStandardTetrahedron(void) { } void CFEMStandardElement::DataStandardPyramid(void) { - /*--- Determine the Lagrangian basis functions and its derivatives in the integration points. ---*/ vector matVandermondeInvDummy; - LagrangianBasisFunctionAndDerivativesPyramid(nPoly, rIntegration, - sIntegration, tIntegration, - nDOFs, rDOFs, sDOFs, tDOFs, - matVandermondeInvDummy, - lagBasisIntegration, - drLagBasisIntegration, - dsLagBasisIntegration, - dtLagBasisIntegration); + LagrangianBasisFunctionAndDerivativesPyramid(nPoly, rIntegration, sIntegration, tIntegration, nDOFs, rDOFs, sDOFs, + tDOFs, matVandermondeInvDummy, lagBasisIntegration, + drLagBasisIntegration, dsLagBasisIntegration, dtLagBasisIntegration); /*--- Determine the local connectivity of the five faces of the pyramid. For a pyramid there are four triangular faces and one quadrilateral face. ---*/ - unsigned short nDOFsQuad = (nPoly+1)*(nPoly+1); - unsigned short nDOFsTriangle = (nPoly+1)*(nPoly+2)/2; + unsigned short nDOFsQuad = (nPoly + 1) * (nPoly + 1); + unsigned short nDOFsTriangle = (nPoly + 1) * (nPoly + 2) / 2; connFace0.reserve(nDOFsQuad); connFace1.reserve(nDOFsTriangle); @@ -2569,14 +2295,14 @@ void CFEMStandardElement::DataStandardPyramid(void) { unsigned short mPoly = nPoly; unsigned int ii = 0; - for(unsigned short k=0; k<=nPoly; ++k, --mPoly) { - for(unsigned short j=0; j<=mPoly; ++j) { - for(unsigned short i=0; i<=mPoly; ++i, ++ii) { - if(k == 0) connFace0.push_back(ii); - if(j == 0) connFace1.push_back(ii); - if(j == mPoly) connFace2.push_back(ii); - if(i == 0) connFace3.push_back(ii); - if(i == mPoly) connFace4.push_back(ii); + for (unsigned short k = 0; k <= nPoly; ++k, --mPoly) { + for (unsigned short j = 0; j <= mPoly; ++j) { + for (unsigned short i = 0; i <= mPoly; ++i, ++ii) { + if (k == 0) connFace0.push_back(ii); + if (j == 0) connFace1.push_back(ii); + if (j == mPoly) connFace2.push_back(ii); + if (i == 0) connFace3.push_back(ii); + if (i == mPoly) connFace4.push_back(ii); } } } @@ -2584,9 +2310,9 @@ void CFEMStandardElement::DataStandardPyramid(void) { /*--- Make sure that the element is to the left of the faces. ---*/ unsigned short n0 = 0; unsigned short n1 = nPoly; - unsigned short n2 = nDOFsQuad -1; + unsigned short n2 = nDOFsQuad - 1; unsigned short n3 = n2 - nPoly; - unsigned short n4 = nDOFs -1; + unsigned short n4 = nDOFs - 1; ChangeDirectionQuadConn(connFace0, n0, n1, n2, n3); ChangeDirectionTriangleConn(connFace1, n0, n4, n1); @@ -2605,23 +2331,17 @@ void CFEMStandardElement::DataStandardPyramid(void) { } void CFEMStandardElement::DataStandardPrism(void) { - /*--- Determine the Lagrangian basis functions and its derivatives in the integration points. ---*/ vector matVandermondeInvDummy; - LagrangianBasisFunctionAndDerivativesPrism(nPoly, rIntegration, - sIntegration, tIntegration, - nDOFs, rDOFs, sDOFs, tDOFs, - matVandermondeInvDummy, - lagBasisIntegration, - drLagBasisIntegration, - dsLagBasisIntegration, - dtLagBasisIntegration); + LagrangianBasisFunctionAndDerivativesPrism(nPoly, rIntegration, sIntegration, tIntegration, nDOFs, rDOFs, sDOFs, + tDOFs, matVandermondeInvDummy, lagBasisIntegration, drLagBasisIntegration, + dsLagBasisIntegration, dtLagBasisIntegration); /*--- Determine the local connectivity of the five faces of the prism. For a prism there are two triangular faces and three quadrilateral faces. ---*/ - unsigned short nDOFsQuad = (nPoly+1)*(nPoly+1); - unsigned short nDOFsTriangle = (nPoly+1)*(nPoly+2)/2; + unsigned short nDOFsQuad = (nPoly + 1) * (nPoly + 1); + unsigned short nDOFsTriangle = (nPoly + 1) * (nPoly + 2) / 2; connFace0.reserve(nDOFsTriangle); connFace1.reserve(nDOFsTriangle); @@ -2630,15 +2350,15 @@ void CFEMStandardElement::DataStandardPrism(void) { connFace4.reserve(nDOFsQuad); unsigned int ii = 0; - for(unsigned short k=0; k<=nPoly; ++k) { - for(unsigned short j=0; j<=nPoly; ++j) { + for (unsigned short k = 0; k <= nPoly; ++k) { + for (unsigned short j = 0; j <= nPoly; ++j) { unsigned short uppBoundI = nPoly - j; - for(unsigned short i=0; i<=uppBoundI; ++i, ++ii) { - if(k == 0) connFace0.push_back(ii); - if(k == nPoly) connFace1.push_back(ii); - if(j == 0) connFace2.push_back(ii); - if(i == 0) connFace3.push_back(ii); - if((i+j) == nPoly) connFace4.push_back(ii); + for (unsigned short i = 0; i <= uppBoundI; ++i, ++ii) { + if (k == 0) connFace0.push_back(ii); + if (k == nPoly) connFace1.push_back(ii); + if (j == 0) connFace2.push_back(ii); + if (i == 0) connFace3.push_back(ii); + if ((i + j) == nPoly) connFace4.push_back(ii); } } } @@ -2646,10 +2366,10 @@ void CFEMStandardElement::DataStandardPrism(void) { /*--- Make sure that the element is to the left of the faces. ---*/ unsigned short n0 = 0; unsigned short n1 = nPoly; - unsigned short n2 = nDOFsTriangle -1; - unsigned short n3 = n0 + nDOFsTriangle*nPoly; - unsigned short n4 = n1 + nDOFsTriangle*nPoly; - unsigned short n5 = n2 + nDOFsTriangle*nPoly; + unsigned short n2 = nDOFsTriangle - 1; + unsigned short n3 = n0 + nDOFsTriangle * nPoly; + unsigned short n4 = n1 + nDOFsTriangle * nPoly; + unsigned short n5 = n2 + nDOFsTriangle * nPoly; ChangeDirectionTriangleConn(connFace0, n0, n1, n2); ChangeDirectionTriangleConn(connFace1, n3, n5, n4); @@ -2668,22 +2388,16 @@ void CFEMStandardElement::DataStandardPrism(void) { } void CFEMStandardElement::DataStandardHexahedron(void) { - /*--- Determine the Lagrangian basis functions and its derivatives in the integration points. ---*/ vector matVandermondeInvDummy; - LagrangianBasisFunctionAndDerivativesHexahedron(nPoly, rIntegration, - sIntegration, tIntegration, - nDOFs, rDOFs, sDOFs, tDOFs, - matVandermondeInvDummy, - lagBasisIntegration, - drLagBasisIntegration, - dsLagBasisIntegration, - dtLagBasisIntegration); + LagrangianBasisFunctionAndDerivativesHexahedron(nPoly, rIntegration, sIntegration, tIntegration, nDOFs, rDOFs, sDOFs, + tDOFs, matVandermondeInvDummy, lagBasisIntegration, + drLagBasisIntegration, dsLagBasisIntegration, dtLagBasisIntegration); /*--- Determine the local connectivity of the six faces of the hexahedron. For a hexahedron the faces are all quadrilateral faces. ---*/ - unsigned short nDOFsQuad = (nPoly+1)*(nPoly+1); + unsigned short nDOFsQuad = (nPoly + 1) * (nPoly + 1); connFace0.reserve(nDOFsQuad); connFace1.reserve(nDOFsQuad); @@ -2693,15 +2407,15 @@ void CFEMStandardElement::DataStandardHexahedron(void) { connFace5.reserve(nDOFsQuad); unsigned int ii = 0; - for(unsigned short k=0; k<=nPoly; ++k) { - for(unsigned short j=0; j<=nPoly; ++j) { - for(unsigned short i=0; i<=nPoly; ++i, ++ii) { - if(k == 0) connFace0.push_back(ii); - if(k == nPoly) connFace1.push_back(ii); - if(j == 0) connFace2.push_back(ii); - if(j == nPoly) connFace3.push_back(ii); - if(i == 0) connFace4.push_back(ii); - if(i == nPoly) connFace5.push_back(ii); + for (unsigned short k = 0; k <= nPoly; ++k) { + for (unsigned short j = 0; j <= nPoly; ++j) { + for (unsigned short i = 0; i <= nPoly; ++i, ++ii) { + if (k == 0) connFace0.push_back(ii); + if (k == nPoly) connFace1.push_back(ii); + if (j == 0) connFace2.push_back(ii); + if (j == nPoly) connFace3.push_back(ii); + if (i == 0) connFace4.push_back(ii); + if (i == nPoly) connFace5.push_back(ii); } } } @@ -2709,12 +2423,12 @@ void CFEMStandardElement::DataStandardHexahedron(void) { /*--- Make sure that the element is to the left of the faces. ---*/ unsigned short n0 = 0; unsigned short n1 = nPoly; - unsigned short n2 = nDOFsQuad -1; + unsigned short n2 = nDOFsQuad - 1; unsigned short n3 = n2 - nPoly; - unsigned short n4 = n0 + nDOFsQuad*nPoly; - unsigned short n5 = n1 + nDOFsQuad*nPoly; - unsigned short n6 = n2 + nDOFsQuad*nPoly; - unsigned short n7 = n3 + nDOFsQuad*nPoly; + unsigned short n4 = n0 + nDOFsQuad * nPoly; + unsigned short n5 = n1 + nDOFsQuad * nPoly; + unsigned short n6 = n2 + nDOFsQuad * nPoly; + unsigned short n7 = n3 + nDOFsQuad * nPoly; ChangeDirectionQuadConn(connFace0, n0, n1, n2, n3); ChangeDirectionQuadConn(connFace1, n4, n7, n6, n5); @@ -2734,20 +2448,17 @@ void CFEMStandardElement::DataStandardHexahedron(void) { } void CFEMStandardElement::SubConnTetrahedron(void) { - /*--- Initialize the number of DOFs for the current edges to the number of DOFs of the edges present in the tetrahedron. Also initialize the current k offset to zero. ---*/ unsigned short nDOFsCurrentEdges = nPoly + 1; - unsigned short offCurrentK = 0; + unsigned short offCurrentK = 0; /*--- Loop in the k-direction of the tetrahedron, which is along the edge from the first vertex to the last vertex of the tet. ---*/ - for(unsigned short k=0; k &connQuad, - unsigned short vert0, - unsigned short vert1, - unsigned short vert2, - unsigned short vert3) const { - +void CFEMStandardElement::ChangeDirectionQuadConn(vector& connQuad, unsigned short vert0, + unsigned short vert1, unsigned short vert2, + unsigned short vert3) const { /*--- Determine the indices of the 4 corner vertices of the quad. ---*/ unsigned short ind0 = 0; unsigned short ind1 = nPoly; - unsigned short ind2 = (nPoly+1)*(nPoly+1) -1; + unsigned short ind2 = (nPoly + 1) * (nPoly + 1) - 1; unsigned short ind3 = ind2 - nPoly; /*--- There exists a linear mapping from the indices of the numbering used in the @@ -3247,125 +2951,113 @@ void CFEMStandardElement::ChangeDirectionQuadConn(vector &connQu determined below. The bool verticesDontMatch is there to check if vertices do not match. This should not happen, but it is checked for security. ---*/ - signed short a=0, b=0, c=0, d=0, e=0, f=0; // Initialization to avoid a compiler warning. + signed short a = 0, b = 0, c = 0, d = 0, e = 0, f = 0; // Initialization to avoid a compiler warning. bool verticesDontMatch = false; - if(vert0 == connQuad[ind0]) { - + if (vert0 == connQuad[ind0]) { /*--- Vert0 coincides with the first vertex of the face connectivity. Set the coefficients a and d accordingly. ---*/ a = d = 0; - if(vert2 != connQuad[ind2]) verticesDontMatch = true; + if (vert2 != connQuad[ind2]) verticesDontMatch = true; /*--- Check the situation for the neighboring vertices. ---*/ - if(vert1 == connQuad[ind1]) { - + if (vert1 == connQuad[ind1]) { /*--- The vertex numbering is the same for both faces. ---*/ - if(vert3 != connQuad[ind3]) verticesDontMatch = true; - - b = f = 1; c = e = 0; - } - else if(vert1 == connQuad[ind3]) { + if (vert3 != connQuad[ind3]) verticesDontMatch = true; + b = f = 1; + c = e = 0; + } else if (vert1 == connQuad[ind3]) { /*--- The i and j numbering are swapped. ---*/ - if(vert3 != connQuad[ind1]) verticesDontMatch = true; + if (vert3 != connQuad[ind1]) verticesDontMatch = true; - b = f = 0; c = e = 1; - } - else { + b = f = 0; + c = e = 1; + } else { verticesDontMatch = true; } - } - else if(vert1 == connQuad[ind0]) { - + } else if (vert1 == connQuad[ind0]) { /*--- Vert1 coincides with the first vertex of the face connectivity. Set the coefficients a and d accordingly. ---*/ - a = nPoly; d = 0; - if(vert3 != connQuad[ind2]) verticesDontMatch = true; + a = nPoly; + d = 0; + if (vert3 != connQuad[ind2]) verticesDontMatch = true; /*--- Check the situation for the neighboring vertices. ---*/ - if(vert0 == connQuad[ind1]) { - + if (vert0 == connQuad[ind1]) { /*--- The i-direction is negated while the j-direction coincides. ---*/ - if(vert2 != connQuad[ind3]) verticesDontMatch = true; - - b = -1; f = 1; c = e = 0; - } - else if(vert0 == connQuad[ind3]) { + if (vert2 != connQuad[ind3]) verticesDontMatch = true; + b = -1; + f = 1; + c = e = 0; + } else if (vert0 == connQuad[ind3]) { /*--- The j-direction of the current face corresponds with the negative i-direction of the target, while the i-direction coincides with the j-direction of the target. ---*/ - if(vert2 != connQuad[ind1]) verticesDontMatch = true; + if (vert2 != connQuad[ind1]) verticesDontMatch = true; - b = f = 0; c = -1; e = 1; - } - else { + b = f = 0; + c = -1; + e = 1; + } else { verticesDontMatch = true; } - } - else if(vert2 == connQuad[ind0]) { - + } else if (vert2 == connQuad[ind0]) { /*--- Vert2 coincides with the first vertex of the face connectivity. Set the coefficients a and d accordingly. ---*/ a = d = nPoly; - if(vert0 != connQuad[ind2]) verticesDontMatch = true; + if (vert0 != connQuad[ind2]) verticesDontMatch = true; /*--- Check the situation for the neighboring vertices. ---*/ - if(vert1 == connQuad[ind3]) { - + if (vert1 == connQuad[ind3]) { /*--- Both the i and j-direction are negated. ---*/ - if(vert3 != connQuad[ind1]) verticesDontMatch = true; - - b = f = -1; c = e = 0; - } - else if(vert1 == connQuad[ind1]) { + if (vert3 != connQuad[ind1]) verticesDontMatch = true; + b = f = -1; + c = e = 0; + } else if (vert1 == connQuad[ind1]) { /*--- The i and j-direction are negated and swapped. ---*/ - if(vert3 != connQuad[ind3]) verticesDontMatch = true; + if (vert3 != connQuad[ind3]) verticesDontMatch = true; - b = f = 0; c = e = -1; - } - else { + b = f = 0; + c = e = -1; + } else { verticesDontMatch = true; } - } - else if(vert3 == connQuad[ind0]) { - + } else if (vert3 == connQuad[ind0]) { /*--- Vert3 coincides with the first vertex of the face connectivity. Set the coefficients a and d accordingly. ---*/ - a = 0; d = nPoly; - if(vert1 != connQuad[ind2]) verticesDontMatch = true; + a = 0; + d = nPoly; + if (vert1 != connQuad[ind2]) verticesDontMatch = true; /*--- Check the situation for the neighboring vertices. ---*/ - if(vert0 == connQuad[ind3]) { - + if (vert0 == connQuad[ind3]) { /*--- The i-direction coincides while the j-direction is negated. ---*/ - if(vert2 != connQuad[ind1]) verticesDontMatch = true; - - b = 1; f = -1; c = e = 0; - } - else if(vert0 == connQuad[ind1]) { + if (vert2 != connQuad[ind1]) verticesDontMatch = true; + b = 1; + f = -1; + c = e = 0; + } else if (vert0 == connQuad[ind1]) { /*--- The j-direction of the current face corresponds with the i-direction of the target, while the i-direction coincides with the negative j-direction of the target. ---*/ - if(vert2 != connQuad[ind3]) verticesDontMatch = true; + if (vert2 != connQuad[ind3]) verticesDontMatch = true; - b = f = 0; c = 1; e = -1; - } - else { + b = f = 0; + c = 1; + e = -1; + } else { verticesDontMatch = true; } - } - else { + } else { verticesDontMatch = true; } /*--- If non-matching vertices have been found, terminate with an error message. ---*/ - if( verticesDontMatch ) - SU2_MPI::Error("Corner vertices do not match. This should not happen.", - CURRENT_FUNCTION); + if (verticesDontMatch) SU2_MPI::Error("Corner vertices do not match. This should not happen.", CURRENT_FUNCTION); /*--- Copy the connectivity, such that things works out correctly when carrying out the renumbering. ---*/ @@ -3373,30 +3065,26 @@ void CFEMStandardElement::ChangeDirectionQuadConn(vector &connQu /*--- Loop over the vertices of the original face to copy the connectivity data. ---*/ unsigned short ind = 0; - for(unsigned short j=0; j<=nPoly; ++j) { - for(unsigned short i=0; i<=nPoly; ++i, ++ind) { - + for (unsigned short j = 0; j <= nPoly; ++j) { + for (unsigned short i = 0; i <= nPoly; ++i, ++ind) { /*--- Determine the ii and jj indices of the target, convert it to a 1D index and shore the modified index in connQuad. ---*/ - unsigned short ii = a + i*b + j*c; - unsigned short jj = d + i*e + j*f; + unsigned short ii = a + i * b + j * c; + unsigned short jj = d + i * e + j * f; - unsigned short iind = jj*(nPoly+1) + ii; + unsigned short iind = jj * (nPoly + 1) + ii; connQuad[iind] = connQuadOr[ind]; } } } -void CFEMStandardElement::ChangeDirectionTriangleConn(vector &connTriangle, - unsigned short vert0, - unsigned short vert1, - unsigned short vert2) const { - +void CFEMStandardElement::ChangeDirectionTriangleConn(vector& connTriangle, unsigned short vert0, + unsigned short vert1, unsigned short vert2) const { /*--- Determine the indices of the 3 corner vertices of the triangle. ---*/ unsigned short ind0 = 0; unsigned short ind1 = nPoly; - unsigned short ind2 = (nPoly+1)*(nPoly+2)/2 -1; + unsigned short ind2 = (nPoly + 1) * (nPoly + 2) / 2 - 1; /*--- There exists a linear mapping from the indices of the numbering used in the connectivity of this face to the indices of the target numbering. This @@ -3406,88 +3094,98 @@ void CFEMStandardElement::ChangeDirectionTriangleConn(vector &co depend on how the corner points coincide with each other. This is determined below. The bool verticesDontMatch is there to check if vertices do not match. This should not happen, but it is checked for security. ---*/ - signed short a=0, b=0, c=0, d=0, e=0, f=0; + signed short a = 0, b = 0, c = 0, d = 0, e = 0, f = 0; bool verticesDontMatch = false; - if(vert0 == connTriangle[ind0]) { - + if (vert0 == connTriangle[ind0]) { /*--- Vert0 coincides with the first vertex of the face connectivity. Check the situation for the neighboring vertices. ---*/ - if(vert1 == connTriangle[ind1]) { - + if (vert1 == connTriangle[ind1]) { /*--- The vertex numbering is the same for both faces. ---*/ - if(vert2 != connTriangle[ind2]) verticesDontMatch = true; - - a = 0; b = 1; c = 0; d = 0; e = 0; f = 1; - } - else if(vert1 == connTriangle[ind2]) { - + if (vert2 != connTriangle[ind2]) verticesDontMatch = true; + + a = 0; + b = 1; + c = 0; + d = 0; + e = 0; + f = 1; + } else if (vert1 == connTriangle[ind2]) { /*--- The ii-index corresponds to the j-index and the jj-index corresponds to i-index. ---*/ - if(vert2 != connTriangle[ind1]) verticesDontMatch = true; - - a = 0; b = 0; c = 1; d = 0; e = 1; f = 0; - } - else { + if (vert2 != connTriangle[ind1]) verticesDontMatch = true; + + a = 0; + b = 0; + c = 1; + d = 0; + e = 1; + f = 0; + } else { verticesDontMatch = true; } - } - else if(vert0 == connTriangle[ind1]) { - + } else if (vert0 == connTriangle[ind1]) { /*--- Vert0 coincides with the second vertex of the face connectivity. Check the situation for the neighboring vertices. ---*/ - if(vert1 == connTriangle[ind0]) { - + if (vert1 == connTriangle[ind0]) { /*--- The ii-index corresponds to a combination of the i and j index and the jj-index corresponds to the j-index. ---*/ - if(vert2 != connTriangle[ind2]) verticesDontMatch = true; - - a = nPoly; b = -1; c = -1; d = 0; e = 0; f = 1; - } - else if(vert1 == connTriangle[ind2]) { - + if (vert2 != connTriangle[ind2]) verticesDontMatch = true; + + a = nPoly; + b = -1; + c = -1; + d = 0; + e = 0; + f = 1; + } else if (vert1 == connTriangle[ind2]) { /*--- The jj-index corresponds to a combination of the i and j index and the ii-index corresponds to the j-index. ---*/ - if(vert2 != connTriangle[ind0]) verticesDontMatch = true; - - a = 0; b = 0; c = 1; d = nPoly; e = -1; f = -1; - } - else { + if (vert2 != connTriangle[ind0]) verticesDontMatch = true; + + a = 0; + b = 0; + c = 1; + d = nPoly; + e = -1; + f = -1; + } else { verticesDontMatch = true; } - } - else if(vert0 == connTriangle[ind2]) { - + } else if (vert0 == connTriangle[ind2]) { /*--- Vert0 coincides with the third vertex of the face connectivity. Check the situation for the neighboring vertices. ---*/ - if(vert1 == connTriangle[ind0]) { - + if (vert1 == connTriangle[ind0]) { /*--- The ii-index corresponds to a combination of the i and j index and the jj-index corresponds with the i-index. ---*/ - if(vert2 != connTriangle[ind1]) verticesDontMatch = true; - - a = nPoly; b = -1; c = -1; d = 0; e = 1; f = 0; - } - else if(vert1 == connTriangle[ind1]) { - + if (vert2 != connTriangle[ind1]) verticesDontMatch = true; + + a = nPoly; + b = -1; + c = -1; + d = 0; + e = 1; + f = 0; + } else if (vert1 == connTriangle[ind1]) { /*--- The jj-index corresponds to a combination of the i and j index and the ii-index corresponds with the i-index. ---*/ - if(vert2 != connTriangle[ind0]) verticesDontMatch = true; - - a = 0; b = 1; c = 0; d = nPoly; e = -1; f = -1; - } - else { + if (vert2 != connTriangle[ind0]) verticesDontMatch = true; + + a = 0; + b = 1; + c = 0; + d = nPoly; + e = -1; + f = -1; + } else { verticesDontMatch = true; } - } - else { + } else { verticesDontMatch = true; } /*--- If non-matching vertices have been found, terminate with an error message. ---*/ - if( verticesDontMatch ) - SU2_MPI::Error("Corner vertices do not match. This should not happen.", - CURRENT_FUNCTION); + if (verticesDontMatch) SU2_MPI::Error("Corner vertices do not match. This should not happen.", CURRENT_FUNCTION); /*--- Copy the connectivity, such that things works out correctly when carrying out the renumbering. ---*/ @@ -3495,15 +3193,14 @@ void CFEMStandardElement::ChangeDirectionTriangleConn(vector &co /*--- Loop over the vertices of the original face to copy the connectivity data. ---*/ unsigned short ind = 0; - for(unsigned short j=0; j<=nPoly; ++j) { - for(unsigned short i=0; i<=(nPoly-j); ++i, ++ind) { - + for (unsigned short j = 0; j <= nPoly; ++j) { + for (unsigned short i = 0; i <= (nPoly - j); ++i, ++ind) { /*--- Determine the ii and jj indices of the target, convert it to a 1D index and shore the modified index in connTriangle. ---*/ - unsigned short ii = a + i*b + j*c; - unsigned short jj = d + i*e + j*f; + unsigned short ii = a + i * b + j * c; + unsigned short jj = d + i * e + j * f; - unsigned short iind = jj*(nPoly+1) + ii - jj*(jj-1)/2; + unsigned short iind = jj * (nPoly + 1) + ii - jj * (jj - 1) / 2; connTriangle[iind] = connTriangleOr[ind]; } @@ -3514,25 +3211,19 @@ void CFEMStandardElement::ChangeDirectionTriangleConn(vector &co /* Public member functions of CFEMStandardInternalFace. */ /*----------------------------------------------------------------------------------*/ -CFEMStandardInternalFace::CFEMStandardInternalFace(unsigned short val_VTK_TypeFace, - unsigned short val_VTK_TypeSide0, - unsigned short val_nPolySide0, - unsigned short val_VTK_TypeSide1, - unsigned short val_nPolySide1, - bool val_constJac, - bool val_swapFaceInElementSide0, - bool val_swapFaceInElementSide1, - CConfig *config, - unsigned short val_orderExact) - - : CFEMStandardElementBase(val_VTK_TypeFace, max(val_nPolySide0, val_nPolySide1), - val_constJac, config, val_orderExact) { +CFEMStandardInternalFace::CFEMStandardInternalFace(unsigned short val_VTK_TypeFace, unsigned short val_VTK_TypeSide0, + unsigned short val_nPolySide0, unsigned short val_VTK_TypeSide1, + unsigned short val_nPolySide1, bool val_constJac, + bool val_swapFaceInElementSide0, bool val_swapFaceInElementSide1, + CConfig* config, unsigned short val_orderExact) + : CFEMStandardElementBase(val_VTK_TypeFace, max(val_nPolySide0, val_nPolySide1), val_constJac, config, + val_orderExact) { /*--- Copy the function arguments to the member variables. ---*/ - nPolyElemSide0 = val_nPolySide0; - VTK_TypeElemSide0 = val_VTK_TypeSide0; - nPolyElemSide1 = val_nPolySide1; - VTK_TypeElemSide1 = val_VTK_TypeSide1; + nPolyElemSide0 = val_nPolySide0; + VTK_TypeElemSide0 = val_VTK_TypeSide0; + nPolyElemSide1 = val_nPolySide1; + VTK_TypeElemSide1 = val_VTK_TypeSide1; swapFaceInElementSide0 = val_swapFaceInElementSide0; swapFaceInElementSide1 = val_swapFaceInElementSide1; @@ -3549,49 +3240,35 @@ CFEMStandardInternalFace::CFEMStandardInternalFace(unsigned short val_VTK_TypeFa /*--- Determine the Lagrangian basis functions and its gradients in the integration points for both sides of the face. ---*/ - switch( VTK_Type ) { + switch (VTK_Type) { case LINE: - LagrangianBasisFunctionAndDerivativesLine(nPolyElemSide0, rIntegration, nDOFsFaceSide0, - rDOFsFaceSide0, matVandermondeInvDummy, - lagBasisFaceIntegrationSide0, + LagrangianBasisFunctionAndDerivativesLine(nPolyElemSide0, rIntegration, nDOFsFaceSide0, rDOFsFaceSide0, + matVandermondeInvDummy, lagBasisFaceIntegrationSide0, drLagBasisFaceIntegrationSide0); - LagrangianBasisFunctionAndDerivativesLine(nPolyElemSide1, rIntegration, nDOFsFaceSide1, - rDOFsFaceSide1, matVandermondeInvDummy, - lagBasisFaceIntegrationSide1, + LagrangianBasisFunctionAndDerivativesLine(nPolyElemSide1, rIntegration, nDOFsFaceSide1, rDOFsFaceSide1, + matVandermondeInvDummy, lagBasisFaceIntegrationSide1, drLagBasisFaceIntegrationSide1); break; case TRIANGLE: - LagrangianBasisFunctionAndDerivativesTriangle(nPolyElemSide0, rIntegration, - sIntegration, nDOFsFaceSide0, - rDOFsFaceSide0, sDOFsFaceSide0, - matVandermondeInvDummy, - lagBasisFaceIntegrationSide0, - drLagBasisFaceIntegrationSide0, + LagrangianBasisFunctionAndDerivativesTriangle(nPolyElemSide0, rIntegration, sIntegration, nDOFsFaceSide0, + rDOFsFaceSide0, sDOFsFaceSide0, matVandermondeInvDummy, + lagBasisFaceIntegrationSide0, drLagBasisFaceIntegrationSide0, dsLagBasisFaceIntegrationSide0); - LagrangianBasisFunctionAndDerivativesTriangle(nPolyElemSide1, rIntegration, - sIntegration, nDOFsFaceSide1, - rDOFsFaceSide1, sDOFsFaceSide1, - matVandermondeInvDummy, - lagBasisFaceIntegrationSide1, - drLagBasisFaceIntegrationSide1, + LagrangianBasisFunctionAndDerivativesTriangle(nPolyElemSide1, rIntegration, sIntegration, nDOFsFaceSide1, + rDOFsFaceSide1, sDOFsFaceSide1, matVandermondeInvDummy, + lagBasisFaceIntegrationSide1, drLagBasisFaceIntegrationSide1, dsLagBasisFaceIntegrationSide1); break; case QUADRILATERAL: - LagrangianBasisFunctionAndDerivativesQuadrilateral(nPolyElemSide0, rIntegration, - sIntegration, nDOFsFaceSide0, - rDOFsFaceSide0, sDOFsFaceSide0, - matVandermondeInvDummy, - lagBasisFaceIntegrationSide0, - drLagBasisFaceIntegrationSide0, + LagrangianBasisFunctionAndDerivativesQuadrilateral(nPolyElemSide0, rIntegration, sIntegration, nDOFsFaceSide0, + rDOFsFaceSide0, sDOFsFaceSide0, matVandermondeInvDummy, + lagBasisFaceIntegrationSide0, drLagBasisFaceIntegrationSide0, dsLagBasisFaceIntegrationSide0); - LagrangianBasisFunctionAndDerivativesQuadrilateral(nPolyElemSide1, rIntegration, - sIntegration, nDOFsFaceSide1, - rDOFsFaceSide0, sDOFsFaceSide1, - matVandermondeInvDummy, - lagBasisFaceIntegrationSide1, - drLagBasisFaceIntegrationSide1, + LagrangianBasisFunctionAndDerivativesQuadrilateral(nPolyElemSide1, rIntegration, sIntegration, nDOFsFaceSide1, + rDOFsFaceSide0, sDOFsFaceSide1, matVandermondeInvDummy, + lagBasisFaceIntegrationSide1, drLagBasisFaceIntegrationSide1, dsLagBasisFaceIntegrationSide1); break; } @@ -3603,85 +3280,67 @@ CFEMStandardInternalFace::CFEMStandardInternalFace(unsigned short val_VTK_TypeFa /*--- Create the transpose versions of lagBasisFaceIntegrationSide0 and lagBasisFaceIntegrationSide1. These are needed for an efficient computation of the residual of the faces. ---*/ - lagBasisFaceIntegrationTransposeSide0.resize(nIntegration*nDOFsFaceSide0); - lagBasisFaceIntegrationTransposeSide1.resize(nIntegration*nDOFsFaceSide1); + lagBasisFaceIntegrationTransposeSide0.resize(nIntegration * nDOFsFaceSide0); + lagBasisFaceIntegrationTransposeSide1.resize(nIntegration * nDOFsFaceSide1); unsigned int ii = 0; - for(unsigned short j=0; j CMeshFEM_DG::ComputeViscousWallADT(const CConfig *config) const { - +std::unique_ptr CMeshFEM_DG::ComputeViscousWallADT(const CConfig* config) const { /*--------------------------------------------------------------------------*/ /*--- Step 1: Create the coordinates and connectivity of the linear ---*/ /*--- subelements of the local boundaries that must be taken ---*/ @@ -50,38 +49,34 @@ std::unique_ptr CMeshFEM_DG::ComputeViscousWallADT(const CConfig vector markerIDs; /* Loop over the boundary markers. */ - for(unsigned short iMarker=0; iMarkerGetMarker_All_KindBC(iMarker) == HEAT_FLUX) || - (config->GetMarker_All_KindBC(iMarker) == ISOTHERMAL) ) { - + if ((config->GetMarker_All_KindBC(iMarker) == HEAT_FLUX) || + (config->GetMarker_All_KindBC(iMarker) == ISOTHERMAL)) { /* Loop over the surface elements of this marker. */ - const vector &surfElem = boundaries[iMarker].surfElem; - for(unsigned long i=0; i& surfElem = boundaries[iMarker].surfElem; + for (unsigned long i = 0; i < surfElem.size(); ++i) { /* Set the flag of the mesh points on this surface to true. */ - for(unsigned short j=0; j CMeshFEM_DG::ComputeViscousWallADT(const CConfig vector surfaceCoor; unsigned long nVertex_SolidWall = 0; - for(unsigned long i=0; i CMeshFEM_DG::ComputeViscousWallADT(const CConfig /*--------------------------------------------------------------------------*/ /* Build the ADT. */ - std::unique_ptr WallADT(new CADTElemClass(nDim, surfaceCoor, surfaceConn, VTK_TypeElem, - markerIDs, elemIDs, true)); + std::unique_ptr WallADT( + new CADTElemClass(nDim, surfaceCoor, surfaceConn, VTK_TypeElem, markerIDs, elemIDs, true)); return WallADT; - } /*! * \brief Set wall distances a specific value */ -void CMeshFEM_DG::SetWallDistance(su2double val){ - - for(unsigned long l=0; l &surfElem = boundaries[iMarker].surfElem; - for(unsigned long l=0; l& surfElem = boundaries[iMarker].surfElem; + for (unsigned long l = 0; l < surfElem.size(); ++l) { /* Get the required data from the corresponding standard element. */ - const unsigned short ind = surfElem[l].indStandardElement; - const unsigned short nInt = standardBoundaryFacesGrid[ind].GetNIntegration(); + const unsigned short ind = surfElem[l].indStandardElement; + const unsigned short nInt = standardBoundaryFacesGrid[ind].GetNIntegration(); /* Allocate the memory for the wall distance for this boundary face. */ surfElem[l].wallDistance.resize(nInt, val); @@ -172,8 +159,7 @@ void CMeshFEM_DG::SetWallDistance(su2double val){ } } -void CMeshFEM_DG::SetWallDistance(CADTElemClass *WallADT, const CConfig* config, unsigned short iZone){ - +void CMeshFEM_DG::SetWallDistance(CADTElemClass* WallADT, const CConfig* config, unsigned short iZone) { /*--------------------------------------------------------------------------*/ /*--- Step 3: Determine the wall distance of the integration points of ---*/ /*--- locally owned volume elements. ---*/ @@ -181,26 +167,23 @@ void CMeshFEM_DG::SetWallDistance(CADTElemClass *WallADT, const CConfig* config, /*--- Loop over the owned elements to compute the wall distance in the integration points. ---*/ - for(unsigned long l=0; lIsEmpty() ) { - + if (!WallADT->IsEmpty()) { /*--- The tree is not empty. Loop over the integration points and determine the wall distance. ---*/ - for(unsigned short i=0; iDetermineNearestElement(coor, dist, markerID, elemID, rankID); volElem[l].wallDistance[i] = dist; @@ -215,25 +198,22 @@ void CMeshFEM_DG::SetWallDistance(CADTElemClass *WallADT, const CConfig* config, /*--- Loop over the owned elements to compute the wall distance in the integration points. ---*/ - for(unsigned long l=0; lIsEmpty() ) { - + if (!WallADT->IsEmpty()) { /*--- The tree is not empty. Loop over the solution DOFs and determine the wall distance. ---*/ - for(unsigned short i=0; iDetermineNearestElement(coor, dist, markerID, elemID, rankID); volElem[l].wallDistanceSolDOFs[i] = dist; @@ -246,27 +226,23 @@ void CMeshFEM_DG::SetWallDistance(CADTElemClass *WallADT, const CConfig* config, /*--- the internal matching faces. ---*/ /*--------------------------------------------------------------------------*/ - for(unsigned long l=0; lIsEmpty() ) { - + if (!WallADT->IsEmpty()) { /*--- The tree is not empty. Loop over the integration points and determine the wall distance. */ - for(unsigned short i=0; iDetermineNearestElement(coor, dist, markerID, elemID, rankID); matchingFaces[l].wallDistance[i] = dist; @@ -281,44 +257,38 @@ void CMeshFEM_DG::SetWallDistance(CADTElemClass *WallADT, const CConfig* config, /*--- Loop over the boundary markers. Make sure to exclude the periodic boundaries, because these are not physical. ---*/ - for(unsigned short iMarker=0; iMarkerGetMarker_All_KindBC(iMarker) == HEAT_FLUX || - config->GetMarker_All_KindBC(iMarker) == ISOTHERMAL; + const bool viscousWall = + config->GetMarker_All_KindBC(iMarker) == HEAT_FLUX || config->GetMarker_All_KindBC(iMarker) == ISOTHERMAL; /* Loop over the boundary faces and determine the wall distances in the integration points. */ - vector &surfElem = boundaries[iMarker].surfElem; - for(unsigned long l=0; l& surfElem = boundaries[iMarker].surfElem; + for (unsigned long l = 0; l < surfElem.size(); ++l) { /* Get the required data from the corresponding standard element. */ - const unsigned short ind = surfElem[l].indStandardElement; - const unsigned short nInt = standardBoundaryFacesGrid[ind].GetNIntegration(); + const unsigned short ind = surfElem[l].indStandardElement; + const unsigned short nInt = standardBoundaryFacesGrid[ind].GetNIntegration(); /* Allocate the memory for the wall distance for this boundary face. */ surfElem[l].wallDistance.resize(nInt); /* Check for an empty tree or a viscous wall. In those case the wall distance is set to zero. */ - if(viscousWall) { - + if (viscousWall) { /* Wall distance must be set to zero. */ - for(unsigned short i=0; iIsEmpty() ) { + for (unsigned short i = 0; i < nInt; ++i) surfElem[l].wallDistance[i] = 0.0; + } else if (!WallADT->IsEmpty()) { /*--- Not a viscous wall boundary, while viscous walls are present. The distance must be computed. Loop over the integration points and do so. ---*/ - for(unsigned short i=0; iDetermineNearestElement(coor, dist, markerID, elemID, rankID); surfElem[l].wallDistance[i] = dist; diff --git a/Common/src/fem/fem_work_estimate_metis.cpp b/Common/src/fem/fem_work_estimate_metis.cpp index 9476452d252..e00f89bf98f 100644 --- a/Common/src/fem/fem_work_estimate_metis.cpp +++ b/Common/src/fem/fem_work_estimate_metis.cpp @@ -28,28 +28,22 @@ #include "../../include/fem/fem_standard_element.hpp" -su2double CFEMStandardElement::WorkEstimateMetis(CConfig *config) { - +su2double CFEMStandardElement::WorkEstimateMetis(CConfig* config) { /* TEMPORARY IMPLEMENTATION. */ - return nIntegration + 0.1*nDOFs; + return nIntegration + 0.1 * nDOFs; } -su2double CFEMStandardInternalFace::WorkEstimateMetis(CConfig *config) { - +su2double CFEMStandardInternalFace::WorkEstimateMetis(CConfig* config) { /* TEMPORARY IMPLEMENTATION. */ - return 2.0*nIntegration + 0.05*(nDOFsFaceSide0 + nDOFsFaceSide1); + return 2.0 * nIntegration + 0.05 * (nDOFsFaceSide0 + nDOFsFaceSide1); } -su2double CFEMStandardBoundaryFace::WorkEstimateMetis(CConfig *config) { - +su2double CFEMStandardBoundaryFace::WorkEstimateMetis(CConfig* config) { /* TEMPORARY IMPLEMENTATION. */ - return nIntegration + 0.05*nDOFsFace; + return nIntegration + 0.05 * nDOFsFace; } -su2double CFEMStandardBoundaryFace::WorkEstimateMetisWallFunctions( - CConfig *config, - const unsigned short nPointsWF) { - +su2double CFEMStandardBoundaryFace::WorkEstimateMetisWallFunctions(CConfig* config, const unsigned short nPointsWF) { /* TEMPORARY IMPLEMENTATION. */ - return 0.25*nIntegration*nPointsWF; + return 0.25 * nIntegration * nPointsWF; } diff --git a/Common/src/fem/geometry_structure_fem_part.cpp b/Common/src/fem/geometry_structure_fem_part.cpp index d6871e9c863..3e6853176d8 100644 --- a/Common/src/fem/geometry_structure_fem_part.cpp +++ b/Common/src/fem/geometry_structure_fem_part.cpp @@ -41,54 +41,50 @@ #include /*--- Epsilon definition ---*/ - CFaceOfElement::CFaceOfElement() { - nCornerPoints = 0; + nCornerPoints = 0; cornerPoints[0] = cornerPoints[1] = cornerPoints[2] = cornerPoints[3] = ULONG_MAX; - elemID0 = elemID1 = ULONG_MAX; - nPolyGrid0 = nPolyGrid1 = 0; - nPolySol0 = nPolySol1 = 0; - nDOFsElem0 = nDOFsElem1 = 0; - elemType0 = elemType1 = 0; - faceID0 = faceID1 = 0; - periodicIndex = periodicIndexDonor = 0; - faceIndicator = 0; + elemID0 = elemID1 = ULONG_MAX; + nPolyGrid0 = nPolyGrid1 = 0; + nPolySol0 = nPolySol1 = 0; + nDOFsElem0 = nDOFsElem1 = 0; + elemType0 = elemType1 = 0; + faceID0 = faceID1 = 0; + periodicIndex = periodicIndexDonor = 0; + faceIndicator = 0; JacFaceIsConsideredConstant = false; - elem0IsOwner = false; + elem0IsOwner = false; } -CFaceOfElement::CFaceOfElement(const unsigned short VTK_Type, - const unsigned short nPoly, - const unsigned long *Nodes) { - +CFaceOfElement::CFaceOfElement(const unsigned short VTK_Type, const unsigned short nPoly, const unsigned long* Nodes) { /* Set the default values of the member variables. */ - nCornerPoints = 0; + nCornerPoints = 0; cornerPoints[0] = cornerPoints[1] = cornerPoints[2] = cornerPoints[3] = ULONG_MAX; - elemID0 = elemID1 = ULONG_MAX; - nPolyGrid0 = nPolyGrid1 = 0; - nPolySol0 = nPolySol1 = 0; - nDOFsElem0 = nDOFsElem1 = 0; - elemType0 = elemType1 = 0; - faceID0 = faceID1 = 0; - periodicIndex = periodicIndexDonor = 0; - faceIndicator = 0; + elemID0 = elemID1 = ULONG_MAX; + nPolyGrid0 = nPolyGrid1 = 0; + nPolySol0 = nPolySol1 = 0; + nDOFsElem0 = nDOFsElem1 = 0; + elemType0 = elemType1 = 0; + faceID0 = faceID1 = 0; + periodicIndex = periodicIndexDonor = 0; + faceIndicator = 0; JacFaceIsConsideredConstant = false; - elem0IsOwner = false; + elem0IsOwner = false; /* Determine the face element type and set the corner points accordingly. */ - switch( VTK_Type ) { + switch (VTK_Type) { case LINE: { - nCornerPoints = 2; + nCornerPoints = 2; cornerPoints[0] = Nodes[0]; cornerPoints[1] = Nodes[nPoly]; break; } case TRIANGLE: { - const unsigned short ind2 = (nPoly+1)*(nPoly+2)/2 -1; - nCornerPoints = 3; + const unsigned short ind2 = (nPoly + 1) * (nPoly + 2) / 2 - 1; + nCornerPoints = 3; cornerPoints[0] = Nodes[0]; cornerPoints[1] = Nodes[nPoly]; cornerPoints[2] = Nodes[ind2]; @@ -96,9 +92,9 @@ CFaceOfElement::CFaceOfElement(const unsigned short VTK_Type, } case QUADRILATERAL: { - const unsigned short ind2 = nPoly*(nPoly+1); - const unsigned short ind3 = (nPoly+1)*(nPoly+1) -1; - nCornerPoints = 4; + const unsigned short ind2 = nPoly * (nPoly + 1); + const unsigned short ind3 = (nPoly + 1) * (nPoly + 1) - 1; + nCornerPoints = 4; cornerPoints[0] = Nodes[0]; cornerPoints[1] = Nodes[nPoly]; cornerPoints[2] = Nodes[ind2]; @@ -114,62 +110,60 @@ CFaceOfElement::CFaceOfElement(const unsigned short VTK_Type, } } -bool CFaceOfElement::operator<(const CFaceOfElement &other) const { - if(nCornerPoints != other.nCornerPoints) return nCornerPoints < other.nCornerPoints; +bool CFaceOfElement::operator<(const CFaceOfElement& other) const { + if (nCornerPoints != other.nCornerPoints) return nCornerPoints < other.nCornerPoints; - for(unsigned short i=0; i=2 ? ind - 2 : ind + 2; // Opposite index. + if (nn[1] < nn[ind]) ind = 1; + if (nn[2] < nn[ind]) ind = 2; + if (nn[3] < nn[ind]) ind = 3; - if(nn[indp1] < nn[indm1]) { + unsigned short indm1 = ind == 0 ? 3 : ind - 1; // Next lower index. + unsigned short indp1 = ind == 3 ? 0 : ind + 1; // Next upper index. + unsigned short indp2 = ind >= 2 ? ind - 2 : ind + 2; // Opposite index. + if (nn[indp1] < nn[indm1]) { /* The orientation of the quadrilateral remains the same. Store the new sorted node numbering. */ cornerPoints[0] = nn[ind]; cornerPoints[1] = nn[indp1]; cornerPoints[2] = nn[indp2]; cornerPoints[3] = nn[indm1]; - } - else { - + } else { /* The orientation of the quadrilateral changes. Store the new sorted node numbering and set swapElements to true. */ cornerPoints[0] = nn[ind]; cornerPoints[1] = nn[indm1]; cornerPoints[2] = nn[indp2]; cornerPoints[3] = nn[indp1]; - swapElements = true; + swapElements = true; } break; @@ -252,39 +239,38 @@ void CFaceOfElement::CreateUniqueNumberingWithOrientation(void) { default: { ostringstream message; - message << "Unknown surface element type with " << nCornerPoints - << " corners." << endl; + message << "Unknown surface element type with " << nCornerPoints << " corners." << endl; SU2_MPI::Error(message.str(), CURRENT_FUNCTION); } } /* Swap the element information, if needed. */ - if( swapElements ) { - swap(elemID0, elemID1); + if (swapElements) { + swap(elemID0, elemID1); swap(nPolyGrid0, nPolyGrid1); - swap(nPolySol0, nPolySol1); + swap(nPolySol0, nPolySol1); swap(nDOFsElem0, nDOFsElem1); - swap(elemType0, elemType1); - swap(faceID0, faceID1); + swap(elemType0, elemType1); + swap(faceID0, faceID1); } } -void CBoundaryFace::Copy(const CBoundaryFace &other) { - VTK_Type = other.VTK_Type; - nPolyGrid = other.nPolyGrid; - nDOFsGrid = other.nDOFsGrid; +void CBoundaryFace::Copy(const CBoundaryFace& other) { + VTK_Type = other.VTK_Type; + nPolyGrid = other.nPolyGrid; + nDOFsGrid = other.nDOFsGrid; globalBoundElemID = other.globalBoundElemID; - domainElementID = other.domainElementID; - Nodes = other.Nodes; + domainElementID = other.domainElementID; + Nodes = other.Nodes; } CMatchingFace::CMatchingFace() { nCornerPoints = 0; - nDim = 0; - nPoly = 0; - nDOFsElem = 0; - elemType = 0; - elemID = 0; + nDim = 0; + nPoly = 0; + nDOFsElem = 0; + elemType = 0; + elemID = 0; cornerCoor[0][0] = cornerCoor[0][1] = cornerCoor[0][2] = 0.0; cornerCoor[1][0] = cornerCoor[1][1] = cornerCoor[1][2] = 0.0; @@ -294,10 +280,9 @@ CMatchingFace::CMatchingFace() { tolForMatching = 0.0; } -bool CMatchingFace::operator<(const CMatchingFace &other) const { - +bool CMatchingFace::operator<(const CMatchingFace& other) const { /* First compare the number of corner points. ---*/ - if(nCornerPoints != other.nCornerPoints) return nCornerPoints < other.nCornerPoints; + if (nCornerPoints != other.nCornerPoints) return nCornerPoints < other.nCornerPoints; /*--- Determine the tolerance for comparing both objects. ---*/ const su2double tol = min(tolForMatching, other.tolForMatching); @@ -305,10 +290,9 @@ bool CMatchingFace::operator<(const CMatchingFace &other) const { /*--- Loop over the number of corner points and dimensions and compare the coordinates. If considered different, return true if the current face is considered smaller and false otherwise. ---*/ - for(unsigned short k=0; k tol) - return cornerCoor[k][l] < other.cornerCoor[k][l]; + for (unsigned short k = 0; k < nCornerPoints; ++k) { + for (unsigned short l = 0; l < nDim; ++l) { + if (fabs(cornerCoor[k][l] - other.cornerCoor[k][l]) > tol) return cornerCoor[k][l] < other.cornerCoor[k][l]; } } @@ -317,21 +301,22 @@ bool CMatchingFace::operator<(const CMatchingFace &other) const { } void CMatchingFace::SortFaceCoordinates(void) { - /*--- Determine the tolerance for a matching point for this face. This is accomplished by computing the minimum distance between the points of the face, multiplied by a relative tolerance. ---*/ - for(unsigned short k=0; k0; --j) { - + for (unsigned short k = 1; k < nCornerPoints; ++k) { + for (unsigned short j = k; j > 0; --j) { /* Check if cornerCoor[j] is considered less than cornerCoor[j-1]. */ bool lessThan = false; - for(unsigned short l=0; l tolForMatching) { - lessThan = cornerCoor[j][l] < cornerCoor[j-1][l]; + for (unsigned short l = 0; l < nDim; ++l) { + if (fabs(cornerCoor[j][l] - cornerCoor[j - 1][l]) > tolForMatching) { + lessThan = cornerCoor[j][l] < cornerCoor[j - 1][l]; break; } } /* If cornerCoor[j] is less than cornerCoor[j-1] they must be swapped. Otherwise an exit can be made from the j-loop. */ - if( lessThan ) { - for(unsigned short l=0; lGetTime_Marching() == TIME_MARCHING::HARMONIC_BALANCE; unsigned short nMarker_Max = config->GetnMarker_Max(); nZone = val_nZone; /*--- Initialize counters for local/global points & elements ---*/ - Global_nPoint = 0; Global_nPointDomain = 0; Global_nElem = 0; - nelem_edge = 0; Global_nelem_edge = 0; - nelem_triangle = 0; Global_nelem_triangle = 0; - nelem_quad = 0; Global_nelem_quad = 0; - nelem_tetra = 0; Global_nelem_tetra = 0; - nelem_hexa = 0; Global_nelem_hexa = 0; - nelem_prism = 0; Global_nelem_prism = 0; - nelem_pyramid = 0; Global_nelem_pyramid = 0; + Global_nPoint = 0; + Global_nPointDomain = 0; + Global_nElem = 0; + nelem_edge = 0; + Global_nelem_edge = 0; + nelem_triangle = 0; + Global_nelem_triangle = 0; + nelem_quad = 0; + Global_nelem_quad = 0; + nelem_tetra = 0; + Global_nelem_tetra = 0; + nelem_hexa = 0; + Global_nelem_hexa = 0; + nelem_prism = 0; + Global_nelem_prism = 0; + nelem_pyramid = 0; + Global_nelem_pyramid = 0; /*--- Allocate memory for the linear partition of the elements of the mesh. These arrays are the size of the number of ranks. ---*/ beg_node = new unsigned long[size]; end_node = new unsigned long[size]; - nPointLinear = new unsigned long[size]; + nPointLinear = new unsigned long[size]; /*--- Open grid file ---*/ @@ -417,23 +407,22 @@ void CPhysicalGeometry::Read_SU2_Format_Parallel_FEM(CConfig *config, /*--- Check the grid ---*/ if (mesh_file.fail()) - SU2_MPI::Error(string("There is no mesh file (CPhysicalGeometry)!! ") + val_mesh_filename, - CURRENT_FUNCTION); + SU2_MPI::Error(string("There is no mesh file (CPhysicalGeometry)!! ") + val_mesh_filename, CURRENT_FUNCTION); /*--- If more than one, find the zone in the mesh file ---*/ if (val_nZone > 1 || time_spectral) { if (time_spectral) { - if (rank == MASTER_NODE) cout << "Reading time spectral instance " << val_iZone+1 << ":" << endl; + if (rank == MASTER_NODE) cout << "Reading time spectral instance " << val_iZone + 1 << ":" << endl; } else { - while (getline (mesh_file,text_line)) { + while (getline(mesh_file, text_line)) { /*--- Search for the current domain ---*/ - position = text_line.find ("IZONE=",0); + position = text_line.find("IZONE=", 0); if (position != string::npos) { - text_line.erase (0,6); + text_line.erase(0, 6); unsigned short jDomain = atoi(text_line.c_str()); - if (jDomain == val_iZone+1) { - if (rank == MASTER_NODE) cout << "Reading zone " << val_iZone+1 << " points:" << endl; + if (jDomain == val_iZone + 1) { + if (rank == MASTER_NODE) cout << "Reading zone " << val_iZone + 1 << " points:" << endl; break; } } @@ -443,27 +432,29 @@ void CPhysicalGeometry::Read_SU2_Format_Parallel_FEM(CConfig *config, /*--- Read grid file with format SU2 ---*/ - while (getline (mesh_file, text_line)) { - + while (getline(mesh_file, text_line)) { /*--- Read the dimension of the problem ---*/ - position = text_line.find ("NDIME=",0); + position = text_line.find("NDIME=", 0); if (position != string::npos) { if (domain_flag == false) { - text_line.erase (0,6); nDim = atoi(text_line.c_str()); + text_line.erase(0, 6); + nDim = atoi(text_line.c_str()); if (rank == MASTER_NODE) { if (nDim == 2) cout << "Two dimensional problem." << endl; if (nDim == 3) cout << "Three dimensional problem." << endl; } domain_flag = true; - } else { break; } + } else { + break; + } } /*--- Read the information about inner elements ---*/ - position = text_line.find ("NELEM=",0); + position = text_line.find("NELEM=", 0); if (position != string::npos) { - text_line.erase (0,6); + text_line.erase(0, 6); stringstream stream_line(text_line); stream_line >> Global_nElem; @@ -473,8 +464,8 @@ void CPhysicalGeometry::Read_SU2_Format_Parallel_FEM(CConfig *config, /*--- Check if the number of cores used is larger than the number of elements. Terminate if this is the case, because it does not make sense to do this. ---*/ - unsigned long nCores = size; // Correct for the number of cores per rank. - if(nCores > Global_nElem) { + unsigned long nCores = size; // Correct for the number of cores per rank. + if (nCores > Global_nElem) { ostringstream message; message << "The number of cores, " << nCores; message << ", is larger than the number of elements, " << Global_nElem << "." << endl; @@ -488,14 +479,14 @@ void CPhysicalGeometry::Read_SU2_Format_Parallel_FEM(CConfig *config, This is a linear partitioning with the addition of a simple load balancing for any remainder elements. ---*/ unsigned long total_elem_accounted = 0; - for(unsigned long i = 0; i < (unsigned long)size; i++) { - nPointLinear[i] = Global_nElem/size; + for (unsigned long i = 0; i < (unsigned long)size; i++) { + nPointLinear[i] = Global_nElem / size; total_elem_accounted = total_elem_accounted + nPointLinear[i]; } /*--- Get the number of remainder elements after the even division ---*/ unsigned long rem_elem = Global_nElem - total_elem_accounted; - for (unsigned long i = 0; i> typeRead; + unsigned long typeRead; + elem_line >> typeRead; unsigned long typeReadErrorMessage = typeRead; unsigned short nPolySol, nPolyGrid; - if(typeRead > 10000) { - nPolySol = typeRead/10000 -1; - typeRead = typeRead%10000; - nPolyGrid = typeRead/100 + 1; - } - else { - nPolyGrid = typeRead/100 + 1; - nPolySol = nPolyGrid; + if (typeRead > 10000) { + nPolySol = typeRead / 10000 - 1; + typeRead = typeRead % 10000; + nPolyGrid = typeRead / 100 + 1; + } else { + nPolyGrid = typeRead / 100 + 1; + nPolySol = nPolyGrid; } - unsigned short VTK_Type = typeRead%100; + unsigned short VTK_Type = typeRead % 100; - unsigned short nDOFsGrid = CFEMStandardElementBase::GetNDOFsStatic(VTK_Type, nPolyGrid, - typeReadErrorMessage); - unsigned short nDOFsSol = CFEMStandardElementBase::GetNDOFsStatic(VTK_Type, nPolySol, - typeReadErrorMessage); + unsigned short nDOFsGrid = CFEMStandardElementBase::GetNDOFsStatic(VTK_Type, nPolyGrid, typeReadErrorMessage); + unsigned short nDOFsSol = CFEMStandardElementBase::GetNDOFsStatic(VTK_Type, nPolySol, typeReadErrorMessage); /*--- Allocate the memory for a new primary grid FEM element if this element must be stored on this rank. ---*/ if ((i >= beg_node[rank]) && (i < end_node[rank])) { - - elem[loc_element_count] = new CPrimalGridFEM(i, VTK_Type, nPolyGrid, nPolySol, - nDOFsGrid, nDOFsSol, nDOFs_tot, - elem_line); + elem[loc_element_count] = + new CPrimalGridFEM(i, VTK_Type, nPolyGrid, nPolySol, nDOFsGrid, nDOFsSol, nDOFs_tot, elem_line); nDOFsGrid_Local += nDOFsGrid; loc_element_count++; } @@ -569,11 +555,9 @@ void CPhysicalGeometry::Read_SU2_Format_Parallel_FEM(CConfig *config, /*--- Create a vector, which contains the global node IDs of the local elements. ---*/ vector nodeIDsElemLoc; nodeIDsElemLoc.reserve(nDOFsGrid_Local); - for(unsigned long i=0; iGetnNodes(); - for(unsigned short j=0; jGetNode(j)); + for (unsigned short j = 0; j < nDOFsElem; ++j) nodeIDsElemLoc.push_back(elem[i]->GetNode(j)); } sort(nodeIDsElemLoc.begin(), nodeIDsElemLoc.end()); @@ -582,7 +566,7 @@ void CPhysicalGeometry::Read_SU2_Format_Parallel_FEM(CConfig *config, nodeIDsElemLoc.erase(lastNode, nodeIDsElemLoc.end()); /*--- Allocate the memory for the coordinates to be stored on this rank. ---*/ - nPoint = nodeIDsElemLoc.size(); + nPoint = nodeIDsElemLoc.size(); nodes = new CPoint(nPoint, nDim); /*--- Open the grid file again and go to the position where @@ -590,37 +574,36 @@ void CPhysicalGeometry::Read_SU2_Format_Parallel_FEM(CConfig *config, mesh_file.open(val_mesh_filename.c_str(), ios::in); if (val_nZone > 1 && !time_spectral) { - while (getline (mesh_file,text_line)) { - position = text_line.find ("IZONE=",0); + while (getline(mesh_file, text_line)) { + position = text_line.find("IZONE=", 0); if (position != string::npos) { - text_line.erase (0,6); + text_line.erase(0, 6); unsigned short jDomain = atoi(text_line.c_str()); - if (jDomain == val_iZone+1) break; + if (jDomain == val_iZone + 1) break; } } } /*--- While loop to read the point information. ---*/ - while (getline (mesh_file, text_line)) { - - position = text_line.find ("NPOIN=",0); + while (getline(mesh_file, text_line)) { + position = text_line.find("NPOIN=", 0); if (position != string::npos) { - text_line.erase (0,6); + text_line.erase(0, 6); stringstream stream_line(text_line); stream_line >> Global_nPoint; /*--- Loop over the global number of points and store the ones that are needed on this processor. ---*/ unsigned long ii = 0; - for(unsigned long i=0; i> Coord[0]; point_line >> Coord[1]; - if (nDim==3) point_line >> Coord[2]; + if (nDim == 3) point_line >> Coord[2]; nodes->SetCoord(ii, Coord); nodes->SetGlobalIndex(ii, i); ++ii; @@ -635,21 +618,19 @@ void CPhysicalGeometry::Read_SU2_Format_Parallel_FEM(CConfig *config, /*--- Determine the faces of the local elements. --- */ vector localFaces; - for(unsigned long k=0; kGetCornerPointsAllFaces(nFaces, nPointsPerFace, faceConn); /*--- Loop over the faces and add them to localFaces. ---*/ - for(unsigned short i=0; i 1 && !time_spectral) { - while (getline (mesh_file,text_line)) { - position = text_line.find ("IZONE=",0); + while (getline(mesh_file, text_line)) { + position = text_line.find("IZONE=", 0); if (position != string::npos) { - text_line.erase (0,6); + text_line.erase(0, 6); unsigned short jDomain = atoi(text_line.c_str()); - if (jDomain == val_iZone+1) break; + if (jDomain == val_iZone + 1) break; } } } /*--- While loop to read the boundary information. ---*/ - while (getline (mesh_file, text_line)) { + while (getline(mesh_file, text_line)) { /*--- Read number of markers ---*/ - position = text_line.find ("NMARK=",0); + position = text_line.find("NMARK=", 0); if (position != string::npos) { - text_line.erase (0,6); + text_line.erase(0, 6); istringstream stream_line(text_line); stream_line >> nMarker; if (rank == MASTER_NODE) cout << nMarker << " surface markers." << endl; config->SetnMarker_All(nMarker); bound = new CPrimalGrid**[nMarker]; - nElem_Bound = new unsigned long [nMarker]; - Tag_to_Marker = new string [nMarker_Max]; + nElem_Bound = new unsigned long[nMarker]; + Tag_to_Marker = new string[nMarker_Max]; - for(unsigned short iMarker = 0 ; iMarker < nMarker; iMarker++) { - getline (mesh_file, text_line); - text_line.erase (0,11); - text_line.erase (remove(text_line.begin(), text_line.end(), ' '), text_line.end()); - text_line.erase (remove(text_line.begin(), text_line.end(), '\r'), text_line.end()); - text_line.erase (remove(text_line.begin(), text_line.end(), '\n'), text_line.end()); + for (unsigned short iMarker = 0; iMarker < nMarker; iMarker++) { + getline(mesh_file, text_line); + text_line.erase(0, 11); + text_line.erase(remove(text_line.begin(), text_line.end(), ' '), text_line.end()); + text_line.erase(remove(text_line.begin(), text_line.end(), '\r'), text_line.end()); + text_line.erase(remove(text_line.begin(), text_line.end(), '\n'), text_line.end()); Marker_Tag = text_line.c_str(); /*--- Read the number of elements for this marker. ---*/ - getline (mesh_file, text_line); - text_line.erase (0,13); istringstream nmark_line(text_line); + getline(mesh_file, text_line); + text_line.erase(0, 13); + istringstream nmark_line(text_line); unsigned long nElem_Bound_Global; nmark_line >> nElem_Bound_Global; if (rank == MASTER_NODE) - cout << nElem_Bound_Global << " boundary elements in index "<< iMarker - <<" (Marker = " < boundElems; /*--- Loop over the global boundary faces. ---*/ - for(unsigned long i=0; i> typeRead; - unsigned short nPolyGrid = typeRead/100 + 1; - unsigned short VTK_Type = typeRead%100; + unsigned long typeRead; + bound_line >> typeRead; + unsigned short nPolyGrid = typeRead / 100 + 1; + unsigned short VTK_Type = typeRead % 100; unsigned short nDOFEdgeGrid = nPolyGrid + 1; unsigned short nDOFsGrid = 0; CFaceOfElement thisFace; - thisFace.cornerPoints[0] = 0; thisFace.cornerPoints[1] = nPolyGrid; - switch( VTK_Type ) { + thisFace.cornerPoints[0] = 0; + thisFace.cornerPoints[1] = nPolyGrid; + switch (VTK_Type) { case LINE: nDOFsGrid = nDOFEdgeGrid; thisFace.nCornerPoints = 2; break; case TRIANGLE: - nDOFsGrid = nDOFEdgeGrid*(nDOFEdgeGrid+1)/2; + nDOFsGrid = nDOFEdgeGrid * (nDOFEdgeGrid + 1) / 2; thisFace.nCornerPoints = 3; - thisFace.cornerPoints[2] = nDOFsGrid -1; + thisFace.cornerPoints[2] = nDOFsGrid - 1; break; case QUADRILATERAL: - nDOFsGrid = nDOFEdgeGrid*nDOFEdgeGrid; + nDOFsGrid = nDOFEdgeGrid * nDOFEdgeGrid; thisFace.nCornerPoints = 4; - thisFace.cornerPoints[2] = nPolyGrid*nDOFEdgeGrid; - thisFace.cornerPoints[3] = nDOFsGrid -1; + thisFace.cornerPoints[2] = nPolyGrid * nDOFEdgeGrid; + thisFace.cornerPoints[3] = nDOFsGrid - 1; break; default: ostringstream message; - message << "Unknown FEM boundary element value, " << typeRead - << ", in " << val_mesh_filename; + message << "Unknown FEM boundary element value, " << typeRead << ", in " << val_mesh_filename; SU2_MPI::Error(message.str(), CURRENT_FUNCTION); } vector nodeIDs(nDOFsGrid); - for(unsigned short j=0; j> nodeIDs[j]; + for (unsigned short j = 0; j < nDOFsGrid; ++j) bound_line >> nodeIDs[j]; /*--- Convert the local numbering of thisFace to global numbering and create a unique numbering of these nodes. ---*/ - for(unsigned short j=0; j::iterator low; low = lower_bound(localFaces.begin(), localFaces.end(), thisFace); - if(low != localFaces.end()) { - if( !(thisFace < *low) ) { - + if (low != localFaces.end()) { + if (!(thisFace < *low)) { CBoundaryFace thisBoundFace; - thisBoundFace.VTK_Type = VTK_Type; - thisBoundFace.nPolyGrid = nPolyGrid; - thisBoundFace.nDOFsGrid = nDOFsGrid; + thisBoundFace.VTK_Type = VTK_Type; + thisBoundFace.nPolyGrid = nPolyGrid; + thisBoundFace.nDOFsGrid = nDOFsGrid; thisBoundFace.globalBoundElemID = i; - thisBoundFace.domainElementID = low->elemID0; - thisBoundFace.Nodes = nodeIDs; + thisBoundFace.domainElementID = low->elemID0; + thisBoundFace.Nodes = nodeIDs; boundElems.push_back(thisBoundFace); } @@ -790,15 +771,12 @@ void CPhysicalGeometry::Read_SU2_Format_Parallel_FEM(CConfig *config, /*--- Allocate space for the boundary elements and store the ones whose parent element is stored on this rank. ---*/ nElem_Bound[iMarker] = boundElems.size(); - bound[iMarker] = new CPrimalGrid* [nElem_Bound[iMarker]]; + bound[iMarker] = new CPrimalGrid*[nElem_Bound[iMarker]]; - for(unsigned long i=0; iGetMarker_CfgFile_TagBound(Marker_Tag)] = Marker_Tag; @@ -824,10 +802,8 @@ void CPhysicalGeometry::Read_SU2_Format_Parallel_FEM(CConfig *config, mesh_file.close(); } -void CPhysicalGeometry::Read_CGNS_Format_Parallel_FEM(CConfig *config, - string val_mesh_filename, - unsigned short val_iZone, - unsigned short val_nZone) { +void CPhysicalGeometry::Read_CGNS_Format_Parallel_FEM(CConfig* config, string val_mesh_filename, + unsigned short val_iZone, unsigned short val_nZone) { #ifdef HAVE_CGNS /*--- For proper support of the high order elements, at least version 3.3 @@ -837,18 +813,26 @@ void CPhysicalGeometry::Read_CGNS_Format_Parallel_FEM(CConfig *config, /*--- Check whether the supplied file is truly a CGNS file. ---*/ int file_type; if (cg_is_cgns(val_mesh_filename.c_str(), &file_type) != CG_OK) - SU2_MPI::Error(val_mesh_filename + string(" is not a CGNS file that can be read."), - CURRENT_FUNCTION); + SU2_MPI::Error(val_mesh_filename + string(" is not a CGNS file that can be read."), CURRENT_FUNCTION); /*--- Initialize counters for local/global points & elements ---*/ - Global_nPoint = 0; Global_nPointDomain = 0; Global_nElem = 0; - nelem_edge = 0; Global_nelem_edge = 0; - nelem_triangle = 0; Global_nelem_triangle = 0; - nelem_quad = 0; Global_nelem_quad = 0; - nelem_tetra = 0; Global_nelem_tetra = 0; - nelem_hexa = 0; Global_nelem_hexa = 0; - nelem_prism = 0; Global_nelem_prism = 0; - nelem_pyramid = 0; Global_nelem_pyramid = 0; + Global_nPoint = 0; + Global_nPointDomain = 0; + Global_nElem = 0; + nelem_edge = 0; + Global_nelem_edge = 0; + nelem_triangle = 0; + Global_nelem_triangle = 0; + nelem_quad = 0; + Global_nelem_quad = 0; + nelem_tetra = 0; + Global_nelem_tetra = 0; + nelem_hexa = 0; + Global_nelem_hexa = 0; + nelem_prism = 0; + Global_nelem_prism = 0; + nelem_pyramid = 0; + Global_nelem_pyramid = 0; /*--------------------------------------------------------------------------*/ /*--- Checking of the file, determine the dimensions, etc. ---*/ @@ -858,20 +842,20 @@ void CPhysicalGeometry::Read_CGNS_Format_Parallel_FEM(CConfig *config, These arrays are the size of the number of ranks. ---*/ beg_node = new unsigned long[size]; end_node = new unsigned long[size]; - nPointLinear = new unsigned long[size]; + nPointLinear = new unsigned long[size]; /* Open the CGNS file for reading and check if it went OK. */ int fn; - if(cg_open(val_mesh_filename.c_str(), CG_MODE_READ, &fn) != CG_OK) cg_error_exit(); - if(rank == MASTER_NODE) { + if (cg_open(val_mesh_filename.c_str(), CG_MODE_READ, &fn) != CG_OK) cg_error_exit(); + if (rank == MASTER_NODE) { cout << "Reading the CGNS file: " << val_mesh_filename << "." << endl; } /* Get the number of databases. This is the highest node in the CGNS heirarchy. The current implementation assumes that there is only one database. */ int nbases; - if(cg_nbases(fn, &nbases) != CG_OK) cg_error_exit(); - if(nbases > 1) { + if (cg_nbases(fn, &nbases) != CG_OK) cg_error_exit(); + if (nbases > 1) { ostringstream message; message << "CGNS file contains " << nbases << " databases." << endl; message << "CGNS reader can handle only 1 at the moment." << endl; @@ -881,22 +865,22 @@ void CPhysicalGeometry::Read_CGNS_Format_Parallel_FEM(CConfig *config, /* Read the information of the base, especially the number of dimensions. */ char cgnsname[CGNS_STRING_SIZE]; - int cellDim, physDim; + int cellDim, physDim; const int iBase = 1; - if(cg_base_read(fn, iBase, cgnsname, &cellDim, &physDim)) cg_error_exit(); + if (cg_base_read(fn, iBase, cgnsname, &cellDim, &physDim)) cg_error_exit(); nDim = physDim; - if(cellDim != physDim) { + if (cellDim != physDim) { ostringstream message; - message << "The element dimension, " << cellDim - << ", differs from the physical dimension, " << physDim << "." << endl; + message << "The element dimension, " << cellDim << ", differs from the physical dimension, " << physDim << "." + << endl; message << "These should be the same for the DG-FEM solver." << endl; SU2_MPI::Error(message.str(), CURRENT_FUNCTION); } /* Write the info about the number of dimensions. */ - if(rank == MASTER_NODE) { + if (rank == MASTER_NODE) { if (nDim == 2) cout << "Two dimensional problem." << endl; if (nDim == 3) cout << "Three dimensional problem." << endl; } @@ -906,11 +890,11 @@ void CPhysicalGeometry::Read_CGNS_Format_Parallel_FEM(CConfig *config, const int iZone = val_iZone + 1; int nzones; - if(cg_nzones(fn, iBase, &nzones) != CG_OK) cg_error_exit(); - if(iZone < 1 || iZone > nzones) { + if (cg_nzones(fn, iBase, &nzones) != CG_OK) cg_error_exit(); + if (iZone < 1 || iZone > nzones) { ostringstream message; - message << "Zone " << iZone << " requested for reading, but there are only " - << nzones << " zones present in the CGNS file." << endl; + message << "Zone " << iZone << " requested for reading, but there are only " << nzones + << " zones present in the CGNS file." << endl; SU2_MPI::Error(message.str(), CURRENT_FUNCTION); } @@ -918,14 +902,13 @@ void CPhysicalGeometry::Read_CGNS_Format_Parallel_FEM(CConfig *config, /* Determine the zone type for the requested zone and check if it is unstructured. */ ZoneType_t zoneType; - if(cg_zone_type(fn, iBase, iZone, &zoneType) != CG_OK) cg_error_exit(); - if(zoneType != Unstructured) - SU2_MPI::Error("Structured CGNS zone found while unstructured expected.", - CURRENT_FUNCTION); + if (cg_zone_type(fn, iBase, iZone, &zoneType) != CG_OK) cg_error_exit(); + if (zoneType != Unstructured) + SU2_MPI::Error("Structured CGNS zone found while unstructured expected.", CURRENT_FUNCTION); /* Determine the number of sections for the connectivities in this zone. */ int nsections; - if(cg_nsections(fn, iBase, iZone, &nsections) != CG_OK) cg_error_exit(); + if (cg_nsections(fn, iBase, iZone, &nsections) != CG_OK) cg_error_exit(); /*--------------------------------------------------------------------------*/ /*--- Reading and distributing the volume elements. ---*/ @@ -936,20 +919,19 @@ void CPhysicalGeometry::Read_CGNS_Format_Parallel_FEM(CConfig *config, Note that the indices start at 1 in CGNS. */ vector CGNSElemTypes(nsections); - for(int iConn=1; iConn<=nsections; ++iConn) { - CGNSElemTypes[iConn-1].DetermineMetaData(nDim, fn, iBase, iZone, iConn); - if( CGNSElemTypes[iConn-1].volumeConn ) - Global_nElem += CGNSElemTypes[iConn-1].nElem; + for (int iConn = 1; iConn <= nsections; ++iConn) { + CGNSElemTypes[iConn - 1].DetermineMetaData(nDim, fn, iBase, iZone, iConn); + if (CGNSElemTypes[iConn - 1].volumeConn) Global_nElem += CGNSElemTypes[iConn - 1].nElem; } - if((rank == MASTER_NODE) && (size > SINGLE_NODE)) + if ((rank == MASTER_NODE) && (size > SINGLE_NODE)) cout << Global_nElem << " interior elements before parallel partitioning." << endl; /*--- Check if the number of cores used is larger than the number of elements. Terminate if this is the case, because it does not make sense to do this. ---*/ - unsigned long nCores = size; // Correct for the number of cores per rank. - if(nCores > Global_nElem) { + unsigned long nCores = size; // Correct for the number of cores per rank. + if (nCores > Global_nElem) { ostringstream message; message << "The number of cores, " << nCores; message << ", is larger than the number of elements, " << Global_nElem << "." << endl; @@ -963,37 +945,36 @@ void CPhysicalGeometry::Read_CGNS_Format_Parallel_FEM(CConfig *config, This is a linear partitioning with the addition of a simple load balancing for any remainder elements. ---*/ unsigned long total_elem_accounted = 0; - for(unsigned long i = 0; i < (unsigned long)size; i++) { - nPointLinear[i] = Global_nElem/size; + for (unsigned long i = 0; i < (unsigned long)size; i++) { + nPointLinear[i] = Global_nElem / size; total_elem_accounted = total_elem_accounted + nPointLinear[i]; } /*--- Get the number of remainder elements after the even division ---*/ const unsigned long rem_elem = Global_nElem - total_elem_accounted; - for (unsigned long i = 0; i indBegOverlap) { - + if (indEndOverlap > indBegOverlap) { /* This rank must read element data from this connectivity section. Determine the offset relative to the start of this section and the number of elements to be read by this rank. */ const unsigned long offsetRank = indBegOverlap - elemCountOld; - const unsigned long nElemRank = indEndOverlap - indBegOverlap; + const unsigned long nElemRank = indEndOverlap - indBegOverlap; /* Read the connectivity range determined above. */ - CGNSElemTypes[iConn].ReadConnectivityRange(fn, iBase, iZone, offsetRank, - nElemRank, beg_node[rank], - elem, locElemCount, nDOFsLoc); + CGNSElemTypes[iConn].ReadConnectivityRange(fn, iBase, iZone, offsetRank, nElemRank, beg_node[rank], elem, + locElemCount, nDOFsLoc); } } } @@ -1022,17 +1001,14 @@ void CPhysicalGeometry::Read_CGNS_Format_Parallel_FEM(CConfig *config, /* The global offset of the DOFs must be corrected when running in parallel. Therefore gather the number of DOFs of all the ranks. */ vector nDOFsPerRank(size); - SU2_MPI::Allgather(&nDOFsLoc, 1, MPI_UNSIGNED_LONG, nDOFsPerRank.data(), 1, - MPI_UNSIGNED_LONG, SU2_MPI::GetComm()); + SU2_MPI::Allgather(&nDOFsLoc, 1, MPI_UNSIGNED_LONG, nDOFsPerRank.data(), 1, MPI_UNSIGNED_LONG, SU2_MPI::GetComm()); /* Determine the offset for the DOFs on this rank. */ unsigned long offsetRank = 0; - for(int i=0; iAddOffsetGlobalDOFs(offsetRank); + for (unsigned long i = 0; i < nElem; ++i) elem[i]->AddOffsetGlobalDOFs(offsetRank); #endif /*--------------------------------------------------------------------------*/ @@ -1042,7 +1018,7 @@ void CPhysicalGeometry::Read_CGNS_Format_Parallel_FEM(CConfig *config, /* Determine the global number of vertices in the requested zone. The other size information is not used. */ cgsize_t sizes[3]; - if(cg_zone_read(fn, iBase, iZone, cgnsname, sizes) != CG_OK) cg_error_exit(); + if (cg_zone_read(fn, iBase, iZone, cgnsname, sizes) != CG_OK) cg_error_exit(); Global_nPoint = sizes[0]; /*--- Determine the number of points per rank in cumulative storage format. @@ -1050,71 +1026,69 @@ void CPhysicalGeometry::Read_CGNS_Format_Parallel_FEM(CConfig *config, The required coordinates for each rank are later obtained via communication. ---*/ unsigned long totalPointsAccounted = 0; - vector nPointsPerRank(size+1); - for(int i=1; i<=size; ++i) { - nPointsPerRank[i] = Global_nPoint/size; + vector nPointsPerRank(size + 1); + for (int i = 1; i <= size; ++i) { + nPointsPerRank[i] = Global_nPoint / size; totalPointsAccounted += nPointsPerRank[i]; } const unsigned long nPointsRem = Global_nPoint - totalPointsAccounted; - for(unsigned long i=1; i<=nPointsRem; ++i) ++nPointsPerRank[i]; + for (unsigned long i = 1; i <= nPointsRem; ++i) ++nPointsPerRank[i]; nPointsPerRank[0] = 0; - for(int i=0; i > coorBuf(nDim, vector(nPointsRead)); /* Loop over the number of dimensions to read the coordinates. Note that the loop starts at 1 and ends at nDim because CGNS requires this. */ - for(unsigned short iDim=1; iDim<=nDim; ++iDim) { - + for (unsigned short iDim = 1; iDim <= nDim; ++iDim) { /* Determine the data type and name of the coordinate. Copy the name of the coordinate in a string for easier comparison. */ DataType_t datatype; - if(cg_coord_info(fn, iBase, iZone, iDim, &datatype, cgnsname) != CG_OK) - cg_error_exit(); + if (cg_coord_info(fn, iBase, iZone, iDim, &datatype, cgnsname) != CG_OK) cg_error_exit(); string coorname = cgnsname; /* Check the name of the coordinate and determine the index in coorBuf where to store this coordinate. Normally this should be iDim-1. */ unsigned short indC = 0; - if( coorname == "CoordinateX") indC = 0; - else if(coorname == "CoordinateY") indC = 1; - else if(coorname == "CoordinateZ") indC = 2; + if (coorname == "CoordinateX") + indC = 0; + else if (coorname == "CoordinateY") + indC = 1; + else if (coorname == "CoordinateZ") + indC = 2; else - SU2_MPI::Error(string("Unknown coordinate name, ") + coorname + - string(", encountered in the CGNS file."), CURRENT_FUNCTION); + SU2_MPI::Error(string("Unknown coordinate name, ") + coorname + string(", encountered in the CGNS file."), + CURRENT_FUNCTION); /* Easier storage of the range in the CGNS file. */ cgsize_t range_min = nPointsPerRank[rank] + 1; - cgsize_t range_max = nPointsPerRank[rank+1]; + cgsize_t range_max = nPointsPerRank[rank + 1]; /*--- Read the coordinate with the required precision and copy this data to the correct index in coorBuf. ---*/ - switch( datatype ) { + switch (datatype) { case RealSingle: { /* Single precision used. */ vector buf(nPointsRead); - if(cg_coord_read(fn, iBase, iZone, cgnsname, datatype, &range_min, - &range_max, buf.data()) != CG_OK) cg_error_exit(); + if (cg_coord_read(fn, iBase, iZone, cgnsname, datatype, &range_min, &range_max, buf.data()) != CG_OK) + cg_error_exit(); - for(cgsize_t i=0; i buf(nPointsRead); - if(cg_coord_read(fn, iBase, iZone, cgnsname, datatype, &range_min, - &range_max, buf.data()) != CG_OK) cg_error_exit(); + if (cg_coord_read(fn, iBase, iZone, cgnsname, datatype, &range_min, &range_max, buf.data()) != CG_OK) + cg_error_exit(); - for(cgsize_t i=0; i nodeIDsElemLoc; nodeIDsElemLoc.reserve(nDOFsLoc); - for(unsigned long i=0; iGetnNodes(); - for(unsigned short j=0; jGetNode(j)); + for (unsigned short j = 0; j < nDOFsElem; ++j) nodeIDsElemLoc.push_back(elem[i]->GetNode(j)); } sort(nodeIDsElemLoc.begin(), nodeIDsElemLoc.end()); @@ -1145,18 +1118,18 @@ void CPhysicalGeometry::Read_CGNS_Format_Parallel_FEM(CConfig *config, nodeIDsElemLoc.erase(lastNode, nodeIDsElemLoc.end()); /*--- Allocate the memory for the coordinates to be stored on this rank. ---*/ - nPoint = nodeIDsElemLoc.size(); + nPoint = nodeIDsElemLoc.size(); nodes = new CPoint(nPoint, nDim); /*--- Store the global ID's of the nodes in such a way that they can be sent to the rank that actually stores the coordinates.. ---*/ vector > nodeBuf(size, vector(0)); - for(unsigned long i=0; i::iterator low; low = lower_bound(nPointsPerRank.begin(), nPointsPerRank.end(), nodeID); cgsize_t rankNode = low - nPointsPerRank.begin(); - if(*low > nodeID) --rankNode; + if (*low > nodeID) --rankNode; nodeBuf[rankNode].push_back(nodeIDsElemLoc[i]); } @@ -1168,13 +1141,13 @@ void CPhysicalGeometry::Read_CGNS_Format_Parallel_FEM(CConfig *config, node. ---*/ int nRankSend = 0; vector sendToRank(size, 0); - vector startingIndRanksInNode(size+1); + vector startingIndRanksInNode(size + 1); startingIndRanksInNode[0] = 0; - for(int i=0; i sizeRecv(size, 1); - SU2_MPI::Reduce_scatter(sendToRank.data(), &nRankRecv, sizeRecv.data(), - MPI_INT, MPI_SUM, SU2_MPI::GetComm()); + SU2_MPI::Reduce_scatter(sendToRank.data(), &nRankRecv, sizeRecv.data(), MPI_INT, MPI_SUM, SU2_MPI::GetComm()); /*--- Send out the messages with the global node numbers. Use nonblocking sends to avoid deadlock. ---*/ vector sendReqs(nRankSend); nRankSend = 0; - for(int i=0; i nodeRecvBuf(sizeMess); - coorReturnBuf[i].resize(nDim*sizeMess); + coorReturnBuf[i].resize(nDim * sizeMess); /* Receive the message using a blocking receive. */ - SU2_MPI::Recv(nodeRecvBuf.data(), sizeMess, MPI_UNSIGNED_LONG, - source, rank, SU2_MPI::GetComm(), &status); + SU2_MPI::Recv(nodeRecvBuf.data(), sizeMess, MPI_UNSIGNED_LONG, source, rank, SU2_MPI::GetComm(), &status); /*--- Loop over the nodes just received and fill the return communication buffer with the coordinates of the requested nodes. ---*/ - for(int j=0; j= nPointsRead) + if (kk < 0 || kk >= nPointsRead) SU2_MPI::Error("Invalid point requested. This should not happen.", CURRENT_FUNCTION); - for(unsigned short k=0; k coorRecvBuf(nDim*nodeBuf[source].size()); + vector coorRecvBuf(nDim * nodeBuf[source].size()); /* Receive the message using a blocking receive. */ - SU2_MPI::Recv(coorRecvBuf.data(), coorRecvBuf.size(), MPI_DOUBLE, - source, rank+1, SU2_MPI::GetComm(), &status); + SU2_MPI::Recv(coorRecvBuf.data(), coorRecvBuf.size(), MPI_DOUBLE, source, rank + 1, SU2_MPI::GetComm(), &status); /*--- Make a distinction between 2D and 3D to store the data of the nodes. This data is created by taking the offset of the source rank into account. In this way the nodes are numbered with increading global node ID. ---*/ - for(unsigned long j=0; jSetCoord(kk, &coorRecvBuf[jj]); @@ -1281,12 +1248,11 @@ void CPhysicalGeometry::Read_CGNS_Format_Parallel_FEM(CConfig *config, #else /*--- Sequential mode. Create the data for the points. The global number of points equals the local number of points. ---*/ - nPoint = Global_nPoint; + nPoint = Global_nPoint; nodes = new CPoint(nPoint, nDim); - for(unsigned long i=0; iSetCoord(i, iDim, coorBuf[iDim][i]); + for (unsigned long i = 0; i < nPoint; ++i) { + for (unsigned short iDim = 0; iDim < nDim; ++iDim) nodes->SetCoord(i, iDim, coorBuf[iDim][i]); nodes->SetGlobalIndex(i, i); } @@ -1301,23 +1267,21 @@ void CPhysicalGeometry::Read_CGNS_Format_Parallel_FEM(CConfig *config, /*--- Determine the faces of the local elements. --- */ vector localFaces; - for(unsigned long k=0; kGetCornerPointsAllFaces(nFaces, nPointsPerFace, faceConn); /*--- Loop over the faces and add them to localFaces. For consistency between sequential and parallel mode the rank is stored at the position for the second element ID. ---*/ - for(unsigned short i=0; i > faceBuf(size, vector(0)); - for(unsigned long i=0; i::iterator low; low = lower_bound(nPointsPerRank.begin(), nPointsPerRank.end(), nodeID); cgsize_t rankNode = low - nPointsPerRank.begin(); - if(*low > nodeID) --rankNode; + if (*low > nodeID) --rankNode; faceBuf[rankNode].push_back(localFaces[i].nCornerPoints); - for(unsigned short j=0; j faceRecvBuf(sizeMess); - SU2_MPI::Recv(faceRecvBuf.data(), faceRecvBuf.size(), MPI_UNSIGNED_LONG, - source, rank+4, SU2_MPI::GetComm(), &status); + SU2_MPI::Recv(faceRecvBuf.data(), faceRecvBuf.size(), MPI_UNSIGNED_LONG, source, rank + 4, SU2_MPI::GetComm(), + &status); /* Loop to extract the data from the receive buffer. */ int ii = 0; - while(ii < sizeMess) { - + while (ii < sizeMess) { /* Store the data for this face in localFaces. The rank where the corresponding element is physically present is stored in the second element ID. Note that it is not necessary to create a unique numbering anymore, because this has already been done before the communication buffer was created. */ CFaceOfElement thisFace; - thisFace.nCornerPoints = (unsigned short) faceRecvBuf[ii++]; - for(unsigned short j=0; j familyNames(nFamilies); - for(int i=1; i<=nFamilies; ++i) { + for (int i = 1; i <= nFamilies; ++i) { int nFamBC, nGeo; - if(cg_family_read(fn, iBase, i, cgnsname, &nFamBC, &nGeo) != CG_OK) cg_error_exit(); - familyNames[i-1] = cgnsname; + if (cg_family_read(fn, iBase, i, cgnsname, &nFamBC, &nGeo) != CG_OK) cg_error_exit(); + familyNames[i - 1] = cgnsname; } /* Determine the number of boundary conditions for this zone. */ int nBCs; - if(cg_nbocos(fn, iBase, iZone, &nBCs) != CG_OK) cg_error_exit(); + if (cg_nbocos(fn, iBase, iZone, &nBCs) != CG_OK) cg_error_exit(); /* Read the names of the boundary conditions and determine their family names. If not family name is specified for a boundary condition, the family name is set to the name of the boundary condition. */ vector BCNames(nBCs), BCFamilyNames(nBCs); - for(int i=1; i<=nBCs; ++i) { - + for (int i = 1; i <= nBCs; ++i) { /* Read the info for this boundary condition. */ BCType_t BCType; PointSetType_t ptsetType; cgsize_t npnts, NormalListSize; int NormalIndex, nDataSet; DataType_t NormalDataType; - if(cg_boco_info(fn, iBase, iZone, i, cgnsname, &BCType, &ptsetType, - &npnts, &NormalIndex, &NormalListSize, &NormalDataType, - &nDataSet) != CG_OK) cg_error_exit(); - BCNames[i-1] = cgnsname; + if (cg_boco_info(fn, iBase, iZone, i, cgnsname, &BCType, &ptsetType, &npnts, &NormalIndex, &NormalListSize, + &NormalDataType, &nDataSet) != CG_OK) + cg_error_exit(); + BCNames[i - 1] = cgnsname; /* Read the possibly family name and set it. If not present, it is equal to BCName. */ - if(cg_goto(fn, iBase, "Zone_t", iZone, "ZoneBC_t", 1, - "BC_t", i, "end") != CG_OK) cg_error_exit(); + if (cg_goto(fn, iBase, "Zone_t", iZone, "ZoneBC_t", 1, "BC_t", i, "end") != CG_OK) cg_error_exit(); int ierr = cg_famname_read(cgnsname); - if(ierr == CG_ERROR) cg_error_exit(); - else if(ierr == CG_OK) BCFamilyNames[i-1] = cgnsname; - else BCFamilyNames[i-1] = BCNames[i-1]; + if (ierr == CG_ERROR) + cg_error_exit(); + else if (ierr == CG_OK) + BCFamilyNames[i - 1] = cgnsname; + else + BCFamilyNames[i - 1] = BCNames[i - 1]; } /*--- Determine the number of different surface connectivities. It is @@ -1491,9 +1451,8 @@ void CPhysicalGeometry::Read_CGNS_Format_Parallel_FEM(CConfig *config, vector surfaceNames; vector > surfaceConnIDs; - for(int i=0; i thisSurfaceConn(1, i); surfaceConnIDs.push_back(thisSurfaceConn); @@ -1547,7 +1507,7 @@ void CPhysicalGeometry::Read_CGNS_Format_Parallel_FEM(CConfig *config, /* Write a message about the number of surface markers and allocate the memory for the data structures to store the required information. */ nMarker = surfaceNames.size(); - if(rank == MASTER_NODE) cout << nMarker << " surface markers." << endl; + if (rank == MASTER_NODE) cout << nMarker << " surface markers." << endl; config->SetnMarker_All(nMarker); unsigned short nMarker_Max = config->GetnMarker_Max(); @@ -1557,42 +1517,39 @@ void CPhysicalGeometry::Read_CGNS_Format_Parallel_FEM(CConfig *config, Tag_to_Marker = new string[nMarker_Max]; /* Loop over the number of markers to read and distribute the connectivities. */ - for(unsigned short iMarker = 0 ; iMarker < nMarker; ++iMarker) { - + for (unsigned short iMarker = 0; iMarker < nMarker; ++iMarker) { /* Easier storage of the entries in CGNSElemTypes that contribute to this boundary marker. */ const int nEntries = surfaceConnIDs[iMarker].size(); - const int *entries = surfaceConnIDs[iMarker].data(); + const int* entries = surfaceConnIDs[iMarker].data(); /* Determine the global number of elements for this boundary marker. */ cgsize_t nElem_Bound_Global = 0; - for(int iConn=0; iConn nBoundElemPerRank(size+1); - for(int i=1; i<=size; ++i) { - nBoundElemPerRank[i] = nElem_Bound_Global/size; + vector nBoundElemPerRank(size + 1); + for (int i = 1; i <= size; ++i) { + nBoundElemPerRank[i] = nElem_Bound_Global / size; totalBoundElemAccounted += nBoundElemPerRank[i]; } const unsigned long nBoundElemRem = nElem_Bound_Global - totalBoundElemAccounted; - for(unsigned long i=1; i<=nBoundElemRem; ++i) ++nBoundElemPerRank[i]; + for (unsigned long i = 1; i <= nBoundElemRem; ++i) ++nBoundElemPerRank[i]; nBoundElemPerRank[0] = 0; - for(int i=0; i indBegOverlap) { + const unsigned long indEndOverlap = min(elemCount, nBoundElemPerRank[rank + 1]); + if (indEndOverlap > indBegOverlap) { /* This rank must read boundary element data from this connectivity section. Determine the offset relative to the start of this section and the number of elements to be read by this rank. */ const unsigned long offsetRank = indBegOverlap - elemCountOld; - const unsigned long nElemRank = indEndOverlap - indBegOverlap; + const unsigned long nElemRank = indEndOverlap - indBegOverlap; /* Read the connectivity range determined above. */ - CGNSElemTypes[entries[iConn]].ReadBoundaryConnectivityRange(fn, iBase, iZone, offsetRank, - nElemRank, nBoundElemPerRank[rank], - locElemCount, boundElems); + CGNSElemTypes[entries[iConn]].ReadBoundaryConnectivityRange(fn, iBase, iZone, offsetRank, nElemRank, + nBoundElemPerRank[rank], locElemCount, boundElems); } } @@ -1631,18 +1585,15 @@ void CPhysicalGeometry::Read_CGNS_Format_Parallel_FEM(CConfig *config, communicated to find out where it must be stored. First clear the contents of the faceBuf, such that it can be used again to send data to the appropiate rank. ---*/ - for(int i=0; i::iterator low; low = lower_bound(nPointsPerRank.begin(), nPointsPerRank.end(), nodeID); cgsize_t rankNode = low - nPointsPerRank.begin(); - if(*low > nodeID) --rankNode; + if (*low > nodeID) --rankNode; /*--- Copy the relevant data of this boundary element into faceBuf. ---*/ faceBuf[rankNode].push_back(boundElems[i].VTK_Type); faceBuf[rankNode].push_back(boundElems[i].nPolyGrid); faceBuf[rankNode].push_back(boundElems[i].nDOFsGrid); faceBuf[rankNode].push_back(boundElems[i].globalBoundElemID); - faceBuf[rankNode].insert(faceBuf[rankNode].end(), - boundElems[i].Nodes.begin(), - boundElems[i].Nodes.end()); + faceBuf[rankNode].insert(faceBuf[rankNode].end(), boundElems[i].Nodes.begin(), boundElems[i].Nodes.end()); } /* The contents of boundElems is copied into faceBuf, so it can @@ -1668,42 +1617,39 @@ void CPhysicalGeometry::Read_CGNS_Format_Parallel_FEM(CConfig *config, /*--- Determine the number of messages this rank will send and receive. ---*/ nRankSend = 0; - for(int i=0; i boundElemRecvBuf(sizeMess); - SU2_MPI::Recv(boundElemRecvBuf.data(), sizeMess, MPI_UNSIGNED_LONG, - source, rank+5, SU2_MPI::GetComm(), &status); + SU2_MPI::Recv(boundElemRecvBuf.data(), sizeMess, MPI_UNSIGNED_LONG, source, rank + 5, SU2_MPI::GetComm(), + &status); /* Loop to extract the data from the receive buffer. */ int ii = 0; - while(ii < sizeMess) { - + while (ii < sizeMess) { /* Store the data for this boundary element. */ - const unsigned short VTK_Type = (unsigned short) boundElemRecvBuf[ii++]; - const unsigned short nPolyGrid = (unsigned short) boundElemRecvBuf[ii++]; - const unsigned short nDOFsGrid = (unsigned short) boundElemRecvBuf[ii++]; + const unsigned short VTK_Type = (unsigned short)boundElemRecvBuf[ii++]; + const unsigned short nPolyGrid = (unsigned short)boundElemRecvBuf[ii++]; + const unsigned short nDOFsGrid = (unsigned short)boundElemRecvBuf[ii++]; const unsigned long globalBoundElemID = boundElemRecvBuf[ii++]; - const unsigned long *Nodes = boundElemRecvBuf.data() + ii; + const unsigned long* Nodes = boundElemRecvBuf.data() + ii; ii += nDOFsGrid; /* Determine the corner nodes and store them in an object of @@ -1739,18 +1684,17 @@ void CPhysicalGeometry::Read_CGNS_Format_Parallel_FEM(CConfig *config, low = lower_bound(localFaces.begin(), localFaces.end(), thisFace); bool thisFaceFound = false; - if(low != localFaces.end()) { - if( !(thisFace < *low) ) thisFaceFound = true; + if (low != localFaces.end()) { + if (!(thisFace < *low)) thisFaceFound = true; } - if( !thisFaceFound ) - SU2_MPI::Error("Boundary element not found in list of faces. This is a bug.", - CURRENT_FUNCTION); + if (!thisFaceFound) + SU2_MPI::Error("Boundary element not found in list of faces. This is a bug.", CURRENT_FUNCTION); /* Determine the domain element and the rank where this boundary element should be sent to.. */ const unsigned long domainElementID = low->elemID0; - const int rankBoundElem = (int) low->elemID1; + const int rankBoundElem = (int)low->elemID1; /*--- Store the data for this element in the communication buffer for rankBoundElem. ---*/ @@ -1760,8 +1704,7 @@ void CPhysicalGeometry::Read_CGNS_Format_Parallel_FEM(CConfig *config, nodeBuf[rankBoundElem].push_back(globalBoundElemID); nodeBuf[rankBoundElem].push_back(domainElementID); - for(unsigned short j=0; j boundElemRecvBuf(sizeMess); - SU2_MPI::Recv(boundElemRecvBuf.data(), sizeMess, MPI_UNSIGNED_LONG, - source, rank+6, SU2_MPI::GetComm(), &status); + SU2_MPI::Recv(boundElemRecvBuf.data(), sizeMess, MPI_UNSIGNED_LONG, source, rank + 6, SU2_MPI::GetComm(), + &status); /* Loop to extract the data from the receive buffer. */ int ii = 0; - while(ii < sizeMess) { - + while (ii < sizeMess) { /* Store the data for this boundary element. */ - const unsigned short VTK_Type = (unsigned short) boundElemRecvBuf[ii++]; - const unsigned short nPolyGrid = (unsigned short) boundElemRecvBuf[ii++]; - const unsigned short nDOFsGrid = (unsigned short) boundElemRecvBuf[ii++]; + const unsigned short VTK_Type = (unsigned short)boundElemRecvBuf[ii++]; + const unsigned short nPolyGrid = (unsigned short)boundElemRecvBuf[ii++]; + const unsigned short nDOFsGrid = (unsigned short)boundElemRecvBuf[ii++]; const unsigned long globalBoundElemID = boundElemRecvBuf[ii++]; - const unsigned long domainElementID = boundElemRecvBuf[ii++]; - const unsigned long *Nodes = boundElemRecvBuf.data() + ii; + const unsigned long domainElementID = boundElemRecvBuf[ii++]; + const unsigned long* Nodes = boundElemRecvBuf.data() + ii; ii += nDOFsGrid; /* Create an object of CBoundaryFace and store it in boundElems. */ CBoundaryFace thisBoundFace; - thisBoundFace.VTK_Type = VTK_Type; - thisBoundFace.nPolyGrid = nPolyGrid; - thisBoundFace.nDOFsGrid = nDOFsGrid; + thisBoundFace.VTK_Type = VTK_Type; + thisBoundFace.nPolyGrid = nPolyGrid; + thisBoundFace.nDOFsGrid = nDOFsGrid; thisBoundFace.globalBoundElemID = globalBoundElemID; - thisBoundFace.domainElementID = domainElementID; + thisBoundFace.domainElementID = domainElementID; thisBoundFace.Nodes.resize(nDOFsGrid); - for(unsigned short j=0; jelemID0; @@ -1888,15 +1822,12 @@ void CPhysicalGeometry::Read_CGNS_Format_Parallel_FEM(CConfig *config, /*--- Allocate space for the local boundary elements and copy the data from boundElems into bound. ---*/ nElem_Bound[iMarker] = boundElems.size(); - bound[iMarker] = new CPrimalGrid* [nElem_Bound[iMarker]]; + bound[iMarker] = new CPrimalGrid*[nElem_Bound[iMarker]]; - for(unsigned long i=0; iGetMarker_CfgFile_TagBound(Marker_Tag)] = Marker_Tag; @@ -1916,52 +1847,45 @@ void CPhysicalGeometry::Read_CGNS_Format_Parallel_FEM(CConfig *config, } /* Close the CGNS file again. */ - if(cg_close(fn) != CG_OK) cg_error_exit(); - if(rank == MASTER_NODE) - cout << "Successfully closed the CGNS file." << endl; + if (cg_close(fn) != CG_OK) cg_error_exit(); + if (rank == MASTER_NODE) cout << "Successfully closed the CGNS file." << endl; -#else /* CGNS_VERSION >= 3300 */ +#else /* CGNS_VERSION >= 3300 */ - SU2_MPI::Error("CGNS version 3.3 or higher is necessary for the DG FEM solver", - CURRENT_FUNCTION); + SU2_MPI::Error("CGNS version 3.3 or higher is necessary for the DG FEM solver", CURRENT_FUNCTION); #endif /* CGNS_VERSION >= 3300 */ -#else /* HAVE_CGNS. */ +#else /* HAVE_CGNS. */ - SU2_MPI::Error("SU2 built without CGNS support!!\nTo use CGNS, build SU2 accordingly.", - CURRENT_FUNCTION); + SU2_MPI::Error("SU2 built without CGNS support!!\nTo use CGNS, build SU2 accordingly.", CURRENT_FUNCTION); -#endif /* HAVE_CGNS. */ +#endif /* HAVE_CGNS. */ } -void CPhysicalGeometry::SetColorFEMGrid_Parallel(CConfig *config) { - +void CPhysicalGeometry::SetColorFEMGrid_Parallel(CConfig* config) { /*--- Initialize the color vector of the elements. ---*/ - for(unsigned long i=0; iSetColor(0); + for (unsigned long i = 0; i < nElem; ++i) elem[i]->SetColor(0); /*--- Determine the faces of the elements. ---*/ vector localFaces; - for(unsigned long k=0; kGetCornerPointsAllFaces(nFaces, nPointsPerFace, faceConn); /*--- Loop over the faces and add them to localFaces. ---*/ - for(unsigned short i=0; iGetNPolySol(); + for (unsigned short j = 0; j < nPointsPerFace[i]; ++j) thisFace.cornerPoints[j] = faceConn[i][j]; + thisFace.elemID0 = beg_node[rank] + k; + thisFace.nPolySol0 = elem[k]->GetNPolySol(); thisFace.nDOFsElem0 = elem[k]->GetNDOFsSol(); - thisFace.elemType0 = elem[k]->GetVTK_Type(); + thisFace.elemType0 = elem[k]->GetVTK_Type(); thisFace.CreateUniqueNumbering(); localFaces.push_back(thisFace); @@ -1976,19 +1900,17 @@ void CPhysicalGeometry::SetColorFEMGrid_Parallel(CConfig *config) { overloaded function GetCornerPointsAllFaces, which explains the dimensions of the variables used in the function call. Also note that the periodic boundaries are excluded, because they are not physical. ---*/ - for(unsigned short iMarker=0; iMarkerGetMarker_All_KindBC(iMarker) != PERIODIC_BOUNDARY) { - for(unsigned long k=0; kGetMarker_All_KindBC(iMarker) != PERIODIC_BOUNDARY) { + for (unsigned long k = 0; k < nElem_Bound[iMarker]; ++k) { unsigned short nFaces; unsigned short nPointsPerFace[6]; - unsigned long faceConn[6][4]; + unsigned long faceConn[6][4]; bound[iMarker][k]->GetCornerPointsAllFaces(nFaces, nPointsPerFace, faceConn); CFaceOfElement thisFace; thisFace.nCornerPoints = nPointsPerFace[0]; - for(unsigned short j=0; j::iterator low; @@ -2006,13 +1928,13 @@ void CPhysicalGeometry::SetColorFEMGrid_Parallel(CConfig *config) { found, the elemID from the second entry is copied to the first entry, the polynomial degree is updated, and the second entry is invalidated. ---*/ unsigned long nFacesLoc = localFaces.size(); - for(unsigned long i=1; i Global_nElem) { + for (unsigned long i = 0; i < nFacesLocOr; ++i) { + if (localFaces[i].elemID0 > Global_nElem) { localFaces[i].nCornerPoints = 4; localFaces[i].cornerPoints[0] = Global_nPoint; localFaces[i].cornerPoints[1] = Global_nPoint; @@ -2045,98 +1967,94 @@ void CPhysicalGeometry::SetColorFEMGrid_Parallel(CConfig *config) { was found. For these faces the other neighbor might be stored on a different rank (unless there are non-matching interfaces). ---*/ vector localFacesComm; - for(unsigned long i=0; i Global_nElem) localFacesComm.push_back(localFaces[i]); + for (unsigned long i = 0; i < nFacesLoc; ++i) + if (localFaces[i].elemID1 > Global_nElem) localFacesComm.push_back(localFaces[i]); /*--- Determine the maximum global point ID that occurs in localFacesComm of all ranks. Note that only the first point is taken into account, because this point determines the rank where the face is sent to. ---*/ unsigned long nFacesLocComm = localFacesComm.size(); unsigned long maxPointIDLoc = 0; - for(unsigned long i=0; i facePointsProc(size+1, 0); + vector facePointsProc(size + 1, 0); unsigned long total_point_accounted = 0; - for(unsigned long i=1; i<=(unsigned long)size; ++i) { - facePointsProc[i] = maxPointID/size; - total_point_accounted += facePointsProc[i]; + for (unsigned long i = 1; i <= (unsigned long)size; ++i) { + facePointsProc[i] = maxPointID / size; + total_point_accounted += facePointsProc[i]; } unsigned long rem_point = maxPointID - total_point_accounted; - for(unsigned long i=1; i<=rem_point; ++i) - ++facePointsProc[i]; + for (unsigned long i = 1; i <= rem_point; ++i) ++facePointsProc[i]; - for(unsigned long i=0; i<(unsigned long)size; ++i) - facePointsProc[i+1] += facePointsProc[i]; + for (unsigned long i = 0; i < (unsigned long)size; ++i) facePointsProc[i + 1] += facePointsProc[i]; /*--- Determine the number of faces that has to be sent to each rank. Note that the rank is stored in elemID1, such that the search does not have to be repeated below. ---*/ vector nFacesComm(size, 0); - for(unsigned long i=0; i::iterator low; - low = lower_bound(facePointsProc.begin(), facePointsProc.end(), - localFacesComm[i].cornerPoints[0]); + low = lower_bound(facePointsProc.begin(), facePointsProc.end(), localFacesComm[i].cornerPoints[0]); unsigned long rankFace = low - facePointsProc.begin(); - if(*low > localFacesComm[i].cornerPoints[0]) --rankFace; + if (*low > localFacesComm[i].cornerPoints[0]) --rankFace; ++nFacesComm[rankFace]; localFacesComm[i].elemID1 = rankFace; } /*--- Create the send buffer for the faces to be communicated. ---*/ - vector sendBufFace(9*nFacesLocComm); + vector sendBufFace(9 * nFacesLocComm); vector counter(size); counter[0] = 0; - for(unsigned long i=1; i<(unsigned long)size; ++i) - counter[i] = counter[i-1] + 9*nFacesComm[i-1]; + for (unsigned long i = 1; i < (unsigned long)size; ++i) counter[i] = counter[i - 1] + 9 * nFacesComm[i - 1]; - for(unsigned long i=0; i sizeRecv(size, 1); unsigned long nMessRecv; - SU2_MPI::Reduce_scatter(counter.data(), &nMessRecv, sizeRecv.data(), - MPI_UNSIGNED_LONG, MPI_SUM, SU2_MPI::GetComm()); + SU2_MPI::Reduce_scatter(counter.data(), &nMessRecv, sizeRecv.data(), MPI_UNSIGNED_LONG, MPI_SUM, SU2_MPI::GetComm()); /*--- Send the data using nonblocking sends. ---*/ - vector commReqs(max(nMessSend,nMessRecv)); + vector commReqs(max(nMessSend, nMessRecv)); nMessSend = 0; unsigned long indSend = 0; - for(unsigned long i=0; i<(unsigned long)size; ++i) { - if( nFacesComm[i] ) { - unsigned long count = 9*nFacesComm[i]; - SU2_MPI::Isend(&sendBufFace[indSend], count, MPI_UNSIGNED_LONG, i, i, - SU2_MPI::GetComm(), &commReqs[nMessSend]); + for (unsigned long i = 0; i < (unsigned long)size; ++i) { + if (nFacesComm[i]) { + unsigned long count = 9 * nFacesComm[i]; + SU2_MPI::Isend(&sendBufFace[indSend], count, MPI_UNSIGNED_LONG, i, i, SU2_MPI::GetComm(), &commReqs[nMessSend]); ++nMessSend; indSend += count; } @@ -2145,10 +2063,10 @@ void CPhysicalGeometry::SetColorFEMGrid_Parallel(CConfig *config) { /*--- Loop over the number of ranks from which faces are received. Receive the messages and store them in facesRecv. ---*/ vector facesRecv; - vector nFacesRecv(nMessRecv+1); - vector rankRecv(nMessRecv); + vector nFacesRecv(nMessRecv + 1); + vector rankRecv(nMessRecv); nFacesRecv[0] = 0; - for(unsigned long i=0; i recvBuf(sizeMess); - SU2_MPI::Recv(recvBuf.data(), sizeMess, MPI_UNSIGNED_LONG, - rankRecv[i], rank, SU2_MPI::GetComm(), &status); + SU2_MPI::Recv(recvBuf.data(), sizeMess, MPI_UNSIGNED_LONG, rankRecv[i], rank, SU2_MPI::GetComm(), &status); - nFacesRecv[i+1] = nFacesRecv[i] + sizeMess/9; - facesRecv.resize(nFacesRecv[i+1]); + nFacesRecv[i + 1] = nFacesRecv[i] + sizeMess / 9; + facesRecv.resize(nFacesRecv[i + 1]); unsigned long ii = 0; - for(unsigned long j=nFacesRecv[i]; j::iterator low; - low = lower_bound(localFacesComm.begin(), localFacesComm.end(), - facesRecv[j]); - if(facesRecv[j].elemID0 == low->elemID0) { - sendBufFace[ii+5] = low->elemID1; - sendBufFace[ii+6] = low->nPolySol1; - sendBufFace[ii+7] = low->nDOFsElem1; - sendBufFace[ii+8] = low->elemType1; - } - else { - sendBufFace[ii+5] = low->elemID0; - sendBufFace[ii+6] = low->nPolySol0; - sendBufFace[ii+7] = low->nDOFsElem0; - sendBufFace[ii+8] = low->elemType0; + low = lower_bound(localFacesComm.begin(), localFacesComm.end(), facesRecv[j]); + if (facesRecv[j].elemID0 == low->elemID0) { + sendBufFace[ii + 5] = low->elemID1; + sendBufFace[ii + 6] = low->nPolySol1; + sendBufFace[ii + 7] = low->nDOFsElem1; + sendBufFace[ii + 8] = low->elemType1; + } else { + sendBufFace[ii + 5] = low->elemID0; + sendBufFace[ii + 6] = low->nPolySol0; + sendBufFace[ii + 7] = low->nDOFsElem0; + sendBufFace[ii + 8] = low->elemType0; } } unsigned long count = ii - indSend; - SU2_MPI::Isend(&sendBufFace[indSend], count, MPI_UNSIGNED_LONG, rankRecv[i], - rankRecv[i]+1, SU2_MPI::GetComm(), &commReqs[i]); + SU2_MPI::Isend(&sendBufFace[indSend], count, MPI_UNSIGNED_LONG, rankRecv[i], rankRecv[i] + 1, SU2_MPI::GetComm(), + &commReqs[i]); indSend = ii; } - /*--- Loop over the ranks to which I originally sent my face data. The return data contains information about the neighboring element. ---*/ - for(unsigned long i=0; i recvBuf(sizeMess); - SU2_MPI::Recv(recvBuf.data(), sizeMess, MPI_UNSIGNED_LONG, - status.MPI_SOURCE, rank+1, SU2_MPI::GetComm(), &status); + SU2_MPI::Recv(recvBuf.data(), sizeMess, MPI_UNSIGNED_LONG, status.MPI_SOURCE, rank + 1, SU2_MPI::GetComm(), + &status); sizeMess /= 9; unsigned long jj = 0; - for(unsigned long j=0; j<(unsigned long) sizeMess; ++j, jj+=9) { + for (unsigned long j = 0; j < (unsigned long)sizeMess; ++j, jj += 9) { CFaceOfElement thisFace; - thisFace.nCornerPoints = recvBuf[jj]; - thisFace.cornerPoints[0] = recvBuf[jj+1]; - thisFace.cornerPoints[1] = recvBuf[jj+2]; - thisFace.cornerPoints[2] = recvBuf[jj+3]; - thisFace.cornerPoints[3] = recvBuf[jj+4]; + thisFace.nCornerPoints = recvBuf[jj]; + thisFace.cornerPoints[0] = recvBuf[jj + 1]; + thisFace.cornerPoints[1] = recvBuf[jj + 2]; + thisFace.cornerPoints[2] = recvBuf[jj + 3]; + thisFace.cornerPoints[3] = recvBuf[jj + 4]; vector::iterator low; low = lower_bound(localFaces.begin(), localFaces.end(), thisFace); - low->elemID1 = recvBuf[jj+5]; - low->nPolySol1 = recvBuf[jj+6]; - low->nDOFsElem1 = recvBuf[jj+7]; - low->elemType1 = recvBuf[jj+8]; + low->elemID1 = recvBuf[jj + 5]; + low->nPolySol1 = recvBuf[jj + 6]; + low->nDOFsElem1 = recvBuf[jj + 7]; + low->elemType1 = recvBuf[jj + 8]; } } @@ -2286,10 +2200,10 @@ void CPhysicalGeometry::SetColorFEMGrid_Parallel(CConfig *config) { DeterminePeriodicFacesFEMGrid(config, localFaces); /*--- Determine the total number of non-matching faces in the grid. ---*/ - nFacesLoc = localFaces.size(); + nFacesLoc = localFaces.size(); nFacesLocOr = nFacesLoc; - for(unsigned long i=0; i Global_nElem) { + for (unsigned long i = 0; i < nFacesLocOr; ++i) { + if (localFaces[i].elemID1 > Global_nElem) { localFaces[i].nCornerPoints = 4; localFaces[i].cornerPoints[0] = Global_nPoint; localFaces[i].cornerPoints[1] = Global_nPoint; @@ -2300,7 +2214,7 @@ void CPhysicalGeometry::SetColorFEMGrid_Parallel(CConfig *config) { } nFacesLocOr -= nFacesLoc; - if( nFacesLocOr ) { + if (nFacesLocOr) { sort(localFaces.begin(), localFaces.end()); localFaces.resize(nFacesLoc); } @@ -2308,10 +2222,9 @@ void CPhysicalGeometry::SetColorFEMGrid_Parallel(CConfig *config) { unsigned long nNonMatchingFaces = nFacesLocOr; #ifdef HAVE_MPI - SU2_MPI::Reduce(&nFacesLocOr, &nNonMatchingFaces, 1, MPI_UNSIGNED_LONG, - MPI_SUM, MASTER_NODE, SU2_MPI::GetComm()); + SU2_MPI::Reduce(&nFacesLocOr, &nNonMatchingFaces, 1, MPI_UNSIGNED_LONG, MPI_SUM, MASTER_NODE, SU2_MPI::GetComm()); #endif - if(rank == MASTER_NODE && nNonMatchingFaces) { + if (rank == MASTER_NODE && nNonMatchingFaces) { cout << "There are " << nNonMatchingFaces << " non-matching faces in the grid. " << "These are ignored in the partitioning." << endl; } @@ -2330,65 +2243,51 @@ void CPhysicalGeometry::SetColorFEMGrid_Parallel(CConfig *config) { /*--- Determine the ownership of the internal faces, i.e. which adjacent element is responsible for computing the fluxes through the face. ---*/ - for(unsigned long i=0; iGetTimeLevel(); unsigned short timeLevel1; - if(localFaces[i].elemID1 >= beg_node[rank] && - localFaces[i].elemID1 < beg_node[rank]+nElem) { - + if (localFaces[i].elemID1 >= beg_node[rank] && localFaces[i].elemID1 < beg_node[rank] + nElem) { unsigned long elemID1 = localFaces[i].elemID1 - beg_node[rank]; timeLevel1 = elem[elemID1]->GetTimeLevel(); - } - else { - - map::const_iterator MI; + } else { + map::const_iterator MI; MI = mapExternalElemIDToTimeLevel.find(localFaces[i].elemID1); - if(MI == mapExternalElemIDToTimeLevel.end()) + if (MI == mapExternalElemIDToTimeLevel.end()) SU2_MPI::Error("Entry not found in mapExternalElemIDToTimeLevel", CURRENT_FUNCTION); timeLevel1 = MI->second.short0; } /* Check if both elements have the same time level. */ - if(timeLevel0 == timeLevel1) { - + if (timeLevel0 == timeLevel1) { /* Same time level, hence both elements can own the face. First check whether elemID0 == elemID1 (which happens for periodic problems with only one element in the periodic direction), because this is a special case. */ - if(localFaces[i].elemID0 == localFaces[i].elemID1) { - + if (localFaces[i].elemID0 == localFaces[i].elemID1) { /* This face occurs twice, but should be owned only once. Base this decision on the periodic index. */ localFaces[i].elem0IsOwner = localFaces[i].periodicIndex < localFaces[i].periodicIndexDonor; - } - else { - + } else { /* Different elements on both sides of the face. The ownership decision below makes an attempt to spread the workload evenly. */ const unsigned long sumElemID = localFaces[i].elemID0 + localFaces[i].elemID1; - if( sumElemID%2 ) + if (sumElemID % 2) localFaces[i].elem0IsOwner = localFaces[i].elemID0 < localFaces[i].elemID1; else localFaces[i].elem0IsOwner = localFaces[i].elemID0 > localFaces[i].elemID1; } - } - else { - + } else { /* The time level of both elements differ. The element with the smallest time level must be the owner of the element. */ localFaces[i].elem0IsOwner = timeLevel0 < timeLevel1; } - } - else { - + } else { /* Non-matching face. Give the ownership to element 0. */ localFaces[i].elem0IsOwner = true; } @@ -2397,21 +2296,20 @@ void CPhysicalGeometry::SetColorFEMGrid_Parallel(CConfig *config) { /*--- All the matching face information is known now, including periodic faces. Store the information of the neighbors in the data structure for the local elements. ---*/ - for(unsigned long k=0; kGetCornerPointsAllFaces(nFaces, nPointsPerFace, faceConn); elem[k]->InitializeNeighbors(nFaces); - for(unsigned short i=0; iGetNPolySol(); + for (unsigned short j = 0; j < nPointsPerFace[i]; ++j) thisFace.cornerPoints[j] = faceConn[i][j]; + thisFace.elemID0 = beg_node[rank] + k; + thisFace.nPolySol0 = elem[k]->GetNPolySol(); thisFace.nDOFsElem0 = elem[k]->GetNDOFsSol(); thisFace.CreateUniqueNumbering(); @@ -2419,19 +2317,17 @@ void CPhysicalGeometry::SetColorFEMGrid_Parallel(CConfig *config) { vector::iterator low; low = lower_bound(localFaces.begin(), localFaces.end(), thisFace); - if(low != localFaces.end() ) { - if( !(thisFace < *low) ) { - if(low->elemID0 == thisFace.elemID0) { + if (low != localFaces.end()) { + if (!(thisFace < *low)) { + if (low->elemID0 == thisFace.elemID0) { elem[k]->SetNeighbor_Elements(low->elemID1, i); elem[k]->SetOwnerFace(low->elem0IsOwner, i); - } - else { + } else { elem[k]->SetNeighbor_Elements(low->elemID0, i); elem[k]->SetOwnerFace(!(low->elem0IsOwner), i); } - if(low->periodicIndex > 0) - elem[k]->SetPeriodicIndex(low->periodicIndex-1, i); + if (low->periodicIndex > 0) elem[k]->SetPeriodicIndex(low->periodicIndex - 1, i); } } } @@ -2440,21 +2336,20 @@ void CPhysicalGeometry::SetColorFEMGrid_Parallel(CConfig *config) { /*--- Create the vector of vectors that describe the connectivity of the graph. First the faces. ---*/ vector > adjacency(nElem, vector(0)); - for(unsigned long i=0; i= 0 && ii < (long) nElem) - adjacency[ii].push_back(localFaces[i].elemID0); + if (ii >= 0 && ii < (long)nElem) adjacency[ii].push_back(localFaces[i].elemID0); } } /* It is possible that some neighbors appear multiple times due to e.g. periodic boundary conditions. ParMETIS is not able to deal with this situation, hence these multiple entries must be removed. */ - for(unsigned long i=0; i::iterator lastEntry; lastEntry = unique(adjacency[i].begin(), adjacency[i].end()); @@ -2464,12 +2359,12 @@ void CPhysicalGeometry::SetColorFEMGrid_Parallel(CConfig *config) { /* Due to periodic boundary conditions it is also possible that self entries are present. ParMETIS is not able to deal with self entries, hence they must be removed as well. */ - for(unsigned long i=0; i additionalExternalEntriesGraph; - for(unsigned short iMarker=0; iMarkerGetDomainElement(); - const unsigned long elemID = globalElemID - beg_node[rank]; + const unsigned long elemID = globalElemID - beg_node[rank]; /* Get the number of donor elements for the wall function treatment and the pointer to the array which stores this info. */ const unsigned short nDonors = bound[iMarker][l]->GetNDonorsWallFunctions(); - const unsigned long *donors = bound[iMarker][l]->GetDonorsWallFunctions(); + const unsigned long* donors = bound[iMarker][l]->GetDonorsWallFunctions(); /* Loop over the number of donors and add the entry in the graph, if not already present. */ - for(unsigned short i=0; i= beg_node[rank] && - donors[i] < beg_node[rank]+nElem) { - + if (donors[i] >= beg_node[rank] && donors[i] < beg_node[rank] + nElem) { /* Donor is stored locally. Add the entry to the graph and sort it afterwards. */ const unsigned long localDonorID = donors[i] - beg_node[rank]; adjacency[localDonorID].push_back(globalElemID); sort(adjacency[localDonorID].begin(), adjacency[localDonorID].end()); - } - else { - + } else { /* Donor is stored externally. Store the graph entry in additionalExternalEntriesGraph. */ additionalExternalEntriesGraph.push_back(donors[i]); @@ -2538,50 +2425,47 @@ void CPhysicalGeometry::SetColorFEMGrid_Parallel(CConfig *config) { vector > sendBufsGraphData(size, vector(0)); vector sendToRank(size, 0); - for(unsigned long i=0; i= beg_node[size-1]) rankElem = size-1; + if (elemID >= beg_node[size - 1]) + rankElem = size - 1; else { - const unsigned long *low; - low = lower_bound(beg_node, beg_node+size, elemID); + const unsigned long* low; + low = lower_bound(beg_node, beg_node + size, elemID); rankElem = low - beg_node; - if(*low > elemID) --rankElem; + if (*low > elemID) --rankElem; } sendBufsGraphData[rankElem].push_back(additionalExternalEntriesGraph[i]); - sendBufsGraphData[rankElem].push_back(additionalExternalEntriesGraph[i+1]); + sendBufsGraphData[rankElem].push_back(additionalExternalEntriesGraph[i + 1]); sendToRank[rankElem] = 1; } /*-- Determine to how many ranks this rank will send data and from how many ranks it will receive data. ---*/ int nRankSend = 0; - for(int i=0; i sizeSend(size, 1); - SU2_MPI::Reduce_scatter(sendToRank.data(), &nRankRecv, sizeSend.data(), - MPI_INT, MPI_SUM, SU2_MPI::GetComm()); + SU2_MPI::Reduce_scatter(sendToRank.data(), &nRankRecv, sizeSend.data(), MPI_INT, MPI_SUM, SU2_MPI::GetComm()); /* Send the data using non-blocking sends. */ vector sendReqs(nRankSend); nRankSend = 0; - for(int i=0; i recvBuf(sizeMess); - SU2_MPI::Recv(recvBuf.data(), sizeMess, MPI_UNSIGNED_LONG, - source, rank, SU2_MPI::GetComm(), &status); + SU2_MPI::Recv(recvBuf.data(), sizeMess, MPI_UNSIGNED_LONG, source, rank, SU2_MPI::GetComm(), &status); /* Loop over the contents of the receive buffer and update the graph accordingly. */ - for(int j=0; j vwgt(2*nElem); + vector vwgt(2 * nElem); vector > adjwgt(nElem, vector(0)); - for(unsigned long i=0; i SINGLE_NODE) - { + if (size > SINGLE_NODE) { /*--- The scalar variables and the options array for the call to ParMETIS. ---*/ - idx_t wgtflag = 3; // Weights on both the vertices and edges. - idx_t numflag = 0; // C-numbering. - idx_t ncon = 2; // Number of constraints. - real_t ubvec[] = {1.05, 1.05}; // Tolerances for the vertex weights, recommended value is 1.05. - idx_t nparts = (idx_t)size; // Number of subdomains. Must be number of MPI ranks. - idx_t options[METIS_NOPTIONS]; // Just use the default options. + idx_t wgtflag = 3; // Weights on both the vertices and edges. + idx_t numflag = 0; // C-numbering. + idx_t ncon = 2; // Number of constraints. + real_t ubvec[] = {1.05, 1.05}; // Tolerances for the vertex weights, recommended value is 1.05. + idx_t nparts = (idx_t)size; // Number of subdomains. Must be number of MPI ranks. + idx_t options[METIS_NOPTIONS]; // Just use the default options. METIS_SetDefaultOptions(options); options[1] = 0; /*--- Determine the array, which stores the distribution of the graph nodes over the ranks. ---*/ - vector vtxdist(size+1); + vector vtxdist(size + 1); vtxdist[0] = 0; - for(int i=0; i xadjPar(nElem+1); + vector xadjPar(nElem + 1); xadjPar[0] = 0; - for(unsigned long i=0; i adjacencyPar(xadjPar[nElem]); unsigned long ii = 0; - for(unsigned long i=0; i vwgtPar(nElem*ncon); - for(unsigned long i=0; i vwgtPar(nElem * ncon); + for (unsigned long i = 0; i < nElem * ncon; ++i) vwgtPar[i] = (idx_t)ceil(vwgt[i]); /* Create the adjacency weight in ParMETIS format. */ vector adjwgtPar(xadjPar[nElem]); ii = 0; - for(unsigned long i=0; i tpwgts(size*ncon, 1.0/((real_t)size)); + vector tpwgts(size * ncon, 1.0 / ((real_t)size)); /*--- Calling ParMETIS ---*/ vector part(nElem); @@ -2687,24 +2562,21 @@ void CPhysicalGeometry::SetColorFEMGrid_Parallel(CConfig *config) { idx_t edgecut; MPI_Comm comm = SU2_MPI::GetComm(); - ParMETIS_V3_PartKway(vtxdist.data(), xadjPar.data(), adjacencyPar.data(), - vwgtPar.data(), adjwgtPar.data(), &wgtflag, &numflag, - &ncon, &nparts, tpwgts.data(), ubvec, options, - &edgecut, part.data(), &comm); + ParMETIS_V3_PartKway(vtxdist.data(), xadjPar.data(), adjacencyPar.data(), vwgtPar.data(), adjwgtPar.data(), + &wgtflag, &numflag, &ncon, &nparts, tpwgts.data(), ubvec, options, &edgecut, part.data(), + &comm); if (rank == MASTER_NODE) { cout << " graph partitioning complete ("; cout << edgecut << " edge cuts)." << endl; } /*--- Set the color of the elements to the outcome of ParMETIS. ---*/ - for(unsigned long i=0; iSetColor(part[i]); + for (unsigned long i = 0; i < nElem; ++i) elem[i]->SetColor(part[i]); } -#else /* HAVE_PARMETIS */ +#else /* HAVE_PARMETIS */ - if(size > SINGLE_NODE) - { + if (size > SINGLE_NODE) { if (rank == MASTER_NODE) { cout << endl; cout << "--------------------- WARNING -------------------------------" << endl; @@ -2715,46 +2587,40 @@ void CPhysicalGeometry::SetColorFEMGrid_Parallel(CConfig *config) { } /* Set the color to the current rank. */ - for(unsigned long i=0; iSetColor(rank); + for (unsigned long i = 0; i < nElem; ++i) elem[i]->SetColor(rank); } -#endif /* HAVE_PARMETIS */ +#endif /* HAVE_PARMETIS */ -#endif /* HAVE_MPI */ +#endif /* HAVE_MPI */ } -void CPhysicalGeometry::DeterminePeriodicFacesFEMGrid(CConfig *config, - vector &localFaces) { - +void CPhysicalGeometry::DeterminePeriodicFacesFEMGrid(CConfig* config, vector& localFaces) { /*--- Determine a mapping from the global point ID to the local index of the points. ---*/ - map globalPointIDToLocalInd; - for(unsigned i=0; i globalPointIDToLocalInd; + for (unsigned i = 0; i < nPoint; ++i) { globalPointIDToLocalInd[nodes->GetGlobalIndex(i)] = i; } /*--- Loop over the number of markers present in the grid and check for a periodic one. ---*/ - for(unsigned short iMarker=0; iMarkerGetnMarker_All(); ++iMarker) { - if(config->GetMarker_All_KindBC(iMarker) == PERIODIC_BOUNDARY) { - + for (unsigned short iMarker = 0; iMarker < config->GetnMarker_All(); ++iMarker) { + if (config->GetMarker_All_KindBC(iMarker) == PERIODIC_BOUNDARY) { /*--- Determine the donor marker and the transformation from the current marker to the donor marker. ---*/ unsigned short jMarker = config->GetMarker_Periodic_Donor(config->GetMarker_All_TagBound(iMarker)); auto center = config->GetPeriodicRotCenter(config->GetMarker_All_TagBound(iMarker)); auto angles = config->GetPeriodicRotAngles(config->GetMarker_All_TagBound(iMarker)); - auto trans = config->GetPeriodicTranslation(config->GetMarker_All_TagBound(iMarker)); + auto trans = config->GetPeriodicTranslation(config->GetMarker_All_TagBound(iMarker)); /*--- Store (center+trans) as it is constant and will be added on. ---*/ - su2double translation[] = {center[0] + trans[0], - center[1] + trans[1], - center[2] + trans[2]}; + su2double translation[] = {center[0] + trans[0], center[1] + trans[1], center[2] + trans[2]}; /*--- Store angles separately for clarity. Compute sines/cosines. ---*/ su2double theta = angles[0]; - su2double phi = angles[1]; - su2double psi = angles[2]; + su2double phi = angles[1]; + su2double psi = angles[2]; su2double cosTheta = cos(theta), cosPhi = cos(phi), cosPsi = cos(psi); su2double sinTheta = sin(theta), sinPhi = sin(phi), sinPsi = sin(psi); @@ -2762,17 +2628,17 @@ void CPhysicalGeometry::DeterminePeriodicFacesFEMGrid(CConfig *co /*--- Compute the rotation matrix. Note that the implicit ordering is rotation about the x-axis, y-axis, then z-axis. ---*/ su2double rotMatrix[3][3]; - rotMatrix[0][0] = cosPhi*cosPsi; - rotMatrix[1][0] = cosPhi*sinPsi; + rotMatrix[0][0] = cosPhi * cosPsi; + rotMatrix[1][0] = cosPhi * sinPsi; rotMatrix[2][0] = -sinPhi; - rotMatrix[0][1] = sinTheta*sinPhi*cosPsi - cosTheta*sinPsi; - rotMatrix[1][1] = sinTheta*sinPhi*sinPsi + cosTheta*cosPsi; - rotMatrix[2][1] = sinTheta*cosPhi; + rotMatrix[0][1] = sinTheta * sinPhi * cosPsi - cosTheta * sinPsi; + rotMatrix[1][1] = sinTheta * sinPhi * sinPsi + cosTheta * cosPsi; + rotMatrix[2][1] = sinTheta * cosPhi; - rotMatrix[0][2] = cosTheta*sinPhi*cosPsi + sinTheta*sinPsi; - rotMatrix[1][2] = cosTheta*sinPhi*sinPsi - sinTheta*cosPsi; - rotMatrix[2][2] = cosTheta*cosPhi; + rotMatrix[0][2] = cosTheta * sinPhi * cosPsi + sinTheta * sinPsi; + rotMatrix[1][2] = cosTheta * sinPhi * sinPsi - sinTheta * cosPsi; + rotMatrix[2][2] = cosTheta * cosPhi; /*--- Define the vector to store the faces of the donor. Initialize its size to the number of local donor faces. ---*/ @@ -2784,41 +2650,38 @@ void CPhysicalGeometry::DeterminePeriodicFacesFEMGrid(CConfig *co /*------------------------------------------------------------------*/ /*--- Loop over the local elements of the donor marker. ---*/ - for(unsigned long k=0; kGetCornerPointsAllFaces(nFaces, nPointsPerFace, faceConn); /*--- Search for this face in localFaces. It must be present. ---*/ CFaceOfElement thisFace; thisFace.nCornerPoints = nPointsPerFace[0]; - for(unsigned short j=0; j::iterator low; low = lower_bound(localFaces.begin(), localFaces.end(), thisFace); /*--- Store the relevant data in facesDonor. ---*/ - facesDonor[k].nDim = nDim; + facesDonor[k].nDim = nDim; facesDonor[k].nCornerPoints = nPointsPerFace[0]; - facesDonor[k].elemID = low->elemID0; - facesDonor[k].nPoly = low->nPolySol0; - facesDonor[k].nDOFsElem = low->nDOFsElem0; - facesDonor[k].elemType = low->elemType0; + facesDonor[k].elemID = low->elemID0; + facesDonor[k].nPoly = low->nPolySol0; + facesDonor[k].nDOFsElem = low->nDOFsElem0; + facesDonor[k].elemType = low->elemType0; - for(unsigned short j=0; j::const_iterator MI; + for (unsigned short j = 0; j < nPointsPerFace[0]; ++j) { + map::const_iterator MI; MI = globalPointIDToLocalInd.find(faceConn[0][j]); unsigned long ind = MI->second; - for(unsigned l=0; lGetCoord(ind, l); + for (unsigned l = 0; l < nDim; ++l) facesDonor[k].cornerCoor[j][l] = nodes->GetCoord(ind, l); } /*--- Create the tolerance for this face and sort the coordinates. ---*/ @@ -2833,21 +2696,19 @@ void CPhysicalGeometry::DeterminePeriodicFacesFEMGrid(CConfig *co #ifdef HAVE_MPI /*--- Check if this is indeed a parallel simulation. ---*/ - if(size > 1) { - + if (size > 1) { /*--- Allocate the memory for the size arrays in Allgatherv. ---*/ vector recvCounts(size), displs(size); /*--- Create the values of recvCounts for the gather of the facesDonor. ---*/ int sizeLocal = facesDonor.size(); - SU2_MPI::Allgather(&sizeLocal, 1, MPI_INT, recvCounts.data(), 1, - MPI_INT, SU2_MPI::GetComm()); + SU2_MPI::Allgather(&sizeLocal, 1, MPI_INT, recvCounts.data(), 1, MPI_INT, SU2_MPI::GetComm()); /*--- Create the data for the vector displs from the known values of recvCounts. Also determine the total size of the data. ---*/ displs[0] = 0; - for(int i=1; i shortLocBuf(5*sizeLocal); - vector longLocBuf(sizeLocal); - vector doubleLocBuf(13*sizeLocal); + vector shortLocBuf(5 * sizeLocal); + vector longLocBuf(sizeLocal); + vector doubleLocBuf(13 * sizeLocal); - unsigned long cS=0, cL=0, cD=0; - for(vector::const_iterator fIt =facesDonor.begin(); - fIt!=facesDonor.end(); ++fIt) { + unsigned long cS = 0, cL = 0, cD = 0; + for (vector::const_iterator fIt = facesDonor.begin(); fIt != facesDonor.end(); ++fIt) { shortLocBuf[cS++] = fIt->nCornerPoints; shortLocBuf[cS++] = fIt->nDim; shortLocBuf[cS++] = fIt->nPoly; @@ -2891,43 +2751,42 @@ void CPhysicalGeometry::DeterminePeriodicFacesFEMGrid(CConfig *co /*--- Gather the faces from all ranks to all ranks. Use Allgatherv for this purpose. ---*/ - vector shortGlobBuf(5*sizeGlobal); - vector longGlobBuf(sizeGlobal); - vector doubleGlobBuf(13*sizeGlobal); + vector shortGlobBuf(5 * sizeGlobal); + vector longGlobBuf(sizeGlobal); + vector doubleGlobBuf(13 * sizeGlobal); - SU2_MPI::Allgatherv(longLocBuf.data(), longLocBuf.size(), MPI_UNSIGNED_LONG, - longGlobBuf.data(), recvCounts.data(), displs.data(), - MPI_UNSIGNED_LONG, SU2_MPI::GetComm()); + SU2_MPI::Allgatherv(longLocBuf.data(), longLocBuf.size(), MPI_UNSIGNED_LONG, longGlobBuf.data(), + recvCounts.data(), displs.data(), MPI_UNSIGNED_LONG, SU2_MPI::GetComm()); - for(int i=0; i::iterator fIt =facesDonor.begin(); - fIt!=facesDonor.end(); ++fIt) { + for (vector::iterator fIt = facesDonor.begin(); fIt != facesDonor.end(); ++fIt) { fIt->nCornerPoints = shortGlobBuf[cS++]; - fIt->nDim = shortGlobBuf[cS++]; - fIt->nPoly = shortGlobBuf[cS++]; - fIt->nDOFsElem = shortGlobBuf[cS++]; - fIt->elemType = shortGlobBuf[cS++]; + fIt->nDim = shortGlobBuf[cS++]; + fIt->nPoly = shortGlobBuf[cS++]; + fIt->nDOFsElem = shortGlobBuf[cS++]; + fIt->elemType = shortGlobBuf[cS++]; fIt->elemID = longGlobBuf[cL++]; @@ -2961,21 +2820,19 @@ void CPhysicalGeometry::DeterminePeriodicFacesFEMGrid(CConfig *co /*------------------------------------------------------------------*/ /*--- Loop over the local faces of this boundary marker. ---*/ - for(unsigned long k=0; kGetCornerPointsAllFaces(nFaces, nPointsPerFace, faceConn); /*--- Search for this face in localFaces. It must be present. ---*/ CFaceOfElement thisFace; thisFace.nCornerPoints = nPointsPerFace[0]; - for(unsigned short j=0; j::iterator low; @@ -2989,29 +2846,29 @@ void CPhysicalGeometry::DeterminePeriodicFacesFEMGrid(CConfig *co such that a search can be carried out in donorFaces. Note that the periodic transformation must be applied to the coordinates. ---*/ CMatchingFace thisMatchingFace; - thisMatchingFace.nDim = nDim; + thisMatchingFace.nDim = nDim; thisMatchingFace.nCornerPoints = nPointsPerFace[0]; - thisMatchingFace.elemID = low->elemID0; - thisMatchingFace.nPoly = low->nPolySol0; - thisMatchingFace.nDOFsElem = low->nDOFsElem0; - thisMatchingFace.elemType = low->elemType0; + thisMatchingFace.elemID = low->elemID0; + thisMatchingFace.nPoly = low->nPolySol0; + thisMatchingFace.nDOFsElem = low->nDOFsElem0; + thisMatchingFace.elemType = low->elemType0; - for(unsigned short j=0; j::const_iterator MI; + for (unsigned short j = 0; j < nPointsPerFace[0]; ++j) { + map::const_iterator MI; MI = globalPointIDToLocalInd.find(faceConn[0][j]); unsigned long ind = MI->second; - const su2double *coor = nodes->GetCoord(ind); + const su2double* coor = nodes->GetCoord(ind); - const su2double dx = coor[0] - center[0]; - const su2double dy = coor[1] - center[1]; + const su2double dx = coor[0] - center[0]; + const su2double dy = coor[1] - center[1]; const su2double dz = nDim == 3 ? coor[2] - center[2] : su2double(0.0); - thisMatchingFace.cornerCoor[j][0] = rotMatrix[0][0]*dx + rotMatrix[0][1]*dy - + rotMatrix[0][2]*dz + translation[0]; - thisMatchingFace.cornerCoor[j][1] = rotMatrix[1][0]*dx + rotMatrix[1][1]*dy - + rotMatrix[1][2]*dz + translation[1]; - thisMatchingFace.cornerCoor[j][2] = rotMatrix[2][0]*dx + rotMatrix[2][1]*dy - + rotMatrix[2][2]*dz + translation[2]; + thisMatchingFace.cornerCoor[j][0] = + rotMatrix[0][0] * dx + rotMatrix[0][1] * dy + rotMatrix[0][2] * dz + translation[0]; + thisMatchingFace.cornerCoor[j][1] = + rotMatrix[1][0] * dx + rotMatrix[1][1] * dy + rotMatrix[1][2] * dz + translation[1]; + thisMatchingFace.cornerCoor[j][2] = + rotMatrix[2][0] * dx + rotMatrix[2][1] * dy + rotMatrix[2][2] * dz + translation[2]; } /*--- Create the tolerance for this face and sort the coordinates. ---*/ @@ -3022,12 +2879,12 @@ void CPhysicalGeometry::DeterminePeriodicFacesFEMGrid(CConfig *co vector::const_iterator donorLow; donorLow = lower_bound(facesDonor.begin(), facesDonor.end(), thisMatchingFace); - if(donorLow != facesDonor.end()) { - if( !(thisMatchingFace < *donorLow) ) { - low->elemID1 = donorLow->elemID; - low->nPolySol1 = donorLow->nPoly; - low->nDOFsElem1 = donorLow->nDOFsElem; - low->elemType1 = donorLow->elemType; + if (donorLow != facesDonor.end()) { + if (!(thisMatchingFace < *donorLow)) { + low->elemID1 = donorLow->elemID; + low->nPolySol1 = donorLow->nPoly; + low->nDOFsElem1 = donorLow->nDOFsElem; + low->elemType1 = donorLow->elemType; low->periodicIndexDonor = jMarker + 1; } } @@ -3036,15 +2893,14 @@ void CPhysicalGeometry::DeterminePeriodicFacesFEMGrid(CConfig *co } } -void CPhysicalGeometry::DetermineFEMConstantJacobiansAndLenScale(CConfig *config) { - +void CPhysicalGeometry::DetermineFEMConstantJacobiansAndLenScale(CConfig* config) { /* Definition of the object that is used to carry out the BLAS calls. */ CBlasStructure blasFunctions; /*--- Determine a mapping from the global point ID to the local index of the points. ---*/ - map globalPointIDToLocalInd; - for(unsigned long i=0; i globalPointIDToLocalInd; + for (unsigned long i = 0; i < nPoint; ++i) { globalPointIDToLocalInd[nodes->GetGlobalIndex(i)] = i; } @@ -3054,8 +2910,7 @@ void CPhysicalGeometry::DetermineFEMConstantJacobiansAndLenScale(CConfig *config vector standardVolumeElements, standardFaceElements; /*--- Loop over the local volume elements. ---*/ - for(unsigned long i=0; iGetVTK_Type(); + unsigned short VTK_Type = elem[i]->GetVTK_Type(); unsigned short nPolyGrid = elem[i]->GetNPolyGrid(); unsigned long ii; - for(ii=0; ii vecResult(sizeResult), vecRHS(sizeRHS); /* Store the coordinates in vecRHS. */ unsigned long jj = 0; - for(unsigned short j=0; jGetNode(j); - map::const_iterator MI = globalPointIDToLocalInd.find(nodeID); + map::const_iterator MI = globalPointIDToLocalInd.find(nodeID); unsigned long ind = MI->second; - for(unsigned short k=0; kGetCoord(ind, k); + for (unsigned short k = 0; k < nDim; ++k, ++jj) vecRHS[jj] = nodes->GetCoord(ind, k); } /*--- Get the pointer to the matrix storage of the basis functions and its derivatives. The first nDOFs*nIntegration entries of this matrix correspond to the interpolation data to the integration points and are not needed. Hence this part is skipped. ---*/ - const su2double *matBasisInt = standardVolumeElements[ii].GetMatBasisFunctionsIntegration(); - const su2double *matDerBasisInt = &matBasisInt[nDOFs*nIntegration]; + const su2double* matBasisInt = standardVolumeElements[ii].GetMatBasisFunctionsIntegration(); + const su2double* matDerBasisInt = &matBasisInt[nDOFs * nIntegration]; /* Carry out the matrix matrix product. The last argument is NULL, such that this gemm call is ignored in the profiling. Replace by config if if should be included. */ - blasFunctions.gemm(nDim*nIntegration, nDim, nDOFs, matDerBasisInt, - vecRHS.data(), vecResult.data(), nullptr); + blasFunctions.gemm(nDim * nIntegration, nDim, nDOFs, matDerBasisInt, vecRHS.data(), vecResult.data(), nullptr); /*--- Compute the Jacobians in the integration points and determine the minimum and maximum values. Make a distinction between a 2D and 3D element. ---*/ su2double jacMin = 1.e+25, jacMax = -1.e+25; - switch( nDim ) { + switch (nDim) { case 2: { - /* 2D computation. Store the offset between the r and s derivatives. */ - const unsigned int off = 2*nIntegration; + const unsigned int off = 2 * nIntegration; /*--- Loop over the integration points to compute the Jacobians. ---*/ - for(unsigned short j=0; jSetJacobianConsideredConstant(constJacobian); /*------------------------------------------------------------------------*/ @@ -3180,7 +3031,7 @@ void CPhysicalGeometry::DetermineFEMConstantJacobiansAndLenScale(CConfig *config of this element. ---*/ unsigned short nFaces; unsigned short nPointsPerFace[6]; - unsigned long faceConn[6][4]; + unsigned long faceConn[6][4]; elem[i]->GetCornerPointsAllFaces(nFaces, nPointsPerFace, faceConn); @@ -3190,99 +3041,112 @@ void CPhysicalGeometry::DetermineFEMConstantJacobiansAndLenScale(CConfig *config /*--- Loop over the number of faces of this element. ---*/ su2double jacFaceMax = 0.0; - for(unsigned short j=0; j normalsFace((nDim+1)*nIntegration); + vector normalsFace((nDim + 1) * nIntegration); /*--- Compute the unit normals in the integration points. Make a distinction between two and three dimensions. ---*/ - switch( nDim ) { + switch (nDim) { case 2: { - /*--- Two dimensional case, for which the faces are edges. The normal is the vector normal to the tangent vector of the edge. Loop over the integration points. ---*/ - for(unsigned short k=0; k= 0.999999 && - maxRatioLenFaceNormals <= 1.000001; + constJacobian = minCosAngleFaceNormals >= 0.999999 && maxRatioLenFaceNormals <= 1.000001; elem[i]->SetJacobianConstantFace(constJacobian, j); @@ -3336,36 +3198,33 @@ void CPhysicalGeometry::DetermineFEMConstantJacobiansAndLenScale(CConfig *config /*--- of all the reference elements used in this code. ---*/ /*------------------------------------------------------------------------*/ - const su2double lenScale = 2.0*jacMin/jacFaceMax; + const su2double lenScale = 2.0 * jacMin / jacFaceMax; elem[i]->SetLengthScale(lenScale); } } -void CPhysicalGeometry::DetermineDonorElementsWallFunctions(CConfig *config) { - +void CPhysicalGeometry::DetermineDonorElementsWallFunctions(CConfig* config) { /*--------------------------------------------------------------------------*/ /*--- Step 1: Check whether wall functions are used at all. ---*/ /*--------------------------------------------------------------------------*/ bool wallFunctions = false; - for(unsigned short iMarker=0; iMarkerGetMarker_All_KindBC(iMarker)) { case ISOTHERMAL: case HEAT_FLUX: { const string Marker_Tag = config->GetMarker_All_TagBound(iMarker); - if(config->GetWallFunction_Treatment(Marker_Tag) != WALL_FUNCTIONS::NONE) - wallFunctions = true; + if (config->GetWallFunction_Treatment(Marker_Tag) != WALL_FUNCTIONS::NONE) wallFunctions = true; break; } - default: /* Just to avoid a compiler warning. */ + default: /* Just to avoid a compiler warning. */ break; } } /* If no wall functions are used, nothing needs to be done and a return can be made. */ - if( !wallFunctions ) return; + if (!wallFunctions) return; /*--------------------------------------------------------------------------*/ /*--- Step 2: Build the ADT of the linear sub-elements of the locally ---*/ @@ -3374,8 +3233,8 @@ void CPhysicalGeometry::DetermineDonorElementsWallFunctions(CConfig *config) { /* Determine a mapping from the global point ID to the local index of the points. */ - map globalPointIDToLocalInd; - for(unsigned long i=0; i globalPointIDToLocalInd; + for (unsigned long i = 0; i < nPoint; ++i) { globalPointIDToLocalInd[nodes->GetGlobalIndex(i)] = i; } @@ -3385,65 +3244,61 @@ void CPhysicalGeometry::DetermineDonorElementsWallFunctions(CConfig *config) { /* Define the vectors, which store the mapping from the subelement to the parent element, subelement ID within the parent element, the element type and the connectivity of the subelements. */ - vector parentElement; + vector parentElement; vector subElementIDInParent; vector VTK_TypeElem; - vector elemConn; + vector elemConn; /* Loop over the local volume elements to create the connectivity of the linear sub-elements. */ - for(unsigned long l=0; lGetVTK_Type(); - unsigned short nPolyGrid = elem[l]->GetNPolyGrid(); + unsigned short nPolyGrid = elem[l]->GetNPolyGrid(); unsigned long ii; - for(ii=0; iiGetGlobalElemID()); subElementIDInParent.push_back(jj); VTK_TypeElem.push_back(VTK_Type[i]); - for(unsigned short k=0; kGetNode(connSubElems[i][kk]); - map::const_iterator MI; + map::const_iterator MI; MI = globalPointIDToLocalInd.find(nodeID); elemConn.push_back(MI->second); @@ -3454,17 +3309,15 @@ void CPhysicalGeometry::DetermineDonorElementsWallFunctions(CConfig *config) { /* Store the coordinates of the locally stored nodes in the format expected by the ADT. */ - vector volCoor(nDim*nPoint); + vector volCoor(nDim * nPoint); unsigned long jj = 0; - for(unsigned long l=0; lGetCoord(l, k); + for (unsigned long l = 0; l < nPoint; ++l) { + for (unsigned short k = 0; k < nDim; ++k, ++jj) volCoor[jj] = nodes->GetCoord(l, k); } /* Build the local ADT. */ - CADTElemClass localVolumeADT(nDim, volCoor, elemConn, VTK_TypeElem, - subElementIDInParent, parentElement, false); + CADTElemClass localVolumeADT(nDim, volCoor, elemConn, VTK_TypeElem, subElementIDInParent, parentElement, false); /* Release the memory of the vectors used to build the ADT. To make sure that all the memory is deleted, the swap function is used. */ @@ -3483,53 +3336,46 @@ void CPhysicalGeometry::DetermineDonorElementsWallFunctions(CConfig *config) { and exchange coordinates for the integration points for which no donor element was found in the locally stored volume elements. */ vector markerIDGlobalSearch; - vector boundaryElemIDGlobalSearch; - vector coorExGlobalSearch; - + vector boundaryElemIDGlobalSearch; + vector coorExGlobalSearch; /* Define the standard boundary faces for the solution and the grid. */ - vector standardBoundaryFacesSol, - standardBoundaryFacesGrid; + vector standardBoundaryFacesSol, standardBoundaryFacesGrid; /* Loop over the markers and select the ones for which a wall function treatment must be carried out. */ - for(unsigned short iMarker=0; iMarkerGetMarker_All_KindBC(iMarker)) { case ISOTHERMAL: case HEAT_FLUX: { const string Marker_Tag = config->GetMarker_All_TagBound(iMarker); - if(config->GetWallFunction_Treatment(Marker_Tag) != WALL_FUNCTIONS::NONE) { - + if (config->GetWallFunction_Treatment(Marker_Tag) != WALL_FUNCTIONS::NONE) { /* Retrieve the floating point information for this boundary marker. The exchange location is the first element of this array. */ - const su2double *doubleInfo = config->GetWallFunction_DoubleInfo(Marker_Tag); + const su2double* doubleInfo = config->GetWallFunction_DoubleInfo(Marker_Tag); /* Loop over the local boundary elements for this marker. */ - for(unsigned long l=0; lGetVTK_Type(); - const unsigned long elemID = bound[iMarker][l]->GetDomainElement() - - beg_node[rank]; + const unsigned short VTK_Type = bound[iMarker][l]->GetVTK_Type(); + const unsigned long elemID = bound[iMarker][l]->GetDomainElement() - beg_node[rank]; const unsigned short nPolyGrid = bound[iMarker][l]->GetNPolyGrid(); - const unsigned short nPolySol = elem[elemID]->GetNPolySol(); - const unsigned short VTK_Elem = elem[elemID]->GetVTK_Type(); + const unsigned short nPolySol = elem[elemID]->GetNPolySol(); + const unsigned short VTK_Elem = elem[elemID]->GetVTK_Type(); /* Get the corner points of the boundary element. Note that this is an overloaded function, hence the arguments that allow for multiple faces. */ unsigned short nFaces; unsigned short nPointsPerFace[6]; - unsigned long faceConn[6][4]; + unsigned long faceConn[6][4]; bound[iMarker][l]->GetCornerPointsAllFaces(nFaces, nPointsPerFace, faceConn); /* Create an object of CFaceOfElement to store the information. */ CFaceOfElement boundaryFace; boundaryFace.nCornerPoints = nPointsPerFace[0]; - for(unsigned short i=0; i coorBoundFace(nDim*nDOFs); + vector coorBoundFace(nDim * nDOFs); ii = 0; - for(unsigned short j=0; jGetNode(j); - map::const_iterator MI; + map::const_iterator MI; MI = globalPointIDToLocalInd.find(nodeID); nodeID = MI->second; - for(unsigned short k=0; kGetCoord(nodeID, k); + for (unsigned short k = 0; k < nDim; ++k, ++ii) coorBoundFace[ii] = nodes->GetCoord(nodeID, k); } /* Set the multiplication factor for the normal, such that @@ -3630,39 +3466,40 @@ void CPhysicalGeometry::DetermineDonorElementsWallFunctions(CConfig *config) { /* Allocate the memory for the exchange locations corresponding to the integration points of this face. */ - vector coorExchange(nDim*nInt); + vector coorExchange(nDim * nInt); /* Make a distinction between 2D and 3D to compute the actual coordinates of the exchange locations. */ - switch(nDim) { + switch (nDim) { case 2: { /* Two dimensional computation. Loop over the integration points to compute the corresponding exchange coordinates. */ - for(unsigned short i=0; i donorElementsFace; - for(unsigned short i=0; i recvCounts(size), displs(size); - int nLocalSearchPoints = (int) markerIDGlobalSearch.size(); + int nLocalSearchPoints = (int)markerIDGlobalSearch.size(); - SU2_MPI::Allgather(&nLocalSearchPoints, 1, MPI_INT, recvCounts.data(), 1, - MPI_INT, SU2_MPI::GetComm()); + SU2_MPI::Allgather(&nLocalSearchPoints, 1, MPI_INT, recvCounts.data(), 1, MPI_INT, SU2_MPI::GetComm()); displs[0] = 0; - for(int i=1; i 0) { - + if (nGlobalSearchPoints > 0) { /* Create a cumulative storage version of recvCounts. */ - vector nSearchPerRank(size+1); + vector nSearchPerRank(size + 1); nSearchPerRank[0] = 0; - for(int i=0; i bufMarkerIDGlobalSearch(nGlobalSearchPoints); - SU2_MPI::Allgatherv(markerIDGlobalSearch.data(), nLocalSearchPoints, - MPI_UNSIGNED_SHORT, bufMarkerIDGlobalSearch.data(), - recvCounts.data(), displs.data(), MPI_UNSIGNED_SHORT, + SU2_MPI::Allgatherv(markerIDGlobalSearch.data(), nLocalSearchPoints, MPI_UNSIGNED_SHORT, + bufMarkerIDGlobalSearch.data(), recvCounts.data(), displs.data(), MPI_UNSIGNED_SHORT, SU2_MPI::GetComm()); - vector bufBoundaryElemIDGlobalSearch(nGlobalSearchPoints); - SU2_MPI::Allgatherv(boundaryElemIDGlobalSearch.data(), nLocalSearchPoints, - MPI_UNSIGNED_LONG, bufBoundaryElemIDGlobalSearch.data(), - recvCounts.data(), displs.data(), MPI_UNSIGNED_LONG, + SU2_MPI::Allgatherv(boundaryElemIDGlobalSearch.data(), nLocalSearchPoints, MPI_UNSIGNED_LONG, + bufBoundaryElemIDGlobalSearch.data(), recvCounts.data(), displs.data(), MPI_UNSIGNED_LONG, SU2_MPI::GetComm()); - for(int i=0; i bufCoorExGlobalSearch(nDim*nGlobalSearchPoints); - SU2_MPI::Allgatherv(coorExGlobalSearch.data(), nDim*nLocalSearchPoints, - MPI_DOUBLE, bufCoorExGlobalSearch.data(), - recvCounts.data(), displs.data(), MPI_DOUBLE, - SU2_MPI::GetComm()); + for (int i = 0; i < size; ++i) { + recvCounts[i] *= nDim; + displs[i] *= nDim; + } + vector bufCoorExGlobalSearch(nDim * nGlobalSearchPoints); + SU2_MPI::Allgatherv(coorExGlobalSearch.data(), nDim * nLocalSearchPoints, MPI_DOUBLE, bufCoorExGlobalSearch.data(), + recvCounts.data(), displs.data(), MPI_DOUBLE, SU2_MPI::GetComm()); /* Buffers to store the return information. */ vector markerIDReturn; - vector boundaryElemIDReturn; - vector volElemIDDonorReturn; + vector boundaryElemIDReturn; + vector volElemIDDonorReturn; /* Loop over the number of global search points to check if these points are contained in the volume elements of this rank. The loop is carried @@ -3838,21 +3668,18 @@ void CPhysicalGeometry::DetermineDonorElementsWallFunctions(CConfig *config) { that were not found earlier on this rank. The vector recvCounts is used as storage for the number of search items that must be returned to the other ranks. */ - for(int rankID=0; rankID commReqs(3*nRankSend); + vector commReqs(3 * nRankSend); nRankSend = 0; - for(int i=0; i bufMarkerIDReturn(sizeMess); - vector bufBoundaryElemIDReturn(sizeMess); - vector bufVolElemIDDonorReturn(sizeMess); + vector bufBoundaryElemIDReturn(sizeMess); + vector bufVolElemIDDonorReturn(sizeMess); /* Receive the three messages using blocking receives. */ - SU2_MPI::Recv(bufMarkerIDReturn.data(), sizeMess, MPI_UNSIGNED_SHORT, - source, rank, SU2_MPI::GetComm(), &status); + SU2_MPI::Recv(bufMarkerIDReturn.data(), sizeMess, MPI_UNSIGNED_SHORT, source, rank, SU2_MPI::GetComm(), &status); - SU2_MPI::Recv(bufBoundaryElemIDReturn.data(), sizeMess, MPI_UNSIGNED_LONG, - source, rank+1, SU2_MPI::GetComm(), &status); + SU2_MPI::Recv(bufBoundaryElemIDReturn.data(), sizeMess, MPI_UNSIGNED_LONG, source, rank + 1, SU2_MPI::GetComm(), + &status); - SU2_MPI::Recv(bufVolElemIDDonorReturn.data(), sizeMess, MPI_UNSIGNED_LONG, - source, rank+2, SU2_MPI::GetComm(), &status); + SU2_MPI::Recv(bufVolElemIDDonorReturn.data(), sizeMess, MPI_UNSIGNED_LONG, source, rank + 2, SU2_MPI::GetComm(), + &status); /* Loop over the data just received and add it to the wall function donor information of the corresponding boundary element. */ - for(int j=0; jAddDonorWallFunctions(volID); } @@ -3945,22 +3768,20 @@ void CPhysicalGeometry::DetermineDonorElementsWallFunctions(CConfig *config) { /* Loop again over the boundary elements of the marker for which a wall function treatment must be used and make remove the multiple entries of the donor information. */ - for(unsigned short iMarker=0; iMarkerGetMarker_All_KindBC(iMarker)) { case ISOTHERMAL: case HEAT_FLUX: { const string Marker_Tag = config->GetMarker_All_TagBound(iMarker); - if(config->GetWallFunction_Treatment(Marker_Tag) != WALL_FUNCTIONS::NONE) { - - for(unsigned long l=0; lGetWallFunction_Treatment(Marker_Tag) != WALL_FUNCTIONS::NONE) { + for (unsigned long l = 0; l < nElem_Bound[iMarker]; ++l) bound[iMarker][l]->RemoveMultipleDonorsWallFunctions(); } break; } - default: /* Just to avoid a compiler warning. */ + default: /* Just to avoid a compiler warning. */ break; } } @@ -3969,30 +3790,24 @@ void CPhysicalGeometry::DetermineDonorElementsWallFunctions(CConfig *config) { #endif } -void CPhysicalGeometry::DetermineTimeLevelElements( - CConfig *config, - const vector &localFaces, - map &mapExternalElemIDToTimeLevel) { - +void CPhysicalGeometry::DetermineTimeLevelElements(CConfig* config, const vector& localFaces, + map& mapExternalElemIDToTimeLevel) { /*--------------------------------------------------------------------------*/ /*--- Step 1: Initialize the map mapExternalElemIDToTimeLevel. ---*/ /*--------------------------------------------------------------------------*/ /*--- Initialize the time level of external elements to zero. First the externals from the faces. ---*/ - for(vector::const_iterator FI =localFaces.begin(); - FI!=localFaces.end(); ++FI) { - if(FI->elemID1 < Global_nElem) { // Safeguard against non-matching faces. - - if(FI->elemID1 < beg_node[rank] || - FI->elemID1 >= beg_node[rank]+nElem) { + for (vector::const_iterator FI = localFaces.begin(); FI != localFaces.end(); ++FI) { + if (FI->elemID1 < Global_nElem) { // Safeguard against non-matching faces. + if (FI->elemID1 < beg_node[rank] || FI->elemID1 >= beg_node[rank] + nElem) { /* This element is an external element. Store it in the map mapExternalElemIDToTimeLevel if not already done so. */ - map::iterator MI; + map::iterator MI; MI = mapExternalElemIDToTimeLevel.find(FI->elemID1); - if(MI == mapExternalElemIDToTimeLevel.end()) - mapExternalElemIDToTimeLevel[FI->elemID1] = CUnsignedShort2T(0,0); + if (MI == mapExternalElemIDToTimeLevel.end()) + mapExternalElemIDToTimeLevel[FI->elemID1] = CUnsignedShort2T(0, 0); } } } @@ -4006,40 +3821,36 @@ void CPhysicalGeometry::DetermineTimeLevelElements( /*--- Add the externals from the wall function donors. Loop over the boundary elements of all markers. ---*/ - for(unsigned short iMarker=0; iMarkerGetNDonorsWallFunctions(); - const unsigned long *donors = bound[iMarker][l]->GetDonorsWallFunctions(); + const unsigned long* donors = bound[iMarker][l]->GetDonorsWallFunctions(); /* Loop over the number of donors and add the externals to mapExternalElemIDToTimeLevel, if not already present. */ - for(unsigned short i=0; i= beg_node[rank]+nElem) { - - map::iterator MI; + for (unsigned short i = 0; i < nDonors; ++i) { + if (donors[i] < beg_node[rank] || donors[i] >= beg_node[rank] + nElem) { + map::iterator MI; MI = mapExternalElemIDToTimeLevel.find(donors[i]); - if(MI == mapExternalElemIDToTimeLevel.end()) { - + if (MI == mapExternalElemIDToTimeLevel.end()) { /* Element not present in external. Add it. */ - mapExternalElemIDToTimeLevel[donors[i]] = CUnsignedShort2T(0,0); + mapExternalElemIDToTimeLevel[donors[i]] = CUnsignedShort2T(0, 0); } /* The reverse connection may not be present either. Store the global ID of this element in the send buffers for the additional externals. */ int rankDonor; - if(donors[i] >= beg_node[size-1]) rankDonor = size-1; + if (donors[i] >= beg_node[size - 1]) + rankDonor = size - 1; else { - const unsigned long *low; - low = lower_bound(beg_node, beg_node+size, donors[i]); + const unsigned long* low; + low = lower_bound(beg_node, beg_node + size, donors[i]); rankDonor = (int)(low - beg_node); - if(*low > donors[i]) --rankDonor; + if (*low > donors[i]) --rankDonor; } sendBufAddExternals[rankDonor].push_back(bound[iMarker][l]->GetDomainElement()); @@ -4055,33 +3866,29 @@ void CPhysicalGeometry::DetermineTimeLevelElements( externals to be stored. */ int nRankRecv; vector sizeSend(size, 1); - SU2_MPI::Reduce_scatter(recvFromRank.data(), &nRankRecv, sizeSend.data(), - MPI_INT, MPI_SUM, SU2_MPI::GetComm()); + SU2_MPI::Reduce_scatter(recvFromRank.data(), &nRankRecv, sizeSend.data(), MPI_INT, MPI_SUM, SU2_MPI::GetComm()); /* Determine the number of messages this rank will send. */ int nRankSend = 0; - for(int i=0; i sendReqs(nRankSend); nRankSend = 0; - for(int i=0; i::iterator lastElem = unique(sendBufAddExternals[i].begin(), - sendBufAddExternals[i].end()); + vector::iterator lastElem = unique(sendBufAddExternals[i].begin(), sendBufAddExternals[i].end()); sendBufAddExternals[i].erase(lastElem, sendBufAddExternals[i].end()); - SU2_MPI::Isend(sendBufAddExternals[i].data(), sendBufAddExternals[i].size(), - MPI_UNSIGNED_LONG, i, i, SU2_MPI::GetComm(), &sendReqs[nRankSend++]); + SU2_MPI::Isend(sendBufAddExternals[i].data(), sendBufAddExternals[i].size(), MPI_UNSIGNED_LONG, i, i, + SU2_MPI::GetComm(), &sendReqs[nRankSend++]); } } /* Loop over the number of ranks from which this rank will receive data to be stored in mapExternalElemIDToTimeLevel. */ - for(int i=0; i recvBuf(sizeMess); - SU2_MPI::Recv(recvBuf.data(), sizeMess, MPI_UNSIGNED_LONG, - source, rank, SU2_MPI::GetComm(), &status); + SU2_MPI::Recv(recvBuf.data(), sizeMess, MPI_UNSIGNED_LONG, source, rank, SU2_MPI::GetComm(), &status); /* Loop over the entries of recvBuf and add them to mapExternalElemIDToTimeLevel, if not present already. */ - for(int j=0; j::iterator MI; + for (int j = 0; j < sizeMess; ++j) { + map::iterator MI; MI = mapExternalElemIDToTimeLevel.find(recvBuf[j]); - if(MI == mapExternalElemIDToTimeLevel.end()) - mapExternalElemIDToTimeLevel[recvBuf[j]] = CUnsignedShort2T(0,0); + if (MI == mapExternalElemIDToTimeLevel.end()) mapExternalElemIDToTimeLevel[recvBuf[j]] = CUnsignedShort2T(0, 0); } } @@ -4120,64 +3925,57 @@ void CPhysicalGeometry::DetermineTimeLevelElements( time accurate local time stepping is used. ---*/ const unsigned short nTimeLevels = config->GetnLevels_TimeAccurateLTS(); - if(nTimeLevels == 1) { - + if (nTimeLevels == 1) { /*--- No time accurate local time stepping. Set the time level of all elements to zero. ---*/ - for(unsigned long i=0; iSetTimeLevel(0); - } - else { - + for (unsigned long i = 0; i < nElem; ++i) elem[i]->SetTimeLevel(0); + } else { /*--- Time accurate local time stepping is used. The estimate of the time step is based on free stream values at the moment, but this is easy to change, if needed. ---*/ - const su2double Gamma = config->GetGamma(); + const su2double Gamma = config->GetGamma(); const su2double Prandtl = config->GetPrandtl_Lam(); - const su2double Density = config->GetDensity_FreeStreamND(); - const su2double *Vel = config->GetVelocity_FreeStreamND(); + const su2double Density = config->GetDensity_FreeStreamND(); + const su2double* Vel = config->GetVelocity_FreeStreamND(); const su2double Viscosity = config->GetViscosity_FreeStreamND(); su2double VelMag = 0.0; - for(unsigned short iDim=0; iDimGetMach(); + const su2double SoundSpeed = VelMag / config->GetMach(); /* In the estimate of the time step the spectral radius of the inviscid terms is needed. As the current estimate is based on the free stream, the value of this spectral radius can be computed beforehand. Note that this is a rather conservative estimate. */ su2double charVel2 = 0.0; - for(unsigned short iDim=0; iDim timeStepElements(nElem); - for(unsigned long i=0; iGetNPolySol(); - if(nPoly == 0) nPoly = 1; - const su2double lenScaleInv = nPoly/elem[i]->GetLengthScale(); - const su2double lenScale = 1.0/lenScaleInv; + if (nPoly == 0) nPoly = 1; + const su2double lenScaleInv = nPoly / elem[i]->GetLengthScale(); + const su2double lenScale = 1.0 / lenScaleInv; - timeStepElements[i] = lenScale/(charVel + lenScaleInv*radVisc); - minDeltaT = min(minDeltaT, timeStepElements[i]); + timeStepElements[i] = lenScale / (charVel + lenScaleInv * radVisc); + minDeltaT = min(minDeltaT, timeStepElements[i]); } /* Determine the minimum value of all elements in the grid. @@ -4188,12 +3986,12 @@ void CPhysicalGeometry::DetermineTimeLevelElements( #endif /* Initial estimate of the time level of the owned elements. */ - for(unsigned long i=0; iSetTimeLevel(timeLevel); @@ -4205,35 +4003,34 @@ void CPhysicalGeometry::DetermineTimeLevelElements( /*--- of the external element data. ---*/ /*--------------------------------------------------------------------------*/ - map::iterator MI; + map::iterator MI; #ifdef HAVE_MPI /*--- Determine the ranks from which I receive element data during the actual exchange. ---*/ recvFromRank.assign(size, 0); - for(MI =mapExternalElemIDToTimeLevel.begin(); - MI!=mapExternalElemIDToTimeLevel.end(); ++MI) { - + for (MI = mapExternalElemIDToTimeLevel.begin(); MI != mapExternalElemIDToTimeLevel.end(); ++MI) { /* Determine the rank where this external is stored. */ const unsigned long elemID = MI->first; int rankElem; - if(elemID >= beg_node[size-1]) rankElem = size-1; + if (elemID >= beg_node[size - 1]) + rankElem = size - 1; else { - const unsigned long *low; - low = lower_bound(beg_node, beg_node+size, elemID); + const unsigned long* low; + low = lower_bound(beg_node, beg_node + size, elemID); rankElem = low - beg_node; - if(*low > elemID) --rankElem; + if (*low > elemID) --rankElem; } /* Set the corresponding index of recvFromRank to 1. */ recvFromRank[rankElem] = 1; } - map mapRankToIndRecv; - for(int i=0; i mapRankToIndRecv; + for (int i = 0; i < size; ++i) { + if (recvFromRank[i]) { int ind = mapRankToIndRecv.size(); mapRankToIndRecv[i] = ind; } @@ -4242,28 +4039,26 @@ void CPhysicalGeometry::DetermineTimeLevelElements( /* Determine the number of ranks from which I will receive data and to which I will send data. */ nRankRecv = mapRankToIndRecv.size(); - SU2_MPI::Reduce_scatter(recvFromRank.data(), &nRankSend, sizeSend.data(), - MPI_INT, MPI_SUM, SU2_MPI::GetComm()); + SU2_MPI::Reduce_scatter(recvFromRank.data(), &nRankSend, sizeSend.data(), MPI_INT, MPI_SUM, SU2_MPI::GetComm()); /*--- Create the vector of vectors of the global element ID's that will be received from other ranks. ---*/ vector > recvElem(nRankRecv, vector(0)); - for(MI =mapExternalElemIDToTimeLevel.begin(); - MI!=mapExternalElemIDToTimeLevel.end(); ++MI) { - + for (MI = mapExternalElemIDToTimeLevel.begin(); MI != mapExternalElemIDToTimeLevel.end(); ++MI) { const unsigned long elemID = MI->first; int rankElem; - if(elemID >= beg_node[size-1]) rankElem = size-1; + if (elemID >= beg_node[size - 1]) + rankElem = size - 1; else { - const unsigned long *low; - low = lower_bound(beg_node, beg_node+size, elemID); + const unsigned long* low; + low = lower_bound(beg_node, beg_node + size, elemID); rankElem = low - beg_node; - if(*low > elemID) --rankElem; + if (*low > elemID) --rankElem; } - map::const_iterator MRI = mapRankToIndRecv.find(rankElem); + map::const_iterator MRI = mapRankToIndRecv.find(rankElem); recvElem[MRI->second].push_back(elemID); } @@ -4271,17 +4066,15 @@ void CPhysicalGeometry::DetermineTimeLevelElements( exchange and send over the global element ID's. In order to avoid unnecessary communication, multiple entries are filtered out. ---*/ sendReqs.resize(nRankRecv); - map::const_iterator MRI = mapRankToIndRecv.begin(); - - for(int i=0; i::const_iterator MRI = mapRankToIndRecv.begin(); + for (int i = 0; i < nRankRecv; ++i, ++MRI) { sort(recvElem[i].begin(), recvElem[i].end()); - vector::iterator lastElem = unique(recvElem[i].begin(), - recvElem[i].end()); + vector::iterator lastElem = unique(recvElem[i].begin(), recvElem[i].end()); recvElem[i].erase(lastElem, recvElem[i].end()); - SU2_MPI::Isend(recvElem[i].data(), recvElem[i].size(), MPI_UNSIGNED_LONG, - MRI->first, MRI->first, SU2_MPI::GetComm(), &sendReqs[i]); + SU2_MPI::Isend(recvElem[i].data(), recvElem[i].size(), MPI_UNSIGNED_LONG, MRI->first, MRI->first, + SU2_MPI::GetComm(), &sendReqs[i]); } /*--- Receive the messages in arbitrary sequence and store the requested @@ -4290,8 +4083,7 @@ void CPhysicalGeometry::DetermineTimeLevelElements( vector > sendElem(nRankSend, vector(0)); vector sendRank(nRankSend); - for(int i=0; iGetTimeLevel(); - sendBuf[i][2*j+1] = elem[sendElem[i][j]]->GetNDOFsSol(); + for (int i = 0; i < nRankSend; ++i) { + sendBuf[i].resize(2 * sendElem[i].size()); + for (unsigned long j = 0; j < sendElem[i].size(); ++j) { + sendBuf[i][2 * j] = elem[sendElem[i][j]]->GetTimeLevel(); + sendBuf[i][2 * j + 1] = elem[sendElem[i][j]]->GetNDOFsSol(); } - SU2_MPI::Isend(sendBuf[i].data(), sendBuf[i].size(), MPI_UNSIGNED_SHORT, - sendRank[i], sendRank[i], SU2_MPI::GetComm(), &sendReqs[i]); + SU2_MPI::Isend(sendBuf[i].data(), sendBuf[i].size(), MPI_UNSIGNED_SHORT, sendRank[i], sendRank[i], + SU2_MPI::GetComm(), &sendReqs[i]); } /*--- Receive the data for the externals. As this data is needed immediately, @@ -4348,19 +4137,18 @@ void CPhysicalGeometry::DetermineTimeLevelElements( of the externals is stored in the second entry of the mapExternalElemIDToTimeLevel, which is set accordingly. ---*/ MRI = mapRankToIndRecv.begin(); - for(int i=0; ifirst, rank, SU2_MPI::GetComm(), &status); + SU2_MPI::Recv(returnBuf[i].data(), returnBuf[i].size(), MPI_UNSIGNED_SHORT, MRI->first, rank, SU2_MPI::GetComm(), + &status); - for(unsigned long j=0; jsecond.short0 = returnBuf[i][2*j]; - MI->second.short1 = returnBuf[i][2*j+1]; + MI->second.short0 = returnBuf[i][2 * j]; + MI->second.short1 = returnBuf[i][2 * j + 1]; } } @@ -4382,11 +4170,9 @@ void CPhysicalGeometry::DetermineTimeLevelElements( /*--------------------------------------------------------------------------*/ /* Test for time accurate local time stepping. */ - if(nTimeLevels > 1) { - + if (nTimeLevels > 1) { /* Infinite loop for the iterative algorithm. */ - for(;;) { - + for (;;) { /* Variable to indicate whether the local situation has changed. */ unsigned short localSituationChanged = 0; @@ -4396,66 +4182,58 @@ void CPhysicalGeometry::DetermineTimeLevelElements( restriction, because in the vast majority of cases, the donor element is this adjacent element itself. Requiring it to be the same makes the implementation of the wall functions easier. ---*/ - for(unsigned short iMarker=0; iMarkerGetDomainElement() - - beg_node[rank]; + const unsigned long elemID = bound[iMarker][l]->GetDomainElement() - beg_node[rank]; /* Get the number of donor elements for the wall function treatment and the pointer to the array which stores this info. */ const unsigned short nDonors = bound[iMarker][l]->GetNDonorsWallFunctions(); - const unsigned long *donors = bound[iMarker][l]->GetDonorsWallFunctions(); + const unsigned long* donors = bound[iMarker][l]->GetDonorsWallFunctions(); /* Loop over the number of donors and check the time levels. */ - for(unsigned short i=0; i= beg_node[rank] && - donors[i] < beg_node[rank]+nElem) { - + if (donors[i] >= beg_node[rank] && donors[i] < beg_node[rank] + nElem) { /* Donor is stored locally. Determine its local ID and get the time levels of both elements. */ - const unsigned long donorID = donors[i] - beg_node[rank]; + const unsigned long donorID = donors[i] - beg_node[rank]; const unsigned short timeLevelB = elem[elemID]->GetTimeLevel(); const unsigned short timeLevelD = elem[donorID]->GetTimeLevel(); - const unsigned short timeLevel = min(timeLevelB, timeLevelD); + const unsigned short timeLevel = min(timeLevelB, timeLevelD); /* If the time level of either element is larger than timeLevel, adapt the time levels and indicate that the local situation has changed. */ - if(timeLevelB > timeLevel) { + if (timeLevelB > timeLevel) { elem[elemID]->SetTimeLevel(timeLevel); localSituationChanged = 1; } - if(timeLevelD > timeLevel) { + if (timeLevelD > timeLevel) { elem[donorID]->SetTimeLevel(timeLevel); localSituationChanged = 1; } - } - else { - + } else { /* The donor element is stored on a different processor. Retrieve its time level from mapExternalElemIDToTimeLevel and determine the minimum time level. */ const unsigned short timeLevelB = elem[elemID]->GetTimeLevel(); MI = mapExternalElemIDToTimeLevel.find(donors[i]); - if(MI == mapExternalElemIDToTimeLevel.end()) - SU2_MPI::Error("Entry not found in mapExternalElemIDToTimeLevel", - CURRENT_FUNCTION); + if (MI == mapExternalElemIDToTimeLevel.end()) + SU2_MPI::Error("Entry not found in mapExternalElemIDToTimeLevel", CURRENT_FUNCTION); const unsigned short timeLevel = min(timeLevelB, MI->second.short0); /* If the time level of either element is larger than timeLevel, adapt the time levels and indicate that the local situation has changed. */ - if(timeLevelB > timeLevel) { + if (timeLevelB > timeLevel) { elem[elemID]->SetTimeLevel(timeLevel); localSituationChanged = 1; } - if(MI->second.short0 > timeLevel) { + if (MI->second.short0 > timeLevel) { MI->second.short0 = timeLevel; localSituationChanged = 1; } @@ -4466,61 +4244,54 @@ void CPhysicalGeometry::DetermineTimeLevelElements( /*--- Loop over the matching faces and update the time levels of the adjacent elements, if needed. ---*/ - for(vector::const_iterator FI =localFaces.begin(); - FI!=localFaces.end(); ++FI) { + for (vector::const_iterator FI = localFaces.begin(); FI != localFaces.end(); ++FI) { /* Safeguard against non-matching faces. */ - if(FI->elemID1 < Global_nElem) { - + if (FI->elemID1 < Global_nElem) { /* Local element ID of the first element. Per definition this is always a locally stored element. Also store its time level. */ - const unsigned long elemID0 = FI->elemID0 - beg_node[rank]; + const unsigned long elemID0 = FI->elemID0 - beg_node[rank]; const unsigned short timeLevel0 = elem[elemID0]->GetTimeLevel(); /* Determine the status of the second element. */ - if(FI->elemID1 >= beg_node[rank] && - FI->elemID1 < beg_node[rank]+nElem) { - + if (FI->elemID1 >= beg_node[rank] && FI->elemID1 < beg_node[rank] + nElem) { /* Both elements are stored locally. Determine the local element of the second element and determine the minimum time level. */ - const unsigned long elemID1 = FI->elemID1 - beg_node[rank]; + const unsigned long elemID1 = FI->elemID1 - beg_node[rank]; const unsigned short timeLevel1 = elem[elemID1]->GetTimeLevel(); - const unsigned short timeLevel = min(timeLevel0, timeLevel1); + const unsigned short timeLevel = min(timeLevel0, timeLevel1); /* If the time level of either element is larger than timeLevel+1, adapt the time levels and indicate that the local situation has changed. */ - if(timeLevel0 > timeLevel+1) { - elem[elemID0]->SetTimeLevel(timeLevel+1); + if (timeLevel0 > timeLevel + 1) { + elem[elemID0]->SetTimeLevel(timeLevel + 1); localSituationChanged = 1; } - if(timeLevel1 > timeLevel+1) { - elem[elemID1]->SetTimeLevel(timeLevel+1); + if (timeLevel1 > timeLevel + 1) { + elem[elemID1]->SetTimeLevel(timeLevel + 1); localSituationChanged = 1; } - } - else { - + } else { /* The second element is stored on a different processor. Retrieve its time level from mapExternalElemIDToTimeLevel and determine the minimum time level. */ MI = mapExternalElemIDToTimeLevel.find(FI->elemID1); - if(MI == mapExternalElemIDToTimeLevel.end()) - SU2_MPI::Error("Entry not found in mapExternalElemIDToTimeLevel", - CURRENT_FUNCTION); + if (MI == mapExternalElemIDToTimeLevel.end()) + SU2_MPI::Error("Entry not found in mapExternalElemIDToTimeLevel", CURRENT_FUNCTION); const unsigned short timeLevel = min(timeLevel0, MI->second.short0); /* If the time level of either element is larger than timeLevel+1, adapt the time levels and indicate that the local situation has changed. */ - if(timeLevel0 > timeLevel+1) { - elem[elemID0]->SetTimeLevel(timeLevel+1); + if (timeLevel0 > timeLevel + 1) { + elem[elemID0]->SetTimeLevel(timeLevel + 1); localSituationChanged = 1; } - if(MI->second.short0 > timeLevel+1) { - MI->second.short0 = timeLevel+1; + if (MI->second.short0 > timeLevel + 1) { + MI->second.short0 = timeLevel + 1; localSituationChanged = 1; } } @@ -4532,25 +4303,23 @@ void CPhysicalGeometry::DetermineTimeLevelElements( unsigned short globalSituationChanged = localSituationChanged; #ifdef HAVE_MPI - SU2_MPI::Allreduce(&localSituationChanged, &globalSituationChanged, - 1, MPI_UNSIGNED_SHORT, MPI_MAX, SU2_MPI::GetComm()); + SU2_MPI::Allreduce(&localSituationChanged, &globalSituationChanged, 1, MPI_UNSIGNED_SHORT, MPI_MAX, + SU2_MPI::GetComm()); #endif - if( !globalSituationChanged ) break; + if (!globalSituationChanged) break; - /*--- Communicate the information of the externals, if needed. ---*/ + /*--- Communicate the information of the externals, if needed. ---*/ #ifdef HAVE_MPI /*--- Copy the information of the time level into the send buffers and send the data using non-blocking sends. Note that the size of sendElem is used and not sendBuf, because the size of sendBuf is twice the size, see step 4. ---*/ - for(int i=0; iGetTimeLevel(); - for(unsigned long j=0; jGetTimeLevel(); - - SU2_MPI::Isend(sendBuf[i].data(), sendElem[i].size(), MPI_UNSIGNED_SHORT, - sendRank[i], sendRank[i], SU2_MPI::GetComm(), &sendReqs[i]); + SU2_MPI::Isend(sendBuf[i].data(), sendElem[i].size(), MPI_UNSIGNED_SHORT, sendRank[i], sendRank[i], + SU2_MPI::GetComm(), &sendReqs[i]); } /*--- Receive the data for the externals. As this data is needed @@ -4563,22 +4332,21 @@ void CPhysicalGeometry::DetermineTimeLevelElements( of recvElem is used and not returnBuf, because the latter is twice as large, see step 4. ---*/ MRI = mapRankToIndRecv.begin(); - for(int i=0; ifirst, rank, SU2_MPI::GetComm(), &status); + SU2_MPI::Recv(returnBuf[i].data(), recvElem[i].size(), MPI_UNSIGNED_SHORT, MRI->first, rank, SU2_MPI::GetComm(), + &status); - for(unsigned long j=0; jsecond.short0 = min(returnBuf[i][j], MI->second.short0); - returnBuf[i][j] = MI->second.short0; + returnBuf[i][j] = MI->second.short0; } - SU2_MPI::Isend(returnBuf[i].data(), recvElem[i].size(), MPI_UNSIGNED_SHORT, - MRI->first, MRI->first+1, SU2_MPI::GetComm(), &returnReqs[i]); + SU2_MPI::Isend(returnBuf[i].data(), recvElem[i].size(), MPI_UNSIGNED_SHORT, MRI->first, MRI->first + 1, + SU2_MPI::GetComm(), &returnReqs[i]); } /* Complete the first round of nonblocking sends, such that the @@ -4589,14 +4357,12 @@ void CPhysicalGeometry::DetermineTimeLevelElements( /* Loop again over the original sending processors to receive the updated time level of elements that may have been updated on other ranks. */ - for(int i=0; iSetTimeLevel(sendBuf[i][j]); + for (unsigned long j = 0; j < sendElem[i].size(); ++j) elem[sendElem[i][j]]->SetTimeLevel(sendBuf[i][j]); } /* Complete the second round of nonblocking sends. */ @@ -4609,52 +4375,43 @@ void CPhysicalGeometry::DetermineTimeLevelElements( /*--- time level. ---*/ /*------------------------------------------------------------------------*/ - if(rank == MASTER_NODE) - cout << endl <<"------- Element distribution for time accurate local time stepping ------" << endl; + if (rank == MASTER_NODE) + cout << endl << "------- Element distribution for time accurate local time stepping ------" << endl; /* Determine the local number of elements per time level. */ vector nLocalElemPerLevel(nTimeLevels, 0); - for(unsigned long i=0; iGetTimeLevel()]; + for (unsigned long i = 0; i < nElem; ++i) ++nLocalElemPerLevel[elem[i]->GetTimeLevel()]; /* Determine the global version of nLocalElemPerLevel. This only needs to be known on the master node. */ vector nGlobalElemPerLevel = nLocalElemPerLevel; #ifdef HAVE_MPI - SU2_MPI::Reduce(nLocalElemPerLevel.data(), nGlobalElemPerLevel.data(), - nTimeLevels, MPI_UNSIGNED_LONG, MPI_SUM, - MASTER_NODE, SU2_MPI::GetComm()); + SU2_MPI::Reduce(nLocalElemPerLevel.data(), nGlobalElemPerLevel.data(), nTimeLevels, MPI_UNSIGNED_LONG, MPI_SUM, + MASTER_NODE, SU2_MPI::GetComm()); #endif /* Write the output. */ - if(rank == MASTER_NODE) { - for(unsigned short i=0; i &localFaces, - const vector > &adjacency, - const map &mapExternalElemIDToTimeLevel, - vector &vwgt, - vector > &adjwgt) { - +void CPhysicalGeometry::ComputeFEMGraphWeights(CConfig* config, const vector& localFaces, + const vector >& adjacency, + const map& mapExternalElemIDToTimeLevel, + vector& vwgt, vector >& adjwgt) { /*--- Determine the maximum time level that occurs in the grid. ---*/ unsigned short maxTimeLevel = 0; - for(unsigned long i=0; iGetTimeLevel()); + for (unsigned long i = 0; i < nElem; ++i) maxTimeLevel = max(maxTimeLevel, elem[i]->GetTimeLevel()); #ifdef HAVE_MPI unsigned short maxTimeLevelLocal = maxTimeLevel; - SU2_MPI::Allreduce(&maxTimeLevelLocal, &maxTimeLevel, 1, - MPI_UNSIGNED_SHORT, MPI_MAX, SU2_MPI::GetComm()); + SU2_MPI::Allreduce(&maxTimeLevelLocal, &maxTimeLevel, 1, MPI_UNSIGNED_SHORT, MPI_MAX, SU2_MPI::GetComm()); #endif /*--------------------------------------------------------------------------*/ @@ -4667,7 +4424,7 @@ void CPhysicalGeometry::ComputeFEMGraphWeights( /*--- Define the standard elements for the volume elements, the boundary faces and the matching internal faces. ---*/ - vector standardElements; + vector standardElements; vector standardBoundaryFaces; vector standardMatchingFaces; @@ -4676,32 +4433,29 @@ void CPhysicalGeometry::ComputeFEMGraphWeights( surface integral to allow for Discontinuous and Continuous Galerkin schemes. For the latter the contribution of the surface integral will be negligible to the total amount of work. ---*/ - for(unsigned long i=0; iGetVTK_Type(); unsigned short nPolySol = elem[i]->GetNPolySol(); - bool JacIsConstant = elem[i]->GetJacobianConsideredConstant(); + bool JacIsConstant = elem[i]->GetJacobianConsideredConstant(); unsigned long ii; - for(ii=0; iiGetCornerPointsAllFaces(nFaces, nPointsPerFace, faceConn); /*--- Loop over the number of faces of this element. ---*/ - for(unsigned short j=0; j::const_iterator low; low = lower_bound(localFaces.begin(), localFaces.end(), thisFace); bool thisFaceFound = false; - if(low != localFaces.end()) { - if( !(thisFace < *low) ) thisFaceFound = true; + if (low != localFaces.end()) { + if (!(thisFace < *low)) thisFaceFound = true; } - if( thisFaceFound ) { - + if (thisFaceFound) { /* Check if this internal matching face is owned by this element. */ bool faceIsOwned; - if(elemID == low->elemID0) faceIsOwned = low->elem0IsOwner; - else faceIsOwned = !low->elem0IsOwner; - - if( faceIsOwned ) { + if (elemID == low->elemID0) + faceIsOwned = low->elem0IsOwner; + else + faceIsOwned = !low->elem0IsOwner; + if (faceIsOwned) { /*--- Determine the index of the corresponding standard matching face. If it does not exist, create it. ---*/ - for(ii=0; iielemType0, low->nPolySol0, - low->elemType1, low->nPolySol1, - false, false) ) + for (ii = 0; ii < standardMatchingFaces.size(); ++ii) { + if (standardMatchingFaces[ii].SameStandardMatchingFace(VTK_Type_Face, JacIsConstant, low->elemType0, + low->nPolySol0, low->elemType1, low->nPolySol1, + false, false)) break; } - if(ii == standardMatchingFaces.size()) - standardMatchingFaces.push_back(CFEMStandardInternalFace(VTK_Type_Face, - low->elemType0, low->nPolySol0, - low->elemType1, low->nPolySol1, - JacIsConstant, false, false, - config)); + if (ii == standardMatchingFaces.size()) + standardMatchingFaces.push_back(CFEMStandardInternalFace(VTK_Type_Face, low->elemType0, low->nPolySol0, + low->elemType1, low->nPolySol1, JacIsConstant, + false, false, config)); /* Update the computational work for this element, i.e. the 1st vertex weight. */ vwgt[ind0] += standardMatchingFaces[ii].WorkEstimateMetis(config); } - } - else { - + } else { /*--- This is a boundary face, which is owned by definition. Determine the index of the corresponding standard boundary face. If it does not exist, create it. ---*/ - for(ii=0; iiGetMarker_All_KindBC(iMarker)) { case ISOTHERMAL: case HEAT_FLUX: { const string Marker_Tag = config->GetMarker_All_TagBound(iMarker); - if(config->GetWallFunction_Treatment(Marker_Tag) != WALL_FUNCTIONS::NONE) { - + if (config->GetWallFunction_Treatment(Marker_Tag) != WALL_FUNCTIONS::NONE) { /* Retrieve the integer information for this boundary marker. The number of points in normal direction for the wall function treatment is the first element of this array. */ - const unsigned short *shortInfo = config->GetWallFunction_IntInfo(Marker_Tag); + const unsigned short* shortInfo = config->GetWallFunction_IntInfo(Marker_Tag); /* Loop over the local boundary elements for this marker. */ - for(unsigned long l=0; lGetVTK_Type(); - const unsigned long elemID = bound[iMarker][l]->GetDomainElement() - - beg_node[rank]; - const unsigned short nPolySol = elem[elemID]->GetNPolySol(); + const unsigned long elemID = bound[iMarker][l]->GetDomainElement() - beg_node[rank]; + const unsigned short nPolySol = elem[elemID]->GetNPolySol(); const unsigned short VTK_Type_Elem = elem[elemID]->GetVTK_Type(); - const bool JacIsConstant = bound[iMarker][l]->GetJacobianConsideredConstant(); + const bool JacIsConstant = bound[iMarker][l]->GetJacobianConsideredConstant(); /* Determine the corresponding entry in the standard elements for boundary faces. This entry must be found. */ unsigned long ii; - for(ii=0; iiGetTimeLevel(); - vwgt[2*i] *= pow(2, diffLevel); + vwgt[2 * i] *= pow(2, diffLevel); } /*--- Determine the minimum of the workload of the elements, i.e. 1st vertex weight, over the entire domain. ---*/ su2double minvwgt = vwgt[0]; - for(unsigned long i=0; iGetTimeLevel(); - const unsigned short nDOFs0 = elem[i]->GetNDOFsSol(); + const unsigned short nDOFs0 = elem[i]->GetNDOFsSol(); /* Loop over the number of entries in the graph for this element. */ - for(unsigned long j=0; j= beg_node[rank] && - adjacency[i][j] < beg_node[rank]+nElem) { - + if (adjacency[i][j] >= beg_node[rank] && adjacency[i][j] < beg_node[rank] + nElem) { /* Locally stored element. Determine its local ID and set the time level and number of solution DOFs. */ unsigned long elemID1 = adjacency[i][j] - beg_node[rank]; timeLevel1 = elem[elemID1]->GetTimeLevel(); - nDOFs1 = elem[elemID1]->GetNDOFsSol(); - } - else { - + nDOFs1 = elem[elemID1]->GetNDOFsSol(); + } else { /* The neighbor is an external element. Find it in mapExternalElemIDToTimeLevel and set the time level and number of solution DOFs accordingly. */ - map::const_iterator MI; + map::const_iterator MI; MI = mapExternalElemIDToTimeLevel.find(adjacency[i][j]); - if(MI == mapExternalElemIDToTimeLevel.end()) + if (MI == mapExternalElemIDToTimeLevel.end()) SU2_MPI::Error("Entry not found in mapExternalElemIDToTimeLevel", CURRENT_FUNCTION); timeLevel1 = MI->second.short0; - nDOFs1 = MI->second.short1; + nDOFs1 = MI->second.short1; } /* Determine the difference of the maximum time level that occurs and @@ -4954,7 +4695,7 @@ void CPhysicalGeometry::ComputeFEMGraphWeights( /* Set the edge weight. As ParMetis expects an undirected graph, set the edge weight to the sum of the number of DOFs on both sides, multiplied by the weight factor to account for different time levels. */ - adjwgt[i][j] = pow(2, diffLevel) *(nDOFs0 + nDOFs1); + adjwgt[i][j] = pow(2, diffLevel) * (nDOFs0 + nDOFs1); } } } diff --git a/Common/src/geometry/CDummyGeometry.cpp b/Common/src/geometry/CDummyGeometry.cpp index 433eefa5b0a..44f820d8877 100644 --- a/Common/src/geometry/CDummyGeometry.cpp +++ b/Common/src/geometry/CDummyGeometry.cpp @@ -27,15 +27,13 @@ #include "../../include/geometry/CDummyGeometry.hpp" - -CDummyGeometry::CDummyGeometry(CConfig *config) : CGeometry() { - +CDummyGeometry::CDummyGeometry(CConfig* config) : CGeometry() { nZone = config->GetnZone(); - nPoint_P2PSend = new int[size] (); - nPoint_P2PRecv = new int[size] (); + nPoint_P2PSend = new int[size](); + nPoint_P2PRecv = new int[size](); - nVertex = new unsigned long[config->GetnMarker_All()] (); + nVertex = new unsigned long[config->GetnMarker_All()](); Tag_to_Marker = new string[config->GetnMarker_All()]; diff --git a/Common/src/geometry/CGeometry.cpp b/Common/src/geometry/CGeometry.cpp index ad15762ce5e..8035608ebc9 100644 --- a/Common/src/geometry/CGeometry.cpp +++ b/Common/src/geometry/CGeometry.cpp @@ -33,20 +33,14 @@ #include "../../include/toolboxes/geometry_toolbox.hpp" #include "../../include/toolboxes/ndflattener.hpp" -CGeometry::CGeometry(void) : - size(SU2_MPI::GetSize()), - rank(SU2_MPI::GetRank()) { - -} +CGeometry::CGeometry(void) : size(SU2_MPI::GetSize()), rank(SU2_MPI::GetRank()) {} CGeometry::~CGeometry(void) { - unsigned long iElem, iElem_Bound, iVertex; unsigned short iMarker; if (elem != nullptr) { - for (iElem = 0; iElem < nElem; iElem++) - delete elem[iElem]; + for (iElem = 0; iElem < nElem; iElem++) delete elem[iElem]; delete[] elem; } @@ -55,9 +49,9 @@ CGeometry::~CGeometry(void) { for (iElem_Bound = 0; iElem_Bound < nElem_Bound[iMarker]; iElem_Bound++) { delete bound[iMarker][iElem_Bound]; } - delete [] bound[iMarker]; + delete[] bound[iMarker]; } - delete [] bound; + delete[] bound; } delete nodes; @@ -69,83 +63,80 @@ CGeometry::~CGeometry(void) { for (iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { delete vertex[iMarker][iVertex]; } - delete [] vertex[iMarker]; + delete[] vertex[iMarker]; } - delete [] vertex; + delete[] vertex; } - delete [] nElem_Bound; - delete [] nVertex; - delete [] Marker_All_SendRecv; - delete [] Tag_to_Marker; + delete[] nElem_Bound; + delete[] nVertex; + delete[] Marker_All_SendRecv; + delete[] Tag_to_Marker; - delete [] beg_node; - delete [] end_node; - delete [] nPointLinear; - delete [] nPointCumulative; + delete[] beg_node; + delete[] end_node; + delete[] nPointLinear; + delete[] nPointCumulative; - if(CustomBoundaryHeatFlux != nullptr){ - for(iMarker=0; iMarker < nMarker; iMarker++){ - delete [] CustomBoundaryHeatFlux[iMarker]; + if (CustomBoundaryHeatFlux != nullptr) { + for (iMarker = 0; iMarker < nMarker; iMarker++) { + delete[] CustomBoundaryHeatFlux[iMarker]; } - delete [] CustomBoundaryHeatFlux; + delete[] CustomBoundaryHeatFlux; } - if(CustomBoundaryTemperature != nullptr){ - for(iMarker=0; iMarker < nMarker; iMarker++){ - delete [] CustomBoundaryTemperature[iMarker]; + if (CustomBoundaryTemperature != nullptr) { + for (iMarker = 0; iMarker < nMarker; iMarker++) { + delete[] CustomBoundaryTemperature[iMarker]; } - delete [] CustomBoundaryTemperature; + delete[] CustomBoundaryTemperature; } /*--- Delete structures for MPI point-to-point communication. ---*/ - delete [] bufD_P2PRecv; - delete [] bufD_P2PSend; + delete[] bufD_P2PRecv; + delete[] bufD_P2PSend; - delete [] bufS_P2PRecv; - delete [] bufS_P2PSend; + delete[] bufS_P2PRecv; + delete[] bufS_P2PSend; - delete [] req_P2PSend; - delete [] req_P2PRecv; + delete[] req_P2PSend; + delete[] req_P2PRecv; - delete [] nPoint_P2PRecv; - delete [] nPoint_P2PSend; + delete[] nPoint_P2PRecv; + delete[] nPoint_P2PSend; - delete [] Neighbors_P2PSend; - delete [] Neighbors_P2PRecv; + delete[] Neighbors_P2PSend; + delete[] Neighbors_P2PRecv; - delete [] Local_Point_P2PSend; - delete [] Local_Point_P2PRecv; + delete[] Local_Point_P2PSend; + delete[] Local_Point_P2PRecv; /*--- Delete structures for MPI periodic communication. ---*/ - delete [] bufD_PeriodicRecv; - delete [] bufD_PeriodicSend; - - delete [] bufS_PeriodicRecv; - delete [] bufS_PeriodicSend; + delete[] bufD_PeriodicRecv; + delete[] bufD_PeriodicSend; - delete [] req_PeriodicSend; - delete [] req_PeriodicRecv; + delete[] bufS_PeriodicRecv; + delete[] bufS_PeriodicSend; - delete [] nPoint_PeriodicRecv; - delete [] nPoint_PeriodicSend; + delete[] req_PeriodicSend; + delete[] req_PeriodicRecv; - delete [] Neighbors_PeriodicSend; - delete [] Neighbors_PeriodicRecv; + delete[] nPoint_PeriodicRecv; + delete[] nPoint_PeriodicSend; - delete [] Local_Point_PeriodicSend; - delete [] Local_Point_PeriodicRecv; + delete[] Neighbors_PeriodicSend; + delete[] Neighbors_PeriodicRecv; - delete [] Local_Marker_PeriodicSend; - delete [] Local_Marker_PeriodicRecv; + delete[] Local_Point_PeriodicSend; + delete[] Local_Point_PeriodicRecv; + delete[] Local_Marker_PeriodicSend; + delete[] Local_Marker_PeriodicRecv; } -void CGeometry::PreprocessP2PComms(CGeometry *geometry, - CConfig *config) { - +void CGeometry::PreprocessP2PComms(CGeometry* geometry, CConfig* config) { /*--- We start with the send and receive lists already available in the form of SEND_RECEIVE boundary markers. We will loop through these markers and establish the neighboring ranks and number of @@ -159,91 +150,94 @@ void CGeometry::PreprocessP2PComms(CGeometry *geometry, /*--- Local variables. ---*/ unsigned short iMarker; - unsigned long nVertexS, nVertexR, iVertex, MarkerS, MarkerR; + unsigned long nVertexS, nVertexR, iVertex, MarkerS, MarkerR; int iRank, iSend, iRecv, count; /*--- Create some temporary structures for tracking sends/recvs. ---*/ - int *nPoint_Send_All = new int[size+1]; nPoint_Send_All[0] = 0; - int *nPoint_Recv_All = new int[size+1]; nPoint_Recv_All[0] = 0; - int *nPoint_Flag = new int[size]; + int* nPoint_Send_All = new int[size + 1]; + nPoint_Send_All[0] = 0; + int* nPoint_Recv_All = new int[size + 1]; + nPoint_Recv_All[0] = 0; + int* nPoint_Flag = new int[size]; for (iRank = 0; iRank < size; iRank++) { - nPoint_Send_All[iRank] = 0; nPoint_Recv_All[iRank] = 0; nPoint_Flag[iRank]= -1; + nPoint_Send_All[iRank] = 0; + nPoint_Recv_All[iRank] = 0; + nPoint_Flag[iRank] = -1; } - nPoint_Send_All[size] = 0; nPoint_Recv_All[size] = 0; + nPoint_Send_All[size] = 0; + nPoint_Recv_All[size] = 0; /*--- Loop through all of our SEND_RECEIVE markers and track our sends with each rank. ---*/ for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { - if ((config->GetMarker_All_KindBC(iMarker) == SEND_RECEIVE) && - (config->GetMarker_All_SendRecv(iMarker) > 0)) { - + if ((config->GetMarker_All_KindBC(iMarker) == SEND_RECEIVE) && (config->GetMarker_All_SendRecv(iMarker) > 0)) { /*--- Get the destination rank and number of points to send. ---*/ - iRank = config->GetMarker_All_SendRecv(iMarker)-1; + iRank = config->GetMarker_All_SendRecv(iMarker) - 1; nVertexS = geometry->nVertex[iMarker]; /*--- If we have not visited this element yet, increment our number of elements that must be sent to a particular proc. ---*/ if ((nPoint_Flag[iRank] != (int)iMarker)) { - nPoint_Flag[iRank] = (int)iMarker; - nPoint_Send_All[iRank+1] += nVertexS; + nPoint_Flag[iRank] = (int)iMarker; + nPoint_Send_All[iRank + 1] += nVertexS; } - } } - delete [] nPoint_Flag; + delete[] nPoint_Flag; /*--- Communicate the number of points to be sent/recv'd amongst all processors. After this communication, each proc knows how many cells it will receive from each other processor. ---*/ - SU2_MPI::Alltoall(&(nPoint_Send_All[1]), 1, MPI_INT, - &(nPoint_Recv_All[1]), 1, MPI_INT, SU2_MPI::GetComm()); + SU2_MPI::Alltoall(&(nPoint_Send_All[1]), 1, MPI_INT, &(nPoint_Recv_All[1]), 1, MPI_INT, SU2_MPI::GetComm()); /*--- Prepare to send connectivities. First check how many messages we will be sending and receiving. Here we also put the counters into cumulative storage format to make the communications simpler. ---*/ - nP2PSend = 0; nP2PRecv = 0; + nP2PSend = 0; + nP2PRecv = 0; for (iRank = 0; iRank < size; iRank++) { - if ((iRank != rank) && (nPoint_Send_All[iRank+1] > 0)) nP2PSend++; - if ((iRank != rank) && (nPoint_Recv_All[iRank+1] > 0)) nP2PRecv++; + if ((iRank != rank) && (nPoint_Send_All[iRank + 1] > 0)) nP2PSend++; + if ((iRank != rank) && (nPoint_Recv_All[iRank + 1] > 0)) nP2PRecv++; - nPoint_Send_All[iRank+1] += nPoint_Send_All[iRank]; - nPoint_Recv_All[iRank+1] += nPoint_Recv_All[iRank]; + nPoint_Send_All[iRank + 1] += nPoint_Send_All[iRank]; + nPoint_Recv_All[iRank + 1] += nPoint_Recv_All[iRank]; } /*--- Allocate only as much memory as we need for the P2P neighbors. ---*/ - nPoint_P2PSend = new int[nP2PSend+1]; nPoint_P2PSend[0] = 0; - nPoint_P2PRecv = new int[nP2PRecv+1]; nPoint_P2PRecv[0] = 0; + nPoint_P2PSend = new int[nP2PSend + 1]; + nPoint_P2PSend[0] = 0; + nPoint_P2PRecv = new int[nP2PRecv + 1]; + nPoint_P2PRecv[0] = 0; Neighbors_P2PSend = new int[nP2PSend]; Neighbors_P2PRecv = new int[nP2PRecv]; - iSend = 0; iRecv = 0; + iSend = 0; + iRecv = 0; for (iRank = 0; iRank < size; iRank++) { - - if ((nPoint_Send_All[iRank+1] > nPoint_Send_All[iRank]) && (iRank != rank)) { + if ((nPoint_Send_All[iRank + 1] > nPoint_Send_All[iRank]) && (iRank != rank)) { Neighbors_P2PSend[iSend] = iRank; - nPoint_P2PSend[iSend+1] = nPoint_Send_All[iRank+1]; + nPoint_P2PSend[iSend + 1] = nPoint_Send_All[iRank + 1]; iSend++; } - if ((nPoint_Recv_All[iRank+1] > nPoint_Recv_All[iRank]) && (iRank != rank)) { + if ((nPoint_Recv_All[iRank + 1] > nPoint_Recv_All[iRank]) && (iRank != rank)) { Neighbors_P2PRecv[iRecv] = iRank; - nPoint_P2PRecv[iRecv+1] = nPoint_Recv_All[iRank+1]; + nPoint_P2PRecv[iRecv + 1] = nPoint_Recv_All[iRank + 1]; iRecv++; } - } /*--- Create a reverse mapping of the message to the rank so that we @@ -251,15 +245,13 @@ void CGeometry::PreprocessP2PComms(CGeometry *geometry, messages dynamically. ---*/ P2PSend2Neighbor.clear(); - for (iSend = 0; iSend < nP2PSend; iSend++) - P2PSend2Neighbor[Neighbors_P2PSend[iSend]] = iSend; + for (iSend = 0; iSend < nP2PSend; iSend++) P2PSend2Neighbor[Neighbors_P2PSend[iSend]] = iSend; P2PRecv2Neighbor.clear(); - for (iRecv = 0; iRecv < nP2PRecv; iRecv++) - P2PRecv2Neighbor[Neighbors_P2PRecv[iRecv]] = iRecv; + for (iRecv = 0; iRecv < nP2PRecv; iRecv++) P2PRecv2Neighbor[Neighbors_P2PRecv[iRecv]] = iRecv; - delete [] nPoint_Send_All; - delete [] nPoint_Recv_All; + delete[] nPoint_Send_All; + delete[] nPoint_Recv_All; /*--- Allocate the memory that we need for receiving the conn values and then cue up the non-blocking receives. Note that @@ -268,13 +260,11 @@ void CGeometry::PreprocessP2PComms(CGeometry *geometry, Local_Point_P2PSend = nullptr; Local_Point_P2PSend = new unsigned long[nPoint_P2PSend[nP2PSend]]; - for (iSend = 0; iSend < nPoint_P2PSend[nP2PSend]; iSend++) - Local_Point_P2PSend[iSend] = 0; + for (iSend = 0; iSend < nPoint_P2PSend[nP2PSend]; iSend++) Local_Point_P2PSend[iSend] = 0; Local_Point_P2PRecv = nullptr; Local_Point_P2PRecv = new unsigned long[nPoint_P2PRecv[nP2PRecv]]; - for (iRecv = 0; iRecv < nPoint_P2PRecv[nP2PRecv]; iRecv++) - Local_Point_P2PRecv[iRecv] = 0; + for (iRecv = 0; iRecv < nPoint_P2PRecv[nP2PRecv]; iRecv++) Local_Point_P2PRecv[iRecv] = 0; /*--- We allocate the memory for communicating values in a later step once we know the maximum packet size that we need to communicate. This @@ -290,10 +280,10 @@ void CGeometry::PreprocessP2PComms(CGeometry *geometry, /*--- Allocate memory for the MPI requests if we need to communicate. ---*/ if (nP2PSend > 0) { - req_P2PSend = new SU2_MPI::Request[nP2PSend]; + req_P2PSend = new SU2_MPI::Request[nP2PSend]; } if (nP2PRecv > 0) { - req_P2PRecv = new SU2_MPI::Request[nP2PRecv]; + req_P2PRecv = new SU2_MPI::Request[nP2PRecv]; } /*--- Build lists of local index values for send. ---*/ @@ -301,12 +291,10 @@ void CGeometry::PreprocessP2PComms(CGeometry *geometry, count = 0; for (iSend = 0; iSend < nP2PSend; iSend++) { for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { - if ((config->GetMarker_All_KindBC(iMarker) == SEND_RECEIVE) && - (config->GetMarker_All_SendRecv(iMarker) > 0)) { - - MarkerS = iMarker; + if ((config->GetMarker_All_KindBC(iMarker) == SEND_RECEIVE) && (config->GetMarker_All_SendRecv(iMarker) > 0)) { + MarkerS = iMarker; nVertexS = geometry->nVertex[MarkerS]; - iRank = config->GetMarker_All_SendRecv(MarkerS)-1; + iRank = config->GetMarker_All_SendRecv(MarkerS) - 1; if (iRank == Neighbors_P2PSend[iSend]) { for (iVertex = 0; iVertex < nVertexS; iVertex++) { @@ -314,7 +302,6 @@ void CGeometry::PreprocessP2PComms(CGeometry *geometry, count++; } } - } } } @@ -324,12 +311,10 @@ void CGeometry::PreprocessP2PComms(CGeometry *geometry, count = 0; for (iRecv = 0; iRecv < nP2PRecv; iRecv++) { for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { - if ((config->GetMarker_All_KindBC(iMarker) == SEND_RECEIVE) && - (config->GetMarker_All_SendRecv(iMarker) > 0)) { - - MarkerR = iMarker+1; + if ((config->GetMarker_All_KindBC(iMarker) == SEND_RECEIVE) && (config->GetMarker_All_SendRecv(iMarker) > 0)) { + MarkerR = iMarker + 1; nVertexR = geometry->nVertex[MarkerR]; - iRank = abs(config->GetMarker_All_SendRecv(MarkerR))-1; + iRank = abs(config->GetMarker_All_SendRecv(MarkerR)) - 1; if (iRank == Neighbors_P2PRecv[iRecv]) { for (iVertex = 0; iVertex < nVertexR; iVertex++) { @@ -337,7 +322,6 @@ void CGeometry::PreprocessP2PComms(CGeometry *geometry, count++; } } - } } } @@ -345,11 +329,9 @@ void CGeometry::PreprocessP2PComms(CGeometry *geometry, /*--- In the future, some additional data structures could be created here to separate the interior and boundary nodes in order to help further overlap computation and communication. ---*/ - } void CGeometry::AllocateP2PComms(unsigned short countPerPoint) { - /*--- This routine is activated whenever we attempt to perform a point-to-point MPI communication with our neighbors but the memory buffer allocated is not large enough for the packet size. @@ -360,36 +342,29 @@ void CGeometry::AllocateP2PComms(unsigned short countPerPoint) { if (countPerPoint <= maxCountPerPoint) return; BEGIN_SU2_OMP_SAFE_GLOBAL_ACCESS { + /*--- Store the larger packet size to the class data. ---*/ - /*--- Store the larger packet size to the class data. ---*/ - - maxCountPerPoint = countPerPoint; - - /*-- Deallocate and reallocate our su2double cummunication memory. ---*/ + maxCountPerPoint = countPerPoint; - delete [] bufD_P2PSend; - bufD_P2PSend = new su2double[maxCountPerPoint*nPoint_P2PSend[nP2PSend]] (); + /*-- Deallocate and reallocate our su2double cummunication memory. ---*/ - delete [] bufD_P2PRecv; - bufD_P2PRecv = new su2double[maxCountPerPoint*nPoint_P2PRecv[nP2PRecv]] (); + delete[] bufD_P2PSend; + bufD_P2PSend = new su2double[maxCountPerPoint * nPoint_P2PSend[nP2PSend]](); - delete [] bufS_P2PSend; - bufS_P2PSend = new unsigned short[maxCountPerPoint*nPoint_P2PSend[nP2PSend]] (); + delete[] bufD_P2PRecv; + bufD_P2PRecv = new su2double[maxCountPerPoint * nPoint_P2PRecv[nP2PRecv]](); - delete [] bufS_P2PRecv; - bufS_P2PRecv = new unsigned short[maxCountPerPoint*nPoint_P2PRecv[nP2PRecv]] (); + delete[] bufS_P2PSend; + bufS_P2PSend = new unsigned short[maxCountPerPoint * nPoint_P2PSend[nP2PSend]](); + delete[] bufS_P2PRecv; + bufS_P2PRecv = new unsigned short[maxCountPerPoint * nPoint_P2PRecv[nP2PRecv]](); } END_SU2_OMP_SAFE_GLOBAL_ACCESS - } -void CGeometry::PostP2PRecvs(CGeometry *geometry, - const CConfig *config, - unsigned short commType, - unsigned short countPerPoint, - bool val_reverse) const { - +void CGeometry::PostP2PRecvs(CGeometry* geometry, const CConfig* config, unsigned short commType, + unsigned short countPerPoint, bool val_reverse) const { /*--- Launch the non-blocking recv's first. Note that we have stored the counts and sources, so we can launch these before we even load the data and send from the neighbor ranks. ---*/ @@ -403,21 +378,20 @@ void CGeometry::PostP2PRecvs(CGeometry *geometry, send nodes become the recv nodes and vice-versa. ---*/ if (val_reverse) { - /*--- Compute our location in the buffer using the send data structure since we are reversing the comms. ---*/ - auto offset = countPerPoint*nPoint_P2PSend[iRecv]; + auto offset = countPerPoint * nPoint_P2PSend[iRecv]; /*--- Take advantage of cumulative storage format to get the number of elems that we need to recv. Note again that we select the send points here as the recv points. ---*/ - auto nPointP2P = nPoint_P2PSend[iRecv+1] - nPoint_P2PSend[iRecv]; + auto nPointP2P = nPoint_P2PSend[iRecv + 1] - nPoint_P2PSend[iRecv]; /*--- Total count can include multiple pieces of data per element. ---*/ - auto count = countPerPoint*nPointP2P; + auto count = countPerPoint * nPointP2P; /*--- Get the rank from which we receive the message. Note again that we use the send rank as the source instead of the recv rank. ---*/ @@ -431,33 +405,31 @@ void CGeometry::PostP2PRecvs(CGeometry *geometry, switch (commType) { case COMM_TYPE_DOUBLE: - SU2_MPI::Irecv(&(bufD_P2PSend[offset]), count, MPI_DOUBLE, - source, tag, SU2_MPI::GetComm(), &(req_P2PRecv[iRecv])); + SU2_MPI::Irecv(&(bufD_P2PSend[offset]), count, MPI_DOUBLE, source, tag, SU2_MPI::GetComm(), + &(req_P2PRecv[iRecv])); break; case COMM_TYPE_UNSIGNED_SHORT: - SU2_MPI::Irecv(&(bufS_P2PSend[offset]), count, MPI_UNSIGNED_SHORT, - source, tag, SU2_MPI::GetComm(), &(req_P2PRecv[iRecv])); + SU2_MPI::Irecv(&(bufS_P2PSend[offset]), count, MPI_UNSIGNED_SHORT, source, tag, SU2_MPI::GetComm(), + &(req_P2PRecv[iRecv])); break; default: - SU2_MPI::Error("Unrecognized data type for point-to-point MPI comms.", - CURRENT_FUNCTION); + SU2_MPI::Error("Unrecognized data type for point-to-point MPI comms.", CURRENT_FUNCTION); break; } } else { - /*--- Compute our location in the recv buffer. ---*/ - auto offset = countPerPoint*nPoint_P2PRecv[iRecv]; + auto offset = countPerPoint * nPoint_P2PRecv[iRecv]; /*--- Take advantage of cumulative storage format to get the number of elems that we need to recv. ---*/ - auto nPointP2P = nPoint_P2PRecv[iRecv+1] - nPoint_P2PRecv[iRecv]; + auto nPointP2P = nPoint_P2PRecv[iRecv + 1] - nPoint_P2PRecv[iRecv]; /*--- Total count can include multiple pieces of data per element. ---*/ - auto count = countPerPoint*nPointP2P; + auto count = countPerPoint * nPointP2P; /*--- Get the rank from which we receive the message. ---*/ @@ -468,33 +440,24 @@ void CGeometry::PostP2PRecvs(CGeometry *geometry, switch (commType) { case COMM_TYPE_DOUBLE: - SU2_MPI::Irecv(&(bufD_P2PRecv[offset]), count, MPI_DOUBLE, - source, tag, SU2_MPI::GetComm(), &(req_P2PRecv[iMessage])); + SU2_MPI::Irecv(&(bufD_P2PRecv[offset]), count, MPI_DOUBLE, source, tag, SU2_MPI::GetComm(), + &(req_P2PRecv[iMessage])); break; case COMM_TYPE_UNSIGNED_SHORT: - SU2_MPI::Irecv(&(bufS_P2PRecv[offset]), count, MPI_UNSIGNED_SHORT, - source, tag, SU2_MPI::GetComm(), &(req_P2PRecv[iMessage])); + SU2_MPI::Irecv(&(bufS_P2PRecv[offset]), count, MPI_UNSIGNED_SHORT, source, tag, SU2_MPI::GetComm(), + &(req_P2PRecv[iMessage])); break; default: - SU2_MPI::Error("Unrecognized data type for point-to-point MPI comms.", - CURRENT_FUNCTION); + SU2_MPI::Error("Unrecognized data type for point-to-point MPI comms.", CURRENT_FUNCTION); break; } - } - } END_SU2_OMP_MASTER - } -void CGeometry::PostP2PSends(CGeometry *geometry, - const CConfig *config, - unsigned short commType, - unsigned short countPerPoint, - int val_iSend, - bool val_reverse) const { - +void CGeometry::PostP2PSends(CGeometry* geometry, const CConfig* config, unsigned short commType, + unsigned short countPerPoint, int val_iSend, bool val_reverse) const { /*--- Post the non-blocking send as soon as the buffer is loaded. ---*/ /*--- In some instances related to the adjoint solver, we need @@ -503,21 +466,20 @@ void CGeometry::PostP2PSends(CGeometry *geometry, SU2_OMP_MASTER if (val_reverse) { - /*--- Compute our location in the buffer using the recv data structure since we are reversing the comms. ---*/ - auto offset = countPerPoint*nPoint_P2PRecv[val_iSend]; + auto offset = countPerPoint * nPoint_P2PRecv[val_iSend]; /*--- Take advantage of cumulative storage format to get the number of points that we need to send. Note again that we select the recv points here as the send points. ---*/ - auto nPointP2P = nPoint_P2PRecv[val_iSend+1] - nPoint_P2PRecv[val_iSend]; + auto nPointP2P = nPoint_P2PRecv[val_iSend + 1] - nPoint_P2PRecv[val_iSend]; /*--- Total count can include multiple pieces of data per element. ---*/ - auto count = countPerPoint*nPointP2P; + auto count = countPerPoint * nPointP2P; /*--- Get the rank to which we send the message. Note again that we use the recv rank as the dest instead of the send rank. ---*/ @@ -531,33 +493,31 @@ void CGeometry::PostP2PSends(CGeometry *geometry, switch (commType) { case COMM_TYPE_DOUBLE: - SU2_MPI::Isend(&(bufD_P2PRecv[offset]), count, MPI_DOUBLE, - dest, tag, SU2_MPI::GetComm(), &(req_P2PSend[val_iSend])); + SU2_MPI::Isend(&(bufD_P2PRecv[offset]), count, MPI_DOUBLE, dest, tag, SU2_MPI::GetComm(), + &(req_P2PSend[val_iSend])); break; case COMM_TYPE_UNSIGNED_SHORT: - SU2_MPI::Isend(&(bufS_P2PRecv[offset]), count, MPI_UNSIGNED_SHORT, - dest, tag, SU2_MPI::GetComm(), &(req_P2PSend[val_iSend])); + SU2_MPI::Isend(&(bufS_P2PRecv[offset]), count, MPI_UNSIGNED_SHORT, dest, tag, SU2_MPI::GetComm(), + &(req_P2PSend[val_iSend])); break; default: - SU2_MPI::Error("Unrecognized data type for point-to-point MPI comms.", - CURRENT_FUNCTION); + SU2_MPI::Error("Unrecognized data type for point-to-point MPI comms.", CURRENT_FUNCTION); break; } } else { - /*--- Compute our location in the send buffer. ---*/ - auto offset = countPerPoint*nPoint_P2PSend[val_iSend]; + auto offset = countPerPoint * nPoint_P2PSend[val_iSend]; /*--- Take advantage of cumulative storage format to get the number of points that we need to send. ---*/ - auto nPointP2P = nPoint_P2PSend[val_iSend+1] - nPoint_P2PSend[val_iSend]; + auto nPointP2P = nPoint_P2PSend[val_iSend + 1] - nPoint_P2PSend[val_iSend]; /*--- Total count can include multiple pieces of data per element. ---*/ - auto count = countPerPoint*nPointP2P; + auto count = countPerPoint * nPointP2P; /*--- Get the rank to which we send the message. ---*/ @@ -568,70 +528,61 @@ void CGeometry::PostP2PSends(CGeometry *geometry, switch (commType) { case COMM_TYPE_DOUBLE: - SU2_MPI::Isend(&(bufD_P2PSend[offset]), count, MPI_DOUBLE, - dest, tag, SU2_MPI::GetComm(), &(req_P2PSend[val_iSend])); + SU2_MPI::Isend(&(bufD_P2PSend[offset]), count, MPI_DOUBLE, dest, tag, SU2_MPI::GetComm(), + &(req_P2PSend[val_iSend])); break; case COMM_TYPE_UNSIGNED_SHORT: - SU2_MPI::Isend(&(bufS_P2PSend[offset]), count, MPI_UNSIGNED_SHORT, - dest, tag, SU2_MPI::GetComm(), &(req_P2PSend[val_iSend])); + SU2_MPI::Isend(&(bufS_P2PSend[offset]), count, MPI_UNSIGNED_SHORT, dest, tag, SU2_MPI::GetComm(), + &(req_P2PSend[val_iSend])); break; default: - SU2_MPI::Error("Unrecognized data type for point-to-point MPI comms.", - CURRENT_FUNCTION); + SU2_MPI::Error("Unrecognized data type for point-to-point MPI comms.", CURRENT_FUNCTION); break; } - } END_SU2_OMP_MASTER - } -void CGeometry::GetCommCountAndType(const CConfig* config, - unsigned short commType, - unsigned short &COUNT_PER_POINT, - unsigned short &MPI_TYPE) const { +void CGeometry::GetCommCountAndType(const CConfig* config, unsigned short commType, unsigned short& COUNT_PER_POINT, + unsigned short& MPI_TYPE) const { switch (commType) { case COORDINATES: - COUNT_PER_POINT = nDim; - MPI_TYPE = COMM_TYPE_DOUBLE; + COUNT_PER_POINT = nDim; + MPI_TYPE = COMM_TYPE_DOUBLE; break; case GRID_VELOCITY: - COUNT_PER_POINT = nDim; - MPI_TYPE = COMM_TYPE_DOUBLE; + COUNT_PER_POINT = nDim; + MPI_TYPE = COMM_TYPE_DOUBLE; break; case COORDINATES_OLD: if (config->GetTime_Marching() == TIME_MARCHING::DT_STEPPING_2ND) - COUNT_PER_POINT = nDim*2; + COUNT_PER_POINT = nDim * 2; else - COUNT_PER_POINT = nDim; - MPI_TYPE = COMM_TYPE_DOUBLE; + COUNT_PER_POINT = nDim; + MPI_TYPE = COMM_TYPE_DOUBLE; break; case MAX_LENGTH: - COUNT_PER_POINT = 1; - MPI_TYPE = COMM_TYPE_DOUBLE; + COUNT_PER_POINT = 1; + MPI_TYPE = COMM_TYPE_DOUBLE; break; case NEIGHBORS: - COUNT_PER_POINT = 1; - MPI_TYPE = COMM_TYPE_UNSIGNED_SHORT; + COUNT_PER_POINT = 1; + MPI_TYPE = COMM_TYPE_UNSIGNED_SHORT; break; default: - SU2_MPI::Error("Unrecognized quantity for point-to-point MPI comms.", - CURRENT_FUNCTION); + SU2_MPI::Error("Unrecognized quantity for point-to-point MPI comms.", CURRENT_FUNCTION); break; } } -void CGeometry::InitiateComms(CGeometry *geometry, - const CConfig *config, - unsigned short commType) const { - +void CGeometry::InitiateComms(CGeometry* geometry, const CConfig* config, unsigned short commType) const { if (nP2PSend == 0) return; /*--- Local variables ---*/ unsigned short iDim; unsigned short COUNT_PER_POINT = 0; - unsigned short MPI_TYPE = 0; + unsigned short MPI_TYPE = 0; unsigned long iPoint, msg_offset, buf_offset; @@ -650,10 +601,10 @@ void CGeometry::InitiateComms(CGeometry *geometry, /*--- Set some local pointers to make access simpler. ---*/ - su2double *bufDSend = geometry->bufD_P2PSend; - unsigned short *bufSSend = geometry->bufS_P2PSend; + su2double* bufDSend = geometry->bufD_P2PSend; + unsigned short* bufSSend = geometry->bufS_P2PSend; - su2double *vector = nullptr; + su2double* vector = nullptr; /*--- Load the specified quantity from the solver into the generic communication buffer in the geometry class. ---*/ @@ -663,46 +614,42 @@ void CGeometry::InitiateComms(CGeometry *geometry, geometry->PostP2PRecvs(geometry, config, MPI_TYPE, COUNT_PER_POINT, false); for (iMessage = 0; iMessage < nP2PSend; iMessage++) { - /*--- Get the offset in the buffer for the start of this message. ---*/ msg_offset = nPoint_P2PSend[iMessage]; /*--- Total count can include multiple pieces of data per element. ---*/ - nSend = (nPoint_P2PSend[iMessage+1] - nPoint_P2PSend[iMessage]); + nSend = (nPoint_P2PSend[iMessage + 1] - nPoint_P2PSend[iMessage]); SU2_OMP_FOR_STAT(OMP_MIN_SIZE) for (iSend = 0; iSend < nSend; iSend++) { - /*--- Get the local index for this communicated data. ---*/ iPoint = geometry->Local_Point_P2PSend[msg_offset + iSend]; /*--- Compute the offset in the recv buffer for this point. ---*/ - buf_offset = (msg_offset + iSend)*COUNT_PER_POINT; + buf_offset = (msg_offset + iSend) * COUNT_PER_POINT; switch (commType) { case COORDINATES: vector = nodes->GetCoord(iPoint); - for (iDim = 0; iDim < nDim; iDim++) - bufDSend[buf_offset+iDim] = vector[iDim]; + for (iDim = 0; iDim < nDim; iDim++) bufDSend[buf_offset + iDim] = vector[iDim]; break; case GRID_VELOCITY: vector = nodes->GetGridVel(iPoint); - for (iDim = 0; iDim < nDim; iDim++) - bufDSend[buf_offset+iDim] = vector[iDim]; + for (iDim = 0; iDim < nDim; iDim++) bufDSend[buf_offset + iDim] = vector[iDim]; break; case COORDINATES_OLD: vector = nodes->GetCoord_n(iPoint); for (iDim = 0; iDim < nDim; iDim++) { - bufDSend[buf_offset+iDim] = vector[iDim]; + bufDSend[buf_offset + iDim] = vector[iDim]; } if (config->GetTime_Marching() == TIME_MARCHING::DT_STEPPING_2ND) { vector = nodes->GetCoord_n1(iPoint); for (iDim = 0; iDim < nDim; iDim++) { - bufDSend[buf_offset+nDim+iDim] = vector[iDim]; + bufDSend[buf_offset + nDim + iDim] = vector[iDim]; } } break; @@ -713,8 +660,7 @@ void CGeometry::InitiateComms(CGeometry *geometry, bufSSend[buf_offset] = geometry->nodes->GetnNeighbor(iPoint); break; default: - SU2_MPI::Error("Unrecognized quantity for point-to-point MPI comms.", - CURRENT_FUNCTION); + SU2_MPI::Error("Unrecognized quantity for point-to-point MPI comms.", CURRENT_FUNCTION); break; } } @@ -723,15 +669,10 @@ void CGeometry::InitiateComms(CGeometry *geometry, /*--- Launch the point-to-point MPI send for this message. ---*/ geometry->PostP2PSends(geometry, config, MPI_TYPE, COUNT_PER_POINT, iMessage, false); - } - } -void CGeometry::CompleteComms(CGeometry *geometry, - const CConfig *config, - unsigned short commType) { - +void CGeometry::CompleteComms(CGeometry* geometry, const CConfig* config, unsigned short commType) { if (nP2PRecv == 0) return; /*--- Local variables ---*/ @@ -750,8 +691,8 @@ void CGeometry::CompleteComms(CGeometry *geometry, /*--- Set some local pointers to make access simpler. ---*/ - const su2double *bufDRecv = geometry->bufD_P2PRecv; - const unsigned short *bufSRecv = geometry->bufS_P2PRecv; + const su2double* bufDRecv = geometry->bufD_P2PRecv; + const unsigned short* bufSRecv = geometry->bufS_P2PRecv; /*--- Store the data that was communicated into the appropriate location within the local class data structures. Note that we @@ -759,7 +700,6 @@ void CGeometry::CompleteComms(CGeometry *geometry, non-blocking comms. ---*/ for (iMessage = 0; iMessage < nP2PRecv; iMessage++) { - /*--- For efficiency, recv the messages dynamically based on the order they arrive. ---*/ @@ -779,34 +719,31 @@ void CGeometry::CompleteComms(CGeometry *geometry, /*--- Get the number of packets to be received in this message. ---*/ - nRecv = nPoint_P2PRecv[jRecv+1] - nPoint_P2PRecv[jRecv]; + nRecv = nPoint_P2PRecv[jRecv + 1] - nPoint_P2PRecv[jRecv]; SU2_OMP_FOR_STAT(OMP_MIN_SIZE) for (iRecv = 0; iRecv < nRecv; iRecv++) { - /*--- Get the local index for this communicated data. ---*/ iPoint = geometry->Local_Point_P2PRecv[msg_offset + iRecv]; /*--- Compute the total offset in the recv buffer for this point. ---*/ - buf_offset = (msg_offset + iRecv)*COUNT_PER_POINT; + buf_offset = (msg_offset + iRecv) * COUNT_PER_POINT; /*--- Store the data correctly depending on the quantity. ---*/ switch (commType) { case COORDINATES: - for (iDim = 0; iDim < nDim; iDim++) - nodes->SetCoord(iPoint, iDim, bufDRecv[buf_offset+iDim]); + for (iDim = 0; iDim < nDim; iDim++) nodes->SetCoord(iPoint, iDim, bufDRecv[buf_offset + iDim]); break; case GRID_VELOCITY: - for (iDim = 0; iDim < nDim; iDim++) - nodes->SetGridVel(iPoint, iDim, bufDRecv[buf_offset+iDim]); + for (iDim = 0; iDim < nDim; iDim++) nodes->SetGridVel(iPoint, iDim, bufDRecv[buf_offset + iDim]); break; case COORDINATES_OLD: nodes->SetCoord_n(iPoint, &bufDRecv[buf_offset]); if (config->GetTime_Marching() == TIME_MARCHING::DT_STEPPING_2ND) - nodes->SetCoord_n1(iPoint, &bufDRecv[buf_offset+nDim]); + nodes->SetCoord_n1(iPoint, &bufDRecv[buf_offset + nDim]); break; case MAX_LENGTH: nodes->SetMaxLength(iPoint, bufDRecv[buf_offset]); @@ -815,8 +752,7 @@ void CGeometry::CompleteComms(CGeometry *geometry, nodes->SetnNeighbor(iPoint, bufSRecv[buf_offset]); break; default: - SU2_MPI::Error("Unrecognized quantity for point-to-point MPI comms.", - CURRENT_FUNCTION); + SU2_MPI::Error("Unrecognized quantity for point-to-point MPI comms.", CURRENT_FUNCTION); break; } } @@ -832,9 +768,7 @@ void CGeometry::CompleteComms(CGeometry *geometry, #endif } -void CGeometry::PreprocessPeriodicComms(CGeometry *geometry, - CConfig *config) { - +void CGeometry::PreprocessPeriodicComms(CGeometry* geometry, CConfig* config) { /*--- We start with the send and receive lists already available in the form of stored periodic point-donor pairs. We will loop through these markers and establish the neighboring ranks and number of @@ -854,16 +788,19 @@ void CGeometry::PreprocessPeriodicComms(CGeometry *geometry, /*--- Create some temporary structures for tracking sends/recvs. ---*/ - int *nPoint_Send_All = new int[size+1]; nPoint_Send_All[0] = 0; - int *nPoint_Recv_All = new int[size+1]; nPoint_Recv_All[0] = 0; - int *nPoint_Flag = new int[size]; + int* nPoint_Send_All = new int[size + 1]; + nPoint_Send_All[0] = 0; + int* nPoint_Recv_All = new int[size + 1]; + nPoint_Recv_All[0] = 0; + int* nPoint_Flag = new int[size]; for (iRank = 0; iRank < size; iRank++) { nPoint_Send_All[iRank] = 0; nPoint_Recv_All[iRank] = 0; - nPoint_Flag[iRank]= -1; + nPoint_Flag[iRank] = -1; } - nPoint_Send_All[size] = 0; nPoint_Recv_All[size] = 0; + nPoint_Send_All[size] = 0; + nPoint_Recv_All[size] = 0; /*--- Loop through all of our periodic markers and track our sends with each rank. ---*/ @@ -872,7 +809,6 @@ void CGeometry::PreprocessPeriodicComms(CGeometry *geometry, if (config->GetMarker_All_KindBC(iMarker) == PERIODIC_BOUNDARY) { iPeriodic = config->GetMarker_All_PerBound(iMarker); for (iVertex = 0; iVertex < geometry->nVertex[iMarker]; iVertex++) { - /*--- Get the current periodic point index. We only communicate the owned nodes on a rank, as the MPI comms will take care of the halos after completing the periodic comms. ---*/ @@ -880,7 +816,6 @@ void CGeometry::PreprocessPeriodicComms(CGeometry *geometry, iPoint = geometry->vertex[iMarker][iVertex]->GetNode(); if (geometry->nodes->GetDomain(iPoint)) { - /*--- Get the rank that holds the matching periodic point on the other marker in the periodic pair. ---*/ @@ -890,23 +825,21 @@ void CGeometry::PreprocessPeriodicComms(CGeometry *geometry, number of points that must be sent to a particular proc. ---*/ if ((nPoint_Flag[iRank] != (int)iPoint)) { - nPoint_Flag[iRank] = (int)iPoint; - nPoint_Send_All[iRank+1] += 1; + nPoint_Flag[iRank] = (int)iPoint; + nPoint_Send_All[iRank + 1] += 1; } - } } } } - delete [] nPoint_Flag; + delete[] nPoint_Flag; /*--- Communicate the number of points to be sent/recv'd amongst all processors. After this communication, each proc knows how many periodic points it will receive from each other processor. ---*/ - SU2_MPI::Alltoall(&(nPoint_Send_All[1]), 1, MPI_INT, - &(nPoint_Recv_All[1]), 1, MPI_INT, SU2_MPI::GetComm()); + SU2_MPI::Alltoall(&(nPoint_Send_All[1]), 1, MPI_INT, &(nPoint_Recv_All[1]), 1, MPI_INT, SU2_MPI::GetComm()); /*--- Check how many messages we will be sending and receiving. Here we also put the counters into cumulative storage format to @@ -914,34 +847,38 @@ void CGeometry::PreprocessPeriodicComms(CGeometry *geometry, rank to communicate to themselves in these counters, although it will not be done through MPI. ---*/ - nPeriodicSend = 0; nPeriodicRecv = 0; + nPeriodicSend = 0; + nPeriodicRecv = 0; for (iRank = 0; iRank < size; iRank++) { - if ((nPoint_Send_All[iRank+1] > 0)) nPeriodicSend++; - if ((nPoint_Recv_All[iRank+1] > 0)) nPeriodicRecv++; + if ((nPoint_Send_All[iRank + 1] > 0)) nPeriodicSend++; + if ((nPoint_Recv_All[iRank + 1] > 0)) nPeriodicRecv++; - nPoint_Send_All[iRank+1] += nPoint_Send_All[iRank]; - nPoint_Recv_All[iRank+1] += nPoint_Recv_All[iRank]; + nPoint_Send_All[iRank + 1] += nPoint_Send_All[iRank]; + nPoint_Recv_All[iRank + 1] += nPoint_Recv_All[iRank]; } /*--- Allocate only as much memory as needed for the periodic neighbors. ---*/ - nPoint_PeriodicSend = new int[nPeriodicSend+1]; nPoint_PeriodicSend[0] = 0; - nPoint_PeriodicRecv = new int[nPeriodicRecv+1]; nPoint_PeriodicRecv[0] = 0; + nPoint_PeriodicSend = new int[nPeriodicSend + 1]; + nPoint_PeriodicSend[0] = 0; + nPoint_PeriodicRecv = new int[nPeriodicRecv + 1]; + nPoint_PeriodicRecv[0] = 0; Neighbors_PeriodicSend = new int[nPeriodicSend]; Neighbors_PeriodicRecv = new int[nPeriodicRecv]; - iSend = 0; iRecv = 0; + iSend = 0; + iRecv = 0; for (iRank = 0; iRank < size; iRank++) { - if ((nPoint_Send_All[iRank+1] > nPoint_Send_All[iRank])) { + if ((nPoint_Send_All[iRank + 1] > nPoint_Send_All[iRank])) { Neighbors_PeriodicSend[iSend] = iRank; - nPoint_PeriodicSend[iSend+1] = nPoint_Send_All[iRank+1]; + nPoint_PeriodicSend[iSend + 1] = nPoint_Send_All[iRank + 1]; iSend++; } - if ((nPoint_Recv_All[iRank+1] > nPoint_Recv_All[iRank])) { + if ((nPoint_Recv_All[iRank + 1] > nPoint_Recv_All[iRank])) { Neighbors_PeriodicRecv[iRecv] = iRank; - nPoint_PeriodicRecv[iRecv+1] = nPoint_Recv_All[iRank+1]; + nPoint_PeriodicRecv[iRecv + 1] = nPoint_Recv_All[iRank + 1]; iRecv++; } } @@ -951,38 +888,32 @@ void CGeometry::PreprocessPeriodicComms(CGeometry *geometry, messages dynamically later during the iterations. ---*/ PeriodicSend2Neighbor.clear(); - for (iSend = 0; iSend < nPeriodicSend; iSend++) - PeriodicSend2Neighbor[Neighbors_PeriodicSend[iSend]] = iSend; + for (iSend = 0; iSend < nPeriodicSend; iSend++) PeriodicSend2Neighbor[Neighbors_PeriodicSend[iSend]] = iSend; PeriodicRecv2Neighbor.clear(); - for (iRecv = 0; iRecv < nPeriodicRecv; iRecv++) - PeriodicRecv2Neighbor[Neighbors_PeriodicRecv[iRecv]] = iRecv; + for (iRecv = 0; iRecv < nPeriodicRecv; iRecv++) PeriodicRecv2Neighbor[Neighbors_PeriodicRecv[iRecv]] = iRecv; - delete [] nPoint_Send_All; - delete [] nPoint_Recv_All; + delete[] nPoint_Send_All; + delete[] nPoint_Recv_All; /*--- Allocate the memory to store the local index values for both the send and receive periodic points and periodic index. ---*/ Local_Point_PeriodicSend = nullptr; Local_Point_PeriodicSend = new unsigned long[nPoint_PeriodicSend[nPeriodicSend]]; - for (iSend = 0; iSend < nPoint_PeriodicSend[nPeriodicSend]; iSend++) - Local_Point_PeriodicSend[iSend] = 0; + for (iSend = 0; iSend < nPoint_PeriodicSend[nPeriodicSend]; iSend++) Local_Point_PeriodicSend[iSend] = 0; Local_Marker_PeriodicSend = nullptr; Local_Marker_PeriodicSend = new unsigned long[nPoint_PeriodicSend[nPeriodicSend]]; - for (iSend = 0; iSend < nPoint_PeriodicSend[nPeriodicSend]; iSend++) - Local_Marker_PeriodicSend[iSend] = 0; + for (iSend = 0; iSend < nPoint_PeriodicSend[nPeriodicSend]; iSend++) Local_Marker_PeriodicSend[iSend] = 0; Local_Point_PeriodicRecv = nullptr; Local_Point_PeriodicRecv = new unsigned long[nPoint_PeriodicRecv[nPeriodicRecv]]; - for (iRecv = 0; iRecv < nPoint_PeriodicRecv[nPeriodicRecv]; iRecv++) - Local_Point_PeriodicRecv[iRecv] = 0; + for (iRecv = 0; iRecv < nPoint_PeriodicRecv[nPeriodicRecv]; iRecv++) Local_Point_PeriodicRecv[iRecv] = 0; Local_Marker_PeriodicRecv = nullptr; Local_Marker_PeriodicRecv = new unsigned long[nPoint_PeriodicRecv[nPeriodicRecv]]; - for (iRecv = 0; iRecv < nPoint_PeriodicRecv[nPeriodicRecv]; iRecv++) - Local_Marker_PeriodicRecv[iRecv] = 0; + for (iRecv = 0; iRecv < nPoint_PeriodicRecv[nPeriodicRecv]; iRecv++) Local_Marker_PeriodicRecv[iRecv] = 0; /*--- We allocate the buffers for communicating values in a later step once we know the maximum packet size that we need to communicate. This @@ -998,10 +929,10 @@ void CGeometry::PreprocessPeriodicComms(CGeometry *geometry, /*--- Allocate memory for the MPI requests if we need to communicate. ---*/ if (nPeriodicSend > 0) { - req_PeriodicSend = new SU2_MPI::Request[nPeriodicSend]; + req_PeriodicSend = new SU2_MPI::Request[nPeriodicSend]; } if (nPeriodicRecv > 0) { - req_PeriodicRecv = new SU2_MPI::Request[nPeriodicRecv]; + req_PeriodicRecv = new SU2_MPI::Request[nPeriodicRecv]; } /*--- Allocate arrays for sending the periodic point index and marker @@ -1009,19 +940,18 @@ void CGeometry::PreprocessPeriodicComms(CGeometry *geometry, the recv rank can quickly loop through the buffers to unpack the data. ---*/ unsigned short nPackets = 2; - unsigned long *idSend = new unsigned long[nPoint_PeriodicSend[nPeriodicSend]*nPackets]; - for (iSend = 0; iSend < nPoint_PeriodicSend[nPeriodicSend]*nPackets; iSend++) - idSend[iSend] = 0; + unsigned long* idSend = new unsigned long[nPoint_PeriodicSend[nPeriodicSend] * nPackets]; + for (iSend = 0; iSend < nPoint_PeriodicSend[nPeriodicSend] * nPackets; iSend++) idSend[iSend] = 0; /*--- Build the lists of local index and periodic marker index values. ---*/ - ii = 0; jj = 0; + ii = 0; + jj = 0; for (iSend = 0; iSend < nPeriodicSend; iSend++) { for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { if (config->GetMarker_All_KindBC(iMarker) == PERIODIC_BOUNDARY) { iPeriodic = config->GetMarker_All_PerBound(iMarker); for (iVertex = 0; iVertex < geometry->nVertex[iMarker]; iVertex++) { - /*--- Get the current periodic point index. We only communicate the owned nodes on a rank, as the MPI comms will take care of the halos after completing the periodic comms. ---*/ @@ -1029,7 +959,6 @@ void CGeometry::PreprocessPeriodicComms(CGeometry *geometry, iPoint = geometry->vertex[iMarker][iVertex]->GetNode(); if (geometry->nodes->GetDomain(iPoint)) { - /*--- Get the rank that holds the matching periodic point on the other marker in the periodic pair. ---*/ @@ -1041,15 +970,14 @@ void CGeometry::PreprocessPeriodicComms(CGeometry *geometry, index to be communicated to the recv rank. ---*/ if (iRank == Neighbors_PeriodicSend[iSend]) { - Local_Point_PeriodicSend[ii] = iPoint; + Local_Point_PeriodicSend[ii] = iPoint; Local_Marker_PeriodicSend[ii] = (unsigned long)iMarker; - jj = ii*nPackets; + jj = ii * nPackets; idSend[jj] = geometry->vertex[iMarker][iVertex]->GetDonorPoint(); jj++; idSend[jj] = (unsigned long)iPeriodic; ii++; } - } } } @@ -1059,9 +987,8 @@ void CGeometry::PreprocessPeriodicComms(CGeometry *geometry, /*--- Allocate arrays for receiving the periodic point index and marker index to the recv rank so that it can store the local values. ---*/ - unsigned long *idRecv = new unsigned long[nPoint_PeriodicRecv[nPeriodicRecv]*nPackets]; - for (iRecv = 0; iRecv < nPoint_PeriodicRecv[nPeriodicRecv]*nPackets; iRecv++) - idRecv[iRecv] = 0; + unsigned long* idRecv = new unsigned long[nPoint_PeriodicRecv[nPeriodicRecv] * nPackets]; + for (iRecv = 0; iRecv < nPoint_PeriodicRecv[nPeriodicRecv] * nPackets; iRecv++) idRecv[iRecv] = 0; #ifdef HAVE_MPI @@ -1073,62 +1000,56 @@ void CGeometry::PreprocessPeriodicComms(CGeometry *geometry, iMessage = 0; for (iRecv = 0; iRecv < nPeriodicRecv; iRecv++) { - /*--- Compute our location in the recv buffer. ---*/ - offset = nPackets*nPoint_PeriodicRecv[iRecv]; + offset = nPackets * nPoint_PeriodicRecv[iRecv]; /*--- Take advantage of cumulative storage format to get the number of elems that we need to recv. ---*/ - count = nPackets*(nPoint_PeriodicRecv[iRecv+1] - nPoint_PeriodicRecv[iRecv]); + count = nPackets * (nPoint_PeriodicRecv[iRecv + 1] - nPoint_PeriodicRecv[iRecv]); /*--- Get the rank from which we receive the message. ---*/ source = Neighbors_PeriodicRecv[iRecv]; - tag = source + 1; + tag = source + 1; /*--- Post non-blocking recv for this proc. ---*/ - SU2_MPI::Irecv(&(static_cast(idRecv)[offset]), - count, MPI_UNSIGNED_LONG, source, tag, SU2_MPI::GetComm(), - &(req_PeriodicRecv[iMessage])); + SU2_MPI::Irecv(&(static_cast(idRecv)[offset]), count, MPI_UNSIGNED_LONG, source, tag, + SU2_MPI::GetComm(), &(req_PeriodicRecv[iMessage])); /*--- Increment message counter. ---*/ iMessage++; - } /*--- Post the non-blocking sends. ---*/ iMessage = 0; for (iSend = 0; iSend < nPeriodicSend; iSend++) { - /*--- Compute our location in the send buffer. ---*/ - offset = nPackets*nPoint_PeriodicSend[iSend]; + offset = nPackets * nPoint_PeriodicSend[iSend]; /*--- Take advantage of cumulative storage format to get the number of points that we need to send. ---*/ - count = nPackets*(nPoint_PeriodicSend[iSend+1] - nPoint_PeriodicSend[iSend]); + count = nPackets * (nPoint_PeriodicSend[iSend + 1] - nPoint_PeriodicSend[iSend]); /*--- Get the rank to which we send the message. ---*/ dest = Neighbors_PeriodicSend[iSend]; - tag = rank + 1; + tag = rank + 1; /*--- Post non-blocking send for this proc. ---*/ - SU2_MPI::Isend(&(static_cast(idSend)[offset]), - count, MPI_UNSIGNED_LONG, dest, tag, SU2_MPI::GetComm(), - &(req_PeriodicSend[iMessage])); + SU2_MPI::Isend(&(static_cast(idSend)[offset]), count, MPI_UNSIGNED_LONG, dest, tag, + SU2_MPI::GetComm(), &(req_PeriodicSend[iMessage])); /*--- Increment message counter. ---*/ iMessage++; - } /*--- Wait for the non-blocking comms to complete. ---*/ @@ -1142,10 +1063,10 @@ void CGeometry::PreprocessPeriodicComms(CGeometry *geometry, int myStart, myFinal; for (int val_iSend = 0; val_iSend < nPeriodicSend; val_iSend++) { - iRank = geometry->PeriodicRecv2Neighbor[rank]; - iRecv = geometry->nPoint_PeriodicRecv[iRank]*nPackets; - myStart = nPoint_PeriodicSend[val_iSend]*nPackets; - myFinal = nPoint_PeriodicSend[val_iSend+1]*nPackets; + iRank = geometry->PeriodicRecv2Neighbor[rank]; + iRecv = geometry->nPoint_PeriodicRecv[iRank] * nPackets; + myStart = nPoint_PeriodicSend[val_iSend] * nPackets; + myFinal = nPoint_PeriodicSend[val_iSend + 1] * nPackets; for (iSend = myStart; iSend < myFinal; iSend++) { idRecv[iRecv] = idSend[iSend]; iRecv++; @@ -1159,17 +1080,17 @@ void CGeometry::PreprocessPeriodicComms(CGeometry *geometry, ii = 0; for (iRecv = 0; iRecv < nPoint_PeriodicRecv[nPeriodicRecv]; iRecv++) { - Local_Point_PeriodicRecv[iRecv] = idRecv[ii]; ii++; - Local_Marker_PeriodicRecv[iRecv] = idRecv[ii]; ii++; + Local_Point_PeriodicRecv[iRecv] = idRecv[ii]; + ii++; + Local_Marker_PeriodicRecv[iRecv] = idRecv[ii]; + ii++; } - delete [] idSend; - delete [] idRecv; - + delete[] idSend; + delete[] idRecv; } void CGeometry::AllocatePeriodicComms(unsigned short countPerPeriodicPoint) { - /*--- This routine is activated whenever we attempt to perform a periodic MPI communication with our neighbors but the memory buffer allocated is not large enough for the packet size. @@ -1180,39 +1101,34 @@ void CGeometry::AllocatePeriodicComms(unsigned short countPerPeriodicPoint) { if (countPerPeriodicPoint <= maxCountPerPeriodicPoint) return; BEGIN_SU2_OMP_SAFE_GLOBAL_ACCESS { + /*--- Store the larger packet size to the class data. ---*/ - /*--- Store the larger packet size to the class data. ---*/ - - maxCountPerPeriodicPoint = countPerPeriodicPoint; - - /*--- Store the total size of the send/recv arrays for clarity. ---*/ + maxCountPerPeriodicPoint = countPerPeriodicPoint; - auto nSend = countPerPeriodicPoint*nPoint_PeriodicSend[nPeriodicSend]; - auto nRecv = countPerPeriodicPoint*nPoint_PeriodicRecv[nPeriodicRecv]; + /*--- Store the total size of the send/recv arrays for clarity. ---*/ - /*-- Deallocate and reallocate our cummunication memory. ---*/ + auto nSend = countPerPeriodicPoint * nPoint_PeriodicSend[nPeriodicSend]; + auto nRecv = countPerPeriodicPoint * nPoint_PeriodicRecv[nPeriodicRecv]; - delete [] bufD_PeriodicSend; - bufD_PeriodicSend = new su2double[nSend] (); + /*-- Deallocate and reallocate our cummunication memory. ---*/ - delete [] bufD_PeriodicRecv; - bufD_PeriodicRecv = new su2double[nRecv] (); + delete[] bufD_PeriodicSend; + bufD_PeriodicSend = new su2double[nSend](); - delete [] bufS_PeriodicSend; - bufS_PeriodicSend = new unsigned short[nSend] (); + delete[] bufD_PeriodicRecv; + bufD_PeriodicRecv = new su2double[nRecv](); - delete [] bufS_PeriodicRecv; - bufS_PeriodicRecv = new unsigned short[nRecv] (); + delete[] bufS_PeriodicSend; + bufS_PeriodicSend = new unsigned short[nSend](); + delete[] bufS_PeriodicRecv; + bufS_PeriodicRecv = new unsigned short[nRecv](); } END_SU2_OMP_SAFE_GLOBAL_ACCESS } -void CGeometry::PostPeriodicRecvs(CGeometry *geometry, - const CConfig *config, - unsigned short commType, +void CGeometry::PostPeriodicRecvs(CGeometry* geometry, const CConfig* config, unsigned short commType, unsigned short countPerPeriodicPoint) { - /*--- In parallel, communicate the data with non-blocking send/recv. ---*/ #ifdef HAVE_MPI @@ -1223,19 +1139,18 @@ void CGeometry::PostPeriodicRecvs(CGeometry *geometry, SU2_OMP_MASTER for (int iRecv = 0; iRecv < nPeriodicRecv; iRecv++) { - /*--- Compute our location in the recv buffer. ---*/ - auto offset = countPerPeriodicPoint*nPoint_PeriodicRecv[iRecv]; + auto offset = countPerPeriodicPoint * nPoint_PeriodicRecv[iRecv]; /*--- Take advantage of cumulative storage format to get the number of elems that we need to recv. ---*/ - auto nPointPeriodic = nPoint_PeriodicRecv[iRecv+1] - nPoint_PeriodicRecv[iRecv]; + auto nPointPeriodic = nPoint_PeriodicRecv[iRecv + 1] - nPoint_PeriodicRecv[iRecv]; /*--- Total count can include multiple pieces of data per element. ---*/ - auto count = countPerPeriodicPoint*nPointPeriodic; + auto count = countPerPeriodicPoint * nPointPeriodic; /*--- Get the rank from which we receive the message. ---*/ @@ -1246,77 +1161,64 @@ void CGeometry::PostPeriodicRecvs(CGeometry *geometry, switch (commType) { case COMM_TYPE_DOUBLE: - SU2_MPI::Irecv(&(static_cast(bufD_PeriodicRecv)[offset]), - count, MPI_DOUBLE, source, tag, SU2_MPI::GetComm(), - &(req_PeriodicRecv[iRecv])); + SU2_MPI::Irecv(&(static_cast(bufD_PeriodicRecv)[offset]), count, MPI_DOUBLE, source, tag, + SU2_MPI::GetComm(), &(req_PeriodicRecv[iRecv])); break; case COMM_TYPE_UNSIGNED_SHORT: - SU2_MPI::Irecv(&(static_cast(bufS_PeriodicRecv)[offset]), - count, MPI_UNSIGNED_SHORT, source, tag, SU2_MPI::GetComm(), - &(req_PeriodicRecv[iRecv])); + SU2_MPI::Irecv(&(static_cast(bufS_PeriodicRecv)[offset]), count, MPI_UNSIGNED_SHORT, source, + tag, SU2_MPI::GetComm(), &(req_PeriodicRecv[iRecv])); break; default: - SU2_MPI::Error("Unrecognized data type for periodic MPI comms.", - CURRENT_FUNCTION); + SU2_MPI::Error("Unrecognized data type for periodic MPI comms.", CURRENT_FUNCTION); break; } - } END_SU2_OMP_MASTER #endif - } -void CGeometry::PostPeriodicSends(CGeometry *geometry, - const CConfig *config, - unsigned short commType, - unsigned short countPerPeriodicPoint, - int val_iSend) const { - +void CGeometry::PostPeriodicSends(CGeometry* geometry, const CConfig* config, unsigned short commType, + unsigned short countPerPeriodicPoint, int val_iSend) const { /*--- In parallel, communicate the data with non-blocking send/recv. ---*/ #ifdef HAVE_MPI SU2_OMP_MASTER { - /*--- Post the non-blocking send as soon as the buffer is loaded. ---*/ + /*--- Post the non-blocking send as soon as the buffer is loaded. ---*/ - /*--- Compute our location in the send buffer. ---*/ + /*--- Compute our location in the send buffer. ---*/ - auto offset = countPerPeriodicPoint*nPoint_PeriodicSend[val_iSend]; + auto offset = countPerPeriodicPoint * nPoint_PeriodicSend[val_iSend]; - /*--- Take advantage of cumulative storage format to get the number - of points that we need to send. ---*/ + /*--- Take advantage of cumulative storage format to get the number + of points that we need to send. ---*/ - auto nPointPeriodic = (nPoint_PeriodicSend[val_iSend+1] - - nPoint_PeriodicSend[val_iSend]); + auto nPointPeriodic = (nPoint_PeriodicSend[val_iSend + 1] - nPoint_PeriodicSend[val_iSend]); - /*--- Total count can include multiple pieces of data per element. ---*/ + /*--- Total count can include multiple pieces of data per element. ---*/ - auto count = countPerPeriodicPoint*nPointPeriodic; + auto count = countPerPeriodicPoint * nPointPeriodic; - /*--- Get the rank to which we send the message. ---*/ + /*--- Get the rank to which we send the message. ---*/ - auto dest = Neighbors_PeriodicSend[val_iSend]; - auto tag = rank + 1; + auto dest = Neighbors_PeriodicSend[val_iSend]; + auto tag = rank + 1; - /*--- Post non-blocking send for this proc. ---*/ + /*--- Post non-blocking send for this proc. ---*/ - switch (commType) { - case COMM_TYPE_DOUBLE: - SU2_MPI::Isend(&(static_cast(bufD_PeriodicSend)[offset]), - count, MPI_DOUBLE, dest, tag, SU2_MPI::GetComm(), - &(req_PeriodicSend[val_iSend])); - break; - case COMM_TYPE_UNSIGNED_SHORT: - SU2_MPI::Isend(&(static_cast(bufS_PeriodicSend)[offset]), - count, MPI_UNSIGNED_SHORT, dest, tag, SU2_MPI::GetComm(), - &(req_PeriodicSend[val_iSend])); - break; - default: - SU2_MPI::Error("Unrecognized data type for periodic MPI comms.", - CURRENT_FUNCTION); - break; - } + switch (commType) { + case COMM_TYPE_DOUBLE: + SU2_MPI::Isend(&(static_cast(bufD_PeriodicSend)[offset]), count, MPI_DOUBLE, dest, tag, + SU2_MPI::GetComm(), &(req_PeriodicSend[val_iSend])); + break; + case COMM_TYPE_UNSIGNED_SHORT: + SU2_MPI::Isend(&(static_cast(bufS_PeriodicSend)[offset]), count, MPI_UNSIGNED_SHORT, dest, tag, + SU2_MPI::GetComm(), &(req_PeriodicSend[val_iSend])); + break; + default: + SU2_MPI::Error("Unrecognized data type for periodic MPI comms.", CURRENT_FUNCTION); + break; + } } END_SU2_OMP_MASTER #else @@ -1324,54 +1226,51 @@ void CGeometry::PostPeriodicSends(CGeometry *geometry, /*--- Copy my own rank's data into the recv buffer directly in serial. ---*/ int myStart, myFinal, iRecv, iRank; - iRank = geometry->PeriodicRecv2Neighbor[rank]; - iRecv = geometry->nPoint_PeriodicRecv[iRank]*countPerPeriodicPoint; - myStart = nPoint_PeriodicSend[val_iSend]*countPerPeriodicPoint; - myFinal = nPoint_PeriodicSend[val_iSend+1]*countPerPeriodicPoint; + iRank = geometry->PeriodicRecv2Neighbor[rank]; + iRecv = geometry->nPoint_PeriodicRecv[iRank] * countPerPeriodicPoint; + myStart = nPoint_PeriodicSend[val_iSend] * countPerPeriodicPoint; + myFinal = nPoint_PeriodicSend[val_iSend + 1] * countPerPeriodicPoint; switch (commType) { case COMM_TYPE_DOUBLE: - parallelCopy(myFinal-myStart, &bufD_PeriodicSend[myStart], &bufD_PeriodicRecv[iRecv]); + parallelCopy(myFinal - myStart, &bufD_PeriodicSend[myStart], &bufD_PeriodicRecv[iRecv]); break; case COMM_TYPE_UNSIGNED_SHORT: - parallelCopy(myFinal-myStart, &bufS_PeriodicSend[myStart], &bufS_PeriodicRecv[iRecv]); + parallelCopy(myFinal - myStart, &bufS_PeriodicSend[myStart], &bufS_PeriodicRecv[iRecv]); break; default: - SU2_MPI::Error("Unrecognized data type for periodic MPI comms.", - CURRENT_FUNCTION); + SU2_MPI::Error("Unrecognized data type for periodic MPI comms.", CURRENT_FUNCTION); break; } #endif - } -su2double CGeometry::Point2Plane_Distance(const su2double *Coord, const su2double *iCoord, const su2double *jCoord, const su2double *kCoord) { +su2double CGeometry::Point2Plane_Distance(const su2double* Coord, const su2double* iCoord, const su2double* jCoord, + const su2double* kCoord) { su2double CrossProduct[3], iVector[3], jVector[3], distance, modulus; unsigned short iDim; - for (iDim = 0; iDim < 3; iDim ++) { + for (iDim = 0; iDim < 3; iDim++) { iVector[iDim] = jCoord[iDim] - iCoord[iDim]; jVector[iDim] = kCoord[iDim] - iCoord[iDim]; } - CrossProduct[0] = iVector[1]*jVector[2] - iVector[2]*jVector[1]; - CrossProduct[1] = iVector[2]*jVector[0] - iVector[0]*jVector[2]; - CrossProduct[2] = iVector[0]*jVector[1] - iVector[1]*jVector[0]; + CrossProduct[0] = iVector[1] * jVector[2] - iVector[2] * jVector[1]; + CrossProduct[1] = iVector[2] * jVector[0] - iVector[0] * jVector[2]; + CrossProduct[2] = iVector[0] * jVector[1] - iVector[1] * jVector[0]; - modulus = sqrt(CrossProduct[0]*CrossProduct[0]+CrossProduct[1]*CrossProduct[1]+CrossProduct[2]*CrossProduct[2]); + modulus = + sqrt(CrossProduct[0] * CrossProduct[0] + CrossProduct[1] * CrossProduct[1] + CrossProduct[2] * CrossProduct[2]); distance = 0.0; - for (iDim = 0; iDim < 3; iDim ++) - distance += CrossProduct[iDim]*(Coord[iDim]-iCoord[iDim]); + for (iDim = 0; iDim < 3; iDim++) distance += CrossProduct[iDim] * (Coord[iDim] - iCoord[iDim]); distance /= modulus; return distance; - } void CGeometry::SetEdges(void) { - nEdge = 0; for (auto iPoint = 0ul; iPoint < nPoint; iPoint++) { for (auto iNode = 0u; iNode < nodes->GetnPoint(iPoint); iNode++) { @@ -1390,7 +1289,7 @@ void CGeometry::SetEdges(void) { } } - edges = new CEdge(nEdge,nDim); + edges = new CEdge(nEdge, nDim); for (auto iPoint = 0ul; iPoint < nPoint; iPoint++) { for (auto jPoint : nodes->GetPoints(iPoint)) { @@ -1435,20 +1334,18 @@ void CGeometry::SetFaces(void) { } void CGeometry::TestGeometry(void) const { - ofstream para_file; para_file.open("test_geometry.dat", ios::out); - su2double *Normal = new su2double[nDim]; + su2double* Normal = new su2double[nDim]; for (unsigned long iEdge = 0; iEdge < nEdge; iEdge++) { para_file << "Edge index: " << iEdge << endl; - para_file << " Point index: " << edges->GetNode(iEdge,0) << "\t" << edges->GetNode(iEdge,1) << endl; - edges->GetNormal(iEdge,Normal); + para_file << " Point index: " << edges->GetNode(iEdge, 0) << "\t" << edges->GetNode(iEdge, 1) << endl; + edges->GetNormal(iEdge, Normal); para_file << " Face normal : "; - for (unsigned short iDim = 0; iDim < nDim; iDim++) - para_file << Normal[iDim] << "\t"; + for (unsigned short iDim = 0; iDim < nDim; iDim++) para_file << Normal[iDim] << "\t"; para_file << endl; } @@ -1457,52 +1354,53 @@ void CGeometry::TestGeometry(void) const { para_file << endl; para_file << endl; - for (unsigned short iMarker =0; iMarker < nMarker; iMarker++) { + for (unsigned short iMarker = 0; iMarker < nMarker; iMarker++) { para_file << "Marker index: " << iMarker << endl; for (unsigned long iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { para_file << " Vertex index: " << iVertex << endl; para_file << " Point index: " << vertex[iMarker][iVertex]->GetNode() << endl; para_file << " Point coordinates : "; for (unsigned short iDim = 0; iDim < nDim; iDim++) { - para_file << nodes->GetCoord(vertex[iMarker][iVertex]->GetNode(), iDim) << "\t";} + para_file << nodes->GetCoord(vertex[iMarker][iVertex]->GetNode(), iDim) << "\t"; + } para_file << endl; vertex[iMarker][iVertex]->GetNormal(Normal); para_file << " Face normal : "; - for (unsigned short iDim = 0; iDim < nDim; iDim++) - para_file << Normal[iDim] << "\t"; + for (unsigned short iDim = 0; iDim < nDim; iDim++) para_file << Normal[iDim] << "\t"; para_file << endl; } } - delete [] Normal; - + delete[] Normal; } -bool CGeometry::SegmentIntersectsPlane(const su2double *Segment_P0, const su2double *Segment_P1, su2double Variable_P0, su2double Variable_P1, - const su2double *Plane_P0, const su2double *Plane_Normal, su2double *Intersection, su2double &Variable_Interp) { +bool CGeometry::SegmentIntersectsPlane(const su2double* Segment_P0, const su2double* Segment_P1, su2double Variable_P0, + su2double Variable_P1, const su2double* Plane_P0, const su2double* Plane_Normal, + su2double* Intersection, su2double& Variable_Interp) { su2double u[3], v[3], Denominator, Numerator, Aux, ModU; - su2double epsilon = 1E-6; // An epsilon is added to eliminate, as much as possible, the posibility of a line that intersects a point + su2double epsilon = + 1E-6; // An epsilon is added to eliminate, as much as possible, the posibility of a line that intersects a point unsigned short iDim; for (iDim = 0; iDim < 3; iDim++) { u[iDim] = Segment_P1[iDim] - Segment_P0[iDim]; - v[iDim] = (Plane_P0[iDim]+epsilon) - Segment_P0[iDim]; + v[iDim] = (Plane_P0[iDim] + epsilon) - Segment_P0[iDim]; } - ModU = sqrt(u[0]*u[0]+u[1]*u[1]+u[2]*u[2]); + ModU = sqrt(u[0] * u[0] + u[1] * u[1] + u[2] * u[2]); - Numerator = (Plane_Normal[0]+epsilon)*v[0] + (Plane_Normal[1]+epsilon)*v[1] + (Plane_Normal[2]+epsilon)*v[2]; - Denominator = (Plane_Normal[0]+epsilon)*u[0] + (Plane_Normal[1]+epsilon)*u[1] + (Plane_Normal[2]+epsilon)*u[2]; + Numerator = + (Plane_Normal[0] + epsilon) * v[0] + (Plane_Normal[1] + epsilon) * v[1] + (Plane_Normal[2] + epsilon) * v[2]; + Denominator = + (Plane_Normal[0] + epsilon) * u[0] + (Plane_Normal[1] + epsilon) * u[1] + (Plane_Normal[2] + epsilon) * u[2]; - if (fabs(Denominator) <= 0.0) return (false); // No intersection. + if (fabs(Denominator) <= 0.0) return (false); // No intersection. Aux = Numerator / Denominator; - if (Aux < 0.0 || Aux > 1.0) return (false); // No intersection. - - for (iDim = 0; iDim < 3; iDim++) - Intersection[iDim] = Segment_P0[iDim] + Aux * u[iDim]; + if (Aux < 0.0 || Aux > 1.0) return (false); // No intersection. + for (iDim = 0; iDim < 3; iDim++) Intersection[iDim] = Segment_P0[iDim] + Aux * u[iDim]; /*--- Check that the intersection is in the segment ---*/ @@ -1511,23 +1409,22 @@ bool CGeometry::SegmentIntersectsPlane(const su2double *Segment_P0, const su2dou v[iDim] = Segment_P1[iDim] - Intersection[iDim]; } - Variable_Interp = Variable_P0 + (Variable_P1 - Variable_P0)*sqrt(u[0]*u[0]+u[1]*u[1]+u[2]*u[2])/ModU; + Variable_Interp = Variable_P0 + (Variable_P1 - Variable_P0) * sqrt(u[0] * u[0] + u[1] * u[1] + u[2] * u[2]) / ModU; - Denominator = (Plane_Normal[0]+epsilon)*u[0] + (Plane_Normal[1]+epsilon)*u[1] + (Plane_Normal[2]+epsilon)*u[2]; - Numerator = (Plane_Normal[0]+epsilon)*v[0] + (Plane_Normal[1]+epsilon)*v[1] + (Plane_Normal[2]+epsilon)*v[2]; + Denominator = + (Plane_Normal[0] + epsilon) * u[0] + (Plane_Normal[1] + epsilon) * u[1] + (Plane_Normal[2] + epsilon) * u[2]; + Numerator = + (Plane_Normal[0] + epsilon) * v[0] + (Plane_Normal[1] + epsilon) * v[1] + (Plane_Normal[2] + epsilon) * v[2]; Aux = Numerator * Denominator; - if (Aux > 0.0) return (false); // Intersection outside the segment. + if (Aux > 0.0) return (false); // Intersection outside the segment. return (true); - } -bool CGeometry::RayIntersectsTriangle(const su2double orig[3], const su2double dir[3], - const su2double vert0[3], const su2double vert1[3], const su2double vert2[3], - su2double *intersect) { - +bool CGeometry::RayIntersectsTriangle(const su2double orig[3], const su2double dir[3], const su2double vert0[3], + const su2double vert1[3], const su2double vert2[3], su2double* intersect) { const passivedouble epsilon = 0.000001; su2double edge1[3], edge2[3], tvec[3], pvec[3], qvec[3]; su2double det, inv_det, t, u, v; @@ -1545,8 +1442,7 @@ bool CGeometry::RayIntersectsTriangle(const su2double orig[3], const su2double d det = GeometryToolbox::DotProduct(3, edge1, pvec); - - if (fabs(det) < epsilon) return(false); + if (fabs(det) < epsilon) return (false); inv_det = 1.0 / det; @@ -1558,7 +1454,7 @@ bool CGeometry::RayIntersectsTriangle(const su2double orig[3], const su2double d u = inv_det * GeometryToolbox::DotProduct(3, tvec, pvec); - if (u < 0.0 || u > 1.0) return(false); + if (u < 0.0 || u > 1.0) return (false); /*--- prepare to test V parameter ---*/ @@ -1568,7 +1464,7 @@ bool CGeometry::RayIntersectsTriangle(const su2double orig[3], const su2double d v = inv_det * GeometryToolbox::DotProduct(3, dir, qvec); - if (v < 0.0 || u + v > 1.0) return(false); + if (v < 0.0 || u + v > 1.0) return (false); /*--- Calculate t, ray intersects triangle ---*/ @@ -1581,11 +1477,10 @@ bool CGeometry::RayIntersectsTriangle(const su2double orig[3], const su2double d intersect[2] = orig[2] + (t * dir[2]); return (true); - } -bool CGeometry::SegmentIntersectsLine(const su2double point0[2], const su2double point1[2], const su2double vert0[2], const su2double vert1[2]) { - +bool CGeometry::SegmentIntersectsLine(const su2double point0[2], const su2double point1[2], const su2double vert0[2], + const su2double vert1[2]) { su2double det, diff0_A, diff0_B, diff1_A, diff1_B, intersect[2]; diff0_A = point0[0] - point1[0]; @@ -1594,48 +1489,46 @@ bool CGeometry::SegmentIntersectsLine(const su2double point0[2], const su2double diff0_B = vert0[0] - vert1[0]; diff1_B = vert0[1] - vert1[1]; - det = (diff0_A)*(diff1_B) - (diff1_A)*(diff0_B); + det = (diff0_A) * (diff1_B) - (diff1_A) * (diff0_B); if (det == 0) return false; /*--- Compute point of intersection ---*/ - intersect[0] = ((point0[0]*point1[1] - point0[1]*point1[0])*diff0_B - -(vert0[0]* vert1[1] - vert0[1]* vert1[0])*diff0_A)/det; - - intersect[1] = ((point0[0]*point1[1] - point0[1]*point1[0])*diff1_B - -(vert0[0]* vert1[1] - vert0[1]* vert1[0])*diff1_A)/det; + intersect[0] = ((point0[0] * point1[1] - point0[1] * point1[0]) * diff0_B - + (vert0[0] * vert1[1] - vert0[1] * vert1[0]) * diff0_A) / + det; + intersect[1] = ((point0[0] * point1[1] - point0[1] * point1[0]) * diff1_B - + (vert0[0] * vert1[1] - vert0[1] * vert1[0]) * diff1_A) / + det; /*--- Check that the point is between the two surface points ---*/ su2double dist0, dist1, length; - dist0 = (intersect[0] - point0[0])*(intersect[0] - point0[0]) - +(intersect[1] - point0[1])*(intersect[1] - point0[1]); + dist0 = + (intersect[0] - point0[0]) * (intersect[0] - point0[0]) + (intersect[1] - point0[1]) * (intersect[1] - point0[1]); - dist1 = (intersect[0] - point1[0])*(intersect[0] - point1[0]) - +(intersect[1] - point1[1])*(intersect[1] - point1[1]); + dist1 = + (intersect[0] - point1[0]) * (intersect[0] - point1[0]) + (intersect[1] - point1[1]) * (intersect[1] - point1[1]); - length = diff0_A*diff0_A - +diff1_A*diff1_A; + length = diff0_A * diff0_A + diff1_A * diff1_A; - if ( (dist0 > length) || (dist1 > length) ) { + if ((dist0 > length) || (dist1 > length)) { return false; } return true; } -bool CGeometry::SegmentIntersectsTriangle(su2double point0[3], const su2double point1[3], - su2double vert0[3], su2double vert1[3], su2double vert2[3]) { - +bool CGeometry::SegmentIntersectsTriangle(su2double point0[3], const su2double point1[3], su2double vert0[3], + su2double vert1[3], su2double vert2[3]) { su2double dir[3], intersect[3], u[3], v[3], edge1[3], edge2[3], Plane_Normal[3], Denominator, Numerator, Aux; GeometryToolbox::Distance(3, point1, point0, dir); if (RayIntersectsTriangle(point0, dir, vert0, vert1, vert2, intersect)) { - /*--- Check that the intersection is in the segment ---*/ GeometryToolbox::Distance(3, point0, intersect, u); @@ -1654,45 +1547,41 @@ bool CGeometry::SegmentIntersectsTriangle(su2double point0[3], const su2double p if (Aux > 0.0) return (false); - } - else { - + } else { /*--- No intersection with the ray ---*/ return (false); - } /*--- Intersection inside the segment ---*/ return (true); - } -void CGeometry::ComputeAirfoil_Section(su2double *Plane_P0, su2double *Plane_Normal, - su2double MinXCoord, su2double MaxXCoord, - su2double MinYCoord, su2double MaxYCoord, - su2double MinZCoord, su2double MaxZCoord, - const su2double *FlowVariable, - vector &Xcoord_Airfoil, vector &Ycoord_Airfoil, - vector &Zcoord_Airfoil, vector &Variable_Airfoil, - bool original_surface, CConfig *config) { - +void CGeometry::ComputeAirfoil_Section(su2double* Plane_P0, su2double* Plane_Normal, su2double MinXCoord, + su2double MaxXCoord, su2double MinYCoord, su2double MaxYCoord, + su2double MinZCoord, su2double MaxZCoord, const su2double* FlowVariable, + vector& Xcoord_Airfoil, vector& Ycoord_Airfoil, + vector& Zcoord_Airfoil, vector& Variable_Airfoil, + bool original_surface, CConfig* config) { const bool wasActive = AD::BeginPassive(); unsigned short iMarker, iNode, jNode, iDim, Index = 0; bool intersect; long Next_Edge = 0; unsigned long iPoint, jPoint, iElem, Trailing_Point, Airfoil_Point, iVertex, iEdge, PointIndex, jEdge; - su2double Segment_P0[3] = {0.0, 0.0, 0.0}, Segment_P1[3] = {0.0, 0.0, 0.0}, Variable_P0 = 0.0, Variable_P1 = 0.0, Intersection[3] = {0.0, 0.0, 0.0}, Trailing_Coord, - *VarCoord = nullptr, Variable_Interp, v1[3] = {0.0, 0.0, 0.0}, v3[3] = {0.0, 0.0, 0.0}, CrossProduct = 1.0; + su2double Segment_P0[3] = {0.0, 0.0, 0.0}, Segment_P1[3] = {0.0, 0.0, 0.0}, Variable_P0 = 0.0, Variable_P1 = 0.0, + Intersection[3] = {0.0, 0.0, 0.0}, Trailing_Coord, *VarCoord = nullptr, Variable_Interp, + v1[3] = {0.0, 0.0, 0.0}, v3[3] = {0.0, 0.0, 0.0}, CrossProduct = 1.0; bool Found_Edge; passivedouble Dist_Value; - vector Xcoord_Index0, Ycoord_Index0, Zcoord_Index0, Variable_Index0, Xcoord_Index1, Ycoord_Index1, Zcoord_Index1, Variable_Index1; - vector IGlobalID_Index0, JGlobalID_Index0, IGlobalID_Index1, JGlobalID_Index1, IGlobalID_Airfoil, JGlobalID_Airfoil; + vector Xcoord_Index0, Ycoord_Index0, Zcoord_Index0, Variable_Index0, Xcoord_Index1, Ycoord_Index1, + Zcoord_Index1, Variable_Index1; + vector IGlobalID_Index0, JGlobalID_Index0, IGlobalID_Index1, JGlobalID_Index1, IGlobalID_Airfoil, + JGlobalID_Airfoil; vector Conection_Index0, Conection_Index1; vector Duplicate; - su2double **Coord_Variation = nullptr; + su2double** Coord_Variation = nullptr; vector XcoordExtra, YcoordExtra, ZcoordExtra, VariableExtra; vector IGlobalIDExtra, JGlobalIDExtra; vector AddExtra; @@ -1700,7 +1589,8 @@ void CGeometry::ComputeAirfoil_Section(su2double *Plane_P0, su2double *Plane_Nor bool FoundEdge; #ifdef HAVE_MPI - unsigned long nLocalEdge, MaxLocalEdge, *Buffer_Send_nEdge, *Buffer_Receive_nEdge, nBuffer_Coord, nBuffer_Variable, nBuffer_GlobalID; + unsigned long nLocalEdge, MaxLocalEdge, *Buffer_Send_nEdge, *Buffer_Receive_nEdge, nBuffer_Coord, nBuffer_Variable, + nBuffer_GlobalID; int nProcessor, iProcessor; su2double *Buffer_Send_Coord, *Buffer_Receive_Coord; su2double *Buffer_Send_Variable, *Buffer_Receive_Variable; @@ -1717,39 +1607,36 @@ void CGeometry::ComputeAirfoil_Section(su2double *Plane_P0, su2double *Plane_Nor /*--- Set the right plane in 2D (note the change in Y-Z plane) ---*/ if (nDim == 2) { - Plane_P0[0] = 0.0; Plane_P0[1] = 0.0; Plane_P0[2] = 0.0; - Plane_Normal[0] = 0.0; Plane_Normal[1] = 1.0; Plane_Normal[2] = 0.0; + Plane_P0[0] = 0.0; + Plane_P0[1] = 0.0; + Plane_P0[2] = 0.0; + Plane_Normal[0] = 0.0; + Plane_Normal[1] = 1.0; + Plane_Normal[2] = 0.0; } /*--- Grid movement is stored using a vertices information, we should go from vertex to points ---*/ if (original_surface == false) { - - Coord_Variation = new su2double *[nPoint]; - for (iPoint = 0; iPoint < nPoint; iPoint++) - Coord_Variation[iPoint] = new su2double [nDim]; + Coord_Variation = new su2double*[nPoint]; + for (iPoint = 0; iPoint < nPoint; iPoint++) Coord_Variation[iPoint] = new su2double[nDim]; for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { if (config->GetMarker_All_GeoEval(iMarker) == YES) { for (iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { VarCoord = vertex[iMarker][iVertex]->GetVarCoord(); iPoint = vertex[iMarker][iVertex]->GetNode(); - for (iDim = 0; iDim < nDim; iDim++) - Coord_Variation[iPoint][iDim] = VarCoord[iDim]; + for (iDim = 0; iDim < nDim; iDim++) Coord_Variation[iPoint][iDim] = VarCoord[iDim]; } } } - } for (iMarker = 0; iMarker < nMarker; iMarker++) { - if (config->GetMarker_All_GeoEval(iMarker) == YES) { - for (iElem = 0; iElem < nElem_Bound[iMarker]; iElem++) { - - PointIndex=0; + PointIndex = 0; /*--- To decide if an element is going to be used or not should be done element based, The first step is to compute and average coordinate for the element ---*/ @@ -1776,9 +1663,8 @@ void CGeometry::ComputeAirfoil_Section(su2double *Plane_P0, su2double *Plane_Nor CrossProduct = 1.0; if (config->GetGeo_Description() == NACELLE) { - - su2double Tilt_Angle = config->GetNacelleLocation(3)*PI_NUMBER/180; - su2double Toe_Angle = config->GetNacelleLocation(4)*PI_NUMBER/180; + su2double Tilt_Angle = config->GetNacelleLocation(3) * PI_NUMBER / 180; + su2double Toe_Angle = config->GetNacelleLocation(4) * PI_NUMBER / 180; /*--- Translate to the origin ---*/ @@ -1788,57 +1674,58 @@ void CGeometry::ComputeAirfoil_Section(su2double *Plane_P0, su2double *Plane_Nor /*--- Apply tilt angle ---*/ - su2double XCoord_Trans_Tilt = XCoord_Trans*cos(Tilt_Angle) + ZCoord_Trans*sin(Tilt_Angle); + su2double XCoord_Trans_Tilt = XCoord_Trans * cos(Tilt_Angle) + ZCoord_Trans * sin(Tilt_Angle); su2double YCoord_Trans_Tilt = YCoord_Trans; - su2double ZCoord_Trans_Tilt = ZCoord_Trans*cos(Tilt_Angle) - XCoord_Trans*sin(Tilt_Angle); + su2double ZCoord_Trans_Tilt = ZCoord_Trans * cos(Tilt_Angle) - XCoord_Trans * sin(Tilt_Angle); /*--- Apply toe angle ---*/ - su2double YCoord_Trans_Tilt_Toe = XCoord_Trans_Tilt*sin(Toe_Angle) + YCoord_Trans_Tilt*cos(Toe_Angle); + su2double YCoord_Trans_Tilt_Toe = XCoord_Trans_Tilt * sin(Toe_Angle) + YCoord_Trans_Tilt * cos(Toe_Angle); su2double ZCoord_Trans_Tilt_Toe = ZCoord_Trans_Tilt; /*--- Undo plane rotation, we have already rotated the nacelle ---*/ /*--- Undo tilt angle ---*/ - su2double XPlane_Normal_Tilt = Plane_Normal[0]*cos(-Tilt_Angle) + Plane_Normal[2]*sin(-Tilt_Angle); + su2double XPlane_Normal_Tilt = Plane_Normal[0] * cos(-Tilt_Angle) + Plane_Normal[2] * sin(-Tilt_Angle); su2double YPlane_Normal_Tilt = Plane_Normal[1]; - su2double ZPlane_Normal_Tilt = Plane_Normal[2]*cos(-Tilt_Angle) - Plane_Normal[0]*sin(-Tilt_Angle); + su2double ZPlane_Normal_Tilt = Plane_Normal[2] * cos(-Tilt_Angle) - Plane_Normal[0] * sin(-Tilt_Angle); /*--- Undo toe angle ---*/ - su2double YPlane_Normal_Tilt_Toe = XPlane_Normal_Tilt*sin(-Toe_Angle) + YPlane_Normal_Tilt*cos(-Toe_Angle); + su2double YPlane_Normal_Tilt_Toe = + XPlane_Normal_Tilt * sin(-Toe_Angle) + YPlane_Normal_Tilt * cos(-Toe_Angle); su2double ZPlane_Normal_Tilt_Toe = ZPlane_Normal_Tilt; - v1[1] = YCoord_Trans_Tilt_Toe - 0.0; v1[2] = ZCoord_Trans_Tilt_Toe - 0.0; - v3[0] = v1[1]*ZPlane_Normal_Tilt_Toe-v1[2]*YPlane_Normal_Tilt_Toe; + v3[0] = v1[1] * ZPlane_Normal_Tilt_Toe - v1[2] * YPlane_Normal_Tilt_Toe; CrossProduct = v3[0] * 1.0; - } - for (unsigned short iFace = 0; iFace < bound[iMarker][iElem]->GetnFaces(); iFace++){ - iNode = bound[iMarker][iElem]->GetFaces(iFace,0); - jNode = bound[iMarker][iElem]->GetFaces(iFace,1); + for (unsigned short iFace = 0; iFace < bound[iMarker][iElem]->GetnFaces(); iFace++) { + iNode = bound[iMarker][iElem]->GetFaces(iFace, 0); + jNode = bound[iMarker][iElem]->GetFaces(iFace, 1); iPoint = bound[iMarker][iElem]->GetNode(iNode); jPoint = bound[iMarker][iElem]->GetNode(jNode); - if ((CrossProduct >= 0.0) - && ((AveXCoord > MinXCoord) && (AveXCoord < MaxXCoord)) - && ((AveYCoord > MinYCoord) && (AveYCoord < MaxYCoord)) - && ((AveZCoord > MinZCoord) && (AveZCoord < MaxZCoord))) { - - Segment_P0[0] = 0.0; Segment_P0[1] = 0.0; Segment_P0[2] = 0.0; Variable_P0 = 0.0; - Segment_P1[0] = 0.0; Segment_P1[1] = 0.0; Segment_P1[2] = 0.0; Variable_P1 = 0.0; - + if ((CrossProduct >= 0.0) && ((AveXCoord > MinXCoord) && (AveXCoord < MaxXCoord)) && + ((AveYCoord > MinYCoord) && (AveYCoord < MaxYCoord)) && + ((AveZCoord > MinZCoord) && (AveZCoord < MaxZCoord))) { + Segment_P0[0] = 0.0; + Segment_P0[1] = 0.0; + Segment_P0[2] = 0.0; + Variable_P0 = 0.0; + Segment_P1[0] = 0.0; + Segment_P1[1] = 0.0; + Segment_P1[2] = 0.0; + Variable_P1 = 0.0; for (iDim = 0; iDim < nDim; iDim++) { if (original_surface == true) { Segment_P0[iDim] = nodes->GetCoord(iPoint, iDim); Segment_P1[iDim] = nodes->GetCoord(jPoint, iDim); - } - else { + } else { Segment_P0[iDim] = nodes->GetCoord(iPoint, iDim) + Coord_Variation[iPoint][iDim]; Segment_P1[iDim] = nodes->GetCoord(jPoint, iDim) + Coord_Variation[jPoint][iDim]; } @@ -1852,19 +1739,26 @@ void CGeometry::ComputeAirfoil_Section(su2double *Plane_P0, su2double *Plane_Nor /*--- In 2D add the points directly (note the change between Y and Z coordinate) ---*/ if (nDim == 2) { - Xcoord_Index0.push_back(Segment_P0[0]); Xcoord_Index1.push_back(Segment_P1[0]); - Ycoord_Index0.push_back(Segment_P0[2]); Ycoord_Index1.push_back(Segment_P1[2]); - Zcoord_Index0.push_back(Segment_P0[1]); Zcoord_Index1.push_back(Segment_P1[1]); - Variable_Index0.push_back(Variable_P0); Variable_Index1.push_back(Variable_P1); - IGlobalID_Index0.push_back(nodes->GetGlobalIndex(iPoint)); IGlobalID_Index1.push_back(nodes->GetGlobalIndex(jPoint)); - JGlobalID_Index0.push_back(nodes->GetGlobalIndex(iPoint)); JGlobalID_Index1.push_back(nodes->GetGlobalIndex(jPoint)); + Xcoord_Index0.push_back(Segment_P0[0]); + Xcoord_Index1.push_back(Segment_P1[0]); + Ycoord_Index0.push_back(Segment_P0[2]); + Ycoord_Index1.push_back(Segment_P1[2]); + Zcoord_Index0.push_back(Segment_P0[1]); + Zcoord_Index1.push_back(Segment_P1[1]); + Variable_Index0.push_back(Variable_P0); + Variable_Index1.push_back(Variable_P1); + IGlobalID_Index0.push_back(nodes->GetGlobalIndex(iPoint)); + IGlobalID_Index1.push_back(nodes->GetGlobalIndex(jPoint)); + JGlobalID_Index0.push_back(nodes->GetGlobalIndex(iPoint)); + JGlobalID_Index1.push_back(nodes->GetGlobalIndex(jPoint)); PointIndex++; } /*--- In 3D compute the intersection ---*/ else if (nDim == 3) { - intersect = SegmentIntersectsPlane(Segment_P0, Segment_P1, Variable_P0, Variable_P1, Plane_P0, Plane_Normal, Intersection, Variable_Interp); + intersect = SegmentIntersectsPlane(Segment_P0, Segment_P1, Variable_P0, Variable_P1, Plane_P0, + Plane_Normal, Intersection, Variable_Interp); if (intersect == true) { if (PointIndex == 0) { Xcoord_Index0.push_back(Intersection[0]); @@ -1892,9 +1786,8 @@ void CGeometry::ComputeAirfoil_Section(su2double *Plane_P0, su2double *Plane_Nor } if (original_surface == false) { - for (iPoint = 0; iPoint < nPoint; iPoint++) - delete [] Coord_Variation[iPoint]; - delete [] Coord_Variation; + for (iPoint = 0; iPoint < nPoint; iPoint++) delete[] Coord_Variation[iPoint]; + delete[] Coord_Variation; } #ifdef HAVE_MPI @@ -1904,117 +1797,131 @@ void CGeometry::ComputeAirfoil_Section(su2double *Plane_P0, su2double *Plane_Nor nLocalEdge = 0, MaxLocalEdge = 0; nProcessor = size; - Buffer_Send_nEdge = new unsigned long [1]; - Buffer_Receive_nEdge = new unsigned long [nProcessor]; + Buffer_Send_nEdge = new unsigned long[1]; + Buffer_Receive_nEdge = new unsigned long[nProcessor]; nLocalEdge = Xcoord_Index0.size(); Buffer_Send_nEdge[0] = nLocalEdge; SU2_MPI::Allreduce(&nLocalEdge, &MaxLocalEdge, 1, MPI_UNSIGNED_LONG, MPI_MAX, SU2_MPI::GetComm()); - SU2_MPI::Allgather(Buffer_Send_nEdge, 1, MPI_UNSIGNED_LONG, Buffer_Receive_nEdge, 1, MPI_UNSIGNED_LONG, SU2_MPI::GetComm()); + SU2_MPI::Allgather(Buffer_Send_nEdge, 1, MPI_UNSIGNED_LONG, Buffer_Receive_nEdge, 1, MPI_UNSIGNED_LONG, + SU2_MPI::GetComm()); - Buffer_Send_Coord = new su2double [MaxLocalEdge*6]; - Buffer_Receive_Coord = new su2double [nProcessor*MaxLocalEdge*6]; + Buffer_Send_Coord = new su2double[MaxLocalEdge * 6]; + Buffer_Receive_Coord = new su2double[nProcessor * MaxLocalEdge * 6]; - Buffer_Send_Variable = new su2double [MaxLocalEdge*2]; - Buffer_Receive_Variable = new su2double [nProcessor*MaxLocalEdge*2]; + Buffer_Send_Variable = new su2double[MaxLocalEdge * 2]; + Buffer_Receive_Variable = new su2double[nProcessor * MaxLocalEdge * 2]; - Buffer_Send_GlobalID = new unsigned long [MaxLocalEdge*4]; - Buffer_Receive_GlobalID = new unsigned long [nProcessor*MaxLocalEdge*4]; + Buffer_Send_GlobalID = new unsigned long[MaxLocalEdge * 4]; + Buffer_Receive_GlobalID = new unsigned long[nProcessor * MaxLocalEdge * 4]; - nBuffer_Coord = MaxLocalEdge*6; - nBuffer_Variable = MaxLocalEdge*2; - nBuffer_GlobalID = MaxLocalEdge*4; + nBuffer_Coord = MaxLocalEdge * 6; + nBuffer_Variable = MaxLocalEdge * 2; + nBuffer_GlobalID = MaxLocalEdge * 4; for (iEdge = 0; iEdge < nLocalEdge; iEdge++) { - Buffer_Send_Coord[iEdge*6 + 0] = Xcoord_Index0[iEdge]; - Buffer_Send_Coord[iEdge*6 + 1] = Ycoord_Index0[iEdge]; - Buffer_Send_Coord[iEdge*6 + 2] = Zcoord_Index0[iEdge]; - Buffer_Send_Coord[iEdge*6 + 3] = Xcoord_Index1[iEdge]; - Buffer_Send_Coord[iEdge*6 + 4] = Ycoord_Index1[iEdge]; - Buffer_Send_Coord[iEdge*6 + 5] = Zcoord_Index1[iEdge]; - - Buffer_Send_Variable[iEdge*2 + 0] = Variable_Index0[iEdge]; - Buffer_Send_Variable[iEdge*2 + 1] = Variable_Index1[iEdge]; - - Buffer_Send_GlobalID[iEdge*4 + 0] = IGlobalID_Index0[iEdge]; - Buffer_Send_GlobalID[iEdge*4 + 1] = JGlobalID_Index0[iEdge]; - Buffer_Send_GlobalID[iEdge*4 + 2] = IGlobalID_Index1[iEdge]; - Buffer_Send_GlobalID[iEdge*4 + 3] = JGlobalID_Index1[iEdge]; + Buffer_Send_Coord[iEdge * 6 + 0] = Xcoord_Index0[iEdge]; + Buffer_Send_Coord[iEdge * 6 + 1] = Ycoord_Index0[iEdge]; + Buffer_Send_Coord[iEdge * 6 + 2] = Zcoord_Index0[iEdge]; + Buffer_Send_Coord[iEdge * 6 + 3] = Xcoord_Index1[iEdge]; + Buffer_Send_Coord[iEdge * 6 + 4] = Ycoord_Index1[iEdge]; + Buffer_Send_Coord[iEdge * 6 + 5] = Zcoord_Index1[iEdge]; + + Buffer_Send_Variable[iEdge * 2 + 0] = Variable_Index0[iEdge]; + Buffer_Send_Variable[iEdge * 2 + 1] = Variable_Index1[iEdge]; + + Buffer_Send_GlobalID[iEdge * 4 + 0] = IGlobalID_Index0[iEdge]; + Buffer_Send_GlobalID[iEdge * 4 + 1] = JGlobalID_Index0[iEdge]; + Buffer_Send_GlobalID[iEdge * 4 + 2] = IGlobalID_Index1[iEdge]; + Buffer_Send_GlobalID[iEdge * 4 + 3] = JGlobalID_Index1[iEdge]; } - SU2_MPI::Allgather(Buffer_Send_Coord, nBuffer_Coord, MPI_DOUBLE, Buffer_Receive_Coord, nBuffer_Coord, MPI_DOUBLE, SU2_MPI::GetComm()); - SU2_MPI::Allgather(Buffer_Send_Variable, nBuffer_Variable, MPI_DOUBLE, Buffer_Receive_Variable, nBuffer_Variable, MPI_DOUBLE, SU2_MPI::GetComm()); - SU2_MPI::Allgather(Buffer_Send_GlobalID, nBuffer_GlobalID, MPI_UNSIGNED_LONG, Buffer_Receive_GlobalID, nBuffer_GlobalID, MPI_UNSIGNED_LONG, SU2_MPI::GetComm()); + SU2_MPI::Allgather(Buffer_Send_Coord, nBuffer_Coord, MPI_DOUBLE, Buffer_Receive_Coord, nBuffer_Coord, MPI_DOUBLE, + SU2_MPI::GetComm()); + SU2_MPI::Allgather(Buffer_Send_Variable, nBuffer_Variable, MPI_DOUBLE, Buffer_Receive_Variable, nBuffer_Variable, + MPI_DOUBLE, SU2_MPI::GetComm()); + SU2_MPI::Allgather(Buffer_Send_GlobalID, nBuffer_GlobalID, MPI_UNSIGNED_LONG, Buffer_Receive_GlobalID, + nBuffer_GlobalID, MPI_UNSIGNED_LONG, SU2_MPI::GetComm()); /*--- Clean the vectors before adding the new vertices only to the master node ---*/ - Xcoord_Index0.clear(); Xcoord_Index1.clear(); - Ycoord_Index0.clear(); Ycoord_Index1.clear(); - Zcoord_Index0.clear(); Zcoord_Index1.clear(); - Variable_Index0.clear(); Variable_Index1.clear(); - IGlobalID_Index0.clear(); IGlobalID_Index1.clear(); - JGlobalID_Index0.clear(); JGlobalID_Index1.clear(); + Xcoord_Index0.clear(); + Xcoord_Index1.clear(); + Ycoord_Index0.clear(); + Ycoord_Index1.clear(); + Zcoord_Index0.clear(); + Zcoord_Index1.clear(); + Variable_Index0.clear(); + Variable_Index1.clear(); + IGlobalID_Index0.clear(); + IGlobalID_Index1.clear(); + JGlobalID_Index0.clear(); + JGlobalID_Index1.clear(); /*--- Copy the boundary to the master node vectors ---*/ if (rank == MASTER_NODE) { for (iProcessor = 0; iProcessor < nProcessor; iProcessor++) { for (iEdge = 0; iEdge < Buffer_Receive_nEdge[iProcessor]; iEdge++) { - Xcoord_Index0.push_back( Buffer_Receive_Coord[ iProcessor*MaxLocalEdge*6 + iEdge*6 + 0] ); - Ycoord_Index0.push_back( Buffer_Receive_Coord[ iProcessor*MaxLocalEdge*6 + iEdge*6 + 1] ); - Zcoord_Index0.push_back( Buffer_Receive_Coord[ iProcessor*MaxLocalEdge*6 + iEdge*6 + 2] ); - Xcoord_Index1.push_back( Buffer_Receive_Coord[ iProcessor*MaxLocalEdge*6 + iEdge*6 + 3] ); - Ycoord_Index1.push_back( Buffer_Receive_Coord[ iProcessor*MaxLocalEdge*6 + iEdge*6 + 4] ); - Zcoord_Index1.push_back( Buffer_Receive_Coord[ iProcessor*MaxLocalEdge*6 + iEdge*6 + 5] ); - - Variable_Index0.push_back( Buffer_Receive_Variable[ iProcessor*MaxLocalEdge*2 + iEdge*2 + 0] ); - Variable_Index1.push_back( Buffer_Receive_Variable[ iProcessor*MaxLocalEdge*2 + iEdge*2 + 1] ); - - IGlobalID_Index0.push_back( Buffer_Receive_GlobalID[ iProcessor*MaxLocalEdge*4 + iEdge*4 + 0] ); - JGlobalID_Index0.push_back( Buffer_Receive_GlobalID[ iProcessor*MaxLocalEdge*4 + iEdge*4 + 1] ); - IGlobalID_Index1.push_back( Buffer_Receive_GlobalID[ iProcessor*MaxLocalEdge*4 + iEdge*4 + 2] ); - JGlobalID_Index1.push_back( Buffer_Receive_GlobalID[ iProcessor*MaxLocalEdge*4 + iEdge*4 + 3] ); - + Xcoord_Index0.push_back(Buffer_Receive_Coord[iProcessor * MaxLocalEdge * 6 + iEdge * 6 + 0]); + Ycoord_Index0.push_back(Buffer_Receive_Coord[iProcessor * MaxLocalEdge * 6 + iEdge * 6 + 1]); + Zcoord_Index0.push_back(Buffer_Receive_Coord[iProcessor * MaxLocalEdge * 6 + iEdge * 6 + 2]); + Xcoord_Index1.push_back(Buffer_Receive_Coord[iProcessor * MaxLocalEdge * 6 + iEdge * 6 + 3]); + Ycoord_Index1.push_back(Buffer_Receive_Coord[iProcessor * MaxLocalEdge * 6 + iEdge * 6 + 4]); + Zcoord_Index1.push_back(Buffer_Receive_Coord[iProcessor * MaxLocalEdge * 6 + iEdge * 6 + 5]); + + Variable_Index0.push_back(Buffer_Receive_Variable[iProcessor * MaxLocalEdge * 2 + iEdge * 2 + 0]); + Variable_Index1.push_back(Buffer_Receive_Variable[iProcessor * MaxLocalEdge * 2 + iEdge * 2 + 1]); + + IGlobalID_Index0.push_back(Buffer_Receive_GlobalID[iProcessor * MaxLocalEdge * 4 + iEdge * 4 + 0]); + JGlobalID_Index0.push_back(Buffer_Receive_GlobalID[iProcessor * MaxLocalEdge * 4 + iEdge * 4 + 1]); + IGlobalID_Index1.push_back(Buffer_Receive_GlobalID[iProcessor * MaxLocalEdge * 4 + iEdge * 4 + 2]); + JGlobalID_Index1.push_back(Buffer_Receive_GlobalID[iProcessor * MaxLocalEdge * 4 + iEdge * 4 + 3]); } } } - delete[] Buffer_Send_Coord; delete[] Buffer_Receive_Coord; - delete[] Buffer_Send_Variable; delete[] Buffer_Receive_Variable; - delete[] Buffer_Send_GlobalID; delete[] Buffer_Receive_GlobalID; - delete[] Buffer_Send_nEdge; delete[] Buffer_Receive_nEdge; + delete[] Buffer_Send_Coord; + delete[] Buffer_Receive_Coord; + delete[] Buffer_Send_Variable; + delete[] Buffer_Receive_Variable; + delete[] Buffer_Send_GlobalID; + delete[] Buffer_Receive_GlobalID; + delete[] Buffer_Send_nEdge; + delete[] Buffer_Receive_nEdge; #endif if ((rank == MASTER_NODE) && (Xcoord_Index0.size() != 0)) { - /*--- Remove singular edges ---*/ bool Remove; - do { Remove = false; + do { + Remove = false; for (iEdge = 0; iEdge < Xcoord_Index0.size(); iEdge++) { - - if (((IGlobalID_Index0[iEdge] == IGlobalID_Index1[iEdge]) && (JGlobalID_Index0[iEdge] == JGlobalID_Index1[iEdge])) || - ((IGlobalID_Index0[iEdge] == JGlobalID_Index1[iEdge]) && (JGlobalID_Index0[iEdge] == IGlobalID_Index1[iEdge]))) { - - Xcoord_Index0.erase (Xcoord_Index0.begin() + iEdge); - Ycoord_Index0.erase (Ycoord_Index0.begin() + iEdge); - Zcoord_Index0.erase (Zcoord_Index0.begin() + iEdge); - Variable_Index0.erase (Variable_Index0.begin() + iEdge); - IGlobalID_Index0.erase (IGlobalID_Index0.begin() + iEdge); - JGlobalID_Index0.erase (JGlobalID_Index0.begin() + iEdge); - - Xcoord_Index1.erase (Xcoord_Index1.begin() + iEdge); - Ycoord_Index1.erase (Ycoord_Index1.begin() + iEdge); - Zcoord_Index1.erase (Zcoord_Index1.begin() + iEdge); - Variable_Index1.erase (Variable_Index1.begin() + iEdge); - IGlobalID_Index1.erase (IGlobalID_Index1.begin() + iEdge); - JGlobalID_Index1.erase (JGlobalID_Index1.begin() + iEdge); - - Remove = true; break; + if (((IGlobalID_Index0[iEdge] == IGlobalID_Index1[iEdge]) && + (JGlobalID_Index0[iEdge] == JGlobalID_Index1[iEdge])) || + ((IGlobalID_Index0[iEdge] == JGlobalID_Index1[iEdge]) && + (JGlobalID_Index0[iEdge] == IGlobalID_Index1[iEdge]))) { + Xcoord_Index0.erase(Xcoord_Index0.begin() + iEdge); + Ycoord_Index0.erase(Ycoord_Index0.begin() + iEdge); + Zcoord_Index0.erase(Zcoord_Index0.begin() + iEdge); + Variable_Index0.erase(Variable_Index0.begin() + iEdge); + IGlobalID_Index0.erase(IGlobalID_Index0.begin() + iEdge); + JGlobalID_Index0.erase(JGlobalID_Index0.begin() + iEdge); + + Xcoord_Index1.erase(Xcoord_Index1.begin() + iEdge); + Ycoord_Index1.erase(Ycoord_Index1.begin() + iEdge); + Zcoord_Index1.erase(Zcoord_Index1.begin() + iEdge); + Variable_Index1.erase(Variable_Index1.begin() + iEdge); + IGlobalID_Index1.erase(IGlobalID_Index1.begin() + iEdge); + JGlobalID_Index1.erase(JGlobalID_Index1.begin() + iEdge); + + Remove = true; + break; } if (Remove) break; } @@ -2022,58 +1929,65 @@ void CGeometry::ComputeAirfoil_Section(su2double *Plane_P0, su2double *Plane_Nor /*--- Remove repeated edges computing distance, this could happend because the MPI ---*/ - do { Remove = false; - for (iEdge = 0; iEdge < Xcoord_Index0.size()-1; iEdge++) { - for (jEdge = iEdge+1; jEdge < Xcoord_Index0.size(); jEdge++) { - + do { + Remove = false; + for (iEdge = 0; iEdge < Xcoord_Index0.size() - 1; iEdge++) { + for (jEdge = iEdge + 1; jEdge < Xcoord_Index0.size(); jEdge++) { /*--- Edges with the same orientation ---*/ - if ((((IGlobalID_Index0[iEdge] == IGlobalID_Index0[jEdge]) && (JGlobalID_Index0[iEdge] == JGlobalID_Index0[jEdge])) || - ((IGlobalID_Index0[iEdge] == JGlobalID_Index0[jEdge]) && (JGlobalID_Index0[iEdge] == IGlobalID_Index0[jEdge]))) && - (((IGlobalID_Index1[iEdge] == IGlobalID_Index1[jEdge]) && (JGlobalID_Index1[iEdge] == JGlobalID_Index1[jEdge])) || - ((IGlobalID_Index1[iEdge] == JGlobalID_Index1[jEdge]) && (JGlobalID_Index1[iEdge] == IGlobalID_Index1[jEdge])))) { - - Xcoord_Index0.erase (Xcoord_Index0.begin() + jEdge); - Ycoord_Index0.erase (Ycoord_Index0.begin() + jEdge); - Zcoord_Index0.erase (Zcoord_Index0.begin() + jEdge); - Variable_Index0.erase (Variable_Index0.begin() + jEdge); - IGlobalID_Index0.erase (IGlobalID_Index0.begin() + jEdge); - JGlobalID_Index0.erase (JGlobalID_Index0.begin() + jEdge); - - Xcoord_Index1.erase (Xcoord_Index1.begin() + jEdge); - Ycoord_Index1.erase (Ycoord_Index1.begin() + jEdge); - Zcoord_Index1.erase (Zcoord_Index1.begin() + jEdge); - Variable_Index1.erase (Variable_Index1.begin() + jEdge); - IGlobalID_Index1.erase (IGlobalID_Index1.begin() + jEdge); - JGlobalID_Index1.erase (JGlobalID_Index1.begin() + jEdge); - - Remove = true; break; - - } + if ((((IGlobalID_Index0[iEdge] == IGlobalID_Index0[jEdge]) && + (JGlobalID_Index0[iEdge] == JGlobalID_Index0[jEdge])) || + ((IGlobalID_Index0[iEdge] == JGlobalID_Index0[jEdge]) && + (JGlobalID_Index0[iEdge] == IGlobalID_Index0[jEdge]))) && + (((IGlobalID_Index1[iEdge] == IGlobalID_Index1[jEdge]) && + (JGlobalID_Index1[iEdge] == JGlobalID_Index1[jEdge])) || + ((IGlobalID_Index1[iEdge] == JGlobalID_Index1[jEdge]) && + (JGlobalID_Index1[iEdge] == IGlobalID_Index1[jEdge])))) { + Xcoord_Index0.erase(Xcoord_Index0.begin() + jEdge); + Ycoord_Index0.erase(Ycoord_Index0.begin() + jEdge); + Zcoord_Index0.erase(Zcoord_Index0.begin() + jEdge); + Variable_Index0.erase(Variable_Index0.begin() + jEdge); + IGlobalID_Index0.erase(IGlobalID_Index0.begin() + jEdge); + JGlobalID_Index0.erase(JGlobalID_Index0.begin() + jEdge); + + Xcoord_Index1.erase(Xcoord_Index1.begin() + jEdge); + Ycoord_Index1.erase(Ycoord_Index1.begin() + jEdge); + Zcoord_Index1.erase(Zcoord_Index1.begin() + jEdge); + Variable_Index1.erase(Variable_Index1.begin() + jEdge); + IGlobalID_Index1.erase(IGlobalID_Index1.begin() + jEdge); + JGlobalID_Index1.erase(JGlobalID_Index1.begin() + jEdge); + + Remove = true; + break; + } /*--- Edges with oposite orientation ---*/ - if ((((IGlobalID_Index0[iEdge] == IGlobalID_Index1[jEdge]) && (JGlobalID_Index0[iEdge] == JGlobalID_Index1[jEdge])) || - ((IGlobalID_Index0[iEdge] == JGlobalID_Index1[jEdge]) && (JGlobalID_Index0[iEdge] == IGlobalID_Index1[jEdge]))) && - (((IGlobalID_Index1[iEdge] == IGlobalID_Index0[jEdge]) && (JGlobalID_Index1[iEdge] == JGlobalID_Index0[jEdge])) || - ((IGlobalID_Index1[iEdge] == JGlobalID_Index0[jEdge]) && (JGlobalID_Index1[iEdge] == IGlobalID_Index0[jEdge])))) { - - Xcoord_Index0.erase (Xcoord_Index0.begin() + jEdge); - Ycoord_Index0.erase (Ycoord_Index0.begin() + jEdge); - Zcoord_Index0.erase (Zcoord_Index0.begin() + jEdge); - Variable_Index0.erase (Variable_Index0.begin() + jEdge); - IGlobalID_Index0.erase (IGlobalID_Index0.begin() + jEdge); - JGlobalID_Index0.erase (JGlobalID_Index0.begin() + jEdge); - - Xcoord_Index1.erase (Xcoord_Index1.begin() + jEdge); - Ycoord_Index1.erase (Ycoord_Index1.begin() + jEdge); - Zcoord_Index1.erase (Zcoord_Index1.begin() + jEdge); - Variable_Index1.erase (Variable_Index1.begin() + jEdge); - IGlobalID_Index1.erase (IGlobalID_Index1.begin() + jEdge); - JGlobalID_Index1.erase (JGlobalID_Index1.begin() + jEdge); - - Remove = true; break; - } + if ((((IGlobalID_Index0[iEdge] == IGlobalID_Index1[jEdge]) && + (JGlobalID_Index0[iEdge] == JGlobalID_Index1[jEdge])) || + ((IGlobalID_Index0[iEdge] == JGlobalID_Index1[jEdge]) && + (JGlobalID_Index0[iEdge] == IGlobalID_Index1[jEdge]))) && + (((IGlobalID_Index1[iEdge] == IGlobalID_Index0[jEdge]) && + (JGlobalID_Index1[iEdge] == JGlobalID_Index0[jEdge])) || + ((IGlobalID_Index1[iEdge] == JGlobalID_Index0[jEdge]) && + (JGlobalID_Index1[iEdge] == IGlobalID_Index0[jEdge])))) { + Xcoord_Index0.erase(Xcoord_Index0.begin() + jEdge); + Ycoord_Index0.erase(Ycoord_Index0.begin() + jEdge); + Zcoord_Index0.erase(Zcoord_Index0.begin() + jEdge); + Variable_Index0.erase(Variable_Index0.begin() + jEdge); + IGlobalID_Index0.erase(IGlobalID_Index0.begin() + jEdge); + JGlobalID_Index0.erase(JGlobalID_Index0.begin() + jEdge); + + Xcoord_Index1.erase(Xcoord_Index1.begin() + jEdge); + Ycoord_Index1.erase(Ycoord_Index1.begin() + jEdge); + Zcoord_Index1.erase(Zcoord_Index1.begin() + jEdge); + Variable_Index1.erase(Variable_Index1.begin() + jEdge); + IGlobalID_Index1.erase(IGlobalID_Index1.begin() + jEdge); + JGlobalID_Index1.erase(JGlobalID_Index1.begin() + jEdge); + + Remove = true; + break; + } if (Remove) break; } if (Remove) break; @@ -2082,38 +1996,38 @@ void CGeometry::ComputeAirfoil_Section(su2double *Plane_P0, su2double *Plane_Nor } while (Remove == true); if (Xcoord_Index0.size() != 1) { - /*--- Rotate from the Y-Z plane to the X-Z plane to reuse the rest of subroutines ---*/ if (config->GetGeo_Description() == FUSELAGE) { - su2double Angle = -0.5*PI_NUMBER; + su2double Angle = -0.5 * PI_NUMBER; for (iEdge = 0; iEdge < Xcoord_Index0.size(); iEdge++) { - su2double XCoord = Xcoord_Index0[iEdge]*cos(Angle) - Ycoord_Index0[iEdge]*sin(Angle); - su2double YCoord = Ycoord_Index0[iEdge]*cos(Angle) + Xcoord_Index0[iEdge]*sin(Angle); + su2double XCoord = Xcoord_Index0[iEdge] * cos(Angle) - Ycoord_Index0[iEdge] * sin(Angle); + su2double YCoord = Ycoord_Index0[iEdge] * cos(Angle) + Xcoord_Index0[iEdge] * sin(Angle); su2double ZCoord = Zcoord_Index0[iEdge]; - Xcoord_Index0[iEdge] = XCoord; Ycoord_Index0[iEdge] = YCoord; Zcoord_Index0[iEdge] = ZCoord; - XCoord = Xcoord_Index1[iEdge]*cos(Angle) - Ycoord_Index1[iEdge]*sin(Angle); - YCoord = Ycoord_Index1[iEdge]*cos(Angle) + Xcoord_Index1[iEdge]*sin(Angle); + Xcoord_Index0[iEdge] = XCoord; + Ycoord_Index0[iEdge] = YCoord; + Zcoord_Index0[iEdge] = ZCoord; + XCoord = Xcoord_Index1[iEdge] * cos(Angle) - Ycoord_Index1[iEdge] * sin(Angle); + YCoord = Ycoord_Index1[iEdge] * cos(Angle) + Xcoord_Index1[iEdge] * sin(Angle); ZCoord = Zcoord_Index1[iEdge]; - Xcoord_Index1[iEdge] = XCoord; Ycoord_Index1[iEdge] = YCoord; Zcoord_Index1[iEdge] = ZCoord; + Xcoord_Index1[iEdge] = XCoord; + Ycoord_Index1[iEdge] = YCoord; + Zcoord_Index1[iEdge] = ZCoord; } } /*--- Rotate nacelle secction to a X-Z plane to reuse the rest of subroutines ---*/ - if (config->GetGeo_Description() == NACELLE) { - - su2double Tilt_Angle = config->GetNacelleLocation(3)*PI_NUMBER/180; - su2double Toe_Angle = config->GetNacelleLocation(4)*PI_NUMBER/180; - su2double Theta_deg = atan2(Plane_Normal[1],-Plane_Normal[2])/PI_NUMBER*180 + 180; - su2double Roll_Angle = 0.5*PI_NUMBER - Theta_deg*PI_NUMBER/180; + su2double Tilt_Angle = config->GetNacelleLocation(3) * PI_NUMBER / 180; + su2double Toe_Angle = config->GetNacelleLocation(4) * PI_NUMBER / 180; + su2double Theta_deg = atan2(Plane_Normal[1], -Plane_Normal[2]) / PI_NUMBER * 180 + 180; + su2double Roll_Angle = 0.5 * PI_NUMBER - Theta_deg * PI_NUMBER / 180; su2double XCoord_Trans, YCoord_Trans, ZCoord_Trans, XCoord_Trans_Tilt, YCoord_Trans_Tilt, ZCoord_Trans_Tilt, - XCoord_Trans_Tilt_Toe, YCoord_Trans_Tilt_Toe, ZCoord_Trans_Tilt_Toe, XCoord, YCoord, ZCoord; + XCoord_Trans_Tilt_Toe, YCoord_Trans_Tilt_Toe, ZCoord_Trans_Tilt_Toe, XCoord, YCoord, ZCoord; for (iEdge = 0; iEdge < Xcoord_Index0.size(); iEdge++) { - /*--- First point of the edge ---*/ /*--- Translate to the origin ---*/ @@ -2124,25 +2038,27 @@ void CGeometry::ComputeAirfoil_Section(su2double *Plane_P0, su2double *Plane_Nor /*--- Apply tilt angle ---*/ - XCoord_Trans_Tilt = XCoord_Trans*cos(Tilt_Angle) + ZCoord_Trans*sin(Tilt_Angle); + XCoord_Trans_Tilt = XCoord_Trans * cos(Tilt_Angle) + ZCoord_Trans * sin(Tilt_Angle); YCoord_Trans_Tilt = YCoord_Trans; - ZCoord_Trans_Tilt = ZCoord_Trans*cos(Tilt_Angle) - XCoord_Trans*sin(Tilt_Angle); + ZCoord_Trans_Tilt = ZCoord_Trans * cos(Tilt_Angle) - XCoord_Trans * sin(Tilt_Angle); /*--- Apply toe angle ---*/ - XCoord_Trans_Tilt_Toe = XCoord_Trans_Tilt*cos(Toe_Angle) - YCoord_Trans_Tilt*sin(Toe_Angle); - YCoord_Trans_Tilt_Toe = XCoord_Trans_Tilt*sin(Toe_Angle) + YCoord_Trans_Tilt*cos(Toe_Angle); + XCoord_Trans_Tilt_Toe = XCoord_Trans_Tilt * cos(Toe_Angle) - YCoord_Trans_Tilt * sin(Toe_Angle); + YCoord_Trans_Tilt_Toe = XCoord_Trans_Tilt * sin(Toe_Angle) + YCoord_Trans_Tilt * cos(Toe_Angle); ZCoord_Trans_Tilt_Toe = ZCoord_Trans_Tilt; /*--- Rotate to X-Z plane (roll) ---*/ XCoord = XCoord_Trans_Tilt_Toe; - YCoord = YCoord_Trans_Tilt_Toe*cos(Roll_Angle) - ZCoord_Trans_Tilt_Toe*sin(Roll_Angle); - ZCoord = YCoord_Trans_Tilt_Toe*sin(Roll_Angle) + ZCoord_Trans_Tilt_Toe*cos(Roll_Angle); + YCoord = YCoord_Trans_Tilt_Toe * cos(Roll_Angle) - ZCoord_Trans_Tilt_Toe * sin(Roll_Angle); + ZCoord = YCoord_Trans_Tilt_Toe * sin(Roll_Angle) + ZCoord_Trans_Tilt_Toe * cos(Roll_Angle); /*--- Update coordinates ---*/ - Xcoord_Index0[iEdge] = XCoord; Ycoord_Index0[iEdge] = YCoord; Zcoord_Index0[iEdge] = ZCoord; + Xcoord_Index0[iEdge] = XCoord; + Ycoord_Index0[iEdge] = YCoord; + Zcoord_Index0[iEdge] = ZCoord; /*--- Second point of the edge ---*/ @@ -2154,59 +2070,73 @@ void CGeometry::ComputeAirfoil_Section(su2double *Plane_P0, su2double *Plane_Nor /*--- Apply tilt angle ---*/ - XCoord_Trans_Tilt = XCoord_Trans*cos(Tilt_Angle) + ZCoord_Trans*sin(Tilt_Angle); + XCoord_Trans_Tilt = XCoord_Trans * cos(Tilt_Angle) + ZCoord_Trans * sin(Tilt_Angle); YCoord_Trans_Tilt = YCoord_Trans; - ZCoord_Trans_Tilt = ZCoord_Trans*cos(Tilt_Angle) - XCoord_Trans*sin(Tilt_Angle); + ZCoord_Trans_Tilt = ZCoord_Trans * cos(Tilt_Angle) - XCoord_Trans * sin(Tilt_Angle); /*--- Apply toe angle ---*/ - XCoord_Trans_Tilt_Toe = XCoord_Trans_Tilt*cos(Toe_Angle) - YCoord_Trans_Tilt*sin(Toe_Angle); - YCoord_Trans_Tilt_Toe = XCoord_Trans_Tilt*sin(Toe_Angle) + YCoord_Trans_Tilt*cos(Toe_Angle); + XCoord_Trans_Tilt_Toe = XCoord_Trans_Tilt * cos(Toe_Angle) - YCoord_Trans_Tilt * sin(Toe_Angle); + YCoord_Trans_Tilt_Toe = XCoord_Trans_Tilt * sin(Toe_Angle) + YCoord_Trans_Tilt * cos(Toe_Angle); ZCoord_Trans_Tilt_Toe = ZCoord_Trans_Tilt; /*--- Rotate to X-Z plane (roll) ---*/ XCoord = XCoord_Trans_Tilt_Toe; - YCoord = YCoord_Trans_Tilt_Toe*cos(Roll_Angle) - ZCoord_Trans_Tilt_Toe*sin(Roll_Angle); - ZCoord = YCoord_Trans_Tilt_Toe*sin(Roll_Angle) + ZCoord_Trans_Tilt_Toe*cos(Roll_Angle); + YCoord = YCoord_Trans_Tilt_Toe * cos(Roll_Angle) - ZCoord_Trans_Tilt_Toe * sin(Roll_Angle); + ZCoord = YCoord_Trans_Tilt_Toe * sin(Roll_Angle) + ZCoord_Trans_Tilt_Toe * cos(Roll_Angle); /*--- Update coordinates ---*/ - Xcoord_Index1[iEdge] = XCoord; Ycoord_Index1[iEdge] = YCoord; Zcoord_Index1[iEdge] = ZCoord; - + Xcoord_Index1[iEdge] = XCoord; + Ycoord_Index1[iEdge] = YCoord; + Zcoord_Index1[iEdge] = ZCoord; } } - /*--- Identify the extreme of the curve and close it ---*/ - Conection_Index0.reserve(Xcoord_Index0.size()+1); - Conection_Index1.reserve(Xcoord_Index0.size()+1); + Conection_Index0.reserve(Xcoord_Index0.size() + 1); + Conection_Index1.reserve(Xcoord_Index0.size() + 1); for (iEdge = 0; iEdge < Xcoord_Index0.size(); iEdge++) { Conection_Index0[iEdge] = 0; Conection_Index1[iEdge] = 0; } - for (iEdge = 0; iEdge < Xcoord_Index0.size()-1; iEdge++) { - for (jEdge = iEdge+1; jEdge < Xcoord_Index0.size(); jEdge++) { - - if (((IGlobalID_Index0[iEdge] == IGlobalID_Index0[jEdge]) && (JGlobalID_Index0[iEdge] == JGlobalID_Index0[jEdge])) || - ((IGlobalID_Index0[iEdge] == JGlobalID_Index0[jEdge]) && (JGlobalID_Index0[iEdge] == IGlobalID_Index0[jEdge]))) - { Conection_Index0[iEdge]++; Conection_Index0[jEdge]++; } - - if (((IGlobalID_Index0[iEdge] == IGlobalID_Index1[jEdge]) && (JGlobalID_Index0[iEdge] == JGlobalID_Index1[jEdge])) || - ((IGlobalID_Index0[iEdge] == JGlobalID_Index1[jEdge]) && (JGlobalID_Index0[iEdge] == IGlobalID_Index1[jEdge]))) - { Conection_Index0[iEdge]++; Conection_Index1[jEdge]++; } + for (iEdge = 0; iEdge < Xcoord_Index0.size() - 1; iEdge++) { + for (jEdge = iEdge + 1; jEdge < Xcoord_Index0.size(); jEdge++) { + if (((IGlobalID_Index0[iEdge] == IGlobalID_Index0[jEdge]) && + (JGlobalID_Index0[iEdge] == JGlobalID_Index0[jEdge])) || + ((IGlobalID_Index0[iEdge] == JGlobalID_Index0[jEdge]) && + (JGlobalID_Index0[iEdge] == IGlobalID_Index0[jEdge]))) { + Conection_Index0[iEdge]++; + Conection_Index0[jEdge]++; + } - if (((IGlobalID_Index1[iEdge] == IGlobalID_Index0[jEdge]) && (JGlobalID_Index1[iEdge] == JGlobalID_Index0[jEdge])) || - ((IGlobalID_Index1[iEdge] == JGlobalID_Index0[jEdge]) && (JGlobalID_Index1[iEdge] == IGlobalID_Index0[jEdge]))) - { Conection_Index1[iEdge]++; Conection_Index0[jEdge]++; } + if (((IGlobalID_Index0[iEdge] == IGlobalID_Index1[jEdge]) && + (JGlobalID_Index0[iEdge] == JGlobalID_Index1[jEdge])) || + ((IGlobalID_Index0[iEdge] == JGlobalID_Index1[jEdge]) && + (JGlobalID_Index0[iEdge] == IGlobalID_Index1[jEdge]))) { + Conection_Index0[iEdge]++; + Conection_Index1[jEdge]++; + } - if (((IGlobalID_Index1[iEdge] == IGlobalID_Index1[jEdge]) && (JGlobalID_Index1[iEdge] == JGlobalID_Index1[jEdge])) || - ((IGlobalID_Index1[iEdge] == JGlobalID_Index1[jEdge]) && (JGlobalID_Index1[iEdge] == IGlobalID_Index1[jEdge]))) - { Conection_Index1[iEdge]++; Conection_Index1[jEdge]++; } + if (((IGlobalID_Index1[iEdge] == IGlobalID_Index0[jEdge]) && + (JGlobalID_Index1[iEdge] == JGlobalID_Index0[jEdge])) || + ((IGlobalID_Index1[iEdge] == JGlobalID_Index0[jEdge]) && + (JGlobalID_Index1[iEdge] == IGlobalID_Index0[jEdge]))) { + Conection_Index1[iEdge]++; + Conection_Index0[jEdge]++; + } + if (((IGlobalID_Index1[iEdge] == IGlobalID_Index1[jEdge]) && + (JGlobalID_Index1[iEdge] == JGlobalID_Index1[jEdge])) || + ((IGlobalID_Index1[iEdge] == JGlobalID_Index1[jEdge]) && + (JGlobalID_Index1[iEdge] == IGlobalID_Index1[jEdge]))) { + Conection_Index1[iEdge]++; + Conection_Index1[jEdge]++; + } } } @@ -2238,56 +2168,57 @@ void CGeometry::ComputeAirfoil_Section(su2double *Plane_P0, su2double *Plane_Nor /*--- Second, if it is an open curve then find the closest point to an extreme to close it ---*/ if (XcoordExtra.size() > 1) { - - for (iEdge = 0; iEdge < XcoordExtra.size()-1; iEdge++) { - - su2double MinDist = 1E6; FoundEdge = false; EdgeDonor = 0; - for (jEdge = iEdge+1; jEdge < XcoordExtra.size(); jEdge++) { - Dist_Value = sqrt(pow(SU2_TYPE::GetValue(XcoordExtra[iEdge])-SU2_TYPE::GetValue(XcoordExtra[jEdge]), 2.0)); + for (iEdge = 0; iEdge < XcoordExtra.size() - 1; iEdge++) { + su2double MinDist = 1E6; + FoundEdge = false; + EdgeDonor = 0; + for (jEdge = iEdge + 1; jEdge < XcoordExtra.size(); jEdge++) { + Dist_Value = + sqrt(pow(SU2_TYPE::GetValue(XcoordExtra[iEdge]) - SU2_TYPE::GetValue(XcoordExtra[jEdge]), 2.0)); if ((Dist_Value < MinDist) && (AddExtra[iEdge]) && (AddExtra[jEdge])) { - EdgeDonor = jEdge; FoundEdge = true; + EdgeDonor = jEdge; + FoundEdge = true; } } if (FoundEdge) { - /*--- Add first point of the new edge ---*/ - Xcoord_Index0.push_back (XcoordExtra[iEdge]); - Ycoord_Index0.push_back (YcoordExtra[iEdge]); - Zcoord_Index0.push_back (ZcoordExtra[iEdge]); - Variable_Index0.push_back (VariableExtra[iEdge]); - IGlobalID_Index0.push_back (IGlobalIDExtra[iEdge]); - JGlobalID_Index0.push_back (JGlobalIDExtra[iEdge]); + Xcoord_Index0.push_back(XcoordExtra[iEdge]); + Ycoord_Index0.push_back(YcoordExtra[iEdge]); + Zcoord_Index0.push_back(ZcoordExtra[iEdge]); + Variable_Index0.push_back(VariableExtra[iEdge]); + IGlobalID_Index0.push_back(IGlobalIDExtra[iEdge]); + JGlobalID_Index0.push_back(JGlobalIDExtra[iEdge]); AddExtra[iEdge] = false; /*--- Add second (closest) point of the new edge ---*/ - Xcoord_Index1.push_back (XcoordExtra[EdgeDonor]); - Ycoord_Index1.push_back (YcoordExtra[EdgeDonor]); - Zcoord_Index1.push_back (ZcoordExtra[EdgeDonor]); - Variable_Index1.push_back (VariableExtra[EdgeDonor]); - IGlobalID_Index1.push_back (IGlobalIDExtra[EdgeDonor]); - JGlobalID_Index1.push_back (JGlobalIDExtra[EdgeDonor]); + Xcoord_Index1.push_back(XcoordExtra[EdgeDonor]); + Ycoord_Index1.push_back(YcoordExtra[EdgeDonor]); + Zcoord_Index1.push_back(ZcoordExtra[EdgeDonor]); + Variable_Index1.push_back(VariableExtra[EdgeDonor]); + IGlobalID_Index1.push_back(IGlobalIDExtra[EdgeDonor]); + JGlobalID_Index1.push_back(JGlobalIDExtra[EdgeDonor]); AddExtra[EdgeDonor] = false; - } - } } else if (XcoordExtra.size() == 1) { - cout <<"There cutting system has failed, there is an incomplete curve (not used)." << endl; + cout << "There cutting system has failed, there is an incomplete curve (not used)." << endl; } /*--- Find and add the trailing edge to to the list and the contect the first point to the trailing edge ---*/ - Trailing_Point = 0; Trailing_Coord = Xcoord_Index0[0]; + Trailing_Point = 0; + Trailing_Coord = Xcoord_Index0[0]; for (iEdge = 1; iEdge < Xcoord_Index0.size(); iEdge++) { if (Xcoord_Index0[iEdge] > Trailing_Coord) { - Trailing_Point = iEdge; Trailing_Coord = Xcoord_Index0[iEdge]; + Trailing_Point = iEdge; + Trailing_Coord = Xcoord_Index0[iEdge]; } } @@ -2305,25 +2236,23 @@ void CGeometry::ComputeAirfoil_Section(su2double *Plane_P0, su2double *Plane_Nor IGlobalID_Airfoil.push_back(IGlobalID_Index1[Trailing_Point]); JGlobalID_Airfoil.push_back(JGlobalID_Index1[Trailing_Point]); - Xcoord_Index0.erase (Xcoord_Index0.begin() + Trailing_Point); - Ycoord_Index0.erase (Ycoord_Index0.begin() + Trailing_Point); - Zcoord_Index0.erase (Zcoord_Index0.begin() + Trailing_Point); - Variable_Index0.erase (Variable_Index0.begin() + Trailing_Point); - IGlobalID_Index0.erase (IGlobalID_Index0.begin() + Trailing_Point); - JGlobalID_Index0.erase (JGlobalID_Index0.begin() + Trailing_Point); - - Xcoord_Index1.erase (Xcoord_Index1.begin() + Trailing_Point); - Ycoord_Index1.erase (Ycoord_Index1.begin() + Trailing_Point); - Zcoord_Index1.erase (Zcoord_Index1.begin() + Trailing_Point); - Variable_Index1.erase (Variable_Index1.begin() + Trailing_Point); - IGlobalID_Index1.erase (IGlobalID_Index1.begin() + Trailing_Point); - JGlobalID_Index1.erase (JGlobalID_Index1.begin() + Trailing_Point); + Xcoord_Index0.erase(Xcoord_Index0.begin() + Trailing_Point); + Ycoord_Index0.erase(Ycoord_Index0.begin() + Trailing_Point); + Zcoord_Index0.erase(Zcoord_Index0.begin() + Trailing_Point); + Variable_Index0.erase(Variable_Index0.begin() + Trailing_Point); + IGlobalID_Index0.erase(IGlobalID_Index0.begin() + Trailing_Point); + JGlobalID_Index0.erase(JGlobalID_Index0.begin() + Trailing_Point); + Xcoord_Index1.erase(Xcoord_Index1.begin() + Trailing_Point); + Ycoord_Index1.erase(Ycoord_Index1.begin() + Trailing_Point); + Zcoord_Index1.erase(Zcoord_Index1.begin() + Trailing_Point); + Variable_Index1.erase(Variable_Index1.begin() + Trailing_Point); + IGlobalID_Index1.erase(IGlobalID_Index1.begin() + Trailing_Point); + JGlobalID_Index1.erase(JGlobalID_Index1.begin() + Trailing_Point); /*--- Algorithm for adding the rest of the points ---*/ do { - /*--- Last added point in the list ---*/ Airfoil_Point = Xcoord_Airfoil.size() - 1; @@ -2333,23 +2262,30 @@ void CGeometry::ComputeAirfoil_Section(su2double *Plane_P0, su2double *Plane_Nor Found_Edge = false; for (iEdge = 0; iEdge < Xcoord_Index0.size(); iEdge++) { - - if (((IGlobalID_Index0[iEdge] == IGlobalID_Airfoil[Airfoil_Point]) && (JGlobalID_Index0[iEdge] == JGlobalID_Airfoil[Airfoil_Point])) || - ((IGlobalID_Index0[iEdge] == JGlobalID_Airfoil[Airfoil_Point]) && (JGlobalID_Index0[iEdge] == IGlobalID_Airfoil[Airfoil_Point]))) { - Next_Edge = iEdge; Found_Edge = true; Index = 0; break; + if (((IGlobalID_Index0[iEdge] == IGlobalID_Airfoil[Airfoil_Point]) && + (JGlobalID_Index0[iEdge] == JGlobalID_Airfoil[Airfoil_Point])) || + ((IGlobalID_Index0[iEdge] == JGlobalID_Airfoil[Airfoil_Point]) && + (JGlobalID_Index0[iEdge] == IGlobalID_Airfoil[Airfoil_Point]))) { + Next_Edge = iEdge; + Found_Edge = true; + Index = 0; + break; } - if (((IGlobalID_Index1[iEdge] == IGlobalID_Airfoil[Airfoil_Point]) && (JGlobalID_Index1[iEdge] == JGlobalID_Airfoil[Airfoil_Point])) || - ((IGlobalID_Index1[iEdge] == JGlobalID_Airfoil[Airfoil_Point]) && (JGlobalID_Index1[iEdge] == IGlobalID_Airfoil[Airfoil_Point]))) { - Next_Edge = iEdge; Found_Edge = true; Index = 1; break; + if (((IGlobalID_Index1[iEdge] == IGlobalID_Airfoil[Airfoil_Point]) && + (JGlobalID_Index1[iEdge] == JGlobalID_Airfoil[Airfoil_Point])) || + ((IGlobalID_Index1[iEdge] == JGlobalID_Airfoil[Airfoil_Point]) && + (JGlobalID_Index1[iEdge] == IGlobalID_Airfoil[Airfoil_Point]))) { + Next_Edge = iEdge; + Found_Edge = true; + Index = 1; + break; } - } /*--- Add and remove the next point to the list and the next point in the edge ---*/ if (Found_Edge) { - if (Index == 0) { Xcoord_Airfoil.push_back(Xcoord_Index1[Next_Edge]); Ycoord_Airfoil.push_back(Ycoord_Index1[Next_Edge]); @@ -2382,36 +2318,43 @@ void CGeometry::ComputeAirfoil_Section(su2double *Plane_P0, su2double *Plane_Nor IGlobalID_Index1.erase(IGlobalID_Index1.begin() + Next_Edge); JGlobalID_Index1.erase(JGlobalID_Index1.begin() + Next_Edge); + } else { + break; } - else { break; } } while (Xcoord_Index0.size() != 0); /*--- Clean the vector before using them again for storing the upper or the lower side ---*/ - Xcoord_Index0.clear(); Ycoord_Index0.clear(); Zcoord_Index0.clear(); Variable_Index0.clear(); IGlobalID_Index0.clear(); JGlobalID_Index0.clear(); - Xcoord_Index1.clear(); Ycoord_Index1.clear(); Zcoord_Index1.clear(); Variable_Index1.clear(); IGlobalID_Index1.clear(); JGlobalID_Index1.clear(); - + Xcoord_Index0.clear(); + Ycoord_Index0.clear(); + Zcoord_Index0.clear(); + Variable_Index0.clear(); + IGlobalID_Index0.clear(); + JGlobalID_Index0.clear(); + Xcoord_Index1.clear(); + Ycoord_Index1.clear(); + Zcoord_Index1.clear(); + Variable_Index1.clear(); + IGlobalID_Index1.clear(); + JGlobalID_Index1.clear(); } - } AD::EndPassive(wasActive); - } void CGeometry::RegisterCoordinates() const { const bool input = true; - SU2_OMP_FOR_STAT(roundUpDiv(nPoint,omp_get_num_threads())) + SU2_OMP_FOR_STAT(roundUpDiv(nPoint, omp_get_num_threads())) for (auto iPoint = 0ul; iPoint < nPoint; iPoint++) { nodes->RegisterCoordinates(iPoint, input); } END_SU2_OMP_FOR } -void CGeometry::UpdateGeometry(CGeometry **geometry_container, CConfig *config) { - +void CGeometry::UpdateGeometry(CGeometry** geometry_container, CConfig* config) { geometry_container[MESH_0]->InitiateComms(geometry_container[MESH_0], config, COORDINATES); geometry_container[MESH_0]->CompleteComms(geometry_container[MESH_0], config, COORDINATES); @@ -2422,18 +2365,16 @@ void CGeometry::UpdateGeometry(CGeometry **geometry_container, CConfig *config) for (unsigned short iMesh = 1; iMesh <= config->GetnMGLevels(); iMesh++) { /*--- Update the control volume structures ---*/ - geometry_container[iMesh]->SetControlVolume(geometry_container[iMesh-1], UPDATE); - geometry_container[iMesh]->SetBoundControlVolume(geometry_container[iMesh-1], UPDATE); - geometry_container[iMesh]->SetCoord(geometry_container[iMesh-1]); - + geometry_container[iMesh]->SetControlVolume(geometry_container[iMesh - 1], UPDATE); + geometry_container[iMesh]->SetBoundControlVolume(geometry_container[iMesh - 1], UPDATE); + geometry_container[iMesh]->SetCoord(geometry_container[iMesh - 1]); } /*--- Compute the global surface areas for all markers. ---*/ geometry_container[MESH_0]->ComputeSurfaceAreaCfgFile(config); } -void CGeometry::SetCustomBoundary(CConfig *config) { - +void CGeometry::SetCustomBoundary(CConfig* config) { unsigned short iMarker; unsigned long iVertex; string Marker_Tag; @@ -2443,21 +2384,21 @@ void CGeometry::SetCustomBoundary(CConfig *config) { CustomBoundaryTemperature = new su2double*[nMarker]; CustomBoundaryHeatFlux = new su2double*[nMarker]; - for(iMarker=0; iMarker < nMarker; iMarker++){ + for (iMarker = 0; iMarker < nMarker; iMarker++) { Marker_Tag = config->GetMarker_All_TagBound(iMarker); CustomBoundaryHeatFlux[iMarker] = nullptr; CustomBoundaryTemperature[iMarker] = nullptr; - if(config->GetMarker_All_PyCustom(iMarker)){ - switch(config->GetMarker_All_KindBC(iMarker)){ + if (config->GetMarker_All_PyCustom(iMarker)) { + switch (config->GetMarker_All_KindBC(iMarker)) { case HEAT_FLUX: CustomBoundaryHeatFlux[iMarker] = new su2double[nVertex[iMarker]]; - for(iVertex=0; iVertex < nVertex[iMarker]; iVertex++){ + for (iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { CustomBoundaryHeatFlux[iMarker][iVertex] = config->GetWall_HeatFlux(Marker_Tag); } break; case ISOTHERMAL: CustomBoundaryTemperature[iMarker] = new su2double[nVertex[iMarker]]; - for(iVertex=0; iVertex < nVertex[iMarker]; iVertex++){ + for (iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { CustomBoundaryTemperature[iMarker][iVertex] = config->GetIsothermal_Temperature(Marker_Tag); } break; @@ -2470,19 +2411,17 @@ void CGeometry::SetCustomBoundary(CConfig *config) { } } } - } -void CGeometry::UpdateCustomBoundaryConditions(CGeometry **geometry_container, CConfig *config){ - +void CGeometry::UpdateCustomBoundaryConditions(CGeometry** geometry_container, CConfig* config) { unsigned short iMGfine, iMGlevel, nMGlevel, iMarker; nMGlevel = config->GetnMGLevels(); - for (iMGlevel=1; iMGlevel <= nMGlevel; iMGlevel++){ - iMGfine = iMGlevel-1; - for(iMarker = 0; iMarker< config->GetnMarker_All(); iMarker++){ - if(config->GetMarker_All_PyCustom(iMarker)){ - switch(config->GetMarker_All_KindBC(iMarker)){ + for (iMGlevel = 1; iMGlevel <= nMGlevel; iMGlevel++) { + iMGfine = iMGlevel - 1; + for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { + if (config->GetMarker_All_PyCustom(iMarker)) { + switch (config->GetMarker_All_KindBC(iMarker)) { case HEAT_FLUX: geometry_container[iMGlevel]->SetMultiGridWallHeatFlux(geometry_container[iMGfine], iMarker); break; @@ -2490,85 +2429,71 @@ void CGeometry::UpdateCustomBoundaryConditions(CGeometry **geometry_container, C geometry_container[iMGlevel]->SetMultiGridWallTemperature(geometry_container[iMGfine], iMarker); break; // Inlet flow handled in solver class. - default: break; + default: + break; } } } } } -void CGeometry::ComputeSurfaceAreaCfgFile(const CConfig *config) { - SU2_OMP_MASTER - { - const auto nMarker_Global = config->GetnMarker_CfgFile(); - SurfaceAreaCfgFile.resize(nMarker_Global); - vector LocalSurfaceArea(nMarker_Global, 0.0); - - /*--- Loop over all local markers ---*/ - for (unsigned short iMarker = 0; iMarker < nMarker; iMarker++) { - - const auto Local_TagBound = config->GetMarker_All_TagBound(iMarker); - - /*--- Loop over all global markers, and find the local-global pair via - matching unique string tags. ---*/ - for (unsigned short iMarker_Global = 0; iMarker_Global < nMarker_Global; iMarker_Global++) { - - const auto Global_TagBound = config->GetMarker_CfgFile_TagBound(iMarker_Global); - if (Local_TagBound == Global_TagBound) { +void CGeometry::ComputeSurfaceAreaCfgFile(const CConfig* config){ + SU2_OMP_MASTER{const auto nMarker_Global = config->GetnMarker_CfgFile(); +SurfaceAreaCfgFile.resize(nMarker_Global); +vector LocalSurfaceArea(nMarker_Global, 0.0); - for(auto iVertex = 0ul; iVertex < nVertex[iMarker]; iVertex++ ) { +/*--- Loop over all local markers ---*/ +for (unsigned short iMarker = 0; iMarker < nMarker; iMarker++) { + const auto Local_TagBound = config->GetMarker_All_TagBound(iMarker); - const auto iPoint = vertex[iMarker][iVertex]->GetNode(); + /*--- Loop over all global markers, and find the local-global pair via + matching unique string tags. ---*/ + for (unsigned short iMarker_Global = 0; iMarker_Global < nMarker_Global; iMarker_Global++) { + const auto Global_TagBound = config->GetMarker_CfgFile_TagBound(iMarker_Global); + if (Local_TagBound == Global_TagBound) { + for (auto iVertex = 0ul; iVertex < nVertex[iMarker]; iVertex++) { + const auto iPoint = vertex[iMarker][iVertex]->GetNode(); - if(!nodes->GetDomain(iPoint)) continue; + if (!nodes->GetDomain(iPoint)) continue; - const auto AreaNormal = vertex[iMarker][iVertex]->GetNormal(); - const auto Area = GeometryToolbox::Norm(nDim, AreaNormal); + const auto AreaNormal = vertex[iMarker][iVertex]->GetNormal(); + const auto Area = GeometryToolbox::Norm(nDim, AreaNormal); - LocalSurfaceArea[iMarker_Global] += Area; - }// for iVertex - }//if Local == Global - }//for iMarker_Global - }//for iMarker + LocalSurfaceArea[iMarker_Global] += Area; + } // for iVertex + } // if Local == Global + } // for iMarker_Global +} // for iMarker - SU2_MPI::Allreduce(LocalSurfaceArea.data(), SurfaceAreaCfgFile.data(), SurfaceAreaCfgFile.size(), MPI_DOUBLE, MPI_SUM, SU2_MPI::GetComm()); - } END_SU2_OMP_MASTER +SU2_MPI::Allreduce(LocalSurfaceArea.data(), SurfaceAreaCfgFile.data(), SurfaceAreaCfgFile.size(), MPI_DOUBLE, MPI_SUM, + SU2_MPI::GetComm()); +} +END_SU2_OMP_MASTER } -su2double CGeometry::GetSurfaceArea(const CConfig *config, unsigned short val_marker) const { +su2double CGeometry::GetSurfaceArea(const CConfig* config, unsigned short val_marker) const { /*---Find the precomputed marker surface area by local-global string-matching. ---*/ const auto Marker_Tag = config->GetMarker_All_TagBound(val_marker); for (unsigned short iMarker_Global = 0; iMarker_Global < config->GetnMarker_CfgFile(); iMarker_Global++) { - const auto Global_TagBound = config->GetMarker_CfgFile_TagBound(iMarker_Global); - if (Marker_Tag == Global_TagBound) - return SurfaceAreaCfgFile[iMarker_Global]; - + if (Marker_Tag == Global_TagBound) return SurfaceAreaCfgFile[iMarker_Global]; } SU2_MPI::Error("Unable to match local-marker with cfg-marker for Surface Area.", CURRENT_FUNCTION); return 0.0; } -void CGeometry::ComputeSurf_Straightness(CConfig *config, - bool print_on_screen) { - +void CGeometry::ComputeSurf_Straightness(CConfig* config, bool print_on_screen) { bool RefUnitNormal_defined; - unsigned short iDim, - iMarker, - iMarker_Global, - nMarker_Global = config->GetnMarker_CfgFile(); + unsigned short iDim, iMarker, iMarker_Global, nMarker_Global = config->GetnMarker_CfgFile(); unsigned long iVertex; constexpr passivedouble epsilon = 1.0e-6; su2double Area; - string Local_TagBound, - Global_TagBound; + string Local_TagBound, Global_TagBound; - vector Normal(nDim), - UnitNormal(nDim), - RefUnitNormal(nDim); + vector Normal(nDim), UnitNormal(nDim), RefUnitNormal(nDim); /*--- Assume now that this boundary marker is straight. As soon as one AreaElement is found that is not aligend with a Reference then it is @@ -2584,7 +2509,6 @@ void CGeometry::ComputeSurf_Straightness(CConfig *config, /*--- Loop over all local markers ---*/ for (iMarker = 0; iMarker < nMarker; iMarker++) { - Local_TagBound = config->GetMarker_All_TagBound(iMarker); /*--- Marker has to be Symmetry or Euler. Additionally marker can't be a @@ -2592,62 +2516,53 @@ void CGeometry::ComputeSurf_Straightness(CConfig *config, other GridMovements are rigid. ---*/ if ((config->GetMarker_All_KindBC(iMarker) == SYMMETRY_PLANE || config->GetMarker_All_KindBC(iMarker) == EULER_WALL) && - !config->GetMarker_Moving_Bool(Local_TagBound) && - !config->GetMarker_Deform_Mesh_Bool(Local_TagBound)) { - + !config->GetMarker_Moving_Bool(Local_TagBound) && !config->GetMarker_Deform_Mesh_Bool(Local_TagBound)) { /*--- Loop over all global markers, and find the local-global pair via matching unique string tags. ---*/ for (iMarker_Global = 0; iMarker_Global < nMarker_Global; iMarker_Global++) { - Global_TagBound = config->GetMarker_CfgFile_TagBound(iMarker_Global); if (Local_TagBound == Global_TagBound) { - RefUnitNormal_defined = false; iVertex = 0; - while(bound_is_straight[iMarker] == true && - iVertex < nVertex[iMarker]) { - + while (bound_is_straight[iMarker] == true && iVertex < nVertex[iMarker]) { vertex[iMarker][iVertex]->GetNormal(Normal.data()); UnitNormal = Normal; /*--- Compute unit normal. ---*/ Area = 0.0; - for (iDim = 0; iDim < nDim; iDim++) - Area += Normal[iDim]*Normal[iDim]; + for (iDim = 0; iDim < nDim; iDim++) Area += Normal[iDim] * Normal[iDim]; Area = sqrt(Area); /*--- Negate for outward convention. ---*/ - for (iDim = 0; iDim < nDim; iDim++) - UnitNormal[iDim] /= -Area; + for (iDim = 0; iDim < nDim; iDim++) UnitNormal[iDim] /= -Area; /*--- Check if unit normal is within tolerance of the Reference unit normal. Reference unit normal = first unit normal found. ---*/ - if(RefUnitNormal_defined) { + if (RefUnitNormal_defined) { for (iDim = 0; iDim < nDim; iDim++) { - if( abs(RefUnitNormal[iDim] - UnitNormal[iDim]) > epsilon ) { + if (abs(RefUnitNormal[iDim] - UnitNormal[iDim]) > epsilon) { bound_is_straight[iMarker] = false; break; } } } else { - RefUnitNormal = UnitNormal; //deep copy of values + RefUnitNormal = UnitNormal; // deep copy of values RefUnitNormal_defined = true; } - iVertex++; - }//while iVertex - }//if Local == Global - }//for iMarker_Global + iVertex++; + } // while iVertex + } // if Local == Global + } // for iMarker_Global } else { /*--- Enforce default value: false ---*/ bound_is_straight[iMarker] = false; - }//if sym or euler ... - }//for iMarker + } // if sym or euler ... + } // for iMarker /*--- Communicate results and print on screen. ---*/ - if(print_on_screen) { - + if (print_on_screen) { /*--- Additional vector which can later be MPI::Allreduce(d) to pring the results on screen as nMarker (local) can vary across ranks. Default 'true' as it can happen that a local rank does not contain an element of each surface marker. ---*/ @@ -2658,65 +2573,60 @@ void CGeometry::ComputeSurf_Straightness(CConfig *config, for (iMarker_Global = 0; iMarker_Global < nMarker_Global; iMarker_Global++) { Global_TagBound = config->GetMarker_CfgFile_TagBound(iMarker_Global); - if(Local_TagBound == Global_TagBound) - bound_is_straight_Global[iMarker_Global] = bound_is_straight[iMarker]; + if (Local_TagBound == Global_TagBound) bound_is_straight_Global[iMarker_Global] = bound_is_straight[iMarker]; - }//for iMarker_Global - }//for iMarker + } // for iMarker_Global + } // for iMarker - vector Buff_Send_isStraight(nMarker_Global), - Buff_Recv_isStraight(nMarker_Global); + vector Buff_Send_isStraight(nMarker_Global), Buff_Recv_isStraight(nMarker_Global); /*--- Cast to int as std::vector can be a special construct. MPI handling using is more straight-forward. ---*/ for (iMarker_Global = 0; iMarker_Global < nMarker_Global; iMarker_Global++) - Buff_Send_isStraight[iMarker_Global] = static_cast (bound_is_straight_Global[iMarker_Global]); + Buff_Send_isStraight[iMarker_Global] = static_cast(bound_is_straight_Global[iMarker_Global]); /*--- Product of type (bool) is equivalnt to a 'logical and' ---*/ - SU2_MPI::Allreduce(Buff_Send_isStraight.data(), Buff_Recv_isStraight.data(), - nMarker_Global, MPI_INT, MPI_PROD, SU2_MPI::GetComm()); + SU2_MPI::Allreduce(Buff_Send_isStraight.data(), Buff_Recv_isStraight.data(), nMarker_Global, MPI_INT, MPI_PROD, + SU2_MPI::GetComm()); /*--- Print results on screen. ---*/ - if(rank == MASTER_NODE) { + if (rank == MASTER_NODE) { for (iMarker_Global = 0; iMarker_Global < nMarker_Global; iMarker_Global++) { if (config->GetMarker_CfgFile_KindBC(config->GetMarker_CfgFile_TagBound(iMarker_Global)) == SYMMETRY_PLANE || - config->GetMarker_CfgFile_KindBC(config->GetMarker_CfgFile_TagBound(iMarker_Global)) == EULER_WALL) { - + config->GetMarker_CfgFile_KindBC(config->GetMarker_CfgFile_TagBound(iMarker_Global)) == EULER_WALL) { cout << "Boundary marker " << config->GetMarker_CfgFile_TagBound(iMarker_Global) << " is"; - if(Buff_Recv_isStraight[iMarker_Global] == false) cout << " NOT"; - if(nDim == 2) cout << " a single straight." << endl; - if(nDim == 3) cout << " a single plane." << endl; - }//if sym or euler - }//for iMarker_Global - }//if rank==MASTER - }//if print_on_scren - + if (Buff_Recv_isStraight[iMarker_Global] == false) cout << " NOT"; + if (nDim == 2) cout << " a single straight." << endl; + if (nDim == 3) cout << " a single plane." << endl; + } // if sym or euler + } // for iMarker_Global + } // if rank==MASTER + } // if print_on_scren } - -void CGeometry::ComputeSurf_Curvature(CConfig *config) { - +void CGeometry::ComputeSurf_Curvature(CConfig* config) { unsigned short iMarker, iNeigh_Point, iDim, iNode, iNeighbor_Nodes, Neighbor_Node; - unsigned long Neighbor_Point, iVertex, iPoint, jPoint, iElem_Bound, iEdge, nLocalVertex, MaxLocalVertex , *Buffer_Send_nVertex, *Buffer_Receive_nVertex, TotalnPointDomain; + unsigned long Neighbor_Point, iVertex, iPoint, jPoint, iElem_Bound, iEdge, nLocalVertex, MaxLocalVertex, + *Buffer_Send_nVertex, *Buffer_Receive_nVertex, TotalnPointDomain; vector Point_NeighborList, Elem_NeighborList, Point_Triangle, Point_Edge, Point_Critical; - su2double U[3] = {0.0}, V[3] = {0.0}, W[3] = {0.0}, Length_U, Length_V, Length_W, CosValue, Angle_Value, *K, *Angle_Defect, *Area_Vertex, *Angle_Alpha, *Angle_Beta, **NormalMeanK, MeanK, GaussK, MaxPrinK, cot_alpha, cot_beta, delta, X1, X2, X3, Y1, Y2, Y3, radius, *Buffer_Send_Coord, *Buffer_Receive_Coord, *Coord, Dist, MinDist, MaxK, MinK, SigmaK; - bool *Check_Edge; + su2double U[3] = {0.0}, V[3] = {0.0}, W[3] = {0.0}, Length_U, Length_V, Length_W, CosValue, Angle_Value, *K, + *Angle_Defect, *Area_Vertex, *Angle_Alpha, *Angle_Beta, **NormalMeanK, MeanK, GaussK, MaxPrinK, cot_alpha, + cot_beta, delta, X1, X2, X3, Y1, Y2, Y3, radius, *Buffer_Send_Coord, *Buffer_Receive_Coord, *Coord, Dist, + MinDist, MaxK, MinK, SigmaK; + bool* Check_Edge; /*--- Allocate surface curvature ---*/ - K = new su2double [nPoint]; + K = new su2double[nPoint]; for (iPoint = 0; iPoint < nPoint; iPoint++) K[iPoint] = 0.0; if (nDim == 2) { - /*--- Loop over all the markers ---*/ for (iMarker = 0; iMarker < nMarker; iMarker++) { - if (config->GetMarker_All_KindBC(iMarker) != SEND_RECEIVE) { - /*--- Loop through all marker vertices again, this time also finding the neighbors of each node.---*/ for (iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { - iPoint = vertex[iMarker][iVertex]->GetNode(); + iPoint = vertex[iMarker][iVertex]->GetNode(); if (nodes->GetDomain(iPoint)) { /*--- Loop through neighbors. In 2-D, there should be 2 nodes on either @@ -2731,11 +2641,9 @@ void CGeometry::ComputeSurf_Curvature(CConfig *config) { if (nodes->GetPhysicalBoundary(Neighbor_Point)) { Point_Edge.push_back(Neighbor_Point); } - } if (Point_Edge.size() == 2) { - /*--- Compute the curvature using three points ---*/ X1 = nodes->GetCoord(iPoint, 0); X2 = nodes->GetCoord(Point_Edge[0], 0); @@ -2744,46 +2652,41 @@ void CGeometry::ComputeSurf_Curvature(CConfig *config) { Y2 = nodes->GetCoord(Point_Edge[0], 1); Y3 = nodes->GetCoord(Point_Edge[1], 1); - radius = sqrt(((X2-X1)*(X2-X1) + (Y2-Y1)*(Y2-Y1))* - ((X2-X3)*(X2-X3) + (Y2-Y3)*(Y2-Y3))* - ((X3-X1)*(X3-X1) + (Y3-Y1)*(Y3-Y1)))/ - (2.0*fabs(X1*Y2+X2*Y3+X3*Y1-X1*Y3-X2*Y1-X3*Y2)+EPS); + radius = sqrt(((X2 - X1) * (X2 - X1) + (Y2 - Y1) * (Y2 - Y1)) * + ((X2 - X3) * (X2 - X3) + (Y2 - Y3) * (Y2 - Y3)) * + ((X3 - X1) * (X3 - X1) + (Y3 - Y1) * (Y3 - Y1))) / + (2.0 * fabs(X1 * Y2 + X2 * Y3 + X3 * Y1 - X1 * Y3 - X2 * Y1 - X3 * Y2) + EPS); - K[iPoint] = 1.0/radius; + K[iPoint] = 1.0 / radius; nodes->SetCurvature(iPoint, K[iPoint]); } - } - } - } - } } else { - - Angle_Defect = new su2double [nPoint]; - Area_Vertex = new su2double [nPoint]; + Angle_Defect = new su2double[nPoint]; + Area_Vertex = new su2double[nPoint]; for (iPoint = 0; iPoint < nPoint; iPoint++) { - Angle_Defect[iPoint] = 2*PI_NUMBER; + Angle_Defect[iPoint] = 2 * PI_NUMBER; Area_Vertex[iPoint] = 0.0; } - Angle_Alpha = new su2double [nEdge]; - Angle_Beta = new su2double [nEdge]; - Check_Edge = new bool [nEdge]; + Angle_Alpha = new su2double[nEdge]; + Angle_Beta = new su2double[nEdge]; + Check_Edge = new bool[nEdge]; for (iEdge = 0; iEdge < nEdge; iEdge++) { Angle_Alpha[iEdge] = 0.0; Angle_Beta[iEdge] = 0.0; Check_Edge[iEdge] = true; } - NormalMeanK = new su2double *[nPoint]; + NormalMeanK = new su2double*[nPoint]; for (iPoint = 0; iPoint < nPoint; iPoint++) { - NormalMeanK[iPoint] = new su2double [nDim]; + NormalMeanK[iPoint] = new su2double[nDim]; for (iDim = 0; iDim < nDim; iDim++) { NormalMeanK[iPoint][iDim] = 0.0; } @@ -2791,23 +2694,19 @@ void CGeometry::ComputeSurf_Curvature(CConfig *config) { /*--- Loop over all the markers ---*/ for (iMarker = 0; iMarker < nMarker; iMarker++) { - if (config->GetMarker_All_KindBC(iMarker) != SEND_RECEIVE) { - /*--- Loop over all the boundary elements ---*/ for (iElem_Bound = 0; iElem_Bound < nElem_Bound[iMarker]; iElem_Bound++) { - /*--- Only triangles ---*/ if (bound[iMarker][iElem_Bound]->GetVTK_Type() == TRIANGLE) { - /*--- Loop over all the nodes of the boundary element ---*/ for (iNode = 0; iNode < bound[iMarker][iElem_Bound]->GetnNodes(); iNode++) { - iPoint = bound[iMarker][iElem_Bound]->GetNode(iNode); Point_Triangle.clear(); - for (iNeighbor_Nodes = 0; iNeighbor_Nodes < bound[iMarker][iElem_Bound]->GetnNeighbor_Nodes(iNode); iNeighbor_Nodes++) { + for (iNeighbor_Nodes = 0; iNeighbor_Nodes < bound[iMarker][iElem_Bound]->GetnNeighbor_Nodes(iNode); + iNeighbor_Nodes++) { Neighbor_Node = bound[iMarker][iElem_Bound]->GetNeighbor_Nodes(iNode, iNeighbor_Nodes); Neighbor_Point = bound[iMarker][iElem_Bound]->GetNode(Neighbor_Node); Point_Triangle.push_back(Neighbor_Point); @@ -2820,21 +2719,37 @@ void CGeometry::ComputeSurf_Curvature(CConfig *config) { V[iDim] = nodes->GetCoord(Point_Triangle[1], iDim) - nodes->GetCoord(iPoint, iDim); } - W[0] = 0.5*(U[1]*V[2]-U[2]*V[1]); W[1] = -0.5*(U[0]*V[2]-U[2]*V[0]); W[2] = 0.5*(U[0]*V[1]-U[1]*V[0]); + W[0] = 0.5 * (U[1] * V[2] - U[2] * V[1]); + W[1] = -0.5 * (U[0] * V[2] - U[2] * V[0]); + W[2] = 0.5 * (U[0] * V[1] - U[1] * V[0]); - Length_U = 0.0; Length_V = 0.0; Length_W = 0.0; CosValue = 0.0; - for (iDim = 0; iDim < nDim; iDim++) { Length_U += U[iDim]*U[iDim]; Length_V += V[iDim]*V[iDim]; Length_W += W[iDim]*W[iDim]; } - Length_U = sqrt(Length_U); Length_V = sqrt(Length_V); Length_W = sqrt(Length_W); - for (iDim = 0; iDim < nDim; iDim++) { U[iDim] /= Length_U; V[iDim] /= Length_V; CosValue += U[iDim]*V[iDim]; } + Length_U = 0.0; + Length_V = 0.0; + Length_W = 0.0; + CosValue = 0.0; + for (iDim = 0; iDim < nDim; iDim++) { + Length_U += U[iDim] * U[iDim]; + Length_V += V[iDim] * V[iDim]; + Length_W += W[iDim] * W[iDim]; + } + Length_U = sqrt(Length_U); + Length_V = sqrt(Length_V); + Length_W = sqrt(Length_W); + for (iDim = 0; iDim < nDim; iDim++) { + U[iDim] /= Length_U; + V[iDim] /= Length_V; + CosValue += U[iDim] * V[iDim]; + } if (CosValue >= 1.0) CosValue = 1.0; if (CosValue <= -1.0) CosValue = -1.0; Angle_Value = acos(CosValue); Area_Vertex[iPoint] += Length_W; Angle_Defect[iPoint] -= Angle_Value; - if (Angle_Alpha[iEdge] == 0.0) Angle_Alpha[iEdge] = Angle_Value; - else Angle_Beta[iEdge] = Angle_Value; - + if (Angle_Alpha[iEdge] == 0.0) + Angle_Alpha[iEdge] = Angle_Value; + else + Angle_Beta[iEdge] = Angle_Value; } } } @@ -2849,26 +2764,37 @@ void CGeometry::ComputeSurf_Curvature(CConfig *config) { for (iNode = 0; iNode < bound[iMarker][iElem_Bound]->GetnNodes(); iNode++) { iPoint = bound[iMarker][iElem_Bound]->GetNode(iNode); - for (iNeighbor_Nodes = 0; iNeighbor_Nodes < bound[iMarker][iElem_Bound]->GetnNeighbor_Nodes(iNode); iNeighbor_Nodes++) { + for (iNeighbor_Nodes = 0; iNeighbor_Nodes < bound[iMarker][iElem_Bound]->GetnNeighbor_Nodes(iNode); + iNeighbor_Nodes++) { Neighbor_Node = bound[iMarker][iElem_Bound]->GetNeighbor_Nodes(iNode, iNeighbor_Nodes); jPoint = bound[iMarker][iElem_Bound]->GetNode(Neighbor_Node); iEdge = FindEdge(iPoint, jPoint); if (Check_Edge[iEdge]) { - Check_Edge[iEdge] = false; - if (tan(Angle_Alpha[iEdge]) != 0.0) cot_alpha = 1.0/tan(Angle_Alpha[iEdge]); else cot_alpha = 0.0; - if (tan(Angle_Beta[iEdge]) != 0.0) cot_beta = 1.0/tan(Angle_Beta[iEdge]); else cot_beta = 0.0; + if (tan(Angle_Alpha[iEdge]) != 0.0) + cot_alpha = 1.0 / tan(Angle_Alpha[iEdge]); + else + cot_alpha = 0.0; + if (tan(Angle_Beta[iEdge]) != 0.0) + cot_beta = 1.0 / tan(Angle_Beta[iEdge]); + else + cot_beta = 0.0; /*--- iPoint, and jPoint ---*/ for (iDim = 0; iDim < nDim; iDim++) { - if (Area_Vertex[iPoint] != 0.0) NormalMeanK[iPoint][iDim] += 3.0 * (cot_alpha + cot_beta) * (nodes->GetCoord(iPoint, iDim) - nodes->GetCoord(jPoint, iDim)) / Area_Vertex[iPoint]; - if (Area_Vertex[jPoint] != 0.0) NormalMeanK[jPoint][iDim] += 3.0 * (cot_alpha + cot_beta) * (nodes->GetCoord(jPoint, iDim) - nodes->GetCoord(iPoint, iDim)) / Area_Vertex[jPoint]; + if (Area_Vertex[iPoint] != 0.0) + NormalMeanK[iPoint][iDim] += 3.0 * (cot_alpha + cot_beta) * + (nodes->GetCoord(iPoint, iDim) - nodes->GetCoord(jPoint, iDim)) / + Area_Vertex[iPoint]; + if (Area_Vertex[jPoint] != 0.0) + NormalMeanK[jPoint][iDim] += 3.0 * (cot_alpha + cot_beta) * + (nodes->GetCoord(jPoint, iDim) - nodes->GetCoord(iPoint, iDim)) / + Area_Vertex[jPoint]; } } - } } } @@ -2882,19 +2808,19 @@ void CGeometry::ComputeSurf_Curvature(CConfig *config) { for (iMarker = 0; iMarker < nMarker; iMarker++) { if (config->GetMarker_All_KindBC(iMarker) != SEND_RECEIVE) { for (iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { - iPoint = vertex[iMarker][iVertex]->GetNode(); + iPoint = vertex[iMarker][iVertex]->GetNode(); if (nodes->GetDomain(iPoint)) { - - if (Area_Vertex[iPoint] != 0.0) GaussK = 3.0*Angle_Defect[iPoint]/Area_Vertex[iPoint]; - else GaussK = 0.0; + if (Area_Vertex[iPoint] != 0.0) + GaussK = 3.0 * Angle_Defect[iPoint] / Area_Vertex[iPoint]; + else + GaussK = 0.0; MeanK = 0.0; - for (iDim = 0; iDim < nDim; iDim++) - MeanK += NormalMeanK[iPoint][iDim]*NormalMeanK[iPoint][iDim]; + for (iDim = 0; iDim < nDim; iDim++) MeanK += NormalMeanK[iPoint][iDim] * NormalMeanK[iPoint][iDim]; MeanK = sqrt(MeanK); - delta = max((MeanK*MeanK - GaussK), 0.0); + delta = max((MeanK * MeanK - GaussK), 0.0); MaxPrinK = MeanK + sqrt(delta); @@ -2902,31 +2828,31 @@ void CGeometry::ComputeSurf_Curvature(CConfig *config) { K[iPoint] = MaxPrinK; nodes->SetCurvature(iPoint, K[iPoint]); } - } } } - delete [] Angle_Defect; - delete [] Area_Vertex; - delete [] Angle_Alpha; - delete [] Angle_Beta; - delete [] Check_Edge; - - for (iPoint = 0; iPoint < nPoint; iPoint++) - delete [] NormalMeanK[iPoint]; - delete [] NormalMeanK; + delete[] Angle_Defect; + delete[] Area_Vertex; + delete[] Angle_Alpha; + delete[] Angle_Beta; + delete[] Check_Edge; + for (iPoint = 0; iPoint < nPoint; iPoint++) delete[] NormalMeanK[iPoint]; + delete[] NormalMeanK; } /*--- Sharp edge detection is based in the statistical distribution of the curvature ---*/ - MaxK = K[0]; MinK = K[0]; MeanK = 0.0; TotalnPointDomain = 0; + MaxK = K[0]; + MinK = K[0]; + MeanK = 0.0; + TotalnPointDomain = 0; for (iMarker = 0; iMarker < nMarker; iMarker++) { if (config->GetMarker_All_KindBC(iMarker) != SEND_RECEIVE) { for (iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { - iPoint = vertex[iMarker][iVertex]->GetNode(); + iPoint = vertex[iMarker][iVertex]->GetNode(); if (nodes->GetDomain(iPoint)) { MaxK = max(MaxK, fabs(K[iPoint])); MinK = min(MinK, fabs(K[iPoint])); @@ -2937,9 +2863,12 @@ void CGeometry::ComputeSurf_Curvature(CConfig *config) { } } - su2double MyMeanK = MeanK; MeanK = 0.0; - su2double MyMaxK = MaxK; MaxK = 0.0; - unsigned long MynPointDomain = TotalnPointDomain; TotalnPointDomain = 0; + su2double MyMeanK = MeanK; + MeanK = 0.0; + su2double MyMaxK = MaxK; + MaxK = 0.0; + unsigned long MynPointDomain = TotalnPointDomain; + TotalnPointDomain = 0; SU2_MPI::Allreduce(&MyMeanK, &MeanK, 1, MPI_DOUBLE, MPI_SUM, SU2_MPI::GetComm()); SU2_MPI::Allreduce(&MyMaxK, &MaxK, 1, MPI_DOUBLE, MPI_MAX, SU2_MPI::GetComm()); SU2_MPI::Allreduce(&MynPointDomain, &TotalnPointDomain, 1, MPI_UNSIGNED_LONG, MPI_SUM, SU2_MPI::GetComm()); @@ -2952,7 +2881,7 @@ void CGeometry::ComputeSurf_Curvature(CConfig *config) { for (iMarker = 0; iMarker < nMarker; iMarker++) { if (config->GetMarker_All_KindBC(iMarker) != SEND_RECEIVE) { for (iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { - iPoint = vertex[iMarker][iVertex]->GetNode(); + iPoint = vertex[iMarker][iVertex]->GetNode(); if (nodes->GetDomain(iPoint)) { SigmaK += (fabs(K[iPoint]) - MeanK) * (fabs(K[iPoint]) - MeanK); } @@ -2960,10 +2889,11 @@ void CGeometry::ComputeSurf_Curvature(CConfig *config) { } } - su2double MySigmaK = SigmaK; SigmaK = 0.0; + su2double MySigmaK = SigmaK; + SigmaK = 0.0; SU2_MPI::Allreduce(&MySigmaK, &SigmaK, 1, MPI_DOUBLE, MPI_SUM, SU2_MPI::GetComm()); - SigmaK = sqrt(SigmaK/su2double(TotalnPointDomain)); + SigmaK = sqrt(SigmaK / su2double(TotalnPointDomain)); if (rank == MASTER_NODE) cout << "Max K: " << MaxK << ". Mean K: " << MeanK << ". Standard deviation K: " << SigmaK << "." << endl; @@ -2973,9 +2903,9 @@ void CGeometry::ComputeSurf_Curvature(CConfig *config) { for (iMarker = 0; iMarker < nMarker; iMarker++) { if (config->GetMarker_All_KindBC(iMarker) != SEND_RECEIVE) { for (iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { - iPoint = vertex[iMarker][iVertex]->GetNode(); + iPoint = vertex[iMarker][iVertex]->GetNode(); if (nodes->GetDomain(iPoint)) { - if (fabs(K[iPoint]) > MeanK + config->GetRefSharpEdges()*SigmaK) { + if (fabs(K[iPoint]) > MeanK + config->GetRefSharpEdges() * SigmaK) { Point_Critical.push_back(iPoint); } } @@ -2985,8 +2915,8 @@ void CGeometry::ComputeSurf_Curvature(CConfig *config) { /*--- Variables and buffers needed for MPI ---*/ - Buffer_Send_nVertex = new unsigned long [1]; - Buffer_Receive_nVertex = new unsigned long [size]; + Buffer_Send_nVertex = new unsigned long[1]; + Buffer_Receive_nVertex = new unsigned long[size]; /*--- Count the total number of critical edge nodes. ---*/ @@ -2997,25 +2927,26 @@ void CGeometry::ComputeSurf_Curvature(CConfig *config) { MaxLocalVertex = 0; SU2_MPI::Allreduce(&nLocalVertex, &MaxLocalVertex, 1, MPI_UNSIGNED_LONG, MPI_MAX, SU2_MPI::GetComm()); - SU2_MPI::Allgather(Buffer_Send_nVertex, 1, MPI_UNSIGNED_LONG, Buffer_Receive_nVertex, 1, MPI_UNSIGNED_LONG, SU2_MPI::GetComm()); + SU2_MPI::Allgather(Buffer_Send_nVertex, 1, MPI_UNSIGNED_LONG, Buffer_Receive_nVertex, 1, MPI_UNSIGNED_LONG, + SU2_MPI::GetComm()); /*--- Create and initialize to zero some buffers to hold the coordinates of the boundary nodes that are communicated from each partition (all-to-all). ---*/ - const unsigned long nBuffer = MaxLocalVertex*nDim; - Buffer_Send_Coord = new su2double [nBuffer] (); - Buffer_Receive_Coord = new su2double [size*nBuffer]; + const unsigned long nBuffer = MaxLocalVertex * nDim; + Buffer_Send_Coord = new su2double[nBuffer](); + Buffer_Receive_Coord = new su2double[size * nBuffer]; /*--- Retrieve and store the coordinates of the sharp edges boundary nodes on the local partition and broadcast them to all partitions. ---*/ for (iVertex = 0; iVertex < Point_Critical.size(); iVertex++) { iPoint = Point_Critical[iVertex]; - for (iDim = 0; iDim < nDim; iDim++) - Buffer_Send_Coord[iVertex*nDim+iDim] = nodes->GetCoord(iPoint, iDim); + for (iDim = 0; iDim < nDim; iDim++) Buffer_Send_Coord[iVertex * nDim + iDim] = nodes->GetCoord(iPoint, iDim); } - SU2_MPI::Allgather(Buffer_Send_Coord, nBuffer, MPI_DOUBLE, Buffer_Receive_Coord, nBuffer, MPI_DOUBLE, SU2_MPI::GetComm()); + SU2_MPI::Allgather(Buffer_Send_Coord, nBuffer, MPI_DOUBLE, Buffer_Receive_Coord, nBuffer, MPI_DOUBLE, + SU2_MPI::GetComm()); /*--- Loop over all interior mesh nodes on the local partition and compute the distances to each of the no-slip boundary nodes in the entire mesh. @@ -3029,11 +2960,13 @@ void CGeometry::ComputeSurf_Curvature(CConfig *config) { for (iVertex = 0; iVertex < Buffer_Receive_nVertex[iProcessor]; iVertex++) { Dist = 0.0; for (iDim = 0; iDim < nDim; iDim++) { - Dist += (Coord[iDim]-Buffer_Receive_Coord[(iProcessor*MaxLocalVertex+iVertex)*nDim+iDim])* - (Coord[iDim]-Buffer_Receive_Coord[(iProcessor*MaxLocalVertex+iVertex)*nDim+iDim]); + Dist += (Coord[iDim] - Buffer_Receive_Coord[(iProcessor * MaxLocalVertex + iVertex) * nDim + iDim]) * + (Coord[iDim] - Buffer_Receive_Coord[(iProcessor * MaxLocalVertex + iVertex) * nDim + iDim]); } - if (Dist!=0.0) Dist = sqrt(Dist); - else Dist = 0.0; + if (Dist != 0.0) + Dist = sqrt(Dist); + else + Dist = 0.0; if (Dist < MinDist) MinDist = Dist; } } @@ -3048,14 +2981,11 @@ void CGeometry::ComputeSurf_Curvature(CConfig *config) { delete[] Buffer_Receive_Coord; delete[] Buffer_Send_nVertex; delete[] Buffer_Receive_nVertex; - } -void CGeometry::FilterValuesAtElementCG(const vector &filter_radius, - const vector > &kernels, - const unsigned short search_limit, - su2double *values) const -{ +void CGeometry::FilterValuesAtElementCG(const vector& filter_radius, + const vector>& kernels, + const unsigned short search_limit, su2double* values) const { /*--- Apply a filter to "input_values". The filter is an averaging process over the neighbourhood of each element, which is a circle in 2D and a sphere in 3D of radius "filter_radius". The filter is characterized by its kernel, i.e. how the weights are computed. Multiple kernels @@ -3063,246 +2993,239 @@ void CGeometry::FilterValuesAtElementCG(const vector &filter_radius, output values of the previous filter. ---*/ /*--- Check if we need to do any work. ---*/ - if ( kernels.empty() ) return; - + if (kernels.empty()) return; /*--- FIRST: Gather the adjacency matrix, element centroids, volumes, and values on every processor, this is required because the filter reaches far into adjacent partitions. ---*/ /*--- Adjacency matrix ---*/ vector neighbour_start; - long *neighbour_idx = nullptr; - GetGlobalElementAdjacencyMatrix(neighbour_start,neighbour_idx); + long* neighbour_idx = nullptr; + GetGlobalElementAdjacencyMatrix(neighbour_start, neighbour_idx); /*--- Element centroids and volumes. ---*/ - su2double *cg_elem = new su2double [Global_nElemDomain*nDim], - *vol_elem = new su2double [Global_nElemDomain]; + su2double *cg_elem = new su2double[Global_nElemDomain * nDim], *vol_elem = new su2double[Global_nElemDomain]; #ifdef HAVE_MPI /*--- Number of subdomain each point is part of. ---*/ vector halo_detect(Global_nElemDomain); #endif /*--- Inputs of a filter stage, like with CG and volumes, each processor needs to see everything. ---*/ - su2double *work_values = new su2double [Global_nElemDomain]; + su2double* work_values = new su2double[Global_nElemDomain]; /*--- When gathering the neighborhood of each element we use a vector of booleans to indicate whether an element is already added to the list of neighbors (one vector per thread). ---*/ - vector > is_neighbor(omp_get_max_threads()); + vector> is_neighbor(omp_get_max_threads()); /*--- Begin OpenMP parallel section, count total number of searches for which the recursion limit is reached and the full neighborhood is not considered. ---*/ unsigned long limited_searches = 0; - SU2_OMP_PARALLEL_(reduction(+:limited_searches)) - { - - /*--- Initialize ---*/ - SU2_OMP_FOR_STAT(256) - for(auto iElem=0ul; iElemGetGlobalIndex(); - for(unsigned short iDim=0; iDimGetCG(iDim); - vol_elem[iElem_global] = elem[iElem]->GetVolume(); - } - END_SU2_OMP_FOR - -#ifdef HAVE_MPI - /*--- Account for the duplication introduced by the halo elements and the - reduction using MPI_SUM, which is required to maintain differentiabillity. ---*/ - SU2_OMP_FOR_STAT(256) - for(auto iElem=0ul; iElemGetGlobalIndex()] = 1; - END_SU2_OMP_FOR - - /*--- Share with all processors ---*/ - BEGIN_SU2_OMP_SAFE_GLOBAL_ACCESS - { - su2double* dbl_buffer = new su2double [Global_nElemDomain*nDim]; - SU2_MPI::Allreduce(cg_elem,dbl_buffer,Global_nElemDomain*nDim,MPI_DOUBLE,MPI_SUM,SU2_MPI::GetComm()); - swap(dbl_buffer, cg_elem); delete [] dbl_buffer; - - dbl_buffer = new su2double [Global_nElemDomain]; - SU2_MPI::Allreduce(vol_elem,dbl_buffer,Global_nElemDomain,MPI_DOUBLE,MPI_SUM,SU2_MPI::GetComm()); - swap(dbl_buffer, vol_elem); delete [] dbl_buffer; - - vector char_buffer(Global_nElemDomain); - MPI_Allreduce(halo_detect.data(),char_buffer.data(),Global_nElemDomain,MPI_CHAR,MPI_SUM,SU2_MPI::GetComm()); - halo_detect.swap(char_buffer); - } - END_SU2_OMP_SAFE_GLOBAL_ACCESS - - SU2_OMP_FOR_STAT(256) - for(auto iElem=0ul; iElemGetGlobalIndex()] = values[iElem]; + for (auto iElem = 0ul; iElem < nElem; ++iElem) { + auto iElem_global = elem[iElem]->GetGlobalIndex(); + for (unsigned short iDim = 0; iDim < nDim; ++iDim) cg_elem[nDim * iElem_global + iDim] = elem[iElem]->GetCG(iDim); + vol_elem[iElem_global] = elem[iElem]->GetVolume(); + } END_SU2_OMP_FOR #ifdef HAVE_MPI + /*--- Account for the duplication introduced by the halo elements and the + reduction using MPI_SUM, which is required to maintain differentiabillity. ---*/ + SU2_OMP_FOR_STAT(256) + for (auto iElem = 0ul; iElem < Global_nElemDomain; ++iElem) halo_detect[iElem] = 0; + END_SU2_OMP_FOR + + SU2_OMP_FOR_STAT(256) + for (auto iElem = 0ul; iElem < nElem; ++iElem) halo_detect[elem[iElem]->GetGlobalIndex()] = 1; + END_SU2_OMP_FOR + /*--- Share with all processors ---*/ - BEGIN_SU2_OMP_SAFE_GLOBAL_ACCESS - { - su2double *buffer = new su2double [Global_nElemDomain]; - SU2_MPI::Allreduce(work_values,buffer,Global_nElemDomain,MPI_DOUBLE,MPI_SUM,SU2_MPI::GetComm()); - swap(buffer, work_values); delete [] buffer; + BEGIN_SU2_OMP_SAFE_GLOBAL_ACCESS { + su2double* dbl_buffer = new su2double[Global_nElemDomain * nDim]; + SU2_MPI::Allreduce(cg_elem, dbl_buffer, Global_nElemDomain * nDim, MPI_DOUBLE, MPI_SUM, SU2_MPI::GetComm()); + swap(dbl_buffer, cg_elem); + delete[] dbl_buffer; + + dbl_buffer = new su2double[Global_nElemDomain]; + SU2_MPI::Allreduce(vol_elem, dbl_buffer, Global_nElemDomain, MPI_DOUBLE, MPI_SUM, SU2_MPI::GetComm()); + swap(dbl_buffer, vol_elem); + delete[] dbl_buffer; + + vector char_buffer(Global_nElemDomain); + MPI_Allreduce(halo_detect.data(), char_buffer.data(), Global_nElemDomain, MPI_CHAR, MPI_SUM, SU2_MPI::GetComm()); + halo_detect.swap(char_buffer); } END_SU2_OMP_SAFE_GLOBAL_ACCESS - /*--- Account for duplication ---*/ SU2_OMP_FOR_STAT(256) - for(auto iElem=0ul; iElemGetGlobalIndex(); + is_neighbor[omp_get_thread_num()].resize(Global_nElemDomain, false); + + for (unsigned long iKernel = 0; iKernel < kernels.size(); ++iKernel) { + auto kernel_type = kernels[iKernel].first; + su2double kernel_param = kernels[iKernel].second; + su2double kernel_radius = filter_radius[iKernel]; + + /*--- Synchronize work values ---*/ + /*--- Initialize ---*/ + SU2_OMP_FOR_STAT(256) + for (auto iElem = 0ul; iElem < Global_nElemDomain; ++iElem) work_values[iElem] = 0.0; + END_SU2_OMP_FOR - /*--- Find the neighbours of iElem ---*/ - vector neighbours; - limited_searches += !GetRadialNeighbourhood(iElem_global, SU2_TYPE::GetValue(kernel_radius), - search_limit, neighbour_start, neighbour_idx, - cg_elem, neighbours, is_neighbor[thread]); - /*--- Apply the kernel ---*/ - su2double weight = 0.0, numerator = 0.0, denominator = 0.0; - - switch ( kernel_type ) { - /*--- distance-based kernels (weighted averages) ---*/ - case ENUM_FILTER_KERNEL::CONSTANT_WEIGHT: - case ENUM_FILTER_KERNEL::CONICAL_WEIGHT: - case ENUM_FILTER_KERNEL::GAUSSIAN_WEIGHT: - - for (auto idx : neighbours) - { - su2double distance = 0.0; - for (unsigned short iDim=0; iDimGetGlobalIndex()] = values[iElem]; + END_SU2_OMP_FOR + +#ifdef HAVE_MPI + /*--- Share with all processors ---*/ + BEGIN_SU2_OMP_SAFE_GLOBAL_ACCESS { + su2double* buffer = new su2double[Global_nElemDomain]; + SU2_MPI::Allreduce(work_values, buffer, Global_nElemDomain, MPI_DOUBLE, MPI_SUM, SU2_MPI::GetComm()); + swap(buffer, work_values); + delete[] buffer; + } + END_SU2_OMP_SAFE_GLOBAL_ACCESS + + /*--- Account for duplication ---*/ + SU2_OMP_FOR_STAT(256) + for (auto iElem = 0ul; iElem < Global_nElemDomain; ++iElem) { + su2double numRepeat = halo_detect[iElem]; + work_values[iElem] /= numRepeat; + } + END_SU2_OMP_FOR +#endif + + /*--- Filter ---*/ + SU2_OMP_FOR_DYN(128) + for (auto iElem = 0ul; iElem < nElem; ++iElem) { + int thread = omp_get_thread_num(); + + /*--- Center of the search ---*/ + auto iElem_global = elem[iElem]->GetGlobalIndex(); + + /*--- Find the neighbours of iElem ---*/ + vector neighbours; + limited_searches += + !GetRadialNeighbourhood(iElem_global, SU2_TYPE::GetValue(kernel_radius), search_limit, neighbour_start, + neighbour_idx, cg_elem, neighbours, is_neighbor[thread]); + /*--- Apply the kernel ---*/ + su2double weight = 0.0, numerator = 0.0, denominator = 0.0; + + switch (kernel_type) { + /*--- distance-based kernels (weighted averages) ---*/ + case ENUM_FILTER_KERNEL::CONSTANT_WEIGHT: + case ENUM_FILTER_KERNEL::CONICAL_WEIGHT: + case ENUM_FILTER_KERNEL::GAUSSIAN_WEIGHT: + + for (auto idx : neighbours) { + su2double distance = 0.0; + for (unsigned short iDim = 0; iDim < nDim; ++iDim) + distance += pow(cg_elem[nDim * iElem_global + iDim] - cg_elem[nDim * idx + iDim], 2); + distance = sqrt(distance); + + switch (kernel_type) { + case ENUM_FILTER_KERNEL::CONSTANT_WEIGHT: + weight = 1.0; + break; + case ENUM_FILTER_KERNEL::CONICAL_WEIGHT: + weight = kernel_radius - distance; + break; + case ENUM_FILTER_KERNEL::GAUSSIAN_WEIGHT: + weight = exp(-0.5 * pow(distance / kernel_param, 2)); + break; + default: + break; + } + weight *= vol_elem[idx]; + numerator += weight * work_values[idx]; + denominator += weight; } - weight *= vol_elem[idx]; - numerator += weight*work_values[idx]; - denominator += weight; - } - values[iElem] = numerator/denominator; - break; + values[iElem] = numerator / denominator; + break; - /*--- morphology kernels (image processing) ---*/ - case ENUM_FILTER_KERNEL::DILATE_MORPH: - case ENUM_FILTER_KERNEL::ERODE_MORPH: + /*--- morphology kernels (image processing) ---*/ + case ENUM_FILTER_KERNEL::DILATE_MORPH: + case ENUM_FILTER_KERNEL::ERODE_MORPH: - for (auto idx : neighbours) - { - switch ( kernel_type ) { - case ENUM_FILTER_KERNEL::DILATE_MORPH: numerator += exp(kernel_param*work_values[idx]); break; - case ENUM_FILTER_KERNEL::ERODE_MORPH: numerator += exp(kernel_param*(1.0-work_values[idx])); break; - default: break; + for (auto idx : neighbours) { + switch (kernel_type) { + case ENUM_FILTER_KERNEL::DILATE_MORPH: + numerator += exp(kernel_param * work_values[idx]); + break; + case ENUM_FILTER_KERNEL::ERODE_MORPH: + numerator += exp(kernel_param * (1.0 - work_values[idx])); + break; + default: + break; + } + denominator += 1.0; } - denominator += 1.0; - } - values[iElem] = log(numerator/denominator)/kernel_param; - if ( kernel_type==ENUM_FILTER_KERNEL::ERODE_MORPH ) values[iElem] = 1.0-values[iElem]; - break; + values[iElem] = log(numerator / denominator) / kernel_param; + if (kernel_type == ENUM_FILTER_KERNEL::ERODE_MORPH) values[iElem] = 1.0 - values[iElem]; + break; - default: - SU2_MPI::Error("Unknown type of filter kernel",CURRENT_FUNCTION); + default: + SU2_MPI::Error("Unknown type of filter kernel", CURRENT_FUNCTION); + } } + END_SU2_OMP_FOR } - END_SU2_OMP_FOR - } - } END_SU2_OMP_PARALLEL limited_searches /= kernels.size(); unsigned long tmp = limited_searches; - SU2_MPI::Reduce(&tmp,&limited_searches,1,MPI_UNSIGNED_LONG,MPI_SUM,MASTER_NODE,SU2_MPI::GetComm()); + SU2_MPI::Reduce(&tmp, &limited_searches, 1, MPI_UNSIGNED_LONG, MPI_SUM, MASTER_NODE, SU2_MPI::GetComm()); - if (rank==MASTER_NODE && limited_searches>0) - cout << "Warning: The filter radius was limited for " << limited_searches - << " elements (" << limited_searches/(0.01*Global_nElemDomain) << "%).\n"; + if (rank == MASTER_NODE && limited_searches > 0) + cout << "Warning: The filter radius was limited for " << limited_searches << " elements (" + << limited_searches / (0.01 * Global_nElemDomain) << "%).\n"; - delete [] neighbour_idx; - delete [] cg_elem; - delete [] vol_elem; - delete [] work_values; + delete[] neighbour_idx; + delete[] cg_elem; + delete[] vol_elem; + delete[] work_values; } -void CGeometry::GetGlobalElementAdjacencyMatrix(vector &neighbour_start, - long *&neighbour_idx) const -{ - if ( neighbour_idx != nullptr ) - SU2_MPI::Error("neighbour_idx is expected to be NULL, stopping to avoid a potential memory leak",CURRENT_FUNCTION); +void CGeometry::GetGlobalElementAdjacencyMatrix(vector& neighbour_start, long*& neighbour_idx) const { + if (neighbour_idx != nullptr) + SU2_MPI::Error("neighbour_idx is expected to be NULL, stopping to avoid a potential memory leak", CURRENT_FUNCTION); /*--- Determine how much space we need for the adjacency matrix by counting the neighbours of each element, i.e. its number of faces---*/ - unsigned short *nFaces_elem = new unsigned short [Global_nElemDomain]; + unsigned short* nFaces_elem = new unsigned short[Global_nElemDomain]; - SU2_OMP_PARALLEL - { + SU2_OMP_PARALLEL { SU2_OMP_FOR_STAT(256) - for(auto iElem=0ul; iElemGetGlobalIndex(); nFaces_elem[iElem_global] = elem[iElem]->GetnFaces(); } @@ -3312,47 +3235,45 @@ void CGeometry::GetGlobalElementAdjacencyMatrix(vector &neighbour #ifdef HAVE_MPI /*--- Share with all processors ---*/ { - unsigned short *buffer = new unsigned short [Global_nElemDomain]; - MPI_Allreduce(nFaces_elem,buffer,Global_nElemDomain,MPI_UNSIGNED_SHORT,MPI_MAX,SU2_MPI::GetComm()); + unsigned short* buffer = new unsigned short[Global_nElemDomain]; + MPI_Allreduce(nFaces_elem, buffer, Global_nElemDomain, MPI_UNSIGNED_SHORT, MPI_MAX, SU2_MPI::GetComm()); /*--- swap pointers and delete old data to keep the same variable name after reduction ---*/ - swap(buffer, nFaces_elem); delete [] buffer; + swap(buffer, nFaces_elem); + delete[] buffer; } #endif /*--- Vector with the addresses of the start of the neighbours of a given element. This is generated by a cumulative sum of the neighbour count. ---*/ - neighbour_start.resize(Global_nElemDomain+1); + neighbour_start.resize(Global_nElemDomain + 1); neighbour_start[0] = 0; - for(auto iElem=0ul; iElemGetGlobalIndex(); auto start_pos = neighbour_start[iElem_global]; - for(unsigned short iFace=0; iFaceGetnFaces(); ++iFace) - { + for (unsigned short iFace = 0; iFace < elem[iElem]->GetnFaces(); ++iFace) { long neighbour = elem[iElem]->GetNeighbor_Elements(iFace); - if ( neighbour>=0 ) { - neighbour_idx[start_pos+iFace] = elem[neighbour]->GetGlobalIndex(); + if (neighbour >= 0) { + neighbour_idx[start_pos + iFace] = elem[neighbour]->GetGlobalIndex(); } } } @@ -3362,25 +3283,20 @@ void CGeometry::GetGlobalElementAdjacencyMatrix(vector &neighbour #ifdef HAVE_MPI /*--- Share with all processors ---*/ { - long *buffer = new long [matrix_size]; - MPI_Allreduce(neighbour_idx,buffer,matrix_size,MPI_LONG,MPI_MAX,SU2_MPI::GetComm()); - swap(buffer, neighbour_idx); delete [] buffer; + long* buffer = new long[matrix_size]; + MPI_Allreduce(neighbour_idx, buffer, matrix_size, MPI_LONG, MPI_MAX, SU2_MPI::GetComm()); + swap(buffer, neighbour_idx); + delete[] buffer; } #endif } -bool CGeometry::GetRadialNeighbourhood(const unsigned long iElem_global, - const passivedouble radius, - size_t search_limit, - const vector &neighbour_start, - const long *neighbour_idx, - const su2double *cg_elem, - vector &neighbours, - vector &is_neighbor) const -{ +bool CGeometry::GetRadialNeighbourhood(const unsigned long iElem_global, const passivedouble radius, + size_t search_limit, const vector& neighbour_start, + const long* neighbour_idx, const su2double* cg_elem, vector& neighbours, + vector& is_neighbor) const { /*--- Validate inputs if we are debugging. ---*/ - assert(neighbour_start.size() == Global_nElemDomain+1 && - neighbour_idx != nullptr && cg_elem != nullptr && + assert(neighbour_start.size() == Global_nElemDomain + 1 && neighbour_idx != nullptr && cg_elem != nullptr && is_neighbor.size() == Global_nElemDomain && "invalid inputs"); /*--- 0 search_limit means "unlimited" (it will probably @@ -3393,26 +3309,25 @@ bool CGeometry::GetRadialNeighbourhood(const unsigned long iElem_global, is_neighbor[iElem_global] = true; passivedouble X0[3] = {0.0, 0.0, 0.0}; - for (unsigned short iDim=0; iDim candidates; - for (auto it = neighbours.begin()+start; it!=neighbours.end(); ++it) { + for (auto it = neighbours.begin() + start; it != neighbours.end(); ++it) { /*--- scan row of the adjacency matrix of element *it ---*/ - for (auto i = neighbour_start[*it]; i < neighbour_start[(*it)+1]; ++i) { + for (auto i = neighbour_start[*it]; i < neighbour_start[(*it) + 1]; ++i) { auto idx = neighbour_idx[i]; - if (idx>=0) if (!is_neighbor[idx]) { - candidates.push_back(idx); - /*--- mark as neighbour for now to avoid duplicate candidates. ---*/ - is_neighbor[idx] = true; - } + if (idx >= 0) + if (!is_neighbor[idx]) { + candidates.push_back(idx); + /*--- mark as neighbour for now to avoid duplicate candidates. ---*/ + is_neighbor[idx] = true; + } } } /*--- update start position to fetch next degree candidates. ---*/ @@ -3420,100 +3335,108 @@ bool CGeometry::GetRadialNeighbourhood(const unsigned long iElem_global, /*--- Add candidates within "radius" of X0, if none qualifies we are "finished". ---*/ finished = true; - for (auto idx : candidates) - { + for (auto idx : candidates) { /*--- passivedouble as we only need to compare "distance". ---*/ passivedouble distance = 0.0; - for (unsigned short iDim=0; iDimGetVTK_Type()) { - case TRIANGLE: element = elements[0]; break; - case QUADRILATERAL: element = elements[1]; break; - case TETRAHEDRON: element = elements[0]; break; - case PYRAMID: element = elements[1]; break; - case PRISM: element = elements[2]; break; - case HEXAHEDRON: element = elements[3]; break; - default: - SU2_MPI::Error("Cannot compute the area/volume of a 1D element.",CURRENT_FUNCTION); + if (nDim == 2) { + elements[0] = new CTRIA1(); + elements[1] = new CQUAD4(); + } else { + elements[0] = new CTETRA1(); + elements[1] = new CPYRAM5(); + elements[2] = new CPRISM6(); + elements[3] = new CHEXA8(); } - /*--- Set the nodal coordinates of the element. ---*/ - for (unsigned short iNode=0; iNodeGetnNodes(); ++iNode) { - unsigned long node_idx = elem[iElem]->GetNode(iNode); - for (unsigned short iDim=0; iDimGetCoord(node_idx, iDim); - element->SetRef_Coord(iNode, iDim, coord); + + /*--- Compute and store the volume of each "elem". ---*/ + SU2_OMP_FOR_DYN(128) + for (unsigned long iElem = 0; iElem < nElem; ++iElem) { + /*--- Get the appropriate type of element. ---*/ + CElement* element = nullptr; + switch (elem[iElem]->GetVTK_Type()) { + case TRIANGLE: + element = elements[0]; + break; + case QUADRILATERAL: + element = elements[1]; + break; + case TETRAHEDRON: + element = elements[0]; + break; + case PYRAMID: + element = elements[1]; + break; + case PRISM: + element = elements[2]; + break; + case HEXAHEDRON: + element = elements[3]; + break; + default: + SU2_MPI::Error("Cannot compute the area/volume of a 1D element.", CURRENT_FUNCTION); + } + /*--- Set the nodal coordinates of the element. ---*/ + for (unsigned short iNode = 0; iNode < elem[iElem]->GetnNodes(); ++iNode) { + unsigned long node_idx = elem[iElem]->GetNode(iNode); + for (unsigned short iDim = 0; iDim < nDim; ++iDim) { + su2double coord = nodes->GetCoord(node_idx, iDim); + element->SetRef_Coord(iNode, iDim, coord); + } } + /*--- Compute ---*/ + if (nDim == 2) + elem[iElem]->SetVolume(element->ComputeArea()); + else + elem[iElem]->SetVolume(element->ComputeVolume()); } - /*--- Compute ---*/ - if(nDim==2) elem[iElem]->SetVolume(element->ComputeArea()); - else elem[iElem]->SetVolume(element->ComputeVolume()); - } - END_SU2_OMP_FOR - - delete elements[0]; - delete elements[1]; - if (nDim==3) { - delete elements[2]; - delete elements[3]; - } + END_SU2_OMP_FOR + delete elements[0]; + delete elements[1]; + if (nDim == 3) { + delete elements[2]; + delete elements[3]; + } } END_SU2_OMP_PARALLEL } -void CGeometry::SetRotationalVelocity(const CConfig *config, bool print) { - +void CGeometry::SetRotationalVelocity(const CConfig* config, bool print) { unsigned long iPoint; unsigned short iDim; - su2double GridVel[3] = {0.0,0.0,0.0}, Distance[3] = {0.0,0.0,0.0}, - Center[3] = {0.0,0.0,0.0}, Omega[3] = {0.0,0.0,0.0}, - xDot[3] = {0.0,0.0,0.0}; + su2double GridVel[3] = {0.0, 0.0, 0.0}, Distance[3] = {0.0, 0.0, 0.0}, Center[3] = {0.0, 0.0, 0.0}, + Omega[3] = {0.0, 0.0, 0.0}, xDot[3] = {0.0, 0.0, 0.0}; /*--- Center of rotation & angular velocity vector from config ---*/ for (iDim = 0; iDim < 3; iDim++) { Center[iDim] = config->GetMotion_Origin(iDim); - Omega[iDim] = config->GetRotation_Rate(iDim)/config->GetOmega_Ref(); - xDot[iDim] = config->GetTranslation_Rate(iDim)/config->GetVelocity_Ref(); + Omega[iDim] = config->GetRotation_Rate(iDim) / config->GetOmega_Ref(); + xDot[iDim] = config->GetTranslation_Rate(iDim) / config->GetVelocity_Ref(); } su2double L_Ref = config->GetLength_Ref(); @@ -3525,48 +3448,43 @@ void CGeometry::SetRotationalVelocity(const CConfig *config, bool print) { cout << ", " << Center[2] << " )\n"; cout << " Angular velocity about x, y, z axes: ( " << Omega[0] << ", "; cout << Omega[1] << ", " << Omega[2] << " ) rad/s" << endl; - cout << " Translational velocity in x, y, z direction: (" - << xDot[0] << ", " << xDot[1] << ", " << xDot[2] << ")." << endl; + cout << " Translational velocity in x, y, z direction: (" << xDot[0] << ", " << xDot[1] << ", " << xDot[2] << ")." + << endl; } /*--- Loop over all nodes and set the rotational and translational velocity ---*/ for (iPoint = 0; iPoint < nPoint; iPoint++) { - /*--- Get the coordinates of the current node ---*/ const su2double* Coord = nodes->GetCoord(iPoint); /*--- Calculate the non-dim. distance from the rotation center ---*/ - for (iDim = 0; iDim < nDim; iDim++) - Distance[iDim] = (Coord[iDim]-Center[iDim])/L_Ref; + for (iDim = 0; iDim < nDim; iDim++) Distance[iDim] = (Coord[iDim] - Center[iDim]) / L_Ref; /*--- Calculate the angular velocity as omega X r and add translational velocity ---*/ - GridVel[0] = Omega[1]*(Distance[2]) - Omega[2]*(Distance[1]) + xDot[0]; - GridVel[1] = Omega[2]*(Distance[0]) - Omega[0]*(Distance[2]) + xDot[1]; - GridVel[2] = Omega[0]*(Distance[1]) - Omega[1]*(Distance[0]) + xDot[2]; + GridVel[0] = Omega[1] * (Distance[2]) - Omega[2] * (Distance[1]) + xDot[0]; + GridVel[1] = Omega[2] * (Distance[0]) - Omega[0] * (Distance[2]) + xDot[1]; + GridVel[2] = Omega[0] * (Distance[1]) - Omega[1] * (Distance[0]) + xDot[2]; /*--- Store the grid velocity at this node ---*/ nodes->SetGridVel(iPoint, GridVel); - } - } -void CGeometry::SetShroudVelocity(const CConfig *config) { - +void CGeometry::SetShroudVelocity(const CConfig* config) { unsigned long iPoint, iVertex; unsigned short iMarker, iMarkerShroud; - su2double RotVel[3] = {0.0,0.0,0.0}; + su2double RotVel[3] = {0.0, 0.0, 0.0}; /*--- Loop over all vertex in the shroud marker and set the rotational velocity to 0.0 ---*/ - for (iMarker = 0; iMarker < nMarker; iMarker++){ - for(iMarkerShroud=0; iMarkerShroud < config->GetnMarker_Shroud(); iMarkerShroud++){ - if(config->GetMarker_Shroud(iMarkerShroud) == config->GetMarker_All_TagBound(iMarker)){ - for (iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { + for (iMarker = 0; iMarker < nMarker; iMarker++) { + for (iMarkerShroud = 0; iMarkerShroud < config->GetnMarker_Shroud(); iMarkerShroud++) { + if (config->GetMarker_Shroud(iMarkerShroud) == config->GetMarker_All_TagBound(iMarker)) { + for (iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { iPoint = vertex[iMarker][iVertex]->GetNode(); nodes->SetGridVel(iPoint, RotVel); } @@ -3575,30 +3493,26 @@ void CGeometry::SetShroudVelocity(const CConfig *config) { } } -void CGeometry::SetTranslationalVelocity(const CConfig *config, bool print) { - - su2double xDot[3] = {0.0,0.0,0.0}; +void CGeometry::SetTranslationalVelocity(const CConfig* config, bool print) { + su2double xDot[3] = {0.0, 0.0, 0.0}; /*--- Get the translational velocity vector from config ---*/ for (unsigned short iDim = 0; iDim < nDim; iDim++) - xDot[iDim] = config->GetTranslation_Rate(iDim)/config->GetVelocity_Ref(); + xDot[iDim] = config->GetTranslation_Rate(iDim) / config->GetVelocity_Ref(); /*--- Print some information to the console ---*/ if (rank == MASTER_NODE && print) { - cout << " Non-dim. translational velocity: (" - << xDot[0] << ", " << xDot[1] << ", " << xDot[2] << ")." << endl; + cout << " Non-dim. translational velocity: (" << xDot[0] << ", " << xDot[1] << ", " << xDot[2] << ")." << endl; } /*--- Loop over all nodes and set the translational velocity ---*/ - for (unsigned long iPoint = 0; iPoint < nPoint; iPoint++) - nodes->SetGridVel(iPoint, xDot); + for (unsigned long iPoint = 0; iPoint < nPoint; iPoint++) nodes->SetGridVel(iPoint, xDot); } -void CGeometry::SetWallVelocity(const CConfig *config, bool print) { - +void CGeometry::SetWallVelocity(const CConfig* config, bool print) { const su2double L_Ref = config->GetLength_Ref(); const su2double Omega_Ref = config->GetOmega_Ref(); const su2double Vel_Ref = config->GetVelocity_Ref(); @@ -3617,7 +3531,7 @@ void CGeometry::SetWallVelocity(const CConfig *config, bool print) { su2double xDot[MAXNDIM], Center[MAXNDIM], Omega[MAXNDIM]; - for (auto iDim = 0u; iDim < MAXNDIM; iDim++){ + for (auto iDim = 0u; iDim < MAXNDIM; iDim++) { Center[iDim] = config->GetMarkerMotion_Origin(jMarker, iDim); Omega[iDim] = config->GetMarkerRotationRate(jMarker, iDim) / Omega_Ref; xDot[iDim] = config->GetMarkerTranslationRate(jMarker, iDim) / Vel_Ref; @@ -3626,10 +3540,13 @@ void CGeometry::SetWallVelocity(const CConfig *config, bool print) { if (rank == MASTER_NODE && print) { cout << " Storing grid velocity for marker: "; cout << Marker_Tag << ".\n"; - cout << " Translational velocity: (" << xDot[0]*config->GetVelocity_Ref() << ", " << xDot[1]*config->GetVelocity_Ref(); - cout << ", " << xDot[2]*config->GetVelocity_Ref(); - if (config->GetSystemMeasurements() == SI) cout << ") m/s.\n"; - else cout << ") ft/s.\n"; + cout << " Translational velocity: (" << xDot[0] * config->GetVelocity_Ref() << ", " + << xDot[1] * config->GetVelocity_Ref(); + cout << ", " << xDot[2] * config->GetVelocity_Ref(); + if (config->GetSystemMeasurements() == SI) + cout << ") m/s.\n"; + else + cout << ") ft/s.\n"; cout << " Angular velocity: (" << Omega[0] << ", " << Omega[1]; cout << ", " << Omega[2] << ") rad/s about origin: (" << Center[0]; cout << ", " << Center[1] << ", " << Center[2] << ")." << endl; @@ -3640,8 +3557,7 @@ void CGeometry::SetWallVelocity(const CConfig *config, bool print) { /*--- Calculate non-dim. position from rotation center ---*/ su2double r[MAXNDIM] = {0.0}; - for (auto iDim = 0u; iDim < nDim; iDim++) - r[iDim] = (nodes->GetCoord(iPoint,iDim) - Center[iDim]) / L_Ref; + for (auto iDim = 0u; iDim < nDim; iDim++) r[iDim] = (nodes->GetCoord(iPoint, iDim) - Center[iDim]) / L_Ref; /*--- Cross Product of angular velocity and distance from center to get the rotational velocity. Note that we are adding on the velocity @@ -3650,14 +3566,12 @@ void CGeometry::SetWallVelocity(const CConfig *config, bool print) { su2double GridVel[MAXNDIM]; GeometryToolbox::CrossProduct(Omega, r, GridVel); - for (auto iDim = 0u; iDim < nDim; iDim++) - nodes->SetGridVel(iPoint, iDim, xDot[iDim]+GridVel[iDim]); + for (auto iDim = 0u; iDim < nDim; iDim++) nodes->SetGridVel(iPoint, iDim, xDot[iDim] + GridVel[iDim]); } } } -void CGeometry::SetGridVelocity(const CConfig *config) { - +void CGeometry::SetGridVelocity(const CConfig* config) { /*--- Get timestep and whether to use 1st or 2nd order backward finite differences ---*/ bool FirstOrder = (config->GetTime_Marching() == TIME_MARCHING::DT_STEPPING_1ST); @@ -3668,41 +3582,35 @@ void CGeometry::SetGridVelocity(const CConfig *config) { /*--- Compute the velocity of each node in the volume mesh ---*/ for (unsigned long iPoint = 0; iPoint < nPoint; iPoint++) { - /*--- Coordinates of the current point at n+1, n, & n-1 time levels ---*/ - const su2double *Coord_nM1 = nodes->GetCoord_n1(iPoint); - const su2double *Coord_n = nodes->GetCoord_n(iPoint); - const su2double *Coord_nP1 = nodes->GetCoord(iPoint); + const su2double* Coord_nM1 = nodes->GetCoord_n1(iPoint); + const su2double* Coord_n = nodes->GetCoord_n(iPoint); + const su2double* Coord_nP1 = nodes->GetCoord(iPoint); /*--- Compute and store mesh velocity with 1st or 2nd-order approximation ---*/ for (unsigned short iDim = 0; iDim < nDim; iDim++) { - su2double GridVel = 0.0; - if (FirstOrder) - GridVel = (Coord_nP1[iDim] - Coord_n[iDim]) / TimeStep; + if (FirstOrder) GridVel = (Coord_nP1[iDim] - Coord_n[iDim]) / TimeStep; - if (SecondOrder) - GridVel = (1.5*Coord_nP1[iDim] - 2.0*Coord_n[iDim] + 0.5*Coord_nM1[iDim]) / TimeStep; + if (SecondOrder) GridVel = (1.5 * Coord_nP1[iDim] - 2.0 * Coord_n[iDim] + 0.5 * Coord_nM1[iDim]) / TimeStep; nodes->SetGridVel(iPoint, iDim, GridVel); } } - } -const CCompressedSparsePatternUL& CGeometry::GetSparsePattern(ConnectivityType type, unsigned long fillLvl) -{ +const CCompressedSparsePatternUL& CGeometry::GetSparsePattern(ConnectivityType type, unsigned long fillLvl) { bool fvm = (type == ConnectivityType::FiniteVolume); CCompressedSparsePatternUL* pattern = nullptr; if (fillLvl == 0) - pattern = fvm? &finiteVolumeCSRFill0 : &finiteElementCSRFill0; + pattern = fvm ? &finiteVolumeCSRFill0 : &finiteElementCSRFill0; else - pattern = fvm? &finiteVolumeCSRFillN : &finiteElementCSRFillN; + pattern = fvm ? &finiteVolumeCSRFillN : &finiteElementCSRFillN; if (pattern->empty()) { *pattern = buildCSRPattern(*this, type, fillLvl); @@ -3712,8 +3620,7 @@ const CCompressedSparsePatternUL& CGeometry::GetSparsePattern(ConnectivityType t return *pattern; } -const CEdgeToNonZeroMapUL& CGeometry::GetEdgeToSparsePatternMap(void) -{ +const CEdgeToNonZeroMapUL& CGeometry::GetEdgeToSparsePatternMap(void) { if (edgeToCSRMap.empty()) { if (finiteVolumeCSRFill0.empty()) { finiteVolumeCSRFill0 = buildCSRPattern(*this, ConnectivityType::FiniteVolume, 0ul); @@ -3723,39 +3630,36 @@ const CEdgeToNonZeroMapUL& CGeometry::GetEdgeToSparsePatternMap(void) return edgeToCSRMap; } -const su2vector& CGeometry::GetTransposeSparsePatternMap(ConnectivityType type) -{ +const su2vector& CGeometry::GetTransposeSparsePatternMap(ConnectivityType type) { /*--- Yes the const cast is weird but it is still better than repeating code. ---*/ auto& pattern = const_cast(GetSparsePattern(type)); pattern.buildTransposePtr(); return pattern.transposePtr(); } -const CCompressedSparsePatternUL& CGeometry::GetEdgeColoring(su2double* efficiency) -{ +const CCompressedSparsePatternUL& CGeometry::GetEdgeColoring(su2double* efficiency) { /*--- Check for dry run mode with dummy geometry. ---*/ - if (nEdge==0) return edgeColoring; + if (nEdge == 0) return edgeColoring; /*--- Build if required. ---*/ if (edgeColoring.empty()) { - /*--- When not using threading use the natural coloring to reduce overhead. ---*/ if (omp_get_max_threads() == 1) { SetNaturalEdgeColoring(); - if (efficiency != nullptr) *efficiency = 1.0; // by definition + if (efficiency != nullptr) *efficiency = 1.0; // by definition return edgeColoring; } /*--- Create a temporary sparse pattern from the edges. ---*/ - su2vector outerPtr(nEdge+1); - su2vector innerIdx(nEdge*2); + su2vector outerPtr(nEdge + 1); + su2vector innerIdx(nEdge * 2); for (unsigned long iEdge = 0; iEdge < nEdge; ++iEdge) { - outerPtr(iEdge) = 2*iEdge; - innerIdx(iEdge*2+0) = edges->GetNode(iEdge,0); - innerIdx(iEdge*2+1) = edges->GetNode(iEdge,1); + outerPtr(iEdge) = 2 * iEdge; + innerIdx(iEdge * 2 + 0) = edges->GetNode(iEdge, 0); + innerIdx(iEdge * 2 + 1) = edges->GetNode(iEdge, 1); } - outerPtr(nEdge) = 2*nEdge; + outerPtr(nEdge) = 2 * nEdge; CCompressedSparsePatternUL pattern(move(outerPtr), move(innerIdx)); @@ -3775,32 +3679,30 @@ const CCompressedSparsePatternUL& CGeometry::GetEdgeColoring(su2double* efficien return edgeColoring; } -void CGeometry::SetNaturalEdgeColoring() -{ +void CGeometry::SetNaturalEdgeColoring() { if (nEdge == 0) return; edgeColoring = createNaturalColoring(nEdge); /*--- In parallel, set the group size to nEdge to protect client code. ---*/ if (omp_get_max_threads() > 1) edgeColorGroupSize = nEdge; } -const CCompressedSparsePatternUL& CGeometry::GetElementColoring(su2double* efficiency) -{ +const CCompressedSparsePatternUL& CGeometry::GetElementColoring(su2double* efficiency) { /*--- Check for dry run mode with dummy geometry. ---*/ - if (nElem==0) return elemColoring; + if (nElem == 0) return elemColoring; /*--- Build if required. ---*/ if (elemColoring.empty()) { - /*--- When not using threading use the natural coloring. ---*/ if (omp_get_max_threads() == 1) { SetNaturalElementColoring(); - if (efficiency != nullptr) *efficiency = 1.0; // by definition + if (efficiency != nullptr) *efficiency = 1.0; // by definition return elemColoring; } /*--- Create a temporary sparse pattern from the elements. ---*/ - vector outerPtr(nElem+1); - vector innerIdx; innerIdx.reserve(nElem); + vector outerPtr(nElem + 1); + vector innerIdx; + innerIdx.reserve(nElem); for (unsigned long iElem = 0; iElem < nElem; ++iElem) { outerPtr[iElem] = innerIdx.size(); @@ -3827,8 +3729,7 @@ const CCompressedSparsePatternUL& CGeometry::GetElementColoring(su2double* effic return elemColoring; } -void CGeometry::SetNaturalElementColoring() -{ +void CGeometry::SetNaturalElementColoring() { if (nElem == 0) return; elemColoring = createNaturalColoring(nElem); /*--- In parallel, set the group size to nElem to protect client code. ---*/ @@ -3836,28 +3737,26 @@ void CGeometry::SetNaturalElementColoring() } void CGeometry::ColorMGLevels(unsigned short nMGLevels, const CGeometry* const* geometry) { - using tColor = uint8_t; constexpr auto nColor = numeric_limits::max(); - if (nMGLevels) CoarseGridColor_.resize(nPoint,nMGLevels) = 0; + if (nMGLevels) CoarseGridColor_.resize(nPoint, nMGLevels) = 0; for (auto iMesh = nMGLevels; iMesh >= 1; --iMesh) { /*--- Color the coarse points. ---*/ vector color; const auto& adjacency = geometry[iMesh]->nodes->GetPoints(); - if (colorSparsePattern(adjacency, 1, false, &color).empty()) - continue; + if (colorSparsePattern(adjacency, 1, false, &color).empty()) continue; /*--- Propagate colors to fine mesh. ---*/ for (auto step = 0u; step < iMesh; ++step) { - auto coarseMesh = geometry[iMesh-1-step]; + auto coarseMesh = geometry[iMesh - 1 - step]; if (step) for (auto iPoint = 0ul; iPoint < coarseMesh->GetnPoint(); ++iPoint) - CoarseGridColor_(iPoint,step) = CoarseGridColor_(coarseMesh->nodes->GetParent_CV(iPoint), step-1); + CoarseGridColor_(iPoint, step) = CoarseGridColor_(coarseMesh->nodes->GetParent_CV(iPoint), step - 1); else for (auto iPoint = 0ul; iPoint < coarseMesh->GetnPoint(); ++iPoint) - CoarseGridColor_(iPoint,step) = color[coarseMesh->nodes->GetParent_CV(iPoint)]; + CoarseGridColor_(iPoint, step) = color[coarseMesh->nodes->GetParent_CV(iPoint)]; } } } @@ -3993,8 +3892,8 @@ const CGeometry::CLineletInfo& CGeometry::GetLineletInfo(const CConfig* config) } } - const auto coloring = colorSparsePattern::max()>( - CCompressedSparsePatternUL(adjacency), 1, true); + const auto coloring = + colorSparsePattern::max()>(CCompressedSparsePatternUL(adjacency), 1, true); const auto nColors = coloring.getOuterSize(); /*--- Sort linelets by color. ---*/ @@ -4034,43 +3933,38 @@ const CGeometry::CLineletInfo& CGeometry::GetLineletInfo(const CConfig* config) return li; } -void CGeometry::ComputeWallDistance(const CConfig* const* config_container, CGeometry ****geometry_container){ - +void CGeometry::ComputeWallDistance(const CConfig* const* config_container, CGeometry**** geometry_container) { int nZone = config_container[ZONE_0]->GetnZone(); bool allEmpty = true; vector wallDistanceNeeded(nZone, false); - for (int iInst = 0; iInst < config_container[ZONE_0]->GetnTimeInstances(); iInst++){ - for (int iZone = 0; iZone < nZone; iZone++){ - + for (int iInst = 0; iInst < config_container[ZONE_0]->GetnTimeInstances(); iInst++) { + for (int iZone = 0; iZone < nZone; iZone++) { /*--- Check if a zone needs the wall distance and store a boolean ---*/ MAIN_SOLVER kindSolver = config_container[iZone]->GetKind_Solver(); - if (kindSolver == MAIN_SOLVER::RANS || - kindSolver == MAIN_SOLVER::INC_RANS || - kindSolver == MAIN_SOLVER::DISC_ADJ_RANS || - kindSolver == MAIN_SOLVER::DISC_ADJ_INC_RANS || - kindSolver == MAIN_SOLVER::FEM_LES || - kindSolver == MAIN_SOLVER::FEM_RANS){ + if (kindSolver == MAIN_SOLVER::RANS || kindSolver == MAIN_SOLVER::INC_RANS || + kindSolver == MAIN_SOLVER::DISC_ADJ_RANS || kindSolver == MAIN_SOLVER::DISC_ADJ_INC_RANS || + kindSolver == MAIN_SOLVER::FEM_LES || kindSolver == MAIN_SOLVER::FEM_RANS) { wallDistanceNeeded[iZone] = true; } /*--- Set the wall distances in all zones to the numerical limit. - * This is necessary, because before a computed distance is set, it will be checked - * whether the new distance is smaller than the currently stored one. ---*/ - CGeometry *geometry = geometry_container[iZone][iInst][MESH_0]; - if (wallDistanceNeeded[iZone]) - geometry->SetWallDistance(numeric_limits::max()); + * This is necessary, because before a computed distance is set, it will be checked + * whether the new distance is smaller than the currently stored one. ---*/ + CGeometry* geometry = geometry_container[iZone][iInst][MESH_0]; + if (wallDistanceNeeded[iZone]) geometry->SetWallDistance(numeric_limits::max()); } /*--- Loop over all zones and compute the ADT based on the viscous walls in that zone ---*/ - for (int iZone = 0; iZone < nZone; iZone++){ - unique_ptr WallADT = geometry_container[iZone][iInst][MESH_0]->ComputeViscousWallADT(config_container[iZone]); - if (WallADT && !WallADT->IsEmpty()){ + for (int iZone = 0; iZone < nZone; iZone++) { + unique_ptr WallADT = + geometry_container[iZone][iInst][MESH_0]->ComputeViscousWallADT(config_container[iZone]); + if (WallADT && !WallADT->IsEmpty()) { allEmpty = false; /*--- Inner loop over all zones to update the wall distances. - * It might happen that there is a closer viscous wall in zone iZone for points in zone jZone. ---*/ - for (int jZone = 0; jZone < nZone; jZone++){ + * It might happen that there is a closer viscous wall in zone iZone for points in zone jZone. ---*/ + for (int jZone = 0; jZone < nZone; jZone++) { if (wallDistanceNeeded[jZone]) geometry_container[jZone][iInst][MESH_0]->SetWallDistance(WallADT.get(), config_container[jZone], iZone); } @@ -4078,31 +3972,30 @@ void CGeometry::ComputeWallDistance(const CConfig* const* config_container, CGeo } /*--- If there are no viscous walls in the entire domain, set distances to zero ---*/ - if (allEmpty){ - for (int iZone = 0; iZone < nZone; iZone++){ - CGeometry *geometry = geometry_container[iZone][iInst][MESH_0]; + if (allEmpty) { + for (int iZone = 0; iZone < nZone; iZone++) { + CGeometry* geometry = geometry_container[iZone][iInst][MESH_0]; geometry->SetWallDistance(0.0); } } /*--- Otherwise, set wall roughnesses. ---*/ - if(!allEmpty){ + if (!allEmpty) { /*--- Store all wall roughnesses in a common data structure. ---*/ // [iZone][iMarker] -> roughness, for this rank - auto roughness_f = - make_pair( nZone, [config_container,geometry_container,iInst](unsigned long iZone){ - const CConfig* config = config_container[iZone]; - const auto nMarker = geometry_container[iZone][iInst][MESH_0]->GetnMarker(); - - return make_pair( nMarker, [config](unsigned long iMarker){ - return config->GetWallRoughnessProperties(config->GetMarker_All_TagBound(iMarker)).second; - }); + auto roughness_f = make_pair(nZone, [config_container, geometry_container, iInst](unsigned long iZone) { + const CConfig* config = config_container[iZone]; + const auto nMarker = geometry_container[iZone][iInst][MESH_0]->GetnMarker(); + + return make_pair(nMarker, [config](unsigned long iMarker) { + return config->GetWallRoughnessProperties(config->GetMarker_All_TagBound(iMarker)).second; }); + }); NdFlattener<2> roughness_local(roughness_f); // [rank][iZone][iMarker] -> roughness NdFlattener<3> roughness_global(Nd_MPI_Environment(), roughness_local); // use it to update roughnesses - for(int jZone=0; jZoneGetnRoughWall()>0){ + for (int jZone = 0; jZone < nZone; jZone++) { + if (wallDistanceNeeded[jZone] && config_container[jZone]->GetnRoughWall() > 0) { geometry_container[jZone][iInst][MESH_0]->nodes->SetWallRoughness(roughness_global); } } diff --git a/Common/src/geometry/CMultiGridGeometry.cpp b/Common/src/geometry/CMultiGridGeometry.cpp index f28716fb795..e131d569df0 100644 --- a/Common/src/geometry/CMultiGridGeometry.cpp +++ b/Common/src/geometry/CMultiGridGeometry.cpp @@ -30,9 +30,8 @@ #include "../../include/toolboxes/printing_toolbox.hpp" #include "../../../Common/include/toolboxes/geometry_toolbox.hpp" -CMultiGridGeometry::CMultiGridGeometry(CGeometry *fine_grid, CConfig *config, unsigned short iMesh) : CGeometry() { - - nDim = fine_grid->GetnDim(); // Write the number of dimensions of the coarse grid. +CMultiGridGeometry::CMultiGridGeometry(CGeometry* fine_grid, CConfig* config, unsigned short iMesh) : CGeometry() { + nDim = fine_grid->GetnDim(); // Write the number of dimensions of the coarse grid. /*--- Create a queue system to do the agglomeration 1st) More than two markers ---> Vertices (never agglomerate) @@ -45,8 +44,7 @@ CMultiGridGeometry::CMultiGridGeometry(CGeometry *fine_grid, CConfig *config, un For other levels this information is propagated down during their construction. ---*/ if (iMesh == MESH_1) { - - for (auto iPoint = 0ul; iPoint < fine_grid->GetnPoint(); iPoint ++) + for (auto iPoint = 0ul; iPoint < fine_grid->GetnPoint(); iPoint++) fine_grid->nodes->SetAgglomerate_Indirect(iPoint, false); for (auto iElem = 0ul; iElem < fine_grid->GetnElem(); iElem++) { @@ -58,7 +56,6 @@ CMultiGridGeometry::CMultiGridGeometry(CGeometry *fine_grid, CConfig *config, un } } } - } /*--- Create the coarse grid structure using as baseline the fine grid ---*/ @@ -73,7 +70,6 @@ CMultiGridGeometry::CMultiGridGeometry(CGeometry *fine_grid, CConfig *config, un /*--- The first step is the boundary agglomeration. ---*/ for (auto iMarker = 0u; iMarker < fine_grid->GetnMarker(); iMarker++) { - for (auto iVertex = 0ul; iVertex < fine_grid->GetnVertex(iMarker); iVertex++) { const auto iPoint = fine_grid->vertex[iMarker][iVertex]->GetNode(); @@ -81,10 +77,8 @@ CMultiGridGeometry::CMultiGridGeometry(CGeometry *fine_grid, CConfig *config, un belongs to this physical domain, and it meets the geometrical criteria, the agglomeration is studied. ---*/ - if ((fine_grid->nodes->GetAgglomerate(iPoint) == false) && - (fine_grid->nodes->GetDomain(iPoint)) && + if ((fine_grid->nodes->GetAgglomerate(iPoint) == false) && (fine_grid->nodes->GetDomain(iPoint)) && (GeometricalCheck(iPoint, fine_grid, config))) { - unsigned short nChildren = 1; /*--- We set an index for the parent control volume, this @@ -103,7 +97,7 @@ CMultiGridGeometry::CMultiGridGeometry(CGeometry *fine_grid, CConfig *config, un /*--- For a particular point in the fine grid we save all the markers that are in that point ---*/ - for (auto jMarker = 0u; jMarker < fine_grid->GetnMarker() && counter < 3; jMarker ++) { + for (auto jMarker = 0u; jMarker < fine_grid->GetnMarker() && counter < 3; jMarker++) { if (fine_grid->nodes->GetVertex(iPoint, jMarker) != -1) { copy_marker[counter] = jMarker; counter++; @@ -123,8 +117,7 @@ CMultiGridGeometry::CMultiGridGeometry(CGeometry *fine_grid, CConfig *config, un if ((config->GetMarker_All_KindBC(copy_marker[0]) == SEND_RECEIVE) || (config->GetMarker_All_KindBC(copy_marker[1]) == SEND_RECEIVE)) { agglomerate_seed = true; - } - else { + } else { agglomerate_seed = false; } } @@ -136,15 +129,12 @@ CMultiGridGeometry::CMultiGridGeometry(CGeometry *fine_grid, CConfig *config, un /*--- If the seed can be agglomerated, we try to agglomerate more points ---*/ if (agglomerate_seed) { - /*--- Now we do a sweep over all the nodes that surround the seed point ---*/ for (auto CVPoint : fine_grid->nodes->GetPoints(iPoint)) { - /*--- The new point can be agglomerated ---*/ if (SetBoundAgglomeration(CVPoint, marker_seed, fine_grid, config)) { - /*--- We set the value of the parent ---*/ fine_grid->nodes->SetParent_CV(CVPoint, Index_CoarseCV); @@ -154,7 +144,6 @@ CMultiGridGeometry::CMultiGridGeometry(CGeometry *fine_grid, CConfig *config, un nodes->SetChildren_CV(Index_CoarseCV, nChildren, CVPoint); nChildren++; } - } Suitable_Indirect_Neighbors.clear(); @@ -165,11 +154,9 @@ CMultiGridGeometry::CMultiGridGeometry(CGeometry *fine_grid, CConfig *config, un /*--- Now we do a sweep over all the indirect nodes that can be added ---*/ for (auto CVPoint : Suitable_Indirect_Neighbors) { - /*--- The new point can be agglomerated ---*/ if (SetBoundAgglomeration(CVPoint, marker_seed, fine_grid, config)) { - /*--- We set the value of the parent ---*/ fine_grid->nodes->SetParent_CV(CVPoint, Index_CoarseCV); @@ -186,7 +173,6 @@ CMultiGridGeometry::CMultiGridGeometry(CGeometry *fine_grid, CConfig *config, un nChildren++; } } - } /*--- Update the number of children of the coarse control volume. ---*/ @@ -204,8 +190,7 @@ CMultiGridGeometry::CMultiGridGeometry(CGeometry *fine_grid, CConfig *config, un for (auto iVertex = 0ul; iVertex < fine_grid->GetnVertex(iMarker); iVertex++) { const auto iPoint = fine_grid->vertex[iMarker][iVertex]->GetNode(); - if ((fine_grid->nodes->GetAgglomerate(iPoint) == false) && - (fine_grid->nodes->GetDomain(iPoint))) { + if ((fine_grid->nodes->GetAgglomerate(iPoint) == false) && (fine_grid->nodes->GetDomain(iPoint))) { fine_grid->nodes->SetParent_CV(iPoint, Index_CoarseCV); nodes->SetChildren_CV(Index_CoarseCV, 0, iPoint); nodes->SetnChildren_CV(Index_CoarseCV, 1); @@ -216,14 +201,11 @@ CMultiGridGeometry::CMultiGridGeometry(CGeometry *fine_grid, CConfig *config, un /*--- Update the queue with the results from the boundary agglomeration ---*/ - for (auto iPoint = 0ul; iPoint < fine_grid->GetnPoint(); iPoint ++) { - + for (auto iPoint = 0ul; iPoint < fine_grid->GetnPoint(); iPoint++) { if (fine_grid->nodes->GetAgglomerate(iPoint)) { - MGQueue_InnerCV.RemoveCV(iPoint); - } - else { + } else { /*--- Count the number of agglomerated neighbors, and modify the queue, Points with more agglomerated neighbors are processed first. ---*/ @@ -239,17 +221,14 @@ CMultiGridGeometry::CMultiGridGeometry(CGeometry *fine_grid, CConfig *config, un auto iteration = 0ul; while (!MGQueue_InnerCV.EmptyQueue() && (iteration < fine_grid->GetnPoint())) { - const auto iPoint = MGQueue_InnerCV.NextCV(); iteration++; /*--- If the element has not being previously agglomerated, belongs to the physical domain, and satisfies several geometrical criteria then the seed CV is accepted for agglomeration. ---*/ - if ((fine_grid->nodes->GetAgglomerate(iPoint) == false) && - (fine_grid->nodes->GetDomain(iPoint)) && + if ((fine_grid->nodes->GetAgglomerate(iPoint) == false) && (fine_grid->nodes->GetDomain(iPoint)) && (GeometricalCheck(iPoint, fine_grid, config))) { - unsigned short nChildren = 1; /*--- We set an index for the parent control volume ---*/ @@ -268,13 +247,10 @@ CMultiGridGeometry::CMultiGridGeometry(CGeometry *fine_grid, CConfig *config, un /*--- Now we do a sweep over all the nodes that surround the seed point ---*/ for (auto CVPoint : fine_grid->nodes->GetPoints(iPoint)) { - /*--- Determine if the CVPoint can be agglomerated ---*/ - if ((fine_grid->nodes->GetAgglomerate(CVPoint) == false) && - (fine_grid->nodes->GetDomain(CVPoint)) && + if ((fine_grid->nodes->GetAgglomerate(CVPoint) == false) && (fine_grid->nodes->GetDomain(CVPoint)) && (GeometricalCheck(CVPoint, fine_grid, config))) { - /*--- We set the value of the parent ---*/ fine_grid->nodes->SetParent_CV(CVPoint, Index_CoarseCV); @@ -288,9 +264,7 @@ CMultiGridGeometry::CMultiGridGeometry(CGeometry *fine_grid, CConfig *config, un increase the priority of its neighbors) ---*/ MGQueue_InnerCV.Update(CVPoint, fine_grid); - } - } /*--- Identify the indirect neighbors ---*/ @@ -302,20 +276,16 @@ CMultiGridGeometry::CMultiGridGeometry(CGeometry *fine_grid, CConfig *config, un /*--- Now we do a sweep over all the indirect nodes that can be added ---*/ for (auto CVPoint : Suitable_Indirect_Neighbors) { - /*--- The new point can be agglomerated ---*/ - if ((fine_grid->nodes->GetAgglomerate(CVPoint) == false) && - (fine_grid->nodes->GetDomain(CVPoint))) { - + if ((fine_grid->nodes->GetAgglomerate(CVPoint) == false) && (fine_grid->nodes->GetDomain(CVPoint))) { /*--- We set the value of the parent ---*/ fine_grid->nodes->SetParent_CV(CVPoint, Index_CoarseCV); /*--- We set the indirect agglomeration information ---*/ - if (fine_grid->nodes->GetAgglomerate_Indirect(CVPoint)) - nodes->SetAgglomerate_Indirect(Index_CoarseCV, true); + if (fine_grid->nodes->GetAgglomerate_Indirect(CVPoint)) nodes->SetAgglomerate_Indirect(Index_CoarseCV, true); /*--- We set the value of the child ---*/ @@ -326,7 +296,6 @@ CMultiGridGeometry::CMultiGridGeometry(CGeometry *fine_grid, CConfig *config, un increase the priority of the neighbors) ---*/ MGQueue_InnerCV.Update(CVPoint, fine_grid); - } } @@ -334,26 +303,20 @@ CMultiGridGeometry::CMultiGridGeometry(CGeometry *fine_grid, CConfig *config, un nodes->SetnChildren_CV(Index_CoarseCV, nChildren); Index_CoarseCV++; - } - else { - + } else { /*--- The seed point can not be agglomerated because of size, domain, streching, etc. move the point to the lowest priority ---*/ MGQueue_InnerCV.MoveCV(iPoint, -1); } - } /*--- Convert any point that was not agglomerated into a coarse point. ---*/ for (auto iPoint = 0ul; iPoint < fine_grid->GetnPoint(); iPoint++) { - if ((fine_grid->nodes->GetAgglomerate(iPoint) == false) && - (fine_grid->nodes->GetDomain(iPoint))) { - + if ((fine_grid->nodes->GetAgglomerate(iPoint) == false) && (fine_grid->nodes->GetDomain(iPoint))) { fine_grid->nodes->SetParent_CV(iPoint, Index_CoarseCV); - if (fine_grid->nodes->GetAgglomerate_Indirect(iPoint)) - nodes->SetAgglomerate_Indirect(Index_CoarseCV, true); + if (fine_grid->nodes->GetAgglomerate_Indirect(iPoint)) nodes->SetAgglomerate_Indirect(Index_CoarseCV, true); nodes->SetChildren_CV(Index_CoarseCV, 0, iPoint); nodes->SetnChildren_CV(Index_CoarseCV, 1); Index_CoarseCV++; @@ -369,9 +332,7 @@ CMultiGridGeometry::CMultiGridGeometry(CGeometry *fine_grid, CConfig *config, un SetPoint_Connectivity(fine_grid); for (auto iCoarsePoint = 0ul; iCoarsePoint < nPointDomain; iCoarsePoint++) { - if (nodes->GetnPoint(iCoarsePoint) == 1) { - /*--- Find the neighbor of the isolated point. This neighbor is the right control volume ---*/ const auto iCoarsePoint_Complete = nodes->GetPoint(iCoarsePoint, 0); @@ -395,7 +356,6 @@ CMultiGridGeometry::CMultiGridGeometry(CGeometry *fine_grid, CConfig *config, un nodes->SetnChildren_CV(iCoarsePoint_Complete, nChildren); nodes->SetnChildren_CV(iCoarsePoint, 0); } - } /*--- Reset the neighbor information. ---*/ @@ -409,10 +369,7 @@ CMultiGridGeometry::CMultiGridGeometry(CGeometry *fine_grid, CConfig *config, un they are domain points. ---*/ for (auto iMarker = 0u; iMarker < config->GetnMarker_All(); iMarker++) { - - if ((config->GetMarker_All_KindBC(iMarker) == SEND_RECEIVE) && - (config->GetMarker_All_SendRecv(iMarker) > 0)) { - + if ((config->GetMarker_All_KindBC(iMarker) == SEND_RECEIVE) && (config->GetMarker_All_SendRecv(iMarker) > 0)) { const auto MarkerS = iMarker; const auto MarkerR = iMarker + 1; @@ -444,8 +401,8 @@ CMultiGridGeometry::CMultiGridGeometry(CGeometry *fine_grid, CConfig *config, un Buffer_Receive_Children.data(), nVertexR, MPI_UNSIGNED_LONG, receive_from, 0, SU2_MPI::GetComm(), MPI_STATUS_IGNORE); SU2_MPI::Sendrecv(Buffer_Send_Parent.data(), nVertexS, MPI_UNSIGNED_LONG, send_to, 1, - Buffer_Receive_Parent.data(), nVertexR, MPI_UNSIGNED_LONG, receive_from, 1, - SU2_MPI::GetComm(), MPI_STATUS_IGNORE); + Buffer_Receive_Parent.data(), nVertexR, MPI_UNSIGNED_LONG, receive_from, 1, SU2_MPI::GetComm(), + MPI_STATUS_IGNORE); /*--- Create a list of the parent nodes without duplicates. ---*/ @@ -462,7 +419,6 @@ CMultiGridGeometry::CMultiGridGeometry(CGeometry *fine_grid, CConfig *config, un vector Children_Local(nVertexR); for (auto iVertex = 0ul; iVertex < nVertexR; iVertex++) { - /*--- We use the same sorting as in the donor domain, i.e. the local parents are numbered according to their order in the remote rank. ---*/ @@ -493,11 +449,9 @@ CMultiGridGeometry::CMultiGridGeometry(CGeometry *fine_grid, CConfig *config, un nodes->SetnChildren_CV(iPoint_Coarse, nChildren_MPI[iPoint_Coarse]); nodes->SetDomain(iPoint_Coarse, false); } - } - } -#endif // HAVE_MPI +#endif // HAVE_MPI /*--- Update the number of points after the MPI agglomeration ---*/ @@ -516,17 +470,15 @@ CMultiGridGeometry::CMultiGridGeometry(CGeometry *fine_grid, CConfig *config, un if (iMesh != MESH_0) { const su2double factor = 1.5; const su2double Coeff = pow(su2double(Global_nPointFine) / Global_nPointCoarse, 1.0 / nDim); - const su2double CFL = factor * config->GetCFL(iMesh-1) / Coeff; + const su2double CFL = factor * config->GetCFL(iMesh - 1) / Coeff; config->SetCFL(iMesh, CFL); } const su2double ratio = su2double(Global_nPointFine) / su2double(Global_nPointCoarse); - if (((nDim == 2) && (ratio < 2.5)) || - ((nDim == 3) && (ratio < 2.5))) { - config->SetMGLevels(iMesh-1); - } - else if (rank == MASTER_NODE) { + if (((nDim == 2) && (ratio < 2.5)) || ((nDim == 3) && (ratio < 2.5))) { + config->SetMGLevels(iMesh - 1); + } else if (rank == MASTER_NODE) { PrintingToolbox::CTablePrinter MGTable(&std::cout); MGTable.AddColumn("MG Level", 10); MGTable.AddColumn("CVs", 10); @@ -534,37 +486,33 @@ CMultiGridGeometry::CMultiGridGeometry(CGeometry *fine_grid, CConfig *config, un MGTable.AddColumn("CFL", 10); MGTable.SetAlign(PrintingToolbox::CTablePrinter::RIGHT); - if (iMesh == MESH_1){ + if (iMesh == MESH_1) { MGTable.PrintHeader(); - MGTable << iMesh - 1 << Global_nPointFine << "1/1.00" << config->GetCFL(iMesh -1); + MGTable << iMesh - 1 << Global_nPointFine << "1/1.00" << config->GetCFL(iMesh - 1); } stringstream ss; ss << "1/" << std::setprecision(3) << ratio; MGTable << iMesh << Global_nPointCoarse << ss.str() << config->GetCFL(iMesh); - if (iMesh == config->GetnMGLevels()){ + if (iMesh == config->GetnMGLevels()) { MGTable.PrintFooter(); } } edgeColorGroupSize = config->GetEdgeColoringGroupSize(); - } -bool CMultiGridGeometry::SetBoundAgglomeration(unsigned long CVPoint, short marker_seed, - const CGeometry *fine_grid, const CConfig *config) const { +bool CMultiGridGeometry::SetBoundAgglomeration(unsigned long CVPoint, short marker_seed, const CGeometry* fine_grid, + const CConfig* config) const { bool agglomerate_CV = false; /*--- Basic condition, the point has not being previously agglomerated, it belongs to the domain, and has passed some basic geometrical checks. ---*/ - if ((fine_grid->nodes->GetAgglomerate(CVPoint) == false) && - (fine_grid->nodes->GetDomain(CVPoint)) && + if ((fine_grid->nodes->GetAgglomerate(CVPoint) == false) && (fine_grid->nodes->GetDomain(CVPoint)) && (GeometricalCheck(CVPoint, fine_grid, config))) { - /*--- If the point belongs to a boundary, its type must be compatible with the seed marker. ---*/ if (fine_grid->nodes->GetBoundary(CVPoint)) { - /*--- Identify the markers of the vertex that we want to agglomerate ---*/ int counter = 0; @@ -582,58 +530,51 @@ bool CMultiGridGeometry::SetBoundAgglomeration(unsigned long CVPoint, short mark /*--- Only one marker in the vertex that is going to be aglomerated ---*/ if (counter == 1) { - /*--- We agglomerate if there is only a marker and is the same marker as the seed marker ---*/ - if (copy_marker[0] == marker_seed) - agglomerate_CV = true; + if (copy_marker[0] == marker_seed) agglomerate_CV = true; /*--- If there is only one marker, but the marker is the SEND_RECEIVE ---*/ - if (config->GetMarker_All_KindBC(copy_marker[0]) == SEND_RECEIVE) - agglomerate_CV = true; - + if (config->GetMarker_All_KindBC(copy_marker[0]) == SEND_RECEIVE) agglomerate_CV = true; } /*--- If there are two markers in the vertex that is going to be aglomerated ---*/ if (counter == 2) { - /*--- First we verify that the seed is a physical boundary ---*/ if (config->GetMarker_All_KindBC(marker_seed) != SEND_RECEIVE) { - /*--- Then we check that one of the marker is equal to the seed marker, and the other is send/receive ---*/ if (((copy_marker[0] == marker_seed) && (config->GetMarker_All_KindBC(copy_marker[1]) == SEND_RECEIVE)) || ((config->GetMarker_All_KindBC(copy_marker[0]) == SEND_RECEIVE) && (copy_marker[1] == marker_seed))) agglomerate_CV = true; } - } } /*--- If the element belongs to the domain, it is allways aglomerated. ---*/ - else { agglomerate_CV = true; } - + else { + agglomerate_CV = true; + } } return agglomerate_CV; } - -bool CMultiGridGeometry::GeometricalCheck(unsigned long iPoint, const CGeometry *fine_grid, const CConfig *config) const { - +bool CMultiGridGeometry::GeometricalCheck(unsigned long iPoint, const CGeometry* fine_grid, + const CConfig* config) const { su2double max_dimension = 1.2; /*--- Evaluate the total size of the element ---*/ bool Volume = true; - su2double ratio = pow(fine_grid->nodes->GetVolume(iPoint), 1.0/su2double(nDim))*max_dimension; - su2double limit = pow(config->GetDomainVolume(), 1.0/su2double(nDim)); - if ( ratio > limit ) Volume = false; + su2double ratio = pow(fine_grid->nodes->GetVolume(iPoint), 1.0 / su2double(nDim)) * max_dimension; + su2double limit = pow(config->GetDomainVolume(), 1.0 / su2double(nDim)); + if (ratio > limit) Volume = false; /*--- Evaluate the stretching of the element ---*/ @@ -656,27 +597,22 @@ bool CMultiGridGeometry::GeometricalCheck(unsigned long iPoint, const CGeometry if ( max_dist/min_dist > 100.0 ) Stretching = false;*/ return (Stretching && Volume); - } void CMultiGridGeometry::SetSuitableNeighbors(vector& Suitable_Indirect_Neighbors, unsigned long iPoint, - unsigned long Index_CoarseCV, const CGeometry *fine_grid) const { - + unsigned long Index_CoarseCV, const CGeometry* fine_grid) const { /*--- Create a list with the first neighbors, including the seed. ---*/ vector First_Neighbor_Points; First_Neighbor_Points.push_back(iPoint); - for (auto jPoint : fine_grid->nodes->GetPoints(iPoint)) - First_Neighbor_Points.push_back(jPoint); + for (auto jPoint : fine_grid->nodes->GetPoints(iPoint)) First_Neighbor_Points.push_back(jPoint); /*--- Create a list with the second neighbors, without first, and seed neighbors. ---*/ vector Second_Neighbor_Points, Second_Origin_Points, Suitable_Second_Neighbors; for (auto jPoint : fine_grid->nodes->GetPoints(iPoint)) { - for (auto kPoint : fine_grid->nodes->GetPoints(jPoint)) { - /*--- Check that the second neighbor does not belong to the first neighbors or the seed. ---*/ auto end = First_Neighbor_Points.end(); @@ -692,21 +628,17 @@ void CMultiGridGeometry::SetSuitableNeighbors(vector& Suitable_In neighbors, and for hexs it produces a 27-point stencil. ---*/ for (auto iNeighbor = 0ul; iNeighbor < Second_Neighbor_Points.size(); iNeighbor++) { - - for (auto jNeighbor = iNeighbor+1; jNeighbor < Second_Neighbor_Points.size(); jNeighbor++) { - + for (auto jNeighbor = iNeighbor + 1; jNeighbor < Second_Neighbor_Points.size(); jNeighbor++) { /*--- Repeated second neighbor with different origin ---*/ if ((Second_Neighbor_Points[iNeighbor] == Second_Neighbor_Points[jNeighbor]) && (Second_Origin_Points[iNeighbor] != Second_Origin_Points[jNeighbor])) { - Suitable_Indirect_Neighbors.push_back(Second_Neighbor_Points[iNeighbor]); /*--- Create a list of suitable second neighbors, that we will use to compute the third neighbors. --*/ Suitable_Second_Neighbors.push_back(Second_Neighbor_Points[iNeighbor]); - } } } @@ -725,7 +657,6 @@ void CMultiGridGeometry::SetSuitableNeighbors(vector& Suitable_In for (auto kPoint : Suitable_Second_Neighbors) { for (auto lPoint : fine_grid->nodes->GetPoints(kPoint)) { - /*--- Check that the third neighbor does not belong to the first neighbors or the seed ---*/ auto end1 = First_Neighbor_Points.end(); @@ -743,14 +674,12 @@ void CMultiGridGeometry::SetSuitableNeighbors(vector& Suitable_In /*--- Identify those third neighbors that are repeated (candidate to be added). ---*/ - for (auto iNeighbor = 0ul; iNeighbor < Third_Neighbor_Points.size(); iNeighbor ++) { - for (auto jNeighbor = iNeighbor+1; jNeighbor < Third_Neighbor_Points.size(); jNeighbor ++) { - + for (auto iNeighbor = 0ul; iNeighbor < Third_Neighbor_Points.size(); iNeighbor++) { + for (auto jNeighbor = iNeighbor + 1; jNeighbor < Third_Neighbor_Points.size(); jNeighbor++) { /*--- Repeated third neighbor with different origin ---*/ if ((Third_Neighbor_Points[iNeighbor] == Third_Neighbor_Points[jNeighbor]) && (Third_Origin_Points[iNeighbor] != Third_Origin_Points[jNeighbor])) { - Suitable_Indirect_Neighbors.push_back(Third_Neighbor_Points[iNeighbor]); } } @@ -761,11 +690,9 @@ void CMultiGridGeometry::SetSuitableNeighbors(vector& Suitable_In sort(Suitable_Indirect_Neighbors.begin(), Suitable_Indirect_Neighbors.end()); auto it2 = unique(Suitable_Indirect_Neighbors.begin(), Suitable_Indirect_Neighbors.end()); Suitable_Indirect_Neighbors.resize(it2 - Suitable_Indirect_Neighbors.begin()); - } -void CMultiGridGeometry::SetPoint_Connectivity(const CGeometry *fine_grid) { - +void CMultiGridGeometry::SetPoint_Connectivity(const CGeometry* fine_grid) { /*--- Temporary, CPoint (nodes) then compresses this structure. ---*/ vector > points(nPoint); @@ -780,8 +707,7 @@ void CMultiGridGeometry::SetPoint_Connectivity(const CGeometry *fine_grid) { if (iParent != iCoarsePoint) { /*--- Avoid duplicates. ---*/ auto End = points[iCoarsePoint].end(); - if (find(points[iCoarsePoint].begin(), End, iParent) == End) - points[iCoarsePoint].push_back(iParent); + if (find(points[iCoarsePoint].begin(), End, iParent) == End) points[iCoarsePoint].push_back(iParent); } } } @@ -792,11 +718,10 @@ void CMultiGridGeometry::SetPoint_Connectivity(const CGeometry *fine_grid) { } nodes->SetPoints(points); - } -void CMultiGridGeometry::SetVertex(const CGeometry *fine_grid, const CConfig *config) { - unsigned long iVertex, iFinePoint, iCoarsePoint; +void CMultiGridGeometry::SetVertex(const CGeometry* fine_grid, const CConfig* config) { + unsigned long iVertex, iFinePoint, iCoarsePoint; unsigned short iMarker, iMarker_Tag, iChildren; nMarker = fine_grid->GetnMarker(); @@ -804,8 +729,8 @@ void CMultiGridGeometry::SetVertex(const CGeometry *fine_grid, const CConfig *co /*--- If any children node belong to the boundary then the entire control volume will belong to the boundary ---*/ - for (iCoarsePoint = 0; iCoarsePoint < nPoint; iCoarsePoint ++) - for (iChildren = 0; iChildren < nodes->GetnChildren_CV(iCoarsePoint); iChildren ++) { + for (iCoarsePoint = 0; iCoarsePoint < nPoint; iCoarsePoint++) + for (iChildren = 0; iChildren < nodes->GetnChildren_CV(iCoarsePoint); iChildren++) { iFinePoint = nodes->GetChildren_CV(iCoarsePoint, iChildren); if (fine_grid->nodes->GetBoundary(iFinePoint)) { nodes->SetBoundary(iCoarsePoint, nMarker); @@ -814,22 +739,22 @@ void CMultiGridGeometry::SetVertex(const CGeometry *fine_grid, const CConfig *co } vertex = new CVertex**[nMarker]; - nVertex = new unsigned long [nMarker]; + nVertex = new unsigned long[nMarker]; - Tag_to_Marker = new string [nMarker_Max]; + Tag_to_Marker = new string[nMarker_Max]; for (iMarker_Tag = 0; iMarker_Tag < nMarker_Max; iMarker_Tag++) Tag_to_Marker[iMarker_Tag] = fine_grid->GetMarker_Tag(iMarker_Tag); /*--- Compute the number of vertices to do the dimensionalization ---*/ for (iMarker = 0; iMarker < nMarker; iMarker++) nVertex[iMarker] = 0; - - for (iCoarsePoint = 0; iCoarsePoint < nPoint; iCoarsePoint ++) { + for (iCoarsePoint = 0; iCoarsePoint < nPoint; iCoarsePoint++) { if (nodes->GetBoundary(iCoarsePoint)) { - for (iChildren = 0; iChildren < nodes->GetnChildren_CV(iCoarsePoint); iChildren ++) { + for (iChildren = 0; iChildren < nodes->GetnChildren_CV(iCoarsePoint); iChildren++) { iFinePoint = nodes->GetChildren_CV(iCoarsePoint, iChildren); - for (iMarker = 0; iMarker < nMarker; iMarker ++) { - if ((fine_grid->nodes->GetVertex(iFinePoint, iMarker) != -1) && (nodes->GetVertex(iCoarsePoint, iMarker) == -1)) { + for (iMarker = 0; iMarker < nMarker; iMarker++) { + if ((fine_grid->nodes->GetVertex(iFinePoint, iMarker) != -1) && + (nodes->GetVertex(iCoarsePoint, iMarker) == -1)) { iVertex = nVertex[iMarker]; nodes->SetVertex(iCoarsePoint, iVertex, iMarker); nVertex[iMarker]++; @@ -840,23 +765,23 @@ void CMultiGridGeometry::SetVertex(const CGeometry *fine_grid, const CConfig *co } for (iMarker = 0; iMarker < nMarker; iMarker++) { - vertex[iMarker] = new CVertex* [fine_grid->GetnVertex(iMarker)+1]; + vertex[iMarker] = new CVertex*[fine_grid->GetnVertex(iMarker) + 1]; nVertex[iMarker] = 0; } - for (iCoarsePoint = 0; iCoarsePoint < nPoint; iCoarsePoint ++) + for (iCoarsePoint = 0; iCoarsePoint < nPoint; iCoarsePoint++) if (nodes->GetBoundary(iCoarsePoint)) - for (iMarker = 0; iMarker < nMarker; iMarker ++) - nodes->SetVertex(iCoarsePoint, -1, iMarker); + for (iMarker = 0; iMarker < nMarker; iMarker++) nodes->SetVertex(iCoarsePoint, -1, iMarker); for (iMarker = 0; iMarker < nMarker; iMarker++) nVertex[iMarker] = 0; - for (iCoarsePoint = 0; iCoarsePoint < nPoint; iCoarsePoint ++) { + for (iCoarsePoint = 0; iCoarsePoint < nPoint; iCoarsePoint++) { if (nodes->GetBoundary(iCoarsePoint)) { - for (iChildren = 0; iChildren < nodes->GetnChildren_CV(iCoarsePoint); iChildren ++) { + for (iChildren = 0; iChildren < nodes->GetnChildren_CV(iCoarsePoint); iChildren++) { iFinePoint = nodes->GetChildren_CV(iCoarsePoint, iChildren); - for (iMarker = 0; iMarker < fine_grid->GetnMarker(); iMarker ++) { - if ((fine_grid->nodes->GetVertex(iFinePoint, iMarker) != -1) && (nodes->GetVertex(iCoarsePoint, iMarker) == -1)) { + for (iMarker = 0; iMarker < fine_grid->GetnMarker(); iMarker++) { + if ((fine_grid->nodes->GetVertex(iFinePoint, iMarker) != -1) && + (nodes->GetVertex(iCoarsePoint, iMarker) == -1)) { iVertex = nVertex[iMarker]; vertex[iMarker][iVertex] = new CVertex(iCoarsePoint, nDim); nodes->SetVertex(iCoarsePoint, iVertex, iMarker); @@ -873,8 +798,7 @@ void CMultiGridGeometry::SetVertex(const CGeometry *fine_grid, const CConfig *co } } -void CMultiGridGeometry::MatchActuator_Disk(const CConfig *config) { - +void CMultiGridGeometry::MatchActuator_Disk(const CConfig* config) { unsigned short iMarker; unsigned long iVertex, iPoint; int iProcessor = size; @@ -890,11 +814,9 @@ void CMultiGridGeometry::MatchActuator_Disk(const CConfig *config) { } } } - } -void CMultiGridGeometry::MatchPeriodic(const CConfig *config, unsigned short val_periodic) { - +void CMultiGridGeometry::MatchPeriodic(const CConfig* config, unsigned short val_periodic) { unsigned short iMarker, iPeriodic, nPeriodic; unsigned long iVertex, iPoint; int iProcessor = rank; @@ -906,133 +828,123 @@ void CMultiGridGeometry::MatchPeriodic(const CConfig *config, unsigned short val for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { if (config->GetMarker_All_KindBC(iMarker) == PERIODIC_BOUNDARY) { iPeriodic = config->GetMarker_All_PerBound(iMarker); - if ((iPeriodic == val_periodic) || - (iPeriodic == val_periodic + nPeriodic/2)) { + if ((iPeriodic == val_periodic) || (iPeriodic == val_periodic + nPeriodic / 2)) { for (iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { iPoint = vertex[iMarker][iVertex]->GetNode(); if (nodes->GetDomain(iPoint)) { - vertex[iMarker][iVertex]->SetDonorPoint(iPoint, nodes->GetGlobalIndex(iPoint), iVertex, iMarker, iProcessor); + vertex[iMarker][iVertex]->SetDonorPoint(iPoint, nodes->GetGlobalIndex(iPoint), iVertex, iMarker, + iProcessor); } } } } } - } -void CMultiGridGeometry::SetControlVolume(const CGeometry *fine_grid, unsigned short action) { - +void CMultiGridGeometry::SetControlVolume(const CGeometry* fine_grid, unsigned short action) { BEGIN_SU2_OMP_SAFE_GLOBAL_ACCESS { - - unsigned long iFinePoint, iCoarsePoint, iEdge, iParent; - long FineEdge, CoarseEdge; - unsigned short iChildren; - bool change_face_orientation; - su2double Coarse_Volume, Area; - - /*--- Compute the area of the coarse volume ---*/ - for (iCoarsePoint = 0; iCoarsePoint < nPoint; iCoarsePoint ++) { - nodes->SetVolume(iCoarsePoint, 0.0); - Coarse_Volume = 0.0; - for (iChildren = 0; iChildren < nodes->GetnChildren_CV(iCoarsePoint); iChildren ++) { - iFinePoint = nodes->GetChildren_CV(iCoarsePoint, iChildren); - Coarse_Volume += fine_grid->nodes->GetVolume(iFinePoint); + unsigned long iFinePoint, iCoarsePoint, iEdge, iParent; + long FineEdge, CoarseEdge; + unsigned short iChildren; + bool change_face_orientation; + su2double Coarse_Volume, Area; + + /*--- Compute the area of the coarse volume ---*/ + for (iCoarsePoint = 0; iCoarsePoint < nPoint; iCoarsePoint++) { + nodes->SetVolume(iCoarsePoint, 0.0); + Coarse_Volume = 0.0; + for (iChildren = 0; iChildren < nodes->GetnChildren_CV(iCoarsePoint); iChildren++) { + iFinePoint = nodes->GetChildren_CV(iCoarsePoint, iChildren); + Coarse_Volume += fine_grid->nodes->GetVolume(iFinePoint); + } + nodes->SetVolume(iCoarsePoint, Coarse_Volume); } - nodes->SetVolume(iCoarsePoint, Coarse_Volume); - } - - /*--- Update or not the values of faces at the edge ---*/ - if (action != ALLOCATE) { - edges->SetZeroValues(); - } - for (iCoarsePoint = 0; iCoarsePoint < nPoint; iCoarsePoint ++) - for (iChildren = 0; iChildren < nodes->GetnChildren_CV(iCoarsePoint); iChildren ++) { - iFinePoint = nodes->GetChildren_CV(iCoarsePoint, iChildren); + /*--- Update or not the values of faces at the edge ---*/ + if (action != ALLOCATE) { + edges->SetZeroValues(); + } - for (auto iFinePoint_Neighbor : fine_grid->nodes->GetPoints(iFinePoint)) { - iParent = fine_grid->nodes->GetParent_CV(iFinePoint_Neighbor); - if ((iParent != iCoarsePoint) && (iParent < iCoarsePoint)) { + for (iCoarsePoint = 0; iCoarsePoint < nPoint; iCoarsePoint++) + for (iChildren = 0; iChildren < nodes->GetnChildren_CV(iCoarsePoint); iChildren++) { + iFinePoint = nodes->GetChildren_CV(iCoarsePoint, iChildren); - FineEdge = fine_grid->FindEdge(iFinePoint, iFinePoint_Neighbor); + for (auto iFinePoint_Neighbor : fine_grid->nodes->GetPoints(iFinePoint)) { + iParent = fine_grid->nodes->GetParent_CV(iFinePoint_Neighbor); + if ((iParent != iCoarsePoint) && (iParent < iCoarsePoint)) { + FineEdge = fine_grid->FindEdge(iFinePoint, iFinePoint_Neighbor); - change_face_orientation = false; - if (iFinePoint < iFinePoint_Neighbor) change_face_orientation = true; + change_face_orientation = false; + if (iFinePoint < iFinePoint_Neighbor) change_face_orientation = true; - CoarseEdge = FindEdge(iParent, iCoarsePoint); + CoarseEdge = FindEdge(iParent, iCoarsePoint); - const auto Normal = fine_grid->edges->GetNormal(FineEdge); + const auto Normal = fine_grid->edges->GetNormal(FineEdge); - if (change_face_orientation) { - edges->SubNormal(CoarseEdge,Normal); - } - else { - edges->AddNormal(CoarseEdge,Normal); + if (change_face_orientation) { + edges->SubNormal(CoarseEdge, Normal); + } else { + edges->AddNormal(CoarseEdge, Normal); + } } } } - } - /*--- Check if there is a normal with null area ---*/ + /*--- Check if there is a normal with null area ---*/ - for (iEdge = 0; iEdge < nEdge; iEdge++) { - const auto NormalFace = edges->GetNormal(iEdge); - Area = GeometryToolbox::Norm(nDim, NormalFace); - if (Area == 0.0) { - su2double DefaultNormal[3] = {EPS*EPS}; - edges->SetNormal(iEdge, DefaultNormal); + for (iEdge = 0; iEdge < nEdge; iEdge++) { + const auto NormalFace = edges->GetNormal(iEdge); + Area = GeometryToolbox::Norm(nDim, NormalFace); + if (Area == 0.0) { + su2double DefaultNormal[3] = {EPS * EPS}; + edges->SetNormal(iEdge, DefaultNormal); + } } } - - } END_SU2_OMP_SAFE_GLOBAL_ACCESS } -void CMultiGridGeometry::SetBoundControlVolume(const CGeometry *fine_grid, unsigned short action) { - +void CMultiGridGeometry::SetBoundControlVolume(const CGeometry* fine_grid, unsigned short action) { BEGIN_SU2_OMP_SAFE_GLOBAL_ACCESS { + unsigned long iCoarsePoint, iFinePoint, FineVertex, iVertex; + unsigned short iMarker, iChildren, iDim; + su2double *Normal, Area, *NormalFace = nullptr; - unsigned long iCoarsePoint, iFinePoint, FineVertex, iVertex; - unsigned short iMarker, iChildren, iDim; - su2double *Normal, Area, *NormalFace = nullptr; + Normal = new su2double[nDim]; - Normal = new su2double [nDim]; + if (action != ALLOCATE) { + for (iMarker = 0; iMarker < nMarker; iMarker++) + for (iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) vertex[iMarker][iVertex]->SetZeroValues(); + } - if (action != ALLOCATE) { for (iMarker = 0; iMarker < nMarker; iMarker++) - for (iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) - vertex[iMarker][iVertex]->SetZeroValues(); - } - - for (iMarker = 0; iMarker < nMarker; iMarker ++) - for (iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { - iCoarsePoint = vertex[iMarker][iVertex]->GetNode(); - for (iChildren = 0; iChildren < nodes->GetnChildren_CV(iCoarsePoint); iChildren ++) { - iFinePoint = nodes->GetChildren_CV(iCoarsePoint, iChildren); - if (fine_grid->nodes->GetVertex(iFinePoint, iMarker)!=-1) { - FineVertex = fine_grid->nodes->GetVertex(iFinePoint, iMarker); - fine_grid->vertex[iMarker][FineVertex]->GetNormal(Normal); - vertex[iMarker][iVertex]->AddNormal(Normal); + for (iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { + iCoarsePoint = vertex[iMarker][iVertex]->GetNode(); + for (iChildren = 0; iChildren < nodes->GetnChildren_CV(iCoarsePoint); iChildren++) { + iFinePoint = nodes->GetChildren_CV(iCoarsePoint, iChildren); + if (fine_grid->nodes->GetVertex(iFinePoint, iMarker) != -1) { + FineVertex = fine_grid->nodes->GetVertex(iFinePoint, iMarker); + fine_grid->vertex[iMarker][FineVertex]->GetNormal(Normal); + vertex[iMarker][iVertex]->AddNormal(Normal); + } } } - } - delete[] Normal; - - /*--- Check if there is a normal with null area ---*/ - for (iMarker = 0; iMarker < nMarker; iMarker ++) - for (iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { - NormalFace = vertex[iMarker][iVertex]->GetNormal(); - Area = GeometryToolbox::Norm(nDim, NormalFace); - if (Area == 0.0) for (iDim = 0; iDim < nDim; iDim++) NormalFace[iDim] = EPS*EPS; - } + delete[] Normal; + /*--- Check if there is a normal with null area ---*/ + for (iMarker = 0; iMarker < nMarker; iMarker++) + for (iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { + NormalFace = vertex[iMarker][iVertex]->GetNormal(); + Area = GeometryToolbox::Norm(nDim, NormalFace); + if (Area == 0.0) + for (iDim = 0; iDim < nDim; iDim++) NormalFace[iDim] = EPS * EPS; + } } END_SU2_OMP_SAFE_GLOBAL_ACCESS } -void CMultiGridGeometry::SetCoord(const CGeometry *fine_grid) { - +void CMultiGridGeometry::SetCoord(const CGeometry* fine_grid) { SU2_OMP_FOR_STAT(roundUpDiv(nPoint, omp_get_max_threads())) for (auto Point_Coarse = 0ul; Point_Coarse < nPoint; Point_Coarse++) { auto Area_Parent = nodes->GetVolume(Point_Coarse); @@ -1042,15 +954,14 @@ void CMultiGridGeometry::SetCoord(const CGeometry *fine_grid) { auto Area_Children = fine_grid->nodes->GetVolume(Point_Fine); auto Coordinates_Fine = fine_grid->nodes->GetCoord(Point_Fine); for (auto iDim = 0u; iDim < nDim; iDim++) - Coordinates[iDim] += Coordinates_Fine[iDim]*Area_Children/Area_Parent; + Coordinates[iDim] += Coordinates_Fine[iDim] * Area_Children / Area_Parent; } nodes->SetCoord(Point_Coarse, Coordinates); } END_SU2_OMP_FOR } -void CMultiGridGeometry::SetMultiGridWallHeatFlux(const CGeometry *fine_grid, unsigned short val_marker) { - +void CMultiGridGeometry::SetMultiGridWallHeatFlux(const CGeometry* fine_grid, unsigned short val_marker) { struct { const CGeometry* fine_grid; unsigned short marker; @@ -1068,8 +979,7 @@ void CMultiGridGeometry::SetMultiGridWallHeatFlux(const CGeometry *fine_grid, un SetMultiGridWallQuantity(fine_grid, val_marker, wall_heat_flux); } -void CMultiGridGeometry::SetMultiGridWallTemperature(const CGeometry *fine_grid, unsigned short val_marker){ - +void CMultiGridGeometry::SetMultiGridWallTemperature(const CGeometry* fine_grid, unsigned short val_marker) { struct { const CGeometry* fine_grid; unsigned short marker; @@ -1087,10 +997,9 @@ void CMultiGridGeometry::SetMultiGridWallTemperature(const CGeometry *fine_grid, SetMultiGridWallQuantity(fine_grid, val_marker, wall_temperature); } -void CMultiGridGeometry::SetRestricted_GridVelocity(const CGeometry *fine_grid) { - +void CMultiGridGeometry::SetRestricted_GridVelocity(const CGeometry* fine_grid) { /*--- Loop over all coarse mesh points. ---*/ - SU2_OMP_FOR_STAT(roundUpDiv(nPoint,omp_get_max_threads())) + SU2_OMP_FOR_STAT(roundUpDiv(nPoint, omp_get_max_threads())) for (unsigned long Point_Coarse = 0; Point_Coarse < nPoint; Point_Coarse++) { su2double Area_Parent = nodes->GetVolume(Point_Coarse); @@ -1100,55 +1009,50 @@ void CMultiGridGeometry::SetRestricted_GridVelocity(const CGeometry *fine_grid) /*--- Loop over all of the children for this coarse CV and compute a grid velocity based on the values in the child CVs (fine mesh). ---*/ for (unsigned short iChild = 0; iChild < nodes->GetnChildren_CV(Point_Coarse); iChild++) { - unsigned long Point_Fine = nodes->GetChildren_CV(Point_Coarse, iChild); - su2double Area_Child = fine_grid->nodes->GetVolume(Point_Fine); + unsigned long Point_Fine = nodes->GetChildren_CV(Point_Coarse, iChild); + su2double Area_Child = fine_grid->nodes->GetVolume(Point_Fine); const su2double* Grid_Vel_Fine = fine_grid->nodes->GetGridVel(Point_Fine); for (unsigned short iDim = 0; iDim < nDim; iDim++) - Grid_Vel[iDim] += Grid_Vel_Fine[iDim]*Area_Child/Area_Parent; + Grid_Vel[iDim] += Grid_Vel_Fine[iDim] * Area_Child / Area_Parent; } /*--- Set the grid velocity for this coarse node. ---*/ - for (unsigned short iDim = 0; iDim < nDim; iDim++) - nodes->SetGridVel(Point_Coarse, iDim, Grid_Vel[iDim]); + for (unsigned short iDim = 0; iDim < nDim; iDim++) nodes->SetGridVel(Point_Coarse, iDim, Grid_Vel[iDim]); } END_SU2_OMP_FOR } - -void CMultiGridGeometry::FindNormal_Neighbor(const CConfig *config) { - +void CMultiGridGeometry::FindNormal_Neighbor(const CConfig* config) { unsigned short iMarker, iDim; unsigned long iPoint, iVertex; for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { - if (config->GetMarker_All_KindBC(iMarker) != SEND_RECEIVE && config->GetMarker_All_KindBC(iMarker) != INTERNAL_BOUNDARY && - config->GetMarker_All_KindBC(iMarker) != NEARFIELD_BOUNDARY ) { - + config->GetMarker_All_KindBC(iMarker) != NEARFIELD_BOUNDARY) { for (iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { - iPoint = vertex[iMarker][iVertex]->GetNode(); /*--- If the node belong to the domain ---*/ if (nodes->GetDomain(iPoint)) { - /*--- Compute closest normal neighbor ---*/ su2double cos_max, scalar_prod, norm_vect, norm_Normal, cos_alpha, diff_coord; unsigned long Point_Normal = 0; - su2double *Normal = vertex[iMarker][iVertex]->GetNormal(); + su2double* Normal = vertex[iMarker][iVertex]->GetNormal(); cos_max = -1.0; for (auto jPoint : nodes->GetPoints(iPoint)) { - scalar_prod = 0.0; norm_vect = 0.0; norm_Normal = 0.0; + scalar_prod = 0.0; + norm_vect = 0.0; + norm_Normal = 0.0; for (iDim = 0; iDim < nDim; iDim++) { - diff_coord = nodes->GetCoord(jPoint, iDim)-nodes->GetCoord(iPoint, iDim); - scalar_prod += diff_coord*Normal[iDim]; - norm_vect += diff_coord*diff_coord; - norm_Normal += Normal[iDim]*Normal[iDim]; + diff_coord = nodes->GetCoord(jPoint, iDim) - nodes->GetCoord(iPoint, iDim); + scalar_prod += diff_coord * Normal[iDim]; + norm_vect += diff_coord * diff_coord; + norm_Normal += Normal[iDim] * Normal[iDim]; } norm_vect = sqrt(norm_vect); norm_Normal = sqrt(norm_Normal); - cos_alpha = scalar_prod/(norm_vect*norm_Normal); + cos_alpha = scalar_prod / (norm_vect * norm_Normal); /*--- Get maximum cosine (not minimum because normals are oriented inwards) ---*/ if (cos_alpha >= cos_max) { @@ -1162,4 +1066,3 @@ void CMultiGridGeometry::FindNormal_Neighbor(const CConfig *config) { } } } - diff --git a/Common/src/geometry/CMultiGridQueue.cpp b/Common/src/geometry/CMultiGridQueue.cpp index 3d670b05455..cc6a16a8b4d 100644 --- a/Common/src/geometry/CMultiGridQueue.cpp +++ b/Common/src/geometry/CMultiGridQueue.cpp @@ -28,14 +28,9 @@ #include "../../include/geometry/CMultiGridQueue.hpp" #include -CMultiGridQueue::CMultiGridQueue(unsigned long npoint) : - Priority(npoint,0), - RightCV(npoint,true), - nPoint(npoint) { - +CMultiGridQueue::CMultiGridQueue(unsigned long npoint) : Priority(npoint, 0), RightCV(npoint, true), nPoint(npoint) { /*--- Queue initialization with all the points in the fine grid. ---*/ QueueCV.emplace_back(nPoint); - } void CMultiGridQueue::ThrowPointNotInListError(unsigned long iPoint) const { @@ -45,8 +40,7 @@ void CMultiGridQueue::ThrowPointNotInListError(unsigned long iPoint) const { } void CMultiGridQueue::AddCV(unsigned long newPoint, short numberNeighbors) { - - const short maxNeighbors = QueueCV.size()-1; + const short maxNeighbors = QueueCV.size() - 1; /*--- Basic check ---*/ if (newPoint >= nPoint) { @@ -55,9 +49,8 @@ void CMultiGridQueue::AddCV(unsigned long newPoint, short numberNeighbors) { /*--- Resize the list ---*/ if (numberNeighbors > maxNeighbors) { - const size_t newSize = numberNeighbors+1; - if (QueueCV.capacity() < newSize) - QueueCV.reserve(2*newSize); + const size_t newSize = numberNeighbors + 1; + if (QueueCV.capacity() < newSize) QueueCV.reserve(2 * newSize); QueueCV.resize(newSize); } @@ -69,11 +62,9 @@ void CMultiGridQueue::AddCV(unsigned long newPoint, short numberNeighbors) { QueueCV[numberNeighbors].push_back(newPoint); Priority[newPoint] = numberNeighbors; } - } void CMultiGridQueue::RemoveCV(unsigned long removePoint) { - /*--- Basic check ---*/ if (removePoint >= nPoint) { SU2_MPI::Error("The index of the CV is greater than the size of the priority list.", CURRENT_FUNCTION); @@ -94,25 +85,21 @@ void CMultiGridQueue::RemoveCV(unsigned long removePoint) { while (sizeQueueCV > 0) { if (!QueueCV[--sizeQueueCV].empty()) break; } - QueueCV.resize(sizeQueueCV+1); - + QueueCV.resize(sizeQueueCV + 1); } void CMultiGridQueue::MoveCV(unsigned long movePoint, short numberNeighbors) { - RightCV[movePoint] = (numberNeighbors >= 0); - numberNeighbors = max(numberNeighbors,0); + numberNeighbors = max(numberNeighbors, 0); /*--- Remove the control volume ---*/ RemoveCV(movePoint); /*--- Add a new control volume ---*/ AddCV(movePoint, numberNeighbors); - } void CMultiGridQueue::IncrPriorityCV(unsigned long incrPoint) { - /*--- Find the priority list ---*/ const short numberNeighbors = Priority[incrPoint]; @@ -120,12 +107,10 @@ void CMultiGridQueue::IncrPriorityCV(unsigned long incrPoint) { RemoveCV(incrPoint); /*--- Increase the priority ---*/ - AddCV(incrPoint, numberNeighbors+1); - + AddCV(incrPoint, numberNeighbors + 1); } void CMultiGridQueue::RedPriorityCV(unsigned long redPoint) { - /*--- Find the priority list ---*/ const short numberNeighbors = Priority[redPoint]; if (numberNeighbors == 0) return; @@ -134,42 +119,35 @@ void CMultiGridQueue::RedPriorityCV(unsigned long redPoint) { RemoveCV(redPoint); /*--- Decrease the priority ---*/ - AddCV(redPoint, numberNeighbors-1); - + AddCV(redPoint, numberNeighbors - 1); } void CMultiGridQueue::VisualizeQueue(void) const { - cout << endl; unsigned short iQ = 0; for (const auto& Q : QueueCV) { cout << "Number of neighbors " << iQ << ": "; for (auto iPoint : Q) - if (iPoint != QueueType::ErasedValue) - cout << iPoint << " "; + if (iPoint != QueueType::ErasedValue) cout << iPoint << " "; cout << endl; iQ++; } } void CMultiGridQueue::VisualizePriority(void) const { - for (auto iPoint = 0ul; iPoint < nPoint; ++iPoint) { cout << "Control Volume: " << iPoint << " Priority: " << Priority[iPoint] << endl; } } bool CMultiGridQueue::EmptyQueue(void) const { - /*--- In case there is only the no agglomerated elements (size 1), check * if they can be agglomerated or if we have already finished. ---*/ if (QueueCV.size() == 1) { for (auto iPoint : QueueCV[0]) - if ((iPoint != QueueType::ErasedValue) && RightCV[iPoint]) - return false; - } - else { + if ((iPoint != QueueType::ErasedValue) && RightCV[iPoint]) return false; + } else { for (size_t iQ = 1; iQ < QueueCV.size(); ++iQ) if (!QueueCV[iQ].empty()) return false; } @@ -182,11 +160,9 @@ unsigned long CMultiGridQueue::TotalCV(void) const { return TotalCV; } -void CMultiGridQueue::Update(unsigned long updatePoint, CGeometry *fineGrid) { - +void CMultiGridQueue::Update(unsigned long updatePoint, CGeometry* fineGrid) { RemoveCV(updatePoint); for (auto jPoint : fineGrid->nodes->GetPoints(updatePoint)) - if (!fineGrid->nodes->GetAgglomerate(jPoint)) - IncrPriorityCV(jPoint); + if (!fineGrid->nodes->GetAgglomerate(jPoint)) IncrPriorityCV(jPoint); } diff --git a/Common/src/geometry/CPhysicalGeometry.cpp b/Common/src/geometry/CPhysicalGeometry.cpp index 5d097a75daa..8496dcb6491 100644 --- a/Common/src/geometry/CPhysicalGeometry.cpp +++ b/Common/src/geometry/CPhysicalGeometry.cpp @@ -55,11 +55,10 @@ #include #endif +CPhysicalGeometry::CPhysicalGeometry() : CGeometry() {} -CPhysicalGeometry::CPhysicalGeometry() : CGeometry() { } - -CPhysicalGeometry::CPhysicalGeometry(CConfig *config, unsigned short val_iZone, unsigned short val_nZone) : CGeometry() { - +CPhysicalGeometry::CPhysicalGeometry(CConfig* config, unsigned short val_iZone, unsigned short val_nZone) + : CGeometry() { edgeColorGroupSize = config->GetEdgeColoringGroupSize(); string text_line, Marker_Tag; @@ -70,7 +69,7 @@ CPhysicalGeometry::CPhysicalGeometry(CConfig *config, unsigned short val_iZone, ofstream boundary_file; string Grid_Marker; - string val_mesh_filename = config->GetMesh_FileName(); + string val_mesh_filename = config->GetMesh_FileName(); unsigned short val_format = config->GetMesh_FileFormat(); /*--- Determine whether or not a FEM discretization is used ---*/ @@ -79,7 +78,7 @@ CPhysicalGeometry::CPhysicalGeometry(CConfig *config, unsigned short val_iZone, /*--- Initialize counters for local/global points & elements ---*/ - if( fem_solver ) { + if (fem_solver) { switch (val_format) { case SU2: Read_SU2_Format_Parallel_FEM(config, val_mesh_filename, val_iZone, val_nZone); @@ -93,11 +92,12 @@ CPhysicalGeometry::CPhysicalGeometry(CConfig *config, unsigned short val_iZone, SU2_MPI::Error("Unrecognized mesh format specified for the FEM solver!", CURRENT_FUNCTION); break; } - } - else { - + } else { switch (val_format) { - case SU2: case CGNS_GRID: case RECTANGLE: case BOX: + case SU2: + case CGNS_GRID: + case RECTANGLE: + case BOX: Read_Mesh_FVM(config, val_mesh_filename, val_iZone, val_nZone); break; default: @@ -113,23 +113,20 @@ CPhysicalGeometry::CPhysicalGeometry(CConfig *config, unsigned short val_iZone, /*--- Loop over the points element to re-scale the mesh, and plot it (only SU2_CFD) ---*/ if (config->GetKind_SU2() == SU2_COMPONENT::SU2_CFD) { - /*--- The US system uses feet, but SU2 assumes that the grid is in inches ---*/ if (config->GetSystemMeasurements() == US) { for (iPoint = 0; iPoint < nPoint; iPoint++) { for (iDim = 0; iDim < nDim; iDim++) { - nodes->SetCoord(iPoint, iDim, nodes->GetCoord(iPoint, iDim)/12.0); + nodes->SetCoord(iPoint, iDim, nodes->GetCoord(iPoint, iDim) / 12.0); } } } - } /*--- If SU2_DEF then write a file with the boundary information ---*/ if ((config->GetKind_SU2() == SU2_COMPONENT::SU2_DEF) && (rank == MASTER_NODE)) { - string str = "boundary.dat"; str = config->GetMultizone_FileName(str, val_iZone, ".dat"); @@ -143,16 +140,15 @@ CPhysicalGeometry::CPhysicalGeometry(CConfig *config, unsigned short val_iZone, boundary_file << "NMARK= " << nMarker << endl; for (iMarker = 0; iMarker < nMarker; iMarker++) { - Grid_Marker = config->GetMarker_All_TagBound(iMarker); boundary_file << "MARKER_TAG= " << Grid_Marker << endl; - boundary_file << "MARKER_ELEMS= " << nElem_Bound[iMarker]<< endl; + boundary_file << "MARKER_ELEMS= " << nElem_Bound[iMarker] << endl; boundary_file << "SEND_TO= " << config->GetMarker_All_SendRecv(iMarker) << endl; if (nDim == 2) { for (iElem_Bound = 0; iElem_Bound < nElem_Bound[iMarker]; iElem_Bound++) { - boundary_file << bound[iMarker][iElem_Bound]->GetVTK_Type() << "\t" ; + boundary_file << bound[iMarker][iElem_Bound]->GetVTK_Type() << "\t"; for (iNodes = 0; iNodes < bound[iMarker][iElem_Bound]->GetnNodes(); iNodes++) - boundary_file << bound[iMarker][iElem_Bound]->GetNode(iNodes) << "\t" ; + boundary_file << bound[iMarker][iElem_Bound]->GetNode(iNodes) << "\t"; if (bound[iMarker][iElem_Bound]->GetVTK_Type() == VERTEX) { boundary_file << bound[iMarker][iElem_Bound]->GetRotation_Type() << "\t"; @@ -163,9 +159,9 @@ CPhysicalGeometry::CPhysicalGeometry(CConfig *config, unsigned short val_iZone, if (nDim == 3) { for (iElem_Bound = 0; iElem_Bound < nElem_Bound[iMarker]; iElem_Bound++) { - boundary_file << bound[iMarker][iElem_Bound]->GetVTK_Type() << "\t" ; + boundary_file << bound[iMarker][iElem_Bound]->GetVTK_Type() << "\t"; for (iNodes = 0; iNodes < bound[iMarker][iElem_Bound]->GetnNodes(); iNodes++) - boundary_file << bound[iMarker][iElem_Bound]->GetNode(iNodes) << "\t" ; + boundary_file << bound[iMarker][iElem_Bound]->GetNode(iNodes) << "\t"; if (bound[iMarker][iElem_Bound]->GetVTK_Type() == VERTEX) { boundary_file << bound[iMarker][iElem_Bound]->GetRotation_Type() << "\t"; @@ -173,28 +169,23 @@ CPhysicalGeometry::CPhysicalGeometry(CConfig *config, unsigned short val_iZone, boundary_file << iElem_Bound << endl; } } - } boundary_file.close(); - } /*--- If the gradient smoothing solver is active, allocate space for the sensitivity and initialize. ---*/ if (config->GetSmoothGradient()) { - Sensitivity.resize(nPoint,nDim) = su2double(0.0); + Sensitivity.resize(nPoint, nDim) = su2double(0.0); } - } -CPhysicalGeometry::CPhysicalGeometry(CGeometry *geometry, - CConfig *config) : CGeometry() { - +CPhysicalGeometry::CPhysicalGeometry(CGeometry* geometry, CConfig* config) : CGeometry() { edgeColorGroupSize = config->GetEdgeColoringGroupSize(); /*--- The new geometry class has the same problem dimension/zone. ---*/ - nDim = geometry->GetnDim(); + nDim = geometry->GetnDim(); nZone = geometry->GetnZone(); /*--- Recompute the linear partitioning offsets. ---*/ @@ -204,34 +195,30 @@ CPhysicalGeometry::CPhysicalGeometry(CGeometry *geometry, /*--- Communicate the coloring data so that each rank has a complete set of colors for all points that reside on it, including repeats. ---*/ - if ((rank == MASTER_NODE) && (size != SINGLE_NODE)) - cout <<"Distributing ParMETIS coloring." << endl; + if ((rank == MASTER_NODE) && (size != SINGLE_NODE)) cout << "Distributing ParMETIS coloring." << endl; DistributeColoring(config, geometry); /*--- Redistribute the points to all ranks based on the coloring. ---*/ - if ((rank == MASTER_NODE) && (size != SINGLE_NODE)) - cout <<"Rebalancing vertices." << endl; + if ((rank == MASTER_NODE) && (size != SINGLE_NODE)) cout << "Rebalancing vertices." << endl; DistributePoints(config, geometry); /*--- Distribute the element information to all ranks based on coloring. ---*/ - if ((rank == MASTER_NODE) && (size != SINGLE_NODE)) - cout <<"Rebalancing volume element connectivity." << endl; + if ((rank == MASTER_NODE) && (size != SINGLE_NODE)) cout << "Rebalancing volume element connectivity." << endl; - DistributeVolumeConnectivity(config, geometry, TRIANGLE ); + DistributeVolumeConnectivity(config, geometry, TRIANGLE); DistributeVolumeConnectivity(config, geometry, QUADRILATERAL); - DistributeVolumeConnectivity(config, geometry, TETRAHEDRON ); - DistributeVolumeConnectivity(config, geometry, HEXAHEDRON ); - DistributeVolumeConnectivity(config, geometry, PRISM ); - DistributeVolumeConnectivity(config, geometry, PYRAMID ); + DistributeVolumeConnectivity(config, geometry, TETRAHEDRON); + DistributeVolumeConnectivity(config, geometry, HEXAHEDRON); + DistributeVolumeConnectivity(config, geometry, PRISM); + DistributeVolumeConnectivity(config, geometry, PYRAMID); /*--- Distribute the marker information to all ranks based on coloring. ---*/ - if ((rank == MASTER_NODE) && (size != SINGLE_NODE)) - cout <<"Rebalancing markers and surface elements." << endl; + if ((rank == MASTER_NODE) && (size != SINGLE_NODE)) cout << "Rebalancing markers and surface elements." << endl; /*--- First, perform a linear partitioning of the marker information, as the grid readers currently store all boundary information on the master @@ -239,32 +226,25 @@ CPhysicalGeometry::CPhysicalGeometry(CGeometry *geometry, reader to avoid reading the markers to the master rank alone at first. ---*/ DistributeMarkerTags(config, geometry); - PartitionSurfaceConnectivity(config, geometry, LINE ); - PartitionSurfaceConnectivity(config, geometry, TRIANGLE ); + PartitionSurfaceConnectivity(config, geometry, LINE); + PartitionSurfaceConnectivity(config, geometry, TRIANGLE); PartitionSurfaceConnectivity(config, geometry, QUADRILATERAL); /*--- Once the markers are distributed according to the linear partitioning of the grid points, we can use similar techniques as above for distributing the surface element connectivity. ---*/ - DistributeSurfaceConnectivity(config, geometry, LINE ); - DistributeSurfaceConnectivity(config, geometry, TRIANGLE ); + DistributeSurfaceConnectivity(config, geometry, LINE); + DistributeSurfaceConnectivity(config, geometry, TRIANGLE); DistributeSurfaceConnectivity(config, geometry, QUADRILATERAL); /*--- Reduce the total number of elements that we have on each rank. ---*/ - nLocal_Elem = (nLocal_Tria + - nLocal_Quad + - nLocal_Tetr + - nLocal_Hexa + - nLocal_Pris + - nLocal_Pyra); + nLocal_Elem = (nLocal_Tria + nLocal_Quad + nLocal_Tetr + nLocal_Hexa + nLocal_Pris + nLocal_Pyra); nLocal_Bound_Elem = nLocal_Line + nLocal_BoundTria + nLocal_BoundQuad; - SU2_MPI::Allreduce(&nLocal_Elem, &nGlobal_Elem, 1, - MPI_UNSIGNED_LONG, MPI_SUM, SU2_MPI::GetComm()); - SU2_MPI::Allreduce(&nLocal_Bound_Elem, &nGlobal_Bound_Elem, 1, - MPI_UNSIGNED_LONG, MPI_SUM, SU2_MPI::GetComm()); + SU2_MPI::Allreduce(&nLocal_Elem, &nGlobal_Elem, 1, MPI_UNSIGNED_LONG, MPI_SUM, SU2_MPI::GetComm()); + SU2_MPI::Allreduce(&nLocal_Bound_Elem, &nGlobal_Bound_Elem, 1, MPI_UNSIGNED_LONG, MPI_SUM, SU2_MPI::GetComm()); /*--- With the distribution of all points, elements, and markers based on the ParMETIS coloring complete, as a final step, load this data into @@ -276,7 +256,7 @@ CPhysicalGeometry::CPhysicalGeometry(CGeometry *geometry, /*--- If the gradient smoothing solver is active, allocate space for the sensitivity and initialize. ---*/ if (config->GetSmoothGradient()) { - Sensitivity.resize(nPoint,nDim) = su2double(0.0); + Sensitivity.resize(nPoint, nDim) = su2double(0.0); } /*--- Free memory associated with the partitioning of points and elems. ---*/ @@ -284,83 +264,81 @@ CPhysicalGeometry::CPhysicalGeometry(CGeometry *geometry, decltype(Neighbors)().swap(Neighbors); decltype(Color_List)().swap(Color_List); - delete [] Local_Points; - delete [] Local_Colors; - delete [] Local_Coords; - - delete [] Conn_Line_Linear; - delete [] Conn_BoundTria_Linear; - delete [] Conn_BoundQuad_Linear; - - delete [] Conn_Line; - delete [] Conn_BoundTria; - delete [] Conn_BoundQuad; - delete [] Conn_Tria; - delete [] Conn_Quad; - delete [] Conn_Tetr; - delete [] Conn_Hexa; - delete [] Conn_Pris; - delete [] Conn_Pyra; - - delete [] ID_Line; - delete [] ID_BoundTria; - delete [] ID_BoundQuad; - delete [] ID_Line_Linear; - delete [] ID_BoundTria_Linear; - delete [] ID_BoundQuad_Linear; - - delete [] ID_Tria; - delete [] ID_Quad; - delete [] ID_Tetr; - delete [] ID_Hexa; - delete [] ID_Pris; - delete [] ID_Pyra; - - delete [] Elem_ID_Line; - delete [] Elem_ID_BoundTria; - delete [] Elem_ID_BoundQuad; - delete [] Elem_ID_Line_Linear; - delete [] Elem_ID_BoundTria_Linear; - delete [] Elem_ID_BoundQuad_Linear; - + delete[] Local_Points; + delete[] Local_Colors; + delete[] Local_Coords; + + delete[] Conn_Line_Linear; + delete[] Conn_BoundTria_Linear; + delete[] Conn_BoundQuad_Linear; + + delete[] Conn_Line; + delete[] Conn_BoundTria; + delete[] Conn_BoundQuad; + delete[] Conn_Tria; + delete[] Conn_Quad; + delete[] Conn_Tetr; + delete[] Conn_Hexa; + delete[] Conn_Pris; + delete[] Conn_Pyra; + + delete[] ID_Line; + delete[] ID_BoundTria; + delete[] ID_BoundQuad; + delete[] ID_Line_Linear; + delete[] ID_BoundTria_Linear; + delete[] ID_BoundQuad_Linear; + + delete[] ID_Tria; + delete[] ID_Quad; + delete[] ID_Tetr; + delete[] ID_Hexa; + delete[] ID_Pris; + delete[] ID_Pyra; + + delete[] Elem_ID_Line; + delete[] Elem_ID_BoundTria; + delete[] Elem_ID_BoundQuad; + delete[] Elem_ID_Line_Linear; + delete[] Elem_ID_BoundTria_Linear; + delete[] Elem_ID_BoundQuad_Linear; } CPhysicalGeometry::~CPhysicalGeometry(void) { - - delete [] Local_to_Global_Point; + delete[] Local_to_Global_Point; /*--- Free up memory from turbomachinery performance computation ---*/ unsigned short iMarker; if (TangGridVelIn != nullptr) { for (iMarker = 0; iMarker < nTurboPerf; iMarker++) - if (TangGridVelIn[iMarker] != nullptr) delete [] TangGridVelIn[iMarker]; - delete [] TangGridVelIn; + if (TangGridVelIn[iMarker] != nullptr) delete[] TangGridVelIn[iMarker]; + delete[] TangGridVelIn; } if (SpanAreaIn != nullptr) { for (iMarker = 0; iMarker < nTurboPerf; iMarker++) - if (SpanAreaIn[iMarker] != nullptr) delete [] SpanAreaIn[iMarker]; - delete [] SpanAreaIn; + if (SpanAreaIn[iMarker] != nullptr) delete[] SpanAreaIn[iMarker]; + delete[] SpanAreaIn; } if (TurboRadiusIn != nullptr) { for (iMarker = 0; iMarker < nTurboPerf; iMarker++) - if (TurboRadiusIn[iMarker] != nullptr) delete [] TurboRadiusIn[iMarker]; - delete [] TurboRadiusIn; + if (TurboRadiusIn[iMarker] != nullptr) delete[] TurboRadiusIn[iMarker]; + delete[] TurboRadiusIn; } if (TangGridVelOut != nullptr) { for (iMarker = 0; iMarker < nTurboPerf; iMarker++) - if (TangGridVelOut[iMarker] != nullptr) delete [] TangGridVelOut[iMarker]; - delete [] TangGridVelOut; + if (TangGridVelOut[iMarker] != nullptr) delete[] TangGridVelOut[iMarker]; + delete[] TangGridVelOut; } if (SpanAreaOut != nullptr) { for (iMarker = 0; iMarker < nTurboPerf; iMarker++) - if (SpanAreaOut[iMarker] != nullptr) delete [] SpanAreaOut[iMarker]; - delete [] SpanAreaOut; + if (SpanAreaOut[iMarker] != nullptr) delete[] SpanAreaOut[iMarker]; + delete[] SpanAreaOut; } if (TurboRadiusOut != nullptr) { for (iMarker = 0; iMarker < nTurboPerf; iMarker++) - if (TurboRadiusOut[iMarker] != nullptr) delete [] TurboRadiusOut[iMarker]; - delete [] TurboRadiusOut; + if (TurboRadiusOut[iMarker] != nullptr) delete[] TurboRadiusOut[iMarker]; + delete[] TurboRadiusOut; } /*--- Free up memory from turbomachinery computations @@ -372,108 +350,97 @@ CPhysicalGeometry::~CPhysicalGeometry(void) { if (turbovertex != nullptr) { for (iMarker = 0; iMarker < nMarker; iMarker++) { if (Marker_All_SendRecv[iMarker] == 0 && turbovertex[iMarker] != nullptr) { - for (iSpan= 0; iSpan < nSpanSectionsByMarker[iMarker]; iSpan++) { + for (iSpan = 0; iSpan < nSpanSectionsByMarker[iMarker]; iSpan++) { if (turbovertex[iMarker][iSpan] != nullptr) { for (iVertex = 0; iVertex < nVertexSpan[iMarker][iSpan]; iVertex++) - if (turbovertex[iMarker][iSpan][iVertex] != nullptr) - delete turbovertex[iMarker][iSpan][iVertex]; - delete [] turbovertex[iMarker][iSpan]; + if (turbovertex[iMarker][iSpan][iVertex] != nullptr) delete turbovertex[iMarker][iSpan][iVertex]; + delete[] turbovertex[iMarker][iSpan]; } } - delete [] turbovertex[iMarker]; + delete[] turbovertex[iMarker]; } } - delete [] turbovertex; + delete[] turbovertex; } if (AverageTurboNormal != nullptr) { for (iMarker = 0; iMarker < nMarker; iMarker++) { if (Marker_All_SendRecv[iMarker] == 0 && AverageTurboNormal[iMarker] != nullptr) { - for (iSpan= 0; iSpan < nSpanSectionsByMarker[iMarker]+1; iSpan++) - delete [] AverageTurboNormal[iMarker][iSpan]; - delete [] AverageTurboNormal[iMarker]; + for (iSpan = 0; iSpan < nSpanSectionsByMarker[iMarker] + 1; iSpan++) + delete[] AverageTurboNormal[iMarker][iSpan]; + delete[] AverageTurboNormal[iMarker]; } } - delete [] AverageTurboNormal; + delete[] AverageTurboNormal; } if (AverageNormal != nullptr) { for (iMarker = 0; iMarker < nMarker; iMarker++) { if (Marker_All_SendRecv[iMarker] == 0 && AverageNormal[iMarker] != nullptr) { - for (iSpan= 0; iSpan < nSpanSectionsByMarker[iMarker]+1; iSpan++) - delete [] AverageNormal[iMarker][iSpan]; - delete [] AverageNormal[iMarker]; + for (iSpan = 0; iSpan < nSpanSectionsByMarker[iMarker] + 1; iSpan++) delete[] AverageNormal[iMarker][iSpan]; + delete[] AverageNormal[iMarker]; } } - delete [] AverageNormal; + delete[] AverageNormal; } if (AverageGridVel != nullptr) { for (iMarker = 0; iMarker < nMarker; iMarker++) { if (Marker_All_SendRecv[iMarker] == 0 && AverageGridVel[iMarker] != nullptr) { - for (iSpan= 0; iSpan < nSpanSectionsByMarker[iMarker]+1; iSpan++) - delete [] AverageGridVel[iMarker][iSpan]; - delete [] AverageGridVel[iMarker]; + for (iSpan = 0; iSpan < nSpanSectionsByMarker[iMarker] + 1; iSpan++) delete[] AverageGridVel[iMarker][iSpan]; + delete[] AverageGridVel[iMarker]; } } - delete [] AverageGridVel; + delete[] AverageGridVel; } if (AverageTangGridVel != nullptr) { for (iMarker = 0; iMarker < nMarker; iMarker++) if (Marker_All_SendRecv[iMarker] == 0 && AverageTangGridVel[iMarker] != nullptr) - delete [] AverageTangGridVel[iMarker]; - delete [] AverageTangGridVel; + delete[] AverageTangGridVel[iMarker]; + delete[] AverageTangGridVel; } if (SpanArea != nullptr) { for (iMarker = 0; iMarker < nMarker; iMarker++) - if (Marker_All_SendRecv[iMarker] == 0 && SpanArea[iMarker] != nullptr) - delete [] SpanArea[iMarker]; - delete [] SpanArea; + if (Marker_All_SendRecv[iMarker] == 0 && SpanArea[iMarker] != nullptr) delete[] SpanArea[iMarker]; + delete[] SpanArea; } if (TurboRadius != nullptr) { for (iMarker = 0; iMarker < nMarker; iMarker++) - if (Marker_All_SendRecv[iMarker] == 0 && TurboRadius[iMarker] != nullptr) - delete [] TurboRadius[iMarker]; - delete [] TurboRadius; + if (Marker_All_SendRecv[iMarker] == 0 && TurboRadius[iMarker] != nullptr) delete[] TurboRadius[iMarker]; + delete[] TurboRadius; } if (MaxAngularCoord != nullptr) { for (iMarker = 0; iMarker < nMarker; iMarker++) - if (Marker_All_SendRecv[iMarker] == 0 && MaxAngularCoord[iMarker] != nullptr) - delete [] MaxAngularCoord[iMarker]; - delete [] MaxAngularCoord; + if (Marker_All_SendRecv[iMarker] == 0 && MaxAngularCoord[iMarker] != nullptr) delete[] MaxAngularCoord[iMarker]; + delete[] MaxAngularCoord; } if (MinAngularCoord != nullptr) { for (iMarker = 0; iMarker < nMarker; iMarker++) - if (Marker_All_SendRecv[iMarker] == 0 && MinAngularCoord[iMarker] != nullptr) - delete [] MinAngularCoord[iMarker]; - delete [] MinAngularCoord; + if (Marker_All_SendRecv[iMarker] == 0 && MinAngularCoord[iMarker] != nullptr) delete[] MinAngularCoord[iMarker]; + delete[] MinAngularCoord; } if (MinRelAngularCoord != nullptr) { for (iMarker = 0; iMarker < nMarker; iMarker++) if (Marker_All_SendRecv[iMarker] == 0 && MinRelAngularCoord[iMarker] != nullptr) - delete [] MinRelAngularCoord[iMarker]; - delete [] MinRelAngularCoord; + delete[] MinRelAngularCoord[iMarker]; + delete[] MinRelAngularCoord; } - delete [] nSpanWiseSections; - delete [] nSpanSectionsByMarker; + delete[] nSpanWiseSections; + delete[] nSpanSectionsByMarker; if (SpanWiseValue != nullptr) { for (iMarker = 0; iMarker < 2; iMarker++) - if (Marker_All_SendRecv[iMarker] == 0 && SpanWiseValue[iMarker] != nullptr) - delete [] SpanWiseValue[iMarker]; - delete [] SpanWiseValue; + if (Marker_All_SendRecv[iMarker] == 0 && SpanWiseValue[iMarker] != nullptr) delete[] SpanWiseValue[iMarker]; + delete[] SpanWiseValue; } if (nVertexSpan != nullptr) { for (iMarker = 0; iMarker < nMarker; iMarker++) - if (Marker_All_SendRecv[iMarker] == 0 && nVertexSpan[iMarker] != nullptr) - delete [] nVertexSpan[iMarker]; - delete [] nVertexSpan; + if (Marker_All_SendRecv[iMarker] == 0 && nVertexSpan[iMarker] != nullptr) delete[] nVertexSpan[iMarker]; + delete[] nVertexSpan; } if (nTotVertexSpan != nullptr) { for (iMarker = 0; iMarker < nMarker; iMarker++) - if (Marker_All_SendRecv[iMarker] == 0 && nTotVertexSpan[iMarker] != nullptr) - delete [] nTotVertexSpan[iMarker]; - delete [] nTotVertexSpan; + if (Marker_All_SendRecv[iMarker] == 0 && nTotVertexSpan[iMarker] != nullptr) delete[] nTotVertexSpan[iMarker]; + delete[] nTotVertexSpan; } - } void CPhysicalGeometry::SetGlobal_to_Local_Point(void) { @@ -483,9 +450,7 @@ void CPhysicalGeometry::SetGlobal_to_Local_Point(void) { } } -void CPhysicalGeometry::DistributeColoring(const CConfig *config, - CGeometry *geometry) { - +void CPhysicalGeometry::DistributeColoring(const CConfig* config, CGeometry* geometry) { /*--- To start, each linear partition carries the color only for the owned nodes (nPoint), but we have repeated elems on each linear partition. We need to complete the coloring information such that the repeated @@ -502,7 +467,7 @@ void CPhysicalGeometry::DistributeColoring(const CConfig *config, /*--- Get a linear partitioner to track the partition counts. ---*/ - CLinearPartitioner pointPartitioner(geometry->GetGlobal_nPoint(),0); + CLinearPartitioner pointPartitioner(geometry->GetGlobal_nPoint(), 0); /*--- First, create a complete map of the points on this rank (excluding repeats) and their neighbors so that we can efficiently loop through the @@ -519,9 +484,8 @@ void CPhysicalGeometry::DistributeColoring(const CConfig *config, rank matches the number in the mesh file (in serial). ---*/ if ((size == SINGLE_NODE) && (Point_Map.size() < geometry->GetnPoint())) { - SU2_MPI::Error( string("Mismatch between NPOIN and number of points") - +string(" listed in mesh file.\n") - +string("Please check the mesh file for correctness.\n"), + SU2_MPI::Error(string("Mismatch between NPOIN and number of points") + string(" listed in mesh file.\n") + + string("Please check the mesh file for correctness.\n"), CURRENT_FUNCTION); } @@ -536,8 +500,8 @@ void CPhysicalGeometry::DistributeColoring(const CConfig *config, jPoint = geometry->GetnPoint(); for (auto iPoint : Point_Map) { - if ((iPoint < pointPartitioner.GetFirstIndexOnRank(rank)) || - (iPoint >= pointPartitioner.GetLastIndexOnRank(rank))){ + if ((iPoint < pointPartitioner.GetFirstIndexOnRank(rank)) || + (iPoint >= pointPartitioner.GetLastIndexOnRank(rank))) { Global2Local[iPoint] = jPoint; jPoint++; } @@ -567,14 +531,19 @@ void CPhysicalGeometry::DistributeColoring(const CConfig *config, /*--- Prepare structures for communication. ---*/ - int *nPoint_Send = new int[size+1]; nPoint_Send[0] = 0; - int *nPoint_Recv = new int[size+1]; nPoint_Recv[0] = 0; - int *nPoint_Flag = new int[size]; + int* nPoint_Send = new int[size + 1]; + nPoint_Send[0] = 0; + int* nPoint_Recv = new int[size + 1]; + nPoint_Recv[0] = 0; + int* nPoint_Flag = new int[size]; for (iProc = 0; iProc < size; iProc++) { - nPoint_Send[iProc] = 0; nPoint_Recv[iProc] = 0; nPoint_Flag[iProc]= -1; + nPoint_Send[iProc] = 0; + nPoint_Recv[iProc] = 0; + nPoint_Flag[iProc] = -1; } - nPoint_Send[size] = 0; nPoint_Recv[size] = 0; + nPoint_Send[size] = 0; + nPoint_Recv[size] = 0; /*--- Loop over the owned points and check all the neighbors for unowned points. The colors of all owned points will be communicated to any ranks @@ -583,7 +552,6 @@ void CPhysicalGeometry::DistributeColoring(const CConfig *config, for (iPoint = 0; iPoint < geometry->GetnPoint(); iPoint++) { for (iNeighbor = 0; iNeighbor < Neighbors[iPoint].size(); iNeighbor++) { - /*--- Global ID of the neighbor ---*/ jPoint = Neighbors[iPoint][iNeighbor]; @@ -597,9 +565,8 @@ void CPhysicalGeometry::DistributeColoring(const CConfig *config, if (nPoint_Flag[iProcessor] != (int)iPoint) { nPoint_Flag[iProcessor] = (int)iPoint; - nPoint_Send[iProcessor+1]++; + nPoint_Send[iProcessor + 1]++; } - } } @@ -607,8 +574,7 @@ void CPhysicalGeometry::DistributeColoring(const CConfig *config, all processors. After this communication, each proc knows how many points it will receive from each other processor. ---*/ - SU2_MPI::Alltoall(&(nPoint_Send[1]), 1, MPI_INT, - &(nPoint_Recv[1]), 1, MPI_INT, SU2_MPI::GetComm()); + SU2_MPI::Alltoall(&(nPoint_Send[1]), 1, MPI_INT, &(nPoint_Recv[1]), 1, MPI_INT, SU2_MPI::GetComm()); /*--- Prepare to send colors. First check how many messages we will be sending and receiving. Here we also put @@ -619,34 +585,33 @@ void CPhysicalGeometry::DistributeColoring(const CConfig *config, for (iProc = 0; iProc < size; iProc++) nPoint_Flag[iProc] = -1; for (iProc = 0; iProc < size; iProc++) { - if ((iProc != rank) && (nPoint_Send[iProc+1] > 0)) nSends++; - if ((iProc != rank) && (nPoint_Recv[iProc+1] > 0)) nRecvs++; + if ((iProc != rank) && (nPoint_Send[iProc + 1] > 0)) nSends++; + if ((iProc != rank) && (nPoint_Recv[iProc + 1] > 0)) nRecvs++; - nPoint_Send[iProc+1] += nPoint_Send[iProc]; - nPoint_Recv[iProc+1] += nPoint_Recv[iProc]; + nPoint_Send[iProc + 1] += nPoint_Send[iProc]; + nPoint_Recv[iProc + 1] += nPoint_Recv[iProc]; } /*--- Allocate arrays for sending the global ID. ---*/ - unsigned long *idSend = new unsigned long[nPoint_Send[size]]; + unsigned long* idSend = new unsigned long[nPoint_Send[size]]; for (iSend = 0; iSend < nPoint_Send[size]; iSend++) idSend[iSend] = 0; /*--- Allocate memory to hold the colors that we are sending. ---*/ - unsigned long *colorSend = new unsigned long[nPoint_Send[size]]; + unsigned long* colorSend = new unsigned long[nPoint_Send[size]]; for (iSend = 0; iSend < nPoint_Send[size]; iSend++) colorSend[iSend] = 0; /*--- Create an index variable to keep track of our index positions as we load up the send buffer. ---*/ - unsigned long *index = new unsigned long[size]; + unsigned long* index = new unsigned long[size]; for (iProc = 0; iProc < size; iProc++) index[iProc] = nPoint_Send[iProc]; /*--- Now load up our buffers with the Global IDs and colors. ---*/ for (iPoint = 0; iPoint < geometry->GetnPoint(); iPoint++) { for (iNeighbor = 0; iNeighbor < Neighbors[iPoint].size(); iNeighbor++) { - /*--- Global ID of the neighbor ---*/ jPoint = Neighbors[iPoint][iNeighbor]; @@ -659,76 +624,69 @@ void CPhysicalGeometry::DistributeColoring(const CConfig *config, counters and load up the global ID and color. ---*/ if (nPoint_Flag[iProcessor] != (int)iPoint) { - nPoint_Flag[iProcessor] = (int)iPoint; unsigned long nn = index[iProcessor]; /*--- Load the data values. ---*/ - idSend[nn] = geometry->nodes->GetGlobalIndex(iPoint); + idSend[nn] = geometry->nodes->GetGlobalIndex(iPoint); colorSend[nn] = geometry->nodes->GetColor(iPoint); /*--- Increment the index by the message length ---*/ index[iProcessor]++; - } } } /*--- Free memory after loading up the send buffer. ---*/ - delete [] index; + delete[] index; /*--- Allocate the memory that we need for receiving the conn values and then cue up the non-blocking receives. Note that we do not include our own rank in the communications. We will directly copy our own data later. ---*/ - unsigned long *colorRecv = new unsigned long[nPoint_Recv[size]]; - for (iRecv = 0; iRecv < nPoint_Recv[size]; iRecv++) - colorRecv[iRecv] = 0; + unsigned long* colorRecv = new unsigned long[nPoint_Recv[size]]; + for (iRecv = 0; iRecv < nPoint_Recv[size]; iRecv++) colorRecv[iRecv] = 0; - unsigned long *idRecv = new unsigned long[nPoint_Recv[size]]; - for (iRecv = 0; iRecv < nPoint_Recv[size]; iRecv++) - idRecv[iRecv] = 0; + unsigned long* idRecv = new unsigned long[nPoint_Recv[size]]; + for (iRecv = 0; iRecv < nPoint_Recv[size]; iRecv++) idRecv[iRecv] = 0; /*--- Allocate memory for the MPI requests if we need to communicate. ---*/ if (nSends > 0) { colorSendReq = new SU2_MPI::Request[nSends]; - idSendReq = new SU2_MPI::Request[nSends]; + idSendReq = new SU2_MPI::Request[nSends]; } if (nRecvs > 0) { colorRecvReq = new SU2_MPI::Request[nRecvs]; - idRecvReq = new SU2_MPI::Request[nRecvs]; + idRecvReq = new SU2_MPI::Request[nRecvs]; } /*--- Launch the non-blocking sends and receives. ---*/ - InitiateCommsAll(colorSend, nPoint_Send, colorSendReq, - colorRecv, nPoint_Recv, colorRecvReq, - 1, COMM_TYPE_UNSIGNED_LONG); + InitiateCommsAll(colorSend, nPoint_Send, colorSendReq, colorRecv, nPoint_Recv, colorRecvReq, 1, + COMM_TYPE_UNSIGNED_LONG); - InitiateCommsAll(idSend, nPoint_Send, idSendReq, - idRecv, nPoint_Recv, idRecvReq, - 1, COMM_TYPE_UNSIGNED_LONG); + InitiateCommsAll(idSend, nPoint_Send, idSendReq, idRecv, nPoint_Recv, idRecvReq, 1, COMM_TYPE_UNSIGNED_LONG); /*--- Copy my own rank's data into the recv buffer directly. ---*/ - iRecv = nPoint_Recv[rank]; + iRecv = nPoint_Recv[rank]; myStart = nPoint_Send[rank]; - myFinal = nPoint_Send[rank+1]; + myFinal = nPoint_Send[rank + 1]; for (iSend = myStart; iSend < myFinal; iSend++) { colorRecv[iRecv] = colorSend[iSend]; - idRecv[iRecv] = idSend[iSend]; + idRecv[iRecv] = idSend[iSend]; iRecv++; } /*--- Complete the non-blocking communications. ---*/ CompleteCommsAll(nSends, colorSendReq, nRecvs, colorRecvReq); - CompleteCommsAll(nSends, idSendReq, nRecvs, idRecvReq); + CompleteCommsAll(nSends, idSendReq, nRecvs, idRecvReq); /*--- Store the complete color map for this rank in class data. Now, each rank has a color value for all owned nodes as well as any repeated @@ -742,32 +700,29 @@ void CPhysicalGeometry::DistributeColoring(const CConfig *config, /*--- Free temporary memory from communications ---*/ - delete [] colorSendReq; - delete [] idSendReq; - - delete [] colorRecvReq; - delete [] idRecvReq; + delete[] colorSendReq; + delete[] idSendReq; - delete [] colorSend; - delete [] colorRecv; - delete [] idSend; - delete [] idRecv; - delete [] nPoint_Recv; - delete [] nPoint_Send; - delete [] nPoint_Flag; + delete[] colorRecvReq; + delete[] idRecvReq; + delete[] colorSend; + delete[] colorRecv; + delete[] idSend; + delete[] idRecv; + delete[] nPoint_Recv; + delete[] nPoint_Send; + delete[] nPoint_Flag; } -void CPhysicalGeometry::DistributeVolumeConnectivity(const CConfig *config, - CGeometry *geometry, +void CPhysicalGeometry::DistributeVolumeConnectivity(const CConfig* config, CGeometry* geometry, unsigned short Elem_Type) { - unsigned short NODES_PER_ELEMENT = 0; unsigned long iProcessor; unsigned long iElem, iNode, jNode, nElem_Total = 0, Global_Index; - unsigned long *Conn_Elem = nullptr; - unsigned long *ID_Elems = nullptr; + unsigned long* Conn_Elem = nullptr; + unsigned long* ID_Elems = nullptr; SU2_MPI::Request *connSendReq = nullptr, *idSendReq = nullptr; SU2_MPI::Request *connRecvReq = nullptr, *idRecvReq = nullptr; @@ -813,19 +768,23 @@ void CPhysicalGeometry::DistributeVolumeConnectivity(const CConfig *config, and decide how many elements we must send to each other rank in order to have all elements distributed according to the ParMETIS coloring. ---*/ - int *nElem_Send = new int[size+1]; nElem_Send[0] = 0; - int *nElem_Recv = new int[size+1]; nElem_Recv[0] = 0; - int *nElem_Flag = new int[size]; + int* nElem_Send = new int[size + 1]; + nElem_Send[0] = 0; + int* nElem_Recv = new int[size + 1]; + nElem_Recv[0] = 0; + int* nElem_Flag = new int[size]; for (iProc = 0; iProc < size; iProc++) { - nElem_Send[iProc] = 0; nElem_Recv[iProc] = 0; nElem_Flag[iProc]= -1; + nElem_Send[iProc] = 0; + nElem_Recv[iProc] = 0; + nElem_Flag[iProc] = -1; } - nElem_Send[size] = 0; nElem_Recv[size] = 0; + nElem_Send[size] = 0; + nElem_Recv[size] = 0; - for (iElem = 0; iElem < geometry->GetnElem(); iElem++ ) { + for (iElem = 0; iElem < geometry->GetnElem(); iElem++) { if (geometry->elem[iElem]->GetVTK_Type() == Elem_Type) { - for (iNode = 0; iNode < NODES_PER_ELEMENT; iNode++ ) { - + for (iNode = 0; iNode < NODES_PER_ELEMENT; iNode++) { /*--- Get the index of the current point. ---*/ Global_Index = geometry->elem[iElem]->GetNode(iNode); @@ -839,9 +798,8 @@ void CPhysicalGeometry::DistributeVolumeConnectivity(const CConfig *config, if ((nElem_Flag[iProcessor] != (int)iElem)) { nElem_Flag[iProcessor] = (int)iElem; - nElem_Send[iProcessor+1]++; + nElem_Send[iProcessor + 1]++; } - } } } @@ -850,8 +808,7 @@ void CPhysicalGeometry::DistributeVolumeConnectivity(const CConfig *config, all processors. After this communication, each proc knows how many cells it will receive from each other processor. ---*/ - SU2_MPI::Alltoall(&(nElem_Send[1]), 1, MPI_INT, - &(nElem_Recv[1]), 1, MPI_INT, SU2_MPI::GetComm()); + SU2_MPI::Alltoall(&(nElem_Send[1]), 1, MPI_INT, &(nElem_Recv[1]), 1, MPI_INT, SU2_MPI::GetComm()); /*--- Prepare to send connectivities. First check how many messages we will be sending and receiving. Here we also put @@ -862,44 +819,40 @@ void CPhysicalGeometry::DistributeVolumeConnectivity(const CConfig *config, for (iProc = 0; iProc < size; iProc++) nElem_Flag[iProc] = -1; for (iProc = 0; iProc < size; iProc++) { - if ((iProc != rank) && (nElem_Send[iProc+1] > 0)) nSends++; - if ((iProc != rank) && (nElem_Recv[iProc+1] > 0)) nRecvs++; + if ((iProc != rank) && (nElem_Send[iProc + 1] > 0)) nSends++; + if ((iProc != rank) && (nElem_Recv[iProc + 1] > 0)) nRecvs++; - nElem_Send[iProc+1] += nElem_Send[iProc]; - nElem_Recv[iProc+1] += nElem_Recv[iProc]; + nElem_Send[iProc + 1] += nElem_Send[iProc]; + nElem_Recv[iProc + 1] += nElem_Recv[iProc]; } /*--- Allocate memory to hold the connectivity and element IDs that we are sending. ---*/ - unsigned long *connSend = nullptr; - connSend = new unsigned long[NODES_PER_ELEMENT*nElem_Send[size]]; - for (iSend = 0; iSend < NODES_PER_ELEMENT*nElem_Send[size]; iSend++) - connSend[iSend] = 0; + unsigned long* connSend = nullptr; + connSend = new unsigned long[NODES_PER_ELEMENT * nElem_Send[size]]; + for (iSend = 0; iSend < NODES_PER_ELEMENT * nElem_Send[size]; iSend++) connSend[iSend] = 0; /*--- Allocate arrays for storing element global index. ---*/ - unsigned long *idSend = new unsigned long[nElem_Send[size]]; + unsigned long* idSend = new unsigned long[nElem_Send[size]]; for (iSend = 0; iSend < nElem_Send[size]; iSend++) idSend[iSend] = 0; /*--- Create an index variable to keep track of our index position as we load up the send buffer. ---*/ - unsigned long *index = new unsigned long[size]; - for (iProc = 0; iProc < size; iProc++) - index[iProc] = NODES_PER_ELEMENT*nElem_Send[iProc]; + unsigned long* index = new unsigned long[size]; + for (iProc = 0; iProc < size; iProc++) index[iProc] = NODES_PER_ELEMENT * nElem_Send[iProc]; - unsigned long *idIndex = new unsigned long[size]; - for (iProc = 0; iProc < size; iProc++) - idIndex[iProc] = nElem_Send[iProc]; + unsigned long* idIndex = new unsigned long[size]; + for (iProc = 0; iProc < size; iProc++) idIndex[iProc] = nElem_Send[iProc]; /*--- Loop through our elements and load the elems and their additional data that we will send to the other procs. ---*/ for (iElem = 0; iElem < geometry->GetnElem(); iElem++) { if (geometry->elem[iElem]->GetVTK_Type() == Elem_Type) { - for (iNode = 0; iNode < NODES_PER_ELEMENT; iNode++ ) { - + for (iNode = 0; iNode < NODES_PER_ELEMENT; iNode++) { /*--- Get the index of the current point. ---*/ Global_Index = geometry->elem[iElem]->GetNode(iNode); @@ -911,7 +864,6 @@ void CPhysicalGeometry::DistributeVolumeConnectivity(const CConfig *config, /*--- Load connectivity and IDs into the buffer for sending ---*/ if (nElem_Flag[iProcessor] != (int)iElem) { - nElem_Flag[iProcessor] = (int)iElem; unsigned long nn = index[iProcessor]; unsigned long mm = idIndex[iProcessor]; @@ -920,7 +872,8 @@ void CPhysicalGeometry::DistributeVolumeConnectivity(const CConfig *config, stored directly based on their global index for the nodes.---*/ for (jNode = 0; jNode < NODES_PER_ELEMENT; jNode++) { - connSend[nn] = geometry->elem[iElem]->GetNode(jNode); nn++; + connSend[nn] = geometry->elem[iElem]->GetNode(jNode); + nn++; } /*--- Global ID for this element. ---*/ @@ -931,7 +884,6 @@ void CPhysicalGeometry::DistributeVolumeConnectivity(const CConfig *config, index[iProcessor] += NODES_PER_ELEMENT; idIndex[iProcessor]++; - } } } @@ -939,56 +891,52 @@ void CPhysicalGeometry::DistributeVolumeConnectivity(const CConfig *config, /*--- Free memory after loading up the send buffer. ---*/ - delete [] index; - delete [] idIndex; + delete[] index; + delete[] idIndex; /*--- Allocate the memory that we need for receiving the values and then cue up the non-blocking receives. Note that we do not include our own rank in the communications. We will directly copy our own data later. ---*/ - unsigned long *connRecv = nullptr; - connRecv = new unsigned long[NODES_PER_ELEMENT*nElem_Recv[size]]; - for (iRecv = 0; iRecv < NODES_PER_ELEMENT*nElem_Recv[size]; iRecv++) - connRecv[iRecv] = 0; + unsigned long* connRecv = nullptr; + connRecv = new unsigned long[NODES_PER_ELEMENT * nElem_Recv[size]]; + for (iRecv = 0; iRecv < NODES_PER_ELEMENT * nElem_Recv[size]; iRecv++) connRecv[iRecv] = 0; - unsigned long *idRecv = new unsigned long[nElem_Recv[size]]; + unsigned long* idRecv = new unsigned long[nElem_Recv[size]]; for (iRecv = 0; iRecv < nElem_Recv[size]; iRecv++) idRecv[iRecv] = 0; /*--- Allocate memory for the MPI requests if we need to communicate. ---*/ if (nSends > 0) { connSendReq = new SU2_MPI::Request[nSends]; - idSendReq = new SU2_MPI::Request[nSends]; + idSendReq = new SU2_MPI::Request[nSends]; } if (nRecvs > 0) { connRecvReq = new SU2_MPI::Request[nRecvs]; - idRecvReq = new SU2_MPI::Request[nRecvs]; + idRecvReq = new SU2_MPI::Request[nRecvs]; } /*--- Launch the non-blocking sends and receives. ---*/ - InitiateCommsAll(connSend, nElem_Send, connSendReq, - connRecv, nElem_Recv, connRecvReq, - NODES_PER_ELEMENT, COMM_TYPE_UNSIGNED_LONG); + InitiateCommsAll(connSend, nElem_Send, connSendReq, connRecv, nElem_Recv, connRecvReq, NODES_PER_ELEMENT, + COMM_TYPE_UNSIGNED_LONG); - InitiateCommsAll(idSend, nElem_Send, idSendReq, - idRecv, nElem_Recv, idRecvReq, - 1, COMM_TYPE_UNSIGNED_LONG); + InitiateCommsAll(idSend, nElem_Send, idSendReq, idRecv, nElem_Recv, idRecvReq, 1, COMM_TYPE_UNSIGNED_LONG); /*--- Copy my own rank's data into the recv buffer directly. ---*/ - iRecv = NODES_PER_ELEMENT*nElem_Recv[rank]; - myStart = NODES_PER_ELEMENT*nElem_Send[rank]; - myFinal = NODES_PER_ELEMENT*nElem_Send[rank+1]; + iRecv = NODES_PER_ELEMENT * nElem_Recv[rank]; + myStart = NODES_PER_ELEMENT * nElem_Send[rank]; + myFinal = NODES_PER_ELEMENT * nElem_Send[rank + 1]; for (iSend = myStart; iSend < myFinal; iSend++) { connRecv[iRecv] = connSend[iSend]; iRecv++; } - iRecv = nElem_Recv[rank]; + iRecv = nElem_Recv[rank]; myStart = nElem_Send[rank]; - myFinal = nElem_Send[rank+1]; + myFinal = nElem_Send[rank + 1]; for (iSend = myStart; iSend < myFinal; iSend++) { idRecv[iRecv] = idSend[iSend]; iRecv++; @@ -997,18 +945,19 @@ void CPhysicalGeometry::DistributeVolumeConnectivity(const CConfig *config, /*--- Complete the non-blocking communications. ---*/ CompleteCommsAll(nSends, connSendReq, nRecvs, connRecvReq); - CompleteCommsAll(nSends, idSendReq, nRecvs, idRecvReq); + CompleteCommsAll(nSends, idSendReq, nRecvs, idRecvReq); /*--- Store the connectivity for this rank in the proper structure It will be loaded into the geometry objects in a later step. ---*/ if (nElem_Recv[size] > 0) { - Conn_Elem = new unsigned long[NODES_PER_ELEMENT*nElem_Recv[size]]; - int count = 0; nElem_Total = 0; + Conn_Elem = new unsigned long[NODES_PER_ELEMENT * nElem_Recv[size]]; + int count = 0; + nElem_Total = 0; for (iRecv = 0; iRecv < nElem_Recv[size]; iRecv++) { nElem_Total++; for (iNode = 0; iNode < NODES_PER_ELEMENT; iNode++) { - Conn_Elem[count] = connRecv[iRecv*NODES_PER_ELEMENT+iNode]; + Conn_Elem[count] = connRecv[iRecv * NODES_PER_ELEMENT + iNode]; count++; } } @@ -1031,42 +980,42 @@ void CPhysicalGeometry::DistributeVolumeConnectivity(const CConfig *config, nLocal_Tria = nElem_Total; if (nLocal_Tria > 0) { Conn_Tria = Conn_Elem; - ID_Tria = ID_Elems; + ID_Tria = ID_Elems; } break; case QUADRILATERAL: nLocal_Quad = nElem_Total; if (nLocal_Quad > 0) { Conn_Quad = Conn_Elem; - ID_Quad = ID_Elems; + ID_Quad = ID_Elems; } break; case TETRAHEDRON: nLocal_Tetr = nElem_Total; if (nLocal_Tetr > 0) { Conn_Tetr = Conn_Elem; - ID_Tetr = ID_Elems; + ID_Tetr = ID_Elems; } break; case HEXAHEDRON: nLocal_Hexa = nElem_Total; if (nLocal_Hexa > 0) { Conn_Hexa = Conn_Elem; - ID_Hexa = ID_Elems; + ID_Hexa = ID_Elems; } break; case PRISM: nLocal_Pris = nElem_Total; if (nLocal_Pris > 0) { Conn_Pris = Conn_Elem; - ID_Pris = ID_Elems; + ID_Pris = ID_Elems; } break; case PYRAMID: nLocal_Pyra = nElem_Total; if (nLocal_Pyra > 0) { Conn_Pyra = Conn_Elem; - ID_Pyra = ID_Elems; + ID_Pyra = ID_Elems; } break; default: @@ -1076,24 +1025,22 @@ void CPhysicalGeometry::DistributeVolumeConnectivity(const CConfig *config, /*--- Free temporary memory from communications ---*/ - delete [] connSendReq; - delete [] idSendReq; - - delete [] connRecvReq; - delete [] idRecvReq; + delete[] connSendReq; + delete[] idSendReq; - delete [] connSend; - delete [] connRecv; - delete [] idSend; - delete [] idRecv; - delete [] nElem_Recv; - delete [] nElem_Send; - delete [] nElem_Flag; + delete[] connRecvReq; + delete[] idRecvReq; + delete[] connSend; + delete[] connRecv; + delete[] idSend; + delete[] idRecv; + delete[] nElem_Recv; + delete[] nElem_Send; + delete[] nElem_Flag; } -void CPhysicalGeometry::DistributePoints(const CConfig *config, CGeometry *geometry) { - +void CPhysicalGeometry::DistributePoints(const CConfig* config, CGeometry* geometry) { /*--- We now know all of the coloring for our local points and neighbors. From this, we can communicate the owned nodes in our linear partitioning to all other ranks, including coordinates and coloring info, so that the @@ -1108,14 +1055,19 @@ void CPhysicalGeometry::DistributePoints(const CConfig *config, CGeometry *geome /*--- Prepare structures for communication. ---*/ - int *nPoint_Send = new int[size+1]; nPoint_Send[0] = 0; - int *nPoint_Recv = new int[size+1]; nPoint_Recv[0] = 0; - int *nPoint_Flag = new int[size]; + int* nPoint_Send = new int[size + 1]; + nPoint_Send[0] = 0; + int* nPoint_Recv = new int[size + 1]; + nPoint_Recv[0] = 0; + int* nPoint_Flag = new int[size]; for (iProc = 0; iProc < size; iProc++) { - nPoint_Send[iProc] = 0; nPoint_Recv[iProc] = 0; nPoint_Flag[iProc]= -1; + nPoint_Send[iProc] = 0; + nPoint_Recv[iProc] = 0; + nPoint_Flag[iProc] = -1; } - nPoint_Send[size] = 0; nPoint_Recv[size] = 0; + nPoint_Send[size] = 0; + nPoint_Recv[size] = 0; /*--- Loop over the owned points and check all the neighbors for unowned points. The colors of all owned points will be communicated to any ranks @@ -1124,7 +1076,6 @@ void CPhysicalGeometry::DistributePoints(const CConfig *config, CGeometry *geome for (iPoint = 0; iPoint < geometry->GetnPoint(); iPoint++) { for (iNeighbor = 0; iNeighbor < Neighbors[iPoint].size(); iNeighbor++) { - /*--- Global ID of the neighbor ---*/ jPoint = Neighbors[iPoint][iNeighbor]; @@ -1138,7 +1089,7 @@ void CPhysicalGeometry::DistributePoints(const CConfig *config, CGeometry *geome if (nPoint_Flag[iProcessor] != (int)iPoint) { nPoint_Flag[iProcessor] = (int)iPoint; - nPoint_Send[iProcessor+1]++; + nPoint_Send[iProcessor + 1]++; } } } @@ -1147,8 +1098,7 @@ void CPhysicalGeometry::DistributePoints(const CConfig *config, CGeometry *geome all processors. After this communication, each proc knows how many points it will receive from each other processor. ---*/ - SU2_MPI::Alltoall(&(nPoint_Send[1]), 1, MPI_INT, - &(nPoint_Recv[1]), 1, MPI_INT, SU2_MPI::GetComm()); + SU2_MPI::Alltoall(&(nPoint_Send[1]), 1, MPI_INT, &(nPoint_Recv[1]), 1, MPI_INT, SU2_MPI::GetComm()); /*--- Prepare to send colors, ids, and coords. First check how many messages we will be sending and receiving. Here we also put @@ -1159,46 +1109,42 @@ void CPhysicalGeometry::DistributePoints(const CConfig *config, CGeometry *geome for (iProc = 0; iProc < size; iProc++) nPoint_Flag[iProc] = -1; for (iProc = 0; iProc < size; iProc++) { - if ((iProc != rank) && (nPoint_Send[iProc+1] > 0)) nSends++; - if ((iProc != rank) && (nPoint_Recv[iProc+1] > 0)) nRecvs++; + if ((iProc != rank) && (nPoint_Send[iProc + 1] > 0)) nSends++; + if ((iProc != rank) && (nPoint_Recv[iProc + 1] > 0)) nRecvs++; - nPoint_Send[iProc+1] += nPoint_Send[iProc]; - nPoint_Recv[iProc+1] += nPoint_Recv[iProc]; + nPoint_Send[iProc + 1] += nPoint_Send[iProc]; + nPoint_Recv[iProc + 1] += nPoint_Recv[iProc]; } /*--- Allocate arrays for sending the global ID. ---*/ - unsigned long *idSend = new unsigned long[nPoint_Send[size]]; + unsigned long* idSend = new unsigned long[nPoint_Send[size]]; for (iSend = 0; iSend < nPoint_Send[size]; iSend++) idSend[iSend] = 0; /*--- Allocate memory to hold the colors that we are sending. ---*/ - unsigned long *colorSend = new unsigned long[nPoint_Send[size]]; + unsigned long* colorSend = new unsigned long[nPoint_Send[size]]; for (iSend = 0; iSend < nPoint_Send[size]; iSend++) colorSend[iSend] = 0; /*--- Allocate memory to hold the coordinates that we are sending. ---*/ - su2double *coordSend = nullptr; - coordSend = new su2double[nDim*nPoint_Send[size]]; - for (iSend = 0; iSend < nDim*nPoint_Send[size]; iSend++) - coordSend[iSend] = 0; + su2double* coordSend = nullptr; + coordSend = new su2double[nDim * nPoint_Send[size]]; + for (iSend = 0; iSend < nDim * nPoint_Send[size]; iSend++) coordSend[iSend] = 0; /*--- Create index variables to keep track of our index positions as we load up the send buffer. ---*/ - unsigned long *index = new unsigned long[size]; - for (iProc = 0; iProc < size; iProc++) - index[iProc] = nPoint_Send[iProc]; + unsigned long* index = new unsigned long[size]; + for (iProc = 0; iProc < size; iProc++) index[iProc] = nPoint_Send[iProc]; - unsigned long *coordIndex = new unsigned long[size]; - for (iProc = 0; iProc < size; iProc++) - coordIndex[iProc] = nDim*nPoint_Send[iProc]; + unsigned long* coordIndex = new unsigned long[size]; + for (iProc = 0; iProc < size; iProc++) coordIndex[iProc] = nDim * nPoint_Send[iProc]; /*--- Now load up our buffers with the colors, ids, and coords. ---*/ for (iPoint = 0; iPoint < geometry->GetnPoint(); iPoint++) { for (iNeighbor = 0; iNeighbor < Neighbors[iPoint].size(); iNeighbor++) { - /*--- Global ID of the neighbor ---*/ jPoint = Neighbors[iPoint][iNeighbor]; @@ -1211,94 +1157,84 @@ void CPhysicalGeometry::DistributePoints(const CConfig *config, CGeometry *geome counters and load up the colors, ids, and coords. ---*/ if (nPoint_Flag[iProcessor] != (int)iPoint) { - nPoint_Flag[iProcessor] = (int)iPoint; unsigned long nn = index[iProcessor]; /*--- Load the global ID, color, and coordinate values. ---*/ - idSend[nn] = geometry->nodes->GetGlobalIndex(iPoint); + idSend[nn] = geometry->nodes->GetGlobalIndex(iPoint); colorSend[nn] = geometry->nodes->GetColor(iPoint); nn = coordIndex[iProcessor]; - for (iDim = 0; iDim < nDim; iDim++) { - coordSend[nn] = geometry->nodes->GetCoord(iPoint, iDim); nn++; + for (iDim = 0; iDim < nDim; iDim++) { + coordSend[nn] = geometry->nodes->GetCoord(iPoint, iDim); + nn++; } /*--- Increment the index by the message length ---*/ coordIndex[iProcessor] += nDim; index[iProcessor]++; - } } } /*--- Free memory after loading up the send buffer. ---*/ - delete [] index; - delete [] coordIndex; + delete[] index; + delete[] coordIndex; /*--- Allocate the memory that we need for receiving the values and then cue up the non-blocking receives. Note that we do not include our own rank in the communications. We will directly copy our own data later. ---*/ - unsigned long *colorRecv = new unsigned long[nPoint_Recv[size]]; - for (iRecv = 0; iRecv < nPoint_Recv[size]; iRecv++) - colorRecv[iRecv] = 0; + unsigned long* colorRecv = new unsigned long[nPoint_Recv[size]]; + for (iRecv = 0; iRecv < nPoint_Recv[size]; iRecv++) colorRecv[iRecv] = 0; - unsigned long *idRecv = new unsigned long[nPoint_Recv[size]]; - for (iRecv = 0; iRecv < nPoint_Recv[size]; iRecv++) - idRecv[iRecv] = 0; + unsigned long* idRecv = new unsigned long[nPoint_Recv[size]]; + for (iRecv = 0; iRecv < nPoint_Recv[size]; iRecv++) idRecv[iRecv] = 0; - su2double *coordRecv = nullptr; - coordRecv = new su2double[nDim*nPoint_Recv[size]]; - for (iRecv = 0; iRecv < nDim*nPoint_Recv[size]; iRecv++) - coordRecv[iRecv] = 0; + su2double* coordRecv = nullptr; + coordRecv = new su2double[nDim * nPoint_Recv[size]]; + for (iRecv = 0; iRecv < nDim * nPoint_Recv[size]; iRecv++) coordRecv[iRecv] = 0; /*--- Allocate memory for the MPI requests if we need to communicate. ---*/ if (nSends > 0) { colorSendReq = new SU2_MPI::Request[nSends]; - idSendReq = new SU2_MPI::Request[nSends]; + idSendReq = new SU2_MPI::Request[nSends]; coordSendReq = new SU2_MPI::Request[nSends]; - } if (nRecvs > 0) { colorRecvReq = new SU2_MPI::Request[nRecvs]; - idRecvReq = new SU2_MPI::Request[nRecvs]; + idRecvReq = new SU2_MPI::Request[nRecvs]; coordRecvReq = new SU2_MPI::Request[nRecvs]; } /*--- Launch the non-blocking sends and receives. ---*/ - InitiateCommsAll(colorSend, nPoint_Send, colorSendReq, - colorRecv, nPoint_Recv, colorRecvReq, - 1, COMM_TYPE_UNSIGNED_LONG); + InitiateCommsAll(colorSend, nPoint_Send, colorSendReq, colorRecv, nPoint_Recv, colorRecvReq, 1, + COMM_TYPE_UNSIGNED_LONG); - InitiateCommsAll(idSend, nPoint_Send, idSendReq, - idRecv, nPoint_Recv, idRecvReq, - 1, COMM_TYPE_UNSIGNED_LONG); + InitiateCommsAll(idSend, nPoint_Send, idSendReq, idRecv, nPoint_Recv, idRecvReq, 1, COMM_TYPE_UNSIGNED_LONG); - InitiateCommsAll(coordSend, nPoint_Send, coordSendReq, - coordRecv, nPoint_Recv, coordRecvReq, - nDim, COMM_TYPE_DOUBLE); + InitiateCommsAll(coordSend, nPoint_Send, coordSendReq, coordRecv, nPoint_Recv, coordRecvReq, nDim, COMM_TYPE_DOUBLE); /*--- Copy my own rank's data into the recv buffer directly. ---*/ - iRecv = nPoint_Recv[rank]; + iRecv = nPoint_Recv[rank]; myStart = nPoint_Send[rank]; - myFinal = nPoint_Send[rank+1]; + myFinal = nPoint_Send[rank + 1]; for (iSend = myStart; iSend < myFinal; iSend++) { colorRecv[iRecv] = colorSend[iSend]; - idRecv[iRecv] = idSend[iSend]; + idRecv[iRecv] = idSend[iSend]; iRecv++; } - iRecv = nDim*nPoint_Recv[rank]; - myStart = nDim*nPoint_Send[rank]; - myFinal = nDim*nPoint_Send[rank+1]; + iRecv = nDim * nPoint_Recv[rank]; + myStart = nDim * nPoint_Send[rank]; + myFinal = nDim * nPoint_Send[rank + 1]; for (iSend = myStart; iSend < myFinal; iSend++) { coordRecv[iRecv] = coordSend[iSend]; iRecv++; @@ -1307,7 +1243,7 @@ void CPhysicalGeometry::DistributePoints(const CConfig *config, CGeometry *geome /*--- Complete the non-blocking communications. ---*/ CompleteCommsAll(nSends, colorSendReq, nRecvs, colorRecvReq); - CompleteCommsAll(nSends, idSendReq, nRecvs, idRecvReq); + CompleteCommsAll(nSends, idSendReq, nRecvs, idRecvReq); CompleteCommsAll(nSends, coordSendReq, nRecvs, coordRecvReq); /*--- Store the total number of local points my rank has for @@ -1320,44 +1256,42 @@ void CPhysicalGeometry::DistributePoints(const CConfig *config, CGeometry *geome Local_Points = new unsigned long[nPoint_Recv[size]]; Local_Colors = new unsigned long[nPoint_Recv[size]]; - Local_Coords = new su2double[nDim*nPoint_Recv[size]]; + Local_Coords = new su2double[nDim * nPoint_Recv[size]]; - nLocal_PointDomain = 0; nLocal_PointGhost = 0; + nLocal_PointDomain = 0; + nLocal_PointGhost = 0; for (iRecv = 0; iRecv < nPoint_Recv[size]; iRecv++) { Local_Points[iRecv] = idRecv[iRecv]; Local_Colors[iRecv] = colorRecv[iRecv]; - for (iDim = 0; iDim < nDim; iDim++) - Local_Coords[iRecv*nDim+iDim] = coordRecv[iRecv*nDim+iDim]; - if (Local_Colors[iRecv] == (unsigned long)rank) nLocal_PointDomain++; - else nLocal_PointGhost++; + for (iDim = 0; iDim < nDim; iDim++) Local_Coords[iRecv * nDim + iDim] = coordRecv[iRecv * nDim + iDim]; + if (Local_Colors[iRecv] == (unsigned long)rank) + nLocal_PointDomain++; + else + nLocal_PointGhost++; } /*--- Free temporary memory from communications ---*/ - delete [] colorSendReq; - delete [] idSendReq; - delete [] coordSendReq; - - delete [] colorRecvReq; - delete [] idRecvReq; - delete [] coordRecvReq; - - delete [] colorSend; - delete [] colorRecv; - delete [] idSend; - delete [] idRecv; - delete [] coordSend; - delete [] coordRecv; - delete [] nPoint_Recv; - delete [] nPoint_Send; - delete [] nPoint_Flag; - + delete[] colorSendReq; + delete[] idSendReq; + delete[] coordSendReq; + + delete[] colorRecvReq; + delete[] idRecvReq; + delete[] coordRecvReq; + + delete[] colorSend; + delete[] colorRecv; + delete[] idSend; + delete[] idRecv; + delete[] coordSend; + delete[] coordRecv; + delete[] nPoint_Recv; + delete[] nPoint_Send; + delete[] nPoint_Flag; } -void CPhysicalGeometry::PartitionSurfaceConnectivity(CConfig *config, - CGeometry *geometry, - unsigned short Elem_Type) { - +void CPhysicalGeometry::PartitionSurfaceConnectivity(CConfig* config, CGeometry* geometry, unsigned short Elem_Type) { /*--- We begin with all marker information residing on the master rank, as the master currently stores all marker info when reading the grid. We first check and communicate basic information that each rank will @@ -1374,9 +1308,9 @@ void CPhysicalGeometry::PartitionSurfaceConnectivity(CConfig *config, unsigned long iMarker, iProcessor, iElem, iNode, jNode; unsigned long nElem_Total = 0, Global_Index, Global_Elem_Index; - unsigned long *Conn_Elem = nullptr; - unsigned long *Linear_Markers = nullptr; - unsigned long *ID_SurfElem = nullptr; + unsigned long* Conn_Elem = nullptr; + unsigned long* Linear_Markers = nullptr; + unsigned long* ID_SurfElem = nullptr; SU2_MPI::Request *connSendReq = nullptr, *markerSendReq = nullptr, *idSendReq = nullptr; SU2_MPI::Request *connRecvReq = nullptr, *markerRecvReq = nullptr, *idRecvReq = nullptr; @@ -1402,33 +1336,34 @@ void CPhysicalGeometry::PartitionSurfaceConnectivity(CConfig *config, break; } - int *nElem_Send = new int[size+1]; nElem_Send[0] = 0; - int *nElem_Recv = new int[size+1]; nElem_Recv[0] = 0; - int *nElem_Flag = new int[size]; + int* nElem_Send = new int[size + 1]; + nElem_Send[0] = 0; + int* nElem_Recv = new int[size + 1]; + nElem_Recv[0] = 0; + int* nElem_Flag = new int[size]; for (iProc = 0; iProc < size; iProc++) { - nElem_Send[iProc] = 0; nElem_Recv[iProc] = 0; nElem_Flag[iProc]= -1; + nElem_Send[iProc] = 0; + nElem_Recv[iProc] = 0; + nElem_Flag[iProc] = -1; } - nElem_Send[size] = 0; nElem_Recv[size] = 0; + nElem_Send[size] = 0; + nElem_Recv[size] = 0; /*--- We know that the master owns all of the info and will be the only rank sending anything, although all ranks might receive something. ---*/ if (rank == MASTER_NODE) { for (iMarker = 0; iMarker < geometry->GetnMarker(); iMarker++) { - /*--- Reset the flag in between markers, just to ensure that we don't miss some elements on different markers with the same local index. ---*/ - for (iProc = 0; iProc < size; iProc++) nElem_Flag[iProc]= -1; + for (iProc = 0; iProc < size; iProc++) nElem_Flag[iProc] = -1; for (iElem = 0; iElem < geometry->GetnElem_Bound(iMarker); iElem++) { - if (geometry->bound[iMarker][iElem]->GetVTK_Type() == Elem_Type) { - - for (iNode = 0; iNode < NODES_PER_ELEMENT; iNode++ ) { - + for (iNode = 0; iNode < NODES_PER_ELEMENT; iNode++) { /*--- Get the index of the current point (stored as global). ---*/ Global_Index = geometry->bound[iMarker][iElem]->GetNode(iNode); @@ -1442,7 +1377,7 @@ void CPhysicalGeometry::PartitionSurfaceConnectivity(CConfig *config, if ((nElem_Flag[iProcessor] != (int)iElem)) { nElem_Flag[iProcessor] = (int)iElem; - nElem_Send[iProcessor+1]++; + nElem_Send[iProcessor + 1]++; } } } @@ -1454,8 +1389,7 @@ void CPhysicalGeometry::PartitionSurfaceConnectivity(CConfig *config, all processors. After this communication, each proc knows how many cells it will receive from each other processor. ---*/ - SU2_MPI::Scatter(&(nElem_Send[1]), 1, MPI_INT, - &(nElem_Recv[1]), 1, MPI_INT, MASTER_NODE, SU2_MPI::GetComm()); + SU2_MPI::Scatter(&(nElem_Send[1]), 1, MPI_INT, &(nElem_Recv[1]), 1, MPI_INT, MASTER_NODE, SU2_MPI::GetComm()); /*--- Prepare to send connectivities. First check how many messages we will be sending and receiving. Here we also put @@ -1466,60 +1400,52 @@ void CPhysicalGeometry::PartitionSurfaceConnectivity(CConfig *config, for (iProc = 0; iProc < size; iProc++) nElem_Flag[iProc] = -1; for (iProc = 0; iProc < size; iProc++) { - if ((iProc != rank) && (nElem_Send[iProc+1] > 0)) nSends++; - if ((iProc != rank) && (nElem_Recv[iProc+1] > 0)) nRecvs++; + if ((iProc != rank) && (nElem_Send[iProc + 1] > 0)) nSends++; + if ((iProc != rank) && (nElem_Recv[iProc + 1] > 0)) nRecvs++; - nElem_Send[iProc+1] += nElem_Send[iProc]; - nElem_Recv[iProc+1] += nElem_Recv[iProc]; + nElem_Send[iProc + 1] += nElem_Send[iProc]; + nElem_Recv[iProc + 1] += nElem_Recv[iProc]; } /*--- Allocate memory to hold the connectivity that we are sending. ---*/ - unsigned long *connSend = nullptr; - unsigned long *markerSend = nullptr; - unsigned long *idSend = nullptr; + unsigned long* connSend = nullptr; + unsigned long* markerSend = nullptr; + unsigned long* idSend = nullptr; if (rank == MASTER_NODE) { - - connSend = new unsigned long[NODES_PER_ELEMENT*nElem_Send[size]]; - for (iSend = 0; iSend < NODES_PER_ELEMENT*nElem_Send[size]; iSend++) - connSend[iSend] = 0; + connSend = new unsigned long[NODES_PER_ELEMENT * nElem_Send[size]]; + for (iSend = 0; iSend < NODES_PER_ELEMENT * nElem_Send[size]; iSend++) connSend[iSend] = 0; markerSend = new unsigned long[nElem_Send[size]]; - for (iSend = 0; iSend < nElem_Send[size]; iSend++) - markerSend[iSend] = 0; + for (iSend = 0; iSend < nElem_Send[size]; iSend++) markerSend[iSend] = 0; idSend = new unsigned long[nElem_Send[size]]; - for (iSend = 0; iSend < nElem_Send[size]; iSend++) - idSend[iSend] = 0; + for (iSend = 0; iSend < nElem_Send[size]; iSend++) idSend[iSend] = 0; /*--- Create an index variable to keep track of our index position as we load up the send buffer. ---*/ - unsigned long *index = new unsigned long[size]; - for (iProc = 0; iProc < size; iProc++) - index[iProc] = NODES_PER_ELEMENT*nElem_Send[iProc]; + unsigned long* index = new unsigned long[size]; + for (iProc = 0; iProc < size; iProc++) index[iProc] = NODES_PER_ELEMENT * nElem_Send[iProc]; - unsigned long *markerIndex = new unsigned long[size]; - for (iProc = 0; iProc < size; iProc++) - markerIndex[iProc] = nElem_Send[iProc]; + unsigned long* markerIndex = new unsigned long[size]; + for (iProc = 0; iProc < size; iProc++) markerIndex[iProc] = nElem_Send[iProc]; /*--- Loop through our elements and load the elems and their additional data that we will send to the other procs. ---*/ Global_Elem_Index = 0; for (iMarker = 0; iMarker < geometry->GetnMarker(); iMarker++) { - /*--- Reset the flag in between markers, just to ensure that we don't miss some elements on different markers with the same local index. ---*/ - for (iProc = 0; iProc < size; iProc++) nElem_Flag[iProc]= -1; + for (iProc = 0; iProc < size; iProc++) nElem_Flag[iProc] = -1; for (iElem = 0; iElem < geometry->GetnElem_Bound(iMarker); iElem++) { if (geometry->bound[iMarker][iElem]->GetVTK_Type() == Elem_Type) { - for (iNode = 0; iNode < NODES_PER_ELEMENT; iNode++ ) { - + for (iNode = 0; iNode < NODES_PER_ELEMENT; iNode++) { /*--- Get the index of the current point. ---*/ Global_Index = geometry->bound[iMarker][iElem]->GetNode(iNode); @@ -1531,7 +1457,6 @@ void CPhysicalGeometry::PartitionSurfaceConnectivity(CConfig *config, /*--- Load connectivity into the buffer for sending ---*/ if ((nElem_Flag[iProcessor] != (int)iElem)) { - nElem_Flag[iProcessor] = (int)iElem; unsigned long nn = index[iProcessor]; unsigned long mm = markerIndex[iProcessor]; @@ -1546,27 +1471,24 @@ void CPhysicalGeometry::PartitionSurfaceConnectivity(CConfig *config, /*--- Store the marker index and surface elem global ID ---*/ markerSend[mm] = iMarker; - idSend[mm] = Global_Elem_Index; + idSend[mm] = Global_Elem_Index; /*--- Increment the index by the message length ---*/ index[iProcessor] += NODES_PER_ELEMENT; markerIndex[iProcessor]++; } - } } Global_Elem_Index++; - } } /*--- Free memory after loading up the send buffer. ---*/ - delete [] index; - delete [] markerIndex; - + delete[] index; + delete[] markerIndex; } /*--- Allocate the memory that we need for receiving the conn @@ -1574,86 +1496,78 @@ void CPhysicalGeometry::PartitionSurfaceConnectivity(CConfig *config, we do not include our own rank in the communications. We will directly copy our own data later. ---*/ - unsigned long *connRecv = nullptr; - connRecv = new unsigned long[NODES_PER_ELEMENT*nElem_Recv[size]]; - for (iRecv = 0; iRecv < NODES_PER_ELEMENT*nElem_Recv[size]; iRecv++) - connRecv[iRecv] = 0; + unsigned long* connRecv = nullptr; + connRecv = new unsigned long[NODES_PER_ELEMENT * nElem_Recv[size]]; + for (iRecv = 0; iRecv < NODES_PER_ELEMENT * nElem_Recv[size]; iRecv++) connRecv[iRecv] = 0; - unsigned long *markerRecv = new unsigned long[nElem_Recv[size]]; - for (iRecv = 0; iRecv < nElem_Recv[size]; iRecv++) - markerRecv[iRecv] = 0; + unsigned long* markerRecv = new unsigned long[nElem_Recv[size]]; + for (iRecv = 0; iRecv < nElem_Recv[size]; iRecv++) markerRecv[iRecv] = 0; - unsigned long *idRecv = new unsigned long[nElem_Recv[size]]; - for (iRecv = 0; iRecv < nElem_Recv[size]; iRecv++) - idRecv[iRecv] = 0; + unsigned long* idRecv = new unsigned long[nElem_Recv[size]]; + for (iRecv = 0; iRecv < nElem_Recv[size]; iRecv++) idRecv[iRecv] = 0; /*--- Allocate memory for the MPI requests if we need to communicate. ---*/ if (nSends > 0) { - connSendReq = new SU2_MPI::Request[nSends]; + connSendReq = new SU2_MPI::Request[nSends]; markerSendReq = new SU2_MPI::Request[nSends]; - idSendReq = new SU2_MPI::Request[nSends]; + idSendReq = new SU2_MPI::Request[nSends]; } if (nRecvs > 0) { - connRecvReq = new SU2_MPI::Request[nRecvs]; + connRecvReq = new SU2_MPI::Request[nRecvs]; markerRecvReq = new SU2_MPI::Request[nRecvs]; - idRecvReq = new SU2_MPI::Request[nRecvs]; + idRecvReq = new SU2_MPI::Request[nRecvs]; } /*--- Launch the non-blocking sends and receives. ---*/ - InitiateCommsAll(connSend, nElem_Send, connSendReq, - connRecv, nElem_Recv, connRecvReq, - NODES_PER_ELEMENT, COMM_TYPE_UNSIGNED_LONG); + InitiateCommsAll(connSend, nElem_Send, connSendReq, connRecv, nElem_Recv, connRecvReq, NODES_PER_ELEMENT, + COMM_TYPE_UNSIGNED_LONG); - InitiateCommsAll(markerSend, nElem_Send, markerSendReq, - markerRecv, nElem_Recv, markerRecvReq, - 1, COMM_TYPE_UNSIGNED_LONG); + InitiateCommsAll(markerSend, nElem_Send, markerSendReq, markerRecv, nElem_Recv, markerRecvReq, 1, + COMM_TYPE_UNSIGNED_LONG); - InitiateCommsAll(idSend, nElem_Send, idSendReq, - idRecv, nElem_Recv, idRecvReq, - 1, COMM_TYPE_UNSIGNED_LONG); + InitiateCommsAll(idSend, nElem_Send, idSendReq, idRecv, nElem_Recv, idRecvReq, 1, COMM_TYPE_UNSIGNED_LONG); /*--- Copy my own rank's data into the recv buffer directly. ---*/ if (rank == MASTER_NODE) { - - iRecv = NODES_PER_ELEMENT*nElem_Recv[rank]; - myStart = NODES_PER_ELEMENT*nElem_Send[rank]; - myFinal = NODES_PER_ELEMENT*nElem_Send[rank+1]; + iRecv = NODES_PER_ELEMENT * nElem_Recv[rank]; + myStart = NODES_PER_ELEMENT * nElem_Send[rank]; + myFinal = NODES_PER_ELEMENT * nElem_Send[rank + 1]; for (iSend = myStart; iSend < myFinal; iSend++) { connRecv[iRecv] = connSend[iSend]; iRecv++; } - iRecv = nElem_Recv[rank]; + iRecv = nElem_Recv[rank]; myStart = nElem_Send[rank]; - myFinal = nElem_Send[rank+1]; + myFinal = nElem_Send[rank + 1]; for (iSend = myStart; iSend < myFinal; iSend++) { markerRecv[iRecv] = markerSend[iSend]; - idRecv[iRecv] = idSend[iSend]; + idRecv[iRecv] = idSend[iSend]; iRecv++; } - } /*--- Complete the non-blocking communications. ---*/ - CompleteCommsAll(nSends, connSendReq, nRecvs, connRecvReq); + CompleteCommsAll(nSends, connSendReq, nRecvs, connRecvReq); CompleteCommsAll(nSends, markerSendReq, nRecvs, markerRecvReq); - CompleteCommsAll(nSends, idSendReq, nRecvs, idRecvReq); + CompleteCommsAll(nSends, idSendReq, nRecvs, idRecvReq); /*--- Store the connectivity for this rank in the proper data structure before post-processing below. First, allocate appropriate amount of memory for this section. ---*/ if (nElem_Recv[size] > 0) { - Conn_Elem = new unsigned long[NODES_PER_ELEMENT*nElem_Recv[size]]; - int count = 0; nElem_Total = 0; + Conn_Elem = new unsigned long[NODES_PER_ELEMENT * nElem_Recv[size]]; + int count = 0; + nElem_Total = 0; for (iRecv = 0; iRecv < nElem_Recv[size]; iRecv++) { nElem_Total++; for (iNode = 0; iNode < NODES_PER_ELEMENT; iNode++) { - Conn_Elem[count] = connRecv[iRecv*NODES_PER_ELEMENT+iNode]; + Conn_Elem[count] = connRecv[iRecv * NODES_PER_ELEMENT + iNode]; count++; } } @@ -1684,24 +1598,24 @@ void CPhysicalGeometry::PartitionSurfaceConnectivity(CConfig *config, case LINE: nLinear_Line = nElem_Total; if (nLinear_Line > 0) { - Conn_Line_Linear = Conn_Elem; - ID_Line_Linear = Linear_Markers; + Conn_Line_Linear = Conn_Elem; + ID_Line_Linear = Linear_Markers; Elem_ID_Line_Linear = ID_SurfElem; } break; case TRIANGLE: nLinear_BoundTria = nElem_Total; if (nLinear_BoundTria > 0) { - Conn_BoundTria_Linear = Conn_Elem; - ID_BoundTria_Linear = Linear_Markers; + Conn_BoundTria_Linear = Conn_Elem; + ID_BoundTria_Linear = Linear_Markers; Elem_ID_BoundTria_Linear = ID_SurfElem; } break; case QUADRILATERAL: nLinear_BoundQuad = nElem_Total; if (nLinear_BoundQuad > 0) { - Conn_BoundQuad_Linear = Conn_Elem; - ID_BoundQuad_Linear = Linear_Markers; + Conn_BoundQuad_Linear = Conn_Elem; + ID_BoundQuad_Linear = Linear_Markers; Elem_ID_BoundQuad_Linear = ID_SurfElem; } break; @@ -1712,46 +1626,42 @@ void CPhysicalGeometry::PartitionSurfaceConnectivity(CConfig *config, /*--- Free temporary memory from communications ---*/ - delete [] connSendReq; - delete [] markerSendReq; - delete [] idSendReq; - - delete [] connRecvReq; - delete [] markerRecvReq; - delete [] idRecvReq; + delete[] connSendReq; + delete[] markerSendReq; + delete[] idSendReq; - delete [] connSend; - delete [] markerSend; - delete [] idSend; + delete[] connRecvReq; + delete[] markerRecvReq; + delete[] idRecvReq; - delete [] connRecv; - delete [] markerRecv; - delete [] idRecv; + delete[] connSend; + delete[] markerSend; + delete[] idSend; - delete [] nElem_Recv; - delete [] nElem_Send; - delete [] nElem_Flag; + delete[] connRecv; + delete[] markerRecv; + delete[] idRecv; + delete[] nElem_Recv; + delete[] nElem_Send; + delete[] nElem_Flag; } -void CPhysicalGeometry::DistributeSurfaceConnectivity(CConfig *config, - CGeometry *geometry, - unsigned short Elem_Type) { - +void CPhysicalGeometry::DistributeSurfaceConnectivity(CConfig* config, CGeometry* geometry, unsigned short Elem_Type) { unsigned short NODES_PER_ELEMENT = 0; unsigned long iProcessor, NELEM = 0; unsigned long iElem, iNode, jNode, nElem_Total = 0, Global_Index; - unsigned long *Conn_Linear = nullptr; - unsigned long *Conn_Elem = nullptr; - unsigned long *Linear_Markers = nullptr; - unsigned long *ID_SurfElem_Linear = nullptr; - unsigned long *Local_Markers = nullptr; - unsigned long *ID_SurfElem = nullptr; + unsigned long* Conn_Linear = nullptr; + unsigned long* Conn_Elem = nullptr; + unsigned long* Linear_Markers = nullptr; + unsigned long* ID_SurfElem_Linear = nullptr; + unsigned long* Local_Markers = nullptr; + unsigned long* ID_SurfElem = nullptr; - SU2_MPI::Request *connSendReq = nullptr,*markerSendReq = nullptr,*idSendReq = nullptr; - SU2_MPI::Request *connRecvReq = nullptr,*markerRecvReq = nullptr,*idRecvReq = nullptr; + SU2_MPI::Request *connSendReq = nullptr, *markerSendReq = nullptr, *idSendReq = nullptr; + SU2_MPI::Request *connRecvReq = nullptr, *markerRecvReq = nullptr, *idRecvReq = nullptr; int iProc, iSend, iRecv, myStart, myFinal; /*--- Store the local number of this element type and the number of nodes @@ -1761,24 +1671,24 @@ void CPhysicalGeometry::DistributeSurfaceConnectivity(CConfig *config, switch (Elem_Type) { case LINE: - NELEM = nLinear_Line; - NODES_PER_ELEMENT = N_POINTS_LINE; - Conn_Linear = Conn_Line_Linear; - Linear_Markers = ID_Line_Linear; + NELEM = nLinear_Line; + NODES_PER_ELEMENT = N_POINTS_LINE; + Conn_Linear = Conn_Line_Linear; + Linear_Markers = ID_Line_Linear; ID_SurfElem_Linear = Elem_ID_Line_Linear; break; case TRIANGLE: - NELEM = nLinear_BoundTria; - NODES_PER_ELEMENT = N_POINTS_TRIANGLE; - Conn_Linear = Conn_BoundTria_Linear; - Linear_Markers = ID_BoundTria_Linear; + NELEM = nLinear_BoundTria; + NODES_PER_ELEMENT = N_POINTS_TRIANGLE; + Conn_Linear = Conn_BoundTria_Linear; + Linear_Markers = ID_BoundTria_Linear; ID_SurfElem_Linear = Elem_ID_BoundTria_Linear; break; case QUADRILATERAL: - NELEM = nLinear_BoundQuad; - NODES_PER_ELEMENT = N_POINTS_QUADRILATERAL; - Conn_Linear = Conn_BoundQuad_Linear; - Linear_Markers = ID_BoundQuad_Linear; + NELEM = nLinear_BoundQuad; + NODES_PER_ELEMENT = N_POINTS_QUADRILATERAL; + Conn_Linear = Conn_BoundQuad_Linear; + Linear_Markers = ID_BoundQuad_Linear; ID_SurfElem_Linear = Elem_ID_BoundQuad_Linear; break; default: @@ -1791,21 +1701,25 @@ void CPhysicalGeometry::DistributeSurfaceConnectivity(CConfig *config, and decide how many elements we must send to each other rank in order to have all elements distributed according to the ParMETIS coloring. ---*/ - int *nElem_Send = new int[size+1]; nElem_Send[0] = 0; - int *nElem_Recv = new int[size+1]; nElem_Recv[0] = 0; - int *nElem_Flag = new int[size]; + int* nElem_Send = new int[size + 1]; + nElem_Send[0] = 0; + int* nElem_Recv = new int[size + 1]; + nElem_Recv[0] = 0; + int* nElem_Flag = new int[size]; for (iProc = 0; iProc < size; iProc++) { - nElem_Send[iProc] = 0; nElem_Recv[iProc] = 0; nElem_Flag[iProc]= -1; + nElem_Send[iProc] = 0; + nElem_Recv[iProc] = 0; + nElem_Flag[iProc] = -1; } - nElem_Send[size] = 0; nElem_Recv[size] = 0; + nElem_Send[size] = 0; + nElem_Recv[size] = 0; for (iElem = 0; iElem < NELEM; iElem++) { for (iNode = 0; iNode < NODES_PER_ELEMENT; iNode++) { - /*--- Get the index of the current point. ---*/ - Global_Index = Conn_Linear[iElem*NODES_PER_ELEMENT+iNode]; + Global_Index = Conn_Linear[iElem * NODES_PER_ELEMENT + iNode]; /*--- We have the color stored in a map for all local points. ---*/ @@ -1816,9 +1730,8 @@ void CPhysicalGeometry::DistributeSurfaceConnectivity(CConfig *config, if ((nElem_Flag[iProcessor] != (int)iElem)) { nElem_Flag[iProcessor] = (int)iElem; - nElem_Send[iProcessor+1]++; + nElem_Send[iProcessor + 1]++; } - } } @@ -1826,8 +1739,7 @@ void CPhysicalGeometry::DistributeSurfaceConnectivity(CConfig *config, all processors. After this communication, each proc knows how many cells it will receive from each other processor. ---*/ - SU2_MPI::Alltoall(&(nElem_Send[1]), 1, MPI_INT, - &(nElem_Recv[1]), 1, MPI_INT, SU2_MPI::GetComm()); + SU2_MPI::Alltoall(&(nElem_Send[1]), 1, MPI_INT, &(nElem_Recv[1]), 1, MPI_INT, SU2_MPI::GetComm()); /*--- Prepare to send connectivities. First check how many messages we will be sending and receiving. Here we also put @@ -1838,49 +1750,45 @@ void CPhysicalGeometry::DistributeSurfaceConnectivity(CConfig *config, for (iProc = 0; iProc < size; iProc++) nElem_Flag[iProc] = -1; for (iProc = 0; iProc < size; iProc++) { - if ((iProc != rank) && (nElem_Send[iProc+1] > 0)) nSends++; - if ((iProc != rank) && (nElem_Recv[iProc+1] > 0)) nRecvs++; + if ((iProc != rank) && (nElem_Send[iProc + 1] > 0)) nSends++; + if ((iProc != rank) && (nElem_Recv[iProc + 1] > 0)) nRecvs++; - nElem_Send[iProc+1] += nElem_Send[iProc]; - nElem_Recv[iProc+1] += nElem_Recv[iProc]; + nElem_Send[iProc + 1] += nElem_Send[iProc]; + nElem_Recv[iProc + 1] += nElem_Recv[iProc]; } /*--- Allocate memory to hold the connectivity that we are sending. ---*/ - unsigned long *connSend = nullptr; - connSend = new unsigned long[NODES_PER_ELEMENT*nElem_Send[size]]; - for (iSend = 0; iSend < NODES_PER_ELEMENT*nElem_Send[size]; iSend++) - connSend[iSend] = 0; + unsigned long* connSend = nullptr; + connSend = new unsigned long[NODES_PER_ELEMENT * nElem_Send[size]]; + for (iSend = 0; iSend < NODES_PER_ELEMENT * nElem_Send[size]; iSend++) connSend[iSend] = 0; /*--- Allocate arrays for storing the marker global index. ---*/ - unsigned long *markerSend = new unsigned long[nElem_Send[size]]; + unsigned long* markerSend = new unsigned long[nElem_Send[size]]; for (iSend = 0; iSend < nElem_Send[size]; iSend++) markerSend[iSend] = 0; - unsigned long *idSend = new unsigned long[nElem_Send[size]]; + unsigned long* idSend = new unsigned long[nElem_Send[size]]; for (iSend = 0; iSend < nElem_Send[size]; iSend++) idSend[iSend] = 0; /*--- Create an index variable to keep track of our index position as we load up the send buffer. ---*/ - unsigned long *index = new unsigned long[size]; - for (iProc = 0; iProc < size; iProc++) - index[iProc] = NODES_PER_ELEMENT*nElem_Send[iProc]; + unsigned long* index = new unsigned long[size]; + for (iProc = 0; iProc < size; iProc++) index[iProc] = NODES_PER_ELEMENT * nElem_Send[iProc]; - unsigned long *markerIndex = new unsigned long[size]; - for (iProc = 0; iProc < size; iProc++) - markerIndex[iProc] = nElem_Send[iProc]; + unsigned long* markerIndex = new unsigned long[size]; + for (iProc = 0; iProc < size; iProc++) markerIndex[iProc] = nElem_Send[iProc]; /*--- Loop through our elements and load the elems and their additional data that we will send to the other procs. ---*/ for (iElem = 0; iElem < NELEM; iElem++) { for (iNode = 0; iNode < NODES_PER_ELEMENT; iNode++) { - /*--- Get the index of the current point. ---*/ - Global_Index = Conn_Linear[iElem*NODES_PER_ELEMENT+iNode]; + Global_Index = Conn_Linear[iElem * NODES_PER_ELEMENT + iNode]; /*--- We have the color stored in a map for all local points. ---*/ @@ -1890,7 +1798,6 @@ void CPhysicalGeometry::DistributeSurfaceConnectivity(CConfig *config, for sending. ---*/ if (nElem_Flag[iProcessor] != (int)iElem) { - nElem_Flag[iProcessor] = (int)iElem; unsigned long nn = index[iProcessor]; unsigned long mm = markerIndex[iProcessor]; @@ -1898,111 +1805,105 @@ void CPhysicalGeometry::DistributeSurfaceConnectivity(CConfig *config, /*--- Load the connectivity values. ---*/ for (jNode = 0; jNode < NODES_PER_ELEMENT; jNode++) { - /*--- Note that elements are already stored directly based on their global index for the nodes. ---*/ - connSend[nn] = Conn_Linear[iElem*NODES_PER_ELEMENT+jNode]; nn++; - + connSend[nn] = Conn_Linear[iElem * NODES_PER_ELEMENT + jNode]; + nn++; } /*--- Global marker ID for this element. ---*/ markerSend[mm] = Linear_Markers[iElem]; - idSend[mm] = ID_SurfElem_Linear[iElem]; + idSend[mm] = ID_SurfElem_Linear[iElem]; /*--- Increment the index by the message length ---*/ index[iProcessor] += NODES_PER_ELEMENT; markerIndex[iProcessor]++; - } } } /*--- Free memory after loading up the send buffer. ---*/ - delete [] index; - delete [] markerIndex; + delete[] index; + delete[] markerIndex; /*--- Allocate the memory that we need for receiving the conn values and then cue up the non-blocking receives. Note that we do not include our own rank in the communications. We will directly copy our own data later. ---*/ - unsigned long *connRecv = nullptr; - connRecv = new unsigned long[NODES_PER_ELEMENT*nElem_Recv[size]]; - for (iRecv = 0; iRecv < NODES_PER_ELEMENT*nElem_Recv[size]; iRecv++) - connRecv[iRecv] = 0; + unsigned long* connRecv = nullptr; + connRecv = new unsigned long[NODES_PER_ELEMENT * nElem_Recv[size]]; + for (iRecv = 0; iRecv < NODES_PER_ELEMENT * nElem_Recv[size]; iRecv++) connRecv[iRecv] = 0; - unsigned long *markerRecv = new unsigned long[nElem_Recv[size]]; + unsigned long* markerRecv = new unsigned long[nElem_Recv[size]]; for (iRecv = 0; iRecv < nElem_Recv[size]; iRecv++) markerRecv[iRecv] = 0; - unsigned long *idRecv = new unsigned long[nElem_Recv[size]]; + unsigned long* idRecv = new unsigned long[nElem_Recv[size]]; for (iRecv = 0; iRecv < nElem_Recv[size]; iRecv++) idRecv[iRecv] = 0; /*--- Allocate memory for the MPI requests if we need to communicate. ---*/ if (nSends > 0) { - connSendReq = new SU2_MPI::Request[nSends]; + connSendReq = new SU2_MPI::Request[nSends]; markerSendReq = new SU2_MPI::Request[nSends]; - idSendReq = new SU2_MPI::Request[nSends]; + idSendReq = new SU2_MPI::Request[nSends]; } if (nRecvs > 0) { - connRecvReq = new SU2_MPI::Request[nRecvs]; + connRecvReq = new SU2_MPI::Request[nRecvs]; markerRecvReq = new SU2_MPI::Request[nRecvs]; - idRecvReq = new SU2_MPI::Request[nRecvs]; + idRecvReq = new SU2_MPI::Request[nRecvs]; } /*--- Launch the non-blocking sends and receives. ---*/ - InitiateCommsAll(connSend, nElem_Send, connSendReq, - connRecv, nElem_Recv, connRecvReq, - NODES_PER_ELEMENT, COMM_TYPE_UNSIGNED_LONG); + InitiateCommsAll(connSend, nElem_Send, connSendReq, connRecv, nElem_Recv, connRecvReq, NODES_PER_ELEMENT, + COMM_TYPE_UNSIGNED_LONG); - InitiateCommsAll(markerSend, nElem_Send, markerSendReq, - markerRecv, nElem_Recv, markerRecvReq, - 1, COMM_TYPE_UNSIGNED_LONG); + InitiateCommsAll(markerSend, nElem_Send, markerSendReq, markerRecv, nElem_Recv, markerRecvReq, 1, + COMM_TYPE_UNSIGNED_LONG); - InitiateCommsAll(idSend, nElem_Send, idSendReq, - idRecv, nElem_Recv, idRecvReq, - 1, COMM_TYPE_UNSIGNED_LONG); + InitiateCommsAll(idSend, nElem_Send, idSendReq, idRecv, nElem_Recv, idRecvReq, 1, COMM_TYPE_UNSIGNED_LONG); /*--- Copy my own rank's data into the recv buffer directly. ---*/ - iRecv = NODES_PER_ELEMENT*nElem_Recv[rank]; - myStart = NODES_PER_ELEMENT*nElem_Send[rank]; - myFinal = NODES_PER_ELEMENT*nElem_Send[rank+1]; + iRecv = NODES_PER_ELEMENT * nElem_Recv[rank]; + myStart = NODES_PER_ELEMENT * nElem_Send[rank]; + myFinal = NODES_PER_ELEMENT * nElem_Send[rank + 1]; for (iSend = myStart; iSend < myFinal; iSend++) { connRecv[iRecv] = connSend[iSend]; iRecv++; } - iRecv = nElem_Recv[rank]; + iRecv = nElem_Recv[rank]; myStart = nElem_Send[rank]; - myFinal = nElem_Send[rank+1]; + myFinal = nElem_Send[rank + 1]; for (iSend = myStart; iSend < myFinal; iSend++) { markerRecv[iRecv] = markerSend[iSend]; - idRecv[iRecv] = idSend[iSend]; + idRecv[iRecv] = idSend[iSend]; iRecv++; } /*--- Complete the non-blocking communications. ---*/ - CompleteCommsAll(nSends, connSendReq, nRecvs, connRecvReq); + CompleteCommsAll(nSends, connSendReq, nRecvs, connRecvReq); CompleteCommsAll(nSends, markerSendReq, nRecvs, markerRecvReq); - CompleteCommsAll(nSends, idSendReq, nRecvs, idRecvReq); + CompleteCommsAll(nSends, idSendReq, nRecvs, idRecvReq); /*--- Store the connectivity for this rank in the proper data structure. It will be loaded into the geometry objects in a later step. ---*/ if (nElem_Recv[size] > 0) { - Conn_Elem = new unsigned long[NODES_PER_ELEMENT*nElem_Recv[size]]; - int count = 0; nElem_Total = 0; + Conn_Elem = new unsigned long[NODES_PER_ELEMENT * nElem_Recv[size]]; + int count = 0; + nElem_Total = 0; for (iRecv = 0; iRecv < nElem_Recv[size]; iRecv++) { nElem_Total++; for (iNode = 0; iNode < NODES_PER_ELEMENT; iNode++) { - Conn_Elem[count] = connRecv[iRecv*NODES_PER_ELEMENT+iNode]; + Conn_Elem[count] = connRecv[iRecv * NODES_PER_ELEMENT + iNode]; count++; } } @@ -2033,24 +1934,24 @@ void CPhysicalGeometry::DistributeSurfaceConnectivity(CConfig *config, case LINE: nLocal_Line = nElem_Total; if (nLocal_Line > 0) { - Conn_Line = Conn_Elem; - ID_Line = Local_Markers; + Conn_Line = Conn_Elem; + ID_Line = Local_Markers; Elem_ID_Line = ID_SurfElem; } break; case TRIANGLE: nLocal_BoundTria = nElem_Total; if (nLocal_BoundTria > 0) { - Conn_BoundTria = Conn_Elem; - ID_BoundTria = Local_Markers; + Conn_BoundTria = Conn_Elem; + ID_BoundTria = Local_Markers; Elem_ID_BoundTria = ID_SurfElem; } break; case QUADRILATERAL: nLocal_BoundQuad = nElem_Total; if (nLocal_BoundQuad > 0) { - Conn_BoundQuad = Conn_Elem; - ID_BoundQuad = Local_Markers; + Conn_BoundQuad = Conn_Elem; + ID_BoundQuad = Local_Markers; Elem_ID_BoundQuad = ID_SurfElem; } break; @@ -2061,28 +1962,26 @@ void CPhysicalGeometry::DistributeSurfaceConnectivity(CConfig *config, /*--- Free temporary memory from communications ---*/ - delete [] connSendReq; - delete [] markerSendReq; - delete [] idSendReq; - - delete [] connRecvReq; - delete [] markerRecvReq; - delete [] idRecvReq; - - delete [] connSend; - delete [] connRecv; - delete [] markerSend; - delete [] markerRecv; - delete [] idSend; - delete [] idRecv; - delete [] nElem_Recv; - delete [] nElem_Send; - delete [] nElem_Flag; - + delete[] connSendReq; + delete[] markerSendReq; + delete[] idSendReq; + + delete[] connRecvReq; + delete[] markerRecvReq; + delete[] idRecvReq; + + delete[] connSend; + delete[] connRecv; + delete[] markerSend; + delete[] markerRecv; + delete[] idSend; + delete[] idRecv; + delete[] nElem_Recv; + delete[] nElem_Send; + delete[] nElem_Flag; } -void CPhysicalGeometry::DistributeMarkerTags(CConfig *config, CGeometry *geometry) { - +void CPhysicalGeometry::DistributeMarkerTags(CConfig* config, CGeometry* geometry) { unsigned long iMarker, index, iChar; char str_buf[MAX_STRING_SIZE]; @@ -2096,48 +1995,43 @@ void CPhysicalGeometry::DistributeMarkerTags(CConfig *config, CGeometry *geometr /*--- Broadcast the global number of markers in the mesh. ---*/ - SU2_MPI::Bcast(&nMarker_Global, 1, MPI_UNSIGNED_LONG, - MASTER_NODE, SU2_MPI::GetComm()); + SU2_MPI::Bcast(&nMarker_Global, 1, MPI_UNSIGNED_LONG, MASTER_NODE, SU2_MPI::GetComm()); - char *mpi_str_buf = new char[nMarker_Global*MAX_STRING_SIZE](); + char* mpi_str_buf = new char[nMarker_Global * MAX_STRING_SIZE](); if (rank == MASTER_NODE) { for (iMarker = 0; iMarker < nMarker_Global; iMarker++) { - SPRINTF(&mpi_str_buf[iMarker*MAX_STRING_SIZE], "%s", - config->GetMarker_All_TagBound(iMarker).c_str()); + SPRINTF(&mpi_str_buf[iMarker * MAX_STRING_SIZE], "%s", config->GetMarker_All_TagBound(iMarker).c_str()); } } /*--- Broadcast the string names of the variables. ---*/ - SU2_MPI::Bcast(mpi_str_buf, (int)nMarker_Global*MAX_STRING_SIZE, MPI_CHAR, - MASTER_NODE, SU2_MPI::GetComm()); + SU2_MPI::Bcast(mpi_str_buf, (int)nMarker_Global * MAX_STRING_SIZE, MPI_CHAR, MASTER_NODE, SU2_MPI::GetComm()); /*--- Now parse the string names and load into our marker tag vector. We also need to set the values of all markers into the config. ---*/ for (iMarker = 0; iMarker < nMarker_Global; iMarker++) { - index = iMarker*MAX_STRING_SIZE; + index = iMarker * MAX_STRING_SIZE; for (iChar = 0; iChar < MAX_STRING_SIZE; iChar++) { str_buf[iChar] = mpi_str_buf[index + iChar]; } Marker_Tags.push_back(str_buf); - config->SetMarker_All_TagBound(iMarker,str_buf); - config->SetMarker_All_SendRecv(iMarker,NO); + config->SetMarker_All_TagBound(iMarker, str_buf); + config->SetMarker_All_SendRecv(iMarker, NO); } /*--- Free string buffer memory. ---*/ - delete [] mpi_str_buf; - + delete[] mpi_str_buf; } -void CPhysicalGeometry::LoadPoints(CConfig *config, CGeometry *geometry) { - +void CPhysicalGeometry::LoadPoints(CConfig* config, CGeometry* geometry) { unsigned long iPoint, jPoint, iOwned, iPeriodic, iGhost; /*--- Create the basic point structures before storing the points. ---*/ - nPoint = nLocal_Point; + nPoint = nLocal_Point; nPointDomain = nLocal_PointDomain; nodes = new CPoint(nPoint, nDim, MESH_0, config); @@ -2153,22 +2047,22 @@ void CPhysicalGeometry::LoadPoints(CConfig *config, CGeometry *geometry) { /*--- Set our counters correctly based on the number of owned and ghost nodes that we counted during the partitioning. ---*/ - jPoint = 0; - iOwned = 0; + jPoint = 0; + iOwned = 0; iPeriodic = nLocal_PointDomain; - iGhost = nLocal_PointDomain + nLocal_PointPeriodic; + iGhost = nLocal_PointDomain + nLocal_PointPeriodic; /*--- Loop over all of the points that we have recv'd and store the coordinates, global index, and colors ---*/ for (iPoint = 0; iPoint < nPoint; iPoint++) { - /*--- Set the starting point to the correct counter for this point. ---*/ if (Local_Colors[iPoint] == (unsigned long)rank) { if (Local_Points[iPoint] < geometry->GetGlobal_nPointDomain()) jPoint = iOwned; - else jPoint = iPeriodic; + else + jPoint = iPeriodic; } else { jPoint = iGhost; } @@ -2179,7 +2073,7 @@ void CPhysicalGeometry::LoadPoints(CConfig *config, CGeometry *geometry) { /*--- Allocating the Point object ---*/ - nodes->SetCoord(jPoint, &Local_Coords[iPoint*nDim]); + nodes->SetCoord(jPoint, &Local_Coords[iPoint * nDim]); nodes->SetGlobalIndex(jPoint, Local_to_Global_Point[jPoint]); /*--- Set the color ---*/ @@ -2191,7 +2085,8 @@ void CPhysicalGeometry::LoadPoints(CConfig *config, CGeometry *geometry) { if (Local_Colors[iPoint] == (unsigned long)rank) { if (Local_Points[iPoint] < geometry->GetGlobal_nPointDomain()) iOwned++; - else iPeriodic++; + else + iPeriodic++; } else { iGhost++; } @@ -2200,8 +2095,7 @@ void CPhysicalGeometry::LoadPoints(CConfig *config, CGeometry *geometry) { /*--- Create the global to local mapping, which will be useful for loading the elements and boundaries in subsequent steps. ---*/ - for (iPoint = 0; iPoint < nPoint; iPoint++) - Global_to_Local_Point[Local_to_Global_Point[iPoint]] = iPoint; + for (iPoint = 0; iPoint < nPoint; iPoint++) Global_to_Local_Point[Local_to_Global_Point[iPoint]] = iPoint; /*--- Set the value of Global_nPoint and Global_nPointDomain ---*/ @@ -2209,10 +2103,8 @@ void CPhysicalGeometry::LoadPoints(CConfig *config, CGeometry *geometry) { unsigned long Local_nPointDomain = nPointDomain; #ifdef HAVE_MPI - SU2_MPI::Allreduce(&Local_nPoint, &Global_nPoint, 1, - MPI_UNSIGNED_LONG, MPI_SUM, SU2_MPI::GetComm()); - SU2_MPI::Allreduce(&Local_nPointDomain, &Global_nPointDomain, 1, - MPI_UNSIGNED_LONG, MPI_SUM, SU2_MPI::GetComm()); + SU2_MPI::Allreduce(&Local_nPoint, &Global_nPoint, 1, MPI_UNSIGNED_LONG, MPI_SUM, SU2_MPI::GetComm()); + SU2_MPI::Allreduce(&Local_nPointDomain, &Global_nPointDomain, 1, MPI_UNSIGNED_LONG, MPI_SUM, SU2_MPI::GetComm()); #else Global_nPoint = Local_nPoint; Global_nPointDomain = Local_nPointDomain; @@ -2220,11 +2112,9 @@ void CPhysicalGeometry::LoadPoints(CConfig *config, CGeometry *geometry) { if ((rank == MASTER_NODE) && (size > SINGLE_NODE)) cout << Global_nPoint << " vertices including ghost points. " << endl; - } -void CPhysicalGeometry::LoadVolumeElements(CConfig *config, CGeometry *geometry) { - +void CPhysicalGeometry::LoadVolumeElements(CConfig* config, CGeometry* geometry) { unsigned short NODES_PER_ELEMENT; unsigned long iElem, jElem, kElem, iNode, Local_Elem, iGlobal_Index; @@ -2253,37 +2143,37 @@ void CPhysicalGeometry::LoadVolumeElements(CConfig *config, CGeometry *geometry) overwriting the duplicate entries. ---*/ jElem = 0; - for (iElem=0; iElem < nLocal_Tria; iElem++) { + for (iElem = 0; iElem < nLocal_Tria; iElem++) { Tria_List[ID_Tria[iElem]] = iElem; } nTria = Tria_List.size(); jElem = 0; - for (iElem=0; iElem < nLocal_Quad; iElem++) { + for (iElem = 0; iElem < nLocal_Quad; iElem++) { Quad_List[ID_Quad[iElem]] = iElem; } nQuad = Quad_List.size(); jElem = 0; - for (iElem=0; iElem < nLocal_Tetr; iElem++) { + for (iElem = 0; iElem < nLocal_Tetr; iElem++) { Tetr_List[ID_Tetr[iElem]] = iElem; } nTetr = Tetr_List.size(); jElem = 0; - for (iElem=0; iElem < nLocal_Hexa; iElem++) { + for (iElem = 0; iElem < nLocal_Hexa; iElem++) { Hexa_List[ID_Hexa[iElem]] = iElem; } nHexa = Hexa_List.size(); jElem = 0; - for (iElem=0; iElem < nLocal_Pris; iElem++) { + for (iElem = 0; iElem < nLocal_Pris; iElem++) { Pris_List[ID_Pris[iElem]] = iElem; } nPris = Pris_List.size(); jElem = 0; - for (iElem=0; iElem < nLocal_Pyra; iElem++) { + for (iElem = 0; iElem < nLocal_Pyra; iElem++) { Pyra_List[ID_Pyra[iElem]] = iElem; } nPyra = Pyra_List.size(); @@ -2296,12 +2186,11 @@ void CPhysicalGeometry::LoadVolumeElements(CConfig *config, CGeometry *geometry) jElem = 0; nElem = Local_Elem; - elem = new CPrimalGrid*[nElem] (); + elem = new CPrimalGrid*[nElem](); /*--- Store the elements of each type in the proper containers. ---*/ for (it = Tria_List.begin(); it != Tria_List.end(); it++) { - kElem = it->first; iElem = it->second; @@ -2310,22 +2199,20 @@ void CPhysicalGeometry::LoadVolumeElements(CConfig *config, CGeometry *geometry) NODES_PER_ELEMENT = N_POINTS_TRIANGLE; for (iNode = 0; iNode < NODES_PER_ELEMENT; iNode++) { - iGlobal_Index = Conn_Tria[iElem*NODES_PER_ELEMENT+iNode]; + iGlobal_Index = Conn_Tria[iElem * NODES_PER_ELEMENT + iNode]; Local_Nodes[iNode] = Global_to_Local_Point[iGlobal_Index]; } /*--- Create the element object. ---*/ - elem[jElem] = new CTriangle(Local_Nodes[0], - Local_Nodes[1], - Local_Nodes[2]); + elem[jElem] = new CTriangle(Local_Nodes[0], Local_Nodes[1], Local_Nodes[2]); elem[jElem]->SetGlobalIndex(kElem); /*--- Increment our local counters. ---*/ - jElem++; iElemTria++; - + jElem++; + iElemTria++; } /*--- Free memory as we go. ---*/ @@ -2333,7 +2220,6 @@ void CPhysicalGeometry::LoadVolumeElements(CConfig *config, CGeometry *geometry) Tria_List.clear(); for (it = Quad_List.begin(); it != Quad_List.end(); it++) { - kElem = it->first; iElem = it->second; @@ -2342,23 +2228,20 @@ void CPhysicalGeometry::LoadVolumeElements(CConfig *config, CGeometry *geometry) NODES_PER_ELEMENT = N_POINTS_QUADRILATERAL; for (iNode = 0; iNode < NODES_PER_ELEMENT; iNode++) { - iGlobal_Index = Conn_Quad[iElem*NODES_PER_ELEMENT+iNode]; + iGlobal_Index = Conn_Quad[iElem * NODES_PER_ELEMENT + iNode]; Local_Nodes[iNode] = Global_to_Local_Point[iGlobal_Index]; } /*--- Create the element object. ---*/ - elem[jElem] = new CQuadrilateral(Local_Nodes[0], - Local_Nodes[1], - Local_Nodes[2], - Local_Nodes[3]); + elem[jElem] = new CQuadrilateral(Local_Nodes[0], Local_Nodes[1], Local_Nodes[2], Local_Nodes[3]); elem[jElem]->SetGlobalIndex(kElem); /*--- Increment our local counters. ---*/ - jElem++; iElemQuad++; - + jElem++; + iElemQuad++; } /*--- Free memory as we go. ---*/ @@ -2366,7 +2249,6 @@ void CPhysicalGeometry::LoadVolumeElements(CConfig *config, CGeometry *geometry) Quad_List.clear(); for (it = Tetr_List.begin(); it != Tetr_List.end(); it++) { - kElem = it->first; iElem = it->second; @@ -2375,23 +2257,20 @@ void CPhysicalGeometry::LoadVolumeElements(CConfig *config, CGeometry *geometry) NODES_PER_ELEMENT = N_POINTS_TETRAHEDRON; for (iNode = 0; iNode < NODES_PER_ELEMENT; iNode++) { - iGlobal_Index = Conn_Tetr[iElem*NODES_PER_ELEMENT+iNode]; + iGlobal_Index = Conn_Tetr[iElem * NODES_PER_ELEMENT + iNode]; Local_Nodes[iNode] = Global_to_Local_Point[iGlobal_Index]; } /*--- Create the element object. ---*/ - elem[jElem] = new CTetrahedron(Local_Nodes[0], - Local_Nodes[1], - Local_Nodes[2], - Local_Nodes[3]); + elem[jElem] = new CTetrahedron(Local_Nodes[0], Local_Nodes[1], Local_Nodes[2], Local_Nodes[3]); elem[jElem]->SetGlobalIndex(kElem); /*--- Increment our local counters. ---*/ - jElem++; iElemTetr++; - + jElem++; + iElemTetr++; } /*--- Free memory as we go. ---*/ @@ -2399,7 +2278,6 @@ void CPhysicalGeometry::LoadVolumeElements(CConfig *config, CGeometry *geometry) Tetr_List.clear(); for (it = Hexa_List.begin(); it != Hexa_List.end(); it++) { - kElem = it->first; iElem = it->second; @@ -2408,27 +2286,21 @@ void CPhysicalGeometry::LoadVolumeElements(CConfig *config, CGeometry *geometry) NODES_PER_ELEMENT = N_POINTS_HEXAHEDRON; for (iNode = 0; iNode < NODES_PER_ELEMENT; iNode++) { - iGlobal_Index = Conn_Hexa[iElem*NODES_PER_ELEMENT+iNode]; + iGlobal_Index = Conn_Hexa[iElem * NODES_PER_ELEMENT + iNode]; Local_Nodes[iNode] = Global_to_Local_Point[iGlobal_Index]; } /*--- Create the element object. ---*/ - elem[jElem] = new CHexahedron(Local_Nodes[0], - Local_Nodes[1], - Local_Nodes[2], - Local_Nodes[3], - Local_Nodes[4], - Local_Nodes[5], - Local_Nodes[6], - Local_Nodes[7]); + elem[jElem] = new CHexahedron(Local_Nodes[0], Local_Nodes[1], Local_Nodes[2], Local_Nodes[3], Local_Nodes[4], + Local_Nodes[5], Local_Nodes[6], Local_Nodes[7]); elem[jElem]->SetGlobalIndex(kElem); /*--- Increment our local counters. ---*/ - jElem++; iElemHexa++; - + jElem++; + iElemHexa++; } /*--- Free memory as we go. ---*/ @@ -2436,7 +2308,6 @@ void CPhysicalGeometry::LoadVolumeElements(CConfig *config, CGeometry *geometry) Hexa_List.clear(); for (it = Pris_List.begin(); it != Pris_List.end(); it++) { - kElem = it->first; iElem = it->second; @@ -2445,25 +2316,21 @@ void CPhysicalGeometry::LoadVolumeElements(CConfig *config, CGeometry *geometry) NODES_PER_ELEMENT = N_POINTS_PRISM; for (iNode = 0; iNode < NODES_PER_ELEMENT; iNode++) { - iGlobal_Index = Conn_Pris[iElem*NODES_PER_ELEMENT+iNode]; + iGlobal_Index = Conn_Pris[iElem * NODES_PER_ELEMENT + iNode]; Local_Nodes[iNode] = Global_to_Local_Point[iGlobal_Index]; } /*--- Create the element object. ---*/ - elem[jElem] = new CPrism(Local_Nodes[0], - Local_Nodes[1], - Local_Nodes[2], - Local_Nodes[3], - Local_Nodes[4], - Local_Nodes[5]); + elem[jElem] = + new CPrism(Local_Nodes[0], Local_Nodes[1], Local_Nodes[2], Local_Nodes[3], Local_Nodes[4], Local_Nodes[5]); elem[jElem]->SetGlobalIndex(kElem); /*--- Increment our local counters. ---*/ - jElem++; iElemPris++; - + jElem++; + iElemPris++; } /*--- Free memory as we go. ---*/ @@ -2471,7 +2338,6 @@ void CPhysicalGeometry::LoadVolumeElements(CConfig *config, CGeometry *geometry) Pris_List.clear(); for (it = Pyra_List.begin(); it != Pyra_List.end(); it++) { - kElem = it->first; iElem = it->second; @@ -2480,24 +2346,20 @@ void CPhysicalGeometry::LoadVolumeElements(CConfig *config, CGeometry *geometry) NODES_PER_ELEMENT = N_POINTS_PYRAMID; for (iNode = 0; iNode < NODES_PER_ELEMENT; iNode++) { - iGlobal_Index = Conn_Pyra[iElem*NODES_PER_ELEMENT+iNode]; + iGlobal_Index = Conn_Pyra[iElem * NODES_PER_ELEMENT + iNode]; Local_Nodes[iNode] = Global_to_Local_Point[iGlobal_Index]; } /*--- Create the element object. ---*/ - elem[jElem] = new CPyramid(Local_Nodes[0], - Local_Nodes[1], - Local_Nodes[2], - Local_Nodes[3], - Local_Nodes[4]); + elem[jElem] = new CPyramid(Local_Nodes[0], Local_Nodes[1], Local_Nodes[2], Local_Nodes[3], Local_Nodes[4]); elem[jElem]->SetGlobalIndex(kElem); /*--- Increment our local counters. ---*/ - jElem++; iElemPyra++; - + jElem++; + iElemPyra++; } /*--- Free memory as we go. ---*/ @@ -2507,8 +2369,7 @@ void CPhysicalGeometry::LoadVolumeElements(CConfig *config, CGeometry *geometry) /*--- Communicate the number of each element type to all processors. These values are important for merging and writing output later. ---*/ - SU2_MPI::Allreduce(&Local_Elem, &Global_nElem, 1, - MPI_UNSIGNED_LONG, MPI_SUM, SU2_MPI::GetComm()); + SU2_MPI::Allreduce(&Local_Elem, &Global_nElem, 1, MPI_UNSIGNED_LONG, MPI_SUM, SU2_MPI::GetComm()); if ((rank == MASTER_NODE) && (size > SINGLE_NODE)) cout << Global_nElem << " interior elements including halo cells. " << endl; @@ -2522,62 +2383,48 @@ void CPhysicalGeometry::LoadVolumeElements(CConfig *config, CGeometry *geometry) counters in the recv loop above (to make sure there aren't repeats). ---*/ nelem_triangle = iElemTria; - nelem_quad = iElemQuad; - nelem_tetra = iElemTetr; - nelem_hexa = iElemHexa; - nelem_prism = iElemPris; - nelem_pyramid = iElemPyra; + nelem_quad = iElemQuad; + nelem_tetra = iElemTetr; + nelem_hexa = iElemHexa; + nelem_prism = iElemPris; + nelem_pyramid = iElemPyra; #ifdef HAVE_MPI - unsigned long Local_nElemTri = nelem_triangle; - unsigned long Local_nElemQuad = nelem_quad; - unsigned long Local_nElemTet = nelem_tetra; - unsigned long Local_nElemHex = nelem_hexa; - unsigned long Local_nElemPrism = nelem_prism; + unsigned long Local_nElemTri = nelem_triangle; + unsigned long Local_nElemQuad = nelem_quad; + unsigned long Local_nElemTet = nelem_tetra; + unsigned long Local_nElemHex = nelem_hexa; + unsigned long Local_nElemPrism = nelem_prism; unsigned long Local_nElemPyramid = nelem_pyramid; - SU2_MPI::Allreduce(&Local_nElemTri, &Global_nelem_triangle, 1, - MPI_UNSIGNED_LONG, MPI_SUM, SU2_MPI::GetComm()); - SU2_MPI::Allreduce(&Local_nElemQuad, &Global_nelem_quad, 1, - MPI_UNSIGNED_LONG, MPI_SUM, SU2_MPI::GetComm()); - SU2_MPI::Allreduce(&Local_nElemTet, &Global_nelem_tetra, 1, - MPI_UNSIGNED_LONG, MPI_SUM, SU2_MPI::GetComm()); - SU2_MPI::Allreduce(&Local_nElemHex, &Global_nelem_hexa, 1, - MPI_UNSIGNED_LONG, MPI_SUM, SU2_MPI::GetComm()); - SU2_MPI::Allreduce(&Local_nElemPrism, &Global_nelem_prism, 1, - MPI_UNSIGNED_LONG, MPI_SUM, SU2_MPI::GetComm()); - SU2_MPI::Allreduce(&Local_nElemPyramid, &Global_nelem_pyramid, 1, - MPI_UNSIGNED_LONG, MPI_SUM, SU2_MPI::GetComm()); + SU2_MPI::Allreduce(&Local_nElemTri, &Global_nelem_triangle, 1, MPI_UNSIGNED_LONG, MPI_SUM, SU2_MPI::GetComm()); + SU2_MPI::Allreduce(&Local_nElemQuad, &Global_nelem_quad, 1, MPI_UNSIGNED_LONG, MPI_SUM, SU2_MPI::GetComm()); + SU2_MPI::Allreduce(&Local_nElemTet, &Global_nelem_tetra, 1, MPI_UNSIGNED_LONG, MPI_SUM, SU2_MPI::GetComm()); + SU2_MPI::Allreduce(&Local_nElemHex, &Global_nelem_hexa, 1, MPI_UNSIGNED_LONG, MPI_SUM, SU2_MPI::GetComm()); + SU2_MPI::Allreduce(&Local_nElemPrism, &Global_nelem_prism, 1, MPI_UNSIGNED_LONG, MPI_SUM, SU2_MPI::GetComm()); + SU2_MPI::Allreduce(&Local_nElemPyramid, &Global_nelem_pyramid, 1, MPI_UNSIGNED_LONG, MPI_SUM, SU2_MPI::GetComm()); #else Global_nelem_triangle = nelem_triangle; - Global_nelem_quad = nelem_quad; - Global_nelem_tetra = nelem_tetra; - Global_nelem_hexa = nelem_hexa; - Global_nelem_prism = nelem_prism; - Global_nelem_pyramid = nelem_pyramid; + Global_nelem_quad = nelem_quad; + Global_nelem_tetra = nelem_tetra; + Global_nelem_hexa = nelem_hexa; + Global_nelem_prism = nelem_prism; + Global_nelem_pyramid = nelem_pyramid; #endif /*--- Print information about the elements to the console ---*/ if (rank == MASTER_NODE) { - if (Global_nelem_triangle > 0) - cout << Global_nelem_triangle << " triangles." << endl; - if (Global_nelem_quad > 0) - cout << Global_nelem_quad << " quadrilaterals." << endl; - if (Global_nelem_tetra > 0) - cout << Global_nelem_tetra << " tetrahedra." << endl; - if (Global_nelem_hexa > 0) - cout << Global_nelem_hexa << " hexahedra." << endl; - if (Global_nelem_prism > 0) - cout << Global_nelem_prism << " prisms." << endl; - if (Global_nelem_pyramid > 0) - cout << Global_nelem_pyramid << " pyramids." << endl; + if (Global_nelem_triangle > 0) cout << Global_nelem_triangle << " triangles." << endl; + if (Global_nelem_quad > 0) cout << Global_nelem_quad << " quadrilaterals." << endl; + if (Global_nelem_tetra > 0) cout << Global_nelem_tetra << " tetrahedra." << endl; + if (Global_nelem_hexa > 0) cout << Global_nelem_hexa << " hexahedra." << endl; + if (Global_nelem_prism > 0) cout << Global_nelem_prism << " prisms." << endl; + if (Global_nelem_pyramid > 0) cout << Global_nelem_pyramid << " pyramids." << endl; } - } -void CPhysicalGeometry::LoadSurfaceElements(CConfig *config, CGeometry *geometry) { - +void CPhysicalGeometry::LoadSurfaceElements(CConfig* config, CGeometry* geometry) { unsigned short NODES_PER_ELEMENT; unsigned short iNode, nMarker_Max = config->GetnMarker_Max(); @@ -2600,22 +2447,19 @@ void CPhysicalGeometry::LoadSurfaceElements(CConfig *config, CGeometry *geometry counting the unique set. ---*/ for (iElem = 0; iElem < nLocal_Line; iElem++) { - if (find(Marker_Local.begin(), Marker_Local.end(), - ID_Line[iElem]) == Marker_Local.end()) { + if (find(Marker_Local.begin(), Marker_Local.end(), ID_Line[iElem]) == Marker_Local.end()) { Marker_Local.push_back(ID_Line[iElem]); } } for (iElem = 0; iElem < nLocal_BoundTria; iElem++) { - if (find(Marker_Local.begin(), Marker_Local.end(), - ID_BoundTria[iElem]) == Marker_Local.end()) { + if (find(Marker_Local.begin(), Marker_Local.end(), ID_BoundTria[iElem]) == Marker_Local.end()) { Marker_Local.push_back(ID_BoundTria[iElem]); } } for (iElem = 0; iElem < nLocal_BoundQuad; iElem++) { - if (find(Marker_Local.begin(), Marker_Local.end(), - ID_BoundQuad[iElem]) == Marker_Local.end()) { + if (find(Marker_Local.begin(), Marker_Local.end(), ID_BoundQuad[iElem]) == Marker_Local.end()) { Marker_Local.push_back(ID_BoundQuad[iElem]); } } @@ -2642,13 +2486,11 @@ void CPhysicalGeometry::LoadSurfaceElements(CConfig *config, CGeometry *geometry vector nElemBound_Local; nElemBound_Local.resize(Marker_Local.size()); - for (iMarker = 0; iMarker < Marker_Local.size(); iMarker++) - nElemBound_Local[iMarker] = 0; + for (iMarker = 0; iMarker < Marker_Local.size(); iMarker++) nElemBound_Local[iMarker] = 0; for (iElem = 0; iElem < nLocal_Line; iElem++) { iMarker = Marker_Global_to_Local[ID_Line[iElem]]; - if (find(Line_List[iMarker].begin(), Line_List[iMarker].end(), - Elem_ID_Line[iElem]) == Line_List[iMarker].end()) { + if (find(Line_List[iMarker].begin(), Line_List[iMarker].end(), Elem_ID_Line[iElem]) == Line_List[iMarker].end()) { nElemBound_Local[iMarker]++; Line_List[iMarker].push_back(Elem_ID_Line[iElem]); } @@ -2656,8 +2498,8 @@ void CPhysicalGeometry::LoadSurfaceElements(CConfig *config, CGeometry *geometry for (iElem = 0; iElem < nLocal_BoundTria; iElem++) { iMarker = Marker_Global_to_Local[ID_BoundTria[iElem]]; - if (find(BoundTria_List[iMarker].begin(), BoundTria_List[iMarker].end(), - Elem_ID_BoundTria[iElem]) == BoundTria_List[iMarker].end()) { + if (find(BoundTria_List[iMarker].begin(), BoundTria_List[iMarker].end(), Elem_ID_BoundTria[iElem]) == + BoundTria_List[iMarker].end()) { nElemBound_Local[iMarker]++; BoundTria_List[iMarker].push_back(Elem_ID_BoundTria[iElem]); } @@ -2665,8 +2507,8 @@ void CPhysicalGeometry::LoadSurfaceElements(CConfig *config, CGeometry *geometry for (iElem = 0; iElem < nLocal_BoundQuad; iElem++) { iMarker = Marker_Global_to_Local[ID_BoundQuad[iElem]]; - if (find(BoundQuad_List[iMarker].begin(), BoundQuad_List[iMarker].end(), - Elem_ID_BoundQuad[iElem]) == BoundQuad_List[iMarker].end()) { + if (find(BoundQuad_List[iMarker].begin(), BoundQuad_List[iMarker].end(), Elem_ID_BoundQuad[iElem]) == + BoundQuad_List[iMarker].end()) { nElemBound_Local[iMarker]++; BoundQuad_List[iMarker].push_back(Elem_ID_BoundQuad[iElem]); } @@ -2676,22 +2518,19 @@ void CPhysicalGeometry::LoadSurfaceElements(CConfig *config, CGeometry *geometry with nMarkerMax here, but come back and compute size we need. Same for OVERHEAD - this can precomputed. ---*/ - nMarker = Marker_Local.size(); - nElem_Bound = new unsigned long[nMarker_Max]; - Tag_to_Marker = new string[nMarker_Max]; + nMarker = Marker_Local.size(); + nElem_Bound = new unsigned long[nMarker_Max]; + Tag_to_Marker = new string[nMarker_Max]; Marker_All_SendRecv = new short[nMarker_Max]; /*--- Allocate space for the elements on each marker ---*/ - for (iMarker = 0; iMarker < nMarker; iMarker++) - nElem_Bound[iMarker] = nElemBound_Local[iMarker]; + for (iMarker = 0; iMarker < nMarker; iMarker++) nElem_Bound[iMarker] = nElemBound_Local[iMarker]; - bound = new CPrimalGrid**[nMarker+(OVERHEAD*size)]; - for (iMarker = 0; iMarker < nMarker+(OVERHEAD*size); iMarker++) - bound[iMarker] = nullptr; + bound = new CPrimalGrid**[nMarker + (OVERHEAD * size)]; + for (iMarker = 0; iMarker < nMarker + (OVERHEAD * size); iMarker++) bound[iMarker] = nullptr; - for (iMarker = 0; iMarker < nMarker; iMarker++) - bound[iMarker] = new CPrimalGrid*[nElem_Bound[iMarker]]; + for (iMarker = 0; iMarker < nMarker; iMarker++) bound[iMarker] = new CPrimalGrid*[nElem_Bound[iMarker]]; /*--- Initialize boundary element counters ---*/ @@ -2699,134 +2538,123 @@ void CPhysicalGeometry::LoadSurfaceElements(CConfig *config, CGeometry *geometry iElem_Tria = 0; iElem_Quad = 0; - Line_List.clear(); Line_List.resize(Marker_Local.size()); - BoundTria_List.clear(); BoundTria_List.resize(Marker_Local.size()); - BoundQuad_List.clear(); BoundQuad_List.resize(Marker_Local.size()); + Line_List.clear(); + Line_List.resize(Marker_Local.size()); + BoundTria_List.clear(); + BoundTria_List.resize(Marker_Local.size()); + BoundQuad_List.clear(); + BoundQuad_List.resize(Marker_Local.size()); /*--- Reset our element counter on a marker-basis. ---*/ - for (iMarker = 0; iMarker < nMarker; iMarker++) - nElemBound_Local[iMarker] = 0; + for (iMarker = 0; iMarker < nMarker; iMarker++) nElemBound_Local[iMarker] = 0; /*--- Store the boundary element connectivity. Note here that we have communicated the global index values for the elements, so we need to convert this to the local index when instantiating the element. ---*/ for (iElem = 0; iElem < nLocal_Line; iElem++) { - iMarker = Marker_Global_to_Local[ID_Line[iElem]]; /*--- Avoid duplicates on this marker. ---*/ - if (find(Line_List[iMarker].begin(), Line_List[iMarker].end(), - Elem_ID_Line[iElem]) == Line_List[iMarker].end()) { - + if (find(Line_List[iMarker].begin(), Line_List[iMarker].end(), Elem_ID_Line[iElem]) == Line_List[iMarker].end()) { /*--- Transform the stored connectivity for this element from global to local values on this rank. ---*/ NODES_PER_ELEMENT = N_POINTS_LINE; for (iNode = 0; iNode < NODES_PER_ELEMENT; iNode++) { - iGlobal_Index = Conn_Line[iElem*NODES_PER_ELEMENT+iNode]; + iGlobal_Index = Conn_Line[iElem * NODES_PER_ELEMENT + iNode]; Local_Nodes[iNode] = Global_to_Local_Point[iGlobal_Index]; } /*--- Create the geometry object for this element. ---*/ - bound[iMarker][nElemBound_Local[iMarker]] = new CLine(Local_Nodes[0], - Local_Nodes[1]); + bound[iMarker][nElemBound_Local[iMarker]] = new CLine(Local_Nodes[0], Local_Nodes[1]); /*--- Increment our counters for this marker and element type. ---*/ - nElemBound_Local[iMarker]++; iElem_Line++; + nElemBound_Local[iMarker]++; + iElem_Line++; Line_List[iMarker].push_back(Elem_ID_Line[iElem]); - } } for (iElem = 0; iElem < nLocal_BoundTria; iElem++) { - iMarker = Marker_Global_to_Local[ID_BoundTria[iElem]]; /*--- Avoid duplicates on this marker. ---*/ - if (find(BoundTria_List[iMarker].begin(), BoundTria_List[iMarker].end(), - Elem_ID_BoundTria[iElem]) == BoundTria_List[iMarker].end()) { - + if (find(BoundTria_List[iMarker].begin(), BoundTria_List[iMarker].end(), Elem_ID_BoundTria[iElem]) == + BoundTria_List[iMarker].end()) { /*--- Transform the stored connectivity for this element from global to local values on this rank. ---*/ NODES_PER_ELEMENT = N_POINTS_TRIANGLE; for (iNode = 0; iNode < NODES_PER_ELEMENT; iNode++) { - iGlobal_Index = Conn_BoundTria[iElem*NODES_PER_ELEMENT+iNode]; + iGlobal_Index = Conn_BoundTria[iElem * NODES_PER_ELEMENT + iNode]; Local_Nodes[iNode] = Global_to_Local_Point[iGlobal_Index]; } /*--- Create the geometry object for this element. ---*/ - bound[iMarker][nElemBound_Local[iMarker]] = new CTriangle(Local_Nodes[0], - Local_Nodes[1], - Local_Nodes[2]); + bound[iMarker][nElemBound_Local[iMarker]] = new CTriangle(Local_Nodes[0], Local_Nodes[1], Local_Nodes[2]); /*--- Increment our counters for this marker and element type. ---*/ - nElemBound_Local[iMarker]++; iElem_Tria++; + nElemBound_Local[iMarker]++; + iElem_Tria++; BoundTria_List[iMarker].push_back(Elem_ID_BoundTria[iElem]); - } } for (iElem = 0; iElem < nLocal_BoundQuad; iElem++) { - iMarker = Marker_Global_to_Local[ID_BoundQuad[iElem]]; /*--- Avoid duplicates on this marker. ---*/ - if (find(BoundQuad_List[iMarker].begin(), BoundQuad_List[iMarker].end(), - Elem_ID_BoundQuad[iElem]) == BoundQuad_List[iMarker].end()) { - + if (find(BoundQuad_List[iMarker].begin(), BoundQuad_List[iMarker].end(), Elem_ID_BoundQuad[iElem]) == + BoundQuad_List[iMarker].end()) { /*--- Transform the stored connectivity for this element from global to local values on this rank. ---*/ NODES_PER_ELEMENT = N_POINTS_QUADRILATERAL; for (iNode = 0; iNode < NODES_PER_ELEMENT; iNode++) { - iGlobal_Index = Conn_BoundQuad[iElem*NODES_PER_ELEMENT+iNode]; + iGlobal_Index = Conn_BoundQuad[iElem * NODES_PER_ELEMENT + iNode]; Local_Nodes[iNode] = Global_to_Local_Point[iGlobal_Index]; } /*--- Create the geometry object for this element. ---*/ - bound[iMarker][nElemBound_Local[iMarker]] = new CQuadrilateral(Local_Nodes[0], - Local_Nodes[1], - Local_Nodes[2], - Local_Nodes[3]); + bound[iMarker][nElemBound_Local[iMarker]] = + new CQuadrilateral(Local_Nodes[0], Local_Nodes[1], Local_Nodes[2], Local_Nodes[3]); /*--- Increment our counters for this marker and element type. ---*/ - nElemBound_Local[iMarker]++; iElem_Quad++; + nElemBound_Local[iMarker]++; + iElem_Quad++; BoundQuad_List[iMarker].push_back(Elem_ID_BoundQuad[iElem]); - } } /*--- Store total number of each boundary element type ---*/ - nelem_edge_bound = iElem_Line; + nelem_edge_bound = iElem_Line; nelem_triangle_bound = iElem_Tria; - nelem_quad_bound = iElem_Quad; + nelem_quad_bound = iElem_Quad; /*--- Set some auxiliary information on a per-marker basis. ---*/ for (iMarker = 0; iMarker < nMarker; iMarker++) { - Global_Marker = Marker_Local_to_Global[iMarker]; /*--- Now each domain has the right information ---*/ string Grid_Marker = config->GetMarker_All_TagBound(Global_Marker); - short SendRecv = config->GetMarker_All_SendRecv(Global_Marker); + short SendRecv = config->GetMarker_All_SendRecv(Global_Marker); Tag_to_Marker[iMarker] = Marker_Tags[Global_Marker]; Marker_All_SendRecv[iMarker] = SendRecv; @@ -2835,49 +2663,41 @@ void CPhysicalGeometry::LoadSurfaceElements(CConfig *config, CGeometry *geometry config->SetMarker_All_TagBound(iMarker, Tag_to_Marker[iMarker]); config->SetMarker_All_SendRecv(iMarker, Marker_All_SendRecv[iMarker]); - } /*--- Initialize pointers for turbomachinery computations ---*/ - nSpanWiseSections = new unsigned short[2] (); - SpanWiseValue = new su2double*[2] (); - - nSpanSectionsByMarker = new unsigned short[nMarker] (); - nVertexSpan = new long* [nMarker] (); - nTotVertexSpan = new unsigned long* [nMarker] (); - turbovertex = new CTurboVertex***[nMarker] (); - AverageTurboNormal = new su2double**[nMarker] (); - AverageNormal = new su2double**[nMarker] (); - AverageGridVel = new su2double**[nMarker] (); - AverageTangGridVel = new su2double*[nMarker] (); - SpanArea = new su2double*[nMarker] (); - TurboRadius = new su2double*[nMarker] (); - MaxAngularCoord = new su2double*[nMarker] (); - MinAngularCoord = new su2double*[nMarker] (); - MinRelAngularCoord = new su2double*[nMarker] (); + nSpanWiseSections = new unsigned short[2](); + SpanWiseValue = new su2double*[2](); + + nSpanSectionsByMarker = new unsigned short[nMarker](); + nVertexSpan = new long*[nMarker](); + nTotVertexSpan = new unsigned long*[nMarker](); + turbovertex = new CTurboVertex***[nMarker](); + AverageTurboNormal = new su2double**[nMarker](); + AverageNormal = new su2double**[nMarker](); + AverageGridVel = new su2double**[nMarker](); + AverageTangGridVel = new su2double*[nMarker](); + SpanArea = new su2double*[nMarker](); + TurboRadius = new su2double*[nMarker](); + MaxAngularCoord = new su2double*[nMarker](); + MinAngularCoord = new su2double*[nMarker](); + MinRelAngularCoord = new su2double*[nMarker](); /*--- Initialize pointers for turbomachinery performance computation ---*/ - nTurboPerf = config->GetnMarker_TurboPerformance(); - TangGridVelIn = new su2double*[nTurboPerf] (); - SpanAreaIn = new su2double*[nTurboPerf] (); - TurboRadiusIn = new su2double*[nTurboPerf] (); - TangGridVelOut = new su2double*[nTurboPerf] (); - SpanAreaOut = new su2double*[nTurboPerf] (); - TurboRadiusOut = new su2double*[nTurboPerf] (); - + nTurboPerf = config->GetnMarker_TurboPerformance(); + TangGridVelIn = new su2double*[nTurboPerf](); + SpanAreaIn = new su2double*[nTurboPerf](); + TurboRadiusIn = new su2double*[nTurboPerf](); + TangGridVelOut = new su2double*[nTurboPerf](); + SpanAreaOut = new su2double*[nTurboPerf](); + TurboRadiusOut = new su2double*[nTurboPerf](); } -void CPhysicalGeometry::InitiateCommsAll(void *bufSend, - const int *nElemSend, - SU2_MPI::Request *sendReq, - void *bufRecv, - const int *nElemRecv, - SU2_MPI::Request *recvReq, - unsigned short countPerElem, +void CPhysicalGeometry::InitiateCommsAll(void* bufSend, const int* nElemSend, SU2_MPI::Request* sendReq, void* bufRecv, + const int* nElemRecv, SU2_MPI::Request* recvReq, unsigned short countPerElem, unsigned short commType) { - /*--- Local variables ---*/ int iMessage, iProc, offset, nElem, count, source, dest, tag; @@ -2886,64 +2706,56 @@ void CPhysicalGeometry::InitiateCommsAll(void *bufSend, iMessage = 0; for (iProc = 0; iProc < size; iProc++) { - /*--- Post recv's only if another proc is sending us data. We do not communicate with ourselves or post recv's for zero length messages to keep overhead down. ---*/ - if ((nElemRecv[iProc+1] > nElemRecv[iProc]) && (iProc != rank)) { - + if ((nElemRecv[iProc + 1] > nElemRecv[iProc]) && (iProc != rank)) { /*--- Compute our location in the recv buffer. ---*/ - offset = countPerElem*nElemRecv[iProc]; + offset = countPerElem * nElemRecv[iProc]; /*--- Take advantage of cumulative storage format to get the number of elems that we need to recv. ---*/ - nElem = nElemRecv[iProc+1] - nElemRecv[iProc]; + nElem = nElemRecv[iProc + 1] - nElemRecv[iProc]; /*--- Total count can include multiple pieces of data per element. ---*/ - count = countPerElem*nElem; + count = countPerElem * nElem; /*--- Post non-blocking recv for this proc. ---*/ - source = iProc; tag = iProc + 1; + source = iProc; + tag = iProc + 1; switch (commType) { case COMM_TYPE_DOUBLE: - SU2_MPI::Irecv(&(static_cast(bufRecv)[offset]), - count, MPI_DOUBLE, source, tag, SU2_MPI::GetComm(), - &(recvReq[iMessage])); + SU2_MPI::Irecv(&(static_cast(bufRecv)[offset]), count, MPI_DOUBLE, source, tag, + SU2_MPI::GetComm(), &(recvReq[iMessage])); break; case COMM_TYPE_UNSIGNED_LONG: - SU2_MPI::Irecv(&(static_cast(bufRecv)[offset]), - count, MPI_UNSIGNED_LONG, source, tag, SU2_MPI::GetComm(), - &(recvReq[iMessage])); + SU2_MPI::Irecv(&(static_cast(bufRecv)[offset]), count, MPI_UNSIGNED_LONG, source, tag, + SU2_MPI::GetComm(), &(recvReq[iMessage])); break; case COMM_TYPE_LONG: - SU2_MPI::Irecv(&(static_cast(bufRecv)[offset]), - count, MPI_LONG, source, tag, SU2_MPI::GetComm(), + SU2_MPI::Irecv(&(static_cast(bufRecv)[offset]), count, MPI_LONG, source, tag, SU2_MPI::GetComm(), &(recvReq[iMessage])); break; case COMM_TYPE_UNSIGNED_SHORT: - SU2_MPI::Irecv(&(static_cast(bufRecv)[offset]), - count, MPI_UNSIGNED_SHORT, source, tag, SU2_MPI::GetComm(), - &(recvReq[iMessage])); + SU2_MPI::Irecv(&(static_cast(bufRecv)[offset]), count, MPI_UNSIGNED_SHORT, source, tag, + SU2_MPI::GetComm(), &(recvReq[iMessage])); break; case COMM_TYPE_CHAR: - SU2_MPI::Irecv(&(static_cast(bufRecv)[offset]), - count, MPI_CHAR, source, tag, SU2_MPI::GetComm(), + SU2_MPI::Irecv(&(static_cast(bufRecv)[offset]), count, MPI_CHAR, source, tag, SU2_MPI::GetComm(), &(recvReq[iMessage])); break; case COMM_TYPE_SHORT: - SU2_MPI::Irecv(&(static_cast(bufRecv)[offset]), - count, MPI_SHORT, source, tag, SU2_MPI::GetComm(), + SU2_MPI::Irecv(&(static_cast(bufRecv)[offset]), count, MPI_SHORT, source, tag, SU2_MPI::GetComm(), &(recvReq[iMessage])); break; case COMM_TYPE_INT: - SU2_MPI::Irecv(&(static_cast(bufRecv)[offset]), - count, MPI_INT, source, tag, SU2_MPI::GetComm(), + SU2_MPI::Irecv(&(static_cast(bufRecv)[offset]), count, MPI_INT, source, tag, SU2_MPI::GetComm(), &(recvReq[iMessage])); break; default: @@ -2953,7 +2765,6 @@ void CPhysicalGeometry::InitiateCommsAll(void *bufSend, /*--- Increment message counter. ---*/ iMessage++; - } } @@ -2961,64 +2772,56 @@ void CPhysicalGeometry::InitiateCommsAll(void *bufSend, iMessage = 0; for (iProc = 0; iProc < size; iProc++) { - /*--- Post sends only if we are sending another proc data. We do not communicate with ourselves or post sends for zero length messages to keep overhead down. ---*/ - if ((nElemSend[iProc+1] > nElemSend[iProc]) && (iProc != rank)) { - + if ((nElemSend[iProc + 1] > nElemSend[iProc]) && (iProc != rank)) { /*--- Compute our location in the send buffer. ---*/ - offset = countPerElem*nElemSend[iProc]; + offset = countPerElem * nElemSend[iProc]; /*--- Take advantage of cumulative storage format to get the number of elems that we need to send. ---*/ - nElem = nElemSend[iProc+1] - nElemSend[iProc]; + nElem = nElemSend[iProc + 1] - nElemSend[iProc]; /*--- Total count can include multiple pieces of data per element. ---*/ - count = countPerElem*nElem; + count = countPerElem * nElem; /*--- Post non-blocking send for this proc. ---*/ - dest = iProc; tag = rank + 1; + dest = iProc; + tag = rank + 1; switch (commType) { case COMM_TYPE_DOUBLE: - SU2_MPI::Isend(&(static_cast(bufSend)[offset]), - count, MPI_DOUBLE, dest, tag, SU2_MPI::GetComm(), + SU2_MPI::Isend(&(static_cast(bufSend)[offset]), count, MPI_DOUBLE, dest, tag, SU2_MPI::GetComm(), &(sendReq[iMessage])); break; case COMM_TYPE_UNSIGNED_LONG: - SU2_MPI::Isend(&(static_cast(bufSend)[offset]), - count, MPI_UNSIGNED_LONG, dest, tag, SU2_MPI::GetComm(), - &(sendReq[iMessage])); + SU2_MPI::Isend(&(static_cast(bufSend)[offset]), count, MPI_UNSIGNED_LONG, dest, tag, + SU2_MPI::GetComm(), &(sendReq[iMessage])); break; case COMM_TYPE_LONG: - SU2_MPI::Isend(&(static_cast(bufSend)[offset]), - count, MPI_LONG, dest, tag, SU2_MPI::GetComm(), + SU2_MPI::Isend(&(static_cast(bufSend)[offset]), count, MPI_LONG, dest, tag, SU2_MPI::GetComm(), &(sendReq[iMessage])); break; case COMM_TYPE_UNSIGNED_SHORT: - SU2_MPI::Isend(&(static_cast(bufSend)[offset]), - count, MPI_UNSIGNED_SHORT, dest, tag, SU2_MPI::GetComm(), - &(sendReq[iMessage])); + SU2_MPI::Isend(&(static_cast(bufSend)[offset]), count, MPI_UNSIGNED_SHORT, dest, tag, + SU2_MPI::GetComm(), &(sendReq[iMessage])); break; case COMM_TYPE_CHAR: - SU2_MPI::Isend(&(static_cast(bufSend)[offset]), - count, MPI_CHAR, dest, tag, SU2_MPI::GetComm(), + SU2_MPI::Isend(&(static_cast(bufSend)[offset]), count, MPI_CHAR, dest, tag, SU2_MPI::GetComm(), &(sendReq[iMessage])); break; case COMM_TYPE_SHORT: - SU2_MPI::Isend(&(static_cast(bufSend)[offset]), - count, MPI_SHORT, dest, tag, SU2_MPI::GetComm(), + SU2_MPI::Isend(&(static_cast(bufSend)[offset]), count, MPI_SHORT, dest, tag, SU2_MPI::GetComm(), &(sendReq[iMessage])); break; case COMM_TYPE_INT: - SU2_MPI::Isend(&(static_cast(bufSend)[offset]), - count, MPI_INT, dest, tag, SU2_MPI::GetComm(), + SU2_MPI::Isend(&(static_cast(bufSend)[offset]), count, MPI_INT, dest, tag, SU2_MPI::GetComm(), &(sendReq[iMessage])); break; default: @@ -3028,17 +2831,11 @@ void CPhysicalGeometry::InitiateCommsAll(void *bufSend, /*--- Increment message counter. ---*/ iMessage++; - } } - } -void CPhysicalGeometry::CompleteCommsAll(int nSends, - SU2_MPI::Request *sendReq, - int nRecvs, - SU2_MPI::Request *recvReq) { - +void CPhysicalGeometry::CompleteCommsAll(int nSends, SU2_MPI::Request* sendReq, int nRecvs, SU2_MPI::Request* recvReq) { /*--- Local variables ---*/ int ind, iSend, iRecv; @@ -3046,18 +2843,14 @@ void CPhysicalGeometry::CompleteCommsAll(int nSends, /*--- Wait for the non-blocking sends to complete. ---*/ - for (iSend = 0; iSend < nSends; iSend++) - SU2_MPI::Waitany(nSends, sendReq, &ind, &status); + for (iSend = 0; iSend < nSends; iSend++) SU2_MPI::Waitany(nSends, sendReq, &ind, &status); /*--- Wait for the non-blocking recvs to complete. ---*/ - for (iRecv = 0; iRecv < nRecvs; iRecv++) - SU2_MPI::Waitany(nRecvs, recvReq, &ind, &status); - + for (iRecv = 0; iRecv < nRecvs; iRecv++) SU2_MPI::Waitany(nRecvs, recvReq, &ind, &status); } void CPhysicalGeometry::PrepareOffsets(unsigned long val_npoint_global) { - /*--- Compute the number of points that will be on each processor. This is a linear partitioning with the addition of a simple load balancing for any remainder points. ---*/ @@ -3065,11 +2858,11 @@ void CPhysicalGeometry::PrepareOffsets(unsigned long val_npoint_global) { if (beg_node == nullptr) beg_node = new unsigned long[size]; if (end_node == nullptr) end_node = new unsigned long[size]; - if (nPointLinear == nullptr) nPointLinear = new unsigned long[size]; - if (nPointCumulative == nullptr) nPointCumulative = new unsigned long[size+1]; + if (nPointLinear == nullptr) nPointLinear = new unsigned long[size]; + if (nPointCumulative == nullptr) nPointCumulative = new unsigned long[size + 1]; - unsigned long quotient = val_npoint_global/size; - int remainder = int(val_npoint_global%size); + unsigned long quotient = val_npoint_global / size; + int remainder = int(val_npoint_global % size); for (int ii = 0; ii < size; ii++) { nPointLinear[ii] = quotient + int(ii < remainder); } @@ -3082,63 +2875,54 @@ void CPhysicalGeometry::PrepareOffsets(unsigned long val_npoint_global) { end_node[0] = beg_node[0] + nPointLinear[0]; nPointCumulative[0] = 0; for (int iProc = 1; iProc < size; iProc++) { - beg_node[iProc] = end_node[iProc-1]; + beg_node[iProc] = end_node[iProc - 1]; end_node[iProc] = beg_node[iProc] + nPointLinear[iProc]; - nPointCumulative[iProc] = nPointCumulative[iProc-1] + nPointLinear[iProc-1]; + nPointCumulative[iProc] = nPointCumulative[iProc - 1] + nPointLinear[iProc - 1]; } nPointCumulative[size] = val_npoint_global; - } unsigned long CPhysicalGeometry::GetLinearPartition(unsigned long val_global_index) { - unsigned long iProcessor = 0; /*--- Initial guess ---*/ - iProcessor = val_global_index/nPointLinear[0]; + iProcessor = val_global_index / nPointLinear[0]; /*--- Guard against going over size. ---*/ - if (iProcessor >= (unsigned long)size) - iProcessor = (unsigned long)size-1; + if (iProcessor >= (unsigned long)size) iProcessor = (unsigned long)size - 1; /*--- Move up or down until we find the processor. ---*/ if (val_global_index >= nPointCumulative[iProcessor]) - while(val_global_index >= nPointCumulative[iProcessor+1]) - iProcessor++; + while (val_global_index >= nPointCumulative[iProcessor + 1]) iProcessor++; else - while(val_global_index < nPointCumulative[iProcessor]) - iProcessor--; + while (val_global_index < nPointCumulative[iProcessor]) iProcessor--; return iProcessor; - } -void CPhysicalGeometry::SortAdjacency(const CConfig *config) { - +void CPhysicalGeometry::SortAdjacency(const CConfig* config) { #ifdef HAVE_MPI #ifdef HAVE_PARMETIS - if ((rank == MASTER_NODE) && (size > SINGLE_NODE)) - cout << "Executing the partitioning functions." << endl; + if ((rank == MASTER_NODE) && (size > SINGLE_NODE)) cout << "Executing the partitioning functions." << endl; /*--- Post process the adjacency information in order to get it into the CSR format before sending the data to ParMETIS. We need to remove repeats and adjust the size of the array for each local node. ---*/ - if ((rank == MASTER_NODE) && (size > SINGLE_NODE)) - cout << "Building the graph adjacency structure." << endl; + if ((rank == MASTER_NODE) && (size > SINGLE_NODE)) cout << "Building the graph adjacency structure." << endl; /*--- Create a partitioner object so we can transform the global index values stored in the elements to a local index. ---*/ - CLinearPartitioner pointPartitioner(Global_nPointDomain,0); + CLinearPartitioner pointPartitioner(Global_nPointDomain, 0); /*--- We can already create the array that indexes the adjacency. ---*/ - xadj.resize(pointPartitioner.GetSizeOnRank(rank)+1); + xadj.resize(pointPartitioner.GetSizeOnRank(rank) + 1); xadj[0] = 0; /*--- Here, we transfer the adjacency information from a multi-dim vector @@ -3172,7 +2956,7 @@ void CPhysicalGeometry::SortAdjacency(const CConfig *config) { for (auto jPoint : neighbors) adjacency.push_back(jPoint); /*--- Increment the starting index for the next point (CSR). ---*/ - xadj[iPoint+1] = xadj[iPoint] + neighbors.size(); + xadj[iPoint + 1] = xadj[iPoint] + neighbors.size(); ++iPoint; } @@ -3182,28 +2966,29 @@ void CPhysicalGeometry::SortAdjacency(const CConfig *config) { #endif #endif - } -void CPhysicalGeometry::SetSendReceive(const CConfig *config) { - +void CPhysicalGeometry::SetSendReceive(const CConfig* config) { unsigned short Counter_Send, Counter_Receive, iMarkerSend, iMarkerReceive; unsigned long iVertex, LocalNode; unsigned short nMarker_Max = config->GetnMarker_Max(); - unsigned long iPoint, jPoint, iElem, nDomain, iDomain, jDomain; - unsigned long *nVertexDomain = new unsigned long[nMarker_Max]; + unsigned long iPoint, jPoint, iElem, nDomain, iDomain, jDomain; + unsigned long* nVertexDomain = new unsigned long[nMarker_Max]; unsigned short iNode, jNode; vector::iterator it; - vector > SendTransfLocal; /*!< \brief Vector to store the type of transformation for this send point. */ - vector > ReceivedTransfLocal; /*!< \brief Vector to store the type of transformation for this received point. */ - vector > SendDomainLocal; /*!< \brief SendDomain[from domain][to domain] and return the point index of the node that must me sended. */ - vector > ReceivedDomainLocal; /*!< \brief SendDomain[from domain][to domain] and return the point index of the node that must me sended. */ + vector > + SendTransfLocal; /*!< \brief Vector to store the type of transformation for this send point. */ + vector > + ReceivedTransfLocal; /*!< \brief Vector to store the type of transformation for this received point. */ + vector > SendDomainLocal; /*!< \brief SendDomain[from domain][to domain] and return the point + index of the node that must me sended. */ + vector > ReceivedDomainLocal; /*!< \brief SendDomain[from domain][to domain] and return the + point index of the node that must me sended. */ unordered_map::const_iterator MI; - if (rank == MASTER_NODE && size > SINGLE_NODE) - cout << "Establishing MPI communication patterns." << endl; + if (rank == MASTER_NODE && size > SINGLE_NODE) cout << "Establishing MPI communication patterns." << endl; nDomain = size; @@ -3218,21 +3003,18 @@ void CPhysicalGeometry::SetSendReceive(const CConfig *config) { for (iElem = 0; iElem < nElem; iElem++) { for (iNode = 0; iNode < elem[iElem]->GetnNodes(); iNode++) { - - iPoint = elem[iElem]->GetNode(iNode); + iPoint = elem[iElem]->GetNode(iNode); iDomain = nodes->GetColor(iPoint); - if (iDomain == (unsigned long) rank) { + if (iDomain == (unsigned long)rank) { for (jNode = 0; jNode < elem[iElem]->GetnNodes(); jNode++) { - - jPoint = elem[iElem]->GetNode(jNode); + jPoint = elem[iElem]->GetNode(jNode); jDomain = nodes->GetColor(jPoint); /*--- If one of the neighbors is a different color and connected by an edge, then we add them to the list. ---*/ if (iDomain != jDomain) { - /*--- We send from iDomain to jDomain the value of iPoint, we save the global value becuase we need to sort the lists. ---*/ @@ -3242,7 +3024,6 @@ void CPhysicalGeometry::SetSendReceive(const CConfig *config) { we save the global value becuase we need to sort the lists. ---*/ ReceivedDomainLocal[jDomain].push_back(Local_to_Global_Point[jPoint]); - } } } @@ -3263,7 +3044,7 @@ void CPhysicalGeometry::SetSendReceive(const CConfig *config) { for (iDomain = 0; iDomain < nDomain; iDomain++) { sort(ReceivedDomainLocal[iDomain].begin(), ReceivedDomainLocal[iDomain].end()); - it = unique( ReceivedDomainLocal[iDomain].begin(), ReceivedDomainLocal[iDomain].end()); + it = unique(ReceivedDomainLocal[iDomain].begin(), ReceivedDomainLocal[iDomain].end()); ReceivedDomainLocal[iDomain].resize(it - ReceivedDomainLocal[iDomain].begin()); } @@ -3271,13 +3052,11 @@ void CPhysicalGeometry::SetSendReceive(const CConfig *config) { number of points in the simulation ---*/ Max_GlobalPoint = 0; for (iPoint = 0; iPoint < nPoint; iPoint++) { - if (Local_to_Global_Point[iPoint] > (long)Max_GlobalPoint) - Max_GlobalPoint = Local_to_Global_Point[iPoint]; + if (Local_to_Global_Point[iPoint] > (long)Max_GlobalPoint) Max_GlobalPoint = Local_to_Global_Point[iPoint]; } /*--- Set the value of some of the points ---*/ - for (iPoint = 0; iPoint < nPoint; iPoint++) - Global_to_Local_Point[Local_to_Global_Point[iPoint]] = iPoint; + for (iPoint = 0; iPoint < nPoint; iPoint++) Global_to_Local_Point[Local_to_Global_Point[iPoint]] = iPoint; /*--- Add the new MPI send boundaries, reset the transformation, and save the local value. ---*/ @@ -3286,11 +3065,11 @@ void CPhysicalGeometry::SetSendReceive(const CConfig *config) { if (SendDomainLocal[iDomain].size() != 0) { nVertexDomain[nMarker] = SendDomainLocal[iDomain].size(); for (iVertex = 0; iVertex < nVertexDomain[nMarker]; iVertex++) { - MI = Global_to_Local_Point.find(SendDomainLocal[iDomain][iVertex]); if (MI != Global_to_Local_Point.end()) iPoint = Global_to_Local_Point[SendDomainLocal[iDomain][iVertex]]; - else iPoint = std::numeric_limits::max(); + else + iPoint = std::numeric_limits::max(); SendDomainLocal[iDomain][iVertex] = iPoint; SendTransfLocal[iDomain].push_back(0); @@ -3306,11 +3085,11 @@ void CPhysicalGeometry::SetSendReceive(const CConfig *config) { if (ReceivedDomainLocal[iDomain].size() != 0) { nVertexDomain[nMarker] = ReceivedDomainLocal[iDomain].size(); for (iVertex = 0; iVertex < nVertexDomain[nMarker]; iVertex++) { - MI = Global_to_Local_Point.find(ReceivedDomainLocal[iDomain][iVertex]); if (MI != Global_to_Local_Point.end()) iPoint = Global_to_Local_Point[ReceivedDomainLocal[iDomain][iVertex]]; - else iPoint = std::numeric_limits::max(); + else + iPoint = std::numeric_limits::max(); ReceivedDomainLocal[iDomain][iVertex] = iPoint; ReceivedTransfLocal[iDomain].push_back(0); @@ -3322,14 +3101,15 @@ void CPhysicalGeometry::SetSendReceive(const CConfig *config) { } /*--- First compute the Send/Receive boundaries ---*/ - Counter_Send = 0; Counter_Receive = 0; + Counter_Send = 0; + Counter_Receive = 0; for (iDomain = 0; iDomain < nDomain; iDomain++) if (SendDomainLocal[iDomain].size() != 0) Counter_Send++; for (iDomain = 0; iDomain < nDomain; iDomain++) if (ReceivedDomainLocal[iDomain].size() != 0) Counter_Receive++; - iMarkerSend = nMarker - Counter_Send - Counter_Receive; + iMarkerSend = nMarker - Counter_Send - Counter_Receive; iMarkerReceive = nMarker - Counter_Receive; /*--- First we do the send ---*/ @@ -3340,7 +3120,7 @@ void CPhysicalGeometry::SetSendReceive(const CConfig *config) { bound[iMarkerSend][iVertex] = new CVertexMPI(LocalNode); bound[iMarkerSend][iVertex]->SetRotation_Type(SendTransfLocal[iDomain][iVertex]); } - Marker_All_SendRecv[iMarkerSend] = iDomain+1; + Marker_All_SendRecv[iMarkerSend] = iDomain + 1; iMarkerSend++; } } @@ -3353,28 +3133,27 @@ void CPhysicalGeometry::SetSendReceive(const CConfig *config) { bound[iMarkerReceive][iVertex] = new CVertexMPI(LocalNode); bound[iMarkerReceive][iVertex]->SetRotation_Type(ReceivedTransfLocal[iDomain][iVertex]); } - Marker_All_SendRecv[iMarkerReceive] = -(iDomain+1); + Marker_All_SendRecv[iMarkerReceive] = -(iDomain + 1); iMarkerReceive++; } } /*--- Free memory ---*/ - delete [] nVertexDomain; - + delete[] nVertexDomain; } -void CPhysicalGeometry::SetBoundaries(CConfig *config) { - +void CPhysicalGeometry::SetBoundaries(CConfig* config) { unsigned long iElem_Bound, TotalElem, *nElem_Bound_Copy, iVertex_; string Grid_Marker; - unsigned short iDomain, nDomain, iMarkersDomain, iLoop, *DomainCount, nMarker_Physical, Duplicate_SendReceive, *DomainSendCount, - **DomainSendMarkers, *DomainReceiveCount, **DomainReceiveMarkers, nMarker_SendRecv, iMarker, iMarker_; + unsigned short iDomain, nDomain, iMarkersDomain, iLoop, *DomainCount, nMarker_Physical, Duplicate_SendReceive, + *DomainSendCount, **DomainSendMarkers, *DomainReceiveCount, **DomainReceiveMarkers, nMarker_SendRecv, iMarker, + iMarker_; CPrimalGrid*** bound_Copy; - short *Marker_All_SendRecv_Copy; + short* Marker_All_SendRecv_Copy; bool CheckStart; - nDomain = size+1; + nDomain = size + 1; /*--- Count the number of physical markers in the boundaries ---*/ @@ -3391,19 +3170,16 @@ void CPhysicalGeometry::SetBoundaries(CConfig *config) { Duplicate_SendReceive = 0; for (iLoop = 0; iLoop < 2; iLoop++) { + DomainCount = new unsigned short[nDomain]; - DomainCount = new unsigned short [nDomain]; - - for (iDomain = 0; iDomain < nDomain; iDomain++) - DomainCount[iDomain] = 0; + for (iDomain = 0; iDomain < nDomain; iDomain++) DomainCount[iDomain] = 0; if (iLoop == 0) { for (iDomain = 0; iDomain < nDomain; iDomain++) for (iMarker = 0; iMarker < nMarker; iMarker++) if (bound[iMarker][0]->GetVTK_Type() == VERTEX) if (Marker_All_SendRecv[iMarker] == iDomain) DomainCount[iDomain]++; - } - else { + } else { for (iDomain = 0; iDomain < nDomain; iDomain++) for (iMarker = 0; iMarker < nMarker; iMarker++) if (bound[iMarker][0]->GetVTK_Type() == VERTEX) @@ -3413,21 +3189,20 @@ void CPhysicalGeometry::SetBoundaries(CConfig *config) { for (iDomain = 0; iDomain < nDomain; iDomain++) if (DomainCount[iDomain] > 1) Duplicate_SendReceive++; - delete [] DomainCount; - + delete[] DomainCount; } - DomainSendCount = new unsigned short [nDomain]; - DomainSendMarkers = new unsigned short *[nDomain]; - DomainReceiveCount = new unsigned short [nDomain]; - DomainReceiveMarkers = new unsigned short *[nDomain]; + DomainSendCount = new unsigned short[nDomain]; + DomainSendMarkers = new unsigned short*[nDomain]; + DomainReceiveCount = new unsigned short[nDomain]; + DomainReceiveMarkers = new unsigned short*[nDomain]; for (iDomain = 0; iDomain < nDomain; iDomain++) { DomainSendCount[iDomain] = 0; - DomainSendMarkers[iDomain] = new unsigned short [nMarker]; + DomainSendMarkers[iDomain] = new unsigned short[nMarker]; DomainReceiveCount[iDomain] = 0; - DomainReceiveMarkers[iDomain] = new unsigned short [nMarker]; + DomainReceiveMarkers[iDomain] = new unsigned short[nMarker]; } for (iDomain = 0; iDomain < nDomain; iDomain++) { @@ -3450,8 +3225,8 @@ void CPhysicalGeometry::SetBoundaries(CConfig *config) { nMarker_SendRecv = nMarker - nMarker_Physical - Duplicate_SendReceive; bound_Copy = new CPrimalGrid**[nMarker_Physical + nMarker_SendRecv]; - nElem_Bound_Copy = new unsigned long [nMarker_Physical + nMarker_SendRecv]; - Marker_All_SendRecv_Copy = new short [nMarker_Physical + nMarker_SendRecv]; + nElem_Bound_Copy = new unsigned long[nMarker_Physical + nMarker_SendRecv]; + Marker_All_SendRecv_Copy = new short[nMarker_Physical + nMarker_SendRecv]; iMarker_ = nMarker_Physical; iVertex_ = 0; CheckStart = false; @@ -3460,31 +3235,27 @@ void CPhysicalGeometry::SetBoundaries(CConfig *config) { for (iMarker = 0; iMarker < nMarker; iMarker++) { if (bound[iMarker][0]->GetVTK_Type() != VERTEX) { - nElem_Bound_Copy[iMarker] = nElem_Bound[iMarker]; - bound_Copy[iMarker] = new CPrimalGrid* [nElem_Bound[iMarker]]; + bound_Copy[iMarker] = new CPrimalGrid*[nElem_Bound[iMarker]]; for (iElem_Bound = 0; iElem_Bound < nElem_Bound[iMarker]; iElem_Bound++) { if (bound[iMarker][iElem_Bound]->GetVTK_Type() == LINE) - bound_Copy[iMarker][iElem_Bound] = new CLine(bound[iMarker][iElem_Bound]->GetNode(0), - bound[iMarker][iElem_Bound]->GetNode(1)); + bound_Copy[iMarker][iElem_Bound] = + new CLine(bound[iMarker][iElem_Bound]->GetNode(0), bound[iMarker][iElem_Bound]->GetNode(1)); if (bound[iMarker][iElem_Bound]->GetVTK_Type() == TRIANGLE) - bound_Copy[iMarker][iElem_Bound] = new CTriangle(bound[iMarker][iElem_Bound]->GetNode(0), - bound[iMarker][iElem_Bound]->GetNode(1), - bound[iMarker][iElem_Bound]->GetNode(2)); + bound_Copy[iMarker][iElem_Bound] = + new CTriangle(bound[iMarker][iElem_Bound]->GetNode(0), bound[iMarker][iElem_Bound]->GetNode(1), + bound[iMarker][iElem_Bound]->GetNode(2)); if (bound[iMarker][iElem_Bound]->GetVTK_Type() == QUADRILATERAL) - bound_Copy[iMarker][iElem_Bound] = new CQuadrilateral(bound[iMarker][iElem_Bound]->GetNode(0), - bound[iMarker][iElem_Bound]->GetNode(1), - bound[iMarker][iElem_Bound]->GetNode(2), - bound[iMarker][iElem_Bound]->GetNode(3)); + bound_Copy[iMarker][iElem_Bound] = + new CQuadrilateral(bound[iMarker][iElem_Bound]->GetNode(0), bound[iMarker][iElem_Bound]->GetNode(1), + bound[iMarker][iElem_Bound]->GetNode(2), bound[iMarker][iElem_Bound]->GetNode(3)); } } } - for (iDomain = 0; iDomain < nDomain; iDomain++) { - /*--- Compute the total number of elements (adding all the boundaries with the same Send/Receive ---*/ @@ -3510,7 +3281,6 @@ void CPhysicalGeometry::SetBoundaries(CConfig *config) { bound_Copy[iMarker_][iVertex_]->SetRotation_Type(bound[iMarker][iElem_Bound]->GetRotation_Type()); iVertex_++; } - } /*--- Compute the total number of elements (adding all the @@ -3527,7 +3297,6 @@ void CPhysicalGeometry::SetBoundaries(CConfig *config) { iVertex_ = 0; nElem_Bound_Copy[iMarker_] = TotalElem; bound_Copy[iMarker_] = new CPrimalGrid*[TotalElem]; - } for (iMarkersDomain = 0; iMarkersDomain < DomainReceiveCount[iDomain]; iMarkersDomain++) { @@ -3539,29 +3308,25 @@ void CPhysicalGeometry::SetBoundaries(CConfig *config) { bound_Copy[iMarker_][iVertex_]->SetRotation_Type(bound[iMarker][iElem_Bound]->GetRotation_Type()); iVertex_++; } - } - } - delete [] DomainSendCount; - for (iDomain = 0; iDomain < nDomain; iDomain++) - delete [] DomainSendMarkers[iDomain]; + delete[] DomainSendCount; + for (iDomain = 0; iDomain < nDomain; iDomain++) delete[] DomainSendMarkers[iDomain]; delete[] DomainSendMarkers; - delete [] DomainReceiveCount; - for (iDomain = 0; iDomain < nDomain; iDomain++) - delete [] DomainReceiveMarkers[iDomain]; + delete[] DomainReceiveCount; + for (iDomain = 0; iDomain < nDomain; iDomain++) delete[] DomainReceiveMarkers[iDomain]; delete[] DomainReceiveMarkers; - /*--- Deallocate the bound variables ---*/ + /*--- Deallocate the bound variables ---*/ for (iMarker = 0; iMarker < nMarker; iMarker++) { - for (iElem_Bound = 0; iElem_Bound < nElem_Bound[iMarker]; iElem_Bound++) - if (bound[iMarker][iElem_Bound] != nullptr) delete bound[iMarker][iElem_Bound]; - if (bound[iMarker] != nullptr) delete [] bound[iMarker]; + for (iElem_Bound = 0; iElem_Bound < nElem_Bound[iMarker]; iElem_Bound++) + if (bound[iMarker][iElem_Bound] != nullptr) delete bound[iMarker][iElem_Bound]; + if (bound[iMarker] != nullptr) delete[] bound[iMarker]; } - delete [] bound; + delete[] bound; /*--- Allocate the new bound variables, and set the number of markers ---*/ @@ -3582,12 +3347,10 @@ void CPhysicalGeometry::SetBoundaries(CConfig *config) { /*--- Update config information storing the boundary information in the right place ---*/ - for (iMarker = 0 ; iMarker < nMarker; iMarker++) { - + for (iMarker = 0; iMarker < nMarker; iMarker++) { string Marker_Tag = config->GetMarker_All_TagBound(iMarker); if (Marker_Tag != "SEND_RECEIVE") { - /*--- Update config information storing the boundary information in the right place ---*/ Tag_to_Marker[config->GetMarker_CfgFile_TagBound(Marker_Tag)] = Marker_Tag; @@ -3615,7 +3378,6 @@ void CPhysicalGeometry::SetBoundaries(CConfig *config) { /*--- Send-Receive boundaries definition ---*/ else { - config->SetMarker_All_KindBC(iMarker, SEND_RECEIVE); config->SetMarker_All_Monitoring(iMarker, NO); config->SetMarker_All_GeoEval(iMarker, NO); @@ -3639,7 +3401,6 @@ void CPhysicalGeometry::SetBoundaries(CConfig *config) { if (config->GetMarker_All_SendRecv(iMarker) < 0) nodes->SetDomain(bound[iMarker][iElem_Bound]->GetNode(0), false); } - } /*--- Loop over the surface element to set the boundaries ---*/ @@ -3657,39 +3418,41 @@ void CPhysicalGeometry::SetBoundaries(CConfig *config) { config->GetMarker_All_KindBC(iMarker) != PERIODIC_BOUNDARY) nodes->SetPhysicalBoundary(Point_Surface, true); - if (config->GetSolid_Wall(iMarker)) - nodes->SetSolidBoundary(Point_Surface, true); + if (config->GetSolid_Wall(iMarker)) nodes->SetSolidBoundary(Point_Surface, true); - if (config->GetViscous_Wall(iMarker)) - nodes->SetViscousBoundary(Point_Surface, true); + if (config->GetViscous_Wall(iMarker)) nodes->SetViscousBoundary(Point_Surface, true); - if (config->GetMarker_All_KindBC(iMarker) == PERIODIC_BOUNDARY) - nodes->SetPeriodicBoundary(Point_Surface, true); + if (config->GetMarker_All_KindBC(iMarker) == PERIODIC_BOUNDARY) nodes->SetPeriodicBoundary(Point_Surface, true); } } - } - delete [] Marker_All_SendRecv_Copy; - delete [] nElem_Bound_Copy; + delete[] Marker_All_SendRecv_Copy; + delete[] nElem_Bound_Copy; } -void CPhysicalGeometry::Read_Mesh_FVM(CConfig *config, - string val_mesh_filename, - unsigned short val_iZone, +void CPhysicalGeometry::Read_Mesh_FVM(CConfig* config, string val_mesh_filename, unsigned short val_iZone, unsigned short val_nZone) { - /*--- Initialize counters for local/global points & elements ---*/ - Global_nPoint = 0; Global_nPointDomain = 0; - Global_nElem = 0; Global_nElemDomain = 0; - nelem_edge = 0; Global_nelem_edge = 0; - nelem_triangle = 0; Global_nelem_triangle = 0; - nelem_quad = 0; Global_nelem_quad = 0; - nelem_tetra = 0; Global_nelem_tetra = 0; - nelem_hexa = 0; Global_nelem_hexa = 0; - nelem_prism = 0; Global_nelem_prism = 0; - nelem_pyramid = 0; Global_nelem_pyramid = 0; + Global_nPoint = 0; + Global_nPointDomain = 0; + Global_nElem = 0; + Global_nElemDomain = 0; + nelem_edge = 0; + Global_nelem_edge = 0; + nelem_triangle = 0; + Global_nelem_triangle = 0; + nelem_quad = 0; + Global_nelem_quad = 0; + nelem_tetra = 0; + Global_nelem_tetra = 0; + nelem_hexa = 0; + Global_nelem_hexa = 0; + nelem_prism = 0; + Global_nelem_prism = 0; + nelem_pyramid = 0; + Global_nelem_pyramid = 0; /*--- Set the zone number from the input value. ---*/ @@ -3699,7 +3462,7 @@ void CPhysicalGeometry::Read_Mesh_FVM(CConfig *config, unsigned short val_format = config->GetMesh_FileFormat(); - CMeshReaderFVM *MeshFVM = nullptr; + CMeshReaderFVM* MeshFVM = nullptr; switch (val_format) { case SU2: MeshFVM = new CSU2ASCIIMeshReaderFVM(config, val_iZone, val_nZone); @@ -3728,9 +3491,9 @@ void CPhysicalGeometry::Read_Mesh_FVM(CConfig *config, /*--- Store the local and global number of nodes for this rank. ---*/ - nPoint = MeshFVM->GetNumberOfLocalPoints(); - nPointDomain = MeshFVM->GetNumberOfLocalPoints(); - Global_nPoint = MeshFVM->GetNumberOfGlobalPoints(); + nPoint = MeshFVM->GetNumberOfLocalPoints(); + nPointDomain = MeshFVM->GetNumberOfLocalPoints(); + Global_nPoint = MeshFVM->GetNumberOfGlobalPoints(); Global_nPointDomain = MeshFVM->GetNumberOfGlobalPoints(); if ((rank == MASTER_NODE) && (size > SINGLE_NODE)) { @@ -3741,8 +3504,8 @@ void CPhysicalGeometry::Read_Mesh_FVM(CConfig *config, /*--- Store the local and global number of interior elements. ---*/ - nElem = MeshFVM->GetNumberOfLocalElements(); - Global_nElem = MeshFVM->GetNumberOfGlobalElements(); + nElem = MeshFVM->GetNumberOfLocalElements(); + Global_nElem = MeshFVM->GetNumberOfGlobalElements(); Global_nElemDomain = MeshFVM->GetNumberOfGlobalElements(); if ((rank == MASTER_NODE) && (size > SINGLE_NODE)) { @@ -3754,9 +3517,9 @@ void CPhysicalGeometry::Read_Mesh_FVM(CConfig *config, /*--- Load the grid points, volume elements, and surface elements from the mesh object into the proper SU2 data structures. ---*/ - LoadLinearlyPartitionedPoints(config, MeshFVM); + LoadLinearlyPartitionedPoints(config, MeshFVM); LoadLinearlyPartitionedVolumeElements(config, MeshFVM); - LoadUnpartitionedSurfaceElements(config, MeshFVM); + LoadUnpartitionedSurfaceElements(config, MeshFVM); /*--- Prepare the nodal adjacency structures for ParMETIS. ---*/ @@ -3766,12 +3529,9 @@ void CPhysicalGeometry::Read_Mesh_FVM(CConfig *config, delete the mesh reader object. ---*/ delete MeshFVM; - } -void CPhysicalGeometry::LoadLinearlyPartitionedPoints(CConfig *config, - CMeshReaderFVM *mesh) { - +void CPhysicalGeometry::LoadLinearlyPartitionedPoints(CConfig* config, CMeshReaderFVM* mesh) { /*--- Get the linearly partitioned coordinates from the mesh object. ---*/ const auto& gridCoords = mesh->GetLocalPointCoordinates(); @@ -3785,20 +3545,16 @@ void CPhysicalGeometry::LoadLinearlyPartitionedPoints(CConfig *config, of the grid nodes, we can simply initialize the global index to the first node that lies on our rank and increment. ---*/ - CLinearPartitioner pointPartitioner(Global_nPointDomain,0); + CLinearPartitioner pointPartitioner(Global_nPointDomain, 0); unsigned long GlobalIndex = pointPartitioner.GetFirstIndexOnRank(rank); for (unsigned long iPoint = 0; iPoint < nPoint; iPoint++) { - for (unsigned short iDim = 0; iDim < nDim; ++iDim) - nodes->SetCoord(iPoint, iDim, gridCoords[iDim][iPoint]); + for (unsigned short iDim = 0; iDim < nDim; ++iDim) nodes->SetCoord(iPoint, iDim, gridCoords[iDim][iPoint]); nodes->SetGlobalIndex(iPoint, GlobalIndex); ++GlobalIndex; } - } -void CPhysicalGeometry::LoadLinearlyPartitionedVolumeElements(CConfig *config, - CMeshReaderFVM *mesh) { - +void CPhysicalGeometry::LoadLinearlyPartitionedVolumeElements(CConfig* config, CMeshReaderFVM* mesh) { /*--- Reset the global to local element mapping. ---*/ Global_to_Local_Elem.clear(); @@ -3810,82 +3566,58 @@ void CPhysicalGeometry::LoadLinearlyPartitionedVolumeElements(CConfig *co /*--- Allocate space for the CGNS interior elements in our SU2 data structure. Note that we only instantiate our rank's local set. ---*/ - elem = new CPrimalGrid*[nElem] (); + elem = new CPrimalGrid*[nElem](); /*--- Loop over all of the internal, local volumetric elements. ---*/ for (unsigned long iElem = 0; iElem < nElem; iElem++) { - /*--- Get the global ID for this element. This is stored in the first entry of our connectivity stucture. ---*/ - const auto Global_Index_Elem = connElems[iElem*SU2_CONN_SIZE + 0]; + const auto Global_Index_Elem = connElems[iElem * SU2_CONN_SIZE + 0]; Global_to_Local_Elem[Global_Index_Elem] = iElem; /*--- Get the VTK type for this element. This is stored in the second entry of the connectivity structure. ---*/ - const auto vtk_type = static_cast(connElems[iElem*SU2_CONN_SIZE + 1]); + const auto vtk_type = static_cast(connElems[iElem * SU2_CONN_SIZE + 1]); /*--- Instantiate this element in the proper SU2 data structure. During this loop, we also set the global to local element map for later use and increment the element counts for all types. ---*/ - auto connectivity = &connElems[iElem*SU2_CONN_SIZE + SU2_CONN_SKIP]; - - switch(vtk_type) { + auto connectivity = &connElems[iElem * SU2_CONN_SIZE + SU2_CONN_SKIP]; + switch (vtk_type) { case TRIANGLE: - elem[iElem] = new CTriangle(connectivity[0], - connectivity[1], - connectivity[2]); + elem[iElem] = new CTriangle(connectivity[0], connectivity[1], connectivity[2]); nelem_triangle++; break; case QUADRILATERAL: - elem[iElem] = new CQuadrilateral(connectivity[0], - connectivity[1], - connectivity[2], - connectivity[3]); + elem[iElem] = new CQuadrilateral(connectivity[0], connectivity[1], connectivity[2], connectivity[3]); nelem_quad++; break; case TETRAHEDRON: - elem[iElem] = new CTetrahedron(connectivity[0], - connectivity[1], - connectivity[2], - connectivity[3]); + elem[iElem] = new CTetrahedron(connectivity[0], connectivity[1], connectivity[2], connectivity[3]); nelem_tetra++; break; case HEXAHEDRON: - elem[iElem] = new CHexahedron(connectivity[0], - connectivity[1], - connectivity[2], - connectivity[3], - connectivity[4], - connectivity[5], - connectivity[6], - connectivity[7]); + elem[iElem] = new CHexahedron(connectivity[0], connectivity[1], connectivity[2], connectivity[3], + connectivity[4], connectivity[5], connectivity[6], connectivity[7]); nelem_hexa++; break; case PRISM: - elem[iElem] = new CPrism(connectivity[0], - connectivity[1], - connectivity[2], - connectivity[3], - connectivity[4], + elem[iElem] = new CPrism(connectivity[0], connectivity[1], connectivity[2], connectivity[3], connectivity[4], connectivity[5]); nelem_prism++; break; case PYRAMID: - elem[iElem] = new CPyramid(connectivity[0], - connectivity[1], - connectivity[2], - connectivity[3], - connectivity[4]); + elem[iElem] = new CPyramid(connectivity[0], connectivity[1], connectivity[2], connectivity[3], connectivity[4]); nelem_pyramid++; break; @@ -3907,20 +3639,16 @@ void CPhysicalGeometry::LoadLinearlyPartitionedVolumeElements(CConfig *co reduce(nelem_tetra, Global_nelem_tetra); reduce(nelem_prism, Global_nelem_prism); reduce(nelem_pyramid, Global_nelem_pyramid); - } -void CPhysicalGeometry::LoadUnpartitionedSurfaceElements(CConfig *config, - CMeshReaderFVM *mesh) { - +void CPhysicalGeometry::LoadUnpartitionedSurfaceElements(CConfig* config, CMeshReaderFVM* mesh) { /*--- The master node takes care of loading all markers and surface elements from the file. This information is later put into linear partitions to make its redistribution easier after we call ParMETIS. ---*/ if (rank == MASTER_NODE) { - - const vector §ionNames = mesh->GetMarkerNames(); + const vector& sectionNames = mesh->GetMarkerNames(); /*--- Store the number of markers and print to the screen. ---*/ @@ -3930,9 +3658,9 @@ void CPhysicalGeometry::LoadUnpartitionedSurfaceElements(CConfig *config, /*--- Create the data structure for boundary elements. ---*/ - bound = new CPrimalGrid**[nMarker]; - nElem_Bound = new unsigned long [nMarker]; - Tag_to_Marker = new string [config->GetnMarker_Max()]; + bound = new CPrimalGrid**[nMarker]; + nElem_Bound = new unsigned long[nMarker]; + Tag_to_Marker = new string[config->GetnMarker_Max()]; /*--- Set some temporaries for the loop below. ---*/ @@ -3945,11 +3673,12 @@ void CPhysicalGeometry::LoadUnpartitionedSurfaceElements(CConfig *config, store those elements into our SU2 data structures. ---*/ for (int iMarker = 0; iMarker < nMarker; iMarker++) { - /*--- Initialize some counter variables ---*/ - nelem_edge_bound = 0; nelem_triangle_bound = 0; - nelem_quad_bound = 0; iElem = 0; + nelem_edge_bound = 0; + nelem_triangle_bound = 0; + nelem_quad_bound = 0; + iElem = 0; /*--- Get the string name for this marker. ---*/ @@ -3957,11 +3686,9 @@ void CPhysicalGeometry::LoadUnpartitionedSurfaceElements(CConfig *config, /* Get the marker info and surface connectivity from the mesh object. */ - const unsigned long surfElems = - mesh->GetNumberOfSurfaceElementsForMarker(iMarker); + const unsigned long surfElems = mesh->GetNumberOfSurfaceElementsForMarker(iMarker); - const vector &connElems = - mesh->GetSurfaceElementConnectivityForMarker(iMarker); + const vector& connElems = mesh->GetSurfaceElementConnectivityForMarker(iMarker); /*--- Set the number of boundary elements in this marker. ---*/ @@ -3969,51 +3696,50 @@ void CPhysicalGeometry::LoadUnpartitionedSurfaceElements(CConfig *config, /*--- Report the number and name of the marker to the console. ---*/ - cout << nElem_Bound[iMarker] << " boundary elements in index "; - cout << iMarker <<" (Marker = " <SetMarker_All_TurbomachineryFlag(iMarker, config->GetMarker_CfgFile_TurbomachineryFlag(Marker_Tag)); config->SetMarker_All_MixingPlaneInterface(iMarker, config->GetMarker_CfgFile_MixingPlaneInterface(Marker_Tag)); config->SetMarker_All_SobolevBC(iMarker, config->GetMarker_CfgFile_SobolevBC(Marker_Tag)); - } } - } -void CPhysicalGeometry::PrepareAdjacency(const CConfig *config) { - +void CPhysicalGeometry::PrepareAdjacency(const CConfig* config) { #ifdef HAVE_MPI #ifdef HAVE_PARMETIS @@ -4059,13 +3782,12 @@ void CPhysicalGeometry::PrepareAdjacency(const CConfig *config) { /*--- Create a partitioner object so we can transform the global index values stored in the elements to a local index. ---*/ - CLinearPartitioner pointPartitioner(Global_nPointDomain,0); + CLinearPartitioner pointPartitioner(Global_nPointDomain, 0); const unsigned long firstIndex = pointPartitioner.GetFirstIndexOnRank(rank); /*--- Loop over all elements that are now loaded and store adjacency. ---*/ for (unsigned long iElem = 0; iElem < nElem; iElem++) { - /*--- Store the connectivity for this element more easily. ---*/ unsigned long connectivity[8] = {0}; for (unsigned long iNode = 0; iNode < elem[iElem]->GetnNodes(); iNode++) { @@ -4074,8 +3796,7 @@ void CPhysicalGeometry::PrepareAdjacency(const CConfig *config) { /*--- Instantiate this element and build adjacency structure. ---*/ - switch(elem[iElem]->GetVTK_Type()) { - + switch (elem[iElem]->GetVTK_Type()) { case TRIANGLE: /*--- Decide whether we need to store the adjacency for any nodes @@ -4083,20 +3804,16 @@ void CPhysicalGeometry::PrepareAdjacency(const CConfig *config) { global index value within the range of our linear partitioning. ---*/ for (unsigned long iNode = 0; iNode < N_POINTS_TRIANGLE; iNode++) { - - const long local_index = connectivity[iNode]-firstIndex; + const long local_index = connectivity[iNode] - firstIndex; if ((local_index >= 0) && (local_index < (long)nPoint)) { - /*--- This node is within our linear partition. Add the neighboring nodes to this nodes' adjacency list. ---*/ for (unsigned long jNode = 0; jNode < N_POINTS_TRIANGLE; jNode++) { - /*--- Build adjacency assuming the VTK connectivity ---*/ - if (iNode != jNode) - adj_nodes[local_index].push_back(connectivity[jNode]); + if (iNode != jNode) adj_nodes[local_index].push_back(connectivity[jNode]); } } } @@ -4110,18 +3827,16 @@ void CPhysicalGeometry::PrepareAdjacency(const CConfig *config) { global index value within the range of our linear partitioning. ---*/ for (unsigned long iNode = 0; iNode < N_POINTS_QUADRILATERAL; iNode++) { - - const long local_index = connectivity[iNode]-firstIndex; + const long local_index = connectivity[iNode] - firstIndex; if ((local_index >= 0) && (local_index < (long)nPoint)) { - /*--- This node is within our linear partition. Add the neighboring nodes to this nodes' adjacency list. ---*/ /*--- Build adjacency assuming the VTK connectivity ---*/ - adj_nodes[local_index].push_back(connectivity[(iNode+1)%4]); - adj_nodes[local_index].push_back(connectivity[(iNode+3)%4]); + adj_nodes[local_index].push_back(connectivity[(iNode + 1) % 4]); + adj_nodes[local_index].push_back(connectivity[(iNode + 3) % 4]); } } @@ -4134,20 +3849,16 @@ void CPhysicalGeometry::PrepareAdjacency(const CConfig *config) { global index value within the range of our linear partitioning. ---*/ for (unsigned long iNode = 0; iNode < N_POINTS_TETRAHEDRON; iNode++) { - - const long local_index = connectivity[iNode]-firstIndex; + const long local_index = connectivity[iNode] - firstIndex; if ((local_index >= 0) && (local_index < (long)nPoint)) { - /*--- This node is within our linear partition. Add the neighboring nodes to this nodes' adjacency list. ---*/ for (unsigned long jNode = 0; jNode < N_POINTS_TETRAHEDRON; jNode++) { - /*--- Build adjacency assuming the VTK connectivity ---*/ - if (iNode != jNode) - adj_nodes[local_index].push_back(connectivity[jNode]); + if (iNode != jNode) adj_nodes[local_index].push_back(connectivity[jNode]); } } } @@ -4161,24 +3872,22 @@ void CPhysicalGeometry::PrepareAdjacency(const CConfig *config) { global index value within the range of our linear partitioning. ---*/ for (unsigned long iNode = 0; iNode < N_POINTS_HEXAHEDRON; iNode++) { - - const long local_index = connectivity[iNode]-firstIndex; + const long local_index = connectivity[iNode] - firstIndex; if ((local_index >= 0) && (local_index < (long)nPoint)) { - /*--- This node is within our linear partition. Add the neighboring nodes to this nodes' adjacency list. ---*/ /*--- Build adjacency assuming the VTK connectivity ---*/ if (iNode < 4) { - adj_nodes[local_index].push_back(connectivity[(iNode+1)%4]); - adj_nodes[local_index].push_back(connectivity[(iNode+3)%4]); + adj_nodes[local_index].push_back(connectivity[(iNode + 1) % 4]); + adj_nodes[local_index].push_back(connectivity[(iNode + 3) % 4]); } else { - adj_nodes[local_index].push_back(connectivity[(iNode-3)%4+4]); - adj_nodes[local_index].push_back(connectivity[(iNode-1)%4+4]); + adj_nodes[local_index].push_back(connectivity[(iNode - 3) % 4 + 4]); + adj_nodes[local_index].push_back(connectivity[(iNode - 1) % 4 + 4]); } - adj_nodes[local_index].push_back(connectivity[(iNode+4)%8]); + adj_nodes[local_index].push_back(connectivity[(iNode + 4) % 8]); } } @@ -4191,24 +3900,22 @@ void CPhysicalGeometry::PrepareAdjacency(const CConfig *config) { global index value within the range of our linear partitioning. ---*/ for (unsigned long iNode = 0; iNode < N_POINTS_PRISM; iNode++) { - - const long local_index = connectivity[iNode]-firstIndex; + const long local_index = connectivity[iNode] - firstIndex; if ((local_index >= 0) && (local_index < (long)nPoint)) { - /*--- This node is within our linear partition. Add the neighboring nodes to this nodes' adjacency list. ---*/ /*--- Build adjacency assuming the VTK connectivity ---*/ if (iNode < 3) { - adj_nodes[local_index].push_back(connectivity[(iNode+1)%3]); - adj_nodes[local_index].push_back(connectivity[(iNode+2)%3]); + adj_nodes[local_index].push_back(connectivity[(iNode + 1) % 3]); + adj_nodes[local_index].push_back(connectivity[(iNode + 2) % 3]); } else { - adj_nodes[local_index].push_back(connectivity[(iNode-2)%3+3]); - adj_nodes[local_index].push_back(connectivity[(iNode-1)%3+3]); + adj_nodes[local_index].push_back(connectivity[(iNode - 2) % 3 + 3]); + adj_nodes[local_index].push_back(connectivity[(iNode - 1) % 3 + 3]); } - adj_nodes[local_index].push_back(connectivity[(iNode+3)%6]); + adj_nodes[local_index].push_back(connectivity[(iNode + 3) % 6]); } } @@ -4221,19 +3928,17 @@ void CPhysicalGeometry::PrepareAdjacency(const CConfig *config) { global index value within the range of our linear partitioning. ---*/ for (unsigned long iNode = 0; iNode < N_POINTS_PYRAMID; iNode++) { - - const long local_index = connectivity[iNode]-firstIndex; + const long local_index = connectivity[iNode] - firstIndex; if ((local_index >= 0) && (local_index < (long)nPoint)) { - /*--- This node is within our linear partition. Add the neighboring nodes to this nodes' adjacency list. ---*/ /*--- Build adjacency assuming the VTK connectivity ---*/ if (iNode < 4) { - adj_nodes[local_index].push_back(connectivity[(iNode+1)%4]); - adj_nodes[local_index].push_back(connectivity[(iNode+3)%4]); + adj_nodes[local_index].push_back(connectivity[(iNode + 1) % 4]); + adj_nodes[local_index].push_back(connectivity[(iNode + 3) % 4]); adj_nodes[local_index].push_back(connectivity[4]); } else { adj_nodes[local_index].push_back(connectivity[0]); @@ -4259,140 +3964,125 @@ void CPhysicalGeometry::PrepareAdjacency(const CConfig *config) { #endif #endif - } -void CPhysicalGeometry::Check_IntElem_Orientation(const CConfig *config) { - - unsigned long tria_flip=0, quad_flip=0, tet_flip=0, prism_flip=0, hexa_flip=0, pyram_flip=0; - unsigned long quad_error=0, prism_error=0, hexa_error=0, pyram_error=0; - - SU2_OMP_PARALLEL_(reduction(+:tria_flip,quad_flip,tet_flip,prism_flip,hexa_flip,pyram_flip)) { - - /*--- Lambda to test triangles. Normal should be positive in the z direction (right hand rule). ---*/ - auto checkTria = [this](unsigned long iElem, int Node_1, int Node_2, int Node_3) { - const auto Coord_1 = nodes->GetCoord(elem[iElem]->GetNode(Node_1)); - const auto Coord_2 = nodes->GetCoord(elem[iElem]->GetNode(Node_2)); - const auto Coord_3 = nodes->GetCoord(elem[iElem]->GetNode(Node_3)); - constexpr int nDim = 2; - su2double a[nDim]={0.0}, b[nDim]={0.0}; - GeometryToolbox::Distance(nDim, Coord_2, Coord_1, a); - GeometryToolbox::Distance(nDim, Coord_3, Coord_1, b); - return a[0]*b[1]-a[1]*b[0] < 0.0; - }; - - /*--- Lambda to test tetrahedrons, volume must be positive, - * the normal of any face must point towards the other point. ---*/ - auto checkTetra = [this](unsigned long iElem, int Node_1, int Node_2, int Node_3, int Node_4) { - const auto Coord_1 = nodes->GetCoord(elem[iElem]->GetNode(Node_1)); - const auto Coord_2 = nodes->GetCoord(elem[iElem]->GetNode(Node_2)); - const auto Coord_3 = nodes->GetCoord(elem[iElem]->GetNode(Node_3)); - const auto Coord_4 = nodes->GetCoord(elem[iElem]->GetNode(Node_4)); - constexpr int nDim = 3; - su2double a[nDim]={0.0}, b[nDim]={0.0}, c[nDim]={0.0}, n[nDim]={0.0}; - GeometryToolbox::Distance(nDim, Coord_2, Coord_1, a); - GeometryToolbox::Distance(nDim, Coord_3, Coord_1, b); - GeometryToolbox::Distance(nDim, Coord_4, Coord_1, c); - GeometryToolbox::CrossProduct(a,b,n); - return GeometryToolbox::DotProduct(nDim,n,c) < 0.0; - }; - - /*--- Loop over all the elements. ---*/ - - SU2_OMP_FOR_DYN(roundUpDiv(nElem, 2*omp_get_max_threads())) - for (auto iElem = 0ul; iElem < nElem; iElem++) { +void CPhysicalGeometry::Check_IntElem_Orientation(const CConfig* config) { + unsigned long tria_flip = 0, quad_flip = 0, tet_flip = 0, prism_flip = 0, hexa_flip = 0, pyram_flip = 0; + unsigned long quad_error = 0, prism_error = 0, hexa_error = 0, pyram_error = 0; + + SU2_OMP_PARALLEL_(reduction(+ : tria_flip, quad_flip, tet_flip, prism_flip, hexa_flip, pyram_flip)) { + /*--- Lambda to test triangles. Normal should be positive in the z direction (right hand rule). ---*/ + auto checkTria = [this](unsigned long iElem, int Node_1, int Node_2, int Node_3) { + const auto Coord_1 = nodes->GetCoord(elem[iElem]->GetNode(Node_1)); + const auto Coord_2 = nodes->GetCoord(elem[iElem]->GetNode(Node_2)); + const auto Coord_3 = nodes->GetCoord(elem[iElem]->GetNode(Node_3)); + constexpr int nDim = 2; + su2double a[nDim] = {0.0}, b[nDim] = {0.0}; + GeometryToolbox::Distance(nDim, Coord_2, Coord_1, a); + GeometryToolbox::Distance(nDim, Coord_3, Coord_1, b); + return a[0] * b[1] - a[1] * b[0] < 0.0; + }; + + /*--- Lambda to test tetrahedrons, volume must be positive, + * the normal of any face must point towards the other point. ---*/ + auto checkTetra = [this](unsigned long iElem, int Node_1, int Node_2, int Node_3, int Node_4) { + const auto Coord_1 = nodes->GetCoord(elem[iElem]->GetNode(Node_1)); + const auto Coord_2 = nodes->GetCoord(elem[iElem]->GetNode(Node_2)); + const auto Coord_3 = nodes->GetCoord(elem[iElem]->GetNode(Node_3)); + const auto Coord_4 = nodes->GetCoord(elem[iElem]->GetNode(Node_4)); + constexpr int nDim = 3; + su2double a[nDim] = {0.0}, b[nDim] = {0.0}, c[nDim] = {0.0}, n[nDim] = {0.0}; + GeometryToolbox::Distance(nDim, Coord_2, Coord_1, a); + GeometryToolbox::Distance(nDim, Coord_3, Coord_1, b); + GeometryToolbox::Distance(nDim, Coord_4, Coord_1, c); + GeometryToolbox::CrossProduct(a, b, n); + return GeometryToolbox::DotProduct(nDim, n, c) < 0.0; + }; + + /*--- Loop over all the elements. ---*/ + + SU2_OMP_FOR_DYN(roundUpDiv(nElem, 2 * omp_get_max_threads())) + for (auto iElem = 0ul; iElem < nElem; iElem++) { + /*--- 2D grid. ---*/ - /*--- 2D grid. ---*/ + if (elem[iElem]->GetVTK_Type() == TRIANGLE) { + if (checkTria(iElem, 0, 1, 2)) { + elem[iElem]->Change_Orientation(); + tria_flip++; + } + } - if (elem[iElem]->GetVTK_Type() == TRIANGLE) { + if (elem[iElem]->GetVTK_Type() == QUADRILATERAL) { + /*--- Two triangles. ---*/ + bool test_1 = checkTria(iElem, 0, 1, 2); + bool test_2 = checkTria(iElem, 0, 2, 3); - if (checkTria(iElem,0,1,2)) { - elem[iElem]->Change_Orientation(); - tria_flip++; + if (test_1 && test_2) { + elem[iElem]->Change_Orientation(); + quad_flip++; + } else if (test_1 || test_2) { + /*--- If one test fails and the other passes the + * element probably has serious problems. ---*/ + SU2_OMP_ATOMIC + quad_error++; + } } - } - if (elem[iElem]->GetVTK_Type() == QUADRILATERAL) { - - /*--- Two triangles. ---*/ - bool test_1 = checkTria(iElem,0,1,2); - bool test_2 = checkTria(iElem,0,2,3); + /*--- 3D grid. ---*/ - if (test_1 && test_2) { - elem[iElem]->Change_Orientation(); - quad_flip++; - } - else if (test_1 || test_2) { - /*--- If one test fails and the other passes the - * element probably has serious problems. ---*/ - SU2_OMP_ATOMIC - quad_error++; + if (elem[iElem]->GetVTK_Type() == TETRAHEDRON) { + if (checkTetra(iElem, 0, 1, 2, 3)) { + elem[iElem]->Change_Orientation(); + tet_flip++; + } } - } - /*--- 3D grid. ---*/ - - if (elem[iElem]->GetVTK_Type() == TETRAHEDRON) { + if (elem[iElem]->GetVTK_Type() == PYRAMID) { + /*--- Slice across top vertex into 2 tets. ---*/ + bool test_1 = checkTetra(iElem, 0, 1, 2, 4); + bool test_2 = checkTetra(iElem, 2, 3, 0, 4); - if (checkTetra(iElem,0,1,2,3)) { - elem[iElem]->Change_Orientation(); - tet_flip++; + if (test_1 && test_2) { + elem[iElem]->Change_Orientation(); + pyram_flip++; + } else if (test_1 || test_2) { + SU2_OMP_ATOMIC + pyram_error++; + } } - } - - if (elem[iElem]->GetVTK_Type() == PYRAMID) { - /*--- Slice across top vertex into 2 tets. ---*/ - bool test_1 = checkTetra(iElem,0,1,2,4); - bool test_2 = checkTetra(iElem,2,3,0,4); + if (elem[iElem]->GetVTK_Type() == PRISM) { + /*--- The triangular faces should point at each other. ---*/ + bool test_1 = checkTetra(iElem, 0, 2, 1, 3); + bool test_2 = checkTetra(iElem, 3, 4, 5, 2); - if (test_1 && test_2) { - elem[iElem]->Change_Orientation(); - pyram_flip++; + if (test_1 && test_2) { + elem[iElem]->Change_Orientation(); + prism_flip++; + } else if (test_1 || test_2) { + SU2_OMP_ATOMIC + prism_error++; + } } - else if (test_1 || test_2) { - SU2_OMP_ATOMIC - pyram_error++; + + if (elem[iElem]->GetVTK_Type() == HEXAHEDRON) { + /*--- The base points at the top. ---*/ + bool test_1 = checkTetra(iElem, 0, 1, 2, 5); + bool test_2 = checkTetra(iElem, 0, 2, 3, 7); + /*--- The top points at the base. ---*/ + bool test_3 = checkTetra(iElem, 4, 6, 5, 1); + bool test_4 = checkTetra(iElem, 4, 7, 6, 3); + + if (test_1 && test_2 && test_3 && test_4) { + elem[iElem]->Change_Orientation(); + hexa_flip++; + } else if (test_1 || test_2 || test_3 || test_4) { + SU2_OMP_ATOMIC + hexa_error++; + } } } - - if (elem[iElem]->GetVTK_Type() == PRISM) { - - /*--- The triangular faces should point at each other. ---*/ - bool test_1 = checkTetra(iElem,0,2,1,3); - bool test_2 = checkTetra(iElem,3,4,5,2); - - if (test_1 && test_2) { - elem[iElem]->Change_Orientation(); - prism_flip++; - } - else if (test_1 || test_2) { - SU2_OMP_ATOMIC - prism_error++; - } - } - - if (elem[iElem]->GetVTK_Type() == HEXAHEDRON) { - - /*--- The base points at the top. ---*/ - bool test_1 = checkTetra(iElem,0,1,2,5); - bool test_2 = checkTetra(iElem,0,2,3,7); - /*--- The top points at the base. ---*/ - bool test_3 = checkTetra(iElem,4,6,5,1); - bool test_4 = checkTetra(iElem,4,7,6,3); - - if (test_1 && test_2 && test_3 && test_4) { - elem[iElem]->Change_Orientation(); - hexa_flip++; - } - else if (test_1 || test_2 || test_3 || test_4) { - SU2_OMP_ATOMIC - hexa_error++; - } - } - - } - END_SU2_OMP_FOR + END_SU2_OMP_FOR } END_SU2_OMP_PARALLEL @@ -4400,11 +4090,16 @@ void CPhysicalGeometry::Check_IntElem_Orientation(const CConfig *config) { unsigned long tmp = val; SU2_MPI::Allreduce(&tmp, &val, 1, MPI_UNSIGNED_LONG, MPI_SUM, SU2_MPI::GetComm()); }; - reduce(tria_flip); reduce(quad_flip); - reduce(tet_flip); reduce(pyram_flip); - reduce(prism_flip); reduce(hexa_flip); - reduce(quad_error); reduce(pyram_error); - reduce(prism_error); reduce(hexa_error); + reduce(tria_flip); + reduce(quad_flip); + reduce(tet_flip); + reduce(pyram_flip); + reduce(prism_flip); + reduce(hexa_flip); + reduce(quad_error); + reduce(pyram_error); + reduce(prism_error); + reduce(hexa_error); if (rank == MASTER_NODE) { string start("There has been a re-orientation of "); @@ -4415,134 +4110,130 @@ void CPhysicalGeometry::Check_IntElem_Orientation(const CConfig *config) { if (pyram_flip) cout << start << pyram_flip << " PYRAMID volume elements." << endl; if (prism_flip) cout << start << prism_flip << " PRISM volume elements." << endl; - if (quad_error+pyram_error+prism_error+hexa_error) { + if (quad_error + pyram_error + prism_error + hexa_error) { cout << ">>> WARNING: "; if (quad_error) cout << quad_error << " QUADRILATERAL, "; if (pyram_error) cout << pyram_error << " PYRAMID, "; if (prism_error) cout << prism_error << " PRISM, "; if (hexa_error) cout << hexa_error << " HEXAHEDRON, "; cout << "volume elements are distorted.\n It was not possible " - "to determine if their orientation is correct." << endl; + "to determine if their orientation is correct." + << endl; } - if (tria_flip+quad_flip+tet_flip+hexa_flip+pyram_flip+prism_flip+ - quad_error+pyram_error+prism_error+hexa_error == 0) { + if (tria_flip + quad_flip + tet_flip + hexa_flip + pyram_flip + prism_flip + quad_error + pyram_error + + prism_error + hexa_error == + 0) { cout << "All volume elements are correctly orientend." << endl; } } - } -void CPhysicalGeometry::Check_BoundElem_Orientation(const CConfig *config) { - +void CPhysicalGeometry::Check_BoundElem_Orientation(const CConfig* config) { unsigned long line_flip = 0, tria_flip = 0, quad_flip = 0, quad_error = 0; - SU2_OMP_PARALLEL_(reduction(+:line_flip,tria_flip,quad_flip,quad_error)) { - - /*--- Lambda to test tetrahedrons. ---*/ - auto checkTetra = [this](unsigned long Point_1, unsigned long Point_2, - unsigned long Point_3, unsigned long Point_4) { - const auto Coord_1 = nodes->GetCoord(Point_1); - const auto Coord_2 = nodes->GetCoord(Point_2); - const auto Coord_3 = nodes->GetCoord(Point_3); - const auto Coord_4 = nodes->GetCoord(Point_4); - constexpr int nDim = 3; - su2double a[nDim]={0.0}, b[nDim]={0.0}, c[nDim]={0.0}, n[nDim]={0.0}; - GeometryToolbox::Distance(nDim, Coord_2, Coord_1, a); - GeometryToolbox::Distance(nDim, Coord_3, Coord_1, b); - GeometryToolbox::Distance(nDim, Coord_4, Coord_1, c); - GeometryToolbox::CrossProduct(a,b,n); - return GeometryToolbox::DotProduct(nDim,n,c) < 0.0; - }; - - for (auto iMarker = 0u; iMarker < nMarker; iMarker++) { - - if (config->GetMarker_All_KindBC(iMarker) == INTERNAL_BOUNDARY) continue; - - SU2_OMP_FOR_DYN(OMP_MIN_SIZE) - for (auto iElem_Surface = 0ul; iElem_Surface < nElem_Bound[iMarker]; iElem_Surface++) { - - /*--- Pick a reference point inside the domain that is not part of the surface element. ---*/ - const auto iElem_Domain = bound[iMarker][iElem_Surface]->GetDomainElement(); - unsigned long Point_Domain = 0; - - for (auto iNode_Domain = 0u; iNode_Domain < elem[iElem_Domain]->GetnNodes(); iNode_Domain++) { - Point_Domain = elem[iElem_Domain]->GetNode(iNode_Domain); - bool find = false; - for (auto iNode_Surface = 0u; iNode_Surface < bound[iMarker][iElem_Surface]->GetnNodes(); iNode_Surface++) { - auto Point_Surface = bound[iMarker][iElem_Surface]->GetNode(iNode_Surface); - if (Point_Surface == Point_Domain) {find = true; break;} + SU2_OMP_PARALLEL_(reduction(+ : line_flip, tria_flip, quad_flip, quad_error)) { + /*--- Lambda to test tetrahedrons. ---*/ + auto checkTetra = [this](unsigned long Point_1, unsigned long Point_2, unsigned long Point_3, + unsigned long Point_4) { + const auto Coord_1 = nodes->GetCoord(Point_1); + const auto Coord_2 = nodes->GetCoord(Point_2); + const auto Coord_3 = nodes->GetCoord(Point_3); + const auto Coord_4 = nodes->GetCoord(Point_4); + constexpr int nDim = 3; + su2double a[nDim] = {0.0}, b[nDim] = {0.0}, c[nDim] = {0.0}, n[nDim] = {0.0}; + GeometryToolbox::Distance(nDim, Coord_2, Coord_1, a); + GeometryToolbox::Distance(nDim, Coord_3, Coord_1, b); + GeometryToolbox::Distance(nDim, Coord_4, Coord_1, c); + GeometryToolbox::CrossProduct(a, b, n); + return GeometryToolbox::DotProduct(nDim, n, c) < 0.0; + }; + + for (auto iMarker = 0u; iMarker < nMarker; iMarker++) { + if (config->GetMarker_All_KindBC(iMarker) == INTERNAL_BOUNDARY) continue; + + SU2_OMP_FOR_DYN(OMP_MIN_SIZE) + for (auto iElem_Surface = 0ul; iElem_Surface < nElem_Bound[iMarker]; iElem_Surface++) { + /*--- Pick a reference point inside the domain that is not part of the surface element. ---*/ + const auto iElem_Domain = bound[iMarker][iElem_Surface]->GetDomainElement(); + unsigned long Point_Domain = 0; + + for (auto iNode_Domain = 0u; iNode_Domain < elem[iElem_Domain]->GetnNodes(); iNode_Domain++) { + Point_Domain = elem[iElem_Domain]->GetNode(iNode_Domain); + bool find = false; + for (auto iNode_Surface = 0u; iNode_Surface < bound[iMarker][iElem_Surface]->GetnNodes(); iNode_Surface++) { + auto Point_Surface = bound[iMarker][iElem_Surface]->GetNode(iNode_Surface); + if (Point_Surface == Point_Domain) { + find = true; + break; + } + } + if (!find) break; } - if (!find) break; - } - - /*--- 2D grid. ---*/ - if (bound[iMarker][iElem_Surface]->GetVTK_Type() == LINE) { - - auto Point_1_Surface = bound[iMarker][iElem_Surface]->GetNode(0); - auto Point_2_Surface = bound[iMarker][iElem_Surface]->GetNode(1); - const auto Coord_1 = nodes->GetCoord(Point_1_Surface); - const auto Coord_2 = nodes->GetCoord(Point_2_Surface); - const auto Coord_3 = nodes->GetCoord(Point_Domain); - - /*--- The normal of the triangle formed by the line and domain - * point should point in the positive z direction. ---*/ - constexpr int nDim = 2; - su2double a[nDim]={0.0}, b[nDim]={0.0}; - GeometryToolbox::Distance(nDim, Coord_2, Coord_1, a); - GeometryToolbox::Distance(nDim, Coord_3, Coord_1, b); - bool test = a[0]*b[1]-a[1]*b[0] < 0.0; - - if (test) { - bound[iMarker][iElem_Surface]->Change_Orientation(); - line_flip++; + /*--- 2D grid. ---*/ + + if (bound[iMarker][iElem_Surface]->GetVTK_Type() == LINE) { + auto Point_1_Surface = bound[iMarker][iElem_Surface]->GetNode(0); + auto Point_2_Surface = bound[iMarker][iElem_Surface]->GetNode(1); + const auto Coord_1 = nodes->GetCoord(Point_1_Surface); + const auto Coord_2 = nodes->GetCoord(Point_2_Surface); + const auto Coord_3 = nodes->GetCoord(Point_Domain); + + /*--- The normal of the triangle formed by the line and domain + * point should point in the positive z direction. ---*/ + constexpr int nDim = 2; + su2double a[nDim] = {0.0}, b[nDim] = {0.0}; + GeometryToolbox::Distance(nDim, Coord_2, Coord_1, a); + GeometryToolbox::Distance(nDim, Coord_3, Coord_1, b); + bool test = a[0] * b[1] - a[1] * b[0] < 0.0; + + if (test) { + bound[iMarker][iElem_Surface]->Change_Orientation(); + line_flip++; + } } - } - - /*--- 3D grid. ---*/ - if (bound[iMarker][iElem_Surface]->GetVTK_Type() == TRIANGLE) { + /*--- 3D grid. ---*/ - auto Point_1_Surface = bound[iMarker][iElem_Surface]->GetNode(0); - auto Point_2_Surface = bound[iMarker][iElem_Surface]->GetNode(1); - auto Point_3_Surface = bound[iMarker][iElem_Surface]->GetNode(2); + if (bound[iMarker][iElem_Surface]->GetVTK_Type() == TRIANGLE) { + auto Point_1_Surface = bound[iMarker][iElem_Surface]->GetNode(0); + auto Point_2_Surface = bound[iMarker][iElem_Surface]->GetNode(1); + auto Point_3_Surface = bound[iMarker][iElem_Surface]->GetNode(2); - /*--- The normal of the triangle should point into the domain, - * resulting in a tetrahedron with positive volume. ---*/ - if (checkTetra(Point_1_Surface, Point_2_Surface, Point_3_Surface, Point_Domain)) { - bound[iMarker][iElem_Surface]->Change_Orientation(); - tria_flip++; + /*--- The normal of the triangle should point into the domain, + * resulting in a tetrahedron with positive volume. ---*/ + if (checkTetra(Point_1_Surface, Point_2_Surface, Point_3_Surface, Point_Domain)) { + bound[iMarker][iElem_Surface]->Change_Orientation(); + tria_flip++; + } } - } - - if (bound[iMarker][iElem_Surface]->GetVTK_Type() == QUADRILATERAL) { - - auto Point_1_Surface = bound[iMarker][iElem_Surface]->GetNode(0); - auto Point_2_Surface = bound[iMarker][iElem_Surface]->GetNode(1); - auto Point_3_Surface = bound[iMarker][iElem_Surface]->GetNode(2); - auto Point_4_Surface = bound[iMarker][iElem_Surface]->GetNode(3); - /*--- Divide quadrilateral/pyramid into triangles/tetrahedrons. ---*/ - int test_1 = checkTetra(Point_1_Surface, Point_2_Surface, Point_3_Surface, Point_Domain); - int test_2 = checkTetra(Point_2_Surface, Point_3_Surface, Point_4_Surface, Point_Domain); - int test_3 = checkTetra(Point_3_Surface, Point_4_Surface, Point_1_Surface, Point_Domain); - int test_4 = checkTetra(Point_4_Surface, Point_1_Surface, Point_2_Surface, Point_Domain); - - if (test_1+test_2+test_3+test_4 >= 3) { - /*--- If 3 or 4 tests fail there is > 75% chance flipping is the right choice. ---*/ - bound[iMarker][iElem_Surface]->Change_Orientation(); - quad_flip++; - } - else if (test_1+test_2+test_3+test_4 == 2) { - /*--- If 50/50 we cannot be sure of what to do -> report to user. - * If only one test fails it is probably (75%) due to skewness or warping. ---*/ - quad_error++; + if (bound[iMarker][iElem_Surface]->GetVTK_Type() == QUADRILATERAL) { + auto Point_1_Surface = bound[iMarker][iElem_Surface]->GetNode(0); + auto Point_2_Surface = bound[iMarker][iElem_Surface]->GetNode(1); + auto Point_3_Surface = bound[iMarker][iElem_Surface]->GetNode(2); + auto Point_4_Surface = bound[iMarker][iElem_Surface]->GetNode(3); + + /*--- Divide quadrilateral/pyramid into triangles/tetrahedrons. ---*/ + int test_1 = checkTetra(Point_1_Surface, Point_2_Surface, Point_3_Surface, Point_Domain); + int test_2 = checkTetra(Point_2_Surface, Point_3_Surface, Point_4_Surface, Point_Domain); + int test_3 = checkTetra(Point_3_Surface, Point_4_Surface, Point_1_Surface, Point_Domain); + int test_4 = checkTetra(Point_4_Surface, Point_1_Surface, Point_2_Surface, Point_Domain); + + if (test_1 + test_2 + test_3 + test_4 >= 3) { + /*--- If 3 or 4 tests fail there is > 75% chance flipping is the right choice. ---*/ + bound[iMarker][iElem_Surface]->Change_Orientation(); + quad_flip++; + } else if (test_1 + test_2 + test_3 + test_4 == 2) { + /*--- If 50/50 we cannot be sure of what to do -> report to user. + * If only one test fails it is probably (75%) due to skewness or warping. ---*/ + quad_error++; + } } } + END_SU2_OMP_FOR } - END_SU2_OMP_FOR - } } END_SU2_OMP_PARALLEL @@ -4550,8 +4241,10 @@ void CPhysicalGeometry::Check_BoundElem_Orientation(const CConfig *config) { unsigned long tmp = val; SU2_MPI::Allreduce(&tmp, &val, 1, MPI_UNSIGNED_LONG, MPI_SUM, SU2_MPI::GetComm()); }; - reduce(line_flip); reduce(tria_flip); - reduce(quad_flip); reduce(quad_error); + reduce(line_flip); + reduce(tria_flip); + reduce(quad_flip); + reduce(quad_error); if (rank == MASTER_NODE) { string start("There has been a re-orientation of "); @@ -4560,24 +4253,27 @@ void CPhysicalGeometry::Check_BoundElem_Orientation(const CConfig *config) { if (quad_flip) cout << start << quad_flip << " QUADRILATERAL surface elements." << endl; if (quad_error) { - cout << ">>> WARNING: " << quad_error << " QUADRILATERAL surface elements are distorted.\n" - " It was not possible to determine if their orientation is correct." << endl; + cout << ">>> WARNING: " << quad_error + << " QUADRILATERAL surface elements are distorted.\n" + " It was not possible to determine if their orientation is correct." + << endl; } - if (line_flip+tria_flip+quad_flip+quad_error == 0) { + if (line_flip + tria_flip + quad_flip + quad_error == 0) { cout << "All surface elements are correctly orientend." << endl; } } - } -void CPhysicalGeometry::SetPositive_ZArea(CConfig *config) { +void CPhysicalGeometry::SetPositive_ZArea(CConfig* config) { unsigned short iMarker, Boundary, Monitoring; unsigned long iVertex, iPoint; - su2double *Normal, PositiveXArea, PositiveYArea, PositiveZArea, WettedArea, CoordX = 0.0, CoordY = 0.0, CoordZ = 0.0, MinCoordX = 1E10, MinCoordY = 1E10, - MinCoordZ = 1E10, MaxCoordX = -1E10, MaxCoordY = -1E10, MaxCoordZ = -1E10, TotalMinCoordX = 1E10, TotalMinCoordY = 1E10, - TotalMinCoordZ = 1E10, TotalMaxCoordX = -1E10, TotalMaxCoordY = -1E10, TotalMaxCoordZ = -1E10; - su2double TotalPositiveXArea = 0.0, TotalPositiveYArea = 0.0, TotalPositiveZArea = 0.0, TotalWettedArea = 0.0, AxiFactor; + su2double *Normal, PositiveXArea, PositiveYArea, PositiveZArea, WettedArea, + CoordX = 0.0, CoordY = 0.0, CoordZ = 0.0, MinCoordX = 1E10, MinCoordY = 1E10, MinCoordZ = 1E10, MaxCoordX = -1E10, + MaxCoordY = -1E10, MaxCoordZ = -1E10, TotalMinCoordX = 1E10, TotalMinCoordY = 1E10, TotalMinCoordZ = 1E10, + TotalMaxCoordX = -1E10, TotalMaxCoordY = -1E10, TotalMaxCoordZ = -1E10; + su2double TotalPositiveXArea = 0.0, TotalPositiveYArea = 0.0, TotalPositiveZArea = 0.0, TotalWettedArea = 0.0, + AxiFactor; const bool axisymmetric = config->GetAxisymmetric(); const bool fea = config->GetStructuralProblem(); @@ -4591,9 +4287,9 @@ void CPhysicalGeometry::SetPositive_ZArea(CConfig *config) { Boundary = config->GetMarker_All_KindBC(iMarker); Monitoring = config->GetMarker_All_Monitoring(iMarker); - if (((config->GetSolid_Wall(iMarker) || Boundary == LOAD_BOUNDARY || - Boundary == DISPLACEMENT_BOUNDARY) && Monitoring == YES) || fea) { - + if (((config->GetSolid_Wall(iMarker) || Boundary == LOAD_BOUNDARY || Boundary == DISPLACEMENT_BOUNDARY) && + Monitoring == YES) || + fea) { for (iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { iPoint = vertex[iMarker][iVertex]->GetNode(); @@ -4603,8 +4299,10 @@ void CPhysicalGeometry::SetPositive_ZArea(CConfig *config) { CoordY = nodes->GetCoord(iPoint, 1); if (nDim == 3) CoordZ = nodes->GetCoord(iPoint, 2); - if (axisymmetric) AxiFactor = 2.0*PI_NUMBER*nodes->GetCoord(iPoint, 1); - else AxiFactor = 1.0; + if (axisymmetric) + AxiFactor = 2.0 * PI_NUMBER * nodes->GetCoord(iPoint, 1); + else + AxiFactor = 1.0; WettedArea += AxiFactor * GeometryToolbox::Norm(nDim, Normal); @@ -4643,131 +4341,126 @@ void CPhysicalGeometry::SetPositive_ZArea(CConfig *config) { /*--- Set a reference area if no value is provided ---*/ - const string L = (config->GetSystemMeasurements() == SI)? " m" : " ft"; - const string A = (config->GetSystemMeasurements() == SI)? " m^2" : " ft^2"; + const string L = (config->GetSystemMeasurements() == SI) ? " m" : " ft"; + const string A = (config->GetSystemMeasurements() == SI) ? " m^2" : " ft^2"; const bool D3 = (nDim == 3); if (config->GetRefArea() == 0.0) { - - if (D3) config->SetRefArea(TotalPositiveZArea); - else config->SetRefArea(TotalPositiveYArea); + if (D3) + config->SetRefArea(TotalPositiveZArea); + else + config->SetRefArea(TotalPositiveYArea); if (rank == MASTER_NODE) { - if (D3) cout << "Reference area = "<< TotalPositiveZArea << A << ".\n"; - else cout << "Reference length = "<< TotalPositiveYArea << L << ".\n"; + if (D3) + cout << "Reference area = " << TotalPositiveZArea << A << ".\n"; + else + cout << "Reference length = " << TotalPositiveYArea << L << ".\n"; } } /*--- Set a semi-span value if no value is provided ---*/ if (config->GetSemiSpan() == 0.0) { - - if (D3) config->SetSemiSpan(fabs(TotalMaxCoordY)); - else config->SetSemiSpan(1.0); + if (D3) + config->SetSemiSpan(fabs(TotalMaxCoordY)); + else + config->SetSemiSpan(1.0); if (D3 && (rank == MASTER_NODE)) { - cout << "Semi-span length = "<< TotalMaxCoordY << L << ".\n"; + cout << "Semi-span length = " << TotalMaxCoordY << L << ".\n"; } } if (rank == MASTER_NODE) { + if (fea) + cout << "Surface area = " << TotalWettedArea; + else + cout << "Wetted area = " << TotalWettedArea; + if (D3 || axisymmetric) + cout << A << ".\n"; + else + cout << L << ".\n"; - if (fea) cout << "Surface area = "<< TotalWettedArea; - else cout << "Wetted area = "<< TotalWettedArea; - if (D3 || axisymmetric) cout << A << ".\n"; - else cout << L << ".\n"; - - cout << "Area projection in the x-plane = "<< TotalPositiveXArea << (D3? A : L); - cout << ", y-plane = "<< TotalPositiveYArea << (D3? A : L); - if (D3) cout << ", z-plane = "<< TotalPositiveZArea << A; + cout << "Area projection in the x-plane = " << TotalPositiveXArea << (D3 ? A : L); + cout << ", y-plane = " << TotalPositiveYArea << (D3 ? A : L); + if (D3) cout << ", z-plane = " << TotalPositiveZArea << A; cout << ".\n"; - cout << "Max. coordinate in the x-direction = "<< TotalMaxCoordX << L; - cout << ", y-direction = "<< TotalMaxCoordY << L; - if (D3) cout << ", z-direction = "<< TotalMaxCoordZ << L; + cout << "Max. coordinate in the x-direction = " << TotalMaxCoordX << L; + cout << ", y-direction = " << TotalMaxCoordY << L; + if (D3) cout << ", z-direction = " << TotalMaxCoordZ << L; cout << ".\n"; - cout << "Min. coordinate in the x-direction = "<< TotalMinCoordX << L; - cout << ", y-direction = "<< TotalMinCoordY << L; - if (D3) cout << ", z-direction = "<< TotalMinCoordZ << L; + cout << "Min. coordinate in the x-direction = " << TotalMinCoordX << L; + cout << ", y-direction = " << TotalMinCoordY << L; + if (D3) cout << ", z-direction = " << TotalMinCoordZ << L; cout << "." << endl; - } - } void CPhysicalGeometry::SetPoint_Connectivity() { - vector > points(nPoint); - SU2_OMP_PARALLEL - { - unsigned short Node_Neighbor, iNode, iNeighbor; - unsigned long jElem, Point_Neighbor, iPoint, iElem; - - /*--- Loop over all the elements ---*/ - BEGIN_SU2_OMP_SAFE_GLOBAL_ACCESS - { - vector > elems(nPoint); + SU2_OMP_PARALLEL { + unsigned short Node_Neighbor, iNode, iNeighbor; + unsigned long jElem, Point_Neighbor, iPoint, iElem; - for (iElem = 0; iElem < nElem; iElem++) { + /*--- Loop over all the elements ---*/ + BEGIN_SU2_OMP_SAFE_GLOBAL_ACCESS { + vector > elems(nPoint); - /*--- Loop over all the nodes of an element ---*/ - for (iNode = 0; iNode < elem[iElem]->GetnNodes(); iNode++) { - iPoint = elem[iElem]->GetNode(iNode); - elems[iPoint].push_back(iElem); + for (iElem = 0; iElem < nElem; iElem++) { + /*--- Loop over all the nodes of an element ---*/ + for (iNode = 0; iNode < elem[iElem]->GetnNodes(); iNode++) { + iPoint = elem[iElem]->GetNode(iNode); + elems[iPoint].push_back(iElem); + } } + nodes->SetElems(elems); } - nodes->SetElems(elems); - } - END_SU2_OMP_SAFE_GLOBAL_ACCESS - - /*--- Loop over all the points ---*/ - - SU2_OMP_FOR_DYN(roundUpDiv(nPoint,2*omp_get_max_threads())) - for (iPoint = 0; iPoint < nPoint; iPoint++) { + END_SU2_OMP_SAFE_GLOBAL_ACCESS - /*--- Loop over all elements shared by the point ---*/ + /*--- Loop over all the points ---*/ - for (iElem = 0; iElem < nodes->GetnElem(iPoint); iElem++) { - - jElem = nodes->GetElem(iPoint, iElem); + SU2_OMP_FOR_DYN(roundUpDiv(nPoint, 2 * omp_get_max_threads())) + for (iPoint = 0; iPoint < nPoint; iPoint++) { + /*--- Loop over all elements shared by the point ---*/ - /*--- If we find the point iPoint in the surrounding element ---*/ + for (iElem = 0; iElem < nodes->GetnElem(iPoint); iElem++) { + jElem = nodes->GetElem(iPoint, iElem); - for (iNode = 0; iNode < elem[jElem]->GetnNodes(); iNode++) { + /*--- If we find the point iPoint in the surrounding element ---*/ - if (elem[jElem]->GetNode(iNode) != iPoint) continue; + for (iNode = 0; iNode < elem[jElem]->GetnNodes(); iNode++) { + if (elem[jElem]->GetNode(iNode) != iPoint) continue; - /*--- Localize the local index of the neighbor of iPoint in the element ---*/ + /*--- Localize the local index of the neighbor of iPoint in the element ---*/ - for (iNeighbor = 0; iNeighbor < elem[jElem]->GetnNeighbor_Nodes(iNode); iNeighbor++) { - Node_Neighbor = elem[jElem]->GetNeighbor_Nodes(iNode, iNeighbor); - Point_Neighbor = elem[jElem]->GetNode(Node_Neighbor); + for (iNeighbor = 0; iNeighbor < elem[jElem]->GetnNeighbor_Nodes(iNode); iNeighbor++) { + Node_Neighbor = elem[jElem]->GetNeighbor_Nodes(iNode, iNeighbor); + Point_Neighbor = elem[jElem]->GetNode(Node_Neighbor); - /*--- Store the point into the point, if it is new ---*/ - auto End = points[iPoint].end(); - if (find(points[iPoint].begin(), End, Point_Neighbor) == End) - points[iPoint].push_back(Point_Neighbor); + /*--- Store the point into the point, if it is new ---*/ + auto End = points[iPoint].end(); + if (find(points[iPoint].begin(), End, Point_Neighbor) == End) points[iPoint].push_back(Point_Neighbor); + } } } - } - - /*--- Set the number of neighbors variable, this is important for JST and multigrid in parallel. ---*/ - nodes->SetnNeighbor(iPoint, points[iPoint].size()); - } - END_SU2_OMP_FOR - SU2_OMP_MASTER - nodes->SetPoints(points); - END_SU2_OMP_MASTER + /*--- Set the number of neighbors variable, this is important for JST and multigrid in parallel. ---*/ + nodes->SetnNeighbor(iPoint, points[iPoint].size()); + } + END_SU2_OMP_FOR + SU2_OMP_MASTER + nodes->SetPoints(points); + END_SU2_OMP_MASTER } END_SU2_OMP_PARALLEL } -void CPhysicalGeometry::SetRCM_Ordering(CConfig *config) { - +void CPhysicalGeometry::SetRCM_Ordering(CConfig* config) { /*--- The result is the RCM ordering, during the process it is also used as * the queue of new points considered by the algorithm. This is possible * because points move from the front of the queue to the back of the result, @@ -4785,7 +4478,6 @@ void CPhysicalGeometry::SetRCM_Ordering(CConfig *config) { /*--- Repeat as many times as necessary to handle disconnected graphs. ---*/ while (Result.size() < nPointDomain) { - /*--- Select the node with the lowest degree in the grid. ---*/ auto AddPoint = nPoint; auto MinDegree = std::numeric_limits::max(); @@ -4807,7 +4499,6 @@ void CPhysicalGeometry::SetRCM_Ordering(CConfig *config) { /*--- Loop until reorganizing all nodes connected to AddPoint. This will * also terminate early once the ordering + queue include all points. ---*/ while (QueueStart < Result.size() && Result.size() < nPointDomain) { - /*--- Move the start of the queue, equivalent to taking from the front of * the queue and inserting at the end of the result. ---*/ AddPoint = Result[QueueStart]; @@ -4826,11 +4517,9 @@ void CPhysicalGeometry::SetRCM_Ordering(CConfig *config) { if (AuxQueue.empty()) continue; /*--- Sort the auxiliar queue based on the number of neighbors (degree). ---*/ - stable_sort(AuxQueue.begin(), AuxQueue.end(), - [&](unsigned long iPoint, unsigned long jPoint) { - return nodes->GetnPoint(iPoint) < nodes->GetnPoint(jPoint); - } - ); + stable_sort(AuxQueue.begin(), AuxQueue.end(), [&](unsigned long iPoint, unsigned long jPoint) { + return nodes->GetnPoint(iPoint) < nodes->GetnPoint(jPoint); + }); Result.insert(Result.end(), AuxQueue.begin(), AuxQueue.end()); } } @@ -4868,7 +4557,7 @@ void CPhysicalGeometry::SetRCM_Ordering(CConfig *config) { for (auto iPoint = 0ul; iPoint < nPoint; iPoint++) { AuxGlobalIndex[iPoint] = nodes->GetGlobalIndex(iPoint); for (auto iDim = 0u; iDim < nDim; iDim++) { - AuxCoord(iPoint,iDim) = nodes->GetCoord(iPoint, iDim); + AuxCoord(iPoint, iDim) = nodes->GetCoord(iPoint, iDim); } } @@ -4879,7 +4568,7 @@ void CPhysicalGeometry::SetRCM_Ordering(CConfig *config) { /*--- Set the new conectivities ---*/ - auto& InvResult = AuxGlobalIndex; // alias to re-use storage + auto& InvResult = AuxGlobalIndex; // alias to re-use storage for (auto iPoint = 0ul; iPoint < nPoint; iPoint++) { InvResult[Result[iPoint]] = iPoint; } @@ -4893,9 +4582,7 @@ void CPhysicalGeometry::SetRCM_Ordering(CConfig *config) { for (auto iMarker = 0u; iMarker < nMarker; iMarker++) { for (auto iElem = 0ul; iElem < nElem_Bound[iMarker]; iElem++) { - - if (config->GetMarker_All_KindBC(iMarker) == SEND_RECEIVE && - config->GetMarker_All_SendRecv(iMarker) < 0) { + if (config->GetMarker_All_KindBC(iMarker) == SEND_RECEIVE && config->GetMarker_All_SendRecv(iMarker) < 0) { nodes->SetDomain(bound[iMarker][iElem]->GetNode(0), false); } @@ -4909,18 +4596,15 @@ void CPhysicalGeometry::SetRCM_Ordering(CConfig *config) { config->GetMarker_All_KindBC(iMarker) != PERIODIC_BOUNDARY) nodes->SetPhysicalBoundary(InvResult[iPoint], true); - if (config->GetSolid_Wall(iMarker)) - nodes->SetSolidBoundary(InvResult[iPoint], true); + if (config->GetSolid_Wall(iMarker)) nodes->SetSolidBoundary(InvResult[iPoint], true); - if (config->GetViscous_Wall(iMarker) ) - nodes->SetViscousBoundary(InvResult[iPoint], true); + if (config->GetViscous_Wall(iMarker)) nodes->SetViscousBoundary(InvResult[iPoint], true); if (config->GetMarker_All_KindBC(iMarker) == PERIODIC_BOUNDARY) nodes->SetPeriodicBoundary(InvResult[iPoint], true); } } } - } void CPhysicalGeometry::SetElement_Connectivity(void) { @@ -4943,7 +4627,6 @@ void CPhysicalGeometry::SetElement_Connectivity(void) { if ((elem[iElem]->GetNeighbor_Elements(iFace) == -1) && (iElem < Test_Elem) && FindFace(iElem, Test_Elem, first_elem_face, second_elem_face)) { - /*--- Localice which faces are sharing both elements ---*/ elem[iElem]->SetNeighbor_Elements(Test_Elem, first_elem_face); @@ -4951,7 +4634,6 @@ void CPhysicalGeometry::SetElement_Connectivity(void) { /*--- Store the element for both elements ---*/ elem[Test_Elem]->SetNeighbor_Elements(iElem, second_elem_face); - } } } @@ -4964,14 +4646,14 @@ void CPhysicalGeometry::SetBoundVolume(void) { for (iMarker = 0; iMarker < nMarker; iMarker++) for (iElem_Surface = 0; iElem_Surface < nElem_Bound[iMarker]; iElem_Surface++) { - /*--- Choose and arbitrary point from the surface --*/ Point = bound[iMarker][iElem_Surface]->GetNode(0); CheckVol = false; for (iElem = 0; iElem < nodes->GetnElem(Point); iElem++) { /*--- Look for elements surronding that point --*/ - cont = 0; iElem_Domain = nodes->GetElem(Point, iElem); + cont = 0; + iElem_Domain = nodes->GetElem(Point, iElem); for (iNode_Domain = 0; iNode_Domain < elem[iElem_Domain]->GetnNodes(); iNode_Domain++) { Point_Domain = elem[iElem_Domain]->GetNode(iNode_Domain); for (iNode_Surface = 0; iNode_Surface < bound[iMarker][iElem_Surface]->GetnNodes(); iNode_Surface++) { @@ -4990,27 +4672,25 @@ void CPhysicalGeometry::SetBoundVolume(void) { } if (!CheckVol) { char buf[100]; - SPRINTF(buf,"The surface element (%u, %lu) doesn't have an associated volume element", iMarker, iElem_Surface ); + SPRINTF(buf, "The surface element (%u, %lu) doesn't have an associated volume element", iMarker, iElem_Surface); SU2_MPI::Error(buf, CURRENT_FUNCTION); } } } -void CPhysicalGeometry::SetVertex(const CConfig *config) { - unsigned long iPoint, iVertex, iElem; +void CPhysicalGeometry::SetVertex(const CConfig* config) { + unsigned long iPoint, iVertex, iElem; unsigned short iMarker, iNode; /*--- Initialize the Vertex vector for each node of the grid ---*/ for (iPoint = 0; iPoint < nPoint; iPoint++) - for (iMarker = 0; iMarker < nMarker; iMarker++) - nodes->SetVertex(iPoint, -1, iMarker); + for (iMarker = 0; iMarker < nMarker; iMarker++) nodes->SetVertex(iPoint, -1, iMarker); /*--- Create and compute the vector with the number of vertex per marker ---*/ - nVertex = new unsigned long [nMarker]; + nVertex = new unsigned long[nMarker]; for (iMarker = 0; iMarker < nMarker; iMarker++) { - /*--- Initialize the number of Bound Vertex for each Marker ---*/ nVertex[iMarker] = 0; @@ -5030,15 +4710,14 @@ void CPhysicalGeometry::SetVertex(const CConfig *config) { /*--- Initialize the Vertex vector for each node, the previous result is deleted ---*/ for (iPoint = 0; iPoint < nPoint; iPoint++) - for (iMarker = 0; iMarker < nMarker; iMarker++) - nodes->SetVertex(iPoint, -1, iMarker); + for (iMarker = 0; iMarker < nMarker; iMarker++) nodes->SetVertex(iPoint, -1, iMarker); /*--- Create the bound vertex structure, note that the order is the same as in the input file, this is important for Send/Receive part ---*/ vertex = new CVertex**[nMarker]; for (iMarker = 0; iMarker < nMarker; iMarker++) { - vertex[iMarker] = new CVertex* [nVertex[iMarker]]; + vertex[iMarker] = new CVertex*[nVertex[iMarker]]; nVertex[iMarker] = 0; /*--- Initialize the number of Bound Vertex for each Marker ---*/ @@ -5063,7 +4742,8 @@ void CPhysicalGeometry::SetVertex(const CConfig *config) { } } -void CPhysicalGeometry::ComputeNSpan(CConfig *config, unsigned short val_iZone, unsigned short marker_flag, bool allocate) { +void CPhysicalGeometry::ComputeNSpan(CConfig* config, unsigned short val_iZone, unsigned short marker_flag, + bool allocate) { unsigned short iMarker, jMarker, iMarkerTP, iSpan, jSpan; unsigned long iPoint, iVertex; long jVertex; @@ -5078,40 +4758,37 @@ void CPhysicalGeometry::ComputeNSpan(CConfig *config, unsigned short val_iZone, nSpan = 0; nSpan_loc = 0; - if (nDim == 2){ - nSpanWiseSections[marker_flag-1] = 1; - //TODO (turbo) make it more genral - if(marker_flag == OUTFLOW) config->SetnSpanWiseSections(1); + if (nDim == 2) { + nSpanWiseSections[marker_flag - 1] = 1; + // TODO (turbo) make it more genral + if (marker_flag == OUTFLOW) config->SetnSpanWiseSections(1); /*---Initilize the vector of span-wise values that will be ordered ---*/ - SpanWiseValue[marker_flag -1] = new su2double[1]; - for (iSpan = 0; iSpan < 1; iSpan++){ - SpanWiseValue[marker_flag -1][iSpan] = 0; + SpanWiseValue[marker_flag - 1] = new su2double[1]; + for (iSpan = 0; iSpan < 1; iSpan++) { + SpanWiseValue[marker_flag - 1][iSpan] = 0; } - } - else{ - if(SpanWise_Kind == AUTOMATIC){ + } else { + if (SpanWise_Kind == AUTOMATIC) { /*--- loop to find inflow of outflow marker---*/ - for (iMarker = 0; iMarker < nMarker; iMarker++){ - for (iMarkerTP=1; iMarkerTP < config->GetnMarker_Turbomachinery()+1; iMarkerTP++){ - + for (iMarker = 0; iMarker < nMarker; iMarker++) { + for (iMarkerTP = 1; iMarkerTP < config->GetnMarker_Turbomachinery() + 1; iMarkerTP++) { if (config->GetMarker_All_Turbomachinery(iMarker) != iMarkerTP) continue; if (config->GetMarker_All_TurbomachineryFlag(iMarker) != marker_flag) continue; /*--- loop to find the vertex that ar both of inflow or outflow marker and on the periodic * in order to caount the number of Span ---*/ - for (jMarker = 0; jMarker < nMarker; jMarker++){ + for (jMarker = 0; jMarker < nMarker; jMarker++) { if (config->GetMarker_All_KindBC(jMarker) != PERIODIC_BOUNDARY) continue; for (iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { - iPoint = vertex[iMarker][iVertex]->GetNode(); if (!nodes->GetDomain(iPoint)) continue; PeriodicBoundary = config->GetMarker_All_PerBound(jMarker); jVertex = nodes->GetVertex(iPoint, jMarker); - if ((jVertex != -1) && (PeriodicBoundary == (val_iZone + 1))){ + if ((jVertex != -1) && (PeriodicBoundary == (val_iZone + 1))) { nSpan++; } } @@ -5125,61 +4802,57 @@ void CPhysicalGeometry::ComputeNSpan(CConfig *config, unsigned short val_iZone, SU2_MPI::Allreduce(&nSpan_loc, &nSpan_max, 1, MPI_INT, MPI_MAX, SU2_MPI::GetComm()); /*--- initialize the vector that will contain the disordered values span-wise ---*/ - nSpanWiseSections[marker_flag -1] = nSpan; + nSpanWiseSections[marker_flag - 1] = nSpan; valueSpan = new su2double[nSpan]; - for (iSpan = 0; iSpan < nSpan; iSpan ++ ){ + for (iSpan = 0; iSpan < nSpan; iSpan++) { valueSpan[iSpan] = -1001.0; } /*--- store the local span-wise value for each processor ---*/ nSpan_loc = 0; - for (iMarker = 0; iMarker < nMarker; iMarker++){ - for (iMarkerTP=1; iMarkerTP < config->GetnMarker_Turbomachinery()+1; iMarkerTP++){ - + for (iMarker = 0; iMarker < nMarker; iMarker++) { + for (iMarkerTP = 1; iMarkerTP < config->GetnMarker_Turbomachinery() + 1; iMarkerTP++) { if (config->GetMarker_All_Turbomachinery(iMarker) != iMarkerTP) continue; if (config->GetMarker_All_TurbomachineryFlag(iMarker) != marker_flag) continue; - for (jMarker = 0; jMarker < nMarker; jMarker++){ + for (jMarker = 0; jMarker < nMarker; jMarker++) { if (config->GetMarker_All_KindBC(jMarker) != PERIODIC_BOUNDARY) continue; for (iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { - iPoint = vertex[iMarker][iVertex]->GetNode(); if (!nodes->GetDomain(iPoint)) continue; PeriodicBoundary = config->GetMarker_All_PerBound(jMarker); jVertex = nodes->GetVertex(iPoint, jMarker); - if ((jVertex != -1) && (PeriodicBoundary == (val_iZone + 1))){ + if ((jVertex != -1) && (PeriodicBoundary == (val_iZone + 1))) { coord = nodes->GetCoord(iPoint); - radius = sqrt(coord[0]*coord[0]+coord[1]*coord[1]); - switch (config->GetKind_TurboMachinery(val_iZone)){ - case CENTRIFUGAL: - valueSpan[nSpan_loc] = coord[2]; - break; - case CENTRIPETAL: - valueSpan[nSpan_loc] = coord[2]; - break; - case AXIAL: - valueSpan[nSpan_loc] = radius; - break; - case CENTRIPETAL_AXIAL: - if (marker_flag == OUTFLOW){ - valueSpan[nSpan_loc] = radius; - } - else{ + radius = sqrt(coord[0] * coord[0] + coord[1] * coord[1]); + switch (config->GetKind_TurboMachinery(val_iZone)) { + case CENTRIFUGAL: valueSpan[nSpan_loc] = coord[2]; - } - break; - case AXIAL_CENTRIFUGAL: - if (marker_flag == INFLOW){ - valueSpan[nSpan_loc] = radius; - } - else{ + break; + case CENTRIPETAL: valueSpan[nSpan_loc] = coord[2]; - } - break; + break; + case AXIAL: + valueSpan[nSpan_loc] = radius; + break; + case CENTRIPETAL_AXIAL: + if (marker_flag == OUTFLOW) { + valueSpan[nSpan_loc] = radius; + } else { + valueSpan[nSpan_loc] = coord[2]; + } + break; + case AXIAL_CENTRIFUGAL: + if (marker_flag == INFLOW) { + valueSpan[nSpan_loc] = radius; + } else { + valueSpan[nSpan_loc] = coord[2]; + } + break; } nSpan_loc++; } @@ -5190,96 +4863,92 @@ void CPhysicalGeometry::ComputeNSpan(CConfig *config, unsigned short val_iZone, /*--- Gather the span-wise values on all the processor ---*/ - vector MyTotValueSpan(nSpan_max*size, -1001.0); + vector MyTotValueSpan(nSpan_max * size, -1001.0); vector MyValueSpan(nSpan_max, -1001.0); vector My_nSpan_loc(size); - for(iSpan = 0; iSpanGet_nSpanWiseSections_User(); - SpanWiseValue[marker_flag -1] = new su2double[config->Get_nSpanWiseSections_User()]; - for (iSpan = 0; iSpan < config->Get_nSpanWiseSections_User(); iSpan++){ - SpanWiseValue[marker_flag -1][iSpan] = 0; + nSpanWiseSections[marker_flag - 1] = config->Get_nSpanWiseSections_User(); + SpanWiseValue[marker_flag - 1] = new su2double[config->Get_nSpanWiseSections_User()]; + for (iSpan = 0; iSpan < config->Get_nSpanWiseSections_User(); iSpan++) { + SpanWiseValue[marker_flag - 1][iSpan] = 0; } /*--- Compute maximum and minimum value span-wise---*/ min = 1E+07; - max =-1E+07; - for (iMarker = 0; iMarker < nMarker; iMarker++){ - for (iMarkerTP=1; iMarkerTP < config->GetnMarker_Turbomachinery()+1; iMarkerTP++){ - + max = -1E+07; + for (iMarker = 0; iMarker < nMarker; iMarker++) { + for (iMarkerTP = 1; iMarkerTP < config->GetnMarker_Turbomachinery() + 1; iMarkerTP++) { if (config->GetMarker_All_Turbomachinery(iMarker) != iMarkerTP) continue; if (config->GetMarker_All_TurbomachineryFlag(iMarker) != marker_flag) continue; - for (jMarker = 0; jMarker < nMarker; jMarker++){ + for (jMarker = 0; jMarker < nMarker; jMarker++) { if (config->GetMarker_All_KindBC(jMarker) != PERIODIC_BOUNDARY) continue; for (iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { - iPoint = vertex[iMarker][iVertex]->GetNode(); if (!nodes->GetDomain(iPoint)) continue; PeriodicBoundary = config->GetMarker_All_PerBound(jMarker); jVertex = nodes->GetVertex(iPoint, jMarker); - if ((jVertex != -1) && (PeriodicBoundary == (val_iZone + 1))){ - + if ((jVertex != -1) && (PeriodicBoundary == (val_iZone + 1))) { coord = nodes->GetCoord(iPoint); - radius = sqrt(coord[0]*coord[0]+coord[1]*coord[1]); - switch (config->GetKind_TurboMachinery(val_iZone)){ - case CENTRIFUGAL: - case CENTRIPETAL: - if (coord[2] < min) min = coord[2]; - if (coord[2] > max) max = coord[2]; - break; - case AXIAL: - if (radius < min) min = radius; - if (radius > max) max = radius; - break; - case CENTRIPETAL_AXIAL: - if (marker_flag == OUTFLOW){ - if (radius < min) min = radius; - if (radius > max) max = radius; - } - else{ + radius = sqrt(coord[0] * coord[0] + coord[1] * coord[1]); + switch (config->GetKind_TurboMachinery(val_iZone)) { + case CENTRIFUGAL: + case CENTRIPETAL: if (coord[2] < min) min = coord[2]; if (coord[2] > max) max = coord[2]; - } - break; - case AXIAL_CENTRIFUGAL: - if (marker_flag == INFLOW){ + break; + case AXIAL: if (radius < min) min = radius; if (radius > max) max = radius; - } - else{ - if (coord[2] < min) min = coord[2]; - if (coord[2] > max) max = coord[2]; - } - break; + break; + case CENTRIPETAL_AXIAL: + if (marker_flag == OUTFLOW) { + if (radius < min) min = radius; + if (radius > max) max = radius; + } else { + if (coord[2] < min) min = coord[2]; + if (coord[2] > max) max = coord[2]; + } + break; + case AXIAL_CENTRIFUGAL: + if (marker_flag == INFLOW) { + if (radius < min) min = radius; + if (radius > max) max = radius; + } else { + if (coord[2] < min) min = coord[2]; + if (coord[2] > max) max = coord[2]; + } + break; } } } @@ -5287,115 +4956,120 @@ void CPhysicalGeometry::ComputeNSpan(CConfig *config, unsigned short val_iZone, } } /*--- compute global minimum and maximum value on span-wise ---*/ - MyMin= min; min = 0; - MyMax= max; max = 0; + MyMin = min; + min = 0; + MyMax = max; + max = 0; SU2_MPI::Allreduce(&MyMin, &min, 1, MPI_DOUBLE, MPI_MIN, SU2_MPI::GetComm()); SU2_MPI::Allreduce(&MyMax, &max, 1, MPI_DOUBLE, MPI_MAX, SU2_MPI::GetComm()); /*--- compute height value for each spanwise section---*/ - delta = (max - min)/(nSpanWiseSections[marker_flag-1] -1); - for(iSpan = 0; iSpan < nSpanWiseSections[marker_flag-1]; iSpan++){ - SpanWiseValue[marker_flag - 1][iSpan]= min + delta*iSpan; + delta = (max - min) / (nSpanWiseSections[marker_flag - 1] - 1); + for (iSpan = 0; iSpan < nSpanWiseSections[marker_flag - 1]; iSpan++) { + SpanWiseValue[marker_flag - 1][iSpan] = min + delta * iSpan; } } - if(marker_flag == OUTFLOW){ - if(nSpanWiseSections[INFLOW -1] != nSpanWiseSections[OUTFLOW - 1]){ + if (marker_flag == OUTFLOW) { + if (nSpanWiseSections[INFLOW - 1] != nSpanWiseSections[OUTFLOW - 1]) { char buf[100]; - SPRINTF(buf, "nSpan inflow %u, nSpan outflow %u", nSpanWiseSections[INFLOW-1], nSpanWiseSections[OUTFLOW-1]); - SU2_MPI::Error(string(" At the moment only turbomachinery with the same amount of span-wise section can be simulated\n") + buf, CURRENT_FUNCTION); - } - else{ - config->SetnSpanWiseSections(nSpanWiseSections[OUTFLOW -1]); + SPRINTF(buf, "nSpan inflow %u, nSpan outflow %u", nSpanWiseSections[INFLOW - 1], + nSpanWiseSections[OUTFLOW - 1]); + SU2_MPI::Error( + string(" At the moment only turbomachinery with the same amount of span-wise section can be simulated\n") + + buf, + CURRENT_FUNCTION); + } else { + config->SetnSpanWiseSections(nSpanWiseSections[OUTFLOW - 1]); } } - } - } -void CPhysicalGeometry::SetTurboVertex(CConfig *config, unsigned short val_iZone, unsigned short marker_flag, bool allocate) { - unsigned long iPoint, **ordered, **disordered, **oldVertex3D, iInternalVertex; +void CPhysicalGeometry::SetTurboVertex(CConfig* config, unsigned short val_iZone, unsigned short marker_flag, + bool allocate) { + unsigned long iPoint, **ordered, **disordered, **oldVertex3D, iInternalVertex; unsigned long nVert, nVertMax; unsigned short iMarker, iMarkerTP, iSpan, jSpan, iDim; - su2double min, minInt, max, *coord, dist, Normal2, *TurboNormal, *NormalArea, target = 0.0, **area, ***unitnormal, Area = 0.0; - bool **checkAssign; - min = 10.0E+06; - minInt = 10.0E+06; - max = -10.0E+06; + su2double min, minInt, max, *coord, dist, Normal2, *TurboNormal, *NormalArea, target = 0.0, **area, ***unitnormal, + Area = 0.0; + bool** checkAssign; + min = 10.0E+06; + minInt = 10.0E+06; + max = -10.0E+06; su2double radius; long iVertex, iSpanVertex, jSpanVertex, kSpanVertex = 0; int *nTotVertex_gb, *nVertexSpanHalo; - su2double **x_loc, **y_loc, **z_loc, **angCoord_loc, **deltaAngCoord_loc, **angPitch, **deltaAngPitch, *minIntAngPitch, - *minAngPitch, *maxAngPitch; - int **rank_loc; + su2double **x_loc, **y_loc, **z_loc, **angCoord_loc, **deltaAngCoord_loc, **angPitch, **deltaAngPitch, + *minIntAngPitch, *minAngPitch, *maxAngPitch; + int** rank_loc; #ifdef HAVE_MPI unsigned short iSize, kSize = 0, jSize; - su2double MyMin,MyIntMin, MyMax; + su2double MyMin, MyIntMin, MyMax; su2double *x_gb = NULL, *y_gb = NULL, *z_gb = NULL, *angCoord_gb = NULL, *deltaAngCoord_gb = NULL; - bool *checkAssign_gb =NULL; + bool* checkAssign_gb = NULL; unsigned long My_nVert; #endif string multizone_filename; - x_loc = new su2double*[nSpanWiseSections[marker_flag-1]]; - y_loc = new su2double*[nSpanWiseSections[marker_flag-1]]; - z_loc = new su2double*[nSpanWiseSections[marker_flag-1]]; - angCoord_loc = new su2double*[nSpanWiseSections[marker_flag-1]]; - deltaAngCoord_loc = new su2double*[nSpanWiseSections[marker_flag-1]]; - angPitch = new su2double*[nSpanWiseSections[marker_flag-1]]; - deltaAngPitch = new su2double*[nSpanWiseSections[marker_flag-1]]; - rank_loc = new int*[nSpanWiseSections[marker_flag-1]]; - minAngPitch = new su2double[nSpanWiseSections[marker_flag-1]]; - minIntAngPitch = new su2double[nSpanWiseSections[marker_flag-1]]; - maxAngPitch = new su2double[nSpanWiseSections[marker_flag-1]]; - - nTotVertex_gb = new int[nSpanWiseSections[marker_flag-1]]; - nVertexSpanHalo = new int[nSpanWiseSections[marker_flag-1]]; - for(iSpan = 0; iSpan < nSpanWiseSections[marker_flag-1]; iSpan++){ - nTotVertex_gb[iSpan] = -1; + x_loc = new su2double*[nSpanWiseSections[marker_flag - 1]]; + y_loc = new su2double*[nSpanWiseSections[marker_flag - 1]]; + z_loc = new su2double*[nSpanWiseSections[marker_flag - 1]]; + angCoord_loc = new su2double*[nSpanWiseSections[marker_flag - 1]]; + deltaAngCoord_loc = new su2double*[nSpanWiseSections[marker_flag - 1]]; + angPitch = new su2double*[nSpanWiseSections[marker_flag - 1]]; + deltaAngPitch = new su2double*[nSpanWiseSections[marker_flag - 1]]; + rank_loc = new int*[nSpanWiseSections[marker_flag - 1]]; + minAngPitch = new su2double[nSpanWiseSections[marker_flag - 1]]; + minIntAngPitch = new su2double[nSpanWiseSections[marker_flag - 1]]; + maxAngPitch = new su2double[nSpanWiseSections[marker_flag - 1]]; + + nTotVertex_gb = new int[nSpanWiseSections[marker_flag - 1]]; + nVertexSpanHalo = new int[nSpanWiseSections[marker_flag - 1]]; + for (iSpan = 0; iSpan < nSpanWiseSections[marker_flag - 1]; iSpan++) { + nTotVertex_gb[iSpan] = -1; nVertexSpanHalo[iSpan] = 0; - minAngPitch[iSpan] = 10.0E+06; - minIntAngPitch[iSpan] = 10.0E+06; - maxAngPitch[iSpan] = -10.0E+06; + minAngPitch[iSpan] = 10.0E+06; + minIntAngPitch[iSpan] = 10.0E+06; + maxAngPitch[iSpan] = -10.0E+06; } /*--- Initialize auxiliary pointers ---*/ - TurboNormal = new su2double[3]; - NormalArea = new su2double[3]; - ordered = new unsigned long* [nSpanWiseSections[marker_flag-1]]; - disordered = new unsigned long* [nSpanWiseSections[marker_flag-1]]; - oldVertex3D = new unsigned long* [nSpanWiseSections[marker_flag-1]]; - area = new su2double* [nSpanWiseSections[marker_flag-1]]; - unitnormal = new su2double** [nSpanWiseSections[marker_flag-1]]; - checkAssign = new bool* [nSpanWiseSections[marker_flag-1]]; + TurboNormal = new su2double[3]; + NormalArea = new su2double[3]; + ordered = new unsigned long*[nSpanWiseSections[marker_flag - 1]]; + disordered = new unsigned long*[nSpanWiseSections[marker_flag - 1]]; + oldVertex3D = new unsigned long*[nSpanWiseSections[marker_flag - 1]]; + area = new su2double*[nSpanWiseSections[marker_flag - 1]]; + unitnormal = new su2double**[nSpanWiseSections[marker_flag - 1]]; + checkAssign = new bool*[nSpanWiseSections[marker_flag - 1]]; /*--- Initialize the new Vertex structure. The if statement ensures that these vectors are initialized * only once even if the routine is called more than once.---*/ - if (allocate){ - for (iMarker = 0; iMarker < nMarker; iMarker++){ - for (iMarkerTP=1; iMarkerTP < config->GetnMarker_Turbomachinery()+1; iMarkerTP++){ - if (config->GetMarker_All_Turbomachinery(iMarker) == iMarkerTP){ - if (config->GetMarker_All_TurbomachineryFlag(iMarker) == marker_flag){ - nSpanSectionsByMarker[iMarker] = nSpanWiseSections[marker_flag-1]; - nVertexSpan[iMarker] = new long[nSpanWiseSections[marker_flag-1]]; - turbovertex[iMarker] = new CTurboVertex** [nSpanWiseSections[marker_flag-1]]; - nTotVertexSpan[iMarker] = new unsigned long [nSpanWiseSections[marker_flag-1] +1]; - MaxAngularCoord[iMarker] = new su2double [nSpanWiseSections[marker_flag-1]]; - MinAngularCoord[iMarker] = new su2double [nSpanWiseSections[marker_flag-1]]; - MinRelAngularCoord[iMarker] = new su2double [nSpanWiseSections[marker_flag-1]]; - for(iSpan = 0; iSpan < nSpanWiseSections[marker_flag-1]; iSpan++){ - nVertexSpan[iMarker][iSpan] = 0; - turbovertex[iMarker][iSpan] = nullptr; - MinAngularCoord[iMarker][iSpan] = 10.0E+06; - MaxAngularCoord[iMarker][iSpan] = -10.0E+06; + if (allocate) { + for (iMarker = 0; iMarker < nMarker; iMarker++) { + for (iMarkerTP = 1; iMarkerTP < config->GetnMarker_Turbomachinery() + 1; iMarkerTP++) { + if (config->GetMarker_All_Turbomachinery(iMarker) == iMarkerTP) { + if (config->GetMarker_All_TurbomachineryFlag(iMarker) == marker_flag) { + nSpanSectionsByMarker[iMarker] = nSpanWiseSections[marker_flag - 1]; + nVertexSpan[iMarker] = new long[nSpanWiseSections[marker_flag - 1]]; + turbovertex[iMarker] = new CTurboVertex**[nSpanWiseSections[marker_flag - 1]]; + nTotVertexSpan[iMarker] = new unsigned long[nSpanWiseSections[marker_flag - 1] + 1]; + MaxAngularCoord[iMarker] = new su2double[nSpanWiseSections[marker_flag - 1]]; + MinAngularCoord[iMarker] = new su2double[nSpanWiseSections[marker_flag - 1]]; + MinRelAngularCoord[iMarker] = new su2double[nSpanWiseSections[marker_flag - 1]]; + for (iSpan = 0; iSpan < nSpanWiseSections[marker_flag - 1]; iSpan++) { + nVertexSpan[iMarker][iSpan] = 0; + turbovertex[iMarker][iSpan] = nullptr; + MinAngularCoord[iMarker][iSpan] = 10.0E+06; + MaxAngularCoord[iMarker][iSpan] = -10.0E+06; MinRelAngularCoord[iMarker][iSpan] = 10.0E+06; } - for(iSpan = 0; iSpan < nSpanWiseSections[marker_flag-1] +1; iSpan++){ - nTotVertexSpan[iMarker][iSpan] = 0; + for (iSpan = 0; iSpan < nSpanWiseSections[marker_flag - 1] + 1; iSpan++) { + nTotVertexSpan[iMarker][iSpan] = 0; } } } @@ -5403,330 +5077,324 @@ void CPhysicalGeometry::SetTurboVertex(CConfig *config, unsigned short val_iZone } } - //this works only for turbomachinery rotating around the Z-Axes. - // the reordering algorithm pitch-wise assumes that X-coordinate of each boundary vertex is positive so that reordering can be based on the Y-coordinate. - for (iMarker = 0; iMarker < nMarker; iMarker++){ - for (iMarkerTP=1; iMarkerTP < config->GetnMarker_Turbomachinery()+1; iMarkerTP++){ - if (config->GetMarker_All_Turbomachinery(iMarker) == iMarkerTP){ - if (config->GetMarker_All_TurbomachineryFlag(iMarker) == marker_flag){ - - /*--- compute the amount of vertexes for each span-wise section to initialize the CTurboVertex pointers and auxiliary pointers ---*/ - for (iVertex = 0; (unsigned long)iVertex < nVertex[iMarker]; iVertex++) { - iPoint = vertex[iMarker][iVertex]->GetNode(); - if (nDim == 3){ - dist = 10E+06; - jSpan = std::numeric_limits::max(); - coord = nodes->GetCoord(iPoint); + // this works only for turbomachinery rotating around the Z-Axes. + // the reordering algorithm pitch-wise assumes that X-coordinate of each boundary vertex is positive so that + // reordering can be based on the Y-coordinate. + for (iMarker = 0; iMarker < nMarker; iMarker++) { + for (iMarkerTP = 1; iMarkerTP < config->GetnMarker_Turbomachinery() + 1; iMarkerTP++) { + if (config->GetMarker_All_Turbomachinery(iMarker) == iMarkerTP) { + if (config->GetMarker_All_TurbomachineryFlag(iMarker) == marker_flag) { + /*--- compute the amount of vertexes for each span-wise section to initialize the CTurboVertex pointers and + * auxiliary pointers ---*/ + for (iVertex = 0; (unsigned long)iVertex < nVertex[iMarker]; iVertex++) { + iPoint = vertex[iMarker][iVertex]->GetNode(); + if (nDim == 3) { + dist = 10E+06; + jSpan = std::numeric_limits::max(); + coord = nodes->GetCoord(iPoint); - switch (config->GetKind_TurboMachinery(val_iZone)){ - case CENTRIFUGAL: case CENTRIPETAL: - for(iSpan = 0; iSpan < nSpanWiseSections[marker_flag-1]; iSpan++){ - if (dist > (abs(coord[2]-SpanWiseValue[marker_flag-1][iSpan]))){ - dist= abs(coord[2]-SpanWiseValue[marker_flag-1][iSpan]); - jSpan=iSpan; + switch (config->GetKind_TurboMachinery(val_iZone)) { + case CENTRIFUGAL: + case CENTRIPETAL: + for (iSpan = 0; iSpan < nSpanWiseSections[marker_flag - 1]; iSpan++) { + if (dist > (abs(coord[2] - SpanWiseValue[marker_flag - 1][iSpan]))) { + dist = abs(coord[2] - SpanWiseValue[marker_flag - 1][iSpan]); + jSpan = iSpan; } } break; case AXIAL: - radius = sqrt(coord[0]*coord[0]+coord[1]*coord[1]); - for(iSpan = 0; iSpan < nSpanWiseSections[marker_flag-1]; iSpan++){ - if (dist > (abs(radius - SpanWiseValue[marker_flag-1][iSpan]))){ - dist= abs(radius-SpanWiseValue[marker_flag-1][iSpan]); - jSpan=iSpan; + radius = sqrt(coord[0] * coord[0] + coord[1] * coord[1]); + for (iSpan = 0; iSpan < nSpanWiseSections[marker_flag - 1]; iSpan++) { + if (dist > (abs(radius - SpanWiseValue[marker_flag - 1][iSpan]))) { + dist = abs(radius - SpanWiseValue[marker_flag - 1][iSpan]); + jSpan = iSpan; } } break; case CENTRIPETAL_AXIAL: - if (marker_flag == OUTFLOW){ - radius = sqrt(coord[0]*coord[0]+coord[1]*coord[1]); - for(iSpan = 0; iSpan < nSpanWiseSections[marker_flag-1]; iSpan++){ - if (dist > (abs(radius - SpanWiseValue[marker_flag-1][iSpan]))){ - dist= abs(radius-SpanWiseValue[marker_flag-1][iSpan]); - jSpan=iSpan; + if (marker_flag == OUTFLOW) { + radius = sqrt(coord[0] * coord[0] + coord[1] * coord[1]); + for (iSpan = 0; iSpan < nSpanWiseSections[marker_flag - 1]; iSpan++) { + if (dist > (abs(radius - SpanWiseValue[marker_flag - 1][iSpan]))) { + dist = abs(radius - SpanWiseValue[marker_flag - 1][iSpan]); + jSpan = iSpan; } } - } - else{ - for(iSpan = 0; iSpan < nSpanWiseSections[marker_flag-1]; iSpan++){ - if (dist > (abs(coord[2]-SpanWiseValue[marker_flag-1][iSpan]))){ - dist= abs(coord[2]-SpanWiseValue[marker_flag-1][iSpan]); - jSpan=iSpan; + } else { + for (iSpan = 0; iSpan < nSpanWiseSections[marker_flag - 1]; iSpan++) { + if (dist > (abs(coord[2] - SpanWiseValue[marker_flag - 1][iSpan]))) { + dist = abs(coord[2] - SpanWiseValue[marker_flag - 1][iSpan]); + jSpan = iSpan; } } } break; case AXIAL_CENTRIFUGAL: - if (marker_flag == INFLOW){ - radius = sqrt(coord[0]*coord[0]+coord[1]*coord[1]); - for(iSpan = 0; iSpan < nSpanWiseSections[marker_flag-1]; iSpan++){ - if (dist > (abs(radius - SpanWiseValue[marker_flag-1][iSpan]))){ - dist= abs(radius-SpanWiseValue[marker_flag-1][iSpan]); - jSpan=iSpan; + if (marker_flag == INFLOW) { + radius = sqrt(coord[0] * coord[0] + coord[1] * coord[1]); + for (iSpan = 0; iSpan < nSpanWiseSections[marker_flag - 1]; iSpan++) { + if (dist > (abs(radius - SpanWiseValue[marker_flag - 1][iSpan]))) { + dist = abs(radius - SpanWiseValue[marker_flag - 1][iSpan]); + jSpan = iSpan; } } - } - else{ - for(iSpan = 0; iSpan < nSpanWiseSections[marker_flag-1]; iSpan++){ - if (dist > (abs(coord[2]-SpanWiseValue[marker_flag-1][iSpan]))){ - dist= abs(coord[2]-SpanWiseValue[marker_flag-1][iSpan]); - jSpan=iSpan; + } else { + for (iSpan = 0; iSpan < nSpanWiseSections[marker_flag - 1]; iSpan++) { + if (dist > (abs(coord[2] - SpanWiseValue[marker_flag - 1][iSpan]))) { + dist = abs(coord[2] - SpanWiseValue[marker_flag - 1][iSpan]); + jSpan = iSpan; } } } break; - } } + } - /*--- 2D problem do not need span-wise separation---*/ - else{ - jSpan = 0; - } + /*--- 2D problem do not need span-wise separation---*/ + else { + jSpan = 0; + } - if(nodes->GetDomain(iPoint)){ - nVertexSpan[iMarker][jSpan]++; - } - nVertexSpanHalo[jSpan]++; + if (nodes->GetDomain(iPoint)) { + nVertexSpan[iMarker][jSpan]++; } + nVertexSpanHalo[jSpan]++; + } - /*--- initialize the CTurboVertex pointers and auxiliary pointers ---*/ - for(iSpan = 0; iSpan < nSpanWiseSections[marker_flag-1]; iSpan++){ - if (allocate){ - turbovertex[iMarker][iSpan] = new CTurboVertex* [nVertexSpan[iMarker][iSpan]]; - for (iVertex = 0; iVertex < nVertexSpan[iMarker][iSpan]; iVertex++){ - turbovertex[iMarker][iSpan][iVertex] = nullptr; - } - } - ordered[iSpan] = new unsigned long [nVertexSpanHalo[iSpan]]; - disordered[iSpan] = new unsigned long [nVertexSpanHalo[iSpan]]; - oldVertex3D[iSpan] = new unsigned long [nVertexSpanHalo[iSpan]]; - checkAssign[iSpan] = new bool [nVertexSpanHalo[iSpan]]; - area[iSpan] = new su2double [nVertexSpanHalo[iSpan]]; - unitnormal[iSpan] = new su2double* [nVertexSpanHalo[iSpan]]; - for (iVertex = 0; iVertex < nVertexSpanHalo[iSpan]; iVertex++){ - unitnormal[iSpan][iVertex] = new su2double [nDim]; + /*--- initialize the CTurboVertex pointers and auxiliary pointers ---*/ + for (iSpan = 0; iSpan < nSpanWiseSections[marker_flag - 1]; iSpan++) { + if (allocate) { + turbovertex[iMarker][iSpan] = new CTurboVertex*[nVertexSpan[iMarker][iSpan]]; + for (iVertex = 0; iVertex < nVertexSpan[iMarker][iSpan]; iVertex++) { + turbovertex[iMarker][iSpan][iVertex] = nullptr; } - angPitch[iSpan] = new su2double [nVertexSpanHalo[iSpan]]; - deltaAngPitch[iSpan] = new su2double [nVertexSpanHalo[iSpan]]; - nVertexSpanHalo[iSpan] = 0; } + ordered[iSpan] = new unsigned long[nVertexSpanHalo[iSpan]]; + disordered[iSpan] = new unsigned long[nVertexSpanHalo[iSpan]]; + oldVertex3D[iSpan] = new unsigned long[nVertexSpanHalo[iSpan]]; + checkAssign[iSpan] = new bool[nVertexSpanHalo[iSpan]]; + area[iSpan] = new su2double[nVertexSpanHalo[iSpan]]; + unitnormal[iSpan] = new su2double*[nVertexSpanHalo[iSpan]]; + for (iVertex = 0; iVertex < nVertexSpanHalo[iSpan]; iVertex++) { + unitnormal[iSpan][iVertex] = new su2double[nDim]; + } + angPitch[iSpan] = new su2double[nVertexSpanHalo[iSpan]]; + deltaAngPitch[iSpan] = new su2double[nVertexSpanHalo[iSpan]]; + nVertexSpanHalo[iSpan] = 0; + } - /*--- store the vertexes in a ordered manner in span-wise directions but not yet ordered pitch-wise ---*/ - for (iVertex = 0; (unsigned long)iVertex < nVertex[iMarker]; iVertex++) { - iPoint = vertex[iMarker][iVertex]->GetNode(); - if(nDim == 3){ - dist = 10E+06; - jSpan = std::numeric_limits::max(); + /*--- store the vertexes in a ordered manner in span-wise directions but not yet ordered pitch-wise ---*/ + for (iVertex = 0; (unsigned long)iVertex < nVertex[iMarker]; iVertex++) { + iPoint = vertex[iMarker][iVertex]->GetNode(); + if (nDim == 3) { + dist = 10E+06; + jSpan = std::numeric_limits::max(); - coord = nodes->GetCoord(iPoint); - switch (config->GetKind_TurboMachinery(val_iZone)){ - case CENTRIFUGAL: case CENTRIPETAL: - for(iSpan = 0; iSpan < nSpanWiseSections[marker_flag-1]; iSpan++){ - if (dist > (abs(coord[2]-SpanWiseValue[marker_flag-1][iSpan]))){ - dist= abs(coord[2]-SpanWiseValue[marker_flag-1][iSpan]); - jSpan=iSpan; + coord = nodes->GetCoord(iPoint); + switch (config->GetKind_TurboMachinery(val_iZone)) { + case CENTRIFUGAL: + case CENTRIPETAL: + for (iSpan = 0; iSpan < nSpanWiseSections[marker_flag - 1]; iSpan++) { + if (dist > (abs(coord[2] - SpanWiseValue[marker_flag - 1][iSpan]))) { + dist = abs(coord[2] - SpanWiseValue[marker_flag - 1][iSpan]); + jSpan = iSpan; } } break; case AXIAL: - radius = sqrt(coord[0]*coord[0]+coord[1]*coord[1]); - for(iSpan = 0; iSpan < nSpanWiseSections[marker_flag-1]; iSpan++){ - if (dist > (abs(radius - SpanWiseValue[marker_flag-1][iSpan]))){ - dist= abs(radius-SpanWiseValue[marker_flag-1][iSpan]); - jSpan=iSpan; + radius = sqrt(coord[0] * coord[0] + coord[1] * coord[1]); + for (iSpan = 0; iSpan < nSpanWiseSections[marker_flag - 1]; iSpan++) { + if (dist > (abs(radius - SpanWiseValue[marker_flag - 1][iSpan]))) { + dist = abs(radius - SpanWiseValue[marker_flag - 1][iSpan]); + jSpan = iSpan; } } break; case CENTRIPETAL_AXIAL: - if(marker_flag == OUTFLOW){ - radius = sqrt(coord[0]*coord[0]+coord[1]*coord[1]); - for(iSpan = 0; iSpan < nSpanWiseSections[marker_flag-1]; iSpan++){ - if (dist > (abs(radius - SpanWiseValue[marker_flag-1][iSpan]))){ - dist= abs(radius-SpanWiseValue[marker_flag-1][iSpan]); - jSpan=iSpan; + if (marker_flag == OUTFLOW) { + radius = sqrt(coord[0] * coord[0] + coord[1] * coord[1]); + for (iSpan = 0; iSpan < nSpanWiseSections[marker_flag - 1]; iSpan++) { + if (dist > (abs(radius - SpanWiseValue[marker_flag - 1][iSpan]))) { + dist = abs(radius - SpanWiseValue[marker_flag - 1][iSpan]); + jSpan = iSpan; } } - }else{ - for(iSpan = 0; iSpan < nSpanWiseSections[marker_flag-1]; iSpan++){ - if (dist > (abs(coord[2]-SpanWiseValue[marker_flag-1][iSpan]))){ - dist= abs(coord[2]-SpanWiseValue[marker_flag-1][iSpan]); - jSpan=iSpan; + } else { + for (iSpan = 0; iSpan < nSpanWiseSections[marker_flag - 1]; iSpan++) { + if (dist > (abs(coord[2] - SpanWiseValue[marker_flag - 1][iSpan]))) { + dist = abs(coord[2] - SpanWiseValue[marker_flag - 1][iSpan]); + jSpan = iSpan; } } } break; case AXIAL_CENTRIFUGAL: - if(marker_flag == INFLOW){ - radius = sqrt(coord[0]*coord[0]+coord[1]*coord[1]); - for(iSpan = 0; iSpan < nSpanWiseSections[marker_flag-1]; iSpan++){ - if (dist > (abs(radius - SpanWiseValue[marker_flag-1][iSpan]))){ - dist= abs(radius-SpanWiseValue[marker_flag-1][iSpan]); - jSpan=iSpan; + if (marker_flag == INFLOW) { + radius = sqrt(coord[0] * coord[0] + coord[1] * coord[1]); + for (iSpan = 0; iSpan < nSpanWiseSections[marker_flag - 1]; iSpan++) { + if (dist > (abs(radius - SpanWiseValue[marker_flag - 1][iSpan]))) { + dist = abs(radius - SpanWiseValue[marker_flag - 1][iSpan]); + jSpan = iSpan; } } - }else{ - for(iSpan = 0; iSpan < nSpanWiseSections[marker_flag-1]; iSpan++){ - if (dist > (abs(coord[2]-SpanWiseValue[marker_flag-1][iSpan]))){ - dist= abs(coord[2]-SpanWiseValue[marker_flag-1][iSpan]); - jSpan=iSpan; + } else { + for (iSpan = 0; iSpan < nSpanWiseSections[marker_flag - 1]; iSpan++) { + if (dist > (abs(coord[2] - SpanWiseValue[marker_flag - 1][iSpan]))) { + dist = abs(coord[2] - SpanWiseValue[marker_flag - 1][iSpan]); + jSpan = iSpan; } } } break; - } - } - /*--- 2D problem do not need span-wise separation---*/ - else{ - jSpan = 0; } - /*--- compute the face area associated with the vertex ---*/ - vertex[iMarker][iVertex]->GetNormal(NormalArea); - for (iDim = 0; iDim < nDim; iDim++) NormalArea[iDim] = -NormalArea[iDim]; - Area = GeometryToolbox::Norm(nDim, NormalArea); - - for (iDim = 0; iDim < nDim; iDim++) NormalArea[iDim] /= Area; - /*--- store all the all the info into the auxiliary containers ---*/ - disordered[jSpan][nVertexSpanHalo[jSpan]] = iPoint; - oldVertex3D[jSpan][nVertexSpanHalo[jSpan]] = iVertex; - area[jSpan][nVertexSpanHalo[jSpan]] = Area; - for (iDim = 0; iDim < nDim; iDim++){ - unitnormal[jSpan][nVertexSpanHalo[jSpan]][iDim] = NormalArea[iDim]; - } - checkAssign[jSpan][nVertexSpanHalo[jSpan]] = false; - nVertexSpanHalo[jSpan]++; } + /*--- 2D problem do not need span-wise separation---*/ + else { + jSpan = 0; + } + /*--- compute the face area associated with the vertex ---*/ + vertex[iMarker][iVertex]->GetNormal(NormalArea); + for (iDim = 0; iDim < nDim; iDim++) NormalArea[iDim] = -NormalArea[iDim]; + Area = GeometryToolbox::Norm(nDim, NormalArea); + + for (iDim = 0; iDim < nDim; iDim++) NormalArea[iDim] /= Area; + /*--- store all the all the info into the auxiliary containers ---*/ + disordered[jSpan][nVertexSpanHalo[jSpan]] = iPoint; + oldVertex3D[jSpan][nVertexSpanHalo[jSpan]] = iVertex; + area[jSpan][nVertexSpanHalo[jSpan]] = Area; + for (iDim = 0; iDim < nDim; iDim++) { + unitnormal[jSpan][nVertexSpanHalo[jSpan]][iDim] = NormalArea[iDim]; + } + checkAssign[jSpan][nVertexSpanHalo[jSpan]] = false; + nVertexSpanHalo[jSpan]++; + } - /*--- using the auxiliary container reordered the vertexes pitch-wise direction at each span ---*/ - // the reordering algorithm can be based on the Y-coordinate. - for(iSpan = 0; iSpan < nSpanWiseSections[marker_flag-1]; iSpan++){ - - /*--- find the local minimum and maximum pitch-wise for each processor---*/ - min = 10E+06; - minInt = 10E+06; - max = -10E+06; - for(iSpanVertex = 0; iSpanVertex < nVertexSpanHalo[iSpan]; iSpanVertex++){ - iPoint = disordered[iSpan][iSpanVertex]; - coord = nodes->GetCoord(iPoint); - /*--- find nodes at minimum pitch among all nodes---*/ - if (coord[1]GetKind_TurboMachinery(val_iZone) == AXIAL){ - MinAngularCoord[iMarker][iSpan] = coord[1]; - } - else{ - MinAngularCoord[iMarker][iSpan] = atan(coord[1]/coord[0]); - } - minAngPitch[iSpan]= MinAngularCoord[iMarker][iSpan]; - kSpanVertex =iSpanVertex; + /*--- using the auxiliary container reordered the vertexes pitch-wise direction at each span ---*/ + // the reordering algorithm can be based on the Y-coordinate. + for (iSpan = 0; iSpan < nSpanWiseSections[marker_flag - 1]; iSpan++) { + /*--- find the local minimum and maximum pitch-wise for each processor---*/ + min = 10E+06; + minInt = 10E+06; + max = -10E+06; + for (iSpanVertex = 0; iSpanVertex < nVertexSpanHalo[iSpan]; iSpanVertex++) { + iPoint = disordered[iSpan][iSpanVertex]; + coord = nodes->GetCoord(iPoint); + /*--- find nodes at minimum pitch among all nodes---*/ + if (coord[1] < min) { + min = coord[1]; + if (nDim == 2 && config->GetKind_TurboMachinery(val_iZone) == AXIAL) { + MinAngularCoord[iMarker][iSpan] = coord[1]; + } else { + MinAngularCoord[iMarker][iSpan] = atan(coord[1] / coord[0]); } + minAngPitch[iSpan] = MinAngularCoord[iMarker][iSpan]; + kSpanVertex = iSpanVertex; + } - /*--- find nodes at minimum pitch among the internal nodes---*/ - if (coord[1]GetDomain(iPoint)){ - minInt = coord[1]; - if (nDim == 2 && config->GetKind_TurboMachinery(val_iZone) == AXIAL){ - minIntAngPitch[iSpan] = coord[1]; - } - else{ - minIntAngPitch[iSpan] = atan(coord[1]/coord[0]); - } + /*--- find nodes at minimum pitch among the internal nodes---*/ + if (coord[1] < minInt) { + if (nodes->GetDomain(iPoint)) { + minInt = coord[1]; + if (nDim == 2 && config->GetKind_TurboMachinery(val_iZone) == AXIAL) { + minIntAngPitch[iSpan] = coord[1]; + } else { + minIntAngPitch[iSpan] = atan(coord[1] / coord[0]); } } + } - /*--- find nodes at maximum pitch among the internal nodes---*/ - if (coord[1]>max){ - if(nodes->GetDomain(iPoint)){ - max =coord[1]; - if (nDim == 2 && config->GetKind_TurboMachinery(val_iZone) == AXIAL){ - MaxAngularCoord[iMarker][iSpan] = coord[1]; - } - else{ - MaxAngularCoord[iMarker][iSpan] = atan(coord[1]/coord[0]); - } - maxAngPitch[iSpan]= MaxAngularCoord[iMarker][iSpan]; + /*--- find nodes at maximum pitch among the internal nodes---*/ + if (coord[1] > max) { + if (nodes->GetDomain(iPoint)) { + max = coord[1]; + if (nDim == 2 && config->GetKind_TurboMachinery(val_iZone) == AXIAL) { + MaxAngularCoord[iMarker][iSpan] = coord[1]; + } else { + MaxAngularCoord[iMarker][iSpan] = atan(coord[1] / coord[0]); } + maxAngPitch[iSpan] = MaxAngularCoord[iMarker][iSpan]; } } + } - iInternalVertex = 0; - - /*--- reordering the vertex pitch-wise, store the ordered vertexes span-wise and pitch-wise---*/ - for(iSpanVertex = 0; iSpanVertexGetCoord(ordered[iSpan][iSpanVertex]); - target = coord[1]; - if (nDim == 2 && config->GetKind_TurboMachinery(val_iZone) == AXIAL){ - angPitch[iSpan][iSpanVertex]=coord[1]; - } - else{ - angPitch[iSpan][iSpanVertex]=atan(coord[1]/coord[0]); - } - if(iSpanVertex == 0){ - deltaAngPitch[iSpan][iSpanVertex]=0.0; - } - else{ - deltaAngPitch[iSpan][iSpanVertex]= angPitch[iSpan][iSpanVertex] - angPitch[iSpan][iSpanVertex - 1]; + iInternalVertex = 0; + + /*--- reordering the vertex pitch-wise, store the ordered vertexes span-wise and pitch-wise---*/ + for (iSpanVertex = 0; iSpanVertex < nVertexSpanHalo[iSpan]; iSpanVertex++) { + dist = 10E+06; + ordered[iSpan][iSpanVertex] = disordered[iSpan][kSpanVertex]; + checkAssign[iSpan][kSpanVertex] = true; + coord = nodes->GetCoord(ordered[iSpan][iSpanVertex]); + target = coord[1]; + if (nDim == 2 && config->GetKind_TurboMachinery(val_iZone) == AXIAL) { + angPitch[iSpan][iSpanVertex] = coord[1]; + } else { + angPitch[iSpan][iSpanVertex] = atan(coord[1] / coord[0]); + } + if (iSpanVertex == 0) { + deltaAngPitch[iSpan][iSpanVertex] = 0.0; + } else { + deltaAngPitch[iSpan][iSpanVertex] = angPitch[iSpan][iSpanVertex] - angPitch[iSpan][iSpanVertex - 1]; + } + /*---create turbovertex structure only for the internal nodes---*/ + if (nodes->GetDomain(ordered[iSpan][iSpanVertex])) { + if (allocate) { + turbovertex[iMarker][iSpan][iInternalVertex] = new CTurboVertex(ordered[iSpan][iSpanVertex], nDim); } - /*---create turbovertex structure only for the internal nodes---*/ - if(nodes->GetDomain(ordered[iSpan][iSpanVertex])){ - if (allocate){ - turbovertex[iMarker][iSpan][iInternalVertex] = new CTurboVertex(ordered[iSpan][iSpanVertex], nDim); - } - turbovertex[iMarker][iSpan][iInternalVertex]->SetArea(area[iSpan][kSpanVertex]); - turbovertex[iMarker][iSpan][iInternalVertex]->SetNormal(unitnormal[iSpan][kSpanVertex]); - turbovertex[iMarker][iSpan][iInternalVertex]->SetOldVertex(oldVertex3D[iSpan][kSpanVertex]); - turbovertex[iMarker][iSpan][iInternalVertex]->SetAngularCoord(angPitch[iSpan][iSpanVertex]); - turbovertex[iMarker][iSpan][iInternalVertex]->SetDeltaAngularCoord(deltaAngPitch[iSpan][iSpanVertex]); - switch (config->GetKind_TurboMachinery(val_iZone)){ + turbovertex[iMarker][iSpan][iInternalVertex]->SetArea(area[iSpan][kSpanVertex]); + turbovertex[iMarker][iSpan][iInternalVertex]->SetNormal(unitnormal[iSpan][kSpanVertex]); + turbovertex[iMarker][iSpan][iInternalVertex]->SetOldVertex(oldVertex3D[iSpan][kSpanVertex]); + turbovertex[iMarker][iSpan][iInternalVertex]->SetAngularCoord(angPitch[iSpan][iSpanVertex]); + turbovertex[iMarker][iSpan][iInternalVertex]->SetDeltaAngularCoord(deltaAngPitch[iSpan][iSpanVertex]); + switch (config->GetKind_TurboMachinery(val_iZone)) { case CENTRIFUGAL: Normal2 = 0.0; - for(iDim = 0; iDim < 2; iDim++) Normal2 +=coord[iDim]*coord[iDim]; - if (marker_flag == INFLOW){ - TurboNormal[0] = -coord[0]/sqrt(Normal2); - TurboNormal[1] = -coord[1]/sqrt(Normal2); + for (iDim = 0; iDim < 2; iDim++) Normal2 += coord[iDim] * coord[iDim]; + if (marker_flag == INFLOW) { + TurboNormal[0] = -coord[0] / sqrt(Normal2); + TurboNormal[1] = -coord[1] / sqrt(Normal2); TurboNormal[2] = 0.0; - }else{ - TurboNormal[0] = coord[0]/sqrt(Normal2); - TurboNormal[1] = coord[1]/sqrt(Normal2); + } else { + TurboNormal[0] = coord[0] / sqrt(Normal2); + TurboNormal[1] = coord[1] / sqrt(Normal2); TurboNormal[2] = 0.0; } break; case CENTRIPETAL: Normal2 = 0.0; - for(iDim = 0; iDim < 2; iDim++) Normal2 +=coord[iDim]*coord[iDim]; - if (marker_flag == OUTFLOW){ - TurboNormal[0] = -coord[0]/sqrt(Normal2); - TurboNormal[1] = -coord[1]/sqrt(Normal2); + for (iDim = 0; iDim < 2; iDim++) Normal2 += coord[iDim] * coord[iDim]; + if (marker_flag == OUTFLOW) { + TurboNormal[0] = -coord[0] / sqrt(Normal2); + TurboNormal[1] = -coord[1] / sqrt(Normal2); TurboNormal[2] = 0.0; - }else{ - TurboNormal[0] = coord[0]/sqrt(Normal2); - TurboNormal[1] = coord[1]/sqrt(Normal2); + } else { + TurboNormal[0] = coord[0] / sqrt(Normal2); + TurboNormal[1] = coord[1] / sqrt(Normal2); TurboNormal[2] = 0.0; } break; case AXIAL: Normal2 = 0.0; - for(iDim = 0; iDim < 2; iDim++) Normal2 +=coord[iDim]*coord[iDim]; - if(nDim == 3){ - if (marker_flag == INFLOW){ - TurboNormal[0] = coord[0]/sqrt(Normal2); - TurboNormal[1] = coord[1]/sqrt(Normal2); + for (iDim = 0; iDim < 2; iDim++) Normal2 += coord[iDim] * coord[iDim]; + if (nDim == 3) { + if (marker_flag == INFLOW) { + TurboNormal[0] = coord[0] / sqrt(Normal2); + TurboNormal[1] = coord[1] / sqrt(Normal2); TurboNormal[2] = 0.0; - }else{ - TurboNormal[0] = coord[0]/sqrt(Normal2); - TurboNormal[1] = coord[1]/sqrt(Normal2); + } else { + TurboNormal[0] = coord[0] / sqrt(Normal2); + TurboNormal[1] = coord[1] / sqrt(Normal2); TurboNormal[2] = 0.0; } - } - else{ - if (marker_flag == INFLOW){ + } else { + if (marker_flag == INFLOW) { TurboNormal[0] = -1.0; TurboNormal[1] = 0.0; TurboNormal[2] = 0.0; - }else{ + } else { TurboNormal[0] = 1.0; TurboNormal[1] = 0.0; TurboNormal[2] = 0.0; @@ -5736,167 +5404,164 @@ void CPhysicalGeometry::SetTurboVertex(CConfig *config, unsigned short val_iZone break; case CENTRIPETAL_AXIAL: Normal2 = 0.0; - for(iDim = 0; iDim < 2; iDim++) Normal2 +=coord[iDim]*coord[iDim]; - if (marker_flag == INFLOW){ - TurboNormal[0] = coord[0]/sqrt(Normal2); - TurboNormal[1] = coord[1]/sqrt(Normal2); + for (iDim = 0; iDim < 2; iDim++) Normal2 += coord[iDim] * coord[iDim]; + if (marker_flag == INFLOW) { + TurboNormal[0] = coord[0] / sqrt(Normal2); + TurboNormal[1] = coord[1] / sqrt(Normal2); TurboNormal[2] = 0.0; - }else{ - TurboNormal[0] = coord[0]/sqrt(Normal2); - TurboNormal[1] = coord[1]/sqrt(Normal2); + } else { + TurboNormal[0] = coord[0] / sqrt(Normal2); + TurboNormal[1] = coord[1] / sqrt(Normal2); TurboNormal[2] = 0.0; } break; case AXIAL_CENTRIFUGAL: Normal2 = 0.0; - for(iDim = 0; iDim < 2; iDim++) Normal2 +=coord[iDim]*coord[iDim]; - if (marker_flag == INFLOW){ - TurboNormal[0] = coord[0]/sqrt(Normal2); - TurboNormal[1] = coord[1]/sqrt(Normal2); + for (iDim = 0; iDim < 2; iDim++) Normal2 += coord[iDim] * coord[iDim]; + if (marker_flag == INFLOW) { + TurboNormal[0] = coord[0] / sqrt(Normal2); + TurboNormal[1] = coord[1] / sqrt(Normal2); TurboNormal[2] = 0.0; - }else{ - TurboNormal[0] = coord[0]/sqrt(Normal2); - TurboNormal[1] = coord[1]/sqrt(Normal2); + } else { + TurboNormal[0] = coord[0] / sqrt(Normal2); + TurboNormal[1] = coord[1] / sqrt(Normal2); TurboNormal[2] = 0.0; } break; - - } - turbovertex[iMarker][iSpan][iInternalVertex]->SetTurboNormal(TurboNormal); - iInternalVertex++; } + turbovertex[iMarker][iSpan][iInternalVertex]->SetTurboNormal(TurboNormal); + iInternalVertex++; + } - - for(jSpanVertex = 0; jSpanVertexGetCoord(disordered[iSpan][jSpanVertex]); - if(dist >= (coord[1] - target) && !checkAssign[iSpan][jSpanVertex] && (coord[1] - target) >= 0.0){ - dist= coord[1] - target; - kSpanVertex =jSpanVertex; - } + for (jSpanVertex = 0; jSpanVertex < nVertexSpanHalo[iSpan]; jSpanVertex++) { + coord = nodes->GetCoord(disordered[iSpan][jSpanVertex]); + if (dist >= (coord[1] - target) && !checkAssign[iSpan][jSpanVertex] && (coord[1] - target) >= 0.0) { + dist = coord[1] - target; + kSpanVertex = jSpanVertex; } } } + } - for(iSpan = 0; iSpan < nSpanWiseSections[marker_flag-1]; iSpan++){ - - delete [] ordered[iSpan]; - delete [] disordered[iSpan]; - delete [] oldVertex3D[iSpan]; - delete [] checkAssign[iSpan]; - delete [] area[iSpan]; - delete [] angPitch[iSpan]; - delete [] deltaAngPitch[iSpan]; - - for(iVertex=0; iVertex < nVertexSpanHalo[iSpan]; iVertex++){ - delete [] unitnormal[iSpan][iVertex]; - } - delete [] unitnormal[iSpan]; + for (iSpan = 0; iSpan < nSpanWiseSections[marker_flag - 1]; iSpan++) { + delete[] ordered[iSpan]; + delete[] disordered[iSpan]; + delete[] oldVertex3D[iSpan]; + delete[] checkAssign[iSpan]; + delete[] area[iSpan]; + delete[] angPitch[iSpan]; + delete[] deltaAngPitch[iSpan]; + + for (iVertex = 0; iVertex < nVertexSpanHalo[iSpan]; iVertex++) { + delete[] unitnormal[iSpan][iVertex]; } + delete[] unitnormal[iSpan]; } } } } + } /*--- to be set for all the processor to initialize an appropriate number of frequency for the NR BC ---*/ nVertMax = 0; /*--- compute global max and min pitch per span ---*/ - for(iSpan = 0; iSpan < nSpanWiseSections[marker_flag-1]; iSpan++){ - nVert = 0; + for (iSpan = 0; iSpan < nSpanWiseSections[marker_flag - 1]; iSpan++) { + nVert = 0; #ifdef HAVE_MPI - MyMin = minAngPitch[iSpan]; minAngPitch[iSpan] = 10.0E+6; - MyIntMin = minIntAngPitch[iSpan]; minIntAngPitch[iSpan] = 10.0E+6; - MyMax = maxAngPitch[iSpan]; maxAngPitch[iSpan] = -10.0E+6; + MyMin = minAngPitch[iSpan]; + minAngPitch[iSpan] = 10.0E+6; + MyIntMin = minIntAngPitch[iSpan]; + minIntAngPitch[iSpan] = 10.0E+6; + MyMax = maxAngPitch[iSpan]; + maxAngPitch[iSpan] = -10.0E+6; SU2_MPI::Allreduce(&MyMin, &minAngPitch[iSpan], 1, MPI_DOUBLE, MPI_MIN, SU2_MPI::GetComm()); SU2_MPI::Allreduce(&MyIntMin, &minIntAngPitch[iSpan], 1, MPI_DOUBLE, MPI_MIN, SU2_MPI::GetComm()); SU2_MPI::Allreduce(&MyMax, &maxAngPitch[iSpan], 1, MPI_DOUBLE, MPI_MAX, SU2_MPI::GetComm()); #endif - /*--- compute the relative angular pitch with respect to the minimum value ---*/ - for (iMarker = 0; iMarker < nMarker; iMarker++){ - for (iMarkerTP=1; iMarkerTP < config->GetnMarker_Turbomachinery()+1; iMarkerTP++){ - if (config->GetMarker_All_Turbomachinery(iMarker) == iMarkerTP){ - if (config->GetMarker_All_TurbomachineryFlag(iMarker) == marker_flag){ + for (iMarker = 0; iMarker < nMarker; iMarker++) { + for (iMarkerTP = 1; iMarkerTP < config->GetnMarker_Turbomachinery() + 1; iMarkerTP++) { + if (config->GetMarker_All_Turbomachinery(iMarker) == iMarkerTP) { + if (config->GetMarker_All_TurbomachineryFlag(iMarker) == marker_flag) { nVert = nVertexSpan[iMarker][iSpan]; - MinAngularCoord[iMarker][iSpan] = minAngPitch[iSpan]; - MaxAngularCoord[iMarker][iSpan] = maxAngPitch[iSpan]; + MinAngularCoord[iMarker][iSpan] = minAngPitch[iSpan]; + MaxAngularCoord[iMarker][iSpan] = maxAngPitch[iSpan]; MinRelAngularCoord[iMarker][iSpan] = minIntAngPitch[iSpan] - minAngPitch[iSpan]; - for(iSpanVertex = 0; iSpanVertex< nVertexSpan[iMarker][iSpan]; iSpanVertex++){ - turbovertex[iMarker][iSpan][iSpanVertex]->SetRelAngularCoord(MinAngularCoord[iMarker][iSpan]); + for (iSpanVertex = 0; iSpanVertex < nVertexSpan[iMarker][iSpan]; iSpanVertex++) { + turbovertex[iMarker][iSpan][iSpanVertex]->SetRelAngularCoord(MinAngularCoord[iMarker][iSpan]); } } } } } - #ifdef HAVE_MPI - My_nVert = nVert;nVert = 0; + My_nVert = nVert; + nVert = 0; SU2_MPI::Allreduce(&My_nVert, &nVert, 1, MPI_INT, MPI_SUM, SU2_MPI::GetComm()); #endif /*--- to be set for all the processor to initialize an appropriate number of frequency for the NR BC ---*/ - if(nVert > nVertMax){ - SetnVertexSpanMax(marker_flag,nVert); + if (nVert > nVertMax) { + SetnVertexSpanMax(marker_flag, nVert); } /*--- for all the processor should be known the amount of total turbovertex per span ---*/ - nTotVertex_gb[iSpan]= (int)nVert; - - for (iMarker = 0; iMarker < nMarker; iMarker++){ - for (iMarkerTP=1; iMarkerTP < config->GetnMarker_Turbomachinery()+1; iMarkerTP++){ - if (config->GetMarker_All_Turbomachinery(iMarker) == iMarkerTP){ - if (config->GetMarker_All_TurbomachineryFlag(iMarker) == marker_flag){ - nTotVertexSpan[iMarker][iSpan]= nVert; - nTotVertexSpan[iMarker][nSpanWiseSections[marker_flag-1]]+= nVert; + nTotVertex_gb[iSpan] = (int)nVert; + + for (iMarker = 0; iMarker < nMarker; iMarker++) { + for (iMarkerTP = 1; iMarkerTP < config->GetnMarker_Turbomachinery() + 1; iMarkerTP++) { + if (config->GetMarker_All_Turbomachinery(iMarker) == iMarkerTP) { + if (config->GetMarker_All_TurbomachineryFlag(iMarker) == marker_flag) { + nTotVertexSpan[iMarker][iSpan] = nVert; + nTotVertexSpan[iMarker][nSpanWiseSections[marker_flag - 1]] += nVert; } } } } } - /*--- Printing Tec file to check the global ordering of the turbovertex pitch-wise ---*/ /*--- Send all the info to the MASTERNODE ---*/ - for(iSpan = 0; iSpan < nSpanWiseSections[marker_flag-1]; iSpan++){ - x_loc[iSpan] = new su2double[nTotVertex_gb[iSpan]]; - y_loc[iSpan] = new su2double[nTotVertex_gb[iSpan]]; - z_loc[iSpan] = new su2double[nTotVertex_gb[iSpan]]; - angCoord_loc[iSpan] = new su2double[nTotVertex_gb[iSpan]]; + for (iSpan = 0; iSpan < nSpanWiseSections[marker_flag - 1]; iSpan++) { + x_loc[iSpan] = new su2double[nTotVertex_gb[iSpan]]; + y_loc[iSpan] = new su2double[nTotVertex_gb[iSpan]]; + z_loc[iSpan] = new su2double[nTotVertex_gb[iSpan]]; + angCoord_loc[iSpan] = new su2double[nTotVertex_gb[iSpan]]; deltaAngCoord_loc[iSpan] = new su2double[nTotVertex_gb[iSpan]]; - rank_loc[iSpan] = new int[nTotVertex_gb[iSpan]]; - for(iSpanVertex = 0; iSpanVertexGetnMarker_Turbomachinery()+1; iMarkerTP++){ - if (config->GetMarker_All_Turbomachinery(iMarker) == iMarkerTP){ - if (config->GetMarker_All_TurbomachineryFlag(iMarker) == marker_flag){ - for(iSpan = 0; iSpan < nSpanWiseSections[marker_flag-1]; iSpan++){ - for(iSpanVertex = 0; iSpanVertexGetnMarker_Turbomachinery() + 1; iMarkerTP++) { + if (config->GetMarker_All_Turbomachinery(iMarker) == iMarkerTP) { + if (config->GetMarker_All_TurbomachineryFlag(iMarker) == marker_flag) { + for (iSpan = 0; iSpan < nSpanWiseSections[marker_flag - 1]; iSpan++) { + for (iSpanVertex = 0; iSpanVertex < nVertexSpan[iMarker][iSpan]; iSpanVertex++) { iPoint = turbovertex[iMarker][iSpan][iSpanVertex]->GetNode(); - coord = nodes->GetCoord(iPoint); - x_loc[iSpan][iSpanVertex] = coord[0]; - y_loc[iSpan][iSpanVertex] = coord[1]; - if (nDim == 3){ + coord = nodes->GetCoord(iPoint); + x_loc[iSpan][iSpanVertex] = coord[0]; + y_loc[iSpan][iSpanVertex] = coord[1]; + if (nDim == 3) { z_loc[iSpan][iSpanVertex] = coord[2]; - } - else{ + } else { z_loc[iSpan][iSpanVertex] = 0.0; } - angCoord_loc[iSpan][iSpanVertex] = turbovertex[iMarker][iSpan][iSpanVertex]->GetRelAngularCoord(); + angCoord_loc[iSpan][iSpanVertex] = turbovertex[iMarker][iSpan][iSpanVertex]->GetRelAngularCoord(); deltaAngCoord_loc[iSpan][iSpanVertex] = turbovertex[iMarker][iSpan][iSpanVertex]->GetDeltaAngularCoord(); } } @@ -5907,283 +5572,301 @@ void CPhysicalGeometry::SetTurboVertex(CConfig *config, unsigned short val_iZone #ifdef HAVE_MPI - for(iSpan = 0; iSpan < nSpanWiseSections[marker_flag-1]; iSpan++){ - if (rank == MASTER_NODE){ - x_gb = new su2double[nTotVertex_gb[iSpan]*size]; - y_gb = new su2double[nTotVertex_gb[iSpan]*size]; - z_gb = new su2double[nTotVertex_gb[iSpan]*size]; - angCoord_gb = new su2double[nTotVertex_gb[iSpan]*size]; - deltaAngCoord_gb = new su2double[nTotVertex_gb[iSpan]*size]; - checkAssign_gb = new bool[nTotVertex_gb[iSpan]*size]; - - for(iSize= 0; iSize < size; iSize++){ - for(iSpanVertex = 0; iSpanVertex < nTotVertex_gb[iSpan]; iSpanVertex++){ - checkAssign_gb[iSize*nTotVertex_gb[iSpan] + iSpanVertex] = false; - } - } - } - SU2_MPI::Gather(y_loc[iSpan], nTotVertex_gb[iSpan] , MPI_DOUBLE, y_gb, nTotVertex_gb[iSpan], MPI_DOUBLE, MASTER_NODE, SU2_MPI::GetComm()); - SU2_MPI::Gather(x_loc[iSpan], nTotVertex_gb[iSpan] , MPI_DOUBLE, x_gb, nTotVertex_gb[iSpan], MPI_DOUBLE, MASTER_NODE, SU2_MPI::GetComm()); - SU2_MPI::Gather(z_loc[iSpan], nTotVertex_gb[iSpan] , MPI_DOUBLE, z_gb, nTotVertex_gb[iSpan], MPI_DOUBLE, MASTER_NODE, SU2_MPI::GetComm()); - SU2_MPI::Gather(angCoord_loc[iSpan], nTotVertex_gb[iSpan] , MPI_DOUBLE, angCoord_gb, nTotVertex_gb[iSpan], MPI_DOUBLE, MASTER_NODE, SU2_MPI::GetComm()); - SU2_MPI::Gather(deltaAngCoord_loc[iSpan], nTotVertex_gb[iSpan] , MPI_DOUBLE, deltaAngCoord_gb, nTotVertex_gb[iSpan], MPI_DOUBLE, MASTER_NODE, SU2_MPI::GetComm()); - - if (rank == MASTER_NODE){ - for(iSpanVertex = 0; iSpanVertex= 0.0){ + for (iSize = 0; iSize < size; iSize++) { + if (angCoord_gb[iSize * nTotVertex_gb[iSpan]] < min && angCoord_gb[iSize * nTotVertex_gb[iSpan]] >= 0.0) { kSize = iSize; - min = angCoord_gb[iSize*nTotVertex_gb[iSpan]]; + min = angCoord_gb[iSize * nTotVertex_gb[iSpan]]; } } kSpanVertex = 0; - for(iSpanVertex = 0; iSpanVertex < nTotVertex_gb[iSpan]; iSpanVertex++){ - x_loc[iSpan][iSpanVertex] = x_gb[kSize*nTotVertex_gb[iSpan] + kSpanVertex]; - y_loc[iSpan][iSpanVertex] = y_gb[kSize*nTotVertex_gb[iSpan] + kSpanVertex]; - z_loc[iSpan][iSpanVertex] = z_gb[kSize*nTotVertex_gb[iSpan] + kSpanVertex]; - angCoord_loc[iSpan][iSpanVertex] = angCoord_gb[kSize*nTotVertex_gb[iSpan] + kSpanVertex]; - deltaAngCoord_loc[iSpan][iSpanVertex] = deltaAngCoord_gb[kSize*nTotVertex_gb[iSpan] + kSpanVertex]; - rank_loc[iSpan][iSpanVertex] = kSize; + for (iSpanVertex = 0; iSpanVertex < nTotVertex_gb[iSpan]; iSpanVertex++) { + x_loc[iSpan][iSpanVertex] = x_gb[kSize * nTotVertex_gb[iSpan] + kSpanVertex]; + y_loc[iSpan][iSpanVertex] = y_gb[kSize * nTotVertex_gb[iSpan] + kSpanVertex]; + z_loc[iSpan][iSpanVertex] = z_gb[kSize * nTotVertex_gb[iSpan] + kSpanVertex]; + angCoord_loc[iSpan][iSpanVertex] = angCoord_gb[kSize * nTotVertex_gb[iSpan] + kSpanVertex]; + deltaAngCoord_loc[iSpan][iSpanVertex] = deltaAngCoord_gb[kSize * nTotVertex_gb[iSpan] + kSpanVertex]; + rank_loc[iSpan][iSpanVertex] = kSize; target = angCoord_loc[iSpan][iSpanVertex]; - checkAssign_gb[kSize*nTotVertex_gb[iSpan] + kSpanVertex] = true; + checkAssign_gb[kSize * nTotVertex_gb[iSpan] + kSpanVertex] = true; min = 10.0E+06; - for(jSize= 0; jSize < size; jSize++){ - for(jSpanVertex = 0; jSpanVertex < nTotVertex_gb[iSpan]; jSpanVertex++){ - if ((angCoord_gb[jSize*nTotVertex_gb[iSpan] + jSpanVertex] < min) && - (angCoord_gb[jSize*nTotVertex_gb[iSpan] + jSpanVertex] >= target) && - !checkAssign_gb[jSize*nTotVertex_gb[iSpan] + jSpanVertex]) { + for (jSize = 0; jSize < size; jSize++) { + for (jSpanVertex = 0; jSpanVertex < nTotVertex_gb[iSpan]; jSpanVertex++) { + if ((angCoord_gb[jSize * nTotVertex_gb[iSpan] + jSpanVertex] < min) && + (angCoord_gb[jSize * nTotVertex_gb[iSpan] + jSpanVertex] >= target) && + !checkAssign_gb[jSize * nTotVertex_gb[iSpan] + jSpanVertex]) { kSize = jSize; kSpanVertex = jSpanVertex; - min = angCoord_gb[jSize*nTotVertex_gb[iSpan] + jSpanVertex]; + min = angCoord_gb[jSize * nTotVertex_gb[iSpan] + jSpanVertex]; } } } } - delete [] x_gb; delete [] y_gb; delete [] z_gb; delete [] angCoord_gb; delete [] deltaAngCoord_gb; delete[] checkAssign_gb; - + delete[] x_gb; + delete[] y_gb; + delete[] z_gb; + delete[] angCoord_gb; + delete[] deltaAngCoord_gb; + delete[] checkAssign_gb; } } #endif - if (rank == MASTER_NODE){ - if (marker_flag == INFLOW && val_iZone ==0){ + if (rank == MASTER_NODE) { + if (marker_flag == INFLOW && val_iZone == 0) { std::string sPath = "TURBOMACHINERY"; int nError = 0; #if defined(_WIN32) #ifdef __MINGW32__ nError = mkdir(sPath.c_str()); // MINGW on Windows #else - nError = _mkdir(sPath.c_str()); // can be used on Windows + nError = _mkdir(sPath.c_str()); // can be used on Windows #endif #else - mode_t nMode = 0733; // UNIX style permissions - nError = mkdir(sPath.c_str(),nMode); // can be used on non-Windows + mode_t nMode = 0733; // UNIX style permissions + nError = mkdir(sPath.c_str(), nMode); // can be used on non-Windows #endif if (nError != 0) { - cout << "TURBOMACHINERY folder creation failed." < 1){ + if (GetnZone() > 1) { unsigned short lastindex = multizone_filename.find_last_of("."); multizone_filename = multizone_filename.substr(0, lastindex); - SPRINTF (buffer, "_%d.dat", SU2_TYPE::Int(val_iZone)); + SPRINTF(buffer, "_%d.dat", SU2_TYPE::Int(val_iZone)); multizone_filename.append(string(buffer)); } // File to print the vector x_loc, y_loc, z_loc, globIdx_loc to check vertex ordering ofstream myfile; - myfile.open (multizone_filename.data(), ios::out | ios::trunc); + myfile.open(multizone_filename.data(), ios::out | ios::trunc); myfile.setf(ios::uppercase | ios::scientific); myfile.precision(8); myfile << "TITLE = \"Global index visualization file\"" << endl; myfile << "VARIABLES =" << endl; - myfile.width(10); myfile << "\"iSpan\""; - myfile.width(20); myfile << "\"x_coord\"" ; - myfile.width(20); myfile << "\"y_coord\"" ; - myfile.width(20); myfile << "\"z_coord\"" ; - myfile.width(20); myfile << "\"radius\"" ; - myfile.width(20); myfile << "\"Relative Angular Coord \"" ; - myfile.width(20); myfile << "\"Delta Angular Coord \"" ; - myfile.width(20); myfile << "\"processor\"" <GetKind_TurboMachinery(val_iZone)){ - myfile.width(20); myfile << angCoord_loc[iSpan][iSpanVertex]; - myfile.width(20); myfile << deltaAngCoord_loc[iSpan][iSpanVertex]; + myfile.width(10); + myfile << "\"iSpan\""; + myfile.width(20); + myfile << "\"x_coord\""; + myfile.width(20); + myfile << "\"y_coord\""; + myfile.width(20); + myfile << "\"z_coord\""; + myfile.width(20); + myfile << "\"radius\""; + myfile.width(20); + myfile << "\"Relative Angular Coord \""; + myfile.width(20); + myfile << "\"Delta Angular Coord \""; + myfile.width(20); + myfile << "\"processor\"" << endl; + for (iSpan = 0; iSpan < nSpanWiseSections[marker_flag - 1]; iSpan++) { + for (iSpanVertex = 0; iSpanVertex < nTotVertex_gb[iSpan]; iSpanVertex++) { + radius = sqrt(x_loc[iSpan][iSpanVertex] * x_loc[iSpan][iSpanVertex] + + y_loc[iSpan][iSpanVertex] * y_loc[iSpan][iSpanVertex]); + myfile.width(10); + myfile << iSpan; + myfile.width(20); + myfile << x_loc[iSpan][iSpanVertex]; + myfile.width(20); + myfile << y_loc[iSpan][iSpanVertex]; + myfile.width(20); + myfile << z_loc[iSpan][iSpanVertex]; + myfile.width(20); + myfile << radius; + if (nDim == 2 && config->GetKind_TurboMachinery(val_iZone)) { + myfile.width(20); + myfile << angCoord_loc[iSpan][iSpanVertex]; + myfile.width(20); + myfile << deltaAngCoord_loc[iSpan][iSpanVertex]; + } else { + myfile.width(20); + myfile << angCoord_loc[iSpan][iSpanVertex] * 180.0 / PI_NUMBER; + myfile.width(20); + myfile << deltaAngCoord_loc[iSpan][iSpanVertex] * 180.0 / PI_NUMBER; } - else{ - myfile.width(20); myfile << angCoord_loc[iSpan][iSpanVertex]*180.0/PI_NUMBER; - myfile.width(20); myfile << deltaAngCoord_loc[iSpan][iSpanVertex]*180.0/PI_NUMBER; - } - myfile.width(20); myfile << rank_loc[iSpan][iSpanVertex]<GetnMarker_Turbomachinery()+1; iMarkerTP++){ - if (config->GetMarker_All_Turbomachinery(iMarker) == iMarkerTP){ - if (config->GetMarker_All_TurbomachineryFlag(iMarker) == marker_flag){ - for(iSpan = 0; iSpan < nSpanWiseSections[marker_flag-1]; iSpan++){ - for(iSpanVertex = 0; iSpanVertexGetnMarker_Turbomachinery() + 1; iMarkerTP++) { + if (config->GetMarker_All_Turbomachinery(iMarker) == iMarkerTP) { + if (config->GetMarker_All_TurbomachineryFlag(iMarker) == marker_flag) { + for (iSpan = 0; iSpan < nSpanWiseSections[marker_flag - 1]; iSpan++) { + for (iSpanVertex = 0; iSpanVertex < nVertexSpan[iMarker][iSpan]; iSpanVertex++) { iPoint = turbovertex[iMarker][iSpan][iSpanVertex]->GetNode(); - coord = nodes->GetCoord(iPoint); + coord = nodes->GetCoord(iPoint); /*--- compute appropriate turbo normal ---*/ - switch (config->GetKind_TurboMachinery(val_iZone)){ - case CENTRIFUGAL: - Normal2 = 0.0; - for(iDim = 0; iDim < 2; iDim++) Normal2 +=coord[iDim]*coord[iDim]; - if (marker_flag == INFLOW){ - TurboNormal[0] = -coord[0]/sqrt(Normal2); - TurboNormal[1] = -coord[1]/sqrt(Normal2); - TurboNormal[2] = 0.0; - }else{ - TurboNormal[0] = coord[0]/sqrt(Normal2); - TurboNormal[1] = coord[1]/sqrt(Normal2); - TurboNormal[2] = 0.0; - } - break; - case CENTRIPETAL: - Normal2 = 0.0; - for(iDim = 0; iDim < 2; iDim++) Normal2 +=coord[iDim]*coord[iDim]; - if (marker_flag == OUTFLOW){ - TurboNormal[0] = -coord[0]/sqrt(Normal2); - TurboNormal[1] = -coord[1]/sqrt(Normal2); - TurboNormal[2] = 0.0; - }else{ - TurboNormal[0] = coord[0]/sqrt(Normal2); - TurboNormal[1] = coord[1]/sqrt(Normal2); - TurboNormal[2] = 0.0; - } - break; - case AXIAL: - Normal2 = 0.0; - for(iDim = 0; iDim < 2; iDim++) Normal2 +=coord[iDim]*coord[iDim]; - if(nDim == 3){ - if (marker_flag == INFLOW){ - TurboNormal[0] = coord[0]/sqrt(Normal2); - TurboNormal[1] = coord[1]/sqrt(Normal2); + switch (config->GetKind_TurboMachinery(val_iZone)) { + case CENTRIFUGAL: + Normal2 = 0.0; + for (iDim = 0; iDim < 2; iDim++) Normal2 += coord[iDim] * coord[iDim]; + if (marker_flag == INFLOW) { + TurboNormal[0] = -coord[0] / sqrt(Normal2); + TurboNormal[1] = -coord[1] / sqrt(Normal2); TurboNormal[2] = 0.0; - }else{ - TurboNormal[0] = coord[0]/sqrt(Normal2); - TurboNormal[1] = coord[1]/sqrt(Normal2); + } else { + TurboNormal[0] = coord[0] / sqrt(Normal2); + TurboNormal[1] = coord[1] / sqrt(Normal2); TurboNormal[2] = 0.0; } - } - else{ - if (marker_flag == INFLOW){ - TurboNormal[0] = -1.0; - TurboNormal[1] = 0.0; + break; + case CENTRIPETAL: + Normal2 = 0.0; + for (iDim = 0; iDim < 2; iDim++) Normal2 += coord[iDim] * coord[iDim]; + if (marker_flag == OUTFLOW) { + TurboNormal[0] = -coord[0] / sqrt(Normal2); + TurboNormal[1] = -coord[1] / sqrt(Normal2); TurboNormal[2] = 0.0; - }else{ - TurboNormal[0] = 1.0; - TurboNormal[1] = 0.0; + } else { + TurboNormal[0] = coord[0] / sqrt(Normal2); + TurboNormal[1] = coord[1] / sqrt(Normal2); TurboNormal[2] = 0.0; } - } + break; + case AXIAL: + Normal2 = 0.0; + for (iDim = 0; iDim < 2; iDim++) Normal2 += coord[iDim] * coord[iDim]; + if (nDim == 3) { + if (marker_flag == INFLOW) { + TurboNormal[0] = coord[0] / sqrt(Normal2); + TurboNormal[1] = coord[1] / sqrt(Normal2); + TurboNormal[2] = 0.0; + } else { + TurboNormal[0] = coord[0] / sqrt(Normal2); + TurboNormal[1] = coord[1] / sqrt(Normal2); + TurboNormal[2] = 0.0; + } + } else { + if (marker_flag == INFLOW) { + TurboNormal[0] = -1.0; + TurboNormal[1] = 0.0; + TurboNormal[2] = 0.0; + } else { + TurboNormal[0] = 1.0; + TurboNormal[1] = 0.0; + TurboNormal[2] = 0.0; + } + } - break; - case CENTRIPETAL_AXIAL: - Normal2 = 0.0; - for(iDim = 0; iDim < 2; iDim++) Normal2 +=coord[iDim]*coord[iDim]; - if (marker_flag == INFLOW){ - TurboNormal[0] = coord[0]/sqrt(Normal2); - TurboNormal[1] = coord[1]/sqrt(Normal2); - TurboNormal[2] = 0.0; - }else{ - TurboNormal[0] = coord[0]/sqrt(Normal2); - TurboNormal[1] = coord[1]/sqrt(Normal2); - TurboNormal[2] = 0.0; - } - break; - - case AXIAL_CENTRIFUGAL: - Normal2 = 0.0; - for(iDim = 0; iDim < 2; iDim++) Normal2 +=coord[iDim]*coord[iDim]; - if (marker_flag == INFLOW){ - TurboNormal[0] = coord[0]/sqrt(Normal2); - TurboNormal[1] = coord[1]/sqrt(Normal2); - TurboNormal[2] = 0.0; - }else{ - TurboNormal[0] = coord[0]/sqrt(Normal2); - TurboNormal[1] = coord[1]/sqrt(Normal2); - TurboNormal[2] = 0.0; - } - break; + break; + case CENTRIPETAL_AXIAL: + Normal2 = 0.0; + for (iDim = 0; iDim < 2; iDim++) Normal2 += coord[iDim] * coord[iDim]; + if (marker_flag == INFLOW) { + TurboNormal[0] = coord[0] / sqrt(Normal2); + TurboNormal[1] = coord[1] / sqrt(Normal2); + TurboNormal[2] = 0.0; + } else { + TurboNormal[0] = coord[0] / sqrt(Normal2); + TurboNormal[1] = coord[1] / sqrt(Normal2); + TurboNormal[2] = 0.0; + } + break; + + case AXIAL_CENTRIFUGAL: + Normal2 = 0.0; + for (iDim = 0; iDim < 2; iDim++) Normal2 += coord[iDim] * coord[iDim]; + if (marker_flag == INFLOW) { + TurboNormal[0] = coord[0] / sqrt(Normal2); + TurboNormal[1] = coord[1] / sqrt(Normal2); + TurboNormal[2] = 0.0; + } else { + TurboNormal[0] = coord[0] / sqrt(Normal2); + TurboNormal[1] = coord[1] / sqrt(Normal2); + TurboNormal[2] = 0.0; + } + break; } /*--- store the new turbo normal ---*/ @@ -6195,54 +5878,54 @@ void CPhysicalGeometry::UpdateTurboVertex(CConfig *config, unsigned short val_iZ } } - delete [] TurboNormal; + delete[] TurboNormal; } -void CPhysicalGeometry::SetAvgTurboValue(CConfig *config, unsigned short val_iZone, unsigned short marker_flag, bool allocate) { - +void CPhysicalGeometry::SetAvgTurboValue(CConfig* config, unsigned short val_iZone, unsigned short marker_flag, + bool allocate) { unsigned short iMarker, iMarkerTP, iSpan, iDim; unsigned long iPoint; - su2double *TurboNormal,*coord, *Normal, turboNormal2, Normal2, *gridVel, TotalArea, TotalRadius, radius; - su2double *TotalTurboNormal,*TotalNormal, *TotalGridVel, Area; + su2double *TurboNormal, *coord, *Normal, turboNormal2, Normal2, *gridVel, TotalArea, TotalRadius, radius; + su2double *TotalTurboNormal, *TotalNormal, *TotalGridVel, Area; long iVertex; /*-- Variables declaration and allocation ---*/ TotalTurboNormal = new su2double[nDim]; - TotalNormal = new su2double[nDim]; - TurboNormal = new su2double[nDim]; - TotalGridVel = new su2double[nDim]; - Normal = new su2double[nDim]; + TotalNormal = new su2double[nDim]; + TurboNormal = new su2double[nDim]; + TotalGridVel = new su2double[nDim]; + Normal = new su2double[nDim]; - bool grid_movement = config->GetGrid_Movement(); + bool grid_movement = config->GetGrid_Movement(); #ifdef HAVE_MPI - su2double MyTotalArea, MyTotalRadius, *MyTotalTurboNormal= NULL, *MyTotalNormal= NULL, *MyTotalGridVel= NULL; + su2double MyTotalArea, MyTotalRadius, *MyTotalTurboNormal = NULL, *MyTotalNormal = NULL, *MyTotalGridVel = NULL; #endif /*--- Intialization of the vector for the interested boundary ---*/ - for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++){ - for (iMarkerTP=1; iMarkerTP < config->GetnMarker_Turbomachinery()+1; iMarkerTP++){ - if (config->GetMarker_All_Turbomachinery(iMarker) == iMarkerTP){ - if (config->GetMarker_All_TurbomachineryFlag(iMarker) == marker_flag){ - if(allocate){ - AverageTurboNormal[iMarker] = new su2double *[nSpanWiseSections[marker_flag-1] + 1]; - AverageNormal[iMarker] = new su2double *[nSpanWiseSections[marker_flag-1] + 1]; - AverageGridVel[iMarker] = new su2double *[nSpanWiseSections[marker_flag-1] + 1]; - AverageTangGridVel[iMarker] = new su2double [nSpanWiseSections[marker_flag-1] + 1]; - SpanArea[iMarker] = new su2double [nSpanWiseSections[marker_flag-1] + 1]; - TurboRadius[iMarker] = new su2double [nSpanWiseSections[marker_flag-1] + 1]; - for (iSpan= 0; iSpan < nSpanWiseSections[marker_flag-1] + 1; iSpan++){ - AverageTurboNormal[iMarker][iSpan] = new su2double [nDim]; - AverageNormal[iMarker][iSpan] = new su2double [nDim]; - AverageGridVel[iMarker][iSpan] = new su2double [nDim]; + for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { + for (iMarkerTP = 1; iMarkerTP < config->GetnMarker_Turbomachinery() + 1; iMarkerTP++) { + if (config->GetMarker_All_Turbomachinery(iMarker) == iMarkerTP) { + if (config->GetMarker_All_TurbomachineryFlag(iMarker) == marker_flag) { + if (allocate) { + AverageTurboNormal[iMarker] = new su2double*[nSpanWiseSections[marker_flag - 1] + 1]; + AverageNormal[iMarker] = new su2double*[nSpanWiseSections[marker_flag - 1] + 1]; + AverageGridVel[iMarker] = new su2double*[nSpanWiseSections[marker_flag - 1] + 1]; + AverageTangGridVel[iMarker] = new su2double[nSpanWiseSections[marker_flag - 1] + 1]; + SpanArea[iMarker] = new su2double[nSpanWiseSections[marker_flag - 1] + 1]; + TurboRadius[iMarker] = new su2double[nSpanWiseSections[marker_flag - 1] + 1]; + for (iSpan = 0; iSpan < nSpanWiseSections[marker_flag - 1] + 1; iSpan++) { + AverageTurboNormal[iMarker][iSpan] = new su2double[nDim]; + AverageNormal[iMarker][iSpan] = new su2double[nDim]; + AverageGridVel[iMarker][iSpan] = new su2double[nDim]; } } - for (iSpan= 0; iSpan < nSpanWiseSections[marker_flag-1] + 1; iSpan++){ - AverageTangGridVel[iMarker][iSpan] = 0.0; - SpanArea[iMarker][iSpan] = 0.0; - TurboRadius[iMarker][iSpan] = 0.0; - for(iDim=0; iDim < nDim; iDim++){ - AverageTurboNormal[iMarker][iSpan][iDim] = 0.0; - AverageNormal[iMarker][iSpan][iDim] = 0.0; - AverageGridVel[iMarker][iSpan][iDim] = 0.0; + for (iSpan = 0; iSpan < nSpanWiseSections[marker_flag - 1] + 1; iSpan++) { + AverageTangGridVel[iMarker][iSpan] = 0.0; + SpanArea[iMarker][iSpan] = 0.0; + TurboRadius[iMarker][iSpan] = 0.0; + for (iDim = 0; iDim < nDim; iDim++) { + AverageTurboNormal[iMarker][iSpan][iDim] = 0.0; + AverageNormal[iMarker][iSpan][iDim] = 0.0; + AverageGridVel[iMarker][iSpan][iDim] = 0.0; } } } @@ -6250,45 +5933,41 @@ void CPhysicalGeometry::SetAvgTurboValue(CConfig *config, unsigned short val_iZo } } - - /*--- start computing the average quantities span wise --- */ - for (iSpan= 0; iSpan < nSpanWiseSections[marker_flag-1]; iSpan++){ - + for (iSpan = 0; iSpan < nSpanWiseSections[marker_flag - 1]; iSpan++) { /*--- Forces initialization for contenitors to zero ---*/ - for (iDim=0; iDimGetnMarker_All(); iMarker++){ - for (iMarkerTP=1; iMarkerTP < config->GetnMarker_Turbomachinery()+1; iMarkerTP++){ - if (config->GetMarker_All_Turbomachinery(iMarker) == iMarkerTP){ - if (config->GetMarker_All_TurbomachineryFlag(iMarker) == marker_flag){ - for(iVertex = 0; iVertex < nVertexSpan[iMarker][iSpan]; iVertex++){ + for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { + for (iMarkerTP = 1; iMarkerTP < config->GetnMarker_Turbomachinery() + 1; iMarkerTP++) { + if (config->GetMarker_All_Turbomachinery(iMarker) == iMarkerTP) { + if (config->GetMarker_All_TurbomachineryFlag(iMarker) == marker_flag) { + for (iVertex = 0; iVertex < nVertexSpan[iMarker][iSpan]; iVertex++) { iPoint = turbovertex[iMarker][iSpan][iVertex]->GetNode(); turbovertex[iMarker][iSpan][iVertex]->GetTurboNormal(TurboNormal); turbovertex[iMarker][iSpan][iVertex]->GetNormal(Normal); - coord = nodes->GetCoord(iPoint); + coord = nodes->GetCoord(iPoint); - if (nDim == 3){ - radius = sqrt(coord[0]*coord[0] + coord[1]*coord[1]); - } - else{ + if (nDim == 3) { + radius = sqrt(coord[0] * coord[0] + coord[1] * coord[1]); + } else { radius = 0.0; } Area = turbovertex[iMarker][iSpan][iVertex]->GetArea(); - TotalArea += Area; + TotalArea += Area; TotalRadius += radius; for (iDim = 0; iDim < nDim; iDim++) { - TotalTurboNormal[iDim] +=TurboNormal[iDim]; - TotalNormal[iDim] +=Normal[iDim]; + TotalTurboNormal[iDim] += TurboNormal[iDim]; + TotalNormal[iDim] += Normal[iDim]; } - if (grid_movement){ + if (grid_movement) { gridVel = nodes->GetGridVel(iPoint); - for (iDim = 0; iDim < nDim; iDim++) TotalGridVel[iDim] +=gridVel[iDim]; + for (iDim = 0; iDim < nDim; iDim++) TotalGridVel[iDim] += gridVel[iDim]; } } } @@ -6298,104 +5977,120 @@ void CPhysicalGeometry::SetAvgTurboValue(CConfig *config, unsigned short val_iZo #ifdef HAVE_MPI - MyTotalArea = TotalArea; TotalArea = 0; - MyTotalRadius = TotalRadius; TotalRadius = 0; + MyTotalArea = TotalArea; + TotalArea = 0; + MyTotalRadius = TotalRadius; + TotalRadius = 0; SU2_MPI::Allreduce(&MyTotalArea, &TotalArea, 1, MPI_DOUBLE, MPI_SUM, SU2_MPI::GetComm()); SU2_MPI::Allreduce(&MyTotalRadius, &TotalRadius, 1, MPI_DOUBLE, MPI_SUM, SU2_MPI::GetComm()); - MyTotalTurboNormal = new su2double[nDim]; - MyTotalNormal = new su2double[nDim]; - MyTotalGridVel = new su2double[nDim]; + MyTotalTurboNormal = new su2double[nDim]; + MyTotalNormal = new su2double[nDim]; + MyTotalGridVel = new su2double[nDim]; for (iDim = 0; iDim < nDim; iDim++) { - MyTotalTurboNormal[iDim] = TotalTurboNormal[iDim]; - TotalTurboNormal[iDim] = 0.0; - MyTotalNormal[iDim] = TotalNormal[iDim]; - TotalNormal[iDim] = 0.0; - MyTotalGridVel[iDim] = TotalGridVel[iDim]; - TotalGridVel[iDim] = 0.0; + MyTotalTurboNormal[iDim] = TotalTurboNormal[iDim]; + TotalTurboNormal[iDim] = 0.0; + MyTotalNormal[iDim] = TotalNormal[iDim]; + TotalNormal[iDim] = 0.0; + MyTotalGridVel[iDim] = TotalGridVel[iDim]; + TotalGridVel[iDim] = 0.0; } SU2_MPI::Allreduce(MyTotalTurboNormal, TotalTurboNormal, nDim, MPI_DOUBLE, MPI_SUM, SU2_MPI::GetComm()); SU2_MPI::Allreduce(MyTotalNormal, TotalNormal, nDim, MPI_DOUBLE, MPI_SUM, SU2_MPI::GetComm()); SU2_MPI::Allreduce(MyTotalGridVel, TotalGridVel, nDim, MPI_DOUBLE, MPI_SUM, SU2_MPI::GetComm()); - delete [] MyTotalTurboNormal;delete [] MyTotalNormal; delete [] MyTotalGridVel; + delete[] MyTotalTurboNormal; + delete[] MyTotalNormal; + delete[] MyTotalGridVel; #endif - for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++){ - for (iMarkerTP=1; iMarkerTP < config->GetnMarker_Turbomachinery()+1; iMarkerTP++){ - if (config->GetMarker_All_Turbomachinery(iMarker) == iMarkerTP){ - if (config->GetMarker_All_TurbomachineryFlag(iMarker) == marker_flag){ - - - SpanArea[iMarker][iSpan] = TotalArea; - TurboRadius[iMarker][iSpan] = TotalRadius/nTotVertexSpan[iMarker][iSpan]; - - turboNormal2 = 0.0; - Normal2 = 0.0; - for (iDim = 0; iDim < nDim; iDim++){ - turboNormal2 += TotalTurboNormal[iDim]*TotalTurboNormal[iDim]; - Normal2 += TotalNormal[iDim]*TotalNormal[iDim]; + for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { + for (iMarkerTP = 1; iMarkerTP < config->GetnMarker_Turbomachinery() + 1; iMarkerTP++) { + if (config->GetMarker_All_Turbomachinery(iMarker) == iMarkerTP) { + if (config->GetMarker_All_TurbomachineryFlag(iMarker) == marker_flag) { + SpanArea[iMarker][iSpan] = TotalArea; + TurboRadius[iMarker][iSpan] = TotalRadius / nTotVertexSpan[iMarker][iSpan]; + + turboNormal2 = 0.0; + Normal2 = 0.0; + for (iDim = 0; iDim < nDim; iDim++) { + turboNormal2 += TotalTurboNormal[iDim] * TotalTurboNormal[iDim]; + Normal2 += TotalNormal[iDim] * TotalNormal[iDim]; } - for (iDim = 0; iDim < nDim; iDim++){ - AverageTurboNormal[iMarker][iSpan][iDim] = TotalTurboNormal[iDim]/sqrt(turboNormal2); - AverageNormal[iMarker][iSpan][iDim] = TotalNormal[iDim]/sqrt(Normal2); + for (iDim = 0; iDim < nDim; iDim++) { + AverageTurboNormal[iMarker][iSpan][iDim] = TotalTurboNormal[iDim] / sqrt(turboNormal2); + AverageNormal[iMarker][iSpan][iDim] = TotalNormal[iDim] / sqrt(Normal2); } - if (grid_movement){ - for (iDim = 0; iDim < nDim; iDim++){ - AverageGridVel[iMarker][iSpan][iDim] =TotalGridVel[iDim]/nTotVertexSpan[iMarker][iSpan]; + if (grid_movement) { + for (iDim = 0; iDim < nDim; iDim++) { + AverageGridVel[iMarker][iSpan][iDim] = TotalGridVel[iDim] / nTotVertexSpan[iMarker][iSpan]; } - switch (config->GetKind_TurboMachinery(val_iZone)){ - case CENTRIFUGAL:case CENTRIPETAL: - if (marker_flag == INFLOW ){ - AverageTangGridVel[iMarker][iSpan]= -(AverageTurboNormal[iMarker][iSpan][0]*AverageGridVel[iMarker][iSpan][1]-AverageTurboNormal[iMarker][iSpan][1]*AverageGridVel[iMarker][iSpan][0]); - } - else{ - AverageTangGridVel[iMarker][iSpan]= AverageTurboNormal[iMarker][iSpan][0]*AverageGridVel[iMarker][iSpan][1]-AverageTurboNormal[iMarker][iSpan][1]*AverageGridVel[iMarker][iSpan][0]; - } - break; - case AXIAL: - if (marker_flag == INFLOW && nDim == 2){ - AverageTangGridVel[iMarker][iSpan]= -AverageTurboNormal[iMarker][iSpan][0]*AverageGridVel[iMarker][iSpan][1] + AverageTurboNormal[iMarker][iSpan][1]*AverageGridVel[iMarker][iSpan][0]; - } - else{ - AverageTangGridVel[iMarker][iSpan]= AverageTurboNormal[iMarker][iSpan][0]*AverageGridVel[iMarker][iSpan][1]-AverageTurboNormal[iMarker][iSpan][1]*AverageGridVel[iMarker][iSpan][0]; - } + switch (config->GetKind_TurboMachinery(val_iZone)) { + case CENTRIFUGAL: + case CENTRIPETAL: + if (marker_flag == INFLOW) { + AverageTangGridVel[iMarker][iSpan] = + -(AverageTurboNormal[iMarker][iSpan][0] * AverageGridVel[iMarker][iSpan][1] - + AverageTurboNormal[iMarker][iSpan][1] * AverageGridVel[iMarker][iSpan][0]); + } else { + AverageTangGridVel[iMarker][iSpan] = + AverageTurboNormal[iMarker][iSpan][0] * AverageGridVel[iMarker][iSpan][1] - + AverageTurboNormal[iMarker][iSpan][1] * AverageGridVel[iMarker][iSpan][0]; + } + break; + case AXIAL: + if (marker_flag == INFLOW && nDim == 2) { + AverageTangGridVel[iMarker][iSpan] = + -AverageTurboNormal[iMarker][iSpan][0] * AverageGridVel[iMarker][iSpan][1] + + AverageTurboNormal[iMarker][iSpan][1] * AverageGridVel[iMarker][iSpan][0]; + } else { + AverageTangGridVel[iMarker][iSpan] = + AverageTurboNormal[iMarker][iSpan][0] * AverageGridVel[iMarker][iSpan][1] - + AverageTurboNormal[iMarker][iSpan][1] * AverageGridVel[iMarker][iSpan][0]; + } + break; + case CENTRIPETAL_AXIAL: + if (marker_flag == OUTFLOW) { + AverageTangGridVel[iMarker][iSpan] = + (AverageTurboNormal[iMarker][iSpan][0] * AverageGridVel[iMarker][iSpan][1] - + AverageTurboNormal[iMarker][iSpan][1] * AverageGridVel[iMarker][iSpan][0]); + } else { + AverageTangGridVel[iMarker][iSpan] = + -(AverageTurboNormal[iMarker][iSpan][0] * AverageGridVel[iMarker][iSpan][1] - + AverageTurboNormal[iMarker][iSpan][1] * AverageGridVel[iMarker][iSpan][0]); + } + break; + case AXIAL_CENTRIFUGAL: + if (marker_flag == INFLOW) { + AverageTangGridVel[iMarker][iSpan] = + AverageTurboNormal[iMarker][iSpan][0] * AverageGridVel[iMarker][iSpan][1] - + AverageTurboNormal[iMarker][iSpan][1] * AverageGridVel[iMarker][iSpan][0]; + } else { + AverageTangGridVel[iMarker][iSpan] = + AverageTurboNormal[iMarker][iSpan][0] * AverageGridVel[iMarker][iSpan][1] - + AverageTurboNormal[iMarker][iSpan][1] * AverageGridVel[iMarker][iSpan][0]; + } break; - case CENTRIPETAL_AXIAL: - if (marker_flag == OUTFLOW){ - AverageTangGridVel[iMarker][iSpan]= (AverageTurboNormal[iMarker][iSpan][0]*AverageGridVel[iMarker][iSpan][1]-AverageTurboNormal[iMarker][iSpan][1]*AverageGridVel[iMarker][iSpan][0]); - } - else{ - AverageTangGridVel[iMarker][iSpan]= -(AverageTurboNormal[iMarker][iSpan][0]*AverageGridVel[iMarker][iSpan][1]-AverageTurboNormal[iMarker][iSpan][1]*AverageGridVel[iMarker][iSpan][0]); - } - break; - case AXIAL_CENTRIFUGAL: - if (marker_flag == INFLOW) - { - AverageTangGridVel[iMarker][iSpan]= AverageTurboNormal[iMarker][iSpan][0]*AverageGridVel[iMarker][iSpan][1]-AverageTurboNormal[iMarker][iSpan][1]*AverageGridVel[iMarker][iSpan][0]; - }else - { - AverageTangGridVel[iMarker][iSpan]= AverageTurboNormal[iMarker][iSpan][0]*AverageGridVel[iMarker][iSpan][1]-AverageTurboNormal[iMarker][iSpan][1]*AverageGridVel[iMarker][iSpan][0]; - } - break; - default: + default: SU2_MPI::Error("Tang grid velocity NOT IMPLEMENTED YET for this configuration", CURRENT_FUNCTION); - break; + break; } } /*--- Compute the 1D average values ---*/ - AverageTangGridVel[iMarker][nSpanWiseSections[marker_flag-1]] += AverageTangGridVel[iMarker][iSpan]/nSpanWiseSections[marker_flag-1]; - SpanArea[iMarker][nSpanWiseSections[marker_flag-1]] += SpanArea[iMarker][iSpan]; - for(iDim=0; iDim < nDim; iDim++){ - AverageTurboNormal[iMarker][nSpanWiseSections[marker_flag-1]][iDim] += AverageTurboNormal[iMarker][iSpan][iDim]; - AverageNormal[iMarker][nSpanWiseSections[marker_flag-1]][iDim] += AverageNormal[iMarker][iSpan][iDim]; - AverageGridVel[iMarker][nSpanWiseSections[marker_flag-1]][iDim] += AverageGridVel[iMarker][iSpan][iDim]/nSpanWiseSections[marker_flag-1]; - + AverageTangGridVel[iMarker][nSpanWiseSections[marker_flag - 1]] += + AverageTangGridVel[iMarker][iSpan] / nSpanWiseSections[marker_flag - 1]; + SpanArea[iMarker][nSpanWiseSections[marker_flag - 1]] += SpanArea[iMarker][iSpan]; + for (iDim = 0; iDim < nDim; iDim++) { + AverageTurboNormal[iMarker][nSpanWiseSections[marker_flag - 1]][iDim] += + AverageTurboNormal[iMarker][iSpan][iDim]; + AverageNormal[iMarker][nSpanWiseSections[marker_flag - 1]][iDim] += AverageNormal[iMarker][iSpan][iDim]; + AverageGridVel[iMarker][nSpanWiseSections[marker_flag - 1]][iDim] += + AverageGridVel[iMarker][iSpan][iDim] / nSpanWiseSections[marker_flag - 1]; } } } @@ -6404,38 +6099,36 @@ void CPhysicalGeometry::SetAvgTurboValue(CConfig *config, unsigned short val_iZo } /*--- Normalize 1D normals---*/ - for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++){ - for (iMarkerTP=1; iMarkerTP < config->GetnMarker_Turbomachinery()+1; iMarkerTP++){ - if (config->GetMarker_All_Turbomachinery(iMarker) == iMarkerTP){ - if (config->GetMarker_All_TurbomachineryFlag(iMarker) == marker_flag){ + for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { + for (iMarkerTP = 1; iMarkerTP < config->GetnMarker_Turbomachinery() + 1; iMarkerTP++) { + if (config->GetMarker_All_Turbomachinery(iMarker) == iMarkerTP) { + if (config->GetMarker_All_TurbomachineryFlag(iMarker) == marker_flag) { turboNormal2 = 0.0; - Normal2 = 0.0; + Normal2 = 0.0; - for (iDim = 0; iDim < nDim; iDim++){ - turboNormal2 += AverageTurboNormal[iMarker][nSpanWiseSections[marker_flag-1]][iDim]*AverageTurboNormal[iMarker][nSpanWiseSections[marker_flag-1]][iDim]; - Normal2 += AverageNormal[iMarker][nSpanWiseSections[marker_flag-1]][iDim]*AverageNormal[iMarker][nSpanWiseSections[marker_flag-1]][iDim]; + for (iDim = 0; iDim < nDim; iDim++) { + turboNormal2 += AverageTurboNormal[iMarker][nSpanWiseSections[marker_flag - 1]][iDim] * + AverageTurboNormal[iMarker][nSpanWiseSections[marker_flag - 1]][iDim]; + Normal2 += AverageNormal[iMarker][nSpanWiseSections[marker_flag - 1]][iDim] * + AverageNormal[iMarker][nSpanWiseSections[marker_flag - 1]][iDim]; } - for (iDim = 0; iDim < nDim; iDim++){ - AverageTurboNormal[iMarker][nSpanWiseSections[marker_flag-1]][iDim] /=sqrt(turboNormal2); - AverageNormal[iMarker][nSpanWiseSections[marker_flag-1]][iDim] /=sqrt(Normal2); + for (iDim = 0; iDim < nDim; iDim++) { + AverageTurboNormal[iMarker][nSpanWiseSections[marker_flag - 1]][iDim] /= sqrt(turboNormal2); + AverageNormal[iMarker][nSpanWiseSections[marker_flag - 1]][iDim] /= sqrt(Normal2); } } } } } - - delete [] TotalTurboNormal; - delete [] TotalNormal; - delete [] TotalGridVel; - delete [] TurboNormal; - delete [] Normal; - + delete[] TotalTurboNormal; + delete[] TotalNormal; + delete[] TotalGridVel; + delete[] TurboNormal; + delete[] Normal; } - -void CPhysicalGeometry::GatherInOutAverageValues(CConfig *config, bool allocate){ - +void CPhysicalGeometry::GatherInOutAverageValues(CConfig* config, bool allocate) { unsigned short iMarker, iMarkerTP; unsigned short iSpan, iDim; int markerTP; @@ -6449,97 +6142,92 @@ void CPhysicalGeometry::GatherInOutAverageValues(CConfig *config, bool allocate) turboNormal = new su2double[nDim]; Pitch = 0.0; - if(allocate){ - for (iMarkerTP=0; iMarkerTP < config->GetnMarker_TurboPerformance(); iMarkerTP++){ - SpanAreaIn[iMarkerTP] = new su2double[config->GetnSpanMaxAllZones() +1]; - TangGridVelIn[iMarkerTP] = new su2double[config->GetnSpanMaxAllZones() +1]; - TurboRadiusIn[iMarkerTP] = new su2double[config->GetnSpanMaxAllZones() +1]; - SpanAreaOut[iMarkerTP] = new su2double[config->GetnSpanMaxAllZones() +1]; - TangGridVelOut[iMarkerTP] = new su2double[config->GetnSpanMaxAllZones() +1]; - TurboRadiusOut[iMarkerTP] = new su2double[config->GetnSpanMaxAllZones() +1]; + if (allocate) { + for (iMarkerTP = 0; iMarkerTP < config->GetnMarker_TurboPerformance(); iMarkerTP++) { + SpanAreaIn[iMarkerTP] = new su2double[config->GetnSpanMaxAllZones() + 1]; + TangGridVelIn[iMarkerTP] = new su2double[config->GetnSpanMaxAllZones() + 1]; + TurboRadiusIn[iMarkerTP] = new su2double[config->GetnSpanMaxAllZones() + 1]; + SpanAreaOut[iMarkerTP] = new su2double[config->GetnSpanMaxAllZones() + 1]; + TangGridVelOut[iMarkerTP] = new su2double[config->GetnSpanMaxAllZones() + 1]; + TurboRadiusOut[iMarkerTP] = new su2double[config->GetnSpanMaxAllZones() + 1]; - for (iSpan= 0; iSpan < config->GetnSpanMaxAllZones() + 1 ; iSpan++){ - SpanAreaIn[iMarkerTP][iSpan] = 0.0; - TangGridVelIn[iMarkerTP][iSpan] = 0.0; - TurboRadiusIn[iMarkerTP][iSpan] = 0.0; - SpanAreaOut[iMarkerTP][iSpan] = 0.0; - TangGridVelOut[iMarkerTP][iSpan] = 0.0; - TurboRadiusOut[iMarkerTP][iSpan] = 0.0; + for (iSpan = 0; iSpan < config->GetnSpanMaxAllZones() + 1; iSpan++) { + SpanAreaIn[iMarkerTP][iSpan] = 0.0; + TangGridVelIn[iMarkerTP][iSpan] = 0.0; + TurboRadiusIn[iMarkerTP][iSpan] = 0.0; + SpanAreaOut[iMarkerTP][iSpan] = 0.0; + TangGridVelOut[iMarkerTP][iSpan] = 0.0; + TurboRadiusOut[iMarkerTP][iSpan] = 0.0; } } } - - - for (iSpan= 0; iSpan < nSpanWiseSections + 1 ; iSpan++){ + for (iSpan = 0; iSpan < nSpanWiseSections + 1; iSpan++) { #ifdef HAVE_MPI - unsigned short i, n1, n2, n1t,n2t; - su2double *TurbGeoIn= NULL,*TurbGeoOut= NULL; - su2double *TotTurbGeoIn = NULL,*TotTurbGeoOut = NULL; - int *TotMarkerTP; - - n1 = 6; - n2 = 3; - n1t = n1*size; - n2t = n2*size; - TurbGeoIn = new su2double[n1]; + unsigned short i, n1, n2, n1t, n2t; + su2double *TurbGeoIn = NULL, *TurbGeoOut = NULL; + su2double *TotTurbGeoIn = NULL, *TotTurbGeoOut = NULL; + int* TotMarkerTP; + + n1 = 6; + n2 = 3; + n1t = n1 * size; + n2t = n2 * size; + TurbGeoIn = new su2double[n1]; TurbGeoOut = new su2double[n2]; - for (i=0;iGetnMarker_All(); iMarker++){ - for (iMarkerTP = 1; iMarkerTP < config->GetnMarker_Turbomachinery()+1; iMarkerTP++){ - if (config->GetMarker_All_Turbomachinery(iMarker) == iMarkerTP){ - if (config->GetMarker_All_TurbomachineryFlag(iMarker) == INFLOW){ - markerTP = iMarkerTP; - if (iSpan < nSpanWiseSections){ - pitchIn = MaxAngularCoord[iMarker][iSpan] - MinAngularCoord[iMarker][iSpan]; + for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { + for (iMarkerTP = 1; iMarkerTP < config->GetnMarker_Turbomachinery() + 1; iMarkerTP++) { + if (config->GetMarker_All_Turbomachinery(iMarker) == iMarkerTP) { + if (config->GetMarker_All_TurbomachineryFlag(iMarker) == INFLOW) { + markerTP = iMarkerTP; + if (iSpan < nSpanWiseSections) { + pitchIn = MaxAngularCoord[iMarker][iSpan] - MinAngularCoord[iMarker][iSpan]; } - areaIn = SpanArea[iMarker][iSpan]; - tangGridVelIn = AverageTangGridVel[iMarker][iSpan]; - radiusIn = TurboRadius[iMarker][iSpan]; - for(iDim = 0; iDim < nDim; iDim++) turboNormal[iDim] = AverageTurboNormal[iMarker][iSpan][iDim]; - + areaIn = SpanArea[iMarker][iSpan]; + tangGridVelIn = AverageTangGridVel[iMarker][iSpan]; + radiusIn = TurboRadius[iMarker][iSpan]; + for (iDim = 0; iDim < nDim; iDim++) turboNormal[iDim] = AverageTurboNormal[iMarker][iSpan][iDim]; #ifdef HAVE_MPI - TurbGeoIn[0] = areaIn; - TurbGeoIn[1] = tangGridVelIn; - TurbGeoIn[2] = radiusIn; - TurbGeoIn[3] = turboNormal[0]; - TurbGeoIn[4] = turboNormal[1]; - TurbGeoIn[5] = pitchIn; + TurbGeoIn[0] = areaIn; + TurbGeoIn[1] = tangGridVelIn; + TurbGeoIn[2] = radiusIn; + TurbGeoIn[3] = turboNormal[0]; + TurbGeoIn[4] = turboNormal[1]; + TurbGeoIn[5] = pitchIn; #endif } /*--- retrieve outlet information ---*/ - if (config->GetMarker_All_TurbomachineryFlag(iMarker) == OUTFLOW){ - if (iSpan < nSpanWiseSections){ - pitchIn = MaxAngularCoord[iMarker][iSpan] - MinAngularCoord[iMarker][iSpan]; + if (config->GetMarker_All_TurbomachineryFlag(iMarker) == OUTFLOW) { + if (iSpan < nSpanWiseSections) { + pitchIn = MaxAngularCoord[iMarker][iSpan] - MinAngularCoord[iMarker][iSpan]; } - areaOut = SpanArea[iMarker][iSpan]; - tangGridVelOut = AverageTangGridVel[iMarker][iSpan]; - radiusOut = TurboRadius[iMarker][iSpan]; + areaOut = SpanArea[iMarker][iSpan]; + tangGridVelOut = AverageTangGridVel[iMarker][iSpan]; + radiusOut = TurboRadius[iMarker][iSpan]; #ifdef HAVE_MPI - TurbGeoOut[0] = areaOut; - TurbGeoOut[1] = tangGridVelOut; - TurbGeoOut[2] = radiusOut; + TurbGeoOut[0] = areaOut; + TurbGeoOut[1] = tangGridVelOut; + TurbGeoOut[2] = radiusOut; #endif } } @@ -6547,89 +6235,83 @@ void CPhysicalGeometry::GatherInOutAverageValues(CConfig *config, bool allocate) } #ifdef HAVE_MPI - TotTurbGeoIn = new su2double[n1t]; - TotTurbGeoOut = new su2double[n2t]; - for (i=0;i 0.0){ - areaIn = 0.0; - areaIn = TotTurbGeoIn[n1*i]; - tangGridVelIn = 0.0; - tangGridVelIn = TotTurbGeoIn[n1*i+1]; - radiusIn = 0.0; - radiusIn = TotTurbGeoIn[n1*i+2]; - turboNormal[0] = 0.0; - turboNormal[0] = TotTurbGeoIn[n1*i+3]; - turboNormal[1] = 0.0; - turboNormal[1] = TotTurbGeoIn[n1*i+4]; - pitchIn = 0.0; - pitchIn = TotTurbGeoIn[n1*i+5]; + for (i = 0; i < size; i++) { + if (TotTurbGeoIn[n1 * i] > 0.0) { + areaIn = 0.0; + areaIn = TotTurbGeoIn[n1 * i]; + tangGridVelIn = 0.0; + tangGridVelIn = TotTurbGeoIn[n1 * i + 1]; + radiusIn = 0.0; + radiusIn = TotTurbGeoIn[n1 * i + 2]; + turboNormal[0] = 0.0; + turboNormal[0] = TotTurbGeoIn[n1 * i + 3]; + turboNormal[1] = 0.0; + turboNormal[1] = TotTurbGeoIn[n1 * i + 4]; + pitchIn = 0.0; + pitchIn = TotTurbGeoIn[n1 * i + 5]; - markerTP = -1; - markerTP = TotMarkerTP[i]; + markerTP = -1; + markerTP = TotMarkerTP[i]; } - if(TotTurbGeoOut[n2*i] > 0.0){ - areaOut = 0.0; - areaOut = TotTurbGeoOut[n2*i]; - tangGridVelOut = 0.0; - tangGridVelOut = TotTurbGeoOut[n2*i+1]; - radiusOut = 0.0; - radiusOut = TotTurbGeoOut[n2*i+2]; + if (TotTurbGeoOut[n2 * i] > 0.0) { + areaOut = 0.0; + areaOut = TotTurbGeoOut[n2 * i]; + tangGridVelOut = 0.0; + tangGridVelOut = TotTurbGeoOut[n2 * i + 1]; + radiusOut = 0.0; + radiusOut = TotTurbGeoOut[n2 * i + 2]; } } - delete [] TotTurbGeoIn, delete [] TotTurbGeoOut; delete [] TotMarkerTP; - + delete[] TotTurbGeoIn, delete[] TotTurbGeoOut; + delete[] TotMarkerTP; #endif - Pitch +=pitchIn/nSpanWiseSections; + Pitch += pitchIn / nSpanWiseSections; if (iSpan == nSpanWiseSections) { config->SetFreeStreamTurboNormal(turboNormal); - if (config->GetKind_TurboMachinery(config->GetiZone()) == AXIAL && nDim == 2){ - nBlades = 1/Pitch; - } - else{ - nBlades = 2*PI_NUMBER/Pitch; + if (config->GetKind_TurboMachinery(config->GetiZone()) == AXIAL && nDim == 2) { + nBlades = 1 / Pitch; + } else { + nBlades = 2 * PI_NUMBER / Pitch; } config->SetnBlades(config->GetiZone(), nBlades); } - if (rank == MASTER_NODE){ + if (rank == MASTER_NODE) { /*----Quantities needed for computing the turbomachinery performance -----*/ - SpanAreaIn[markerTP -1][iSpan] = areaIn; - TangGridVelIn[markerTP -1][iSpan] = tangGridVelIn; - TurboRadiusIn[markerTP -1][iSpan] = radiusIn; + SpanAreaIn[markerTP - 1][iSpan] = areaIn; + TangGridVelIn[markerTP - 1][iSpan] = tangGridVelIn; + TurboRadiusIn[markerTP - 1][iSpan] = radiusIn; - SpanAreaOut[markerTP -1][iSpan] = areaOut; - TangGridVelOut[markerTP -1][iSpan] = tangGridVelOut; - TurboRadiusOut[markerTP -1][iSpan] = radiusOut; + SpanAreaOut[markerTP - 1][iSpan] = areaOut; + TangGridVelOut[markerTP - 1][iSpan] = tangGridVelOut; + TurboRadiusOut[markerTP - 1][iSpan] = radiusOut; } } - delete [] turboNormal; - + delete[] turboNormal; } void CPhysicalGeometry::SetMaxLength(CConfig* config) { - - SU2_OMP_FOR_STAT(roundUpDiv(nPointDomain,omp_get_max_threads())) + SU2_OMP_FOR_STAT(roundUpDiv(nPointDomain, omp_get_max_threads())) for (unsigned long iPoint = 0; iPoint < nPointDomain; iPoint++) { const su2double* Coord_i = nodes->GetCoord(iPoint); @@ -6639,13 +6321,12 @@ void CPhysicalGeometry::SetMaxLength(CConfig* config) { const bool wasActive = AD::BeginPassive(); - su2double max_delta=0; + su2double max_delta = 0; auto max_neighbor = iPoint; for (unsigned short iNeigh = 0; iNeigh < nodes->GetnPoint(iPoint); iNeigh++) { - /*-- Calculate the cell-center to cell-center length ---*/ - const unsigned long jPoint = nodes->GetPoint(iPoint, iNeigh); + const unsigned long jPoint = nodes->GetPoint(iPoint, iNeigh); const su2double* Coord_j = nodes->GetCoord(jPoint); su2double delta = GeometryToolbox::SquaredDistance(nDim, Coord_i, Coord_j); @@ -6669,19 +6350,17 @@ void CPhysicalGeometry::SetMaxLength(CConfig* config) { InitiateComms(this, config, MAX_LENGTH); CompleteComms(this, config, MAX_LENGTH); - } -void CPhysicalGeometry::MatchActuator_Disk(const CConfig *config) { - +void CPhysicalGeometry::MatchActuator_Disk(const CConfig* config) { su2double epsilon = 1e-1; unsigned short nMarker_ActDiskInlet = config->GetnMarker_ActDiskInlet(); if (nMarker_ActDiskInlet != 0) { - unsigned short iMarker, iDim; - unsigned long iVertex, iPoint, iPointGlobal, pPoint = 0, pPointGlobal = 0, pVertex = 0, pMarker = 0, jVertex, jVertex_, jPoint, jPointGlobal, jMarker; + unsigned long iVertex, iPoint, iPointGlobal, pPoint = 0, pPointGlobal = 0, pVertex = 0, pMarker = 0, jVertex, + jVertex_, jPoint, jPointGlobal, jMarker; su2double *Coord_i, Coord_j[3], dist = 0.0, mindist, maxdist_local = 0.0, maxdist_global = 0.0; int iProcessor, pProcessor = 0; unsigned long nLocalVertex_ActDisk = 0, MaxLocalVertex_ActDisk = 0; @@ -6690,12 +6369,17 @@ void CPhysicalGeometry::MatchActuator_Disk(const CConfig *config) { bool Perimeter; for (iBC = 0; iBC < 2; iBC++) { + if (iBC == 0) { + Beneficiary = ACTDISK_INLET; + Donor = ACTDISK_OUTLET; + } + if (iBC == 1) { + Beneficiary = ACTDISK_OUTLET; + Donor = ACTDISK_INLET; + } - if (iBC == 0) { Beneficiary = ACTDISK_INLET; Donor = ACTDISK_OUTLET; } - if (iBC == 1) { Beneficiary = ACTDISK_OUTLET; Donor = ACTDISK_INLET; } - - unsigned long *Buffer_Send_nVertex = new unsigned long [1]; - unsigned long *Buffer_Receive_nVertex = new unsigned long [nProcessor]; + unsigned long* Buffer_Send_nVertex = new unsigned long[1]; + unsigned long* Buffer_Receive_nVertex = new unsigned long[nProcessor]; if ((iBC == 0) && (rank == MASTER_NODE)) cout << "Set Actuator Disk inlet boundary conditions." << endl; if ((iBC == 1) && (rank == MASTER_NODE)) cout << "Set Actuator Disk outlet boundary conditions." << endl; @@ -6708,7 +6392,7 @@ void CPhysicalGeometry::MatchActuator_Disk(const CConfig *config) { if (config->GetMarker_All_KindBC(iMarker) == Donor) { for (iVertex = 0; iVertex < GetnVertex(iMarker); iVertex++) { iPoint = vertex[iMarker][iVertex]->GetNode(); - if (nodes->GetDomain(iPoint)) nLocalVertex_ActDisk ++; + if (nodes->GetDomain(iPoint)) nLocalVertex_ActDisk++; } } } @@ -6717,24 +6401,26 @@ void CPhysicalGeometry::MatchActuator_Disk(const CConfig *config) { /*--- Send actuator disk vertex information --*/ - SU2_MPI::Allreduce(&nLocalVertex_ActDisk, &MaxLocalVertex_ActDisk, 1, MPI_UNSIGNED_LONG, MPI_MAX, SU2_MPI::GetComm()); - SU2_MPI::Allgather(Buffer_Send_nVertex, 1, MPI_UNSIGNED_LONG, Buffer_Receive_nVertex, 1, MPI_UNSIGNED_LONG, SU2_MPI::GetComm()); + SU2_MPI::Allreduce(&nLocalVertex_ActDisk, &MaxLocalVertex_ActDisk, 1, MPI_UNSIGNED_LONG, MPI_MAX, + SU2_MPI::GetComm()); + SU2_MPI::Allgather(Buffer_Send_nVertex, 1, MPI_UNSIGNED_LONG, Buffer_Receive_nVertex, 1, MPI_UNSIGNED_LONG, + SU2_MPI::GetComm()); /*--- Array dimensionalization --*/ - su2double *Buffer_Send_Coord = new su2double [MaxLocalVertex_ActDisk*nDim]; - unsigned long *Buffer_Send_Point = new unsigned long [MaxLocalVertex_ActDisk]; - unsigned long *Buffer_Send_GlobalIndex = new unsigned long [MaxLocalVertex_ActDisk]; - unsigned long *Buffer_Send_Vertex = new unsigned long [MaxLocalVertex_ActDisk]; - unsigned long *Buffer_Send_Marker = new unsigned long [MaxLocalVertex_ActDisk]; + su2double* Buffer_Send_Coord = new su2double[MaxLocalVertex_ActDisk * nDim]; + unsigned long* Buffer_Send_Point = new unsigned long[MaxLocalVertex_ActDisk]; + unsigned long* Buffer_Send_GlobalIndex = new unsigned long[MaxLocalVertex_ActDisk]; + unsigned long* Buffer_Send_Vertex = new unsigned long[MaxLocalVertex_ActDisk]; + unsigned long* Buffer_Send_Marker = new unsigned long[MaxLocalVertex_ActDisk]; - su2double *Buffer_Receive_Coord = new su2double [nProcessor*MaxLocalVertex_ActDisk*nDim]; - unsigned long *Buffer_Receive_Point = new unsigned long [nProcessor*MaxLocalVertex_ActDisk]; - unsigned long *Buffer_Receive_GlobalIndex = new unsigned long [nProcessor*MaxLocalVertex_ActDisk]; - unsigned long *Buffer_Receive_Vertex = new unsigned long [nProcessor*MaxLocalVertex_ActDisk]; - unsigned long *Buffer_Receive_Marker = new unsigned long [nProcessor*MaxLocalVertex_ActDisk]; + su2double* Buffer_Receive_Coord = new su2double[nProcessor * MaxLocalVertex_ActDisk * nDim]; + unsigned long* Buffer_Receive_Point = new unsigned long[nProcessor * MaxLocalVertex_ActDisk]; + unsigned long* Buffer_Receive_GlobalIndex = new unsigned long[nProcessor * MaxLocalVertex_ActDisk]; + unsigned long* Buffer_Receive_Vertex = new unsigned long[nProcessor * MaxLocalVertex_ActDisk]; + unsigned long* Buffer_Receive_Marker = new unsigned long[nProcessor * MaxLocalVertex_ActDisk]; - unsigned long nBuffer_Coord = MaxLocalVertex_ActDisk*nDim; + unsigned long nBuffer_Coord = MaxLocalVertex_ActDisk * nDim; unsigned long nBuffer_Point = MaxLocalVertex_ActDisk; unsigned long nBuffer_GlobalIndex = MaxLocalVertex_ActDisk; unsigned long nBuffer_Vertex = MaxLocalVertex_ActDisk; @@ -6745,8 +6431,7 @@ void CPhysicalGeometry::MatchActuator_Disk(const CConfig *config) { Buffer_Send_GlobalIndex[iVertex] = 0; Buffer_Send_Vertex[iVertex] = 0; Buffer_Send_Marker[iVertex] = 0; - for (iDim = 0; iDim < nDim; iDim++) - Buffer_Send_Coord[iVertex*nDim+iDim] = 0.0; + for (iDim = 0; iDim < nDim; iDim++) Buffer_Send_Coord[iVertex * nDim + iDim] = 0.0; } /*--- Copy coordinates and point to the auxiliar vector --*/ @@ -6763,18 +6448,23 @@ void CPhysicalGeometry::MatchActuator_Disk(const CConfig *config) { Buffer_Send_Vertex[nLocalVertex_ActDisk] = iVertex; Buffer_Send_Marker[nLocalVertex_ActDisk] = iMarker; for (iDim = 0; iDim < nDim; iDim++) - Buffer_Send_Coord[nLocalVertex_ActDisk*nDim+iDim] = nodes->GetCoord(iPoint, iDim); + Buffer_Send_Coord[nLocalVertex_ActDisk * nDim + iDim] = nodes->GetCoord(iPoint, iDim); nLocalVertex_ActDisk++; } } } } - SU2_MPI::Allgather(Buffer_Send_Coord, nBuffer_Coord, MPI_DOUBLE, Buffer_Receive_Coord, nBuffer_Coord, MPI_DOUBLE, SU2_MPI::GetComm()); - SU2_MPI::Allgather(Buffer_Send_Point, nBuffer_Point, MPI_UNSIGNED_LONG, Buffer_Receive_Point, nBuffer_Point, MPI_UNSIGNED_LONG, SU2_MPI::GetComm()); - SU2_MPI::Allgather(Buffer_Send_GlobalIndex, nBuffer_GlobalIndex, MPI_UNSIGNED_LONG, Buffer_Receive_GlobalIndex, nBuffer_GlobalIndex, MPI_UNSIGNED_LONG, SU2_MPI::GetComm()); - SU2_MPI::Allgather(Buffer_Send_Vertex, nBuffer_Vertex, MPI_UNSIGNED_LONG, Buffer_Receive_Vertex, nBuffer_Vertex, MPI_UNSIGNED_LONG, SU2_MPI::GetComm()); - SU2_MPI::Allgather(Buffer_Send_Marker, nBuffer_Marker, MPI_UNSIGNED_LONG, Buffer_Receive_Marker, nBuffer_Marker, MPI_UNSIGNED_LONG, SU2_MPI::GetComm()); + SU2_MPI::Allgather(Buffer_Send_Coord, nBuffer_Coord, MPI_DOUBLE, Buffer_Receive_Coord, nBuffer_Coord, MPI_DOUBLE, + SU2_MPI::GetComm()); + SU2_MPI::Allgather(Buffer_Send_Point, nBuffer_Point, MPI_UNSIGNED_LONG, Buffer_Receive_Point, nBuffer_Point, + MPI_UNSIGNED_LONG, SU2_MPI::GetComm()); + SU2_MPI::Allgather(Buffer_Send_GlobalIndex, nBuffer_GlobalIndex, MPI_UNSIGNED_LONG, Buffer_Receive_GlobalIndex, + nBuffer_GlobalIndex, MPI_UNSIGNED_LONG, SU2_MPI::GetComm()); + SU2_MPI::Allgather(Buffer_Send_Vertex, nBuffer_Vertex, MPI_UNSIGNED_LONG, Buffer_Receive_Vertex, nBuffer_Vertex, + MPI_UNSIGNED_LONG, SU2_MPI::GetComm()); + SU2_MPI::Allgather(Buffer_Send_Marker, nBuffer_Marker, MPI_UNSIGNED_LONG, Buffer_Receive_Marker, nBuffer_Marker, + MPI_UNSIGNED_LONG, SU2_MPI::GetComm()); /*--- Compute the closest point to an actuator disk inlet point ---*/ @@ -6782,17 +6472,17 @@ void CPhysicalGeometry::MatchActuator_Disk(const CConfig *config) { for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { if (config->GetMarker_All_KindBC(iMarker) == Beneficiary) { - for (iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { iPoint = vertex[iMarker][iVertex]->GetNode(); iPointGlobal = nodes->GetGlobalIndex(iPoint); - if (nodes->GetDomain(iPoint)) { - /*--- Coordinates of the boundary point ---*/ - Coord_i = nodes->GetCoord(iPoint); mindist = 1E6; pProcessor = 0; pPoint = 0; + Coord_i = nodes->GetCoord(iPoint); + mindist = 1E6; + pProcessor = 0; + pPoint = 0; /*--- Loop over all the boundaries to find the pair ---*/ @@ -6800,32 +6490,36 @@ void CPhysicalGeometry::MatchActuator_Disk(const CConfig *config) { for (iProcessor = 0; iProcessor < nProcessor; iProcessor++) { for (jVertex = 0; jVertex < Buffer_Receive_nVertex[iProcessor]; jVertex++) { - jPoint = Buffer_Receive_Point[iProcessor*MaxLocalVertex_ActDisk+jVertex]; - jPointGlobal = Buffer_Receive_GlobalIndex[iProcessor*MaxLocalVertex_ActDisk+jVertex]; - jVertex_ = Buffer_Receive_Vertex[iProcessor*MaxLocalVertex_ActDisk+jVertex]; - jMarker = Buffer_Receive_Marker[iProcessor*MaxLocalVertex_ActDisk+jVertex]; + jPoint = Buffer_Receive_Point[iProcessor * MaxLocalVertex_ActDisk + jVertex]; + jPointGlobal = Buffer_Receive_GlobalIndex[iProcessor * MaxLocalVertex_ActDisk + jVertex]; + jVertex_ = Buffer_Receive_Vertex[iProcessor * MaxLocalVertex_ActDisk + jVertex]; + jMarker = Buffer_Receive_Marker[iProcessor * MaxLocalVertex_ActDisk + jVertex]; - // if (jPointGlobal != iPointGlobal) { - // ActDisk_Perimeter + // if (jPointGlobal != iPointGlobal) { + // ActDisk_Perimeter - /*--- Compute the distance ---*/ + /*--- Compute the distance ---*/ - dist = 0.0; - for (iDim = 0; iDim < nDim; iDim++) { - Coord_j[iDim] = Buffer_Receive_Coord[(iProcessor*MaxLocalVertex_ActDisk+jVertex)*nDim+iDim]; - dist += pow(Coord_j[iDim]-Coord_i[iDim], 2.0); - } - dist = sqrt(dist); - - if (dist < mindist) { - mindist = dist; pProcessor = iProcessor; pPoint = jPoint; pPointGlobal = jPointGlobal; - pVertex = jVertex_; pMarker = jMarker; - if (dist == 0.0) break; - } + dist = 0.0; + for (iDim = 0; iDim < nDim; iDim++) { + Coord_j[iDim] = Buffer_Receive_Coord[(iProcessor * MaxLocalVertex_ActDisk + jVertex) * nDim + iDim]; + dist += pow(Coord_j[iDim] - Coord_i[iDim], 2.0); + } + dist = sqrt(dist); + + if (dist < mindist) { + mindist = dist; + pProcessor = iProcessor; + pPoint = jPoint; + pPointGlobal = jPointGlobal; + pVertex = jVertex_; + pMarker = jMarker; + if (dist == 0.0) break; + } -// } -// else { Perimeter = true; mindist = 0.0; dist = 0.0; break; } - } + // } + // else { Perimeter = true; mindist = 0.0; dist = 0.0; break; } + } } /*--- Store the value of the pair ---*/ @@ -6842,16 +6536,14 @@ void CPhysicalGeometry::MatchActuator_Disk(const CConfig *config) { vertex[iMarker][iVertex]->SetDonorPoint(iPoint, iPointGlobal, pVertex, pMarker, pProcessor); maxdist_local = min(maxdist_local, 0.0); } - } } - } } SU2_MPI::Reduce(&maxdist_local, &maxdist_global, 1, MPI_DOUBLE, MPI_MAX, MASTER_NODE, SU2_MPI::GetComm()); - if (rank == MASTER_NODE) cout <<"The max distance between points is: " << maxdist_global <<"."<< endl; + if (rank == MASTER_NODE) cout << "The max distance between points is: " << maxdist_global << "." << endl; delete[] Buffer_Send_Coord; delete[] Buffer_Send_Point; @@ -6862,22 +6554,18 @@ void CPhysicalGeometry::MatchActuator_Disk(const CConfig *config) { delete[] Buffer_Send_nVertex; delete[] Buffer_Receive_nVertex; - delete [] Buffer_Send_GlobalIndex; - delete [] Buffer_Send_Vertex; - delete [] Buffer_Send_Marker; - - delete [] Buffer_Receive_GlobalIndex; - delete [] Buffer_Receive_Vertex; - delete [] Buffer_Receive_Marker; + delete[] Buffer_Send_GlobalIndex; + delete[] Buffer_Send_Vertex; + delete[] Buffer_Send_Marker; + delete[] Buffer_Receive_GlobalIndex; + delete[] Buffer_Receive_Vertex; + delete[] Buffer_Receive_Marker; } } - } -void CPhysicalGeometry::MatchPeriodic(const CConfig *config, - unsigned short val_periodic) { - +void CPhysicalGeometry::MatchPeriodic(const CConfig* config, unsigned short val_periodic) { unsigned short iMarker, iDim, jMarker, pMarker = 0; unsigned short iPeriodic, nPeriodic; @@ -6895,8 +6583,8 @@ void CPhysicalGeometry::MatchPeriodic(const CConfig *config, su2double *Coord_i, Coord_j[3], dist, mindist, maxdist_local, maxdist_global; const su2double *center, *angles, *trans; - su2double translation[3]={0.0,0.0,0.0}, dx, dy, dz; - su2double rotMatrix[3][3] = {{1.0,0.0,0.0},{0.0,1.0,0.0},{0.0,0.0,1.0}}; + su2double translation[3] = {0.0, 0.0, 0.0}, dx, dy, dz; + su2double rotMatrix[3][3] = {{1.0, 0.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 0.0, 1.0}}; su2double Theta, Phi, Psi, cosTheta, sinTheta, cosPhi, sinPhi, cosPsi, sinPsi; su2double rotCoord[3] = {0.0, 0.0, 0.0}; @@ -6928,8 +6616,7 @@ void CPhysicalGeometry::MatchPeriodic(const CConfig *config, for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { if (config->GetMarker_All_KindBC(iMarker) == PERIODIC_BOUNDARY) { iPeriodic = config->GetMarker_All_PerBound(iMarker); - if ((iPeriodic == val_periodic) || - (iPeriodic == val_periodic + nPeriodic/2)) { + if ((iPeriodic == val_periodic) || (iPeriodic == val_periodic + nPeriodic / 2)) { for (iVertex = 0; iVertex < GetnVertex(iMarker); iVertex++) { iPoint = vertex[iMarker][iVertex]->GetNode(); if (nodes->GetDomain(iPoint)) nLocalVertex_Periodic++; @@ -6941,46 +6628,45 @@ void CPhysicalGeometry::MatchPeriodic(const CConfig *config, /*--- Communicate our local periodic point count globally and receive the counts of periodic points from all other ranks.---*/ - unsigned long *Buffer_Send_nVertex = new unsigned long [1]; - unsigned long *Buffer_Recv_nVertex = new unsigned long [nProcessor]; + unsigned long* Buffer_Send_nVertex = new unsigned long[1]; + unsigned long* Buffer_Recv_nVertex = new unsigned long[nProcessor]; Buffer_Send_nVertex[0] = nLocalVertex_Periodic; /*--- Copy our own count in serial or use collective comms with MPI. ---*/ - SU2_MPI::Allreduce(&nLocalVertex_Periodic, &MaxLocalVertex_Periodic, 1, - MPI_UNSIGNED_LONG, MPI_MAX, SU2_MPI::GetComm()); - SU2_MPI::Allgather(Buffer_Send_nVertex, 1, MPI_UNSIGNED_LONG, - Buffer_Recv_nVertex, 1, MPI_UNSIGNED_LONG, SU2_MPI::GetComm()); + SU2_MPI::Allreduce(&nLocalVertex_Periodic, &MaxLocalVertex_Periodic, 1, MPI_UNSIGNED_LONG, MPI_MAX, + SU2_MPI::GetComm()); + SU2_MPI::Allgather(Buffer_Send_nVertex, 1, MPI_UNSIGNED_LONG, Buffer_Recv_nVertex, 1, MPI_UNSIGNED_LONG, + SU2_MPI::GetComm()); /*--- Prepare buffers to send the information for each periodic point to all ranks so that we can match pairs. ---*/ - su2double *Buffer_Send_Coord = new su2double [MaxLocalVertex_Periodic*nDim]; - unsigned long *Buffer_Send_Point = new unsigned long [MaxLocalVertex_Periodic]; - unsigned long *Buffer_Send_GlobalIndex = new unsigned long [MaxLocalVertex_Periodic]; - unsigned long *Buffer_Send_Vertex = new unsigned long [MaxLocalVertex_Periodic]; - unsigned long *Buffer_Send_Marker = new unsigned long [MaxLocalVertex_Periodic]; + su2double* Buffer_Send_Coord = new su2double[MaxLocalVertex_Periodic * nDim]; + unsigned long* Buffer_Send_Point = new unsigned long[MaxLocalVertex_Periodic]; + unsigned long* Buffer_Send_GlobalIndex = new unsigned long[MaxLocalVertex_Periodic]; + unsigned long* Buffer_Send_Vertex = new unsigned long[MaxLocalVertex_Periodic]; + unsigned long* Buffer_Send_Marker = new unsigned long[MaxLocalVertex_Periodic]; - su2double *Buffer_Recv_Coord = new su2double [nProcessor*MaxLocalVertex_Periodic*nDim]; - unsigned long *Buffer_Recv_Point = new unsigned long [nProcessor*MaxLocalVertex_Periodic]; - unsigned long *Buffer_Recv_GlobalIndex = new unsigned long [nProcessor*MaxLocalVertex_Periodic]; - unsigned long *Buffer_Recv_Vertex = new unsigned long [nProcessor*MaxLocalVertex_Periodic]; - unsigned long *Buffer_Recv_Marker = new unsigned long [nProcessor*MaxLocalVertex_Periodic]; + su2double* Buffer_Recv_Coord = new su2double[nProcessor * MaxLocalVertex_Periodic * nDim]; + unsigned long* Buffer_Recv_Point = new unsigned long[nProcessor * MaxLocalVertex_Periodic]; + unsigned long* Buffer_Recv_GlobalIndex = new unsigned long[nProcessor * MaxLocalVertex_Periodic]; + unsigned long* Buffer_Recv_Vertex = new unsigned long[nProcessor * MaxLocalVertex_Periodic]; + unsigned long* Buffer_Recv_Marker = new unsigned long[nProcessor * MaxLocalVertex_Periodic]; - unsigned long nBuffer_Coord = MaxLocalVertex_Periodic*nDim; - unsigned long nBuffer_Point = MaxLocalVertex_Periodic; + unsigned long nBuffer_Coord = MaxLocalVertex_Periodic * nDim; + unsigned long nBuffer_Point = MaxLocalVertex_Periodic; unsigned long nBuffer_GlobalIndex = MaxLocalVertex_Periodic; - unsigned long nBuffer_Vertex = MaxLocalVertex_Periodic; - unsigned long nBuffer_Marker = MaxLocalVertex_Periodic; + unsigned long nBuffer_Vertex = MaxLocalVertex_Periodic; + unsigned long nBuffer_Marker = MaxLocalVertex_Periodic; for (iVertex = 0; iVertex < MaxLocalVertex_Periodic; iVertex++) { - Buffer_Send_Point[iVertex] = 0; + Buffer_Send_Point[iVertex] = 0; Buffer_Send_GlobalIndex[iVertex] = 0; - Buffer_Send_Vertex[iVertex] = 0; - Buffer_Send_Marker[iVertex] = 0; - for (iDim = 0; iDim < nDim; iDim++) - Buffer_Send_Coord[iVertex*nDim+iDim] = 0.0; + Buffer_Send_Vertex[iVertex] = 0; + Buffer_Send_Marker[iVertex] = 0; + for (iDim = 0; iDim < nDim; iDim++) Buffer_Send_Coord[iVertex * nDim + iDim] = 0.0; } /*--- Store the local index, global index, local boundary index, @@ -6992,8 +6678,7 @@ void CPhysicalGeometry::MatchPeriodic(const CConfig *config, for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { if (config->GetMarker_All_KindBC(iMarker) == PERIODIC_BOUNDARY) { iPeriodic = config->GetMarker_All_PerBound(iMarker); - if ((iPeriodic == val_periodic) || - (iPeriodic == val_periodic + nPeriodic/2)) { + if ((iPeriodic == val_periodic) || (iPeriodic == val_periodic + nPeriodic / 2)) { for (iVertex = 0; iVertex < GetnVertex(iMarker); iVertex++) { iPoint = vertex[iMarker][iVertex]->GetNode(); iPointGlobal = nodes->GetGlobalIndex(iPoint); @@ -7003,7 +6688,7 @@ void CPhysicalGeometry::MatchPeriodic(const CConfig *config, Buffer_Send_Vertex[nLocalVertex_Periodic] = iVertex; Buffer_Send_Marker[nLocalVertex_Periodic] = iMarker; for (iDim = 0; iDim < nDim; iDim++) - Buffer_Send_Coord[nLocalVertex_Periodic*nDim+iDim] = nodes->GetCoord(iPoint, iDim); + Buffer_Send_Coord[nLocalVertex_Periodic * nDim + iDim] = nodes->GetCoord(iPoint, iDim); nLocalVertex_Periodic++; } } @@ -7017,16 +6702,16 @@ void CPhysicalGeometry::MatchPeriodic(const CConfig *config, and we are only storing one periodic marker pair at a time, repeating the data for each pair on all ranks should be manageable. ---*/ - SU2_MPI::Allgather(Buffer_Send_Coord, nBuffer_Coord, MPI_DOUBLE, - Buffer_Recv_Coord, nBuffer_Coord, MPI_DOUBLE, SU2_MPI::GetComm()); - SU2_MPI::Allgather(Buffer_Send_Point, nBuffer_Point, MPI_UNSIGNED_LONG, - Buffer_Recv_Point, nBuffer_Point, MPI_UNSIGNED_LONG, SU2_MPI::GetComm()); - SU2_MPI::Allgather(Buffer_Send_GlobalIndex, nBuffer_GlobalIndex, MPI_UNSIGNED_LONG, - Buffer_Recv_GlobalIndex, nBuffer_GlobalIndex, MPI_UNSIGNED_LONG, SU2_MPI::GetComm()); - SU2_MPI::Allgather(Buffer_Send_Vertex, nBuffer_Vertex, MPI_UNSIGNED_LONG, - Buffer_Recv_Vertex, nBuffer_Vertex, MPI_UNSIGNED_LONG, SU2_MPI::GetComm()); - SU2_MPI::Allgather(Buffer_Send_Marker, nBuffer_Marker, MPI_UNSIGNED_LONG, - Buffer_Recv_Marker, nBuffer_Marker, MPI_UNSIGNED_LONG, SU2_MPI::GetComm()); + SU2_MPI::Allgather(Buffer_Send_Coord, nBuffer_Coord, MPI_DOUBLE, Buffer_Recv_Coord, nBuffer_Coord, MPI_DOUBLE, + SU2_MPI::GetComm()); + SU2_MPI::Allgather(Buffer_Send_Point, nBuffer_Point, MPI_UNSIGNED_LONG, Buffer_Recv_Point, nBuffer_Point, + MPI_UNSIGNED_LONG, SU2_MPI::GetComm()); + SU2_MPI::Allgather(Buffer_Send_GlobalIndex, nBuffer_GlobalIndex, MPI_UNSIGNED_LONG, Buffer_Recv_GlobalIndex, + nBuffer_GlobalIndex, MPI_UNSIGNED_LONG, SU2_MPI::GetComm()); + SU2_MPI::Allgather(Buffer_Send_Vertex, nBuffer_Vertex, MPI_UNSIGNED_LONG, Buffer_Recv_Vertex, nBuffer_Vertex, + MPI_UNSIGNED_LONG, SU2_MPI::GetComm()); + SU2_MPI::Allgather(Buffer_Send_Marker, nBuffer_Marker, MPI_UNSIGNED_LONG, Buffer_Recv_Marker, nBuffer_Marker, + MPI_UNSIGNED_LONG, SU2_MPI::GetComm()); /*--- Now that all ranks have the data for all periodic points for this pair of periodic markers, we match the individual points @@ -7035,17 +6720,14 @@ void CPhysicalGeometry::MatchPeriodic(const CConfig *config, maxdist_local = 0.0; for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { if (config->GetMarker_All_KindBC(iMarker) == PERIODIC_BOUNDARY) { - iPeriodic = config->GetMarker_All_PerBound(iMarker); - if ((iPeriodic == val_periodic) || - (iPeriodic == val_periodic + nPeriodic/2)) { - + if ((iPeriodic == val_periodic) || (iPeriodic == val_periodic + nPeriodic / 2)) { /*--- Retrieve the supplied periodic information. ---*/ Marker_Tag = config->GetMarker_All_TagBound(iMarker); - center = config->GetPeriodicRotCenter(Marker_Tag); - angles = config->GetPeriodicRotAngles(Marker_Tag); - trans = config->GetPeriodicTranslation(Marker_Tag); + center = config->GetPeriodicRotCenter(Marker_Tag); + angles = config->GetPeriodicRotAngles(Marker_Tag); + trans = config->GetPeriodicTranslation(Marker_Tag); /*--- Store (center+trans) as it is constant and will be added. ---*/ @@ -7055,39 +6737,43 @@ void CPhysicalGeometry::MatchPeriodic(const CConfig *config, /*--- Store angles separately for clarity. Compute sines/cosines. ---*/ - Theta = angles[0]; Phi = angles[1]; Psi = angles[2]; - cosTheta = cos(Theta); cosPhi = cos(Phi); cosPsi = cos(Psi); - sinTheta = sin(Theta); sinPhi = sin(Phi); sinPsi = sin(Psi); + Theta = angles[0]; + Phi = angles[1]; + Psi = angles[2]; + cosTheta = cos(Theta); + cosPhi = cos(Phi); + cosPsi = cos(Psi); + sinTheta = sin(Theta); + sinPhi = sin(Phi); + sinPsi = sin(Psi); /*--- Compute the rotation matrix. Note that the implicit ordering is rotation about the x-axis, y-axis, then z-axis. ---*/ - rotMatrix[0][0] = cosPhi*cosPsi; - rotMatrix[1][0] = cosPhi*sinPsi; + rotMatrix[0][0] = cosPhi * cosPsi; + rotMatrix[1][0] = cosPhi * sinPsi; rotMatrix[2][0] = -sinPhi; - rotMatrix[0][1] = sinTheta*sinPhi*cosPsi - cosTheta*sinPsi; - rotMatrix[1][1] = sinTheta*sinPhi*sinPsi + cosTheta*cosPsi; - rotMatrix[2][1] = sinTheta*cosPhi; + rotMatrix[0][1] = sinTheta * sinPhi * cosPsi - cosTheta * sinPsi; + rotMatrix[1][1] = sinTheta * sinPhi * sinPsi + cosTheta * cosPsi; + rotMatrix[2][1] = sinTheta * cosPhi; - rotMatrix[0][2] = cosTheta*sinPhi*cosPsi + sinTheta*sinPsi; - rotMatrix[1][2] = cosTheta*sinPhi*sinPsi - sinTheta*cosPsi; - rotMatrix[2][2] = cosTheta*cosPhi; + rotMatrix[0][2] = cosTheta * sinPhi * cosPsi + sinTheta * sinPsi; + rotMatrix[1][2] = cosTheta * sinPhi * sinPsi - sinTheta * cosPsi; + rotMatrix[2][2] = cosTheta * cosPhi; /*--- Loop over each point on the periodic marker that this rank holds locally and find the matching point from the donor marker. ---*/ for (iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { - /*--- Local and global index for the owned periodic point. ---*/ - iPoint = vertex[iMarker][iVertex]->GetNode(); + iPoint = vertex[iMarker][iVertex]->GetNode(); iPointGlobal = nodes->GetGlobalIndex(iPoint); /*--- If this is not a ghost, find the periodic match. ---*/ if (nodes->GetDomain(iPoint)) { - /*--- Coordinates of the current boundary point ---*/ Coord_i = nodes->GetCoord(iPoint); @@ -7096,22 +6782,18 @@ void CPhysicalGeometry::MatchPeriodic(const CConfig *config, dx = Coord_i[0] - center[0]; dy = Coord_i[1] - center[1]; - if (nDim == 3) dz = Coord_i[2] - center[2]; - else dz = 0.0; + if (nDim == 3) + dz = Coord_i[2] - center[2]; + else + dz = 0.0; /*--- Compute transformed point coordinates. ---*/ - rotCoord[0] = (rotMatrix[0][0]*dx + - rotMatrix[0][1]*dy + - rotMatrix[0][2]*dz + translation[0]); + rotCoord[0] = (rotMatrix[0][0] * dx + rotMatrix[0][1] * dy + rotMatrix[0][2] * dz + translation[0]); - rotCoord[1] = (rotMatrix[1][0]*dx + - rotMatrix[1][1]*dy + - rotMatrix[1][2]*dz + translation[1]); + rotCoord[1] = (rotMatrix[1][0] * dx + rotMatrix[1][1] * dy + rotMatrix[1][2] * dz + translation[1]); - rotCoord[2] = (rotMatrix[2][0]*dx + - rotMatrix[2][1]*dy + - rotMatrix[2][2]*dz + translation[2]); + rotCoord[2] = (rotMatrix[2][0] * dx + rotMatrix[2][1] * dy + rotMatrix[2][2] * dz + translation[2]); /*--- Check if the point lies on the axis of rotation. If it does, the rotated coordinate and the original coordinate are the same. ---*/ @@ -7119,7 +6801,7 @@ void CPhysicalGeometry::MatchPeriodic(const CConfig *config, pointOnAxis = false; distToAxis = 0.0; for (iDim = 0; iDim < nDim; iDim++) - distToAxis = (rotCoord[iDim] - Coord_i[iDim])*(rotCoord[iDim] - Coord_i[iDim]); + distToAxis = (rotCoord[iDim] - Coord_i[iDim]) * (rotCoord[iDim] - Coord_i[iDim]); distToAxis = sqrt(distToAxis); if (distToAxis < epsilon) pointOnAxis = true; @@ -7127,70 +6809,66 @@ void CPhysicalGeometry::MatchPeriodic(const CConfig *config, /*--- Our search is based on the minimum distance, so we initialize the distance to a large value. ---*/ - mindist = 1E6; pProcessor = 0; pPoint = 0; + mindist = 1E6; + pProcessor = 0; + pPoint = 0; /*--- Loop over all of the periodic data that was gathered from all ranks in order to find the matching periodic point. ---*/ for (iProcessor = 0; iProcessor < nProcessor; iProcessor++) - for (jVertex = 0; jVertex < Buffer_Recv_nVertex[iProcessor]; jVertex++) { + for (jVertex = 0; jVertex < Buffer_Recv_nVertex[iProcessor]; jVertex++) { + /*--- Store the loop index more easily. ---*/ - /*--- Store the loop index more easily. ---*/ + index = iProcessor * MaxLocalVertex_Periodic + jVertex; - index = iProcessor*MaxLocalVertex_Periodic + jVertex; + /*--- For each candidate, we have the local and global index, + along with the boundary vertex and marker index. ---*/ - /*--- For each candidate, we have the local and global index, - along with the boundary vertex and marker index. ---*/ + jPoint = Buffer_Recv_Point[index]; + jPointGlobal = Buffer_Recv_GlobalIndex[index]; + jVertex_ = Buffer_Recv_Vertex[index]; + jMarker = Buffer_Recv_Marker[index]; - jPoint = Buffer_Recv_Point[index]; - jPointGlobal = Buffer_Recv_GlobalIndex[index]; - jVertex_ = Buffer_Recv_Vertex[index]; - jMarker = Buffer_Recv_Marker[index]; + /*--- The gathered data will also include the current + "owned" periodic point that we are matching, so first make + sure that we avoid the original point by checking that the + global index values are not the same. ---*/ - /*--- The gathered data will also include the current - "owned" periodic point that we are matching, so first make - sure that we avoid the original point by checking that the - global index values are not the same. ---*/ - - if ((jPointGlobal != iPointGlobal) || (pointOnAxis)) { - - /*--- Compute the distance between the candidate periodic - point and the transformed coordinates of the owned point. ---*/ - - dist = 0.0; - for (iDim = 0; iDim < nDim; iDim++) { - Coord_j[iDim] = Buffer_Recv_Coord[index*nDim + iDim]; - dist += pow(Coord_j[iDim]-rotCoord[iDim],2.0); - } - dist = sqrt(dist); - - /*--- Compare the distance against the existing minimum - and also perform checks just to be sure that this is an - independent periodic point (even if on the same rank), - unless it lies on the axis of rotation. ---*/ - - chkSamePoint = false; - chkSamePoint = (((dist < mindist) && (iProcessor != rank)) || - ((dist < mindist) && (iProcessor == rank) && - (jPoint != iPoint))); - - if (chkSamePoint || ((dist < mindist) && (pointOnAxis))) { - - /*--- We have found an intermediate match. Store the - data for this point before continuing the search. ---*/ - - mindist = dist; - pProcessor = iProcessor; - pPoint = jPoint; - pPointGlobal = jPointGlobal; - pVertex = jVertex_; - pMarker = jMarker; + if ((jPointGlobal != iPointGlobal) || (pointOnAxis)) { + /*--- Compute the distance between the candidate periodic + point and the transformed coordinates of the owned point. ---*/ + dist = 0.0; + for (iDim = 0; iDim < nDim; iDim++) { + Coord_j[iDim] = Buffer_Recv_Coord[index * nDim + iDim]; + dist += pow(Coord_j[iDim] - rotCoord[iDim], 2.0); + } + dist = sqrt(dist); + + /*--- Compare the distance against the existing minimum + and also perform checks just to be sure that this is an + independent periodic point (even if on the same rank), + unless it lies on the axis of rotation. ---*/ + + chkSamePoint = false; + chkSamePoint = (((dist < mindist) && (iProcessor != rank)) || + ((dist < mindist) && (iProcessor == rank) && (jPoint != iPoint))); + + if (chkSamePoint || ((dist < mindist) && (pointOnAxis))) { + /*--- We have found an intermediate match. Store the + data for this point before continuing the search. ---*/ + + mindist = dist; + pProcessor = iProcessor; + pPoint = jPoint; + pPointGlobal = jPointGlobal; + pVertex = jVertex_; + pMarker = jMarker; + } } } - } - /*--- Store the data for the best match found for the owned periodic point. ---*/ @@ -7209,7 +6887,6 @@ void CPhysicalGeometry::MatchPeriodic(const CConfig *config, maxdist_local = min(maxdist_local, 0.0); isBadMatch = true; } - } } } @@ -7221,19 +6898,17 @@ void CPhysicalGeometry::MatchPeriodic(const CConfig *config, pairs of points. ---*/ unsigned long nPointMatch_Local = nPointMatch; - SU2_MPI::Reduce(&nPointMatch_Local, &nPointMatch, 1, MPI_UNSIGNED_LONG, - MPI_SUM, MASTER_NODE, SU2_MPI::GetComm()); - SU2_MPI::Reduce(&maxdist_local, &maxdist_global, 1, MPI_DOUBLE, - MPI_MAX, MASTER_NODE, SU2_MPI::GetComm()); + SU2_MPI::Reduce(&nPointMatch_Local, &nPointMatch, 1, MPI_UNSIGNED_LONG, MPI_SUM, MASTER_NODE, SU2_MPI::GetComm()); + SU2_MPI::Reduce(&maxdist_local, &maxdist_global, 1, MPI_DOUBLE, MPI_MAX, MASTER_NODE, SU2_MPI::GetComm()); /*--- Output some information about the matching process. ---*/ if (rank == MASTER_NODE) { if (nPointMatch > 0) { - cout <<" Matched " << nPointMatch << " points with a max distance of: "; - cout << maxdist_global <<"."<< endl; + cout << " Matched " << nPointMatch << " points with a max distance of: "; + cout << maxdist_global << "." << endl; } else { - cout <<" No matching points for periodic marker pair "; + cout << " No matching points for periodic marker pair "; cout << val_periodic << " in current zone." << endl; } @@ -7257,17 +6932,16 @@ void CPhysicalGeometry::MatchPeriodic(const CConfig *config, delete[] Buffer_Send_nVertex; delete[] Buffer_Recv_nVertex; - delete [] Buffer_Send_GlobalIndex; - delete [] Buffer_Send_Vertex; - delete [] Buffer_Send_Marker; + delete[] Buffer_Send_GlobalIndex; + delete[] Buffer_Send_Vertex; + delete[] Buffer_Send_Marker; - delete [] Buffer_Recv_GlobalIndex; - delete [] Buffer_Recv_Vertex; - delete [] Buffer_Recv_Marker; + delete[] Buffer_Recv_GlobalIndex; + delete[] Buffer_Recv_Vertex; + delete[] Buffer_Recv_Marker; } -void CPhysicalGeometry::FindUniqueNode_PeriodicBound(const CConfig *config) { - +void CPhysicalGeometry::FindUniqueNode_PeriodicBound(const CConfig* config) { /*-------------------------------------------------------------------------------------------*/ /*--- Find reference node on the 'inlet' streamwise periodic marker for the computation ---*/ /*--- of recovered pressure/temperature, such that this found node is independent of the ---*/ @@ -7284,9 +6958,9 @@ void CPhysicalGeometry::FindUniqueNode_PeriodicBound(const CConfig *config) { su2double min_norm = numeric_limits::max(); /*--- Communicate Coordinates plus the minimum distance, therefor the nDim+1 ---*/ - vector Buffer_Send_RefNode(nDim+1, numeric_limits::max()); - su2activematrix Buffer_Recv_RefNode(size,nDim+1); - unsigned long iPointMin = 0; // Initialisaton, otherwise 'may be uninitialized` warning' + vector Buffer_Send_RefNode(nDim + 1, numeric_limits::max()); + su2activematrix Buffer_Recv_RefNode(size, nDim + 1); + unsigned long iPointMin = 0; // Initialisaton, otherwise 'may be uninitialized` warning' /*-------------------------------------------------------------------------------------------*/ /*--- Step 1: Find a unique reference node on each rank and communicate them such that ---*/ @@ -7297,16 +6971,14 @@ void CPhysicalGeometry::FindUniqueNode_PeriodicBound(const CConfig *config) { for (unsigned short iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { if (config->GetMarker_All_KindBC(iMarker) == PERIODIC_BOUNDARY) { - /*--- 1 is the receiver/'inlet', 2 is the donor/'outlet', 0 if no PBC at all. ---*/ auto iPeriodic = config->GetMarker_All_PerBound(iMarker); if (iPeriodic == 1) { - for (auto iVertex = 0ul; iVertex < GetnVertex(iMarker); iVertex++) { - auto iPoint = vertex[iMarker][iVertex]->GetNode(); - /*--- Get the squared norm of the current point. sqrt is a monotonic function in [0,R+) so for comparison we dont need Norm. ---*/ + /*--- Get the squared norm of the current point. sqrt is a monotonic function in [0,R+) so for comparison we + * dont need Norm. ---*/ auto norm = GeometryToolbox::SquaredNorm(nDim, nodes->GetCoord(iPoint)); /*--- Check if new unique reference node is found and store Point ID. ---*/ @@ -7314,21 +6986,21 @@ void CPhysicalGeometry::FindUniqueNode_PeriodicBound(const CConfig *config) { min_norm = norm; iPointMin = iPoint; } - /*--- The theoretical case, that multiple inlet points with the same distance to the origin exists, remains. ---*/ + /*--- The theoretical case, that multiple inlet points with the same distance to the origin exists, remains. + * ---*/ } - break; // Actually no more than one streamwise periodic marker pair is allowed - } // receiver conditional - } // periodic conditional - } // marker loop + break; // Actually no more than one streamwise periodic marker pair is allowed + } // receiver conditional + } // periodic conditional + } // marker loop /*--- Copy the Coordinates and norm into send buffer. ---*/ - for (unsigned short iDim = 0; iDim < nDim; iDim++) - Buffer_Send_RefNode[iDim] = nodes->GetCoord(iPointMin,iDim); + for (unsigned short iDim = 0; iDim < nDim; iDim++) Buffer_Send_RefNode[iDim] = nodes->GetCoord(iPointMin, iDim); Buffer_Send_RefNode[nDim] = min_norm; /*--- Communicate unique nodes to all processes. In case of serial mode nothing happens. ---*/ - SU2_MPI::Allgather(Buffer_Send_RefNode.data(), nDim+1, MPI_DOUBLE, - Buffer_Recv_RefNode.data(), nDim+1, MPI_DOUBLE, SU2_MPI::GetComm()); + SU2_MPI::Allgather(Buffer_Send_RefNode.data(), nDim + 1, MPI_DOUBLE, Buffer_Recv_RefNode.data(), nDim + 1, MPI_DOUBLE, + SU2_MPI::GetComm()); /*-------------------------------------------------------------------------------------------*/ /*--- Step 2: Amongst all local nodes with the smallest distance to the origin, find the ---*/ @@ -7339,176 +7011,164 @@ void CPhysicalGeometry::FindUniqueNode_PeriodicBound(const CConfig *config) { min_norm = numeric_limits::max(); for (int iRank = 0; iRank < size; iRank++) { - - auto norm = Buffer_Recv_RefNode(iRank,nDim); + auto norm = Buffer_Recv_RefNode(iRank, nDim); /*--- Check if new unique reference node is found. ---*/ if (norm < min_norm) { min_norm = norm; for (unsigned short iDim = 0; iDim < nDim; iDim++) - Streamwise_Periodic_RefNode[iDim] = Buffer_Recv_RefNode(iRank,iDim); + Streamwise_Periodic_RefNode[iDim] = Buffer_Recv_RefNode(iRank, iDim); } } /*--- Print the reference node to screen. ---*/ if (rank == MASTER_NODE) { cout << "Streamwise Periodic Reference Node: ["; - for (unsigned short iDim = 0; iDim < nDim; iDim++) - cout << " " << Streamwise_Periodic_RefNode[iDim]; + for (unsigned short iDim = 0; iDim < nDim; iDim++) cout << " " << Streamwise_Periodic_RefNode[iDim]; cout << " ]" << endl; } - } -void CPhysicalGeometry::SetControlVolume(CConfig *config, unsigned short action) { - +void CPhysicalGeometry::SetControlVolume(CConfig* config, unsigned short action) { /*--- Update values of faces of the edge ---*/ if (action != ALLOCATE) { su2double ZeroArea[MAXNDIM] = {0.0}; SU2_OMP_FOR_STAT(1024) - for (auto iEdge = 0ul; iEdge < nEdge; iEdge++) - edges->SetNormal(iEdge, ZeroArea); + for (auto iEdge = 0ul; iEdge < nEdge; iEdge++) edges->SetNormal(iEdge, ZeroArea); END_SU2_OMP_FOR SU2_OMP_FOR_STAT(1024) - for (auto iPoint = 0ul; iPoint < nPoint; iPoint++) - nodes->SetVolume(iPoint, 0.0); + for (auto iPoint = 0ul; iPoint < nPoint; iPoint++) nodes->SetVolume(iPoint, 0.0); END_SU2_OMP_FOR } BEGIN_SU2_OMP_SAFE_GLOBAL_ACCESS { /*--- The following is difficult to parallelize with threads. ---*/ - su2double my_DomainVolume = 0.0; - for (auto iElem = 0ul; iElem < nElem; iElem++) { - - const auto nNodes = elem[iElem]->GetnNodes(); + su2double my_DomainVolume = 0.0; + for (auto iElem = 0ul; iElem < nElem; iElem++) { + const auto nNodes = elem[iElem]->GetnNodes(); - /*--- To make preaccumulation more effective, use as few inputs - as possible, recomputing intermediate quantities as needed. ---*/ - AD::StartPreacc(); + /*--- To make preaccumulation more effective, use as few inputs + as possible, recomputing intermediate quantities as needed. ---*/ + AD::StartPreacc(); - /*--- Get pointers to the coordinates of all the element nodes ---*/ - array Coord; + /*--- Get pointers to the coordinates of all the element nodes ---*/ + array Coord; - for (unsigned short iNode = 0; iNode < nNodes; iNode++) { - auto iPoint = elem[iElem]->GetNode(iNode); - Coord[iNode] = nodes->GetCoord(iPoint); + for (unsigned short iNode = 0; iNode < nNodes; iNode++) { + auto iPoint = elem[iElem]->GetNode(iNode); + Coord[iNode] = nodes->GetCoord(iPoint); #ifdef CODI_REVERSE_TYPE - /*--- The same points and edges will be referenced multiple times as they are common - to many of the element's faces, therefore they are "registered" here only once. ---*/ - AD::SetPreaccIn(nodes->Volume(iPoint)); - for (unsigned short jNode = iNode+1; jNode < nNodes; jNode++) { - auto jPoint = elem[iElem]->GetNode(jNode); - auto iEdge = FindEdge(iPoint, jPoint, false); - if (iEdge >= 0) AD::SetPreaccIn(edges->Normal[iEdge], nDim); - } + /*--- The same points and edges will be referenced multiple times as they are common + to many of the element's faces, therefore they are "registered" here only once. ---*/ + AD::SetPreaccIn(nodes->Volume(iPoint)); + for (unsigned short jNode = iNode + 1; jNode < nNodes; jNode++) { + auto jPoint = elem[iElem]->GetNode(jNode); + auto iEdge = FindEdge(iPoint, jPoint, false); + if (iEdge >= 0) AD::SetPreaccIn(edges->Normal[iEdge], nDim); + } #endif - } - AD::SetPreaccIn(Coord, nNodes, nDim); - - /*--- Compute the element median CG coordinates ---*/ - auto Coord_Elem_CG = elem[iElem]->SetCoord_CG(nDim, Coord); - AD::SetPreaccOut(Coord_Elem_CG, nDim); + } + AD::SetPreaccIn(Coord, nNodes, nDim); - for (unsigned short iFace = 0; iFace < elem[iElem]->GetnFaces(); iFace++) { + /*--- Compute the element median CG coordinates ---*/ + auto Coord_Elem_CG = elem[iElem]->SetCoord_CG(nDim, Coord); + AD::SetPreaccOut(Coord_Elem_CG, nDim); - /*--- In 2D all the faces have only one edge ---*/ - unsigned short nEdgesFace = 1; + for (unsigned short iFace = 0; iFace < elem[iElem]->GetnFaces(); iFace++) { + /*--- In 2D all the faces have only one edge ---*/ + unsigned short nEdgesFace = 1; - /*--- In 3D the number of edges per face is the same as the number of point - per face and the median CG of the face is needed. ---*/ - su2double Coord_FaceElem_CG[MAXNDIM] = {0.0}; - if (nDim == 3) { - nEdgesFace = elem[iElem]->GetnNodesFace(iFace); + /*--- In 3D the number of edges per face is the same as the number of point + per face and the median CG of the face is needed. ---*/ + su2double Coord_FaceElem_CG[MAXNDIM] = {0.0}; + if (nDim == 3) { + nEdgesFace = elem[iElem]->GetnNodesFace(iFace); - for (unsigned short iNode = 0; iNode < nEdgesFace; iNode++) { - auto NodeFace = elem[iElem]->GetFaces(iFace, iNode); - for (unsigned short iDim = 0; iDim < nDim; iDim++) - Coord_FaceElem_CG[iDim] += Coord[NodeFace][iDim]/nEdgesFace; + for (unsigned short iNode = 0; iNode < nEdgesFace; iNode++) { + auto NodeFace = elem[iElem]->GetFaces(iFace, iNode); + for (unsigned short iDim = 0; iDim < nDim; iDim++) + Coord_FaceElem_CG[iDim] += Coord[NodeFace][iDim] / nEdgesFace; + } } - } - /*-- Loop over the edges of a face ---*/ - for (unsigned short iEdgesFace = 0; iEdgesFace < nEdgesFace; iEdgesFace++) { + /*-- Loop over the edges of a face ---*/ + for (unsigned short iEdgesFace = 0; iEdgesFace < nEdgesFace; iEdgesFace++) { + const auto face_iNode = elem[iElem]->GetFaces(iFace, iEdgesFace); + unsigned short face_jNode; - const auto face_iNode = elem[iElem]->GetFaces(iFace,iEdgesFace); - unsigned short face_jNode; - - if (nDim == 2) { - /*--- In 2D only one edge (two points) per edge ---*/ - face_jNode = elem[iElem]->GetFaces(iFace,1); - } - else { - /*--- In 3D we "circle around" the face ---*/ - face_jNode = elem[iElem]->GetFaces(iFace, (iEdgesFace+1)%nEdgesFace); - } + if (nDim == 2) { + /*--- In 2D only one edge (two points) per edge ---*/ + face_jNode = elem[iElem]->GetFaces(iFace, 1); + } else { + /*--- In 3D we "circle around" the face ---*/ + face_jNode = elem[iElem]->GetFaces(iFace, (iEdgesFace + 1) % nEdgesFace); + } - const auto face_iPoint = elem[iElem]->GetNode(face_iNode); - const auto face_jPoint = elem[iElem]->GetNode(face_jNode); + const auto face_iPoint = elem[iElem]->GetNode(face_iNode); + const auto face_jPoint = elem[iElem]->GetNode(face_jNode); - /*--- We define a direction (from the smalest index to the greatest) --*/ - const bool change_face_orientation = (face_iPoint > face_jPoint); - const auto iEdge = FindEdge(face_iPoint, face_jPoint); + /*--- We define a direction (from the smalest index to the greatest) --*/ + const bool change_face_orientation = (face_iPoint > face_jPoint); + const auto iEdge = FindEdge(face_iPoint, face_jPoint); - su2double Coord_Edge_CG[MAXNDIM] = {0.0}; - for (unsigned short iDim = 0; iDim < nDim; iDim++) { - Coord_Edge_CG[iDim] = 0.5 * (Coord[face_iNode][iDim] + Coord[face_jNode][iDim]); - } + su2double Coord_Edge_CG[MAXNDIM] = {0.0}; + for (unsigned short iDim = 0; iDim < nDim; iDim++) { + Coord_Edge_CG[iDim] = 0.5 * (Coord[face_iNode][iDim] + Coord[face_jNode][iDim]); + } - su2double Volume_i, Volume_j; + su2double Volume_i, Volume_j; - if (nDim == 2) { - /*--- Two dimensional problem ---*/ - if (change_face_orientation) - edges->SetNodes_Coord(iEdge, Coord_Elem_CG, Coord_Edge_CG); - else - edges->SetNodes_Coord(iEdge, Coord_Edge_CG, Coord_Elem_CG); + if (nDim == 2) { + /*--- Two dimensional problem ---*/ + if (change_face_orientation) + edges->SetNodes_Coord(iEdge, Coord_Elem_CG, Coord_Edge_CG); + else + edges->SetNodes_Coord(iEdge, Coord_Edge_CG, Coord_Elem_CG); + + Volume_i = CEdge::GetVolume(Coord[face_iNode], Coord_Edge_CG, Coord_Elem_CG); + Volume_j = CEdge::GetVolume(Coord[face_jNode], Coord_Edge_CG, Coord_Elem_CG); + } else { + /*--- Three dimensional problem ---*/ + if (change_face_orientation) + edges->SetNodes_Coord(iEdge, Coord_FaceElem_CG, Coord_Edge_CG, Coord_Elem_CG); + else + edges->SetNodes_Coord(iEdge, Coord_Edge_CG, Coord_FaceElem_CG, Coord_Elem_CG); + + Volume_i = CEdge::GetVolume(Coord[face_iNode], Coord_Edge_CG, Coord_FaceElem_CG, Coord_Elem_CG); + Volume_j = CEdge::GetVolume(Coord[face_jNode], Coord_Edge_CG, Coord_FaceElem_CG, Coord_Elem_CG); + } - Volume_i = CEdge::GetVolume(Coord[face_iNode], Coord_Edge_CG, Coord_Elem_CG); - Volume_j = CEdge::GetVolume(Coord[face_jNode], Coord_Edge_CG, Coord_Elem_CG); - } - else { - /*--- Three dimensional problem ---*/ - if (change_face_orientation) - edges->SetNodes_Coord(iEdge, Coord_FaceElem_CG, Coord_Edge_CG, Coord_Elem_CG); - else - edges->SetNodes_Coord(iEdge, Coord_Edge_CG, Coord_FaceElem_CG, Coord_Elem_CG); + nodes->AddVolume(face_iPoint, Volume_i); + nodes->AddVolume(face_jPoint, Volume_j); - Volume_i = CEdge::GetVolume(Coord[face_iNode], Coord_Edge_CG, Coord_FaceElem_CG, Coord_Elem_CG); - Volume_j = CEdge::GetVolume(Coord[face_jNode], Coord_Edge_CG, Coord_FaceElem_CG, Coord_Elem_CG); + my_DomainVolume += Volume_i + Volume_j; } - - nodes->AddVolume(face_iPoint, Volume_i); - nodes->AddVolume(face_jPoint, Volume_j); - - my_DomainVolume += Volume_i+Volume_j; } - } #ifdef CODI_REVERSE_TYPE - for (unsigned short iNode = 0; iNode < nNodes; iNode++) { - auto iPoint = elem[iElem]->GetNode(iNode); - AD::SetPreaccOut(nodes->Volume(iPoint)); - for (unsigned short jNode = iNode+1; jNode < nNodes; jNode++) { - auto jPoint = elem[iElem]->GetNode(jNode); - auto iEdge = FindEdge(iPoint, jPoint, false); - if (iEdge >= 0) AD::SetPreaccOut(edges->Normal[iEdge], nDim); + for (unsigned short iNode = 0; iNode < nNodes; iNode++) { + auto iPoint = elem[iElem]->GetNode(iNode); + AD::SetPreaccOut(nodes->Volume(iPoint)); + for (unsigned short jNode = iNode + 1; jNode < nNodes; jNode++) { + auto jPoint = elem[iElem]->GetNode(jNode); + auto iEdge = FindEdge(iPoint, jPoint, false); + if (iEdge >= 0) AD::SetPreaccOut(edges->Normal[iEdge], nDim); + } } - } #endif - AD::EndPreacc(); - } - - su2double DomainVolume; - SU2_MPI::Allreduce(&my_DomainVolume, &DomainVolume, 1, MPI_DOUBLE, MPI_SUM, SU2_MPI::GetComm()); - config->SetDomainVolume(DomainVolume); + AD::EndPreacc(); + } - if ((rank == MASTER_NODE) && (action == ALLOCATE)) { - if (nDim == 2) cout <<"Area of the computational grid: "<< DomainVolume <<"."<< endl; - if (nDim == 3) cout <<"Volume of the computational grid: "<< DomainVolume <<"."<< endl; - } + su2double DomainVolume; + SU2_MPI::Allreduce(&my_DomainVolume, &DomainVolume, 1, MPI_DOUBLE, MPI_SUM, SU2_MPI::GetComm()); + config->SetDomainVolume(DomainVolume); + if ((rank == MASTER_NODE) && (action == ALLOCATE)) { + if (nDim == 2) cout << "Area of the computational grid: " << DomainVolume << "." << endl; + if (nDim == 3) cout << "Volume of the computational grid: " << DomainVolume << "." << endl; + } } END_SU2_OMP_SAFE_GLOBAL_ACCESS @@ -7516,21 +7176,19 @@ void CPhysicalGeometry::SetControlVolume(CConfig *config, unsigned short action) SU2_OMP_FOR_STAT(1024) for (auto iEdge = 0ul; iEdge < nEdge; iEdge++) { const auto Area2 = GeometryToolbox::SquaredNorm(nDim, edges->GetNormal(iEdge)); - su2double DefaultArea[MAXNDIM] = {EPS*EPS}; + su2double DefaultArea[MAXNDIM] = {EPS * EPS}; if (Area2 == 0.0) edges->SetNormal(iEdge, DefaultArea); } END_SU2_OMP_FOR } -void CPhysicalGeometry::SetBoundControlVolume(const CConfig *config, unsigned short action) { - +void CPhysicalGeometry::SetBoundControlVolume(const CConfig* config, unsigned short action) { /*--- Clear normals ---*/ if (action != ALLOCATE) { SU2_OMP_FOR_DYN(1) for (unsigned short iMarker = 0; iMarker < nMarker; iMarker++) - for (unsigned long iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) - vertex[iMarker][iVertex]->SetZeroValues(); + for (unsigned long iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) vertex[iMarker][iVertex]->SetZeroValues(); END_SU2_OMP_FOR } @@ -7539,7 +7197,6 @@ void CPhysicalGeometry::SetBoundControlVolume(const CConfig *config, unsigned sh SU2_OMP_FOR_DYN(1) for (unsigned short iMarker = 0; iMarker < nMarker; iMarker++) { for (unsigned long iElem = 0; iElem < nElem_Bound[iMarker]; iElem++) { - const auto nNodes = bound[iMarker][iElem]->GetnNodes(); /*--- Cannot preaccumulate if hybrid parallel due to shared reading. ---*/ @@ -7574,8 +7231,7 @@ void CPhysicalGeometry::SetBoundControlVolume(const CConfig *config, unsigned sh /*--- Store the 2D face ---*/ if (iNode == 0) vertex[iMarker][iVertex]->SetNodes_Coord(Coord_Elem_CG, Coord_Vertex); if (iNode == 1) vertex[iMarker][iVertex]->SetNodes_Coord(Coord_Vertex, Coord_Elem_CG); - } - else { + } else { const auto Neighbor_Node = bound[iMarker][iElem]->GetNeighbor_Nodes(iNode, iNeighbor); auto Neighbor_Coord = Coord[Neighbor_Node]; @@ -7603,18 +7259,17 @@ void CPhysicalGeometry::SetBoundControlVolume(const CConfig *config, unsigned sh /*--- Check if there is a normal with null area ---*/ SU2_OMP_FOR_DYN(1) - for (unsigned short iMarker = 0; iMarker < nMarker; iMarker ++) { + for (unsigned short iMarker = 0; iMarker < nMarker; iMarker++) { for (unsigned long iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { auto Area2 = GeometryToolbox::SquaredNorm(nDim, vertex[iMarker][iVertex]->GetNormal()); - su2double DefaultArea[MAXNDIM] = {EPS*EPS}; + su2double DefaultArea[MAXNDIM] = {EPS * EPS}; if (Area2 == 0.0) vertex[iMarker][iVertex]->SetNormal(DefaultArea); } } END_SU2_OMP_FOR } -void CPhysicalGeometry::VisualizeControlVolume(const CConfig *config) const { - +void CPhysicalGeometry::VisualizeControlVolume(const CConfig* config) const { /*--- Access the point number for control volume we want to vizualize ---*/ auto iPoint = GetGlobal_to_Local_Point(config->GetVisualize_CV()); @@ -7627,7 +7282,6 @@ void CPhysicalGeometry::VisualizeControlVolume(const CConfig *config) const { /*--- Loop over each face of each element ---*/ for (auto iElem = 0ul; iElem < nElem; iElem++) { - /*--- Get pointers to the coordinates of all the element nodes ---*/ array Coord; @@ -7637,7 +7291,6 @@ void CPhysicalGeometry::VisualizeControlVolume(const CConfig *config) const { } for (unsigned short iFace = 0; iFace < elem[iElem]->GetnFaces(); iFace++) { - /*--- In 2D all the faces have only one edge ---*/ unsigned short nEdgesFace = 1; @@ -7650,30 +7303,27 @@ void CPhysicalGeometry::VisualizeControlVolume(const CConfig *config) const { for (unsigned short iNode = 0; iNode < nEdgesFace; iNode++) { auto NodeFace = elem[iElem]->GetFaces(iFace, iNode); for (unsigned short iDim = 0; iDim < nDim; iDim++) - Coord_FaceElem_CG[iDim] += Coord[NodeFace][iDim]/nEdgesFace; + Coord_FaceElem_CG[iDim] += Coord[NodeFace][iDim] / nEdgesFace; } } /*-- Loop over the edges of a face ---*/ for (unsigned short iEdgesFace = 0; iEdgesFace < nEdgesFace; iEdgesFace++) { - - const auto face_iPoint = elem[iElem]->GetNode(elem[iElem]->GetFaces(iFace,iEdgesFace)); + const auto face_iPoint = elem[iElem]->GetNode(elem[iElem]->GetFaces(iFace, iEdgesFace)); unsigned long face_jPoint; if (nDim == 2) { /*--- In 2D only one edge (two points) per edge ---*/ - face_jPoint = elem[iElem]->GetNode(elem[iElem]->GetFaces(iFace,1)); - } - else { + face_jPoint = elem[iElem]->GetNode(elem[iElem]->GetFaces(iFace, 1)); + } else { /*--- In 3D we "circle around" the face ---*/ - face_jPoint = elem[iElem]->GetNode(elem[iElem]->GetFaces(iFace, (iEdgesFace+1)%nEdgesFace)); + face_jPoint = elem[iElem]->GetNode(elem[iElem]->GetFaces(iFace, (iEdgesFace + 1) % nEdgesFace)); } /*--- Print out the coordinates for a set of triangles making up a single dual control volume for visualization. ---*/ if (face_iPoint == iPoint_Viz || face_jPoint == iPoint_Viz) { - const su2double* Coord_FaceiPoint = nodes->GetCoord(face_iPoint); const su2double* Coord_FacejPoint = nodes->GetCoord(face_jPoint); const su2double* Coord_Elem_CG = elem[iElem]->GetCG(); @@ -7684,12 +7334,20 @@ void CPhysicalGeometry::VisualizeControlVolume(const CConfig *config) const { } if (nDim == 2) { - X.push_back(Coord_Elem_CG[0]); X.push_back(Coord_Edge_CG[0]); - Y.push_back(Coord_Elem_CG[1]); Y.push_back(Coord_Edge_CG[1]); + X.push_back(Coord_Elem_CG[0]); + X.push_back(Coord_Edge_CG[0]); + Y.push_back(Coord_Elem_CG[1]); + Y.push_back(Coord_Edge_CG[1]); } else { - X.push_back(Coord_FaceElem_CG[0]); X.push_back(Coord_Edge_CG[0]); X.push_back(Coord_Elem_CG[0]); - Y.push_back(Coord_FaceElem_CG[1]); Y.push_back(Coord_Edge_CG[1]); Y.push_back(Coord_Elem_CG[1]); - Z.push_back(Coord_FaceElem_CG[2]); Z.push_back(Coord_Edge_CG[2]); Z.push_back(Coord_Elem_CG[2]); + X.push_back(Coord_FaceElem_CG[0]); + X.push_back(Coord_Edge_CG[0]); + X.push_back(Coord_Elem_CG[0]); + Y.push_back(Coord_FaceElem_CG[1]); + Y.push_back(Coord_Edge_CG[1]); + Y.push_back(Coord_Elem_CG[1]); + Z.push_back(Coord_FaceElem_CG[2]); + Z.push_back(Coord_Edge_CG[2]); + Z.push_back(Coord_Elem_CG[2]); } counter++; } @@ -7707,12 +7365,12 @@ void CPhysicalGeometry::VisualizeControlVolume(const CConfig *config) const { if (nDim == 2) { Tecplot_File << "VARIABLES = \"x\",\"y\" " << endl; - Tecplot_File << "ZONE NODES= "<< counter*2 <<", ELEMENTS= "; - Tecplot_File << counter <<", DATAPACKING=POINT, ZONETYPE=FEQUADRILATERAL"<< endl; + Tecplot_File << "ZONE NODES= " << counter * 2 << ", ELEMENTS= "; + Tecplot_File << counter << ", DATAPACKING=POINT, ZONETYPE=FEQUADRILATERAL" << endl; } else { Tecplot_File << "VARIABLES = \"x\",\"y\",\"z\" " << endl; - Tecplot_File << "ZONE NODES= "<< counter*3 <<", ELEMENTS= "; - Tecplot_File << counter <<", DATAPACKING=POINT, ZONETYPE=FEBRICK"<< endl; + Tecplot_File << "ZONE NODES= " << counter * 3 << ", ELEMENTS= "; + Tecplot_File << counter << ", DATAPACKING=POINT, ZONETYPE=FEBRICK" << endl; } /*--- Write coordinates for the nodes in the order that they were found @@ -7728,44 +7386,42 @@ void CPhysicalGeometry::VisualizeControlVolume(const CConfig *config) const { for (int i = 0, j; i < counter; i++) { if (nDim == 2) { - j = i*2; - Tecplot_File << j+1 <<"\t"<SetCoord_Old(); /*--- Jacobi iterations ---*/ for (iSmooth = 0; iSmooth < val_nSmooth; iSmooth++) { - nodes->SetCoord_SumZero(); /*--- Loop over Interior edges ---*/ for (iEdge = 0; iEdge < nEdge; iEdge++) { - iPoint = edges->GetNode(iEdge,0); + iPoint = edges->GetNode(iEdge, 0); Coord_i = nodes->GetCoord(iPoint); - jPoint = edges->GetNode(iEdge,1); + jPoint = edges->GetNode(iEdge, 1); Coord_j = nodes->GetCoord(jPoint); /*--- Accumulate nearest neighbor Coord to Res_sum for each variable ---*/ nodes->AddCoord_Sum(iPoint, Coord_j); nodes->AddCoord_Sum(jPoint, Coord_i); - } /*--- Loop over all mesh points (Update Coords with averaged sum) ---*/ @@ -7775,17 +7431,17 @@ void CPhysicalGeometry::SetCoord_Smoothing (unsigned short val_nSmooth, su2doubl Coord_Old = nodes->GetCoord_Old(iPoint); if (nDim == 2) { - Coord[0] =(Coord_Old[0] + val_smooth_coeff*Coord_Sum[0]) /(1.0 + val_smooth_coeff*su2double(nneigh)); - Coord[1] =(Coord_Old[1] + val_smooth_coeff*Coord_Sum[1]) /(1.0 + val_smooth_coeff*su2double(nneigh)); - if ((NearField) && ((Coord_Old[1] > Position_Plane-eps) && (Coord_Old[1] < Position_Plane+eps))) + Coord[0] = (Coord_Old[0] + val_smooth_coeff * Coord_Sum[0]) / (1.0 + val_smooth_coeff * su2double(nneigh)); + Coord[1] = (Coord_Old[1] + val_smooth_coeff * Coord_Sum[1]) / (1.0 + val_smooth_coeff * su2double(nneigh)); + if ((NearField) && ((Coord_Old[1] > Position_Plane - eps) && (Coord_Old[1] < Position_Plane + eps))) Coord[1] = Coord_Old[1]; } if (nDim == 3) { - Coord[0] =(Coord_Old[0] + val_smooth_coeff*Coord_Sum[0]) /(1.0 + val_smooth_coeff*su2double(nneigh)); - Coord[1] =(Coord_Old[1] + val_smooth_coeff*Coord_Sum[1]) /(1.0 + val_smooth_coeff*su2double(nneigh)); - Coord[2] =(Coord_Old[2] + val_smooth_coeff*Coord_Sum[2]) /(1.0 + val_smooth_coeff*su2double(nneigh)); - if ((NearField) && ((Coord_Old[2] > Position_Plane-eps) && (Coord_Old[2] < Position_Plane+eps))) + Coord[0] = (Coord_Old[0] + val_smooth_coeff * Coord_Sum[0]) / (1.0 + val_smooth_coeff * su2double(nneigh)); + Coord[1] = (Coord_Old[1] + val_smooth_coeff * Coord_Sum[1]) / (1.0 + val_smooth_coeff * su2double(nneigh)); + Coord[2] = (Coord_Old[2] + val_smooth_coeff * Coord_Sum[2]) / (1.0 + val_smooth_coeff * su2double(nneigh)); + if ((NearField) && ((Coord_Old[2] > Position_Plane - eps) && (Coord_Old[2] < Position_Plane + eps))) Coord[2] = Coord_Old[2]; } @@ -7804,9 +7460,8 @@ void CPhysicalGeometry::SetCoord_Smoothing (unsigned short val_nSmooth, su2doubl delete[] Coord; } -bool CPhysicalGeometry::FindFace(unsigned long first_elem, unsigned long second_elem, unsigned short &face_first_elem, - unsigned short &face_second_elem) { - +bool CPhysicalGeometry::FindFace(unsigned long first_elem, unsigned long second_elem, unsigned short& face_first_elem, + unsigned short& face_second_elem) { if (first_elem == second_elem) return false; /*--- Find repeated nodes between two elements to identify the common face. ---*/ @@ -7827,7 +7482,7 @@ bool CPhysicalGeometry::FindFace(unsigned long first_elem, unsigned long second_ } /*--- Sort point in face and check that the list is unique ---*/ - sort(CommonPoints, CommonPoints+numCommonPoints); + sort(CommonPoints, CommonPoints + numCommonPoints); /*--- In 2D, the two elements must share two points that make up an edge, as all "faces" are edges in 2D. In 3D, we need to find @@ -7838,9 +7493,8 @@ bool CPhysicalGeometry::FindFace(unsigned long first_elem, unsigned long second_ /*--- Find the faces with the CommonPoint sequence in the first and second elements ---*/ for (auto iElem = 0ul; iElem < 2; ++iElem) { - - const auto idxElem = (iElem==0)? first_elem : second_elem; - auto& idxFaceOut = (iElem==0)? face_first_elem : face_second_elem; + const auto idxElem = (iElem == 0) ? first_elem : second_elem; + auto& idxFaceOut = (iElem == 0) ? face_first_elem : face_second_elem; bool faceFound = false; for (auto iFace = 0u; iFace < elem[idxElem]->GetnFaces(); iFace++) { @@ -7856,7 +7510,7 @@ bool CPhysicalGeometry::FindFace(unsigned long first_elem, unsigned long second_ } /*--- Sort face_poin to perform comparison ---*/ - const auto PointsFaceEnd = PointsFace+nNodesFace; + const auto PointsFaceEnd = PointsFace + nNodesFace; sort(PointsFace, PointsFaceEnd); /*--- List comparison ---*/ @@ -7876,7 +7530,6 @@ bool CPhysicalGeometry::FindFace(unsigned long first_elem, unsigned long second_ } void CPhysicalGeometry::SetTecPlot(char mesh_filename[MAX_STRING_SIZE], bool new_file) { - unsigned long iElem, iPoint; unsigned short iDim; ofstream Tecplot_File; @@ -7888,21 +7541,22 @@ void CPhysicalGeometry::SetTecPlot(char mesh_filename[MAX_STRING_SIZE], bool new Tecplot_File << "TITLE= \"Visualization of the volumetric grid\"" << endl; if (nDim == 2) Tecplot_File << "VARIABLES = \"x\",\"y\" " << endl; if (nDim == 3) Tecplot_File << "VARIABLES = \"x\",\"y\",\"z\" " << endl; - } - else Tecplot_File.open(mesh_filename, ios::out | ios::app); + } else + Tecplot_File.open(mesh_filename, ios::out | ios::app); Tecplot_File << "ZONE T= "; - if (new_file) Tecplot_File << "\"Original grid\", C=BLACK, "; - else Tecplot_File << "\"Deformed grid\", C=RED, "; - Tecplot_File << "NODES= "<< nPoint <<", ELEMENTS= "<< nElem <<", DATAPACKING= POINT"; - if (nDim == 2) Tecplot_File << ", ZONETYPE= FEQUADRILATERAL"<< endl; - if (nDim == 3) Tecplot_File << ", ZONETYPE= FEBRICK"<< endl; + if (new_file) + Tecplot_File << "\"Original grid\", C=BLACK, "; + else + Tecplot_File << "\"Deformed grid\", C=RED, "; + Tecplot_File << "NODES= " << nPoint << ", ELEMENTS= " << nElem << ", DATAPACKING= POINT"; + if (nDim == 2) Tecplot_File << ", ZONETYPE= FEQUADRILATERAL" << endl; + if (nDim == 3) Tecplot_File << ", ZONETYPE= FEBRICK" << endl; /*--- Adding coordinates ---*/ for (iPoint = 0; iPoint < nPoint; iPoint++) { - for (iDim = 0; iDim < nDim; iDim++) - Tecplot_File << scientific << nodes->GetCoord(iPoint, iDim) << "\t"; + for (iDim = 0; iDim < nDim; iDim++) Tecplot_File << scientific << nodes->GetCoord(iPoint, iDim) << "\t"; Tecplot_File << "\n"; } @@ -7910,50 +7564,43 @@ void CPhysicalGeometry::SetTecPlot(char mesh_filename[MAX_STRING_SIZE], bool new for (iElem = 0; iElem < nElem; iElem++) { if (elem[iElem]->GetVTK_Type() == TRIANGLE) { - Tecplot_File << - elem[iElem]->GetNode(0)+1 <<" "<< elem[iElem]->GetNode(1)+1 <<" "<< - elem[iElem]->GetNode(2)+1 <<" "<< elem[iElem]->GetNode(2)+1 << endl; + Tecplot_File << elem[iElem]->GetNode(0) + 1 << " " << elem[iElem]->GetNode(1) + 1 << " " + << elem[iElem]->GetNode(2) + 1 << " " << elem[iElem]->GetNode(2) + 1 << endl; } if (elem[iElem]->GetVTK_Type() == QUADRILATERAL) { - Tecplot_File << - elem[iElem]->GetNode(0)+1 <<" "<< elem[iElem]->GetNode(1)+1 <<" "<< - elem[iElem]->GetNode(2)+1 <<" "<< elem[iElem]->GetNode(3)+1 << endl; + Tecplot_File << elem[iElem]->GetNode(0) + 1 << " " << elem[iElem]->GetNode(1) + 1 << " " + << elem[iElem]->GetNode(2) + 1 << " " << elem[iElem]->GetNode(3) + 1 << endl; } if (elem[iElem]->GetVTK_Type() == TETRAHEDRON) { - Tecplot_File << - elem[iElem]->GetNode(0)+1 <<" "<< elem[iElem]->GetNode(1)+1 <<" "<< - elem[iElem]->GetNode(2)+1 <<" "<< elem[iElem]->GetNode(2)+1 <<" "<< - elem[iElem]->GetNode(3)+1 <<" "<< elem[iElem]->GetNode(3)+1 <<" "<< - elem[iElem]->GetNode(3)+1 <<" "<< elem[iElem]->GetNode(3)+1 << endl; + Tecplot_File << elem[iElem]->GetNode(0) + 1 << " " << elem[iElem]->GetNode(1) + 1 << " " + << elem[iElem]->GetNode(2) + 1 << " " << elem[iElem]->GetNode(2) + 1 << " " + << elem[iElem]->GetNode(3) + 1 << " " << elem[iElem]->GetNode(3) + 1 << " " + << elem[iElem]->GetNode(3) + 1 << " " << elem[iElem]->GetNode(3) + 1 << endl; } if (elem[iElem]->GetVTK_Type() == HEXAHEDRON) { - Tecplot_File << - elem[iElem]->GetNode(0)+1 <<" "<< elem[iElem]->GetNode(1)+1 <<" "<< - elem[iElem]->GetNode(2)+1 <<" "<< elem[iElem]->GetNode(3)+1 <<" "<< - elem[iElem]->GetNode(4)+1 <<" "<< elem[iElem]->GetNode(5)+1 <<" "<< - elem[iElem]->GetNode(6)+1 <<" "<< elem[iElem]->GetNode(7)+1 << endl; + Tecplot_File << elem[iElem]->GetNode(0) + 1 << " " << elem[iElem]->GetNode(1) + 1 << " " + << elem[iElem]->GetNode(2) + 1 << " " << elem[iElem]->GetNode(3) + 1 << " " + << elem[iElem]->GetNode(4) + 1 << " " << elem[iElem]->GetNode(5) + 1 << " " + << elem[iElem]->GetNode(6) + 1 << " " << elem[iElem]->GetNode(7) + 1 << endl; } if (elem[iElem]->GetVTK_Type() == PYRAMID) { - Tecplot_File << - elem[iElem]->GetNode(0)+1 <<" "<< elem[iElem]->GetNode(1)+1 <<" "<< - elem[iElem]->GetNode(2)+1 <<" "<< elem[iElem]->GetNode(3)+1 <<" "<< - elem[iElem]->GetNode(4)+1 <<" "<< elem[iElem]->GetNode(4)+1 <<" "<< - elem[iElem]->GetNode(4)+1 <<" "<< elem[iElem]->GetNode(4)+1 << endl; + Tecplot_File << elem[iElem]->GetNode(0) + 1 << " " << elem[iElem]->GetNode(1) + 1 << " " + << elem[iElem]->GetNode(2) + 1 << " " << elem[iElem]->GetNode(3) + 1 << " " + << elem[iElem]->GetNode(4) + 1 << " " << elem[iElem]->GetNode(4) + 1 << " " + << elem[iElem]->GetNode(4) + 1 << " " << elem[iElem]->GetNode(4) + 1 << endl; } if (elem[iElem]->GetVTK_Type() == PRISM) { - Tecplot_File << - elem[iElem]->GetNode(0)+1 <<" "<< elem[iElem]->GetNode(1)+1 <<" "<< - elem[iElem]->GetNode(1)+1 <<" "<< elem[iElem]->GetNode(2)+1 <<" "<< - elem[iElem]->GetNode(3)+1 <<" "<< elem[iElem]->GetNode(4)+1 <<" "<< - elem[iElem]->GetNode(4)+1 <<" "<< elem[iElem]->GetNode(5)+1 << endl; + Tecplot_File << elem[iElem]->GetNode(0) + 1 << " " << elem[iElem]->GetNode(1) + 1 << " " + << elem[iElem]->GetNode(1) + 1 << " " << elem[iElem]->GetNode(2) + 1 << " " + << elem[iElem]->GetNode(3) + 1 << " " << elem[iElem]->GetNode(4) + 1 << " " + << elem[iElem]->GetNode(4) + 1 << " " << elem[iElem]->GetNode(5) + 1 << endl; } } Tecplot_File.close(); } -void CPhysicalGeometry::SetBoundTecPlot(char mesh_filename[MAX_STRING_SIZE], bool new_file, CConfig *config) { - +void CPhysicalGeometry::SetBoundTecPlot(char mesh_filename[MAX_STRING_SIZE], bool new_file, CConfig* config) { ofstream Tecplot_File; unsigned long iPoint, Total_nElem_Bound, iElem, *PointSurface = nullptr, nPointSurface = 0; unsigned short Coord_i, iMarker; @@ -7984,35 +7631,33 @@ void CPhysicalGeometry::SetBoundTecPlot(char mesh_filename[MAX_STRING_SIZE], boo Tecplot_File << "TITLE= \"Visualization of the surface grid\"" << endl; if (nDim == 2) Tecplot_File << "VARIABLES = \"x\",\"y\" " << endl; if (nDim == 3) Tecplot_File << "VARIABLES = \"x\",\"y\",\"z\" " << endl; - } - else Tecplot_File.open(mesh_filename, ios::out | ios::app); + } else + Tecplot_File.open(mesh_filename, ios::out | ios::app); if (Total_nElem_Bound != 0) { - /*--- Write the header of the file ---*/ Tecplot_File << "ZONE T= "; - if (new_file) Tecplot_File << "\"Original grid\", C=BLACK, "; - else Tecplot_File << "\"Deformed grid\", C=RED, "; - Tecplot_File << "NODES= "<< nPointSurface <<", ELEMENTS= "<< Total_nElem_Bound <<", DATAPACKING= POINT"; - if (nDim == 2) Tecplot_File << ", ZONETYPE= FELINESEG"<< endl; - if (nDim == 3) Tecplot_File << ", ZONETYPE= FEQUADRILATERAL"<< endl; + if (new_file) + Tecplot_File << "\"Original grid\", C=BLACK, "; + else + Tecplot_File << "\"Deformed grid\", C=RED, "; + Tecplot_File << "NODES= " << nPointSurface << ", ELEMENTS= " << Total_nElem_Bound << ", DATAPACKING= POINT"; + if (nDim == 2) Tecplot_File << ", ZONETYPE= FELINESEG" << endl; + if (nDim == 3) Tecplot_File << ", ZONETYPE= FEQUADRILATERAL" << endl; /*--- Only write the coordiantes of the points that are on the surfaces ---*/ if (nDim == 3) { for (iPoint = 0; iPoint < nPoint; iPoint++) if (nodes->GetBoundary(iPoint)) { - for (Coord_i = 0; Coord_i < nDim-1; Coord_i++) - Tecplot_File << nodes->GetCoord(iPoint, Coord_i) << " "; - Tecplot_File << nodes->GetCoord(iPoint, nDim-1) << "\n"; + for (Coord_i = 0; Coord_i < nDim - 1; Coord_i++) Tecplot_File << nodes->GetCoord(iPoint, Coord_i) << " "; + Tecplot_File << nodes->GetCoord(iPoint, nDim - 1) << "\n"; } - } - else { + } else { for (iPoint = 0; iPoint < nPoint; iPoint++) if (nodes->GetBoundary(iPoint)) { - for (Coord_i = 0; Coord_i < nDim; Coord_i++) - Tecplot_File << nodes->GetCoord(iPoint, Coord_i) << " "; + for (Coord_i = 0; Coord_i < nDim; Coord_i++) Tecplot_File << nodes->GetCoord(iPoint, Coord_i) << " "; Tecplot_File << "\n"; } } @@ -8023,38 +7668,36 @@ void CPhysicalGeometry::SetBoundTecPlot(char mesh_filename[MAX_STRING_SIZE], boo if (config->GetMarker_All_Plotting(iMarker) == YES) for (iElem = 0; iElem < nElem_Bound[iMarker]; iElem++) { if (nDim == 2) { - Tecplot_File << PointSurface[bound[iMarker][iElem]->GetNode(0)]+1 << " " - << PointSurface[bound[iMarker][iElem]->GetNode(1)]+1 << endl; + Tecplot_File << PointSurface[bound[iMarker][iElem]->GetNode(0)] + 1 << " " + << PointSurface[bound[iMarker][iElem]->GetNode(1)] + 1 << endl; } if (nDim == 3) { if (bound[iMarker][iElem]->GetnNodes() == 3) { - Tecplot_File << PointSurface[bound[iMarker][iElem]->GetNode(0)]+1 << " " - << PointSurface[bound[iMarker][iElem]->GetNode(1)]+1 << " " - << PointSurface[bound[iMarker][iElem]->GetNode(2)]+1 << " " - << PointSurface[bound[iMarker][iElem]->GetNode(2)]+1 << endl; + Tecplot_File << PointSurface[bound[iMarker][iElem]->GetNode(0)] + 1 << " " + << PointSurface[bound[iMarker][iElem]->GetNode(1)] + 1 << " " + << PointSurface[bound[iMarker][iElem]->GetNode(2)] + 1 << " " + << PointSurface[bound[iMarker][iElem]->GetNode(2)] + 1 << endl; } if (bound[iMarker][iElem]->GetnNodes() == 4) { - Tecplot_File << PointSurface[bound[iMarker][iElem]->GetNode(0)]+1 << " " - << PointSurface[bound[iMarker][iElem]->GetNode(1)]+1 << " " - << PointSurface[bound[iMarker][iElem]->GetNode(2)]+1 << " " - << PointSurface[bound[iMarker][iElem]->GetNode(3)]+1 << endl; + Tecplot_File << PointSurface[bound[iMarker][iElem]->GetNode(0)] + 1 << " " + << PointSurface[bound[iMarker][iElem]->GetNode(1)] + 1 << " " + << PointSurface[bound[iMarker][iElem]->GetNode(2)] + 1 << " " + << PointSurface[bound[iMarker][iElem]->GetNode(3)] + 1 << endl; } } } - } - else { - + } else { /*--- No elements in the surface ---*/ if (nDim == 2) { - Tecplot_File << "ZONE NODES= 1, ELEMENTS= 1, DATAPACKING=POINT, ZONETYPE=FELINESEG"<< endl; - Tecplot_File << "0.0 0.0"<< endl; - Tecplot_File << "1 1"<< endl; + Tecplot_File << "ZONE NODES= 1, ELEMENTS= 1, DATAPACKING=POINT, ZONETYPE=FELINESEG" << endl; + Tecplot_File << "0.0 0.0" << endl; + Tecplot_File << "1 1" << endl; } if (nDim == 3) { - Tecplot_File << "ZONE NODES= 1, ELEMENTS= 1, DATAPACKING=POINT, ZONETYPE=FEQUADRILATERAL"<< endl; - Tecplot_File << "0.0 0.0 0.0"<< endl; - Tecplot_File << "1 1 1 1"<< endl; + Tecplot_File << "ZONE NODES= 1, ELEMENTS= 1, DATAPACKING=POINT, ZONETYPE=FEQUADRILATERAL" << endl; + Tecplot_File << "0.0 0.0 0.0" << endl; + Tecplot_File << "1 1 1 1" << endl; } } @@ -8062,11 +7705,9 @@ void CPhysicalGeometry::SetBoundTecPlot(char mesh_filename[MAX_STRING_SIZE], boo delete[] PointSurface; Tecplot_File.close(); - } -void CPhysicalGeometry::SetColorGrid_Parallel(const CConfig *config) { - +void CPhysicalGeometry::SetColorGrid_Parallel(const CConfig* config) { /*--- We need to have parallel support with MPI and have the ParMETIS library compiled and linked for parallel graph partitioning. ---*/ @@ -8080,27 +7721,27 @@ void CPhysicalGeometry::SetColorGrid_Parallel(const CConfig *config) { /*--- Linear partitioner object to help prepare parmetis data. ---*/ - CLinearPartitioner pointPartitioner(Global_nPointDomain,0); + CLinearPartitioner pointPartitioner(Global_nPointDomain, 0); /*--- Some recommended defaults for the various ParMETIS options. ---*/ idx_t wgtflag = 2; idx_t numflag = 0; - idx_t ncon = 1; - real_t ubvec = 1.0 + config->GetParMETIS_Tolerance(); - idx_t nparts = size; + idx_t ncon = 1; + real_t ubvec = 1.0 + config->GetParMETIS_Tolerance(); + idx_t nparts = size; idx_t options[METIS_NOPTIONS]; METIS_SetDefaultOptions(options); options[1] = 0; /*--- Fill the necessary ParMETIS input data arrays. ---*/ - vector tpwgts(size, 1.0/size); + vector tpwgts(size, 1.0 / size); - vector vtxdist(size+1); + vector vtxdist(size + 1); vtxdist[0] = 0; for (int i = 0; i < size; i++) { - vtxdist[i+1] = pointPartitioner.GetLastIndexOnRank(i); + vtxdist[i + 1] = pointPartitioner.GetLastIndexOnRank(i); } /*--- For most FVM-type operations the amount of work is proportional to the @@ -8114,7 +7755,7 @@ void CPhysicalGeometry::SetColorGrid_Parallel(const CConfig *config) { vector vwgt(nPoint); for (unsigned long iPoint = 0; iPoint < nPoint; ++iPoint) { - vwgt[iPoint] = wp + we * (xadj[iPoint+1] - xadj[iPoint]); + vwgt[iPoint] = wp + we * (xadj[iPoint + 1] - xadj[iPoint]); } /*--- Create some structures that ParMETIS needs to output the partitioning. ---*/ @@ -8125,9 +7766,9 @@ void CPhysicalGeometry::SetColorGrid_Parallel(const CConfig *config) { /*--- Calling ParMETIS ---*/ if (rank == MASTER_NODE) cout << "Calling ParMETIS..."; - auto err = ParMETIS_V3_PartKway(vtxdist.data(), xadj.data(), adjacency.data(), vwgt.data(), - nullptr, &wgtflag, &numflag, &ncon, &nparts, tpwgts.data(), - &ubvec, options, &edgecut, part.data(), &comm); + auto err = + ParMETIS_V3_PartKway(vtxdist.data(), xadj.data(), adjacency.data(), vwgt.data(), nullptr, &wgtflag, &numflag, + &ncon, &nparts, tpwgts.data(), &ubvec, options, &edgecut, part.data(), &comm); if (err != METIS_OK) SU2_MPI::Error("Partitioning failed.", CURRENT_FUNCTION); if (rank == MASTER_NODE) { cout << " graph partitioning complete (" << edgecut << " edge cuts)." << endl; @@ -8149,32 +7790,30 @@ void CPhysicalGeometry::SetColorGrid_Parallel(const CConfig *config) { #endif } -void CPhysicalGeometry::ComputeMeshQualityStatistics(const CConfig *config) { - +void CPhysicalGeometry::ComputeMeshQualityStatistics(const CConfig* config) { /*--- Resize our vectors for the 3 metrics: orthogonality, aspect ratio, and volume ratio. All are vertex-based for the dual CV. ---*/ - Orthogonality.resize(nPoint,0.0); - Aspect_Ratio.resize(nPoint,0.0); - Volume_Ratio.resize(nPoint,0.0); + Orthogonality.resize(nPoint, 0.0); + Aspect_Ratio.resize(nPoint, 0.0); + Volume_Ratio.resize(nPoint, 0.0); /*--- Helper vectors for holding intermediate values. ---*/ - vector SurfaceArea(nPoint,0.0); - vector Area_Max(nPoint,0.0); - vector Area_Min(nPoint,1.e6); - vector SubVolume_Max(nPoint,0.0); - vector SubVolume_Min(nPoint,1.e6); + vector SurfaceArea(nPoint, 0.0); + vector Area_Max(nPoint, 0.0); + vector Area_Min(nPoint, 1.e6); + vector SubVolume_Max(nPoint, 0.0); + vector SubVolume_Min(nPoint, 1.e6); /*--- Orthogonality and aspect ratio (areas) are computed by looping over all edges to check the angles and the face areas. ---*/ for (unsigned long iEdge = 0; iEdge < nEdge; iEdge++) { - /*--- Point identification, edge normal vector and area ---*/ - const unsigned long iPoint = edges->GetNode(iEdge,0); - const unsigned long jPoint = edges->GetNode(iEdge,1); + const unsigned long iPoint = edges->GetNode(iEdge, 0); + const unsigned long jPoint = edges->GetNode(iEdge, 1); const unsigned long GlobalIndex_i = nodes->GetGlobalIndex(iPoint); const unsigned long GlobalIndex_j = nodes->GetGlobalIndex(jPoint); @@ -8183,26 +7822,26 @@ void CPhysicalGeometry::ComputeMeshQualityStatistics(const CConfig *config) { is computed by summing the normals of adjacent faces along the edge between iPoint & jPoint. ---*/ - const su2double *Normal = edges->GetNormal(iEdge); + const su2double* Normal = edges->GetNormal(iEdge); /*--- Get the coordinates for point i & j. ---*/ - const su2double *Coord_i = nodes->GetCoord(iPoint); - const su2double *Coord_j = nodes->GetCoord(jPoint); + const su2double* Coord_i = nodes->GetCoord(iPoint); + const su2double* Coord_j = nodes->GetCoord(jPoint); /*--- Compute the vector pointing from iPoint to jPoint and its distance. We also compute face area (norm of the normal vector). ---*/ su2double distance = 0.0; - su2double area = 0.0; + su2double area = 0.0; vector edgeVector(nDim); for (unsigned short iDim = 0; iDim < nDim; iDim++) { - edgeVector[iDim] = Coord_j[iDim]-Coord_i[iDim]; - distance += edgeVector[iDim]*edgeVector[iDim]; - area += Normal[iDim]*Normal[iDim]; + edgeVector[iDim] = Coord_j[iDim] - Coord_i[iDim]; + distance += edgeVector[iDim] * edgeVector[iDim]; + area += Normal[iDim] * Normal[iDim]; } distance = sqrt(distance); - area = sqrt(area); + area = sqrt(area); /*--- Aspect ratio is the ratio between the largest and smallest faces making up the boundary of the dual CV and is a measure @@ -8221,8 +7860,7 @@ void CPhysicalGeometry::ComputeMeshQualityStatistics(const CConfig *config) { if (area <= 0.0) { char buf[200]; - SPRINTF(buf, "Zero-area CV face found for edge (%lu,%lu).", - GlobalIndex_i, GlobalIndex_j); + SPRINTF(buf, "Zero-area CV face found for edge (%lu,%lu).", GlobalIndex_i, GlobalIndex_j); SU2_MPI::Error(string(buf), CURRENT_FUNCTION); } @@ -8231,7 +7869,7 @@ void CPhysicalGeometry::ComputeMeshQualityStatistics(const CConfig *config) { su2double dotProduct = 0.0; for (unsigned short iDim = 0; iDim < nDim; iDim++) { - dotProduct += (Normal[iDim]/area)*(edgeVector[iDim]/distance); + dotProduct += (Normal[iDim] / area) * (edgeVector[iDim] / distance); } /*--- The definition of orthogonality is an area-weighted average of @@ -8242,12 +7880,12 @@ void CPhysicalGeometry::ComputeMeshQualityStatistics(const CConfig *config) { are close to 90 degress, poor values are typically below 20 degress. ---*/ if (nodes->GetDomain(iPoint)) { - Orthogonality[iPoint] += area*(90.0 - acos(dotProduct)*180.0/PI_NUMBER); - SurfaceArea[iPoint] += area; + Orthogonality[iPoint] += area * (90.0 - acos(dotProduct) * 180.0 / PI_NUMBER); + SurfaceArea[iPoint] += area; } if (nodes->GetDomain(jPoint)) { - Orthogonality[jPoint] += area*(90.0 - acos(dotProduct)*180.0/PI_NUMBER); - SurfaceArea[jPoint] += area; + Orthogonality[jPoint] += area * (90.0 - acos(dotProduct) * 180.0 / PI_NUMBER); + SurfaceArea[jPoint] += area; } /*--- Error check for zero volume of the dual CVs. ---*/ @@ -8263,33 +7901,28 @@ void CPhysicalGeometry::ComputeMeshQualityStatistics(const CConfig *config) { SPRINTF(buf, "Zero-area CV face found for point %lu.", GlobalIndex_j); SU2_MPI::Error(string(buf), CURRENT_FUNCTION); } - } /*--- Loop boundary edges to include the area of the boundary elements. ---*/ for (unsigned short iMarker = 0; iMarker < nMarker; iMarker++) { if ((config->GetMarker_All_KindBC(iMarker) != INTERNAL_BOUNDARY) && - (config->GetMarker_All_KindBC(iMarker) != SEND_RECEIVE)){ - + (config->GetMarker_All_KindBC(iMarker) != SEND_RECEIVE)) { for (unsigned long iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { const unsigned long iPoint = vertex[iMarker][iVertex]->GetNode(); - const su2double *Normal = vertex[iMarker][iVertex]->GetNormal(); + const su2double* Normal = vertex[iMarker][iVertex]->GetNormal(); if (nodes->GetDomain(iPoint)) { - /*--- Face area (norm of the normal vector) ---*/ su2double area = 0.0; - for (unsigned short iDim = 0; iDim < nDim; iDim++) - area += Normal[iDim]*Normal[iDim]; + for (unsigned short iDim = 0; iDim < nDim; iDim++) area += Normal[iDim] * Normal[iDim]; area = sqrt(area); /*--- Check to store the area as the min or max for i or j. ---*/ Area_Min[iPoint] = min(Area_Min[iPoint], area); Area_Max[iPoint] = max(Area_Max[iPoint], area); - } } } @@ -8302,7 +7935,6 @@ void CPhysicalGeometry::ComputeMeshQualityStatistics(const CConfig *config) { is better (closer to isotropic). ----*/ for (unsigned long iElem = 0; iElem < nElem; iElem++) { - /*--- Get pointers to the coordinates of all the element nodes ---*/ array Coord; @@ -8314,7 +7946,6 @@ void CPhysicalGeometry::ComputeMeshQualityStatistics(const CConfig *config) { const su2double* Coord_Elem_CG = elem[iElem]->GetCG(); for (unsigned short iFace = 0; iFace < elem[iElem]->GetnFaces(); iFace++) { - /*--- In 2D all the faces have only one edge ---*/ unsigned short nEdgesFace = 1; @@ -8327,23 +7958,21 @@ void CPhysicalGeometry::ComputeMeshQualityStatistics(const CConfig *config) { for (unsigned short iNode = 0; iNode < nEdgesFace; iNode++) { auto NodeFace = elem[iElem]->GetFaces(iFace, iNode); for (unsigned short iDim = 0; iDim < nDim; iDim++) - Coord_FaceElem_CG[iDim] += Coord[NodeFace][iDim]/nEdgesFace; + Coord_FaceElem_CG[iDim] += Coord[NodeFace][iDim] / nEdgesFace; } } /*-- Loop over the edges of a face ---*/ for (unsigned short iEdgesFace = 0; iEdgesFace < nEdgesFace; iEdgesFace++) { - - const auto face_iNode = elem[iElem]->GetFaces(iFace,iEdgesFace); + const auto face_iNode = elem[iElem]->GetFaces(iFace, iEdgesFace); unsigned short face_jNode; if (nDim == 2) { /*--- In 2D only one edge (two points) per edge ---*/ - face_jNode = elem[iElem]->GetFaces(iFace,1); - } - else { + face_jNode = elem[iElem]->GetFaces(iFace, 1); + } else { /*--- In 3D we "circle around" the face ---*/ - face_jNode = elem[iElem]->GetFaces(iFace, (iEdgesFace+1)%nEdgesFace); + face_jNode = elem[iElem]->GetFaces(iFace, (iEdgesFace + 1) % nEdgesFace); } const auto face_iPoint = elem[iElem]->GetNode(face_iNode); @@ -8360,12 +7989,9 @@ void CPhysicalGeometry::ComputeMeshQualityStatistics(const CConfig *config) { if (nDim == 2) { Volume_i = CEdge::GetVolume(Coord[face_iNode], Coord_Edge_CG, Coord_Elem_CG); Volume_j = CEdge::GetVolume(Coord[face_jNode], Coord_Edge_CG, Coord_Elem_CG); - } - else { - Volume_i = CEdge::GetVolume(Coord[face_iNode], Coord_Edge_CG, - Coord_FaceElem_CG, Coord_Elem_CG); - Volume_j = CEdge::GetVolume(Coord[face_jNode], Coord_Edge_CG, - Coord_FaceElem_CG, Coord_Elem_CG); + } else { + Volume_i = CEdge::GetVolume(Coord[face_iNode], Coord_Edge_CG, Coord_FaceElem_CG, Coord_Elem_CG); + Volume_j = CEdge::GetVolume(Coord[face_jNode], Coord_Edge_CG, Coord_FaceElem_CG, Coord_Elem_CG); } /*--- Check if sub-elem volume is the min or max for iPoint. ---*/ @@ -8381,7 +8007,6 @@ void CPhysicalGeometry::ComputeMeshQualityStatistics(const CConfig *config) { SubVolume_Min[face_jPoint] = min(SubVolume_Min[face_jPoint], Volume_j); SubVolume_Max[face_jPoint] = max(SubVolume_Max[face_jPoint], Volume_j); } - } } } @@ -8390,17 +8015,17 @@ void CPhysicalGeometry::ComputeMeshQualityStatistics(const CConfig *config) { compute the local min and max values here for reporting. ---*/ su2double orthoMin = 1.e6, arMin = 1.e6, vrMin = 1.e6; - su2double orthoMax = 0.0, arMax = 0.0, vrMax = 0.0; - for (unsigned long iPoint= 0; iPoint < nPointDomain; iPoint++) { - Orthogonality[iPoint] = Orthogonality[iPoint]/SurfaceArea[iPoint]; + su2double orthoMax = 0.0, arMax = 0.0, vrMax = 0.0; + for (unsigned long iPoint = 0; iPoint < nPointDomain; iPoint++) { + Orthogonality[iPoint] = Orthogonality[iPoint] / SurfaceArea[iPoint]; orthoMin = min(Orthogonality[iPoint], orthoMin); orthoMax = max(Orthogonality[iPoint], orthoMax); - Aspect_Ratio[iPoint] = Area_Max[iPoint]/Area_Min[iPoint]; + Aspect_Ratio[iPoint] = Area_Max[iPoint] / Area_Min[iPoint]; arMin = min(Aspect_Ratio[iPoint], arMin); arMax = max(Aspect_Ratio[iPoint], arMax); - Volume_Ratio[iPoint] = SubVolume_Max[iPoint]/SubVolume_Min[iPoint]; + Volume_Ratio[iPoint] = SubVolume_Max[iPoint] / SubVolume_Min[iPoint]; vrMin = min(Volume_Ratio[iPoint], vrMin); vrMax = max(Volume_Ratio[iPoint], vrMax); } @@ -8408,22 +8033,16 @@ void CPhysicalGeometry::ComputeMeshQualityStatistics(const CConfig *config) { /*--- Reduction to find the min and max values globally. ---*/ su2double Global_Ortho_Min, Global_Ortho_Max; - SU2_MPI::Allreduce(&orthoMin, &Global_Ortho_Min, 1, - MPI_DOUBLE, MPI_MIN, SU2_MPI::GetComm()); - SU2_MPI::Allreduce(&orthoMax, &Global_Ortho_Max, 1, - MPI_DOUBLE, MPI_MAX, SU2_MPI::GetComm()); + SU2_MPI::Allreduce(&orthoMin, &Global_Ortho_Min, 1, MPI_DOUBLE, MPI_MIN, SU2_MPI::GetComm()); + SU2_MPI::Allreduce(&orthoMax, &Global_Ortho_Max, 1, MPI_DOUBLE, MPI_MAX, SU2_MPI::GetComm()); su2double Global_AR_Min, Global_AR_Max; - SU2_MPI::Allreduce(&arMin, &Global_AR_Min, 1, - MPI_DOUBLE, MPI_MIN, SU2_MPI::GetComm()); - SU2_MPI::Allreduce(&arMax, &Global_AR_Max, 1, - MPI_DOUBLE, MPI_MAX, SU2_MPI::GetComm()); + SU2_MPI::Allreduce(&arMin, &Global_AR_Min, 1, MPI_DOUBLE, MPI_MIN, SU2_MPI::GetComm()); + SU2_MPI::Allreduce(&arMax, &Global_AR_Max, 1, MPI_DOUBLE, MPI_MAX, SU2_MPI::GetComm()); su2double Global_VR_Min, Global_VR_Max; - SU2_MPI::Allreduce(&vrMin, &Global_VR_Min, 1, - MPI_DOUBLE, MPI_MIN, SU2_MPI::GetComm()); - SU2_MPI::Allreduce(&vrMax, &Global_VR_Max, 1, - MPI_DOUBLE, MPI_MAX, SU2_MPI::GetComm()); + SU2_MPI::Allreduce(&vrMin, &Global_VR_Min, 1, MPI_DOUBLE, MPI_MIN, SU2_MPI::GetComm()); + SU2_MPI::Allreduce(&vrMax, &Global_VR_Max, 1, MPI_DOUBLE, MPI_MAX, SU2_MPI::GetComm()); /*--- Print the summary to the console for the user. ---*/ @@ -8431,7 +8050,7 @@ void CPhysicalGeometry::ComputeMeshQualityStatistics(const CConfig *config) { MetricsTable.AddColumn("Mesh Quality Metric", 30); MetricsTable.AddColumn("Minimum", 15); MetricsTable.AddColumn("Maximum", 15); - if (rank == MASTER_NODE){ + if (rank == MASTER_NODE) { MetricsTable.PrintHeader(); MetricsTable << "Orthogonality Angle (deg.)" << Global_Ortho_Min << Global_Ortho_Max; MetricsTable << "CV Face Area Aspect Ratio" << Global_AR_Min << Global_AR_Max; @@ -8447,40 +8066,39 @@ void CPhysicalGeometry::ComputeMeshQualityStatistics(const CConfig *config) { vector().swap(Aspect_Ratio); vector().swap(Volume_Ratio); } - } -void CPhysicalGeometry::FindNormal_Neighbor(const CConfig *config) { +void CPhysicalGeometry::FindNormal_Neighbor(const CConfig* config) { su2double cos_max, scalar_prod, norm_vect, norm_Normal, cos_alpha, diff_coord, *Normal; unsigned long Point_Normal, jPoint; unsigned short iNeigh, iMarker, iDim; unsigned long iPoint, iVertex; for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { - if (config->GetMarker_All_KindBC(iMarker) != SEND_RECEIVE && config->GetMarker_All_KindBC(iMarker) != INTERNAL_BOUNDARY && - config->GetMarker_All_KindBC(iMarker) != NEARFIELD_BOUNDARY ) { - + config->GetMarker_All_KindBC(iMarker) != NEARFIELD_BOUNDARY) { for (iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { - iPoint = vertex[iMarker][iVertex]->GetNode(); Normal = vertex[iMarker][iVertex]->GetNormal(); /*--- Compute closest normal neighbor, note that the normal are oriented inwards ---*/ - Point_Normal = 0; cos_max = -1.0; + Point_Normal = 0; + cos_max = -1.0; for (iNeigh = 0; iNeigh < nodes->GetnPoint(iPoint); iNeigh++) { jPoint = nodes->GetPoint(iPoint, iNeigh); - scalar_prod = 0.0; norm_vect = 0.0; norm_Normal = 0.0; + scalar_prod = 0.0; + norm_vect = 0.0; + norm_Normal = 0.0; for (iDim = 0; iDim < nDim; iDim++) { - diff_coord = nodes->GetCoord(jPoint, iDim)-nodes->GetCoord(iPoint, iDim); - scalar_prod += diff_coord*Normal[iDim]; - norm_vect += diff_coord*diff_coord; - norm_Normal += Normal[iDim]*Normal[iDim]; + diff_coord = nodes->GetCoord(jPoint, iDim) - nodes->GetCoord(iPoint, iDim); + scalar_prod += diff_coord * Normal[iDim]; + norm_vect += diff_coord * diff_coord; + norm_Normal += Normal[iDim] * Normal[iDim]; } norm_vect = sqrt(norm_vect); norm_Normal = sqrt(norm_Normal); - cos_alpha = scalar_prod/(norm_vect*norm_Normal); + cos_alpha = scalar_prod / (norm_vect * norm_Normal); /*--- Get maximum cosine ---*/ if (cos_alpha >= cos_max) { @@ -8494,11 +8112,11 @@ void CPhysicalGeometry::FindNormal_Neighbor(const CConfig *config) { } } -void CPhysicalGeometry::SetBoundSensitivity(CConfig *config) { +void CPhysicalGeometry::SetBoundSensitivity(CConfig* config) { unsigned short iMarker, icommas; unsigned long iVertex, iPoint, (*Point2Vertex)[2], nPointLocal = 0, nPointGlobal = 0; su2double Sensitivity; - bool *PointInDomain; + bool* PointInDomain; nPointLocal = nPoint; SU2_MPI::Allreduce(&nPointLocal, &nPointGlobal, 1, MPI_UNSIGNED_LONG, MPI_SUM, SU2_MPI::GetComm()); @@ -8506,13 +8124,11 @@ void CPhysicalGeometry::SetBoundSensitivity(CConfig *config) { Point2Vertex = new unsigned long[nPointGlobal][2]; PointInDomain = new bool[nPointGlobal]; - for (iPoint = 0; iPoint < nPointGlobal; iPoint ++) - PointInDomain[iPoint] = false; + for (iPoint = 0; iPoint < nPointGlobal; iPoint++) PointInDomain[iPoint] = false; for (iMarker = 0; iMarker < nMarker; iMarker++) if (config->GetMarker_All_DV(iMarker) == YES) for (iVertex = 0; iVertex < nVertex[iMarker]; iVertex++) { - /*--- The sensitivity file uses the global numbering ---*/ iPoint = nodes->GetGlobalIndex(vertex[iMarker][iVertex]->GetNode()); @@ -8530,25 +8146,23 @@ void CPhysicalGeometry::SetBoundSensitivity(CConfig *config) { su2double delta_T, total_T; if ((config->GetTime_Marching() != TIME_MARCHING::STEADY) && config->GetTime_Domain()) { nTimeIter = config->GetUnst_AdjointIter(); - delta_T = config->GetTime_Step(); - total_T = (su2double)nTimeIter*delta_T; + delta_T = config->GetTime_Step(); + total_T = (su2double)nTimeIter * delta_T; } else if (config->GetTime_Marching() == TIME_MARCHING::HARMONIC_BALANCE) { - /*--- Compute period of oscillation & compute time interval using nTimeInstances ---*/ su2double period = config->GetHarmonicBalance_Period(); - nTimeIter = config->GetnTimeInstances(); - delta_T = period/(su2double)nTimeIter; - total_T = period; + nTimeIter = config->GetnTimeInstances(); + delta_T = period / (su2double)nTimeIter; + total_T = period; } else { nTimeIter = 1; - delta_T = 1.0; - total_T = 1.0; + delta_T = 1.0; + total_T = 1.0; } for (iTimeIter = 0; iTimeIter < nTimeIter; iTimeIter++) { - /*--- Prepare to read surface sensitivity files (CSV) ---*/ string text_line; @@ -8556,24 +8170,27 @@ void CPhysicalGeometry::SetBoundSensitivity(CConfig *config) { char buffer[50]; char cstr[MAX_STRING_SIZE]; string surfadj_filename = config->GetSurfAdjCoeff_FileName(); - strcpy (cstr, surfadj_filename.c_str()); + strcpy(cstr, surfadj_filename.c_str()); /*--- Write file name with extension if unsteady or steady ---*/ if (config->GetTime_Marching() == TIME_MARCHING::HARMONIC_BALANCE) - SPRINTF (buffer, "_%d.csv", SU2_TYPE::Int(iTimeIter)); + SPRINTF(buffer, "_%d.csv", SU2_TYPE::Int(iTimeIter)); if (((config->GetTime_Marching() != TIME_MARCHING::STEADY) && config->GetTime_Domain()) || (config->GetTime_Marching() == TIME_MARCHING::HARMONIC_BALANCE)) { - if ((SU2_TYPE::Int(iTimeIter) >= 0) && (SU2_TYPE::Int(iTimeIter) < 10)) SPRINTF (buffer, "_0000%d.csv", SU2_TYPE::Int(iTimeIter)); - if ((SU2_TYPE::Int(iTimeIter) >= 10) && (SU2_TYPE::Int(iTimeIter) < 100)) SPRINTF (buffer, "_000%d.csv", SU2_TYPE::Int(iTimeIter)); - if ((SU2_TYPE::Int(iTimeIter) >= 100) && (SU2_TYPE::Int(iTimeIter) < 1000)) SPRINTF (buffer, "_00%d.csv", SU2_TYPE::Int(iTimeIter)); - if ((SU2_TYPE::Int(iTimeIter) >= 1000) && (SU2_TYPE::Int(iTimeIter) < 10000)) SPRINTF (buffer, "_0%d.csv", SU2_TYPE::Int(iTimeIter)); - if (SU2_TYPE::Int(iTimeIter) >= 10000) SPRINTF (buffer, "_%d.csv", SU2_TYPE::Int(iTimeIter)); - } - else - SPRINTF (buffer, ".csv"); - - strcat (cstr, buffer); + if ((SU2_TYPE::Int(iTimeIter) >= 0) && (SU2_TYPE::Int(iTimeIter) < 10)) + SPRINTF(buffer, "_0000%d.csv", SU2_TYPE::Int(iTimeIter)); + if ((SU2_TYPE::Int(iTimeIter) >= 10) && (SU2_TYPE::Int(iTimeIter) < 100)) + SPRINTF(buffer, "_000%d.csv", SU2_TYPE::Int(iTimeIter)); + if ((SU2_TYPE::Int(iTimeIter) >= 100) && (SU2_TYPE::Int(iTimeIter) < 1000)) + SPRINTF(buffer, "_00%d.csv", SU2_TYPE::Int(iTimeIter)); + if ((SU2_TYPE::Int(iTimeIter) >= 1000) && (SU2_TYPE::Int(iTimeIter) < 10000)) + SPRINTF(buffer, "_0%d.csv", SU2_TYPE::Int(iTimeIter)); + if (SU2_TYPE::Int(iTimeIter) >= 10000) SPRINTF(buffer, "_%d.csv", SU2_TYPE::Int(iTimeIter)); + } else + SPRINTF(buffer, ".csv"); + + strcat(cstr, buffer); /*--- Read the sensitivity file ---*/ @@ -8590,13 +8207,13 @@ void CPhysicalGeometry::SetBoundSensitivity(CConfig *config) { char delimiter = ','; split_line = PrintingToolbox::split(text_line, delimiter); - for (unsigned short iField = 0; iField < split_line.size(); iField++){ + for (unsigned short iField = 0; iField < split_line.size(); iField++) { PrintingToolbox::trim(split_line[iField]); } std::vector::iterator it = std::find(split_line.begin(), split_line.end(), "\"Surface_Sensitivity\""); - if (it == split_line.end()){ + if (it == split_line.end()) { SU2_MPI::Error("Surface sensitivity not found in file.", CURRENT_FUNCTION); } @@ -8604,17 +8221,15 @@ void CPhysicalGeometry::SetBoundSensitivity(CConfig *config) { while (getline(Surface_file, text_line)) { for (icommas = 0; icommas < 50; icommas++) { - position = text_line.find( ",", 0 ); - if (position!=string::npos) text_line.erase (position,1); + position = text_line.find(",", 0); + if (position != string::npos) text_line.erase(position, 1); } - stringstream point_line(text_line); + stringstream point_line(text_line); point_line >> iPoint; - for (int i = 1; i <= sens_index; i++) - point_line >> Sensitivity; + for (int i = 1; i <= sens_index; i++) point_line >> Sensitivity; if (PointInDomain[iPoint]) { - /*--- Find the vertex for the Point and Marker ---*/ iMarker = Point2Vertex[iPoint][0]; @@ -8624,20 +8239,17 @@ void CPhysicalGeometry::SetBoundSensitivity(CConfig *config) { this unsteady timestep. For steady problems, this reduces to a single sensitivity value multiplied by 1.0. ---*/ - vertex[iMarker][iVertex]->AddAuxVar(Sensitivity*(delta_T/total_T)); + vertex[iMarker][iVertex]->AddAuxVar(Sensitivity * (delta_T / total_T)); } - } Surface_file.close(); } delete[] Point2Vertex; delete[] PointInDomain; - } -void CPhysicalGeometry::SetSensitivity(CConfig *config) { - +void CPhysicalGeometry::SetSensitivity(CConfig* config) { ifstream restart_file; string filename = config->GetSolution_AdjFileName(); @@ -8647,19 +8259,20 @@ void CPhysicalGeometry::SetSensitivity(CConfig *config) { string::size_type position; int counter = 0; - Sensitivity.resize(nPoint,nDim) = su2double(0.0); + Sensitivity.resize(nPoint, nDim) = su2double(0.0); if (config->GetTime_Domain()) { nTimeIter = config->GetnTime_Iter(); - }else { + } else { nTimeIter = 1; } - if (rank == MASTER_NODE) - cout << "Reading in sensitivity at iteration " << nTimeIter-1 << "."<< endl; + if (rank == MASTER_NODE) cout << "Reading in sensitivity at iteration " << nTimeIter - 1 << "." << endl; /*--- Read all lines in the restart file ---*/ - long iPoint_Local; unsigned long iPoint_Global = 0; string text_line; + long iPoint_Local; + unsigned long iPoint_Global = 0; + string text_line; iPoint_Global = 0; @@ -8667,27 +8280,25 @@ void CPhysicalGeometry::SetSensitivity(CConfig *config) { filename = config->GetObjFunc_Extension(filename); - if (config->GetRead_Binary_Restart()) { - - filename = config->GetFilename(filename, ".dat", nTimeIter-1); + filename = config->GetFilename(filename, ".dat", nTimeIter - 1); char str_buf[CGNS_STRING_SIZE], fname[100]; unsigned short iVar; strcpy(fname, filename.c_str()); int nRestart_Vars = 5, nFields; - int *Restart_Vars = new int[5]; - passivedouble *Restart_Data = nullptr; + int* Restart_Vars = new int[5]; + passivedouble* Restart_Data = nullptr; int Restart_Iter = 0; - passivedouble Restart_Meta_Passive[8] = {0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0}; - su2double Restart_Meta[8] = {0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0}; + passivedouble Restart_Meta_Passive[8] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; + su2double Restart_Meta[8] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; #ifndef HAVE_MPI /*--- Serial binary input. ---*/ - FILE *fhw; - fhw = fopen(fname,"rb"); + FILE* fhw; + fhw = fopen(fname, "rb"); size_t ret; /*--- Error check for opening the file. ---*/ @@ -8708,9 +8319,10 @@ void CPhysicalGeometry::SetSensitivity(CConfig *config) { if (Restart_Vars[0] != 535532) { SU2_MPI::Error(string("File ") + string(fname) + string(" is not a binary SU2 restart file.\n") + - string("SU2 reads/writes binary restart files by default.\n") + - string("Note that backward compatibility for ASCII restart files is\n") + - string("possible with the READ_BINARY_RESTART option."), CURRENT_FUNCTION); + string("SU2 reads/writes binary restart files by default.\n") + + string("Note that backward compatibility for ASCII restart files is\n") + + string("possible with the READ_BINARY_RESTART option."), + CURRENT_FUNCTION); } /*--- Store the number of fields for simplicity. ---*/ @@ -8733,19 +8345,19 @@ void CPhysicalGeometry::SetSensitivity(CConfig *config) { /*--- For now, create a temp 1D buffer to read the data from file. ---*/ - Restart_Data = new passivedouble[nFields*GetnPointDomain()]; + Restart_Data = new passivedouble[nFields * GetnPointDomain()]; /*--- Read in the data for the restart at all local points. ---*/ - ret = fread(Restart_Data, sizeof(passivedouble), nFields*GetnPointDomain(), fhw); - if (ret != (unsigned long)nFields*GetnPointDomain()) { + ret = fread(Restart_Data, sizeof(passivedouble), nFields * GetnPointDomain(), fhw); + if (ret != (unsigned long)nFields * GetnPointDomain()) { SU2_MPI::Error("Error reading restart file.", CURRENT_FUNCTION); } /*--- Compute (negative) displacements and grab the metadata. ---*/ - ret = sizeof(int) + 8*sizeof(passivedouble); - fseek(fhw,-ret, SEEK_END); + ret = sizeof(int) + 8 * sizeof(passivedouble); + fseek(fhw, -ret, SEEK_END); /*--- Read the external iteration. ---*/ @@ -8792,8 +8404,7 @@ void CPhysicalGeometry::SetSensitivity(CConfig *config) { which we will need in order to read the file later. Also, read the variable string names here. Only the master rank reads the header. ---*/ - if (rank == MASTER_NODE) - MPI_File_read(fhw, Restart_Vars, nRestart_Vars, MPI_INT, MPI_STATUS_IGNORE); + if (rank == MASTER_NODE) MPI_File_read(fhw, Restart_Vars, nRestart_Vars, MPI_INT, MPI_STATUS_IGNORE); /*--- Broadcast the number of variables to all procs and store clearly. ---*/ @@ -8803,11 +8414,11 @@ void CPhysicalGeometry::SetSensitivity(CConfig *config) { have the hex representation of "SU2" as the first int in the file. ---*/ if (Restart_Vars[0] != 535532) { - SU2_MPI::Error(string("File ") + string(fname) + string(" is not a binary SU2 restart file.\n") + - string("SU2 reads/writes binary restart files by default.\n") + - string("Note that backward compatibility for ASCII restart files is\n") + - string("possible with the READ_BINARY_RESTART option."), CURRENT_FUNCTION); + string("SU2 reads/writes binary restart files by default.\n") + + string("Note that backward compatibility for ASCII restart files is\n") + + string("possible with the READ_BINARY_RESTART option."), + CURRENT_FUNCTION); } /*--- Store the number of fields for simplicity. ---*/ @@ -8818,24 +8429,22 @@ void CPhysicalGeometry::SetSensitivity(CConfig *config) { fixed length of 33 for the string length to match with CGNS. This is needed for when we read the strings later. ---*/ - char *mpi_str_buf = new char[nFields*CGNS_STRING_SIZE]; + char* mpi_str_buf = new char[nFields * CGNS_STRING_SIZE]; if (rank == MASTER_NODE) { - disp = nRestart_Vars*sizeof(int); - MPI_File_read_at(fhw, disp, mpi_str_buf, nFields*CGNS_STRING_SIZE, - MPI_CHAR, MPI_STATUS_IGNORE); + disp = nRestart_Vars * sizeof(int); + MPI_File_read_at(fhw, disp, mpi_str_buf, nFields * CGNS_STRING_SIZE, MPI_CHAR, MPI_STATUS_IGNORE); } /*--- Broadcast the string names of the variables. ---*/ - SU2_MPI::Bcast(mpi_str_buf, nFields*CGNS_STRING_SIZE, MPI_CHAR, - MASTER_NODE, SU2_MPI::GetComm()); + SU2_MPI::Bcast(mpi_str_buf, nFields * CGNS_STRING_SIZE, MPI_CHAR, MASTER_NODE, SU2_MPI::GetComm()); /*--- Now parse the string names and load into the config class in case we need them for writing visualization files (SU2_SOL). ---*/ config->fields.push_back("Point_ID"); for (iVar = 0; iVar < nFields; iVar++) { - index = iVar*CGNS_STRING_SIZE; + index = iVar * CGNS_STRING_SIZE; for (iChar = 0; iChar < (unsigned long)CGNS_STRING_SIZE; iChar++) { str_buf[iChar] = mpi_str_buf[index + iChar]; } @@ -8846,7 +8455,7 @@ void CPhysicalGeometry::SetSensitivity(CConfig *config) { /*--- Free string buffer memory. ---*/ - delete [] mpi_str_buf; + delete[] mpi_str_buf; /*--- We're writing only su2doubles in the data portion of the file. ---*/ @@ -8855,20 +8464,20 @@ void CPhysicalGeometry::SetSensitivity(CConfig *config) { /*--- We need to ignore the 4 ints describing the nVar_Restart and nPoints, along with the string names of the variables. ---*/ - disp = nRestart_Vars*sizeof(int) + CGNS_STRING_SIZE*nFields*sizeof(char); + disp = nRestart_Vars * sizeof(int) + CGNS_STRING_SIZE * nFields * sizeof(char); /*--- Define a derived datatype for this rank's set of non-contiguous data that will be placed in the restart. Here, we are collecting each one of the points which are distributed throughout the file in blocks of nVar_Restart data. ---*/ - int *blocklen = new int[GetnPointDomain()]; - MPI_Aint *displace = new MPI_Aint[GetnPointDomain()]; + int* blocklen = new int[GetnPointDomain()]; + MPI_Aint* displace = new MPI_Aint[GetnPointDomain()]; counter = 0; - for (iPoint_Global = 0; iPoint_Global < GetGlobal_nPointDomain(); iPoint_Global++ ) { + for (iPoint_Global = 0; iPoint_Global < GetGlobal_nPointDomain(); iPoint_Global++) { if (GetGlobal_to_Local_Point(iPoint_Global) > -1) { blocklen[counter] = nFields; - displace[counter] = iPoint_Global*nFields*sizeof(passivedouble); + displace[counter] = iPoint_Global * nFields * sizeof(passivedouble); counter++; } } @@ -8882,11 +8491,11 @@ void CPhysicalGeometry::SetSensitivity(CConfig *config) { /*--- For now, create a temp 1D buffer to read the data from file. ---*/ - Restart_Data = new passivedouble[nFields*GetnPointDomain()]; + Restart_Data = new passivedouble[nFields * GetnPointDomain()]; /*--- Collective call for all ranks to read from their view simultaneously. ---*/ - MPI_File_read_all(fhw, Restart_Data, nFields*GetnPointDomain(), MPI_DOUBLE, &status); + MPI_File_read_all(fhw, Restart_Data, nFields * GetnPointDomain(), MPI_DOUBLE, &status); /*--- Free the derived datatype. ---*/ @@ -8899,18 +8508,16 @@ void CPhysicalGeometry::SetSensitivity(CConfig *config) { /*--- Access the metadata. ---*/ if (rank == MASTER_NODE) { - /*--- External iteration. ---*/ - disp = (nRestart_Vars*sizeof(int) + nFields*CGNS_STRING_SIZE*sizeof(char) + - nFields*Restart_Vars[2]*sizeof(passivedouble)); + disp = (nRestart_Vars * sizeof(int) + nFields * CGNS_STRING_SIZE * sizeof(char) + + nFields * Restart_Vars[2] * sizeof(passivedouble)); MPI_File_read_at(fhw, disp, &Restart_Iter, 1, MPI_INT, MPI_STATUS_IGNORE); /*--- Additional doubles for AoA, AoS, etc. ---*/ - disp = (nRestart_Vars*sizeof(int) + nFields*CGNS_STRING_SIZE*sizeof(char) + - nFields*Restart_Vars[2]*sizeof(passivedouble) + 1*sizeof(int)); + disp = (nRestart_Vars * sizeof(int) + nFields * CGNS_STRING_SIZE * sizeof(char) + + nFields * Restart_Vars[2] * sizeof(passivedouble) + 1 * sizeof(int)); MPI_File_read_at(fhw, disp, Restart_Meta_Passive, 8, MPI_DOUBLE, MPI_STATUS_IGNORE); - } /*--- Communicate metadata. ---*/ @@ -8920,8 +8527,7 @@ void CPhysicalGeometry::SetSensitivity(CConfig *config) { /*--- Copy to a su2double structure (because of the SU2_MPI::Bcast doesn't work with passive data)---*/ - for (unsigned short iVar = 0; iVar < 8; iVar++) - Restart_Meta[iVar] = Restart_Meta_Passive[iVar]; + for (unsigned short iVar = 0; iVar < 8; iVar++) Restart_Meta[iVar] = Restart_Meta_Passive[iVar]; SU2_MPI::Bcast(Restart_Meta, 8, MPI_DOUBLE, MASTER_NODE, SU2_MPI::GetComm()); @@ -8929,8 +8535,8 @@ void CPhysicalGeometry::SetSensitivity(CConfig *config) { MPI_File_close(&fhw); - delete [] blocklen; - delete [] displace; + delete[] blocklen; + delete[] displace; #endif @@ -8938,14 +8544,14 @@ void CPhysicalGeometry::SetSensitivity(CConfig *config) { std::vector::iterator ity = std::find(config->fields.begin(), config->fields.end(), "Sensitivity_y"); std::vector::iterator itz = std::find(config->fields.begin(), config->fields.end(), "Sensitivity_z"); - if (itx == config->fields.end()){ + if (itx == config->fields.end()) { SU2_MPI::Error("Sensitivity x not found in file.", CURRENT_FUNCTION); } - if (ity == config->fields.end()){ + if (ity == config->fields.end()) { SU2_MPI::Error("Sensitivity y not found in file.", CURRENT_FUNCTION); } - if (nDim == 3){ - if (itz == config->fields.end()){ + if (nDim == 3) { + if (itz == config->fields.end()) { SU2_MPI::Error("Sensitivity z not found in file.", CURRENT_FUNCTION); } } @@ -8953,32 +8559,29 @@ void CPhysicalGeometry::SetSensitivity(CConfig *config) { unsigned short sens_x_idx = std::distance(config->fields.begin(), itx); unsigned short sens_y_idx = std::distance(config->fields.begin(), ity); unsigned short sens_z_idx = 0; - if (nDim == 3) - sens_z_idx = std::distance(config->fields.begin(), itz); + if (nDim == 3) sens_z_idx = std::distance(config->fields.begin(), itz); /*--- Load the data from the binary restart. ---*/ counter = 0; - for (iPoint_Global = 0; iPoint_Global < GetGlobal_nPointDomain(); iPoint_Global++ ) { - + for (iPoint_Global = 0; iPoint_Global < GetGlobal_nPointDomain(); iPoint_Global++) { /*--- Retrieve local index. If this node from the restart file lives on the current processor, we will load and instantiate the vars. ---*/ iPoint_Local = GetGlobal_to_Local_Point(iPoint_Global); if (iPoint_Local > -1) { - /*--- We need to store this point's data, so jump to the correct offset in the buffer of data from the restart file and load it. ---*/ - index = counter*nFields + sens_x_idx - 1; - Sensitivity(iPoint_Local,0) = Restart_Data[index]; - index = counter*nFields + sens_y_idx - 1; - Sensitivity(iPoint_Local,1) = Restart_Data[index]; + index = counter * nFields + sens_x_idx - 1; + Sensitivity(iPoint_Local, 0) = Restart_Data[index]; + index = counter * nFields + sens_y_idx - 1; + Sensitivity(iPoint_Local, 1) = Restart_Data[index]; - if (nDim == 3){ - index = counter*nFields + sens_z_idx - 1; - Sensitivity(iPoint_Local,2) = Restart_Data[index]; + if (nDim == 3) { + index = counter * nFields + sens_z_idx - 1; + Sensitivity(iPoint_Local, 2) = Restart_Data[index]; } /*--- Increment the overall counter for how many points have been loaded. ---*/ counter++; @@ -8990,8 +8593,7 @@ void CPhysicalGeometry::SetSensitivity(CConfig *config) { config->SetAoA_Sens(Restart_Meta[4]); } else { - - filename = config->GetFilename(filename, ".csv", nTimeIter-1); + filename = config->GetFilename(filename, ".csv", nTimeIter - 1); /*--- First, check that this is not a binary restart file. ---*/ @@ -9003,8 +8605,8 @@ void CPhysicalGeometry::SetSensitivity(CConfig *config) { /*--- Serial binary input. ---*/ - FILE *fhw; - fhw = fopen(fname,"rb"); + FILE* fhw; + fhw = fopen(fname, "rb"); size_t ret; /*--- Error check for opening the file. ---*/ @@ -9025,9 +8627,10 @@ void CPhysicalGeometry::SetSensitivity(CConfig *config) { if (magic_number == 535532) { SU2_MPI::Error(string("File ") + string(fname) + string(" is a binary SU2 restart file, expected ASCII.\n") + - string("SU2 reads/writes binary restart files by default.\n") + - string("Note that backward compatibility for ASCII restart files is\n") + - string("possible with the READ_BINARY_RESTART option."), CURRENT_FUNCTION); + string("SU2 reads/writes binary restart files by default.\n") + + string("Note that backward compatibility for ASCII restart files is\n") + + string("possible with the READ_BINARY_RESTART option."), + CURRENT_FUNCTION); } fclose(fhw); @@ -9051,8 +8654,7 @@ void CPhysicalGeometry::SetSensitivity(CConfig *config) { /*--- Have the master attempt to read the magic number. ---*/ - if (rank == MASTER_NODE) - MPI_File_read(fhw, &magic_number, 1, MPI_INT, MPI_STATUS_IGNORE); + if (rank == MASTER_NODE) MPI_File_read(fhw, &magic_number, 1, MPI_INT, MPI_STATUS_IGNORE); /*--- Broadcast the number of variables to all procs and store clearly. ---*/ @@ -9062,93 +8664,86 @@ void CPhysicalGeometry::SetSensitivity(CConfig *config) { have the hex representation of "SU2" as the first int in the file. ---*/ if (magic_number == 535532) { - SU2_MPI::Error(string("File ") + string(fname) + string(" is a binary SU2 restart file, expected ASCII.\n") + - string("SU2 reads/writes binary restart files by default.\n") + - string("Note that backward compatibility for ASCII restart files is\n") + - string("possible with the READ_BINARY_RESTART option."), CURRENT_FUNCTION); + string("SU2 reads/writes binary restart files by default.\n") + + string("Note that backward compatibility for ASCII restart files is\n") + + string("possible with the READ_BINARY_RESTART option."), + CURRENT_FUNCTION); } MPI_File_close(&fhw); #endif - restart_file.open(filename.data(), ios::in); - if (restart_file.fail()) { - SU2_MPI::Error(string("There is no adjoint restart file ") + filename, CURRENT_FUNCTION); - } - - /*--- The first line is the header ---*/ - - getline (restart_file, text_line); + restart_file.open(filename.data(), ios::in); + if (restart_file.fail()) { + SU2_MPI::Error(string("There is no adjoint restart file ") + filename, CURRENT_FUNCTION); + } - vector fields = PrintingToolbox::split(text_line, ','); + /*--- The first line is the header ---*/ - for (unsigned short iField = 0; iField < fields.size(); iField++){ - PrintingToolbox::trim(fields[iField]); - } + getline(restart_file, text_line); - std::vector::iterator itx = std::find(fields.begin(), fields.end(), "\"Sensitivity_x\""); - std::vector::iterator ity = std::find(fields.begin(), fields.end(), "\"Sensitivity_y\""); - std::vector::iterator itz = std::find(fields.begin(), fields.end(), "\"Sensitivity_z\""); + vector fields = PrintingToolbox::split(text_line, ','); - if (itx == fields.end()){ - SU2_MPI::Error("Sensitivity x not found in file.", CURRENT_FUNCTION); - } - if (ity ==fields.end()){ - SU2_MPI::Error("Sensitivity y not found in file.", CURRENT_FUNCTION); - } - if (nDim == 3){ - if (itz == fields.end()){ - SU2_MPI::Error("Sensitivity z not found in file.", CURRENT_FUNCTION); + for (unsigned short iField = 0; iField < fields.size(); iField++) { + PrintingToolbox::trim(fields[iField]); } - } - unsigned short sens_x_idx = std::distance(fields.begin(), itx); - unsigned short sens_y_idx = std::distance(fields.begin(), ity); - unsigned short sens_z_idx = 0; - if (nDim == 3) - sens_z_idx = std::distance(fields.begin(), itz); + std::vector::iterator itx = std::find(fields.begin(), fields.end(), "\"Sensitivity_x\""); + std::vector::iterator ity = std::find(fields.begin(), fields.end(), "\"Sensitivity_y\""); + std::vector::iterator itz = std::find(fields.begin(), fields.end(), "\"Sensitivity_z\""); + if (itx == fields.end()) { + SU2_MPI::Error("Sensitivity x not found in file.", CURRENT_FUNCTION); + } + if (ity == fields.end()) { + SU2_MPI::Error("Sensitivity y not found in file.", CURRENT_FUNCTION); + } + if (nDim == 3) { + if (itz == fields.end()) { + SU2_MPI::Error("Sensitivity z not found in file.", CURRENT_FUNCTION); + } + } - for (iPoint_Global = 0; iPoint_Global < GetGlobal_nPointDomain(); iPoint_Global++ ) { + unsigned short sens_x_idx = std::distance(fields.begin(), itx); + unsigned short sens_y_idx = std::distance(fields.begin(), ity); + unsigned short sens_z_idx = 0; + if (nDim == 3) sens_z_idx = std::distance(fields.begin(), itz); - getline (restart_file, text_line); + for (iPoint_Global = 0; iPoint_Global < GetGlobal_nPointDomain(); iPoint_Global++) { + getline(restart_file, text_line); - vector point_line = PrintingToolbox::split(text_line, ','); + vector point_line = PrintingToolbox::split(text_line, ','); - /*--- Retrieve local index. If this node from the restart file lives - on the current processor, we will load and instantiate the vars. ---*/ + /*--- Retrieve local index. If this node from the restart file lives + on the current processor, we will load and instantiate the vars. ---*/ - iPoint_Local = GetGlobal_to_Local_Point(iPoint_Global); + iPoint_Local = GetGlobal_to_Local_Point(iPoint_Global); - if (iPoint_Local > -1) { - Sensitivity(iPoint_Local,0) = PrintingToolbox::stod(point_line[sens_x_idx]); - Sensitivity(iPoint_Local,1) = PrintingToolbox::stod(point_line[sens_y_idx]); - if (nDim == 3) - Sensitivity(iPoint_Local,2) = PrintingToolbox::stod(point_line[sens_z_idx]); + if (iPoint_Local > -1) { + Sensitivity(iPoint_Local, 0) = PrintingToolbox::stod(point_line[sens_x_idx]); + Sensitivity(iPoint_Local, 1) = PrintingToolbox::stod(point_line[sens_y_idx]); + if (nDim == 3) Sensitivity(iPoint_Local, 2) = PrintingToolbox::stod(point_line[sens_z_idx]); + } } - } - - /*--- Read AoA sensitivity ---*/ + /*--- Read AoA sensitivity ---*/ - while (getline (restart_file, text_line)) { - position = text_line.find ("SENS_AOA=",0); - if (position != string::npos) { - text_line.erase (0,9); AoASens = atof(text_line.c_str()); - config->SetAoA_Sens(AoASens); + while (getline(restart_file, text_line)) { + position = text_line.find("SENS_AOA=", 0); + if (position != string::npos) { + text_line.erase(0, 9); + AoASens = atof(text_line.c_str()); + config->SetAoA_Sens(AoASens); + } } - } - - restart_file.close(); + restart_file.close(); } - } -void CPhysicalGeometry::ReadUnorderedSensitivity(CConfig *config) { - +void CPhysicalGeometry::ReadUnorderedSensitivity(CConfig* config) { /*--- This routine makes SU2_DOT more interoperable with other packages so that folks can customize their workflows. For example, one may want to compute flow and adjoint with package A, deform the mesh @@ -9168,7 +8763,7 @@ void CPhysicalGeometry::ReadUnorderedSensitivity(CConfig *config) { unsigned long iPoint, pointID; unsigned long unmatched = 0, iPoint_Found = 0, iPoint_Ext = 0; - su2double Coor_External[3] = {0.0,0.0,0.0}, Sens_External[3] = {0.0,0.0,0.0}; + su2double Coor_External[3] = {0.0, 0.0, 0.0}, Sens_External[3] = {0.0, 0.0, 0.0}; su2double dist; int rankID; @@ -9176,26 +8771,24 @@ void CPhysicalGeometry::ReadUnorderedSensitivity(CConfig *config) { ifstream external_file; ofstream sens_file; - if (rank == MASTER_NODE) - cout << "Parsing unordered ASCII volume sensitivity file."<< endl; + if (rank == MASTER_NODE) cout << "Parsing unordered ASCII volume sensitivity file." << endl; /*--- Allocate space for the sensitivity and initialize. ---*/ - Sensitivity.resize(nPoint,nDim) = su2double(0.0); + Sensitivity.resize(nPoint, nDim) = su2double(0.0); /*--- Get the filename for the unordered ASCII sensitivity file input. ---*/ filename = config->GetDV_Unordered_Sens_Filename(); external_file.open(filename.data(), ios::in); if (external_file.fail()) { - SU2_MPI::Error(string("There is no unordered ASCII sensitivity file ") + - filename, CURRENT_FUNCTION); + SU2_MPI::Error(string("There is no unordered ASCII sensitivity file ") + filename, CURRENT_FUNCTION); } /*--- Allocate the vectors to hold boundary node coordinates and its local ID. ---*/ - vector Coords(nDim*nPointDomain); + vector Coords(nDim * nPointDomain); vector PointIDs(nPointDomain); /*--- Retrieve and store the coordinates of owned interior nodes @@ -9203,39 +8796,33 @@ void CPhysicalGeometry::ReadUnorderedSensitivity(CConfig *config) { for (iPoint = 0; iPoint < nPointDomain; iPoint++) { PointIDs[iPoint] = iPoint; - for (iDim = 0; iDim < nDim; iDim++) - Coords[iPoint*nDim + iDim] = nodes->GetCoord(iPoint, iDim); + for (iDim = 0; iDim < nDim; iDim++) Coords[iPoint * nDim + iDim] = nodes->GetCoord(iPoint, iDim); } /*--- Build the ADT of all interior nodes. ---*/ - CADTPointsOnlyClass VertexADT(nDim, nPointDomain, - Coords.data(), PointIDs.data(), true); + CADTPointsOnlyClass VertexADT(nDim, nPointDomain, Coords.data(), PointIDs.data(), true); /*--- Loop over all interior mesh nodes owned by this rank and find the matching point with minimum distance. Once we have the match, store the sensitivities from the file for that node. ---*/ if (VertexADT.IsEmpty()) { - SU2_MPI::Error("No external points given to ADT.", CURRENT_FUNCTION); } else { - /*--- Read the input sensitivity file and locate the point matches using the ADT search, on a line-by-line basis. ---*/ - iPoint_Found = 0; iPoint_Ext = 0; - while (getline (external_file, text_line)) { - + iPoint_Found = 0; + iPoint_Ext = 0; + while (getline(external_file, text_line)) { /*--- First, check that the line has 6 entries, otherwise throw out. ---*/ istringstream point_line(text_line); - vector tokens((istream_iterator(point_line)), - istream_iterator()); + vector tokens((istream_iterator(point_line)), istream_iterator()); if (tokens.size() == 6) { - istringstream point_line(text_line); /*--- Get the coordinates and sensitivity for this line. ---*/ @@ -9246,15 +8833,12 @@ void CPhysicalGeometry::ReadUnorderedSensitivity(CConfig *config) { /*--- Locate the nearest node to this external point. If it is on our rank, then store the sensitivity value. ---*/ - VertexADT.DetermineNearestNode(&Coor_External[0], dist, - pointID, rankID); + VertexADT.DetermineNearestNode(&Coor_External[0], dist, pointID, rankID); if (rankID == rank) { - /*--- Store the sensitivities at the matched local node. ---*/ - for (iDim = 0; iDim < nDim; iDim++) - Sensitivity(pointID,iDim) = Sens_External[iDim]; + for (iDim = 0; iDim < nDim; iDim++) Sensitivity(pointID, iDim) = Sens_External[iDim]; /*--- Keep track of how many points we match. ---*/ @@ -9263,13 +8847,11 @@ void CPhysicalGeometry::ReadUnorderedSensitivity(CConfig *config) { /*--- Keep track of points with poor matches for reporting. ---*/ if (dist > 1e-10) unmatched++; - } /*--- Increment counter for total points in the external file. ---*/ iPoint_Ext++; - } } @@ -9282,56 +8864,60 @@ void CPhysicalGeometry::ReadUnorderedSensitivity(CConfig *config) { if ((iPoint_Ext < GetGlobal_nPointDomain()) && (rank == MASTER_NODE)) { sens_file.open(config->GetDV_Unordered_Sens_Filename().data(), ios::out); sens_file.close(); - SU2_MPI::Error("Not enough points in the input sensitivity file.", - CURRENT_FUNCTION); + SU2_MPI::Error("Not enough points in the input sensitivity file.", CURRENT_FUNCTION); } /*--- Check for points with a poor match and report the count. ---*/ - unsigned long myUnmatched = unmatched; unmatched = 0; - SU2_MPI::Allreduce(&myUnmatched, &unmatched, 1, - MPI_UNSIGNED_LONG, MPI_SUM, SU2_MPI::GetComm()); + unsigned long myUnmatched = unmatched; + unmatched = 0; + SU2_MPI::Allreduce(&myUnmatched, &unmatched, 1, MPI_UNSIGNED_LONG, MPI_SUM, SU2_MPI::GetComm()); if ((unmatched > 0) && (rank == MASTER_NODE)) { cout << " Warning: there are " << unmatched; cout << " points with a match distance > 1e-10." << endl; } - } - } -void CPhysicalGeometry::Check_Periodicity(CConfig *config) { - +void CPhysicalGeometry::Check_Periodicity(CConfig* config) { /*--- Check for the presence of any periodic BCs and disable multigrid for now if found. ---*/ if ((config->GetnMarker_Periodic() != 0) && (config->GetnMGLevels() > 0)) { - if (rank == MASTER_NODE) - cout << "WARNING: Periodicity has been detected. Disabling multigrid. "<< endl; + if (rank == MASTER_NODE) cout << "WARNING: Periodicity has been detected. Disabling multigrid. " << endl; config->SetMGLevels(0); } - } -su2double CPhysicalGeometry::Compute_MaxThickness(su2double *Plane_P0, su2double *Plane_Normal, CConfig *config, vector &Xcoord_Airfoil, - vector &Ycoord_Airfoil, vector &Zcoord_Airfoil) { - +su2double CPhysicalGeometry::Compute_MaxThickness(su2double* Plane_P0, su2double* Plane_Normal, CConfig* config, + vector& Xcoord_Airfoil, vector& Ycoord_Airfoil, + vector& Zcoord_Airfoil) { unsigned long iVertex, jVertex, Trailing_Point, Leading_Point; - su2double Normal[3], Tangent[3], BiNormal[3], auxXCoord, auxYCoord, auxZCoord, zp1, zpn, MaxThickness_Value = 0, Thickness, Length, Xcoord_Trailing, Ycoord_Trailing, Zcoord_Trailing, ValCos, ValSin, XValue, ZValue, MaxDistance, Distance, AoA; - vector Xcoord, Ycoord, Zcoord, Xcoord_Normal, Ycoord_Normal, Zcoord_Normal, Xcoord_Airfoil_, Ycoord_Airfoil_, Zcoord_Airfoil_; + su2double Normal[3], Tangent[3], BiNormal[3], auxXCoord, auxYCoord, auxZCoord, zp1, zpn, + MaxThickness_Value = 0, Thickness, Length, Xcoord_Trailing, Ycoord_Trailing, Zcoord_Trailing, ValCos, ValSin, + XValue, ZValue, MaxDistance, Distance, AoA; + vector Xcoord, Ycoord, Zcoord, Xcoord_Normal, Ycoord_Normal, Zcoord_Normal, Xcoord_Airfoil_, + Ycoord_Airfoil_, Zcoord_Airfoil_; /*--- Find the leading and trailing edges and compute the angle of attack ---*/ - MaxDistance = 0.0; Trailing_Point = 0; Leading_Point = 0; + MaxDistance = 0.0; + Trailing_Point = 0; + Leading_Point = 0; for (iVertex = 1; iVertex < Xcoord_Airfoil.size(); iVertex++) { Distance = sqrt(pow(Xcoord_Airfoil[iVertex] - Xcoord_Airfoil[Trailing_Point], 2.0) + pow(Ycoord_Airfoil[iVertex] - Ycoord_Airfoil[Trailing_Point], 2.0) + pow(Zcoord_Airfoil[iVertex] - Zcoord_Airfoil[Trailing_Point], 2.0)); - if (MaxDistance < Distance) { MaxDistance = Distance; Leading_Point = iVertex; } + if (MaxDistance < Distance) { + MaxDistance = Distance; + Leading_Point = iVertex; + } } - AoA = atan((Zcoord_Airfoil[Leading_Point] - Zcoord_Airfoil[Trailing_Point]) / (Xcoord_Airfoil[Trailing_Point] - Xcoord_Airfoil[Leading_Point]))*180/PI_NUMBER; + AoA = atan((Zcoord_Airfoil[Leading_Point] - Zcoord_Airfoil[Trailing_Point]) / + (Xcoord_Airfoil[Trailing_Point] - Xcoord_Airfoil[Leading_Point])) * + 180 / PI_NUMBER; /*--- Translate to the origin ---*/ @@ -9347,67 +8933,78 @@ su2double CPhysicalGeometry::Compute_MaxThickness(su2double *Plane_P0, su2double /*--- Rotate the airfoil ---*/ - ValCos = cos(AoA*PI_NUMBER/180.0); - ValSin = sin(AoA*PI_NUMBER/180.0); + ValCos = cos(AoA * PI_NUMBER / 180.0); + ValSin = sin(AoA * PI_NUMBER / 180.0); for (iVertex = 0; iVertex < Xcoord_Airfoil.size(); iVertex++) { XValue = Xcoord_Airfoil_[iVertex]; ZValue = Zcoord_Airfoil_[iVertex]; - Xcoord_Airfoil_[iVertex] = XValue*ValCos - ZValue*ValSin; - Zcoord_Airfoil_[iVertex] = ZValue*ValCos + XValue*ValSin; + Xcoord_Airfoil_[iVertex] = XValue * ValCos - ZValue * ValSin; + Zcoord_Airfoil_[iVertex] = ZValue * ValCos + XValue * ValSin; } /*--- Identify upper and lower side, and store the value of the normal --*/ for (iVertex = 1; iVertex < Xcoord_Airfoil_.size(); iVertex++) { - Tangent[0] = Xcoord_Airfoil_[iVertex] - Xcoord_Airfoil_[iVertex-1]; - Tangent[1] = Ycoord_Airfoil_[iVertex] - Ycoord_Airfoil_[iVertex-1]; - Tangent[2] = Zcoord_Airfoil_[iVertex] - Zcoord_Airfoil_[iVertex-1]; + Tangent[0] = Xcoord_Airfoil_[iVertex] - Xcoord_Airfoil_[iVertex - 1]; + Tangent[1] = Ycoord_Airfoil_[iVertex] - Ycoord_Airfoil_[iVertex - 1]; + Tangent[2] = Zcoord_Airfoil_[iVertex] - Zcoord_Airfoil_[iVertex - 1]; Length = sqrt(pow(Tangent[0], 2.0) + pow(Tangent[1], 2.0) + pow(Tangent[2], 2.0)); - Tangent[0] /= Length; Tangent[1] /= Length; Tangent[2] /= Length; + Tangent[0] /= Length; + Tangent[1] /= Length; + Tangent[2] /= Length; BiNormal[0] = Plane_Normal[0]; BiNormal[1] = Plane_Normal[1]; BiNormal[2] = Plane_Normal[2]; Length = sqrt(pow(BiNormal[0], 2.0) + pow(BiNormal[1], 2.0) + pow(BiNormal[2], 2.0)); - BiNormal[0] /= Length; BiNormal[1] /= Length; BiNormal[2] /= Length; + BiNormal[0] /= Length; + BiNormal[1] /= Length; + BiNormal[2] /= Length; - Normal[0] = Tangent[1]*BiNormal[2] - Tangent[2]*BiNormal[1]; - Normal[1] = Tangent[2]*BiNormal[0] - Tangent[0]*BiNormal[2]; - Normal[2] = Tangent[0]*BiNormal[1] - Tangent[1]*BiNormal[0]; + Normal[0] = Tangent[1] * BiNormal[2] - Tangent[2] * BiNormal[1]; + Normal[1] = Tangent[2] * BiNormal[0] - Tangent[0] * BiNormal[2]; + Normal[2] = Tangent[0] * BiNormal[1] - Tangent[1] * BiNormal[0]; - Xcoord_Normal.push_back(Normal[0]); Ycoord_Normal.push_back(Normal[1]); Zcoord_Normal.push_back(Normal[2]); + Xcoord_Normal.push_back(Normal[0]); + Ycoord_Normal.push_back(Normal[1]); + Zcoord_Normal.push_back(Normal[2]); unsigned short index = 2; /*--- Removing the trailing edge from list of points that we are going to use in the interpolation, to be sure that a blunt trailing edge do not affect the interpolation ---*/ - if ((Normal[index] >= 0.0) && (fabs(Xcoord_Airfoil_[iVertex]) > MaxDistance*0.01)) { + if ((Normal[index] >= 0.0) && (fabs(Xcoord_Airfoil_[iVertex]) > MaxDistance * 0.01)) { Xcoord.push_back(Xcoord_Airfoil_[iVertex]); Ycoord.push_back(Ycoord_Airfoil_[iVertex]); Zcoord.push_back(Zcoord_Airfoil_[iVertex]); } - } /*--- Order the arrays using the X component ---*/ for (iVertex = 0; iVertex < Xcoord.size(); iVertex++) { for (jVertex = 0; jVertex < Xcoord.size() - 1 - iVertex; jVertex++) { - if (Xcoord[jVertex] > Xcoord[jVertex+1]) { - auxXCoord = Xcoord[jVertex]; Xcoord[jVertex] = Xcoord[jVertex+1]; Xcoord[jVertex+1] = auxXCoord; - auxYCoord = Ycoord[jVertex]; Ycoord[jVertex] = Ycoord[jVertex+1]; Ycoord[jVertex+1] = auxYCoord; - auxZCoord = Zcoord[jVertex]; Zcoord[jVertex] = Zcoord[jVertex+1]; Zcoord[jVertex+1] = auxZCoord; + if (Xcoord[jVertex] > Xcoord[jVertex + 1]) { + auxXCoord = Xcoord[jVertex]; + Xcoord[jVertex] = Xcoord[jVertex + 1]; + Xcoord[jVertex + 1] = auxXCoord; + auxYCoord = Ycoord[jVertex]; + Ycoord[jVertex] = Ycoord[jVertex + 1]; + Ycoord[jVertex + 1] = auxYCoord; + auxZCoord = Zcoord[jVertex]; + Zcoord[jVertex] = Zcoord[jVertex + 1]; + Zcoord[jVertex + 1] = auxZCoord; } } } const auto n = Xcoord.size(); if (n > 1) { - zp1 = (Zcoord[1]-Zcoord[0])/(Xcoord[1]-Xcoord[0]); - zpn = (Zcoord[n-1]-Zcoord[n-2])/(Xcoord[n-1]-Xcoord[n-2]); + zp1 = (Zcoord[1] - Zcoord[0]) / (Xcoord[1] - Xcoord[0]); + zpn = (Zcoord[n - 1] - Zcoord[n - 2]) / (Xcoord[n - 1] - Xcoord[n - 2]); CCubicSpline spline(Xcoord, Zcoord, CCubicSpline::FIRST, zp1, CCubicSpline::FIRST, zpn); @@ -9418,33 +9015,34 @@ su2double CPhysicalGeometry::Compute_MaxThickness(su2double *Plane_P0, su2double for (iVertex = 0; iVertex < Xcoord_Airfoil_.size(); iVertex++) { if (Zcoord_Normal[iVertex] < 0.0) { Thickness = fabs(Zcoord_Airfoil_[iVertex] - spline(Xcoord_Airfoil_[iVertex])); - if (Thickness > MaxThickness_Value) { MaxThickness_Value = Thickness; } + if (Thickness > MaxThickness_Value) { + MaxThickness_Value = Thickness; + } } } + } else { + MaxThickness_Value = 0.0; } - else { MaxThickness_Value = 0.0; } return MaxThickness_Value; - } -su2double CPhysicalGeometry::Compute_Dihedral(su2double *LeadingEdge_im1, su2double *TrailingEdge_im1, - su2double *LeadingEdge_i, su2double *TrailingEdge_i) { - - // su2double Dihedral_Leading = atan((LeadingEdge_i[2] - LeadingEdge_im1[2]) / (LeadingEdge_i[1] - LeadingEdge_im1[1]))*180/PI_NUMBER; - su2double Dihedral_Trailing = atan((TrailingEdge_i[2] - TrailingEdge_im1[2]) / (TrailingEdge_i[1] - TrailingEdge_im1[1]))*180/PI_NUMBER; +su2double CPhysicalGeometry::Compute_Dihedral(su2double* LeadingEdge_im1, su2double* TrailingEdge_im1, + su2double* LeadingEdge_i, su2double* TrailingEdge_i) { + // su2double Dihedral_Leading = atan((LeadingEdge_i[2] - LeadingEdge_im1[2]) / (LeadingEdge_i[1] - + // LeadingEdge_im1[1]))*180/PI_NUMBER; + su2double Dihedral_Trailing = + atan((TrailingEdge_i[2] - TrailingEdge_im1[2]) / (TrailingEdge_i[1] - TrailingEdge_im1[1])) * 180 / PI_NUMBER; // su2double Dihedral = 0.5*(Dihedral_Leading + Dihedral_Trailing); return Dihedral_Trailing; - } -su2double CPhysicalGeometry::Compute_Curvature(su2double *LeadingEdge_im1, su2double *TrailingEdge_im1, - su2double *LeadingEdge_i, su2double *TrailingEdge_i, - su2double *LeadingEdge_ip1, su2double *TrailingEdge_ip1) { - - su2double A[2], B[2], C[2], BC[2], AB[2], AC[2], BC_MOD, AB_MOD, AC_MOD, AB_CROSS_AC; +su2double CPhysicalGeometry::Compute_Curvature(su2double* LeadingEdge_im1, su2double* TrailingEdge_im1, + su2double* LeadingEdge_i, su2double* TrailingEdge_i, + su2double* LeadingEdge_ip1, su2double* TrailingEdge_ip1) { + su2double A[2], B[2], C[2], BC[2], AB[2], AC[2], BC_MOD, AB_MOD, AC_MOD, AB_CROSS_AC; // A[0] = LeadingEdge_im1[1]; A[1] = LeadingEdge_im1[2]; // B[0] = LeadingEdge_i[1]; B[1] = LeadingEdge_i[2]; @@ -9460,64 +9058,82 @@ su2double CPhysicalGeometry::Compute_Curvature(su2double *LeadingEdge_im1, su2do // su2double Curvature_Leading = fabs(1.0/(0.5*BC_MOD*AB_MOD*AC_MOD/AB_CROSS_AC)); - A[0] = TrailingEdge_im1[1]; A[1] = TrailingEdge_im1[2]; - B[0] = TrailingEdge_i[1]; B[1] = TrailingEdge_i[2]; - C[0] = TrailingEdge_ip1[1]; C[1] = TrailingEdge_ip1[2]; - - BC[0] = C[0] - B[0]; BC[1] = C[1] - B[1]; - AB[0] = B[0] - A[0]; AB[1] = B[1] - A[1]; - AC[0] = C[0] - A[0]; AC[1] = C[1] - A[1]; - BC_MOD = sqrt(BC[0]*BC[0] + BC[1]*BC[1] ); - AB_MOD = sqrt(AB[0]*AB[0] + AB[1]*AB[1] ); - AC_MOD = sqrt(AC[0]*AC[0] + AC[1]*AC[1] ); - AB_CROSS_AC = AB[0]* AC[1] - AB[1]* AC[0]; - - su2double Curvature_Trailing = fabs(1.0/(0.5*BC_MOD*AB_MOD*AC_MOD/AB_CROSS_AC)); + A[0] = TrailingEdge_im1[1]; + A[1] = TrailingEdge_im1[2]; + B[0] = TrailingEdge_i[1]; + B[1] = TrailingEdge_i[2]; + C[0] = TrailingEdge_ip1[1]; + C[1] = TrailingEdge_ip1[2]; + + BC[0] = C[0] - B[0]; + BC[1] = C[1] - B[1]; + AB[0] = B[0] - A[0]; + AB[1] = B[1] - A[1]; + AC[0] = C[0] - A[0]; + AC[1] = C[1] - A[1]; + BC_MOD = sqrt(BC[0] * BC[0] + BC[1] * BC[1]); + AB_MOD = sqrt(AB[0] * AB[0] + AB[1] * AB[1]); + AC_MOD = sqrt(AC[0] * AC[0] + AC[1] * AC[1]); + AB_CROSS_AC = AB[0] * AC[1] - AB[1] * AC[0]; + + su2double Curvature_Trailing = fabs(1.0 / (0.5 * BC_MOD * AB_MOD * AC_MOD / AB_CROSS_AC)); // su2double Curvature = 0.5*(Curvature_Leading + Curvature_Trailing); return Curvature_Trailing; - } -su2double CPhysicalGeometry::Compute_Twist(su2double *Plane_P0, su2double *Plane_Normal, vector &Xcoord_Airfoil, - vector &Ycoord_Airfoil, vector &Zcoord_Airfoil) { +su2double CPhysicalGeometry::Compute_Twist(su2double* Plane_P0, su2double* Plane_Normal, + vector& Xcoord_Airfoil, vector& Ycoord_Airfoil, + vector& Zcoord_Airfoil) { unsigned long iVertex, Trailing_Point, Leading_Point; su2double MaxDistance, Distance, Twist = 0.0; /*--- Find the leading and trailing edges and compute the angle of attack ---*/ - MaxDistance = 0.0; Trailing_Point = 0; Leading_Point = 0; + MaxDistance = 0.0; + Trailing_Point = 0; + Leading_Point = 0; for (iVertex = 1; iVertex < Xcoord_Airfoil.size(); iVertex++) { Distance = sqrt(pow(Xcoord_Airfoil[iVertex] - Xcoord_Airfoil[Trailing_Point], 2.0) + pow(Ycoord_Airfoil[iVertex] - Ycoord_Airfoil[Trailing_Point], 2.0) + pow(Zcoord_Airfoil[iVertex] - Zcoord_Airfoil[Trailing_Point], 2.0)); - if (MaxDistance < Distance) { MaxDistance = Distance; Leading_Point = iVertex; } + if (MaxDistance < Distance) { + MaxDistance = Distance; + Leading_Point = iVertex; + } } - Twist = atan((Zcoord_Airfoil[Leading_Point] - Zcoord_Airfoil[Trailing_Point]) / (Xcoord_Airfoil[Trailing_Point] - Xcoord_Airfoil[Leading_Point]))*180/PI_NUMBER; + Twist = atan((Zcoord_Airfoil[Leading_Point] - Zcoord_Airfoil[Trailing_Point]) / + (Xcoord_Airfoil[Trailing_Point] - Xcoord_Airfoil[Leading_Point])) * + 180 / PI_NUMBER; return Twist; - } -void CPhysicalGeometry::Compute_Wing_LeadingTrailing(su2double *LeadingEdge, su2double *TrailingEdge, su2double *Plane_P0, su2double *Plane_Normal, - vector &Xcoord_Airfoil, vector &Ycoord_Airfoil, vector &Zcoord_Airfoil) { - +void CPhysicalGeometry::Compute_Wing_LeadingTrailing(su2double* LeadingEdge, su2double* TrailingEdge, + su2double* Plane_P0, su2double* Plane_Normal, + vector& Xcoord_Airfoil, + vector& Ycoord_Airfoil, + vector& Zcoord_Airfoil) { unsigned long iVertex, Trailing_Point, Leading_Point; su2double MaxDistance, Distance; /*--- Find the leading and trailing edges and compute the angle of attack ---*/ - MaxDistance = 0.0; Trailing_Point = 0; Leading_Point = 0; + MaxDistance = 0.0; + Trailing_Point = 0; + Leading_Point = 0; for (iVertex = 1; iVertex < Xcoord_Airfoil.size(); iVertex++) { - Distance = sqrt(pow(Xcoord_Airfoil[iVertex] - Xcoord_Airfoil[Trailing_Point], 2.0) + pow(Ycoord_Airfoil[iVertex] - Ycoord_Airfoil[Trailing_Point], 2.0) + pow(Zcoord_Airfoil[iVertex] - Zcoord_Airfoil[Trailing_Point], 2.0)); - if (MaxDistance < Distance) { MaxDistance = Distance; Leading_Point = iVertex; } + if (MaxDistance < Distance) { + MaxDistance = Distance; + Leading_Point = iVertex; + } } LeadingEdge[0] = Xcoord_Airfoil[Leading_Point]; @@ -9527,84 +9143,101 @@ void CPhysicalGeometry::Compute_Wing_LeadingTrailing(su2double *LeadingEdge, su2 TrailingEdge[0] = Xcoord_Airfoil[Trailing_Point]; TrailingEdge[1] = Ycoord_Airfoil[Trailing_Point]; TrailingEdge[2] = Zcoord_Airfoil[Trailing_Point]; - } -void CPhysicalGeometry::Compute_Fuselage_LeadingTrailing(su2double *LeadingEdge, su2double *TrailingEdge, su2double *Plane_P0, su2double *Plane_Normal, - vector &Xcoord_Airfoil, vector &Ycoord_Airfoil, vector &Zcoord_Airfoil) { - +void CPhysicalGeometry::Compute_Fuselage_LeadingTrailing(su2double* LeadingEdge, su2double* TrailingEdge, + su2double* Plane_P0, su2double* Plane_Normal, + vector& Xcoord_Airfoil, + vector& Ycoord_Airfoil, + vector& Zcoord_Airfoil) { unsigned long iVertex, Trailing_Point, Leading_Point; su2double MaxDistance, Distance; - MaxDistance = 0.0; Trailing_Point = 0; Leading_Point = 0; + MaxDistance = 0.0; + Trailing_Point = 0; + Leading_Point = 0; for (iVertex = 1; iVertex < Xcoord_Airfoil.size(); iVertex++) { Distance = sqrt(pow(Xcoord_Airfoil[iVertex] - Xcoord_Airfoil[Trailing_Point], 2.0)); - if (MaxDistance < Distance) { MaxDistance = Distance; Leading_Point = iVertex; } + if (MaxDistance < Distance) { + MaxDistance = Distance; + Leading_Point = iVertex; + } } LeadingEdge[0] = Xcoord_Airfoil[Leading_Point]; LeadingEdge[1] = Ycoord_Airfoil[Leading_Point]; LeadingEdge[2] = Zcoord_Airfoil[Leading_Point]; - MaxDistance = 0.0; Trailing_Point = 0; Leading_Point = 0; + MaxDistance = 0.0; + Trailing_Point = 0; + Leading_Point = 0; for (iVertex = 1; iVertex < Zcoord_Airfoil.size(); iVertex++) { Distance = sqrt(pow(Zcoord_Airfoil[iVertex] - Zcoord_Airfoil[Trailing_Point], 2.0)); - if (MaxDistance < Distance) { MaxDistance = Distance; Leading_Point = iVertex; } + if (MaxDistance < Distance) { + MaxDistance = Distance; + Leading_Point = iVertex; + } } - TrailingEdge[0] = 0.5*(Xcoord_Airfoil[Trailing_Point]+Xcoord_Airfoil[Leading_Point]); - TrailingEdge[1] = 0.5*(Ycoord_Airfoil[Trailing_Point]+Ycoord_Airfoil[Leading_Point]); - TrailingEdge[2] = 0.5*(Zcoord_Airfoil[Trailing_Point]+Zcoord_Airfoil[Leading_Point]); - + TrailingEdge[0] = 0.5 * (Xcoord_Airfoil[Trailing_Point] + Xcoord_Airfoil[Leading_Point]); + TrailingEdge[1] = 0.5 * (Ycoord_Airfoil[Trailing_Point] + Ycoord_Airfoil[Leading_Point]); + TrailingEdge[2] = 0.5 * (Zcoord_Airfoil[Trailing_Point] + Zcoord_Airfoil[Leading_Point]); } -su2double CPhysicalGeometry::Compute_Chord(su2double *Plane_P0, su2double *Plane_Normal, vector &Xcoord_Airfoil, - vector &Ycoord_Airfoil, vector &Zcoord_Airfoil) { +su2double CPhysicalGeometry::Compute_Chord(su2double* Plane_P0, su2double* Plane_Normal, + vector& Xcoord_Airfoil, vector& Ycoord_Airfoil, + vector& Zcoord_Airfoil) { unsigned long iVertex, Trailing_Point; su2double MaxDistance, Distance, Chord = 0.0; /*--- Find the leading and trailing edges and compute the angle of attack ---*/ - MaxDistance = 0.0; Trailing_Point = 0; + MaxDistance = 0.0; + Trailing_Point = 0; for (iVertex = 1; iVertex < Xcoord_Airfoil.size(); iVertex++) { - Distance = sqrt(pow(Xcoord_Airfoil[iVertex] - Xcoord_Airfoil[Trailing_Point], 2.0) + pow(Ycoord_Airfoil[iVertex] - Ycoord_Airfoil[Trailing_Point], 2.0) + pow(Zcoord_Airfoil[iVertex] - Zcoord_Airfoil[Trailing_Point], 2.0)); - if (MaxDistance < Distance) { MaxDistance = Distance; } + if (MaxDistance < Distance) { + MaxDistance = Distance; + } } Chord = MaxDistance; return Chord; - } -su2double CPhysicalGeometry::Compute_Width(su2double *Plane_P0, su2double *Plane_Normal, vector &Xcoord_Airfoil, - vector &Ycoord_Airfoil, vector &Zcoord_Airfoil) { - +su2double CPhysicalGeometry::Compute_Width(su2double* Plane_P0, su2double* Plane_Normal, + vector& Xcoord_Airfoil, vector& Ycoord_Airfoil, + vector& Zcoord_Airfoil) { unsigned long iVertex, Trailing_Point; su2double MaxDistance, Distance, Width = 0.0; - MaxDistance = 0.0; Trailing_Point = 0; + MaxDistance = 0.0; + Trailing_Point = 0; for (iVertex = 1; iVertex < Xcoord_Airfoil.size(); iVertex++) { Distance = fabs(Xcoord_Airfoil[iVertex] - Xcoord_Airfoil[Trailing_Point]); - if (MaxDistance < Distance) { MaxDistance = Distance; } + if (MaxDistance < Distance) { + MaxDistance = Distance; + } } Width = MaxDistance; return Width; - } -su2double CPhysicalGeometry::Compute_WaterLineWidth(su2double *Plane_P0, su2double *Plane_Normal, CConfig *config, - vector &Xcoord_Airfoil, vector &Ycoord_Airfoil, vector &Zcoord_Airfoil) { - +su2double CPhysicalGeometry::Compute_WaterLineWidth(su2double* Plane_P0, su2double* Plane_Normal, CConfig* config, + vector& Xcoord_Airfoil, + vector& Ycoord_Airfoil, + vector& Zcoord_Airfoil) { unsigned long iVertex, Trailing_Point; su2double MinDistance, Distance, WaterLineWidth = 0.0; su2double WaterLine = config->GetGeo_Waterline_Location(); - MinDistance = 1E10; WaterLineWidth = 0; Trailing_Point = 0; + MinDistance = 1E10; + WaterLineWidth = 0; + Trailing_Point = 0; for (iVertex = 0; iVertex < Xcoord_Airfoil.size(); iVertex++) { Distance = fabs(Zcoord_Airfoil[iVertex] - WaterLine); if (Distance < MinDistance) { @@ -9614,91 +9247,119 @@ su2double CPhysicalGeometry::Compute_WaterLineWidth(su2double *Plane_P0, su2doub } return WaterLineWidth; - } -su2double CPhysicalGeometry::Compute_Height(su2double *Plane_P0, su2double *Plane_Normal, vector &Xcoord_Airfoil, - vector &Ycoord_Airfoil, vector &Zcoord_Airfoil) { - +su2double CPhysicalGeometry::Compute_Height(su2double* Plane_P0, su2double* Plane_Normal, + vector& Xcoord_Airfoil, vector& Ycoord_Airfoil, + vector& Zcoord_Airfoil) { unsigned long iVertex, Trailing_Point; su2double MaxDistance, Distance, Height = 0.0; - MaxDistance = 0.0; Trailing_Point = 0; + MaxDistance = 0.0; + Trailing_Point = 0; for (iVertex = 1; iVertex < Zcoord_Airfoil.size(); iVertex++) { Distance = sqrt(pow(Zcoord_Airfoil[iVertex] - Zcoord_Airfoil[Trailing_Point], 2.0)); - if (MaxDistance < Distance) { MaxDistance = Distance; } + if (MaxDistance < Distance) { + MaxDistance = Distance; + } } Height = MaxDistance; return Height; - } -su2double CPhysicalGeometry::Compute_LERadius(su2double *Plane_P0, su2double *Plane_Normal, vector &Xcoord_Airfoil, - vector &Ycoord_Airfoil, vector &Zcoord_Airfoil) { - +su2double CPhysicalGeometry::Compute_LERadius(su2double* Plane_P0, su2double* Plane_Normal, + vector& Xcoord_Airfoil, vector& Ycoord_Airfoil, + vector& Zcoord_Airfoil) { unsigned long iVertex, Trailing_Point, Leading_Point; su2double MaxDistance, Distance, LERadius = 0.0, X1, X2, X3, Y1, Y2, Y3, Ma, Mb, Xc, Yc, Radius; /*--- Find the leading and trailing edges and compute the radius of curvature ---*/ - MaxDistance = 0.0; Trailing_Point = 0; Leading_Point = 0; + MaxDistance = 0.0; + Trailing_Point = 0; + Leading_Point = 0; for (iVertex = 1; iVertex < Xcoord_Airfoil.size(); iVertex++) { - Distance = sqrt(pow(Xcoord_Airfoil[iVertex] - Xcoord_Airfoil[Trailing_Point], 2.0) + pow(Ycoord_Airfoil[iVertex] - Ycoord_Airfoil[Trailing_Point], 2.0) + pow(Zcoord_Airfoil[iVertex] - Zcoord_Airfoil[Trailing_Point], 2.0)); - if (MaxDistance < Distance) { MaxDistance = Distance; Leading_Point = iVertex; } + if (MaxDistance < Distance) { + MaxDistance = Distance; + Leading_Point = iVertex; + } } - X1 = Xcoord_Airfoil[Leading_Point-3]; - Y1 = Zcoord_Airfoil[Leading_Point-3]; + X1 = Xcoord_Airfoil[Leading_Point - 3]; + Y1 = Zcoord_Airfoil[Leading_Point - 3]; X2 = Xcoord_Airfoil[Leading_Point]; Y2 = Zcoord_Airfoil[Leading_Point]; - X3 = Xcoord_Airfoil[Leading_Point+3]; - Y3 = Zcoord_Airfoil[Leading_Point+3]; + X3 = Xcoord_Airfoil[Leading_Point + 3]; + Y3 = Zcoord_Airfoil[Leading_Point + 3]; - if (X2 != X1) Ma = (Y2-Y1) / (X2-X1); else Ma = 0.0; - if (X3 != X2) Mb = (Y3-Y2) / (X3-X2); else Mb = 0.0; + if (X2 != X1) + Ma = (Y2 - Y1) / (X2 - X1); + else + Ma = 0.0; + if (X3 != X2) + Mb = (Y3 - Y2) / (X3 - X2); + else + Mb = 0.0; - if (Mb != Ma) Xc = (Ma*Mb*(Y1-Y3)+Mb*(X1+X2)-Ma*(X2+X3))/(2.0*(Mb-Ma)); else Xc = 0.0; - if (Ma != 0.0) Yc = -(1.0/Ma)*(Xc-0.5*(X1+X2))+0.5*(Y1+Y2); else Yc = 0.0; + if (Mb != Ma) + Xc = (Ma * Mb * (Y1 - Y3) + Mb * (X1 + X2) - Ma * (X2 + X3)) / (2.0 * (Mb - Ma)); + else + Xc = 0.0; + if (Ma != 0.0) + Yc = -(1.0 / Ma) * (Xc - 0.5 * (X1 + X2)) + 0.5 * (Y1 + Y2); + else + Yc = 0.0; - Radius = sqrt((Xc-X1)*(Xc-X1)+(Yc-Y1)*(Yc-Y1)); - if (Radius != 0.0) LERadius = 1.0/Radius; else LERadius = 0.0; + Radius = sqrt((Xc - X1) * (Xc - X1) + (Yc - Y1) * (Yc - Y1)); + if (Radius != 0.0) + LERadius = 1.0 / Radius; + else + LERadius = 0.0; return LERadius; - } -su2double CPhysicalGeometry::Compute_Thickness(su2double *Plane_P0, su2double *Plane_Normal, su2double Location, CConfig *config, - vector &Xcoord_Airfoil, vector &Ycoord_Airfoil, vector &Zcoord_Airfoil, su2double &ZLoc) { - +su2double CPhysicalGeometry::Compute_Thickness(su2double* Plane_P0, su2double* Plane_Normal, su2double Location, + CConfig* config, vector& Xcoord_Airfoil, + vector& Ycoord_Airfoil, vector& Zcoord_Airfoil, + su2double& ZLoc) { unsigned long iVertex, jVertex, n_Upper, n_Lower, Trailing_Point, Leading_Point; - su2double Thickness_Location, Normal[3], Tangent[3], BiNormal[3], auxXCoord, auxYCoord, auxZCoord, Thickness_Value = 0.0, Length, - Xcoord_Trailing, Ycoord_Trailing, Zcoord_Trailing, ValCos, ValSin, XValue, ZValue, zp1, zpn, Chord, MaxDistance, Distance, AoA; + su2double Thickness_Location, Normal[3], Tangent[3], BiNormal[3], auxXCoord, auxYCoord, auxZCoord, + Thickness_Value = 0.0, Length, Xcoord_Trailing, Ycoord_Trailing, Zcoord_Trailing, ValCos, ValSin, XValue, ZValue, + zp1, zpn, Chord, MaxDistance, Distance, AoA; - vector Xcoord_Upper, Ycoord_Upper, Zcoord_Upper, Xcoord_Lower, Ycoord_Lower, Zcoord_Lower, - Xcoord_Normal, Ycoord_Normal, Zcoord_Normal, Xcoord_Airfoil_, Ycoord_Airfoil_, Zcoord_Airfoil_; + vector Xcoord_Upper, Ycoord_Upper, Zcoord_Upper, Xcoord_Lower, Ycoord_Lower, Zcoord_Lower, Xcoord_Normal, + Ycoord_Normal, Zcoord_Normal, Xcoord_Airfoil_, Ycoord_Airfoil_, Zcoord_Airfoil_; su2double Zcoord_Up, Zcoord_Down, ZLoc_, YLoc_; /*--- Find the leading and trailing edges and compute the angle of attack ---*/ - MaxDistance = 0.0; Trailing_Point = 0; Leading_Point = 0; + MaxDistance = 0.0; + Trailing_Point = 0; + Leading_Point = 0; for (iVertex = 1; iVertex < Xcoord_Airfoil.size(); iVertex++) { Distance = sqrt(pow(Xcoord_Airfoil[iVertex] - Xcoord_Airfoil[Trailing_Point], 2.0) + pow(Ycoord_Airfoil[iVertex] - Ycoord_Airfoil[Trailing_Point], 2.0) + pow(Zcoord_Airfoil[iVertex] - Zcoord_Airfoil[Trailing_Point], 2.0)); - if (MaxDistance < Distance) { MaxDistance = Distance; Leading_Point = iVertex; } + if (MaxDistance < Distance) { + MaxDistance = Distance; + Leading_Point = iVertex; + } } - AoA = atan((Zcoord_Airfoil[Leading_Point] - Zcoord_Airfoil[Trailing_Point]) / (Xcoord_Airfoil[Trailing_Point] - Xcoord_Airfoil[Leading_Point]))*180/PI_NUMBER; + AoA = atan((Zcoord_Airfoil[Leading_Point] - Zcoord_Airfoil[Trailing_Point]) / + (Xcoord_Airfoil[Trailing_Point] - Xcoord_Airfoil[Leading_Point])) * + 180 / PI_NUMBER; Chord = MaxDistance; /*--- Translate to the origin ---*/ @@ -9715,37 +9376,43 @@ su2double CPhysicalGeometry::Compute_Thickness(su2double *Plane_P0, su2double *P /*--- Rotate the airfoil ---*/ - ValCos = cos(AoA*PI_NUMBER/180.0); - ValSin = sin(AoA*PI_NUMBER/180.0); + ValCos = cos(AoA * PI_NUMBER / 180.0); + ValSin = sin(AoA * PI_NUMBER / 180.0); for (iVertex = 0; iVertex < Xcoord_Airfoil.size(); iVertex++) { XValue = Xcoord_Airfoil_[iVertex]; ZValue = Zcoord_Airfoil_[iVertex]; - Xcoord_Airfoil_[iVertex] = XValue*ValCos - ZValue*ValSin; - Zcoord_Airfoil_[iVertex] = ZValue*ValCos + XValue*ValSin; + Xcoord_Airfoil_[iVertex] = XValue * ValCos - ZValue * ValSin; + Zcoord_Airfoil_[iVertex] = ZValue * ValCos + XValue * ValSin; } /*--- Identify upper and lower side, and store the value of the normal --*/ for (iVertex = 1; iVertex < Xcoord_Airfoil_.size(); iVertex++) { - Tangent[0] = Xcoord_Airfoil_[iVertex] - Xcoord_Airfoil_[iVertex-1]; - Tangent[1] = Ycoord_Airfoil_[iVertex] - Ycoord_Airfoil_[iVertex-1]; - Tangent[2] = Zcoord_Airfoil_[iVertex] - Zcoord_Airfoil_[iVertex-1]; + Tangent[0] = Xcoord_Airfoil_[iVertex] - Xcoord_Airfoil_[iVertex - 1]; + Tangent[1] = Ycoord_Airfoil_[iVertex] - Ycoord_Airfoil_[iVertex - 1]; + Tangent[2] = Zcoord_Airfoil_[iVertex] - Zcoord_Airfoil_[iVertex - 1]; Length = sqrt(pow(Tangent[0], 2.0) + pow(Tangent[1], 2.0) + pow(Tangent[2], 2.0)); - Tangent[0] /= Length; Tangent[1] /= Length; Tangent[2] /= Length; + Tangent[0] /= Length; + Tangent[1] /= Length; + Tangent[2] /= Length; BiNormal[0] = Plane_Normal[0]; BiNormal[1] = Plane_Normal[1]; BiNormal[2] = Plane_Normal[2]; Length = sqrt(pow(BiNormal[0], 2.0) + pow(BiNormal[1], 2.0) + pow(BiNormal[2], 2.0)); - BiNormal[0] /= Length; BiNormal[1] /= Length; BiNormal[2] /= Length; + BiNormal[0] /= Length; + BiNormal[1] /= Length; + BiNormal[2] /= Length; - Normal[0] = Tangent[1]*BiNormal[2] - Tangent[2]*BiNormal[1]; - Normal[1] = Tangent[2]*BiNormal[0] - Tangent[0]*BiNormal[2]; - Normal[2] = Tangent[0]*BiNormal[1] - Tangent[1]*BiNormal[0]; + Normal[0] = Tangent[1] * BiNormal[2] - Tangent[2] * BiNormal[1]; + Normal[1] = Tangent[2] * BiNormal[0] - Tangent[0] * BiNormal[2]; + Normal[2] = Tangent[0] * BiNormal[1] - Tangent[1] * BiNormal[0]; - Xcoord_Normal.push_back(Normal[0]); Ycoord_Normal.push_back(Normal[1]); Zcoord_Normal.push_back(Normal[2]); + Xcoord_Normal.push_back(Normal[0]); + Ycoord_Normal.push_back(Normal[1]); + Zcoord_Normal.push_back(Normal[2]); unsigned short index = 2; @@ -9753,23 +9420,27 @@ su2double CPhysicalGeometry::Compute_Thickness(su2double *Plane_P0, su2double *P Xcoord_Upper.push_back(Xcoord_Airfoil_[iVertex]); Ycoord_Upper.push_back(Ycoord_Airfoil_[iVertex]); Zcoord_Upper.push_back(Zcoord_Airfoil_[iVertex]); - } - else { + } else { Xcoord_Lower.push_back(Xcoord_Airfoil_[iVertex]); Ycoord_Lower.push_back(Ycoord_Airfoil_[iVertex]); Zcoord_Lower.push_back(Zcoord_Airfoil_[iVertex]); } - } /*--- Order the arrays using the X component ---*/ for (iVertex = 0; iVertex < Xcoord_Upper.size(); iVertex++) { for (jVertex = 0; jVertex < Xcoord_Upper.size() - 1 - iVertex; jVertex++) { - if (Xcoord_Upper[jVertex] > Xcoord_Upper[jVertex+1]) { - auxXCoord = Xcoord_Upper[jVertex]; Xcoord_Upper[jVertex] = Xcoord_Upper[jVertex+1]; Xcoord_Upper[jVertex+1] = auxXCoord; - auxYCoord = Ycoord_Upper[jVertex]; Ycoord_Upper[jVertex] = Ycoord_Upper[jVertex+1]; Ycoord_Upper[jVertex+1] = auxYCoord; - auxZCoord = Zcoord_Upper[jVertex]; Zcoord_Upper[jVertex] = Zcoord_Upper[jVertex+1]; Zcoord_Upper[jVertex+1] = auxZCoord; + if (Xcoord_Upper[jVertex] > Xcoord_Upper[jVertex + 1]) { + auxXCoord = Xcoord_Upper[jVertex]; + Xcoord_Upper[jVertex] = Xcoord_Upper[jVertex + 1]; + Xcoord_Upper[jVertex + 1] = auxXCoord; + auxYCoord = Ycoord_Upper[jVertex]; + Ycoord_Upper[jVertex] = Ycoord_Upper[jVertex + 1]; + Ycoord_Upper[jVertex + 1] = auxYCoord; + auxZCoord = Zcoord_Upper[jVertex]; + Zcoord_Upper[jVertex] = Zcoord_Upper[jVertex + 1]; + Zcoord_Upper[jVertex + 1] = auxZCoord; } } } @@ -9778,10 +9449,16 @@ su2double CPhysicalGeometry::Compute_Thickness(su2double *Plane_P0, su2double *P for (iVertex = 0; iVertex < Xcoord_Lower.size(); iVertex++) { for (jVertex = 0; jVertex < Xcoord_Lower.size() - 1 - iVertex; jVertex++) { - if (Xcoord_Lower[jVertex] > Xcoord_Lower[jVertex+1]) { - auxXCoord = Xcoord_Lower[jVertex]; Xcoord_Lower[jVertex] = Xcoord_Lower[jVertex+1]; Xcoord_Lower[jVertex+1] = auxXCoord; - auxYCoord = Ycoord_Lower[jVertex]; Ycoord_Lower[jVertex] = Ycoord_Lower[jVertex+1]; Ycoord_Lower[jVertex+1] = auxYCoord; - auxZCoord = Zcoord_Lower[jVertex]; Zcoord_Lower[jVertex] = Zcoord_Lower[jVertex+1]; Zcoord_Lower[jVertex+1] = auxZCoord; + if (Xcoord_Lower[jVertex] > Xcoord_Lower[jVertex + 1]) { + auxXCoord = Xcoord_Lower[jVertex]; + Xcoord_Lower[jVertex] = Xcoord_Lower[jVertex + 1]; + Xcoord_Lower[jVertex + 1] = auxXCoord; + auxYCoord = Ycoord_Lower[jVertex]; + Ycoord_Lower[jVertex] = Ycoord_Lower[jVertex + 1]; + Ycoord_Lower[jVertex + 1] = auxYCoord; + auxZCoord = Zcoord_Lower[jVertex]; + Zcoord_Lower[jVertex] = Zcoord_Lower[jVertex + 1]; + Zcoord_Lower[jVertex + 1] = auxZCoord; } } } @@ -9790,45 +9467,47 @@ su2double CPhysicalGeometry::Compute_Thickness(su2double *Plane_P0, su2double *P n_Lower = Xcoord_Lower.size(); if ((n_Upper > 1) && (n_Lower > 1)) { - - zp1 = (Zcoord_Upper[1]-Zcoord_Upper[0])/(Xcoord_Upper[1]-Xcoord_Upper[0]); - zpn = (Zcoord_Upper[n_Upper-1]-Zcoord_Upper[n_Upper-2])/(Xcoord_Upper[n_Upper-1]-Xcoord_Upper[n_Upper-2]); + zp1 = (Zcoord_Upper[1] - Zcoord_Upper[0]) / (Xcoord_Upper[1] - Xcoord_Upper[0]); + zpn = (Zcoord_Upper[n_Upper - 1] - Zcoord_Upper[n_Upper - 2]) / + (Xcoord_Upper[n_Upper - 1] - Xcoord_Upper[n_Upper - 2]); CCubicSpline splineUpper(Xcoord_Upper, Zcoord_Upper, CCubicSpline::FIRST, zp1, CCubicSpline::FIRST, zpn); - zp1 = (Zcoord_Lower[1]-Zcoord_Lower[0])/(Xcoord_Lower[1]-Xcoord_Lower[0]); - zpn = (Zcoord_Lower[n_Lower-1]-Zcoord_Lower[n_Lower-2])/(Xcoord_Lower[n_Lower-1]-Xcoord_Lower[n_Lower-2]); + zp1 = (Zcoord_Lower[1] - Zcoord_Lower[0]) / (Xcoord_Lower[1] - Xcoord_Lower[0]); + zpn = (Zcoord_Lower[n_Lower - 1] - Zcoord_Lower[n_Lower - 2]) / + (Xcoord_Lower[n_Lower - 1] - Xcoord_Lower[n_Lower - 2]); CCubicSpline splineLower(Xcoord_Lower, Zcoord_Lower, CCubicSpline::FIRST, zp1, CCubicSpline::FIRST, zpn); - Thickness_Location = - Chord*(1.0-Location); + Thickness_Location = -Chord * (1.0 - Location); Zcoord_Up = splineUpper(Thickness_Location); Zcoord_Down = splineLower(Thickness_Location); YLoc_ = Thickness_Location; - ZLoc_ = 0.5*(Zcoord_Up + Zcoord_Down); + ZLoc_ = 0.5 * (Zcoord_Up + Zcoord_Down); - ZLoc = sin(-AoA*PI_NUMBER/180.0)*YLoc_ + cos(-AoA*PI_NUMBER/180.0)*ZLoc_ + Zcoord_Trailing; + ZLoc = sin(-AoA * PI_NUMBER / 180.0) * YLoc_ + cos(-AoA * PI_NUMBER / 180.0) * ZLoc_ + Zcoord_Trailing; /*--- Compute the thickness (we add a fabs because we can not guarantee the right sorting of the points and the upper and/or lower part of the airfoil is not well defined) ---*/ Thickness_Value = fabs(Zcoord_Up - Zcoord_Down); + } else { + Thickness_Value = 0.0; } - else { Thickness_Value = 0.0; } return Thickness_Value; - } -su2double CPhysicalGeometry::Compute_Area(su2double *Plane_P0, su2double *Plane_Normal, CConfig *config, - vector &Xcoord_Airfoil, vector &Ycoord_Airfoil, vector &Zcoord_Airfoil) { +su2double CPhysicalGeometry::Compute_Area(su2double* Plane_P0, su2double* Plane_Normal, CConfig* config, + vector& Xcoord_Airfoil, vector& Ycoord_Airfoil, + vector& Zcoord_Airfoil) { unsigned long iVertex; su2double Area_Value = 0.0; - vector Xcoord_Upper, Ycoord_Upper, Zcoord_Upper, Xcoord_Lower, Ycoord_Lower, Zcoord_Lower, Z2coord, Xcoord_Normal, - Ycoord_Normal, Zcoord_Normal, Xcoord_Airfoil_, Ycoord_Airfoil_, Zcoord_Airfoil_; + vector Xcoord_Upper, Ycoord_Upper, Zcoord_Upper, Xcoord_Lower, Ycoord_Lower, Zcoord_Lower, Z2coord, + Xcoord_Normal, Ycoord_Normal, Zcoord_Normal, Xcoord_Airfoil_, Ycoord_Airfoil_, Zcoord_Airfoil_; su2double DeltaZ, DeltaX, X, Z; /*--- Use the Green theorem to evaluate the area (the points have been sortered), @@ -9836,28 +9515,28 @@ su2double CPhysicalGeometry::Compute_Area(su2double *Plane_P0, su2double *Plane_ Area_Value = 0.0; - for (iVertex = 0; iVertex < Xcoord_Airfoil.size()-1; iVertex++) { - X = 0.5*(Xcoord_Airfoil[iVertex]+Xcoord_Airfoil[iVertex+1]); - Z = 0.5*(Zcoord_Airfoil[iVertex]+Zcoord_Airfoil[iVertex+1]); - DeltaX = Xcoord_Airfoil[iVertex+1] - Xcoord_Airfoil[iVertex]; - DeltaZ = Zcoord_Airfoil[iVertex+1] - Zcoord_Airfoil[iVertex]; - Area_Value += 0.5*( X*DeltaZ-Z*DeltaX); + for (iVertex = 0; iVertex < Xcoord_Airfoil.size() - 1; iVertex++) { + X = 0.5 * (Xcoord_Airfoil[iVertex] + Xcoord_Airfoil[iVertex + 1]); + Z = 0.5 * (Zcoord_Airfoil[iVertex] + Zcoord_Airfoil[iVertex + 1]); + DeltaX = Xcoord_Airfoil[iVertex + 1] - Xcoord_Airfoil[iVertex]; + DeltaZ = Zcoord_Airfoil[iVertex + 1] - Zcoord_Airfoil[iVertex]; + Area_Value += 0.5 * (X * DeltaZ - Z * DeltaX); } - X = 0.5*(Xcoord_Airfoil[Xcoord_Airfoil.size()-1]+Xcoord_Airfoil[0]); - Z = 0.5*(Zcoord_Airfoil[Xcoord_Airfoil.size()-1]+Zcoord_Airfoil[0]); - DeltaX = Xcoord_Airfoil[0] - Xcoord_Airfoil[Xcoord_Airfoil.size()-1]; - DeltaZ = Zcoord_Airfoil[0] - Zcoord_Airfoil[Xcoord_Airfoil.size()-1]; - Area_Value += 0.5 * (X*DeltaZ-Z*DeltaX); + X = 0.5 * (Xcoord_Airfoil[Xcoord_Airfoil.size() - 1] + Xcoord_Airfoil[0]); + Z = 0.5 * (Zcoord_Airfoil[Xcoord_Airfoil.size() - 1] + Zcoord_Airfoil[0]); + DeltaX = Xcoord_Airfoil[0] - Xcoord_Airfoil[Xcoord_Airfoil.size() - 1]; + DeltaZ = Zcoord_Airfoil[0] - Zcoord_Airfoil[Xcoord_Airfoil.size() - 1]; + Area_Value += 0.5 * (X * DeltaZ - Z * DeltaX); Area_Value = fabs(Area_Value); return Area_Value; - } -su2double CPhysicalGeometry::Compute_Length(su2double *Plane_P0, su2double *Plane_Normal, CConfig *config, - vector &Xcoord_Airfoil, vector &Ycoord_Airfoil, vector &Zcoord_Airfoil) { +su2double CPhysicalGeometry::Compute_Length(su2double* Plane_P0, su2double* Plane_Normal, CConfig* config, + vector& Xcoord_Airfoil, vector& Ycoord_Airfoil, + vector& Zcoord_Airfoil) { unsigned long iVertex; su2double Length_Value = 0.0, Length_Value_ = 0.0; su2double DeltaZ, DeltaX; @@ -9867,35 +9546,35 @@ su2double CPhysicalGeometry::Compute_Length(su2double *Plane_P0, su2double *Plan both distance and picked the smallest one ---*/ Length_Value = 0.0; - for (iVertex = 0; iVertex < Xcoord_Airfoil.size()-2; iVertex++) { - DeltaX = Xcoord_Airfoil[iVertex+1] - Xcoord_Airfoil[iVertex]; - DeltaZ = Zcoord_Airfoil[iVertex+1] - Zcoord_Airfoil[iVertex]; - Length_Value += sqrt(DeltaX*DeltaX + DeltaZ*DeltaZ); + for (iVertex = 0; iVertex < Xcoord_Airfoil.size() - 2; iVertex++) { + DeltaX = Xcoord_Airfoil[iVertex + 1] - Xcoord_Airfoil[iVertex]; + DeltaZ = Zcoord_Airfoil[iVertex + 1] - Zcoord_Airfoil[iVertex]; + Length_Value += sqrt(DeltaX * DeltaX + DeltaZ * DeltaZ); } Length_Value_ = 0.0; - for (iVertex = 1; iVertex < Xcoord_Airfoil.size()-1; iVertex++) { - DeltaX = Xcoord_Airfoil[iVertex+1] - Xcoord_Airfoil[iVertex]; - DeltaZ = Zcoord_Airfoil[iVertex+1] - Zcoord_Airfoil[iVertex]; - Length_Value_ += sqrt(DeltaX*DeltaX + DeltaZ*DeltaZ); + for (iVertex = 1; iVertex < Xcoord_Airfoil.size() - 1; iVertex++) { + DeltaX = Xcoord_Airfoil[iVertex + 1] - Xcoord_Airfoil[iVertex]; + DeltaZ = Zcoord_Airfoil[iVertex + 1] - Zcoord_Airfoil[iVertex]; + Length_Value_ += sqrt(DeltaX * DeltaX + DeltaZ * DeltaZ); } Length_Value = min(Length_Value, Length_Value_); return Length_Value; - } -void CPhysicalGeometry::Compute_Wing(CConfig *config, bool original_surface, - su2double &Wing_Volume, su2double &Wing_MinMaxThickness, su2double &Wing_MaxMaxThickness, su2double &Wing_MinChord, su2double &Wing_MaxChord, - su2double &Wing_MinLERadius, su2double &Wing_MaxLERadius, - su2double &Wing_MinToC, su2double &Wing_MaxToC, su2double &Wing_ObjFun_MinToC, su2double &Wing_MaxTwist, su2double &Wing_MaxCurvature, - su2double &Wing_MaxDihedral) { - +void CPhysicalGeometry::Compute_Wing(CConfig* config, bool original_surface, su2double& Wing_Volume, + su2double& Wing_MinMaxThickness, su2double& Wing_MaxMaxThickness, + su2double& Wing_MinChord, su2double& Wing_MaxChord, su2double& Wing_MinLERadius, + su2double& Wing_MaxLERadius, su2double& Wing_MinToC, su2double& Wing_MaxToC, + su2double& Wing_ObjFun_MinToC, su2double& Wing_MaxTwist, + su2double& Wing_MaxCurvature, su2double& Wing_MaxDihedral) { unsigned short iPlane, iDim, nPlane = 0; unsigned long iVertex; - su2double MinPlane, MaxPlane, dPlane, *Area, *MaxThickness, *ToC, *Chord, *LERadius, *Twist, *Curvature, *Dihedral, SemiSpan; - vector *Xcoord_Airfoil, *Ycoord_Airfoil, *Zcoord_Airfoil, *Variable_Airfoil; + su2double MinPlane, MaxPlane, dPlane, *Area, *MaxThickness, *ToC, *Chord, *LERadius, *Twist, *Curvature, *Dihedral, + SemiSpan; + vector*Xcoord_Airfoil, *Ycoord_Airfoil, *Zcoord_Airfoil, *Variable_Airfoil; ofstream Wing_File, Section_File; /*--- Make a large number of section cuts for approximating volume ---*/ @@ -9905,160 +9584,173 @@ void CPhysicalGeometry::Compute_Wing(CConfig *config, bool original_surface, /*--- Allocate memory for the section cutting ---*/ - Area = new su2double [nPlane]; - MaxThickness = new su2double [nPlane]; - Chord = new su2double [nPlane]; - LERadius = new su2double [nPlane]; - ToC = new su2double [nPlane]; - Twist = new su2double [nPlane]; - Curvature = new su2double [nPlane]; - Dihedral = new su2double [nPlane]; + Area = new su2double[nPlane]; + MaxThickness = new su2double[nPlane]; + Chord = new su2double[nPlane]; + LERadius = new su2double[nPlane]; + ToC = new su2double[nPlane]; + Twist = new su2double[nPlane]; + Curvature = new su2double[nPlane]; + Dihedral = new su2double[nPlane]; - su2double **LeadingEdge = new su2double*[nPlane]; - for (iPlane = 0; iPlane < nPlane; iPlane++ ) - LeadingEdge[iPlane] = new su2double[nDim]; + su2double** LeadingEdge = new su2double*[nPlane]; + for (iPlane = 0; iPlane < nPlane; iPlane++) LeadingEdge[iPlane] = new su2double[nDim]; - su2double **TrailingEdge = new su2double*[nPlane]; - for (iPlane = 0; iPlane < nPlane; iPlane++ ) - TrailingEdge[iPlane] = new su2double[nDim]; + su2double** TrailingEdge = new su2double*[nPlane]; + for (iPlane = 0; iPlane < nPlane; iPlane++) TrailingEdge[iPlane] = new su2double[nDim]; - su2double **Plane_P0 = new su2double*[nPlane]; - for (iPlane = 0; iPlane < nPlane; iPlane++ ) - Plane_P0[iPlane] = new su2double[nDim]; + su2double** Plane_P0 = new su2double*[nPlane]; + for (iPlane = 0; iPlane < nPlane; iPlane++) Plane_P0[iPlane] = new su2double[nDim]; - su2double **Plane_Normal = new su2double*[nPlane]; - for (iPlane = 0; iPlane < nPlane; iPlane++ ) - Plane_Normal[iPlane] = new su2double[nDim]; + su2double** Plane_Normal = new su2double*[nPlane]; + for (iPlane = 0; iPlane < nPlane; iPlane++) Plane_Normal[iPlane] = new su2double[nDim]; - MinPlane = config->GetStations_Bounds(0); MaxPlane = config->GetStations_Bounds(1); - dPlane = fabs((MaxPlane - MinPlane)/su2double(nPlane-1)); + MinPlane = config->GetStations_Bounds(0); + MaxPlane = config->GetStations_Bounds(1); + dPlane = fabs((MaxPlane - MinPlane) / su2double(nPlane - 1)); for (iPlane = 0; iPlane < nPlane; iPlane++) { - Plane_Normal[iPlane][0] = 0.0; Plane_P0[iPlane][0] = 0.0; - Plane_Normal[iPlane][1] = 0.0; Plane_P0[iPlane][1] = 0.0; - Plane_Normal[iPlane][2] = 0.0; Plane_P0[iPlane][2] = 0.0; + Plane_Normal[iPlane][0] = 0.0; + Plane_P0[iPlane][0] = 0.0; + Plane_Normal[iPlane][1] = 0.0; + Plane_P0[iPlane][1] = 0.0; + Plane_Normal[iPlane][2] = 0.0; + Plane_P0[iPlane][2] = 0.0; if (config->GetGeo_Description() == WING) { Plane_Normal[iPlane][1] = 1.0; - Plane_P0[iPlane][1] = MinPlane + iPlane*dPlane; + Plane_P0[iPlane][1] = MinPlane + iPlane * dPlane; } if (config->GetGeo_Description() == TWOD_AIRFOIL) { Plane_Normal[iPlane][2] = 1.0; - Plane_P0[iPlane][2] = MinPlane + iPlane*dPlane; + Plane_P0[iPlane][2] = MinPlane + iPlane * dPlane; } - } /*--- Allocate some vectors for storing airfoil coordinates ---*/ - Xcoord_Airfoil = new vector[nPlane]; - Ycoord_Airfoil = new vector[nPlane]; - Zcoord_Airfoil = new vector[nPlane]; + Xcoord_Airfoil = new vector[nPlane]; + Ycoord_Airfoil = new vector[nPlane]; + Zcoord_Airfoil = new vector[nPlane]; Variable_Airfoil = new vector[nPlane]; /*--- Create the section slices through the geometry ---*/ for (iPlane = 0; iPlane < nPlane; iPlane++) { - - ComputeAirfoil_Section(Plane_P0[iPlane], Plane_Normal[iPlane], - -1E6, 1E6, -1E6, 1E6, -1E6, 1E6, nullptr, Xcoord_Airfoil[iPlane], - Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane], + ComputeAirfoil_Section(Plane_P0[iPlane], Plane_Normal[iPlane], -1E6, 1E6, -1E6, 1E6, -1E6, 1E6, nullptr, + Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane], Variable_Airfoil[iPlane], original_surface, config); - - } + } /*--- Compute airfoil characteristic only in the master node ---*/ if (rank == MASTER_NODE) { - /*--- Write an output file---*/ if (config->GetTabular_FileFormat() == TAB_OUTPUT::TAB_CSV) { Wing_File.open("wing_description.csv", ios::out); if (config->GetSystemMeasurements() == US) - Wing_File << "\"yCoord/SemiSpan\",\"Area (in^2)\",\"Max. Thickness (in)\",\"Chord (in)\",\"Leading Edge Radius (1/in)\",\"Max. Thickness/Chord\",\"Twist (deg)\",\"Curvature (1/in)\",\"Dihedral (deg)\",\"Leading Edge XLoc/SemiSpan\",\"Leading Edge ZLoc/SemiSpan\",\"Trailing Edge XLoc/SemiSpan\",\"Trailing Edge ZLoc/SemiSpan\"" << endl; + Wing_File << "\"yCoord/SemiSpan\",\"Area (in^2)\",\"Max. Thickness (in)\",\"Chord (in)\",\"Leading Edge Radius " + "(1/in)\",\"Max. Thickness/Chord\",\"Twist (deg)\",\"Curvature (1/in)\",\"Dihedral " + "(deg)\",\"Leading Edge XLoc/SemiSpan\",\"Leading Edge ZLoc/SemiSpan\",\"Trailing Edge " + "XLoc/SemiSpan\",\"Trailing Edge ZLoc/SemiSpan\"" + << endl; else - Wing_File << "\"yCoord/SemiSpan\",\"Area (m^2)\",\"Max. Thickness (m)\",\"Chord (m)\",\"Leading Edge Radius (1/m)\",\"Max. Thickness/Chord\",\"Twist (deg)\",\"Curvature (1/in)\",\"Dihedral (deg)\",\"Leading Edge XLoc/SemiSpan\",\"Leading Edge ZLoc/SemiSpan\",\"Trailing Edge XLoc/SemiSpan\",\"Trailing Edge ZLoc/SemiSpan\"" << endl; - } - else { + Wing_File << "\"yCoord/SemiSpan\",\"Area (m^2)\",\"Max. Thickness (m)\",\"Chord (m)\",\"Leading Edge Radius " + "(1/m)\",\"Max. Thickness/Chord\",\"Twist (deg)\",\"Curvature (1/in)\",\"Dihedral " + "(deg)\",\"Leading Edge XLoc/SemiSpan\",\"Leading Edge ZLoc/SemiSpan\",\"Trailing Edge " + "XLoc/SemiSpan\",\"Trailing Edge ZLoc/SemiSpan\"" + << endl; + } else { Wing_File.open("wing_description.dat", ios::out); Wing_File << "TITLE = \"Wing description\"" << endl; if (config->GetSystemMeasurements() == US) - Wing_File << "VARIABLES = \"h\",\"Area (in2)\",\"Max. Thickness (in)\",\"Chord (in)\",\"Leading Edge Radius (1/in)\",\"Max. Thickness/Chord\",\"Twist (deg)\",\"Curvature (1/in)\",\"Dihedral (deg)\",\"Leading Edge XLoc/SemiSpan\",\"Leading Edge ZLoc/SemiSpan\",\"Trailing Edge XLoc/SemiSpan\",\"Trailing Edge ZLoc/SemiSpan\"" << endl; + Wing_File << "VARIABLES = \"h\",\"Area (in2)\",\"Max. Thickness (in)\",\"Chord " + "(in)\",\"Leading Edge Radius (1/in)\",\"Max. Thickness/Chord\",\"Twist (deg)\",\"Curvature " + "(1/in)\",\"Dihedral (deg)\",\"Leading Edge XLoc/SemiSpan\",\"Leading Edge " + "ZLoc/SemiSpan\",\"Trailing Edge XLoc/SemiSpan\",\"Trailing Edge ZLoc/SemiSpan\"" + << endl; else - Wing_File << "VARIABLES = \"h\",\"Area (m2)\",\"Max. Thickness (m)\",\"Chord (m)\",\"Leading Edge Radius (1/m)\",\"Max. Thickness/Chord\",\"Twist (deg)\",\"Curvature (1/m)\",\"Dihedral (deg)\",\"Leading Edge XLoc/SemiSpan\",\"Leading Edge ZLoc/SemiSpan\",\"Trailing Edge XLoc/SemiSpan\",\"Trailing Edge ZLoc/SemiSpan\"" << endl; + Wing_File << "VARIABLES = \"h\",\"Area (m2)\",\"Max. Thickness (m)\",\"Chord " + "(m)\",\"Leading Edge Radius (1/m)\",\"Max. Thickness/Chord\",\"Twist (deg)\",\"Curvature " + "(1/m)\",\"Dihedral (deg)\",\"Leading Edge XLoc/SemiSpan\",\"Leading Edge " + "ZLoc/SemiSpan\",\"Trailing Edge XLoc/SemiSpan\",\"Trailing Edge ZLoc/SemiSpan\"" + << endl; Wing_File << "ZONE T= \"Baseline wing\"" << endl; } - /*--- Evaluate geometrical quatities that do not require any kind of filter, local to each point ---*/ for (iPlane = 0; iPlane < nPlane; iPlane++) { - for (iDim = 0; iDim < nDim; iDim++) { - LeadingEdge[iPlane][iDim] = 0.0; + LeadingEdge[iPlane][iDim] = 0.0; TrailingEdge[iPlane][iDim] = 0.0; } - Area[iPlane] = 0.0; - MaxThickness[iPlane] = 0.0; - Chord[iPlane] = 0.0; - LERadius[iPlane] = 0.0; - ToC[iPlane] = 0.0; - Twist[iPlane] = 0.0; + Area[iPlane] = 0.0; + MaxThickness[iPlane] = 0.0; + Chord[iPlane] = 0.0; + LERadius[iPlane] = 0.0; + ToC[iPlane] = 0.0; + Twist[iPlane] = 0.0; if (Xcoord_Airfoil[iPlane].size() > 1) { + Compute_Wing_LeadingTrailing(LeadingEdge[iPlane], TrailingEdge[iPlane], Plane_P0[iPlane], Plane_Normal[iPlane], + Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - Compute_Wing_LeadingTrailing(LeadingEdge[iPlane], TrailingEdge[iPlane], Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); + Area[iPlane] = Compute_Area(Plane_P0[iPlane], Plane_Normal[iPlane], config, Xcoord_Airfoil[iPlane], + Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - Area[iPlane] = Compute_Area(Plane_P0[iPlane], Plane_Normal[iPlane], config, Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); + MaxThickness[iPlane] = + Compute_MaxThickness(Plane_P0[iPlane], Plane_Normal[iPlane], config, Xcoord_Airfoil[iPlane], + Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - MaxThickness[iPlane] = Compute_MaxThickness(Plane_P0[iPlane], Plane_Normal[iPlane], config, Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); + Chord[iPlane] = Compute_Chord(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], + Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - Chord[iPlane] = Compute_Chord(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); + Twist[iPlane] = Compute_Twist(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], + Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - Twist[iPlane] = Compute_Twist(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - - LERadius[iPlane] = Compute_LERadius(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); + LERadius[iPlane] = Compute_LERadius(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], + Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); ToC[iPlane] = MaxThickness[iPlane] / Chord[iPlane]; - - } - } - /*--- Evaluate geometrical quatities that have been computed using a filtered value (they depend on more than one point) ---*/ + /*--- Evaluate geometrical quatities that have been computed using a filtered value (they depend on more than one + * point) ---*/ for (iPlane = 0; iPlane < nPlane; iPlane++) { - - Curvature[iPlane] = 0.0; - Dihedral[iPlane] = 0.0; + Curvature[iPlane] = 0.0; + Dihedral[iPlane] = 0.0; if (Xcoord_Airfoil[iPlane].size() > 1) { + if ((iPlane == 0) || (iPlane == nPlane - 1)) + Curvature[iPlane] = 0.0; + else + Curvature[iPlane] = + Compute_Curvature(LeadingEdge[iPlane - 1], TrailingEdge[iPlane - 1], LeadingEdge[iPlane], + TrailingEdge[iPlane], LeadingEdge[iPlane + 1], TrailingEdge[iPlane + 1]); - if ((iPlane == 0) || (iPlane == nPlane-1)) Curvature[iPlane] = 0.0; - else Curvature[iPlane] = Compute_Curvature(LeadingEdge[iPlane-1], TrailingEdge[iPlane-1], - LeadingEdge[iPlane], TrailingEdge[iPlane], - LeadingEdge[iPlane+1], TrailingEdge[iPlane+1]); - - if (iPlane == 0) Dihedral[iPlane] = 0.0; - else Dihedral[iPlane] = Compute_Dihedral(LeadingEdge[iPlane-1], TrailingEdge[iPlane-1], - LeadingEdge[iPlane], TrailingEdge[iPlane]); - + if (iPlane == 0) + Dihedral[iPlane] = 0.0; + else + Dihedral[iPlane] = Compute_Dihedral(LeadingEdge[iPlane - 1], TrailingEdge[iPlane - 1], LeadingEdge[iPlane], + TrailingEdge[iPlane]); } - } /*--- Set the curvature and dihedral angles at the extremes ---*/ if (nPlane > 1) { if ((Xcoord_Airfoil[0].size() != 0) && (Xcoord_Airfoil[1].size() != 0)) { - Curvature[0] = Curvature[1]; Dihedral[0] = Dihedral[1]; + Curvature[0] = Curvature[1]; + Dihedral[0] = Dihedral[1]; } - if ((Xcoord_Airfoil[nPlane-1].size() != 0) && (Xcoord_Airfoil[nPlane-2].size() != 0)) { - Curvature[nPlane-1] = Curvature[nPlane-2]; + if ((Xcoord_Airfoil[nPlane - 1].size() != 0) && (Xcoord_Airfoil[nPlane - 2].size() != 0)) { + Curvature[nPlane - 1] = Curvature[nPlane - 2]; } } @@ -10067,17 +9759,17 @@ void CPhysicalGeometry::Compute_Wing(CConfig *config, bool original_surface, for (iPlane = 0; iPlane < nPlane; iPlane++) { if (Xcoord_Airfoil[iPlane].size() > 1) { if (config->GetTabular_FileFormat() == TAB_OUTPUT::TAB_CSV) { - Wing_File << Ycoord_Airfoil[iPlane][0]/SemiSpan <<", "<< Area[iPlane] <<", "<< MaxThickness[iPlane] <<", "<< Chord[iPlane] <<", "<< LERadius[iPlane] <<", "<< ToC[iPlane] - <<", "<< Twist[iPlane] <<", "<< Curvature[iPlane] <<", "<< Dihedral[iPlane] - <<", "<< LeadingEdge[iPlane][0]/SemiSpan <<", "<< LeadingEdge[iPlane][2]/SemiSpan - <<", "<< TrailingEdge[iPlane][0]/SemiSpan <<", "<< TrailingEdge[iPlane][2]/SemiSpan << endl; - } - else { - Wing_File << Ycoord_Airfoil[iPlane][0]/SemiSpan <<" "<< Area[iPlane] <<" "<< MaxThickness[iPlane] <<" "<< Chord[iPlane] <<" "<< LERadius[iPlane] <<" "<< ToC[iPlane] - <<" "<< Twist[iPlane] <<" "<< Curvature[iPlane] <<" "<< Dihedral[iPlane] - <<" "<< LeadingEdge[iPlane][0]/SemiSpan <<" "<< LeadingEdge[iPlane][2]/SemiSpan - <<" "<< TrailingEdge[iPlane][0]/SemiSpan <<" "<< TrailingEdge[iPlane][2]/SemiSpan << endl; - + Wing_File << Ycoord_Airfoil[iPlane][0] / SemiSpan << ", " << Area[iPlane] << ", " << MaxThickness[iPlane] + << ", " << Chord[iPlane] << ", " << LERadius[iPlane] << ", " << ToC[iPlane] << ", " << Twist[iPlane] + << ", " << Curvature[iPlane] << ", " << Dihedral[iPlane] << ", " + << LeadingEdge[iPlane][0] / SemiSpan << ", " << LeadingEdge[iPlane][2] / SemiSpan << ", " + << TrailingEdge[iPlane][0] / SemiSpan << ", " << TrailingEdge[iPlane][2] / SemiSpan << endl; + } else { + Wing_File << Ycoord_Airfoil[iPlane][0] / SemiSpan << " " << Area[iPlane] << " " << MaxThickness[iPlane] << " " + << Chord[iPlane] << " " << LERadius[iPlane] << " " << ToC[iPlane] << " " << Twist[iPlane] << " " + << Curvature[iPlane] << " " << Dihedral[iPlane] << " " << LeadingEdge[iPlane][0] / SemiSpan << " " + << LeadingEdge[iPlane][2] / SemiSpan << " " << TrailingEdge[iPlane][0] / SemiSpan << " " + << TrailingEdge[iPlane][2] / SemiSpan << endl; } } } @@ -10087,20 +9779,21 @@ void CPhysicalGeometry::Compute_Wing(CConfig *config, bool original_surface, Section_File.open("wing_slices.dat", ios::out); for (iPlane = 0; iPlane < nPlane; iPlane++) { - if (iPlane == 0) { Section_File << "TITLE = \"Aircraft Slices\"" << endl; if (config->GetSystemMeasurements() == US) - Section_File << "VARIABLES = \"x (in)\", \"y (in)\", \"z (in)\", \"x2D/c\", \"y2D/c\"" << endl; - else Section_File << "VARIABLES = \"x (m)\", \"y (m)\", \"z (m)\", \"x2D/c\", \"y2D/c\"" << endl; + Section_File << "VARIABLES = \"x (in)\", \"y (in)\", \"z (in)\", \"x2D/c\", \"y2D/c\"" + << endl; + else + Section_File << "VARIABLES = \"x (m)\", \"y (m)\", \"z (m)\", \"x2D/c\", \"y2D/c\"" + << endl; } if (Xcoord_Airfoil[iPlane].size() > 1) { - - Section_File << "ZONE T=\"h = " << Ycoord_Airfoil[iPlane][0]/SemiSpan << " \", I= " << Xcoord_Airfoil[iPlane].size() << ", F=POINT" << endl; + Section_File << "ZONE T=\"h = " << Ycoord_Airfoil[iPlane][0] / SemiSpan + << " \", I= " << Xcoord_Airfoil[iPlane].size() << ", F=POINT" << endl; for (iVertex = 0; iVertex < Xcoord_Airfoil[iPlane].size(); iVertex++) { - /*--- Move to the origin ---*/ su2double XValue_ = Xcoord_Airfoil[iPlane][iVertex] - LeadingEdge[iPlane][0]; @@ -10108,37 +9801,44 @@ void CPhysicalGeometry::Compute_Wing(CConfig *config, bool original_surface, /*--- Rotate the airfoil and divide by the chord ---*/ - su2double ValCos = cos(Twist[iPlane]*PI_NUMBER/180.0); - su2double ValSin = sin(Twist[iPlane]*PI_NUMBER/180.0); + su2double ValCos = cos(Twist[iPlane] * PI_NUMBER / 180.0); + su2double ValSin = sin(Twist[iPlane] * PI_NUMBER / 180.0); - su2double XValue = (XValue_*ValCos - ZValue_*ValSin) / Chord[iPlane]; - su2double ZValue = (ZValue_*ValCos + XValue_*ValSin) / Chord[iPlane]; + su2double XValue = (XValue_ * ValCos - ZValue_ * ValSin) / Chord[iPlane]; + su2double ZValue = (ZValue_ * ValCos + XValue_ * ValSin) / Chord[iPlane]; /*--- Write the file ---*/ - Section_File << Xcoord_Airfoil[iPlane][iVertex] << " " << Ycoord_Airfoil[iPlane][iVertex] << " " << Zcoord_Airfoil[iPlane][iVertex] << " " << XValue << " " << ZValue << endl; + Section_File << Xcoord_Airfoil[iPlane][iVertex] << " " << Ycoord_Airfoil[iPlane][iVertex] << " " + << Zcoord_Airfoil[iPlane][iVertex] << " " << XValue << " " << ZValue << endl; } } - } Section_File.close(); - /*--- Compute the wing volume using a composite Simpson's rule ---*/ Wing_Volume = 0.0; - for (iPlane = 0; iPlane < nPlane-2; iPlane+=2) { + for (iPlane = 0; iPlane < nPlane - 2; iPlane += 2) { if (Xcoord_Airfoil[iPlane].size() > 1) { - Wing_Volume += (1.0/3.0)*dPlane*(Area[iPlane] + 4.0*Area[iPlane+1] + Area[iPlane+2]); + Wing_Volume += (1.0 / 3.0) * dPlane * (Area[iPlane] + 4.0 * Area[iPlane + 1] + Area[iPlane + 2]); } } /*--- Evaluate Max and Min quantities ---*/ - Wing_MaxMaxThickness = -1E6; Wing_MinMaxThickness = 1E6; Wing_MinChord = 1E6; Wing_MaxChord = -1E6; - Wing_MinLERadius = 1E6; Wing_MaxLERadius = -1E6; Wing_MinToC = 1E6; Wing_MaxToC = -1E6; - Wing_MaxTwist = -1E6; Wing_MaxCurvature = -1E6; Wing_MaxDihedral = -1E6; + Wing_MaxMaxThickness = -1E6; + Wing_MinMaxThickness = 1E6; + Wing_MinChord = 1E6; + Wing_MaxChord = -1E6; + Wing_MinLERadius = 1E6; + Wing_MaxLERadius = -1E6; + Wing_MinToC = 1E6; + Wing_MaxToC = -1E6; + Wing_MaxTwist = -1E6; + Wing_MaxCurvature = -1E6; + Wing_MaxDihedral = -1E6; for (iPlane = 0; iPlane < nPlane; iPlane++) { if (MaxThickness[iPlane] != 0.0) Wing_MinMaxThickness = min(Wing_MinMaxThickness, MaxThickness[iPlane]); @@ -10149,59 +9849,51 @@ void CPhysicalGeometry::Compute_Wing(CConfig *config, bool original_surface, Wing_MaxLERadius = max(Wing_MaxLERadius, LERadius[iPlane]); if (ToC[iPlane] != 0.0) Wing_MinToC = min(Wing_MinToC, ToC[iPlane]); Wing_MaxToC = max(Wing_MaxToC, ToC[iPlane]); - Wing_ObjFun_MinToC = sqrt((Wing_MinToC - 0.07)*(Wing_MinToC - 0.07)); + Wing_ObjFun_MinToC = sqrt((Wing_MinToC - 0.07) * (Wing_MinToC - 0.07)); Wing_MaxTwist = max(Wing_MaxTwist, fabs(Twist[iPlane])); Wing_MaxCurvature = max(Wing_MaxCurvature, Curvature[iPlane]); Wing_MaxDihedral = max(Wing_MaxDihedral, fabs(Dihedral[iPlane])); } - } /*--- Free memory for the section cuts ---*/ - delete [] Xcoord_Airfoil; - delete [] Ycoord_Airfoil; - delete [] Zcoord_Airfoil; - delete [] Variable_Airfoil; + delete[] Xcoord_Airfoil; + delete[] Ycoord_Airfoil; + delete[] Zcoord_Airfoil; + delete[] Variable_Airfoil; - for (iPlane = 0; iPlane < nPlane; iPlane++) - delete [] LeadingEdge[iPlane]; - delete [] LeadingEdge; + for (iPlane = 0; iPlane < nPlane; iPlane++) delete[] LeadingEdge[iPlane]; + delete[] LeadingEdge; - for (iPlane = 0; iPlane < nPlane; iPlane++) - delete [] TrailingEdge[iPlane]; - delete [] TrailingEdge; + for (iPlane = 0; iPlane < nPlane; iPlane++) delete[] TrailingEdge[iPlane]; + delete[] TrailingEdge; - for (iPlane = 0; iPlane < nPlane; iPlane++) - delete [] Plane_P0[iPlane]; - delete [] Plane_P0; + for (iPlane = 0; iPlane < nPlane; iPlane++) delete[] Plane_P0[iPlane]; + delete[] Plane_P0; - for (iPlane = 0; iPlane < nPlane; iPlane++) - delete [] Plane_Normal[iPlane]; - delete [] Plane_Normal; - - delete [] Area; - delete [] MaxThickness; - delete [] Chord; - delete [] LERadius; - delete [] ToC; - delete [] Twist; - delete [] Curvature; - delete [] Dihedral; + for (iPlane = 0; iPlane < nPlane; iPlane++) delete[] Plane_Normal[iPlane]; + delete[] Plane_Normal; + delete[] Area; + delete[] MaxThickness; + delete[] Chord; + delete[] LERadius; + delete[] ToC; + delete[] Twist; + delete[] Curvature; + delete[] Dihedral; } -void CPhysicalGeometry::Compute_Fuselage(CConfig *config, bool original_surface, - su2double &Fuselage_Volume, su2double &Fuselage_WettedArea, - su2double &Fuselage_MinWidth, su2double &Fuselage_MaxWidth, - su2double &Fuselage_MinWaterLineWidth, su2double &Fuselage_MaxWaterLineWidth, - su2double &Fuselage_MinHeight, su2double &Fuselage_MaxHeight, - su2double &Fuselage_MaxCurvature) { - +void CPhysicalGeometry::Compute_Fuselage(CConfig* config, bool original_surface, su2double& Fuselage_Volume, + su2double& Fuselage_WettedArea, su2double& Fuselage_MinWidth, + su2double& Fuselage_MaxWidth, su2double& Fuselage_MinWaterLineWidth, + su2double& Fuselage_MaxWaterLineWidth, su2double& Fuselage_MinHeight, + su2double& Fuselage_MaxHeight, su2double& Fuselage_MaxCurvature) { unsigned short iPlane, iDim, nPlane = 0; unsigned long iVertex; su2double MinPlane, MaxPlane, dPlane, *Area, *Length, *Width, *WaterLineWidth, *Height, *Curvature; - vector *Xcoord_Airfoil, *Ycoord_Airfoil, *Zcoord_Airfoil, *Variable_Airfoil; + vector*Xcoord_Airfoil, *Ycoord_Airfoil, *Zcoord_Airfoil, *Variable_Airfoil; ofstream Fuselage_File, Section_File; /*--- Make a large number of section cuts for approximating volume ---*/ @@ -10210,131 +9902,144 @@ void CPhysicalGeometry::Compute_Fuselage(CConfig *config, bool original_surface, /*--- Allocate memory for the section cutting ---*/ - Area = new su2double [nPlane]; - Length = new su2double [nPlane]; - Width = new su2double [nPlane]; - WaterLineWidth = new su2double [nPlane]; - Height = new su2double [nPlane]; - Curvature = new su2double [nPlane]; + Area = new su2double[nPlane]; + Length = new su2double[nPlane]; + Width = new su2double[nPlane]; + WaterLineWidth = new su2double[nPlane]; + Height = new su2double[nPlane]; + Curvature = new su2double[nPlane]; - su2double **LeadingEdge = new su2double*[nPlane]; - for (iPlane = 0; iPlane < nPlane; iPlane++ ) - LeadingEdge[iPlane] = new su2double[nDim]; + su2double** LeadingEdge = new su2double*[nPlane]; + for (iPlane = 0; iPlane < nPlane; iPlane++) LeadingEdge[iPlane] = new su2double[nDim]; - su2double **TrailingEdge = new su2double*[nPlane]; - for (iPlane = 0; iPlane < nPlane; iPlane++ ) - TrailingEdge[iPlane] = new su2double[nDim]; + su2double** TrailingEdge = new su2double*[nPlane]; + for (iPlane = 0; iPlane < nPlane; iPlane++) TrailingEdge[iPlane] = new su2double[nDim]; - su2double **Plane_P0 = new su2double*[nPlane]; - for (iPlane = 0; iPlane < nPlane; iPlane++ ) - Plane_P0[iPlane] = new su2double[nDim]; + su2double** Plane_P0 = new su2double*[nPlane]; + for (iPlane = 0; iPlane < nPlane; iPlane++) Plane_P0[iPlane] = new su2double[nDim]; - su2double **Plane_Normal = new su2double*[nPlane]; - for (iPlane = 0; iPlane < nPlane; iPlane++ ) - Plane_Normal[iPlane] = new su2double[nDim]; + su2double** Plane_Normal = new su2double*[nPlane]; + for (iPlane = 0; iPlane < nPlane; iPlane++) Plane_Normal[iPlane] = new su2double[nDim]; - MinPlane = config->GetStations_Bounds(0); MaxPlane = config->GetStations_Bounds(1); - dPlane = fabs((MaxPlane - MinPlane)/su2double(nPlane-1)); + MinPlane = config->GetStations_Bounds(0); + MaxPlane = config->GetStations_Bounds(1); + dPlane = fabs((MaxPlane - MinPlane) / su2double(nPlane - 1)); for (iPlane = 0; iPlane < nPlane; iPlane++) { - Plane_Normal[iPlane][0] = 0.0; Plane_P0[iPlane][0] = 0.0; - Plane_Normal[iPlane][1] = 0.0; Plane_P0[iPlane][1] = 0.0; - Plane_Normal[iPlane][2] = 0.0; Plane_P0[iPlane][2] = 0.0; + Plane_Normal[iPlane][0] = 0.0; + Plane_P0[iPlane][0] = 0.0; + Plane_Normal[iPlane][1] = 0.0; + Plane_P0[iPlane][1] = 0.0; + Plane_Normal[iPlane][2] = 0.0; + Plane_P0[iPlane][2] = 0.0; Plane_Normal[iPlane][0] = 1.0; - Plane_P0[iPlane][0] = MinPlane + iPlane*dPlane; - + Plane_P0[iPlane][0] = MinPlane + iPlane * dPlane; } /*--- Allocate some vectors for storing airfoil coordinates ---*/ - Xcoord_Airfoil = new vector[nPlane]; - Ycoord_Airfoil = new vector[nPlane]; - Zcoord_Airfoil = new vector[nPlane]; + Xcoord_Airfoil = new vector[nPlane]; + Ycoord_Airfoil = new vector[nPlane]; + Zcoord_Airfoil = new vector[nPlane]; Variable_Airfoil = new vector[nPlane]; /*--- Create the section slices through the geometry ---*/ for (iPlane = 0; iPlane < nPlane; iPlane++) { - - ComputeAirfoil_Section(Plane_P0[iPlane], Plane_Normal[iPlane], - -1E6, 1E6, -1E6, 1E6, -1E6, 1E6, nullptr, Xcoord_Airfoil[iPlane], - Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane], + ComputeAirfoil_Section(Plane_P0[iPlane], Plane_Normal[iPlane], -1E6, 1E6, -1E6, 1E6, -1E6, 1E6, nullptr, + Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane], Variable_Airfoil[iPlane], original_surface, config); } /*--- Compute the area at each section ---*/ if (rank == MASTER_NODE) { - /*--- Write an output file---*/ if (config->GetTabular_FileFormat() == TAB_OUTPUT::TAB_CSV) { Fuselage_File.open("fuselage_description.csv", ios::out); if (config->GetSystemMeasurements() == US) - Fuselage_File << "\"x (in)\",\"Area (in^2)\",\"Length (in)\",\"Width (in)\",\"Waterline width (in)\",\"Height (in)\",\"Curvature (1/in)\",\"Generatrix Curve X (in)\",\"Generatrix Curve Y (in)\",\"Generatrix Curve Z (in)\",\"Axis Curve X (in)\",\"Axis Curve Y (in)\",\"Axis Curve Z (in)\"" << endl; + Fuselage_File + << "\"x (in)\",\"Area (in^2)\",\"Length (in)\",\"Width (in)\",\"Waterline width (in)\",\"Height " + "(in)\",\"Curvature (1/in)\",\"Generatrix Curve X (in)\",\"Generatrix Curve Y (in)\",\"Generatrix Curve " + "Z (in)\",\"Axis Curve X (in)\",\"Axis Curve Y (in)\",\"Axis Curve Z (in)\"" + << endl; else - Fuselage_File << "\"x (m)\",\"Area (m^2)\",\"Length (m)\",\"Width (m)\",\"Waterline width (m)\",\"Height (m)\",\"Curvature (1/in)\",\"Generatrix Curve X (m)\",\"Generatrix Curve Y (m)\",\"Generatrix Curve Z (m)\",\"Axis Curve X (m)\",\"Axis Curve Y (m)\",\"Axis Curve Z (m)\"" << endl; - } - else { + Fuselage_File + << "\"x (m)\",\"Area (m^2)\",\"Length (m)\",\"Width (m)\",\"Waterline width (m)\",\"Height " + "(m)\",\"Curvature (1/in)\",\"Generatrix Curve X (m)\",\"Generatrix Curve Y (m)\",\"Generatrix Curve Z " + "(m)\",\"Axis Curve X (m)\",\"Axis Curve Y (m)\",\"Axis Curve Z (m)\"" + << endl; + } else { Fuselage_File.open("fuselage_description.dat", ios::out); Fuselage_File << "TITLE = \"Fuselage description\"" << endl; if (config->GetSystemMeasurements() == US) - Fuselage_File << "VARIABLES = \"x (in)\",\"Area (in2)\",\"Length (in)\",\"Width (in)\",\"Waterline width (in)\",\"Height (in)\",\"Curvature (1/in)\",\"Generatrix Curve X (in)\",\"Generatrix Curve Y (in)\",\"Generatrix Curve Z (in)\",\"Axis Curve X (in)\",\"Axis Curve Y (in)\",\"Axis Curve Z (in)\"" << endl; + Fuselage_File + << "VARIABLES = \"x (in)\",\"Area (in2)\",\"Length (in)\",\"Width (in)\",\"Waterline width " + "(in)\",\"Height (in)\",\"Curvature (1/in)\",\"Generatrix Curve X (in)\",\"Generatrix Curve Y " + "(in)\",\"Generatrix Curve Z (in)\",\"Axis Curve X (in)\",\"Axis Curve Y (in)\",\"Axis Curve Z (in)\"" + << endl; else - Fuselage_File << "VARIABLES = \"x (m)\",\"Area (m2)\",\"Length (m)\",\"Width (m)\",\"Waterline width (m)\",\"Height (m)\",\"Curvature (1/m)\",\"Generatrix Curve X (m)\",\"Generatrix Curve Y (m)\",\"Generatrix Curve Z (m)\",\"Axis Curve X (m)\",\"Axis Curve Y (m)\",\"Axis Curve Z (m)\"" << endl; + Fuselage_File + << "VARIABLES = \"x (m)\",\"Area (m2)\",\"Length (m)\",\"Width (m)\",\"Waterline width " + "(m)\",\"Height (m)\",\"Curvature (1/m)\",\"Generatrix Curve X (m)\",\"Generatrix Curve Y " + "(m)\",\"Generatrix Curve Z (m)\",\"Axis Curve X (m)\",\"Axis Curve Y (m)\",\"Axis Curve Z (m)\"" + << endl; Fuselage_File << "ZONE T= \"Baseline fuselage\"" << endl; } - /*--- Evaluate geometrical quatities that do not require any kind of filter, local to each point ---*/ for (iPlane = 0; iPlane < nPlane; iPlane++) { - for (iDim = 0; iDim < nDim; iDim++) { - LeadingEdge[iPlane][iDim] = 0.0; + LeadingEdge[iPlane][iDim] = 0.0; TrailingEdge[iPlane][iDim] = 0.0; } - Area[iPlane] = 0.0; - Length[iPlane] = 0.0; - Width[iPlane] = 0.0; - WaterLineWidth[iPlane] = 0.0; + Area[iPlane] = 0.0; + Length[iPlane] = 0.0; + Width[iPlane] = 0.0; + WaterLineWidth[iPlane] = 0.0; Height[iPlane] = 0.0; if (Xcoord_Airfoil[iPlane].size() > 1) { + Compute_Fuselage_LeadingTrailing(LeadingEdge[iPlane], TrailingEdge[iPlane], Plane_P0[iPlane], + Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], + Zcoord_Airfoil[iPlane]); - Compute_Fuselage_LeadingTrailing(LeadingEdge[iPlane], TrailingEdge[iPlane], Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - - Area[iPlane] = Compute_Area(Plane_P0[iPlane], Plane_Normal[iPlane], config, Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); + Area[iPlane] = Compute_Area(Plane_P0[iPlane], Plane_Normal[iPlane], config, Xcoord_Airfoil[iPlane], + Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - Length[iPlane] = Compute_Length(Plane_P0[iPlane], Plane_Normal[iPlane], config, Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); + Length[iPlane] = Compute_Length(Plane_P0[iPlane], Plane_Normal[iPlane], config, Xcoord_Airfoil[iPlane], + Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - Width[iPlane] = Compute_Width(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); + Width[iPlane] = Compute_Width(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], + Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - WaterLineWidth[iPlane] = Compute_WaterLineWidth(Plane_P0[iPlane], Plane_Normal[iPlane], config, Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - - Height[iPlane] = Compute_Height(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); + WaterLineWidth[iPlane] = + Compute_WaterLineWidth(Plane_P0[iPlane], Plane_Normal[iPlane], config, Xcoord_Airfoil[iPlane], + Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); + Height[iPlane] = Compute_Height(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], + Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); } - } - /*--- Evaluate geometrical quatities that have been computed using a filtered value (they depend on more than one point) ---*/ + /*--- Evaluate geometrical quatities that have been computed using a filtered value (they depend on more than one + * point) ---*/ for (iPlane = 0; iPlane < nPlane; iPlane++) { - Curvature[iPlane] = 0.0; if (Xcoord_Airfoil[iPlane].size() > 1) { - - if ((iPlane == 0) || (iPlane == nPlane-1)) Curvature[iPlane] = 0.0; - else Curvature[iPlane] = Compute_Curvature(LeadingEdge[iPlane-1], TrailingEdge[iPlane-1], - LeadingEdge[iPlane], TrailingEdge[iPlane], - LeadingEdge[iPlane+1], TrailingEdge[iPlane+1]); - + if ((iPlane == 0) || (iPlane == nPlane - 1)) + Curvature[iPlane] = 0.0; + else + Curvature[iPlane] = + Compute_Curvature(LeadingEdge[iPlane - 1], TrailingEdge[iPlane - 1], LeadingEdge[iPlane], + TrailingEdge[iPlane], LeadingEdge[iPlane + 1], TrailingEdge[iPlane + 1]); } - } /*--- Set the curvature and dihedral angles at the extremes ---*/ @@ -10343,8 +10048,8 @@ void CPhysicalGeometry::Compute_Fuselage(CConfig *config, bool original_surface, if ((Xcoord_Airfoil[0].size() != 0) && (Xcoord_Airfoil[1].size() != 0)) { Curvature[0] = Curvature[1]; } - if ((Xcoord_Airfoil[nPlane-1].size() != 0) && (Xcoord_Airfoil[nPlane-2].size() != 0)) { - Curvature[nPlane-1] = Curvature[nPlane-2]; + if ((Xcoord_Airfoil[nPlane - 1].size() != 0) && (Xcoord_Airfoil[nPlane - 2].size() != 0)) { + Curvature[nPlane - 1] = Curvature[nPlane - 2]; } } @@ -10353,14 +10058,17 @@ void CPhysicalGeometry::Compute_Fuselage(CConfig *config, bool original_surface, for (iPlane = 0; iPlane < nPlane; iPlane++) { if (Xcoord_Airfoil[iPlane].size() > 1) { if (config->GetTabular_FileFormat() == TAB_OUTPUT::TAB_CSV) { - Fuselage_File << -Ycoord_Airfoil[iPlane][0] <<", "<< Area[iPlane] <<", "<< Length[iPlane] <<", "<< Width[iPlane] <<", "<< WaterLineWidth[iPlane] <<", "<< Height[iPlane] <<", "<< Curvature[iPlane] - <<", "<< -LeadingEdge[iPlane][1] <<", "<< LeadingEdge[iPlane][0] <<", "<< LeadingEdge[iPlane][2] - <<", "<< -TrailingEdge[iPlane][1] <<", "<< TrailingEdge[iPlane][0] <<", "<< TrailingEdge[iPlane][2] << endl; - } - else { - Fuselage_File << -Ycoord_Airfoil[iPlane][0] <<" "<< Area[iPlane] <<" "<< Length[iPlane] <<" "<< Width[iPlane] <<" "<< WaterLineWidth[iPlane] <<" "<< Height[iPlane] <<" "<< Curvature[iPlane] - <<" "<< -LeadingEdge[iPlane][1] <<" "<< LeadingEdge[iPlane][0] <<" "<< LeadingEdge[iPlane][2] - <<" "<< -TrailingEdge[iPlane][1] <<" "<< TrailingEdge[iPlane][0] <<" "<< TrailingEdge[iPlane][2] << endl; + Fuselage_File << -Ycoord_Airfoil[iPlane][0] << ", " << Area[iPlane] << ", " << Length[iPlane] << ", " + << Width[iPlane] << ", " << WaterLineWidth[iPlane] << ", " << Height[iPlane] << ", " + << Curvature[iPlane] << ", " << -LeadingEdge[iPlane][1] << ", " << LeadingEdge[iPlane][0] + << ", " << LeadingEdge[iPlane][2] << ", " << -TrailingEdge[iPlane][1] << ", " + << TrailingEdge[iPlane][0] << ", " << TrailingEdge[iPlane][2] << endl; + } else { + Fuselage_File << -Ycoord_Airfoil[iPlane][0] << " " << Area[iPlane] << " " << Length[iPlane] << " " + << Width[iPlane] << " " << WaterLineWidth[iPlane] << " " << Height[iPlane] << " " + << Curvature[iPlane] << " " << -LeadingEdge[iPlane][1] << " " << LeadingEdge[iPlane][0] << " " + << LeadingEdge[iPlane][2] << " " << -TrailingEdge[iPlane][1] << " " << TrailingEdge[iPlane][0] + << " " << TrailingEdge[iPlane][2] << endl; } } } @@ -10370,156 +10078,150 @@ void CPhysicalGeometry::Compute_Fuselage(CConfig *config, bool original_surface, Section_File.open("fuselage_slices.dat", ios::out); for (iPlane = 0; iPlane < nPlane; iPlane++) { - if (iPlane == 0) { Section_File << "TITLE = \"Aircraft Slices\"" << endl; if (config->GetSystemMeasurements() == US) Section_File << "VARIABLES = \"x (in)\", \"y (in)\", \"z (in)\"" << endl; - else Section_File << "VARIABLES = \"x (m)\", \"y (m)\", \"z (m)\"" << endl; + else + Section_File << "VARIABLES = \"x (m)\", \"y (m)\", \"z (m)\"" << endl; } if (Xcoord_Airfoil[iPlane].size() > 1) { - - Section_File << "ZONE T=\"X = " << -Ycoord_Airfoil[iPlane][0] << " \", I= " << Ycoord_Airfoil[iPlane].size() << ", F=POINT" << endl; + Section_File << "ZONE T=\"X = " << -Ycoord_Airfoil[iPlane][0] << " \", I= " << Ycoord_Airfoil[iPlane].size() + << ", F=POINT" << endl; for (iVertex = 0; iVertex < Xcoord_Airfoil[iPlane].size(); iVertex++) { - /*--- Write the file ---*/ - Section_File << -Ycoord_Airfoil[iPlane][iVertex] << " " << Xcoord_Airfoil[iPlane][iVertex] << " " << Zcoord_Airfoil[iPlane][iVertex] << endl; + Section_File << -Ycoord_Airfoil[iPlane][iVertex] << " " << Xcoord_Airfoil[iPlane][iVertex] << " " + << Zcoord_Airfoil[iPlane][iVertex] << endl; } } - } Section_File.close(); - /*--- Compute the fuselage volume using a composite Simpson's rule ---*/ Fuselage_Volume = 0.0; - for (iPlane = 0; iPlane < nPlane-2; iPlane+=2) { + for (iPlane = 0; iPlane < nPlane - 2; iPlane += 2) { if (Xcoord_Airfoil[iPlane].size() > 1) { - Fuselage_Volume += (1.0/3.0)*dPlane*(Area[iPlane] + 4.0*Area[iPlane+1] + Area[iPlane+2]); + Fuselage_Volume += (1.0 / 3.0) * dPlane * (Area[iPlane] + 4.0 * Area[iPlane + 1] + Area[iPlane + 2]); } } /*--- Compute the fuselage wetted area ---*/ Fuselage_WettedArea = 0.0; - if (Xcoord_Airfoil[0].size() > 1) Fuselage_WettedArea += (1.0/2.0)*dPlane*Length[0]; - for (iPlane = 1; iPlane < nPlane-1; iPlane++) { + if (Xcoord_Airfoil[0].size() > 1) Fuselage_WettedArea += (1.0 / 2.0) * dPlane * Length[0]; + for (iPlane = 1; iPlane < nPlane - 1; iPlane++) { if (Xcoord_Airfoil[iPlane].size() > 1) { - Fuselage_WettedArea += dPlane*Length[iPlane]; + Fuselage_WettedArea += dPlane * Length[iPlane]; } } - if (Xcoord_Airfoil[nPlane-1].size() > 1) Fuselage_WettedArea += (1.0/2.0)*dPlane*Length[nPlane-1]; + if (Xcoord_Airfoil[nPlane - 1].size() > 1) Fuselage_WettedArea += (1.0 / 2.0) * dPlane * Length[nPlane - 1]; /*--- Evaluate Max and Min quantities ---*/ - Fuselage_MaxWidth = -1E6; Fuselage_MinWidth = 1E6; - Fuselage_MaxWaterLineWidth = -1E6; Fuselage_MinWaterLineWidth = 1E6; - Fuselage_MaxHeight = -1E6; Fuselage_MinHeight = 1E6; + Fuselage_MaxWidth = -1E6; + Fuselage_MinWidth = 1E6; + Fuselage_MaxWaterLineWidth = -1E6; + Fuselage_MinWaterLineWidth = 1E6; + Fuselage_MaxHeight = -1E6; + Fuselage_MinHeight = 1E6; Fuselage_MaxCurvature = -1E6; for (iPlane = 0; iPlane < nPlane; iPlane++) { if (Width[iPlane] != 0.0) Fuselage_MinWidth = min(Fuselage_MinWidth, Width[iPlane]); Fuselage_MaxWidth = max(Fuselage_MaxWidth, Width[iPlane]); - if (WaterLineWidth[iPlane] != 0.0) Fuselage_MinWaterLineWidth = min(Fuselage_MinWaterLineWidth, WaterLineWidth[iPlane]); + if (WaterLineWidth[iPlane] != 0.0) + Fuselage_MinWaterLineWidth = min(Fuselage_MinWaterLineWidth, WaterLineWidth[iPlane]); Fuselage_MaxWaterLineWidth = max(Fuselage_MaxWaterLineWidth, WaterLineWidth[iPlane]); if (Height[iPlane] != 0.0) Fuselage_MinHeight = min(Fuselage_MinHeight, Height[iPlane]); Fuselage_MaxHeight = max(Fuselage_MaxHeight, Height[iPlane]); Fuselage_MaxCurvature = max(Fuselage_MaxCurvature, Curvature[iPlane]); } - } /*--- Free memory for the section cuts ---*/ - delete [] Xcoord_Airfoil; - delete [] Ycoord_Airfoil; - delete [] Zcoord_Airfoil; - delete [] Variable_Airfoil; - - for (iPlane = 0; iPlane < nPlane; iPlane++) - delete [] LeadingEdge[iPlane]; - delete [] LeadingEdge; + delete[] Xcoord_Airfoil; + delete[] Ycoord_Airfoil; + delete[] Zcoord_Airfoil; + delete[] Variable_Airfoil; - for (iPlane = 0; iPlane < nPlane; iPlane++) - delete [] TrailingEdge[iPlane]; - delete [] TrailingEdge; + for (iPlane = 0; iPlane < nPlane; iPlane++) delete[] LeadingEdge[iPlane]; + delete[] LeadingEdge; - for (iPlane = 0; iPlane < nPlane; iPlane++) - delete [] Plane_P0[iPlane]; - delete [] Plane_P0; + for (iPlane = 0; iPlane < nPlane; iPlane++) delete[] TrailingEdge[iPlane]; + delete[] TrailingEdge; - for (iPlane = 0; iPlane < nPlane; iPlane++) - delete [] Plane_Normal[iPlane]; - delete [] Plane_Normal; + for (iPlane = 0; iPlane < nPlane; iPlane++) delete[] Plane_P0[iPlane]; + delete[] Plane_P0; - delete [] Area; - delete [] Length; - delete [] Width; - delete [] WaterLineWidth; - delete [] Height; - delete [] Curvature; + for (iPlane = 0; iPlane < nPlane; iPlane++) delete[] Plane_Normal[iPlane]; + delete[] Plane_Normal; + delete[] Area; + delete[] Length; + delete[] Width; + delete[] WaterLineWidth; + delete[] Height; + delete[] Curvature; } -void CPhysicalGeometry::Compute_Nacelle(CConfig *config, bool original_surface, - su2double &Nacelle_Volume, su2double &Nacelle_MinMaxThickness, - su2double &Nacelle_MinChord, su2double &Nacelle_MaxChord, - su2double &Nacelle_MaxMaxThickness, su2double &Nacelle_MinLERadius, - su2double &Nacelle_MaxLERadius, su2double &Nacelle_MinToC, su2double &Nacelle_MaxToC, - su2double &Nacelle_ObjFun_MinToC, su2double &Nacelle_MaxTwist) { - +void CPhysicalGeometry::Compute_Nacelle(CConfig* config, bool original_surface, su2double& Nacelle_Volume, + su2double& Nacelle_MinMaxThickness, su2double& Nacelle_MinChord, + su2double& Nacelle_MaxChord, su2double& Nacelle_MaxMaxThickness, + su2double& Nacelle_MinLERadius, su2double& Nacelle_MaxLERadius, + su2double& Nacelle_MinToC, su2double& Nacelle_MaxToC, + su2double& Nacelle_ObjFun_MinToC, su2double& Nacelle_MaxTwist) { unsigned short iPlane, iDim, nPlane = 0; unsigned long iVertex; su2double Angle, MinAngle, MaxAngle, dAngle, *Area, *MaxThickness, *ToC, *Chord, *LERadius, *Twist; - vector *Xcoord_Airfoil, *Ycoord_Airfoil, *Zcoord_Airfoil, *Variable_Airfoil; + vector*Xcoord_Airfoil, *Ycoord_Airfoil, *Zcoord_Airfoil, *Variable_Airfoil; ofstream Nacelle_File, Section_File; - /*--- Make a large number of section cuts for approximating volume ---*/ nPlane = config->GetnWingStations(); /*--- Allocate memory for the section cutting ---*/ - Area = new su2double [nPlane]; - MaxThickness = new su2double [nPlane]; - Chord = new su2double [nPlane]; - LERadius = new su2double [nPlane]; - ToC = new su2double [nPlane]; - Twist = new su2double [nPlane]; + Area = new su2double[nPlane]; + MaxThickness = new su2double[nPlane]; + Chord = new su2double[nPlane]; + LERadius = new su2double[nPlane]; + ToC = new su2double[nPlane]; + Twist = new su2double[nPlane]; - su2double **LeadingEdge = new su2double*[nPlane]; - for (iPlane = 0; iPlane < nPlane; iPlane++ ) - LeadingEdge[iPlane] = new su2double[nDim]; + su2double** LeadingEdge = new su2double*[nPlane]; + for (iPlane = 0; iPlane < nPlane; iPlane++) LeadingEdge[iPlane] = new su2double[nDim]; - su2double **TrailingEdge = new su2double*[nPlane]; - for (iPlane = 0; iPlane < nPlane; iPlane++ ) - TrailingEdge[iPlane] = new su2double[nDim]; + su2double** TrailingEdge = new su2double*[nPlane]; + for (iPlane = 0; iPlane < nPlane; iPlane++) TrailingEdge[iPlane] = new su2double[nDim]; - su2double **Plane_P0 = new su2double*[nPlane]; - for (iPlane = 0; iPlane < nPlane; iPlane++ ) - Plane_P0[iPlane] = new su2double[nDim]; + su2double** Plane_P0 = new su2double*[nPlane]; + for (iPlane = 0; iPlane < nPlane; iPlane++) Plane_P0[iPlane] = new su2double[nDim]; - su2double **Plane_Normal = new su2double*[nPlane]; - for (iPlane = 0; iPlane < nPlane; iPlane++ ) - Plane_Normal[iPlane] = new su2double[nDim]; + su2double** Plane_Normal = new su2double*[nPlane]; + for (iPlane = 0; iPlane < nPlane; iPlane++) Plane_Normal[iPlane] = new su2double[nDim]; - MinAngle = config->GetStations_Bounds(0); MaxAngle = config->GetStations_Bounds(1); - dAngle = fabs((MaxAngle - MinAngle)/su2double(nPlane-1)); + MinAngle = config->GetStations_Bounds(0); + MaxAngle = config->GetStations_Bounds(1); + dAngle = fabs((MaxAngle - MinAngle) / su2double(nPlane - 1)); for (iPlane = 0; iPlane < nPlane; iPlane++) { - Plane_Normal[iPlane][0] = 0.0; Plane_P0[iPlane][0] = 0.0; - Plane_Normal[iPlane][1] = 0.0; Plane_P0[iPlane][1] = 0.0; - Plane_Normal[iPlane][2] = 0.0; Plane_P0[iPlane][2] = 0.0; + Plane_Normal[iPlane][0] = 0.0; + Plane_P0[iPlane][0] = 0.0; + Plane_Normal[iPlane][1] = 0.0; + Plane_P0[iPlane][1] = 0.0; + Plane_Normal[iPlane][2] = 0.0; + Plane_P0[iPlane][2] = 0.0; /*--- Apply roll to cut the nacelle ---*/ - Angle = MinAngle + iPlane*dAngle*PI_NUMBER/180.0; + Angle = MinAngle + iPlane * dAngle * PI_NUMBER / 180.0; if (Angle <= 0) Angle = 1E-6; if (Angle >= 360) Angle = 359.999999; @@ -10530,16 +10232,18 @@ void CPhysicalGeometry::Compute_Nacelle(CConfig *config, bool original_surface, /*--- Apply tilt angle to the plane ---*/ - su2double Tilt_Angle = config->GetNacelleLocation(3)*PI_NUMBER/180; - su2double Plane_NormalX_Tilt = Plane_Normal[iPlane][0]*cos(Tilt_Angle) + Plane_Normal[iPlane][2]*sin(Tilt_Angle); + su2double Tilt_Angle = config->GetNacelleLocation(3) * PI_NUMBER / 180; + su2double Plane_NormalX_Tilt = + Plane_Normal[iPlane][0] * cos(Tilt_Angle) + Plane_Normal[iPlane][2] * sin(Tilt_Angle); su2double Plane_NormalY_Tilt = Plane_Normal[iPlane][1]; - su2double Plane_NormalZ_Tilt = Plane_Normal[iPlane][2]*cos(Tilt_Angle) - Plane_Normal[iPlane][0]*sin(Tilt_Angle); + su2double Plane_NormalZ_Tilt = + Plane_Normal[iPlane][2] * cos(Tilt_Angle) - Plane_Normal[iPlane][0] * sin(Tilt_Angle); /*--- Apply toe angle to the plane ---*/ - su2double Toe_Angle = config->GetNacelleLocation(4)*PI_NUMBER/180; - su2double Plane_NormalX_Tilt_Toe = Plane_NormalX_Tilt*cos(Toe_Angle) - Plane_NormalY_Tilt*sin(Toe_Angle); - su2double Plane_NormalY_Tilt_Toe = Plane_NormalX_Tilt*sin(Toe_Angle) + Plane_NormalY_Tilt*cos(Toe_Angle); + su2double Toe_Angle = config->GetNacelleLocation(4) * PI_NUMBER / 180; + su2double Plane_NormalX_Tilt_Toe = Plane_NormalX_Tilt * cos(Toe_Angle) - Plane_NormalY_Tilt * sin(Toe_Angle); + su2double Plane_NormalY_Tilt_Toe = Plane_NormalX_Tilt * sin(Toe_Angle) + Plane_NormalY_Tilt * cos(Toe_Angle); su2double Plane_NormalZ_Tilt_Toe = Plane_NormalZ_Tilt; /*--- Update normal vector ---*/ @@ -10553,108 +10257,116 @@ void CPhysicalGeometry::Compute_Nacelle(CConfig *config, bool original_surface, Plane_P0[iPlane][0] = config->GetNacelleLocation(0); Plane_P0[iPlane][1] = config->GetNacelleLocation(1); Plane_P0[iPlane][2] = config->GetNacelleLocation(2); - } /*--- Allocate some vectors for storing airfoil coordinates ---*/ - Xcoord_Airfoil = new vector[nPlane]; - Ycoord_Airfoil = new vector[nPlane]; - Zcoord_Airfoil = new vector[nPlane]; + Xcoord_Airfoil = new vector[nPlane]; + Ycoord_Airfoil = new vector[nPlane]; + Zcoord_Airfoil = new vector[nPlane]; Variable_Airfoil = new vector[nPlane]; /*--- Create the section slices through the geometry ---*/ for (iPlane = 0; iPlane < nPlane; iPlane++) { - - ComputeAirfoil_Section(Plane_P0[iPlane], Plane_Normal[iPlane], - -1E6, 1E6, -1E6, 1E6, -1E6, 1E6, nullptr, Xcoord_Airfoil[iPlane], - Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane], + ComputeAirfoil_Section(Plane_P0[iPlane], Plane_Normal[iPlane], -1E6, 1E6, -1E6, 1E6, -1E6, 1E6, nullptr, + Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane], Variable_Airfoil[iPlane], original_surface, config); - } /*--- Compute airfoil characteristic only in the master node ---*/ if (rank == MASTER_NODE) { - /*--- Write an output file---*/ if (config->GetTabular_FileFormat() == TAB_OUTPUT::TAB_CSV) { Nacelle_File.open("nacelle_description.csv", ios::out); if (config->GetSystemMeasurements() == US) - Nacelle_File << "\"Theta (deg)\",\"Area (in^2)\",\"Max. Thickness (in)\",\"Chord (in)\",\"Leading Edge Radius (1/in)\",\"Max. Thickness/Chord\",\"Twist (deg)\",\"Leading Edge XLoc\",\"Leading Edge ZLoc\",\"Trailing Edge XLoc\",\"Trailing Edge ZLoc\"" << endl; + Nacelle_File << "\"Theta (deg)\",\"Area (in^2)\",\"Max. Thickness (in)\",\"Chord (in)\",\"Leading Edge Radius " + "(1/in)\",\"Max. Thickness/Chord\",\"Twist (deg)\",\"Leading Edge XLoc\",\"Leading Edge " + "ZLoc\",\"Trailing Edge XLoc\",\"Trailing Edge ZLoc\"" + << endl; else - Nacelle_File << "\"Theta (deg)\",\"Area (m^2)\",\"Max. Thickness (m)\",\"Chord (m)\",\"Leading Edge Radius (1/m)\",\"Max. Thickness/Chord\",\"Twist (deg)\",\"Curvature (1/in)\",\"Dihedral (deg)\",\"Leading Edge XLoc\",\"Leading Edge ZLoc\",\"Trailing Edge XLoc\",\"Trailing Edge ZLoc\"" << endl; - } - else { + Nacelle_File + << "\"Theta (deg)\",\"Area (m^2)\",\"Max. Thickness (m)\",\"Chord (m)\",\"Leading Edge Radius " + "(1/m)\",\"Max. Thickness/Chord\",\"Twist (deg)\",\"Curvature (1/in)\",\"Dihedral (deg)\",\"Leading " + "Edge XLoc\",\"Leading Edge ZLoc\",\"Trailing Edge XLoc\",\"Trailing Edge ZLoc\"" + << endl; + } else { Nacelle_File.open("nacelle_description.dat", ios::out); Nacelle_File << "TITLE = \"Nacelle description\"" << endl; if (config->GetSystemMeasurements() == US) - Nacelle_File << "VARIABLES = \"q (deg)\",\"Area (in2)\",\"Max. Thickness (in)\",\"Chord (in)\",\"Leading Edge Radius (1/in)\",\"Max. Thickness/Chord\",\"Twist (deg)\",\"Leading Edge XLoc\",\"Leading Edge ZLoc\",\"Trailing Edge XLoc\",\"Trailing Edge ZLoc\"" << endl; + Nacelle_File + << "VARIABLES = \"q (deg)\",\"Area (in2)\",\"Max. Thickness (in)\",\"Chord " + "(in)\",\"Leading Edge Radius (1/in)\",\"Max. Thickness/Chord\",\"Twist (deg)\",\"Leading Edge " + "XLoc\",\"Leading Edge ZLoc\",\"Trailing Edge XLoc\",\"Trailing Edge ZLoc\"" + << endl; else - Nacelle_File << "VARIABLES = \"q (deg)\",\"Area (m2)\",\"Max. Thickness (m)\",\"Chord (m)\",\"Leading Edge Radius (1/m)\",\"Max. Thickness/Chord\",\"Twist (deg)\",\"Leading Edge XLoc\",\"Leading Edge ZLoc\",\"Trailing Edge XLoc\",\"Trailing Edge ZLoc\"" << endl; + Nacelle_File + << "VARIABLES = \"q (deg)\",\"Area (m2)\",\"Max. Thickness (m)\",\"Chord " + "(m)\",\"Leading Edge Radius (1/m)\",\"Max. Thickness/Chord\",\"Twist (deg)\",\"Leading Edge " + "XLoc\",\"Leading Edge ZLoc\",\"Trailing Edge XLoc\",\"Trailing Edge ZLoc\"" + << endl; Nacelle_File << "ZONE T= \"Baseline nacelle\"" << endl; } - /*--- Evaluate geometrical quatities that do not require any kind of filter, local to each point ---*/ for (iPlane = 0; iPlane < nPlane; iPlane++) { - for (iDim = 0; iDim < nDim; iDim++) { - LeadingEdge[iPlane][iDim] = 0.0; + LeadingEdge[iPlane][iDim] = 0.0; TrailingEdge[iPlane][iDim] = 0.0; } - Area[iPlane] = 0.0; - MaxThickness[iPlane] = 0.0; - Chord[iPlane] = 0.0; - LERadius[iPlane] = 0.0; - ToC[iPlane] = 0.0; - Twist[iPlane] = 0.0; + Area[iPlane] = 0.0; + MaxThickness[iPlane] = 0.0; + Chord[iPlane] = 0.0; + LERadius[iPlane] = 0.0; + ToC[iPlane] = 0.0; + Twist[iPlane] = 0.0; if (Xcoord_Airfoil[iPlane].size() > 1) { + Compute_Wing_LeadingTrailing(LeadingEdge[iPlane], TrailingEdge[iPlane], Plane_P0[iPlane], Plane_Normal[iPlane], + Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - Compute_Wing_LeadingTrailing(LeadingEdge[iPlane], TrailingEdge[iPlane], Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); + Area[iPlane] = Compute_Area(Plane_P0[iPlane], Plane_Normal[iPlane], config, Xcoord_Airfoil[iPlane], + Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - Area[iPlane] = Compute_Area(Plane_P0[iPlane], Plane_Normal[iPlane], config, Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); + MaxThickness[iPlane] = + Compute_MaxThickness(Plane_P0[iPlane], Plane_Normal[iPlane], config, Xcoord_Airfoil[iPlane], + Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - MaxThickness[iPlane] = Compute_MaxThickness(Plane_P0[iPlane], Plane_Normal[iPlane], config, Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); + Chord[iPlane] = Compute_Chord(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], + Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - Chord[iPlane] = Compute_Chord(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); + Twist[iPlane] = Compute_Twist(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], + Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - Twist[iPlane] = Compute_Twist(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - - LERadius[iPlane] = Compute_LERadius(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); + LERadius[iPlane] = Compute_LERadius(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], + Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); ToC[iPlane] = MaxThickness[iPlane] / Chord[iPlane]; - - } - } /*--- Plot the geometrical quatities ---*/ for (iPlane = 0; iPlane < nPlane; iPlane++) { - - su2double theta_deg = atan2(Plane_Normal[iPlane][1], -Plane_Normal[iPlane][2])/PI_NUMBER*180 + 180; + su2double theta_deg = atan2(Plane_Normal[iPlane][1], -Plane_Normal[iPlane][2]) / PI_NUMBER * 180 + 180; if (Xcoord_Airfoil[iPlane].size() > 1) { if (config->GetTabular_FileFormat() == TAB_OUTPUT::TAB_CSV) { - Nacelle_File << theta_deg <<", "<< Area[iPlane] <<", "<< MaxThickness[iPlane] <<", "<< Chord[iPlane] <<", "<< LERadius[iPlane] <<", "<< ToC[iPlane] - <<", "<< Twist[iPlane] <<", "<< LeadingEdge[iPlane][0] <<", "<< LeadingEdge[iPlane][2] - <<", "<< TrailingEdge[iPlane][0] <<", "<< TrailingEdge[iPlane][2] << endl; - } - else { - Nacelle_File << theta_deg <<" "<< Area[iPlane] <<" "<< MaxThickness[iPlane] <<" "<< Chord[iPlane] <<" "<< LERadius[iPlane] <<" "<< ToC[iPlane] - <<" "<< Twist[iPlane] <<" "<< LeadingEdge[iPlane][0] <<" "<< LeadingEdge[iPlane][2] - <<" "<< TrailingEdge[iPlane][0] <<" "<< TrailingEdge[iPlane][2] << endl; - + Nacelle_File << theta_deg << ", " << Area[iPlane] << ", " << MaxThickness[iPlane] << ", " << Chord[iPlane] + << ", " << LERadius[iPlane] << ", " << ToC[iPlane] << ", " << Twist[iPlane] << ", " + << LeadingEdge[iPlane][0] << ", " << LeadingEdge[iPlane][2] << ", " << TrailingEdge[iPlane][0] + << ", " << TrailingEdge[iPlane][2] << endl; + } else { + Nacelle_File << theta_deg << " " << Area[iPlane] << " " << MaxThickness[iPlane] << " " << Chord[iPlane] << " " + << LERadius[iPlane] << " " << ToC[iPlane] << " " << Twist[iPlane] << " " + << LeadingEdge[iPlane][0] << " " << LeadingEdge[iPlane][2] << " " << TrailingEdge[iPlane][0] + << " " << TrailingEdge[iPlane][2] << endl; } } - } Nacelle_File.close(); @@ -10662,23 +10374,24 @@ void CPhysicalGeometry::Compute_Nacelle(CConfig *config, bool original_surface, Section_File.open("nacelle_slices.dat", ios::out); for (iPlane = 0; iPlane < nPlane; iPlane++) { - if (iPlane == 0) { Section_File << "TITLE = \"Nacelle Slices\"" << endl; if (config->GetSystemMeasurements() == US) - Section_File << "VARIABLES = \"x (in)\", \"y (in)\", \"z (in)\", \"x2D/c\", \"y2D/c\"" << endl; - else Section_File << "VARIABLES = \"x (m)\", \"y (m)\", \"z (m)\", \"x2D/c\", \"y2D/c\"" << endl; + Section_File << "VARIABLES = \"x (in)\", \"y (in)\", \"z (in)\", \"x2D/c\", \"y2D/c\"" + << endl; + else + Section_File << "VARIABLES = \"x (m)\", \"y (m)\", \"z (m)\", \"x2D/c\", \"y2D/c\"" + << endl; } if (Xcoord_Airfoil[iPlane].size() > 1) { + su2double theta_deg = atan2(Plane_Normal[iPlane][1], -Plane_Normal[iPlane][2]) / PI_NUMBER * 180 + 180; + su2double Angle = theta_deg * PI_NUMBER / 180 - 0.5 * PI_NUMBER; - su2double theta_deg = atan2(Plane_Normal[iPlane][1], -Plane_Normal[iPlane][2])/PI_NUMBER*180 + 180; - su2double Angle = theta_deg*PI_NUMBER/180 - 0.5*PI_NUMBER; - - Section_File << "ZONE T=\"q = " << theta_deg << " deg\", I= " << Xcoord_Airfoil[iPlane].size() << ", F=POINT" << endl; + Section_File << "ZONE T=\"q = " << theta_deg << " deg\", I= " << Xcoord_Airfoil[iPlane].size() + << ", F=POINT" << endl; for (iVertex = 0; iVertex < Xcoord_Airfoil[iPlane].size(); iVertex++) { - /*--- Move to the origin ---*/ su2double XValue_ = Xcoord_Airfoil[iPlane][iVertex] - LeadingEdge[iPlane][0]; @@ -10686,40 +10399,48 @@ void CPhysicalGeometry::Compute_Nacelle(CConfig *config, bool original_surface, /*--- Rotate the airfoil and divide by the chord ---*/ - su2double ValCos = cos(Twist[iPlane]*PI_NUMBER/180.0); - su2double ValSin = sin(Twist[iPlane]*PI_NUMBER/180.0); + su2double ValCos = cos(Twist[iPlane] * PI_NUMBER / 180.0); + su2double ValSin = sin(Twist[iPlane] * PI_NUMBER / 180.0); - su2double XValue = (XValue_*ValCos - ZValue_*ValSin) / Chord[iPlane]; - su2double ZValue = (ZValue_*ValCos + XValue_*ValSin) / Chord[iPlane]; + su2double XValue = (XValue_ * ValCos - ZValue_ * ValSin) / Chord[iPlane]; + su2double ZValue = (ZValue_ * ValCos + XValue_ * ValSin) / Chord[iPlane]; su2double XCoord = Xcoord_Airfoil[iPlane][iVertex] + config->GetNacelleLocation(0); - su2double YCoord = (Ycoord_Airfoil[iPlane][iVertex]*cos(Angle) - Zcoord_Airfoil[iPlane][iVertex]*sin(Angle)) + config->GetNacelleLocation(1); - su2double ZCoord = (Zcoord_Airfoil[iPlane][iVertex]*cos(Angle) + Ycoord_Airfoil[iPlane][iVertex]*sin(Angle)) + config->GetNacelleLocation(2); + su2double YCoord = + (Ycoord_Airfoil[iPlane][iVertex] * cos(Angle) - Zcoord_Airfoil[iPlane][iVertex] * sin(Angle)) + + config->GetNacelleLocation(1); + su2double ZCoord = + (Zcoord_Airfoil[iPlane][iVertex] * cos(Angle) + Ycoord_Airfoil[iPlane][iVertex] * sin(Angle)) + + config->GetNacelleLocation(2); /*--- Write the file ---*/ - Section_File << XCoord << " " << YCoord << " " << ZCoord << " " << XValue << " " << ZValue << endl; + Section_File << XCoord << " " << YCoord << " " << ZCoord << " " << XValue << " " << ZValue << endl; } } - } Section_File.close(); - /*--- Compute the wing volume using a composite Simpson's rule ---*/ Nacelle_Volume = 0.0; - for (iPlane = 0; iPlane < nPlane-2; iPlane+=2) { + for (iPlane = 0; iPlane < nPlane - 2; iPlane += 2) { if (Xcoord_Airfoil[iPlane].size() > 1) { - Nacelle_Volume += (1.0/3.0)*dAngle*(Area[iPlane] + 4.0*Area[iPlane+1] + Area[iPlane+2]); + Nacelle_Volume += (1.0 / 3.0) * dAngle * (Area[iPlane] + 4.0 * Area[iPlane + 1] + Area[iPlane + 2]); } } /*--- Evaluate Max and Min quantities ---*/ - Nacelle_MaxMaxThickness = -1E6; Nacelle_MinMaxThickness = 1E6; Nacelle_MinChord = 1E6; Nacelle_MaxChord = -1E6; - Nacelle_MinLERadius = 1E6; Nacelle_MaxLERadius = -1E6; Nacelle_MinToC = 1E6; Nacelle_MaxToC = -1E6; + Nacelle_MaxMaxThickness = -1E6; + Nacelle_MinMaxThickness = 1E6; + Nacelle_MinChord = 1E6; + Nacelle_MaxChord = -1E6; + Nacelle_MinLERadius = 1E6; + Nacelle_MaxLERadius = -1E6; + Nacelle_MinToC = 1E6; + Nacelle_MaxToC = -1E6; Nacelle_MaxTwist = -1E6; for (iPlane = 0; iPlane < nPlane; iPlane++) { @@ -10731,46 +10452,39 @@ void CPhysicalGeometry::Compute_Nacelle(CConfig *config, bool original_surface, Nacelle_MaxLERadius = max(Nacelle_MaxLERadius, LERadius[iPlane]); if (ToC[iPlane] != 0.0) Nacelle_MinToC = min(Nacelle_MinToC, ToC[iPlane]); Nacelle_MaxToC = max(Nacelle_MaxToC, ToC[iPlane]); - Nacelle_ObjFun_MinToC = sqrt((Nacelle_MinToC - 0.07)*(Nacelle_MinToC - 0.07)); + Nacelle_ObjFun_MinToC = sqrt((Nacelle_MinToC - 0.07) * (Nacelle_MinToC - 0.07)); Nacelle_MaxTwist = max(Nacelle_MaxTwist, fabs(Twist[iPlane])); } - } /*--- Free memory for the section cuts ---*/ - delete [] Xcoord_Airfoil; - delete [] Ycoord_Airfoil; - delete [] Zcoord_Airfoil; - delete [] Variable_Airfoil; + delete[] Xcoord_Airfoil; + delete[] Ycoord_Airfoil; + delete[] Zcoord_Airfoil; + delete[] Variable_Airfoil; - for (iPlane = 0; iPlane < nPlane; iPlane++) - delete [] LeadingEdge[iPlane]; - delete [] LeadingEdge; + for (iPlane = 0; iPlane < nPlane; iPlane++) delete[] LeadingEdge[iPlane]; + delete[] LeadingEdge; - for (iPlane = 0; iPlane < nPlane; iPlane++) - delete [] TrailingEdge[iPlane]; - delete [] TrailingEdge; + for (iPlane = 0; iPlane < nPlane; iPlane++) delete[] TrailingEdge[iPlane]; + delete[] TrailingEdge; - for (iPlane = 0; iPlane < nPlane; iPlane++) - delete [] Plane_P0[iPlane]; - delete [] Plane_P0; + for (iPlane = 0; iPlane < nPlane; iPlane++) delete[] Plane_P0[iPlane]; + delete[] Plane_P0; - for (iPlane = 0; iPlane < nPlane; iPlane++) - delete [] Plane_Normal[iPlane]; - delete [] Plane_Normal; - - delete [] Area; - delete [] MaxThickness; - delete [] Chord; - delete [] LERadius; - delete [] ToC; - delete [] Twist; + for (iPlane = 0; iPlane < nPlane; iPlane++) delete[] Plane_Normal[iPlane]; + delete[] Plane_Normal; + delete[] Area; + delete[] MaxThickness; + delete[] Chord; + delete[] LERadius; + delete[] ToC; + delete[] Twist; } -std::unique_ptr CPhysicalGeometry::ComputeViscousWallADT(const CConfig *config) const{ - +std::unique_ptr CPhysicalGeometry::ComputeViscousWallADT(const CConfig* config) const { /*--------------------------------------------------------------------------*/ /*--- Step 1: Create the coordinates and connectivity of the linear ---*/ /*--- subelements of the local boundaries that must be taken ---*/ @@ -10792,15 +10506,11 @@ std::unique_ptr CPhysicalGeometry::ComputeViscousWallADT(const CC /* Loop over the boundary markers. */ - for(unsigned short iMarker=0; iMarkerGetnMarker_All(); ++iMarker) { - - + for (unsigned short iMarker = 0; iMarker < config->GetnMarker_All(); ++iMarker) { /* Check for a viscous wall. */ - if( config->GetViscous_Wall(iMarker)) { - + if (config->GetViscous_Wall(iMarker)) { /* Loop over the surface elements of this marker. */ - for(unsigned long iElem=0; iElem < nElem_Bound[iMarker]; iElem++) { - + for (unsigned long iElem = 0; iElem < nElem_Bound[iMarker]; iElem++) { /* Set the flag of the mesh points on this surface to true. */ for (unsigned short iNode = 0; iNode < bound[iMarker][iElem]->GetnNodes(); iNode++) { unsigned long iPoint = bound[iMarker][iElem]->GetNode(iNode); @@ -10809,10 +10519,10 @@ std::unique_ptr CPhysicalGeometry::ComputeViscousWallADT(const CC /* Determine the necessary data from the corresponding standard face, such as the number of linear subfaces, the number of DOFs per linear subface and the corresponding local connectivity. */ - const unsigned short VTK_Type = bound[iMarker][iElem]->GetVTK_Type(); - const unsigned short nDOFsPerElem = bound[iMarker][iElem]->GetnNodes(); + const unsigned short VTK_Type = bound[iMarker][iElem]->GetVTK_Type(); + const unsigned short nDOFsPerElem = bound[iMarker][iElem]->GetnNodes(); - /* Loop over the nodes of element and store the required data. */ + /* Loop over the nodes of element and store the required data. */ markerIDs.push_back(iMarker); VTK_TypeElem.push_back(VTK_Type); @@ -10829,19 +10539,17 @@ std::unique_ptr CPhysicalGeometry::ComputeViscousWallADT(const CC vector surfaceCoor; unsigned long nVertex_SolidWall = 0; - for(unsigned long i=0; iGetCoord(i, k)); + for (unsigned short k = 0; k < nDim; ++k) surfaceCoor.push_back(nodes->GetCoord(i, k)); } } /*--- Change the surface connectivity, such that it corresponds to the entries in surfaceCoor rather than in meshPoints. ---*/ - for(unsigned long i=0; i CPhysicalGeometry::ComputeViscousWallADT(const CC /*--- points of the elements close to a wall boundary. ---*/ /*--------------------------------------------------------------------------*/ - std::unique_ptr WallADT(new CADTElemClass(nDim, surfaceCoor, surfaceConn, VTK_TypeElem, - markerIDs, elemIDs, true)); + std::unique_ptr WallADT( + new CADTElemClass(nDim, surfaceCoor, surfaceConn, VTK_TypeElem, markerIDs, elemIDs, true)); return WallADT; - } void CPhysicalGeometry::SetWallDistance(CADTElemClass* WallADT, const CConfig* config, unsigned short iZone) { - /*--------------------------------------------------------------------------*/ /*--- Step 3: Loop over all interior mesh nodes and compute minimum ---*/ /*--- distance to a solid wall element ---*/ @@ -10869,16 +10575,16 @@ void CPhysicalGeometry::SetWallDistance(CADTElemClass* WallADT, const CConfig* c /*--- Solid wall boundary nodes are present. Compute the wall distance for all nodes. ---*/ - SU2_OMP_FOR_DYN(roundUpDiv(nPoint,2*omp_get_max_threads())) - for (unsigned long iPoint=0; iPointDetermineNearestElement(nodes->GetCoord(iPoint), dist, markerID, elemID, rankID); - if(dist < nodes->GetWall_Distance(iPoint)){ + if (dist < nodes->GetWall_Distance(iPoint)) { nodes->SetWall_Distance(iPoint, dist, rankID, iZone, markerID, elemID); } } diff --git a/Common/src/geometry/dual_grid/CDualGrid.cpp b/Common/src/geometry/dual_grid/CDualGrid.cpp index a3969b4088e..2a277094bc6 100644 --- a/Common/src/geometry/dual_grid/CDualGrid.cpp +++ b/Common/src/geometry/dual_grid/CDualGrid.cpp @@ -29,6 +29,6 @@ unsigned short CDualGrid::nDim = 0; -CDualGrid::CDualGrid(unsigned short val_nDim) { nDim = val_nDim;} +CDualGrid::CDualGrid(unsigned short val_nDim) { nDim = val_nDim; } CDualGrid::~CDualGrid() {} diff --git a/Common/src/geometry/dual_grid/CEdge.cpp b/Common/src/geometry/dual_grid/CEdge.cpp index a5f30f90473..d3a45abeee1 100644 --- a/Common/src/geometry/dual_grid/CEdge.cpp +++ b/Common/src/geometry/dual_grid/CEdge.cpp @@ -32,39 +32,31 @@ using namespace GeometryToolbox; CEdge::CEdge(unsigned long nEdge_, unsigned long nDim) - : nEdge(nEdge_), - nEdgeSIMD(nextMultiple(nEdge_, simd::preferredLen())) { + : nEdge(nEdge_), nEdgeSIMD(nextMultiple(nEdge_, simd::preferredLen())) { /*--- Allocate with padding. ---*/ - Nodes.resize(nEdgeSIMD,2) = 0; - Normal.resize(nEdgeSIMD,nDim) = su2double(0.0); + Nodes.resize(nEdgeSIMD, 2) = 0; + Normal.resize(nEdgeSIMD, nDim) = su2double(0.0); } -void CEdge::SetZeroValues(void) { - Normal = su2double(0.0); -} - -su2double CEdge::GetVolume(const su2double *coord_Edge_CG, - const su2double *coord_FaceElem_CG, - const su2double *coord_Elem_CG, - const su2double *coord_Point) { +void CEdge::SetZeroValues(void) { Normal = su2double(0.0); } +su2double CEdge::GetVolume(const su2double* coord_Edge_CG, const su2double* coord_FaceElem_CG, + const su2double* coord_Elem_CG, const su2double* coord_Point) { constexpr unsigned long nDim = 3; su2double vec_a[nDim] = {0.0}, vec_b[nDim] = {0.0}, vec_c[nDim] = {0.0}, vec_d[nDim] = {0.0}; - Distance(nDim, coord_Edge_CG, coord_Point, vec_a); + Distance(nDim, coord_Edge_CG, coord_Point, vec_a); Distance(nDim, coord_FaceElem_CG, coord_Point, vec_b); - Distance(nDim, coord_Elem_CG, coord_Point, vec_c); + Distance(nDim, coord_Elem_CG, coord_Point, vec_c); CrossProduct(vec_a, vec_b, vec_d); return fabs(DotProduct(nDim, vec_c, vec_d)) / 6.0; } -su2double CEdge::GetVolume(const su2double *coord_Edge_CG, - const su2double *coord_Elem_CG, - const su2double *coord_Point) { - +su2double CEdge::GetVolume(const su2double* coord_Edge_CG, const su2double* coord_Elem_CG, + const su2double* coord_Point) { constexpr unsigned long nDim = 2; su2double vec_a[nDim] = {0.0}, vec_b[nDim] = {0.0}; @@ -72,14 +64,11 @@ su2double CEdge::GetVolume(const su2double *coord_Edge_CG, Distance(nDim, coord_Elem_CG, coord_Point, vec_a); Distance(nDim, coord_Edge_CG, coord_Point, vec_b); - return 0.5 * fabs(vec_a[0]*vec_b[1] - vec_a[1]*vec_b[0]); + return 0.5 * fabs(vec_a[0] * vec_b[1] - vec_a[1] * vec_b[0]); } -void CEdge::SetNodes_Coord(unsigned long iEdge, - const su2double *coord_Edge_CG, - const su2double *coord_FaceElem_CG, - const su2double *coord_Elem_CG) { - +void CEdge::SetNodes_Coord(unsigned long iEdge, const su2double* coord_Edge_CG, const su2double* coord_FaceElem_CG, + const su2double* coord_Elem_CG) { constexpr unsigned long nDim = 3; su2double vec_a[nDim] = {0.0}, vec_b[nDim] = {0.0}, Dim_Normal[nDim]; @@ -89,14 +78,10 @@ void CEdge::SetNodes_Coord(unsigned long iEdge, CrossProduct(vec_a, vec_b, Dim_Normal); - for (auto iDim = 0ul; iDim < nDim; ++iDim) - Normal(iEdge,iDim) += 0.5 * Dim_Normal[iDim]; + for (auto iDim = 0ul; iDim < nDim; ++iDim) Normal(iEdge, iDim) += 0.5 * Dim_Normal[iDim]; } -void CEdge::SetNodes_Coord(unsigned long iEdge, - const su2double *coord_Edge_CG, - const su2double *coord_Elem_CG) { - - Normal(iEdge,0) += coord_Elem_CG[1] - coord_Edge_CG[1]; - Normal(iEdge,1) -= coord_Elem_CG[0] - coord_Edge_CG[0]; +void CEdge::SetNodes_Coord(unsigned long iEdge, const su2double* coord_Edge_CG, const su2double* coord_Elem_CG) { + Normal(iEdge, 0) += coord_Elem_CG[1] - coord_Edge_CG[1]; + Normal(iEdge, 1) -= coord_Elem_CG[0] - coord_Edge_CG[0]; } diff --git a/Common/src/geometry/dual_grid/CPoint.cpp b/Common/src/geometry/dual_grid/CPoint.cpp index 8f3eaefff01..190bf7ad69a 100644 --- a/Common/src/geometry/dual_grid/CPoint.cpp +++ b/Common/src/geometry/dual_grid/CPoint.cpp @@ -29,13 +29,9 @@ #include "../../../include/CConfig.hpp" #include "../../../include/parallelization/omp_structure.hpp" -CPoint::CPoint(unsigned long npoint, unsigned long ndim) : nDim(ndim) { - - MinimalAllocation(npoint); -} +CPoint::CPoint(unsigned long npoint, unsigned long ndim) : nDim(ndim) { MinimalAllocation(npoint); } void CPoint::MinimalAllocation(unsigned long npoint) { - /*--- Global index a parallel simulation. ---*/ GlobalIndex.resize(npoint) = 0; @@ -43,19 +39,16 @@ void CPoint::MinimalAllocation(unsigned long npoint) { Color.resize(npoint) = 0; /*--- Coordinates. ---*/ - Coord.resize(npoint,nDim) = su2double(0.0); - + Coord.resize(npoint, nDim) = su2double(0.0); } -CPoint::CPoint(unsigned long npoint, unsigned long ndim, unsigned short imesh, const CConfig *config) : nDim(ndim) { - +CPoint::CPoint(unsigned long npoint, unsigned long ndim, unsigned short imesh, const CConfig* config) : nDim(ndim) { MinimalAllocation(npoint); FullAllocation(imesh, config); } -void CPoint::FullAllocation(unsigned short imesh, const CConfig *config) { - +void CPoint::FullAllocation(unsigned short imesh, const CConfig* config) { const auto npoint = GlobalIndex.size(); /*--- Volumes ---*/ @@ -74,8 +67,8 @@ void CPoint::FullAllocation(unsigned short imesh, const CConfig *config) { } if (config->GetDiscrete_Adjoint()) { - AD_InputIndex.resize(npoint,nDim) = 0; - AD_OutputIndex.resize(npoint,nDim) = 0; + AD_InputIndex.resize(npoint, nDim) = 0; + AD_OutputIndex.resize(npoint, nDim) = 0; } /*--- Multigrid structures. ---*/ @@ -103,27 +96,26 @@ void CPoint::FullAllocation(unsigned short imesh, const CConfig *config) { /*--- For smoothing the numerical grid coordinates ---*/ if (config->GetSmoothNumGrid()) { - Coord_Old.resize(npoint,nDim) = su2double(0.0); - Coord_Sum.resize(npoint,nDim) = su2double(0.0); + Coord_Old.resize(npoint, nDim) = su2double(0.0); + Coord_Sum.resize(npoint, nDim) = su2double(0.0); } /*--- Storage of grid velocities for dynamic meshes. ---*/ if (config->GetDynamic_Grid()) { - GridVel.resize(npoint,nDim) = su2double(0.0); + GridVel.resize(npoint, nDim) = su2double(0.0); /*--- Grid velocity gradients are needed for the continuous adjoint. ---*/ - if (config->GetContinuous_Adjoint()) - GridVel_Grad.resize(npoint,nDim,nDim,0.0); + if (config->GetContinuous_Adjoint()) GridVel_Grad.resize(npoint, nDim, nDim, 0.0); /*--- Structures for storing old node coordinates for computing grid * velocities via finite differencing with dynamically deforming meshes. ---*/ /*--- In the case of CMeshSolver, these coordinates are stored as solutions to the mesh problem. ---*/ if (config->GetGrid_Movement() && (config->GetTime_Marching() != TIME_MARCHING::STEADY)) { - Coord_n.resize(npoint,nDim) = su2double(0.0); - Coord_p1.resize(npoint,nDim) = su2double(0.0); - Coord_n1.resize(npoint,nDim) = su2double(0.0); - if (Coord_Old.empty()) Coord_Old.resize(npoint,nDim) = su2double(0.0); + Coord_n.resize(npoint, nDim) = su2double(0.0); + Coord_p1.resize(npoint, nDim) = su2double(0.0); + Coord_n1.resize(npoint, nDim) = su2double(0.0); + if (Coord_Old.empty()) Coord_Old.resize(npoint, nDim) = su2double(0.0); } } @@ -140,18 +132,13 @@ void CPoint::FullAllocation(unsigned short imesh, const CConfig *config) { RoughnessHeight.resize(npoint) = su2double(0.0); SharpEdge_Distance.resize(npoint) = su2double(0.0); - } -void CPoint::SetElems(const vector >& elemsMatrix) { - - Elem = CCompressedSparsePatternL(elemsMatrix); -} +void CPoint::SetElems(const vector >& elemsMatrix) { Elem = CCompressedSparsePatternL(elemsMatrix); } void CPoint::SetPoints(const vector >& pointsMatrix) { - Point = CCompressedSparsePatternUL(pointsMatrix); - Edge = CCompressedSparsePatternL(Point.outerPtr(), Point.outerPtr()+Point.getOuterSize()+1, long(-1)); + Edge = CCompressedSparsePatternL(Point.outerPtr(), Point.outerPtr() + Point.getOuterSize() + 1, long(-1)); } void CPoint::SetVolume_n() { @@ -205,4 +192,3 @@ void CPoint::SetCoord_Old() { } void CPoint::SetCoord_SumZero() { parallelSet(Coord_Sum.size(), 0.0, Coord_Sum.data()); } - diff --git a/Common/src/geometry/dual_grid/CTurboVertex.cpp b/Common/src/geometry/dual_grid/CTurboVertex.cpp index 592bbc1cb6c..4c19dd2bf21 100644 --- a/Common/src/geometry/dual_grid/CTurboVertex.cpp +++ b/Common/src/geometry/dual_grid/CTurboVertex.cpp @@ -27,20 +27,15 @@ #include "../../../include/geometry/dual_grid/CTurboVertex.hpp" -CTurboVertex::CTurboVertex(unsigned long val_point, unsigned short val_nDim) : CVertex(val_point, val_nDim){ +CTurboVertex::CTurboVertex(unsigned long val_point, unsigned short val_nDim) : CVertex(val_point, val_nDim) { unsigned short iDim; - /*--- Pointers initialization ---*/ + /*--- Pointers initialization ---*/ TurboNormal = nullptr; /*--- Allocate node, and face normal ---*/ - TurboNormal = new su2double [nDim]; + TurboNormal = new su2double[nDim]; /*--- Initializate the structure ---*/ - for (iDim = 0; iDim < nDim; iDim ++) TurboNormal[iDim] = 0.0; - + for (iDim = 0; iDim < nDim; iDim++) TurboNormal[iDim] = 0.0; } -CTurboVertex::~CTurboVertex() { - - delete [] TurboNormal; - -} +CTurboVertex::~CTurboVertex() { delete[] TurboNormal; } diff --git a/Common/src/geometry/dual_grid/CVertex.cpp b/Common/src/geometry/dual_grid/CVertex.cpp index 4b3e9d657d8..844245759ab 100644 --- a/Common/src/geometry/dual_grid/CVertex.cpp +++ b/Common/src/geometry/dual_grid/CVertex.cpp @@ -30,15 +30,10 @@ using namespace GeometryToolbox; -CVertex::CVertex(unsigned long val_point, unsigned short val_nDim) : - CDualGrid(val_nDim) { - Nodes[0] = val_point; -} - -void CVertex::SetNodes_Coord(const su2double *coord_Edge_CG, - const su2double *coord_FaceElem_CG, - const su2double *coord_Elem_CG) { +CVertex::CVertex(unsigned long val_point, unsigned short val_nDim) : CDualGrid(val_nDim) { Nodes[0] = val_point; } +void CVertex::SetNodes_Coord(const su2double* coord_Edge_CG, const su2double* coord_FaceElem_CG, + const su2double* coord_Elem_CG) { constexpr unsigned long nDim = 3; su2double vec_a[nDim] = {0.0}, vec_b[nDim] = {0.0}, Dim_Normal[nDim]; @@ -47,13 +42,10 @@ void CVertex::SetNodes_Coord(const su2double *coord_Edge_CG, CrossProduct(vec_a, vec_b, Dim_Normal); - for (auto iDim = 0ul; iDim < nDim; ++iDim) - Normal[iDim] += 0.5 * Dim_Normal[iDim]; + for (auto iDim = 0ul; iDim < nDim; ++iDim) Normal[iDim] += 0.5 * Dim_Normal[iDim]; } -void CVertex::SetNodes_Coord(const su2double *val_coord_Edge_CG, - const su2double *val_coord_Elem_CG) { - - Normal[0] += val_coord_Elem_CG[1]-val_coord_Edge_CG[1]; - Normal[1] -= val_coord_Elem_CG[0]-val_coord_Edge_CG[0]; +void CVertex::SetNodes_Coord(const su2double* val_coord_Edge_CG, const su2double* val_coord_Elem_CG) { + Normal[0] += val_coord_Elem_CG[1] - val_coord_Edge_CG[1]; + Normal[1] -= val_coord_Elem_CG[0] - val_coord_Edge_CG[0]; } diff --git a/Common/src/geometry/elements/CElement.cpp b/Common/src/geometry/elements/CElement.cpp index 2e35eeecf98..91c41d7ff9a 100644 --- a/Common/src/geometry/elements/CElement.cpp +++ b/Common/src/geometry/elements/CElement.cpp @@ -27,9 +27,7 @@ #include "../../../include/geometry/elements/CElement.hpp" - CElement::CElement(unsigned short ngauss, unsigned short nnodes, unsigned short ndim) { - nGaussPoints = ngauss; nNodes = nnodes; nDim = ndim; @@ -42,8 +40,7 @@ CElement::CElement(unsigned short ngauss, unsigned short nnodes, unsigned short RefCoord.resize(nNodes, MAXNDIM) = su2double(0.0); GaussPoint.reserve(nGaussPoints); - for(unsigned short iGauss = 0; iGauss < nGaussPoints; ++iGauss) - GaussPoint.emplace_back(iGauss, nDim, nNodes); + for (unsigned short iGauss = 0; iGauss < nGaussPoints; ++iGauss) GaussPoint.emplace_back(iGauss, nDim, nNodes); GaussWeight.resize(nGaussPoints) = su2double(0.0); NodalExtrap.resize(nNodes, nGaussPoints) = su2double(0.0); @@ -53,33 +50,30 @@ CElement::CElement(unsigned short ngauss, unsigned short nnodes, unsigned short Mab.resize(nNodes, nNodes); Ks_ab.resize(nNodes, nNodes); Kab.resize(nNodes); - for(auto& kab_i : Kab) kab_i.resize(nNodes, nDim*nDim); + for (auto& kab_i : Kab) kab_i.resize(nNodes, nDim * nDim); Kt_a.resize(nNodes, nDim); FDL_a.resize(nNodes, nDim); - HiHj.resize(nNodes,nNodes); + HiHj.resize(nNodes, nNodes); DHiDHj.resize(nNodes); - for(auto& DHiDHj_a : DHiDHj) { + for (auto& DHiDHj_a : DHiDHj) { DHiDHj_a.resize(nNodes); - for(auto& DHiDHj_ab : DHiDHj_a) DHiDHj_ab.resize(nDim,nDim); + for (auto& DHiDHj_ab : DHiDHj_a) DHiDHj_ab.resize(nDim, nDim); } ClearElement(); } void CElement::ClearElement(void) { - Mab.setConstant(0.0); Kt_a.setConstant(0.0); FDL_a.setConstant(0.0); Ks_ab.setConstant(0.0); HiHj.setConstant(0.0); - for(auto& DHiDHj_a : DHiDHj) { - for(auto& DHiDHj_ab : DHiDHj_a) DHiDHj_ab.setConstant(0.0); + for (auto& DHiDHj_a : DHiDHj) { + for (auto& DHiDHj_ab : DHiDHj_a) DHiDHj_ab.setConstant(0.0); } - for(auto& kab_i : Kab) - kab_i.setConstant(0.0); + for (auto& kab_i : Kab) kab_i.setConstant(0.0); } - diff --git a/Common/src/geometry/elements/CHEXA8.cpp b/Common/src/geometry/elements/CHEXA8.cpp index 79d033c0e59..fee133c71fe 100644 --- a/Common/src/geometry/elements/CHEXA8.cpp +++ b/Common/src/geometry/elements/CHEXA8.cpp @@ -27,21 +27,43 @@ #include "../../../include/geometry/elements/CElement.hpp" - -CHEXA8::CHEXA8() : CElementWithKnownSizes() { - +CHEXA8::CHEXA8() : CElementWithKnownSizes() { /*--- Gauss coordinates and weights ---*/ su2double oneOnSqrt3 = 0.577350269189626; - GaussCoord[0][0] = -oneOnSqrt3; GaussCoord[0][1] = -oneOnSqrt3; GaussCoord[0][2] = -oneOnSqrt3; GaussWeight(0) = 1.0; - GaussCoord[1][0] = oneOnSqrt3; GaussCoord[1][1] = -oneOnSqrt3; GaussCoord[1][2] = -oneOnSqrt3; GaussWeight(1) = 1.0; - GaussCoord[2][0] = oneOnSqrt3; GaussCoord[2][1] = oneOnSqrt3; GaussCoord[2][2] = -oneOnSqrt3; GaussWeight(2) = 1.0; - GaussCoord[3][0] = -oneOnSqrt3; GaussCoord[3][1] = oneOnSqrt3; GaussCoord[3][2] = -oneOnSqrt3; GaussWeight(3) = 1.0; - GaussCoord[4][0] = -oneOnSqrt3; GaussCoord[4][1] = -oneOnSqrt3; GaussCoord[4][2] = oneOnSqrt3; GaussWeight(4) = 1.0; - GaussCoord[5][0] = oneOnSqrt3; GaussCoord[5][1] = -oneOnSqrt3; GaussCoord[5][2] = oneOnSqrt3; GaussWeight(5) = 1.0; - GaussCoord[6][0] = oneOnSqrt3; GaussCoord[6][1] = oneOnSqrt3; GaussCoord[6][2] = oneOnSqrt3; GaussWeight(6) = 1.0; - GaussCoord[7][0] = -oneOnSqrt3; GaussCoord[7][1] = oneOnSqrt3; GaussCoord[7][2] = oneOnSqrt3; GaussWeight(7) = 1.0; + GaussCoord[0][0] = -oneOnSqrt3; + GaussCoord[0][1] = -oneOnSqrt3; + GaussCoord[0][2] = -oneOnSqrt3; + GaussWeight(0) = 1.0; + GaussCoord[1][0] = oneOnSqrt3; + GaussCoord[1][1] = -oneOnSqrt3; + GaussCoord[1][2] = -oneOnSqrt3; + GaussWeight(1) = 1.0; + GaussCoord[2][0] = oneOnSqrt3; + GaussCoord[2][1] = oneOnSqrt3; + GaussCoord[2][2] = -oneOnSqrt3; + GaussWeight(2) = 1.0; + GaussCoord[3][0] = -oneOnSqrt3; + GaussCoord[3][1] = oneOnSqrt3; + GaussCoord[3][2] = -oneOnSqrt3; + GaussWeight(3) = 1.0; + GaussCoord[4][0] = -oneOnSqrt3; + GaussCoord[4][1] = -oneOnSqrt3; + GaussCoord[4][2] = oneOnSqrt3; + GaussWeight(4) = 1.0; + GaussCoord[5][0] = oneOnSqrt3; + GaussCoord[5][1] = -oneOnSqrt3; + GaussCoord[5][2] = oneOnSqrt3; + GaussWeight(5) = 1.0; + GaussCoord[6][0] = oneOnSqrt3; + GaussCoord[6][1] = oneOnSqrt3; + GaussCoord[6][2] = oneOnSqrt3; + GaussWeight(6) = 1.0; + GaussCoord[7][0] = -oneOnSqrt3; + GaussCoord[7][1] = oneOnSqrt3; + GaussCoord[7][2] = oneOnSqrt3; + GaussWeight(7) = 1.0; /*--- Store the values of the shape functions and their derivatives ---*/ @@ -49,96 +71,115 @@ CHEXA8::CHEXA8() : CElementWithKnownSizes() { su2double Xi, Eta, Zeta, val_Ni; for (iGauss = 0; iGauss < NGAUSS; iGauss++) { - Xi = GaussCoord[iGauss][0]; Eta = GaussCoord[iGauss][1]; Zeta = GaussCoord[iGauss][2]; - val_Ni = 0.125*(1.0-Xi)*(1.0-Eta)*(1.0-Zeta); GaussPoint[iGauss].SetNi(val_Ni,0); - val_Ni = 0.125*(1.0+Xi)*(1.0-Eta)*(1.0-Zeta); GaussPoint[iGauss].SetNi(val_Ni,1); - val_Ni = 0.125*(1.0+Xi)*(1.0+Eta)*(1.0-Zeta); GaussPoint[iGauss].SetNi(val_Ni,2); - val_Ni = 0.125*(1.0-Xi)*(1.0+Eta)*(1.0-Zeta); GaussPoint[iGauss].SetNi(val_Ni,3); - val_Ni = 0.125*(1.0-Xi)*(1.0-Eta)*(1.0+Zeta); GaussPoint[iGauss].SetNi(val_Ni,4); - val_Ni = 0.125*(1.0+Xi)*(1.0-Eta)*(1.0+Zeta); GaussPoint[iGauss].SetNi(val_Ni,5); - val_Ni = 0.125*(1.0+Xi)*(1.0+Eta)*(1.0+Zeta); GaussPoint[iGauss].SetNi(val_Ni,6); - val_Ni = 0.125*(1.0-Xi)*(1.0+Eta)*(1.0+Zeta); GaussPoint[iGauss].SetNi(val_Ni,7); + val_Ni = 0.125 * (1.0 - Xi) * (1.0 - Eta) * (1.0 - Zeta); + GaussPoint[iGauss].SetNi(val_Ni, 0); + val_Ni = 0.125 * (1.0 + Xi) * (1.0 - Eta) * (1.0 - Zeta); + GaussPoint[iGauss].SetNi(val_Ni, 1); + val_Ni = 0.125 * (1.0 + Xi) * (1.0 + Eta) * (1.0 - Zeta); + GaussPoint[iGauss].SetNi(val_Ni, 2); + val_Ni = 0.125 * (1.0 - Xi) * (1.0 + Eta) * (1.0 - Zeta); + GaussPoint[iGauss].SetNi(val_Ni, 3); + val_Ni = 0.125 * (1.0 - Xi) * (1.0 - Eta) * (1.0 + Zeta); + GaussPoint[iGauss].SetNi(val_Ni, 4); + val_Ni = 0.125 * (1.0 + Xi) * (1.0 - Eta) * (1.0 + Zeta); + GaussPoint[iGauss].SetNi(val_Ni, 5); + val_Ni = 0.125 * (1.0 + Xi) * (1.0 + Eta) * (1.0 + Zeta); + GaussPoint[iGauss].SetNi(val_Ni, 6); + val_Ni = 0.125 * (1.0 - Xi) * (1.0 + Eta) * (1.0 + Zeta); + GaussPoint[iGauss].SetNi(val_Ni, 7); /*--- dN/d xi ---*/ - dNiXj[iGauss][0][0] = -0.125*(1.0-Eta)*(1.0-Zeta); - dNiXj[iGauss][1][0] = 0.125*(1.0-Eta)*(1.0-Zeta); - dNiXj[iGauss][2][0] = 0.125*(1.0+Eta)*(1.0-Zeta); - dNiXj[iGauss][3][0] = -0.125*(1.0+Eta)*(1.0-Zeta); - dNiXj[iGauss][4][0] = -0.125*(1.0-Eta)*(1.0+Zeta); - dNiXj[iGauss][5][0] = 0.125*(1.0-Eta)*(1.0+Zeta); - dNiXj[iGauss][6][0] = 0.125*(1.0+Eta)*(1.0+Zeta); - dNiXj[iGauss][7][0] = -0.125*(1.0+Eta)*(1.0+Zeta); + dNiXj[iGauss][0][0] = -0.125 * (1.0 - Eta) * (1.0 - Zeta); + dNiXj[iGauss][1][0] = 0.125 * (1.0 - Eta) * (1.0 - Zeta); + dNiXj[iGauss][2][0] = 0.125 * (1.0 + Eta) * (1.0 - Zeta); + dNiXj[iGauss][3][0] = -0.125 * (1.0 + Eta) * (1.0 - Zeta); + dNiXj[iGauss][4][0] = -0.125 * (1.0 - Eta) * (1.0 + Zeta); + dNiXj[iGauss][5][0] = 0.125 * (1.0 - Eta) * (1.0 + Zeta); + dNiXj[iGauss][6][0] = 0.125 * (1.0 + Eta) * (1.0 + Zeta); + dNiXj[iGauss][7][0] = -0.125 * (1.0 + Eta) * (1.0 + Zeta); /*--- dN/d eta ---*/ - dNiXj[iGauss][0][1] = -0.125*(1.0-Xi)*(1.0-Zeta); - dNiXj[iGauss][1][1] = -0.125*(1.0+Xi)*(1.0-Zeta); - dNiXj[iGauss][2][1] = 0.125*(1.0+Xi)*(1.0-Zeta); - dNiXj[iGauss][3][1] = 0.125*(1.0-Xi)*(1.0-Zeta); - dNiXj[iGauss][4][1] = -0.125*(1.0-Xi)*(1.0+Zeta); - dNiXj[iGauss][5][1] = -0.125*(1.0+Xi)*(1.0+Zeta); - dNiXj[iGauss][6][1] = 0.125*(1.0+Xi)*(1.0+Zeta); - dNiXj[iGauss][7][1] = 0.125*(1.0-Xi)*(1.0+Zeta); + dNiXj[iGauss][0][1] = -0.125 * (1.0 - Xi) * (1.0 - Zeta); + dNiXj[iGauss][1][1] = -0.125 * (1.0 + Xi) * (1.0 - Zeta); + dNiXj[iGauss][2][1] = 0.125 * (1.0 + Xi) * (1.0 - Zeta); + dNiXj[iGauss][3][1] = 0.125 * (1.0 - Xi) * (1.0 - Zeta); + dNiXj[iGauss][4][1] = -0.125 * (1.0 - Xi) * (1.0 + Zeta); + dNiXj[iGauss][5][1] = -0.125 * (1.0 + Xi) * (1.0 + Zeta); + dNiXj[iGauss][6][1] = 0.125 * (1.0 + Xi) * (1.0 + Zeta); + dNiXj[iGauss][7][1] = 0.125 * (1.0 - Xi) * (1.0 + Zeta); /*--- dN/d zeta ---*/ - dNiXj[iGauss][0][2] = -0.125*(1.0-Xi)*(1.0-Eta); - dNiXj[iGauss][1][2] = -0.125*(1.0+Xi)*(1.0-Eta); - dNiXj[iGauss][2][2] = -0.125*(1.0+Xi)*(1.0+Eta); - dNiXj[iGauss][3][2] = -0.125*(1.0-Xi)*(1.0+Eta); - dNiXj[iGauss][4][2] = 0.125*(1.0-Xi)*(1.0-Eta); - dNiXj[iGauss][5][2] = 0.125*(1.0+Xi)*(1.0-Eta); - dNiXj[iGauss][6][2] = 0.125*(1.0+Xi)*(1.0+Eta); - dNiXj[iGauss][7][2] = 0.125*(1.0-Xi)*(1.0+Eta); - + dNiXj[iGauss][0][2] = -0.125 * (1.0 - Xi) * (1.0 - Eta); + dNiXj[iGauss][1][2] = -0.125 * (1.0 + Xi) * (1.0 - Eta); + dNiXj[iGauss][2][2] = -0.125 * (1.0 + Xi) * (1.0 + Eta); + dNiXj[iGauss][3][2] = -0.125 * (1.0 - Xi) * (1.0 + Eta); + dNiXj[iGauss][4][2] = 0.125 * (1.0 - Xi) * (1.0 - Eta); + dNiXj[iGauss][5][2] = 0.125 * (1.0 + Xi) * (1.0 - Eta); + dNiXj[iGauss][6][2] = 0.125 * (1.0 + Xi) * (1.0 + Eta); + dNiXj[iGauss][7][2] = 0.125 * (1.0 - Xi) * (1.0 + Eta); } /*--- Store the extrapolation functions ---*/ su2double ExtrapCoord[8][3], sqrt3 = 1.732050807568877; - ExtrapCoord[0][0] = -sqrt3; ExtrapCoord[0][1] = -sqrt3; ExtrapCoord[0][2] = -sqrt3; - ExtrapCoord[1][0] = sqrt3; ExtrapCoord[1][1] = -sqrt3; ExtrapCoord[1][2] = -sqrt3; - ExtrapCoord[2][0] = sqrt3; ExtrapCoord[2][1] = sqrt3; ExtrapCoord[2][2] = -sqrt3; - ExtrapCoord[3][0] = -sqrt3; ExtrapCoord[3][1] = sqrt3; ExtrapCoord[3][2] = -sqrt3; - ExtrapCoord[4][0] = -sqrt3; ExtrapCoord[4][1] = -sqrt3; ExtrapCoord[4][2] = sqrt3; - ExtrapCoord[5][0] = sqrt3; ExtrapCoord[5][1] = -sqrt3; ExtrapCoord[5][2] = sqrt3; - ExtrapCoord[6][0] = sqrt3; ExtrapCoord[6][1] = sqrt3; ExtrapCoord[6][2] = sqrt3; - ExtrapCoord[7][0] = -sqrt3; ExtrapCoord[7][1] = sqrt3; ExtrapCoord[7][2] = sqrt3; + ExtrapCoord[0][0] = -sqrt3; + ExtrapCoord[0][1] = -sqrt3; + ExtrapCoord[0][2] = -sqrt3; + ExtrapCoord[1][0] = sqrt3; + ExtrapCoord[1][1] = -sqrt3; + ExtrapCoord[1][2] = -sqrt3; + ExtrapCoord[2][0] = sqrt3; + ExtrapCoord[2][1] = sqrt3; + ExtrapCoord[2][2] = -sqrt3; + ExtrapCoord[3][0] = -sqrt3; + ExtrapCoord[3][1] = sqrt3; + ExtrapCoord[3][2] = -sqrt3; + ExtrapCoord[4][0] = -sqrt3; + ExtrapCoord[4][1] = -sqrt3; + ExtrapCoord[4][2] = sqrt3; + ExtrapCoord[5][0] = sqrt3; + ExtrapCoord[5][1] = -sqrt3; + ExtrapCoord[5][2] = sqrt3; + ExtrapCoord[6][0] = sqrt3; + ExtrapCoord[6][1] = sqrt3; + ExtrapCoord[6][2] = sqrt3; + ExtrapCoord[7][0] = -sqrt3; + ExtrapCoord[7][1] = sqrt3; + ExtrapCoord[7][2] = sqrt3; for (iNode = 0; iNode < NNODE; iNode++) { - Xi = ExtrapCoord[iNode][0]; Eta = ExtrapCoord[iNode][1]; Zeta = ExtrapCoord[iNode][2]; - NodalExtrap[iNode][0] = 0.125*(1.0-Xi)*(1.0-Eta)*(1.0-Zeta); - NodalExtrap[iNode][1] = 0.125*(1.0+Xi)*(1.0-Eta)*(1.0-Zeta); - NodalExtrap[iNode][2] = 0.125*(1.0+Xi)*(1.0+Eta)*(1.0-Zeta); - NodalExtrap[iNode][3] = 0.125*(1.0-Xi)*(1.0+Eta)*(1.0-Zeta); - NodalExtrap[iNode][4] = 0.125*(1.0-Xi)*(1.0-Eta)*(1.0+Zeta); - NodalExtrap[iNode][5] = 0.125*(1.0+Xi)*(1.0-Eta)*(1.0+Zeta); - NodalExtrap[iNode][6] = 0.125*(1.0+Xi)*(1.0+Eta)*(1.0+Zeta); - NodalExtrap[iNode][7] = 0.125*(1.0-Xi)*(1.0+Eta)*(1.0+Zeta); - + NodalExtrap[iNode][0] = 0.125 * (1.0 - Xi) * (1.0 - Eta) * (1.0 - Zeta); + NodalExtrap[iNode][1] = 0.125 * (1.0 + Xi) * (1.0 - Eta) * (1.0 - Zeta); + NodalExtrap[iNode][2] = 0.125 * (1.0 + Xi) * (1.0 + Eta) * (1.0 - Zeta); + NodalExtrap[iNode][3] = 0.125 * (1.0 - Xi) * (1.0 + Eta) * (1.0 - Zeta); + NodalExtrap[iNode][4] = 0.125 * (1.0 - Xi) * (1.0 - Eta) * (1.0 + Zeta); + NodalExtrap[iNode][5] = 0.125 * (1.0 + Xi) * (1.0 - Eta) * (1.0 + Zeta); + NodalExtrap[iNode][6] = 0.125 * (1.0 + Xi) * (1.0 + Eta) * (1.0 + Zeta); + NodalExtrap[iNode][7] = 0.125 * (1.0 - Xi) * (1.0 + Eta) * (1.0 + Zeta); } - } su2double CHEXA8::ComputeVolume(const FrameType mode) const { - unsigned short iDim; - su2double r1[3] = {0.0,0.0,0.0}, r2[3] = {0.0,0.0,0.0}, r3[3] = {0.0,0.0,0.0}, CrossProduct[3] = {0.0,0.0,0.0}; + su2double r1[3] = {0.0, 0.0, 0.0}, r2[3] = {0.0, 0.0, 0.0}, r3[3] = {0.0, 0.0, 0.0}, + CrossProduct[3] = {0.0, 0.0, 0.0}; su2double Volume = 0.0; /*--- Select the appropriate source for the nodal coordinates depending on the frame requested for the gradient computation, REFERENCE (undeformed) or CURRENT (deformed)---*/ - const su2activematrix& Coord = (mode==REFERENCE) ? RefCoord : CurrentCoord; + const su2activematrix& Coord = (mode == REFERENCE) ? RefCoord : CurrentCoord; for (iDim = 0; iDim < NDIM; iDim++) { r1[iDim] = Coord[1][iDim] - Coord[0][iDim]; @@ -146,11 +187,11 @@ su2double CHEXA8::ComputeVolume(const FrameType mode) const { r3[iDim] = Coord[5][iDim] - Coord[0][iDim]; } - CrossProduct[0] = (r1[1]*r2[2] - r1[2]*r2[1])*r3[0]; - CrossProduct[1] = (r1[2]*r2[0] - r1[0]*r2[2])*r3[1]; - CrossProduct[2] = (r1[0]*r2[1] - r1[1]*r2[0])*r3[2]; + CrossProduct[0] = (r1[1] * r2[2] - r1[2] * r2[1]) * r3[0]; + CrossProduct[1] = (r1[2] * r2[0] - r1[0] * r2[2]) * r3[1]; + CrossProduct[2] = (r1[0] * r2[1] - r1[1] * r2[0]) * r3[2]; - Volume = fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2])/6.0; + Volume = fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2]) / 6.0; for (iDim = 0; iDim < NDIM; iDim++) { r1[iDim] = Coord[2][iDim] - Coord[0][iDim]; @@ -158,11 +199,11 @@ su2double CHEXA8::ComputeVolume(const FrameType mode) const { r3[iDim] = Coord[5][iDim] - Coord[0][iDim]; } - CrossProduct[0] = (r1[1]*r2[2] - r1[2]*r2[1])*r3[0]; - CrossProduct[1] = (r1[2]*r2[0] - r1[0]*r2[2])*r3[1]; - CrossProduct[2] = (r1[0]*r2[1] - r1[1]*r2[0])*r3[2]; + CrossProduct[0] = (r1[1] * r2[2] - r1[2] * r2[1]) * r3[0]; + CrossProduct[1] = (r1[2] * r2[0] - r1[0] * r2[2]) * r3[1]; + CrossProduct[2] = (r1[0] * r2[1] - r1[1] * r2[0]) * r3[2]; - Volume += fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2])/6.0; + Volume += fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2]) / 6.0; for (iDim = 0; iDim < NDIM; iDim++) { r1[iDim] = Coord[2][iDim] - Coord[0][iDim]; @@ -170,11 +211,11 @@ su2double CHEXA8::ComputeVolume(const FrameType mode) const { r3[iDim] = Coord[7][iDim] - Coord[0][iDim]; } - CrossProduct[0] = (r1[1]*r2[2] - r1[2]*r2[1])*r3[0]; - CrossProduct[1] = (r1[2]*r2[0] - r1[0]*r2[2])*r3[1]; - CrossProduct[2] = (r1[0]*r2[1] - r1[1]*r2[0])*r3[2]; + CrossProduct[0] = (r1[1] * r2[2] - r1[2] * r2[1]) * r3[0]; + CrossProduct[1] = (r1[2] * r2[0] - r1[0] * r2[2]) * r3[1]; + CrossProduct[2] = (r1[0] * r2[1] - r1[1] * r2[0]) * r3[2]; - Volume += fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2])/6.0; + Volume += fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2]) / 6.0; for (iDim = 0; iDim < NDIM; iDim++) { r1[iDim] = Coord[5][iDim] - Coord[0][iDim]; @@ -182,11 +223,11 @@ su2double CHEXA8::ComputeVolume(const FrameType mode) const { r3[iDim] = Coord[4][iDim] - Coord[0][iDim]; } - CrossProduct[0] = (r1[1]*r2[2] - r1[2]*r2[1])*r3[0]; - CrossProduct[1] = (r1[2]*r2[0] - r1[0]*r2[2])*r3[1]; - CrossProduct[2] = (r1[0]*r2[1] - r1[1]*r2[0])*r3[2]; + CrossProduct[0] = (r1[1] * r2[2] - r1[2] * r2[1]) * r3[0]; + CrossProduct[1] = (r1[2] * r2[0] - r1[0] * r2[2]) * r3[1]; + CrossProduct[2] = (r1[0] * r2[1] - r1[1] * r2[0]) * r3[2]; - Volume += fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2])/6.0; + Volume += fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2]) / 6.0; for (iDim = 0; iDim < NDIM; iDim++) { r1[iDim] = Coord[7][iDim] - Coord[2][iDim]; @@ -194,13 +235,11 @@ su2double CHEXA8::ComputeVolume(const FrameType mode) const { r3[iDim] = Coord[6][iDim] - Coord[2][iDim]; } - CrossProduct[0] = (r1[1]*r2[2] - r1[2]*r2[1])*r3[0]; - CrossProduct[1] = (r1[2]*r2[0] - r1[0]*r2[2])*r3[1]; - CrossProduct[2] = (r1[0]*r2[1] - r1[1]*r2[0])*r3[2]; + CrossProduct[0] = (r1[1] * r2[2] - r1[2] * r2[1]) * r3[0]; + CrossProduct[1] = (r1[2] * r2[0] - r1[0] * r2[2]) * r3[1]; + CrossProduct[2] = (r1[0] * r2[1] - r1[1] * r2[0]) * r3[2]; - Volume += fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2])/6.0; + Volume += fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2]) / 6.0; return Volume; - } - diff --git a/Common/src/geometry/elements/CLINE.cpp b/Common/src/geometry/elements/CLINE.cpp index f9b62361137..d2dd6dd66fd 100644 --- a/Common/src/geometry/elements/CLINE.cpp +++ b/Common/src/geometry/elements/CLINE.cpp @@ -27,40 +27,38 @@ #include "../../../include/geometry/elements/CElement.hpp" -CLINE::CLINE() : CElementWithKnownSizes() { - +CLINE::CLINE() : CElementWithKnownSizes() { su2double Xi, val_Ni; /*--- Gauss coordinates and weights ---*/ su2double oneOnTwoSqrt3 = 0.288675134594813; - GaussCoord[0][0] = 0.5-oneOnTwoSqrt3; GaussWeight(0) = 0.5; - GaussCoord[1][0] = 0.5+oneOnTwoSqrt3; GaussWeight(1) = 0.5; + GaussCoord[0][0] = 0.5 - oneOnTwoSqrt3; + GaussWeight(0) = 0.5; + GaussCoord[1][0] = 0.5 + oneOnTwoSqrt3; + GaussWeight(1) = 0.5; /*--- Store the values of the shape functions and their derivatives ---*/ unsigned short iGauss; for (iGauss = 0; iGauss < nGaussPoints; iGauss++) { - Xi = GaussCoord[iGauss][0]; - val_Ni = 1.0-Xi; GaussPoint[iGauss].SetNi(val_Ni, 0); - val_Ni = Xi; GaussPoint[iGauss].SetNi(val_Ni, 1); + val_Ni = 1.0 - Xi; + GaussPoint[iGauss].SetNi(val_Ni, 0); + val_Ni = Xi; + GaussPoint[iGauss].SetNi(val_Ni, 1); /*--- dN/d xi ---*/ dNiXj[iGauss][0][0] = -1.0; dNiXj[iGauss][1][0] = 1.0; - } - } su2double CLINE::ComputeLength(const FrameType mode) const { - /*--- Select the appropriate source for the nodal coordinates depending on the frame requested for the gradient computation, REFERENCE (undeformed) or CURRENT (deformed)---*/ - const su2activematrix& Coord = (mode==REFERENCE) ? RefCoord : CurrentCoord; + const su2activematrix& Coord = (mode == REFERENCE) ? RefCoord : CurrentCoord; return fabs(Coord[1][0] - Coord[0][0]); - } diff --git a/Common/src/geometry/elements/CPRISM6.cpp b/Common/src/geometry/elements/CPRISM6.cpp index 4e7fb019a3d..111c771c8b7 100644 --- a/Common/src/geometry/elements/CPRISM6.cpp +++ b/Common/src/geometry/elements/CPRISM6.cpp @@ -27,21 +27,37 @@ #include "../../../include/geometry/elements/CElement.hpp" - -CPRISM6::CPRISM6() : CElementWithKnownSizes() { - +CPRISM6::CPRISM6() : CElementWithKnownSizes() { /*--- Gauss coordinates and weights ---*/ /*--- There is some inconsistency between the shape functions and the order of the nodes that causes "negative" stiffness, the remedy is to use negative weights. ---*/ su2double oneOnSqrt3 = 0.577350269189626; - GaussCoord[0][0] = -oneOnSqrt3; GaussCoord[0][1] = 1.0/6.0; GaussCoord[0][2] = 1.0/6.0; GaussWeight(0) = -1.0/6.0; - GaussCoord[1][0] = -oneOnSqrt3; GaussCoord[1][1] = 2.0/3.0; GaussCoord[1][2] = 1.0/6.0; GaussWeight(1) = -1.0/6.0; - GaussCoord[2][0] = -oneOnSqrt3; GaussCoord[2][1] = 1.0/6.0; GaussCoord[2][2] = 2.0/3.0; GaussWeight(2) = -1.0/6.0; - GaussCoord[3][0] = oneOnSqrt3; GaussCoord[3][1] = 1.0/6.0; GaussCoord[3][2] = 1.0/6.0; GaussWeight(3) = -1.0/6.0; - GaussCoord[4][0] = oneOnSqrt3; GaussCoord[4][1] = 2.0/3.0; GaussCoord[4][2] = 1.0/6.0; GaussWeight(4) = -1.0/6.0; - GaussCoord[5][0] = oneOnSqrt3; GaussCoord[5][1] = 1.0/6.0; GaussCoord[5][2] = 2.0/3.0; GaussWeight(5) = -1.0/6.0; + GaussCoord[0][0] = -oneOnSqrt3; + GaussCoord[0][1] = 1.0 / 6.0; + GaussCoord[0][2] = 1.0 / 6.0; + GaussWeight(0) = -1.0 / 6.0; + GaussCoord[1][0] = -oneOnSqrt3; + GaussCoord[1][1] = 2.0 / 3.0; + GaussCoord[1][2] = 1.0 / 6.0; + GaussWeight(1) = -1.0 / 6.0; + GaussCoord[2][0] = -oneOnSqrt3; + GaussCoord[2][1] = 1.0 / 6.0; + GaussCoord[2][2] = 2.0 / 3.0; + GaussWeight(2) = -1.0 / 6.0; + GaussCoord[3][0] = oneOnSqrt3; + GaussCoord[3][1] = 1.0 / 6.0; + GaussCoord[3][2] = 1.0 / 6.0; + GaussWeight(3) = -1.0 / 6.0; + GaussCoord[4][0] = oneOnSqrt3; + GaussCoord[4][1] = 2.0 / 3.0; + GaussCoord[4][2] = 1.0 / 6.0; + GaussWeight(4) = -1.0 / 6.0; + GaussCoord[5][0] = oneOnSqrt3; + GaussCoord[5][1] = 1.0 / 6.0; + GaussCoord[5][2] = 2.0 / 3.0; + GaussWeight(5) = -1.0 / 6.0; /*--- Store the values of the shape functions and their derivatives ---*/ @@ -49,84 +65,97 @@ CPRISM6::CPRISM6() : CElementWithKnownSizes() { su2double Xi, Eta, Zeta, val_Ni; for (iGauss = 0; iGauss < NGAUSS; iGauss++) { - Xi = GaussCoord[iGauss][0]; Eta = GaussCoord[iGauss][1]; Zeta = GaussCoord[iGauss][2]; - val_Ni = 0.5*Eta*(1.0-Xi); GaussPoint[iGauss].SetNi(val_Ni,0); - val_Ni = 0.5*Zeta*(1.0-Xi); GaussPoint[iGauss].SetNi(val_Ni,1); - val_Ni = 0.5*(1.0-Eta-Zeta)*(1.0-Xi); GaussPoint[iGauss].SetNi(val_Ni,2); - val_Ni = 0.5*Eta*(Xi+1.0); GaussPoint[iGauss].SetNi(val_Ni,3); - val_Ni = 0.5*Zeta*(Xi+1.0); GaussPoint[iGauss].SetNi(val_Ni,4); - val_Ni = 0.5*(1.0-Eta-Zeta)*(Xi+1.0); GaussPoint[iGauss].SetNi(val_Ni,5); + val_Ni = 0.5 * Eta * (1.0 - Xi); + GaussPoint[iGauss].SetNi(val_Ni, 0); + val_Ni = 0.5 * Zeta * (1.0 - Xi); + GaussPoint[iGauss].SetNi(val_Ni, 1); + val_Ni = 0.5 * (1.0 - Eta - Zeta) * (1.0 - Xi); + GaussPoint[iGauss].SetNi(val_Ni, 2); + val_Ni = 0.5 * Eta * (Xi + 1.0); + GaussPoint[iGauss].SetNi(val_Ni, 3); + val_Ni = 0.5 * Zeta * (Xi + 1.0); + GaussPoint[iGauss].SetNi(val_Ni, 4); + val_Ni = 0.5 * (1.0 - Eta - Zeta) * (Xi + 1.0); + GaussPoint[iGauss].SetNi(val_Ni, 5); /*--- dN/d xi ---*/ - dNiXj[iGauss][0][0] = -0.5*Eta; - dNiXj[iGauss][1][0] = -0.5*Zeta; - dNiXj[iGauss][2][0] = -0.5*(1.0-Eta-Zeta); - dNiXj[iGauss][3][0] = 0.5*Eta; - dNiXj[iGauss][4][0] = 0.5*Zeta; - dNiXj[iGauss][5][0] = 0.5*(1.0-Eta-Zeta); + dNiXj[iGauss][0][0] = -0.5 * Eta; + dNiXj[iGauss][1][0] = -0.5 * Zeta; + dNiXj[iGauss][2][0] = -0.5 * (1.0 - Eta - Zeta); + dNiXj[iGauss][3][0] = 0.5 * Eta; + dNiXj[iGauss][4][0] = 0.5 * Zeta; + dNiXj[iGauss][5][0] = 0.5 * (1.0 - Eta - Zeta); /*--- dN/d eta ---*/ - dNiXj[iGauss][0][1] = 0.5*(1.0-Xi); - dNiXj[iGauss][1][1] = 0.0; - dNiXj[iGauss][2][1] = -0.5*(1.0-Xi); - dNiXj[iGauss][3][1] = 0.5*(Xi+1.0); - dNiXj[iGauss][4][1] = 0.0; - dNiXj[iGauss][5][1] = -0.5*(Xi+1.0); + dNiXj[iGauss][0][1] = 0.5 * (1.0 - Xi); + dNiXj[iGauss][1][1] = 0.0; + dNiXj[iGauss][2][1] = -0.5 * (1.0 - Xi); + dNiXj[iGauss][3][1] = 0.5 * (Xi + 1.0); + dNiXj[iGauss][4][1] = 0.0; + dNiXj[iGauss][5][1] = -0.5 * (Xi + 1.0); /*--- dN/d mu ---*/ - dNiXj[iGauss][0][2] = 0.0; - dNiXj[iGauss][1][2] = 0.5*(1.0-Xi); - dNiXj[iGauss][2][2] = -0.5*(1.0-Xi); - dNiXj[iGauss][3][2] = 0.0; - dNiXj[iGauss][4][2] = 0.5*(Xi+1.0); - dNiXj[iGauss][5][2] = -0.5*(Xi+1.0); - + dNiXj[iGauss][0][2] = 0.0; + dNiXj[iGauss][1][2] = 0.5 * (1.0 - Xi); + dNiXj[iGauss][2][2] = -0.5 * (1.0 - Xi); + dNiXj[iGauss][3][2] = 0.0; + dNiXj[iGauss][4][2] = 0.5 * (Xi + 1.0); + dNiXj[iGauss][5][2] = -0.5 * (Xi + 1.0); } /*--- Store the extrapolation functions ---*/ su2double ExtrapCoord[6][3], sqrt3 = 1.732050807568877; - ExtrapCoord[0][0] = -sqrt3; ExtrapCoord[0][1] = -1.0/3.0; ExtrapCoord[0][2] = -1.0/3.0; - ExtrapCoord[1][0] = -sqrt3; ExtrapCoord[1][1] = 5.0/3.0; ExtrapCoord[1][2] = -1.0/3.0; - ExtrapCoord[2][0] = -sqrt3; ExtrapCoord[2][1] = -1.0/3.0; ExtrapCoord[2][2] = 5.0/3.0; - ExtrapCoord[3][0] = sqrt3; ExtrapCoord[3][1] = -1.0/3.0; ExtrapCoord[3][2] = -1.0/3.0; - ExtrapCoord[4][0] = sqrt3; ExtrapCoord[4][1] = 5.0/3.0; ExtrapCoord[4][2] = -1.0/3.0; - ExtrapCoord[5][0] = sqrt3; ExtrapCoord[5][1] = -1.0/3.0; ExtrapCoord[5][2] = 5.0/3.0; + ExtrapCoord[0][0] = -sqrt3; + ExtrapCoord[0][1] = -1.0 / 3.0; + ExtrapCoord[0][2] = -1.0 / 3.0; + ExtrapCoord[1][0] = -sqrt3; + ExtrapCoord[1][1] = 5.0 / 3.0; + ExtrapCoord[1][2] = -1.0 / 3.0; + ExtrapCoord[2][0] = -sqrt3; + ExtrapCoord[2][1] = -1.0 / 3.0; + ExtrapCoord[2][2] = 5.0 / 3.0; + ExtrapCoord[3][0] = sqrt3; + ExtrapCoord[3][1] = -1.0 / 3.0; + ExtrapCoord[3][2] = -1.0 / 3.0; + ExtrapCoord[4][0] = sqrt3; + ExtrapCoord[4][1] = 5.0 / 3.0; + ExtrapCoord[4][2] = -1.0 / 3.0; + ExtrapCoord[5][0] = sqrt3; + ExtrapCoord[5][1] = -1.0 / 3.0; + ExtrapCoord[5][2] = 5.0 / 3.0; for (iNode = 0; iNode < NNODE; iNode++) { - Xi = ExtrapCoord[iNode][0]; Eta = ExtrapCoord[iNode][1]; Zeta = ExtrapCoord[iNode][2]; - NodalExtrap[iNode][0] = 0.5*Eta*(1.0-Xi); - NodalExtrap[iNode][1] = 0.5*Zeta*(1.0-Xi); - NodalExtrap[iNode][2] = 0.5*(1.0-Eta-Zeta)*(1.0-Xi); - NodalExtrap[iNode][3] = 0.5*Eta*(Xi+1.0); - NodalExtrap[iNode][4] = 0.5*Zeta*(Xi+1.0); - NodalExtrap[iNode][5] = 0.5*(1.0-Eta-Zeta)*(Xi+1.0); - + NodalExtrap[iNode][0] = 0.5 * Eta * (1.0 - Xi); + NodalExtrap[iNode][1] = 0.5 * Zeta * (1.0 - Xi); + NodalExtrap[iNode][2] = 0.5 * (1.0 - Eta - Zeta) * (1.0 - Xi); + NodalExtrap[iNode][3] = 0.5 * Eta * (Xi + 1.0); + NodalExtrap[iNode][4] = 0.5 * Zeta * (Xi + 1.0); + NodalExtrap[iNode][5] = 0.5 * (1.0 - Eta - Zeta) * (Xi + 1.0); } - } su2double CPRISM6::ComputeVolume(const FrameType mode) const { - unsigned short iDim; - su2double r1[3] = {0.0,0.0,0.0}, r2[3] = {0.0,0.0,0.0}, r3[3] = {0.0,0.0,0.0}, CrossProduct[3] = {0.0,0.0,0.0}; + su2double r1[3] = {0.0, 0.0, 0.0}, r2[3] = {0.0, 0.0, 0.0}, r3[3] = {0.0, 0.0, 0.0}, + CrossProduct[3] = {0.0, 0.0, 0.0}; su2double Volume = 0.0; /*--- Select the appropriate source for the nodal coordinates depending on the frame requested for the gradient computation, REFERENCE (undeformed) or CURRENT (deformed)---*/ - const su2activematrix& Coord = (mode==REFERENCE) ? RefCoord : CurrentCoord; + const su2activematrix& Coord = (mode == REFERENCE) ? RefCoord : CurrentCoord; for (iDim = 0; iDim < NDIM; iDim++) { r1[iDim] = Coord[2][iDim] - Coord[0][iDim]; @@ -134,11 +163,11 @@ su2double CPRISM6::ComputeVolume(const FrameType mode) const { r3[iDim] = Coord[5][iDim] - Coord[0][iDim]; } - CrossProduct[0] = (r1[1]*r2[2] - r1[2]*r2[1])*r3[0]; - CrossProduct[1] = (r1[2]*r2[0] - r1[0]*r2[2])*r3[1]; - CrossProduct[2] = (r1[0]*r2[1] - r1[1]*r2[0])*r3[2]; + CrossProduct[0] = (r1[1] * r2[2] - r1[2] * r2[1]) * r3[0]; + CrossProduct[1] = (r1[2] * r2[0] - r1[0] * r2[2]) * r3[1]; + CrossProduct[2] = (r1[0] * r2[1] - r1[1] * r2[0]) * r3[2]; - Volume = fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2])/6.0; + Volume = fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2]) / 6.0; for (iDim = 0; iDim < NDIM; iDim++) { r1[iDim] = Coord[5][iDim] - Coord[0][iDim]; @@ -146,11 +175,11 @@ su2double CPRISM6::ComputeVolume(const FrameType mode) const { r3[iDim] = Coord[4][iDim] - Coord[0][iDim]; } - CrossProduct[0] = (r1[1]*r2[2] - r1[2]*r2[1])*r3[0]; - CrossProduct[1] = (r1[2]*r2[0] - r1[0]*r2[2])*r3[1]; - CrossProduct[2] = (r1[0]*r2[1] - r1[1]*r2[0])*r3[2]; + CrossProduct[0] = (r1[1] * r2[2] - r1[2] * r2[1]) * r3[0]; + CrossProduct[1] = (r1[2] * r2[0] - r1[0] * r2[2]) * r3[1]; + CrossProduct[2] = (r1[0] * r2[1] - r1[1] * r2[0]) * r3[2]; - Volume += fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2])/6.0; + Volume += fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2]) / 6.0; for (iDim = 0; iDim < NDIM; iDim++) { r1[iDim] = Coord[5][iDim] - Coord[0][iDim]; @@ -158,13 +187,11 @@ su2double CPRISM6::ComputeVolume(const FrameType mode) const { r3[iDim] = Coord[3][iDim] - Coord[0][iDim]; } - CrossProduct[0] = (r1[1]*r2[2] - r1[2]*r2[1])*r3[0]; - CrossProduct[1] = (r1[2]*r2[0] - r1[0]*r2[2])*r3[1]; - CrossProduct[2] = (r1[0]*r2[1] - r1[1]*r2[0])*r3[2]; + CrossProduct[0] = (r1[1] * r2[2] - r1[2] * r2[1]) * r3[0]; + CrossProduct[1] = (r1[2] * r2[0] - r1[0] * r2[2]) * r3[1]; + CrossProduct[2] = (r1[0] * r2[1] - r1[1] * r2[0]) * r3[2]; - Volume += fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2])/6.0; + Volume += fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2]) / 6.0; return Volume; - } - diff --git a/Common/src/geometry/elements/CPYRAM5.cpp b/Common/src/geometry/elements/CPYRAM5.cpp index 9003a7d378e..c82d1dbbfeb 100644 --- a/Common/src/geometry/elements/CPYRAM5.cpp +++ b/Common/src/geometry/elements/CPYRAM5.cpp @@ -27,16 +27,29 @@ #include "../../../include/geometry/elements/CElement.hpp" - -CPYRAM5::CPYRAM5() : CElementWithKnownSizes() { - +CPYRAM5::CPYRAM5() : CElementWithKnownSizes() { /*--- Gauss coordinates and weights ---*/ - GaussCoord[0][0] = 0.5; GaussCoord[0][1] = 0.0; GaussCoord[0][2] = 0.1531754163448146; GaussWeight(0) = 2.0/15.0; - GaussCoord[1][0] = 0.0; GaussCoord[1][1] = 0.5; GaussCoord[1][2] = 0.1531754163448146; GaussWeight(1) = 2.0/15.0; - GaussCoord[2][0] =-0.5; GaussCoord[2][1] = 0.0; GaussCoord[2][2] = 0.1531754163448146; GaussWeight(2) = 2.0/15.0; - GaussCoord[3][0] = 0.0; GaussCoord[3][1] =-0.5; GaussCoord[3][2] = 0.1531754163448146; GaussWeight(3) = 2.0/15.0; - GaussCoord[4][0] = 0.0; GaussCoord[4][1] = 0.0; GaussCoord[4][2] = 0.6372983346207416; GaussWeight(4) = 2.0/15.0; + GaussCoord[0][0] = 0.5; + GaussCoord[0][1] = 0.0; + GaussCoord[0][2] = 0.1531754163448146; + GaussWeight(0) = 2.0 / 15.0; + GaussCoord[1][0] = 0.0; + GaussCoord[1][1] = 0.5; + GaussCoord[1][2] = 0.1531754163448146; + GaussWeight(1) = 2.0 / 15.0; + GaussCoord[2][0] = -0.5; + GaussCoord[2][1] = 0.0; + GaussCoord[2][2] = 0.1531754163448146; + GaussWeight(2) = 2.0 / 15.0; + GaussCoord[3][0] = 0.0; + GaussCoord[3][1] = -0.5; + GaussCoord[3][2] = 0.1531754163448146; + GaussWeight(3) = 2.0 / 15.0; + GaussCoord[4][0] = 0.0; + GaussCoord[4][1] = 0.0; + GaussCoord[4][2] = 0.6372983346207416; + GaussWeight(4) = 2.0 / 15.0; /*--- Store the values of the shape functions and their derivatives ---*/ @@ -44,78 +57,90 @@ CPYRAM5::CPYRAM5() : CElementWithKnownSizes() { su2double Xi, Eta, Zeta, val_Ni; for (iGauss = 0; iGauss < NGAUSS; iGauss++) { - Xi = GaussCoord[iGauss][0]; Eta = GaussCoord[iGauss][1]; Zeta = GaussCoord[iGauss][2]; - val_Ni = 0.25*(-Xi+Eta+Zeta-1.0)*(-Xi-Eta+Zeta-1.0)/(1.0-Zeta); GaussPoint[iGauss].SetNi(val_Ni,0); - val_Ni = 0.25*(-Xi-Eta+Zeta-1.0)*( Xi-Eta+Zeta-1.0)/(1.0-Zeta); GaussPoint[iGauss].SetNi(val_Ni,1); - val_Ni = 0.25*( Xi+Eta+Zeta-1.0)*( Xi-Eta+Zeta-1.0)/(1.0-Zeta); GaussPoint[iGauss].SetNi(val_Ni,2); - val_Ni = 0.25*( Xi+Eta+Zeta-1.0)*(-Xi+Eta+Zeta-1.0)/(1.0-Zeta); GaussPoint[iGauss].SetNi(val_Ni,3); - val_Ni = Zeta; GaussPoint[iGauss].SetNi(val_Ni,4); + val_Ni = 0.25 * (-Xi + Eta + Zeta - 1.0) * (-Xi - Eta + Zeta - 1.0) / (1.0 - Zeta); + GaussPoint[iGauss].SetNi(val_Ni, 0); + val_Ni = 0.25 * (-Xi - Eta + Zeta - 1.0) * (Xi - Eta + Zeta - 1.0) / (1.0 - Zeta); + GaussPoint[iGauss].SetNi(val_Ni, 1); + val_Ni = 0.25 * (Xi + Eta + Zeta - 1.0) * (Xi - Eta + Zeta - 1.0) / (1.0 - Zeta); + GaussPoint[iGauss].SetNi(val_Ni, 2); + val_Ni = 0.25 * (Xi + Eta + Zeta - 1.0) * (-Xi + Eta + Zeta - 1.0) / (1.0 - Zeta); + GaussPoint[iGauss].SetNi(val_Ni, 3); + val_Ni = Zeta; + GaussPoint[iGauss].SetNi(val_Ni, 4); /*--- dN/d xi ---*/ - dNiXj[iGauss][0][0] = 0.5*(Zeta-Xi-1.0)/(Zeta-1.0); - dNiXj[iGauss][1][0] = 0.5*Xi/(Zeta-1.0); - dNiXj[iGauss][2][0] = 0.5*(1.0-Zeta-Xi)/(Zeta-1.0); + dNiXj[iGauss][0][0] = 0.5 * (Zeta - Xi - 1.0) / (Zeta - 1.0); + dNiXj[iGauss][1][0] = 0.5 * Xi / (Zeta - 1.0); + dNiXj[iGauss][2][0] = 0.5 * (1.0 - Zeta - Xi) / (Zeta - 1.0); dNiXj[iGauss][3][0] = dNiXj[iGauss][1][0]; dNiXj[iGauss][4][0] = 0.0; /*--- dN/d eta ---*/ - dNiXj[iGauss][0][1] = 0.5*Eta/(Zeta-1.0); - dNiXj[iGauss][1][1] = 0.5*(Zeta-Eta-1.0)/(Zeta-1.0); + dNiXj[iGauss][0][1] = 0.5 * Eta / (Zeta - 1.0); + dNiXj[iGauss][1][1] = 0.5 * (Zeta - Eta - 1.0) / (Zeta - 1.0); dNiXj[iGauss][2][1] = dNiXj[iGauss][0][1]; - dNiXj[iGauss][3][1] = 0.5*(1.0-Zeta-Eta)/(Zeta-1.0); + dNiXj[iGauss][3][1] = 0.5 * (1.0 - Zeta - Eta) / (Zeta - 1.0); dNiXj[iGauss][4][1] = 0.0; /*--- dN/d zeta ---*/ - dNiXj[iGauss][0][2] = 0.25*(-1.0 + 2.0*Zeta - Zeta*Zeta - Eta*Eta + Xi*Xi)/((1.0-Zeta)*(1.0-Zeta)); - dNiXj[iGauss][1][2] = 0.25*(-1.0 + 2.0*Zeta - Zeta*Zeta + Eta*Eta - Xi*Xi)/((1.0-Zeta)*(1.0-Zeta)); + dNiXj[iGauss][0][2] = + 0.25 * (-1.0 + 2.0 * Zeta - Zeta * Zeta - Eta * Eta + Xi * Xi) / ((1.0 - Zeta) * (1.0 - Zeta)); + dNiXj[iGauss][1][2] = + 0.25 * (-1.0 + 2.0 * Zeta - Zeta * Zeta + Eta * Eta - Xi * Xi) / ((1.0 - Zeta) * (1.0 - Zeta)); dNiXj[iGauss][2][2] = dNiXj[iGauss][0][2]; dNiXj[iGauss][3][2] = dNiXj[iGauss][1][2]; dNiXj[iGauss][4][2] = 1.0; - } /*--- Store the extrapolation functions ---*/ su2double ExtrapCoord[5][3]; - ExtrapCoord[0][0] = 2.0; ExtrapCoord[0][1] = 0.0; ExtrapCoord[0][2] = -0.316397779494322; - ExtrapCoord[1][0] = 0.0; ExtrapCoord[1][1] = 2.0; ExtrapCoord[1][2] = -0.316397779494322; - ExtrapCoord[2][0] = -2.0; ExtrapCoord[2][1] = 0.0; ExtrapCoord[2][2] = -0.316397779494322; - ExtrapCoord[3][0] = 0.0; ExtrapCoord[3][1] = -2.0; ExtrapCoord[3][2] = -0.316397779494322; - ExtrapCoord[4][0] = 0.0; ExtrapCoord[4][1] = 0.0; ExtrapCoord[4][2] = 1.749193338482970; + ExtrapCoord[0][0] = 2.0; + ExtrapCoord[0][1] = 0.0; + ExtrapCoord[0][2] = -0.316397779494322; + ExtrapCoord[1][0] = 0.0; + ExtrapCoord[1][1] = 2.0; + ExtrapCoord[1][2] = -0.316397779494322; + ExtrapCoord[2][0] = -2.0; + ExtrapCoord[2][1] = 0.0; + ExtrapCoord[2][2] = -0.316397779494322; + ExtrapCoord[3][0] = 0.0; + ExtrapCoord[3][1] = -2.0; + ExtrapCoord[3][2] = -0.316397779494322; + ExtrapCoord[4][0] = 0.0; + ExtrapCoord[4][1] = 0.0; + ExtrapCoord[4][2] = 1.749193338482970; for (iNode = 0; iNode < NNODE; iNode++) { - Xi = ExtrapCoord[iNode][0]; Eta = ExtrapCoord[iNode][1]; Zeta = ExtrapCoord[iNode][2]; - NodalExtrap[iNode][0] = 0.25*(-Xi+Eta+Zeta-1.0)*(-Xi-Eta+Zeta-1.0)/(1.0-Zeta); - NodalExtrap[iNode][1] = 0.25*(-Xi-Eta+Zeta-1.0)*( Xi-Eta+Zeta-1.0)/(1.0-Zeta); - NodalExtrap[iNode][2] = 0.25*( Xi+Eta+Zeta-1.0)*( Xi-Eta+Zeta-1.0)/(1.0-Zeta); - NodalExtrap[iNode][3] = 0.25*( Xi+Eta+Zeta-1.0)*(-Xi+Eta+Zeta-1.0)/(1.0-Zeta); + NodalExtrap[iNode][0] = 0.25 * (-Xi + Eta + Zeta - 1.0) * (-Xi - Eta + Zeta - 1.0) / (1.0 - Zeta); + NodalExtrap[iNode][1] = 0.25 * (-Xi - Eta + Zeta - 1.0) * (Xi - Eta + Zeta - 1.0) / (1.0 - Zeta); + NodalExtrap[iNode][2] = 0.25 * (Xi + Eta + Zeta - 1.0) * (Xi - Eta + Zeta - 1.0) / (1.0 - Zeta); + NodalExtrap[iNode][3] = 0.25 * (Xi + Eta + Zeta - 1.0) * (-Xi + Eta + Zeta - 1.0) / (1.0 - Zeta); NodalExtrap[iNode][4] = Zeta; - } - } su2double CPYRAM5::ComputeVolume(const FrameType mode) const { - unsigned short iDim; - su2double r1[3] = {0.0,0.0,0.0}, r2[3] = {0.0,0.0,0.0}, r3[3] = {0.0,0.0,0.0}, CrossProduct[3] = {0.0,0.0,0.0}; + su2double r1[3] = {0.0, 0.0, 0.0}, r2[3] = {0.0, 0.0, 0.0}, r3[3] = {0.0, 0.0, 0.0}, + CrossProduct[3] = {0.0, 0.0, 0.0}; su2double Volume = 0.0; /*--- Select the appropriate source for the nodal coordinates depending on the frame requested for the gradient computation, REFERENCE (undeformed) or CURRENT (deformed)---*/ - const su2activematrix& Coord = (mode==REFERENCE) ? RefCoord : CurrentCoord; + const su2activematrix& Coord = (mode == REFERENCE) ? RefCoord : CurrentCoord; for (iDim = 0; iDim < NDIM; iDim++) { r1[iDim] = Coord[1][iDim] - Coord[0][iDim]; @@ -123,11 +148,11 @@ su2double CPYRAM5::ComputeVolume(const FrameType mode) const { r3[iDim] = Coord[4][iDim] - Coord[0][iDim]; } - CrossProduct[0] = (r1[1]*r2[2] - r1[2]*r2[1])*r3[0]; - CrossProduct[1] = (r1[2]*r2[0] - r1[0]*r2[2])*r3[1]; - CrossProduct[2] = (r1[0]*r2[1] - r1[1]*r2[0])*r3[2]; + CrossProduct[0] = (r1[1] * r2[2] - r1[2] * r2[1]) * r3[0]; + CrossProduct[1] = (r1[2] * r2[0] - r1[0] * r2[2]) * r3[1]; + CrossProduct[2] = (r1[0] * r2[1] - r1[1] * r2[0]) * r3[2]; - Volume = fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2])/6.0; + Volume = fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2]) / 6.0; for (iDim = 0; iDim < NDIM; iDim++) { r1[iDim] = Coord[2][iDim] - Coord[0][iDim]; @@ -135,13 +160,11 @@ su2double CPYRAM5::ComputeVolume(const FrameType mode) const { r3[iDim] = Coord[4][iDim] - Coord[0][iDim]; } - CrossProduct[0] = (r1[1]*r2[2] - r1[2]*r2[1])*r3[0]; - CrossProduct[1] = (r1[2]*r2[0] - r1[0]*r2[2])*r3[1]; - CrossProduct[2] = (r1[0]*r2[1] - r1[1]*r2[0])*r3[2]; + CrossProduct[0] = (r1[1] * r2[2] - r1[2] * r2[1]) * r3[0]; + CrossProduct[1] = (r1[2] * r2[0] - r1[0] * r2[2]) * r3[1]; + CrossProduct[2] = (r1[0] * r2[1] - r1[1] * r2[0]) * r3[2]; - Volume += fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2])/6.0; + Volume += fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2]) / 6.0; return Volume; - } - diff --git a/Common/src/geometry/elements/CPYRAM6.cpp b/Common/src/geometry/elements/CPYRAM6.cpp index 8ea03251f51..d152598b594 100644 --- a/Common/src/geometry/elements/CPYRAM6.cpp +++ b/Common/src/geometry/elements/CPYRAM6.cpp @@ -27,95 +27,124 @@ #include "../../../include/geometry/elements/CElement.hpp" - -CPYRAM6::CPYRAM6() : CElementWithKnownSizes() { - +CPYRAM6::CPYRAM6() : CElementWithKnownSizes() { /*--- Gauss coordinates and weights ---*/ - GaussCoord[0][0] = sqrt(4.0/27.0); GaussCoord[0][1] = sqrt(4.0/27.0); GaussCoord[0][2] = 1.0/6.0; GaussWeight(0) = 9.0/20.0; - GaussCoord[0][0] = sqrt(4.0/27.0); GaussCoord[0][1] = sqrt(4.0/27.0); GaussCoord[0][2] = 1.0/6.0; GaussWeight(1) = 9.0/20.0; - GaussCoord[0][0] = sqrt(4.0/27.0); GaussCoord[0][1] = sqrt(4.0/27.0); GaussCoord[0][2] = 1.0/6.0; GaussWeight(2) = 9.0/20.0; - GaussCoord[0][0] = sqrt(4.0/27.0); GaussCoord[0][1] = sqrt(4.0/27.0); GaussCoord[0][2] = 1.0/6.0; GaussWeight(3) = 9.0/20.0; - GaussCoord[4][0] = 0.0; GaussCoord[4][1] = 0.0; GaussCoord[4][2] = 0.5; GaussWeight(4) = 3.0/5.0; - GaussCoord[5][0] = 0.0; GaussCoord[5][1] = 0.0; GaussCoord[5][2] = 0.25; GaussWeight(5) = -16.0/15.0; - - /*--- Store the values of the shape functions and their derivatives ---*/ - - unsigned short iNode, iGauss; - su2double Xi, Eta, Zeta, val_Ni; - - for (iGauss = 0; iGauss < nGaussPoints; iGauss++) { - - Xi = GaussCoord[iGauss][0]; - Eta = GaussCoord[iGauss][1]; - Zeta = GaussCoord[iGauss][2]; - - val_Ni = 0.25*(-Xi+Eta+Zeta-1.0)*(-Xi-Eta+Zeta-1.0)/(1.0-Zeta); GaussPoint[iGauss].SetNi(val_Ni,0); - val_Ni = 0.25*(-Xi-Eta+Zeta-1.0)*( Xi-Eta+Zeta-1.0)/(1.0-Zeta); GaussPoint[iGauss].SetNi(val_Ni,1); - val_Ni = 0.25*( Xi+Eta+Zeta-1.0)*( Xi-Eta+Zeta-1.0)/(1.0-Zeta); GaussPoint[iGauss].SetNi(val_Ni,2); - val_Ni = 0.25*( Xi+Eta+Zeta-1.0)*(-Xi+Eta+Zeta-1.0)/(1.0-Zeta); GaussPoint[iGauss].SetNi(val_Ni,3); - val_Ni = Zeta; GaussPoint[iGauss].SetNi(val_Ni,4); - - /*--- dN/d xi ---*/ - - dNiXj[iGauss][0][0] = 0.5*(Zeta-Xi-1.0)/(Zeta-1.0); - dNiXj[iGauss][1][0] = 0.5*Xi/(Zeta-1.0); - dNiXj[iGauss][2][0] = 0.5*(1.0-Zeta-Xi)/(Zeta-1.0); - dNiXj[iGauss][3][0] = dNiXj[iGauss][1][0]; - dNiXj[iGauss][4][0] = 0.0; - - /*--- dN/d eta ---*/ - - dNiXj[iGauss][0][1] = 0.5*Eta/(Zeta-1.0); - dNiXj[iGauss][1][1] = 0.5*(Zeta-Eta-1.0)/(Zeta-1.0); - dNiXj[iGauss][2][1] = dNiXj[iGauss][0][1]; - dNiXj[iGauss][3][1] = 0.5*(1.0-Zeta-Eta)/(Zeta-1.0); - dNiXj[iGauss][4][1] = 0.0; - - /*--- dN/d zeta ---*/ - - dNiXj[iGauss][0][2] = 0.25*(-1.0 + 2.0*Zeta - Zeta*Zeta - Eta*Eta + Xi*Xi)/((1.0-Zeta)*(1.0-Zeta)); - dNiXj[iGauss][1][2] = 0.25*(-1.0 + 2.0*Zeta - Zeta*Zeta + Eta*Eta - Xi*Xi)/((1.0-Zeta)*(1.0-Zeta)); - dNiXj[iGauss][2][2] = dNiXj[iGauss][0][2]; - dNiXj[iGauss][3][2] = dNiXj[iGauss][1][2]; - dNiXj[iGauss][4][2] = 1.0; - - } - - /*--- Store the extrapolation functions ---*/ - - su2double ExtrapCoord[5][3]; - - ExtrapCoord[0][0] = 2.0; ExtrapCoord[0][1] = 0.0; ExtrapCoord[0][2] = -0.316397779494322; - ExtrapCoord[1][0] = 0.0; ExtrapCoord[1][1] = 2.0; ExtrapCoord[1][2] = -0.316397779494322; - ExtrapCoord[2][0] = -2.0; ExtrapCoord[2][1] = 0.0; ExtrapCoord[2][2] = -0.316397779494322; - ExtrapCoord[3][0] = 0.0; ExtrapCoord[3][1] = -2.0; ExtrapCoord[3][2] = -0.316397779494322; - ExtrapCoord[4][0] = 0.0; ExtrapCoord[4][1] = 0.0; ExtrapCoord[4][2] = 1.749193338482970; - - for (iNode = 0; iNode < nNodes; iNode++) { - - Xi = ExtrapCoord[iNode][0]; - Eta = ExtrapCoord[iNode][1]; - Zeta = ExtrapCoord[iNode][2]; - - NodalExtrap[iNode][0] = 0.25*(-Xi+Eta+Zeta-1.0)*(-Xi-Eta+Zeta-1.0)/(1.0-Zeta); - NodalExtrap[iNode][1] = 0.25*(-Xi-Eta+Zeta-1.0)*( Xi-Eta+Zeta-1.0)/(1.0-Zeta); - NodalExtrap[iNode][2] = 0.25*( Xi+Eta+Zeta-1.0)*( Xi-Eta+Zeta-1.0)/(1.0-Zeta); - NodalExtrap[iNode][3] = 0.25*( Xi+Eta+Zeta-1.0)*(-Xi+Eta+Zeta-1.0)/(1.0-Zeta); - NodalExtrap[iNode][4] = Zeta; + GaussCoord[0][0] = sqrt(4.0 / 27.0); + GaussCoord[0][1] = sqrt(4.0 / 27.0); + GaussCoord[0][2] = 1.0 / 6.0; + GaussWeight(0) = 9.0 / 20.0; + GaussCoord[0][0] = sqrt(4.0 / 27.0); + GaussCoord[0][1] = sqrt(4.0 / 27.0); + GaussCoord[0][2] = 1.0 / 6.0; + GaussWeight(1) = 9.0 / 20.0; + GaussCoord[0][0] = sqrt(4.0 / 27.0); + GaussCoord[0][1] = sqrt(4.0 / 27.0); + GaussCoord[0][2] = 1.0 / 6.0; + GaussWeight(2) = 9.0 / 20.0; + GaussCoord[0][0] = sqrt(4.0 / 27.0); + GaussCoord[0][1] = sqrt(4.0 / 27.0); + GaussCoord[0][2] = 1.0 / 6.0; + GaussWeight(3) = 9.0 / 20.0; + GaussCoord[4][0] = 0.0; + GaussCoord[4][1] = 0.0; + GaussCoord[4][2] = 0.5; + GaussWeight(4) = 3.0 / 5.0; + GaussCoord[5][0] = 0.0; + GaussCoord[5][1] = 0.0; + GaussCoord[5][2] = 0.25; + GaussWeight(5) = -16.0 / 15.0; + + /*--- Store the values of the shape functions and their derivatives ---*/ + + unsigned short iNode, iGauss; + su2double Xi, Eta, Zeta, val_Ni; + + for (iGauss = 0; iGauss < nGaussPoints; iGauss++) { + Xi = GaussCoord[iGauss][0]; + Eta = GaussCoord[iGauss][1]; + Zeta = GaussCoord[iGauss][2]; + + val_Ni = 0.25 * (-Xi + Eta + Zeta - 1.0) * (-Xi - Eta + Zeta - 1.0) / (1.0 - Zeta); + GaussPoint[iGauss].SetNi(val_Ni, 0); + val_Ni = 0.25 * (-Xi - Eta + Zeta - 1.0) * (Xi - Eta + Zeta - 1.0) / (1.0 - Zeta); + GaussPoint[iGauss].SetNi(val_Ni, 1); + val_Ni = 0.25 * (Xi + Eta + Zeta - 1.0) * (Xi - Eta + Zeta - 1.0) / (1.0 - Zeta); + GaussPoint[iGauss].SetNi(val_Ni, 2); + val_Ni = 0.25 * (Xi + Eta + Zeta - 1.0) * (-Xi + Eta + Zeta - 1.0) / (1.0 - Zeta); + GaussPoint[iGauss].SetNi(val_Ni, 3); + val_Ni = Zeta; + GaussPoint[iGauss].SetNi(val_Ni, 4); + + /*--- dN/d xi ---*/ + + dNiXj[iGauss][0][0] = 0.5 * (Zeta - Xi - 1.0) / (Zeta - 1.0); + dNiXj[iGauss][1][0] = 0.5 * Xi / (Zeta - 1.0); + dNiXj[iGauss][2][0] = 0.5 * (1.0 - Zeta - Xi) / (Zeta - 1.0); + dNiXj[iGauss][3][0] = dNiXj[iGauss][1][0]; + dNiXj[iGauss][4][0] = 0.0; + + /*--- dN/d eta ---*/ + + dNiXj[iGauss][0][1] = 0.5 * Eta / (Zeta - 1.0); + dNiXj[iGauss][1][1] = 0.5 * (Zeta - Eta - 1.0) / (Zeta - 1.0); + dNiXj[iGauss][2][1] = dNiXj[iGauss][0][1]; + dNiXj[iGauss][3][1] = 0.5 * (1.0 - Zeta - Eta) / (Zeta - 1.0); + dNiXj[iGauss][4][1] = 0.0; + + /*--- dN/d zeta ---*/ + + dNiXj[iGauss][0][2] = + 0.25 * (-1.0 + 2.0 * Zeta - Zeta * Zeta - Eta * Eta + Xi * Xi) / ((1.0 - Zeta) * (1.0 - Zeta)); + dNiXj[iGauss][1][2] = + 0.25 * (-1.0 + 2.0 * Zeta - Zeta * Zeta + Eta * Eta - Xi * Xi) / ((1.0 - Zeta) * (1.0 - Zeta)); + dNiXj[iGauss][2][2] = dNiXj[iGauss][0][2]; + dNiXj[iGauss][3][2] = dNiXj[iGauss][1][2]; + dNiXj[iGauss][4][2] = 1.0; + } - } + /*--- Store the extrapolation functions ---*/ + + su2double ExtrapCoord[5][3]; + + ExtrapCoord[0][0] = 2.0; + ExtrapCoord[0][1] = 0.0; + ExtrapCoord[0][2] = -0.316397779494322; + ExtrapCoord[1][0] = 0.0; + ExtrapCoord[1][1] = 2.0; + ExtrapCoord[1][2] = -0.316397779494322; + ExtrapCoord[2][0] = -2.0; + ExtrapCoord[2][1] = 0.0; + ExtrapCoord[2][2] = -0.316397779494322; + ExtrapCoord[3][0] = 0.0; + ExtrapCoord[3][1] = -2.0; + ExtrapCoord[3][2] = -0.316397779494322; + ExtrapCoord[4][0] = 0.0; + ExtrapCoord[4][1] = 0.0; + ExtrapCoord[4][2] = 1.749193338482970; + + for (iNode = 0; iNode < nNodes; iNode++) { + Xi = ExtrapCoord[iNode][0]; + Eta = ExtrapCoord[iNode][1]; + Zeta = ExtrapCoord[iNode][2]; + + NodalExtrap[iNode][0] = 0.25 * (-Xi + Eta + Zeta - 1.0) * (-Xi - Eta + Zeta - 1.0) / (1.0 - Zeta); + NodalExtrap[iNode][1] = 0.25 * (-Xi - Eta + Zeta - 1.0) * (Xi - Eta + Zeta - 1.0) / (1.0 - Zeta); + NodalExtrap[iNode][2] = 0.25 * (Xi + Eta + Zeta - 1.0) * (Xi - Eta + Zeta - 1.0) / (1.0 - Zeta); + NodalExtrap[iNode][3] = 0.25 * (Xi + Eta + Zeta - 1.0) * (-Xi + Eta + Zeta - 1.0) / (1.0 - Zeta); + NodalExtrap[iNode][4] = Zeta; + } } su2double CPYRAM6::ComputeVolume(const FrameType mode) const { - unsigned short iDim; - su2double r1[3] = {0.0,0.0,0.0}, r2[3] = {0.0,0.0,0.0}, r3[3] = {0.0,0.0,0.0}, CrossProduct[3] = {0.0,0.0,0.0}; + su2double r1[3] = {0.0, 0.0, 0.0}, r2[3] = {0.0, 0.0, 0.0}, r3[3] = {0.0, 0.0, 0.0}, + CrossProduct[3] = {0.0, 0.0, 0.0}; su2double Volume = 0.0; /*--- Select the appropriate source for the nodal coordinates depending on the frame requested for the gradient computation, REFERENCE (undeformed) or CURRENT (deformed)---*/ - const su2activematrix& Coord = (mode==REFERENCE) ? RefCoord : CurrentCoord; + const su2activematrix& Coord = (mode == REFERENCE) ? RefCoord : CurrentCoord; for (iDim = 0; iDim < NDIM; iDim++) { r1[iDim] = Coord[1][iDim] - Coord[0][iDim]; @@ -123,11 +152,11 @@ su2double CPYRAM6::ComputeVolume(const FrameType mode) const { r3[iDim] = Coord[4][iDim] - Coord[0][iDim]; } - CrossProduct[0] = (r1[1]*r2[2] - r1[2]*r2[1])*r3[0]; - CrossProduct[1] = (r1[2]*r2[0] - r1[0]*r2[2])*r3[1]; - CrossProduct[2] = (r1[0]*r2[1] - r1[1]*r2[0])*r3[2]; + CrossProduct[0] = (r1[1] * r2[2] - r1[2] * r2[1]) * r3[0]; + CrossProduct[1] = (r1[2] * r2[0] - r1[0] * r2[2]) * r3[1]; + CrossProduct[2] = (r1[0] * r2[1] - r1[1] * r2[0]) * r3[2]; - Volume = fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2])/6.0; + Volume = fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2]) / 6.0; for (iDim = 0; iDim < NDIM; iDim++) { r1[iDim] = Coord[2][iDim] - Coord[0][iDim]; @@ -135,13 +164,11 @@ su2double CPYRAM6::ComputeVolume(const FrameType mode) const { r3[iDim] = Coord[4][iDim] - Coord[0][iDim]; } - CrossProduct[0] = (r1[1]*r2[2] - r1[2]*r2[1])*r3[0]; - CrossProduct[1] = (r1[2]*r2[0] - r1[0]*r2[2])*r3[1]; - CrossProduct[2] = (r1[0]*r2[1] - r1[1]*r2[0])*r3[2]; + CrossProduct[0] = (r1[1] * r2[2] - r1[2] * r2[1]) * r3[0]; + CrossProduct[1] = (r1[2] * r2[0] - r1[0] * r2[2]) * r3[1]; + CrossProduct[2] = (r1[0] * r2[1] - r1[1] * r2[0]) * r3[2]; - Volume += fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2])/6.0; + Volume += fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2]) / 6.0; return Volume; - } - diff --git a/Common/src/geometry/elements/CQUAD4.cpp b/Common/src/geometry/elements/CQUAD4.cpp index 5a495abcb07..628700ed0b7 100644 --- a/Common/src/geometry/elements/CQUAD4.cpp +++ b/Common/src/geometry/elements/CQUAD4.cpp @@ -27,17 +27,23 @@ #include "../../../include/geometry/elements/CElement.hpp" - -CQUAD4::CQUAD4() : CElementWithKnownSizes() { - +CQUAD4::CQUAD4() : CElementWithKnownSizes() { /*--- Gauss coordinates and weights ---*/ su2double oneOnSqrt3 = 0.577350269189626; - GaussCoord[0][0] = -oneOnSqrt3; GaussCoord[0][1] = -oneOnSqrt3; GaussWeight(0) = 1.0; - GaussCoord[1][0] = oneOnSqrt3; GaussCoord[1][1] = -oneOnSqrt3; GaussWeight(1) = 1.0; - GaussCoord[2][0] = oneOnSqrt3; GaussCoord[2][1] = oneOnSqrt3; GaussWeight(2) = 1.0; - GaussCoord[3][0] = -oneOnSqrt3; GaussCoord[3][1] = oneOnSqrt3; GaussWeight(3) = 1.0; + GaussCoord[0][0] = -oneOnSqrt3; + GaussCoord[0][1] = -oneOnSqrt3; + GaussWeight(0) = 1.0; + GaussCoord[1][0] = oneOnSqrt3; + GaussCoord[1][1] = -oneOnSqrt3; + GaussWeight(1) = 1.0; + GaussCoord[2][0] = oneOnSqrt3; + GaussCoord[2][1] = oneOnSqrt3; + GaussWeight(2) = 1.0; + GaussCoord[3][0] = -oneOnSqrt3; + GaussCoord[3][1] = oneOnSqrt3; + GaussWeight(3) = 1.0; /*--- Store the values of the shape functions and their derivatives ---*/ @@ -45,70 +51,66 @@ CQUAD4::CQUAD4() : CElementWithKnownSizes() { su2double Xi, Eta; for (iGauss = 0; iGauss < NGAUSS; iGauss++) { - Xi = GaussCoord[iGauss][0]; Eta = GaussCoord[iGauss][1]; su2double Ni[4] = {0.0}; ShapeFunctions(Xi, Eta, Ni); - for (jGauss = 0; jGauss < NGAUSS; jGauss++) - GaussPoint[iGauss].SetNi(Ni[jGauss], jGauss); + for (jGauss = 0; jGauss < NGAUSS; jGauss++) GaussPoint[iGauss].SetNi(Ni[jGauss], jGauss); /*--- dN/d xi, dN/d eta ---*/ ShapeFunctionJacobian(Xi, Eta, dNiXj[iGauss]); - } /*--- Store the extrapolation functions (used to compute nodal stresses) ---*/ - su2double ExtrapCoord[4][2], sqrt3 = 1.732050807568877;; + su2double ExtrapCoord[4][2], sqrt3 = 1.732050807568877; + ; - ExtrapCoord[0][0] = -sqrt3; ExtrapCoord[0][1] = -sqrt3; - ExtrapCoord[1][0] = sqrt3; ExtrapCoord[1][1] = -sqrt3; - ExtrapCoord[2][0] = sqrt3; ExtrapCoord[2][1] = sqrt3; - ExtrapCoord[3][0] = -sqrt3; ExtrapCoord[3][1] = sqrt3; + ExtrapCoord[0][0] = -sqrt3; + ExtrapCoord[0][1] = -sqrt3; + ExtrapCoord[1][0] = sqrt3; + ExtrapCoord[1][1] = -sqrt3; + ExtrapCoord[2][0] = sqrt3; + ExtrapCoord[2][1] = sqrt3; + ExtrapCoord[3][0] = -sqrt3; + ExtrapCoord[3][1] = sqrt3; for (iNode = 0; iNode < NNODE; iNode++) { - Xi = ExtrapCoord[iNode][0]; Eta = ExtrapCoord[iNode][1]; - NodalExtrap[iNode][0] = 0.25*(1.0-Xi)*(1.0-Eta); - NodalExtrap[iNode][1] = 0.25*(1.0+Xi)*(1.0-Eta); - NodalExtrap[iNode][2] = 0.25*(1.0+Xi)*(1.0+Eta); - NodalExtrap[iNode][3] = 0.25*(1.0-Xi)*(1.0+Eta); - + NodalExtrap[iNode][0] = 0.25 * (1.0 - Xi) * (1.0 - Eta); + NodalExtrap[iNode][1] = 0.25 * (1.0 + Xi) * (1.0 - Eta); + NodalExtrap[iNode][2] = 0.25 * (1.0 + Xi) * (1.0 + Eta); + NodalExtrap[iNode][3] = 0.25 * (1.0 - Xi) * (1.0 + Eta); } - } su2double CQUAD4::ComputeArea(const FrameType mode) const { - unsigned short iDim; - su2double a[2] = {0.0,0.0}, b[2] = {0.0,0.0}; + su2double a[2] = {0.0, 0.0}, b[2] = {0.0, 0.0}; su2double Area = 0.0; /*--- Select the appropriate source for the nodal coordinates depending on the frame requested for the gradient computation, REFERENCE (undeformed) or CURRENT (deformed)---*/ - const su2activematrix& Coord = (mode==REFERENCE) ? RefCoord : CurrentCoord; + const su2activematrix& Coord = (mode == REFERENCE) ? RefCoord : CurrentCoord; for (iDim = 0; iDim < NDIM; iDim++) { - a[iDim] = Coord[0][iDim]-Coord[2][iDim]; - b[iDim] = Coord[1][iDim]-Coord[2][iDim]; + a[iDim] = Coord[0][iDim] - Coord[2][iDim]; + b[iDim] = Coord[1][iDim] - Coord[2][iDim]; } - Area = 0.5*fabs(a[0]*b[1]-a[1]*b[0]); + Area = 0.5 * fabs(a[0] * b[1] - a[1] * b[0]); for (iDim = 0; iDim < NDIM; iDim++) { - a[iDim] = Coord[0][iDim]-Coord[3][iDim]; - b[iDim] = Coord[2][iDim]-Coord[3][iDim]; + a[iDim] = Coord[0][iDim] - Coord[3][iDim]; + b[iDim] = Coord[2][iDim] - Coord[3][iDim]; } - Area += 0.5*fabs(a[0]*b[1]-a[1]*b[0]); + Area += 0.5 * fabs(a[0] * b[1] - a[1] * b[0]); return Area; - } - diff --git a/Common/src/geometry/elements/CTETRA1.cpp b/Common/src/geometry/elements/CTETRA1.cpp index 41242eec185..1d937ef56ce 100644 --- a/Common/src/geometry/elements/CTETRA1.cpp +++ b/Common/src/geometry/elements/CTETRA1.cpp @@ -28,11 +28,13 @@ #include "../../../include/geometry/elements/CElement.hpp" #include "../../../include/toolboxes/geometry_toolbox.hpp" -CTETRA1::CTETRA1() : CElementWithKnownSizes() { - +CTETRA1::CTETRA1() : CElementWithKnownSizes() { /*--- Gauss coordinates and weights ---*/ - GaussCoord[0][0] = 0.25; GaussCoord[0][1] = 0.25; GaussCoord[0][2] = 0.25; GaussWeight(0) = 1.0/6.0; + GaussCoord[0][0] = 0.25; + GaussCoord[0][1] = 0.25; + GaussCoord[0][2] = 0.25; + GaussWeight(0) = 1.0 / 6.0; /*--- Store the values of the shape functions and their derivatives ---*/ @@ -40,23 +42,33 @@ CTETRA1::CTETRA1() : CElementWithKnownSizes() { su2double Xi, Eta, Zeta, val_Ni; for (iGauss = 0; iGauss < NGAUSS; iGauss++) { - Xi = GaussCoord[iGauss][0]; Eta = GaussCoord[iGauss][1]; Zeta = GaussCoord[iGauss][2]; - val_Ni = Xi; GaussPoint[iGauss].SetNi(val_Ni,0); - val_Ni = Eta; GaussPoint[iGauss].SetNi(val_Ni,1); - val_Ni = 1.0-Xi-Eta-Zeta; GaussPoint[iGauss].SetNi(val_Ni,2); - val_Ni = Zeta; GaussPoint[iGauss].SetNi(val_Ni,3); + val_Ni = Xi; + GaussPoint[iGauss].SetNi(val_Ni, 0); + val_Ni = Eta; + GaussPoint[iGauss].SetNi(val_Ni, 1); + val_Ni = 1.0 - Xi - Eta - Zeta; + GaussPoint[iGauss].SetNi(val_Ni, 2); + val_Ni = Zeta; + GaussPoint[iGauss].SetNi(val_Ni, 3); /*--- dN/d xi, dN/d eta, dN/d zeta ---*/ - dNiXj[iGauss][0][0] = 1.0; dNiXj[iGauss][0][1] = 0.0; dNiXj[iGauss][0][2] = 0.0; - dNiXj[iGauss][1][0] = 0.0; dNiXj[iGauss][1][1] = 1.0; dNiXj[iGauss][1][2] = 0.0; - dNiXj[iGauss][2][0] = -1.0; dNiXj[iGauss][2][1] = -1.0; dNiXj[iGauss][2][2] = -1.0; - dNiXj[iGauss][3][0] = 0.0; dNiXj[iGauss][3][1] = 0.0; dNiXj[iGauss][3][2] = 1.0; - + dNiXj[iGauss][0][0] = 1.0; + dNiXj[iGauss][0][1] = 0.0; + dNiXj[iGauss][0][2] = 0.0; + dNiXj[iGauss][1][0] = 0.0; + dNiXj[iGauss][1][1] = 1.0; + dNiXj[iGauss][1][2] = 0.0; + dNiXj[iGauss][2][0] = -1.0; + dNiXj[iGauss][2][1] = -1.0; + dNiXj[iGauss][2][2] = -1.0; + dNiXj[iGauss][3][0] = 0.0; + dNiXj[iGauss][3][1] = 0.0; + dNiXj[iGauss][3][2] = 1.0; } /*--- Shape functions evaluated at the nodes for extrapolation of the stresses at the Gaussian Points ---*/ @@ -66,18 +78,17 @@ CTETRA1::CTETRA1() : CElementWithKnownSizes() { NodalExtrap[1][0] = 1.0; NodalExtrap[2][0] = 1.0; NodalExtrap[3][0] = 1.0; - } su2double CTETRA1::ComputeVolume(const FrameType mode) const { - unsigned short iDim; - su2double r1[3] = {0.0,0.0,0.0}, r2[3] = {0.0,0.0,0.0}, r3[3] = {0.0,0.0,0.0}, CrossProduct[3] = {0.0,0.0,0.0}; + su2double r1[3] = {0.0, 0.0, 0.0}, r2[3] = {0.0, 0.0, 0.0}, r3[3] = {0.0, 0.0, 0.0}, + CrossProduct[3] = {0.0, 0.0, 0.0}; su2double Volume = 0.0; /*--- Select the appropriate source for the nodal coordinates depending on the frame requested for the gradient computation, REFERENCE (undeformed) or CURRENT (deformed)---*/ - const su2activematrix& Coord = (mode==REFERENCE) ? RefCoord : CurrentCoord; + const su2activematrix& Coord = (mode == REFERENCE) ? RefCoord : CurrentCoord; for (iDim = 0; iDim < NDIM; iDim++) { r1[iDim] = Coord[1][iDim] - Coord[0][iDim]; @@ -86,9 +97,7 @@ su2double CTETRA1::ComputeVolume(const FrameType mode) const { } GeometryToolbox::CrossProduct(r1, r2, CrossProduct); - Volume = fabs(GeometryToolbox::DotProduct(3, CrossProduct, r3))/6.0; + Volume = fabs(GeometryToolbox::DotProduct(3, CrossProduct, r3)) / 6.0; return Volume; - } - diff --git a/Common/src/geometry/elements/CTETRA4.cpp b/Common/src/geometry/elements/CTETRA4.cpp index 74740cb227e..614d0352c29 100644 --- a/Common/src/geometry/elements/CTETRA4.cpp +++ b/Common/src/geometry/elements/CTETRA4.cpp @@ -28,16 +28,27 @@ #include "../../../include/geometry/elements/CElement.hpp" #include "../../../include/toolboxes/geometry_toolbox.hpp" -CTETRA4::CTETRA4() : CElementWithKnownSizes() { - +CTETRA4::CTETRA4() : CElementWithKnownSizes() { /*--- Gauss coordinates and weights ---*/ - su2double r = ((5.0-sqrt(5.0))/20); - su2double s = ((5.0+3*sqrt(5.0))/20); - GaussCoord[0][0] = r; GaussCoord[0][1] = r; GaussCoord[0][2] = r; GaussWeight(0) = 1.0/24.0; - GaussCoord[0][0] = s; GaussCoord[0][1] = r; GaussCoord[0][2] = r; GaussWeight(1) = 1.0/24.0; - GaussCoord[0][0] = r; GaussCoord[0][1] = s; GaussCoord[0][2] = r; GaussWeight(2) = 1.0/24.0; - GaussCoord[0][0] = r; GaussCoord[0][1] = r; GaussCoord[0][2] = s; GaussWeight(3) = 1.0/24.0; + su2double r = ((5.0 - sqrt(5.0)) / 20); + su2double s = ((5.0 + 3 * sqrt(5.0)) / 20); + GaussCoord[0][0] = r; + GaussCoord[0][1] = r; + GaussCoord[0][2] = r; + GaussWeight(0) = 1.0 / 24.0; + GaussCoord[0][0] = s; + GaussCoord[0][1] = r; + GaussCoord[0][2] = r; + GaussWeight(1) = 1.0 / 24.0; + GaussCoord[0][0] = r; + GaussCoord[0][1] = s; + GaussCoord[0][2] = r; + GaussWeight(2) = 1.0 / 24.0; + GaussCoord[0][0] = r; + GaussCoord[0][1] = r; + GaussCoord[0][2] = s; + GaussWeight(3) = 1.0 / 24.0; /*--- Store the values of the shape functions and their derivatives ---*/ @@ -45,23 +56,33 @@ CTETRA4::CTETRA4() : CElementWithKnownSizes() { su2double Xi, Eta, Zeta, val_Ni; for (iGauss = 0; iGauss < nGaussPoints; iGauss++) { - Xi = GaussCoord[iGauss][0]; Eta = GaussCoord[iGauss][1]; Zeta = GaussCoord[iGauss][2]; - val_Ni = Xi; GaussPoint[iGauss].SetNi(val_Ni,0); - val_Ni = Eta; GaussPoint[iGauss].SetNi(val_Ni,1); - val_Ni = 1.0-Xi-Eta-Zeta; GaussPoint[iGauss].SetNi(val_Ni,2); - val_Ni = Zeta; GaussPoint[iGauss].SetNi(val_Ni,3); + val_Ni = Xi; + GaussPoint[iGauss].SetNi(val_Ni, 0); + val_Ni = Eta; + GaussPoint[iGauss].SetNi(val_Ni, 1); + val_Ni = 1.0 - Xi - Eta - Zeta; + GaussPoint[iGauss].SetNi(val_Ni, 2); + val_Ni = Zeta; + GaussPoint[iGauss].SetNi(val_Ni, 3); /*--- dN/d xi, dN/d eta, dN/d zeta ---*/ - dNiXj[iGauss][0][0] = 1.0; dNiXj[iGauss][0][1] = 0.0; dNiXj[iGauss][0][2] = 0.0; - dNiXj[iGauss][1][0] = 0.0; dNiXj[iGauss][1][1] = 1.0; dNiXj[iGauss][1][2] = 0.0; - dNiXj[iGauss][2][0] = -1.0; dNiXj[iGauss][2][1] = -1.0; dNiXj[iGauss][2][2] = -1.0; - dNiXj[iGauss][3][0] = 0.0; dNiXj[iGauss][3][1] = 0.0; dNiXj[iGauss][3][2] = 1.0; - + dNiXj[iGauss][0][0] = 1.0; + dNiXj[iGauss][0][1] = 0.0; + dNiXj[iGauss][0][2] = 0.0; + dNiXj[iGauss][1][0] = 0.0; + dNiXj[iGauss][1][1] = 1.0; + dNiXj[iGauss][1][2] = 0.0; + dNiXj[iGauss][2][0] = -1.0; + dNiXj[iGauss][2][1] = -1.0; + dNiXj[iGauss][2][2] = -1.0; + dNiXj[iGauss][3][0] = 0.0; + dNiXj[iGauss][3][1] = 0.0; + dNiXj[iGauss][3][2] = 1.0; } /*--- Shape functions evaluated at the nodes for extrapolation of the stresses at the Gaussian Points ---*/ @@ -71,18 +92,17 @@ CTETRA4::CTETRA4() : CElementWithKnownSizes() { NodalExtrap[1][0] = 1.0; NodalExtrap[2][0] = 1.0; NodalExtrap[3][0] = 1.0; - } su2double CTETRA4::ComputeVolume(const FrameType mode) const { - unsigned short iDim; - su2double r1[3] = {0.0,0.0,0.0}, r2[3] = {0.0,0.0,0.0}, r3[3] = {0.0,0.0,0.0}, CrossProduct[3] = {0.0,0.0,0.0}; + su2double r1[3] = {0.0, 0.0, 0.0}, r2[3] = {0.0, 0.0, 0.0}, r3[3] = {0.0, 0.0, 0.0}, + CrossProduct[3] = {0.0, 0.0, 0.0}; su2double Volume = 0.0; /*--- Select the appropriate source for the nodal coordinates depending on the frame requested for the gradient computation, REFERENCE (undeformed) or CURRENT (deformed)---*/ - const su2activematrix& Coord = (mode==REFERENCE) ? RefCoord : CurrentCoord; + const su2activematrix& Coord = (mode == REFERENCE) ? RefCoord : CurrentCoord; for (iDim = 0; iDim < NDIM; iDim++) { r1[iDim] = Coord[1][iDim] - Coord[0][iDim]; @@ -91,9 +111,7 @@ su2double CTETRA4::ComputeVolume(const FrameType mode) const { } GeometryToolbox::CrossProduct(r1, r2, CrossProduct); - Volume = fabs(GeometryToolbox::DotProduct(3, CrossProduct, r3))/6.0; + Volume = fabs(GeometryToolbox::DotProduct(3, CrossProduct, r3)) / 6.0; return Volume; - } - diff --git a/Common/src/geometry/elements/CTRIA1.cpp b/Common/src/geometry/elements/CTRIA1.cpp index e74c707f627..f845f2634fb 100644 --- a/Common/src/geometry/elements/CTRIA1.cpp +++ b/Common/src/geometry/elements/CTRIA1.cpp @@ -27,12 +27,12 @@ #include "../../../include/geometry/elements/CElement.hpp" - -CTRIA1::CTRIA1() : CElementWithKnownSizes() { - +CTRIA1::CTRIA1() : CElementWithKnownSizes() { /*--- Gauss coordinates and weights ---*/ - GaussCoord[0][0] = 1.0/3.0; GaussCoord[0][1] = 1.0/3.0; GaussWeight(0) = 0.5; + GaussCoord[0][0] = 1.0 / 3.0; + GaussCoord[0][1] = 1.0 / 3.0; + GaussWeight(0) = 0.5; /*--- Store the values of the shape functions and their derivatives ---*/ @@ -40,20 +40,24 @@ CTRIA1::CTRIA1() : CElementWithKnownSizes() { su2double Xi, Eta, val_Ni; for (iGauss = 0; iGauss < NGAUSS; iGauss++) { - Xi = GaussCoord[iGauss][0]; Eta = GaussCoord[iGauss][1]; - val_Ni = Xi; GaussPoint[iGauss].SetNi(val_Ni,0); - val_Ni = Eta; GaussPoint[iGauss].SetNi(val_Ni,1); - val_Ni = 1-Xi-Eta; GaussPoint[iGauss].SetNi(val_Ni,2); + val_Ni = Xi; + GaussPoint[iGauss].SetNi(val_Ni, 0); + val_Ni = Eta; + GaussPoint[iGauss].SetNi(val_Ni, 1); + val_Ni = 1 - Xi - Eta; + GaussPoint[iGauss].SetNi(val_Ni, 2); /*--- dN/d xi, dN/d eta ---*/ - dNiXj[iGauss][0][0] = 1.0; dNiXj[iGauss][0][1] = 0.0; - dNiXj[iGauss][1][0] = 0.0; dNiXj[iGauss][1][1] = 1.0; - dNiXj[iGauss][2][0] = -1.0; dNiXj[iGauss][2][1] = -1.0; - + dNiXj[iGauss][0][0] = 1.0; + dNiXj[iGauss][0][1] = 0.0; + dNiXj[iGauss][1][0] = 0.0; + dNiXj[iGauss][1][1] = 1.0; + dNiXj[iGauss][2][0] = -1.0; + dNiXj[iGauss][2][1] = -1.0; } /*--- Shape functions evaluated at the nodes for extrapolation of the stresses at the Gaussian Points ---*/ @@ -62,27 +66,23 @@ CTRIA1::CTRIA1() : CElementWithKnownSizes() { NodalExtrap[0][0] = 1.0; NodalExtrap[1][0] = 1.0; NodalExtrap[2][0] = 1.0; - } su2double CTRIA1::ComputeArea(const FrameType mode) const { - unsigned short iDim; - su2double a[2] = {0.0,0.0}, b[2] = {0.0,0.0}; + su2double a[2] = {0.0, 0.0}, b[2] = {0.0, 0.0}; su2double Area = 0.0; /*--- Select the appropriate source for the nodal coordinates depending on the frame requested for the gradient computation, REFERENCE (undeformed) or CURRENT (deformed) ---*/ - const su2activematrix& Coord = (mode==REFERENCE) ? RefCoord : CurrentCoord; + const su2activematrix& Coord = (mode == REFERENCE) ? RefCoord : CurrentCoord; for (iDim = 0; iDim < NDIM; iDim++) { - a[iDim] = Coord[0][iDim]-Coord[2][iDim]; - b[iDim] = Coord[1][iDim]-Coord[2][iDim]; + a[iDim] = Coord[0][iDim] - Coord[2][iDim]; + b[iDim] = Coord[1][iDim] - Coord[2][iDim]; } - Area = 0.5*fabs(a[0]*b[1]-a[1]*b[0]); + Area = 0.5 * fabs(a[0] * b[1] - a[1] * b[0]); return Area; - } - diff --git a/Common/src/geometry/elements/CTRIA3.cpp b/Common/src/geometry/elements/CTRIA3.cpp index afc3996a811..f9856113e4a 100644 --- a/Common/src/geometry/elements/CTRIA3.cpp +++ b/Common/src/geometry/elements/CTRIA3.cpp @@ -27,13 +27,18 @@ #include "../../../include/geometry/elements/CElement.hpp" -CTRIA3::CTRIA3() : CElementWithKnownSizes() { - +CTRIA3::CTRIA3() : CElementWithKnownSizes() { /*--- Gauss coordinates and weights ---*/ - GaussCoord[0][0] = 0.66666666666666666667; GaussCoord[0][1] = 0.16666666666666666667; GaussWeight(0) = 0.33333333333333333333; - GaussCoord[1][0] = 0.16666666666666666667; GaussCoord[1][1] = 0.66666666666666666667; GaussWeight(1) = 0.33333333333333333333; - GaussCoord[2][0] = 0.16666666666666666667; GaussCoord[2][1] = 0.16666666666666666667; GaussWeight(2) = 0.33333333333333333333; + GaussCoord[0][0] = 0.66666666666666666667; + GaussCoord[0][1] = 0.16666666666666666667; + GaussWeight(0) = 0.33333333333333333333; + GaussCoord[1][0] = 0.16666666666666666667; + GaussCoord[1][1] = 0.66666666666666666667; + GaussWeight(1) = 0.33333333333333333333; + GaussCoord[2][0] = 0.16666666666666666667; + GaussCoord[2][1] = 0.16666666666666666667; + GaussWeight(2) = 0.33333333333333333333; /*--- Store the values of the shape functions and their derivatives ---*/ @@ -41,20 +46,24 @@ CTRIA3::CTRIA3() : CElementWithKnownSizes() { su2double Xi, Eta, val_Ni; for (iGauss = 0; iGauss < nGaussPoints; iGauss++) { - Xi = GaussCoord[iGauss][0]; Eta = GaussCoord[iGauss][1]; - val_Ni = 1-Xi-Eta; GaussPoint[iGauss].SetNi(val_Ni,0); - val_Ni = Xi; GaussPoint[iGauss].SetNi(val_Ni,1); - val_Ni = Eta; GaussPoint[iGauss].SetNi(val_Ni,2); + val_Ni = 1 - Xi - Eta; + GaussPoint[iGauss].SetNi(val_Ni, 0); + val_Ni = Xi; + GaussPoint[iGauss].SetNi(val_Ni, 1); + val_Ni = Eta; + GaussPoint[iGauss].SetNi(val_Ni, 2); /*--- dN/d xi, dN/d eta ---*/ - dNiXj[iGauss][0][0] = -1.0; dNiXj[iGauss][0][1] = -1.0; - dNiXj[iGauss][1][0] = 1.0; dNiXj[iGauss][1][1] = 0.0; - dNiXj[iGauss][2][0] = 0.0; dNiXj[iGauss][2][1] = 1.0; - + dNiXj[iGauss][0][0] = -1.0; + dNiXj[iGauss][0][1] = -1.0; + dNiXj[iGauss][1][0] = 1.0; + dNiXj[iGauss][1][1] = 0.0; + dNiXj[iGauss][2][0] = 0.0; + dNiXj[iGauss][2][1] = 1.0; } /*--- Shape functions evaluated at the nodes for extrapolation of the stresses at the Gaussian Points ---*/ @@ -63,26 +72,23 @@ CTRIA3::CTRIA3() : CElementWithKnownSizes() { NodalExtrap[0][0] = 1.0; NodalExtrap[1][0] = 1.0; NodalExtrap[2][0] = 1.0; - } su2double CTRIA3::ComputeArea(const FrameType mode) const { - unsigned short iDim; - su2double a[3] = {0.0,0.0,0.0}, b[3] = {0.0,0.0,0.0}; + su2double a[3] = {0.0, 0.0, 0.0}, b[3] = {0.0, 0.0, 0.0}; su2double Area = 0.0; /*--- Select the appropriate source for the nodal coordinates depending on the frame requested for the gradient computation, REFERENCE (undeformed) or CURRENT (deformed) ---*/ - const su2activematrix& Coord = (mode==REFERENCE) ? RefCoord : CurrentCoord; + const su2activematrix& Coord = (mode == REFERENCE) ? RefCoord : CurrentCoord; for (iDim = 0; iDim < NDIM; iDim++) { - a[iDim] = Coord[0][iDim]-Coord[2][iDim]; - b[iDim] = Coord[1][iDim]-Coord[2][iDim]; + a[iDim] = Coord[0][iDim] - Coord[2][iDim]; + b[iDim] = Coord[1][iDim] - Coord[2][iDim]; } - Area = 0.5*fabs(a[0]*b[1]-a[1]*b[0]); + Area = 0.5 * fabs(a[0] * b[1] - a[1] * b[0]); return Area; - } diff --git a/Common/src/geometry/meshreader/CBoxMeshReaderFVM.cpp b/Common/src/geometry/meshreader/CBoxMeshReaderFVM.cpp index 09c0427c920..7d63be15052 100644 --- a/Common/src/geometry/meshreader/CBoxMeshReaderFVM.cpp +++ b/Common/src/geometry/meshreader/CBoxMeshReaderFVM.cpp @@ -29,16 +29,13 @@ #include "../../../include/toolboxes/CLinearPartitioner.hpp" #include "../../../include/geometry/meshreader/CBoxMeshReaderFVM.hpp" -CBoxMeshReaderFVM::CBoxMeshReaderFVM(CConfig *val_config, - unsigned short val_iZone, - unsigned short val_nZone) -: CMeshReaderFVM(val_config, val_iZone, val_nZone) { - +CBoxMeshReaderFVM::CBoxMeshReaderFVM(CConfig* val_config, unsigned short val_iZone, unsigned short val_nZone) + : CMeshReaderFVM(val_config, val_iZone, val_nZone) { /* The box mesh is always 3D. */ dimension = 3; /* Set the VTK type for the interior elements and the boundary elements. */ - KindElem = HEXAHEDRON; + KindElem = HEXAHEDRON; KindBound = QUADRILATERAL; /* The number of nodes in the i and j directions. */ @@ -64,21 +61,19 @@ CBoxMeshReaderFVM::CBoxMeshReaderFVM(CConfig *val_config, ComputeBoxPointCoordinates(); ComputeBoxVolumeConnectivity(); ComputeBoxSurfaceConnectivity(); - } -CBoxMeshReaderFVM::~CBoxMeshReaderFVM(void) { } +CBoxMeshReaderFVM::~CBoxMeshReaderFVM(void) {} void CBoxMeshReaderFVM::ComputeBoxPointCoordinates() { - /* Set the global count of points based on the grid dimensions. */ - numberOfGlobalPoints = (nNode)*(mNode)*(pNode); + numberOfGlobalPoints = (nNode) * (mNode) * (pNode); /* Get a partitioner to help with linear partitioning. */ - CLinearPartitioner pointPartitioner(numberOfGlobalPoints,0); + CLinearPartitioner pointPartitioner(numberOfGlobalPoints, 0); /* Determine number of local points */ - for(unsigned long globalIndex=0; globalIndex < numberOfGlobalPoints; globalIndex++) { + for (unsigned long globalIndex = 0; globalIndex < numberOfGlobalPoints; globalIndex++) { if ((int)pointPartitioner.GetRankContainingIndex(globalIndex) == rank) { numberOfLocalPoints++; } @@ -87,19 +82,17 @@ void CBoxMeshReaderFVM::ComputeBoxPointCoordinates() { /* Loop over our analytically defined of coordinates and store only those that contain a node within our linear partition of points. */ localPointCoordinates.resize(dimension); - for (int k = 0; k < dimension; k++) - localPointCoordinates[k].reserve(numberOfLocalPoints); + for (int k = 0; k < dimension; k++) localPointCoordinates[k].reserve(numberOfLocalPoints); unsigned long globalIndex = 0; for (unsigned long kNode = 0; kNode < pNode; kNode++) { for (unsigned long jNode = 0; jNode < mNode; jNode++) { for (unsigned long iNode = 0; iNode < nNode; iNode++) { if ((int)pointPartitioner.GetRankContainingIndex(globalIndex) == rank) { - /* Store the coordinates more clearly. */ - const passivedouble x = SU2_TYPE::GetValue(Lx*((su2double)iNode)/((su2double)(nNode-1))+Ox); - const passivedouble y = SU2_TYPE::GetValue(Ly*((su2double)jNode)/((su2double)(mNode-1))+Oy); - const passivedouble z = SU2_TYPE::GetValue(Lz*((su2double)kNode)/((su2double)(pNode-1))+Oz); + const passivedouble x = SU2_TYPE::GetValue(Lx * ((su2double)iNode) / ((su2double)(nNode - 1)) + Ox); + const passivedouble y = SU2_TYPE::GetValue(Ly * ((su2double)jNode) / ((su2double)(mNode - 1)) + Oy); + const passivedouble z = SU2_TYPE::GetValue(Lz * ((su2double)kNode) / ((su2double)(pNode - 1)) + Oz); /* Load into the coordinate class data structure. */ localPointCoordinates[0].push_back(x); @@ -110,35 +103,32 @@ void CBoxMeshReaderFVM::ComputeBoxPointCoordinates() { } } } - } void CBoxMeshReaderFVM::ComputeBoxVolumeConnectivity() { - /* Set the global count of elements based on the grid dimensions. */ - numberOfGlobalElements = (nNode-1)*(mNode-1)*(pNode-1); + numberOfGlobalElements = (nNode - 1) * (mNode - 1) * (pNode - 1); /* Get a partitioner to help with linear partitioning. */ - CLinearPartitioner pointPartitioner(numberOfGlobalPoints,0); + CLinearPartitioner pointPartitioner(numberOfGlobalPoints, 0); /* Loop over our analytically defined of elements and store only those that contain a node within our linear partition of points. */ - numberOfLocalElements = 0; - vector connectivity(N_POINTS_HEXAHEDRON,0); + numberOfLocalElements = 0; + vector connectivity(N_POINTS_HEXAHEDRON, 0); unsigned long globalIndex = 0; - for (unsigned long kNode = 0; kNode < pNode-1; kNode++) { - for (unsigned long jNode = 0; jNode < mNode-1; jNode++) { - for (unsigned long iNode = 0; iNode < nNode-1; iNode++) { - + for (unsigned long kNode = 0; kNode < pNode - 1; kNode++) { + for (unsigned long jNode = 0; jNode < mNode - 1; jNode++) { + for (unsigned long iNode = 0; iNode < nNode - 1; iNode++) { /* Compute connectivity based on the i,j,k index. */ - connectivity[0] = kNode*mNode*nNode + jNode*nNode + iNode; - connectivity[1] = kNode*mNode*nNode + jNode*nNode + iNode + 1; - connectivity[2] = kNode*mNode*nNode + (jNode + 1)*nNode + (iNode + 1); - connectivity[3] = kNode*mNode*nNode + (jNode + 1)*nNode + iNode; - connectivity[4] = (kNode + 1)*mNode*nNode + jNode*nNode + iNode; - connectivity[5] = (kNode + 1)*mNode*nNode + jNode*nNode + iNode + 1; - connectivity[6] = (kNode + 1)*mNode*nNode + (jNode + 1)*nNode + (iNode + 1); - connectivity[7] = (kNode + 1)*mNode*nNode + (jNode + 1)*nNode + iNode; + connectivity[0] = kNode * mNode * nNode + jNode * nNode + iNode; + connectivity[1] = kNode * mNode * nNode + jNode * nNode + iNode + 1; + connectivity[2] = kNode * mNode * nNode + (jNode + 1) * nNode + (iNode + 1); + connectivity[3] = kNode * mNode * nNode + (jNode + 1) * nNode + iNode; + connectivity[4] = (kNode + 1) * mNode * nNode + jNode * nNode + iNode; + connectivity[5] = (kNode + 1) * mNode * nNode + jNode * nNode + iNode + 1; + connectivity[6] = (kNode + 1) * mNode * nNode + (jNode + 1) * nNode + (iNode + 1); + connectivity[7] = (kNode + 1) * mNode * nNode + (jNode + 1) * nNode + iNode; /* Check whether any of the points is in our linear partition. */ bool isOwned = false; @@ -161,126 +151,117 @@ void CBoxMeshReaderFVM::ComputeBoxVolumeConnectivity() { } } } - } void CBoxMeshReaderFVM::ComputeBoxSurfaceConnectivity() { - /* The rectangle alays has 4 markers. */ numberOfMarkers = 6; surfaceElementConnectivity.resize(numberOfMarkers); markerNames.resize(numberOfMarkers); - vector connectivity(N_POINTS_HEXAHEDRON,0); + vector connectivity(N_POINTS_HEXAHEDRON, 0); /* Compute and store the 6 sets of connectivity. */ markerNames[0] = "x_minus"; if (rank == MASTER_NODE) { - for (unsigned long kNode = 0; kNode < pNode-1; kNode++) { - for (unsigned long jNode = 0; jNode < mNode-1; jNode++) { - - connectivity[0] = kNode*mNode*nNode + jNode*nNode; - connectivity[1] = (kNode + 1)*mNode*nNode + jNode*nNode; - connectivity[2] = (kNode + 1)*mNode*nNode + (jNode + 1)*nNode; - connectivity[3] = kNode*mNode*nNode + (jNode + 1)*nNode; + for (unsigned long kNode = 0; kNode < pNode - 1; kNode++) { + for (unsigned long jNode = 0; jNode < mNode - 1; jNode++) { + connectivity[0] = kNode * mNode * nNode + jNode * nNode; + connectivity[1] = (kNode + 1) * mNode * nNode + jNode * nNode; + connectivity[2] = (kNode + 1) * mNode * nNode + (jNode + 1) * nNode; + connectivity[3] = kNode * mNode * nNode + (jNode + 1) * nNode; surfaceElementConnectivity[0].push_back(0); surfaceElementConnectivity[0].push_back(KindBound); for (unsigned short i = 0; i < N_POINTS_HEXAHEDRON; i++) - surfaceElementConnectivity[0].push_back(connectivity[i]); + surfaceElementConnectivity[0].push_back(connectivity[i]); } } } markerNames[1] = "x_plus"; if (rank == MASTER_NODE) { - for (unsigned long kNode = 0; kNode < pNode-1; kNode++) { - for (unsigned long jNode = 0; jNode < mNode-1; jNode++) { - - connectivity[0] = kNode*mNode*nNode + jNode*nNode + (nNode - 1); - connectivity[1] = kNode*mNode*nNode + (jNode + 1)*nNode + (nNode - 1); - connectivity[2] = (kNode + 1)*mNode*nNode + (jNode + 1)*nNode + (nNode - 1); - connectivity[3] = (kNode + 1)*mNode*nNode + jNode*nNode + (nNode - 1); + for (unsigned long kNode = 0; kNode < pNode - 1; kNode++) { + for (unsigned long jNode = 0; jNode < mNode - 1; jNode++) { + connectivity[0] = kNode * mNode * nNode + jNode * nNode + (nNode - 1); + connectivity[1] = kNode * mNode * nNode + (jNode + 1) * nNode + (nNode - 1); + connectivity[2] = (kNode + 1) * mNode * nNode + (jNode + 1) * nNode + (nNode - 1); + connectivity[3] = (kNode + 1) * mNode * nNode + jNode * nNode + (nNode - 1); surfaceElementConnectivity[1].push_back(0); surfaceElementConnectivity[1].push_back(KindBound); for (unsigned short i = 0; i < N_POINTS_HEXAHEDRON; i++) - surfaceElementConnectivity[1].push_back(connectivity[i]); + surfaceElementConnectivity[1].push_back(connectivity[i]); } } } markerNames[2] = "y_minus"; if (rank == MASTER_NODE) { - for (unsigned long kNode = 0; kNode < pNode-1; kNode++) { - for (unsigned long iNode = 0; iNode < nNode-1; iNode++) { - - connectivity[0] = kNode*mNode*nNode + iNode; - connectivity[1] = kNode*mNode*nNode + iNode + 1; - connectivity[2] = (kNode + 1)*mNode*nNode + iNode + 1; - connectivity[3] = (kNode + 1)*mNode*nNode + iNode; + for (unsigned long kNode = 0; kNode < pNode - 1; kNode++) { + for (unsigned long iNode = 0; iNode < nNode - 1; iNode++) { + connectivity[0] = kNode * mNode * nNode + iNode; + connectivity[1] = kNode * mNode * nNode + iNode + 1; + connectivity[2] = (kNode + 1) * mNode * nNode + iNode + 1; + connectivity[3] = (kNode + 1) * mNode * nNode + iNode; surfaceElementConnectivity[2].push_back(0); surfaceElementConnectivity[2].push_back(KindBound); for (unsigned short i = 0; i < N_POINTS_HEXAHEDRON; i++) - surfaceElementConnectivity[2].push_back(connectivity[i]); + surfaceElementConnectivity[2].push_back(connectivity[i]); } } } markerNames[3] = "y_plus"; if (rank == MASTER_NODE) { - for (unsigned long kNode = 0; kNode < pNode-1; kNode++) { - for (unsigned long iNode = 0; iNode < nNode-1; iNode++) { - - connectivity[0] = kNode*mNode*nNode + (mNode - 1)*nNode + iNode; - connectivity[1] = kNode*mNode*nNode + (mNode - 1)*nNode + iNode + 1; - connectivity[2] = (kNode + 1)*mNode*nNode + (mNode - 1)*nNode + iNode + 1; - connectivity[3] = (kNode + 1)*mNode*nNode + (mNode - 1)*nNode + iNode; + for (unsigned long kNode = 0; kNode < pNode - 1; kNode++) { + for (unsigned long iNode = 0; iNode < nNode - 1; iNode++) { + connectivity[0] = kNode * mNode * nNode + (mNode - 1) * nNode + iNode; + connectivity[1] = kNode * mNode * nNode + (mNode - 1) * nNode + iNode + 1; + connectivity[2] = (kNode + 1) * mNode * nNode + (mNode - 1) * nNode + iNode + 1; + connectivity[3] = (kNode + 1) * mNode * nNode + (mNode - 1) * nNode + iNode; surfaceElementConnectivity[3].push_back(0); surfaceElementConnectivity[3].push_back(KindBound); for (unsigned short i = 0; i < N_POINTS_HEXAHEDRON; i++) - surfaceElementConnectivity[3].push_back(connectivity[i]); + surfaceElementConnectivity[3].push_back(connectivity[i]); } } } markerNames[4] = "z_minus"; if (rank == MASTER_NODE) { - for (unsigned long jNode = 0; jNode < mNode-1; jNode++) { - for (unsigned long iNode = 0; iNode < nNode-1; iNode++) { - - connectivity[0] = jNode*nNode + iNode; - connectivity[1] = jNode*nNode + iNode + 1; - connectivity[2] = (jNode + 1)*nNode + (iNode + 1); - connectivity[3] = (jNode + 1)*nNode + iNode; + for (unsigned long jNode = 0; jNode < mNode - 1; jNode++) { + for (unsigned long iNode = 0; iNode < nNode - 1; iNode++) { + connectivity[0] = jNode * nNode + iNode; + connectivity[1] = jNode * nNode + iNode + 1; + connectivity[2] = (jNode + 1) * nNode + (iNode + 1); + connectivity[3] = (jNode + 1) * nNode + iNode; surfaceElementConnectivity[4].push_back(0); surfaceElementConnectivity[4].push_back(KindBound); for (unsigned short i = 0; i < N_POINTS_HEXAHEDRON; i++) - surfaceElementConnectivity[4].push_back(connectivity[i]); + surfaceElementConnectivity[4].push_back(connectivity[i]); } } } markerNames[5] = "z_plus"; if (rank == MASTER_NODE) { - for (unsigned long jNode = 0; jNode < mNode-1; jNode++) { - for (unsigned long iNode = 0; iNode < nNode-1; iNode++) { - - connectivity[0] = (pNode-1)*mNode*nNode + jNode*nNode + iNode; - connectivity[1] = (pNode-1)*mNode*nNode + jNode*nNode + iNode + 1; - connectivity[2] = (pNode-1)*mNode*nNode + (jNode + 1)*nNode + (iNode + 1); - connectivity[3] = (pNode-1)*mNode*nNode + (jNode + 1)*nNode + iNode; + for (unsigned long jNode = 0; jNode < mNode - 1; jNode++) { + for (unsigned long iNode = 0; iNode < nNode - 1; iNode++) { + connectivity[0] = (pNode - 1) * mNode * nNode + jNode * nNode + iNode; + connectivity[1] = (pNode - 1) * mNode * nNode + jNode * nNode + iNode + 1; + connectivity[2] = (pNode - 1) * mNode * nNode + (jNode + 1) * nNode + (iNode + 1); + connectivity[3] = (pNode - 1) * mNode * nNode + (jNode + 1) * nNode + iNode; surfaceElementConnectivity[5].push_back(0); surfaceElementConnectivity[5].push_back(KindBound); for (unsigned short i = 0; i < N_POINTS_HEXAHEDRON; i++) - surfaceElementConnectivity[5].push_back(connectivity[i]); + surfaceElementConnectivity[5].push_back(connectivity[i]); } } } - } diff --git a/Common/src/geometry/meshreader/CCGNSMeshReaderFVM.cpp b/Common/src/geometry/meshreader/CCGNSMeshReaderFVM.cpp index 53e3b3dd0c7..8c5019c9c53 100644 --- a/Common/src/geometry/meshreader/CCGNSMeshReaderFVM.cpp +++ b/Common/src/geometry/meshreader/CCGNSMeshReaderFVM.cpp @@ -29,11 +29,8 @@ #include "../../../include/toolboxes/CLinearPartitioner.hpp" #include "../../../include/geometry/meshreader/CCGNSMeshReaderFVM.hpp" -CCGNSMeshReaderFVM::CCGNSMeshReaderFVM(CConfig *val_config, - unsigned short val_iZone, - unsigned short val_nZone) -: CMeshReaderFVM(val_config, val_iZone, val_nZone) { - +CCGNSMeshReaderFVM::CCGNSMeshReaderFVM(CConfig* val_config, unsigned short val_iZone, unsigned short val_nZone) + : CMeshReaderFVM(val_config, val_iZone, val_nZone) { #ifdef HAVE_CGNS OpenCGNSFile(config->GetMesh_FileName()); @@ -69,26 +66,23 @@ CCGNSMeshReaderFVM::CCGNSMeshReaderFVM(CConfig *val_config, ReformatCGNSSurfaceConnectivity(); #else - SU2_MPI::Error(string(" SU2 built without CGNS support. \n") + - string(" To use CGNS, build SU2 accordingly."), + SU2_MPI::Error(string(" SU2 built without CGNS support. \n") + string(" To use CGNS, build SU2 accordingly."), CURRENT_FUNCTION); #endif } -CCGNSMeshReaderFVM::~CCGNSMeshReaderFVM(void) { } +CCGNSMeshReaderFVM::~CCGNSMeshReaderFVM(void) {} #ifdef HAVE_CGNS void CCGNSMeshReaderFVM::OpenCGNSFile(string val_filename) { - /*--- Check whether the supplied file is truly a CGNS file. ---*/ int file_type; float file_version; if (cg_is_cgns(val_filename.c_str(), &file_type) != CG_OK) { - SU2_MPI::Error(val_filename + - string(" was not found or is not a properly formatted") + - string(" CGNS file.\nNote that SU2 expects unstructured") + - string(" CGNS files in ADF data format."), + SU2_MPI::Error(val_filename + string(" was not found or is not a properly formatted") + + string(" CGNS file.\nNote that SU2 expects unstructured") + + string(" CGNS files in ADF data format."), CURRENT_FUNCTION); } @@ -96,46 +90,42 @@ void CCGNSMeshReaderFVM::OpenCGNSFile(string val_filename) { is the specific index number for this file and will be repeatedly used in the function calls. ---*/ - if (cg_open(val_filename.c_str(), CG_MODE_READ, &cgnsFileID)) - cg_error_exit(); + if (cg_open(val_filename.c_str(), CG_MODE_READ, &cgnsFileID)) cg_error_exit(); if (rank == MASTER_NODE) { cout << "Reading the CGNS file: "; cout << val_filename.c_str() << "." << endl; } - if (cg_version(cgnsFileID, &file_version)) - cg_error_exit(); + if (cg_version(cgnsFileID, &file_version)) cg_error_exit(); if (rank == MASTER_NODE) { if (file_version < 4.0) { - cout << "WARNING: The CGNS file version (" << file_version << ") is old and may cause high memory usage issues, consider updating the file with the cgnsupdate tool.\n"; + cout + << "WARNING: The CGNS file version (" << file_version + << ") is old and may cause high memory usage issues, consider updating the file with the cgnsupdate tool.\n"; } } } void CCGNSMeshReaderFVM::ReadCGNSDatabaseMetadata() { - /*--- Get the number of databases. This is the highest node in the CGNS heirarchy. ---*/ int nbases; if (cg_nbases(cgnsFileID, &nbases)) cg_error_exit(); - if (rank == MASTER_NODE) - cout << "CGNS file contains " << nbases << " database(s)." << endl; + if (rank == MASTER_NODE) cout << "CGNS file contains " << nbases << " database(s)." << endl; /*--- Check if there is more than one database. Throw an error if there is because this reader can currently only handle one database. ---*/ - if ( nbases > 1 ) { - SU2_MPI::Error("CGNS reader currently can only handle 1 database.", - CURRENT_FUNCTION); + if (nbases > 1) { + SU2_MPI::Error("CGNS reader currently can only handle 1 database.", CURRENT_FUNCTION); } /*--- Read the database. Note that the CGNS indexing starts at 1. ---*/ int cell_dim, phys_dim; char basename[CGNS_STRING_SIZE]; - if (cg_base_read(cgnsFileID, cgnsBase, basename, &cell_dim, &phys_dim)) - cg_error_exit(); + if (cg_base_read(cgnsFileID, cgnsBase, basename, &cell_dim, &phys_dim)) cg_error_exit(); if (rank == MASTER_NODE) { cout << "Database " << cgnsBase << ", " << basename << ": "; cout << " cell dimension of " << cell_dim << ", physical "; @@ -145,11 +135,9 @@ void CCGNSMeshReaderFVM::ReadCGNSDatabaseMetadata() { /*--- Set the number of dimensions baed on cell_dim. ---*/ dimension = (unsigned short)cell_dim; - } void CCGNSMeshReaderFVM::ReadCGNSZoneMetadata() { - /*--- First, check all sections to find the element types and to classify them as either surface or volume elements. We will also perform some error checks here to avoid partitioning issues. ---*/ @@ -159,16 +147,17 @@ void CCGNSMeshReaderFVM::ReadCGNSZoneMetadata() { int nzones; if (cg_nzones(cgnsFileID, cgnsBase, &nzones)) cg_error_exit(); if (rank == MASTER_NODE) { - cout << nzones << " total zone(s)." << endl; + cout << nzones << " total zone(s)." << endl; } /*--- Check if there is more than one zone. Until we enable it, we will require a single zone CGNS file. Multizone problems can still be run with CGNS by using separate CGNS files for each zone. ---*/ - if ( nzones > 1 ) { + if (nzones > 1) { SU2_MPI::Error(string("CGNS reader currently expects only 1 zone per CGNS file.") + - string("Multizone problems can be run with separate CGNS files for each zone."), CURRENT_FUNCTION); + string("Multizone problems can be run with separate CGNS files for each zone."), + CURRENT_FUNCTION); } /*--- Read the basic information for this zone, including @@ -178,8 +167,7 @@ void CCGNSMeshReaderFVM::ReadCGNSZoneMetadata() { vector cgsize(3); ZoneType_t zonetype; char zonename[CGNS_STRING_SIZE]; - if (cg_zone_read(cgnsFileID, cgnsBase, cgnsZone, zonename, cgsize.data())) - cg_error_exit(); + if (cg_zone_read(cgnsFileID, cgnsBase, cgnsZone, zonename, cgsize.data())) cg_error_exit(); /*--- Rename the zone size information for clarity. NOTE: The number of cells here may be only the number of @@ -187,7 +175,7 @@ void CCGNSMeshReaderFVM::ReadCGNSZoneMetadata() { be counted explicitly later. ---*/ numberOfGlobalPoints = cgsize[0]; - int nElemCGNS = cgsize[1]; + int nElemCGNS = cgsize[1]; /*--- Get some additional information about the current zone. ---*/ @@ -196,8 +184,7 @@ void CCGNSMeshReaderFVM::ReadCGNSZoneMetadata() { /*--- Check for an unstructured mesh. Throw an error if not found. ---*/ if (zonetype != Unstructured) - SU2_MPI::Error("Structured CGNS zone found while unstructured expected.", - CURRENT_FUNCTION); + SU2_MPI::Error("Structured CGNS zone found while unstructured expected.", CURRENT_FUNCTION); /*--- Print current zone info to the console. ---*/ @@ -214,19 +201,16 @@ void CCGNSMeshReaderFVM::ReadCGNSZoneMetadata() { int ngrids; if (cg_ngrids(cgnsFileID, cgnsBase, cgnsZone, &ngrids)) cg_error_exit(); if (ngrids > 1) { - SU2_MPI::Error("CGNS reader currently handles only 1 grid per zone.", - CURRENT_FUNCTION); + SU2_MPI::Error("CGNS reader currently handles only 1 grid per zone.", CURRENT_FUNCTION); } - } void CCGNSMeshReaderFVM::ReadCGNSPointCoordinates() { - /*--- Compute the number of points that will be on each processor. This is a linear partitioning with the addition of a simple load balancing for any remainder points. ---*/ - CLinearPartitioner pointPartitioner(numberOfGlobalPoints,0); + CLinearPartitioner pointPartitioner(numberOfGlobalPoints, 0); /*--- Store the local number of nodes for this rank. ---*/ @@ -235,21 +219,19 @@ void CCGNSMeshReaderFVM::ReadCGNSPointCoordinates() { /*--- Create buffer to hold the grid coordinates for our rank. ---*/ localPointCoordinates.resize(dimension); - for (int k = 0; k < dimension; k++) - localPointCoordinates[k].resize(numberOfLocalPoints, 0.0); + for (int k = 0; k < dimension; k++) localPointCoordinates[k].resize(numberOfLocalPoints, 0.0); /*--- Set the value of range_max to the total number of nodes in the unstructured mesh. Also allocate memory for the temporary array that will hold the grid coordinates as they are extracted. Note the +1 for CGNS convention. ---*/ - cgsize_t range_min = (cgsize_t)pointPartitioner.GetFirstIndexOnRank(rank)+1; + cgsize_t range_min = (cgsize_t)pointPartitioner.GetFirstIndexOnRank(rank) + 1; cgsize_t range_max = (cgsize_t)pointPartitioner.GetLastIndexOnRank(rank); /*--- Loop over each set of coordinates. ---*/ for (int k = 0; k < dimension; k++) { - /*--- Read the coordinate info. This will retrieve the data type (either RealSingle or RealDouble) as well as the coordname which will specify the @@ -258,8 +240,7 @@ void CCGNSMeshReaderFVM::ReadCGNSPointCoordinates() { char coordname[CGNS_STRING_SIZE]; DataType_t datatype; - if (cg_coord_info(cgnsFileID, cgnsBase, cgnsZone, k+1, - &datatype, coordname)) cg_error_exit(); + if (cg_coord_info(cgnsFileID, cgnsBase, cgnsZone, k + 1, &datatype, coordname)) cg_error_exit(); if (rank == MASTER_NODE) { cout << "Loading " << coordname; if (size > SINGLE_NODE) { @@ -272,30 +253,29 @@ void CCGNSMeshReaderFVM::ReadCGNSPointCoordinates() { /*--- Check the coordinate name to decide the index for storage. ---*/ unsigned short indC = 0; - if (string(coordname) == "CoordinateX") indC = 0; - else if (string(coordname) == "CoordinateY") indC = 1; - else if (string(coordname) == "CoordinateZ") indC = 2; + if (string(coordname) == "CoordinateX") + indC = 0; + else if (string(coordname) == "CoordinateY") + indC = 1; + else if (string(coordname) == "CoordinateZ") + indC = 2; else - SU2_MPI::Error(string("Unknown coordinate name, ") + coordname + - string(", in the CGNS file."), CURRENT_FUNCTION); + SU2_MPI::Error(string("Unknown coordinate name, ") + coordname + string(", in the CGNS file."), CURRENT_FUNCTION); /*--- Now read our rank's chunk of coordinates from the file. Ask for datatype RealDouble and let CGNS library do the translation when RealSingle is found. ---*/ - if (cg_coord_read(cgnsFileID, cgnsBase, cgnsZone, coordname, RealDouble, - &range_min, &range_max, localPointCoordinates[indC].data())) + if (cg_coord_read(cgnsFileID, cgnsBase, cgnsZone, coordname, RealDouble, &range_min, &range_max, + localPointCoordinates[indC].data())) cg_error_exit(); } - } void CCGNSMeshReaderFVM::ReadCGNSSectionMetadata() { - /*--- Begin section for retrieving the connectivity info. ---*/ - if ((rank == MASTER_NODE) && (size > SINGLE_NODE)) - cout << "Distributing connectivity across all ranks." << endl; + if ((rank == MASTER_NODE) && (size > SINGLE_NODE)) cout << "Distributing connectivity across all ranks." << endl; /*--- First check the number of sections. ---*/ @@ -309,26 +289,26 @@ void CCGNSMeshReaderFVM::ReadCGNSSectionMetadata() { pieces of information describing each section. ---*/ isInterior.resize(nSections); - nElems.resize(nSections,0); - elemOffset.resize(nSections+1, 0); elemOffset[0] = 0; + nElems.resize(nSections, 0); + elemOffset.resize(nSections + 1, 0); + elemOffset[0] = 0; connElems.resize(nSections); sectionNames.resize(nSections, vector(CGNS_STRING_SIZE)); numberOfGlobalElements = 0; for (int s = 0; s < nSections; s++) { - /*--- Read the connectivity details for this section. ---*/ int nbndry, parent_flag, vtk_type; cgsize_t startE, endE, sizeNeeded; ElementType_t elemType; - if (cg_section_read(cgnsFileID, cgnsBase, cgnsZone, s+1, - sectionNames[s].data(), &elemType, &startE, &endE, - &nbndry, &parent_flag)) cg_error_exit(); + if (cg_section_read(cgnsFileID, cgnsBase, cgnsZone, s + 1, sectionNames[s].data(), &elemType, &startE, &endE, + &nbndry, &parent_flag)) + cg_error_exit(); /*--- Compute the total element count in this section (global). ---*/ - unsigned long element_count = (endE-startE+1); + unsigned long element_count = (endE - startE + 1); /* Get the details for the CGNS element type in this section. */ @@ -343,26 +323,23 @@ void CCGNSMeshReaderFVM::ReadCGNSSectionMetadata() { isInterior[s] = true; if (elemType == MIXED) { - /* For a mixed section, we check the type of the first element so that we can correctly label this section as an interior or boundary element section. Here, we also assume that a section can not hold both interior and boundary elements. First, get the size required to read a single element from the section. */ - if (cg_ElementPartialSize(cgnsFileID, cgnsBase, cgnsZone, s+1, startE, - startE, &sizeNeeded) != CG_OK) + if (cg_ElementPartialSize(cgnsFileID, cgnsBase, cgnsZone, s + 1, startE, startE, &sizeNeeded) != CG_OK) cg_error_exit(); /* A couple of auxiliary vectors for mixed element sections. */ vector connElemCGNS(sizeNeeded); - vector connOffsetCGNS(2,0); + vector connOffsetCGNS(2, 0); /* Retrieve the connectivity information for the first element. */ - if (cg_poly_elements_partial_read(cgnsFileID, cgnsBase, cgnsZone, s+1, - startE, startE, connElemCGNS.data(), + if (cg_poly_elements_partial_read(cgnsFileID, cgnsBase, cgnsZone, s + 1, startE, startE, connElemCGNS.data(), connOffsetCGNS.data(), NULL) != CG_OK) cg_error_exit(); @@ -370,39 +347,35 @@ void CCGNSMeshReaderFVM::ReadCGNSSectionMetadata() { information that we retrieved from the CGNS file. */ elemType = ElementType_t(connElemCGNS[0]); - } /* Check for 1D elements in 2D problems, or for 2D elements in 3D problems. If found, mark the section as a boundary section. */ - if ((dimension == 2) && - (elemType == BAR_2 || elemType == BAR_3)) isInterior[s] = false; - if ((dimension == 3) && - (elemType == TRI_3 || elemType == QUAD_4)) isInterior[s] = false; + if ((dimension == 2) && (elemType == BAR_2 || elemType == BAR_3)) isInterior[s] = false; + if ((dimension == 3) && (elemType == TRI_3 || elemType == QUAD_4)) isInterior[s] = false; /*--- Increment the global element offset for each section based on whether or not this is a surface or volume section. We also keep a running count of the total elements globally. ---*/ - elemOffset[s+1] = elemOffset[s]; - if (!isInterior[s]) elemOffset[s+1] += element_count; - else numberOfGlobalElements += element_count; + elemOffset[s + 1] = elemOffset[s]; + if (!isInterior[s]) + elemOffset[s + 1] += element_count; + else + numberOfGlobalElements += element_count; /*--- Print some information to the console. ---*/ if (rank == MASTER_NODE) { cout << "Section " << string(sectionNames[s].data()); cout << " contains " << element_count << " elements"; - cout << " of type " << elem_name << "." < elemTypes(nElems[val_section], 0); - vector nPoinPerElem(nElems[val_section],0); - vector elemGlobalID(nElems[val_section],0); + vector elemTypes(nElems[val_section], 0); + vector nPoinPerElem(nElems[val_section], 0); + vector elemGlobalID(nElems[val_section], 0); /*--- Determine the size of the vector needed to read the connectivity data from the CGNS file. Only call the CGNS API if we have a non-zero @@ -450,21 +423,20 @@ void CCGNSMeshReaderFVM::ReadCGNSVolumeSection(int val_section) { cgsize_t sizeNeeded = 0, sizeOffset = 0; if (nElems[val_section] > 0) { - if (cg_ElementPartialSize(cgnsFileID, cgnsBase, cgnsZone, val_section+1, + if (cg_ElementPartialSize(cgnsFileID, cgnsBase, cgnsZone, val_section + 1, (cgsize_t)elementPartitioner.GetFirstIndexOnRank(rank), - (cgsize_t)elementPartitioner.GetLastIndexOnRank(rank), - &sizeNeeded) != CG_OK) - cg_error_exit(); + (cgsize_t)elementPartitioner.GetLastIndexOnRank(rank), &sizeNeeded) != CG_OK) + cg_error_exit(); } /*--- Allocate the memory for the connectivity, the offset if needed and read the data. ---*/ - vector connElemCGNS(sizeNeeded,0); + vector connElemCGNS(sizeNeeded, 0); if (elemType == MIXED || elemType == NFACE_n || elemType == NGON_n) { - sizeOffset = nElems[val_section]+1; + sizeOffset = nElems[val_section] + 1; } - vector connOffsetCGNS(sizeOffset,0); + vector connOffsetCGNS(sizeOffset, 0); /*--- Retrieve the connectivity information and store. Note that we are only accessing our rank's piece of the data here in the @@ -473,18 +445,16 @@ void CCGNSMeshReaderFVM::ReadCGNSVolumeSection(int val_section) { if (nElems[val_section] > 0) { if (elemType == MIXED || elemType == NFACE_n || elemType == NGON_n) { - if (cg_poly_elements_partial_read(cgnsFileID, cgnsBase, cgnsZone, val_section+1, + if (cg_poly_elements_partial_read(cgnsFileID, cgnsBase, cgnsZone, val_section + 1, (cgsize_t)elementPartitioner.GetFirstIndexOnRank(rank), - (cgsize_t)elementPartitioner.GetLastIndexOnRank(rank), - connElemCGNS.data(), + (cgsize_t)elementPartitioner.GetLastIndexOnRank(rank), connElemCGNS.data(), connOffsetCGNS.data(), NULL) != CG_OK) - cg_error_exit(); + cg_error_exit(); } else { - if (cg_elements_partial_read(cgnsFileID, cgnsBase, cgnsZone, val_section+1, - (cgsize_t)elementPartitioner.GetFirstIndexOnRank(rank), - (cgsize_t)elementPartitioner.GetLastIndexOnRank(rank), - connElemCGNS.data(), NULL) != CG_OK) - cg_error_exit(); + if (cg_elements_partial_read( + cgnsFileID, cgnsBase, cgnsZone, val_section + 1, (cgsize_t)elementPartitioner.GetFirstIndexOnRank(rank), + (cgsize_t)elementPartitioner.GetLastIndexOnRank(rank), connElemCGNS.data(), NULL) != CG_OK) + cg_error_exit(); } } @@ -492,7 +462,7 @@ void CCGNSMeshReaderFVM::ReadCGNSVolumeSection(int val_section) { if (rank == MASTER_NODE) { cout << "Loading volume section " << string(sectionName); - cout << " from file." << endl; + cout << " from file." << endl; } /*--- Find the number of nodes required to represent @@ -514,7 +484,6 @@ void CCGNSMeshReaderFVM::ReadCGNSVolumeSection(int val_section) { unsigned long counterCGNS = 0; for (iElem = 0; iElem < nElems[val_section]; iElem++) { - ElementType_t iElemType = elemType; /*--- If we have a mixed element section, we need to check the elem @@ -523,7 +492,7 @@ void CCGNSMeshReaderFVM::ReadCGNSVolumeSection(int val_section) { if (isMixed) { iElemType = ElementType_t(connElemCGNS[counterCGNS]); - npe = connOffsetCGNS[iElem+1]-connOffsetCGNS[iElem]-1; + npe = connOffsetCGNS[iElem + 1] - connOffsetCGNS[iElem] - 1; counterCGNS++; for (int jj = 0; jj < npe; jj++) counterCGNS++; } @@ -538,15 +507,13 @@ void CCGNSMeshReaderFVM::ReadCGNSVolumeSection(int val_section) { prior to this one, in order to keep the internal element global IDs indexed starting from zero. ---*/ - elemGlobalID[iElem] = (elementPartitioner.GetFirstIndexOnRank(rank) + - iElem - elemOffset[val_section]); + elemGlobalID[iElem] = (elementPartitioner.GetFirstIndexOnRank(rank) + iElem - elemOffset[val_section]); /* Get the VTK type for this element. */ int vtk_type; string elem_name = GetCGNSElementType(iElemType, vtk_type); elemTypes[iElem] = vtk_type; - } /*--- Force free the memory for the conn offset from the CGNS file. ---*/ @@ -555,22 +522,23 @@ void CCGNSMeshReaderFVM::ReadCGNSVolumeSection(int val_section) { /*--- These are internal elems. Allocate memory on each proc. ---*/ - vector connElemTemp(nElems[val_section]*SU2_CONN_SIZE,0); + vector connElemTemp(nElems[val_section] * SU2_CONN_SIZE, 0); /*--- Copy the connectivity into the larger array with a standard format per element: [globalID vtkType n0 n1 n2 n3 n4 n5 n6 n7 n8]. ---*/ counterCGNS = 0; for (iElem = 0; iElem < nElems[val_section]; iElem++) { - /*--- Store the conn in chunks of SU2_CONN_SIZE for simplicity. ---*/ - unsigned long nn = iElem*SU2_CONN_SIZE; + unsigned long nn = iElem * SU2_CONN_SIZE; /*--- First, store the global element ID and the VTK type. ---*/ - connElemTemp[nn] = elemGlobalID[iElem]; nn++; - connElemTemp[nn] = elemTypes[iElem]; nn++; + connElemTemp[nn] = elemGlobalID[iElem]; + nn++; + connElemTemp[nn] = elemTypes[iElem]; + nn++; /*--- Store the connectivity values. Note we subtract one from the CGNS 1-based convention. We may also need to remove the first @@ -578,10 +546,10 @@ void CCGNSMeshReaderFVM::ReadCGNSVolumeSection(int val_section) { if (isMixed) counterCGNS++; for (iNode = 0; iNode < (unsigned long)nPoinPerElem[iElem]; iNode++) { - connElemTemp[nn] = connElemCGNS[counterCGNS + iNode] - 1; nn++; + connElemTemp[nn] = connElemCGNS[counterCGNS + iNode] - 1; + nn++; } counterCGNS += nPoinPerElem[iElem]; - } /*--- Force free the memory for the conn from the CGNS file. ---*/ @@ -595,28 +563,29 @@ void CCGNSMeshReaderFVM::ReadCGNSVolumeSection(int val_section) { will appear on multiple ranks). First, initialize a counter and flag. ---*/ - int *nElem_Send = new int[size+1]; nElem_Send[0] = 0; - int *nElem_Recv = new int[size+1]; nElem_Recv[0] = 0; - int *nElem_Flag = new int[size]; + int* nElem_Send = new int[size + 1]; + nElem_Send[0] = 0; + int* nElem_Recv = new int[size + 1]; + nElem_Recv[0] = 0; + int* nElem_Flag = new int[size]; for (iProcessor = 0; iProcessor < size; iProcessor++) { nElem_Send[iProcessor] = 0; nElem_Recv[iProcessor] = 0; - nElem_Flag[iProcessor]= -1; + nElem_Flag[iProcessor] = -1; } nElem_Send[size] = 0; nElem_Recv[size] = 0; /*--- Create a partitioner object to find the owning rank of points. ---*/ - CLinearPartitioner pointPartitioner(numberOfGlobalPoints,0); + CLinearPartitioner pointPartitioner(numberOfGlobalPoints, 0); for (iElem = 0; iElem < nElems[val_section]; iElem++) { for (iNode = 0; iNode < (unsigned long)nPoinPerElem[iElem]; iNode++) { - /*--- Get the index of the current point. ---*/ - iPoint = connElemTemp[iElem*SU2_CONN_SIZE + SU2_CONN_SKIP + iNode]; + iPoint = connElemTemp[iElem * SU2_CONN_SIZE + SU2_CONN_SKIP + iNode]; /*--- Search for the processor that owns this point. ---*/ @@ -627,9 +596,8 @@ void CCGNSMeshReaderFVM::ReadCGNSVolumeSection(int val_section) { if ((nElem_Flag[iProcessor] != (int)iElem)) { nElem_Flag[iProcessor] = iElem; - nElem_Send[iProcessor+1]++; + nElem_Send[iProcessor + 1]++; } - } } @@ -637,8 +605,7 @@ void CCGNSMeshReaderFVM::ReadCGNSVolumeSection(int val_section) { all processors. After this communication, each proc knows how many cells it will receive from each other processor. ---*/ - SU2_MPI::Alltoall(&(nElem_Send[1]), 1, MPI_INT, - &(nElem_Recv[1]), 1, MPI_INT, SU2_MPI::GetComm()); + SU2_MPI::Alltoall(&(nElem_Send[1]), 1, MPI_INT, &(nElem_Recv[1]), 1, MPI_INT, SU2_MPI::GetComm()); /*--- Prepare to send connectivities. First check how many messages we will be sending and receiving. Here we also put @@ -646,15 +613,14 @@ void CCGNSMeshReaderFVM::ReadCGNSVolumeSection(int val_section) { communications simpler. ---*/ unsigned long nSends = 0, nRecvs = 0; - for (iProcessor = 0; iProcessor < size; iProcessor++) - nElem_Flag[iProcessor] = -1; + for (iProcessor = 0; iProcessor < size; iProcessor++) nElem_Flag[iProcessor] = -1; for (iProcessor = 0; iProcessor < size; iProcessor++) { - if ((iProcessor != rank) && (nElem_Send[iProcessor+1] > 0)) nSends++; - if ((iProcessor != rank) && (nElem_Recv[iProcessor+1] > 0)) nRecvs++; + if ((iProcessor != rank) && (nElem_Send[iProcessor + 1] > 0)) nSends++; + if ((iProcessor != rank) && (nElem_Recv[iProcessor + 1] > 0)) nRecvs++; - nElem_Send[iProcessor+1] += nElem_Send[iProcessor]; - nElem_Recv[iProcessor+1] += nElem_Recv[iProcessor]; + nElem_Send[iProcessor + 1] += nElem_Send[iProcessor]; + nElem_Recv[iProcessor + 1] += nElem_Recv[iProcessor]; } /*--- Allocate memory to hold the connectivity that we are @@ -664,27 +630,24 @@ void CCGNSMeshReaderFVM::ReadCGNSVolumeSection(int val_section) { + 2 extra values for the ID and VTK. ---*/ unsigned long *connSend = NULL, iSend = 0; - unsigned long sendSize = (unsigned long)SU2_CONN_SIZE*nElem_Send[size]; + unsigned long sendSize = (unsigned long)SU2_CONN_SIZE * nElem_Send[size]; connSend = new unsigned long[sendSize]; - for (iSend = 0; iSend < sendSize; iSend++) - connSend[iSend] = 0; + for (iSend = 0; iSend < sendSize; iSend++) connSend[iSend] = 0; /*--- Create an index variable to keep track of our index position as we load up the send buffer. ---*/ vector index(size); - for (iProcessor = 0; iProcessor < size; iProcessor++) - index[iProcessor] = SU2_CONN_SIZE*nElem_Send[iProcessor]; + for (iProcessor = 0; iProcessor < size; iProcessor++) index[iProcessor] = SU2_CONN_SIZE * nElem_Send[iProcessor]; /*--- Loop through our elements and load the elems and their additional data that we will send to the other procs. ---*/ for (iElem = 0; iElem < (unsigned long)nElems[val_section]; iElem++) { for (iNode = 0; iNode < (unsigned long)nPoinPerElem[iElem]; iNode++) { - /*--- Get the index of the current point. ---*/ - iPoint = connElemTemp[iElem*SU2_CONN_SIZE + SU2_CONN_SKIP + iNode]; + iPoint = connElemTemp[iElem * SU2_CONN_SIZE + SU2_CONN_SKIP + iNode]; /*--- Search for the processor that owns this point ---*/ @@ -693,7 +656,6 @@ void CCGNSMeshReaderFVM::ReadCGNSVolumeSection(int val_section) { /*--- Load connectivity into the buffer for sending ---*/ if (nElem_Flag[iProcessor] != (int)iElem) { - nElem_Flag[iProcessor] = iElem; unsigned long nn = index[iProcessor]; @@ -701,15 +663,14 @@ void CCGNSMeshReaderFVM::ReadCGNSVolumeSection(int val_section) { then the connectivity vals, and last, the global ID. ---*/ for (jNode = 0; jNode < SU2_CONN_SIZE; jNode++) { - connSend[nn] = connElemTemp[iElem*SU2_CONN_SIZE + jNode]; nn++; + connSend[nn] = connElemTemp[iElem * SU2_CONN_SIZE + jNode]; + nn++; } /*--- Increment the index by the message length ---*/ index[iProcessor] += SU2_CONN_SIZE; - } - } } @@ -728,15 +689,14 @@ void CCGNSMeshReaderFVM::ReadCGNSVolumeSection(int val_section) { directly copy our own data later. ---*/ unsigned long *connRecv = NULL, iRecv = 0; - unsigned long recvSize = (unsigned long)SU2_CONN_SIZE*nElem_Recv[size]; + unsigned long recvSize = (unsigned long)SU2_CONN_SIZE * nElem_Recv[size]; connRecv = new unsigned long[recvSize]; - for (iRecv = 0; iRecv < recvSize; iRecv++) - connRecv[iRecv] = 0; + for (iRecv = 0; iRecv < recvSize; iRecv++) connRecv[iRecv] = 0; /*--- Allocate memory for the MPI requests if we will communicate. ---*/ - SU2_MPI::Request *connSendReq = NULL; - SU2_MPI::Request *connRecvReq = NULL; + SU2_MPI::Request* connSendReq = NULL; + SU2_MPI::Request* connRecvReq = NULL; if (nSends > 0) { connSendReq = new SU2_MPI::Request[nSends]; @@ -747,15 +707,14 @@ void CCGNSMeshReaderFVM::ReadCGNSVolumeSection(int val_section) { /*--- Launch the non-blocking sends and receives. ---*/ - InitiateCommsAll(connSend, nElem_Send, connSendReq, - connRecv, nElem_Recv, connRecvReq, - SU2_CONN_SIZE, COMM_TYPE_UNSIGNED_LONG); + InitiateCommsAll(connSend, nElem_Send, connSendReq, connRecv, nElem_Recv, connRecvReq, SU2_CONN_SIZE, + COMM_TYPE_UNSIGNED_LONG); /*--- Copy the current rank's data into the recv buffer directly. ---*/ - iRecv = SU2_CONN_SIZE*nElem_Recv[rank]; - unsigned long myStart = SU2_CONN_SIZE*nElem_Send[rank]; - unsigned long myFinal = SU2_CONN_SIZE*nElem_Send[rank+1]; + iRecv = SU2_CONN_SIZE * nElem_Recv[rank]; + unsigned long myStart = SU2_CONN_SIZE * nElem_Send[rank]; + unsigned long myFinal = SU2_CONN_SIZE * nElem_Send[rank + 1]; for (iSend = myStart; iSend < myFinal; iSend++) { connRecv[iRecv] = connSend[iSend]; iRecv++; @@ -770,11 +729,11 @@ void CCGNSMeshReaderFVM::ReadCGNSVolumeSection(int val_section) { for this section, then write the recv'd values. ---*/ if (nElem_Recv[size] > 0) { - connElems[val_section].resize(nElem_Recv[size]*SU2_CONN_SIZE,0); + connElems[val_section].resize(nElem_Recv[size] * SU2_CONN_SIZE, 0); unsigned long count = 0; for (iElem = 0; iElem < (unsigned long)nElem_Recv[size]; iElem++) { for (iNode = 0; iNode < SU2_CONN_SIZE; iNode++) { - unsigned long nn = iElem*SU2_CONN_SIZE+iNode; + unsigned long nn = iElem * SU2_CONN_SIZE + iNode; connElems[val_section][count] = (cgsize_t)connRecv[nn]; count++; } @@ -786,30 +745,26 @@ void CCGNSMeshReaderFVM::ReadCGNSVolumeSection(int val_section) { nElems[val_section] = nElem_Recv[size]; } else { - /*--- The current rank did not recv any elements from this section. Set the count to zero and nullify the data structure. ---*/ - nElems[val_section] = 0; + nElems[val_section] = 0; connElems[val_section].resize(0); - } /*--- Free temporary memory from communications ---*/ - if (connSendReq != NULL) delete [] connSendReq; - if (connRecvReq != NULL) delete [] connRecvReq; - - delete [] connSend; - delete [] connRecv; - delete [] nElem_Recv; - delete [] nElem_Send; - delete [] nElem_Flag; + if (connSendReq != NULL) delete[] connSendReq; + if (connRecvReq != NULL) delete[] connRecvReq; + delete[] connSend; + delete[] connRecv; + delete[] nElem_Recv; + delete[] nElem_Send; + delete[] nElem_Flag; } void CCGNSMeshReaderFVM::ReadCGNSSurfaceSection(int val_section) { - /*--- In this routine, we access a CGNS surface section and have the master rank load all of the surface conn. This can help avoid issues where there are fewer elements than ranks on a surface. This is later @@ -825,37 +780,33 @@ void CCGNSMeshReaderFVM::ReadCGNSSurfaceSection(int val_section) { char sectionName[CGNS_STRING_SIZE]; if (rank == MASTER_NODE) { - /*--- Allocate some memory for the handling the connectivity and auxiliary data that we are need to communicate. ---*/ - vector connElemCGNS(nElems[val_section]*SU2_CONN_SIZE,0); - vector elemTypes(nElems[val_section],0); - vector nPoinPerElem(nElems[val_section],0); - vector elemGlobalID(nElems[val_section],0); + vector connElemCGNS(nElems[val_section] * SU2_CONN_SIZE, 0); + vector elemTypes(nElems[val_section], 0); + vector nPoinPerElem(nElems[val_section], 0); + vector elemGlobalID(nElems[val_section], 0); /*--- Read the section info again ---*/ - if (cg_section_read(cgnsFileID, cgnsBase, cgnsZone, val_section+1, - sectionName, &elemType, &startE, &endE, &nbndry, - &parent_flag)) + if (cg_section_read(cgnsFileID, cgnsBase, cgnsZone, val_section + 1, sectionName, &elemType, &startE, &endE, + &nbndry, &parent_flag)) cg_error_exit(); /*--- Print some information to the console. ---*/ cout << "Loading surface section " << string(sectionName); - cout << " from file." << endl; + cout << " from file." << endl; /*--- Store the number of elems (all on the master). ---*/ - nElems[val_section] = (endE-startE+1); + nElems[val_section] = (endE - startE + 1); /*--- Read and store the total amount of data that will be listed when reading this section. ---*/ - if (cg_ElementDataSize(cgnsFileID, cgnsBase, cgnsZone, val_section+1, - &ElementDataSize)) - cg_error_exit(); + if (cg_ElementDataSize(cgnsFileID, cgnsBase, cgnsZone, val_section + 1, &ElementDataSize)) cg_error_exit(); /*--- Find the number of nodes required to represent this type of element. ---*/ @@ -874,31 +825,26 @@ void CCGNSMeshReaderFVM::ReadCGNSSurfaceSection(int val_section) { /*--- Allocate memory for accessing the connectivity and to store it in the proper data structure for post-processing. ---*/ - vector connElemTemp(ElementDataSize,0); + vector connElemTemp(ElementDataSize, 0); /*--- Retrieve the connectivity information and store. ---*/ if (elemType == MIXED || elemType == NGON_n || elemType == NFACE_n) { - vector connOffsetTemp(nElems[val_section]+1, 0); - if (cg_poly_elements_partial_read(cgnsFileID, cgnsBase, cgnsZone, - val_section+1, startE, endE, - connElemTemp.data(), - connOffsetTemp.data(), NULL) != CG_OK) + vector connOffsetTemp(nElems[val_section] + 1, 0); + if (cg_poly_elements_partial_read(cgnsFileID, cgnsBase, cgnsZone, val_section + 1, startE, endE, + connElemTemp.data(), connOffsetTemp.data(), NULL) != CG_OK) cg_error_exit(); } else { - if (cg_elements_read(cgnsFileID, cgnsBase, cgnsZone, val_section+1, - connElemTemp.data(), NULL)) - cg_error_exit(); + if (cg_elements_read(cgnsFileID, cgnsBase, cgnsZone, val_section + 1, connElemTemp.data(), NULL)) cg_error_exit(); } /*--- Allocate the memory for the data structure used to carry the connectivity for this section. ---*/ - connElems[val_section].resize(nElems[val_section]*SU2_CONN_SIZE,0); + connElems[val_section].resize(nElems[val_section] * SU2_CONN_SIZE, 0); unsigned long counterCGNS = 0; for (iElem = 0; iElem < nElems[val_section]; iElem++) { - ElementType_t iElemType = elemType; /*--- If we have a mixed element section, we need to check the elem @@ -925,29 +871,24 @@ void CCGNSMeshReaderFVM::ReadCGNSSurfaceSection(int val_section) { format as the interior elements. Note that we subtract 1 to move from the CGNS 1-based indexing to SU2's zero-based. ---*/ - connElems[val_section][iElem*SU2_CONN_SIZE+0] = 0; - connElems[val_section][iElem*SU2_CONN_SIZE+1] = vtk_type; + connElems[val_section][iElem * SU2_CONN_SIZE + 0] = 0; + connElems[val_section][iElem * SU2_CONN_SIZE + 1] = vtk_type; for (iNode = 0; iNode < (unsigned long)npe; iNode++) { - unsigned long nn = iElem*SU2_CONN_SIZE+SU2_CONN_SKIP+iNode; + unsigned long nn = iElem * SU2_CONN_SIZE + SU2_CONN_SKIP + iNode; connElems[val_section][nn] = connElemTemp[counterCGNS] - 1; counterCGNS++; } - } } else { - /*--- We are not the master, so we resize to zero for safety. ---*/ nElems[val_section] = 0; connElems[val_section].resize(0); - } - } void CCGNSMeshReaderFVM::ReformatCGNSVolumeConnectivity() { - /*--- Loop to store total number of elements we have locally. This number includes repeats across ranks due to redistribution according to the linear partitioning of the grid nodes. ---*/ @@ -958,13 +899,13 @@ void CCGNSMeshReaderFVM::ReformatCGNSVolumeConnectivity() { /* Put our CGNS data into the class data structures for the mesh reader */ - localVolumeElementConnectivity.resize(numberOfLocalElements*SU2_CONN_SIZE); + localVolumeElementConnectivity.resize(numberOfLocalElements * SU2_CONN_SIZE); unsigned long count = 0; for (int s = 0; s < nSections; s++) { if (isInterior[s]) { for (unsigned long iElem = 0; iElem < nElems[s]; iElem++) { for (unsigned long iNode = 0; iNode < SU2_CONN_SIZE; iNode++) { - unsigned long nn = iElem*SU2_CONN_SIZE+iNode; + unsigned long nn = iElem * SU2_CONN_SIZE + iNode; localVolumeElementConnectivity[count] = (unsigned long)connElems[s][nn]; count++; } @@ -972,37 +913,33 @@ void CCGNSMeshReaderFVM::ReformatCGNSVolumeConnectivity() { vector().swap(connElems[s]); } } - } void CCGNSMeshReaderFVM::ReformatCGNSSurfaceConnectivity() { - /*--- Prepare the class data for the marker names and connectivity. ---*/ markerNames.resize(numberOfMarkers); surfaceElementConnectivity.resize(numberOfMarkers); - int markerCount = 0; + int markerCount = 0; int elementCount = 0; for (int s = 0; s < nSections; s++) { if (!isInterior[s]) { - /*--- Store the tag for this marker. Remove any whitespaces from the marker names found in the CGNS file to avoid any issues. ---*/ string Marker_Tag = string(sectionNames[s].data()); - Marker_Tag.erase(remove(Marker_Tag.begin(), Marker_Tag.end(),' '), - Marker_Tag.end()); + Marker_Tag.erase(remove(Marker_Tag.begin(), Marker_Tag.end(), ' '), Marker_Tag.end()); markerNames[markerCount] = Marker_Tag; /*--- The master node alone stores the connectivity. ---*/ if (rank == MASTER_NODE) { - surfaceElementConnectivity[markerCount].resize(nElems[s]*SU2_CONN_SIZE); + surfaceElementConnectivity[markerCount].resize(nElems[s] * SU2_CONN_SIZE); elementCount = 0; for (unsigned long iElem = 0; iElem < nElems[s]; iElem++) { for (unsigned long iNode = 0; iNode < SU2_CONN_SIZE; iNode++) { - unsigned long nn = iElem*SU2_CONN_SIZE+iNode; + unsigned long nn = iElem * SU2_CONN_SIZE + iNode; surfaceElementConnectivity[markerCount][elementCount] = (unsigned long)connElems[s][nn]; elementCount++; } @@ -1012,87 +949,71 @@ void CCGNSMeshReaderFVM::ReformatCGNSSurfaceConnectivity() { markerCount++; } } - } -string CCGNSMeshReaderFVM::GetCGNSElementType(ElementType_t val_elem_type, - int &val_vtk_type) { - +string CCGNSMeshReaderFVM::GetCGNSElementType(ElementType_t val_elem_type, int& val_vtk_type) { /* Check the CGNS element type and return the string name for the element and the associated VTK type index. */ string elem_name; switch (val_elem_type) { case NODE: - elem_name = "Vertex"; - val_vtk_type = 1; - SU2_MPI::Error("Vertex elements detected. Please remove.", - CURRENT_FUNCTION); + elem_name = "Vertex"; + val_vtk_type = 1; + SU2_MPI::Error("Vertex elements detected. Please remove.", CURRENT_FUNCTION); break; case BAR_2: - elem_name = "Line"; - val_vtk_type = 3; - if (dimension == 3) - SU2_MPI::Error("Line elements detected in a 3D mesh. Please remove.", - CURRENT_FUNCTION); + elem_name = "Line"; + val_vtk_type = 3; + if (dimension == 3) SU2_MPI::Error("Line elements detected in a 3D mesh. Please remove.", CURRENT_FUNCTION); break; case BAR_3: - elem_name = "Line"; - val_vtk_type = 3; - if (dimension == 3) - SU2_MPI::Error("Line elements detected in a 3D mesh. Please remove.", - CURRENT_FUNCTION); + elem_name = "Line"; + val_vtk_type = 3; + if (dimension == 3) SU2_MPI::Error("Line elements detected in a 3D mesh. Please remove.", CURRENT_FUNCTION); break; case TRI_3: - elem_name = "Triangle"; - val_vtk_type = 5; + elem_name = "Triangle"; + val_vtk_type = 5; break; case QUAD_4: - elem_name = "Quadrilateral"; - val_vtk_type = 9; + elem_name = "Quadrilateral"; + val_vtk_type = 9; break; case TETRA_4: - elem_name = "Tetrahedron"; - val_vtk_type = 10; + elem_name = "Tetrahedron"; + val_vtk_type = 10; break; case HEXA_8: - elem_name = "Hexahedron"; - val_vtk_type = 12; + elem_name = "Hexahedron"; + val_vtk_type = 12; break; case PENTA_6: - elem_name = "Prism"; - val_vtk_type = 13; + elem_name = "Prism"; + val_vtk_type = 13; break; case PYRA_5: - elem_name = "Pyramid"; - val_vtk_type = 14; + elem_name = "Pyramid"; + val_vtk_type = 14; break; case MIXED: - elem_name = "Mixed"; - val_vtk_type = -1; + elem_name = "Mixed"; + val_vtk_type = -1; break; default: char buf[100]; - SPRINTF(buf, "Unsupported or unknown CGNS element type: (type %d)\n", - val_elem_type); + SPRINTF(buf, "Unsupported or unknown CGNS element type: (type %d)\n", val_elem_type); SU2_MPI::Error(string(buf), CURRENT_FUNCTION); break; } return elem_name; - } #endif -void CCGNSMeshReaderFVM::InitiateCommsAll(void *bufSend, - const int *nElemSend, - SU2_MPI::Request *sendReq, - void *bufRecv, - const int *nElemRecv, - SU2_MPI::Request *recvReq, - unsigned short countPerElem, +void CCGNSMeshReaderFVM::InitiateCommsAll(void* bufSend, const int* nElemSend, SU2_MPI::Request* sendReq, void* bufRecv, + const int* nElemRecv, SU2_MPI::Request* recvReq, unsigned short countPerElem, unsigned short commType) { - /*--- Local variables ---*/ int iMessage, iProc, offset, nElem, count, source, dest, tag; @@ -1101,64 +1022,56 @@ void CCGNSMeshReaderFVM::InitiateCommsAll(void *bufSend, iMessage = 0; for (iProc = 0; iProc < size; iProc++) { - /*--- Post recv's only if another proc is sending us data. We do not communicate with ourselves or post recv's for zero length messages to keep overhead down. ---*/ - if ((nElemRecv[iProc+1] > nElemRecv[iProc]) && (iProc != rank)) { - + if ((nElemRecv[iProc + 1] > nElemRecv[iProc]) && (iProc != rank)) { /*--- Compute our location in the recv buffer. ---*/ - offset = countPerElem*nElemRecv[iProc]; + offset = countPerElem * nElemRecv[iProc]; /*--- Take advantage of cumulative storage format to get the number of elems that we need to recv. ---*/ - nElem = nElemRecv[iProc+1] - nElemRecv[iProc]; + nElem = nElemRecv[iProc + 1] - nElemRecv[iProc]; /*--- Total count can include multiple pieces of data per element. ---*/ - count = countPerElem*nElem; + count = countPerElem * nElem; /*--- Post non-blocking recv for this proc. ---*/ - source = iProc; tag = iProc + 1; + source = iProc; + tag = iProc + 1; switch (commType) { case COMM_TYPE_DOUBLE: - SU2_MPI::Irecv(&(static_cast(bufRecv)[offset]), - count, MPI_DOUBLE, source, tag, SU2_MPI::GetComm(), - &(recvReq[iMessage])); + SU2_MPI::Irecv(&(static_cast(bufRecv)[offset]), count, MPI_DOUBLE, source, tag, + SU2_MPI::GetComm(), &(recvReq[iMessage])); break; case COMM_TYPE_UNSIGNED_LONG: - SU2_MPI::Irecv(&(static_cast(bufRecv)[offset]), - count, MPI_UNSIGNED_LONG, source, tag, SU2_MPI::GetComm(), - &(recvReq[iMessage])); + SU2_MPI::Irecv(&(static_cast(bufRecv)[offset]), count, MPI_UNSIGNED_LONG, source, tag, + SU2_MPI::GetComm(), &(recvReq[iMessage])); break; case COMM_TYPE_LONG: - SU2_MPI::Irecv(&(static_cast(bufRecv)[offset]), - count, MPI_LONG, source, tag, SU2_MPI::GetComm(), + SU2_MPI::Irecv(&(static_cast(bufRecv)[offset]), count, MPI_LONG, source, tag, SU2_MPI::GetComm(), &(recvReq[iMessage])); break; case COMM_TYPE_UNSIGNED_SHORT: - SU2_MPI::Irecv(&(static_cast(bufRecv)[offset]), - count, MPI_UNSIGNED_SHORT, source, tag, SU2_MPI::GetComm(), - &(recvReq[iMessage])); + SU2_MPI::Irecv(&(static_cast(bufRecv)[offset]), count, MPI_UNSIGNED_SHORT, source, tag, + SU2_MPI::GetComm(), &(recvReq[iMessage])); break; case COMM_TYPE_CHAR: - SU2_MPI::Irecv(&(static_cast(bufRecv)[offset]), - count, MPI_CHAR, source, tag, SU2_MPI::GetComm(), + SU2_MPI::Irecv(&(static_cast(bufRecv)[offset]), count, MPI_CHAR, source, tag, SU2_MPI::GetComm(), &(recvReq[iMessage])); break; case COMM_TYPE_SHORT: - SU2_MPI::Irecv(&(static_cast(bufRecv)[offset]), - count, MPI_SHORT, source, tag, SU2_MPI::GetComm(), + SU2_MPI::Irecv(&(static_cast(bufRecv)[offset]), count, MPI_SHORT, source, tag, SU2_MPI::GetComm(), &(recvReq[iMessage])); break; case COMM_TYPE_INT: - SU2_MPI::Irecv(&(static_cast(bufRecv)[offset]), - count, MPI_INT, source, tag, SU2_MPI::GetComm(), + SU2_MPI::Irecv(&(static_cast(bufRecv)[offset]), count, MPI_INT, source, tag, SU2_MPI::GetComm(), &(recvReq[iMessage])); break; default: @@ -1168,7 +1081,6 @@ void CCGNSMeshReaderFVM::InitiateCommsAll(void *bufSend, /*--- Increment message counter. ---*/ iMessage++; - } } @@ -1176,64 +1088,56 @@ void CCGNSMeshReaderFVM::InitiateCommsAll(void *bufSend, iMessage = 0; for (iProc = 0; iProc < size; iProc++) { - /*--- Post sends only if we are sending another proc data. We do not communicate with ourselves or post sends for zero length messages to keep overhead down. ---*/ - if ((nElemSend[iProc+1] > nElemSend[iProc]) && (iProc != rank)) { - + if ((nElemSend[iProc + 1] > nElemSend[iProc]) && (iProc != rank)) { /*--- Compute our location in the send buffer. ---*/ - offset = countPerElem*nElemSend[iProc]; + offset = countPerElem * nElemSend[iProc]; /*--- Take advantage of cumulative storage format to get the number of elems that we need to send. ---*/ - nElem = nElemSend[iProc+1] - nElemSend[iProc]; + nElem = nElemSend[iProc + 1] - nElemSend[iProc]; /*--- Total count can include multiple pieces of data per element. ---*/ - count = countPerElem*nElem; + count = countPerElem * nElem; /*--- Post non-blocking send for this proc. ---*/ - dest = iProc; tag = rank + 1; + dest = iProc; + tag = rank + 1; switch (commType) { case COMM_TYPE_DOUBLE: - SU2_MPI::Isend(&(static_cast(bufSend)[offset]), - count, MPI_DOUBLE, dest, tag, SU2_MPI::GetComm(), + SU2_MPI::Isend(&(static_cast(bufSend)[offset]), count, MPI_DOUBLE, dest, tag, SU2_MPI::GetComm(), &(sendReq[iMessage])); break; case COMM_TYPE_UNSIGNED_LONG: - SU2_MPI::Isend(&(static_cast(bufSend)[offset]), - count, MPI_UNSIGNED_LONG, dest, tag, SU2_MPI::GetComm(), - &(sendReq[iMessage])); + SU2_MPI::Isend(&(static_cast(bufSend)[offset]), count, MPI_UNSIGNED_LONG, dest, tag, + SU2_MPI::GetComm(), &(sendReq[iMessage])); break; case COMM_TYPE_LONG: - SU2_MPI::Isend(&(static_cast(bufSend)[offset]), - count, MPI_LONG, dest, tag, SU2_MPI::GetComm(), + SU2_MPI::Isend(&(static_cast(bufSend)[offset]), count, MPI_LONG, dest, tag, SU2_MPI::GetComm(), &(sendReq[iMessage])); break; case COMM_TYPE_UNSIGNED_SHORT: - SU2_MPI::Isend(&(static_cast(bufSend)[offset]), - count, MPI_UNSIGNED_SHORT, dest, tag, SU2_MPI::GetComm(), - &(sendReq[iMessage])); + SU2_MPI::Isend(&(static_cast(bufSend)[offset]), count, MPI_UNSIGNED_SHORT, dest, tag, + SU2_MPI::GetComm(), &(sendReq[iMessage])); break; case COMM_TYPE_CHAR: - SU2_MPI::Isend(&(static_cast(bufSend)[offset]), - count, MPI_CHAR, dest, tag, SU2_MPI::GetComm(), + SU2_MPI::Isend(&(static_cast(bufSend)[offset]), count, MPI_CHAR, dest, tag, SU2_MPI::GetComm(), &(sendReq[iMessage])); break; case COMM_TYPE_SHORT: - SU2_MPI::Isend(&(static_cast(bufSend)[offset]), - count, MPI_SHORT, dest, tag, SU2_MPI::GetComm(), + SU2_MPI::Isend(&(static_cast(bufSend)[offset]), count, MPI_SHORT, dest, tag, SU2_MPI::GetComm(), &(sendReq[iMessage])); break; case COMM_TYPE_INT: - SU2_MPI::Isend(&(static_cast(bufSend)[offset]), - count, MPI_INT, dest, tag, SU2_MPI::GetComm(), + SU2_MPI::Isend(&(static_cast(bufSend)[offset]), count, MPI_INT, dest, tag, SU2_MPI::GetComm(), &(sendReq[iMessage])); break; default: @@ -1243,17 +1147,12 @@ void CCGNSMeshReaderFVM::InitiateCommsAll(void *bufSend, /*--- Increment message counter. ---*/ iMessage++; - } } - } -void CCGNSMeshReaderFVM::CompleteCommsAll(int nSends, - SU2_MPI::Request *sendReq, - int nRecvs, - SU2_MPI::Request *recvReq) { - +void CCGNSMeshReaderFVM::CompleteCommsAll(int nSends, SU2_MPI::Request* sendReq, int nRecvs, + SU2_MPI::Request* recvReq) { /*--- Local variables ---*/ int ind, iSend, iRecv; @@ -1261,12 +1160,9 @@ void CCGNSMeshReaderFVM::CompleteCommsAll(int nSends, /*--- Wait for the non-blocking sends to complete. ---*/ - for (iSend = 0; iSend < nSends; iSend++) - SU2_MPI::Waitany(nSends, sendReq, &ind, &status); + for (iSend = 0; iSend < nSends; iSend++) SU2_MPI::Waitany(nSends, sendReq, &ind, &status); /*--- Wait for the non-blocking recvs to complete. ---*/ - for (iRecv = 0; iRecv < nRecvs; iRecv++) - SU2_MPI::Waitany(nRecvs, recvReq, &ind, &status); - + for (iRecv = 0; iRecv < nRecvs; iRecv++) SU2_MPI::Waitany(nRecvs, recvReq, &ind, &status); } diff --git a/Common/src/geometry/meshreader/CMeshReaderFVM.cpp b/Common/src/geometry/meshreader/CMeshReaderFVM.cpp index dde520aa244..23a23db1d87 100644 --- a/Common/src/geometry/meshreader/CMeshReaderFVM.cpp +++ b/Common/src/geometry/meshreader/CMeshReaderFVM.cpp @@ -28,10 +28,5 @@ #include "../../../include/geometry/meshreader/CMeshReaderFVM.hpp" -CMeshReaderFVM::CMeshReaderFVM(const CConfig *val_config, - unsigned short val_iZone, - unsigned short val_nZone) : - rank(SU2_MPI::GetRank()), - size(SU2_MPI::GetSize()), - config(val_config) { -} +CMeshReaderFVM::CMeshReaderFVM(const CConfig* val_config, unsigned short val_iZone, unsigned short val_nZone) + : rank(SU2_MPI::GetRank()), size(SU2_MPI::GetSize()), config(val_config) {} diff --git a/Common/src/geometry/meshreader/CRectangularMeshReaderFVM.cpp b/Common/src/geometry/meshreader/CRectangularMeshReaderFVM.cpp index e4dd6c48a26..5b312489b74 100644 --- a/Common/src/geometry/meshreader/CRectangularMeshReaderFVM.cpp +++ b/Common/src/geometry/meshreader/CRectangularMeshReaderFVM.cpp @@ -29,16 +29,14 @@ #include "../../../include/toolboxes/CLinearPartitioner.hpp" #include "../../../include/geometry/meshreader/CRectangularMeshReaderFVM.hpp" -CRectangularMeshReaderFVM::CRectangularMeshReaderFVM(const CConfig *val_config, - unsigned short val_iZone, +CRectangularMeshReaderFVM::CRectangularMeshReaderFVM(const CConfig* val_config, unsigned short val_iZone, unsigned short val_nZone) -: CMeshReaderFVM(val_config, val_iZone, val_nZone) { - + : CMeshReaderFVM(val_config, val_iZone, val_nZone) { /* The rectangular mesh is always 2D. */ dimension = 2; /* Set the VTK type for the interior elements and the boundary elements. */ - KindElem = QUADRILATERAL; + KindElem = QUADRILATERAL; KindBound = LINE; /* The number of nodes in the i and j directions. */ @@ -61,19 +59,17 @@ CRectangularMeshReaderFVM::CRectangularMeshReaderFVM(const CConfig *val_config, ComputeRectangularPointCoordinates(); ComputeRectangularVolumeConnectivity(); ComputeRectangularSurfaceConnectivity(); - } void CRectangularMeshReaderFVM::ComputeRectangularPointCoordinates() { - /* Set the global count of points based on the grid dimensions. */ - numberOfGlobalPoints = (nNode)*(mNode); + numberOfGlobalPoints = (nNode) * (mNode); /* Get a partitioner to help with linear partitioning. */ - CLinearPartitioner pointPartitioner(numberOfGlobalPoints,0); + CLinearPartitioner pointPartitioner(numberOfGlobalPoints, 0); /* Determine number of local points */ - for(unsigned long globalIndex=0; globalIndex < numberOfGlobalPoints; globalIndex++) { + for (unsigned long globalIndex = 0; globalIndex < numberOfGlobalPoints; globalIndex++) { if ((int)pointPartitioner.GetRankContainingIndex(globalIndex) == rank) { numberOfLocalPoints++; } @@ -82,16 +78,14 @@ void CRectangularMeshReaderFVM::ComputeRectangularPointCoordinates() { /* Loop over our analytically defined of coordinates and store only those that contain a node within our linear partition of points. */ localPointCoordinates.resize(dimension); - for (int k = 0; k < dimension; k++) - localPointCoordinates[k].reserve(numberOfLocalPoints); + for (int k = 0; k < dimension; k++) localPointCoordinates[k].reserve(numberOfLocalPoints); unsigned long globalIndex = 0; for (unsigned long jNode = 0; jNode < mNode; jNode++) { for (unsigned long iNode = 0; iNode < nNode; iNode++) { if ((int)pointPartitioner.GetRankContainingIndex(globalIndex) == rank) { - /* Store the coordinates more clearly. */ - const passivedouble x = SU2_TYPE::GetValue(Lx*((su2double)iNode)/((su2double)(nNode-1))+Ox); - const passivedouble y = SU2_TYPE::GetValue(Ly*((su2double)jNode)/((su2double)(mNode-1))+Oy); + const passivedouble x = SU2_TYPE::GetValue(Lx * ((su2double)iNode) / ((su2double)(nNode - 1)) + Ox); + const passivedouble y = SU2_TYPE::GetValue(Ly * ((su2double)jNode) / ((su2double)(mNode - 1)) + Oy); /* Load into the coordinate class data structure. */ localPointCoordinates[0].push_back(x); @@ -100,30 +94,27 @@ void CRectangularMeshReaderFVM::ComputeRectangularPointCoordinates() { globalIndex++; } } - } void CRectangularMeshReaderFVM::ComputeRectangularVolumeConnectivity() { - /* Set the global count of elements based on the grid dimensions. */ - numberOfGlobalElements = (nNode-1)*(mNode-1); + numberOfGlobalElements = (nNode - 1) * (mNode - 1); /* Get a partitioner to help with linear partitioning. */ - CLinearPartitioner pointPartitioner(numberOfGlobalPoints,0); + CLinearPartitioner pointPartitioner(numberOfGlobalPoints, 0); /* Loop over our analytically defined of elements and store only those that contain a node within our linear partition of points. */ - numberOfLocalElements = 0; - vector connectivity(N_POINTS_HEXAHEDRON,0); + numberOfLocalElements = 0; + vector connectivity(N_POINTS_HEXAHEDRON, 0); unsigned long globalIndex = 0; - for (unsigned long jNode = 0; jNode < mNode-1; jNode++) { - for (unsigned long iNode = 0; iNode < nNode-1; iNode++) { - + for (unsigned long jNode = 0; jNode < mNode - 1; jNode++) { + for (unsigned long iNode = 0; iNode < nNode - 1; iNode++) { /* Compute connectivity based on the i,j index. */ - connectivity[0] = jNode*nNode + iNode; - connectivity[1] = jNode*nNode + iNode + 1; - connectivity[2] = (jNode + 1)*nNode + (iNode + 1); - connectivity[3] = (jNode + 1)*nNode + iNode; + connectivity[0] = jNode * nNode + iNode; + connectivity[1] = jNode * nNode + iNode + 1; + connectivity[2] = (jNode + 1) * nNode + (iNode + 1); + connectivity[3] = (jNode + 1) * nNode + iNode; /* Check whether any of the points is in our linear partition. */ bool isOwned = false; @@ -145,11 +136,9 @@ void CRectangularMeshReaderFVM::ComputeRectangularVolumeConnectivity() { globalIndex++; } } - } void CRectangularMeshReaderFVM::ComputeRectangularSurfaceConnectivity() { - /* The rectangle alays has 4 markers. */ numberOfMarkers = 4; surfaceElementConnectivity.resize(numberOfMarkers); @@ -158,49 +147,45 @@ void CRectangularMeshReaderFVM::ComputeRectangularSurfaceConnectivity() { /* Compute and store the 4 sets of connectivity. */ markerNames[0] = "y_minus"; if (rank == MASTER_NODE) { - for (unsigned long iNode = 0; iNode < nNode-1; iNode++) { + for (unsigned long iNode = 0; iNode < nNode - 1; iNode++) { surfaceElementConnectivity[0].push_back(0); surfaceElementConnectivity[0].push_back(KindBound); surfaceElementConnectivity[0].push_back(iNode); surfaceElementConnectivity[0].push_back(iNode + 1); - for (unsigned short i = 0; i < 6; i++) - surfaceElementConnectivity[0].push_back(0); + for (unsigned short i = 0; i < 6; i++) surfaceElementConnectivity[0].push_back(0); } } markerNames[1] = "x_plus"; if (rank == MASTER_NODE) { - for (unsigned long jNode = 0; jNode < mNode-1; jNode++) { + for (unsigned long jNode = 0; jNode < mNode - 1; jNode++) { surfaceElementConnectivity[1].push_back(0); surfaceElementConnectivity[1].push_back(KindBound); - surfaceElementConnectivity[1].push_back(jNode*nNode + (nNode - 1)); - surfaceElementConnectivity[1].push_back((jNode + 1)*nNode + (nNode - 1)); - for (unsigned short i = 0; i < 6; i++) - surfaceElementConnectivity[1].push_back(0); + surfaceElementConnectivity[1].push_back(jNode * nNode + (nNode - 1)); + surfaceElementConnectivity[1].push_back((jNode + 1) * nNode + (nNode - 1)); + for (unsigned short i = 0; i < 6; i++) surfaceElementConnectivity[1].push_back(0); } } markerNames[2] = "y_plus"; if (rank == MASTER_NODE) { - for (unsigned long iNode = 0; iNode < nNode-1; iNode++) { + for (unsigned long iNode = 0; iNode < nNode - 1; iNode++) { surfaceElementConnectivity[2].push_back(0); surfaceElementConnectivity[2].push_back(KindBound); - surfaceElementConnectivity[2].push_back((nNode*mNode - 1) - iNode); - surfaceElementConnectivity[2].push_back((nNode*mNode - 1) - (iNode + 1)); - for (unsigned short i = 0; i < 6; i++) - surfaceElementConnectivity[2].push_back(0); + surfaceElementConnectivity[2].push_back((nNode * mNode - 1) - iNode); + surfaceElementConnectivity[2].push_back((nNode * mNode - 1) - (iNode + 1)); + for (unsigned short i = 0; i < 6; i++) surfaceElementConnectivity[2].push_back(0); } } markerNames[3] = "x_minus"; if (rank == MASTER_NODE) { - for (unsigned long jNode = 0; jNode < mNode-1; jNode++) { + for (unsigned long jNode = 0; jNode < mNode - 1; jNode++) { surfaceElementConnectivity[3].push_back(0); surfaceElementConnectivity[3].push_back(KindBound); - surfaceElementConnectivity[3].push_back((jNode + 1)*nNode); - surfaceElementConnectivity[3].push_back(jNode*nNode); - for (unsigned short i = 0; i < 6; i++) - surfaceElementConnectivity[3].push_back(0); + surfaceElementConnectivity[3].push_back((jNode + 1) * nNode); + surfaceElementConnectivity[3].push_back(jNode * nNode); + for (unsigned short i = 0; i < 6; i++) surfaceElementConnectivity[3].push_back(0); } } } diff --git a/Common/src/geometry/meshreader/CSU2ASCIIMeshReaderFVM.cpp b/Common/src/geometry/meshreader/CSU2ASCIIMeshReaderFVM.cpp index 92e63d0623d..272dafd79ed 100644 --- a/Common/src/geometry/meshreader/CSU2ASCIIMeshReaderFVM.cpp +++ b/Common/src/geometry/meshreader/CSU2ASCIIMeshReaderFVM.cpp @@ -29,19 +29,14 @@ #include "../../../include/toolboxes/CLinearPartitioner.hpp" #include "../../../include/geometry/meshreader/CSU2ASCIIMeshReaderFVM.hpp" -CSU2ASCIIMeshReaderFVM::CSU2ASCIIMeshReaderFVM(CConfig *val_config, - unsigned short val_iZone, - unsigned short val_nZone) -: CMeshReaderFVM(val_config, val_iZone, val_nZone), - myZone(val_iZone), - nZones(val_nZone), - meshFilename(config->GetMesh_FileName()) { - - actuator_disk = (((config->GetnMarker_ActDiskInlet() != 0) || - (config->GetnMarker_ActDiskOutlet() != 0)) && - ((config->GetKind_SU2() == SU2_COMPONENT::SU2_CFD) || - ((config->GetKind_SU2() == SU2_COMPONENT::SU2_DEF) && - (config->GetActDisk_SU2_DEF())))); +CSU2ASCIIMeshReaderFVM::CSU2ASCIIMeshReaderFVM(CConfig* val_config, unsigned short val_iZone, unsigned short val_nZone) + : CMeshReaderFVM(val_config, val_iZone, val_nZone), + myZone(val_iZone), + nZones(val_nZone), + meshFilename(config->GetMesh_FileName()) { + actuator_disk = (((config->GetnMarker_ActDiskInlet() != 0) || (config->GetnMarker_ActDiskOutlet() != 0)) && + ((config->GetKind_SU2() == SU2_COMPONENT::SU2_CFD) || + ((config->GetKind_SU2() == SU2_COMPONENT::SU2_DEF) && (config->GetActDisk_SU2_DEF())))); if (config->GetActDisk_DoubleSurface()) actuator_disk = false; /* Read the basic metadata and perform some basic error checks. */ @@ -55,8 +50,7 @@ CSU2ASCIIMeshReaderFVM::CSU2ASCIIMeshReaderFVM(CConfig *val_config, /* If the mesh contains an actuator disk as a single surface, we need to first split the surface into repeated points and update the connectivity for each element touching the surface. */ - if (actuator_disk) - SplitActuatorDiskSurface(); + if (actuator_disk) SplitActuatorDiskSurface(); /* Read and store the points, interior elements, and surface elements. We store only the points and interior elements on our rank's linear @@ -67,22 +61,21 @@ CSU2ASCIIMeshReaderFVM::CSU2ASCIIMeshReaderFVM(CConfig *val_config, for (auto section : SectionOrder) { switch (section) { - case FileSection::ELEMENTS: - ReadVolumeElementConnectivity(); - break; - case FileSection::POINTS: - ReadPointCoordinates(); - break; - case FileSection::MARKERS: - ReadSurfaceElementConnectivity(); - break; + case FileSection::ELEMENTS: + ReadVolumeElementConnectivity(); + break; + case FileSection::POINTS: + ReadPointCoordinates(); + break; + case FileSection::MARKERS: + ReadSurfaceElementConnectivity(); + break; } } mesh_file.close(); } -bool CSU2ASCIIMeshReaderFVM::ReadMetadata(const bool single_pass, CConfig *config) { - +bool CSU2ASCIIMeshReaderFVM::ReadMetadata(const bool single_pass, CConfig* config) { const bool harmonic_balance = config->GetTime_Marching() == TIME_MARCHING::HARMONIC_BALANCE; const bool multizone_file = config->GetMultizone_Mesh(); @@ -90,8 +83,10 @@ bool CSU2ASCIIMeshReaderFVM::ReadMetadata(const bool single_pass, CConfig *confi mesh_file.open(meshFilename); if (mesh_file.fail()) { - SU2_MPI::Error("Error opening SU2 ASCII grid.\n" - "Check that the file exists.", CURRENT_FUNCTION); + SU2_MPI::Error( + "Error opening SU2 ASCII grid.\n" + "Check that the file exists.", + CURRENT_FUNCTION); } /*--- If more than one, find the curent zone in the mesh file. ---*/ @@ -99,16 +94,15 @@ bool CSU2ASCIIMeshReaderFVM::ReadMetadata(const bool single_pass, CConfig *confi string text_line; if ((nZones > 1 && multizone_file) || harmonic_balance) { if (harmonic_balance) { - if (rank == MASTER_NODE) cout << "Reading time instance " << config->GetiInst()+1 << "." << endl; - } - else { + if (rank == MASTER_NODE) cout << "Reading time instance " << config->GetiInst() + 1 << "." << endl; + } else { bool foundZone = false; - while (getline (mesh_file,text_line)) { + while (getline(mesh_file, text_line)) { /*--- Search for the current domain ---*/ - if (text_line.find ("IZONE=",0) != string::npos) { - text_line.erase (0,6); + if (text_line.find("IZONE=", 0) != string::npos) { + text_line.erase(0, 6); unsigned short jZone = atoi(text_line.c_str()); - if (jZone == myZone+1) { + if (jZone == myZone + 1) { if (rank == MASTER_NODE) cout << "Reading zone " << myZone << " from native SU2 ASCII mesh." << endl; foundZone = true; break; @@ -116,8 +110,10 @@ bool CSU2ASCIIMeshReaderFVM::ReadMetadata(const bool single_pass, CConfig *confi } } if (!foundZone) { - SU2_MPI::Error("Could not find the IZONE= keyword or the zone contents.\n" - "Check the SU2 ASCII file format.", CURRENT_FUNCTION); + SU2_MPI::Error( + "Could not find the IZONE= keyword or the zone contents.\n" + "Check the SU2 ASCII file format.", + CURRENT_FUNCTION); } } } @@ -132,12 +128,11 @@ bool CSU2ASCIIMeshReaderFVM::ReadMetadata(const bool single_pass, CConfig *confi int current_section_idx = 0; bool single_pass_active = false; - while (getline (mesh_file, text_line)) { - + while (getline(mesh_file, text_line)) { /*--- Read the dimension of the problem ---*/ - if (!foundNDIME && text_line.find ("NDIME=",0) != string::npos) { - text_line.erase (0,6); + if (!foundNDIME && text_line.find("NDIME=", 0) != string::npos) { + text_line.erase(0, 6); dimension = atoi(text_line.c_str()); foundNDIME = true; continue; @@ -145,8 +140,8 @@ bool CSU2ASCIIMeshReaderFVM::ReadMetadata(const bool single_pass, CConfig *confi /*--- The AoA and AoS offset values are optional. ---*/ - if (text_line.find ("AOA_OFFSET=",0) != string::npos) { - text_line.erase (0,11); + if (text_line.find("AOA_OFFSET=", 0) != string::npos) { + text_line.erase(0, 11); su2double AoA_Offset = atof(text_line.c_str()); /*--- The offset is in deg ---*/ @@ -158,16 +153,15 @@ bool CSU2ASCIIMeshReaderFVM::ReadMetadata(const bool single_pass, CConfig *confi if (!config->GetDiscard_InFiles()) { cout << "WARNING: AoA in the config file (" << config->GetAoA() << " deg.) +\n"; cout << " AoA offset in mesh file (" << AoA_Offset << " deg.) = " << AoA_Current << " deg." << endl; - } - else { + } else { cout << "WARNING: Discarding the AoA offset in the mesh file." << endl; } } continue; } - if (text_line.find ("AOS_OFFSET=",0) != string::npos) { - text_line.erase (0,11); + if (text_line.find("AOS_OFFSET=", 0) != string::npos) { + text_line.erase(0, 11); su2double AoS_Offset = atof(text_line.c_str()); /*--- The offset is in deg ---*/ @@ -179,50 +173,45 @@ bool CSU2ASCIIMeshReaderFVM::ReadMetadata(const bool single_pass, CConfig *confi if (!config->GetDiscard_InFiles()) { cout << "WARNING: AoS in the config file (" << config->GetAoS() << " deg.) +\n"; cout << " AoS offset in mesh file (" << AoS_Offset << " deg.) = " << AoS_Current << " deg." << endl; - } - else { + } else { cout << "WARNING: Discarding the AoS offset in the mesh file." << endl; } } continue; } - if (!foundNPOIN && text_line.find ("NPOIN=",0) != string::npos) { - text_line.erase (0,6); + if (!foundNPOIN && text_line.find("NPOIN=", 0) != string::npos) { + text_line.erase(0, 6); numberOfGlobalPoints = atoi(text_line.c_str()); /* If the points were found first, read them, otherwise just consume the lines. */ if (single_pass && foundNDIME && current_section_idx == 0) { single_pass_active = true; ReadPointCoordinates(true); - } - else { - for (auto iPoint = 0ul; iPoint < numberOfGlobalPoints; iPoint++) - getline (mesh_file, text_line); + } else { + for (auto iPoint = 0ul; iPoint < numberOfGlobalPoints; iPoint++) getline(mesh_file, text_line); } SectionOrder[current_section_idx++] = FileSection::POINTS; foundNPOIN = true; continue; } - if (!foundNELEM && text_line.find ("NELEM=",0) != string::npos) { - text_line.erase (0,6); + if (!foundNELEM && text_line.find("NELEM=", 0) != string::npos) { + text_line.erase(0, 6); numberOfGlobalElements = atoi(text_line.c_str()); if (single_pass_active) { ReadVolumeElementConnectivity(true); - } - else { - for (auto iElem = 0ul; iElem < numberOfGlobalElements; iElem++) - getline (mesh_file, text_line); + } else { + for (auto iElem = 0ul; iElem < numberOfGlobalElements; iElem++) getline(mesh_file, text_line); } SectionOrder[current_section_idx++] = FileSection::ELEMENTS; foundNELEM = true; continue; } - if (!foundNMARK && text_line.find ("NMARK=",0) != string::npos) { - text_line.erase (0,6); + if (!foundNMARK && text_line.find("NMARK=", 0) != string::npos) { + text_line.erase(0, 6); numberOfMarkers = atoi(text_line.c_str()); if (current_section_idx != 2) { @@ -237,7 +226,7 @@ bool CSU2ASCIIMeshReaderFVM::ReadMetadata(const bool single_pass, CConfig *confi } /* Stop before we reach the next zone then check for errors below. */ - if (text_line.find ("IZONE=",0) != string::npos) { + if (text_line.find("IZONE=", 0) != string::npos) { break; } } @@ -246,32 +235,41 @@ bool CSU2ASCIIMeshReaderFVM::ReadMetadata(const bool single_pass, CConfig *confi /* Throw an error if any of the keywords was not found. */ if (!foundNDIME) { - SU2_MPI::Error("Could not find the keyword \"NDIME=\".\n" - "Check the SU2 ASCII file format.", CURRENT_FUNCTION); + SU2_MPI::Error( + "Could not find the keyword \"NDIME=\".\n" + "Check the SU2 ASCII file format.", + CURRENT_FUNCTION); } if (!foundNPOIN) { - SU2_MPI::Error("Could not find the keyword \"NPOIN=\".\n" - "Check the SU2 ASCII file format.", CURRENT_FUNCTION); + SU2_MPI::Error( + "Could not find the keyword \"NPOIN=\".\n" + "Check the SU2 ASCII file format.", + CURRENT_FUNCTION); } if (!foundNELEM) { - SU2_MPI::Error("Could not find the keyword \"NELEM=\".\n" - "Check the SU2 ASCII file format.", CURRENT_FUNCTION); + SU2_MPI::Error( + "Could not find the keyword \"NELEM=\".\n" + "Check the SU2 ASCII file format.", + CURRENT_FUNCTION); } if (!foundNMARK) { - SU2_MPI::Error("Could not find the keyword \"NMARK=\".\n" - "Check the SU2 ASCII file format.", CURRENT_FUNCTION); + SU2_MPI::Error( + "Could not find the keyword \"NMARK=\".\n" + "Check the SU2 ASCII file format.", + CURRENT_FUNCTION); } return single_pass_active; } void CSU2ASCIIMeshReaderFVM::SplitActuatorDiskSurface() { - /*--- Actuator disk preprocesing ---*/ bool InElem, Perimeter; unsigned long Counter = 0; - Xloc = 0.0; Yloc = 0.0; Zloc = 0.0; + Xloc = 0.0; + Yloc = 0.0; + Zloc = 0.0; unsigned long nElem_Bound_; vector EdgeBegin, EdgeEnd; @@ -279,7 +277,7 @@ void CSU2ASCIIMeshReaderFVM::SplitActuatorDiskSurface() { unsigned long AuxEdge, iEdge, jEdge, nEdges, nPointVolume; unsigned long long FirstEdgeIndex, SecondEdgeIndex; - vector connectivity(N_POINTS_HEXAHEDRON,0); + vector connectivity(N_POINTS_HEXAHEDRON, 0); vector ActDiskPoint_Front_Inv(numberOfGlobalPoints); vector ActDiskPoint_Front; vector VolumePoint; @@ -291,7 +289,7 @@ void CSU2ASCIIMeshReaderFVM::SplitActuatorDiskSurface() { boundary. Throw an error otherwise. */ if (config->GetnMarker_ActDiskInlet() > 1) { SU2_MPI::Error(string("Current implementation can only split a single actuator disk.") + - string(" \n Remove disks or re-export your mesh with double surfaces (repeated points)."), + string(" \n Remove disks or re-export your mesh with double surfaces (repeated points)."), CURRENT_FUNCTION); } @@ -304,74 +302,78 @@ void CSU2ASCIIMeshReaderFVM::SplitActuatorDiskSurface() { string text_line; string::size_type position; - while (getline (mesh_file, text_line)) { - - position = text_line.find ("NMARK=",0); + while (getline(mesh_file, text_line)) { + position = text_line.find("NMARK=", 0); if (position != string::npos) { - - for (unsigned short iMarker = 0 ; iMarker < numberOfMarkers; iMarker++) { - - getline (mesh_file, text_line); - text_line.erase (0,11); string::size_type position; + for (unsigned short iMarker = 0; iMarker < numberOfMarkers; iMarker++) { + getline(mesh_file, text_line); + text_line.erase(0, 11); + string::size_type position; for (unsigned short iChar = 0; iChar < 20; iChar++) { - position = text_line.find( " ", 0 ); - if (position != string::npos) text_line.erase (position,1); - position = text_line.find( "\r", 0 ); - if (position != string::npos) text_line.erase (position,1); - position = text_line.find( "\n", 0 ); - if (position != string::npos) text_line.erase (position,1); + position = text_line.find(" ", 0); + if (position != string::npos) text_line.erase(position, 1); + position = text_line.find("\r", 0); + if (position != string::npos) text_line.erase(position, 1); + position = text_line.find("\n", 0); + if (position != string::npos) text_line.erase(position, 1); } string Marker_Tag = text_line.c_str(); - getline (mesh_file, text_line); - text_line.erase (0,13); + getline(mesh_file, text_line); + text_line.erase(0, 13); nElem_Bound_ = atoi(text_line.c_str()); if (Marker_Tag != config->GetMarker_ActDiskInlet_TagBound(0)) { - for (unsigned long iElem_Bound = 0; iElem_Bound < nElem_Bound_; iElem_Bound++) { getline (mesh_file, text_line); } - } - else { - + for (unsigned long iElem_Bound = 0; iElem_Bound < nElem_Bound_; iElem_Bound++) { + getline(mesh_file, text_line); + } + } else { if (rank == MASTER_NODE) - cout << "Splitting the surface " << Marker_Tag << "( " << nElem_Bound_ << " boundary elements )." << endl; + cout << "Splitting the surface " << Marker_Tag << "( " << nElem_Bound_ << " boundary elements )." << endl; /*--- Create a list of edges ---*/ for (unsigned long iElem_Bound = 0; iElem_Bound < nElem_Bound_; iElem_Bound++) { - getline(mesh_file, text_line); unsigned short VTK_Type; istringstream bound_line(text_line); bound_line >> VTK_Type; - switch(VTK_Type) { + switch (VTK_Type) { case LINE: bound_line >> connectivity[0]; bound_line >> connectivity[1]; - EdgeBegin.push_back(connectivity[0]); EdgeEnd.push_back(connectivity[1]); + EdgeBegin.push_back(connectivity[0]); + EdgeEnd.push_back(connectivity[1]); break; case TRIANGLE: bound_line >> connectivity[0]; bound_line >> connectivity[1]; bound_line >> connectivity[2]; - EdgeBegin.push_back(connectivity[0]); EdgeEnd.push_back(connectivity[1]); - EdgeBegin.push_back(connectivity[1]); EdgeEnd.push_back(connectivity[2]); - EdgeBegin.push_back(connectivity[2]); EdgeEnd.push_back(connectivity[0]); + EdgeBegin.push_back(connectivity[0]); + EdgeEnd.push_back(connectivity[1]); + EdgeBegin.push_back(connectivity[1]); + EdgeEnd.push_back(connectivity[2]); + EdgeBegin.push_back(connectivity[2]); + EdgeEnd.push_back(connectivity[0]); break; case QUADRILATERAL: bound_line >> connectivity[0]; bound_line >> connectivity[1]; bound_line >> connectivity[2]; bound_line >> connectivity[3]; - EdgeBegin.push_back(connectivity[0]); EdgeEnd.push_back(connectivity[1]); - EdgeBegin.push_back(connectivity[1]); EdgeEnd.push_back(connectivity[2]); - EdgeBegin.push_back(connectivity[2]); EdgeEnd.push_back(connectivity[3]); - EdgeBegin.push_back(connectivity[3]); EdgeEnd.push_back(connectivity[0]); + EdgeBegin.push_back(connectivity[0]); + EdgeEnd.push_back(connectivity[1]); + EdgeBegin.push_back(connectivity[1]); + EdgeEnd.push_back(connectivity[2]); + EdgeBegin.push_back(connectivity[2]); + EdgeEnd.push_back(connectivity[3]); + EdgeBegin.push_back(connectivity[3]); + EdgeEnd.push_back(connectivity[0]); break; } - } /*--- Set the total number of edges ---*/ @@ -380,17 +382,18 @@ void CSU2ASCIIMeshReaderFVM::SplitActuatorDiskSurface() { /*--- Sort edges based on local point index, first index is always the largest ---*/ - for (iEdge = 0; iEdge < nEdges; iEdge++) { + for (iEdge = 0; iEdge < nEdges; iEdge++) { if (EdgeEnd[iEdge] < EdgeBegin[iEdge]) { - AuxEdge = EdgeEnd[iEdge]; EdgeEnd[iEdge] = EdgeBegin[iEdge]; EdgeBegin[iEdge] = AuxEdge; + AuxEdge = EdgeEnd[iEdge]; + EdgeEnd[iEdge] = EdgeBegin[iEdge]; + EdgeBegin[iEdge] = AuxEdge; } } /*--- Bubble sort of the points based on the first index ---*/ for (iEdge = 0; iEdge < nEdges; iEdge++) { - for (jEdge = iEdge+1; jEdge < nEdges; jEdge++) { - + for (jEdge = iEdge + 1; jEdge < nEdges; jEdge++) { FirstEdgeIndex = EdgeBegin[jEdge] << 31; FirstEdgeIndex += EdgeEnd[jEdge]; @@ -398,14 +401,17 @@ void CSU2ASCIIMeshReaderFVM::SplitActuatorDiskSurface() { SecondEdgeIndex += EdgeEnd[iEdge]; if (FirstEdgeIndex <= SecondEdgeIndex) { - AuxEdge = EdgeBegin[iEdge]; EdgeBegin[iEdge] = EdgeBegin[jEdge]; EdgeBegin[jEdge] = AuxEdge; - AuxEdge = EdgeEnd[iEdge]; EdgeEnd[iEdge] = EdgeEnd[jEdge]; EdgeEnd[jEdge] = AuxEdge; + AuxEdge = EdgeBegin[iEdge]; + EdgeBegin[iEdge] = EdgeBegin[jEdge]; + EdgeBegin[jEdge] = AuxEdge; + AuxEdge = EdgeEnd[iEdge]; + EdgeEnd[iEdge] = EdgeEnd[jEdge]; + EdgeEnd[jEdge] = AuxEdge; } } } if (dimension == 3) { - /*--- Check the begning of the list ---*/ if (!((EdgeBegin[0] == EdgeBegin[1]) && (EdgeEnd[0] == EdgeEnd[1]))) { @@ -413,9 +419,9 @@ void CSU2ASCIIMeshReaderFVM::SplitActuatorDiskSurface() { PerimeterPoint.push_back(EdgeEnd[0]); } - for (iEdge = 1; iEdge < nEdges-1; iEdge++) { - bool Check_1 = !((EdgeBegin[iEdge] == EdgeBegin[iEdge-1]) && (EdgeEnd[iEdge] == EdgeEnd[iEdge-1])); - bool Check_2 = !((EdgeBegin[iEdge] == EdgeBegin[iEdge+1]) && (EdgeEnd[iEdge] == EdgeEnd[iEdge+1])); + for (iEdge = 1; iEdge < nEdges - 1; iEdge++) { + bool Check_1 = !((EdgeBegin[iEdge] == EdgeBegin[iEdge - 1]) && (EdgeEnd[iEdge] == EdgeEnd[iEdge - 1])); + bool Check_2 = !((EdgeBegin[iEdge] == EdgeBegin[iEdge + 1]) && (EdgeEnd[iEdge] == EdgeEnd[iEdge + 1])); if ((Check_1 && Check_2)) { PerimeterPoint.push_back(EdgeBegin[iEdge]); PerimeterPoint.push_back(EdgeEnd[iEdge]); @@ -424,14 +430,12 @@ void CSU2ASCIIMeshReaderFVM::SplitActuatorDiskSurface() { /*--- Check the end of the list ---*/ - if (!((EdgeBegin[nEdges-1] == EdgeBegin[nEdges-2]) && (EdgeEnd[nEdges-1] == EdgeEnd[nEdges-2]))) { - PerimeterPoint.push_back(EdgeBegin[nEdges-1]); - PerimeterPoint.push_back(EdgeEnd[nEdges-1]); + if (!((EdgeBegin[nEdges - 1] == EdgeBegin[nEdges - 2]) && (EdgeEnd[nEdges - 1] == EdgeEnd[nEdges - 2]))) { + PerimeterPoint.push_back(EdgeBegin[nEdges - 1]); + PerimeterPoint.push_back(EdgeEnd[nEdges - 1]); } } else { - - /*--- Create a list with all the points ---*/ for (iEdge = 0; iEdge < nEdges; iEdge++) { @@ -445,22 +449,25 @@ void CSU2ASCIIMeshReaderFVM::SplitActuatorDiskSurface() { /*--- Check the begning of the list ---*/ - if (!(ActDiskPoint_Front[0] == ActDiskPoint_Front[1]) ) { PerimeterPoint.push_back(ActDiskPoint_Front[0]); } + if (!(ActDiskPoint_Front[0] == ActDiskPoint_Front[1])) { + PerimeterPoint.push_back(ActDiskPoint_Front[0]); + } - for (unsigned long iPoint = 1; iPoint < ActDiskPoint_Front.size()-1; iPoint++) { - bool Check_1 = !((ActDiskPoint_Front[iPoint] == ActDiskPoint_Front[iPoint-1]) ); - bool Check_2 = !((ActDiskPoint_Front[iPoint] == ActDiskPoint_Front[iPoint+1]) ); - if ((Check_1 && Check_2)) { PerimeterPoint.push_back(ActDiskPoint_Front[iEdge]); } + for (unsigned long iPoint = 1; iPoint < ActDiskPoint_Front.size() - 1; iPoint++) { + bool Check_1 = !((ActDiskPoint_Front[iPoint] == ActDiskPoint_Front[iPoint - 1])); + bool Check_2 = !((ActDiskPoint_Front[iPoint] == ActDiskPoint_Front[iPoint + 1])); + if ((Check_1 && Check_2)) { + PerimeterPoint.push_back(ActDiskPoint_Front[iEdge]); + } } /*--- Check the end of the list ---*/ - if (!((EdgeBegin[ActDiskPoint_Front.size()-1] == EdgeBegin[ActDiskPoint_Front.size()-2]) )) { - PerimeterPoint.push_back(ActDiskPoint_Front[ActDiskPoint_Front.size()-1]); + if (!((EdgeBegin[ActDiskPoint_Front.size() - 1] == EdgeBegin[ActDiskPoint_Front.size() - 2]))) { + PerimeterPoint.push_back(ActDiskPoint_Front[ActDiskPoint_Front.size() - 1]); } ActDiskPoint_Front.clear(); - } vector::iterator it; @@ -469,11 +476,11 @@ void CSU2ASCIIMeshReaderFVM::SplitActuatorDiskSurface() { PerimeterPoint.resize(it - PerimeterPoint.begin()); for (iEdge = 0; iEdge < nEdges; iEdge++) { - Perimeter = false; for (unsigned long iPoint = 0; iPoint < PerimeterPoint.size(); iPoint++) { if (EdgeBegin[iEdge] == PerimeterPoint[iPoint]) { - Perimeter = true; break; + Perimeter = true; + break; } } @@ -482,12 +489,12 @@ void CSU2ASCIIMeshReaderFVM::SplitActuatorDiskSurface() { Perimeter = false; for (unsigned long iPoint = 0; iPoint < PerimeterPoint.size(); iPoint++) { if (EdgeEnd[iEdge] == PerimeterPoint[iPoint]) { - Perimeter = true; break; + Perimeter = true; + break; } } if (!Perimeter) ActDiskPoint_Front.push_back(EdgeEnd[iEdge]); - } /*--- Sort, and remove repeated points from the disk list of points ---*/ @@ -498,7 +505,8 @@ void CSU2ASCIIMeshReaderFVM::SplitActuatorDiskSurface() { ActDiskNewPoints = ActDiskPoint_Front.size(); if (rank == MASTER_NODE) - cout << "Splitting the surface " << Marker_Tag << "( " << ActDiskPoint_Front.size() << " internal points )." << endl; + cout << "Splitting the surface " << Marker_Tag << "( " << ActDiskPoint_Front.size() << " internal points )." + << endl; /*--- Create a map from original point to the new ones (back plane) ---*/ @@ -517,7 +525,6 @@ void CSU2ASCIIMeshReaderFVM::SplitActuatorDiskSurface() { ActDiskPoint_Back[ActDiskPoint_Front[iPoint]] = kPoint; kPoint++; } - } } break; @@ -537,15 +544,14 @@ void CSU2ASCIIMeshReaderFVM::SplitActuatorDiskSurface() { mesh_file.open(meshFilename); FastForwardToMyZone(); - while (getline (mesh_file, text_line)) { - - position = text_line.find ("NPOIN=",0); + while (getline(mesh_file, text_line)) { + position = text_line.find("NPOIN=", 0); if (position != string::npos) { for (unsigned long iPoint = 0; iPoint < numberOfGlobalPoints; iPoint++) { - getline (mesh_file, text_line); + getline(mesh_file, text_line); istringstream point_line(text_line); - su2double Coords[3] = {0.0,0.0,0.0}; + su2double Coords[3] = {0.0, 0.0, 0.0}; if (dimension == 2) { point_line >> Coords[0]; point_line >> Coords[1]; @@ -560,40 +566,45 @@ void CSU2ASCIIMeshReaderFVM::SplitActuatorDiskSurface() { if (ActDisk_Bool[iPoint]) { CoordXActDisk[ActDiskPoint_Front_Inv[iPoint]] = Coords[0]; CoordYActDisk[ActDiskPoint_Front_Inv[iPoint]] = Coords[1]; - Xloc += Coords[0]; Yloc += Coords[1]; + Xloc += Coords[0]; + Yloc += Coords[1]; if (dimension == 3) { CoordZActDisk[ActDiskPoint_Front_Inv[iPoint]] = Coords[2]; Zloc += Coords[2]; } Counter++; } - } } /*--- Locate and tag points that touch the actuator disk surface. ---*/ - position = text_line.find ("NELEM=",0); + position = text_line.find("NELEM=", 0); if (position != string::npos) { for (unsigned long iElem = 0; iElem < numberOfGlobalElements; iElem++) { - getline(mesh_file, text_line); istringstream elem_line(text_line); unsigned short VTK_Type; elem_line >> VTK_Type; - switch(VTK_Type) { + switch (VTK_Type) { case TRIANGLE: elem_line >> connectivity[0]; elem_line >> connectivity[1]; elem_line >> connectivity[2]; InElem = false; for (unsigned long i = 0; i < (unsigned long)N_POINTS_TRIANGLE; i++) { - if (ActDisk_Bool[connectivity[i]]) { InElem = true; break; } } + if (ActDisk_Bool[connectivity[i]]) { + InElem = true; + break; + } + } if (InElem) { for (unsigned long i = 0; i < (unsigned long)N_POINTS_TRIANGLE; i++) { - VolumePoint.push_back(connectivity[i]); } } + VolumePoint.push_back(connectivity[i]); + } + } break; case QUADRILATERAL: elem_line >> connectivity[0]; @@ -602,10 +613,16 @@ void CSU2ASCIIMeshReaderFVM::SplitActuatorDiskSurface() { elem_line >> connectivity[3]; InElem = false; for (unsigned long i = 0; i < (unsigned long)N_POINTS_QUADRILATERAL; i++) { - if (ActDisk_Bool[connectivity[i]]) { InElem = true; break; } } + if (ActDisk_Bool[connectivity[i]]) { + InElem = true; + break; + } + } if (InElem) { for (unsigned long i = 0; i < (unsigned long)N_POINTS_QUADRILATERAL; i++) { - VolumePoint.push_back(connectivity[i]); } } + VolumePoint.push_back(connectivity[i]); + } + } break; case TETRAHEDRON: elem_line >> connectivity[0]; @@ -614,10 +631,16 @@ void CSU2ASCIIMeshReaderFVM::SplitActuatorDiskSurface() { elem_line >> connectivity[3]; InElem = false; for (unsigned long i = 0; i < (unsigned long)N_POINTS_TETRAHEDRON; i++) { - if (ActDisk_Bool[connectivity[i]]) { InElem = true; break; } } + if (ActDisk_Bool[connectivity[i]]) { + InElem = true; + break; + } + } if (InElem) { for (unsigned long i = 0; i < (unsigned long)N_POINTS_TETRAHEDRON; i++) { - VolumePoint.push_back(connectivity[i]); } } + VolumePoint.push_back(connectivity[i]); + } + } break; case HEXAHEDRON: elem_line >> connectivity[0]; @@ -630,10 +653,16 @@ void CSU2ASCIIMeshReaderFVM::SplitActuatorDiskSurface() { elem_line >> connectivity[7]; InElem = false; for (unsigned long i = 0; i < (unsigned long)N_POINTS_HEXAHEDRON; i++) { - if (ActDisk_Bool[connectivity[i]]) { InElem = true; break; } } + if (ActDisk_Bool[connectivity[i]]) { + InElem = true; + break; + } + } if (InElem) { for (unsigned long i = 0; i < (unsigned long)N_POINTS_HEXAHEDRON; i++) { - VolumePoint.push_back(connectivity[i]); } } + VolumePoint.push_back(connectivity[i]); + } + } break; case PRISM: elem_line >> connectivity[0]; @@ -644,10 +673,16 @@ void CSU2ASCIIMeshReaderFVM::SplitActuatorDiskSurface() { elem_line >> connectivity[5]; InElem = false; for (unsigned long i = 0; i < (unsigned long)N_POINTS_PRISM; i++) { - if (ActDisk_Bool[connectivity[i]]) { InElem = true; break; } } + if (ActDisk_Bool[connectivity[i]]) { + InElem = true; + break; + } + } if (InElem) { for (unsigned long i = 0; i < (unsigned long)N_POINTS_PRISM; i++) { - VolumePoint.push_back(connectivity[i]); } } + VolumePoint.push_back(connectivity[i]); + } + } break; case PYRAMID: elem_line >> connectivity[0]; @@ -657,10 +692,16 @@ void CSU2ASCIIMeshReaderFVM::SplitActuatorDiskSurface() { elem_line >> connectivity[4]; InElem = false; for (unsigned long i = 0; i < (unsigned long)N_POINTS_PYRAMID; i++) { - if (ActDisk_Bool[connectivity[i]]) { InElem = true; break; } } + if (ActDisk_Bool[connectivity[i]]) { + InElem = true; + break; + } + } if (InElem) { for (unsigned long i = 0; i < (unsigned long)N_POINTS_PYRAMID; i++) { - VolumePoint.push_back(connectivity[i]); } } + VolumePoint.push_back(connectivity[i]); + } + } break; } } @@ -697,7 +738,7 @@ void CSU2ASCIIMeshReaderFVM::SplitActuatorDiskSurface() { for (unsigned long iPoint = 0; iPoint < nPointVolume; iPoint++) { MapVolumePointBool[VolumePoint[iPoint]] = true; - VolumePoint_Inv[VolumePoint[iPoint]] = iPoint; + VolumePoint_Inv[VolumePoint[iPoint]] = iPoint; } /*--- Store the coordinates of all the surface and volume @@ -706,13 +747,13 @@ void CSU2ASCIIMeshReaderFVM::SplitActuatorDiskSurface() { mesh_file.open(meshFilename); FastForwardToMyZone(); - while (getline (mesh_file, text_line)) { - position = text_line.find ("NPOIN=",0); + while (getline(mesh_file, text_line)) { + position = text_line.find("NPOIN=", 0); if (position != string::npos) { for (unsigned long iPoint = 0; iPoint < numberOfGlobalPoints; iPoint++) { - getline (mesh_file, text_line); + getline(mesh_file, text_line); istringstream point_line(text_line); - su2double Coords[3] = {0.0,0.0,0.0}; + su2double Coords[3] = {0.0, 0.0, 0.0}; if (dimension == 2) { point_line >> Coords[0]; point_line >> Coords[1]; @@ -741,21 +782,18 @@ void CSU2ASCIIMeshReaderFVM::SplitActuatorDiskSurface() { numberOfMarkers++; mesh_file.close(); - } void CSU2ASCIIMeshReaderFVM::ReadPointCoordinates(const bool single_pass) { - /* Get a partitioner to help with linear partitioning. */ - CLinearPartitioner pointPartitioner(numberOfGlobalPoints,0); + CLinearPartitioner pointPartitioner(numberOfGlobalPoints, 0); /* Determine number of local points */ numberOfLocalPoints = pointPartitioner.GetSizeOnRank(rank); /* Prepare our data structure for the point coordinates. */ localPointCoordinates.resize(dimension); - for (int k = 0; k < dimension; k++) - localPointCoordinates[k].reserve(numberOfLocalPoints); + for (int k = 0; k < dimension; k++) localPointCoordinates[k].reserve(numberOfLocalPoints); /*--- Read the point coordinates into our data structure. ---*/ @@ -763,28 +801,30 @@ void CSU2ASCIIMeshReaderFVM::ReadPointCoordinates(const bool single_pass) { string text_line; if (!single_pass) { getline(mesh_file, text_line); - if (text_line.find("NPOIN=",0) == string::npos) continue; + if (text_line.find("NPOIN=", 0) == string::npos) continue; } for (unsigned long GlobalIndex = 0; GlobalIndex < numberOfGlobalPoints; ++GlobalIndex) { - if (!actuator_disk) { getline(mesh_file, text_line); - } - else { - if (GlobalIndex < numberOfGlobalPoints-ActDiskNewPoints) { + } else { + if (GlobalIndex < numberOfGlobalPoints - ActDiskNewPoints) { getline(mesh_file, text_line); - } - else { + } else { /* This is a new actuator disk point, so we must construct a string with the new point's coordinates. */ ostringstream strsX, strsY, strsZ; unsigned long BackActDisk_Index = GlobalIndex; - unsigned long LocalIndex = BackActDisk_Index - (numberOfGlobalPoints-ActDiskNewPoints); - strsX.precision(20); strsY.precision(20); strsZ.precision(20); - su2double CoordX = CoordXActDisk[LocalIndex]; strsX << scientific << CoordX; - su2double CoordY = CoordYActDisk[LocalIndex]; strsY << scientific << CoordY; - su2double CoordZ = CoordZActDisk[LocalIndex]; strsZ << scientific << CoordZ; + unsigned long LocalIndex = BackActDisk_Index - (numberOfGlobalPoints - ActDiskNewPoints); + strsX.precision(20); + strsY.precision(20); + strsZ.precision(20); + su2double CoordX = CoordXActDisk[LocalIndex]; + strsX << scientific << CoordX; + su2double CoordY = CoordYActDisk[LocalIndex]; + strsY << scientific << CoordY; + su2double CoordZ = CoordZActDisk[LocalIndex]; + strsZ << scientific << CoordZ; text_line = strsX.str() + "\t" + strsY.str() + "\t" + strsZ.str(); } } @@ -792,9 +832,8 @@ void CSU2ASCIIMeshReaderFVM::ReadPointCoordinates(const bool single_pass) { /*--- We only read information for this node if it is owned by this rank based upon our initial linear partitioning. ---*/ - passivedouble Coords[3] = {0.0,0.0,0.0}; + passivedouble Coords[3] = {0.0, 0.0, 0.0}; if (pointPartitioner.IndexBelongsToRank(GlobalIndex, rank)) { - istringstream point_line(text_line); /* Store the coordinates more clearly. */ @@ -815,20 +854,19 @@ void CSU2ASCIIMeshReaderFVM::ReadPointCoordinates(const bool single_pass) { } void CSU2ASCIIMeshReaderFVM::ReadVolumeElementConnectivity(const bool single_pass) { - /* Get a partitioner to help with linear partitioning. */ - CLinearPartitioner pointPartitioner(numberOfGlobalPoints,0); + CLinearPartitioner pointPartitioner(numberOfGlobalPoints, 0); /* Loop over our analytically defined of elements and store only those that contain a node within our linear partition of points. */ - numberOfLocalElements = 0; + numberOfLocalElements = 0; array connectivity{}; while (true) { string text_line; if (!single_pass) { if (!getline(mesh_file, text_line)) break; - if (text_line.find("NELEM=",0) == string::npos) continue; + if (text_line.find("NELEM=", 0) == string::npos) continue; } /*--- Loop over all the volumetric elements and store any element that @@ -849,24 +887,24 @@ void CSU2ASCIIMeshReaderFVM::ReadVolumeElementConnectivity(const bool single_pas const auto nPointsElem = nPointsOfElementType(VTK_Type); - for (unsigned short i = 0; i < nPointsElem; i++) { + for (unsigned short i = 0; i < nPointsElem; i++) { elem_line >> connectivity[i]; } if (actuator_disk) { - for (unsigned short i = 0; i Xloc) { + if (Counter != 0 && Xcg > Xloc) { connectivity[i] = ActDiskPoint_Back[connectivity[i]]; } } @@ -898,7 +936,6 @@ void CSU2ASCIIMeshReaderFVM::ReadVolumeElementConnectivity(const bool single_pas } void CSU2ASCIIMeshReaderFVM::ReadSurfaceElementConnectivity(const bool single_pass) { - /* We already read in the number of markers with the metadata. */ surfaceElementConnectivity.resize(numberOfMarkers); markerNames.resize(numberOfMarkers); @@ -913,29 +950,28 @@ void CSU2ASCIIMeshReaderFVM::ReadSurfaceElementConnectivity(const bool single_pa string text_line; if (!single_pass) { if (!getline(mesh_file, text_line)) break; - if (text_line.find("NMARK=",0) == string::npos) continue; + if (text_line.find("NMARK=", 0) == string::npos) continue; } for (unsigned short iMarker = 0; iMarker < numberOfMarkers; ++iMarker) { - getline (mesh_file, text_line); - text_line.erase (0,11); + getline(mesh_file, text_line); + text_line.erase(0, 11); string::size_type position; for (unsigned short iChar = 0; iChar < 20; iChar++) { - position = text_line.find( " ", 0 ); - if (position != string::npos) text_line.erase (position,1); - position = text_line.find( "\r", 0 ); - if (position != string::npos) text_line.erase (position,1); - position = text_line.find( "\n", 0 ); - if (position != string::npos) text_line.erase (position,1); + position = text_line.find(" ", 0); + if (position != string::npos) text_line.erase(position, 1); + position = text_line.find("\r", 0); + if (position != string::npos) text_line.erase(position, 1); + position = text_line.find("\n", 0); + if (position != string::npos) text_line.erase(position, 1); } markerNames[iMarker] = text_line; bool duplicate = false; - if ((actuator_disk) && - (markerNames[iMarker] == config->GetMarker_ActDiskInlet_TagBound(0))) { + if ((actuator_disk) && (markerNames[iMarker] == config->GetMarker_ActDiskInlet_TagBound(0))) { duplicate = true; - markerNames[iMarker+1] = config->GetMarker_ActDiskOutlet_TagBound(0); + markerNames[iMarker + 1] = config->GetMarker_ActDiskOutlet_TagBound(0); } /*--- Physical boundaries definition ---*/ @@ -943,13 +979,14 @@ void CSU2ASCIIMeshReaderFVM::ReadSurfaceElementConnectivity(const bool single_pa if (markerNames[iMarker] == "SEND_RECEIVE") { /*--- Throw an error if we find deprecated references to SEND_RECEIVE boundaries in the mesh. ---*/ - SU2_MPI::Error("Mesh file contains deprecated SEND_RECEIVE marker!\n" - "Please remove any SEND_RECEIVE markers from the SU2 ASCII mesh.", - CURRENT_FUNCTION); + SU2_MPI::Error( + "Mesh file contains deprecated SEND_RECEIVE marker!\n" + "Please remove any SEND_RECEIVE markers from the SU2 ASCII mesh.", + CURRENT_FUNCTION); } - getline (mesh_file, text_line); - text_line.erase (0,13); + getline(mesh_file, text_line); + text_line.erase(0, 13); unsigned long nElem_Bound = atoi(text_line.c_str()); /*--- Allocate space for elements ---*/ @@ -964,8 +1001,10 @@ void CSU2ASCIIMeshReaderFVM::ReadSurfaceElementConnectivity(const bool single_pa const auto nPointsElem = nPointsOfElementType(VTK_Type); if (dimension == 3 && VTK_Type == LINE) { - SU2_MPI::Error("Line boundary conditions are not possible for 3D calculations.\n" - "Please check the SU2 ASCII mesh file.", CURRENT_FUNCTION); + SU2_MPI::Error( + "Line boundary conditions are not possible for 3D calculations.\n" + "Please check the SU2 ASCII mesh file.", + CURRENT_FUNCTION); } for (unsigned short i = 0; i < nPointsElem; i++) { @@ -1002,42 +1041,39 @@ void CSU2ASCIIMeshReaderFVM::ReadSurfaceElementConnectivity(const bool single_pa /*--- Final error check for deprecated periodic BC format. ---*/ string text_line; - while (getline (mesh_file, text_line)) { - + while (getline(mesh_file, text_line)) { /*--- Find any periodic transformation information. ---*/ - if (text_line.find ("NPERIODIC=",0) != string::npos) { - + if (text_line.find("NPERIODIC=", 0) != string::npos) { /*--- Read and store the number of transformations. ---*/ - text_line.erase(0,10); + text_line.erase(0, 10); unsigned short nPeriodic = atoi(text_line.c_str()); if (nPeriodic - 1 != 0) { - SU2_MPI::Error("Mesh file contains deprecated periodic format!\n\n" - "For SU2 v7.0.0 and later, preprocessing of periodic grids by SU2_MSH\n" - "is no longer necessary. Please use the original mesh file (prior to SU2_MSH)\n" - "with the same MARKER_PERIODIC definition in the configuration file.", CURRENT_FUNCTION); + SU2_MPI::Error( + "Mesh file contains deprecated periodic format!\n\n" + "For SU2 v7.0.0 and later, preprocessing of periodic grids by SU2_MSH\n" + "is no longer necessary. Please use the original mesh file (prior to SU2_MSH)\n" + "with the same MARKER_PERIODIC definition in the configuration file.", + CURRENT_FUNCTION); } } /*--- Stop before we reach the next zone. ---*/ - if (text_line.find ("IZONE=",0) != string::npos) break; + if (text_line.find("IZONE=", 0) != string::npos) break; } - } void CSU2ASCIIMeshReaderFVM::FastForwardToMyZone() { - /*--- If more than one, fast-forward to my zone in the mesh file. ---*/ if (nZones == 1 || !config->GetMultizone_Mesh()) return; string text_line; - while (getline (mesh_file,text_line)) { + while (getline(mesh_file, text_line)) { /*--- Search for the current domain ---*/ - if (text_line.find ("IZONE=",0) == string::npos) continue; - text_line.erase (0,6); + if (text_line.find("IZONE=", 0) == string::npos) continue; + text_line.erase(0, 6); unsigned short jZone = atoi(text_line.c_str()); - if (jZone == myZone+1) break; + if (jZone == myZone + 1) break; } - } diff --git a/Common/src/geometry/meson.build b/Common/src/geometry/meson.build index 0da48dee7b0..b67e2b98658 100644 --- a/Common/src/geometry/meson.build +++ b/Common/src/geometry/meson.build @@ -3,4 +3,3 @@ common_src += files(['CGeometry.cpp', 'CMultiGridGeometry.cpp', 'CDummyGeometry.cpp', 'CMultiGridQueue.cpp']) - diff --git a/Common/src/geometry/primal_grid/CHexahedron.cpp b/Common/src/geometry/primal_grid/CHexahedron.cpp index 1ee5c813f46..a4f7f7cf918 100644 --- a/Common/src/geometry/primal_grid/CHexahedron.cpp +++ b/Common/src/geometry/primal_grid/CHexahedron.cpp @@ -33,17 +33,19 @@ constexpr unsigned short CHexahedronConnectivity::Faces[6][4]; constexpr unsigned short CHexahedronConnectivity::nNeighbor_Nodes[8]; constexpr unsigned short CHexahedronConnectivity::Neighbor_Nodes[8][3]; -CHexahedron::CHexahedron(unsigned long val_point_0, unsigned long val_point_1, - unsigned long val_point_2, unsigned long val_point_3, - unsigned long val_point_4, unsigned long val_point_5, - unsigned long val_point_6, unsigned long val_point_7): - CPrimalGridWithConnectivity(false) -{ +CHexahedron::CHexahedron(unsigned long val_point_0, unsigned long val_point_1, unsigned long val_point_2, + unsigned long val_point_3, unsigned long val_point_4, unsigned long val_point_5, + unsigned long val_point_6, unsigned long val_point_7) + : CPrimalGridWithConnectivity(false) { /*--- Define face structure of the element ---*/ - Nodes[0] = val_point_0; Nodes[1] = val_point_1; - Nodes[2] = val_point_2; Nodes[3] = val_point_3; - Nodes[4] = val_point_4; Nodes[5] = val_point_5; - Nodes[6] = val_point_6; Nodes[7] = val_point_7; + Nodes[0] = val_point_0; + Nodes[1] = val_point_1; + Nodes[2] = val_point_2; + Nodes[3] = val_point_3; + Nodes[4] = val_point_4; + Nodes[5] = val_point_5; + Nodes[6] = val_point_6; + Nodes[7] = val_point_7; } void CHexahedron::Change_Orientation() { diff --git a/Common/src/geometry/primal_grid/CLine.cpp b/Common/src/geometry/primal_grid/CLine.cpp index 66bd2a3cc5c..c3d0d7c26c3 100644 --- a/Common/src/geometry/primal_grid/CLine.cpp +++ b/Common/src/geometry/primal_grid/CLine.cpp @@ -33,10 +33,8 @@ constexpr unsigned short CLineConnectivity::Faces[1][2]; constexpr unsigned short CLineConnectivity::nNeighbor_Nodes[2]; constexpr unsigned short CLineConnectivity::Neighbor_Nodes[2][1]; - -CLine::CLine(unsigned long val_point_0, unsigned long val_point_1): - CPrimalGridWithConnectivity(false) -{ +CLine::CLine(unsigned long val_point_0, unsigned long val_point_1) + : CPrimalGridWithConnectivity(false) { /*--- Define face structure of the element ---*/ Nodes[0] = val_point_0; Nodes[1] = val_point_1; diff --git a/Common/src/geometry/primal_grid/CPrimalGrid.cpp b/Common/src/geometry/primal_grid/CPrimalGrid.cpp index 2ed6d9a550c..94269844044 100644 --- a/Common/src/geometry/primal_grid/CPrimalGrid.cpp +++ b/Common/src/geometry/primal_grid/CPrimalGrid.cpp @@ -27,18 +27,13 @@ #include "../../../include/geometry/primal_grid/CPrimalGrid.hpp" -CPrimalGrid::CPrimalGrid(bool FEM, unsigned short nNodes, unsigned short nNeighbor_Elements) : - Nodes(new unsigned long[nNodes]), - Neighbor_Elements(new long[nNeighbor_Elements]), - FEM(FEM) { - +CPrimalGrid::CPrimalGrid(bool FEM, unsigned short nNodes, unsigned short nNeighbor_Elements) + : Nodes(new unsigned long[nNodes]), Neighbor_Elements(new long[nNeighbor_Elements]), FEM(FEM) { GlobalIndex_DomainElement = 0; - for(unsigned short i = 0; i < nNeighbor_Elements; i++) - Neighbor_Elements[i] = -1; + for (unsigned short i = 0; i < nNeighbor_Elements; i++) Neighbor_Elements[i] = -1; } void CPrimalGrid::InitializeNeighbors(unsigned short val_nFaces) { - /*--- Initialize arrays to -1/false to indicate that no neighbor is present and that no periodic transformation is needed to the neighbor. ---*/ for (size_t i = 0; i < val_nFaces; i++) { @@ -46,6 +41,5 @@ void CPrimalGrid::InitializeNeighbors(unsigned short val_nFaces) { PeriodIndexNeighbors[i] = -1; } - for (auto i = 0; i < N_FACES_MAXIMUM; ++i) - ElementOwnsFace[i] = false; + for (auto i = 0; i < N_FACES_MAXIMUM; ++i) ElementOwnsFace[i] = false; } diff --git a/Common/src/geometry/primal_grid/CPrimalGridBoundFEM.cpp b/Common/src/geometry/primal_grid/CPrimalGridBoundFEM.cpp index b8dc1c1191b..bd33fb325e5 100644 --- a/Common/src/geometry/primal_grid/CPrimalGridBoundFEM.cpp +++ b/Common/src/geometry/primal_grid/CPrimalGridBoundFEM.cpp @@ -27,13 +27,10 @@ #include "../../../include/geometry/primal_grid/CPrimalGridBoundFEM.hpp" -CPrimalGridBoundFEM::CPrimalGridBoundFEM(unsigned long val_elemGlobalID, - unsigned long val_domainElementID, - unsigned short val_VTK_Type, - unsigned short val_nPolyGrid, - unsigned short val_nDOFsGrid, - std::vector &val_nodes): CPrimalGrid(true, val_nDOFsGrid, 1) -{ +CPrimalGridBoundFEM::CPrimalGridBoundFEM(unsigned long val_elemGlobalID, unsigned long val_domainElementID, + unsigned short val_VTK_Type, unsigned short val_nPolyGrid, + unsigned short val_nDOFsGrid, std::vector& val_nodes) + : CPrimalGrid(true, val_nDOFsGrid, 1) { /*--- Store the integer data in the member variables of this object. ---*/ VTK_Type = val_VTK_Type; @@ -41,51 +38,51 @@ CPrimalGridBoundFEM::CPrimalGridBoundFEM(unsigned long val_elemGlobalID, nDOFsGrid = val_nDOFsGrid; boundElemIDGlobal = val_elemGlobalID; - GlobalIndex_DomainElement = val_domainElementID; + GlobalIndex_DomainElement = val_domainElementID; /*--- Copy face structure of the element from val_nodes. ---*/ - for(unsigned short i=0; i> Nodes[i]; + for (unsigned short i = 0; i < nDOFsGrid; i++) elem_line >> Nodes[i]; /*--- If a linear element is used, the node numbering for non-simplices must be adapted. The reason is that compatability with the original SU2 format is maintained for linear elements, but for the FEM solver the nodes of the elements are stored row-wise. ---*/ - if(nPolyGrid == 1){ - switch( VTK_Type ) { - + if (nPolyGrid == 1) { + switch (VTK_Type) { case QUADRILATERAL: std::swap(Nodes[2], Nodes[3]); break; @@ -73,110 +69,190 @@ CPrimalGridFEM::CPrimalGridFEM(unsigned long val_elemGlobalID, unsigned short v } } -CPrimalGridFEM::CPrimalGridFEM(unsigned long val_elemGlobalID, unsigned short val_VTK_Type, - unsigned short val_nPolyGrid, unsigned short val_nPolySol, - unsigned short val_nDOFsGrid, unsigned short val_nDOFsSol, - unsigned long val_offDOfsSol, const unsigned long *connGrid) - : CPrimalGrid(true, val_nDOFsGrid, nFacesOfElementType(val_VTK_Type)) -{ +CPrimalGridFEM::CPrimalGridFEM(unsigned long val_elemGlobalID, unsigned short val_VTK_Type, + unsigned short val_nPolyGrid, unsigned short val_nPolySol, unsigned short val_nDOFsGrid, + unsigned short val_nDOFsSol, unsigned long val_offDOfsSol, const unsigned long* connGrid) + : CPrimalGrid(true, val_nDOFsGrid, nFacesOfElementType(val_VTK_Type)) { /*--- Store the integer data in the member variables of this object. ---*/ VTK_Type = val_VTK_Type; nFaces = nFacesOfElementType(VTK_Type); nPolyGrid = val_nPolyGrid; - nPolySol = val_nPolySol; + nPolySol = val_nPolySol; nDOFsGrid = val_nDOFsGrid; - nDOFsSol = val_nDOFsSol; + nDOFsSol = val_nDOFsSol; - elemIDGlobal = val_elemGlobalID; + elemIDGlobal = val_elemGlobalID; offsetDOFsSolGlobal = val_offDOfsSol; /*--- Copy face structure of the element from connGrid. ---*/ - for(unsigned short i=0; i(false) -{ +CPrism::CPrism(unsigned long val_point_0, unsigned long val_point_1, unsigned long val_point_2, + unsigned long val_point_3, unsigned long val_point_4, unsigned long val_point_5) + : CPrimalGridWithConnectivity(false) { /*--- Define face structure of the element ---*/ Nodes[0] = val_point_0; Nodes[1] = val_point_1; diff --git a/Common/src/geometry/primal_grid/CPyramid.cpp b/Common/src/geometry/primal_grid/CPyramid.cpp index f75aac437f0..38baeaae45e 100644 --- a/Common/src/geometry/primal_grid/CPyramid.cpp +++ b/Common/src/geometry/primal_grid/CPyramid.cpp @@ -33,11 +33,9 @@ constexpr unsigned short CPyramidConnectivity::Faces[5][4]; constexpr unsigned short CPyramidConnectivity::nNeighbor_Nodes[5]; constexpr unsigned short CPyramidConnectivity::Neighbor_Nodes[5][4]; -CPyramid::CPyramid(unsigned long val_point_0, unsigned long val_point_1, - unsigned long val_point_2, unsigned long val_point_3, - unsigned long val_point_4): - CPrimalGridWithConnectivity(false) -{ +CPyramid::CPyramid(unsigned long val_point_0, unsigned long val_point_1, unsigned long val_point_2, + unsigned long val_point_3, unsigned long val_point_4) + : CPrimalGridWithConnectivity(false) { /*--- Define face structure of the element ---*/ Nodes[0] = val_point_0; Nodes[1] = val_point_1; @@ -46,6 +44,4 @@ CPyramid::CPyramid(unsigned long val_point_0, unsigned long val_point_1, Nodes[4] = val_point_4; } -void CPyramid::Change_Orientation() { - std::swap(Nodes[1],Nodes[3]); -} +void CPyramid::Change_Orientation() { std::swap(Nodes[1], Nodes[3]); } diff --git a/Common/src/geometry/primal_grid/CQuadrilateral.cpp b/Common/src/geometry/primal_grid/CQuadrilateral.cpp index 643e10209b8..fab0b7a280a 100644 --- a/Common/src/geometry/primal_grid/CQuadrilateral.cpp +++ b/Common/src/geometry/primal_grid/CQuadrilateral.cpp @@ -33,10 +33,9 @@ constexpr unsigned short CQuadrilateralConnectivity::Faces[4][2]; constexpr unsigned short CQuadrilateralConnectivity::nNeighbor_Nodes[4]; constexpr unsigned short CQuadrilateralConnectivity::Neighbor_Nodes[4][2]; -CQuadrilateral::CQuadrilateral(unsigned long val_point_0, unsigned long val_point_1, - unsigned long val_point_2, unsigned long val_point_3): - CPrimalGridWithConnectivity(false) -{ +CQuadrilateral::CQuadrilateral(unsigned long val_point_0, unsigned long val_point_1, unsigned long val_point_2, + unsigned long val_point_3) + : CPrimalGridWithConnectivity(false) { /*--- Define face structure of the element ---*/ Nodes[0] = val_point_0; Nodes[1] = val_point_1; @@ -44,6 +43,4 @@ CQuadrilateral::CQuadrilateral(unsigned long val_point_0, unsigned long val_poin Nodes[3] = val_point_3; } -void CQuadrilateral::Change_Orientation() { - std::swap(Nodes[1], Nodes[3]); -} +void CQuadrilateral::Change_Orientation() { std::swap(Nodes[1], Nodes[3]); } diff --git a/Common/src/geometry/primal_grid/CTetrahedron.cpp b/Common/src/geometry/primal_grid/CTetrahedron.cpp index 0c82ac1ef45..78a9ae6de17 100644 --- a/Common/src/geometry/primal_grid/CTetrahedron.cpp +++ b/Common/src/geometry/primal_grid/CTetrahedron.cpp @@ -33,10 +33,9 @@ constexpr unsigned short CTetrahedronConnectivity::Faces[4][3]; constexpr unsigned short CTetrahedronConnectivity::nNeighbor_Nodes[4]; constexpr unsigned short CTetrahedronConnectivity::Neighbor_Nodes[4][3]; -CTetrahedron::CTetrahedron(unsigned long val_point_0, unsigned long val_point_1, - unsigned long val_point_2, unsigned long val_point_3): - CPrimalGridWithConnectivity(false) -{ +CTetrahedron::CTetrahedron(unsigned long val_point_0, unsigned long val_point_1, unsigned long val_point_2, + unsigned long val_point_3) + : CPrimalGridWithConnectivity(false) { /*--- Define face structure of the element ---*/ Nodes[0] = val_point_0; Nodes[1] = val_point_1; @@ -44,6 +43,4 @@ CTetrahedron::CTetrahedron(unsigned long val_point_0, unsigned long val_point_1, Nodes[3] = val_point_3; } -void CTetrahedron::Change_Orientation() { - std::swap(Nodes[0],Nodes[1]); -} +void CTetrahedron::Change_Orientation() { std::swap(Nodes[0], Nodes[1]); } diff --git a/Common/src/geometry/primal_grid/CTriangle.cpp b/Common/src/geometry/primal_grid/CTriangle.cpp index 8f5dbdfa1c8..36370731c4d 100644 --- a/Common/src/geometry/primal_grid/CTriangle.cpp +++ b/Common/src/geometry/primal_grid/CTriangle.cpp @@ -33,10 +33,8 @@ constexpr unsigned short CTriangleConnectivity::Faces[3][2]; constexpr unsigned short CTriangleConnectivity::nNeighbor_Nodes[3]; constexpr unsigned short CTriangleConnectivity::Neighbor_Nodes[3][2]; -CTriangle::CTriangle(unsigned long val_point_0, unsigned long val_point_1, - unsigned long val_point_2): - CPrimalGridWithConnectivity(false) -{ +CTriangle::CTriangle(unsigned long val_point_0, unsigned long val_point_1, unsigned long val_point_2) + : CPrimalGridWithConnectivity(false) { /*--- Define face structure of the element ---*/ Nodes[0] = val_point_0; Nodes[1] = val_point_1; diff --git a/Common/src/geometry/primal_grid/CVertexMPI.cpp b/Common/src/geometry/primal_grid/CVertexMPI.cpp index 7fe7451cce5..0de612a88bf 100644 --- a/Common/src/geometry/primal_grid/CVertexMPI.cpp +++ b/Common/src/geometry/primal_grid/CVertexMPI.cpp @@ -32,9 +32,7 @@ constexpr unsigned short CVertexMPIConnectivity::Faces[1][1]; constexpr unsigned short CVertexMPIConnectivity::nNeighbor_Nodes[1]; constexpr unsigned short CVertexMPIConnectivity::Neighbor_Nodes[1][1]; -CVertexMPI::CVertexMPI(unsigned long val_point): - CPrimalGridWithConnectivity(false) -{ +CVertexMPI::CVertexMPI(unsigned long val_point) : CPrimalGridWithConnectivity(false) { /*--- Define face structure of the element ---*/ Nodes[0] = val_point; diff --git a/Common/src/graph_coloring_structure.cpp b/Common/src/graph_coloring_structure.cpp index 1b661765d9b..16755851014 100644 --- a/Common/src/graph_coloring_structure.cpp +++ b/Common/src/graph_coloring_structure.cpp @@ -28,15 +28,11 @@ #include "../include/graph_coloring_structure.hpp" /* Function, which determines the colors for the vertices of the given graph. */ -void CGraphColoringStructure::GraphVertexColoring( - CConfig *config, - const vector &nVerticesPerRank, - const vector > &entriesVertices, - int &nGlobalColors, - vector &colorLocalVertices) { - +void CGraphColoringStructure::GraphVertexColoring(CConfig* config, const vector& nVerticesPerRank, + const vector >& entriesVertices, + int& nGlobalColors, vector& colorLocalVertices) { /* Determine the number of ranks and the current rank. */ - int nRank = 1; + int nRank = 1; int myRank = 0; #ifdef HAVE_MPI @@ -45,14 +41,11 @@ void CGraphColoringStructure::GraphVertexColoring( #endif /*--- Determine the algorithm to use for the graph coloring. ---*/ - switch( config->GetKind_Matrix_Coloring() ) { - + switch (config->GetKind_Matrix_Coloring()) { case GREEDY_COLORING: { - /* Greedy algorithm, which is implemented sequentially. Make a distinction between the master rank and the other ranks. */ - if(myRank == 0) { - + if (myRank == 0) { /*--------------------------------------------------------------------*/ /* Master node, which does all the work. */ /* Step 1: Create the global vector for the graph by gathering all the*/ @@ -63,16 +56,13 @@ void CGraphColoringStructure::GraphVertexColoring( /**************************************************************************/ /* Define the global vector and copy my data in it. */ - vector > entriesVert(nVerticesPerRank[nRank], - vector(0)); + vector > entriesVert(nVerticesPerRank[nRank], vector(0)); - for(unsigned long i=nVerticesPerRank[0]; i recvBuf(sizeMess); - SU2_MPI::Recv(recvBuf.data(), sizeMess, MPI_UNSIGNED_LONG, rank, rank, - SU2_MPI::GetComm(), &status); + SU2_MPI::Recv(recvBuf.data(), sizeMess, MPI_UNSIGNED_LONG, rank, rank, SU2_MPI::GetComm(), &status); /* Store the data just received in the global vector for the graph. */ unsigned long ii = 0; - for(unsigned long i=nVerticesPerRank[rank]; i flagColorStored(nVerticesPerRank[nRank], - nVerticesPerRank[nRank]); + vector flagColorStored(nVerticesPerRank[nRank], nVerticesPerRank[nRank]); vector colorNeighbors; colorNeighbors.reserve(1000); /* Loop over the vertices of the graph. */ - for(unsigned long i=0; i sendBuf; - for(unsigned long i=0; i(Order, 0.0)); } -su2double CBSplineBlending::GetBasis(short val_i, su2double val_t){ - +su2double CBSplineBlending::GetBasis(short val_i, su2double val_t) { /*--- Evaluation is based on the algorithm from "The NURBS Book (Les Piegl and Wayne Tiller)" ---*/ /*--- Special cases ---*/ - if ((val_i == 0 && val_t == U[0]) || (val_i == (short)U.size()-1 && val_t == U.back())) {return 1.0;} + if ((val_i == 0 && val_t == U[0]) || (val_i == (short)U.size() - 1 && val_t == U.back())) { + return 1.0; + } /*--- Local property of BSplines ---*/ - if ((val_t < U[val_i]) || (val_t >= U[val_i+Order])){ return 0.0;} + if ((val_t < U[val_i]) || (val_t >= U[val_i + Order])) { + return 0.0; + } - unsigned short j,k; + unsigned short j, k; su2double saved, temp; - for (j = 0; j < Order; j++){ - if ((val_t >= U[val_i+j]) && (val_t < U[val_i+j+1])) N[j][0] = 1.0; - else N[j][0] = 0; + for (j = 0; j < Order; j++) { + if ((val_t >= U[val_i + j]) && (val_t < U[val_i + j + 1])) + N[j][0] = 1.0; + else + N[j][0] = 0; } - for (k = 1; k < Order; k++){ - if (N[0][k-1] == 0.0) saved = 0.0; - else saved = ((val_t - U[val_i])*N[0][k-1])/(U[val_i+k] - U[val_i]); - for (j = 0; j < Order-k; j++){ - if (N[j+1][k-1] == 0.0){ - N[j][k] = saved; saved = 0.0; + for (k = 1; k < Order; k++) { + if (N[0][k - 1] == 0.0) + saved = 0.0; + else + saved = ((val_t - U[val_i]) * N[0][k - 1]) / (U[val_i + k] - U[val_i]); + for (j = 0; j < Order - k; j++) { + if (N[j + 1][k - 1] == 0.0) { + N[j][k] = saved; + saved = 0.0; } else { - temp = N[j+1][k-1]/(U[val_i+j+k+1] - U[val_i+j+1]); - N[j][k] = saved+(U[val_i+j+k+1] - val_t)*temp; - saved = (val_t - U[val_i+j+1])*temp; + temp = N[j + 1][k - 1] / (U[val_i + j + k + 1] - U[val_i + j + 1]); + N[j][k] = saved + (U[val_i + j + k + 1] - val_t) * temp; + saved = (val_t - U[val_i + j + 1]) * temp; } } } - return N[0][Order-1]; + return N[0][Order - 1]; } -su2double CBSplineBlending::GetDerivative(short val_i, su2double val_t, short val_order_der){ - - if ((val_t < U[val_i]) || (val_t >= U[val_i+Order])){ return 0.0;} +su2double CBSplineBlending::GetDerivative(short val_i, su2double val_t, short val_order_der) { + if ((val_t < U[val_i]) || (val_t >= U[val_i + Order])) { + return 0.0; + } /*--- Evaluate the i+p basis functions up to the order p (stored in the matrix N). ---*/ @@ -110,27 +118,29 @@ su2double CBSplineBlending::GetDerivative(short val_i, su2double val_t, short va /*--- Use the recursive definition for the derivative (hardcoded for 1st and 2nd derivative). ---*/ - if (val_order_der == 0){ return N[0][Order-1];} + if (val_order_der == 0) { + return N[0][Order - 1]; + } - if (val_order_der == 1){ - return (Order-1.0)/(1e-10 + U[val_i+Order-1] - U[val_i] )*N[0][Order-2] - - (Order-1.0)/(1e-10 + U[val_i+Order] - U[val_i+1])*N[1][Order-2]; + if (val_order_der == 1) { + return (Order - 1.0) / (1e-10 + U[val_i + Order - 1] - U[val_i]) * N[0][Order - 2] - + (Order - 1.0) / (1e-10 + U[val_i + Order] - U[val_i + 1]) * N[1][Order - 2]; } - if (val_order_der == 2 && Order > 2){ - const su2double left = (Order-2.0)/(1e-10 + U[val_i+Order-2] - U[val_i]) *N[0][Order-3] - - (Order-2.0)/(1e-10 + U[val_i+Order-1] - U[val_i+1])*N[1][Order-3]; + if (val_order_der == 2 && Order > 2) { + const su2double left = (Order - 2.0) / (1e-10 + U[val_i + Order - 2] - U[val_i]) * N[0][Order - 3] - + (Order - 2.0) / (1e-10 + U[val_i + Order - 1] - U[val_i + 1]) * N[1][Order - 3]; - const su2double right = (Order-2.0)/(1e-10 + U[val_i+Order-1] - U[val_i+1])*N[1][Order-3] - - (Order-2.0)/(1e-10 + U[val_i+Order] - U[val_i+2])*N[2][Order-3]; + const su2double right = (Order - 2.0) / (1e-10 + U[val_i + Order - 1] - U[val_i + 1]) * N[1][Order - 3] - + (Order - 2.0) / (1e-10 + U[val_i + Order] - U[val_i + 2]) * N[2][Order - 3]; - return (Order-1.0)/(1e-10 + U[val_i+Order-1] - U[val_i] )*left - - (Order-1.0)/(1e-10 + U[val_i+Order] - U[val_i+1])*right; + return (Order - 1.0) / (1e-10 + U[val_i + Order - 1] - U[val_i]) * left - + (Order - 1.0) / (1e-10 + U[val_i + Order] - U[val_i + 1]) * right; } /*--- Higher order derivatives are not implemented, so we exit if they are requested. ---*/ - if (val_order_der > 2){ + if (val_order_der > 2) { SU2_MPI::Error("Higher order derivatives for BSplines are not implemented.", CURRENT_FUNCTION); } return 0.0; diff --git a/Common/src/grid_movement/CBezierBlending.cpp b/Common/src/grid_movement/CBezierBlending.cpp index 03c41efd037..d24ebdbb974 100644 --- a/Common/src/grid_movement/CBezierBlending.cpp +++ b/Common/src/grid_movement/CBezierBlending.cpp @@ -28,71 +28,73 @@ #include "../../include/grid_movement/CBezierBlending.hpp" #include "../../include/option_structure.hpp" +CBezierBlending::CBezierBlending(short val_order, short n_controlpoints) { SetOrder(val_order, n_controlpoints); } -CBezierBlending::CBezierBlending(short val_order, short n_controlpoints){ - SetOrder(val_order, n_controlpoints); -} - -CBezierBlending::~CBezierBlending(){} +CBezierBlending::~CBezierBlending() {} -void CBezierBlending::SetOrder(short val_order, short n_controlpoints){ - Order = val_order; +void CBezierBlending::SetOrder(short val_order, short n_controlpoints) { + Order = val_order; Degree = Order - 1; - binomial.resize(Order+1, 0.0); -} - -su2double CBezierBlending::GetBasis(short val_i, su2double val_t){ - return GetBernstein(Degree, val_i, val_t); + binomial.resize(Order + 1, 0.0); } -su2double CBezierBlending::GetBernstein(short val_n, short val_i, su2double val_t){ +su2double CBezierBlending::GetBasis(short val_i, su2double val_t) { return GetBernstein(Degree, val_i, val_t); } +su2double CBezierBlending::GetBernstein(short val_n, short val_i, su2double val_t) { su2double value = 0.0; - if (val_i > val_n) { value = 0.0; return value; } + if (val_i > val_n) { + value = 0.0; + return value; + } if (val_i == 0) { - if (val_t == 0) value = 1.0; - else if (val_t == 1) value = 0.0; - else value = Binomial(val_n, val_i) * pow(val_t, val_i) * pow(1.0 - val_t, val_n - val_i); - } - else if (val_i == val_n) { - if (val_t == 0) value = 0.0; - else if (val_t == 1) value = 1.0; - else value = pow(val_t, val_n); - } - else { + if (val_t == 0) + value = 1.0; + else if (val_t == 1) + value = 0.0; + else + value = Binomial(val_n, val_i) * pow(val_t, val_i) * pow(1.0 - val_t, val_n - val_i); + } else if (val_i == val_n) { + if (val_t == 0) + value = 0.0; + else if (val_t == 1) + value = 1.0; + else + value = pow(val_t, val_n); + } else { if ((val_t == 0) || (val_t == 1)) value = 0.0; - value = Binomial(val_n, val_i) * pow(val_t, val_i) * pow(1.0-val_t, val_n - val_i); + value = Binomial(val_n, val_i) * pow(val_t, val_i) * pow(1.0 - val_t, val_n - val_i); } return value; } -su2double CBezierBlending::GetDerivative(short val_i, su2double val_t, short val_order_der){ +su2double CBezierBlending::GetDerivative(short val_i, su2double val_t, short val_order_der) { return GetBernsteinDerivative(Degree, val_i, val_t, val_order_der); } -su2double CBezierBlending::GetBernsteinDerivative(short val_n, short val_i, su2double val_t, short val_order_der){ - +su2double CBezierBlending::GetBernsteinDerivative(short val_n, short val_i, su2double val_t, short val_order_der) { su2double value = 0.0; /*--- Verify this subroutine, it provides negative val_n, which is a wrong value for GetBernstein ---*/ if (val_order_der == 0) { - value = GetBernstein(val_n, val_i, val_t); return value; + value = GetBernstein(val_n, val_i, val_t); + return value; } if (val_i == 0) { - value = val_n*(-GetBernsteinDerivative(val_n-1, val_i, val_t, val_order_der-1)); return value; - } - else { + value = val_n * (-GetBernsteinDerivative(val_n - 1, val_i, val_t, val_order_der - 1)); + return value; + } else { if (val_n == 0) { - value = val_t; return value; - } - else { - value = val_n*(GetBernsteinDerivative(val_n-1, val_i-1, val_t, val_order_der-1) - GetBernsteinDerivative(val_n-1, val_i, val_t, val_order_der-1)); + value = val_t; + return value; + } else { + value = val_n * (GetBernsteinDerivative(val_n - 1, val_i - 1, val_t, val_order_der - 1) - + GetBernsteinDerivative(val_n - 1, val_i, val_t, val_order_der - 1)); return value; } } @@ -100,22 +102,22 @@ su2double CBezierBlending::GetBernsteinDerivative(short val_n, short val_i, su2d return value; } -su2double CBezierBlending::Binomial(unsigned short n, unsigned short m){ - +su2double CBezierBlending::Binomial(unsigned short n, unsigned short m) { unsigned short i, j; su2double result; binomial[0] = 1.0; for (i = 1; i <= n; ++i) { binomial[i] = 1.0; - for (j = i-1U; j > 0; --j) { - binomial[j] += binomial[j-1U]; + for (j = i - 1U; j > 0; --j) { + binomial[j] += binomial[j - 1U]; } } result = binomial[m]; - if (fabs(result) < EPS*EPS) { result = 0.0; } + if (fabs(result) < EPS * EPS) { + result = 0.0; + } return result; - } diff --git a/Common/src/grid_movement/CFreeFormBlending.cpp b/Common/src/grid_movement/CFreeFormBlending.cpp index 9a1871c2f31..50aa23a131f 100644 --- a/Common/src/grid_movement/CFreeFormBlending.cpp +++ b/Common/src/grid_movement/CFreeFormBlending.cpp @@ -27,6 +27,6 @@ #include "../../include/grid_movement/CFreeFormBlending.hpp" -CFreeFormBlending::CFreeFormBlending(){} +CFreeFormBlending::CFreeFormBlending() {} -CFreeFormBlending::~CFreeFormBlending(){} +CFreeFormBlending::~CFreeFormBlending() {} diff --git a/Common/src/grid_movement/CFreeFormDefBox.cpp b/Common/src/grid_movement/CFreeFormDefBox.cpp index c16ef15b716..0d0ca8351c3 100644 --- a/Common/src/grid_movement/CFreeFormDefBox.cpp +++ b/Common/src/grid_movement/CFreeFormDefBox.cpp @@ -29,10 +29,11 @@ #include "../../include/grid_movement/CBezierBlending.hpp" #include "../../include/grid_movement/CBSplineBlending.hpp" -CFreeFormDefBox::CFreeFormDefBox(void) : CGridMovement() { } - -CFreeFormDefBox::CFreeFormDefBox(const unsigned short Degree[], unsigned short BSplineOrder[], unsigned short kind_blending) : CGridMovement() { +CFreeFormDefBox::CFreeFormDefBox(void) : CGridMovement() {} +CFreeFormDefBox::CFreeFormDefBox(const unsigned short Degree[], unsigned short BSplineOrder[], + unsigned short kind_blending) + : CGridMovement() { unsigned short iCornerPoints, iOrder, jOrder, kOrder, iDim; /*--- FFD is always 3D (even in 2D problems) ---*/ @@ -42,39 +43,47 @@ CFreeFormDefBox::CFreeFormDefBox(const unsigned short Degree[], unsigned short B /*--- Allocate Corners points ---*/ - Coord_Corner_Points = new su2double* [nCornerPoints]; + Coord_Corner_Points = new su2double*[nCornerPoints]; for (iCornerPoints = 0; iCornerPoints < nCornerPoints; iCornerPoints++) - Coord_Corner_Points[iCornerPoints] = new su2double [nDim]; + Coord_Corner_Points[iCornerPoints] = new su2double[nDim]; - ParamCoord = new su2double[nDim]; ParamCoord_ = new su2double[nDim]; - cart_coord = new su2double[nDim]; cart_coord_ = new su2double[nDim]; + ParamCoord = new su2double[nDim]; + ParamCoord_ = new su2double[nDim]; + cart_coord = new su2double[nDim]; + cart_coord_ = new su2double[nDim]; Gradient = new su2double[nDim]; - lDegree = Degree[0]; lOrder = lDegree+1; - mDegree = Degree[1]; mOrder = mDegree+1; - nDegree = Degree[2]; nOrder = nDegree+1; - nControlPoints = lOrder*mOrder*nOrder; - - lDegree_Copy = Degree[0]; lOrder_Copy = lDegree+1; - mDegree_Copy = Degree[1]; mOrder_Copy = mDegree+1; - nDegree_Copy = Degree[2]; nOrder_Copy = nDegree+1; - nControlPoints_Copy = lOrder_Copy*mOrder_Copy*nOrder_Copy; - - Coord_Control_Points = new su2double*** [lOrder]; - ParCoord_Control_Points = new su2double*** [lOrder]; - Coord_Control_Points_Copy = new su2double*** [lOrder]; + lDegree = Degree[0]; + lOrder = lDegree + 1; + mDegree = Degree[1]; + mOrder = mDegree + 1; + nDegree = Degree[2]; + nOrder = nDegree + 1; + nControlPoints = lOrder * mOrder * nOrder; + + lDegree_Copy = Degree[0]; + lOrder_Copy = lDegree + 1; + mDegree_Copy = Degree[1]; + mOrder_Copy = mDegree + 1; + nDegree_Copy = Degree[2]; + nOrder_Copy = nDegree + 1; + nControlPoints_Copy = lOrder_Copy * mOrder_Copy * nOrder_Copy; + + Coord_Control_Points = new su2double***[lOrder]; + ParCoord_Control_Points = new su2double***[lOrder]; + Coord_Control_Points_Copy = new su2double***[lOrder]; for (iOrder = 0; iOrder < lOrder; iOrder++) { - Coord_Control_Points[iOrder] = new su2double** [mOrder]; - ParCoord_Control_Points[iOrder] = new su2double** [mOrder]; - Coord_Control_Points_Copy[iOrder] = new su2double** [mOrder]; + Coord_Control_Points[iOrder] = new su2double**[mOrder]; + ParCoord_Control_Points[iOrder] = new su2double**[mOrder]; + Coord_Control_Points_Copy[iOrder] = new su2double**[mOrder]; for (jOrder = 0; jOrder < mOrder; jOrder++) { - Coord_Control_Points[iOrder][jOrder] = new su2double* [nOrder]; - ParCoord_Control_Points[iOrder][jOrder] = new su2double* [nOrder]; - Coord_Control_Points_Copy[iOrder][jOrder] = new su2double* [nOrder]; + Coord_Control_Points[iOrder][jOrder] = new su2double*[nOrder]; + ParCoord_Control_Points[iOrder][jOrder] = new su2double*[nOrder]; + Coord_Control_Points_Copy[iOrder][jOrder] = new su2double*[nOrder]; for (kOrder = 0; kOrder < nOrder; kOrder++) { - Coord_Control_Points[iOrder][jOrder][kOrder] = new su2double [nDim]; - ParCoord_Control_Points[iOrder][jOrder][kOrder] = new su2double [nDim]; - Coord_Control_Points_Copy[iOrder][jOrder][kOrder] = new su2double [nDim]; + Coord_Control_Points[iOrder][jOrder][kOrder] = new su2double[nDim]; + ParCoord_Control_Points[iOrder][jOrder][kOrder] = new su2double[nDim]; + Coord_Control_Points_Copy[iOrder][jOrder][kOrder] = new su2double[nDim]; for (iDim = 0; iDim < nDim; iDim++) { Coord_Control_Points[iOrder][jOrder][kOrder][iDim] = 0.0; ParCoord_Control_Points[iOrder][jOrder][kOrder][iDim] = 0.0; @@ -86,17 +95,16 @@ CFreeFormDefBox::CFreeFormDefBox(const unsigned short Degree[], unsigned short B BlendingFunction = new CFreeFormBlending*[nDim]; - if (kind_blending == BEZIER){ + if (kind_blending == BEZIER) { BlendingFunction[0] = new CBezierBlending(lOrder, lOrder); BlendingFunction[1] = new CBezierBlending(mOrder, mOrder); BlendingFunction[2] = new CBezierBlending(nOrder, nOrder); } - if (kind_blending == BSPLINE_UNIFORM){ + if (kind_blending == BSPLINE_UNIFORM) { BlendingFunction[0] = new CBSplineBlending(BSplineOrder[0], lOrder); BlendingFunction[1] = new CBSplineBlending(BSplineOrder[1], mOrder); BlendingFunction[2] = new CBSplineBlending(BSplineOrder[2], nOrder); } - } CFreeFormDefBox::~CFreeFormDefBox(void) { @@ -105,146 +113,171 @@ CFreeFormDefBox::~CFreeFormDefBox(void) { for (iOrder = 0; iOrder < lOrder; iOrder++) { for (jOrder = 0; jOrder < mOrder; jOrder++) { for (kOrder = 0; kOrder < nOrder; kOrder++) { - delete [] Coord_Control_Points[iOrder][jOrder][kOrder]; - delete [] ParCoord_Control_Points[iOrder][jOrder][kOrder]; - delete [] Coord_Control_Points_Copy[iOrder][jOrder][kOrder]; - if (Coord_SupportCP != nullptr) delete [] Coord_SupportCP[iOrder][jOrder][kOrder]; + delete[] Coord_Control_Points[iOrder][jOrder][kOrder]; + delete[] ParCoord_Control_Points[iOrder][jOrder][kOrder]; + delete[] Coord_Control_Points_Copy[iOrder][jOrder][kOrder]; + if (Coord_SupportCP != nullptr) delete[] Coord_SupportCP[iOrder][jOrder][kOrder]; } - delete [] Coord_Control_Points[iOrder][jOrder]; - delete [] ParCoord_Control_Points[iOrder][jOrder]; - delete [] Coord_Control_Points_Copy[iOrder][jOrder]; - if (Coord_SupportCP != nullptr) delete [] Coord_SupportCP[iOrder][jOrder]; - } - delete [] Coord_Control_Points[iOrder]; - delete [] ParCoord_Control_Points[iOrder]; - delete [] Coord_Control_Points_Copy[iOrder]; - if (Coord_SupportCP != nullptr) delete [] Coord_SupportCP[iOrder]; + delete[] Coord_Control_Points[iOrder][jOrder]; + delete[] ParCoord_Control_Points[iOrder][jOrder]; + delete[] Coord_Control_Points_Copy[iOrder][jOrder]; + if (Coord_SupportCP != nullptr) delete[] Coord_SupportCP[iOrder][jOrder]; } + delete[] Coord_Control_Points[iOrder]; + delete[] ParCoord_Control_Points[iOrder]; + delete[] Coord_Control_Points_Copy[iOrder]; + if (Coord_SupportCP != nullptr) delete[] Coord_SupportCP[iOrder]; + } - delete [] Coord_Control_Points; - delete [] ParCoord_Control_Points; - delete [] Coord_Control_Points_Copy; - delete [] Coord_SupportCP; + delete[] Coord_Control_Points; + delete[] ParCoord_Control_Points; + delete[] Coord_Control_Points_Copy; + delete[] Coord_SupportCP; - delete [] ParamCoord; - delete [] ParamCoord_; - delete [] cart_coord; - delete [] cart_coord_; - delete [] Gradient; + delete[] ParamCoord; + delete[] ParamCoord_; + delete[] cart_coord; + delete[] cart_coord_; + delete[] Gradient; - for (iCornerPoints = 0; iCornerPoints < nCornerPoints; iCornerPoints++) - delete [] Coord_Corner_Points[iCornerPoints]; - delete [] Coord_Corner_Points; + for (iCornerPoints = 0; iCornerPoints < nCornerPoints; iCornerPoints++) delete[] Coord_Corner_Points[iCornerPoints]; + delete[] Coord_Corner_Points; - for (iDim = 0; iDim < nDim; iDim++){ + for (iDim = 0; iDim < nDim; iDim++) { delete BlendingFunction[iDim]; } - delete [] BlendingFunction; + delete[] BlendingFunction; } -void CFreeFormDefBox::SetUnitCornerPoints(void) { - +void CFreeFormDefBox::SetUnitCornerPoints(void) { unsigned short iDim; - su2double *coord = new su2double [nDim]; + su2double* coord = new su2double[nDim]; for (iDim = 0; iDim < nDim; iDim++) coord[iDim] = 0.0; - coord [0] = 0.0; coord [1] = 0.0; coord [2] = 0.0; this->SetCoordCornerPoints(coord, 0); - coord [0] = 1.0; coord [1] = 0.0; coord [2] = 0.0; this->SetCoordCornerPoints(coord, 1); - coord [0] = 1.0; coord [1] = 1.0; coord [2] = 0.0; this->SetCoordCornerPoints(coord, 2); - coord [0] = 0.0; coord [1] = 1.0; coord [2] = 0.0; this->SetCoordCornerPoints(coord, 3); - coord [0] = 0.0; coord [1] = 0.0; coord [2] = 1.0; this->SetCoordCornerPoints(coord, 4); - coord [0] = 1.0; coord [1] = 0.0; coord [2] = 1.0; this->SetCoordCornerPoints(coord, 5); - coord [0] = 1.0; coord [1] = 1.0; coord [2] = 1.0; this->SetCoordCornerPoints(coord, 6); - coord [0] = 0.0; coord [1] = 1.0; coord [2] = 1.0; this->SetCoordCornerPoints(coord, 7); - - delete [] coord; - + coord[0] = 0.0; + coord[1] = 0.0; + coord[2] = 0.0; + this->SetCoordCornerPoints(coord, 0); + coord[0] = 1.0; + coord[1] = 0.0; + coord[2] = 0.0; + this->SetCoordCornerPoints(coord, 1); + coord[0] = 1.0; + coord[1] = 1.0; + coord[2] = 0.0; + this->SetCoordCornerPoints(coord, 2); + coord[0] = 0.0; + coord[1] = 1.0; + coord[2] = 0.0; + this->SetCoordCornerPoints(coord, 3); + coord[0] = 0.0; + coord[1] = 0.0; + coord[2] = 1.0; + this->SetCoordCornerPoints(coord, 4); + coord[0] = 1.0; + coord[1] = 0.0; + coord[2] = 1.0; + this->SetCoordCornerPoints(coord, 5); + coord[0] = 1.0; + coord[1] = 1.0; + coord[2] = 1.0; + this->SetCoordCornerPoints(coord, 6); + coord[0] = 0.0; + coord[1] = 1.0; + coord[2] = 1.0; + this->SetCoordCornerPoints(coord, 7); + + delete[] coord; } -void CFreeFormDefBox::SetControlPoints_Parallelepiped (void) { +void CFreeFormDefBox::SetControlPoints_Parallelepiped(void) { unsigned short iDim, iDegree, jDegree, kDegree; /*--- Set base control points according to the notation of Vtk for hexahedrons ---*/ for (iDim = 0; iDim < nDim; iDim++) { - Coord_Control_Points [0] [0] [0] [iDim] = Coord_Corner_Points[0][iDim]; - Coord_Control_Points [lOrder-1] [0] [0] [iDim] = Coord_Corner_Points[1][iDim]; - Coord_Control_Points [lOrder-1] [mOrder-1] [0] [iDim] = Coord_Corner_Points[2][iDim]; - Coord_Control_Points [0] [mOrder-1] [0] [iDim] = Coord_Corner_Points[3][iDim]; - Coord_Control_Points [0] [0] [nOrder-1] [iDim] = Coord_Corner_Points[4][iDim]; - Coord_Control_Points [lOrder-1] [0] [nOrder-1] [iDim] = Coord_Corner_Points[5][iDim]; - Coord_Control_Points [lOrder-1] [mOrder-1] [nOrder-1] [iDim] = Coord_Corner_Points[6][iDim]; - Coord_Control_Points [0] [mOrder-1] [nOrder-1] [iDim] = Coord_Corner_Points[7][iDim]; + Coord_Control_Points[0][0][0][iDim] = Coord_Corner_Points[0][iDim]; + Coord_Control_Points[lOrder - 1][0][0][iDim] = Coord_Corner_Points[1][iDim]; + Coord_Control_Points[lOrder - 1][mOrder - 1][0][iDim] = Coord_Corner_Points[2][iDim]; + Coord_Control_Points[0][mOrder - 1][0][iDim] = Coord_Corner_Points[3][iDim]; + Coord_Control_Points[0][0][nOrder - 1][iDim] = Coord_Corner_Points[4][iDim]; + Coord_Control_Points[lOrder - 1][0][nOrder - 1][iDim] = Coord_Corner_Points[5][iDim]; + Coord_Control_Points[lOrder - 1][mOrder - 1][nOrder - 1][iDim] = Coord_Corner_Points[6][iDim]; + Coord_Control_Points[0][mOrder - 1][nOrder - 1][iDim] = Coord_Corner_Points[7][iDim]; } /*--- Fill the rest of the cubic matrix of control points with uniform spacing (parallelepiped) ---*/ for (iDegree = 0; iDegree <= lDegree; iDegree++) for (jDegree = 0; jDegree <= mDegree; jDegree++) for (kDegree = 0; kDegree <= nDegree; kDegree++) { - Coord_Control_Points[iDegree][jDegree][kDegree][0] = Coord_Corner_Points[0][0] - + su2double(iDegree)/su2double(lDegree)*(Coord_Corner_Points[1][0]-Coord_Corner_Points[0][0]); - Coord_Control_Points[iDegree][jDegree][kDegree][1] = Coord_Corner_Points[0][1] - + su2double(jDegree)/su2double(mDegree)*(Coord_Corner_Points[3][1]-Coord_Corner_Points[0][1]); - Coord_Control_Points[iDegree][jDegree][kDegree][2] = Coord_Corner_Points[0][2] - + su2double(kDegree)/su2double(nDegree)*(Coord_Corner_Points[4][2]-Coord_Corner_Points[0][2]); + Coord_Control_Points[iDegree][jDegree][kDegree][0] = + Coord_Corner_Points[0][0] + + su2double(iDegree) / su2double(lDegree) * (Coord_Corner_Points[1][0] - Coord_Corner_Points[0][0]); + Coord_Control_Points[iDegree][jDegree][kDegree][1] = + Coord_Corner_Points[0][1] + + su2double(jDegree) / su2double(mDegree) * (Coord_Corner_Points[3][1] - Coord_Corner_Points[0][1]); + Coord_Control_Points[iDegree][jDegree][kDegree][2] = + Coord_Corner_Points[0][2] + + su2double(kDegree) / su2double(nDegree) * (Coord_Corner_Points[4][2] - Coord_Corner_Points[0][2]); } } -void CFreeFormDefBox::SetSupportCP(CFreeFormDefBox *FFDBox) { +void CFreeFormDefBox::SetSupportCP(CFreeFormDefBox* FFDBox) { unsigned short iDim, iOrder, jOrder, kOrder; unsigned short lOrder = FFDBox->GetlOrder(); unsigned short mOrder = FFDBox->GetmOrder(); unsigned short nOrder = FFDBox->GetnOrder(); - Coord_SupportCP = new su2double*** [lOrder]; + Coord_SupportCP = new su2double***[lOrder]; for (iOrder = 0; iOrder < lOrder; iOrder++) { - Coord_SupportCP[iOrder] = new su2double** [mOrder]; + Coord_SupportCP[iOrder] = new su2double**[mOrder]; for (jOrder = 0; jOrder < mOrder; jOrder++) { - Coord_SupportCP[iOrder][jOrder] = new su2double* [nOrder]; - for (kOrder = 0; kOrder < nOrder; kOrder++) - Coord_SupportCP[iOrder][jOrder][kOrder] = new su2double [nDim]; + Coord_SupportCP[iOrder][jOrder] = new su2double*[nOrder]; + for (kOrder = 0; kOrder < nOrder; kOrder++) Coord_SupportCP[iOrder][jOrder][kOrder] = new su2double[nDim]; } } /*--- Set base support control points according to the notation of Vtk for hexahedrons ---*/ for (iDim = 0; iDim < nDim; iDim++) { - Coord_SupportCP [0] [0] [0] [iDim] = Coord_Corner_Points[0][iDim]; - Coord_SupportCP [lOrder-1] [0] [0] [iDim] = Coord_Corner_Points[1][iDim]; - Coord_SupportCP [lOrder-1] [mOrder-1] [0] [iDim] = Coord_Corner_Points[2][iDim]; - Coord_SupportCP [0] [mOrder-1] [0] [iDim] = Coord_Corner_Points[3][iDim]; - Coord_SupportCP [0] [0] [nOrder-1] [iDim] = Coord_Corner_Points[4][iDim]; - Coord_SupportCP [lOrder-1] [0] [nOrder-1] [iDim] = Coord_Corner_Points[5][iDim]; - Coord_SupportCP [lOrder-1] [mOrder-1] [nOrder-1] [iDim] = Coord_Corner_Points[6][iDim]; - Coord_SupportCP [0] [mOrder-1] [nOrder-1] [iDim] = Coord_Corner_Points[7][iDim]; + Coord_SupportCP[0][0][0][iDim] = Coord_Corner_Points[0][iDim]; + Coord_SupportCP[lOrder - 1][0][0][iDim] = Coord_Corner_Points[1][iDim]; + Coord_SupportCP[lOrder - 1][mOrder - 1][0][iDim] = Coord_Corner_Points[2][iDim]; + Coord_SupportCP[0][mOrder - 1][0][iDim] = Coord_Corner_Points[3][iDim]; + Coord_SupportCP[0][0][nOrder - 1][iDim] = Coord_Corner_Points[4][iDim]; + Coord_SupportCP[lOrder - 1][0][nOrder - 1][iDim] = Coord_Corner_Points[5][iDim]; + Coord_SupportCP[lOrder - 1][mOrder - 1][nOrder - 1][iDim] = Coord_Corner_Points[6][iDim]; + Coord_SupportCP[0][mOrder - 1][nOrder - 1][iDim] = Coord_Corner_Points[7][iDim]; } /*--- Fill the rest of the cubic matrix of support control points with uniform spacing ---*/ for (iOrder = 0; iOrder < lOrder; iOrder++) for (jOrder = 0; jOrder < mOrder; jOrder++) for (kOrder = 0; kOrder < nOrder; kOrder++) { - Coord_SupportCP[iOrder][jOrder][kOrder][0] = Coord_Corner_Points[0][0] - + su2double(iOrder)/su2double(lOrder-1)*(Coord_Corner_Points[1][0]-Coord_Corner_Points[0][0]); - Coord_SupportCP[iOrder][jOrder][kOrder][1] = Coord_Corner_Points[0][1] - + su2double(jOrder)/su2double(mOrder-1)*(Coord_Corner_Points[3][1]-Coord_Corner_Points[0][1]); - Coord_SupportCP[iOrder][jOrder][kOrder][2] = Coord_Corner_Points[0][2] - + su2double(kOrder)/su2double(nOrder-1)*(Coord_Corner_Points[4][2]-Coord_Corner_Points[0][2]); + Coord_SupportCP[iOrder][jOrder][kOrder][0] = + Coord_Corner_Points[0][0] + + su2double(iOrder) / su2double(lOrder - 1) * (Coord_Corner_Points[1][0] - Coord_Corner_Points[0][0]); + Coord_SupportCP[iOrder][jOrder][kOrder][1] = + Coord_Corner_Points[0][1] + + su2double(jOrder) / su2double(mOrder - 1) * (Coord_Corner_Points[3][1] - Coord_Corner_Points[0][1]); + Coord_SupportCP[iOrder][jOrder][kOrder][2] = + Coord_Corner_Points[0][2] + + su2double(kOrder) / su2double(nOrder - 1) * (Coord_Corner_Points[4][2] - Coord_Corner_Points[0][2]); } } -void CFreeFormDefBox::SetSupportCPChange(CFreeFormDefBox *FFDBox) { +void CFreeFormDefBox::SetSupportCPChange(CFreeFormDefBox* FFDBox) { unsigned short iDim, iOrder, jOrder, kOrder; su2double *CartCoordNew, *ParamCoord; unsigned short lOrder = FFDBox->GetlOrder(); unsigned short mOrder = FFDBox->GetmOrder(); unsigned short nOrder = FFDBox->GetnOrder(); - su2double ****ParamCoord_SupportCP = new su2double*** [lOrder]; + su2double**** ParamCoord_SupportCP = new su2double***[lOrder]; for (iOrder = 0; iOrder < lOrder; iOrder++) { - ParamCoord_SupportCP[iOrder] = new su2double** [mOrder]; + ParamCoord_SupportCP[iOrder] = new su2double**[mOrder]; for (jOrder = 0; jOrder < mOrder; jOrder++) { - ParamCoord_SupportCP[iOrder][jOrder] = new su2double* [nOrder]; - for (kOrder = 0; kOrder < nOrder; kOrder++) - ParamCoord_SupportCP[iOrder][jOrder][kOrder] = new su2double [nDim]; + ParamCoord_SupportCP[iOrder][jOrder] = new su2double*[nOrder]; + for (kOrder = 0; kOrder < nOrder; kOrder++) ParamCoord_SupportCP[iOrder][jOrder][kOrder] = new su2double[nDim]; } } @@ -252,18 +285,17 @@ void CFreeFormDefBox::SetSupportCPChange(CFreeFormDefBox *FFDBox) { for (jOrder = 0; jOrder < mOrder; jOrder++) for (kOrder = 0; kOrder < nOrder; kOrder++) for (iDim = 0; iDim < nDim; iDim++) - ParamCoord_SupportCP[iOrder][jOrder][kOrder][iDim] = - Coord_SupportCP[iOrder][jOrder][kOrder][iDim]; + ParamCoord_SupportCP[iOrder][jOrder][kOrder][iDim] = Coord_SupportCP[iOrder][jOrder][kOrder][iDim]; for (iDim = 0; iDim < nDim; iDim++) { - Coord_Control_Points[0][0][0][iDim] = FFDBox->GetCoordCornerPoints(iDim, 0); - Coord_Control_Points[1][0][0][iDim] = FFDBox->GetCoordCornerPoints(iDim, 1); - Coord_Control_Points[1][1][0][iDim] = FFDBox->GetCoordCornerPoints(iDim, 2); - Coord_Control_Points[0][1][0][iDim] = FFDBox->GetCoordCornerPoints(iDim, 3); - Coord_Control_Points[0][0][1][iDim] = FFDBox->GetCoordCornerPoints(iDim, 4); - Coord_Control_Points[1][0][1][iDim] = FFDBox->GetCoordCornerPoints(iDim, 5); - Coord_Control_Points[1][1][1][iDim] = FFDBox->GetCoordCornerPoints(iDim, 6); - Coord_Control_Points[0][1][1][iDim] = FFDBox->GetCoordCornerPoints(iDim, 7); + Coord_Control_Points[0][0][0][iDim] = FFDBox->GetCoordCornerPoints(iDim, 0); + Coord_Control_Points[1][0][0][iDim] = FFDBox->GetCoordCornerPoints(iDim, 1); + Coord_Control_Points[1][1][0][iDim] = FFDBox->GetCoordCornerPoints(iDim, 2); + Coord_Control_Points[0][1][0][iDim] = FFDBox->GetCoordCornerPoints(iDim, 3); + Coord_Control_Points[0][0][1][iDim] = FFDBox->GetCoordCornerPoints(iDim, 4); + Coord_Control_Points[1][0][1][iDim] = FFDBox->GetCoordCornerPoints(iDim, 5); + Coord_Control_Points[1][1][1][iDim] = FFDBox->GetCoordCornerPoints(iDim, 6); + Coord_Control_Points[0][1][1][iDim] = FFDBox->GetCoordCornerPoints(iDim, 7); } for (iOrder = 0; iOrder < FFDBox->GetlOrder(); iOrder++) { @@ -276,180 +308,186 @@ void CFreeFormDefBox::SetSupportCPChange(CFreeFormDefBox *FFDBox) { } } } - } -void CFreeFormDefBox::SetCart2Cyl_ControlPoints(CConfig *config) { - +void CFreeFormDefBox::SetCart2Cyl_ControlPoints(CConfig* config) { unsigned short iDegree, jDegree, kDegree; su2double CartCoord[3]; su2double X_0, Y_0, Z_0, Xbar, Ybar, Zbar; - X_0 = config->GetFFD_Axis(0); Y_0 = config->GetFFD_Axis(1); Z_0 = config->GetFFD_Axis(2); + X_0 = config->GetFFD_Axis(0); + Y_0 = config->GetFFD_Axis(1); + Z_0 = config->GetFFD_Axis(2); for (kDegree = 0; kDegree <= nDegree; kDegree++) { for (jDegree = 0; jDegree <= mDegree; jDegree++) { for (iDegree = 0; iDegree <= lDegree; iDegree++) { - CartCoord[0] = Coord_Control_Points[iDegree][jDegree][kDegree][0]; CartCoord[1] = Coord_Control_Points[iDegree][jDegree][kDegree][1]; CartCoord[2] = Coord_Control_Points[iDegree][jDegree][kDegree][2]; - Xbar = CartCoord[0] - X_0; Ybar = CartCoord[1] - Y_0; Zbar = CartCoord[2] - Z_0; + Xbar = CartCoord[0] - X_0; + Ybar = CartCoord[1] - Y_0; + Zbar = CartCoord[2] - Z_0; - Coord_Control_Points[iDegree][jDegree][kDegree][0] = sqrt(Ybar*Ybar + Zbar*Zbar); - Coord_Control_Points[iDegree][jDegree][kDegree][1] = atan2 ( Zbar, Ybar); - if (Coord_Control_Points[iDegree][jDegree][kDegree][1] > PI_NUMBER/2.0) Coord_Control_Points[iDegree][jDegree][kDegree][1] -= 2.0*PI_NUMBER; + Coord_Control_Points[iDegree][jDegree][kDegree][0] = sqrt(Ybar * Ybar + Zbar * Zbar); + Coord_Control_Points[iDegree][jDegree][kDegree][1] = atan2(Zbar, Ybar); + if (Coord_Control_Points[iDegree][jDegree][kDegree][1] > PI_NUMBER / 2.0) + Coord_Control_Points[iDegree][jDegree][kDegree][1] -= 2.0 * PI_NUMBER; Coord_Control_Points[iDegree][jDegree][kDegree][2] = Xbar; CartCoord[0] = Coord_Control_Points_Copy[iDegree][jDegree][kDegree][0]; CartCoord[1] = Coord_Control_Points_Copy[iDegree][jDegree][kDegree][1]; CartCoord[2] = Coord_Control_Points_Copy[iDegree][jDegree][kDegree][2]; - Xbar = CartCoord[0] - X_0; Ybar = CartCoord[1] - Y_0; Zbar = CartCoord[2] - Z_0; + Xbar = CartCoord[0] - X_0; + Ybar = CartCoord[1] - Y_0; + Zbar = CartCoord[2] - Z_0; - Coord_Control_Points_Copy[iDegree][jDegree][kDegree][0] = sqrt(Ybar*Ybar + Zbar*Zbar); - Coord_Control_Points_Copy[iDegree][jDegree][kDegree][1] = atan2 (Zbar, Ybar); - if (Coord_Control_Points_Copy[iDegree][jDegree][kDegree][1] > PI_NUMBER/2.0) Coord_Control_Points_Copy[iDegree][jDegree][kDegree][1] -= 2.0*PI_NUMBER; + Coord_Control_Points_Copy[iDegree][jDegree][kDegree][0] = sqrt(Ybar * Ybar + Zbar * Zbar); + Coord_Control_Points_Copy[iDegree][jDegree][kDegree][1] = atan2(Zbar, Ybar); + if (Coord_Control_Points_Copy[iDegree][jDegree][kDegree][1] > PI_NUMBER / 2.0) + Coord_Control_Points_Copy[iDegree][jDegree][kDegree][1] -= 2.0 * PI_NUMBER; Coord_Control_Points_Copy[iDegree][jDegree][kDegree][2] = Xbar; - } } } - } -void CFreeFormDefBox::SetCyl2Cart_ControlPoints(CConfig *config) { - +void CFreeFormDefBox::SetCyl2Cart_ControlPoints(CConfig* config) { unsigned short iDegree, jDegree, kDegree; su2double PolarCoord[3]; - su2double X_0, Y_0, Z_0, Xbar, Ybar, Zbar; - X_0 = config->GetFFD_Axis(0); Y_0 = config->GetFFD_Axis(1); Z_0 = config->GetFFD_Axis(2); + su2double X_0, Y_0, Z_0, Xbar, Ybar, Zbar; + X_0 = config->GetFFD_Axis(0); + Y_0 = config->GetFFD_Axis(1); + Z_0 = config->GetFFD_Axis(2); for (kDegree = 0; kDegree <= nDegree; kDegree++) { for (jDegree = 0; jDegree <= mDegree; jDegree++) { for (iDegree = 0; iDegree <= lDegree; iDegree++) { - - - PolarCoord[0] = Coord_Control_Points[iDegree][jDegree][kDegree][0]; - PolarCoord[1] = Coord_Control_Points[iDegree][jDegree][kDegree][1]; - PolarCoord[2] = Coord_Control_Points[iDegree][jDegree][kDegree][2]; - + PolarCoord[0] = Coord_Control_Points[iDegree][jDegree][kDegree][0]; + PolarCoord[1] = Coord_Control_Points[iDegree][jDegree][kDegree][1]; + PolarCoord[2] = Coord_Control_Points[iDegree][jDegree][kDegree][2]; Xbar = PolarCoord[2]; Ybar = PolarCoord[0] * cos(PolarCoord[1]); Zbar = PolarCoord[0] * sin(PolarCoord[1]); - PolarCoord[0] = Xbar +X_0; PolarCoord[1] = Ybar +Y_0; PolarCoord[2] = Zbar +Z_0; + PolarCoord[0] = Xbar + X_0; + PolarCoord[1] = Ybar + Y_0; + PolarCoord[2] = Zbar + Z_0; Coord_Control_Points[iDegree][jDegree][kDegree][0] = PolarCoord[0]; Coord_Control_Points[iDegree][jDegree][kDegree][1] = PolarCoord[1]; Coord_Control_Points[iDegree][jDegree][kDegree][2] = PolarCoord[2]; - } } } - } -void CFreeFormDefBox::SetCart2Cyl_CornerPoints(CConfig *config) { - +void CFreeFormDefBox::SetCart2Cyl_CornerPoints(CConfig* config) { unsigned short iCornerPoint; - su2double *CartCoord; + su2double* CartCoord; su2double X_0, Y_0, Z_0, Xbar, Ybar, Zbar; - X_0 = config->GetFFD_Axis(0); Y_0 = config->GetFFD_Axis(1); Z_0 = config->GetFFD_Axis(2); + X_0 = config->GetFFD_Axis(0); + Y_0 = config->GetFFD_Axis(1); + Z_0 = config->GetFFD_Axis(2); for (iCornerPoint = 0; iCornerPoint < 8; iCornerPoint++) { - CartCoord = GetCoordCornerPoints(iCornerPoint); - Xbar = CartCoord[0] - X_0; Ybar = CartCoord[1] - Y_0; Zbar = CartCoord[2] - Z_0; - - CartCoord[0] = sqrt(Ybar*Ybar + Zbar*Zbar); - CartCoord[1] = atan2 ( Zbar, Ybar); if (CartCoord[1] > PI_NUMBER/2.0) CartCoord[1] -= 2.0*PI_NUMBER; - CartCoord[2] = Xbar; - + Xbar = CartCoord[0] - X_0; + Ybar = CartCoord[1] - Y_0; + Zbar = CartCoord[2] - Z_0; + + CartCoord[0] = sqrt(Ybar * Ybar + Zbar * Zbar); + CartCoord[1] = atan2(Zbar, Ybar); + if (CartCoord[1] > PI_NUMBER / 2.0) CartCoord[1] -= 2.0 * PI_NUMBER; + CartCoord[2] = Xbar; } - } - -void CFreeFormDefBox::SetCyl2Cart_CornerPoints(CConfig *config) { - +void CFreeFormDefBox::SetCyl2Cart_CornerPoints(CConfig* config) { unsigned short iCornerPoint; - su2double *PolarCoord; + su2double* PolarCoord; su2double X_0, Y_0, Z_0, Xbar, Ybar, Zbar; - X_0 = config->GetFFD_Axis(0); Y_0 = config->GetFFD_Axis(1); Z_0 = config->GetFFD_Axis(2); + X_0 = config->GetFFD_Axis(0); + Y_0 = config->GetFFD_Axis(1); + Z_0 = config->GetFFD_Axis(2); for (iCornerPoint = 0; iCornerPoint < 8; iCornerPoint++) { - PolarCoord = GetCoordCornerPoints(iCornerPoint); Xbar = PolarCoord[2]; Ybar = PolarCoord[0] * cos(PolarCoord[1]); Zbar = PolarCoord[0] * sin(PolarCoord[1]); - PolarCoord[0] = Xbar + X_0; PolarCoord[1] = Ybar + Y_0; PolarCoord[2] = Zbar + Z_0; - + PolarCoord[0] = Xbar + X_0; + PolarCoord[1] = Ybar + Y_0; + PolarCoord[2] = Zbar + Z_0; } - } -void CFreeFormDefBox::SetCart2Sphe_ControlPoints(CConfig *config) { - +void CFreeFormDefBox::SetCart2Sphe_ControlPoints(CConfig* config) { unsigned short iDegree, jDegree, kDegree; su2double CartCoord[3]; su2double X_0, Y_0, Z_0, Xbar, Ybar, Zbar; - X_0 = config->GetFFD_Axis(0); Y_0 = config->GetFFD_Axis(1); Z_0 = config->GetFFD_Axis(2); + X_0 = config->GetFFD_Axis(0); + Y_0 = config->GetFFD_Axis(1); + Z_0 = config->GetFFD_Axis(2); for (kDegree = 0; kDegree <= nDegree; kDegree++) { for (jDegree = 0; jDegree <= mDegree; jDegree++) { for (iDegree = 0; iDegree <= lDegree; iDegree++) { - CartCoord[0] = Coord_Control_Points[iDegree][jDegree][kDegree][0]; CartCoord[1] = Coord_Control_Points[iDegree][jDegree][kDegree][1]; CartCoord[2] = Coord_Control_Points[iDegree][jDegree][kDegree][2]; - Xbar = CartCoord[0] - X_0; Ybar = CartCoord[1] - Y_0; Zbar = CartCoord[2] - Z_0; + Xbar = CartCoord[0] - X_0; + Ybar = CartCoord[1] - Y_0; + Zbar = CartCoord[2] - Z_0; - Coord_Control_Points[iDegree][jDegree][kDegree][0] = sqrt(Xbar*Xbar + Ybar*Ybar + Zbar*Zbar); - Coord_Control_Points[iDegree][jDegree][kDegree][1] = atan2 ( Zbar, Ybar); - if (Coord_Control_Points[iDegree][jDegree][kDegree][1] > PI_NUMBER/2.0) Coord_Control_Points[iDegree][jDegree][kDegree][1] -= 2.0*PI_NUMBER; - Coord_Control_Points[iDegree][jDegree][kDegree][2] = acos(Xbar/Coord_Control_Points[iDegree][jDegree][kDegree][0] ); + Coord_Control_Points[iDegree][jDegree][kDegree][0] = sqrt(Xbar * Xbar + Ybar * Ybar + Zbar * Zbar); + Coord_Control_Points[iDegree][jDegree][kDegree][1] = atan2(Zbar, Ybar); + if (Coord_Control_Points[iDegree][jDegree][kDegree][1] > PI_NUMBER / 2.0) + Coord_Control_Points[iDegree][jDegree][kDegree][1] -= 2.0 * PI_NUMBER; + Coord_Control_Points[iDegree][jDegree][kDegree][2] = + acos(Xbar / Coord_Control_Points[iDegree][jDegree][kDegree][0]); CartCoord[0] = Coord_Control_Points_Copy[iDegree][jDegree][kDegree][0]; CartCoord[1] = Coord_Control_Points_Copy[iDegree][jDegree][kDegree][1]; CartCoord[2] = Coord_Control_Points_Copy[iDegree][jDegree][kDegree][2]; - Xbar = CartCoord[0] - X_0; Ybar = CartCoord[1] - Y_0; Zbar = CartCoord[2] - Z_0; - - Coord_Control_Points_Copy[iDegree][jDegree][kDegree][0] = sqrt(Xbar*Xbar + Ybar*Ybar + Zbar*Zbar); - Coord_Control_Points_Copy[iDegree][jDegree][kDegree][1] = atan2 ( Zbar, Ybar); - if (Coord_Control_Points_Copy[iDegree][jDegree][kDegree][1] > PI_NUMBER/2.0) - Coord_Control_Points_Copy[iDegree][jDegree][kDegree][1] -= 2.0*PI_NUMBER; - Coord_Control_Points_Copy[iDegree][jDegree][kDegree][2] = acos(Xbar/Coord_Control_Points_Copy[iDegree][jDegree][kDegree][0]); + Xbar = CartCoord[0] - X_0; + Ybar = CartCoord[1] - Y_0; + Zbar = CartCoord[2] - Z_0; + Coord_Control_Points_Copy[iDegree][jDegree][kDegree][0] = sqrt(Xbar * Xbar + Ybar * Ybar + Zbar * Zbar); + Coord_Control_Points_Copy[iDegree][jDegree][kDegree][1] = atan2(Zbar, Ybar); + if (Coord_Control_Points_Copy[iDegree][jDegree][kDegree][1] > PI_NUMBER / 2.0) + Coord_Control_Points_Copy[iDegree][jDegree][kDegree][1] -= 2.0 * PI_NUMBER; + Coord_Control_Points_Copy[iDegree][jDegree][kDegree][2] = + acos(Xbar / Coord_Control_Points_Copy[iDegree][jDegree][kDegree][0]); } } } - } -void CFreeFormDefBox::SetSphe2Cart_ControlPoints(CConfig *config) { - +void CFreeFormDefBox::SetSphe2Cart_ControlPoints(CConfig* config) { unsigned short iDegree, jDegree, kDegree; su2double PolarCoord[3]; - su2double X_0, Y_0, Z_0, Xbar, Ybar, Zbar; - X_0 = config->GetFFD_Axis(0); Y_0 = config->GetFFD_Axis(1); Z_0 = config->GetFFD_Axis(2); + su2double X_0, Y_0, Z_0, Xbar, Ybar, Zbar; + X_0 = config->GetFFD_Axis(0); + Y_0 = config->GetFFD_Axis(1); + Z_0 = config->GetFFD_Axis(2); for (kDegree = 0; kDegree <= nDegree; kDegree++) { for (jDegree = 0; jDegree <= mDegree; jDegree++) { for (iDegree = 0; iDegree <= lDegree; iDegree++) { - PolarCoord[0] = Coord_Control_Points[iDegree][jDegree][kDegree][0]; PolarCoord[1] = Coord_Control_Points[iDegree][jDegree][kDegree][1]; PolarCoord[2] = Coord_Control_Points[iDegree][jDegree][kDegree][2]; @@ -458,64 +496,63 @@ void CFreeFormDefBox::SetSphe2Cart_ControlPoints(CConfig *config) { Ybar = PolarCoord[0] * cos(PolarCoord[1]) * sin(PolarCoord[2]); Zbar = PolarCoord[0] * sin(PolarCoord[1]) * sin(PolarCoord[2]); - PolarCoord[0] = Xbar + X_0; PolarCoord[1] = Ybar + Y_0; PolarCoord[2] = Zbar + Z_0; + PolarCoord[0] = Xbar + X_0; + PolarCoord[1] = Ybar + Y_0; + PolarCoord[2] = Zbar + Z_0; Coord_Control_Points[iDegree][jDegree][kDegree][0] = PolarCoord[0]; Coord_Control_Points[iDegree][jDegree][kDegree][1] = PolarCoord[1]; Coord_Control_Points[iDegree][jDegree][kDegree][2] = PolarCoord[2]; - } } } - } -void CFreeFormDefBox::SetCart2Sphe_CornerPoints(CConfig *config) { - +void CFreeFormDefBox::SetCart2Sphe_CornerPoints(CConfig* config) { unsigned short iCornerPoint; - su2double *CartCoord; + su2double* CartCoord; su2double X_0, Y_0, Z_0, Xbar, Ybar, Zbar; - X_0 = config->GetFFD_Axis(0); Y_0 = config->GetFFD_Axis(1); Z_0 = config->GetFFD_Axis(2); + X_0 = config->GetFFD_Axis(0); + Y_0 = config->GetFFD_Axis(1); + Z_0 = config->GetFFD_Axis(2); for (iCornerPoint = 0; iCornerPoint < 8; iCornerPoint++) { - CartCoord = GetCoordCornerPoints(iCornerPoint); - Xbar = CartCoord[0] - X_0; Ybar = CartCoord[1] - Y_0; Zbar = CartCoord[2] - Z_0; - - CartCoord[0] = sqrt(Xbar*Xbar + Ybar*Ybar + Zbar*Zbar); - CartCoord[1] = atan2(Zbar, Ybar); if (CartCoord[1] > PI_NUMBER/2.0) CartCoord[1] -= 2.0*PI_NUMBER; - CartCoord[2] = acos(Xbar/CartCoord[0]); - + Xbar = CartCoord[0] - X_0; + Ybar = CartCoord[1] - Y_0; + Zbar = CartCoord[2] - Z_0; + + CartCoord[0] = sqrt(Xbar * Xbar + Ybar * Ybar + Zbar * Zbar); + CartCoord[1] = atan2(Zbar, Ybar); + if (CartCoord[1] > PI_NUMBER / 2.0) CartCoord[1] -= 2.0 * PI_NUMBER; + CartCoord[2] = acos(Xbar / CartCoord[0]); } - } - -void CFreeFormDefBox::SetSphe2Cart_CornerPoints(CConfig *config) { - +void CFreeFormDefBox::SetSphe2Cart_CornerPoints(CConfig* config) { unsigned short iCornerPoint; - su2double *PolarCoord; + su2double* PolarCoord; su2double X_0, Y_0, Z_0, Xbar, Ybar, Zbar; - X_0 = config->GetFFD_Axis(0); Y_0 = config->GetFFD_Axis(1); Z_0 = config->GetFFD_Axis(2); + X_0 = config->GetFFD_Axis(0); + Y_0 = config->GetFFD_Axis(1); + Z_0 = config->GetFFD_Axis(2); for (iCornerPoint = 0; iCornerPoint < 8; iCornerPoint++) { - PolarCoord = GetCoordCornerPoints(iCornerPoint); Xbar = PolarCoord[0] * cos(PolarCoord[2]); Ybar = PolarCoord[0] * cos(PolarCoord[1]) * sin(PolarCoord[2]); Zbar = PolarCoord[0] * sin(PolarCoord[1]) * sin(PolarCoord[2]); - PolarCoord[0] = Xbar + X_0; PolarCoord[1] = Ybar + Y_0; PolarCoord[2] = Zbar + Z_0; - + PolarCoord[0] = Xbar + X_0; + PolarCoord[1] = Ybar + Y_0; + PolarCoord[2] = Zbar + Z_0; } - } - -void CFreeFormDefBox::SetCGNS(CGeometry *geometry, unsigned short iFFDBox, bool original) { +void CFreeFormDefBox::SetCGNS(CGeometry* geometry, unsigned short iFFDBox, bool original) { #ifdef HAVE_CGNS char FFDBox_filename[MAX_STRING_SIZE]; @@ -526,39 +563,38 @@ void CFreeFormDefBox::SetCGNS(CGeometry *geometry, unsigned short iFFDBox, bool char zonename[33]; int FFDBox_cgns_file; int cell_dim, phys_dim; - int cgns_base=0, cgns_family, cgns_zone, cgns_err, dummy; - const char * basename; + int cgns_base = 0, cgns_family, cgns_zone, cgns_err, dummy; + const char* basename; /*--- FFD output is always 3D (even in 2D problems), this is important for debuging ---*/ nDim = geometry->GetnDim(); - cell_dim = nDim, - phys_dim = 3; + cell_dim = nDim, phys_dim = 3; - SPRINTF (FFDBox_filename, "ffd_boxes.cgns"); + SPRINTF(FFDBox_filename, "ffd_boxes.cgns"); - if ((original) && (iFFDBox == 0)) new_file = true; - else new_file = false; + if ((original) && (iFFDBox == 0)) + new_file = true; + else + new_file = false; if (new_file) { cgns_err = cg_open(FFDBox_filename, CG_MODE_WRITE, &FFDBox_cgns_file); if (cgns_err) cg_error_print(); - cgns_err = cg_descriptor_write("Title", "Visualization of the FFD boxes generated by SU2_DEF." ); + cgns_err = cg_descriptor_write("Title", "Visualization of the FFD boxes generated by SU2_DEF."); if (cgns_err) cg_error_print(); - } - else { + } else { cgns_err = cg_open(FFDBox_filename, CG_MODE_MODIFY, &FFDBox_cgns_file); if (cgns_err) cg_error_print(); } if (original) { basename = "Original_FFD"; - } - else { + } else { basename = "Deformed_FFD"; } - if (iFFDBox == 0){ + if (iFFDBox == 0) { cgns_err = cg_base_write(FFDBox_cgns_file, basename, cell_dim, phys_dim, &cgns_base); if (cgns_err) cg_error_print(); } @@ -566,20 +602,20 @@ void CFreeFormDefBox::SetCGNS(CGeometry *geometry, unsigned short iFFDBox, bool if (cgns_err) cg_error_print(); cgsize_t dims[9]; - dims[0] = lDegree+1; - dims[1] = mDegree+1; - if (cell_dim == 3){ - dims[2] = nDegree+1; + dims[0] = lDegree + 1; + dims[1] = mDegree + 1; + if (cell_dim == 3) { + dims[2] = nDegree + 1; } cgsize_t pointlen = 1; - for(int ii=0; iiGetnDim(); - if (original) new_file = true; - else new_file = false; + if (original) + new_file = true; + else + new_file = false; - if (new_file) SPRINTF (FFDBox_filename, "ffd_boxes_%d.vtk", SU2_TYPE::Int(iFFDBox)); - else SPRINTF (FFDBox_filename, "ffd_boxes_def_%d.vtk", SU2_TYPE::Int(iFFDBox)); + if (new_file) + SPRINTF(FFDBox_filename, "ffd_boxes_%d.vtk", SU2_TYPE::Int(iFFDBox)); + else + SPRINTF(FFDBox_filename, "ffd_boxes_def_%d.vtk", SU2_TYPE::Int(iFFDBox)); FFDBox_file.open(FFDBox_filename, ios::out); FFDBox_file << "# vtk DataFile Version 3.0" << endl; @@ -699,10 +743,14 @@ void CFreeFormDefBox::SetParaview(CGeometry *geometry, unsigned short iFFDBox, b FFDBox_file << "ASCII" << endl; FFDBox_file << "DATASET STRUCTURED_GRID" << endl; - if (nDim == 2) FFDBox_file << "DIMENSIONS "<GetBasis(iDegree, ParamCoord[0]) - * BlendingFunction[1]->GetBasis(jDegree, ParamCoord[1]) - * BlendingFunction[2]->GetBasis(kDegree, ParamCoord[2]); + cart_coord[iDim] += Coord_Control_Points[iDegree][jDegree][kDegree][iDim] * + BlendingFunction[0]->GetBasis(iDegree, ParamCoord[0]) * + BlendingFunction[1]->GetBasis(jDegree, ParamCoord[1]) * + BlendingFunction[2]->GetBasis(kDegree, ParamCoord[2]); } return cart_coord; } - -su2double *CFreeFormDefBox::GetFFDGradient(su2double *val_coord, su2double *xyz) { - +su2double* CFreeFormDefBox::GetFFDGradient(su2double* val_coord, su2double* xyz) { unsigned short iDim, jDim, lmn[3]; /*--- Set the Degree of the spline ---*/ - lmn[0] = lDegree; lmn[1] = mDegree; lmn[2] = nDegree; + lmn[0] = lDegree; + lmn[1] = mDegree; + lmn[2] = nDegree; for (iDim = 0; iDim < nDim; iDim++) Gradient[iDim] = 0.0; for (iDim = 0; iDim < nDim; iDim++) for (jDim = 0; jDim < nDim; jDim++) - Gradient[jDim] += GetDerivative2(val_coord, iDim, xyz, lmn) * - GetDerivative3(val_coord, iDim, jDim, lmn); + Gradient[jDim] += GetDerivative2(val_coord, iDim, xyz, lmn) * GetDerivative3(val_coord, iDim, jDim, lmn); return Gradient; - } -void CFreeFormDefBox::GetFFDHessian(su2double *uvw, su2double *xyz, su2double **val_Hessian) { - +void CFreeFormDefBox::GetFFDHessian(su2double* uvw, su2double* xyz, su2double** val_Hessian) { unsigned short iDim, jDim, lmn[3]; /*--- Set the Degree of the spline ---*/ - lmn[0] = lDegree; lmn[1] = mDegree; lmn[2] = nDegree; + lmn[0] = lDegree; + lmn[1] = mDegree; + lmn[2] = nDegree; for (iDim = 0; iDim < nDim; iDim++) - for (jDim = 0; jDim < nDim; jDim++) - val_Hessian[iDim][jDim] = 0.0; + for (jDim = 0; jDim < nDim; jDim++) val_Hessian[iDim][jDim] = 0.0; /*--- Note that being all the functions linear combinations of polynomials, they are C^\infty, and the Hessian will be symmetric; no need to compute the under-diagonal part, for example ---*/ for (iDim = 0; iDim < nDim; iDim++) { - val_Hessian[0][0] += 2.0 * GetDerivative3(uvw, iDim,0, lmn) * GetDerivative3(uvw, iDim,0, lmn) + - GetDerivative2(uvw, iDim,xyz, lmn) * GetDerivative5(uvw, iDim,0,0, lmn); + val_Hessian[0][0] += 2.0 * GetDerivative3(uvw, iDim, 0, lmn) * GetDerivative3(uvw, iDim, 0, lmn) + + GetDerivative2(uvw, iDim, xyz, lmn) * GetDerivative5(uvw, iDim, 0, 0, lmn); - val_Hessian[1][1] += 2.0 * GetDerivative3(uvw, iDim,1, lmn) * GetDerivative3(uvw, iDim,1, lmn) + - GetDerivative2(uvw, iDim,xyz, lmn) * GetDerivative5(uvw, iDim,1,1, lmn); + val_Hessian[1][1] += 2.0 * GetDerivative3(uvw, iDim, 1, lmn) * GetDerivative3(uvw, iDim, 1, lmn) + + GetDerivative2(uvw, iDim, xyz, lmn) * GetDerivative5(uvw, iDim, 1, 1, lmn); - val_Hessian[2][2] += 2.0 * GetDerivative3(uvw, iDim,2, lmn) * GetDerivative3(uvw, iDim,2, lmn) + - GetDerivative2(uvw, iDim,xyz, lmn) * GetDerivative5(uvw, iDim,2,2, lmn); + val_Hessian[2][2] += 2.0 * GetDerivative3(uvw, iDim, 2, lmn) * GetDerivative3(uvw, iDim, 2, lmn) + + GetDerivative2(uvw, iDim, xyz, lmn) * GetDerivative5(uvw, iDim, 2, 2, lmn); - val_Hessian[0][1] += 2.0 * GetDerivative3(uvw, iDim,0, lmn) * GetDerivative3(uvw, iDim,1, lmn) + - GetDerivative2(uvw, iDim,xyz, lmn) * GetDerivative5(uvw, iDim,0,1, lmn); + val_Hessian[0][1] += 2.0 * GetDerivative3(uvw, iDim, 0, lmn) * GetDerivative3(uvw, iDim, 1, lmn) + + GetDerivative2(uvw, iDim, xyz, lmn) * GetDerivative5(uvw, iDim, 0, 1, lmn); - val_Hessian[0][2] += 2.0 * GetDerivative3(uvw, iDim,0, lmn) * GetDerivative3(uvw, iDim,2, lmn) + - GetDerivative2(uvw, iDim,xyz, lmn) * GetDerivative5(uvw, iDim,0,2, lmn); + val_Hessian[0][2] += 2.0 * GetDerivative3(uvw, iDim, 0, lmn) * GetDerivative3(uvw, iDim, 2, lmn) + + GetDerivative2(uvw, iDim, xyz, lmn) * GetDerivative5(uvw, iDim, 0, 2, lmn); - val_Hessian[1][2] += 2.0 * GetDerivative3(uvw, iDim,1, lmn) * GetDerivative3(uvw, iDim,2, lmn) + - GetDerivative2(uvw, iDim,xyz, lmn) * GetDerivative5(uvw, iDim,1,2, lmn); + val_Hessian[1][2] += 2.0 * GetDerivative3(uvw, iDim, 1, lmn) * GetDerivative3(uvw, iDim, 2, lmn) + + GetDerivative2(uvw, iDim, xyz, lmn) * GetDerivative5(uvw, iDim, 1, 2, lmn); } val_Hessian[1][0] = val_Hessian[0][1]; val_Hessian[2][0] = val_Hessian[0][2]; val_Hessian[2][1] = val_Hessian[1][2]; - } -su2double *CFreeFormDefBox::GetParametricCoord_Iterative(unsigned long iPoint, su2double *xyz, const su2double *ParamCoordGuess, CConfig *config) { - - su2double *IndepTerm, SOR_Factor = 1.0, MinNormError, NormError, Determinant, AdjHessian[3][3], Temp[3] = {0.0,0.0,0.0}; +su2double* CFreeFormDefBox::GetParametricCoord_Iterative(unsigned long iPoint, su2double* xyz, + const su2double* ParamCoordGuess, CConfig* config) { + su2double *IndepTerm, SOR_Factor = 1.0, MinNormError, NormError, Determinant, AdjHessian[3][3], + Temp[3] = {0.0, 0.0, 0.0}; unsigned short iDim, jDim, RandonCounter; unsigned long iter; - su2double tol = config->GetFFD_Tol()*1E-3; + su2double tol = config->GetFFD_Tol() * 1E-3; unsigned short it_max = config->GetnFFD_Iter(); unsigned short Random_Trials = 500; /*--- Allocate the Hessian ---*/ - Hessian = new su2double* [nDim]; - IndepTerm = new su2double [nDim]; + Hessian = new su2double*[nDim]; + IndepTerm = new su2double[nDim]; for (iDim = 0; iDim < nDim; iDim++) { Hessian[iDim] = new su2double[nDim]; ParamCoord[iDim] = ParamCoordGuess[iDim]; - IndepTerm [iDim] = 0.0; + IndepTerm[iDim] = 0.0; } - RandonCounter = 0; MinNormError = 1E6; + RandonCounter = 0; + MinNormError = 1E6; /*--- External iteration ---*/ - for (iter = 0; iter < (unsigned long)it_max*Random_Trials; iter++) { - + for (iter = 0; iter < (unsigned long)it_max * Random_Trials; iter++) { /*--- The independent term of the solution of our system is -Gradient(sol_old) ---*/ Gradient = GetFFDGradient(ParamCoord, xyz); - for (iDim = 0; iDim < nDim; iDim++) IndepTerm[iDim] = - Gradient[iDim]; + for (iDim = 0; iDim < nDim; iDim++) IndepTerm[iDim] = -Gradient[iDim]; /*--- Hessian = The Matrix of our system, getHessian(sol_old,xyz,...) ---*/ @@ -887,19 +933,20 @@ su2double *CFreeFormDefBox::GetParametricCoord_Iterative(unsigned long iPoint, s /*--- Adjoint to Hessian ---*/ - AdjHessian[0][0] = Hessian[1][1]*Hessian[2][2]-Hessian[1][2]*Hessian[2][1]; - AdjHessian[0][1] = Hessian[0][2]*Hessian[2][1]-Hessian[0][1]*Hessian[2][2]; - AdjHessian[0][2] = Hessian[0][1]*Hessian[1][2]-Hessian[0][2]*Hessian[1][1]; - AdjHessian[1][0] = Hessian[1][2]*Hessian[2][0]-Hessian[1][0]*Hessian[2][2]; - AdjHessian[1][1] = Hessian[0][0]*Hessian[2][2]-Hessian[0][2]*Hessian[2][0]; - AdjHessian[1][2] = Hessian[0][2]*Hessian[1][0]-Hessian[0][0]*Hessian[1][2]; - AdjHessian[2][0] = Hessian[1][0]*Hessian[2][1]-Hessian[1][1]*Hessian[2][0]; - AdjHessian[2][1] = Hessian[0][1]*Hessian[2][0]-Hessian[0][0]*Hessian[2][1]; - AdjHessian[2][2] = Hessian[0][0]*Hessian[1][1]-Hessian[0][1]*Hessian[1][0]; + AdjHessian[0][0] = Hessian[1][1] * Hessian[2][2] - Hessian[1][2] * Hessian[2][1]; + AdjHessian[0][1] = Hessian[0][2] * Hessian[2][1] - Hessian[0][1] * Hessian[2][2]; + AdjHessian[0][2] = Hessian[0][1] * Hessian[1][2] - Hessian[0][2] * Hessian[1][1]; + AdjHessian[1][0] = Hessian[1][2] * Hessian[2][0] - Hessian[1][0] * Hessian[2][2]; + AdjHessian[1][1] = Hessian[0][0] * Hessian[2][2] - Hessian[0][2] * Hessian[2][0]; + AdjHessian[1][2] = Hessian[0][2] * Hessian[1][0] - Hessian[0][0] * Hessian[1][2]; + AdjHessian[2][0] = Hessian[1][0] * Hessian[2][1] - Hessian[1][1] * Hessian[2][0]; + AdjHessian[2][1] = Hessian[0][1] * Hessian[2][0] - Hessian[0][0] * Hessian[2][1]; + AdjHessian[2][2] = Hessian[0][0] * Hessian[1][1] - Hessian[0][1] * Hessian[1][0]; /*--- Determinant of Hessian ---*/ - Determinant = Hessian[0][0]*AdjHessian[0][0]+Hessian[0][1]*AdjHessian[1][0]+Hessian[0][2]*AdjHessian[2][0]; + Determinant = + Hessian[0][0] * AdjHessian[0][0] + Hessian[0][1] * AdjHessian[1][0] + Hessian[0][2] * AdjHessian[2][0]; /*--- Hessian inverse ---*/ @@ -907,7 +954,7 @@ su2double *CFreeFormDefBox::GetParametricCoord_Iterative(unsigned long iPoint, s for (iDim = 0; iDim < nDim; iDim++) { Temp[iDim] = 0.0; for (jDim = 0; jDim < nDim; jDim++) { - Temp[iDim] += AdjHessian[iDim][jDim]*IndepTerm[jDim]/Determinant; + Temp[iDim] += AdjHessian[iDim][jDim] * IndepTerm[jDim] / Determinant; } } for (iDim = 0; iDim < nDim; iDim++) { @@ -918,18 +965,17 @@ su2double *CFreeFormDefBox::GetParametricCoord_Iterative(unsigned long iPoint, s /*--- Update with Successive over-relaxation ---*/ for (iDim = 0; iDim < nDim; iDim++) { - ParamCoord[iDim] = (1.0-SOR_Factor)*ParamCoord[iDim] + SOR_Factor*(ParamCoord[iDim] + IndepTerm[iDim]); + ParamCoord[iDim] = (1.0 - SOR_Factor) * ParamCoord[iDim] + SOR_Factor * (ParamCoord[iDim] + IndepTerm[iDim]); } /*--- If the gradient is small, we have converged ---*/ - if ((fabs(IndepTerm[0]) < tol) && (fabs(IndepTerm[1]) < tol) && (fabs(IndepTerm[2]) < tol)) break; + if ((fabs(IndepTerm[0]) < tol) && (fabs(IndepTerm[1]) < tol) && (fabs(IndepTerm[2]) < tol)) break; /*--- Compute the norm of the error ---*/ NormError = 0.0; - for (iDim = 0; iDim < nDim; iDim++) - NormError += IndepTerm[iDim]*IndepTerm[iDim]; + for (iDim = 0; iDim < nDim; iDim++) NormError += IndepTerm[iDim] * IndepTerm[iDim]; NormError = sqrt(NormError); MinNormError = min(NormError, MinNormError); @@ -937,54 +983,47 @@ su2double *CFreeFormDefBox::GetParametricCoord_Iterative(unsigned long iPoint, s /*--- If we have no convergence with Random_Trials iterations probably we are in a local minima. ---*/ if (((iter % it_max) == 0) && (iter != 0)) { - RandonCounter++; if (RandonCounter == Random_Trials) { - cout << endl << "Unknown point: "<< iPoint <<" (" << xyz[0] <<", "<< xyz[1] <<", "<< xyz[2] <<"). Min Error: "<< MinNormError <<". Iter: "<< iter <<"."<< endl; - } - else { + cout << endl + << "Unknown point: " << iPoint << " (" << xyz[0] << ", " << xyz[1] << ", " << xyz[2] + << "). Min Error: " << MinNormError << ". Iter: " << iter << "." << endl; + } else { SOR_Factor = 0.1; - for (iDim = 0; iDim < nDim; iDim++) - ParamCoord[iDim] = su2double(rand())/su2double(RAND_MAX); + for (iDim = 0; iDim < nDim; iDim++) ParamCoord[iDim] = su2double(rand()) / su2double(RAND_MAX); } - } /* --- Splines are not defined outside of [0,1]. So if the parametric coords are outside of * [0,1] the step was too big and we have to use a smaller relaxation factor. ---*/ - if ((config->GetFFD_Blending() == BSPLINE_UNIFORM) && - (((ParamCoord[0] < 0.0) || (ParamCoord[0] > 1.0)) || - ((ParamCoord[1] < 0.0) || (ParamCoord[1] > 1.0)) || + if ((config->GetFFD_Blending() == BSPLINE_UNIFORM) && + (((ParamCoord[0] < 0.0) || (ParamCoord[0] > 1.0)) || ((ParamCoord[1] < 0.0) || (ParamCoord[1] > 1.0)) || ((ParamCoord[2] < 0.0) || (ParamCoord[2] > 1.0)))) { - - for (iDim = 0; iDim < nDim; iDim++){ + for (iDim = 0; iDim < nDim; iDim++) { ParamCoord[iDim] = ParamCoordGuess[iDim]; } - SOR_Factor = 0.9*SOR_Factor; + SOR_Factor = 0.9 * SOR_Factor; } - } - for (iDim = 0; iDim < nDim; iDim++) - delete [] Hessian[iDim]; - delete [] Hessian; - delete [] IndepTerm; + for (iDim = 0; iDim < nDim; iDim++) delete[] Hessian[iDim]; + delete[] Hessian; + delete[] IndepTerm; /*--- The code has hit the max number of iterations ---*/ - if (iter == (unsigned long)it_max*Random_Trials) { - cout << "Unknown point: (" << xyz[0] <<", "<< xyz[1] <<", "<< xyz[2] <<"). Increase the value of FFD_ITERATIONS." << endl; + if (iter == (unsigned long)it_max * Random_Trials) { + cout << "Unknown point: (" << xyz[0] << ", " << xyz[1] << ", " << xyz[2] + << "). Increase the value of FFD_ITERATIONS." << endl; } /*--- Real Solution is now ParamCoord; Return it ---*/ return ParamCoord; - } -bool CFreeFormDefBox::GetPointFFD(CGeometry *geometry, CConfig *config, unsigned long iPoint) const { - +bool CFreeFormDefBox::GetPointFFD(CGeometry* geometry, CConfig* config, unsigned long iPoint) const { bool Inside = true; bool cylindrical = (config->GetFFD_CoordSystem() == CYLINDRICAL); bool spherical = (config->GetFFD_CoordSystem() == SPHERICAL); @@ -992,74 +1031,75 @@ bool CFreeFormDefBox::GetPointFFD(CGeometry *geometry, CConfig *config, unsigned /*--- indices of the FFD box. Note that the front face is labelled 0,1,2,3 and the back face is 4,5,6,7 ---*/ - unsigned short Index[6][5] = { - {0,1,2,3,0}, // front side - {1,5,6,2,1}, // right side - {2,6,7,3,2}, // top side - {3,7,4,0,3}, // left side - {4,5,1,0,4}, // bottom side - {4,7,6,5,4}}; // back side + unsigned short Index[6][5] = {{0, 1, 2, 3, 0}, // front side + {1, 5, 6, 2, 1}, // right side + {2, 6, 7, 3, 2}, // top side + {3, 7, 4, 0, 3}, // left side + {4, 5, 1, 0, 4}, // bottom side + {4, 7, 6, 5, 4}}; // back side /*--- The current approach is to subdivide each of the 6 faces of the hexahedral FFD box into 4 triangles by defining a supporting middle point. This allows nonplanar FFD boxes. - Note that the definition of the FFD box is as follows: the FFD box is a 6-sided die and we are looking at the side "1". - The opposite side is side "6". - If we are looking at side "1", we define the nodes counterclockwise. - If we are looking at side "6", we define the face clockwise ---*/ + Note that the definition of the FFD box is as follows: the FFD box is a 6-sided die and we are looking at the side + "1". The opposite side is side "6". If we are looking at side "1", we define the nodes counterclockwise. If we are + looking at side "6", we define the face clockwise ---*/ unsigned short nDim = geometry->GetnDim(); su2double Coord[3] = {0.0, 0.0, 0.0}; - for (unsigned short iDim = 0; iDim < nDim; iDim++) - Coord[iDim] = geometry->nodes->GetCoord(iPoint, iDim); + for (unsigned short iDim = 0; iDim < nDim; iDim++) Coord[iDim] = geometry->nodes->GetCoord(iPoint, iDim); su2double X_0, Y_0, Z_0, Xbar, Ybar, Zbar; if (cylindrical) { + X_0 = config->GetFFD_Axis(0); + Y_0 = config->GetFFD_Axis(1); + Z_0 = config->GetFFD_Axis(2); - X_0 = config->GetFFD_Axis(0); Y_0 = config->GetFFD_Axis(1); Z_0 = config->GetFFD_Axis(2); - - Xbar = Coord[0] - X_0; Ybar = Coord[1] - Y_0; Zbar = Coord[2] - Z_0; + Xbar = Coord[0] - X_0; + Ybar = Coord[1] - Y_0; + Zbar = Coord[2] - Z_0; - Coord[0] = sqrt(Ybar*Ybar + Zbar*Zbar); - Coord[1] = atan2(Zbar, Ybar); if (Coord[1] > PI_NUMBER/2.0) Coord[1] -= 2.0*PI_NUMBER; + Coord[0] = sqrt(Ybar * Ybar + Zbar * Zbar); + Coord[1] = atan2(Zbar, Ybar); + if (Coord[1] > PI_NUMBER / 2.0) Coord[1] -= 2.0 * PI_NUMBER; Coord[2] = Xbar; } else if (spherical || polar) { - - X_0 = config->GetFFD_Axis(0); Y_0 = config->GetFFD_Axis(1); Z_0 = config->GetFFD_Axis(2); - - Xbar = Coord[0] - X_0; Ybar = Coord[1] - Y_0; Zbar = Coord[2] - Z_0; - - Coord[0] = sqrt(Xbar*Xbar + Ybar*Ybar + Zbar*Zbar); - Coord[1] = atan2(Zbar, Ybar); if (Coord[1] > PI_NUMBER/2.0) Coord[1] -= 2.0*PI_NUMBER; - Coord[2] = acos(Xbar/Coord[0]); - + X_0 = config->GetFFD_Axis(0); + Y_0 = config->GetFFD_Axis(1); + Z_0 = config->GetFFD_Axis(2); + + Xbar = Coord[0] - X_0; + Ybar = Coord[1] - Y_0; + Zbar = Coord[2] - Z_0; + + Coord[0] = sqrt(Xbar * Xbar + Ybar * Ybar + Zbar * Zbar); + Coord[1] = atan2(Zbar, Ybar); + if (Coord[1] > PI_NUMBER / 2.0) Coord[1] -= 2.0 * PI_NUMBER; + Coord[2] = acos(Xbar / Coord[0]); } /*--- loop over the faces of the FFD box ---*/ for (unsigned short iVar = 0; iVar < 6; iVar++) { - su2double P[3] = {0.0, 0.0, 0.0}; /*--- every face needs an interpolated middle point for the triangles ---*/ - for (int p = 0; p < 4; p++){ - P[0] += 0.25*Coord_Corner_Points[Index[iVar][p]][0]; - P[1] += 0.25*Coord_Corner_Points[Index[iVar][p]][1]; - P[2] += 0.25*Coord_Corner_Points[Index[iVar][p]][2]; + for (int p = 0; p < 4; p++) { + P[0] += 0.25 * Coord_Corner_Points[Index[iVar][p]][0]; + P[1] += 0.25 * Coord_Corner_Points[Index[iVar][p]][1]; + P[2] += 0.25 * Coord_Corner_Points[Index[iVar][p]][2]; } /*--- loop over the 4 triangles making up the FFD box. The sign is equal for all distances ---*/ for (unsigned short jVar = 0; jVar < 4; jVar++) { - su2double Distance_Point = geometry->Point2Plane_Distance(Coord, - Coord_Corner_Points[Index[iVar][jVar]], - Coord_Corner_Points[Index[iVar][jVar+1]], - P); + su2double Distance_Point = geometry->Point2Plane_Distance(Coord, Coord_Corner_Points[Index[iVar][jVar]], + Coord_Corner_Points[Index[iVar][jVar + 1]], P); if (Distance_Point < 0) { Inside = false; return Inside; @@ -1068,104 +1108,97 @@ bool CFreeFormDefBox::GetPointFFD(CGeometry *geometry, CConfig *config, unsigned } return Inside; - } - -su2double CFreeFormDefBox::GetDerivative1(su2double *uvw, unsigned short val_diff, unsigned short *ijk, unsigned short *lmn) const { - +su2double CFreeFormDefBox::GetDerivative1(su2double* uvw, unsigned short val_diff, unsigned short* ijk, + unsigned short* lmn) const { unsigned short iDim; su2double value = 0.0; value = BlendingFunction[val_diff]->GetDerivative(ijk[val_diff], uvw[val_diff], 1); for (iDim = 0; iDim < nDim; iDim++) - if (iDim != val_diff) - value *= BlendingFunction[iDim]->GetBasis(ijk[iDim], uvw[iDim]); + if (iDim != val_diff) value *= BlendingFunction[iDim]->GetBasis(ijk[iDim], uvw[iDim]); return value; - } -su2double CFreeFormDefBox::GetDerivative2 (su2double *uvw, unsigned short dim, const su2double *xyz, const unsigned short *lmn) const { - +su2double CFreeFormDefBox::GetDerivative2(su2double* uvw, unsigned short dim, const su2double* xyz, + const unsigned short* lmn) const { unsigned short iDegree, jDegree, kDegree; su2double value = 0.0; for (iDegree = 0; iDegree <= lmn[0]; iDegree++) for (jDegree = 0; jDegree <= lmn[1]; jDegree++) for (kDegree = 0; kDegree <= lmn[2]; kDegree++) { - value += Coord_Control_Points[iDegree][jDegree][kDegree][dim] - * BlendingFunction[0]->GetBasis(iDegree, uvw[0]) - * BlendingFunction[1]->GetBasis(jDegree, uvw[1]) - * BlendingFunction[2]->GetBasis(kDegree, uvw[2]); + value += Coord_Control_Points[iDegree][jDegree][kDegree][dim] * BlendingFunction[0]->GetBasis(iDegree, uvw[0]) * + BlendingFunction[1]->GetBasis(jDegree, uvw[1]) * BlendingFunction[2]->GetBasis(kDegree, uvw[2]); } - return 2.0*(value - xyz[dim]); + return 2.0 * (value - xyz[dim]); } -su2double CFreeFormDefBox::GetDerivative3(su2double *uvw, unsigned short dim, unsigned short diff_this, unsigned short *lmn) { - +su2double CFreeFormDefBox::GetDerivative3(su2double* uvw, unsigned short dim, unsigned short diff_this, + unsigned short* lmn) { unsigned short iDegree, jDegree, kDegree, iDim; su2double value = 0; - unsigned short *ijk = new unsigned short[nDim]; + unsigned short* ijk = new unsigned short[nDim]; for (iDim = 0; iDim < nDim; iDim++) ijk[iDim] = 0; for (iDegree = 0; iDegree <= lmn[0]; iDegree++) for (jDegree = 0; jDegree <= lmn[1]; jDegree++) for (kDegree = 0; kDegree <= lmn[2]; kDegree++) { - ijk[0] = iDegree; ijk[1] = jDegree; ijk[2] = kDegree; - value += Coord_Control_Points[iDegree][jDegree][kDegree][dim] * - GetDerivative1(uvw, diff_this, ijk, lmn); + ijk[0] = iDegree; + ijk[1] = jDegree; + ijk[2] = kDegree; + value += Coord_Control_Points[iDegree][jDegree][kDegree][dim] * GetDerivative1(uvw, diff_this, ijk, lmn); } - delete [] ijk; + delete[] ijk; return value; } -su2double CFreeFormDefBox::GetDerivative4(su2double *uvw, unsigned short val_diff, unsigned short val_diff2, - unsigned short *ijk, unsigned short *lmn) const { +su2double CFreeFormDefBox::GetDerivative4(su2double* uvw, unsigned short val_diff, unsigned short val_diff2, + unsigned short* ijk, unsigned short* lmn) const { unsigned short iDim; su2double value = 0.0; if (val_diff == val_diff2) { value = BlendingFunction[val_diff]->GetDerivative(ijk[val_diff], uvw[val_diff], 2); for (iDim = 0; iDim < nDim; iDim++) - if (iDim != val_diff) - value *= BlendingFunction[iDim]->GetBasis(ijk[iDim], uvw[iDim]); - } - else { - value = BlendingFunction[val_diff]->GetDerivative(ijk[val_diff], uvw[val_diff],1) * - BlendingFunction[val_diff2]->GetDerivative(ijk[val_diff2], uvw[val_diff2], 1); + if (iDim != val_diff) value *= BlendingFunction[iDim]->GetBasis(ijk[iDim], uvw[iDim]); + } else { + value = BlendingFunction[val_diff]->GetDerivative(ijk[val_diff], uvw[val_diff], 1) * + BlendingFunction[val_diff2]->GetDerivative(ijk[val_diff2], uvw[val_diff2], 1); for (iDim = 0; iDim < nDim; iDim++) - if ((iDim != val_diff) && (iDim != val_diff2)) - value *= BlendingFunction[iDim]->GetBasis(ijk[iDim], uvw[iDim]); + if ((iDim != val_diff) && (iDim != val_diff2)) value *= BlendingFunction[iDim]->GetBasis(ijk[iDim], uvw[iDim]); } return value; } -su2double CFreeFormDefBox::GetDerivative5(su2double *uvw, unsigned short dim, unsigned short diff_this, unsigned short diff_this_also, - unsigned short *lmn) { - +su2double CFreeFormDefBox::GetDerivative5(su2double* uvw, unsigned short dim, unsigned short diff_this, + unsigned short diff_this_also, unsigned short* lmn) { unsigned short iDegree, jDegree, kDegree, iDim; su2double value = 0.0; - unsigned short *ijk = new unsigned short[nDim]; + unsigned short* ijk = new unsigned short[nDim]; for (iDim = 0; iDim < nDim; iDim++) ijk[iDim] = 0; for (iDegree = 0; iDegree <= lmn[0]; iDegree++) for (jDegree = 0; jDegree <= lmn[1]; jDegree++) for (kDegree = 0; kDegree <= lmn[2]; kDegree++) { - ijk[0] = iDegree; ijk[1] = jDegree; ijk[2] = kDegree; + ijk[0] = iDegree; + ijk[1] = jDegree; + ijk[2] = kDegree; value += Coord_Control_Points[iDegree][jDegree][kDegree][dim] * - GetDerivative4(uvw, diff_this, diff_this_also, ijk, lmn); + GetDerivative4(uvw, diff_this, diff_this_also, ijk, lmn); } - delete [] ijk; + delete[] ijk; return value; } diff --git a/Common/src/grid_movement/CGridMovement.cpp b/Common/src/grid_movement/CGridMovement.cpp index 3ead32ae339..656583439b4 100644 --- a/Common/src/grid_movement/CGridMovement.cpp +++ b/Common/src/grid_movement/CGridMovement.cpp @@ -27,6 +27,6 @@ #include "../../include/grid_movement/CGridMovement.hpp" -CGridMovement::CGridMovement(void) { } +CGridMovement::CGridMovement(void) {} -CGridMovement::~CGridMovement(void) { } +CGridMovement::~CGridMovement(void) {} diff --git a/Common/src/grid_movement/CSurfaceMovement.cpp b/Common/src/grid_movement/CSurfaceMovement.cpp index f4e7844ce32..0834e05c426 100644 --- a/Common/src/grid_movement/CSurfaceMovement.cpp +++ b/Common/src/grid_movement/CSurfaceMovement.cpp @@ -29,7 +29,6 @@ #include "../../include/toolboxes/C1DInterpolation.hpp" CSurfaceMovement::CSurfaceMovement(void) : CGridMovement() { - size = SU2_MPI::GetSize(); rank = SU2_MPI::GetRank(); @@ -40,18 +39,17 @@ CSurfaceMovement::CSurfaceMovement(void) : CGridMovement() { CSurfaceMovement::~CSurfaceMovement(void) {} -vector > CSurfaceMovement::SetSurface_Deformation(CGeometry *geometry, CConfig *config) { - +vector > CSurfaceMovement::SetSurface_Deformation(CGeometry* geometry, CConfig* config) { unsigned short iFFDBox, iDV, iLevel, iChild, iParent, jFFDBox, iMarker; - unsigned short Degree_Unitary [] = {1,1,1}, BSpline_Unitary [] = {2,2,2}; + unsigned short Degree_Unitary[] = {1, 1, 1}, BSpline_Unitary[] = {2, 2, 2}; su2double MaxDiff, Current_Scale, Ratio, New_Scale; string FFDBoxTag; bool allmoving; const bool cylindrical = (config->GetFFD_CoordSystem() == CYLINDRICAL); - const bool spherical = (config->GetFFD_CoordSystem() == SPHERICAL); - const bool polar = (config->GetFFD_CoordSystem() == POLAR); - const bool cartesian = (config->GetFFD_CoordSystem() == CARTESIAN); + const bool spherical = (config->GetFFD_CoordSystem() == SPHERICAL); + const bool polar = (config->GetFFD_CoordSystem() == POLAR); + const bool cartesian = (config->GetFFD_CoordSystem() == CARTESIAN); const su2double BoundLimit = config->GetOpt_LineSearch_Bound(); vector > totaldeformation; @@ -59,7 +57,6 @@ vector > CSurfaceMovement::SetSurface_Deformation(CGeometry *g /*--- Setting the Free Form Deformation ---*/ if (config->GetDesign_Variable(0) == FFD_SETTING) { - /*--- Definition of the FFD deformation class ---*/ FFDBox = new CFreeFormDefBox*[MAX_NUMBER_FFD]; @@ -71,15 +68,13 @@ vector > CSurfaceMovement::SetSurface_Deformation(CGeometry *g /*--- If there is a FFDBox in the input file ---*/ if (nFFDBox != 0) { - /*--- if polar coordinates, trnasform the corner to polar ---*/ if (cylindrical) { for (iFFDBox = 0; iFFDBox < GetnFFDBox(); iFFDBox++) { FFDBox[iFFDBox]->SetCart2Cyl_CornerPoints(config); } - } - else if (spherical || polar) { + } else if (spherical || polar) { for (iFFDBox = 0; iFFDBox < GetnFFDBox(); iFFDBox++) { FFDBox[iFFDBox]->SetCart2Sphe_CornerPoints(config); } @@ -88,10 +83,14 @@ vector > CSurfaceMovement::SetSurface_Deformation(CGeometry *g /*--- If the FFDBox was not defined in the input file ---*/ if ((rank == MASTER_NODE) && (GetnFFDBox() != 0)) { - if (cartesian) cout << endl <<"----------------- FFD technique (cartesian -> parametric) ---------------" << endl; - else if (cylindrical) cout << endl <<"----------------- FFD technique (cylinder -> parametric) ---------------" << endl; - else if (spherical) cout << endl <<"----------------- FFD technique (spherical -> parametric) ---------------" << endl; - else if (polar) cout << endl <<"----------------- FFD technique (polar -> parametric) ---------------" << endl; + if (cartesian) + cout << endl << "----------------- FFD technique (cartesian -> parametric) ---------------" << endl; + else if (cylindrical) + cout << endl << "----------------- FFD technique (cylinder -> parametric) ---------------" << endl; + else if (spherical) + cout << endl << "----------------- FFD technique (spherical -> parametric) ---------------" << endl; + else if (polar) + cout << endl << "----------------- FFD technique (polar -> parametric) ---------------" << endl; } /*--- Create a unitary FFDBox as baseline for other FFDBoxes shapes ---*/ @@ -104,7 +103,6 @@ vector > CSurfaceMovement::SetSurface_Deformation(CGeometry *g FFDBox_unitary.SetControlPoints_Parallelepiped(); for (iFFDBox = 0; iFFDBox < GetnFFDBox(); iFFDBox++) { - /*--- Compute the support control points for the final FFD using the unitary box ---*/ FFDBox_unitary.SetSupportCP(FFDBox[iFFDBox]); @@ -118,14 +116,12 @@ vector > CSurfaceMovement::SetSurface_Deformation(CGeometry *g SetParametricCoord(geometry, config, FFDBox[iFFDBox], iFFDBox); - /*--- If polar coordinates, transform the corners and control points to cartesians ---*/ if (cylindrical) { FFDBox[iFFDBox]->SetCyl2Cart_CornerPoints(config); FFDBox[iFFDBox]->SetCyl2Cart_ControlPoints(config); - } - else if (spherical || polar) { + } else if (spherical || polar) { FFDBox[iFFDBox]->SetSphe2Cart_CornerPoints(config); FFDBox[iFFDBox]->SetSphe2Cart_ControlPoints(config); } @@ -133,7 +129,7 @@ vector > CSurfaceMovement::SetSurface_Deformation(CGeometry *g /*--- Output original FFD FFDBox ---*/ if (rank == MASTER_NODE) { - for (unsigned short iFile = 0; iFile < config->GetnVolumeOutputFiles(); iFile++){ + for (unsigned short iFile = 0; iFile < config->GetnVolumeOutputFiles(); iFile++) { auto FileFormat = config->GetVolumeOutputFiles(); if (isParaview(FileFormat[iFile])) { cout << "Writing a Paraview file of the FFD boxes." << endl; @@ -145,8 +141,7 @@ vector > CSurfaceMovement::SetSurface_Deformation(CGeometry *g for (iFFDBox = 0; iFFDBox < GetnFFDBox(); iFFDBox++) { FFDBox[iFFDBox]->SetTecplot(geometry, iFFDBox, true); } - } - else if (FileFormat[iFile] == OUTPUT_TYPE::CGNS) { + } else if (FileFormat[iFile] == OUTPUT_TYPE::CGNS) { cout << "Writing a CGNS file of the FFD boxes." << endl; for (iFFDBox = 0; iFFDBox < GetnFFDBox(); iFFDBox++) { FFDBox[iFFDBox]->SetCGNS(geometry, iFFDBox, true); @@ -159,25 +154,17 @@ vector > CSurfaceMovement::SetSurface_Deformation(CGeometry *g else { SU2_MPI::Error("There are no FFD boxes in the mesh file!!", CURRENT_FUNCTION); } - } /*--- Free Form deformation based ---*/ - if ((config->GetDesign_Variable(0) == FFD_CONTROL_POINT_2D) || - (config->GetDesign_Variable(0) == FFD_CAMBER_2D) || - (config->GetDesign_Variable(0) == FFD_THICKNESS_2D) || - (config->GetDesign_Variable(0) == FFD_TWIST_2D) || - (config->GetDesign_Variable(0) == FFD_CONTROL_POINT) || - (config->GetDesign_Variable(0) == FFD_NACELLE) || - (config->GetDesign_Variable(0) == FFD_GULL) || - (config->GetDesign_Variable(0) == FFD_TWIST) || - (config->GetDesign_Variable(0) == FFD_ROTATION) || - (config->GetDesign_Variable(0) == FFD_CONTROL_SURFACE) || - (config->GetDesign_Variable(0) == FFD_CAMBER) || - (config->GetDesign_Variable(0) == FFD_THICKNESS) || + if ((config->GetDesign_Variable(0) == FFD_CONTROL_POINT_2D) || (config->GetDesign_Variable(0) == FFD_CAMBER_2D) || + (config->GetDesign_Variable(0) == FFD_THICKNESS_2D) || (config->GetDesign_Variable(0) == FFD_TWIST_2D) || + (config->GetDesign_Variable(0) == FFD_CONTROL_POINT) || (config->GetDesign_Variable(0) == FFD_NACELLE) || + (config->GetDesign_Variable(0) == FFD_GULL) || (config->GetDesign_Variable(0) == FFD_TWIST) || + (config->GetDesign_Variable(0) == FFD_ROTATION) || (config->GetDesign_Variable(0) == FFD_CONTROL_SURFACE) || + (config->GetDesign_Variable(0) == FFD_CAMBER) || (config->GetDesign_Variable(0) == FFD_THICKNESS) || (config->GetDesign_Variable(0) == FFD_ANGLE_OF_ATTACK)) { - /*--- Definition of the FFD deformation class ---*/ FFDBox = new CFreeFormDefBox*[MAX_NUMBER_FFD]; @@ -189,20 +176,22 @@ vector > CSurfaceMovement::SetSurface_Deformation(CGeometry *g /*--- If there is a FFDBox in the input file ---*/ if (nFFDBox != 0) { - /*--- If the FFDBox was not defined in the input file ---*/ if (!GetFFDBoxDefinition()) { - SU2_MPI::Error(string("There is not FFD box definition in the mesh file,\n") + - string("run DV_KIND=FFD_SETTING first !!"), CURRENT_FUNCTION); + SU2_MPI::Error( + string("There is not FFD box definition in the mesh file,\n") + string("run DV_KIND=FFD_SETTING first !!"), + CURRENT_FUNCTION); } /* --- Check if the FFD boxes referenced in the design variable definition can be found --- */ for (iDV = 0; iDV < config->GetnDV(); iDV++) { if (!CheckFFDBoxDefinition(config, iDV)) { - SU2_MPI::Error(string("There is no FFD box with tag \"") + config->GetFFDTag(iDV) + string("\" defined in the mesh file.\n") + - string("Check the definition of the design variables and/or the FFD settings !!"), CURRENT_FUNCTION); + SU2_MPI::Error(string("There is no FFD box with tag \"") + config->GetFFDTag(iDV) + + string("\" defined in the mesh file.\n") + + string("Check the definition of the design variables and/or the FFD settings !!"), + CURRENT_FUNCTION); } } @@ -210,14 +199,14 @@ vector > CSurfaceMovement::SetSurface_Deformation(CGeometry *g if (config->GetnMarker_DV() == 0) { SU2_MPI::Error(string("No markers are specified in DV_MARKER, so no deformation will occur.\n") + - string("List markers to be deformed in DV_MARKER."), CURRENT_FUNCTION); + string("List markers to be deformed in DV_MARKER."), + CURRENT_FUNCTION); } /*--- Output original FFD FFDBox ---*/ if ((rank == MASTER_NODE) && (config->GetKind_SU2() != SU2_COMPONENT::SU2_DOT)) { - - for (unsigned short iFile = 0; iFile < config->GetnVolumeOutputFiles(); iFile++){ + for (unsigned short iFile = 0; iFile < config->GetnVolumeOutputFiles(); iFile++) { auto FileFormat = config->GetVolumeOutputFiles(); if (isParaview(FileFormat[iFile])) { @@ -230,8 +219,7 @@ vector > CSurfaceMovement::SetSurface_Deformation(CGeometry *g for (iFFDBox = 0; iFFDBox < GetnFFDBox(); iFFDBox++) { FFDBox[iFFDBox]->SetTecplot(geometry, iFFDBox, true); } - } - else if (FileFormat[iFile] == OUTPUT_TYPE::CGNS) { + } else if (FileFormat[iFile] == OUTPUT_TYPE::CGNS) { cout << "Writing a CGNS file of the FFD boxes." << endl; for (iFFDBox = 0; iFFDBox < GetnFFDBox(); iFFDBox++) { FFDBox[iFFDBox]->SetCGNS(geometry, iFFDBox, true); @@ -247,8 +235,7 @@ vector > CSurfaceMovement::SetSurface_Deformation(CGeometry *g FFDBox[iFFDBox]->SetCart2Cyl_CornerPoints(config); FFDBox[iFFDBox]->SetCart2Cyl_ControlPoints(config); } - } - else if (spherical || polar) { + } else if (spherical || polar) { for (iFFDBox = 0; iFFDBox < GetnFFDBox(); iFFDBox++) { FFDBox[iFFDBox]->SetCart2Sphe_CornerPoints(config); FFDBox[iFFDBox]->SetCart2Sphe_ControlPoints(config); @@ -258,20 +245,17 @@ vector > CSurfaceMovement::SetSurface_Deformation(CGeometry *g /*--- Apply the deformation to the orifinal FFD box ---*/ if ((rank == MASTER_NODE) && (GetnFFDBox() != 0)) - cout << endl <<"----------------- FFD technique (parametric -> cartesian) ---------------" << endl; + cout << endl << "----------------- FFD technique (parametric -> cartesian) ---------------" << endl; /*--- Loop over all the FFD boxes levels ---*/ for (iLevel = 0; iLevel < GetnLevel(); iLevel++) { - /*--- Loop over all FFD FFDBoxes ---*/ for (iFFDBox = 0; iFFDBox < GetnFFDBox(); iFFDBox++) { - /*--- Check the level of the FFD box ---*/ if (FFDBox[iFFDBox]->GetLevel() == iLevel) { - /*--- Check the dimension of the FFD compared with the design variables ---*/ if (rank == MASTER_NODE) cout << "Checking FFD box dimension." << endl; @@ -305,12 +289,12 @@ vector > CSurfaceMovement::SetSurface_Deformation(CGeometry *g MaxDiff = SetCartesianCoord(geometry, config, FFDBox[iFFDBox], iFFDBox, false); if ((MaxDiff > BoundLimit) && (config->GetKind_SU2() == SU2_COMPONENT::SU2_DEF)) { - - if (rank == MASTER_NODE) cout << "Out-of-bounds, re-adjusting scale factor to safisfy line search limit." << endl; + if (rank == MASTER_NODE) + cout << "Out-of-bounds, re-adjusting scale factor to safisfy line search limit." << endl; Current_Scale = config->GetOpt_RelaxFactor(); - Ratio = (BoundLimit/MaxDiff); - New_Scale = Current_Scale *(Ratio-1.0); + Ratio = (BoundLimit / MaxDiff); + New_Scale = Current_Scale * (Ratio - 1.0); config->SetOpt_RelaxFactor(New_Scale); /*--- Apply the design variables to the control point position ---*/ @@ -319,12 +303,10 @@ vector > CSurfaceMovement::SetSurface_Deformation(CGeometry *g /*--- Recompute cartesian coordinates using the new control point location ---*/ MaxDiff = SetCartesianCoord(geometry, config, FFDBox[iFFDBox], iFFDBox, false); - } /*--- Set total deformation values in config ---*/ if (config->GetKind_SU2() == SU2_COMPONENT::SU2_DEF) { - totaldeformation.resize(config->GetnDV()); for (iDV = 0; iDV < config->GetnDV(); iDV++) { totaldeformation[iDV].resize(config->GetnDV_Value(iDV)); @@ -352,7 +334,6 @@ vector > CSurfaceMovement::SetSurface_Deformation(CGeometry *g /*--- If enabled: start recursive procedure to decrease deformation magnitude to remove self-intersections in FFD box ---*/ if (nNegativeDeterminants > 0) { - if (rank == MASTER_NODE) { cout << "Self-intersections within FFD box present. "; cout << "Performing iterative deformation reduction procedure." << endl; @@ -362,8 +343,8 @@ vector > CSurfaceMovement::SetSurface_Deformation(CGeometry *g for (iDV = 0; iDV < config->GetnDV(); iDV++) { for (auto iDV_Value = 0u; iDV_Value < config->GetnDV_Value(iDV); iDV_Value++) { auto dv_value = config->GetDV_Value(iDV, iDV_Value); - config->SetDV_Value(iDV, iDV_Value, -dv_value/2); - totaldeformation[iDV][iDV_Value] -= dv_value/2; + config->SetDV_Value(iDV, iDV_Value, -dv_value / 2); + totaldeformation[iDV][iDV_Value] -= dv_value / 2; } } @@ -374,18 +355,16 @@ vector > CSurfaceMovement::SetSurface_Deformation(CGeometry *g /*--- Recursively check for self-intersections. ---*/ unsigned short FFD_IntPrev_Iter, FFD_IntPrev_Depth = 0; - for (FFD_IntPrev_Iter = 1; FFD_IntPrev_Iter <= FFD_IntPrev_MaxIter; FFD_IntPrev_Iter++){ - + for (FFD_IntPrev_Iter = 1; FFD_IntPrev_Iter <= FFD_IntPrev_MaxIter; FFD_IntPrev_Iter++) { if (rank == MASTER_NODE) cout << "Checking FFD box intersections with the solid surfaces." << endl; - CheckFFDIntersections(geometry, config, FFDBox[iFFDBox], iFFDBox); + CheckFFDIntersections(geometry, config, FFDBox[iFFDBox], iFFDBox); /*--- Compute the parametric coordinates of the child box control points (using the parent FFDBox) ---*/ for (iChild = 0; iChild < FFDBox[iFFDBox]->GetnChildFFDBox(); iChild++) { FFDBoxTag = FFDBox[iFFDBox]->GetChildFFDBoxTag(iChild); for (jFFDBox = 0; jFFDBox < GetnFFDBox(); jFFDBox++) - if (FFDBoxTag == FFDBox[jFFDBox]->GetTag()) - break; + if (FFDBoxTag == FFDBox[jFFDBox]->GetTag()) break; SetParametricCoordCP(geometry, config, FFDBox[iFFDBox], FFDBox[jFFDBox]); } @@ -405,13 +384,14 @@ vector > CSurfaceMovement::SetSurface_Deformation(CGeometry *g if (rank == MASTER_NODE) { cout << "Amount of points with negative Jacobian determinant for iteration "; cout << FFD_IntPrev_Iter << ": " << nNegativeDeterminants << endl; - cout << "Remaining amount of original deformation: " << DeformationFactor*100.0 << " percent." << endl; + cout << "Remaining amount of original deformation: " << DeformationFactor * 100.0 << " percent." + << endl; } /*--- Recursively change deformation magnitude. Increase if there are no points with negative determinants, decrease otherwise. ---*/ - if (nNegativeDeterminants == 0){ - DeformationDifference = abs(DeformationDifference/2.0); + if (nNegativeDeterminants == 0) { + DeformationDifference = abs(DeformationDifference / 2.0); /*--- Update recursion depth if there are no points with negative determinant. Quit if maximum depth is reached. ---*/ @@ -421,12 +401,12 @@ vector > CSurfaceMovement::SetSurface_Deformation(CGeometry *g if (rank == MASTER_NODE) { cout << "Maximum recursion depth reached." << endl; cout << "Remaining amount of original deformation: " << endl; - cout << DeformationFactor*100.0 << " percent." << endl; + cout << DeformationFactor * 100.0 << " percent." << endl; } break; } } else { - DeformationDifference = -abs(DeformationDifference/2.0); + DeformationDifference = -abs(DeformationDifference / 2.0); } if (FFD_IntPrev_Iter < FFD_IntPrev_MaxIter) { @@ -438,23 +418,22 @@ vector > CSurfaceMovement::SetSurface_Deformation(CGeometry *g if (FFD_IntPrev_Iter < FFD_IntPrev_MaxIter) { su2double sign = -1.0; if ((nNegativeDeterminants_previous > 0 && nNegativeDeterminants > 0) || - (nNegativeDeterminants_previous == 0 && nNegativeDeterminants == 0)){ + (nNegativeDeterminants_previous == 0 && nNegativeDeterminants == 0)) { sign = 1.0; } for (iDV = 0; iDV < config->GetnDV(); iDV++) { for (auto iDV_Value = 0u; iDV_Value < config->GetnDV_Value(iDV); iDV_Value++) { auto dv_value = sign * config->GetDV_Value(iDV, iDV_Value); - config->SetDV_Value(iDV, iDV_Value, dv_value/2.0); - totaldeformation[iDV][iDV_Value] += dv_value/2.0; + config->SetDV_Value(iDV, iDV_Value, dv_value / 2.0); + totaldeformation[iDV][iDV_Value] += dv_value / 2.0; } } } nNegativeDeterminants_previous = nNegativeDeterminants; } - } - } // end SU2_DEF + } // end SU2_DEF /*--- Reparametrization of the parent FFD box ---*/ @@ -484,8 +463,7 @@ vector > CSurfaceMovement::SetSurface_Deformation(CGeometry *g FFDBox[iFFDBox]->SetCyl2Cart_CornerPoints(config); FFDBox[iFFDBox]->SetCyl2Cart_ControlPoints(config); } - } - else if (spherical || polar) { + } else if (spherical || polar) { for (iFFDBox = 0; iFFDBox < GetnFFDBox(); iFFDBox++) { FFDBox[iFFDBox]->SetSphe2Cart_CornerPoints(config); FFDBox[iFFDBox]->SetSphe2Cart_ControlPoints(config); @@ -495,8 +473,7 @@ vector > CSurfaceMovement::SetSurface_Deformation(CGeometry *g /*--- Output the deformed FFD Boxes ---*/ if ((rank == MASTER_NODE) && (config->GetKind_SU2() != SU2_COMPONENT::SU2_DOT)) { - - for (unsigned short iFile = 0; iFile < config->GetnVolumeOutputFiles(); iFile++){ + for (unsigned short iFile = 0; iFile < config->GetnVolumeOutputFiles(); iFile++) { auto FileFormat = config->GetVolumeOutputFiles(); if (isParaview(FileFormat[iFile])) { @@ -509,8 +486,7 @@ vector > CSurfaceMovement::SetSurface_Deformation(CGeometry *g for (iFFDBox = 0; iFFDBox < GetnFFDBox(); iFFDBox++) { FFDBox[iFFDBox]->SetTecplot(geometry, iFFDBox, false); } - } - else if (FileFormat[iFile] == OUTPUT_TYPE::CGNS) { + } else if (FileFormat[iFile] == OUTPUT_TYPE::CGNS) { cout << "Writing a CGNS file of the FFD boxes." << endl; for (iFFDBox = 0; iFFDBox < GetnFFDBox(); iFFDBox++) { FFDBox[iFFDBox]->SetCGNS(geometry, iFFDBox, false); @@ -530,7 +506,6 @@ vector > CSurfaceMovement::SetSurface_Deformation(CGeometry *g /*--- External surface file based ---*/ else if (config->GetDesign_Variable(0) == SURFACE_FILE) { - /*--- Check whether a surface file exists for input ---*/ ofstream Surface_File; string filename = config->GetDV_Filename(); @@ -539,13 +514,13 @@ vector > CSurfaceMovement::SetSurface_Deformation(CGeometry *g /*--- A surface file does not exist, so write a new one for the markers that are specified as part of the motion. ---*/ if (Surface_File.fail()) { - if (rank == MASTER_NODE && size == SINGLE_NODE) { cout << "No surface positions file found. Writing a template file: " << filename << "." << endl; Surface_File.open(filename.c_str(), ios::out); Surface_File.precision(15); - unsigned long iMarker, jPoint, GlobalIndex, iVertex; su2double *Coords; + unsigned long iMarker, jPoint, GlobalIndex, iVertex; + su2double* Coords; for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { if (config->GetMarker_All_DV(iMarker) == YES) { for (iVertex = 0; iVertex < geometry->nVertex[iMarker]; iVertex++) { @@ -553,15 +528,20 @@ vector > CSurfaceMovement::SetSurface_Deformation(CGeometry *g GlobalIndex = geometry->nodes->GetGlobalIndex(jPoint); Coords = geometry->nodes->GetCoord(jPoint); Surface_File << GlobalIndex << "\t" << Coords[0] << "\t" << Coords[1]; - if (geometry->GetnDim() == 2) Surface_File << endl; - else Surface_File << "\t" << Coords[2] << endl; + if (geometry->GetnDim() == 2) + Surface_File << endl; + else + Surface_File << "\t" << Coords[2] << endl; } } } Surface_File.close(); } else { - SU2_MPI::Error("No surface positions file found and template writing not yet supported in parallel.\n To generate a template surface positions file, run SU2_DEF again in serial.", CURRENT_FUNCTION); + SU2_MPI::Error( + "No surface positions file found and template writing not yet supported in parallel.\n To generate a " + "template surface positions file, run SU2_DEF again in serial.", + CURRENT_FUNCTION); } } @@ -574,45 +554,53 @@ vector > CSurfaceMovement::SetSurface_Deformation(CGeometry *g } - else if ((config->GetDesign_Variable(0) == ROTATION) || - (config->GetDesign_Variable(0) == TRANSLATION) || - (config->GetDesign_Variable(0) == SCALE) || - (config->GetDesign_Variable(0) == HICKS_HENNE) || - (config->GetDesign_Variable(0) == SURFACE_BUMP) || - (config->GetDesign_Variable(0) == ANGLE_OF_ATTACK)) { - + else if ((config->GetDesign_Variable(0) == ROTATION) || (config->GetDesign_Variable(0) == TRANSLATION) || + (config->GetDesign_Variable(0) == SCALE) || (config->GetDesign_Variable(0) == HICKS_HENNE) || + (config->GetDesign_Variable(0) == SURFACE_BUMP) || (config->GetDesign_Variable(0) == ANGLE_OF_ATTACK)) { /*--- Apply rotation, displacement and stretching design variables (this should be done before the bump function design variables) ---*/ for (iDV = 0; iDV < config->GetnDV(); iDV++) { - switch ( config->GetDesign_Variable(iDV) ) { - case SCALE : SetScale(geometry, config, iDV, false); break; - case TRANSLATION : SetTranslation(geometry, config, iDV, false); break; - case ROTATION : SetRotation(geometry, config, iDV, false); break; + switch (config->GetDesign_Variable(iDV)) { + case SCALE: + SetScale(geometry, config, iDV, false); + break; + case TRANSLATION: + SetTranslation(geometry, config, iDV, false); + break; + case ROTATION: + SetRotation(geometry, config, iDV, false); + break; } } /*--- Apply the design variables to the control point position ---*/ for (iDV = 0; iDV < config->GetnDV(); iDV++) { - switch ( config->GetDesign_Variable(iDV) ) { - case HICKS_HENNE : SetHicksHenne(geometry, config, iDV, false); break; + switch (config->GetDesign_Variable(iDV)) { + case HICKS_HENNE: + SetHicksHenne(geometry, config, iDV, false); + break; } } /*--- Apply the design variables to the control point position ---*/ for (iDV = 0; iDV < config->GetnDV(); iDV++) { - switch ( config->GetDesign_Variable(iDV) ) { - case SURFACE_BUMP : SetSurface_Bump(geometry, config, iDV, false); break; + switch (config->GetDesign_Variable(iDV)) { + case SURFACE_BUMP: + SetSurface_Bump(geometry, config, iDV, false); + break; } } /*--- Apply the angle of attack design variable ---*/ for (iDV = 0; iDV < config->GetnDV(); iDV++) { - switch ( config->GetDesign_Variable(iDV) ) { - case ANGLE_OF_ATTACK : SetAngleOfAttack(geometry, config, iDV, false); break; + switch (config->GetDesign_Variable(iDV)) { + case ANGLE_OF_ATTACK: + SetAngleOfAttack(geometry, config, iDV, false); + break; } } @@ -620,29 +608,32 @@ vector > CSurfaceMovement::SetSurface_Deformation(CGeometry *g /*--- NACA_4Digits design variable ---*/ - else if (config->GetDesign_Variable(0) == NACA_4DIGITS) { SetNACA_4Digits(geometry, config); } + else if (config->GetDesign_Variable(0) == NACA_4DIGITS) { + SetNACA_4Digits(geometry, config); + } /*--- Parabolic airfoil design variable ---*/ - else if (config->GetDesign_Variable(0) == PARABOLIC) { SetParabolic(geometry, config); } + else if (config->GetDesign_Variable(0) == PARABOLIC) { + SetParabolic(geometry, config); + } /*--- Airfoil from file design variable ---*/ - else if (config->GetDesign_Variable(0) == AIRFOIL) { SetAirfoil(geometry, config); } + else if (config->GetDesign_Variable(0) == AIRFOIL) { + SetAirfoil(geometry, config); + } /*--- FFD setting ---*/ else if (config->GetDesign_Variable(0) == FFD_SETTING) { - if (rank == MASTER_NODE) - cout << "No surface deformation (setting FFD)." << endl; + if (rank == MASTER_NODE) cout << "No surface deformation (setting FFD)." << endl; } /*--- Scale, Translate, and Rotate will be done with rigid mesh transforms. ---*/ - else if ((config->GetDesign_Variable(0) == ROTATION) || - (config->GetDesign_Variable(0) == TRANSLATION) || + else if ((config->GetDesign_Variable(0) == ROTATION) || (config->GetDesign_Variable(0) == TRANSLATION) || (config->GetDesign_Variable(0) == SCALE)) { - /*--- If all markers are deforming, use volume method. If only some are deforming, use surface method ---*/ @@ -653,52 +644,41 @@ vector > CSurfaceMovement::SetSurface_Deformation(CGeometry *g /*--- Loop over markers ---*/ for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { - if (config->GetMarker_All_DV(iMarker) == NO) - allmoving = false; + if (config->GetMarker_All_DV(iMarker) == NO) allmoving = false; } if (!allmoving) { /*---Only some markers are moving, use the surface method ---*/ - if (config->GetDesign_Variable(0) == ROTATION) - SetRotation(geometry, config, iDV, false); - if (config->GetDesign_Variable(0) == SCALE) - SetScale(geometry, config, iDV, false); - if (config->GetDesign_Variable(0) == TRANSLATION) - SetTranslation(geometry, config, iDV, false); - } - else { - if (rank == MASTER_NODE) - cout << "No surface deformation (scaling, rotation, or translation)." << endl; + if (config->GetDesign_Variable(0) == ROTATION) SetRotation(geometry, config, iDV, false); + if (config->GetDesign_Variable(0) == SCALE) SetScale(geometry, config, iDV, false); + if (config->GetDesign_Variable(0) == TRANSLATION) SetTranslation(geometry, config, iDV, false); + } else { + if (rank == MASTER_NODE) cout << "No surface deformation (scaling, rotation, or translation)." << endl; } } /*--- Design variable not implement ---*/ else { - if (rank == MASTER_NODE) - cout << "Design Variable not implemented yet" << endl; + if (rank == MASTER_NODE) cout << "Design Variable not implemented yet" << endl; } return totaldeformation; } - -void CSurfaceMovement::SetSurface_Derivative(CGeometry *geometry, CConfig *config) { - +void CSurfaceMovement::SetSurface_Derivative(CGeometry* geometry, CConfig* config) { su2double DV_Value = 0.0; unsigned short iDV = 0, iDV_Value = 0; for (iDV = 0; iDV < config->GetnDV(); iDV++) { for (iDV_Value = 0; iDV_Value < config->GetnDV_Value(iDV); iDV_Value++) { - DV_Value = config->GetDV_Value(iDV, iDV_Value); /*--- If value of the design variable is not 0.0 we apply the differentation. - * Note if multiple variables are non-zero, we end up with the sum of all the derivatives. ---*/ + * Note if multiple variables are non-zero, we end up with the sum of all the derivatives. ---*/ if (DV_Value != 0.0) { - DV_Value = 0.0; SU2_TYPE::SetDerivative(DV_Value, 1.0); @@ -713,11 +693,10 @@ void CSurfaceMovement::SetSurface_Derivative(CGeometry *geometry, CConfig *confi SetSurface_Deformation(geometry, config); } -void CSurfaceMovement::CopyBoundary(CGeometry *geometry, CConfig *config) { - +void CSurfaceMovement::CopyBoundary(CGeometry* geometry, CConfig* config) { unsigned short iMarker; unsigned long iVertex, iPoint; - su2double *Coord; + su2double* Coord; for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { for (iVertex = 0; iVertex < geometry->nVertex[iMarker]; iVertex++) { @@ -726,11 +705,10 @@ void CSurfaceMovement::CopyBoundary(CGeometry *geometry, CConfig *config) { geometry->vertex[iMarker][iVertex]->SetCoord(Coord); } } - } -void CSurfaceMovement::SetParametricCoord(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox, unsigned short iFFDBox) { - +void CSurfaceMovement::SetParametricCoord(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBox, + unsigned short iFFDBox) { unsigned short iMarker, iDim, iOrder, jOrder, kOrder, lOrder, mOrder, nOrder; unsigned long iVertex, iPoint, TotalVertex = 0; su2double *CartCoordNew, *ParamCoord, CartCoord[3], ParamCoordGuess[3], MaxDiff, my_MaxDiff = 0.0, Diff, *Coord; @@ -747,25 +725,32 @@ void CSurfaceMovement::SetParametricCoord(CGeometry *geometry, CConfig *config, in case of Bezier curves, and we maintain an internal copy)---*/ if (BoxFFD && (config->GetFFD_Blending() == BEZIER)) { - for (iOrder = 0; iOrder < 2; iOrder++) { for (jOrder = 0; jOrder < 2; jOrder++) { for (kOrder = 0; kOrder < 2; kOrder++) { - - lOrder = 0; mOrder = 0; nOrder = 0; - if (iOrder == 1) {lOrder = FFDBox->GetlOrder()-1;} - if (jOrder == 1) {mOrder = FFDBox->GetmOrder()-1;} - if (kOrder == 1) {nOrder = FFDBox->GetnOrder()-1;} + lOrder = 0; + mOrder = 0; + nOrder = 0; + if (iOrder == 1) { + lOrder = FFDBox->GetlOrder() - 1; + } + if (jOrder == 1) { + mOrder = FFDBox->GetmOrder() - 1; + } + if (kOrder == 1) { + nOrder = FFDBox->GetnOrder() - 1; + } Coord = FFDBox->GetCoordControlPoints(lOrder, mOrder, nOrder); FFDBox->SetCoordControlPoints(Coord, iOrder, jOrder, kOrder); - } } } - FFDBox->SetlOrder(2); FFDBox->SetmOrder(2); FFDBox->SetnOrder(2); + FFDBox->SetlOrder(2); + FFDBox->SetmOrder(2); + FFDBox->SetnOrder(2); FFDBox->SetnControlPoints(); FFDBox->BlendingFunction[0]->SetOrder(2, 2); FFDBox->BlendingFunction[1]->SetOrder(2, 2); @@ -773,44 +758,54 @@ void CSurfaceMovement::SetParametricCoord(CGeometry *geometry, CConfig *config, } /*--- Point inversion algorithm with a basic box ---*/ - ParamCoordGuess[0] = 0.5; ParamCoordGuess[1] = 0.5; ParamCoordGuess[2] = 0.5; - CartCoord[0] = 0.0; CartCoord[1] = 0.0; CartCoord[2] = 0.0; + ParamCoordGuess[0] = 0.5; + ParamCoordGuess[1] = 0.5; + ParamCoordGuess[2] = 0.5; + CartCoord[0] = 0.0; + CartCoord[1] = 0.0; + CartCoord[2] = 0.0; /*--- Count the number of vertices ---*/ for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) if (config->GetMarker_All_DV(iMarker) == YES) - for (iVertex = 0; iVertex < geometry->nVertex[iMarker]; iVertex++) - TotalVertex++; + for (iVertex = 0; iVertex < geometry->nVertex[iMarker]; iVertex++) TotalVertex++; for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { if (config->GetMarker_All_DV(iMarker) == YES) { for (iVertex = 0; iVertex < geometry->nVertex[iMarker]; iVertex++) { - /*--- Get the cartesian coordinates ---*/ - for (iDim = 0; iDim < nDim; iDim++) - CartCoord[iDim] = geometry->vertex[iMarker][iVertex]->GetCoord(iDim); + for (iDim = 0; iDim < nDim; iDim++) CartCoord[iDim] = geometry->vertex[iMarker][iVertex]->GetCoord(iDim); /*--- Transform the cartesian into polar ---*/ if (cylindrical) { - X_0 = config->GetFFD_Axis(0); Y_0 = config->GetFFD_Axis(1); Z_0 = config->GetFFD_Axis(2); + X_0 = config->GetFFD_Axis(0); + Y_0 = config->GetFFD_Axis(1); + Z_0 = config->GetFFD_Axis(2); - Xbar = CartCoord[0] - X_0; Ybar = CartCoord[1] - Y_0; Zbar = CartCoord[2] - Z_0; + Xbar = CartCoord[0] - X_0; + Ybar = CartCoord[1] - Y_0; + Zbar = CartCoord[2] - Z_0; - CartCoord[0] = sqrt(Ybar*Ybar + Zbar*Zbar); - CartCoord[1] = atan2(Zbar, Ybar); if (CartCoord[1] > PI_NUMBER/2.0) CartCoord[1] -= 2.0*PI_NUMBER; + CartCoord[0] = sqrt(Ybar * Ybar + Zbar * Zbar); + CartCoord[1] = atan2(Zbar, Ybar); + if (CartCoord[1] > PI_NUMBER / 2.0) CartCoord[1] -= 2.0 * PI_NUMBER; CartCoord[2] = Xbar; - } - else if (spherical || polar) { - X_0 = config->GetFFD_Axis(0); Y_0 = config->GetFFD_Axis(1); Z_0 = config->GetFFD_Axis(2); - - Xbar = CartCoord[0] - X_0; Ybar = CartCoord[1] - Y_0; Zbar = CartCoord[2] - Z_0; - - CartCoord[0] = sqrt(Xbar*Xbar + Ybar*Ybar + Zbar*Zbar); - CartCoord[1] = atan2(Zbar, Ybar); if (CartCoord[1] > PI_NUMBER/2.0) CartCoord[1] -= 2.0*PI_NUMBER; - CartCoord[2] = acos(Xbar/CartCoord[0]); + } else if (spherical || polar) { + X_0 = config->GetFFD_Axis(0); + Y_0 = config->GetFFD_Axis(1); + Z_0 = config->GetFFD_Axis(2); + + Xbar = CartCoord[0] - X_0; + Ybar = CartCoord[1] - Y_0; + Zbar = CartCoord[2] - Z_0; + + CartCoord[0] = sqrt(Xbar * Xbar + Ybar * Ybar + Zbar * Zbar); + CartCoord[1] = atan2(Zbar, Ybar); + if (CartCoord[1] > PI_NUMBER / 2.0) CartCoord[1] -= 2.0 * PI_NUMBER; + CartCoord[2] = acos(Xbar / CartCoord[0]); } iPoint = geometry->vertex[iMarker][iVertex]->GetNode(); @@ -818,7 +813,6 @@ void CSurfaceMovement::SetParametricCoord(CGeometry *geometry, CConfig *config, /*--- If the point is inside the FFD, compute the value of the parametric coordinate ---*/ if (FFDBox->GetPointFFD(geometry, config, iPoint)) { - /*--- Find the parametric coordinate ---*/ ParamCoord = FFDBox->GetParametricCoord_Iterative(iPoint, CartCoord, ParamCoordGuess, config); @@ -832,22 +826,21 @@ void CSurfaceMovement::SetParametricCoord(CGeometry *geometry, CConfig *config, Diff = 0.0; for (iDim = 0; iDim < nDim; iDim++) - Diff += (CartCoordNew[iDim]-CartCoord[iDim])*(CartCoordNew[iDim]-CartCoord[iDim]); + Diff += (CartCoordNew[iDim] - CartCoord[iDim]) * (CartCoordNew[iDim] - CartCoord[iDim]); Diff = sqrt(Diff); my_MaxDiff = max(my_MaxDiff, Diff); - /*--- If the parametric coordinates are in (0,1) the point belongs to the FFDBox, using the input tolerance ---*/ - - if (((ParamCoord[0] >= - config->GetFFD_Tol()) && (ParamCoord[0] <= 1.0 + config->GetFFD_Tol())) && - ((ParamCoord[1] >= - config->GetFFD_Tol()) && (ParamCoord[1] <= 1.0 + config->GetFFD_Tol())) && - ((ParamCoord[2] >= - config->GetFFD_Tol()) && (ParamCoord[2] <= 1.0 + config->GetFFD_Tol()))) { - + /*--- If the parametric coordinates are in (0,1) the point belongs to the FFDBox, using the input tolerance + * ---*/ + if (((ParamCoord[0] >= -config->GetFFD_Tol()) && (ParamCoord[0] <= 1.0 + config->GetFFD_Tol())) && + ((ParamCoord[1] >= -config->GetFFD_Tol()) && (ParamCoord[1] <= 1.0 + config->GetFFD_Tol())) && + ((ParamCoord[2] >= -config->GetFFD_Tol()) && (ParamCoord[2] <= 1.0 + config->GetFFD_Tol()))) { /*--- Rectification of the initial tolerance (we have detected situations where 0.0 and 1.0 doesn't work properly ---*/ su2double lower_limit = config->GetFFD_Tol(); - su2double upper_limit = 1.0-config->GetFFD_Tol(); + su2double upper_limit = 1.0 - config->GetFFD_Tol(); if (ParamCoord[0] < lower_limit) ParamCoord[0] = lower_limit; if (ParamCoord[1] < lower_limit) ParamCoord[1] = lower_limit; @@ -864,23 +857,23 @@ void CSurfaceMovement::SetParametricCoord(CGeometry *geometry, CConfig *config, FFDBox->Set_ParametricCoord(ParamCoord); FFDBox->Set_CartesianCoord(CartCoord); - ParamCoordGuess[0] = ParamCoord[0]; ParamCoordGuess[1] = ParamCoord[1]; ParamCoordGuess[2] = ParamCoord[2]; + ParamCoordGuess[0] = ParamCoord[0]; + ParamCoordGuess[1] = ParamCoord[1]; + ParamCoordGuess[2] = ParamCoord[2]; if (Diff >= config->GetFFD_Tol()) { - cout << "Please check this point: Local (" << ParamCoord[0] <<" "<< ParamCoord[1] <<" "<< ParamCoord[2] <<") <-> Global (" - << CartCoord[0] <<" "<< CartCoord[1] <<" "<< CartCoord[2] <<") <-> Error "<< Diff <<" vs "<< config->GetFFD_Tol() <<"." << endl; + cout << "Please check this point: Local (" << ParamCoord[0] << " " << ParamCoord[1] << " " + << ParamCoord[2] << ") <-> Global (" << CartCoord[0] << " " << CartCoord[1] << " " << CartCoord[2] + << ") <-> Error " << Diff << " vs " << config->GetFFD_Tol() << "." << endl; } - } - else { - + } else { if (Diff >= config->GetFFD_Tol()) { - cout << "Please check this point: Local (" << ParamCoord[0] <<" "<< ParamCoord[1] <<" "<< ParamCoord[2] <<") <-> Global (" - << CartCoord[0] <<" "<< CartCoord[1] <<" "<< CartCoord[2] <<") <-> Error "<< Diff <<" vs "<< config->GetFFD_Tol() <<"." << endl; + cout << "Please check this point: Local (" << ParamCoord[0] << " " << ParamCoord[1] << " " + << ParamCoord[2] << ") <-> Global (" << CartCoord[0] << " " << CartCoord[1] << " " << CartCoord[2] + << ") <-> Error " << Diff << " vs " << config->GetFFD_Tol() << "." << endl; } - } - } } } @@ -893,8 +886,7 @@ void CSurfaceMovement::SetParametricCoord(CGeometry *geometry, CConfig *config, #endif if (rank == MASTER_NODE) - cout << "Compute parametric coord | FFD box: " << FFDBox->GetTag() << ". Max Diff: " << MaxDiff <<"."<< endl; - + cout << "Compute parametric coord | FFD box: " << FFDBox->GetTag() << ". Max Diff: " << MaxDiff << "." << endl; /*--- After the point inversion, copy the original information back (this only works with boxes, @@ -902,7 +894,7 @@ void CSurfaceMovement::SetParametricCoord(CGeometry *geometry, CConfig *config, if (BoxFFD) { FFDBox->SetOriginalControlPoints(); - if (config->GetFFD_Blending() == BEZIER){ + if (config->GetFFD_Blending() == BEZIER) { FFDBox->BlendingFunction[0]->SetOrder(FFDBox->GetlOrder(), FFDBox->GetlOrder()); FFDBox->BlendingFunction[1]->SetOrder(FFDBox->GetmOrder(), FFDBox->GetmOrder()); FFDBox->BlendingFunction[2]->SetOrder(FFDBox->GetnOrder(), FFDBox->GetnOrder()); @@ -910,7 +902,8 @@ void CSurfaceMovement::SetParametricCoord(CGeometry *geometry, CConfig *config, } } -void CSurfaceMovement::SetParametricCoordCP(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBoxParent, CFreeFormDefBox *FFDBoxChild) { +void CSurfaceMovement::SetParametricCoordCP(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBoxParent, + CFreeFormDefBox* FFDBoxChild) { unsigned short iOrder, jOrder, kOrder; su2double *CartCoord, *ParamCoord, ParamCoordGuess[3]; @@ -923,12 +916,12 @@ void CSurfaceMovement::SetParametricCoordCP(CGeometry *geometry, CConfig *config } if (rank == MASTER_NODE) - cout << "Compute parametric coord (CP) | FFD parent box: " << FFDBoxParent->GetTag() << ". FFD child box: " << FFDBoxChild->GetTag() <<"."<< endl; - - + cout << "Compute parametric coord (CP) | FFD parent box: " << FFDBoxParent->GetTag() + << ". FFD child box: " << FFDBoxChild->GetTag() << "." << endl; } -void CSurfaceMovement::GetCartesianCoordCP(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBoxParent, CFreeFormDefBox *FFDBoxChild) { +void CSurfaceMovement::GetCartesianCoordCP(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBoxParent, + CFreeFormDefBox* FFDBoxChild) { unsigned short iOrder, jOrder, kOrder, iDim; su2double *CartCoord, *ParamCoord; @@ -946,57 +939,59 @@ void CSurfaceMovement::GetCartesianCoordCP(CGeometry *geometry, CConfig *config, CartCoord = FFDBoxParent->EvalCartesianCoord(ParamCoord); FFDBoxChild->SetCoordControlPoints(CartCoord, iOrder, jOrder, kOrder); FFDBoxChild->SetCoordControlPoints_Copy(CartCoord, iOrder, jOrder, kOrder); - } if (rank == MASTER_NODE) - cout << "Update cartesian coord (CP) | FFD parent box: " << FFDBoxParent->GetTag() << ". FFD child box: " << FFDBoxChild->GetTag() <<"."<< endl; - + cout << "Update cartesian coord (CP) | FFD parent box: " << FFDBoxParent->GetTag() + << ". FFD child box: " << FFDBoxChild->GetTag() << "." << endl; } -void CSurfaceMovement::CheckFFDDimension(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox, unsigned short iFFDBox) { - +void CSurfaceMovement::CheckFFDDimension(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBox, + unsigned short iFFDBox) { unsigned short iIndex, jIndex, kIndex, lDegree, mDegree, nDegree, iDV; bool OutOffLimits; bool polar = (config->GetFFD_CoordSystem() == POLAR); - lDegree = FFDBox->GetlOrder()-1; - mDegree = FFDBox->GetmOrder()-1; - nDegree = FFDBox->GetnOrder()-1; + lDegree = FFDBox->GetlOrder() - 1; + mDegree = FFDBox->GetmOrder() - 1; + nDegree = FFDBox->GetnOrder() - 1; OutOffLimits = false; for (iDV = 0; iDV < config->GetnDV(); iDV++) { - if (config->GetFFDTag(iDV)== FFDBox->GetTag()){ - switch ( config->GetDesign_Variable(iDV) ) { - case FFD_CONTROL_POINT_2D : + if (config->GetFFDTag(iDV) == FFDBox->GetTag()) { + switch (config->GetDesign_Variable(iDV)) { + case FFD_CONTROL_POINT_2D: if (polar) { iIndex = SU2_TYPE::Int(fabs(config->GetParamDV(iDV, 1))); kIndex = SU2_TYPE::Int(fabs(config->GetParamDV(iDV, 2))); if ((iIndex > lDegree) || (kIndex > nDegree)) OutOffLimits = true; - } - else { + } else { iIndex = SU2_TYPE::Int(fabs(config->GetParamDV(iDV, 1))); jIndex = SU2_TYPE::Int(fabs(config->GetParamDV(iDV, 2))); if ((iIndex > lDegree) || (jIndex > mDegree)) OutOffLimits = true; } break; - case FFD_CAMBER : case FFD_THICKNESS : - iIndex = SU2_TYPE::Int(fabs(config->GetParamDV(iDV, 1))); - jIndex = SU2_TYPE::Int(fabs(config->GetParamDV(iDV, 2))); - if ((iIndex > lDegree) || (jIndex > mDegree)) OutOffLimits = true; + case FFD_CAMBER: + case FFD_THICKNESS: + iIndex = SU2_TYPE::Int(fabs(config->GetParamDV(iDV, 1))); + jIndex = SU2_TYPE::Int(fabs(config->GetParamDV(iDV, 2))); + if ((iIndex > lDegree) || (jIndex > mDegree)) OutOffLimits = true; break; - case FFD_CAMBER_2D : case FFD_THICKNESS_2D : + case FFD_CAMBER_2D: + case FFD_THICKNESS_2D: iIndex = SU2_TYPE::Int(fabs(config->GetParamDV(iDV, 1))); if (iIndex > lDegree) OutOffLimits = true; break; - case FFD_CONTROL_POINT : case FFD_NACELLE : + case FFD_CONTROL_POINT: + case FFD_NACELLE: iIndex = SU2_TYPE::Int(fabs(config->GetParamDV(iDV, 1))); - jIndex= SU2_TYPE::Int(fabs(config->GetParamDV(iDV, 2))); + jIndex = SU2_TYPE::Int(fabs(config->GetParamDV(iDV, 2))); kIndex = SU2_TYPE::Int(fabs(config->GetParamDV(iDV, 3))); if ((iIndex > lDegree) || (jIndex > mDegree) || (kIndex > nDegree)) OutOffLimits = true; break; - case FFD_GULL : case FFD_TWIST : - jIndex= SU2_TYPE::Int(fabs(config->GetParamDV(iDV, 1))); + case FFD_GULL: + case FFD_TWIST: + jIndex = SU2_TYPE::Int(fabs(config->GetParamDV(iDV, 1))); if (jIndex > mDegree) OutOffLimits = true; break; } @@ -1017,12 +1012,11 @@ void CSurfaceMovement::CheckFFDDimension(CGeometry *geometry, CConfig *config, C #ifdef HAVE_MPI SU2_MPI::Barrier(SU2_MPI::GetComm()); #endif - } -void CSurfaceMovement::CheckFFDIntersections(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox, unsigned short iFFDBox) { - - su2double Coord_0[] = {0,0,0}, Coord_1[] = {0,0,0}; +void CSurfaceMovement::CheckFFDIntersections(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBox, + unsigned short iFFDBox) { + su2double Coord_0[] = {0, 0, 0}, Coord_1[] = {0, 0, 0}; unsigned short index, iMarker, iNode, jNode, lDegree, mDegree, nDegree, iDim; unsigned long iElem, iPoint, jPoint; bool IPlane_Intersect_A = false, IPlane_Intersect_B = false; @@ -1037,90 +1031,89 @@ void CSurfaceMovement::CheckFFDIntersections(CGeometry *geometry, CConfig *confi bool polar = (config->GetFFD_CoordSystem() == POLAR); bool cartesian = (config->GetFFD_CoordSystem() == CARTESIAN); - lDegree = FFDBox->GetlOrder()-1; - mDegree = FFDBox->GetmOrder()-1; - nDegree = FFDBox->GetnOrder()-1; + lDegree = FFDBox->GetlOrder() - 1; + mDegree = FFDBox->GetmOrder() - 1; + nDegree = FFDBox->GetnOrder() - 1; if (config->GetFFD_Continuity() != USER_INPUT) { - /*--- Check intersection with plane i=0 ---*/ - su2double *IPlane_Coord_0_A = FFDBox->GetCoordControlPoints(0, 0, 0); - su2double *IPlane_Coord_1_A = FFDBox->GetCoordControlPoints(0, 0, nDegree); - su2double *IPlane_Coord_2_A = FFDBox->GetCoordControlPoints(0, mDegree, 0); + su2double* IPlane_Coord_0_A = FFDBox->GetCoordControlPoints(0, 0, 0); + su2double* IPlane_Coord_1_A = FFDBox->GetCoordControlPoints(0, 0, nDegree); + su2double* IPlane_Coord_2_A = FFDBox->GetCoordControlPoints(0, mDegree, 0); - su2double *IPlane_Coord_0_A_ = FFDBox->GetCoordControlPoints(0, mDegree, nDegree); - su2double *IPlane_Coord_1_A_ = FFDBox->GetCoordControlPoints(0, mDegree, 0); - su2double *IPlane_Coord_2_A_ = FFDBox->GetCoordControlPoints(0, 0, nDegree); + su2double* IPlane_Coord_0_A_ = FFDBox->GetCoordControlPoints(0, mDegree, nDegree); + su2double* IPlane_Coord_1_A_ = FFDBox->GetCoordControlPoints(0, mDegree, 0); + su2double* IPlane_Coord_2_A_ = FFDBox->GetCoordControlPoints(0, 0, nDegree); /*--- Check intersection with plane i=lDegree ---*/ - su2double *IPlane_Coord_0_B = FFDBox->GetCoordControlPoints(lDegree, 0, 0); - su2double *IPlane_Coord_1_B = FFDBox->GetCoordControlPoints(lDegree, 0, nDegree); - su2double *IPlane_Coord_2_B = FFDBox->GetCoordControlPoints(lDegree, mDegree, 0); + su2double* IPlane_Coord_0_B = FFDBox->GetCoordControlPoints(lDegree, 0, 0); + su2double* IPlane_Coord_1_B = FFDBox->GetCoordControlPoints(lDegree, 0, nDegree); + su2double* IPlane_Coord_2_B = FFDBox->GetCoordControlPoints(lDegree, mDegree, 0); - su2double *IPlane_Coord_0_B_ = FFDBox->GetCoordControlPoints(lDegree, mDegree, nDegree); - su2double *IPlane_Coord_1_B_ = FFDBox->GetCoordControlPoints(lDegree, mDegree, 0); - su2double *IPlane_Coord_2_B_ = FFDBox->GetCoordControlPoints(lDegree, 0, nDegree); + su2double* IPlane_Coord_0_B_ = FFDBox->GetCoordControlPoints(lDegree, mDegree, nDegree); + su2double* IPlane_Coord_1_B_ = FFDBox->GetCoordControlPoints(lDegree, mDegree, 0); + su2double* IPlane_Coord_2_B_ = FFDBox->GetCoordControlPoints(lDegree, 0, nDegree); /*--- Check intersection with plane j=0 ---*/ - su2double *JPlane_Coord_0_A = FFDBox->GetCoordControlPoints(0, 0, 0); - su2double *JPlane_Coord_1_A = FFDBox->GetCoordControlPoints(0, 0, nDegree); - su2double *JPlane_Coord_2_A = FFDBox->GetCoordControlPoints(lDegree, 0, 0); + su2double* JPlane_Coord_0_A = FFDBox->GetCoordControlPoints(0, 0, 0); + su2double* JPlane_Coord_1_A = FFDBox->GetCoordControlPoints(0, 0, nDegree); + su2double* JPlane_Coord_2_A = FFDBox->GetCoordControlPoints(lDegree, 0, 0); - su2double *JPlane_Coord_0_A_ = FFDBox->GetCoordControlPoints(lDegree, 0, nDegree); - su2double *JPlane_Coord_1_A_ = FFDBox->GetCoordControlPoints(lDegree, 0, 0); - su2double *JPlane_Coord_2_A_ = FFDBox->GetCoordControlPoints(0, 0, nDegree); + su2double* JPlane_Coord_0_A_ = FFDBox->GetCoordControlPoints(lDegree, 0, nDegree); + su2double* JPlane_Coord_1_A_ = FFDBox->GetCoordControlPoints(lDegree, 0, 0); + su2double* JPlane_Coord_2_A_ = FFDBox->GetCoordControlPoints(0, 0, nDegree); /*--- Check intersection with plane j=mDegree ---*/ - su2double *JPlane_Coord_0_B = FFDBox->GetCoordControlPoints(0, mDegree, 0); - su2double *JPlane_Coord_1_B = FFDBox->GetCoordControlPoints(0, mDegree, nDegree); - su2double *JPlane_Coord_2_B = FFDBox->GetCoordControlPoints(lDegree, mDegree, 0); + su2double* JPlane_Coord_0_B = FFDBox->GetCoordControlPoints(0, mDegree, 0); + su2double* JPlane_Coord_1_B = FFDBox->GetCoordControlPoints(0, mDegree, nDegree); + su2double* JPlane_Coord_2_B = FFDBox->GetCoordControlPoints(lDegree, mDegree, 0); - su2double *JPlane_Coord_0_B_ = FFDBox->GetCoordControlPoints(lDegree, mDegree, nDegree); - su2double *JPlane_Coord_1_B_ = FFDBox->GetCoordControlPoints(lDegree, mDegree, 0); - su2double *JPlane_Coord_2_B_ = FFDBox->GetCoordControlPoints(0, mDegree, nDegree); + su2double* JPlane_Coord_0_B_ = FFDBox->GetCoordControlPoints(lDegree, mDegree, nDegree); + su2double* JPlane_Coord_1_B_ = FFDBox->GetCoordControlPoints(lDegree, mDegree, 0); + su2double* JPlane_Coord_2_B_ = FFDBox->GetCoordControlPoints(0, mDegree, nDegree); /*--- Check intersection with plane k=0 ---*/ - su2double *KPlane_Coord_0_A = FFDBox->GetCoordControlPoints(0, 0, 0); - su2double *KPlane_Coord_1_A = FFDBox->GetCoordControlPoints(0, mDegree, 0); - su2double *KPlane_Coord_2_A = FFDBox->GetCoordControlPoints(lDegree, 0, 0); + su2double* KPlane_Coord_0_A = FFDBox->GetCoordControlPoints(0, 0, 0); + su2double* KPlane_Coord_1_A = FFDBox->GetCoordControlPoints(0, mDegree, 0); + su2double* KPlane_Coord_2_A = FFDBox->GetCoordControlPoints(lDegree, 0, 0); - su2double *KPlane_Coord_0_A_ = FFDBox->GetCoordControlPoints(lDegree, mDegree, 0); - su2double *KPlane_Coord_1_A_ = FFDBox->GetCoordControlPoints(lDegree, 0, 0); - su2double *KPlane_Coord_2_A_ = FFDBox->GetCoordControlPoints(0, mDegree, 0); + su2double* KPlane_Coord_0_A_ = FFDBox->GetCoordControlPoints(lDegree, mDegree, 0); + su2double* KPlane_Coord_1_A_ = FFDBox->GetCoordControlPoints(lDegree, 0, 0); + su2double* KPlane_Coord_2_A_ = FFDBox->GetCoordControlPoints(0, mDegree, 0); /*--- Check intersection with plane k=nDegree ---*/ - su2double *KPlane_Coord_0_B = FFDBox->GetCoordControlPoints(0, 0, nDegree); - su2double *KPlane_Coord_1_B = FFDBox->GetCoordControlPoints(0, mDegree, nDegree); - su2double *KPlane_Coord_2_B = FFDBox->GetCoordControlPoints(lDegree, 0, nDegree); + su2double* KPlane_Coord_0_B = FFDBox->GetCoordControlPoints(0, 0, nDegree); + su2double* KPlane_Coord_1_B = FFDBox->GetCoordControlPoints(0, mDegree, nDegree); + su2double* KPlane_Coord_2_B = FFDBox->GetCoordControlPoints(lDegree, 0, nDegree); - su2double *KPlane_Coord_0_B_ = FFDBox->GetCoordControlPoints(lDegree, mDegree, nDegree); - su2double *KPlane_Coord_1_B_ = FFDBox->GetCoordControlPoints(lDegree, 0, nDegree); - su2double *KPlane_Coord_2_B_ = FFDBox->GetCoordControlPoints(0, mDegree, nDegree); + su2double* KPlane_Coord_0_B_ = FFDBox->GetCoordControlPoints(lDegree, mDegree, nDegree); + su2double* KPlane_Coord_1_B_ = FFDBox->GetCoordControlPoints(lDegree, 0, nDegree); + su2double* KPlane_Coord_2_B_ = FFDBox->GetCoordControlPoints(0, mDegree, nDegree); /*--- Loop over all the grid triangles ---*/ - IPlane_Intersect_A = false; IPlane_Intersect_B = false; - JPlane_Intersect_A = false; JPlane_Intersect_B = false; - KPlane_Intersect_A = false; KPlane_Intersect_B = false; + IPlane_Intersect_A = false; + IPlane_Intersect_B = false; + JPlane_Intersect_A = false; + JPlane_Intersect_B = false; + KPlane_Intersect_A = false; + KPlane_Intersect_B = false; /*--- Only the markers in the moving list ---*/ for (iMarker = 0; iMarker < geometry->GetnMarker(); iMarker++) { - if (((config->GetMarker_All_Moving(iMarker) == YES) && (Kind_SU2 == SU2_COMPONENT::SU2_CFD)) || ((config->GetMarker_All_DV(iMarker) == YES) && (Kind_SU2 == SU2_COMPONENT::SU2_DEF)) || ((config->GetMarker_All_DV(iMarker) == YES) && (Kind_SU2 == SU2_COMPONENT::SU2_GEO)) || ((config->GetMarker_All_DV(iMarker) == YES) && (Kind_SU2 == SU2_COMPONENT::SU2_DOT)) || ((config->GetMarker_All_DV(iMarker) == YES) && (config->GetDirectDiff() == D_DESIGN))) { - for (iElem = 0; iElem < geometry->GetnElem_Bound(iMarker); iElem++) { - for (iNode = 0; iNode < geometry->bound[iMarker][iElem]->GetnNodes(); iNode++) { iPoint = geometry->bound[iMarker][iElem]->GetNode(iNode); @@ -1128,103 +1121,162 @@ void CSurfaceMovement::CheckFFDIntersections(CGeometry *geometry, CConfig *confi jPoint = geometry->bound[iMarker][iElem]->GetNode(jNode); if (jPoint > iPoint) { - for (iDim = 0; iDim < geometry->GetnDim(); iDim++) { - Coord_0[iDim] = geometry->nodes->GetCoord(iPoint,iDim); - Coord_1[iDim] = geometry->nodes->GetCoord(jPoint,iDim); + Coord_0[iDim] = geometry->nodes->GetCoord(iPoint, iDim); + Coord_1[iDim] = geometry->nodes->GetCoord(jPoint, iDim); } /*--- Write the coordinates in the right parametric system ---*/ if (cylindrical) { + X_0 = config->GetFFD_Axis(0); + Y_0 = config->GetFFD_Axis(1); + Z_0 = config->GetFFD_Axis(2); - X_0 = config->GetFFD_Axis(0); Y_0 = config->GetFFD_Axis(1); Z_0 = config->GetFFD_Axis(2); + Xbar = Coord_0[0] - X_0; + Ybar = Coord_0[1] - Y_0; + Zbar = Coord_0[2] - Z_0; - Xbar = Coord_0[0] - X_0; Ybar = Coord_0[1] - Y_0; Zbar = Coord_0[2] - Z_0; - - Coord_0[0] = sqrt(Ybar*Ybar + Zbar*Zbar); - Coord_0[1] = atan2(Zbar, Ybar); if (Coord_0[1] > PI_NUMBER/2.0) Coord_0[1] -= 2.0*PI_NUMBER; + Coord_0[0] = sqrt(Ybar * Ybar + Zbar * Zbar); + Coord_0[1] = atan2(Zbar, Ybar); + if (Coord_0[1] > PI_NUMBER / 2.0) Coord_0[1] -= 2.0 * PI_NUMBER; Coord_0[2] = Xbar; - Xbar = Coord_1[0] - X_0; Ybar = Coord_1[1] - Y_0; Zbar = Coord_1[2] - Z_0; + Xbar = Coord_1[0] - X_0; + Ybar = Coord_1[1] - Y_0; + Zbar = Coord_1[2] - Z_0; - Coord_1[0] = sqrt(Ybar*Ybar + Zbar*Zbar); - Coord_1[1] = atan2(Zbar, Ybar); if (Coord_1[1] > PI_NUMBER/2.0) Coord_1[1] -= 2.0*PI_NUMBER; + Coord_1[0] = sqrt(Ybar * Ybar + Zbar * Zbar); + Coord_1[1] = atan2(Zbar, Ybar); + if (Coord_1[1] > PI_NUMBER / 2.0) Coord_1[1] -= 2.0 * PI_NUMBER; Coord_1[2] = Xbar; } else if (spherical || polar) { - - X_0 = config->GetFFD_Axis(0); Y_0 = config->GetFFD_Axis(1); Z_0 = config->GetFFD_Axis(2); - - Xbar = Coord_0[0] - X_0; Ybar = Coord_0[1] - Y_0; Zbar = Coord_0[2] - Z_0; - - Coord_0[0] = sqrt(Xbar*Xbar + Ybar*Ybar + Zbar*Zbar); - Coord_0[1] = atan2(Zbar, Ybar); if (Coord_0[1] > PI_NUMBER/2.0) Coord_0[1] -= 2.0*PI_NUMBER; - Coord_0[2] = acos (Xbar/Coord_0[0]); - - Xbar = Coord_1[0] - X_0; Ybar = Coord_1[1] - Y_0; Zbar = Coord_1[2] - Z_0; - - Coord_1[0] = sqrt(Xbar*Xbar + Ybar*Ybar + Zbar*Zbar); - Coord_1[1] = atan2(Zbar, Ybar); if (Coord_1[1] > PI_NUMBER/2.0) Coord_1[1] -= 2.0*PI_NUMBER; - Coord_1[2] = acos(Xbar/Coord_1[0]); - + X_0 = config->GetFFD_Axis(0); + Y_0 = config->GetFFD_Axis(1); + Z_0 = config->GetFFD_Axis(2); + + Xbar = Coord_0[0] - X_0; + Ybar = Coord_0[1] - Y_0; + Zbar = Coord_0[2] - Z_0; + + Coord_0[0] = sqrt(Xbar * Xbar + Ybar * Ybar + Zbar * Zbar); + Coord_0[1] = atan2(Zbar, Ybar); + if (Coord_0[1] > PI_NUMBER / 2.0) Coord_0[1] -= 2.0 * PI_NUMBER; + Coord_0[2] = acos(Xbar / Coord_0[0]); + + Xbar = Coord_1[0] - X_0; + Ybar = Coord_1[1] - Y_0; + Zbar = Coord_1[2] - Z_0; + + Coord_1[0] = sqrt(Xbar * Xbar + Ybar * Ybar + Zbar * Zbar); + Coord_1[1] = atan2(Zbar, Ybar); + if (Coord_1[1] > PI_NUMBER / 2.0) Coord_1[1] -= 2.0 * PI_NUMBER; + Coord_1[2] = acos(Xbar / Coord_1[0]); } if (geometry->GetnDim() == 3) { - if (!IPlane_Intersect_A) { - if (geometry->SegmentIntersectsTriangle(Coord_0, Coord_1, IPlane_Coord_0_A, IPlane_Coord_1_A, IPlane_Coord_2_A)) { IPlane_Intersect_A = true; } - if (geometry->SegmentIntersectsTriangle(Coord_0, Coord_1, IPlane_Coord_0_A_, IPlane_Coord_1_A_, IPlane_Coord_2_A_)) { IPlane_Intersect_A = true; } + if (geometry->SegmentIntersectsTriangle(Coord_0, Coord_1, IPlane_Coord_0_A, IPlane_Coord_1_A, + IPlane_Coord_2_A)) { + IPlane_Intersect_A = true; + } + if (geometry->SegmentIntersectsTriangle(Coord_0, Coord_1, IPlane_Coord_0_A_, IPlane_Coord_1_A_, + IPlane_Coord_2_A_)) { + IPlane_Intersect_A = true; + } } if (!IPlane_Intersect_B) { - if (geometry->SegmentIntersectsTriangle(Coord_0, Coord_1, IPlane_Coord_0_B, IPlane_Coord_1_B, IPlane_Coord_2_B)) { IPlane_Intersect_B = true; } - if (geometry->SegmentIntersectsTriangle(Coord_0, Coord_1, IPlane_Coord_0_B_, IPlane_Coord_1_B_, IPlane_Coord_2_B_)) { IPlane_Intersect_B = true; } + if (geometry->SegmentIntersectsTriangle(Coord_0, Coord_1, IPlane_Coord_0_B, IPlane_Coord_1_B, + IPlane_Coord_2_B)) { + IPlane_Intersect_B = true; + } + if (geometry->SegmentIntersectsTriangle(Coord_0, Coord_1, IPlane_Coord_0_B_, IPlane_Coord_1_B_, + IPlane_Coord_2_B_)) { + IPlane_Intersect_B = true; + } } if ((!JPlane_Intersect_A) && (!FFD_Symmetry_Plane)) { - if (geometry->SegmentIntersectsTriangle(Coord_0, Coord_1, JPlane_Coord_0_A, JPlane_Coord_1_A, JPlane_Coord_2_A)) { JPlane_Intersect_A = true; } - if (geometry->SegmentIntersectsTriangle(Coord_0, Coord_1, JPlane_Coord_0_A_, JPlane_Coord_1_A_, JPlane_Coord_2_A_)) { JPlane_Intersect_A = true; } + if (geometry->SegmentIntersectsTriangle(Coord_0, Coord_1, JPlane_Coord_0_A, JPlane_Coord_1_A, + JPlane_Coord_2_A)) { + JPlane_Intersect_A = true; + } + if (geometry->SegmentIntersectsTriangle(Coord_0, Coord_1, JPlane_Coord_0_A_, JPlane_Coord_1_A_, + JPlane_Coord_2_A_)) { + JPlane_Intersect_A = true; + } } if (cartesian) { if ((!JPlane_Intersect_B) && (!FFD_Symmetry_Plane)) { - if (geometry->SegmentIntersectsTriangle(Coord_0, Coord_1, JPlane_Coord_0_B, JPlane_Coord_1_B, JPlane_Coord_2_B)) { JPlane_Intersect_B = true; } - if (geometry->SegmentIntersectsTriangle(Coord_0, Coord_1, JPlane_Coord_0_B_, JPlane_Coord_1_B_, JPlane_Coord_2_B_)) { JPlane_Intersect_B = true; } + if (geometry->SegmentIntersectsTriangle(Coord_0, Coord_1, JPlane_Coord_0_B, JPlane_Coord_1_B, + JPlane_Coord_2_B)) { + JPlane_Intersect_B = true; + } + if (geometry->SegmentIntersectsTriangle(Coord_0, Coord_1, JPlane_Coord_0_B_, JPlane_Coord_1_B_, + JPlane_Coord_2_B_)) { + JPlane_Intersect_B = true; + } } - } - else { + } else { if (!JPlane_Intersect_B) { - if (geometry->SegmentIntersectsTriangle(Coord_0, Coord_1, JPlane_Coord_0_B, JPlane_Coord_1_B, JPlane_Coord_2_B)) { JPlane_Intersect_B = true; } - if (geometry->SegmentIntersectsTriangle(Coord_0, Coord_1, JPlane_Coord_0_B_, JPlane_Coord_1_B_, JPlane_Coord_2_B_)) { JPlane_Intersect_B = true; } + if (geometry->SegmentIntersectsTriangle(Coord_0, Coord_1, JPlane_Coord_0_B, JPlane_Coord_1_B, + JPlane_Coord_2_B)) { + JPlane_Intersect_B = true; + } + if (geometry->SegmentIntersectsTriangle(Coord_0, Coord_1, JPlane_Coord_0_B_, JPlane_Coord_1_B_, + JPlane_Coord_2_B_)) { + JPlane_Intersect_B = true; + } } } if (!KPlane_Intersect_A) { - if (geometry->SegmentIntersectsTriangle(Coord_0, Coord_1, KPlane_Coord_0_A, KPlane_Coord_1_A, KPlane_Coord_2_A)) { KPlane_Intersect_A = true; } - if (geometry->SegmentIntersectsTriangle(Coord_0, Coord_1, KPlane_Coord_0_A_, KPlane_Coord_1_A_, KPlane_Coord_2_A_)) { KPlane_Intersect_A = true; } + if (geometry->SegmentIntersectsTriangle(Coord_0, Coord_1, KPlane_Coord_0_A, KPlane_Coord_1_A, + KPlane_Coord_2_A)) { + KPlane_Intersect_A = true; + } + if (geometry->SegmentIntersectsTriangle(Coord_0, Coord_1, KPlane_Coord_0_A_, KPlane_Coord_1_A_, + KPlane_Coord_2_A_)) { + KPlane_Intersect_A = true; + } } if (!KPlane_Intersect_B) { - if (geometry->SegmentIntersectsTriangle(Coord_0, Coord_1, KPlane_Coord_0_B, KPlane_Coord_1_B, KPlane_Coord_2_B)) { KPlane_Intersect_B = true; } - if (geometry->SegmentIntersectsTriangle(Coord_0, Coord_1, KPlane_Coord_0_B_, KPlane_Coord_1_B_, KPlane_Coord_2_B_)) { KPlane_Intersect_B = true; } + if (geometry->SegmentIntersectsTriangle(Coord_0, Coord_1, KPlane_Coord_0_B, KPlane_Coord_1_B, + KPlane_Coord_2_B)) { + KPlane_Intersect_B = true; + } + if (geometry->SegmentIntersectsTriangle(Coord_0, Coord_1, KPlane_Coord_0_B_, KPlane_Coord_1_B_, + KPlane_Coord_2_B_)) { + KPlane_Intersect_B = true; + } } } else { - if (!IPlane_Intersect_A) { - if (geometry->SegmentIntersectsLine(Coord_0, Coord_1, IPlane_Coord_0_A, IPlane_Coord_2_A)) { IPlane_Intersect_A = true;} + if (geometry->SegmentIntersectsLine(Coord_0, Coord_1, IPlane_Coord_0_A, IPlane_Coord_2_A)) { + IPlane_Intersect_A = true; + } } if (!IPlane_Intersect_B) { - if (geometry->SegmentIntersectsLine(Coord_0, Coord_1, IPlane_Coord_0_B, IPlane_Coord_2_B)) { IPlane_Intersect_B = true;} + if (geometry->SegmentIntersectsLine(Coord_0, Coord_1, IPlane_Coord_0_B, IPlane_Coord_2_B)) { + IPlane_Intersect_B = true; + } } if (!JPlane_Intersect_A) { - if (geometry->SegmentIntersectsLine(Coord_0, Coord_1, JPlane_Coord_0_A, JPlane_Coord_2_A)) { JPlane_Intersect_A = true;} + if (geometry->SegmentIntersectsLine(Coord_0, Coord_1, JPlane_Coord_0_A, JPlane_Coord_2_A)) { + JPlane_Intersect_A = true; + } } if (!JPlane_Intersect_B) { - if (geometry->SegmentIntersectsLine(Coord_0, Coord_1, JPlane_Coord_0_B, JPlane_Coord_2_B)) { JPlane_Intersect_B = true;} + if (geometry->SegmentIntersectsLine(Coord_0, Coord_1, JPlane_Coord_0_B, JPlane_Coord_2_B)) { + JPlane_Intersect_B = true; + } } } } @@ -1236,7 +1288,7 @@ void CSurfaceMovement::CheckFFDIntersections(CGeometry *geometry, CConfig *confi /*--- Comunicate the planes that interesect the surface ---*/ - unsigned short MyCode[6] = {0,0,0,0,0,0}, Code[6] = {0,0,0,0,0,0}; + unsigned short MyCode[6] = {0, 0, 0, 0, 0, 0}, Code[6] = {0, 0, 0, 0, 0, 0}; if (IPlane_Intersect_A) MyCode[0] = 1; if (IPlane_Intersect_B) MyCode[1] = 1; @@ -1253,64 +1305,78 @@ void CSurfaceMovement::CheckFFDIntersections(CGeometry *geometry, CConfig *confi #else - Code[0] = MyCode[0]; Code[1] = MyCode[1]; Code[2] = MyCode[2]; - Code[3] = MyCode[3]; Code[4] = MyCode[4]; Code[5] = MyCode[5]; + Code[0] = MyCode[0]; + Code[1] = MyCode[1]; + Code[2] = MyCode[2]; + Code[3] = MyCode[3]; + Code[4] = MyCode[4]; + Code[5] = MyCode[5]; #endif - if (Code[0] != 0) IPlane_Intersect_A = true; else IPlane_Intersect_A = false; - if (Code[1] != 0) IPlane_Intersect_B = true; else IPlane_Intersect_B = false; - if (Code[2] != 0) JPlane_Intersect_A = true; else JPlane_Intersect_A = false; - if (Code[3] != 0) JPlane_Intersect_B = true; else JPlane_Intersect_B = false; - if (Code[4] != 0) KPlane_Intersect_A = true; else KPlane_Intersect_A = false; - if (Code[5] != 0) KPlane_Intersect_B = true; else KPlane_Intersect_B = false; + if (Code[0] != 0) + IPlane_Intersect_A = true; + else + IPlane_Intersect_A = false; + if (Code[1] != 0) + IPlane_Intersect_B = true; + else + IPlane_Intersect_B = false; + if (Code[2] != 0) + JPlane_Intersect_A = true; + else + JPlane_Intersect_A = false; + if (Code[3] != 0) + JPlane_Intersect_B = true; + else + JPlane_Intersect_B = false; + if (Code[4] != 0) + KPlane_Intersect_A = true; + else + KPlane_Intersect_A = false; + if (Code[5] != 0) + KPlane_Intersect_B = true; + else + KPlane_Intersect_B = false; /*--- Screen output ---*/ if (rank == MASTER_NODE) { - - if (IPlane_Intersect_A || IPlane_Intersect_B || - JPlane_Intersect_A || JPlane_Intersect_B || - KPlane_Intersect_A || KPlane_Intersect_B ) { - + if (IPlane_Intersect_A || IPlane_Intersect_B || JPlane_Intersect_A || JPlane_Intersect_B || KPlane_Intersect_A || + KPlane_Intersect_B) { cout << "The FFD planes "; if (cartesian) { if (IPlane_Intersect_A) cout << "i=0, "; - if (IPlane_Intersect_B) cout << "i="<< lDegree << ", "; + if (IPlane_Intersect_B) cout << "i=" << lDegree << ", "; if (JPlane_Intersect_A) cout << "j=0, "; - if (JPlane_Intersect_B) cout << "j="<< mDegree << ", "; + if (JPlane_Intersect_B) cout << "j=" << mDegree << ", "; if (KPlane_Intersect_A) cout << "k=0, "; - if (KPlane_Intersect_B) cout << "k="<< nDegree << ", "; - } - else if (cylindrical) { + if (KPlane_Intersect_B) cout << "k=" << nDegree << ", "; + } else if (cylindrical) { if (IPlane_Intersect_A) cout << "r=0, "; - if (IPlane_Intersect_B) cout << "r="<< lDegree << ", "; + if (IPlane_Intersect_B) cout << "r=" << lDegree << ", "; if (JPlane_Intersect_A) cout << "theta=0, "; - if (JPlane_Intersect_B) cout << "theta="<< mDegree << ", "; + if (JPlane_Intersect_B) cout << "theta=" << mDegree << ", "; if (KPlane_Intersect_A) cout << "z=0, "; - if (KPlane_Intersect_B) cout << "z="<< nDegree << ", "; - } - else if (spherical) { + if (KPlane_Intersect_B) cout << "z=" << nDegree << ", "; + } else if (spherical) { if (IPlane_Intersect_A) cout << "r=0, "; - if (IPlane_Intersect_B) cout << "r="<< lDegree << ", "; + if (IPlane_Intersect_B) cout << "r=" << lDegree << ", "; if (JPlane_Intersect_A) cout << "theta=0, "; - if (JPlane_Intersect_B) cout << "theta="<< mDegree << ", "; + if (JPlane_Intersect_B) cout << "theta=" << mDegree << ", "; if (KPlane_Intersect_A) cout << "phi=0, "; - if (KPlane_Intersect_B) cout << "phi="<< nDegree << ", "; - } - else if (polar) { + if (KPlane_Intersect_B) cout << "phi=" << nDegree << ", "; + } else if (polar) { if (IPlane_Intersect_A) cout << "r=0, "; - if (IPlane_Intersect_B) cout << "r="<< lDegree << ", "; + if (IPlane_Intersect_B) cout << "r=" << lDegree << ", "; if (KPlane_Intersect_A) cout << "theta=0, "; - if (KPlane_Intersect_B) cout << "theta="<< nDegree << ", "; + if (KPlane_Intersect_B) cout << "theta=" << nDegree << ", "; } cout << "intersect solid surfaces." << endl; } - } - } /*--- Fix the FFD planes based on the intersections with solid surfaces, @@ -1318,8 +1384,7 @@ void CSurfaceMovement::CheckFFDIntersections(CGeometry *geometry, CConfig *confi that we are looking for ---*/ if (config->GetFFD_Continuity() == USER_INPUT) { - if (rank == MASTER_NODE) - cout << "SU2 is fixing user's input planes." << endl; + if (rank == MASTER_NODE) cout << "SU2 is fixing user's input planes." << endl; for (index = 0; index < config->GetnFFD_Fix_IDir(); index++) if ((config->GetFFD_Fix_IDir(index) <= lDegree) && (config->GetFFD_Fix_IDir(index) >= 0)) @@ -1330,67 +1395,112 @@ void CSurfaceMovement::CheckFFDIntersections(CGeometry *geometry, CConfig *confi for (index = 0; index < config->GetnFFD_Fix_KDir(); index++) if ((config->GetFFD_Fix_KDir(index) <= nDegree) && (config->GetFFD_Fix_KDir(index) >= 0)) FFDBox->Set_Fix_KPlane(config->GetFFD_Fix_KDir(index)); - } if (config->GetFFD_Continuity() == DERIVATIVE_NONE) { - if (rank == MASTER_NODE) - cout << "SU2 is fixing the planes to maintain a continuous surface." << endl; - - if (IPlane_Intersect_A) { FFDBox->Set_Fix_IPlane(0); } - if (IPlane_Intersect_B) { FFDBox->Set_Fix_IPlane(lDegree); } - if (JPlane_Intersect_A) { FFDBox->Set_Fix_JPlane(0); } - if (JPlane_Intersect_B) { FFDBox->Set_Fix_JPlane(mDegree); } - if (KPlane_Intersect_A) { FFDBox->Set_Fix_KPlane(0); } - if (KPlane_Intersect_B) { FFDBox->Set_Fix_KPlane(nDegree); } + if (rank == MASTER_NODE) cout << "SU2 is fixing the planes to maintain a continuous surface." << endl; + if (IPlane_Intersect_A) { + FFDBox->Set_Fix_IPlane(0); + } + if (IPlane_Intersect_B) { + FFDBox->Set_Fix_IPlane(lDegree); + } + if (JPlane_Intersect_A) { + FFDBox->Set_Fix_JPlane(0); + } + if (JPlane_Intersect_B) { + FFDBox->Set_Fix_JPlane(mDegree); + } + if (KPlane_Intersect_A) { + FFDBox->Set_Fix_KPlane(0); + } + if (KPlane_Intersect_B) { + FFDBox->Set_Fix_KPlane(nDegree); + } } if (config->GetFFD_Continuity() == DERIVATIVE_1ST) { - if (rank == MASTER_NODE) - cout << "SU2 is fixing the planes to maintain a continuous 1st order derivative." << endl; - - if (IPlane_Intersect_A) { FFDBox->Set_Fix_IPlane(0); FFDBox->Set_Fix_IPlane(1); } - if (IPlane_Intersect_B) { FFDBox->Set_Fix_IPlane(lDegree); FFDBox->Set_Fix_IPlane(lDegree-1); } - if (JPlane_Intersect_A) { FFDBox->Set_Fix_JPlane(0); FFDBox->Set_Fix_JPlane(1); } - if (JPlane_Intersect_B) { FFDBox->Set_Fix_JPlane(mDegree); FFDBox->Set_Fix_JPlane(mDegree-1); } - if (KPlane_Intersect_A) { FFDBox->Set_Fix_KPlane(0); FFDBox->Set_Fix_KPlane(1); } - if (KPlane_Intersect_B) { FFDBox->Set_Fix_KPlane(nDegree); FFDBox->Set_Fix_KPlane(nDegree-1); } + if (rank == MASTER_NODE) cout << "SU2 is fixing the planes to maintain a continuous 1st order derivative." << endl; + if (IPlane_Intersect_A) { + FFDBox->Set_Fix_IPlane(0); + FFDBox->Set_Fix_IPlane(1); + } + if (IPlane_Intersect_B) { + FFDBox->Set_Fix_IPlane(lDegree); + FFDBox->Set_Fix_IPlane(lDegree - 1); + } + if (JPlane_Intersect_A) { + FFDBox->Set_Fix_JPlane(0); + FFDBox->Set_Fix_JPlane(1); + } + if (JPlane_Intersect_B) { + FFDBox->Set_Fix_JPlane(mDegree); + FFDBox->Set_Fix_JPlane(mDegree - 1); + } + if (KPlane_Intersect_A) { + FFDBox->Set_Fix_KPlane(0); + FFDBox->Set_Fix_KPlane(1); + } + if (KPlane_Intersect_B) { + FFDBox->Set_Fix_KPlane(nDegree); + FFDBox->Set_Fix_KPlane(nDegree - 1); + } } if (config->GetFFD_Continuity() == DERIVATIVE_2ND) { - if (rank == MASTER_NODE) - cout << "SU2 is fixing the planes to maintain a continuous 2nd order derivative." << endl; - - if ((IPlane_Intersect_A) && (lDegree > 1)) { FFDBox->Set_Fix_IPlane(0); FFDBox->Set_Fix_IPlane(1); FFDBox->Set_Fix_IPlane(2); } - if ((IPlane_Intersect_B) && (lDegree > 1)) { FFDBox->Set_Fix_IPlane(lDegree); FFDBox->Set_Fix_IPlane(lDegree-1); FFDBox->Set_Fix_IPlane(lDegree-2); } - if ((JPlane_Intersect_A) && (mDegree > 1)) { FFDBox->Set_Fix_JPlane(0); FFDBox->Set_Fix_JPlane(1); FFDBox->Set_Fix_JPlane(2); } - if ((JPlane_Intersect_B) && (mDegree > 1)) { FFDBox->Set_Fix_JPlane(mDegree); FFDBox->Set_Fix_JPlane(mDegree-1); FFDBox->Set_Fix_JPlane(mDegree-2); } - if ((KPlane_Intersect_A) && (nDegree > 1)) { FFDBox->Set_Fix_KPlane(0); FFDBox->Set_Fix_KPlane(1);FFDBox->Set_Fix_KPlane(2); } - if ((KPlane_Intersect_B) && (nDegree > 1)) { FFDBox->Set_Fix_KPlane(nDegree); FFDBox->Set_Fix_KPlane(nDegree-1); FFDBox->Set_Fix_KPlane(nDegree-2); } + if (rank == MASTER_NODE) cout << "SU2 is fixing the planes to maintain a continuous 2nd order derivative." << endl; + if ((IPlane_Intersect_A) && (lDegree > 1)) { + FFDBox->Set_Fix_IPlane(0); + FFDBox->Set_Fix_IPlane(1); + FFDBox->Set_Fix_IPlane(2); + } + if ((IPlane_Intersect_B) && (lDegree > 1)) { + FFDBox->Set_Fix_IPlane(lDegree); + FFDBox->Set_Fix_IPlane(lDegree - 1); + FFDBox->Set_Fix_IPlane(lDegree - 2); + } + if ((JPlane_Intersect_A) && (mDegree > 1)) { + FFDBox->Set_Fix_JPlane(0); + FFDBox->Set_Fix_JPlane(1); + FFDBox->Set_Fix_JPlane(2); + } + if ((JPlane_Intersect_B) && (mDegree > 1)) { + FFDBox->Set_Fix_JPlane(mDegree); + FFDBox->Set_Fix_JPlane(mDegree - 1); + FFDBox->Set_Fix_JPlane(mDegree - 2); + } + if ((KPlane_Intersect_A) && (nDegree > 1)) { + FFDBox->Set_Fix_KPlane(0); + FFDBox->Set_Fix_KPlane(1); + FFDBox->Set_Fix_KPlane(2); + } + if ((KPlane_Intersect_B) && (nDegree > 1)) { + FFDBox->Set_Fix_KPlane(nDegree); + FFDBox->Set_Fix_KPlane(nDegree - 1); + FFDBox->Set_Fix_KPlane(nDegree - 2); + } } - } -void CSurfaceMovement::UpdateParametricCoord(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox, unsigned short iFFDBox) { +void CSurfaceMovement::UpdateParametricCoord(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBox, + unsigned short iFFDBox) { unsigned short iMarker, iDim; unsigned long iVertex, iPoint, iSurfacePoints; - su2double CartCoord[3] = {0.0,0.0,0.0}, *CartCoordNew, *CartCoordOld; - su2double *ParamCoord, *var_coord, ParamCoordGuess[3] = {0.0,0.0,0.0}; + su2double CartCoord[3] = {0.0, 0.0, 0.0}, *CartCoordNew, *CartCoordOld; + su2double *ParamCoord, *var_coord, ParamCoordGuess[3] = {0.0, 0.0, 0.0}; su2double MaxDiff, my_MaxDiff = 0.0, Diff; /*--- Recompute the parametric coordinates ---*/ for (iSurfacePoints = 0; iSurfacePoints < FFDBox->GetnSurfacePoint(); iSurfacePoints++) { - /*--- Get the marker of the surface point ---*/ iMarker = FFDBox->Get_MarkerIndex(iSurfacePoints); if (config->GetMarker_All_DV(iMarker) == YES) { - /*--- Get the vertex of the surface point ---*/ iVertex = FFDBox->Get_VertexIndex(iSurfacePoints); @@ -1406,13 +1516,14 @@ void CSurfaceMovement::UpdateParametricCoord(CGeometry *geometry, CConfig *confi var_coord = geometry->vertex[iMarker][iVertex]->GetVarCoord(); CartCoordOld = geometry->nodes->GetCoord(iPoint); - for (iDim = 0; iDim < 3; iDim++) - CartCoord[iDim] = CartCoordOld[iDim] + var_coord[iDim]; + for (iDim = 0; iDim < 3; iDim++) CartCoord[iDim] = CartCoordOld[iDim] + var_coord[iDim]; FFDBox->Set_CartesianCoord(CartCoord, iSurfacePoints); /*--- Find the parametric coordinate using as ParamCoordGuess the previous value ---*/ - ParamCoordGuess[0] = ParamCoord[0]; ParamCoordGuess[1] = ParamCoord[1]; ParamCoordGuess[2] = ParamCoord[2]; + ParamCoordGuess[0] = ParamCoord[0]; + ParamCoordGuess[1] = ParamCoord[1]; + ParamCoordGuess[2] = ParamCoord[2]; ParamCoord = FFDBox->GetParametricCoord_Iterative(iPoint, CartCoord, ParamCoordGuess, config); /*--- Set the new value of the parametric coordinates ---*/ @@ -1428,10 +1539,9 @@ void CSurfaceMovement::UpdateParametricCoord(CGeometry *geometry, CConfig *confi Diff = 0.0; for (iDim = 0; iDim < geometry->GetnDim(); iDim++) - Diff += (CartCoordNew[iDim]-CartCoord[iDim])*(CartCoordNew[iDim]-CartCoord[iDim]); + Diff += (CartCoordNew[iDim] - CartCoord[iDim]) * (CartCoordNew[iDim] - CartCoord[iDim]); Diff = sqrt(Diff); my_MaxDiff = max(my_MaxDiff, Diff); - } } @@ -1442,37 +1552,62 @@ void CSurfaceMovement::UpdateParametricCoord(CGeometry *geometry, CConfig *confi #endif if (rank == MASTER_NODE) - cout << "Update parametric coord | FFD box: " << FFDBox->GetTag() << ". Max Diff: " << MaxDiff <<"."<< endl; - + cout << "Update parametric coord | FFD box: " << FFDBox->GetTag() << ". Max Diff: " << MaxDiff << "." << endl; } -void CSurfaceMovement::ApplyDesignVariables(CGeometry *geometry, CConfig *config, CFreeFormDefBox **FFDBox, unsigned short iFFDBox) { - +void CSurfaceMovement::ApplyDesignVariables(CGeometry* geometry, CConfig* config, CFreeFormDefBox** FFDBox, + unsigned short iFFDBox) { unsigned short iDV; for (iDV = 0; iDV < config->GetnDV(); iDV++) { - switch ( config->GetDesign_Variable(iDV) ) { - case FFD_CONTROL_POINT_2D : SetFFDCPChange_2D(geometry, config, FFDBox[iFFDBox], FFDBox, iDV, false); break; - case FFD_CAMBER_2D : SetFFDCamber_2D(geometry, config, FFDBox[iFFDBox], FFDBox, iDV, false); break; - case FFD_THICKNESS_2D : SetFFDThickness_2D(geometry, config, FFDBox[iFFDBox], FFDBox, iDV, false); break; - case FFD_TWIST_2D : SetFFDTwist_2D(geometry, config, FFDBox[iFFDBox], FFDBox, iDV, false); break; - case FFD_CONTROL_POINT : SetFFDCPChange(geometry, config, FFDBox[iFFDBox], FFDBox, iDV, false); break; - case FFD_NACELLE : SetFFDNacelle(geometry, config, FFDBox[iFFDBox], FFDBox, iDV, false); break; - case FFD_GULL : SetFFDGull(geometry, config, FFDBox[iFFDBox], FFDBox, iDV, false); break; - case FFD_TWIST : SetFFDTwist(geometry, config, FFDBox[iFFDBox], FFDBox, iDV, false); break; - case FFD_ROTATION : SetFFDRotation(geometry, config, FFDBox[iFFDBox], FFDBox, iDV, false); break; - case FFD_CONTROL_SURFACE : SetFFDControl_Surface(geometry, config, FFDBox[iFFDBox], FFDBox, iDV, false); break; - case FFD_CAMBER : SetFFDCamber(geometry, config, FFDBox[iFFDBox], FFDBox, iDV, false); break; - case FFD_THICKNESS : SetFFDThickness(geometry, config, FFDBox[iFFDBox], FFDBox, iDV, false); break; - case FFD_ANGLE_OF_ATTACK : SetFFDAngleOfAttack(geometry, config, FFDBox[iFFDBox], FFDBox, iDV, false); break; + switch (config->GetDesign_Variable(iDV)) { + case FFD_CONTROL_POINT_2D: + SetFFDCPChange_2D(geometry, config, FFDBox[iFFDBox], FFDBox, iDV, false); + break; + case FFD_CAMBER_2D: + SetFFDCamber_2D(geometry, config, FFDBox[iFFDBox], FFDBox, iDV, false); + break; + case FFD_THICKNESS_2D: + SetFFDThickness_2D(geometry, config, FFDBox[iFFDBox], FFDBox, iDV, false); + break; + case FFD_TWIST_2D: + SetFFDTwist_2D(geometry, config, FFDBox[iFFDBox], FFDBox, iDV, false); + break; + case FFD_CONTROL_POINT: + SetFFDCPChange(geometry, config, FFDBox[iFFDBox], FFDBox, iDV, false); + break; + case FFD_NACELLE: + SetFFDNacelle(geometry, config, FFDBox[iFFDBox], FFDBox, iDV, false); + break; + case FFD_GULL: + SetFFDGull(geometry, config, FFDBox[iFFDBox], FFDBox, iDV, false); + break; + case FFD_TWIST: + SetFFDTwist(geometry, config, FFDBox[iFFDBox], FFDBox, iDV, false); + break; + case FFD_ROTATION: + SetFFDRotation(geometry, config, FFDBox[iFFDBox], FFDBox, iDV, false); + break; + case FFD_CONTROL_SURFACE: + SetFFDControl_Surface(geometry, config, FFDBox[iFFDBox], FFDBox, iDV, false); + break; + case FFD_CAMBER: + SetFFDCamber(geometry, config, FFDBox[iFFDBox], FFDBox, iDV, false); + break; + case FFD_THICKNESS: + SetFFDThickness(geometry, config, FFDBox[iFFDBox], FFDBox, iDV, false); + break; + case FFD_ANGLE_OF_ATTACK: + SetFFDAngleOfAttack(geometry, config, FFDBox[iFFDBox], FFDBox, iDV, false); + break; } } } -su2double CSurfaceMovement::SetCartesianCoord(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox, unsigned short iFFDBox, bool ResetDef) { - - su2double *CartCoordNew, Diff, my_MaxDiff = 0.0, MaxDiff, - *ParamCoord, VarCoord[3] = {0.0, 0.0, 0.0}, CartCoordOld[3] = {0.0, 0.0, 0.0}; +su2double CSurfaceMovement::SetCartesianCoord(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBox, + unsigned short iFFDBox, bool ResetDef) { + su2double *CartCoordNew, Diff, my_MaxDiff = 0.0, MaxDiff, *ParamCoord, VarCoord[3] = {0.0, 0.0, 0.0}, + CartCoordOld[3] = {0.0, 0.0, 0.0}; unsigned short iMarker, iDim; unsigned long iVertex, iPoint, iSurfacePoints; @@ -1495,13 +1630,11 @@ su2double CSurfaceMovement::SetCartesianCoord(CGeometry *geometry, CConfig *conf /*--- Recompute the cartesians coordinates ---*/ for (iSurfacePoints = 0; iSurfacePoints < FFDBox->GetnSurfacePoint(); iSurfacePoints++) { - /*--- Get the marker of the surface point ---*/ iMarker = FFDBox->Get_MarkerIndex(iSurfacePoints); if (config->GetMarker_All_DV(iMarker) == YES) { - /*--- Get the vertex of the surface point ---*/ iVertex = FFDBox->Get_VertexIndex(iSurfacePoints); @@ -1523,28 +1656,32 @@ su2double CSurfaceMovement::SetCartesianCoord(CGeometry *geometry, CConfig *conf /*--- If polar coordinates, compute the cartesians from the polar value ---*/ if (cylindrical) { - su2double X_0, Y_0, Z_0, Xbar, Ybar, Zbar; - X_0 = config->GetFFD_Axis(0); Y_0 = config->GetFFD_Axis(1); Z_0 = config->GetFFD_Axis(2); + X_0 = config->GetFFD_Axis(0); + Y_0 = config->GetFFD_Axis(1); + Z_0 = config->GetFFD_Axis(2); Xbar = CartCoordNew[2]; Ybar = CartCoordNew[0] * cos(CartCoordNew[1]); Zbar = CartCoordNew[0] * sin(CartCoordNew[1]); - CartCoordNew[0] = Xbar + X_0; CartCoordNew[1] = Ybar + Y_0; CartCoordNew[2] = Zbar + Z_0; - - } - else if (spherical || polar) { + CartCoordNew[0] = Xbar + X_0; + CartCoordNew[1] = Ybar + Y_0; + CartCoordNew[2] = Zbar + Z_0; + } else if (spherical || polar) { su2double X_0, Y_0, Z_0, Xbar, Ybar, Zbar; - X_0 = config->GetFFD_Axis(0); Y_0 = config->GetFFD_Axis(1); Z_0 = config->GetFFD_Axis(2); + X_0 = config->GetFFD_Axis(0); + Y_0 = config->GetFFD_Axis(1); + Z_0 = config->GetFFD_Axis(2); Xbar = CartCoordNew[0] * cos(CartCoordNew[2]); Ybar = CartCoordNew[0] * cos(CartCoordNew[1]) * sin(CartCoordNew[2]); Zbar = CartCoordNew[0] * sin(CartCoordNew[1]) * sin(CartCoordNew[2]); - CartCoordNew[0] = Xbar + X_0; CartCoordNew[1] = Ybar + Y_0; CartCoordNew[2] = Zbar + Z_0; - + CartCoordNew[0] = Xbar + X_0; + CartCoordNew[1] = Ybar + Y_0; + CartCoordNew[2] = Zbar + Z_0; } FFDBox->Set_CartesianCoord(CartCoordNew, iSurfacePoints); @@ -1562,7 +1699,7 @@ su2double CSurfaceMovement::SetCartesianCoord(CGeometry *geometry, CConfig *conf VarCoord[iDim] = CartCoordNew[iDim] - CartCoordOld[iDim]; if ((fabs(VarCoord[iDim]) <= EPS) && (config->GetDirectDiff() != D_DESIGN) && (!config->GetAD_Mode())) VarCoord[iDim] = 0.0; - Diff += (VarCoord[iDim]*VarCoord[iDim]); + Diff += (VarCoord[iDim] * VarCoord[iDim]); } Diff = sqrt(Diff); @@ -1571,24 +1708,20 @@ su2double CSurfaceMovement::SetCartesianCoord(CGeometry *geometry, CConfig *conf /*--- Set the variation of the coordinates ---*/ geometry->vertex[iMarker][iVertex]->SetVarCoord(VarCoord); - } } SU2_MPI::Allreduce(&my_MaxDiff, &MaxDiff, 1, MPI_DOUBLE, MPI_MAX, SU2_MPI::GetComm()); if (rank == MASTER_NODE) - cout << "Update cartesian coord | FFD box: " << FFDBox->GetTag() << ". Max Diff: " << MaxDiff <<"."<< endl; + cout << "Update cartesian coord | FFD box: " << FFDBox->GetTag() << ". Max Diff: " << MaxDiff << "." << endl; return MaxDiff; - } - -bool CSurfaceMovement::SetFFDCPChange_2D(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox, CFreeFormDefBox **ResetFFDBox, - unsigned short iDV, bool ResetDef) const { - - su2double movement[3] = {0.0,0.0,0.0}, Ampl; +bool CSurfaceMovement::SetFFDCPChange_2D(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBox, + CFreeFormDefBox** ResetFFDBox, unsigned short iDV, bool ResetDef) const { + su2double movement[3] = {0.0, 0.0, 0.0}, Ampl; unsigned short index[3], i, j, iFFDBox, iPlane; string design_FFDBox; su2double Scale = config->GetOpt_RelaxFactor(); @@ -1598,91 +1731,81 @@ bool CSurfaceMovement::SetFFDCPChange_2D(CGeometry *geometry, CConfig *config, C design variable is not in this box) ---*/ if (ResetDef == true) { - for (iFFDBox = 0; iFFDBox < nFFDBox; iFFDBox++) - ResetFFDBox[iFFDBox]->SetOriginalControlPoints(); + for (iFFDBox = 0; iFFDBox < nFFDBox; iFFDBox++) ResetFFDBox[iFFDBox]->SetOriginalControlPoints(); } design_FFDBox = config->GetFFDTag(iDV); if (design_FFDBox.compare(FFDBox->GetTag()) == 0) { - /*--- Compute deformation ---*/ /*--- If we have only design value, than this value is the amplitude, * otherwise we have a general movement. ---*/ if (config->GetnDV_Value(iDV) == 1) { + Ampl = config->GetDV_Value(iDV) * Scale; - Ampl = config->GetDV_Value(iDV)*Scale; - - if (polar){ - movement[0] = config->GetParamDV(iDV, 3)*Ampl; + if (polar) { + movement[0] = config->GetParamDV(iDV, 3) * Ampl; movement[1] = 0.0; - movement[2] = config->GetParamDV(iDV, 4)*Ampl; - } - else { - movement[0] = config->GetParamDV(iDV, 3)*Ampl; - movement[1] = config->GetParamDV(iDV, 4)*Ampl; + movement[2] = config->GetParamDV(iDV, 4) * Ampl; + } else { + movement[0] = config->GetParamDV(iDV, 3) * Ampl; + movement[1] = config->GetParamDV(iDV, 4) * Ampl; movement[2] = 0.0; } } else { - if (polar){ + if (polar) { movement[0] = config->GetDV_Value(iDV, 0); movement[1] = 0.0; movement[2] = config->GetDV_Value(iDV, 1); + } else { + movement[0] = config->GetDV_Value(iDV, 0); + movement[1] = config->GetDV_Value(iDV, 1); + movement[2] = 0.0; } - else { - movement[0] = config->GetDV_Value(iDV, 0); - movement[1] = config->GetDV_Value(iDV, 1); - movement[2] = 0.0; - } - } - if (polar){ - index[0] = SU2_TYPE::Int(config->GetParamDV(iDV, 1)); - index[1] = 0; + if (polar) { + index[0] = SU2_TYPE::Int(config->GetParamDV(iDV, 1)); + index[1] = 0; index[2] = SU2_TYPE::Int(config->GetParamDV(iDV, 2)); - } - else { - index[0] = SU2_TYPE::Int(config->GetParamDV(iDV, 1)); - index[1] = SU2_TYPE::Int(config->GetParamDV(iDV, 2)); + } else { + index[0] = SU2_TYPE::Int(config->GetParamDV(iDV, 1)); + index[1] = SU2_TYPE::Int(config->GetParamDV(iDV, 2)); index[2] = 0; } /*--- Check that it is possible to move the control point ---*/ - for (iPlane = 0 ; iPlane < FFDBox->Get_nFix_IPlane(); iPlane++) { + for (iPlane = 0; iPlane < FFDBox->Get_nFix_IPlane(); iPlane++) { if (index[0] == FFDBox->Get_Fix_IPlane(iPlane)) return false; } - for (iPlane = 0 ; iPlane < FFDBox->Get_nFix_JPlane(); iPlane++) { + for (iPlane = 0; iPlane < FFDBox->Get_nFix_JPlane(); iPlane++) { if (index[1] == FFDBox->Get_Fix_JPlane(iPlane)) return false; } - for (iPlane = 0 ; iPlane < FFDBox->Get_nFix_KPlane(); iPlane++) { + for (iPlane = 0; iPlane < FFDBox->Get_nFix_KPlane(); iPlane++) { if (index[2] == FFDBox->Get_Fix_KPlane(iPlane)) return false; } - if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) == -1) && - (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) != -1)) { + if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) == -1) && (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) != -1)) { for (i = 0; i < FFDBox->GetlOrder(); i++) { index[0] = i; FFDBox->SetControlPoints(index, movement); } } - if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) != -1) && - (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) == -1)) { + if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) != -1) && (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) == -1)) { for (j = 0; j < FFDBox->GetmOrder(); j++) { index[1] = j; FFDBox->SetControlPoints(index, movement); } } - if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) == -1) && - (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) == -1)) { + if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) == -1) && (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) == -1)) { for (i = 0; i < FFDBox->GetlOrder(); i++) { index[0] = i; for (j = 0; j < FFDBox->GetmOrder(); j++) { @@ -1691,35 +1814,32 @@ bool CSurfaceMovement::SetFFDCPChange_2D(CGeometry *geometry, CConfig *config, C } } } - if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) != -1) && - (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) != -1)) { - + if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) != -1) && (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) != -1)) { FFDBox->SetControlPoints(index, movement); } /*--- Upper surface ---*/ - if (polar) index[1] = 1; - else index[2] = 1; + if (polar) + index[1] = 1; + else + index[2] = 1; - if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) == -1) && - (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) != -1)) { + if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) == -1) && (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) != -1)) { for (i = 0; i < FFDBox->GetlOrder(); i++) { index[0] = i; FFDBox->SetControlPoints(index, movement); } } - if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) != -1) && - (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) == -1)) { + if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) != -1) && (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) == -1)) { for (j = 0; j < FFDBox->GetmOrder(); j++) { index[1] = j; FFDBox->SetControlPoints(index, movement); } } - if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) == -1) && - (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) == -1)) { + if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) == -1) && (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) == -1)) { for (i = 0; i < FFDBox->GetlOrder(); i++) { index[0] = i; for (j = 0; j < FFDBox->GetmOrder(); j++) { @@ -1728,24 +1848,19 @@ bool CSurfaceMovement::SetFFDCPChange_2D(CGeometry *geometry, CConfig *config, C } } } - if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) != -1) && - (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) != -1)) { - + if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) != -1) && (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) != -1)) { FFDBox->SetControlPoints(index, movement); } - } - else { + } else { return false; } return true; - } -bool CSurfaceMovement::SetFFDCPChange(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox, CFreeFormDefBox **ResetFFDBox, - unsigned short iDV, bool ResetDef) const { - - su2double movement[3] = {0.0,0.0,0.0}, Ampl; +bool CSurfaceMovement::SetFFDCPChange(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBox, + CFreeFormDefBox** ResetFFDBox, unsigned short iDV, bool ResetDef) const { + su2double movement[3] = {0.0, 0.0, 0.0}, Ampl; unsigned short index[3], i, j, k, iPlane, iFFDBox; bool CheckIndex; string design_FFDBox; @@ -1756,33 +1871,28 @@ bool CSurfaceMovement::SetFFDCPChange(CGeometry *geometry, CConfig *config, CFre if (ResetDef == true) { FFDBox->SetOriginalControlPoints(); - for (iFFDBox = 0; iFFDBox < nFFDBox; iFFDBox++) - ResetFFDBox[iFFDBox]->SetOriginalControlPoints(); + for (iFFDBox = 0; iFFDBox < nFFDBox; iFFDBox++) ResetFFDBox[iFFDBox]->SetOriginalControlPoints(); } design_FFDBox = config->GetFFDTag(iDV); if (design_FFDBox.compare(FFDBox->GetTag()) == 0) { - /*--- Compute deformation ---*/ /*--- If we have only design value, than this value is the amplitude, * otherwise we have a general movement. ---*/ if (config->GetnDV_Value(iDV) == 1) { + Ampl = config->GetDV_Value(iDV) * Scale; - Ampl = config->GetDV_Value(iDV)*Scale; - - movement[0] = config->GetParamDV(iDV, 4)*Ampl; - movement[1] = config->GetParamDV(iDV, 5)*Ampl; - movement[2] = config->GetParamDV(iDV, 6)*Ampl; + movement[0] = config->GetParamDV(iDV, 4) * Ampl; + movement[1] = config->GetParamDV(iDV, 5) * Ampl; + movement[2] = config->GetParamDV(iDV, 6) * Ampl; } else { - movement[0] = config->GetDV_Value(iDV, 0); movement[1] = config->GetDV_Value(iDV, 1); movement[2] = config->GetDV_Value(iDV, 2); - } index[0] = SU2_TYPE::Int(config->GetParamDV(iDV, 1)); @@ -1791,68 +1901,61 @@ bool CSurfaceMovement::SetFFDCPChange(CGeometry *geometry, CConfig *config, CFre /*--- Check that it is possible to move the control point ---*/ - for (iPlane = 0 ; iPlane < FFDBox->Get_nFix_IPlane(); iPlane++) { + for (iPlane = 0; iPlane < FFDBox->Get_nFix_IPlane(); iPlane++) { if (index[0] == FFDBox->Get_Fix_IPlane(iPlane)) return false; } - for (iPlane = 0 ; iPlane < FFDBox->Get_nFix_JPlane(); iPlane++) { + for (iPlane = 0; iPlane < FFDBox->Get_nFix_JPlane(); iPlane++) { if (index[1] == FFDBox->Get_Fix_JPlane(iPlane)) return false; } - for (iPlane = 0 ; iPlane < FFDBox->Get_nFix_KPlane(); iPlane++) { + for (iPlane = 0; iPlane < FFDBox->Get_nFix_KPlane(); iPlane++) { if (index[2] == FFDBox->Get_Fix_KPlane(iPlane)) return false; } - if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) == -1) && - (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) != -1) && + if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) == -1) && (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) != -1) && (SU2_TYPE::Int(config->GetParamDV(iDV, 3)) != -1)) { for (i = 0; i < FFDBox->GetlOrder(); i++) { index[0] = i; CheckIndex = true; - for (iPlane = 0 ; iPlane < FFDBox->Get_nFix_IPlane(); iPlane++) { + for (iPlane = 0; iPlane < FFDBox->Get_nFix_IPlane(); iPlane++) { if (index[0] == FFDBox->Get_Fix_IPlane(iPlane)) CheckIndex = false; } if (CheckIndex) FFDBox->SetControlPoints(index, movement); - } } - if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) != -1) && - (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) == -1) && + if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) != -1) && (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) == -1) && (SU2_TYPE::Int(config->GetParamDV(iDV, 3)) != -1)) { for (j = 0; j < FFDBox->GetmOrder(); j++) { index[1] = j; CheckIndex = true; - for (iPlane = 0 ; iPlane < FFDBox->Get_nFix_JPlane(); iPlane++) { + for (iPlane = 0; iPlane < FFDBox->Get_nFix_JPlane(); iPlane++) { if (index[1] == FFDBox->Get_Fix_JPlane(iPlane)) CheckIndex = false; } if (CheckIndex) FFDBox->SetControlPoints(index, movement); - } } - if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) != -1) && - (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) != -1) && + if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) != -1) && (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) != -1) && (SU2_TYPE::Int(config->GetParamDV(iDV, 3)) == -1)) { for (k = 0; k < FFDBox->GetnOrder(); k++) { index[2] = k; CheckIndex = true; - for (iPlane = 0 ; iPlane < FFDBox->Get_nFix_KPlane(); iPlane++) { + for (iPlane = 0; iPlane < FFDBox->Get_nFix_KPlane(); iPlane++) { if (index[2] == FFDBox->Get_Fix_KPlane(iPlane)) CheckIndex = false; } if (CheckIndex) FFDBox->SetControlPoints(index, movement); - } } - if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) == -1) && - (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) == -1) && + if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) == -1) && (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) == -1) && (SU2_TYPE::Int(config->GetParamDV(iDV, 3)) != -1)) { for (i = 0; i < FFDBox->GetlOrder(); i++) { index[0] = i; @@ -1863,8 +1966,7 @@ bool CSurfaceMovement::SetFFDCPChange(CGeometry *geometry, CConfig *config, CFre } } - if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) != -1) && - (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) == -1) && + if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) != -1) && (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) == -1) && (SU2_TYPE::Int(config->GetParamDV(iDV, 3)) == -1)) { for (j = 0; j < FFDBox->GetmOrder(); j++) { index[1] = j; @@ -1875,8 +1977,7 @@ bool CSurfaceMovement::SetFFDCPChange(CGeometry *geometry, CConfig *config, CFre } } - if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) == -1) && - (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) != -1) && + if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) == -1) && (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) != -1) && (SU2_TYPE::Int(config->GetParamDV(iDV, 3)) == -1)) { for (i = 0; i < FFDBox->GetlOrder(); i++) { index[0] = i; @@ -1887,25 +1988,21 @@ bool CSurfaceMovement::SetFFDCPChange(CGeometry *geometry, CConfig *config, CFre } } - if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) != -1) && - (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) != -1) && + if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) != -1) && (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) != -1) && (SU2_TYPE::Int(config->GetParamDV(iDV, 3)) != -1)) { FFDBox->SetControlPoints(index, movement); } - } - else { + } else { return false; } return true; - } -bool CSurfaceMovement::SetFFDGull(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox, CFreeFormDefBox **ResetFFDBox, - unsigned short iDV, bool ResetDef) const { - - su2double movement[3] = {0.0,0.0,0.0}, Ampl; +bool CSurfaceMovement::SetFFDGull(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBox, + CFreeFormDefBox** ResetFFDBox, unsigned short iDV, bool ResetDef) const { + su2double movement[3] = {0.0, 0.0, 0.0}, Ampl; unsigned short index[3], i, k, iPlane, iFFDBox; string design_FFDBox; su2double Scale = config->GetOpt_RelaxFactor(); @@ -1915,17 +2012,15 @@ bool CSurfaceMovement::SetFFDGull(CGeometry *geometry, CConfig *config, CFreeFor if (ResetDef == true) { FFDBox->SetOriginalControlPoints(); - for (iFFDBox = 0; iFFDBox < nFFDBox; iFFDBox++) - ResetFFDBox[iFFDBox]->SetOriginalControlPoints(); + for (iFFDBox = 0; iFFDBox < nFFDBox; iFFDBox++) ResetFFDBox[iFFDBox]->SetOriginalControlPoints(); } design_FFDBox = config->GetFFDTag(iDV); if (design_FFDBox.compare(FFDBox->GetTag()) == 0) { - /*--- Compute deformation ---*/ - Ampl = config->GetDV_Value(iDV)*Scale; + Ampl = config->GetDV_Value(iDV) * Scale; movement[0] = 0.0; movement[1] = 0.0; @@ -1937,7 +2032,7 @@ bool CSurfaceMovement::SetFFDGull(CGeometry *geometry, CConfig *config, CFreeFor /*--- Check that it is possible to move the control point ---*/ - for (iPlane = 0 ; iPlane < FFDBox->Get_nFix_JPlane(); iPlane++) { + for (iPlane = 0; iPlane < FFDBox->Get_nFix_JPlane(); iPlane++) { if (index[1] == FFDBox->Get_Fix_JPlane(iPlane)) return false; } @@ -1949,19 +2044,16 @@ bool CSurfaceMovement::SetFFDGull(CGeometry *geometry, CConfig *config, CFreeFor } } - } - else { + } else { return false; } return true; - } -bool CSurfaceMovement::SetFFDNacelle(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox, CFreeFormDefBox **ResetFFDBox, - unsigned short iDV, bool ResetDef) const { - - su2double movement[3] = {0.0,0.0,0.0}, Ampl; +bool CSurfaceMovement::SetFFDNacelle(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBox, + CFreeFormDefBox** ResetFFDBox, unsigned short iDV, bool ResetDef) const { + su2double movement[3] = {0.0, 0.0, 0.0}, Ampl; unsigned short index[3], i, j, k, iPlane, iFFDBox, Theta, ThetaMax; string design_FFDBox; bool SameCP = false; @@ -1972,50 +2064,46 @@ bool CSurfaceMovement::SetFFDNacelle(CGeometry *geometry, CConfig *config, CFree if (ResetDef == true) { FFDBox->SetOriginalControlPoints(); - for (iFFDBox = 0; iFFDBox < nFFDBox; iFFDBox++) - ResetFFDBox[iFFDBox]->SetOriginalControlPoints(); + for (iFFDBox = 0; iFFDBox < nFFDBox; iFFDBox++) ResetFFDBox[iFFDBox]->SetOriginalControlPoints(); } design_FFDBox = config->GetFFDTag(iDV); if (design_FFDBox.compare(FFDBox->GetTag()) == 0) { - /*--- Compute deformation ---*/ - Ampl = config->GetDV_Value(iDV)*Scale; + Ampl = config->GetDV_Value(iDV) * Scale; - movement[0] = config->GetParamDV(iDV, 4)*Ampl; + movement[0] = config->GetParamDV(iDV, 4) * Ampl; movement[1] = 0.0; - movement[2] = config->GetParamDV(iDV, 5)*Ampl; + movement[2] = config->GetParamDV(iDV, 5) * Ampl; index[0] = SU2_TYPE::Int(config->GetParamDV(iDV, 1)); index[1] = SU2_TYPE::Int(config->GetParamDV(iDV, 2)); index[2] = SU2_TYPE::Int(config->GetParamDV(iDV, 3)); - if (index[1] == SU2_TYPE::Int(FFDBox->GetmOrder()) - index[1] -1) SameCP = true; + if (index[1] == SU2_TYPE::Int(FFDBox->GetmOrder()) - index[1] - 1) SameCP = true; ThetaMax = 2; if (SameCP) ThetaMax = 1; for (Theta = 0; Theta < ThetaMax; Theta++) { - - if (Theta == 1) index[1] = SU2_TYPE::Int(FFDBox->GetmOrder()) - index[1] -1; + if (Theta == 1) index[1] = SU2_TYPE::Int(FFDBox->GetmOrder()) - index[1] - 1; /*--- Check that it is possible to move the control point ---*/ - for (iPlane = 0 ; iPlane < FFDBox->Get_nFix_IPlane(); iPlane++) { + for (iPlane = 0; iPlane < FFDBox->Get_nFix_IPlane(); iPlane++) { if (index[0] == FFDBox->Get_Fix_IPlane(iPlane)) return false; } - for (iPlane = 0 ; iPlane < FFDBox->Get_nFix_JPlane(); iPlane++) { + for (iPlane = 0; iPlane < FFDBox->Get_nFix_JPlane(); iPlane++) { if (index[1] == FFDBox->Get_Fix_JPlane(iPlane)) return false; } - for (iPlane = 0 ; iPlane < FFDBox->Get_nFix_KPlane(); iPlane++) { + for (iPlane = 0; iPlane < FFDBox->Get_nFix_KPlane(); iPlane++) { if (index[2] == FFDBox->Get_Fix_KPlane(iPlane)) return false; } - if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) == -1) && - (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) != -1) && + if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) == -1) && (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) != -1) && (SU2_TYPE::Int(config->GetParamDV(iDV, 3)) != -1)) { for (i = 0; i < FFDBox->GetlOrder(); i++) { index[0] = i; @@ -2023,8 +2111,7 @@ bool CSurfaceMovement::SetFFDNacelle(CGeometry *geometry, CConfig *config, CFree } } - if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) != -1) && - (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) == -1) && + if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) != -1) && (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) == -1) && (SU2_TYPE::Int(config->GetParamDV(iDV, 3)) != -1)) { for (j = 0; j < FFDBox->GetmOrder(); j++) { index[1] = j; @@ -2032,8 +2119,7 @@ bool CSurfaceMovement::SetFFDNacelle(CGeometry *geometry, CConfig *config, CFree } } - if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) != -1) && - (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) != -1) && + if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) != -1) && (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) != -1) && (SU2_TYPE::Int(config->GetParamDV(iDV, 3)) == -1)) { for (k = 0; k < FFDBox->GetnOrder(); k++) { index[2] = k; @@ -2041,8 +2127,7 @@ bool CSurfaceMovement::SetFFDNacelle(CGeometry *geometry, CConfig *config, CFree } } - if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) == -1) && - (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) == -1) && + if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) == -1) && (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) == -1) && (SU2_TYPE::Int(config->GetParamDV(iDV, 3)) != -1)) { for (i = 0; i < FFDBox->GetlOrder(); i++) { index[0] = i; @@ -2053,8 +2138,7 @@ bool CSurfaceMovement::SetFFDNacelle(CGeometry *geometry, CConfig *config, CFree } } - if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) != -1) && - (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) == -1) && + if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) != -1) && (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) == -1) && (SU2_TYPE::Int(config->GetParamDV(iDV, 3)) == -1)) { for (j = 0; j < FFDBox->GetmOrder(); j++) { index[1] = j; @@ -2065,8 +2149,7 @@ bool CSurfaceMovement::SetFFDNacelle(CGeometry *geometry, CConfig *config, CFree } } - if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) == -1) && - (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) != -1) && + if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) == -1) && (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) != -1) && (SU2_TYPE::Int(config->GetParamDV(iDV, 3)) == -1)) { for (i = 0; i < FFDBox->GetlOrder(); i++) { index[0] = i; @@ -2077,26 +2160,22 @@ bool CSurfaceMovement::SetFFDNacelle(CGeometry *geometry, CConfig *config, CFree } } - if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) != -1) && - (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) != -1) && + if ((SU2_TYPE::Int(config->GetParamDV(iDV, 1)) != -1) && (SU2_TYPE::Int(config->GetParamDV(iDV, 2)) != -1) && (SU2_TYPE::Int(config->GetParamDV(iDV, 3)) != -1)) { FFDBox->SetControlPoints(index, movement); } } - } - else { + } else { return false; } return true; - } -bool CSurfaceMovement::SetFFDCamber_2D(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox, CFreeFormDefBox **ResetFFDBox, - unsigned short iDV, bool ResetDef) const { - - su2double Ampl, movement[3] = {0.0,0.0,0.0}; +bool CSurfaceMovement::SetFFDCamber_2D(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBox, + CFreeFormDefBox** ResetFFDBox, unsigned short iDV, bool ResetDef) const { + su2double Ampl, movement[3] = {0.0, 0.0, 0.0}; unsigned short index[3], kIndex, iFFDBox; string design_FFDBox; su2double Scale = config->GetOpt_RelaxFactor(); @@ -2105,44 +2184,41 @@ bool CSurfaceMovement::SetFFDCamber_2D(CGeometry *geometry, CConfig *config, CFr design variable is not in this box) ---*/ if (ResetDef == true) { - for (iFFDBox = 0; iFFDBox < nFFDBox; iFFDBox++) - ResetFFDBox[iFFDBox]->SetOriginalControlPoints(); + for (iFFDBox = 0; iFFDBox < nFFDBox; iFFDBox++) ResetFFDBox[iFFDBox]->SetOriginalControlPoints(); } design_FFDBox = config->GetFFDTag(iDV); if (design_FFDBox.compare(FFDBox->GetTag()) == 0) { - for (kIndex = 0; kIndex < 2; kIndex++) { - - Ampl = config->GetDV_Value(iDV)*Scale; + Ampl = config->GetDV_Value(iDV) * Scale; movement[0] = 0.0; - if (kIndex == 0) movement[1] = Ampl; - else movement[1] = Ampl; + if (kIndex == 0) + movement[1] = Ampl; + else + movement[1] = Ampl; movement[2] = 0.0; - index[0] = SU2_TYPE::Int(config->GetParamDV(iDV, 1)); index[1] = kIndex; index[2] = 0; + index[0] = SU2_TYPE::Int(config->GetParamDV(iDV, 1)); + index[1] = kIndex; + index[2] = 0; FFDBox->SetControlPoints(index, movement); index[2] = 1; FFDBox->SetControlPoints(index, movement); - } - } - else { + } else { return false; } return true; - } -bool CSurfaceMovement::SetFFDThickness_2D(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox, CFreeFormDefBox **ResetFFDBox, - unsigned short iDV, bool ResetDef) const { - - su2double Ampl, movement[3]= {0.0,0.0,0.0}; +bool CSurfaceMovement::SetFFDThickness_2D(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBox, + CFreeFormDefBox** ResetFFDBox, unsigned short iDV, bool ResetDef) const { + su2double Ampl, movement[3] = {0.0, 0.0, 0.0}; unsigned short index[3], kIndex, iFFDBox; string design_FFDBox; su2double Scale = config->GetOpt_RelaxFactor(); @@ -2151,51 +2227,46 @@ bool CSurfaceMovement::SetFFDThickness_2D(CGeometry *geometry, CConfig *config, design variable is not in this box) ---*/ if (ResetDef == true) { - for (iFFDBox = 0; iFFDBox < nFFDBox; iFFDBox++) - ResetFFDBox[iFFDBox]->SetOriginalControlPoints(); + for (iFFDBox = 0; iFFDBox < nFFDBox; iFFDBox++) ResetFFDBox[iFFDBox]->SetOriginalControlPoints(); } design_FFDBox = config->GetFFDTag(iDV); if (design_FFDBox.compare(FFDBox->GetTag()) == 0) { - for (kIndex = 0; kIndex < 2; kIndex++) { - - Ampl = config->GetDV_Value(iDV)*Scale; + Ampl = config->GetDV_Value(iDV) * Scale; movement[0] = 0.0; - if (kIndex == 0) movement[1] = -Ampl; - else movement[1] = Ampl; + if (kIndex == 0) + movement[1] = -Ampl; + else + movement[1] = Ampl; movement[2] = 0.0; - index[0] = SU2_TYPE::Int(config->GetParamDV(iDV, 1)); index[1] = kIndex; index[2] = 0; + index[0] = SU2_TYPE::Int(config->GetParamDV(iDV, 1)); + index[1] = kIndex; + index[2] = 0; FFDBox->SetControlPoints(index, movement); index[2] = 1; FFDBox->SetControlPoints(index, movement); - } - } - else { + } else { return false; } return true; - } -bool CSurfaceMovement::SetFFDTwist_2D(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox, CFreeFormDefBox **ResetFFDBox, - unsigned short iDV, bool ResetDef) { - +bool CSurfaceMovement::SetFFDTwist_2D(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBox, + CFreeFormDefBox** ResetFFDBox, unsigned short iDV, bool ResetDef) { return true; - } -bool CSurfaceMovement::SetFFDCamber(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox, CFreeFormDefBox **ResetFFDBox, - unsigned short iDV, bool ResetDef) const { - - su2double Ampl, movement[3] = {0.0,0.0,0.0}; +bool CSurfaceMovement::SetFFDCamber(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBox, + CFreeFormDefBox** ResetFFDBox, unsigned short iDV, bool ResetDef) const { + su2double Ampl, movement[3] = {0.0, 0.0, 0.0}; unsigned short index[3], kIndex, iPlane, iFFDBox; string design_FFDBox; su2double Scale = config->GetOpt_RelaxFactor(); @@ -2204,76 +2275,68 @@ bool CSurfaceMovement::SetFFDCamber(CGeometry *geometry, CConfig *config, CFreeF design variable is not in this box) ---*/ if (ResetDef == true) { - for (iFFDBox = 0; iFFDBox < nFFDBox; iFFDBox++) - ResetFFDBox[iFFDBox]->SetOriginalControlPoints(); + for (iFFDBox = 0; iFFDBox < nFFDBox; iFFDBox++) ResetFFDBox[iFFDBox]->SetOriginalControlPoints(); } design_FFDBox = config->GetFFDTag(iDV); if (design_FFDBox.compare(FFDBox->GetTag()) == 0) { - /*--- Check that it is possible to move the control point ---*/ for (kIndex = 0; kIndex < 2; kIndex++) { - index[0] = SU2_TYPE::Int(config->GetParamDV(iDV, 1)); index[1] = SU2_TYPE::Int(config->GetParamDV(iDV, 2)); index[2] = kIndex; - for (iPlane = 0 ; iPlane < FFDBox->Get_nFix_IPlane(); iPlane++) { + for (iPlane = 0; iPlane < FFDBox->Get_nFix_IPlane(); iPlane++) { if (index[0] == FFDBox->Get_Fix_IPlane(iPlane)) return false; } - for (iPlane = 0 ; iPlane < FFDBox->Get_nFix_JPlane(); iPlane++) { + for (iPlane = 0; iPlane < FFDBox->Get_nFix_JPlane(); iPlane++) { if (index[1] == FFDBox->Get_Fix_JPlane(iPlane)) return false; } - for (iPlane = 0 ; iPlane < FFDBox->Get_nFix_KPlane(); iPlane++) { + for (iPlane = 0; iPlane < FFDBox->Get_nFix_KPlane(); iPlane++) { if (index[2] == FFDBox->Get_Fix_KPlane(iPlane)) return false; } - } for (kIndex = 0; kIndex < 2; kIndex++) { - - Ampl = config->GetDV_Value(iDV)*Scale; + Ampl = config->GetDV_Value(iDV) * Scale; index[0] = SU2_TYPE::Int(config->GetParamDV(iDV, 1)); index[1] = SU2_TYPE::Int(config->GetParamDV(iDV, 2)); index[2] = kIndex; - movement[0] = 0.0; movement[1] = 0.0; - if (kIndex == 0) movement[2] = Ampl; - else movement[2] = Ampl; + movement[0] = 0.0; + movement[1] = 0.0; + if (kIndex == 0) + movement[2] = Ampl; + else + movement[2] = Ampl; FFDBox->SetControlPoints(index, movement); - } - } - else { + } else { return false; } return true; - } -void CSurfaceMovement::SetFFDAngleOfAttack(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox, CFreeFormDefBox **ResetFFDBox, - unsigned short iDV, bool ResetDef) { - +void CSurfaceMovement::SetFFDAngleOfAttack(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBox, + CFreeFormDefBox** ResetFFDBox, unsigned short iDV, bool ResetDef) { su2double Scale = config->GetOpt_RelaxFactor(); - su2double Ampl = config->GetDV_Value(iDV)*Scale; + su2double Ampl = config->GetDV_Value(iDV) * Scale; config->SetAoA_Offset(Ampl); - } -bool CSurfaceMovement::SetFFDThickness(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox, CFreeFormDefBox **ResetFFDBox, - unsigned short iDV, bool ResetDef) const { - - su2double Ampl, movement[3] = {0.0,0.0,0.0}; +bool CSurfaceMovement::SetFFDThickness(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBox, + CFreeFormDefBox** ResetFFDBox, unsigned short iDV, bool ResetDef) const { + su2double Ampl, movement[3] = {0.0, 0.0, 0.0}; unsigned short index[3], kIndex, iPlane, iFFDBox; string design_FFDBox; su2double Scale = config->GetOpt_RelaxFactor(); @@ -2282,68 +2345,61 @@ bool CSurfaceMovement::SetFFDThickness(CGeometry *geometry, CConfig *config, CFr design variable is not in this box) ---*/ if (ResetDef == true) { - for (iFFDBox = 0; iFFDBox < nFFDBox; iFFDBox++) - ResetFFDBox[iFFDBox]->SetOriginalControlPoints(); + for (iFFDBox = 0; iFFDBox < nFFDBox; iFFDBox++) ResetFFDBox[iFFDBox]->SetOriginalControlPoints(); } design_FFDBox = config->GetFFDTag(iDV); if (design_FFDBox.compare(FFDBox->GetTag()) == 0) { - /*--- Check that it is possible to move the control point ---*/ for (kIndex = 0; kIndex < 2; kIndex++) { - index[0] = SU2_TYPE::Int(config->GetParamDV(iDV, 1)); index[1] = SU2_TYPE::Int(config->GetParamDV(iDV, 2)); index[2] = kIndex; - for (iPlane = 0 ; iPlane < FFDBox->Get_nFix_IPlane(); iPlane++) { + for (iPlane = 0; iPlane < FFDBox->Get_nFix_IPlane(); iPlane++) { if (index[0] == FFDBox->Get_Fix_IPlane(iPlane)) return false; } - for (iPlane = 0 ; iPlane < FFDBox->Get_nFix_JPlane(); iPlane++) { + for (iPlane = 0; iPlane < FFDBox->Get_nFix_JPlane(); iPlane++) { if (index[1] == FFDBox->Get_Fix_JPlane(iPlane)) return false; } - for (iPlane = 0 ; iPlane < FFDBox->Get_nFix_KPlane(); iPlane++) { + for (iPlane = 0; iPlane < FFDBox->Get_nFix_KPlane(); iPlane++) { if (index[2] == FFDBox->Get_Fix_KPlane(iPlane)) return false; } - } - for (kIndex = 0; kIndex < 2; kIndex++) { - - Ampl = config->GetDV_Value(iDV)*Scale; + Ampl = config->GetDV_Value(iDV) * Scale; index[0] = SU2_TYPE::Int(config->GetParamDV(iDV, 1)); index[1] = SU2_TYPE::Int(config->GetParamDV(iDV, 2)); index[2] = kIndex; - movement[0] = 0.0; movement[1] = 0.0; - if (kIndex == 0) movement[2] = -Ampl; - else movement[2] = Ampl; + movement[0] = 0.0; + movement[1] = 0.0; + if (kIndex == 0) + movement[2] = -Ampl; + else + movement[2] = Ampl; FFDBox->SetControlPoints(index, movement); - } - } - else { + } else { return false; } return true; - } -bool CSurfaceMovement::SetFFDTwist(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox, CFreeFormDefBox **ResetFFDBox, - unsigned short iDV, bool ResetDef) const { - +bool CSurfaceMovement::SetFFDTwist(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBox, + CFreeFormDefBox** ResetFFDBox, unsigned short iDV, bool ResetDef) const { unsigned short iOrder, jOrder, kOrder; - su2double x, y, z, movement[3], Segment_P0[3], Segment_P1[3], Plane_P0[3], Plane_Normal[3], - Variable_P0, Variable_P1, Intersection[3], Variable_Interp; + su2double x, y, z, movement[3], Segment_P0[3], Segment_P1[3], Plane_P0[3], Plane_Normal[3], Variable_P0, Variable_P1, + Intersection[3], Variable_Interp; unsigned short index[3], iPlane, iFFDBox; string design_FFDBox; su2double Scale = config->GetOpt_RelaxFactor(); @@ -2352,18 +2408,16 @@ bool CSurfaceMovement::SetFFDTwist(CGeometry *geometry, CConfig *config, CFreeFo design variable is not in this box) ---*/ if (ResetDef == true) { - for (iFFDBox = 0; iFFDBox < nFFDBox; iFFDBox++) - ResetFFDBox[iFFDBox]->SetOriginalControlPoints(); + for (iFFDBox = 0; iFFDBox < nFFDBox; iFFDBox++) ResetFFDBox[iFFDBox]->SetOriginalControlPoints(); } design_FFDBox = config->GetFFDTag(iDV); if (design_FFDBox.compare(FFDBox->GetTag()) == 0) { - /*--- Check that it is possible to move the control point ---*/ jOrder = SU2_TYPE::Int(config->GetParamDV(iDV, 1)); - for (iPlane = 0 ; iPlane < FFDBox->Get_nFix_JPlane(); iPlane++) { + for (iPlane = 0; iPlane < FFDBox->Get_nFix_JPlane(); iPlane++) { if (jOrder == FFDBox->Get_Fix_JPlane(iPlane)) return false; } @@ -2380,19 +2434,25 @@ bool CSurfaceMovement::SetFFDTwist(CGeometry *geometry, CConfig *config, CFreeFo iOrder = 0; jOrder = SU2_TYPE::Int(config->GetParamDV(iDV, 1)); kOrder = 0; - su2double *coord = FFDBox->GetCoordControlPoints(iOrder, jOrder, kOrder); - Plane_P0[0] = coord[0]; Plane_P0[1] = coord[1]; Plane_P0[2] = coord[2]; - Plane_Normal[0] = 0.0; Plane_Normal[1] = 1.0; Plane_Normal[2] = 0.0; + su2double* coord = FFDBox->GetCoordControlPoints(iOrder, jOrder, kOrder); + Plane_P0[0] = coord[0]; + Plane_P0[1] = coord[1]; + Plane_P0[2] = coord[2]; + Plane_Normal[0] = 0.0; + Plane_Normal[1] = 1.0; + Plane_Normal[2] = 0.0; - Variable_P0 = 0.0; Variable_P1 = 0.0; + Variable_P0 = 0.0; + Variable_P1 = 0.0; - Intersection[0] = 0.0; Intersection[1] = 0.0; Intersection[2] = 0.0; + Intersection[0] = 0.0; + Intersection[1] = 0.0; + Intersection[2] = 0.0; - bool result = geometry->SegmentIntersectsPlane(Segment_P0, Segment_P1, Variable_P0, Variable_P1, - Plane_P0, Plane_Normal, Intersection, Variable_Interp); + bool result = geometry->SegmentIntersectsPlane(Segment_P0, Segment_P1, Variable_P0, Variable_P1, Plane_P0, + Plane_Normal, Intersection, Variable_Interp); if (result) { - /*--- xyz-coordinates of a point on the line of rotation. ---*/ su2double a = Intersection[0]; @@ -2409,75 +2469,82 @@ bool CSurfaceMovement::SetFFDTwist(CGeometry *geometry, CConfig *config, CFreeFo otherwise it is difficult to compare with other length based design variables. ---*/ su2double RefLength = config->GetRefLength(); - su2double theta = atan(config->GetDV_Value(iDV)*Scale/RefLength); + su2double theta = atan(config->GetDV_Value(iDV) * Scale / RefLength); /*--- An intermediate value used in computations. ---*/ - su2double u2=u*u; su2double v2=v*v; su2double w2=w*w; - su2double l2 = u2 + v2 + w2; su2double l = sqrt(l2); - su2double cosT; su2double sinT; + su2double u2 = u * u; + su2double v2 = v * v; + su2double w2 = w * w; + su2double l2 = u2 + v2 + w2; + su2double l = sqrt(l2); + su2double cosT; + su2double sinT; /*--- Change the value of the control point if move is true ---*/ jOrder = SU2_TYPE::Int(config->GetParamDV(iDV, 1)); for (iOrder = 0; iOrder < FFDBox->GetlOrder(); iOrder++) for (kOrder = 0; kOrder < FFDBox->GetnOrder(); kOrder++) { - index[0] = iOrder; index[1] = jOrder; index[2] = kOrder; - su2double *coord = FFDBox->GetCoordControlPoints(iOrder, jOrder, kOrder); - x = coord[0]; y = coord[1]; z = coord[2]; + index[0] = iOrder; + index[1] = jOrder; + index[2] = kOrder; + su2double* coord = FFDBox->GetCoordControlPoints(iOrder, jOrder, kOrder); + x = coord[0]; + y = coord[1]; + z = coord[2]; cosT = cos(theta); sinT = sin(theta); - movement[0] = a*(v2 + w2) + u*(-b*v - c*w + u*x + v*y + w*z) - + (-a*(v2 + w2) + u*(b*v + c*w - v*y - w*z) + (v2 + w2)*x)*cosT - + l*(-c*v + b*w - w*y + v*z)*sinT; - movement[0] = movement[0]/l2 - x; + movement[0] = a * (v2 + w2) + u * (-b * v - c * w + u * x + v * y + w * z) + + (-a * (v2 + w2) + u * (b * v + c * w - v * y - w * z) + (v2 + w2) * x) * cosT + + l * (-c * v + b * w - w * y + v * z) * sinT; + movement[0] = movement[0] / l2 - x; - movement[1] = b*(u2 + w2) + v*(-a*u - c*w + u*x + v*y + w*z) - + (-b*(u2 + w2) + v*(a*u + c*w - u*x - w*z) + (u2 + w2)*y)*cosT - + l*(c*u - a*w + w*x - u*z)*sinT; - movement[1] = movement[1]/l2 - y; + movement[1] = b * (u2 + w2) + v * (-a * u - c * w + u * x + v * y + w * z) + + (-b * (u2 + w2) + v * (a * u + c * w - u * x - w * z) + (u2 + w2) * y) * cosT + + l * (c * u - a * w + w * x - u * z) * sinT; + movement[1] = movement[1] / l2 - y; - movement[2] = c*(u2 + v2) + w*(-a*u - b*v + u*x + v*y + w*z) - + (-c*(u2 + v2) + w*(a*u + b*v - u*x - v*y) + (u2 + v2)*z)*cosT - + l*(-b*u + a*v - v*x + u*y)*sinT; - movement[2] = movement[2]/l2 - z; + movement[2] = c * (u2 + v2) + w * (-a * u - b * v + u * x + v * y + w * z) + + (-c * (u2 + v2) + w * (a * u + b * v - u * x - v * y) + (u2 + v2) * z) * cosT + + l * (-b * u + a * v - v * x + u * y) * sinT; + movement[2] = movement[2] / l2 - z; /*--- Check that it is possible to move the control point ---*/ - for (iPlane = 0 ; iPlane < FFDBox->Get_nFix_IPlane(); iPlane++) { + for (iPlane = 0; iPlane < FFDBox->Get_nFix_IPlane(); iPlane++) { if (iOrder == FFDBox->Get_Fix_IPlane(iPlane)) { - movement[0] = 0.0; movement[1] = 0.0; movement[2] = 0.0; + movement[0] = 0.0; + movement[1] = 0.0; + movement[2] = 0.0; } } - for (iPlane = 0 ; iPlane < FFDBox->Get_nFix_KPlane(); iPlane++) { + for (iPlane = 0; iPlane < FFDBox->Get_nFix_KPlane(); iPlane++) { if (kOrder == FFDBox->Get_Fix_KPlane(iPlane)) { - movement[0] = 0.0; movement[1] = 0.0; movement[2] = 0.0; + movement[0] = 0.0; + movement[1] = 0.0; + movement[2] = 0.0; } } FFDBox->SetControlPoints(index, movement); - } - } - } - else { + } else { return false; } return true; - } -bool CSurfaceMovement::SetFFDRotation(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox, CFreeFormDefBox **ResetFFDBox, - unsigned short iDV, bool ResetDef) const { - +bool CSurfaceMovement::SetFFDRotation(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBox, + CFreeFormDefBox** ResetFFDBox, unsigned short iDV, bool ResetDef) const { unsigned short iOrder, jOrder, kOrder; - su2double movement[3] = {0.0,0.0,0.0}, x, y, z; + su2double movement[3] = {0.0, 0.0, 0.0}, x, y, z; unsigned short index[3], iFFDBox; string design_FFDBox; su2double Scale = config->GetOpt_RelaxFactor(); @@ -2486,14 +2553,12 @@ bool CSurfaceMovement::SetFFDRotation(CGeometry *geometry, CConfig *config, CFre design variable is not in this box) ---*/ if (ResetDef == true) { - for (iFFDBox = 0; iFFDBox < nFFDBox; iFFDBox++) - ResetFFDBox[iFFDBox]->SetOriginalControlPoints(); + for (iFFDBox = 0; iFFDBox < nFFDBox; iFFDBox++) ResetFFDBox[iFFDBox]->SetOriginalControlPoints(); } design_FFDBox = config->GetFFDTag(iDV); if (design_FFDBox.compare(FFDBox->GetTag()) == 0) { - /*--- xyz-coordinates of a point on the line of rotation. ---*/ su2double a = config->GetParamDV(iDV, 1); @@ -2502,60 +2567,64 @@ bool CSurfaceMovement::SetFFDRotation(CGeometry *geometry, CConfig *config, CFre /*--- xyz-coordinate of the line's direction vector. ---*/ - su2double u = config->GetParamDV(iDV, 4)-config->GetParamDV(iDV, 1); - su2double v = config->GetParamDV(iDV, 5)-config->GetParamDV(iDV, 2); - su2double w = config->GetParamDV(iDV, 6)-config->GetParamDV(iDV, 3); + su2double u = config->GetParamDV(iDV, 4) - config->GetParamDV(iDV, 1); + su2double v = config->GetParamDV(iDV, 5) - config->GetParamDV(iDV, 2); + su2double w = config->GetParamDV(iDV, 6) - config->GetParamDV(iDV, 3); /*--- The angle of rotation. ---*/ - su2double theta = config->GetDV_Value(iDV)*Scale*PI_NUMBER/180.0; + su2double theta = config->GetDV_Value(iDV) * Scale * PI_NUMBER / 180.0; /*--- An intermediate value used in computations. ---*/ - su2double u2=u*u; su2double v2=v*v; su2double w2=w*w; - su2double cosT = cos(theta); su2double sinT = sin(theta); - su2double l2 = u2 + v2 + w2; su2double l = sqrt(l2); + su2double u2 = u * u; + su2double v2 = v * v; + su2double w2 = w * w; + su2double cosT = cos(theta); + su2double sinT = sin(theta); + su2double l2 = u2 + v2 + w2; + su2double l = sqrt(l2); /*--- Change the value of the control point if move is true ---*/ for (iOrder = 0; iOrder < FFDBox->GetlOrder(); iOrder++) for (jOrder = 0; jOrder < FFDBox->GetmOrder(); jOrder++) for (kOrder = 0; kOrder < FFDBox->GetnOrder(); kOrder++) { - index[0] = iOrder; index[1] = jOrder; index[2] = kOrder; - su2double *coord = FFDBox->GetCoordControlPoints(iOrder, jOrder, kOrder); - x = coord[0]; y = coord[1]; z = coord[2]; - movement[0] = a*(v2 + w2) + u*(-b*v - c*w + u*x + v*y + w*z) - + (-a*(v2 + w2) + u*(b*v + c*w - v*y - w*z) + (v2 + w2)*x)*cosT - + l*(-c*v + b*w - w*y + v*z)*sinT; - movement[0] = movement[0]/l2 - x; - - movement[1] = b*(u2 + w2) + v*(-a*u - c*w + u*x + v*y + w*z) - + (-b*(u2 + w2) + v*(a*u + c*w - u*x - w*z) + (u2 + w2)*y)*cosT - + l*(c*u - a*w + w*x - u*z)*sinT; - movement[1] = movement[1]/l2 - y; - - movement[2] = c*(u2 + v2) + w*(-a*u - b*v + u*x + v*y + w*z) - + (-c*(u2 + v2) + w*(a*u + b*v - u*x - v*y) + (u2 + v2)*z)*cosT - + l*(-b*u + a*v - v*x + u*y)*sinT; - movement[2] = movement[2]/l2 - z; + index[0] = iOrder; + index[1] = jOrder; + index[2] = kOrder; + su2double* coord = FFDBox->GetCoordControlPoints(iOrder, jOrder, kOrder); + x = coord[0]; + y = coord[1]; + z = coord[2]; + movement[0] = a * (v2 + w2) + u * (-b * v - c * w + u * x + v * y + w * z) + + (-a * (v2 + w2) + u * (b * v + c * w - v * y - w * z) + (v2 + w2) * x) * cosT + + l * (-c * v + b * w - w * y + v * z) * sinT; + movement[0] = movement[0] / l2 - x; + + movement[1] = b * (u2 + w2) + v * (-a * u - c * w + u * x + v * y + w * z) + + (-b * (u2 + w2) + v * (a * u + c * w - u * x - w * z) + (u2 + w2) * y) * cosT + + l * (c * u - a * w + w * x - u * z) * sinT; + movement[1] = movement[1] / l2 - y; + + movement[2] = c * (u2 + v2) + w * (-a * u - b * v + u * x + v * y + w * z) + + (-c * (u2 + v2) + w * (a * u + b * v - u * x - v * y) + (u2 + v2) * z) * cosT + + l * (-b * u + a * v - v * x + u * y) * sinT; + movement[2] = movement[2] / l2 - z; FFDBox->SetControlPoints(index, movement); - } - } - else { + } else { return false; } return true; - } -bool CSurfaceMovement::SetFFDControl_Surface(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox, CFreeFormDefBox **ResetFFDBox, - unsigned short iDV, bool ResetDef) const { - +bool CSurfaceMovement::SetFFDControl_Surface(CGeometry* geometry, CConfig* config, CFreeFormDefBox* FFDBox, + CFreeFormDefBox** ResetFFDBox, unsigned short iDV, bool ResetDef) const { unsigned short iOrder, jOrder, kOrder; - su2double movement[3] = {0.0,0.0,0.0}, x, y, z; + su2double movement[3] = {0.0, 0.0, 0.0}, x, y, z; unsigned short index[3], iFFDBox; string design_FFDBox; su2double Scale = config->GetOpt_RelaxFactor(); @@ -2564,14 +2633,12 @@ bool CSurfaceMovement::SetFFDControl_Surface(CGeometry *geometry, CConfig *confi design variable is not in this box) ---*/ if (ResetDef == true) { - for (iFFDBox = 0; iFFDBox < nFFDBox; iFFDBox++) - ResetFFDBox[iFFDBox]->SetOriginalControlPoints(); + for (iFFDBox = 0; iFFDBox < nFFDBox; iFFDBox++) ResetFFDBox[iFFDBox]->SetOriginalControlPoints(); } design_FFDBox = config->GetFFDTag(iDV); if (design_FFDBox.compare(FFDBox->GetTag()) == 0) { - /*--- xyz-coordinates of a point on the line of rotation. ---*/ su2double a = config->GetParamDV(iDV, 1); @@ -2580,69 +2647,72 @@ bool CSurfaceMovement::SetFFDControl_Surface(CGeometry *geometry, CConfig *confi /*--- xyz-coordinate of the line's direction vector. ---*/ - su2double u = config->GetParamDV(iDV, 4)-config->GetParamDV(iDV, 1); - su2double v = config->GetParamDV(iDV, 5)-config->GetParamDV(iDV, 2); - su2double w = config->GetParamDV(iDV, 6)-config->GetParamDV(iDV, 3); + su2double u = config->GetParamDV(iDV, 4) - config->GetParamDV(iDV, 1); + su2double v = config->GetParamDV(iDV, 5) - config->GetParamDV(iDV, 2); + su2double w = config->GetParamDV(iDV, 6) - config->GetParamDV(iDV, 3); /*--- The angle of rotation. ---*/ - su2double theta = -config->GetDV_Value(iDV)*Scale*PI_NUMBER/180.0; + su2double theta = -config->GetDV_Value(iDV) * Scale * PI_NUMBER / 180.0; /*--- An intermediate value used in computations. ---*/ - su2double u2=u*u; su2double v2=v*v; su2double w2=w*w; - su2double cosT = cos(theta); su2double sinT = sin(theta); - su2double l2 = u2 + v2 + w2; su2double l = sqrt(l2); + su2double u2 = u * u; + su2double v2 = v * v; + su2double w2 = w * w; + su2double cosT = cos(theta); + su2double sinT = sin(theta); + su2double l2 = u2 + v2 + w2; + su2double l = sqrt(l2); /*--- Change the value of the control point if move is true ---*/ - for (iOrder = 0; iOrder < FFDBox->GetlOrder()-2; iOrder++) - for (jOrder = 2; jOrder < FFDBox->GetmOrder()-2; jOrder++) + for (iOrder = 0; iOrder < FFDBox->GetlOrder() - 2; iOrder++) + for (jOrder = 2; jOrder < FFDBox->GetmOrder() - 2; jOrder++) for (kOrder = 0; kOrder < FFDBox->GetnOrder(); kOrder++) { - index[0] = iOrder; index[1] = jOrder; index[2] = kOrder; - su2double *coord = FFDBox->GetCoordControlPoints(iOrder, jOrder, kOrder); - x = coord[0]; y = coord[1]; z = coord[2]; - movement[0] = a*(v2 + w2) + u*(-b*v - c*w + u*x + v*y + w*z) - + (-a*(v2 + w2) + u*(b*v + c*w - v*y - w*z) + (v2 + w2)*x)*cosT - + l*(-c*v + b*w - w*y + v*z)*sinT; - movement[0] = movement[0]/l2 - x; - - movement[1] = b*(u2 + w2) + v*(-a*u - c*w + u*x + v*y + w*z) - + (-b*(u2 + w2) + v*(a*u + c*w - u*x - w*z) + (u2 + w2)*y)*cosT - + l*(c*u - a*w + w*x - u*z)*sinT; - movement[1] = movement[1]/l2 - y; - - movement[2] = c*(u2 + v2) + w*(-a*u - b*v + u*x + v*y + w*z) - + (-c*(u2 + v2) + w*(a*u + b*v - u*x - v*y) + (u2 + v2)*z)*cosT - + l*(-b*u + a*v - v*x + u*y)*sinT; - movement[2] = movement[2]/l2 - z; + index[0] = iOrder; + index[1] = jOrder; + index[2] = kOrder; + su2double* coord = FFDBox->GetCoordControlPoints(iOrder, jOrder, kOrder); + x = coord[0]; + y = coord[1]; + z = coord[2]; + movement[0] = a * (v2 + w2) + u * (-b * v - c * w + u * x + v * y + w * z) + + (-a * (v2 + w2) + u * (b * v + c * w - v * y - w * z) + (v2 + w2) * x) * cosT + + l * (-c * v + b * w - w * y + v * z) * sinT; + movement[0] = movement[0] / l2 - x; + + movement[1] = b * (u2 + w2) + v * (-a * u - c * w + u * x + v * y + w * z) + + (-b * (u2 + w2) + v * (a * u + c * w - u * x - w * z) + (u2 + w2) * y) * cosT + + l * (c * u - a * w + w * x - u * z) * sinT; + movement[1] = movement[1] / l2 - y; + + movement[2] = c * (u2 + v2) + w * (-a * u - b * v + u * x + v * y + w * z) + + (-c * (u2 + v2) + w * (a * u + b * v - u * x - v * y) + (u2 + v2) * z) * cosT + + l * (-b * u + a * v - v * x + u * y) * sinT; + movement[2] = movement[2] / l2 - z; FFDBox->SetControlPoints(index, movement); - } - } - else { + } else { return false; } return true; - } -void CSurfaceMovement::SetAngleOfAttack(CGeometry *boundary, CConfig *config, unsigned short iDV, bool ResetDef) { - +void CSurfaceMovement::SetAngleOfAttack(CGeometry* boundary, CConfig* config, unsigned short iDV, bool ResetDef) { su2double Scale = config->GetOpt_RelaxFactor(); - su2double Ampl = config->GetDV_Value(iDV)*Scale; + su2double Ampl = config->GetDV_Value(iDV) * Scale; config->SetAoA_Offset(Ampl); - } -void CSurfaceMovement::SetHicksHenne(CGeometry *boundary, CConfig *config, unsigned short iDV, bool ResetDef) { +void CSurfaceMovement::SetHicksHenne(CGeometry* boundary, CConfig* config, unsigned short iDV, bool ResetDef) { unsigned long iVertex; unsigned short iMarker; - su2double VarCoord[3] = {0.0,0.0,0.0}, VarCoord_[3] = {0.0,0.0,0.0}, *Coord_, *Normal_, ek, fk, - Coord[3] = {0.0,0.0,0.0}, Normal[3] = {0.0,0.0,0.0}, - TPCoord[2] = {0.0, 0.0}, LPCoord[2] = {0.0, 0.0}, Distance, Chord, AoA, ValCos, ValSin; + su2double VarCoord[3] = {0.0, 0.0, 0.0}, VarCoord_[3] = {0.0, 0.0, 0.0}, *Coord_, *Normal_, ek, fk, + Coord[3] = {0.0, 0.0, 0.0}, Normal[3] = {0.0, 0.0, 0.0}, TPCoord[2] = {0.0, 0.0}, LPCoord[2] = {0.0, 0.0}, + Distance, Chord, AoA, ValCos, ValSin; bool upper = true; su2double Scale = config->GetOpt_RelaxFactor(); @@ -2652,7 +2722,9 @@ void CSurfaceMovement::SetHicksHenne(CGeometry *boundary, CConfig *config, unsig if ((iDV == 0) || (ResetDef == true)) { for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) for (iVertex = 0; iVertex < boundary->nVertex[iMarker]; iVertex++) { - VarCoord[0] = 0.0; VarCoord[1] = 0.0; VarCoord[2] = 0.0; + VarCoord[0] = 0.0; + VarCoord[1] = 0.0; + VarCoord[2] = 0.0; boundary->vertex[iMarker][iVertex]->SetVarCoord(VarCoord); } } @@ -2662,10 +2734,14 @@ void CSurfaceMovement::SetHicksHenne(CGeometry *boundary, CConfig *config, unsig for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { if (config->GetMarker_All_DV(iMarker) == YES) { Coord_ = boundary->vertex[iMarker][0]->GetCoord(); - TPCoord[0] = Coord_[0]; TPCoord[1] = Coord_[1]; + TPCoord[0] = Coord_[0]; + TPCoord[1] = Coord_[1]; for (iVertex = 1; iVertex < boundary->nVertex[iMarker]; iVertex++) { Coord_ = boundary->vertex[iMarker][iVertex]->GetCoord(); - if (Coord_[0] > TPCoord[0]) { TPCoord[0] = Coord_[0]; TPCoord[1] = Coord_[1]; } + if (Coord_[0] > TPCoord[0]) { + TPCoord[0] = Coord_[0]; + TPCoord[1] = Coord_[1]; + } } } } @@ -2675,126 +2751,148 @@ void CSurfaceMovement::SetHicksHenne(CGeometry *boundary, CConfig *config, unsig int iProcessor, nProcessor = size; su2double *Buffer_Send_Coord, *Buffer_Receive_Coord; - Buffer_Receive_Coord = new su2double [nProcessor*2]; - Buffer_Send_Coord = new su2double [2]; + Buffer_Receive_Coord = new su2double[nProcessor * 2]; + Buffer_Send_Coord = new su2double[2]; - Buffer_Send_Coord[0] = TPCoord[0]; Buffer_Send_Coord[1] = TPCoord[1]; + Buffer_Send_Coord[0] = TPCoord[0]; + Buffer_Send_Coord[1] = TPCoord[1]; SU2_MPI::Allgather(Buffer_Send_Coord, 2, MPI_DOUBLE, Buffer_Receive_Coord, 2, MPI_DOUBLE, SU2_MPI::GetComm()); - TPCoord[0] = Buffer_Receive_Coord[0]; TPCoord[1] = Buffer_Receive_Coord[1]; + TPCoord[0] = Buffer_Receive_Coord[0]; + TPCoord[1] = Buffer_Receive_Coord[1]; for (iProcessor = 1; iProcessor < nProcessor; iProcessor++) { - Coord[0] = Buffer_Receive_Coord[iProcessor*2 + 0]; - Coord[1] = Buffer_Receive_Coord[iProcessor*2 + 1]; - if (Coord[0] > TPCoord[0]) { TPCoord[0] = Coord[0]; TPCoord[1] = Coord[1]; } + Coord[0] = Buffer_Receive_Coord[iProcessor * 2 + 0]; + Coord[1] = Buffer_Receive_Coord[iProcessor * 2 + 1]; + if (Coord[0] > TPCoord[0]) { + TPCoord[0] = Coord[0]; + TPCoord[1] = Coord[1]; + } } - delete[] Buffer_Send_Coord; delete[] Buffer_Receive_Coord; + delete[] Buffer_Send_Coord; + delete[] Buffer_Receive_Coord; #endif - Chord = 0.0; for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { if (config->GetMarker_All_DV(iMarker) == YES) { for (iVertex = 0; iVertex < boundary->nVertex[iMarker]; iVertex++) { Coord_ = boundary->vertex[iMarker][iVertex]->GetCoord(); Distance = sqrt(pow(Coord_[0] - TPCoord[0], 2.0) + pow(Coord_[1] - TPCoord[1], 2.0)); - if (Chord < Distance) { Chord = Distance; LPCoord[0] = Coord_[0]; LPCoord[1] = Coord_[1]; } + if (Chord < Distance) { + Chord = Distance; + LPCoord[0] = Coord_[0]; + LPCoord[1] = Coord_[1]; + } } } } #ifdef HAVE_MPI - Buffer_Receive_Coord = new su2double [nProcessor*2]; - Buffer_Send_Coord = new su2double [2]; + Buffer_Receive_Coord = new su2double[nProcessor * 2]; + Buffer_Send_Coord = new su2double[2]; - Buffer_Send_Coord[0] = LPCoord[0]; Buffer_Send_Coord[1] = LPCoord[1]; + Buffer_Send_Coord[0] = LPCoord[0]; + Buffer_Send_Coord[1] = LPCoord[1]; SU2_MPI::Allgather(Buffer_Send_Coord, 2, MPI_DOUBLE, Buffer_Receive_Coord, 2, MPI_DOUBLE, SU2_MPI::GetComm()); Chord = 0.0; for (iProcessor = 0; iProcessor < nProcessor; iProcessor++) { - Coord[0] = Buffer_Receive_Coord[iProcessor*2 + 0]; - Coord[1] = Buffer_Receive_Coord[iProcessor*2 + 1]; + Coord[0] = Buffer_Receive_Coord[iProcessor * 2 + 0]; + Coord[1] = Buffer_Receive_Coord[iProcessor * 2 + 1]; Distance = sqrt(pow(Coord[0] - TPCoord[0], 2.0) + pow(Coord[1] - TPCoord[1], 2.0)); - if (Chord < Distance) { Chord = Distance; LPCoord[0] = Coord[0]; LPCoord[1] = Coord[1]; } + if (Chord < Distance) { + Chord = Distance; + LPCoord[0] = Coord[0]; + LPCoord[1] = Coord[1]; + } } - delete[] Buffer_Send_Coord; delete[] Buffer_Receive_Coord; + delete[] Buffer_Send_Coord; + delete[] Buffer_Receive_Coord; #endif - AoA = atan((LPCoord[1] - TPCoord[1]) / (TPCoord[0] - LPCoord[0]))*180/PI_NUMBER; + AoA = atan((LPCoord[1] - TPCoord[1]) / (TPCoord[0] - LPCoord[0])) * 180 / PI_NUMBER; /*--- WARNING: AoA currently overwritten to zero. ---*/ AoA = 0.0; /*--- Perform multiple airfoil deformation ---*/ - su2double Ampl = config->GetDV_Value(iDV)*Scale; + su2double Ampl = config->GetDV_Value(iDV) * Scale; su2double xk = config->GetParamDV(iDV, 1); const su2double t2 = 3.0; - if (config->GetParamDV(iDV, 0) == NO) { upper = false; } - if (config->GetParamDV(iDV, 0) == YES) { upper = true; } + if (config->GetParamDV(iDV, 0) == NO) { + upper = false; + } + if (config->GetParamDV(iDV, 0) == YES) { + upper = true; + } for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { - for (iVertex = 0; iVertex < boundary->nVertex[iMarker]; iVertex++) { - VarCoord[0] = 0.0; VarCoord[1] = 0.0; VarCoord[2] = 0.0; + VarCoord[0] = 0.0; + VarCoord[1] = 0.0; + VarCoord[2] = 0.0; if (config->GetMarker_All_DV(iMarker) == YES) { - Coord_ = boundary->vertex[iMarker][iVertex]->GetCoord(); Normal_ = boundary->vertex[iMarker][iVertex]->GetNormal(); /*--- The Hicks Henne bump functions should be applied to a basic airfoil without AoA, and unitary chord, a tranformation is required ---*/ - ValCos = cos(AoA*PI_NUMBER/180.0); - ValSin = sin(AoA*PI_NUMBER/180.0); + ValCos = cos(AoA * PI_NUMBER / 180.0); + ValSin = sin(AoA * PI_NUMBER / 180.0); - Coord[0] = Coord_[0]*ValCos - Coord_[1]*ValSin; - Coord[0] = max(0.0, Coord[0]); // Coord x should be always positive - Coord[1] = Coord_[1]*ValCos + Coord_[0]*ValSin; + Coord[0] = Coord_[0] * ValCos - Coord_[1] * ValSin; + Coord[0] = max(0.0, Coord[0]); // Coord x should be always positive + Coord[1] = Coord_[1] * ValCos + Coord_[0] * ValSin; - Normal[0] = Normal_[0]*ValCos - Normal_[1]*ValSin; - Normal[1] = Normal_[1]*ValCos + Normal_[0]*ValSin; + Normal[0] = Normal_[0] * ValCos - Normal_[1] * ValSin; + Normal[1] = Normal_[1] * ValCos + Normal_[0] * ValSin; /*--- Bump computation ---*/ - ek = log10(0.5)/log10(xk); - if (Coord[0] > 10*EPS) fk = pow( sin( PI_NUMBER * pow(Coord[0], ek) ), t2); - else fk = 0.0; + ek = log10(0.5) / log10(xk); + if (Coord[0] > 10 * EPS) + fk = pow(sin(PI_NUMBER * pow(Coord[0], ek)), t2); + else + fk = 0.0; /*--- Upper and lower surface ---*/ - if (( upper) && (Normal[1] > 0)) { VarCoord[1] = Ampl*fk; } - if ((!upper) && (Normal[1] < 0)) { VarCoord[1] = -Ampl*fk; } - + if ((upper) && (Normal[1] > 0)) { + VarCoord[1] = Ampl * fk; + } + if ((!upper) && (Normal[1] < 0)) { + VarCoord[1] = -Ampl * fk; + } } /*--- Apply the transformation to the coordinate variation ---*/ - ValCos = cos(-AoA*PI_NUMBER/180.0); - ValSin = sin(-AoA*PI_NUMBER/180.0); + ValCos = cos(-AoA * PI_NUMBER / 180.0); + ValSin = sin(-AoA * PI_NUMBER / 180.0); - VarCoord_[0] = VarCoord[0]*ValCos - VarCoord[1]*ValSin; - VarCoord_[1] = VarCoord[1]*ValCos + VarCoord[0]*ValSin; + VarCoord_[0] = VarCoord[0] * ValCos - VarCoord[1] * ValSin; + VarCoord_[1] = VarCoord[1] * ValCos + VarCoord[0] * ValSin; boundary->vertex[iMarker][iVertex]->AddVarCoord(VarCoord_); - } } - } -void CSurfaceMovement::SetSurface_Bump(CGeometry *boundary, CConfig *config, unsigned short iDV, bool ResetDef) { +void CSurfaceMovement::SetSurface_Bump(CGeometry* boundary, CConfig* config, unsigned short iDV, bool ResetDef) { unsigned long iVertex; unsigned short iMarker; - su2double VarCoord[3] = {0.0,0.0,0.0}, ek, fk, *Coord, xCoord; + su2double VarCoord[3] = {0.0, 0.0, 0.0}, ek, fk, *Coord, xCoord; su2double Scale = config->GetOpt_RelaxFactor(); /*--- Reset airfoil deformation if first deformation or if it required by the solver ---*/ @@ -2802,14 +2900,16 @@ void CSurfaceMovement::SetSurface_Bump(CGeometry *boundary, CConfig *config, uns if ((iDV == 0) || (ResetDef == true)) { for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) for (iVertex = 0; iVertex < boundary->nVertex[iMarker]; iVertex++) { - VarCoord[0] = 0.0; VarCoord[1] = 0.0; VarCoord[2] = 0.0; + VarCoord[0] = 0.0; + VarCoord[1] = 0.0; + VarCoord[2] = 0.0; boundary->vertex[iMarker][iVertex]->SetVarCoord(VarCoord); } } /*--- Perform multiple airfoil deformation ---*/ - su2double Ampl = config->GetDV_Value(iDV)*Scale; + su2double Ampl = config->GetDV_Value(iDV) * Scale; su2double x_start = config->GetParamDV(iDV, 0); su2double x_end = config->GetParamDV(iDV, 1); su2double BumpSize = x_end - x_start; @@ -2818,37 +2918,39 @@ void CSurfaceMovement::SetSurface_Bump(CGeometry *boundary, CConfig *config, uns const su2double t2 = 3.0; for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { - for (iVertex = 0; iVertex < boundary->nVertex[iMarker]; iVertex++) { - VarCoord[0] = 0.0; VarCoord[1] = 0.0; VarCoord[2] = 0.0; + VarCoord[0] = 0.0; + VarCoord[1] = 0.0; + VarCoord[2] = 0.0; if (config->GetMarker_All_DV(iMarker) == YES) { - Coord = boundary->vertex[iMarker][iVertex]->GetCoord(); xCoord = (Coord[0] - BumpLoc); - ek = log10(0.5)/log10((xk-BumpLoc+EPS)/BumpSize); - if (xCoord > 0.0) fk = pow( sin( PI_NUMBER * pow((xCoord+EPS)/BumpSize, ek)), t2); - else fk = 0.0; - - if ((xCoord <= 0.0) || (xCoord >= BumpSize)) VarCoord[1] = 0.0; - else { VarCoord[1] = Ampl*fk; } - + ek = log10(0.5) / log10((xk - BumpLoc + EPS) / BumpSize); + if (xCoord > 0.0) + fk = pow(sin(PI_NUMBER * pow((xCoord + EPS) / BumpSize, ek)), t2); + else + fk = 0.0; + + if ((xCoord <= 0.0) || (xCoord >= BumpSize)) + VarCoord[1] = 0.0; + else { + VarCoord[1] = Ampl * fk; + } } boundary->vertex[iMarker][iVertex]->AddVarCoord(VarCoord); - } } - } -void CSurfaceMovement::SetCST(CGeometry *boundary, CConfig *config, unsigned short iDV, bool ResetDef) { +void CSurfaceMovement::SetCST(CGeometry* boundary, CConfig* config, unsigned short iDV, bool ResetDef) { unsigned long iVertex; unsigned short iMarker; - su2double VarCoord[3] = {0.0,0.0,0.0}, VarCoord_[3] = {0.0,0.0,0.0}, *Coord_, *Normal_, fk, - Coord[3] = {0.0,0.0,0.0}, Normal[3] = {0.0,0.0,0.0}, - TPCoord[2] = {0.0, 0.0}, LPCoord[2] = {0.0, 0.0}, Distance, Chord, AoA, ValCos, ValSin; + su2double VarCoord[3] = {0.0, 0.0, 0.0}, VarCoord_[3] = {0.0, 0.0, 0.0}, *Coord_, *Normal_, fk, + Coord[3] = {0.0, 0.0, 0.0}, Normal[3] = {0.0, 0.0, 0.0}, TPCoord[2] = {0.0, 0.0}, LPCoord[2] = {0.0, 0.0}, + Distance, Chord, AoA, ValCos, ValSin; bool upper = true; su2double Scale = config->GetOpt_RelaxFactor(); @@ -2858,20 +2960,26 @@ void CSurfaceMovement::SetCST(CGeometry *boundary, CConfig *config, unsigned sho if ((iDV == 0) || (ResetDef == true)) { for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) for (iVertex = 0; iVertex < boundary->nVertex[iMarker]; iVertex++) { - VarCoord[0] = 0.0; VarCoord[1] = 0.0; VarCoord[2] = 0.0; + VarCoord[0] = 0.0; + VarCoord[1] = 0.0; + VarCoord[2] = 0.0; boundary->vertex[iMarker][iVertex]->SetVarCoord(VarCoord); } } - /*--- Compute the angle of attack to apply the deformation ---*/ + /*--- Compute the angle of attack to apply the deformation ---*/ for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { if (config->GetMarker_All_DV(iMarker) == YES) { Coord_ = boundary->vertex[iMarker][0]->GetCoord(); - TPCoord[0] = Coord_[0]; TPCoord[1] = Coord_[1]; + TPCoord[0] = Coord_[0]; + TPCoord[1] = Coord_[1]; for (iVertex = 1; iVertex < boundary->nVertex[iMarker]; iVertex++) { Coord_ = boundary->vertex[iMarker][iVertex]->GetCoord(); - if (Coord_[0] > TPCoord[0]) { TPCoord[0] = Coord_[0]; TPCoord[1] = Coord_[1]; } + if (Coord_[0] > TPCoord[0]) { + TPCoord[0] = Coord_[0]; + TPCoord[1] = Coord_[1]; + } } } } @@ -2881,65 +2989,80 @@ void CSurfaceMovement::SetCST(CGeometry *boundary, CConfig *config, unsigned sho int iProcessor, nProcessor = size; su2double *Buffer_Send_Coord, *Buffer_Receive_Coord; - Buffer_Receive_Coord = new su2double [nProcessor*2]; - Buffer_Send_Coord = new su2double [2]; + Buffer_Receive_Coord = new su2double[nProcessor * 2]; + Buffer_Send_Coord = new su2double[2]; - Buffer_Send_Coord[0] = TPCoord[0]; Buffer_Send_Coord[1] = TPCoord[1]; + Buffer_Send_Coord[0] = TPCoord[0]; + Buffer_Send_Coord[1] = TPCoord[1]; SU2_MPI::Allgather(Buffer_Send_Coord, 2, MPI_DOUBLE, Buffer_Receive_Coord, 2, MPI_DOUBLE, SU2_MPI::GetComm()); - TPCoord[0] = Buffer_Receive_Coord[0]; TPCoord[1] = Buffer_Receive_Coord[1]; + TPCoord[0] = Buffer_Receive_Coord[0]; + TPCoord[1] = Buffer_Receive_Coord[1]; for (iProcessor = 1; iProcessor < nProcessor; iProcessor++) { - Coord[0] = Buffer_Receive_Coord[iProcessor*2 + 0]; - Coord[1] = Buffer_Receive_Coord[iProcessor*2 + 1]; - if (Coord[0] > TPCoord[0]) { TPCoord[0] = Coord[0]; TPCoord[1] = Coord[1]; } + Coord[0] = Buffer_Receive_Coord[iProcessor * 2 + 0]; + Coord[1] = Buffer_Receive_Coord[iProcessor * 2 + 1]; + if (Coord[0] > TPCoord[0]) { + TPCoord[0] = Coord[0]; + TPCoord[1] = Coord[1]; + } } - delete[] Buffer_Send_Coord; delete[] Buffer_Receive_Coord; + delete[] Buffer_Send_Coord; + delete[] Buffer_Receive_Coord; #endif - Chord = 0.0; for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { if (config->GetMarker_All_DV(iMarker) == YES) { for (iVertex = 0; iVertex < boundary->nVertex[iMarker]; iVertex++) { Coord_ = boundary->vertex[iMarker][iVertex]->GetCoord(); Distance = sqrt(pow(Coord_[0] - TPCoord[0], 2.0) + pow(Coord_[1] - TPCoord[1], 2.0)); - if (Chord < Distance) { Chord = Distance; LPCoord[0] = Coord_[0]; LPCoord[1] = Coord_[1]; } + if (Chord < Distance) { + Chord = Distance; + LPCoord[0] = Coord_[0]; + LPCoord[1] = Coord_[1]; + } } } } #ifdef HAVE_MPI - Buffer_Receive_Coord = new su2double [nProcessor*2]; - Buffer_Send_Coord = new su2double [2]; + Buffer_Receive_Coord = new su2double[nProcessor * 2]; + Buffer_Send_Coord = new su2double[2]; - Buffer_Send_Coord[0] = LPCoord[0]; Buffer_Send_Coord[1] = LPCoord[1]; + Buffer_Send_Coord[0] = LPCoord[0]; + Buffer_Send_Coord[1] = LPCoord[1]; SU2_MPI::Allgather(Buffer_Send_Coord, 2, MPI_DOUBLE, Buffer_Receive_Coord, 2, MPI_DOUBLE, SU2_MPI::GetComm()); Chord = 0.0; for (iProcessor = 0; iProcessor < nProcessor; iProcessor++) { - Coord[0] = Buffer_Receive_Coord[iProcessor*2 + 0]; - Coord[1] = Buffer_Receive_Coord[iProcessor*2 + 1]; + Coord[0] = Buffer_Receive_Coord[iProcessor * 2 + 0]; + Coord[1] = Buffer_Receive_Coord[iProcessor * 2 + 1]; Distance = sqrt(pow(Coord[0] - TPCoord[0], 2.0) + pow(Coord[1] - TPCoord[1], 2.0)); - if (Chord < Distance) { Chord = Distance; LPCoord[0] = Coord[0]; LPCoord[1] = Coord[1]; } + if (Chord < Distance) { + Chord = Distance; + LPCoord[0] = Coord[0]; + LPCoord[1] = Coord[1]; + } } - delete[] Buffer_Send_Coord; delete[] Buffer_Receive_Coord; + delete[] Buffer_Send_Coord; + delete[] Buffer_Receive_Coord; #endif - AoA = atan((LPCoord[1] - TPCoord[1]) / (TPCoord[0] - LPCoord[0]))*180/PI_NUMBER; + AoA = atan((LPCoord[1] - TPCoord[1]) / (TPCoord[0] - LPCoord[0])) * 180 / PI_NUMBER; /*--- WARNING: AoA currently overwritten to zero. ---*/ AoA = 0.0; /*--- Perform multiple airfoil deformation ---*/ - su2double Ampl = config->GetDV_Value(iDV)*Scale; + su2double Ampl = config->GetDV_Value(iDV) * Scale; su2double KulfanNum = config->GetParamDV(iDV, 1) - 1.0; su2double maxKulfanNum = config->GetParamDV(iDV, 2) - 1.0; if (KulfanNum < 0) { @@ -2949,80 +3072,88 @@ void CSurfaceMovement::SetCST(CGeometry *boundary, CConfig *config, unsigned sho std::cout << "Warning: Kulfan number should be less than provided maximum." << std::endl; } - if (config->GetParamDV(iDV, 0) == NO) { upper = false;} - if (config->GetParamDV(iDV, 0) == YES) { upper = true;} + if (config->GetParamDV(iDV, 0) == NO) { + upper = false; + } + if (config->GetParamDV(iDV, 0) == YES) { + upper = true; + } for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { - for (iVertex = 0; iVertex < boundary->nVertex[iMarker]; iVertex++) { - VarCoord[0] = 0.0; VarCoord[1] = 0.0; VarCoord[2] = 0.0; + VarCoord[0] = 0.0; + VarCoord[1] = 0.0; + VarCoord[2] = 0.0; if (config->GetMarker_All_DV(iMarker) == YES) { - Coord_ = boundary->vertex[iMarker][iVertex]->GetCoord(); Normal_ = boundary->vertex[iMarker][iVertex]->GetNormal(); /*--- The CST functions should be applied to a basic airfoil without AoA, and unitary chord, a tranformation is required ---*/ - ValCos = cos(AoA*PI_NUMBER/180.0); - ValSin = sin(AoA*PI_NUMBER/180.0); + ValCos = cos(AoA * PI_NUMBER / 180.0); + ValSin = sin(AoA * PI_NUMBER / 180.0); - Coord[0] = Coord_[0]*ValCos - Coord_[1]*ValSin; - Coord[0] = max(0.0, Coord[0]); // Coord x should be always positive - Coord[1] = Coord_[1]*ValCos + Coord_[0]*ValSin; + Coord[0] = Coord_[0] * ValCos - Coord_[1] * ValSin; + Coord[0] = max(0.0, Coord[0]); // Coord x should be always positive + Coord[1] = Coord_[1] * ValCos + Coord_[0] * ValSin; - Normal[0] = Normal_[0]*ValCos - Normal_[1]*ValSin; - Normal[1] = Normal_[1]*ValCos + Normal_[0]*ValSin; + Normal[0] = Normal_[0] * ValCos - Normal_[1] * ValSin; + Normal[1] = Normal_[1] * ValCos + Normal_[0] * ValSin; /*--- CST computation ---*/ su2double fact_n = 1; su2double fact_cst = 1; su2double fact_cst_n = 1; - for (int i = 1; i <= maxKulfanNum; i++) { - fact_n = fact_n * i; - } - for (int i = 1; i <= KulfanNum; i++) { - fact_cst = fact_cst * i; - } - for (int i = 1; i <= maxKulfanNum - KulfanNum; i++) { - fact_cst_n = fact_cst_n * i; - } - - // CST method only for 2D NACA type airfoils - su2double N1, N2; - N1 = 0.5; - N2 = 1.0; - - /*--- Upper and lower surface change in coordinates based on CST equations by Kulfan et. al (www.brendakulfan.com/docs/CST3.pdf) ---*/ - fk = pow(Coord[0],N1)*pow((1-Coord[0]), N2) * fact_n/(fact_cst*(fact_cst_n)) * pow(Coord[0], KulfanNum) * pow((1-Coord[0]), (maxKulfanNum-(KulfanNum))); + for (int i = 1; i <= maxKulfanNum; i++) { + fact_n = fact_n * i; + } + for (int i = 1; i <= KulfanNum; i++) { + fact_cst = fact_cst * i; + } + for (int i = 1; i <= maxKulfanNum - KulfanNum; i++) { + fact_cst_n = fact_cst_n * i; + } - if (( upper) && (Normal[1] > 0)) { VarCoord[1] = Ampl*fk; } + // CST method only for 2D NACA type airfoils + su2double N1, N2; + N1 = 0.5; + N2 = 1.0; - if ((!upper) && (Normal[1] < 0)) { VarCoord[1] = Ampl*fk; } + /*--- Upper and lower surface change in coordinates based on CST equations by Kulfan et. al + * (www.brendakulfan.com/docs/CST3.pdf) ---*/ + fk = pow(Coord[0], N1) * pow((1 - Coord[0]), N2) * fact_n / (fact_cst * (fact_cst_n)) * + pow(Coord[0], KulfanNum) * pow((1 - Coord[0]), (maxKulfanNum - (KulfanNum))); + if ((upper) && (Normal[1] > 0)) { + VarCoord[1] = Ampl * fk; + } - } + if ((!upper) && (Normal[1] < 0)) { + VarCoord[1] = Ampl * fk; + } + } /*--- Apply the transformation to the coordinate variation ---*/ - ValCos = cos(-AoA*PI_NUMBER/180.0); - ValSin = sin(-AoA*PI_NUMBER/180.0); + ValCos = cos(-AoA * PI_NUMBER / 180.0); + ValSin = sin(-AoA * PI_NUMBER / 180.0); - VarCoord_[0] = VarCoord[0]*ValCos - VarCoord[1]*ValSin; - VarCoord_[1] = VarCoord[1]*ValCos + VarCoord[0]*ValSin; + VarCoord_[0] = VarCoord[0] * ValCos - VarCoord[1] * ValSin; + VarCoord_[1] = VarCoord[1] * ValCos + VarCoord[0] * ValSin; - boundary->vertex[iMarker][iVertex]->AddVarCoord(VarCoord_); + boundary->vertex[iMarker][iVertex]->AddVarCoord(VarCoord_); } } } -void CSurfaceMovement::SetRotation(CGeometry *boundary, CConfig *config, unsigned short iDV, bool ResetDef) { +void CSurfaceMovement::SetRotation(CGeometry* boundary, CConfig* config, unsigned short iDV, bool ResetDef) { unsigned long iVertex; unsigned short iMarker; - su2double VarCoord[3] = {0.0,0.0,0.0}, *Coord; - su2double movement[3] = {0.0,0.0,0.0}, x, y, z; + su2double VarCoord[3] = {0.0, 0.0, 0.0}, *Coord; + su2double movement[3] = {0.0, 0.0, 0.0}, x, y, z; su2double Scale = config->GetOpt_RelaxFactor(); /*--- Reset airfoil deformation if first deformation or if it required by the solver ---*/ @@ -3030,7 +3161,9 @@ void CSurfaceMovement::SetRotation(CGeometry *boundary, CConfig *config, unsigne if ((iDV == 0) || (ResetDef == true)) { for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) for (iVertex = 0; iVertex < boundary->nVertex[iMarker]; iVertex++) { - VarCoord[0] = 0.0; VarCoord[1] = 0.0; VarCoord[2] = 0.0; + VarCoord[0] = 0.0; + VarCoord[1] = 0.0; + VarCoord[2] = 0.0; boundary->vertex[iMarker][iVertex]->SetVarCoord(VarCoord); } } @@ -3040,70 +3173,81 @@ void CSurfaceMovement::SetRotation(CGeometry *boundary, CConfig *config, unsigne su2double a = config->GetParamDV(iDV, 0); su2double b = config->GetParamDV(iDV, 1); su2double c = 0.0; - if (boundary->GetnDim() == 3) c = config->GetParamDV(0,2); + if (boundary->GetnDim() == 3) c = config->GetParamDV(0, 2); /*--- xyz-coordinate of the line's direction vector. ---*/ - su2double u = config->GetParamDV(iDV, 3)-config->GetParamDV(iDV, 0); - su2double v = config->GetParamDV(iDV, 4)-config->GetParamDV(iDV, 1); + su2double u = config->GetParamDV(iDV, 3) - config->GetParamDV(iDV, 0); + su2double v = config->GetParamDV(iDV, 4) - config->GetParamDV(iDV, 1); su2double w = 1.0; - if (boundary->GetnDim() == 3) w = config->GetParamDV(iDV, 5)-config->GetParamDV(iDV, 2); + if (boundary->GetnDim() == 3) w = config->GetParamDV(iDV, 5) - config->GetParamDV(iDV, 2); /*--- The angle of rotation. ---*/ - su2double theta = config->GetDV_Value(iDV)*Scale*PI_NUMBER/180.0; + su2double theta = config->GetDV_Value(iDV) * Scale * PI_NUMBER / 180.0; /*--- An intermediate value used in computations. ---*/ - su2double u2=u*u; su2double v2=v*v; su2double w2=w*w; - su2double cosT = cos(theta); su2double sinT = sin(theta); - su2double l2 = u2 + v2 + w2; su2double l = sqrt(l2); + su2double u2 = u * u; + su2double v2 = v * v; + su2double w2 = w * w; + su2double cosT = cos(theta); + su2double sinT = sin(theta); + su2double l2 = u2 + v2 + w2; + su2double l = sqrt(l2); for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) for (iVertex = 0; iVertex < boundary->nVertex[iMarker]; iVertex++) { - VarCoord[0] = 0.0; VarCoord[1] = 0.0; VarCoord[2] = 0.0; + VarCoord[0] = 0.0; + VarCoord[1] = 0.0; + VarCoord[2] = 0.0; if (config->GetMarker_All_DV(iMarker) == YES) { Coord = boundary->vertex[iMarker][iVertex]->GetCoord(); - x = Coord[0]; y = Coord[1]; z = Coord[2]; - - movement[0] = a*(v2 + w2) + u*(-b*v - c*w + u*x + v*y + w*z) - + (-a*(v2 + w2) + u*(b*v + c*w - v*y - w*z) + (v2 + w2)*x)*cosT - + l*(-c*v + b*w - w*y + v*z)*sinT; - movement[0] = movement[0]/l2 - x; - - movement[1] = b*(u2 + w2) + v*(-a*u - c*w + u*x + v*y + w*z) - + (-b*(u2 + w2) + v*(a*u + c*w - u*x - w*z) + (u2 + w2)*y)*cosT - + l*(c*u - a*w + w*x - u*z)*sinT; - movement[1] = movement[1]/l2 - y; - - movement[2] = c*(u2 + v2) + w*(-a*u - b*v + u*x + v*y + w*z) - + (-c*(u2 + v2) + w*(a*u + b*v - u*x - v*y) + (u2 + v2)*z)*cosT - + l*(-b*u + a*v - v*x + u*y)*sinT; - if (boundary->GetnDim() == 3) movement[2] = movement[2]/l2 - z; - else movement[2] = 0.0; + x = Coord[0]; + y = Coord[1]; + z = Coord[2]; + + movement[0] = a * (v2 + w2) + u * (-b * v - c * w + u * x + v * y + w * z) + + (-a * (v2 + w2) + u * (b * v + c * w - v * y - w * z) + (v2 + w2) * x) * cosT + + l * (-c * v + b * w - w * y + v * z) * sinT; + movement[0] = movement[0] / l2 - x; + + movement[1] = b * (u2 + w2) + v * (-a * u - c * w + u * x + v * y + w * z) + + (-b * (u2 + w2) + v * (a * u + c * w - u * x - w * z) + (u2 + w2) * y) * cosT + + l * (c * u - a * w + w * x - u * z) * sinT; + movement[1] = movement[1] / l2 - y; + + movement[2] = c * (u2 + v2) + w * (-a * u - b * v + u * x + v * y + w * z) + + (-c * (u2 + v2) + w * (a * u + b * v - u * x - v * y) + (u2 + v2) * z) * cosT + + l * (-b * u + a * v - v * x + u * y) * sinT; + if (boundary->GetnDim() == 3) + movement[2] = movement[2] / l2 - z; + else + movement[2] = 0.0; VarCoord[0] = movement[0]; VarCoord[1] = movement[1]; if (boundary->GetnDim() == 3) VarCoord[2] = movement[2]; - } boundary->vertex[iMarker][iVertex]->AddVarCoord(VarCoord); } } -void CSurfaceMovement::SetTranslation(CGeometry *boundary, CConfig *config, unsigned short iDV, bool ResetDef) { +void CSurfaceMovement::SetTranslation(CGeometry* boundary, CConfig* config, unsigned short iDV, bool ResetDef) { unsigned long iVertex; unsigned short iMarker; - su2double VarCoord[3] = {0.0,0.0,0.0}; + su2double VarCoord[3] = {0.0, 0.0, 0.0}; su2double Scale = config->GetOpt_RelaxFactor(); - su2double Ampl = config->GetDV_Value(iDV)*Scale; + su2double Ampl = config->GetDV_Value(iDV) * Scale; /*--- Reset airfoil deformation if first deformation or if it required by the solver ---*/ if ((iDV == 0) || (ResetDef == true)) { for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) for (iVertex = 0; iVertex < boundary->nVertex[iMarker]; iVertex++) { - VarCoord[0] = 0.0; VarCoord[1] = 0.0; VarCoord[2] = 0.0; + VarCoord[0] = 0.0; + VarCoord[1] = 0.0; + VarCoord[2] = 0.0; boundary->vertex[iMarker][iVertex]->SetVarCoord(VarCoord); } } @@ -3115,59 +3259,66 @@ void CSurfaceMovement::SetTranslation(CGeometry *boundary, CConfig *config, unsi for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) for (iVertex = 0; iVertex < boundary->nVertex[iMarker]; iVertex++) { - VarCoord[0] = 0.0; VarCoord[1] = 0.0; VarCoord[2] = 0.0; + VarCoord[0] = 0.0; + VarCoord[1] = 0.0; + VarCoord[2] = 0.0; if (config->GetMarker_All_DV(iMarker) == YES) { - VarCoord[0] = Ampl*xDispl; - VarCoord[1] = Ampl*yDispl; - if (boundary->GetnDim() == 3) VarCoord[2] = Ampl*zDispl; + VarCoord[0] = Ampl * xDispl; + VarCoord[1] = Ampl * yDispl; + if (boundary->GetnDim() == 3) VarCoord[2] = Ampl * zDispl; } boundary->vertex[iMarker][iVertex]->AddVarCoord(VarCoord); } - } -void CSurfaceMovement::SetScale(CGeometry *boundary, CConfig *config, unsigned short iDV, bool ResetDef) { +void CSurfaceMovement::SetScale(CGeometry* boundary, CConfig* config, unsigned short iDV, bool ResetDef) { unsigned long iVertex; unsigned short iMarker; - su2double VarCoord[3] = {0.0,0.0,0.0}, x, y, z, *Coord; + su2double VarCoord[3] = {0.0, 0.0, 0.0}, x, y, z, *Coord; su2double Scale = config->GetOpt_RelaxFactor(); - su2double Ampl = config->GetDV_Value(iDV)*Scale; + su2double Ampl = config->GetDV_Value(iDV) * Scale; /*--- Reset airfoil deformation if first deformation or if it required by the solver ---*/ if ((iDV == 0) || (ResetDef == true)) { for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) for (iVertex = 0; iVertex < boundary->nVertex[iMarker]; iVertex++) { - VarCoord[0] = 0.0; VarCoord[1] = 0.0; VarCoord[2] = 0.0; + VarCoord[0] = 0.0; + VarCoord[1] = 0.0; + VarCoord[2] = 0.0; boundary->vertex[iMarker][iVertex]->SetVarCoord(VarCoord); } } for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) for (iVertex = 0; iVertex < boundary->nVertex[iMarker]; iVertex++) { - VarCoord[0] = 0.0; VarCoord[1] = 0.0; VarCoord[2] = 0.0; + VarCoord[0] = 0.0; + VarCoord[1] = 0.0; + VarCoord[2] = 0.0; if (config->GetMarker_All_DV(iMarker) == YES) { Coord = boundary->vertex[iMarker][iVertex]->GetCoord(); - x = Coord[0]; y = Coord[1]; z = Coord[2]; - VarCoord[0] = (Ampl-1.0)*x; - VarCoord[1] = (Ampl-1.0)*y; - if (boundary->GetnDim() == 3) VarCoord[2] = (Ampl-1.0)*z; + x = Coord[0]; + y = Coord[1]; + z = Coord[2]; + VarCoord[0] = (Ampl - 1.0) * x; + VarCoord[1] = (Ampl - 1.0) * y; + if (boundary->GetnDim() == 3) VarCoord[2] = (Ampl - 1.0) * z; } boundary->vertex[iMarker][iVertex]->AddVarCoord(VarCoord); } - } -void CSurfaceMovement::AeroelasticDeform(CGeometry *geometry, CConfig *config, unsigned long TimeIter, unsigned short iMarker, unsigned short iMarker_Monitoring, vector& displacements) { - +void CSurfaceMovement::AeroelasticDeform(CGeometry* geometry, CConfig* config, unsigned long TimeIter, + unsigned short iMarker, unsigned short iMarker_Monitoring, + vector& displacements) { /* The sign conventions of these are those of the Typical Section Wing Model, below the signs are corrected */ - su2double dh = -displacements[0]; // relative plunge - su2double dalpha = -displacements[1]; // relative pitch + su2double dh = -displacements[0]; // relative plunge + su2double dalpha = -displacements[1]; // relative pitch su2double dh_x, dh_y; su2double Center[2]; unsigned short iDim; su2double Lref = config->GetLength_Ref(); - su2double *Coord; + su2double* Coord; unsigned long iPoint, iVertex; su2double x_new, y_new; su2double VarCoord[3]; @@ -3177,24 +3328,22 @@ void CSurfaceMovement::AeroelasticDeform(CGeometry *geometry, CConfig *config, u if (config->GetKind_GridMovement() == AEROELASTIC_RIGID_MOTION) { su2double Omega, dt, psi; dt = config->GetDelta_UnstTimeND(); - Omega = config->GetRotation_Rate(2)/config->GetOmega_Ref(); - psi = Omega*(dt*TimeIter); + Omega = config->GetRotation_Rate(2) / config->GetOmega_Ref(); + psi = Omega * (dt * TimeIter); /*--- Correct for the airfoil starting position (This is hardcoded in here) ---*/ if (Monitoring_Tag == "Airfoil1") { psi = psi + 0.0; - } - else if (Monitoring_Tag == "Airfoil2") { - psi = psi + 2.0/3.0*PI_NUMBER; - } - else if (Monitoring_Tag == "Airfoil3") { - psi = psi + 4.0/3.0*PI_NUMBER; - } - else - cout << "WARNING: There is a marker that we are monitoring that doesn't match the values hardcoded above!" << endl; + } else if (Monitoring_Tag == "Airfoil2") { + psi = psi + 2.0 / 3.0 * PI_NUMBER; + } else if (Monitoring_Tag == "Airfoil3") { + psi = psi + 4.0 / 3.0 * PI_NUMBER; + } else + cout << "WARNING: There is a marker that we are monitoring that doesn't match the values hardcoded above!" + << endl; - dh_x = -dh*sin(psi); - dh_y = dh*cos(psi); + dh_x = -dh * sin(psi); + dh_y = dh * cos(psi); } else { dh_x = 0; @@ -3212,15 +3361,14 @@ void CSurfaceMovement::AeroelasticDeform(CGeometry *geometry, CConfig *config, u Coord = geometry->nodes->GetCoord(iPoint); /*--- Calculate non-dim. position from rotation center ---*/ - su2double r[2] = {0,0}; - for (iDim = 0; iDim < geometry->GetnDim(); iDim++) - r[iDim] = (Coord[iDim]-Center[iDim])/Lref; + su2double r[2] = {0, 0}; + for (iDim = 0; iDim < geometry->GetnDim(); iDim++) r[iDim] = (Coord[iDim] - Center[iDim]) / Lref; /*--- Compute delta of transformed point coordinates ---*/ // The deltas are needed for the FEA grid deformation Method. // rotation contribution - previous position + plunging contribution - x_new = cos(dalpha)*r[0] - sin(dalpha)*r[1] -r[0] + dh_x; - y_new = sin(dalpha)*r[0] + cos(dalpha)*r[1] -r[1] + dh_y; + x_new = cos(dalpha) * r[0] - sin(dalpha) * r[1] - r[0] + dh_x; + y_new = sin(dalpha) * r[0] + cos(dalpha) * r[1] - r[1] + dh_y; VarCoord[0] = x_new; VarCoord[1] = y_new; @@ -3230,20 +3378,17 @@ void CSurfaceMovement::AeroelasticDeform(CGeometry *geometry, CConfig *config, u geometry->vertex[iMarker][iVertex]->SetVarCoord(VarCoord); } /*--- Set the elastic axis to the new location after incrementing the position with the plunge ---*/ - config->SetRefOriginMoment_X(iMarker_Monitoring, Center[0]+dh_x); - config->SetRefOriginMoment_Y(iMarker_Monitoring, Center[1]+dh_y); - - + config->SetRefOriginMoment_X(iMarker_Monitoring, Center[0] + dh_x); + config->SetRefOriginMoment_Y(iMarker_Monitoring, Center[1] + dh_y); } -void CSurfaceMovement::SetBoundary_Flutter3D(CGeometry *geometry, CConfig *config, - CFreeFormDefBox **FFDBox, unsigned long iter, unsigned short iZone) { - +void CSurfaceMovement::SetBoundary_Flutter3D(CGeometry* geometry, CConfig* config, CFreeFormDefBox** FFDBox, + unsigned long iter, unsigned short iZone) { su2double omega, deltaT; su2double alpha, alpha_new, alpha_old; su2double time_new, time_old; su2double Omega[3], Ampl[3]; - su2double DEG2RAD = PI_NUMBER/180.0; + su2double DEG2RAD = PI_NUMBER / 180.0; bool adjoint = (config->GetContinuous_Adjoint() || config->GetDiscrete_Adjoint()); unsigned short iDim = 0; @@ -3253,50 +3398,49 @@ void CSurfaceMovement::SetBoundary_Flutter3D(CGeometry *geometry, CConfig *confi /*--- Pitching origin, frequency, and amplitude from config. ---*/ - for (iDim = 0; iDim < 3; iDim++){ - Omega[iDim] = config->GetPitching_Omega(iDim)/config->GetOmega_Ref(); - Ampl[iDim] = config->GetPitching_Ampl(iDim)*DEG2RAD; + for (iDim = 0; iDim < 3; iDim++) { + Omega[iDim] = config->GetPitching_Omega(iDim) / config->GetOmega_Ref(); + Ampl[iDim] = config->GetPitching_Ampl(iDim) * DEG2RAD; } /*--- Compute delta time based on physical time step ---*/ if (adjoint) { - /*--- For the unsteady adjoint, we integrate backwards through physical time, so perform mesh motion in reverse. ---*/ - unsigned long nFlowIter = config->GetnTime_Iter(); + unsigned long nFlowIter = config->GetnTime_Iter(); unsigned long directIter = nFlowIter - iter - 1; - time_new = static_cast(directIter)*deltaT; + time_new = static_cast(directIter) * deltaT; time_old = time_new; - if (iter != 0) time_old = (static_cast(directIter)+1.0)*deltaT; + if (iter != 0) time_old = (static_cast(directIter) + 1.0) * deltaT; } else { - /*--- Forward time for the direct problem ---*/ - time_new = static_cast(iter)*deltaT; + time_new = static_cast(iter) * deltaT; time_old = time_new; - if (iter != 0) time_old = (static_cast(iter)-1.0)*deltaT; + if (iter != 0) time_old = (static_cast(iter) - 1.0) * deltaT; } /*--- Update the pitching angle at this time step. Flip sign for nose-up positive convention. ---*/ - omega = Omega[2]; - alpha_new = Ampl[2]*sin(omega*time_new); - alpha_old = Ampl[2]*sin(omega*time_old); - alpha = (1E-10 + (alpha_new - alpha_old))*(-PI_NUMBER/180.0); + omega = Omega[2]; + alpha_new = Ampl[2] * sin(omega * time_new); + alpha_old = Ampl[2] * sin(omega * time_old); + alpha = (1E-10 + (alpha_new - alpha_old)) * (-PI_NUMBER / 180.0); - if (rank == MASTER_NODE) - cout << "New dihedral angle (alpha): " << alpha_new/DEG2RAD << " degrees." << endl; + if (rank == MASTER_NODE) cout << "New dihedral angle (alpha): " << alpha_new / DEG2RAD << " degrees." << endl; unsigned short iOrder, jOrder, kOrder; short iFFDBox; - su2double movement[3] = {0.0,0.0,0.0}; - bool *move = new bool [nFFDBox]; - unsigned short *index = new unsigned short[3]; + su2double movement[3] = {0.0, 0.0, 0.0}; + bool* move = new bool[nFFDBox]; + unsigned short* index = new unsigned short[3]; - move[0] = true; move[1] = true; move[2] = true; + move[0] = true; + move[1] = true; + move[2] = true; /*--- Change the value of the control point if move is true ---*/ @@ -3305,33 +3449,35 @@ void CSurfaceMovement::SetBoundary_Flutter3D(CGeometry *geometry, CConfig *confi for (iOrder = 0; iOrder < FFDBox[iFFDBox]->GetlOrder(); iOrder++) for (jOrder = 0; jOrder < FFDBox[iFFDBox]->GetmOrder(); jOrder++) for (kOrder = 0; kOrder < FFDBox[iFFDBox]->GetnOrder(); kOrder++) { - index[0] = iOrder; index[1] = jOrder; index[2] = kOrder; - su2double *coord = FFDBox[iFFDBox]->GetCoordControlPoints(iOrder, jOrder, kOrder); - movement[0] = 0.0; movement[1] = 0.0; movement[2] = coord[1]*tan(alpha); + index[0] = iOrder; + index[1] = jOrder; + index[2] = kOrder; + su2double* coord = FFDBox[iFFDBox]->GetCoordControlPoints(iOrder, jOrder, kOrder); + movement[0] = 0.0; + movement[1] = 0.0; + movement[2] = coord[1] * tan(alpha); FFDBox[iFFDBox]->SetControlPoints(index, movement); } /*--- Recompute cartesian coordinates using the new control points position ---*/ - for (iFFDBox = 0; iFFDBox < nFFDBox; iFFDBox++) - SetCartesianCoord(geometry, config, FFDBox[iFFDBox], iFFDBox, false); - - delete [] index; - delete [] move; + for (iFFDBox = 0; iFFDBox < nFFDBox; iFFDBox++) SetCartesianCoord(geometry, config, FFDBox[iFFDBox], iFFDBox, false); + delete[] index; + delete[] move; } -void CSurfaceMovement::SetExternal_Deformation(CGeometry *geometry, CConfig *config, unsigned short iZone, unsigned long iter) { - +void CSurfaceMovement::SetExternal_Deformation(CGeometry* geometry, CConfig* config, unsigned short iZone, + unsigned long iter) { /*--- Local variables ---*/ unsigned short iDim, nDim; unsigned long iPoint = 0, flowIter = 0; unsigned long jPoint, GlobalIndex; - su2double VarCoord[3], *Coord_Old = nullptr, *Coord_New = nullptr, Center[3] = {0.0,0.0,0.0}; - su2double Lref = config->GetLength_Ref(); - su2double NewCoord[3] = {0.0,0.0,0.0}, rotMatrix[3][3] = {{0.0,0.0,0.0}, {0.0,0.0,0.0}, {0.0,0.0,0.0}}; - su2double r[3] = {0.0,0.0,0.0}, rotCoord[3] = {0.0,0.0,0.0}; + su2double VarCoord[3], *Coord_Old = nullptr, *Coord_New = nullptr, Center[3] = {0.0, 0.0, 0.0}; + su2double Lref = config->GetLength_Ref(); + su2double NewCoord[3] = {0.0, 0.0, 0.0}, rotMatrix[3][3] = {{0.0, 0.0, 0.0}, {0.0, 0.0, 0.0}, {0.0, 0.0, 0.0}}; + su2double r[3] = {0.0, 0.0, 0.0}, rotCoord[3] = {0.0, 0.0, 0.0}; unsigned long iVertex; unsigned short iMarker; char buffer[50]; @@ -3352,14 +3498,18 @@ void CSurfaceMovement::SetExternal_Deformation(CGeometry *geometry, CConfig *con /*--- For the unsteady adjoint, we integrate backwards through physical time, so perform mesh motion in reverse. ---*/ unsigned long nFlowIter = config->GetnTime_Iter() - 1; - flowIter = nFlowIter - iter; + flowIter = nFlowIter - iter; unsigned short lastindex = DV_Filename.find_last_of("."); DV_Filename = DV_Filename.substr(0, lastindex); - if ((SU2_TYPE::Int(flowIter) >= 0) && (SU2_TYPE::Int(flowIter) < 10)) SPRINTF (buffer, "_0000%d.dat", SU2_TYPE::Int(flowIter)); - if ((SU2_TYPE::Int(flowIter) >= 10) && (SU2_TYPE::Int(flowIter) < 100)) SPRINTF (buffer, "_000%d.dat", SU2_TYPE::Int(flowIter)); - if ((SU2_TYPE::Int(flowIter) >= 100) && (SU2_TYPE::Int(flowIter) < 1000)) SPRINTF (buffer, "_00%d.dat", SU2_TYPE::Int(flowIter)); - if ((SU2_TYPE::Int(flowIter) >= 1000) && (SU2_TYPE::Int(flowIter) < 10000)) SPRINTF (buffer, "_0%d.dat", SU2_TYPE::Int(flowIter)); - if (SU2_TYPE::Int(flowIter) >= 10000) SPRINTF (buffer, "_%d.dat", SU2_TYPE::Int(flowIter)); + if ((SU2_TYPE::Int(flowIter) >= 0) && (SU2_TYPE::Int(flowIter) < 10)) + SPRINTF(buffer, "_0000%d.dat", SU2_TYPE::Int(flowIter)); + if ((SU2_TYPE::Int(flowIter) >= 10) && (SU2_TYPE::Int(flowIter) < 100)) + SPRINTF(buffer, "_000%d.dat", SU2_TYPE::Int(flowIter)); + if ((SU2_TYPE::Int(flowIter) >= 100) && (SU2_TYPE::Int(flowIter) < 1000)) + SPRINTF(buffer, "_00%d.dat", SU2_TYPE::Int(flowIter)); + if ((SU2_TYPE::Int(flowIter) >= 1000) && (SU2_TYPE::Int(flowIter) < 10000)) + SPRINTF(buffer, "_0%d.dat", SU2_TYPE::Int(flowIter)); + if (SU2_TYPE::Int(flowIter) >= 10000) SPRINTF(buffer, "_%d.dat", SU2_TYPE::Int(flowIter)); UnstExt = string(buffer); DV_Filename.append(UnstExt); } else { @@ -3367,11 +3517,15 @@ void CSurfaceMovement::SetExternal_Deformation(CGeometry *geometry, CConfig *con flowIter = iter; unsigned short lastindex = DV_Filename.find_last_of("."); DV_Filename = DV_Filename.substr(0, lastindex); - if ((SU2_TYPE::Int(flowIter) >= 0) && (SU2_TYPE::Int(flowIter) < 10)) SPRINTF (buffer, "_0000%d.dat", SU2_TYPE::Int(flowIter)); - if ((SU2_TYPE::Int(flowIter) >= 10) && (SU2_TYPE::Int(flowIter) < 100)) SPRINTF (buffer, "_000%d.dat", SU2_TYPE::Int(flowIter)); - if ((SU2_TYPE::Int(flowIter) >= 100) && (SU2_TYPE::Int(flowIter) < 1000)) SPRINTF (buffer, "_00%d.dat", SU2_TYPE::Int(flowIter)); - if ((SU2_TYPE::Int(flowIter) >= 1000) && (SU2_TYPE::Int(flowIter) < 10000)) SPRINTF (buffer, "_0%d.dat", SU2_TYPE::Int(flowIter)); - if (SU2_TYPE::Int(flowIter) >= 10000) SPRINTF (buffer, "_%d.dat", SU2_TYPE::Int(flowIter)); + if ((SU2_TYPE::Int(flowIter) >= 0) && (SU2_TYPE::Int(flowIter) < 10)) + SPRINTF(buffer, "_0000%d.dat", SU2_TYPE::Int(flowIter)); + if ((SU2_TYPE::Int(flowIter) >= 10) && (SU2_TYPE::Int(flowIter) < 100)) + SPRINTF(buffer, "_000%d.dat", SU2_TYPE::Int(flowIter)); + if ((SU2_TYPE::Int(flowIter) >= 100) && (SU2_TYPE::Int(flowIter) < 1000)) + SPRINTF(buffer, "_00%d.dat", SU2_TYPE::Int(flowIter)); + if ((SU2_TYPE::Int(flowIter) >= 1000) && (SU2_TYPE::Int(flowIter) < 10000)) + SPRINTF(buffer, "_0%d.dat", SU2_TYPE::Int(flowIter)); + if (SU2_TYPE::Int(flowIter) >= 10000) SPRINTF(buffer, "_%d.dat", SU2_TYPE::Int(flowIter)); UnstExt = string(buffer); DV_Filename.append(UnstExt); } @@ -3418,7 +3572,6 @@ void CSurfaceMovement::SetExternal_Deformation(CGeometry *geometry, CConfig *con /*--- If rotating as well, prepare the rotation matrix ---*/ if (config->GetKind_GridMovement() == EXTERNAL_ROTATION) { - /*--- Variables needed only for rotation ---*/ su2double Omega[3], dt; @@ -3432,17 +3585,18 @@ void CSurfaceMovement::SetExternal_Deformation(CGeometry *geometry, CConfig *con /*--- Angular velocity vector from config ---*/ - dt = static_cast(iter)*config->GetDelta_UnstTimeND(); - Omega[0] = config->GetRotation_Rate(0); - Omega[1] = config->GetRotation_Rate(1); - Omega[2] = config->GetRotation_Rate(2); + dt = static_cast(iter) * config->GetDelta_UnstTimeND(); + Omega[0] = config->GetRotation_Rate(0); + Omega[1] = config->GetRotation_Rate(1); + Omega[2] = config->GetRotation_Rate(2); /*--- For the unsteady adjoint, use reverse time ---*/ if (adjoint) { /*--- Set the first adjoint mesh position to the final direct one ---*/ - if (iter == 0) dt = ((su2double)config->GetnTime_Iter()-1) * dt; + if (iter == 0) dt = ((su2double)config->GetnTime_Iter() - 1) * dt; /*--- Reverse the rotation direction for the adjoint ---*/ - else dt = -1.0*dt; + else + dt = -1.0 * dt; } else { /*--- No rotation at all for the first direct solution ---*/ if (iter == 0) dt = 0; @@ -3450,30 +3604,33 @@ void CSurfaceMovement::SetExternal_Deformation(CGeometry *geometry, CConfig *con /*--- Compute delta change in the angle about the x, y, & z axes. ---*/ - dtheta = Omega[0]*dt; - dphi = Omega[1]*dt; - dpsi = Omega[2]*dt; + dtheta = Omega[0] * dt; + dphi = Omega[1] * dt; + dpsi = Omega[2] * dt; /*--- Store angles separately for clarity. Compute sines/cosines. ---*/ - cosTheta = cos(dtheta); cosPhi = cos(dphi); cosPsi = cos(dpsi); - sinTheta = sin(dtheta); sinPhi = sin(dphi); sinPsi = sin(dpsi); + cosTheta = cos(dtheta); + cosPhi = cos(dphi); + cosPsi = cos(dpsi); + sinTheta = sin(dtheta); + sinPhi = sin(dphi); + sinPsi = sin(dpsi); /*--- Compute the rotation matrix. Note that the implicit ordering is rotation about the x-axis, y-axis, then z-axis. ---*/ - rotMatrix[0][0] = cosPhi*cosPsi; - rotMatrix[1][0] = cosPhi*sinPsi; + rotMatrix[0][0] = cosPhi * cosPsi; + rotMatrix[1][0] = cosPhi * sinPsi; rotMatrix[2][0] = -sinPhi; - rotMatrix[0][1] = sinTheta*sinPhi*cosPsi - cosTheta*sinPsi; - rotMatrix[1][1] = sinTheta*sinPhi*sinPsi + cosTheta*cosPsi; - rotMatrix[2][1] = sinTheta*cosPhi; - - rotMatrix[0][2] = cosTheta*sinPhi*cosPsi + sinTheta*sinPsi; - rotMatrix[1][2] = cosTheta*sinPhi*sinPsi - sinTheta*cosPsi; - rotMatrix[2][2] = cosTheta*cosPhi; + rotMatrix[0][1] = sinTheta * sinPhi * cosPsi - cosTheta * sinPsi; + rotMatrix[1][1] = sinTheta * sinPhi * sinPsi + cosTheta * cosPsi; + rotMatrix[2][1] = sinTheta * cosPhi; + rotMatrix[0][2] = cosTheta * sinPhi * cosPsi + sinTheta * sinPsi; + rotMatrix[1][2] = cosTheta * sinPhi * sinPsi - sinTheta * cosPsi; + rotMatrix[2][2] = cosTheta * cosPhi; } /*--- Loop through to find only moving surface markers ---*/ @@ -3481,7 +3638,6 @@ void CSurfaceMovement::SetExternal_Deformation(CGeometry *geometry, CConfig *con for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { if ((config->GetMarker_All_DV(iMarker) == YES && config->GetKind_SU2() == SU2_COMPONENT::SU2_DEF) || (config->GetMarker_All_Moving(iMarker) == YES && config->GetKind_SU2() == SU2_COMPONENT::SU2_CFD)) { - /*--- Loop over all surface points for this marker ---*/ for (iVertex = 0; iVertex < geometry->nVertex[iMarker]; iVertex++) { @@ -3497,115 +3653,115 @@ void CSurfaceMovement::SetExternal_Deformation(CGeometry *geometry, CConfig *con Coord_Old have already been rotated using SetRigid_Rotation(). ---*/ if (config->GetKind_GridMovement() == EXTERNAL_ROTATION) { - /*--- Calculate non-dim. position from rotation center ---*/ - for (iDim = 0; iDim < nDim; iDim++) - r[iDim] = (Coord_New[iDim]-Center[iDim])/Lref; + for (iDim = 0; iDim < nDim; iDim++) r[iDim] = (Coord_New[iDim] - Center[iDim]) / Lref; if (nDim == 2) r[nDim] = 0.0; /*--- Compute transformed point coordinates ---*/ - rotCoord[0] = rotMatrix[0][0]*r[0] - + rotMatrix[0][1]*r[1] - + rotMatrix[0][2]*r[2] + Center[0]; + rotCoord[0] = rotMatrix[0][0] * r[0] + rotMatrix[0][1] * r[1] + rotMatrix[0][2] * r[2] + Center[0]; - rotCoord[1] = rotMatrix[1][0]*r[0] - + rotMatrix[1][1]*r[1] - + rotMatrix[1][2]*r[2] + Center[1]; + rotCoord[1] = rotMatrix[1][0] * r[0] + rotMatrix[1][1] * r[1] + rotMatrix[1][2] * r[2] + Center[1]; - rotCoord[2] = rotMatrix[2][0]*r[0] - + rotMatrix[2][1]*r[1] - + rotMatrix[2][2]*r[2] + Center[2]; + rotCoord[2] = rotMatrix[2][0] * r[0] + rotMatrix[2][1] * r[1] + rotMatrix[2][2] * r[2] + Center[2]; /*--- Copy rotated coords back to original array for consistency ---*/ - for (iDim = 0; iDim < nDim; iDim++) - Coord_New[iDim] = rotCoord[iDim]; + for (iDim = 0; iDim < nDim; iDim++) Coord_New[iDim] = rotCoord[iDim]; } /*--- Calculate delta change in the x, y, & z directions ---*/ - for (iDim = 0; iDim < nDim; iDim++) - VarCoord[iDim] = (Coord_New[iDim]-Coord_Old[iDim])/Lref; + for (iDim = 0; iDim < nDim; iDim++) VarCoord[iDim] = (Coord_New[iDim] - Coord_Old[iDim]) / Lref; if (nDim == 2) VarCoord[nDim] = 0.0; /*--- Set position changes to be applied by the spring analogy ---*/ geometry->vertex[iMarker][iVertex]->SetVarCoord(VarCoord); - } } } } -void CSurfaceMovement::SetNACA_4Digits(CGeometry *boundary, CConfig *config) { +void CSurfaceMovement::SetNACA_4Digits(CGeometry* boundary, CConfig* config) { unsigned long iVertex; unsigned short iMarker; su2double VarCoord[3], *Coord, *Normal, Ycurv, Yesp; - if (config->GetnDV() != 1) { cout << "This kind of design variable is not prepared for multiple deformations."; cin.get(); } + if (config->GetnDV() != 1) { + cout << "This kind of design variable is not prepared for multiple deformations."; + cin.get(); + } - su2double Ya = config->GetParamDV(0,0) / 100.0; /*--- Maximum camber as a fraction of the chord - (100 m is the first of the four digits) ---*/ - su2double Xa = config->GetParamDV(0,1) / 10.0; /*--- Location of maximum camber as a fraction of - the chord (10 p is the second digit in the NACA xxxx description) ---*/ - su2double t = config->GetParamDV(0,2) / 100.0; /*--- Maximum thickness as a fraction of the - chord (so 100 t gives the last two digits in - the NACA 4-digit denomination) ---*/ + su2double Ya = config->GetParamDV(0, 0) / 100.0; /*--- Maximum camber as a fraction of the chord + (100 m is the first of the four digits) ---*/ + su2double Xa = config->GetParamDV(0, 1) / 10.0; /*--- Location of maximum camber as a fraction of + the chord (10 p is the second digit in the NACA xxxx description) ---*/ + su2double t = config->GetParamDV(0, 2) / 100.0; /*--- Maximum thickness as a fraction of the + chord (so 100 t gives the last two digits in + the NACA 4-digit denomination) ---*/ for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) for (iVertex = 0; iVertex < boundary->nVertex[iMarker]; iVertex++) { - VarCoord[0] = 0.0; VarCoord[1] = 0.0; VarCoord[2] = 0.0; + VarCoord[0] = 0.0; + VarCoord[1] = 0.0; + VarCoord[2] = 0.0; if (config->GetMarker_All_DV(iMarker) == YES) { Coord = boundary->vertex[iMarker][iVertex]->GetCoord(); Normal = boundary->vertex[iMarker][iVertex]->GetNormal(); - if (Coord[0] < Xa) Ycurv = (2.0*Xa*Coord[0]-pow(Coord[0],2.0))*(Ya/pow(Xa,2.0)); - else Ycurv = ((1.0-2.0*Xa)+2.0*Xa*Coord[0]-pow(Coord[0],2.0))*(Ya/pow((1.0-Xa), 2.0)); - - Yesp = t*(1.4845*sqrt(Coord[0])-0.6300*Coord[0]-1.7580*pow(Coord[0],2.0)+ - 1.4215*pow(Coord[0],3.0)-0.518*pow(Coord[0],4.0)); + if (Coord[0] < Xa) + Ycurv = (2.0 * Xa * Coord[0] - pow(Coord[0], 2.0)) * (Ya / pow(Xa, 2.0)); + else + Ycurv = ((1.0 - 2.0 * Xa) + 2.0 * Xa * Coord[0] - pow(Coord[0], 2.0)) * (Ya / pow((1.0 - Xa), 2.0)); - if (Normal[1] > 0) VarCoord[1] = (Ycurv + Yesp) - Coord[1]; - if (Normal[1] < 0) VarCoord[1] = (Ycurv - Yesp) - Coord[1]; + Yesp = t * (1.4845 * sqrt(Coord[0]) - 0.6300 * Coord[0] - 1.7580 * pow(Coord[0], 2.0) + + 1.4215 * pow(Coord[0], 3.0) - 0.518 * pow(Coord[0], 4.0)); + if (Normal[1] > 0) VarCoord[1] = (Ycurv + Yesp) - Coord[1]; + if (Normal[1] < 0) VarCoord[1] = (Ycurv - Yesp) - Coord[1]; } boundary->vertex[iMarker][iVertex]->SetVarCoord(VarCoord); } } -void CSurfaceMovement::SetParabolic(CGeometry *boundary, CConfig *config) { +void CSurfaceMovement::SetParabolic(CGeometry* boundary, CConfig* config) { unsigned long iVertex; unsigned short iMarker; su2double VarCoord[3], *Coord, *Normal; - if (config->GetnDV() != 1) { cout << "This kind of design variable is not prepared for multiple deformations."; cin.get(); } + if (config->GetnDV() != 1) { + cout << "This kind of design variable is not prepared for multiple deformations."; + cin.get(); + } - su2double c = config->GetParamDV(0,0); /*--- Center of the parabola ---*/ - su2double t = config->GetParamDV(0,1) / 100.0; /*--- Thickness of the parabola ---*/ + su2double c = config->GetParamDV(0, 0); /*--- Center of the parabola ---*/ + su2double t = config->GetParamDV(0, 1) / 100.0; /*--- Thickness of the parabola ---*/ for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) for (iVertex = 0; iVertex < boundary->nVertex[iMarker]; iVertex++) { - VarCoord[0] = 0.0; VarCoord[1] = 0.0; VarCoord[2] = 0.0; + VarCoord[0] = 0.0; + VarCoord[1] = 0.0; + VarCoord[2] = 0.0; if (config->GetMarker_All_DV(iMarker) == YES) { Coord = boundary->vertex[iMarker][iVertex]->GetCoord(); Normal = boundary->vertex[iMarker][iVertex]->GetNormal(); if (Normal[1] > 0) { - VarCoord[1] = t*(Coord[0]*Coord[0]-Coord[0])/(2.0*(c*c-c)) - Coord[1]; + VarCoord[1] = t * (Coord[0] * Coord[0] - Coord[0]) / (2.0 * (c * c - c)) - Coord[1]; } if (Normal[1] < 0) { - VarCoord[1] = t*(Coord[0]-Coord[0]*Coord[0])/(2.0*(c*c-c)) - Coord[1]; + VarCoord[1] = t * (Coord[0] - Coord[0] * Coord[0]) / (2.0 * (c * c - c)) - Coord[1]; } } boundary->vertex[iMarker][iVertex]->SetVarCoord(VarCoord); } } -void CSurfaceMovement::SetAirfoil(CGeometry *boundary, CConfig *config) { +void CSurfaceMovement::SetAirfoil(CGeometry* boundary, CConfig* config) { unsigned long iVertex, n_Airfoil = 0; unsigned short iMarker, nUpper, nLower, iUpper, iLower, iVar, iDim; su2double *VarCoord, *Coord, NewYCoord, NewXCoord, *Coord_i, *Coord_ip1, yp1, ypn, - Airfoil_Coord[2]= {0.0,0.0}, factor, coeff = 10000, Upper, Lower, Arch = 0.0, TotalArch = 0.0, - x_i, x_ip1, y_i, y_ip1; + Airfoil_Coord[2] = {0.0, 0.0}, factor, coeff = 10000, Upper, Lower, Arch = 0.0, TotalArch = 0.0, x_i, x_ip1, y_i, + y_ip1; passivedouble AirfoilScale; vector Svalue, Xcoord, Ycoord, Xcoord2, Ycoord2, Xcoord_Aux, Ycoord_Aux; bool AddBegin = true, AddEnd = true; @@ -3617,8 +3773,7 @@ void CSurfaceMovement::SetAirfoil(CGeometry *boundary, CConfig *config) { unsigned short nDim = boundary->GetnDim(); VarCoord = new su2double[nDim]; - for (iDim = 0; iDim < nDim; iDim++) - VarCoord[iDim] = 0.0; + for (iDim = 0; iDim < nDim; iDim++) VarCoord[iDim] = 0.0; /*--- Get the SU2 module. SU2_CFD will use this routine for dynamically deforming meshes (MARKER_MOVING), while SU2_DEF will use it for deforming @@ -3637,35 +3792,44 @@ void CSurfaceMovement::SetAirfoil(CGeometry *boundary, CConfig *config) { cout << "Enter the name of file with the airfoil information: "; ierr = scanf("%255s", AirfoilFile); - if (ierr == 0) { SU2_MPI::Error("No input read!!", CURRENT_FUNCTION); } + if (ierr == 0) { + SU2_MPI::Error("No input read!!", CURRENT_FUNCTION); + } airfoil_file.open(AirfoilFile, ios::in); if (airfoil_file.fail()) { SU2_MPI::Error(string("There is no airfoil file ") + string(AirfoilFile), CURRENT_FUNCTION); } cout << "Enter the format of the airfoil (Selig or Lednicer): "; ierr = scanf("%14s", AirfoilFormat); - if (ierr == 0) { SU2_MPI::Error("No input read!!", CURRENT_FUNCTION); } + if (ierr == 0) { + SU2_MPI::Error("No input read!!", CURRENT_FUNCTION); + } cout << "Thickness scaling (1.0 means no scaling)?: "; ierr = scanf("%lf", &AirfoilScale); - if (ierr == 0) { SU2_MPI::Error("No input read!!", CURRENT_FUNCTION); } + if (ierr == 0) { + SU2_MPI::Error("No input read!!", CURRENT_FUNCTION); + } cout << "Close the airfoil (Yes or No)?: "; ierr = scanf("%14s", AirfoilClose); - if (ierr == 0) { SU2_MPI::Error("No input read!!", CURRENT_FUNCTION); } + if (ierr == 0) { + SU2_MPI::Error("No input read!!", CURRENT_FUNCTION); + } cout << "Surface mesh orientation (clockwise, or anticlockwise): "; ierr = scanf("%14s", MeshOrientation); - if (ierr == 0) { SU2_MPI::Error("No input read!!", CURRENT_FUNCTION); } + if (ierr == 0) { + SU2_MPI::Error("No input read!!", CURRENT_FUNCTION); + } /*--- The first line is the header ---*/ - getline (airfoil_file, text_line); + getline(airfoil_file, text_line); cout << "File info: " << text_line << endl; - if (strcmp (AirfoilFormat,"Selig") == 0) { - - while (getline (airfoil_file, text_line)) { + if (strcmp(AirfoilFormat, "Selig") == 0) { + while (getline(airfoil_file, text_line)) { istringstream point_line(text_line); /*--- Read the x & y coordinates from this line of the file (anticlockwise) ---*/ @@ -3674,19 +3838,18 @@ void CSurfaceMovement::SetAirfoil(CGeometry *boundary, CConfig *config) { /*--- Close the arifoil ---*/ - if (strcmp (AirfoilClose,"Yes") == 0) - factor = -atan(coeff*(Airfoil_Coord[0]-1.0))*2.0/PI_NUMBER; - else factor = 1.0; + if (strcmp(AirfoilClose, "Yes") == 0) + factor = -atan(coeff * (Airfoil_Coord[0] - 1.0)) * 2.0 / PI_NUMBER; + else + factor = 1.0; /*--- Store the coordinates in vectors ---*/ Xcoord.push_back(Airfoil_Coord[0]); - Ycoord.push_back(Airfoil_Coord[1]*factor*AirfoilScale); + Ycoord.push_back(Airfoil_Coord[1] * factor * AirfoilScale); } - } - if (strcmp (AirfoilFormat,"Lednicer") == 0) { - + if (strcmp(AirfoilFormat, "Lednicer") == 0) { /*--- The second line is the number of points ---*/ getline(airfoil_file, text_line); @@ -3696,82 +3859,96 @@ void CSurfaceMovement::SetAirfoil(CGeometry *boundary, CConfig *config) { nUpper = SU2_TYPE::Int(Upper); nLower = SU2_TYPE::Int(Lower); - Xcoord.resize(nUpper+nLower-1); - Ycoord.resize(nUpper+nLower-1); + Xcoord.resize(nUpper + nLower - 1); + Ycoord.resize(nUpper + nLower - 1); /*--- White line ---*/ - getline (airfoil_file, text_line); + getline(airfoil_file, text_line); for (iUpper = 0; iUpper < nUpper; iUpper++) { - getline (airfoil_file, text_line); + getline(airfoil_file, text_line); istringstream point_line(text_line); point_line >> Airfoil_Coord[0] >> Airfoil_Coord[1]; - Xcoord[nUpper-iUpper-1] = Airfoil_Coord[0]; + Xcoord[nUpper - iUpper - 1] = Airfoil_Coord[0]; - if (strcmp (AirfoilClose,"Yes") == 0) - factor = -atan(coeff*(Airfoil_Coord[0]-1.0))*2.0/PI_NUMBER; - else factor = 1.0; + if (strcmp(AirfoilClose, "Yes") == 0) + factor = -atan(coeff * (Airfoil_Coord[0] - 1.0)) * 2.0 / PI_NUMBER; + else + factor = 1.0; - Ycoord[nUpper-iUpper-1] = Airfoil_Coord[1]*AirfoilScale*factor; + Ycoord[nUpper - iUpper - 1] = Airfoil_Coord[1] * AirfoilScale * factor; } - getline (airfoil_file, text_line); + getline(airfoil_file, text_line); for (iLower = 0; iLower < nLower; iLower++) { - getline (airfoil_file, text_line); + getline(airfoil_file, text_line); istringstream point_line(text_line); point_line >> Airfoil_Coord[0] >> Airfoil_Coord[1]; - if (strcmp (AirfoilClose,"Yes") == 0) - factor = -atan(coeff*(Airfoil_Coord[0]-1.0))*2.0/PI_NUMBER; - else factor = 1.0; + if (strcmp(AirfoilClose, "Yes") == 0) + factor = -atan(coeff * (Airfoil_Coord[0] - 1.0)) * 2.0 / PI_NUMBER; + else + factor = 1.0; - Xcoord[nUpper+iLower-1] = Airfoil_Coord[0]; - Ycoord[nUpper+iLower-1] = Airfoil_Coord[1]*AirfoilScale*factor; + Xcoord[nUpper + iLower - 1] = Airfoil_Coord[0]; + Ycoord[nUpper + iLower - 1] = Airfoil_Coord[1] * AirfoilScale * factor; } - } /*--- Check the coordinate (1,0) at the beginning and end of the file ---*/ if (Xcoord[0] == 1.0) AddBegin = false; - if (Xcoord[Xcoord.size()-1] == 1.0) AddEnd = false; + if (Xcoord[Xcoord.size() - 1] == 1.0) AddEnd = false; - if (AddBegin) { Xcoord.insert(Xcoord.begin(), 1.0); Ycoord.insert(Ycoord.begin(), 0.0);} - if (AddEnd) { Xcoord.push_back(1.0); Ycoord.push_back(0.0);} + if (AddBegin) { + Xcoord.insert(Xcoord.begin(), 1.0); + Ycoord.insert(Ycoord.begin(), 0.0); + } + if (AddEnd) { + Xcoord.push_back(1.0); + Ycoord.push_back(0.0); + } /*--- Change the orientation (depend on the input file, and the mesh file) ---*/ - if (strcmp (MeshOrientation,"clockwise") == 0) { + if (strcmp(MeshOrientation, "clockwise") == 0) { for (iVar = 0; iVar < Xcoord.size(); iVar++) { Xcoord_Aux.push_back(Xcoord[iVar]); Ycoord_Aux.push_back(Ycoord[iVar]); } for (iVar = 0; iVar < Xcoord.size(); iVar++) { - Xcoord[iVar] = Xcoord_Aux[Xcoord.size()-iVar-1]; - Ycoord[iVar] = Ycoord_Aux[Xcoord.size()-iVar-1]; + Xcoord[iVar] = Xcoord_Aux[Xcoord.size() - iVar - 1]; + Ycoord[iVar] = Ycoord_Aux[Xcoord.size() - iVar - 1]; } } /*--- Compute the total arch length ---*/ - Arch = 0.0; Svalue.push_back(Arch); + Arch = 0.0; + Svalue.push_back(Arch); - for (iVar = 0; iVar < Xcoord.size()-1; iVar++) { - x_i = Xcoord[iVar]; x_ip1 = Xcoord[iVar+1]; - y_i = Ycoord[iVar]; y_ip1 = Ycoord[iVar+1]; - Arch += sqrt((x_ip1-x_i)*(x_ip1-x_i)+(y_ip1-y_i)*(y_ip1-y_i)); + for (iVar = 0; iVar < Xcoord.size() - 1; iVar++) { + x_i = Xcoord[iVar]; + x_ip1 = Xcoord[iVar + 1]; + y_i = Ycoord[iVar]; + y_ip1 = Ycoord[iVar + 1]; + Arch += sqrt((x_ip1 - x_i) * (x_ip1 - x_i) + (y_ip1 - y_i) * (y_ip1 - y_i)); Svalue.push_back(Arch); } - x_i = Xcoord[Xcoord.size()-1]; x_ip1 = Xcoord[0]; - y_i = Ycoord[Xcoord.size()-1]; y_ip1 = Ycoord[0]; - Arch += sqrt((x_ip1-x_i)*(x_ip1-x_i)+(y_ip1-y_i)*(y_ip1-y_i)); + x_i = Xcoord[Xcoord.size() - 1]; + x_ip1 = Xcoord[0]; + y_i = Ycoord[Xcoord.size() - 1]; + y_ip1 = Ycoord[0]; + Arch += sqrt((x_ip1 - x_i) * (x_ip1 - x_i) + (y_ip1 - y_i) * (y_ip1 - y_i)); /*--- Non dimensionalization ---*/ - for (iVar = 0; iVar < Svalue.size(); iVar++) { Svalue[iVar] /= Arch; } + for (iVar = 0; iVar < Svalue.size(); iVar++) { + Svalue[iVar] /= Arch; + } /*--- Close the restart file ---*/ @@ -3780,14 +3957,14 @@ void CSurfaceMovement::SetAirfoil(CGeometry *boundary, CConfig *config) { /*--- Create a spline for X and Y coordiantes using the arch length ---*/ n_Airfoil = Svalue.size(); - yp1 = (Xcoord[1]-Xcoord[0])/(Svalue[1]-Svalue[0]); - ypn = (Xcoord[n_Airfoil-1]-Xcoord[n_Airfoil-2])/(Svalue[n_Airfoil-1]-Svalue[n_Airfoil-2]); + yp1 = (Xcoord[1] - Xcoord[0]) / (Svalue[1] - Svalue[0]); + ypn = (Xcoord[n_Airfoil - 1] - Xcoord[n_Airfoil - 2]) / (Svalue[n_Airfoil - 1] - Svalue[n_Airfoil - 2]); CCubicSpline splineX(Svalue, Xcoord, CCubicSpline::FIRST, yp1, CCubicSpline::FIRST, ypn); n_Airfoil = Svalue.size(); - yp1 = (Ycoord[1]-Ycoord[0])/(Svalue[1]-Svalue[0]); - ypn = (Ycoord[n_Airfoil-1]-Ycoord[n_Airfoil-2])/(Svalue[n_Airfoil-1]-Svalue[n_Airfoil-2]); + yp1 = (Ycoord[1] - Ycoord[0]) / (Svalue[1] - Svalue[0]); + ypn = (Ycoord[n_Airfoil - 1] - Ycoord[n_Airfoil - 2]) / (Svalue[n_Airfoil - 1] - Svalue[n_Airfoil - 2]); CCubicSpline splineY(Svalue, Ycoord, CCubicSpline::FIRST, yp1, CCubicSpline::FIRST, ypn); @@ -3795,39 +3972,47 @@ void CSurfaceMovement::SetAirfoil(CGeometry *boundary, CConfig *config) { for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { if (((config->GetMarker_All_Moving(iMarker) == YES) && (Kind_SU2 == SU2_COMPONENT::SU2_CFD)) || ((config->GetMarker_All_DV(iMarker) == YES) && (Kind_SU2 == SU2_COMPONENT::SU2_DEF))) { - for (iVertex = 0; iVertex < boundary->nVertex[iMarker]-1; iVertex++) { + for (iVertex = 0; iVertex < boundary->nVertex[iMarker] - 1; iVertex++) { Coord_i = boundary->vertex[iMarker][iVertex]->GetCoord(); - Coord_ip1 = boundary->vertex[iMarker][iVertex+1]->GetCoord(); + Coord_ip1 = boundary->vertex[iMarker][iVertex + 1]->GetCoord(); - x_i = Coord_i[0]; x_ip1 = Coord_ip1[0]; - y_i = Coord_i[1]; y_ip1 = Coord_ip1[1]; + x_i = Coord_i[0]; + x_ip1 = Coord_ip1[0]; + y_i = Coord_i[1]; + y_ip1 = Coord_ip1[1]; - TotalArch += sqrt((x_ip1-x_i)*(x_ip1-x_i)+(y_ip1-y_i)*(y_ip1-y_i)); + TotalArch += sqrt((x_ip1 - x_i) * (x_ip1 - x_i) + (y_ip1 - y_i) * (y_ip1 - y_i)); } - Coord_i = boundary->vertex[iMarker][boundary->nVertex[iMarker]-1]->GetCoord(); + Coord_i = boundary->vertex[iMarker][boundary->nVertex[iMarker] - 1]->GetCoord(); Coord_ip1 = boundary->vertex[iMarker][0]->GetCoord(); - x_i = Coord_i[0]; x_ip1 = Coord_ip1[0]; - y_i = Coord_i[1]; y_ip1 = Coord_ip1[1]; - TotalArch += sqrt((x_ip1-x_i)*(x_ip1-x_i)+(y_ip1-y_i)*(y_ip1-y_i)); + x_i = Coord_i[0]; + x_ip1 = Coord_ip1[0]; + y_i = Coord_i[1]; + y_ip1 = Coord_ip1[1]; + TotalArch += sqrt((x_ip1 - x_i) * (x_ip1 - x_i) + (y_ip1 - y_i) * (y_ip1 - y_i)); } } - for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { Arch = 0.0; for (iVertex = 0; iVertex < boundary->nVertex[iMarker]; iVertex++) { - VarCoord[0] = 0.0; VarCoord[1] = 0.0; VarCoord[2] = 0.0; + VarCoord[0] = 0.0; + VarCoord[1] = 0.0; + VarCoord[2] = 0.0; if (((config->GetMarker_All_Moving(iMarker) == YES) && (Kind_SU2 == SU2_COMPONENT::SU2_CFD)) || ((config->GetMarker_All_DV(iMarker) == YES) && (Kind_SU2 == SU2_COMPONENT::SU2_DEF))) { Coord = boundary->vertex[iMarker][iVertex]->GetCoord(); - if (iVertex == 0) Arch = 0.0; + if (iVertex == 0) + Arch = 0.0; else { - Coord_i = boundary->vertex[iMarker][iVertex-1]->GetCoord(); + Coord_i = boundary->vertex[iMarker][iVertex - 1]->GetCoord(); Coord_ip1 = boundary->vertex[iMarker][iVertex]->GetCoord(); - x_i = Coord_i[0]; x_ip1 = Coord_ip1[0]; - y_i = Coord_i[1]; y_ip1 = Coord_ip1[1]; - Arch += sqrt((x_ip1-x_i)*(x_ip1-x_i)+(y_ip1-y_i)*(y_ip1-y_i))/TotalArch; + x_i = Coord_i[0]; + x_ip1 = Coord_ip1[0]; + y_i = Coord_i[1]; + y_ip1 = Coord_ip1[1]; + Arch += sqrt((x_ip1 - x_i) * (x_ip1 - x_i) + (y_ip1 - y_i) * (y_ip1 - y_i)) / TotalArch; } NewXCoord = splineX(Arch); @@ -3840,24 +4025,21 @@ void CSurfaceMovement::SetAirfoil(CGeometry *boundary, CConfig *config) { } boundary->vertex[iMarker][iVertex]->SetVarCoord(VarCoord); - } } - delete [] VarCoord; - + delete[] VarCoord; } -void CSurfaceMovement::ReadFFDInfo(CGeometry *geometry, CConfig *config, CFreeFormDefBox **FFDBox, string val_mesh_filename) { - +void CSurfaceMovement::ReadFFDInfo(CGeometry* geometry, CConfig* config, CFreeFormDefBox** FFDBox, + string val_mesh_filename) { string text_line, iTag; ifstream mesh_file; - su2double CPcoord[3], coord[] = {0,0,0}; - unsigned short degree[3], iFFDBox, iCornerPoints, iControlPoints, iMarker, iDegree, jDegree, kDegree, - iChar, LevelFFDBox, nParentFFDBox, iParentFFDBox, nChildFFDBox, iChildFFDBox, nMarker, *nCornerPoints, - *nControlPoints; - unsigned long iSurfacePoints, iPoint, jPoint, iVertex, nVertex, nPoint, iElem = 0, - nElem, my_nSurfPoints, nSurfPoints, *nSurfacePoints; + su2double CPcoord[3], coord[] = {0, 0, 0}; + unsigned short degree[3], iFFDBox, iCornerPoints, iControlPoints, iMarker, iDegree, jDegree, kDegree, iChar, + LevelFFDBox, nParentFFDBox, iParentFFDBox, nChildFFDBox, iChildFFDBox, nMarker, *nCornerPoints, *nControlPoints; + unsigned long iSurfacePoints, iPoint, jPoint, iVertex, nVertex, nPoint, iElem = 0, nElem, my_nSurfPoints, nSurfPoints, + *nSurfacePoints; su2double XCoord, YCoord; bool polar = (config->GetFFD_CoordSystem() == POLAR); @@ -3870,13 +4052,13 @@ void CSurfaceMovement::ReadFFDInfo(CGeometry *geometry, CConfig *config, CFreeFo SU2_MPI::Error("There is no geometry file (ReadFFDInfo)!!", CURRENT_FUNCTION); } - while (getline (mesh_file, text_line)) { - + while (getline(mesh_file, text_line)) { /*--- Read the inner elements ---*/ - string::size_type position = text_line.find ("NELEM=",0); + string::size_type position = text_line.find("NELEM=", 0); if (position != string::npos) { - text_line.erase (0,6); nElem = atoi(text_line.c_str()); + text_line.erase(0, 6); + nElem = atoi(text_line.c_str()); for (iElem = 0; iElem < nElem; iElem++) { getline(mesh_file, text_line); } @@ -3884,9 +4066,10 @@ void CSurfaceMovement::ReadFFDInfo(CGeometry *geometry, CConfig *config, CFreeFo /*--- Read the inner points ---*/ - position = text_line.find ("NPOIN=",0); + position = text_line.find("NPOIN=", 0); if (position != string::npos) { - text_line.erase (0,6); nPoint = atoi(text_line.c_str()); + text_line.erase(0, 6); + nPoint = atoi(text_line.c_str()); for (iPoint = 0; iPoint < nPoint; iPoint++) { getline(mesh_file, text_line); } @@ -3894,13 +4077,15 @@ void CSurfaceMovement::ReadFFDInfo(CGeometry *geometry, CConfig *config, CFreeFo /*--- Read the boundaries ---*/ - position = text_line.find ("NMARK=",0); + position = text_line.find("NMARK=", 0); if (position != string::npos) { - text_line.erase (0,6); nMarker = atoi(text_line.c_str()); + text_line.erase(0, 6); + nMarker = atoi(text_line.c_str()); for (iMarker = 0; iMarker < nMarker; iMarker++) { getline(mesh_file, text_line); getline(mesh_file, text_line); - text_line.erase (0,13); nVertex = atoi(text_line.c_str()); + text_line.erase(0, 13); + nVertex = atoi(text_line.c_str()); for (iVertex = 0; iVertex < nVertex; iVertex++) { getline(mesh_file, text_line); } @@ -3909,9 +4094,9 @@ void CSurfaceMovement::ReadFFDInfo(CGeometry *geometry, CConfig *config, CFreeFo /*--- Read the FFDBox information ---*/ - position = text_line.find ("FFD_NBOX=",0); + position = text_line.find("FFD_NBOX=", 0); if (position != string::npos) { - text_line.erase (0,9); + text_line.erase(0, 9); nFFDBox = atoi(text_line.c_str()); if (rank == MASTER_NODE) cout << nFFDBox << " Free Form Deformation boxes." << endl; @@ -3920,126 +4105,138 @@ void CSurfaceMovement::ReadFFDInfo(CGeometry *geometry, CConfig *config, CFreeFo nControlPoints = new unsigned short[nFFDBox]; nSurfacePoints = new unsigned long[nFFDBox]; - getline (mesh_file, text_line); - text_line.erase (0,11); + getline(mesh_file, text_line); + text_line.erase(0, 11); nLevel = atoi(text_line.c_str()); if (rank == MASTER_NODE) cout << nLevel << " Free Form Deformation nested levels." << endl; - for (iFFDBox = 0 ; iFFDBox < nFFDBox; iFFDBox++) { - + for (iFFDBox = 0; iFFDBox < nFFDBox; iFFDBox++) { /*--- Read the name of the FFD box ---*/ - getline (mesh_file, text_line); - text_line.erase (0,8); + getline(mesh_file, text_line); + text_line.erase(0, 8); /*--- Remove extra data from the FFDBox name ---*/ string::size_type position; for (iChar = 0; iChar < 20; iChar++) { - position = text_line.find( " ", 0 ); - if (position != string::npos) text_line.erase (position,1); - position = text_line.find( "\r", 0 ); - if (position != string::npos) text_line.erase (position,1); - position = text_line.find( "\n", 0 ); - if (position != string::npos) text_line.erase (position,1); + position = text_line.find(" ", 0); + if (position != string::npos) text_line.erase(position, 1); + position = text_line.find("\r", 0); + if (position != string::npos) text_line.erase(position, 1); + position = text_line.find("\n", 0); + if (position != string::npos) text_line.erase(position, 1); } string TagFFDBox = text_line.c_str(); - if (rank == MASTER_NODE) cout << "FFD box tag: " << TagFFDBox <<". "; + if (rank == MASTER_NODE) cout << "FFD box tag: " << TagFFDBox << ". "; /*--- Read the level of the FFD box ---*/ - getline (mesh_file, text_line); - text_line.erase (0,10); + getline(mesh_file, text_line); + text_line.erase(0, 10); LevelFFDBox = atoi(text_line.c_str()); - if (rank == MASTER_NODE) cout << "FFD box level: " << LevelFFDBox <<". "; + if (rank == MASTER_NODE) cout << "FFD box level: " << LevelFFDBox << ". "; /*--- Read the degree of the FFD box ---*/ - if (nDim == 2) { if (polar) { - getline (mesh_file, text_line); - text_line.erase (0,13); degree[0] = atoi(text_line.c_str()); + getline(mesh_file, text_line); + text_line.erase(0, 13); + degree[0] = atoi(text_line.c_str()); degree[1] = 1; - getline (mesh_file, text_line); - text_line.erase (0,13); degree[2] = atoi(text_line.c_str()); - } - else { - getline (mesh_file, text_line); - text_line.erase (0,13); degree[0] = atoi(text_line.c_str()); - getline (mesh_file, text_line); - text_line.erase (0,13); degree[1] = atoi(text_line.c_str()); + getline(mesh_file, text_line); + text_line.erase(0, 13); + degree[2] = atoi(text_line.c_str()); + } else { + getline(mesh_file, text_line); + text_line.erase(0, 13); + degree[0] = atoi(text_line.c_str()); + getline(mesh_file, text_line); + text_line.erase(0, 13); + degree[1] = atoi(text_line.c_str()); degree[2] = 1; } - } - else { - getline (mesh_file, text_line); - text_line.erase (0,13); degree[0] = atoi(text_line.c_str()); - getline (mesh_file, text_line); - text_line.erase (0,13); degree[1] = atoi(text_line.c_str()); - getline (mesh_file, text_line); - text_line.erase (0,13); degree[2] = atoi(text_line.c_str()); + } else { + getline(mesh_file, text_line); + text_line.erase(0, 13); + degree[0] = atoi(text_line.c_str()); + getline(mesh_file, text_line); + text_line.erase(0, 13); + degree[1] = atoi(text_line.c_str()); + getline(mesh_file, text_line); + text_line.erase(0, 13); + degree[2] = atoi(text_line.c_str()); } if (rank == MASTER_NODE) { if (nDim == 2) { - if (polar) cout << "Degrees: " << degree[0] << ", " << degree[2] << "." << endl; - else cout << "Degrees: " << degree[0] << ", " << degree[1] << "." << endl; - } - else cout << "Degrees: " << degree[0] << ", " << degree[1] << ", " << degree[2] << "." << endl; + if (polar) + cout << "Degrees: " << degree[0] << ", " << degree[2] << "." << endl; + else + cout << "Degrees: " << degree[0] << ", " << degree[1] << "." << endl; + } else + cout << "Degrees: " << degree[0] << ", " << degree[1] << ", " << degree[2] << "." << endl; } - getline (mesh_file, text_line); - if (text_line.substr(0,12) != "FFD_BLENDING"){ - SU2_MPI::Error(string("Deprecated FFD information found in mesh file.\n") + - string("FFD information generated with SU2 version <= 4.3 is incompatible with the current version.") + - string("Run SU2_DEF again with DV_KIND= FFD_SETTING."), CURRENT_FUNCTION); + getline(mesh_file, text_line); + if (text_line.substr(0, 12) != "FFD_BLENDING") { + SU2_MPI::Error( + string("Deprecated FFD information found in mesh file.\n") + + string( + "FFD information generated with SU2 version <= 4.3 is incompatible with the current version.") + + string("Run SU2_DEF again with DV_KIND= FFD_SETTING."), + CURRENT_FUNCTION); } - text_line.erase(0,14); - if (text_line == "BEZIER"){ + text_line.erase(0, 14); + if (text_line == "BEZIER") { Blending = BEZIER; } - if (text_line == "BSPLINE_UNIFORM"){ + if (text_line == "BSPLINE_UNIFORM") { Blending = BSPLINE_UNIFORM; } if (Blending == BSPLINE_UNIFORM) { - getline (mesh_file, text_line); - text_line.erase (0,17); SplineOrder[0] = atoi(text_line.c_str()); - getline (mesh_file, text_line); - text_line.erase (0,17); SplineOrder[1] = atoi(text_line.c_str()); - if (nDim == 3){ - getline (mesh_file, text_line); - text_line.erase (0,17); SplineOrder[2] = atoi(text_line.c_str()); + getline(mesh_file, text_line); + text_line.erase(0, 17); + SplineOrder[0] = atoi(text_line.c_str()); + getline(mesh_file, text_line); + text_line.erase(0, 17); + SplineOrder[1] = atoi(text_line.c_str()); + if (nDim == 3) { + getline(mesh_file, text_line); + text_line.erase(0, 17); + SplineOrder[2] = atoi(text_line.c_str()); } else { SplineOrder[2] = 2; } } - if (rank == MASTER_NODE){ - if (Blending == BSPLINE_UNIFORM){ + if (rank == MASTER_NODE) { + if (Blending == BSPLINE_UNIFORM) { cout << "FFD Blending using B-Splines. "; cout << "Order: " << SplineOrder[0] << ", " << SplineOrder[1]; if (nDim == 3) cout << ", " << SplineOrder[2]; cout << ". " << endl; } - if (Blending == BEZIER){ + if (Blending == BEZIER) { cout << "FFD Blending using Bezier Curves." << endl; } } FFDBox[iFFDBox] = new CFreeFormDefBox(degree, SplineOrder, Blending); - FFDBox[iFFDBox]->SetTag(TagFFDBox); FFDBox[iFFDBox]->SetLevel(LevelFFDBox); + FFDBox[iFFDBox]->SetTag(TagFFDBox); + FFDBox[iFFDBox]->SetLevel(LevelFFDBox); /*--- Read the number of parents boxes ---*/ - getline (mesh_file, text_line); - text_line.erase (0,12); + getline(mesh_file, text_line); + text_line.erase(0, 12); nParentFFDBox = atoi(text_line.c_str()); - if (rank == MASTER_NODE) cout << "Number of parent boxes: " << nParentFFDBox <<". "; + if (rank == MASTER_NODE) cout << "Number of parent boxes: " << nParentFFDBox << ". "; for (iParentFFDBox = 0; iParentFFDBox < nParentFFDBox; iParentFFDBox++) { getline(mesh_file, text_line); @@ -4047,12 +4244,12 @@ void CSurfaceMovement::ReadFFDInfo(CGeometry *geometry, CConfig *config, CFreeFo string::size_type position; for (iChar = 0; iChar < 20; iChar++) { - position = text_line.find( " ", 0 ); - if (position != string::npos) text_line.erase (position,1); - position = text_line.find( "\r", 0 ); - if (position != string::npos) text_line.erase (position,1); - position = text_line.find( "\n", 0 ); - if (position != string::npos) text_line.erase (position,1); + position = text_line.find(" ", 0); + if (position != string::npos) text_line.erase(position, 1); + position = text_line.find("\r", 0); + if (position != string::npos) text_line.erase(position, 1); + position = text_line.find("\n", 0); + if (position != string::npos) text_line.erase(position, 1); } string ParentFFDBox = text_line.c_str(); @@ -4061,10 +4258,10 @@ void CSurfaceMovement::ReadFFDInfo(CGeometry *geometry, CConfig *config, CFreeFo /*--- Read the number of children boxes ---*/ - getline (mesh_file, text_line); - text_line.erase (0,13); + getline(mesh_file, text_line); + text_line.erase(0, 13); nChildFFDBox = atoi(text_line.c_str()); - if (rank == MASTER_NODE) cout << "Number of child boxes: " << nChildFFDBox <<"." << endl; + if (rank == MASTER_NODE) cout << "Number of child boxes: " << nChildFFDBox << "." << endl; for (iChildFFDBox = 0; iChildFFDBox < nChildFFDBox; iChildFFDBox++) { getline(mesh_file, text_line); @@ -4073,12 +4270,12 @@ void CSurfaceMovement::ReadFFDInfo(CGeometry *geometry, CConfig *config, CFreeFo string::size_type position; for (iChar = 0; iChar < 20; iChar++) { - position = text_line.find( " ", 0 ); - if (position != string::npos) text_line.erase (position,1); - position = text_line.find( "\r", 0 ); - if (position != string::npos) text_line.erase (position,1); - position = text_line.find( "\n", 0 ); - if (position != string::npos) text_line.erase (position,1); + position = text_line.find(" ", 0); + if (position != string::npos) text_line.erase(position, 1); + position = text_line.find("\r", 0); + if (position != string::npos) text_line.erase(position, 1); + position = text_line.find("\n", 0); + if (position != string::npos) text_line.erase(position, 1); } string ChildFFDBox = text_line.c_str(); @@ -4087,103 +4284,113 @@ void CSurfaceMovement::ReadFFDInfo(CGeometry *geometry, CConfig *config, CFreeFo /*--- Read the number of the corner points ---*/ - getline (mesh_file, text_line); - text_line.erase (0,18); nCornerPoints[iFFDBox] = atoi(text_line.c_str()); - if (rank == MASTER_NODE) cout << "Corner points: " << nCornerPoints[iFFDBox] <<". "; - if (nDim == 2) nCornerPoints[iFFDBox] = nCornerPoints[iFFDBox]*SU2_TYPE::Int(2); - - + getline(mesh_file, text_line); + text_line.erase(0, 18); + nCornerPoints[iFFDBox] = atoi(text_line.c_str()); + if (rank == MASTER_NODE) cout << "Corner points: " << nCornerPoints[iFFDBox] << ". "; + if (nDim == 2) nCornerPoints[iFFDBox] = nCornerPoints[iFFDBox] * SU2_TYPE::Int(2); /*--- Read the coordinates of the corner points ---*/ - if (nDim == 2) { - if (polar) { - - getline(mesh_file, text_line); istringstream FFDBox_line_1(text_line); - FFDBox_line_1 >> XCoord; FFDBox_line_1 >> YCoord; + getline(mesh_file, text_line); + istringstream FFDBox_line_1(text_line); + FFDBox_line_1 >> XCoord; + FFDBox_line_1 >> YCoord; CPcoord[0] = XCoord; - CPcoord[1] = cos(0.1)*YCoord; - CPcoord[2] = -sin(0.1)*YCoord; + CPcoord[1] = cos(0.1) * YCoord; + CPcoord[2] = -sin(0.1) * YCoord; FFDBox[iFFDBox]->SetCoordCornerPoints(coord, 4); CPcoord[0] = XCoord; - CPcoord[1] = cos(0.1)*YCoord; - CPcoord[2] = sin(0.1)*YCoord; + CPcoord[1] = cos(0.1) * YCoord; + CPcoord[2] = sin(0.1) * YCoord; FFDBox[iFFDBox]->SetCoordCornerPoints(coord, 7); - getline(mesh_file, text_line); istringstream FFDBox_line_2(text_line); - FFDBox_line_2 >> XCoord; FFDBox_line_2 >> YCoord; + getline(mesh_file, text_line); + istringstream FFDBox_line_2(text_line); + FFDBox_line_2 >> XCoord; + FFDBox_line_2 >> YCoord; CPcoord[0] = XCoord; - CPcoord[1] = cos(0.1)*YCoord; - CPcoord[2] = -sin(0.1)*YCoord; + CPcoord[1] = cos(0.1) * YCoord; + CPcoord[2] = -sin(0.1) * YCoord; FFDBox[iFFDBox]->SetCoordCornerPoints(CPcoord, 0); CPcoord[0] = XCoord; - CPcoord[1] = cos(0.1)*YCoord; - CPcoord[2] = sin(0.1)*YCoord; + CPcoord[1] = cos(0.1) * YCoord; + CPcoord[2] = sin(0.1) * YCoord; FFDBox[iFFDBox]->SetCoordCornerPoints(CPcoord, 3); - getline(mesh_file, text_line); istringstream FFDBox_line_3(text_line); - FFDBox_line_3 >> XCoord; FFDBox_line_3 >> YCoord; + getline(mesh_file, text_line); + istringstream FFDBox_line_3(text_line); + FFDBox_line_3 >> XCoord; + FFDBox_line_3 >> YCoord; CPcoord[0] = XCoord; - CPcoord[1] = cos(0.1)*YCoord; - CPcoord[2] = -sin(0.1)*YCoord; + CPcoord[1] = cos(0.1) * YCoord; + CPcoord[2] = -sin(0.1) * YCoord; FFDBox[iFFDBox]->SetCoordCornerPoints(CPcoord, 1); CPcoord[0] = XCoord; - CPcoord[1] = cos(0.1)*YCoord; - CPcoord[2] = sin(0.1)*YCoord; + CPcoord[1] = cos(0.1) * YCoord; + CPcoord[2] = sin(0.1) * YCoord; FFDBox[iFFDBox]->SetCoordCornerPoints(CPcoord, 2); - getline(mesh_file, text_line); istringstream FFDBox_line_4(text_line); - FFDBox_line_4 >> XCoord; FFDBox_line_4 >> YCoord; + getline(mesh_file, text_line); + istringstream FFDBox_line_4(text_line); + FFDBox_line_4 >> XCoord; + FFDBox_line_4 >> YCoord; CPcoord[0] = XCoord; - CPcoord[1] = cos(0.1)*YCoord; - CPcoord[2] = -sin(0.1)*YCoord; + CPcoord[1] = cos(0.1) * YCoord; + CPcoord[2] = -sin(0.1) * YCoord; FFDBox[iFFDBox]->SetCoordCornerPoints(CPcoord, 5); CPcoord[0] = XCoord; - CPcoord[1] = cos(0.1)*YCoord; - CPcoord[2] = sin(0.1)*YCoord; + CPcoord[1] = cos(0.1) * YCoord; + CPcoord[2] = sin(0.1) * YCoord; FFDBox[iFFDBox]->SetCoordCornerPoints(CPcoord, 6); - } - else { + } else { for (iCornerPoints = 0; iCornerPoints < nCornerPoints[iFFDBox]; iCornerPoints++) { - if (iCornerPoints < nCornerPoints[iFFDBox]/SU2_TYPE::Int(2)) { - getline(mesh_file, text_line); istringstream FFDBox_line(text_line); - FFDBox_line >> CPcoord[0]; FFDBox_line >> CPcoord[1]; CPcoord[2] = -0.5; - } - else { - CPcoord[0] = FFDBox[iFFDBox]->GetCoordCornerPoints(0, iCornerPoints-nCornerPoints[iFFDBox]/SU2_TYPE::Int(2)); - CPcoord[1] = FFDBox[iFFDBox]->GetCoordCornerPoints(1, iCornerPoints-nCornerPoints[iFFDBox]/SU2_TYPE::Int(2)); + if (iCornerPoints < nCornerPoints[iFFDBox] / SU2_TYPE::Int(2)) { + getline(mesh_file, text_line); + istringstream FFDBox_line(text_line); + FFDBox_line >> CPcoord[0]; + FFDBox_line >> CPcoord[1]; + CPcoord[2] = -0.5; + } else { + CPcoord[0] = + FFDBox[iFFDBox]->GetCoordCornerPoints(0, iCornerPoints - nCornerPoints[iFFDBox] / SU2_TYPE::Int(2)); + CPcoord[1] = + FFDBox[iFFDBox]->GetCoordCornerPoints(1, iCornerPoints - nCornerPoints[iFFDBox] / SU2_TYPE::Int(2)); CPcoord[2] = 0.5; } FFDBox[iFFDBox]->SetCoordCornerPoints(CPcoord, iCornerPoints); } } - } - else { + } else { for (iCornerPoints = 0; iCornerPoints < nCornerPoints[iFFDBox]; iCornerPoints++) { - getline(mesh_file, text_line); istringstream FFDBox_line(text_line); - FFDBox_line >> CPcoord[0]; FFDBox_line >> CPcoord[1]; FFDBox_line >> CPcoord[2]; + getline(mesh_file, text_line); + istringstream FFDBox_line(text_line); + FFDBox_line >> CPcoord[0]; + FFDBox_line >> CPcoord[1]; + FFDBox_line >> CPcoord[2]; FFDBox[iFFDBox]->SetCoordCornerPoints(CPcoord, iCornerPoints); } } /*--- Read the number of the control points ---*/ - getline (mesh_file, text_line); - text_line.erase (0,19); nControlPoints[iFFDBox] = atoi(text_line.c_str()); + getline(mesh_file, text_line); + text_line.erase(0, 19); + nControlPoints[iFFDBox] = atoi(text_line.c_str()); - if (rank == MASTER_NODE) cout << "Control points: " << nControlPoints[iFFDBox] <<". "; + if (rank == MASTER_NODE) cout << "Control points: " << nControlPoints[iFFDBox] << ". "; /*--- Method to identify if there is a FFDBox definition ---*/ @@ -4192,34 +4399,43 @@ void CSurfaceMovement::ReadFFDInfo(CGeometry *geometry, CConfig *config, CFreeFo /*--- Read the coordinates of the control points ---*/ for (iControlPoints = 0; iControlPoints < nControlPoints[iFFDBox]; iControlPoints++) { - getline(mesh_file, text_line); istringstream FFDBox_line(text_line); - FFDBox_line >> iDegree; FFDBox_line >> jDegree; FFDBox_line >> kDegree; - FFDBox_line >> CPcoord[0]; FFDBox_line >> CPcoord[1]; FFDBox_line >> CPcoord[2]; + getline(mesh_file, text_line); + istringstream FFDBox_line(text_line); + FFDBox_line >> iDegree; + FFDBox_line >> jDegree; + FFDBox_line >> kDegree; + FFDBox_line >> CPcoord[0]; + FFDBox_line >> CPcoord[1]; + FFDBox_line >> CPcoord[2]; FFDBox[iFFDBox]->SetCoordControlPoints(CPcoord, iDegree, jDegree, kDegree); FFDBox[iFFDBox]->SetCoordControlPoints_Copy(CPcoord, iDegree, jDegree, kDegree); } - getline (mesh_file, text_line); - text_line.erase (0,19); nSurfacePoints[iFFDBox] = atoi(text_line.c_str()); + getline(mesh_file, text_line); + text_line.erase(0, 19); + nSurfacePoints[iFFDBox] = atoi(text_line.c_str()); /*--- The surface points parametric coordinates, all the nodes read the FFD information but they only store their part ---*/ my_nSurfPoints = 0; for (iSurfacePoints = 0; iSurfacePoints < nSurfacePoints[iFFDBox]; iSurfacePoints++) { - getline(mesh_file, text_line); istringstream FFDBox_line(text_line); - FFDBox_line >> iTag; FFDBox_line >> iPoint; + getline(mesh_file, text_line); + istringstream FFDBox_line(text_line); + FFDBox_line >> iTag; + FFDBox_line >> iPoint; if (config->GetMarker_All_TagBound(iTag) != -1) { - iMarker = config->GetMarker_All_TagBound(iTag); - FFDBox_line >> CPcoord[0]; FFDBox_line >> CPcoord[1]; FFDBox_line >> CPcoord[2]; + FFDBox_line >> CPcoord[0]; + FFDBox_line >> CPcoord[1]; + FFDBox_line >> CPcoord[2]; for (iVertex = 0; iVertex < geometry->nVertex[iMarker]; iVertex++) { - jPoint = geometry->vertex[iMarker][iVertex]->GetNode(); + jPoint = geometry->vertex[iMarker][iVertex]->GetNode(); if (iPoint == geometry->nodes->GetGlobalIndex(jPoint)) { for (iDim = 0; iDim < nDim; iDim++) { - coord[iDim] = geometry->nodes->GetCoord(jPoint,iDim); + coord[iDim] = geometry->nodes->GetCoord(jPoint, iDim); } FFDBox[iFFDBox]->Set_MarkerIndex(iMarker); FFDBox[iFFDBox]->Set_VertexIndex(iVertex); @@ -4229,9 +4445,7 @@ void CSurfaceMovement::ReadFFDInfo(CGeometry *geometry, CConfig *config, CFreeFo my_nSurfPoints++; } } - } - } nSurfacePoints[iFFDBox] = my_nSurfPoints; @@ -4239,44 +4453,40 @@ void CSurfaceMovement::ReadFFDInfo(CGeometry *geometry, CConfig *config, CFreeFo #ifdef HAVE_MPI nSurfPoints = 0; SU2_MPI::Allreduce(&my_nSurfPoints, &nSurfPoints, 1, MPI_UNSIGNED_LONG, MPI_SUM, SU2_MPI::GetComm()); - if (rank == MASTER_NODE) cout << "Surface points: " << nSurfPoints <<"."<< endl; + if (rank == MASTER_NODE) cout << "Surface points: " << nSurfPoints << "." << endl; #else nSurfPoints = my_nSurfPoints; - if (rank == MASTER_NODE) cout << "Surface points: " << nSurfPoints <<"."<< endl; + if (rank == MASTER_NODE) cout << "Surface points: " << nSurfPoints << "." << endl; #endif - } - delete [] nCornerPoints; - delete [] nControlPoints; - delete [] nSurfacePoints; + delete[] nCornerPoints; + delete[] nControlPoints; + delete[] nSurfacePoints; } } mesh_file.close(); if (nFFDBox == 0) { - if (rank == MASTER_NODE) cout <<"There is no FFD box definition. Just in case, check the .su2 file" << endl; + if (rank == MASTER_NODE) cout << "There is no FFD box definition. Just in case, check the .su2 file" << endl; } - } -void CSurfaceMovement::ReadFFDInfo(CGeometry *geometry, CConfig *config, CFreeFormDefBox **FFDBox) { - +void CSurfaceMovement::ReadFFDInfo(CGeometry* geometry, CConfig* config, CFreeFormDefBox** FFDBox) { string text_line, iTag; ifstream mesh_file; su2double coord[3]; - unsigned short degree[3], iFFDBox, iCornerPoints, LevelFFDBox, nParentFFDBox, - iParentFFDBox, nChildFFDBox, iChildFFDBox, *nCornerPoints; + unsigned short degree[3], iFFDBox, iCornerPoints, LevelFFDBox, nParentFFDBox, iParentFFDBox, nChildFFDBox, + iChildFFDBox, *nCornerPoints; bool polar = (config->GetFFD_CoordSystem() == POLAR); unsigned short nDim = geometry->GetnDim(), iDim; - unsigned short SplineOrder[3]={2,2,2}; + unsigned short SplineOrder[3] = {2, 2, 2}; - for (iDim = 0; iDim < 3; iDim++){ + for (iDim = 0; iDim < 3; iDim++) { SplineOrder[iDim] = SU2_TYPE::Short(config->GetFFD_BSplineOrder()[iDim]); } - /*--- Read the FFDBox information from the config file ---*/ nFFDBox = config->GetnFFDBox(); @@ -4285,23 +4495,22 @@ void CSurfaceMovement::ReadFFDInfo(CGeometry *geometry, CConfig *config, CFreeFo nCornerPoints = new unsigned short[nFFDBox]; - nLevel = 1; // Nested FFD is not active + nLevel = 1; // Nested FFD is not active if (rank == MASTER_NODE) cout << nLevel << " Free Form Deformation nested levels." << endl; - for (iFFDBox = 0 ; iFFDBox < nFFDBox; iFFDBox++) { - + for (iFFDBox = 0; iFFDBox < nFFDBox; iFFDBox++) { /*--- Read the name of the FFD box ---*/ string TagFFDBox = config->GetTagFFDBox(iFFDBox); - if (rank == MASTER_NODE) cout << "FFD box tag: " << TagFFDBox <<". "; + if (rank == MASTER_NODE) cout << "FFD box tag: " << TagFFDBox << ". "; /*--- Read the level of the FFD box ---*/ - LevelFFDBox = 0; // Nested FFD is not active + LevelFFDBox = 0; // Nested FFD is not active - if (rank == MASTER_NODE) cout << "FFD box level: " << LevelFFDBox <<". "; + if (rank == MASTER_NODE) cout << "FFD box level: " << LevelFFDBox << ". "; /*--- Read the degree of the FFD box ---*/ @@ -4310,14 +4519,12 @@ void CSurfaceMovement::ReadFFDInfo(CGeometry *geometry, CConfig *config, CFreeFo degree[0] = config->GetDegreeFFDBox(iFFDBox, 0); degree[1] = 1; degree[2] = config->GetDegreeFFDBox(iFFDBox, 1); - } - else { + } else { degree[0] = config->GetDegreeFFDBox(iFFDBox, 0); degree[1] = config->GetDegreeFFDBox(iFFDBox, 1); degree[2] = 1; } - } - else { + } else { degree[0] = config->GetDegreeFFDBox(iFFDBox, 0); degree[1] = config->GetDegreeFFDBox(iFFDBox, 1); degree[2] = config->GetDegreeFFDBox(iFFDBox, 2); @@ -4325,44 +4532,47 @@ void CSurfaceMovement::ReadFFDInfo(CGeometry *geometry, CConfig *config, CFreeFo if (rank == MASTER_NODE) { if (nDim == 2) { - if (polar) cout << "Degrees: " << degree[0] << ", " << degree[2] << "." << endl; - else cout << "Degrees: " << degree[0] << ", " << degree[1] << "." << endl; - } - else cout << "Degrees: " << degree[0] << ", " << degree[1] << ", " << degree[2] << "." << endl; + if (polar) + cout << "Degrees: " << degree[0] << ", " << degree[2] << "." << endl; + else + cout << "Degrees: " << degree[0] << ", " << degree[1] << "." << endl; + } else + cout << "Degrees: " << degree[0] << ", " << degree[1] << ", " << degree[2] << "." << endl; } - if (rank == MASTER_NODE){ - if (config->GetFFD_Blending() == BSPLINE_UNIFORM){ + if (rank == MASTER_NODE) { + if (config->GetFFD_Blending() == BSPLINE_UNIFORM) { cout << "FFD Blending using B-Splines. "; cout << "Order: " << SplineOrder[0] << ", " << SplineOrder[1]; if (nDim == 3) cout << ", " << SplineOrder[2]; cout << ". " << endl; } - if (config->GetFFD_Blending() == BEZIER){ + if (config->GetFFD_Blending() == BEZIER) { cout << "FFD Blending using Bezier Curves." << endl; } } FFDBox[iFFDBox] = new CFreeFormDefBox(degree, SplineOrder, config->GetFFD_Blending()); - FFDBox[iFFDBox]->SetTag(TagFFDBox); FFDBox[iFFDBox]->SetLevel(LevelFFDBox); + FFDBox[iFFDBox]->SetTag(TagFFDBox); + FFDBox[iFFDBox]->SetLevel(LevelFFDBox); /*--- Read the number of parents boxes ---*/ - nParentFFDBox = 0; // Nested FFD is not active - if (rank == MASTER_NODE) cout << "Number of parent boxes: " << nParentFFDBox <<". "; + nParentFFDBox = 0; // Nested FFD is not active + if (rank == MASTER_NODE) cout << "Number of parent boxes: " << nParentFFDBox << ". "; for (iParentFFDBox = 0; iParentFFDBox < nParentFFDBox; iParentFFDBox++) { - string ParentFFDBox = "NONE"; // Nested FFD is not active + string ParentFFDBox = "NONE"; // Nested FFD is not active FFDBox[iFFDBox]->SetParentFFDBox(ParentFFDBox); } /*--- Read the number of children boxes ---*/ - nChildFFDBox = 0; // Nested FFD is not active - if (rank == MASTER_NODE) cout << "Number of child boxes: " << nChildFFDBox <<"." << endl; + nChildFFDBox = 0; // Nested FFD is not active + if (rank == MASTER_NODE) cout << "Number of child boxes: " << nChildFFDBox << "." << endl; for (iChildFFDBox = 0; iChildFFDBox < nChildFFDBox; iChildFFDBox++) { - string ChildFFDBox = "NONE"; // Nested FFD is not active + string ChildFFDBox = "NONE"; // Nested FFD is not active FFDBox[iFFDBox]->SetChildFFDBox(ChildFFDBox); } @@ -4373,93 +4583,86 @@ void CSurfaceMovement::ReadFFDInfo(CGeometry *geometry, CConfig *config, CFreeFo /*--- Read the coordinates of the corner points ---*/ for (iCornerPoints = 0; iCornerPoints < nCornerPoints[iFFDBox]; iCornerPoints++) { - if (nDim == 2) { - if (polar) { - - coord[0] = config->GetCoordFFDBox(iFFDBox, 1*3); - coord[1] = cos(0.1)*config->GetCoordFFDBox(iFFDBox, 1*3+1); - coord[2] = -sin(0.1)*config->GetCoordFFDBox(iFFDBox, 1*3+1); + coord[0] = config->GetCoordFFDBox(iFFDBox, 1 * 3); + coord[1] = cos(0.1) * config->GetCoordFFDBox(iFFDBox, 1 * 3 + 1); + coord[2] = -sin(0.1) * config->GetCoordFFDBox(iFFDBox, 1 * 3 + 1); FFDBox[iFFDBox]->SetCoordCornerPoints(coord, 0); - coord[0] = config->GetCoordFFDBox(iFFDBox, 2*3); - coord[1] = cos(0.1)*config->GetCoordFFDBox(iFFDBox, 2*3+1); - coord[2] = -sin(0.1)*config->GetCoordFFDBox(iFFDBox, 2*3+1); + coord[0] = config->GetCoordFFDBox(iFFDBox, 2 * 3); + coord[1] = cos(0.1) * config->GetCoordFFDBox(iFFDBox, 2 * 3 + 1); + coord[2] = -sin(0.1) * config->GetCoordFFDBox(iFFDBox, 2 * 3 + 1); FFDBox[iFFDBox]->SetCoordCornerPoints(coord, 1); - coord[0] = config->GetCoordFFDBox(iFFDBox, 2*3); - coord[1] = cos(0.1)*config->GetCoordFFDBox(iFFDBox, 2*3+1); - coord[2] = sin(0.1)*config->GetCoordFFDBox(iFFDBox, 2*3+1); + coord[0] = config->GetCoordFFDBox(iFFDBox, 2 * 3); + coord[1] = cos(0.1) * config->GetCoordFFDBox(iFFDBox, 2 * 3 + 1); + coord[2] = sin(0.1) * config->GetCoordFFDBox(iFFDBox, 2 * 3 + 1); FFDBox[iFFDBox]->SetCoordCornerPoints(coord, 2); - coord[0] = config->GetCoordFFDBox(iFFDBox, 1*3); - coord[1] = cos(0.1)*config->GetCoordFFDBox(iFFDBox, 1*3+1); - coord[2] = sin(0.1)*config->GetCoordFFDBox(iFFDBox, 1*3+1); + coord[0] = config->GetCoordFFDBox(iFFDBox, 1 * 3); + coord[1] = cos(0.1) * config->GetCoordFFDBox(iFFDBox, 1 * 3 + 1); + coord[2] = sin(0.1) * config->GetCoordFFDBox(iFFDBox, 1 * 3 + 1); FFDBox[iFFDBox]->SetCoordCornerPoints(coord, 3); - coord[0] = config->GetCoordFFDBox(iFFDBox, 0*3); - coord[1] = cos(0.1)*config->GetCoordFFDBox(iFFDBox, 0*3+1); - coord[2] = -sin(0.1)*config->GetCoordFFDBox(iFFDBox, 0*3+1); + coord[0] = config->GetCoordFFDBox(iFFDBox, 0 * 3); + coord[1] = cos(0.1) * config->GetCoordFFDBox(iFFDBox, 0 * 3 + 1); + coord[2] = -sin(0.1) * config->GetCoordFFDBox(iFFDBox, 0 * 3 + 1); FFDBox[iFFDBox]->SetCoordCornerPoints(coord, 4); - coord[0] = config->GetCoordFFDBox(iFFDBox, 3*3); - coord[1] = cos(0.1)*config->GetCoordFFDBox(iFFDBox, 3*3+1); - coord[2] = -sin(0.1)*config->GetCoordFFDBox(iFFDBox, 3*3+1); + coord[0] = config->GetCoordFFDBox(iFFDBox, 3 * 3); + coord[1] = cos(0.1) * config->GetCoordFFDBox(iFFDBox, 3 * 3 + 1); + coord[2] = -sin(0.1) * config->GetCoordFFDBox(iFFDBox, 3 * 3 + 1); FFDBox[iFFDBox]->SetCoordCornerPoints(coord, 5); - coord[0] = config->GetCoordFFDBox(iFFDBox, 3*3); - coord[1] = cos(0.1)*config->GetCoordFFDBox(iFFDBox, 3*3+1); - coord[2] = sin(0.1)*config->GetCoordFFDBox(iFFDBox, 3*3+1); + coord[0] = config->GetCoordFFDBox(iFFDBox, 3 * 3); + coord[1] = cos(0.1) * config->GetCoordFFDBox(iFFDBox, 3 * 3 + 1); + coord[2] = sin(0.1) * config->GetCoordFFDBox(iFFDBox, 3 * 3 + 1); FFDBox[iFFDBox]->SetCoordCornerPoints(coord, 6); - coord[0] = config->GetCoordFFDBox(iFFDBox, 0*3); - coord[1] = cos(0.1)*config->GetCoordFFDBox(iFFDBox, 0*3+1); - coord[2] = sin(0.1)*config->GetCoordFFDBox(iFFDBox, 0*3+1); + coord[0] = config->GetCoordFFDBox(iFFDBox, 0 * 3); + coord[1] = cos(0.1) * config->GetCoordFFDBox(iFFDBox, 0 * 3 + 1); + coord[2] = sin(0.1) * config->GetCoordFFDBox(iFFDBox, 0 * 3 + 1); FFDBox[iFFDBox]->SetCoordCornerPoints(coord, 7); } else { - if (iCornerPoints < nCornerPoints[iFFDBox]/SU2_TYPE::Int(2)) { - coord[0] = config->GetCoordFFDBox(iFFDBox, iCornerPoints*3); - coord[1] = config->GetCoordFFDBox(iFFDBox, iCornerPoints*3+1); + if (iCornerPoints < nCornerPoints[iFFDBox] / SU2_TYPE::Int(2)) { + coord[0] = config->GetCoordFFDBox(iFFDBox, iCornerPoints * 3); + coord[1] = config->GetCoordFFDBox(iFFDBox, iCornerPoints * 3 + 1); coord[2] = -0.5; - } - else { - coord[0] = FFDBox[iFFDBox]->GetCoordCornerPoints(0, iCornerPoints-nCornerPoints[iFFDBox]/SU2_TYPE::Int(2)); - coord[1] = FFDBox[iFFDBox]->GetCoordCornerPoints(1, iCornerPoints-nCornerPoints[iFFDBox]/SU2_TYPE::Int(2)); + } else { + coord[0] = + FFDBox[iFFDBox]->GetCoordCornerPoints(0, iCornerPoints - nCornerPoints[iFFDBox] / SU2_TYPE::Int(2)); + coord[1] = + FFDBox[iFFDBox]->GetCoordCornerPoints(1, iCornerPoints - nCornerPoints[iFFDBox] / SU2_TYPE::Int(2)); coord[2] = 0.5; } } - } - else { - coord[0] = config->GetCoordFFDBox(iFFDBox, iCornerPoints*3); - coord[1] = config->GetCoordFFDBox(iFFDBox, iCornerPoints*3+1); - coord[2] = config->GetCoordFFDBox(iFFDBox, iCornerPoints*3+2); + } else { + coord[0] = config->GetCoordFFDBox(iFFDBox, iCornerPoints * 3); + coord[1] = config->GetCoordFFDBox(iFFDBox, iCornerPoints * 3 + 1); + coord[2] = config->GetCoordFFDBox(iFFDBox, iCornerPoints * 3 + 2); } FFDBox[iFFDBox]->SetCoordCornerPoints(coord, iCornerPoints); - } /*--- Method to identify if there is a FFDBox definition ---*/ FFDBoxDefinition = false; - } - delete [] nCornerPoints; + delete[] nCornerPoints; if (nFFDBox == 0) { SU2_MPI::Error("There is no FFD box definition. Check the config file.", CURRENT_FUNCTION); } - } -void CSurfaceMovement::MergeFFDInfo(CGeometry *geometry, CConfig *config) { - +void CSurfaceMovement::MergeFFDInfo(CGeometry* geometry, CConfig* config) { /*--- Local variables needed on all processors ---*/ unsigned long iPoint; @@ -4472,12 +4675,10 @@ void CSurfaceMovement::MergeFFDInfo(CGeometry *geometry, CConfig *config) { /*--- Total number of points in each FFD box. ---*/ - for (iFFDBox = 0 ; iFFDBox < nFFDBox; iFFDBox++) { - + for (iFFDBox = 0; iFFDBox < nFFDBox; iFFDBox++) { /*--- Loop over the mesh to collect the coords of the local points. ---*/ for (iPoint = 0; iPoint < FFDBox[iFFDBox]->GetnSurfacePoint(); iPoint++) { - /*--- Retrieve the current parametric coordinates at this node. ---*/ GlobalCoordX[iFFDBox].push_back(FFDBox[iFFDBox]->Get_ParametricCoord(iPoint)[0]); @@ -4498,9 +4699,7 @@ void CSurfaceMovement::MergeFFDInfo(CGeometry *geometry, CConfig *config) { /*--- Set the value of the tag at this node. ---*/ GlobalTag[iFFDBox].push_back(TagBound_CfgFile); - } - } #else @@ -4518,55 +4717,50 @@ void CSurfaceMovement::MergeFFDInfo(CGeometry *geometry, CConfig *config) { if (rank == MASTER_NODE) Buffer_Recv_nPoint = new unsigned long[nProcessor]; - for (iFFDBox = 0 ; iFFDBox < nFFDBox; iFFDBox++) { - + for (iFFDBox = 0; iFFDBox < nFFDBox; iFFDBox++) { nLocalPoint = 0; for (iPoint = 0; iPoint < FFDBox[iFFDBox]->GetnSurfacePoint(); iPoint++) { - iPointLocal = FFDBox[iFFDBox]->Get_PointIndex(iPoint); if (iPointLocal < geometry->GetnPointDomain()) { nLocalPoint++; } - } Buffer_Send_nPoint[0] = nLocalPoint; /*--- Communicate the total number of nodes on this domain. ---*/ - SU2_MPI::Gather(&Buffer_Send_nPoint, 1, MPI_UNSIGNED_LONG, - Buffer_Recv_nPoint, 1, MPI_UNSIGNED_LONG, MASTER_NODE, SU2_MPI::GetComm()); + SU2_MPI::Gather(&Buffer_Send_nPoint, 1, MPI_UNSIGNED_LONG, Buffer_Recv_nPoint, 1, MPI_UNSIGNED_LONG, MASTER_NODE, + SU2_MPI::GetComm()); SU2_MPI::Allreduce(&nLocalPoint, &MaxLocalPoint, 1, MPI_UNSIGNED_LONG, MPI_MAX, SU2_MPI::GetComm()); nBuffer_Scalar = MaxLocalPoint; /*--- Send and Recv buffers. ---*/ - su2double *Buffer_Send_X = new su2double[MaxLocalPoint]; - su2double *Buffer_Recv_X = nullptr; + su2double* Buffer_Send_X = new su2double[MaxLocalPoint]; + su2double* Buffer_Recv_X = nullptr; - su2double *Buffer_Send_Y = new su2double[MaxLocalPoint]; - su2double *Buffer_Recv_Y = nullptr; + su2double* Buffer_Send_Y = new su2double[MaxLocalPoint]; + su2double* Buffer_Recv_Y = nullptr; - su2double *Buffer_Send_Z = new su2double[MaxLocalPoint]; - su2double *Buffer_Recv_Z = nullptr; + su2double* Buffer_Send_Z = new su2double[MaxLocalPoint]; + su2double* Buffer_Recv_Z = nullptr; - unsigned long *Buffer_Send_Point = new unsigned long[MaxLocalPoint]; - unsigned long *Buffer_Recv_Point = nullptr; + unsigned long* Buffer_Send_Point = new unsigned long[MaxLocalPoint]; + unsigned long* Buffer_Recv_Point = nullptr; - unsigned short *Buffer_Send_MarkerIndex_CfgFile = new unsigned short[MaxLocalPoint]; - unsigned short *Buffer_Recv_MarkerIndex_CfgFile = nullptr; + unsigned short* Buffer_Send_MarkerIndex_CfgFile = new unsigned short[MaxLocalPoint]; + unsigned short* Buffer_Recv_MarkerIndex_CfgFile = nullptr; /*--- Prepare the receive buffers in the master node only. ---*/ if (rank == MASTER_NODE) { - - Buffer_Recv_X = new su2double[nProcessor*MaxLocalPoint]; - Buffer_Recv_Y = new su2double[nProcessor*MaxLocalPoint]; - Buffer_Recv_Z = new su2double[nProcessor*MaxLocalPoint]; - Buffer_Recv_Point = new unsigned long[nProcessor*MaxLocalPoint]; - Buffer_Recv_MarkerIndex_CfgFile = new unsigned short[nProcessor*MaxLocalPoint]; - + Buffer_Recv_X = new su2double[nProcessor * MaxLocalPoint]; + Buffer_Recv_Y = new su2double[nProcessor * MaxLocalPoint]; + Buffer_Recv_Z = new su2double[nProcessor * MaxLocalPoint]; + Buffer_Recv_Point = new unsigned long[nProcessor * MaxLocalPoint]; + Buffer_Recv_MarkerIndex_CfgFile = new unsigned short[nProcessor * MaxLocalPoint]; } /*--- Main communication routine. Loop over each coordinate and perform @@ -4578,11 +4772,9 @@ void CSurfaceMovement::MergeFFDInfo(CGeometry *geometry, CConfig *config) { jPoint = 0; for (iPoint = 0; iPoint < FFDBox[iFFDBox]->GetnSurfacePoint(); iPoint++) { - iPointLocal = FFDBox[iFFDBox]->Get_PointIndex(iPoint); if (iPointLocal < geometry->GetnPointDomain()) { - /*--- Load local coords into the temporary send buffer. ---*/ Buffer_Send_X[jPoint] = FFDBox[iFFDBox]->Get_ParametricCoord(iPoint)[0]; @@ -4604,28 +4796,30 @@ void CSurfaceMovement::MergeFFDInfo(CGeometry *geometry, CConfig *config) { Buffer_Send_MarkerIndex_CfgFile[jPoint] = MarkerIndex_CfgFile; jPoint++; - } - } /*--- Gather the coordinate data on the master node using MPI. ---*/ - SU2_MPI::Gather(Buffer_Send_X, nBuffer_Scalar, MPI_DOUBLE, Buffer_Recv_X, nBuffer_Scalar, MPI_DOUBLE, MASTER_NODE, SU2_MPI::GetComm()); - SU2_MPI::Gather(Buffer_Send_Y, nBuffer_Scalar, MPI_DOUBLE, Buffer_Recv_Y, nBuffer_Scalar, MPI_DOUBLE, MASTER_NODE, SU2_MPI::GetComm()); - SU2_MPI::Gather(Buffer_Send_Z, nBuffer_Scalar, MPI_DOUBLE, Buffer_Recv_Z, nBuffer_Scalar, MPI_DOUBLE, MASTER_NODE, SU2_MPI::GetComm()); - SU2_MPI::Gather(Buffer_Send_Point, nBuffer_Scalar, MPI_UNSIGNED_LONG, Buffer_Recv_Point, nBuffer_Scalar, MPI_UNSIGNED_LONG, MASTER_NODE, SU2_MPI::GetComm()); - SU2_MPI::Gather(Buffer_Send_MarkerIndex_CfgFile, nBuffer_Scalar, MPI_UNSIGNED_SHORT, Buffer_Recv_MarkerIndex_CfgFile, nBuffer_Scalar, MPI_UNSIGNED_SHORT, MASTER_NODE, SU2_MPI::GetComm()); + SU2_MPI::Gather(Buffer_Send_X, nBuffer_Scalar, MPI_DOUBLE, Buffer_Recv_X, nBuffer_Scalar, MPI_DOUBLE, MASTER_NODE, + SU2_MPI::GetComm()); + SU2_MPI::Gather(Buffer_Send_Y, nBuffer_Scalar, MPI_DOUBLE, Buffer_Recv_Y, nBuffer_Scalar, MPI_DOUBLE, MASTER_NODE, + SU2_MPI::GetComm()); + SU2_MPI::Gather(Buffer_Send_Z, nBuffer_Scalar, MPI_DOUBLE, Buffer_Recv_Z, nBuffer_Scalar, MPI_DOUBLE, MASTER_NODE, + SU2_MPI::GetComm()); + SU2_MPI::Gather(Buffer_Send_Point, nBuffer_Scalar, MPI_UNSIGNED_LONG, Buffer_Recv_Point, nBuffer_Scalar, + MPI_UNSIGNED_LONG, MASTER_NODE, SU2_MPI::GetComm()); + SU2_MPI::Gather(Buffer_Send_MarkerIndex_CfgFile, nBuffer_Scalar, MPI_UNSIGNED_SHORT, + Buffer_Recv_MarkerIndex_CfgFile, nBuffer_Scalar, MPI_UNSIGNED_SHORT, MASTER_NODE, + SU2_MPI::GetComm()); /*--- The master node unpacks and sorts this variable by global index ---*/ if (rank == MASTER_NODE) { - jPoint = 0; for (iProcessor = 0; iProcessor < nProcessor; iProcessor++) { for (iPoint = 0; iPoint < Buffer_Recv_nPoint[iProcessor]; iPoint++) { - /*--- Get global index, then loop over each variable and store ---*/ GlobalCoordX[iFFDBox].push_back(Buffer_Recv_X[jPoint]); @@ -4636,67 +4830,58 @@ void CSurfaceMovement::MergeFFDInfo(CGeometry *geometry, CConfig *config) { string TagBound_CfgFile = config->GetMarker_CfgFile_TagBound(Buffer_Recv_MarkerIndex_CfgFile[jPoint]); GlobalTag[iFFDBox].push_back(TagBound_CfgFile); jPoint++; - } /*--- Adjust jPoint to index of next proc's data in the buffers. ---*/ - jPoint = (iProcessor+1)*nBuffer_Scalar; - + jPoint = (iProcessor + 1) * nBuffer_Scalar; } } /*--- Immediately release the temporary data buffers. ---*/ - delete [] Buffer_Send_X; - delete [] Buffer_Send_Y; - delete [] Buffer_Send_Z; - delete [] Buffer_Send_Point; - delete [] Buffer_Send_MarkerIndex_CfgFile; + delete[] Buffer_Send_X; + delete[] Buffer_Send_Y; + delete[] Buffer_Send_Z; + delete[] Buffer_Send_Point; + delete[] Buffer_Send_MarkerIndex_CfgFile; if (rank == MASTER_NODE) { - delete [] Buffer_Recv_X; - delete [] Buffer_Recv_Y; - delete [] Buffer_Recv_Z; - delete [] Buffer_Recv_Point; - delete [] Buffer_Recv_MarkerIndex_CfgFile; + delete[] Buffer_Recv_X; + delete[] Buffer_Recv_Y; + delete[] Buffer_Recv_Z; + delete[] Buffer_Recv_Point; + delete[] Buffer_Recv_MarkerIndex_CfgFile; } - } if (rank == MASTER_NODE) { - delete [] Buffer_Recv_nPoint; + delete[] Buffer_Recv_nPoint; } #endif - } -void CSurfaceMovement::WriteFFDInfo(CSurfaceMovement** surface_movement, CGeometry ****geometry, CConfig **config) { - - +void CSurfaceMovement::WriteFFDInfo(CSurfaceMovement** surface_movement, CGeometry**** geometry, CConfig** config) { unsigned short iOrder, jOrder, kOrder, iFFDBox, iCornerPoints, iParentFFDBox, iChildFFDBox, iZone; unsigned long iSurfacePoints; ofstream output_file; - su2double *coord; + su2double* coord; string text_line; bool polar = (config[ZONE_0]->GetFFD_CoordSystem() == POLAR); unsigned short nDim = geometry[ZONE_0][INST_0][MESH_0]->GetnDim(); - for (iZone = 0; iZone < config[ZONE_0]->GetnZone(); iZone++){ - + for (iZone = 0; iZone < config[ZONE_0]->GetnZone(); iZone++) { /*--- Merge the parallel FFD info ---*/ surface_movement[iZone]->MergeFFDInfo(geometry[iZone][INST_0][MESH_0], config[iZone]); - if (iZone > 0){ - + if (iZone > 0) { /* --- Merge the per-zone FFD info from the other zones into ZONE_0 ---*/ - for (iFFDBox = 0; iFFDBox < nFFDBox; iFFDBox++){ - + for (iFFDBox = 0; iFFDBox < nFFDBox; iFFDBox++) { surface_movement[ZONE_0]->GlobalCoordX[iFFDBox].insert(surface_movement[ZONE_0]->GlobalCoordX[iFFDBox].end(), surface_movement[iZone]->GlobalCoordX[iFFDBox].begin(), surface_movement[iZone]->GlobalCoordX[iFFDBox].end()); @@ -4707,22 +4892,18 @@ void CSurfaceMovement::WriteFFDInfo(CSurfaceMovement** surface_movement, CGeomet surface_movement[iZone]->GlobalCoordZ[iFFDBox].begin(), surface_movement[iZone]->GlobalCoordZ[iFFDBox].end()); surface_movement[ZONE_0]->GlobalTag[iFFDBox].insert(surface_movement[ZONE_0]->GlobalTag[iFFDBox].end(), - surface_movement[iZone]->GlobalTag[iFFDBox].begin(), - surface_movement[iZone]->GlobalTag[iFFDBox].end()); + surface_movement[iZone]->GlobalTag[iFFDBox].begin(), + surface_movement[iZone]->GlobalTag[iFFDBox].end()); surface_movement[ZONE_0]->GlobalPoint[iFFDBox].insert(surface_movement[ZONE_0]->GlobalPoint[iFFDBox].end(), - surface_movement[iZone]->GlobalPoint[iFFDBox].begin(), - surface_movement[iZone]->GlobalPoint[iFFDBox].end()); + surface_movement[iZone]->GlobalPoint[iFFDBox].begin(), + surface_movement[iZone]->GlobalPoint[iFFDBox].end()); } } } - - - /*--- Attach to the mesh file the FFD information (all information is in ZONE_0) ---*/ if (rank == MASTER_NODE) { - /*--- Read the name of the output file ---*/ auto str = config[ZONE_0]->GetMesh_Out_FileName(); @@ -4737,20 +4918,23 @@ void CSurfaceMovement::WriteFFDInfo(CSurfaceMovement** surface_movement, CGeomet output_file << "FFD_NLEVEL= " << nLevel << endl; } - for (iFFDBox = 0 ; iFFDBox < nFFDBox; iFFDBox++) { - + for (iFFDBox = 0; iFFDBox < nFFDBox; iFFDBox++) { output_file << "FFD_TAG= " << FFDBox[iFFDBox]->GetTag() << endl; output_file << "FFD_LEVEL= " << FFDBox[iFFDBox]->GetLevel() << endl; - output_file << "FFD_DEGREE_I= " << FFDBox[iFFDBox]->GetlOrder()-1 << endl; - if (polar) output_file << "FFD_DEGREE_J= " << FFDBox[iFFDBox]->GetnOrder()-1 << endl; - else output_file << "FFD_DEGREE_J= " << FFDBox[iFFDBox]->GetmOrder()-1 << endl; - if (nDim == 3) output_file << "FFD_DEGREE_K= " << FFDBox[iFFDBox]->GetnOrder()-1 << endl; + output_file << "FFD_DEGREE_I= " << FFDBox[iFFDBox]->GetlOrder() - 1 << endl; + if (polar) + output_file << "FFD_DEGREE_J= " << FFDBox[iFFDBox]->GetnOrder() - 1 << endl; + else + output_file << "FFD_DEGREE_J= " << FFDBox[iFFDBox]->GetmOrder() - 1 << endl; + if (nDim == 3) output_file << "FFD_DEGREE_K= " << FFDBox[iFFDBox]->GetnOrder() - 1 << endl; if (config[ZONE_0]->GetFFD_Blending() == BSPLINE_UNIFORM) { output_file << "FFD_BLENDING= BSPLINE_UNIFORM" << endl; output_file << "BSPLINE_ORDER_I= " << FFDBox[iFFDBox]->BlendingFunction[0]->GetOrder() << endl; - if (polar) output_file << "BSPLINE_ORDER_J= " << FFDBox[iFFDBox]->BlendingFunction[2]->GetOrder() << endl; - else output_file << "BSPLINE_ORDER_J= " << FFDBox[iFFDBox]->BlendingFunction[1]->GetOrder() << endl; + if (polar) + output_file << "BSPLINE_ORDER_J= " << FFDBox[iFFDBox]->BlendingFunction[2]->GetOrder() << endl; + else + output_file << "BSPLINE_ORDER_J= " << FFDBox[iFFDBox]->BlendingFunction[1]->GetOrder() << endl; if (nDim == 3) output_file << "BSPLINE_ORDER_K= " << FFDBox[iFFDBox]->BlendingFunction[2]->GetOrder() << endl; } if (config[ZONE_0]->GetFFD_Blending() == BEZIER) { @@ -4765,28 +4949,27 @@ void CSurfaceMovement::WriteFFDInfo(CSurfaceMovement** surface_movement, CGeomet output_file << FFDBox[iFFDBox]->GetChildFFDBoxTag(iChildFFDBox) << endl; if (nDim == 2) { - output_file << "FFD_CORNER_POINTS= " << FFDBox[iFFDBox]->GetnCornerPoints()/SU2_TYPE::Int(2) << endl; + output_file << "FFD_CORNER_POINTS= " << FFDBox[iFFDBox]->GetnCornerPoints() / SU2_TYPE::Int(2) << endl; if (polar) { coord = FFDBox[iFFDBox]->GetCoordCornerPoints(4); - output_file << coord[0] << "\t" << sqrt(coord[1]*coord[1]+coord[2]*coord[2]) << endl; + output_file << coord[0] << "\t" << sqrt(coord[1] * coord[1] + coord[2] * coord[2]) << endl; coord = FFDBox[iFFDBox]->GetCoordCornerPoints(0); - output_file << coord[0] << "\t" << sqrt(coord[1]*coord[1]+coord[2]*coord[2]) << endl; + output_file << coord[0] << "\t" << sqrt(coord[1] * coord[1] + coord[2] * coord[2]) << endl; coord = FFDBox[iFFDBox]->GetCoordCornerPoints(1); - output_file << coord[0] << "\t" << sqrt(coord[1]*coord[1]+coord[2]*coord[2]) << endl; + output_file << coord[0] << "\t" << sqrt(coord[1] * coord[1] + coord[2] * coord[2]) << endl; coord = FFDBox[iFFDBox]->GetCoordCornerPoints(5); - output_file << coord[0] << "\t" << sqrt(coord[1]*coord[1]+coord[2]*coord[2]) << endl; - } - else { - for (iCornerPoints = 0; iCornerPoints < FFDBox[iFFDBox]->GetnCornerPoints()/SU2_TYPE::Int(2); iCornerPoints++) { + output_file << coord[0] << "\t" << sqrt(coord[1] * coord[1] + coord[2] * coord[2]) << endl; + } else { + for (iCornerPoints = 0; iCornerPoints < FFDBox[iFFDBox]->GetnCornerPoints() / SU2_TYPE::Int(2); + iCornerPoints++) { coord = FFDBox[iFFDBox]->GetCoordCornerPoints(iCornerPoints); output_file << coord[0] << "\t" << coord[1] << endl; } } - } - else { + } else { output_file << "FFD_CORNER_POINTS= " << FFDBox[iFFDBox]->GetnCornerPoints() << endl; for (iCornerPoints = 0; iCornerPoints < FFDBox[iFFDBox]->GetnCornerPoints(); iCornerPoints++) { coord = FFDBox[iFFDBox]->GetCoordCornerPoints(iCornerPoints); @@ -4798,14 +4981,14 @@ void CSurfaceMovement::WriteFFDInfo(CSurfaceMovement** surface_movement, CGeomet if (FFDBox[iFFDBox]->GetnControlPoints() == 0) { output_file << "FFD_CONTROL_POINTS= 0" << endl; - } - else { + } else { output_file << "FFD_CONTROL_POINTS= " << FFDBox[iFFDBox]->GetnControlPoints() << endl; for (iOrder = 0; iOrder < FFDBox[iFFDBox]->GetlOrder(); iOrder++) for (jOrder = 0; jOrder < FFDBox[iFFDBox]->GetmOrder(); jOrder++) for (kOrder = 0; kOrder < FFDBox[iFFDBox]->GetnOrder(); kOrder++) { coord = FFDBox[iFFDBox]->GetCoordControlPoints(iOrder, jOrder, kOrder); - output_file << iOrder << "\t" << jOrder << "\t" << kOrder << "\t" << coord[0] << "\t" << coord[1] << "\t" << coord[2] << endl; + output_file << iOrder << "\t" << jOrder << "\t" << kOrder << "\t" << coord[0] << "\t" << coord[1] << "\t" + << coord[2] << endl; } } @@ -4813,39 +4996,33 @@ void CSurfaceMovement::WriteFFDInfo(CSurfaceMovement** surface_movement, CGeomet if (FFDBox[iFFDBox]->GetnControlPoints() == 0) { output_file << "FFD_SURFACE_POINTS= 0" << endl; - } - else { + } else { output_file << "FFD_SURFACE_POINTS= " << GlobalTag[iFFDBox].size() << endl; for (iSurfacePoints = 0; iSurfacePoints < GlobalTag[iFFDBox].size(); iSurfacePoints++) { - output_file << scientific << GlobalTag[iFFDBox][iSurfacePoints] << "\t" << GlobalPoint[iFFDBox][iSurfacePoints] - << "\t" << GlobalCoordX[iFFDBox][iSurfacePoints] << "\t" << GlobalCoordY[iFFDBox][iSurfacePoints] - << "\t" << GlobalCoordZ[iFFDBox][iSurfacePoints] << endl; + output_file << scientific << GlobalTag[iFFDBox][iSurfacePoints] << "\t" + << GlobalPoint[iFFDBox][iSurfacePoints] << "\t" << GlobalCoordX[iFFDBox][iSurfacePoints] << "\t" + << GlobalCoordY[iFFDBox][iSurfacePoints] << "\t" << GlobalCoordZ[iFFDBox][iSurfacePoints] << endl; } - } - } output_file.close(); - } } -unsigned long CSurfaceMovement::calculateJacobianDeterminant(CGeometry *geometry, CConfig *config, CFreeFormDefBox *FFDBox) const { - +unsigned long CSurfaceMovement::calculateJacobianDeterminant(CGeometry* geometry, CConfig* config, + CFreeFormDefBox* FFDBox) const { unsigned long iSurfacePoints; unsigned short iMarker; unsigned long negative_determinants = 0; /*--- Loop over the surface points ---*/ for (iSurfacePoints = 0; iSurfacePoints < FFDBox->GetnSurfacePoint(); iSurfacePoints++) { - /*--- Get the marker of the surface point ---*/ iMarker = FFDBox->Get_MarkerIndex(iSurfacePoints); if (config->GetMarker_All_DV(iMarker) == YES) { - const auto ParamCoord = FFDBox->Get_ParametricCoord(iSurfacePoints); /*--- Calculate partial derivatives ---*/ @@ -4853,32 +5030,33 @@ unsigned long CSurfaceMovement::calculateJacobianDeterminant(CGeometry *geometry su2double Ba, Bb, Bc, Ba_der, Bb_der, Bc_der; su2double determinant, d_du[3] = {0.0}, d_dv[3] = {0.0}, d_dw[3] = {0.0}; - for (iDegree = 0; iDegree <= FFDBox->lDegree; iDegree++){ + for (iDegree = 0; iDegree <= FFDBox->lDegree; iDegree++) { Ba = FFDBox->BlendingFunction[0]->GetBasis(iDegree, ParamCoord[0]); Ba_der = FFDBox->BlendingFunction[0]->GetDerivative(iDegree, ParamCoord[0], 1); - for (jDegree = 0; jDegree <= FFDBox->mDegree; jDegree++){ + for (jDegree = 0; jDegree <= FFDBox->mDegree; jDegree++) { Bb = FFDBox->BlendingFunction[1]->GetBasis(jDegree, ParamCoord[1]); Bb_der = FFDBox->BlendingFunction[1]->GetDerivative(jDegree, ParamCoord[1], 1); - for (kDegree = 0; kDegree <= FFDBox->nDegree; kDegree++){ - + for (kDegree = 0; kDegree <= FFDBox->nDegree; kDegree++) { Bc = FFDBox->BlendingFunction[2]->GetBasis(kDegree, ParamCoord[2]); Bc_der = FFDBox->BlendingFunction[2]->GetDerivative(kDegree, ParamCoord[2], 1); - for (int i=0; i<3; ++i) { - d_du[i] += Ba_der*Bb*Bc*FFDBox->Coord_Control_Points[iDegree][jDegree][kDegree][i]; - d_dv[i] += Ba*Bb_der*Bc*FFDBox->Coord_Control_Points[iDegree][jDegree][kDegree][i]; - d_dw[i] += Ba*Bb*Bc_der*FFDBox->Coord_Control_Points[iDegree][jDegree][kDegree][i]; + for (int i = 0; i < 3; ++i) { + d_du[i] += Ba_der * Bb * Bc * FFDBox->Coord_Control_Points[iDegree][jDegree][kDegree][i]; + d_dv[i] += Ba * Bb_der * Bc * FFDBox->Coord_Control_Points[iDegree][jDegree][kDegree][i]; + d_dw[i] += Ba * Bb * Bc_der * FFDBox->Coord_Control_Points[iDegree][jDegree][kDegree][i]; } } } } /*--- Calculate determinant ---*/ - determinant = d_du[0]*(d_dv[1]*d_dw[2] - d_dv[2]*d_dw[1]) - d_dv[0]*(d_du[1]*d_dw[2] - d_du[2]*d_dw[1]) + d_dw[0]*(d_du[1]*d_dv[2] - d_du[2]*d_dv[1]); + determinant = d_du[0] * (d_dv[1] * d_dw[2] - d_dv[2] * d_dw[1]) - + d_dv[0] * (d_du[1] * d_dw[2] - d_du[2] * d_dw[1]) + + d_dw[0] * (d_du[1] * d_dv[2] - d_du[2] * d_dv[1]); - if (determinant < 0){ + if (determinant < 0) { negative_determinants++; } } diff --git a/Common/src/grid_movement/CVolumetricMovement.cpp b/Common/src/grid_movement/CVolumetricMovement.cpp index ef7e3d423af..b1c9ff10f7d 100644 --- a/Common/src/grid_movement/CVolumetricMovement.cpp +++ b/Common/src/grid_movement/CVolumetricMovement.cpp @@ -25,42 +25,38 @@ * License along with SU2. If not, see . */ - #include "../../include/grid_movement/CVolumetricMovement.hpp" #include "../../include/adt/CADTPointsOnlyClass.hpp" #include "../../include/toolboxes/geometry_toolbox.hpp" -CVolumetricMovement::CVolumetricMovement(void) : CGridMovement(), System(LINEAR_SOLVER_MODE::MESH_DEFORM) { - -} - -CVolumetricMovement::CVolumetricMovement(CGeometry *geometry, CConfig *config) : CGridMovement(), System(LINEAR_SOLVER_MODE::MESH_DEFORM) { +CVolumetricMovement::CVolumetricMovement(void) : CGridMovement(), System(LINEAR_SOLVER_MODE::MESH_DEFORM) {} +CVolumetricMovement::CVolumetricMovement(CGeometry* geometry, CConfig* config) + : CGridMovement(), System(LINEAR_SOLVER_MODE::MESH_DEFORM) { size = SU2_MPI::GetSize(); rank = SU2_MPI::GetRank(); /*--- Initialize the number of spatial dimensions, length of the state vector (same as spatial dimensions for grid deformation), and grid nodes. ---*/ - nDim = geometry->GetnDim(); - nVar = geometry->GetnDim(); + nDim = geometry->GetnDim(); + nVar = geometry->GetnDim(); nPoint = geometry->GetnPoint(); nPointDomain = geometry->GetnPointDomain(); nIterMesh = 0; /*--- Initialize matrix, solution, and r.h.s. structures for the linear solver. ---*/ - if (config->GetVolumetric_Movement() || config->GetSmoothGradient()){ + if (config->GetVolumetric_Movement() || config->GetSmoothGradient()) { LinSysSol.Initialize(nPoint, nPointDomain, nVar, 0.0); LinSysRes.Initialize(nPoint, nPointDomain, nVar, 0.0); StiffMatrix.Initialize(nPoint, nPointDomain, nVar, nVar, false, geometry, config); } } -CVolumetricMovement::~CVolumetricMovement(void) { } - -void CVolumetricMovement::UpdateGridCoord(CGeometry *geometry, CConfig *config) { +CVolumetricMovement::~CVolumetricMovement(void) {} +void CVolumetricMovement::UpdateGridCoord(CGeometry* geometry, CConfig* config) { unsigned short iDim; unsigned long iPoint, total_index; su2double new_coord; @@ -70,9 +66,9 @@ void CVolumetricMovement::UpdateGridCoord(CGeometry *geometry, CConfig *config) for (iPoint = 0; iPoint < nPoint; iPoint++) for (iDim = 0; iDim < nDim; iDim++) { - total_index = iPoint*nDim + iDim; - new_coord = geometry->nodes->GetCoord(iPoint, iDim)+LinSysSol[total_index]; - if (fabs(new_coord) < EPS*EPS) new_coord = 0.0; + total_index = iPoint * nDim + iDim; + new_coord = geometry->nodes->GetCoord(iPoint, iDim) + LinSysSol[total_index]; + if (fabs(new_coord) < EPS * EPS) new_coord = 0.0; geometry->nodes->SetCoord(iPoint, iDim, new_coord); } @@ -82,52 +78,46 @@ void CVolumetricMovement::UpdateGridCoord(CGeometry *geometry, CConfig *config) geometry->InitiateComms(geometry, config, COORDINATES); geometry->CompleteComms(geometry, config, COORDINATES); - } -void CVolumetricMovement::UpdateDualGrid(CGeometry *geometry, CConfig *config) { - +void CVolumetricMovement::UpdateDualGrid(CGeometry* geometry, CConfig* config) { /*--- After moving all nodes, update the dual mesh. Recompute the edges and dual mesh control volumes in the domain and on the boundaries. ---*/ geometry->SetControlVolume(config, UPDATE); geometry->SetBoundControlVolume(config, UPDATE); geometry->SetMaxLength(config); - } -void CVolumetricMovement::UpdateMultiGrid(CGeometry **geometry, CConfig *config) { - +void CVolumetricMovement::UpdateMultiGrid(CGeometry** geometry, CConfig* config) { unsigned short iMGfine, iMGlevel, nMGlevel = config->GetnMGLevels(); /*--- Update the multigrid structure after moving the finest grid, including computing the grid velocities on the coarser levels. ---*/ for (iMGlevel = 1; iMGlevel <= nMGlevel; iMGlevel++) { - iMGfine = iMGlevel-1; + iMGfine = iMGlevel - 1; geometry[iMGlevel]->SetControlVolume(geometry[iMGfine], UPDATE); - geometry[iMGlevel]->SetBoundControlVolume(geometry[iMGfine],UPDATE); + geometry[iMGlevel]->SetBoundControlVolume(geometry[iMGfine], UPDATE); geometry[iMGlevel]->SetCoord(geometry[iMGfine]); - if (config->GetGrid_Movement()) - geometry[iMGlevel]->SetRestricted_GridVelocity(geometry[iMGfine]); + if (config->GetGrid_Movement()) geometry[iMGlevel]->SetRestricted_GridVelocity(geometry[iMGfine]); } - } -void CVolumetricMovement::SetVolume_Deformation(CGeometry *geometry, CConfig *config, bool UpdateGeo, bool Derivative, bool ForwardProjectionDerivative) { - +void CVolumetricMovement::SetVolume_Deformation(CGeometry* geometry, CConfig* config, bool UpdateGeo, bool Derivative, + bool ForwardProjectionDerivative) { unsigned long Tot_Iter = 0; su2double MinVolume, MaxVolume; /*--- Retrieve number or iterations, tol, output, etc. from config ---*/ - auto Screen_Output = config->GetDeform_Output(); + auto Screen_Output = config->GetDeform_Output(); auto Nonlinear_Iter = config->GetGridDef_Nonlinear_Iter(); /*--- Disable the screen output if we're running SU2_CFD ---*/ if (config->GetKind_SU2() == SU2_COMPONENT::SU2_CFD && !Derivative) Screen_Output = false; - if (config->GetSmoothGradient()) Screen_Output=true; + if (config->GetSmoothGradient()) Screen_Output = true; /*--- Set the number of nonlinear iterations to 1 if Derivative computation is enabled ---*/ @@ -138,7 +128,6 @@ void CVolumetricMovement::SetVolume_Deformation(CGeometry *geometry, CConfig *co particular, the linear elasticity equations hold only for small deformations. ---*/ for (auto iNonlinear_Iter = 0ul; iNonlinear_Iter < Nonlinear_Iter; iNonlinear_Iter++) { - /*--- Initialize vector and sparse matrix ---*/ LinSysSol.SetValZero(); @@ -163,7 +152,9 @@ void CVolumetricMovement::SetVolume_Deformation(CGeometry *geometry, CConfig *co /*--- Set the boundary derivatives (overrides the actual displacements) ---*/ - if (Derivative) { SetBoundaryDerivatives(geometry, config, ForwardProjectionDerivative); } + if (Derivative) { + SetBoundaryDerivatives(geometry, config, ForwardProjectionDerivative); + } /*--- Communicate any prescribed boundary displacements via MPI, so that all nodes have the same solution and r.h.s. entries @@ -183,12 +174,11 @@ void CVolumetricMovement::SetVolume_Deformation(CGeometry *geometry, CConfig *co /*--- If we want no derivatives or the direct derivatives, we solve the system using the * normal matrix vector product and preconditioner. For the mesh sensitivities using * the discrete adjoint method we solve the system using the transposed matrix. ---*/ - if (!Derivative || ((config->GetKind_SU2() == SU2_COMPONENT::SU2_CFD) && Derivative) || (config->GetSmoothGradient() && ForwardProjectionDerivative)) { - + if (!Derivative || ((config->GetKind_SU2() == SU2_COMPONENT::SU2_CFD) && Derivative) || + (config->GetSmoothGradient() && ForwardProjectionDerivative)) { Tot_Iter = System.Solve(StiffMatrix, LinSysRes, LinSysSol, geometry, config); } else if (Derivative && (config->GetKind_SU2() == SU2_COMPONENT::SU2_DOT)) { - Tot_Iter = System.Solve_b(StiffMatrix, LinSysRes, LinSysSol, geometry, config); } su2double Residual = System.GetResidual(); @@ -196,9 +186,14 @@ void CVolumetricMovement::SetVolume_Deformation(CGeometry *geometry, CConfig *co /*--- Update the grid coordinates and cell volumes using the solution of the linear system (usol contains the x, y, z displacements). ---*/ - if (!Derivative) { UpdateGridCoord(geometry, config); } - else { UpdateGridCoord_Derivatives(geometry, config, ForwardProjectionDerivative); } - if (UpdateGeo) { UpdateDualGrid(geometry, config); } + if (!Derivative) { + UpdateGridCoord(geometry, config); + } else { + UpdateGridCoord_Derivatives(geometry, config, ForwardProjectionDerivative); + } + if (UpdateGeo) { + UpdateDualGrid(geometry, config); + } if (!Derivative) { /*--- Check for failed deformation (negative volumes). ---*/ @@ -215,37 +210,37 @@ void CVolumetricMovement::SetVolume_Deformation(CGeometry *geometry, CConfig *co Set_nIterMesh(Tot_Iter); if (rank == MASTER_NODE && Screen_Output) { - cout << "Non-linear iter.: " << iNonlinear_Iter+1 << "/" << Nonlinear_Iter << ". Linear iter.: " << Tot_Iter << ". "; - if (nDim == 2) cout << "Min. area: " << MinVolume << ". Error: " << Residual << "." << endl; - else cout << "Min. volume: " << MinVolume << ". Error: " << Residual << "." << endl; + cout << "Non-linear iter.: " << iNonlinear_Iter + 1 << "/" << Nonlinear_Iter << ". Linear iter.: " << Tot_Iter + << ". "; + if (nDim == 2) + cout << "Min. area: " << MinVolume << ". Error: " << Residual << "." << endl; + else + cout << "Min. volume: " << MinVolume << ". Error: " << Residual << "." << endl; } - } - } -void CVolumetricMovement::ComputeDeforming_Element_Volume(CGeometry *geometry, su2double &MinVolume, su2double &MaxVolume, bool Screen_Output) { - +void CVolumetricMovement::ComputeDeforming_Element_Volume(CGeometry* geometry, su2double& MinVolume, + su2double& MaxVolume, bool Screen_Output) { unsigned long iElem, ElemCounter = 0, PointCorners[8]; su2double Volume = 0.0, CoordCorners[8][3]; unsigned short nNodes = 0, iNodes, iDim; bool RightVol = true; - if (rank == MASTER_NODE && Screen_Output) - cout << "Computing volumes of the grid elements." << endl; + if (rank == MASTER_NODE && Screen_Output) cout << "Computing volumes of the grid elements." << endl; - MaxVolume = -1E22; MinVolume = 1E22; + MaxVolume = -1E22; + MinVolume = 1E22; /*--- Load up each triangle and tetrahedron to check for negative volumes. ---*/ for (iElem = 0; iElem < geometry->GetnElem(); iElem++) { - - if (geometry->elem[iElem]->GetVTK_Type() == TRIANGLE) nNodes = 3; - if (geometry->elem[iElem]->GetVTK_Type() == QUADRILATERAL) nNodes = 4; - if (geometry->elem[iElem]->GetVTK_Type() == TETRAHEDRON) nNodes = 4; - if (geometry->elem[iElem]->GetVTK_Type() == PYRAMID) nNodes = 5; - if (geometry->elem[iElem]->GetVTK_Type() == PRISM) nNodes = 6; - if (geometry->elem[iElem]->GetVTK_Type() == HEXAHEDRON) nNodes = 8; + if (geometry->elem[iElem]->GetVTK_Type() == TRIANGLE) nNodes = 3; + if (geometry->elem[iElem]->GetVTK_Type() == QUADRILATERAL) nNodes = 4; + if (geometry->elem[iElem]->GetVTK_Type() == TETRAHEDRON) nNodes = 4; + if (geometry->elem[iElem]->GetVTK_Type() == PYRAMID) nNodes = 5; + if (geometry->elem[iElem]->GetVTK_Type() == PRISM) nNodes = 6; + if (geometry->elem[iElem]->GetVTK_Type() == HEXAHEDRON) nNodes = 8; for (iNodes = 0; iNodes < nNodes; iNodes++) { PointCorners[iNodes] = geometry->elem[iElem]->GetNode(iNodes); @@ -278,13 +273,15 @@ void CVolumetricMovement::ComputeDeforming_Element_Volume(CGeometry *geometry, s geometry->elem[iElem]->SetVolume(Volume); if (!RightVol) ElemCounter++; - } #ifdef HAVE_MPI - unsigned long ElemCounter_Local = ElemCounter; ElemCounter = 0; - su2double MaxVolume_Local = MaxVolume; MaxVolume = 0.0; - su2double MinVolume_Local = MinVolume; MinVolume = 0.0; + unsigned long ElemCounter_Local = ElemCounter; + ElemCounter = 0; + su2double MaxVolume_Local = MaxVolume; + MaxVolume = 0.0; + su2double MinVolume_Local = MinVolume; + MinVolume = 0.0; SU2_MPI::Allreduce(&ElemCounter_Local, &ElemCounter, 1, MPI_UNSIGNED_LONG, MPI_SUM, SU2_MPI::GetComm()); SU2_MPI::Allreduce(&MaxVolume_Local, &MaxVolume, 1, MPI_DOUBLE, MPI_MAX, SU2_MPI::GetComm()); SU2_MPI::Allreduce(&MinVolume_Local, &MinVolume, 1, MPI_DOUBLE, MPI_MIN, SU2_MPI::GetComm()); @@ -293,22 +290,21 @@ void CVolumetricMovement::ComputeDeforming_Element_Volume(CGeometry *geometry, s /*--- Volume from 0 to 1 ---*/ for (iElem = 0; iElem < geometry->GetnElem(); iElem++) { - Volume = geometry->elem[iElem]->GetVolume()/MaxVolume; + Volume = geometry->elem[iElem]->GetVolume() / MaxVolume; geometry->elem[iElem]->SetVolume(Volume); } if ((ElemCounter != 0) && (rank == MASTER_NODE) && (Screen_Output)) - cout <<"There are " << ElemCounter << " elements with negative volume.\n" << endl; - + cout << "There are " << ElemCounter << " elements with negative volume.\n" << endl; } -void CVolumetricMovement::ComputenNonconvexElements(CGeometry *geometry, bool Screen_Output) { +void CVolumetricMovement::ComputenNonconvexElements(CGeometry* geometry, bool Screen_Output) { unsigned long iElem; unsigned short iDim; unsigned long nNonconvexElements = 0; /*--- Load up each tetrahedron to check for convex properties. ---*/ - if (nDim == 2){ + if (nDim == 2) { for (iElem = 0; iElem < geometry->GetnElem(); iElem++) { su2double minCrossProduct = 1.e6, maxCrossProduct = -1.e6; @@ -325,35 +321,34 @@ void CVolumetricMovement::ComputenNonconvexElements(CGeometry *geometry, bool Sc } /*--- Determine whether element is convex ---*/ - for (iNodes = 0; iNodes < nNodes; iNodes ++) { - + for (iNodes = 0; iNodes < nNodes; iNodes++) { /*--- Calculate minimum and maximum angle between edge vectors adjacent to each node ---*/ su2double edgeVector_i[3], edgeVector_j[3]; - for (iDim = 0; iDim < nDim; iDim ++) { + for (iDim = 0; iDim < nDim; iDim++) { if (iNodes == 0) { - edgeVector_i[iDim] = CoordCorners[nNodes-1][iDim] - CoordCorners[iNodes][iDim]; + edgeVector_i[iDim] = CoordCorners[nNodes - 1][iDim] - CoordCorners[iNodes][iDim]; } else { - edgeVector_i[iDim] = CoordCorners[iNodes-1][iDim] - CoordCorners[iNodes][iDim]; + edgeVector_i[iDim] = CoordCorners[iNodes - 1][iDim] - CoordCorners[iNodes][iDim]; } - if (iNodes == nNodes-1) { + if (iNodes == nNodes - 1) { edgeVector_j[iDim] = CoordCorners[0][iDim] - CoordCorners[iNodes][iDim]; } else { - edgeVector_j[iDim] = CoordCorners[iNodes+1][iDim] - CoordCorners[iNodes][iDim]; + edgeVector_j[iDim] = CoordCorners[iNodes + 1][iDim] - CoordCorners[iNodes][iDim]; } } /*--- Calculate cross product of edge vectors ---*/ su2double crossProduct; - crossProduct = edgeVector_i[1]*edgeVector_j[0] - edgeVector_i[0]*edgeVector_j[1]; + crossProduct = edgeVector_i[1] * edgeVector_j[0] - edgeVector_i[0] * edgeVector_j[1]; if (crossProduct < minCrossProduct) minCrossProduct = crossProduct; if (crossProduct > maxCrossProduct) maxCrossProduct = crossProduct; } /*--- Element is nonconvex if cross product of at least one set of adjacent edges is negative ---*/ - if (minCrossProduct < 0 && maxCrossProduct > 0){ + if (minCrossProduct < 0 && maxCrossProduct > 0) { nNonconvexElements++; } } @@ -361,17 +356,16 @@ void CVolumetricMovement::ComputenNonconvexElements(CGeometry *geometry, bool Sc cout << "\nWARNING: Convexity is not checked for 3D elements (issue #1171).\n" << endl; } - unsigned long nNonconvexElements_Local = nNonconvexElements; nNonconvexElements = 0; + unsigned long nNonconvexElements_Local = nNonconvexElements; + nNonconvexElements = 0; SU2_MPI::Allreduce(&nNonconvexElements_Local, &nNonconvexElements, 1, MPI_UNSIGNED_LONG, MPI_SUM, SU2_MPI::GetComm()); /*--- Set number of nonconvex elements in geometry ---*/ geometry->SetnNonconvexElements(nNonconvexElements); } - - -void CVolumetricMovement::ComputeSolid_Wall_Distance(CGeometry *geometry, CConfig *config, su2double &MinDistance, su2double &MaxDistance) const { - +void CVolumetricMovement::ComputeSolid_Wall_Distance(CGeometry* geometry, CConfig* config, su2double& MinDistance, + su2double& MaxDistance) const { unsigned long nVertex_SolidWall, ii, jj, iVertex, iPoint, pointID; unsigned short iMarker, iDim; su2double dist, MaxDistance_Local, MinDistance_Local; @@ -379,75 +373,69 @@ void CVolumetricMovement::ComputeSolid_Wall_Distance(CGeometry *geometry, CConfi /*--- Initialize min and max distance ---*/ - MaxDistance = -1E22; MinDistance = 1E22; + MaxDistance = -1E22; + MinDistance = 1E22; /*--- Compute the total number of nodes on no-slip boundaries ---*/ nVertex_SolidWall = 0; - for(iMarker=0; iMarkerGetnMarker_All(); ++iMarker) { - if(config->GetSolid_Wall(iMarker)) - nVertex_SolidWall += geometry->GetnVertex(iMarker); + for (iMarker = 0; iMarker < config->GetnMarker_All(); ++iMarker) { + if (config->GetSolid_Wall(iMarker)) nVertex_SolidWall += geometry->GetnVertex(iMarker); } /*--- Allocate the vectors to hold boundary node coordinates and its local ID. ---*/ - vector Coord_bound(nDim*nVertex_SolidWall); + vector Coord_bound(nDim * nVertex_SolidWall); vector PointIDs(nVertex_SolidWall); /*--- Retrieve and store the coordinates of the no-slip boundary nodes and their local point IDs. ---*/ - ii = 0; jj = 0; - for (iMarker=0; iMarkerGetnMarker_All(); ++iMarker) { + ii = 0; + jj = 0; + for (iMarker = 0; iMarker < config->GetnMarker_All(); ++iMarker) { if (config->GetSolid_Wall(iMarker)) { - for (iVertex=0; iVertexGetnVertex(iMarker); ++iVertex) { + for (iVertex = 0; iVertex < geometry->GetnVertex(iMarker); ++iVertex) { iPoint = geometry->vertex[iMarker][iVertex]->GetNode(); PointIDs[jj++] = iPoint; - for (iDim=0; iDimnodes->GetCoord(iPoint, iDim); + for (iDim = 0; iDim < nDim; ++iDim) Coord_bound[ii++] = geometry->nodes->GetCoord(iPoint, iDim); } } } /*--- Build the ADT of the boundary nodes. ---*/ - CADTPointsOnlyClass WallADT(nDim, nVertex_SolidWall, Coord_bound.data(), - PointIDs.data(), true); + CADTPointsOnlyClass WallADT(nDim, nVertex_SolidWall, Coord_bound.data(), PointIDs.data(), true); /*--- Loop over all interior mesh nodes and compute the distances to each of the no-slip boundary nodes. Store the minimum distance to the wall for each interior mesh node. ---*/ - if( WallADT.IsEmpty() ) { - + if (WallADT.IsEmpty()) { /*--- No solid wall boundary nodes in the entire mesh. Set the wall distance to zero for all nodes. ---*/ - for (iPoint=0; iPointGetnPoint(); ++iPoint) - geometry->nodes->SetWall_Distance(iPoint, 0.0); - } - else { - + for (iPoint = 0; iPoint < geometry->GetnPoint(); ++iPoint) geometry->nodes->SetWall_Distance(iPoint, 0.0); + } else { /*--- Solid wall boundary nodes are present. Compute the wall distance for all nodes. ---*/ - for(iPoint=0; iPointGetnPoint(); ++iPoint) { - - WallADT.DetermineNearestNode(geometry->nodes->GetCoord(iPoint), dist, - pointID, rankID); + for (iPoint = 0; iPoint < geometry->GetnPoint(); ++iPoint) { + WallADT.DetermineNearestNode(geometry->nodes->GetCoord(iPoint), dist, pointID, rankID); geometry->nodes->SetWall_Distance(iPoint, dist); MaxDistance = max(MaxDistance, dist); /*--- To discard points on the surface we use > EPS ---*/ - if (sqrt(dist) > EPS) MinDistance = min(MinDistance, dist); - + if (sqrt(dist) > EPS) MinDistance = min(MinDistance, dist); } - MaxDistance_Local = MaxDistance; MaxDistance = 0.0; - MinDistance_Local = MinDistance; MinDistance = 0.0; + MaxDistance_Local = MaxDistance; + MaxDistance = 0.0; + MinDistance_Local = MinDistance; + MinDistance = 0.0; #ifdef HAVE_MPI SU2_MPI::Allreduce(&MaxDistance_Local, &MaxDistance, 1, MPI_DOUBLE, MPI_MAX, SU2_MPI::GetComm()); @@ -456,53 +444,52 @@ void CVolumetricMovement::ComputeSolid_Wall_Distance(CGeometry *geometry, CConfi MaxDistance = MaxDistance_Local; MinDistance = MinDistance_Local; #endif - } - } -su2double CVolumetricMovement::SetFEAMethodContributions_Elem(CGeometry *geometry, CConfig *config) { - +su2double CVolumetricMovement::SetFEAMethodContributions_Elem(CGeometry* geometry, CConfig* config) { unsigned short iVar, iDim, nNodes = 0, iNodes, StiffMatrix_nElem = 0; unsigned long iElem, PointCorners[8]; su2double **StiffMatrix_Elem = nullptr, CoordCorners[8][3]; - su2double MinVolume = 0.0, MaxVolume = 0.0, MinDistance = 0.0, MaxDistance = 0.0, ElemVolume = 0.0, ElemDistance = 0.0; + su2double MinVolume = 0.0, MaxVolume = 0.0, MinDistance = 0.0, MaxDistance = 0.0, ElemVolume = 0.0, + ElemDistance = 0.0; - bool Screen_Output = config->GetDeform_Output(); + bool Screen_Output = config->GetDeform_Output(); /*--- Allocate maximum size (quadrilateral and hexahedron) ---*/ - if (nDim == 2) StiffMatrix_nElem = 8; - else StiffMatrix_nElem = 24; + if (nDim == 2) + StiffMatrix_nElem = 8; + else + StiffMatrix_nElem = 24; - StiffMatrix_Elem = new su2double* [StiffMatrix_nElem]; - for (iVar = 0; iVar < StiffMatrix_nElem; iVar++) - StiffMatrix_Elem[iVar] = new su2double [StiffMatrix_nElem]; + StiffMatrix_Elem = new su2double*[StiffMatrix_nElem]; + for (iVar = 0; iVar < StiffMatrix_nElem; iVar++) StiffMatrix_Elem[iVar] = new su2double[StiffMatrix_nElem]; /*--- Compute min volume in the entire mesh. ---*/ ComputeDeforming_Element_Volume(geometry, MinVolume, MaxVolume, Screen_Output); - if (rank == MASTER_NODE && Screen_Output) cout <<"Min. volume: "<< MinVolume <<", max. volume: "<< MaxVolume <<"." << endl; + if (rank == MASTER_NODE && Screen_Output) + cout << "Min. volume: " << MinVolume << ", max. volume: " << MaxVolume << "." << endl; /*--- Compute the distance to the nearest surface if needed as part of the stiffness calculation.. ---*/ - if ((config->GetDeform_Stiffness_Type() == SOLID_WALL_DISTANCE) || - (config->GetDeform_Limit() < 1E6)) { + if ((config->GetDeform_Stiffness_Type() == SOLID_WALL_DISTANCE) || (config->GetDeform_Limit() < 1E6)) { ComputeSolid_Wall_Distance(geometry, config, MinDistance, MaxDistance); - if (rank == MASTER_NODE && Screen_Output) cout <<"Min. distance: "<< MinDistance <<", max. distance: "<< MaxDistance <<"." << endl; + if (rank == MASTER_NODE && Screen_Output) + cout << "Min. distance: " << MinDistance << ", max. distance: " << MaxDistance << "." << endl; } /*--- Compute contributions from each element by forming the stiffness matrix (FEA) ---*/ for (iElem = 0; iElem < geometry->GetnElem(); iElem++) { - - if (geometry->elem[iElem]->GetVTK_Type() == TRIANGLE) nNodes = 3; + if (geometry->elem[iElem]->GetVTK_Type() == TRIANGLE) nNodes = 3; if (geometry->elem[iElem]->GetVTK_Type() == QUADRILATERAL) nNodes = 4; - if (geometry->elem[iElem]->GetVTK_Type() == TETRAHEDRON) nNodes = 4; - if (geometry->elem[iElem]->GetVTK_Type() == PYRAMID) nNodes = 5; - if (geometry->elem[iElem]->GetVTK_Type() == PRISM) nNodes = 6; - if (geometry->elem[iElem]->GetVTK_Type() == HEXAHEDRON) nNodes = 8; + if (geometry->elem[iElem]->GetVTK_Type() == TETRAHEDRON) nNodes = 4; + if (geometry->elem[iElem]->GetVTK_Type() == PYRAMID) nNodes = 5; + if (geometry->elem[iElem]->GetVTK_Type() == PRISM) nNodes = 6; + if (geometry->elem[iElem]->GetVTK_Type() == HEXAHEDRON) nNodes = 8; for (iNodes = 0; iNodes < nNodes; iNodes++) { PointCorners[iNodes] = geometry->elem[iElem]->GetNode(iNodes); @@ -519,28 +506,29 @@ su2double CVolumetricMovement::SetFEAMethodContributions_Elem(CGeometry *geometr ElemDistance = 0.0; for (iNodes = 0; iNodes < nNodes; iNodes++) ElemDistance += geometry->nodes->GetWall_Distance(PointCorners[iNodes]); - ElemDistance = ElemDistance/(su2double)nNodes; + ElemDistance = ElemDistance / (su2double)nNodes; } - if (nDim == 2) SetFEA_StiffMatrix2D(geometry, config, StiffMatrix_Elem, PointCorners, CoordCorners, nNodes, ElemVolume, ElemDistance); - if (nDim == 3) SetFEA_StiffMatrix3D(geometry, config, StiffMatrix_Elem, PointCorners, CoordCorners, nNodes, ElemVolume, ElemDistance); + if (nDim == 2) + SetFEA_StiffMatrix2D(geometry, config, StiffMatrix_Elem, PointCorners, CoordCorners, nNodes, ElemVolume, + ElemDistance); + if (nDim == 3) + SetFEA_StiffMatrix3D(geometry, config, StiffMatrix_Elem, PointCorners, CoordCorners, nNodes, ElemVolume, + ElemDistance); AddFEA_StiffMatrix(geometry, StiffMatrix_Elem, PointCorners, nNodes); - } /*--- Deallocate memory and exit ---*/ - for (iVar = 0; iVar < StiffMatrix_nElem; iVar++) - delete [] StiffMatrix_Elem[iVar]; - delete [] StiffMatrix_Elem; + for (iVar = 0; iVar < StiffMatrix_nElem; iVar++) delete[] StiffMatrix_Elem[iVar]; + delete[] StiffMatrix_Elem; return MinVolume; - } -su2double CVolumetricMovement::ShapeFunc_Triangle(su2double Xi, su2double Eta, su2double CoordCorners[8][3], su2double DShapeFunction[8][4]) { - +su2double CVolumetricMovement::ShapeFunc_Triangle(su2double Xi, su2double Eta, su2double CoordCorners[8][3], + su2double DShapeFunction[8][4]) { int i, j, k; su2double c0, c1, xsj; su2double xs[3][3], ad[3][3]; @@ -549,13 +537,16 @@ su2double CVolumetricMovement::ShapeFunc_Triangle(su2double Xi, su2double Eta, s DShapeFunction[0][3] = Xi; DShapeFunction[1][3] = Eta; - DShapeFunction[2][3] = 1-Xi-Eta; + DShapeFunction[2][3] = 1 - Xi - Eta; /*--- dN/d xi, dN/d eta ---*/ - DShapeFunction[0][0] = 1.0; DShapeFunction[0][1] = 0.0; - DShapeFunction[1][0] = 0.0; DShapeFunction[1][1] = 1.0; - DShapeFunction[2][0] = -1.0; DShapeFunction[2][1] = -1.0; + DShapeFunction[0][0] = 1.0; + DShapeFunction[0][1] = 0.0; + DShapeFunction[1][0] = 0.0; + DShapeFunction[1][1] = 1.0; + DShapeFunction[2][0] = -1.0; + DShapeFunction[2][1] = -1.0; /*--- Jacobian transformation ---*/ @@ -563,7 +554,7 @@ su2double CVolumetricMovement::ShapeFunc_Triangle(su2double Xi, su2double Eta, s for (j = 0; j < 2; j++) { xs[i][j] = 0.0; for (k = 0; k < 3; k++) { - xs[i][j] = xs[i][j]+CoordCorners[k][j]*DShapeFunction[k][i]; + xs[i][j] = xs[i][j] + CoordCorners[k][j] * DShapeFunction[k][i]; } } } @@ -577,48 +568,51 @@ su2double CVolumetricMovement::ShapeFunc_Triangle(su2double Xi, su2double Eta, s /*--- Determinant of Jacobian ---*/ - xsj = ad[0][0]*ad[1][1]-ad[0][1]*ad[1][0]; + xsj = ad[0][0] * ad[1][1] - ad[0][1] * ad[1][0]; /*--- Jacobian inverse ---*/ for (i = 0; i < 2; i++) { for (j = 0; j < 2; j++) { - xs[i][j] = ad[i][j]/xsj; + xs[i][j] = ad[i][j] / xsj; } } /*--- Derivatives with repect to global coordinates ---*/ for (k = 0; k < 3; k++) { - c0 = xs[0][0]*DShapeFunction[k][0]+xs[0][1]*DShapeFunction[k][1]; // dN/dx - c1 = xs[1][0]*DShapeFunction[k][0]+xs[1][1]*DShapeFunction[k][1]; // dN/dy - DShapeFunction[k][0] = c0; // store dN/dx instead of dN/d xi - DShapeFunction[k][1] = c1; // store dN/dy instead of dN/d eta + c0 = xs[0][0] * DShapeFunction[k][0] + xs[0][1] * DShapeFunction[k][1]; // dN/dx + c1 = xs[1][0] * DShapeFunction[k][0] + xs[1][1] * DShapeFunction[k][1]; // dN/dy + DShapeFunction[k][0] = c0; // store dN/dx instead of dN/d xi + DShapeFunction[k][1] = c1; // store dN/dy instead of dN/d eta } return xsj; - } -su2double CVolumetricMovement::ShapeFunc_Quadrilateral(su2double Xi, su2double Eta, su2double CoordCorners[8][3], su2double DShapeFunction[8][4]) { - +su2double CVolumetricMovement::ShapeFunc_Quadrilateral(su2double Xi, su2double Eta, su2double CoordCorners[8][3], + su2double DShapeFunction[8][4]) { int i, j, k; su2double c0, c1, xsj; su2double xs[3][3], ad[3][3]; /*--- Shape functions ---*/ - DShapeFunction[0][3] = 0.25*(1.0-Xi)*(1.0-Eta); - DShapeFunction[1][3] = 0.25*(1.0+Xi)*(1.0-Eta); - DShapeFunction[2][3] = 0.25*(1.0+Xi)*(1.0+Eta); - DShapeFunction[3][3] = 0.25*(1.0-Xi)*(1.0+Eta); + DShapeFunction[0][3] = 0.25 * (1.0 - Xi) * (1.0 - Eta); + DShapeFunction[1][3] = 0.25 * (1.0 + Xi) * (1.0 - Eta); + DShapeFunction[2][3] = 0.25 * (1.0 + Xi) * (1.0 + Eta); + DShapeFunction[3][3] = 0.25 * (1.0 - Xi) * (1.0 + Eta); /*--- dN/d xi, dN/d eta ---*/ - DShapeFunction[0][0] = -0.25*(1.0-Eta); DShapeFunction[0][1] = -0.25*(1.0-Xi); - DShapeFunction[1][0] = 0.25*(1.0-Eta); DShapeFunction[1][1] = -0.25*(1.0+Xi); - DShapeFunction[2][0] = 0.25*(1.0+Eta); DShapeFunction[2][1] = 0.25*(1.0+Xi); - DShapeFunction[3][0] = -0.25*(1.0+Eta); DShapeFunction[3][1] = 0.25*(1.0-Xi); + DShapeFunction[0][0] = -0.25 * (1.0 - Eta); + DShapeFunction[0][1] = -0.25 * (1.0 - Xi); + DShapeFunction[1][0] = 0.25 * (1.0 - Eta); + DShapeFunction[1][1] = -0.25 * (1.0 + Xi); + DShapeFunction[2][0] = 0.25 * (1.0 + Eta); + DShapeFunction[2][1] = 0.25 * (1.0 + Xi); + DShapeFunction[3][0] = -0.25 * (1.0 + Eta); + DShapeFunction[3][1] = 0.25 * (1.0 - Xi); /*--- Jacobian transformation ---*/ @@ -626,7 +620,7 @@ su2double CVolumetricMovement::ShapeFunc_Quadrilateral(su2double Xi, su2double E for (j = 0; j < 2; j++) { xs[i][j] = 0.0; for (k = 0; k < 4; k++) { - xs[i][j] = xs[i][j]+CoordCorners[k][j]*DShapeFunction[k][i]; + xs[i][j] = xs[i][j] + CoordCorners[k][j] * DShapeFunction[k][i]; } } } @@ -640,31 +634,30 @@ su2double CVolumetricMovement::ShapeFunc_Quadrilateral(su2double Xi, su2double E /*--- Determinant of Jacobian ---*/ - xsj = ad[0][0]*ad[1][1]-ad[0][1]*ad[1][0]; + xsj = ad[0][0] * ad[1][1] - ad[0][1] * ad[1][0]; /*--- Jacobian inverse ---*/ for (i = 0; i < 2; i++) { for (j = 0; j < 2; j++) { - xs[i][j] = ad[i][j]/xsj; + xs[i][j] = ad[i][j] / xsj; } } /*--- Derivatives with repect to global coordinates ---*/ for (k = 0; k < 4; k++) { - c0 = xs[0][0]*DShapeFunction[k][0]+xs[0][1]*DShapeFunction[k][1]; // dN/dx - c1 = xs[1][0]*DShapeFunction[k][0]+xs[1][1]*DShapeFunction[k][1]; // dN/dy - DShapeFunction[k][0] = c0; // store dN/dx instead of dN/d xi - DShapeFunction[k][1] = c1; // store dN/dy instead of dN/d eta + c0 = xs[0][0] * DShapeFunction[k][0] + xs[0][1] * DShapeFunction[k][1]; // dN/dx + c1 = xs[1][0] * DShapeFunction[k][0] + xs[1][1] * DShapeFunction[k][1]; // dN/dy + DShapeFunction[k][0] = c0; // store dN/dx instead of dN/d xi + DShapeFunction[k][1] = c1; // store dN/dy instead of dN/d eta } return xsj; - } -su2double CVolumetricMovement::ShapeFunc_Tetra(su2double Xi, su2double Eta, su2double Zeta, su2double CoordCorners[8][3], su2double DShapeFunction[8][4]) { - +su2double CVolumetricMovement::ShapeFunc_Tetra(su2double Xi, su2double Eta, su2double Zeta, + su2double CoordCorners[8][3], su2double DShapeFunction[8][4]) { int i, j, k; su2double c0, c1, c2, xsj; su2double xs[3][3], ad[3][3]; @@ -678,10 +671,18 @@ su2double CVolumetricMovement::ShapeFunc_Tetra(su2double Xi, su2double Eta, su2d /*--- dN/d xi, dN/d eta, dN/d zeta ---*/ - DShapeFunction[0][0] = 1.0; DShapeFunction[0][1] = 0.0; DShapeFunction[0][2] = 0.0; - DShapeFunction[1][0] = 0.0; DShapeFunction[1][1] = 0.0; DShapeFunction[1][2] = 1.0; - DShapeFunction[2][0] = -1.0; DShapeFunction[2][1] = -1.0; DShapeFunction[2][2] = -1.0; - DShapeFunction[3][0] = 0.0; DShapeFunction[3][1] = 1.0; DShapeFunction[3][2] = 0.0; + DShapeFunction[0][0] = 1.0; + DShapeFunction[0][1] = 0.0; + DShapeFunction[0][2] = 0.0; + DShapeFunction[1][0] = 0.0; + DShapeFunction[1][1] = 0.0; + DShapeFunction[1][2] = 1.0; + DShapeFunction[2][0] = -1.0; + DShapeFunction[2][1] = -1.0; + DShapeFunction[2][2] = -1.0; + DShapeFunction[3][0] = 0.0; + DShapeFunction[3][1] = 1.0; + DShapeFunction[3][2] = 0.0; /*--- Jacobian transformation ---*/ @@ -689,84 +690,83 @@ su2double CVolumetricMovement::ShapeFunc_Tetra(su2double Xi, su2double Eta, su2d for (j = 0; j < 3; j++) { xs[i][j] = 0.0; for (k = 0; k < 4; k++) { - xs[i][j] = xs[i][j]+CoordCorners[k][j]*DShapeFunction[k][i]; + xs[i][j] = xs[i][j] + CoordCorners[k][j] * DShapeFunction[k][i]; } } } /*--- Adjoint to Jacobian ---*/ - ad[0][0] = xs[1][1]*xs[2][2]-xs[1][2]*xs[2][1]; - ad[0][1] = xs[0][2]*xs[2][1]-xs[0][1]*xs[2][2]; - ad[0][2] = xs[0][1]*xs[1][2]-xs[0][2]*xs[1][1]; - ad[1][0] = xs[1][2]*xs[2][0]-xs[1][0]*xs[2][2]; - ad[1][1] = xs[0][0]*xs[2][2]-xs[0][2]*xs[2][0]; - ad[1][2] = xs[0][2]*xs[1][0]-xs[0][0]*xs[1][2]; - ad[2][0] = xs[1][0]*xs[2][1]-xs[1][1]*xs[2][0]; - ad[2][1] = xs[0][1]*xs[2][0]-xs[0][0]*xs[2][1]; - ad[2][2] = xs[0][0]*xs[1][1]-xs[0][1]*xs[1][0]; + ad[0][0] = xs[1][1] * xs[2][2] - xs[1][2] * xs[2][1]; + ad[0][1] = xs[0][2] * xs[2][1] - xs[0][1] * xs[2][2]; + ad[0][2] = xs[0][1] * xs[1][2] - xs[0][2] * xs[1][1]; + ad[1][0] = xs[1][2] * xs[2][0] - xs[1][0] * xs[2][2]; + ad[1][1] = xs[0][0] * xs[2][2] - xs[0][2] * xs[2][0]; + ad[1][2] = xs[0][2] * xs[1][0] - xs[0][0] * xs[1][2]; + ad[2][0] = xs[1][0] * xs[2][1] - xs[1][1] * xs[2][0]; + ad[2][1] = xs[0][1] * xs[2][0] - xs[0][0] * xs[2][1]; + ad[2][2] = xs[0][0] * xs[1][1] - xs[0][1] * xs[1][0]; /*--- Determinant of Jacobian ---*/ - xsj = xs[0][0]*ad[0][0]+xs[0][1]*ad[1][0]+xs[0][2]*ad[2][0]; + xsj = xs[0][0] * ad[0][0] + xs[0][1] * ad[1][0] + xs[0][2] * ad[2][0]; /*--- Jacobian inverse ---*/ for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { - xs[i][j] = ad[i][j]/xsj; + xs[i][j] = ad[i][j] / xsj; } } /*--- Derivatives with repect to global coordinates ---*/ for (k = 0; k < 4; k++) { - c0 = xs[0][0]*DShapeFunction[k][0]+xs[0][1]*DShapeFunction[k][1]+xs[0][2]*DShapeFunction[k][2]; // dN/dx - c1 = xs[1][0]*DShapeFunction[k][0]+xs[1][1]*DShapeFunction[k][1]+xs[1][2]*DShapeFunction[k][2]; // dN/dy - c2 = xs[2][0]*DShapeFunction[k][0]+xs[2][1]*DShapeFunction[k][1]+xs[2][2]*DShapeFunction[k][2]; // dN/dz - DShapeFunction[k][0] = c0; // store dN/dx instead of dN/d xi - DShapeFunction[k][1] = c1; // store dN/dy instead of dN/d eta - DShapeFunction[k][2] = c2; // store dN/dz instead of dN/d zeta + c0 = xs[0][0] * DShapeFunction[k][0] + xs[0][1] * DShapeFunction[k][1] + xs[0][2] * DShapeFunction[k][2]; // dN/dx + c1 = xs[1][0] * DShapeFunction[k][0] + xs[1][1] * DShapeFunction[k][1] + xs[1][2] * DShapeFunction[k][2]; // dN/dy + c2 = xs[2][0] * DShapeFunction[k][0] + xs[2][1] * DShapeFunction[k][1] + xs[2][2] * DShapeFunction[k][2]; // dN/dz + DShapeFunction[k][0] = c0; // store dN/dx instead of dN/d xi + DShapeFunction[k][1] = c1; // store dN/dy instead of dN/d eta + DShapeFunction[k][2] = c2; // store dN/dz instead of dN/d zeta } return xsj; - } -su2double CVolumetricMovement::ShapeFunc_Pyram(su2double Xi, su2double Eta, su2double Zeta, su2double CoordCorners[8][3], su2double DShapeFunction[8][4]) { - +su2double CVolumetricMovement::ShapeFunc_Pyram(su2double Xi, su2double Eta, su2double Zeta, + su2double CoordCorners[8][3], su2double DShapeFunction[8][4]) { int i, j, k; su2double c0, c1, c2, xsj; su2double xs[3][3], ad[3][3]; /*--- Shape functions ---*/ - DShapeFunction[0][3] = 0.25*(-Xi+Eta+Zeta-1.0)*(-Xi-Eta+Zeta-1.0)/(1.0-Zeta); - DShapeFunction[1][3] = 0.25*(-Xi-Eta+Zeta-1.0)*( Xi-Eta+Zeta-1.0)/(1.0-Zeta); - DShapeFunction[2][3] = 0.25*( Xi+Eta+Zeta-1.0)*( Xi-Eta+Zeta-1.0)/(1.0-Zeta); - DShapeFunction[3][3] = 0.25*( Xi+Eta+Zeta-1.0)*(-Xi+Eta+Zeta-1.0)/(1.0-Zeta); + DShapeFunction[0][3] = 0.25 * (-Xi + Eta + Zeta - 1.0) * (-Xi - Eta + Zeta - 1.0) / (1.0 - Zeta); + DShapeFunction[1][3] = 0.25 * (-Xi - Eta + Zeta - 1.0) * (Xi - Eta + Zeta - 1.0) / (1.0 - Zeta); + DShapeFunction[2][3] = 0.25 * (Xi + Eta + Zeta - 1.0) * (Xi - Eta + Zeta - 1.0) / (1.0 - Zeta); + DShapeFunction[3][3] = 0.25 * (Xi + Eta + Zeta - 1.0) * (-Xi + Eta + Zeta - 1.0) / (1.0 - Zeta); DShapeFunction[4][3] = Zeta; /*--- dN/d xi ---*/ - DShapeFunction[0][0] = 0.5*(Zeta-Xi-1.0)/(Zeta-1.0); - DShapeFunction[1][0] = 0.5*Xi/(Zeta-1.0); - DShapeFunction[2][0] = 0.5*(1.0-Zeta-Xi)/(Zeta-1.0); + DShapeFunction[0][0] = 0.5 * (Zeta - Xi - 1.0) / (Zeta - 1.0); + DShapeFunction[1][0] = 0.5 * Xi / (Zeta - 1.0); + DShapeFunction[2][0] = 0.5 * (1.0 - Zeta - Xi) / (Zeta - 1.0); DShapeFunction[3][0] = DShapeFunction[1][0]; DShapeFunction[4][0] = 0.0; /*--- dN/d eta ---*/ - DShapeFunction[0][1] = 0.5*Eta/(Zeta-1.0); - DShapeFunction[1][1] = 0.5*(Zeta-Eta-1.0)/(Zeta-1.0); + DShapeFunction[0][1] = 0.5 * Eta / (Zeta - 1.0); + DShapeFunction[1][1] = 0.5 * (Zeta - Eta - 1.0) / (Zeta - 1.0); DShapeFunction[2][1] = DShapeFunction[0][1]; - DShapeFunction[3][1] = 0.5*(1.0-Zeta-Eta)/(Zeta-1.0); + DShapeFunction[3][1] = 0.5 * (1.0 - Zeta - Eta) / (Zeta - 1.0); DShapeFunction[4][1] = 0.0; /*--- dN/d zeta ---*/ - DShapeFunction[0][2] = 0.25*(-1.0 + 2.0*Zeta - Zeta*Zeta - Eta*Eta + Xi*Xi)/((1.0-Zeta)*(1.0-Zeta)); - DShapeFunction[1][2] = 0.25*(-1.0 + 2.0*Zeta - Zeta*Zeta + Eta*Eta - Xi*Xi)/((1.0-Zeta)*(1.0-Zeta)); + DShapeFunction[0][2] = 0.25 * (-1.0 + 2.0 * Zeta - Zeta * Zeta - Eta * Eta + Xi * Xi) / ((1.0 - Zeta) * (1.0 - Zeta)); + DShapeFunction[1][2] = 0.25 * (-1.0 + 2.0 * Zeta - Zeta * Zeta + Eta * Eta - Xi * Xi) / ((1.0 - Zeta) * (1.0 - Zeta)); DShapeFunction[2][2] = DShapeFunction[0][2]; DShapeFunction[3][2] = DShapeFunction[1][2]; DShapeFunction[4][2] = 1.0; @@ -777,73 +777,84 @@ su2double CVolumetricMovement::ShapeFunc_Pyram(su2double Xi, su2double Eta, su2d for (j = 0; j < 3; j++) { xs[i][j] = 0.0; for (k = 0; k < 5; k++) { - xs[i][j] = xs[i][j]+CoordCorners[k][j]*DShapeFunction[k][i]; + xs[i][j] = xs[i][j] + CoordCorners[k][j] * DShapeFunction[k][i]; } } } /*--- Adjoint to Jacobian ---*/ - ad[0][0] = xs[1][1]*xs[2][2]-xs[1][2]*xs[2][1]; - ad[0][1] = xs[0][2]*xs[2][1]-xs[0][1]*xs[2][2]; - ad[0][2] = xs[0][1]*xs[1][2]-xs[0][2]*xs[1][1]; - ad[1][0] = xs[1][2]*xs[2][0]-xs[1][0]*xs[2][2]; - ad[1][1] = xs[0][0]*xs[2][2]-xs[0][2]*xs[2][0]; - ad[1][2] = xs[0][2]*xs[1][0]-xs[0][0]*xs[1][2]; - ad[2][0] = xs[1][0]*xs[2][1]-xs[1][1]*xs[2][0]; - ad[2][1] = xs[0][1]*xs[2][0]-xs[0][0]*xs[2][1]; - ad[2][2] = xs[0][0]*xs[1][1]-xs[0][1]*xs[1][0]; + ad[0][0] = xs[1][1] * xs[2][2] - xs[1][2] * xs[2][1]; + ad[0][1] = xs[0][2] * xs[2][1] - xs[0][1] * xs[2][2]; + ad[0][2] = xs[0][1] * xs[1][2] - xs[0][2] * xs[1][1]; + ad[1][0] = xs[1][2] * xs[2][0] - xs[1][0] * xs[2][2]; + ad[1][1] = xs[0][0] * xs[2][2] - xs[0][2] * xs[2][0]; + ad[1][2] = xs[0][2] * xs[1][0] - xs[0][0] * xs[1][2]; + ad[2][0] = xs[1][0] * xs[2][1] - xs[1][1] * xs[2][0]; + ad[2][1] = xs[0][1] * xs[2][0] - xs[0][0] * xs[2][1]; + ad[2][2] = xs[0][0] * xs[1][1] - xs[0][1] * xs[1][0]; /*--- Determinant of Jacobian ---*/ - xsj = xs[0][0]*ad[0][0]+xs[0][1]*ad[1][0]+xs[0][2]*ad[2][0]; + xsj = xs[0][0] * ad[0][0] + xs[0][1] * ad[1][0] + xs[0][2] * ad[2][0]; /*--- Jacobian inverse ---*/ for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { - xs[i][j] = ad[i][j]/xsj; + xs[i][j] = ad[i][j] / xsj; } } /*--- Derivatives with repect to global coordinates ---*/ for (k = 0; k < 5; k++) { - c0 = xs[0][0]*DShapeFunction[k][0]+xs[0][1]*DShapeFunction[k][1]+xs[0][2]*DShapeFunction[k][2]; // dN/dx - c1 = xs[1][0]*DShapeFunction[k][0]+xs[1][1]*DShapeFunction[k][1]+xs[1][2]*DShapeFunction[k][2]; // dN/dy - c2 = xs[2][0]*DShapeFunction[k][0]+xs[2][1]*DShapeFunction[k][1]+xs[2][2]*DShapeFunction[k][2]; // dN/dz - DShapeFunction[k][0] = c0; // store dN/dx instead of dN/d xi - DShapeFunction[k][1] = c1; // store dN/dy instead of dN/d eta - DShapeFunction[k][2] = c2; // store dN/dz instead of dN/d zeta + c0 = xs[0][0] * DShapeFunction[k][0] + xs[0][1] * DShapeFunction[k][1] + xs[0][2] * DShapeFunction[k][2]; // dN/dx + c1 = xs[1][0] * DShapeFunction[k][0] + xs[1][1] * DShapeFunction[k][1] + xs[1][2] * DShapeFunction[k][2]; // dN/dy + c2 = xs[2][0] * DShapeFunction[k][0] + xs[2][1] * DShapeFunction[k][1] + xs[2][2] * DShapeFunction[k][2]; // dN/dz + DShapeFunction[k][0] = c0; // store dN/dx instead of dN/d xi + DShapeFunction[k][1] = c1; // store dN/dy instead of dN/d eta + DShapeFunction[k][2] = c2; // store dN/dz instead of dN/d zeta } return xsj; - } -su2double CVolumetricMovement::ShapeFunc_Prism(su2double Xi, su2double Eta, su2double Zeta, su2double CoordCorners[8][3], su2double DShapeFunction[8][4]) { - +su2double CVolumetricMovement::ShapeFunc_Prism(su2double Xi, su2double Eta, su2double Zeta, + su2double CoordCorners[8][3], su2double DShapeFunction[8][4]) { int i, j, k; su2double c0, c1, c2, xsj; su2double xs[3][3], ad[3][3]; /*--- Shape functions ---*/ - DShapeFunction[0][3] = 0.5*Eta*(1.0-Xi); - DShapeFunction[1][3] = 0.5*Zeta*(1.0-Xi); - DShapeFunction[2][3] = 0.5*(1.0-Eta-Zeta)*(1.0-Xi); - DShapeFunction[3][3] = 0.5*Eta*(Xi+1.0); - DShapeFunction[4][3] = 0.5*Zeta*(Xi+1.0); - DShapeFunction[5][3] = 0.5*(1.0-Eta-Zeta)*(Xi+1.0); + DShapeFunction[0][3] = 0.5 * Eta * (1.0 - Xi); + DShapeFunction[1][3] = 0.5 * Zeta * (1.0 - Xi); + DShapeFunction[2][3] = 0.5 * (1.0 - Eta - Zeta) * (1.0 - Xi); + DShapeFunction[3][3] = 0.5 * Eta * (Xi + 1.0); + DShapeFunction[4][3] = 0.5 * Zeta * (Xi + 1.0); + DShapeFunction[5][3] = 0.5 * (1.0 - Eta - Zeta) * (Xi + 1.0); /*--- dN/d Xi, dN/d Eta, dN/d Zeta ---*/ - DShapeFunction[0][0] = -0.5*Eta; DShapeFunction[0][1] = 0.5*(1.0-Xi); DShapeFunction[0][2] = 0.0; - DShapeFunction[1][0] = -0.5*Zeta; DShapeFunction[1][1] = 0.0; DShapeFunction[1][2] = 0.5*(1.0-Xi); - DShapeFunction[2][0] = -0.5*(1.0-Eta-Zeta); DShapeFunction[2][1] = -0.5*(1.0-Xi); DShapeFunction[2][2] = -0.5*(1.0-Xi); - DShapeFunction[3][0] = 0.5*Eta; DShapeFunction[3][1] = 0.5*(Xi+1.0); DShapeFunction[3][2] = 0.0; - DShapeFunction[4][0] = 0.5*Zeta; DShapeFunction[4][1] = 0.0; DShapeFunction[4][2] = 0.5*(Xi+1.0); - DShapeFunction[5][0] = 0.5*(1.0-Eta-Zeta); DShapeFunction[5][1] = -0.5*(Xi+1.0); DShapeFunction[5][2] = -0.5*(Xi+1.0); + DShapeFunction[0][0] = -0.5 * Eta; + DShapeFunction[0][1] = 0.5 * (1.0 - Xi); + DShapeFunction[0][2] = 0.0; + DShapeFunction[1][0] = -0.5 * Zeta; + DShapeFunction[1][1] = 0.0; + DShapeFunction[1][2] = 0.5 * (1.0 - Xi); + DShapeFunction[2][0] = -0.5 * (1.0 - Eta - Zeta); + DShapeFunction[2][1] = -0.5 * (1.0 - Xi); + DShapeFunction[2][2] = -0.5 * (1.0 - Xi); + DShapeFunction[3][0] = 0.5 * Eta; + DShapeFunction[3][1] = 0.5 * (Xi + 1.0); + DShapeFunction[3][2] = 0.0; + DShapeFunction[4][0] = 0.5 * Zeta; + DShapeFunction[4][1] = 0.0; + DShapeFunction[4][2] = 0.5 * (Xi + 1.0); + DShapeFunction[5][0] = 0.5 * (1.0 - Eta - Zeta); + DShapeFunction[5][1] = -0.5 * (Xi + 1.0); + DShapeFunction[5][2] = -0.5 * (Xi + 1.0); /*--- Jacobian transformation ---*/ @@ -851,100 +862,98 @@ su2double CVolumetricMovement::ShapeFunc_Prism(su2double Xi, su2double Eta, su2d for (j = 0; j < 3; j++) { xs[i][j] = 0.0; for (k = 0; k < 6; k++) { - xs[i][j] = xs[i][j]+CoordCorners[k][j]*DShapeFunction[k][i]; + xs[i][j] = xs[i][j] + CoordCorners[k][j] * DShapeFunction[k][i]; } } } /*--- Adjoint to Jacobian ---*/ - ad[0][0] = xs[1][1]*xs[2][2]-xs[1][2]*xs[2][1]; - ad[0][1] = xs[0][2]*xs[2][1]-xs[0][1]*xs[2][2]; - ad[0][2] = xs[0][1]*xs[1][2]-xs[0][2]*xs[1][1]; - ad[1][0] = xs[1][2]*xs[2][0]-xs[1][0]*xs[2][2]; - ad[1][1] = xs[0][0]*xs[2][2]-xs[0][2]*xs[2][0]; - ad[1][2] = xs[0][2]*xs[1][0]-xs[0][0]*xs[1][2]; - ad[2][0] = xs[1][0]*xs[2][1]-xs[1][1]*xs[2][0]; - ad[2][1] = xs[0][1]*xs[2][0]-xs[0][0]*xs[2][1]; - ad[2][2] = xs[0][0]*xs[1][1]-xs[0][1]*xs[1][0]; + ad[0][0] = xs[1][1] * xs[2][2] - xs[1][2] * xs[2][1]; + ad[0][1] = xs[0][2] * xs[2][1] - xs[0][1] * xs[2][2]; + ad[0][2] = xs[0][1] * xs[1][2] - xs[0][2] * xs[1][1]; + ad[1][0] = xs[1][2] * xs[2][0] - xs[1][0] * xs[2][2]; + ad[1][1] = xs[0][0] * xs[2][2] - xs[0][2] * xs[2][0]; + ad[1][2] = xs[0][2] * xs[1][0] - xs[0][0] * xs[1][2]; + ad[2][0] = xs[1][0] * xs[2][1] - xs[1][1] * xs[2][0]; + ad[2][1] = xs[0][1] * xs[2][0] - xs[0][0] * xs[2][1]; + ad[2][2] = xs[0][0] * xs[1][1] - xs[0][1] * xs[1][0]; /*--- Determinant of Jacobian ---*/ - xsj = xs[0][0]*ad[0][0]+xs[0][1]*ad[1][0]+xs[0][2]*ad[2][0]; + xsj = xs[0][0] * ad[0][0] + xs[0][1] * ad[1][0] + xs[0][2] * ad[2][0]; /*--- Jacobian inverse ---*/ for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { - xs[i][j] = ad[i][j]/xsj; + xs[i][j] = ad[i][j] / xsj; } } /*--- Derivatives with repect to global coordinates ---*/ for (k = 0; k < 6; k++) { - c0 = xs[0][0]*DShapeFunction[k][0]+xs[0][1]*DShapeFunction[k][1]+xs[0][2]*DShapeFunction[k][2]; // dN/dx - c1 = xs[1][0]*DShapeFunction[k][0]+xs[1][1]*DShapeFunction[k][1]+xs[1][2]*DShapeFunction[k][2]; // dN/dy - c2 = xs[2][0]*DShapeFunction[k][0]+xs[2][1]*DShapeFunction[k][1]+xs[2][2]*DShapeFunction[k][2]; // dN/dz - DShapeFunction[k][0] = c0; // store dN/dx instead of dN/d xi - DShapeFunction[k][1] = c1; // store dN/dy instead of dN/d eta - DShapeFunction[k][2] = c2; // store dN/dz instead of dN/d zeta + c0 = xs[0][0] * DShapeFunction[k][0] + xs[0][1] * DShapeFunction[k][1] + xs[0][2] * DShapeFunction[k][2]; // dN/dx + c1 = xs[1][0] * DShapeFunction[k][0] + xs[1][1] * DShapeFunction[k][1] + xs[1][2] * DShapeFunction[k][2]; // dN/dy + c2 = xs[2][0] * DShapeFunction[k][0] + xs[2][1] * DShapeFunction[k][1] + xs[2][2] * DShapeFunction[k][2]; // dN/dz + DShapeFunction[k][0] = c0; // store dN/dx instead of dN/d xi + DShapeFunction[k][1] = c1; // store dN/dy instead of dN/d eta + DShapeFunction[k][2] = c2; // store dN/dz instead of dN/d zeta } return xsj; - } -su2double CVolumetricMovement::ShapeFunc_Hexa(su2double Xi, su2double Eta, su2double Zeta, su2double CoordCorners[8][3], su2double DShapeFunction[8][4]) { - +su2double CVolumetricMovement::ShapeFunc_Hexa(su2double Xi, su2double Eta, su2double Zeta, su2double CoordCorners[8][3], + su2double DShapeFunction[8][4]) { int i, j, k; su2double c0, c1, c2, xsj; su2double xs[3][3], ad[3][3]; - /*--- Shape functions ---*/ - DShapeFunction[0][3] = 0.125*(1.0-Xi)*(1.0-Eta)*(1.0-Zeta); - DShapeFunction[1][3] = 0.125*(1.0+Xi)*(1.0-Eta)*(1.0-Zeta); - DShapeFunction[2][3] = 0.125*(1.0+Xi)*(1.0+Eta)*(1.0-Zeta); - DShapeFunction[3][3] = 0.125*(1.0-Xi)*(1.0+Eta)*(1.0-Zeta); - DShapeFunction[4][3] = 0.125*(1.0-Xi)*(1.0-Eta)*(1.0+Zeta); - DShapeFunction[5][3] = 0.125*(1.0+Xi)*(1.0-Eta)*(1.0+Zeta); - DShapeFunction[6][3] = 0.125*(1.0+Xi)*(1.0+Eta)*(1.0+Zeta); - DShapeFunction[7][3] = 0.125*(1.0-Xi)*(1.0+Eta)*(1.0+Zeta); + DShapeFunction[0][3] = 0.125 * (1.0 - Xi) * (1.0 - Eta) * (1.0 - Zeta); + DShapeFunction[1][3] = 0.125 * (1.0 + Xi) * (1.0 - Eta) * (1.0 - Zeta); + DShapeFunction[2][3] = 0.125 * (1.0 + Xi) * (1.0 + Eta) * (1.0 - Zeta); + DShapeFunction[3][3] = 0.125 * (1.0 - Xi) * (1.0 + Eta) * (1.0 - Zeta); + DShapeFunction[4][3] = 0.125 * (1.0 - Xi) * (1.0 - Eta) * (1.0 + Zeta); + DShapeFunction[5][3] = 0.125 * (1.0 + Xi) * (1.0 - Eta) * (1.0 + Zeta); + DShapeFunction[6][3] = 0.125 * (1.0 + Xi) * (1.0 + Eta) * (1.0 + Zeta); + DShapeFunction[7][3] = 0.125 * (1.0 - Xi) * (1.0 + Eta) * (1.0 + Zeta); /*--- dN/d xi ---*/ - DShapeFunction[0][0] = -0.125*(1.0-Eta)*(1.0-Zeta); - DShapeFunction[1][0] = 0.125*(1.0-Eta)*(1.0-Zeta); - DShapeFunction[2][0] = 0.125*(1.0+Eta)*(1.0-Zeta); - DShapeFunction[3][0] = -0.125*(1.0+Eta)*(1.0-Zeta); - DShapeFunction[4][0] = -0.125*(1.0-Eta)*(1.0+Zeta); - DShapeFunction[5][0] = 0.125*(1.0-Eta)*(1.0+Zeta); - DShapeFunction[6][0] = 0.125*(1.0+Eta)*(1.0+Zeta); - DShapeFunction[7][0] = -0.125*(1.0+Eta)*(1.0+Zeta); + DShapeFunction[0][0] = -0.125 * (1.0 - Eta) * (1.0 - Zeta); + DShapeFunction[1][0] = 0.125 * (1.0 - Eta) * (1.0 - Zeta); + DShapeFunction[2][0] = 0.125 * (1.0 + Eta) * (1.0 - Zeta); + DShapeFunction[3][0] = -0.125 * (1.0 + Eta) * (1.0 - Zeta); + DShapeFunction[4][0] = -0.125 * (1.0 - Eta) * (1.0 + Zeta); + DShapeFunction[5][0] = 0.125 * (1.0 - Eta) * (1.0 + Zeta); + DShapeFunction[6][0] = 0.125 * (1.0 + Eta) * (1.0 + Zeta); + DShapeFunction[7][0] = -0.125 * (1.0 + Eta) * (1.0 + Zeta); /*--- dN/d eta ---*/ - DShapeFunction[0][1] = -0.125*(1.0-Xi)*(1.0-Zeta); - DShapeFunction[1][1] = -0.125*(1.0+Xi)*(1.0-Zeta); - DShapeFunction[2][1] = 0.125*(1.0+Xi)*(1.0-Zeta); - DShapeFunction[3][1] = 0.125*(1.0-Xi)*(1.0-Zeta); - DShapeFunction[4][1] = -0.125*(1.0-Xi)*(1.0+Zeta); - DShapeFunction[5][1] = -0.125*(1.0+Xi)*(1.0+Zeta); - DShapeFunction[6][1] = 0.125*(1.0+Xi)*(1.0+Zeta); - DShapeFunction[7][1] = 0.125*(1.0-Xi)*(1.0+Zeta); + DShapeFunction[0][1] = -0.125 * (1.0 - Xi) * (1.0 - Zeta); + DShapeFunction[1][1] = -0.125 * (1.0 + Xi) * (1.0 - Zeta); + DShapeFunction[2][1] = 0.125 * (1.0 + Xi) * (1.0 - Zeta); + DShapeFunction[3][1] = 0.125 * (1.0 - Xi) * (1.0 - Zeta); + DShapeFunction[4][1] = -0.125 * (1.0 - Xi) * (1.0 + Zeta); + DShapeFunction[5][1] = -0.125 * (1.0 + Xi) * (1.0 + Zeta); + DShapeFunction[6][1] = 0.125 * (1.0 + Xi) * (1.0 + Zeta); + DShapeFunction[7][1] = 0.125 * (1.0 - Xi) * (1.0 + Zeta); /*--- dN/d zeta ---*/ - DShapeFunction[0][2] = -0.125*(1.0-Xi)*(1.0-Eta); - DShapeFunction[1][2] = -0.125*(1.0+Xi)*(1.0-Eta); - DShapeFunction[2][2] = -0.125*(1.0+Xi)*(1.0+Eta); - DShapeFunction[3][2] = -0.125*(1.0-Xi)*(1.0+Eta); - DShapeFunction[4][2] = 0.125*(1.0-Xi)*(1.0-Eta); - DShapeFunction[5][2] = 0.125*(1.0+Xi)*(1.0-Eta); - DShapeFunction[6][2] = 0.125*(1.0+Xi)*(1.0+Eta); - DShapeFunction[7][2] = 0.125*(1.0-Xi)*(1.0+Eta); + DShapeFunction[0][2] = -0.125 * (1.0 - Xi) * (1.0 - Eta); + DShapeFunction[1][2] = -0.125 * (1.0 + Xi) * (1.0 - Eta); + DShapeFunction[2][2] = -0.125 * (1.0 + Xi) * (1.0 + Eta); + DShapeFunction[3][2] = -0.125 * (1.0 - Xi) * (1.0 + Eta); + DShapeFunction[4][2] = 0.125 * (1.0 - Xi) * (1.0 - Eta); + DShapeFunction[5][2] = 0.125 * (1.0 + Xi) * (1.0 - Eta); + DShapeFunction[6][2] = 0.125 * (1.0 + Xi) * (1.0 + Eta); + DShapeFunction[7][2] = 0.125 * (1.0 - Xi) * (1.0 + Eta); /*--- Jacobian transformation ---*/ @@ -952,53 +961,51 @@ su2double CVolumetricMovement::ShapeFunc_Hexa(su2double Xi, su2double Eta, su2do for (j = 0; j < 3; j++) { xs[i][j] = 0.0; for (k = 0; k < 8; k++) { - xs[i][j] = xs[i][j]+CoordCorners[k][j]*DShapeFunction[k][i]; + xs[i][j] = xs[i][j] + CoordCorners[k][j] * DShapeFunction[k][i]; } } } /*--- Adjoint to Jacobian ---*/ - ad[0][0] = xs[1][1]*xs[2][2]-xs[1][2]*xs[2][1]; - ad[0][1] = xs[0][2]*xs[2][1]-xs[0][1]*xs[2][2]; - ad[0][2] = xs[0][1]*xs[1][2]-xs[0][2]*xs[1][1]; - ad[1][0] = xs[1][2]*xs[2][0]-xs[1][0]*xs[2][2]; - ad[1][1] = xs[0][0]*xs[2][2]-xs[0][2]*xs[2][0]; - ad[1][2] = xs[0][2]*xs[1][0]-xs[0][0]*xs[1][2]; - ad[2][0] = xs[1][0]*xs[2][1]-xs[1][1]*xs[2][0]; - ad[2][1] = xs[0][1]*xs[2][0]-xs[0][0]*xs[2][1]; - ad[2][2] = xs[0][0]*xs[1][1]-xs[0][1]*xs[1][0]; + ad[0][0] = xs[1][1] * xs[2][2] - xs[1][2] * xs[2][1]; + ad[0][1] = xs[0][2] * xs[2][1] - xs[0][1] * xs[2][2]; + ad[0][2] = xs[0][1] * xs[1][2] - xs[0][2] * xs[1][1]; + ad[1][0] = xs[1][2] * xs[2][0] - xs[1][0] * xs[2][2]; + ad[1][1] = xs[0][0] * xs[2][2] - xs[0][2] * xs[2][0]; + ad[1][2] = xs[0][2] * xs[1][0] - xs[0][0] * xs[1][2]; + ad[2][0] = xs[1][0] * xs[2][1] - xs[1][1] * xs[2][0]; + ad[2][1] = xs[0][1] * xs[2][0] - xs[0][0] * xs[2][1]; + ad[2][2] = xs[0][0] * xs[1][1] - xs[0][1] * xs[1][0]; /*--- Determinant of Jacobian ---*/ - xsj = xs[0][0]*ad[0][0]+xs[0][1]*ad[1][0]+xs[0][2]*ad[2][0]; + xsj = xs[0][0] * ad[0][0] + xs[0][1] * ad[1][0] + xs[0][2] * ad[2][0]; /*--- Jacobian inverse ---*/ for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { - xs[i][j] = ad[i][j]/xsj; + xs[i][j] = ad[i][j] / xsj; } } /*--- Derivatives with repect to global coordinates ---*/ for (k = 0; k < 8; k++) { - c0 = xs[0][0]*DShapeFunction[k][0]+xs[0][1]*DShapeFunction[k][1]+xs[0][2]*DShapeFunction[k][2]; // dN/dx - c1 = xs[1][0]*DShapeFunction[k][0]+xs[1][1]*DShapeFunction[k][1]+xs[1][2]*DShapeFunction[k][2]; // dN/dy - c2 = xs[2][0]*DShapeFunction[k][0]+xs[2][1]*DShapeFunction[k][1]+xs[2][2]*DShapeFunction[k][2]; // dN/dz - DShapeFunction[k][0] = c0; // store dN/dx instead of dN/d xi - DShapeFunction[k][1] = c1; // store dN/dy instead of dN/d eta - DShapeFunction[k][2] = c2; // store dN/dz instead of dN/d zeta + c0 = xs[0][0] * DShapeFunction[k][0] + xs[0][1] * DShapeFunction[k][1] + xs[0][2] * DShapeFunction[k][2]; // dN/dx + c1 = xs[1][0] * DShapeFunction[k][0] + xs[1][1] * DShapeFunction[k][1] + xs[1][2] * DShapeFunction[k][2]; // dN/dy + c2 = xs[2][0] * DShapeFunction[k][0] + xs[2][1] * DShapeFunction[k][1] + xs[2][2] * DShapeFunction[k][2]; // dN/dz + DShapeFunction[k][0] = c0; // store dN/dx instead of dN/d xi + DShapeFunction[k][1] = c1; // store dN/dy instead of dN/d eta + DShapeFunction[k][2] = c2; // store dN/dz instead of dN/d zeta } return xsj; - } su2double CVolumetricMovement::GetTriangle_Area(su2double CoordCorners[8][3]) const { - unsigned short iDim; - su2double a[3] = {0.0,0.0,0.0}, b[3] = {0.0,0.0,0.0}; + su2double a[3] = {0.0, 0.0, 0.0}, b[3] = {0.0, 0.0, 0.0}; su2double *Coord_0, *Coord_1, *Coord_2, Area; Coord_0 = CoordCorners[0]; @@ -1006,20 +1013,18 @@ su2double CVolumetricMovement::GetTriangle_Area(su2double CoordCorners[8][3]) co Coord_2 = CoordCorners[2]; for (iDim = 0; iDim < nDim; iDim++) { - a[iDim] = Coord_0[iDim]-Coord_2[iDim]; - b[iDim] = Coord_1[iDim]-Coord_2[iDim]; + a[iDim] = Coord_0[iDim] - Coord_2[iDim]; + b[iDim] = Coord_1[iDim] - Coord_2[iDim]; } - Area = 0.5*fabs(a[0]*b[1]-a[1]*b[0]); + Area = 0.5 * fabs(a[0] * b[1] - a[1] * b[0]); return Area; - } su2double CVolumetricMovement::GetQuadrilateral_Area(su2double CoordCorners[8][3]) const { - unsigned short iDim; - su2double a[3] = {0.0,0.0,0.0}, b[3] = {0.0,0.0,0.0}; + su2double a[3] = {0.0, 0.0, 0.0}, b[3] = {0.0, 0.0, 0.0}; su2double *Coord_0, *Coord_1, *Coord_2, Area; Coord_0 = CoordCorners[0]; @@ -1027,32 +1032,31 @@ su2double CVolumetricMovement::GetQuadrilateral_Area(su2double CoordCorners[8][3 Coord_2 = CoordCorners[2]; for (iDim = 0; iDim < nDim; iDim++) { - a[iDim] = Coord_0[iDim]-Coord_2[iDim]; - b[iDim] = Coord_1[iDim]-Coord_2[iDim]; + a[iDim] = Coord_0[iDim] - Coord_2[iDim]; + b[iDim] = Coord_1[iDim] - Coord_2[iDim]; } - Area = 0.5*fabs(a[0]*b[1]-a[1]*b[0]); + Area = 0.5 * fabs(a[0] * b[1] - a[1] * b[0]); Coord_0 = CoordCorners[0]; Coord_1 = CoordCorners[2]; Coord_2 = CoordCorners[3]; for (iDim = 0; iDim < nDim; iDim++) { - a[iDim] = Coord_0[iDim]-Coord_2[iDim]; - b[iDim] = Coord_1[iDim]-Coord_2[iDim]; + a[iDim] = Coord_0[iDim] - Coord_2[iDim]; + b[iDim] = Coord_1[iDim] - Coord_2[iDim]; } - Area += 0.5*fabs(a[0]*b[1]-a[1]*b[0]); + Area += 0.5 * fabs(a[0] * b[1] - a[1] * b[0]); return Area; - } su2double CVolumetricMovement::GetTetra_Volume(su2double CoordCorners[8][3]) const { - unsigned short iDim; su2double *Coord_0, *Coord_1, *Coord_2, *Coord_3; - su2double r1[3] = {0.0,0.0,0.0}, r2[3] = {0.0,0.0,0.0}, r3[3] = {0.0,0.0,0.0}, CrossProduct[3] = {0.0,0.0,0.0}, Volume; + su2double r1[3] = {0.0, 0.0, 0.0}, r2[3] = {0.0, 0.0, 0.0}, r3[3] = {0.0, 0.0, 0.0}, + CrossProduct[3] = {0.0, 0.0, 0.0}, Volume; Coord_0 = CoordCorners[0]; Coord_1 = CoordCorners[1]; @@ -1065,21 +1069,20 @@ su2double CVolumetricMovement::GetTetra_Volume(su2double CoordCorners[8][3]) con r3[iDim] = Coord_3[iDim] - Coord_0[iDim]; } - CrossProduct[0] = (r1[1]*r2[2] - r1[2]*r2[1])*r3[0]; - CrossProduct[1] = (r1[2]*r2[0] - r1[0]*r2[2])*r3[1]; - CrossProduct[2] = (r1[0]*r2[1] - r1[1]*r2[0])*r3[2]; + CrossProduct[0] = (r1[1] * r2[2] - r1[2] * r2[1]) * r3[0]; + CrossProduct[1] = (r1[2] * r2[0] - r1[0] * r2[2]) * r3[1]; + CrossProduct[2] = (r1[0] * r2[1] - r1[1] * r2[0]) * r3[2]; - Volume = fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2])/6.0; + Volume = fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2]) / 6.0; return Volume; - } su2double CVolumetricMovement::GetPyram_Volume(su2double CoordCorners[8][3]) const { - unsigned short iDim; su2double *Coord_0, *Coord_1, *Coord_2, *Coord_3; - su2double r1[3] = {0.0,0.0,0.0}, r2[3] = {0.0,0.0,0.0}, r3[3] = {0.0,0.0,0.0}, CrossProduct[3] = {0.0,0.0,0.0}, Volume; + su2double r1[3] = {0.0, 0.0, 0.0}, r2[3] = {0.0, 0.0, 0.0}, r3[3] = {0.0, 0.0, 0.0}, + CrossProduct[3] = {0.0, 0.0, 0.0}, Volume; Coord_0 = CoordCorners[0]; Coord_1 = CoordCorners[1]; @@ -1092,11 +1095,11 @@ su2double CVolumetricMovement::GetPyram_Volume(su2double CoordCorners[8][3]) con r3[iDim] = Coord_3[iDim] - Coord_0[iDim]; } - CrossProduct[0] = (r1[1]*r2[2] - r1[2]*r2[1])*r3[0]; - CrossProduct[1] = (r1[2]*r2[0] - r1[0]*r2[2])*r3[1]; - CrossProduct[2] = (r1[0]*r2[1] - r1[1]*r2[0])*r3[2]; + CrossProduct[0] = (r1[1] * r2[2] - r1[2] * r2[1]) * r3[0]; + CrossProduct[1] = (r1[2] * r2[0] - r1[0] * r2[2]) * r3[1]; + CrossProduct[2] = (r1[0] * r2[1] - r1[1] * r2[0]) * r3[2]; - Volume = fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2])/6.0; + Volume = fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2]) / 6.0; Coord_0 = CoordCorners[0]; Coord_1 = CoordCorners[2]; @@ -1109,21 +1112,20 @@ su2double CVolumetricMovement::GetPyram_Volume(su2double CoordCorners[8][3]) con r3[iDim] = Coord_3[iDim] - Coord_0[iDim]; } - CrossProduct[0] = (r1[1]*r2[2] - r1[2]*r2[1])*r3[0]; - CrossProduct[1] = (r1[2]*r2[0] - r1[0]*r2[2])*r3[1]; - CrossProduct[2] = (r1[0]*r2[1] - r1[1]*r2[0])*r3[2]; + CrossProduct[0] = (r1[1] * r2[2] - r1[2] * r2[1]) * r3[0]; + CrossProduct[1] = (r1[2] * r2[0] - r1[0] * r2[2]) * r3[1]; + CrossProduct[2] = (r1[0] * r2[1] - r1[1] * r2[0]) * r3[2]; - Volume += fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2])/6.0; + Volume += fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2]) / 6.0; return Volume; - } su2double CVolumetricMovement::GetPrism_Volume(su2double CoordCorners[8][3]) const { - unsigned short iDim; su2double *Coord_0, *Coord_1, *Coord_2, *Coord_3; - su2double r1[3] = {0.0,0.0,0.0}, r2[3] = {0.0,0.0,0.0}, r3[3] = {0.0,0.0,0.0}, CrossProduct[3] = {0.0,0.0,0.0}, Volume; + su2double r1[3] = {0.0, 0.0, 0.0}, r2[3] = {0.0, 0.0, 0.0}, r3[3] = {0.0, 0.0, 0.0}, + CrossProduct[3] = {0.0, 0.0, 0.0}, Volume; Coord_0 = CoordCorners[0]; Coord_1 = CoordCorners[2]; @@ -1136,11 +1138,11 @@ su2double CVolumetricMovement::GetPrism_Volume(su2double CoordCorners[8][3]) con r3[iDim] = Coord_3[iDim] - Coord_0[iDim]; } - CrossProduct[0] = (r1[1]*r2[2] - r1[2]*r2[1])*r3[0]; - CrossProduct[1] = (r1[2]*r2[0] - r1[0]*r2[2])*r3[1]; - CrossProduct[2] = (r1[0]*r2[1] - r1[1]*r2[0])*r3[2]; + CrossProduct[0] = (r1[1] * r2[2] - r1[2] * r2[1]) * r3[0]; + CrossProduct[1] = (r1[2] * r2[0] - r1[0] * r2[2]) * r3[1]; + CrossProduct[2] = (r1[0] * r2[1] - r1[1] * r2[0]) * r3[2]; - Volume = fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2])/6.0; + Volume = fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2]) / 6.0; Coord_0 = CoordCorners[0]; Coord_1 = CoordCorners[5]; @@ -1153,11 +1155,11 @@ su2double CVolumetricMovement::GetPrism_Volume(su2double CoordCorners[8][3]) con r3[iDim] = Coord_3[iDim] - Coord_0[iDim]; } - CrossProduct[0] = (r1[1]*r2[2] - r1[2]*r2[1])*r3[0]; - CrossProduct[1] = (r1[2]*r2[0] - r1[0]*r2[2])*r3[1]; - CrossProduct[2] = (r1[0]*r2[1] - r1[1]*r2[0])*r3[2]; + CrossProduct[0] = (r1[1] * r2[2] - r1[2] * r2[1]) * r3[0]; + CrossProduct[1] = (r1[2] * r2[0] - r1[0] * r2[2]) * r3[1]; + CrossProduct[2] = (r1[0] * r2[1] - r1[1] * r2[0]) * r3[2]; - Volume += fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2])/6.0; + Volume += fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2]) / 6.0; Coord_0 = CoordCorners[0]; Coord_1 = CoordCorners[5]; @@ -1170,21 +1172,20 @@ su2double CVolumetricMovement::GetPrism_Volume(su2double CoordCorners[8][3]) con r3[iDim] = Coord_3[iDim] - Coord_0[iDim]; } - CrossProduct[0] = (r1[1]*r2[2] - r1[2]*r2[1])*r3[0]; - CrossProduct[1] = (r1[2]*r2[0] - r1[0]*r2[2])*r3[1]; - CrossProduct[2] = (r1[0]*r2[1] - r1[1]*r2[0])*r3[2]; + CrossProduct[0] = (r1[1] * r2[2] - r1[2] * r2[1]) * r3[0]; + CrossProduct[1] = (r1[2] * r2[0] - r1[0] * r2[2]) * r3[1]; + CrossProduct[2] = (r1[0] * r2[1] - r1[1] * r2[0]) * r3[2]; - Volume += fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2])/6.0; + Volume += fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2]) / 6.0; return Volume; - } su2double CVolumetricMovement::GetHexa_Volume(su2double CoordCorners[8][3]) const { - unsigned short iDim; su2double *Coord_0, *Coord_1, *Coord_2, *Coord_3; - su2double r1[3] = {0.0,0.0,0.0}, r2[3] = {0.0,0.0,0.0}, r3[3] = {0.0,0.0,0.0}, CrossProduct[3] = {0.0,0.0,0.0}, Volume; + su2double r1[3] = {0.0, 0.0, 0.0}, r2[3] = {0.0, 0.0, 0.0}, r3[3] = {0.0, 0.0, 0.0}, + CrossProduct[3] = {0.0, 0.0, 0.0}, Volume; Coord_0 = CoordCorners[0]; Coord_1 = CoordCorners[1]; @@ -1197,11 +1198,11 @@ su2double CVolumetricMovement::GetHexa_Volume(su2double CoordCorners[8][3]) cons r3[iDim] = Coord_3[iDim] - Coord_0[iDim]; } - CrossProduct[0] = (r1[1]*r2[2] - r1[2]*r2[1])*r3[0]; - CrossProduct[1] = (r1[2]*r2[0] - r1[0]*r2[2])*r3[1]; - CrossProduct[2] = (r1[0]*r2[1] - r1[1]*r2[0])*r3[2]; + CrossProduct[0] = (r1[1] * r2[2] - r1[2] * r2[1]) * r3[0]; + CrossProduct[1] = (r1[2] * r2[0] - r1[0] * r2[2]) * r3[1]; + CrossProduct[2] = (r1[0] * r2[1] - r1[1] * r2[0]) * r3[2]; - Volume = fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2])/6.0; + Volume = fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2]) / 6.0; Coord_0 = CoordCorners[0]; Coord_1 = CoordCorners[2]; @@ -1214,11 +1215,11 @@ su2double CVolumetricMovement::GetHexa_Volume(su2double CoordCorners[8][3]) cons r3[iDim] = Coord_3[iDim] - Coord_0[iDim]; } - CrossProduct[0] = (r1[1]*r2[2] - r1[2]*r2[1])*r3[0]; - CrossProduct[1] = (r1[2]*r2[0] - r1[0]*r2[2])*r3[1]; - CrossProduct[2] = (r1[0]*r2[1] - r1[1]*r2[0])*r3[2]; + CrossProduct[0] = (r1[1] * r2[2] - r1[2] * r2[1]) * r3[0]; + CrossProduct[1] = (r1[2] * r2[0] - r1[0] * r2[2]) * r3[1]; + CrossProduct[2] = (r1[0] * r2[1] - r1[1] * r2[0]) * r3[2]; - Volume += fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2])/6.0; + Volume += fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2]) / 6.0; Coord_0 = CoordCorners[0]; Coord_1 = CoordCorners[2]; @@ -1231,11 +1232,11 @@ su2double CVolumetricMovement::GetHexa_Volume(su2double CoordCorners[8][3]) cons r3[iDim] = Coord_3[iDim] - Coord_0[iDim]; } - CrossProduct[0] = (r1[1]*r2[2] - r1[2]*r2[1])*r3[0]; - CrossProduct[1] = (r1[2]*r2[0] - r1[0]*r2[2])*r3[1]; - CrossProduct[2] = (r1[0]*r2[1] - r1[1]*r2[0])*r3[2]; + CrossProduct[0] = (r1[1] * r2[2] - r1[2] * r2[1]) * r3[0]; + CrossProduct[1] = (r1[2] * r2[0] - r1[0] * r2[2]) * r3[1]; + CrossProduct[2] = (r1[0] * r2[1] - r1[1] * r2[0]) * r3[2]; - Volume += fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2])/6.0; + Volume += fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2]) / 6.0; Coord_0 = CoordCorners[0]; Coord_1 = CoordCorners[5]; @@ -1248,11 +1249,11 @@ su2double CVolumetricMovement::GetHexa_Volume(su2double CoordCorners[8][3]) cons r3[iDim] = Coord_3[iDim] - Coord_0[iDim]; } - CrossProduct[0] = (r1[1]*r2[2] - r1[2]*r2[1])*r3[0]; - CrossProduct[1] = (r1[2]*r2[0] - r1[0]*r2[2])*r3[1]; - CrossProduct[2] = (r1[0]*r2[1] - r1[1]*r2[0])*r3[2]; + CrossProduct[0] = (r1[1] * r2[2] - r1[2] * r2[1]) * r3[0]; + CrossProduct[1] = (r1[2] * r2[0] - r1[0] * r2[2]) * r3[1]; + CrossProduct[2] = (r1[0] * r2[1] - r1[1] * r2[0]) * r3[2]; - Volume += fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2])/6.0; + Volume += fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2]) / 6.0; Coord_0 = CoordCorners[2]; Coord_1 = CoordCorners[7]; @@ -1265,29 +1266,29 @@ su2double CVolumetricMovement::GetHexa_Volume(su2double CoordCorners[8][3]) cons r3[iDim] = Coord_3[iDim] - Coord_0[iDim]; } - CrossProduct[0] = (r1[1]*r2[2] - r1[2]*r2[1])*r3[0]; - CrossProduct[1] = (r1[2]*r2[0] - r1[0]*r2[2])*r3[1]; - CrossProduct[2] = (r1[0]*r2[1] - r1[1]*r2[0])*r3[2]; + CrossProduct[0] = (r1[1] * r2[2] - r1[2] * r2[1]) * r3[0]; + CrossProduct[1] = (r1[2] * r2[0] - r1[0] * r2[2]) * r3[1]; + CrossProduct[2] = (r1[0] * r2[1] - r1[1] * r2[0]) * r3[2]; - Volume += fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2])/6.0; + Volume += fabs(CrossProduct[0] + CrossProduct[1] + CrossProduct[2]) / 6.0; return Volume; - } -void CVolumetricMovement::SetFEA_StiffMatrix2D(CGeometry *geometry, CConfig *config, su2double **StiffMatrix_Elem, unsigned long PointCorners[8], su2double CoordCorners[8][3], +void CVolumetricMovement::SetFEA_StiffMatrix2D(CGeometry* geometry, CConfig* config, su2double** StiffMatrix_Elem, + unsigned long PointCorners[8], su2double CoordCorners[8][3], unsigned short nNodes, su2double ElemVolume, su2double ElemDistance) { - su2double B_Matrix[3][8], D_Matrix[3][3], Aux_Matrix[8][3]; - su2double Xi = 0.0, Eta = 0.0, Det = 0.0, E = 1/EPS, Lambda = 0.0, Mu = 0.0, Nu = 0.0; + su2double Xi = 0.0, Eta = 0.0, Det = 0.0, E = 1 / EPS, Lambda = 0.0, Mu = 0.0, Nu = 0.0; unsigned short iNode, iVar, jVar, kVar, iGauss, nGauss = 0; - su2double DShapeFunction[8][4] = {{0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0}, - {0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0}}; + su2double DShapeFunction[8][4] = {{0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0}, + {0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0}, + {0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0}}; su2double Location[4][3], Weight[4]; unsigned short nVar = geometry->GetnDim(); - for (iVar = 0; iVar < nNodes*nVar; iVar++) { - for (jVar = 0; jVar < nNodes*nVar; jVar++) { + for (iVar = 0; iVar < nNodes * nVar; iVar++) { + for (jVar = 0; jVar < nNodes * nVar; jVar++) { StiffMatrix_Elem[iVar][jVar] = 0.0; } } @@ -1299,22 +1300,32 @@ void CVolumetricMovement::SetFEA_StiffMatrix2D(CGeometry *geometry, CConfig *con if (nNodes == 3) { nGauss = 1; - Location[0][0] = 0.333333333333333; Location[0][1] = 0.333333333333333; Weight[0] = 0.5; + Location[0][0] = 0.333333333333333; + Location[0][1] = 0.333333333333333; + Weight[0] = 0.5; } /*--- Quadrilateral. Nodes of numerical integration at 4 points (order 2). ---*/ if (nNodes == 4) { nGauss = 4; - Location[0][0] = -0.577350269189626; Location[0][1] = -0.577350269189626; Weight[0] = 1.0; - Location[1][0] = 0.577350269189626; Location[1][1] = -0.577350269189626; Weight[1] = 1.0; - Location[2][0] = 0.577350269189626; Location[2][1] = 0.577350269189626; Weight[2] = 1.0; - Location[3][0] = -0.577350269189626; Location[3][1] = 0.577350269189626; Weight[3] = 1.0; + Location[0][0] = -0.577350269189626; + Location[0][1] = -0.577350269189626; + Weight[0] = 1.0; + Location[1][0] = 0.577350269189626; + Location[1][1] = -0.577350269189626; + Weight[1] = 1.0; + Location[2][0] = 0.577350269189626; + Location[2][1] = 0.577350269189626; + Weight[2] = 1.0; + Location[3][0] = -0.577350269189626; + Location[3][1] = 0.577350269189626; + Weight[3] = 1.0; } for (iGauss = 0; iGauss < nGauss; iGauss++) { - - Xi = Location[iGauss][0]; Eta = Location[iGauss][1]; + Xi = Location[iGauss][0]; + Eta = Location[iGauss][1]; if (nNodes == 3) Det = ShapeFunc_Triangle(Xi, Eta, CoordCorners, DShapeFunction); if (nNodes == 4) Det = ShapeFunc_Quadrilateral(Xi, Eta, CoordCorners, DShapeFunction); @@ -1322,75 +1333,85 @@ void CVolumetricMovement::SetFEA_StiffMatrix2D(CGeometry *geometry, CConfig *con /*--- Compute the B Matrix ---*/ for (iVar = 0; iVar < 3; iVar++) - for (jVar = 0; jVar < nNodes*nVar; jVar++) - B_Matrix[iVar][jVar] = 0.0; + for (jVar = 0; jVar < nNodes * nVar; jVar++) B_Matrix[iVar][jVar] = 0.0; for (iNode = 0; iNode < nNodes; iNode++) { - B_Matrix[0][0+iNode*nVar] = DShapeFunction[iNode][0]; - B_Matrix[1][1+iNode*nVar] = DShapeFunction[iNode][1]; + B_Matrix[0][0 + iNode * nVar] = DShapeFunction[iNode][0]; + B_Matrix[1][1 + iNode * nVar] = DShapeFunction[iNode][1]; - B_Matrix[2][0+iNode*nVar] = DShapeFunction[iNode][1]; - B_Matrix[2][1+iNode*nVar] = DShapeFunction[iNode][0]; + B_Matrix[2][0 + iNode * nVar] = DShapeFunction[iNode][1]; + B_Matrix[2][1 + iNode * nVar] = DShapeFunction[iNode][0]; } /*--- Impose a type of stiffness for each element ---*/ switch (config->GetDeform_Stiffness_Type()) { - case INVERSE_VOLUME: E = 1.0 / ElemVolume; break; - case SOLID_WALL_DISTANCE: E = 1.0 / ElemDistance; break; - case CONSTANT_STIFFNESS: E = 1.0 / EPS; break; + case INVERSE_VOLUME: + E = 1.0 / ElemVolume; + break; + case SOLID_WALL_DISTANCE: + E = 1.0 / ElemDistance; + break; + case CONSTANT_STIFFNESS: + E = 1.0 / EPS; + break; } Nu = config->GetDeform_Coeff(); - Mu = E / (2.0*(1.0 + Nu)); - Lambda = Nu*E/((1.0+Nu)*(1.0-2.0*Nu)); + Mu = E / (2.0 * (1.0 + Nu)); + Lambda = Nu * E / ((1.0 + Nu) * (1.0 - 2.0 * Nu)); /*--- Compute the D Matrix (for plane strain and 3-D)---*/ - D_Matrix[0][0] = Lambda + 2.0*Mu; D_Matrix[0][1] = Lambda; D_Matrix[0][2] = 0.0; - D_Matrix[1][0] = Lambda; D_Matrix[1][1] = Lambda + 2.0*Mu; D_Matrix[1][2] = 0.0; - D_Matrix[2][0] = 0.0; D_Matrix[2][1] = 0.0; D_Matrix[2][2] = Mu; - + D_Matrix[0][0] = Lambda + 2.0 * Mu; + D_Matrix[0][1] = Lambda; + D_Matrix[0][2] = 0.0; + D_Matrix[1][0] = Lambda; + D_Matrix[1][1] = Lambda + 2.0 * Mu; + D_Matrix[1][2] = 0.0; + D_Matrix[2][0] = 0.0; + D_Matrix[2][1] = 0.0; + D_Matrix[2][2] = Mu; /*--- Compute the BT.D Matrix ---*/ - for (iVar = 0; iVar < nNodes*nVar; iVar++) { + for (iVar = 0; iVar < nNodes * nVar; iVar++) { for (jVar = 0; jVar < 3; jVar++) { Aux_Matrix[iVar][jVar] = 0.0; - for (kVar = 0; kVar < 3; kVar++) - Aux_Matrix[iVar][jVar] += B_Matrix[kVar][iVar]*D_Matrix[kVar][jVar]; + for (kVar = 0; kVar < 3; kVar++) Aux_Matrix[iVar][jVar] += B_Matrix[kVar][iVar] * D_Matrix[kVar][jVar]; } } /*--- Compute the BT.D.B Matrix (stiffness matrix), and add to the original matrix using Gauss integration ---*/ - for (iVar = 0; iVar < nNodes*nVar; iVar++) { - for (jVar = 0; jVar < nNodes*nVar; jVar++) { + for (iVar = 0; iVar < nNodes * nVar; iVar++) { + for (jVar = 0; jVar < nNodes * nVar; jVar++) { for (kVar = 0; kVar < 3; kVar++) { - StiffMatrix_Elem[iVar][jVar] += Weight[iGauss] * Aux_Matrix[iVar][kVar]*B_Matrix[kVar][jVar] * fabs(Det); + StiffMatrix_Elem[iVar][jVar] += Weight[iGauss] * Aux_Matrix[iVar][kVar] * B_Matrix[kVar][jVar] * fabs(Det); } } } - } - } -void CVolumetricMovement::SetFEA_StiffMatrix3D(CGeometry *geometry, CConfig *config, su2double **StiffMatrix_Elem, unsigned long PointCorners[8], su2double CoordCorners[8][3], +void CVolumetricMovement::SetFEA_StiffMatrix3D(CGeometry* geometry, CConfig* config, su2double** StiffMatrix_Elem, + unsigned long PointCorners[8], su2double CoordCorners[8][3], unsigned short nNodes, su2double ElemVolume, su2double ElemDistance) { - - su2double B_Matrix[6][24], D_Matrix[6][6] = {{0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, - {0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0, 0.0, 0.0}}, Aux_Matrix[24][6]; + su2double B_Matrix[6][24], + D_Matrix[6][6] = {{0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, + {0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0, 0.0, 0.0}}, + Aux_Matrix[24][6]; su2double Xi = 0.0, Eta = 0.0, Zeta = 0.0, Det = 0.0, Mu = 0.0, E = 0.0, Lambda = 0.0, Nu = 0.0; unsigned short iNode, iVar, jVar, kVar, iGauss, nGauss = 0; - su2double DShapeFunction[8][4] = {{0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0}, - {0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0}}; + su2double DShapeFunction[8][4] = {{0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0}, + {0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0}, + {0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0}}; su2double Location[8][3], Weight[8]; unsigned short nVar = geometry->GetnDim(); - for (iVar = 0; iVar < nNodes*nVar; iVar++) { - for (jVar = 0; jVar < nNodes*nVar; jVar++) { + for (iVar = 0; iVar < nNodes * nVar; iVar++) { + for (jVar = 0; jVar < nNodes * nVar; jVar++) { StiffMatrix_Elem[iVar][jVar] = 0.0; } } @@ -1402,49 +1423,110 @@ void CVolumetricMovement::SetFEA_StiffMatrix3D(CGeometry *geometry, CConfig *con if (nNodes == 4) { nGauss = 1; - Location[0][0] = 0.25; Location[0][1] = 0.25; Location[0][2] = 0.25; Weight[0] = 0.166666666666666; + Location[0][0] = 0.25; + Location[0][1] = 0.25; + Location[0][2] = 0.25; + Weight[0] = 0.166666666666666; } /*--- Pyramids. Nodes numerical integration at 5 points. ---*/ if (nNodes == 5) { nGauss = 5; - Location[0][0] = 0.5; Location[0][1] = 0.0; Location[0][2] = 0.1531754163448146; Weight[0] = 0.133333333333333; - Location[1][0] = 0.0; Location[1][1] = 0.5; Location[1][2] = 0.1531754163448146; Weight[1] = 0.133333333333333; - Location[2][0] = -0.5; Location[2][1] = 0.0; Location[2][2] = 0.1531754163448146; Weight[2] = 0.133333333333333; - Location[3][0] = 0.0; Location[3][1] = -0.5; Location[3][2] = 0.1531754163448146; Weight[3] = 0.133333333333333; - Location[4][0] = 0.0; Location[4][1] = 0.0; Location[4][2] = 0.6372983346207416; Weight[4] = 0.133333333333333; + Location[0][0] = 0.5; + Location[0][1] = 0.0; + Location[0][2] = 0.1531754163448146; + Weight[0] = 0.133333333333333; + Location[1][0] = 0.0; + Location[1][1] = 0.5; + Location[1][2] = 0.1531754163448146; + Weight[1] = 0.133333333333333; + Location[2][0] = -0.5; + Location[2][1] = 0.0; + Location[2][2] = 0.1531754163448146; + Weight[2] = 0.133333333333333; + Location[3][0] = 0.0; + Location[3][1] = -0.5; + Location[3][2] = 0.1531754163448146; + Weight[3] = 0.133333333333333; + Location[4][0] = 0.0; + Location[4][1] = 0.0; + Location[4][2] = 0.6372983346207416; + Weight[4] = 0.133333333333333; } /*--- Prism. Nodes of numerical integration at 6 points (order 3 in Xi, order 2 in Eta and Mu ). ---*/ if (nNodes == 6) { nGauss = 6; - Location[0][0] = -0.577350269189626; Location[0][1] = 0.166666666666667; Location[0][2] = 0.166666666666667; Weight[0] = 0.166666666666667; - Location[1][0] = -0.577350269189626; Location[1][1] = 0.666666666666667; Location[1][2] = 0.166666666666667; Weight[1] = 0.166666666666667; - Location[2][0] = -0.577350269189626; Location[2][1] = 0.166666666666667; Location[2][2] = 0.666666666666667; Weight[2] = 0.166666666666667; - Location[3][0] = 0.577350269189626; Location[3][1] = 0.166666666666667; Location[3][2] = 0.166666666666667; Weight[3] = 0.166666666666667; - Location[4][0] = 0.577350269189626; Location[4][1] = 0.666666666666667; Location[4][2] = 0.166666666666667; Weight[4] = 0.166666666666667; - Location[5][0] = 0.577350269189626; Location[5][1] = 0.166666666666667; Location[5][2] = 0.666666666666667; Weight[5] = 0.166666666666667; + Location[0][0] = -0.577350269189626; + Location[0][1] = 0.166666666666667; + Location[0][2] = 0.166666666666667; + Weight[0] = 0.166666666666667; + Location[1][0] = -0.577350269189626; + Location[1][1] = 0.666666666666667; + Location[1][2] = 0.166666666666667; + Weight[1] = 0.166666666666667; + Location[2][0] = -0.577350269189626; + Location[2][1] = 0.166666666666667; + Location[2][2] = 0.666666666666667; + Weight[2] = 0.166666666666667; + Location[3][0] = 0.577350269189626; + Location[3][1] = 0.166666666666667; + Location[3][2] = 0.166666666666667; + Weight[3] = 0.166666666666667; + Location[4][0] = 0.577350269189626; + Location[4][1] = 0.666666666666667; + Location[4][2] = 0.166666666666667; + Weight[4] = 0.166666666666667; + Location[5][0] = 0.577350269189626; + Location[5][1] = 0.166666666666667; + Location[5][2] = 0.666666666666667; + Weight[5] = 0.166666666666667; } /*--- Hexahedrons. Nodes of numerical integration at 6 points (order 3). ---*/ if (nNodes == 8) { nGauss = 8; - Location[0][0] = -0.577350269189626; Location[0][1] = -0.577350269189626; Location[0][2] = -0.577350269189626; Weight[0] = 1.0; - Location[1][0] = -0.577350269189626; Location[1][1] = -0.577350269189626; Location[1][2] = 0.577350269189626; Weight[1] = 1.0; - Location[2][0] = -0.577350269189626; Location[2][1] = 0.577350269189626; Location[2][2] = -0.577350269189626; Weight[2] = 1.0; - Location[3][0] = -0.577350269189626; Location[3][1] = 0.577350269189626; Location[3][2] = 0.577350269189626; Weight[3] = 1.0; - Location[4][0] = 0.577350269189626; Location[4][1] = -0.577350269189626; Location[4][2] = -0.577350269189626; Weight[4] = 1.0; - Location[5][0] = 0.577350269189626; Location[5][1] = -0.577350269189626; Location[5][2] = 0.577350269189626; Weight[5] = 1.0; - Location[6][0] = 0.577350269189626; Location[6][1] = 0.577350269189626; Location[6][2] = -0.577350269189626; Weight[6] = 1.0; - Location[7][0] = 0.577350269189626; Location[7][1] = 0.577350269189626; Location[7][2] = 0.577350269189626; Weight[7] = 1.0; + Location[0][0] = -0.577350269189626; + Location[0][1] = -0.577350269189626; + Location[0][2] = -0.577350269189626; + Weight[0] = 1.0; + Location[1][0] = -0.577350269189626; + Location[1][1] = -0.577350269189626; + Location[1][2] = 0.577350269189626; + Weight[1] = 1.0; + Location[2][0] = -0.577350269189626; + Location[2][1] = 0.577350269189626; + Location[2][2] = -0.577350269189626; + Weight[2] = 1.0; + Location[3][0] = -0.577350269189626; + Location[3][1] = 0.577350269189626; + Location[3][2] = 0.577350269189626; + Weight[3] = 1.0; + Location[4][0] = 0.577350269189626; + Location[4][1] = -0.577350269189626; + Location[4][2] = -0.577350269189626; + Weight[4] = 1.0; + Location[5][0] = 0.577350269189626; + Location[5][1] = -0.577350269189626; + Location[5][2] = 0.577350269189626; + Weight[5] = 1.0; + Location[6][0] = 0.577350269189626; + Location[6][1] = 0.577350269189626; + Location[6][2] = -0.577350269189626; + Weight[6] = 1.0; + Location[7][0] = 0.577350269189626; + Location[7][1] = 0.577350269189626; + Location[7][2] = 0.577350269189626; + Weight[7] = 1.0; } for (iGauss = 0; iGauss < nGauss; iGauss++) { - - Xi = Location[iGauss][0]; Eta = Location[iGauss][1]; Zeta = Location[iGauss][2]; + Xi = Location[iGauss][0]; + Eta = Location[iGauss][1]; + Zeta = Location[iGauss][2]; if (nNodes == 4) Det = ShapeFunc_Tetra(Xi, Eta, Zeta, CoordCorners, DShapeFunction); if (nNodes == 5) Det = ShapeFunc_Pyram(Xi, Eta, Zeta, CoordCorners, DShapeFunction); @@ -1454,116 +1536,116 @@ void CVolumetricMovement::SetFEA_StiffMatrix3D(CGeometry *geometry, CConfig *con /*--- Compute the B Matrix ---*/ for (iVar = 0; iVar < 6; iVar++) - for (jVar = 0; jVar < nNodes*nVar; jVar++) - B_Matrix[iVar][jVar] = 0.0; + for (jVar = 0; jVar < nNodes * nVar; jVar++) B_Matrix[iVar][jVar] = 0.0; for (iNode = 0; iNode < nNodes; iNode++) { - B_Matrix[0][0+iNode*nVar] = DShapeFunction[iNode][0]; - B_Matrix[1][1+iNode*nVar] = DShapeFunction[iNode][1]; - B_Matrix[2][2+iNode*nVar] = DShapeFunction[iNode][2]; + B_Matrix[0][0 + iNode * nVar] = DShapeFunction[iNode][0]; + B_Matrix[1][1 + iNode * nVar] = DShapeFunction[iNode][1]; + B_Matrix[2][2 + iNode * nVar] = DShapeFunction[iNode][2]; - B_Matrix[3][0+iNode*nVar] = DShapeFunction[iNode][1]; - B_Matrix[3][1+iNode*nVar] = DShapeFunction[iNode][0]; + B_Matrix[3][0 + iNode * nVar] = DShapeFunction[iNode][1]; + B_Matrix[3][1 + iNode * nVar] = DShapeFunction[iNode][0]; - B_Matrix[4][1+iNode*nVar] = DShapeFunction[iNode][2]; - B_Matrix[4][2+iNode*nVar] = DShapeFunction[iNode][1]; + B_Matrix[4][1 + iNode * nVar] = DShapeFunction[iNode][2]; + B_Matrix[4][2 + iNode * nVar] = DShapeFunction[iNode][1]; - B_Matrix[5][0+iNode*nVar] = DShapeFunction[iNode][2]; - B_Matrix[5][2+iNode*nVar] = DShapeFunction[iNode][0]; + B_Matrix[5][0 + iNode * nVar] = DShapeFunction[iNode][2]; + B_Matrix[5][2 + iNode * nVar] = DShapeFunction[iNode][0]; } /*--- Impose a type of stiffness for each element ---*/ switch (config->GetDeform_Stiffness_Type()) { - case INVERSE_VOLUME: E = 1.0 / ElemVolume; break; - case SOLID_WALL_DISTANCE: E = 1.0 / ElemDistance; break; - case CONSTANT_STIFFNESS: E = 1.0 / EPS; break; + case INVERSE_VOLUME: + E = 1.0 / ElemVolume; + break; + case SOLID_WALL_DISTANCE: + E = 1.0 / ElemDistance; + break; + case CONSTANT_STIFFNESS: + E = 1.0 / EPS; + break; } Nu = config->GetDeform_Coeff(); - Mu = E / (2.0*(1.0 + Nu)); - Lambda = Nu*E/((1.0+Nu)*(1.0-2.0*Nu)); + Mu = E / (2.0 * (1.0 + Nu)); + Lambda = Nu * E / ((1.0 + Nu) * (1.0 - 2.0 * Nu)); /*--- Compute the D Matrix (for plane strain and 3-D)---*/ - D_Matrix[0][0] = Lambda + 2.0*Mu; D_Matrix[0][1] = Lambda; D_Matrix[0][2] = Lambda; - D_Matrix[1][0] = Lambda; D_Matrix[1][1] = Lambda + 2.0*Mu; D_Matrix[1][2] = Lambda; - D_Matrix[2][0] = Lambda; D_Matrix[2][1] = Lambda; D_Matrix[2][2] = Lambda + 2.0*Mu; + D_Matrix[0][0] = Lambda + 2.0 * Mu; + D_Matrix[0][1] = Lambda; + D_Matrix[0][2] = Lambda; + D_Matrix[1][0] = Lambda; + D_Matrix[1][1] = Lambda + 2.0 * Mu; + D_Matrix[1][2] = Lambda; + D_Matrix[2][0] = Lambda; + D_Matrix[2][1] = Lambda; + D_Matrix[2][2] = Lambda + 2.0 * Mu; D_Matrix[3][3] = Mu; D_Matrix[4][4] = Mu; D_Matrix[5][5] = Mu; - /*--- Compute the BT.D Matrix ---*/ - for (iVar = 0; iVar < nNodes*nVar; iVar++) { + for (iVar = 0; iVar < nNodes * nVar; iVar++) { for (jVar = 0; jVar < 6; jVar++) { Aux_Matrix[iVar][jVar] = 0.0; - for (kVar = 0; kVar < 6; kVar++) - Aux_Matrix[iVar][jVar] += B_Matrix[kVar][iVar]*D_Matrix[kVar][jVar]; + for (kVar = 0; kVar < 6; kVar++) Aux_Matrix[iVar][jVar] += B_Matrix[kVar][iVar] * D_Matrix[kVar][jVar]; } } /*--- Compute the BT.D.B Matrix (stiffness matrix), and add to the original matrix using Gauss integration ---*/ - for (iVar = 0; iVar < nNodes*nVar; iVar++) { - for (jVar = 0; jVar < nNodes*nVar; jVar++) { + for (iVar = 0; iVar < nNodes * nVar; iVar++) { + for (jVar = 0; jVar < nNodes * nVar; jVar++) { for (kVar = 0; kVar < 6; kVar++) { - StiffMatrix_Elem[iVar][jVar] += Weight[iGauss] * Aux_Matrix[iVar][kVar]*B_Matrix[kVar][jVar] * fabs(Det); + StiffMatrix_Elem[iVar][jVar] += Weight[iGauss] * Aux_Matrix[iVar][kVar] * B_Matrix[kVar][jVar] * fabs(Det); } } } - } - } -void CVolumetricMovement::AddFEA_StiffMatrix(CGeometry *geometry, su2double **StiffMatrix_Elem, unsigned long PointCorners[8], unsigned short nNodes) { - +void CVolumetricMovement::AddFEA_StiffMatrix(CGeometry* geometry, su2double** StiffMatrix_Elem, + unsigned long PointCorners[8], unsigned short nNodes) { unsigned short iVar, jVar, iDim, jDim; unsigned short nVar = geometry->GetnDim(); - su2double **StiffMatrix_Node; - StiffMatrix_Node = new su2double* [nVar]; - for (iVar = 0; iVar < nVar; iVar++) - StiffMatrix_Node[iVar] = new su2double [nVar]; + su2double** StiffMatrix_Node; + StiffMatrix_Node = new su2double*[nVar]; + for (iVar = 0; iVar < nVar; iVar++) StiffMatrix_Node[iVar] = new su2double[nVar]; for (iVar = 0; iVar < nVar; iVar++) - for (jVar = 0; jVar < nVar; jVar++) - StiffMatrix_Node[iVar][jVar] = 0.0; + for (jVar = 0; jVar < nVar; jVar++) StiffMatrix_Node[iVar][jVar] = 0.0; /*--- Transform the stiffness matrix for the hexahedral element into the contributions for the individual nodes relative to each other. ---*/ for (iVar = 0; iVar < nNodes; iVar++) { for (jVar = 0; jVar < nNodes; jVar++) { - for (iDim = 0; iDim < nVar; iDim++) { for (jDim = 0; jDim < nVar; jDim++) { - StiffMatrix_Node[iDim][jDim] = StiffMatrix_Elem[(iVar*nVar)+iDim][(jVar*nVar)+jDim]; + StiffMatrix_Node[iDim][jDim] = StiffMatrix_Elem[(iVar * nVar) + iDim][(jVar * nVar) + jDim]; } } StiffMatrix.AddBlock(PointCorners[iVar], PointCorners[jVar], StiffMatrix_Node); - } } /*--- Deallocate memory and exit ---*/ - for (iVar = 0; iVar < nVar; iVar++) - delete [] StiffMatrix_Node[iVar]; - delete [] StiffMatrix_Node; - + for (iVar = 0; iVar < nVar; iVar++) delete[] StiffMatrix_Node[iVar]; + delete[] StiffMatrix_Node; } -void CVolumetricMovement::SetBoundaryDisplacements(CGeometry *geometry, CConfig *config) { - +void CVolumetricMovement::SetBoundaryDisplacements(CGeometry* geometry, CConfig* config) { unsigned short iDim, nDim = geometry->GetnDim(), iMarker, axis = 0; unsigned long iPoint, total_index, iVertex; - su2double *VarCoord, MeanCoord[3] = {0.0,0.0,0.0}, VarIncrement = 1.0; + su2double *VarCoord, MeanCoord[3] = {0.0, 0.0, 0.0}, VarIncrement = 1.0; /*--- Get the SU2 module. SU2_CFD will use this routine for dynamically deforming meshes (MARKER_MOVING), while SU2_DEF will use it for deforming @@ -1575,7 +1657,7 @@ void CVolumetricMovement::SetBoundaryDisplacements(CGeometry *geometry, CConfig increments and solve the grid deformation equations iteratively with successive small deformations. ---*/ - VarIncrement = 1.0/((su2double)config->GetGridDef_Nonlinear_Iter()); + VarIncrement = 1.0 / ((su2double)config->GetGridDef_Nonlinear_Iter()); /*--- As initialization, set to zero displacements of all the surfaces except the symmetry plane (which is treated specially, see below), internal and the send-receive boundaries ---*/ @@ -1587,7 +1669,7 @@ void CVolumetricMovement::SetBoundaryDisplacements(CGeometry *geometry, CConfig for (iVertex = 0; iVertex < geometry->nVertex[iMarker]; iVertex++) { iPoint = geometry->vertex[iMarker][iVertex]->GetNode(); for (iDim = 0; iDim < nDim; iDim++) { - total_index = iPoint*nDim + iDim; + total_index = iPoint * nDim + iDim; LinSysRes[total_index] = 0.0; LinSysSol[total_index] = 0.0; StiffMatrix.DeleteValsRowi(total_index); @@ -1602,13 +1684,14 @@ void CVolumetricMovement::SetBoundaryDisplacements(CGeometry *geometry, CConfig for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { if (((config->GetMarker_All_Moving(iMarker) == YES) && (Kind_SU2 == SU2_COMPONENT::SU2_CFD)) || ((config->GetMarker_All_DV(iMarker) == YES) && (Kind_SU2 == SU2_COMPONENT::SU2_DEF)) || - ((config->GetDirectDiff() == D_DESIGN) && (Kind_SU2 == SU2_COMPONENT::SU2_CFD) && (config->GetMarker_All_DV(iMarker) == YES)) || + ((config->GetDirectDiff() == D_DESIGN) && (Kind_SU2 == SU2_COMPONENT::SU2_CFD) && + (config->GetMarker_All_DV(iMarker) == YES)) || ((config->GetMarker_All_DV(iMarker) == YES) && (Kind_SU2 == SU2_COMPONENT::SU2_DOT))) { for (iVertex = 0; iVertex < geometry->nVertex[iMarker]; iVertex++) { iPoint = geometry->vertex[iMarker][iVertex]->GetNode(); VarCoord = geometry->vertex[iMarker][iVertex]->GetVarCoord(); for (iDim = 0; iDim < nDim; iDim++) { - total_index = iPoint*nDim + iDim; + total_index = iPoint * nDim + iDim; LinSysRes[total_index] = SU2_TYPE::GetValue(VarCoord[iDim] * VarIncrement); LinSysSol[total_index] = SU2_TYPE::GetValue(VarCoord[iDim] * VarIncrement); StiffMatrix.DeleteValsRowi(total_index); @@ -1620,37 +1703,35 @@ void CVolumetricMovement::SetBoundaryDisplacements(CGeometry *geometry, CConfig /*--- Set to zero displacements of the normal component for the symmetry plane condition ---*/ for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { - if ((config->GetMarker_All_KindBC(iMarker) == SYMMETRY_PLANE) ) { - - su2double *Coord_0 = nullptr; + if ((config->GetMarker_All_KindBC(iMarker) == SYMMETRY_PLANE)) { + su2double* Coord_0 = nullptr; for (iDim = 0; iDim < nDim; iDim++) MeanCoord[iDim] = 0.0; /*--- Store the coord of the first point to help identify the axis. ---*/ - iPoint = geometry->vertex[iMarker][0]->GetNode(); + iPoint = geometry->vertex[iMarker][0]->GetNode(); Coord_0 = geometry->nodes->GetCoord(iPoint); for (iVertex = 0; iVertex < geometry->nVertex[iMarker]; iVertex++) { iPoint = geometry->vertex[iMarker][iVertex]->GetNode(); VarCoord = geometry->nodes->GetCoord(iPoint); for (iDim = 0; iDim < nDim; iDim++) - MeanCoord[iDim] += (VarCoord[iDim]-Coord_0[iDim])*(VarCoord[iDim]-Coord_0[iDim]); + MeanCoord[iDim] += (VarCoord[iDim] - Coord_0[iDim]) * (VarCoord[iDim] - Coord_0[iDim]); } for (iDim = 0; iDim < nDim; iDim++) MeanCoord[iDim] = sqrt(MeanCoord[iDim]); - if (nDim==3) { + if (nDim == 3) { if ((MeanCoord[0] <= MeanCoord[1]) && (MeanCoord[0] <= MeanCoord[2])) axis = 0; if ((MeanCoord[1] <= MeanCoord[0]) && (MeanCoord[1] <= MeanCoord[2])) axis = 1; if ((MeanCoord[2] <= MeanCoord[0]) && (MeanCoord[2] <= MeanCoord[1])) axis = 2; - } - else { - if ((MeanCoord[0] <= MeanCoord[1]) ) axis = 0; - if ((MeanCoord[1] <= MeanCoord[0]) ) axis = 1; + } else { + if ((MeanCoord[0] <= MeanCoord[1])) axis = 0; + if ((MeanCoord[1] <= MeanCoord[0])) axis = 1; } for (iVertex = 0; iVertex < geometry->nVertex[iMarker]; iVertex++) { iPoint = geometry->vertex[iMarker][iVertex]->GetNode(); - total_index = iPoint*nDim + axis; + total_index = iPoint * nDim + axis; LinSysRes[total_index] = 0.0; LinSysSol[total_index] = 0.0; StiffMatrix.DeleteValsRowi(total_index); @@ -1665,7 +1746,7 @@ void CVolumetricMovement::SetBoundaryDisplacements(CGeometry *geometry, CConfig for (iVertex = 0; iVertex < geometry->nVertex[iMarker]; iVertex++) { iPoint = geometry->vertex[iMarker][iVertex]->GetNode(); for (iDim = 0; iDim < nDim; iDim++) { - total_index = iPoint*nDim + iDim; + total_index = iPoint * nDim + iDim; LinSysRes[total_index] = 0.0; LinSysSol[total_index] = 0.0; StiffMatrix.DeleteValsRowi(total_index); @@ -1682,7 +1763,7 @@ void CVolumetricMovement::SetBoundaryDisplacements(CGeometry *geometry, CConfig iPoint = geometry->vertex[iMarker][iVertex]->GetNode(); VarCoord = geometry->vertex[iMarker][iVertex]->GetVarCoord(); for (iDim = 0; iDim < nDim; iDim++) { - total_index = iPoint*nDim + iDim; + total_index = iPoint * nDim + iDim; LinSysRes[total_index] = SU2_TYPE::GetValue(VarCoord[iDim] * VarIncrement); LinSysSol[total_index] = SU2_TYPE::GetValue(VarCoord[iDim] * VarIncrement); StiffMatrix.DeleteValsRowi(total_index); @@ -1690,14 +1771,14 @@ void CVolumetricMovement::SetBoundaryDisplacements(CGeometry *geometry, CConfig } } } - } -void CVolumetricMovement::SetBoundaryDerivatives(CGeometry *geometry, CConfig *config, bool ForwardProjectionDerivative) { +void CVolumetricMovement::SetBoundaryDerivatives(CGeometry* geometry, CConfig* config, + bool ForwardProjectionDerivative) { unsigned short iDim, iMarker; unsigned long iPoint, total_index, iVertex; - su2double * VarCoord; + su2double* VarCoord; SU2_COMPONENT Kind_SU2 = config->GetKind_SU2(); if ((config->GetDirectDiff() == D_DESIGN) && (Kind_SU2 == SU2_COMPONENT::SU2_CFD)) { for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { @@ -1706,7 +1787,7 @@ void CVolumetricMovement::SetBoundaryDerivatives(CGeometry *geometry, CConfig *c iPoint = geometry->vertex[iMarker][iVertex]->GetNode(); VarCoord = geometry->vertex[iMarker][iVertex]->GetVarCoord(); for (iDim = 0; iDim < nDim; iDim++) { - total_index = iPoint*nDim + iDim; + total_index = iPoint * nDim + iDim; LinSysRes[total_index] = SU2_TYPE::GetDerivative(VarCoord[iDim]); LinSysSol[total_index] = SU2_TYPE::GetDerivative(VarCoord[iDim]); } @@ -1714,11 +1795,10 @@ void CVolumetricMovement::SetBoundaryDerivatives(CGeometry *geometry, CConfig *c } } if (LinSysRes.norm() == 0.0) cout << "Warning: Derivatives are zero!" << endl; - } else if ((Kind_SU2 == SU2_COMPONENT::SU2_DOT) && !ForwardProjectionDerivative ) { - + } else if ((Kind_SU2 == SU2_COMPONENT::SU2_DOT) && !ForwardProjectionDerivative) { for (iPoint = 0; iPoint < nPoint; iPoint++) { for (iDim = 0; iDim < nDim; iDim++) { - total_index = iPoint*nDim + iDim; + total_index = iPoint * nDim + iDim; LinSysRes[total_index] = SU2_TYPE::GetValue(geometry->GetSensitivity(iPoint, iDim)); LinSysSol[total_index] = SU2_TYPE::GetValue(geometry->GetSensitivity(iPoint, iDim)); } @@ -1729,7 +1809,7 @@ void CVolumetricMovement::SetBoundaryDerivatives(CGeometry *geometry, CConfig *c for (iVertex = 0; iVertex < geometry->nVertex[iMarker]; iVertex++) { iPoint = geometry->vertex[iMarker][iVertex]->GetNode(); for (iDim = 0; iDim < nDim; iDim++) { - total_index = iPoint*nDim + iDim; + total_index = iPoint * nDim + iDim; LinSysRes[total_index] = SU2_TYPE::GetValue(geometry->GetSensitivity(iPoint, iDim)); LinSysSol[total_index] = SU2_TYPE::GetValue(geometry->GetSensitivity(iPoint, iDim)); } @@ -1740,10 +1820,11 @@ void CVolumetricMovement::SetBoundaryDerivatives(CGeometry *geometry, CConfig *c } } -void CVolumetricMovement::UpdateGridCoord_Derivatives(CGeometry *geometry, CConfig *config, bool ForwardProjectionDerivative) { +void CVolumetricMovement::UpdateGridCoord_Derivatives(CGeometry* geometry, CConfig* config, + bool ForwardProjectionDerivative) { unsigned short iDim, iMarker; unsigned long iPoint, total_index, iVertex; - su2double *new_coord = new su2double[3]; + su2double* new_coord = new su2double[3]; SU2_COMPONENT Kind_SU2 = config->GetKind_SU2(); @@ -1751,9 +1832,11 @@ void CVolumetricMovement::UpdateGridCoord_Derivatives(CGeometry *geometry, CConf after grid deformation (LinSysSol contains the derivatives of the x, y, z displacements). ---*/ if ((config->GetDirectDiff() == D_DESIGN) && (Kind_SU2 == SU2_COMPONENT::SU2_CFD)) { for (iPoint = 0; iPoint < geometry->GetnPoint(); iPoint++) { - new_coord[0] = 0.0; new_coord[1] = 0.0; new_coord[2] = 0.0; + new_coord[0] = 0.0; + new_coord[1] = 0.0; + new_coord[2] = 0.0; for (iDim = 0; iDim < nDim; iDim++) { - total_index = iPoint*nDim + iDim; + total_index = iPoint * nDim + iDim; new_coord[iDim] = geometry->nodes->GetCoord(iPoint, iDim); SU2_TYPE::SetDerivative(new_coord[iDim], SU2_TYPE::GetValue(LinSysSol[total_index])); } @@ -1764,19 +1847,19 @@ void CVolumetricMovement::UpdateGridCoord_Derivatives(CGeometry *geometry, CConf if (config->GetSmoothGradient()) { for (iPoint = 0; iPoint < geometry->GetnPoint(); iPoint++) { for (iDim = 0; iDim < nDim; iDim++) { - total_index = iPoint*nDim + iDim; - geometry->SetSensitivity(iPoint,iDim, 0.0); + total_index = iPoint * nDim + iDim; + geometry->SetSensitivity(iPoint, iDim, 0.0); } } } for (iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { - if(config->GetSolid_Wall(iMarker) || (config->GetMarker_All_DV(iMarker) == YES)) { + if (config->GetSolid_Wall(iMarker) || (config->GetMarker_All_DV(iMarker) == YES)) { for (iVertex = 0; iVertex < geometry->nVertex[iMarker]; iVertex++) { iPoint = geometry->vertex[iMarker][iVertex]->GetNode(); if (geometry->nodes->GetDomain(iPoint)) { for (iDim = 0; iDim < nDim; iDim++) { - total_index = iPoint*nDim + iDim; - geometry->SetSensitivity(iPoint,iDim, LinSysSol[total_index]); + total_index = iPoint * nDim + iDim; + geometry->SetSensitivity(iPoint, iDim, LinSysSol[total_index]); } } } @@ -1785,22 +1868,20 @@ void CVolumetricMovement::UpdateGridCoord_Derivatives(CGeometry *geometry, CConf } else if (config->GetSmoothGradient() && ForwardProjectionDerivative) { for (iPoint = 0; iPoint < geometry->GetnPoint(); iPoint++) { for (iDim = 0; iDim < nDim; iDim++) { - total_index = iPoint*nDim + iDim; - geometry->SetSensitivity(iPoint,iDim, LinSysSol[total_index]); + total_index = iPoint * nDim + iDim; + geometry->SetSensitivity(iPoint, iDim, LinSysSol[total_index]); } } } - delete [] new_coord; + delete[] new_coord; } -void CVolumetricMovement::SetDomainDisplacements(CGeometry *geometry, CConfig *config) { - +void CVolumetricMovement::SetDomainDisplacements(CGeometry* geometry, CConfig* config) { unsigned short iDim, nDim = geometry->GetnDim(); unsigned long iPoint, total_index; if (config->GetHold_GridFixed()) { - auto MinCoordValues = config->GetHold_GridFixed_Coord(); auto MaxCoordValues = &config->GetHold_GridFixed_Coord()[3]; @@ -1811,7 +1892,7 @@ void CVolumetricMovement::SetDomainDisplacements(CGeometry *geometry, CConfig *c auto Coord = geometry->nodes->GetCoord(iPoint); for (iDim = 0; iDim < nDim; iDim++) { if ((Coord[iDim] < MinCoordValues[iDim]) || (Coord[iDim] > MaxCoordValues[iDim])) { - total_index = iPoint*nDim + iDim; + total_index = iPoint * nDim + iDim; LinSysRes[total_index] = 0.0; LinSysSol[total_index] = 0.0; StiffMatrix.DeleteValsRowi(total_index); @@ -1827,7 +1908,7 @@ void CVolumetricMovement::SetDomainDisplacements(CGeometry *geometry, CConfig *c for (iPoint = 0; iPoint < nPoint; iPoint++) { if (geometry->nodes->GetWall_Distance(iPoint) >= config->GetDeform_Limit()) { for (iDim = 0; iDim < nDim; iDim++) { - total_index = iPoint*nDim + iDim; + total_index = iPoint * nDim + iDim; LinSysRes[total_index] = 0.0; LinSysSol[total_index] = 0.0; StiffMatrix.DeleteValsRowi(total_index); @@ -1835,20 +1916,18 @@ void CVolumetricMovement::SetDomainDisplacements(CGeometry *geometry, CConfig *c } } } - } -void CVolumetricMovement::Rigid_Rotation(CGeometry *geometry, CConfig *config, - unsigned short iZone, unsigned long iter) { - +void CVolumetricMovement::Rigid_Rotation(CGeometry* geometry, CConfig* config, unsigned short iZone, + unsigned long iter) { /*--- Local variables ---*/ unsigned short iDim, nDim; unsigned long iPoint; - su2double r[3] = {0.0,0.0,0.0}, rotCoord[3] = {0.0,0.0,0.0}, *Coord; - su2double Center[3] = {0.0,0.0,0.0}, Omega[3] = {0.0,0.0,0.0}, Lref; - su2double dt, Center_Moment[3] = {0.0,0.0,0.0}; - su2double *GridVel, newGridVel[3] = {0.0,0.0,0.0}; - su2double rotMatrix[3][3] = {{0.0,0.0,0.0}, {0.0,0.0,0.0}, {0.0,0.0,0.0}}; + su2double r[3] = {0.0, 0.0, 0.0}, rotCoord[3] = {0.0, 0.0, 0.0}, *Coord; + su2double Center[3] = {0.0, 0.0, 0.0}, Omega[3] = {0.0, 0.0, 0.0}, Lref; + su2double dt, Center_Moment[3] = {0.0, 0.0, 0.0}; + su2double *GridVel, newGridVel[3] = {0.0, 0.0, 0.0}; + su2double rotMatrix[3][3] = {{0.0, 0.0, 0.0}, {0.0, 0.0, 0.0}, {0.0, 0.0, 0.0}}; su2double dtheta, dphi, dpsi, cosTheta, sinTheta; su2double cosPhi, sinPhi, cosPsi, sinPsi; bool harmonic_balance = (config->GetTime_Marching() == TIME_MARCHING::HARMONIC_BALANCE); @@ -1856,15 +1935,16 @@ void CVolumetricMovement::Rigid_Rotation(CGeometry *geometry, CConfig *config, /*--- Problem dimension and physical time step ---*/ nDim = geometry->GetnDim(); - dt = config->GetDelta_UnstTimeND(); + dt = config->GetDelta_UnstTimeND(); Lref = config->GetLength_Ref(); /*--- For the unsteady adjoint, use reverse time ---*/ if (adjoint) { /*--- Set the first adjoint mesh position to the final direct one ---*/ - if (iter == 0) dt = ((su2double)config->GetnTime_Iter()-1)*dt; + if (iter == 0) dt = ((su2double)config->GetnTime_Iter() - 1) * dt; /*--- Reverse the rotation direction for the adjoint ---*/ - else dt = -1.0*dt; + else + dt = -1.0 * dt; } else { /*--- No rotation at all for the first direct solution ---*/ if (iter == 0) dt = 0; @@ -1872,9 +1952,9 @@ void CVolumetricMovement::Rigid_Rotation(CGeometry *geometry, CConfig *config, /*--- Center of rotation & angular velocity vector from config ---*/ - for (iDim = 0; iDim < 3; iDim++){ + for (iDim = 0; iDim < 3; iDim++) { Center[iDim] = config->GetMotion_Origin(iDim); - Omega[iDim] = config->GetRotation_Rate(iDim)/config->GetOmega_Ref(); + Omega[iDim] = config->GetRotation_Rate(iDim) / config->GetOmega_Ref(); } /*-- Set dt for harmonic balance cases ---*/ @@ -1882,14 +1962,14 @@ void CVolumetricMovement::Rigid_Rotation(CGeometry *geometry, CConfig *config, /*--- period of oscillation & compute time interval using nTimeInstances ---*/ su2double period = config->GetHarmonicBalance_Period(); period /= config->GetTime_Ref(); - dt = period * (su2double)iter/(su2double)(config->GetnTimeInstances()); + dt = period * (su2double)iter / (su2double)(config->GetnTimeInstances()); } /*--- Compute delta change in the angle about the x, y, & z axes. ---*/ - dtheta = Omega[0]*dt; - dphi = Omega[1]*dt; - dpsi = Omega[2]*dt; + dtheta = Omega[0] * dt; + dphi = Omega[1] * dt; + dpsi = Omega[2] * dt; if (rank == MASTER_NODE && iter == 0) { cout << " Angular velocity: (" << Omega[0] << ", " << Omega[1]; @@ -1898,56 +1978,53 @@ void CVolumetricMovement::Rigid_Rotation(CGeometry *geometry, CConfig *config, /*--- Store angles separately for clarity. Compute sines/cosines. ---*/ - cosTheta = cos(dtheta); cosPhi = cos(dphi); cosPsi = cos(dpsi); - sinTheta = sin(dtheta); sinPhi = sin(dphi); sinPsi = sin(dpsi); + cosTheta = cos(dtheta); + cosPhi = cos(dphi); + cosPsi = cos(dpsi); + sinTheta = sin(dtheta); + sinPhi = sin(dphi); + sinPsi = sin(dpsi); /*--- Compute the rotation matrix. Note that the implicit ordering is rotation about the x-axis, y-axis, then z-axis. ---*/ - rotMatrix[0][0] = cosPhi*cosPsi; - rotMatrix[1][0] = cosPhi*sinPsi; + rotMatrix[0][0] = cosPhi * cosPsi; + rotMatrix[1][0] = cosPhi * sinPsi; rotMatrix[2][0] = -sinPhi; - rotMatrix[0][1] = sinTheta*sinPhi*cosPsi - cosTheta*sinPsi; - rotMatrix[1][1] = sinTheta*sinPhi*sinPsi + cosTheta*cosPsi; - rotMatrix[2][1] = sinTheta*cosPhi; + rotMatrix[0][1] = sinTheta * sinPhi * cosPsi - cosTheta * sinPsi; + rotMatrix[1][1] = sinTheta * sinPhi * sinPsi + cosTheta * cosPsi; + rotMatrix[2][1] = sinTheta * cosPhi; - rotMatrix[0][2] = cosTheta*sinPhi*cosPsi + sinTheta*sinPsi; - rotMatrix[1][2] = cosTheta*sinPhi*sinPsi - sinTheta*cosPsi; - rotMatrix[2][2] = cosTheta*cosPhi; + rotMatrix[0][2] = cosTheta * sinPhi * cosPsi + sinTheta * sinPsi; + rotMatrix[1][2] = cosTheta * sinPhi * sinPsi - sinTheta * cosPsi; + rotMatrix[2][2] = cosTheta * cosPhi; /*--- Loop over and rotate each node in the volume mesh ---*/ for (iPoint = 0; iPoint < geometry->GetnPoint(); iPoint++) { - /*--- Coordinates of the current point ---*/ - Coord = geometry->nodes->GetCoord(iPoint); + Coord = geometry->nodes->GetCoord(iPoint); GridVel = geometry->nodes->GetGridVel(iPoint); /*--- Calculate non-dim. position from rotation center ---*/ - r[0] = (Coord[0]-Center[0])/Lref; - r[1] = (Coord[1]-Center[1])/Lref; - if (nDim == 3) r[2] = (Coord[2]-Center[2])/Lref; + r[0] = (Coord[0] - Center[0]) / Lref; + r[1] = (Coord[1] - Center[1]) / Lref; + if (nDim == 3) r[2] = (Coord[2] - Center[2]) / Lref; /*--- Compute transformed point coordinates ---*/ - rotCoord[0] = rotMatrix[0][0]*r[0] - + rotMatrix[0][1]*r[1] - + rotMatrix[0][2]*r[2]; + rotCoord[0] = rotMatrix[0][0] * r[0] + rotMatrix[0][1] * r[1] + rotMatrix[0][2] * r[2]; - rotCoord[1] = rotMatrix[1][0]*r[0] - + rotMatrix[1][1]*r[1] - + rotMatrix[1][2]*r[2]; + rotCoord[1] = rotMatrix[1][0] * r[0] + rotMatrix[1][1] * r[1] + rotMatrix[1][2] * r[2]; - rotCoord[2] = rotMatrix[2][0]*r[0] - + rotMatrix[2][1]*r[1] - + rotMatrix[2][2]*r[2]; + rotCoord[2] = rotMatrix[2][0] * r[0] + rotMatrix[2][1] * r[1] + rotMatrix[2][2] * r[2]; /*--- Cross Product of angular velocity and distance from center. Note that we have assumed the grid velocities have been set to an initial value in the plunging routine. ---*/ - newGridVel[0] = GridVel[0] + Omega[1]*rotCoord[2] - Omega[2]*rotCoord[1]; - newGridVel[1] = GridVel[1] + Omega[2]*rotCoord[0] - Omega[0]*rotCoord[2]; - if (nDim == 3) newGridVel[2] = GridVel[2] + Omega[0]*rotCoord[1] - Omega[1]*rotCoord[0]; + newGridVel[0] = GridVel[0] + Omega[1] * rotCoord[2] - Omega[2] * rotCoord[1]; + newGridVel[1] = GridVel[1] + Omega[2] * rotCoord[0] - Omega[0] * rotCoord[2]; + if (nDim == 3) newGridVel[2] = GridVel[2] + Omega[0] * rotCoord[1] - Omega[1] * rotCoord[0]; /*--- Store new node location & grid velocity. Add center. Do not store the grid velocity if this is an adjoint calculation.---*/ @@ -1955,61 +2032,51 @@ void CVolumetricMovement::Rigid_Rotation(CGeometry *geometry, CConfig *config, for (iDim = 0; iDim < nDim; iDim++) { geometry->nodes->SetCoord(iPoint, iDim, rotCoord[iDim] + Center[iDim]); if (!adjoint) geometry->nodes->SetGridVel(iPoint, iDim, newGridVel[iDim]); - } } /*--- Set the moment computation center to the new location after incrementing the position with the rotation. ---*/ - for (unsigned short jMarker=0; jMarkerGetnMarker_Monitoring(); jMarker++) { - + for (unsigned short jMarker = 0; jMarker < config->GetnMarker_Monitoring(); jMarker++) { Center_Moment[0] = config->GetRefOriginMoment_X(jMarker); Center_Moment[1] = config->GetRefOriginMoment_Y(jMarker); Center_Moment[2] = config->GetRefOriginMoment_Z(jMarker); /*--- Calculate non-dim. position from rotation center ---*/ - for (iDim = 0; iDim < nDim; iDim++) - r[iDim] = (Center_Moment[iDim]-Center[iDim])/Lref; + for (iDim = 0; iDim < nDim; iDim++) r[iDim] = (Center_Moment[iDim] - Center[iDim]) / Lref; if (nDim == 2) r[nDim] = 0.0; /*--- Compute transformed point coordinates ---*/ - rotCoord[0] = rotMatrix[0][0]*r[0] - + rotMatrix[0][1]*r[1] - + rotMatrix[0][2]*r[2]; + rotCoord[0] = rotMatrix[0][0] * r[0] + rotMatrix[0][1] * r[1] + rotMatrix[0][2] * r[2]; - rotCoord[1] = rotMatrix[1][0]*r[0] - + rotMatrix[1][1]*r[1] - + rotMatrix[1][2]*r[2]; + rotCoord[1] = rotMatrix[1][0] * r[0] + rotMatrix[1][1] * r[1] + rotMatrix[1][2] * r[2]; - rotCoord[2] = rotMatrix[2][0]*r[0] - + rotMatrix[2][1]*r[1] - + rotMatrix[2][2]*r[2]; + rotCoord[2] = rotMatrix[2][0] * r[0] + rotMatrix[2][1] * r[1] + rotMatrix[2][2] * r[2]; - config->SetRefOriginMoment_X(jMarker, Center[0]+rotCoord[0]); - config->SetRefOriginMoment_Y(jMarker, Center[1]+rotCoord[1]); - config->SetRefOriginMoment_Z(jMarker, Center[2]+rotCoord[2]); + config->SetRefOriginMoment_X(jMarker, Center[0] + rotCoord[0]); + config->SetRefOriginMoment_Y(jMarker, Center[1] + rotCoord[1]); + config->SetRefOriginMoment_Z(jMarker, Center[2] + rotCoord[2]); } /*--- After moving all nodes, update geometry class ---*/ UpdateDualGrid(geometry, config); - } -void CVolumetricMovement::Rigid_Pitching(CGeometry *geometry, CConfig *config, unsigned short iZone, unsigned long iter) { - +void CVolumetricMovement::Rigid_Pitching(CGeometry* geometry, CConfig* config, unsigned short iZone, + unsigned long iter) { /*--- Local variables ---*/ - su2double r[3] = {0.0,0.0,0.0}, rotCoord[3] = {0.0,0.0,0.0}, *Coord, Center[3] = {0.0,0.0,0.0}, - Omega[3] = {0.0,0.0,0.0}, Ampl[3] = {0.0,0.0,0.0}, Phase[3] = {0.0,0.0,0.0}; - su2double Lref, deltaT, alphaDot[3], *GridVel, newGridVel[3] = {0.0,0.0,0.0}; - su2double rotMatrix[3][3] = {{0.0,0.0,0.0}, {0.0,0.0,0.0}, {0.0,0.0,0.0}}; + su2double r[3] = {0.0, 0.0, 0.0}, rotCoord[3] = {0.0, 0.0, 0.0}, *Coord, Center[3] = {0.0, 0.0, 0.0}, + Omega[3] = {0.0, 0.0, 0.0}, Ampl[3] = {0.0, 0.0, 0.0}, Phase[3] = {0.0, 0.0, 0.0}; + su2double Lref, deltaT, alphaDot[3], *GridVel, newGridVel[3] = {0.0, 0.0, 0.0}; + su2double rotMatrix[3][3] = {{0.0, 0.0, 0.0}, {0.0, 0.0, 0.0}, {0.0, 0.0, 0.0}}; su2double dtheta, dphi, dpsi, cosTheta, sinTheta; su2double cosPhi, sinPhi, cosPsi, sinPsi; su2double time_new, time_old; - su2double DEG2RAD = PI_NUMBER/180.0; + su2double DEG2RAD = PI_NUMBER / 180.0; unsigned short iDim; unsigned short nDim = geometry->GetnDim(); unsigned long iPoint; @@ -2018,127 +2085,122 @@ void CVolumetricMovement::Rigid_Pitching(CGeometry *geometry, CConfig *config, u /*--- Retrieve values from the config file ---*/ deltaT = config->GetDelta_UnstTimeND(); - Lref = config->GetLength_Ref(); + Lref = config->GetLength_Ref(); /*--- Pitching origin, frequency, and amplitude from config. ---*/ - for (iDim = 0; iDim < 3; iDim++){ + for (iDim = 0; iDim < 3; iDim++) { Center[iDim] = config->GetMotion_Origin(iDim); - Omega[iDim] = config->GetPitching_Omega(iDim)/config->GetOmega_Ref(); - Ampl[iDim] = config->GetPitching_Ampl(iDim)*DEG2RAD; - Phase[iDim] = config->GetPitching_Phase(iDim)*DEG2RAD; + Omega[iDim] = config->GetPitching_Omega(iDim) / config->GetOmega_Ref(); + Ampl[iDim] = config->GetPitching_Ampl(iDim) * DEG2RAD; + Phase[iDim] = config->GetPitching_Phase(iDim) * DEG2RAD; } - if (harmonic_balance) { /*--- period of oscillation & compute time interval using nTimeInstances ---*/ su2double period = config->GetHarmonicBalance_Period(); period /= config->GetTime_Ref(); - deltaT = period/(su2double)(config->GetnTimeInstances()); + deltaT = period / (su2double)(config->GetnTimeInstances()); } /*--- Compute delta time based on physical time step ---*/ if (adjoint) { /*--- For the unsteady adjoint, we integrate backwards through physical time, so perform mesh motion in reverse. ---*/ - unsigned long nFlowIter = config->GetnTime_Iter(); + unsigned long nFlowIter = config->GetnTime_Iter(); unsigned long directIter = nFlowIter - iter - 1; - time_new = static_cast(directIter)*deltaT; + time_new = static_cast(directIter) * deltaT; time_old = time_new; - if (iter != 0) time_old = (static_cast(directIter)+1.0)*deltaT; + if (iter != 0) time_old = (static_cast(directIter) + 1.0) * deltaT; } else { /*--- Forward time for the direct problem ---*/ - time_new = static_cast(iter)*deltaT; + time_new = static_cast(iter) * deltaT; if (harmonic_balance) { /*--- For harmonic balance, begin movement from the zero position ---*/ time_old = 0.0; } else { time_old = time_new; - if (iter != 0) time_old = (static_cast(iter)-1.0)*deltaT; + if (iter != 0) time_old = (static_cast(iter) - 1.0) * deltaT; } } /*--- Compute delta change in the angle about the x, y, & z axes. ---*/ - dtheta = -Ampl[0]*(sin(Omega[0]*time_new + Phase[0]) - sin(Omega[0]*time_old + Phase[0])); - dphi = -Ampl[1]*(sin(Omega[1]*time_new + Phase[1]) - sin(Omega[1]*time_old + Phase[1])); - dpsi = -Ampl[2]*(sin(Omega[2]*time_new + Phase[2]) - sin(Omega[2]*time_old + Phase[2])); + dtheta = -Ampl[0] * (sin(Omega[0] * time_new + Phase[0]) - sin(Omega[0] * time_old + Phase[0])); + dphi = -Ampl[1] * (sin(Omega[1] * time_new + Phase[1]) - sin(Omega[1] * time_old + Phase[1])); + dpsi = -Ampl[2] * (sin(Omega[2] * time_new + Phase[2]) - sin(Omega[2] * time_old + Phase[2])); /*--- Angular velocity at the new time ---*/ - alphaDot[0] = -Omega[0]*Ampl[0]*cos(Omega[0]*time_new + Phase[0]); - alphaDot[1] = -Omega[1]*Ampl[1]*cos(Omega[1]*time_new + Phase[1]); - alphaDot[2] = -Omega[2]*Ampl[2]*cos(Omega[2]*time_new + Phase[2]); + alphaDot[0] = -Omega[0] * Ampl[0] * cos(Omega[0] * time_new + Phase[0]); + alphaDot[1] = -Omega[1] * Ampl[1] * cos(Omega[1] * time_new + Phase[1]); + alphaDot[2] = -Omega[2] * Ampl[2] * cos(Omega[2] * time_new + Phase[2]); if (rank == MASTER_NODE && iter == 0) { - cout << " Pitching frequency: (" << Omega[0] << ", " << Omega[1]; - cout << ", " << Omega[2] << ") rad/s." << endl; - cout << " Pitching amplitude: (" << Ampl[0]/DEG2RAD << ", "; - cout << Ampl[1]/DEG2RAD << ", " << Ampl[2]/DEG2RAD; - cout << ") degrees."<< endl; - cout << " Pitching phase lag: (" << Phase[0]/DEG2RAD << ", "; - cout << Phase[1]/DEG2RAD <<", "<< Phase[2]/DEG2RAD; - cout << ") degrees."<< endl; + cout << " Pitching frequency: (" << Omega[0] << ", " << Omega[1]; + cout << ", " << Omega[2] << ") rad/s." << endl; + cout << " Pitching amplitude: (" << Ampl[0] / DEG2RAD << ", "; + cout << Ampl[1] / DEG2RAD << ", " << Ampl[2] / DEG2RAD; + cout << ") degrees." << endl; + cout << " Pitching phase lag: (" << Phase[0] / DEG2RAD << ", "; + cout << Phase[1] / DEG2RAD << ", " << Phase[2] / DEG2RAD; + cout << ") degrees." << endl; } /*--- Store angles separately for clarity. Compute sines/cosines. ---*/ - cosTheta = cos(dtheta); cosPhi = cos(dphi); cosPsi = cos(dpsi); - sinTheta = sin(dtheta); sinPhi = sin(dphi); sinPsi = sin(dpsi); + cosTheta = cos(dtheta); + cosPhi = cos(dphi); + cosPsi = cos(dpsi); + sinTheta = sin(dtheta); + sinPhi = sin(dphi); + sinPsi = sin(dpsi); /*--- Compute the rotation matrix. Note that the implicit ordering is rotation about the x-axis, y-axis, then z-axis. ---*/ - rotMatrix[0][0] = cosPhi*cosPsi; - rotMatrix[1][0] = cosPhi*sinPsi; + rotMatrix[0][0] = cosPhi * cosPsi; + rotMatrix[1][0] = cosPhi * sinPsi; rotMatrix[2][0] = -sinPhi; - rotMatrix[0][1] = sinTheta*sinPhi*cosPsi - cosTheta*sinPsi; - rotMatrix[1][1] = sinTheta*sinPhi*sinPsi + cosTheta*cosPsi; - rotMatrix[2][1] = sinTheta*cosPhi; + rotMatrix[0][1] = sinTheta * sinPhi * cosPsi - cosTheta * sinPsi; + rotMatrix[1][1] = sinTheta * sinPhi * sinPsi + cosTheta * cosPsi; + rotMatrix[2][1] = sinTheta * cosPhi; - rotMatrix[0][2] = cosTheta*sinPhi*cosPsi + sinTheta*sinPsi; - rotMatrix[1][2] = cosTheta*sinPhi*sinPsi - sinTheta*cosPsi; - rotMatrix[2][2] = cosTheta*cosPhi; + rotMatrix[0][2] = cosTheta * sinPhi * cosPsi + sinTheta * sinPsi; + rotMatrix[1][2] = cosTheta * sinPhi * sinPsi - sinTheta * cosPsi; + rotMatrix[2][2] = cosTheta * cosPhi; /*--- Loop over and rotate each node in the volume mesh ---*/ for (iPoint = 0; iPoint < geometry->GetnPoint(); iPoint++) { - /*--- Coordinates of the current point ---*/ - Coord = geometry->nodes->GetCoord(iPoint); + Coord = geometry->nodes->GetCoord(iPoint); GridVel = geometry->nodes->GetGridVel(iPoint); /*--- Calculate non-dim. position from rotation center ---*/ - for (iDim = 0; iDim < nDim; iDim++) - r[iDim] = (Coord[iDim]-Center[iDim])/Lref; + for (iDim = 0; iDim < nDim; iDim++) r[iDim] = (Coord[iDim] - Center[iDim]) / Lref; if (nDim == 2) r[nDim] = 0.0; /*--- Compute transformed point coordinates ---*/ - rotCoord[0] = rotMatrix[0][0]*r[0] - + rotMatrix[0][1]*r[1] - + rotMatrix[0][2]*r[2]; + rotCoord[0] = rotMatrix[0][0] * r[0] + rotMatrix[0][1] * r[1] + rotMatrix[0][2] * r[2]; - rotCoord[1] = rotMatrix[1][0]*r[0] - + rotMatrix[1][1]*r[1] - + rotMatrix[1][2]*r[2]; + rotCoord[1] = rotMatrix[1][0] * r[0] + rotMatrix[1][1] * r[1] + rotMatrix[1][2] * r[2]; - rotCoord[2] = rotMatrix[2][0]*r[0] - + rotMatrix[2][1]*r[1] - + rotMatrix[2][2]*r[2]; + rotCoord[2] = rotMatrix[2][0] * r[0] + rotMatrix[2][1] * r[1] + rotMatrix[2][2] * r[2]; /*--- Cross Product of angular velocity and distance from center. Note that we have assumed the grid velocities have been set to an initial value in the plunging routine. ---*/ - newGridVel[0] = GridVel[0] + alphaDot[1]*rotCoord[2] - alphaDot[2]*rotCoord[1]; - newGridVel[1] = GridVel[1] + alphaDot[2]*rotCoord[0] - alphaDot[0]*rotCoord[2]; - if (nDim == 3) newGridVel[2] = GridVel[2] + alphaDot[0]*rotCoord[1] - alphaDot[1]*rotCoord[0]; + newGridVel[0] = GridVel[0] + alphaDot[1] * rotCoord[2] - alphaDot[2] * rotCoord[1]; + newGridVel[1] = GridVel[1] + alphaDot[2] * rotCoord[0] - alphaDot[0] * rotCoord[2]; + if (nDim == 3) newGridVel[2] = GridVel[2] + alphaDot[0] * rotCoord[1] - alphaDot[1] * rotCoord[0]; /*--- Store new node location & grid velocity. Add center location. Do not store the grid velocity if this is an adjoint calculation.---*/ for (iDim = 0; iDim < nDim; iDim++) { - geometry->nodes->SetCoord(iPoint, iDim, rotCoord[iDim]+Center[iDim]); + geometry->nodes->SetCoord(iPoint, iDim, rotCoord[iDim] + Center[iDim]); if (!adjoint) geometry->nodes->SetGridVel(iPoint, iDim, newGridVel[iDim]); } } @@ -2148,11 +2210,10 @@ void CVolumetricMovement::Rigid_Pitching(CGeometry *geometry, CConfig *config, u /*--- After moving all nodes, update geometry class ---*/ UpdateDualGrid(geometry, config); - } -void CVolumetricMovement::Rigid_Plunging(CGeometry *geometry, CConfig *config, unsigned short iZone, unsigned long iter) { - +void CVolumetricMovement::Rigid_Plunging(CGeometry* geometry, CConfig* config, unsigned short iZone, + unsigned long iter) { /*--- Local variables ---*/ su2double deltaX[3], newCoord[3] = {0.0, 0.0, 0.0}, Center[3], *Coord, Omega[3], Ampl[3], Lref; su2double *GridVel, newGridVel[3] = {0.0, 0.0, 0.0}, xDot[3]; @@ -2164,12 +2225,12 @@ void CVolumetricMovement::Rigid_Plunging(CGeometry *geometry, CConfig *config, u /*--- Retrieve values from the config file ---*/ deltaT = config->GetDelta_UnstTimeND(); - Lref = config->GetLength_Ref(); + Lref = config->GetLength_Ref(); - for (iDim = 0; iDim < 3; iDim++){ + for (iDim = 0; iDim < 3; iDim++) { Center[iDim] = config->GetMotion_Origin(iDim); - Omega[iDim] = config->GetPlunging_Omega(iDim)/config->GetOmega_Ref(); - Ampl[iDim] = config->GetPlunging_Ampl(iDim)/Lref; + Omega[iDim] = config->GetPlunging_Omega(iDim) / config->GetOmega_Ref(); + Ampl[iDim] = config->GetPlunging_Ampl(iDim) / Lref; } /*--- Plunging frequency and amplitude from config. ---*/ @@ -2178,57 +2239,55 @@ void CVolumetricMovement::Rigid_Plunging(CGeometry *geometry, CConfig *config, u /*--- period of oscillation & time interval using nTimeInstances ---*/ su2double period = config->GetHarmonicBalance_Period(); period /= config->GetTime_Ref(); - deltaT = period/(su2double)(config->GetnTimeInstances()); + deltaT = period / (su2double)(config->GetnTimeInstances()); } /*--- Compute delta time based on physical time step ---*/ if (adjoint) { /*--- For the unsteady adjoint, we integrate backwards through physical time, so perform mesh motion in reverse. ---*/ - unsigned long nFlowIter = config->GetnTime_Iter(); + unsigned long nFlowIter = config->GetnTime_Iter(); unsigned long directIter = nFlowIter - iter - 1; - time_new = static_cast(directIter)*deltaT; + time_new = static_cast(directIter) * deltaT; time_old = time_new; - if (iter != 0) time_old = (static_cast(directIter)+1.0)*deltaT; + if (iter != 0) time_old = (static_cast(directIter) + 1.0) * deltaT; } else { /*--- Forward time for the direct problem ---*/ - time_new = static_cast(iter)*deltaT; + time_new = static_cast(iter) * deltaT; if (harmonic_balance) { /*--- For harmonic balance, begin movement from the zero position ---*/ time_old = 0.0; } else { time_old = time_new; - if (iter != 0) time_old = (static_cast(iter)-1.0)*deltaT; + if (iter != 0) time_old = (static_cast(iter) - 1.0) * deltaT; } } /*--- Compute delta change in the position in the x, y, & z directions. ---*/ - deltaX[0] = -Ampl[0]*(sin(Omega[0]*time_new) - sin(Omega[0]*time_old)); - deltaX[1] = -Ampl[1]*(sin(Omega[1]*time_new) - sin(Omega[1]*time_old)); - deltaX[2] = -Ampl[2]*(sin(Omega[2]*time_new) - sin(Omega[2]*time_old)); + deltaX[0] = -Ampl[0] * (sin(Omega[0] * time_new) - sin(Omega[0] * time_old)); + deltaX[1] = -Ampl[1] * (sin(Omega[1] * time_new) - sin(Omega[1] * time_old)); + deltaX[2] = -Ampl[2] * (sin(Omega[2] * time_new) - sin(Omega[2] * time_old)); /*--- Compute grid velocity due to plunge in the x, y, & z directions. ---*/ - xDot[0] = -Ampl[0]*Omega[0]*(cos(Omega[0]*time_new)); - xDot[1] = -Ampl[1]*Omega[1]*(cos(Omega[1]*time_new)); - xDot[2] = -Ampl[2]*Omega[2]*(cos(Omega[2]*time_new)); + xDot[0] = -Ampl[0] * Omega[0] * (cos(Omega[0] * time_new)); + xDot[1] = -Ampl[1] * Omega[1] * (cos(Omega[1] * time_new)); + xDot[2] = -Ampl[2] * Omega[2] * (cos(Omega[2] * time_new)); if (rank == MASTER_NODE && iter == 0) { cout << " Plunging frequency: (" << Omega[0] << ", " << Omega[1]; cout << ", " << Omega[2] << ") rad/s." << endl; cout << " Plunging amplitude: (" << Ampl[0] << ", "; - cout << Ampl[1] << ", " << Ampl[2] << ") m."<< endl; + cout << Ampl[1] << ", " << Ampl[2] << ") m." << endl; } /*--- Loop over and move each node in the volume mesh ---*/ for (iPoint = 0; iPoint < geometry->GetnPoint(); iPoint++) { - /*--- Coordinates of the current point ---*/ - Coord = geometry->nodes->GetCoord(iPoint); + Coord = geometry->nodes->GetCoord(iPoint); GridVel = geometry->nodes->GetGridVel(iPoint); /*--- Increment the node position using the delta values. ---*/ - for (iDim = 0; iDim < nDim; iDim++) - newCoord[iDim] = Coord[iDim] + deltaX[iDim]; + for (iDim = 0; iDim < nDim; iDim++) newCoord[iDim] = Coord[iDim] + deltaX[iDim]; /*--- Cross Product of angular velocity and distance from center. Note that we have assumed the grid velocities have been set to @@ -2236,7 +2295,7 @@ void CVolumetricMovement::Rigid_Plunging(CGeometry *geometry, CConfig *config, u newGridVel[0] = GridVel[0] + xDot[0]; newGridVel[1] = GridVel[1] + xDot[1]; - if (nDim == 3) newGridVel[2] = GridVel[2] + xDot[2]; + if (nDim == 3) newGridVel[2] = GridVel[2] + xDot[2]; /*--- Store new node location & grid velocity. Do not store the grid velocity if this is an adjoint calculation. ---*/ @@ -2251,23 +2310,23 @@ void CVolumetricMovement::Rigid_Plunging(CGeometry *geometry, CConfig *config, u incrementing the position with the rigid translation. This new location will be used for subsequent pitching/rotation.---*/ - for (iDim = 0; iDim < 3; iDim++){ + for (iDim = 0; iDim < 3; iDim++) { Center[iDim] = config->GetMotion_Origin(iDim) + deltaX[iDim]; } config->SetMotion_Origin(Center); /*--- As the body origin may have moved, print it to the console ---*/ -// if (rank == MASTER_NODE) { -// cout << " Body origin: (" << Center[0]+deltaX[0]; -// cout << ", " << Center[1]+deltaX[1] << ", " << Center[2]+deltaX[2]; -// cout << ")." << endl; -// } + // if (rank == MASTER_NODE) { + // cout << " Body origin: (" << Center[0]+deltaX[0]; + // cout << ", " << Center[1]+deltaX[1] << ", " << Center[2]+deltaX[2]; + // cout << ")." << endl; + // } /*--- Set the moment computation center to the new location after incrementing the position with the plunging. ---*/ - for (unsigned short jMarker=0; jMarkerGetnMarker_Monitoring(); jMarker++) { + for (unsigned short jMarker = 0; jMarker < config->GetnMarker_Monitoring(); jMarker++) { Center[0] = config->GetRefOriginMoment_X(jMarker) + deltaX[0]; Center[1] = config->GetRefOriginMoment_Y(jMarker) + deltaX[1]; Center[2] = config->GetRefOriginMoment_Z(jMarker) + deltaX[2]; @@ -2279,11 +2338,10 @@ void CVolumetricMovement::Rigid_Plunging(CGeometry *geometry, CConfig *config, u /*--- After moving all nodes, update geometry class ---*/ UpdateDualGrid(geometry, config); - } -void CVolumetricMovement::Rigid_Translation(CGeometry *geometry, CConfig *config, unsigned short iZone, unsigned long iter) { - +void CVolumetricMovement::Rigid_Translation(CGeometry* geometry, CConfig* config, unsigned short iZone, + unsigned long iter) { /*--- Local variables ---*/ su2double deltaX[3], newCoord[3] = {0.0, 0.0, 0.0}, Center[3], *Coord; su2double xDot[3]; @@ -2298,70 +2356,71 @@ void CVolumetricMovement::Rigid_Translation(CGeometry *geometry, CConfig *config /*--- Get motion center and translation rates from config ---*/ - for (iDim = 0; iDim < 3; iDim++){ + for (iDim = 0; iDim < 3; iDim++) { Center[iDim] = config->GetMotion_Origin(iDim); - xDot[iDim] = config->GetTranslation_Rate(iDim); + xDot[iDim] = config->GetTranslation_Rate(iDim); } if (harmonic_balance) { /*--- period of oscillation & time interval using nTimeInstances ---*/ su2double period = config->GetHarmonicBalance_Period(); period /= config->GetTime_Ref(); - deltaT = period/(su2double)(config->GetnTimeInstances()); + deltaT = period / (su2double)(config->GetnTimeInstances()); } /*--- Compute delta time based on physical time step ---*/ if (adjoint) { /*--- For the unsteady adjoint, we integrate backwards through physical time, so perform mesh motion in reverse. ---*/ - unsigned long nFlowIter = config->GetnTime_Iter(); + unsigned long nFlowIter = config->GetnTime_Iter(); unsigned long directIter = nFlowIter - iter - 1; - time_new = static_cast(directIter)*deltaT; + time_new = static_cast(directIter) * deltaT; time_old = time_new; - if (iter != 0) time_old = (static_cast(directIter)+1.0)*deltaT; + if (iter != 0) time_old = (static_cast(directIter) + 1.0) * deltaT; } else { /*--- Forward time for the direct problem ---*/ - time_new = static_cast(iter)*deltaT; + time_new = static_cast(iter) * deltaT; if (harmonic_balance) { /*--- For harmonic balance, begin movement from the zero position ---*/ time_old = 0.0; } else { time_old = time_new; - if (iter != 0) time_old = (static_cast(iter)-1.0)*deltaT; + if (iter != 0) time_old = (static_cast(iter) - 1.0) * deltaT; } } /*--- Compute delta change in the position in the x, y, & z directions. ---*/ - deltaX[0] = xDot[0]*(time_new-time_old); - deltaX[1] = xDot[1]*(time_new-time_old); - deltaX[2] = xDot[2]*(time_new-time_old); + deltaX[0] = xDot[0] * (time_new - time_old); + deltaX[1] = xDot[1] * (time_new - time_old); + deltaX[2] = xDot[2] * (time_new - time_old); if (rank == MASTER_NODE) { cout << " New physical time: " << time_new << " seconds." << endl; if (iter == 0) { - cout << " Translational velocity: (" << xDot[0]*config->GetVelocity_Ref() << ", " << xDot[1]*config->GetVelocity_Ref(); - cout << ", " << xDot[2]*config->GetVelocity_Ref(); - if (config->GetSystemMeasurements() == SI) cout << ") m/s." << endl; - else cout << ") ft/s." << endl; + cout << " Translational velocity: (" << xDot[0] * config->GetVelocity_Ref() << ", " + << xDot[1] * config->GetVelocity_Ref(); + cout << ", " << xDot[2] * config->GetVelocity_Ref(); + if (config->GetSystemMeasurements() == SI) + cout << ") m/s." << endl; + else + cout << ") ft/s." << endl; } } /*--- Loop over and move each node in the volume mesh ---*/ for (iPoint = 0; iPoint < geometry->GetnPoint(); iPoint++) { - /*--- Coordinates of the current point ---*/ Coord = geometry->nodes->GetCoord(iPoint); /*--- Increment the node position using the delta values. ---*/ - for (iDim = 0; iDim < nDim; iDim++) - newCoord[iDim] = Coord[iDim] + deltaX[iDim]; + for (iDim = 0; iDim < nDim; iDim++) newCoord[iDim] = Coord[iDim] + deltaX[iDim]; /*--- Store new node location & grid velocity. Do not store the grid velocity if this is an adjoint calculation. ---*/ for (iDim = 0; iDim < nDim; iDim++) { geometry->nodes->SetCoord(iPoint, iDim, newCoord[iDim]); - if (!adjoint) geometry->nodes->SetGridVel(iPoint, iDim,xDot[iDim]); + if (!adjoint) geometry->nodes->SetGridVel(iPoint, iDim, xDot[iDim]); } } @@ -2369,16 +2428,15 @@ void CVolumetricMovement::Rigid_Translation(CGeometry *geometry, CConfig *config incrementing the position with the rigid translation. This new location will be used for subsequent pitching/rotation.---*/ - for (iDim = 0; iDim < 3; iDim++){ + for (iDim = 0; iDim < 3; iDim++) { Center[iDim] = config->GetMotion_Origin(iDim) + deltaX[iDim]; } config->SetMotion_Origin(Center); - /*--- Set the moment computation center to the new location after incrementing the position with the translation. ---*/ - for (unsigned short jMarker=0; jMarkerGetnMarker_Monitoring(); jMarker++) { + for (unsigned short jMarker = 0; jMarker < config->GetnMarker_Monitoring(); jMarker++) { Center[0] = config->GetRefOriginMoment_X(jMarker) + deltaX[0]; Center[1] = config->GetRefOriginMoment_Y(jMarker) + deltaX[1]; Center[2] = config->GetRefOriginMoment_Z(jMarker) + deltaX[2]; @@ -2390,19 +2448,17 @@ void CVolumetricMovement::Rigid_Translation(CGeometry *geometry, CConfig *config /*--- After moving all nodes, update geometry class ---*/ UpdateDualGrid(geometry, config); - } -void CVolumetricMovement::SetVolume_Scaling(CGeometry *geometry, CConfig *config, bool UpdateGeo) { - +void CVolumetricMovement::SetVolume_Scaling(CGeometry* geometry, CConfig* config, bool UpdateGeo) { unsigned short iDim; unsigned long iPoint; - su2double newCoord[3] = {0.0,0.0,0.0}, *Coord; + su2double newCoord[3] = {0.0, 0.0, 0.0}, *Coord; /*--- The scaling factor is the only input to this option. Currently, the mesh must be scaled the same amount in all three directions. ---*/ - su2double Scale = config->GetDV_Value(0)*config->GetOpt_RelaxFactor(); + su2double Scale = config->GetDV_Value(0) * config->GetOpt_RelaxFactor(); if (rank == MASTER_NODE) { cout << "Scaling the mesh by a constant factor of " << Scale << "." << endl; @@ -2410,13 +2466,11 @@ void CVolumetricMovement::SetVolume_Scaling(CGeometry *geometry, CConfig *config /*--- Loop over and move each node in the volume mesh ---*/ for (iPoint = 0; iPoint < geometry->GetnPoint(); iPoint++) { - /*--- Coordinates of the current point ---*/ Coord = geometry->nodes->GetCoord(iPoint); /*--- Scale the node position by the specified factor. ---*/ - for (iDim = 0; iDim < nDim; iDim++) - newCoord[iDim] = Scale*Coord[iDim]; + for (iDim = 0; iDim < nDim; iDim++) newCoord[iDim] = Scale * Coord[iDim]; /*--- Store the new node location. ---*/ for (iDim = 0; iDim < nDim; iDim++) { @@ -2426,43 +2480,38 @@ void CVolumetricMovement::SetVolume_Scaling(CGeometry *geometry, CConfig *config /*--- After moving all nodes, update geometry class ---*/ if (UpdateGeo) UpdateDualGrid(geometry, config); - } -void CVolumetricMovement::SetVolume_Translation(CGeometry *geometry, CConfig *config, bool UpdateGeo) { - +void CVolumetricMovement::SetVolume_Translation(CGeometry* geometry, CConfig* config, bool UpdateGeo) { unsigned short iDim; unsigned long iPoint; - su2double *Coord, deltaX[3] = {0.0,0.0,0.0}, newCoord[3] = {0.0,0.0,0.0}; + su2double *Coord, deltaX[3] = {0.0, 0.0, 0.0}, newCoord[3] = {0.0, 0.0, 0.0}; su2double Scale = config->GetOpt_RelaxFactor(); /*--- Get the unit vector and magnitude of displacement. Note that we assume this is the first DV entry since it is for mesh translation. Create the displacement vector from the magnitude and direction. ---*/ - su2double Ampl = config->GetDV_Value(0)*Scale; + su2double Ampl = config->GetDV_Value(0) * Scale; su2double length = 0.0; for (iDim = 0; iDim < nDim; iDim++) { deltaX[iDim] = config->GetParamDV(0, iDim); - length += deltaX[iDim]*deltaX[iDim]; + length += deltaX[iDim] * deltaX[iDim]; } length = sqrt(length); - for (iDim = 0; iDim < nDim; iDim++) - deltaX[iDim] = Ampl*deltaX[iDim]/length; + for (iDim = 0; iDim < nDim; iDim++) deltaX[iDim] = Ampl * deltaX[iDim] / length; if (rank == MASTER_NODE) { cout << "Translational displacement: (" << deltaX[0] << ", "; - cout << deltaX[1] << ", " << deltaX[2] << ")." << endl; + cout << deltaX[1] << ", " << deltaX[2] << ")." << endl; } /*--- Loop over and move each node in the volume mesh ---*/ for (iPoint = 0; iPoint < geometry->GetnPoint(); iPoint++) { - /*--- Coordinates of the current point ---*/ Coord = geometry->nodes->GetCoord(iPoint); /*--- Increment the node position using the delta values. ---*/ - for (iDim = 0; iDim < nDim; iDim++) - newCoord[iDim] = Coord[iDim] + deltaX[iDim]; + for (iDim = 0; iDim < nDim; iDim++) newCoord[iDim] = Coord[iDim] + deltaX[iDim]; /*--- Store new node location. ---*/ for (iDim = 0; iDim < nDim; iDim++) { @@ -2472,75 +2521,78 @@ void CVolumetricMovement::SetVolume_Translation(CGeometry *geometry, CConfig *co /*--- After moving all nodes, update geometry class ---*/ if (UpdateGeo) UpdateDualGrid(geometry, config); - } -void CVolumetricMovement::SetVolume_Rotation(CGeometry *geometry, CConfig *config, bool UpdateGeo) { - +void CVolumetricMovement::SetVolume_Rotation(CGeometry* geometry, CConfig* config, bool UpdateGeo) { unsigned short iDim; unsigned long iPoint; su2double x, y, z; - su2double *Coord, deltaX[3] = {0.0,0.0,0.0}, newCoord[3] = {0.0,0.0,0.0}; + su2double *Coord, deltaX[3] = {0.0, 0.0, 0.0}, newCoord[3] = {0.0, 0.0, 0.0}; su2double Scale = config->GetOpt_RelaxFactor(); /*--- xyz-coordinates of a point on the line of rotation. */ su2double a = config->GetParamDV(0, 0); su2double b = config->GetParamDV(0, 1); su2double c = 0.0; - if (geometry->GetnDim() == 3) c = config->GetParamDV(0,2); + if (geometry->GetnDim() == 3) c = config->GetParamDV(0, 2); /*--- xyz-coordinate of the line's direction vector. ---*/ - su2double u = config->GetParamDV(0, 3)-config->GetParamDV(0, 0); - su2double v = config->GetParamDV(0, 4)-config->GetParamDV(0, 1); + su2double u = config->GetParamDV(0, 3) - config->GetParamDV(0, 0); + su2double v = config->GetParamDV(0, 4) - config->GetParamDV(0, 1); su2double w = 1.0; - if (geometry->GetnDim() == 3) - w = config->GetParamDV(0, 5)-config->GetParamDV(0, 2); + if (geometry->GetnDim() == 3) w = config->GetParamDV(0, 5) - config->GetParamDV(0, 2); /*--- The angle of rotation. ---*/ - su2double theta = config->GetDV_Value(0)*Scale*PI_NUMBER/180.0; + su2double theta = config->GetDV_Value(0) * Scale * PI_NUMBER / 180.0; /*--- Print to the console. ---*/ if (rank == MASTER_NODE) { cout << "Rotation axis vector: (" << u << ", "; cout << v << ", " << w << ")." << endl; - cout << "Angle of rotation: " << config->GetDV_Value(0)*Scale; + cout << "Angle of rotation: " << config->GetDV_Value(0) * Scale; cout << " degrees." << endl; } /*--- Intermediate values used in computations. ---*/ - su2double u2=u*u; su2double v2=v*v; su2double w2=w*w; - su2double cosT = cos(theta); su2double sinT = sin(theta); - su2double l2 = u2 + v2 + w2; su2double l = sqrt(l2); + su2double u2 = u * u; + su2double v2 = v * v; + su2double w2 = w * w; + su2double cosT = cos(theta); + su2double sinT = sin(theta); + su2double l2 = u2 + v2 + w2; + su2double l = sqrt(l2); /*--- Loop over and move each node in the volume mesh ---*/ for (iPoint = 0; iPoint < geometry->GetnPoint(); iPoint++) { - /*--- Coordinates of the current point ---*/ Coord = geometry->nodes->GetCoord(iPoint); /*--- Displacement for this point due to the rotation. ---*/ - x = Coord[0]; y = Coord[1]; z = 0.0; + x = Coord[0]; + y = Coord[1]; + z = 0.0; if (geometry->GetnDim() == 3) z = Coord[2]; - deltaX[0] = a*(v2 + w2) + u*(-b*v - c*w + u*x + v*y + w*z) - + (-a*(v2 + w2) + u*(b*v + c*w - v*y - w*z) + (v2 + w2)*x)*cosT - + l*(-c*v + b*w - w*y + v*z)*sinT; - deltaX[0] = deltaX[0]/l2 - x; + deltaX[0] = a * (v2 + w2) + u * (-b * v - c * w + u * x + v * y + w * z) + + (-a * (v2 + w2) + u * (b * v + c * w - v * y - w * z) + (v2 + w2) * x) * cosT + + l * (-c * v + b * w - w * y + v * z) * sinT; + deltaX[0] = deltaX[0] / l2 - x; - deltaX[1] = b*(u2 + w2) + v*(-a*u - c*w + u*x + v*y + w*z) - + (-b*(u2 + w2) + v*(a*u + c*w - u*x - w*z) + (u2 + w2)*y)*cosT - + l*(c*u - a*w + w*x - u*z)*sinT; - deltaX[1] = deltaX[1]/l2 - y; + deltaX[1] = b * (u2 + w2) + v * (-a * u - c * w + u * x + v * y + w * z) + + (-b * (u2 + w2) + v * (a * u + c * w - u * x - w * z) + (u2 + w2) * y) * cosT + + l * (c * u - a * w + w * x - u * z) * sinT; + deltaX[1] = deltaX[1] / l2 - y; - deltaX[2] = c*(u2 + v2) + w*(-a*u - b*v + u*x + v*y + w*z) - + (-c*(u2 + v2) + w*(a*u + b*v - u*x - v*y) + (u2 + v2)*z)*cosT - + l*(-b*u + a*v - v*x + u*y)*sinT; - if (geometry->GetnDim() == 3) deltaX[2] = deltaX[2]/l2 - z; - else deltaX[2] = 0.0; + deltaX[2] = c * (u2 + v2) + w * (-a * u - b * v + u * x + v * y + w * z) + + (-c * (u2 + v2) + w * (a * u + b * v - u * x - v * y) + (u2 + v2) * z) * cosT + + l * (-b * u + a * v - v * x + u * y) * sinT; + if (geometry->GetnDim() == 3) + deltaX[2] = deltaX[2] / l2 - z; + else + deltaX[2] = 0.0; /*--- Increment the node position using the delta values. ---*/ - for (iDim = 0; iDim < nDim; iDim++) - newCoord[iDim] = Coord[iDim] + deltaX[iDim]; + for (iDim = 0; iDim < nDim; iDim++) newCoord[iDim] = Coord[iDim] + deltaX[iDim]; /*--- Store new node location. ---*/ for (iDim = 0; iDim < nDim; iDim++) { @@ -2550,5 +2602,4 @@ void CVolumetricMovement::SetVolume_Rotation(CGeometry *geometry, CConfig *confi /*--- After moving all nodes, update geometry class ---*/ if (UpdateGeo) UpdateDualGrid(geometry, config); - } diff --git a/Common/src/interface_interpolation/CInterpolator.cpp b/Common/src/interface_interpolation/CInterpolator.cpp index 250bf916d98..8879287a440 100644 --- a/Common/src/interface_interpolation/CInterpolator.cpp +++ b/Common/src/interface_interpolation/CInterpolator.cpp @@ -153,7 +153,6 @@ unsigned long CInterpolator::Collect_ElementInfo(int markDonor, unsigned short n } void CInterpolator::ReconstructBoundary(unsigned long val_zone, int val_marker) { - const CGeometry* geom = Geometry[val_zone][INST_0][MESH_0]; const auto nDim = geom->GetnDim(); @@ -197,7 +196,8 @@ void CInterpolator::ReconstructBoundary(unsigned long val_zone, int val_marker) if (geom->nodes->GetDomain(iPoint)) { const auto iLocalVertex = iVertex_to_iLocalVertex[iVertex]; Buffer_Send_GlobalPoint[iLocalVertex] = geom->nodes->GetGlobalIndex(iPoint); - for (unsigned long iDim = 0; iDim < nDim; iDim++) Buffer_Send_Coord(iLocalVertex,iDim) = geom->nodes->GetCoord(iPoint, iDim); + for (unsigned long iDim = 0; iDim < nDim; iDim++) + Buffer_Send_Coord(iLocalVertex, iDim) = geom->nodes->GetCoord(iPoint, iDim); neighbors.insert(pair >(iPoint, set())); } } @@ -344,7 +344,7 @@ void CInterpolator::ReconstructBoundary(unsigned long val_zone, int val_marker) * Buffer_Receive_GlobalPoint, Buffer_Receive_nLinkedNodes etc. ---*/ if (rank == MASTER_NODE) { for (unsigned long iVertex = 0; iVertex < nGlobalVertex; iVertex++) { - unsigned long *uptr = &Buffer_Receive_LinkedNodes[Buffer_Receive_StartLinkedNodes[iVertex]]; + unsigned long* uptr = &Buffer_Receive_LinkedNodes[Buffer_Receive_StartLinkedNodes[iVertex]]; for (unsigned long jLinkedNode = 0; jLinkedNode < Buffer_Receive_nLinkedNodes[iVertex]; jLinkedNode++) { const auto jPoint = uptr[jLinkedNode]; diff --git a/Common/src/interface_interpolation/CInterpolatorFactory.cpp b/Common/src/interface_interpolation/CInterpolatorFactory.cpp index 64b989981e5..be50f5075ce 100644 --- a/Common/src/interface_interpolation/CInterpolatorFactory.cpp +++ b/Common/src/interface_interpolation/CInterpolatorFactory.cpp @@ -34,11 +34,9 @@ #include "../../include/interface_interpolation/CSlidingMesh.hpp" namespace CInterpolatorFactory { -CInterpolator* CreateInterpolator(CGeometry ****geometry_container, - const CConfig* const* config, - const CInterpolator* transpInterpolator, - unsigned iZone, unsigned jZone, bool verbose) { - +CInterpolator* CreateInterpolator(CGeometry**** geometry_container, const CConfig* const* config, + const CInterpolator* transpInterpolator, unsigned iZone, unsigned jZone, + bool verbose) { CInterpolator* interpolator = nullptr; /*--- Only print information on master node. ---*/ @@ -57,30 +55,28 @@ CInterpolator* CreateInterpolator(CGeometry ****geometry_container, if (type == INTERFACE_INTERPOLATOR::WEIGHTED_AVERAGE) { if (verbose) cout << "using a sliding mesh approach." << endl; interpolator = new CSlidingMesh(geometry_container, config, iZone, jZone); - } - else if (config[jZone]->GetConservativeInterpolation()) { + } else if (config[jZone]->GetConservativeInterpolation()) { if (verbose) cout << "using the mirror approach, \"transposing\" coefficients from opposite mesh." << endl; interpolator = new CMirror(geometry_container, config, transpInterpolator, iZone, jZone); - } - else { - switch(type) { - case INTERFACE_INTERPOLATOR::ISOPARAMETRIC: - if (verbose) cout << "using the isoparametric approach." << endl; - interpolator = new CIsoparametric(geometry_container, config, iZone, jZone); - break; + } else { + switch (type) { + case INTERFACE_INTERPOLATOR::ISOPARAMETRIC: + if (verbose) cout << "using the isoparametric approach." << endl; + interpolator = new CIsoparametric(geometry_container, config, iZone, jZone); + break; - case INTERFACE_INTERPOLATOR::NEAREST_NEIGHBOR: - if (verbose) cout << "using a nearest neighbor approach." << endl; - interpolator = new CNearestNeighbor(geometry_container, config, iZone, jZone); - break; + case INTERFACE_INTERPOLATOR::NEAREST_NEIGHBOR: + if (verbose) cout << "using a nearest neighbor approach." << endl; + interpolator = new CNearestNeighbor(geometry_container, config, iZone, jZone); + break; - case INTERFACE_INTERPOLATOR::RADIAL_BASIS_FUNCTION: - if (verbose) cout << "using a radial basis function approach." << endl; - interpolator = new CRadialBasisFunction(geometry_container, config, iZone, jZone); - break; + case INTERFACE_INTERPOLATOR::RADIAL_BASIS_FUNCTION: + if (verbose) cout << "using a radial basis function approach." << endl; + interpolator = new CRadialBasisFunction(geometry_container, config, iZone, jZone); + break; - default: - SU2_MPI::Error("Unknown type of interpolation.", CURRENT_FUNCTION); + default: + SU2_MPI::Error("Unknown type of interpolation.", CURRENT_FUNCTION); } } @@ -88,4 +84,4 @@ CInterpolator* CreateInterpolator(CGeometry ****geometry_container, return interpolator; } -} // end namespace +} // namespace CInterpolatorFactory diff --git a/Common/src/interface_interpolation/CIsoparametric.cpp b/Common/src/interface_interpolation/CIsoparametric.cpp index e660664a891..f8ed1c6b588 100644 --- a/Common/src/interface_interpolation/CIsoparametric.cpp +++ b/Common/src/interface_interpolation/CIsoparametric.cpp @@ -34,9 +34,9 @@ using namespace GeometryToolbox; -CIsoparametric::CIsoparametric(CGeometry ****geometry_container, const CConfig* const* config, - unsigned int iZone, unsigned int jZone) : - CInterpolator(geometry_container, config, iZone, jZone) { +CIsoparametric::CIsoparametric(CGeometry**** geometry_container, const CConfig* const* config, unsigned int iZone, + unsigned int jZone) + : CInterpolator(geometry_container, config, iZone, jZone) { SetTransferCoeff(config); } @@ -47,27 +47,26 @@ void CIsoparametric::PrintStatistics(void) const { } void CIsoparametric::SetTransferCoeff(const CConfig* const* config) { - - const su2double matchingVertexTol = 1e-12; // 1um^2 + const su2double matchingVertexTol = 1e-12; // 1um^2 const int nProcessor = size; - const auto nMarkerInt = config[donorZone]->GetMarker_n_ZoneInterface()/2; + const auto nMarkerInt = config[donorZone]->GetMarker_n_ZoneInterface() / 2; const auto nDim = donor_geometry->GetnDim(); - Buffer_Receive_nVertex_Donor = new unsigned long [nProcessor]; + Buffer_Receive_nVertex_Donor = new unsigned long[nProcessor]; /*--- Make space for donor info. ---*/ targetVertices.resize(config[targetZone]->GetnMarker_All()); /*--- Init stats. ---*/ - MaxDistance = 0.0; ErrorCounter = 0; + MaxDistance = 0.0; + ErrorCounter = 0; unsigned long nGlobalVertexTarget = 0; /*--- Cycle over nMarkersInt interface to determine communication pattern. ---*/ for (unsigned short iMarkerInt = 0; iMarkerInt < nMarkerInt; iMarkerInt++) { - /* High level procedure: * - Loop through vertices of the target grid; * - Find nearest element; @@ -90,12 +89,12 @@ void CIsoparametric::SetTransferCoeff(const CConfig* const* config) { /*--- Sets MaxLocalVertex_Donor, Buffer_Receive_nVertex_Donor. ---*/ Determine_ArraySize(markDonor, markTarget, nVertexDonor, nDim); - const auto nGlobalVertexDonor = accumulate(Buffer_Receive_nVertex_Donor, - Buffer_Receive_nVertex_Donor+nProcessor, 0ul); + const auto nGlobalVertexDonor = + accumulate(Buffer_Receive_nVertex_Donor, Buffer_Receive_nVertex_Donor + nProcessor, 0ul); Buffer_Send_Coord.resize(MaxLocalVertex_Donor, nDim); - Buffer_Send_GlobalPoint .resize(MaxLocalVertex_Donor); - Buffer_Receive_Coord.resize(nProcessor*MaxLocalVertex_Donor,nDim); + Buffer_Send_GlobalPoint.resize(MaxLocalVertex_Donor); + Buffer_Receive_Coord.resize(nProcessor * MaxLocalVertex_Donor, nDim); Buffer_Receive_GlobalPoint.resize(nProcessor * MaxLocalVertex_Donor); /*--- Collect coordinates and global point indices. ---*/ @@ -114,9 +113,8 @@ void CIsoparametric::SetTransferCoeff(const CConfig* const* config) { for (int iProcessor = 0; iProcessor < nProcessor; ++iProcessor) { auto offset = iProcessor * MaxLocalVertex_Donor; for (auto iVertex = 0ul; iVertex < Buffer_Receive_nVertex_Donor[iProcessor]; ++iVertex) { - for (int iDim = 0; iDim < nDim; ++iDim) - donorCoord(iCount,iDim) = Buffer_Receive_Coord(offset+iVertex, iDim); - donorPoint[iCount] = Buffer_Receive_GlobalPoint[offset+iVertex]; + for (int iDim = 0; iDim < nDim; ++iDim) donorCoord(iCount, iDim) = Buffer_Receive_Coord(offset + iVertex, iDim); + donorPoint[iCount] = Buffer_Receive_GlobalPoint[offset + iVertex]; donorProc[iCount] = iProcessor; assert((globalToLocalMap.count(donorPoint[iCount]) == 0) && "Duplicate donor point found."); globalToLocalMap[donorPoint[iCount]] = iCount; @@ -131,135 +129,132 @@ void CIsoparametric::SetTransferCoeff(const CConfig* const* config) { vector elemNumNodes; su2matrix elemIdxNodes; - const auto nGlobalElemDonor = Collect_ElementInfo(markDonor, nDim, true, - allNumElem, elemNumNodes, elemIdxNodes); + const auto nGlobalElemDonor = Collect_ElementInfo(markDonor, nDim, true, allNumElem, elemNumNodes, elemIdxNodes); /*--- Map the node to "local" indices and create a list of connected elements for each vertex. ---*/ vector > vertexElements(nGlobalVertexDonor); for (auto iElem = 0u; iElem < nGlobalElemDonor; ++iElem) { - const auto nNode = elemNumNodes[iElem]; for (auto iNode = 0u; iNode < nNode; ++iNode) { - - assert(globalToLocalMap.count(elemIdxNodes(iElem,iNode)) && + assert(globalToLocalMap.count(elemIdxNodes(iElem, iNode)) && "Unknown donor point referenced by donor element."); - const auto iVertex = globalToLocalMap.at(elemIdxNodes(iElem,iNode)); - elemIdxNodes(iElem,iNode) = iVertex; + const auto iVertex = globalToLocalMap.at(elemIdxNodes(iElem, iNode)); + elemIdxNodes(iElem, iNode) = iVertex; vertexElements[iVertex].push_back(iElem); } } /*--- Compute transfer coefficients for each target point. ---*/ - SU2_OMP_PARALLEL - { - su2double maxDist = 0.0; - unsigned long errorCount = 0, totalCount = 0; - - SU2_OMP_FOR_DYN(roundUpDiv(nVertexTarget,2*omp_get_max_threads())) - for (auto iVertexTarget = 0u; iVertexTarget < nVertexTarget; ++iVertexTarget) { - - auto& target_vertex = targetVertices[markTarget][iVertexTarget]; - const auto iPoint = target_geometry->vertex[markTarget][iVertexTarget]->GetNode(); - - if (!target_geometry->nodes->GetDomain(iPoint)) continue; - totalCount += 1; - - /*--- Coordinates of the target point. ---*/ - const su2double* coord_i = target_geometry->nodes->GetCoord(iPoint); - - /*--- Find the closest donor vertex. ---*/ - su2double minDist = 1e9; - unsigned iClosestVertex = 0; - for (auto iVertexDonor = 0u; iVertexDonor < nGlobalVertexDonor; ++iVertexDonor) { - su2double d = SquaredDistance(nDim, coord_i, donorCoord[iVertexDonor]); - if (d < minDist) { - minDist = d; - iClosestVertex = iVertexDonor; + SU2_OMP_PARALLEL { + su2double maxDist = 0.0; + unsigned long errorCount = 0, totalCount = 0; + + SU2_OMP_FOR_DYN(roundUpDiv(nVertexTarget, 2 * omp_get_max_threads())) + for (auto iVertexTarget = 0u; iVertexTarget < nVertexTarget; ++iVertexTarget) { + auto& target_vertex = targetVertices[markTarget][iVertexTarget]; + const auto iPoint = target_geometry->vertex[markTarget][iVertexTarget]->GetNode(); + + if (!target_geometry->nodes->GetDomain(iPoint)) continue; + totalCount += 1; + + /*--- Coordinates of the target point. ---*/ + const su2double* coord_i = target_geometry->nodes->GetCoord(iPoint); + + /*--- Find the closest donor vertex. ---*/ + su2double minDist = 1e9; + unsigned iClosestVertex = 0; + for (auto iVertexDonor = 0u; iVertexDonor < nGlobalVertexDonor; ++iVertexDonor) { + su2double d = SquaredDistance(nDim, coord_i, donorCoord[iVertexDonor]); + if (d < minDist) { + minDist = d; + iClosestVertex = iVertexDonor; + } } - } - - if (minDist < matchingVertexTol) { - /*--- Perfect match. ---*/ - target_vertex.resize(1); - target_vertex.coefficient[0] = 1.0; - target_vertex.globalPoint[0] = donorPoint[iClosestVertex]; - target_vertex.processor[0] = donorProc[iClosestVertex]; - continue; - } - - /*--- Evaluate interpolation for the elements connected to the closest vertex. ---*/ - DonorInfo donor; - donor.error = 2; - donor.distance = 1e9; - for (auto iElem : vertexElements[iClosestVertex]) { - /*--- Fetch element info. ---*/ - DonorInfo candidate; - candidate.iElem = iElem; - const auto nNode = elemNumNodes[iElem]; - su2double coords[4][3] = {{0.0}}; - for (auto iNode = 0u; iNode < nNode; ++iNode) { - const auto iVertex = elemIdxNodes(iElem, iNode); - for (auto iDim = 0u; iDim < nDim; ++iDim) - coords[iNode][iDim] = donorCoord(iVertex,iDim); - } - - /*--- Compute the interpolation coefficients. ---*/ - switch (nNode) { - case 2: candidate.error = LineIsoparameters(coords, coord_i, candidate.isoparams); break; - case 3: candidate.error = TriangleIsoparameters(coords, coord_i, candidate.isoparams); break; - case 4: candidate.error = QuadrilateralIsoparameters(coords, coord_i, candidate.isoparams); break; + if (minDist < matchingVertexTol) { + /*--- Perfect match. ---*/ + target_vertex.resize(1); + target_vertex.coefficient[0] = 1.0; + target_vertex.globalPoint[0] = donorPoint[iClosestVertex]; + target_vertex.processor[0] = donorProc[iClosestVertex]; + continue; } - /*--- Evaluate distance from target to final mapped point. ---*/ - su2double finalCoord[3] = {0.0}; - for (auto iDim = 0u; iDim < nDim; ++iDim) - for (auto iNode = 0u; iNode < nNode; ++iNode) - finalCoord[iDim] += coords[iNode][iDim] * candidate.isoparams[iNode]; + /*--- Evaluate interpolation for the elements connected to the closest vertex. ---*/ + DonorInfo donor; + donor.error = 2; + donor.distance = 1e9; + for (auto iElem : vertexElements[iClosestVertex]) { + /*--- Fetch element info. ---*/ + DonorInfo candidate; + candidate.iElem = iElem; + const auto nNode = elemNumNodes[iElem]; + su2double coords[4][3] = {{0.0}}; + + for (auto iNode = 0u; iNode < nNode; ++iNode) { + const auto iVertex = elemIdxNodes(iElem, iNode); + for (auto iDim = 0u; iDim < nDim; ++iDim) coords[iNode][iDim] = donorCoord(iVertex, iDim); + } + + /*--- Compute the interpolation coefficients. ---*/ + switch (nNode) { + case 2: + candidate.error = LineIsoparameters(coords, coord_i, candidate.isoparams); + break; + case 3: + candidate.error = TriangleIsoparameters(coords, coord_i, candidate.isoparams); + break; + case 4: + candidate.error = QuadrilateralIsoparameters(coords, coord_i, candidate.isoparams); + break; + } + + /*--- Evaluate distance from target to final mapped point. ---*/ + su2double finalCoord[3] = {0.0}; + for (auto iDim = 0u; iDim < nDim; ++iDim) + for (auto iNode = 0u; iNode < nNode; ++iNode) + finalCoord[iDim] += coords[iNode][iDim] * candidate.isoparams[iNode]; - candidate.distance = Distance(nDim, coord_i, finalCoord); + candidate.distance = Distance(nDim, coord_i, finalCoord); - /*--- Detect a very bad candidate (NaN). ---*/ - if (candidate.distance != candidate.distance) continue; + /*--- Detect a very bad candidate (NaN). ---*/ + if (candidate.distance != candidate.distance) continue; - /*--- Check if the candidate is an improvement, update donor if so. ---*/ - if (candidate < donor) donor = candidate; - } + /*--- Check if the candidate is an improvement, update donor if so. ---*/ + if (candidate < donor) donor = candidate; + } - if (donor.error > 1) - SU2_MPI::Error("Isoparametric interpolation failed, NaN detected.", CURRENT_FUNCTION); + if (donor.error > 1) SU2_MPI::Error("Isoparametric interpolation failed, NaN detected.", CURRENT_FUNCTION); - errorCount += donor.error; - maxDist = max(maxDist, donor.distance); + errorCount += donor.error; + maxDist = max(maxDist, donor.distance); - const auto nNode = elemNumNodes[donor.iElem]; + const auto nNode = elemNumNodes[donor.iElem]; - target_vertex.resize(nNode); + target_vertex.resize(nNode); - for (auto iNode = 0u; iNode < nNode; ++iNode) { - const auto iVertex = elemIdxNodes(donor.iElem, iNode); - target_vertex.coefficient[iNode] = donor.isoparams[iNode]; - target_vertex.globalPoint[iNode] = donorPoint[iVertex]; - target_vertex.processor[iNode] = donorProc[iVertex]; + for (auto iNode = 0u; iNode < nNode; ++iNode) { + const auto iVertex = elemIdxNodes(donor.iElem, iNode); + target_vertex.coefficient[iNode] = donor.isoparams[iNode]; + target_vertex.globalPoint[iNode] = donorPoint[iVertex]; + target_vertex.processor[iNode] = donorProc[iVertex]; + } } - - } - END_SU2_OMP_FOR - SU2_OMP_CRITICAL - { - MaxDistance = max(MaxDistance, maxDist); - ErrorCounter += errorCount; - nGlobalVertexTarget += totalCount; - } - END_SU2_OMP_CRITICAL + END_SU2_OMP_FOR + SU2_OMP_CRITICAL { + MaxDistance = max(MaxDistance, maxDist); + ErrorCounter += errorCount; + nGlobalVertexTarget += totalCount; + } + END_SU2_OMP_CRITICAL } END_SU2_OMP_PARALLEL - } // end nMarkerInt loop + } // end nMarkerInt loop /*--- Final reduction of statistics. ---*/ su2double tmp = MaxDistance; @@ -268,18 +263,16 @@ void CIsoparametric::SetTransferCoeff(const CConfig* const* config) { SU2_MPI::Allreduce(&tmp1, &ErrorCounter, 1, MPI_UNSIGNED_LONG, MPI_SUM, SU2_MPI::GetComm()); SU2_MPI::Allreduce(&tmp2, &nGlobalVertexTarget, 1, MPI_UNSIGNED_LONG, MPI_SUM, SU2_MPI::GetComm()); - ErrorRate = 100*su2double(ErrorCounter) / nGlobalVertexTarget; - + ErrorRate = 100 * su2double(ErrorCounter) / nGlobalVertexTarget; } -int CIsoparametric::LineIsoparameters(const su2double X[][3], const su2double *xj, su2double *isoparams) { - +int CIsoparametric::LineIsoparameters(const su2double X[][3], const su2double* xj, su2double* isoparams) { /*--- Project the target point onto the line. ---*/ su2double normal[2] = {0.0}; LineNormal(X, normal); su2double xprj[2] = {0.0}; - PointPlaneProjection(xj, X[0], normal, xprj); + PointPlaneProjection(xj, X[0], normal, xprj); su2double l01 = Distance(2, X[0], X[1]); su2double l0j = Distance(2, X[0], xprj); @@ -287,16 +280,15 @@ int CIsoparametric::LineIsoparameters(const su2double X[][3], const su2double *x /*--- Detect out of bounds point. ---*/ - const int outOfBounds = (l0j+lj1) > (2*l01); + const int outOfBounds = (l0j + lj1) > (2 * l01); - isoparams[0] = max(-0.5, min(lj1/l01, 1.5)); + isoparams[0] = max(-0.5, min(lj1 / l01, 1.5)); isoparams[1] = 1.0 - isoparams[0]; return outOfBounds; } -int CIsoparametric::TriangleIsoparameters(const su2double X[][3], const su2double *xj, su2double *isoparams) { - +int CIsoparametric::TriangleIsoparameters(const su2double X[][3], const su2double* xj, su2double* isoparams) { /*--- The isoparameters are the solution to the determined system X^T * isoparams = xj. * For which we solve the normal equations to avoid divisions by zero. * This is consistent with the shape functions of the linear triangular element. ---*/ @@ -307,18 +299,15 @@ int CIsoparametric::TriangleIsoparameters(const su2double X[][3], const su2doubl su2double normal[3] = {0.0}, xproj[3] = {0.0}; TriangleNormal(X, normal); - PointPlaneProjection(xj, X[0], normal, xproj); + PointPlaneProjection(xj, X[0], normal, xproj); - su2double A[3][3] = {{0.0}}; // = X*X^T + su2double A[3][3] = {{0.0}}; // = X*X^T for (int i = 0; i < 3; ++i) { - for (int j = 0; j < 3; ++j) - for (int k = 0; k < 3; ++k) - A[i][j] += X[i][k] * X[j][k]; + for (int k = 0; k < 3; ++k) A[i][j] += X[i][k] * X[j][k]; - isoparams[i] = 0.0; // use isoparams as rhs - for (int k = 0; k < 3; ++k) - isoparams[i] += X[i][k] * xproj[k]; + isoparams[i] = 0.0; // use isoparams as rhs + for (int k = 0; k < 3; ++k) isoparams[i] += X[i][k] * xproj[k]; } /*--- Solve system by in-place Gaussian elimination without pivoting. ---*/ @@ -327,22 +316,18 @@ int CIsoparametric::TriangleIsoparameters(const su2double X[][3], const su2doubl for (int i = 1; i < 3; ++i) { for (int j = 0; j < i; ++j) { su2double w = A[i][j] / A[j][j]; - for (int k = j; k < 3; ++k) - A[i][k] -= w * A[j][k]; + for (int k = j; k < 3; ++k) A[i][k] -= w * A[j][k]; isoparams[i] -= w * isoparams[j]; } } /*--- Backwards substitution. ---*/ for (int i = 2; i >= 0; --i) { - for (int j = i+1; j < 3; ++j) - isoparams[i] -= A[i][j] * isoparams[j]; + for (int j = i + 1; j < 3; ++j) isoparams[i] -= A[i][j] * isoparams[j]; isoparams[i] /= A[i][i]; } /*--- Detect out of bounds point. ---*/ - const int outOfBounds = (isoparams[0] < extrapTol) || - (isoparams[1] < extrapTol) || - (isoparams[2] < extrapTol); + const int outOfBounds = (isoparams[0] < extrapTol) || (isoparams[1] < extrapTol) || (isoparams[2] < extrapTol); /*--- Mitigation. ---*/ if (outOfBounds) { @@ -353,15 +338,13 @@ int CIsoparametric::TriangleIsoparameters(const su2double X[][3], const su2doubl sum += isoparams[i]; } /*--- Enforce unit sum. ---*/ - for (int i = 0; i < 3; ++i) - isoparams[i] /= sum; + for (int i = 0; i < 3; ++i) isoparams[i] /= sum; } return outOfBounds; } -int CIsoparametric::QuadrilateralIsoparameters(const su2double X[][3], const su2double *xj, su2double *isoparams) { - +int CIsoparametric::QuadrilateralIsoparameters(const su2double X[][3], const su2double* xj, su2double* isoparams) { /*--- The isoparameters are the shape functions (Ni) evaluated at xj, for that we need * the corresponding Xi and Eta, which are obtained by solving the overdetermined * nonlinear system r = xj - X^T * Ni(Xi,Eta) = 0 via the modified Marquardt method. @@ -380,14 +363,12 @@ int CIsoparametric::QuadrilateralIsoparameters(const su2double X[][3], const su2 const bool wasActive = AD::BeginPassive(); for (int iter = 0; iter < NITER; ++iter) { - /*--- Evaluate the residual. ---*/ su2double r[3] = {xj[0], xj[1], xj[2]}; su2double Ni[4] = {0.0}; CQUAD4::ShapeFunctions(Xi, Eta, Ni); for (int i = 0; i < 3; ++i) - for (int j = 0; j < 4; ++j) - r[i] -= X[j][i] * Ni[j]; + for (int j = 0; j < 4; ++j) r[i] -= X[j][i] * Ni[j]; /*--- Evaluate the residual Jacobian. ---*/ su2double dNi[4][2] = {{0.0}}; @@ -396,30 +377,27 @@ int CIsoparametric::QuadrilateralIsoparameters(const su2double X[][3], const su2 su2double jac[3][2] = {{0.0}}; for (int i = 0; i < 3; ++i) for (int j = 0; j < 2; ++j) - for (int k = 0; k < 4; ++k) - jac[i][j] -= X[k][i] * dNi[k][j]; + for (int k = 0; k < 4; ++k) jac[i][j] -= X[k][i] * dNi[k][j]; /*--- Compute the correction (normal equations and Cramer's rule). ---*/ su2double A[2][2] = {{0.0}}, b[2] = {0.0}; for (int i = 0; i < 2; ++i) { for (int j = i; j < 2; ++j) - for (int k = 0; k < 3; ++k) - A[i][j] += jac[k][i] * jac[k][j]; + for (int k = 0; k < 3; ++k) A[i][j] += jac[k][i] * jac[k][j]; - A[i][i] *= (1.0+lambda); + A[i][i] *= (1.0 + lambda); - for (int k = 0; k < 3; ++k) - b[i] += jac[k][i] * r[k]; + for (int k = 0; k < 3; ++k) b[i] += jac[k][i] * r[k]; } A[1][0] = A[0][1]; - su2double detA = 1.0 / (A[0][0]*A[1][1] - A[0][1]*A[1][0]); - su2double dXi = (b[0]*A[1][1] - b[1]*A[0][1]) * detA; - su2double dEta = (A[0][0]*b[1] - A[1][0]*b[0]) * detA; + su2double detA = 1.0 / (A[0][0] * A[1][1] - A[0][1] * A[1][0]); + su2double dXi = (b[0] * A[1][1] - b[1] * A[0][1]) * detA; + su2double dEta = (A[0][0] * b[1] - A[1][0] * b[0]) * detA; Xi -= dXi; Eta -= dEta; - eps = fabs(dXi)+fabs(dEta); + eps = fabs(dXi) + fabs(dEta); if (eps < tol) break; } @@ -431,8 +409,7 @@ int CIsoparametric::QuadrilateralIsoparameters(const su2double X[][3], const su2 /*--- Iteration diverged, hard fallback. ---*/ Xi = Eta = 0.0; outOfBounds = 1; - } - else { + } else { /*--- Check bounds. ---*/ outOfBounds = (fabs(Xi) > extrapTol) || (fabs(Eta) > extrapTol); diff --git a/Common/src/interface_interpolation/CMirror.cpp b/Common/src/interface_interpolation/CMirror.cpp index 9e1695635dc..c663af40763 100644 --- a/Common/src/interface_interpolation/CMirror.cpp +++ b/Common/src/interface_interpolation/CMirror.cpp @@ -30,21 +30,20 @@ #include "../../include/geometry/CGeometry.hpp" #include "../../include/toolboxes/printing_toolbox.hpp" - -CMirror::CMirror(CGeometry ****geometry_container, const CConfig* const* config, - const CInterpolator* interpolator, unsigned int iZone, unsigned int jZone) : - CInterpolator(geometry_container, config, iZone, jZone), - transpInterpolator(interpolator) { +CMirror::CMirror(CGeometry**** geometry_container, const CConfig* const* config, const CInterpolator* interpolator, + unsigned int iZone, unsigned int jZone) + : CInterpolator(geometry_container, config, iZone, jZone), transpInterpolator(interpolator) { using PrintingToolbox::to_string; if (jZone < iZone) { SU2_MPI::Error(string("The order of the zones does not allow conservative interpolation to be setup.\n" - "Swap zones ") + to_string(iZone) + string(" and ") + to_string(jZone) + string("."),CURRENT_FUNCTION); + "Swap zones ") + + to_string(iZone) + string(" and ") + to_string(jZone) + string("."), + CURRENT_FUNCTION); } SetTransferCoeff(config); } void CMirror::SetTransferCoeff(const CConfig* const* config) { - const int nProcessor = size; vector allNumVertexTarget(nProcessor); @@ -57,15 +56,14 @@ void CMirror::SetTransferCoeff(const CConfig* const* config) { targetVertices.resize(config[targetZone]->GetnMarker_All()); /*--- Number of markers on the interface ---*/ - const auto nMarkerInt = (config[targetZone]->GetMarker_n_ZoneInterface())/2; + const auto nMarkerInt = (config[targetZone]->GetMarker_n_ZoneInterface()) / 2; /*--- For the number of markers on the interface... ---*/ for (unsigned short iMarkerInt = 0; iMarkerInt < nMarkerInt; iMarkerInt++) { - - /* High level procedure: - * - Gather the interpolation matrix of the donor geometry; - * - Set the interpolation matrix of the target as the transpose. - */ + /* High level procedure: + * - Gather the interpolation matrix of the donor geometry; + * - Set the interpolation matrix of the target as the transpose. + */ /*--- On the donor side: find the tag of the boundary sharing the interface ---*/ const auto markDonor = config[donorZone]->FindInterfaceMarker(iMarkerInt); @@ -77,8 +75,8 @@ void CMirror::SetTransferCoeff(const CConfig* const* config) { if (!CheckInterfaceBoundary(markDonor, markTarget)) continue; unsigned long nVertexDonor = 0, nVertexTarget = 0; - if (markDonor != -1) nVertexDonor = donor_geometry->GetnVertex( markDonor ); - if (markTarget != -1) nVertexTarget = target_geometry->GetnVertex( markTarget ); + if (markDonor != -1) nVertexDonor = donor_geometry->GetnVertex(markDonor); + if (markTarget != -1) nVertexTarget = target_geometry->GetnVertex(markTarget); /*--- Count the number of donor nodes on the donor geometry. ---*/ unsigned long nVertexDonorLocal = 0; @@ -92,12 +90,12 @@ void CMirror::SetTransferCoeff(const CConfig* const* config) { } /*--- Communicate vertex and donor node counts. ---*/ - SU2_MPI::Allgather(&nVertexTarget, 1, MPI_UNSIGNED_LONG, - allNumVertexTarget.data(), 1, MPI_UNSIGNED_LONG, SU2_MPI::GetComm()); - SU2_MPI::Allgather(&nVertexDonorLocal, 1, MPI_UNSIGNED_LONG, - allNumVertexDonor.data(), 1, MPI_UNSIGNED_LONG, SU2_MPI::GetComm()); - SU2_MPI::Allgather(&nNodeDonorLocal, 1, MPI_UNSIGNED_LONG, - allNumNodeDonor.data(), 1, MPI_UNSIGNED_LONG, SU2_MPI::GetComm()); + SU2_MPI::Allgather(&nVertexTarget, 1, MPI_UNSIGNED_LONG, allNumVertexTarget.data(), 1, MPI_UNSIGNED_LONG, + SU2_MPI::GetComm()); + SU2_MPI::Allgather(&nVertexDonorLocal, 1, MPI_UNSIGNED_LONG, allNumVertexDonor.data(), 1, MPI_UNSIGNED_LONG, + SU2_MPI::GetComm()); + SU2_MPI::Allgather(&nNodeDonorLocal, 1, MPI_UNSIGNED_LONG, allNumNodeDonor.data(), 1, MPI_UNSIGNED_LONG, + SU2_MPI::GetComm()); /*--- Copy donor interpolation matrix (triplet format). ---*/ vector sendGlobalIndex(nNodeDonorLocal); @@ -105,7 +103,6 @@ void CMirror::SetTransferCoeff(const CConfig* const* config) { vector sendDonorCoeff(nNodeDonorLocal); for (auto iVertex = 0ul, iDonor = 0ul; iVertex < nVertexDonor; ++iVertex) { - auto& donor_vertex = donorVertices[markDonor][iVertex]; const auto iPoint = donor_geometry->vertex[markDonor][iVertex]->GetNode(); @@ -125,11 +122,7 @@ void CMirror::SetTransferCoeff(const CConfig* const* config) { /*--- Sort the matrix by donor index, effectively transposing the triplets. ---*/ vector order(nNodeDonorLocal); iota(order.begin(), order.end(), 0); - sort(order.begin(), order.end(), - [&sendDonorIndex](int i, int j) { - return sendDonorIndex[i] < sendDonorIndex[j]; - } - ); + sort(order.begin(), order.end(), [&sendDonorIndex](int i, int j) { return sendDonorIndex[i] < sendDonorIndex[j]; }); for (int i = 0; i < int(nNodeDonorLocal); ++i) { int j = order[i]; while (j < i) j = order[j]; @@ -138,7 +131,7 @@ void CMirror::SetTransferCoeff(const CConfig* const* config) { swap(sendDonorIndex[i], sendDonorIndex[j]); swap(sendDonorCoeff[i], sendDonorCoeff[j]); } - vector().swap(order); // no longer needed + vector().swap(order); // no longer needed /*--- Communicate donor interpolation matrix and info. We only gather the * matrix in ranks that need it, i.e. have target vertices, to avoid @@ -147,13 +140,12 @@ void CMirror::SetTransferCoeff(const CConfig* const* config) { vector iSendProcessor; for (int iProcessor = 0; iProcessor < nProcessor; ++iProcessor) - if (allNumVertexDonor[iProcessor] != 0) - iSendProcessor.push_back(iProcessor); + if (allNumVertexDonor[iProcessor] != 0) iSendProcessor.push_back(iProcessor); const int nSend = iSendProcessor.size(); - vector GlobalIndex(nSend,nullptr), DonorIndex(nSend,nullptr); - vector DonorCoeff(nSend,nullptr); + vector GlobalIndex(nSend, nullptr), DonorIndex(nSend, nullptr); + vector DonorCoeff(nSend, nullptr); /*--- For each "target processor" that needs the interpolation matrix. ---*/ for (int iProcessor = 0; iProcessor < nProcessor; ++iProcessor) { @@ -169,20 +161,18 @@ void CMirror::SetTransferCoeff(const CConfig* const* config) { GlobalIndex[iSend] = sendGlobalIndex.data(); DonorIndex[iSend] = sendDonorIndex.data(); DonorCoeff[iSend] = sendDonorCoeff.data(); - } - else if (rank == iProcessor) { + } else if (rank == iProcessor) { /*--- "I'm" the target, allocate and receive. ---*/ - GlobalIndex[iSend] = new long [numCoeff]; - DonorIndex[iSend] = new long [numCoeff]; - DonorCoeff[iSend] = new su2double [numCoeff]; + GlobalIndex[iSend] = new long[numCoeff]; + DonorIndex[iSend] = new long[numCoeff]; + DonorCoeff[iSend] = new su2double[numCoeff]; SU2_MPI::Recv(GlobalIndex[iSend], numCoeff, MPI_LONG, jProcessor, 0, SU2_MPI::GetComm(), MPI_STATUS_IGNORE); - SU2_MPI::Recv(DonorIndex[iSend], numCoeff, MPI_LONG, jProcessor, 0, SU2_MPI::GetComm(), MPI_STATUS_IGNORE); + SU2_MPI::Recv(DonorIndex[iSend], numCoeff, MPI_LONG, jProcessor, 0, SU2_MPI::GetComm(), MPI_STATUS_IGNORE); SU2_MPI::Recv(DonorCoeff[iSend], numCoeff, MPI_DOUBLE, jProcessor, 0, SU2_MPI::GetComm(), MPI_STATUS_IGNORE); - } - else if (rank == jProcessor) { + } else if (rank == jProcessor) { /*--- "I'm" the donor, send. ---*/ SU2_MPI::Send(sendGlobalIndex.data(), numCoeff, MPI_LONG, iProcessor, 0, SU2_MPI::GetComm()); - SU2_MPI::Send(sendDonorIndex.data(), numCoeff, MPI_LONG, iProcessor, 0, SU2_MPI::GetComm()); + SU2_MPI::Send(sendDonorIndex.data(), numCoeff, MPI_LONG, iProcessor, 0, SU2_MPI::GetComm()); SU2_MPI::Send(sendDonorCoeff.data(), numCoeff, MPI_DOUBLE, iProcessor, 0, SU2_MPI::GetComm()); } } @@ -192,11 +182,9 @@ void CMirror::SetTransferCoeff(const CConfig* const* config) { /*--- Loop over the vertices on the target marker, define one row of the transpose matrix. ---*/ - SU2_OMP_PARALLEL - { - SU2_OMP_FOR_DYN(roundUpDiv(nVertexTarget, 2*omp_get_max_threads())) + SU2_OMP_PARALLEL { + SU2_OMP_FOR_DYN(roundUpDiv(nVertexTarget, 2 * omp_get_max_threads())) for (auto iVertex = 0ul; iVertex < nVertexTarget; ++iVertex) { - auto& target_vertex = targetVertices[markTarget][iVertex]; const auto iPoint = target_geometry->vertex[markTarget][iVertex]->GetNode(); @@ -207,11 +195,11 @@ void CMirror::SetTransferCoeff(const CConfig* const* config) { /*--- Count donors and safe the binary search results (this is why we sorted the matrix). ---*/ auto nDonor = 0ul; - vector > ranges(nSend); + vector > ranges(nSend); for (int iSend = 0; iSend < nSend; ++iSend) { const auto iProcessor = iSendProcessor[iSend]; const auto numCoeff = allNumNodeDonor[iProcessor]; - auto p = equal_range(DonorIndex[iSend], DonorIndex[iSend]+numCoeff, targetGlobalIndex); + auto p = equal_range(DonorIndex[iSend], DonorIndex[iSend] + numCoeff, targetGlobalIndex); nDonor += (p.second - p.first); ranges[iSend] = p; } @@ -238,10 +226,12 @@ void CMirror::SetTransferCoeff(const CConfig* const* config) { END_SU2_OMP_PARALLEL /*--- Free the heap allocations. ---*/ - for (auto ptr : GlobalIndex) if (ptr != sendGlobalIndex.data()) delete [] ptr; - for (auto ptr : DonorIndex) if (ptr != sendDonorIndex.data()) delete [] ptr; - for (auto ptr : DonorCoeff) if (ptr != sendDonorCoeff.data()) delete [] ptr; - - } // end marker loop - + for (auto ptr : GlobalIndex) + if (ptr != sendGlobalIndex.data()) delete[] ptr; + for (auto ptr : DonorIndex) + if (ptr != sendDonorIndex.data()) delete[] ptr; + for (auto ptr : DonorCoeff) + if (ptr != sendDonorCoeff.data()) delete[] ptr; + + } // end marker loop } diff --git a/Common/src/interface_interpolation/CNearestNeighbor.cpp b/Common/src/interface_interpolation/CNearestNeighbor.cpp index 8518b4a19dc..1fba622ef70 100644 --- a/Common/src/interface_interpolation/CNearestNeighbor.cpp +++ b/Common/src/interface_interpolation/CNearestNeighbor.cpp @@ -30,9 +30,9 @@ #include "../../include/geometry/CGeometry.hpp" #include "../../include/toolboxes/geometry_toolbox.hpp" -CNearestNeighbor::CNearestNeighbor(CGeometry ****geometry_container, const CConfig* const* config, - unsigned int iZone, unsigned int jZone) : - CInterpolator(geometry_container, config, iZone, jZone) { +CNearestNeighbor::CNearestNeighbor(CGeometry**** geometry_container, const CConfig* const* config, unsigned int iZone, + unsigned int jZone) + : CInterpolator(geometry_container, config, iZone, jZone) { SetTransferCoeff(config); } @@ -42,7 +42,6 @@ void CNearestNeighbor::PrintStatistics() const { } void CNearestNeighbor::SetTransferCoeff(const CConfig* const* config) { - /*--- Desired number of donor points. ---*/ const auto nDonor = max(config[donorZone]->GetNumNearestNeighbors(), 1); @@ -50,10 +49,10 @@ void CNearestNeighbor::SetTransferCoeff(const CConfig* const* config) { const su2double eps = numeric_limits::epsilon(); const int nProcessor = size; - const auto nMarkerInt = config[donorZone]->GetMarker_n_ZoneInterface()/2; + const auto nMarkerInt = config[donorZone]->GetMarker_n_ZoneInterface() / 2; const auto nDim = donor_geometry->GetnDim(); - Buffer_Receive_nVertex_Donor = new unsigned long [nProcessor]; + Buffer_Receive_nVertex_Donor = new unsigned long[nProcessor]; targetVertices.resize(config[targetZone]->GetnMarker_All()); @@ -65,7 +64,6 @@ void CNearestNeighbor::SetTransferCoeff(const CConfig* const* config) { unsigned long totalTargetPoints = 0; for (unsigned short iMarkerInt = 0; iMarkerInt < nMarkerInt; iMarkerInt++) { - /*--- On the donor side: find the tag of the boundary sharing the interface. ---*/ const auto markDonor = config[donorZone]->FindInterfaceMarker(iMarkerInt); @@ -83,8 +81,8 @@ void CNearestNeighbor::SetTransferCoeff(const CConfig* const* config) { Determine_ArraySize(markDonor, markTarget, nVertexDonor, nDim); if (nVertexTarget) targetVertices[markTarget].resize(nVertexTarget); - const auto nPossibleDonor = accumulate(Buffer_Receive_nVertex_Donor, - Buffer_Receive_nVertex_Donor+nProcessor, 0ul); + const auto nPossibleDonor = + accumulate(Buffer_Receive_nVertex_Donor, Buffer_Receive_nVertex_Donor + nProcessor, 0ul); Buffer_Send_Coord.resize(MaxLocalVertex_Donor, nDim); Buffer_Send_GlobalPoint.resize(MaxLocalVertex_Donor); @@ -95,80 +93,74 @@ void CNearestNeighbor::SetTransferCoeff(const CConfig* const* config) { Collect_VertexInfo(markDonor, markTarget, nVertexDonor, nDim); /*--- Find the closest donor points to each target. ---*/ - SU2_OMP_PARALLEL - { - /*--- Working array for this thread. ---*/ - auto& donorInfo = DonorInfoVec[omp_get_thread_num()]; - donorInfo.resize(nPossibleDonor); - - su2double avgDist = 0.0, maxDist = 0.0; - unsigned long numTarget = 0; - - SU2_OMP_FOR_DYN(roundUpDiv(nVertexTarget,2*omp_get_max_threads())) - for (auto iVertexTarget = 0ul; iVertexTarget < nVertexTarget; iVertexTarget++) { - - auto& target_vertex = targetVertices[markTarget][iVertexTarget]; - const auto Point_Target = target_geometry->vertex[markTarget][iVertexTarget]->GetNode(); - - if (!target_geometry->nodes->GetDomain(Point_Target)) continue; - - /*--- Coordinates of the target point. ---*/ - const su2double* Coord_i = target_geometry->nodes->GetCoord(Point_Target); - - /*--- Compute all distances. ---*/ - for (int iProcessor = 0, iDonor = 0; iProcessor < nProcessor; ++iProcessor) { - for (auto jVertex = 0ul; jVertex < Buffer_Receive_nVertex_Donor[iProcessor]; ++jVertex) { - - const auto idx = iProcessor*MaxLocalVertex_Donor + jVertex; - const auto pGlobalPoint = Buffer_Receive_GlobalPoint[idx]; - const su2double* Coord_j = Buffer_Receive_Coord[idx]; - const auto dist2 = GeometryToolbox::SquaredDistance(nDim, Coord_i, Coord_j); - - donorInfo[iDonor++] = DonorInfo(dist2, pGlobalPoint, iProcessor); + SU2_OMP_PARALLEL { + /*--- Working array for this thread. ---*/ + auto& donorInfo = DonorInfoVec[omp_get_thread_num()]; + donorInfo.resize(nPossibleDonor); + + su2double avgDist = 0.0, maxDist = 0.0; + unsigned long numTarget = 0; + + SU2_OMP_FOR_DYN(roundUpDiv(nVertexTarget, 2 * omp_get_max_threads())) + for (auto iVertexTarget = 0ul; iVertexTarget < nVertexTarget; iVertexTarget++) { + auto& target_vertex = targetVertices[markTarget][iVertexTarget]; + const auto Point_Target = target_geometry->vertex[markTarget][iVertexTarget]->GetNode(); + + if (!target_geometry->nodes->GetDomain(Point_Target)) continue; + + /*--- Coordinates of the target point. ---*/ + const su2double* Coord_i = target_geometry->nodes->GetCoord(Point_Target); + + /*--- Compute all distances. ---*/ + for (int iProcessor = 0, iDonor = 0; iProcessor < nProcessor; ++iProcessor) { + for (auto jVertex = 0ul; jVertex < Buffer_Receive_nVertex_Donor[iProcessor]; ++jVertex) { + const auto idx = iProcessor * MaxLocalVertex_Donor + jVertex; + const auto pGlobalPoint = Buffer_Receive_GlobalPoint[idx]; + const su2double* Coord_j = Buffer_Receive_Coord[idx]; + const auto dist2 = GeometryToolbox::SquaredDistance(nDim, Coord_i, Coord_j); + + donorInfo[iDonor++] = DonorInfo(dist2, pGlobalPoint, iProcessor); + } } - } - /*--- Find k closest points. ---*/ - partial_sort(donorInfo.begin(), donorInfo.begin()+nDonor, donorInfo.end(), - [](const DonorInfo& a, const DonorInfo& b) { - /*--- Global index is used as tie-breaker to make sorted order independent of initial. ---*/ - return (a.dist != b.dist)? (a.dist < b.dist) : (a.pidx < b.pidx); + /*--- Find k closest points. ---*/ + partial_sort(donorInfo.begin(), donorInfo.begin() + nDonor, donorInfo.end(), + [](const DonorInfo& a, const DonorInfo& b) { + /*--- Global index is used as tie-breaker to make sorted order independent of initial. ---*/ + return (a.dist != b.dist) ? (a.dist < b.dist) : (a.pidx < b.pidx); + }); + + /*--- Update stats. ---*/ + numTarget += 1; + su2double d = sqrt(donorInfo[0].dist); + avgDist += d; + maxDist = max(maxDist, d); + + /*--- Compute interpolation numerators and denominator. ---*/ + su2double denom = 0.0; + for (auto iDonor = 0ul; iDonor < nDonor; ++iDonor) { + donorInfo[iDonor].dist = 1.0 / (donorInfo[iDonor].dist + eps); + denom += donorInfo[iDonor].dist; } - ); - - /*--- Update stats. ---*/ - numTarget += 1; - su2double d = sqrt(donorInfo[0].dist); - avgDist += d; - maxDist = max(maxDist, d); - - /*--- Compute interpolation numerators and denominator. ---*/ - su2double denom = 0.0; - for (auto iDonor = 0ul; iDonor < nDonor; ++iDonor) { - donorInfo[iDonor].dist = 1.0 / (donorInfo[iDonor].dist + eps); - denom += donorInfo[iDonor].dist; - } - /*--- Set interpolation coefficients. ---*/ - target_vertex.resize(nDonor); + /*--- Set interpolation coefficients. ---*/ + target_vertex.resize(nDonor); - for (auto iDonor = 0ul; iDonor < nDonor; ++iDonor) { - target_vertex.globalPoint[iDonor] = donorInfo[iDonor].pidx; - target_vertex.processor[iDonor] = donorInfo[iDonor].proc; - target_vertex.coefficient[iDonor] = donorInfo[iDonor].dist/denom; + for (auto iDonor = 0ul; iDonor < nDonor; ++iDonor) { + target_vertex.globalPoint[iDonor] = donorInfo[iDonor].pidx; + target_vertex.processor[iDonor] = donorInfo[iDonor].proc; + target_vertex.coefficient[iDonor] = donorInfo[iDonor].dist / denom; + } } - } - END_SU2_OMP_FOR - SU2_OMP_CRITICAL - { - totalTargetPoints += numTarget; - AvgDistance += avgDist; - MaxDistance = max(MaxDistance, maxDist); - } - END_SU2_OMP_CRITICAL + END_SU2_OMP_FOR + SU2_OMP_CRITICAL { + totalTargetPoints += numTarget; + AvgDistance += avgDist; + MaxDistance = max(MaxDistance, maxDist); + } + END_SU2_OMP_CRITICAL } END_SU2_OMP_PARALLEL - } delete[] Buffer_Receive_nVertex_Donor; @@ -179,5 +171,4 @@ void CNearestNeighbor::SetTransferCoeff(const CConfig* const* config) { SU2_MPI::Allreduce(&tmp1, &AvgDistance, 1, MPI_DOUBLE, MPI_SUM, SU2_MPI::GetComm()); SU2_MPI::Allreduce(&tmp2, &MaxDistance, 1, MPI_DOUBLE, MPI_MAX, SU2_MPI::GetComm()); AvgDistance /= totalTargetPoints; - } diff --git a/Common/src/interface_interpolation/CRadialBasisFunction.cpp b/Common/src/interface_interpolation/CRadialBasisFunction.cpp index 7433a401299..424c227b745 100644 --- a/Common/src/interface_interpolation/CRadialBasisFunction.cpp +++ b/Common/src/interface_interpolation/CRadialBasisFunction.cpp @@ -38,56 +38,60 @@ #endif #elif defined(HAVE_LAPACK) // dgemm(opA, opB, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc) -extern "C" void dgemm_(const char*, const char*, const int*, const int*, const int*, - const passivedouble*, const passivedouble*, const int*, const passivedouble*, - const int*, const passivedouble*, passivedouble*, const int*); +extern "C" void dgemm_(const char*, const char*, const int*, const int*, const int*, const passivedouble*, + const passivedouble*, const int*, const passivedouble*, const int*, const passivedouble*, + passivedouble*, const int*); #define DGEMM dgemm_ #endif - -CRadialBasisFunction::CRadialBasisFunction(CGeometry ****geometry_container, const CConfig* const* config, - unsigned int iZone, unsigned int jZone) : - CInterpolator(geometry_container, config, iZone, jZone) { +CRadialBasisFunction::CRadialBasisFunction(CGeometry**** geometry_container, const CConfig* const* config, + unsigned int iZone, unsigned int jZone) + : CInterpolator(geometry_container, config, iZone, jZone) { SetTransferCoeff(config); } void CRadialBasisFunction::PrintStatistics() const { if (rank != MASTER_NODE) return; cout.precision(3); - cout << " Min/avg/max number of RBF donors per target point: " - << MinDonors << "/" << AvgDonors << "/" << MaxDonors << "\n" + cout << " Min/avg/max number of RBF donors per target point: " << MinDonors << "/" << AvgDonors << "/" << MaxDonors + << "\n" << " Avg/max correction factor after pruning: " << AvgCorrection << "/" << MaxCorrection; - if (MaxCorrection < 1.1 || AvgCorrection < 1.02) cout << " (ok)\n"; - else if (MaxCorrection < 2.0 && AvgCorrection < 1.05) cout << " (warning)\n"; - else cout << " <<< WARNING >>>\n"; + if (MaxCorrection < 1.1 || AvgCorrection < 1.02) + cout << " (ok)\n"; + else if (MaxCorrection < 2.0 && AvgCorrection < 1.05) + cout << " (warning)\n"; + else + cout << " <<< WARNING >>>\n"; cout << " Interpolation matrix is " << Density << "% dense." << endl; cout.unsetf(ios::floatfield); } -su2double CRadialBasisFunction::Get_RadialBasisValue(RADIAL_BASIS type, const su2double radius, const su2double dist) -{ - su2double rbf = dist/radius; +su2double CRadialBasisFunction::Get_RadialBasisValue(RADIAL_BASIS type, const su2double radius, const su2double dist) { + su2double rbf = dist / radius; switch (type) { - case RADIAL_BASIS::WENDLAND_C2: - if(rbf < 1) rbf = pow(pow((1-rbf),2),2)*(4*rbf+1); // double use of pow(x,2) for optimization - else rbf = 0.0; + if (rbf < 1) + rbf = pow(pow((1 - rbf), 2), 2) * (4 * rbf + 1); // double use of pow(x,2) for optimization + else + rbf = 0.0; break; case RADIAL_BASIS::GAUSSIAN: - rbf = exp(-rbf*rbf); + rbf = exp(-rbf * rbf); break; case RADIAL_BASIS::THIN_PLATE_SPLINE: - if(rbf < numeric_limits::min()) rbf = 0.0; - else rbf *= rbf*log(rbf); + if (rbf < numeric_limits::min()) + rbf = 0.0; + else + rbf *= rbf * log(rbf); break; case RADIAL_BASIS::MULTI_QUADRIC: case RADIAL_BASIS::INV_MULTI_QUADRIC: - rbf = sqrt(1.0+rbf*rbf); - if(type == RADIAL_BASIS::INV_MULTI_QUADRIC) rbf = 1.0/rbf; + rbf = sqrt(1.0 + rbf * rbf); + if (type == RADIAL_BASIS::INV_MULTI_QUADRIC) rbf = 1.0 / rbf; break; } @@ -95,18 +99,17 @@ su2double CRadialBasisFunction::Get_RadialBasisValue(RADIAL_BASIS type, const su } void CRadialBasisFunction::SetTransferCoeff(const CConfig* const* config) { - /*--- RBF options. ---*/ const auto kindRBF = config[donorZone]->GetKindRadialBasisFunction(); const bool usePolynomial = config[donorZone]->GetRadialBasisFunctionPolynomialOption(); const su2double paramRBF = config[donorZone]->GetRadialBasisFunctionParameter(); const su2double pruneTol = config[donorZone]->GetRadialBasisFunctionPruneTol(); - const auto nMarkerInt = config[donorZone]->GetMarker_n_ZoneInterface()/2; + const auto nMarkerInt = config[donorZone]->GetMarker_n_ZoneInterface() / 2; const int nDim = donor_geometry->GetnDim(); const int nProcessor = size; - Buffer_Receive_nVertex_Donor = new unsigned long [nProcessor]; + Buffer_Receive_nVertex_Donor = new unsigned long[nProcessor]; targetVertices.resize(config[targetZone]->GetnMarker_All()); @@ -118,11 +121,10 @@ void CRadialBasisFunction::SetTransferCoeff(const CConfig* const* config) { vector donorCoordinates(nMarkerInt); vector > donorGlobalPoint(nMarkerInt); vector > donorProcessor(nMarkerInt); - vector assignedProcessor(nMarkerInt,-1); - vector totalWork(nProcessor,0); + vector assignedProcessor(nMarkerInt, -1); + vector totalWork(nProcessor, 0); for (unsigned short iMarkerInt = 0; iMarkerInt < nMarkerInt; ++iMarkerInt) { - /*--- On the donor side: find the tag of the boundary sharing the interface. ---*/ const auto markDonor = config[donorZone]->FindInterfaceMarker(iMarkerInt); @@ -130,7 +132,7 @@ void CRadialBasisFunction::SetTransferCoeff(const CConfig* const* config) { const auto markTarget = config[targetZone]->FindInterfaceMarker(iMarkerInt); /*--- If the zone does not contain the interface continue to the next pair of markers. ---*/ - if (!CheckInterfaceBoundary(markDonor,markTarget)) continue; + if (!CheckInterfaceBoundary(markDonor, markTarget)) continue; unsigned long nVertexDonor = 0; if (markDonor != -1) nVertexDonor = donor_geometry->GetnVertex(markDonor); @@ -139,8 +141,8 @@ void CRadialBasisFunction::SetTransferCoeff(const CConfig* const* config) { Determine_ArraySize(markDonor, markTarget, nVertexDonor, nDim); /*--- Compute total number of donor vertices. ---*/ - const auto nGlobalVertexDonor = accumulate(Buffer_Receive_nVertex_Donor, - Buffer_Receive_nVertex_Donor+nProcessor, 0ul); + const auto nGlobalVertexDonor = + accumulate(Buffer_Receive_nVertex_Donor, Buffer_Receive_nVertex_Donor + nProcessor, 0ul); /*--- Gather coordinates and global point indices. ---*/ Buffer_Send_Coord.resize(MaxLocalVertex_Donor, nDim); @@ -162,9 +164,8 @@ void CRadialBasisFunction::SetTransferCoeff(const CConfig* const* config) { for (int iProcessor = 0; iProcessor < nProcessor; ++iProcessor) { auto offset = iProcessor * MaxLocalVertex_Donor; for (auto iVertex = 0ul; iVertex < Buffer_Receive_nVertex_Donor[iProcessor]; ++iVertex) { - for (int iDim = 0; iDim < nDim; ++iDim) - donorCoord(iCount,iDim) = Buffer_Receive_Coord(offset+iVertex, iDim); - donorPoint[iCount] = Buffer_Receive_GlobalPoint[offset+iVertex]; + for (int iDim = 0; iDim < nDim; ++iDim) donorCoord(iCount, iDim) = Buffer_Receive_Coord(offset + iVertex, iDim); + donorPoint[iCount] = Buffer_Receive_GlobalPoint[offset + iVertex]; donorProc[iCount] = iProcessor; ++iCount; } @@ -175,7 +176,7 @@ void CRadialBasisFunction::SetTransferCoeff(const CConfig* const* config) { * number of the RBF matrix, avoids diff results with diff number of ranks. ---*/ vector order(nGlobalVertexDonor); iota(order.begin(), order.end(), 0); - sort(order.begin(), order.end(), [&donorPoint](int i, int j){return donorPoint[i] < donorPoint[j];}); + sort(order.begin(), order.end(), [&donorPoint](int i, int j) { return donorPoint[i] < donorPoint[j]; }); for (int i = 0; i < int(nGlobalVertexDonor); ++i) { int j = order[i]; @@ -183,8 +184,7 @@ void CRadialBasisFunction::SetTransferCoeff(const CConfig* const* config) { if (i == j) continue; swap(donorProc[i], donorProc[j]); swap(donorPoint[i], donorPoint[j]); - for (int iDim = 0; iDim < nDim; ++iDim) - swap(donorCoord(i,iDim), donorCoord(j,iDim)); + for (int iDim = 0; iDim < nDim; ++iDim) swap(donorCoord(i, iDim), donorCoord(j, iDim)); } /*--- Static work scheduling over ranks based on which one has less work currently. ---*/ @@ -192,24 +192,22 @@ void CRadialBasisFunction::SetTransferCoeff(const CConfig* const* config) { for (int i = 1; i < nProcessor; ++i) if (totalWork[i] < totalWork[iProcessor]) iProcessor = i; - totalWork[iProcessor] += pow(nGlobalVertexDonor,3); // based on matrix inversion. + totalWork[iProcessor] += pow(nGlobalVertexDonor, 3); // based on matrix inversion. assignedProcessor[iMarkerInt] = iProcessor; - } delete[] Buffer_Receive_nVertex_Donor; /*--- Compute the interpolation matrices for each patch of coordinates * assigned to the rank. Subdivide work further by threads. ---*/ - vector nPolynomialVec(nMarkerInt,-1); - vector > keepPolynomialRowVec(nMarkerInt, vector(nDim,1)); + vector nPolynomialVec(nMarkerInt, -1); + vector > keepPolynomialRowVec(nMarkerInt, vector(nDim, 1)); vector CinvTrucVec(nMarkerInt); SU2_OMP_PARALLEL_(for schedule(dynamic,1)) for (unsigned short iMarkerInt = 0; iMarkerInt < nMarkerInt; ++iMarkerInt) { if (rank == assignedProcessor[iMarkerInt]) { - ComputeGeneratorMatrix(kindRBF, usePolynomial, paramRBF, - donorCoordinates[iMarkerInt], nPolynomialVec[iMarkerInt], + ComputeGeneratorMatrix(kindRBF, usePolynomial, paramRBF, donorCoordinates[iMarkerInt], nPolynomialVec[iMarkerInt], keepPolynomialRowVec[iMarkerInt], CinvTrucVec[iMarkerInt]); } } @@ -219,10 +217,12 @@ void CRadialBasisFunction::SetTransferCoeff(const CConfig* const* config) { /*--- Initialize variables for interpolation statistics. ---*/ unsigned long totalTargetPoints = 0, totalDonorPoints = 0, denseSize = 0; - MinDonors = 1<<30; MaxDonors = 0; MaxCorrection = 0.0; AvgCorrection = 0.0; + MinDonors = 1 << 30; + MaxDonors = 0; + MaxCorrection = 0.0; + AvgCorrection = 0.0; for (unsigned short iMarkerInt = 0; iMarkerInt < nMarkerInt; iMarkerInt++) { - /*--- Identify the rank that computed the interpolation matrix for this marker. ---*/ const int iProcessor = assignedProcessor[iMarkerInt]; /*--- If no processor was assigned to work, the zone does not contain the interface. ---*/ @@ -252,19 +252,17 @@ void CRadialBasisFunction::SetTransferCoeff(const CConfig* const* config) { /*--- Send C_inv_trunc only to the ranks that need it (those with target points), * partial broadcast. MPI wrapper not used due to passive double. ---*/ vector allNumVertex(nProcessor); - SU2_MPI::Allgather(&nVertexTarget, 1, MPI_UNSIGNED_LONG, - allNumVertex.data(), 1, MPI_UNSIGNED_LONG, SU2_MPI::GetComm()); + SU2_MPI::Allgather(&nVertexTarget, 1, MPI_UNSIGNED_LONG, allNumVertex.data(), 1, MPI_UNSIGNED_LONG, + SU2_MPI::GetComm()); if (rank == iProcessor) { for (int jProcessor = 0; jProcessor < nProcessor; ++jProcessor) if ((jProcessor != iProcessor) && (allNumVertex[jProcessor] != 0)) - MPI_Send(C_inv_trunc.data(), C_inv_trunc.size(), - MPI_DOUBLE, jProcessor, 0, SU2_MPI::GetComm()); - } - else if (nVertexTarget != 0) { - C_inv_trunc.resize(1+nPolynomial+nGlobalVertexDonor, nGlobalVertexDonor); - MPI_Recv(C_inv_trunc.data(), C_inv_trunc.size(), MPI_DOUBLE, - iProcessor, 0, SU2_MPI::GetComm(), MPI_STATUS_IGNORE); + MPI_Send(C_inv_trunc.data(), C_inv_trunc.size(), MPI_DOUBLE, jProcessor, 0, SU2_MPI::GetComm()); + } else if (nVertexTarget != 0) { + C_inv_trunc.resize(1 + nPolynomial + nGlobalVertexDonor, nGlobalVertexDonor); + MPI_Recv(C_inv_trunc.data(), C_inv_trunc.size(), MPI_DOUBLE, iProcessor, 0, SU2_MPI::GetComm(), + MPI_STATUS_IGNORE); } #endif @@ -283,123 +281,119 @@ void CRadialBasisFunction::SetTransferCoeff(const CConfig* const* config) { targetCoord[iVertexTarget] = target_geometry->nodes->GetCoord(pointTarget); } totalTargetPoints += nVertexTarget; - denseSize += nVertexTarget*nGlobalVertexDonor; + denseSize += nVertexTarget * nGlobalVertexDonor; /*--- Distribute target slabs over the threads in the rank for processing. ---*/ SU2_OMP_PARALLEL if (nVertexTarget > 0) { - - constexpr unsigned long targetSlabSize = 32; - - su2passivematrix funcMat(targetSlabSize, 1+nPolynomial+nGlobalVertexDonor); - su2passivematrix interpMat(targetSlabSize, nGlobalVertexDonor); - - /*--- Thread-local variables for statistics. ---*/ - unsigned long minDonors = 1<<30, maxDonors = 0, totalDonors = 0; - passivedouble sumCorr = 0.0, maxCorr = 0.0; - - SU2_OMP_FOR_DYN(1) - for (auto iVertexTarget = 0ul; iVertexTarget < nVertexTarget; iVertexTarget += targetSlabSize) { - - const auto iLastVertex = min(nVertexTarget, iVertexTarget+targetSlabSize); - const auto slabSize = iLastVertex - iVertexTarget; - - /*--- Prepare matrix of functions A (the targets to donors matrix). ---*/ - - /*--- Polynominal part: ---*/ - if (usePolynomial) { - /*--- Constant term. ---*/ - for (auto k = 0ul; k < slabSize; ++k) funcMat(k,0) = 1.0; - - /*--- Linear terms. ---*/ - for (int iDim = 0, idx = 1; iDim < nDim; ++iDim) { - /*--- Of which one may have been excluded. ---*/ - if (!keepPolynomialRow[iDim]) continue; - for (auto k = 0ul; k < slabSize; ++k) - funcMat(k, idx) = SU2_TYPE::GetValue(targetCoord[iVertexTarget+k][iDim]); - idx += 1; + constexpr unsigned long targetSlabSize = 32; + + su2passivematrix funcMat(targetSlabSize, 1 + nPolynomial + nGlobalVertexDonor); + su2passivematrix interpMat(targetSlabSize, nGlobalVertexDonor); + + /*--- Thread-local variables for statistics. ---*/ + unsigned long minDonors = 1 << 30, maxDonors = 0, totalDonors = 0; + passivedouble sumCorr = 0.0, maxCorr = 0.0; + + SU2_OMP_FOR_DYN(1) + for (auto iVertexTarget = 0ul; iVertexTarget < nVertexTarget; iVertexTarget += targetSlabSize) { + const auto iLastVertex = min(nVertexTarget, iVertexTarget + targetSlabSize); + const auto slabSize = iLastVertex - iVertexTarget; + + /*--- Prepare matrix of functions A (the targets to donors matrix). ---*/ + + /*--- Polynominal part: ---*/ + if (usePolynomial) { + /*--- Constant term. ---*/ + for (auto k = 0ul; k < slabSize; ++k) funcMat(k, 0) = 1.0; + + /*--- Linear terms. ---*/ + for (int iDim = 0, idx = 1; iDim < nDim; ++iDim) { + /*--- Of which one may have been excluded. ---*/ + if (!keepPolynomialRow[iDim]) continue; + for (auto k = 0ul; k < slabSize; ++k) + funcMat(k, idx) = SU2_TYPE::GetValue(targetCoord[iVertexTarget + k][iDim]); + idx += 1; + } } - } - /*--- RBF terms: ---*/ - for (auto iVertexDonor = 0ul; iVertexDonor < nGlobalVertexDonor; ++iVertexDonor) { - for (auto k = 0ul; k < slabSize; ++k) { - auto dist = GeometryToolbox::Distance(nDim, targetCoord[iVertexTarget+k], donorCoord[iVertexDonor]); - auto rbf = Get_RadialBasisValue(kindRBF, paramRBF, dist); - funcMat(k, 1+nPolynomial+iVertexDonor) = SU2_TYPE::GetValue(rbf); + /*--- RBF terms: ---*/ + for (auto iVertexDonor = 0ul; iVertexDonor < nGlobalVertexDonor; ++iVertexDonor) { + for (auto k = 0ul; k < slabSize; ++k) { + auto dist = GeometryToolbox::Distance(nDim, targetCoord[iVertexTarget + k], donorCoord[iVertexDonor]); + auto rbf = Get_RadialBasisValue(kindRBF, paramRBF, dist); + funcMat(k, 1 + nPolynomial + iVertexDonor) = SU2_TYPE::GetValue(rbf); + } } - } - /*--- Compute slab of the interpolation matrix. ---*/ + /*--- Compute slab of the interpolation matrix. ---*/ #ifdef HAVE_LAPACK - /*--- interpMat = funcMat * C_inv_trunc, but order of gemm arguments - * is swapped due to row-major storage of su2passivematrix. ---*/ - const char op = 'N'; - const int M = interpMat.cols(), N = slabSize, K = funcMat.cols(); - // lda = C_inv_trunc.cols() = M; ldb = funcMat.cols() = K; ldc = interpMat.cols() = M; - const passivedouble alpha = 1.0, beta = 0.0; - DGEMM(&op, &op, &M, &N, &K, &alpha, C_inv_trunc[0], &M, funcMat[0], &K, &beta, interpMat[0], &M); + /*--- interpMat = funcMat * C_inv_trunc, but order of gemm arguments + * is swapped due to row-major storage of su2passivematrix. ---*/ + const char op = 'N'; + const int M = interpMat.cols(), N = slabSize, K = funcMat.cols(); + // lda = C_inv_trunc.cols() = M; ldb = funcMat.cols() = K; ldc = interpMat.cols() = M; + const passivedouble alpha = 1.0, beta = 0.0; + DGEMM(&op, &op, &M, &N, &K, &alpha, C_inv_trunc[0], &M, funcMat[0], &K, &beta, interpMat[0], &M); #else - /*--- Naive product, loop order considers short-wide - * nature of funcMat and interpMat. ---*/ - interpMat = 0.0; - for (auto k = 0ul; k < funcMat.cols(); ++k) - for (auto i = 0ul; i < slabSize; ++i) - for (auto j = 0ul; j < interpMat.cols(); ++j) - interpMat(i,j) += funcMat(i,k) * C_inv_trunc(k,j); + /*--- Naive product, loop order considers short-wide + * nature of funcMat and interpMat. ---*/ + interpMat = 0.0; + for (auto k = 0ul; k < funcMat.cols(); ++k) + for (auto i = 0ul; i < slabSize; ++i) + for (auto j = 0ul; j < interpMat.cols(); ++j) interpMat(i, j) += funcMat(i, k) * C_inv_trunc(k, j); #endif - /*--- Set interpolation coefficients. ---*/ - - for (auto k = 0ul; k < slabSize; ++k) { - auto& targetVertex = targetVertices[markTarget][iVertexTarget+k]; - - /*--- Prune small coefficients. ---*/ - auto info = PruneSmallCoefficients(SU2_TYPE::GetValue(pruneTol), interpMat.cols(), interpMat[k]); - auto nnz = info.first; - totalDonors += nnz; - minDonors = min(minDonors, nnz); - maxDonors = max(maxDonors, nnz); - auto corr = fabs(info.second-1.0); // far from 1 either way is bad; - sumCorr += corr; - maxCorr = max(maxCorr, corr); - - /*--- Allocate and set donor information for this target point. ---*/ - targetVertex.resize(nnz); - - for (unsigned long iVertex = 0, iSet = 0; iVertex < nGlobalVertexDonor; ++iVertex) { - auto coeff = interpMat(k,iVertex); - if (fabs(coeff) > 0.0) { - targetVertex.processor[iSet] = donorProc[iVertex]; - targetVertex.globalPoint[iSet] = donorPoint[iVertex]; - targetVertex.coefficient[iSet] = coeff; - ++iSet; + /*--- Set interpolation coefficients. ---*/ + + for (auto k = 0ul; k < slabSize; ++k) { + auto& targetVertex = targetVertices[markTarget][iVertexTarget + k]; + + /*--- Prune small coefficients. ---*/ + auto info = PruneSmallCoefficients(SU2_TYPE::GetValue(pruneTol), interpMat.cols(), interpMat[k]); + auto nnz = info.first; + totalDonors += nnz; + minDonors = min(minDonors, nnz); + maxDonors = max(maxDonors, nnz); + auto corr = fabs(info.second - 1.0); // far from 1 either way is bad; + sumCorr += corr; + maxCorr = max(maxCorr, corr); + + /*--- Allocate and set donor information for this target point. ---*/ + targetVertex.resize(nnz); + + for (unsigned long iVertex = 0, iSet = 0; iVertex < nGlobalVertexDonor; ++iVertex) { + auto coeff = interpMat(k, iVertex); + if (fabs(coeff) > 0.0) { + targetVertex.processor[iSet] = donorProc[iVertex]; + targetVertex.globalPoint[iSet] = donorPoint[iVertex]; + targetVertex.coefficient[iSet] = coeff; + ++iSet; + } } } + } // end target vertex loop + END_SU2_OMP_FOR + SU2_OMP_CRITICAL { + totalDonorPoints += totalDonors; + MinDonors = min(MinDonors, minDonors); + MaxDonors = max(MaxDonors, maxDonors); + AvgCorrection += sumCorr; + MaxCorrection = max(MaxCorrection, maxCorr); } - } // end target vertex loop - END_SU2_OMP_FOR - SU2_OMP_CRITICAL - { - totalDonorPoints += totalDonors; - MinDonors = min(MinDonors, minDonors); - MaxDonors = max(MaxDonors, maxDonors); - AvgCorrection += sumCorr; - MaxCorrection = max(MaxCorrection, maxCorr); - } - END_SU2_OMP_CRITICAL + END_SU2_OMP_CRITICAL } END_SU2_OMP_PARALLEL /*--- Free global data that will no longer be used. ---*/ - donorCoord.resize(0,0); + donorCoord.resize(0, 0); vector().swap(donorPoint); vector().swap(donorProc); - C_inv_trunc.resize(0,0); + C_inv_trunc.resize(0, 0); - } // end loop over interface markers + } // end loop over interface markers /*--- Final reduction of interpolation statistics and basic sanity checks. ---*/ - auto Reduce = [](SU2_MPI::Op op, unsigned long &val) { + auto Reduce = [](SU2_MPI::Op op, unsigned long& val) { auto tmp = val; SU2_MPI::Allreduce(&tmp, &val, 1, MPI_UNSIGNED_LONG, op, SU2_MPI::GetComm()); }; @@ -413,26 +407,25 @@ void CRadialBasisFunction::SetTransferCoeff(const CConfig* const* config) { MPI_Allreduce(&tmp1, &AvgCorrection, 1, MPI_DOUBLE, MPI_SUM, SU2_MPI::GetComm()); MPI_Allreduce(&tmp2, &MaxCorrection, 1, MPI_DOUBLE, MPI_MAX, SU2_MPI::GetComm()); #endif - if (totalTargetPoints == 0) - SU2_MPI::Error("Somehow there are no target interpolation points.", CURRENT_FUNCTION); + if (totalTargetPoints == 0) SU2_MPI::Error("Somehow there are no target interpolation points.", CURRENT_FUNCTION); if (MinDonors == 0) - SU2_MPI::Error("One or more target points have no donors, either:\n" - " - The interface surfaces are not in contact.\n" - " - The RBF radius is too small.\n" - " - The pruning tolerance is too aggressive.", CURRENT_FUNCTION); - - MaxCorrection += 1.0; // put back the reference "1" + SU2_MPI::Error( + "One or more target points have no donors, either:\n" + " - The interface surfaces are not in contact.\n" + " - The RBF radius is too small.\n" + " - The pruning tolerance is too aggressive.", + CURRENT_FUNCTION); + + MaxCorrection += 1.0; // put back the reference "1" AvgCorrection = AvgCorrection / totalTargetPoints + 1.0; AvgDonors = totalDonorPoints / totalTargetPoints; - Density = totalDonorPoints / (0.01*denseSize); - + Density = totalDonorPoints / (0.01 * denseSize); } -void CRadialBasisFunction::ComputeGeneratorMatrix(RADIAL_BASIS type, bool usePolynomial, - su2double radius, const su2activematrix& coords, int& nPolynomial, - vector& keepPolynomialRow, su2passivematrix& C_inv_trunc) { - +void CRadialBasisFunction::ComputeGeneratorMatrix(RADIAL_BASIS type, bool usePolynomial, su2double radius, + const su2activematrix& coords, int& nPolynomial, + vector& keepPolynomialRow, su2passivematrix& C_inv_trunc) { const su2double interfaceCoordTol = 1e6 * numeric_limits::epsilon(); const int nVertexDonor = coords.rows(); @@ -443,24 +436,22 @@ void CRadialBasisFunction::ComputeGeneratorMatrix(RADIAL_BASIS type, bool usePol for (int iVertex = 0; iVertex < nVertexDonor; ++iVertex) for (int jVertex = iVertex; jVertex < nVertexDonor; ++jVertex) - global_M(iVertex, jVertex) = SU2_TYPE::GetValue(Get_RadialBasisValue(type, radius, - GeometryToolbox::Distance(nDim, coords[iVertex], coords[jVertex]))); + global_M(iVertex, jVertex) = SU2_TYPE::GetValue( + Get_RadialBasisValue(type, radius, GeometryToolbox::Distance(nDim, coords[iVertex], coords[jVertex]))); /*--- Invert M matrix (operation is in-place). ---*/ - const bool kernelIsSPD = (type==RADIAL_BASIS::WENDLAND_C2) || (type==RADIAL_BASIS::GAUSSIAN) || - (type==RADIAL_BASIS::INV_MULTI_QUADRIC); + const bool kernelIsSPD = (type == RADIAL_BASIS::WENDLAND_C2) || (type == RADIAL_BASIS::GAUSSIAN) || + (type == RADIAL_BASIS::INV_MULTI_QUADRIC); global_M.Invert(kernelIsSPD); /*--- Compute C_inv_trunc. ---*/ if (usePolynomial) { - /*--- Fill P matrix (P for points, with an extra top row of ones). ---*/ - su2passivematrix P(1+nDim, nVertexDonor); + su2passivematrix P(1 + nDim, nVertexDonor); for (int iVertex = 0; iVertex < nVertexDonor; iVertex++) { P(0, iVertex) = 1.0; - for (int iDim = 0; iDim < nDim; ++iDim) - P(1+iDim, iVertex) = SU2_TYPE::GetValue(coords(iVertex, iDim)); + for (int iDim = 0; iDim < nDim; ++iDim) P(1 + iDim, iVertex) = SU2_TYPE::GetValue(coords(iVertex, iDim)); } /*--- Check if points lie on a plane and remove one coordinate from P if so. ---*/ @@ -471,13 +462,12 @@ void CRadialBasisFunction::ComputeGeneratorMatrix(RADIAL_BASIS type, bool usePol global_M.MatMatMult('R', P, Q); /*--- Compute Mp = (Q * P^T)^-1 ---*/ - CSymmetricMatrix Mp(nPolynomial+1); + CSymmetricMatrix Mp(nPolynomial + 1); for (int i = 0; i <= nPolynomial; ++i) for (int j = i; j <= nPolynomial; ++j) { - Mp(i,j) = 0.0; - for (int k = 0; k < nVertexDonor; ++k) - Mp(i,j) += Q(i,k) * P(j,k); + Mp(i, j) = 0.0; + for (int k = 0; k < nVertexDonor; ++k) Mp(i, j) += Q(i, k) * P(j, k); } Mp.Invert(false); @@ -490,40 +480,36 @@ void CRadialBasisFunction::ComputeGeneratorMatrix(RADIAL_BASIS type, bool usePol #ifdef HAVE_LAPACK /*--- Order of gemm arguments swapped due to row-major storage. ---*/ const char opa = 'N', opb = 'T'; - const int M = nVertexDonor, N = nVertexDonor, K = nPolynomial+1; + const int M = nVertexDonor, N = nVertexDonor, K = nPolynomial + 1; // lda = C_inv_top.cols() = M; ldb = Q.cols() = M; ldc = C_inv_bot.cols() = M; const passivedouble alpha = -1.0, beta = 1.0; DGEMM(&opa, &opb, &M, &N, &K, &alpha, C_inv_top[0], &M, Q[0], &M, &beta, C_inv_bot[0], &M); -#else // naive product +#else // naive product for (int i = 0; i < nVertexDonor; ++i) for (int j = 0; j < nVertexDonor; ++j) - for (int k = 0; k <= nPolynomial; ++k) - C_inv_bot(i,j) -= Q(k,i) * C_inv_top(k,j); + for (int k = 0; k <= nPolynomial; ++k) C_inv_bot(i, j) -= Q(k, i) * C_inv_top(k, j); #endif /*--- Merge top and bottom of C_inv_trunc. More intrusive memory * management, or separate handling of top and bottom, would * avoid these copies (and associated temporary vars). ---*/ - C_inv_trunc.resize(1+nPolynomial+nVertexDonor, nVertexDonor); - memcpy(C_inv_trunc[0], C_inv_top.data(), C_inv_top.size()*sizeof(passivedouble)); - memcpy(C_inv_trunc[1+nPolynomial], C_inv_bot.data(), C_inv_bot.size()*sizeof(passivedouble)); - } - else { + C_inv_trunc.resize(1 + nPolynomial + nVertexDonor, nVertexDonor); + memcpy(C_inv_trunc[0], C_inv_top.data(), C_inv_top.size() * sizeof(passivedouble)); + memcpy(C_inv_trunc[1 + nPolynomial], C_inv_bot.data(), C_inv_bot.size() * sizeof(passivedouble)); + } else { /*--- No polynomial term used in the interpolation, C_inv_trunc = M^-1. ---*/ C_inv_trunc = global_M.StealData(); - } // end usePolynomial - + } // end usePolynomial } -int CRadialBasisFunction::CheckPolynomialTerms(su2double max_diff_tol, vector& keep_row, - su2passivematrix &P) { +int CRadialBasisFunction::CheckPolynomialTerms(su2double max_diff_tol, vector& keep_row, su2passivematrix& P) { const int m = P.rows(); const int n = P.cols(); /*--- The first row of P is all ones and we do not care about it for this analysis. ---*/ - const int n_rows = m-1; + const int n_rows = m - 1; keep_row.resize(n_rows); /*--- By default assume points are not on a plane (all rows kept). ---*/ @@ -538,17 +524,16 @@ int CRadialBasisFunction::CheckPolynomialTerms(su2double max_diff_tol, vector rhs(n_rows,0.0), coeff(n_rows); + vector rhs(n_rows, 0.0), coeff(n_rows); for (int i = 0; i < n_rows; ++i) - for (int j = 0; j < n; ++j) - rhs[i] += P(i+1,j); + for (int j = 0; j < n; ++j) rhs[i] += P(i + 1, j); /*--- Multiply the RHS by the inverse thus obtaining the coefficients. ---*/ PPT.MatVecMult(rhs.begin(), coeff.begin()); @@ -556,33 +541,29 @@ int CRadialBasisFunction::CheckPolynomialTerms(su2double max_diff_tol, vector abs(coeff[remove_row])) - remove_row = i; + if (abs(coeff[i]) > abs(coeff[remove_row])) remove_row = i; /*--- Mark row as removed and adjust number of polynomial terms. ---*/ - n_polynomial = n_rows-1; + n_polynomial = n_rows - 1; keep_row[remove_row] = 0; /*--- Truncated P by shifting rows "up". ---*/ - for (auto i = remove_row+1; i < m-1; ++i) - for (int j = 0; j < n; ++j) - P(i,j) = P(i+1,j); + for (auto i = remove_row + 1; i < m - 1; ++i) + for (int j = 0; j < n; ++j) P(i, j) = P(i + 1, j); } return n_polynomial; diff --git a/Common/src/interface_interpolation/CSlidingMesh.cpp b/Common/src/interface_interpolation/CSlidingMesh.cpp index 81c46bf88b6..ca01a7d43df 100644 --- a/Common/src/interface_interpolation/CSlidingMesh.cpp +++ b/Common/src/interface_interpolation/CSlidingMesh.cpp @@ -30,15 +30,13 @@ #include "../../include/geometry/CGeometry.hpp" #include "../../include/toolboxes/geometry_toolbox.hpp" - -CSlidingMesh::CSlidingMesh(CGeometry ****geometry_container, const CConfig* const* config, - unsigned int iZone, unsigned int jZone) : - CInterpolator(geometry_container, config, iZone, jZone) { +CSlidingMesh::CSlidingMesh(CGeometry**** geometry_container, const CConfig* const* config, unsigned int iZone, + unsigned int jZone) + : CInterpolator(geometry_container, config, iZone, jZone) { SetTransferCoeff(config); } void CSlidingMesh::SetTransferCoeff(const CConfig* const* config) { - /* 0 - Variable declaration */ /* --- General variables --- */ @@ -64,7 +62,6 @@ void CSlidingMesh::SetTransferCoeff(const CConfig* const* config) { su2double Area, Area_old, tmp_Area; su2double LineIntersectionLength, *Direction, length; - /* --- Markers Variables --- */ unsigned short iMarkerInt, nMarkerInt; @@ -80,7 +77,7 @@ void CSlidingMesh::SetTransferCoeff(const CConfig* const* config) { su2vector Target_nLinkedNodes; su2vector Target_StartLinkedNodes; - unsigned long *target_segment; + unsigned long* target_segment; su2vector Target_LinkedNodes; su2vector Target_GlobalPoint, Donor_GlobalPoint; @@ -100,7 +97,7 @@ void CSlidingMesh::SetTransferCoeff(const CConfig* const* config) { su2vector Donor_Proc; su2double *donor_iMidEdge_point, *donor_jMidEdge_point; - su2double **donor_element; + su2double** donor_element; su2activematrix DonorPoint_Coord; targetVertices.resize(config[targetZone]->GetnMarker_All()); @@ -113,24 +110,22 @@ void CSlidingMesh::SetTransferCoeff(const CConfig* const* config) { Donor_Vect = nullptr; Coeff_Vect = nullptr; - storeProc = nullptr; + storeProc = nullptr; tmp_Donor_Vect = nullptr; tmp_Coeff_Vect = nullptr; - tmp_storeProc = nullptr; + tmp_storeProc = nullptr; - Normal = new su2double[nDim]; + Normal = new su2double[nDim]; Direction = new su2double[nDim]; - /* 2 - Find boundary tag between touching grids */ /*--- Number of markers on the FSI interface ---*/ - nMarkerInt = (int)( config[ donorZone ]->GetMarker_n_ZoneInterface() ) / 2; + nMarkerInt = (int)(config[donorZone]->GetMarker_n_ZoneInterface()) / 2; /*--- For the number of markers on the interface... ---*/ - for ( iMarkerInt = 0; iMarkerInt < nMarkerInt; iMarkerInt++ ){ - + for (iMarkerInt = 0; iMarkerInt < nMarkerInt; iMarkerInt++) { /*--- On the donor side: find the tag of the boundary sharing the interface ---*/ markDonor = config[donorZone]->FindInterfaceMarker(iMarkerInt); @@ -138,10 +133,10 @@ void CSlidingMesh::SetTransferCoeff(const CConfig* const* config) { markTarget = config[targetZone]->FindInterfaceMarker(iMarkerInt); /*--- Checks if the zone contains the interface, if not continue to the next step ---*/ - if(!CheckInterfaceBoundary(markDonor, markTarget)) continue; + if (!CheckInterfaceBoundary(markDonor, markTarget)) continue; nVertexTarget = 0; - if(markTarget != -1) nVertexTarget = target_geometry->GetnVertex( markTarget ); + if (markTarget != -1) nVertexTarget = target_geometry->GetnVertex(markTarget); /* 3 -Reconstruct the boundaries from parallel partitioning @@ -152,23 +147,23 @@ void CSlidingMesh::SetTransferCoeff(const CConfig* const* config) { nGlobalVertex_Target = nGlobalVertex; - TargetPoint_Coord = Buffer_Receive_Coord; - Target_GlobalPoint = Buffer_Receive_GlobalPoint; - Target_nLinkedNodes = Buffer_Receive_nLinkedNodes; + TargetPoint_Coord = Buffer_Receive_Coord; + Target_GlobalPoint = Buffer_Receive_GlobalPoint; + Target_nLinkedNodes = Buffer_Receive_nLinkedNodes; Target_StartLinkedNodes = Buffer_Receive_StartLinkedNodes; - Target_LinkedNodes = Buffer_Receive_LinkedNodes; + Target_LinkedNodes = Buffer_Receive_LinkedNodes; /*--- Donor boundary ---*/ ReconstructBoundary(donorZone, markDonor); nGlobalVertex_Donor = nGlobalVertex; - DonorPoint_Coord = Buffer_Receive_Coord; - Donor_GlobalPoint = Buffer_Receive_GlobalPoint; - Donor_nLinkedNodes = Buffer_Receive_nLinkedNodes; + DonorPoint_Coord = Buffer_Receive_Coord; + Donor_GlobalPoint = Buffer_Receive_GlobalPoint; + Donor_nLinkedNodes = Buffer_Receive_nLinkedNodes; Donor_StartLinkedNodes = Buffer_Receive_StartLinkedNodes; - Donor_LinkedNodes = Buffer_Receive_LinkedNodes; - Donor_Proc = Buffer_Receive_Proc; + Donor_LinkedNodes = Buffer_Receive_LinkedNodes; + Donor_Proc = Buffer_Receive_Proc; /*--- Starts building the supermesh layer (2D or 3D) ---*/ /* - For each target node, it first finds the closest donor point @@ -178,8 +173,7 @@ void CSlidingMesh::SetTransferCoeff(const CConfig* const* config) { */ if (nVertexTarget) targetVertices[markTarget].resize(nVertexTarget); - if(nDim == 2){ - + if (nDim == 2) { target_iMidEdge_point = new su2double[nDim]; target_jMidEdge_point = new su2double[nDim]; @@ -191,15 +185,13 @@ void CSlidingMesh::SetTransferCoeff(const CConfig* const* config) { target_segment = new unsigned long[2]; for (iVertex = 0; iVertex < nVertexTarget; iVertex++) { - nDonorPoints = 0; /*--- Stores coordinates of the target node ---*/ target_iPoint = target_geometry->vertex[markTarget][iVertex]->GetNode(); - if (target_geometry->nodes->GetDomain(target_iPoint)){ - + if (target_geometry->nodes->GetDomain(target_iPoint)) { Coord_i = target_geometry->nodes->GetCoord(target_iPoint); /*--- Brute force to find the closest donor_node ---*/ @@ -208,8 +200,7 @@ void CSlidingMesh::SetTransferCoeff(const CConfig* const* config) { donor_StartIndex = 0; for (donor_iPoint = 0; donor_iPoint < nGlobalVertex_Donor; donor_iPoint++) { - - Coord_j = DonorPoint_Coord[ donor_iPoint ]; + Coord_j = DonorPoint_Coord[donor_iPoint]; dist = GeometryToolbox::Distance(nDim, Coord_i, Coord_j); @@ -218,45 +209,44 @@ void CSlidingMesh::SetTransferCoeff(const CConfig* const* config) { donor_StartIndex = donor_iPoint; } - if (dist == 0.0){ + if (dist == 0.0) { donor_StartIndex = donor_iPoint; break; } } - donor_iPoint = donor_StartIndex; + donor_iPoint = donor_StartIndex; donor_OldiPoint = donor_iPoint; /*--- Contruct information regarding the target cell ---*/ auto dPoint = target_geometry->nodes->GetGlobalIndex(target_iPoint); for (jVertexTarget = 0; jVertexTarget < nGlobalVertex_Target; jVertexTarget++) - if( dPoint == Target_GlobalPoint[jVertexTarget] ) - break; + if (dPoint == Target_GlobalPoint[jVertexTarget]) break; - if ( Target_nLinkedNodes[jVertexTarget] == 1 ){ - target_segment[0] = Target_LinkedNodes[ Target_StartLinkedNodes[jVertexTarget] ]; + if (Target_nLinkedNodes[jVertexTarget] == 1) { + target_segment[0] = Target_LinkedNodes[Target_StartLinkedNodes[jVertexTarget]]; target_segment[1] = jVertexTarget; - } - else{ - target_segment[0] = Target_LinkedNodes[ Target_StartLinkedNodes[jVertexTarget] ]; - target_segment[1] = Target_LinkedNodes[ Target_StartLinkedNodes[jVertexTarget] + 1]; + } else { + target_segment[0] = Target_LinkedNodes[Target_StartLinkedNodes[jVertexTarget]]; + target_segment[1] = Target_LinkedNodes[Target_StartLinkedNodes[jVertexTarget] + 1]; } dTMP = 0; - for(iDim = 0; iDim < nDim; iDim++){ - target_iMidEdge_point[iDim] = ( TargetPoint_Coord(target_segment[0], iDim ) + - target_geometry->nodes->GetCoord( target_iPoint , iDim) ) / 2.; - target_jMidEdge_point[iDim] = ( TargetPoint_Coord(target_segment[1], iDim ) + - target_geometry->nodes->GetCoord( target_iPoint , iDim) ) / 2.; + for (iDim = 0; iDim < nDim; iDim++) { + target_iMidEdge_point[iDim] = + (TargetPoint_Coord(target_segment[0], iDim) + target_geometry->nodes->GetCoord(target_iPoint, iDim)) / + 2.; + target_jMidEdge_point[iDim] = + (TargetPoint_Coord(target_segment[1], iDim) + target_geometry->nodes->GetCoord(target_iPoint, iDim)) / + 2.; Direction[iDim] = target_jMidEdge_point[iDim] - target_iMidEdge_point[iDim]; dTMP += Direction[iDim] * Direction[iDim]; } dTMP = sqrt(dTMP); - for(iDim = 0; iDim < nDim; iDim++) - Direction[iDim] /= dTMP; + for (iDim = 0; iDim < nDim; iDim++) Direction[iDim] /= dTMP; length = GeometryToolbox::Distance(nDim, target_iMidEdge_point, target_jMidEdge_point); @@ -264,156 +254,153 @@ void CSlidingMesh::SetTransferCoeff(const CConfig* const* config) { /*--- Proceeds along the forward direction (depending on which connected boundary node is found first) ---*/ - while( !check ){ - + while (!check) { /*--- Proceeds until the value of the intersection area is null ---*/ - if ( Donor_nLinkedNodes[donor_iPoint] == 1 ){ - donor_forward_point = Donor_LinkedNodes[ Donor_StartLinkedNodes[donor_iPoint] ]; + if (Donor_nLinkedNodes[donor_iPoint] == 1) { + donor_forward_point = Donor_LinkedNodes[Donor_StartLinkedNodes[donor_iPoint]]; donor_backward_point = donor_iPoint; - } - else{ - uptr = &Donor_LinkedNodes[ Donor_StartLinkedNodes[donor_iPoint] ]; + } else { + uptr = &Donor_LinkedNodes[Donor_StartLinkedNodes[donor_iPoint]]; - if( donor_OldiPoint != uptr[0] ){ - donor_forward_point = uptr[0]; + if (donor_OldiPoint != uptr[0]) { + donor_forward_point = uptr[0]; donor_backward_point = uptr[1]; - } - else{ - donor_forward_point = uptr[1]; + } else { + donor_forward_point = uptr[1]; donor_backward_point = uptr[0]; } } - if(donor_iPoint >= nGlobalVertex_Donor){ + if (donor_iPoint >= nGlobalVertex_Donor) { check = true; continue; } - for(iDim = 0; iDim < nDim; iDim++){ - donor_iMidEdge_point[iDim] = ( DonorPoint_Coord(donor_forward_point, iDim) + - DonorPoint_Coord(donor_iPoint, iDim) ) / 2.; - donor_jMidEdge_point[iDim] = ( DonorPoint_Coord(donor_backward_point, iDim) + - DonorPoint_Coord(donor_iPoint, iDim) ) / 2.; + for (iDim = 0; iDim < nDim; iDim++) { + donor_iMidEdge_point[iDim] = + (DonorPoint_Coord(donor_forward_point, iDim) + DonorPoint_Coord(donor_iPoint, iDim)) / 2.; + donor_jMidEdge_point[iDim] = + (DonorPoint_Coord(donor_backward_point, iDim) + DonorPoint_Coord(donor_iPoint, iDim)) / 2.; } - LineIntersectionLength = ComputeLineIntersectionLength(nDim, target_iMidEdge_point, target_jMidEdge_point, - donor_iMidEdge_point, donor_jMidEdge_point, Direction); + LineIntersectionLength = + ComputeLineIntersectionLength(nDim, target_iMidEdge_point, target_jMidEdge_point, donor_iMidEdge_point, + donor_jMidEdge_point, Direction); - if ( LineIntersectionLength == 0.0 ){ + if (LineIntersectionLength == 0.0) { check = true; continue; } - /*--- In case the element intersects the target cell, update the auxiliary communication data structure ---*/ + /*--- In case the element intersects the target cell, update the auxiliary communication data structure + * ---*/ - tmp_Coeff_Vect = new su2double[ nDonorPoints + 1 ]; - tmp_Donor_Vect = new unsigned long[ nDonorPoints + 1 ]; - tmp_storeProc = new unsigned long[ nDonorPoints + 1 ]; + tmp_Coeff_Vect = new su2double[nDonorPoints + 1]; + tmp_Donor_Vect = new unsigned long[nDonorPoints + 1]; + tmp_storeProc = new unsigned long[nDonorPoints + 1]; - for( iDonor = 0; iDonor < nDonorPoints; iDonor++){ + for (iDonor = 0; iDonor < nDonorPoints; iDonor++) { tmp_Donor_Vect[iDonor] = Donor_Vect[iDonor]; tmp_Coeff_Vect[iDonor] = Coeff_Vect[iDonor]; - tmp_storeProc[iDonor] = storeProc[iDonor]; + tmp_storeProc[iDonor] = storeProc[iDonor]; } - tmp_Donor_Vect[ nDonorPoints ] = donor_iPoint; - tmp_Coeff_Vect[ nDonorPoints ] = LineIntersectionLength / length; - tmp_storeProc[ nDonorPoints ] = Donor_Proc[donor_iPoint]; + tmp_Donor_Vect[nDonorPoints] = donor_iPoint; + tmp_Coeff_Vect[nDonorPoints] = LineIntersectionLength / length; + tmp_storeProc[nDonorPoints] = Donor_Proc[donor_iPoint]; - delete [] Donor_Vect; - delete [] Coeff_Vect; - delete [] storeProc; + delete[] Donor_Vect; + delete[] Coeff_Vect; + delete[] storeProc; Donor_Vect = tmp_Donor_Vect; Coeff_Vect = tmp_Coeff_Vect; - storeProc = tmp_storeProc; + storeProc = tmp_storeProc; donor_OldiPoint = donor_iPoint; - donor_iPoint = donor_forward_point; + donor_iPoint = donor_forward_point; nDonorPoints++; } - if ( Donor_nLinkedNodes[donor_StartIndex] == 2 ){ + if (Donor_nLinkedNodes[donor_StartIndex] == 2) { check = false; - uptr = &Donor_LinkedNodes[ Donor_StartLinkedNodes[donor_StartIndex] ]; + uptr = &Donor_LinkedNodes[Donor_StartLinkedNodes[donor_StartIndex]]; donor_iPoint = uptr[1]; donor_OldiPoint = donor_StartIndex; - } - else + } else check = true; /*--- Proceeds along the backward direction (depending on which connected boundary node is found first) ---*/ - while( !check ){ - + while (!check) { /*--- Proceeds until the value of the intersection length is null ---*/ - if ( Donor_nLinkedNodes[donor_iPoint] == 1 ){ - donor_forward_point = donor_OldiPoint; + if (Donor_nLinkedNodes[donor_iPoint] == 1) { + donor_forward_point = donor_OldiPoint; donor_backward_point = donor_iPoint; - } - else{ - uptr = &Donor_LinkedNodes[ Donor_StartLinkedNodes[donor_iPoint] ]; + } else { + uptr = &Donor_LinkedNodes[Donor_StartLinkedNodes[donor_iPoint]]; - if( donor_OldiPoint != uptr[0] ){ - donor_forward_point = uptr[0]; + if (donor_OldiPoint != uptr[0]) { + donor_forward_point = uptr[0]; donor_backward_point = uptr[1]; - } - else{ - donor_forward_point = uptr[1]; + } else { + donor_forward_point = uptr[1]; donor_backward_point = uptr[0]; } } - if(donor_iPoint >= nGlobalVertex_Donor){ + if (donor_iPoint >= nGlobalVertex_Donor) { check = true; continue; } - for(iDim = 0; iDim < nDim; iDim++){ - donor_iMidEdge_point[iDim] = ( DonorPoint_Coord(donor_forward_point , iDim) + - DonorPoint_Coord(donor_iPoint, iDim) ) / 2.; - donor_jMidEdge_point[iDim] = ( DonorPoint_Coord(donor_backward_point, iDim) + - DonorPoint_Coord(donor_iPoint, iDim) ) / 2.; + for (iDim = 0; iDim < nDim; iDim++) { + donor_iMidEdge_point[iDim] = + (DonorPoint_Coord(donor_forward_point, iDim) + DonorPoint_Coord(donor_iPoint, iDim)) / 2.; + donor_jMidEdge_point[iDim] = + (DonorPoint_Coord(donor_backward_point, iDim) + DonorPoint_Coord(donor_iPoint, iDim)) / 2.; } - LineIntersectionLength = ComputeLineIntersectionLength(nDim, target_iMidEdge_point, target_jMidEdge_point, - donor_iMidEdge_point, donor_jMidEdge_point, Direction); + LineIntersectionLength = + ComputeLineIntersectionLength(nDim, target_iMidEdge_point, target_jMidEdge_point, donor_iMidEdge_point, + donor_jMidEdge_point, Direction); - if ( LineIntersectionLength == 0.0 ){ + if (LineIntersectionLength == 0.0) { check = true; continue; } - /*--- In case the element intersects the target cell, update the auxiliary communication data structure ---*/ + /*--- In case the element intersects the target cell, update the auxiliary communication data structure + * ---*/ - tmp_Coeff_Vect = new su2double[ nDonorPoints + 1 ]; - tmp_Donor_Vect = new unsigned long[ nDonorPoints + 1 ]; - tmp_storeProc = new unsigned long[ nDonorPoints + 1 ]; + tmp_Coeff_Vect = new su2double[nDonorPoints + 1]; + tmp_Donor_Vect = new unsigned long[nDonorPoints + 1]; + tmp_storeProc = new unsigned long[nDonorPoints + 1]; - for( iDonor = 0; iDonor < nDonorPoints; iDonor++){ + for (iDonor = 0; iDonor < nDonorPoints; iDonor++) { tmp_Donor_Vect[iDonor] = Donor_Vect[iDonor]; tmp_Coeff_Vect[iDonor] = Coeff_Vect[iDonor]; - tmp_storeProc[iDonor] = storeProc[iDonor]; + tmp_storeProc[iDonor] = storeProc[iDonor]; } - tmp_Coeff_Vect[ nDonorPoints ] = LineIntersectionLength / length; - tmp_Donor_Vect[ nDonorPoints ] = donor_iPoint; - tmp_storeProc[ nDonorPoints ] = Donor_Proc[donor_iPoint]; + tmp_Coeff_Vect[nDonorPoints] = LineIntersectionLength / length; + tmp_Donor_Vect[nDonorPoints] = donor_iPoint; + tmp_storeProc[nDonorPoints] = Donor_Proc[donor_iPoint]; - delete [] Donor_Vect; - delete [] Coeff_Vect; - delete [] storeProc; + delete[] Donor_Vect; + delete[] Coeff_Vect; + delete[] storeProc; Donor_Vect = tmp_Donor_Vect; Coeff_Vect = tmp_Coeff_Vect; - storeProc = tmp_storeProc; + storeProc = tmp_storeProc; donor_OldiPoint = donor_iPoint; - donor_iPoint = donor_forward_point; + donor_iPoint = donor_forward_point; nDonorPoints++; } @@ -422,7 +409,7 @@ void CSlidingMesh::SetTransferCoeff(const CConfig* const* config) { targetVertices[markTarget][iVertex].resize(nDonorPoints); - for ( iDonor = 0; iDonor < nDonorPoints; iDonor++ ){ + for (iDonor = 0; iDonor < nDonorPoints; iDonor++) { targetVertices[markTarget][iVertex].coefficient[iDonor] = Coeff_Vect[iDonor]; targetVertices[markTarget][iVertex].globalPoint[iDonor] = Donor_GlobalPoint[Donor_Vect[iDonor]]; targetVertices[markTarget][iVertex].processor[iDonor] = storeProc[iDonor]; @@ -430,19 +417,17 @@ void CSlidingMesh::SetTransferCoeff(const CConfig* const* config) { } } - delete [] target_segment; + delete[] target_segment; - delete [] target_iMidEdge_point; - delete [] target_jMidEdge_point; + delete[] target_iMidEdge_point; + delete[] target_jMidEdge_point; - delete [] donor_iMidEdge_point; - delete [] donor_jMidEdge_point; - } - else{ + delete[] donor_iMidEdge_point; + delete[] donor_jMidEdge_point; + } else { /* --- 3D geometry, creates a superficial super-mesh --- */ for (iVertex = 0; iVertex < nVertexTarget; iVertex++) { - nDonorPoints = 0; /*--- Stores coordinates of the target node ---*/ @@ -458,27 +443,23 @@ void CSlidingMesh::SetTransferCoeff(const CConfig* const* config) { /*--- The value of Area computed here includes also portion of boundary belonging to different marker ---*/ Area = GeometryToolbox::Norm(nDim, Normal); - for (iDim = 0; iDim < nDim; iDim++) - Normal[iDim] /= Area; + for (iDim = 0; iDim < nDim; iDim++) Normal[iDim] /= Area; - for (iDim = 0; iDim < nDim; iDim++) - Coord_i[iDim] = target_geometry->nodes->GetCoord(target_iPoint, iDim); + for (iDim = 0; iDim < nDim; iDim++) Coord_i[iDim] = target_geometry->nodes->GetCoord(target_iPoint, iDim); auto dPoint = target_geometry->nodes->GetGlobalIndex(target_iPoint); - for (target_iPoint = 0; target_iPoint < nGlobalVertex_Target; target_iPoint++){ - if( dPoint == Target_GlobalPoint[target_iPoint] ) - break; + for (target_iPoint = 0; target_iPoint < nGlobalVertex_Target; target_iPoint++) { + if (dPoint == Target_GlobalPoint[target_iPoint]) break; } /*--- Build local surface dual mesh for target element ---*/ nEdges_target = Target_nLinkedNodes[target_iPoint]; - nNode_target = 2*(nEdges_target + 1); + nNode_target = 2 * (nEdges_target + 1); target_element = new su2double*[nNode_target]; - for (ii = 0; ii < nNode_target; ii++) - target_element[ii] = new su2double[nDim]; + for (ii = 0; ii < nNode_target; ii++) target_element[ii] = new su2double[nDim]; nNode_target = Build_3D_surface_element(Target_LinkedNodes, Target_StartLinkedNodes, Target_nLinkedNodes, TargetPoint_Coord, target_iPoint, target_element); @@ -489,8 +470,7 @@ void CSlidingMesh::SetTransferCoeff(const CConfig* const* config) { donor_StartIndex = 0; for (donor_iPoint = 0; donor_iPoint < nGlobalVertex_Donor; donor_iPoint++) { - - Coord_j = DonorPoint_Coord[ donor_iPoint ]; + Coord_j = DonorPoint_Coord[donor_iPoint]; dist = GeometryToolbox::Distance(nDim, Coord_i, Coord_j); @@ -499,7 +479,7 @@ void CSlidingMesh::SetTransferCoeff(const CConfig* const* config) { donor_StartIndex = donor_iPoint; } - if (dist == 0.0){ + if (dist == 0.0) { donor_StartIndex = donor_iPoint; break; } @@ -509,36 +489,34 @@ void CSlidingMesh::SetTransferCoeff(const CConfig* const* config) { nEdges_donor = Donor_nLinkedNodes[donor_iPoint]; - donor_element = new su2double*[ 2*nEdges_donor + 2 ]; - for (ii = 0; ii < 2*nEdges_donor + 2; ii++) - donor_element[ii] = new su2double[nDim]; + donor_element = new su2double*[2 * nEdges_donor + 2]; + for (ii = 0; ii < 2 * nEdges_donor + 2; ii++) donor_element[ii] = new su2double[nDim]; nNode_donor = Build_3D_surface_element(Donor_LinkedNodes, Donor_StartLinkedNodes, Donor_nLinkedNodes, DonorPoint_Coord, donor_iPoint, donor_element); Area = 0; - for (ii = 1; ii < nNode_target-1; ii++){ - for (jj = 1; jj < nNode_donor-1; jj++){ - Area += Compute_Triangle_Intersection(target_element[0], target_element[ii], target_element[ii+1], - donor_element[0], donor_element[jj], donor_element[jj+1], Normal); + for (ii = 1; ii < nNode_target - 1; ii++) { + for (jj = 1; jj < nNode_donor - 1; jj++) { + Area += Compute_Triangle_Intersection(target_element[0], target_element[ii], target_element[ii + 1], + donor_element[0], donor_element[jj], donor_element[jj + 1], Normal); } } - for (ii = 0; ii < 2*nEdges_donor + 2; ii++) - delete [] donor_element[ii]; - delete [] donor_element; + for (ii = 0; ii < 2 * nEdges_donor + 2; ii++) delete[] donor_element[ii]; + delete[] donor_element; nDonorPoints = 1; /*--- In case the element intersect the target cell update the auxiliary communication data structure ---*/ - Coeff_Vect = new su2double[ nDonorPoints ]; - Donor_Vect = new unsigned long[ nDonorPoints ]; - storeProc = new unsigned long[ nDonorPoints ]; + Coeff_Vect = new su2double[nDonorPoints]; + Donor_Vect = new unsigned long[nDonorPoints]; + storeProc = new unsigned long[nDonorPoints]; Coeff_Vect[0] = Area; Donor_Vect[0] = donor_iPoint; - storeProc[0] = Donor_Proc[donor_iPoint]; + storeProc[0] = Donor_Proc[donor_iPoint]; alreadyVisitedDonor = new unsigned long[1]; @@ -548,11 +526,11 @@ void CSlidingMesh::SetTransferCoeff(const CConfig* const* config) { Area_old = -1; - while( Area > Area_old ){ - + while (Area > Area_old) { /* * - Starting from the closest donor_point, it expands the supermesh by a countour search pattern. - * - The closest donor element becomes the core, at each iteration a new layer of elements around the core is taken into account + * - The closest donor element becomes the core, at each iteration a new layer of elements around the core is + * taken into account */ Area_old = Area; @@ -560,100 +538,97 @@ void CSlidingMesh::SetTransferCoeff(const CConfig* const* config) { ToVisit = nullptr; nToVisit = 0; - for( iNodeVisited = StartVisited; iNodeVisited < nAlreadyVisited; iNodeVisited++ ){ - - vPoint = alreadyVisitedDonor[ iNodeVisited ]; + for (iNodeVisited = StartVisited; iNodeVisited < nAlreadyVisited; iNodeVisited++) { + vPoint = alreadyVisitedDonor[iNodeVisited]; nEdgeVisited = Donor_nLinkedNodes[vPoint]; - for (iEdgeVisited = 0; iEdgeVisited < nEdgeVisited; iEdgeVisited++){ - - donor_iPoint = Donor_LinkedNodes[ Donor_StartLinkedNodes[vPoint] + iEdgeVisited]; + for (iEdgeVisited = 0; iEdgeVisited < nEdgeVisited; iEdgeVisited++) { + donor_iPoint = Donor_LinkedNodes[Donor_StartLinkedNodes[vPoint] + iEdgeVisited]; /*--- Check if the node to visit is already listed in the data structure to avoid double visits ---*/ check = 0; - for( jj = 0; jj < nAlreadyVisited; jj++ ){ - if( donor_iPoint == alreadyVisitedDonor[jj] ){ + for (jj = 0; jj < nAlreadyVisited; jj++) { + if (donor_iPoint == alreadyVisitedDonor[jj]) { check = 1; break; } } - if( check == 0 && ToVisit != nullptr){ - for( jj = 0; jj < nToVisit; jj++ ) - if( donor_iPoint == ToVisit[jj] ){ + if (check == 0 && ToVisit != nullptr) { + for (jj = 0; jj < nToVisit; jj++) + if (donor_iPoint == ToVisit[jj]) { check = 1; break; } } - if( check == 0 ){ + if (check == 0) { /*--- If the node was not already visited, visit it and list it into data structure ---*/ - tmpVect = new unsigned long[ nToVisit + 1 ]; + tmpVect = new unsigned long[nToVisit + 1]; - for( jj = 0; jj < nToVisit; jj++ ) - tmpVect[jj] = ToVisit[jj]; + for (jj = 0; jj < nToVisit; jj++) tmpVect[jj] = ToVisit[jj]; tmpVect[nToVisit] = donor_iPoint; - - delete [] ToVisit; + delete[] ToVisit; ToVisit = tmpVect; tmpVect = nullptr; nToVisit++; - /*--- Find the value of the intersection area between the current donor element and the target element --- */ + /*--- Find the value of the intersection area between the current donor element and the target element + * --- */ nEdges_donor = Donor_nLinkedNodes[donor_iPoint]; - donor_element = new su2double*[ 2*nEdges_donor + 2 ]; - for (ii = 0; ii < 2*nEdges_donor + 2; ii++) - donor_element[ii] = new su2double[nDim]; + donor_element = new su2double*[2 * nEdges_donor + 2]; + for (ii = 0; ii < 2 * nEdges_donor + 2; ii++) donor_element[ii] = new su2double[nDim]; nNode_donor = Build_3D_surface_element(Donor_LinkedNodes, Donor_StartLinkedNodes, Donor_nLinkedNodes, DonorPoint_Coord, donor_iPoint, donor_element); tmp_Area = 0; - for (ii = 1; ii < nNode_target-1; ii++) - for (jj = 1; jj < nNode_donor-1; jj++) - tmp_Area += Compute_Triangle_Intersection(target_element[0], target_element[ii], target_element[ii+1], - donor_element[0], donor_element[jj], donor_element[jj+1], Normal); + for (ii = 1; ii < nNode_target - 1; ii++) + for (jj = 1; jj < nNode_donor - 1; jj++) + tmp_Area += Compute_Triangle_Intersection(target_element[0], target_element[ii], + target_element[ii + 1], donor_element[0], + donor_element[jj], donor_element[jj + 1], Normal); - for (ii = 0; ii < 2*nEdges_donor + 2; ii++) - delete [] donor_element[ii]; - delete [] donor_element; + for (ii = 0; ii < 2 * nEdges_donor + 2; ii++) delete[] donor_element[ii]; + delete[] donor_element; - /*--- In case the element intersect the target cell update the auxiliary communication data structure ---*/ + /*--- In case the element intersect the target cell update the auxiliary communication data structure + * ---*/ - tmp_Coeff_Vect = new su2double[ nDonorPoints + 1 ]; - tmp_Donor_Vect = new unsigned long[ nDonorPoints + 1 ]; - tmp_storeProc = new unsigned long[ nDonorPoints + 1 ]; + tmp_Coeff_Vect = new su2double[nDonorPoints + 1]; + tmp_Donor_Vect = new unsigned long[nDonorPoints + 1]; + tmp_storeProc = new unsigned long[nDonorPoints + 1]; - for( iDonor = 0; iDonor < nDonorPoints; iDonor++){ + for (iDonor = 0; iDonor < nDonorPoints; iDonor++) { tmp_Donor_Vect[iDonor] = Donor_Vect[iDonor]; tmp_Coeff_Vect[iDonor] = Coeff_Vect[iDonor]; - tmp_storeProc[iDonor] = storeProc[iDonor]; + tmp_storeProc[iDonor] = storeProc[iDonor]; } - tmp_Coeff_Vect[ nDonorPoints ] = tmp_Area; - tmp_Donor_Vect[ nDonorPoints ] = donor_iPoint; - tmp_storeProc[ nDonorPoints ] = Donor_Proc[donor_iPoint]; + tmp_Coeff_Vect[nDonorPoints] = tmp_Area; + tmp_Donor_Vect[nDonorPoints] = donor_iPoint; + tmp_storeProc[nDonorPoints] = Donor_Proc[donor_iPoint]; - delete [] Donor_Vect; - delete [] Coeff_Vect; - delete [] storeProc; + delete[] Donor_Vect; + delete[] Coeff_Vect; + delete[] storeProc; Donor_Vect = tmp_Donor_Vect; Coeff_Vect = tmp_Coeff_Vect; - storeProc = tmp_storeProc; + storeProc = tmp_storeProc; tmp_Coeff_Vect = nullptr; tmp_Donor_Vect = nullptr; - tmp_storeProc = nullptr; + tmp_storeProc = nullptr; nDonorPoints++; @@ -666,78 +641,75 @@ void CSlidingMesh::SetTransferCoeff(const CConfig* const* config) { StartVisited = nAlreadyVisited; - tmpVect = new unsigned long[ nAlreadyVisited + nToVisit ]; - - for( jj = 0; jj < nAlreadyVisited; jj++ ) - tmpVect[jj] = alreadyVisitedDonor[jj]; + tmpVect = new unsigned long[nAlreadyVisited + nToVisit]; - for( jj = 0; jj < nToVisit; jj++ ) - tmpVect[ nAlreadyVisited + jj ] = ToVisit[jj]; + for (jj = 0; jj < nAlreadyVisited; jj++) tmpVect[jj] = alreadyVisitedDonor[jj]; + for (jj = 0; jj < nToVisit; jj++) tmpVect[nAlreadyVisited + jj] = ToVisit[jj]; - delete [] alreadyVisitedDonor; + delete[] alreadyVisitedDonor; alreadyVisitedDonor = tmpVect; nAlreadyVisited += nToVisit; - delete [] ToVisit; + delete[] ToVisit; } - delete [] alreadyVisitedDonor; + delete[] alreadyVisitedDonor; /*--- Set the communication data structure and copy data from the auxiliary vectors ---*/ targetVertices[markTarget][iVertex].resize(nDonorPoints); - for ( iDonor = 0; iDonor < nDonorPoints; iDonor++ ){ + for (iDonor = 0; iDonor < nDonorPoints; iDonor++) { targetVertices[markTarget][iVertex].coefficient[iDonor] = Coeff_Vect[iDonor] / Area; targetVertices[markTarget][iVertex].globalPoint[iDonor] = Donor_GlobalPoint[Donor_Vect[iDonor]]; targetVertices[markTarget][iVertex].processor[iDonor] = storeProc[iDonor]; } - for (ii = 0; ii < 2*nEdges_target + 2; ii++) - delete [] target_element[ii]; - delete [] target_element; + for (ii = 0; ii < 2 * nEdges_target + 2; ii++) delete[] target_element[ii]; + delete[] target_element; - delete [] Donor_Vect; Donor_Vect = nullptr; - delete [] Coeff_Vect; Coeff_Vect = nullptr; - delete [] storeProc; storeProc = nullptr; + delete[] Donor_Vect; + Donor_Vect = nullptr; + delete[] Coeff_Vect; + Coeff_Vect = nullptr; + delete[] storeProc; + storeProc = nullptr; } } - } - delete [] Normal; - delete [] Direction; + delete[] Normal; + delete[] Direction; - delete [] Donor_Vect; - delete [] Coeff_Vect; - delete [] storeProc; + delete[] Donor_Vect; + delete[] Coeff_Vect; + delete[] storeProc; } -int CSlidingMesh::Build_3D_surface_element(const su2vector& map, const su2vector& startIndex, +int CSlidingMesh::Build_3D_surface_element(const su2vector& map, + const su2vector& startIndex, const su2vector& nNeighbor, su2activematrix const& coord, unsigned long centralNode, su2double** element) { - /*--- Given a node "centralNode", this routines reconstruct the vertex centered * surface element around the node and store it into "element" ---*/ constexpr unsigned short nDim = 3; - const unsigned long *OuterNodes; + const unsigned long* OuterNodes; /* --- Store central node as element first point --- */ - for (unsigned short iDim = 0; iDim < nDim; iDim++) - element[0][iDim] = coord(centralNode,iDim); + for (unsigned short iDim = 0; iDim < nDim; iDim++) element[0][iDim] = coord(centralNode, iDim); unsigned long nOuterNodes = nNeighbor[centralNode]; - OuterNodes = &map[ startIndex[centralNode] ]; + OuterNodes = &map[startIndex[centralNode]]; // For each neighbor n of centralNode, store <=2 neighbors of centralNode that are neighbors of n. - su2matrix OuterNodesNeighbour(nOuterNodes,2); + su2matrix OuterNodesNeighbour(nOuterNodes, 2); OuterNodesNeighbour = -1; // Typically there are exactly 2 such neighbors, and all the neighbors of centralNode can be // arranged into a closed chain. However at 1D boundaries of 2D markers, the neighbors might @@ -745,75 +717,73 @@ int CSlidingMesh::Build_3D_surface_element(const su2vector& map, // StartNode is a node where we can start to iterate through the chain. I.e. it's any node in // case of a closed chain, or one of the two ends in case of an open chain. int StartNode = 0; - for( unsigned long iNode = 0; iNode < nOuterNodes; iNode++ ){ - - int count = 0; // number of neighboring outer nodes already found - const unsigned long iPoint = OuterNodes[ iNode ]; - const unsigned long *ptr = &map[ startIndex[iPoint] ]; + for (unsigned long iNode = 0; iNode < nOuterNodes; iNode++) { + int count = 0; // number of neighboring outer nodes already found + const unsigned long iPoint = OuterNodes[iNode]; + const unsigned long* ptr = &map[startIndex[iPoint]]; - for ( unsigned long jNode = 0; jNode < nNeighbor[iPoint]; jNode++ ){ + for (unsigned long jNode = 0; jNode < nNeighbor[iPoint]; jNode++) { const unsigned long jPoint = ptr[jNode]; - for( unsigned long kNode = 0; kNode < nOuterNodes; kNode++ ){ - if ( jPoint == OuterNodes[ kNode ] && jPoint != centralNode){ - OuterNodesNeighbour(iNode,count) = static_cast(kNode); + for (unsigned long kNode = 0; kNode < nOuterNodes; kNode++) { + if (jPoint == OuterNodes[kNode] && jPoint != centralNode) { + OuterNodesNeighbour(iNode, count) = static_cast(kNode); count++; break; } } } - if( count == 1 ) - StartNode = static_cast(iNode); + if (count == 1) StartNode = static_cast(iNode); } - /* --- Build element, starts from one outer node and loops along the external edges until the element is reconstructed --- */ + /* --- Build element, starts from one outer node and loops along the external edges until the element is reconstructed + * --- */ int CurrentNode = StartNode; - int NextNode = OuterNodesNeighbour(CurrentNode,0); + int NextNode = OuterNodesNeighbour(CurrentNode, 0); unsigned long iElementNode = 1; - while( NextNode != -1 ){ // We finished iterating through the chain if it is an open chain and we reached the other end. + while (NextNode != + -1) { // We finished iterating through the chain if it is an open chain and we reached the other end. for (unsigned short iDim = 0; iDim < nDim; iDim++) - element[ iElementNode ][iDim] = ( element[0][iDim] + coord(OuterNodes[ CurrentNode ], iDim) )/2.; + element[iElementNode][iDim] = (element[0][iDim] + coord(OuterNodes[CurrentNode], iDim)) / 2.; iElementNode++; for (unsigned short iDim = 0; iDim < nDim; iDim++) - element[ iElementNode ][iDim] = ( element[0][iDim] + coord[ OuterNodes[ CurrentNode ] ][ iDim] + - coord(OuterNodes[ NextNode ], iDim) )/3.; + element[iElementNode][iDim] = + (element[0][iDim] + coord[OuterNodes[CurrentNode]][iDim] + coord(OuterNodes[NextNode], iDim)) / 3.; iElementNode++; // "Place the next domino piece in the correct orientation." - if( OuterNodesNeighbour(NextNode, 0) == CurrentNode){ + if (OuterNodesNeighbour(NextNode, 0) == CurrentNode) { CurrentNode = NextNode; NextNode = OuterNodesNeighbour(NextNode, 1); - } else{ + } else { CurrentNode = NextNode; NextNode = OuterNodesNeighbour(NextNode, 0); } // We finished iterating through the chain if it is closed and we reached the beginning again. - if (CurrentNode == StartNode) - break; + if (CurrentNode == StartNode) break; } - if( CurrentNode == StartNode ){ // This is a closed element, so add again element 1 to the end of the structure, useful later - for (unsigned short iDim = 0; iDim < nDim; iDim++) - element[ iElementNode ][iDim] = element[1][iDim]; + if (CurrentNode == + StartNode) { // This is a closed element, so add again element 1 to the end of the structure, useful later + for (unsigned short iDim = 0; iDim < nDim; iDim++) element[iElementNode][iDim] = element[1][iDim]; iElementNode++; - } else{ + } else { for (unsigned short iDim = 0; iDim < nDim; iDim++) - element[ iElementNode ][iDim] = ( element[0][iDim] + coord(OuterNodes[ CurrentNode ], iDim) )/2.; + element[iElementNode][iDim] = (element[0][iDim] + coord(OuterNodes[CurrentNode], iDim)) / 2.; iElementNode++; } return static_cast(iElementNode); - } su2double CSlidingMesh::ComputeLineIntersectionLength(unsigned short nDim, const su2double* A1, const su2double* A2, - const su2double* B1, const su2double* B2, const su2double* Direction) { - + const su2double* B1, const su2double* B2, + const su2double* Direction) { /*--- Given 2 segments, each defined by 2 points, it projects them along a given direction * and it computes the length of the segment resulting from their intersection ---*/ /*--- The algorithm works for both 2D and 3D problems ---*/ @@ -823,46 +793,39 @@ su2double CSlidingMesh::ComputeLineIntersectionLength(unsigned short nDim, const su2double dotA2, dotB1, dotB2; dotA2 = 0; - for(iDim = 0; iDim < nDim; iDim++) - dotA2 += ( A2[iDim] - A1[iDim] ) * Direction[iDim]; + for (iDim = 0; iDim < nDim; iDim++) dotA2 += (A2[iDim] - A1[iDim]) * Direction[iDim]; - if( dotA2 >= 0 ){ + if (dotA2 >= 0) { dotB1 = 0; dotB2 = 0; - for(iDim = 0; iDim < nDim; iDim++){ - dotB1 += ( B1[iDim] - A1[iDim] ) * Direction[iDim]; - dotB2 += ( B2[iDim] - A1[iDim] ) * Direction[iDim]; + for (iDim = 0; iDim < nDim; iDim++) { + dotB1 += (B1[iDim] - A1[iDim]) * Direction[iDim]; + dotB2 += (B2[iDim] - A1[iDim]) * Direction[iDim]; } - } - else{ + } else { dotA2 *= -1; dotB1 = 0; dotB2 = 0; - for(iDim = 0; iDim < nDim; iDim++){ - dotB1 -= ( B1[iDim] - A1[iDim] ) * Direction[iDim]; - dotB2 -= ( B2[iDim] - A1[iDim] ) * Direction[iDim]; + for (iDim = 0; iDim < nDim; iDim++) { + dotB1 -= (B1[iDim] - A1[iDim]) * Direction[iDim]; + dotB2 -= (B2[iDim] - A1[iDim]) * Direction[iDim]; } } - if( dotB1 >= 0 && dotB1 <= dotA2 ){ - if ( dotB2 < 0 ) - return fabs( dotB1 ); - if ( dotB2 > dotA2 ) - return fabs( dotA2 - dotB1 ); + if (dotB1 >= 0 && dotB1 <= dotA2) { + if (dotB2 < 0) return fabs(dotB1); + if (dotB2 > dotA2) return fabs(dotA2 - dotB1); - return fabs( dotB1 - dotB2 ); + return fabs(dotB1 - dotB2); } - if( dotB2 >= 0 && dotB2 <= dotA2 ){ - if ( dotB1 < 0 ) - return fabs(dotB2); - if ( dotB1 > dotA2 ) - return fabs( dotA2 - dotB2 ); + if (dotB2 >= 0 && dotB2 <= dotA2) { + if (dotB1 < 0) return fabs(dotB2); + if (dotB1 > dotA2) return fabs(dotA2 - dotB2); } - if( ( dotB1 <= 0 && dotA2 <= dotB2 ) || ( dotB2 <= 0 && dotA2 <= dotB1 ) ) - return fabs( dotA2 ); + if ((dotB1 <= 0 && dotA2 <= dotB2) || (dotB2 <= 0 && dotA2 <= dotB1)) return fabs(dotA2); return 0.0; } @@ -870,9 +833,9 @@ su2double CSlidingMesh::ComputeLineIntersectionLength(unsigned short nDim, const su2double CSlidingMesh::Compute_Triangle_Intersection(const su2double* A1, const su2double* A2, const su2double* A3, const su2double* B1, const su2double* B2, const su2double* B3, const su2double* Direction) { - /* --- This routine is ONLY for 3D grids --- */ - /* --- Projects triangle points onto a plane, specified by its normal "Direction", and calls the ComputeIntersectionArea routine --- */ + /* --- Projects triangle points onto a plane, specified by its normal "Direction", and calls the + * ComputeIntersectionArea routine --- */ unsigned short iDim; constexpr unsigned short nDim = 3; @@ -884,7 +847,7 @@ su2double CSlidingMesh::Compute_Triangle_Intersection(const su2double* A1, const /* --- Reference frame is determined by: x = A1A2 y = x ^ ( -Direction ) --- */ - for(iDim = 0; iDim < 3; iDim++){ + for (iDim = 0; iDim < 3; iDim++) { a1[iDim] = 0; a2[iDim] = 0; a3[iDim] = 0; @@ -895,36 +858,34 @@ su2double CSlidingMesh::Compute_Triangle_Intersection(const su2double* A1, const } m1 = 0; - for(iDim = 0; iDim < nDim; iDim++){ + for (iDim = 0; iDim < nDim; iDim++) { K[iDim] = Direction[iDim]; m1 += K[iDim] * K[iDim]; } - for(iDim = 0; iDim < nDim; iDim++) - K[iDim] /= sqrt(m1); + for (iDim = 0; iDim < nDim; iDim++) K[iDim] /= sqrt(m1); m2 = 0; - for(iDim = 0; iDim < nDim; iDim++) - m2 += (A2[iDim] - A1[iDim]) * K[iDim]; + for (iDim = 0; iDim < nDim; iDim++) m2 += (A2[iDim] - A1[iDim]) * K[iDim]; m1 = 0; - for(iDim = 0; iDim < nDim; iDim++){ + for (iDim = 0; iDim < nDim; iDim++) { I[iDim] = (A2[iDim] - A1[iDim]) - m2 * K[iDim]; m1 += I[iDim] * I[iDim]; } - for(iDim = 0; iDim < nDim; iDim++) - I[iDim] /= sqrt(m1); + for (iDim = 0; iDim < nDim; iDim++) I[iDim] /= sqrt(m1); // Cross product to find Y - J[0] = K[1]*I[2] - K[2]*I[1]; - J[1] = -(K[0]*I[2] - K[2]*I[0]); - J[2] = K[0]*I[1] - K[1]*I[0]; + J[0] = K[1] * I[2] - K[2] * I[1]; + J[1] = -(K[0] * I[2] - K[2] * I[0]); + J[2] = K[0] * I[1] - K[1] * I[0]; - /* --- Project all points on the plane specified by Direction and change their reference frame taking A1 as origin --- */ + /* --- Project all points on the plane specified by Direction and change their reference frame taking A1 as origin --- + */ - for(iDim = 0; iDim < nDim; iDim++){ + for (iDim = 0; iDim < nDim; iDim++) { a2[0] += (A2[iDim] - A1[iDim]) * I[iDim]; a2[1] += (A2[iDim] - A1[iDim]) * J[iDim]; a2[2] += (A2[iDim] - A1[iDim]) * K[iDim]; @@ -948,13 +909,13 @@ su2double CSlidingMesh::Compute_Triangle_Intersection(const su2double* A1, const /*--- Compute intersection area ---*/ - return ComputeIntersectionArea( a1, a2, a3, b1, b2, b3 ); + return ComputeIntersectionArea(a1, a2, a3, b1, b2, b3); } su2double CSlidingMesh::ComputeIntersectionArea(const su2double* P1, const su2double* P2, const su2double* P3, const su2double* Q1, const su2double* Q2, const su2double* Q3) { - - /* --- This routines computes the area of the polygonal element generated by the superimposition of 2 planar triangle --- */ + /* --- This routines computes the area of the polygonal element generated by the superimposition of 2 planar triangle + * --- */ /* --- The 2 triangle must lie on the same plane --- */ unsigned short iDim, nPoints = 0, i, j, k; @@ -966,7 +927,7 @@ su2double CSlidingMesh::ComputeIntersectionArea(const su2double* P1, const su2do constexpr unsigned short nDim = 2; - for(iDim = 0; iDim < nDim; iDim++){ + for (iDim = 0; iDim < nDim; iDim++) { TriangleP[0][iDim] = 0; TriangleP[1][iDim] = P2[iDim] - P1[iDim]; TriangleP[2][iDim] = P3[iDim] - P1[iDim]; @@ -978,69 +939,61 @@ su2double CSlidingMesh::ComputeIntersectionArea(const su2double* P1, const su2do TriangleQ[3][iDim] = Q1[iDim] - P1[iDim]; } - - for( j = 0; j < 3; j++){ - if( CheckPointInsideTriangle(TriangleP[j], TriangleQ[0], TriangleQ[1], TriangleQ[2]) ){ - + for (j = 0; j < 3; j++) { + if (CheckPointInsideTriangle(TriangleP[j], TriangleQ[0], TriangleQ[1], TriangleQ[2])) { // Then P1 is also inside triangle Q, so store it - for(iDim = 0; iDim < nDim; iDim++) - points[nPoints][iDim] = TriangleP[j][iDim]; + for (iDim = 0; iDim < nDim; iDim++) points[nPoints][iDim] = TriangleP[j][iDim]; nPoints++; } } - for( j = 0; j < 3; j++){ - if( CheckPointInsideTriangle(TriangleQ[j], TriangleP[0], TriangleP[1], TriangleP[2]) ){ - + for (j = 0; j < 3; j++) { + if (CheckPointInsideTriangle(TriangleQ[j], TriangleP[0], TriangleP[1], TriangleP[2])) { // Then Q1 is also inside triangle P, so store it - for(iDim = 0; iDim < nDim; iDim++) - points[nPoints][iDim] = TriangleQ[j][iDim]; + for (iDim = 0; iDim < nDim; iDim++) points[nPoints][iDim] = TriangleQ[j][iDim]; nPoints++; } } - // Compute all edge intersections - for( j = 0; j < 3; j++){ - for( i = 0; i < 3; i++){ + for (j = 0; j < 3; j++) { + for (i = 0; i < 3; i++) { + det = (TriangleP[j][0] - TriangleP[j + 1][0]) * (TriangleQ[i][1] - TriangleQ[i + 1][1]) - + (TriangleP[j][1] - TriangleP[j + 1][1]) * (TriangleQ[i][0] - TriangleQ[i + 1][0]); - det = (TriangleP[j][0] - TriangleP[j+1][0]) * (TriangleQ[i][1] - TriangleQ[i+1][1]) - - (TriangleP[j][1] - TriangleP[j+1][1]) * (TriangleQ[i][0] - TriangleQ[i+1][0]); - - if ( det != 0.0 ){ - ComputeLineIntersectionPoint( TriangleP[j], TriangleP[j+1], TriangleQ[i], TriangleQ[i+1], IntersectionPoint ); + if (det != 0.0) { + ComputeLineIntersectionPoint(TriangleP[j], TriangleP[j + 1], TriangleQ[i], TriangleQ[i + 1], IntersectionPoint); dot1 = 0; dot2 = 0; - for(iDim = 0; iDim < nDim; iDim++){ - dot1 += ( TriangleP[j][iDim] - IntersectionPoint[iDim] ) * ( TriangleP[j+1][iDim] - IntersectionPoint[iDim] ); - dot2 += ( TriangleQ[i][iDim] - IntersectionPoint[iDim] ) * ( TriangleQ[i+1][iDim] - IntersectionPoint[iDim] ); + for (iDim = 0; iDim < nDim; iDim++) { + dot1 += (TriangleP[j][iDim] - IntersectionPoint[iDim]) * (TriangleP[j + 1][iDim] - IntersectionPoint[iDim]); + dot2 += (TriangleQ[i][iDim] - IntersectionPoint[iDim]) * (TriangleQ[i + 1][iDim] - IntersectionPoint[iDim]); } - if( dot1 <= 0 && dot2 <= 0 ){ // It found one intersection + if (dot1 <= 0 && dot2 <= 0) { // It found one intersection - // Store temporarily the intersection point + // Store temporarily the intersection point - for(iDim = 0; iDim < nDim; iDim++) - points[nPoints][iDim] = IntersectionPoint[iDim]; + for (iDim = 0; iDim < nDim; iDim++) points[nPoints][iDim] = IntersectionPoint[iDim]; - nPoints++; - } - } - } - } + nPoints++; + } + } + } + } // Remove double points, if any - for( i = 0; i < nPoints; i++){ - for( j = i+1; j < nPoints; j++){ - if(points[j][0] == points[i][0] && points[j][1] == points[i][1]){ - for( k = j; k < nPoints-1; k++){ - points[k][0] = points[k+1][0]; - points[k][1] = points[k+1][1]; + for (i = 0; i < nPoints; i++) { + for (j = i + 1; j < nPoints; j++) { + if (points[j][0] == points[i][0] && points[j][1] == points[i][1]) { + for (k = j; k < nPoints - 1; k++) { + points[k][0] = points[k + 1][0]; + points[k][1] = points[k + 1][1]; } nPoints--; j--; @@ -1050,31 +1003,27 @@ su2double CSlidingMesh::ComputeIntersectionArea(const su2double* P1, const su2do // Re-order nodes - for( i = 1; i < nPoints; i++){ // Change again reference frame - for(iDim = 0; iDim < nDim; iDim++) - points[i][iDim] -= points[0][iDim]; + for (i = 1; i < nPoints; i++) { // Change again reference frame + for (iDim = 0; iDim < nDim; iDim++) points[i][iDim] -= points[0][iDim]; // Compute polar azimuth for each node but the first theta[i] = atan2(points[i][1], points[i][0]); } - for(iDim = 0; iDim < nDim; iDim++) - points[0][iDim] = 0; - - for( i = 1; i < nPoints; i++){ + for (iDim = 0; iDim < nDim; iDim++) points[0][iDim] = 0; + for (i = 1; i < nPoints; i++) { min_theta = theta[i]; min_theta_index = 0; - for( j = i + 1; j < nPoints; j++){ - - if( theta[j] < min_theta ){ + for (j = i + 1; j < nPoints; j++) { + if (theta[j] < min_theta) { min_theta = theta[j]; min_theta_index = j; } } - if( min_theta_index != 0 ){ + if (min_theta_index != 0) { dtmp = theta[i]; theta[i] = theta[min_theta_index]; theta[min_theta_index] = dtmp; @@ -1094,39 +1043,39 @@ su2double CSlidingMesh::ComputeIntersectionArea(const su2double* P1, const su2do Area = 0; - if (nPoints > 2){ - for( i = 1; i < nPoints-1; i++ ){ - + if (nPoints > 2) { + for (i = 1; i < nPoints - 1; i++) { // Ax*By - Area += ( points[i][0] - points[0][0] ) * ( points[i+1][1] - points[0][1] ); + Area += (points[i][0] - points[0][0]) * (points[i + 1][1] - points[0][1]); // Ay*Bx - Area -= ( points[i][1] - points[0][1] ) * ( points[i+1][0] - points[0][0] ); + Area -= (points[i][1] - points[0][1]) * (points[i + 1][0] - points[0][0]); } } - return fabs(Area)/2; + return fabs(Area) / 2; } void CSlidingMesh::ComputeLineIntersectionPoint(const su2double* A1, const su2double* A2, const su2double* B1, - const su2double* B2, su2double* IntersectionPoint ){ - + const su2double* B2, su2double* IntersectionPoint) { /* --- Uses determinant rule to compute the intersection point between 2 straight segments --- */ - /* This works only for lines on a 2D plane, A1, A2 and B1, B2 are respectively the head and the tail points of each segment, - * since they're on a 2D plane they are defined by a 2-elements array containing their coordinates */ + /* This works only for lines on a 2D plane, A1, A2 and B1, B2 are respectively the head and the tail points of each + * segment, since they're on a 2D plane they are defined by a 2-elements array containing their coordinates */ su2double det; det = (A1[0] - A2[0]) * (B1[1] - B2[1]) - (A1[1] - A2[1]) * (B1[0] - B2[0]); - if ( det != 0.0 ){ // else there is no intersection point - IntersectionPoint[0] = ( ( A1[0]*A2[1] - A1[1]*A2[0] ) * ( B1[0] - B2[0] ) - ( B1[0]*B2[1] - B1[1]*B2[0] ) * ( A1[0] - A2[0] ) ) / det; - IntersectionPoint[1] = ( ( A1[0]*A2[1] - A1[1]*A2[0] ) * ( B1[1] - B2[1] ) - ( B1[0]*B2[1] - B1[1]*B2[0] ) * ( A1[1] - A2[1] ) ) / det; + if (det != 0.0) { // else there is no intersection point + IntersectionPoint[0] = + ((A1[0] * A2[1] - A1[1] * A2[0]) * (B1[0] - B2[0]) - (B1[0] * B2[1] - B1[1] * B2[0]) * (A1[0] - A2[0])) / det; + IntersectionPoint[1] = + ((A1[0] * A2[1] - A1[1] * A2[0]) * (B1[1] - B2[1]) - (B1[0] * B2[1] - B1[1] * B2[0]) * (A1[1] - A2[1])) / det; } } -bool CSlidingMesh::CheckPointInsideTriangle(const su2double* Point, const su2double* T1, const su2double* T2, const su2double* T3) { - +bool CSlidingMesh::CheckPointInsideTriangle(const su2double* Point, const su2double* T1, const su2double* T2, + const su2double* T3) { /* --- Check whether a point "Point" lies inside or outside a triangle defined by 3 points "T1", "T2", "T3" --- */ /* For each edge it checks on which side the point lies: * - Computes the unit vector pointing at the internal side of the edge @@ -1140,14 +1089,14 @@ bool CSlidingMesh::CheckPointInsideTriangle(const su2double* Point, const su2dou su2double vect1[2], vect2[2], r[2]; su2double dot; - constexpr unsigned short nDim = 2; + constexpr unsigned short nDim = 2; /* --- Check first edge --- */ dot = 0; - for(iDim = 0; iDim < nDim; iDim++){ - vect1[iDim] = T3[iDim] - T1[iDim]; // vec 1 is aligned to the edge - vect2[iDim] = T2[iDim] - T1[iDim]; // vect 2 is the vector connecting one edge point to the third triangle vertex + for (iDim = 0; iDim < nDim; iDim++) { + vect1[iDim] = T3[iDim] - T1[iDim]; // vec 1 is aligned to the edge + vect2[iDim] = T2[iDim] - T1[iDim]; // vect 2 is the vector connecting one edge point to the third triangle vertex r[iDim] = Point[iDim] - T1[iDim]; // Connects point to vertex T1 @@ -1155,27 +1104,24 @@ bool CSlidingMesh::CheckPointInsideTriangle(const su2double* Point, const su2dou } dot = sqrt(dot); - for(iDim = 0; iDim < nDim; iDim++) - vect2[iDim] /= dot; + for (iDim = 0; iDim < nDim; iDim++) vect2[iDim] /= dot; dot = 0; - for(iDim = 0; iDim < nDim; iDim++) - dot += vect1[iDim] * vect2[iDim]; + for (iDim = 0; iDim < nDim; iDim++) dot += vect1[iDim] * vect2[iDim]; - for(iDim = 0; iDim < nDim; iDim++) - vect1[iDim] = T3[iDim] - (T1[iDim] + dot * vect2[iDim]); // Computes the inward unit vector + for (iDim = 0; iDim < nDim; iDim++) + vect1[iDim] = T3[iDim] - (T1[iDim] + dot * vect2[iDim]); // Computes the inward unit vector dot = 0; - for(iDim = 0; iDim < nDim; iDim++) // Checs that the point lies on the internal plane + for (iDim = 0; iDim < nDim; iDim++) // Checs that the point lies on the internal plane dot += vect1[iDim] * r[iDim]; - if (dot >= 0) - check++; + if (dot >= 0) check++; /* --- Check second edge --- */ dot = 0; - for(iDim = 0; iDim < nDim; iDim++){ + for (iDim = 0; iDim < nDim; iDim++) { vect1[iDim] = T1[iDim] - T2[iDim]; vect2[iDim] = T3[iDim] - T2[iDim]; @@ -1185,27 +1131,22 @@ bool CSlidingMesh::CheckPointInsideTriangle(const su2double* Point, const su2dou } dot = sqrt(dot); - for(iDim = 0; iDim < nDim; iDim++) - vect2[iDim] /= dot; + for (iDim = 0; iDim < nDim; iDim++) vect2[iDim] /= dot; dot = 0; - for(iDim = 0; iDim < nDim; iDim++) - dot += vect1[iDim] * vect2[iDim]; + for (iDim = 0; iDim < nDim; iDim++) dot += vect1[iDim] * vect2[iDim]; - for(iDim = 0; iDim < nDim; iDim++) - vect1[iDim] = T1[iDim] - (T2[iDim] + dot * vect2[iDim]); + for (iDim = 0; iDim < nDim; iDim++) vect1[iDim] = T1[iDim] - (T2[iDim] + dot * vect2[iDim]); dot = 0; - for(iDim = 0; iDim < nDim; iDim++) - dot += vect1[iDim] * r[iDim]; + for (iDim = 0; iDim < nDim; iDim++) dot += vect1[iDim] * r[iDim]; - if (dot >= 0) - check++; + if (dot >= 0) check++; /* --- Check third edge --- */ dot = 0; - for(iDim = 0; iDim < nDim; iDim++){ + for (iDim = 0; iDim < nDim; iDim++) { vect1[iDim] = T2[iDim] - T3[iDim]; vect2[iDim] = T1[iDim] - T3[iDim]; @@ -1215,22 +1156,17 @@ bool CSlidingMesh::CheckPointInsideTriangle(const su2double* Point, const su2dou } dot = sqrt(dot); - for(iDim = 0; iDim < nDim; iDim++) - vect2[iDim] /= dot; + for (iDim = 0; iDim < nDim; iDim++) vect2[iDim] /= dot; dot = 0; - for(iDim = 0; iDim < nDim; iDim++) - dot += vect1[iDim] * vect2[iDim]; + for (iDim = 0; iDim < nDim; iDim++) dot += vect1[iDim] * vect2[iDim]; - for(iDim = 0; iDim < nDim; iDim++) - vect1[iDim] = T2[iDim] - (T3[iDim] + dot * vect2[iDim]); + for (iDim = 0; iDim < nDim; iDim++) vect1[iDim] = T2[iDim] - (T3[iDim] + dot * vect2[iDim]); dot = 0; - for(iDim = 0; iDim < nDim; iDim++) - dot += vect1[iDim] * r[iDim]; + for (iDim = 0; iDim < nDim; iDim++) dot += vect1[iDim] * r[iDim]; - if (dot >= 0) - check++; + if (dot >= 0) check++; return (check == 3); } diff --git a/Common/src/linear_algebra/CPastixWrapper.cpp b/Common/src/linear_algebra/CPastixWrapper.cpp index 9cf791cbdd9..8500c44445a 100644 --- a/Common/src/linear_algebra/CPastixWrapper.cpp +++ b/Common/src/linear_algebra/CPastixWrapper.cpp @@ -34,33 +34,29 @@ #include "../../include/geometry/CGeometry.hpp" #include "../../include/linear_algebra/CPastixWrapper.hpp" -#include - -template -void CPastixWrapper::Initialize(CGeometry *geometry, const CConfig *config) { +#include +template +void CPastixWrapper::Initialize(CGeometry* geometry, const CConfig* config) { using namespace PaStiX; - if (isinitialized) return; // only need to do this once + if (isinitialized) return; // only need to do this once - unsigned long nVar = matrix.nVar, - nPoint = matrix.nPoint, - nPointDomain = matrix.nPointDomain; - const unsigned long *row_ptr = matrix.rowptr, - *col_ind = matrix.colidx; + unsigned long nVar = matrix.nVar, nPoint = matrix.nPoint, nPointDomain = matrix.nPointDomain; + const unsigned long *row_ptr = matrix.rowptr, *col_ind = matrix.colidx; unsigned long iPoint, offset = 0, nNonZero = row_ptr[nPointDomain]; /*--- Allocate ---*/ nCols = pastix_int_t(nPointDomain); - colptr.resize(nPointDomain+1); + colptr.resize(nPointDomain + 1); rowidx.clear(); rowidx.reserve(nNonZero); - values.resize(nNonZero*nVar*nVar); + values.resize(nNonZero * nVar * nVar); loc2glb.resize(nPointDomain); perm.resize(nPointDomain); - workvec.resize(nPointDomain*nVar); + workvec.resize(nPointDomain * nVar); /*--- Set default parameter values ---*/ @@ -72,25 +68,25 @@ void CPastixWrapper::Initialize(CGeometry *geometry, const CConfig * /*--- Customize important parameters ---*/ switch (verb) { - case 1: - iparm[IPARM_VERBOSE] = API_VERBOSE_NO; - break; - case 2: - iparm[IPARM_VERBOSE] = API_VERBOSE_YES; - break; - default: - iparm[IPARM_VERBOSE] = API_VERBOSE_NOT; - break; + case 1: + iparm[IPARM_VERBOSE] = API_VERBOSE_NO; + break; + case 2: + iparm[IPARM_VERBOSE] = API_VERBOSE_YES; + break; + default: + iparm[IPARM_VERBOSE] = API_VERBOSE_NOT; + break; } - iparm[IPARM_DOF_NBR] = pastix_int_t(nVar); + iparm[IPARM_DOF_NBR] = pastix_int_t(nVar); iparm[IPARM_MATRIX_VERIFICATION] = API_NO; - iparm[IPARM_FREE_CSCPASTIX] = API_CSC_FREE; - iparm[IPARM_CSCD_CORRECT] = API_NO; - iparm[IPARM_RHSD_CHECK] = API_NO; - iparm[IPARM_ORDERING] = API_ORDER_PTSCOTCH; - iparm[IPARM_INCOMPLETE] = incomplete; - iparm[IPARM_LEVEL_OF_FILL] = pastix_int_t(config->GetPastixFillLvl()); - iparm[IPARM_THREAD_NBR] = omp_get_max_threads(); + iparm[IPARM_FREE_CSCPASTIX] = API_CSC_FREE; + iparm[IPARM_CSCD_CORRECT] = API_NO; + iparm[IPARM_RHSD_CHECK] = API_NO; + iparm[IPARM_ORDERING] = API_ORDER_PTSCOTCH; + iparm[IPARM_INCOMPLETE] = incomplete; + iparm[IPARM_LEVEL_OF_FILL] = pastix_int_t(config->GetPastixFillLvl()); + iparm[IPARM_THREAD_NBR] = omp_get_max_threads(); #if defined(HAVE_MPI) && defined(HAVE_OMP) int comm_mode = MPI_THREAD_SINGLE; MPI_Query_thread(&comm_mode); @@ -100,40 +96,37 @@ void CPastixWrapper::Initialize(CGeometry *geometry, const CConfig * iparm[IPARM_THREAD_COMM_MODE] = API_THREAD_FUNNELED; #endif - /*--- Prepare sparsity structure ---*/ + /*--- Prepare sparsity structure ---*/ - /*--- We need it in global coordinates, i.e. shifted according to the position - of the current rank in the linear partitioning space, and "unpacked" halo part. - The latter forces us to re-sort the column indices of rows with halo points, which - in turn requires blocks to be swapped accordingly. Moreover we need "pointer" and - indices in Fortran-style numbering (start at 1), effectively the matrix is copied. - Here we prepare the pointer and index part, and map the required swaps. ---*/ + /*--- We need it in global coordinates, i.e. shifted according to the position + of the current rank in the linear partitioning space, and "unpacked" halo part. + The latter forces us to re-sort the column indices of rows with halo points, which + in turn requires blocks to be swapped accordingly. Moreover we need "pointer" and + indices in Fortran-style numbering (start at 1), effectively the matrix is copied. + Here we prepare the pointer and index part, and map the required swaps. ---*/ - /*--- 1 - Determine position in the linear partitioning ---*/ + /*--- 1 - Determine position in the linear partitioning ---*/ #ifdef HAVE_MPI vector domain_sizes(mpi_size); MPI_Allgather(&nPointDomain, 1, MPI_UNSIGNED_LONG, domain_sizes.data(), 1, MPI_UNSIGNED_LONG, SU2_MPI::GetComm()); - for (int i=0; i map(nPoint-nPointDomain,0); + vector map(nPoint - nPointDomain, 0); #ifdef HAVE_MPI - for (unsigned short iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) - { - if ((config->GetMarker_All_KindBC(iMarker) == SEND_RECEIVE) && - (config->GetMarker_All_SendRecv(iMarker) > 0)) - { - unsigned short MarkerS = iMarker, MarkerR = iMarker+1; + for (unsigned short iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { + if ((config->GetMarker_All_KindBC(iMarker) == SEND_RECEIVE) && (config->GetMarker_All_SendRecv(iMarker) > 0)) { + unsigned short MarkerS = iMarker, MarkerR = iMarker + 1; - int sender = config->GetMarker_All_SendRecv(MarkerS)-1; - int recver = abs(config->GetMarker_All_SendRecv(MarkerR))-1; + int sender = config->GetMarker_All_SendRecv(MarkerS) - 1; + int recver = abs(config->GetMarker_All_SendRecv(MarkerR)) - 1; unsigned long nVertexS = geometry->nVertex[MarkerS]; unsigned long nVertexR = geometry->nVertex[MarkerR]; @@ -143,34 +136,31 @@ void CPastixWrapper::Initialize(CGeometry *geometry, const CConfig * /*--- Prepare data to send ---*/ for (unsigned long iVertex = 0; iVertex < nVertexS; iVertex++) - Buffer_Send[iVertex] = geometry->vertex[MarkerS][iVertex]->GetNode()+offset; + Buffer_Send[iVertex] = geometry->vertex[MarkerS][iVertex]->GetNode() + offset; /*--- Send and Receive data ---*/ - MPI_Sendrecv(Buffer_Send.data(), nVertexS, MPI_UNSIGNED_LONG, sender, 0, - Buffer_Recv.data(), nVertexR, MPI_UNSIGNED_LONG, recver, 0, - SU2_MPI::GetComm(), MPI_STATUS_IGNORE); + MPI_Sendrecv(Buffer_Send.data(), nVertexS, MPI_UNSIGNED_LONG, sender, 0, Buffer_Recv.data(), nVertexR, + MPI_UNSIGNED_LONG, recver, 0, SU2_MPI::GetComm(), MPI_STATUS_IGNORE); /*--- Store received data---*/ for (unsigned long iVertex = 0; iVertex < nVertexR; iVertex++) - map[ geometry->vertex[MarkerR][iVertex]->GetNode()-nPointDomain ] = Buffer_Recv[iVertex]; + map[geometry->vertex[MarkerR][iVertex]->GetNode() - nPointDomain] = Buffer_Recv[iVertex]; } } #endif /*--- 3 - Copy, map the sparsity, and put it in Fortran numbering ---*/ - for (iPoint = 0; iPoint < nPointDomain; ++iPoint) - { - colptr[iPoint] = pastix_int_t(row_ptr[iPoint]+1); + for (iPoint = 0; iPoint < nPointDomain; ++iPoint) { + colptr[iPoint] = pastix_int_t(row_ptr[iPoint] + 1); - unsigned long begin = row_ptr[iPoint], end = row_ptr[iPoint+1], j; + unsigned long begin = row_ptr[iPoint], end = row_ptr[iPoint + 1], j; /*--- If last point of row is halo ---*/ - bool sort_required = (col_ind[end-1] >= nPointDomain); + bool sort_required = (col_ind[end - 1] >= nPointDomain); - if (sort_required) - { - unsigned long nnz_row = end-begin; + if (sort_required) { + unsigned long nnz_row = end - begin; sort_rows.push_back(iPoint); sort_order.push_back(vector(nnz_row)); @@ -178,42 +168,36 @@ void CPastixWrapper::Initialize(CGeometry *geometry, const CConfig * /*--- Sort mapped indices ("first") and keep track of source ("second") for when we later need to swap blocks for these rows. ---*/ - vector > aux(nnz_row); + vector > aux(nnz_row); - for (j = begin; j < end; ++j) - { + for (j = begin; j < end; ++j) { if (col_ind[j] < nPointDomain) - aux[j-begin].first = pastix_int_t(offset+col_ind[j]+1); + aux[j - begin].first = pastix_int_t(offset + col_ind[j] + 1); else - aux[j-begin].first = pastix_int_t(map[col_ind[j]-nPointDomain]+1); - aux[j-begin].second = j; + aux[j - begin].first = pastix_int_t(map[col_ind[j] - nPointDomain] + 1); + aux[j - begin].second = j; } sort(aux.begin(), aux.end()); - for (j = 0; j < nnz_row; ++j) - { + for (j = 0; j < nnz_row; ++j) { rowidx.push_back(aux[j].first); sort_order.back()[j] = aux[j].second; } - } - else - { + } else { /*--- These are all internal, no need to go through map. ---*/ - for (j = begin; j < end; ++j) - rowidx.push_back(pastix_int_t(offset+col_ind[j]+1)); + for (j = begin; j < end; ++j) rowidx.push_back(pastix_int_t(offset + col_ind[j] + 1)); } } - colptr[nPointDomain] = pastix_int_t(nNonZero+1); + colptr[nPointDomain] = pastix_int_t(nNonZero + 1); - if (rowidx.size() != nNonZero) - SU2_MPI::Error("Error during preparation of PaStiX data", CURRENT_FUNCTION); + if (rowidx.size() != nNonZero) SU2_MPI::Error("Error during preparation of PaStiX data", CURRENT_FUNCTION); /*--- 4 - Perform ordering, symbolic factorization, and analysis steps ---*/ if (mpi_rank == MASTER_NODE && verb > 0) cout << endl; iparm[IPARM_START_TASK] = API_TASK_ORDERING; - iparm[IPARM_END_TASK] = API_TASK_ANALYSE; + iparm[IPARM_END_TASK] = API_TASK_ANALYSE; Run(); if (mpi_rank == MASTER_NODE && verb > 0) @@ -222,18 +206,17 @@ void CPastixWrapper::Initialize(CGeometry *geometry, const CConfig * isinitialized = true; } -template -void CPastixWrapper::Factorize(CGeometry *geometry, const CConfig *config, - unsigned short kind_fact) { +template +void CPastixWrapper::Factorize(CGeometry* geometry, const CConfig* config, unsigned short kind_fact) { using namespace PaStiX; /*--- Detect a possible change of settings between direct and adjoint that requires a reset ---*/ if (isinitialized) - if ((kind_fact == PASTIX_ILU) != (iparm[IPARM_INCOMPLETE] == API_YES)) { - Clean(); - isinitialized = false; - iter = 0; - } + if ((kind_fact == PASTIX_ILU) != (iparm[IPARM_INCOMPLETE] == API_YES)) { + Clean(); + isinitialized = false; + iter = 0; + } verb = config->GetPastixVerbLvl(); iparm[IPARM_INCOMPLETE] = (kind_fact == PASTIX_ILU); @@ -243,31 +226,30 @@ void CPastixWrapper::Factorize(CGeometry *geometry, const CConfig *c /*--- Set some options that affect "compute" and could (one day) change during run ---*/ switch (verb) { - case 1: - iparm[IPARM_VERBOSE] = API_VERBOSE_NO; - break; - case 2: - iparm[IPARM_VERBOSE] = API_VERBOSE_YES; - break; - default: - iparm[IPARM_VERBOSE] = API_VERBOSE_NOT; - break; + case 1: + iparm[IPARM_VERBOSE] = API_VERBOSE_NO; + break; + case 2: + iparm[IPARM_VERBOSE] = API_VERBOSE_YES; + break; + default: + iparm[IPARM_VERBOSE] = API_VERBOSE_NOT; + break; } if (kind_fact == PASTIX_LDLT || kind_fact == PASTIX_LDLT_P) - iparm[IPARM_TRANSPOSE_SOLVE] = API_NO; // symmetric so no need for slower transp. solve + iparm[IPARM_TRANSPOSE_SOLVE] = API_NO; // symmetric so no need for slower transp. solve else - iparm[IPARM_TRANSPOSE_SOLVE] = API_YES; // negated due to CSR to CSC copy + iparm[IPARM_TRANSPOSE_SOLVE] = API_YES; // negated due to CSR to CSC copy /*--- Is factorizing needed on this iteration? ---*/ bool factorize = false; - if (config->GetPastixFactFreq() != 0) - factorize = (iter % config->GetPastixFactFreq() == 0); + if (config->GetPastixFactFreq() != 0) factorize = (iter % config->GetPastixFactFreq() == 0); iter++; - if (isfactorized && !factorize) return; // No + if (isfactorized && !factorize) return; // No /*--- Yes ---*/ @@ -278,49 +260,47 @@ void CPastixWrapper::Factorize(CGeometry *geometry, const CConfig *c cout << " +--------------------------------------------------------------------+" << endl; } - unsigned long i, j, k, iRow, begin, target, source, - szBlk = matrix.nVar*matrix.nVar, nNonZero = values.size(); + unsigned long i, j, k, iRow, begin, target, source, szBlk = matrix.nVar * matrix.nVar, nNonZero = values.size(); /*--- Copy matrix values and swap blocks as required ---*/ - for (i = 0; i < nNonZero; ++i) - values[i] = SU2_TYPE::GetValue(matrix.values[i]); + for (i = 0; i < nNonZero; ++i) values[i] = SU2_TYPE::GetValue(matrix.values[i]); - for (i = 0; i < sort_rows.size(); ++i) - { + for (i = 0; i < sort_rows.size(); ++i) { iRow = sort_rows[i]; begin = matrix.rowptr[iRow]; - for (j = 0; j < sort_order[i].size(); ++j) - { - target = (begin+j)*szBlk; - source = sort_order[i][j]*szBlk; + for (j = 0; j < sort_order[i].size(); ++j) { + target = (begin + j) * szBlk; + source = sort_order[i][j] * szBlk; - for (k = 0; k < szBlk; ++k) - values[target+k] = SU2_TYPE::GetValue(matrix.values[source+k]); + for (k = 0; k < szBlk; ++k) values[target + k] = SU2_TYPE::GetValue(matrix.values[source + k]); } } /*--- Set factorization options ---*/ switch (kind_fact) { - case PASTIX_LDLT: case PASTIX_LDLT_P: - iparm[IPARM_SYM] = API_SYM_YES; - iparm[IPARM_FACTORIZATION] = API_FACT_LDLT; - break; - case PASTIX_LU: case PASTIX_LU_P: case PASTIX_ILU: - iparm[IPARM_SYM] = API_SYM_NO; - iparm[IPARM_FACTORIZATION] = API_FACT_LU; - break; - default: - SU2_MPI::Error("Unknown type of PaStiX factorization.", CURRENT_FUNCTION); - break; + case PASTIX_LDLT: + case PASTIX_LDLT_P: + iparm[IPARM_SYM] = API_SYM_YES; + iparm[IPARM_FACTORIZATION] = API_FACT_LDLT; + break; + case PASTIX_LU: + case PASTIX_LU_P: + case PASTIX_ILU: + iparm[IPARM_SYM] = API_SYM_NO; + iparm[IPARM_FACTORIZATION] = API_FACT_LU; + break; + default: + SU2_MPI::Error("Unknown type of PaStiX factorization.", CURRENT_FUNCTION); + break; } /*--- Compute factorization ---*/ iparm[IPARM_START_TASK] = API_TASK_NUMFACT; - iparm[IPARM_END_TASK] = API_TASK_NUMFACT; + iparm[IPARM_END_TASK] = API_TASK_NUMFACT; Run(); if (mpi_rank == MASTER_NODE && verb > 0) diff --git a/Common/src/linear_algebra/CSysMatrix.cpp b/Common/src/linear_algebra/CSysMatrix.cpp index a03797b64c7..fa84ecfa131 100644 --- a/Common/src/linear_algebra/CSysMatrix.cpp +++ b/Common/src/linear_algebra/CSysMatrix.cpp @@ -32,86 +32,77 @@ #include -template -CSysMatrix::CSysMatrix() : - rank(SU2_MPI::GetRank()), - size(SU2_MPI::GetSize()) { - +template +CSysMatrix::CSysMatrix() : rank(SU2_MPI::GetRank()), size(SU2_MPI::GetSize()) { nPoint = nPointDomain = nVar = nEqn = 0; nnz = nnz_ilu = 0; ilu_fill_in = 0; - omp_partitions = nullptr; + omp_partitions = nullptr; - matrix = nullptr; - row_ptr = nullptr; - dia_ptr = nullptr; - col_ind = nullptr; - col_ptr = nullptr; + matrix = nullptr; + row_ptr = nullptr; + dia_ptr = nullptr; + col_ind = nullptr; + col_ptr = nullptr; - ILU_matrix = nullptr; - row_ptr_ilu = nullptr; - dia_ptr_ilu = nullptr; - col_ind_ilu = nullptr; + ILU_matrix = nullptr; + row_ptr_ilu = nullptr; + dia_ptr_ilu = nullptr; + col_ind_ilu = nullptr; - invM = nullptr; + invM = nullptr; #ifdef USE_MKL - MatrixMatrixProductJitter = nullptr; - MatrixVectorProductJitterBetaOne = nullptr; - MatrixVectorProductJitterBetaZero = nullptr; + MatrixMatrixProductJitter = nullptr; + MatrixVectorProductJitterBetaOne = nullptr; + MatrixVectorProductJitterBetaZero = nullptr; MatrixVectorProductJitterAlphaMinusOne = nullptr; #endif - } -template +template CSysMatrix::~CSysMatrix(void) { - - delete [] omp_partitions; + delete[] omp_partitions; MemoryAllocation::aligned_free(ILU_matrix); MemoryAllocation::aligned_free(matrix); MemoryAllocation::aligned_free(invM); #ifdef USE_MKL - mkl_jit_destroy( MatrixMatrixProductJitter ); - mkl_jit_destroy( MatrixVectorProductJitterBetaZero ); - mkl_jit_destroy( MatrixVectorProductJitterBetaOne ); - mkl_jit_destroy( MatrixVectorProductJitterAlphaMinusOne ); + mkl_jit_destroy(MatrixMatrixProductJitter); + mkl_jit_destroy(MatrixVectorProductJitterBetaZero); + mkl_jit_destroy(MatrixVectorProductJitterBetaOne); + mkl_jit_destroy(MatrixVectorProductJitterAlphaMinusOne); #endif - } -template -void CSysMatrix::Initialize(unsigned long npoint, unsigned long npointdomain, - unsigned short nvar, unsigned short neqn, - bool EdgeConnect, CGeometry *geometry, - const CConfig *config, bool needTranspPtr, bool grad_mode) { - - assert(omp_get_thread_num()==0 && "Only the master thread is allowed to initialize the matrix."); +template +void CSysMatrix::Initialize(unsigned long npoint, unsigned long npointdomain, unsigned short nvar, + unsigned short neqn, bool EdgeConnect, CGeometry* geometry, + const CConfig* config, bool needTranspPtr, bool grad_mode) { + assert(omp_get_thread_num() == 0 && "Only the master thread is allowed to initialize the matrix."); - if(npoint == 0) return; + if (npoint == 0) return; - if(matrix != nullptr) { + if (matrix != nullptr) { SU2_MPI::Error("CSysMatrix can only be initialized once.", CURRENT_FUNCTION); } - if(nvar > MAXNVAR) { + if (nvar > MAXNVAR) { SU2_MPI::Error("nVar larger than expected, increase MAXNVAR.", CURRENT_FUNCTION); } /*--- Application of this matrix, FVM or FEM. ---*/ - const auto type = EdgeConnect? ConnectivityType::FiniteVolume : ConnectivityType::FiniteElement; + const auto type = EdgeConnect ? ConnectivityType::FiniteVolume : ConnectivityType::FiniteElement; /*--- Type of preconditioner the matrix will be asked to build. ---*/ auto prec = config->GetKind_Linear_Solver_Prec(); - if ((!EdgeConnect && !config->GetStructuralProblem()) || - (config->GetKind_SU2() == SU2_COMPONENT::SU2_DEF) || (config->GetKind_SU2() == SU2_COMPONENT::SU2_DOT)) { + if ((!EdgeConnect && !config->GetStructuralProblem()) || (config->GetKind_SU2() == SU2_COMPONENT::SU2_DEF) || + (config->GetKind_SU2() == SU2_COMPONENT::SU2_DOT)) { /*--- FEM-type connectivity in non-structural context implies mesh deformation. ---*/ prec = config->GetKind_Deform_Linear_Solver_Prec(); - } - else if (config->GetDiscrete_Adjoint() && (prec!=ILU)) { + } else if (config->GetDiscrete_Adjoint() && (prec != ILU)) { /*--- Else "upgrade" primal solver settings. ---*/ prec = config->GetKind_DiscAdj_Linear_Prec(); } @@ -121,8 +112,8 @@ void CSysMatrix::Initialize(unsigned long npoint, unsigned long npoi prec = config->GetKind_Grad_Linear_Solver_Prec(); } - const bool ilu_needed = (prec==ILU); - const bool diag_needed = ilu_needed || (prec==JACOBI) || (prec==LINELET); + const bool ilu_needed = (prec == ILU); + const bool diag_needed = ilu_needed || (prec == JACOBI) || (prec == LINELET); /*--- Basic dimensions. ---*/ nVar = nvar; @@ -133,15 +124,14 @@ void CSysMatrix::Initialize(unsigned long npoint, unsigned long npoi /*--- Get sparse structure pointers from geometry, * the data is managed by CGeometry to allow re-use. ---*/ - const auto& csr = geometry->GetSparsePattern(type,0); + const auto& csr = geometry->GetSparsePattern(type, 0); nnz = csr.getNumNonZeros(); row_ptr = csr.outerPtr(); col_ind = csr.innerIdx(); dia_ptr = csr.diagPtr(); - if (needTranspPtr) - col_ptr = geometry->GetTransposeSparsePatternMap(type).data(); + if (needTranspPtr) col_ptr = geometry->GetTransposeSparsePatternMap(type).data(); if (type == ConnectivityType::FiniteVolume) { edge_ptr.ptr = geometry->GetEdgeToSparsePatternMap().data(); @@ -150,8 +140,7 @@ void CSysMatrix::Initialize(unsigned long npoint, unsigned long npoi /*--- Get ILU sparse pattern, if fill is 0 no new data is allocated. --*/ - if(ilu_needed) - { + if (ilu_needed) { ilu_fill_in = config->GetLinear_Solver_ILU_n(); const auto& csr_ilu = geometry->GetSparsePattern(type, ilu_fill_in); @@ -164,16 +153,16 @@ void CSysMatrix::Initialize(unsigned long npoint, unsigned long npoi /*--- Allocate data. ---*/ auto allocAndInit = [](ScalarType*& ptr, unsigned long num) { - ptr = MemoryAllocation::aligned_alloc(64, num*sizeof(ScalarType)); + ptr = MemoryAllocation::aligned_alloc(64, num * sizeof(ScalarType)); }; - allocAndInit(matrix, nnz*nVar*nEqn); + allocAndInit(matrix, nnz * nVar * nEqn); /*--- Preconditioners. ---*/ - if (ilu_needed) allocAndInit(ILU_matrix, nnz_ilu*nVar*nEqn); + if (ilu_needed) allocAndInit(ILU_matrix, nnz_ilu * nVar * nEqn); - if (diag_needed) allocAndInit(invM, nPointDomain*nVar*nEqn); + if (diag_needed) allocAndInit(invM, nPointDomain * nVar * nEqn); /*--- Thread parallel initialization. ---*/ @@ -181,33 +170,34 @@ void CSysMatrix::Initialize(unsigned long npoint, unsigned long npoi /*--- Set suitable chunk sizes for light static for loops, and heavy dynamic ones, such that threads are approximately evenly loaded. ---*/ - omp_light_size = computeStaticChunkSize(nnz*nVar*nEqn, num_threads, OMP_MAX_SIZE_L); + omp_light_size = computeStaticChunkSize(nnz * nVar * nEqn, num_threads, OMP_MAX_SIZE_L); omp_heavy_size = computeStaticChunkSize(nPointDomain, num_threads, OMP_MAX_SIZE_H); omp_num_parts = config->GetLinear_Solver_Prec_Threads(); if (omp_num_parts == 0) omp_num_parts = num_threads; /*--- This is akin to the row_ptr. ---*/ - omp_partitions = new unsigned long [omp_num_parts+1]; + omp_partitions = new unsigned long[omp_num_parts + 1]; for (unsigned long i = 0; i <= omp_num_parts; ++i) omp_partitions[i] = nPointDomain; /*--- Work estimate based on non-zeros to produce balanced partitions. ---*/ - const auto row_ptr_prec = ilu_needed? row_ptr_ilu : row_ptr; + const auto row_ptr_prec = ilu_needed ? row_ptr_ilu : row_ptr; const auto nnz_prec = row_ptr_prec[nPointDomain]; const auto nnz_per_part = roundUpDiv(nnz_prec, omp_num_parts); for (auto iPoint = 0ul, part = 0ul; iPoint < nPointDomain; ++iPoint) { - if (row_ptr_prec[iPoint] >= part*nnz_per_part) - omp_partitions[part++] = iPoint; + if (row_ptr_prec[iPoint] >= part * nnz_per_part) omp_partitions[part++] = iPoint; } for (unsigned long thread = 0; thread < omp_num_parts; ++thread) { const auto begin = omp_partitions[thread]; const auto end = omp_partitions[thread + 1]; if (begin == end) { - cout << "WARNING: Redundant thread has been detected. Performance could be impacted due to low number of nodes per thread." << endl; + cout << "WARNING: Redundant thread has been detected. Performance could be impacted due to low number of nodes " + "per thread." + << endl; break; } } @@ -216,29 +206,27 @@ void CSysMatrix::Initialize(unsigned long npoint, unsigned long npoi #ifdef USE_MKL using mkl = mkl_jit_wrapper; - mkl::create_gemm(&MatrixMatrixProductJitter, MKL_ROW_MAJOR, MKL_NOTRANS, - MKL_NOTRANS, nVar, nVar, nVar, 1.0, nVar, nVar, 0.0, nVar); + mkl::create_gemm(&MatrixMatrixProductJitter, MKL_ROW_MAJOR, MKL_NOTRANS, MKL_NOTRANS, nVar, nVar, nVar, 1.0, nVar, + nVar, 0.0, nVar); MatrixMatrixProductKernel = mkl::get_gemm(MatrixMatrixProductJitter); - mkl::create_gemm(&MatrixVectorProductJitterBetaZero, MKL_COL_MAJOR, - MKL_NOTRANS, MKL_NOTRANS, 1, nVar, nEqn, 1.0, 1, nEqn, 0.0, 1); + mkl::create_gemm(&MatrixVectorProductJitterBetaZero, MKL_COL_MAJOR, MKL_NOTRANS, MKL_NOTRANS, 1, nVar, nEqn, 1.0, 1, + nEqn, 0.0, 1); MatrixVectorProductKernelBetaZero = mkl::get_gemm(MatrixVectorProductJitterBetaZero); - mkl::create_gemm(&MatrixVectorProductJitterBetaOne, MKL_COL_MAJOR, - MKL_NOTRANS, MKL_NOTRANS, 1, nVar, nEqn, 1.0, 1, nEqn, 1.0, 1); + mkl::create_gemm(&MatrixVectorProductJitterBetaOne, MKL_COL_MAJOR, MKL_NOTRANS, MKL_NOTRANS, 1, nVar, nEqn, 1.0, 1, + nEqn, 1.0, 1); MatrixVectorProductKernelBetaOne = mkl::get_gemm(MatrixVectorProductJitterBetaOne); - mkl::create_gemm(&MatrixVectorProductJitterAlphaMinusOne, MKL_COL_MAJOR, - MKL_NOTRANS, MKL_NOTRANS, 1, nVar, nEqn, -1.0, 1, nEqn, 1.0, 1); + mkl::create_gemm(&MatrixVectorProductJitterAlphaMinusOne, MKL_COL_MAJOR, MKL_NOTRANS, MKL_NOTRANS, 1, nVar, nEqn, + -1.0, 1, nEqn, 1.0, 1); MatrixVectorProductKernelAlphaMinusOne = mkl::get_gemm(MatrixVectorProductJitterAlphaMinusOne); #endif - } -template -void CSysMatrixComms::Initiate(const CSysVector& x, CGeometry *geometry, - const CConfig *config, unsigned short commType) { - +template +void CSysMatrixComms::Initiate(const CSysVector& x, CGeometry* geometry, const CConfig* config, + unsigned short commType) { if (geometry->nP2PSend == 0) return; /*--- Local variables ---*/ @@ -276,11 +264,8 @@ void CSysMatrixComms::Initiate(const CSysVector& x, CGeometry *geometry, geometry->PostP2PRecvs(geometry, config, MPI_TYPE, COUNT_PER_POINT, reverse); for (auto iMessage = 0; iMessage < geometry->nP2PSend; iMessage++) { - switch (commType) { - case SOLUTION_MATRIX: { - su2double* bufDSend = geometry->bufD_P2PSend; /*--- Get the offset for the start of this message. ---*/ @@ -289,30 +274,27 @@ void CSysMatrixComms::Initiate(const CSysVector& x, CGeometry *geometry, /*--- Total count can include multiple pieces of data per point. ---*/ - const auto nSend = (geometry->nPoint_P2PSend[iMessage+1] - geometry->nPoint_P2PSend[iMessage]); + const auto nSend = (geometry->nPoint_P2PSend[iMessage + 1] - geometry->nPoint_P2PSend[iMessage]); SU2_OMP_FOR_STAT(CSysMatrix::OMP_MIN_SIZE) for (auto iSend = 0; iSend < nSend; iSend++) { - /*--- Get the local index for this communicated data. ---*/ const auto iPoint = geometry->Local_Point_P2PSend[msg_offset + iSend]; /*--- Compute the offset in the recv buffer for this point. ---*/ - const auto buf_offset = (msg_offset + iSend)*COUNT_PER_POINT; + const auto buf_offset = (msg_offset + iSend) * COUNT_PER_POINT; /*--- Load the buffer with the data to be sent. ---*/ - for (auto iVar = 0ul; iVar < x.GetNVar(); iVar++) - bufDSend[buf_offset+iVar] = x(iPoint,iVar); + for (auto iVar = 0ul; iVar < x.GetNVar(); iVar++) bufDSend[buf_offset + iVar] = x(iPoint, iVar); } END_SU2_OMP_FOR break; } case SOLUTION_MATRIXTRANS: { - /*--- We are going to communicate in reverse, so we use the recv buffer for the send instead. Also, all of the offsets and counts are derived from the recv data structures. ---*/ @@ -325,11 +307,10 @@ void CSysMatrixComms::Initiate(const CSysVector& x, CGeometry *geometry, /*--- Total count can include multiple pieces of data per point. ---*/ - const auto nSend = (geometry->nPoint_P2PRecv[iMessage+1] - geometry->nPoint_P2PRecv[iMessage]); + const auto nSend = (geometry->nPoint_P2PRecv[iMessage + 1] - geometry->nPoint_P2PRecv[iMessage]); SU2_OMP_FOR_STAT(CSysMatrix::OMP_MIN_SIZE) for (auto iSend = 0; iSend < nSend; iSend++) { - /*--- Get the local index for this communicated data. Here we again use the recv structure to find the send point, since the usual recv points are now the senders in reverse mode. ---*/ @@ -338,36 +319,29 @@ void CSysMatrixComms::Initiate(const CSysVector& x, CGeometry *geometry, /*--- Compute the offset in the recv buffer for this point. ---*/ - const auto buf_offset = (msg_offset + iSend)*COUNT_PER_POINT; + const auto buf_offset = (msg_offset + iSend) * COUNT_PER_POINT; /*--- Load the buffer with the data to be sent. ---*/ - for (auto iVar = 0ul; iVar < x.GetNVar(); iVar++) - bufDSend[buf_offset+iVar] = x(iPoint,iVar); + for (auto iVar = 0ul; iVar < x.GetNVar(); iVar++) bufDSend[buf_offset + iVar] = x(iPoint, iVar); } END_SU2_OMP_FOR break; } default: - SU2_MPI::Error("Unrecognized quantity for point-to-point MPI comms.", - CURRENT_FUNCTION); + SU2_MPI::Error("Unrecognized quantity for point-to-point MPI comms.", CURRENT_FUNCTION); break; - } /*--- Launch the point-to-point MPI send for this message. ---*/ geometry->PostP2PSends(geometry, config, MPI_TYPE, COUNT_PER_POINT, iMessage, reverse); - } - } -template -void CSysMatrixComms::Complete(CSysVector& x, CGeometry *geometry, - const CConfig *config, unsigned short commType) { - +template +void CSysMatrixComms::Complete(CSysVector& x, CGeometry* geometry, const CConfig* config, unsigned short commType) { if (geometry->nP2PRecv == 0) return; /*--- Local variables ---*/ @@ -382,7 +356,6 @@ void CSysMatrixComms::Complete(CSysVector& x, CGeometry *geometry, location within the local class data structures. ---*/ for (auto iMessage = 0; iMessage < geometry->nP2PRecv; iMessage++) { - /*--- For efficiency, recv the messages dynamically based on the order they arrive. ---*/ @@ -394,8 +367,7 @@ void CSysMatrixComms::Complete(CSysVector& x, CGeometry *geometry, switch (commType) { case SOLUTION_MATRIX: { - - const su2double *bufDRecv = geometry->bufD_P2PRecv; + const su2double* bufDRecv = geometry->bufD_P2PRecv; /*--- We know the offsets based on the source rank. ---*/ @@ -407,30 +379,28 @@ void CSysMatrixComms::Complete(CSysVector& x, CGeometry *geometry, /*--- Get the number of packets to be received in this message. ---*/ - const auto nRecv = (geometry->nPoint_P2PRecv[jRecv+1] - geometry->nPoint_P2PRecv[jRecv]); + const auto nRecv = (geometry->nPoint_P2PRecv[jRecv + 1] - geometry->nPoint_P2PRecv[jRecv]); SU2_OMP_FOR_STAT(CSysMatrix::OMP_MIN_SIZE) for (auto iRecv = 0; iRecv < nRecv; iRecv++) { - /*--- Get the local index for this communicated data. ---*/ const auto iPoint = geometry->Local_Point_P2PRecv[msg_offset + iRecv]; /*--- Compute the offset in the recv buffer for this point. ---*/ - const auto buf_offset = (msg_offset + iRecv)*COUNT_PER_POINT; + const auto buf_offset = (msg_offset + iRecv) * COUNT_PER_POINT; /*--- Store the data correctly depending on the quantity. ---*/ for (auto iVar = 0ul; iVar < x.GetNVar(); iVar++) - x(iPoint,iVar) = CSysMatrix::template ActiveAssign(bufDRecv[buf_offset+iVar]); + x(iPoint, iVar) = CSysMatrix::template ActiveAssign(bufDRecv[buf_offset + iVar]); } END_SU2_OMP_FOR break; } case SOLUTION_MATRIXTRANS: { - /*--- We are going to communicate in reverse, so we use the send buffer for the recv instead. Also, all of the offsets and counts are derived from the send data structures. ---*/ @@ -447,23 +417,22 @@ void CSysMatrixComms::Complete(CSysVector& x, CGeometry *geometry, /*--- Get the number of packets to be received in this message. ---*/ - const auto nRecv = (geometry->nPoint_P2PSend[jRecv+1] - geometry->nPoint_P2PSend[jRecv]); + const auto nRecv = (geometry->nPoint_P2PSend[jRecv + 1] - geometry->nPoint_P2PSend[jRecv]); SU2_OMP_FOR_STAT(CSysMatrix::OMP_MIN_SIZE) for (auto iRecv = 0; iRecv < nRecv; iRecv++) { - /*--- Get the local index for this communicated data. ---*/ const auto iPoint = geometry->Local_Point_P2PSend[msg_offset + iRecv]; /*--- Compute the offset in the recv buffer for this point. ---*/ - const auto buf_offset = (msg_offset + iRecv)*COUNT_PER_POINT; + const auto buf_offset = (msg_offset + iRecv) * COUNT_PER_POINT; /*--- Update receiving point. ---*/ for (auto iVar = 0ul; iVar < x.GetNVar(); iVar++) - x(iPoint,iVar) += CSysMatrix::template ActiveAssign(bufDRecv[buf_offset+iVar]); + x(iPoint, iVar) += CSysMatrix::template ActiveAssign(bufDRecv[buf_offset + iVar]); } END_SU2_OMP_FOR break; @@ -484,60 +453,55 @@ void CSysMatrixComms::Complete(CSysVector& x, CGeometry *geometry, #endif } -template +template void CSysMatrix::SetValZero() { - const auto size = nnz*nVar*nEqn; - const auto chunk = roundUpDiv(size,omp_get_num_threads()); + const auto size = nnz * nVar * nEqn; + const auto chunk = roundUpDiv(size, omp_get_num_threads()); const auto begin = chunk * omp_get_thread_num(); - const auto mySize = min(chunk, size-begin) * sizeof(ScalarType); + const auto mySize = min(chunk, size - begin) * sizeof(ScalarType); memset(&matrix[begin], 0, mySize); SU2_OMP_BARRIER } -template +template void CSysMatrix::SetValDiagonalZero() { SU2_OMP_FOR_STAT(omp_heavy_size) for (auto iPoint = 0ul; iPoint < nPointDomain; ++iPoint) - for (auto index = 0ul; index < nVar*nEqn; ++index) - matrix[dia_ptr[iPoint]*nVar*nEqn + index] = 0.0; + for (auto index = 0ul; index < nVar * nEqn; ++index) matrix[dia_ptr[iPoint] * nVar * nEqn + index] = 0.0; END_SU2_OMP_FOR } -template +template void CSysMatrix::Gauss_Elimination(ScalarType* matrix, ScalarType* vec) const { - #ifdef USE_MKL_LAPACK // With MKL_DIRECT_CALL enabled, this is significantly faster than native code on Intel Architectures. lapack_int ipiv[MAXNVAR]; - LAPACKE_dgetrf( LAPACK_ROW_MAJOR, nVar, nVar, matrix, nVar, ipiv); - LAPACKE_dgetrs( LAPACK_ROW_MAJOR, 'N', nVar, 1, matrix, nVar, ipiv, vec, 1 ); + LAPACKE_dgetrf(LAPACK_ROW_MAJOR, nVar, nVar, matrix, nVar, ipiv); + LAPACKE_dgetrs(LAPACK_ROW_MAJOR, 'N', nVar, 1, matrix, nVar, ipiv, vec, 1); #else -#define A(I,J) matrix[(I)*nVar+(J)] +#define A(I, J) matrix[(I)*nVar + (J)] /*--- Transform system in Upper Matrix ---*/ for (auto iVar = 1ul; iVar < nVar; iVar++) { for (auto jVar = 0ul; jVar < iVar; jVar++) { - ScalarType weight = A(iVar,jVar) / A(jVar,jVar); - for (auto kVar = jVar; kVar < nVar; kVar++) - A(iVar,kVar) -= weight * A(jVar,kVar); + ScalarType weight = A(iVar, jVar) / A(jVar, jVar); + for (auto kVar = jVar; kVar < nVar; kVar++) A(iVar, kVar) -= weight * A(jVar, kVar); vec[iVar] -= weight * vec[jVar]; } } /*--- Backwards substitution ---*/ for (auto iVar = nVar; iVar > 0ul;) { - iVar--; // unsigned type - for (auto jVar = iVar+1; jVar < nVar; jVar++) - vec[iVar] -= A(iVar,jVar) * vec[jVar]; - vec[iVar] /= A(iVar,iVar); + iVar--; // unsigned type + for (auto jVar = iVar + 1; jVar < nVar; jVar++) vec[iVar] -= A(iVar, jVar) * vec[jVar]; + vec[iVar] /= A(iVar, iVar); } #undef A #endif } -template -void CSysMatrix::MatrixInverse(ScalarType *matrix, ScalarType *inverse) const { - +template +void CSysMatrix::MatrixInverse(ScalarType* matrix, ScalarType* inverse) const { /*--- This is a generalization of Gaussian elimination for multiple rhs' (the basis vectors). We could call "Gauss_Elimination" multiple times or fully generalize it for multiple rhs, the performance of both routines would suffer in both cases without the use of exotic templating. @@ -545,70 +509,62 @@ void CSysMatrix::MatrixInverse(ScalarType *matrix, ScalarType *inver assert((matrix != inverse) && "Output cannot be the same as the input."); -#define M(I,J) inverse[(I)*nVar+(J)] +#define M(I, J) inverse[(I)*nVar + (J)] /*--- Initialize the inverse with the identity. ---*/ for (auto iVar = 0ul; iVar < nVar; iVar++) - for (auto jVar = 0ul; jVar < nVar; jVar++) - M(iVar,jVar) = ScalarType(iVar==jVar); + for (auto jVar = 0ul; jVar < nVar; jVar++) M(iVar, jVar) = ScalarType(iVar == jVar); - /*--- Inversion ---*/ + /*--- Inversion ---*/ #ifdef USE_MKL_LAPACK // With MKL_DIRECT_CALL enabled, this is significantly faster than native code on Intel Architectures. lapack_int ipiv[MAXNVAR]; - LAPACKE_dgetrf( LAPACK_ROW_MAJOR, nVar, nVar, matrix, nVar, ipiv ); - LAPACKE_dgetrs( LAPACK_ROW_MAJOR, 'N', nVar, nVar, matrix, nVar, ipiv, inverse, nVar ); + LAPACKE_dgetrf(LAPACK_ROW_MAJOR, nVar, nVar, matrix, nVar, ipiv); + LAPACKE_dgetrs(LAPACK_ROW_MAJOR, 'N', nVar, nVar, matrix, nVar, ipiv, inverse, nVar); #else -#define A(I,J) matrix[(I)*nVar+(J)] +#define A(I, J) matrix[(I)*nVar + (J)] /*--- Transform system in Upper Matrix ---*/ for (auto iVar = 1ul; iVar < nVar; iVar++) { - for (auto jVar = 0ul; jVar < iVar; jVar++) - { - ScalarType weight = A(iVar,jVar) / A(jVar,jVar); + for (auto jVar = 0ul; jVar < iVar; jVar++) { + ScalarType weight = A(iVar, jVar) / A(jVar, jVar); - for (auto kVar = jVar; kVar < nVar; kVar++) - A(iVar,kVar) -= weight * A(jVar,kVar); + for (auto kVar = jVar; kVar < nVar; kVar++) A(iVar, kVar) -= weight * A(jVar, kVar); /*--- at this stage M is lower triangular so not all cols need updating ---*/ - for (auto kVar = 0ul; kVar <= jVar; kVar++) - M(iVar,kVar) -= weight * M(jVar,kVar); + for (auto kVar = 0ul; kVar <= jVar; kVar++) M(iVar, kVar) -= weight * M(jVar, kVar); } } /*--- Backwards substitution ---*/ for (auto iVar = nVar; iVar > 0ul;) { - iVar--; // unsigned type - for (auto jVar = iVar+1; jVar < nVar; jVar++) - for (auto kVar = 0ul; kVar < nVar; kVar++) - M(iVar,kVar) -= A(iVar,jVar) * M(jVar,kVar); + iVar--; // unsigned type + for (auto jVar = iVar + 1; jVar < nVar; jVar++) + for (auto kVar = 0ul; kVar < nVar; kVar++) M(iVar, kVar) -= A(iVar, jVar) * M(jVar, kVar); - for (auto kVar = 0ul; kVar < nVar; kVar++) - M(iVar,kVar) /= A(iVar,iVar); + for (auto kVar = 0ul; kVar < nVar; kVar++) M(iVar, kVar) /= A(iVar, iVar); } #undef A #endif #undef M } -template +template void CSysMatrix::DeleteValsRowi(unsigned long i) { + const auto block_i = i / nVar; + const auto row = i % nVar; - const auto block_i = i/nVar; - const auto row = i%nVar; - - for (auto index = row_ptr[block_i]; index < row_ptr[block_i+1]; index++) { + for (auto index = row_ptr[block_i]; index < row_ptr[block_i + 1]; index++) { for (auto iVar = 0u; iVar < nVar; iVar++) - matrix[index*nVar*nVar+row*nVar+iVar] = 0.0; // Delete row values in the block + matrix[index * nVar * nVar + row * nVar + iVar] = 0.0; // Delete row values in the block if (col_ind[index] == block_i) - matrix[index*nVar*nVar+row*nVar+row] = 1.0; // Set 1 to the diagonal element + matrix[index * nVar * nVar + row * nVar + row] = 1.0; // Set 1 to the diagonal element } } -template -void CSysMatrix::MatrixVectorProduct(const CSysVector & vec, CSysVector & prod, - CGeometry *geometry, const CConfig *config) const { - +template +void CSysMatrix::MatrixVectorProduct(const CSysVector& vec, CSysVector& prod, + CGeometry* geometry, const CConfig* config) const { /*--- Some checks for consistency between CSysMatrix and the CSysVectors ---*/ #ifndef NDEBUG if ((nEqn != vec.GetNVar()) || (nVar != prod.GetNVar())) { @@ -627,7 +583,7 @@ void CSysMatrix::MatrixVectorProduct(const CSysVector & SU2_OMP_FOR_DYN(omp_heavy_size) for (auto row_i = 0ul; row_i < nPointDomain; row_i++) { - RowProduct(vec, row_i, &prod[row_i*nVar]); + RowProduct(vec, row_i, &prod[row_i * nVar]); } END_SU2_OMP_FOR @@ -635,63 +591,55 @@ void CSysMatrix::MatrixVectorProduct(const CSysVector & CSysMatrixComms::Initiate(prod, geometry, config); CSysMatrixComms::Complete(prod, geometry, config); - } -template +template void CSysMatrix::BuildJacobiPreconditioner() { - /*--- Build Jacobi preconditioner (M = D), compute and store the inverses of the diagonal blocks. ---*/ SU2_OMP_FOR_DYN(omp_heavy_size) for (unsigned long iPoint = 0; iPoint < nPointDomain; iPoint++) - InverseDiagonalBlock(iPoint, &(invM[iPoint*nVar*nVar])); + InverseDiagonalBlock(iPoint, &(invM[iPoint * nVar * nVar])); END_SU2_OMP_FOR - } -template -void CSysMatrix::ComputeJacobiPreconditioner(const CSysVector & vec, CSysVector & prod, - CGeometry *geometry, const CConfig *config) const { - +template +void CSysMatrix::ComputeJacobiPreconditioner(const CSysVector& vec, + CSysVector& prod, CGeometry* geometry, + const CConfig* config) const { /*--- Apply Jacobi preconditioner, y = D^{-1} * x, the inverse of the diagonal is already known. ---*/ SU2_OMP_BARRIER SU2_OMP_FOR_DYN(omp_heavy_size) for (unsigned long iPoint = 0; iPoint < nPointDomain; iPoint++) - MatrixVectorProduct(&(invM[iPoint*nVar*nVar]), &vec[iPoint*nVar], &prod[iPoint*nVar]); + MatrixVectorProduct(&(invM[iPoint * nVar * nVar]), &vec[iPoint * nVar], &prod[iPoint * nVar]); END_SU2_OMP_FOR /*--- MPI Parallelization ---*/ CSysMatrixComms::Initiate(prod, geometry, config); CSysMatrixComms::Complete(prod, geometry, config); - } -template +template void CSysMatrix::BuildILUPreconditioner() { - /*--- Copy block matrix to compute factorization in-place. ---*/ if (ilu_fill_in == 0) { /*--- ILU0, direct copy. ---*/ SU2_OMP_FOR_STAT(omp_light_size) - for (auto iVar = 0ul; iVar < nnz*nVar*nVar; ++iVar) - ILU_matrix[iVar] = matrix[iVar]; + for (auto iVar = 0ul; iVar < nnz * nVar * nVar; ++iVar) ILU_matrix[iVar] = matrix[iVar]; END_SU2_OMP_FOR - } - else { + } else { /*--- ILUn clear the ILU matrix first. ---*/ SU2_OMP_FOR_STAT(omp_light_size) - for (auto iVar = 0ul; iVar < nnz_ilu*nVar*nVar; iVar++) - ILU_matrix[iVar] = 0.0; + for (auto iVar = 0ul; iVar < nnz_ilu * nVar * nVar; iVar++) ILU_matrix[iVar] = 0.0; END_SU2_OMP_FOR /*--- ILUn, traverse matrix to access its blocks * sequentially and set them in the ILU matrix. ---*/ SU2_OMP_FOR_DYN(omp_heavy_size) for (auto iPoint = 0ul; iPoint < nPointDomain; iPoint++) { - for (auto index = row_ptr[iPoint]; index < row_ptr[iPoint+1]; index++) { + for (auto index = row_ptr[iPoint]; index < row_ptr[iPoint + 1]; index++) { auto jPoint = col_ind[index]; - SetBlock_ILUMatrix(iPoint, jPoint, &matrix[index*nVar*nVar]); + SetBlock_ILUMatrix(iPoint, jPoint, &matrix[index * nVar * nVar]); } } END_SU2_OMP_FOR @@ -704,28 +652,25 @@ void CSysMatrix::BuildILUPreconditioner() { * outside of a parallel section. ---*/ SU2_OMP_FOR_STAT(1) - for(unsigned long thread = 0; thread < omp_num_parts; ++thread) - { + for (unsigned long thread = 0; thread < omp_num_parts; ++thread) { const auto begin = omp_partitions[thread]; - const auto end = omp_partitions[thread+1]; + const auto end = omp_partitions[thread + 1]; if (begin == end) continue; /*--- Each thread will work on the submatrix defined from row/col "begin" * to row/col "end-1" (i.e. the range [begin,end[). Which is exactly * what the MPI-only implementation does. ---*/ - ScalarType weight[MAXNVAR*MAXNVAR], aux_block[MAXNVAR*MAXNVAR]; - - for (auto iPoint = begin+1; iPoint < end; iPoint++) { + ScalarType weight[MAXNVAR * MAXNVAR], aux_block[MAXNVAR * MAXNVAR]; + for (auto iPoint = begin + 1; iPoint < end; iPoint++) { /*--- Invert and store the previous diagonal block to later compute the weight. ---*/ - InverseDiagonalBlock_ILUMatrix(iPoint-1, &invM[(iPoint-1)*nVar*nVar]); + InverseDiagonalBlock_ILUMatrix(iPoint - 1, &invM[(iPoint - 1) * nVar * nVar]); /*--- For this row (unknown), loop over its lower diagonal entries. ---*/ for (auto index = row_ptr_ilu[iPoint]; index < dia_ptr_ilu[iPoint]; index++) { - /*--- jPoint is the column index (jPoint < iPoint). ---*/ auto jPoint = col_ind_ilu[index]; @@ -736,13 +681,12 @@ void CSysMatrix::BuildILUPreconditioner() { /*--- Multiply the block by the inverse of the corresponding diagonal block. ---*/ - auto Block_ij = &ILU_matrix[index*nVar*nVar]; - MatrixMatrixProduct(Block_ij, &invM[jPoint*nVar*nVar], weight); + auto Block_ij = &ILU_matrix[index * nVar * nVar]; + MatrixMatrixProduct(Block_ij, &invM[jPoint * nVar * nVar], weight); /*--- "weight" holds Aij*inv(Ajj). Jump to the upper part of the jPoint row. ---*/ - for (auto index_ = dia_ptr_ilu[jPoint]+1; index_ < row_ptr_ilu[jPoint+1]; index_++) { - + for (auto index_ = dia_ptr_ilu[jPoint] + 1; index_ < row_ptr_ilu[jPoint + 1]; index_++) { /*--- Get the column index (kPoint > jPoint). ---*/ auto kPoint = col_ind_ilu[index_]; @@ -754,7 +698,7 @@ void CSysMatrix::BuildILUPreconditioner() { auto Block_ik = GetBlock_ILUMatrix(iPoint, kPoint); if (Block_ik != nullptr) { - auto Block_jk = &ILU_matrix[index_*nVar*nVar]; + auto Block_jk = &ILU_matrix[index_ * nVar * nVar]; MatrixMatrixProduct(weight, Block_jk, aux_block); MatrixSubtraction(Block_ik, aux_block, Block_ik); } @@ -763,66 +707,60 @@ void CSysMatrix::BuildILUPreconditioner() { /*--- Lastly, store "weight" in the lower triangular part, which will be reused during the forward solve in the precon/smoother. ---*/ - for (auto iVar = 0ul; iVar < nVar*nVar; ++iVar) - Block_ij[iVar] = weight[iVar]; + for (auto iVar = 0ul; iVar < nVar * nVar; ++iVar) Block_ij[iVar] = weight[iVar]; } } - InverseDiagonalBlock_ILUMatrix(end-1, &invM[(end-1)*nVar*nVar]); - + InverseDiagonalBlock_ILUMatrix(end - 1, &invM[(end - 1) * nVar * nVar]); } END_SU2_OMP_FOR - } -template -void CSysMatrix::ComputeILUPreconditioner(const CSysVector & vec, CSysVector & prod, - CGeometry *geometry, const CConfig *config) const { +template +void CSysMatrix::ComputeILUPreconditioner(const CSysVector& vec, CSysVector& prod, + CGeometry* geometry, const CConfig* config) const { /*--- Coherent view of vectors. ---*/ SU2_OMP_BARRIER /*--- OpenMP Parallelization ---*/ SU2_OMP_FOR_STAT(1) - for(unsigned long thread = 0; thread < omp_num_parts; ++thread) - { + for (unsigned long thread = 0; thread < omp_num_parts; ++thread) { const auto begin = omp_partitions[thread]; - const auto end = omp_partitions[thread+1]; + const auto end = omp_partitions[thread + 1]; if (begin == end) continue; ScalarType aux_vec[MAXNVAR]; /*--- Copy vector to then work on prod in place ---*/ - for (auto iVar = begin*nVar; iVar < end*nVar; iVar++) - prod[iVar] = vec[iVar]; + for (auto iVar = begin * nVar; iVar < end * nVar; iVar++) prod[iVar] = vec[iVar]; /*--- Forward solve the system using the lower matrix entries that were computed and stored during the ILU preprocessing. Note that we are overwriting the residual vector as we go. ---*/ - for (auto iPoint = begin+1; iPoint < end; iPoint++) { + for (auto iPoint = begin + 1; iPoint < end; iPoint++) { for (auto index = row_ptr_ilu[iPoint]; index < dia_ptr_ilu[iPoint]; index++) { auto jPoint = col_ind_ilu[index]; if (jPoint < begin) continue; - auto Block_ij = &ILU_matrix[index*nVar*nVar]; - MatrixVectorProductSub(Block_ij, &prod[jPoint*nVar], &prod[iPoint*nVar]); + auto Block_ij = &ILU_matrix[index * nVar * nVar]; + MatrixVectorProductSub(Block_ij, &prod[jPoint * nVar], &prod[iPoint * nVar]); } } /*--- Backwards substitution (starts at the last row) ---*/ for (auto iPoint = end; iPoint > begin;) { - iPoint--; // unsigned type - for (auto iVar = 0ul; iVar < nVar; iVar++) - aux_vec[iVar] = prod[iPoint*nVar+iVar]; + iPoint--; // unsigned type + for (auto iVar = 0ul; iVar < nVar; iVar++) aux_vec[iVar] = prod[iPoint * nVar + iVar]; - for (auto index = dia_ptr_ilu[iPoint]+1; index < row_ptr_ilu[iPoint+1]; index++) { + for (auto index = dia_ptr_ilu[iPoint] + 1; index < row_ptr_ilu[iPoint + 1]; index++) { auto jPoint = col_ind_ilu[index]; if (jPoint >= end) break; - auto Block_ij = &ILU_matrix[index*nVar*nVar]; - MatrixVectorProductSub(Block_ij, &prod[jPoint*nVar], aux_vec); + auto Block_ij = &ILU_matrix[index * nVar * nVar]; + MatrixVectorProductSub(Block_ij, &prod[jPoint * nVar], aux_vec); } - MatrixVectorProduct(&invM[iPoint*nVar*nVar], aux_vec, &prod[iPoint*nVar]); + MatrixVectorProduct(&invM[iPoint * nVar * nVar], aux_vec, &prod[iPoint * nVar]); } } END_SU2_OMP_FOR @@ -831,13 +769,12 @@ void CSysMatrix::ComputeILUPreconditioner(const CSysVector -void CSysMatrix::ComputeLU_SGSPreconditioner(const CSysVector & vec, CSysVector & prod, - CGeometry *geometry, const CConfig *config) const { - +template +void CSysMatrix::ComputeLU_SGSPreconditioner(const CSysVector& vec, + CSysVector& prod, CGeometry* geometry, + const CConfig* config) const { /*--- First part of the symmetric iteration: (D+L).x* = b ---*/ /*--- Coherent view of vectors. ---*/ @@ -845,10 +782,9 @@ void CSysMatrix::ComputeLU_SGSPreconditioner(const CSysVector::ComputeLU_SGSPreconditioner(const CSysVector::ComputeLU_SGSPreconditioner(const CSysVector begin;) { - iPoint--; // because of unsigned type - auto idx = iPoint*nVar; - DiagonalProduct(prod, iPoint, dia_prod); // Compute D.x* - UpperProduct(prod, iPoint, row_end, up_prod); // Compute U.x_(n+1) - VectorSubtraction(dia_prod, up_prod, &prod[idx]); // Compute y = D.x*-U.x_(n+1) - Gauss_Elimination(iPoint, &prod[idx]); // Solve D.x* = y + iPoint--; // because of unsigned type + auto idx = iPoint * nVar; + DiagonalProduct(prod, iPoint, dia_prod); // Compute D.x* + UpperProduct(prod, iPoint, row_end, up_prod); // Compute U.x_(n+1) + VectorSubtraction(dia_prod, up_prod, &prod[idx]); // Compute y = D.x*-U.x_(n+1) + Gauss_Elimination(iPoint, &prod[idx]); // Solve D.x* = y } } END_SU2_OMP_FOR @@ -899,12 +834,10 @@ void CSysMatrix::ComputeLU_SGSPreconditioner(const CSysVector -void CSysMatrix::BuildLineletPreconditioner(const CGeometry *geometry, const CConfig *config) { - +template +void CSysMatrix::BuildLineletPreconditioner(const CGeometry* geometry, const CConfig* config) { BuildJacobiPreconditioner(); /*--- Allocate working vectors if not done yet. ---*/ @@ -932,9 +865,10 @@ void CSysMatrix::BuildLineletPreconditioner(const CGeometry *geometr END_SU2_OMP_FOR } -template -void CSysMatrix::ComputeLineletPreconditioner(const CSysVector & vec, CSysVector & prod, - CGeometry *geometry, const CConfig *config) const { +template +void CSysMatrix::ComputeLineletPreconditioner(const CSysVector& vec, + CSysVector& prod, CGeometry* geometry, + const CConfig* config) const { /*--- Coherent view of vectors. ---*/ SU2_OMP_BARRIER @@ -942,17 +876,16 @@ void CSysMatrix::ComputeLineletPreconditioner(const CSysVector::ComputeLineletPreconditioner(const CSysVector::ComputeLineletPreconditioner(const CSysVector 0; --iElem) { - const auto* inv_dm1 = &lineletInvDiag[(iElem-1)*nVar*nVar]; - MatrixVectorProduct(lineletUpper[iElem-1], &lineletVector[iElem*nVar], aux_vector); - VectorSubtraction(&lineletVector[(iElem-1)*nVar], aux_vector, aux_vector); - MatrixVectorProduct(inv_dm1, aux_vector, &lineletVector[(iElem-1)*nVar]); + for (auto iElem = nElem - 1; iElem > 0; --iElem) { + const auto* inv_dm1 = &lineletInvDiag[(iElem - 1) * nVar * nVar]; + MatrixVectorProduct(lineletUpper[iElem - 1], &lineletVector[iElem * nVar], aux_vector); + VectorSubtraction(&lineletVector[(iElem - 1) * nVar], aux_vector, aux_vector); + MatrixVectorProduct(inv_dm1, aux_vector, &lineletVector[(iElem - 1) * nVar]); } /*--- Copy results to product vector ---*/ for (auto iElem = 0ul; iElem < nElem; iElem++) { const auto iPoint = li.linelets[iLinelet][iElem]; - for (auto iVar = 0ul; iVar < nVar; iVar++) - prod[iPoint*nVar+iVar] = lineletVector[iElem*nVar+iVar]; + for (auto iVar = 0ul; iVar < nVar; iVar++) prod[iPoint * nVar + iVar] = lineletVector[iElem * nVar + iVar]; } - } END_SU2_OMP_FOR @@ -1040,40 +968,38 @@ void CSysMatrix::ComputeLineletPreconditioner(const CSysVector -void CSysMatrix::ComputeResidual(const CSysVector & sol, const CSysVector & f, - CSysVector & res) const { +template +void CSysMatrix::ComputeResidual(const CSysVector& sol, const CSysVector& f, + CSysVector& res) const { SU2_OMP_BARRIER SU2_OMP_FOR_DYN(omp_heavy_size) for (unsigned long iPoint = 0; iPoint < nPointDomain; iPoint++) { ScalarType aux_vec[MAXNVAR]; RowProduct(sol, iPoint, aux_vec); - VectorSubtraction(aux_vec, &f[iPoint*nVar], &res[iPoint*nVar]); + VectorSubtraction(aux_vec, &f[iPoint * nVar], &res[iPoint * nVar]); } END_SU2_OMP_FOR } -template -template -void CSysMatrix::EnforceSolutionAtNode(const unsigned long node_i, const OtherType *x_i, CSysVector & b) { - +template +template +void CSysMatrix::EnforceSolutionAtNode(const unsigned long node_i, const OtherType* x_i, + CSysVector& b) { /*--- Eliminate the row associated with node i (Block_ii = I and all other Block_ij = 0). * To preserve eventual symmetry, also attempt to eliminate the column, if the sparse pattern is not * symmetric the entire column may not be eliminated, the result (matrix and vector) is still correct. * The vector is updated with the product of column i by the known (enforced) solution at node i. ---*/ - for (auto index = row_ptr[node_i]; index < row_ptr[node_i+1]; ++index) { - + for (auto index = row_ptr[node_i]; index < row_ptr[node_i + 1]; ++index) { auto node_j = col_ind[index]; /*--- The diagonal block is handled outside the loop. ---*/ if (node_j == node_i) continue; /*--- Delete block j on row i (bij) and ATTEMPT to delete block i on row j (bji). ---*/ - auto bij = &matrix[index*nVar*nVar]; + auto bij = &matrix[index * nVar * nVar]; auto bji = GetBlock(node_j, node_i); /*--- The "attempt" part. ---*/ @@ -1082,15 +1008,14 @@ void CSysMatrix::EnforceSolutionAtNode(const unsigned long node_i, c bji = bij; } - for(auto iVar = 0ul; iVar < nVar; ++iVar) { - for(auto jVar = 0ul; jVar < nVar; ++jVar) { + for (auto iVar = 0ul; iVar < nVar; ++iVar) { + for (auto jVar = 0ul; jVar < nVar; ++jVar) { /*--- Column product. ---*/ - b[node_j*nVar+iVar] -= bji[iVar*nVar+jVar] * x_i[jVar]; + b[node_j * nVar + iVar] -= bji[iVar * nVar + jVar] * x_i[jVar]; /*--- Delete blocks. ---*/ - bij[iVar*nVar+jVar] = bji[iVar*nVar+jVar] = 0.0; + bij[iVar * nVar + jVar] = bji[iVar * nVar + jVar] = 0.0; } } - } /*--- Set the diagonal block to the identity. ---*/ @@ -1098,82 +1023,73 @@ void CSysMatrix::EnforceSolutionAtNode(const unsigned long node_i, c /*--- Set known solution in rhs vector. ---*/ b.SetBlock(node_i, x_i); - } -template -template -void CSysMatrix::EnforceSolutionAtDOF(unsigned long node_i, unsigned long iVar, - OtherType x_i, CSysVector & b) { - - for (auto index = row_ptr[node_i]; index < row_ptr[node_i+1]; ++index) { - +template +template +void CSysMatrix::EnforceSolutionAtDOF(unsigned long node_i, unsigned long iVar, OtherType x_i, + CSysVector& b) { + for (auto index = row_ptr[node_i]; index < row_ptr[node_i + 1]; ++index) { const auto node_j = col_ind[index]; /*--- Delete row iVar of block j on row i (bij) and ATTEMPT * to delete column iVar block i on row j (bji). ---*/ - auto bij = &matrix[index*nVar*nVar]; + auto bij = &matrix[index * nVar * nVar]; auto bji = GetBlock(node_j, node_i); /*--- The "attempt" part. ---*/ if (bji != nullptr) { - for(auto jVar = 0ul; jVar < nVar; ++jVar) { + for (auto jVar = 0ul; jVar < nVar; ++jVar) { /*--- Column product. ---*/ - b[node_j*nVar+jVar] -= bji[jVar*nVar+iVar] * x_i; + b[node_j * nVar + jVar] -= bji[jVar * nVar + iVar] * x_i; /*--- Delete entries. ---*/ - bji[jVar*nVar+iVar] = 0.0; + bji[jVar * nVar + iVar] = 0.0; } } /*--- Delete row. ---*/ - for(auto jVar = 0ul; jVar < nVar; ++jVar) - bij[iVar*nVar+jVar] = 0.0; + for (auto jVar = 0ul; jVar < nVar; ++jVar) bij[iVar * nVar + jVar] = 0.0; /*--- Set the diagonal entry of the block to 1. ---*/ - if (node_j == node_i) - bij[iVar*(nVar+1)] = 1.0; + if (node_j == node_i) bij[iVar * (nVar + 1)] = 1.0; } /*--- Set known solution in rhs vector. ---*/ b(node_i, iVar) = x_i; - } -template +template void CSysMatrix::SetDiagonalAsColumnSum() { - SU2_OMP_FOR_DYN(omp_heavy_size) for (auto iPoint = 0ul; iPoint < nPoint; ++iPoint) { + auto block_ii = &matrix[dia_ptr[iPoint] * nVar * nEqn]; - auto block_ii = &matrix[dia_ptr[iPoint]*nVar*nEqn]; - - for (auto k = 0ul; k < nVar*nEqn; ++k) block_ii[k] = 0.0; + for (auto k = 0ul; k < nVar * nEqn; ++k) block_ii[k] = 0.0; - for (auto k = row_ptr[iPoint]; k < row_ptr[iPoint+1]; ++k) { - auto block_ji = &matrix[col_ptr[k]*nVar*nEqn]; + for (auto k = row_ptr[iPoint]; k < row_ptr[iPoint + 1]; ++k) { + auto block_ji = &matrix[col_ptr[k] * nVar * nEqn]; if (block_ji != block_ii) MatrixSubtraction(block_ii, block_ji, block_ii); } } END_SU2_OMP_FOR } -template +template void CSysMatrix::TransposeInPlace() { - - assert(nVar==nEqn && "Cannot transpose with nVar != nEqn."); + assert(nVar == nEqn && "Cannot transpose with nVar != nEqn."); auto swapAndTransp = [](unsigned long n, ScalarType* a, ScalarType* b) { - assert(a!=b); + assert(a != b); /*--- a=b', b=a' ---*/ - for (auto i=0ul; i::TransposeInPlace() { if (edge_ptr) { /*--- The FV way. ---*/ - SU2_OMP_FOR_DYN(omp_heavy_size*2) + SU2_OMP_FOR_DYN(omp_heavy_size * 2) for (auto iEdge = 0ul; iEdge < edge_ptr.nEdge; ++iEdge) { - auto bij = &matrix[edge_ptr(iEdge,0)*nVar*nVar]; - auto bji = &matrix[edge_ptr(iEdge,1)*nVar*nVar]; + auto bij = &matrix[edge_ptr(iEdge, 0) * nVar * nVar]; + auto bji = &matrix[edge_ptr(iEdge, 1) * nVar * nVar]; swapAndTransp(nVar, bij, bji); } END_SU2_OMP_FOR - } - else if (col_ptr) { + } else if (col_ptr) { /*--- If the column pointer was built. ---*/ SU2_OMP_FOR_DYN(omp_heavy_size) for (auto iPoint = 0ul; iPoint < nPoint; ++iPoint) { for (auto k = row_ptr[iPoint]; k < dia_ptr[iPoint]; ++k) { - auto bij = &matrix[k*nVar*nVar]; - auto bji = &matrix[col_ptr[k]*nVar*nVar]; + auto bij = &matrix[k * nVar * nVar]; + auto bji = &matrix[col_ptr[k] * nVar * nVar]; swapAndTransp(nVar, bij, bji); } } END_SU2_OMP_FOR - } - else { + } else { /*--- Slow fallback, needs to search for ji. ---*/ SU2_OMP_FOR_DYN(omp_heavy_size) for (auto iPoint = 0ul; iPoint < nPoint; ++iPoint) { - for (auto k = dia_ptr[iPoint]+1ul; k < row_ptr[iPoint+1]; ++k) { + for (auto k = dia_ptr[iPoint] + 1ul; k < row_ptr[iPoint + 1]; ++k) { const auto jPoint = col_ind[k]; - auto bij = &matrix[k*nVar*nVar]; - auto bji = GetBlock(jPoint,iPoint); + auto bij = &matrix[k * nVar * nVar]; + auto bji = GetBlock(jPoint, iPoint); assert(bji && "Pattern is not symmetric."); swapAndTransp(nVar, bij, bji); @@ -1223,10 +1137,9 @@ void CSysMatrix::TransposeInPlace() { SU2_OMP_FOR_STAT(omp_heavy_size) for (auto iPoint = 0ul; iPoint < nPoint; ++iPoint) { - auto bii = &matrix[dia_ptr[iPoint]*nVar*nVar]; - for (auto i=0ul; i::TransposeInPlace() { #endif } -template +template void CSysMatrix::MatrixMatrixAddition(ScalarType alpha, const CSysMatrix& B) { - /*--- Check that the sparse structure is shared between the two matrices, * comparing pointers is ok as they are obtained from CGeometry. ---*/ - bool ok = (row_ptr == B.row_ptr) && (col_ind == B.col_ind) && - (nVar == B.nVar) && (nEqn == B.nEqn) && (nnz == B.nnz); + bool ok = (row_ptr == B.row_ptr) && (col_ind == B.col_ind) && (nVar == B.nVar) && (nEqn == B.nEqn) && (nnz == B.nnz); if (!ok) { SU2_MPI::Error("Matrices do not have compatible sparsity.", CURRENT_FUNCTION); } SU2_OMP_FOR_STAT(omp_light_size) - for (auto i = 0ul; i < nnz*nVar*nEqn; ++i) - matrix[i] += alpha*B.matrix[i]; + for (auto i = 0ul; i < nnz * nVar * nEqn; ++i) matrix[i] += alpha * B.matrix[i]; END_SU2_OMP_FOR - } -template -void CSysMatrix::BuildPastixPreconditioner(CGeometry *geometry, const CConfig *config, +template +void CSysMatrix::BuildPastixPreconditioner(CGeometry* geometry, const CConfig* config, unsigned short kind_fact) { #ifdef HAVE_PASTIX /*--- Pastix will launch nested threads. ---*/ - BEGIN_SU2_OMP_SAFE_GLOBAL_ACCESS - { - pastix_wrapper.SetMatrix(nVar,nPoint,nPointDomain,row_ptr,col_ind,matrix); + BEGIN_SU2_OMP_SAFE_GLOBAL_ACCESS { + pastix_wrapper.SetMatrix(nVar, nPoint, nPointDomain, row_ptr, col_ind, matrix); pastix_wrapper.Factorize(geometry, config, kind_fact); } END_SU2_OMP_SAFE_GLOBAL_ACCESS @@ -1272,11 +1180,12 @@ void CSysMatrix::BuildPastixPreconditioner(CGeometry *geometry, cons #endif } -template -void CSysMatrix::ComputePastixPreconditioner(const CSysVector & vec, CSysVector & prod, - CGeometry *geometry, const CConfig *config) const { +template +void CSysMatrix::ComputePastixPreconditioner(const CSysVector& vec, + CSysVector& prod, CGeometry* geometry, + const CConfig* config) const { #ifdef HAVE_PASTIX - SU2_OMP_SAFE_GLOBAL_ACCESS(pastix_wrapper.Solve(vec,prod);) + SU2_OMP_SAFE_GLOBAL_ACCESS(pastix_wrapper.Solve(vec, prod);) CSysMatrixComms::Initiate(prod, geometry, config); CSysMatrixComms::Complete(prod, geometry, config); @@ -1287,15 +1196,16 @@ void CSysMatrix::ComputePastixPreconditioner(const CSysVector(const CSysVector&, CGeometry*, const CConfig*, unsigned short);\ -template void CSysMatrixComms::Complete(CSysVector&, CGeometry*, const CConfig*, unsigned short); +#define INSTANTIATE_COMMS(TYPE) \ + template void CSysMatrixComms::Initiate(const CSysVector&, CGeometry*, const CConfig*, unsigned short); \ + template void CSysMatrixComms::Complete(CSysVector&, CGeometry*, const CConfig*, unsigned short); -#define INSTANTIATE_MATRIX(TYPE)\ -template class CSysMatrix;\ -template void CSysMatrix::EnforceSolutionAtNode(unsigned long, const su2double*, CSysVector&);\ -template void CSysMatrix::EnforceSolutionAtDOF(unsigned long, unsigned long, su2double, CSysVector&);\ -INSTANTIATE_COMMS(TYPE) +#define INSTANTIATE_MATRIX(TYPE) \ + template class CSysMatrix; \ + template void CSysMatrix::EnforceSolutionAtNode(unsigned long, const su2double*, CSysVector&); \ + template void CSysMatrix::EnforceSolutionAtDOF(unsigned long, unsigned long, su2double, \ + CSysVector&); \ + INSTANTIATE_COMMS(TYPE) #ifdef CODI_FORWARD_TYPE /*--- In forward AD only the active type is used. ---*/ @@ -1310,4 +1220,4 @@ INSTANTIATE_MATRIX(passivedouble) #ifdef CODI_REVERSE_TYPE INSTANTIATE_COMMS(su2double) #endif -#endif // CODI_FORWARD_TYPE +#endif // CODI_FORWARD_TYPE diff --git a/Common/src/linear_algebra/CSysSolve.cpp b/Common/src/linear_algebra/CSysSolve.cpp index 691ae822918..fdebc018574 100644 --- a/Common/src/linear_algebra/CSysSolve.cpp +++ b/Common/src/linear_algebra/CSysSolve.cpp @@ -41,80 +41,76 @@ * decide if the linear system is already solved. */ namespace { - template - constexpr T linSolEpsilon() { return numeric_limits::epsilon(); } - template<> - constexpr float linSolEpsilon() { return 1e-12; } +template +constexpr T linSolEpsilon() { + return numeric_limits::epsilon(); } - -template -CSysSolve::CSysSolve(LINEAR_SOLVER_MODE linear_solver_mode) : - eps(linSolEpsilon()), - lin_sol_mode(linear_solver_mode), - cg_ready(false), - bcg_ready(false), - smooth_ready(false), - LinSysSol_ptr(nullptr), - LinSysRes_ptr(nullptr) { +template <> +constexpr float linSolEpsilon() { + return 1e-12; } - -template -void CSysSolve::ApplyGivens(ScalarType s, ScalarType c, ScalarType & h1, ScalarType & h2) const { - - ScalarType temp = c*h1 + s*h2; - h2 = c*h2 - s*h1; +} // namespace + +template +CSysSolve::CSysSolve(LINEAR_SOLVER_MODE linear_solver_mode) + : eps(linSolEpsilon()), + lin_sol_mode(linear_solver_mode), + cg_ready(false), + bcg_ready(false), + smooth_ready(false), + LinSysSol_ptr(nullptr), + LinSysRes_ptr(nullptr) {} + +template +void CSysSolve::ApplyGivens(ScalarType s, ScalarType c, ScalarType& h1, ScalarType& h2) const { + ScalarType temp = c * h1 + s * h2; + h2 = c * h2 - s * h1; h1 = temp; } -template -void CSysSolve::GenerateGivens(ScalarType & dx, ScalarType & dy, ScalarType & s, ScalarType & c) const { - - if ( (dx == 0.0) && (dy == 0.0) ) { +template +void CSysSolve::GenerateGivens(ScalarType& dx, ScalarType& dy, ScalarType& s, ScalarType& c) const { + if ((dx == 0.0) && (dy == 0.0)) { c = 1.0; s = 0.0; - } - else if ( fabs(dy) > fabs(dx) ) { - ScalarType tmp = dx/dy; - dx = sqrt(1.0 + tmp*tmp); - s = Sign(1.0/dx, dy); - c = tmp*s; - } - else if ( fabs(dy) <= fabs(dx) ) { - ScalarType tmp = dy/dx; - dy = sqrt(1.0 + tmp*tmp); - c = Sign(1.0/dy, dx); - s = tmp*c; - } - else { + } else if (fabs(dy) > fabs(dx)) { + ScalarType tmp = dx / dy; + dx = sqrt(1.0 + tmp * tmp); + s = Sign(1.0 / dx, dy); + c = tmp * s; + } else if (fabs(dy) <= fabs(dx)) { + ScalarType tmp = dy / dx; + dy = sqrt(1.0 + tmp * tmp); + c = Sign(1.0 / dy, dx); + s = tmp * c; + } else { // dx and/or dy must be invalid dx = 0.0; dy = 0.0; c = 1.0; s = 0.0; } - dx = fabs(dx*dy); + dx = fabs(dx * dy); dy = 0.0; } -template -void CSysSolve::SolveReduced(int n, const su2matrix& Hsbg, - const su2vector& rhs, su2vector& x) const { +template +void CSysSolve::SolveReduced(int n, const su2matrix& Hsbg, const su2vector& rhs, + su2vector& x) const { // initialize... - for (int i = 0; i < n; i++) - x[i] = rhs[i]; + for (int i = 0; i < n; i++) x[i] = rhs[i]; // ... and backsolve - for (int i = n-1; i >= 0; i--) { - x[i] /= Hsbg(i,i); - for (int j = i-1; j >= 0; j--) { - x[j] -= Hsbg(j,i)*x[i]; + for (int i = n - 1; i >= 0; i--) { + x[i] /= Hsbg(i, i); + for (int j = i - 1; j >= 0; j--) { + x[j] -= Hsbg(j, i) * x[i]; } } } -template +template void CSysSolve::ModGramSchmidt(int i, su2matrix& Hsbg, vector >& w) const { - /*--- Parameter for reorthonormalization ---*/ const ScalarType reorth = 0.98; @@ -122,8 +118,8 @@ void CSysSolve::ModGramSchmidt(int i, su2matrix& Hsbg, /*--- Get the norm of the vector being orthogonalized, and find the threshold for re-orthogonalization ---*/ - ScalarType nrm = w[i+1].squaredNorm(); - ScalarType thr = nrm*reorth; + ScalarType nrm = w[i + 1].squaredNorm(); + ScalarType thr = nrm * reorth; /*--- The norm of w[i+1] < 0.0 or w[i+1] = NaN ---*/ @@ -134,72 +130,68 @@ void CSysSolve::ModGramSchmidt(int i, su2matrix& Hsbg, /*--- Begin main Gram-Schmidt loop ---*/ - for (int k = 0; k < i+1; k++) { - ScalarType prod = w[i+1].dot(w[k]); - Hsbg(k,i) = prod; - w[i+1] -= prod * w[k]; + for (int k = 0; k < i + 1; k++) { + ScalarType prod = w[i + 1].dot(w[k]); + Hsbg(k, i) = prod; + w[i + 1] -= prod * w[k]; /*--- Check if reorthogonalization is necessary ---*/ - if (prod*prod > thr) { - prod = w[i+1].dot(w[k]); - Hsbg(k,i) += prod; - w[i+1] -= prod * w[k]; + if (prod * prod > thr) { + prod = w[i + 1].dot(w[k]); + Hsbg(k, i) += prod; + w[i + 1] -= prod * w[k]; } /*--- Update the norm and check its size ---*/ - nrm -= pow(Hsbg(k,i),2); + nrm -= pow(Hsbg(k, i), 2); nrm = max(nrm, 0.0); - thr = nrm*reorth; + thr = nrm * reorth; } /*--- Test the resulting vector ---*/ - nrm = w[i+1].norm(); - Hsbg(i+1,i) = nrm; + nrm = w[i + 1].norm(); + Hsbg(i + 1, i) = nrm; /*--- Scale the resulting vector ---*/ - w[i+1] /= nrm; - + w[i + 1] /= nrm; } -template +template void CSysSolve::WriteHeader(string solver, ScalarType restol, ScalarType resinit) const { - cout << "\n# " << solver << " residual history\n"; cout << "# Residual tolerance target = " << restol << "\n"; cout << "# Initial residual norm = " << resinit << endl; } -template +template void CSysSolve::WriteHistory(unsigned long iter, ScalarType res) const { - cout << " " << iter << " " << res << endl; } -template +template void CSysSolve::WriteFinalResidual(string solver, unsigned long iter, ScalarType res) const { - cout << "# " << solver << " final (true) residual:\n"; cout << "# Iteration = " << iter << ": |res|/|res0| = " << res << ".\n" << endl; } -template +template void CSysSolve::WriteWarning(ScalarType res_calc, ScalarType res_true, ScalarType tol) const { - cout << "# WARNING:\n"; cout << "# true residual norm and calculated residual norm do not agree.\n"; - cout << "# true_res = " << res_true << ", calc_res = " << res_calc << ", tol = " << tol*10 << ".\n"; + cout << "# true_res = " << res_true << ", calc_res = " << res_calc << ", tol = " << tol * 10 << ".\n"; cout << "# true_res - calc_res = " << res_true - res_calc << endl; } -template -unsigned long CSysSolve::CG_LinSolver(const CSysVector & b, CSysVector & x, - const CMatrixVectorProduct & mat_vec, const CPreconditioner & precond, - ScalarType tol, unsigned long m, ScalarType & residual, bool monitoring, const CConfig *config) const { - +template +unsigned long CSysSolve::CG_LinSolver(const CSysVector& b, CSysVector& x, + const CMatrixVectorProduct& mat_vec, + const CPreconditioner& precond, ScalarType tol, + unsigned long m, ScalarType& residual, bool monitoring, + const CConfig* config) const { const bool master = (SU2_MPI::GetRank() == MASTER_NODE) && (omp_get_thread_num() == 0); ScalarType norm_r = 0.0, norm0 = 0.0; unsigned long i = 0; @@ -214,8 +206,7 @@ unsigned long CSysSolve::CG_LinSolver(const CSysVector & * do this since the working vectors are shared. ---*/ if (!cg_ready) { - BEGIN_SU2_OMP_SAFE_GLOBAL_ACCESS - { + BEGIN_SU2_OMP_SAFE_GLOBAL_ACCESS { auto nVar = b.GetNVar(); auto nBlk = b.GetNBlk(); auto nBlkDomain = b.GetNBlkDomain(); @@ -242,16 +233,16 @@ unsigned long CSysSolve::CG_LinSolver(const CSysVector & /*--- Only compute the residuals in full communication mode. ---*/ if (config->GetComm_Level() == COMM_FULL) { - norm_r = r.norm(); - norm0 = b.norm(); + norm0 = b.norm(); /*--- Set the norm to the initial initial residual value ---*/ if (tol_type == LinearToleranceType::RELATIVE) norm0 = norm_r; - if ((norm_r < tol*norm0) || (norm_r < eps)) { - if (master && (lin_sol_mode!=LINEAR_SOLVER_MODE::MESH_DEFORM)) cout << "CSysSolve::ConjugateGradient(): system solved by initial guess." << endl; + if ((norm_r < tol * norm0) || (norm_r < eps)) { + if (master && (lin_sol_mode != LINEAR_SOLVER_MODE::MESH_DEFORM)) + cout << "CSysSolve::ConjugateGradient(): system solved by initial guess." << endl; return 0; } @@ -259,9 +250,8 @@ unsigned long CSysSolve::CG_LinSolver(const CSysVector & if (monitoring && master) { WriteHeader("CG", tol, norm_r); - WriteHistory(i, norm_r/norm0); + WriteHistory(i, norm_r / norm0); } - } precond(r, z); @@ -271,7 +261,6 @@ unsigned long CSysSolve::CG_LinSolver(const CSysVector & /*--- Loop over all search directions ---*/ for (i = 0; i < m; i++) { - /*--- Apply matrix to p to build Krylov subspace ---*/ mat_vec(p, A_x); @@ -288,14 +277,11 @@ unsigned long CSysSolve::CG_LinSolver(const CSysVector & /*--- Only compute the residuals in full communication mode. ---*/ if (config->GetComm_Level() == COMM_FULL) { - /*--- Check if solution has converged, else output the relative residual if necessary ---*/ norm_r = r.norm(); - if (norm_r < tol*norm0) break; - if (((monitoring) && (master)) && ((i+1) % monitorFreq == 0)) - WriteHistory(i+1, norm_r/norm0); - + if (norm_r < tol * norm0) break; + if (((monitoring) && (master)) && ((i + 1) % monitorFreq == 0)) WriteHistory(i + 1, norm_r / norm0); } precond(r, z); @@ -308,22 +294,20 @@ unsigned long CSysSolve::CG_LinSolver(const CSysVector & /*--- Gram-Schmidt orthogonalization. ---*/ - p = beta*p + z; - + p = beta * p + z; } /*--- Recalculate final residual (this should be optional) ---*/ if ((monitoring) && (config->GetComm_Level() == COMM_FULL)) { - - if (master) WriteFinalResidual("CG", i, norm_r/norm0); + if (master) WriteFinalResidual("CG", i, norm_r / norm0); if (recomputeRes) { mat_vec(x, A_x); r = b - A_x; ScalarType true_res = r.norm(); - if (fabs(true_res - norm_r) > tol*10.0) { + if (fabs(true_res - norm_r) > tol * 10.0) { if (master) { WriteWarning(norm_r, true_res, tol); } @@ -331,16 +315,16 @@ unsigned long CSysSolve::CG_LinSolver(const CSysVector & } } - residual = norm_r/norm0; + residual = norm_r / norm0; return i; - } -template -unsigned long CSysSolve::FGMRES_LinSolver(const CSysVector & b, CSysVector & x, - const CMatrixVectorProduct & mat_vec, const CPreconditioner & precond, - ScalarType tol, unsigned long m, ScalarType & residual, bool monitoring, const CConfig *config) const { - +template +unsigned long CSysSolve::FGMRES_LinSolver(const CSysVector& b, CSysVector& x, + const CMatrixVectorProduct& mat_vec, + const CPreconditioner& precond, ScalarType tol, + unsigned long m, ScalarType& residual, bool monitoring, + const CConfig* config) const { const bool master = (SU2_MPI::GetRank() == MASTER_NODE) && (omp_get_thread_num() == 0); const bool flexible = !precond.IsIdentity(); @@ -357,12 +341,11 @@ unsigned long CSysSolve::FGMRES_LinSolver(const CSysVector::FGMRES_LinSolver(const CSysVector g(m+1), sn(m+1), cs(m+1), y(m); + su2vector g(m + 1), sn(m + 1), cs(m + 1), y(m); g = ScalarType(0); sn = ScalarType(0); cs = ScalarType(0); y = ScalarType(0); - su2matrix H(m+1, m); + su2matrix H(m + 1, m); H = ScalarType(0); /*--- Calculate the norm of the rhs vector. ---*/ @@ -390,8 +373,7 @@ unsigned long CSysSolve::FGMRES_LinSolver(const CSysVector::FGMRES_LinSolver(const CSysVector::FGMRES_LinSolver(const CSysVector::FGMRES_LinSolver(const CSysVector::FGMRES_LinSolver(const CSysVector::FGMRES_LinSolver(const CSysVectorGetComm_Level() == COMM_FULL)) { - - if (master) WriteFinalResidual("FGMRES", i, beta/norm0); + if (master) WriteFinalResidual("FGMRES", i, beta / norm0); if (recomputeRes) { mat_vec(x, W[0]); W[0] -= b; ScalarType res = W[0].norm(); - if (fabs(res - beta) > tol*10) { + if (fabs(res - beta) > tol * 10) { if (master) { WriteWarning(beta, res, tol); } @@ -499,16 +475,16 @@ unsigned long CSysSolve::FGMRES_LinSolver(const CSysVector -unsigned long CSysSolve::RFGMRES_LinSolver(const CSysVector & b, CSysVector & x, - const CMatrixVectorProduct & mat_vec, const CPreconditioner & precond, - ScalarType tol, unsigned long MaxIter, ScalarType & residual, bool monitoring, const CConfig *config) { - +template +unsigned long CSysSolve::RFGMRES_LinSolver(const CSysVector& b, CSysVector& x, + const CMatrixVectorProduct& mat_vec, + const CPreconditioner& precond, ScalarType tol, + unsigned long MaxIter, ScalarType& residual, bool monitoring, + const CConfig* config) { const auto restartIter = config->GetLinear_Solver_Restart_Frequency(); SU2_OMP_MASTER { @@ -517,23 +493,24 @@ unsigned long CSysSolve::RFGMRES_LinSolver(const CSysVector -unsigned long CSysSolve::BCGSTAB_LinSolver(const CSysVector & b, CSysVector & x, - const CMatrixVectorProduct & mat_vec, const CPreconditioner & precond, - ScalarType tol, unsigned long m, ScalarType & residual, bool monitoring, const CConfig *config) const { - +template +unsigned long CSysSolve::BCGSTAB_LinSolver(const CSysVector& b, CSysVector& x, + const CMatrixVectorProduct& mat_vec, + const CPreconditioner& precond, ScalarType tol, + unsigned long m, ScalarType& residual, bool monitoring, + const CConfig* config) const { const bool master = (SU2_MPI::GetRank() == MASTER_NODE) && (omp_get_thread_num() == 0); ScalarType norm_r = 0.0, norm0 = 0.0; unsigned long i = 0; @@ -547,8 +524,7 @@ unsigned long CSysSolve::BCGSTAB_LinSolver(const CSysVector::BCGSTAB_LinSolver(const CSysVectorGetComm_Level() == COMM_FULL) { - norm_r = r.norm(); - norm0 = b.norm(); + norm0 = b.norm(); /*--- Set the norm to the initial initial residual value ---*/ if (tol_type == LinearToleranceType::RELATIVE) norm0 = norm_r; - if ((norm_r < tol*norm0) || (norm_r < eps)) { + if ((norm_r < tol * norm0) || (norm_r < eps)) { if (master) cout << "CSysSolve::BCGSTAB(): system solved by initial guess." << endl; return 0; } @@ -594,20 +569,20 @@ unsigned long CSysSolve::BCGSTAB_LinSolver(const CSysVector::BCGSTAB_LinSolver(const CSysVector::BCGSTAB_LinSolver(const CSysVectorGetComm_Level() == COMM_FULL) { - /*--- Check if solution has converged, else output the relative residual if necessary ---*/ norm_r = r.norm(); - if (norm_r < tol*norm0) break; - if (((monitoring) && (master)) && ((i+1) % monitorFreq == 0) && (master)) - WriteHistory(i+1, norm_r/norm0); - + if (norm_r < tol * norm0) break; + if (((monitoring) && (master)) && ((i + 1) % monitorFreq == 0) && (master)) WriteHistory(i + 1, norm_r / norm0); } - } /*--- Recalculate final residual (this should be optional) ---*/ if ((monitoring) && (config->GetComm_Level() == COMM_FULL)) { - - if (master) WriteFinalResidual("BCGSTAB", i, norm_r/norm0); + if (master) WriteFinalResidual("BCGSTAB", i, norm_r / norm0); if (recomputeRes) { mat_vec(x, A_x); r = b - A_x; ScalarType true_res = r.norm(); - if ((fabs(true_res - norm_r) > tol*10.0) && (master)) { + if ((fabs(true_res - norm_r) > tol * 10.0) && (master)) { WriteWarning(norm_r, true_res, tol); } } } - residual = norm_r/norm0; + residual = norm_r / norm0; return i; } -template -unsigned long CSysSolve::Smoother_LinSolver(const CSysVector & b, CSysVector & x, - const CMatrixVectorProduct & mat_vec, const CPreconditioner & precond, - ScalarType tol, unsigned long m, ScalarType & residual, bool monitoring, const CConfig *config) const { - +template +unsigned long CSysSolve::Smoother_LinSolver(const CSysVector& b, CSysVector& x, + const CMatrixVectorProduct& mat_vec, + const CPreconditioner& precond, ScalarType tol, + unsigned long m, ScalarType& residual, bool monitoring, + const CConfig* config) const { const bool master = (SU2_MPI::GetRank() == MASTER_NODE) && (omp_get_thread_num() == 0); const bool fix_iter_mode = tol < eps; ScalarType norm_r = 0.0, norm0 = 0.0; @@ -712,8 +683,7 @@ unsigned long CSysSolve::Smoother_LinSolver(const CSysVector::Smoother_LinSolver(const CSysVectorGetComm_Level() == COMM_FULL) { - norm_r = r.norm(); - norm0 = b.norm(); + norm0 = b.norm(); /*--- Set the norm to the initial initial residual value ---*/ if (tol_type == LinearToleranceType::RELATIVE) norm0 = norm_r; - if ( (norm_r < tol*norm0) || (norm_r < eps) ) { + if ((norm_r < tol * norm0) || (norm_r < eps)) { if (master) cout << "CSysSolve::Smoother_LinSolver(): system solved by initial guess." << endl; return 0; } @@ -756,15 +725,13 @@ unsigned long CSysSolve::Smoother_LinSolver(const CSysVector::Smoother_LinSolver(const CSysVectorGetComm_Level() == COMM_FULL) { norm_r = r.norm(); - if (norm_r < tol*norm0) break; - if (((monitoring) && (master)) && ((i+1) % monitorFreq == 0)) - WriteHistory(i+1, norm_r/norm0); + if (norm_r < tol * norm0) break; + if (((monitoring) && (master)) && ((i + 1) % monitorFreq == 0)) WriteHistory(i + 1, norm_r / norm0); } } if (fix_iter_mode) norm_r = r.norm(); if ((monitoring) && (master) && (config->GetComm_Level() == COMM_FULL)) { - WriteFinalResidual("Smoother", i, norm_r/norm0); + WriteFinalResidual("Smoother", i, norm_r / norm0); } - residual = norm_r/norm0; + residual = norm_r / norm0; return i; } -template -unsigned long CSysSolve::Solve(CSysMatrix & Jacobian, const CSysVector & LinSysRes, - CSysVector & LinSysSol, CGeometry *geometry, const CConfig *config) { +template +unsigned long CSysSolve::Solve(CSysMatrix& Jacobian, const CSysVector& LinSysRes, + CSysVector& LinSysSol, CGeometry* geometry, + const CConfig* config) { /*--- A word about the templated types. It is assumed that the residual and solution vectors are always of su2doubles, meaning that they are active in the discrete adjoint. The same assumption is made in SetExternalSolve. @@ -828,31 +795,32 @@ unsigned long CSysSolve::Solve(CSysMatrix & Jacobian, co switch (lin_sol_mode) { /*--- Mesh Deformation mode ---*/ case LINEAR_SOLVER_MODE::MESH_DEFORM: { - KindSolver = config->GetKind_Deform_Linear_Solver(); - KindPrecond = config->GetKind_Deform_Linear_Solver_Prec(); - MaxIter = config->GetDeform_Linear_Solver_Iter(); - SolverTol = SU2_TYPE::GetValue(config->GetDeform_Linear_Solver_Error()); + KindSolver = config->GetKind_Deform_Linear_Solver(); + KindPrecond = config->GetKind_Deform_Linear_Solver_Prec(); + MaxIter = config->GetDeform_Linear_Solver_Iter(); + SolverTol = SU2_TYPE::GetValue(config->GetDeform_Linear_Solver_Error()); ScreenOutput = config->GetDeform_Output(); break; } /*--- Gradient Smoothing mode ---*/ case LINEAR_SOLVER_MODE::GRADIENT_MODE: { - KindSolver = config->GetKind_Grad_Linear_Solver(); - KindPrecond = config->GetKind_Grad_Linear_Solver_Prec(); - MaxIter = config->GetGrad_Linear_Solver_Iter(); - SolverTol = SU2_TYPE::GetValue(config->GetGrad_Linear_Solver_Error()); + KindSolver = config->GetKind_Grad_Linear_Solver(); + KindPrecond = config->GetKind_Grad_Linear_Solver_Prec(); + MaxIter = config->GetGrad_Linear_Solver_Iter(); + SolverTol = SU2_TYPE::GetValue(config->GetGrad_Linear_Solver_Error()); ScreenOutput = true; break; } /*--- Normal mode - * assumes that 'lin_sol_mode==LINEAR_SOLVER_MODE::STANDARD', but does not enforce it to avoid compiler warning. ---*/ + * assumes that 'lin_sol_mode==LINEAR_SOLVER_MODE::STANDARD', but does not enforce it to avoid compiler warning. + * ---*/ default: { - KindSolver = config->GetKind_Linear_Solver(); - KindPrecond = config->GetKind_Linear_Solver_Prec(); - MaxIter = config->GetLinear_Solver_Iter(); - SolverTol = SU2_TYPE::GetValue(config->GetLinear_Solver_Error()); + KindSolver = config->GetKind_Linear_Solver(); + KindPrecond = config->GetKind_Linear_Solver_Prec(); + MaxIter = config->GetLinear_Solver_Iter(); + SolverTol = SU2_TYPE::GetValue(config->GetLinear_Solver_Error()); ScreenOutput = false; break; } @@ -905,32 +873,37 @@ unsigned long CSysSolve::Solve(CSysMatrix & Jacobian, co switch (KindSolver) { case BCGSTAB: - IterLinSol = BCGSTAB_LinSolver(*LinSysRes_ptr, *LinSysSol_ptr, mat_vec, *precond, SolverTol, MaxIter, residual, ScreenOutput, config); + IterLinSol = BCGSTAB_LinSolver(*LinSysRes_ptr, *LinSysSol_ptr, mat_vec, *precond, SolverTol, MaxIter, residual, + ScreenOutput, config); break; case FGMRES: - IterLinSol = FGMRES_LinSolver(*LinSysRes_ptr, *LinSysSol_ptr, mat_vec, *precond, SolverTol, MaxIter, residual, ScreenOutput, config); + IterLinSol = FGMRES_LinSolver(*LinSysRes_ptr, *LinSysSol_ptr, mat_vec, *precond, SolverTol, MaxIter, residual, + ScreenOutput, config); break; case RESTARTED_FGMRES: - IterLinSol = RFGMRES_LinSolver(*LinSysRes_ptr, *LinSysSol_ptr, mat_vec, *precond, SolverTol, MaxIter, residual, ScreenOutput, config); + IterLinSol = RFGMRES_LinSolver(*LinSysRes_ptr, *LinSysSol_ptr, mat_vec, *precond, SolverTol, MaxIter, residual, + ScreenOutput, config); break; case CONJUGATE_GRADIENT: - IterLinSol = CG_LinSolver(*LinSysRes_ptr, *LinSysSol_ptr, mat_vec, *precond, SolverTol, MaxIter, residual, ScreenOutput, config); + IterLinSol = CG_LinSolver(*LinSysRes_ptr, *LinSysSol_ptr, mat_vec, *precond, SolverTol, MaxIter, residual, + ScreenOutput, config); break; case SMOOTHER: - IterLinSol = Smoother_LinSolver(*LinSysRes_ptr, *LinSysSol_ptr, mat_vec, *precond, SolverTol, MaxIter, residual, ScreenOutput, config); + IterLinSol = Smoother_LinSolver(*LinSysRes_ptr, *LinSysSol_ptr, mat_vec, *precond, SolverTol, MaxIter, residual, + ScreenOutput, config); break; - case PASTIX_LDLT : case PASTIX_LU: + case PASTIX_LDLT: + case PASTIX_LU: Jacobian.BuildPastixPreconditioner(geometry, config, KindSolver); Jacobian.ComputePastixPreconditioner(*LinSysRes_ptr, *LinSysSol_ptr, geometry, config); IterLinSol = 1; residual = 1e-20; break; default: - SU2_MPI::Error("Unknown type of linear solver.",CURRENT_FUNCTION); + SU2_MPI::Error("Unknown type of linear solver.", CURRENT_FUNCTION); } - SU2_OMP_MASTER - { + SU2_OMP_MASTER { Residual = residual; Iterations = IterLinSol; } @@ -940,20 +913,23 @@ unsigned long CSysSolve::Solve(CSysMatrix & Jacobian, co delete precond; - if(TapeActive) { - + if (TapeActive) { /*--- To keep the behavior of SU2_DOT, but not strictly required since jacobian is symmetric(?). ---*/ - const bool RequiresTranspose = ((lin_sol_mode!=LINEAR_SOLVER_MODE::MESH_DEFORM) || (config->GetKind_SU2() == SU2_COMPONENT::SU2_DOT)); + const bool RequiresTranspose = + ((lin_sol_mode != LINEAR_SOLVER_MODE::MESH_DEFORM) || (config->GetKind_SU2() == SU2_COMPONENT::SU2_DOT)); - if (lin_sol_mode==LINEAR_SOLVER_MODE::MESH_DEFORM) KindPrecond = config->GetKind_Deform_Linear_Solver_Prec(); - else if (lin_sol_mode==LINEAR_SOLVER_MODE::GRADIENT_MODE) KindPrecond = config->GetKind_Grad_Linear_Solver_Prec(); - else KindPrecond = config->GetKind_DiscAdj_Linear_Prec(); + if (lin_sol_mode == LINEAR_SOLVER_MODE::MESH_DEFORM) + KindPrecond = config->GetKind_Deform_Linear_Solver_Prec(); + else if (lin_sol_mode == LINEAR_SOLVER_MODE::GRADIENT_MODE) + KindPrecond = config->GetKind_Grad_Linear_Solver_Prec(); + else + KindPrecond = config->GetKind_DiscAdj_Linear_Prec(); /*--- Build preconditioner for the transposed Jacobian ---*/ if (RequiresTranspose) Jacobian.TransposeInPlace(); - switch(KindPrecond) { + switch (KindPrecond) { case ILU: if (RequiresTranspose) Jacobian.BuildILUPreconditioner(); break; @@ -964,11 +940,14 @@ unsigned long CSysSolve::Solve(CSysMatrix & Jacobian, co case LU_SGS: /*--- Nothing to build. ---*/ break; - case PASTIX_ILU: case PASTIX_LU_P: case PASTIX_LDLT_P: + case PASTIX_ILU: + case PASTIX_LU_P: + case PASTIX_LDLT_P: /*--- It was already built. ---*/ break; default: - SU2_MPI::Error("The specified preconditioner is not yet implemented for the discrete adjoint method.", CURRENT_FUNCTION); + SU2_MPI::Error("The specified preconditioner is not yet implemented for the discrete adjoint method.", + CURRENT_FUNCTION); break; } } @@ -987,11 +966,10 @@ unsigned long CSysSolve::Solve(CSysMatrix & Jacobian, co return IterLinSol; } -template -unsigned long CSysSolve::Solve_b(CSysMatrix & Jacobian, const CSysVector & LinSysRes, - CSysVector & LinSysSol, CGeometry *geometry, const CConfig *config, - const bool directCall) { - +template +unsigned long CSysSolve::Solve_b(CSysMatrix& Jacobian, const CSysVector& LinSysRes, + CSysVector& LinSysSol, CGeometry* geometry, + const CConfig* config, const bool directCall) { unsigned short KindSolver, KindPrecond; unsigned long MaxIter, IterLinSol = 0; ScalarType SolverTol; @@ -1000,31 +978,32 @@ unsigned long CSysSolve::Solve_b(CSysMatrix & Jacobian, switch (lin_sol_mode) { /*--- Mesh Deformation mode ---*/ case LINEAR_SOLVER_MODE::MESH_DEFORM: { - KindSolver = config->GetKind_Deform_Linear_Solver(); - KindPrecond = config->GetKind_Deform_Linear_Solver_Prec(); - MaxIter = config->GetDeform_Linear_Solver_Iter(); - SolverTol = SU2_TYPE::GetValue(config->GetDeform_Linear_Solver_Error()); + KindSolver = config->GetKind_Deform_Linear_Solver(); + KindPrecond = config->GetKind_Deform_Linear_Solver_Prec(); + MaxIter = config->GetDeform_Linear_Solver_Iter(); + SolverTol = SU2_TYPE::GetValue(config->GetDeform_Linear_Solver_Error()); ScreenOutput = config->GetDeform_Output(); break; } /*--- Gradient Smoothing mode ---*/ case LINEAR_SOLVER_MODE::GRADIENT_MODE: { - KindSolver = config->GetKind_Grad_Linear_Solver(); - KindPrecond = config->GetKind_Grad_Linear_Solver_Prec(); - MaxIter = config->GetGrad_Linear_Solver_Iter(); - SolverTol = SU2_TYPE::GetValue(config->GetGrad_Linear_Solver_Error()); + KindSolver = config->GetKind_Grad_Linear_Solver(); + KindPrecond = config->GetKind_Grad_Linear_Solver_Prec(); + MaxIter = config->GetGrad_Linear_Solver_Iter(); + SolverTol = SU2_TYPE::GetValue(config->GetGrad_Linear_Solver_Error()); ScreenOutput = true; break; } /*--- Normal mode - * assumes that 'lin_sol_mode==LINEAR_SOLVER_MODE::STANDARD', but does not enforce it to avoid compiler warning. ---*/ + * assumes that 'lin_sol_mode==LINEAR_SOLVER_MODE::STANDARD', but does not enforce it to avoid compiler warning. + * ---*/ default: { - KindSolver = config->GetKind_Linear_Solver(); - KindPrecond = config->GetKind_Linear_Solver_Prec(); - MaxIter = config->GetLinear_Solver_Iter(); - SolverTol = SU2_TYPE::GetValue(config->GetLinear_Solver_Error()); + KindSolver = config->GetKind_Linear_Solver(); + KindPrecond = config->GetKind_Linear_Solver_Prec(); + MaxIter = config->GetLinear_Solver_Iter(); + SolverTol = SU2_TYPE::GetValue(config->GetLinear_Solver_Error()); ScreenOutput = false; break; } @@ -1051,30 +1030,36 @@ unsigned long CSysSolve::Solve_b(CSysMatrix & Jacobian, HandleTemporariesIn(LinSysRes, LinSysSol); - switch(KindSolver) { + switch (KindSolver) { case FGMRES: - IterLinSol = FGMRES_LinSolver(*LinSysRes_ptr, *LinSysSol_ptr, mat_vec, *precond, SolverTol , MaxIter, residual, ScreenOutput, config); + IterLinSol = FGMRES_LinSolver(*LinSysRes_ptr, *LinSysSol_ptr, mat_vec, *precond, SolverTol, MaxIter, residual, + ScreenOutput, config); break; case RESTARTED_FGMRES: - IterLinSol = RFGMRES_LinSolver(*LinSysRes_ptr, *LinSysSol_ptr, mat_vec, *precond, SolverTol , MaxIter, residual, ScreenOutput, config); + IterLinSol = RFGMRES_LinSolver(*LinSysRes_ptr, *LinSysSol_ptr, mat_vec, *precond, SolverTol, MaxIter, residual, + ScreenOutput, config); break; case BCGSTAB: - IterLinSol = BCGSTAB_LinSolver(*LinSysRes_ptr, *LinSysSol_ptr, mat_vec, *precond, SolverTol , MaxIter, residual, ScreenOutput, config); + IterLinSol = BCGSTAB_LinSolver(*LinSysRes_ptr, *LinSysSol_ptr, mat_vec, *precond, SolverTol, MaxIter, residual, + ScreenOutput, config); break; case CONJUGATE_GRADIENT: - IterLinSol = CG_LinSolver(*LinSysRes_ptr, *LinSysSol_ptr, mat_vec, *precond, SolverTol, MaxIter, residual, ScreenOutput, config); + IterLinSol = CG_LinSolver(*LinSysRes_ptr, *LinSysSol_ptr, mat_vec, *precond, SolverTol, MaxIter, residual, + ScreenOutput, config); break; case SMOOTHER: - IterLinSol = Smoother_LinSolver(*LinSysRes_ptr, *LinSysSol_ptr, mat_vec, *precond, SolverTol, MaxIter, residual, ScreenOutput, config); + IterLinSol = Smoother_LinSolver(*LinSysRes_ptr, *LinSysSol_ptr, mat_vec, *precond, SolverTol, MaxIter, residual, + ScreenOutput, config); break; - case PASTIX_LDLT : case PASTIX_LU: + case PASTIX_LDLT: + case PASTIX_LU: if (directCall) Jacobian.BuildPastixPreconditioner(geometry, config, KindSolver); Jacobian.ComputePastixPreconditioner(*LinSysRes_ptr, *LinSysSol_ptr, geometry, config); IterLinSol = 1; residual = 1e-20; break; default: - SU2_MPI::Error("Unknown type of linear solver.",CURRENT_FUNCTION); + SU2_MPI::Error("Unknown type of linear solver.", CURRENT_FUNCTION); break; } @@ -1082,14 +1067,13 @@ unsigned long CSysSolve::Solve_b(CSysMatrix & Jacobian, delete precond; - SU2_OMP_MASTER - { + SU2_OMP_MASTER { Residual = residual; Iterations = IterLinSol; - } END_SU2_OMP_MASTER + } + END_SU2_OMP_MASTER return IterLinSol; - } /*--- Explicit instantiations ---*/ diff --git a/Common/src/linear_algebra/CSysSolve_b.cpp b/Common/src/linear_algebra/CSysSolve_b.cpp index 238542a8f5e..000b389b8a5 100644 --- a/Common/src/linear_algebra/CSysSolve_b.cpp +++ b/Common/src/linear_algebra/CSysSolve_b.cpp @@ -31,11 +31,10 @@ #include "../../include/linear_algebra/CSysVector.hpp" #ifdef CODI_REVERSE_TYPE -template +template void CSysSolve_b::Solve_b(const su2double::Real* x, su2double::Real* x_b, size_t m, const su2double::Real* y, const su2double::Real* y_b, size_t n, codi::ExternalFunctionUserData* d) { - CSysVector* LinSysRes_b = nullptr; d->getDataByIndex(LinSysRes_b, 0); @@ -57,7 +56,7 @@ void CSysSolve_b::Solve_b(const su2double::Real* x, su2double::Real* /*--- Initialize the right-hand side with the gradient of the solution of the primal linear system ---*/ SU2_OMP_BARRIER - SU2_OMP_FOR_STAT(roundUpDiv(n,omp_get_num_threads())) + SU2_OMP_FOR_STAT(roundUpDiv(n, omp_get_num_threads())) for (unsigned long i = 0; i < n; i++) { (*LinSysRes_b)[i] = y_b[i]; (*LinSysSol_b)[i] = 0.0; @@ -66,8 +65,8 @@ void CSysSolve_b::Solve_b(const su2double::Real* x, su2double::Real* solver->Solve_b(*Jacobian, *LinSysRes_b, *LinSysSol_b, geometry, config, false); - SU2_OMP_FOR_STAT(roundUpDiv(n,omp_get_num_threads())) - for (unsigned long i = 0; i < n; i ++) { + SU2_OMP_FOR_STAT(roundUpDiv(n, omp_get_num_threads())) + for (unsigned long i = 0; i < n; i++) { x_b[i] = SU2_TYPE::GetValue((*LinSysSol_b)[i]); } END_SU2_OMP_FOR diff --git a/Common/src/linear_algebra/CSysVector.cpp b/Common/src/linear_algebra/CSysVector.cpp index af335ac99f5..9a43baf070a 100644 --- a/Common/src/linear_algebra/CSysVector.cpp +++ b/Common/src/linear_algebra/CSysVector.cpp @@ -50,7 +50,7 @@ void CSysVector::Initialize(unsigned long numBlk, unsigned long numB omp_chunk_size = computeStaticChunkSize(nElm, omp_get_max_threads(), OMP_MAX_SIZE); - if (vec_val == nullptr) vec_val = MemoryAllocation::aligned_alloc(64, nElm*sizeof(ScalarType)); + if (vec_val == nullptr) vec_val = MemoryAllocation::aligned_alloc(64, nElm * sizeof(ScalarType)); if (val != nullptr) { if (!valIsArray) { diff --git a/Common/src/linear_algebra/blas_structure.cpp b/Common/src/linear_algebra/blas_structure.cpp index c23a77ecec7..5a1ec172b11 100644 --- a/Common/src/linear_algebra/blas_structure.cpp +++ b/Common/src/linear_algebra/blas_structure.cpp @@ -31,38 +31,38 @@ #include /* MKL or BLAS, if supported. */ -#if (defined (HAVE_MKL) || defined(HAVE_BLAS)) && !(defined(CODI_REVERSE_TYPE) || defined(CODI_FORWARD_TYPE)) +#if (defined(HAVE_MKL) || defined(HAVE_BLAS)) && !(defined(CODI_REVERSE_TYPE) || defined(CODI_FORWARD_TYPE)) /* Function prototypes for the BLAS routines used. */ -extern "C" void dgemm_(char*, char*, const int*, const int*, const int*, - const passivedouble*, const passivedouble*, const int*, - const passivedouble*, const int*, - const passivedouble*, passivedouble*, const int*); - -extern "C" void dgemv_(char*, const int*, const int*, const passivedouble*, - const passivedouble*, const int*, const passivedouble*, - const int*, const passivedouble*, passivedouble*, const int*); +extern "C" void dgemm_(char*, char*, const int*, const int*, const int*, const passivedouble*, const passivedouble*, + const int*, const passivedouble*, const int*, const passivedouble*, passivedouble*, const int*); + +extern "C" void dgemv_(char*, const int*, const int*, const passivedouble*, const passivedouble*, const int*, + const passivedouble*, const int*, const passivedouble*, passivedouble*, const int*); #endif /* Constructor. Initialize the const member variables, if needed. */ CBlasStructure::CBlasStructure(void) -#if !(defined(HAVE_LIBXSMM) || defined(HAVE_BLAS) || defined(HAVE_MKL)) || (defined(CODI_REVERSE_TYPE) || defined(CODI_FORWARD_TYPE)) - : mc (256), kc (128), nc (128) +#if !(defined(HAVE_LIBXSMM) || defined(HAVE_BLAS) || defined(HAVE_MKL)) || \ + (defined(CODI_REVERSE_TYPE) || defined(CODI_FORWARD_TYPE)) + : mc(256), + kc(128), + nc(128) #endif -{} +{ +} /* Dense matrix multiplication, gemm functionality. */ -void CBlasStructure::gemm(const int M, const int N, const int K, - const su2double *A, const su2double *B, su2double *C, - const CConfig *config) { - +void CBlasStructure::gemm(const int M, const int N, const int K, const su2double* A, const su2double* B, su2double* C, + const CConfig* config) { /* Initialize the variable for the timing, if profiling is active. */ #ifdef PROFILE double timeGemm; - if( config ) config->GEMM_Tick(&timeGemm); + if (config) config->GEMM_Tick(&timeGemm); #endif -#if (defined(CODI_REVERSE_TYPE) || defined(CODI_FORWARD_TYPE)) || !(defined(HAVE_LIBXSMM) || defined(HAVE_MKL) || defined(HAVE_BLAS)) +#if (defined(CODI_REVERSE_TYPE) || defined(CODI_FORWARD_TYPE)) || \ + !(defined(HAVE_LIBXSMM) || defined(HAVE_MKL) || defined(HAVE_BLAS)) /* Native implementation of the matrix product. This optimized implementation assumes that the matrices are in column major order. This can be accomplished by swapping N and M and A and B. This implementation is based @@ -76,18 +76,18 @@ void CBlasStructure::gemm(const int M, const int N, const int K, Note that libxsmm_gemm expects the matrices in column major order. That's why the in the calling sequence A and B and M and N are reversed. */ su2double alpha = 1.0; - su2double beta = 0.0; + su2double beta = 0.0; char trans = 'N'; libxsmm_dgemm(&trans, &trans, &N, &M, &K, &alpha, B, &N, A, &K, &beta, C, &N); -#else // MKL and BLAS +#else // MKL and BLAS /* The standard blas routine dgemm is used for the multiplication. Call dgemm without transposing the matrices. In that case dgemm expects the matrices in column major order, see the comments for libxsmm. */ su2double alpha = 1.0; - su2double beta = 0.0; + su2double beta = 0.0; char trans = 'N'; dgemm_(&trans, &trans, &N, &M, &K, &alpha, B, &N, A, &K, &beta, C, &N); @@ -97,44 +97,42 @@ void CBlasStructure::gemm(const int M, const int N, const int K, /* Store the profiling information, if needed. */ #ifdef PROFILE - if( config ) config->GEMM_Tock(timeGemm, M, N, K); + if (config) config->GEMM_Tock(timeGemm, M, N, K); #endif } /* Dense matrix vector multiplication, gemv functionality. */ -void CBlasStructure::gemv(const int M, const int N, const su2double *A, - const su2double *x, su2double *y) { - -#if (defined (HAVE_BLAS) || defined(HAVE_MKL)) && !(defined(CODI_REVERSE_TYPE) || defined(CODI_FORWARD_TYPE)) +void CBlasStructure::gemv(const int M, const int N, const su2double* A, const su2double* x, su2double* y) { +#if (defined(HAVE_BLAS) || defined(HAVE_MKL)) && !(defined(CODI_REVERSE_TYPE) || defined(CODI_FORWARD_TYPE)) /* The standard blas routine dgemv is used for the multiplication. Note that dgemv expects the matrices in column major order, while A is in row major order. This can be solved by using the transpose and switching M and N. */ - su2double alpha = 1.0; - su2double beta = 0.0; - int inc = 1; - char trans = 'T'; + su2double alpha = 1.0; + su2double beta = 0.0; + int inc = 1; + char trans = 'T'; - dgemv_(&trans, &N, &M, &alpha, A, &N, x, &inc, &beta, y, &inc); + dgemv_(&trans, &N, &M, &alpha, A, &N, x, &inc, &beta, y, &inc); #else /* Native implementation of the matix vector product. Initialize the elements of y to zero. */ - for(int i=0; i= x.size()-1) return (Point_Interp <= x[0])? y.front() : y.back(); + if (i >= x.size() - 1) return (Point_Interp <= x[0]) ? y.front() : y.back(); - const su2double h = Point_Interp-x[i]; + const su2double h = Point_Interp - x[i]; - return y[i]+h*(b[i]+h*(c[i]+h*d[i])); + return y[i] + h * (b[i] + h * (c[i] + h * d[i])); } su2double CLinearInterpolation::EvaluateSpline(su2double Point_Interp) const { - const auto i = lower_bound(Point_Interp); - if (i >= x.size()-1) return (Point_Interp <= x[0])? y.front() : y.back(); + if (i >= x.size() - 1) return (Point_Interp <= x[0]) ? y.front() : y.back(); - return y[i] + (Point_Interp-x[i]) * (y[i+1]-y[i]) / (x[i+1]-x[i]); + return y[i] + (Point_Interp - x[i]) * (y[i + 1] - y[i]) / (x[i + 1] - x[i]); } -void CCubicSpline::SetSpline(const vector &X, const vector &Data) { - - C1DInterpolation::SetSpline(X,Data); +void CCubicSpline::SetSpline(const vector& X, const vector& Data) { + C1DInterpolation::SetSpline(X, Data); const int N = x.size(); /*--- Alias the vectors of coefficients to build the tridiagonal system. ---*/ - auto& lower = b; b.resize(N); - auto& main = c; c.resize(N); - auto& upper = d; d.resize(N); + auto& lower = b; + b.resize(N); + auto& main = c; + c.resize(N); + auto& upper = d; + d.resize(N); vector rhs(N); /*--- Main part of the tridiagonal system. ---*/ - for (int i=1; i &X, const vector main[0] = 1.0; upper[0] = 0; rhs[0] = startVal; - } - else { // FIRST - main[0] = 2*lower[1]; + } else { // FIRST + main[0] = 2 * lower[1]; upper[0] = lower[1]; - rhs[0] = 6*((y[1]-y[0])/lower[1] - startVal); + rhs[0] = 6 * ((y[1] - y[0]) / lower[1] - startVal); } /*--- End condition. ---*/ if (endDer == SECOND) { - main[N-1] = 1.0; - lower[N-1] = 0; - rhs[N-1] = endVal; - } - else { // FIRST - main[N-1] = 2*upper[N-2]; - lower[N-1] = upper[N-2]; - rhs[N-1] = 6*(endVal - (y[N-1]-y[N-2])/upper[N-2]); + main[N - 1] = 1.0; + lower[N - 1] = 0; + rhs[N - 1] = endVal; + } else { // FIRST + main[N - 1] = 2 * upper[N - 2]; + lower[N - 1] = upper[N - 2]; + rhs[N - 1] = 6 * (endVal - (y[N - 1] - y[N - 2]) / upper[N - 2]); } /*--- Solve system for 2nd derivative at the knots. ---*/ @@ -109,26 +107,25 @@ void CCubicSpline::SetSpline(const vector &X, const vector /*--- Compute the polynomial coefficients. ---*/ - for (int i=0; i &X, const vector &Data){ - - C1DInterpolation::SetSpline(X,Data); +void CAkimaInterpolation::SetSpline(const vector& X, const vector& Data) { + C1DInterpolation::SetSpline(X, Data); const int n = X.size(); - vector h (n-1); - vector p (n-1); + vector h(n - 1); + vector p(n - 1); /*---calculating finite differences (h) and gradients (p) ---*/ - for (int i=0; i &X, const vector CorrectedInletValues(const vector &Inlet_Interpolated , - su2double Theta , - unsigned short nDim, - const su2double *Coord, - unsigned short nVar_Turb, - INLET_INTERP_TYPE Interpolation_Type){ - - unsigned short size_columns=Inlet_Interpolated.size()+nDim; +vector CorrectedInletValues(const vector& Inlet_Interpolated, su2double Theta, + unsigned short nDim, const su2double* Coord, unsigned short nVar_Turb, + INLET_INTERP_TYPE Interpolation_Type) { + unsigned short size_columns = Inlet_Interpolated.size() + nDim; vector Inlet_Values(size_columns); su2double unit_r, unit_Theta, unit_m, Alpha, Phi; /*---For x,y,z,T,P columns---*/ - for (int i=0;i CorrectedInletValues(const vector &Inlet_Interpolat } /*--- Converting from cylindrical to cartesian unit vectors ---*/ - Inlet_Values[nDim+2] = unit_r*cos(Theta) - unit_Theta*sin(Theta); - Inlet_Values[nDim+3] = unit_r*sin(Theta) + unit_Theta*cos(Theta); - Inlet_Values[nDim+4] = sqrt(1-pow(unit_r,2)- pow(unit_Theta,2)); + Inlet_Values[nDim + 2] = unit_r * cos(Theta) - unit_Theta * sin(Theta); + Inlet_Values[nDim + 3] = unit_r * sin(Theta) + unit_Theta * cos(Theta); + Inlet_Values[nDim + 4] = sqrt(1 - pow(unit_r, 2) - pow(unit_Theta, 2)); return Inlet_Values; } -void PrintInletInterpolatedData(const vector& Inlet_Data_Interpolated, string Marker, - unsigned long nVertex, unsigned short nDim, unsigned short nColumns){ - +void PrintInletInterpolatedData(const vector& Inlet_Data_Interpolated, string Marker, unsigned long nVertex, + unsigned short nDim, unsigned short nColumns) { ofstream myfile; myfile.precision(16); - myfile.open("Interpolated_Data_"+Marker+".dat",ios_base::out); + myfile.open("Interpolated_Data_" + Marker + ".dat", ios_base::out); - if (myfile.is_open()){ + if (myfile.is_open()) { for (unsigned long iVertex = 0; iVertex < nVertex; iVertex++) { - for (unsigned short iVar=0; iVar < nColumns; iVar++){ - myfile<= (unsigned long)size) - quotient = global_count/size; + if (global_count >= (unsigned long)size) quotient = global_count / size; - int remainder = int(global_count%size); + int remainder = int(global_count % size); for (int ii = 0; ii < size; ii++) { sizeOnRank[ii] = quotient + int(ii < remainder); } @@ -64,32 +60,27 @@ void CLinearPartitioner::Initialize(unsigned long global_count, if (isDisjoint) adjust = 1; firstIndex[0] = offset; - lastIndex[0] = firstIndex[0] + sizeOnRank[0] - adjust; + lastIndex[0] = firstIndex[0] + sizeOnRank[0] - adjust; cumulativeSizeBeforeRank[0] = 0; for (int iProc = 1; iProc < size; iProc++) { - firstIndex[iProc] = lastIndex[iProc-1] + adjust; - lastIndex[iProc] = firstIndex[iProc] + sizeOnRank[iProc] - adjust; - cumulativeSizeBeforeRank[iProc] = (cumulativeSizeBeforeRank[iProc-1] + - sizeOnRank[iProc-1]); + firstIndex[iProc] = lastIndex[iProc - 1] + adjust; + lastIndex[iProc] = firstIndex[iProc] + sizeOnRank[iProc] - adjust; + cumulativeSizeBeforeRank[iProc] = (cumulativeSizeBeforeRank[iProc - 1] + sizeOnRank[iProc - 1]); } cumulativeSizeBeforeRank[size] = global_count; - } unsigned long CLinearPartitioner::GetRankContainingIndex(unsigned long index) const { - /*--- Initial guess ---*/ - unsigned long iProcessor = min(index/sizeOnRank[0], size-1); + unsigned long iProcessor = min(index / sizeOnRank[0], size - 1); /*--- Move up or down until we find the processor. ---*/ if (index >= cumulativeSizeBeforeRank[iProcessor]) - while(index >= cumulativeSizeBeforeRank[iProcessor+1]) - iProcessor++; + while (index >= cumulativeSizeBeforeRank[iProcessor + 1]) iProcessor++; else - while(index < cumulativeSizeBeforeRank[iProcessor]) - iProcessor--; + while (index < cumulativeSizeBeforeRank[iProcessor]) iProcessor--; return iProcessor; } diff --git a/Common/src/toolboxes/CSquareMatrixCM.cpp b/Common/src/toolboxes/CSquareMatrixCM.cpp index 09b990dc448..b4a33c8b2db 100644 --- a/Common/src/toolboxes/CSquareMatrixCM.cpp +++ b/Common/src/toolboxes/CSquareMatrixCM.cpp @@ -38,26 +38,19 @@ using namespace std; #endif #elif defined(HAVE_LAPACK) /*--- Lapack / Blas routines used in CSquareMatrixCM. ---*/ -extern "C" void dgetrf_(const int*, const int*, passivedouble*, const int*, - int*, int*); -extern "C" void dgetri_(const int*, passivedouble*, const int*, int*, - passivedouble*, const int*, int*); -extern "C" void dgemm_(char*, char*, const int*, const int*, const int*, - const passivedouble*, const passivedouble*, - const int *, const passivedouble*, const int*, - const passivedouble*, passivedouble*, const int*); +extern "C" void dgetrf_(const int*, const int*, passivedouble*, const int*, int*, int*); +extern "C" void dgetri_(const int*, passivedouble*, const int*, int*, passivedouble*, const int*, int*); +extern "C" void dgemm_(char*, char*, const int*, const int*, const int*, const passivedouble*, const passivedouble*, + const int*, const passivedouble*, const int*, const passivedouble*, passivedouble*, const int*); #define DGEMM dgemm_ #endif void CSquareMatrixCM::Transpose() { - - for(int j=1; j work(sz); dgetrf_(&sz, &sz, mat.data(), &sz, ipiv.data(), &info); - if(info != 0) SU2_MPI::Error(string("Matrix is singular"), CURRENT_FUNCTION); + if (info != 0) SU2_MPI::Error(string("Matrix is singular"), CURRENT_FUNCTION); dgetri_(&sz, mat.data(), &sz, ipiv.data(), work.data(), &sz, &info); - if(info != 0) SU2_MPI::Error(string("Matrix inversion failed"), CURRENT_FUNCTION); + if (info != 0) SU2_MPI::Error(string("Matrix inversion failed"), CURRENT_FUNCTION); #else CBlasStructure::inverse(Size(), mat); #endif } -void CSquareMatrixCM::MatMatMult(const char side, - const ColMajorMatrix &mat_in, - ColMajorMatrix &mat_out) const { - +void CSquareMatrixCM::MatMatMult(const char side, const ColMajorMatrix& mat_in, + ColMajorMatrix& mat_out) const { /*--- Check the type of multiplication to be carried out. ---*/ if (side == 'L' || side == 'l') { - /*--- Left side: mat_out = this * mat_in. Set some sizes and allocate the memory for mat_out. ---*/ const int M = Size(), N = mat_in.cols(); assert(M == static_cast(mat_in.rows())); - mat_out.resize(M,N); + mat_out.resize(M, N); #ifdef HAVE_LAPACK @@ -98,28 +88,24 @@ void CSquareMatrixCM::MatMatMult(const char side, passivedouble alpha = 1.0, beta = 0.0; char trans = 'N'; - DGEMM(&trans, &trans, &M, &N, &M, &alpha, mat.data(), &M, - mat_in.data(), &M, &beta, mat_out.data(), &M); + DGEMM(&trans, &trans, &M, &N, &M, &alpha, mat.data(), &M, mat_in.data(), &M, &beta, mat_out.data(), &M); #else /*--- Naive product. ---*/ for (int i = 0; i < M; ++i) { for (int j = 0; j < N; ++j) { - mat_out(i,j) = 0.0; - for (int k = 0; k < M; ++k) - mat_out(i,j) += mat(i,k) * mat_in(k,j); + mat_out(i, j) = 0.0; + for (int k = 0; k < M; ++k) mat_out(i, j) += mat(i, k) * mat_in(k, j); } } #endif - } - else { - + } else { /*--- Right_side: mat_out = mat_in * this. Set some sizes and allocate the memory for mat_out. ---*/ const int M = mat_in.rows(), N = Size(); assert(N == static_cast(mat_in.cols())); - mat_out.resize(M,N); + mat_out.resize(M, N); #ifdef HAVE_LAPACK @@ -128,15 +114,13 @@ void CSquareMatrixCM::MatMatMult(const char side, passivedouble alpha = 1.0, beta = 0.0; char trans = 'N'; - DGEMM(&trans, &trans, &M, &N, &N, &alpha, mat_in.data(), &M, - mat.data(), &N, &beta, mat_out.data(), &M); + DGEMM(&trans, &trans, &M, &N, &N, &alpha, mat_in.data(), &M, mat.data(), &N, &beta, mat_out.data(), &M); #else /*--- Naive product. ---*/ for (int i = 0; i < M; ++i) { for (int j = 0; j < N; ++j) { - mat_out(i,j) = 0.0; - for (int k = 0; k < N; ++k) - mat_out(i,j) += mat_in(i,k) * mat(k,j); + mat_out(i, j) = 0.0; + for (int k = 0; k < N; ++k) mat_out(i, j) += mat_in(i, k) * mat(k, j); } } #endif diff --git a/Common/src/toolboxes/CSymmetricMatrix.cpp b/Common/src/toolboxes/CSymmetricMatrix.cpp index a2adb505562..e5f6daa723f 100644 --- a/Common/src/toolboxes/CSymmetricMatrix.cpp +++ b/Common/src/toolboxes/CSymmetricMatrix.cpp @@ -47,38 +47,35 @@ extern "C" void dsymm_(const char*, const char*, const int*, const int*, const p #define DSYMM dsymm_ #endif -void CSymmetricMatrix::Initialize(int N) { mat.resize(N,N); } +void CSymmetricMatrix::Initialize(int N) { mat.resize(N, N); } -void CSymmetricMatrix::CholeskyDecompose() -{ +void CSymmetricMatrix::CholeskyDecompose() { #ifndef HAVE_LAPACK int j; for (j = 0; j < Size(); ++j) { passivedouble sum = 0.0; - for (int k = 0; k < j; ++k) sum -= pow(Get(j,k), 2); - sum += Get(j,j); - if (sum < 0.0) break; // not SPD + for (int k = 0; k < j; ++k) sum -= pow(Get(j, k), 2); + sum += Get(j, j); + if (sum < 0.0) break; // not SPD Set(j, j, sqrt(sum)); - for (int i = j+1; i < Size(); ++i) { + for (int i = j + 1; i < Size(); ++i) { passivedouble sum = 0.0; - for (int k = 0; k < j; ++k) sum -= Get(i,k) * Get(j,k); - sum += Get(i,j); - Set(i, j, sum / Get(j,j)); + for (int k = 0; k < j; ++k) sum -= Get(i, k) * Get(j, k); + sum += Get(i, j); + Set(i, j, sum / Get(j, j)); } } - if (j!=Size()) SU2_MPI::Error("LLT factorization failed.", CURRENT_FUNCTION); + if (j != Size()) SU2_MPI::Error("LLT factorization failed.", CURRENT_FUNCTION); #endif } -void CSymmetricMatrix::CalcInv(bool is_spd) -{ +void CSymmetricMatrix::CalcInv(bool is_spd) { #ifndef HAVE_LAPACK const int sz = Size(); /*--- Compute inverse from decomposed matrices. ---*/ - if (is_spd) - { + if (is_spd) { CholeskyDecompose(); /*--- Initialize inverse matrix. ---*/ @@ -88,24 +85,23 @@ void CSymmetricMatrix::CalcInv(bool is_spd) /*--- Solve smaller and smaller systems. ---*/ for (int j = 0; j < sz; ++j) { /*--- Forward substitution. ---*/ - inv(j,j) = 1.0 / Get(j,j); + inv(j, j) = 1.0 / Get(j, j); - for (int i = j+1; i < sz; ++i) { + for (int i = j + 1; i < sz; ++i) { passivedouble sum = 0.0; - for (int k = j; k < i; ++k) sum -= Get(i,k) * inv(k,j); - inv(i,j) = sum / Get(i,i); + for (int k = j; k < i; ++k) sum -= Get(i, k) * inv(k, j); + inv(i, j) = sum / Get(i, i); } - } // L inverse in inv + } // L inverse in inv /*--- Multiply inversed matrices overwrite mat. ---*/ for (int j = 0; j < sz; ++j) for (int i = j; i < sz; ++i) { passivedouble sum = 0.0; - for (int k = i; k < sz; ++k) sum += inv(k,i) * inv(k,j); + for (int k = i; k < sz; ++k) sum += inv(k, i) * inv(k, j); Set(i, j, sum); } - } - else { + } else { auto inv = StealData(); CBlasStructure::inverse(sz, inv); mat = move(inv); @@ -113,8 +109,7 @@ void CSymmetricMatrix::CalcInv(bool is_spd) #endif } -void CSymmetricMatrix::CalcInv_sytri() -{ +void CSymmetricMatrix::CalcInv_sytri() { #ifdef HAVE_LAPACK const char uplo = 'L'; const int sz = Size(); @@ -122,66 +117,62 @@ void CSymmetricMatrix::CalcInv_sytri() vector ipiv(sz); /*--- Query the optimum work size. ---*/ - int query = -1; passivedouble tmp; + int query = -1; + passivedouble tmp; dsytrf_(&uplo, &sz, mat.data(), &sz, ipiv.data(), &tmp, &query, &info); query = static_cast(tmp); vector work(query); /*--- Factorize and invert. ---*/ dsytrf_(&uplo, &sz, mat.data(), &sz, ipiv.data(), work.data(), &query, &info); - if (info!=0) SU2_MPI::Error("LDLT factorization failed.", CURRENT_FUNCTION); + if (info != 0) SU2_MPI::Error("LDLT factorization failed.", CURRENT_FUNCTION); dsytri_(&uplo, &sz, mat.data(), &sz, ipiv.data(), work.data(), &info); - if (info!=0) SU2_MPI::Error("Inversion with LDLT factorization failed.", CURRENT_FUNCTION); + if (info != 0) SU2_MPI::Error("Inversion with LDLT factorization failed.", CURRENT_FUNCTION); #endif } -void CSymmetricMatrix::CalcInv_potri() -{ +void CSymmetricMatrix::CalcInv_potri() { #ifdef HAVE_LAPACK const char uplo = 'L'; const int sz = Size(); int info; dpotrf_(&uplo, &sz, mat.data(), &sz, &info); - if (info!=0) SU2_MPI::Error("LLT factorization failed.", CURRENT_FUNCTION); + if (info != 0) SU2_MPI::Error("LLT factorization failed.", CURRENT_FUNCTION); dpotri_(&uplo, &sz, mat.data(), &sz, &info); - if (info!=0) SU2_MPI::Error("Inversion with LLT factorization failed.", CURRENT_FUNCTION); + if (info != 0) SU2_MPI::Error("Inversion with LLT factorization failed.", CURRENT_FUNCTION); #endif } -void CSymmetricMatrix::Invert(const bool is_spd) -{ +void CSymmetricMatrix::Invert(const bool is_spd) { #ifdef HAVE_LAPACK - if(is_spd) CalcInv_potri(); - else CalcInv_sytri(); + if (is_spd) + CalcInv_potri(); + else + CalcInv_sytri(); #else CalcInv(is_spd); #endif } -void CSymmetricMatrix::MatMatMult(const char side, - const su2passivematrix& mat_in, - su2passivematrix& mat_out) const -{ +void CSymmetricMatrix::MatMatMult(const char side, const su2passivematrix& mat_in, su2passivematrix& mat_out) const { /*--- Left side: mat_out = this * mat_in. ---*/ if (side == 'L' || side == 'l') { const int M = Size(), N = mat_in.cols(); assert(M == static_cast(mat_in.rows())); - mat_out.resize(M,N); + mat_out.resize(M, N); #ifdef HAVE_LAPACK /*--- Right and lower because matrices are in row major order. ---*/ const char side = 'R', uplo = 'L'; const passivedouble alpha = 1.0, beta = 0.0; - DSYMM(&side, &uplo, &N, &M, &alpha, mat.data(), &M, - mat_in.data(), &N, &beta, mat_out.data(), &N); -#else // Naive product + DSYMM(&side, &uplo, &N, &M, &alpha, mat.data(), &M, mat_in.data(), &N, &beta, mat_out.data(), &N); +#else // Naive product for (int i = 0; i < M; ++i) for (int j = 0; j < N; ++j) { - mat_out(i,j) = 0.0; - for (int k = 0; k < M; ++k) - mat_out(i,j) += Get(i,k) * mat_in(k,j); + mat_out(i, j) = 0.0; + for (int k = 0; k < M; ++k) mat_out(i, j) += Get(i, k) * mat_in(k, j); } #endif } @@ -190,31 +181,27 @@ void CSymmetricMatrix::MatMatMult(const char side, const int M = mat_in.rows(), N = Size(); assert(N == static_cast(mat_in.cols())); - mat_out.resize(M,N); + mat_out.resize(M, N); #ifdef HAVE_LAPACK /*--- Left and lower because matrices are in row major order. ---*/ const char side = 'L', uplo = 'L'; const passivedouble alpha = 1.0, beta = 0.0; - DSYMM(&side, &uplo, &N, &M, &alpha, mat.data(), &N, - mat_in.data(), &N, &beta, mat_out.data(), &N); -#else // Naive product + DSYMM(&side, &uplo, &N, &M, &alpha, mat.data(), &N, mat_in.data(), &N, &beta, mat_out.data(), &N); +#else // Naive product for (int i = 0; i < M; ++i) for (int j = 0; j < N; ++j) { - mat_out(i,j) = 0.0; - for (int k = 0; k < N; ++k) - mat_out(i,j) += mat_in(i,k) * Get(k,j); + mat_out(i, j) = 0.0; + for (int k = 0; k < N; ++k) mat_out(i, j) += mat_in(i, k) * Get(k, j); } #endif } } -su2passivematrix CSymmetricMatrix::StealData() -{ +su2passivematrix CSymmetricMatrix::StealData() { /*--- Fill lower triangular part. ---*/ for (int i = 1; i < Size(); ++i) - for (int j = 0; j < i; ++j) - mat(i,j) = mat(j,i); + for (int j = 0; j < i; ++j) mat(i, j) = mat(j, i); return move(mat); } diff --git a/Common/src/toolboxes/MMS/CIncTGVSolution.cpp b/Common/src/toolboxes/MMS/CIncTGVSolution.cpp index 51b0499dae0..9baa1999c18 100644 --- a/Common/src/toolboxes/MMS/CIncTGVSolution.cpp +++ b/Common/src/toolboxes/MMS/CIncTGVSolution.cpp @@ -27,18 +27,14 @@ #include "../../../include/toolboxes/MMS/CIncTGVSolution.hpp" -CIncTGVSolution::CIncTGVSolution(void) : CVerificationSolution() { } - -CIncTGVSolution::CIncTGVSolution(unsigned short val_nDim, - unsigned short val_nVar, - unsigned short val_iMesh, - CConfig* config) -: CVerificationSolution(val_nDim, val_nVar, val_iMesh, config) { +CIncTGVSolution::CIncTGVSolution(void) : CVerificationSolution() {} +CIncTGVSolution::CIncTGVSolution(unsigned short val_nDim, unsigned short val_nVar, unsigned short val_iMesh, + CConfig* config) + : CVerificationSolution(val_nDim, val_nVar, val_iMesh, config) { /*--- Disable this solution for now, as it has not been tested. ---*/ - SU2_MPI::Error("CIncTGVSolution not yet fully implemented/tested.", - CURRENT_FUNCTION); + SU2_MPI::Error("CIncTGVSolution not yet fully implemented/tested.", CURRENT_FUNCTION); /*--- Write a message that the solution is initialized for the Taylor-Green vortex test case. ---*/ @@ -52,9 +48,9 @@ CIncTGVSolution::CIncTGVSolution(unsigned short val_nDim, /*--- Store TGV specific parameters here. ---*/ - tgvLength = 1.0; - tgvVelocity = 1.0; - tgvDensity = config->GetDensity_FreeStreamND(); + tgvLength = 1.0; + tgvVelocity = 1.0; + tgvDensity = config->GetDensity_FreeStreamND(); tgvViscosity = config->GetViscosity_FreeStreamND(); /*--- We keep a copy of the freestream temperature just to be safe @@ -64,73 +60,61 @@ CIncTGVSolution::CIncTGVSolution(unsigned short val_nDim, /*--- Perform some sanity and error checks for this solution here. ---*/ - if((config->GetTime_Marching() != TIME_MARCHING::TIME_STEPPING) && - (config->GetTime_Marching() != TIME_MARCHING::DT_STEPPING_1ST) && - (config->GetTime_Marching() != TIME_MARCHING::DT_STEPPING_2ND)) - SU2_MPI::Error("Unsteady mode must be selected for the incompressible Taylor Green Vortex", - CURRENT_FUNCTION); + if ((config->GetTime_Marching() != TIME_MARCHING::TIME_STEPPING) && + (config->GetTime_Marching() != TIME_MARCHING::DT_STEPPING_1ST) && + (config->GetTime_Marching() != TIME_MARCHING::DT_STEPPING_2ND)) + SU2_MPI::Error("Unsteady mode must be selected for the incompressible Taylor Green Vortex", CURRENT_FUNCTION); - if(Kind_Solver != MAIN_SOLVER::INC_EULER && Kind_Solver != MAIN_SOLVER::INC_NAVIER_STOKES && Kind_Solver != MAIN_SOLVER::INC_RANS ) + if (Kind_Solver != MAIN_SOLVER::INC_EULER && Kind_Solver != MAIN_SOLVER::INC_NAVIER_STOKES && + Kind_Solver != MAIN_SOLVER::INC_RANS) SU2_MPI::Error("Incompressible flow equations must be selected for the incompressible Taylor Green Vortex", CURRENT_FUNCTION); - if(Kind_Solver != MAIN_SOLVER::INC_NAVIER_STOKES) + if (Kind_Solver != MAIN_SOLVER::INC_NAVIER_STOKES) SU2_MPI::Error("Navier Stokes equations must be selected for the incompressible Taylor Green Vortex", CURRENT_FUNCTION); - if(config->GetKind_FluidModel() != CONSTANT_DENSITY) + if (config->GetKind_FluidModel() != CONSTANT_DENSITY) SU2_MPI::Error("Constant density fluid model must be selected for the incompressible Taylor Green Vortex", CURRENT_FUNCTION); - if(config->GetKind_ViscosityModel() != VISCOSITYMODEL::CONSTANT) - SU2_MPI::Error("Constant viscosity must be selected for the incompressible Taylor Green Vortex", - CURRENT_FUNCTION); + if (config->GetKind_ViscosityModel() != VISCOSITYMODEL::CONSTANT) + SU2_MPI::Error("Constant viscosity must be selected for the incompressible Taylor Green Vortex", CURRENT_FUNCTION); - if(config->GetEnergy_Equation()) + if (config->GetEnergy_Equation()) SU2_MPI::Error("Energy equation must be disabled (isothermal) for the incompressible Taylor Green Vortex", CURRENT_FUNCTION); - if(nDim != 2) - SU2_MPI::Error("2D calculation required for the incompressible Taylor Green Vortex", - CURRENT_FUNCTION); + if (nDim != 2) SU2_MPI::Error("2D calculation required for the incompressible Taylor Green Vortex", CURRENT_FUNCTION); } -CIncTGVSolution::~CIncTGVSolution(void) { } - -void CIncTGVSolution::GetBCState(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const { +CIncTGVSolution::~CIncTGVSolution(void) {} +void CIncTGVSolution::GetBCState(const su2double* val_coords, const su2double val_t, su2double* val_solution) const { /*--- The exact solution is prescribed on the boundaries. ---*/ GetSolution(val_coords, val_t, val_solution); } -void CIncTGVSolution::GetSolution(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const { - +void CIncTGVSolution::GetSolution(const su2double* val_coords, const su2double val_t, su2double* val_solution) const { /* The exact solution is set for the incompressible Taylor-Green vortex case. This is the classic solution from the original work of Taylor and Green for the specific 2D situation where the exact solution can be derived for an incompressible flow. */ /* Store the termporal term more easily (Taylor expansion). */ - su2double F = 1.0 - 2.0*(tgvViscosity/tgvDensity)*val_t; + su2double F = 1.0 - 2.0 * (tgvViscosity / tgvDensity) * val_t; /* Compute the primitive variables. */ - su2double u = tgvVelocity * F * (sin(val_coords[0]/tgvLength)* - cos(val_coords[1]/tgvLength)); - su2double v = -tgvVelocity * F * (cos(val_coords[0]/tgvLength)* - sin(val_coords[1]/tgvLength)); + su2double u = tgvVelocity * F * (sin(val_coords[0] / tgvLength) * cos(val_coords[1] / tgvLength)); + su2double v = -tgvVelocity * F * (cos(val_coords[0] / tgvLength) * sin(val_coords[1] / tgvLength)); - su2double B = (cos(2.0*val_coords[0]/tgvLength) + - cos(2.0*val_coords[1]/tgvLength)); - su2double p = -(tgvDensity/4.0)*B*F*F; + su2double B = (cos(2.0 * val_coords[0] / tgvLength) + cos(2.0 * val_coords[1] / tgvLength)); + su2double p = -(tgvDensity / 4.0) * B * F * F; /* Compute the conservative variables. Note that both 2D and 3D cases are treated correctly. */ - val_solution[0] = p; - val_solution[1] = u; - val_solution[2] = v; - val_solution[nVar-1] = Temperature; + val_solution[0] = p; + val_solution[1] = u; + val_solution[2] = v; + val_solution[nVar - 1] = Temperature; } diff --git a/Common/src/toolboxes/MMS/CInviscidVortexSolution.cpp b/Common/src/toolboxes/MMS/CInviscidVortexSolution.cpp index f699d9f6ccb..2dc8e090197 100644 --- a/Common/src/toolboxes/MMS/CInviscidVortexSolution.cpp +++ b/Common/src/toolboxes/MMS/CInviscidVortexSolution.cpp @@ -27,14 +27,11 @@ #include "../../../include/toolboxes/MMS/CInviscidVortexSolution.hpp" -CInviscidVortexSolution::CInviscidVortexSolution(void) : CVerificationSolution() { } - -CInviscidVortexSolution::CInviscidVortexSolution(unsigned short val_nDim, - unsigned short val_nVar, - unsigned short val_iMesh, - CConfig* config) - : CVerificationSolution(val_nDim, val_nVar, val_iMesh, config) { +CInviscidVortexSolution::CInviscidVortexSolution(void) : CVerificationSolution() {} +CInviscidVortexSolution::CInviscidVortexSolution(unsigned short val_nDim, unsigned short val_nVar, + unsigned short val_iMesh, CConfig* config) + : CVerificationSolution(val_nDim, val_nVar, val_iMesh, config) { /*--- Write a message that the solution is initialized for the inviscid vortex test case. ---*/ if ((rank == MASTER_NODE) && (val_iMesh == MESH_0)) { @@ -45,98 +42,86 @@ CInviscidVortexSolution::CInviscidVortexSolution(unsigned short val_nDim, } /*--- Store the inviscid vortex specific parameters here. ---*/ - x0Vortex = -0.5; // Initial x-coordinate of the vortex center. - y0Vortex = 0.0; // Initial y-coordinate of the vortex center. - RVortex = 0.1; // Radius of the vortex. - epsVortex = 1.0; // Strength of the vortex. + x0Vortex = -0.5; // Initial x-coordinate of the vortex center. + y0Vortex = 0.0; // Initial y-coordinate of the vortex center. + RVortex = 0.1; // Radius of the vortex. + epsVortex = 1.0; // Strength of the vortex. /* Get the Mach number and advection angle (in degrees). */ - MachVortex = config->GetMach(); + MachVortex = config->GetMach(); thetaVortex = config->GetAoA(); /*--- Useful coefficients in which Gamma is present. ---*/ - Gamma = config->GetGamma(); - Gm1 = Gamma - 1.0; - ovGm1 = 1.0/Gm1; - gamOvGm1 = ovGm1*Gamma; + Gamma = config->GetGamma(); + Gm1 = Gamma - 1.0; + ovGm1 = 1.0 / Gm1; + gamOvGm1 = ovGm1 * Gamma; /*--- Perform some sanity and error checks for this solution here. ---*/ - if((config->GetTime_Marching() != TIME_MARCHING::TIME_STEPPING) && - (config->GetTime_Marching() != TIME_MARCHING::DT_STEPPING_1ST) && - (config->GetTime_Marching() != TIME_MARCHING::DT_STEPPING_2ND)) - SU2_MPI::Error("Unsteady mode must be selected for the inviscid vortex", - CURRENT_FUNCTION); - - if(Kind_Solver != MAIN_SOLVER::EULER && Kind_Solver != MAIN_SOLVER::NAVIER_STOKES && Kind_Solver != MAIN_SOLVER::RANS && - Kind_Solver != MAIN_SOLVER::FEM_EULER && Kind_Solver != MAIN_SOLVER::FEM_NAVIER_STOKES && Kind_Solver != MAIN_SOLVER::FEM_RANS && - Kind_Solver != MAIN_SOLVER::FEM_LES) - SU2_MPI::Error("Compressible flow equations must be selected for the inviscid vortex", - CURRENT_FUNCTION); - - if((Kind_Solver != MAIN_SOLVER::EULER) && - (Kind_Solver != MAIN_SOLVER::FEM_EULER)) - SU2_MPI::Error("Euler equations must be selected for the inviscid vortex", - CURRENT_FUNCTION); - - if((config->GetKind_FluidModel() != STANDARD_AIR) && - (config->GetKind_FluidModel() != IDEAL_GAS)) - SU2_MPI::Error("Standard air or ideal gas must be selected for the inviscid vortex", - CURRENT_FUNCTION); - - if(fabs(config->GetPressure_FreeStreamND() - 1.0) > 1.e-8) - SU2_MPI::Error("Free-stream pressure must be 1.0 for the inviscid vortex", - CURRENT_FUNCTION); - - if(fabs(config->GetDensity_FreeStreamND() - 1.0) > 1.e-8) - SU2_MPI::Error("Free-stream density must be 1.0 for the inviscid vortex", - CURRENT_FUNCTION); -} + if ((config->GetTime_Marching() != TIME_MARCHING::TIME_STEPPING) && + (config->GetTime_Marching() != TIME_MARCHING::DT_STEPPING_1ST) && + (config->GetTime_Marching() != TIME_MARCHING::DT_STEPPING_2ND)) + SU2_MPI::Error("Unsteady mode must be selected for the inviscid vortex", CURRENT_FUNCTION); + + if (Kind_Solver != MAIN_SOLVER::EULER && Kind_Solver != MAIN_SOLVER::NAVIER_STOKES && + Kind_Solver != MAIN_SOLVER::RANS && Kind_Solver != MAIN_SOLVER::FEM_EULER && + Kind_Solver != MAIN_SOLVER::FEM_NAVIER_STOKES && Kind_Solver != MAIN_SOLVER::FEM_RANS && + Kind_Solver != MAIN_SOLVER::FEM_LES) + SU2_MPI::Error("Compressible flow equations must be selected for the inviscid vortex", CURRENT_FUNCTION); + + if ((Kind_Solver != MAIN_SOLVER::EULER) && (Kind_Solver != MAIN_SOLVER::FEM_EULER)) + SU2_MPI::Error("Euler equations must be selected for the inviscid vortex", CURRENT_FUNCTION); -CInviscidVortexSolution::~CInviscidVortexSolution(void) { } + if ((config->GetKind_FluidModel() != STANDARD_AIR) && (config->GetKind_FluidModel() != IDEAL_GAS)) + SU2_MPI::Error("Standard air or ideal gas must be selected for the inviscid vortex", CURRENT_FUNCTION); -void CInviscidVortexSolution::GetBCState(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const { + if (fabs(config->GetPressure_FreeStreamND() - 1.0) > 1.e-8) + SU2_MPI::Error("Free-stream pressure must be 1.0 for the inviscid vortex", CURRENT_FUNCTION); + if (fabs(config->GetDensity_FreeStreamND() - 1.0) > 1.e-8) + SU2_MPI::Error("Free-stream density must be 1.0 for the inviscid vortex", CURRENT_FUNCTION); +} + +CInviscidVortexSolution::~CInviscidVortexSolution(void) {} + +void CInviscidVortexSolution::GetBCState(const su2double* val_coords, const su2double val_t, + su2double* val_solution) const { /*--- For the case that the inviscid vortex is run with boundary conditions (other possibility is with periodic conditions), the exact solution is prescribed on the boundaries. ---*/ GetSolution(val_coords, val_t, val_solution); } -void CInviscidVortexSolution::GetSolution(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const { - +void CInviscidVortexSolution::GetSolution(const su2double* val_coords, const su2double val_t, + su2double* val_solution) const { /* Compute the free stream velocities in x- and y-direction. */ - const su2double VelInf = MachVortex*sqrt(Gamma); - const su2double uInf = VelInf*cos(thetaVortex*PI_NUMBER/180.0); - const su2double vInf = VelInf*sin(thetaVortex*PI_NUMBER/180.0); + const su2double VelInf = MachVortex * sqrt(Gamma); + const su2double uInf = VelInf * cos(thetaVortex * PI_NUMBER / 180.0); + const su2double vInf = VelInf * sin(thetaVortex * PI_NUMBER / 180.0); /* Compute the coordinates relative to the center of the vortex. */ - const su2double dx = val_coords[0] - (x0Vortex + val_t*uInf); - const su2double dy = val_coords[1] - (y0Vortex + val_t*vInf); + const su2double dx = val_coords[0] - (x0Vortex + val_t * uInf); + const su2double dy = val_coords[1] - (y0Vortex + val_t * vInf); /* Compute the components of the velocity. */ - su2double f = 1.0 - (dx*dx + dy*dy)/(RVortex*RVortex); - su2double t1 = epsVortex*dy*exp(0.5*f)/(2.0*PI_NUMBER*RVortex); - su2double u = uInf - VelInf*t1; + su2double f = 1.0 - (dx * dx + dy * dy) / (RVortex * RVortex); + su2double t1 = epsVortex * dy * exp(0.5 * f) / (2.0 * PI_NUMBER * RVortex); + su2double u = uInf - VelInf * t1; - t1 = epsVortex*dx*exp(0.5*f)/(2.0*PI_NUMBER*RVortex); - su2double v = vInf + VelInf*t1; + t1 = epsVortex * dx * exp(0.5 * f) / (2.0 * PI_NUMBER * RVortex); + su2double v = vInf + VelInf * t1; /* Compute the density and the pressure. */ - t1 = 1.0 - epsVortex*epsVortex*Gm1 - * MachVortex*MachVortex*exp(f)/(8.0*PI_NUMBER*PI_NUMBER); + t1 = 1.0 - epsVortex * epsVortex * Gm1 * MachVortex * MachVortex * exp(f) / (8.0 * PI_NUMBER * PI_NUMBER); - su2double rho = pow(t1,ovGm1); - su2double p = pow(t1,gamOvGm1); + su2double rho = pow(t1, ovGm1); + su2double p = pow(t1, gamOvGm1); /* Compute the conservative variables. Note that both 2D and 3D cases are treated correctly. */ - val_solution[0] = rho; - val_solution[1] = rho*u; - val_solution[2] = rho*v; - val_solution[3] = 0.0; - val_solution[nVar-1] = p*ovGm1 + 0.5*rho*(u*u + v*v); + val_solution[0] = rho; + val_solution[1] = rho * u; + val_solution[2] = rho * v; + val_solution[3] = 0.0; + val_solution[nVar - 1] = p * ovGm1 + 0.5 * rho * (u * u + v * v); } diff --git a/Common/src/toolboxes/MMS/CMMSIncEulerSolution.cpp b/Common/src/toolboxes/MMS/CMMSIncEulerSolution.cpp index 2352988dcdc..9c6e28ee18e 100644 --- a/Common/src/toolboxes/MMS/CMMSIncEulerSolution.cpp +++ b/Common/src/toolboxes/MMS/CMMSIncEulerSolution.cpp @@ -27,14 +27,11 @@ #include "../../../include/toolboxes/MMS/CMMSIncEulerSolution.hpp" -CMMSIncEulerSolution::CMMSIncEulerSolution(void) : CVerificationSolution() { } - -CMMSIncEulerSolution::CMMSIncEulerSolution(unsigned short val_nDim, - unsigned short val_nVar, - unsigned short val_iMesh, - CConfig* config) -: CVerificationSolution(val_nDim, val_nVar, val_iMesh, config) { +CMMSIncEulerSolution::CMMSIncEulerSolution(void) : CVerificationSolution() {} +CMMSIncEulerSolution::CMMSIncEulerSolution(unsigned short val_nDim, unsigned short val_nVar, unsigned short val_iMesh, + CConfig* config) + : CVerificationSolution(val_nDim, val_nVar, val_iMesh, config) { /*--- Write a message that the solution is initialized for the manufactured solution for the incompressible Navier-Stokes equations. ---*/ if ((rank == MASTER_NODE) && (val_iMesh == MESH_0)) { @@ -46,7 +43,7 @@ CMMSIncEulerSolution::CMMSIncEulerSolution(unsigned short val_nDim, } /*--- Coefficients, needed to determine the solution. ---*/ - Density = config->GetDensity_FreeStreamND(); + Density = config->GetDensity_FreeStreamND(); Temperature = config->GetTemperature_FreeStreamND(); /*--- Constants, which describe this manufactured solution. This is a @@ -55,85 +52,80 @@ CMMSIncEulerSolution::CMMSIncEulerSolution(unsigned short val_nDim, Knupp P, "Code verification by the method of manufactured solutions," SAND 2000-1444, Sandia National Laboratories, Albuquerque, NM, 2000. ---*/ - P_0 = 1.0; - u_0 = 1.0; - v_0 = 1.0; + P_0 = 1.0; + u_0 = 1.0; + v_0 = 1.0; epsilon = 0.001; /*--- Perform some sanity and error checks for this solution here. ---*/ - if(config->GetTime_Marching() != TIME_MARCHING::STEADY) - SU2_MPI::Error("Steady mode must be selected for the MMS incompressible Euler case", - CURRENT_FUNCTION); + if (config->GetTime_Marching() != TIME_MARCHING::STEADY) + SU2_MPI::Error("Steady mode must be selected for the MMS incompressible Euler case", CURRENT_FUNCTION); - if(Kind_Solver != MAIN_SOLVER::INC_EULER && Kind_Solver != MAIN_SOLVER::INC_NAVIER_STOKES && Kind_Solver != MAIN_SOLVER::INC_RANS ) + if (Kind_Solver != MAIN_SOLVER::INC_EULER && Kind_Solver != MAIN_SOLVER::INC_NAVIER_STOKES && + Kind_Solver != MAIN_SOLVER::INC_RANS) SU2_MPI::Error("Incompressible flow equations must be selected for the MMS incompressible Euler case", CURRENT_FUNCTION); - if(Kind_Solver != MAIN_SOLVER::INC_EULER) - SU2_MPI::Error("Euler equations must be selected for the MMS incompressible Euler case", - CURRENT_FUNCTION); + if (Kind_Solver != MAIN_SOLVER::INC_EULER) + SU2_MPI::Error("Euler equations must be selected for the MMS incompressible Euler case", CURRENT_FUNCTION); - if(config->GetKind_FluidModel() != CONSTANT_DENSITY) + if (config->GetKind_FluidModel() != CONSTANT_DENSITY) SU2_MPI::Error("Constant density fluid model must be selected for the MMS incompressible Euler case", CURRENT_FUNCTION); - if(config->GetEnergy_Equation()) + if (config->GetEnergy_Equation()) SU2_MPI::Error("Energy equation must be disabled (isothermal) for the MMS incompressible Euler case", CURRENT_FUNCTION); } -CMMSIncEulerSolution::~CMMSIncEulerSolution(void) { } - -void CMMSIncEulerSolution::GetBCState(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const { +CMMSIncEulerSolution::~CMMSIncEulerSolution(void) {} +void CMMSIncEulerSolution::GetBCState(const su2double* val_coords, const su2double val_t, + su2double* val_solution) const { /*--- The exact solution is prescribed on the boundaries. ---*/ GetSolution(val_coords, val_t, val_solution); } -void CMMSIncEulerSolution::GetSolution(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const { - +void CMMSIncEulerSolution::GetSolution(const su2double* val_coords, const su2double val_t, + su2double* val_solution) const { /* Easier storage of the x- and y-coordinates. */ const su2double x = val_coords[0]; const su2double y = val_coords[1]; /* Compute the primitives from the defined solution. */ - const su2double u = u_0*(sin(x*x + y*y) + epsilon); - const su2double v = v_0*(cos(x*x + y*y) + epsilon); - const su2double p = P_0*(sin(x*x + y*y) + 2.0); + const su2double u = u_0 * (sin(x * x + y * y) + epsilon); + const su2double v = v_0 * (cos(x * x + y * y) + epsilon); + const su2double p = P_0 * (sin(x * x + y * y) + 2.0); /* For the incompressible solver, we return the primitive variables directly, as they are used for the working variables in the solver. Note that the implementation below is valid for both 2D and 3D. */ - val_solution[0] = p; - val_solution[1] = u; - val_solution[2] = v; - val_solution[3] = 0.0; - val_solution[nVar-1] = Temperature; - + val_solution[0] = p; + val_solution[1] = u; + val_solution[2] = v; + val_solution[3] = 0.0; + val_solution[nVar - 1] = Temperature; } -void CMMSIncEulerSolution::GetMMSSourceTerm(const su2double *val_coords, - const su2double val_t, - su2double *val_source) const { - +void CMMSIncEulerSolution::GetMMSSourceTerm(const su2double* val_coords, const su2double val_t, + su2double* val_source) const { /*--- Easier storage of the x- and y-coordinates. ---*/ const su2double x = val_coords[0]; const su2double y = val_coords[1]; /*--- The expressions for the source terms are generated automatically by the sympy package in python.---*/ - val_source[0] = 2*Density*(u_0*x*cos(pow(x, 2) + pow(y, 2)) - v_0*y*sin(pow(x, 2) + pow(y, 2))); - val_source[1] = 4*Density*pow(u_0, 2)*x*(epsilon + sin(pow(x, 2) + pow(y, 2)))*cos(pow(x, 2) + pow(y, 2)) - 2*Density*u_0*v_0*y*(epsilon + sin(pow(x, 2) + pow(y, 2)))*sin(pow(x, 2) + pow(y, 2)) + 2*Density*u_0*v_0*y*(epsilon + cos(pow(x, 2) + pow(y, 2)))*cos(pow(x, 2) + pow(y, 2)) + 2*P_0*x*cos(pow(x, 2) + pow(y, 2)); - val_source[2] = -2*Density*u_0*v_0*x*(epsilon + sin(pow(x, 2) + pow(y, 2)))*sin(pow(x, 2) + pow(y, 2)) + 2*Density*u_0*v_0*x*(epsilon + cos(pow(x, 2) + pow(y, 2)))*cos(pow(x, 2) + pow(y, 2)) - 4*Density*pow(v_0, 2)*y*(epsilon + cos(pow(x, 2) + pow(y, 2)))*sin(pow(x, 2) + pow(y, 2)) + 2*P_0*y*cos(pow(x, 2) + pow(y, 2)); - val_source[3] = 0.0; - val_source[nVar-1] = 0.0; - + val_source[0] = 2 * Density * (u_0 * x * cos(pow(x, 2) + pow(y, 2)) - v_0 * y * sin(pow(x, 2) + pow(y, 2))); + val_source[1] = 4 * Density * pow(u_0, 2) * x * (epsilon + sin(pow(x, 2) + pow(y, 2))) * cos(pow(x, 2) + pow(y, 2)) - + 2 * Density * u_0 * v_0 * y * (epsilon + sin(pow(x, 2) + pow(y, 2))) * sin(pow(x, 2) + pow(y, 2)) + + 2 * Density * u_0 * v_0 * y * (epsilon + cos(pow(x, 2) + pow(y, 2))) * cos(pow(x, 2) + pow(y, 2)) + + 2 * P_0 * x * cos(pow(x, 2) + pow(y, 2)); + val_source[2] = -2 * Density * u_0 * v_0 * x * (epsilon + sin(pow(x, 2) + pow(y, 2))) * sin(pow(x, 2) + pow(y, 2)) + + 2 * Density * u_0 * v_0 * x * (epsilon + cos(pow(x, 2) + pow(y, 2))) * cos(pow(x, 2) + pow(y, 2)) - + 4 * Density * pow(v_0, 2) * y * (epsilon + cos(pow(x, 2) + pow(y, 2))) * sin(pow(x, 2) + pow(y, 2)) + + 2 * P_0 * y * cos(pow(x, 2) + pow(y, 2)); + val_source[3] = 0.0; + val_source[nVar - 1] = 0.0; } -bool CMMSIncEulerSolution::IsManufacturedSolution(void) const { - return true; -} +bool CMMSIncEulerSolution::IsManufacturedSolution(void) const { return true; } diff --git a/Common/src/toolboxes/MMS/CMMSIncNSSolution.cpp b/Common/src/toolboxes/MMS/CMMSIncNSSolution.cpp index 8cd7ed00b89..8cf32d65407 100644 --- a/Common/src/toolboxes/MMS/CMMSIncNSSolution.cpp +++ b/Common/src/toolboxes/MMS/CMMSIncNSSolution.cpp @@ -27,14 +27,11 @@ #include "../../../include/toolboxes/MMS/CMMSIncNSSolution.hpp" -CMMSIncNSSolution::CMMSIncNSSolution(void) : CVerificationSolution() { } - -CMMSIncNSSolution::CMMSIncNSSolution(unsigned short val_nDim, - unsigned short val_nVar, - unsigned short val_iMesh, - CConfig* config) -: CVerificationSolution(val_nDim, val_nVar, val_iMesh, config) { +CMMSIncNSSolution::CMMSIncNSSolution(void) : CVerificationSolution() {} +CMMSIncNSSolution::CMMSIncNSSolution(unsigned short val_nDim, unsigned short val_nVar, unsigned short val_iMesh, + CConfig* config) + : CVerificationSolution(val_nDim, val_nVar, val_iMesh, config) { /*--- Write a message that the solution is initialized for the manufactured solution for the incompressible Navier-Stokes equations. ---*/ if ((rank == MASTER_NODE) && (val_iMesh == MESH_0)) { @@ -46,8 +43,8 @@ CMMSIncNSSolution::CMMSIncNSSolution(unsigned short val_nDim, } /*--- Coefficients, needed to determine the solution. ---*/ - Viscosity = config->GetViscosity_FreeStreamND(); - Density = config->GetDensity_FreeStreamND(); + Viscosity = config->GetViscosity_FreeStreamND(); + Density = config->GetDensity_FreeStreamND(); Temperature = config->GetTemperature_FreeStreamND(); /*--- Constants, which describe this manufactured solution. This is a @@ -56,89 +53,93 @@ CMMSIncNSSolution::CMMSIncNSSolution(unsigned short val_nDim, Knupp P, "Code verification by the method of manufactured solutions," SAND 2000-1444, Sandia National Laboratories, Albuquerque, NM, 2000. ---*/ - P_0 = 1.0; - u_0 = 1.0; - v_0 = 1.0; + P_0 = 1.0; + u_0 = 1.0; + v_0 = 1.0; epsilon = 0.001; /*--- Perform some sanity and error checks for this solution here. ---*/ - if(config->GetTime_Marching() != TIME_MARCHING::STEADY) - SU2_MPI::Error("Steady mode must be selected for the MMS incompressible NS case", - CURRENT_FUNCTION); + if (config->GetTime_Marching() != TIME_MARCHING::STEADY) + SU2_MPI::Error("Steady mode must be selected for the MMS incompressible NS case", CURRENT_FUNCTION); - if(Kind_Solver != MAIN_SOLVER::INC_EULER && Kind_Solver != MAIN_SOLVER::INC_NAVIER_STOKES && Kind_Solver != MAIN_SOLVER::INC_RANS ) + if (Kind_Solver != MAIN_SOLVER::INC_EULER && Kind_Solver != MAIN_SOLVER::INC_NAVIER_STOKES && + Kind_Solver != MAIN_SOLVER::INC_RANS) SU2_MPI::Error("Incompressible flow equations must be selected for the MMS incompressible NS case", CURRENT_FUNCTION); - if(Kind_Solver != MAIN_SOLVER::INC_NAVIER_STOKES) - SU2_MPI::Error("Navier Stokes equations must be selected for the MMS incompressible NS case", - CURRENT_FUNCTION); + if (Kind_Solver != MAIN_SOLVER::INC_NAVIER_STOKES) + SU2_MPI::Error("Navier Stokes equations must be selected for the MMS incompressible NS case", CURRENT_FUNCTION); - if(config->GetKind_FluidModel() != CONSTANT_DENSITY) + if (config->GetKind_FluidModel() != CONSTANT_DENSITY) SU2_MPI::Error("Constant density fluid model must be selected for the MMS incompressible NS case", CURRENT_FUNCTION); - if(config->GetKind_ViscosityModel() != VISCOSITYMODEL::CONSTANT) - SU2_MPI::Error("Constant viscosity must be selected for the MMS incompressible NS case", - CURRENT_FUNCTION); + if (config->GetKind_ViscosityModel() != VISCOSITYMODEL::CONSTANT) + SU2_MPI::Error("Constant viscosity must be selected for the MMS incompressible NS case", CURRENT_FUNCTION); - if(config->GetEnergy_Equation()) + if (config->GetEnergy_Equation()) SU2_MPI::Error("Energy equation must be disabled (isothermal) for the MMS incompressible NS case", CURRENT_FUNCTION); } -CMMSIncNSSolution::~CMMSIncNSSolution(void) { } - -void CMMSIncNSSolution::GetBCState(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const { +CMMSIncNSSolution::~CMMSIncNSSolution(void) {} +void CMMSIncNSSolution::GetBCState(const su2double* val_coords, const su2double val_t, su2double* val_solution) const { /*--- The exact solution is prescribed on the boundaries. ---*/ GetSolution(val_coords, val_t, val_solution); } -void CMMSIncNSSolution::GetSolution(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const { - +void CMMSIncNSSolution::GetSolution(const su2double* val_coords, const su2double val_t, su2double* val_solution) const { /* Easier storage of the x- and y-coordinates. */ const su2double x = val_coords[0]; const su2double y = val_coords[1]; /* Compute the primitives from the defined solution. */ - const su2double u = u_0*(sin(x*x + y*y) + epsilon); - const su2double v = v_0*(cos(x*x + y*y) + epsilon); - const su2double p = P_0*(sin(x*x + y*y) + 2.0); + const su2double u = u_0 * (sin(x * x + y * y) + epsilon); + const su2double v = v_0 * (cos(x * x + y * y) + epsilon); + const su2double p = P_0 * (sin(x * x + y * y) + 2.0); /* For the incompressible solver, we return the primitive variables directly, as they are used for the working variables in the solver. Note that the implementation below is valid for both 2D and 3D. */ - val_solution[0] = p; - val_solution[1] = u; - val_solution[2] = v; - val_solution[3] = 0.0; - val_solution[nVar-1] = Temperature; - + val_solution[0] = p; + val_solution[1] = u; + val_solution[2] = v; + val_solution[3] = 0.0; + val_solution[nVar - 1] = Temperature; } -void CMMSIncNSSolution::GetMMSSourceTerm(const su2double *val_coords, - const su2double val_t, - su2double *val_source) const { - +void CMMSIncNSSolution::GetMMSSourceTerm(const su2double* val_coords, const su2double val_t, + su2double* val_source) const { /*--- Easier storage of the x- and y-coordinates. ---*/ const su2double x = val_coords[0]; const su2double y = val_coords[1]; /*--- The expressions for the source terms are generated automatically by the sympy package in python.---*/ - val_source[0] = 2*Density*(u_0*x*cos(pow(x, 2) + pow(y, 2)) - v_0*y*sin(pow(x, 2) + pow(y, 2))); - val_source[1] = 4*Density*pow(u_0, 2)*x*(epsilon + sin(pow(x, 2) + pow(y, 2)))*cos(pow(x, 2) + pow(y, 2)) - 2*Density*u_0*v_0*y*(epsilon + sin(pow(x, 2) + pow(y, 2)))*sin(pow(x, 2) + pow(y, 2)) + 2*Density*u_0*v_0*y*(epsilon + cos(pow(x, 2) + pow(y, 2)))*cos(pow(x, 2) + pow(y, 2)) + 2*P_0*x*cos(pow(x, 2) + pow(y, 2)) - 0.666666666666667*Viscosity*(-8.0*u_0*pow(x, 2)*sin(pow(x, 2) + pow(y, 2)) + 4.0*u_0*cos(pow(x, 2) + pow(y, 2)) + 4*v_0*x*y*cos(pow(x, 2) + pow(y, 2))) + 2*Viscosity*(2*u_0*pow(y, 2)*sin(pow(x, 2) + pow(y, 2)) - u_0*cos(pow(x, 2) + pow(y, 2)) + 2*v_0*x*y*cos(pow(x, 2) + pow(y, 2))); - val_source[2] = -2*Density*u_0*v_0*x*(epsilon + sin(pow(x, 2) + pow(y, 2)))*sin(pow(x, 2) + pow(y, 2)) + 2*Density*u_0*v_0*x*(epsilon + cos(pow(x, 2) + pow(y, 2)))*cos(pow(x, 2) + pow(y, 2)) - 4*Density*pow(v_0, 2)*y*(epsilon + cos(pow(x, 2) + pow(y, 2)))*sin(pow(x, 2) + pow(y, 2)) + 2*P_0*y*cos(pow(x, 2) + pow(y, 2)) + 0.666666666666667*Viscosity*(-4*u_0*x*y*sin(pow(x, 2) + pow(y, 2)) + 8.0*v_0*pow(y, 2)*cos(pow(x, 2) + pow(y, 2)) + 4.0*v_0*sin(pow(x, 2) + pow(y, 2))) + 2*Viscosity*(2*u_0*x*y*sin(pow(x, 2) + pow(y, 2)) + 2*v_0*pow(x, 2)*cos(pow(x, 2) + pow(y, 2)) + v_0*sin(pow(x, 2) + pow(y, 2))); - val_source[3] = 0.0; - val_source[nVar-1] = 0.0; - + val_source[0] = 2 * Density * (u_0 * x * cos(pow(x, 2) + pow(y, 2)) - v_0 * y * sin(pow(x, 2) + pow(y, 2))); + val_source[1] = 4 * Density * pow(u_0, 2) * x * (epsilon + sin(pow(x, 2) + pow(y, 2))) * cos(pow(x, 2) + pow(y, 2)) - + 2 * Density * u_0 * v_0 * y * (epsilon + sin(pow(x, 2) + pow(y, 2))) * sin(pow(x, 2) + pow(y, 2)) + + 2 * Density * u_0 * v_0 * y * (epsilon + cos(pow(x, 2) + pow(y, 2))) * cos(pow(x, 2) + pow(y, 2)) + + 2 * P_0 * x * cos(pow(x, 2) + pow(y, 2)) - + 0.666666666666667 * Viscosity * + (-8.0 * u_0 * pow(x, 2) * sin(pow(x, 2) + pow(y, 2)) + 4.0 * u_0 * cos(pow(x, 2) + pow(y, 2)) + + 4 * v_0 * x * y * cos(pow(x, 2) + pow(y, 2))) + + 2 * Viscosity * + (2 * u_0 * pow(y, 2) * sin(pow(x, 2) + pow(y, 2)) - u_0 * cos(pow(x, 2) + pow(y, 2)) + + 2 * v_0 * x * y * cos(pow(x, 2) + pow(y, 2))); + val_source[2] = -2 * Density * u_0 * v_0 * x * (epsilon + sin(pow(x, 2) + pow(y, 2))) * sin(pow(x, 2) + pow(y, 2)) + + 2 * Density * u_0 * v_0 * x * (epsilon + cos(pow(x, 2) + pow(y, 2))) * cos(pow(x, 2) + pow(y, 2)) - + 4 * Density * pow(v_0, 2) * y * (epsilon + cos(pow(x, 2) + pow(y, 2))) * sin(pow(x, 2) + pow(y, 2)) + + 2 * P_0 * y * cos(pow(x, 2) + pow(y, 2)) + + 0.666666666666667 * Viscosity * + (-4 * u_0 * x * y * sin(pow(x, 2) + pow(y, 2)) + + 8.0 * v_0 * pow(y, 2) * cos(pow(x, 2) + pow(y, 2)) + 4.0 * v_0 * sin(pow(x, 2) + pow(y, 2))) + + 2 * Viscosity * + (2 * u_0 * x * y * sin(pow(x, 2) + pow(y, 2)) + 2 * v_0 * pow(x, 2) * cos(pow(x, 2) + pow(y, 2)) + + v_0 * sin(pow(x, 2) + pow(y, 2))); + val_source[3] = 0.0; + val_source[nVar - 1] = 0.0; } -bool CMMSIncNSSolution::IsManufacturedSolution(void) const { - return true; -} +bool CMMSIncNSSolution::IsManufacturedSolution(void) const { return true; } diff --git a/Common/src/toolboxes/MMS/CMMSNSTwoHalfCirclesSolution.cpp b/Common/src/toolboxes/MMS/CMMSNSTwoHalfCirclesSolution.cpp index c21f7d927a3..70f6cee1164 100644 --- a/Common/src/toolboxes/MMS/CMMSNSTwoHalfCirclesSolution.cpp +++ b/Common/src/toolboxes/MMS/CMMSNSTwoHalfCirclesSolution.cpp @@ -27,14 +27,11 @@ #include "../../../include/toolboxes/MMS/CMMSNSTwoHalfCirclesSolution.hpp" -CMMSNSTwoHalfCirclesSolution::CMMSNSTwoHalfCirclesSolution(void) : CVerificationSolution() { } - -CMMSNSTwoHalfCirclesSolution::CMMSNSTwoHalfCirclesSolution(unsigned short val_nDim, - unsigned short val_nVar, - unsigned short val_iMesh, - CConfig* config) - : CVerificationSolution(val_nDim, val_nVar, val_iMesh, config) { +CMMSNSTwoHalfCirclesSolution::CMMSNSTwoHalfCirclesSolution(void) : CVerificationSolution() {} +CMMSNSTwoHalfCirclesSolution::CMMSNSTwoHalfCirclesSolution(unsigned short val_nDim, unsigned short val_nVar, + unsigned short val_iMesh, CConfig* config) + : CVerificationSolution(val_nDim, val_nVar, val_iMesh, config) { /*--- Write a message that the solution is initialized for the manufactured solution for the Navier-Stokes equations between two half circles. ---*/ if ((rank == MASTER_NODE) && (val_iMesh == MESH_0)) { @@ -48,17 +45,17 @@ CMMSNSTwoHalfCirclesSolution::CMMSNSTwoHalfCirclesSolution(unsigned short val_nD /*--- Coefficients, needed to determine the solution. ---*/ const su2double Prandtl = config->GetPrandtl_Lam(); - RGas = config->GetGas_Constant(); - Gamma = config->GetGamma(); - Viscosity = config->GetMu_Constant(); - Conductivity = Viscosity*Gamma*RGas/(Prandtl*(Gamma-1.0)); + RGas = config->GetGas_Constant(); + Gamma = config->GetGamma(); + Viscosity = config->GetMu_Constant(); + Conductivity = Viscosity * Gamma * RGas / (Prandtl * (Gamma - 1.0)); /*--- Initialize TWall to the default value of 300 K (in case the outer wall is not modelled as an isothermal wall) and try to retrieve the wall temperature from the boundary conditions. ---*/ TWall = 300.0; - for(unsigned short iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { - if(config->GetMarker_All_KindBC(iMarker) == ISOTHERMAL) { + for (unsigned short iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { + if (config->GetMarker_All_KindBC(iMarker) == ISOTHERMAL) { const string Marker_Tag = config->GetMarker_All_TagBound(iMarker); TWall = config->GetIsothermal_Temperature(Marker_Tag); } @@ -66,100 +63,88 @@ CMMSNSTwoHalfCirclesSolution::CMMSNSTwoHalfCirclesSolution(unsigned short val_nD /*--- Get the reference values for pressure, density and velocity. ---*/ Pressure_Ref = config->GetPressure_Ref(); - Density_Ref = config->GetDensity_Ref(); + Density_Ref = config->GetDensity_Ref(); Velocity_Ref = config->GetVelocity_Ref(); /*--- The constants for the density and velocities. ---*/ - rho_0 = 1.25; - u_0 = 135.78; - v_0 = -67.61; + rho_0 = 1.25; + u_0 = 135.78; + v_0 = -67.61; /*--- The constants for the temperature solution. ---*/ - a_T1 = 1.05; + a_T1 = 1.05; a_T2 = -0.85; /*--- Perform some sanity and error checks for this solution here. ---*/ - if(config->GetTime_Marching() != TIME_MARCHING::STEADY) - SU2_MPI::Error("Steady mode must be selected for the MMS NS Two Half Circles case", + if (config->GetTime_Marching() != TIME_MARCHING::STEADY) + SU2_MPI::Error("Steady mode must be selected for the MMS NS Two Half Circles case", CURRENT_FUNCTION); + + if (Kind_Solver != MAIN_SOLVER::EULER && Kind_Solver != MAIN_SOLVER::NAVIER_STOKES && + Kind_Solver != MAIN_SOLVER::RANS && Kind_Solver != MAIN_SOLVER::FEM_EULER && + Kind_Solver != MAIN_SOLVER::FEM_NAVIER_STOKES && Kind_Solver != MAIN_SOLVER::FEM_RANS && + Kind_Solver != MAIN_SOLVER::FEM_LES) + SU2_MPI::Error("Compressible flow equations must be selected for the MMS NS Two Half Circles case", CURRENT_FUNCTION); - if(Kind_Solver != MAIN_SOLVER::EULER && Kind_Solver != MAIN_SOLVER::NAVIER_STOKES && Kind_Solver != MAIN_SOLVER::RANS && - Kind_Solver != MAIN_SOLVER::FEM_EULER && Kind_Solver != MAIN_SOLVER::FEM_NAVIER_STOKES && Kind_Solver != MAIN_SOLVER::FEM_RANS && - Kind_Solver != MAIN_SOLVER::FEM_LES) SU2_MPI::Error("Compressible flow equations must be selected for the MMS NS Two Half Circles case", - CURRENT_FUNCTION); + if ((Kind_Solver != MAIN_SOLVER::NAVIER_STOKES) && (Kind_Solver != MAIN_SOLVER::FEM_NAVIER_STOKES)) + SU2_MPI::Error("Navier Stokes equations must be selected for the MMS NS Two Half Circles case", CURRENT_FUNCTION); - if((Kind_Solver != MAIN_SOLVER::NAVIER_STOKES) && - (Kind_Solver != MAIN_SOLVER::FEM_NAVIER_STOKES)) - SU2_MPI::Error("Navier Stokes equations must be selected for the MMS NS Two Half Circles case", - CURRENT_FUNCTION); + if ((config->GetKind_FluidModel() != STANDARD_AIR) && (config->GetKind_FluidModel() != IDEAL_GAS)) + SU2_MPI::Error("Standard air or ideal gas must be selected for the MMS NS Two Half Circles case", CURRENT_FUNCTION); - if((config->GetKind_FluidModel() != STANDARD_AIR) && - (config->GetKind_FluidModel() != IDEAL_GAS)) - SU2_MPI::Error("Standard air or ideal gas must be selected for the MMS NS Two Half Circles case", - CURRENT_FUNCTION); + if (config->GetKind_ViscosityModel() != VISCOSITYMODEL::CONSTANT) + SU2_MPI::Error("Sutherland must be selected for viscosity for the MMS NS Two Half Circles case", CURRENT_FUNCTION); - if(config->GetKind_ViscosityModel() != VISCOSITYMODEL::CONSTANT) - SU2_MPI::Error("Sutherland must be selected for viscosity for the MMS NS Two Half Circles case", - CURRENT_FUNCTION); - - if(config->GetKind_ConductivityModel() != CONDUCTIVITYMODEL::CONSTANT_PRANDTL) - SU2_MPI::Error("Constant Prandtl number must be selected for the MMS NS Two Half Circles case", - CURRENT_FUNCTION); + if (config->GetKind_ConductivityModel() != CONDUCTIVITYMODEL::CONSTANT_PRANDTL) + SU2_MPI::Error("Constant Prandtl number must be selected for the MMS NS Two Half Circles case", CURRENT_FUNCTION); } -CMMSNSTwoHalfCirclesSolution::~CMMSNSTwoHalfCirclesSolution(void) { } - -void CMMSNSTwoHalfCirclesSolution::GetBCState(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const { +CMMSNSTwoHalfCirclesSolution::~CMMSNSTwoHalfCirclesSolution(void) {} +void CMMSNSTwoHalfCirclesSolution::GetBCState(const su2double* val_coords, const su2double val_t, + su2double* val_solution) const { /*--- The exact solution is prescribed on the boundaries. ---*/ GetSolution(val_coords, val_t, val_solution); } -void CMMSNSTwoHalfCirclesSolution::GetSolution(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const { - +void CMMSNSTwoHalfCirclesSolution::GetSolution(const su2double* val_coords, const su2double val_t, + su2double* val_solution) const { /* Easier storage of the x- and y-coordinates. */ const su2double x = val_coords[0]; const su2double y = val_coords[1]; /* Determine the dimensional solution for the temperature. */ - const su2double Pi = PI_NUMBER; - const su2double r = sqrt(x*x + y*y); - const su2double fact = (r-1.0)*(r-1.0)/(a_T1 + a_T2); + const su2double Pi = PI_NUMBER; + const su2double r = sqrt(x * x + y * y); + const su2double fact = (r - 1.0) * (r - 1.0) / (a_T1 + a_T2); - su2double T = 0.25*TWall*(3.0 + fact*(a_T1*cos(Pi*(r-2.0)) - + a_T2*cos(Pi*(r-2.0)*2.0))); + su2double T = 0.25 * TWall * (3.0 + fact * (a_T1 * cos(Pi * (r - 2.0)) + a_T2 * cos(Pi * (r - 2.0) * 2.0))); /* Determine the dimensional solution for the velocities. */ - su2double u = u_0*(r-1.0)*(2.0-r)*4.0; - su2double v = v_0*(r-1.0)*(2.0-r)*4.0; + su2double u = u_0 * (r - 1.0) * (2.0 - r) * 4.0; + su2double v = v_0 * (r - 1.0) * (2.0 - r) * 4.0; /* Compute the pressure from the density and temperature. */ su2double rho = rho_0; - su2double p = rho*RGas*T; + su2double p = rho * RGas * T; /* Determine the non-dimensional solution. */ rho /= Density_Ref; - p /= Pressure_Ref; - u /= Velocity_Ref; - v /= Velocity_Ref; + p /= Pressure_Ref; + u /= Velocity_Ref; + v /= Velocity_Ref; /* Determine the non-dimensional conserved variables. Note that the implementation below is valid for both 2D and 3D. */ - val_solution[0] = rho; - val_solution[1] = rho*u; - val_solution[2] = rho*v; - val_solution[3] = 0.0; - val_solution[nDim+1] = p/(Gamma-1.0) + 0.5*rho*(u*u + v*v); + val_solution[0] = rho; + val_solution[1] = rho * u; + val_solution[2] = rho * v; + val_solution[3] = 0.0; + val_solution[nDim + 1] = p / (Gamma - 1.0) + 0.5 * rho * (u * u + v * v); } -void CMMSNSTwoHalfCirclesSolution::GetMMSSourceTerm(const su2double *val_coords, - const su2double val_t, - su2double *val_source) const { - +void CMMSNSTwoHalfCirclesSolution::GetMMSSourceTerm(const su2double* val_coords, const su2double val_t, + su2double* val_source) const { /*--- Abbreviate Pi and the coordinates. ---*/ const su2double Pi = PI_NUMBER; const su2double x = val_coords[0]; @@ -167,7 +152,7 @@ void CMMSNSTwoHalfCirclesSolution::GetMMSSourceTerm(const su2double *val_coords, /*--- The source code for the source terms is generated in Maple. See the file CMMSNSTwoHalfCirclesSolution.mw in the directory - CreateMMSSourceTerms for the details how to do this. ---*/ + CreateMMSSourceTerms for the details how to do this. ---*/ const su2double t1 = rho_0 * u_0; const su2double t2 = x * x; const su2double t3 = y * y; @@ -225,12 +210,14 @@ void CMMSNSTwoHalfCirclesSolution::GetMMSSourceTerm(const su2double *val_coords, const su2double t99 = t3 * u_0; const su2double t102 = t81 * t75; const su2double t105 = v_0 * x; - const su2double t113 = (0.4e1 * y * t102 * t105 - 0.8e1 * y * t65 * t105 - 0.4e1 * t6 * t75 * u_0 - + 0.4e1 * t102 * t99 - 0.8e1 * t65 * t99) * Viscosity; + const su2double t113 = (0.4e1 * y * t102 * t105 - 0.8e1 * y * t65 * t105 - 0.4e1 * t6 * t75 * u_0 + + 0.4e1 * t102 * t99 - 0.8e1 * t65 * t99) * + Viscosity; const su2double t121 = u_0 * y; const su2double t131 = t2 * v_0; - const su2double t137 = (0.4e1 * x * t102 * t121 - 0.8e1 * x * t65 * t121 - 0.4e1 * t6 * t75 * v_0 - + 0.4e1 * t102 * t131 - 0.8e1 * t65 * t131) * Viscosity; + const su2double t137 = (0.4e1 * x * t102 * t121 - 0.8e1 * x * t65 * t121 - 0.4e1 * t6 * t75 * v_0 + + 0.4e1 * t102 * t131 - 0.8e1 * t65 * t131) * + Viscosity; const su2double t138 = v_0 * v_0; const su2double t139 = t138 * rho_0; const su2double t141 = y * t26; @@ -263,11 +250,12 @@ void CMMSNSTwoHalfCirclesSolution::GetMMSSourceTerm(const su2double *val_coords, const su2double t254 = t30 * t138; const su2double t261 = t248 * t246 * t34 / 0.4e1 + 0.8e1 * (t25 * t252 + t25 * t254) * rho_0 + t246 * t34 / 0.4e1; const su2double t262 = v_0 * t261; - const su2double t267 = -0.4e1 * t193 * t2 * TWall * t65 - 0.4e1 * t193 * TWall * t65 * t3 - 0.8e1 * t193 * t201 - + 0.64e2 / 0.3e1 * t8 * t12 * t22 * t76 - 0.4e1 * t9 * t213 + 0.4e1 * t13 * t213 - - 0.4e1 * t17 * t218 + 0.4e1 * t19 * t218 + 0.128e3 / 0.3e1 * t8 * t11 * Viscosity * t6 * t161 * t138 - + 0.64e2 / 0.3e1 * t231 * t230 * t173 * t172 - 0.32e2 / 0.3e1 * t237 * t236 * t82 * t76 - - 0.4e1 * t8 * t236 * t113 - 0.4e1 * t19 * t262 + 0.4e1 * t17 * t262; + const su2double t267 = -0.4e1 * t193 * t2 * TWall * t65 - 0.4e1 * t193 * TWall * t65 * t3 - 0.8e1 * t193 * t201 + + 0.64e2 / 0.3e1 * t8 * t12 * t22 * t76 - 0.4e1 * t9 * t213 + 0.4e1 * t13 * t213 - + 0.4e1 * t17 * t218 + 0.4e1 * t19 * t218 + + 0.128e3 / 0.3e1 * t8 * t11 * Viscosity * t6 * t161 * t138 + + 0.64e2 / 0.3e1 * t231 * t230 * t173 * t172 - 0.32e2 / 0.3e1 * t237 * t236 * t82 * t76 - + 0.4e1 * t8 * t236 * t113 - 0.4e1 * t19 * t262 + 0.4e1 * t17 * t262; const su2double t271 = u_0 * t261; const su2double t277 = Pi * Pi; const su2double t278 = t6 * t277; @@ -283,37 +271,40 @@ void CMMSNSTwoHalfCirclesSolution::GetMMSSourceTerm(const su2double *val_coords, const su2double t321 = t65 * t172; const su2double t364 = t11 * t22; const su2double t367 = t11 * t138; - const su2double t391 = -0.4e1 * t8 * t230 * t137 + 0.4e1 * t9 * t271 - 0.4e1 * t13 * t271 - - 0.4e1 * t300 * (-t281 * y * t278 + t11 * a_T2 * y * t285 - Pi * t16 * t183 - - 0.2e1 * a_T2 * t51 * y * t292 - t151 / 0.2e1) * t11 * TWall * t16 - + 0.4e1 * t300 * t190 * t11 * TWall * t81 * t3 + 0.32e2 / 0.3e1 * t237 * t311 * t310 - - 0.64e2 / 0.3e1 * t317 * t316 * y * t168 - 0.64e2 / 0.3e1 * t231 * t316 * t321 - + 0.64e2 / 0.3e1 * y * t11 * t316 * t321 - 0.4e1 * t300 * x * (-t281 * x * t278 - + t11 * a_T2 * x * t285 - Pi * t7 * t183 - 0.2e1 * a_T2 * t51 * x * t292 - t53 / 0.2e1) * t201 - + 0.4e1 * t300 * t2 * t190 * t11 * TWall * t81 + 0.64e2 / 0.3e1 * t317 * u_0 * t70 * x * t66 - - 0.32e2 / 0.3e1 * x * t11 * t311 * t310 + 0.4e1 * t317 * u_0 * (t248 * t62 * t34 / 0.4e1 - + 0.16e2 * (-t9 * t252 - t9 * t254 + t27 * t364 + t27 * t367) * rho_0 + t64) - + 0.4e1 * t317 * v_0 * (t248 * t158 * t34 / 0.4e1 - + 0.16e2 * (t141 * t364 + t141 * t367 - t17 * t252 - t17 * t254) * rho_0 + t160); + const su2double t391 = + -0.4e1 * t8 * t230 * t137 + 0.4e1 * t9 * t271 - 0.4e1 * t13 * t271 - + 0.4e1 * t300 * + (-t281 * y * t278 + t11 * a_T2 * y * t285 - Pi * t16 * t183 - 0.2e1 * a_T2 * t51 * y * t292 - t151 / 0.2e1) * + t11 * TWall * t16 + + 0.4e1 * t300 * t190 * t11 * TWall * t81 * t3 + 0.32e2 / 0.3e1 * t237 * t311 * t310 - + 0.64e2 / 0.3e1 * t317 * t316 * y * t168 - 0.64e2 / 0.3e1 * t231 * t316 * t321 + + 0.64e2 / 0.3e1 * y * t11 * t316 * t321 - + 0.4e1 * t300 * x * + (-t281 * x * t278 + t11 * a_T2 * x * t285 - Pi * t7 * t183 - 0.2e1 * a_T2 * t51 * x * t292 - t53 / 0.2e1) * + t201 + + 0.4e1 * t300 * t2 * t190 * t11 * TWall * t81 + 0.64e2 / 0.3e1 * t317 * u_0 * t70 * x * t66 - + 0.32e2 / 0.3e1 * x * t11 * t311 * t310 + + 0.4e1 * t317 * u_0 * + (t248 * t62 * t34 / 0.4e1 + 0.16e2 * (-t9 * t252 - t9 * t254 + t27 * t364 + t27 * t367) * rho_0 + t64) + + 0.4e1 * t317 * v_0 * + (t248 * t158 * t34 / 0.4e1 + 0.16e2 * (t141 * t364 + t141 * t367 - t17 * t252 - t17 * t254) * rho_0 + t160); /*--- Set the source term, which is valid for both 2D and 3D cases. Note the scaling for the correct non-dimensionalization. ---*/ - val_source[0] = -0.4e1 * t13 * t1 + 0.4e1 * t9 * t1 + 0.4e1 * t17 * t15 - 0.4e1 * t19 * t15; - val_source[1] = 0.32e2 * t27 * t11 * t23 - 0.32e2 * t9 * t30 * t23 + t64 + 0.16e2 / 0.3e1 * t70 * x * t66 - + 0.16e2 / 0.3e1 * t6 * u_0 * t76 - 0.8e1 / 0.3e1 * x * t82 * t76 + 0.32e2 * t16 * t87 * t86 - - 0.32e2 * t16 * t92 * t91 - t113; - val_source[2] = 0.32e2 * t7 * t87 * t86 - 0.32e2 * t7 * t92 * t91 - t137 + 0.32e2 * t141 * t11 * t139 - - 0.32e2 * t17 * t30 * t139 + t160 + 0.32e2 / 0.3e1 * Viscosity * t6 * t161 * v_0 - - 0.16e2 / 0.3e1 * y * Viscosity * t168 + 0.16e2 / 0.3e1 * y * t173 * t172; - val_source[3] = 0.0; - val_source[nDim+1] = t267 + t391; - - val_source[0] /= Density_Ref*Velocity_Ref; - val_source[1] /= Pressure_Ref; - val_source[2] /= Pressure_Ref; - val_source[nDim+1] /= Velocity_Ref*Pressure_Ref; + val_source[0] = -0.4e1 * t13 * t1 + 0.4e1 * t9 * t1 + 0.4e1 * t17 * t15 - 0.4e1 * t19 * t15; + val_source[1] = 0.32e2 * t27 * t11 * t23 - 0.32e2 * t9 * t30 * t23 + t64 + 0.16e2 / 0.3e1 * t70 * x * t66 + + 0.16e2 / 0.3e1 * t6 * u_0 * t76 - 0.8e1 / 0.3e1 * x * t82 * t76 + 0.32e2 * t16 * t87 * t86 - + 0.32e2 * t16 * t92 * t91 - t113; + val_source[2] = 0.32e2 * t7 * t87 * t86 - 0.32e2 * t7 * t92 * t91 - t137 + 0.32e2 * t141 * t11 * t139 - + 0.32e2 * t17 * t30 * t139 + t160 + 0.32e2 / 0.3e1 * Viscosity * t6 * t161 * v_0 - + 0.16e2 / 0.3e1 * y * Viscosity * t168 + 0.16e2 / 0.3e1 * y * t173 * t172; + val_source[3] = 0.0; + val_source[nDim + 1] = t267 + t391; + + val_source[0] /= Density_Ref * Velocity_Ref; + val_source[1] /= Pressure_Ref; + val_source[2] /= Pressure_Ref; + val_source[nDim + 1] /= Velocity_Ref * Pressure_Ref; } -bool CMMSNSTwoHalfCirclesSolution::IsManufacturedSolution(void) const { - return true; -} +bool CMMSNSTwoHalfCirclesSolution::IsManufacturedSolution(void) const { return true; } diff --git a/Common/src/toolboxes/MMS/CMMSNSTwoHalfSpheresSolution.cpp b/Common/src/toolboxes/MMS/CMMSNSTwoHalfSpheresSolution.cpp index c6e7a5f005a..b86cc10b24a 100644 --- a/Common/src/toolboxes/MMS/CMMSNSTwoHalfSpheresSolution.cpp +++ b/Common/src/toolboxes/MMS/CMMSNSTwoHalfSpheresSolution.cpp @@ -27,14 +27,11 @@ #include "../../../include/toolboxes/MMS/CMMSNSTwoHalfSpheresSolution.hpp" -CMMSNSTwoHalfSpheresSolution::CMMSNSTwoHalfSpheresSolution(void) : CVerificationSolution() { } - -CMMSNSTwoHalfSpheresSolution::CMMSNSTwoHalfSpheresSolution(unsigned short val_nDim, - unsigned short val_nVar, - unsigned short val_iMesh, - CConfig* config) - : CVerificationSolution(val_nDim, val_nVar, val_iMesh, config) { +CMMSNSTwoHalfSpheresSolution::CMMSNSTwoHalfSpheresSolution(void) : CVerificationSolution() {} +CMMSNSTwoHalfSpheresSolution::CMMSNSTwoHalfSpheresSolution(unsigned short val_nDim, unsigned short val_nVar, + unsigned short val_iMesh, CConfig* config) + : CVerificationSolution(val_nDim, val_nVar, val_iMesh, config) { /*--- Write a message that the solution is initialized for the manufactured solution for the Navier-Stokes equations between two half spheres. ---*/ if ((rank == MASTER_NODE) && (val_iMesh == MESH_0)) { @@ -48,17 +45,17 @@ CMMSNSTwoHalfSpheresSolution::CMMSNSTwoHalfSpheresSolution(unsigned short val_nD /*--- Coefficients, needed to determine the solution. ---*/ const su2double Prandtl = config->GetPrandtl_Lam(); - RGas = config->GetGas_Constant(); - Gamma = config->GetGamma(); - Viscosity = config->GetMu_Constant(); - Conductivity = Viscosity*Gamma*RGas/(Prandtl*(Gamma-1.0)); + RGas = config->GetGas_Constant(); + Gamma = config->GetGamma(); + Viscosity = config->GetMu_Constant(); + Conductivity = Viscosity * Gamma * RGas / (Prandtl * (Gamma - 1.0)); /*--- Initialize TWall to the default value of 300 K (in case the outer wall is not modelled as an isothermal wall) and try to retrieve the wall temperature from the boundary conditions. ---*/ TWall = 300.0; - for(unsigned short iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { - if(config->GetMarker_All_KindBC(iMarker) == ISOTHERMAL) { + for (unsigned short iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { + if (config->GetMarker_All_KindBC(iMarker) == ISOTHERMAL) { const string Marker_Tag = config->GetMarker_All_TagBound(iMarker); TWall = config->GetIsothermal_Temperature(Marker_Tag); } @@ -66,108 +63,93 @@ CMMSNSTwoHalfSpheresSolution::CMMSNSTwoHalfSpheresSolution(unsigned short val_nD /*--- Get the reference values for pressure, density and velocity. ---*/ Pressure_Ref = config->GetPressure_Ref(); - Density_Ref = config->GetDensity_Ref(); + Density_Ref = config->GetDensity_Ref(); Velocity_Ref = config->GetVelocity_Ref(); /*--- The constants for the density and velocities. ---*/ - rho_0 = 1.25; - u_0 = 135.78; - v_0 = -67.61; - w_0 = 82.75; + rho_0 = 1.25; + u_0 = 135.78; + v_0 = -67.61; + w_0 = 82.75; /*--- The constants for the temperature solution. ---*/ - a_T1 = 1.05; + a_T1 = 1.05; a_T2 = -0.85; /*--- Perform some sanity and error checks for this solution here. ---*/ - if(nDim != 3) - SU2_MPI::Error("Grid must be 3D for the MMS NS Two Half Spheres case", - CURRENT_FUNCTION); + if (nDim != 3) SU2_MPI::Error("Grid must be 3D for the MMS NS Two Half Spheres case", CURRENT_FUNCTION); - if(config->GetTime_Marching() != TIME_MARCHING::STEADY) - SU2_MPI::Error("Steady mode must be selected for the MMS NS Two Half Spheres case", - CURRENT_FUNCTION); + if (config->GetTime_Marching() != TIME_MARCHING::STEADY) + SU2_MPI::Error("Steady mode must be selected for the MMS NS Two Half Spheres case", CURRENT_FUNCTION); - if(Kind_Solver != MAIN_SOLVER::EULER && Kind_Solver != MAIN_SOLVER::NAVIER_STOKES && Kind_Solver != MAIN_SOLVER::RANS && - Kind_Solver != MAIN_SOLVER::FEM_EULER && Kind_Solver != MAIN_SOLVER::FEM_NAVIER_STOKES && Kind_Solver != MAIN_SOLVER::FEM_RANS && - Kind_Solver != MAIN_SOLVER::FEM_LES) + if (Kind_Solver != MAIN_SOLVER::EULER && Kind_Solver != MAIN_SOLVER::NAVIER_STOKES && + Kind_Solver != MAIN_SOLVER::RANS && Kind_Solver != MAIN_SOLVER::FEM_EULER && + Kind_Solver != MAIN_SOLVER::FEM_NAVIER_STOKES && Kind_Solver != MAIN_SOLVER::FEM_RANS && + Kind_Solver != MAIN_SOLVER::FEM_LES) SU2_MPI::Error("Compressible flow equations must be selected for the MMS NS Two Half Spheres case", CURRENT_FUNCTION); - if((Kind_Solver != MAIN_SOLVER::NAVIER_STOKES) && - (Kind_Solver != MAIN_SOLVER::FEM_NAVIER_STOKES)) - SU2_MPI::Error("Navier Stokes equations must be selected for the MMS NS Two Half Spheres case", - CURRENT_FUNCTION); + if ((Kind_Solver != MAIN_SOLVER::NAVIER_STOKES) && (Kind_Solver != MAIN_SOLVER::FEM_NAVIER_STOKES)) + SU2_MPI::Error("Navier Stokes equations must be selected for the MMS NS Two Half Spheres case", CURRENT_FUNCTION); - if((config->GetKind_FluidModel() != STANDARD_AIR) && - (config->GetKind_FluidModel() != IDEAL_GAS)) - SU2_MPI::Error("Standard air or ideal gas must be selected for the MMS NS Two Half Spheres case", - CURRENT_FUNCTION); + if ((config->GetKind_FluidModel() != STANDARD_AIR) && (config->GetKind_FluidModel() != IDEAL_GAS)) + SU2_MPI::Error("Standard air or ideal gas must be selected for the MMS NS Two Half Spheres case", CURRENT_FUNCTION); - if(config->GetKind_ViscosityModel() != VISCOSITYMODEL::CONSTANT) - SU2_MPI::Error("Sutherland must be selected for viscosity for the MMS NS Two Half Spheres case", - CURRENT_FUNCTION); + if (config->GetKind_ViscosityModel() != VISCOSITYMODEL::CONSTANT) + SU2_MPI::Error("Sutherland must be selected for viscosity for the MMS NS Two Half Spheres case", CURRENT_FUNCTION); - if(config->GetKind_ConductivityModel() != CONDUCTIVITYMODEL::CONSTANT_PRANDTL) - SU2_MPI::Error("Constant Prandtl number must be selected for the MMS NS Two Half Spheres case", - CURRENT_FUNCTION); + if (config->GetKind_ConductivityModel() != CONDUCTIVITYMODEL::CONSTANT_PRANDTL) + SU2_MPI::Error("Constant Prandtl number must be selected for the MMS NS Two Half Spheres case", CURRENT_FUNCTION); } -CMMSNSTwoHalfSpheresSolution::~CMMSNSTwoHalfSpheresSolution(void) { } - -void CMMSNSTwoHalfSpheresSolution::GetBCState(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const { +CMMSNSTwoHalfSpheresSolution::~CMMSNSTwoHalfSpheresSolution(void) {} +void CMMSNSTwoHalfSpheresSolution::GetBCState(const su2double* val_coords, const su2double val_t, + su2double* val_solution) const { /*--- The exact solution is prescribed on the boundaries. ---*/ GetSolution(val_coords, val_t, val_solution); } -void CMMSNSTwoHalfSpheresSolution::GetSolution(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const { - +void CMMSNSTwoHalfSpheresSolution::GetSolution(const su2double* val_coords, const su2double val_t, + su2double* val_solution) const { /* Easier storage of the x-, y- and z-coordinates. */ const su2double x = val_coords[0]; const su2double y = val_coords[1]; const su2double z = val_coords[2]; /* Determine the dimensional solution for the temperature. */ - const su2double Pi = PI_NUMBER; - const su2double r = sqrt(x*x + y*y + z*z); - const su2double fact = (r-1.0)*(r-1.0)/(a_T1 + a_T2); + const su2double Pi = PI_NUMBER; + const su2double r = sqrt(x * x + y * y + z * z); + const su2double fact = (r - 1.0) * (r - 1.0) / (a_T1 + a_T2); - su2double T = 0.25*TWall*(3.0 + fact*(a_T1*cos(Pi*(r-2.0)) - + a_T2*cos(Pi*(r-2.0)*2.0))); + su2double T = 0.25 * TWall * (3.0 + fact * (a_T1 * cos(Pi * (r - 2.0)) + a_T2 * cos(Pi * (r - 2.0) * 2.0))); /* Determine the dimensional solution for the velocities. */ - su2double u = u_0*(r-1.0)*(2.0-r)*4.0; - su2double v = v_0*(r-1.0)*(2.0-r)*4.0; - su2double w = w_0*(r-1.0)*(2.0-r)*4.0; + su2double u = u_0 * (r - 1.0) * (2.0 - r) * 4.0; + su2double v = v_0 * (r - 1.0) * (2.0 - r) * 4.0; + su2double w = w_0 * (r - 1.0) * (2.0 - r) * 4.0; /* Compute the pressure from the density and temperature. */ su2double rho = rho_0; - su2double p = rho*RGas*T; + su2double p = rho * RGas * T; /* Determine the non-dimensional solution. */ rho /= Density_Ref; - p /= Pressure_Ref; - u /= Velocity_Ref; - v /= Velocity_Ref; - w /= Velocity_Ref; + p /= Pressure_Ref; + u /= Velocity_Ref; + v /= Velocity_Ref; + w /= Velocity_Ref; /* Determine the non-dimensional conserved variables. */ val_solution[0] = rho; - val_solution[1] = rho*u; - val_solution[2] = rho*v; - val_solution[3] = rho*w; - val_solution[4] = p/(Gamma-1.0) + 0.5*rho*(u*u + v*v + w*w); + val_solution[1] = rho * u; + val_solution[2] = rho * v; + val_solution[3] = rho * w; + val_solution[4] = p / (Gamma - 1.0) + 0.5 * rho * (u * u + v * v + w * w); } -void CMMSNSTwoHalfSpheresSolution::GetMMSSourceTerm(const su2double *val_coords, - const su2double val_t, - su2double *val_source) const { - +void CMMSNSTwoHalfSpheresSolution::GetMMSSourceTerm(const su2double* val_coords, const su2double val_t, + su2double* val_source) const { /*--- Abbreviate Pi and the coordinates. ---*/ const su2double Pi = PI_NUMBER; const su2double x = val_coords[0]; @@ -176,7 +158,7 @@ void CMMSNSTwoHalfSpheresSolution::GetMMSSourceTerm(const su2double *val_coords, /*--- The source code for the source terms is generated in Maple. See the file CMMSNSTwoHalfSpheresSolution.mw in the directory - CreateMMSSourceTerms for the details how to do this. ---*/ + CreateMMSSourceTerms for the details how to do this. ---*/ const su2double t1 = rho_0 * u_0; const su2double t2 = x * x; const su2double t3 = y * y; @@ -253,10 +235,11 @@ void CMMSNSTwoHalfSpheresSolution::GetMMSSourceTerm(const su2double *val_coords, const su2double t134 = t111 * t129; const su2double t135 = t89 * Viscosity; const su2double t136 = z * t135; - const su2double t139 = 0.32e2 * t34 * t12 * t30 - 0.32e2 * t10 * t37 * t30 + t71 + 0.16e2 / 0.3e1 * t78 * x * t73 - + 0.16e2 / 0.3e1 * t85 * t84 - 0.8e1 / 0.3e1 * x * t90 * t84 + 0.32e2 * t17 * t95 * t94 - - 0.32e2 * t17 * t100 * t99 + 0.8e1 * t108 * t104 + 0.16e2 * t85 * t112 - 0.8e1 * y * t115 * t112 - + 0.32e2 * t120 * t94 - 0.32e2 * t124 * t99 + 0.8e1 * t131 * t130 - 0.8e1 * t136 * t134; + const su2double t139 = 0.32e2 * t34 * t12 * t30 - 0.32e2 * t10 * t37 * t30 + t71 + 0.16e2 / 0.3e1 * t78 * x * t73 + + 0.16e2 / 0.3e1 * t85 * t84 - 0.8e1 / 0.3e1 * x * t90 * t84 + 0.32e2 * t17 * t95 * t94 - + 0.32e2 * t17 * t100 * t99 + 0.8e1 * t108 * t104 + 0.16e2 * t85 * t112 - + 0.8e1 * y * t115 * t112 + 0.32e2 * t120 * t94 - 0.32e2 * t124 * t99 + 0.8e1 * t131 * t130 - + 0.8e1 * t136 * t134; const su2double t146 = x * t72; const su2double t155 = v_0 * v_0; const su2double t156 = t155 * rho_0; @@ -271,11 +254,11 @@ void CMMSNSTwoHalfSpheresSolution::GetMMSSourceTerm(const su2double *val_coords, const su2double t195 = v_0 * z + w_0 * y; const su2double t196 = t72 * t195; const su2double t199 = t111 * t195; - const su2double t202 = 0.32e2 * t8 * t95 * t94 - 0.32e2 * t8 * t100 * t99 + 0.8e1 * t108 * t146 - + 0.80e2 / 0.3e1 * t7 * v_0 * t112 - 0.8e1 * x * t115 * t112 + 0.32e2 * t158 * t12 * t156 - - 0.32e2 * t18 * t37 * t156 + t177 + 0.16e2 / 0.3e1 * y * t180 * t135 - - 0.16e2 / 0.3e1 * y * t179 * t73 + 0.32e2 * t120 * t187 - 0.32e2 * t124 * t190 - + 0.8e1 * t131 * t196 - 0.8e1 * t136 * t199; + const su2double t202 = 0.32e2 * t8 * t95 * t94 - 0.32e2 * t8 * t100 * t99 + 0.8e1 * t108 * t146 + + 0.80e2 / 0.3e1 * t7 * v_0 * t112 - 0.8e1 * x * t115 * t112 + 0.32e2 * t158 * t12 * t156 - + 0.32e2 * t18 * t37 * t156 + t177 + 0.16e2 / 0.3e1 * y * t180 * t135 - + 0.16e2 / 0.3e1 * y * t179 * t73 + 0.32e2 * t120 * t187 - 0.32e2 * t124 * t190 + + 0.8e1 * t131 * t196 - 0.8e1 * t136 * t199; const su2double t209 = t111 * w_0; const su2double t231 = w_0 * w_0; const su2double t232 = t231 * rho_0; @@ -285,11 +268,11 @@ void CMMSNSTwoHalfSpheresSolution::GetMMSSourceTerm(const su2double *val_coords, const su2double t253 = t252 * t41; const su2double t255 = t74 + t76 - 0.2e1 * t77; const su2double t256 = t111 * t255; - const su2double t263 = 0.32e2 * t8 * t119 * t94 - 0.32e2 * t8 * t123 * t99 + 0.80e2 / 0.3e1 * t7 * Viscosity * t209 - + 0.8e1 * x * Viscosity * t130 - 0.8e1 * x * t135 * t134 + 0.32e2 * t17 * t119 * t187 - - 0.32e2 * t17 * t123 * t190 + 0.8e1 * y * Viscosity * t196 - 0.8e1 * y * t135 * t199 - + 0.32e2 * t234 * t12 * t232 - 0.32e2 * t24 * t37 * t232 + t253 - + 0.16e2 / 0.3e1 * z * t256 * t135 - 0.16e2 / 0.3e1 * z * t255 * t73; + const su2double t263 = 0.32e2 * t8 * t119 * t94 - 0.32e2 * t8 * t123 * t99 + 0.80e2 / 0.3e1 * t7 * Viscosity * t209 + + 0.8e1 * x * Viscosity * t130 - 0.8e1 * x * t135 * t134 + 0.32e2 * t17 * t119 * t187 - + 0.32e2 * t17 * t123 * t190 + 0.8e1 * y * Viscosity * t196 - 0.8e1 * y * t135 * t199 + + 0.32e2 * t234 * t12 * t232 - 0.32e2 * t24 * t37 * t232 + t253 + + 0.16e2 / 0.3e1 * z * t256 * t135 - 0.16e2 / 0.3e1 * z * t255 * t73; const su2double t265 = t12 * u_0; const su2double t266 = x * t9; const su2double t270 = t115 * t112; @@ -308,11 +291,12 @@ void CMMSNSTwoHalfSpheresSolution::GetMMSSourceTerm(const su2double *val_coords, const su2double t316 = t305 * Viscosity * w_0; const su2double t319 = Viscosity * t134; const su2double t320 = w_0 * t72; - const su2double t329 = -0.32e2 / 0.3e1 * t266 * t265 * t90 * t84 - 0.32e2 * t266 * t271 * t270 - - 0.32e2 * t266 * t276 * t275 - 0.32e2 * t280 * t265 * t270 + 0.64e2 / 0.3e1 * t285 * t180 * t135 - - 0.32e2 * t280 * t276 * t288 - 0.32e2 * t292 * t265 * t275 - 0.32e2 * t292 * t271 * t288 - + 0.64e2 / 0.3e1 * t300 * t256 * t135 + 0.32e2 * t305 * v_0 * t107 * t303 + 0.32e2 * t266 * t310 * t309 - + 0.32e2 * t316 * x * t130 + 0.32e2 * t266 * t320 * t319 + 0.32e2 * t305 * u_0 * t107 * Viscosity * t104; + const su2double t329 = + -0.32e2 / 0.3e1 * t266 * t265 * t90 * t84 - 0.32e2 * t266 * t271 * t270 - 0.32e2 * t266 * t276 * t275 - + 0.32e2 * t280 * t265 * t270 + 0.64e2 / 0.3e1 * t285 * t180 * t135 - 0.32e2 * t280 * t276 * t288 - + 0.32e2 * t292 * t265 * t275 - 0.32e2 * t292 * t271 * t288 + 0.64e2 / 0.3e1 * t300 * t256 * t135 + + 0.32e2 * t305 * v_0 * t107 * t303 + 0.32e2 * t266 * t310 * t309 + 0.32e2 * t316 * x * t130 + + 0.32e2 * t266 * t320 * t319 + 0.32e2 * t305 * u_0 * t107 * Viscosity * t104; const su2double t330 = u_0 * t72; const su2double t334 = t179 * t73; const su2double t337 = v_0 * t111; @@ -333,13 +317,14 @@ void CMMSNSTwoHalfSpheresSolution::GetMMSSourceTerm(const su2double *val_coords, const su2double t412 = t12 * t89 * t410; const su2double t421 = t78 * t84; const su2double t422 = x * t12; - const su2double t426 = 0.32e2 * t280 * t330 * t309 - 0.64e2 / 0.3e1 * t285 * t334 - 0.64e2 / 0.3e1 * t280 * t337 * t334 - + 0.32e2 * t316 * y * t196 + 0.32e2 * t280 * t320 * t344 + 0.32e2 * t305 * Viscosity * u_0 * z * t130 - + 0.32e2 * t292 * t330 * t319 + 0.32e2 * t305 * Viscosity * v_0 * z * t196 + 0.32e2 * t292 * t310 * t344 - - 0.64e2 / 0.3e1 * t300 * t364 - 0.64e2 / 0.3e1 * t292 * t209 * t364 - + 0.4e1 * t400 * TWall * x * t12 * t7 * (t377 * x * t371 - t12 * a_T2 * x * t381 + Pi * t8 * t385 - + 0.2e1 * a_T2 * t58 * x * t389 + t60 / 0.2e1) - 0.4e1 * t400 * t2 * TWall - * t412 + 0.64e2 / 0.3e1 * t305 * u_0 * t78 * t303 - 0.32e2 / 0.3e1 * t422 * t330 * t421; + const su2double t426 = + 0.32e2 * t280 * t330 * t309 - 0.64e2 / 0.3e1 * t285 * t334 - 0.64e2 / 0.3e1 * t280 * t337 * t334 + + 0.32e2 * t316 * y * t196 + 0.32e2 * t280 * t320 * t344 + 0.32e2 * t305 * Viscosity * u_0 * z * t130 + + 0.32e2 * t292 * t330 * t319 + 0.32e2 * t305 * Viscosity * v_0 * z * t196 + 0.32e2 * t292 * t310 * t344 - + 0.64e2 / 0.3e1 * t300 * t364 - 0.64e2 / 0.3e1 * t292 * t209 * t364 + + 0.4e1 * t400 * TWall * x * t12 * t7 * + (t377 * x * t371 - t12 * a_T2 * x * t381 + Pi * t8 * t385 + 0.2e1 * a_T2 * t58 * x * t389 + t60 / 0.2e1) - + 0.4e1 * t400 * t2 * TWall * t412 + 0.64e2 / 0.3e1 * t305 * u_0 * t78 * t303 - 0.32e2 / 0.3e1 * t422 * t330 * t421; const su2double t457 = y * t12; const su2double t483 = t400 * TWall * t12; const su2double t486 = t410 * t4; @@ -351,14 +336,18 @@ void CMMSNSTwoHalfSpheresSolution::GetMMSSourceTerm(const su2double *val_coords, const su2double t515 = t37 * t231; const su2double t521 = t508 * t506 * t41 + 0.8e1 * (t32 * t511 + t32 * t513 + t32 * t515) * rho_0 + t506 * t41; const su2double t522 = u_0 * t521; - const su2double t527 = -0.32e2 * t422 * t310 * t309 - 0.32e2 * t422 * t320 * t319 - + 0.4e1 * t400 * y * TWall * t12 * t7 * (t377 * y * t371 - t12 * a_T2 * y * t381 + Pi * t17 * t385 - + 0.2e1 * a_T2 * t58 * y * t389 + t168 / 0.2e1) - 0.4e1 * t400 * TWall * t3 * t412 - - 0.32e2 * t457 * t330 * t309 + 0.64e2 / 0.3e1 * t457 * t337 * t334 - 0.32e2 * t457 * t320 * t344 - + 0.4e1 * t483 * t7 * (t377 * z * t371 - t12 * a_T2 * z * t381 + Pi * t23 * t385 - + 0.2e1 * a_T2 * t58 * z * t389 + t244 / 0.2e1) * z - 0.4e1 * t483 * t89 * t486 - - 0.32e2 * t490 * t330 * t319 - 0.32e2 * t490 * t310 * t344 + 0.64e2 / 0.3e1 * t490 * t209 * t364 - + 0.32e2 / 0.3e1 * t266 * t330 * t421 + 0.4e1 * t10 * t522 - 0.4e1 * t14 * t522; + const su2double t527 = + -0.32e2 * t422 * t310 * t309 - 0.32e2 * t422 * t320 * t319 + + 0.4e1 * t400 * y * TWall * t12 * t7 * + (t377 * y * t371 - t12 * a_T2 * y * t381 + Pi * t17 * t385 + 0.2e1 * a_T2 * t58 * y * t389 + t168 / 0.2e1) - + 0.4e1 * t400 * TWall * t3 * t412 - 0.32e2 * t457 * t330 * t309 + 0.64e2 / 0.3e1 * t457 * t337 * t334 - + 0.32e2 * t457 * t320 * t344 + + 0.4e1 * t483 * t7 * + (t377 * z * t371 - t12 * a_T2 * z * t381 + Pi * t23 * t385 + 0.2e1 * a_T2 * t58 * z * t389 + t244 / 0.2e1) * + z - + 0.4e1 * t483 * t89 * t486 - 0.32e2 * t490 * t330 * t319 - 0.32e2 * t490 * t310 * t344 + + 0.64e2 / 0.3e1 * t490 * t209 * t364 + 0.32e2 / 0.3e1 * t266 * t330 * t421 + 0.4e1 * t10 * t522 - + 0.4e1 * t14 * t522; const su2double t528 = v_0 * t521; const su2double t533 = w_0 * t521; const su2double t541 = Conductivity * t399 * TWall; @@ -367,30 +356,35 @@ void CMMSNSTwoHalfSpheresSolution::GetMMSSourceTerm(const su2double *val_coords, const su2double t570 = t12 * t29; const su2double t573 = t12 * t155; const su2double t576 = t12 * t231; - const su2double t616 = 0.4e1 * t18 * t528 - 0.4e1 * t20 * t528 + 0.4e1 * t24 * t533 - 0.4e1 * t26 * t533 - + 0.12e2 * t541 * t12 * t7 * t410 + 0.320e3 / 0.3e1 * t545 * t155 * t112 - + 0.320e3 / 0.3e1 * t545 * Viscosity * t111 * t231 + 0.64e2 * t545 * t29 * t112 - + 0.64e2 / 0.3e1 * t545 * t29 * t84 + 0.4e1 * t541 * t2 * t558 + 0.4e1 * t541 * t3 * t558 - + 0.4e1 * t541 * t72 * t486 + 0.4e1 * t305 * u_0 * (t508 * t70 * t41 - + 0.16e2 * (-t10 * t511 - t10 * t513 - t10 * t515 + t34 * t570 + t34 * t573 + t34 * t576) * rho_0 + t71) - + 0.4e1 * t305 * v_0 * (t508 * t176 * t41 + 0.16e2 * (t158 * t570 + t158 * t573 + t158 * t576 - - t18 * t511 - t18 * t513 - t18 * t515) * rho_0 + t177) + 0.4e1 * t305 * w_0 * (t508 * t252 * t41 - + 0.16e2 * (t234 * t570 + t234 * t573 + t234 * t576 - t24 * t511 - t24 * t513 - t24 * t515) * rho_0 + t253); + const su2double t616 = + 0.4e1 * t18 * t528 - 0.4e1 * t20 * t528 + 0.4e1 * t24 * t533 - 0.4e1 * t26 * t533 + + 0.12e2 * t541 * t12 * t7 * t410 + 0.320e3 / 0.3e1 * t545 * t155 * t112 + + 0.320e3 / 0.3e1 * t545 * Viscosity * t111 * t231 + 0.64e2 * t545 * t29 * t112 + + 0.64e2 / 0.3e1 * t545 * t29 * t84 + 0.4e1 * t541 * t2 * t558 + 0.4e1 * t541 * t3 * t558 + + 0.4e1 * t541 * t72 * t486 + + 0.4e1 * t305 * u_0 * + (t508 * t70 * t41 + + 0.16e2 * (-t10 * t511 - t10 * t513 - t10 * t515 + t34 * t570 + t34 * t573 + t34 * t576) * rho_0 + t71) + + 0.4e1 * t305 * v_0 * + (t508 * t176 * t41 + + 0.16e2 * (t158 * t570 + t158 * t573 + t158 * t576 - t18 * t511 - t18 * t513 - t18 * t515) * rho_0 + t177) + + 0.4e1 * t305 * w_0 * + (t508 * t252 * t41 + + 0.16e2 * (t234 * t570 + t234 * t573 + t234 * t576 - t24 * t511 - t24 * t513 - t24 * t515) * rho_0 + t253); /*--- Set the source term. Note the scaling for the correct non-dimensionalization. ---*/ - val_source[0] = 0.4e1 * t10 * t1 - 0.4e1 * t14 * t1 + 0.4e1 * t18 * t16 - 0.4e1 * t20 * t16 + 0.4e1 * t24 * t22 - 0.4e1 * t26 * t22; + val_source[0] = 0.4e1 * t10 * t1 - 0.4e1 * t14 * t1 + 0.4e1 * t18 * t16 - 0.4e1 * t20 * t16 + 0.4e1 * t24 * t22 - + 0.4e1 * t26 * t22; val_source[1] = t139; val_source[2] = t202; val_source[3] = t263; val_source[4] = t329 + t426 + t527 + t616; - val_source[0] /= Density_Ref*Velocity_Ref; + val_source[0] /= Density_Ref * Velocity_Ref; val_source[1] /= Pressure_Ref; val_source[2] /= Pressure_Ref; val_source[3] /= Pressure_Ref; - val_source[4] /= Velocity_Ref*Pressure_Ref; + val_source[4] /= Velocity_Ref * Pressure_Ref; } -bool CMMSNSTwoHalfSpheresSolution::IsManufacturedSolution(void) const { - return true; -} +bool CMMSNSTwoHalfSpheresSolution::IsManufacturedSolution(void) const { return true; } diff --git a/Common/src/toolboxes/MMS/CMMSNSUnitQuadSolution.cpp b/Common/src/toolboxes/MMS/CMMSNSUnitQuadSolution.cpp index 8a8f537f546..39721dca2d1 100644 --- a/Common/src/toolboxes/MMS/CMMSNSUnitQuadSolution.cpp +++ b/Common/src/toolboxes/MMS/CMMSNSUnitQuadSolution.cpp @@ -27,14 +27,11 @@ #include "../../../include/toolboxes/MMS/CMMSNSUnitQuadSolution.hpp" -CMMSNSUnitQuadSolution::CMMSNSUnitQuadSolution(void) : CVerificationSolution() { } - -CMMSNSUnitQuadSolution::CMMSNSUnitQuadSolution(unsigned short val_nDim, - unsigned short val_nVar, - unsigned short val_iMesh, - CConfig* config) - : CVerificationSolution(val_nDim, val_nVar, val_iMesh, config) { +CMMSNSUnitQuadSolution::CMMSNSUnitQuadSolution(void) : CVerificationSolution() {} +CMMSNSUnitQuadSolution::CMMSNSUnitQuadSolution(unsigned short val_nDim, unsigned short val_nVar, + unsigned short val_iMesh, CConfig* config) + : CVerificationSolution(val_nDim, val_nVar, val_iMesh, config) { /*--- Write a message that the solution is initialized for the manufactured solution for the Navier-Stokes equations on a unit quad. ---*/ if ((rank == MASTER_NODE) && (val_iMesh == MESH_0)) { @@ -48,132 +45,116 @@ CMMSNSUnitQuadSolution::CMMSNSUnitQuadSolution(unsigned short val_nDim, /*--- Coefficients, needed to determine the solution. ---*/ const su2double Prandtl = config->GetPrandtl_Lam(); - RGas = config->GetGas_ConstantND(); - Gamma = config->GetGamma(); - Viscosity = config->GetMu_ConstantND(); - Conductivity = Viscosity*Gamma*RGas/(Prandtl*(Gamma-1.0)); + RGas = config->GetGas_ConstantND(); + Gamma = config->GetGamma(); + Viscosity = config->GetMu_ConstantND(); + Conductivity = Viscosity * Gamma * RGas / (Prandtl * (Gamma - 1.0)); /*--- Constants, which describe this manufactured solution. This is a viscous solution on the unit quad, where the primitive variables vary as a combination of sine and cosine functions. The unit quad is probably not necessary, and an arbitrary domain should work as well. ---*/ - L = 1.0; - a_Px = 1.0; - a_Pxy = 0.75; - a_Py = 1.25; - a_rhox = 0.75; - a_rhoxy = 1.25; - a_rhoy = 1.0; - a_ux = 1.6666666667; - a_uxy = 0.6; - a_uy = 1.5; - a_vx = 1.5; - a_vxy = 0.9; - a_vy = 1.0; - P_0 = 100000.0; - P_x = -30000.0; - P_xy = -25000.0; - P_y = 20000.0; - rho_0 = 1.0; - rho_x = 0.1; - rho_xy = 0.08; - rho_y = 0.15; - u_0 = 70.0; - u_x = 4.0; - u_xy = 7.0; - u_y = -12.0; - v_0 = 90.0; - v_x = -20.0; - v_xy = -11.0; - v_y = 4.0; + L = 1.0; + a_Px = 1.0; + a_Pxy = 0.75; + a_Py = 1.25; + a_rhox = 0.75; + a_rhoxy = 1.25; + a_rhoy = 1.0; + a_ux = 1.6666666667; + a_uxy = 0.6; + a_uy = 1.5; + a_vx = 1.5; + a_vxy = 0.9; + a_vy = 1.0; + P_0 = 100000.0; + P_x = -30000.0; + P_xy = -25000.0; + P_y = 20000.0; + rho_0 = 1.0; + rho_x = 0.1; + rho_xy = 0.08; + rho_y = 0.15; + u_0 = 70.0; + u_x = 4.0; + u_xy = 7.0; + u_y = -12.0; + v_0 = 90.0; + v_x = -20.0; + v_xy = -11.0; + v_y = 4.0; /*--- Perform some sanity and error checks for this solution here. ---*/ - if(config->GetTime_Marching() != TIME_MARCHING::STEADY) - SU2_MPI::Error("Steady mode must be selected for the MMS NS Unit Quad case", - CURRENT_FUNCTION); + if (config->GetTime_Marching() != TIME_MARCHING::STEADY) + SU2_MPI::Error("Steady mode must be selected for the MMS NS Unit Quad case", CURRENT_FUNCTION); - if(Kind_Solver != MAIN_SOLVER::EULER && Kind_Solver != MAIN_SOLVER::NAVIER_STOKES && Kind_Solver != MAIN_SOLVER::RANS && - Kind_Solver != MAIN_SOLVER::FEM_EULER && Kind_Solver != MAIN_SOLVER::FEM_NAVIER_STOKES && Kind_Solver != MAIN_SOLVER::FEM_RANS && - Kind_Solver != MAIN_SOLVER::FEM_LES) SU2_MPI::Error("Compressible flow equations must be selected for the MMS NS Unit Quad case", - CURRENT_FUNCTION); + if (Kind_Solver != MAIN_SOLVER::EULER && Kind_Solver != MAIN_SOLVER::NAVIER_STOKES && + Kind_Solver != MAIN_SOLVER::RANS && Kind_Solver != MAIN_SOLVER::FEM_EULER && + Kind_Solver != MAIN_SOLVER::FEM_NAVIER_STOKES && Kind_Solver != MAIN_SOLVER::FEM_RANS && + Kind_Solver != MAIN_SOLVER::FEM_LES) + SU2_MPI::Error("Compressible flow equations must be selected for the MMS NS Unit Quad case", CURRENT_FUNCTION); - if((Kind_Solver != MAIN_SOLVER::NAVIER_STOKES) && - (Kind_Solver != MAIN_SOLVER::FEM_NAVIER_STOKES)) - SU2_MPI::Error("Navier Stokes equations must be selected for the MMS NS Unit Quad case", - CURRENT_FUNCTION); + if ((Kind_Solver != MAIN_SOLVER::NAVIER_STOKES) && (Kind_Solver != MAIN_SOLVER::FEM_NAVIER_STOKES)) + SU2_MPI::Error("Navier Stokes equations must be selected for the MMS NS Unit Quad case", CURRENT_FUNCTION); - if((config->GetKind_FluidModel() != STANDARD_AIR) && - (config->GetKind_FluidModel() != IDEAL_GAS)) - SU2_MPI::Error("Standard air or ideal gas must be selected for the MMS NS Unit Quad case", - CURRENT_FUNCTION); + if ((config->GetKind_FluidModel() != STANDARD_AIR) && (config->GetKind_FluidModel() != IDEAL_GAS)) + SU2_MPI::Error("Standard air or ideal gas must be selected for the MMS NS Unit Quad case", CURRENT_FUNCTION); - if(config->GetKind_ViscosityModel() != VISCOSITYMODEL::CONSTANT) - SU2_MPI::Error("Constant viscosity must be selected for the MMS NS Unit Quad case", - CURRENT_FUNCTION); + if (config->GetKind_ViscosityModel() != VISCOSITYMODEL::CONSTANT) + SU2_MPI::Error("Constant viscosity must be selected for the MMS NS Unit Quad case", CURRENT_FUNCTION); - if(config->GetKind_ConductivityModel() != CONDUCTIVITYMODEL::CONSTANT_PRANDTL) - SU2_MPI::Error("Constant Prandtl number must be selected for the MMS NS Unit Quad case", - CURRENT_FUNCTION); + if (config->GetKind_ConductivityModel() != CONDUCTIVITYMODEL::CONSTANT_PRANDTL) + SU2_MPI::Error("Constant Prandtl number must be selected for the MMS NS Unit Quad case", CURRENT_FUNCTION); } -CMMSNSUnitQuadSolution::~CMMSNSUnitQuadSolution(void) { } - -void CMMSNSUnitQuadSolution::GetBCState(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const { +CMMSNSUnitQuadSolution::~CMMSNSUnitQuadSolution(void) {} +void CMMSNSUnitQuadSolution::GetBCState(const su2double* val_coords, const su2double val_t, + su2double* val_solution) const { /*--- The exact solution is prescribed on the boundaries. ---*/ GetSolution(val_coords, val_t, val_solution); } -void CMMSNSUnitQuadSolution::GetSolution(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const { - +void CMMSNSUnitQuadSolution::GetSolution(const su2double* val_coords, const su2double val_t, + su2double* val_solution) const { /* Easier storage of the x- and y-coordinates. */ const su2double x = val_coords[0]; const su2double y = val_coords[1]; /* Determine the solution for the density, velocity components and pressure. */ - const su2double LInv = 1.0/L; - const su2double PiLInv = PI_NUMBER*LInv; - const su2double PiL2Inv = PiLInv*LInv; + const su2double LInv = 1.0 / L; + const su2double PiLInv = PI_NUMBER * LInv; + const su2double PiL2Inv = PiLInv * LInv; - const su2double rho = rho_0 + rho_x *sin(a_rhox *PiLInv*x) - + rho_y *cos(a_rhoy *PiLInv*y) - + rho_xy*cos(a_rhoxy*PiL2Inv*x*y); + const su2double rho = rho_0 + rho_x * sin(a_rhox * PiLInv * x) + rho_y * cos(a_rhoy * PiLInv * y) + + rho_xy * cos(a_rhoxy * PiL2Inv * x * y); - const su2double u = u_0 + u_x *sin(a_ux *PiLInv*x) - + u_y *cos(a_uy *PiLInv*y) - + u_xy*cos(a_uxy*PiL2Inv*x*y); + const su2double u = + u_0 + u_x * sin(a_ux * PiLInv * x) + u_y * cos(a_uy * PiLInv * y) + u_xy * cos(a_uxy * PiL2Inv * x * y); - const su2double v = v_0 + v_x *cos(a_vx *PiLInv*x) - + v_y *sin(a_vy *PiLInv*y) - + v_xy*cos(a_vxy*PiL2Inv*x*y); + const su2double v = + v_0 + v_x * cos(a_vx * PiLInv * x) + v_y * sin(a_vy * PiLInv * y) + v_xy * cos(a_vxy * PiL2Inv * x * y); - const su2double p = P_0 + P_x *cos(a_Px *PiLInv*x) - + P_y *sin(a_Py *PiLInv*y) - + P_xy*sin(a_Pxy*PiL2Inv*x*y); + const su2double p = + P_0 + P_x * cos(a_Px * PiLInv * x) + P_y * sin(a_Py * PiLInv * y) + P_xy * sin(a_Pxy * PiL2Inv * x * y); /* Compute the conservative variables from the primitive ones. Note that the implementation below is valid for both 2D and 3D. */ - val_solution[0] = rho; - val_solution[1] = rho*u; - val_solution[2] = rho*v; - val_solution[3] = 0.0; - val_solution[nDim+1] = p/(Gamma-1.0) + 0.5*rho*(u*u + v*v); + val_solution[0] = rho; + val_solution[1] = rho * u; + val_solution[2] = rho * v; + val_solution[3] = 0.0; + val_solution[nDim + 1] = p / (Gamma - 1.0) + 0.5 * rho * (u * u + v * v); } -void CMMSNSUnitQuadSolution::GetMMSSourceTerm(const su2double *val_coords, - const su2double val_t, - su2double *val_source) const { - +void CMMSNSUnitQuadSolution::GetMMSSourceTerm(const su2double* val_coords, const su2double val_t, + su2double* val_source) const { /*--- The source code for the source terms is generated in Maple. See the file CMMSNSUnitQuadSolution.mw in the directory - CreateMMSSourceTerms for the details how to do this. ---*/ + CreateMMSSourceTerms for the details how to do this. ---*/ const su2double Pi = PI_NUMBER; - const su2double fourThird = 4.0/3.0; + const su2double fourThird = 4.0 / 3.0; const su2double x = val_coords[0]; const su2double y = val_coords[1]; @@ -263,7 +244,8 @@ void CMMSNSUnitQuadSolution::GetMMSSourceTerm(const su2double *val_coords, const su2double t143 = -t138 * t3 * t137 - t53 * t16 * t52; const su2double t147 = a_uy * a_uy; const su2double t150 = x * x; - const su2double t161 = (-t13 * (u_xy * t34 * t150 * t111 + t31 * Pi * t147) * Pi - t13 * (t122 + t125) * Pi) * Viscosity; + const su2double t161 = + (-t13 * (u_xy * t34 * t150 * t111 + t31 * Pi * t147) * Pi - t13 * (t122 + t125) * Pi) * Viscosity; const su2double t165 = v_x * a_vx; const su2double t166 = sin(t66); const su2double t171 = -t85 * t14 * t84 - t166 * t3 * t165; @@ -272,7 +254,8 @@ void CMMSNSUnitQuadSolution::GetMMSSourceTerm(const su2double *val_coords, const su2double t177 = a_uxy * t53; const su2double t178 = u_xy * t177; const su2double t182 = a_vx * a_vx; - const su2double t192 = (-t13 * (t176 + t178) * Pi - t13 * (v_xy * t75 * t112 * t118 + t68 * Pi * t182) * Pi) * Viscosity; + const su2double t192 = + (-t13 * (t176 + t178) * Pi - t13 * (v_xy * t75 * t112 * t118 + t68 * Pi * t182) * Pi) * Viscosity; const su2double t193 = t77 * t77; const su2double t200 = t28 * a_Py * Pi; const su2double t201 = cos(t200); @@ -291,7 +274,7 @@ void CMMSNSUnitQuadSolution::GetMMSSourceTerm(const su2double *val_coords, const su2double t237 = sin(t105); const su2double t238 = t237 * P_xy; const su2double t239 = P_0 + t234 + t236 + t238; - const su2double t243 = t221 * t239 + t223 * t46 / 0.2e1 + P_0 + t234 + t236 + t238; + const su2double t243 = t221 * t239 + t223 * t46 / 0.2e1 + P_0 + t234 + t236 + t238; const su2double t245 = a_Px * a_Px; const su2double t246 = Pi * t245; const su2double t248 = a_Pxy * a_Pxy; @@ -323,7 +306,8 @@ void CMMSNSUnitQuadSolution::GetMMSSourceTerm(const su2double *val_coords, const su2double t330 = t7 * t7; const su2double t331 = rho_x * rho_x; const su2double t336 = rho_0 * rho_0; - const su2double t337 = 0.2e1 * rho_x * rho_0 * t38 + t319 * t318 + 0.2e1 * t44 * t321 + t325 * t324 + 0.2e1 * t42 * t327 - t331 * t330 + t331 + t336; + const su2double t337 = 0.2e1 * rho_x * rho_0 * t38 + t319 * t318 + 0.2e1 * t44 * t321 + t325 * t324 + + 0.2e1 * t42 * t327 - t331 * t330 + t331 + t336; const su2double t338 = 0.1e1 / t337; const su2double t340 = 0.1e1 / RGas; const su2double t341 = t340 * t13; @@ -336,7 +320,8 @@ void CMMSNSUnitQuadSolution::GetMMSSourceTerm(const su2double *val_coords, const su2double t399 = t120 * t124; const su2double t402 = a_ux * u_x * t48; const su2double t404 = a_vy * v_y * t80; - const su2double t428 = (-t13 * (t137 * t138 * L + t174 * t177) * Pi - t13 * (t165 * t166 * L + v_xy * y * t124) * Pi) * Viscosity; + const su2double t428 = + (-t13 * (t137 * t138 * L + t174 * t177) * Pi - t13 * (t165 * t166 * L + v_xy * y * t124) * Pi) * Viscosity; const su2double t430 = t203 + t205; const su2double t442 = a_Py * a_Py; const su2double t446 = P_xy * t150 * t248; @@ -348,36 +333,54 @@ void CMMSNSUnitQuadSolution::GetMMSSourceTerm(const su2double *val_coords, const su2double t475 = t474 * rho_y; const su2double t480 = P_xy * t59; const su2double t486 = t235 * t2; - const su2double t564 = t36 * ( t221 * t219 + t223 * t22 / 0.2e1 + (t171 * t77 + t56 * t36) * t46 - t101 + t108) + t56 * t243 - + Conductivity * t341 * t338 * (t44 * (t234 * t246 + t252 * t250) * rho_xy - t267 * a_rhoxy * t264 - - t19 * t219 * y * t10 - t277 * t112 * t273 - t106 * t7 * t2 * t4 * P_xy * rho_x * t260 + t288 * t250 - + (t42 * P_x * t233 * t2 * Pi * rho_y * t245 - t238 * t38 * t2 * Pi * t291 - + t107 * t104 * t296 * t1 + t311 * t234 * t2 * t246 - t308 * t306 * t291) * L) * Pi; - const su2double t565 = -0.2e1 * (t44 * t7 * t3 * rho_xy * rho_x * a_rhox + t42 * t7 * t3 * rho_y * rho_x * a_rhox - + rho_x * rho_0 * t7 * t2 * t4 + t308 * a_rhox * t331 * t7 - t267 * t369 - t267 * t376) * Conductivity * t341 * t366 - * (t44 * t264 - t19 * t239 * y * t10 - t349 * t260 + (t311 * P_x * t99 * a_Px + t42 * t258 * a_Px * rho_y - + t237 * t296 * t1 + t7 * t306 * t1) * L) * Pi - fourThird * t36 * t132 * t131 - - fourThird * t56 * t132 * (-t398 + t399 / 0.2e1 + (t402 - t404 / 0.2e1) * L) * Pi; - const su2double t566 = -t77 * t192 - t171 * t428 + t77 * ( t221 * t430 + t223 * t64 / 0.2e1 + (t143 * t36 + t88 * t77) * t46 + t203 + t205) - + t88 * t243 - Conductivity * t340 * t338 * t13 * (t44 * (-t236 * Pi * t442 - t252 * t446) * rho_xy - - t460 * a_rhoxy * t457 + t19 * t430 * x * t10 + t277 * t150 * t273 - t106 * t59 * t2 * t40 * P_xy * rho_y * t454 - - t288 * t446 + (-P_y * t38 * t486 * Pi * rho_x * t442 - t42 * P_y * t486 * Pi * rho_y * t442 - - P_y * t486 * Pi * rho_0 * t442 + t238 * t42 * t2 * Pi * t475 + t204 * t104 * t480 * t58 - + t42 * t3 * t306 * t475) * L) * Pi; - const su2double t567 = 0.2e1 * (-t44 * t59 * t3 * rho_xy * rho_y * a_rhoy - - t60 * a_rhoy * t325 * t42 - t60 * a_rhoy * t327 - t460 * t369 - t460 * t376) * Conductivity * t340 * t366 * t13 - * (t44 * t457 + t19 * t239 * x * t10 + t349 * t454 + (P_y * t38 * t201 * a_Py * rho_x + t42 * t452 * a_Py * rho_y - + t452 * a_Py * rho_0 + t237 * t480 * t58 + t59 * t306 * t58) * L) * Pi - t36 * t161 - - t143 * t428 + 0.2e1 / 0.3e1 * t77 * t132 * t215 + 0.2e1 / 0.3e1 * t88 * t132 * (-t398 + 0.2e1 * t399 - + (t402 - 0.2e1 * t404) * L) * Pi; + const su2double t564 = + t36 * (t221 * t219 + t223 * t22 / 0.2e1 + (t171 * t77 + t56 * t36) * t46 - t101 + t108) + t56 * t243 + + Conductivity * t341 * t338 * + (t44 * (t234 * t246 + t252 * t250) * rho_xy - t267 * a_rhoxy * t264 - t19 * t219 * y * t10 - + t277 * t112 * t273 - t106 * t7 * t2 * t4 * P_xy * rho_x * t260 + t288 * t250 + + (t42 * P_x * t233 * t2 * Pi * rho_y * t245 - t238 * t38 * t2 * Pi * t291 + t107 * t104 * t296 * t1 + + t311 * t234 * t2 * t246 - t308 * t306 * t291) * + L) * + Pi; + const su2double t565 = + -0.2e1 * + (t44 * t7 * t3 * rho_xy * rho_x * a_rhox + t42 * t7 * t3 * rho_y * rho_x * a_rhox + + rho_x * rho_0 * t7 * t2 * t4 + t308 * a_rhox * t331 * t7 - t267 * t369 - t267 * t376) * + Conductivity * t341 * t366 * + (t44 * t264 - t19 * t239 * y * t10 - t349 * t260 + + (t311 * P_x * t99 * a_Px + t42 * t258 * a_Px * rho_y + t237 * t296 * t1 + t7 * t306 * t1) * L) * + Pi - + fourThird * t36 * t132 * t131 - fourThird * t56 * t132 * (-t398 + t399 / 0.2e1 + (t402 - t404 / 0.2e1) * L) * Pi; + const su2double t566 = + -t77 * t192 - t171 * t428 + + t77 * (t221 * t430 + t223 * t64 / 0.2e1 + (t143 * t36 + t88 * t77) * t46 + t203 + t205) + t88 * t243 - + Conductivity * t340 * t338 * t13 * + (t44 * (-t236 * Pi * t442 - t252 * t446) * rho_xy - t460 * a_rhoxy * t457 + t19 * t430 * x * t10 + + t277 * t150 * t273 - t106 * t59 * t2 * t40 * P_xy * rho_y * t454 - t288 * t446 + + (-P_y * t38 * t486 * Pi * rho_x * t442 - t42 * P_y * t486 * Pi * rho_y * t442 - + P_y * t486 * Pi * rho_0 * t442 + t238 * t42 * t2 * Pi * t475 + t204 * t104 * t480 * t58 + + t42 * t3 * t306 * t475) * + L) * + Pi; + const su2double t567 = 0.2e1 * + (-t44 * t59 * t3 * rho_xy * rho_y * a_rhoy - t60 * a_rhoy * t325 * t42 - + t60 * a_rhoy * t327 - t460 * t369 - t460 * t376) * + Conductivity * t340 * t366 * t13 * + (t44 * t457 + t19 * t239 * x * t10 + t349 * t454 + + (P_y * t38 * t201 * a_Py * rho_x + t42 * t452 * a_Py * rho_y + t452 * a_Py * rho_0 + + t237 * t480 * t58 + t59 * t306 * t58) * + L) * + Pi - + t36 * t161 - t143 * t428 + 0.2e1 / 0.3e1 * t77 * t132 * t215 + + 0.2e1 / 0.3e1 * t88 * t132 * (-t398 + 0.2e1 * t399 + (t402 - 0.2e1 * t404) * L) * Pi; - val_source[0] = t88 * t46 + t77 * t64 + t37 + t57; - val_source[1] = t91 * t22 + 0.2e1 * t56 * t93 - t101 + t108 - fourThird * t132 * t131 + t77 * t36 * t64 + t77 * t143 * t46 + t88 * t93 - t161; - val_source[2] = t77 * t37 + t77 * t57 + t171 * t93 - t192 + t193 * t64 + 0.2e1 * t88 * t77 * t46 + t203 + t205 + 0.2e1 / 0.3e1 * t132 * t215; - val_source[3] = 0.0; - val_source[nDim+1] = t564 + t565 + t566 + t567; + val_source[0] = t88 * t46 + t77 * t64 + t37 + t57; + val_source[1] = t91 * t22 + 0.2e1 * t56 * t93 - t101 + t108 - fourThird * t132 * t131 + t77 * t36 * t64 + + t77 * t143 * t46 + t88 * t93 - t161; + val_source[2] = t77 * t37 + t77 * t57 + t171 * t93 - t192 + t193 * t64 + 0.2e1 * t88 * t77 * t46 + t203 + t205 + + 0.2e1 / 0.3e1 * t132 * t215; + val_source[3] = 0.0; + val_source[nDim + 1] = t564 + t565 + t566 + t567; } -bool CMMSNSUnitQuadSolution::IsManufacturedSolution(void) const { - return true; -} +bool CMMSNSUnitQuadSolution::IsManufacturedSolution(void) const { return true; } diff --git a/Common/src/toolboxes/MMS/CMMSNSUnitQuadSolutionWallBC.cpp b/Common/src/toolboxes/MMS/CMMSNSUnitQuadSolutionWallBC.cpp index 32fc77ebe74..8fb480d4e4c 100644 --- a/Common/src/toolboxes/MMS/CMMSNSUnitQuadSolutionWallBC.cpp +++ b/Common/src/toolboxes/MMS/CMMSNSUnitQuadSolutionWallBC.cpp @@ -27,14 +27,11 @@ #include "../../../include/toolboxes/MMS/CMMSNSUnitQuadSolutionWallBC.hpp" -CMMSNSUnitQuadSolutionWallBC::CMMSNSUnitQuadSolutionWallBC(void) : CVerificationSolution() { } - -CMMSNSUnitQuadSolutionWallBC::CMMSNSUnitQuadSolutionWallBC(unsigned short val_nDim, - unsigned short val_nVar, - unsigned short val_iMesh, - CConfig* config) - : CVerificationSolution(val_nDim, val_nVar, val_iMesh, config) { +CMMSNSUnitQuadSolutionWallBC::CMMSNSUnitQuadSolutionWallBC(void) : CVerificationSolution() {} +CMMSNSUnitQuadSolutionWallBC::CMMSNSUnitQuadSolutionWallBC(unsigned short val_nDim, unsigned short val_nVar, + unsigned short val_iMesh, CConfig* config) + : CVerificationSolution(val_nDim, val_nVar, val_iMesh, config) { /*--- Write a message that the solution is initialized for the manufactured solution for the Navier-Stokes equations on a unit quad with no-slip wall boundary conditions. ---*/ @@ -50,17 +47,17 @@ CMMSNSUnitQuadSolutionWallBC::CMMSNSUnitQuadSolutionWallBC(unsigned short val_nD /*--- Coefficients, needed to determine the solution. ---*/ const su2double Prandtl = config->GetPrandtl_Lam(); - RGas = config->GetGas_Constant(); - Gamma = config->GetGamma(); - Viscosity = config->GetMu_Constant(); - Conductivity = Viscosity*Gamma*RGas/(Prandtl*(Gamma-1.0)); + RGas = config->GetGas_Constant(); + Gamma = config->GetGamma(); + Viscosity = config->GetMu_Constant(); + Conductivity = Viscosity * Gamma * RGas / (Prandtl * (Gamma - 1.0)); /*--- Initialize TWall to the default value of 300 K (in case the outer wall is not modelled as an isothermal wall) and try to retrieve the wall temperature from the boundary conditions. ---*/ TWall = 300.0; - for(unsigned short iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { - if(config->GetMarker_All_KindBC(iMarker) == ISOTHERMAL) { + for (unsigned short iMarker = 0; iMarker < config->GetnMarker_All(); iMarker++) { + if (config->GetMarker_All_KindBC(iMarker) == ISOTHERMAL) { const string Marker_Tag = config->GetMarker_All_TagBound(iMarker); TWall = config->GetIsothermal_Temperature(Marker_Tag); } @@ -68,105 +65,97 @@ CMMSNSUnitQuadSolutionWallBC::CMMSNSUnitQuadSolutionWallBC(unsigned short val_nD /*--- Get the reference values for pressure, density and velocity. ---*/ Pressure_Ref = config->GetPressure_Ref(); - Density_Ref = config->GetDensity_Ref(); + Density_Ref = config->GetDensity_Ref(); Velocity_Ref = config->GetVelocity_Ref(); /*--- The constants for the density and velocities. ---*/ - rho_0 = 1.25; - u_0 = 135.78; - v_0 = -67.61; + rho_0 = 1.25; + u_0 = 135.78; + v_0 = -67.61; /*--- The constants for the temperature solution. ---*/ - a_T1 = 1.05; + a_T1 = 1.05; a_T2 = -0.85; /*--- Perform some sanity and error checks for this solution here. ---*/ - if(config->GetTime_Marching() != TIME_MARCHING::STEADY) - SU2_MPI::Error("Steady mode must be selected for the MMS NS Unit Quad case with wall BCs.", - CURRENT_FUNCTION); + if (config->GetTime_Marching() != TIME_MARCHING::STEADY) + SU2_MPI::Error("Steady mode must be selected for the MMS NS Unit Quad case with wall BCs.", CURRENT_FUNCTION); - if(Kind_Solver != MAIN_SOLVER::EULER && Kind_Solver != MAIN_SOLVER::NAVIER_STOKES && Kind_Solver != MAIN_SOLVER::RANS && - Kind_Solver != MAIN_SOLVER::FEM_EULER && Kind_Solver != MAIN_SOLVER::FEM_NAVIER_STOKES && Kind_Solver != MAIN_SOLVER::FEM_RANS && - Kind_Solver != MAIN_SOLVER::FEM_LES) + if (Kind_Solver != MAIN_SOLVER::EULER && Kind_Solver != MAIN_SOLVER::NAVIER_STOKES && + Kind_Solver != MAIN_SOLVER::RANS && Kind_Solver != MAIN_SOLVER::FEM_EULER && + Kind_Solver != MAIN_SOLVER::FEM_NAVIER_STOKES && Kind_Solver != MAIN_SOLVER::FEM_RANS && + Kind_Solver != MAIN_SOLVER::FEM_LES) SU2_MPI::Error("Compressible flow equations must be selected for the MMS NS Unit Quad case with wall BCs.", CURRENT_FUNCTION); - if((Kind_Solver != MAIN_SOLVER::NAVIER_STOKES) && - (Kind_Solver != MAIN_SOLVER::FEM_NAVIER_STOKES)) + if ((Kind_Solver != MAIN_SOLVER::NAVIER_STOKES) && (Kind_Solver != MAIN_SOLVER::FEM_NAVIER_STOKES)) SU2_MPI::Error("Navier Stokes equations must be selected for the MMS NS Unit Quad case with wall BCs.", CURRENT_FUNCTION); - if((config->GetKind_FluidModel() != STANDARD_AIR) && - (config->GetKind_FluidModel() != IDEAL_GAS)) + if ((config->GetKind_FluidModel() != STANDARD_AIR) && (config->GetKind_FluidModel() != IDEAL_GAS)) SU2_MPI::Error("Standard air or ideal gas must be selected for the MMS NS Unit Quad case with wall BCs.", CURRENT_FUNCTION); - if(config->GetKind_ViscosityModel() != VISCOSITYMODEL::CONSTANT) + if (config->GetKind_ViscosityModel() != VISCOSITYMODEL::CONSTANT) SU2_MPI::Error("Sutherland must be selected for viscosity for the MMS NS Unit Quad case with wall BCs.", CURRENT_FUNCTION); - if(config->GetKind_ConductivityModel() != CONDUCTIVITYMODEL::CONSTANT_PRANDTL) + if (config->GetKind_ConductivityModel() != CONDUCTIVITYMODEL::CONSTANT_PRANDTL) SU2_MPI::Error("Constant Prandtl number must be selected for the MMS NS Unit Quad case with wall BCs.", CURRENT_FUNCTION); } -CMMSNSUnitQuadSolutionWallBC::~CMMSNSUnitQuadSolutionWallBC(void) { } - -void CMMSNSUnitQuadSolutionWallBC::GetBCState(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const { +CMMSNSUnitQuadSolutionWallBC::~CMMSNSUnitQuadSolutionWallBC(void) {} +void CMMSNSUnitQuadSolutionWallBC::GetBCState(const su2double* val_coords, const su2double val_t, + su2double* val_solution) const { /*--- The exact solution is prescribed on the boundaries. ---*/ GetSolution(val_coords, val_t, val_solution); } -void CMMSNSUnitQuadSolutionWallBC::GetSolution(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const { +void CMMSNSUnitQuadSolutionWallBC::GetSolution(const su2double* val_coords, const su2double val_t, + su2double* val_solution) const { /* Easier storage of the y-coordinate. */ const su2double y = val_coords[1]; /* Determine the dimensional solution for the temperature. */ - const su2double Pi = PI_NUMBER; - const su2double fact = y*y/(a_T1 + a_T2); + const su2double Pi = PI_NUMBER; + const su2double fact = y * y / (a_T1 + a_T2); - su2double T = 0.25*TWall*(3.0 + fact*(a_T1*cos(Pi*(y-1.0)) - + a_T2*cos(Pi*(y-1.0)*2.0))); + su2double T = 0.25 * TWall * (3.0 + fact * (a_T1 * cos(Pi * (y - 1.0)) + a_T2 * cos(Pi * (y - 1.0) * 2.0))); /* Determine the dimensional solution for the velocities. */ - su2double u = u_0*y*(1.0-y)*4.0; - su2double v = v_0*y*(1.0-y)*4.0; + su2double u = u_0 * y * (1.0 - y) * 4.0; + su2double v = v_0 * y * (1.0 - y) * 4.0; /* Compute the pressure from the density and temperature. */ su2double rho = rho_0; - su2double p = rho*RGas*T; + su2double p = rho * RGas * T; /* Determine the non-dimensional solution. */ rho /= Density_Ref; - p /= Pressure_Ref; - u /= Velocity_Ref; - v /= Velocity_Ref; + p /= Pressure_Ref; + u /= Velocity_Ref; + v /= Velocity_Ref; /* Compute the conservative variables from the primitive ones. Note that the implementation below is valid for both 2D and 3D. */ - val_solution[0] = rho; - val_solution[1] = rho*u; - val_solution[2] = rho*v; - val_solution[3] = 0.0; - val_solution[nDim+1] = p/(Gamma-1.0) + 0.5*rho*(u*u + v*v); + val_solution[0] = rho; + val_solution[1] = rho * u; + val_solution[2] = rho * v; + val_solution[3] = 0.0; + val_solution[nDim + 1] = p / (Gamma - 1.0) + 0.5 * rho * (u * u + v * v); } -void CMMSNSUnitQuadSolutionWallBC::GetMMSSourceTerm(const su2double *val_coords, - const su2double val_t, - su2double *val_source) const { - +void CMMSNSUnitQuadSolutionWallBC::GetMMSSourceTerm(const su2double* val_coords, const su2double val_t, + su2double* val_source) const { /*--- Abbreviate Pi and the y-coordinate. ---*/ const su2double Pi = PI_NUMBER; const su2double y = val_coords[1]; /*--- The source code for the source terms is generated in Maple. See the file CMMSNSUnitQuadSolutionWallBC.mw in the directory - CreateMMSSourceTerms for the details how to do this. ---*/ + CreateMMSSourceTerms for the details how to do this. ---*/ const su2double t1 = (v_0 * rho_0); const su2double t2 = 1.0 - y; const su2double t6 = rho_0 * u_0; @@ -210,27 +199,31 @@ void CMMSNSUnitQuadSolutionWallBC::GetMMSSourceTerm(const su2double *val_coords, const su2double t118 = a_T2 * y; const su2double t138 = Viscosity * (-8.0 * y + 4.0); const su2double t149 = Viscosity * (2.0 * y - 1.0); - const su2double t155 = 0.4e1 * t75 * v_0 * (t57 * t50 * t26 / 0.4e1 + (16.0 * (-t2 * t64 - t2 * t68 + t7 * t62 + t7 * t66) * rho_0) + t52) - + 0.4e1 * t2 * t92 - 0.4e1 * y * t92 - Conductivity * t111 * (-t102 * Pi * t41 - 0.4e1 * y * t43 * t97 + 0.4e1 * t104 * a_T2 - - 0.2e1 * a_T2 + 0.2e1 * t32) * TWall - Conductivity * t111 * (-t102 * t31 * t115 - 0.4e1 * t118 * t115 * t104 - + 0.4e1 * t118 * t116 * t115 - 0.12e2 * t43 * t97 - 0.3e1 * t42) * TWall * y + (32.0 * t75 * t61 * Viscosity) - - (4.0 * t2 * t61 * t138) + (4.0 * t62 * t138) + 0.128e3 / 0.3e1 * t75 * t20 * Viscosity + 0.64e2 / 0.3e1 * t2 * t20 * t149 - - 0.64e2 / 0.3e1 * t66 * t149; + const su2double t155 = + 0.4e1 * t75 * v_0 * + (t57 * t50 * t26 / 0.4e1 + (16.0 * (-t2 * t64 - t2 * t68 + t7 * t62 + t7 * t66) * rho_0) + t52) + + 0.4e1 * t2 * t92 - 0.4e1 * y * t92 - + Conductivity * t111 * + (-t102 * Pi * t41 - 0.4e1 * y * t43 * t97 + 0.4e1 * t104 * a_T2 - 0.2e1 * a_T2 + 0.2e1 * t32) * TWall - + Conductivity * t111 * + (-t102 * t31 * t115 - 0.4e1 * t118 * t115 * t104 + 0.4e1 * t118 * t116 * t115 - 0.12e2 * t43 * t97 - + 0.3e1 * t42) * + TWall * y + + (32.0 * t75 * t61 * Viscosity) - (4.0 * t2 * t61 * t138) + (4.0 * t62 * t138) + + 0.128e3 / 0.3e1 * t75 * t20 * Viscosity + 0.64e2 / 0.3e1 * t2 * t20 * t149 - 0.64e2 / 0.3e1 * t66 * t149; /*--- Set the source term, which is valid for both 2D and 3D cases. Note the scaling for the correct non-dimensionalization. ---*/ - val_source[0] = 4.0 * t2 * t1 - 4.0 * y * t1; - val_source[1] = (-0.32e2 * v_0 * t13 * t6 + 0.32e2 * v_0 * t8 * t6 + (8.0 * Viscosity * u_0)); - val_source[2] = ((32.0 * t8 * t21) - (32.0 * t13 * t21) + t52 + 0.32e2 / 0.3e1 * Viscosity * v_0); - val_source[3] = 0.0; - val_source[nDim+1] = t155; - - val_source[0] /= Density_Ref*Velocity_Ref; - val_source[1] /= Pressure_Ref; - val_source[2] /= Pressure_Ref; - val_source[nDim+1] /= Velocity_Ref*Pressure_Ref; + val_source[0] = 4.0 * t2 * t1 - 4.0 * y * t1; + val_source[1] = (-0.32e2 * v_0 * t13 * t6 + 0.32e2 * v_0 * t8 * t6 + (8.0 * Viscosity * u_0)); + val_source[2] = ((32.0 * t8 * t21) - (32.0 * t13 * t21) + t52 + 0.32e2 / 0.3e1 * Viscosity * v_0); + val_source[3] = 0.0; + val_source[nDim + 1] = t155; + + val_source[0] /= Density_Ref * Velocity_Ref; + val_source[1] /= Pressure_Ref; + val_source[2] /= Pressure_Ref; + val_source[nDim + 1] /= Velocity_Ref * Pressure_Ref; } -bool CMMSNSUnitQuadSolutionWallBC::IsManufacturedSolution(void) const { - return true; -} +bool CMMSNSUnitQuadSolutionWallBC::IsManufacturedSolution(void) const { return true; } diff --git a/Common/src/toolboxes/MMS/CNSUnitQuadSolution.cpp b/Common/src/toolboxes/MMS/CNSUnitQuadSolution.cpp index f3b9519e379..b98995b1d50 100644 --- a/Common/src/toolboxes/MMS/CNSUnitQuadSolution.cpp +++ b/Common/src/toolboxes/MMS/CNSUnitQuadSolution.cpp @@ -27,14 +27,11 @@ #include "../../../include/toolboxes/MMS/CNSUnitQuadSolution.hpp" -CNSUnitQuadSolution::CNSUnitQuadSolution(void) : CVerificationSolution() { } - -CNSUnitQuadSolution::CNSUnitQuadSolution(unsigned short val_nDim, - unsigned short val_nVar, - unsigned short val_iMesh, - CConfig* config) - : CVerificationSolution(val_nDim, val_nVar, val_iMesh, config) { +CNSUnitQuadSolution::CNSUnitQuadSolution(void) : CVerificationSolution() {} +CNSUnitQuadSolution::CNSUnitQuadSolution(unsigned short val_nDim, unsigned short val_nVar, unsigned short val_iMesh, + CConfig* config) + : CVerificationSolution(val_nDim, val_nVar, val_iMesh, config) { /*--- Write a message that the solution is initialized for the Navier-Stokes case on a unit quad. Note that heat conduction is neglected for this case. ---*/ @@ -49,75 +46,61 @@ CNSUnitQuadSolution::CNSUnitQuadSolution(unsigned short val_nDim, } /*--- Coefficients, needed to determine the solution. ---*/ - Gm1 = config->GetGamma() - 1.0; - flowAngle = config->GetAoA()*PI_NUMBER/180.0; + Gm1 = config->GetGamma() - 1.0; + flowAngle = config->GetAoA() * PI_NUMBER / 180.0; Viscosity = config->GetMu_ConstantND(); /*--- Perform some sanity and error checks for this solution here. ---*/ - if(config->GetTime_Marching() != TIME_MARCHING::STEADY) - SU2_MPI::Error("Steady mode must be selected for the NS Unit Quad case", - CURRENT_FUNCTION); - - if(Kind_Solver != MAIN_SOLVER::EULER && Kind_Solver != MAIN_SOLVER::NAVIER_STOKES && Kind_Solver != MAIN_SOLVER::RANS && - Kind_Solver != MAIN_SOLVER::FEM_EULER && Kind_Solver != MAIN_SOLVER::FEM_NAVIER_STOKES && Kind_Solver != MAIN_SOLVER::FEM_RANS && - Kind_Solver != MAIN_SOLVER::FEM_LES) - SU2_MPI::Error("Compressible flow equations must be selected for the NS Unit Quad case", - CURRENT_FUNCTION); - - if((Kind_Solver != MAIN_SOLVER::NAVIER_STOKES) && - (Kind_Solver != MAIN_SOLVER::FEM_NAVIER_STOKES)) - SU2_MPI::Error("Navier Stokes equations must be selected for the NS Unit Quad case", - CURRENT_FUNCTION); - - if(config->GetKind_FluidModel() != IDEAL_GAS) - SU2_MPI::Error("Ideal gas must be selected for the NS Unit Quad case", - CURRENT_FUNCTION); - - if(fabs(Gm1-0.5) > 1.e-8) - SU2_MPI::Error("Gamma must be 1.5 for the NS Unit Quad case", - CURRENT_FUNCTION); - - if(config->GetKind_ViscosityModel() != VISCOSITYMODEL::CONSTANT) - SU2_MPI::Error("Constant viscosity must be selected for the NS Unit Quad case", - CURRENT_FUNCTION); - - if(config->GetKind_ConductivityModel() != CONDUCTIVITYMODEL::CONSTANT_PRANDTL) - SU2_MPI::Error("Constant Prandtl number must be selected for the NS Unit Quad case", - CURRENT_FUNCTION); - - if(config->GetPrandtl_Lam() < 1.e+20) - SU2_MPI::Error("Laminar Prandtl number must be larger than 1.e+20 for the NS Unit Quad case", - CURRENT_FUNCTION); -} + if (config->GetTime_Marching() != TIME_MARCHING::STEADY) + SU2_MPI::Error("Steady mode must be selected for the NS Unit Quad case", CURRENT_FUNCTION); + + if (Kind_Solver != MAIN_SOLVER::EULER && Kind_Solver != MAIN_SOLVER::NAVIER_STOKES && + Kind_Solver != MAIN_SOLVER::RANS && Kind_Solver != MAIN_SOLVER::FEM_EULER && + Kind_Solver != MAIN_SOLVER::FEM_NAVIER_STOKES && Kind_Solver != MAIN_SOLVER::FEM_RANS && + Kind_Solver != MAIN_SOLVER::FEM_LES) + SU2_MPI::Error("Compressible flow equations must be selected for the NS Unit Quad case", CURRENT_FUNCTION); + + if ((Kind_Solver != MAIN_SOLVER::NAVIER_STOKES) && (Kind_Solver != MAIN_SOLVER::FEM_NAVIER_STOKES)) + SU2_MPI::Error("Navier Stokes equations must be selected for the NS Unit Quad case", CURRENT_FUNCTION); + + if (config->GetKind_FluidModel() != IDEAL_GAS) + SU2_MPI::Error("Ideal gas must be selected for the NS Unit Quad case", CURRENT_FUNCTION); -CNSUnitQuadSolution::~CNSUnitQuadSolution(void) { } + if (fabs(Gm1 - 0.5) > 1.e-8) SU2_MPI::Error("Gamma must be 1.5 for the NS Unit Quad case", CURRENT_FUNCTION); -void CNSUnitQuadSolution::GetBCState(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const { + if (config->GetKind_ViscosityModel() != VISCOSITYMODEL::CONSTANT) + SU2_MPI::Error("Constant viscosity must be selected for the NS Unit Quad case", CURRENT_FUNCTION); + if (config->GetKind_ConductivityModel() != CONDUCTIVITYMODEL::CONSTANT_PRANDTL) + SU2_MPI::Error("Constant Prandtl number must be selected for the NS Unit Quad case", CURRENT_FUNCTION); + + if (config->GetPrandtl_Lam() < 1.e+20) + SU2_MPI::Error("Laminar Prandtl number must be larger than 1.e+20 for the NS Unit Quad case", CURRENT_FUNCTION); +} + +CNSUnitQuadSolution::~CNSUnitQuadSolution(void) {} + +void CNSUnitQuadSolution::GetBCState(const su2double* val_coords, const su2double val_t, + su2double* val_solution) const { /*--- The exact solution is prescribed on the boundaries. ---*/ GetSolution(val_coords, val_t, val_solution); } -void CNSUnitQuadSolution::GetSolution(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const { - +void CNSUnitQuadSolution::GetSolution(const su2double* val_coords, const su2double val_t, + su2double* val_solution) const { /*--- Compute the flow direction and the coordinates in the rotated frame. ---*/ const su2double cosFlowAngle = cos(flowAngle); const su2double sinFlowAngle = sin(flowAngle); - const su2double xTilde = val_coords[0]*cosFlowAngle - val_coords[1]*sinFlowAngle; - const su2double yTilde = val_coords[0]*sinFlowAngle + val_coords[1]*cosFlowAngle; + const su2double xTilde = val_coords[0] * cosFlowAngle - val_coords[1] * sinFlowAngle; + const su2double yTilde = val_coords[0] * sinFlowAngle + val_coords[1] * cosFlowAngle; /*--- Compute the exact solution for this case. Note that it works both in 2D and 3D. ---*/ - val_solution[0] = 1.0; - val_solution[1] = cosFlowAngle*yTilde*yTilde; - val_solution[2] = -sinFlowAngle*yTilde*yTilde; - val_solution[3] = 0.0; - val_solution[nVar-1] = (2.0*Viscosity*xTilde + 10.0)/Gm1 - + 0.5*yTilde*yTilde*yTilde*yTilde; + val_solution[0] = 1.0; + val_solution[1] = cosFlowAngle * yTilde * yTilde; + val_solution[2] = -sinFlowAngle * yTilde * yTilde; + val_solution[3] = 0.0; + val_solution[nVar - 1] = (2.0 * Viscosity * xTilde + 10.0) / Gm1 + 0.5 * yTilde * yTilde * yTilde * yTilde; } diff --git a/Common/src/toolboxes/MMS/CRinglebSolution.cpp b/Common/src/toolboxes/MMS/CRinglebSolution.cpp index 09012fbc4cb..ed2870662fd 100644 --- a/Common/src/toolboxes/MMS/CRinglebSolution.cpp +++ b/Common/src/toolboxes/MMS/CRinglebSolution.cpp @@ -27,14 +27,11 @@ #include "../../../include/toolboxes/MMS/CRinglebSolution.hpp" -CRinglebSolution::CRinglebSolution(void) : CVerificationSolution() { } - -CRinglebSolution::CRinglebSolution(unsigned short val_nDim, - unsigned short val_nVar, - unsigned short val_iMesh, - CConfig* config) - : CVerificationSolution(val_nDim, val_nVar, val_iMesh, config) { +CRinglebSolution::CRinglebSolution(void) : CVerificationSolution() {} +CRinglebSolution::CRinglebSolution(unsigned short val_nDim, unsigned short val_nVar, unsigned short val_iMesh, + CConfig* config) + : CVerificationSolution(val_nDim, val_nVar, val_iMesh, config) { /*--- Write a message that the solution is initialized for the Ringleb test case. ---*/ if ((rank == MASTER_NODE) && (val_iMesh == MESH_0)) { @@ -45,39 +42,31 @@ CRinglebSolution::CRinglebSolution(unsigned short val_nDim, } /*--- Useful coefficients in which Gamma is present. ---*/ - Gamma = config->GetGamma(); - Gm1 = Gamma - 1.0; - tovGm1 = 2.0/Gm1; - tGamOvGm1 = Gamma*tovGm1; + Gamma = config->GetGamma(); + Gm1 = Gamma - 1.0; + tovGm1 = 2.0 / Gm1; + tGamOvGm1 = Gamma * tovGm1; /*--- Perform some sanity and error checks for this solution here. ---*/ - if(config->GetTime_Marching() != TIME_MARCHING::STEADY) - SU2_MPI::Error("Steady mode must be selected for the Ringleb case", - CURRENT_FUNCTION); - - if(Kind_Solver != MAIN_SOLVER::EULER && Kind_Solver != MAIN_SOLVER::NAVIER_STOKES && Kind_Solver != MAIN_SOLVER::RANS && - Kind_Solver != MAIN_SOLVER::FEM_EULER && Kind_Solver != MAIN_SOLVER::FEM_NAVIER_STOKES && Kind_Solver != MAIN_SOLVER::FEM_RANS && - Kind_Solver != MAIN_SOLVER::FEM_LES) - SU2_MPI::Error("Compressible flow equations must be selected for the Ringleb case", - CURRENT_FUNCTION); - - if((Kind_Solver != MAIN_SOLVER::EULER) && - (Kind_Solver != MAIN_SOLVER::FEM_EULER)) - SU2_MPI::Error("Euler equations must be selected for the Ringleb case", - CURRENT_FUNCTION); - - if((config->GetKind_FluidModel() != STANDARD_AIR) && - (config->GetKind_FluidModel() != IDEAL_GAS)) - SU2_MPI::Error("Standard air or ideal gas must be selected for the Ringleb case", - CURRENT_FUNCTION); -} + if (config->GetTime_Marching() != TIME_MARCHING::STEADY) + SU2_MPI::Error("Steady mode must be selected for the Ringleb case", CURRENT_FUNCTION); + + if (Kind_Solver != MAIN_SOLVER::EULER && Kind_Solver != MAIN_SOLVER::NAVIER_STOKES && + Kind_Solver != MAIN_SOLVER::RANS && Kind_Solver != MAIN_SOLVER::FEM_EULER && + Kind_Solver != MAIN_SOLVER::FEM_NAVIER_STOKES && Kind_Solver != MAIN_SOLVER::FEM_RANS && + Kind_Solver != MAIN_SOLVER::FEM_LES) + SU2_MPI::Error("Compressible flow equations must be selected for the Ringleb case", CURRENT_FUNCTION); + + if ((Kind_Solver != MAIN_SOLVER::EULER) && (Kind_Solver != MAIN_SOLVER::FEM_EULER)) + SU2_MPI::Error("Euler equations must be selected for the Ringleb case", CURRENT_FUNCTION); -CRinglebSolution::~CRinglebSolution(void) { } + if ((config->GetKind_FluidModel() != STANDARD_AIR) && (config->GetKind_FluidModel() != IDEAL_GAS)) + SU2_MPI::Error("Standard air or ideal gas must be selected for the Ringleb case", CURRENT_FUNCTION); +} -void CRinglebSolution::GetBCState(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const { +CRinglebSolution::~CRinglebSolution(void) {} +void CRinglebSolution::GetBCState(const su2double* val_coords, const su2double val_t, su2double* val_solution) const { /*--- The exact solution is prescribed on the boundaries for the Ringleb flow. Note that a (much) more difficult test case is to use inviscid wall boundary conditions for the inner and outer @@ -85,13 +74,10 @@ void CRinglebSolution::GetBCState(const su2double *val_coords, GetSolution(val_coords, val_t, val_solution); } -void CRinglebSolution::GetSolution(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const { - +void CRinglebSolution::GetSolution(const su2double* val_coords, const su2double val_t, su2double* val_solution) const { /* Easier storage of the coordinates and abbreviate y*y. */ - const su2double x = val_coords[0], y = val_coords[1]; - const su2double y2 = y*y; + const su2double x = val_coords[0], y = val_coords[1]; + const su2double y2 = y * y; /* Initial guess for q (velocity magnitude) and k (streamline parameter). */ su2double k = 1.2; @@ -102,85 +88,85 @@ void CRinglebSolution::GetSolution(const su2double *val_coords, su2double duMaxPrev = 10.0; int iter; - for(iter=0; iter 1.0) alp = 0.04; - else if(dUMax > 0.1) alp = 0.2; + if (dUMax > 1.0) + alp = 0.04; + else if (dUMax > 0.1) + alp = 0.2; /* Update q and k. */ - q -= alp*dU[0]; - k -= alp*dU[1]; + q -= alp * dU[0]; + k -= alp * dU[1]; /* Convergence check, which is independent of the precision used. */ - if((dUMax < 1.e-3) && (dUMax >= duMaxPrev)) break; + if ((dUMax < 1.e-3) && (dUMax >= duMaxPrev)) break; duMaxPrev = dUMax; } /* Check if the Newton algorithm actually converged. */ - if(iter == iterMax) - SU2_MPI::Error("Newton algorithm did not converge", CURRENT_FUNCTION); + if (iter == iterMax) SU2_MPI::Error("Newton algorithm did not converge", CURRENT_FUNCTION); /* Compute the speed of sound, density and pressure. */ - const su2double a = sqrt(1.0 - 0.5*Gm1*q*q); - const su2double rho = pow(a,tovGm1); - const su2double p = pow(a,tGamOvGm1)/Gamma; + const su2double a = sqrt(1.0 - 0.5 * Gm1 * q * q); + const su2double rho = pow(a, tovGm1); + const su2double p = pow(a, tGamOvGm1) / Gamma; /* Determine the derivative of x w.r.t. q and ydxdq. */ - const su2double dadq = -0.5*Gm1*q/a; - const su2double drhodq = 2.0*rho*dadq/(Gm1*a); - const su2double dJJdq = dadq/(pow(a,6)*(a*a-1.0)); + const su2double dadq = -0.5 * Gm1 * q / a; + const su2double drhodq = 2.0 * rho * dadq / (Gm1 * a); + const su2double dJJdq = dadq / (pow(a, 6) * (a * a - 1.0)); - const su2double dxdq = -(1.0/(k*k) - 0.5/(q*q))*drhodq/(rho*rho) - + 1.0/(rho*q*q*q) - 0.5*dJJdq; - const su2double ydxdq = y*dxdq; + const su2double dxdq = + -(1.0 / (k * k) - 0.5 / (q * q)) * drhodq / (rho * rho) + 1.0 / (rho * q * q * q) - 0.5 * dJJdq; + const su2double ydxdq = y * dxdq; /* Determine the derivative of 1/2 y2 w.r.t. q, which is ydydq. The reason is that ydydq is always well defined, while dydq is singular for y = 0. */ - const su2double ydydq = drhodq*(q*q-k*k)/(k*k*k*k*rho*rho*rho*q*q) - - 1.0/(k*k*rho*rho*q*q*q); + const su2double ydydq = + drhodq * (q * q - k * k) / (k * k * k * k * rho * rho * rho * q * q) - 1.0 / (k * k * rho * rho * q * q * q); /* Determine the direction of the streamline. */ - const su2double vecLen = sqrt(ydxdq*ydxdq + ydydq*ydydq); + const su2double vecLen = sqrt(ydxdq * ydxdq + ydydq * ydydq); - su2double velDir[] = {ydxdq/vecLen, ydydq/vecLen}; - if(velDir[1] > 0.0){velDir[0] = -velDir[0]; velDir[1] = -velDir[1];} + su2double velDir[] = {ydxdq / vecLen, ydydq / vecLen}; + if (velDir[1] > 0.0) { + velDir[0] = -velDir[0]; + velDir[1] = -velDir[1]; + } /* Compute the conservative variables. Note that both 2D and 3D cases are treated correctly. */ - val_solution[0] = rho; - val_solution[1] = rho*q*velDir[0]; - val_solution[2] = rho*q*velDir[1]; - val_solution[3] = 0.0; - val_solution[nVar-1] = p/Gm1 + 0.5*rho*q*q; + val_solution[0] = rho; + val_solution[1] = rho * q * velDir[0]; + val_solution[2] = rho * q * velDir[1]; + val_solution[3] = 0.0; + val_solution[nVar - 1] = p / Gm1 + 0.5 * rho * q * q; } diff --git a/Common/src/toolboxes/MMS/CTGVSolution.cpp b/Common/src/toolboxes/MMS/CTGVSolution.cpp index 77eaf387213..f561b9b54a6 100644 --- a/Common/src/toolboxes/MMS/CTGVSolution.cpp +++ b/Common/src/toolboxes/MMS/CTGVSolution.cpp @@ -27,14 +27,10 @@ #include "../../../include/toolboxes/MMS/CTGVSolution.hpp" -CTGVSolution::CTGVSolution(void) : CVerificationSolution() { } - -CTGVSolution::CTGVSolution(unsigned short val_nDim, - unsigned short val_nVar, - unsigned short val_iMesh, - CConfig* config) - : CVerificationSolution(val_nDim, val_nVar, val_iMesh, config) { +CTGVSolution::CTGVSolution(void) : CVerificationSolution() {} +CTGVSolution::CTGVSolution(unsigned short val_nDim, unsigned short val_nVar, unsigned short val_iMesh, CConfig* config) + : CVerificationSolution(val_nDim, val_nVar, val_iMesh, config) { /*--- Write a message that the solution is initialized for the Taylor-Green vortex test case. ---*/ @@ -47,88 +43,74 @@ CTGVSolution::CTGVSolution(unsigned short val_nDim, /*--- Store TGV specific parameters here. ---*/ - tgvLength = 1.0; // Taylor-Green length scale. - tgvVelocity = 1.0; // Taylor-Green velocity. - tgvDensity = 1.0; // Taylor-Green density. - tgvPressure = 100.0; // Taylor-Green pressure. + tgvLength = 1.0; // Taylor-Green length scale. + tgvVelocity = 1.0; // Taylor-Green velocity. + tgvDensity = 1.0; // Taylor-Green density. + tgvPressure = 100.0; // Taylor-Green pressure. /*--- Useful coefficient in which Gamma is present. ---*/ - ovGm1 = 1.0/(config->GetGamma() - 1.0); + ovGm1 = 1.0 / (config->GetGamma() - 1.0); /*--- Perform some sanity and error checks for this solution here. ---*/ - if((config->GetTime_Marching() != TIME_MARCHING::TIME_STEPPING) && - (config->GetTime_Marching() != TIME_MARCHING::DT_STEPPING_1ST) && - (config->GetTime_Marching() != TIME_MARCHING::DT_STEPPING_2ND)) - SU2_MPI::Error("Unsteady mode must be selected for the Taylor Green Vortex", - CURRENT_FUNCTION); - - if(Kind_Solver != MAIN_SOLVER::EULER && Kind_Solver != MAIN_SOLVER::NAVIER_STOKES && Kind_Solver != MAIN_SOLVER::RANS && - Kind_Solver != MAIN_SOLVER::FEM_EULER && Kind_Solver != MAIN_SOLVER::FEM_NAVIER_STOKES && Kind_Solver != MAIN_SOLVER::FEM_RANS && - Kind_Solver != MAIN_SOLVER::FEM_LES) - SU2_MPI::Error("Compressible flow equations must be selected for the Taylor Green Vortex", - CURRENT_FUNCTION); - - if((Kind_Solver != MAIN_SOLVER::NAVIER_STOKES) && - (Kind_Solver != MAIN_SOLVER::FEM_NAVIER_STOKES)) - SU2_MPI::Error("Navier Stokes equations must be selected for the Taylor Green Vortex", - CURRENT_FUNCTION); - - if((config->GetKind_FluidModel() != STANDARD_AIR) && - (config->GetKind_FluidModel() != IDEAL_GAS)) - SU2_MPI::Error("Standard air or ideal gas must be selected for the Taylor Green Vortex", - CURRENT_FUNCTION); - - if(config->GetKind_ViscosityModel() != VISCOSITYMODEL::CONSTANT) - SU2_MPI::Error("Constant viscosity must be selected for the Taylor Green Vortex", - CURRENT_FUNCTION); - - if(config->GetKind_ConductivityModel() != CONDUCTIVITYMODEL::CONSTANT_PRANDTL) - SU2_MPI::Error("Constant Prandtl number must be selected for the Taylor Green Vortex", - CURRENT_FUNCTION); -} + if ((config->GetTime_Marching() != TIME_MARCHING::TIME_STEPPING) && + (config->GetTime_Marching() != TIME_MARCHING::DT_STEPPING_1ST) && + (config->GetTime_Marching() != TIME_MARCHING::DT_STEPPING_2ND)) + SU2_MPI::Error("Unsteady mode must be selected for the Taylor Green Vortex", CURRENT_FUNCTION); + + if (Kind_Solver != MAIN_SOLVER::EULER && Kind_Solver != MAIN_SOLVER::NAVIER_STOKES && + Kind_Solver != MAIN_SOLVER::RANS && Kind_Solver != MAIN_SOLVER::FEM_EULER && + Kind_Solver != MAIN_SOLVER::FEM_NAVIER_STOKES && Kind_Solver != MAIN_SOLVER::FEM_RANS && + Kind_Solver != MAIN_SOLVER::FEM_LES) + SU2_MPI::Error("Compressible flow equations must be selected for the Taylor Green Vortex", CURRENT_FUNCTION); + + if ((Kind_Solver != MAIN_SOLVER::NAVIER_STOKES) && (Kind_Solver != MAIN_SOLVER::FEM_NAVIER_STOKES)) + SU2_MPI::Error("Navier Stokes equations must be selected for the Taylor Green Vortex", CURRENT_FUNCTION); -CTGVSolution::~CTGVSolution(void) { } + if ((config->GetKind_FluidModel() != STANDARD_AIR) && (config->GetKind_FluidModel() != IDEAL_GAS)) + SU2_MPI::Error("Standard air or ideal gas must be selected for the Taylor Green Vortex", CURRENT_FUNCTION); + + if (config->GetKind_ViscosityModel() != VISCOSITYMODEL::CONSTANT) + SU2_MPI::Error("Constant viscosity must be selected for the Taylor Green Vortex", CURRENT_FUNCTION); + + if (config->GetKind_ConductivityModel() != CONDUCTIVITYMODEL::CONSTANT_PRANDTL) + SU2_MPI::Error("Constant Prandtl number must be selected for the Taylor Green Vortex", CURRENT_FUNCTION); +} -void CTGVSolution::GetSolution(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const { +CTGVSolution::~CTGVSolution(void) {} +void CTGVSolution::GetSolution(const su2double* val_coords, const su2double val_t, su2double* val_solution) const { /* The initial conditions are set for the Taylor-Green vortex case, which is a DNS case that features vortex breakdown into turbulence. These particular settings are for the typical Re = 1600 case (M = 0.08) with an initial temperature of 300 K. Note that this condition works in both 2D and 3D. */ - su2double val_coordsZ = 0.0; + su2double val_coordsZ = 0.0; if (nDim == 3) val_coordsZ = val_coords[2]; /* Compute the primitive variables. */ - su2double rho = tgvDensity; - su2double u = tgvVelocity * (sin(val_coords[0]/tgvLength)* - cos(val_coords[1]/tgvLength)* - cos(val_coordsZ /tgvLength)); - su2double v = -tgvVelocity * (cos(val_coords[0]/tgvLength)* - sin(val_coords[1]/tgvLength)* - cos(val_coordsZ /tgvLength)); + su2double rho = tgvDensity; + su2double u = + tgvVelocity * (sin(val_coords[0] / tgvLength) * cos(val_coords[1] / tgvLength) * cos(val_coordsZ / tgvLength)); + su2double v = + -tgvVelocity * (cos(val_coords[0] / tgvLength) * sin(val_coords[1] / tgvLength) * cos(val_coordsZ / tgvLength)); - su2double factorA = cos(2.0*val_coordsZ/tgvLength) + 2.0; - su2double factorB = (cos(2.0*val_coords[0]/tgvLength) + - cos(2.0*val_coords[1]/tgvLength)); + su2double factorA = cos(2.0 * val_coordsZ / tgvLength) + 2.0; + su2double factorB = (cos(2.0 * val_coords[0] / tgvLength) + cos(2.0 * val_coords[1] / tgvLength)); - su2double p = (tgvPressure + - tgvDensity*(pow(tgvVelocity,2.0)/16.0)*factorA*factorB); + su2double p = (tgvPressure + tgvDensity * (pow(tgvVelocity, 2.0) / 16.0) * factorA * factorB); /* Compute the conservative variables. Note that both 2D and 3D cases are treated correctly. */ - val_solution[0] = rho; - val_solution[1] = rho*u; - val_solution[2] = rho*v; - val_solution[3] = 0.0; - val_solution[nVar-1] = p*ovGm1 + 0.5*rho*(u*u + v*v); + val_solution[0] = rho; + val_solution[1] = rho * u; + val_solution[2] = rho * v; + val_solution[3] = 0.0; + val_solution[nVar - 1] = p * ovGm1 + 0.5 * rho * (u * u + v * v); } -bool CTGVSolution::ExactSolutionKnown(void) const {return false;} +bool CTGVSolution::ExactSolutionKnown(void) const { return false; } diff --git a/Common/src/toolboxes/MMS/CUserDefinedSolution.cpp b/Common/src/toolboxes/MMS/CUserDefinedSolution.cpp index 2332a27d5da..da2806cfcd2 100644 --- a/Common/src/toolboxes/MMS/CUserDefinedSolution.cpp +++ b/Common/src/toolboxes/MMS/CUserDefinedSolution.cpp @@ -27,14 +27,11 @@ #include "../../../include/toolboxes/MMS/CUserDefinedSolution.hpp" -CUserDefinedSolution::CUserDefinedSolution(void) : CVerificationSolution() { } - -CUserDefinedSolution::CUserDefinedSolution(unsigned short val_nDim, - unsigned short val_nVar, - unsigned short val_iMesh, - CConfig* config) - : CVerificationSolution(val_nDim, val_nVar, val_iMesh, config) { +CUserDefinedSolution::CUserDefinedSolution(void) : CVerificationSolution() {} +CUserDefinedSolution::CUserDefinedSolution(unsigned short val_nDim, unsigned short val_nVar, unsigned short val_iMesh, + CConfig* config) + : CVerificationSolution(val_nDim, val_nVar, val_iMesh, config) { /*--- Write a message that the solution is initialized for a user-defined verification case. ---*/ @@ -48,30 +45,24 @@ CUserDefinedSolution::CUserDefinedSolution(unsigned short val_nDim, SU2_MPI::Error("User must implement this function", CURRENT_FUNCTION); } -CUserDefinedSolution::~CUserDefinedSolution(void) { } - -void CUserDefinedSolution::GetBCState(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const { +CUserDefinedSolution::~CUserDefinedSolution(void) {} +void CUserDefinedSolution::GetBCState(const su2double* val_coords, const su2double val_t, + su2double* val_solution) const { SU2_MPI::Error("User must implement this function", CURRENT_FUNCTION); } -void CUserDefinedSolution::GetSolution(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const { - +void CUserDefinedSolution::GetSolution(const su2double* val_coords, const su2double val_t, + su2double* val_solution) const { SU2_MPI::Error("User must implement this function", CURRENT_FUNCTION); } -void CUserDefinedSolution::GetMMSSourceTerm(const su2double *val_coords, - const su2double val_t, - su2double *val_source) const { - +void CUserDefinedSolution::GetMMSSourceTerm(const su2double* val_coords, const su2double val_t, + su2double* val_source) const { SU2_MPI::Error("User must implement this function", CURRENT_FUNCTION); } bool CUserDefinedSolution::IsManufacturedSolution(void) const { SU2_MPI::Error("User must implement this function", CURRENT_FUNCTION); - return false; /* True if manufactured. */ + return false; /* True if manufactured. */ } diff --git a/Common/src/toolboxes/MMS/CVerificationSolution.cpp b/Common/src/toolboxes/MMS/CVerificationSolution.cpp index e5f707a015c..ff8687aad87 100644 --- a/Common/src/toolboxes/MMS/CVerificationSolution.cpp +++ b/Common/src/toolboxes/MMS/CVerificationSolution.cpp @@ -28,18 +28,15 @@ #include "../../../include/toolboxes/MMS/CVerificationSolution.hpp" CVerificationSolution::CVerificationSolution(void) { - /*--- Initialize the pointers to NULL. ---*/ - Error_RMS = nullptr; - Error_Max = nullptr; - Error_Point_Max = nullptr; + Error_RMS = nullptr; + Error_Max = nullptr; + Error_Point_Max = nullptr; Error_Point_Max_Coord = nullptr; } -CVerificationSolution::CVerificationSolution(unsigned short val_nDim, - unsigned short val_nVar, - unsigned short val_iMesh, - CConfig* config) { +CVerificationSolution::CVerificationSolution(unsigned short val_nDim, unsigned short val_nVar, unsigned short val_iMesh, + CConfig* config) { /*--- Store the kind of solver ---*/ Kind_Solver = config->GetKind_Solver(); @@ -59,73 +56,58 @@ CVerificationSolution::CVerificationSolution(unsigned short val_nDim, Error_Max = new su2double[nVar]; Error_Point_Max = new unsigned long[nVar]; - for (unsigned short iVar = 0; iVar < nVar; iVar++) - Error_Point_Max[iVar] = 0; + for (unsigned short iVar = 0; iVar < nVar; iVar++) Error_Point_Max[iVar] = 0; Error_Point_Max_Coord = new su2double*[nVar]; for (unsigned short iVar = 0; iVar < nVar; iVar++) { Error_Point_Max_Coord[iVar] = new su2double[nDim]; - for (unsigned short iDim = 0; iDim < nDim; iDim++) - Error_Point_Max_Coord[iVar][iDim] = 0.0; + for (unsigned short iDim = 0; iDim < nDim; iDim++) Error_Point_Max_Coord[iVar][iDim] = 0.0; } } CVerificationSolution::~CVerificationSolution(void) { - /*--- Release the memory of the pointers, if allocated. ---*/ - delete [] Error_RMS; - delete [] Error_Max; + delete[] Error_RMS; + delete[] Error_Max; - delete [] Error_Point_Max; + delete[] Error_Point_Max; if (Error_Point_Max_Coord != nullptr) { for (unsigned short iVar = 0; iVar < nVar; iVar++) { - delete [] Error_Point_Max_Coord[iVar]; + delete[] Error_Point_Max_Coord[iVar]; } - delete [] Error_Point_Max_Coord; + delete[] Error_Point_Max_Coord; } } -void CVerificationSolution::GetSolution(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const { - +void CVerificationSolution::GetSolution(const su2double* val_coords, const su2double val_t, + su2double* val_solution) const { SU2_MPI::Error("Function must be overwritten by the derived class", CURRENT_FUNCTION); } -void CVerificationSolution::GetInitialCondition(const su2double *val_coords, - su2double *val_solution) const { - +void CVerificationSolution::GetInitialCondition(const su2double* val_coords, su2double* val_solution) const { /*--- Initial conditions call the GetSolution() method at t = 0. ---*/ GetSolution(val_coords, 0.0, val_solution); } -void CVerificationSolution::GetBCState(const su2double *val_coords, - const su2double val_t, - su2double *val_solution) const { - +void CVerificationSolution::GetBCState(const su2double* val_coords, const su2double val_t, + su2double* val_solution) const { SU2_MPI::Error("Function must be overwritten by the derived class", CURRENT_FUNCTION); } -void CVerificationSolution::GetMMSSourceTerm(const su2double *val_coords, - const su2double val_t, - su2double *val_source) const { - +void CVerificationSolution::GetMMSSourceTerm(const su2double* val_coords, const su2double val_t, + su2double* val_source) const { /* Default implementation of the source terms for the method of manufactured solutions. Simply set them to zero. */ - for(unsigned short iVar=0; iVarGetComm_Level() == COMM_FULL) { - /*--- Get the number of ranks and the MPI communicator. ---*/ int size = SU2_MPI::GetSize(); SU2_MPI::Comm comm = SU2_MPI::GetComm(); /*--- The local L2 norms must be added to obtain the global value. ---*/ - vector rbufError(nVar,0.0); - SU2_MPI::Allreduce(Error_RMS, rbufError.data(), nVar, - MPI_DOUBLE, MPI_SUM, comm); + vector rbufError(nVar, 0.0); + SU2_MPI::Allreduce(Error_RMS, rbufError.data(), nVar, MPI_DOUBLE, MPI_SUM, comm); - for(unsigned short iVar=0; iVar rbufPoint(nVar*size); - SU2_MPI::Allgather(Error_Point_Max, nVar, MPI_UNSIGNED_LONG, rbufPoint.data(), - nVar, MPI_UNSIGNED_LONG, comm); - - vector sbufCoor(nDim*nVar,0.0); - for(unsigned short iVar=0; iVar rbufPoint(nVar * size); + SU2_MPI::Allgather(Error_Point_Max, nVar, MPI_UNSIGNED_LONG, rbufPoint.data(), nVar, MPI_UNSIGNED_LONG, comm); + + vector sbufCoor(nDim * nVar, 0.0); + for (unsigned short iVar = 0; iVar < nVar; ++iVar) { + for (unsigned short iDim = 0; iDim < nDim; ++iDim) + sbufCoor[iVar * nDim + iDim] = Error_Point_Max_Coord[iVar][iDim]; } - vector rbufCoor(nDim*nVar*size,0.0); - SU2_MPI::Allgather(sbufCoor.data(), nVar*nDim, MPI_DOUBLE, rbufCoor.data(), - nVar*nDim, MPI_DOUBLE, comm); + vector rbufCoor(nDim * nVar * size, 0.0); + SU2_MPI::Allgather(sbufCoor.data(), nVar * nDim, MPI_DOUBLE, rbufCoor.data(), nVar * nDim, MPI_DOUBLE, comm); - for(unsigned short iVar=0; iVarLUklbXJvd0c2Iy9JK21vZHVsZW5hbWVHNiJJLFR5cGVzZXR0aW5nR0koX3N5c2xpYkdGJzYnLUkjbWlHRiQ2JlEiQ0YnLyUnaXRhbGljR1EldHJ1ZUYnLyUwZm9udF9zdHlsZV9uYW1lR1EpMkR+SW5wdXRGJy8lLG1hdGh2YXJpYW50R1EnaXRhbGljRictSShtZmVuY2VkR0YkNiUtRiM2Ky1GLDYmUSdzb3VyY2VGJ0YvRjJGNS1JI21vR0YkNi5RIixGJ0YyL0Y2USdub3JtYWxGJy8lJmZlbmNlR1EmZmFsc2VGJy8lKnNlcGFyYXRvckdGMS8lKXN0cmV0Y2h5R0ZILyUqc3ltbWV0cmljR0ZILyUobGFyZ2VvcEdGSC8lLm1vdmFibGVsaW1pdHNHRkgvJSdhY2NlbnRHRkgvJSdsc3BhY2VHUSYwLjBlbUYnLyUncnNwYWNlR1EsMC4zMzMzMzMzZW1GJy1GLDYmUSlvcHRpbWl6ZUYnRi9GMkY1RkAtRiw2JlEnb3V0cHV0RidGL0YyRjUtRkE2LlEiPUYnRjJGREZGL0ZKRkhGS0ZNRk9GUUZTL0ZWUSwwLjI3Nzc3NzhlbUYnL0ZZRmBvLUkjbXNHRiQ2I1EuU291cmNlTU1TLmNwcEYnLUYsNiNRIUYnRkRGMkZELUZBNi1RIjpGJ0ZERkZGXm9GS0ZNRk9GUUZTRl9vRmFvLyUrZXhlY3V0YWJsZUdGSEZE - \ No newline at end of file + diff --git a/Common/src/toolboxes/MMS/CreateMMSSourceTerms/CMMSNSTwoHalfSpheresSolution.mw b/Common/src/toolboxes/MMS/CreateMMSSourceTerms/CMMSNSTwoHalfSpheresSolution.mw index 931ee55b4ab..9b560a8e61f 100644 --- a/Common/src/toolboxes/MMS/CreateMMSSourceTerms/CMMSNSTwoHalfSpheresSolution.mw +++ b/Common/src/toolboxes/MMS/CreateMMSSourceTerms/CMMSNSTwoHalfSpheresSolution.mw @@ -516,4 +516,4 @@ LUklbXJvd0c2Iy9JK21vZHVsZW5hbWVHNiJJLFR5cGVzZXR0aW5nR0koX3N5c2xpYkdGJzYjLUkjbWlHRiQ2I1EhRic= - \ No newline at end of file + diff --git a/Common/src/toolboxes/MMS/CreateMMSSourceTerms/CMMSNSUnitQuadSolution.mw b/Common/src/toolboxes/MMS/CreateMMSSourceTerms/CMMSNSUnitQuadSolution.mw index 1cd09221b48..b6d131b2c89 100644 --- a/Common/src/toolboxes/MMS/CreateMMSSourceTerms/CMMSNSUnitQuadSolution.mw +++ b/Common/src/toolboxes/MMS/CreateMMSSourceTerms/CMMSNSUnitQuadSolution.mw @@ -404,4 +404,4 @@ LUklbXJvd0c2Iy9JK21vZHVsZW5hbWVHNiJJLFR5cGVzZXR0aW5nR0koX3N5c2xpYkdGJzYjLUkjbWlHRiQ2I1EhRic= - \ No newline at end of file + diff --git a/Common/src/toolboxes/MMS/CreateMMSSourceTerms/CMMSNSUnitQuadSolutionWallBC.mw b/Common/src/toolboxes/MMS/CreateMMSSourceTerms/CMMSNSUnitQuadSolutionWallBC.mw index 9793789b2de..08fe53f8771 100644 --- a/Common/src/toolboxes/MMS/CreateMMSSourceTerms/CMMSNSUnitQuadSolutionWallBC.mw +++ b/Common/src/toolboxes/MMS/CreateMMSSourceTerms/CMMSNSUnitQuadSolutionWallBC.mw @@ -384,4 +384,4 @@ JSFH - \ No newline at end of file + diff --git a/Common/src/toolboxes/printing_toolbox.cpp b/Common/src/toolboxes/printing_toolbox.cpp index f2b21f1da51..7153bcf1b98 100644 --- a/Common/src/toolboxes/printing_toolbox.cpp +++ b/Common/src/toolboxes/printing_toolbox.cpp @@ -30,86 +30,71 @@ #include #include "../../include/toolboxes/printing_toolbox.hpp" -PrintingToolbox::CTablePrinter::CTablePrinter(std::ostream * output, const std::string & separator){ +PrintingToolbox::CTablePrinter::CTablePrinter(std::ostream* output, const std::string& separator) { out_stream_ = output; i_ = 0; j_ = 0; separator_ = separator; table_width_ = 0; print_header_bottom_line_ = true; - print_header_top_line_ = true; + print_header_top_line_ = true; align_ = RIGHT; inner_separator_ = separator; precision_ = 6; } -int PrintingToolbox::CTablePrinter::GetNumColumns() const { - return (int)column_headers_.size(); -} +int PrintingToolbox::CTablePrinter::GetNumColumns() const { return (int)column_headers_.size(); } -int PrintingToolbox::CTablePrinter::GetTableWidth() const { - return table_width_; -} +int PrintingToolbox::CTablePrinter::GetTableWidth() const { return table_width_; } -void PrintingToolbox::CTablePrinter::SetSeparator(const std::string &separator){ - separator_ = separator; -} +void PrintingToolbox::CTablePrinter::SetSeparator(const std::string& separator) { separator_ = separator; } -void PrintingToolbox::CTablePrinter::SetInnerSeparator(const std::string &inner_separator){ +void PrintingToolbox::CTablePrinter::SetInnerSeparator(const std::string& inner_separator) { inner_separator_ = inner_separator; } -void PrintingToolbox::CTablePrinter::SetPrintHeaderBottomLine(bool print){ - print_header_bottom_line_ = print; -} +void PrintingToolbox::CTablePrinter::SetPrintHeaderBottomLine(bool print) { print_header_bottom_line_ = print; } -void PrintingToolbox::CTablePrinter::SetPrintHeaderTopLine(bool print){ - print_header_top_line_ = print; -} +void PrintingToolbox::CTablePrinter::SetPrintHeaderTopLine(bool print) { print_header_top_line_ = print; } -void PrintingToolbox::CTablePrinter::SetAlign(int align){ - align_ = align; -} +void PrintingToolbox::CTablePrinter::SetAlign(int align) { align_ = align; } -void PrintingToolbox::CTablePrinter::SetPrecision(int precision){ +void PrintingToolbox::CTablePrinter::SetPrecision(int precision) { precision_ = precision; out_stream_->precision(precision_); } -void PrintingToolbox::CTablePrinter::AddColumn(const std::string & header_name, int column_width){ - if (column_width < 4){ +void PrintingToolbox::CTablePrinter::AddColumn(const std::string& header_name, int column_width) { + if (column_width < 4) { throw std::invalid_argument("Column size has to be >= 4"); } column_headers_.push_back(header_name); column_widths_.push_back(column_width); - table_width_ += column_width + separator_.size(); // for the separator + table_width_ += column_width + separator_.size(); // for the separator } void PrintingToolbox::CTablePrinter::PrintHorizontalLine() { - *out_stream_ << "+"; // the left bar + *out_stream_ << "+"; // the left bar - for (int i=0; iGetPrandtl_Lam(); + Pr_lam = config->GetPrandtl_Lam(); Pr_turb = config->GetPrandtl_Turb(); - karman = config->GetwallModel_Kappa(); // von Karman constant -> k = 0.41; or 0.38; + karman = config->GetwallModel_Kappa(); // von Karman constant -> k = 0.41; or 0.38; } -void CWallModel::WallShearStressAndHeatFlux(const su2double rhoExchange, - const su2double velExchange, - const su2double muExchange, - const su2double pExchange, - const su2double Wall_HeatFlux, - const bool HeatFlux_Prescribed, - const su2double Wall_Temperature, - const bool Temperature_Prescribed, - CFluidModel *FluidModel, - su2double &tauWall, - su2double &qWall, - su2double &ViscosityWall, - su2double &kOverCvWall) {} - -CWallModel1DEQ::CWallModel1DEQ(CConfig *config, - const string &Marker_Tag) - : CWallModel(config) { +void CWallModel::WallShearStressAndHeatFlux(const su2double rhoExchange, const su2double velExchange, + const su2double muExchange, const su2double pExchange, + const su2double Wall_HeatFlux, const bool HeatFlux_Prescribed, + const su2double Wall_Temperature, const bool Temperature_Prescribed, + CFluidModel* FluidModel, su2double& tauWall, su2double& qWall, + su2double& ViscosityWall, su2double& kOverCvWall) {} +CWallModel1DEQ::CWallModel1DEQ(CConfig* config, const string& Marker_Tag) : CWallModel(config) { /* Retrieve the integer and floating point information for this boundary marker. */ - const unsigned short *intInfo = config->GetWallFunction_IntInfo(Marker_Tag); - const su2double *doubleInfo = config->GetWallFunction_DoubleInfo(Marker_Tag); + const unsigned short* intInfo = config->GetWallFunction_IntInfo(Marker_Tag); + const su2double* doubleInfo = config->GetWallFunction_DoubleInfo(Marker_Tag); /* Copy the data into the member variables. */ - numPoints = intInfo[0]; - h_wm = doubleInfo[0]; + numPoints = intInfo[0]; + h_wm = doubleInfo[0]; expansionRatio = doubleInfo[1]; unsigned short nfa = numPoints + 1; @@ -78,42 +66,33 @@ CWallModel1DEQ::CWallModel1DEQ(CConfig *config, /* Allocate the memory for the coordinates of the grid points used in the 1D equilibrium wall model. */ y_cv.resize(numPoints); - y_fa.resize(numPoints+1); + y_fa.resize(numPoints + 1); /* Determine the scaled version of the normal coordinates, where the first normal coordinate is simply 1.0. */ y_fa[0] = 0.0; - for(unsigned short i=1; i mu_fa(nfa, muExchange); vector tmp(nfa, 0.0); vector u(numPoints, 0.0); - vector lower(numPoints-1,0.0); - vector upper(numPoints-1,0.0); - vector diagonal(numPoints,0.0); - vector rhs(numPoints,0.0); + vector lower(numPoints - 1, 0.0); + vector upper(numPoints - 1, 0.0); + vector diagonal(numPoints, 0.0); + vector rhs(numPoints, 0.0); /* Set parameters for control */ bool converged = false; unsigned short iter = 0, max_iter = 25; - su2double tauWall_prev = 0.0, tol = 1e-3, aux_rhs=0.0; - su2double qWall_prev=0.0; + su2double tauWall_prev = 0.0, tol = 1e-3, aux_rhs = 0.0; + su2double qWall_prev = 0.0; su2double mut, nu, mu_lam, rho, utau, y_plus, D; - while (converged == false){ - + while (converged == false) { iter += 1; if (iter == max_iter) converged = true; @@ -167,17 +145,17 @@ void CWallModel1DEQ::WallShearStressAndHeatFlux(const su2double tExchange, /* Calculate total viscosity note: rho and mu_lam will be a function of temperature when solving an energy equation */ - for(unsigned short i=0; i < nfa; ++i){ - mu_lam = C_1 * pow(T[i]/T_ref, 1.5) * ((T_ref + S)/ (T[i] + S)); + for (unsigned short i = 0; i < nfa; ++i) { + mu_lam = C_1 * pow(T[i] / T_ref, 1.5) * ((T_ref + S) / (T[i] + S)); mu_fa[i] = mu_lam; } - for(unsigned short i=1; i < nfa; ++i){ - rho = pExchange / (R*T[i]); + for (unsigned short i = 1; i < nfa; ++i) { + rho = pExchange / (R * T[i]); nu = mu_fa[i] / rho; utau = sqrt(tauWall / rho); y_plus = y_fa[i] * utau / nu; - D = pow(1.0 - exp((-y_plus)/A),2.0); + D = pow(1.0 - exp((-y_plus) / A), 2.0); mut = rho * karman * y_fa[i] * utau * D; mu_fa[i] += mut; } @@ -185,10 +163,10 @@ void CWallModel1DEQ::WallShearStressAndHeatFlux(const su2double tExchange, /* Momentum matrix The solution vector is u at y_cv */ - lower.assign(numPoints-1,0.0); - upper.assign(numPoints-1,0.0); - diagonal.assign(numPoints,0.0); - rhs.assign(numPoints,0.0); + lower.assign(numPoints - 1, 0.0); + upper.assign(numPoints - 1, 0.0); + diagonal.assign(numPoints, 0.0); + rhs.assign(numPoints, 0.0); /* Top bc */ @@ -197,16 +175,16 @@ void CWallModel1DEQ::WallShearStressAndHeatFlux(const su2double tExchange, /* Internal cvs */ - for (unsigned short i=1; i < (numPoints - 1); ++i){ - upper[i] = mu_fa[i + 1] / (y_cv[i + 1] - y_cv[i] ); - lower[i-1] = mu_fa[i] / (y_cv[i] - y_cv[i - 1] ); + for (unsigned short i = 1; i < (numPoints - 1); ++i) { + upper[i] = mu_fa[i + 1] / (y_cv[i + 1] - y_cv[i]); + lower[i - 1] = mu_fa[i] / (y_cv[i] - y_cv[i - 1]); diagonal[i] = -1.0 * (upper[i] + lower[i - 1]); } /* Wall BC */ - upper[0] = mu_fa[1]/(y_cv[1] - y_cv[0]); - diagonal[0] = -1.0 * (upper[0] + mu_fa[0]/(y_cv[0]-y_fa[0]) ); + upper[0] = mu_fa[1] / (y_cv[1] - y_cv[0]); + diagonal[0] = -1.0 * (upper[0] + mu_fa[0] / (y_cv[0] - y_fa[0])); rhs[0] = 0.0; /* Solve the matrix problem to get the velocity field @@ -215,9 +193,8 @@ void CWallModel1DEQ::WallShearStressAndHeatFlux(const su2double tExchange, #if (defined(HAVE_MKL) || defined(HAVE_LAPACK)) && !(defined(CODI_REVERSE_TYPE) || defined(CODI_FORWARD_TYPE)) int info, nrhs = 1; - dgtsv_(&numPoints,&nrhs,lower.data(),diagonal.data(),upper.data(),rhs.data(),&numPoints, &info); - if (info != 0) - SU2_MPI::Error("Unsuccessful call to dgtsv_", CURRENT_FUNCTION); + dgtsv_(&numPoints, &nrhs, lower.data(), diagonal.data(), upper.data(), rhs.data(), &numPoints, &info); + if (info != 0) SU2_MPI::Error("Unsuccessful call to dgtsv_", CURRENT_FUNCTION); #else SU2_MPI::Error("Not compiled with MKL or LAPACK support", CURRENT_FUNCTION); #endif @@ -226,38 +203,38 @@ void CWallModel1DEQ::WallShearStressAndHeatFlux(const su2double tExchange, /* Update total viscosity */ - for(unsigned short i=0; i < nfa; ++i){ - mu_lam = C_1 * pow(T[i]/T_ref, 1.5) * ((T_ref + S)/ (T[i] + S)); + for (unsigned short i = 0; i < nfa; ++i) { + mu_lam = C_1 * pow(T[i] / T_ref, 1.5) * ((T_ref + S) / (T[i] + S)); mu_fa[i] = mu_lam; - tmp[i] = mu_lam/Pr_lam; + tmp[i] = mu_lam / Pr_lam; } /* Update tauWall */ - tauWall = mu_fa[0] * (u[0] - 0.0)/(y_cv[0]-y_fa[0]); - for(unsigned short i=1; i < nfa; ++i){ - rho = pExchange / (R*T[i]); + tauWall = mu_fa[0] * (u[0] - 0.0) / (y_cv[0] - y_fa[0]); + for (unsigned short i = 1; i < nfa; ++i) { + rho = pExchange / (R * T[i]); nu = mu_fa[i] / rho; utau = sqrt(tauWall / rho); y_plus = y_fa[i] * utau / nu; - D = pow(1.0 - exp((-y_plus)/A),2.0); + D = pow(1.0 - exp((-y_plus) / A), 2.0); mut = rho * karman * y_fa[i] * utau * D; mu_fa[i] += mut; - tmp[i] += mut/Pr_turb; + tmp[i] += mut / Pr_turb; } /* Energy matrix The Solution vector is Enthalpy at y_cv */ - lower.assign(numPoints-1,0.0); - upper.assign(numPoints-1,0.0); - diagonal.assign(numPoints,0.0); - rhs.assign(numPoints,0.0); + lower.assign(numPoints - 1, 0.0); + upper.assign(numPoints - 1, 0.0); + diagonal.assign(numPoints, 0.0); + rhs.assign(numPoints, 0.0); /* Internal cvs */ - for (unsigned short i=1; i < (numPoints - 1); ++i){ - upper[i] = tmp[i + 1] / (y_cv[i + 1] - y_cv[i] ); - lower[i-1] = tmp[i] / (y_cv[i] - y_cv[i - 1] ); + for (unsigned short i = 1; i < (numPoints - 1); ++i) { + upper[i] = tmp[i + 1] / (y_cv[i + 1] - y_cv[i]); + lower[i - 1] = tmp[i] / (y_cv[i] - y_cv[i - 1]); diagonal[i] = -1.0 * (upper[i] + lower[i - 1]); } @@ -267,9 +244,9 @@ void CWallModel1DEQ::WallShearStressAndHeatFlux(const su2double tExchange, /* Wall BC */ - upper[0] = tmp[1]/(y_cv[1] - y_cv[0]); - diagonal[0] = -1.0 * (upper[0] + tmp[0]/(y_cv[0]-y_fa[0]) ); - aux_rhs = tmp[0]/(y_cv[0]-y_fa[0]); + upper[0] = tmp[1] / (y_cv[1] - y_cv[0]); + diagonal[0] = -1.0 * (upper[0] + tmp[0] / (y_cv[0] - y_fa[0])); + aux_rhs = tmp[0] / (y_cv[0] - y_fa[0]); /* RHS of the Energy equation - Compute flux -- (mu + mu_t) * u * du/dy -- @@ -277,28 +254,27 @@ void CWallModel1DEQ::WallShearStressAndHeatFlux(const su2double tExchange, /* Zero flux at the wall */ - tmp[0] = 0. ; - for (unsigned short i=1; i < numPoints; ++i){ - tmp[i] = 0.5* (mu_fa[i]) * (u[i] + u[i-1]) * (u[i] -u[i-1])/(y_cv[i] - y_cv[i - 1] ) ; + tmp[0] = 0.; + for (unsigned short i = 1; i < numPoints; ++i) { + tmp[i] = 0.5 * (mu_fa[i]) * (u[i] + u[i - 1]) * (u[i] - u[i - 1]) / (y_cv[i] - y_cv[i - 1]); } - for (unsigned short i=0; i < (numPoints - 1); ++i){ - rhs[i] = -tmp[i+1] + tmp[i]; + for (unsigned short i = 0; i < (numPoints - 1); ++i) { + rhs[i] = -tmp[i + 1] + tmp[i]; } - if (HeatFlux_Prescribed == true){ + if (HeatFlux_Prescribed == true) { /* dT/dy = 0 -> Twall = T[1] */ h_wall = c_p * T[1]; } rhs[0] -= aux_rhs * h_wall; - rhs[numPoints-1] = h_bc; + rhs[numPoints - 1] = h_bc; /* Solve the matrix problem to get the Enthalpy field */ #if (defined(HAVE_MKL) || defined(HAVE_LAPACK)) && !(defined(CODI_REVERSE_TYPE) || defined(CODI_FORWARD_TYPE)) - dgtsv_(&numPoints,&nrhs,lower.data(),diagonal.data(),upper.data(),rhs.data(),&numPoints, &info); - if (info != 0) - SU2_MPI::Error("Unsuccessful call to dgtsv_", CURRENT_FUNCTION); + dgtsv_(&numPoints, &nrhs, lower.data(), diagonal.data(), upper.data(), rhs.data(), &numPoints, &info); + if (info != 0) SU2_MPI::Error("Unsuccessful call to dgtsv_", CURRENT_FUNCTION); #else SU2_MPI::Error("Not compiled with MKL or LAPACK support", CURRENT_FUNCTION); #endif @@ -306,64 +282,53 @@ void CWallModel1DEQ::WallShearStressAndHeatFlux(const su2double tExchange, /* Get Temperature from enthalpy - Temperature will be at face */ - T[0] = h_wall/c_p; - T[numPoints] = h_bc/c_p; - for (unsigned short i=0; i < numPoints-1; i++){ - T[i+1] = 0.5 * (rhs[i] + rhs[i+1])/c_p; + T[0] = h_wall / c_p; + T[numPoints] = h_bc / c_p; + for (unsigned short i = 0; i < numPoints - 1; i++) { + T[i + 1] = 0.5 * (rhs[i] + rhs[i + 1]) / c_p; } /* Final update tauWall */ - mu_lam = C_1 * pow(T[0]/T_ref, 1.5) * ((T_ref + S)/ (T[0] + S)); + mu_lam = C_1 * pow(T[0] / T_ref, 1.5) * ((T_ref + S) / (T[0] + S)); /* These quantities will be returned. */ - tauWall = mu_lam * (u[0] - 0.0)/(y_cv[0]-y_fa[0]); - qWall = mu_lam * (c_p / Pr_lam) * -(T[1] - T[0]) / (y_fa[1]-y_fa[0]); + tauWall = mu_lam * (u[0] - 0.0) / (y_cv[0] - y_fa[0]); + qWall = mu_lam * (c_p / Pr_lam) * -(T[1] - T[0]) / (y_fa[1] - y_fa[0]); ViscosityWall = mu_lam; - //kOverCvWall = c_p / c_v * (mu[0]/Pr_lam + muTurb[0]/Pr_turb); - kOverCvWall = c_p / c_v * (mu_lam/Pr_lam); + // kOverCvWall = c_p / c_v * (mu[0]/Pr_lam + muTurb[0]/Pr_turb); + kOverCvWall = c_p / c_v * (mu_lam / Pr_lam); /* Final check of the Y+ */ rho = pExchange / (R * T[0]); - if (y_cv[0] * sqrt(tauWall/rho) / (mu_lam/rho) > 1.0) + if (y_cv[0] * sqrt(tauWall / rho) / (mu_lam / rho) > 1.0) SU2_MPI::Error("Y+ greater than one: Increase the number of points or growth ratio.", CURRENT_FUNCTION); /* Define a norm */ - if (abs(1.0 - tauWall/tauWall_prev) < tol && abs(1.0 - qWall/qWall_prev) < tol){ + if (abs(1.0 - tauWall / tauWall_prev) < tol && abs(1.0 - qWall / qWall_prev) < tol) { converged = true; } } } -CWallModelLogLaw::CWallModelLogLaw(CConfig *config, - const string &Marker_Tag) - : CWallModel(config) { - +CWallModelLogLaw::CWallModelLogLaw(CConfig* config, const string& Marker_Tag) : CWallModel(config) { C = 5.25; /* Constant to match the Reichardt BL profile -> C = 4.1; or 5.25. */ /* Retrieve the floating point information for this boundary marker and set the exchange height. */ - const su2double *doubleInfo = config->GetWallFunction_DoubleInfo(Marker_Tag); + const su2double* doubleInfo = config->GetWallFunction_DoubleInfo(Marker_Tag); h_wm = doubleInfo[0]; } -void CWallModelLogLaw::WallShearStressAndHeatFlux(const su2double tExchange, - const su2double velExchange, - const su2double muExchange, - const su2double pExchange, - const su2double Wall_HeatFlux, - const bool HeatFlux_Prescribed, - const su2double Wall_Temperature, - const bool Temperature_Prescribed, - CFluidModel *FluidModel, - su2double &tauWall, - su2double &qWall, - su2double &ViscosityWall, - su2double &kOverCvWall) { - +void CWallModelLogLaw::WallShearStressAndHeatFlux(const su2double tExchange, const su2double velExchange, + const su2double muExchange, const su2double pExchange, + const su2double Wall_HeatFlux, const bool HeatFlux_Prescribed, + const su2double Wall_Temperature, const bool Temperature_Prescribed, + CFluidModel* FluidModel, su2double& tauWall, su2double& qWall, + su2double& ViscosityWall, su2double& kOverCvWall) { /* Set the wall temperature, depending whether or not the temperature was prescribed and initialize the fluid model. */ const su2double TWall = Temperature_Prescribed ? Wall_Temperature : tExchange; @@ -372,64 +337,67 @@ void CWallModelLogLaw::WallShearStressAndHeatFlux(const su2double tExchange, /* Get the required data from the fluid model. */ const su2double rho_wall = FluidModel->GetDensity(); - const su2double mu_wall = FluidModel->GetLaminarViscosity(); - const su2double c_p = FluidModel->GetCp(); - const su2double c_v = FluidModel->GetCv(); - const su2double nu_wall = mu_wall / rho_wall; + const su2double mu_wall = FluidModel->GetLaminarViscosity(); + const su2double c_p = FluidModel->GetCp(); + const su2double c_v = FluidModel->GetCv(); + const su2double nu_wall = mu_wall / rho_wall; /* Initial guess of the friction velocity. */ - su2double u_tau = max(0.01*velExchange, 1.e-5); + su2double u_tau = max(0.01 * velExchange, 1.e-5); /* Set parameters for control of the Newton iteration. */ bool converged = false; unsigned short iter = 0, max_iter = 50; - const su2double tol=1e-3; - - while (converged == false){ + const su2double tol = 1e-3; + while (converged == false) { iter += 1; if (iter == max_iter) converged = true; const su2double u_tau0 = u_tau; - const su2double y_plus = u_tau0*h_wm/nu_wall; + const su2double y_plus = u_tau0 * h_wm / nu_wall; /* Reichardt boundary layer analytical law fprime is the differentiation of the Reichardt law with repect to u_tau. */ - const su2double fval = velExchange/u_tau0 - ((C - log(karman)/karman)*(1.0 - exp(-y_plus/11.0) - - (y_plus/11.0)*exp(-0.33*y_plus))) - log(karman*y_plus + 1.0)/karman; - const su2double fprime = -velExchange/pow(u_tau0,2.0) - + (- C + log(karman)/karman)*(-(1.0/11.0)*h_wm*exp(-0.33*y_plus)/nu_wall - + (1.0/11.0)*h_wm*exp(-(1.0/11.0)*y_plus)/nu_wall - + (1.0/33.0)*u_tau0*pow(h_wm,2.0)*exp(-0.33*y_plus)/pow(nu_wall, 2.0)) - - 1.0*h_wm/(nu_wall*(karman*y_plus + 1.0)); + const su2double fval = + velExchange / u_tau0 - + ((C - log(karman) / karman) * (1.0 - exp(-y_plus / 11.0) - (y_plus / 11.0) * exp(-0.33 * y_plus))) - + log(karman * y_plus + 1.0) / karman; + const su2double fprime = -velExchange / pow(u_tau0, 2.0) + + (-C + log(karman) / karman) * + (-(1.0 / 11.0) * h_wm * exp(-0.33 * y_plus) / nu_wall + + (1.0 / 11.0) * h_wm * exp(-(1.0 / 11.0) * y_plus) / nu_wall + + (1.0 / 33.0) * u_tau0 * pow(h_wm, 2.0) * exp(-0.33 * y_plus) / pow(nu_wall, 2.0)) - + 1.0 * h_wm / (nu_wall * (karman * y_plus + 1.0)); /* Newton method */ - const su2double newton_step = fval/fprime; + const su2double newton_step = fval / fprime; u_tau = u_tau0 - newton_step; /* Define a norm */ - if (abs(1.0 - u_tau/u_tau0) < tol) converged = true; + if (abs(1.0 - u_tau / u_tau0) < tol) converged = true; } - tauWall = rho_wall * pow(u_tau,2.0); + tauWall = rho_wall * pow(u_tau, 2.0); - if (Temperature_Prescribed){ + if (Temperature_Prescribed) { /* The Kader's law will be used to approximate the variations of the temperature inside the boundary layer. */ - const su2double y_plus = u_tau*h_wm/nu_wall; - const su2double lhs = - ((tExchange - TWall) * rho_wall * c_p * u_tau); - const su2double Gamma = - (0.01 * (Pr_lam * pow(y_plus,4.0))/(1.0 + 5.0*y_plus*pow(Pr_lam,3.0))); + const su2double y_plus = u_tau * h_wm / nu_wall; + const su2double lhs = -((tExchange - TWall) * rho_wall * c_p * u_tau); + const su2double Gamma = -(0.01 * (Pr_lam * pow(y_plus, 4.0)) / (1.0 + 5.0 * y_plus * pow(Pr_lam, 3.0))); const su2double rhs_1 = Pr_lam * y_plus * exp(Gamma); - const su2double rhs_2 = (2.12*log(1.0+y_plus) + pow((3.85*pow(Pr_lam,(1.0/3.0)) - 1.3),2.0) + 2.12*log(Pr_lam)) * exp(1./Gamma); - qWall = lhs/(rhs_1 + rhs_2); - } - else{ + const su2double rhs_2 = + (2.12 * log(1.0 + y_plus) + pow((3.85 * pow(Pr_lam, (1.0 / 3.0)) - 1.3), 2.0) + 2.12 * log(Pr_lam)) * + exp(1. / Gamma); + qWall = lhs / (rhs_1 + rhs_2); + } else { qWall = Wall_HeatFlux; } ViscosityWall = mu_wall; - kOverCvWall = FluidModel->GetThermalConductivity()/c_v; + kOverCvWall = FluidModel->GetThermalConductivity() / c_v; } diff --git a/Docs/docmain.hpp b/Docs/docmain.hpp index 704f85acdcb..ab8b45fa8ec 100644 --- a/Docs/docmain.hpp +++ b/Docs/docmain.hpp @@ -224,4 +224,4 @@ * \defgroup SIMD Vectorization (SIMD) * \brief Classes for explicit (done by the programmer) vectorization (SIMD) of computations. * \ingroup Toolboxes - */ \ No newline at end of file + */ diff --git a/QuickStart/inv_NACA0012.cfg b/QuickStart/inv_NACA0012.cfg index 6f6dbc9424a..a4668268b9c 100644 --- a/QuickStart/inv_NACA0012.cfg +++ b/QuickStart/inv_NACA0012.cfg @@ -30,7 +30,7 @@ MACH_NUMBER= 0.8 % Angle of attack (degrees) AOA= 1.25 % -% Free-stream pressure (101325.0 N/m^2 by default, only Euler flows) +% Free-stream pressure (101325.0 N/m^2 by default, only Euler flows) FREESTREAM_PRESSURE= 101325.0 % % Free-stream temperature (273.15 K by default) @@ -234,7 +234,7 @@ DEFORM_LINEAR_SOLVER_ERROR= 1E-14 % Print the residuals during mesh deformation to the console (YES, NO) DEFORM_CONSOLE_OUTPUT= YES % -% Type of element stiffness imposed for FEA mesh deformation (INVERSE_VOLUME, +% Type of element stiffness imposed for FEA mesh deformation (INVERSE_VOLUME, % WALL_DISTANCE, CONSTANT_STIFFNESS) DEFORM_STIFFNESS_TYPE= INVERSE_VOLUME @@ -275,7 +275,7 @@ SOLUTION_ADJ_FILENAME= solution_adj.dat % Output file format (TECPLOT, CSV) TABULAR_FORMAT= CSV % -% Output file convergence history (w/o extension) +% Output file convergence history (w/o extension) CONV_FILENAME= history % % Output file restart flow @@ -308,7 +308,7 @@ OUTPUT_WRT_FREQ= 250 % FORCE_X, FORCE_Y, FORCE_Z, % MOMENT_X, MOMENT_Y, MOMENT_Z, % THRUST, TORQUE, FIGURE_OF_MERIT, -% EQUIVALENT_AREA, NEARFIELD_PRESSURE, +% EQUIVALENT_AREA, NEARFIELD_PRESSURE, % TOTAL_HEATFLUX, MAXIMUM_HEATFLUX, % INVERSE_DESIGN_PRESSURE, INVERSE_DESIGN_HEATFLUX, % diff --git a/SU2_DEF/src/SU2_DEF.cpp b/SU2_DEF/src/SU2_DEF.cpp index 379a1a356c9..63c8bff70e6 100644 --- a/SU2_DEF/src/SU2_DEF.cpp +++ b/SU2_DEF/src/SU2_DEF.cpp @@ -28,7 +28,6 @@ #include "../include/drivers/CDeformationDriver.hpp" int main(int argc, char* argv[]) { - char config_file_name[MAX_STRING_SIZE]; /*--- MPI initialization ---*/ diff --git a/SU2_DEF/src/drivers/CDeformationDriver.cpp b/SU2_DEF/src/drivers/CDeformationDriver.cpp index d88d0048ec3..9ec2b31120a 100644 --- a/SU2_DEF/src/drivers/CDeformationDriver.cpp +++ b/SU2_DEF/src/drivers/CDeformationDriver.cpp @@ -36,7 +36,6 @@ using namespace std; CDeformationDriver::CDeformationDriver(char* confFile, SU2_Comm MPICommunicator) : CDriverBase(confFile, 1, MPICommunicator) { - /*--- Initialize MeDiPack (must also be here to initialize it from Python) ---*/ #ifdef HAVE_MPI #if defined(CODI_REVERSE_TYPE) || defined(CODI_FORWARD_TYPE) @@ -73,7 +72,6 @@ CDeformationDriver::CDeformationDriver(char* confFile, SU2_Comm MPICommunicator) /*--- Preprocessing of the mesh solver for all zones. ---*/ Numerics_Preprocessing(); - } /*--- Preprocessing time is reported now, but not included in the next compute portion. ---*/ @@ -115,7 +113,8 @@ void CDeformationDriver::Input_Preprocessing() { strcpy(zone_file_name, driver_config->GetConfigFilename(iZone).c_str()); config_container[iZone] = new CConfig(driver_config, zone_file_name, SU2_COMPONENT::SU2_DEF, iZone, nZone, true); } else { - config_container[iZone] = new CConfig(driver_config, config_file_name, SU2_COMPONENT::SU2_DEF, iZone, nZone, true); + config_container[iZone] = + new CConfig(driver_config, config_file_name, SU2_COMPONENT::SU2_DEF, iZone, nZone, true); } config_container[iZone]->SetMPICommunicator(SU2_MPI::GetComm()); @@ -173,7 +172,8 @@ void CDeformationDriver::Geometrical_Preprocessing() { /*--- Computational grid preprocessing. ---*/ - if (rank == MASTER_NODE) cout << endl << "----------------------- Preprocessing computations ----------------------" << endl; + if (rank == MASTER_NODE) + cout << endl << "----------------------- Preprocessing computations ----------------------" << endl; /*--- Compute elements surrounding points, points surrounding points. ---*/ @@ -205,7 +205,8 @@ void CDeformationDriver::Geometrical_Preprocessing() { /*--- Create the point-to-point MPI communication structures. ---*/ - geometry_container[iZone][INST_0][MESH_0]->PreprocessP2PComms(geometry_container[iZone][INST_0][MESH_0],config_container[iZone]); + geometry_container[iZone][INST_0][MESH_0]->PreprocessP2PComms(geometry_container[iZone][INST_0][MESH_0], + config_container[iZone]); } /*--- Get the number of dimensions. ---*/ @@ -221,7 +222,8 @@ void CDeformationDriver::Output_Preprocessing() { for (iZone = 0; iZone < nZone; iZone++) { /*--- Allocate the mesh output. ---*/ - output_container[iZone] = new CMeshOutput(config_container[iZone], geometry_container[iZone][INST_0][MESH_0]->GetnDim()); + output_container[iZone] = + new CMeshOutput(config_container[iZone], geometry_container[iZone][INST_0][MESH_0]->GetnDim()); /*--- Preprocess the volume output. ---*/ @@ -292,7 +294,10 @@ void CDeformationDriver::Run() { if (rank == MASTER_NODE) { cout << "\nCompleted in " << fixed << UsedTimeCompute << " seconds on " << size; - if (size == 1) cout << " core." << endl; else cout << " cores." << endl; + if (size == 1) + cout << " core." << endl; + else + cout << " cores." << endl; } /*--- Output the deformed mesh. ---*/ @@ -304,7 +309,8 @@ void CDeformationDriver::Update() { for (iZone = 0; iZone < nZone; iZone++) { /*--- Set the stiffness of each element mesh into the mesh numerics. ---*/ - solver_container[iZone][INST_0][MESH_0][MESH_SOL]->SetMesh_Stiffness(numerics_container[iZone][INST_0][MESH_0][MESH_SOL], config_container[iZone]); + solver_container[iZone][INST_0][MESH_0][MESH_SOL]->SetMesh_Stiffness( + numerics_container[iZone][INST_0][MESH_0][MESH_SOL], config_container[iZone]); /*--- Deform the volume grid around the new boundary locations. ---*/ /*--- Force the number of levels to be 0 because in this driver we do not build MG levels. ---*/ @@ -325,7 +331,8 @@ void CDeformationDriver::Update_Legacy() { /*--- Definition of the Class for grid movement. ---*/ grid_movement[iZone] = new CVolumetricMovement*[nInst_Zone](); - grid_movement[iZone][INST_0] = new CVolumetricMovement(geometry_container[iZone][INST_0][MESH_0], config_container[iZone]); + grid_movement[iZone][INST_0] = + new CVolumetricMovement(geometry_container[iZone][INST_0][MESH_0], config_container[iZone]); /*--- Save original coordinates to be reused in convexity checking procedure. ---*/ @@ -335,25 +342,32 @@ void CDeformationDriver::Update_Legacy() { if (config_container[iZone]->GetDesign_Variable(0) == SCALE_GRID) { if (rank == MASTER_NODE) - cout << endl << "--------------------- Volumetric grid scaling (ZONE " << iZone << ") ------------------" << endl; - grid_movement[iZone][INST_0]->SetVolume_Scaling(geometry_container[iZone][INST_0][MESH_0], config_container[iZone], false); + cout << endl + << "--------------------- Volumetric grid scaling (ZONE " << iZone << ") ------------------" << endl; + grid_movement[iZone][INST_0]->SetVolume_Scaling(geometry_container[iZone][INST_0][MESH_0], + config_container[iZone], false); } else if (config_container[iZone]->GetDesign_Variable(0) == TRANSLATE_GRID) { if (rank == MASTER_NODE) - cout << endl << "------------------- Volumetric grid translation (ZONE " << iZone << ") ----------------" << endl; - grid_movement[iZone][INST_0]->SetVolume_Translation(geometry_container[iZone][INST_0][MESH_0], config_container[iZone], false); + cout << endl + << "------------------- Volumetric grid translation (ZONE " << iZone << ") ----------------" << endl; + grid_movement[iZone][INST_0]->SetVolume_Translation(geometry_container[iZone][INST_0][MESH_0], + config_container[iZone], false); } else if (config_container[iZone]->GetDesign_Variable(0) == ROTATE_GRID) { if (rank == MASTER_NODE) - cout << endl << "--------------------- Volumetric grid rotation (ZONE " << iZone << ") -----------------" << endl; - grid_movement[iZone][INST_0]->SetVolume_Rotation(geometry_container[iZone][INST_0][MESH_0], config_container[iZone], false); + cout << endl + << "--------------------- Volumetric grid rotation (ZONE " << iZone << ") -----------------" << endl; + grid_movement[iZone][INST_0]->SetVolume_Rotation(geometry_container[iZone][INST_0][MESH_0], + config_container[iZone], false); } else { /*--- If no volume-type deformations are requested, then this is a * surface-based deformation or FFD set up. ---*/ if (rank == MASTER_NODE) - cout << endl << "--------------------- Surface grid deformation (ZONE " << iZone << ") -----------------" << endl; + cout << endl + << "--------------------- Surface grid deformation (ZONE " << iZone << ") -----------------" << endl; /*--- Definition and initialization of the surface deformation class. ---*/ @@ -367,20 +381,24 @@ void CDeformationDriver::Update_Legacy() { /*--- Surface grid deformation. ---*/ if (rank == MASTER_NODE) cout << "Performing the deformation of the surface grid." << endl; - auto TotalDeformation = surface_movement[iZone]->SetSurface_Deformation(geometry_container[iZone][INST_0][MESH_0], config_container[iZone]); + auto TotalDeformation = surface_movement[iZone]->SetSurface_Deformation( + geometry_container[iZone][INST_0][MESH_0], config_container[iZone]); if (config_container[iZone]->GetDesign_Variable(0) != FFD_SETTING) { if (rank == MASTER_NODE) - cout << endl << "------------------- Volumetric grid deformation (ZONE " << iZone << ") ----------------" << endl; + cout << endl + << "------------------- Volumetric grid deformation (ZONE " << iZone << ") ----------------" << endl; if (rank == MASTER_NODE) cout << "Performing the deformation of the volumetric grid." << endl; - grid_movement[iZone][INST_0]->SetVolume_Deformation(geometry_container[iZone][INST_0][MESH_0],config_container[iZone], false); + grid_movement[iZone][INST_0]->SetVolume_Deformation(geometry_container[iZone][INST_0][MESH_0], + config_container[iZone], false); /*--- Get parameters for convexity check. ---*/ bool ConvexityCheck; unsigned short ConvexityCheck_MaxIter, ConvexityCheck_MaxDepth; - tie(ConvexityCheck, ConvexityCheck_MaxIter, ConvexityCheck_MaxDepth) = config_container[iZone]->GetConvexityCheck(); + tie(ConvexityCheck, ConvexityCheck_MaxIter, ConvexityCheck_MaxDepth) = + config_container[iZone]->GetConvexityCheck(); /*--- Recursively change deformations if there are non-convex elements. ---*/ @@ -397,7 +415,8 @@ void CDeformationDriver::Update_Legacy() { unsigned short ConvexityCheckIter, RecursionDepth = 0; su2double DeformationFactor = 1.0, DeformationDifference = 1.0; for (ConvexityCheckIter = 1; ConvexityCheckIter <= ConvexityCheck_MaxIter; ConvexityCheckIter++) { - /*--- Recursively change deformation magnitude (decrease for non-convex elements, increase otherwise). ---*/ + /*--- Recursively change deformation magnitude (decrease for non-convex elements, increase otherwise). + * ---*/ DeformationDifference /= 2.0; @@ -422,7 +441,8 @@ void CDeformationDriver::Update_Legacy() { for (auto iPoint = 0ul; iPoint < OriginalCoordinates.rows(); iPoint++) { for (auto iDim = 0ul; iDim < OriginalCoordinates.cols(); iDim++) { - geometry_container[iZone][INST_0][MESH_0]->nodes->SetCoord(iPoint, iDim, OriginalCoordinates(iPoint, iDim)); + geometry_container[iZone][INST_0][MESH_0]->nodes->SetCoord(iPoint, iDim, + OriginalCoordinates(iPoint, iDim)); } } @@ -430,7 +450,8 @@ void CDeformationDriver::Update_Legacy() { for (auto iDV = 0u; iDV < driver_config->GetnDV(); iDV++) { for (auto iDV_Value = 0u; iDV_Value < driver_config->GetnDV_Value(iDV); iDV_Value++) { - config_container[iZone]->SetDV_Value(iDV, iDV_Value,InitialDeformation[iDV][iDV_Value] * DeformationFactor); + config_container[iZone]->SetDV_Value(iDV, iDV_Value, + InitialDeformation[iDV][iDV_Value] * DeformationFactor); } } @@ -438,13 +459,17 @@ void CDeformationDriver::Update_Legacy() { if (rank == MASTER_NODE) cout << "Performing the deformation of the surface grid." << endl; - TotalDeformation = surface_movement[iZone]->SetSurface_Deformation(geometry_container[iZone][INST_0][MESH_0], config_container[iZone]); + TotalDeformation = surface_movement[iZone]->SetSurface_Deformation( + geometry_container[iZone][INST_0][MESH_0], config_container[iZone]); if (rank == MASTER_NODE) - cout << endl << "------------------- Volumetric grid deformation (ZONE " << iZone << ") ----------------" << endl; + cout << endl + << "------------------- Volumetric grid deformation (ZONE " << iZone << ") ----------------" + << endl; if (rank == MASTER_NODE) cout << "Performing the deformation of the volumetric grid." << endl; - grid_movement[iZone][INST_0]->SetVolume_Deformation(geometry_container[iZone][INST_0][MESH_0], config_container[iZone], false); + grid_movement[iZone][INST_0]->SetVolume_Deformation(geometry_container[iZone][INST_0][MESH_0], + config_container[iZone], false); if (rank == MASTER_NODE) { cout << "Number of non-convex elements for iteration " << ConvexityCheckIter << ": "; @@ -488,7 +513,8 @@ void CDeformationDriver::Output() { output_container[iZone]->Load_Data(geometry_container[iZone][INST_0][MESH_0], config_container[iZone], nullptr); - output_container[iZone]->WriteToFile(config_container[iZone], geometry_container[iZone][INST_0][MESH_0],OUTPUT_TYPE::MESH, driver_config->GetMesh_Out_FileName()); + output_container[iZone]->WriteToFile(config_container[iZone], geometry_container[iZone][INST_0][MESH_0], + OUTPUT_TYPE::MESH, driver_config->GetMesh_Out_FileName()); /*--- Set the file names for the visualization files. ---*/ @@ -499,7 +525,8 @@ void CDeformationDriver::Output() { auto FileFormat = config_container[iZone]->GetVolumeOutputFiles(); if (FileFormat[iFile] != OUTPUT_TYPE::RESTART_ASCII && FileFormat[iFile] != OUTPUT_TYPE::RESTART_BINARY && FileFormat[iFile] != OUTPUT_TYPE::CSV) - output_container[iZone]->WriteToFile(config_container[iZone], geometry_container[iZone][INST_0][MESH_0],FileFormat[iFile]); + output_container[iZone]->WriteToFile(config_container[iZone], geometry_container[iZone][INST_0][MESH_0], + FileFormat[iFile]); } } @@ -508,7 +535,6 @@ void CDeformationDriver::Output() { (config_container[ZONE_0]->GetDesign_Variable(0) != SCALE_GRID) && (config_container[ZONE_0]->GetDesign_Variable(0) != TRANSLATE_GRID) && (config_container[ZONE_0]->GetDesign_Variable(0) != ROTATE_GRID)) { - /*--- Write the free form deformation boxes after deformation if defined. ---*/ if (!haveSurfaceDeformation) { if (rank == MASTER_NODE) cout << "No FFD information available." << endl; @@ -558,6 +584,8 @@ void CDeformationDriver::Postprocessing() { } void CDeformationDriver::CommunicateMeshDisplacements(void) { - solver_container[ZONE_0][INST_0][MESH_0][MESH_SOL]->InitiateComms(geometry_container[ZONE_0][INST_0][MESH_0],config_container[ZONE_0], MESH_DISPLACEMENTS); - solver_container[ZONE_0][INST_0][MESH_0][MESH_SOL]->CompleteComms(geometry_container[ZONE_0][INST_0][MESH_0],config_container[ZONE_0], MESH_DISPLACEMENTS); + solver_container[ZONE_0][INST_0][MESH_0][MESH_SOL]->InitiateComms(geometry_container[ZONE_0][INST_0][MESH_0], + config_container[ZONE_0], MESH_DISPLACEMENTS); + solver_container[ZONE_0][INST_0][MESH_0][MESH_SOL]->CompleteComms(geometry_container[ZONE_0][INST_0][MESH_0], + config_container[ZONE_0], MESH_DISPLACEMENTS); } diff --git a/SU2_DEF/src/drivers/CDiscAdjDeformationDriver.cpp b/SU2_DEF/src/drivers/CDiscAdjDeformationDriver.cpp index ddab47fc4f9..db2a64f4961 100644 --- a/SU2_DEF/src/drivers/CDiscAdjDeformationDriver.cpp +++ b/SU2_DEF/src/drivers/CDiscAdjDeformationDriver.cpp @@ -42,7 +42,6 @@ using namespace std; CDiscAdjDeformationDriver::CDiscAdjDeformationDriver(char* confFile, SU2_Comm MPICommunicator) : CDriverBase(confFile, 1, MPICommunicator) { - /*--- Initialize MeDiPack (must also be here to initialize it from Python). ---*/ #ifdef HAVE_MPI #if defined(CODI_REVERSE_TYPE) || defined(CODI_FORWARD_TYPE) @@ -122,13 +121,15 @@ void CDiscAdjDeformationDriver::Input_Preprocessing() { strcpy(zone_file_name, driver_config->GetConfigFilename(iZone).c_str()); config_container[iZone] = new CConfig(driver_config, zone_file_name, SU2_COMPONENT::SU2_DOT, iZone, nZone, true); } else { - config_container[iZone] = new CConfig(driver_config, config_file_name, SU2_COMPONENT::SU2_DOT, iZone, nZone, true); + config_container[iZone] = + new CConfig(driver_config, config_file_name, SU2_COMPONENT::SU2_DOT, iZone, nZone, true); } config_container[iZone]->SetMPICommunicator(SU2_MPI::GetComm()); if (!config_container[iZone]->GetDiscrete_Adjoint() && !config_container[iZone]->GetContinuous_Adjoint()) { - SU2_MPI::Error("An adjoint solver (discrete or continuous) was not specified in the configuration file.", CURRENT_FUNCTION); + SU2_MPI::Error("An adjoint solver (discrete or continuous) was not specified in the configuration file.", + CURRENT_FUNCTION); } } @@ -296,7 +297,8 @@ void CDiscAdjDeformationDriver::Preprocess() { unsigned short nInst_Zone = nInst[iZone]; grid_movement[iZone] = new CVolumetricMovement*[nInst_Zone](); - grid_movement[iZone][INST_0] = new CVolumetricMovement(geometry_container[iZone][INST_0][MESH_0], config_container[iZone]); + grid_movement[iZone][INST_0] = + new CVolumetricMovement(geometry_container[iZone][INST_0][MESH_0], config_container[iZone]); /*--- Read in sensitivities from file. ---*/ @@ -358,10 +360,12 @@ void CDiscAdjDeformationDriver::Run() { DerivativeTreatment_Gradient(geometry_container[iZone][INST_0][MESH_0], config_container[iZone], grid_movement[iZone][INST_0], surface_movement[iZone], Gradient); } else { - SetProjection_AD(geometry_container[iZone][INST_0][MESH_0], config_container[iZone], surface_movement[iZone], Gradient); + SetProjection_AD(geometry_container[iZone][INST_0][MESH_0], config_container[iZone], surface_movement[iZone], + Gradient); } } else { - SetProjection_FD(geometry_container[iZone][INST_0][MESH_0], config_container[iZone], surface_movement[iZone], Gradient); + SetProjection_FD(geometry_container[iZone][INST_0][MESH_0], config_container[iZone], surface_movement[iZone], + Gradient); } } } @@ -417,7 +421,10 @@ void CDiscAdjDeformationDriver::SetProjection_FD(CGeometry* geometry, CConfig* c for (iDV = 0; iDV < nDV; iDV++) { nDV_Value = config->GetnDV_Value(iDV); if (nDV_Value != 1) { - SU2_MPI::Error("The projection using finite differences currently only supports a fixed direction of movement for FFD points.", CURRENT_FUNCTION); + SU2_MPI::Error( + "The projection using finite differences currently only supports a fixed direction of movement for FFD " + "points.", + CURRENT_FUNCTION); } } @@ -759,7 +766,6 @@ void CDiscAdjDeformationDriver::SetProjection_AD(CGeometry* geometry, CConfig* c } void CDiscAdjDeformationDriver::OutputGradient(su2double** Gradient, CConfig* config, ofstream& Gradient_file) { - unsigned short nDV, iDV, iDV_Value, nDV_Value; int rank = SU2_MPI::GetRank(); @@ -782,7 +788,8 @@ void CDiscAdjDeformationDriver::OutputGradient(su2double** Gradient, CConfig* co /*--- Print the kind of objective function to screen. ---*/ - for (std::map::const_iterator it = Objective_Map.begin(); it != Objective_Map.end(); ++it) { + for (std::map::const_iterator it = Objective_Map.begin(); it != Objective_Map.end(); + ++it) { if (it->second == config->GetKind_ObjFunc()) { cout << it->first << " gradient : "; if (iDV == 0) Gradient_file << it->first << " gradient " << endl; @@ -842,7 +849,8 @@ void CDiscAdjDeformationDriver::SetSensitivity_Files(CGeometry**** geometry, CCo for (iPoint = 0; iPoint < nPoint; iPoint++) { for (iDim = 0; iDim < nDim; iDim++) { solver->GetNodes()->SetSolution(iPoint, iDim, geometry[iZone][INST_0][MESH_0]->nodes->GetCoord(iPoint, iDim)); - solver->GetNodes()->SetSolution(iPoint, iDim + nDim, geometry[iZone][INST_0][MESH_0]->GetSensitivity(iPoint, iDim)); + solver->GetNodes()->SetSolution(iPoint, iDim + nDim, + geometry[iZone][INST_0][MESH_0]->GetSensitivity(iPoint, iDim)); } } @@ -954,7 +962,7 @@ void CDiscAdjDeformationDriver::DerivativeTreatment_MeshSensitivity(CGeometry* g solver->WriteSensToGeometry(geometry); - /*--- Work with the volume derivatives. ---*/ + /*--- Work with the volume derivatives. ---*/ } else { /*--- Get the sensitivities from the geometry class to work with. ---*/ @@ -1001,7 +1009,7 @@ void CDiscAdjDeformationDriver::DerivativeTreatment_Gradient(CGeometry* geometry if (config->GetSobMode() == ENUM_SOBOLEV_MODUS::PARAM_LEVEL_COMPLETE) { solver->ApplyGradientSmoothingDV(geometry, numerics.get(), surface_movement, grid_movement, config, Gradient); - /*--- If smoothing already took place on the mesh level, or none is requested, just do standard projection. ---*/ + /*--- If smoothing already took place on the mesh level, or none is requested, just do standard projection. ---*/ } else if (config->GetSobMode() == ENUM_SOBOLEV_MODUS::ONLY_GRAD || config->GetSobMode() == ENUM_SOBOLEV_MODUS::MESH_LEVEL) { solver->RecordTapeAndCalculateOriginalGradient(geometry, surface_movement, grid_movement, config, Gradient); diff --git a/SU2_DOT/src/SU2_DOT.cpp b/SU2_DOT/src/SU2_DOT.cpp index b8b606ca75c..f66dd007b35 100644 --- a/SU2_DOT/src/SU2_DOT.cpp +++ b/SU2_DOT/src/SU2_DOT.cpp @@ -28,7 +28,6 @@ #include "../../SU2_DEF/include/drivers/CDiscAdjDeformationDriver.hpp" int main(int argc, char* argv[]) { - char config_file_name[MAX_STRING_SIZE]; /*--- MPI initialization. ---*/ diff --git a/SU2_GEO/include/SU2_GEO.hpp b/SU2_GEO/include/SU2_GEO.hpp index 9752149364e..2b2a31f9c4a 100644 --- a/SU2_GEO/include/SU2_GEO.hpp +++ b/SU2_GEO/include/SU2_GEO.hpp @@ -26,7 +26,6 @@ * License along with SU2. If not, see . */ - #pragma once #include "../../Common/include/parallelization/mpi_structure.hpp" diff --git a/SU2_GEO/src/SU2_GEO.cpp b/SU2_GEO/src/SU2_GEO.cpp index ffe89dd510a..59ec6cf2107 100644 --- a/SU2_GEO/src/SU2_GEO.cpp +++ b/SU2_GEO/src/SU2_GEO.cpp @@ -25,31 +25,48 @@ * License along with SU2. If not, see . */ - #include "../include/SU2_GEO.hpp" using namespace std; -int main(int argc, char *argv[]) { - +int main(int argc, char* argv[]) { unsigned short iZone, nZone = SINGLE_ZONE; su2double StartTime = 0.0, StopTime = 0.0, UsedTime = 0.0; unsigned short iDV, iFFDBox, iPlane, nPlane, iVar; - su2double *ObjectiveFunc, *ObjectiveFunc_New, *Gradient, delta_eps, - **Plane_P0, **Plane_Normal, - - Fuselage_Volume = 0.0, Fuselage_WettedArea = 0.0, Fuselage_MinWidth = 0.0, Fuselage_MaxWidth = 0.0, Fuselage_MinWaterLineWidth = 0.0, Fuselage_MaxWaterLineWidth = 0.0, Fuselage_MinHeight = 0.0, Fuselage_MaxHeight = 0.0, Fuselage_MaxCurvature = 0.0, - Fuselage_Volume_New = 0.0, Fuselage_WettedArea_New = 0.0, Fuselage_MinWidth_New = 0.0, Fuselage_MaxWidth_New = 0.0, Fuselage_MinWaterLineWidth_New = 0.0, Fuselage_MaxWaterLineWidth_New = 0.0, Fuselage_MinHeight_New = 0.0, Fuselage_MaxHeight_New = 0.0, Fuselage_MaxCurvature_New = 0.0, - Fuselage_Volume_Grad = 0.0, Fuselage_WettedArea_Grad = 0.0, Fuselage_MinWidth_Grad = 0.0, Fuselage_MaxWidth_Grad = 0.0, Fuselage_MinWaterLineWidth_Grad = 0.0, Fuselage_MaxWaterLineWidth_Grad = 0.0, Fuselage_MinHeight_Grad = 0.0, Fuselage_MaxHeight_Grad = 0.0, Fuselage_MaxCurvature_Grad = 0.0, - - Wing_Volume = 0.0, Wing_MinThickness = 0.0, Wing_MaxThickness = 0.0, Wing_MinChord = 0.0, Wing_MaxChord = 0.0, Wing_MinLERadius = 0.0, Wing_MaxLERadius = 0.0, Wing_MinToC = 0.0, Wing_MaxToC = 0.0, Wing_ObjFun_MinToC = 0.0, Wing_MaxTwist = 0.0, Wing_MaxCurvature = 0.0, Wing_MaxDihedral = 0.0, - Wing_Volume_New = 0.0, Wing_MinThickness_New = 0.0, Wing_MaxThickness_New = 0.0, Wing_MinChord_New = 0.0, Wing_MaxChord_New = 0.0, Wing_MinLERadius_New = 0.0, Wing_MaxLERadius_New = 0.0, Wing_MinToC_New = 0.0, Wing_MaxToC_New = 0.0, Wing_ObjFun_MinToC_New = 0.0, Wing_MaxTwist_New = 0.0, Wing_MaxCurvature_New = 0.0, Wing_MaxDihedral_New = 0.0, - Wing_Volume_Grad = 0.0, Wing_MinThickness_Grad = 0.0, Wing_MaxThickness_Grad = 0.0, Wing_MinChord_Grad = 0.0, Wing_MaxChord_Grad = 0.0, Wing_MinLERadius_Grad = 0.0, Wing_MaxLERadius_Grad = 0.0, Wing_MinToC_Grad = 0.0, Wing_MaxToC_Grad = 0.0, Wing_ObjFun_MinToC_Grad = 0.0, Wing_MaxTwist_Grad = 0.0, Wing_MaxCurvature_Grad = 0.0, Wing_MaxDihedral_Grad = 0.0, - - Nacelle_Volume = 0.0, Nacelle_MinThickness = 0.0, Nacelle_MaxThickness = 0.0, Nacelle_MinChord = 0.0, Nacelle_MaxChord = 0.0, Nacelle_MinLERadius = 0.0, Nacelle_MaxLERadius = 0.0, Nacelle_MinToC = 0.0, Nacelle_MaxToC = 0.0, Nacelle_ObjFun_MinToC = 0.0, Nacelle_MaxTwist = 0.0, - Nacelle_Volume_New = 0.0, Nacelle_MinThickness_New = 0.0, Nacelle_MaxThickness_New = 0.0, Nacelle_MinChord_New = 0.0, Nacelle_MaxChord_New = 0.0, Nacelle_MinLERadius_New = 0.0, Nacelle_MaxLERadius_New = 0.0, Nacelle_MinToC_New = 0.0, Nacelle_MaxToC_New = 0.0, Nacelle_ObjFun_MinToC_New = 0.0, Nacelle_MaxTwist_New = 0.0, - Nacelle_Volume_Grad = 0.0, Nacelle_MinThickness_Grad = 0.0, Nacelle_MaxThickness_Grad = 0.0, Nacelle_MinChord_Grad = 0.0, Nacelle_MaxChord_Grad = 0.0, Nacelle_MinLERadius_Grad = 0.0, Nacelle_MaxLERadius_Grad = 0.0, Nacelle_MinToC_Grad = 0.0, Nacelle_MaxToC_Grad = 0.0, Nacelle_ObjFun_MinToC_Grad = 0.0, Nacelle_MaxTwist_Grad = 0.0; - - vector *Xcoord_Airfoil, *Ycoord_Airfoil, *Zcoord_Airfoil, *Variable_Airfoil; + su2double *ObjectiveFunc, *ObjectiveFunc_New, *Gradient, delta_eps, **Plane_P0, **Plane_Normal, + + Fuselage_Volume = 0.0, Fuselage_WettedArea = 0.0, Fuselage_MinWidth = 0.0, Fuselage_MaxWidth = 0.0, + Fuselage_MinWaterLineWidth = 0.0, Fuselage_MaxWaterLineWidth = 0.0, Fuselage_MinHeight = 0.0, + Fuselage_MaxHeight = 0.0, Fuselage_MaxCurvature = 0.0, Fuselage_Volume_New = 0.0, Fuselage_WettedArea_New = 0.0, + Fuselage_MinWidth_New = 0.0, Fuselage_MaxWidth_New = 0.0, Fuselage_MinWaterLineWidth_New = 0.0, + Fuselage_MaxWaterLineWidth_New = 0.0, Fuselage_MinHeight_New = 0.0, Fuselage_MaxHeight_New = 0.0, + Fuselage_MaxCurvature_New = 0.0, Fuselage_Volume_Grad = 0.0, Fuselage_WettedArea_Grad = 0.0, + Fuselage_MinWidth_Grad = 0.0, Fuselage_MaxWidth_Grad = 0.0, Fuselage_MinWaterLineWidth_Grad = 0.0, + Fuselage_MaxWaterLineWidth_Grad = 0.0, Fuselage_MinHeight_Grad = 0.0, Fuselage_MaxHeight_Grad = 0.0, + Fuselage_MaxCurvature_Grad = 0.0, + + Wing_Volume = 0.0, Wing_MinThickness = 0.0, Wing_MaxThickness = 0.0, Wing_MinChord = 0.0, Wing_MaxChord = 0.0, + Wing_MinLERadius = 0.0, Wing_MaxLERadius = 0.0, Wing_MinToC = 0.0, Wing_MaxToC = 0.0, Wing_ObjFun_MinToC = 0.0, + Wing_MaxTwist = 0.0, Wing_MaxCurvature = 0.0, Wing_MaxDihedral = 0.0, Wing_Volume_New = 0.0, + Wing_MinThickness_New = 0.0, Wing_MaxThickness_New = 0.0, Wing_MinChord_New = 0.0, Wing_MaxChord_New = 0.0, + Wing_MinLERadius_New = 0.0, Wing_MaxLERadius_New = 0.0, Wing_MinToC_New = 0.0, Wing_MaxToC_New = 0.0, + Wing_ObjFun_MinToC_New = 0.0, Wing_MaxTwist_New = 0.0, Wing_MaxCurvature_New = 0.0, Wing_MaxDihedral_New = 0.0, + Wing_Volume_Grad = 0.0, Wing_MinThickness_Grad = 0.0, Wing_MaxThickness_Grad = 0.0, Wing_MinChord_Grad = 0.0, + Wing_MaxChord_Grad = 0.0, Wing_MinLERadius_Grad = 0.0, Wing_MaxLERadius_Grad = 0.0, Wing_MinToC_Grad = 0.0, + Wing_MaxToC_Grad = 0.0, Wing_ObjFun_MinToC_Grad = 0.0, Wing_MaxTwist_Grad = 0.0, Wing_MaxCurvature_Grad = 0.0, + Wing_MaxDihedral_Grad = 0.0, + + Nacelle_Volume = 0.0, Nacelle_MinThickness = 0.0, Nacelle_MaxThickness = 0.0, Nacelle_MinChord = 0.0, + Nacelle_MaxChord = 0.0, Nacelle_MinLERadius = 0.0, Nacelle_MaxLERadius = 0.0, Nacelle_MinToC = 0.0, + Nacelle_MaxToC = 0.0, Nacelle_ObjFun_MinToC = 0.0, Nacelle_MaxTwist = 0.0, Nacelle_Volume_New = 0.0, + Nacelle_MinThickness_New = 0.0, Nacelle_MaxThickness_New = 0.0, Nacelle_MinChord_New = 0.0, + Nacelle_MaxChord_New = 0.0, Nacelle_MinLERadius_New = 0.0, Nacelle_MaxLERadius_New = 0.0, + Nacelle_MinToC_New = 0.0, Nacelle_MaxToC_New = 0.0, Nacelle_ObjFun_MinToC_New = 0.0, Nacelle_MaxTwist_New = 0.0, + Nacelle_Volume_Grad = 0.0, Nacelle_MinThickness_Grad = 0.0, Nacelle_MaxThickness_Grad = 0.0, + Nacelle_MinChord_Grad = 0.0, Nacelle_MaxChord_Grad = 0.0, Nacelle_MinLERadius_Grad = 0.0, + Nacelle_MaxLERadius_Grad = 0.0, Nacelle_MinToC_Grad = 0.0, Nacelle_MaxToC_Grad = 0.0, + Nacelle_ObjFun_MinToC_Grad = 0.0, Nacelle_MaxTwist_Grad = 0.0; + + vector*Xcoord_Airfoil, *Ycoord_Airfoil, *Zcoord_Airfoil, *Variable_Airfoil; vector Xcoord_Fan, Ycoord_Fan, Zcoord_Fan; char config_file_name[MAX_STRING_SIZE]; bool Local_MoveSurface, MoveSurface = false; @@ -58,7 +75,7 @@ int main(int argc, char *argv[]) { /*--- MPI initialization ---*/ - SU2_MPI::Init(&argc,&argv); + SU2_MPI::Init(&argc, &argv); SU2_MPI::Comm MPICommunicator = SU2_MPI::GetComm(); rank = SU2_MPI::GetRank(); @@ -66,25 +83,28 @@ int main(int argc, char *argv[]) { /*--- Pointer to different structures that will be used throughout the entire code ---*/ - CConfig **config_container = nullptr; - CGeometry **geometry_container = nullptr; - CSurfaceMovement *surface_movement = nullptr; - CFreeFormDefBox** FFDBox = nullptr; + CConfig** config_container = nullptr; + CGeometry** geometry_container = nullptr; + CSurfaceMovement* surface_movement = nullptr; + CFreeFormDefBox** FFDBox = nullptr; /*--- Load in the number of zones and spatial dimensions in the mesh file (if no config file is specified, default.cfg is used) ---*/ - if (argc == 2) { strcpy(config_file_name,argv[1]); } - else { strcpy(config_file_name, "default.cfg"); } + if (argc == 2) { + strcpy(config_file_name, argv[1]); + } else { + strcpy(config_file_name, "default.cfg"); + } /*--- Read the name and format of the input mesh file to get from the mesh file the number of zones and dimensions from the numerical grid (required for variables allocation) ---*/ - CConfig *config = nullptr; + CConfig* config = nullptr; config = new CConfig(config_file_name, SU2_COMPONENT::SU2_GEO); - nZone = config->GetnZone(); + nZone = config->GetnZone(); /*--- Definition of the containers per zones ---*/ @@ -92,8 +112,8 @@ int main(int argc, char *argv[]) { geometry_container = new CGeometry*[nZone]; for (iZone = 0; iZone < nZone; iZone++) { - config_container[iZone] = nullptr; - geometry_container[iZone] = nullptr; + config_container[iZone] = nullptr; + geometry_container[iZone] = nullptr; } /*--- Loop over all zones to initialize the various classes. In most @@ -101,7 +121,6 @@ int main(int argc, char *argv[]) { differential equation on a single block, unstructured mesh. ---*/ for (iZone = 0; iZone < nZone; iZone++) { - /*--- Definition of the configuration option class for all zones. In this constructor, the input configuration file is parsed and all options are read and stored. ---*/ @@ -111,7 +130,7 @@ int main(int argc, char *argv[]) { /*--- Definition of the geometry class to store the primal grid in the partitioning process. ---*/ - CGeometry *geometry_aux = nullptr; + CGeometry* geometry_aux = nullptr; /*--- All ranks process the grid and call ParMETIS for partitioning ---*/ @@ -136,7 +155,6 @@ int main(int argc, char *argv[]) { /*--- Add the Send/Receive boundaries ---*/ geometry_container[iZone]->SetBoundaries(config_container[iZone]); - } bool tabTecplot = config_container[ZONE_0]->GetTabular_FileFormat() == TAB_OUTPUT::TAB_TECPLOT; @@ -148,12 +166,14 @@ int main(int argc, char *argv[]) { /*--- Evaluation of the objective function ---*/ if (rank == MASTER_NODE) - cout << endl <<"----------------------- Preprocessing computations ----------------------" << endl; + cout << endl << "----------------------- Preprocessing computations ----------------------" << endl; /*--- Set the number of sections, and allocate the memory ---*/ - if (geometry_container[ZONE_0]->GetnDim() == 2) nPlane = 1; - else nPlane = config_container[ZONE_0]->GetnLocationStations(); + if (geometry_container[ZONE_0]->GetnDim() == 2) + nPlane = 1; + else + nPlane = config_container[ZONE_0]->GetnLocationStations(); Xcoord_Airfoil = new vector[nPlane]; Ycoord_Airfoil = new vector[nPlane]; @@ -162,38 +182,38 @@ int main(int argc, char *argv[]) { Plane_P0 = new su2double*[nPlane]; Plane_Normal = new su2double*[nPlane]; - for(iPlane = 0; iPlane < nPlane; iPlane++ ) { + for (iPlane = 0; iPlane < nPlane; iPlane++) { Plane_P0[iPlane] = new su2double[3]; Plane_Normal[iPlane] = new su2double[3]; } - ObjectiveFunc = new su2double[nPlane*20]; - ObjectiveFunc_New = new su2double[nPlane*20]; - Gradient = new su2double[nPlane*20]; + ObjectiveFunc = new su2double[nPlane * 20]; + ObjectiveFunc_New = new su2double[nPlane * 20]; + Gradient = new su2double[nPlane * 20]; - for (iVar = 0; iVar < nPlane*20; iVar++) { + for (iVar = 0; iVar < nPlane * 20; iVar++) { ObjectiveFunc[iVar] = 0.0; ObjectiveFunc_New[iVar] = 0.0; Gradient[iVar] = 0.0; } - /*--- Compute elements surrounding points, points surrounding points ---*/ - if (rank == MASTER_NODE) cout << "Setting local point connectivity." <SetPoint_Connectivity(); /*--- Check the orientation before computing geometrical quantities ---*/ if (config_container[ZONE_0]->GetReorientElements()) { - if (rank == MASTER_NODE) cout << "Checking the numerical grid orientation of the interior elements." <Check_IntElem_Orientation(config_container[ZONE_0]); } /*--- Create the edge structure ---*/ - if (rank == MASTER_NODE) cout << "Identify edges and vertices." <SetEdges(); geometry_container[ZONE_0]->SetVertex(config_container[ZONE_0]); + if (rank == MASTER_NODE) cout << "Identify edges and vertices." << endl; + geometry_container[ZONE_0]->SetEdges(); + geometry_container[ZONE_0]->SetVertex(config_container[ZONE_0]); /*--- Create the dual control volume structures ---*/ @@ -218,37 +238,43 @@ int main(int argc, char *argv[]) { if (rank == MASTER_NODE) cout << "Set plane structure." << endl; if (geometry_container[ZONE_0]->GetnDim() == 2) { - Plane_Normal[0][0] = 0.0; Plane_P0[0][0] = 0.0; - Plane_Normal[0][1] = 1.0; Plane_P0[0][1] = 0.0; - Plane_Normal[0][2] = 0.0; Plane_P0[0][2] = 0.0; - } - else if (geometry_container[ZONE_0]->GetnDim() == 3) { + Plane_Normal[0][0] = 0.0; + Plane_P0[0][0] = 0.0; + Plane_Normal[0][1] = 1.0; + Plane_P0[0][1] = 0.0; + Plane_Normal[0][2] = 0.0; + Plane_P0[0][2] = 0.0; + } else if (geometry_container[ZONE_0]->GetnDim() == 3) { for (iPlane = 0; iPlane < nPlane; iPlane++) { - Plane_Normal[iPlane][0] = 0.0; Plane_P0[iPlane][0] = 0.0; - Plane_Normal[iPlane][1] = 0.0; Plane_P0[iPlane][1] = 0.0; - Plane_Normal[iPlane][2] = 0.0; Plane_P0[iPlane][2] = 0.0; + Plane_Normal[iPlane][0] = 0.0; + Plane_P0[iPlane][0] = 0.0; + Plane_Normal[iPlane][1] = 0.0; + Plane_P0[iPlane][1] = 0.0; + Plane_Normal[iPlane][2] = 0.0; + Plane_P0[iPlane][2] = 0.0; if (config_container[ZONE_0]->GetGeo_Description() == FUSELAGE) { Plane_Normal[iPlane][0] = 1.0; Plane_P0[iPlane][0] = config_container[ZONE_0]->GetLocationStations(iPlane); - } - else if (config_container[ZONE_0]->GetGeo_Description() == NACELLE) { + } else if (config_container[ZONE_0]->GetGeo_Description() == NACELLE) { Plane_Normal[iPlane][0] = 0.0; - Plane_Normal[iPlane][1] = -sin(config_container[ZONE_0]->GetLocationStations(iPlane)*PI_NUMBER/180.0); - Plane_Normal[iPlane][2] = cos(config_container[ZONE_0]->GetLocationStations(iPlane)*PI_NUMBER/180.0); + Plane_Normal[iPlane][1] = -sin(config_container[ZONE_0]->GetLocationStations(iPlane) * PI_NUMBER / 180.0); + Plane_Normal[iPlane][2] = cos(config_container[ZONE_0]->GetLocationStations(iPlane) * PI_NUMBER / 180.0); /*--- Apply tilt angle to the plane ---*/ - su2double Tilt_Angle = config_container[ZONE_0]->GetNacelleLocation(3)*PI_NUMBER/180; - su2double Plane_NormalX_Tilt = Plane_Normal[iPlane][0]*cos(Tilt_Angle) + Plane_Normal[iPlane][2]*sin(Tilt_Angle); + su2double Tilt_Angle = config_container[ZONE_0]->GetNacelleLocation(3) * PI_NUMBER / 180; + su2double Plane_NormalX_Tilt = + Plane_Normal[iPlane][0] * cos(Tilt_Angle) + Plane_Normal[iPlane][2] * sin(Tilt_Angle); su2double Plane_NormalY_Tilt = Plane_Normal[iPlane][1]; - su2double Plane_NormalZ_Tilt = Plane_Normal[iPlane][2]*cos(Tilt_Angle) - Plane_Normal[iPlane][0]*sin(Tilt_Angle); + su2double Plane_NormalZ_Tilt = + Plane_Normal[iPlane][2] * cos(Tilt_Angle) - Plane_Normal[iPlane][0] * sin(Tilt_Angle); /*--- Apply toe angle to the plane ---*/ - su2double Toe_Angle = config_container[ZONE_0]->GetNacelleLocation(4)*PI_NUMBER/180; - su2double Plane_NormalX_Tilt_Toe = Plane_NormalX_Tilt*cos(Toe_Angle) - Plane_NormalY_Tilt*sin(Toe_Angle); - su2double Plane_NormalY_Tilt_Toe = Plane_NormalX_Tilt*sin(Toe_Angle) + Plane_NormalY_Tilt*cos(Toe_Angle); + su2double Toe_Angle = config_container[ZONE_0]->GetNacelleLocation(4) * PI_NUMBER / 180; + su2double Plane_NormalX_Tilt_Toe = Plane_NormalX_Tilt * cos(Toe_Angle) - Plane_NormalY_Tilt * sin(Toe_Angle); + su2double Plane_NormalY_Tilt_Toe = Plane_NormalX_Tilt * sin(Toe_Angle) + Plane_NormalY_Tilt * cos(Toe_Angle); su2double Plane_NormalZ_Tilt_Toe = Plane_NormalZ_Tilt; /*--- Update normal vector ---*/ @@ -262,321 +288,432 @@ int main(int argc, char *argv[]) { Plane_P0[iPlane][0] = config_container[ZONE_0]->GetNacelleLocation(0); Plane_P0[iPlane][1] = config_container[ZONE_0]->GetNacelleLocation(1); Plane_P0[iPlane][2] = config_container[ZONE_0]->GetNacelleLocation(2); - } - else { + } else { Plane_Normal[iPlane][1] = 1.0; Plane_P0[iPlane][1] = config_container[ZONE_0]->GetLocationStations(iPlane); } - } } /*--- Compute the wing and fan description (only 3D). ---*/ if (geometry_container[ZONE_0]->GetnDim() == 3) { - if (config_container[ZONE_0]->GetGeo_Description() == FUSELAGE) { - if (rank == MASTER_NODE) { cout << "Computing the fuselage continuous description." << endl << endl; } - geometry_container[ZONE_0]->Compute_Fuselage(config_container[ZONE_0], true, - Fuselage_Volume, Fuselage_WettedArea, Fuselage_MinWidth, Fuselage_MaxWidth, - Fuselage_MinWaterLineWidth, Fuselage_MaxWaterLineWidth, - Fuselage_MinHeight, Fuselage_MaxHeight, + geometry_container[ZONE_0]->Compute_Fuselage(config_container[ZONE_0], true, Fuselage_Volume, Fuselage_WettedArea, + Fuselage_MinWidth, Fuselage_MaxWidth, Fuselage_MinWaterLineWidth, + Fuselage_MaxWaterLineWidth, Fuselage_MinHeight, Fuselage_MaxHeight, Fuselage_MaxCurvature); /*--- Screen output for the wing definition ---*/ if (rank == MASTER_NODE) { - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << "Fuselage volume: " << Fuselage_Volume << " in^3. "; - else cout << "Fuselage volume: " << Fuselage_Volume << " m^3. "; - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << "Fuselage wetted area: " << Fuselage_WettedArea << " in^2. " << endl; - else cout << "Fuselage wetted area: " << Fuselage_WettedArea << " m^2. " << endl; - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << "Fuselage min. width: " << Fuselage_MinWidth << " in. "; - else cout << "Fuselage min. width: " << Fuselage_MinWidth << " m. "; - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << "Fuselage max. width: " << Fuselage_MaxWidth << " in. " << endl; - else cout << "Fuselage max. width: " << Fuselage_MaxWidth << " m. " << endl; - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << "Fuselage min. waterline width: " << Fuselage_MinWaterLineWidth << " in. "; - else cout << "Fuselage min. waterline width: " << Fuselage_MinWaterLineWidth << " m. "; - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << "Fuselage max. waterline width: " << Fuselage_MaxWaterLineWidth << " in. " << endl; - else cout << "Fuselage max. waterline width: " << Fuselage_MaxWaterLineWidth << " m. " << endl; - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << "Fuselage min. height: " << Fuselage_MinHeight << " in. "; - else cout << "Fuselage min. height: " << Fuselage_MinHeight << " m. "; - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << "Fuselage max. height: " << Fuselage_MaxHeight << " in. " << endl; - else cout << "Fuselage max. height: " << Fuselage_MaxHeight << " m. " << endl; - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << "Fuselage max. curvature: " << Fuselage_MaxCurvature << " 1/in. " << endl; - else cout << "Fuselage max. curvature: " << Fuselage_MaxCurvature << " 1/m. " << endl; + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << "Fuselage volume: " << Fuselage_Volume << " in^3. "; + else + cout << "Fuselage volume: " << Fuselage_Volume << " m^3. "; + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << "Fuselage wetted area: " << Fuselage_WettedArea << " in^2. " << endl; + else + cout << "Fuselage wetted area: " << Fuselage_WettedArea << " m^2. " << endl; + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << "Fuselage min. width: " << Fuselage_MinWidth << " in. "; + else + cout << "Fuselage min. width: " << Fuselage_MinWidth << " m. "; + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << "Fuselage max. width: " << Fuselage_MaxWidth << " in. " << endl; + else + cout << "Fuselage max. width: " << Fuselage_MaxWidth << " m. " << endl; + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << "Fuselage min. waterline width: " << Fuselage_MinWaterLineWidth << " in. "; + else + cout << "Fuselage min. waterline width: " << Fuselage_MinWaterLineWidth << " m. "; + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << "Fuselage max. waterline width: " << Fuselage_MaxWaterLineWidth << " in. " << endl; + else + cout << "Fuselage max. waterline width: " << Fuselage_MaxWaterLineWidth << " m. " << endl; + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << "Fuselage min. height: " << Fuselage_MinHeight << " in. "; + else + cout << "Fuselage min. height: " << Fuselage_MinHeight << " m. "; + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << "Fuselage max. height: " << Fuselage_MaxHeight << " in. " << endl; + else + cout << "Fuselage max. height: " << Fuselage_MaxHeight << " m. " << endl; + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << "Fuselage max. curvature: " << Fuselage_MaxCurvature << " 1/in. " << endl; + else + cout << "Fuselage max. curvature: " << Fuselage_MaxCurvature << " 1/m. " << endl; } } else if (config_container[ZONE_0]->GetGeo_Description() == NACELLE) { - if (rank == MASTER_NODE) { cout << "Computing the nacelle continuous description." << endl << endl; } - geometry_container[ZONE_0]->Compute_Nacelle(config_container[ZONE_0], true, - Nacelle_Volume, Nacelle_MinThickness, Nacelle_MaxThickness, Nacelle_MinChord, Nacelle_MaxChord, - Nacelle_MinLERadius, Nacelle_MaxLERadius, Nacelle_MinToC, Nacelle_MaxToC, Nacelle_ObjFun_MinToC, - Nacelle_MaxTwist); + geometry_container[ZONE_0]->Compute_Nacelle(config_container[ZONE_0], true, Nacelle_Volume, Nacelle_MinThickness, + Nacelle_MaxThickness, Nacelle_MinChord, Nacelle_MaxChord, + Nacelle_MinLERadius, Nacelle_MaxLERadius, Nacelle_MinToC, + Nacelle_MaxToC, Nacelle_ObjFun_MinToC, Nacelle_MaxTwist); /*--- Screen output for the wing definition ---*/ if (rank == MASTER_NODE) { - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << "Nacelle volume: " << Nacelle_Volume << " in^3. "; - else cout << "Nacelle volume: " << Nacelle_Volume << " m^3. "; - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << "Nacelle min. thickness: " << Nacelle_MinThickness << " in. "; - else cout << "Nacelle min. thickness: " << Nacelle_MinThickness << " m. "; - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << "Nacelle max. thickness: " << Nacelle_MaxThickness << " in. " << endl; - else cout << "Nacelle max. thickness: " << Nacelle_MaxThickness << " m. " << endl; - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << "Nacelle min. chord: " << Nacelle_MinChord << " in. "; - else cout << "Nacelle min. chord: " << Nacelle_MinChord << " m. "; - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << "Nacelle max. chord: " << Nacelle_MaxChord << " in. "; - else cout << "Nacelle max. chord: " << Nacelle_MaxChord << " m. "; - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << "Nacelle min. LE radius: " << Nacelle_MinLERadius << " 1/in. "; - else cout << "Nacelle min. LE radius: " << Nacelle_MinLERadius << " 1/m. "; - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << "Nacelle max. LE radius: " << Nacelle_MaxLERadius << " 1/in. " << endl; - else cout << "Nacelle max. LE radius: " << Nacelle_MaxLERadius << " 1/m. " << endl; - cout << "Nacelle min. ToC: " << Nacelle_MinToC << ". "; - cout << "Nacelle max. ToC: " << Nacelle_MaxToC << ". "; - cout << "Nacelle delta ToC: " << Nacelle_ObjFun_MinToC << ". "; - cout << "Nacelle max. twist: " << Nacelle_MaxTwist << " deg. "<< endl; + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << "Nacelle volume: " << Nacelle_Volume << " in^3. "; + else + cout << "Nacelle volume: " << Nacelle_Volume << " m^3. "; + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << "Nacelle min. thickness: " << Nacelle_MinThickness << " in. "; + else + cout << "Nacelle min. thickness: " << Nacelle_MinThickness << " m. "; + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << "Nacelle max. thickness: " << Nacelle_MaxThickness << " in. " << endl; + else + cout << "Nacelle max. thickness: " << Nacelle_MaxThickness << " m. " << endl; + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << "Nacelle min. chord: " << Nacelle_MinChord << " in. "; + else + cout << "Nacelle min. chord: " << Nacelle_MinChord << " m. "; + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << "Nacelle max. chord: " << Nacelle_MaxChord << " in. "; + else + cout << "Nacelle max. chord: " << Nacelle_MaxChord << " m. "; + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << "Nacelle min. LE radius: " << Nacelle_MinLERadius << " 1/in. "; + else + cout << "Nacelle min. LE radius: " << Nacelle_MinLERadius << " 1/m. "; + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << "Nacelle max. LE radius: " << Nacelle_MaxLERadius << " 1/in. " << endl; + else + cout << "Nacelle max. LE radius: " << Nacelle_MaxLERadius << " 1/m. " << endl; + cout << "Nacelle min. ToC: " << Nacelle_MinToC << ". "; + cout << "Nacelle max. ToC: " << Nacelle_MaxToC << ". "; + cout << "Nacelle delta ToC: " << Nacelle_ObjFun_MinToC << ". "; + cout << "Nacelle max. twist: " << Nacelle_MaxTwist << " deg. " << endl; } } else { - if (rank == MASTER_NODE) { cout << "Computing the wing continuous description." << endl << endl; } - geometry_container[ZONE_0]->Compute_Wing(config_container[ZONE_0], true, - Wing_Volume, Wing_MinThickness, Wing_MaxThickness, Wing_MinChord, Wing_MaxChord, - Wing_MinLERadius, Wing_MaxLERadius, Wing_MinToC, Wing_MaxToC, Wing_ObjFun_MinToC, + geometry_container[ZONE_0]->Compute_Wing(config_container[ZONE_0], true, Wing_Volume, Wing_MinThickness, + Wing_MaxThickness, Wing_MinChord, Wing_MaxChord, Wing_MinLERadius, + Wing_MaxLERadius, Wing_MinToC, Wing_MaxToC, Wing_ObjFun_MinToC, Wing_MaxTwist, Wing_MaxCurvature, Wing_MaxDihedral); /*--- Screen output for the wing definition ---*/ if (rank == MASTER_NODE) { - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << "Wing volume: " << Wing_Volume << " in^3. "; - else cout << "Wing volume: " << Wing_Volume << " m^3. "; - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << "Wing min. thickness: " << Wing_MinThickness << " in. "; - else cout << "Wing min. thickness: " << Wing_MinThickness << " m. "; - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << "Wing max. thickness: " << Wing_MaxThickness << " in. " << endl; - else cout << "Wing max. thickness: " << Wing_MaxThickness << " m. " << endl; - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << "Wing min. chord: " << Wing_MinChord << " in. "; - else cout << "Wing min. chord: " << Wing_MinChord << " m. "; - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << "Wing max. chord: " << Wing_MaxChord << " in. "; - else cout << "Wing max. chord: " << Wing_MaxChord << " m. "; - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << "Wing min. LE radius: " << Wing_MinLERadius << " 1/in. "; - else cout << "Wing min. LE radius: " << Wing_MinLERadius << " 1/m. "; - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << "Wing max. LE radius: " << Wing_MaxLERadius << " 1/in. " << endl; - else cout << "Wing max. LE radius: " << Wing_MaxLERadius << " 1/m. " << endl; - cout << "Wing min. ToC: " << Wing_MinToC << ". "; - cout << "Wing max. ToC: " << Wing_MaxToC << ". "; - cout << "Wing delta ToC: " << Wing_ObjFun_MinToC << ". "; - cout << "Wing max. twist: " << Wing_MaxTwist << " deg. "<< endl; - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << "Wing max. curvature: " << Wing_MaxCurvature << " 1/in. "; - else cout << "Wing max. curvature: " << Wing_MaxCurvature << " 1/m. "; - cout << "Wing max. dihedral: " << Wing_MaxDihedral << " deg." << endl; + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << "Wing volume: " << Wing_Volume << " in^3. "; + else + cout << "Wing volume: " << Wing_Volume << " m^3. "; + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << "Wing min. thickness: " << Wing_MinThickness << " in. "; + else + cout << "Wing min. thickness: " << Wing_MinThickness << " m. "; + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << "Wing max. thickness: " << Wing_MaxThickness << " in. " << endl; + else + cout << "Wing max. thickness: " << Wing_MaxThickness << " m. " << endl; + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << "Wing min. chord: " << Wing_MinChord << " in. "; + else + cout << "Wing min. chord: " << Wing_MinChord << " m. "; + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << "Wing max. chord: " << Wing_MaxChord << " in. "; + else + cout << "Wing max. chord: " << Wing_MaxChord << " m. "; + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << "Wing min. LE radius: " << Wing_MinLERadius << " 1/in. "; + else + cout << "Wing min. LE radius: " << Wing_MinLERadius << " 1/m. "; + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << "Wing max. LE radius: " << Wing_MaxLERadius << " 1/in. " << endl; + else + cout << "Wing max. LE radius: " << Wing_MaxLERadius << " 1/m. " << endl; + cout << "Wing min. ToC: " << Wing_MinToC << ". "; + cout << "Wing max. ToC: " << Wing_MaxToC << ". "; + cout << "Wing delta ToC: " << Wing_ObjFun_MinToC << ". "; + cout << "Wing max. twist: " << Wing_MaxTwist << " deg. " << endl; + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << "Wing max. curvature: " << Wing_MaxCurvature << " 1/in. "; + else + cout << "Wing max. curvature: " << Wing_MaxCurvature << " 1/m. "; + cout << "Wing max. dihedral: " << Wing_MaxDihedral << " deg." << endl; } - } - } for (iPlane = 0; iPlane < nPlane; iPlane++) { - - geometry_container[ZONE_0]->ComputeAirfoil_Section(Plane_P0[iPlane], Plane_Normal[iPlane], -1E6, 1E6, -1E6, 1E6, -1E6, 1E6, nullptr, - Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane], - Variable_Airfoil[iPlane], true, config_container[ZONE_0]); + geometry_container[ZONE_0]->ComputeAirfoil_Section( + Plane_P0[iPlane], Plane_Normal[iPlane], -1E6, 1E6, -1E6, 1E6, -1E6, 1E6, nullptr, Xcoord_Airfoil[iPlane], + Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane], Variable_Airfoil[iPlane], true, config_container[ZONE_0]); } if (rank == MASTER_NODE) - cout << endl <<"-------------------- Objective function evaluation ----------------------" << endl; + cout << endl << "-------------------- Objective function evaluation ----------------------" << endl; if (rank == MASTER_NODE) { - /*--- Evaluate objective function ---*/ for (iPlane = 0; iPlane < nPlane; iPlane++) { - if (Xcoord_Airfoil[iPlane].size() > 1) { - - cout << "\nStation " << (iPlane+1); + cout << "\nStation " << (iPlane + 1); if (config_container[ZONE_0]->GetGeo_Description() == FUSELAGE) { - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << ". XCoord: " << Plane_P0[iPlane][0] << " in, "; - else cout << ". XCoord: " << Plane_P0[iPlane][0] << " m, "; + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << ". XCoord: " << Plane_P0[iPlane][0] << " in, "; + else + cout << ". XCoord: " << Plane_P0[iPlane][0] << " m, "; } if (config_container[ZONE_0]->GetGeo_Description() == WING) { - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << ". YCoord: " << Plane_P0[iPlane][1] << " in, "; - else cout << ". YCoord: " << Plane_P0[iPlane][1] << " m, "; + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << ". YCoord: " << Plane_P0[iPlane][1] << " in, "; + else + cout << ". YCoord: " << Plane_P0[iPlane][1] << " m, "; } if (config_container[ZONE_0]->GetGeo_Description() == TWOD_AIRFOIL) { - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << ". ZCoord: " << Plane_P0[iPlane][2] << " in, "; - else cout << ". ZCoord: " << Plane_P0[iPlane][2] << " m, "; + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << ". ZCoord: " << Plane_P0[iPlane][2] << " in, "; + else + cout << ". ZCoord: " << Plane_P0[iPlane][2] << " m, "; } - if (config_container[ZONE_0]->GetGeo_Description() == NACELLE) cout << ". Theta: " << atan2(Plane_Normal[iPlane][1], -Plane_Normal[iPlane][2])/PI_NUMBER*180 + 180 << " deg, "; + if (config_container[ZONE_0]->GetGeo_Description() == NACELLE) + cout << ". Theta: " << atan2(Plane_Normal[iPlane][1], -Plane_Normal[iPlane][2]) / PI_NUMBER * 180 + 180 + << " deg, "; if (config_container[ZONE_0]->GetGeo_Description() == FUSELAGE) { - ObjectiveFunc[0*nPlane+iPlane] = geometry_container[ZONE_0]->Compute_Area(Plane_P0[iPlane], Plane_Normal[iPlane], config_container[ZONE_0], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - ObjectiveFunc[1*nPlane+iPlane] = geometry_container[ZONE_0]->Compute_Length(Plane_P0[iPlane], Plane_Normal[iPlane], config_container[ZONE_0], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - ObjectiveFunc[2*nPlane+iPlane] = geometry_container[ZONE_0]->Compute_Width(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - ObjectiveFunc[3*nPlane+iPlane] = geometry_container[ZONE_0]->Compute_WaterLineWidth(Plane_P0[iPlane], Plane_Normal[iPlane], config_container[ZONE_0], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - ObjectiveFunc[4*nPlane+iPlane] = geometry_container[ZONE_0]->Compute_Height(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << "Area: " << ObjectiveFunc[0*nPlane+iPlane] << " in^2, "; - else cout << "Area: " << ObjectiveFunc[0*nPlane+iPlane] << " m^2, "; - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << "Length: " << ObjectiveFunc[1*nPlane+iPlane] << " in, "; - else cout << "Length: " << ObjectiveFunc[1*nPlane+iPlane] << " m, "; - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << "Width: " << ObjectiveFunc[2*nPlane+iPlane] << " in, "; - else cout << "Width: " << ObjectiveFunc[2*nPlane+iPlane] << " m, "; - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << "Waterline width: " << ObjectiveFunc[3*nPlane+iPlane] << " in, "; - else cout << "Waterline width: " << ObjectiveFunc[3*nPlane+iPlane] << " m, "; - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << "Height: " << ObjectiveFunc[4*nPlane+iPlane] << " in."; - else cout << "Height: " << ObjectiveFunc[4*nPlane+iPlane] << " m."; - } - else if (config_container[ZONE_0]->GetGeo_Description() == NACELLE) { - ObjectiveFunc[0*nPlane+iPlane] = geometry_container[ZONE_0]->Compute_Area(Plane_P0[iPlane], Plane_Normal[iPlane], config_container[ZONE_0], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - ObjectiveFunc[1*nPlane+iPlane] = geometry_container[ZONE_0]->Compute_MaxThickness(Plane_P0[iPlane], Plane_Normal[iPlane], config_container[ZONE_0], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - ObjectiveFunc[2*nPlane+iPlane] = geometry_container[ZONE_0]->Compute_Chord(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - ObjectiveFunc[3*nPlane+iPlane] = geometry_container[ZONE_0]->Compute_LERadius(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - ObjectiveFunc[4*nPlane+iPlane] = ObjectiveFunc[1*nPlane+iPlane]/ObjectiveFunc[2*nPlane+iPlane]; - ObjectiveFunc[5*nPlane+iPlane] = geometry_container[ZONE_0]->Compute_Twist(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << "Area: " << ObjectiveFunc[0*nPlane+iPlane] << " in^2, "; - else cout << "Area: " << ObjectiveFunc[0*nPlane+iPlane] << " m^2, "; - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << "Thickness: " << ObjectiveFunc[1*nPlane+iPlane] << " in, " << endl; - else cout << "Thickness: " << ObjectiveFunc[1*nPlane+iPlane] << " m, " << endl; - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << "Chord: " << ObjectiveFunc[2*nPlane+iPlane] << " in, "; - else cout << "Chord: " << ObjectiveFunc[2*nPlane+iPlane] << " m, "; - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << "LE radius: " << ObjectiveFunc[3*nPlane+iPlane] << " 1/in, "; - else cout << "LE radius: " << ObjectiveFunc[3*nPlane+iPlane] << " 1/m, "; - cout << "ToC: " << ObjectiveFunc[4*nPlane+iPlane] << ", "; - if (geometry_container[ZONE_0]->GetnDim() == 2) cout << "Alpha: " << ObjectiveFunc[5*nPlane+iPlane] <<" deg."; - else if (geometry_container[ZONE_0]->GetnDim() == 3) cout << "Twist angle: " << ObjectiveFunc[5*nPlane+iPlane] <<" deg."; + ObjectiveFunc[0 * nPlane + iPlane] = geometry_container[ZONE_0]->Compute_Area( + Plane_P0[iPlane], Plane_Normal[iPlane], config_container[ZONE_0], Xcoord_Airfoil[iPlane], + Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); + ObjectiveFunc[1 * nPlane + iPlane] = geometry_container[ZONE_0]->Compute_Length( + Plane_P0[iPlane], Plane_Normal[iPlane], config_container[ZONE_0], Xcoord_Airfoil[iPlane], + Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); + ObjectiveFunc[2 * nPlane + iPlane] = + geometry_container[ZONE_0]->Compute_Width(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], + Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); + ObjectiveFunc[3 * nPlane + iPlane] = geometry_container[ZONE_0]->Compute_WaterLineWidth( + Plane_P0[iPlane], Plane_Normal[iPlane], config_container[ZONE_0], Xcoord_Airfoil[iPlane], + Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); + ObjectiveFunc[4 * nPlane + iPlane] = + geometry_container[ZONE_0]->Compute_Height(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], + Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); + + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << "Area: " << ObjectiveFunc[0 * nPlane + iPlane] << " in^2, "; + else + cout << "Area: " << ObjectiveFunc[0 * nPlane + iPlane] << " m^2, "; + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << "Length: " << ObjectiveFunc[1 * nPlane + iPlane] << " in, "; + else + cout << "Length: " << ObjectiveFunc[1 * nPlane + iPlane] << " m, "; + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << "Width: " << ObjectiveFunc[2 * nPlane + iPlane] << " in, "; + else + cout << "Width: " << ObjectiveFunc[2 * nPlane + iPlane] << " m, "; + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << "Waterline width: " << ObjectiveFunc[3 * nPlane + iPlane] << " in, "; + else + cout << "Waterline width: " << ObjectiveFunc[3 * nPlane + iPlane] << " m, "; + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << "Height: " << ObjectiveFunc[4 * nPlane + iPlane] << " in."; + else + cout << "Height: " << ObjectiveFunc[4 * nPlane + iPlane] << " m."; + } else if (config_container[ZONE_0]->GetGeo_Description() == NACELLE) { + ObjectiveFunc[0 * nPlane + iPlane] = geometry_container[ZONE_0]->Compute_Area( + Plane_P0[iPlane], Plane_Normal[iPlane], config_container[ZONE_0], Xcoord_Airfoil[iPlane], + Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); + ObjectiveFunc[1 * nPlane + iPlane] = geometry_container[ZONE_0]->Compute_MaxThickness( + Plane_P0[iPlane], Plane_Normal[iPlane], config_container[ZONE_0], Xcoord_Airfoil[iPlane], + Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); + ObjectiveFunc[2 * nPlane + iPlane] = + geometry_container[ZONE_0]->Compute_Chord(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], + Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); + ObjectiveFunc[3 * nPlane + iPlane] = geometry_container[ZONE_0]->Compute_LERadius( + Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], + Zcoord_Airfoil[iPlane]); + ObjectiveFunc[4 * nPlane + iPlane] = ObjectiveFunc[1 * nPlane + iPlane] / ObjectiveFunc[2 * nPlane + iPlane]; + ObjectiveFunc[5 * nPlane + iPlane] = + geometry_container[ZONE_0]->Compute_Twist(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], + Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); + + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << "Area: " << ObjectiveFunc[0 * nPlane + iPlane] << " in^2, "; + else + cout << "Area: " << ObjectiveFunc[0 * nPlane + iPlane] << " m^2, "; + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << "Thickness: " << ObjectiveFunc[1 * nPlane + iPlane] << " in, " << endl; + else + cout << "Thickness: " << ObjectiveFunc[1 * nPlane + iPlane] << " m, " << endl; + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << "Chord: " << ObjectiveFunc[2 * nPlane + iPlane] << " in, "; + else + cout << "Chord: " << ObjectiveFunc[2 * nPlane + iPlane] << " m, "; + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << "LE radius: " << ObjectiveFunc[3 * nPlane + iPlane] << " 1/in, "; + else + cout << "LE radius: " << ObjectiveFunc[3 * nPlane + iPlane] << " 1/m, "; + cout << "ToC: " << ObjectiveFunc[4 * nPlane + iPlane] << ", "; + if (geometry_container[ZONE_0]->GetnDim() == 2) + cout << "Alpha: " << ObjectiveFunc[5 * nPlane + iPlane] << " deg."; + else if (geometry_container[ZONE_0]->GetnDim() == 3) + cout << "Twist angle: " << ObjectiveFunc[5 * nPlane + iPlane] << " deg."; + } else { + ObjectiveFunc[0 * nPlane + iPlane] = geometry_container[ZONE_0]->Compute_Area( + Plane_P0[iPlane], Plane_Normal[iPlane], config_container[ZONE_0], Xcoord_Airfoil[iPlane], + Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); + ObjectiveFunc[1 * nPlane + iPlane] = geometry_container[ZONE_0]->Compute_MaxThickness( + Plane_P0[iPlane], Plane_Normal[iPlane], config_container[ZONE_0], Xcoord_Airfoil[iPlane], + Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); + ObjectiveFunc[2 * nPlane + iPlane] = + geometry_container[ZONE_0]->Compute_Chord(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], + Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); + ObjectiveFunc[3 * nPlane + iPlane] = geometry_container[ZONE_0]->Compute_LERadius( + Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], + Zcoord_Airfoil[iPlane]); + ObjectiveFunc[4 * nPlane + iPlane] = ObjectiveFunc[1 * nPlane + iPlane] / ObjectiveFunc[2 * nPlane + iPlane]; + ObjectiveFunc[5 * nPlane + iPlane] = + geometry_container[ZONE_0]->Compute_Twist(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], + Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); + + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << "Area: " << ObjectiveFunc[0 * nPlane + iPlane] << " in^2, "; + else + cout << "Area: " << ObjectiveFunc[0 * nPlane + iPlane] << " m^2, "; + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << "Thickness: " << ObjectiveFunc[1 * nPlane + iPlane] << " in, " << endl; + else + cout << "Thickness: " << ObjectiveFunc[1 * nPlane + iPlane] << " m, " << endl; + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << "Chord: " << ObjectiveFunc[2 * nPlane + iPlane] << " in, "; + else + cout << "Chord: " << ObjectiveFunc[2 * nPlane + iPlane] << " m, "; + if (config_container[ZONE_0]->GetSystemMeasurements() == US) + cout << "LE radius: " << ObjectiveFunc[3 * nPlane + iPlane] << " 1/in, "; + else + cout << "LE radius: " << ObjectiveFunc[3 * nPlane + iPlane] << " 1/m, "; + cout << "ToC: " << ObjectiveFunc[4 * nPlane + iPlane] << ", "; + if (geometry_container[ZONE_0]->GetnDim() == 2) + cout << "Alpha: " << ObjectiveFunc[5 * nPlane + iPlane] << " deg."; + else if (geometry_container[ZONE_0]->GetnDim() == 3) + cout << "Twist angle: " << ObjectiveFunc[5 * nPlane + iPlane] << " deg."; } - else { - ObjectiveFunc[0*nPlane+iPlane] = geometry_container[ZONE_0]->Compute_Area(Plane_P0[iPlane], Plane_Normal[iPlane], config_container[ZONE_0], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - ObjectiveFunc[1*nPlane+iPlane] = geometry_container[ZONE_0]->Compute_MaxThickness(Plane_P0[iPlane], Plane_Normal[iPlane], config_container[ZONE_0], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - ObjectiveFunc[2*nPlane+iPlane] = geometry_container[ZONE_0]->Compute_Chord(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - ObjectiveFunc[3*nPlane+iPlane] = geometry_container[ZONE_0]->Compute_LERadius(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - ObjectiveFunc[4*nPlane+iPlane] = ObjectiveFunc[1*nPlane+iPlane]/ObjectiveFunc[2*nPlane+iPlane]; - ObjectiveFunc[5*nPlane+iPlane] = geometry_container[ZONE_0]->Compute_Twist(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << "Area: " << ObjectiveFunc[0*nPlane+iPlane] << " in^2, "; - else cout << "Area: " << ObjectiveFunc[0*nPlane+iPlane] << " m^2, "; - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << "Thickness: " << ObjectiveFunc[1*nPlane+iPlane] << " in, " << endl; - else cout << "Thickness: " << ObjectiveFunc[1*nPlane+iPlane] << " m, " << endl; - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << "Chord: " << ObjectiveFunc[2*nPlane+iPlane] << " in, "; - else cout << "Chord: " << ObjectiveFunc[2*nPlane+iPlane] << " m, "; - if (config_container[ZONE_0]->GetSystemMeasurements() == US) cout << "LE radius: " << ObjectiveFunc[3*nPlane+iPlane] << " 1/in, "; - else cout << "LE radius: " << ObjectiveFunc[3*nPlane+iPlane] << " 1/m, "; - cout << "ToC: " << ObjectiveFunc[4*nPlane+iPlane] << ", "; - if (geometry_container[ZONE_0]->GetnDim() == 2) cout << "Alpha: " << ObjectiveFunc[5*nPlane+iPlane] <<" deg."; - else if (geometry_container[ZONE_0]->GetnDim() == 3) cout << "Twist angle: " << ObjectiveFunc[5*nPlane+iPlane] <<" deg."; - } - } - } /*--- Write the objective function in a external file ---*/ string filename = config_container[ZONE_0]->GetObjFunc_Value_FileName(); unsigned short lastindex = filename.find_last_of("."); filename = filename.substr(0, lastindex); - if (tabTecplot) filename += ".dat"; - else filename += ".csv"; + if (tabTecplot) + filename += ".dat"; + else + filename += ".csv"; ObjFunc_file.open(filename.c_str(), ios::out); if (tabTecplot) ObjFunc_file << "TITLE = \"SU2_GEO Evaluation\"" << endl; if (geometry_container[ZONE_0]->GetnDim() == 2) { if (tabTecplot) ObjFunc_file << "VARIABLES =//" << endl; - ObjFunc_file << "\"AIRFOIL_AREA\",\"AIRFOIL_THICKNESS\",\"AIRFOIL_CHORD\",\"AIRFOIL_LE_RADIUS\",\"AIRFOIL_TOC\",\"AIRFOIL_ALPHA\""; - } - else if (geometry_container[ZONE_0]->GetnDim() == 3) { - + ObjFunc_file << "\"AIRFOIL_AREA\",\"AIRFOIL_THICKNESS\",\"AIRFOIL_CHORD\",\"AIRFOIL_LE_RADIUS\",\"AIRFOIL_TOC\"," + "\"AIRFOIL_ALPHA\""; + } else if (geometry_container[ZONE_0]->GetnDim() == 3) { if (tabTecplot) ObjFunc_file << "VARIABLES = //" << endl; if (config_container[ZONE_0]->GetGeo_Description() == FUSELAGE) { - ObjFunc_file << "\"FUSELAGE_VOLUME\",\"FUSELAGE_WETTED_AREA\",\"FUSELAGE_MIN_WIDTH\",\"FUSELAGE_MAX_WIDTH\",\"FUSELAGE_MIN_WATERLINE_WIDTH\",\"FUSELAGE_MAX_WATERLINE_WIDTH\",\"FUSELAGE_MIN_HEIGHT\",\"FUSELAGE_MAX_HEIGHT\",\"FUSELAGE_MAX_CURVATURE\","; - for (iPlane = 0; iPlane < nPlane; iPlane++) ObjFunc_file << "\"STATION"<< (iPlane+1) << "_AREA\","; - for (iPlane = 0; iPlane < nPlane; iPlane++) ObjFunc_file << "\"STATION"<< (iPlane+1) << "_LENGTH\","; - for (iPlane = 0; iPlane < nPlane; iPlane++) ObjFunc_file << "\"STATION"<< (iPlane+1) << "_WIDTH\","; - for (iPlane = 0; iPlane < nPlane; iPlane++) ObjFunc_file << "\"STATION"<< (iPlane+1) << "_WATERLINE_WIDTH\","; + ObjFunc_file << "\"FUSELAGE_VOLUME\",\"FUSELAGE_WETTED_AREA\",\"FUSELAGE_MIN_WIDTH\",\"FUSELAGE_MAX_WIDTH\"," + "\"FUSELAGE_MIN_WATERLINE_WIDTH\",\"FUSELAGE_MAX_WATERLINE_WIDTH\",\"FUSELAGE_MIN_HEIGHT\"," + "\"FUSELAGE_MAX_HEIGHT\",\"FUSELAGE_MAX_CURVATURE\","; + for (iPlane = 0; iPlane < nPlane; iPlane++) ObjFunc_file << "\"STATION" << (iPlane + 1) << "_AREA\","; + for (iPlane = 0; iPlane < nPlane; iPlane++) ObjFunc_file << "\"STATION" << (iPlane + 1) << "_LENGTH\","; + for (iPlane = 0; iPlane < nPlane; iPlane++) ObjFunc_file << "\"STATION" << (iPlane + 1) << "_WIDTH\","; + for (iPlane = 0; iPlane < nPlane; iPlane++) + ObjFunc_file << "\"STATION" << (iPlane + 1) << "_WATERLINE_WIDTH\","; for (iPlane = 0; iPlane < nPlane; iPlane++) { - ObjFunc_file << "\"STATION" << (iPlane+1) << "_HEIGHT\""; - if (iPlane != nPlane-1) ObjFunc_file << ","; + ObjFunc_file << "\"STATION" << (iPlane + 1) << "_HEIGHT\""; + if (iPlane != nPlane - 1) ObjFunc_file << ","; } - } - else if (config_container[ZONE_0]->GetGeo_Description() == NACELLE) { - ObjFunc_file << "\"NACELLE_VOLUME\",\"NACELLE_MIN_THICKNESS\",\"NACELLE_MAX_THICKNESS\",\"NACELLE_MIN_CHORD\",\"NACELLE_MAX_CHORD\",\"NACELLE_MIN_LE_RADIUS\",\"NACELLE_MAX_LE_RADIUS\",\"NACELLE_MIN_TOC\",\"NACELLE_MAX_TOC\",\"NACELLE_OBJFUN_MIN_TOC\",\"NACELLE_MAX_TWIST\","; - for (iPlane = 0; iPlane < nPlane; iPlane++) ObjFunc_file << "\"STATION"<< (iPlane+1) << "_AREA\","; - for (iPlane = 0; iPlane < nPlane; iPlane++) ObjFunc_file << "\"STATION"<< (iPlane+1) << "_THICKNESS\","; - for (iPlane = 0; iPlane < nPlane; iPlane++) ObjFunc_file << "\"STATION"<< (iPlane+1) << "_CHORD\","; - for (iPlane = 0; iPlane < nPlane; iPlane++) ObjFunc_file << "\"STATION"<< (iPlane+1) << "_LE_RADIUS\","; - for (iPlane = 0; iPlane < nPlane; iPlane++) ObjFunc_file << "\"STATION"<< (iPlane+1) << "_TOC\","; + } else if (config_container[ZONE_0]->GetGeo_Description() == NACELLE) { + ObjFunc_file << "\"NACELLE_VOLUME\",\"NACELLE_MIN_THICKNESS\",\"NACELLE_MAX_THICKNESS\",\"NACELLE_MIN_CHORD\"," + "\"NACELLE_MAX_CHORD\",\"NACELLE_MIN_LE_RADIUS\",\"NACELLE_MAX_LE_RADIUS\",\"NACELLE_MIN_TOC\"," + "\"NACELLE_MAX_TOC\",\"NACELLE_OBJFUN_MIN_TOC\",\"NACELLE_MAX_TWIST\","; + for (iPlane = 0; iPlane < nPlane; iPlane++) ObjFunc_file << "\"STATION" << (iPlane + 1) << "_AREA\","; + for (iPlane = 0; iPlane < nPlane; iPlane++) ObjFunc_file << "\"STATION" << (iPlane + 1) << "_THICKNESS\","; + for (iPlane = 0; iPlane < nPlane; iPlane++) ObjFunc_file << "\"STATION" << (iPlane + 1) << "_CHORD\","; + for (iPlane = 0; iPlane < nPlane; iPlane++) ObjFunc_file << "\"STATION" << (iPlane + 1) << "_LE_RADIUS\","; + for (iPlane = 0; iPlane < nPlane; iPlane++) ObjFunc_file << "\"STATION" << (iPlane + 1) << "_TOC\","; for (iPlane = 0; iPlane < nPlane; iPlane++) { - ObjFunc_file << "\"STATION" << (iPlane+1) << "_TWIST\""; - if (iPlane != nPlane-1) ObjFunc_file << ","; + ObjFunc_file << "\"STATION" << (iPlane + 1) << "_TWIST\""; + if (iPlane != nPlane - 1) ObjFunc_file << ","; } - } - else { - ObjFunc_file << "\"WING_VOLUME\",\"WING_MIN_THICKNESS\",\"WING_MAX_THICKNESS\",\"WING_MIN_CHORD\",\"WING_MAX_CHORD\",\"WING_MIN_LE_RADIUS\",\"WING_MAX_LE_RADIUS\",\"WING_MIN_TOC\",\"WING_MAX_TOC\",\"WING_OBJFUN_MIN_TOC\",\"WING_MAX_TWIST\",\"WING_MAX_CURVATURE\",\"WING_MAX_DIHEDRAL\","; - for (iPlane = 0; iPlane < nPlane; iPlane++) ObjFunc_file << "\"STATION"<< (iPlane+1) << "_AREA\","; - for (iPlane = 0; iPlane < nPlane; iPlane++) ObjFunc_file << "\"STATION"<< (iPlane+1) << "_THICKNESS\","; - for (iPlane = 0; iPlane < nPlane; iPlane++) ObjFunc_file << "\"STATION"<< (iPlane+1) << "_CHORD\","; - for (iPlane = 0; iPlane < nPlane; iPlane++) ObjFunc_file << "\"STATION"<< (iPlane+1) << "_LE_RADIUS\","; - for (iPlane = 0; iPlane < nPlane; iPlane++) ObjFunc_file << "\"STATION"<< (iPlane+1) << "_TOC\","; + } else { + ObjFunc_file << "\"WING_VOLUME\",\"WING_MIN_THICKNESS\",\"WING_MAX_THICKNESS\",\"WING_MIN_CHORD\",\"WING_MAX_" + "CHORD\",\"WING_MIN_LE_RADIUS\",\"WING_MAX_LE_RADIUS\",\"WING_MIN_TOC\",\"WING_MAX_TOC\"," + "\"WING_OBJFUN_MIN_TOC\",\"WING_MAX_TWIST\",\"WING_MAX_CURVATURE\",\"WING_MAX_DIHEDRAL\","; + for (iPlane = 0; iPlane < nPlane; iPlane++) ObjFunc_file << "\"STATION" << (iPlane + 1) << "_AREA\","; + for (iPlane = 0; iPlane < nPlane; iPlane++) ObjFunc_file << "\"STATION" << (iPlane + 1) << "_THICKNESS\","; + for (iPlane = 0; iPlane < nPlane; iPlane++) ObjFunc_file << "\"STATION" << (iPlane + 1) << "_CHORD\","; + for (iPlane = 0; iPlane < nPlane; iPlane++) ObjFunc_file << "\"STATION" << (iPlane + 1) << "_LE_RADIUS\","; + for (iPlane = 0; iPlane < nPlane; iPlane++) ObjFunc_file << "\"STATION" << (iPlane + 1) << "_TOC\","; for (iPlane = 0; iPlane < nPlane; iPlane++) { - ObjFunc_file << "\"STATION" << (iPlane+1) << "_TWIST\""; - if (iPlane != nPlane-1) ObjFunc_file << ","; + ObjFunc_file << "\"STATION" << (iPlane + 1) << "_TWIST\""; + if (iPlane != nPlane - 1) ObjFunc_file << ","; } } - } - if (tabTecplot) ObjFunc_file << "\nZONE T= \"Geometrical variables (value)\"" << endl; - else ObjFunc_file << endl; + if (tabTecplot) + ObjFunc_file << "\nZONE T= \"Geometrical variables (value)\"" << endl; + else + ObjFunc_file << endl; if (config_container[ZONE_0]->GetGeo_Description() == FUSELAGE) { if (geometry_container[ZONE_0]->GetnDim() == 3) { - ObjFunc_file << Fuselage_Volume <<", "<< Fuselage_WettedArea <<", "<< Fuselage_MinWidth <<", "<< Fuselage_MaxWidth <<", "<< Fuselage_MinWaterLineWidth <<", "<< Fuselage_MaxWaterLineWidth<<", "<< Fuselage_MinHeight <<", "<< Fuselage_MaxHeight <<", "<< Fuselage_MaxCurvature <<", "; + ObjFunc_file << Fuselage_Volume << ", " << Fuselage_WettedArea << ", " << Fuselage_MinWidth << ", " + << Fuselage_MaxWidth << ", " << Fuselage_MinWaterLineWidth << ", " << Fuselage_MaxWaterLineWidth + << ", " << Fuselage_MinHeight << ", " << Fuselage_MaxHeight << ", " << Fuselage_MaxCurvature + << ", "; } - for (iPlane = 0; iPlane < nPlane*5; iPlane++) { + for (iPlane = 0; iPlane < nPlane * 5; iPlane++) { ObjFunc_file << ObjectiveFunc[iPlane]; - if (iPlane != (nPlane*5)-1) ObjFunc_file <<", "; + if (iPlane != (nPlane * 5) - 1) ObjFunc_file << ", "; } - } - else if (config_container[ZONE_0]->GetGeo_Description() == NACELLE) { + } else if (config_container[ZONE_0]->GetGeo_Description() == NACELLE) { if (geometry_container[ZONE_0]->GetnDim() == 3) { - ObjFunc_file << Nacelle_Volume <<", "<< Nacelle_MinThickness <<", "<< Nacelle_MaxThickness <<", "<< Nacelle_MinChord <<", "<< Nacelle_MaxChord <<", "<< Nacelle_MinLERadius <<", "<< Nacelle_MaxLERadius<<", "<< Nacelle_MinToC <<", "<< Nacelle_MaxToC <<", "<< Nacelle_ObjFun_MinToC <<", "<< Nacelle_MaxTwist <<", "; + ObjFunc_file << Nacelle_Volume << ", " << Nacelle_MinThickness << ", " << Nacelle_MaxThickness << ", " + << Nacelle_MinChord << ", " << Nacelle_MaxChord << ", " << Nacelle_MinLERadius << ", " + << Nacelle_MaxLERadius << ", " << Nacelle_MinToC << ", " << Nacelle_MaxToC << ", " + << Nacelle_ObjFun_MinToC << ", " << Nacelle_MaxTwist << ", "; } - for (iPlane = 0; iPlane < nPlane*6; iPlane++) { + for (iPlane = 0; iPlane < nPlane * 6; iPlane++) { ObjFunc_file << ObjectiveFunc[iPlane]; - if (iPlane != (nPlane*6)-1) ObjFunc_file <<", "; + if (iPlane != (nPlane * 6) - 1) ObjFunc_file << ", "; } - } - else { + } else { if (geometry_container[ZONE_0]->GetnDim() == 3) { - ObjFunc_file << Wing_Volume <<", "<< Wing_MinThickness <<", "<< Wing_MaxThickness <<", "<< Wing_MinChord <<", "<< Wing_MaxChord <<", "<< Wing_MinLERadius <<", "<< Wing_MaxLERadius<<", "<< Wing_MinToC <<", "<< Wing_MaxToC <<", "<< Wing_ObjFun_MinToC <<", "<< Wing_MaxTwist <<", "<< Wing_MaxCurvature <<", "<< Wing_MaxDihedral <<", "; + ObjFunc_file << Wing_Volume << ", " << Wing_MinThickness << ", " << Wing_MaxThickness << ", " << Wing_MinChord + << ", " << Wing_MaxChord << ", " << Wing_MinLERadius << ", " << Wing_MaxLERadius << ", " + << Wing_MinToC << ", " << Wing_MaxToC << ", " << Wing_ObjFun_MinToC << ", " << Wing_MaxTwist + << ", " << Wing_MaxCurvature << ", " << Wing_MaxDihedral << ", "; } - for (iPlane = 0; iPlane < nPlane*6; iPlane++) { + for (iPlane = 0; iPlane < nPlane * 6; iPlane++) { ObjFunc_file << ObjectiveFunc[iPlane]; - if (iPlane != (nPlane*6)-1) ObjFunc_file <<", "; + if (iPlane != (nPlane * 6) - 1) ObjFunc_file << ", "; } } ObjFunc_file.close(); - } if (config_container[ZONE_0]->GetGeometryMode() == GRADIENT) { - /*--- Definition of the Class for surface deformation ---*/ surface_movement = new CSurfaceMovement(); @@ -595,13 +732,14 @@ int main(int argc, char *argv[]) { string filename = config_container[ZONE_0]->GetObjFunc_Grad_FileName(); unsigned short lastindex = filename.find_last_of("."); filename = filename.substr(0, lastindex); - if (tabTecplot) filename += ".dat"; - else filename += ".csv"; + if (tabTecplot) + filename += ".dat"; + else + filename += ".csv"; Gradient_file.open(filename.c_str(), ios::out); } for (iDV = 0; iDV < config_container[ZONE_0]->GetnDV(); iDV++) { - /*--- Free Form deformation based ---*/ if ((config_container[ZONE_0]->GetDesign_Variable(iDV) == FFD_CONTROL_POINT_2D) || @@ -614,17 +752,16 @@ int main(int argc, char *argv[]) { (config_container[ZONE_0]->GetDesign_Variable(iDV) == FFD_TWIST) || (config_container[ZONE_0]->GetDesign_Variable(iDV) == FFD_ROTATION) || (config_container[ZONE_0]->GetDesign_Variable(iDV) == FFD_CAMBER) || - (config_container[ZONE_0]->GetDesign_Variable(iDV) == FFD_THICKNESS) ) { - + (config_container[ZONE_0]->GetDesign_Variable(iDV) == FFD_THICKNESS)) { /*--- Read the FFD information in the first iteration ---*/ if (iDV == 0) { - if (rank == MASTER_NODE) cout << "Read the FFD information from mesh file." << endl; /*--- Read the FFD information from the grid file ---*/ - surface_movement->ReadFFDInfo(geometry_container[ZONE_0], config_container[ZONE_0], FFDBox, config_container[ZONE_0]->GetMesh_FileName()); + surface_movement->ReadFFDInfo(geometry_container[ZONE_0], config_container[ZONE_0], FFDBox, + config_container[ZONE_0]->GetMesh_FileName()); /*--- Modify the control points for polar based computations ---*/ @@ -632,13 +769,11 @@ int main(int argc, char *argv[]) { for (iFFDBox = 0; iFFDBox < surface_movement->GetnFFDBox(); iFFDBox++) { FFDBox[iFFDBox]->SetCart2Cyl_ControlPoints(config_container[ZONE_0]); } - } - else if (config_container[ZONE_0]->GetFFD_CoordSystem() == SPHERICAL) { + } else if (config_container[ZONE_0]->GetFFD_CoordSystem() == SPHERICAL) { for (iFFDBox = 0; iFFDBox < surface_movement->GetnFFDBox(); iFFDBox++) { FFDBox[iFFDBox]->SetCart2Sphe_ControlPoints(config_container[ZONE_0]); } - } - else if (config_container[ZONE_0]->GetFFD_CoordSystem() == POLAR) { + } else if (config_container[ZONE_0]->GetFFD_CoordSystem() == POLAR) { for (iFFDBox = 0; iFFDBox < surface_movement->GetnFFDBox(); iFFDBox++) { FFDBox[iFFDBox]->SetCart2Sphe_ControlPoints(config_container[ZONE_0]); } @@ -651,23 +786,21 @@ int main(int argc, char *argv[]) { } for (iFFDBox = 0; iFFDBox < surface_movement->GetnFFDBox(); iFFDBox++) { - if (rank == MASTER_NODE) cout << "Checking FFD box dimension." << endl; - surface_movement->CheckFFDDimension(geometry_container[ZONE_0], config_container[ZONE_0], FFDBox[iFFDBox], iFFDBox); - + surface_movement->CheckFFDDimension(geometry_container[ZONE_0], config_container[ZONE_0], FFDBox[iFFDBox], + iFFDBox); if (rank == MASTER_NODE) cout << "Check the FFD box intersections with the solid surfaces." << endl; - surface_movement->CheckFFDIntersections(geometry_container[ZONE_0], config_container[ZONE_0], FFDBox[iFFDBox], iFFDBox); - + surface_movement->CheckFFDIntersections(geometry_container[ZONE_0], config_container[ZONE_0], + FFDBox[iFFDBox], iFFDBox); } if (rank == MASTER_NODE) - cout <<"-------------------------------------------------------------------------" << endl; - + cout << "-------------------------------------------------------------------------" << endl; } if (rank == MASTER_NODE) { - cout << endl << "Design variable number "<< iDV <<"." << endl; + cout << endl << "Design variable number " << iDV << "." << endl; cout << "Perform 3D deformation of the surface." << endl; } @@ -676,31 +809,66 @@ int main(int argc, char *argv[]) { MoveSurface = false; for (iFFDBox = 0; iFFDBox < surface_movement->GetnFFDBox(); iFFDBox++) { - Local_MoveSurface = false; - switch ( config_container[ZONE_0]->GetDesign_Variable(iDV) ) { - case FFD_CONTROL_POINT_2D : Local_MoveSurface = surface_movement->SetFFDCPChange_2D(geometry_container[ZONE_0], config_container[ZONE_0], FFDBox[iFFDBox], FFDBox, iDV, true); break; - case FFD_CAMBER_2D : Local_MoveSurface = surface_movement->SetFFDCamber_2D(geometry_container[ZONE_0], config_container[ZONE_0], FFDBox[iFFDBox], FFDBox, iDV, true); break; - case FFD_THICKNESS_2D : Local_MoveSurface = surface_movement->SetFFDThickness_2D(geometry_container[ZONE_0], config_container[ZONE_0], FFDBox[iFFDBox], FFDBox, iDV, true); break; - case FFD_TWIST_2D : Local_MoveSurface = surface_movement->SetFFDTwist_2D(geometry_container[ZONE_0], config_container[ZONE_0], FFDBox[iFFDBox], FFDBox, iDV, true); break; - case FFD_CONTROL_POINT : Local_MoveSurface = surface_movement->SetFFDCPChange(geometry_container[ZONE_0], config_container[ZONE_0], FFDBox[iFFDBox], FFDBox, iDV, true); break; - case FFD_NACELLE : Local_MoveSurface = surface_movement->SetFFDNacelle(geometry_container[ZONE_0], config_container[ZONE_0], FFDBox[iFFDBox], FFDBox, iDV, true); break; - case FFD_GULL : Local_MoveSurface = surface_movement->SetFFDGull(geometry_container[ZONE_0], config_container[ZONE_0], FFDBox[iFFDBox], FFDBox, iDV, true); break; - case FFD_TWIST : Local_MoveSurface = surface_movement->SetFFDTwist(geometry_container[ZONE_0], config_container[ZONE_0], FFDBox[iFFDBox], FFDBox, iDV, true); break; - case FFD_ROTATION : Local_MoveSurface = surface_movement->SetFFDRotation(geometry_container[ZONE_0], config_container[ZONE_0], FFDBox[iFFDBox], FFDBox, iDV, true); break; - case FFD_CAMBER : Local_MoveSurface = surface_movement->SetFFDCamber(geometry_container[ZONE_0], config_container[ZONE_0], FFDBox[iFFDBox], FFDBox, iDV, true); break; - case FFD_THICKNESS : Local_MoveSurface = surface_movement->SetFFDThickness(geometry_container[ZONE_0], config_container[ZONE_0], FFDBox[iFFDBox], FFDBox, iDV, true); break; - case FFD_CONTROL_SURFACE : Local_MoveSurface = surface_movement->SetFFDControl_Surface(geometry_container[ZONE_0], config_container[ZONE_0], FFDBox[iFFDBox], FFDBox, iDV, true); break; + switch (config_container[ZONE_0]->GetDesign_Variable(iDV)) { + case FFD_CONTROL_POINT_2D: + Local_MoveSurface = surface_movement->SetFFDCPChange_2D( + geometry_container[ZONE_0], config_container[ZONE_0], FFDBox[iFFDBox], FFDBox, iDV, true); + break; + case FFD_CAMBER_2D: + Local_MoveSurface = surface_movement->SetFFDCamber_2D( + geometry_container[ZONE_0], config_container[ZONE_0], FFDBox[iFFDBox], FFDBox, iDV, true); + break; + case FFD_THICKNESS_2D: + Local_MoveSurface = surface_movement->SetFFDThickness_2D( + geometry_container[ZONE_0], config_container[ZONE_0], FFDBox[iFFDBox], FFDBox, iDV, true); + break; + case FFD_TWIST_2D: + Local_MoveSurface = surface_movement->SetFFDTwist_2D(geometry_container[ZONE_0], config_container[ZONE_0], + FFDBox[iFFDBox], FFDBox, iDV, true); + break; + case FFD_CONTROL_POINT: + Local_MoveSurface = surface_movement->SetFFDCPChange(geometry_container[ZONE_0], config_container[ZONE_0], + FFDBox[iFFDBox], FFDBox, iDV, true); + break; + case FFD_NACELLE: + Local_MoveSurface = surface_movement->SetFFDNacelle(geometry_container[ZONE_0], config_container[ZONE_0], + FFDBox[iFFDBox], FFDBox, iDV, true); + break; + case FFD_GULL: + Local_MoveSurface = surface_movement->SetFFDGull(geometry_container[ZONE_0], config_container[ZONE_0], + FFDBox[iFFDBox], FFDBox, iDV, true); + break; + case FFD_TWIST: + Local_MoveSurface = surface_movement->SetFFDTwist(geometry_container[ZONE_0], config_container[ZONE_0], + FFDBox[iFFDBox], FFDBox, iDV, true); + break; + case FFD_ROTATION: + Local_MoveSurface = surface_movement->SetFFDRotation(geometry_container[ZONE_0], config_container[ZONE_0], + FFDBox[iFFDBox], FFDBox, iDV, true); + break; + case FFD_CAMBER: + Local_MoveSurface = surface_movement->SetFFDCamber(geometry_container[ZONE_0], config_container[ZONE_0], + FFDBox[iFFDBox], FFDBox, iDV, true); + break; + case FFD_THICKNESS: + Local_MoveSurface = surface_movement->SetFFDThickness( + geometry_container[ZONE_0], config_container[ZONE_0], FFDBox[iFFDBox], FFDBox, iDV, true); + break; + case FFD_CONTROL_SURFACE: + Local_MoveSurface = surface_movement->SetFFDControl_Surface( + geometry_container[ZONE_0], config_container[ZONE_0], FFDBox[iFFDBox], FFDBox, iDV, true); + break; } /*--- Recompute cartesian coordinates using the new control points position ---*/ if (Local_MoveSurface) { MoveSurface = true; - surface_movement->SetCartesianCoord(geometry_container[ZONE_0], config_container[ZONE_0], FFDBox[iFFDBox], iFFDBox, true); + surface_movement->SetCartesianCoord(geometry_container[ZONE_0], config_container[ZONE_0], FFDBox[iFFDBox], + iFFDBox, true); } - } } @@ -709,7 +877,7 @@ int main(int argc, char *argv[]) { else if (config_container[ZONE_0]->GetDesign_Variable(iDV) == HICKS_HENNE) { if (rank == MASTER_NODE) { - cout << endl << "Design variable number "<< iDV <<"." << endl; + cout << endl << "Design variable number " << iDV << "." << endl; cout << "Perform 2D deformation of the surface." << endl; } MoveSurface = true; @@ -720,7 +888,7 @@ int main(int argc, char *argv[]) { else if (config_container[ZONE_0]->GetDesign_Variable(iDV) == SURFACE_BUMP) { if (rank == MASTER_NODE) { - cout << endl << "Design variable number "<< iDV <<"." << endl; + cout << endl << "Design variable number " << iDV << "." << endl; cout << "Perform 2D deformation of the surface." << endl; } MoveSurface = true; @@ -731,7 +899,7 @@ int main(int argc, char *argv[]) { else if (config_container[ZONE_0]->GetDesign_Variable(iDV) == CST) { if (rank == MASTER_NODE) { - cout << endl << "Design variable number "<< iDV <<"." << endl; + cout << endl << "Design variable number " << iDV << "." << endl; cout << "Perform 2D deformation of the surface." << endl; } MoveSurface = true; @@ -742,7 +910,7 @@ int main(int argc, char *argv[]) { else if (config_container[ZONE_0]->GetDesign_Variable(iDV) == TRANSLATION) { if (rank == MASTER_NODE) { - cout << endl << "Design variable number "<< iDV <<"." << endl; + cout << endl << "Design variable number " << iDV << "." << endl; cout << "Perform 2D deformation of the surface." << endl; } MoveSurface = true; @@ -753,7 +921,7 @@ int main(int argc, char *argv[]) { else if (config_container[ZONE_0]->GetDesign_Variable(iDV) == SCALE) { if (rank == MASTER_NODE) { - cout << endl << "Design variable number "<< iDV <<"." << endl; + cout << endl << "Design variable number " << iDV << "." << endl; cout << "Perform 2D deformation of the surface." << endl; } MoveSurface = true; @@ -764,7 +932,7 @@ int main(int argc, char *argv[]) { else if (config_container[ZONE_0]->GetDesign_Variable(iDV) == ROTATION) { if (rank == MASTER_NODE) { - cout << endl << "Design variable number "<< iDV <<"." << endl; + cout << endl << "Design variable number " << iDV << "." << endl; cout << "Perform 2D deformation of the surface." << endl; } MoveSurface = true; @@ -775,7 +943,7 @@ int main(int argc, char *argv[]) { else if (config_container[ZONE_0]->GetDesign_Variable(iDV) == NACA_4DIGITS) { if (rank == MASTER_NODE) { - cout << endl << "Design variable number "<< iDV <<"." << endl; + cout << endl << "Design variable number " << iDV << "." << endl; cout << "Perform 2D deformation of the surface." << endl; } MoveSurface = true; @@ -786,7 +954,7 @@ int main(int argc, char *argv[]) { else if (config_container[ZONE_0]->GetDesign_Variable(iDV) == PARABOLIC) { if (rank == MASTER_NODE) { - cout << endl << "Design variable number "<< iDV <<"." << endl; + cout << endl << "Design variable number " << iDV << "." << endl; cout << "Perform 2D deformation of the surface." << endl; } MoveSurface = true; @@ -796,53 +964,46 @@ int main(int argc, char *argv[]) { /*--- Design variable not implement ---*/ else { - if (rank == MASTER_NODE) - cout << "Design Variable not implemented yet" << endl; + if (rank == MASTER_NODE) cout << "Design Variable not implemented yet" << endl; } if (MoveSurface) { - /*--- Compute the gradient for the volume. In 2D this is just the gradient of the area. ---*/ if (geometry_container[ZONE_0]->GetnDim() == 3) { - if (config_container[ZONE_0]->GetGeo_Description() == FUSELAGE) { - geometry_container[ZONE_0]->Compute_Fuselage(config_container[ZONE_0], false, - Fuselage_Volume_New, Fuselage_WettedArea_New, Fuselage_MinWidth_New, Fuselage_MaxWidth_New, - Fuselage_MinWaterLineWidth_New, Fuselage_MaxWaterLineWidth_New, - Fuselage_MinHeight_New, Fuselage_MaxHeight_New, - Fuselage_MaxCurvature_New); - } - else if (config_container[ZONE_0]->GetGeo_Description() == NACELLE) { - geometry_container[ZONE_0]->Compute_Nacelle(config_container[ZONE_0], false, - Nacelle_Volume_New, Nacelle_MinThickness_New, Nacelle_MaxThickness_New, Nacelle_MinChord_New, - Nacelle_MaxChord_New, Nacelle_MinLERadius_New, Nacelle_MaxLERadius_New, Nacelle_MinToC_New, - Nacelle_MaxToC_New, Nacelle_ObjFun_MinToC_New, Nacelle_MaxTwist_New); - } - else { - geometry_container[ZONE_0]->Compute_Wing(config_container[ZONE_0], false, - Wing_Volume_New, Wing_MinThickness_New, Wing_MaxThickness_New, Wing_MinChord_New, - Wing_MaxChord_New, Wing_MinLERadius_New, Wing_MaxLERadius_New, Wing_MinToC_New, Wing_MaxToC_New, - Wing_ObjFun_MinToC_New, Wing_MaxTwist_New, Wing_MaxCurvature_New, Wing_MaxDihedral_New); + geometry_container[ZONE_0]->Compute_Fuselage( + config_container[ZONE_0], false, Fuselage_Volume_New, Fuselage_WettedArea_New, Fuselage_MinWidth_New, + Fuselage_MaxWidth_New, Fuselage_MinWaterLineWidth_New, Fuselage_MaxWaterLineWidth_New, + Fuselage_MinHeight_New, Fuselage_MaxHeight_New, Fuselage_MaxCurvature_New); + } else if (config_container[ZONE_0]->GetGeo_Description() == NACELLE) { + geometry_container[ZONE_0]->Compute_Nacelle( + config_container[ZONE_0], false, Nacelle_Volume_New, Nacelle_MinThickness_New, Nacelle_MaxThickness_New, + Nacelle_MinChord_New, Nacelle_MaxChord_New, Nacelle_MinLERadius_New, Nacelle_MaxLERadius_New, + Nacelle_MinToC_New, Nacelle_MaxToC_New, Nacelle_ObjFun_MinToC_New, Nacelle_MaxTwist_New); + } else { + geometry_container[ZONE_0]->Compute_Wing(config_container[ZONE_0], false, Wing_Volume_New, + Wing_MinThickness_New, Wing_MaxThickness_New, Wing_MinChord_New, + Wing_MaxChord_New, Wing_MinLERadius_New, Wing_MaxLERadius_New, + Wing_MinToC_New, Wing_MaxToC_New, Wing_ObjFun_MinToC_New, + Wing_MaxTwist_New, Wing_MaxCurvature_New, Wing_MaxDihedral_New); } - } /*--- Create airfoil structure ---*/ for (iPlane = 0; iPlane < nPlane; iPlane++) { - geometry_container[ZONE_0]->ComputeAirfoil_Section(Plane_P0[iPlane], Plane_Normal[iPlane], -1E6, 1E6, -1E6, 1E6, -1E6, 1E6, nullptr, - Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane], + geometry_container[ZONE_0]->ComputeAirfoil_Section(Plane_P0[iPlane], Plane_Normal[iPlane], -1E6, 1E6, -1E6, + 1E6, -1E6, 1E6, nullptr, Xcoord_Airfoil[iPlane], + Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane], Variable_Airfoil[iPlane], false, config_container[ZONE_0]); } - } /*--- Compute gradient ---*/ if (rank == MASTER_NODE) { - delta_eps = config_container[ZONE_0]->GetDV_Value(iDV); if (delta_eps == 0) { @@ -850,7 +1011,6 @@ int main(int argc, char *argv[]) { } if (MoveSurface) { - if (config_container[ZONE_0]->GetGeo_Description() == FUSELAGE) { Fuselage_Volume_Grad = (Fuselage_Volume_New - Fuselage_Volume) / delta_eps; Fuselage_WettedArea_Grad = (Fuselage_WettedArea_New - Fuselage_WettedArea) / delta_eps; @@ -862,8 +1022,7 @@ int main(int argc, char *argv[]) { Fuselage_MaxHeight_Grad = (Fuselage_MaxHeight_New - Fuselage_MaxHeight) / delta_eps; Fuselage_MaxCurvature_Grad = (Fuselage_MaxCurvature_New - Fuselage_MaxCurvature) / delta_eps; - } - else if (config_container[ZONE_0]->GetGeo_Description() == NACELLE) { + } else if (config_container[ZONE_0]->GetGeo_Description() == NACELLE) { Nacelle_Volume_Grad = (Nacelle_Volume_New - Nacelle_Volume) / delta_eps; Nacelle_MinThickness_Grad = (Nacelle_MinThickness_New - Nacelle_MinThickness) / delta_eps; Nacelle_MaxThickness_Grad = (Nacelle_MaxThickness_New - Nacelle_MaxThickness) / delta_eps; @@ -875,8 +1034,7 @@ int main(int argc, char *argv[]) { Nacelle_MaxToC_Grad = (Nacelle_MaxToC_New - Nacelle_MaxToC) / delta_eps; Nacelle_ObjFun_MinToC_Grad = (Nacelle_ObjFun_MinToC_New - Nacelle_ObjFun_MinToC) / delta_eps; Nacelle_MaxTwist_Grad = (Nacelle_MaxTwist_New - Nacelle_MaxTwist) / delta_eps; - } - else { + } else { Wing_Volume_Grad = (Wing_Volume_New - Wing_Volume) / delta_eps; Wing_MinThickness_Grad = (Wing_MinThickness_New - Wing_MinThickness) / delta_eps; Wing_MaxThickness_Grad = (Wing_MaxThickness_New - Wing_MaxThickness) / delta_eps; @@ -894,356 +1052,412 @@ int main(int argc, char *argv[]) { for (iPlane = 0; iPlane < nPlane; iPlane++) { if (Xcoord_Airfoil[iPlane].size() > 1) { - if (config_container[ZONE_0]->GetGeo_Description() == FUSELAGE) { - - ObjectiveFunc_New[0*nPlane + iPlane] = geometry_container[ZONE_0]->Compute_Area(Plane_P0[iPlane], Plane_Normal[iPlane], config_container[ZONE_0], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - Gradient[0*nPlane + iPlane] = (ObjectiveFunc_New[0*nPlane + iPlane] - ObjectiveFunc[0*nPlane + iPlane]) / delta_eps; - - ObjectiveFunc_New[1*nPlane + iPlane] = geometry_container[ZONE_0]->Compute_Length(Plane_P0[iPlane], Plane_Normal[iPlane], config_container[ZONE_0], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - Gradient[1*nPlane + iPlane] = (ObjectiveFunc_New[1*nPlane + iPlane] - ObjectiveFunc[1*nPlane + iPlane]) / delta_eps; - - ObjectiveFunc_New[2*nPlane + iPlane] = geometry_container[ZONE_0]->Compute_Width(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - Gradient[2*nPlane + iPlane] = (ObjectiveFunc_New[2*nPlane + iPlane] - ObjectiveFunc[2*nPlane + iPlane]) / delta_eps; - - ObjectiveFunc_New[3*nPlane + iPlane] = geometry_container[ZONE_0]->Compute_WaterLineWidth(Plane_P0[iPlane], Plane_Normal[iPlane], config_container[ZONE_0], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - Gradient[3*nPlane + iPlane] = (ObjectiveFunc_New[3*nPlane + iPlane] - ObjectiveFunc[3*nPlane + iPlane]) / delta_eps; - - ObjectiveFunc_New[4*nPlane + iPlane] = geometry_container[ZONE_0]->Compute_Height(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - Gradient[4*nPlane + iPlane] = (ObjectiveFunc_New[4*nPlane + iPlane] - ObjectiveFunc[4*nPlane + iPlane]) / delta_eps; + ObjectiveFunc_New[0 * nPlane + iPlane] = geometry_container[ZONE_0]->Compute_Area( + Plane_P0[iPlane], Plane_Normal[iPlane], config_container[ZONE_0], Xcoord_Airfoil[iPlane], + Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); + Gradient[0 * nPlane + iPlane] = + (ObjectiveFunc_New[0 * nPlane + iPlane] - ObjectiveFunc[0 * nPlane + iPlane]) / delta_eps; + + ObjectiveFunc_New[1 * nPlane + iPlane] = geometry_container[ZONE_0]->Compute_Length( + Plane_P0[iPlane], Plane_Normal[iPlane], config_container[ZONE_0], Xcoord_Airfoil[iPlane], + Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); + Gradient[1 * nPlane + iPlane] = + (ObjectiveFunc_New[1 * nPlane + iPlane] - ObjectiveFunc[1 * nPlane + iPlane]) / delta_eps; + + ObjectiveFunc_New[2 * nPlane + iPlane] = geometry_container[ZONE_0]->Compute_Width( + Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], + Zcoord_Airfoil[iPlane]); + Gradient[2 * nPlane + iPlane] = + (ObjectiveFunc_New[2 * nPlane + iPlane] - ObjectiveFunc[2 * nPlane + iPlane]) / delta_eps; + + ObjectiveFunc_New[3 * nPlane + iPlane] = geometry_container[ZONE_0]->Compute_WaterLineWidth( + Plane_P0[iPlane], Plane_Normal[iPlane], config_container[ZONE_0], Xcoord_Airfoil[iPlane], + Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); + Gradient[3 * nPlane + iPlane] = + (ObjectiveFunc_New[3 * nPlane + iPlane] - ObjectiveFunc[3 * nPlane + iPlane]) / delta_eps; + + ObjectiveFunc_New[4 * nPlane + iPlane] = geometry_container[ZONE_0]->Compute_Height( + Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], + Zcoord_Airfoil[iPlane]); + Gradient[4 * nPlane + iPlane] = + (ObjectiveFunc_New[4 * nPlane + iPlane] - ObjectiveFunc[4 * nPlane + iPlane]) / delta_eps; } else if (config_container[ZONE_0]->GetGeo_Description() == FUSELAGE) { - - ObjectiveFunc_New[0*nPlane + iPlane] = geometry_container[ZONE_0]->Compute_Area(Plane_P0[iPlane], Plane_Normal[iPlane], config_container[ZONE_0], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - Gradient[0*nPlane + iPlane] = (ObjectiveFunc_New[0*nPlane + iPlane] - ObjectiveFunc[0*nPlane + iPlane]) / delta_eps; - - ObjectiveFunc_New[1*nPlane + iPlane] = geometry_container[ZONE_0]->Compute_MaxThickness(Plane_P0[iPlane], Plane_Normal[iPlane], config_container[ZONE_0], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - Gradient[1*nPlane + iPlane] = (ObjectiveFunc_New[1*nPlane + iPlane] - ObjectiveFunc[1*nPlane + iPlane]) / delta_eps; - - ObjectiveFunc_New[2*nPlane + iPlane] = geometry_container[ZONE_0]->Compute_Chord(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - Gradient[2*nPlane + iPlane] = (ObjectiveFunc_New[2*nPlane + iPlane] - ObjectiveFunc[2*nPlane + iPlane]) / delta_eps; - - ObjectiveFunc_New[3*nPlane + iPlane] = geometry_container[ZONE_0]->Compute_LERadius(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - Gradient[3*nPlane + iPlane] = (ObjectiveFunc_New[3*nPlane + iPlane] - ObjectiveFunc[3*nPlane + iPlane]) / delta_eps; - - ObjectiveFunc_New[4*nPlane + iPlane] = ObjectiveFunc_New[1*nPlane + iPlane] / ObjectiveFunc_New[2*nPlane + iPlane]; - Gradient[4*nPlane + iPlane] = (ObjectiveFunc_New[4*nPlane + iPlane] - ObjectiveFunc[4*nPlane + iPlane]) / delta_eps; - - ObjectiveFunc_New[5*nPlane + iPlane] = geometry_container[ZONE_0]->Compute_Twist(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - Gradient[5*nPlane + iPlane] = (ObjectiveFunc_New[5*nPlane + iPlane] - ObjectiveFunc[5*nPlane + iPlane]) / delta_eps; + ObjectiveFunc_New[0 * nPlane + iPlane] = geometry_container[ZONE_0]->Compute_Area( + Plane_P0[iPlane], Plane_Normal[iPlane], config_container[ZONE_0], Xcoord_Airfoil[iPlane], + Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); + Gradient[0 * nPlane + iPlane] = + (ObjectiveFunc_New[0 * nPlane + iPlane] - ObjectiveFunc[0 * nPlane + iPlane]) / delta_eps; + + ObjectiveFunc_New[1 * nPlane + iPlane] = geometry_container[ZONE_0]->Compute_MaxThickness( + Plane_P0[iPlane], Plane_Normal[iPlane], config_container[ZONE_0], Xcoord_Airfoil[iPlane], + Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); + Gradient[1 * nPlane + iPlane] = + (ObjectiveFunc_New[1 * nPlane + iPlane] - ObjectiveFunc[1 * nPlane + iPlane]) / delta_eps; + + ObjectiveFunc_New[2 * nPlane + iPlane] = geometry_container[ZONE_0]->Compute_Chord( + Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], + Zcoord_Airfoil[iPlane]); + Gradient[2 * nPlane + iPlane] = + (ObjectiveFunc_New[2 * nPlane + iPlane] - ObjectiveFunc[2 * nPlane + iPlane]) / delta_eps; + + ObjectiveFunc_New[3 * nPlane + iPlane] = geometry_container[ZONE_0]->Compute_LERadius( + Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], + Zcoord_Airfoil[iPlane]); + Gradient[3 * nPlane + iPlane] = + (ObjectiveFunc_New[3 * nPlane + iPlane] - ObjectiveFunc[3 * nPlane + iPlane]) / delta_eps; + + ObjectiveFunc_New[4 * nPlane + iPlane] = + ObjectiveFunc_New[1 * nPlane + iPlane] / ObjectiveFunc_New[2 * nPlane + iPlane]; + Gradient[4 * nPlane + iPlane] = + (ObjectiveFunc_New[4 * nPlane + iPlane] - ObjectiveFunc[4 * nPlane + iPlane]) / delta_eps; + + ObjectiveFunc_New[5 * nPlane + iPlane] = geometry_container[ZONE_0]->Compute_Twist( + Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], + Zcoord_Airfoil[iPlane]); + Gradient[5 * nPlane + iPlane] = + (ObjectiveFunc_New[5 * nPlane + iPlane] - ObjectiveFunc[5 * nPlane + iPlane]) / delta_eps; } else { - - ObjectiveFunc_New[0*nPlane + iPlane] = geometry_container[ZONE_0]->Compute_Area(Plane_P0[iPlane], Plane_Normal[iPlane], config_container[ZONE_0], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - Gradient[0*nPlane + iPlane] = (ObjectiveFunc_New[0*nPlane + iPlane] - ObjectiveFunc[0*nPlane + iPlane]) / delta_eps; - - ObjectiveFunc_New[1*nPlane + iPlane] = geometry_container[ZONE_0]->Compute_MaxThickness(Plane_P0[iPlane], Plane_Normal[iPlane], config_container[ZONE_0], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - Gradient[1*nPlane + iPlane] = (ObjectiveFunc_New[1*nPlane + iPlane] - ObjectiveFunc[1*nPlane + iPlane]) / delta_eps; - - ObjectiveFunc_New[2*nPlane + iPlane] = geometry_container[ZONE_0]->Compute_Chord(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - Gradient[2*nPlane + iPlane] = (ObjectiveFunc_New[2*nPlane + iPlane] - ObjectiveFunc[2*nPlane + iPlane]) / delta_eps; - - ObjectiveFunc_New[3*nPlane + iPlane] = geometry_container[ZONE_0]->Compute_LERadius(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - Gradient[3*nPlane + iPlane] = (ObjectiveFunc_New[3*nPlane + iPlane] - ObjectiveFunc[3*nPlane + iPlane]) / delta_eps; - - ObjectiveFunc_New[4*nPlane + iPlane] = ObjectiveFunc_New[1*nPlane + iPlane] / ObjectiveFunc_New[2*nPlane + iPlane]; - Gradient[4*nPlane + iPlane] = (ObjectiveFunc_New[4*nPlane + iPlane] - ObjectiveFunc[4*nPlane + iPlane]) / delta_eps; - - ObjectiveFunc_New[5*nPlane + iPlane] = geometry_container[ZONE_0]->Compute_Twist(Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); - Gradient[5*nPlane + iPlane] = (ObjectiveFunc_New[5*nPlane + iPlane] - ObjectiveFunc[5*nPlane + iPlane]) / delta_eps; - + ObjectiveFunc_New[0 * nPlane + iPlane] = geometry_container[ZONE_0]->Compute_Area( + Plane_P0[iPlane], Plane_Normal[iPlane], config_container[ZONE_0], Xcoord_Airfoil[iPlane], + Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); + Gradient[0 * nPlane + iPlane] = + (ObjectiveFunc_New[0 * nPlane + iPlane] - ObjectiveFunc[0 * nPlane + iPlane]) / delta_eps; + + ObjectiveFunc_New[1 * nPlane + iPlane] = geometry_container[ZONE_0]->Compute_MaxThickness( + Plane_P0[iPlane], Plane_Normal[iPlane], config_container[ZONE_0], Xcoord_Airfoil[iPlane], + Ycoord_Airfoil[iPlane], Zcoord_Airfoil[iPlane]); + Gradient[1 * nPlane + iPlane] = + (ObjectiveFunc_New[1 * nPlane + iPlane] - ObjectiveFunc[1 * nPlane + iPlane]) / delta_eps; + + ObjectiveFunc_New[2 * nPlane + iPlane] = geometry_container[ZONE_0]->Compute_Chord( + Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], + Zcoord_Airfoil[iPlane]); + Gradient[2 * nPlane + iPlane] = + (ObjectiveFunc_New[2 * nPlane + iPlane] - ObjectiveFunc[2 * nPlane + iPlane]) / delta_eps; + + ObjectiveFunc_New[3 * nPlane + iPlane] = geometry_container[ZONE_0]->Compute_LERadius( + Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], + Zcoord_Airfoil[iPlane]); + Gradient[3 * nPlane + iPlane] = + (ObjectiveFunc_New[3 * nPlane + iPlane] - ObjectiveFunc[3 * nPlane + iPlane]) / delta_eps; + + ObjectiveFunc_New[4 * nPlane + iPlane] = + ObjectiveFunc_New[1 * nPlane + iPlane] / ObjectiveFunc_New[2 * nPlane + iPlane]; + Gradient[4 * nPlane + iPlane] = + (ObjectiveFunc_New[4 * nPlane + iPlane] - ObjectiveFunc[4 * nPlane + iPlane]) / delta_eps; + + ObjectiveFunc_New[5 * nPlane + iPlane] = geometry_container[ZONE_0]->Compute_Twist( + Plane_P0[iPlane], Plane_Normal[iPlane], Xcoord_Airfoil[iPlane], Ycoord_Airfoil[iPlane], + Zcoord_Airfoil[iPlane]); + Gradient[5 * nPlane + iPlane] = + (ObjectiveFunc_New[5 * nPlane + iPlane] - ObjectiveFunc[5 * nPlane + iPlane]) / delta_eps; } - } } } else { - if (config_container[ZONE_0]->GetGeo_Description() == FUSELAGE) { - Fuselage_Volume_Grad = 0.0; - Fuselage_WettedArea_Grad = 0.0; - Fuselage_MinWidth_Grad = 0.0; - Fuselage_MaxWidth_Grad = 0.0; + Fuselage_Volume_Grad = 0.0; + Fuselage_WettedArea_Grad = 0.0; + Fuselage_MinWidth_Grad = 0.0; + Fuselage_MaxWidth_Grad = 0.0; Fuselage_MinWaterLineWidth_Grad = 0.0; Fuselage_MaxWaterLineWidth_Grad = 0.0; - Fuselage_MinHeight_Grad = 0.0; - Fuselage_MaxHeight_Grad = 0.0; - Fuselage_MaxCurvature_Grad = 0.0; + Fuselage_MinHeight_Grad = 0.0; + Fuselage_MaxHeight_Grad = 0.0; + Fuselage_MaxCurvature_Grad = 0.0; for (iPlane = 0; iPlane < nPlane; iPlane++) { - Gradient[0*nPlane + iPlane] = 0.0; - Gradient[1*nPlane + iPlane] = 0.0; - Gradient[2*nPlane + iPlane] = 0.0; - Gradient[3*nPlane + iPlane] = 0.0; - Gradient[4*nPlane + iPlane] = 0.0; + Gradient[0 * nPlane + iPlane] = 0.0; + Gradient[1 * nPlane + iPlane] = 0.0; + Gradient[2 * nPlane + iPlane] = 0.0; + Gradient[3 * nPlane + iPlane] = 0.0; + Gradient[4 * nPlane + iPlane] = 0.0; } - } - else if (config_container[ZONE_0]->GetGeo_Description() == NACELLE) { - Nacelle_Volume_Grad = 0.0; - Nacelle_MinThickness_Grad = 0.0; - Nacelle_MaxThickness_Grad = 0.0; - Nacelle_MinChord_Grad = 0.0; - Nacelle_MaxChord_Grad = 0.0; - Nacelle_MinLERadius_Grad = 0.0; - Nacelle_MaxLERadius_Grad = 0.0; - Nacelle_MinToC_Grad = 0.0; - Nacelle_MaxToC_Grad = 0.0; - Nacelle_ObjFun_MinToC_Grad = 0.0; - Nacelle_MaxTwist_Grad = 0.0; + } else if (config_container[ZONE_0]->GetGeo_Description() == NACELLE) { + Nacelle_Volume_Grad = 0.0; + Nacelle_MinThickness_Grad = 0.0; + Nacelle_MaxThickness_Grad = 0.0; + Nacelle_MinChord_Grad = 0.0; + Nacelle_MaxChord_Grad = 0.0; + Nacelle_MinLERadius_Grad = 0.0; + Nacelle_MaxLERadius_Grad = 0.0; + Nacelle_MinToC_Grad = 0.0; + Nacelle_MaxToC_Grad = 0.0; + Nacelle_ObjFun_MinToC_Grad = 0.0; + Nacelle_MaxTwist_Grad = 0.0; for (iPlane = 0; iPlane < nPlane; iPlane++) { - Gradient[0*nPlane + iPlane] = 0.0; - Gradient[1*nPlane + iPlane] = 0.0; - Gradient[2*nPlane + iPlane] = 0.0; - Gradient[3*nPlane + iPlane] = 0.0; - Gradient[4*nPlane + iPlane] = 0.0; - Gradient[5*nPlane + iPlane] = 0.0; + Gradient[0 * nPlane + iPlane] = 0.0; + Gradient[1 * nPlane + iPlane] = 0.0; + Gradient[2 * nPlane + iPlane] = 0.0; + Gradient[3 * nPlane + iPlane] = 0.0; + Gradient[4 * nPlane + iPlane] = 0.0; + Gradient[5 * nPlane + iPlane] = 0.0; } - } - else { - Wing_Volume_Grad = 0.0; - Wing_MinThickness_Grad = 0.0; - Wing_MaxThickness_Grad = 0.0; - Wing_MinChord_Grad = 0.0; - Wing_MaxChord_Grad = 0.0; - Wing_MinLERadius_Grad = 0.0; - Wing_MaxLERadius_Grad = 0.0; - Wing_MinToC_Grad = 0.0; - Wing_MaxToC_Grad = 0.0; - Wing_ObjFun_MinToC_Grad = 0.0; - Wing_MaxTwist_Grad = 0.0; - Wing_MaxCurvature_Grad = 0.0; - Wing_MaxDihedral_Grad = 0.0; + } else { + Wing_Volume_Grad = 0.0; + Wing_MinThickness_Grad = 0.0; + Wing_MaxThickness_Grad = 0.0; + Wing_MinChord_Grad = 0.0; + Wing_MaxChord_Grad = 0.0; + Wing_MinLERadius_Grad = 0.0; + Wing_MaxLERadius_Grad = 0.0; + Wing_MinToC_Grad = 0.0; + Wing_MaxToC_Grad = 0.0; + Wing_ObjFun_MinToC_Grad = 0.0; + Wing_MaxTwist_Grad = 0.0; + Wing_MaxCurvature_Grad = 0.0; + Wing_MaxDihedral_Grad = 0.0; for (iPlane = 0; iPlane < nPlane; iPlane++) { - Gradient[0*nPlane + iPlane] = 0.0; - Gradient[1*nPlane + iPlane] = 0.0; - Gradient[2*nPlane + iPlane] = 0.0; - Gradient[3*nPlane + iPlane] = 0.0; - Gradient[4*nPlane + iPlane] = 0.0; - Gradient[5*nPlane + iPlane] = 0.0; + Gradient[0 * nPlane + iPlane] = 0.0; + Gradient[1 * nPlane + iPlane] = 0.0; + Gradient[2 * nPlane + iPlane] = 0.0; + Gradient[3 * nPlane + iPlane] = 0.0; + Gradient[4 * nPlane + iPlane] = 0.0; + Gradient[5 * nPlane + iPlane] = 0.0; } } - } /*--- Screen output ---*/ if (config_container[ZONE_0]->GetGeo_Description() == FUSELAGE) { if (geometry_container[ZONE_0]->GetnDim() == 3) { - cout << "\nFuselage volume grad.: " << Fuselage_Volume_Grad << ". "; - cout << "Fuselage wetted area grad.: " << Fuselage_WettedArea_Grad << ". "; - cout << "Fuselage min. width grad.: " << Fuselage_MinWidth_Grad << ". "; - cout << "Fuselage max. width grad.: " << Fuselage_MaxWidth_Grad << "." << endl; - cout << "Fuselage min. waterline width grad.: " << Fuselage_MinWaterLineWidth_Grad << ". "; - cout << "Fuselage max. waterline width grad.: " << Fuselage_MaxWaterLineWidth_Grad << "." << endl; + cout << "\nFuselage volume grad.: " << Fuselage_Volume_Grad << ". "; + cout << "Fuselage wetted area grad.: " << Fuselage_WettedArea_Grad << ". "; + cout << "Fuselage min. width grad.: " << Fuselage_MinWidth_Grad << ". "; + cout << "Fuselage max. width grad.: " << Fuselage_MaxWidth_Grad << "." << endl; + cout << "Fuselage min. waterline width grad.: " << Fuselage_MinWaterLineWidth_Grad << ". "; + cout << "Fuselage max. waterline width grad.: " << Fuselage_MaxWaterLineWidth_Grad << "." << endl; cout << "Fuselage min. height grad.: " << Fuselage_MinHeight_Grad << ". "; cout << "Fuselage max. height grad.: " << Fuselage_MaxHeight_Grad << ". "; - cout << "Fuselage max. curv. grad.: " << Fuselage_MaxCurvature_Grad << "."; + cout << "Fuselage max. curv. grad.: " << Fuselage_MaxCurvature_Grad << "."; } for (iPlane = 0; iPlane < nPlane; iPlane++) { if (Xcoord_Airfoil[iPlane].size() > 1) { - cout << "\nStation " << (iPlane+1) << ". XCoord: " << Plane_P0[iPlane][0] << ". "; - cout << "Area grad.: " << Gradient[0*nPlane + iPlane] << ". "; - cout << "Length grad.: " << Gradient[1*nPlane + iPlane] << ". "; - cout << "Width grad.: " << Gradient[2*nPlane + iPlane] << ". "; - cout << "Waterline width grad.: " << Gradient[3*nPlane + iPlane] << ". "; - cout << "Height grad.: " << Gradient[4*nPlane + iPlane] << ". "; + cout << "\nStation " << (iPlane + 1) << ". XCoord: " << Plane_P0[iPlane][0] << ". "; + cout << "Area grad.: " << Gradient[0 * nPlane + iPlane] << ". "; + cout << "Length grad.: " << Gradient[1 * nPlane + iPlane] << ". "; + cout << "Width grad.: " << Gradient[2 * nPlane + iPlane] << ". "; + cout << "Waterline width grad.: " << Gradient[3 * nPlane + iPlane] << ". "; + cout << "Height grad.: " << Gradient[4 * nPlane + iPlane] << ". "; } } - } - else if (config_container[ZONE_0]->GetGeo_Description() == NACELLE) { + } else if (config_container[ZONE_0]->GetGeo_Description() == NACELLE) { if (geometry_container[ZONE_0]->GetnDim() == 3) { - cout << "\nNacelle volume grad.: " << Nacelle_Volume_Grad << ". "; - cout << "Nacelle min. thickness grad.: " << Nacelle_MinThickness_Grad << ". "; - cout << "Nacelle max. thickness grad.: " << Nacelle_MaxThickness_Grad << ". "; - cout << "Nacelle min. chord grad.: " << Nacelle_MinChord_Grad << ". "; - cout << "Nacelle max. chord grad.: " << Nacelle_MaxChord_Grad << "." << endl; - cout << "Nacelle min. LE radius grad.: " << Nacelle_MinChord_Grad << ". "; - cout << "Nacelle max. LE radius grad.: " << Nacelle_MaxChord_Grad << ". "; - cout << "Nacelle min. ToC grad.: " << Nacelle_MinToC_Grad << ". "; - cout << "Nacelle max. ToC grad.: " << Nacelle_MaxToC_Grad << ". "; - cout << "Nacelle delta ToC grad.: " << Nacelle_ObjFun_MinToC_Grad << "." << endl; - cout << "Nacelle max. twist grad.: " << Nacelle_MaxTwist_Grad << ". "; + cout << "\nNacelle volume grad.: " << Nacelle_Volume_Grad << ". "; + cout << "Nacelle min. thickness grad.: " << Nacelle_MinThickness_Grad << ". "; + cout << "Nacelle max. thickness grad.: " << Nacelle_MaxThickness_Grad << ". "; + cout << "Nacelle min. chord grad.: " << Nacelle_MinChord_Grad << ". "; + cout << "Nacelle max. chord grad.: " << Nacelle_MaxChord_Grad << "." << endl; + cout << "Nacelle min. LE radius grad.: " << Nacelle_MinChord_Grad << ". "; + cout << "Nacelle max. LE radius grad.: " << Nacelle_MaxChord_Grad << ". "; + cout << "Nacelle min. ToC grad.: " << Nacelle_MinToC_Grad << ". "; + cout << "Nacelle max. ToC grad.: " << Nacelle_MaxToC_Grad << ". "; + cout << "Nacelle delta ToC grad.: " << Nacelle_ObjFun_MinToC_Grad << "." << endl; + cout << "Nacelle max. twist grad.: " << Nacelle_MaxTwist_Grad << ". "; } for (iPlane = 0; iPlane < nPlane; iPlane++) { if (Xcoord_Airfoil[iPlane].size() > 1) { - cout << "\nStation " << (iPlane+1) << ". YCoord: " << Plane_P0[iPlane][1] << ". "; - cout << "Area grad.: " << Gradient[0*nPlane + iPlane] << ". "; - cout << "Thickness grad.: " << Gradient[1*nPlane + iPlane] << ". "; - cout << "Chord grad.: " << Gradient[2*nPlane + iPlane] << ". "; - cout << "LE radius grad.: " << Gradient[3*nPlane + iPlane] << ". "; - cout << "ToC grad.: " << Gradient[4*nPlane + iPlane] << ". "; - cout << "Twist angle grad.: " << Gradient[5*nPlane + iPlane] << ". "; + cout << "\nStation " << (iPlane + 1) << ". YCoord: " << Plane_P0[iPlane][1] << ". "; + cout << "Area grad.: " << Gradient[0 * nPlane + iPlane] << ". "; + cout << "Thickness grad.: " << Gradient[1 * nPlane + iPlane] << ". "; + cout << "Chord grad.: " << Gradient[2 * nPlane + iPlane] << ". "; + cout << "LE radius grad.: " << Gradient[3 * nPlane + iPlane] << ". "; + cout << "ToC grad.: " << Gradient[4 * nPlane + iPlane] << ". "; + cout << "Twist angle grad.: " << Gradient[5 * nPlane + iPlane] << ". "; } } - } - else { + } else { if (geometry_container[ZONE_0]->GetnDim() == 3) { - cout << "\nWing volume grad.: " << Wing_Volume_Grad << ". "; - cout << "Wing min. thickness grad.: " << Wing_MinThickness_Grad << ". "; - cout << "Wing max. thickness grad.: " << Wing_MaxThickness_Grad << ". "; - cout << "Wing min. chord grad.: " << Wing_MinChord_Grad << ". "; - cout << "Wing max. chord grad.: " << Wing_MaxChord_Grad << "." << endl; - cout << "Wing min. LE radius grad.: " << Wing_MinChord_Grad << ". "; - cout << "Wing max. LE radius grad.: " << Wing_MaxChord_Grad << ". "; - cout << "Wing min. ToC grad.: " << Wing_MinToC_Grad << ". "; - cout << "Wing max. ToC grad.: " << Wing_MaxToC_Grad << ". "; - cout << "Wing delta ToC grad.: " << Wing_ObjFun_MinToC_Grad << "." << endl; - cout << "Wing max. twist grad.: " << Wing_MaxTwist_Grad << ". "; - cout << "Wing max. curv. grad.: " << Wing_MaxCurvature_Grad << ". "; - cout << "Wing max. dihedral grad.: " << Wing_MaxDihedral_Grad << "." << endl; + cout << "\nWing volume grad.: " << Wing_Volume_Grad << ". "; + cout << "Wing min. thickness grad.: " << Wing_MinThickness_Grad << ". "; + cout << "Wing max. thickness grad.: " << Wing_MaxThickness_Grad << ". "; + cout << "Wing min. chord grad.: " << Wing_MinChord_Grad << ". "; + cout << "Wing max. chord grad.: " << Wing_MaxChord_Grad << "." << endl; + cout << "Wing min. LE radius grad.: " << Wing_MinChord_Grad << ". "; + cout << "Wing max. LE radius grad.: " << Wing_MaxChord_Grad << ". "; + cout << "Wing min. ToC grad.: " << Wing_MinToC_Grad << ". "; + cout << "Wing max. ToC grad.: " << Wing_MaxToC_Grad << ". "; + cout << "Wing delta ToC grad.: " << Wing_ObjFun_MinToC_Grad << "." << endl; + cout << "Wing max. twist grad.: " << Wing_MaxTwist_Grad << ". "; + cout << "Wing max. curv. grad.: " << Wing_MaxCurvature_Grad << ". "; + cout << "Wing max. dihedral grad.: " << Wing_MaxDihedral_Grad << "." << endl; } for (iPlane = 0; iPlane < nPlane; iPlane++) { if (Xcoord_Airfoil[iPlane].size() > 1) { - cout << "\nStation " << (iPlane+1) << ". YCoord: " << Plane_P0[iPlane][1] << ". "; - cout << "Area grad.: " << Gradient[0*nPlane + iPlane] << ". "; - cout << "Thickness grad.: " << Gradient[1*nPlane + iPlane] << ". "; - cout << "Chord grad.: " << Gradient[2*nPlane + iPlane] << ". "; - cout << "LE radius grad.: " << Gradient[3*nPlane + iPlane] << ". "; - cout << "ToC grad.: " << Gradient[4*nPlane + iPlane] << ". "; - cout << "Twist angle grad.: " << Gradient[5*nPlane + iPlane] << ". "; + cout << "\nStation " << (iPlane + 1) << ". YCoord: " << Plane_P0[iPlane][1] << ". "; + cout << "Area grad.: " << Gradient[0 * nPlane + iPlane] << ". "; + cout << "Thickness grad.: " << Gradient[1 * nPlane + iPlane] << ". "; + cout << "Chord grad.: " << Gradient[2 * nPlane + iPlane] << ". "; + cout << "LE radius grad.: " << Gradient[3 * nPlane + iPlane] << ". "; + cout << "ToC grad.: " << Gradient[4 * nPlane + iPlane] << ". "; + cout << "Twist angle grad.: " << Gradient[5 * nPlane + iPlane] << ". "; } } } cout << endl; - if (iDV == 0) { if (tabTecplot) Gradient_file << "TITLE = \"SU2_GEO Gradient\"" << endl; if (tabTecplot) Gradient_file << "VARIABLES = //" << endl; if (geometry_container[ZONE_0]->GetnDim() == 2) { - Gradient_file << "\"DESIGN_VARIABLE\",\"AIRFOIL_AREA\",\"AIRFOIL_THICKNESS\",\"AIRFOIL_CHORD\",\"AIRFOIL_LE_RADIUS\",\"AIRFOIL_TOC\",\"AIRFOIL_ALPHA\""; - } - else if (geometry_container[ZONE_0]->GetnDim() == 3) { - + Gradient_file << "\"DESIGN_VARIABLE\",\"AIRFOIL_AREA\",\"AIRFOIL_THICKNESS\",\"AIRFOIL_CHORD\",\"AIRFOIL_" + "LE_RADIUS\",\"AIRFOIL_TOC\",\"AIRFOIL_ALPHA\""; + } else if (geometry_container[ZONE_0]->GetnDim() == 3) { if (config_container[ZONE_0]->GetGeo_Description() == FUSELAGE) { Gradient_file << "\"DESIGN_VARIABLE\","; - Gradient_file << "\"FUSELAGE_VOLUME\",\"FUSELAGE_WETTED_AREA\",\"FUSELAGE_MIN_WIDTH\",\"FUSELAGE_MAX_WIDTH\",\"FUSELAGE_MIN_WATERLINE_WIDTH\",\"FUSELAGE_MAX_WATERLINE_WIDTH\",\"FUSELAGE_MIN_HEIGHT\",\"FUSELAGE_MAX_HEIGHT\",\"FUSELAGE_MAX_CURVATURE\","; - for (iPlane = 0; iPlane < nPlane; iPlane++) Gradient_file << "\"STATION"<< (iPlane+1) << "_AREA\","; - for (iPlane = 0; iPlane < nPlane; iPlane++) Gradient_file << "\"STATION"<< (iPlane+1) << "_LENGTH\","; - for (iPlane = 0; iPlane < nPlane; iPlane++) Gradient_file << "\"STATION"<< (iPlane+1) << "_WIDTH\","; - for (iPlane = 0; iPlane < nPlane; iPlane++) Gradient_file << "\"STATION"<< (iPlane+1) << "_WATERLINE_WIDTH\","; + Gradient_file << "\"FUSELAGE_VOLUME\",\"FUSELAGE_WETTED_AREA\",\"FUSELAGE_MIN_WIDTH\",\"FUSELAGE_MAX_" + "WIDTH\",\"FUSELAGE_MIN_WATERLINE_WIDTH\",\"FUSELAGE_MAX_WATERLINE_WIDTH\",\"FUSELAGE_" + "MIN_HEIGHT\",\"FUSELAGE_MAX_HEIGHT\",\"FUSELAGE_MAX_CURVATURE\","; + for (iPlane = 0; iPlane < nPlane; iPlane++) Gradient_file << "\"STATION" << (iPlane + 1) << "_AREA\","; + for (iPlane = 0; iPlane < nPlane; iPlane++) Gradient_file << "\"STATION" << (iPlane + 1) << "_LENGTH\","; + for (iPlane = 0; iPlane < nPlane; iPlane++) Gradient_file << "\"STATION" << (iPlane + 1) << "_WIDTH\","; + for (iPlane = 0; iPlane < nPlane; iPlane++) + Gradient_file << "\"STATION" << (iPlane + 1) << "_WATERLINE_WIDTH\","; for (iPlane = 0; iPlane < nPlane; iPlane++) { - Gradient_file << "\"STATION"<< (iPlane+1) << "_HEIGHT\""; - if (iPlane != nPlane-1) Gradient_file << ","; + Gradient_file << "\"STATION" << (iPlane + 1) << "_HEIGHT\""; + if (iPlane != nPlane - 1) Gradient_file << ","; } - } - else if (config_container[ZONE_0]->GetGeo_Description() == NACELLE) { + } else if (config_container[ZONE_0]->GetGeo_Description() == NACELLE) { Gradient_file << "\"DESIGN_VARIABLE\","; - Gradient_file << "\"NACELLE_VOLUME\",\"NACELLE_MIN_THICKNESS\",\"NACELLE_MAX_THICKNESS\",\"NACELLE_MIN_CHORD\",\"NACELLE_MAX_CHORD\",\"NACELLE_MIN_LE_RADIUS\",\"NACELLE_MAX_LE_RADIUS\",\"NACELLE_MIN_TOC\",\"NACELLE_MAX_TOC\",\"NACELLE_OBJFUN_MIN_TOC\",\"NACELLE_MAX_TWIST\","; - for (iPlane = 0; iPlane < nPlane; iPlane++) Gradient_file << "\"STATION"<< (iPlane+1) << "_AREA\","; - for (iPlane = 0; iPlane < nPlane; iPlane++) Gradient_file << "\"STATION"<< (iPlane+1) << "_THICKNESS\","; - for (iPlane = 0; iPlane < nPlane; iPlane++) Gradient_file << "\"STATION"<< (iPlane+1) << "_CHORD\","; - for (iPlane = 0; iPlane < nPlane; iPlane++) Gradient_file << "\"STATION"<< (iPlane+1) << "_LE_RADIUS\","; - for (iPlane = 0; iPlane < nPlane; iPlane++) Gradient_file << "\"STATION"<< (iPlane+1) << "_TOC\","; + Gradient_file + << "\"NACELLE_VOLUME\",\"NACELLE_MIN_THICKNESS\",\"NACELLE_MAX_THICKNESS\",\"NACELLE_MIN_CHORD\"," + "\"NACELLE_MAX_CHORD\",\"NACELLE_MIN_LE_RADIUS\",\"NACELLE_MAX_LE_RADIUS\",\"NACELLE_MIN_TOC\"," + "\"NACELLE_MAX_TOC\",\"NACELLE_OBJFUN_MIN_TOC\",\"NACELLE_MAX_TWIST\","; + for (iPlane = 0; iPlane < nPlane; iPlane++) Gradient_file << "\"STATION" << (iPlane + 1) << "_AREA\","; + for (iPlane = 0; iPlane < nPlane; iPlane++) + Gradient_file << "\"STATION" << (iPlane + 1) << "_THICKNESS\","; + for (iPlane = 0; iPlane < nPlane; iPlane++) Gradient_file << "\"STATION" << (iPlane + 1) << "_CHORD\","; + for (iPlane = 0; iPlane < nPlane; iPlane++) + Gradient_file << "\"STATION" << (iPlane + 1) << "_LE_RADIUS\","; + for (iPlane = 0; iPlane < nPlane; iPlane++) Gradient_file << "\"STATION" << (iPlane + 1) << "_TOC\","; for (iPlane = 0; iPlane < nPlane; iPlane++) { - Gradient_file << "\"STATION"<< (iPlane+1) << "_TWIST\""; - if (iPlane != nPlane-1) Gradient_file << ","; + Gradient_file << "\"STATION" << (iPlane + 1) << "_TWIST\""; + if (iPlane != nPlane - 1) Gradient_file << ","; } - } - else { + } else { Gradient_file << "\"DESIGN_VARIABLE\","; - Gradient_file << "\"WING_VOLUME\",\"WING_MIN_THICKNESS\",\"WING_MAX_THICKNESS\",\"WING_MIN_CHORD\",\"WING_MAX_CHORD\",\"WING_MIN_LE_RADIUS\",\"WING_MAX_LE_RADIUS\",\"WING_MIN_TOC\",\"WING_MAX_TOC\",\"WING_OBJFUN_MIN_TOC\",\"WING_MAX_TWIST\",\"WING_MAX_CURVATURE\",\"WING_MAX_DIHEDRAL\","; - for (iPlane = 0; iPlane < nPlane; iPlane++) Gradient_file << "\"STATION"<< (iPlane+1) << "_AREA\","; - for (iPlane = 0; iPlane < nPlane; iPlane++) Gradient_file << "\"STATION"<< (iPlane+1) << "_THICKNESS\","; - for (iPlane = 0; iPlane < nPlane; iPlane++) Gradient_file << "\"STATION"<< (iPlane+1) << "_CHORD\","; - for (iPlane = 0; iPlane < nPlane; iPlane++) Gradient_file << "\"STATION"<< (iPlane+1) << "_LE_RADIUS\","; - for (iPlane = 0; iPlane < nPlane; iPlane++) Gradient_file << "\"STATION"<< (iPlane+1) << "_TOC\","; + Gradient_file + << "\"WING_VOLUME\",\"WING_MIN_THICKNESS\",\"WING_MAX_THICKNESS\",\"WING_MIN_CHORD\",\"WING_MAX_" + "CHORD\",\"WING_MIN_LE_RADIUS\",\"WING_MAX_LE_RADIUS\",\"WING_MIN_TOC\",\"WING_MAX_TOC\",\"WING_" + "OBJFUN_MIN_TOC\",\"WING_MAX_TWIST\",\"WING_MAX_CURVATURE\",\"WING_MAX_DIHEDRAL\","; + for (iPlane = 0; iPlane < nPlane; iPlane++) Gradient_file << "\"STATION" << (iPlane + 1) << "_AREA\","; + for (iPlane = 0; iPlane < nPlane; iPlane++) + Gradient_file << "\"STATION" << (iPlane + 1) << "_THICKNESS\","; + for (iPlane = 0; iPlane < nPlane; iPlane++) Gradient_file << "\"STATION" << (iPlane + 1) << "_CHORD\","; + for (iPlane = 0; iPlane < nPlane; iPlane++) + Gradient_file << "\"STATION" << (iPlane + 1) << "_LE_RADIUS\","; + for (iPlane = 0; iPlane < nPlane; iPlane++) Gradient_file << "\"STATION" << (iPlane + 1) << "_TOC\","; for (iPlane = 0; iPlane < nPlane; iPlane++) { - Gradient_file << "\"STATION"<< (iPlane+1) << "_TWIST\""; - if (iPlane != nPlane-1) Gradient_file << ","; + Gradient_file << "\"STATION" << (iPlane + 1) << "_TWIST\""; + if (iPlane != nPlane - 1) Gradient_file << ","; } } - } - if (tabTecplot) Gradient_file << "\nZONE T= \"Geometrical variables (gradient)\"" << endl; - else Gradient_file << endl; + if (tabTecplot) + Gradient_file << "\nZONE T= \"Geometrical variables (gradient)\"" << endl; + else + Gradient_file << endl; } - Gradient_file << (iDV) <<","; + Gradient_file << (iDV) << ","; if (config_container[ZONE_0]->GetGeo_Description() == FUSELAGE) { if (geometry_container[ZONE_0]->GetnDim() == 3) { - Gradient_file << Fuselage_Volume_Grad <<","<< Fuselage_WettedArea_Grad <<","<< Fuselage_MinWidth_Grad <<","<< Fuselage_MaxWidth_Grad <<","<< Fuselage_MinWaterLineWidth_Grad <<","<< Fuselage_MaxWaterLineWidth_Grad <<","<< Fuselage_MinHeight_Grad <<","<< Fuselage_MaxHeight_Grad <<","<< Fuselage_MaxCurvature_Grad <<","; + Gradient_file << Fuselage_Volume_Grad << "," << Fuselage_WettedArea_Grad << "," << Fuselage_MinWidth_Grad + << "," << Fuselage_MaxWidth_Grad << "," << Fuselage_MinWaterLineWidth_Grad << "," + << Fuselage_MaxWaterLineWidth_Grad << "," << Fuselage_MinHeight_Grad << "," + << Fuselage_MaxHeight_Grad << "," << Fuselage_MaxCurvature_Grad << ","; } - for (iPlane = 0; iPlane < nPlane*5; iPlane++) { + for (iPlane = 0; iPlane < nPlane * 5; iPlane++) { Gradient_file << Gradient[iPlane]; - if (iPlane != (nPlane*5)-1) Gradient_file <<","; + if (iPlane != (nPlane * 5) - 1) Gradient_file << ","; } - } - else if (config_container[ZONE_0]->GetGeo_Description() == NACELLE) { + } else if (config_container[ZONE_0]->GetGeo_Description() == NACELLE) { if (geometry_container[ZONE_0]->GetnDim() == 3) { - Gradient_file << Nacelle_Volume_Grad <<","<< Nacelle_MinThickness_Grad <<","<< Nacelle_MaxThickness_Grad <<","<< Nacelle_MinChord_Grad <<","<< Nacelle_MaxChord_Grad <<","<< Nacelle_MinLERadius_Grad <<","<< Nacelle_MaxLERadius_Grad<<","<< Nacelle_MinToC_Grad <<","<< Nacelle_MaxToC_Grad <<","<< Nacelle_ObjFun_MinToC_Grad <<","<< Nacelle_MaxTwist_Grad <<","; + Gradient_file << Nacelle_Volume_Grad << "," << Nacelle_MinThickness_Grad << "," << Nacelle_MaxThickness_Grad + << "," << Nacelle_MinChord_Grad << "," << Nacelle_MaxChord_Grad << "," + << Nacelle_MinLERadius_Grad << "," << Nacelle_MaxLERadius_Grad << "," << Nacelle_MinToC_Grad + << "," << Nacelle_MaxToC_Grad << "," << Nacelle_ObjFun_MinToC_Grad << "," + << Nacelle_MaxTwist_Grad << ","; } - for (iPlane = 0; iPlane < nPlane*6; iPlane++) { + for (iPlane = 0; iPlane < nPlane * 6; iPlane++) { Gradient_file << Gradient[iPlane]; - if (iPlane != (nPlane*6)-1) Gradient_file <<","; + if (iPlane != (nPlane * 6) - 1) Gradient_file << ","; } - } - else { + } else { if (geometry_container[ZONE_0]->GetnDim() == 3) { - Gradient_file << Wing_Volume_Grad <<","<< Wing_MinThickness_Grad <<","<< Wing_MaxThickness_Grad <<","<< Wing_MinChord_Grad <<","<< Wing_MaxChord_Grad <<","<< Wing_MinLERadius_Grad <<","<< Wing_MaxLERadius_Grad<<","<< Wing_MinToC_Grad <<","<< Wing_MaxToC_Grad <<","<< Wing_ObjFun_MinToC_Grad <<","<< Wing_MaxTwist_Grad <<","<< Wing_MaxCurvature_Grad <<","<< Wing_MaxDihedral_Grad <<","; + Gradient_file << Wing_Volume_Grad << "," << Wing_MinThickness_Grad << "," << Wing_MaxThickness_Grad << "," + << Wing_MinChord_Grad << "," << Wing_MaxChord_Grad << "," << Wing_MinLERadius_Grad << "," + << Wing_MaxLERadius_Grad << "," << Wing_MinToC_Grad << "," << Wing_MaxToC_Grad << "," + << Wing_ObjFun_MinToC_Grad << "," << Wing_MaxTwist_Grad << "," << Wing_MaxCurvature_Grad + << "," << Wing_MaxDihedral_Grad << ","; } - for (iPlane = 0; iPlane < nPlane*6; iPlane++) { + for (iPlane = 0; iPlane < nPlane * 6; iPlane++) { Gradient_file << Gradient[iPlane]; - if (iPlane != (nPlane*6)-1) Gradient_file <<","; + if (iPlane != (nPlane * 6) - 1) Gradient_file << ","; } } Gradient_file << endl; - if (iDV != (config_container[ZONE_0]->GetnDV()-1)) cout <<"-------------------------------------------------------------------------" << endl; - + if (iDV != (config_container[ZONE_0]->GetnDV() - 1)) + cout << "-------------------------------------------------------------------------" << endl; } - } - if (rank == MASTER_NODE) - Gradient_file.close(); - + if (rank == MASTER_NODE) Gradient_file.close(); } if (rank == MASTER_NODE) - cout << endl <<"------------------------- Solver Postprocessing -------------------------" << endl; + cout << endl << "------------------------- Solver Postprocessing -------------------------" << endl; - delete [] Xcoord_Airfoil; delete [] Ycoord_Airfoil; delete [] Zcoord_Airfoil; + delete[] Xcoord_Airfoil; + delete[] Ycoord_Airfoil; + delete[] Zcoord_Airfoil; - delete [] ObjectiveFunc; delete [] ObjectiveFunc_New; delete [] Gradient; + delete[] ObjectiveFunc; + delete[] ObjectiveFunc_New; + delete[] Gradient; - for(iPlane = 0; iPlane < nPlane; iPlane++ ) { + for (iPlane = 0; iPlane < nPlane; iPlane++) { delete Plane_P0[iPlane]; delete Plane_Normal[iPlane]; } - delete [] Plane_P0; - delete [] Plane_Normal; + delete[] Plane_P0; + delete[] Plane_Normal; delete config; config = nullptr; if (rank == MASTER_NODE) cout << "Deleted main variables." << endl; - if (geometry_container != nullptr) { for (iZone = 0; iZone < nZone; iZone++) { if (geometry_container[iZone] != nullptr) { delete geometry_container[iZone]; } } - delete [] geometry_container; + delete[] geometry_container; } if (rank == MASTER_NODE) cout << "Deleted CGeometry container." << endl; @@ -1256,7 +1470,7 @@ int main(int argc, char *argv[]) { delete FFDBox[iFFDBox]; } } - delete [] FFDBox; + delete[] FFDBox; } if (rank == MASTER_NODE) cout << "Deleted CFreeFormDefBox class." << endl; @@ -1266,7 +1480,7 @@ int main(int argc, char *argv[]) { delete config_container[iZone]; } } - delete [] config_container; + delete[] config_container; } if (rank == MASTER_NODE) cout << "Deleted CConfig container." << endl; @@ -1277,21 +1491,22 @@ int main(int argc, char *argv[]) { /*--- Compute/print the total time for performance benchmarking. ---*/ - UsedTime = StopTime-StartTime; + UsedTime = StopTime - StartTime; if (rank == MASTER_NODE) { - cout << "\n\nCompleted in " << fixed << UsedTime << " seconds on "<< size; - if (size == 1) cout << " core." << endl; else cout << " cores." << endl; + cout << "\n\nCompleted in " << fixed << UsedTime << " seconds on " << size; + if (size == 1) + cout << " core." << endl; + else + cout << " cores." << endl; } /*--- Exit the solver cleanly ---*/ if (rank == MASTER_NODE) - cout << endl <<"------------------------- Exit Success (SU2_GEO) ------------------------" << endl << endl; - + cout << endl << "------------------------- Exit Success (SU2_GEO) ------------------------" << endl << endl; /*--- Finalize MPI parallelization ---*/ SU2_MPI::Finalize(); return EXIT_SUCCESS; - } diff --git a/SU2_GEO/src/meson.build b/SU2_GEO/src/meson.build index 13e7e6f8875..dbbbbd25333 100644 --- a/SU2_GEO/src/meson.build +++ b/SU2_GEO/src/meson.build @@ -4,6 +4,6 @@ if get_option('enable-normal') su2_geo = executable('SU2_GEO', su2_geo_src, install: true, - dependencies: [su2_deps, common_dep], + dependencies: [su2_deps, common_dep], cpp_args : [default_warning_flags, su2_cpp_args]) endif diff --git a/SU2_IDE/Eclipse/README b/SU2_IDE/Eclipse/README index 454e31b4ebc..07c6b1c46f5 100644 --- a/SU2_IDE/Eclipse/README +++ b/SU2_IDE/Eclipse/README @@ -2,10 +2,10 @@ This README file includes instructions on how to use Eclipse with the SU2 github repository. It is assumed that Eclipse has already been installed. ------------------------------------------------------------------------------- 1. Initial Eclipse Set-up -In order to view files with helpful text highlighting and code navigation +In order to view files with helpful text highlighting and code navigation tools, install the packages for C++, Python, and Git: Help -> Install New Software - Install packages for Git, C++ and Python, for example: + Install packages for Git, C++ and Python, for example: C/C++ Development Tools SDK Eclipse EGit PyDev for Eclipse @@ -13,8 +13,8 @@ tools, install the packages for C++, Python, and Git: ------------------------------------------------------------------------------- 2. Get the code -2a.If you have already cloned the SU2 source code, or prefer to clone via the -command line, you will need to import this project into the Eclipse Workspace: +2a.If you have already cloned the SU2 source code, or prefer to clone via the +command line, you will need to import this project into the Eclipse Workspace: File -> New -> Makefile project with existing code Name the project and navigate to the appropriate directory. Make sure "C++" is checked and select "finish" @@ -37,13 +37,13 @@ command line, you will need to import this project into the Eclipse Workspace: If you did not clone the repository using Egit: Window -> open perspective -> Git Repository Exploring Window -> Show View -> Git Repositories - Add the repository: + Add the repository: In the Git repositories window, select "add an existing local git - repository to this view". + repository to this view". Browse to the location where you cloned the repository, select "finish" - When in the Git perspective, you will be able to see your local github - repositories and graphically explore the branch structure. + When in the Git perspective, you will be able to see your local github + repositories and graphically explore the branch structure. ------------------------------------------------------------------------------- @@ -54,7 +54,3 @@ If you did not clone the repository using Egit: Select Project-> Properties to edit Eclipse behavior ------------------------------------------------------------------------------- - - - - diff --git a/SU2_PY/FSI_tools/FSIInterface.py b/SU2_PY/FSI_tools/FSIInterface.py index 88c030ff6a0..bcd8526c5ee 100644 --- a/SU2_PY/FSI_tools/FSIInterface.py +++ b/SU2_PY/FSI_tools/FSIInterface.py @@ -41,6 +41,7 @@ # FSI Interface Class # ---------------------------------------------------------------------- + class Interface: """ FSI interface class that handles fluid/solid solvers synchronisation and communication @@ -52,161 +53,239 @@ def __init__(self, FSI_config, FluidSolver, SolidSolver, have_MPI): """ if have_MPI: - from mpi4py import MPI - self.MPI = MPI - self.comm = MPI.COMM_WORLD #MPI World communicator - self.have_MPI = True - myid = self.comm.Get_rank() - else: - self.comm = 0 - self.have_MPI = False - myid = 0 - - self.rootProcess = 0 #the root process is chosen to be MPI rank = 0 - - self.nDim = FSI_config['NDIM'] #problem dimension - - self.haveFluidSolver = False #True if the fluid solver is initialized on the current rank - self.haveSolidSolver = False #True if the solid solver is initialized on the current rank - self.haveFluidInterface = False #True if the current rank owns at least one fluid interface node - self.haveSolidInterface = False #True if the current rank owns at least one solid interface node - - self.fluidSolverProcessors = list() #list of partitions where the fluid solver is initialized - self.solidSolverProcessors = list() #list of partitions where the solid solver is initialized - self.fluidInterfaceProcessors = list() #list of partitions where there are fluid interface nodes - self.solidInterfaceProcessors = list() #list of partitions where there are solid interface nodes - - self.fluidInterfaceIdentifier = None #object that can identify the f/s interface within the fluid solver - self.solidInterfaceIdentifier = None #object that can identify the f/s interface within the solid solver - - self.fluidGlobalIndexRange = {} #contains the global FSI indexing of each fluid interface node for all partitions - self.solidGlobalIndexRange = {} #contains the global FSI indexing of each solid interface node for all partitions - - self.FluidHaloNodeList = {} #contains the the indices (fluid solver indexing) of the halo nodes for each partition - self.fluidIndexing = {} #links between the fluid solver indexing and the FSI indexing for the interface nodes - self.SolidHaloNodeList = {} #contains the the indices (solid solver indexing) of the halo nodes for each partition - self.solidIndexing = {} #links between the solid solver indexing and the FSI indexing for the interface nodes - - self.nLocalFluidInterfaceNodes = 0 #number of nodes (halo nodes included) on the fluid interface, on each partition - self.nLocalFluidInterfaceHaloNode = 0 #number of halo nodes on the fluid intrface, on each partition - self.nLocalFluidInterfacePhysicalNodes = 0 #number of physical (= non halo) nodes on the fluid interface, on each partition - self.nFluidInterfaceNodes = np.array(int(0)) #number of nodes on the fluid interface, sum over all the partitions - self.nFluidInterfacePhysicalNodes = np.array(int(0)) #number of physical nodes on the fluid interface, sum over all partitions - - self.nLocalSolidInterfaceNodes = 0 #number of physical nodes on the solid interface, on each partition - self.nLocalSolidInterfaceHaloNode = 0 #number of halo nodes on the solid intrface, on each partition - self.nLocalSolidInterfacePhysicalNodes = 0 #number of physical (= non halo) nodes on the solid interface, on each partition - self.nSolidInterfaceNodes = np.array(int(0)) #number of nodes on the solid interface, sum over all partitions - self.nSolidInterfacePhysicalNodes = np.array(int(0)) #number of physical nodes on the solid interface, sum over all partitions - - if FSI_config['MATCHING_MESH'] == 'NO' and (FSI_config['MESH_INTERP_METHOD'] == 'RBF' or FSI_config['MESH_INTERP_METHOD'] == 'TPS'): - self.MappingMatrixA = None - self.MappingMatrixA_T = None - self.MappingMatrixB = None - self.MappingMatrixB_T = None - self.d_RBF = self.nDim+1 - else: - self.MappingMatrix = None #interpolation/mapping matrix for meshes interpolation/mapping - self.MappingMatrix_T = None #transposed interpolation/mapping matrix for meshes interpolation/mapping - self.d_RBF = 0 - - self.localFluidInterface_array_X_init = None #initial fluid interface position on each partition (used for the meshes mapping) + from mpi4py import MPI + + self.MPI = MPI + self.comm = MPI.COMM_WORLD # MPI World communicator + self.have_MPI = True + myid = self.comm.Get_rank() + else: + self.comm = 0 + self.have_MPI = False + myid = 0 + + self.rootProcess = 0 # the root process is chosen to be MPI rank = 0 + + self.nDim = FSI_config["NDIM"] # problem dimension + + self.haveFluidSolver = ( + False # True if the fluid solver is initialized on the current rank + ) + self.haveSolidSolver = ( + False # True if the solid solver is initialized on the current rank + ) + self.haveFluidInterface = ( + False # True if the current rank owns at least one fluid interface node + ) + self.haveSolidInterface = ( + False # True if the current rank owns at least one solid interface node + ) + + self.fluidSolverProcessors = ( + list() + ) # list of partitions where the fluid solver is initialized + self.solidSolverProcessors = ( + list() + ) # list of partitions where the solid solver is initialized + self.fluidInterfaceProcessors = ( + list() + ) # list of partitions where there are fluid interface nodes + self.solidInterfaceProcessors = ( + list() + ) # list of partitions where there are solid interface nodes + + self.fluidInterfaceIdentifier = ( + None # object that can identify the f/s interface within the fluid solver + ) + self.solidInterfaceIdentifier = ( + None # object that can identify the f/s interface within the solid solver + ) + + self.fluidGlobalIndexRange = ( + {} + ) # contains the global FSI indexing of each fluid interface node for all partitions + self.solidGlobalIndexRange = ( + {} + ) # contains the global FSI indexing of each solid interface node for all partitions + + self.FluidHaloNodeList = ( + {} + ) # contains the the indices (fluid solver indexing) of the halo nodes for each partition + self.fluidIndexing = ( + {} + ) # links between the fluid solver indexing and the FSI indexing for the interface nodes + self.SolidHaloNodeList = ( + {} + ) # contains the the indices (solid solver indexing) of the halo nodes for each partition + self.solidIndexing = ( + {} + ) # links between the solid solver indexing and the FSI indexing for the interface nodes + + self.nLocalFluidInterfaceNodes = 0 # number of nodes (halo nodes included) on the fluid interface, on each partition + self.nLocalFluidInterfaceHaloNode = ( + 0 # number of halo nodes on the fluid intrface, on each partition + ) + self.nLocalFluidInterfacePhysicalNodes = 0 # number of physical (= non halo) nodes on the fluid interface, on each partition + self.nFluidInterfaceNodes = np.array( + int(0) + ) # number of nodes on the fluid interface, sum over all the partitions + self.nFluidInterfacePhysicalNodes = np.array( + int(0) + ) # number of physical nodes on the fluid interface, sum over all partitions + + self.nLocalSolidInterfaceNodes = ( + 0 # number of physical nodes on the solid interface, on each partition + ) + self.nLocalSolidInterfaceHaloNode = ( + 0 # number of halo nodes on the solid intrface, on each partition + ) + self.nLocalSolidInterfacePhysicalNodes = 0 # number of physical (= non halo) nodes on the solid interface, on each partition + self.nSolidInterfaceNodes = np.array( + int(0) + ) # number of nodes on the solid interface, sum over all partitions + self.nSolidInterfacePhysicalNodes = np.array( + int(0) + ) # number of physical nodes on the solid interface, sum over all partitions + + if FSI_config["MATCHING_MESH"] == "NO" and ( + FSI_config["MESH_INTERP_METHOD"] == "RBF" + or FSI_config["MESH_INTERP_METHOD"] == "TPS" + ): + self.MappingMatrixA = None + self.MappingMatrixA_T = None + self.MappingMatrixB = None + self.MappingMatrixB_T = None + self.d_RBF = self.nDim + 1 + else: + self.MappingMatrix = ( + None # interpolation/mapping matrix for meshes interpolation/mapping + ) + self.MappingMatrix_T = None # transposed interpolation/mapping matrix for meshes interpolation/mapping + self.d_RBF = 0 + + self.localFluidInterface_array_X_init = None # initial fluid interface position on each partition (used for the meshes mapping) self.localFluidInterface_array_Y_init = None self.localFluidInterface_array_Z_init = None - self.localSolidInterface_array_X_init = None #initial solid interface position on each partition (used for mesh mapping) + self.localSolidInterface_array_X_init = None # initial solid interface position on each partition (used for mesh mapping) self.localSolidInterface_array_Y_init = None self.localSolidInterface_array_Z_init = None - self.solidInterface_array_DispX = None #solid interface displacement + self.solidInterface_array_DispX = None # solid interface displacement self.solidInterface_array_DispY = None self.solidInterface_array_DispZ = None - self.solidInterfaceResidual_array_X = None #solid interface position residual + self.solidInterfaceResidual_array_X = None # solid interface position residual self.solidInterfaceResidual_array_Y = None self.solidInterfaceResidual_array_Z = None - self.solidInterfaceResidualnM1_array_X = None #solid interface position residual at the previous BGS iteration + self.solidInterfaceResidualnM1_array_X = ( + None # solid interface position residual at the previous BGS iteration + ) self.solidInterfaceResidualnM1_array_Y = None self.solidInterfaceResidualnM1_array_Z = None - self.fluidInterface_array_DispX = None #fluid interface displacement + self.fluidInterface_array_DispX = None # fluid interface displacement self.fluidInterface_array_DispY = None self.fluidInterface_array_DispZ = None - self.fluidLoads_array_X = None #loads on the fluid side of the f/s interface + self.fluidLoads_array_X = None # loads on the fluid side of the f/s interface self.fluidLoads_array_Y = None self.fluidLoads_array_Z = None - self.solidLoads_array_X = None #loads on the solid side of the f/s interface + self.solidLoads_array_X = None # loads on the solid side of the f/s interface self.solidLoads_array_Y = None self.solidLoads_array_Z = None - self.aitkenParam = FSI_config['AITKEN_PARAM'] #relaxation parameter for the BGS method - self.FSIIter = 0 #current FSI iteration - self.unsteady = False #flag for steady or unsteady simulation (default is steady) - if FSI_config['IMPOSED_MOTION']=='YES': - self.ImposedMotion = True + self.aitkenParam = FSI_config[ + "AITKEN_PARAM" + ] # relaxation parameter for the BGS method + self.FSIIter = 0 # current FSI iteration + self.unsteady = ( + False # flag for steady or unsteady simulation (default is steady) + ) + if FSI_config["IMPOSED_MOTION"] == "YES": + self.ImposedMotion = True else: - self.ImposedMotion = False + self.ImposedMotion = False # ---Some screen output --- - self.MPIPrint('Fluid solver : SU2_CFD') - self.MPIPrint('Solid solver : {}'.format(FSI_config['CSD_SOLVER'])) - - if FSI_config['TIME_MARCHING'] == 'YES': - self.MPIPrint('Unsteady coupled simulation with physical time step : {} s'.format(FSI_config['UNST_TIMESTEP'])) - self.unsteady = True + self.MPIPrint("Fluid solver : SU2_CFD") + self.MPIPrint("Solid solver : {}".format(FSI_config["CSD_SOLVER"])) + + if FSI_config["TIME_MARCHING"] == "YES": + self.MPIPrint( + "Unsteady coupled simulation with physical time step : {} s".format( + FSI_config["UNST_TIMESTEP"] + ) + ) + self.unsteady = True else: - self.MPIPrint('Steady coupled simulation') + self.MPIPrint("Steady coupled simulation") - if FSI_config['MATCHING_MESH'] == 'YES': - self.MPIPrint('Matching fluid-solid interface') + if FSI_config["MATCHING_MESH"] == "YES": + self.MPIPrint("Matching fluid-solid interface") else: - if FSI_config['MESH_INTERP_METHOD'] == 'TPS': - self.MPIPrint('Non matching fluid-solid interface with Thin Plate Spline interpolation') - elif FSI_config['MESH_INTERP_METHOD'] == 'RBF': - self.MPIPrint('Non matching fluid-solid interface with Radial Basis Function interpolation') - self.RBF_rad = FSI_config['RBF_RADIUS'] - self.MPIPrint('Radius value : {}'.format(self.RBF_rad)) - else: - self.MPIPrint('Non matching fluid-solid interface with Nearest Neighboor interpolation') - - self.MPIPrint('Solid predictor : {}'.format(FSI_config['DISP_PRED'])) - - self.MPIPrint('Maximum number of FSI iterations : {}'.format(FSI_config['NB_FSI_ITER'])) - - self.MPIPrint('FSI tolerance : {}'.format(FSI_config['FSI_TOLERANCE'])) - - if FSI_config['AITKEN_RELAX'] == 'STATIC': - self.MPIPrint('Static Aitken under-relaxation with constant parameter {}'.format(FSI_config['AITKEN_PARAM'])) - elif FSI_config['AITKEN_RELAX'] == 'DYNAMIC': - self.MPIPrint('Dynamic Aitken under-relaxation with initial parameter {}'.format(FSI_config['AITKEN_PARAM'])) + if FSI_config["MESH_INTERP_METHOD"] == "TPS": + self.MPIPrint( + "Non matching fluid-solid interface with Thin Plate Spline interpolation" + ) + elif FSI_config["MESH_INTERP_METHOD"] == "RBF": + self.MPIPrint( + "Non matching fluid-solid interface with Radial Basis Function interpolation" + ) + self.RBF_rad = FSI_config["RBF_RADIUS"] + self.MPIPrint("Radius value : {}".format(self.RBF_rad)) + else: + self.MPIPrint( + "Non matching fluid-solid interface with Nearest Neighboor interpolation" + ) + + self.MPIPrint("Solid predictor : {}".format(FSI_config["DISP_PRED"])) + + self.MPIPrint( + "Maximum number of FSI iterations : {}".format(FSI_config["NB_FSI_ITER"]) + ) + + self.MPIPrint("FSI tolerance : {}".format(FSI_config["FSI_TOLERANCE"])) + + if FSI_config["AITKEN_RELAX"] == "STATIC": + self.MPIPrint( + "Static Aitken under-relaxation with constant parameter {}".format( + FSI_config["AITKEN_PARAM"] + ) + ) + elif FSI_config["AITKEN_RELAX"] == "DYNAMIC": + self.MPIPrint( + "Dynamic Aitken under-relaxation with initial parameter {}".format( + FSI_config["AITKEN_PARAM"] + ) + ) else: - self.MPIPrint('No Aitken under-relaxation') + self.MPIPrint("No Aitken under-relaxation") - self.MPIPrint('FSI interface is set') + self.MPIPrint("FSI interface is set") def MPIPrint(self, message): - """ - Print a message on screen only from the master process. - """ + """ + Print a message on screen only from the master process. + """ - if self.have_MPI: - myid = self.comm.Get_rank() - else: - myid = 0 + if self.have_MPI: + myid = self.comm.Get_rank() + else: + myid = 0 - if myid == self.rootProcess: - print(message) + if myid == self.rootProcess: + print(message) def MPIBarrier(self): - """ - Perform a synchronization barrier in case of parallel run with MPI. - """ + """ + Perform a synchronization barrier in case of parallel run with MPI. + """ - if self.have_MPI: - self.comm.barrier() + if self.have_MPI: + self.comm.barrier() def connect(self, FSI_config, FluidSolver, SolidSolver): """ @@ -215,85 +294,108 @@ def connect(self, FSI_config, FluidSolver, SolidSolver): Gets information about f/s interfaces from the two solvers. """ if self.have_MPI: - myid = self.comm.Get_rank() - MPIsize = self.comm.Get_size() + myid = self.comm.Get_rank() + MPIsize = self.comm.Get_size() else: - myid = 0 - MPIsize = 1 + myid = 0 + MPIsize = 1 # --- Identify the fluid and solid interfaces and store the number of nodes on both sides (and for each partition) --- self.fluidInterfaceIdentifier = None self.nLocalFluidInterfaceNodes = 0 if FluidSolver is not None: - print('Fluid solver is initialized on process {}'.format(myid)) + print("Fluid solver is initialized on process {}".format(myid)) self.haveFluidSolver = True allMovingMarkersTags = FluidSolver.GetDeformableMarkerTags() allMarkersID = FluidSolver.GetMarkerTags() if not allMovingMarkersTags: - raise Exception('No interface for FSI was defined.') + raise Exception("No interface for FSI was defined.") else: if allMovingMarkersTags[0] in allMarkersID.keys(): - self.fluidInterfaceIdentifier = allMarkersID[allMovingMarkersTags[0]] + self.fluidInterfaceIdentifier = allMarkersID[ + allMovingMarkersTags[0] + ] if self.fluidInterfaceIdentifier is not None: - self.nLocalFluidInterfaceNodes = FluidSolver.GetNumberMarkerNodes(self.fluidInterfaceIdentifier) + self.nLocalFluidInterfaceNodes = FluidSolver.GetNumberMarkerNodes( + self.fluidInterfaceIdentifier + ) if self.nLocalFluidInterfaceNodes != 0: - self.haveFluidInterface = True - print('Number of interface fluid nodes (halo nodes included) on proccess {} : {}'.format(myid,self.nLocalFluidInterfaceNodes)) + self.haveFluidInterface = True + print( + "Number of interface fluid nodes (halo nodes included) on proccess {} : {}".format( + myid, self.nLocalFluidInterfaceNodes + ) + ) else: pass if SolidSolver is not None: - print('Solid solver is initialized on process {}'.format(myid)) + print("Solid solver is initialized on process {}".format(myid)) self.haveSolidSolver = True self.solidInterfaceIdentifier = SolidSolver.getFSIMarkerID() - self.nLocalSolidInterfaceNodes = SolidSolver.getNumberOfSolidInterfaceNodes(self.solidInterfaceIdentifier) + self.nLocalSolidInterfaceNodes = SolidSolver.getNumberOfSolidInterfaceNodes( + self.solidInterfaceIdentifier + ) if self.nLocalSolidInterfaceNodes != 0: - self.haveSolidInterface = True - print('Number of interface solid nodes (halo nodes included) on proccess {} : {}'.format(myid,self.nLocalSolidInterfaceNodes)) + self.haveSolidInterface = True + print( + "Number of interface solid nodes (halo nodes included) on proccess {} : {}".format( + myid, self.nLocalSolidInterfaceNodes + ) + ) else: pass # --- Exchange information about processors on which the solvers are defined and where the interface nodes are lying --- if self.have_MPI: - if self.haveFluidSolver: - sendBufFluid = np.array(int(1)) - else: - sendBufFluid = np.array(int(0)) - if self.haveSolidSolver: - sendBufSolid = np.array(int(1)) - else: - sendBufSolid = np.array(int(0)) - if self.haveFluidInterface: - sendBufFluidInterface = np.array(int(1)) - else: - sendBufFluidInterface = np.array(int(0)) - if self.haveSolidInterface: - sendBufSolidInterface = np.array(int(1)) - else: - sendBufSolidInterface = np.array(int(0)) - rcvBufFluid = np.zeros(MPIsize, dtype = int) - rcvBufSolid = np.zeros(MPIsize, dtype = int) - rcvBufFluidInterface = np.zeros(MPIsize, dtype = int) - rcvBufSolidInterface = np.zeros(MPIsize, dtype = int) - self.comm.Allgather(sendBufFluid, rcvBufFluid) - self.comm.Allgather(sendBufSolid, rcvBufSolid) - self.comm.Allgather(sendBufFluidInterface, rcvBufFluidInterface) - self.comm.Allgather(sendBufSolidInterface, rcvBufSolidInterface) - for iProc in range(MPIsize): - if rcvBufFluid[iProc] == 1: - self.fluidSolverProcessors.append(iProc) - if rcvBufSolid[iProc] == 1: - self.solidSolverProcessors.append(iProc) - if rcvBufFluidInterface[iProc] == 1: - self.fluidInterfaceProcessors.append(iProc) - if rcvBufSolidInterface[iProc] == 1: - self.solidInterfaceProcessors.append(iProc) - del sendBufFluid, sendBufSolid, rcvBufFluid, rcvBufSolid, sendBufFluidInterface, sendBufSolidInterface, rcvBufFluidInterface, rcvBufSolidInterface - else: - self.fluidSolverProcessors.append(0) - self.solidSolverProcessors.append(0) - self.fluidInterfaceProcessors.append(0) - self.solidInterfaceProcessors.append(0) + if self.haveFluidSolver: + sendBufFluid = np.array(int(1)) + else: + sendBufFluid = np.array(int(0)) + if self.haveSolidSolver: + sendBufSolid = np.array(int(1)) + else: + sendBufSolid = np.array(int(0)) + if self.haveFluidInterface: + sendBufFluidInterface = np.array(int(1)) + else: + sendBufFluidInterface = np.array(int(0)) + if self.haveSolidInterface: + sendBufSolidInterface = np.array(int(1)) + else: + sendBufSolidInterface = np.array(int(0)) + rcvBufFluid = np.zeros(MPIsize, dtype=int) + rcvBufSolid = np.zeros(MPIsize, dtype=int) + rcvBufFluidInterface = np.zeros(MPIsize, dtype=int) + rcvBufSolidInterface = np.zeros(MPIsize, dtype=int) + self.comm.Allgather(sendBufFluid, rcvBufFluid) + self.comm.Allgather(sendBufSolid, rcvBufSolid) + self.comm.Allgather(sendBufFluidInterface, rcvBufFluidInterface) + self.comm.Allgather(sendBufSolidInterface, rcvBufSolidInterface) + for iProc in range(MPIsize): + if rcvBufFluid[iProc] == 1: + self.fluidSolverProcessors.append(iProc) + if rcvBufSolid[iProc] == 1: + self.solidSolverProcessors.append(iProc) + if rcvBufFluidInterface[iProc] == 1: + self.fluidInterfaceProcessors.append(iProc) + if rcvBufSolidInterface[iProc] == 1: + self.solidInterfaceProcessors.append(iProc) + del ( + sendBufFluid, + sendBufSolid, + rcvBufFluid, + rcvBufSolid, + sendBufFluidInterface, + sendBufSolidInterface, + rcvBufFluidInterface, + rcvBufSolidInterface, + ) + else: + self.fluidSolverProcessors.append(0) + self.solidSolverProcessors.append(0) + self.fluidInterfaceProcessors.append(0) + self.solidInterfaceProcessors.append(0) self.MPIBarrier() # --- Calculate the total number of nodes at the fluid interface (sum over all the partitions) --- @@ -302,29 +404,34 @@ def connect(self, FSI_config, FluidSolver, SolidSolver): for iVertex in range(self.nLocalFluidInterfaceNodes): iPoint = FluidSolver.GetMarkerNode(self.fluidInterfaceIdentifier, iVertex) if not FluidSolver.GetNodeDomain(iPoint): - GlobalIndex = FluidSolver.GetNodeGlobalIndex(iPoint) - self.FluidHaloNodeList[GlobalIndex] = iVertex - self.nLocalFluidInterfaceHaloNode += 1 + GlobalIndex = FluidSolver.GetNodeGlobalIndex(iPoint) + self.FluidHaloNodeList[GlobalIndex] = iVertex + self.nLocalFluidInterfaceHaloNode += 1 # Calculate the number of physical (= not halo) nodes on each partition - self.nLocalFluidInterfacePhysicalNodes = self.nLocalFluidInterfaceNodes - self.nLocalFluidInterfaceHaloNode + self.nLocalFluidInterfacePhysicalNodes = ( + self.nLocalFluidInterfaceNodes - self.nLocalFluidInterfaceHaloNode + ) if self.have_MPI: - self.FluidHaloNodeList = self.comm.allgather(self.FluidHaloNodeList) + self.FluidHaloNodeList = self.comm.allgather(self.FluidHaloNodeList) else: - self.FluidHaloNodeList = [{}] + self.FluidHaloNodeList = [{}] # Same thing for the solid part self.nLocalSolidInterfaceHaloNode = 0 for iVertex in range(self.nLocalSolidInterfaceNodes): if SolidSolver.IsAHaloNode(self.solidInterfaceIdentifier, iVertex): - GlobalIndex = SolidSolver.getVertexGlobalIndex(self.solidInterfaceIdentifier, iVertex) - self.SolidHaloNodeList[GlobalIndex] = iVertex - self.nLocalSolidInterfaceHaloNode += 1 - self.nLocalSolidInterfacePhysicalNodes = self.nLocalSolidInterfaceNodes - self.nLocalSolidInterfaceHaloNode + GlobalIndex = SolidSolver.getVertexGlobalIndex( + self.solidInterfaceIdentifier, iVertex + ) + self.SolidHaloNodeList[GlobalIndex] = iVertex + self.nLocalSolidInterfaceHaloNode += 1 + self.nLocalSolidInterfacePhysicalNodes = ( + self.nLocalSolidInterfaceNodes - self.nLocalSolidInterfaceHaloNode + ) if self.have_MPI: - self.SolidHaloNodeList = self.comm.allgather(self.SolidHaloNodeList) + self.SolidHaloNodeList = self.comm.allgather(self.SolidHaloNodeList) else: - self.SolidHaloNodeList = [{}] - + self.SolidHaloNodeList = [{}] # --- Calculate the total number of nodes (with and without halo) at the fluid interface (sum over all the partitions) and broadcast the number accross all processors --- sendBuffTotal = np.array(int(self.nLocalFluidInterfaceNodes)) @@ -332,12 +439,16 @@ def connect(self, FSI_config, FluidSolver, SolidSolver): rcvBuffTotal = np.zeros(1, dtype=int) rcvBuffPhysical = np.zeros(1, dtype=int) if self.have_MPI: - self.comm.barrier() - self.comm.Allreduce(sendBuffTotal, self.nFluidInterfaceNodes, op=self.MPI.SUM) - self.comm.Allreduce(sendBuffPhysical, self.nFluidInterfacePhysicalNodes, op=self.MPI.SUM) + self.comm.barrier() + self.comm.Allreduce( + sendBuffTotal, self.nFluidInterfaceNodes, op=self.MPI.SUM + ) + self.comm.Allreduce( + sendBuffPhysical, self.nFluidInterfacePhysicalNodes, op=self.MPI.SUM + ) else: - self.nFluidInterfaceNodes = np.copy(sendBuffTotal) - self.nFluidInterfacePhysicalNodes = np.copy(sendBuffPhysical) + self.nFluidInterfaceNodes = np.copy(sendBuffTotal) + self.nFluidInterfacePhysicalNodes = np.copy(sendBuffPhysical) del sendBuffTotal, rcvBuffTotal, sendBuffPhysical, rcvBuffPhysical # Same thing for the solid part @@ -346,111 +457,153 @@ def connect(self, FSI_config, FluidSolver, SolidSolver): rcvBuffTotal = np.zeros(1, dtype=int) rcvBuffPhysical = np.zeros(1, dtype=int) if self.have_MPI: - self.comm.barrier() - self.comm.Allreduce(sendBuffTotal, self.nSolidInterfaceNodes, op=self.MPI.SUM) - self.comm.Allreduce(sendBuffPhysical, self.nSolidInterfacePhysicalNodes, op=self.MPI.SUM) + self.comm.barrier() + self.comm.Allreduce( + sendBuffTotal, self.nSolidInterfaceNodes, op=self.MPI.SUM + ) + self.comm.Allreduce( + sendBuffPhysical, self.nSolidInterfacePhysicalNodes, op=self.MPI.SUM + ) else: - self.nSolidInterfaceNodes = np.copy(sendBuffTotal) - self.nSolidInterfacePhysicalNodes = np.copy(sendBuffPhysical) + self.nSolidInterfaceNodes = np.copy(sendBuffTotal) + self.nSolidInterfacePhysicalNodes = np.copy(sendBuffPhysical) del sendBuffTotal, rcvBuffTotal, sendBuffPhysical, rcvBuffPhysical # --- Store the number of physical interface nodes on each processor and allgather the information --- self.fluidPhysicalInterfaceNodesDistribution = np.zeros(MPIsize, dtype=int) if self.have_MPI: - sendBuffPhysical = np.array(int(self.nLocalFluidInterfacePhysicalNodes)) - self.comm.Allgather(sendBuffPhysical,self.fluidPhysicalInterfaceNodesDistribution) - del sendBuffPhysical + sendBuffPhysical = np.array(int(self.nLocalFluidInterfacePhysicalNodes)) + self.comm.Allgather( + sendBuffPhysical, self.fluidPhysicalInterfaceNodesDistribution + ) + del sendBuffPhysical else: - self.fluidPhysicalInterfaceNodesDistribution[0] = self.nFluidInterfacePhysicalNodes + self.fluidPhysicalInterfaceNodesDistribution[ + 0 + ] = self.nFluidInterfacePhysicalNodes # Same thing for the solid part self.solidPhysicalInterfaceNodesDistribution = np.zeros(MPIsize, dtype=int) if self.have_MPI: - sendBuffPhysical = np.array(int(self.nLocalSolidInterfacePhysicalNodes)) - self.comm.Allgather(sendBuffPhysical,self.solidPhysicalInterfaceNodesDistribution) - del sendBuffPhysical + sendBuffPhysical = np.array(int(self.nLocalSolidInterfacePhysicalNodes)) + self.comm.Allgather( + sendBuffPhysical, self.solidPhysicalInterfaceNodesDistribution + ) + del sendBuffPhysical else: - self.solidPhysicalInterfaceNodesDistribution[0] = self.nSolidInterfacePhysicalNodes + self.solidPhysicalInterfaceNodesDistribution[ + 0 + ] = self.nSolidInterfacePhysicalNodes # --- Calculate and store the global indexing of interface physical nodes on each processor and allgather the information --- if self.have_MPI: - if myid in self.fluidInterfaceProcessors: - globalIndexStart = 0 - for iProc in range(myid): - globalIndexStart += self.fluidPhysicalInterfaceNodesDistribution[iProc] - globalIndexStop = globalIndexStart + self.nLocalFluidInterfacePhysicalNodes-1 - else: - globalIndexStart = 0 - globalIndexStop = 0 - self.fluidGlobalIndexRange[myid] = [globalIndexStart,globalIndexStop] - self.fluidGlobalIndexRange = self.comm.allgather(self.fluidGlobalIndexRange) - else: - temp = {} - temp[0] = [0,self.nLocalFluidInterfacePhysicalNodes-1] - self.fluidGlobalIndexRange = list() - self.fluidGlobalIndexRange.append(temp) + if myid in self.fluidInterfaceProcessors: + globalIndexStart = 0 + for iProc in range(myid): + globalIndexStart += self.fluidPhysicalInterfaceNodesDistribution[ + iProc + ] + globalIndexStop = ( + globalIndexStart + self.nLocalFluidInterfacePhysicalNodes - 1 + ) + else: + globalIndexStart = 0 + globalIndexStop = 0 + self.fluidGlobalIndexRange[myid] = [globalIndexStart, globalIndexStop] + self.fluidGlobalIndexRange = self.comm.allgather(self.fluidGlobalIndexRange) + else: + temp = {} + temp[0] = [0, self.nLocalFluidInterfacePhysicalNodes - 1] + self.fluidGlobalIndexRange = list() + self.fluidGlobalIndexRange.append(temp) # Same thing for the solid part if self.have_MPI: - if myid in self.solidInterfaceProcessors: - globalIndexStart = 0 - for iProc in range(myid): - globalIndexStart += self.solidPhysicalInterfaceNodesDistribution[iProc] - globalIndexStop = globalIndexStart + self.nLocalSolidInterfacePhysicalNodes-1 - else: - globalIndexStart = 0 - globalIndexStop = 0 - self.solidGlobalIndexRange[myid] = [globalIndexStart,globalIndexStop] - self.solidGlobalIndexRange = self.comm.allgather(self.solidGlobalIndexRange) - else: - temp = {} - temp[0] = [0,self.nSolidInterfacePhysicalNodes-1] - self.solidGlobalIndexRange = list() - self.solidGlobalIndexRange.append(temp) - - self.MPIPrint('Total number of fluid interface nodes (halo nodes included) : {}'.format(self.nFluidInterfaceNodes)) - self.MPIPrint('Total number of solid interface nodes (halo nodes included) : {}'.format(self.nSolidInterfaceNodes)) - self.MPIPrint('Total number of fluid interface nodes : {}'.format(self.nFluidInterfacePhysicalNodes)) - self.MPIPrint('Total number of solid interface nodes : {}'.format(self.nSolidInterfacePhysicalNodes)) + if myid in self.solidInterfaceProcessors: + globalIndexStart = 0 + for iProc in range(myid): + globalIndexStart += self.solidPhysicalInterfaceNodesDistribution[ + iProc + ] + globalIndexStop = ( + globalIndexStart + self.nLocalSolidInterfacePhysicalNodes - 1 + ) + else: + globalIndexStart = 0 + globalIndexStop = 0 + self.solidGlobalIndexRange[myid] = [globalIndexStart, globalIndexStop] + self.solidGlobalIndexRange = self.comm.allgather(self.solidGlobalIndexRange) + else: + temp = {} + temp[0] = [0, self.nSolidInterfacePhysicalNodes - 1] + self.solidGlobalIndexRange = list() + self.solidGlobalIndexRange.append(temp) + + self.MPIPrint( + "Total number of fluid interface nodes (halo nodes included) : {}".format( + self.nFluidInterfaceNodes + ) + ) + self.MPIPrint( + "Total number of solid interface nodes (halo nodes included) : {}".format( + self.nSolidInterfaceNodes + ) + ) + self.MPIPrint( + "Total number of fluid interface nodes : {}".format( + self.nFluidInterfacePhysicalNodes + ) + ) + self.MPIPrint( + "Total number of solid interface nodes : {}".format( + self.nSolidInterfacePhysicalNodes + ) + ) self.MPIBarrier() # --- Create all the PETSc vectors required for parallel communication and parallel mesh mapping/interpolation (working for serial too) --- if self.have_MPI: - self.solidInterface_array_DispX = PETSc.Vec().create(self.comm) - self.solidInterface_array_DispY = PETSc.Vec().create(self.comm) - self.solidInterface_array_DispZ = PETSc.Vec().create(self.comm) - self.solidInterface_array_DispX.setType('mpi') - self.solidInterface_array_DispY.setType('mpi') - self.solidInterface_array_DispZ.setType('mpi') - else: - self.solidInterface_array_DispX = PETSc.Vec().create() - self.solidInterface_array_DispY = PETSc.Vec().create() - self.solidInterface_array_DispZ = PETSc.Vec().create() - self.solidInterface_array_DispX.setType('seq') - self.solidInterface_array_DispY.setType('seq') - self.solidInterface_array_DispZ.setType('seq') - self.solidInterface_array_DispX.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) - self.solidInterface_array_DispY.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) - self.solidInterface_array_DispZ.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) + self.solidInterface_array_DispX = PETSc.Vec().create(self.comm) + self.solidInterface_array_DispY = PETSc.Vec().create(self.comm) + self.solidInterface_array_DispZ = PETSc.Vec().create(self.comm) + self.solidInterface_array_DispX.setType("mpi") + self.solidInterface_array_DispY.setType("mpi") + self.solidInterface_array_DispZ.setType("mpi") + else: + self.solidInterface_array_DispX = PETSc.Vec().create() + self.solidInterface_array_DispY = PETSc.Vec().create() + self.solidInterface_array_DispZ = PETSc.Vec().create() + self.solidInterface_array_DispX.setType("seq") + self.solidInterface_array_DispY.setType("seq") + self.solidInterface_array_DispZ.setType("seq") + self.solidInterface_array_DispX.setSizes( + self.nSolidInterfacePhysicalNodes + self.d_RBF + ) + self.solidInterface_array_DispY.setSizes( + self.nSolidInterfacePhysicalNodes + self.d_RBF + ) + self.solidInterface_array_DispZ.setSizes( + self.nSolidInterfacePhysicalNodes + self.d_RBF + ) self.solidInterface_array_DispX.set(0.0) self.solidInterface_array_DispY.set(0.0) self.solidInterface_array_DispZ.set(0.0) if self.have_MPI: - self.fluidInterface_array_DispX = PETSc.Vec().create(self.comm) - self.fluidInterface_array_DispY = PETSc.Vec().create(self.comm) - self.fluidInterface_array_DispZ = PETSc.Vec().create(self.comm) - self.fluidInterface_array_DispX.setType('mpi') - self.fluidInterface_array_DispY.setType('mpi') - self.fluidInterface_array_DispZ.setType('mpi') - else: - self.fluidInterface_array_DispX = PETSc.Vec().create() - self.fluidInterface_array_DispY = PETSc.Vec().create() - self.fluidInterface_array_DispZ = PETSc.Vec().create() - self.fluidInterface_array_DispX.setType('seq') - self.fluidInterface_array_DispY.setType('seq') - self.fluidInterface_array_DispZ.setType('seq') + self.fluidInterface_array_DispX = PETSc.Vec().create(self.comm) + self.fluidInterface_array_DispY = PETSc.Vec().create(self.comm) + self.fluidInterface_array_DispZ = PETSc.Vec().create(self.comm) + self.fluidInterface_array_DispX.setType("mpi") + self.fluidInterface_array_DispY.setType("mpi") + self.fluidInterface_array_DispZ.setType("mpi") + else: + self.fluidInterface_array_DispX = PETSc.Vec().create() + self.fluidInterface_array_DispY = PETSc.Vec().create() + self.fluidInterface_array_DispZ = PETSc.Vec().create() + self.fluidInterface_array_DispX.setType("seq") + self.fluidInterface_array_DispY.setType("seq") + self.fluidInterface_array_DispZ.setType("seq") self.fluidInterface_array_DispX.setSizes(self.nFluidInterfacePhysicalNodes) self.fluidInterface_array_DispY.setSizes(self.nFluidInterfacePhysicalNodes) self.fluidInterface_array_DispZ.setSizes(self.nFluidInterfacePhysicalNodes) @@ -459,19 +612,19 @@ def connect(self, FSI_config, FluidSolver, SolidSolver): self.fluidInterface_array_DispZ.set(0.0) if self.have_MPI: - self.fluidLoads_array_X = PETSc.Vec().create(self.comm) - self.fluidLoads_array_Y = PETSc.Vec().create(self.comm) - self.fluidLoads_array_Z = PETSc.Vec().create(self.comm) - self.fluidLoads_array_X.setType('mpi') - self.fluidLoads_array_Y.setType('mpi') - self.fluidLoads_array_Z.setType('mpi') - else: - self.fluidLoads_array_X = PETSc.Vec().create() - self.fluidLoads_array_Y = PETSc.Vec().create() - self.fluidLoads_array_Z = PETSc.Vec().create() - self.fluidLoads_array_X.setType('seq') - self.fluidLoads_array_Y.setType('seq') - self.fluidLoads_array_Z.setType('seq') + self.fluidLoads_array_X = PETSc.Vec().create(self.comm) + self.fluidLoads_array_Y = PETSc.Vec().create(self.comm) + self.fluidLoads_array_Z = PETSc.Vec().create(self.comm) + self.fluidLoads_array_X.setType("mpi") + self.fluidLoads_array_Y.setType("mpi") + self.fluidLoads_array_Z.setType("mpi") + else: + self.fluidLoads_array_X = PETSc.Vec().create() + self.fluidLoads_array_Y = PETSc.Vec().create() + self.fluidLoads_array_Z = PETSc.Vec().create() + self.fluidLoads_array_X.setType("seq") + self.fluidLoads_array_Y.setType("seq") + self.fluidLoads_array_Z.setType("seq") self.fluidLoads_array_X.setSizes(self.nFluidInterfacePhysicalNodes) self.fluidLoads_array_Y.setSizes(self.nFluidInterfacePhysicalNodes) self.fluidLoads_array_Z.setSizes(self.nFluidInterfacePhysicalNodes) @@ -480,88 +633,106 @@ def connect(self, FSI_config, FluidSolver, SolidSolver): self.fluidLoads_array_Z.set(0.0) if self.have_MPI: - self.solidLoads_array_X = PETSc.Vec().create(self.comm) - self.solidLoads_array_Y = PETSc.Vec().create(self.comm) - self.solidLoads_array_Z = PETSc.Vec().create(self.comm) - self.solidLoads_array_X.setType('mpi') - self.solidLoads_array_Y.setType('mpi') - self.solidLoads_array_Z.setType('mpi') - else: - self.solidLoads_array_X = PETSc.Vec().create() - self.solidLoads_array_Y = PETSc.Vec().create() - self.solidLoads_array_Z = PETSc.Vec().create() - self.solidLoads_array_X.setType('seq') - self.solidLoads_array_Y.setType('seq') - self.solidLoads_array_Z.setType('seq') - self.solidLoads_array_X.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) - self.solidLoads_array_Y.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) - self.solidLoads_array_Z.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) + self.solidLoads_array_X = PETSc.Vec().create(self.comm) + self.solidLoads_array_Y = PETSc.Vec().create(self.comm) + self.solidLoads_array_Z = PETSc.Vec().create(self.comm) + self.solidLoads_array_X.setType("mpi") + self.solidLoads_array_Y.setType("mpi") + self.solidLoads_array_Z.setType("mpi") + else: + self.solidLoads_array_X = PETSc.Vec().create() + self.solidLoads_array_Y = PETSc.Vec().create() + self.solidLoads_array_Z = PETSc.Vec().create() + self.solidLoads_array_X.setType("seq") + self.solidLoads_array_Y.setType("seq") + self.solidLoads_array_Z.setType("seq") + self.solidLoads_array_X.setSizes(self.nSolidInterfacePhysicalNodes + self.d_RBF) + self.solidLoads_array_Y.setSizes(self.nSolidInterfacePhysicalNodes + self.d_RBF) + self.solidLoads_array_Z.setSizes(self.nSolidInterfacePhysicalNodes + self.d_RBF) self.solidLoads_array_X.set(0.0) self.solidLoads_array_Y.set(0.0) self.solidLoads_array_Z.set(0.0) # --- Create the PETSc vectors required for parallel relaxed BGS algo (working for serial too) --- if self.have_MPI: - self.solidInterfaceResidual_array_X = PETSc.Vec().create(self.comm) - self.solidInterfaceResidual_array_Y = PETSc.Vec().create(self.comm) - self.solidInterfaceResidual_array_Z = PETSc.Vec().create(self.comm) - self.solidInterfaceResidual_array_X.setType('mpi') - self.solidInterfaceResidual_array_Y.setType('mpi') - self.solidInterfaceResidual_array_Z.setType('mpi') - else: - self.solidInterfaceResidual_array_X = PETSc.Vec().create() - self.solidInterfaceResidual_array_Y = PETSc.Vec().create() - self.solidInterfaceResidual_array_Z = PETSc.Vec().create() - self.solidInterfaceResidual_array_X.setType('seq') - self.solidInterfaceResidual_array_Y.setType('seq') - self.solidInterfaceResidual_array_Z.setType('seq') - self.solidInterfaceResidual_array_X.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) - self.solidInterfaceResidual_array_Y.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) - self.solidInterfaceResidual_array_Z.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) + self.solidInterfaceResidual_array_X = PETSc.Vec().create(self.comm) + self.solidInterfaceResidual_array_Y = PETSc.Vec().create(self.comm) + self.solidInterfaceResidual_array_Z = PETSc.Vec().create(self.comm) + self.solidInterfaceResidual_array_X.setType("mpi") + self.solidInterfaceResidual_array_Y.setType("mpi") + self.solidInterfaceResidual_array_Z.setType("mpi") + else: + self.solidInterfaceResidual_array_X = PETSc.Vec().create() + self.solidInterfaceResidual_array_Y = PETSc.Vec().create() + self.solidInterfaceResidual_array_Z = PETSc.Vec().create() + self.solidInterfaceResidual_array_X.setType("seq") + self.solidInterfaceResidual_array_Y.setType("seq") + self.solidInterfaceResidual_array_Z.setType("seq") + self.solidInterfaceResidual_array_X.setSizes( + self.nSolidInterfacePhysicalNodes + self.d_RBF + ) + self.solidInterfaceResidual_array_Y.setSizes( + self.nSolidInterfacePhysicalNodes + self.d_RBF + ) + self.solidInterfaceResidual_array_Z.setSizes( + self.nSolidInterfacePhysicalNodes + self.d_RBF + ) self.solidInterfaceResidual_array_X.set(0.0) self.solidInterfaceResidual_array_Y.set(0.0) self.solidInterfaceResidual_array_Z.set(0.0) if self.have_MPI: - self.solidInterfaceResidualnM1_array_X = PETSc.Vec().create(self.comm) - self.solidInterfaceResidualnM1_array_Y = PETSc.Vec().create(self.comm) - self.solidInterfaceResidualnM1_array_Z = PETSc.Vec().create(self.comm) - self.solidInterfaceResidualnM1_array_X.setType('mpi') - self.solidInterfaceResidualnM1_array_Y.setType('mpi') - self.solidInterfaceResidualnM1_array_Z.setType('mpi') - else: - self.solidInterfaceResidualnM1_array_X = PETSc.Vec().create() - self.solidInterfaceResidualnM1_array_Y = PETSc.Vec().create() - self.solidInterfaceResidualnM1_array_Z = PETSc.Vec().create() - self.solidInterfaceResidualnM1_array_X.setType('seq') - self.solidInterfaceResidualnM1_array_Y.setType('seq') - self.solidInterfaceResidualnM1_array_Z.setType('seq') - self.solidInterfaceResidualnM1_array_X.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) - self.solidInterfaceResidualnM1_array_Y.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) - self.solidInterfaceResidualnM1_array_Z.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) + self.solidInterfaceResidualnM1_array_X = PETSc.Vec().create(self.comm) + self.solidInterfaceResidualnM1_array_Y = PETSc.Vec().create(self.comm) + self.solidInterfaceResidualnM1_array_Z = PETSc.Vec().create(self.comm) + self.solidInterfaceResidualnM1_array_X.setType("mpi") + self.solidInterfaceResidualnM1_array_Y.setType("mpi") + self.solidInterfaceResidualnM1_array_Z.setType("mpi") + else: + self.solidInterfaceResidualnM1_array_X = PETSc.Vec().create() + self.solidInterfaceResidualnM1_array_Y = PETSc.Vec().create() + self.solidInterfaceResidualnM1_array_Z = PETSc.Vec().create() + self.solidInterfaceResidualnM1_array_X.setType("seq") + self.solidInterfaceResidualnM1_array_Y.setType("seq") + self.solidInterfaceResidualnM1_array_Z.setType("seq") + self.solidInterfaceResidualnM1_array_X.setSizes( + self.nSolidInterfacePhysicalNodes + self.d_RBF + ) + self.solidInterfaceResidualnM1_array_Y.setSizes( + self.nSolidInterfacePhysicalNodes + self.d_RBF + ) + self.solidInterfaceResidualnM1_array_Z.setSizes( + self.nSolidInterfacePhysicalNodes + self.d_RBF + ) self.solidInterfaceResidualnM1_array_X.set(0.0) self.solidInterfaceResidualnM1_array_Y.set(0.0) self.solidInterfaceResidualnM1_array_Z.set(0.0) - def interfaceMapping(self,FluidSolver, SolidSolver, FSI_config): + def interfaceMapping(self, FluidSolver, SolidSolver, FSI_config): """ Creates the one-to-one mapping between interfaces in case of matching meshes. Creates the interpolation rules between interfaces in case of non-matching meshes. """ if self.have_MPI: - myid = self.comm.Get_rank() - MPIsize = self.comm.Get_size() + myid = self.comm.Get_rank() + MPIsize = self.comm.Get_size() else: - myid = 0 - MPIsize = 1 + myid = 0 + MPIsize = 1 # --- Get the fluid interface from fluid solver on each partition --- GlobalIndex = int() localIndex = 0 fluidIndexing_temp = {} - self.localFluidInterface_array_X_init = np.zeros((self.nLocalFluidInterfacePhysicalNodes)) - self.localFluidInterface_array_Y_init = np.zeros((self.nLocalFluidInterfacePhysicalNodes)) - self.localFluidInterface_array_Z_init = np.zeros((self.nLocalFluidInterfacePhysicalNodes)) + self.localFluidInterface_array_X_init = np.zeros( + (self.nLocalFluidInterfacePhysicalNodes) + ) + self.localFluidInterface_array_Y_init = np.zeros( + (self.nLocalFluidInterfacePhysicalNodes) + ) + self.localFluidInterface_array_Z_init = np.zeros( + (self.nLocalFluidInterfacePhysicalNodes) + ) for iVertex in range(self.nLocalFluidInterfaceNodes): # Note that the fluid solver is separated in more processors outside the python script # thus when, from a core, we request for the vertices on the interface, we only obtain @@ -574,19 +745,21 @@ def interfaceMapping(self,FluidSolver, SolidSolver, FSI_config): else: posx, posy, posz = FluidSolver.InitialCoordinates().Get(iPoint) if GlobalIndex not in self.FluidHaloNodeList[myid].keys(): - fluidIndexing_temp[GlobalIndex] = self.__getGlobalIndex('fluid', myid, localIndex) - self.localFluidInterface_array_X_init[localIndex] = posx - self.localFluidInterface_array_Y_init[localIndex] = posy - self.localFluidInterface_array_Z_init[localIndex] = posz - localIndex += 1 + fluidIndexing_temp[GlobalIndex] = self.__getGlobalIndex( + "fluid", myid, localIndex + ) + self.localFluidInterface_array_X_init[localIndex] = posx + self.localFluidInterface_array_Y_init[localIndex] = posy + self.localFluidInterface_array_Z_init[localIndex] = posz + localIndex += 1 if self.have_MPI: - fluidIndexing_temp = self.comm.allgather(fluidIndexing_temp) - for ii in range(len(fluidIndexing_temp)): - for key, value in fluidIndexing_temp[ii].items(): - # This contains the link between the global index in python and that in SU2 - self.fluidIndexing[key] = value + fluidIndexing_temp = self.comm.allgather(fluidIndexing_temp) + for ii in range(len(fluidIndexing_temp)): + for key, value in fluidIndexing_temp[ii].items(): + # This contains the link between the global index in python and that in SU2 + self.fluidIndexing[key] = value else: - self.fluidIndexing = fluidIndexing_temp.copy() + self.fluidIndexing = fluidIndexing_temp.copy() del fluidIndexing_temp # --- Get the solid interface from solid solver on each partition --- @@ -596,181 +769,332 @@ def interfaceMapping(self,FluidSolver, SolidSolver, FSI_config): self.localSolidInterface_array_Y_init = np.zeros(self.nLocalSolidInterfaceNodes) self.localSolidInterface_array_Z_init = np.zeros(self.nLocalSolidInterfaceNodes) for iVertex in range(self.nLocalSolidInterfaceNodes): - GlobalIndex = SolidSolver.getVertexGlobalIndex(self.solidInterfaceIdentifier, iVertex) - posx, posy, posz = SolidSolver.getInterfaceNodePosInit(self.solidInterfaceIdentifier, iVertex) - if GlobalIndex not in self.SolidHaloNodeList[myid].keys(): - solidIndexing_temp[GlobalIndex] = self.__getGlobalIndex('solid', myid, localIndex) - self.localSolidInterface_array_X_init[localIndex] = posx - self.localSolidInterface_array_Y_init[localIndex] = posy - self.localSolidInterface_array_Z_init[localIndex] = posz - localIndex += 1 + GlobalIndex = SolidSolver.getVertexGlobalIndex( + self.solidInterfaceIdentifier, iVertex + ) + posx, posy, posz = SolidSolver.getInterfaceNodePosInit( + self.solidInterfaceIdentifier, iVertex + ) + if GlobalIndex not in self.SolidHaloNodeList[myid].keys(): + solidIndexing_temp[GlobalIndex] = self.__getGlobalIndex( + "solid", myid, localIndex + ) + self.localSolidInterface_array_X_init[localIndex] = posx + self.localSolidInterface_array_Y_init[localIndex] = posy + self.localSolidInterface_array_Z_init[localIndex] = posz + localIndex += 1 if self.have_MPI: - solidIndexing_temp = self.comm.allgather(solidIndexing_temp) - for ii in range(len(solidIndexing_temp)): - for key, value in solidIndexing_temp[ii].items(): - self.solidIndexing[key] = value + solidIndexing_temp = self.comm.allgather(solidIndexing_temp) + for ii in range(len(solidIndexing_temp)): + for key, value in solidIndexing_temp[ii].items(): + self.solidIndexing[key] = value else: - self.solidIndexing = solidIndexing_temp.copy() + self.solidIndexing = solidIndexing_temp.copy() del solidIndexing_temp - # --- Create the PETSc parallel interpolation matrix --- - if FSI_config['MATCHING_MESH'] == 'NO' and (FSI_config['MESH_INTERP_METHOD'] == 'RBF' or FSI_config['MESH_INTERP_METHOD'] == 'TPS'): - if self.have_MPI: - self.MappingMatrixA = PETSc.Mat().create(self.comm) - self.MappingMatrixB = PETSc.Mat().create(self.comm) - self.MappingMatrixA_T = PETSc.Mat().create(self.comm) - self.MappingMatrixB_T = PETSc.Mat().create(self.comm) - if FSI_config['MESH_INTERP_METHOD'] == 'RBF' : - self.MappingMatrixA.setType('mpiaij') - self.MappingMatrixB.setType('mpiaij') - self.MappingMatrixA_T.setType('mpiaij') - self.MappingMatrixB_T.setType('mpiaij') + if FSI_config["MATCHING_MESH"] == "NO" and ( + FSI_config["MESH_INTERP_METHOD"] == "RBF" + or FSI_config["MESH_INTERP_METHOD"] == "TPS" + ): + if self.have_MPI: + self.MappingMatrixA = PETSc.Mat().create(self.comm) + self.MappingMatrixB = PETSc.Mat().create(self.comm) + self.MappingMatrixA_T = PETSc.Mat().create(self.comm) + self.MappingMatrixB_T = PETSc.Mat().create(self.comm) + if FSI_config["MESH_INTERP_METHOD"] == "RBF": + self.MappingMatrixA.setType("mpiaij") + self.MappingMatrixB.setType("mpiaij") + self.MappingMatrixA_T.setType("mpiaij") + self.MappingMatrixB_T.setType("mpiaij") + else: + self.MappingMatrixA.setType("mpiaij") + self.MappingMatrixB.setType("mpiaij") + self.MappingMatrixA_T.setType("mpiaij") + self.MappingMatrixB_T.setType("mpiaij") else: - self.MappingMatrixA.setType('mpiaij') - self.MappingMatrixB.setType('mpiaij') - self.MappingMatrixA_T.setType('mpiaij') - self.MappingMatrixB_T.setType('mpiaij') - else: - self.MappingMatrixA = PETSc.Mat().create() - self.MappingMatrixB = PETSc.Mat().create() - self.MappingMatrixA_T = PETSc.Mat().create() - self.MappingMatrixB_T = PETSc.Mat().create() - if FSI_config['MESH_INTERP_METHOD'] == 'RBF' : - self.MappingMatrixA.setType('aij') - self.MappingMatrixB.setType('aij') - self.MappingMatrixA_T.setType('aij') - self.MappingMatrixB_T.setType('aij') + self.MappingMatrixA = PETSc.Mat().create() + self.MappingMatrixB = PETSc.Mat().create() + self.MappingMatrixA_T = PETSc.Mat().create() + self.MappingMatrixB_T = PETSc.Mat().create() + if FSI_config["MESH_INTERP_METHOD"] == "RBF": + self.MappingMatrixA.setType("aij") + self.MappingMatrixB.setType("aij") + self.MappingMatrixA_T.setType("aij") + self.MappingMatrixB_T.setType("aij") + else: + self.MappingMatrixA.setType("aij") + self.MappingMatrixB.setType("aij") + self.MappingMatrixA_T.setType("aij") + self.MappingMatrixB_T.setType("aij") + self.MappingMatrixA.setSizes( + ( + self.nSolidInterfacePhysicalNodes + self.d_RBF, + self.nSolidInterfacePhysicalNodes + self.d_RBF, + ) + ) + self.MappingMatrixA.setUp() + self.MappingMatrixA.setOption( + PETSc.Mat().Option.NEW_NONZERO_ALLOCATION_ERR, False + ) + self.MappingMatrixB.setSizes( + ( + self.nFluidInterfacePhysicalNodes, + self.nSolidInterfacePhysicalNodes + self.d_RBF, + ) + ) + self.MappingMatrixB.setUp() + self.MappingMatrixB.setOption( + PETSc.Mat().Option.NEW_NONZERO_ALLOCATION_ERR, False + ) + self.MappingMatrixA_T.setSizes( + ( + self.nSolidInterfacePhysicalNodes + self.d_RBF, + self.nSolidInterfacePhysicalNodes + self.d_RBF, + ) + ) + self.MappingMatrixA_T.setUp() + self.MappingMatrixA_T.setOption( + PETSc.Mat().Option.NEW_NONZERO_ALLOCATION_ERR, False + ) + self.MappingMatrixB_T.setSizes( + ( + self.nSolidInterfacePhysicalNodes + self.d_RBF, + self.nFluidInterfacePhysicalNodes, + ) + ) + self.MappingMatrixB_T.setUp() + self.MappingMatrixB_T.setOption( + PETSc.Mat().Option.NEW_NONZERO_ALLOCATION_ERR, False + ) + else: + if self.have_MPI: + self.MappingMatrix = PETSc.Mat().create(self.comm) + self.MappingMatrix_T = PETSc.Mat().create(self.comm) + self.MappingMatrix.setType("mpiaij") + self.MappingMatrix_T.setType("mpiaij") else: - self.MappingMatrixA.setType('aij') - self.MappingMatrixB.setType('aij') - self.MappingMatrixA_T.setType('aij') - self.MappingMatrixB_T.setType('aij') - self.MappingMatrixA.setSizes((self.nSolidInterfacePhysicalNodes+self.d_RBF, self.nSolidInterfacePhysicalNodes+self.d_RBF)) - self.MappingMatrixA.setUp() - self.MappingMatrixA.setOption(PETSc.Mat().Option.NEW_NONZERO_ALLOCATION_ERR, False) - self.MappingMatrixB.setSizes((self.nFluidInterfacePhysicalNodes, self.nSolidInterfacePhysicalNodes+self.d_RBF)) - self.MappingMatrixB.setUp() - self.MappingMatrixB.setOption(PETSc.Mat().Option.NEW_NONZERO_ALLOCATION_ERR, False) - self.MappingMatrixA_T.setSizes((self.nSolidInterfacePhysicalNodes+self.d_RBF, self.nSolidInterfacePhysicalNodes+self.d_RBF)) - self.MappingMatrixA_T.setUp() - self.MappingMatrixA_T.setOption(PETSc.Mat().Option.NEW_NONZERO_ALLOCATION_ERR, False) - self.MappingMatrixB_T.setSizes((self.nSolidInterfacePhysicalNodes+self.d_RBF, self.nFluidInterfacePhysicalNodes)) - self.MappingMatrixB_T.setUp() - self.MappingMatrixB_T.setOption(PETSc.Mat().Option.NEW_NONZERO_ALLOCATION_ERR, False) - else: - if self.have_MPI: - self.MappingMatrix = PETSc.Mat().create(self.comm) - self.MappingMatrix_T = PETSc.Mat().create(self.comm) - self.MappingMatrix.setType('mpiaij') - self.MappingMatrix_T.setType('mpiaij') - else: - self.MappingMatrix = PETSc.Mat().create() - self.MappingMatrix_T = PETSc.Mat().create() - self.MappingMatrix.setType('aij') - self.MappingMatrix_T.setType('aij') - self.MappingMatrix.setSizes((self.nFluidInterfacePhysicalNodes, self.nSolidInterfacePhysicalNodes)) - self.MappingMatrix.setUp() - self.MappingMatrix.setOption(PETSc.Mat().Option.NEW_NONZERO_ALLOCATION_ERR, False) - self.MappingMatrix_T.setSizes((self.nSolidInterfacePhysicalNodes, self.nFluidInterfacePhysicalNodes)) - self.MappingMatrix_T.setUp() - self.MappingMatrix_T.setOption(PETSc.Mat().Option.NEW_NONZERO_ALLOCATION_ERR, False) - + self.MappingMatrix = PETSc.Mat().create() + self.MappingMatrix_T = PETSc.Mat().create() + self.MappingMatrix.setType("aij") + self.MappingMatrix_T.setType("aij") + self.MappingMatrix.setSizes( + (self.nFluidInterfacePhysicalNodes, self.nSolidInterfacePhysicalNodes) + ) + self.MappingMatrix.setUp() + self.MappingMatrix.setOption( + PETSc.Mat().Option.NEW_NONZERO_ALLOCATION_ERR, False + ) + self.MappingMatrix_T.setSizes( + (self.nSolidInterfacePhysicalNodes, self.nFluidInterfacePhysicalNodes) + ) + self.MappingMatrix_T.setUp() + self.MappingMatrix_T.setOption( + PETSc.Mat().Option.NEW_NONZERO_ALLOCATION_ERR, False + ) # --- Fill the interpolation matrix in parallel (working in serial too) --- - if FSI_config['MATCHING_MESH'] == 'NO' and (FSI_config['MESH_INTERP_METHOD'] == 'RBF' or FSI_config['MESH_INTERP_METHOD'] == 'TPS'): - self.MPIPrint('Building interpolation matrices...') - if self.have_MPI: - for iProc in self.solidInterfaceProcessors: - if myid == iProc: - for jProc in self.solidInterfaceProcessors: - if jProc != iProc: - self.comm.Send(self.localSolidInterface_array_X_init, dest=jProc, tag=1) - self.comm.Send(self.localSolidInterface_array_Y_init, dest=jProc, tag=2) - self.comm.Send(self.localSolidInterface_array_Z_init, dest=jProc, tag=3) - else: - solidInterfaceBuffRcv_X = np.copy(self.localSolidInterface_array_X_init) - solidInterfaceBuffRcv_Y = np.copy(self.localSolidInterface_array_Y_init) - solidInterfaceBuffRcv_Z = np.copy(self.localSolidInterface_array_Z_init) - if myid in self.solidInterfaceProcessors: - if myid != iProc: - sizeOfBuff = self.solidPhysicalInterfaceNodesDistribution[iProc] - solidInterfaceBuffRcv_X = np.empty(sizeOfBuff, dtype=np.float64) - solidInterfaceBuffRcv_Y = np.empty(sizeOfBuff, dtype=np.float64) - solidInterfaceBuffRcv_Z = np.empty(sizeOfBuff, dtype=np.float64) - self.comm.Recv(solidInterfaceBuffRcv_X, source=iProc, tag=1) - self.comm.Recv(solidInterfaceBuffRcv_Y, source=iProc, tag=2) - self.comm.Recv(solidInterfaceBuffRcv_Z, source=iProc, tag=3) - if FSI_config['MESH_INTERP_METHOD'] == 'RBF': - self.RBFMeshMapping_A(solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, solidInterfaceBuffRcv_Z, iProc, self.RBF_rad) - else: - self.TPSMeshMapping_A(solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, solidInterfaceBuffRcv_Z, iProc) - else: - if FSI_config['MESH_INTERP_METHOD'] == 'RBF': - self.RBFMeshMapping_A(self.localSolidInterface_array_X_init, self.localSolidInterface_array_Y_init, self.localSolidInterface_array_Z_init, 0, self.RBF_rad) + if FSI_config["MATCHING_MESH"] == "NO" and ( + FSI_config["MESH_INTERP_METHOD"] == "RBF" + or FSI_config["MESH_INTERP_METHOD"] == "TPS" + ): + self.MPIPrint("Building interpolation matrices...") + if self.have_MPI: + for iProc in self.solidInterfaceProcessors: + if myid == iProc: + for jProc in self.solidInterfaceProcessors: + if jProc != iProc: + self.comm.Send( + self.localSolidInterface_array_X_init, + dest=jProc, + tag=1, + ) + self.comm.Send( + self.localSolidInterface_array_Y_init, + dest=jProc, + tag=2, + ) + self.comm.Send( + self.localSolidInterface_array_Z_init, + dest=jProc, + tag=3, + ) + else: + solidInterfaceBuffRcv_X = np.copy( + self.localSolidInterface_array_X_init + ) + solidInterfaceBuffRcv_Y = np.copy( + self.localSolidInterface_array_Y_init + ) + solidInterfaceBuffRcv_Z = np.copy( + self.localSolidInterface_array_Z_init + ) + if myid in self.solidInterfaceProcessors: + if myid != iProc: + sizeOfBuff = self.solidPhysicalInterfaceNodesDistribution[ + iProc + ] + solidInterfaceBuffRcv_X = np.empty( + sizeOfBuff, dtype=np.float64 + ) + solidInterfaceBuffRcv_Y = np.empty( + sizeOfBuff, dtype=np.float64 + ) + solidInterfaceBuffRcv_Z = np.empty( + sizeOfBuff, dtype=np.float64 + ) + self.comm.Recv(solidInterfaceBuffRcv_X, source=iProc, tag=1) + self.comm.Recv(solidInterfaceBuffRcv_Y, source=iProc, tag=2) + self.comm.Recv(solidInterfaceBuffRcv_Z, source=iProc, tag=3) + if FSI_config["MESH_INTERP_METHOD"] == "RBF": + self.RBFMeshMapping_A( + solidInterfaceBuffRcv_X, + solidInterfaceBuffRcv_Y, + solidInterfaceBuffRcv_Z, + iProc, + self.RBF_rad, + ) + else: + self.TPSMeshMapping_A( + solidInterfaceBuffRcv_X, + solidInterfaceBuffRcv_Y, + solidInterfaceBuffRcv_Z, + iProc, + ) else: - self.TPSMeshMapping_A(self.localSolidInterface_array_X_init, self.localSolidInterface_array_Y_init, self.localSolidInterface_array_Z_init, 0) - self.MappingMatrixA.assemblyBegin() - self.MappingMatrixA.assemblyEnd() - self.MappingMatrixA_T.assemblyBegin() - self.MappingMatrixA_T.assemblyEnd() - self.MPIPrint('Matrix A is built.') - else: - self.MPIPrint("Building interpolation matrix...") + if FSI_config["MESH_INTERP_METHOD"] == "RBF": + self.RBFMeshMapping_A( + self.localSolidInterface_array_X_init, + self.localSolidInterface_array_Y_init, + self.localSolidInterface_array_Z_init, + 0, + self.RBF_rad, + ) + else: + self.TPSMeshMapping_A( + self.localSolidInterface_array_X_init, + self.localSolidInterface_array_Y_init, + self.localSolidInterface_array_Z_init, + 0, + ) + self.MappingMatrixA.assemblyBegin() + self.MappingMatrixA.assemblyEnd() + self.MappingMatrixA_T.assemblyBegin() + self.MappingMatrixA_T.assemblyEnd() + self.MPIPrint("Matrix A is built.") + else: + self.MPIPrint("Building interpolation matrix...") self.MPIBarrier() if self.have_MPI: - for iProc in self.solidInterfaceProcessors: - if myid == iProc: - for jProc in self.fluidInterfaceProcessors: - if jProc != iProc: - self.comm.Send(self.localSolidInterface_array_X_init, dest=jProc, tag=1) - self.comm.Send(self.localSolidInterface_array_Y_init, dest=jProc, tag=2) - self.comm.Send(self.localSolidInterface_array_Z_init, dest=jProc, tag=3) - else: - solidInterfaceBuffRcv_X = np.copy(self.localSolidInterface_array_X_init) - solidInterfaceBuffRcv_Y = np.copy(self.localSolidInterface_array_Y_init) - solidInterfaceBuffRcv_Z = np.copy(self.localSolidInterface_array_Z_init) - if myid in self.fluidInterfaceProcessors: - if myid != iProc: - sizeOfBuff = self.solidPhysicalInterfaceNodesDistribution[iProc] - solidInterfaceBuffRcv_X = np.empty(sizeOfBuff, dtype=np.float64) - solidInterfaceBuffRcv_Y = np.empty(sizeOfBuff, dtype=np.float64) - solidInterfaceBuffRcv_Z = np.empty(sizeOfBuff, dtype=np.float64) - self.comm.Recv(solidInterfaceBuffRcv_X, source=iProc, tag=1) - self.comm.Recv(solidInterfaceBuffRcv_Y, source=iProc, tag=2) - self.comm.Recv(solidInterfaceBuffRcv_Z, source=iProc, tag=3) - if FSI_config['MATCHING_MESH'] == 'NO': - if FSI_config['MESH_INTERP_METHOD'] == 'RBF': - self.RBFMeshMapping_B(solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, solidInterfaceBuffRcv_Z, iProc, self.RBF_rad) - elif FSI_config['MESH_INTERP_METHOD'] == 'TPS': - self.TPSMeshMapping_B(solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, solidInterfaceBuffRcv_Z, iProc) + for iProc in self.solidInterfaceProcessors: + if myid == iProc: + for jProc in self.fluidInterfaceProcessors: + if jProc != iProc: + self.comm.Send( + self.localSolidInterface_array_X_init, dest=jProc, tag=1 + ) + self.comm.Send( + self.localSolidInterface_array_Y_init, dest=jProc, tag=2 + ) + self.comm.Send( + self.localSolidInterface_array_Z_init, dest=jProc, tag=3 + ) + else: + solidInterfaceBuffRcv_X = np.copy( + self.localSolidInterface_array_X_init + ) + solidInterfaceBuffRcv_Y = np.copy( + self.localSolidInterface_array_Y_init + ) + solidInterfaceBuffRcv_Z = np.copy( + self.localSolidInterface_array_Z_init + ) + if myid in self.fluidInterfaceProcessors: + if myid != iProc: + sizeOfBuff = self.solidPhysicalInterfaceNodesDistribution[iProc] + solidInterfaceBuffRcv_X = np.empty(sizeOfBuff, dtype=np.float64) + solidInterfaceBuffRcv_Y = np.empty(sizeOfBuff, dtype=np.float64) + solidInterfaceBuffRcv_Z = np.empty(sizeOfBuff, dtype=np.float64) + self.comm.Recv(solidInterfaceBuffRcv_X, source=iProc, tag=1) + self.comm.Recv(solidInterfaceBuffRcv_Y, source=iProc, tag=2) + self.comm.Recv(solidInterfaceBuffRcv_Z, source=iProc, tag=3) + if FSI_config["MATCHING_MESH"] == "NO": + if FSI_config["MESH_INTERP_METHOD"] == "RBF": + self.RBFMeshMapping_B( + solidInterfaceBuffRcv_X, + solidInterfaceBuffRcv_Y, + solidInterfaceBuffRcv_Z, + iProc, + self.RBF_rad, + ) + elif FSI_config["MESH_INTERP_METHOD"] == "TPS": + self.TPSMeshMapping_B( + solidInterfaceBuffRcv_X, + solidInterfaceBuffRcv_Y, + solidInterfaceBuffRcv_Z, + iProc, + ) + else: + self.NearestNeighboorMeshMapping( + solidInterfaceBuffRcv_X, + solidInterfaceBuffRcv_Y, + solidInterfaceBuffRcv_Z, + iProc, + ) + else: + self.matchingMeshMapping( + solidInterfaceBuffRcv_X, + solidInterfaceBuffRcv_Y, + solidInterfaceBuffRcv_Z, + iProc, + ) + else: + if FSI_config["MATCHING_MESH"] == "NO": + if FSI_config["MESH_INTERP_METHOD"] == "RBF": + self.RBFMeshMapping_B( + self.localSolidInterface_array_X_init, + self.localSolidInterface_array_Y_init, + self.localSolidInterface_array_Z_init, + 0, + self.RBF_rad, + ) + elif FSI_config["MESH_INTERP_METHOD"] == "TPS": + self.TPSMeshMapping_B( + self.localSolidInterface_array_X_init, + self.localSolidInterface_array_Y_init, + self.localSolidInterface_array_Z_init, + 0, + ) else: - self.NearestNeighboorMeshMapping(solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, solidInterfaceBuffRcv_Z, iProc) - else: - self.matchingMeshMapping(solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, solidInterfaceBuffRcv_Z, iProc) - else: - if FSI_config['MATCHING_MESH'] == 'NO': - if FSI_config['MESH_INTERP_METHOD'] == 'RBF': - self.RBFMeshMapping_B(self.localSolidInterface_array_X_init, self.localSolidInterface_array_Y_init, self.localSolidInterface_array_Z_init, 0, self.RBF_rad) - elif FSI_config['MESH_INTERP_METHOD'] == 'TPS' : - self.TPSMeshMapping_B(self.localSolidInterface_array_X_init, self.localSolidInterface_array_Y_init, self.localSolidInterface_array_Z_init, 0) + self.NearestNeighboorMeshMapping( + self.localSolidInterface_array_X_init, + self.localSolidInterface_array_Y_init, + self.localSolidInterface_array_Z_init, + 0, + ) else: - self.NearestNeighboorMeshMapping(self.localSolidInterface_array_X_init, self.localSolidInterface_array_Y_init, self.localSolidInterface_array_Z_init, 0) - else: - self.matchingMeshMapping(self.localSolidInterface_array_X_init, self.localSolidInterface_array_Y_init, self.localSolidInterface_array_Z_init, 0) - - if FSI_config['MATCHING_MESH'] == 'NO' and (FSI_config['MESH_INTERP_METHOD'] == 'RBF' or FSI_config['MESH_INTERP_METHOD'] == 'TPS'): - self.MappingMatrixB.assemblyBegin() - self.MappingMatrixB.assemblyEnd() - self.MappingMatrixB_T.assemblyBegin() - self.MappingMatrixB_T.assemblyEnd() - self.MPIPrint('Matrix B is built.') - else: - self.MappingMatrix.assemblyBegin() - self.MappingMatrix.assemblyEnd() - self.MappingMatrix_T.assemblyBegin() - self.MappingMatrix_T.assemblyEnd() - self.MPIPrint("Interpolation matrix is built.") + self.matchingMeshMapping( + self.localSolidInterface_array_X_init, + self.localSolidInterface_array_Y_init, + self.localSolidInterface_array_Z_init, + 0, + ) + + if FSI_config["MATCHING_MESH"] == "NO" and ( + FSI_config["MESH_INTERP_METHOD"] == "RBF" + or FSI_config["MESH_INTERP_METHOD"] == "TPS" + ): + self.MappingMatrixB.assemblyBegin() + self.MappingMatrixB.assemblyEnd() + self.MappingMatrixB_T.assemblyBegin() + self.MappingMatrixB_T.assemblyEnd() + self.MPIPrint("Matrix B is built.") + else: + self.MappingMatrix.assemblyBegin() + self.MappingMatrix.assemblyEnd() + self.MappingMatrix_T.assemblyBegin() + self.MappingMatrix_T.assemblyEnd() + self.MPIPrint("Interpolation matrix is built.") self.MPIBarrier() @@ -781,14 +1105,20 @@ def interfaceMapping(self,FluidSolver, SolidSolver, FSI_config): del self.localFluidInterface_array_Y_init del self.localFluidInterface_array_Z_init - def matchingMeshMapping(self,solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, solidInterfaceBuffRcv_Z, iProc): + def matchingMeshMapping( + self, + solidInterfaceBuffRcv_X, + solidInterfaceBuffRcv_Y, + solidInterfaceBuffRcv_Z, + iProc, + ): """ Fill the mapping matrix in case of matching meshes at the f/s interface. """ if self.have_MPI: - myid = self.comm.Get_rank() + myid = self.comm.Get_rank() else: - myid = 0 + myid = 0 # --- Instantiate the spatial indexing --- prop_index = index.Property() @@ -798,39 +1128,65 @@ def matchingMeshMapping(self,solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, s nSolidNodes = solidInterfaceBuffRcv_X.shape[0] for jVertex in range(nSolidNodes): - posX = solidInterfaceBuffRcv_X[jVertex] - posY = solidInterfaceBuffRcv_Y[jVertex] - posZ = solidInterfaceBuffRcv_Z[jVertex] - if self.nDim == 2 : - SolidSpatialTree.add(jVertex, (posX, posY)) - else : - SolidSpatialTree.add(jVertex, (posX, posY, posZ)) + posX = solidInterfaceBuffRcv_X[jVertex] + posY = solidInterfaceBuffRcv_Y[jVertex] + posZ = solidInterfaceBuffRcv_Z[jVertex] + if self.nDim == 2: + SolidSpatialTree.add(jVertex, (posX, posY)) + else: + SolidSpatialTree.add(jVertex, (posX, posY, posZ)) if self.nFluidInterfacePhysicalNodes != self.nSolidInterfacePhysicalNodes: - raise Exception("Fluid and solid interface must have the same number of nodes for matching meshes ! ") + raise Exception( + "Fluid and solid interface must have the same number of nodes for matching meshes ! " + ) # --- For each fluid interface node, find the nearest solid interface node and fill the boolean mapping matrix --- for iVertexFluid in range(self.nLocalFluidInterfacePhysicalNodes): - posX = self.localFluidInterface_array_X_init[iVertexFluid] - posY = self.localFluidInterface_array_Y_init[iVertexFluid] - posZ = self.localFluidInterface_array_Z_init[iVertexFluid] - if self.nDim == 2: - neighboors = list(SolidSpatialTree.nearest((posX, posY),1)) - elif self.nDim == 3: - neighboors = list(SolidSpatialTree.nearest((posX, posY, posZ),1)) - jVertexSolid = neighboors[0] - # Check if the distance is small enough to ensure coincidence - NodeA = np.array([posX, posY, posZ]) - NodeB = np.array([solidInterfaceBuffRcv_X[jVertexSolid], solidInterfaceBuffRcv_Y[jVertexSolid], solidInterfaceBuffRcv_Z[jVertexSolid]]) - distance = spdist.euclidean(NodeA, NodeB) - iGlobalVertexFluid = self.__getGlobalIndex('fluid', myid, iVertexFluid) - jGlobalVertexSolid = self.__getGlobalIndex('solid', iProc, jVertexSolid) - if distance > 1e-6: - print("WARNING : Tolerance for matching meshes is not matched between node F{} and S{} : ({}, {}, {})<-->({}, {}, {}) , DISTANCE : {} !".format(iGlobalVertexFluid,jGlobalVertexSolid,posX, posY, posZ,solidInterfaceBuffRcv_X[jVertexSolid], solidInterfaceBuffRcv_Y[jVertexSolid], solidInterfaceBuffRcv_Z[jVertexSolid], distance)) - self.MappingMatrix.setValue(iGlobalVertexFluid,jGlobalVertexSolid,1.0) - self.MappingMatrix_T.setValue(jGlobalVertexSolid, iGlobalVertexFluid,1.0) - - def NearestNeighboorMeshMapping(self, solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, solidInterfaceBuffRcv_Z, iProc): + posX = self.localFluidInterface_array_X_init[iVertexFluid] + posY = self.localFluidInterface_array_Y_init[iVertexFluid] + posZ = self.localFluidInterface_array_Z_init[iVertexFluid] + if self.nDim == 2: + neighboors = list(SolidSpatialTree.nearest((posX, posY), 1)) + elif self.nDim == 3: + neighboors = list(SolidSpatialTree.nearest((posX, posY, posZ), 1)) + jVertexSolid = neighboors[0] + # Check if the distance is small enough to ensure coincidence + NodeA = np.array([posX, posY, posZ]) + NodeB = np.array( + [ + solidInterfaceBuffRcv_X[jVertexSolid], + solidInterfaceBuffRcv_Y[jVertexSolid], + solidInterfaceBuffRcv_Z[jVertexSolid], + ] + ) + distance = spdist.euclidean(NodeA, NodeB) + iGlobalVertexFluid = self.__getGlobalIndex("fluid", myid, iVertexFluid) + jGlobalVertexSolid = self.__getGlobalIndex("solid", iProc, jVertexSolid) + if distance > 1e-6: + print( + "WARNING : Tolerance for matching meshes is not matched between node F{} and S{} : ({}, {}, {})<-->({}, {}, {}) , DISTANCE : {} !".format( + iGlobalVertexFluid, + jGlobalVertexSolid, + posX, + posY, + posZ, + solidInterfaceBuffRcv_X[jVertexSolid], + solidInterfaceBuffRcv_Y[jVertexSolid], + solidInterfaceBuffRcv_Z[jVertexSolid], + distance, + ) + ) + self.MappingMatrix.setValue(iGlobalVertexFluid, jGlobalVertexSolid, 1.0) + self.MappingMatrix_T.setValue(jGlobalVertexSolid, iGlobalVertexFluid, 1.0) + + def NearestNeighboorMeshMapping( + self, + solidInterfaceBuffRcv_X, + solidInterfaceBuffRcv_Y, + solidInterfaceBuffRcv_Z, + iProc, + ): """ Interpolation based on the nearest neighboor. For each node, the mesh is scanned to find the closed node to the first @@ -838,9 +1194,9 @@ def NearestNeighboorMeshMapping(self, solidInterfaceBuffRcv_X, solidInterfaceBuf """ if self.have_MPI: - myid = self.comm.Get_rank() + myid = self.comm.Get_rank() else: - myid = 0 + myid = 0 # --- Instantiate the spatial indexing --- prop_index = index.Property() @@ -850,30 +1206,37 @@ def NearestNeighboorMeshMapping(self, solidInterfaceBuffRcv_X, solidInterfaceBuf nSolidNodes = solidInterfaceBuffRcv_X.shape[0] for jVertex in range(nSolidNodes): - posX = solidInterfaceBuffRcv_X[jVertex] - posY = solidInterfaceBuffRcv_Y[jVertex] - posZ = solidInterfaceBuffRcv_Z[jVertex] - if self.nDim == 2 : - SolidSpatialTree.add(jVertex, (posX, posY)) - else : - SolidSpatialTree.add(jVertex, (posX, posY, posZ)) + posX = solidInterfaceBuffRcv_X[jVertex] + posY = solidInterfaceBuffRcv_Y[jVertex] + posZ = solidInterfaceBuffRcv_Z[jVertex] + if self.nDim == 2: + SolidSpatialTree.add(jVertex, (posX, posY)) + else: + SolidSpatialTree.add(jVertex, (posX, posY, posZ)) # --- For each fluid interface node, find the nearest solid interface node and fill the boolean mapping matrix --- for iVertexFluid in range(self.nLocalFluidInterfacePhysicalNodes): - posX = self.localFluidInterface_array_X_init[iVertexFluid] - posY = self.localFluidInterface_array_Y_init[iVertexFluid] - posZ = self.localFluidInterface_array_Z_init[iVertexFluid] - if self.nDim == 2: - neighboors = list(SolidSpatialTree.nearest((posX, posY),1)) - elif self.nDim == 3: - neighboors = list(SolidSpatialTree.nearest((posX, posY, posZ),1)) - jVertexSolid = neighboors[0] - iGlobalVertexFluid = self.__getGlobalIndex('fluid', myid, iVertexFluid) - jGlobalVertexSolid = self.__getGlobalIndex('solid', iProc, jVertexSolid) - self.MappingMatrix.setValue(iGlobalVertexFluid,jGlobalVertexSolid,1.0) - self.MappingMatrix_T.setValue(jGlobalVertexSolid, iGlobalVertexFluid,1.0) - - def RBFMeshMapping_A(self, solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, solidInterfaceBuffRcv_Z, iProc, rad): + posX = self.localFluidInterface_array_X_init[iVertexFluid] + posY = self.localFluidInterface_array_Y_init[iVertexFluid] + posZ = self.localFluidInterface_array_Z_init[iVertexFluid] + if self.nDim == 2: + neighboors = list(SolidSpatialTree.nearest((posX, posY), 1)) + elif self.nDim == 3: + neighboors = list(SolidSpatialTree.nearest((posX, posY, posZ), 1)) + jVertexSolid = neighboors[0] + iGlobalVertexFluid = self.__getGlobalIndex("fluid", myid, iVertexFluid) + jGlobalVertexSolid = self.__getGlobalIndex("solid", iProc, jVertexSolid) + self.MappingMatrix.setValue(iGlobalVertexFluid, jGlobalVertexSolid, 1.0) + self.MappingMatrix_T.setValue(jGlobalVertexSolid, iGlobalVertexFluid, 1.0) + + def RBFMeshMapping_A( + self, + solidInterfaceBuffRcv_X, + solidInterfaceBuffRcv_Y, + solidInterfaceBuffRcv_Z, + iProc, + rad, + ): """ First part of the RBF mapping. This method provides the matrix required to obtain, from the structural displacements, the loadings of the kernel @@ -881,9 +1244,9 @@ def RBFMeshMapping_A(self, solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, sol """ if self.have_MPI: - myid = self.comm.Get_rank() + myid = self.comm.Get_rank() else: - myid = 0 + myid = 0 # --- Instantiate the spatial indexing --- prop_index = index.Property() @@ -893,52 +1256,86 @@ def RBFMeshMapping_A(self, solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, sol nSolidNodes = solidInterfaceBuffRcv_X.shape[0] for jVertex in range(nSolidNodes): - posX = solidInterfaceBuffRcv_X[jVertex] - posY = solidInterfaceBuffRcv_Y[jVertex] - posZ = solidInterfaceBuffRcv_Z[jVertex] - if self.nDim == 2 : - SolidSpatialTree.add(jVertex, (posX, posY)) - else : - SolidSpatialTree.add(jVertex, (posX, posY, posZ)) + posX = solidInterfaceBuffRcv_X[jVertex] + posY = solidInterfaceBuffRcv_Y[jVertex] + posZ = solidInterfaceBuffRcv_Z[jVertex] + if self.nDim == 2: + SolidSpatialTree.add(jVertex, (posX, posY)) + else: + SolidSpatialTree.add(jVertex, (posX, posY, posZ)) for iVertexSolid in range(self.nLocalSolidInterfacePhysicalNodes): - posX = self.localSolidInterface_array_X_init[iVertexSolid] - posY = self.localSolidInterface_array_Y_init[iVertexSolid] - posZ = self.localSolidInterface_array_Z_init[iVertexSolid] - NodeA = np.array([posX, posY, posZ]) - iGlobalVertexSolid = self.__getGlobalIndex('solid', myid, iVertexSolid) - if self.nDim == 2: - neighboors = list(SolidSpatialTree.intersection((posX-rad, posY-rad, posX+rad, posY+rad))) - elif self.nDim == 3: - neighboors = list(SolidSpatialTree.intersection((posX-rad, posY-rad, posZ-rad, posX+rad, posY+rad, posZ+rad))) - for jVertexSolid in neighboors: - NodeB = np.array([solidInterfaceBuffRcv_X[jVertexSolid], solidInterfaceBuffRcv_Y[jVertexSolid], solidInterfaceBuffRcv_Z[jVertexSolid]]) - distance = spdist.euclidean(NodeA, NodeB) - phi = self.__CPC2(distance, rad) - jGlobalVertexSolid = self.__getGlobalIndex('solid', iProc, jVertexSolid) - self.MappingMatrixA.setValue(iGlobalVertexSolid, jGlobalVertexSolid, phi) - self.MappingMatrixA_T.setValue(jGlobalVertexSolid, iGlobalVertexSolid, phi) - self.MappingMatrixA.setValue(iGlobalVertexSolid, nSolidNodes, 1.0) - self.MappingMatrixA.setValue(iGlobalVertexSolid, nSolidNodes+1, posX) - self.MappingMatrixA.setValue(iGlobalVertexSolid, nSolidNodes+2, posY) - if self.nDim == 3: - self.MappingMatrixA.setValue(iGlobalVertexSolid, nSolidNodes+3, posZ) - self.MappingMatrixA_T.setValue(nSolidNodes, iGlobalVertexSolid, 1.0) - self.MappingMatrixA_T.setValue(nSolidNodes+1, iGlobalVertexSolid, posX) - self.MappingMatrixA_T.setValue(nSolidNodes+2, iGlobalVertexSolid, posY) - if self.nDim == 3: - self.MappingMatrixA_T.setValue(nSolidNodes+3, iGlobalVertexSolid, posZ) - - def RBFMeshMapping_B(self, solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, solidInterfaceBuffRcv_Z, iProc, rad): + posX = self.localSolidInterface_array_X_init[iVertexSolid] + posY = self.localSolidInterface_array_Y_init[iVertexSolid] + posZ = self.localSolidInterface_array_Z_init[iVertexSolid] + NodeA = np.array([posX, posY, posZ]) + iGlobalVertexSolid = self.__getGlobalIndex("solid", myid, iVertexSolid) + if self.nDim == 2: + neighboors = list( + SolidSpatialTree.intersection( + (posX - rad, posY - rad, posX + rad, posY + rad) + ) + ) + elif self.nDim == 3: + neighboors = list( + SolidSpatialTree.intersection( + ( + posX - rad, + posY - rad, + posZ - rad, + posX + rad, + posY + rad, + posZ + rad, + ) + ) + ) + for jVertexSolid in neighboors: + NodeB = np.array( + [ + solidInterfaceBuffRcv_X[jVertexSolid], + solidInterfaceBuffRcv_Y[jVertexSolid], + solidInterfaceBuffRcv_Z[jVertexSolid], + ] + ) + distance = spdist.euclidean(NodeA, NodeB) + phi = self.__CPC2(distance, rad) + jGlobalVertexSolid = self.__getGlobalIndex("solid", iProc, jVertexSolid) + self.MappingMatrixA.setValue( + iGlobalVertexSolid, jGlobalVertexSolid, phi + ) + self.MappingMatrixA_T.setValue( + jGlobalVertexSolid, iGlobalVertexSolid, phi + ) + self.MappingMatrixA.setValue(iGlobalVertexSolid, nSolidNodes, 1.0) + self.MappingMatrixA.setValue(iGlobalVertexSolid, nSolidNodes + 1, posX) + self.MappingMatrixA.setValue(iGlobalVertexSolid, nSolidNodes + 2, posY) + if self.nDim == 3: + self.MappingMatrixA.setValue(iGlobalVertexSolid, nSolidNodes + 3, posZ) + self.MappingMatrixA_T.setValue(nSolidNodes, iGlobalVertexSolid, 1.0) + self.MappingMatrixA_T.setValue(nSolidNodes + 1, iGlobalVertexSolid, posX) + self.MappingMatrixA_T.setValue(nSolidNodes + 2, iGlobalVertexSolid, posY) + if self.nDim == 3: + self.MappingMatrixA_T.setValue( + nSolidNodes + 3, iGlobalVertexSolid, posZ + ) + + def RBFMeshMapping_B( + self, + solidInterfaceBuffRcv_X, + solidInterfaceBuffRcv_Y, + solidInterfaceBuffRcv_Z, + iProc, + rad, + ): """ Second part of the RBF mapping. This method provides the matrix required to obtain, from the kernel function loadings, the fluid nodes displacements. """ if self.have_MPI: - myid = self.comm.Get_rank() + myid = self.comm.Get_rank() else: - myid = 0 + myid = 0 # --- Instantiate the spatial indexing --- prop_index = index.Property() @@ -948,43 +1345,76 @@ def RBFMeshMapping_B(self, solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, sol nSolidNodes = solidInterfaceBuffRcv_X.shape[0] for jVertex in range(nSolidNodes): - posX = solidInterfaceBuffRcv_X[jVertex] - posY = solidInterfaceBuffRcv_Y[jVertex] - posZ = solidInterfaceBuffRcv_Z[jVertex] - if self.nDim == 2 : - SolidSpatialTree.add(jVertex, (posX, posY)) - else : - SolidSpatialTree.add(jVertex, (posX, posY, posZ)) + posX = solidInterfaceBuffRcv_X[jVertex] + posY = solidInterfaceBuffRcv_Y[jVertex] + posZ = solidInterfaceBuffRcv_Z[jVertex] + if self.nDim == 2: + SolidSpatialTree.add(jVertex, (posX, posY)) + else: + SolidSpatialTree.add(jVertex, (posX, posY, posZ)) for iVertexFluid in range(self.nLocalFluidInterfacePhysicalNodes): - posX = self.localFluidInterface_array_X_init[iVertexFluid] - posY = self.localFluidInterface_array_Y_init[iVertexFluid] - posZ = self.localFluidInterface_array_Z_init[iVertexFluid] - NodeA = np.array([posX, posY, posZ]) - iGlobalVertexFluid = self.__getGlobalIndex('fluid', myid, iVertexFluid) - if self.nDim == 2: - neighboors = list(SolidSpatialTree.intersection((posX-rad, posY-rad, posX+rad, posY+rad))) - elif self.nDim == 3: - neighboors = list(SolidSpatialTree.intersection((posX-rad, posY-rad, posZ-rad, posX+rad, posY+rad, posZ+rad))) - for jVertexSolid in neighboors: - NodeB = np.array([solidInterfaceBuffRcv_X[jVertexSolid], solidInterfaceBuffRcv_Y[jVertexSolid], solidInterfaceBuffRcv_Z[jVertexSolid]]) - distance = spdist.euclidean(NodeA, NodeB) - phi = self.__CPC2(distance, rad) - jGlobalVertexSolid = self.__getGlobalIndex('solid', iProc, jVertexSolid) - self.MappingMatrixB.setValue(iGlobalVertexFluid, jGlobalVertexSolid, phi) - self.MappingMatrixB_T.setValue(jGlobalVertexSolid, iGlobalVertexFluid, phi) - self.MappingMatrixB.setValue(iGlobalVertexFluid, nSolidNodes, 1.0) - self.MappingMatrixB.setValue(iGlobalVertexFluid, nSolidNodes+1, posX) - self.MappingMatrixB.setValue(iGlobalVertexFluid, nSolidNodes+2, posY) - if self.nDim == 3: - self.MappingMatrixB.setValue(iGlobalVertexFluid, nSolidNodes+3, posZ) - self.MappingMatrixB_T.setValue(nSolidNodes, iGlobalVertexFluid, 1.0) - self.MappingMatrixB_T.setValue(nSolidNodes+1, iGlobalVertexFluid, posX) - self.MappingMatrixB_T.setValue(nSolidNodes+2, iGlobalVertexFluid, posY) - if self.nDim == 3: - self.MappingMatrixB_T.setValue(nSolidNodes+3, iGlobalVertexFluid, posZ) - - def TPSMeshMapping_A(self, solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, solidInterfaceBuffRcv_Z, iProc): + posX = self.localFluidInterface_array_X_init[iVertexFluid] + posY = self.localFluidInterface_array_Y_init[iVertexFluid] + posZ = self.localFluidInterface_array_Z_init[iVertexFluid] + NodeA = np.array([posX, posY, posZ]) + iGlobalVertexFluid = self.__getGlobalIndex("fluid", myid, iVertexFluid) + if self.nDim == 2: + neighboors = list( + SolidSpatialTree.intersection( + (posX - rad, posY - rad, posX + rad, posY + rad) + ) + ) + elif self.nDim == 3: + neighboors = list( + SolidSpatialTree.intersection( + ( + posX - rad, + posY - rad, + posZ - rad, + posX + rad, + posY + rad, + posZ + rad, + ) + ) + ) + for jVertexSolid in neighboors: + NodeB = np.array( + [ + solidInterfaceBuffRcv_X[jVertexSolid], + solidInterfaceBuffRcv_Y[jVertexSolid], + solidInterfaceBuffRcv_Z[jVertexSolid], + ] + ) + distance = spdist.euclidean(NodeA, NodeB) + phi = self.__CPC2(distance, rad) + jGlobalVertexSolid = self.__getGlobalIndex("solid", iProc, jVertexSolid) + self.MappingMatrixB.setValue( + iGlobalVertexFluid, jGlobalVertexSolid, phi + ) + self.MappingMatrixB_T.setValue( + jGlobalVertexSolid, iGlobalVertexFluid, phi + ) + self.MappingMatrixB.setValue(iGlobalVertexFluid, nSolidNodes, 1.0) + self.MappingMatrixB.setValue(iGlobalVertexFluid, nSolidNodes + 1, posX) + self.MappingMatrixB.setValue(iGlobalVertexFluid, nSolidNodes + 2, posY) + if self.nDim == 3: + self.MappingMatrixB.setValue(iGlobalVertexFluid, nSolidNodes + 3, posZ) + self.MappingMatrixB_T.setValue(nSolidNodes, iGlobalVertexFluid, 1.0) + self.MappingMatrixB_T.setValue(nSolidNodes + 1, iGlobalVertexFluid, posX) + self.MappingMatrixB_T.setValue(nSolidNodes + 2, iGlobalVertexFluid, posY) + if self.nDim == 3: + self.MappingMatrixB_T.setValue( + nSolidNodes + 3, iGlobalVertexFluid, posZ + ) + + def TPSMeshMapping_A( + self, + solidInterfaceBuffRcv_X, + solidInterfaceBuffRcv_Y, + solidInterfaceBuffRcv_Z, + iProc, + ): """ First part of the RBF mapping. This method provides the matrix required to obtain, from the structural displacements, the loadings of the kernel @@ -992,73 +1422,102 @@ def TPSMeshMapping_A(self, solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, sol """ if self.have_MPI: - myid = self.comm.Get_rank() + myid = self.comm.Get_rank() else: - myid = 0 + myid = 0 nSolidNodes = solidInterfaceBuffRcv_X.shape[0] for iVertexSolid in range(self.nLocalSolidInterfacePhysicalNodes): - posX = self.localSolidInterface_array_X_init[iVertexSolid] - posY = self.localSolidInterface_array_Y_init[iVertexSolid] - posZ = self.localSolidInterface_array_Z_init[iVertexSolid] - NodeA = np.array([posX, posY, posZ]) - iGlobalVertexSolid = self.__getGlobalIndex('solid', myid, iVertexSolid) - for jVertexSolid in range(nSolidNodes): - NodeB = np.array([solidInterfaceBuffRcv_X[jVertexSolid], solidInterfaceBuffRcv_Y[jVertexSolid], solidInterfaceBuffRcv_Z[jVertexSolid]]) - distance = spdist.euclidean(NodeA, NodeB) - phi = self.__TPS(distance) - jGlobalVertexSolid = self.__getGlobalIndex('solid', iProc, jVertexSolid) - self.MappingMatrixA.setValue(iGlobalVertexSolid, jGlobalVertexSolid, phi) - self.MappingMatrixA_T.setValue(jGlobalVertexSolid, iGlobalVertexSolid, phi) - self.MappingMatrixA.setValue(iGlobalVertexSolid, nSolidNodes, 1.0) - self.MappingMatrixA.setValue(iGlobalVertexSolid, nSolidNodes+1, posX) - self.MappingMatrixA.setValue(iGlobalVertexSolid, nSolidNodes+2, posY) - if self.nDim == 3: - self.MappingMatrixA.setValue(iGlobalVertexSolid, nSolidNodes+3, posZ) - self.MappingMatrixA_T.setValue(nSolidNodes, iGlobalVertexSolid, 1.0) - self.MappingMatrixA_T.setValue(nSolidNodes+1, iGlobalVertexSolid, posX) - self.MappingMatrixA_T.setValue(nSolidNodes+2, iGlobalVertexSolid, posY) - if self.nDim == 3: - self.MappingMatrixA_T.setValue(nSolidNodes+3, iGlobalVertexSolid, posZ) - - def TPSMeshMapping_B(self, solidInterfaceBuffRcv_X, solidInterfaceBuffRcv_Y, solidInterfaceBuffRcv_Z, iProc): + posX = self.localSolidInterface_array_X_init[iVertexSolid] + posY = self.localSolidInterface_array_Y_init[iVertexSolid] + posZ = self.localSolidInterface_array_Z_init[iVertexSolid] + NodeA = np.array([posX, posY, posZ]) + iGlobalVertexSolid = self.__getGlobalIndex("solid", myid, iVertexSolid) + for jVertexSolid in range(nSolidNodes): + NodeB = np.array( + [ + solidInterfaceBuffRcv_X[jVertexSolid], + solidInterfaceBuffRcv_Y[jVertexSolid], + solidInterfaceBuffRcv_Z[jVertexSolid], + ] + ) + distance = spdist.euclidean(NodeA, NodeB) + phi = self.__TPS(distance) + jGlobalVertexSolid = self.__getGlobalIndex("solid", iProc, jVertexSolid) + self.MappingMatrixA.setValue( + iGlobalVertexSolid, jGlobalVertexSolid, phi + ) + self.MappingMatrixA_T.setValue( + jGlobalVertexSolid, iGlobalVertexSolid, phi + ) + self.MappingMatrixA.setValue(iGlobalVertexSolid, nSolidNodes, 1.0) + self.MappingMatrixA.setValue(iGlobalVertexSolid, nSolidNodes + 1, posX) + self.MappingMatrixA.setValue(iGlobalVertexSolid, nSolidNodes + 2, posY) + if self.nDim == 3: + self.MappingMatrixA.setValue(iGlobalVertexSolid, nSolidNodes + 3, posZ) + self.MappingMatrixA_T.setValue(nSolidNodes, iGlobalVertexSolid, 1.0) + self.MappingMatrixA_T.setValue(nSolidNodes + 1, iGlobalVertexSolid, posX) + self.MappingMatrixA_T.setValue(nSolidNodes + 2, iGlobalVertexSolid, posY) + if self.nDim == 3: + self.MappingMatrixA_T.setValue( + nSolidNodes + 3, iGlobalVertexSolid, posZ + ) + + def TPSMeshMapping_B( + self, + solidInterfaceBuffRcv_X, + solidInterfaceBuffRcv_Y, + solidInterfaceBuffRcv_Z, + iProc, + ): """ Second part of the TPS mapping. This method provides the matrix required to obtain, from the kernel function loadings, the fluid nodes displacements. """ if self.have_MPI: - myid = self.comm.Get_rank() + myid = self.comm.Get_rank() else: - myid = 0 + myid = 0 nSolidNodes = solidInterfaceBuffRcv_X.shape[0] for iVertexFluid in range(self.nLocalFluidInterfacePhysicalNodes): - posX = self.localFluidInterface_array_X_init[iVertexFluid] - posY = self.localFluidInterface_array_Y_init[iVertexFluid] - posZ = self.localFluidInterface_array_Z_init[iVertexFluid] - NodeA = np.array([posX, posY, posZ]) - iGlobalVertexFluid = self.__getGlobalIndex('fluid', myid, iVertexFluid) - for jVertexSolid in range(nSolidNodes): - NodeB = np.array([solidInterfaceBuffRcv_X[jVertexSolid], solidInterfaceBuffRcv_Y[jVertexSolid], solidInterfaceBuffRcv_Z[jVertexSolid]]) - distance = spdist.euclidean(NodeA, NodeB) - phi = self.__TPS(distance) - jGlobalVertexSolid = self.__getGlobalIndex('solid', iProc, jVertexSolid) - self.MappingMatrixB.setValue(iGlobalVertexFluid, jGlobalVertexSolid, phi) - self.MappingMatrixB_T.setValue(jGlobalVertexSolid, iGlobalVertexFluid, phi) - self.MappingMatrixB.setValue(iGlobalVertexFluid, nSolidNodes, 1.0) - self.MappingMatrixB.setValue(iGlobalVertexFluid, nSolidNodes+1, posX) - self.MappingMatrixB.setValue(iGlobalVertexFluid, nSolidNodes+2, posY) - if self.nDim == 3: - self.MappingMatrixB.setValue(iGlobalVertexFluid, nSolidNodes+3, posZ) - self.MappingMatrixB_T.setValue(nSolidNodes, iGlobalVertexFluid, 1.0) - self.MappingMatrixB_T.setValue(nSolidNodes+1, iGlobalVertexFluid, posX) - self.MappingMatrixB_T.setValue(nSolidNodes+2, iGlobalVertexFluid, posY) - if self.nDim == 3: - self.MappingMatrixB_T.setValue(nSolidNodes+3, iGlobalVertexFluid, posZ) - + posX = self.localFluidInterface_array_X_init[iVertexFluid] + posY = self.localFluidInterface_array_Y_init[iVertexFluid] + posZ = self.localFluidInterface_array_Z_init[iVertexFluid] + NodeA = np.array([posX, posY, posZ]) + iGlobalVertexFluid = self.__getGlobalIndex("fluid", myid, iVertexFluid) + for jVertexSolid in range(nSolidNodes): + NodeB = np.array( + [ + solidInterfaceBuffRcv_X[jVertexSolid], + solidInterfaceBuffRcv_Y[jVertexSolid], + solidInterfaceBuffRcv_Z[jVertexSolid], + ] + ) + distance = spdist.euclidean(NodeA, NodeB) + phi = self.__TPS(distance) + jGlobalVertexSolid = self.__getGlobalIndex("solid", iProc, jVertexSolid) + self.MappingMatrixB.setValue( + iGlobalVertexFluid, jGlobalVertexSolid, phi + ) + self.MappingMatrixB_T.setValue( + jGlobalVertexSolid, iGlobalVertexFluid, phi + ) + self.MappingMatrixB.setValue(iGlobalVertexFluid, nSolidNodes, 1.0) + self.MappingMatrixB.setValue(iGlobalVertexFluid, nSolidNodes + 1, posX) + self.MappingMatrixB.setValue(iGlobalVertexFluid, nSolidNodes + 2, posY) + if self.nDim == 3: + self.MappingMatrixB.setValue(iGlobalVertexFluid, nSolidNodes + 3, posZ) + self.MappingMatrixB_T.setValue(nSolidNodes, iGlobalVertexFluid, 1.0) + self.MappingMatrixB_T.setValue(nSolidNodes + 1, iGlobalVertexFluid, posX) + self.MappingMatrixB_T.setValue(nSolidNodes + 2, iGlobalVertexFluid, posY) + if self.nDim == 3: + self.MappingMatrixB_T.setValue( + nSolidNodes + 3, iGlobalVertexFluid, posZ + ) def __CPC2(self, distance, rad): """ @@ -1066,12 +1525,12 @@ def __CPC2(self, distance, rad): distance. The kernel function is the one used for RBF. """ phi = 0.0 - eps = distance/rad + eps = distance / rad if eps < 1: - phi = ((1.0-eps)**4)*(4.0*eps+1.0) + phi = ((1.0 - eps) ** 4) * (4.0 * eps + 1.0) else: - phi = 0.0 + phi = 0.0 return phi @@ -1083,75 +1542,84 @@ def __TPS(self, distance): phi = 0.0 if distance > 0.0: - phi = (distance**2)*np.log10(distance) + phi = (distance**2) * np.log10(distance) else: - phi = 0.0 + phi = 0.0 return phi - def interpolateSolidPositionOnFluidMesh(self, FSI_config): """ Applies the one-to-one mapping or the interpolaiton rules from solid to fluid mesh. """ if self.have_MPI: - myid = self.comm.Get_rank() - MPIsize = self.comm.Get_size() + myid = self.comm.Get_rank() + MPIsize = self.comm.Get_size() else: - myid = 0 - MPIsize = 1 - + myid = 0 + MPIsize = 1 # --- Interpolate (or map) in parallel the solid interface displacement on the fluid interface --- - if FSI_config['MATCHING_MESH'] == 'NO' and (FSI_config['MESH_INTERP_METHOD'] == 'RBF' or FSI_config['MESH_INTERP_METHOD'] == 'TPS'): - if self.have_MPI: - gamma_array_DispX = PETSc.Vec().create(self.comm) - gamma_array_DispY = PETSc.Vec().create(self.comm) - gamma_array_DispZ = PETSc.Vec().create(self.comm) - gamma_array_DispX.setType('mpi') - gamma_array_DispY.setType('mpi') - gamma_array_DispZ.setType('mpi') - KSP_solver = PETSc.KSP().create(self.comm) - else: - gamma_array_DispX = PETSc.Vec().create() - gamma_array_DispY = PETSc.Vec().create() - gamma_array_DispZ = PETSc.Vec().create() - gamma_array_DispX.setType('seq') - gamma_array_DispY.setType('seq') - gamma_array_DispZ.setType('seq') - KSP_solver = PETSc.KSP().create() - gamma_array_DispX.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) - gamma_array_DispY.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) - gamma_array_DispZ.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) - gamma_array_DispX.set(0.0) - gamma_array_DispY.set(0.0) - gamma_array_DispZ.set(0.0) - KSP_solver.setType('fgmres') - KSP_solver.getPC().setType('jacobi') - KSP_solver.setOperators(self.MappingMatrixA) - KSP_solver.setFromOptions() - KSP_solver.setInitialGuessNonzero(True) - KSP_solver.solve(self.solidInterface_array_DispX, gamma_array_DispX) - KSP_solver.solve(self.solidInterface_array_DispY, gamma_array_DispY) - if self.nDim==3: - KSP_solver.solve(self.solidInterface_array_DispZ, gamma_array_DispZ) - self.MappingMatrixB.mult(gamma_array_DispX, self.fluidInterface_array_DispX) - self.MappingMatrixB.mult(gamma_array_DispY, self.fluidInterface_array_DispY) - if self.nDim==3: - self.MappingMatrixB.mult(gamma_array_DispZ, self.fluidInterface_array_DispZ) - gamma_array_DispX.destroy() - gamma_array_DispY.destroy() - gamma_array_DispZ.destroy() - KSP_solver.destroy() - del gamma_array_DispX - del gamma_array_DispY - del gamma_array_DispZ - del KSP_solver - else: - self.MappingMatrix.mult(self.solidInterface_array_DispX, self.fluidInterface_array_DispX) - self.MappingMatrix.mult(self.solidInterface_array_DispY, self.fluidInterface_array_DispY) - if self.nDim==3: - self.MappingMatrix.mult(self.solidInterface_array_DispZ, self.fluidInterface_array_DispZ) + if FSI_config["MATCHING_MESH"] == "NO" and ( + FSI_config["MESH_INTERP_METHOD"] == "RBF" + or FSI_config["MESH_INTERP_METHOD"] == "TPS" + ): + if self.have_MPI: + gamma_array_DispX = PETSc.Vec().create(self.comm) + gamma_array_DispY = PETSc.Vec().create(self.comm) + gamma_array_DispZ = PETSc.Vec().create(self.comm) + gamma_array_DispX.setType("mpi") + gamma_array_DispY.setType("mpi") + gamma_array_DispZ.setType("mpi") + KSP_solver = PETSc.KSP().create(self.comm) + else: + gamma_array_DispX = PETSc.Vec().create() + gamma_array_DispY = PETSc.Vec().create() + gamma_array_DispZ = PETSc.Vec().create() + gamma_array_DispX.setType("seq") + gamma_array_DispY.setType("seq") + gamma_array_DispZ.setType("seq") + KSP_solver = PETSc.KSP().create() + gamma_array_DispX.setSizes(self.nSolidInterfacePhysicalNodes + self.d_RBF) + gamma_array_DispY.setSizes(self.nSolidInterfacePhysicalNodes + self.d_RBF) + gamma_array_DispZ.setSizes(self.nSolidInterfacePhysicalNodes + self.d_RBF) + gamma_array_DispX.set(0.0) + gamma_array_DispY.set(0.0) + gamma_array_DispZ.set(0.0) + KSP_solver.setType("fgmres") + KSP_solver.getPC().setType("jacobi") + KSP_solver.setOperators(self.MappingMatrixA) + KSP_solver.setFromOptions() + KSP_solver.setInitialGuessNonzero(True) + KSP_solver.solve(self.solidInterface_array_DispX, gamma_array_DispX) + KSP_solver.solve(self.solidInterface_array_DispY, gamma_array_DispY) + if self.nDim == 3: + KSP_solver.solve(self.solidInterface_array_DispZ, gamma_array_DispZ) + self.MappingMatrixB.mult(gamma_array_DispX, self.fluidInterface_array_DispX) + self.MappingMatrixB.mult(gamma_array_DispY, self.fluidInterface_array_DispY) + if self.nDim == 3: + self.MappingMatrixB.mult( + gamma_array_DispZ, self.fluidInterface_array_DispZ + ) + gamma_array_DispX.destroy() + gamma_array_DispY.destroy() + gamma_array_DispZ.destroy() + KSP_solver.destroy() + del gamma_array_DispX + del gamma_array_DispY + del gamma_array_DispZ + del KSP_solver + else: + self.MappingMatrix.mult( + self.solidInterface_array_DispX, self.fluidInterface_array_DispX + ) + self.MappingMatrix.mult( + self.solidInterface_array_DispY, self.fluidInterface_array_DispY + ) + if self.nDim == 3: + self.MappingMatrix.mult( + self.solidInterface_array_DispZ, self.fluidInterface_array_DispZ + ) # --- Checking conservation --- WSX = self.solidLoads_array_X.dot(self.solidInterface_array_DispX) @@ -1163,105 +1631,169 @@ def interpolateSolidPositionOnFluidMesh(self, FSI_config): WFZ = self.fluidLoads_array_Z.dot(self.fluidInterface_array_DispZ) self.MPIPrint("Checking f/s interface conservation...") - self.MPIPrint('Solid side (Wx, Wy, Wz) = ({}, {}, {})'.format(WSX, WSY, WSZ)) - self.MPIPrint('Fluid side (Wx, Wy, Wz) = ({}, {}, {})'.format(WFX, WFY, WFZ)) - + self.MPIPrint("Solid side (Wx, Wy, Wz) = ({}, {}, {})".format(WSX, WSY, WSZ)) + self.MPIPrint("Fluid side (Wx, Wy, Wz) = ({}, {}, {})".format(WFX, WFY, WFZ)) # --- Redistribute the interpolated fluid interface according to the partitions that own the fluid interface --- # Gather the fluid interface on the master process # This is required because PETSc redistributes evenly in the cores, and does not use the same division # of SU2, thus we need to redistribute if self.have_MPI: - sendBuff_X = None - sendBuff_Y = None - sendBuff_Z = None - self.fluidInterface_array_DispX_recon = None - self.fluidInterface_array_DispY_recon = None - self.fluidInterface_array_DispZ_recon = None - - if myid == self.rootProcess: - self.fluidInterface_array_DispX_recon = np.zeros(self.nFluidInterfacePhysicalNodes) - self.fluidInterface_array_DispY_recon = np.zeros(self.nFluidInterfacePhysicalNodes) - self.fluidInterface_array_DispZ_recon = np.zeros(self.nFluidInterfacePhysicalNodes) - - myNumberOfNodes = self.fluidInterface_array_DispX.getArray().shape[0] - sendBuffNumber = np.array([myNumberOfNodes], dtype=int) - rcvBuffNumber = np.zeros(MPIsize, dtype=int) - self.comm.Allgather(sendBuffNumber, rcvBuffNumber) - - counts = tuple(rcvBuffNumber) - displ = np.zeros(MPIsize, dtype=int) - for ii in range(rcvBuffNumber.shape[0]): - displ[ii] = rcvBuffNumber[0:ii].sum() - displ = tuple(displ) - - del sendBuffNumber, rcvBuffNumber - - self.comm.Gatherv(self.fluidInterface_array_DispX.getArray(), [self.fluidInterface_array_DispX_recon, counts, displ, self.MPI.DOUBLE], root=self.rootProcess) - self.comm.Gatherv(self.fluidInterface_array_DispY.getArray(), [self.fluidInterface_array_DispY_recon, counts, displ, self.MPI.DOUBLE], root=self.rootProcess) - self.comm.Gatherv(self.fluidInterface_array_DispZ.getArray(), [self.fluidInterface_array_DispZ_recon, counts, displ, self.MPI.DOUBLE], root=self.rootProcess) - - # Send the partitioned interface to the right fluid partitions - if myid == self.rootProcess: - for iProc in self.fluidInterfaceProcessors: - sendBuff_X = np.empty(self.fluidPhysicalInterfaceNodesDistribution[iProc], dtype=np.float64) - sendBuff_Y = np.empty(self.fluidPhysicalInterfaceNodesDistribution[iProc], dtype=np.float64) - sendBuff_Z = np.empty(self.fluidPhysicalInterfaceNodesDistribution[iProc], dtype=np.float64) - globalIndex = self.__getGlobalIndex('fluid', iProc, 0) - for iVertex in range(self.fluidPhysicalInterfaceNodesDistribution[iProc]): - sendBuff_X[iVertex] = self.fluidInterface_array_DispX_recon[globalIndex] - sendBuff_Y[iVertex] = self.fluidInterface_array_DispY_recon[globalIndex] - sendBuff_Z[iVertex] = self.fluidInterface_array_DispZ_recon[globalIndex] - globalIndex += 1 - if iProc == self.rootProcess: - self.localFluidInterface_array_DispX = np.copy(sendBuff_X) - self.localFluidInterface_array_DispY = np.copy(sendBuff_Y) - self.localFluidInterface_array_DispZ = np.copy(sendBuff_Z) - else: - self.comm.Send(sendBuff_X, dest=iProc, tag = 1) - self.comm.Send(sendBuff_Y, dest=iProc, tag = 2) - self.comm.Send(sendBuff_Z, dest=iProc, tag = 3) - if myid in self.fluidInterfaceProcessors: - if myid != self.rootProcess: - self.localFluidInterface_array_DispX = np.empty(self.nLocalFluidInterfacePhysicalNodes, dtype=np.float64) - self.localFluidInterface_array_DispY = np.empty(self.nLocalFluidInterfacePhysicalNodes, dtype=np.float64) - self.localFluidInterface_array_DispZ = np.empty(self.nLocalFluidInterfacePhysicalNodes, dtype=np.float64) - self.comm.Recv(self.localFluidInterface_array_DispX, source=self.rootProcess, tag = 1) - self.comm.Recv(self.localFluidInterface_array_DispY, source=self.rootProcess, tag = 2) - self.comm.Recv(self.localFluidInterface_array_DispZ, source=self.rootProcess, tag = 3) - del sendBuff_X - del sendBuff_Y - del sendBuff_Z - self.comm.barrier() - else: - self.localFluidInterface_array_DispX = self.fluidInterface_array_DispX.getArray().copy() - self.localFluidInterface_array_DispY = self.fluidInterface_array_DispY.getArray().copy() - self.localFluidInterface_array_DispZ = self.fluidInterface_array_DispZ.getArray().copy() + sendBuff_X = None + sendBuff_Y = None + sendBuff_Z = None + self.fluidInterface_array_DispX_recon = None + self.fluidInterface_array_DispY_recon = None + self.fluidInterface_array_DispZ_recon = None + + if myid == self.rootProcess: + self.fluidInterface_array_DispX_recon = np.zeros( + self.nFluidInterfacePhysicalNodes + ) + self.fluidInterface_array_DispY_recon = np.zeros( + self.nFluidInterfacePhysicalNodes + ) + self.fluidInterface_array_DispZ_recon = np.zeros( + self.nFluidInterfacePhysicalNodes + ) + + myNumberOfNodes = self.fluidInterface_array_DispX.getArray().shape[0] + sendBuffNumber = np.array([myNumberOfNodes], dtype=int) + rcvBuffNumber = np.zeros(MPIsize, dtype=int) + self.comm.Allgather(sendBuffNumber, rcvBuffNumber) + + counts = tuple(rcvBuffNumber) + displ = np.zeros(MPIsize, dtype=int) + for ii in range(rcvBuffNumber.shape[0]): + displ[ii] = rcvBuffNumber[0:ii].sum() + displ = tuple(displ) + + del sendBuffNumber, rcvBuffNumber + + self.comm.Gatherv( + self.fluidInterface_array_DispX.getArray(), + [self.fluidInterface_array_DispX_recon, counts, displ, self.MPI.DOUBLE], + root=self.rootProcess, + ) + self.comm.Gatherv( + self.fluidInterface_array_DispY.getArray(), + [self.fluidInterface_array_DispY_recon, counts, displ, self.MPI.DOUBLE], + root=self.rootProcess, + ) + self.comm.Gatherv( + self.fluidInterface_array_DispZ.getArray(), + [self.fluidInterface_array_DispZ_recon, counts, displ, self.MPI.DOUBLE], + root=self.rootProcess, + ) + + # Send the partitioned interface to the right fluid partitions + if myid == self.rootProcess: + for iProc in self.fluidInterfaceProcessors: + sendBuff_X = np.empty( + self.fluidPhysicalInterfaceNodesDistribution[iProc], + dtype=np.float64, + ) + sendBuff_Y = np.empty( + self.fluidPhysicalInterfaceNodesDistribution[iProc], + dtype=np.float64, + ) + sendBuff_Z = np.empty( + self.fluidPhysicalInterfaceNodesDistribution[iProc], + dtype=np.float64, + ) + globalIndex = self.__getGlobalIndex("fluid", iProc, 0) + for iVertex in range( + self.fluidPhysicalInterfaceNodesDistribution[iProc] + ): + sendBuff_X[iVertex] = self.fluidInterface_array_DispX_recon[ + globalIndex + ] + sendBuff_Y[iVertex] = self.fluidInterface_array_DispY_recon[ + globalIndex + ] + sendBuff_Z[iVertex] = self.fluidInterface_array_DispZ_recon[ + globalIndex + ] + globalIndex += 1 + if iProc == self.rootProcess: + self.localFluidInterface_array_DispX = np.copy(sendBuff_X) + self.localFluidInterface_array_DispY = np.copy(sendBuff_Y) + self.localFluidInterface_array_DispZ = np.copy(sendBuff_Z) + else: + self.comm.Send(sendBuff_X, dest=iProc, tag=1) + self.comm.Send(sendBuff_Y, dest=iProc, tag=2) + self.comm.Send(sendBuff_Z, dest=iProc, tag=3) + if myid in self.fluidInterfaceProcessors: + if myid != self.rootProcess: + self.localFluidInterface_array_DispX = np.empty( + self.nLocalFluidInterfacePhysicalNodes, dtype=np.float64 + ) + self.localFluidInterface_array_DispY = np.empty( + self.nLocalFluidInterfacePhysicalNodes, dtype=np.float64 + ) + self.localFluidInterface_array_DispZ = np.empty( + self.nLocalFluidInterfacePhysicalNodes, dtype=np.float64 + ) + self.comm.Recv( + self.localFluidInterface_array_DispX, + source=self.rootProcess, + tag=1, + ) + self.comm.Recv( + self.localFluidInterface_array_DispY, + source=self.rootProcess, + tag=2, + ) + self.comm.Recv( + self.localFluidInterface_array_DispZ, + source=self.rootProcess, + tag=3, + ) + del sendBuff_X + del sendBuff_Y + del sendBuff_Z + self.comm.barrier() + else: + self.localFluidInterface_array_DispX = ( + self.fluidInterface_array_DispX.getArray().copy() + ) + self.localFluidInterface_array_DispY = ( + self.fluidInterface_array_DispY.getArray().copy() + ) + self.localFluidInterface_array_DispZ = ( + self.fluidInterface_array_DispZ.getArray().copy() + ) # Special treatment for the halo nodes on the fluid interface self.haloNodesDisplacements = {} sendBuff = {} if self.have_MPI: - if myid == self.rootProcess: - for iProc in self.fluidInterfaceProcessors: - sendBuff = {} - for key in self.FluidHaloNodeList[iProc].keys(): # The keys are the SU2 global IDs of the interface nodes - globalIndex = self.fluidIndexing[key] # These are the interface global IDs, not the SU2 global IDs - DispX = self.fluidInterface_array_DispX_recon[globalIndex] - DispY = self.fluidInterface_array_DispY_recon[globalIndex] - DispZ = self.fluidInterface_array_DispZ_recon[globalIndex] - sendBuff[key] = (DispX, DispY, DispZ) - if iProc == self.rootProcess: - self.haloNodesDisplacements = sendBuff - else: - self.comm.send(sendBuff, dest = iProc, tag=4) - if myid in self.fluidInterfaceProcessors: - if myid != self.rootProcess: - self.haloNodesDisplacements = self.comm.recv(source = self.rootProcess, tag = 4) - self.comm.barrier() - del self.fluidInterface_array_DispX_recon - del self.fluidInterface_array_DispY_recon - del self.fluidInterface_array_DispZ_recon + if myid == self.rootProcess: + for iProc in self.fluidInterfaceProcessors: + sendBuff = {} + for key in self.FluidHaloNodeList[ + iProc + ].keys(): # The keys are the SU2 global IDs of the interface nodes + globalIndex = self.fluidIndexing[ + key + ] # These are the interface global IDs, not the SU2 global IDs + DispX = self.fluidInterface_array_DispX_recon[globalIndex] + DispY = self.fluidInterface_array_DispY_recon[globalIndex] + DispZ = self.fluidInterface_array_DispZ_recon[globalIndex] + sendBuff[key] = (DispX, DispY, DispZ) + if iProc == self.rootProcess: + self.haloNodesDisplacements = sendBuff + else: + self.comm.send(sendBuff, dest=iProc, tag=4) + if myid in self.fluidInterfaceProcessors: + if myid != self.rootProcess: + self.haloNodesDisplacements = self.comm.recv( + source=self.rootProcess, tag=4 + ) + self.comm.barrier() + del self.fluidInterface_array_DispX_recon + del self.fluidInterface_array_DispY_recon + del self.fluidInterface_array_DispZ_recon del sendBuff def interpolateFluidLoadsOnSolidMesh(self, FSI_config): @@ -1269,154 +1801,200 @@ def interpolateFluidLoadsOnSolidMesh(self, FSI_config): Applies the one-to-one mapping or the interpolaiton rules from fluid to solid mesh. """ if self.have_MPI: - myid = self.comm.Get_rank() - MPIsize = self.comm.Get_size() + myid = self.comm.Get_rank() + MPIsize = self.comm.Get_size() else: - myid = 0 - MPIsize = 1 + myid = 0 + MPIsize = 1 # --- Interpolate (or map) in parallel the fluid interface loads on the solid interface --- - #self.MappingMatrix.transpose() - if FSI_config['MATCHING_MESH'] == 'NO' and (FSI_config['MESH_INTERP_METHOD'] == 'RBF' or FSI_config['MESH_INTERP_METHOD'] == 'TPS'): - if self.have_MPI: - gamma_array_LoadX = PETSc.Vec().create(self.comm) - gamma_array_LoadY = PETSc.Vec().create(self.comm) - gamma_array_LoadZ = PETSc.Vec().create(self.comm) - gamma_array_LoadX.setType('mpi') - gamma_array_LoadY.setType('mpi') - gamma_array_LoadZ.setType('mpi') - KSP_solver = PETSc.KSP().create(self.comm) - else: - gamma_array_LoadX = PETSc.Vec().create() - gamma_array_LoadY = PETSc.Vec().create() - gamma_array_LoadZ = PETSc.Vec().create() - gamma_array_LoadX.setType('seq') - gamma_array_LoadY.setType('seq') - gamma_array_LoadZ.setType('seq') - KSP_solver = PETSc.KSP().create() - gamma_array_LoadX.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) - gamma_array_LoadY.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) - gamma_array_LoadZ.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) - gamma_array_LoadX.set(0.0) - gamma_array_LoadY.set(0.0) - gamma_array_LoadZ.set(0.0) - KSP_solver.setType('fgmres') - KSP_solver.getPC().setType('jacobi') - KSP_solver.setOperators(self.MappingMatrixA_T) - KSP_solver.setFromOptions() - self.MappingMatrixB_T.mult(self.fluidLoads_array_X, gamma_array_LoadX) - self.MappingMatrixB_T.mult(self.fluidLoads_array_Y, gamma_array_LoadY) - if self.nDim==3: - self.MappingMatrixB_T.mult(self.fluidLoads_array_Z, gamma_array_LoadZ) - KSP_solver.solve(gamma_array_LoadX, self.solidLoads_array_X) - KSP_solver.solve(gamma_array_LoadY, self.solidLoads_array_Y) - if self.nDim==3: - KSP_solver.solve(gamma_array_LoadZ, self.solidLoads_array_Z) - gamma_array_LoadX.destroy() - gamma_array_LoadY.destroy() - gamma_array_LoadZ.destroy() - KSP_solver.destroy() - del gamma_array_LoadX - del gamma_array_LoadY - del gamma_array_LoadZ - del KSP_solver - else: - self.MappingMatrix_T.mult(self.fluidLoads_array_X, self.solidLoads_array_X) - self.MappingMatrix_T.mult(self.fluidLoads_array_Y, self.solidLoads_array_Y) - if self.nDim==3: - self.MappingMatrix_T.mult(self.fluidLoads_array_Z, self.solidLoads_array_Z) + # self.MappingMatrix.transpose() + if FSI_config["MATCHING_MESH"] == "NO" and ( + FSI_config["MESH_INTERP_METHOD"] == "RBF" + or FSI_config["MESH_INTERP_METHOD"] == "TPS" + ): + if self.have_MPI: + gamma_array_LoadX = PETSc.Vec().create(self.comm) + gamma_array_LoadY = PETSc.Vec().create(self.comm) + gamma_array_LoadZ = PETSc.Vec().create(self.comm) + gamma_array_LoadX.setType("mpi") + gamma_array_LoadY.setType("mpi") + gamma_array_LoadZ.setType("mpi") + KSP_solver = PETSc.KSP().create(self.comm) + else: + gamma_array_LoadX = PETSc.Vec().create() + gamma_array_LoadY = PETSc.Vec().create() + gamma_array_LoadZ = PETSc.Vec().create() + gamma_array_LoadX.setType("seq") + gamma_array_LoadY.setType("seq") + gamma_array_LoadZ.setType("seq") + KSP_solver = PETSc.KSP().create() + gamma_array_LoadX.setSizes(self.nSolidInterfacePhysicalNodes + self.d_RBF) + gamma_array_LoadY.setSizes(self.nSolidInterfacePhysicalNodes + self.d_RBF) + gamma_array_LoadZ.setSizes(self.nSolidInterfacePhysicalNodes + self.d_RBF) + gamma_array_LoadX.set(0.0) + gamma_array_LoadY.set(0.0) + gamma_array_LoadZ.set(0.0) + KSP_solver.setType("fgmres") + KSP_solver.getPC().setType("jacobi") + KSP_solver.setOperators(self.MappingMatrixA_T) + KSP_solver.setFromOptions() + self.MappingMatrixB_T.mult(self.fluidLoads_array_X, gamma_array_LoadX) + self.MappingMatrixB_T.mult(self.fluidLoads_array_Y, gamma_array_LoadY) + if self.nDim == 3: + self.MappingMatrixB_T.mult(self.fluidLoads_array_Z, gamma_array_LoadZ) + KSP_solver.solve(gamma_array_LoadX, self.solidLoads_array_X) + KSP_solver.solve(gamma_array_LoadY, self.solidLoads_array_Y) + if self.nDim == 3: + KSP_solver.solve(gamma_array_LoadZ, self.solidLoads_array_Z) + gamma_array_LoadX.destroy() + gamma_array_LoadY.destroy() + gamma_array_LoadZ.destroy() + KSP_solver.destroy() + del gamma_array_LoadX + del gamma_array_LoadY + del gamma_array_LoadZ + del KSP_solver + else: + self.MappingMatrix_T.mult(self.fluidLoads_array_X, self.solidLoads_array_X) + self.MappingMatrix_T.mult(self.fluidLoads_array_Y, self.solidLoads_array_Y) + if self.nDim == 3: + self.MappingMatrix_T.mult( + self.fluidLoads_array_Z, self.solidLoads_array_Z + ) # --- Redistribute the interpolated solid loads according to the partitions that own the solid interface --- # Gather the solid loads on the master process if self.have_MPI: - sendBuff_X = None - sendBuff_Y = None - sendBuff_Z = None - self.solidLoads_array_X_recon = None - self.solidLoads_array_Y_recon = None - self.solidLoads_array_Z_recon = None - if myid == self.rootProcess: - self.solidLoads_array_X_recon = np.zeros(self.nSolidInterfacePhysicalNodes+self.d_RBF) - self.solidLoads_array_Y_recon = np.zeros(self.nSolidInterfacePhysicalNodes+self.d_RBF) - self.solidLoads_array_Z_recon = np.zeros(self.nSolidInterfacePhysicalNodes+self.d_RBF) - myNumberOfNodes = self.solidLoads_array_X.getArray().shape[0] - sendBuffNumber = np.array([myNumberOfNodes], dtype=int) - rcvBuffNumber = np.zeros(MPIsize, dtype=int) - self.comm.Allgather(sendBuffNumber, rcvBuffNumber) - - counts = tuple(rcvBuffNumber) - displ = np.zeros(MPIsize, dtype=int) - for ii in range(rcvBuffNumber.shape[0]): - displ[ii] = rcvBuffNumber[0:ii].sum() - displ = tuple(displ) - - del sendBuffNumber, rcvBuffNumber - - self.comm.Gatherv(self.solidLoads_array_X.getArray(), [self.solidLoads_array_X_recon, counts, displ, self.MPI.DOUBLE], root=self.rootProcess) - self.comm.Gatherv(self.solidLoads_array_Y.getArray(), [self.solidLoads_array_Y_recon, counts, displ, self.MPI.DOUBLE], root=self.rootProcess) - self.comm.Gatherv(self.solidLoads_array_Z.getArray(), [self.solidLoads_array_Z_recon, counts, displ, self.MPI.DOUBLE], root=self.rootProcess) - - # Send the partitioned loads to the right solid partitions - if myid == self.rootProcess: - for iProc in self.solidInterfaceProcessors: - sendBuff_X = np.empty(self.solidPhysicalInterfaceNodesDistribution[iProc], dtype=np.float64) - sendBuff_Y = np.empty(self.solidPhysicalInterfaceNodesDistribution[iProc], dtype=np.float64) - sendBuff_Z = np.empty(self.solidPhysicalInterfaceNodesDistribution[iProc], dtype=np.float64) - globalIndex = self.__getGlobalIndex('solid', iProc, 0) - for iVertex in range(self.solidPhysicalInterfaceNodesDistribution[iProc]): - sendBuff_X[iVertex] = self.solidLoads_array_X_recon[globalIndex] - sendBuff_Y[iVertex] = self.solidLoads_array_Y_recon[globalIndex] - sendBuff_Z[iVertex] = self.solidLoads_array_Z_recon[globalIndex] - globalIndex += 1 - if iProc != myid: - self.comm.Send(sendBuff_X, dest=iProc, tag = 1) - self.comm.Send(sendBuff_Y, dest=iProc, tag = 2) - self.comm.Send(sendBuff_Z, dest=iProc, tag = 3) - else: - self.localSolidLoads_array_X = np.copy(sendBuff_X) - self.localSolidLoads_array_Y = np.copy(sendBuff_Y) - self.localSolidLoads_array_Z = np.copy(sendBuff_Z) - if myid in self.solidInterfaceProcessors: - if myid != self.rootProcess: - self.localSolidLoads_array_X = np.empty(self.nLocalSolidInterfacePhysicalNodes, dtype=np.float64) - self.localSolidLoads_array_Y = np.empty(self.nLocalSolidInterfacePhysicalNodes, dtype=np.float64) - self.localSolidLoads_array_Z = np.empty(self.nLocalSolidInterfacePhysicalNodes, dtype=np.float64) - self.comm.Recv(self.localSolidLoads_array_X, source=self.rootProcess, tag = 1) - self.comm.Recv(self.localSolidLoads_array_Y, source=self.rootProcess, tag = 2) - self.comm.Recv(self.localSolidLoads_array_Z, source=self.rootProcess, tag = 3) - del sendBuff_X - del sendBuff_Y - del sendBuff_Z - self.comm.barrier() - else: - self.localSolidLoads_array_X = self.solidLoads_array_X.getArray().copy() - self.localSolidLoads_array_Y = self.solidLoads_array_Y.getArray().copy() - self.localSolidLoads_array_Z = self.solidLoads_array_Z.getArray().copy() + sendBuff_X = None + sendBuff_Y = None + sendBuff_Z = None + self.solidLoads_array_X_recon = None + self.solidLoads_array_Y_recon = None + self.solidLoads_array_Z_recon = None + if myid == self.rootProcess: + self.solidLoads_array_X_recon = np.zeros( + self.nSolidInterfacePhysicalNodes + self.d_RBF + ) + self.solidLoads_array_Y_recon = np.zeros( + self.nSolidInterfacePhysicalNodes + self.d_RBF + ) + self.solidLoads_array_Z_recon = np.zeros( + self.nSolidInterfacePhysicalNodes + self.d_RBF + ) + myNumberOfNodes = self.solidLoads_array_X.getArray().shape[0] + sendBuffNumber = np.array([myNumberOfNodes], dtype=int) + rcvBuffNumber = np.zeros(MPIsize, dtype=int) + self.comm.Allgather(sendBuffNumber, rcvBuffNumber) + + counts = tuple(rcvBuffNumber) + displ = np.zeros(MPIsize, dtype=int) + for ii in range(rcvBuffNumber.shape[0]): + displ[ii] = rcvBuffNumber[0:ii].sum() + displ = tuple(displ) + + del sendBuffNumber, rcvBuffNumber + + self.comm.Gatherv( + self.solidLoads_array_X.getArray(), + [self.solidLoads_array_X_recon, counts, displ, self.MPI.DOUBLE], + root=self.rootProcess, + ) + self.comm.Gatherv( + self.solidLoads_array_Y.getArray(), + [self.solidLoads_array_Y_recon, counts, displ, self.MPI.DOUBLE], + root=self.rootProcess, + ) + self.comm.Gatherv( + self.solidLoads_array_Z.getArray(), + [self.solidLoads_array_Z_recon, counts, displ, self.MPI.DOUBLE], + root=self.rootProcess, + ) + + # Send the partitioned loads to the right solid partitions + if myid == self.rootProcess: + for iProc in self.solidInterfaceProcessors: + sendBuff_X = np.empty( + self.solidPhysicalInterfaceNodesDistribution[iProc], + dtype=np.float64, + ) + sendBuff_Y = np.empty( + self.solidPhysicalInterfaceNodesDistribution[iProc], + dtype=np.float64, + ) + sendBuff_Z = np.empty( + self.solidPhysicalInterfaceNodesDistribution[iProc], + dtype=np.float64, + ) + globalIndex = self.__getGlobalIndex("solid", iProc, 0) + for iVertex in range( + self.solidPhysicalInterfaceNodesDistribution[iProc] + ): + sendBuff_X[iVertex] = self.solidLoads_array_X_recon[globalIndex] + sendBuff_Y[iVertex] = self.solidLoads_array_Y_recon[globalIndex] + sendBuff_Z[iVertex] = self.solidLoads_array_Z_recon[globalIndex] + globalIndex += 1 + if iProc != myid: + self.comm.Send(sendBuff_X, dest=iProc, tag=1) + self.comm.Send(sendBuff_Y, dest=iProc, tag=2) + self.comm.Send(sendBuff_Z, dest=iProc, tag=3) + else: + self.localSolidLoads_array_X = np.copy(sendBuff_X) + self.localSolidLoads_array_Y = np.copy(sendBuff_Y) + self.localSolidLoads_array_Z = np.copy(sendBuff_Z) + if myid in self.solidInterfaceProcessors: + if myid != self.rootProcess: + self.localSolidLoads_array_X = np.empty( + self.nLocalSolidInterfacePhysicalNodes, dtype=np.float64 + ) + self.localSolidLoads_array_Y = np.empty( + self.nLocalSolidInterfacePhysicalNodes, dtype=np.float64 + ) + self.localSolidLoads_array_Z = np.empty( + self.nLocalSolidInterfacePhysicalNodes, dtype=np.float64 + ) + self.comm.Recv( + self.localSolidLoads_array_X, source=self.rootProcess, tag=1 + ) + self.comm.Recv( + self.localSolidLoads_array_Y, source=self.rootProcess, tag=2 + ) + self.comm.Recv( + self.localSolidLoads_array_Z, source=self.rootProcess, tag=3 + ) + del sendBuff_X + del sendBuff_Y + del sendBuff_Z + self.comm.barrier() + else: + self.localSolidLoads_array_X = self.solidLoads_array_X.getArray().copy() + self.localSolidLoads_array_Y = self.solidLoads_array_Y.getArray().copy() + self.localSolidLoads_array_Z = self.solidLoads_array_Z.getArray().copy() # Special treatment for the halo nodes on the solid interface self.haloNodesLoads = {} sendBuff = {} if self.have_MPI: - if myid == self.rootProcess: - for iProc in self.solidInterfaceProcessors: - sendBuff = {} - for key in self.SolidHaloNodeList[iProc].keys(): - globalIndex = self.solidIndexing[key] - DispX = self.solidLoads_array_X_recon[globalIndex] - DispY = self.solidLoads_array_Y_recon[globalIndex] - DispZ = self.solidLoads_array_Z_recon[globalIndex] - sendBuff[key] = (DispX, DispY, DispZ) - if iProc == self.rootProcess: - self.haloNodesLoads = sendBuff - else: - self.comm.send(sendBuff, dest = iProc, tag=4) - if myid in self.solidInterfaceProcessors: - if myid != self.rootProcess: - self.haloNodesLoads = self.comm.recv(source = self.rootProcess, tag = 4) - self.comm.barrier() - del self.solidLoads_array_X_recon - del self.solidLoads_array_Y_recon - del self.solidLoads_array_Z_recon + if myid == self.rootProcess: + for iProc in self.solidInterfaceProcessors: + sendBuff = {} + for key in self.SolidHaloNodeList[iProc].keys(): + globalIndex = self.solidIndexing[key] + DispX = self.solidLoads_array_X_recon[globalIndex] + DispY = self.solidLoads_array_Y_recon[globalIndex] + DispZ = self.solidLoads_array_Z_recon[globalIndex] + sendBuff[key] = (DispX, DispY, DispZ) + if iProc == self.rootProcess: + self.haloNodesLoads = sendBuff + else: + self.comm.send(sendBuff, dest=iProc, tag=4) + if myid in self.solidInterfaceProcessors: + if myid != self.rootProcess: + self.haloNodesLoads = self.comm.recv(source=self.rootProcess, tag=4) + self.comm.barrier() + del self.solidLoads_array_X_recon + del self.solidLoads_array_Y_recon + del self.solidLoads_array_Z_recon del sendBuff def getSolidInterfaceDisplacement(self, SolidSolver): @@ -1424,22 +2002,26 @@ def getSolidInterfaceDisplacement(self, SolidSolver): Gets the current solid interface position from the solid solver. """ if self.have_MPI: - myid = self.comm.Get_rank() + myid = self.comm.Get_rank() else: - myid = 0 + myid = 0 # --- Get the solid interface position from the solid solver and directly fill the corresponding PETSc vector --- GlobalIndex = int() localIndex = 0 for iVertex in range(self.nLocalSolidInterfaceNodes): - GlobalIndex = SolidSolver.getVertexGlobalIndex(self.solidInterfaceIdentifier, iVertex) - if GlobalIndex not in self.SolidHaloNodeList[myid].keys(): - newDispx, newDispy, newDispz = SolidSolver.getInterfaceNodeDisp(self.solidInterfaceIdentifier, iVertex) - iGlobalVertex = self.__getGlobalIndex('solid', myid, localIndex) - self.solidInterface_array_DispX.setValues([iGlobalVertex],newDispx) - self.solidInterface_array_DispY.setValues([iGlobalVertex],newDispy) - self.solidInterface_array_DispZ.setValues([iGlobalVertex],newDispz) - localIndex += 1 + GlobalIndex = SolidSolver.getVertexGlobalIndex( + self.solidInterfaceIdentifier, iVertex + ) + if GlobalIndex not in self.SolidHaloNodeList[myid].keys(): + newDispx, newDispy, newDispz = SolidSolver.getInterfaceNodeDisp( + self.solidInterfaceIdentifier, iVertex + ) + iGlobalVertex = self.__getGlobalIndex("solid", myid, localIndex) + self.solidInterface_array_DispX.setValues([iGlobalVertex], newDispx) + self.solidInterface_array_DispY.setValues([iGlobalVertex], newDispy) + self.solidInterface_array_DispZ.setValues([iGlobalVertex], newDispz) + localIndex += 1 self.solidInterface_array_DispX.assemblyBegin() self.solidInterface_array_DispX.assemblyEnd() @@ -1453,23 +2035,27 @@ def getFluidInterfaceNodalForce(self, FSI_config, FluidSolver): Gets the fluid interface loads from the fluid solver. """ if self.have_MPI: - myid = self.comm.Get_rank() + myid = self.comm.Get_rank() else: - myid = 0 + myid = 0 GlobalIndex = int() localIndex = 0 # --- Get the fluid interface loads from the fluid solver and directly fill the corresponding PETSc vector --- for iVertex in range(self.nLocalFluidInterfaceNodes): - GlobalIndex = FluidSolver.GetNodeGlobalIndex(FluidSolver.GetMarkerNode(self.fluidInterfaceIdentifier, iVertex)) + GlobalIndex = FluidSolver.GetNodeGlobalIndex( + FluidSolver.GetMarkerNode(self.fluidInterfaceIdentifier, iVertex) + ) if GlobalIndex not in self.FluidHaloNodeList[myid].keys(): - loadX, loadY, loadZ = FluidSolver.GetFlowLoad(self.fluidInterfaceIdentifier, iVertex) - iGlobalVertex = self.__getGlobalIndex('fluid', myid, localIndex) - self.fluidLoads_array_X.setValues([iGlobalVertex], loadX) - self.fluidLoads_array_Y.setValues([iGlobalVertex], loadY) - self.fluidLoads_array_Z.setValues([iGlobalVertex], loadZ) - localIndex += 1 + loadX, loadY, loadZ = FluidSolver.GetFlowLoad( + self.fluidInterfaceIdentifier, iVertex + ) + iGlobalVertex = self.__getGlobalIndex("fluid", myid, localIndex) + self.fluidLoads_array_X.setValues([iGlobalVertex], loadX) + self.fluidLoads_array_Y.setValues([iGlobalVertex], loadY) + self.fluidLoads_array_Z.setValues([iGlobalVertex], loadZ) + localIndex += 1 self.fluidLoads_array_X.assemblyBegin() self.fluidLoads_array_X.assemblyEnd() @@ -1478,31 +2064,39 @@ def getFluidInterfaceNodalForce(self, FSI_config, FluidSolver): self.fluidLoads_array_Z.assemblyBegin() self.fluidLoads_array_Z.assemblyEnd() - def setFluidInterfaceVarCoord(self, FluidSolver): """ Communicate the change of coordinates of the fluid interface to the fluid solver. Prepare the fluid solver for mesh deformation. """ if self.have_MPI: - myid = self.comm.Get_rank() + myid = self.comm.Get_rank() else: - myid = 0 + myid = 0 # --- Send the new fluid interface position to the fluid solver (on each partition, halo nodes included) --- localIndex = 0 for iVertex in range(self.nLocalFluidInterfaceNodes): - GlobalIndex = FluidSolver.GetNodeGlobalIndex(FluidSolver.GetMarkerNode(self.fluidInterfaceIdentifier, iVertex)) + GlobalIndex = FluidSolver.GetNodeGlobalIndex( + FluidSolver.GetMarkerNode(self.fluidInterfaceIdentifier, iVertex) + ) if GlobalIndex in self.FluidHaloNodeList[myid].keys(): - DispX, DispY, DispZ = self.haloNodesDisplacements[GlobalIndex] - FluidSolver.SetMarkerDisplacements(self.fluidInterfaceIdentifier, int(iVertex), np.array([DispX, DispY, DispZ])) + DispX, DispY, DispZ = self.haloNodesDisplacements[GlobalIndex] + FluidSolver.SetMarkerDisplacements( + self.fluidInterfaceIdentifier, + int(iVertex), + np.array([DispX, DispY, DispZ]), + ) else: - DispX = self.localFluidInterface_array_DispX[localIndex] - DispY = self.localFluidInterface_array_DispY[localIndex] - DispZ = self.localFluidInterface_array_DispZ[localIndex] - FluidSolver.SetMarkerDisplacements(self.fluidInterfaceIdentifier, int(iVertex), np.array([DispX, DispY, DispZ])) - localIndex += 1 - + DispX = self.localFluidInterface_array_DispX[localIndex] + DispY = self.localFluidInterface_array_DispY[localIndex] + DispZ = self.localFluidInterface_array_DispZ[localIndex] + FluidSolver.SetMarkerDisplacements( + self.fluidInterfaceIdentifier, + int(iVertex), + np.array([DispX, DispY, DispZ]), + ) + localIndex += 1 def setSolidInterfaceLoads(self, SolidSolver, FSI_config): """ @@ -1510,17 +2104,17 @@ def setSolidInterfaceLoads(self, SolidSolver, FSI_config): Calculates the new resultant forces (lift, drag, ...). """ if self.have_MPI: - myid = self.comm.Get_rank() + myid = self.comm.Get_rank() else: - myid = 0 + myid = 0 FX = np.array(0.0, dtype=np.float64) - FY = np.array(0.0, dtype=np.float64) # solid-side resultant forces + FY = np.array(0.0, dtype=np.float64) # solid-side resultant forces FZ = np.array(0.0, dtype=np.float64) FXSendBuff = np.array(0.0, dtype=np.float64) FYSendBuff = np.array(0.0, dtype=np.float64) FZSendBuff = np.array(0.0, dtype=np.float64) - FFX = 0.0 # fluid-side resultant forces + FFX = 0.0 # fluid-side resultant forces FFY = 0.0 FFZ = 0.0 @@ -1530,40 +2124,42 @@ def setSolidInterfaceLoads(self, SolidSolver, FSI_config): FFZ = self.fluidLoads_array_Z.sum() for iVertex in range(self.nLocalSolidInterfacePhysicalNodes): - FXSendBuff += self.localSolidLoads_array_X[iVertex] - FYSendBuff += self.localSolidLoads_array_Y[iVertex] - FZSendBuff += self.localSolidLoads_array_Z[iVertex] + FXSendBuff += self.localSolidLoads_array_X[iVertex] + FYSendBuff += self.localSolidLoads_array_Y[iVertex] + FZSendBuff += self.localSolidLoads_array_Z[iVertex] if self.have_MPI: - self.comm.Allreduce(FXSendBuff, FX, op=self.MPI.SUM) - self.comm.Allreduce(FYSendBuff, FY, op=self.MPI.SUM) - self.comm.Allreduce(FZSendBuff, FZ, op=self.MPI.SUM) + self.comm.Allreduce(FXSendBuff, FX, op=self.MPI.SUM) + self.comm.Allreduce(FYSendBuff, FY, op=self.MPI.SUM) + self.comm.Allreduce(FZSendBuff, FZ, op=self.MPI.SUM) else: - FX = np.copy(FXSendBuff) - FY = np.copy(FYSendBuff) - FZ = np.copy(FZSendBuff) + FX = np.copy(FXSendBuff) + FY = np.copy(FYSendBuff) + FZ = np.copy(FZSendBuff) del FXSendBuff del FYSendBuff del FZSendBuff self.MPIPrint("Checking f/s interface total force...") - self.MPIPrint('Solid side (Fx, Fy, Fz) = ({}, {}, {})'.format(FX, FY, FZ)) - self.MPIPrint('Fluid side (Fx, Fy, Fz) = ({}, {}, {})'.format(FFX, FFY, FFZ)) + self.MPIPrint("Solid side (Fx, Fy, Fz) = ({}, {}, {})".format(FX, FY, FZ)) + self.MPIPrint("Fluid side (Fx, Fy, Fz) = ({}, {}, {})".format(FFX, FFY, FFZ)) # --- Send the new solid interface loads to the solid solver (on each partition, halo nodes included) --- GlobalIndex = int() localIndex = 0 for iVertex in range(self.nLocalSolidInterfaceNodes): - GlobalIndex = SolidSolver.getVertexGlobalIndex(self.solidInterfaceIdentifier, iVertex) - if GlobalIndex in self.SolidHaloNodeList[myid].keys(): - pass #TODO here, when the solid solver will run in parallel, we will need to pass the halo loads - else: - Fx = self.localSolidLoads_array_X[localIndex] - Fy = self.localSolidLoads_array_Y[localIndex] - Fz = self.localSolidLoads_array_Z[localIndex] - SolidSolver.applyload(iVertex, Fx, Fy, Fz) - localIndex += 1 + GlobalIndex = SolidSolver.getVertexGlobalIndex( + self.solidInterfaceIdentifier, iVertex + ) + if GlobalIndex in self.SolidHaloNodeList[myid].keys(): + pass # TODO here, when the solid solver will run in parallel, we will need to pass the halo loads + else: + Fx = self.localSolidLoads_array_X[localIndex] + Fy = self.localSolidLoads_array_Y[localIndex] + Fz = self.localSolidLoads_array_Z[localIndex] + SolidSolver.applyload(iVertex, Fx, Fy, Fz) + localIndex += 1 def computeSolidInterfaceResidual(self, SolidSolver): """ @@ -1571,40 +2167,42 @@ def computeSolidInterfaceResidual(self, SolidSolver): """ if self.have_MPI: - myid = self.comm.Get_rank() + myid = self.comm.Get_rank() else: - myid = 0 + myid = 0 normInterfaceResidualSquare = 0.0 # --- Create and fill the PETSc vector for the predicted solid interface position (predicted by the solid computation) --- if self.have_MPI: - predDisp_array_X = PETSc.Vec().create(self.comm) - predDisp_array_X.setType('mpi') - predDisp_array_Y = PETSc.Vec().create(self.comm) - predDisp_array_Y.setType('mpi') - predDisp_array_Z = PETSc.Vec().create(self.comm) - predDisp_array_Z.setType('mpi') - else: - predDisp_array_X = PETSc.Vec().create() - predDisp_array_X.setType('seq') - predDisp_array_Y = PETSc.Vec().create() - predDisp_array_Y.setType('seq') - predDisp_array_Z = PETSc.Vec().create() - predDisp_array_Z.setType('seq') - predDisp_array_X.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) - predDisp_array_Y.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) - predDisp_array_Z.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) + predDisp_array_X = PETSc.Vec().create(self.comm) + predDisp_array_X.setType("mpi") + predDisp_array_Y = PETSc.Vec().create(self.comm) + predDisp_array_Y.setType("mpi") + predDisp_array_Z = PETSc.Vec().create(self.comm) + predDisp_array_Z.setType("mpi") + else: + predDisp_array_X = PETSc.Vec().create() + predDisp_array_X.setType("seq") + predDisp_array_Y = PETSc.Vec().create() + predDisp_array_Y.setType("seq") + predDisp_array_Z = PETSc.Vec().create() + predDisp_array_Z.setType("seq") + predDisp_array_X.setSizes(self.nSolidInterfacePhysicalNodes + self.d_RBF) + predDisp_array_Y.setSizes(self.nSolidInterfacePhysicalNodes + self.d_RBF) + predDisp_array_Z.setSizes(self.nSolidInterfacePhysicalNodes + self.d_RBF) predDisp_array_X.set(0.0) predDisp_array_Y.set(0.0) predDisp_array_Z.set(0.0) for iVertex in range(self.nLocalSolidInterfaceNodes): - predDispx, predDispy, predDispz = SolidSolver.getInterfaceNodeDisp(self.solidInterfaceIdentifier, iVertex) - iGlobalVertex = self.__getGlobalIndex('solid', myid, iVertex) - predDisp_array_X.setValues([iGlobalVertex], predDispx) - predDisp_array_Y.setValues([iGlobalVertex], predDispy) - predDisp_array_Z.setValues([iGlobalVertex], predDispz) + predDispx, predDispy, predDispz = SolidSolver.getInterfaceNodeDisp( + self.solidInterfaceIdentifier, iVertex + ) + iGlobalVertex = self.__getGlobalIndex("solid", myid, iVertex) + predDisp_array_X.setValues([iGlobalVertex], predDispx) + predDisp_array_Y.setValues([iGlobalVertex], predDispy) + predDisp_array_Z.setValues([iGlobalVertex], predDispz) predDisp_array_X.assemblyBegin() predDisp_array_X.assemblyEnd() @@ -1614,15 +2212,25 @@ def computeSolidInterfaceResidual(self, SolidSolver): predDisp_array_Z.assemblyEnd() # --- Calculate the residual (vector and norm) --- - self.solidInterfaceResidual_array_X = predDisp_array_X - self.solidInterface_array_DispX - self.solidInterfaceResidual_array_Y = predDisp_array_Y - self.solidInterface_array_DispY - self.solidInterfaceResidual_array_Z = predDisp_array_Z - self.solidInterface_array_DispZ + self.solidInterfaceResidual_array_X = ( + predDisp_array_X - self.solidInterface_array_DispX + ) + self.solidInterfaceResidual_array_Y = ( + predDisp_array_Y - self.solidInterface_array_DispY + ) + self.solidInterfaceResidual_array_Z = ( + predDisp_array_Z - self.solidInterface_array_DispZ + ) normInterfaceResidual_X = self.solidInterfaceResidual_array_X.norm() normInterfaceResidual_Y = self.solidInterfaceResidual_array_Y.norm() normInterfaceResidual_Z = self.solidInterfaceResidual_array_Z.norm() - normInterfaceResidualSquare = normInterfaceResidual_X**2 + normInterfaceResidual_Y**2 + normInterfaceResidual_Z**2 + normInterfaceResidualSquare = ( + normInterfaceResidual_X**2 + + normInterfaceResidual_Y**2 + + normInterfaceResidual_Z**2 + ) predDisp_array_X.destroy() predDisp_array_Y.destroy() @@ -1633,30 +2241,37 @@ def computeSolidInterfaceResidual(self, SolidSolver): return sqrt(normInterfaceResidualSquare) - def relaxSolidPosition(self,FSI_config): + def relaxSolidPosition(self, FSI_config): """ Apply solid displacement under-relaxation. """ if self.have_MPI: - myid = self.comm.Get_rank() + myid = self.comm.Get_rank() else: - myid = 0 + myid = 0 # --- Set the Aitken coefficient for the relaxation --- - if FSI_config['AITKEN_RELAX'] == 'STATIC': - self.aitkenParam = FSI_config['AITKEN_PARAM'] - elif FSI_config['AITKEN_RELAX'] == 'DYNAMIC': + if FSI_config["AITKEN_RELAX"] == "STATIC": + self.aitkenParam = FSI_config["AITKEN_PARAM"] + elif FSI_config["AITKEN_RELAX"] == "DYNAMIC": self.setAitkenCoefficient(FSI_config) else: self.aitkenParam = 1.0 - self.MPIPrint('Aitken under-relaxation step with parameter {}'.format(self.aitkenParam)) + self.MPIPrint( + "Aitken under-relaxation step with parameter {}".format(self.aitkenParam) + ) # --- Relax the solid interface position --- - self.solidInterface_array_DispX += self.aitkenParam*self.solidInterfaceResidual_array_X - self.solidInterface_array_DispY += self.aitkenParam*self.solidInterfaceResidual_array_Y - self.solidInterface_array_DispZ += self.aitkenParam*self.solidInterfaceResidual_array_Z - + self.solidInterface_array_DispX += ( + self.aitkenParam * self.solidInterfaceResidual_array_X + ) + self.solidInterface_array_DispY += ( + self.aitkenParam * self.solidInterfaceResidual_array_Y + ) + self.solidInterface_array_DispZ += ( + self.aitkenParam * self.solidInterfaceResidual_array_Z + ) def setAitkenCoefficient(self, FSI_config): """ @@ -1668,22 +2283,22 @@ def setAitkenCoefficient(self, FSI_config): # --- Create the PETSc vector for the difference between the residuals (current and previous FSI iter) --- if self.FSIIter == 0: - self.aitkenParam = max(FSI_config['AITKEN_PARAM'], self.aitkenParam) + self.aitkenParam = max(FSI_config["AITKEN_PARAM"], self.aitkenParam) else: if self.have_MPI: - deltaResx_array_X = PETSc.Vec().create(self.comm) - deltaResx_array_X.setType('mpi') - deltaResx_array_Y = PETSc.Vec().create(self.comm) - deltaResx_array_Y.setType('mpi') - deltaResx_array_Z = PETSc.Vec().create(self.comm) - deltaResx_array_Z.setType('mpi') + deltaResx_array_X = PETSc.Vec().create(self.comm) + deltaResx_array_X.setType("mpi") + deltaResx_array_Y = PETSc.Vec().create(self.comm) + deltaResx_array_Y.setType("mpi") + deltaResx_array_Z = PETSc.Vec().create(self.comm) + deltaResx_array_Z.setType("mpi") else: - deltaResx_array_X = PETSc.Vec().create() - deltaResx_array_X.setType('seq') - deltaResx_array_Y = PETSc.Vec().create() - deltaResx_array_Y.setType('seq') - deltaResx_array_Z = PETSc.Vec().create() - deltaResx_array_Z.setType('seq') + deltaResx_array_X = PETSc.Vec().create() + deltaResx_array_X.setType("seq") + deltaResx_array_Y = PETSc.Vec().create() + deltaResx_array_Y.setType("seq") + deltaResx_array_Z = PETSc.Vec().create() + deltaResx_array_Z.setType("seq") deltaResx_array_X.setSizes(self.nSolidInterfacePhysicalNodes + self.d_RBF) deltaResx_array_X.set(0.0) deltaResx_array_Y.setSizes(self.nSolidInterfacePhysicalNodes + self.d_RBF) @@ -1692,21 +2307,38 @@ def setAitkenCoefficient(self, FSI_config): deltaResx_array_Z.set(0.0) # --- Compute the dynamic Aitken coefficient --- - deltaResx_array_X = self.solidInterfaceResidual_array_X - self.solidInterfaceResidualnM1_array_X - deltaResx_array_Y = self.solidInterfaceResidual_array_Y - self.solidInterfaceResidualnM1_array_Y - deltaResx_array_Z = self.solidInterfaceResidual_array_Z - self.solidInterfaceResidualnM1_array_Z - - prodScalRes_X = deltaResx_array_X.dot(self.solidInterfaceResidualnM1_array_X) - prodScalRes_Y = deltaResx_array_Y.dot(self.solidInterfaceResidualnM1_array_Y) - prodScalRes_Z = deltaResx_array_Z.dot(self.solidInterfaceResidualnM1_array_Z) + deltaResx_array_X = ( + self.solidInterfaceResidual_array_X + - self.solidInterfaceResidualnM1_array_X + ) + deltaResx_array_Y = ( + self.solidInterfaceResidual_array_Y + - self.solidInterfaceResidualnM1_array_Y + ) + deltaResx_array_Z = ( + self.solidInterfaceResidual_array_Z + - self.solidInterfaceResidualnM1_array_Z + ) + + prodScalRes_X = deltaResx_array_X.dot( + self.solidInterfaceResidualnM1_array_X + ) + prodScalRes_Y = deltaResx_array_Y.dot( + self.solidInterfaceResidualnM1_array_Y + ) + prodScalRes_Z = deltaResx_array_Z.dot( + self.solidInterfaceResidualnM1_array_Z + ) prodScalRes = prodScalRes_X + prodScalRes_Y + prodScalRes_Z - deltaResNormSquare_X = (deltaResx_array_X.norm())**2 - deltaResNormSquare_Y = (deltaResx_array_Y.norm())**2 - deltaResNormSquare_Z = (deltaResx_array_Z.norm())**2 - deltaResNormSquare = deltaResNormSquare_X + deltaResNormSquare_Y + deltaResNormSquare_Z + deltaResNormSquare_X = (deltaResx_array_X.norm()) ** 2 + deltaResNormSquare_Y = (deltaResx_array_Y.norm()) ** 2 + deltaResNormSquare_Z = (deltaResx_array_Z.norm()) ** 2 + deltaResNormSquare = ( + deltaResNormSquare_X + deltaResNormSquare_Y + deltaResNormSquare_Z + ) - self.aitkenParam *= -prodScalRes/deltaResNormSquare + self.aitkenParam *= -prodScalRes / deltaResNormSquare deltaResx_array_X.destroy() deltaResx_array_Y.destroy() @@ -1723,21 +2355,21 @@ def setAitkenCoefficient(self, FSI_config): self.solidInterfaceResidual_array_Y.copy(self.solidInterfaceResidualnM1_array_Y) self.solidInterfaceResidual_array_Z.copy(self.solidInterfaceResidualnM1_array_Z) - def displacementPredictor(self, FSI_config , SolidSolver, deltaT): + def displacementPredictor(self, FSI_config, SolidSolver, deltaT): """ Calculates a prediciton for the solid interface position for the next time step. """ if self.have_MPI: - myid = self.comm.Get_rank() + myid = self.comm.Get_rank() else: - myid = 0 + myid = 0 - if FSI_config['DISP_PRED'] == 'FIRST_ORDER': + if FSI_config["DISP_PRED"] == "FIRST_ORDER": self.MPIPrint("First order predictor") alpha_0 = 1.0 alpha_1 = 0.0 - elif FSI_config['DISP_PRED'] == 'SECOND_ORDER': + elif FSI_config["DISP_PRED"] == "SECOND_ORDER": self.MPIPrint("Second order predictor") alpha_0 = 1.0 alpha_1 = 0.5 @@ -1748,61 +2380,66 @@ def displacementPredictor(self, FSI_config , SolidSolver, deltaT): # --- Create the PETSc vectors to store the solid interface velocity --- if self.have_MPI: - Vel_array_X = PETSc.Vec().create(self.comm) - Vel_array_X.setType('mpi') - Vel_array_Y = PETSc.Vec().create(self.comm) - Vel_array_Y.setType('mpi') - Vel_array_Z = PETSc.Vec().create(self.comm) - Vel_array_Z.setType('mpi') - VelnM1_array_X = PETSc.Vec().create(self.comm) - VelnM1_array_X.setType('mpi') - VelnM1_array_Y = PETSc.Vec().create(self.comm) - VelnM1_array_Y.setType('mpi') - VelnM1_array_Z = PETSc.Vec().create(self.comm) - VelnM1_array_Z.setType('mpi') - else: - Vel_array_X = PETSc.Vec().create() - Vel_array_X.setType('seq') - Vel_array_Y = PETSc.Vec().create() - Vel_array_Y.setType('seq') - Vel_array_Z = PETSc.Vec().create() - Vel_array_Z.setType('seq') - VelnM1_array_X = PETSc.Vec().create() - VelnM1_array_X.setType('seq') - VelnM1_array_Y = PETSc.Vec().create() - VelnM1_array_Y.setType('seq') - VelnM1_array_Z = PETSc.Vec().create() - VelnM1_array_Z.setType('seq') - Vel_array_X.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) - Vel_array_Y.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) - Vel_array_Z.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) + Vel_array_X = PETSc.Vec().create(self.comm) + Vel_array_X.setType("mpi") + Vel_array_Y = PETSc.Vec().create(self.comm) + Vel_array_Y.setType("mpi") + Vel_array_Z = PETSc.Vec().create(self.comm) + Vel_array_Z.setType("mpi") + VelnM1_array_X = PETSc.Vec().create(self.comm) + VelnM1_array_X.setType("mpi") + VelnM1_array_Y = PETSc.Vec().create(self.comm) + VelnM1_array_Y.setType("mpi") + VelnM1_array_Z = PETSc.Vec().create(self.comm) + VelnM1_array_Z.setType("mpi") + else: + Vel_array_X = PETSc.Vec().create() + Vel_array_X.setType("seq") + Vel_array_Y = PETSc.Vec().create() + Vel_array_Y.setType("seq") + Vel_array_Z = PETSc.Vec().create() + Vel_array_Z.setType("seq") + VelnM1_array_X = PETSc.Vec().create() + VelnM1_array_X.setType("seq") + VelnM1_array_Y = PETSc.Vec().create() + VelnM1_array_Y.setType("seq") + VelnM1_array_Z = PETSc.Vec().create() + VelnM1_array_Z.setType("seq") + Vel_array_X.setSizes(self.nSolidInterfacePhysicalNodes + self.d_RBF) + Vel_array_Y.setSizes(self.nSolidInterfacePhysicalNodes + self.d_RBF) + Vel_array_Z.setSizes(self.nSolidInterfacePhysicalNodes + self.d_RBF) Vel_array_X.set(0.0) Vel_array_Y.set(0.0) Vel_array_Z.set(0.0) - VelnM1_array_X.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) - VelnM1_array_Y.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) - VelnM1_array_Z.setSizes(self.nSolidInterfacePhysicalNodes+self.d_RBF) + VelnM1_array_X.setSizes(self.nSolidInterfacePhysicalNodes + self.d_RBF) + VelnM1_array_Y.setSizes(self.nSolidInterfacePhysicalNodes + self.d_RBF) + VelnM1_array_Z.setSizes(self.nSolidInterfacePhysicalNodes + self.d_RBF) VelnM1_array_X.set(0.0) VelnM1_array_Y.set(0.0) VelnM1_array_Z.set(0.0) - # --- Fill the PETSc vectors --- GlobalIndex = int() localIndex = 0 for iVertex in range(self.nLocalSolidInterfaceNodes): - GlobalIndex = SolidSolver.getVertexGlobalIndex(self.solidInterfaceIdentifier, iVertex) + GlobalIndex = SolidSolver.getVertexGlobalIndex( + self.solidInterfaceIdentifier, iVertex + ) if GlobalIndex not in self.SolidHaloNodeList[myid].keys(): - iGlobalVertex = self.__getGlobalIndex('solid', myid, localIndex) - velx, vely, velz = SolidSolver.getInterfaceNodeVel(self.solidInterfaceIdentifier, iVertex) - velxNm1, velyNm1, velzNm1 = SolidSolver.getInterfaceNodeVelNm1(self.solidInterfaceIdentifier, iVertex) - Vel_array_X.setValues([iGlobalVertex],velx) - Vel_array_Y.setValues([iGlobalVertex],vely) - Vel_array_Z.setValues([iGlobalVertex],velz) - VelnM1_array_X.setValues([iGlobalVertex],velxNm1) - VelnM1_array_Y.setValues([iGlobalVertex],velyNm1) - VelnM1_array_Z.setValues([iGlobalVertex],velzNm1) - localIndex += 1 + iGlobalVertex = self.__getGlobalIndex("solid", myid, localIndex) + velx, vely, velz = SolidSolver.getInterfaceNodeVel( + self.solidInterfaceIdentifier, iVertex + ) + velxNm1, velyNm1, velzNm1 = SolidSolver.getInterfaceNodeVelNm1( + self.solidInterfaceIdentifier, iVertex + ) + Vel_array_X.setValues([iGlobalVertex], velx) + Vel_array_Y.setValues([iGlobalVertex], vely) + Vel_array_Z.setValues([iGlobalVertex], velz) + VelnM1_array_X.setValues([iGlobalVertex], velxNm1) + VelnM1_array_Y.setValues([iGlobalVertex], velyNm1) + VelnM1_array_Z.setValues([iGlobalVertex], velzNm1) + localIndex += 1 Vel_array_X.assemblyBegin() Vel_array_X.assemblyEnd() @@ -1818,9 +2455,18 @@ def displacementPredictor(self, FSI_config , SolidSolver, deltaT): VelnM1_array_Z.assemblyEnd() # --- Predict the solid position for the next time step --- - self.solidInterface_array_DispX += alpha_0*deltaT*Vel_array_X + alpha_1*deltaT*(Vel_array_X - VelnM1_array_X) - self.solidInterface_array_DispY += alpha_0*deltaT*Vel_array_Y + alpha_1*deltaT*(Vel_array_Y - VelnM1_array_Y) - self.solidInterface_array_DispZ += alpha_0*deltaT*Vel_array_Z + alpha_1*deltaT*(Vel_array_Z - VelnM1_array_Z) + self.solidInterface_array_DispX += ( + alpha_0 * deltaT * Vel_array_X + + alpha_1 * deltaT * (Vel_array_X - VelnM1_array_X) + ) + self.solidInterface_array_DispY += ( + alpha_0 * deltaT * Vel_array_Y + + alpha_1 * deltaT * (Vel_array_Y - VelnM1_array_Y) + ) + self.solidInterface_array_DispZ += ( + alpha_0 * deltaT * Vel_array_Z + + alpha_1 * deltaT * (Vel_array_Z - VelnM1_array_Z) + ) Vel_array_X.destroy() Vel_array_Y.destroy() @@ -1837,31 +2483,48 @@ def writeFSIHistory(self, TimeIter, time, varCoordNorm, FSIConv): """ if self.have_MPI: - myid = self.comm.Get_rank() + myid = self.comm.Get_rank() else: - myid = 0 + myid = 0 if myid == self.rootProcess: - if self.unsteady: - if TimeIter == 0: - histFile = open('FSIhistory.dat', "w") - histFile.write("TimeIter\tTime\tFSIRes\tFSINbIter\n") - else: - histFile = open('FSIhistory.dat', "a") - if FSIConv: - histFile.write(str(TimeIter) + '\t' + str(time) + '\t' + str(varCoordNorm) + '\t' + str(self.FSIIter+1) + '\n') + if self.unsteady: + if TimeIter == 0: + histFile = open("FSIhistory.dat", "w") + histFile.write("TimeIter\tTime\tFSIRes\tFSINbIter\n") + else: + histFile = open("FSIhistory.dat", "a") + if FSIConv: + histFile.write( + str(TimeIter) + + "\t" + + str(time) + + "\t" + + str(varCoordNorm) + + "\t" + + str(self.FSIIter + 1) + + "\n" + ) + else: + histFile.write( + str(TimeIter) + + "\t" + + str(time) + + "\t" + + str(varCoordNorm) + + "\t" + + str(self.FSIIter) + + "\n" + ) + histFile.close() else: - histFile.write(str(TimeIter) + '\t' + str(time) + '\t' + str(varCoordNorm) + '\t' + str(self.FSIIter) + '\n') - histFile.close() - else: - if self.FSIIter == 0: - histFile = open('FSIhistory.dat', "w") - histFile.write("FSI Iter\tFSIRes\n") - else : - histFile = open('FSIhistory.dat', "a") - histFile.write(str(self.FSIIter) + '\t' + str(varCoordNorm) + '\n') - histFile.close() - + if self.FSIIter == 0: + histFile = open("FSIhistory.dat", "w") + histFile.write("FSI Iter\tFSIRes\n") + else: + histFile = open("FSIhistory.dat", "a") + histFile.write(str(self.FSIIter) + "\t" + str(varCoordNorm) + "\n") + histFile.close() self.MPIBarrier() @@ -1873,338 +2536,380 @@ def __getGlobalIndex(self, physics, iProc, iLocalVertex): interface. """ - if physics == 'fluid': - globalStartIndex = self.fluidGlobalIndexRange[iProc][iProc][0] - elif physics == 'solid': - globalStartIndex = self.solidGlobalIndexRange[iProc][iProc][0] + if physics == "fluid": + globalStartIndex = self.fluidGlobalIndexRange[iProc][iProc][0] + elif physics == "solid": + globalStartIndex = self.solidGlobalIndexRange[iProc][iProc][0] globalIndex = globalStartIndex + iLocalVertex return globalIndex + def UnsteadyFSI(self, FSI_config, FluidSolver, SolidSolver): + """ + Run the unsteady FSI computation by synchronizing the fluid and solid solvers. + F/s interface data are exchanged through interface mapping and interpolation (if non mathcing meshes). + """ - def UnsteadyFSI(self,FSI_config, FluidSolver, SolidSolver): - """ - Run the unsteady FSI computation by synchronizing the fluid and solid solvers. - F/s interface data are exchanged through interface mapping and interpolation (if non mathcing meshes). - """ - - if self.have_MPI: + if self.have_MPI: myid = self.comm.Get_rank() numberPart = self.comm.Get_size() - else: + else: myid = 0 numberPart = 1 - # --- Set some general variables for the unsteady computation --- # - deltaT = FSI_config['UNST_TIMESTEP'] # physical time step - totTime = FSI_config['UNST_TIME'] # physical simulation time - NbFSIIterMax = FSI_config['NB_FSI_ITER'] # maximum number of FSI iteration (for each time step) - FSITolerance = FSI_config['FSI_TOLERANCE'] # f/s interface tolerance - TimeIterTreshold = FSI_config['TIME_TRESHOLD'] # time iteration from which we allow the solid to deform - self.MPIPrint('The FSI coupling will start after {} iterations'.format(TimeIterTreshold)) - - if FSI_config['RESTART_SOL'] == 'YES': - NbTimeIter = ((totTime)/deltaT)-1 - time = (FSI_config['RESTART_ITER'])*deltaT - TimeIter = FSI_config['RESTART_ITER'] - else: - NbTimeIter = (totTime/deltaT)-1 # number of time iterations - time = 0.0 # initial time - TimeIter = 0 # initial time iteration - - NbTimeIter = int(NbTimeIter) # be sure that NbTimeIter is an integer - - varCoordNorm = 0.0 # FSI residual - FSIConv = False # FSI convergence flag - - self.MPIPrint('\n**********************************') - self.MPIPrint('* Begin unsteady FSI computation *') - self.MPIPrint('**********************************\n') - - # --- Initialize the coupled solution --- # - #If restart - if FSI_config['RESTART_SOL'] == 'YES': + # --- Set some general variables for the unsteady computation --- # + deltaT = FSI_config["UNST_TIMESTEP"] # physical time step + totTime = FSI_config["UNST_TIME"] # physical simulation time + NbFSIIterMax = FSI_config[ + "NB_FSI_ITER" + ] # maximum number of FSI iteration (for each time step) + FSITolerance = FSI_config["FSI_TOLERANCE"] # f/s interface tolerance + TimeIterTreshold = FSI_config[ + "TIME_TRESHOLD" + ] # time iteration from which we allow the solid to deform + self.MPIPrint( + "The FSI coupling will start after {} iterations".format(TimeIterTreshold) + ) + + if FSI_config["RESTART_SOL"] == "YES": + NbTimeIter = ((totTime) / deltaT) - 1 + time = (FSI_config["RESTART_ITER"]) * deltaT + TimeIter = FSI_config["RESTART_ITER"] + else: + NbTimeIter = (totTime / deltaT) - 1 # number of time iterations + time = 0.0 # initial time + TimeIter = 0 # initial time iteration + + NbTimeIter = int(NbTimeIter) # be sure that NbTimeIter is an integer + + varCoordNorm = 0.0 # FSI residual + FSIConv = False # FSI convergence flag + + self.MPIPrint("\n**********************************") + self.MPIPrint("* Begin unsteady FSI computation *") + self.MPIPrint("**********************************\n") + + # --- Initialize the coupled solution --- # + # If restart + if FSI_config["RESTART_SOL"] == "YES": self.getSolidInterfaceDisplacement(SolidSolver) self.displacementPredictor(FSI_config, SolidSolver, deltaT) if myid in self.solidSolverProcessors: - SolidSolver.updateSolution() - #If no restart - else: - self.MPIPrint('Setting FSI initial conditions') + SolidSolver.updateSolution() + # If no restart + else: + self.MPIPrint("Setting FSI initial conditions") if myid in self.solidSolverProcessors: - SolidSolver.setInitialDisplacements() + SolidSolver.setInitialDisplacements() self.getSolidInterfaceDisplacement(SolidSolver) self.interpolateSolidPositionOnFluidMesh(FSI_config) self.setFluidInterfaceVarCoord(FluidSolver) - self.MPIPrint('\nPerforming static mesh deformation (ALE) of initial mesh...\n') + self.MPIPrint( + "\nPerforming static mesh deformation (ALE) of initial mesh...\n" + ) if myid in self.fluidSolverProcessors: - FluidSolver.SetInitialMesh() # if there is an initial deformation in the solid, it has to be communicated to the fluid solver - self.MPIPrint('\nFSI initial conditions are set') - self.MPIPrint('Beginning time integration\n') + FluidSolver.SetInitialMesh() # if there is an initial deformation in the solid, it has to be communicated to the fluid solver + self.MPIPrint("\nFSI initial conditions are set") + self.MPIPrint("Beginning time integration\n") + + # --- External temporal loop --- # + while TimeIter <= NbTimeIter: + + if TimeIter > TimeIterTreshold: + NbFSIIter = NbFSIIterMax + self.MPIPrint("\n") + self.MPIPrint( + " Enter Block Gauss Seidel (BGS) method for strong coupling FSI on time iteration {} ".format( + TimeIter + ).center( + 80, "*" + ) + ) + else: + NbFSIIter = 1 - # --- External temporal loop --- # - while TimeIter <= NbTimeIter: + self.FSIIter = 0 + FSIConv = False - if TimeIter > TimeIterTreshold: - NbFSIIter = NbFSIIterMax - self.MPIPrint("\n") - self.MPIPrint(" Enter Block Gauss Seidel (BGS) method for strong coupling FSI on time iteration {} ".format(TimeIter).center(80,"*")) - else: - NbFSIIter = 1 - - self.FSIIter = 0 - FSIConv = False - - # --- Internal FSI loop --- # - while self.FSIIter <= (NbFSIIter-1): - - self.MPIPrint("\n>>>> Time iteration {} / FSI iteration {} <<<<".format(TimeIter,self.FSIIter)) - - # --- Mesh morphing step (displacements interpolation, displacements communication, and mesh morpher call) --- # - self.interpolateSolidPositionOnFluidMesh(FSI_config) - self.MPIPrint('\nPerforming dynamic mesh deformation (ALE)...\n') - self.setFluidInterfaceVarCoord(FluidSolver) - if myid in self.fluidSolverProcessors: - if self.FSIIter == 0: - FluidSolver.Preprocess(TimeIter) # set some parameters before temporal fluid iteration and dynamic mesh update - else: - FluidSolver.DynamicMeshUpdate(TimeIter) - # --- Fluid solver call for FSI subiteration --- # - self.MPIPrint('\nLaunching fluid solver for one single dual-time iteration...') - self.MPIBarrier() - if myid in self.fluidSolverProcessors: - FluidSolver.ResetConvergence() - FluidSolver.Run() - self.MPIBarrier() - FluidSolver.Postprocess() - self.MPIBarrier() - - # --- Surface fluid loads interpolation and communication --- # - if TimeIter > TimeIterTreshold: - if not self.ImposedMotion: - self.MPIPrint('\nProcessing interface fluid loads...\n') - self.MPIBarrier() - self.getFluidInterfaceNodalForce(FSI_config, FluidSolver) - self.MPIBarrier() - self.interpolateFluidLoadsOnSolidMesh(FSI_config) - self.setSolidInterfaceLoads(SolidSolver, FSI_config) - - # --- Solid solver call for FSI subiteration --- # - self.MPIPrint('\nLaunching solid solver for a single time iteration...\n') - if myid in self.solidSolverProcessors: - SolidSolver.run(time) - - # --- Compute and monitor the FSI residual --- # - varCoordNorm = self.computeSolidInterfaceResidual(SolidSolver) - self.MPIPrint('\nFSI displacement norm : {}\n'.format(varCoordNorm)) - if varCoordNorm < FSITolerance: - FSIConv = True - break - - # --- Relaxe the solid position --- # - self.MPIPrint('\nProcessing interface displacements...\n') - self.relaxSolidPosition(FSI_config) - - self.FSIIter += 1 - # --- End OF FSI loop --- # + # --- Internal FSI loop --- # + while self.FSIIter <= (NbFSIIter - 1): + self.MPIPrint( + "\n>>>> Time iteration {} / FSI iteration {} <<<<".format( + TimeIter, self.FSIIter + ) + ) + + # --- Mesh morphing step (displacements interpolation, displacements communication, and mesh morpher call) --- # + self.interpolateSolidPositionOnFluidMesh(FSI_config) + self.MPIPrint("\nPerforming dynamic mesh deformation (ALE)...\n") + self.setFluidInterfaceVarCoord(FluidSolver) + if myid in self.fluidSolverProcessors: + if self.FSIIter == 0: + FluidSolver.Preprocess( + TimeIter + ) # set some parameters before temporal fluid iteration and dynamic mesh update + else: + FluidSolver.DynamicMeshUpdate(TimeIter) + # --- Fluid solver call for FSI subiteration --- # + self.MPIPrint( + "\nLaunching fluid solver for one single dual-time iteration..." + ) self.MPIBarrier() + if myid in self.fluidSolverProcessors: + FluidSolver.ResetConvergence() + FluidSolver.Run() + self.MPIBarrier() + FluidSolver.Postprocess() + self.MPIBarrier() - # --- Update the FSI history file --- # + # --- Surface fluid loads interpolation and communication --- # if TimeIter > TimeIterTreshold: - self.MPIPrint('\nBGS is converged (strong coupling)') - self.writeFSIHistory(TimeIter, time, varCoordNorm, FSIConv) - - # --- Update, monitor and output the fluid solution before the next time step ---# - if myid in self.fluidSolverProcessors: - FluidSolver.Update() - FluidSolver.Monitor(TimeIter) - FluidSolver.Output(TimeIter) + if not self.ImposedMotion: + self.MPIPrint("\nProcessing interface fluid loads...\n") + self.MPIBarrier() + self.getFluidInterfaceNodalForce(FSI_config, FluidSolver) + self.MPIBarrier() + self.interpolateFluidLoadsOnSolidMesh(FSI_config) + self.setSolidInterfaceLoads(SolidSolver, FSI_config) + + # --- Solid solver call for FSI subiteration --- # + self.MPIPrint( + "\nLaunching solid solver for a single time iteration...\n" + ) + if myid in self.solidSolverProcessors: + SolidSolver.run(time) + + # --- Compute and monitor the FSI residual --- # + varCoordNorm = self.computeSolidInterfaceResidual(SolidSolver) + self.MPIPrint("\nFSI displacement norm : {}\n".format(varCoordNorm)) + if varCoordNorm < FSITolerance: + FSIConv = True + break + + # --- Relaxe the solid position --- # + self.MPIPrint("\nProcessing interface displacements...\n") + self.relaxSolidPosition(FSI_config) + + self.FSIIter += 1 + # --- End OF FSI loop --- # + + self.MPIBarrier() + + # --- Update the FSI history file --- # + if TimeIter > TimeIterTreshold: + self.MPIPrint("\nBGS is converged (strong coupling)") + self.writeFSIHistory(TimeIter, time, varCoordNorm, FSIConv) + + # --- Update, monitor and output the fluid solution before the next time step ---# + if myid in self.fluidSolverProcessors: + FluidSolver.Update() + FluidSolver.Monitor(TimeIter) + FluidSolver.Output(TimeIter) - if TimeIter >= TimeIterTreshold: - if myid in self.solidSolverProcessors: + if TimeIter >= TimeIterTreshold: + if myid in self.solidSolverProcessors: # --- Output the solid solution before thr next time step --- # SolidSolver.writeSolution(time, TimeIter, self.FSIIter) - if TimeIter > TimeIterTreshold: - # --- Displacement predictor for the next time step and update of the solid solution --- # - self.MPIPrint('\nSolid displacement prediction for next time step') - self.displacementPredictor(FSI_config, SolidSolver, deltaT) - if myid in self.solidSolverProcessors: + if TimeIter > TimeIterTreshold: + # --- Displacement predictor for the next time step and update of the solid solution --- # + self.MPIPrint("\nSolid displacement prediction for next time step") + self.displacementPredictor(FSI_config, SolidSolver, deltaT) + if myid in self.solidSolverProcessors: SolidSolver.updateSolution() - TimeIter += 1 - time += deltaT - #--- End of the temporal loop --- # + TimeIter += 1 + time += deltaT + # --- End of the temporal loop --- # - self.MPIBarrier() + self.MPIBarrier() - self.MPIPrint('\n*************************') - self.MPIPrint('* End FSI computation *') - self.MPIPrint('*************************\n') + self.MPIPrint("\n*************************") + self.MPIPrint("* End FSI computation *") + self.MPIPrint("*************************\n") - def SteadyFSI(self, FSI_config,FluidSolver, SolidSolver): - """ - Runs the steady FSI computation by synchronizing the fluid and solid solver with data exchange at the f/s interface. - """ + def SteadyFSI(self, FSI_config, FluidSolver, SolidSolver): + """ + Runs the steady FSI computation by synchronizing the fluid and solid solver with data exchange at the f/s interface. + """ - if self.have_MPI: + if self.have_MPI: myid = self.comm.Get_rank() numberPart = self.comm.Get_size() - else: + else: myid = 0 numberPart = 1 - # --- Set some general variables for the steady computation --- # - NbFSIIterMax = FSI_config['NB_FSI_ITER'] # maximum number of FSI iteration (for each time step) - FSITolerance = FSI_config['FSI_TOLERANCE'] # f/s interface tolerance - varCoordNorm = 0.0 - - self.MPIPrint('\n********************************') - self.MPIPrint('* Begin steady FSI computation *') - self.MPIPrint('********************************\n') - self.MPIPrint("\n") - self.MPIPrint(" Enter Block Gauss Seidel (BGS) method for strong coupling FSI ".center(80,"*")) - - self.MPIPrint('Setting initial deformed mesh') - if myid in self.solidSolverProcessors: - SolidSolver.setInitialDisplacements() - self.getSolidInterfaceDisplacement(SolidSolver) - self.interpolateSolidPositionOnFluidMesh(FSI_config) - self.setFluidInterfaceVarCoord(FluidSolver) - self.MPIPrint('\nFSI initial conditions are set') - - # --- External FSI loop --- # - self.FSIIter = 0 - while self.FSIIter < NbFSIIterMax: + # --- Set some general variables for the steady computation --- # + NbFSIIterMax = FSI_config[ + "NB_FSI_ITER" + ] # maximum number of FSI iteration (for each time step) + FSITolerance = FSI_config["FSI_TOLERANCE"] # f/s interface tolerance + varCoordNorm = 0.0 + + self.MPIPrint("\n********************************") + self.MPIPrint("* Begin steady FSI computation *") + self.MPIPrint("********************************\n") + self.MPIPrint("\n") + self.MPIPrint( + " Enter Block Gauss Seidel (BGS) method for strong coupling FSI ".center( + 80, "*" + ) + ) + + self.MPIPrint("Setting initial deformed mesh") + if myid in self.solidSolverProcessors: + SolidSolver.setInitialDisplacements() + self.getSolidInterfaceDisplacement(SolidSolver) + self.interpolateSolidPositionOnFluidMesh(FSI_config) + self.setFluidInterfaceVarCoord(FluidSolver) + self.MPIPrint("\nFSI initial conditions are set") + + # --- External FSI loop --- # + self.FSIIter = 0 + while self.FSIIter < NbFSIIterMax: self.MPIPrint("\n>>>> FSI iteration {} <<<<".format(self.FSIIter)) - self.MPIPrint('\nLaunching fluid solver for a steady computation...') + self.MPIPrint("\nLaunching fluid solver for a steady computation...") # --- Fluid solver call for FSI subiteration ---# if myid in self.fluidSolverProcessors: - FluidSolver.ResetConvergence() #This is setting to zero the convergence in the integrator, important to reset it. - # The mesh will be deformed in the context of the preprocessor, there is no need to set the initial - # mesh pushing back the solution to avoid spurious velocities, as the velocity is not computed at all - self.MPIPrint('\nPerforming static mesh deformation...\n') - FluidSolver.Preprocess(0)# This will attempt to always set the initial condition, but there is a flag on the unsteady computation that will avoid it - FluidSolver.Run() - FluidSolver.Postprocess() - FluidSolver.Monitor(0) #This is actually not needed, it only saves the fact that the fluid solver converged innerly or reached max iterations - FluidSolver.Output(0) + FluidSolver.ResetConvergence() # This is setting to zero the convergence in the integrator, important to reset it. + # The mesh will be deformed in the context of the preprocessor, there is no need to set the initial + # mesh pushing back the solution to avoid spurious velocities, as the velocity is not computed at all + self.MPIPrint("\nPerforming static mesh deformation...\n") + FluidSolver.Preprocess( + 0 + ) # This will attempt to always set the initial condition, but there is a flag on the unsteady computation that will avoid it + FluidSolver.Run() + FluidSolver.Postprocess() + FluidSolver.Monitor( + 0 + ) # This is actually not needed, it only saves the fact that the fluid solver converged innerly or reached max iterations + FluidSolver.Output(0) # --- Surface fluid loads interpolation and communication ---# if not self.ImposedMotion: - self.MPIPrint('\nProcessing interface fluid loads...\n') - self.MPIBarrier() - self.getFluidInterfaceNodalForce(FSI_config, FluidSolver) - self.MPIBarrier() - self.interpolateFluidLoadsOnSolidMesh(FSI_config) - self.setSolidInterfaceLoads(SolidSolver, FSI_config) - # --- Solid solver call for FSI subiteration --- # - self.MPIPrint('\nLaunching solid solver for a static computation...\n') - if myid in self.solidSolverProcessors: - SolidSolver.run(0.0) - SolidSolver.writeSolution(0.0, 0, self.FSIIter) + self.MPIPrint("\nProcessing interface fluid loads...\n") + self.MPIBarrier() + self.getFluidInterfaceNodalForce(FSI_config, FluidSolver) + self.MPIBarrier() + self.interpolateFluidLoadsOnSolidMesh(FSI_config) + self.setSolidInterfaceLoads(SolidSolver, FSI_config) + # --- Solid solver call for FSI subiteration --- # + self.MPIPrint("\nLaunching solid solver for a static computation...\n") + if myid in self.solidSolverProcessors: + SolidSolver.run(0.0) + SolidSolver.writeSolution(0.0, 0, self.FSIIter) # --- Compute and monitor the FSI residual --- # varCoordNorm = self.computeSolidInterfaceResidual(SolidSolver) - self.MPIPrint('\nFSI displacement norm : {}\n'.format(varCoordNorm)) + self.MPIPrint("\nFSI displacement norm : {}\n".format(varCoordNorm)) self.writeFSIHistory(0, 0.0, varCoordNorm, False) if varCoordNorm < FSITolerance: - break + break # --- Relaxe the solid displacement and update the solid solution --- # - self.MPIPrint('\nProcessing interface displacements...\n') + self.MPIPrint("\nProcessing interface displacements...\n") self.relaxSolidPosition(FSI_config) if myid in self.solidSolverProcessors: - SolidSolver.updateSolution() + SolidSolver.updateSolution() # --- Mesh morphing step (displacement interpolation, displacements communication, and mesh morpher call) --- # self.interpolateSolidPositionOnFluidMesh(FSI_config) self.setFluidInterfaceVarCoord(FluidSolver) self.FSIIter += 1 - self.MPIBarrier() + self.MPIBarrier() - self.MPIPrint('\nBGS is converged (strong coupling)') - self.MPIPrint(' ') - self.MPIPrint('*************************') - self.MPIPrint('* End FSI computation *') - self.MPIPrint('*************************') - self.MPIPrint(' ') + self.MPIPrint("\nBGS is converged (strong coupling)") + self.MPIPrint(" ") + self.MPIPrint("*************************") + self.MPIPrint("* End FSI computation *") + self.MPIPrint("*************************") + self.MPIPrint(" ") def MapModes(self, FSI_config, FluidSolver, SolidSolver): - """ - Runs nothing, just extract the structural modes mapped on the fluid mesh - """ - - if self.have_MPI: - myid = self.comm.Get_rank() - numberPart = self.comm.Get_size() - else: - myid = 0 - numberPart = 1 - - nodeNormals = {} - for iVertex in range(self.nLocalFluidInterfaceNodes): - if self.nDim == 2: - nx, ny = FluidSolver.GetMarkerVertexNormals(self.fluidInterfaceIdentifier, iVertex, False) - nz = 0 - else: - nx, ny, nz = FluidSolver.GetMarkerVertexNormals(self.fluidInterfaceIdentifier, iVertex, False) - GlobalIndex = FluidSolver.GetNodeGlobalIndex(FluidSolver.GetMarkerNode(self.fluidInterfaceIdentifier, iVertex)) - nodeNormals[GlobalIndex] = [nx, ny, nz] - - nodeNormals = self.comm.gather(nodeNormals, root=self.rootProcess) - if myid == self.rootProcess: - normalsToPrint = {} - for iDictionary in range(numberPart): - for key, value in nodeNormals[iDictionary].items(): - normalsToPrint[key] = value - normalsToPrint = dict(sorted(normalsToPrint.items())) - with open('Normals.csv', 'w') as f: - writer = csv.writer(f) - for key, value in normalsToPrint.items(): - writer.writerow([key, value]) - - - SurfaceFileName = FluidSolver.GetSurfaceFileName() - - self.MPIPrint('\n********************************') - self.MPIPrint('* Begin mapping the modes *') - self.MPIPrint('********************************\n') - self.MPIPrint("\n") - - if myid == self.rootProcess: # The root process contains the solid solver for sure - modesNumber = np.array(int(SolidSolver.getNumberOfModes())) - else: - modesNumber = np.empty(1, dtype=np.int) - - self.comm.Bcast(modesNumber, root=self.rootProcess) - - for mode in range(np.asscalar(modesNumber)): - self.MPIPrint("Setting mode {} active".format(mode)) - if myid in self.solidSolverProcessors: - SolidSolver.activateMode(mode) - self.MPIBarrier() - self.getSolidInterfaceDisplacement(SolidSolver) - self.interpolateSolidPositionOnFluidMesh(FSI_config) - self.setFluidInterfaceVarCoord(FluidSolver) + """ + Runs nothing, just extract the structural modes mapped on the fluid mesh + """ - self.MPIPrint('\nPerforming mesh deformation...\n') - FluidSolver.DynamicMeshUpdate(0) - FluidSolver.Output(0) - self.MPIBarrier() + if self.have_MPI: + myid = self.comm.Get_rank() + numberPart = self.comm.Get_size() + else: + myid = 0 + numberPart = 1 + nodeNormals = {} + for iVertex in range(self.nLocalFluidInterfaceNodes): + if self.nDim == 2: + nx, ny = FluidSolver.GetMarkerVertexNormals( + self.fluidInterfaceIdentifier, iVertex, False + ) + nz = 0 + else: + nx, ny, nz = FluidSolver.GetMarkerVertexNormals( + self.fluidInterfaceIdentifier, iVertex, False + ) + GlobalIndex = FluidSolver.GetNodeGlobalIndex( + FluidSolver.GetMarkerNode(self.fluidInterfaceIdentifier, iVertex) + ) + nodeNormals[GlobalIndex] = [nx, ny, nz] + + nodeNormals = self.comm.gather(nodeNormals, root=self.rootProcess) if myid == self.rootProcess: - AllFiles = os.listdir() - for FileNumber,FileName in enumerate(AllFiles): - if SurfaceFileName in FileName: - file = FileName.split(".")[0] - extension = FileName.split(".")[1] - os.rename(file+"."+extension,"Mode{}.".format(mode)+extension) - - self.MPIPrint('\n*************************') - self.MPIPrint('* Mapping completed *') - self.MPIPrint('*************************\n') + normalsToPrint = {} + for iDictionary in range(numberPart): + for key, value in nodeNormals[iDictionary].items(): + normalsToPrint[key] = value + normalsToPrint = dict(sorted(normalsToPrint.items())) + with open("Normals.csv", "w") as f: + writer = csv.writer(f) + for key, value in normalsToPrint.items(): + writer.writerow([key, value]) + + SurfaceFileName = FluidSolver.GetSurfaceFileName() + + self.MPIPrint("\n********************************") + self.MPIPrint("* Begin mapping the modes *") + self.MPIPrint("********************************\n") + self.MPIPrint("\n") + + if ( + myid == self.rootProcess + ): # The root process contains the solid solver for sure + modesNumber = np.array(int(SolidSolver.getNumberOfModes())) + else: + modesNumber = np.empty(1, dtype=np.int) + + self.comm.Bcast(modesNumber, root=self.rootProcess) + + for mode in range(np.asscalar(modesNumber)): + self.MPIPrint("Setting mode {} active".format(mode)) + if myid in self.solidSolverProcessors: + SolidSolver.activateMode(mode) + self.MPIBarrier() + self.getSolidInterfaceDisplacement(SolidSolver) + self.interpolateSolidPositionOnFluidMesh(FSI_config) + self.setFluidInterfaceVarCoord(FluidSolver) + + self.MPIPrint("\nPerforming mesh deformation...\n") + FluidSolver.DynamicMeshUpdate(0) + FluidSolver.Output(0) + self.MPIBarrier() + + if myid == self.rootProcess: + AllFiles = os.listdir() + for FileNumber, FileName in enumerate(AllFiles): + if SurfaceFileName in FileName: + file = FileName.split(".")[0] + extension = FileName.split(".")[1] + os.rename( + file + "." + extension, "Mode{}.".format(mode) + extension + ) + + self.MPIPrint("\n*************************") + self.MPIPrint("* Mapping completed *") + self.MPIPrint("*************************\n") diff --git a/SU2_PY/FSI_tools/FSI_config.py b/SU2_PY/FSI_tools/FSI_config.py index 2def017c750..a0fca32d019 100644 --- a/SU2_PY/FSI_tools/FSI_config.py +++ b/SU2_PY/FSI_tools/FSI_config.py @@ -38,13 +38,14 @@ # FSI Configuration Class # ---------------------------------------------------------------------- + class FSIConfig: """ Class that contains all the parameters coming from the FSI configuration file. Read the file and store all the options into a dictionary. """ - def __init__(self,FileName,comm): + def __init__(self, FileName, comm): self.ConfigFileName = FileName self.comm = comm self._ConfigContent = {} @@ -54,10 +55,10 @@ def __init__(self,FileName,comm): def __str__(self): tempString = str() for key, value in self._ConfigContent.items(): - tempString += "{} = {}\n".format(key,value) + tempString += "{} = {}\n".format(key, value) return tempString - def __getitem__(self,key): + def __getitem__(self, key): return self._ConfigContent[key] def __setitem__(self, key, value): @@ -70,67 +71,91 @@ def readConfig(self): if not line: break # remove line returns - line = line.strip('\r\n') + line = line.strip("\r\n") # make sure it has useful data - if (not "=" in line) or (line[0] == '%'): + if (not "=" in line) or (line[0] == "%"): continue # split across equal sign - line = line.split("=",1) + line = line.split("=", 1) this_param = line[0].strip() this_value = line[1].strip() - #integer values - if (this_param == "NDIM") or \ - (this_param == "RESTART_ITER") or \ - (this_param == "TIME_TRESHOLD") or \ - (this_param == "NB_FSI_ITER") : + # integer values + if ( + (this_param == "NDIM") + or (this_param == "RESTART_ITER") + or (this_param == "TIME_TRESHOLD") + or (this_param == "NB_FSI_ITER") + ): self._ConfigContent[this_param] = int(this_value) - #float values - elif (this_param == "RBF_RADIUS") or \ - (this_param == "AITKEN_PARAM") or \ - (this_param == "UNST_TIMESTEP") or \ - (this_param == "UNST_TIME") or \ - (this_param == "FSI_TOLERANCE") : + # float values + elif ( + (this_param == "RBF_RADIUS") + or (this_param == "AITKEN_PARAM") + or (this_param == "UNST_TIMESTEP") + or (this_param == "UNST_TIME") + or (this_param == "FSI_TOLERANCE") + ): self._ConfigContent[this_param] = float(this_value) - #string values - elif (this_param == "CFD_CONFIG_FILE_NAME") or \ - (this_param == "CSD_SOLVER") or \ - (this_param == "CSD_CONFIG_FILE_NAME") or \ - (this_param == "RESTART_SOL") or \ - (this_param == "MATCHING_MESH") or \ - (this_param == "MESH_INTERP_METHOD") or \ - (this_param == "DISP_PRED") or \ - (this_param == "AITKEN_RELAX") or \ - (this_param == "TIME_MARCHING") or \ - (this_param == "IMPOSED_MOTION") or \ - (this_param == "MAPPING_MODES"): + # string values + elif ( + (this_param == "CFD_CONFIG_FILE_NAME") + or (this_param == "CSD_SOLVER") + or (this_param == "CSD_CONFIG_FILE_NAME") + or (this_param == "RESTART_SOL") + or (this_param == "MATCHING_MESH") + or (this_param == "MESH_INTERP_METHOD") + or (this_param == "DISP_PRED") + or (this_param == "AITKEN_RELAX") + or (this_param == "TIME_MARCHING") + or (this_param == "IMPOSED_MOTION") + or (this_param == "MAPPING_MODES") + ): self._ConfigContent[this_param] = this_value - else : - self.MPIPrint(this_param + " is an invalid option !",False) + else: + self.MPIPrint(this_param + " is an invalid option !", False) def applyDefaults(self): if "MAPPING_MODES" not in self._ConfigContent: self._ConfigContent["MAPPING_MODES"] = "NO" - self.MPIPrint("MAPPING_MODES keyword was not found in the configuration file of the interface, setting to NO",False) + self.MPIPrint( + "MAPPING_MODES keyword was not found in the configuration file of the interface, setting to NO", + False, + ) if "IMPOSED_MOTION" not in self._ConfigContent: self._ConfigContent["IMPOSED_MOTION"] = "NO" - self.MPIPrint("IMPOSED_MOTION keyword was not found in the configuration file of the interface, setting to NO",False) + self.MPIPrint( + "IMPOSED_MOTION keyword was not found in the configuration file of the interface, setting to NO", + False, + ) if self._ConfigContent["IMPOSED_MOTION"] == "YES": - if self._ConfigContent["AITKEN_RELAX"] != "STATIC" or self._ConfigContent["AITKEN_PARAM"] != 1.0: - self.MPIPrint("When imposing motion, the Aitken parameter must be static and equal to 1",True) + if ( + self._ConfigContent["AITKEN_RELAX"] != "STATIC" + or self._ConfigContent["AITKEN_PARAM"] != 1.0 + ): + self.MPIPrint( + "When imposing motion, the Aitken parameter must be static and equal to 1", + True, + ) if self._ConfigContent["RESTART_SOL"] == "YES": if self._ConfigContent["TIME_TRESHOLD"] != -1: - self.MPIPrint("When restarting a simulation, the time threshold must be -1 for immediate coupling",True) - - if self._ConfigContent["MAPPING_MODES"] == "YES" and self._ConfigContent["CSD_SOLVER"]!="NATIVE": - self.MPIPrint("Mapping modes only works with the native solver",True) + self.MPIPrint( + "When restarting a simulation, the time threshold must be -1 for immediate coupling", + True, + ) + + if ( + self._ConfigContent["MAPPING_MODES"] == "YES" + and self._ConfigContent["CSD_SOLVER"] != "NATIVE" + ): + self.MPIPrint("Mapping modes only works with the native solver", True) def MPIPrint(self, message, error): """ diff --git a/SU2_PY/OptimalPropeller.py b/SU2_PY/OptimalPropeller.py index ef22e7db419..388689fb637 100644 --- a/SU2_PY/OptimalPropeller.py +++ b/SU2_PY/OptimalPropeller.py @@ -48,83 +48,90 @@ ### Functions ### ########################## -def a_distribution (w0, Chi): + +def a_distribution(w0, Chi): """Function used to compute the value of the axial interference factor using the inviscid theory of the optimal propeller.""" - return (w0*pow(Chi,2))/(pow(Chi,2)+pow((1+(w0)),2)) + return (w0 * pow(Chi, 2)) / (pow(Chi, 2) + pow((1 + (w0)), 2)) def write_su2_config_file(): """Write the actuator disk configuration file""" - with open('ActuatorDisk.cfg', 'w') as f: - f.write('% Automatic generated actuator disk configuration file.\n') - f.write('%\n') - f.write('% The first two elements of MARKER_ACTDISK must be filled.\n') - f.write('% An example of this file can be found in the TestCases directory.\n') - f.write('%\n') - f.write('% Author: Ettore Saetta, Lorenzo Russo, Renato Tognaccini.\n') - f.write('% Theoretical and Applied Aerodynamic Research Group (TAARG),\n') - f.write('% University of Naples Federico II\n') - f.write('\n') - f.write('ACTDISK_TYPE = VARIABLE_LOAD\n') - f.write('ACTDISK_FILENAME = ActuatorDisk.dat\n') - f.write('MARKER_ACTDISK = ( , , 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)\n') + with open("ActuatorDisk.cfg", "w") as f: + f.write("% Automatic generated actuator disk configuration file.\n") + f.write("%\n") + f.write("% The first two elements of MARKER_ACTDISK must be filled.\n") + f.write("% An example of this file can be found in the TestCases directory.\n") + f.write("%\n") + f.write("% Author: Ettore Saetta, Lorenzo Russo, Renato Tognaccini.\n") + f.write("% Theoretical and Applied Aerodynamic Research Group (TAARG),\n") + f.write("% University of Naples Federico II\n") + f.write("\n") + f.write("ACTDISK_TYPE = VARIABLE_LOAD\n") + f.write("ACTDISK_FILENAME = ActuatorDisk.dat\n") + f.write("MARKER_ACTDISK = ( , , 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)\n") - print('SU2 file generated!') + print("SU2 file generated!") def write_external_file(CTrs, CPrs): """Function to write the actuator disk input data file""" - with open('ActuatorDisk.dat', 'w') as f: - f.write('# Automatic generated actuator disk input data file using the Optimal Propeller code.\n') - f.write('# Data file needed for the actuator disk VARIABLE_LOAD type.\n') - f.write('# The load distribution is obtained using the inviscid theory of the optimal propeller\n') - f.write('# using global data.\n') - f.write('#\n') - f.write('# The first three lines must be filled.\n') - f.write('# An example of this file can be found in the TestCases directory.\n') - f.write('#\n') - f.write('# Author: Ettore Saetta, Lorenzo Russo, Renato Tognaccini.\n') - f.write('# Theoretical and Applied Aerodynamic Research Group (TAARG),\n') - f.write('# University of Naples Federico II\n') - f.write('# -------------------------------------------------------------------------------------\n') - f.write('#\n') - f.write('MARKER_ACTDISK= \n') - f.write('CENTER= \n') - f.write('AXIS= \n') - f.write('RADIUS= '+str(R)+'\n') - f.write('ADV_RATIO= '+str(J)+'\n') - f.write('NROW= '+str(stations)+'\n') - f.write('# rs=r/R dCT/drs dCP/drs dCR/drs\n') + with open("ActuatorDisk.dat", "w") as f: + f.write( + "# Automatic generated actuator disk input data file using the Optimal Propeller code.\n" + ) + f.write("# Data file needed for the actuator disk VARIABLE_LOAD type.\n") + f.write( + "# The load distribution is obtained using the inviscid theory of the optimal propeller\n" + ) + f.write("# using global data.\n") + f.write("#\n") + f.write("# The first three lines must be filled.\n") + f.write("# An example of this file can be found in the TestCases directory.\n") + f.write("#\n") + f.write("# Author: Ettore Saetta, Lorenzo Russo, Renato Tognaccini.\n") + f.write("# Theoretical and Applied Aerodynamic Research Group (TAARG),\n") + f.write("# University of Naples Federico II\n") + f.write( + "# -------------------------------------------------------------------------------------\n" + ) + f.write("#\n") + f.write("MARKER_ACTDISK= \n") + f.write("CENTER= \n") + f.write("AXIS= \n") + f.write("RADIUS= " + str(R) + "\n") + f.write("ADV_RATIO= " + str(J) + "\n") + f.write("NROW= " + str(stations) + "\n") + f.write("# rs=r/R dCT/drs dCP/drs dCR/drs\n") for i in range(0, stations): - f.write(f' {r[i]:.7f} {CTrs[i]:.7f} {CPrs[i]:.7f} 0.0\n') + f.write(f" {r[i]:.7f} {CTrs[i]:.7f} {CPrs[i]:.7f} 0.0\n") ########################## ### Main ### ########################## -print('------------------ Optimal Propeller vsn 7.0.6 ------------------') -print('| Computation of the optimal dCT/dr and dCP/dr distributions. |') -print('| Based on the inviscid theory of the optimal propeller. |') -print('| |') -print('| This code is used to generate the actuator disk input data |') -print('| file needed for the VARIABLE_LOAD actuator disk type |') -print('| implemented in SU2 7.0.6. |') -print('| |') -print('| Author: Ettore Saetta, Lorenzo Russo, Renato Tognaccini. |') -print('| Theoretical and Applied Aerodynamic Research Group (TAARG), |') -print('| University of Naples Federico II. |') -print('-----------------------------------------------------------------') -print('') -print('Warning: present version requires input in SI units.') -print('') +print("------------------ Optimal Propeller vsn 7.0.6 ------------------") +print("| Computation of the optimal dCT/dr and dCP/dr distributions. |") +print("| Based on the inviscid theory of the optimal propeller. |") +print("| |") +print("| This code is used to generate the actuator disk input data |") +print("| file needed for the VARIABLE_LOAD actuator disk type |") +print("| implemented in SU2 7.0.6. |") +print("| |") +print("| Author: Ettore Saetta, Lorenzo Russo, Renato Tognaccini. |") +print("| Theoretical and Applied Aerodynamic Research Group (TAARG), |") +print("| University of Naples Federico II. |") +print("-----------------------------------------------------------------") +print("") +print("Warning: present version requires input in SI units.") +print("") # Number of radial stations in input. -stations = int(input('Number of radial stations: ')) +stations = int(input("Number of radial stations: ")) # Resize the vectors using the number of radial stations. r = np.empty(stations) @@ -136,26 +143,26 @@ def write_external_file(CTrs, CPrs): ap_optimal = np.empty(stations) # Thrust coefficient in input. -Ct = float(input('\nCT (Renard definition): ')) +Ct = float(input("\nCT (Renard definition): ")) # Propeller radius in input. -R = float(input('\nR (propeller radius [m]): ')) +R = float(input("\nR (propeller radius [m]): ")) # Hub radius in input. -rhub = float(input('\nr_hub (hub radius [m]): ')) +rhub = float(input("\nr_hub (hub radius [m]): ")) # Advance ratio in input. -J = float(input('\nJ (advance ratio): ')) +J = float(input("\nJ (advance ratio): ")) # Freestream velocity in input. -Vinf = float(input('\nVinf (m/s): ')) +Vinf = float(input("\nVinf (m/s): ")) # Asking if the tip loss Prandtl correction function needs to be used. -prandtl_input = input('\nUsing tip loss Prandtl correction? (/n): ') +prandtl_input = input("\nUsing tip loss Prandtl correction? (/n): ") -if prandtl_input.lower() in ['yes', 'y', '']: +if prandtl_input.lower() in ["yes", "y", ""]: # Number of propeller blades in input. - N = int(input('\nN (number of propeller blades): ')) + N = int(input("\nN (number of propeller blades): ")) prandtl_correction = True else: prandtl_correction = False @@ -164,47 +171,54 @@ def write_external_file(CTrs, CPrs): rs_hub = rhub / R # Computation of the non-dimensional radial stations. -for i in range(1, stations+1): - r[i-1] = i / float(stations) - if r[i-1] <= rs_hub: +for i in range(1, stations + 1): + r[i - 1] = i / float(stations) + if r[i - 1] <= rs_hub: i_hub = i - 1 # Computation of the propeller diameter. D = 2 * R # Computation of the propeller angular velocity (Rounds/s). -n = Vinf / (D*J) +n = Vinf / (D * J) # Computation of the propeller angular velocity (Rad/s). Omega = n * 2 * math.pi # Computation of the tip loss Prandtl correction function F. if prandtl_correction: - F = (2/math.pi)*np.arccos(np.exp(-0.5*N*(1-r)*np.sqrt(1+pow(Omega*R/Vinf,2)))) + F = (2 / math.pi) * np.arccos( + np.exp(-0.5 * N * (1 - r) * np.sqrt(1 + pow(Omega * R / Vinf, 2))) + ) else: F = np.ones((stations)) # Computation of the non-dimensional radius chi=Omega*r/Vinf. -chi = Omega*r*R/Vinf +chi = Omega * r * R / Vinf -eps = 5E-20 +eps = 5e-20 # Computation of the propeller radial stations spacing. -h = (1.0/stations) +h = 1.0 / stations # Computation of the first try induced velocity distribution. -w = (2/np.power(Vinf,2))*((-1/Vinf)+np.sqrt(1+((np.power(D,4)*(Ct)*np.power(n,2))/(np.power(Vinf,2)*np.pi*r)))) +w = (2 / np.power(Vinf, 2)) * ( + (-1 / Vinf) + + np.sqrt( + 1 + ((np.power(D, 4) * (Ct) * np.power(n, 2)) / (np.power(Vinf, 2) * np.pi * r)) + ) +) # Computation of the first try Lagrange moltiplicator. -w_0 = sum(w)/(Vinf*stations) +w_0 = sum(w) / (Vinf * stations) # Computation of the first try axial interference factor distribution. for i in range(0, stations): - a_0[i] = a_distribution(w_0*F[i],chi[i]) + a_0[i] = a_distribution(w_0 * F[i], chi[i]) # Computation of the thrust coefficient distribution -dCt_0 = math.pi*J**2*r*(1+a_0)*a_0 +dCt_0 = math.pi * J**2 * r * (1 + a_0) * a_0 # Computation of the total thrust coefficient. -Ct_0 = sum(h*dCt_0[i_hub:]) +Ct_0 = sum(h * dCt_0[i_hub:]) # Compute the error with respect to the thrust coefficient given in input. err_0 = Ct_0 - Ct @@ -216,13 +230,13 @@ def write_external_file(CTrs, CPrs): # Computation of the second try axial interference factor distribution. for i in range(0, stations): - a_old[i] = a_distribution(w_old*F[i],chi[i]) + a_old[i] = a_distribution(w_old * F[i], chi[i]) # Computation of the thrust coefficient distribution -dCt_old = math.pi*J**2*r*(1+a_old)*a_old +dCt_old = math.pi * J**2 * r * (1 + a_old) * a_old # Computation of the total thrust coefficient. -Ct_old = sum(h*dCt_old[i_hub:]) +Ct_old = sum(h * dCt_old[i_hub:]) # Compute the error with respect to the thrust coefficient given in input. err_old = Ct_old - Ct @@ -239,17 +253,17 @@ def write_external_file(CTrs, CPrs): iteration += 1 # Computation of the new Lagrange moltiplicator value based on the false position method. - w_new = (w_old*err_0 - w_0*err_old)/(err_0 - err_old) + w_new = (w_old * err_0 - w_0 * err_old) / (err_0 - err_old) # Computation of the new axial interference factor distribution. for i in range(0, stations): - a_new[i] = a_distribution(w_new*F[i],chi[i]) + a_new[i] = a_distribution(w_new * F[i], chi[i]) # Computation of the new thrust coefficient distribution. - dCt_new = math.pi*J**2*r*(1+a_new)*a_new + dCt_new = math.pi * J**2 * r * (1 + a_new) * a_new # Computation of the new total thrust coefficient. - Ct_new = sum(h*dCt_new[i_hub:]) + Ct_new = sum(h * dCt_new[i_hub:]) # Computation of the total thrust coefficient error with respect to the input value. err_new = Ct_new - Ct @@ -264,46 +278,55 @@ def write_external_file(CTrs, CPrs): # Computation of the correct axial and rotational interference factors (a and ap). for i in range(0, stations): - a_optimal[i] = a_distribution(w_new*F[i],chi[i]) - ap_optimal[i] = (w_new*F[i])*((1+w_new*F[i])/(chi[i]*chi[i]+math.pow(1+w_new*F[i],2))) + a_optimal[i] = a_distribution(w_new * F[i], chi[i]) + ap_optimal[i] = (w_new * F[i]) * ( + (1 + w_new * F[i]) / (chi[i] * chi[i] + math.pow(1 + w_new * F[i], 2)) + ) # Computation of the correct thrust coefficient distribution. -dCt_optimal = math.pi*J**2*r*(1+a_optimal)*a_optimal +dCt_optimal = math.pi * J**2 * r * (1 + a_optimal) * a_optimal # Computation of the correct power coefficient distribution. for i in range(0, stations): - dCp[i] = (R*4*math.pi/(math.pow(n,3)*math.pow(D,5)))*(math.pow(Vinf,3)*math.pow(1+a_optimal[i],2)*a_optimal[i]*r[i]*R+math.pow(Omega,2)*Vinf*(1+a_optimal[i])*math.pow(ap_optimal[i],2)*math.pow(r[i]*R,3)) + dCp[i] = (R * 4 * math.pi / (math.pow(n, 3) * math.pow(D, 5))) * ( + math.pow(Vinf, 3) * math.pow(1 + a_optimal[i], 2) * a_optimal[i] * r[i] * R + + math.pow(Omega, 2) + * Vinf + * (1 + a_optimal[i]) + * math.pow(ap_optimal[i], 2) + * math.pow(r[i] * R, 3) + ) ########################## ### Check Results ### ########################## # Computation of the total power coefficient. -Cp = sum(h*dCp[i_hub:]) +Cp = sum(h * dCp[i_hub:]) # Computation of the total thrust coefficient. -Ct_optimal = sum(h*dCt_optimal[i_hub:]) +Ct_optimal = sum(h * dCt_optimal[i_hub:]) # Computation of the static pressure jump distribution. -DeltaP = dCt_optimal*(2*Vinf**2)/(J**2*math.pi*r) +DeltaP = dCt_optimal * (2 * Vinf**2) / (J**2 * math.pi * r) # Computation of the thrust over density (T) using the static pressure jump distribution. -T = sum(2*math.pi*r[i_hub:]*math.pow(R,2)*h*DeltaP[i_hub:]) +T = sum(2 * math.pi * r[i_hub:] * math.pow(R, 2) * h * DeltaP[i_hub:]) # Computation of the thrust coefficient using T. -Ct_Renard = T / (math.pow(n,2)*math.pow(D,4)) +Ct_Renard = T / (math.pow(n, 2) * math.pow(D, 4)) # Computation of the efficiency. -eta = J * (Ct_optimal/Cp) +eta = J * (Ct_optimal / Cp) # Screen output used to check that everything worked correcty. -print('%%%%%%%%%%%%%%%%%%%%%%%%% CHECK OUTPUT VALUES %%%%%%%%%%%%%%%%%%%%%%%%%') -print(f' dCT distribution integral: {Ct_optimal:.4f}') -print(f' dCT computed using the static pressure jump: {Ct_Renard:.4f}') -print(f' dCP distribution integral: {Cp:.4f}') -print(f' Thrust over Density (T/rho): {T:.4f} [N*m^3/kg]') -print(f' Efficiency eta: {eta:.4f}') -print(f' w0/Vinf: {w_new:.4f}') -print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%') +print("%%%%%%%%%%%%%%%%%%%%%%%%% CHECK OUTPUT VALUES %%%%%%%%%%%%%%%%%%%%%%%%%") +print(f" dCT distribution integral: {Ct_optimal:.4f}") +print(f" dCT computed using the static pressure jump: {Ct_Renard:.4f}") +print(f" dCP distribution integral: {Cp:.4f}") +print(f" Thrust over Density (T/rho): {T:.4f} [N*m^3/kg]") +print(f" Efficiency eta: {eta:.4f}") +print(f" w0/Vinf: {w_new:.4f}") +print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%") ########################## ### File Writing ### @@ -321,29 +344,29 @@ def write_external_file(CTrs, CPrs): # Automatically plot the computed propeller performance. pl.figure(1) -pl.plot(r, dCt_optimal, 'r', markersize=4, label='$\\frac{dCT}{d\overline{r}}$') -pl.plot(r, dCp, 'k', markersize=4, label='$\\frac{dCP}{d\overline{r}}$') +pl.plot(r, dCt_optimal, "r", markersize=4, label="$\\frac{dCT}{d\overline{r}}$") +pl.plot(r, dCp, "k", markersize=4, label="$\\frac{dCP}{d\overline{r}}$") pl.grid(True) pl.legend(numpoints=3) -pl.xlabel('$\overline{r}$') -pl.ylabel('') +pl.xlabel("$\overline{r}$") +pl.ylabel("") pl.title("Load Distribution") pl.figure(2) -pl.plot(chi, a_optimal, 'r', markersize=4, label='$a$') -pl.plot(chi, ap_optimal, 'k', markersize=4, label='$a^1$') +pl.plot(chi, a_optimal, "r", markersize=4, label="$a$") +pl.plot(chi, ap_optimal, "k", markersize=4, label="$a^1$") pl.grid(True) pl.legend(numpoints=3) -pl.xlabel('$\chi$') -pl.ylabel('') +pl.xlabel("$\chi$") +pl.ylabel("") pl.title("Interference Factors") if prandtl_correction: pl.figure(3) - pl.plot(r, F, 'k', markersize=4) + pl.plot(r, F, "k", markersize=4) pl.grid(True) - pl.xlabel('$\overline{r}$') - pl.ylabel('$F(\overline{r})$') + pl.xlabel("$\overline{r}$") + pl.ylabel("$F(\overline{r})$") pl.title("Tip Loss Prandtl Correction Function") pl.show() diff --git a/SU2_PY/SU2/__init__.py b/SU2_PY/SU2/__init__.py index 5bff3570f40..bfb81241707 100644 --- a/SU2_PY/SU2/__init__.py +++ b/SU2_PY/SU2/__init__.py @@ -1,7 +1,10 @@ # SU2/__init__.py + class EvaluationFailure(RuntimeError): pass + + class DivergenceFailure(EvaluationFailure): pass @@ -20,13 +23,10 @@ class DivergenceFailure(EvaluationFailure): try: import readline import rlcompleter - if readline.__doc__ and 'libedit' in readline.__doc__: + + if readline.__doc__ and "libedit" in readline.__doc__: readline.parse_and_bind("bind ^I rl_complete") else: readline.parse_and_bind("tab: complete") except: pass - - - - diff --git a/SU2_PY/SU2/eval/__init__.py b/SU2_PY/SU2/eval/__init__.py index 58cba7dfb55..5e718795af8 100644 --- a/SU2_PY/SU2/eval/__init__.py +++ b/SU2_PY/SU2/eval/__init__.py @@ -1,10 +1,15 @@ - from SU2.eval.functions import function as func from SU2.eval.functions import aerodynamics, geometry from SU2.eval.gradients import gradient as grad from SU2.eval.gradients import adjoint, findiff -from SU2.eval.design import (Design, - obj_f, obj_df, - con_ceq, con_dceq, - con_cieq, con_dcieq, - touch, skip) \ No newline at end of file +from SU2.eval.design import ( + Design, + obj_f, + obj_df, + con_ceq, + con_dceq, + con_cieq, + con_dcieq, + touch, + skip, +) diff --git a/SU2_PY/SU2/eval/design.py b/SU2_PY/SU2/eval/design.py index 82768dcd42f..adc8fb1ab45 100644 --- a/SU2_PY/SU2/eval/design.py +++ b/SU2_PY/SU2/eval/design.py @@ -30,9 +30,9 @@ # ---------------------------------------------------------------------- import os, copy -from .. import io as su2io -from . import func as su2func -from . import grad as su2grad +from .. import io as su2io +from . import func as su2func +from . import grad as su2grad from ..io import redirect_folder, save_data # todo: @@ -43,166 +43,171 @@ # Design Class # ---------------------------------------------------------------------- + class Design(object): - """ SU2.eval.Design(config,state=None,folder='DESIGNS/DSN_*') - - Starts a design class, which manages a config and state. - Will run design in folder, and with self indexing name if '*' is - included in the folder name. - Methods are wrappers for SU2.eval.func() and SU2.eval.grad() - - Attributes: - state - design state - config - design config - files - design files - folder - design folder - funcs - design function value bunch - grads - design gradient values bunch - - Methods: - Optimizer Interface - The following methods take a design vector for input - as a list (shape n) or numpy array (shape n or nx1 or 1xn). - Values are returned as floats or lists or lists of lists. - See SU2.eval.obj_f, etc for more detail. - - obj_f(dvs) - objective function : float - obj_df(dvs) - objective function derivatives : list - con_ceq(dvs) - equality constraints : list - con_dceq(dvs) - equality constraint derivatives : list[list] - con_cieq(dvs) - inequality constraints : list - con_dcieq(dvs) - inequality constraint gradients : list[list] - - Functional Interface - The following methods take an objective function name for input. - func(func_name) - function of specified name - grad(func_name,method='CONTINUOUS_ADJOINT') - gradient of specified name + """SU2.eval.Design(config,state=None,folder='DESIGNS/DSN_*') + + Starts a design class, which manages a config and state. + Will run design in folder, and with self indexing name if '*' is + included in the folder name. + Methods are wrappers for SU2.eval.func() and SU2.eval.grad() + + Attributes: + state - design state + config - design config + files - design files + folder - design folder + funcs - design function value bunch + grads - design gradient values bunch + + Methods: + Optimizer Interface + The following methods take a design vector for input + as a list (shape n) or numpy array (shape n or nx1 or 1xn). + Values are returned as floats or lists or lists of lists. + See SU2.eval.obj_f, etc for more detail. + + obj_f(dvs) - objective function : float + obj_df(dvs) - objective function derivatives : list + con_ceq(dvs) - equality constraints : list + con_dceq(dvs) - equality constraint derivatives : list[list] + con_cieq(dvs) - inequality constraints : list + con_dcieq(dvs) - inequality constraint gradients : list[list] + + Functional Interface + The following methods take an objective function name for input. + func(func_name) - function of specified name + grad(func_name,method='CONTINUOUS_ADJOINT') - gradient of specified name """ - def __init__(self, config, state=None, folder='DESIGNS/DSN_*'): - """ Initializes an SU2 Design """ + def __init__(self, config, state=None, folder="DESIGNS/DSN_*"): + """Initializes an SU2 Design""" ## ???: Move to Project, no next folder here - if '*' in folder: folder = su2io.next_folder(folder) + if "*" in folder: + folder = su2io.next_folder(folder) config = copy.deepcopy(config) - state = copy.deepcopy(state) - state = su2io.State(state) + state = copy.deepcopy(state) + state = su2io.State(state) state.find_files(config) self.config = config - self.state = state - self.files = state.FILES - self.funcs = state.FUNCTIONS - self.grads = state.GRADIENTS + self.state = state + self.files = state.FILES + self.funcs = state.FUNCTIONS + self.grads = state.GRADIENTS self.folder = folder - self.filename = 'design.pkl' + self.filename = "design.pkl" # initialize folder with files - pull,link = state.pullnlink(config) - with redirect_folder(folder,pull,link,force=True): + pull, link = state.pullnlink(config) + with redirect_folder(folder, pull, link, force=True): # save design, config - save_data(self.filename,self) - config.dump('config_DSN.cfg') + save_data(self.filename, self) + config.dump("config_DSN.cfg") - def _eval(self,eval_func,*args): - """ Evaluates an SU2 Design - always adds config and state to the inputs list + def _eval(self, eval_func, *args): + """Evaluates an SU2 Design + always adds config and state to the inputs list """ config = self.config - state = self.state - files = self.files + state = self.state + files = self.files folder = self.folder filename = self.filename # check folder - assert os.path.exists(folder) , 'cannot find design folder %s' % folder + assert os.path.exists(folder), "cannot find design folder %s" % folder konfig = copy.deepcopy(config) - ''' + """ If the time convergence criterion was activated, we have less time iterations. Store the changed values of TIME_ITER, ITER_AVERAGE_OBJ and UNST_ADJOINT_ITER in - state.WND_CAUCHY_DATA''' - if 'TIME_ITER' in state.WND_CAUCHY_DATA: # Use Convergence data, if we have already a direct run - konfig['TIME_ITER'] = state.WND_CAUCHY_DATA['TIME_ITER'] - konfig['ITER_AVERAGE_OBJ'] = state.WND_CAUCHY_DATA['ITER_AVERAGE_OBJ'] - konfig['UNST_ADJOINT_ITER'] = state.WND_CAUCHY_DATA['UNST_ADJOINT_ITER'] + state.WND_CAUCHY_DATA""" + if ( + "TIME_ITER" in state.WND_CAUCHY_DATA + ): # Use Convergence data, if we have already a direct run + konfig["TIME_ITER"] = state.WND_CAUCHY_DATA["TIME_ITER"] + konfig["ITER_AVERAGE_OBJ"] = state.WND_CAUCHY_DATA["ITER_AVERAGE_OBJ"] + konfig["UNST_ADJOINT_ITER"] = state.WND_CAUCHY_DATA["UNST_ADJOINT_ITER"] # list files to pull and link - pull,link = state.pullnlink(konfig) + pull, link = state.pullnlink(konfig) # output redirection, don't re-pull files - with redirect_folder(folder,pull,link,force=False) as push: + with redirect_folder(folder, pull, link, force=False) as push: # get timestamp timestamp = state.tic() # run - inputs = args + (config,state) + inputs = args + (config, state) vals = eval_func(*inputs) # save design if state.toc(timestamp): - save_data(filename,self) + save_data(filename, self) #: with redirect folder # update files - files.update(state['FILES']) + files.update(state["FILES"]) return vals - def obj_f(self,dvs): - """ Evaluates SU2 Design Objectives """ - return self._eval(obj_f,dvs) + def obj_f(self, dvs): + """Evaluates SU2 Design Objectives""" + return self._eval(obj_f, dvs) - def obj_df(self,dvs): - """ Evaluates SU2 Design Objective Gradients """ - return self._eval(obj_df,dvs) + def obj_df(self, dvs): + """Evaluates SU2 Design Objective Gradients""" + return self._eval(obj_df, dvs) - def con_ceq(self,dvs): - """ Evaluates SU2 Design Equality Constraints """ - return self._eval(con_ceq,dvs) + def con_ceq(self, dvs): + """Evaluates SU2 Design Equality Constraints""" + return self._eval(con_ceq, dvs) - def con_dceq(self,dvs): - """ Evaluates SU2 Design Equality Constraint Gradients """ - return self._eval(con_dceq,dvs) + def con_dceq(self, dvs): + """Evaluates SU2 Design Equality Constraint Gradients""" + return self._eval(con_dceq, dvs) - def con_cieq(self,dvs): - """ Evaluates SU2 Design Inequality Constraints """ - return self._eval(con_cieq,dvs) + def con_cieq(self, dvs): + """Evaluates SU2 Design Inequality Constraints""" + return self._eval(con_cieq, dvs) - def con_dcieq(self,dvs): - """ Evaluates SU2 Design Inequality Constraint Gradients """ - return self._eval(con_dcieq,dvs) + def con_dcieq(self, dvs): + """Evaluates SU2 Design Inequality Constraint Gradients""" + return self._eval(con_dcieq, dvs) - def func(self,func_name): - """ Evaluates SU2 Design Functions by Name """ - return self._eval(su2func,func_name) + def func(self, func_name): + """Evaluates SU2 Design Functions by Name""" + return self._eval(su2func, func_name) - def grad(self,func_name,method='CONTINUOUS_ADJOINT'): - """ Evaluates SU2 Design Gradients by Name """ - return self._eval(su2grad,func_name,method) + def grad(self, func_name, method="CONTINUOUS_ADJOINT"): + """Evaluates SU2 Design Gradients by Name""" + return self._eval(su2grad, func_name, method) def touch(self): return self._eval(touch) - def skip(self,*args,**kwarg): + def skip(self, *args, **kwarg): return self._eval(skip) - def __repr__(self): - return ' %s' % self.folder + return " %s" % self.folder + def __str__(self): output = self.__repr__() - output += '\n%s' % self.state + output += "\n%s" % self.state return output + #: class Design() @@ -210,178 +215,188 @@ def __str__(self): # Optimization Interface Functions # ---------------------------------------------------------------------- -def obj_f(dvs,config,state=None): - """ val = SU2.eval.obj_f(dvs,config,state=None) - Evaluates SU2 Objectives - Wraps SU2.eval.func() +def obj_f(dvs, config, state=None): + """val = SU2.eval.obj_f(dvs,config,state=None) + + Evaluates SU2 Objectives + Wraps SU2.eval.func() - Takes a design vector for input as a list (shape n) - or numpy array (shape n or nx1 or 1xn), a config - and optionally a state. + Takes a design vector for input as a list (shape n) + or numpy array (shape n or nx1 or 1xn), a config + and optionally a state. - Outputs a float. + Outputs a float. """ # unpack config and state config.unpack_dvs(dvs) state = su2io.State(state) - def_objs = config['OPT_OBJECTIVE'] + def_objs = config["OPT_OBJECTIVE"] objectives = def_objs.keys() # evaluate each objective vals_out = [] func = 0.0 - for i_obj,this_obj in enumerate(objectives): - scale = def_objs[this_obj]['SCALE'] - global_factor = float(config['OPT_GRADIENT_FACTOR']) - sign = su2io.get_objectiveSign(this_obj) + for i_obj, this_obj in enumerate(objectives): + scale = def_objs[this_obj]["SCALE"] + global_factor = float(config["OPT_GRADIENT_FACTOR"]) + sign = su2io.get_objectiveSign(this_obj) # Evaluate Objective Function scaling and sign # If default evaluate as normal, - if def_objs[this_obj]['OBJTYPE']=='DEFAULT': - func += su2func(this_obj,config,state) * sign * scale * global_factor + if def_objs[this_obj]["OBJTYPE"] == "DEFAULT": + func += su2func(this_obj, config, state) * sign * scale * global_factor # otherwise evaluate the penalty function (OBJTYPE = '>','<', or '=') else: - func += obj_p(config,state,this_obj,def_objs) * scale + func += obj_p(config, state, this_obj, def_objs) * scale vals_out.append(func) #: for each objective # If evaluating the combined function is desired, update it here. # This is only used when OPT_COMBINE_OBJECTIVE = YES - if 'COMBO' in state.FUNCTIONS: - state['FUNCTIONS']['COMBO'] = func + if "COMBO" in state.FUNCTIONS: + state["FUNCTIONS"]["COMBO"] = func return vals_out + #: def obj_f() -def obj_p(config,state,this_obj,def_objs): + +def obj_p(config, state, this_obj, def_objs): # Penalty function: square of the difference between value and limit # This function is used when a constraint-type term is added to OPT_OBJECTIVE # This code, and obj_dp, must be changed to use a non-quadratic penalty function - funcval = su2func(this_obj,config,state) - constraint = float(def_objs[this_obj]['VALUE']) + funcval = su2func(this_obj, config, state) + constraint = float(def_objs[this_obj]["VALUE"]) penalty = 0.0 - if (def_objs[this_obj]['OBJTYPE']=='=' or \ - (def_objs[this_obj]['OBJTYPE']=='>' and funcval < constraint) or \ - (def_objs[this_obj]['OBJTYPE']=='<' and funcval > constraint )): - penalty = (constraint - funcval)**2.0 + if ( + def_objs[this_obj]["OBJTYPE"] == "=" + or (def_objs[this_obj]["OBJTYPE"] == ">" and funcval < constraint) + or (def_objs[this_obj]["OBJTYPE"] == "<" and funcval > constraint) + ): + penalty = (constraint - funcval) ** 2.0 # If 'DEFAULT' objtype this returns the function value. else: penalty = funcval return penalty + #: def obj_p() -def obj_dp(config,state,this_obj,def_objs): + +def obj_dp(config, state, this_obj, def_objs): # Partial Derivative of Penalty function: square of the difference between value and limit # This function is used when a constraint-type term is added to OPT_OBJECTIVE # This code, and obj_p, must be changed to use a non-quadratic penalty function - funcval = su2func(this_obj,config,state) - constraint = float(def_objs[this_obj]['VALUE']) - dpenalty=0.0 + funcval = su2func(this_obj, config, state) + constraint = float(def_objs[this_obj]["VALUE"]) + dpenalty = 0.0 # Inequalities will be 0 or a positive value - if ((def_objs[this_obj]['OBJTYPE']=='>' and funcval < constraint) or\ - (def_objs[this_obj]['OBJTYPE']=='<' and funcval > constraint )): - dpenalty=2.0*abs(constraint - funcval) + if (def_objs[this_obj]["OBJTYPE"] == ">" and funcval < constraint) or ( + def_objs[this_obj]["OBJTYPE"] == "<" and funcval > constraint + ): + dpenalty = 2.0 * abs(constraint - funcval) # Equalities dp will be positive if value>constraint, negative if value1): + if combine_obj and n_obj > 1: # Evaluate objectives all-at-once; for adjoint methods this results in a # single, combined objective. - scale = [1.0]*n_obj - obj_list=['DRAG']*n_obj - for i_obj,this_obj in enumerate(objectives): - obj_list[i_obj]=this_obj - scale[i_obj] = def_objs[this_obj]['SCALE'] - if def_objs[this_obj]['OBJTYPE']== 'DEFAULT': + scale = [1.0] * n_obj + obj_list = ["DRAG"] * n_obj + for i_obj, this_obj in enumerate(objectives): + obj_list[i_obj] = this_obj + scale[i_obj] = def_objs[this_obj]["SCALE"] + if def_objs[this_obj]["OBJTYPE"] == "DEFAULT": # Standard case sign = su2io.get_objectiveSign(this_obj) scale[i_obj] *= sign else: # For a penalty function, the term is scaled by the partial derivative # d p(j) / dx = (dj / dx) * ( dp / dj) - scale[i_obj]*=obj_dp(config, state, this_obj, def_objs) + scale[i_obj] *= obj_dp(config, state, this_obj, def_objs) - config['OBJECTIVE_WEIGHT']=','.join(map(str,scale)) - grad= su2grad(obj_list,grad_method,config,state) + config["OBJECTIVE_WEIGHT"] = ",".join(map(str, scale)) + grad = su2grad(obj_list, grad_method, config, state) # scaling : obj scale and sign are accounted for in combo gradient, dv scale now applied - global_factor = float(config['OPT_GRADIENT_FACTOR']) + global_factor = float(config["OPT_GRADIENT_FACTOR"]) k = 0 - for i_dv,dv_scl in enumerate(dv_scales): + for i_dv, dv_scl in enumerate(dv_scales): for i_grd in range(dv_size[i_dv]): - grad[k] = grad[k]*global_factor / dv_scl + grad[k] = grad[k] * global_factor / dv_scl k = k + 1 vals_out.append(grad) else: # Evaluate objectives one-by-one - marker_monitored = config['MARKER_MONITORING'] - for i_obj,this_obj in enumerate(objectives): + marker_monitored = config["MARKER_MONITORING"] + for i_obj, this_obj in enumerate(objectives): # For multiple objectives are evaluated one-by-one rather than combined # MARKER_MONITORING should be updated to only include the marker for i_obj # For single objectives, multiple markers can be used - if (n_obj>1): config['MARKER_MONITORING'] = marker_monitored[i_obj] - scale = def_objs[this_obj]['SCALE'] - global_factor = float(config['OPT_GRADIENT_FACTOR']) - sign = su2io.get_objectiveSign(this_obj) - if def_objs[this_obj]['OBJTYPE']!= 'DEFAULT': + if n_obj > 1: + config["MARKER_MONITORING"] = marker_monitored[i_obj] + scale = def_objs[this_obj]["SCALE"] + global_factor = float(config["OPT_GRADIENT_FACTOR"]) + sign = su2io.get_objectiveSign(this_obj) + if def_objs[this_obj]["OBJTYPE"] != "DEFAULT": # For a penalty function, the term is scaled by the partial derivative # and the sign is always positive # d p(j) / dx = (dj / dx) * ( dp / dj) - scale*=obj_dp(config, state, this_obj, def_objs) + scale *= obj_dp(config, state, this_obj, def_objs) sign = 1.0 # Evaluate Objective Gradient - grad = su2grad(this_obj,grad_method,config,state) + grad = su2grad(this_obj, grad_method, config, state) # scaling and sign k = 0 - for i_dv,dv_scl in enumerate(dv_scales): + for i_dv, dv_scl in enumerate(dv_scales): for i_grd in range(dv_size[i_dv]): grad[k] = grad[k] * sign * scale * global_factor / dv_scl k = k + 1 @@ -392,38 +407,40 @@ def obj_df(dvs,config,state=None): return vals_out + #: def obj_df() -def con_ceq(dvs,config,state=None): - """ vals = SU2.eval.con_ceq(dvs,config,state=None) - Evaluates SU2 Equality Constraints - Wraps SU2.eval.func() +def con_ceq(dvs, config, state=None): + """vals = SU2.eval.con_ceq(dvs,config,state=None) + + Evaluates SU2 Equality Constraints + Wraps SU2.eval.func() - Takes a design vector for input as a list (shape n) - or numpy array (shape n or nx1 or 1xn), a config - and optionally a state. + Takes a design vector for input as a list (shape n) + or numpy array (shape n or nx1 or 1xn), a config + and optionally a state. - Returns: a list of constraint values, ordered - by the OPT_CONSTRAINT config parameter. + Returns: a list of constraint values, ordered + by the OPT_CONSTRAINT config parameter. """ # unpack state and config config.unpack_dvs(dvs) state = su2io.State(state) - def_cons = config['OPT_CONSTRAINT']['EQUALITY'] + def_cons = config["OPT_CONSTRAINT"]["EQUALITY"] constraints = def_cons.keys() # evaluate each constraint vals_out = [] - for i_obj,this_con in enumerate(constraints): - global_factor = float(config['OPT_GRADIENT_FACTOR']) - push = def_cons[this_con]['SCALE'] - value = def_cons[this_con]['VALUE'] + for i_obj, this_con in enumerate(constraints): + global_factor = float(config["OPT_GRADIENT_FACTOR"]) + push = def_cons[this_con]["SCALE"] + value = def_cons[this_con]["VALUE"] # Evaluate Constraint Function - func = su2func(this_con,config,state) + func = su2func(this_con, config, state) # scaling and centering func = (func - value) * global_factor * push @@ -434,45 +451,47 @@ def con_ceq(dvs,config,state=None): return vals_out + #: def obj_ceq() -def con_dceq(dvs,config,state=None): - """ vals = SU2.eval.con_dceq(dvs,config,state=None) - Evaluates SU2 Equality Constraint Gradients - Wraps SU2.eval.grad() +def con_dceq(dvs, config, state=None): + """vals = SU2.eval.con_dceq(dvs,config,state=None) + + Evaluates SU2 Equality Constraint Gradients + Wraps SU2.eval.grad() - Takes a design vector for input as a list (shape n) - or numpy array (shape n or nx1 or 1xn), a config - and optionally a state. + Takes a design vector for input as a list (shape n) + or numpy array (shape n or nx1 or 1xn), a config + and optionally a state. - Returns a list of lists of constraint gradients, - ordered by the OPT_CONSTRAINT config parameter. + Returns a list of lists of constraint gradients, + ordered by the OPT_CONSTRAINT config parameter. """ # unpack state and config config.unpack_dvs(dvs) state = su2io.State(state) - grad_method = config.get('GRADIENT_METHOD','CONTINUOUS_ADJOINT') + grad_method = config.get("GRADIENT_METHOD", "CONTINUOUS_ADJOINT") - def_cons = config['OPT_CONSTRAINT']['EQUALITY'] + def_cons = config["OPT_CONSTRAINT"]["EQUALITY"] constraints = def_cons.keys() - dv_scales = config['DEFINITION_DV']['SCALE'] - dv_size = config['DEFINITION_DV']['SIZE'] + dv_scales = config["DEFINITION_DV"]["SCALE"] + dv_size = config["DEFINITION_DV"]["SIZE"] # evaluate each constraint vals_out = [] - for i_obj,this_con in enumerate(constraints): - global_factor = float(config['OPT_GRADIENT_FACTOR']) - value = def_cons[this_con]['VALUE'] + for i_obj, this_con in enumerate(constraints): + global_factor = float(config["OPT_GRADIENT_FACTOR"]) + value = def_cons[this_con]["VALUE"] # Evaluate Constraint Gradient - grad = su2grad(this_con,grad_method,config,state) + grad = su2grad(this_con, grad_method, config, state) # scaling k = 0 - for i_dv,dv_scl in enumerate(dv_scales): + for i_dv, dv_scl in enumerate(dv_scales): for i_grd in range(dv_size[i_dv]): grad[k] = grad[k] * global_factor / dv_scl k = k + 1 @@ -483,41 +502,43 @@ def con_dceq(dvs,config,state=None): return vals_out + #: def obj_dceq() -def con_cieq(dvs,config,state=None): - """ vals = SU2.eval.con_cieq(dvs,config,state=None) - Evaluates SU2 Inequality Constraints - Wraps SU2.eval.func() - Convention is con(x)<=0 +def con_cieq(dvs, config, state=None): + """vals = SU2.eval.con_cieq(dvs,config,state=None) - Takes a design vector for input as a list (shape n) - or numpy array (shape n or nx1 or 1xn), a config - and optionally a state. + Evaluates SU2 Inequality Constraints + Wraps SU2.eval.func() + Convention is con(x)<=0 - Returns a list of constraint gradients, ordered - by the OPT_CONSTRAINT config parameter. + Takes a design vector for input as a list (shape n) + or numpy array (shape n or nx1 or 1xn), a config + and optionally a state. + + Returns a list of constraint gradients, ordered + by the OPT_CONSTRAINT config parameter. """ # unpack state and config config.unpack_dvs(dvs) state = su2io.State(state) - def_cons = config['OPT_CONSTRAINT']['INEQUALITY'] + def_cons = config["OPT_CONSTRAINT"]["INEQUALITY"] constraints = def_cons.keys() # evaluate each constraint vals_out = [] - for i_obj,this_con in enumerate(constraints): - global_factor = float(config['OPT_GRADIENT_FACTOR']) - push = def_cons[this_con]['SCALE'] - value = def_cons[this_con]['VALUE'] - sign = def_cons[this_con]['SIGN'] - sign = su2io.get_constraintSign(sign) + for i_obj, this_con in enumerate(constraints): + global_factor = float(config["OPT_GRADIENT_FACTOR"]) + push = def_cons[this_con]["SCALE"] + value = def_cons[this_con]["VALUE"] + sign = def_cons[this_con]["SIGN"] + sign = su2io.get_constraintSign(sign) # Evaluate Constraint Function - func = su2func(this_con,config,state) + func = su2func(this_con, config, state) # scaling and centering func = (func - value) * sign * global_factor * push @@ -528,48 +549,50 @@ def con_cieq(dvs,config,state=None): return vals_out + #: def obj_cieq() -def con_dcieq(dvs,config,state=None): - """ vals = SU2.eval.con_dceq(dvs,config,state=None) - Evaluates SU2 Inequality Constraint Gradients - Wraps SU2.eval.grad() - Convention is con(x)<=0 +def con_dcieq(dvs, config, state=None): + """vals = SU2.eval.con_dceq(dvs,config,state=None) + + Evaluates SU2 Inequality Constraint Gradients + Wraps SU2.eval.grad() + Convention is con(x)<=0 - Takes a design vector for input as a list (shape n) - or numpy array (shape n or nx1 or 1xn), a config - and optionally a state. + Takes a design vector for input as a list (shape n) + or numpy array (shape n or nx1 or 1xn), a config + and optionally a state. - Returns a list of lists of constraint gradients, - ordered by the OPT_CONSTRAINT config parameter. + Returns a list of lists of constraint gradients, + ordered by the OPT_CONSTRAINT config parameter. """ # unpack state and config config.unpack_dvs(dvs) state = su2io.State(state) - grad_method = config.get('GRADIENT_METHOD','CONTINUOUS_ADJOINT') + grad_method = config.get("GRADIENT_METHOD", "CONTINUOUS_ADJOINT") - def_cons = config['OPT_CONSTRAINT']['INEQUALITY'] + def_cons = config["OPT_CONSTRAINT"]["INEQUALITY"] constraints = def_cons.keys() - dv_scales = config['DEFINITION_DV']['SCALE'] - dv_size = config['DEFINITION_DV']['SIZE'] + dv_scales = config["DEFINITION_DV"]["SCALE"] + dv_size = config["DEFINITION_DV"]["SIZE"] # evaluate each constraint vals_out = [] - for i_obj,this_con in enumerate(constraints): - global_factor = float(config['OPT_GRADIENT_FACTOR']) - value = def_cons[this_con]['VALUE'] - sign = def_cons[this_con]['SIGN'] - sign = su2io.get_constraintSign(sign) + for i_obj, this_con in enumerate(constraints): + global_factor = float(config["OPT_GRADIENT_FACTOR"]) + value = def_cons[this_con]["VALUE"] + sign = def_cons[this_con]["SIGN"] + sign = su2io.get_constraintSign(sign) # Evaluate Constraint Gradient - grad = su2grad(this_con,grad_method,config,state) + grad = su2grad(this_con, grad_method, config, state) # scaling and sign k = 0 - for i_dv,dv_scl in enumerate(dv_scales): + for i_dv, dv_scl in enumerate(dv_scales): for i_grd in range(dv_size[i_dv]): grad[k] = grad[k] * sign * global_factor / dv_scl k = k + 1 @@ -580,16 +603,19 @@ def con_dcieq(dvs,config,state=None): return vals_out + #: def obj_dcieq() -def touch(config,state): - """ SU2.eval.touch(config,state) - resets state timestamp + +def touch(config, state): + """SU2.eval.touch(config,state) + resets state timestamp """ state.set_timestamp() -def skip(config,state): - """ SU2.eval.skip(config,state) - does nothing + +def skip(config, state): + """SU2.eval.skip(config,state) + does nothing """ pass diff --git a/SU2_PY/SU2/eval/functions.py b/SU2_PY/SU2/eval/functions.py index 78bb2f190a2..08dc2f19692 100644 --- a/SU2_PY/SU2/eval/functions.py +++ b/SU2_PY/SU2/eval/functions.py @@ -30,8 +30,8 @@ # ---------------------------------------------------------------------- import os, sys, shutil, copy, time, subprocess -from .. import run as su2run -from .. import io as su2io +from .. import run as su2run +from .. import io as su2io from .. import util as su2util from ..io import redirect_folder, redirect_output @@ -40,93 +40,101 @@ # Main Function Interface # ---------------------------------------------------------------------- -def function( func_name, config, state=None ): - """ val = SU2.eval.func(func_name,config,state=None) - Evaluates the aerodynamics and geometry functions. +def function(func_name, config, state=None): + """val = SU2.eval.func(func_name,config,state=None) - Wraps: - SU2.eval.aerodynamics() - SU2.eval.geometry() + Evaluates the aerodynamics and geometry functions. - Assumptions: - Config is already setup for deformation. - Mesh need not be deformed. - Updates config and state by reference. - Redundancy if state.FUNCTIONS is not empty. + Wraps: + SU2.eval.aerodynamics() + SU2.eval.geometry() - Executes in: - ./DIRECT or ./GEOMETRY + Assumptions: + Config is already setup for deformation. + Mesh need not be deformed. + Updates config and state by reference. + Redundancy if state.FUNCTIONS is not empty. - Inputs: - func_name - SU2 objective function name or 'ALL' - config - an SU2 config - state - optional, an SU2 state + Executes in: + ./DIRECT or ./GEOMETRY - Outputs: - If func_name is 'ALL', returns a Bunch() of - functions with keys of objective function names - and values of objective function floats. - Otherwise returns a float. + Inputs: + func_name - SU2 objective function name or 'ALL' + config - an SU2 config + state - optional, an SU2 state + + Outputs: + If func_name is 'ALL', returns a Bunch() of + functions with keys of objective function names + and values of objective function floats. + Otherwise returns a float. """ # initialize state = su2io.State(state) # check for multiple objectives - multi_objective = (type(func_name)==list) + multi_objective = type(func_name) == list # func_name_string is only used to check whether the function has already been evaluated. func_name_string = func_name - if multi_objective: func_name_string = func_name[0] + if multi_objective: + func_name_string = func_name[0] # redundancy check - if not func_name_string in state['FUNCTIONS']: + if not func_name_string in state["FUNCTIONS"]: # Aerodynamics - if multi_objective or func_name == 'ALL': - aerodynamics( config, state ) + if multi_objective or func_name == "ALL": + aerodynamics(config, state) elif func_name in su2io.historyOutFields: - if su2io.historyOutFields[func_name]['TYPE'] == 'COEFFICIENT' or su2io.historyOutFields[func_name]['TYPE'] == 'D_COEFFICIENT': - aerodynamics( config, state ) + if ( + su2io.historyOutFields[func_name]["TYPE"] == "COEFFICIENT" + or su2io.historyOutFields[func_name]["TYPE"] == "D_COEFFICIENT" + ): + aerodynamics(config, state) # Stability elif func_name in su2io.optnames_stab: - stability( config, state ) + stability(config, state) # Multipoint elif func_name in su2io.optnames_multi: - multipoint( config, state ) + multipoint(config, state) # Geometry elif func_name in su2io.optnames_geo: - geometry( func_name, config, state ) + geometry(func_name, config, state) else: - raise Exception('unknown function name, %s. Please check config_template.cfg for updated list of function names' % func_name) + raise Exception( + "unknown function name, %s. Please check config_template.cfg for updated list of function names" + % func_name + ) #: if not redundant # prepare output - if func_name == 'ALL': - func_out = state['FUNCTIONS'] - elif (multi_objective): + if func_name == "ALL": + func_out = state["FUNCTIONS"] + elif multi_objective: # If combine_objective is true, use the 'combo' output. - func_out = state['FUNCTIONS']['COMBO'] + func_out = state["FUNCTIONS"]["COMBO"] else: - func_out = state['FUNCTIONS'][func_name] + func_out = state["FUNCTIONS"][func_name] - if func_name_string in config['OPT_OBJECTIVE']: - marker = config['OPT_OBJECTIVE'][func_name_string]['MARKER'] + if func_name_string in config["OPT_OBJECTIVE"]: + marker = config["OPT_OBJECTIVE"][func_name_string]["MARKER"] if func_name_string in su2io.per_surface_map: - name = su2io.per_surface_map[func_name_string]+'_'+marker - if name in state['FUNCTIONS']: - func_out = state['FUNCTIONS'][name] - + name = su2io.per_surface_map[func_name_string] + "_" + marker + if name in state["FUNCTIONS"]: + func_out = state["FUNCTIONS"][name] return copy.deepcopy(func_out) + #: def function() @@ -134,29 +142,30 @@ def function( func_name, config, state=None ): # Aerodynamic Functions # ---------------------------------------------------------------------- -def aerodynamics( config, state=None ): - """ vals = SU2.eval.aerodynamics(config,state=None) - Evaluates aerodynamics with the following: - SU2.run.deform() - SU2.run.direct() +def aerodynamics(config, state=None): + """vals = SU2.eval.aerodynamics(config,state=None) + + Evaluates aerodynamics with the following: + SU2.run.deform() + SU2.run.direct() - Assumptions: - Config is already setup for deformation. - Mesh may or may not be deformed. - Updates config and state by reference. - Redundancy if state.FUNCTIONS is not empty. + Assumptions: + Config is already setup for deformation. + Mesh may or may not be deformed. + Updates config and state by reference. + Redundancy if state.FUNCTIONS is not empty. - Executes in: - ./DIRECT + Executes in: + ./DIRECT - Inputs: - config - an SU2 config - state - optional, an SU2 state + Inputs: + config - an SU2 config + state - optional, an SU2 state - Outputs: - Bunch() of functions with keys of objective function names - and values of objective function floats. + Outputs: + Bunch() of functions with keys of objective function names + and values of objective function floats. """ # ---------------------------------------------------- @@ -167,16 +176,16 @@ def aerodynamics( config, state=None ): state = su2io.State(state) # Make sure to output aerodynamic coeff. - if not 'AERO_COEFF' in config['HISTORY_OUTPUT']: - config['HISTORY_OUTPUT'].append('AERO_COEFF') + if not "AERO_COEFF" in config["HISTORY_OUTPUT"]: + config["HISTORY_OUTPUT"].append("AERO_COEFF") - if not 'MESH' in state.FILES: - state.FILES.MESH = config['MESH_FILENAME'] + if not "MESH" in state.FILES: + state.FILES.MESH = config["MESH_FILENAME"] special_cases = su2io.get_specialCases(config) # console output - if config.get('CONSOLE','VERBOSE') in ['QUIET','CONCISE']: - log_direct = 'log_Direct.out' + if config.get("CONSOLE", "VERBOSE") in ["QUIET", "CONCISE"]: + log_direct = "log_Direct.out" else: log_direct = None @@ -185,13 +194,13 @@ def aerodynamics( config, state=None ): # ---------------------------------------------------- # does decomposition and deformation - info = update_mesh(config,state) + info = update_mesh(config, state) # ---------------------------------------------------- # Adaptation (not implemented) # ---------------------------------------------------- - #if not state.['ADAPTED_FUNC']: + # if not state.['ADAPTED_FUNC']: # config = su2run.adaptation(config) # state['ADAPTED_FUNC'] = True @@ -200,7 +209,7 @@ def aerodynamics( config, state=None ): # ---------------------------------------------------- opt_names = [] for key in su2io.historyOutFields: - if su2io.historyOutFields[key]['TYPE'] == 'COEFFICIENT': + if su2io.historyOutFields[key]["TYPE"] == "COEFFICIENT": opt_names.append(key) # redundancy check @@ -216,104 +225,108 @@ def aerodynamics( config, state=None ): # files to pull files = state.FILES - pull = []; link = [] + pull = [] + link = [] # files: mesh - name = files['MESH'] - name = su2io.expand_part(name,config) + name = files["MESH"] + name = su2io.expand_part(name, config) link.extend(name) - pull.extend(config.get('CONFIG_LIST',[])) + pull.extend(config.get("CONFIG_LIST", [])) # files: restarts - if config.get('TIME_DOMAIN', 'NO') == 'YES' and config.get('RESTART_SOL','NO') =='YES': - if 'RESTART_FILE_1' in files: # not the case for directdiff restart - name = files['RESTART_FILE_1'] + if ( + config.get("TIME_DOMAIN", "NO") == "YES" + and config.get("RESTART_SOL", "NO") == "YES" + ): + if "RESTART_FILE_1" in files: # not the case for directdiff restart + name = files["RESTART_FILE_1"] name = su2io.expand_part(name, config) link.extend(name) - if 'RESTART_FILE_2' in files: # not the case for 1st order time stepping - name = files['RESTART_FILE_2'] + if "RESTART_FILE_2" in files: # not the case for 1st order time stepping + name = files["RESTART_FILE_2"] name = su2io.expand_part(name, config) link.extend(name) - if 'FLOW_META' in files: - pull.append(files['FLOW_META']) + if "FLOW_META" in files: + pull.append(files["FLOW_META"]) # files: direct solution - if 'DIRECT' in files: - name = files['DIRECT'] + if "DIRECT" in files: + name = files["DIRECT"] name = su2io.expand_zones(name, config) - name = su2io.expand_time(name,config) - link.extend( name ) + name = su2io.expand_time(name, config) + link.extend(name) ##config['RESTART_SOL'] = 'YES' # don't override config file else: - if config.get('TIME_DOMAIN', 'NO') != 'YES': #rules out steady state optimization special cases. - config['RESTART_SOL'] = 'NO' #for shape optimization with restart files. + if ( + config.get("TIME_DOMAIN", "NO") != "YES" + ): # rules out steady state optimization special cases. + config["RESTART_SOL"] = "NO" # for shape optimization with restart files. # files: target equivarea distribution - if ( 'EQUIV_AREA' in special_cases and - 'TARGET_EA' in files ) : - pull.append( files['TARGET_EA'] ) + if "EQUIV_AREA" in special_cases and "TARGET_EA" in files: + pull.append(files["TARGET_EA"]) # files: target pressure distribution - if ( 'INV_DESIGN_CP' in special_cases and - 'TARGET_CP' in files ) : - pull.append( files['TARGET_CP'] ) + if "INV_DESIGN_CP" in special_cases and "TARGET_CP" in files: + pull.append(files["TARGET_CP"]) # files: target heat flux distribution - if ( 'INV_DESIGN_HEATFLUX' in special_cases and - 'TARGET_HEATFLUX' in files ) : - pull.append( files['TARGET_HEATFLUX'] ) - + if "INV_DESIGN_HEATFLUX" in special_cases and "TARGET_HEATFLUX" in files: + pull.append(files["TARGET_HEATFLUX"]) # output redirection - with redirect_folder( 'DIRECT', pull, link ) as push: + with redirect_folder("DIRECT", pull, link) as push: with redirect_output(log_direct): # # RUN DIRECT SOLUTION # # info = su2run.direct(config) - - konfig = copy.deepcopy(config) - ''' + """ If the time convergence criterion was activated, we have less time iterations. Store the changed values of TIME_ITER, ITER_AVERAGE_OBJ and UNST_ADJOINT_ITER in - info.WND_CAUCHY_DATA''' - if konfig.get('WINDOW_CAUCHY_CRIT', 'NO') == 'YES' and konfig.TIME_MARCHING != 'NO': # Tranfer Convergence Data, if necessary - konfig['TIME_ITER'] = info.WND_CAUCHY_DATA['TIME_ITER'] - konfig['ITER_AVERAGE_OBJ'] = info.WND_CAUCHY_DATA['ITER_AVERAGE_OBJ'] - konfig['UNST_ADJOINT_ITER'] = info.WND_CAUCHY_DATA['UNST_ADJOINT_ITER'] - - su2io.restart2solution(konfig,info) + info.WND_CAUCHY_DATA""" + if ( + konfig.get("WINDOW_CAUCHY_CRIT", "NO") == "YES" + and konfig.TIME_MARCHING != "NO" + ): # Tranfer Convergence Data, if necessary + konfig["TIME_ITER"] = info.WND_CAUCHY_DATA["TIME_ITER"] + konfig["ITER_AVERAGE_OBJ"] = info.WND_CAUCHY_DATA["ITER_AVERAGE_OBJ"] + konfig["UNST_ADJOINT_ITER"] = info.WND_CAUCHY_DATA["UNST_ADJOINT_ITER"] + + su2io.restart2solution(konfig, info) state.update(info) # direct files to push - name = info.FILES['DIRECT'] - name = su2io.expand_zones(name,konfig) - name = su2io.expand_time(name,konfig) + name = info.FILES["DIRECT"] + name = su2io.expand_zones(name, konfig) + name = su2io.expand_time(name, konfig) push.extend(name) # pressure files to push - if 'TARGET_CP' in info.FILES: - push.append(info.FILES['TARGET_CP']) + if "TARGET_CP" in info.FILES: + push.append(info.FILES["TARGET_CP"]) # heat flux files to push - if 'TARGET_HEATFLUX' in info.FILES: - push.append(info.FILES['TARGET_HEATFLUX']) + if "TARGET_HEATFLUX" in info.FILES: + push.append(info.FILES["TARGET_HEATFLUX"]) - if 'FLOW_META' in info.FILES: - push.append(info.FILES['FLOW_META']) + if "FLOW_META" in info.FILES: + push.append(info.FILES["FLOW_META"]) #: with output redirection - su2io.update_persurface(konfig,state) + su2io.update_persurface(konfig, state) # return output funcs = su2util.ordered_bunch() - for key in state['FUNCTIONS']: - funcs[key] = state['FUNCTIONS'][key] + for key in state["FUNCTIONS"]: + funcs[key] = state["FUNCTIONS"][key] return funcs + #: def aerodynamics() @@ -321,10 +334,10 @@ def aerodynamics( config, state=None ): # Stability Functions # ---------------------------------------------------------------------- -def stability( config, state=None, step=1e-2 ): +def stability(config, state=None, step=1e-2): - folder = 'STABILITY' # os.path.join('STABILITY',func_name) #STABILITY/D_MOMENT_Y_D_ALPHA/ + folder = "STABILITY" # os.path.join('STABILITY',func_name) #STABILITY/D_MOMENT_Y_D_ALPHA/ # ---------------------------------------------------- # Initialize @@ -332,13 +345,13 @@ def stability( config, state=None, step=1e-2 ): # initialize state = su2io.State(state) - if not 'MESH' in state.FILES: - state.FILES.MESH = config['MESH_FILENAME'] + if not "MESH" in state.FILES: + state.FILES.MESH = config["MESH_FILENAME"] special_cases = su2io.get_specialCases(config) # console output - if config.get('CONSOLE','VERBOSE') in ['QUIET','CONCISE']: - log_direct = 'log_Direct.out' + if config.get("CONSOLE", "VERBOSE") in ["QUIET", "CONCISE"]: + log_direct = "log_Direct.out" else: log_direct = None @@ -346,17 +359,15 @@ def stability( config, state=None, step=1e-2 ): # Update Mesh # ---------------------------------------------------- - # does decomposition and deformation - info = update_mesh(config,state) + info = update_mesh(config, state) # ---------------------------------------------------- # CENTRAL POINT # ---------------------------------------------------- # will run in DIRECT/ - func_0 = aerodynamics(config,state) - + func_0 = aerodynamics(config, state) # ---------------------------------------------------- # Run Forward Point @@ -364,59 +375,57 @@ def stability( config, state=None, step=1e-2 ): # files to pull files = state.FILES - pull = []; link = [] + pull = [] + link = [] # files: mesh - name = files['MESH'] - name = su2io.expand_part(name,config) + name = files["MESH"] + name = su2io.expand_part(name, config) link.extend(name) # files: direct solution - if 'DIRECT' in files: - name = files['DIRECT'] - name = su2io.expand_time(name,config) - link.extend( name ) + if "DIRECT" in files: + name = files["DIRECT"] + name = su2io.expand_time(name, config) + link.extend(name) ##config['RESTART_SOL'] = 'YES' # don't override config file else: - config['RESTART_SOL'] = 'NO' + config["RESTART_SOL"] = "NO" # files: target equivarea distribution - if ( 'EQUIV_AREA' in special_cases and - 'TARGET_EA' in files ) : - pull.append( files['TARGET_EA'] ) + if "EQUIV_AREA" in special_cases and "TARGET_EA" in files: + pull.append(files["TARGET_EA"]) # files: target pressure distribution - if ( 'INV_DESIGN_CP' in special_cases and - 'TARGET_CP' in files ) : - pull.append( files['TARGET_CP'] ) + if "INV_DESIGN_CP" in special_cases and "TARGET_CP" in files: + pull.append(files["TARGET_CP"]) # files: target heat flux distribution - if ( 'INV_DESIGN_HEATFLUX' in special_cases and - 'TARGET_HEATFLUX' in files ) : - pull.append( files['TARGET_HEATFLUX'] ) + if "INV_DESIGN_HEATFLUX" in special_cases and "TARGET_HEATFLUX" in files: + pull.append(files["TARGET_HEATFLUX"]) # pull needed files, start folder - with redirect_folder( folder, pull, link ) as push: + with redirect_folder(folder, pull, link) as push: with redirect_output(log_direct): konfig = copy.deepcopy(config) - ztate = copy.deepcopy(state) + ztate = copy.deepcopy(state) # TODO: GENERALIZE konfig.AOA = konfig.AOA + step ztate.FUNCTIONS.clear() - func_1 = aerodynamics(konfig,ztate) + func_1 = aerodynamics(konfig, ztate) ## direct files to store - #name = ztate.FILES['DIRECT'] - #if not 'STABILITY' in state.FILES: - #state.FILES.STABILITY = su2io.ordered_bunch() - #state.FILES.STABILITY['DIRECT'] = name + # name = ztate.FILES['DIRECT'] + # if not 'STABILITY' in state.FILES: + # state.FILES.STABILITY = su2io.ordered_bunch() + # state.FILES.STABILITY['DIRECT'] = name ## equivarea files to store - #if 'WEIGHT_NF' in ztate.FILES: - #state.FILES.STABILITY['WEIGHT_NF'] = ztate.FILES['WEIGHT_NF'] + # if 'WEIGHT_NF' in ztate.FILES: + # state.FILES.STABILITY['WEIGHT_NF'] = ztate.FILES['WEIGHT_NF'] # ---------------------------------------------------- # DIFFERENCING @@ -424,20 +433,20 @@ def stability( config, state=None, step=1e-2 ): for derv_name in su2io.optnames_stab: - matches = [ k for k in su2io.optnames_aero if k in derv_name ] - if not len(matches) == 1: continue + matches = [k for k in su2io.optnames_aero if k in derv_name] + if not len(matches) == 1: + continue func_name = matches[0] - obj_func = ( func_1[func_name] - func_0[func_name] ) / step + obj_func = (func_1[func_name] - func_0[func_name]) / step state.FUNCTIONS[derv_name] = obj_func - # return output funcs = su2util.ordered_bunch() for key in su2io.optnames_stab: - if key in state['FUNCTIONS']: - funcs[key] = state['FUNCTIONS'][key] + if key in state["FUNCTIONS"]: + funcs[key] = state["FUNCTIONS"][key] return funcs @@ -446,21 +455,47 @@ def stability( config, state=None, step=1e-2 ): # Multipoint Functions # ---------------------------------------------------------------------- -def multipoint( config, state=None, step=1e-2 ): - - mach_list = config['MULTIPOINT_MACH_NUMBER'].replace("(", "").replace(")", "").split(',') - reynolds_list = config['MULTIPOINT_REYNOLDS_NUMBER'].replace("(", "").replace(")", "").split(',') - freestream_temp_list = config['MULTIPOINT_FREESTREAM_TEMPERATURE'].replace("(", "").replace(")", "").split(',') - freestream_press_list = config['MULTIPOINT_FREESTREAM_PRESSURE'].replace("(", "").replace(")", "").split(',') - aoa_list = config['MULTIPOINT_AOA'].replace("(", "").replace(")", "").split(',') - sideslip_list = config['MULTIPOINT_SIDESLIP_ANGLE'].replace("(", "").replace(")", "").split(',') - target_cl_list = config['MULTIPOINT_TARGET_CL'].replace("(", "").replace(")", "").split(',') - weight_list = config['MULTIPOINT_WEIGHT'].replace("(", "").replace(")", "").split(',') - outlet_value_list = config['MULTIPOINT_OUTLET_VALUE'].replace("(", "").replace(")", "").split(',') + +def multipoint(config, state=None, step=1e-2): + + mach_list = ( + config["MULTIPOINT_MACH_NUMBER"].replace("(", "").replace(")", "").split(",") + ) + reynolds_list = ( + config["MULTIPOINT_REYNOLDS_NUMBER"] + .replace("(", "") + .replace(")", "") + .split(",") + ) + freestream_temp_list = ( + config["MULTIPOINT_FREESTREAM_TEMPERATURE"] + .replace("(", "") + .replace(")", "") + .split(",") + ) + freestream_press_list = ( + config["MULTIPOINT_FREESTREAM_PRESSURE"] + .replace("(", "") + .replace(")", "") + .split(",") + ) + aoa_list = config["MULTIPOINT_AOA"].replace("(", "").replace(")", "").split(",") + sideslip_list = ( + config["MULTIPOINT_SIDESLIP_ANGLE"].replace("(", "").replace(")", "").split(",") + ) + target_cl_list = ( + config["MULTIPOINT_TARGET_CL"].replace("(", "").replace(")", "").split(",") + ) + weight_list = ( + config["MULTIPOINT_WEIGHT"].replace("(", "").replace(")", "").split(",") + ) + outlet_value_list = ( + config["MULTIPOINT_OUTLET_VALUE"].replace("(", "").replace(")", "").split(",") + ) solution_flow_list = su2io.expand_multipoint(config.SOLUTION_FILENAME, config) - flow_meta_list = su2io.expand_multipoint('flow.meta', config) - restart_sol = config['RESTART_SOL'] - dv_value_old = config['DV_VALUE_OLD']; + flow_meta_list = su2io.expand_multipoint("flow.meta", config) + restart_sol = config["RESTART_SOL"] + dv_value_old = config["DV_VALUE_OLD"] func = [] folder = [] @@ -469,11 +504,11 @@ def multipoint( config, state=None, step=1e-2 ): folder.append(0) for i in range(len(weight_list)): - folder[i] = 'MULTIPOINT_' + str(i) + folder[i] = "MULTIPOINT_" + str(i) opt_names = [] for key in su2io.historyOutFields: - if su2io.historyOutFields[key]['TYPE'] == 'COEFFICIENT': + if su2io.historyOutFields[key]["TYPE"] == "COEFFICIENT": opt_names.append(key) # ---------------------------------------------------- @@ -482,13 +517,13 @@ def multipoint( config, state=None, step=1e-2 ): # initialize state = su2io.State(state) - if not 'MESH' in state.FILES: - state.FILES.MESH = config['MESH_FILENAME'] + if not "MESH" in state.FILES: + state.FILES.MESH = config["MESH_FILENAME"] special_cases = su2io.get_specialCases(config) # console output - if config.get('CONSOLE','VERBOSE') in ['QUIET','CONCISE']: - log_direct = 'log_Direct.out' + if config.get("CONSOLE", "VERBOSE") in ["QUIET", "CONCISE"]: + log_direct = "log_Direct.out" else: log_direct = None @@ -497,12 +532,12 @@ def multipoint( config, state=None, step=1e-2 ): # ---------------------------------------------------- # If multiple meshes specified, use relevant mesh - if 'MULTIPOINT_MESH_FILENAME' in state.FILES: + if "MULTIPOINT_MESH_FILENAME" in state.FILES: state.FILES.MESH = state.FILES.MULTIPOINT_MESH_FILENAME[0] config.MESH_FILENAME = state.FILES.MULTIPOINT_MESH_FILENAME[0] # does decomposition and deformation - info = update_mesh(config,state) + info = update_mesh(config, state) # ---------------------------------------------------- # FIRST POINT @@ -517,209 +552,223 @@ def multipoint( config, state=None, step=1e-2 ): config.FREESTREAM_TEMPERATURE = freestream_temp_list[0] config.FREESTREAM_PRESSURE = freestream_press_list[0] config.TARGET_CL = target_cl_list[0] - orig_marker_outlet = config['MARKER_OUTLET'] - orig_marker_outlet = orig_marker_outlet.replace("(", "").replace(")", "").split(',') + orig_marker_outlet = config["MARKER_OUTLET"] + orig_marker_outlet = orig_marker_outlet.replace("(", "").replace(")", "").split(",") new_marker_outlet = "(" + orig_marker_outlet[0] + "," + outlet_value_list[0] + ")" config.MARKER_OUTLET = new_marker_outlet config.SOLUTION_FILENAME = solution_flow_list[0] # If solution file for the first point is available, use it - if 'MULTIPOINT_DIRECT' in state.FILES and state.FILES.MULTIPOINT_DIRECT[0]: - state.FILES['DIRECT'] = state.FILES.MULTIPOINT_DIRECT[0] + if "MULTIPOINT_DIRECT" in state.FILES and state.FILES.MULTIPOINT_DIRECT[0]: + state.FILES["DIRECT"] = state.FILES.MULTIPOINT_DIRECT[0] # If flow.meta file for the first point is available, rename it before using it - if 'MULTIPOINT_FLOW_META' in state.FILES and state.FILES.MULTIPOINT_FLOW_META[0]: - os.rename(state.FILES.MULTIPOINT_FLOW_META[0], 'flow.meta') - state.FILES['FLOW_META'] = 'flow.meta' + if "MULTIPOINT_FLOW_META" in state.FILES and state.FILES.MULTIPOINT_FLOW_META[0]: + os.rename(state.FILES.MULTIPOINT_FLOW_META[0], "flow.meta") + state.FILES["FLOW_META"] = "flow.meta" - func[0] = aerodynamics(config,state) + func[0] = aerodynamics(config, state) # change name of flow.meta back to multipoint name - if os.path.exists('flow.meta'): - os.rename('flow.meta', flow_meta_list[0]) - state.FILES['FLOW_META'] = flow_meta_list[0] + if os.path.exists("flow.meta"): + os.rename("flow.meta", flow_meta_list[0]) + state.FILES["FLOW_META"] = flow_meta_list[0] src = os.getcwd() - src = os.path.abspath(src).rstrip('/')+'/DIRECT/' + src = os.path.abspath(src).rstrip("/") + "/DIRECT/" # files to pull files = state.FILES - pull = []; link = [] + pull = [] + link = [] # files: mesh - name = files['MESH'] - name = su2io.expand_part(name,config) + name = files["MESH"] + name = su2io.expand_part(name, config) link.extend(name) # files: direct solution - if 'DIRECT' in files: - name = files['DIRECT'] - name = su2io.expand_time(name,config) - link.extend( name ) + if "DIRECT" in files: + name = files["DIRECT"] + name = su2io.expand_time(name, config) + link.extend(name) else: - config['RESTART_SOL'] = 'NO' + config["RESTART_SOL"] = "NO" # files: meta data for the flow - if 'FLOW_META' in files: - pull.append(files['FLOW_META']) + if "FLOW_META" in files: + pull.append(files["FLOW_META"]) # files: target equivarea distribution - if ( 'EQUIV_AREA' in special_cases and - 'TARGET_EA' in files ) : - pull.append( files['TARGET_EA'] ) + if "EQUIV_AREA" in special_cases and "TARGET_EA" in files: + pull.append(files["TARGET_EA"]) # files: target pressure distribution - if ( 'INV_DESIGN_CP' in special_cases and - 'TARGET_CP' in files ) : - pull.append( files['TARGET_CP'] ) + if "INV_DESIGN_CP" in special_cases and "TARGET_CP" in files: + pull.append(files["TARGET_CP"]) # files: target heat flux distribution - if ( 'INV_DESIGN_HEATFLUX' in special_cases and - 'TARGET_HEATFLUX' in files ) : - pull.append( files['TARGET_HEATFLUX'] ) + if "INV_DESIGN_HEATFLUX" in special_cases and "TARGET_HEATFLUX" in files: + pull.append(files["TARGET_HEATFLUX"]) # pull needed files, start folder_0 - with redirect_folder( folder[0], pull, link ) as push: + with redirect_folder(folder[0], pull, link) as push: with redirect_output(log_direct): konfig = copy.deepcopy(config) - ztate = copy.deepcopy(state) + ztate = copy.deepcopy(state) # Reset restart to original value - konfig['RESTART_SOL'] = restart_sol + konfig["RESTART_SOL"] = restart_sol dst = os.getcwd() - dst = os.path.abspath(dst).rstrip('/')+'/'+'DIRECT' + dst = os.path.abspath(dst).rstrip("/") + "/" + "DIRECT" # make unix link string = "ln -s " + src + " " + dst stringlist = string.split() subprocess.Popen(stringlist) - for i in range(len(weight_list)-1): + for i in range(len(weight_list) - 1): konfig = copy.deepcopy(config) - ztate = copy.deepcopy(state) + ztate = copy.deepcopy(state) - konfig.SOLUTION_FILENAME = solution_flow_list[i+1] + konfig.SOLUTION_FILENAME = solution_flow_list[i + 1] # delete direct solution file from previous point - if 'DIRECT' in ztate.FILES: + if "DIRECT" in ztate.FILES: del ztate.FILES.DIRECT - if 'FLOW_META' in ztate.FILES: + if "FLOW_META" in ztate.FILES: del ztate.FILES.FLOW_META # use direct solution file from relevant point - if 'MULTIPOINT_DIRECT' in state.FILES and state.FILES.MULTIPOINT_DIRECT[i+1]: - ztate.FILES['DIRECT'] = state.FILES.MULTIPOINT_DIRECT[i+1] + if "MULTIPOINT_DIRECT" in state.FILES and state.FILES.MULTIPOINT_DIRECT[i + 1]: + ztate.FILES["DIRECT"] = state.FILES.MULTIPOINT_DIRECT[i + 1] # use flow.meta file from relevant point - if 'MULTIPOINT_FLOW_META' in state.FILES and state.FILES.MULTIPOINT_FLOW_META[i+1]: - ztate.FILES['FLOW_META'] = state.FILES.MULTIPOINT_FLOW_META[i+1] + if ( + "MULTIPOINT_FLOW_META" in state.FILES + and state.FILES.MULTIPOINT_FLOW_META[i + 1] + ): + ztate.FILES["FLOW_META"] = state.FILES.MULTIPOINT_FLOW_META[i + 1] # use mesh file from relevant point - if 'MULTIPOINT_MESH_FILENAME' in ztate.FILES: - ztate.FILES.MESH = ztate.FILES.MULTIPOINT_MESH_FILENAME[i+1] - konfig.MESH_FILENAME= ztate.FILES.MULTIPOINT_MESH_FILENAME[i+1] - konfig['DV_VALUE_OLD'] = dv_value_old + if "MULTIPOINT_MESH_FILENAME" in ztate.FILES: + ztate.FILES.MESH = ztate.FILES.MULTIPOINT_MESH_FILENAME[i + 1] + konfig.MESH_FILENAME = ztate.FILES.MULTIPOINT_MESH_FILENAME[i + 1] + konfig["DV_VALUE_OLD"] = dv_value_old files = ztate.FILES link = [] pull = [] # files: mesh - name = files['MESH'] - name = su2io.expand_part(name,konfig) + name = files["MESH"] + name = su2io.expand_part(name, konfig) link.extend(name) # files: direction solution - if 'DIRECT' in files: - name = files['DIRECT'] - name = su2io.expand_time(name,konfig) - link.extend( name ) + if "DIRECT" in files: + name = files["DIRECT"] + name = su2io.expand_time(name, konfig) + link.extend(name) else: - konfig['RESTART_SOL'] = 'NO' + konfig["RESTART_SOL"] = "NO" # files: meta data for the flow - if 'FLOW_META' in files: - pull.append(files['FLOW_META']) + if "FLOW_META" in files: + pull.append(files["FLOW_META"]) # pull needed files, start folder_1 - with redirect_folder( folder[i+1], pull, link ) as push: + with redirect_folder(folder[i + 1], pull, link) as push: with redirect_output(log_direct): # Perform deformation on multipoint mesh - if 'MULTIPOINT_MESH_FILENAME' in state.FILES: - info = update_mesh(konfig,ztate) + if "MULTIPOINT_MESH_FILENAME" in state.FILES: + info = update_mesh(konfig, ztate) # Update config values - konfig.AOA = aoa_list[i+1] - konfig.SIDESLIP_ANGLE = sideslip_list[i+1] - konfig.MACH_NUMBER = mach_list[i+1] - konfig.REYNOLDS_NUMBER = reynolds_list[i+1] - konfig.FREESTREAM_TEMPERATURE = freestream_temp_list[i+1] - konfig.FREESTREAM_PRESSURE = freestream_press_list[i+1] - konfig.TARGET_CL = target_cl_list[i+1] - orig_marker_outlet = config['MARKER_OUTLET'] - orig_marker_outlet = orig_marker_outlet.replace("(", "").replace(")", "").split(',') - new_marker_outlet = "(" + orig_marker_outlet[0] + "," + outlet_value_list[i+1] + ")" + konfig.AOA = aoa_list[i + 1] + konfig.SIDESLIP_ANGLE = sideslip_list[i + 1] + konfig.MACH_NUMBER = mach_list[i + 1] + konfig.REYNOLDS_NUMBER = reynolds_list[i + 1] + konfig.FREESTREAM_TEMPERATURE = freestream_temp_list[i + 1] + konfig.FREESTREAM_PRESSURE = freestream_press_list[i + 1] + konfig.TARGET_CL = target_cl_list[i + 1] + orig_marker_outlet = config["MARKER_OUTLET"] + orig_marker_outlet = ( + orig_marker_outlet.replace("(", "").replace(")", "").split(",") + ) + new_marker_outlet = ( + "(" + orig_marker_outlet[0] + "," + outlet_value_list[i + 1] + ")" + ) konfig.MARKER_OUTLET = new_marker_outlet ztate.FUNCTIONS.clear() # rename meta data to flow.meta - if 'FLOW_META' in ztate.FILES: - ztate.FILES['FLOW_META'] = 'flow.meta' - os.rename(ztate.FILES.MULTIPOINT_FLOW_META[i+1], 'flow.meta') + if "FLOW_META" in ztate.FILES: + ztate.FILES["FLOW_META"] = "flow.meta" + os.rename(ztate.FILES.MULTIPOINT_FLOW_META[i + 1], "flow.meta") - func[i+1] = aerodynamics(konfig,ztate) + func[i + 1] = aerodynamics(konfig, ztate) dst = os.getcwd() # revert name of flow.meta file to multipoint name - if os.path.exists('flow.meta'): - os.rename('flow.meta', flow_meta_list[i+1]) - ztate.FILES['FLOW_META'] = flow_meta_list[i+1] - dst_flow_meta = os.path.abspath(dst).rstrip('/')+'/'+ztate.FILES['FLOW_META'] - push.append(ztate.FILES['FLOW_META']) + if os.path.exists("flow.meta"): + os.rename("flow.meta", flow_meta_list[i + 1]) + ztate.FILES["FLOW_META"] = flow_meta_list[i + 1] + dst_flow_meta = ( + os.path.abspath(dst).rstrip("/") + + "/" + + ztate.FILES["FLOW_META"] + ) + push.append(ztate.FILES["FLOW_META"]) # direct files to push - dst_direct = os.path.abspath(dst).rstrip('/')+'/'+ztate.FILES['DIRECT'] - name = ztate.FILES['DIRECT'] - name = su2io.expand_zones(name,konfig) - name = su2io.expand_time(name,konfig) + dst_direct = ( + os.path.abspath(dst).rstrip("/") + "/" + ztate.FILES["DIRECT"] + ) + name = ztate.FILES["DIRECT"] + name = su2io.expand_zones(name, konfig) + name = su2io.expand_time(name, konfig) push.extend(name) - if 'MULTIPOINT_MESH_FILENAME' in state.FILES: + if "MULTIPOINT_MESH_FILENAME" in state.FILES: # Mesh files to push - dst_mesh = os.path.abspath(dst).rstrip('/')+'/'+ztate.FILES['MESH'] - name = ztate.FILES['MESH'] - name = su2io.expand_part(name,konfig) + dst_mesh = ( + os.path.abspath(dst).rstrip("/") + "/" + ztate.FILES["MESH"] + ) + name = ztate.FILES["MESH"] + name = su2io.expand_part(name, konfig) push.extend(name) - # Link direct solution to MULTIPOINT_# folder src = os.getcwd() - src_direct = os.path.abspath(src).rstrip('/')+'/'+ztate.FILES['DIRECT'] + src_direct = os.path.abspath(src).rstrip("/") + "/" + ztate.FILES["DIRECT"] # make unix link os.symlink(src_direct, dst_direct) # If the mesh doesn't already exist, link it - if 'MULTIPOINT_MESH_FILENAME' in state.FILES: - src_mesh = os.path.abspath(src).rstrip('/')+'/'+ztate.FILES['MESH'] + if "MULTIPOINT_MESH_FILENAME" in state.FILES: + src_mesh = os.path.abspath(src).rstrip("/") + "/" + ztate.FILES["MESH"] if not os.path.exists(src_mesh): os.symlink(src_mesh, dst_mesh) # link flow.meta - if 'MULTIPOINT_FLOW_META' in state.FILES: - src_flow_meta = os.path.abspath(src).rstrip('/')+'/'+ztate.FILES['FLOW_META'] + if "MULTIPOINT_FLOW_META" in state.FILES: + src_flow_meta = ( + os.path.abspath(src).rstrip("/") + "/" + ztate.FILES["FLOW_META"] + ) if not os.path.exists(src_flow_meta): os.symlink(src_flow_meta, dst_flow_meta) # Update MULTIPOINT_DIRECT in state.FILES state.FILES.MULTIPOINT_DIRECT = solution_flow_list - if 'FLOW_META' in state.FILES: + if "FLOW_META" in state.FILES: state.FILES.MULTIPOINT_FLOW_META = flow_meta_list # ---------------------------------------------------- @@ -727,20 +776,21 @@ def multipoint( config, state=None, step=1e-2 ): # ---------------------------------------------------- for derv_name in su2io.optnames_multi: - matches = [ k for k in opt_names if k in derv_name ] - if not len(matches) == 1: continue + matches = [k for k in opt_names if k in derv_name] + if not len(matches) == 1: + continue func_name = matches[0] obj_func = 0.0 for i in range(len(weight_list)): - obj_func = obj_func + float(weight_list[i])*func[i][func_name] + obj_func = obj_func + float(weight_list[i]) * func[i][func_name] state.FUNCTIONS[derv_name] = obj_func # return output funcs = su2util.ordered_bunch() for key in su2io.optnames_multi: - if key in state['FUNCTIONS']: - funcs[key] = state['FUNCTIONS'][key] + if key in state["FUNCTIONS"]: + funcs[key] = state["FUNCTIONS"][key] return funcs @@ -749,29 +799,30 @@ def multipoint( config, state=None, step=1e-2 ): # Geometric Functions # ---------------------------------------------------------------------- -def geometry( func_name, config, state=None ): - """ val = SU2.eval.geometry(config,state=None) - Evaluates geometry with the following: - SU2.run.deform() - SU2.run.geometry() +def geometry(func_name, config, state=None): + """val = SU2.eval.geometry(config,state=None) + + Evaluates geometry with the following: + SU2.run.deform() + SU2.run.geometry() - Assumptions: - Config is already setup for deformation. - Mesh may or may not be deformed. - Updates config and state by reference. - Redundancy if state.FUNCTIONS does not have func_name. + Assumptions: + Config is already setup for deformation. + Mesh may or may not be deformed. + Updates config and state by reference. + Redundancy if state.FUNCTIONS does not have func_name. - Executes in: - ./GEOMETRY + Executes in: + ./GEOMETRY - Inputs: - config - an SU2 config - state - optional, an SU2 state + Inputs: + config - an SU2 config + state - optional, an SU2 state - Outputs: - Bunch() of functions with keys of objective function names - and values of objective function floats. + Outputs: + Bunch() of functions with keys of objective function names + and values of objective function floats. """ # ---------------------------------------------------- @@ -780,13 +831,13 @@ def geometry( func_name, config, state=None ): # initialize state = su2io.State(state) - if not 'MESH' in state.FILES: - state.FILES.MESH = config['MESH_FILENAME'] + if not "MESH" in state.FILES: + state.FILES.MESH = config["MESH_FILENAME"] special_cases = su2io.get_specialCases(config) # console output - if config.get('CONSOLE','VERBOSE') in ['QUIET','CONCISE']: - log_geom = 'log_Geometry.out' + if config.get("CONSOLE", "VERBOSE") in ["QUIET", "CONCISE"]: + log_geom = "log_Geometry.out" else: log_geom = None @@ -795,8 +846,7 @@ def geometry( func_name, config, state=None ): # ---------------------------------------------------- # does decomposition and deformation - #info = update_mesh(config,state) - + # info = update_mesh(config,state) # ---------------------------------------------------- # Geometry Solution @@ -804,28 +854,29 @@ def geometry( func_name, config, state=None ): # redundancy check geometry_done = func_name in state.FUNCTIONS - #geometry_done = all([key in state.FUNCTIONS for key in su2io.optnames_geo]) + # geometry_done = all([key in state.FUNCTIONS for key in su2io.optnames_geo]) if not geometry_done: # files to pull files = state.FILES - pull = []; link = [] + pull = [] + link = [] # files: mesh - name = files['MESH'] - name = su2io.expand_part(name,config) + name = files["MESH"] + name = su2io.expand_part(name, config) link.extend(name) # update function name ## TODO # output redirection - with redirect_folder( 'GEOMETRY', pull, link ) as push: + with redirect_folder("GEOMETRY", pull, link) as push: with redirect_output(log_geom): # setup config config.GEO_PARAM = func_name - config.GEO_MODE = 'FUNCTION' + config.GEO_MODE = "FUNCTION" # # RUN GEOMETRY SOLUTION # # info = su2run.geometry(config) @@ -840,38 +891,37 @@ def geometry( func_name, config, state=None ): # return output funcs = su2util.ordered_bunch() for key in su2io.optnames_geo: - if key in state['FUNCTIONS']: - funcs[key] = state['FUNCTIONS'][key] + if key in state["FUNCTIONS"]: + funcs[key] = state["FUNCTIONS"][key] return funcs #: def geometry() +def update_mesh(config, state=None): + """SU2.eval.update_mesh(config,state=None) -def update_mesh(config,state=None): - """ SU2.eval.update_mesh(config,state=None) + updates mesh with the following: + SU2.run.deform() - updates mesh with the following: - SU2.run.deform() + Assumptions: + Config is already setup for deformation. + Mesh may or may not be deformed. + Updates config and state by reference. - Assumptions: - Config is already setup for deformation. - Mesh may or may not be deformed. - Updates config and state by reference. + Executes in: + ./DECOMP and ./DEFORM - Executes in: - ./DECOMP and ./DEFORM + Inputs: + config - an SU2 config + state - optional, an SU2 state - Inputs: - config - an SU2 config - state - optional, an SU2 state + Outputs: + nothing - Outputs: - nothing - - Modifies: - config and state by reference + Modifies: + config and state by reference """ # ---------------------------------------------------- @@ -880,37 +930,36 @@ def update_mesh(config,state=None): # initialize state = su2io.State(state) - if not 'MESH' in state.FILES: - state.FILES.MESH = config['MESH_FILENAME'] + if not "MESH" in state.FILES: + state.FILES.MESH = config["MESH_FILENAME"] special_cases = su2io.get_specialCases(config) # console output - if config.get('CONSOLE','VERBOSE') in ['QUIET','CONCISE']: - log_decomp = 'log_Decomp.out' - log_deform = 'log_Deform.out' + if config.get("CONSOLE", "VERBOSE") in ["QUIET", "CONCISE"]: + log_decomp = "log_Decomp.out" + log_deform = "log_Deform.out" else: log_decomp = None log_deform = None - # ---------------------------------------------------- # Deformation # ---------------------------------------------------- # redundancy check - deform_set = config['DV_KIND'] == config['DEFINITION_DV']['KIND'] - deform_todo = not config['DV_VALUE_NEW'] == config['DV_VALUE_OLD'] + deform_set = config["DV_KIND"] == config["DEFINITION_DV"]["KIND"] + deform_todo = not config["DV_VALUE_NEW"] == config["DV_VALUE_OLD"] if deform_set and deform_todo: # files to pull pull = [] - link = config['MESH_FILENAME'] - link = su2io.expand_part(link,config) + link = config["MESH_FILENAME"] + link = su2io.expand_part(link, config) - pull.extend(config.get('CONFIG_LIST',[])) + pull.extend(config.get("CONFIG_LIST", [])) # output redirection - with redirect_folder('DEFORM',pull,link) as push: + with redirect_folder("DEFORM", pull, link) as push: with redirect_output(log_deform): # # RUN DEFORMATION # # @@ -919,8 +968,8 @@ def update_mesh(config,state=None): # data to push meshname = info.FILES.MESH - names = su2io.expand_part( meshname , config ) - push.extend( names ) + names = su2io.expand_part(meshname, config) + push.extend(names) #: with redirect output @@ -930,4 +979,3 @@ def update_mesh(config,state=None): #: if not redundant return - diff --git a/SU2_PY/SU2/eval/gradients.py b/SU2_PY/SU2/eval/gradients.py index 739001f24e4..da8b76d94c7 100644 --- a/SU2_PY/SU2/eval/gradients.py +++ b/SU2_PY/SU2/eval/gradients.py @@ -30,8 +30,8 @@ # ---------------------------------------------------------------------- import os, sys, shutil, copy, subprocess -from .. import run as su2run -from .. import io as su2io +from .. import run as su2run +from .. import io as su2io from .. import util as su2util from .functions import function, update_mesh from ..io import redirect_folder, redirect_output @@ -41,99 +41,101 @@ # Main Gradient Interface # ---------------------------------------------------------------------- -def gradient( func_name, method, config, state=None ): - """ val = SU2.eval.grad(func_name,method,config,state=None) - Evaluates the aerodynamic gradients. +def gradient(func_name, method, config, state=None): + """val = SU2.eval.grad(func_name,method,config,state=None) - Wraps: - SU2.eval.adjoint() - SU2.eval.findiff() + Evaluates the aerodynamic gradients. - Assumptions: - Config is already setup for deformation. - Mesh need not be deformed. - Updates config and state by reference. - Redundancy if state.GRADIENTS has the key func_name. + Wraps: + SU2.eval.adjoint() + SU2.eval.findiff() - Executes in: - ./ADJOINT_* or ./FINDIFF + Assumptions: + Config is already setup for deformation. + Mesh need not be deformed. + Updates config and state by reference. + Redundancy if state.GRADIENTS has the key func_name. - Inputs: - func_name - SU2 objective function name - method - 'CONTINUOUS_ADJOINT' or 'FINDIFF' or 'DISCRETE_ADJOINT' - config - an SU2 config - state - optional, an SU2 state + Executes in: + ./ADJOINT_* or ./FINDIFF - Outputs: - A list of floats of gradient values + Inputs: + func_name - SU2 objective function name + method - 'CONTINUOUS_ADJOINT' or 'FINDIFF' or 'DISCRETE_ADJOINT' + config - an SU2 config + state - optional, an SU2 state + + Outputs: + A list of floats of gradient values """ # Initialize grads = {} state = su2io.State(state) - if func_name == 'ALL': + if func_name == "ALL": raise Exception("func_name = 'ALL' not yet supported") func_output = func_name - if (type(func_name)==list): - if (config.OPT_COMBINE_OBJECTIVE=="YES"): - func_output = 'COMBO' + if type(func_name) == list: + if config.OPT_COMBINE_OBJECTIVE == "YES": + func_output = "COMBO" else: func_name = func_name[0] else: - config.OPT_COMBINE_OBJECTIVE="NO" + config.OPT_COMBINE_OBJECTIVE = "NO" config.OBJECTIVE_WEIGHT = "1.0" # redundancy check - if not func_output in state['GRADIENTS']: + if not func_output in state["GRADIENTS"]: # Adjoint Gradients - if any([method == 'CONTINUOUS_ADJOINT', method == 'DISCRETE_ADJOINT']): + if any([method == "CONTINUOUS_ADJOINT", method == "DISCRETE_ADJOINT"]): # Aerodynamics if func_output in su2io.historyOutFields: - if su2io.historyOutFields[func_output]['TYPE'] == 'COEFFICIENT': - grads = adjoint( func_name, config, state ) + if su2io.historyOutFields[func_output]["TYPE"] == "COEFFICIENT": + grads = adjoint(func_name, config, state) elif func_name in su2io.historyOutFields: - if su2io.historyOutFields[func_name]['TYPE'] == 'COEFFICIENT': - grads = adjoint( func_name, config, state ) + if su2io.historyOutFields[func_name]["TYPE"] == "COEFFICIENT": + grads = adjoint(func_name, config, state) # Stability elif func_output in su2io.optnames_stab: - grads = stability( func_name, config, state ) + grads = stability(func_name, config, state) # Multipoint elif func_output in su2io.optnames_multi: - grads = multipoint( func_name, config, state ) + grads = multipoint(func_name, config, state) # Geometry (actually a finite difference) elif func_output in su2io.optnames_geo: - grads = geometry( func_name, config, state ) + grads = geometry(func_name, config, state) else: - raise Exception('unknown function name: %s' % func_name) + raise Exception("unknown function name: %s" % func_name) # Finite Difference Gradients - elif method == 'FINDIFF': - grads = findiff( config, state ) + elif method == "FINDIFF": + grads = findiff(config, state) - elif method == 'DIRECTDIFF': - grad = directdiff (config , state ) + elif method == "DIRECTDIFF": + grad = directdiff(config, state) else: - raise Exception('unrecognized gradient method') + raise Exception("unrecognized gradient method") # store - state['GRADIENTS'].update(grads) + state["GRADIENTS"].update(grads) # if not redundant # prepare output - grads_out = state['GRADIENTS'][func_output] + grads_out = state["GRADIENTS"][func_output] return copy.deepcopy(grads_out) + #: def gradient() @@ -141,34 +143,35 @@ def gradient( func_name, method, config, state=None ): # Adjoint Gradients # ---------------------------------------------------------------------- -def adjoint( func_name, config, state=None ): - """ vals = SU2.eval.adjoint(func_name,config,state=None) - - Evaluates the aerodynamics gradients using the - adjoint methodology with: - SU2.eval.func() - SU2.run.deform() - SU2.run.direct() - SU2.run.adjoint() - - Assumptions: - Config is already setup for deformation. - Mesh may or may not be deformed. - Updates config and state by reference. - Adjoint Redundancy if state.GRADIENTS has key func_name. - Direct Redundancy if state.FUNCTIONS has key func_name. - - Executes in: - ./ADJOINT_ - - Inputs: - func_name - SU2 objective function name - config - an SU2 config - state - optional, an SU2 state - - Outputs: - A Bunch() with keys of objective function names - and values of list of floats of gradient values + +def adjoint(func_name, config, state=None): + """vals = SU2.eval.adjoint(func_name,config,state=None) + + Evaluates the aerodynamics gradients using the + adjoint methodology with: + SU2.eval.func() + SU2.run.deform() + SU2.run.direct() + SU2.run.adjoint() + + Assumptions: + Config is already setup for deformation. + Mesh may or may not be deformed. + Updates config and state by reference. + Adjoint Redundancy if state.GRADIENTS has key func_name. + Direct Redundancy if state.FUNCTIONS has key func_name. + + Executes in: + ./ADJOINT_ + + Inputs: + func_name - SU2 objective function name + config - an SU2 config + state - optional, an SU2 state + + Outputs: + A Bunch() with keys of objective function names + and values of list of floats of gradient values """ # ---------------------------------------------------- @@ -181,15 +184,16 @@ def adjoint( func_name, config, state=None ): # When a list of objectives is used, they are combined # and the output name is 'COMBO' - multi_objective = (type(func_name)==list) + multi_objective = type(func_name) == list func_output = func_name - if multi_objective: func_output = 'COMBO' + if multi_objective: + func_output = "COMBO" - ADJ_NAME = 'ADJOINT_'+func_output + ADJ_NAME = "ADJOINT_" + func_output # console output - if config.get('CONSOLE','VERBOSE') in ['QUIET','CONCISE']: - log_adjoint = 'log_Adjoint.out' + if config.get("CONSOLE", "VERBOSE") in ["QUIET", "CONCISE"]: + log_adjoint = "log_Adjoint.out" else: log_adjoint = None @@ -198,8 +202,8 @@ def adjoint( func_name, config, state=None ): # ---------------------------------------------------- # master redundancy check - if func_output in state['GRADIENTS']: - grads = state['GRADIENTS'] + if func_output in state["GRADIENTS"]: + grads = state["GRADIENTS"] return copy.deepcopy(grads) # ---------------------------------------------------- @@ -207,13 +211,13 @@ def adjoint( func_name, config, state=None ): # ---------------------------------------------------- # run (includes redundancy checks) - function( func_name, config, state ) + function(func_name, config, state) # ---------------------------------------------------- # Adaptation (not implemented) # ---------------------------------------------------- - #if not state.['ADAPTED_ADJOINT']: + # if not state.['ADAPTED_ADJOINT']: # config = su2run.adaptation(config) # state['ADAPTED_FUNC'] = True @@ -224,118 +228,132 @@ def adjoint( func_name, config, state=None ): konfig = copy.deepcopy(config) # Set correct starting time for reverse sweep - if 'TIME_ITER' in state.WND_CAUCHY_DATA: # Use Convergence data, if we have already a direct run - konfig['TIME_ITER'] = state.WND_CAUCHY_DATA['TIME_ITER'] - konfig['ITER_AVERAGE_OBJ'] = state.WND_CAUCHY_DATA['ITER_AVERAGE_OBJ'] - konfig['UNST_ADJOINT_ITER'] = state.WND_CAUCHY_DATA['UNST_ADJOINT_ITER'] - + if ( + "TIME_ITER" in state.WND_CAUCHY_DATA + ): # Use Convergence data, if we have already a direct run + konfig["TIME_ITER"] = state.WND_CAUCHY_DATA["TIME_ITER"] + konfig["ITER_AVERAGE_OBJ"] = state.WND_CAUCHY_DATA["ITER_AVERAGE_OBJ"] + konfig["UNST_ADJOINT_ITER"] = state.WND_CAUCHY_DATA["UNST_ADJOINT_ITER"] # files to pull - files = state['FILES'] - pull = []; link = [] + files = state["FILES"] + pull = [] + link = [] # files: mesh - name = files['MESH'] - name = su2io.expand_part(name,konfig) + name = files["MESH"] + name = su2io.expand_part(name, konfig) link.extend(name) # files: direct solution - name = files['DIRECT'] - name = su2io.expand_zones(name,konfig) - name = su2io.expand_time(name,konfig) + name = files["DIRECT"] + name = su2io.expand_zones(name, konfig) + name = su2io.expand_time(name, konfig) link.extend(name) # files restart - if config.get('TIME_DOMAIN', 'NO') == 'YES' and config.get('RESTART_SOL', 'NO') == 'YES': - if 'RESTART_FILE_1' in files: - name = files['RESTART_FILE_1'] - name = su2io.expand_part(name, config) - link.extend(name) - if 'RESTART_FILE_1' in files: # not the case for 1st order time stepping - name = files['RESTART_FILE_2'] - name = su2io.expand_part(name, config) - link.extend(name) - - if 'FLOW_META' in files: - pull.append(files['FLOW_META']) + if ( + config.get("TIME_DOMAIN", "NO") == "YES" + and config.get("RESTART_SOL", "NO") == "YES" + ): + if "RESTART_FILE_1" in files: + name = files["RESTART_FILE_1"] + name = su2io.expand_part(name, config) + link.extend(name) + if "RESTART_FILE_1" in files: # not the case for 1st order time stepping + name = files["RESTART_FILE_2"] + name = su2io.expand_part(name, config) + link.extend(name) + + if "FLOW_META" in files: + pull.append(files["FLOW_META"]) # files: adjoint solution if ADJ_NAME in files: name = files[ADJ_NAME] - name = su2io.expand_zones(name,konfig) - name = su2io.expand_time(name,konfig) + name = su2io.expand_zones(name, konfig) + name = su2io.expand_time(name, konfig) link.extend(name) else: - config['RESTART_SOL'] = 'NO' #Can this be deleted? - if config.get('TIME_DOMAIN', 'NO') != 'YES': # rules out steady state optimization special cases. - konfig['RESTART_SOL'] = 'NO' # for shape optimization with restart files. + config["RESTART_SOL"] = "NO" # Can this be deleted? + if ( + config.get("TIME_DOMAIN", "NO") != "YES" + ): # rules out steady state optimization special cases. + konfig["RESTART_SOL"] = "NO" # for shape optimization with restart files. # Restart solution gets handled just before solver starts for unsteady optimization # files: target equivarea adjoint weights - if 'EQUIV_AREA' in special_cases: - pull.append(files['TARGET_EA']) + if "EQUIV_AREA" in special_cases: + pull.append(files["TARGET_EA"]) # files: target pressure coefficient - if 'INV_DESIGN_CP' in special_cases: - pull.append(files['TARGET_CP']) + if "INV_DESIGN_CP" in special_cases: + pull.append(files["TARGET_CP"]) # files: target heat flux coefficient - if 'INV_DESIGN_HEATFLUX' in special_cases: - pull.append(files['TARGET_HEATFLUX']) - - if not 'OUTPUT_FILES' in config: - config['OUTPUT_FILES'] = ['RESTART'] + if "INV_DESIGN_HEATFLUX" in special_cases: + pull.append(files["TARGET_HEATFLUX"]) - if not 'SURFACE_CSV' in config['OUTPUT_FILES']: - config['OUTPUT_FILES'].append('SURFACE_CSV') + if not "OUTPUT_FILES" in config: + config["OUTPUT_FILES"] = ["RESTART"] + if not "SURFACE_CSV" in config["OUTPUT_FILES"]: + config["OUTPUT_FILES"].append("SURFACE_CSV") # output redirection - with redirect_folder( ADJ_NAME, pull, link ) as push: + with redirect_folder(ADJ_NAME, pull, link) as push: with redirect_output(log_adjoint): # Format objective list in config if multi_objective: - config['OBJECTIVE_FUNCTION'] = ", ".join(func_name) #Can this be deleted? - konfig['OBJECTIVE_FUNCTION'] = ", ".join(func_name) + config["OBJECTIVE_FUNCTION"] = ", ".join( + func_name + ) # Can this be deleted? + konfig["OBJECTIVE_FUNCTION"] = ", ".join(func_name) else: - config['OBJECTIVE_FUNCTION'] = func_name #Can this be deleted? - konfig['OBJECTIVE_FUNCTION'] = func_name + config["OBJECTIVE_FUNCTION"] = func_name # Can this be deleted? + konfig["OBJECTIVE_FUNCTION"] = func_name # # RUN ADJOINT SOLUTION # # # We do not want a restart in adjoint run, we want that the adjoint run computes only up to the restart iteration of the primal run. restart_sol_activated = False - if konfig.get('TIME_DOMAIN', 'NO') == 'YES' and konfig.get('RESTART_SOL', 'NO') == 'YES': + if ( + konfig.get("TIME_DOMAIN", "NO") == "YES" + and konfig.get("RESTART_SOL", "NO") == "YES" + ): restart_sol_activated = True - original_time_iter = konfig['TIME_ITER'] - konfig['TIME_ITER'] = konfig['TIME_ITER'] - int(konfig['RESTART_ITER']) - konfig.RESTART_SOL = 'NO' + original_time_iter = konfig["TIME_ITER"] + konfig["TIME_ITER"] = konfig["TIME_ITER"] - int(konfig["RESTART_ITER"]) + konfig.RESTART_SOL = "NO" info = su2run.adjoint(konfig) # Workaround, since expandTime relies on UNST_ADJOINT_ITER to determine number of solution files. if restart_sol_activated: - konfig['UNST_ADJOINT_ITER'] = original_time_iter - int(konfig['RESTART_ITER']) - su2io.restart2solution(konfig,info) + konfig["UNST_ADJOINT_ITER"] = original_time_iter - int( + konfig["RESTART_ITER"] + ) + su2io.restart2solution(konfig, info) state.update(info) # Gradient Projection - info = su2run.projection(konfig,state) + info = su2run.projection(konfig, state) state.update(info) # solution files to push name = state.FILES[ADJ_NAME] - name = su2io.expand_zones(name,konfig) - name = su2io.expand_time(name,konfig) + name = su2io.expand_zones(name, konfig) + name = su2io.expand_time(name, konfig) push.extend(name) #: with output redirection # return output grads = su2util.ordered_bunch() - grads[func_output] = state['GRADIENTS'][func_output] + grads[func_output] = state["GRADIENTS"][func_output] return grads + #: def adjoint() @@ -343,10 +361,10 @@ def adjoint( func_name, config, state=None ): # Stability Functions # ---------------------------------------------------------------------- -def stability( func_name, config, state=None, step=1e-2 ): +def stability(func_name, config, state=None, step=1e-2): - folder = 'STABILITY' # os.path.join('STABILITY',func_name) #STABILITY/D_MOMENT_Y_D_ALPHA/ + folder = "STABILITY" # os.path.join('STABILITY',func_name) #STABILITY/D_MOMENT_Y_D_ALPHA/ # ---------------------------------------------------- # Initialize @@ -354,21 +372,21 @@ def stability( func_name, config, state=None, step=1e-2 ): # initialize state = su2io.State(state) - if not 'MESH' in state.FILES: - state.FILES.MESH = config['MESH_FILENAME'] + if not "MESH" in state.FILES: + state.FILES.MESH = config["MESH_FILENAME"] special_cases = su2io.get_specialCases(config) # find base func name - matches = [ k for k in su2io.optnames_aero if k in func_name ] + matches = [k for k in su2io.optnames_aero if k in func_name] if not len(matches) == 1: - raise Exception('could not find stability function name') + raise Exception("could not find stability function name") base_name = matches[0] - ADJ_NAME = 'ADJOINT_'+base_name + ADJ_NAME = "ADJOINT_" + base_name # console output - if config.get('CONSOLE','VERBOSE') in ['QUIET','CONCISE']: - log_direct = 'log_Direct.out' + if config.get("CONSOLE", "VERBOSE") in ["QUIET", "CONCISE"]: + log_direct = "log_Direct.out" else: log_direct = None @@ -377,15 +395,14 @@ def stability( func_name, config, state=None, step=1e-2 ): # ---------------------------------------------------- # does decomposition and deformation - info = update_mesh(config,state) + info = update_mesh(config, state) # ---------------------------------------------------- # CENTRAL POINT # ---------------------------------------------------- # will run in ADJOINT/ - grads_0 = gradient(base_name,'CONTINUOUS_ADJOINT',config,state) - + grads_0 = gradient(base_name, "CONTINUOUS_ADJOINT", config, state) # ---------------------------------------------------- # Run Forward Point @@ -393,11 +410,12 @@ def stability( func_name, config, state=None, step=1e-2 ): # files to pull files = state.FILES - pull = []; link = [] + pull = [] + link = [] # files: mesh - name = files['MESH'] - name = su2io.expand_part(name,config) + name = files["MESH"] + name = su2io.expand_part(name, config) link.extend(name) # files: direct solution @@ -406,39 +424,36 @@ def stability( func_name, config, state=None, step=1e-2 ): # files: adjoint solution if ADJ_NAME in files: name = files[ADJ_NAME] - name = su2io.expand_time(name,config) + name = su2io.expand_time(name, config) link.extend(name) else: - config['RESTART_SOL'] = 'NO' + config["RESTART_SOL"] = "NO" # files: target equivarea adjoint weights ## DO NOT PULL EQUIVAREA WEIGHTS, use the one in STABILITY/ - # pull needed files, start folder - with redirect_folder( folder, pull, link ) as push: + with redirect_folder(folder, pull, link) as push: with redirect_output(log_direct): konfig = copy.deepcopy(config) - ztate = copy.deepcopy(state) + ztate = copy.deepcopy(state) # TODO: GENERALIZE konfig.AOA = konfig.AOA + step # let's start somethin somthin del ztate.GRADIENTS[base_name] - #ztate.find_files(konfig) + # ztate.find_files(konfig) # the gradient - grads_1 = gradient(base_name,'CONTINUOUS_ADJOINT',konfig,ztate) - + grads_1 = gradient(base_name, "CONTINUOUS_ADJOINT", konfig, ztate) # ---------------------------------------------------- # DIFFERENCING # ---------------------------------------------------- - grads = [ ( g_1 - g_0 ) / step - for g_1,g_0 in zip(grads_1,grads_0) ] + grads = [(g_1 - g_0) / step for g_1, g_0 in zip(grads_1, grads_0)] state.GRADIENTS[func_name] = grads grads_out = su2util.ordered_bunch() @@ -451,20 +466,44 @@ def stability( func_name, config, state=None, step=1e-2 ): # Multipoint Functions # ---------------------------------------------------------------------- -def multipoint( func_name, config, state=None, step=1e-2 ): - mach_list = config['MULTIPOINT_MACH_NUMBER'].replace("(", "").replace(")", "").split(',') - reynolds_list = config['MULTIPOINT_REYNOLDS_NUMBER'].replace("(", "").replace(")", "").split(',') - freestream_temp_list = config['MULTIPOINT_FREESTREAM_TEMPERATURE'].replace("(", "").replace(")", "").split(',') - freestream_press_list = config['MULTIPOINT_FREESTREAM_PRESSURE'].replace("(", "").replace(")", "").split(',') - aoa_list = config['MULTIPOINT_AOA'].replace("(", "").replace(")", "").split(',') - sideslip_list = config['MULTIPOINT_SIDESLIP_ANGLE'].replace("(", "").replace(")", "").split(',') - target_cl_list = config['MULTIPOINT_TARGET_CL'].replace("(", "").replace(")", "").split(',') - weight_list = config['MULTIPOINT_WEIGHT'].replace("(", "").replace(")", "").split(',') +def multipoint(func_name, config, state=None, step=1e-2): + + mach_list = ( + config["MULTIPOINT_MACH_NUMBER"].replace("(", "").replace(")", "").split(",") + ) + reynolds_list = ( + config["MULTIPOINT_REYNOLDS_NUMBER"] + .replace("(", "") + .replace(")", "") + .split(",") + ) + freestream_temp_list = ( + config["MULTIPOINT_FREESTREAM_TEMPERATURE"] + .replace("(", "") + .replace(")", "") + .split(",") + ) + freestream_press_list = ( + config["MULTIPOINT_FREESTREAM_PRESSURE"] + .replace("(", "") + .replace(")", "") + .split(",") + ) + aoa_list = config["MULTIPOINT_AOA"].replace("(", "").replace(")", "").split(",") + sideslip_list = ( + config["MULTIPOINT_SIDESLIP_ANGLE"].replace("(", "").replace(")", "").split(",") + ) + target_cl_list = ( + config["MULTIPOINT_TARGET_CL"].replace("(", "").replace(")", "").split(",") + ) + weight_list = ( + config["MULTIPOINT_WEIGHT"].replace("(", "").replace(")", "").split(",") + ) solution_flow_list = su2io.expand_multipoint(config.SOLUTION_FILENAME, config) solution_adj_list = su2io.expand_multipoint(config.SOLUTION_ADJ_FILENAME, config) - flow_meta_list = su2io.expand_multipoint('flow.meta', config) - restart_sol = config['RESTART_SOL'] + flow_meta_list = su2io.expand_multipoint("flow.meta", config) + restart_sol = config["RESTART_SOL"] grads = [] folder = [] for i in range(len(weight_list)): @@ -472,11 +511,11 @@ def multipoint( func_name, config, state=None, step=1e-2 ): folder.append(0) for i in range(len(weight_list)): - folder[i] = 'MULTIPOINT_' + str(i) + folder[i] = "MULTIPOINT_" + str(i) opt_names = [] for key in su2io.historyOutFields: - if su2io.historyOutFields[key]['TYPE'] == 'COEFFICIENT': + if su2io.historyOutFields[key]["TYPE"] == "COEFFICIENT": opt_names.append(key) # ---------------------------------------------------- @@ -485,31 +524,31 @@ def multipoint( func_name, config, state=None, step=1e-2 ): # initialize state = su2io.State(state) - if not 'MESH' in state.FILES: - state.FILES.MESH = config['MESH_FILENAME'] + if not "MESH" in state.FILES: + state.FILES.MESH = config["MESH_FILENAME"] special_cases = su2io.get_specialCases(config) # find base func name - matches = [ k for k in opt_names if k in func_name ] + matches = [k for k in opt_names if k in func_name] if not len(matches) == 1: - raise Exception('could not find multipoint function name') + raise Exception("could not find multipoint function name") base_name = matches[0] - ADJ_NAME = 'ADJOINT_' + base_name - MULTIPOINT_ADJ_NAME = 'MULTIPOINT_' + ADJ_NAME + ADJ_NAME = "ADJOINT_" + base_name + MULTIPOINT_ADJ_NAME = "MULTIPOINT_" + ADJ_NAME # console output - if config.get('CONSOLE','VERBOSE') in ['QUIET','CONCISE']: - log_direct = 'log_Direct.out' + if config.get("CONSOLE", "VERBOSE") in ["QUIET", "CONCISE"]: + log_direct = "log_Direct.out" else: log_direct = None -# # ---------------------------------------------------- -# # Update Mesh -# # ---------------------------------------------------- -# -# # does decomposition and deformation -# info = update_mesh(config,state) + # # ---------------------------------------------------- + # # Update Mesh + # # ---------------------------------------------------- + # + # # does decomposition and deformation + # info = update_mesh(config,state) # ---------------------------------------------------- # FIRST POINT @@ -531,18 +570,18 @@ def multipoint( func_name, config, state=None, step=1e-2 ): # If flow.meta file for the first point is available, rename it before using it if os.path.exists(flow_meta_list[0]): - os.rename(flow_meta_list[0], 'flow.meta') - state.FILES['FLOW_META'] = 'flow.meta' + os.rename(flow_meta_list[0], "flow.meta") + state.FILES["FLOW_META"] = "flow.meta" - grads[0] = gradient(base_name,'DISCRETE_ADJOINT',config,state) + grads[0] = gradient(base_name, "DISCRETE_ADJOINT", config, state) src = os.getcwd() - src = os.path.abspath(src).rstrip('/') + '/' + ADJ_NAME + '/' + src = os.path.abspath(src).rstrip("/") + "/" + ADJ_NAME + "/" # change name of flow.meta back to multipoint name - if os.path.exists('flow.meta'): - os.rename('flow.meta',flow_meta_list[0]) - state.FILES['FLOW_META'] = flow_meta_list[0] + if os.path.exists("flow.meta"): + os.rename("flow.meta", flow_meta_list[0]) + state.FILES["FLOW_META"] = flow_meta_list[0] # ---------------------------------------------------- # Run Multipoint @@ -550,11 +589,12 @@ def multipoint( func_name, config, state=None, step=1e-2 ): # files to pull files = state.FILES - pull = []; link = [] + pull = [] + link = [] # files: mesh - name = files['MESH'] - name = su2io.expand_part(name,config) + name = files["MESH"] + name = su2io.expand_part(name, config) link.extend(name) # files: direct solution @@ -563,127 +603,137 @@ def multipoint( func_name, config, state=None, step=1e-2 ): # files: adjoint solution if ADJ_NAME in files: name = files[ADJ_NAME] - name = su2io.expand_time(name,config) + name = su2io.expand_time(name, config) link.extend(name) solution_adj_list[0] = files[ADJ_NAME] else: - config['RESTART_SOL'] = 'NO' + config["RESTART_SOL"] = "NO" # files: target equivarea adjoint weights ## DO NOT PULL EQUIVAREA WEIGHTS, use the one in MULTIPOINT/ # pull needed files, start folder - with redirect_folder( folder[0], pull, link ) as push: + with redirect_folder(folder[0], pull, link) as push: with redirect_output(log_direct): konfig = copy.deepcopy(config) - ztate = copy.deepcopy(state) + ztate = copy.deepcopy(state) dst = os.getcwd() - dst = os.path.abspath(dst).rstrip('/')+'/' + dst = os.path.abspath(dst).rstrip("/") + "/" # make unix link string = "ln -s " + src + " " + dst string_list = string.split() subprocess.Popen(string_list) - for i in range(len(weight_list)-1): + for i in range(len(weight_list) - 1): konfig = copy.deepcopy(config) - ztate = copy.deepcopy(state) + ztate = copy.deepcopy(state) # Reset RESTART_SOL to original value - konfig['RESTART_SOL'] = restart_sol + konfig["RESTART_SOL"] = restart_sol # Set correct config option names - konfig.SOLUTION_FILENAME = solution_flow_list[i+1] - konfig.SOLUTION_ADJ_FILENAME = solution_adj_list[i+1] + konfig.SOLUTION_FILENAME = solution_flow_list[i + 1] + konfig.SOLUTION_ADJ_FILENAME = solution_adj_list[i + 1] # Delete file run in previous case if ADJ_NAME in ztate.FILES: del ztate.FILES[ADJ_NAME] # Update ADJOINT filename with MULTIPOINT_ADJOINT filename - if MULTIPOINT_ADJ_NAME in state.FILES and state.FILES[MULTIPOINT_ADJ_NAME][i+1]: - ztate.FILES[ADJ_NAME] = state.FILES[MULTIPOINT_ADJ_NAME][i+1] - - if 'MULTIPOINT_MESH_FILENAME' in ztate.FILES: - if 'deform' in ztate.FILES.MESH: - ztate.FILES.MESH = su2io.add_suffix(ztate.FILES.MULTIPOINT_MESH_FILENAME[i+1],'deform') - konfig.MESH_FILENAME= su2io.add_suffix(ztate.FILES.MULTIPOINT_MESH_FILENAME[i+1],'deform') + if ( + MULTIPOINT_ADJ_NAME in state.FILES + and state.FILES[MULTIPOINT_ADJ_NAME][i + 1] + ): + ztate.FILES[ADJ_NAME] = state.FILES[MULTIPOINT_ADJ_NAME][i + 1] + + if "MULTIPOINT_MESH_FILENAME" in ztate.FILES: + if "deform" in ztate.FILES.MESH: + ztate.FILES.MESH = su2io.add_suffix( + ztate.FILES.MULTIPOINT_MESH_FILENAME[i + 1], "deform" + ) + konfig.MESH_FILENAME = su2io.add_suffix( + ztate.FILES.MULTIPOINT_MESH_FILENAME[i + 1], "deform" + ) else: - ztate.FILES.MESH = ztate.FILES.MULTIPOINT_MESH_FILENAME[i+1] - konfig.MESH_FILENAME= ztate.FILES.MULTIPOINT_MESH_FILENAME[i+1] + ztate.FILES.MESH = ztate.FILES.MULTIPOINT_MESH_FILENAME[i + 1] + konfig.MESH_FILENAME = ztate.FILES.MULTIPOINT_MESH_FILENAME[i + 1] # use flow.meta file from relevant point - if 'MULTIPOINT_FLOW_META' in state.FILES and state.FILES.MULTIPOINT_FLOW_META[i+1]: - ztate.FILES['FLOW_META'] = state.FILES.MULTIPOINT_FLOW_META[i+1] + if ( + "MULTIPOINT_FLOW_META" in state.FILES + and state.FILES.MULTIPOINT_FLOW_META[i + 1] + ): + ztate.FILES["FLOW_META"] = state.FILES.MULTIPOINT_FLOW_META[i + 1] files = ztate.FILES link = [] - files['DIRECT'] = state.FILES.MULTIPOINT_DIRECT[i+1] + files["DIRECT"] = state.FILES.MULTIPOINT_DIRECT[i + 1] # files: mesh - name = files['MESH'] - name = su2io.expand_part(name,konfig) + name = files["MESH"] + name = su2io.expand_part(name, konfig) link.extend(name) # files: direct solution - if 'DIRECT' in files: - name = files['DIRECT'] - name = su2io.expand_time(name,konfig) - link.extend( name ) + if "DIRECT" in files: + name = files["DIRECT"] + name = su2io.expand_time(name, konfig) + link.extend(name) # files: adjoint solution if ADJ_NAME in files: name = files[ADJ_NAME] - name = su2io.expand_time(name,konfig) + name = su2io.expand_time(name, konfig) link.extend(name) else: - konfig['RESTART_SOL'] = 'NO' + konfig["RESTART_SOL"] = "NO" # files: meta data of solution - if 'FLOW_META' in files: - pull.append(files['FLOW_META']) + if "FLOW_META" in files: + pull.append(files["FLOW_META"]) # pull needed files, start folder - with redirect_folder( folder[i+1], pull, link ) as push: + with redirect_folder(folder[i + 1], pull, link) as push: with redirect_output(log_direct): # Set the multipoint options - konfig.AOA = aoa_list[i+1] - konfig.SIDESLIP_ANGLE = sideslip_list[i+1] - konfig.MACH_NUMBER = mach_list[i+1] - konfig.REYNOLDS_NUMBER = reynolds_list[i+1] - konfig.FREESTREAM_TEMPERATURE = freestream_temp_list[i+1] - konfig.FREESTREAM_PRESSURE = freestream_press_list[i+1] - konfig.TARGET_CL = target_cl_list[i+1] + konfig.AOA = aoa_list[i + 1] + konfig.SIDESLIP_ANGLE = sideslip_list[i + 1] + konfig.MACH_NUMBER = mach_list[i + 1] + konfig.REYNOLDS_NUMBER = reynolds_list[i + 1] + konfig.FREESTREAM_TEMPERATURE = freestream_temp_list[i + 1] + konfig.FREESTREAM_PRESSURE = freestream_press_list[i + 1] + konfig.TARGET_CL = target_cl_list[i + 1] # rename meta data to flow.meta - if 'FLOW_META' in ztate.FILES: - os.rename(ztate.FILES.MULTIPOINT_FLOW_META[i+1], 'flow.meta') - ztate.FILES['FLOW_META'] = 'flow.meta' + if "FLOW_META" in ztate.FILES: + os.rename(ztate.FILES.MULTIPOINT_FLOW_META[i + 1], "flow.meta") + ztate.FILES["FLOW_META"] = "flow.meta" # let's start somethin somthin ztate.GRADIENTS.clear() # the gradient - grads[i+1] = gradient(base_name,'DISCRETE_ADJOINT',konfig,ztate) + grads[i + 1] = gradient(base_name, "DISCRETE_ADJOINT", konfig, ztate) # rename meta data to multipoint name - if os.path.exists('flow.meta'): - os.rename('flow.meta', flow_meta_list[i+1]) + if os.path.exists("flow.meta"): + os.rename("flow.meta", flow_meta_list[i + 1]) # adjoint files to push dst = os.getcwd() - dst = os.path.abspath(dst).rstrip('/')+'/'+ztate.FILES[ADJ_NAME] + dst = os.path.abspath(dst).rstrip("/") + "/" + ztate.FILES[ADJ_NAME] name = ztate.FILES[ADJ_NAME] - solution_adj_list[i+1] = name - name = su2io.expand_zones(name,konfig) - name = su2io.expand_time(name,konfig) + solution_adj_list[i + 1] = name + name = su2io.expand_zones(name, konfig) + name = su2io.expand_time(name, konfig) push.extend(name) # Link adjoint solution to MULTIPOINT_# folder src = os.getcwd() - src = os.path.abspath(src).rstrip('/')+'/'+ztate.FILES[ADJ_NAME] + src = os.path.abspath(src).rstrip("/") + "/" + ztate.FILES[ADJ_NAME] # make unix link string = "ln -s " + src + " " + dst @@ -704,7 +754,9 @@ def multipoint( func_name, config, state=None, step=1e-2 ): for variable in range(len(grads[0])): grad[variable] = 0.0 for point in range(len(weight_list)): - grad[variable] = grad[variable] + float(weight_list[point])*grads[point][variable] + grad[variable] = ( + grad[variable] + float(weight_list[point]) * grads[point][variable] + ) state.GRADIENTS[func_name] = grad grads_out = su2util.ordered_bunch() @@ -717,32 +769,33 @@ def multipoint( func_name, config, state=None, step=1e-2 ): # Finite Difference Gradients # ---------------------------------------------------------------------- -def findiff( config, state=None ): - """ vals = SU2.eval.findiff(config,state=None) - Evaluates the aerodynamics gradients using - finite differencing with: - SU2.eval.func() - SU2.run.deform() - SU2.run.direct() +def findiff(config, state=None): + """vals = SU2.eval.findiff(config,state=None) + + Evaluates the aerodynamics gradients using + finite differencing with: + SU2.eval.func() + SU2.run.deform() + SU2.run.direct() - Assumptions: - Config is already setup for deformation. - Mesh may or may not be deformed. - Updates config and state by reference. - Gradient Redundancy if state.GRADIENTS has the key func_name. - Direct Redundancy if state.FUNCTIONS has key func_name. + Assumptions: + Config is already setup for deformation. + Mesh may or may not be deformed. + Updates config and state by reference. + Gradient Redundancy if state.GRADIENTS has the key func_name. + Direct Redundancy if state.FUNCTIONS has key func_name. - Executes in: - ./FINDIFF + Executes in: + ./FINDIFF - Inputs: - config - an SU2 config - state - optional, an SU2 state + Inputs: + config - an SU2 config + state - optional, an SU2 state - Outputs: - A Bunch() with keys of objective function names - and values of list of floats of gradient values + Outputs: + A Bunch() with keys of objective function names + and values of list of floats of gradient values """ # ---------------------------------------------------- @@ -752,28 +805,28 @@ def findiff( config, state=None ): # initialize state = su2io.State(state) special_cases = su2io.get_specialCases(config) - Definition_DV = config['DEFINITION_DV'] + Definition_DV = config["DEFINITION_DV"] # console output - if config.get('CONSOLE','VERBOSE') in ['QUIET','CONCISE']: - log_findiff = 'log_FinDiff.out' + if config.get("CONSOLE", "VERBOSE") in ["QUIET", "CONCISE"]: + log_findiff = "log_FinDiff.out" else: log_findiff = None # evaluate step length or set default value - if 'FIN_DIFF_STEP' in config: + if "FIN_DIFF_STEP" in config: step = float(config.FIN_DIFF_STEP) else: step = 0.001 opt_names = [] - for i in range(config['NZONES']): + for i in range(config["NZONES"]): for key in sorted(su2io.historyOutFields): - if su2io.historyOutFields[key]['TYPE'] == 'COEFFICIENT': - if (config['NZONES'] == 1): + if su2io.historyOutFields[key]["TYPE"] == "COEFFICIENT": + if config["NZONES"] == 1: opt_names.append(key) else: - opt_names.append(key + '[' + str(i) + ']') + opt_names.append(key + "[" + str(i) + "]") # ---------------------------------------------------- # Redundancy Check @@ -782,7 +835,7 @@ def findiff( config, state=None ): # master redundancy check findiff_todo = all([key in state.GRADIENTS for key in opt_names]) if findiff_todo: - grads = state['GRADIENTS'] + grads = state["GRADIENTS"] return copy.deepcopy(grads) # ---------------------------------------------------- @@ -790,17 +843,17 @@ def findiff( config, state=None ): # ---------------------------------------------------- # run - func_base = function( 'ALL', config, state ) + func_base = function("ALL", config, state) # ---------------------------------------------------- # Plot Setup # ---------------------------------------------------- - grad_filename = config['GRAD_OBJFUNC_FILENAME'] - grad_filename = os.path.splitext( grad_filename )[0] - output_format = config['TABULAR_FORMAT'] + grad_filename = config["GRAD_OBJFUNC_FILENAME"] + grad_filename = os.path.splitext(grad_filename)[0] + output_format = config["TABULAR_FORMAT"] plot_extension = su2io.get_extension(output_format) - grad_filename = grad_filename + '_findiff' + plot_extension + grad_filename = grad_filename + "_findiff" + plot_extension # ---------------------------------------------------- # Finite Difference Steps @@ -810,108 +863,109 @@ def findiff( config, state=None ): konfig = copy.deepcopy(config) # check deformation setup - n_dv = sum(Definition_DV['SIZE']) - deform_set = konfig['DV_KIND'] == Definition_DV['KIND'] + n_dv = sum(Definition_DV["SIZE"]) + deform_set = konfig["DV_KIND"] == Definition_DV["KIND"] if not deform_set: dvs_base = [0.0] * n_dv - konfig.unpack_dvs(dvs_base,dvs_base) + konfig.unpack_dvs(dvs_base, dvs_base) else: - dvs_base = konfig['DV_VALUE_NEW'] + dvs_base = konfig["DV_VALUE_NEW"] # initialize gradients - func_keys = ['VARIABLE'] + opt_names + ['FINDIFF_STEP'] + func_keys = ["VARIABLE"] + opt_names + ["FINDIFF_STEP"] grads = su2util.ordered_bunch.fromkeys(func_keys) - for key in grads.keys(): grads[key] = [] + for key in grads.keys(): + grads[key] = [] # step vector - if isinstance(step,list): - assert n_dv == len(step) , 'unexpected step vector length' + if isinstance(step, list): + assert n_dv == len(step), "unexpected step vector length" else: step = [step] * n_dv # files to pull - files = state['FILES'] - pull = []; link = [] - pull.extend(config.get('CONFIG_LIST',[])) + files = state["FILES"] + pull = [] + link = [] + pull.extend(config.get("CONFIG_LIST", [])) # files: mesh - name = files['MESH'] - name = su2io.expand_part(name,konfig) + name = files["MESH"] + name = su2io.expand_part(name, konfig) link.extend(name) # files: direct solution - if 'DIRECT' in files: - name = files['DIRECT'] - name = su2io.expand_time(name,config) + if "DIRECT" in files: + name = files["DIRECT"] + name = su2io.expand_time(name, config) link.extend(name) # files: restart solution for dual-time stepping first and second order - if 'RESTART_FILE_1' in files: - name = files['RESTART_FILE_1'] + if "RESTART_FILE_1" in files: + name = files["RESTART_FILE_1"] pull.append(name) - if 'RESTART_FILE_2' in files: - name = files['RESTART_FILE_2'] + if "RESTART_FILE_2" in files: + name = files["RESTART_FILE_2"] pull.append(name) # files: target equivarea distribution - if 'EQUIV_AREA' in special_cases and 'TARGET_EA' in files: - pull.append(files['TARGET_EA']) + if "EQUIV_AREA" in special_cases and "TARGET_EA" in files: + pull.append(files["TARGET_EA"]) # files: target pressure distribution - if 'INV_DESIGN_CP' in special_cases and 'TARGET_CP' in files: - pull.append(files['TARGET_CP']) + if "INV_DESIGN_CP" in special_cases and "TARGET_CP" in files: + pull.append(files["TARGET_CP"]) # files: target heat flux distribution - if 'INV_DESIGN_HEATFLUX' in special_cases and 'TARGET_HEATFLUX' in files: - pull.append(files['TARGET_HEATFLUX']) - + if "INV_DESIGN_HEATFLUX" in special_cases and "TARGET_HEATFLUX" in files: + pull.append(files["TARGET_HEATFLUX"]) # output redirection - with redirect_folder('FINDIFF',pull,link) as push: + with redirect_folder("FINDIFF", pull, link) as push: with redirect_output(log_findiff): # iterate each dv for i_dv in range(n_dv): this_step = step[i_dv] - temp_config_name = 'config_FINDIFF_%i.cfg' % i_dv + temp_config_name = "config_FINDIFF_%i.cfg" % i_dv - this_dvs = copy.deepcopy(dvs_base) + this_dvs = copy.deepcopy(dvs_base) this_konfig = copy.deepcopy(konfig) this_dvs[i_dv] = this_dvs[i_dv] + this_step this_state = su2io.State() - this_state.FILES = copy.deepcopy( state.FILES ) - this_konfig.unpack_dvs(this_dvs,dvs_base) + this_state.FILES = copy.deepcopy(state.FILES) + this_konfig.unpack_dvs(this_dvs, dvs_base) this_konfig.dump(temp_config_name) # Direct Solution, findiff step - func_step = function( 'ALL', this_konfig, this_state ) + func_step = function("ALL", this_konfig, this_state) # remove deform step files meshfiles = this_state.FILES.MESH - meshfiles = su2io.expand_part(meshfiles,this_konfig) - for name in meshfiles: os.remove(name) + meshfiles = su2io.expand_part(meshfiles, this_konfig) + for name in meshfiles: + os.remove(name) for key in grads.keys(): - if key == 'VARIABLE' or key == 'FINDIFF_STEP': + if key == "VARIABLE" or key == "FINDIFF_STEP": pass elif not key in func_step: del grads[key] # calc finite difference and store for key in grads.keys(): - if key == 'VARIABLE': + if key == "VARIABLE": grads[key].append(i_dv) - elif key == 'FINDIFF_STEP': + elif key == "FINDIFF_STEP": grads[key].append(this_step) else: - this_grad = ( func_step[key] - func_base[key] ) / this_step + this_grad = (func_step[key] - func_base[key]) / this_step grads[key].append(this_grad) - #: for each grad name - su2util.write_plot(grad_filename,output_format,grads) + su2util.write_plot(grad_filename, output_format, grads) os.remove(temp_config_name) #: for each dv @@ -919,14 +973,15 @@ def findiff( config, state=None ): #: with output redirection # remove plot items - del grads['VARIABLE'] - del grads['FINDIFF_STEP'] + del grads["VARIABLE"] + del grads["FINDIFF_STEP"] state.GRADIENTS.update(grads) # return results grads = copy.deepcopy(grads) return grads + #: def findiff() @@ -934,29 +989,30 @@ def findiff( config, state=None ): # Geometric Gradients # ---------------------------------------------------------------------- -def geometry( func_name, config, state=None ): - """ val = SU2.eval.geometry(config,state=None) - Evaluates geometry with the following: - SU2.run.deform() - SU2.run.geometry() +def geometry(func_name, config, state=None): + """val = SU2.eval.geometry(config,state=None) - Assumptions: - Config is already setup for deformation. - Mesh may or may not be deformed. - Updates config and state by reference. - Redundancy if state.FUNCTIONS does not have func_name. + Evaluates geometry with the following: + SU2.run.deform() + SU2.run.geometry() - Executes in: - ./GEOMETRY + Assumptions: + Config is already setup for deformation. + Mesh may or may not be deformed. + Updates config and state by reference. + Redundancy if state.FUNCTIONS does not have func_name. - Inputs: - config - an SU2 config - state - optional, an SU2 state + Executes in: + ./GEOMETRY - Outputs: - Bunch() of functions with keys of objective function names - and values of objective function floats. + Inputs: + config - an SU2 config + state - optional, an SU2 state + + Outputs: + Bunch() of functions with keys of objective function names + and values of objective function floats. """ # ---------------------------------------------------- @@ -965,13 +1021,13 @@ def geometry( func_name, config, state=None ): # initialize state = su2io.State(state) - if not 'MESH' in state.FILES: - state.FILES.MESH = config['MESH_FILENAME'] + if not "MESH" in state.FILES: + state.FILES.MESH = config["MESH_FILENAME"] special_cases = su2io.get_specialCases(config) # console output - if config.get('CONSOLE','VERBOSE') in ['QUIET','CONCISE']: - log_geom = 'log_Geometry.out' + if config.get("CONSOLE", "VERBOSE") in ["QUIET", "CONCISE"]: + log_geom = "log_Geometry.out" else: log_geom = None @@ -982,35 +1038,35 @@ def geometry( func_name, config, state=None ): # does decomposition and deformation # info = update_mesh(config,state) - # ---------------------------------------------------- # Geometry Solution # ---------------------------------------------------- # redundancy check geometry_done = func_name in state.GRADIENTS - #geometry_done = all([key in state.FUNCTIONS for key in su2io.optnames_geo]) + # geometry_done = all([key in state.FUNCTIONS for key in su2io.optnames_geo]) if not geometry_done: # files to pull files = state.FILES - pull = []; link = [] + pull = [] + link = [] # files: mesh - name = files['MESH'] - name = su2io.expand_part(name,config) + name = files["MESH"] + name = su2io.expand_part(name, config) link.extend(name) # update function name ## TODO # output redirection - with redirect_folder( 'GEOMETRY', pull, link ) as push: + with redirect_folder("GEOMETRY", pull, link) as push: with redirect_output(log_geom): # setup config config.GEO_PARAM = func_name - config.GEO_MODE = 'GRADIENT' + config.GEO_MODE = "GRADIENT" # # RUN GEOMETRY SOLUTION # # info = su2run.geometry(config) @@ -1022,14 +1078,14 @@ def geometry( func_name, config, state=None ): #: if not redundant - # return output grads = su2util.ordered_bunch() for key in su2io.optnames_geo: - if key in state['GRADIENTS']: - grads[key] = state['GRADIENTS'][key] + if key in state["GRADIENTS"]: + grads[key] = state["GRADIENTS"][key] return grads + #: def geometry() @@ -1037,34 +1093,35 @@ def geometry( func_name, config, state=None ): # Direct Differentiation Gradients # ---------------------------------------------------------------------- -def directdiff( config, state=None ): - """ vals = SU2.eval.directdiff(config,state=None) - - Evaluates the aerodynamics gradients using - direct differentiation with: - SU2.eval.func() - SU2.run.deform() - SU2.run.direct() - - Assumptions: - Config is already setup for deformation. - Mesh may or may not be deformed. - Updates config and state by reference. - Gradient Redundancy if state.GRADIENTS has the key func_name. - Direct Redundancy if state.FUNCTIONS has key func_name. - - Executes in: - ./DIRECTDIFF - - Inputs: - config - an SU2 config - state - optional, an SU2 state - step - finite difference step size, as a float or - list of floats of length n_DV - - Outputs: - A Bunch() with keys of objective function names - and values of list of floats of gradient values + +def directdiff(config, state=None): + """vals = SU2.eval.directdiff(config,state=None) + + Evaluates the aerodynamics gradients using + direct differentiation with: + SU2.eval.func() + SU2.run.deform() + SU2.run.direct() + + Assumptions: + Config is already setup for deformation. + Mesh may or may not be deformed. + Updates config and state by reference. + Gradient Redundancy if state.GRADIENTS has the key func_name. + Direct Redundancy if state.FUNCTIONS has key func_name. + + Executes in: + ./DIRECTDIFF + + Inputs: + config - an SU2 config + state - optional, an SU2 state + step - finite difference step size, as a float or + list of floats of length n_DV + + Outputs: + A Bunch() with keys of objective function names + and values of list of floats of gradient values """ # ---------------------------------------------------- @@ -1074,11 +1131,11 @@ def directdiff( config, state=None ): # initialize state = su2io.State(state) special_cases = su2io.get_specialCases(config) - Definition_DV = config['DEFINITION_DV'] + Definition_DV = config["DEFINITION_DV"] # console output - if config.get('CONSOLE','VERBOSE') in ['QUIET','CONCISE']: - log_directdiff = 'log_DirectDiff.out' + if config.get("CONSOLE", "VERBOSE") in ["QUIET", "CONCISE"]: + log_directdiff = "log_DirectDiff.out" else: log_directdiff = None @@ -1089,23 +1146,23 @@ def directdiff( config, state=None ): # master redundancy check opt_names = [] for key in sorted(su2io.historyOutFields): - if su2io.historyOutFields[key]['TYPE'] == 'COEFFICIENT': + if su2io.historyOutFields[key]["TYPE"] == "COEFFICIENT": opt_names.append(key) directdiff_todo = all([key in state.GRADIENTS for key in opt_names]) if directdiff_todo: - grads = state['GRADIENTS'] + grads = state["GRADIENTS"] return copy.deepcopy(grads) # ---------------------------------------------------- # Plot Setup # ---------------------------------------------------- - grad_filename = config['GRAD_OBJFUNC_FILENAME'] - grad_filename = os.path.splitext( grad_filename )[0] - output_format = config.get('TABULAR_FORMAT', 'CSV') + grad_filename = config["GRAD_OBJFUNC_FILENAME"] + grad_filename = os.path.splitext(grad_filename)[0] + output_format = config.get("TABULAR_FORMAT", "CSV") plot_extension = su2io.get_extension(output_format) - grad_filename = grad_filename + '_directdiff' + plot_extension + grad_filename = grad_filename + "_directdiff" + plot_extension # ---------------------------------------------------- # Direct Differentiation Evaluation @@ -1114,84 +1171,86 @@ def directdiff( config, state=None ): # local config konfig = copy.deepcopy(config) - n_dv = sum(Definition_DV['SIZE']) + n_dv = sum(Definition_DV["SIZE"]) # initialize gradients func_keys = opt_names - func_keys = ['VARIABLE'] + func_keys + func_keys = ["VARIABLE"] + func_keys grads = su2util.ordered_bunch.fromkeys(func_keys) - for key in grads.keys(): grads[key] = [] + for key in grads.keys(): + grads[key] = [] # files to pull - files = state['FILES'] - pull = []; link = [] + files = state["FILES"] + pull = [] + link = [] # files: mesh - name = files['MESH'] - name = su2io.expand_part(name,konfig) + name = files["MESH"] + name = su2io.expand_part(name, konfig) link.extend(name) - if 'FLOW_META' in files: - pull.append(files['FLOW_META']) + if "FLOW_META" in files: + pull.append(files["FLOW_META"]) # files: direct solution - if 'DIRECT' in files: - name = files['DIRECT'] - name = su2io.expand_time(name,config) + if "DIRECT" in files: + name = files["DIRECT"] + name = su2io.expand_time(name, config) link.extend(name) # files: target equivarea distribution - if 'EQUIV_AREA' in special_cases and 'TARGET_EA' in files: - pull.append(files['TARGET_EA']) + if "EQUIV_AREA" in special_cases and "TARGET_EA" in files: + pull.append(files["TARGET_EA"]) # files: target pressure distribution - if 'INV_DESIGN_CP' in special_cases and 'TARGET_CP' in files: - pull.append(files['TARGET_CP']) + if "INV_DESIGN_CP" in special_cases and "TARGET_CP" in files: + pull.append(files["TARGET_CP"]) # files: target heat flux distribution - if 'INV_DESIGN_HEATFLUX' in special_cases and 'TARGET_HEATFLUX' in files: - pull.append(files['TARGET_HEATFLUX']) + if "INV_DESIGN_HEATFLUX" in special_cases and "TARGET_HEATFLUX" in files: + pull.append(files["TARGET_HEATFLUX"]) # output redirection - with redirect_folder('DIRECTDIFF',pull,link) as push: + with redirect_folder("DIRECTDIFF", pull, link) as push: with redirect_output(log_directdiff): # iterate each dv for i_dv in range(n_dv): - temp_config_name = 'config_DIRECTDIFF_%i.cfg' % i_dv + temp_config_name = "config_DIRECTDIFF_%i.cfg" % i_dv this_konfig = copy.deepcopy(konfig) - this_dvs = [0.0]*n_dv + this_dvs = [0.0] * n_dv this_dvs[i_dv] = 1.0 - this_dvs_old = [0.0]*n_dv + this_dvs_old = [0.0] * n_dv this_dvs_old[i_dv] = 1.0 this_state = su2io.State() - this_state.FILES = copy.deepcopy( state.FILES ) + this_state.FILES = copy.deepcopy(state.FILES) this_konfig.unpack_dvs(this_dvs, this_dvs_old) this_konfig.dump(temp_config_name) # Direct Solution - func_step = function( 'ALL', this_konfig, this_state ) + func_step = function("ALL", this_konfig, this_state) # delete keys not returned by the solver for key in grads.keys(): - if key == 'VARIABLE': + if key == "VARIABLE": pass - elif not 'D_' + key in func_step: + elif not "D_" + key in func_step: del grads[key] # store for key in grads.keys(): - if key == 'VARIABLE': + if key == "VARIABLE": grads[key].append(i_dv) else: - this_grad = func_step['D_' + key] + this_grad = func_step["D_" + key] grads[key].append(this_grad) #: for each grad name - su2util.write_plot(grad_filename,output_format,grads) + su2util.write_plot(grad_filename, output_format, grads) os.remove(temp_config_name) #: for each dv @@ -1199,7 +1258,7 @@ def directdiff( config, state=None ): #: with output redirection # remove plot items - del grads['VARIABLE'] + del grads["VARIABLE"] state.GRADIENTS.update(grads) state.update(this_state) @@ -1207,5 +1266,5 @@ def directdiff( config, state=None ): grads = copy.deepcopy(grads) return grads -#: def directdiff() +#: def directdiff() diff --git a/SU2_PY/SU2/io/__init__.py b/SU2_PY/SU2/io/__init__.py index d79c0aa59c2..8b222a5d021 100644 --- a/SU2_PY/SU2/io/__init__.py +++ b/SU2_PY/SU2/io/__init__.py @@ -1,11 +1,11 @@ # SU2/io/__init__.py -from .tools import * +from .tools import * from .redirect import output as redirect_output from .redirect import folder as redirect_folder -from .data import load_data, save_data +from .data import load_data, save_data from .filelock import filelock -from .config import Config -from .state import State_Factory as State +from .config import Config +from .state import State_Factory as State from .historyMap import history_header_map as historyOutFields diff --git a/SU2_PY/SU2/io/config.py b/SU2_PY/SU2/io/config.py index 2376dcf0408..e80e61ff900 100755 --- a/SU2_PY/SU2/io/config.py +++ b/SU2_PY/SU2/io/config.py @@ -45,56 +45,57 @@ # Configuration Class # ---------------------------------------------------------------------- + class Config(ordered_bunch): - """ config = SU2.io.Config(filename="") - - Starts a config class, an extension of - ordered_bunch() - - use 1: initialize by reading config file - config = SU2.io.Config('filename') - use 2: initialize from dictionary or bunch - config = SU2.io.Config(param_dict) - use 3: initialize empty - config = SU2.io.Config() - - Parameters can be accessed by item or attribute - ie: config['MESH_FILENAME'] or config.MESH_FILENAME - - Methods: - read() - read from a config file - write() - write to a config file (requires existing file) - dump() - dump a raw config file - unpack_dvs() - unpack a design vector - diff() - returns the difference from another config - dist() - computes the distance from another config + """config = SU2.io.Config(filename="") + + Starts a config class, an extension of + ordered_bunch() + + use 1: initialize by reading config file + config = SU2.io.Config('filename') + use 2: initialize from dictionary or bunch + config = SU2.io.Config(param_dict) + use 3: initialize empty + config = SU2.io.Config() + + Parameters can be accessed by item or attribute + ie: config['MESH_FILENAME'] or config.MESH_FILENAME + + Methods: + read() - read from a config file + write() - write to a config file (requires existing file) + dump() - dump a raw config file + unpack_dvs() - unpack a design vector + diff() - returns the difference from another config + dist() - computes the distance from another config """ - _filename = 'config.cfg' + _filename = "config.cfg" - def __init__(self,*args,**kwarg): + def __init__(self, *args, **kwarg): # look for filename in inputs - if args and isinstance(args[0],str): + if args and isinstance(args[0], str): filename = args[0] args = args[1:] - elif 'filename' in kwarg: - filename = kwarg['filename'] - del kwarg['filename'] + elif "filename" in kwarg: + filename = kwarg["filename"] + del kwarg["filename"] else: - filename = '' + filename = "" # initialize ordered bunch - super(Config,self).__init__(*args,**kwarg) + super(Config, self).__init__(*args, **kwarg) # read config if it exists if filename: try: self.read(filename) except IOError: - print('Could not find config file: %s' % filename) + print("Could not find config file: %s" % filename) except: - print('Unexpected error: ', sys.exc_info()[0]) + print("Unexpected error: ", sys.exc_info()[0]) raise self._filename = filename @@ -104,81 +105,82 @@ def __init__(self,*args,**kwarg): diff_objective = self.get("OBJECTIVE_FUNCTION") constrFuncFields = self.get("OPT_CONSTRAINT") - #OPT_OBJECTIVES - if bool (objFuncsFields): + # OPT_OBJECTIVES + if bool(objFuncsFields): for key in objFuncsFields: tavg_keyGroup = "TAVG_" + historyOutFields[key]["GROUP"] - if not tavg_keyGroup in histFields: + if not tavg_keyGroup in histFields: histFields.append(tavg_keyGroup) dtavg_keyGroup = "D_TAVG_" + historyOutFields[key]["GROUP"] if not dtavg_keyGroup in histFields: histFields.append(dtavg_keyGroup) - #OPT_CONSTRAINTS - if bool (constrFuncFields): + # OPT_CONSTRAINTS + if bool(constrFuncFields): for key in constrFuncFields: eqIneqConstrFunc = constrFuncFields.get(key) for key_inner in eqIneqConstrFunc: tavg_keyGroup = "TAVG_" + historyOutFields[key_inner]["GROUP"] - if not tavg_keyGroup in histFields: + if not tavg_keyGroup in histFields: histFields.append(tavg_keyGroup) - #DIRECT_DIFF Field + # DIRECT_DIFF Field if diff_objective in historyOutFields: tavg_keyGroup = "TAVG_" + historyOutFields[diff_objective]["GROUP"] - if not tavg_keyGroup in histFields: + if not tavg_keyGroup in histFields: histFields.append(tavg_keyGroup) dtavg_keyGroup = "D_TAVG_" + historyOutFields[diff_objective]["GROUP"] if not dtavg_keyGroup in histFields: histFields.append(dtavg_keyGroup) - self["HISTORY_OUTPUT"]= histFields - + self["HISTORY_OUTPUT"] = histFields - def read(self,filename): - """ reads from a config file """ + def read(self, filename): + """reads from a config file""" konfig = read_config(filename) self.update(konfig) - def write(self,filename=''): - """ updates an existing config file """ - if not filename: filename = self._filename - assert os.path.exists(filename) , 'must write over an existing config file' - write_config(filename,self) + def write(self, filename=""): + """updates an existing config file""" + if not filename: + filename = self._filename + assert os.path.exists(filename), "must write over an existing config file" + write_config(filename, self) - def dump(self,filename=''): - """ dumps all items in the config bunch, without comments """ - if not filename: filename = self._filename - dump_config(filename,self) + def dump(self, filename=""): + """dumps all items in the config bunch, without comments""" + if not filename: + filename = self._filename + dump_config(filename, self) - def __getattr__(self,k): + def __getattr__(self, k): try: - return super(Config,self).__getattr__(k) + return super(Config, self).__getattr__(k) except AttributeError: - raise AttributeError('Config parameter not found') + raise AttributeError("Config parameter not found") - def __getitem__(self,k): + def __getitem__(self, k): try: - return super(Config,self).__getitem__(k) + return super(Config, self).__getitem__(k) except KeyError: - raise KeyError('Config parameter not found: %s' % k) + raise KeyError("Config parameter not found: %s" % k) - def unpack_dvs(self,dv_new,dv_old=None): - """ updates config with design variable vectors - will scale according to each DEFINITION_DV scale parameter + def unpack_dvs(self, dv_new, dv_old=None): + """updates config with design variable vectors + will scale according to each DEFINITION_DV scale parameter - Modifies: - DV_KIND - DV_MARKER - DV_PARAM - DV_VALUE_OLD - DV_VALUE_NEW + Modifies: + DV_KIND + DV_MARKER + DV_PARAM + DV_VALUE_OLD + DV_VALUE_NEW - Inputs: - dv_new - list or array of new dv values - dv_old - optional, list or array of old dv values, defaults to zeros + Inputs: + dv_new - list or array of new dv values + dv_old - optional, list or array of old dv values, defaults to zeros """ @@ -186,96 +188,95 @@ def unpack_dvs(self,dv_new,dv_old=None): dv_old = copy.deepcopy(dv_old) # handle unpacking cases - def_dv = self['DEFINITION_DV'] + def_dv = self["DEFINITION_DV"] - n_dv = sum(def_dv['SIZE']) + n_dv = sum(def_dv["SIZE"]) - if not dv_old: dv_old = [0.0]*n_dv - assert len(dv_new) == len(dv_old) , 'unexpected design vector length' + if not dv_old: + dv_old = [0.0] * n_dv + assert len(dv_new) == len(dv_old), "unexpected design vector length" # handle param - param_dv = self['DV_PARAM'] + param_dv = self["DV_PARAM"] # apply scale - dv_scales = def_dv['SCALE'] + dv_scales = def_dv["SCALE"] k = 0 for i, dv_scl in enumerate(dv_scales): - for j in range(def_dv['SIZE'][i]): - dv_new[k] = dv_new[k]*dv_scl; - dv_old[k] = dv_old[k]*dv_scl; + for j in range(def_dv["SIZE"][i]): + dv_new[k] = dv_new[k] * dv_scl + dv_old[k] = dv_old[k] * dv_scl k = k + 1 # Change the parameters of the design variables - self['DV_KIND'] = def_dv['KIND'] - param_dv['PARAM'] = def_dv['PARAM'] - param_dv['FFDTAG'] = def_dv['FFDTAG'] - param_dv['SIZE'] = def_dv['SIZE'] + self["DV_KIND"] = def_dv["KIND"] + param_dv["PARAM"] = def_dv["PARAM"] + param_dv["FFDTAG"] = def_dv["FFDTAG"] + param_dv["SIZE"] = def_dv["SIZE"] - self.update({ 'DV_VALUE_OLD' : dv_old , - 'DV_VALUE_NEW' : dv_new }) + self.update({"DV_VALUE_OLD": dv_old, "DV_VALUE_NEW": dv_new}) - def __eq__(self,konfig): - return super(Config,self).__eq__(konfig) - def __ne__(self,konfig): - return super(Config,self).__ne__(konfig) + def __eq__(self, konfig): + return super(Config, self).__eq__(konfig) + def __ne__(self, konfig): + return super(Config, self).__ne__(konfig) def local_files(self): - """ removes path prefix from all *_FILENAME params - """ + """removes path prefix from all *_FILENAME params""" for key, value in self.items(): - if key.split('_')[-1] == 'FILENAME': + if key.split("_")[-1] == "FILENAME": self[key] = os.path.basename(value) - def diff(self,konfig): - """ compares self to another config + def diff(self, konfig): + """compares self to another config - Inputs: - konfig - a second config + Inputs: + konfig - a second config - Outputs: - config_diff - a config containing only the differing - keys, each with values of a list of the different - config values. - for example: - config_diff.MATH_PROBLEM = ['DIRECT','CONTINUOUS_ADJOINT'] + Outputs: + config_diff - a config containing only the differing + keys, each with values of a list of the different + config values. + for example: + config_diff.MATH_PROBLEM = ['DIRECT','CONTINUOUS_ADJOINT'] """ keys = set([]) - keys.update( self.keys() ) - keys.update( konfig.keys() ) + keys.update(self.keys()) + keys.update(konfig.keys()) konfig_diff = Config() for key in keys: - value1 = self.get(key,None) - value2 = konfig.get(key,None) + value1 = self.get(key, None) + value2 = konfig.get(key, None) if not value1 == value2: - konfig_diff[key] = [value1,value2] + konfig_diff[key] = [value1, value2] return konfig_diff - def dist(self,konfig,keys_check='ALL'): - """ calculates a distance to another config + def dist(self, konfig, keys_check="ALL"): + """calculates a distance to another config - Inputs: - konfig - a second config - keys_check - optional, a list of keys to check + Inputs: + konfig - a second config + keys_check - optional, a list of keys to check - Outputs: - distance - a float + Outputs: + distance - a float - Currently only works for DV_VALUE_NEW and DV_VALUE_OLD - Returns a large value otherwise + Currently only works for DV_VALUE_NEW and DV_VALUE_OLD + Returns a large value otherwise """ konfig_diff = self.diff(konfig) - if keys_check == 'ALL': + if keys_check == "ALL": keys_check = konfig_diff.keys() distance = 0.0 @@ -286,14 +287,13 @@ def dist(self,konfig,keys_check='ALL'): val1 = konfig_diff[key][0] val2 = konfig_diff[key][1] - if key in ['DV_VALUE_NEW', - 'DV_VALUE_OLD']: - val1 = np.array( val1 ) - val2 = np.array( val2 ) - this_diff = np.sqrt( np.sum( (val1-val2)**2 ) ) + if key in ["DV_VALUE_NEW", "DV_VALUE_OLD"]: + val1 = np.array(val1) + val2 = np.array(val2) + this_diff = np.sqrt(np.sum((val1 - val2) ** 2)) else: - print('Warning, unexpected config difference') + print("Warning, unexpected config difference") this_diff = inf distance += this_diff @@ -304,28 +304,26 @@ def dist(self,konfig,keys_check='ALL'): return distance def __repr__(self): - #return ' %s' % self._filename + # return ' %s' % self._filename return self.__str__() def __str__(self): - output = 'Config: %s' % self._filename - for k,v in self.items(): - output += '\n %s= %s' % (k,v) + output = "Config: %s" % self._filename + for k, v in self.items(): + output += "\n %s= %s" % (k, v) return output -#: class Config - - - +#: class Config # ------------------------------------------------------------------- # Get SU2 Configuration Parameters # ------------------------------------------------------------------- + def read_config(filename): - """ reads a config file """ + """reads a config file""" # initialize output dictionary data_dict = OrderedDict() @@ -340,12 +338,12 @@ def read_config(filename): break # remove line returns - line = line.strip('\r\n').strip() + line = line.strip("\r\n").strip() - if (len(line) == 0): + if len(line) == 0: continue # make sure it has useful data - if (line[0] == '%'): + if line[0] == "%": continue # --- Check if there is a line continuation character at the @@ -354,34 +352,40 @@ def read_config(filename): # If there is a statement after a cont. char # throw an error. ---*/ - while(line[0].endswith('\\') or len(line.split('\\')) > 1): + while line[0].endswith("\\") or len(line.split("\\")) > 1: tmp_line = input_file.readline() tmp_line = tmp_line.strip() - assert len(tmp_line.split('=')) <= 1, ('Statement found after line ' - 'continuation character in config file %s' % tmp_line) - if (not tmp_line.startswith('%')): - line = line.split('\\')[0] - line += ' ' + tmp_line + assert len(tmp_line.split("=")) <= 1, ( + "Statement found after line " + "continuation character in config file %s" % tmp_line + ) + if not tmp_line.startswith("%"): + line = line.split("\\")[0] + line += " " + tmp_line # split across equals sign - line = line.split("=",1) + line = line.split("=", 1) this_param = line[0].strip() this_value = line[1].strip() - assert this_param not in data_dict, ('Config file has multiple specifications of %s' % this_param ) + assert this_param not in data_dict, ( + "Config file has multiple specifications of %s" % this_param + ) for case in switch(this_param): # comma delimited lists of strings with or without paren's - if case("MARKER_EULER") or\ - case("MARKER_FAR") or\ - case("MARKER_PLOTTING") or\ - case("MARKER_MONITORING") or\ - case("MARKER_SYM") or\ - case("DV_KIND") : + if ( + case("MARKER_EULER") + or case("MARKER_FAR") + or case("MARKER_PLOTTING") + or case("MARKER_MONITORING") + or case("MARKER_SYM") + or case("DV_KIND") + ): # remove white space - this_value = ''.join(this_value.split()) + this_value = "".join(this_value.split()) # remove parens - this_value = this_value.strip('()') + this_value = this_value.strip("()") # split by comma data_dict[this_param] = this_value.split(",") break @@ -389,80 +393,102 @@ def read_config(filename): # semicolon delimited lists of comma delimited lists of floats if case("DV_PARAM"): # remove white space - info_General = ''.join(this_value.split()) + info_General = "".join(this_value.split()) # split by semicolon - info_General = info_General.split(';') + info_General = info_General.split(";") # build list of dv params, convert string to float dv_Parameters = [] - dv_FFDTag = [] - dv_Size = [] + dv_FFDTag = [] + dv_Size = [] for this_dvParam in info_General: - this_dvParam = this_dvParam.strip('()') + this_dvParam = this_dvParam.strip("()") this_dvParam = this_dvParam.split(",") - this_dvSize = 1 + this_dvSize = 1 # if FFD change the first element to work with numbers and float(x) - if data_dict["DV_KIND"][0] in ['FFD_SETTING','FFD_ANGLE_OF_ATTACK','FFD_CONTROL_POINT','FFD_NACELLE','FFD_GULL','FFD_TWIST_2D','FFD_TWIST','FFD_ROTATION','FFD_CAMBER','FFD_THICKNESS','FFD_CONTROL_POINT_2D','FFD_CAMBER_2D','FFD_THICKNESS_2D']: + if data_dict["DV_KIND"][0] in [ + "FFD_SETTING", + "FFD_ANGLE_OF_ATTACK", + "FFD_CONTROL_POINT", + "FFD_NACELLE", + "FFD_GULL", + "FFD_TWIST_2D", + "FFD_TWIST", + "FFD_ROTATION", + "FFD_CAMBER", + "FFD_THICKNESS", + "FFD_CONTROL_POINT_2D", + "FFD_CAMBER_2D", + "FFD_THICKNESS_2D", + ]: this_dvFFDTag = this_dvParam[0] - this_dvParam[0] = '0' + this_dvParam[0] = "0" else: this_dvFFDTag = [] - if not data_dict["DV_KIND"][0] in ['NO_DEFORMATION']: - this_dvParam = [ float(x) for x in this_dvParam ] + if not data_dict["DV_KIND"][0] in ["NO_DEFORMATION"]: + this_dvParam = [float(x) for x in this_dvParam] - if data_dict["DV_KIND"][0] in ['FFD_CONTROL_POINT_2D']: + if data_dict["DV_KIND"][0] in ["FFD_CONTROL_POINT_2D"]: if this_dvParam[3] == 0 and this_dvParam[4] == 0: this_dvSize = 2 - if data_dict["DV_KIND"][0]in ['FFD_CONTROL_POINT']: - if this_dvParam[4] == 0 and this_dvParam[5] == 0 and this_dvParam[6] == 0: + if data_dict["DV_KIND"][0] in ["FFD_CONTROL_POINT"]: + if ( + this_dvParam[4] == 0 + and this_dvParam[5] == 0 + and this_dvParam[6] == 0 + ): this_dvSize = 3 - dv_FFDTag = dv_FFDTag + [this_dvFFDTag] + dv_FFDTag = dv_FFDTag + [this_dvFFDTag] dv_Parameters = dv_Parameters + [this_dvParam] - dv_Size = dv_Size + [this_dvSize] + dv_Size = dv_Size + [this_dvSize] - # store in a dictionary - dv_Definitions = { 'FFDTAG' : dv_FFDTag , - 'PARAM' : dv_Parameters , - 'SIZE' : dv_Size} + # store in a dictionary + dv_Definitions = { + "FFDTAG": dv_FFDTag, + "PARAM": dv_Parameters, + "SIZE": dv_Size, + } data_dict[this_param] = dv_Definitions break # comma delimited lists of floats - if case("DV_VALUE_OLD") or\ - case("DV_VALUE_NEW") or\ - case("DV_VALUE") : + if case("DV_VALUE_OLD") or case("DV_VALUE_NEW") or case("DV_VALUE"): # remove white space - this_value = ''.join(this_value.split()) + this_value = "".join(this_value.split()) # split by comma, map to float, store in dictionary - data_dict[this_param] = list(map(float,this_value.split(","))) + data_dict[this_param] = list(map(float, this_value.split(","))) break # float parameters - if case("MACH_NUMBER") or\ - case("AOA") or\ - case("FIN_DIFF_STEP") or\ - case("CFL_NUMBER") or\ - case("HB_PERIOD") or\ - case("WRT_SOL_FREQ") : + if ( + case("MACH_NUMBER") + or case("AOA") + or case("FIN_DIFF_STEP") + or case("CFL_NUMBER") + or case("HB_PERIOD") + or case("WRT_SOL_FREQ") + ): data_dict[this_param] = float(this_value) break # int parameters - if case("NUMBER_PART") or\ - case("AVAILABLE_PROC") or\ - case("ITER") or\ - case("TIME_INSTANCES") or\ - case("UNST_ADJOINT_ITER") or\ - case("ITER_AVERAGE_OBJ") or\ - case("INNER_ITER") or\ - case("OUTER_ITER") or\ - case("TIME_ITER") or\ - case("ADAPT_CYCLES") : + if ( + case("NUMBER_PART") + or case("AVAILABLE_PROC") + or case("ITER") + or case("TIME_INSTANCES") + or case("UNST_ADJOINT_ITER") + or case("ITER_AVERAGE_OBJ") + or case("INNER_ITER") + or case("OUTER_ITER") + or case("TIME_ITER") + or case("ADAPT_CYCLES") + ): data_dict[this_param] = int(this_value) break @@ -482,154 +508,199 @@ def read_config(filename): # unitary design variable definition if case("DEFINITION_DV"): # remove white space - this_value = ''.join(this_value.split()) + this_value = "".join(this_value.split()) # split into unitary definitions info_Unitary = this_value.split(";") # process each Design Variable - dv_Kind = [] - dv_Scale = [] - dv_Markers = [] - dv_FFDTag = [] + dv_Kind = [] + dv_Scale = [] + dv_Markers = [] + dv_FFDTag = [] dv_Parameters = [] - dv_Size = [] + dv_Size = [] for this_General in info_Unitary: - if not this_General: continue + if not this_General: + continue # split each unitary definition into one general definition - info_General = this_General.strip("()").split("|") # check for needed strip()? + info_General = this_General.strip("()").split( + "|" + ) # check for needed strip()? # split information for dv Kinds - info_Kind = info_General[0].split(",") + info_Kind = info_General[0].split(",") # pull processed dv values - this_dvKind = get_dvKind( int( info_Kind[0] ) ) - this_dvScale = float( info_Kind[1] ) - this_dvMarkers = info_General[1].split(",") - this_dvSize = 1 + this_dvKind = get_dvKind(int(info_Kind[0])) + this_dvScale = float(info_Kind[1]) + this_dvMarkers = info_General[1].split(",") + this_dvSize = 1 - if this_dvKind=='MACH_NUMBER' or this_dvKind=='AOA': + if this_dvKind == "MACH_NUMBER" or this_dvKind == "AOA": this_dvParameters = [] else: this_dvParameters = info_General[2].split(",") # if FFD change the first element to work with numbers and float(x), save also the tag - if this_dvKind in ['FFD_SETTING','FFD_ANGLE_OF_ATTACK','FFD_CONTROL_POINT','FFD_NACELLE','FFD_GULL','FFD_TWIST','FFD_TWIST_2D','FFD_TWIST_ANGLE','FFD_ROTATION','FFD_CAMBER','FFD_THICKNESS','FFD_CONTROL_POINT_2D','FFD_CAMBER_2D','FFD_THICKNESS_2D']: - this_dvFFDTag = this_dvParameters[0] - this_dvParameters[0] = '0' + if this_dvKind in [ + "FFD_SETTING", + "FFD_ANGLE_OF_ATTACK", + "FFD_CONTROL_POINT", + "FFD_NACELLE", + "FFD_GULL", + "FFD_TWIST", + "FFD_TWIST_2D", + "FFD_TWIST_ANGLE", + "FFD_ROTATION", + "FFD_CAMBER", + "FFD_THICKNESS", + "FFD_CONTROL_POINT_2D", + "FFD_CAMBER_2D", + "FFD_THICKNESS_2D", + ]: + this_dvFFDTag = this_dvParameters[0] + this_dvParameters[0] = "0" else: - this_dvFFDTag = [] + this_dvFFDTag = [] - this_dvParameters = [ float(x) for x in this_dvParameters ] + this_dvParameters = [float(x) for x in this_dvParameters] - if this_dvKind in ['FFD_CONTROL_POINT_2D']: + if this_dvKind in ["FFD_CONTROL_POINT_2D"]: if this_dvParameters[3] == 0 and this_dvParameters[4] == 0: this_dvSize = 2 - if this_dvKind in ['FFD_CONTROL_POINT']: - if this_dvParameters[4] == 0 and this_dvParameters[5] == 0 and this_dvParameters[6] == 0: + if this_dvKind in ["FFD_CONTROL_POINT"]: + if ( + this_dvParameters[4] == 0 + and this_dvParameters[5] == 0 + and this_dvParameters[6] == 0 + ): this_dvSize = 3 # add to lists - dv_Kind = dv_Kind + [this_dvKind] - dv_Scale = dv_Scale + [this_dvScale] - dv_Markers = dv_Markers + [this_dvMarkers] - dv_FFDTag = dv_FFDTag + [this_dvFFDTag] + dv_Kind = dv_Kind + [this_dvKind] + dv_Scale = dv_Scale + [this_dvScale] + dv_Markers = dv_Markers + [this_dvMarkers] + dv_FFDTag = dv_FFDTag + [this_dvFFDTag] dv_Parameters = dv_Parameters + [this_dvParameters] - dv_Size = dv_Size + [this_dvSize] + dv_Size = dv_Size + [this_dvSize] # store in a dictionary - dv_Definitions = { 'KIND' : dv_Kind , - 'SCALE' : dv_Scale , - 'MARKER' : dv_Markers , - 'FFDTAG' : dv_FFDTag , - 'PARAM' : dv_Parameters , - 'SIZE' : dv_Size} + dv_Definitions = { + "KIND": dv_Kind, + "SCALE": dv_Scale, + "MARKER": dv_Markers, + "FFDTAG": dv_FFDTag, + "PARAM": dv_Parameters, + "SIZE": dv_Size, + } # save to output dictionary data_dict[this_param] = dv_Definitions break # unitary objective definition - if case('OPT_OBJECTIVE'): + if case("OPT_OBJECTIVE"): # remove white space - this_value = ''.join(this_value.split()) - #split by ; - this_def=OrderedDict() + this_value = "".join(this_value.split()) + # split by ; + this_def = OrderedDict() this_value = this_value.split(";") - for this_obj in this_value: + for this_obj in this_value: # split by scale this_obj = this_obj.split("*") - this_name = this_obj[0] + this_name = this_obj[0] this_scale = 1.0 if len(this_obj) > 1: - this_scale = float( this_obj[1] ) + this_scale = float(this_obj[1]) # check for penalty-based constraint function - for this_sgn in ['<','>','=']: - if this_sgn in this_name: break - this_obj = this_name.strip('()').split(this_sgn) - if len(this_obj)>1: + for this_sgn in ["<", ">", "="]: + if this_sgn in this_name: + break + this_obj = this_name.strip("()").split(this_sgn) + if len(this_obj) > 1: this_type = this_sgn this_val = this_obj[1] else: - this_type = 'DEFAULT' - this_val = 0.0 + this_type = "DEFAULT" + this_val = 0.0 this_name = this_obj[0] # Print an error and exit if the same key appears twice - if (this_name in this_def): - raise SystemExit('Multiple occurrences of the same objective in the OPT_OBJECTIVE definition are not currently supported. To evaluate one objective over multiple surfaces, list the objective once.') + if this_name in this_def: + raise SystemExit( + "Multiple occurrences of the same objective in the OPT_OBJECTIVE definition are not currently supported. To evaluate one objective over multiple surfaces, list the objective once." + ) # Set up dict for objective, including scale, whether it is a penalty, and constraint value - this_def.update({ this_name : {'SCALE':this_scale, 'OBJTYPE':this_type, 'VALUE':this_val} }) + this_def.update( + { + this_name: { + "SCALE": this_scale, + "OBJTYPE": this_type, + "VALUE": this_val, + } + } + ) # OPT_OBJECTIVE has to appear after MARKER_MONITORING in the .cfg, maybe catch that here - if (len(data_dict['MARKER_MONITORING'])>1): - this_def[this_name]['MARKER'] = data_dict['MARKER_MONITORING'][len(this_def)-1] + if len(data_dict["MARKER_MONITORING"]) > 1: + this_def[this_name]["MARKER"] = data_dict["MARKER_MONITORING"][ + len(this_def) - 1 + ] else: - this_def[this_name]['MARKER'] = data_dict['MARKER_MONITORING'][0] + this_def[this_name]["MARKER"] = data_dict["MARKER_MONITORING"][ + 0 + ] # save to output dictionary data_dict[this_param] = this_def break # unitary constraint definition - if case('OPT_CONSTRAINT'): + if case("OPT_CONSTRAINT"): # remove white space - this_value = ''.join(this_value.split()) + this_value = "".join(this_value.split()) # check for none case - if this_value == 'NONE': - data_dict[this_param] = {'EQUALITY':OrderedDict(), 'INEQUALITY':OrderedDict()} + if this_value == "NONE": + data_dict[this_param] = { + "EQUALITY": OrderedDict(), + "INEQUALITY": OrderedDict(), + } break # split definitions - this_value = this_value.split(';') + this_value = this_value.split(";") this_def = OrderedDict() for this_con in this_value: - if not this_con: continue # if no definition + if not this_con: + continue # if no definition # defaults - this_obj = 'NONE' - this_sgn = '=' + this_obj = "NONE" + this_sgn = "=" this_scl = 1.0 this_val = 0.0 # split scale if present - this_con = this_con.split('*') + this_con = this_con.split("*") if len(this_con) > 1: - this_scl = float( this_con[1] ) + this_scl = float(this_con[1]) this_con = this_con[0] # find sign - for this_sgn in ['<','>','=']: - if this_sgn in this_con: break + for this_sgn in ["<", ">", "="]: + if this_sgn in this_con: + break # split sign, store objective and value - this_con = this_con.strip('()').split(this_sgn) - assert len(this_con) == 2 , 'incorrect constraint definition' + this_con = this_con.strip("()").split(this_sgn) + assert len(this_con) == 2, "incorrect constraint definition" this_obj = this_con[0] - this_val = float( this_con[1] ) + this_val = float(this_con[1]) # store in dictionary - this_def[this_obj] = { 'SIGN' : this_sgn , - 'VALUE' : this_val , - 'SCALE' : this_scl } + this_def[this_obj] = { + "SIGN": this_sgn, + "VALUE": this_val, + "SCALE": this_scl, + } #: for each constraint definition # sort constraints by type - this_sort = { 'EQUALITY' : OrderedDict() , - 'INEQUALITY' : OrderedDict() } - for key,value in this_def.items(): - if value['SIGN'] == '=': - this_sort['EQUALITY'][key] = value + this_sort = {"EQUALITY": OrderedDict(), "INEQUALITY": OrderedDict()} + for key, value in this_def.items(): + if value["SIGN"] == "=": + this_sort["EQUALITY"][key] = value else: - this_sort['INEQUALITY'][key] = value + this_sort["INEQUALITY"][key] = value #: for each definition # save to output dictionary data_dict[this_param] = this_sort @@ -647,198 +718,223 @@ def read_config(filename): #: for line - if 'OPT_CONSTRAINT' in data_dict: - if 'BUFFET' in data_dict['OPT_CONSTRAINT']['EQUALITY'] or 'BUFFET' in data_dict['OPT_CONSTRAINT']['INEQUALITY']: - data_dict['BUFFET_MONITORING'] = "YES" - - if 'OPT_OBJECTIVE' in data_dict: - if 'BUFFET' in data_dict['OPT_OBJECTIVE']: - data_dict['BUFFET_MONITORING'] = "YES" - - #hack - twl - if 'DV_VALUE_NEW' not in data_dict: - data_dict['DV_VALUE_NEW'] = [0] - if 'DV_VALUE_OLD' not in data_dict: - data_dict['DV_VALUE_OLD'] = [0] - if 'OPT_ITERATIONS' not in data_dict: - data_dict['OPT_ITERATIONS'] = 100 - if 'OPT_ACCURACY' not in data_dict: - data_dict['OPT_ACCURACY'] = 1e-10 - if 'OPT_RELAX_FACTOR' not in data_dict: - data_dict['OPT_RELAX_FACTOR'] = 1.0 - if 'OPT_GRADIENT_FACTOR' not in data_dict: - data_dict['OPT_GRADIENT_FACTOR'] = 1.0 - if 'OPT_BOUND_UPPER' not in data_dict: - data_dict['OPT_BOUND_UPPER'] = 1e10 - if 'OPT_BOUND_LOWER' not in data_dict: - data_dict['OPT_BOUND_LOWER'] = -1e10 - if 'OPT_COMBINE_OBJECTIVE' not in data_dict: - data_dict['OPT_COMBINE_OBJECTIVE'] = "NO" - if 'OPT_CONSTRAINT' not in data_dict: - data_dict['OPT_CONSTRAINT'] = {'INEQUALITY': OrderedDict(), 'EQUALITY': OrderedDict()} - if 'VALUE_OBJFUNC_FILENAME' not in data_dict: - data_dict['VALUE_OBJFUNC_FILENAME'] = 'of_eval.dat' - if 'GRAD_OBJFUNC_FILENAME' not in data_dict: - data_dict['GRAD_OBJFUNC_FILENAME'] = 'of_grad.dat' - if 'AOA' not in data_dict: - data_dict['AOA'] = 0.0 - if 'SIDESLIP_ANGLE' not in data_dict: - data_dict['SIDESLIP_ANGLE'] = 0.0 - if 'MACH_NUMBER' not in data_dict: - data_dict['MACH_NUMBER'] = 0.0 - if 'REYNOLDS_NUMBER' not in data_dict: - data_dict['REYNOLDS_NUMBER'] = 0.0 - if 'TARGET_CL' not in data_dict: - data_dict['TARGET_CL'] = 0.0 - if 'FREESTREAM_PRESSURE' not in data_dict: - data_dict['FREESTREAM_PRESSURE'] = 101325.0 - if 'FREESTREAM_TEMPERATURE' not in data_dict: - data_dict['FREESTREAM_TEMPERATURE'] = 288.15 - if 'MARKER_OUTLET' not in data_dict: - data_dict['MARKER_OUTLET'] = '(NONE)' + if "OPT_CONSTRAINT" in data_dict: + if ( + "BUFFET" in data_dict["OPT_CONSTRAINT"]["EQUALITY"] + or "BUFFET" in data_dict["OPT_CONSTRAINT"]["INEQUALITY"] + ): + data_dict["BUFFET_MONITORING"] = "YES" + + if "OPT_OBJECTIVE" in data_dict: + if "BUFFET" in data_dict["OPT_OBJECTIVE"]: + data_dict["BUFFET_MONITORING"] = "YES" + + # hack - twl + if "DV_VALUE_NEW" not in data_dict: + data_dict["DV_VALUE_NEW"] = [0] + if "DV_VALUE_OLD" not in data_dict: + data_dict["DV_VALUE_OLD"] = [0] + if "OPT_ITERATIONS" not in data_dict: + data_dict["OPT_ITERATIONS"] = 100 + if "OPT_ACCURACY" not in data_dict: + data_dict["OPT_ACCURACY"] = 1e-10 + if "OPT_RELAX_FACTOR" not in data_dict: + data_dict["OPT_RELAX_FACTOR"] = 1.0 + if "OPT_GRADIENT_FACTOR" not in data_dict: + data_dict["OPT_GRADIENT_FACTOR"] = 1.0 + if "OPT_BOUND_UPPER" not in data_dict: + data_dict["OPT_BOUND_UPPER"] = 1e10 + if "OPT_BOUND_LOWER" not in data_dict: + data_dict["OPT_BOUND_LOWER"] = -1e10 + if "OPT_COMBINE_OBJECTIVE" not in data_dict: + data_dict["OPT_COMBINE_OBJECTIVE"] = "NO" + if "OPT_CONSTRAINT" not in data_dict: + data_dict["OPT_CONSTRAINT"] = { + "INEQUALITY": OrderedDict(), + "EQUALITY": OrderedDict(), + } + if "VALUE_OBJFUNC_FILENAME" not in data_dict: + data_dict["VALUE_OBJFUNC_FILENAME"] = "of_eval.dat" + if "GRAD_OBJFUNC_FILENAME" not in data_dict: + data_dict["GRAD_OBJFUNC_FILENAME"] = "of_grad.dat" + if "AOA" not in data_dict: + data_dict["AOA"] = 0.0 + if "SIDESLIP_ANGLE" not in data_dict: + data_dict["SIDESLIP_ANGLE"] = 0.0 + if "MACH_NUMBER" not in data_dict: + data_dict["MACH_NUMBER"] = 0.0 + if "REYNOLDS_NUMBER" not in data_dict: + data_dict["REYNOLDS_NUMBER"] = 0.0 + if "TARGET_CL" not in data_dict: + data_dict["TARGET_CL"] = 0.0 + if "FREESTREAM_PRESSURE" not in data_dict: + data_dict["FREESTREAM_PRESSURE"] = 101325.0 + if "FREESTREAM_TEMPERATURE" not in data_dict: + data_dict["FREESTREAM_TEMPERATURE"] = 288.15 + if "MARKER_OUTLET" not in data_dict: + data_dict["MARKER_OUTLET"] = "(NONE)" # # Multipoints requires some particular default values # multipoints = 1 - if 'MULTIPOINT_WEIGHT' not in data_dict: - data_dict['MULTIPOINT_WEIGHT'] = "(1.0)" - multipoints = 1 + if "MULTIPOINT_WEIGHT" not in data_dict: + data_dict["MULTIPOINT_WEIGHT"] = "(1.0)" + multipoints = 1 else: - multipoints = len(data_dict['MULTIPOINT_WEIGHT'].replace("(", "").replace(")", "").split(',')) - - if 'MULTIPOINT_MACH_NUMBER' not in data_dict: - Mach_Value = data_dict['MACH_NUMBER'] - Mach_List = "(" - for i in range(multipoints): - if i != 0: Mach_List += ", " - Mach_List += str(Mach_Value) - Mach_List += ")" - data_dict['MULTIPOINT_MACH_NUMBER'] = Mach_List - - if 'MULTIPOINT_AOA' not in data_dict: - Alpha_Value = data_dict['AOA'] - Alpha_List = "(" - for i in range(multipoints): - if i != 0: Alpha_List += ", " - Alpha_List += str(Alpha_Value) - Alpha_List += ")" - data_dict['MULTIPOINT_AOA'] = Alpha_List - - if 'MULTIPOINT_SIDESLIP_ANGLE' not in data_dict: - Beta_Value = data_dict['SIDESLIP_ANGLE'] - Beta_List = "(" - for i in range(multipoints): - if i != 0: Beta_List += ", " - Beta_List += str(Beta_Value) - Beta_List += ")" - data_dict['MULTIPOINT_SIDESLIP_ANGLE'] = Beta_List - - if 'MULTIPOINT_REYNOLDS_NUMBER' not in data_dict: - Reynolds_Value = data_dict['REYNOLDS_NUMBER'] - Reynolds_List = "(" - for i in range(multipoints): - if i != 0: Reynolds_List += ", " - Reynolds_List += str(Reynolds_Value) - Reynolds_List += ")" - data_dict['MULTIPOINT_REYNOLDS_NUMBER'] = Reynolds_List - - if 'MULTIPOINT_TARGET_CL' not in data_dict: - TargetCLValue = data_dict['TARGET_CL'] - TargetCL_List = "(" - for i in range(multipoints): - if i != 0: TargetCL_List += ", " - TargetCL_List += str(TargetCLValue) - TargetCL_List += ")" - data_dict['MULTIPOINT_TARGET_CL'] = TargetCL_List - - if 'MULTIPOINT_FREESTREAM_PRESSURE' not in data_dict: - Pressure_Value = data_dict['FREESTREAM_PRESSURE'] - Pressure_List = "(" - for i in range(multipoints): - if i != 0: Pressure_List += ", " - Pressure_List += str(Pressure_Value) - Pressure_List += ")" - data_dict['MULTIPOINT_FREESTREAM_PRESSURE'] = Pressure_List - - if 'MULTIPOINT_FREESTREAM_TEMPERATURE' not in data_dict: - Temperature_Value = data_dict['FREESTREAM_TEMPERATURE'] - Temperature_List = "(" - for i in range(multipoints): - if i != 0: Temperature_List += ", " - Temperature_List += str(Temperature_Value) - Temperature_List += ")" - data_dict['MULTIPOINT_FREESTREAM_TEMPERATURE'] = Temperature_List - - if 'MULTIPOINT_OUTLET_VALUE' not in data_dict: - if 'NONE' in data_dict['MARKER_OUTLET']: - Outlet_Value = 0.0 - else: - Outlet_Value = data_dict['MARKER_OUTLET'].replace("(", "").replace(")", "").split(',')[1] - Outlet_Value_List = "(" - for i in range(multipoints): - if i != 0: Outlet_Value_List += ", " - Outlet_Value_List += str(Outlet_Value) - Outlet_Value_List += ")" - data_dict['MULTIPOINT_OUTLET_VALUE'] = Outlet_Value_List - - if 'MULTIPOINT_MESH_FILENAME' not in data_dict: - Mesh_Filename = data_dict['MESH_FILENAME'] - Mesh_List = "(" - for i in range(multipoints): - if i != 0: Mesh_List += ", " - Mesh_List += str(Mesh_Filename) - Mesh_List += ")" - data_dict['MULTIPOINT_MESH_FILENAME'] = Mesh_List - - if 'HISTORY_OUTPUT' not in data_dict: - data_dict['HISTORY_OUTPUT'] = ['ITER', 'RMS_RES'] + multipoints = len( + data_dict["MULTIPOINT_WEIGHT"].replace("(", "").replace(")", "").split(",") + ) + + if "MULTIPOINT_MACH_NUMBER" not in data_dict: + Mach_Value = data_dict["MACH_NUMBER"] + Mach_List = "(" + for i in range(multipoints): + if i != 0: + Mach_List += ", " + Mach_List += str(Mach_Value) + Mach_List += ")" + data_dict["MULTIPOINT_MACH_NUMBER"] = Mach_List + + if "MULTIPOINT_AOA" not in data_dict: + Alpha_Value = data_dict["AOA"] + Alpha_List = "(" + for i in range(multipoints): + if i != 0: + Alpha_List += ", " + Alpha_List += str(Alpha_Value) + Alpha_List += ")" + data_dict["MULTIPOINT_AOA"] = Alpha_List + + if "MULTIPOINT_SIDESLIP_ANGLE" not in data_dict: + Beta_Value = data_dict["SIDESLIP_ANGLE"] + Beta_List = "(" + for i in range(multipoints): + if i != 0: + Beta_List += ", " + Beta_List += str(Beta_Value) + Beta_List += ")" + data_dict["MULTIPOINT_SIDESLIP_ANGLE"] = Beta_List + + if "MULTIPOINT_REYNOLDS_NUMBER" not in data_dict: + Reynolds_Value = data_dict["REYNOLDS_NUMBER"] + Reynolds_List = "(" + for i in range(multipoints): + if i != 0: + Reynolds_List += ", " + Reynolds_List += str(Reynolds_Value) + Reynolds_List += ")" + data_dict["MULTIPOINT_REYNOLDS_NUMBER"] = Reynolds_List + + if "MULTIPOINT_TARGET_CL" not in data_dict: + TargetCLValue = data_dict["TARGET_CL"] + TargetCL_List = "(" + for i in range(multipoints): + if i != 0: + TargetCL_List += ", " + TargetCL_List += str(TargetCLValue) + TargetCL_List += ")" + data_dict["MULTIPOINT_TARGET_CL"] = TargetCL_List + + if "MULTIPOINT_FREESTREAM_PRESSURE" not in data_dict: + Pressure_Value = data_dict["FREESTREAM_PRESSURE"] + Pressure_List = "(" + for i in range(multipoints): + if i != 0: + Pressure_List += ", " + Pressure_List += str(Pressure_Value) + Pressure_List += ")" + data_dict["MULTIPOINT_FREESTREAM_PRESSURE"] = Pressure_List + + if "MULTIPOINT_FREESTREAM_TEMPERATURE" not in data_dict: + Temperature_Value = data_dict["FREESTREAM_TEMPERATURE"] + Temperature_List = "(" + for i in range(multipoints): + if i != 0: + Temperature_List += ", " + Temperature_List += str(Temperature_Value) + Temperature_List += ")" + data_dict["MULTIPOINT_FREESTREAM_TEMPERATURE"] = Temperature_List + + if "MULTIPOINT_OUTLET_VALUE" not in data_dict: + if "NONE" in data_dict["MARKER_OUTLET"]: + Outlet_Value = 0.0 + else: + Outlet_Value = ( + data_dict["MARKER_OUTLET"] + .replace("(", "") + .replace(")", "") + .split(",")[1] + ) + Outlet_Value_List = "(" + for i in range(multipoints): + if i != 0: + Outlet_Value_List += ", " + Outlet_Value_List += str(Outlet_Value) + Outlet_Value_List += ")" + data_dict["MULTIPOINT_OUTLET_VALUE"] = Outlet_Value_List + + if "MULTIPOINT_MESH_FILENAME" not in data_dict: + Mesh_Filename = data_dict["MESH_FILENAME"] + Mesh_List = "(" + for i in range(multipoints): + if i != 0: + Mesh_List += ", " + Mesh_List += str(Mesh_Filename) + Mesh_List += ")" + data_dict["MULTIPOINT_MESH_FILENAME"] = Mesh_List + + if "HISTORY_OUTPUT" not in data_dict: + data_dict["HISTORY_OUTPUT"] = ["ITER", "RMS_RES"] # # Default values for optimization parameters (needed for some eval functions # that can be called outside of an opt. context. # - if 'OBJECTIVE_FUNCTION' not in data_dict: - data_dict['OBJECTIVE_FUNCTION']='DRAG' - if 'DV_KIND' not in data_dict: - data_dict['DV_KIND']=['FFD_SETTING'] - if 'DV_PARAM' not in data_dict: - data_dict['DV_PARAM']={'FFDTAG': ['1'], 'PARAM': [[0.0, 0.5]], 'SIZE': [1]} - if 'DEFINITION_DV' not in data_dict: - data_dict['DEFINITION_DV']={'FFDTAG': [[]], - 'KIND': ['HICKS_HENNE'], - 'MARKER': [['WING']], - 'PARAM': [[0.0, 0.05]], - 'SCALE': [1.0], - 'SIZE': [1]} - if 'VALUE_OBJFUNC_FILENAME' not in data_dict: - data_dict['VALUE_OBJFUNC_FILENAME'] = 'of_eval.dat' - if 'GRAD_OBJFUNC_FILENAME' not in data_dict: - data_dict['GRAD_OBJFUNC_FILENAME'] = 'of_grad.dat' + if "OBJECTIVE_FUNCTION" not in data_dict: + data_dict["OBJECTIVE_FUNCTION"] = "DRAG" + if "DV_KIND" not in data_dict: + data_dict["DV_KIND"] = ["FFD_SETTING"] + if "DV_PARAM" not in data_dict: + data_dict["DV_PARAM"] = {"FFDTAG": ["1"], "PARAM": [[0.0, 0.5]], "SIZE": [1]} + if "DEFINITION_DV" not in data_dict: + data_dict["DEFINITION_DV"] = { + "FFDTAG": [[]], + "KIND": ["HICKS_HENNE"], + "MARKER": [["WING"]], + "PARAM": [[0.0, 0.05]], + "SCALE": [1.0], + "SIZE": [1], + } + if "VALUE_OBJFUNC_FILENAME" not in data_dict: + data_dict["VALUE_OBJFUNC_FILENAME"] = "of_eval.dat" + if "GRAD_OBJFUNC_FILENAME" not in data_dict: + data_dict["GRAD_OBJFUNC_FILENAME"] = "of_grad.dat" return data_dict -#: def read_config() +#: def read_config() # ------------------------------------------------------------------- # Set SU2 Configuration Parameters # ------------------------------------------------------------------- -def write_config(filename,param_dict): - """ updates an existing config file """ - temp_filename = filename+"_tmp" - shutil.copy(filename,temp_filename) - output_file = open(filename,"w") +def write_config(filename, param_dict): + """updates an existing config file""" + + temp_filename = filename + "_tmp" + shutil.copy(filename, temp_filename) + output_file = open(filename, "w") # break pointers param_dict = copy.deepcopy(param_dict) for raw_line in open(temp_filename): # remove line returns - line = raw_line.strip('\r\n') + line = raw_line.strip("\r\n") # make sure it has useful data if not "=" in line: @@ -848,7 +944,7 @@ def write_config(filename,param_dict): # split across equals sign line = line.split("=") this_param = line[0].strip() - old_value = line[1].strip() + old_value = line[1].strip() # skip if parameter unwanted if this_param not in param_dict: @@ -863,43 +959,52 @@ def write_config(filename,param_dict): for case in switch(this_param): # comma delimited list of floats - if case("DV_VALUE_NEW") : pass - if case("DV_VALUE_OLD") : pass - if case("DV_VALUE") : + if case("DV_VALUE_NEW"): + pass + if case("DV_VALUE_OLD"): + pass + if case("DV_VALUE"): n_lists = len(new_value) for i_value in range(n_lists): output_file.write("%s" % new_value[i_value]) - if i_value+1 < n_lists: + if i_value + 1 < n_lists: output_file.write(", ") break # comma delimited list of strings no paren's - if case("DV_KIND") : pass - if case("TASKS") : pass - if case("GRADIENTS") : - if not isinstance(new_value,list): - new_value = [ new_value ] + if case("DV_KIND"): + pass + if case("TASKS"): + pass + if case("GRADIENTS"): + if not isinstance(new_value, list): + new_value = [new_value] n_lists = len(new_value) for i_value in range(n_lists): output_file.write(new_value[i_value]) - if i_value+1 < n_lists: + if i_value + 1 < n_lists: output_file.write(", ") break # comma delimited list of strings inside paren's - if case("MARKER_EULER") : pass - if case("MARKER_FAR") : pass - if case("MARKER_PLOTTING") : pass - if case("MARKER_MONITORING") : pass - if case("MARKER_SYM") : pass - if case("DV_MARKER") : - if not isinstance(new_value,list): - new_value = [ new_value ] + if case("MARKER_EULER"): + pass + if case("MARKER_FAR"): + pass + if case("MARKER_PLOTTING"): + pass + if case("MARKER_MONITORING"): + pass + if case("MARKER_SYM"): + pass + if case("DV_MARKER"): + if not isinstance(new_value, list): + new_value = [new_value] output_file.write("( ") n_lists = len(new_value) for i_value in range(n_lists): output_file.write(new_value[i_value]) - if i_value+1 < n_lists: + if i_value + 1 < n_lists: output_file.write(", ") output_file.write(" )") break @@ -908,7 +1013,7 @@ def write_config(filename,param_dict): output_file.write("(") for i_value in range(n_lists): output_file.write(new_value[i_value]) - if i_value+1 < n_lists: + if i_value + 1 < n_lists: output_file.write(", ") output_file.write(")") break @@ -918,7 +1023,7 @@ def write_config(filename,param_dict): output_file.write("(") for i_value in range(n_lists): output_file.write(new_value[i_value]) - if i_value+1 < n_lists: + if i_value + 1 < n_lists: output_file.write(", ") output_file.write(")") break @@ -927,123 +1032,159 @@ def write_config(filename,param_dict): n_lists = len(new_value) for i_value in range(n_lists): output_file.write(new_value[i_value]) - if i_value+1 < n_lists: + if i_value + 1 < n_lists: output_file.write(", ") break # semicolon delimited lists of comma delimited lists - if case("DV_PARAM") : + if case("DV_PARAM"): - assert isinstance(new_value['PARAM'],list) , 'incorrect specification of DV_PARAM' - if not isinstance(new_value['PARAM'][0],list): new_value = [ new_value ] + assert isinstance( + new_value["PARAM"], list + ), "incorrect specification of DV_PARAM" + if not isinstance(new_value["PARAM"][0], list): + new_value = [new_value] - for i_value in range(len(new_value['PARAM'])): + for i_value in range(len(new_value["PARAM"])): output_file.write("( ") - this_param_list = new_value['PARAM'][i_value] - this_ffd_list = new_value['FFDTAG'][i_value] + this_param_list = new_value["PARAM"][i_value] + this_ffd_list = new_value["FFDTAG"][i_value] n_lists = len(this_param_list) if this_ffd_list != []: - output_file.write("%s, " % this_ffd_list) - for j_value in range(1,n_lists): - output_file.write("%s" % this_param_list[j_value]) - if j_value+1 < n_lists: - output_file.write(", ") + output_file.write("%s, " % this_ffd_list) + for j_value in range(1, n_lists): + output_file.write("%s" % this_param_list[j_value]) + if j_value + 1 < n_lists: + output_file.write(", ") else: - for j_value in range(n_lists): - output_file.write("%s" % this_param_list[j_value]) - if j_value+1 < n_lists: - output_file.write(", ") + for j_value in range(n_lists): + output_file.write("%s" % this_param_list[j_value]) + if j_value + 1 < n_lists: + output_file.write(", ") output_file.write(") ") - if i_value+1 < len(new_value['PARAM']): + if i_value + 1 < len(new_value["PARAM"]): output_file.write("; ") break # int parameters - if case("NUMBER_PART") : pass - if case("ADAPT_CYCLES") : pass - if case("TIME_INSTANCES") : pass - if case("AVAILABLE_PROC") : pass - if case("UNST_ADJOINT_ITER") : pass - if case("ITER") or\ - case("TIME_ITER") or\ - case("INNER_ITER") or\ - case("OUTER_ITER"): + if case("NUMBER_PART"): + pass + if case("ADAPT_CYCLES"): + pass + if case("TIME_INSTANCES"): + pass + if case("AVAILABLE_PROC"): + pass + if case("UNST_ADJOINT_ITER"): + pass + if ( + case("ITER") + or case("TIME_ITER") + or case("INNER_ITER") + or case("OUTER_ITER") + ): output_file.write("%i" % new_value) break - if case("DEFINITION_DV") : - n_dv = len(new_value['KIND']) + if case("DEFINITION_DV"): + n_dv = len(new_value["KIND"]) if not n_dv: output_file.write("NONE") for i_dv in range(n_dv): - this_kind = new_value['KIND'][i_dv] + this_kind = new_value["KIND"][i_dv] output_file.write("( ") - output_file.write("%i , " % get_dvID(this_kind) ) - output_file.write("%s " % new_value['SCALE'][i_dv]) + output_file.write("%i , " % get_dvID(this_kind)) + output_file.write("%s " % new_value["SCALE"][i_dv]) output_file.write("| ") # markers - n_mark = len(new_value['MARKER'][i_dv]) + n_mark = len(new_value["MARKER"][i_dv]) for i_mark in range(n_mark): - output_file.write("%s " % new_value['MARKER'][i_dv][i_mark]) - if i_mark+1 < n_mark: + output_file.write("%s " % new_value["MARKER"][i_dv][i_mark]) + if i_mark + 1 < n_mark: output_file.write(", ") #: for each marker - if not this_kind in ['AOA','MACH_NUMBER']: + if not this_kind in ["AOA", "MACH_NUMBER"]: output_file.write(" | ") # params - if this_kind in ['FFD_SETTING','FFD_ANGLE_OF_ATTACK','FFD_CONTROL_POINT','FFD_NACELLE','FFD_GULL','FFD_TWIST_ANGLE','FFD_TWIST','FFD_TWIST_2D','FFD_ROTATION','FFD_CAMBER','FFD_THICKNESS','FFD_CONTROL_POINT_2D','FFD_CAMBER_2D','FFD_THICKNESS_2D']: - n_param = len(new_value['PARAM'][i_dv]) - output_file.write("%s , " % new_value['FFDTAG'][i_dv]) - for i_param in range(1,n_param): - output_file.write("%s " % new_value['PARAM'][i_dv][i_param]) - if i_param+1 < n_param: + if this_kind in [ + "FFD_SETTING", + "FFD_ANGLE_OF_ATTACK", + "FFD_CONTROL_POINT", + "FFD_NACELLE", + "FFD_GULL", + "FFD_TWIST_ANGLE", + "FFD_TWIST", + "FFD_TWIST_2D", + "FFD_ROTATION", + "FFD_CAMBER", + "FFD_THICKNESS", + "FFD_CONTROL_POINT_2D", + "FFD_CAMBER_2D", + "FFD_THICKNESS_2D", + ]: + n_param = len(new_value["PARAM"][i_dv]) + output_file.write("%s , " % new_value["FFDTAG"][i_dv]) + for i_param in range(1, n_param): + output_file.write( + "%s " % new_value["PARAM"][i_dv][i_param] + ) + if i_param + 1 < n_param: output_file.write(", ") else: - n_param = len(new_value['PARAM'][i_dv]) + n_param = len(new_value["PARAM"][i_dv]) for i_param in range(n_param): - output_file.write("%s " % new_value['PARAM'][i_dv][i_param]) - if i_param+1 < n_param: + output_file.write( + "%s " % new_value["PARAM"][i_dv][i_param] + ) + if i_param + 1 < n_param: output_file.write(", ") #: for each param output_file.write(" )") - if i_dv+1 < n_dv: + if i_dv + 1 < n_dv: output_file.write("; ") #: for each dv break if case("OPT_OBJECTIVE"): n_obj = 0 - for name,value in new_value.items(): - if n_obj>0: output_file.write("; ") - if value['OBJTYPE']=='DEFAULT': - output_file.write( "%s * %s " % (name,value['SCALE']) ) + for name, value in new_value.items(): + if n_obj > 0: + output_file.write("; ") + if value["OBJTYPE"] == "DEFAULT": + output_file.write("%s * %s " % (name, value["SCALE"])) else: - output_file.write( "( %s %s %s ) * %s" - % (name, value['OBJTYPE'], value['VALUE'], value['SCALE']) ) + output_file.write( + "( %s %s %s ) * %s" + % (name, value["OBJTYPE"], value["VALUE"], value["SCALE"]) + ) n_obj += 1 break if case("OPT_CONSTRAINT"): i_con = 0 - for con_type in ['EQUALITY','INEQUALITY']: + for con_type in ["EQUALITY", "INEQUALITY"]: this_con = new_value[con_type] - for name,value in this_con.items(): - if i_con>0: output_file.write("; ") - output_file.write( "( %s %s %s ) * %s" - % (name, value['SIGN'], value['VALUE'], value['SCALE']) ) + for name, value in this_con.items(): + if i_con > 0: + output_file.write("; ") + output_file.write( + "( %s %s %s ) * %s" + % (name, value["SIGN"], value["VALUE"], value["SCALE"]) + ) i_con += 1 #: for each constraint #: for each constraint type - if not i_con: output_file.write("NONE") + if not i_con: + output_file.write("NONE") break # default, assume string, integer or unformatted float if case(): - output_file.write('%s' % new_value) + output_file.write("%s" % new_value) break #: for case @@ -1058,29 +1199,32 @@ def write_config(filename,param_dict): # check that all params were used for this_param in param_dict.keys(): - if not this_param in ['JOB_NUMBER']: - print('Warning: Parameter %s not found in config file and was not written' % (this_param)) + if not this_param in ["JOB_NUMBER"]: + print( + "Warning: Parameter %s not found in config file and was not written" + % (this_param) + ) output_file.close() os.remove(temp_filename) + #: def write_config() -def dump_config(filename,config): - ''' dumps a raw config file with all options in config - and no comments - ''' +def dump_config(filename, config): + """dumps a raw config file with all options in config + and no comments + """ # HACK - twl - if 'DV_VALUE_NEW' in config: + if "DV_VALUE_NEW" in config: config.DV_VALUE = config.DV_VALUE_NEW - config_file = open(filename,'w') + config_file = open(filename, "w") # write dummy file for key in config.keys(): - config_file.write( '%s= 0 \n' % key ) + config_file.write("%s= 0 \n" % key) config_file.close() # dump data - write_config(filename,config) - + write_config(filename, config) diff --git a/SU2_PY/SU2/io/config_options.py b/SU2_PY/SU2/io/config_options.py index 6423e8499d0..1fda9691abd 100644 --- a/SU2_PY/SU2/io/config_options.py +++ b/SU2_PY/SU2/io/config_options.py @@ -29,130 +29,139 @@ from ..util import ordered_bunch + class OptionError(Exception): pass -class Option(object): +class Option(object): def __init__(self): self.val = "" def __get__(self): return self.val - def __set__(self,newval): + def __set__(self, newval): self.val = newval + #: class Option -class MathProblem(Option): - def __init__(self,*args,**kwarg): - super(MathProblem,self).__init__(*args,**kwarg) - self.validoptions = ['DIRECT','CONTINUOUS_ADJOINT','LINEARIZED'] +class MathProblem(Option): + def __init__(self, *args, **kwarg): + super(MathProblem, self).__init__(*args, **kwarg) + self.validoptions = ["DIRECT", "CONTINUOUS_ADJOINT", "LINEARIZED"] - def __set__(self,newval): + def __set__(self, newval): if not self.newval in self.validoptions: - raise OptionError("Invalid option. Valid options are: %s"%self.validoptions) - super(MathProblem,self).__set__(newval) + raise OptionError( + "Invalid option. Valid options are: %s" % self.validoptions + ) + super(MathProblem, self).__set__(newval) + #: class MathProblem + class DEFINITION_DV(ordered_bunch): - """ SU2.io.config.DEFINITION_DV() - - List of design variables (Design variables are separated by semicolons) - 2D Design variables - -FFD_CONTROL_POINT_2D ( 19, Scale | Mark. List | FFD_BoxTag, i_Ind, j_Ind, x_Mov, y_Mov ) - -FFD_CAMBER_2D ( 20, Scale | Mark. List | FFD_BoxTag, i_Ind ) - -FFD_THICKNESS_2D ( 21, Scale | Mark. List | FFD_BoxTag, i_Ind ) - -FFD_TWIST_2D ( 22, Scale | Mark. List | FFD_BoxTag, x_Orig, y_Orig ) - -HICKS_HENNE ( 30, Scale | Mark. List | Lower(0)/Upper(1) side, x_Loc ) - -ANGLE_OF_ATTACK ( 101, Scale | Mark. List | 1.0 ) - - 3D Design variables - -FFD_CONTROL_POINT ( 11, Scale | Mark. List | FFD_BoxTag, i_Ind, j_Ind, k_Ind, x_Mov, y_Mov, z_Mov ) - -FFD_NACELLE ( 12, Scale | Mark. List | FFD_BoxTag, rho_Ind, theta_Ind, phi_Ind, rho_Mov, phi_Mov ) - -FFD_GULL ( 13, Scale | Mark. List | FFD_BoxTag, j_Ind ) - -FFD_CAMBER ( 14, Scale | Mark. List | FFD_BoxTag, i_Ind, j_Ind ) - -FFD_TWIST ( 15, Scale | Mark. List | FFD_BoxTag, j_Ind, x_Orig, y_Orig, z_Orig, x_End, y_End, z_End ) - -FFD_THICKNESS ( 16, Scale | Mark. List | FFD_BoxTag, i_Ind, j_Ind ) - -FFD_ROTATION ( 18, Scale | Mark. List | FFD_BoxTag, x_Axis, y_Axis, z_Axis, x_Turn, y_Turn, z_Turn ) - -FFD_ANGLE_OF_ATTACK ( 24, Scale | Mark. List | FFD_BoxTag, 1.0 ) - - Global design variables - -TRANSLATION ( 1, Scale | Mark. List | x_Disp, y_Disp, z_Disp ) - -ROTATION ( 2, Scale | Mark. List | x_Axis, y_Axis, z_Axis, x_Turn, y_Turn, z_Turn ) + """SU2.io.config.DEFINITION_DV() + + List of design variables (Design variables are separated by semicolons) + 2D Design variables + -FFD_CONTROL_POINT_2D ( 19, Scale | Mark. List | FFD_BoxTag, i_Ind, j_Ind, x_Mov, y_Mov ) + -FFD_CAMBER_2D ( 20, Scale | Mark. List | FFD_BoxTag, i_Ind ) + -FFD_THICKNESS_2D ( 21, Scale | Mark. List | FFD_BoxTag, i_Ind ) + -FFD_TWIST_2D ( 22, Scale | Mark. List | FFD_BoxTag, x_Orig, y_Orig ) + -HICKS_HENNE ( 30, Scale | Mark. List | Lower(0)/Upper(1) side, x_Loc ) + -ANGLE_OF_ATTACK ( 101, Scale | Mark. List | 1.0 ) + + 3D Design variables + -FFD_CONTROL_POINT ( 11, Scale | Mark. List | FFD_BoxTag, i_Ind, j_Ind, k_Ind, x_Mov, y_Mov, z_Mov ) + -FFD_NACELLE ( 12, Scale | Mark. List | FFD_BoxTag, rho_Ind, theta_Ind, phi_Ind, rho_Mov, phi_Mov ) + -FFD_GULL ( 13, Scale | Mark. List | FFD_BoxTag, j_Ind ) + -FFD_CAMBER ( 14, Scale | Mark. List | FFD_BoxTag, i_Ind, j_Ind ) + -FFD_TWIST ( 15, Scale | Mark. List | FFD_BoxTag, j_Ind, x_Orig, y_Orig, z_Orig, x_End, y_End, z_End ) + -FFD_THICKNESS ( 16, Scale | Mark. List | FFD_BoxTag, i_Ind, j_Ind ) + -FFD_ROTATION ( 18, Scale | Mark. List | FFD_BoxTag, x_Axis, y_Axis, z_Axis, x_Turn, y_Turn, z_Turn ) + -FFD_ANGLE_OF_ATTACK ( 24, Scale | Mark. List | FFD_BoxTag, 1.0 ) + + Global design variables + -TRANSLATION ( 1, Scale | Mark. List | x_Disp, y_Disp, z_Disp ) + -ROTATION ( 2, Scale | Mark. List | x_Axis, y_Axis, z_Axis, x_Turn, y_Turn, z_Turn ) """ - def __init__(self,*args,**kwarg): + def __init__(self, *args, **kwarg): ordered_bunch.__init__(self) - self.KIND = [] - self.SCALE = [] + self.KIND = [] + self.SCALE = [] self.MARKER = [] self.FFDTAG = [] - self.PARAM = [] - self.update(ordered_bunch(*args,**kwarg)) - - def append(self,new_dv): - self.KIND. append(new_dv['KIND']) - self.SCALE. append(new_dv['SCALE']) - self.MARKER.append(new_dv['MARKER']) - self.FFDTAG.append(new_dv['FFDTAG']) - self.PARAM. append(new_dv['PARAM']) - - def extend(self,new_dvs): - assert isinstance(new_dvs,DEFINITION_DV) , 'input must be of type DEFINITION_DV' - self.KIND. extend(new_dvs['KIND']) - self.SCALE. extend(new_dvs['SCALE']) - self.MARKER.extend(new_dvs['MARKER']) - self.FFDTAG.extend(new_dvs['FFDTAG']) - self.PARAM. extend(new_dvs['PARAM']) + self.PARAM = [] + self.update(ordered_bunch(*args, **kwarg)) + + def append(self, new_dv): + self.KIND.append(new_dv["KIND"]) + self.SCALE.append(new_dv["SCALE"]) + self.MARKER.append(new_dv["MARKER"]) + self.FFDTAG.append(new_dv["FFDTAG"]) + self.PARAM.append(new_dv["PARAM"]) + + def extend(self, new_dvs): + assert isinstance(new_dvs, DEFINITION_DV), "input must be of type DEFINITION_DV" + self.KIND.extend(new_dvs["KIND"]) + self.SCALE.extend(new_dvs["SCALE"]) + self.MARKER.extend(new_dvs["MARKER"]) + self.FFDTAG.extend(new_dvs["FFDTAG"]) + self.PARAM.extend(new_dvs["PARAM"]) + #: class DEFINITION_DV + class DV_KIND(ordered_bunch): - """ SU2.io.config.DV_KIND() - - List of design variables (Design variables are separated by semicolons) - 2D Design variables - -FFD_CONTROL_POINT_2D ( 19, Scale | Mark. List | FFD_BoxTag, i_Ind, j_Ind, x_Mov, y_Mov ) - -FFD_CAMBER_2D ( 20, Scale | Mark. List | FFD_BoxTag, i_Ind ) - -FFD_THICKNESS_2D ( 21, Scale | Mark. List | FFD_BoxTag, i_Ind ) - -FFD_TWIST_2D ( 22, Scale | Mark. List | FFD_BoxTag, x_Orig, y_Orig ) - -HICKS_HENNE ( 30, Scale | Mark. List | Lower(0)/Upper(1) side, x_Loc ) - -ANGLE_OF_ATTACK ( 101, Scale | Mark. List | 1.0 ) - - 3D Design variables - -FFD_CONTROL_POINT ( 11, Scale | Mark. List | FFD_BoxTag, i_Ind, j_Ind, k_Ind, x_Mov, y_Mov, z_Mov ) - -FFD_NACELLE ( 12, Scale | Mark. List | FFD_BoxTag, rho_Ind, theta_Ind, phi_Ind, rho_Mov, phi_Mov ) - -FFD_GULL ( 13, Scale | Mark. List | FFD_BoxTag, j_Ind ) - -FFD_CAMBER ( 14, Scale | Mark. List | FFD_BoxTag, i_Ind, j_Ind ) - -FFD_TWIST ( 15, Scale | Mark. List | FFD_BoxTag, j_Ind, x_Orig, y_Orig, z_Orig, x_End, y_End, z_End ) - -FFD_THICKNESS ( 16, Scale | Mark. List | FFD_BoxTag, i_Ind, j_Ind ) - -FFD_ROTATION ( 18, Scale | Mark. List | FFD_BoxTag, x_Axis, y_Axis, z_Axis, x_Turn, y_Turn, z_Turn ) - -FFD_ANGLE_OF_ATTACK ( 24, Scale | Mark. List | FFD_BoxTag, 1.0 ) - - Global design variables - -TRANSLATION ( 1, Scale | Mark. List | x_Disp, y_Disp, z_Disp ) - -ROTATION ( 2, Scale | Mark. List | x_Axis, y_Axis, z_Axis, x_Turn, y_Turn, z_Turn ) + """SU2.io.config.DV_KIND() + + List of design variables (Design variables are separated by semicolons) + 2D Design variables + -FFD_CONTROL_POINT_2D ( 19, Scale | Mark. List | FFD_BoxTag, i_Ind, j_Ind, x_Mov, y_Mov ) + -FFD_CAMBER_2D ( 20, Scale | Mark. List | FFD_BoxTag, i_Ind ) + -FFD_THICKNESS_2D ( 21, Scale | Mark. List | FFD_BoxTag, i_Ind ) + -FFD_TWIST_2D ( 22, Scale | Mark. List | FFD_BoxTag, x_Orig, y_Orig ) + -HICKS_HENNE ( 30, Scale | Mark. List | Lower(0)/Upper(1) side, x_Loc ) + -ANGLE_OF_ATTACK ( 101, Scale | Mark. List | 1.0 ) + + 3D Design variables + -FFD_CONTROL_POINT ( 11, Scale | Mark. List | FFD_BoxTag, i_Ind, j_Ind, k_Ind, x_Mov, y_Mov, z_Mov ) + -FFD_NACELLE ( 12, Scale | Mark. List | FFD_BoxTag, rho_Ind, theta_Ind, phi_Ind, rho_Mov, phi_Mov ) + -FFD_GULL ( 13, Scale | Mark. List | FFD_BoxTag, j_Ind ) + -FFD_CAMBER ( 14, Scale | Mark. List | FFD_BoxTag, i_Ind, j_Ind ) + -FFD_TWIST ( 15, Scale | Mark. List | FFD_BoxTag, j_Ind, x_Orig, y_Orig, z_Orig, x_End, y_End, z_End ) + -FFD_THICKNESS ( 16, Scale | Mark. List | FFD_BoxTag, i_Ind, j_Ind ) + -FFD_ROTATION ( 18, Scale | Mark. List | FFD_BoxTag, x_Axis, y_Axis, z_Axis, x_Turn, y_Turn, z_Turn ) + -FFD_ANGLE_OF_ATTACK ( 24, Scale | Mark. List | FFD_BoxTag, 1.0 ) + + Global design variables + -TRANSLATION ( 1, Scale | Mark. List | x_Disp, y_Disp, z_Disp ) + -ROTATION ( 2, Scale | Mark. List | x_Axis, y_Axis, z_Axis, x_Turn, y_Turn, z_Turn ) """ - def __init__(self,*args,**kwarg): - ordered_bunch.__init__(self) - self.FFDTAG = [] - self.PARAM = [] - self.update(ordered_bunch(*args,**kwarg)) + def __init__(self, *args, **kwarg): + ordered_bunch.__init__(self) + self.FFDTAG = [] + self.PARAM = [] + self.update(ordered_bunch(*args, **kwarg)) + + def append(self, new_dv): + self.FFDTAG.append(new_dv["FFDTAG"]) + self.PARAM.append(new_dv["PARAM"]) - def append(self,new_dv): - self.FFDTAG.append(new_dv['FFDTAG']) - self.PARAM. append(new_dv['PARAM']) + def extend(self, new_dvs): + assert isinstance(new_dvs, DV_KIND), "input must be of type DV_KIND" + self.FFDTAG.extend(new_dvs["FFDTAG"]) + self.PARAM.extend(new_dvs["PARAM"]) - def extend(self,new_dvs): - assert isinstance(new_dvs,DV_KIND) , 'input must be of type DV_KIND' - self.FFDTAG.extend(new_dvs['FFDTAG']) - self.PARAM. extend(new_dvs['PARAM']) #: class DV_KIND diff --git a/SU2_PY/SU2/io/data.py b/SU2_PY/SU2/io/data.py index ee667f0d18d..a666b3643e4 100644 --- a/SU2_PY/SU2/io/data.py +++ b/SU2_PY/SU2/io/data.py @@ -30,6 +30,7 @@ # ---------------------------------------------------------------------- import os, sys, shutil, copy + if sys.version_info[0] > 2: # Py3 pickle now manage both accelerated cPickle and pure python pickle # See https://docs.python.org/3/whatsnew/3.0.html#library-changes, 4th item. @@ -44,67 +45,69 @@ # Load a Dictionary of Data # ------------------------------------------------------------------- -def load_data( file_name, var_names=None , - file_format = 'infer' , - core_name = 'python_data' ): - """ data = load_data( file_name, var_names=None , - file_format = 'infer' , - core_name = 'python_data' ) - - loads dictionary of data from python pickle or matlab struct - - Inputs: - file_name - data file name - var_names - variable names to read - file_format - 'infer', 'pickle', or 'matlab' - core_name - data is stored under a dictionary with this name - - default looks for variable 'python_data' in file_name - file_format = pickle, will return any python object - file_format = matlab, will return strings or float lists and - requires scipy.io.loadmat - file_format = infer (default), will infer format from extention - ('.mat','.pkl') + +def load_data(file_name, var_names=None, file_format="infer", core_name="python_data"): + """data = load_data( file_name, var_names=None , + file_format = 'infer' , + core_name = 'python_data' ) + + loads dictionary of data from python pickle or matlab struct + + Inputs: + file_name - data file name + var_names - variable names to read + file_format - 'infer', 'pickle', or 'matlab' + core_name - data is stored under a dictionary with this name + + default looks for variable 'python_data' in file_name + file_format = pickle, will return any python object + file_format = matlab, will return strings or float lists and + requires scipy.io.loadmat + file_format = infer (default), will infer format from extention + ('.mat','.pkl') """ try: import scipy.io + scipy_loaded = True except ImportError: scipy_loaded = False if not os.path.exists(file_name): - raise Exception('File does not exist: %s' % file_name) + raise Exception("File does not exist: %s" % file_name) # process file format - if file_format == 'infer': - if os.path.splitext(file_name)[1] == '.mat': - file_format = 'matlab' - elif os.path.splitext(file_name)[1] == '.pkl': - file_format = 'pickle' - assert file_format in ['matlab','pickle'] , 'unsupported file format' + if file_format == "infer": + if os.path.splitext(file_name)[1] == ".mat": + file_format = "matlab" + elif os.path.splitext(file_name)[1] == ".pkl": + file_format = "pickle" + assert file_format in ["matlab", "pickle"], "unsupported file format" # get filelock with filelock(file_name): # LOAD MATLAB - if file_format == 'matlab' and scipy_loaded: - input_data = scipy.io.loadmat( file_name = file_name , - squeeze_me = False , - chars_as_strings = True , - struct_as_record = True ) + if file_format == "matlab" and scipy_loaded: + input_data = scipy.io.loadmat( + file_name=file_name, + squeeze_me=False, + chars_as_strings=True, + struct_as_record=True, + ) # pull core variable - assert (core_name in input_data) , 'core data not found' + assert core_name in input_data, "core data not found" input_data = input_data[core_name] # convert recarray to dictionary input_data = rec2dict(input_data) # LOAD PICKLE - elif file_format == 'pickle': + elif file_format == "pickle": input_data = load_pickle(file_name) # pull core variable - assert (core_name in input_data) , 'core data not found' + assert core_name in input_data, "core data not found" input_data = input_data[core_name] #: if file_format @@ -114,8 +117,10 @@ def load_data( file_name, var_names=None , # load specified varname into dictionary if var_names != None: # check for one item name array - if isinstance(var_names,str): - var_names = [var_names,] + if isinstance(var_names, str): + var_names = [ + var_names, + ] for key in input_data.keys(): if not key in var_names: del input_data[key] @@ -124,53 +129,55 @@ def load_data( file_name, var_names=None , return input_data -#: def load() +#: def load() # ------------------------------------------------------------------- # Save a Dictionary of Data # ------------------------------------------------------------------- -def save_data( file_name, data_dict, append=False , + +def save_data( + file_name, data_dict, append=False, file_format="infer", core_name="python_data" +): + """save_data( file_name, data_dict, append=False , file_format = 'infer' , core_name='python_data' ): - """ save_data( file_name, data_dict, append=False , - file_format = 'infer' , - core_name='python_data' ): - - Inputs: - file_name - data file name - data_dict - a dictionary or bunch to write - append - True/False to append existing data - file_format - 'infer', 'pickle', or 'matlab' - core_name - data is stored under a dictionary with this name - - file_format = pickle, will save any pickleable python object - file_format = matlab, will save strings or float lists and - requires scipy.io.loadmat - file_format = infer (default), will infer format from extention - ('.mat','.pkl') - - matlab format saves data file from matlab 5 and later - will save nested dictionaries into nested matlab structures - cannot save classes and modules - uses scipy.io.loadmat + + Inputs: + file_name - data file name + data_dict - a dictionary or bunch to write + append - True/False to append existing data + file_format - 'infer', 'pickle', or 'matlab' + core_name - data is stored under a dictionary with this name + + file_format = pickle, will save any pickleable python object + file_format = matlab, will save strings or float lists and + requires scipy.io.loadmat + file_format = infer (default), will infer format from extention + ('.mat','.pkl') + + matlab format saves data file from matlab 5 and later + will save nested dictionaries into nested matlab structures + cannot save classes and modules + uses scipy.io.loadmat """ try: import scipy.io + scipy_loaded = True except ImportError: scipy_loaded = False # process file format - if file_format == 'infer': - if os.path.splitext(file_name)[1] == '.mat': - file_format = 'matlab' - elif os.path.splitext(file_name)[1] == '.pkl': - file_format = 'pickle' - assert file_format in ['matlab','pickle'] , 'unsupported file format' + if file_format == "infer": + if os.path.splitext(file_name)[1] == ".mat": + file_format = "matlab" + elif os.path.splitext(file_name)[1] == ".pkl": + file_format = "pickle" + assert file_format in ["matlab", "pickle"], "unsupported file format" # get filelock with filelock(file_name): @@ -180,34 +187,38 @@ def save_data( file_name, data_dict, append=False , if append == True and os.path.exists(file_name): # check file exists if not os.path.exists(file_name): - raise Exception('Cannot append, file does not exist: %s' % file_name) + raise Exception("Cannot append, file does not exist: %s" % file_name) # load old data - data_dict_old = load( file_name = file_name , - var_names = None , - file_format = file_format , - core_name = core_name ) + data_dict_old = load( + file_name=file_name, + var_names=None, + file_format=file_format, + core_name=core_name, + ) # check for keys not in new data - for key,value in data_dict_old.iteritems(): - if not(key in data_dict): + for key, value in data_dict_old.iteritems(): + if not (key in data_dict): data_dict[key] = value #: for each dict item #: if append # save to core name - data_dict = {core_name : data_dict} + data_dict = {core_name: data_dict} # SAVE MATLAB - if file_format == 'matlab': + if file_format == "matlab": # bunch it data_dict = mat_bunch(data_dict) # save it - scipy.io.savemat( file_name = file_name , - mdict = data_dict, - format = '5', # matlab 5 .mat format - oned_as = 'column' ) - elif file_format == 'pickle': + scipy.io.savemat( + file_name=file_name, + mdict=data_dict, + format="5", # matlab 5 .mat format + oned_as="column", + ) + elif file_format == "pickle": # save it - save_pickle(file_name,data_dict) + save_pickle(file_name, data_dict) #: if file_format @@ -215,26 +226,27 @@ def save_data( file_name, data_dict, append=False , return -#: def save() +#: def save() # ------------------------------------------------------------------- # Load Pickle # ------------------------------------------------------------------- + def load_pickle(file_name): - """ data = load_pickle(file_name) - loads a pickle with core_data dictionaries - assumes first entry is a list of all following data names - returns dictionary of data + """data = load_pickle(file_name) + loads a pickle with core_data dictionaries + assumes first entry is a list of all following data names + returns dictionary of data """ - pkl_file = open(file_name,'rb') - #names = safe_unpickle.loadf(pkl_file) + pkl_file = open(file_name, "rb") + # names = safe_unpickle.loadf(pkl_file) names = pickle.load(pkl_file) - data_dict = dict.fromkeys(names,[]) + data_dict = dict.fromkeys(names, []) for key in names: - #data_dict[key] = safe_unpickle.loadf(pkl_file) + # data_dict[key] = safe_unpickle.loadf(pkl_file) data_dict[key] = pickle.load(pkl_file) pkl_file.close() return data_dict @@ -244,12 +256,13 @@ def load_pickle(file_name): # Save Pickle # ------------------------------------------------------------------- + def save_pickle(file_name, data_dict): - """ save_pickle(file_name, data_dict) - saves a core data dictionary - first pickle entry is a list of all following data names + """save_pickle(file_name, data_dict) + saves a core data dictionary + first pickle entry is a list of all following data names """ - pkl_file = open(file_name, 'wb') + pkl_file = open(file_name, "wb") names = list(data_dict.keys()) pickle.dump(names, pkl_file) for key in names: @@ -261,84 +274,84 @@ def save_pickle(file_name, data_dict): # Safe UnPickle # ------------------------------------------------------------------- -#class safe_unpickle(pickle.Unpickler): - #''' adds some safety to unpickling - #checks that only supported classes are loaded - #original source from http://nadiana.com/python-pickle-insecure#comment-144 - #''' - - ## modules : classes considered safe - #PICKLE_SAFE = { - #'copy_reg' : ['_reconstructor'] , - #'__builtin__' : ['object'] , - #'numpy' : ['dtype','ndarray'] , - #'numpy.core.multiarray' : ['scalar','_reconstruct'] , - #'collections' : ['OrderedDict'] , - #'SU2.io.state' : ['State'] , # SU2 Specific - #'SU2.io.config' : ['Config'] , - #'SU2.eval.design' : ['Design'] , - #'SU2.opt.project' : ['Project'] , - #'SU2.util.ordered_bunch' : ['OrderedBunch'] , - #'SU2.util.bunch' : ['Bunch'] , - #'tasks_general' : ['General_Task'] , - #'tasks_project' : ['Project','Job'] , - #'tasks_su2' : ['Decomp','Deform','Direct','Cont_Adjoint', - #'Multiple_Cont_Adjoint','Finite_Diff','Adapt'] , - #} - - ## make sets - #for key in PICKLE_SAFE.keys(): - #PICKLE_SAFE[key] = set(PICKLE_SAFE[key]) - - ## check for save module/class - #def find_class(self, module, name): - #if not module in self.PICKLE_SAFE: - #raise pickle.UnpicklingError( - #'Attempting to unpickle unsafe module %s' % module - #) - #__import__(module) - #mod = sys.modules[module] - #if not name in self.PICKLE_SAFE[module]: - #raise pickle.UnpicklingError( - #'Attempting to unpickle unsafe class %s' % name - #) - #klass = getattr(mod, name) - #return klass - - ## extend the load() and loads() methods - #@classmethod - #def loadf(self, pickle_file): # loads a file like pickle.load() - #return self(pickle_file).load() - #@classmethod - #def loads(self, pickle_string): #loads a string like pickle.loads() - #return self(StringIO.StringIO(pickle_string)).load() - +# class safe_unpickle(pickle.Unpickler): +#''' adds some safety to unpickling +# checks that only supported classes are loaded +# original source from http://nadiana.com/python-pickle-insecure#comment-144 +#''' + +## modules : classes considered safe +# PICKLE_SAFE = { +#'copy_reg' : ['_reconstructor'] , +#'__builtin__' : ['object'] , +#'numpy' : ['dtype','ndarray'] , +#'numpy.core.multiarray' : ['scalar','_reconstruct'] , +#'collections' : ['OrderedDict'] , +#'SU2.io.state' : ['State'] , # SU2 Specific +#'SU2.io.config' : ['Config'] , +#'SU2.eval.design' : ['Design'] , +#'SU2.opt.project' : ['Project'] , +#'SU2.util.ordered_bunch' : ['OrderedBunch'] , +#'SU2.util.bunch' : ['Bunch'] , +#'tasks_general' : ['General_Task'] , +#'tasks_project' : ['Project','Job'] , +#'tasks_su2' : ['Decomp','Deform','Direct','Cont_Adjoint', +#'Multiple_Cont_Adjoint','Finite_Diff','Adapt'] , +# } + +## make sets +# for key in PICKLE_SAFE.keys(): +# PICKLE_SAFE[key] = set(PICKLE_SAFE[key]) + +## check for save module/class +# def find_class(self, module, name): +# if not module in self.PICKLE_SAFE: +# raise pickle.UnpicklingError( +#'Attempting to unpickle unsafe module %s' % module +# ) +# __import__(module) +# mod = sys.modules[module] +# if not name in self.PICKLE_SAFE[module]: +# raise pickle.UnpicklingError( +#'Attempting to unpickle unsafe class %s' % name +# ) +# klass = getattr(mod, name) +# return klass + +## extend the load() and loads() methods +# @classmethod +# def loadf(self, pickle_file): # loads a file like pickle.load() +# return self(pickle_file).load() +# @classmethod +# def loads(self, pickle_string): #loads a string like pickle.loads() +# return self(StringIO.StringIO(pickle_string)).load() # ------------------------------------------------------------------- # Convert Record Array to Dictionary # ------------------------------------------------------------------- + def rec2dict(array_in): - """ converts numpy record array to dictionary of lists - needed for loading matlab data - assumes array comes from scipy.io.loadmat, with - squeeze_me = False and struct_as_record = True + """converts numpy record array to dictionary of lists + needed for loading matlab data + assumes array comes from scipy.io.loadmat, with + squeeze_me = False and struct_as_record = True """ import numpy - assert isinstance(array_in,numpy.ndarray) , 'input must be a numpy record array' + assert isinstance(array_in, numpy.ndarray), "input must be a numpy record array" # make sure it's not an object array - if array_in.dtype == numpy.dtype('object'): + if array_in.dtype == numpy.dtype("object"): array_in = array_in.tolist() # get record keys/names keys = array_in.dtype.names # start output dictionary - dataout = dict.fromkeys(keys,[]) + dataout = dict.fromkeys(keys, []) for key in keys: @@ -346,11 +359,11 @@ def rec2dict(array_in): value = array_in[key].tolist()[0][0] # convert string - if isinstance(value[0],unicode): + if isinstance(value[0], unicode): value = str(value[0]) # convert array - elif isinstance(value,numpy.ndarray): + elif isinstance(value, numpy.ndarray): # check for another struct level if value.dtype.names == None: value = value.tolist() @@ -363,6 +376,7 @@ def rec2dict(array_in): return dataout + #: def rec2dict() @@ -370,30 +384,31 @@ def rec2dict(array_in): # Flatten a List # ------------------------------------------------------------------- + def flatten_list(input_list): - ''' flatten an irregular list of lists of any depth - ''' + """flatten an irregular list of lists of any depth""" output_list = [] for value in input_list: - if isinstance(value,list): - output_list.extend( flatten_list(value) ) # telescope + if isinstance(value, list): + output_list.extend(flatten_list(value)) # telescope else: output_list.append(value) return output_list -#: def flatten_list() +#: def flatten_list() # ------------------------------------------------------------------- # Append Lists in a Nested Dictionary # ------------------------------------------------------------------- -def append_nestdict(base_dict,add_dict): - """ append_nestdict(base_dict,add_dict) - appends base_dict with add_dict, allowing for - updating nested dictionaries - will update base_dict in place + +def append_nestdict(base_dict, add_dict): + """append_nestdict(base_dict,add_dict) + appends base_dict with add_dict, allowing for + updating nested dictionaries + will update base_dict in place """ # break pointer @@ -404,18 +419,19 @@ def append_nestdict(base_dict,add_dict): # ensure base_dict key exists and is a list if not base_dict.has_key(key): - if isinstance( add_dict[key] , dict ): + if isinstance(add_dict[key], dict): base_dict[key] = {} else: base_dict[key] = [] - elif not ( isinstance( base_dict[key] , list ) - or isinstance( base_dict[key] , dict ) ): - assert not isinstance( add_dict[key] , dict ) , 'base[key] is not a dictionary while add[key] is' + elif not (isinstance(base_dict[key], list) or isinstance(base_dict[key], dict)): + assert not isinstance( + add_dict[key], dict + ), "base[key] is not a dictionary while add[key] is" base_dict[key] = [base_dict[key]] # append list or telescope - if isinstance( base_dict[key] , dict ): - append_nestdict(base_dict[key],add_dict[key]) # telescope + if isinstance(base_dict[key], dict): + append_nestdict(base_dict[key], add_dict[key]) # telescope else: base_dict[key].append(add_dict[key]) @@ -424,28 +440,27 @@ def append_nestdict(base_dict,add_dict): # base_dict will be updated through its pointer return -#: def append_nestdict() - - - - +#: def append_nestdict() # ------------------------------------------------------------------- # Matlab Bunch Class # ------------------------------------------------------------------- + class mat_bunch: - """ replicates dictionary functionality with class dot structure - for output of dictionaries to matlab + """replicates dictionary functionality with class dot structure + for output of dictionaries to matlab """ def __init__(self, d): for k, v in d.items(): if isinstance(v, dict): - if len(v): v = mat_bunch(v) - else: v = [] + if len(v): + v = mat_bunch(v) + else: + v = [] self.__dict__[k] = v def __dict__(self): @@ -454,27 +469,31 @@ def __dict__(self): # items def keys(self): return self.__dict__.keys() + def values(self): return self.__dict__.values() + def items(self): return self.__dict__.items() # dictionary get/set/etc - def __getitem__(self,k): + def __getitem__(self, k): return self.__dict__[k] - def __setitem__(self,k,v): + + def __setitem__(self, k, v): self.__dict__[k] = v - def __delitem__(self,k): + + def __delitem__(self, k): del self.__dict__[k] + def __str__(self): - print_format = '%s: %s' + print_format = "%s: %s" state = [] - for k,v in self.__dict__.items(): - if isinstance(v,mat_bunch): - v = '%i-item mat_bunch' % len(v.items()) - state.append(print_format % (k,v) ) - return '\n'.join(state) - -#: class mat_bunch + for k, v in self.__dict__.items(): + if isinstance(v, mat_bunch): + v = "%i-item mat_bunch" % len(v.items()) + state.append(print_format % (k, v)) + return "\n".join(state) +#: class mat_bunch diff --git a/SU2_PY/SU2/io/filelock.py b/SU2_PY/SU2/io/filelock.py index 87da207295f..1a6a15b19ae 100644 --- a/SU2_PY/SU2/io/filelock.py +++ b/SU2_PY/SU2/io/filelock.py @@ -32,27 +32,27 @@ # File Lock Class # ------------------------------------------------------------------- class filelock(object): - """ A file locking mechanism that has context-manager support so - you can use it in a with statement. - - Example: - with filelock("test.txt", timeout=2, delay=0.5): - print("Lock acquired.") - # Do something with the locked file - - Inputs: - file_name - filename to lock - timeout - default 10sec, maximum timeout to wait for lock - delay - default 0.05sec, delay between each attempt to lock - number incremented with a random perturbation - - original source: Evan Fosmark, BSD license - http://www.evanfosmark.com/2009/01/cross-platform-file-locking-support-in-python/ + """A file locking mechanism that has context-manager support so + you can use it in a with statement. + + Example: + with filelock("test.txt", timeout=2, delay=0.5): + print("Lock acquired.") + # Do something with the locked file + + Inputs: + file_name - filename to lock + timeout - default 10sec, maximum timeout to wait for lock + delay - default 0.05sec, delay between each attempt to lock + number incremented with a random perturbation + + original source: Evan Fosmark, BSD license + http://www.evanfosmark.com/2009/01/cross-platform-file-locking-support-in-python/ """ - def __init__(self, file_name, timeout=10, delay=.05): - """ Prepare the file locker. Specify the file to lock and optionally - the maximum timeout and the delay between each attempt to lock. + def __init__(self, file_name, timeout=10, delay=0.05): + """Prepare the file locker. Specify the file to lock and optionally + the maximum timeout and the delay between each attempt to lock. """ self.is_locked = False self.lockfile = os.path.join(os.getcwd(), "%s.lock" % file_name) @@ -60,63 +60,62 @@ def __init__(self, file_name, timeout=10, delay=.05): self.timeout = timeout self.delay = delay - def acquire(self): - """ Acquire the lock, if possible. If the lock is in use, it check again - every `wait` seconds. It does this until it either gets the lock or - exceeds `timeout` number of seconds, in which case it throws - an exception. + """Acquire the lock, if possible. If the lock is in use, it check again + every `wait` seconds. It does this until it either gets the lock or + exceeds `timeout` number of seconds, in which case it throws + an exception. """ start_time = time.time() while True: try: - self.fd = os.open(self.lockfile, os.O_CREAT|os.O_EXCL|os.O_RDWR) - break; + self.fd = os.open(self.lockfile, os.O_CREAT | os.O_EXCL | os.O_RDWR) + break except OSError as e: if e.errno != errno.EEXIST: raise if (time.time() - start_time) >= self.timeout: - raise FileLockException("FileLock timeout occured for %s" % self.lockfile) - delay = self.delay*( 1. + 0.2*random() ) + raise FileLockException( + "FileLock timeout occured for %s" % self.lockfile + ) + delay = self.delay * (1.0 + 0.2 * random()) time.sleep(delay) self.is_locked = True - def release(self): - """ Get rid of the lock by deleting the lockfile. - When working in a `with` statement, this gets automatically - called at the end. + """Get rid of the lock by deleting the lockfile. + When working in a `with` statement, this gets automatically + called at the end. """ if self.is_locked: os.close(self.fd) os.unlink(self.lockfile) self.is_locked = False - def __enter__(self): - """ Activated when used in the with statement. - Should automatically acquire a lock to be used in the with block. + """Activated when used in the with statement. + Should automatically acquire a lock to be used in the with block. """ if not self.is_locked: self.acquire() return self - def __exit__(self, type, value, traceback): - """ Activated at the end of the with statement. - It automatically releases the lock if it isn't locked. + """Activated at the end of the with statement. + It automatically releases the lock if it isn't locked. """ if self.is_locked: self.release() - def __del__(self): - """ Make sure that the FileLock instance doesn't leave a lockfile - lying around. + """Make sure that the FileLock instance doesn't leave a lockfile + lying around. """ self.release() + class FileLockException(Exception): pass + #: class filelock diff --git a/SU2_PY/SU2/io/historyMap.py b/SU2_PY/SU2/io/historyMap.py index 1e16597389c..aca169155e2 100644 --- a/SU2_PY/SU2/io/historyMap.py +++ b/SU2_PY/SU2/io/historyMap.py @@ -1,1480 +1,2011 @@ -history_header_map = {'ADJOINT_DISP_X': {'DESCRIPTION': 'Root-mean square residual of the adjoint ' - 'of the X displacements.', - 'GROUP': 'RMS_RES', - 'HEADER': 'rms[Ux_adj]', - 'TYPE': 'RESIDUAL'}, - 'ADJOINT_DISP_Y': {'DESCRIPTION': 'Root-mean square residual of the adjoint ' - 'of the Y displacements.', - 'GROUP': 'RMS_RES', - 'HEADER': 'rms[Uy_adj]', - 'TYPE': 'RESIDUAL'}, - 'ADJOINT_DISP_Z': {'DESCRIPTION': 'Root-mean square residual of the adjoint ' - 'of the Z displacements.', - 'GROUP': 'RMS_RES', - 'HEADER': 'rms[Uz_adj]', - 'TYPE': 'RESIDUAL'}, - 'ADJOINT_SOLEXTRA': {'DESCRIPTION': 'Adjoint value of the first extra ' - 'Solution.', - 'GROUP': 'ADJOINT_SOLEXTRA', - 'HEADER': 'Adjoint_SolExtra', - 'TYPE': 'COEFFICIENT'}, - 'AOA': {'DESCRIPTION': 'Angle of attack', - 'GROUP': 'AOA', - 'HEADER': 'AoA', - 'TYPE': 'DEFAULT'}, - 'AVG_CFL': {'DESCRIPTION': 'Current average of the local CFL numbers', - 'GROUP': 'CFL_NUMBER', - 'HEADER': 'Avg CFL', - 'TYPE': 'DEFAULT'}, - 'AVG_DENSITY': {'DESCRIPTION': 'Total average density on all markers set in ' - 'MARKER_ANALYZE', - 'GROUP': 'FLOW_COEFF', - 'HEADER': 'Avg_Density', - 'TYPE': 'COEFFICIENT'}, - 'AVG_ENTHALPY': {'DESCRIPTION': 'Total average enthalpy on all markers set in ' - 'MARKER_ANALYZE', - 'GROUP': 'FLOW_COEFF', - 'HEADER': 'Avg_Enthalpy', - 'TYPE': 'COEFFICIENT'}, - 'AVG_NORMALVEL': {'DESCRIPTION': 'Total average normal velocity on all ' - 'markers set in MARKER_ANALYZE', - 'GROUP': 'FLOW_COEFF', - 'HEADER': 'Avg_NormalVel', - 'TYPE': 'COEFFICIENT'}, - 'AVG_TEMPERATURE': {'DESCRIPTION': 'Average temperature on all surfaces ' - 'defined in MARKER_MONITORING', - 'GROUP': 'HEAT', - 'HEADER': 'AvgTemp', - 'TYPE': 'COEFFICIENT'}, - 'BGS_ADJ_DENSITY': {'DESCRIPTION': 'BGS residual of the adjoint density.', - 'GROUP': 'BGS_RES', - 'HEADER': 'bgs[A_Rho]', - 'TYPE': 'RESIDUAL'}, - 'BGS_ADJ_DISP_X': {'DESCRIPTION': 'BGS residual of the adjoint X ' - 'displacement.', - 'GROUP': 'BGS_RES', - 'HEADER': 'bgs[A_Ux]', - 'TYPE': 'RESIDUAL'}, - 'BGS_ADJ_DISP_Y': {'DESCRIPTION': 'BGS residual of the adjoint Y ' - 'displacement.', - 'GROUP': 'BGS_RES', - 'HEADER': 'bgs[A_Uy]', - 'TYPE': 'RESIDUAL'}, - 'BGS_ADJ_DISP_Z': {'DESCRIPTION': 'BGS residual of the adjoint Z ' - 'displacement.', - 'GROUP': 'BGS_RES', - 'HEADER': 'bgs[A_Uz]', - 'TYPE': 'RESIDUAL'}, - 'BGS_ADJ_DISSIPATION': {'DESCRIPTION': 'BGS residual of the adjoint ' - 'dissipation.', - 'GROUP': 'BGS_RES', - 'HEADER': 'bgs[A_w]', - 'TYPE': 'RESIDUAL'}, - 'BGS_ADJ_ENERGY': {'DESCRIPTION': 'BGS residual of the adjoint energy.', - 'GROUP': 'BGS_RES', - 'HEADER': 'bgs[A_E]', - 'TYPE': 'RESIDUAL'}, - 'BGS_ADJ_MOMENTUM-X': {'DESCRIPTION': 'BGS residual of the adjoint momentum ' - 'x-component', - 'GROUP': 'BGS_RES', - 'HEADER': 'bgs[A_RhoU]', - 'TYPE': 'RESIDUAL'}, - 'BGS_ADJ_MOMENTUM-Y': {'DESCRIPTION': 'BGS residual of the adjoint momentum ' - 'y-component', - 'GROUP': 'BGS_RES', - 'HEADER': 'bgs[A_RhoV]', - 'TYPE': 'RESIDUAL'}, - 'BGS_ADJ_MOMENTUM-Z': {'DESCRIPTION': 'BGS residual of the adjoint momentum ' - 'z-component', - 'GROUP': 'BGS_RES', - 'HEADER': 'bgs[A_RhoW]', - 'TYPE': 'RESIDUAL'}, - 'BGS_ADJ_NU_TILDE': {'DESCRIPTION': 'BGS residual of the adjoint nu tilde.', - 'GROUP': 'BGS_RES', - 'HEADER': 'bgs[A_nu]', - 'TYPE': 'RESIDUAL'}, - 'BGS_ADJ_PRESSURE': {'DESCRIPTION': 'BGS residual of the adjoint Pressure.', - 'GROUP': 'BGS_RES', - 'HEADER': 'bgs[A_Rho]', - 'TYPE': 'RESIDUAL'}, - 'BGS_ADJ_RAD_ENERGY': {'DESCRIPTION': 'BGS residual of the P1 radiative ' - 'energy.', - 'GROUP': 'BGS_RES', - 'HEADER': 'bgs[A_P1]', - 'TYPE': 'RESIDUAL'}, - 'BGS_ADJ_SPECIES_" + std::to_string(iVar': {'DESCRIPTION': 'BGS residual of ' - 'the adjoint ' - 'transported ' - 'species.', - 'GROUP': 'BGS_RES', - 'HEADER': 'bgs[A_rho*Y_" + ' - 'std::to_string(iVar) + ' - '"]', - 'TYPE': 'RESIDUAL'}, - 'BGS_ADJ_TEMPERATURE': {'DESCRIPTION': 'BGS residual of the adjoint ' - 'temperature.', - 'GROUP': 'BGS_RES', - 'HEADER': 'bgs[A_T]', - 'TYPE': 'RESIDUAL'}, - 'BGS_ADJ_TKE': {'DESCRIPTION': 'BGS residual of the adjoint kinetic energy.', - 'GROUP': 'BGS_RES', - 'HEADER': 'bgs[A_k]', - 'TYPE': 'RESIDUAL'}, - 'BGS_ADJ_VELOCITY-X': {'DESCRIPTION': 'BGS residual of the adjoint Velocity ' - 'x-component', - 'GROUP': 'BGS_RES', - 'HEADER': 'bgs[A_RhoU]', - 'TYPE': 'RESIDUAL'}, - 'BGS_ADJ_VELOCITY-Y': {'DESCRIPTION': 'BGS residual of the adjoint Velocity ' - 'y-component', - 'GROUP': 'BGS_RES', - 'HEADER': 'bgs[A_RhoV]', - 'TYPE': 'RESIDUAL'}, - 'BGS_ADJ_VELOCITY-Z': {'DESCRIPTION': 'BGS residual of the adjoint Velocity ' - 'z-component', - 'GROUP': 'BGS_RES', - 'HEADER': 'bgs[A_RhoW]', - 'TYPE': 'RESIDUAL'}, - 'BGS_DENSITY': {'DESCRIPTION': 'BGS residual of the density.', - 'GROUP': 'BGS_RES', - 'HEADER': 'bgs[Rho]', - 'TYPE': 'RESIDUAL'}, - 'BGS_DISP_X': {'DESCRIPTION': 'BGS residual of X displacement', - 'GROUP': 'BGS_RES', - 'HEADER': 'bgs[DispX]', - 'TYPE': 'RESIDUAL'}, - 'BGS_DISP_Y': {'DESCRIPTION': 'BGS residual of Y displacement', - 'GROUP': 'BGS_RES', - 'HEADER': 'bgs[DispY]', - 'TYPE': 'RESIDUAL'}, - 'BGS_DISP_Z': {'DESCRIPTION': 'BGS residual of Z displacement', - 'GROUP': 'BGS_RES', - 'HEADER': 'bgs[DispZ]', - 'TYPE': 'RESIDUAL'}, - 'BGS_DISSIPATION': {'DESCRIPTION': 'BGS residual of dissipation (SST model).', - 'GROUP': 'BGS_RES', - 'HEADER': 'bgs[w]', - 'TYPE': 'RESIDUAL'}, - 'BGS_ENERGY': {'DESCRIPTION': 'BGS residual of the energy.', - 'GROUP': 'BGS_RES', - 'HEADER': 'bgs[RhoE]', - 'TYPE': 'RESIDUAL'}, - 'BGS_MOMENTUM-X': {'DESCRIPTION': 'BGS residual of the momentum x-component.', - 'GROUP': 'BGS_RES', - 'HEADER': 'bgs[RhoU]', - 'TYPE': 'RESIDUAL'}, - 'BGS_MOMENTUM-Y': {'DESCRIPTION': 'BGS residual of the momentum y-component.', - 'GROUP': 'BGS_RES', - 'HEADER': 'bgs[RhoV]', - 'TYPE': 'RESIDUAL'}, - 'BGS_NU_TILDE': {'DESCRIPTION': 'BGS residual of nu tilde (SA model).', - 'GROUP': 'BGS_RES', - 'HEADER': 'bgs[nu]', - 'TYPE': 'RESIDUAL'}, - 'BGS_PRESSURE': {'DESCRIPTION': 'BGS residual of the pressure.', - 'GROUP': 'BGS_RES', - 'HEADER': 'bgs[P]', - 'TYPE': 'RESIDUAL'}, - 'BGS_SPECIES_" + std::to_string(iVar': {'DESCRIPTION': 'BGS residual of ' - 'transported species.', - 'GROUP': 'BGS_RES', - 'HEADER': 'bgs[rho*Y_" + ' - 'std::to_string(iVar)+"]', - 'TYPE': 'RESIDUAL'}, - 'BGS_TEMPERATURE': {'DESCRIPTION': 'Block-Gauss-Seidel residual of the ' - 'temperature', - 'GROUP': 'BGS_RES', - 'HEADER': 'bgs[T]', - 'TYPE': 'RESIDUAL'}, - 'BGS_TKE': {'DESCRIPTION': 'BGS residual of kinetic energy (SST model).', - 'GROUP': 'BGS_RES', - 'HEADER': 'bgs[k]', - 'TYPE': 'RESIDUAL'}, - 'BGS_VELOCITY-X': {'DESCRIPTION': 'BGS residual of the velocity x-component.', - 'GROUP': 'BGS_RES', - 'HEADER': 'bgs[U]', - 'TYPE': 'RESIDUAL'}, - 'BGS_VELOCITY-Y': {'DESCRIPTION': 'BGS residual of the velocity y-component.', - 'GROUP': 'BGS_RES', - 'HEADER': 'bgs[V]', - 'TYPE': 'RESIDUAL'}, - 'BGS_VELOCITY-Z': {'DESCRIPTION': 'BGS residual of the velocity z-component.', - 'GROUP': 'BGS_RES', - 'HEADER': 'bgs[W]', - 'TYPE': 'RESIDUAL'}, - 'BUFFET': {'DESCRIPTION': 'Buffet sensor', - 'GROUP': 'AERO_COEFF', - 'HEADER': 'Buffet', - 'TYPE': 'COEFFICIENT'}, - 'CFL_NUMBER': {'DESCRIPTION': 'Current value of the CFL number', - 'GROUP': 'CFL_NUMBER', - 'HEADER': 'CFL number', - 'TYPE': 'DEFAULT'}, - 'CHANGE_IN_AOA': {'DESCRIPTION': 'Last change in Angle of Attack by Fixed CL ' - 'Driver', - 'GROUP': 'FIXED_CL', - 'HEADER': 'Change_in_AOA', - 'TYPE': 'RESIDUAL'}, - 'CL_DRIVER_COMMAND': {'DESCRIPTION': "CL Driver's control command", - 'GROUP': 'FIXED_CL', - 'HEADER': 'CL_Driver_Command', - 'TYPE': 'RESIDUAL'}, - 'COMBO': {'DESCRIPTION': 'Combined obj. function value.', - 'GROUP': 'COMBO', - 'HEADER': 'ComboObj', - 'TYPE': 'COEFFICIENT'}, - 'DEFORM_ITER': {'DESCRIPTION': 'Linear solver iterations for the mesh ' - 'deformation', - 'GROUP': 'DEFORM', - 'HEADER': 'DeformIter', - 'TYPE': 'DEFAULT'}, - 'DEFORM_MAX_VOLUME': {'DESCRIPTION': 'Maximum volume in the mesh', - 'GROUP': 'DEFORM', - 'HEADER': 'MaxVolume', - 'TYPE': 'DEFAULT'}, - 'DEFORM_MIN_VOLUME': {'DESCRIPTION': 'Minimum volume in the mesh', - 'GROUP': 'DEFORM', - 'HEADER': 'MinVolume', - 'TYPE': 'DEFAULT'}, - 'DEFORM_RESIDUAL': {'DESCRIPTION': 'Residual of the linear solver for the ' - 'mesh deformation', - 'GROUP': 'DEFORM', - 'HEADER': 'DeformRes', - 'TYPE': 'DEFAULT'}, - 'DELTA_CL': {'DESCRIPTION': 'Difference between Target CL and current CL', - 'GROUP': 'FIXED_CL', - 'HEADER': 'Delta_CL', - 'TYPE': 'COEFFICIENT'}, - 'DRAG': {'DESCRIPTION': 'Total drag coefficient on all surfaces set with ' - 'MARKER_MONITORING', - 'GROUP': 'AERO_COEFF', - 'HEADER': 'CD', - 'TYPE': 'COEFFICIENT'}, - 'D_ADJOINT_SOLEXTRA': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_ADJOINT_SOLEXTRA', - 'HEADER': 'd[Adjoint_SolExtra]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_AVG_DENSITY': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_FLOW_COEFF', - 'HEADER': 'd[Avg_Density]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_AVG_ENTHALPY': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_FLOW_COEFF', - 'HEADER': 'd[Avg_Enthalpy]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_AVG_NORMALVEL': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_FLOW_COEFF', - 'HEADER': 'd[Avg_NormalVel]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_AVG_TEMPERATURE': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_HEAT', - 'HEADER': 'd[AvgTemp]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_BUFFET': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_AERO_COEFF', - 'HEADER': 'd[Buffet]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_COMBO': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_COMBO', - 'HEADER': 'd[ComboObj]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_DELTA_CL': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_FIXED_CL', - 'HEADER': 'd[Delta_CL]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_DRAG': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_AERO_COEFF', - 'HEADER': 'd[CD]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_EFFICIENCY': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_AERO_COEFF', - 'HEADER': 'd[CEff]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_EQUIVALENT_AREA': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_EQUIVALENT_AREA', - 'HEADER': 'd[CEquiv_Area]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_FIGURE_OF_MERIT': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_ROTATING_FRAME', - 'HEADER': 'd[CMerit]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_FORCE_X': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_AERO_COEFF', - 'HEADER': 'd[CFx]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_FORCE_Y': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_AERO_COEFF', - 'HEADER': 'd[CFy]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_FORCE_Z': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_AERO_COEFF', - 'HEADER': 'd[CFz]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_INVERSE_DESIGN_PRESSURE': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_CP_DIFF', - 'HEADER': 'd[Cp_Diff]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_LIFT': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_AERO_COEFF', - 'HEADER': 'd[CL]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_MAXIMUM_HEATFLUX': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_HEAT', - 'HEADER': 'd[MaxHF]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_MOMENT_X': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_AERO_COEFF', - 'HEADER': 'd[CMx]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_MOMENT_Y': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_AERO_COEFF', - 'HEADER': 'd[CMy]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_MOMENT_Z': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_AERO_COEFF', - 'HEADER': 'd[CMz]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_REFERENCE_GEOMETRY': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_STRUCT_COEFF', - 'HEADER': 'd[RefGeom]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_REFERENCE_NODE': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_STRUCT_COEFF', - 'HEADER': 'd[RefNode]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_SENS_AOA': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_SENSITIVITY', - 'HEADER': 'd[Sens_AoA]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_SENS_GEO': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_SENSITIVITY', - 'HEADER': 'd[Sens_Geo]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_SENS_MACH': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_SENSITIVITY', - 'HEADER': 'd[Sens_Mach]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_SENS_PRESS': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_SENSITIVITY', - 'HEADER': 'd[Sens_Press]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_SENS_PRESS_OUT': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_SENSITIVITY', - 'HEADER': 'd[Sens_Pout]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_SENS_TEMP': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_SENSITIVITY', - 'HEADER': 'd[Sens_Temp]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_SENS_VEL_IN': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_SENSITIVITY', - 'HEADER': 'd[Sens_Vin]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_SIDEFORCE': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_AERO_COEFF', - 'HEADER': 'd[CSF]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_STRESS_PENALTY': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_STRUCT_COEFF', - 'HEADER': 'd[StressPen]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_SURFACE_MACH': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_FLOW_COEFF', - 'HEADER': 'd[Avg_Mach]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_SURFACE_MASSFLOW': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_FLOW_COEFF', - 'HEADER': 'd[Avg_Massflow]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_SURFACE_MOM_DISTORTION': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_FLOW_COEFF', - 'HEADER': 'd[Momentum_Distortion]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_SURFACE_PRESSURE_DROP': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_FLOW_COEFF', - 'HEADER': 'd[Pressure_Drop]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_SURFACE_SECONDARY': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_FLOW_COEFF', - 'HEADER': 'd[Secondary_Strength]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_SURFACE_SECOND_OVER_UNIFORM': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_FLOW_COEFF', - 'HEADER': 'd[Secondary_Over_Uniformity]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_SURFACE_SPECIES_" + std::to_string(iVar': {'DESCRIPTION': 'Derivative ' - 'value', - 'GROUP': 'D_SPECIES_COEFF', - 'HEADER': 'd[Avg_Species_" + ' - 'std::to_string(iVar]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_SURFACE_STATIC_PRESSURE': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_FLOW_COEFF', - 'HEADER': 'd[Avg_Press]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_SURFACE_STATIC_TEMPERATURE': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_FLOW_COEFF', - 'HEADER': 'd[Avg_Temp]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_SURFACE_TOTAL_PRESSURE': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_FLOW_COEFF', - 'HEADER': 'd[Avg_TotalPress]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_SURFACE_TOTAL_TEMPERATURE': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_FLOW_COEFF', - 'HEADER': 'd[Avg_TotalTemp]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_SURFACE_UNIFORMITY': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_FLOW_COEFF', - 'HEADER': 'd[Uniformity]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_THRUST': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_ROTATING_FRAME', - 'HEADER': 'd[CT]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_TOPOL_COMPLIANCE': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_STRUCT_COEFF', - 'HEADER': 'd[TopComp]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_TOPOL_DISCRETENESS': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_STRUCT_COEFF', - 'HEADER': 'd[TopDisc]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_TORQUE': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_ROTATING_FRAME', - 'HEADER': 'd[CQ]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_TOTAL_HEATFLUX': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_HEAT', - 'HEADER': 'd[HF]', - 'TYPE': 'D_COEFFICIENT'}, - 'D_VOLUME_FRACTION': {'DESCRIPTION': 'Derivative value', - 'GROUP': 'D_STRUCT_COEFF', - 'HEADER': 'd[VolFrac]', - 'TYPE': 'D_COEFFICIENT'}, - 'EFFICIENCY': {'DESCRIPTION': 'Total lift-to-drag ratio on all surfaces set ' - 'with MARKER_MONITORING', - 'GROUP': 'AERO_COEFF', - 'HEADER': 'CEff', - 'TYPE': 'COEFFICIENT'}, - 'EQUIVALENT_AREA': {'DESCRIPTION': 'Equivalent area', - 'GROUP': 'EQUIVALENT_AREA', - 'HEADER': 'CEquiv_Area', - 'TYPE': 'COEFFICIENT'}, - 'FIGURE_OF_MERIT': {'DESCRIPTION': 'Thrust over torque', - 'GROUP': 'ROTATING_FRAME', - 'HEADER': 'CMerit', - 'TYPE': 'COEFFICIENT'}, - 'FORCE_X': {'DESCRIPTION': 'Total force x-component on all surfaces set with ' - 'MARKER_MONITORING', - 'GROUP': 'AERO_COEFF', - 'HEADER': 'CFx', - 'TYPE': 'COEFFICIENT'}, - 'FORCE_Y': {'DESCRIPTION': 'Total force y-component on all surfaces set with ' - 'MARKER_MONITORING', - 'GROUP': 'AERO_COEFF', - 'HEADER': 'CFy', - 'TYPE': 'COEFFICIENT'}, - 'FORCE_Z': {'DESCRIPTION': 'Total force z-component on all surfaces set with ' - 'MARKER_MONITORING', - 'GROUP': 'AERO_COEFF', - 'HEADER': 'CFz', - 'TYPE': 'COEFFICIENT'}, - 'INVERSE_DESIGN_PRESSURE': {'DESCRIPTION': 'Cp difference for inverse design', - 'GROUP': 'CP_DIFF', - 'HEADER': 'Cp_Diff', - 'TYPE': 'COEFFICIENT'}, - 'LIFT': {'DESCRIPTION': 'Total lift coefficient on all surfaces set with ' - 'MARKER_MONITORING', - 'GROUP': 'AERO_COEFF', - 'HEADER': 'CL', - 'TYPE': 'COEFFICIENT'}, - 'LINSOL_ITER': {'DESCRIPTION': 'Number of iterations of the linear solver.', - 'GROUP': 'LINSOL', - 'HEADER': 'LinSolIter', - 'TYPE': 'DEFAULT'}, - 'LINSOL_ITER_SPECIES': {'DESCRIPTION': 'Number of iterations of the linear ' - 'solver for species solver.', - 'GROUP': 'LINSOL', - 'HEADER': 'LinSolIterSpecies', - 'TYPE': 'DEFAULT'}, - 'LINSOL_ITER_TURB': {'DESCRIPTION': 'Number of iterations of the linear ' - 'solver for turbulence.', - 'GROUP': 'LINSOL', - 'HEADER': 'LinSolIterTurb', - 'TYPE': 'DEFAULT'}, - 'LINSOL_RESIDUAL': {'DESCRIPTION': 'Residual of the linear solver.', - 'GROUP': 'LINSOL', - 'HEADER': 'LinSolRes', - 'TYPE': 'DEFAULT'}, - 'LINSOL_RESIDUAL_SPECIES': {'DESCRIPTION': 'Residual of the linear solver for ' - 'species solver.', - 'GROUP': 'LINSOL', - 'HEADER': 'LinSolResSpecies', - 'TYPE': 'DEFAULT'}, - 'LINSOL_RESIDUAL_TURB': {'DESCRIPTION': 'Residual of the linear solver for ' - 'turbulence.', - 'GROUP': 'LINSOL', - 'HEADER': 'LinSolResTurb', - 'TYPE': 'DEFAULT'}, - 'LOAD_INCREMENT': {'DESCRIPTION': 'LOAD_INCREMENT', - 'GROUP': 'Percent of total load (incremental', - 'HEADER': 'Load[%]', - 'TYPE': 'DEFAULT'}, - 'LOAD_RAMP': {'DESCRIPTION': 'LOAD_RAMP', - 'GROUP': 'Fraction of total load (ramped', - 'HEADER': 'Load_Ramp', - 'TYPE': 'DEFAULT'}, - 'MAXIMUM_HEATFLUX': {'DESCRIPTION': 'Maximum heatflux on all surfaces defined ' - 'in MARKER_MONITORING', - 'GROUP': 'HEAT', - 'HEADER': 'MaxHF', - 'TYPE': 'COEFFICIENT'}, - 'MAX_ADJ_DENSITY': {'DESCRIPTION': 'Maximum residual of the adjoint density.', - 'GROUP': 'MAX_RES', - 'HEADER': 'max[A_Rho]', - 'TYPE': 'RESIDUAL'}, - 'MAX_ADJ_DISSIPATION': {'DESCRIPTION': 'Maximum residual of the adjoint ' - 'dissipation.', - 'GROUP': 'MAX_RES', - 'HEADER': 'max[A_w]', - 'TYPE': 'RESIDUAL'}, - 'MAX_ADJ_ENERGY': {'DESCRIPTION': 'Maximum residual of the adjoint energy.', - 'GROUP': 'MAX_RES', - 'HEADER': 'max[A_E]', - 'TYPE': 'RESIDUAL'}, - 'MAX_ADJ_MOMENTUM-X': {'DESCRIPTION': 'Maximum residual of the adjoint ' - 'momentum x-component', - 'GROUP': 'MAX_RES', - 'HEADER': 'max[A_RhoU]', - 'TYPE': 'RESIDUAL'}, - 'MAX_ADJ_MOMENTUM-Y': {'DESCRIPTION': 'Maximum residual of the adjoint ' - 'momentum y-component', - 'GROUP': 'MAX_RES', - 'HEADER': 'max[A_RhoV]', - 'TYPE': 'RESIDUAL'}, - 'MAX_ADJ_MOMENTUM-Z': {'DESCRIPTION': 'Maximum residual of the adjoint ' - 'momentum z-component', - 'GROUP': 'MAX_RES', - 'HEADER': 'max[A_RhoW]', - 'TYPE': 'RESIDUAL'}, - 'MAX_ADJ_NU_TILDE': {'DESCRIPTION': 'Maximum residual of the adjoint nu ' - 'tilde.', - 'GROUP': 'MAX_RES', - 'HEADER': 'max[A_nu]', - 'TYPE': 'RESIDUAL'}, - 'MAX_ADJ_PRESSURE': {'DESCRIPTION': 'Maximum residual of the adjoint ' - 'Pressure.', - 'GROUP': 'MAX_RES', - 'HEADER': 'max[A_Rho]', - 'TYPE': 'RESIDUAL'}, - 'MAX_ADJ_SPECIES_" + std::to_string(iVar': {'DESCRIPTION': 'Maximum residual ' - 'of the adjoint ' - 'transported ' - 'species.', - 'GROUP': 'MAX_RES', - 'HEADER': 'max[A_rho*Y_" + ' - 'std::to_string(iVar) + ' - '"]', - 'TYPE': 'RESIDUAL'}, - 'MAX_ADJ_TEMPERATURE': {'DESCRIPTION': 'Maximum residual of the temperature.', - 'GROUP': 'MAX_RES', - 'HEADER': 'max[A_T]', - 'TYPE': 'RESIDUAL'}, - 'MAX_ADJ_TKE': {'DESCRIPTION': 'Maximum residual of the adjoint kinetic ' - 'energy.', - 'GROUP': 'MAX_RES', - 'HEADER': 'max[A_k]', - 'TYPE': 'RESIDUAL'}, - 'MAX_ADJ_VELOCITY-X': {'DESCRIPTION': 'Maximum residual of the adjoint ' - 'Velocity x-component', - 'GROUP': 'MAX_RES', - 'HEADER': 'max[A_RhoU]', - 'TYPE': 'RESIDUAL'}, - 'MAX_ADJ_VELOCITY-Y': {'DESCRIPTION': 'Maximum residual of the adjoint ' - 'Velocity y-component', - 'GROUP': 'MAX_RES', - 'HEADER': 'max[A_RhoV]', - 'TYPE': 'RESIDUAL'}, - 'MAX_ADJ_VELOCITY-Z': {'DESCRIPTION': 'Maximum residual of the adjoint ' - 'Velocity z-component', - 'GROUP': 'MAX_RES', - 'HEADER': 'max[A_RhoW]', - 'TYPE': 'RESIDUAL'}, - 'MAX_CFL': {'DESCRIPTION': 'Current maximum of the local CFL numbers', - 'GROUP': 'CFL_NUMBER', - 'HEADER': 'Max CFL', - 'TYPE': 'DEFAULT'}, - 'MAX_DELTA_TIME': {'DESCRIPTION': 'Current maximum local time step', - 'GROUP': 'CFL_NUMBER', - 'HEADER': 'Max DT', - 'TYPE': 'DEFAULT'}, - 'MAX_DENSITY': {'DESCRIPTION': 'Maximum square residual of the density.', - 'GROUP': 'MAX_RES', - 'HEADER': 'max[Rho]', - 'TYPE': 'RESIDUAL'}, - 'MAX_DISSIPATION': {'DESCRIPTION': 'Maximum residual of dissipation (SST ' - 'model).', - 'GROUP': 'MAX_RES', - 'HEADER': 'max[w]', - 'TYPE': 'RESIDUAL'}, - 'MAX_ENERGY': {'DESCRIPTION': 'Maximum residual of the energy.', - 'GROUP': 'MAX_RES', - 'HEADER': 'max[RhoE]', - 'TYPE': 'RESIDUAL'}, - 'MAX_MOMENTUM-X': {'DESCRIPTION': 'Maximum square residual of the momentum ' - 'x-component.', - 'GROUP': 'MAX_RES', - 'HEADER': 'max[RhoU]', - 'TYPE': 'RESIDUAL'}, - 'MAX_MOMENTUM-Y': {'DESCRIPTION': 'Maximum square residual of the momentum ' - 'y-component.', - 'GROUP': 'MAX_RES', - 'HEADER': 'max[RhoV]', - 'TYPE': 'RESIDUAL'}, - 'MAX_NU_TILDE': {'DESCRIPTION': 'Maximum residual of nu tilde (SA model).', - 'GROUP': 'MAX_RES', - 'HEADER': 'max[nu]', - 'TYPE': 'RESIDUAL'}, - 'MAX_PRESSURE': {'DESCRIPTION': 'Maximum residual of the pressure.', - 'GROUP': 'MAX_RES', - 'HEADER': 'max[P]', - 'TYPE': 'RESIDUAL'}, - 'MAX_SPECIES_" + std::to_string(iVar': {'DESCRIPTION': 'Maximum residual of ' - 'transported species.', - 'GROUP': 'MAX_RES', - 'HEADER': 'max[rho*Y_" + ' - 'std::to_string(iVar)+"]', - 'TYPE': 'RESIDUAL'}, - 'MAX_TEMPERATURE': {'DESCRIPTION': 'Maximum residual of the temperature', - 'GROUP': 'MAX_RES', - 'HEADER': 'max[T]', - 'TYPE': 'RESIDUAL'}, - 'MAX_TKE': {'DESCRIPTION': 'Maximum residual of kinetic energy (SST model).', - 'GROUP': 'MAX_RES', - 'HEADER': 'max[k]', - 'TYPE': 'RESIDUAL'}, - 'MAX_VELOCITY-X': {'DESCRIPTION': 'Maximum residual of the velocity ' - 'x-component.', - 'GROUP': 'MAX_RES', - 'HEADER': 'max[U]', - 'TYPE': 'RESIDUAL'}, - 'MAX_VELOCITY-Y': {'DESCRIPTION': 'Maximum residual of the velocity ' - 'y-component.', - 'GROUP': 'MAX_RES', - 'HEADER': 'max[V]', - 'TYPE': 'RESIDUAL'}, - 'MAX_VELOCITY-Z': {'DESCRIPTION': 'Maximum residual of the velocity ' - 'z-component.', - 'GROUP': 'MAX_RES', - 'HEADER': 'max[W]', - 'TYPE': 'RESIDUAL'}, - 'MIN_CFL': {'DESCRIPTION': 'Current minimum of the local CFL numbers', - 'GROUP': 'CFL_NUMBER', - 'HEADER': 'Min CFL', - 'TYPE': 'DEFAULT'}, - 'MIN_DELTA_TIME': {'DESCRIPTION': 'Current minimum local time step', - 'GROUP': 'CFL_NUMBER', - 'HEADER': 'Min DT', - 'TYPE': 'DEFAULT'}, - 'MOMENT_X': {'DESCRIPTION': 'Total momentum x-component on all surfaces set ' - 'with MARKER_MONITORING', - 'GROUP': 'AERO_COEFF', - 'HEADER': 'CMx', - 'TYPE': 'COEFFICIENT'}, - 'MOMENT_Y': {'DESCRIPTION': 'Total momentum y-component on all surfaces set ' - 'with MARKER_MONITORING', - 'GROUP': 'AERO_COEFF', - 'HEADER': 'CMy', - 'TYPE': 'COEFFICIENT'}, - 'MOMENT_Z': {'DESCRIPTION': 'Total momentum z-component on all surfaces set ' - 'with MARKER_MONITORING', - 'GROUP': 'AERO_COEFF', - 'HEADER': 'CMz', - 'TYPE': 'COEFFICIENT'}, - 'PREV_AOA': {'DESCRIPTION': 'Angle of Attack at the previous iteration of the ' - 'Fixed CL driver', - 'GROUP': 'FIXED_CL', - 'HEADER': 'Previous_AOA', - 'TYPE': 'DEFAULT'}, - 'REFERENCE_GEOMETRY': {'DESCRIPTION': 'L2 norm of difference wrt reference ' - 'geometry', - 'GROUP': 'STRUCT_COEFF', - 'HEADER': 'RefGeom', - 'TYPE': 'COEFFICIENT'}, - 'REFERENCE_NODE': {'DESCRIPTION': 'Distance to reference node', - 'GROUP': 'STRUCT_COEFF', - 'HEADER': 'RefNode', - 'TYPE': 'COEFFICIENT'}, - 'RMS_ADJ_DENSITY': {'DESCRIPTION': 'Root-mean square residual of the adjoint ' - 'density.', - 'GROUP': 'RMS_RES', - 'HEADER': 'rms[A_Rho]', - 'TYPE': 'RESIDUAL'}, - 'RMS_ADJ_DISSIPATION': {'DESCRIPTION': 'Root-mean square residual of the ' - 'adjoint dissipation.', - 'GROUP': 'RMS_RES', - 'HEADER': 'rms[A_w]', - 'TYPE': 'RESIDUAL'}, - 'RMS_ADJ_ENERGY': {'DESCRIPTION': 'Root-mean square residual of the adjoint ' - 'energy.', - 'GROUP': 'RMS_RES', - 'HEADER': 'rms[A_E]', - 'TYPE': 'RESIDUAL'}, - 'RMS_ADJ_MOMENTUM-X': {'DESCRIPTION': 'Root-mean square residual of the ' - 'adjoint momentum x-component.', - 'GROUP': 'RMS_RES', - 'HEADER': 'rms[A_RhoU]', - 'TYPE': 'RESIDUAL'}, - 'RMS_ADJ_MOMENTUM-Y': {'DESCRIPTION': 'Root-mean square residual of the ' - 'adjoint momentum y-component.', - 'GROUP': 'RMS_RES', - 'HEADER': 'rms[A_RhoV]', - 'TYPE': 'RESIDUAL'}, - 'RMS_ADJ_MOMENTUM-Z': {'DESCRIPTION': 'Root-mean square residual of the ' - 'adjoint momentum z-component.', - 'GROUP': 'RMS_RES', - 'HEADER': 'rms[A_RhoW]', - 'TYPE': 'RESIDUAL'}, - 'RMS_ADJ_NU_TILDE': {'DESCRIPTION': 'Root-mean square residual of the adjoint ' - 'nu tilde.', - 'GROUP': 'RMS_RES', - 'HEADER': 'rms[A_nu]', - 'TYPE': 'RESIDUAL'}, - 'RMS_ADJ_PRESSURE': {'DESCRIPTION': 'Root-mean square residual of the adjoint ' - 'Pressure.', - 'GROUP': 'RMS_RES', - 'HEADER': 'rms[A_P]', - 'TYPE': 'RESIDUAL'}, - 'RMS_ADJ_RAD_ENERGY': {'DESCRIPTION': 'Root-mean square residual of the P1 ' - 'radiative energy.', - 'GROUP': 'RMS_RES', - 'HEADER': 'rms[A_P1]', - 'TYPE': 'RESIDUAL'}, - 'RMS_ADJ_SPECIES_" + std::to_string(iVar': {'DESCRIPTION': 'Root-mean square ' - 'residual of the ' - 'adjoint ' - 'transported ' - 'species.', - 'GROUP': 'RMS_RES', - 'HEADER': 'rms[A_rho*Y_" + ' - 'std::to_string(iVar) + ' - '"]', - 'TYPE': 'RESIDUAL'}, - 'RMS_ADJ_TEMPERATURE': {'DESCRIPTION': 'Root-mean square residual of the ' - 'adjoint temperature.', - 'GROUP': 'RMS_RES', - 'HEADER': 'rms[A_T]', - 'TYPE': 'RESIDUAL'}, - 'RMS_ADJ_TKE': {'DESCRIPTION': 'Root-mean square residual of the adjoint ' - 'kinetic energy.', - 'GROUP': 'RMS_RES', - 'HEADER': 'rms[A_k]', - 'TYPE': 'RESIDUAL'}, - 'RMS_ADJ_VELOCITY-X': {'DESCRIPTION': 'Root-mean square residual of the ' - 'adjoint Velocity x-component.', - 'GROUP': 'RMS_RES', - 'HEADER': 'rms[A_U]', - 'TYPE': 'RESIDUAL'}, - 'RMS_ADJ_VELOCITY-Y': {'DESCRIPTION': 'Root-mean square residual of the ' - 'adjoint Velocity y-component.', - 'GROUP': 'RMS_RES', - 'HEADER': 'rms[A_V]', - 'TYPE': 'RESIDUAL'}, - 'RMS_ADJ_VELOCITY-Z': {'DESCRIPTION': 'Root-mean square residual of the ' - 'adjoint Velocity z-component.', - 'GROUP': 'RMS_RES', - 'HEADER': 'rms[A_W]', - 'TYPE': 'RESIDUAL'}, - 'RMS_DENSITY': {'DESCRIPTION': 'Root-mean square residual of the density.', - 'GROUP': 'RMS_RES', - 'HEADER': 'rms[Rho]', - 'TYPE': 'RESIDUAL'}, - 'RMS_DISP_X': {'DESCRIPTION': 'Residual of X displacement', - 'GROUP': 'RMS_RES', - 'HEADER': 'rms[DispX]', - 'TYPE': 'RESIDUAL'}, - 'RMS_DISP_Y': {'DESCRIPTION': 'Residual of Y displacement', - 'GROUP': 'RMS_RES', - 'HEADER': 'rms[DispY]', - 'TYPE': 'RESIDUAL'}, - 'RMS_DISP_Z': {'DESCRIPTION': 'Residual of Z displacement', - 'GROUP': 'RMS_RES', - 'HEADER': 'rms[DispZ]', - 'TYPE': 'RESIDUAL'}, - 'RMS_DISSIPATION': {'DESCRIPTION': 'Root-mean square residual of dissipation ' - '(SST model).', - 'GROUP': 'RMS_RES', - 'HEADER': 'rms[w]', - 'TYPE': 'RESIDUAL'}, - 'RMS_ENERGY': {'DESCRIPTION': 'Root-mean square residual of the energy.', - 'GROUP': 'RMS_RES', - 'HEADER': 'rms[RhoE]', - 'TYPE': 'RESIDUAL'}, - 'RMS_ETOL': {'DESCRIPTION': 'Norm of energy/work increment', - 'GROUP': 'RMS_RES', - 'HEADER': 'rms[E]', - 'TYPE': 'RESIDUAL'}, - 'RMS_MOMENTUM-X': {'DESCRIPTION': 'Root-mean square residual of the momentum ' - 'x-component.', - 'GROUP': 'RMS_RES', - 'HEADER': 'rms[RhoU]', - 'TYPE': 'RESIDUAL'}, - 'RMS_MOMENTUM-Y': {'DESCRIPTION': 'Root-mean square residual of the momentum ' - 'y-component.', - 'GROUP': 'RMS_RES', - 'HEADER': 'rms[RhoV]', - 'TYPE': 'RESIDUAL'}, - 'RMS_NU_TILDE': {'DESCRIPTION': 'Root-mean square residual of nu tilde (SA ' - 'model).', - 'GROUP': 'RMS_RES', - 'HEADER': 'rms[nu]', - 'TYPE': 'RESIDUAL'}, - 'RMS_PRESSURE': {'DESCRIPTION': 'Root-mean square residual of the pressure.', - 'GROUP': 'RMS_RES', - 'HEADER': 'rms[P]', - 'TYPE': 'RESIDUAL'}, - 'RMS_RTOL': {'DESCRIPTION': 'Norm of residual', - 'GROUP': 'RMS_RES', - 'HEADER': 'rms[R]', - 'TYPE': 'RESIDUAL'}, - 'RMS_SPECIES_" + std::to_string(iVar': {'DESCRIPTION': 'Root-mean square ' - 'residual of ' - 'transported species.', - 'GROUP': 'RMS_RES', - 'HEADER': 'rms[rho*Y_" + ' - 'std::to_string(iVar)+"]', - 'TYPE': 'RESIDUAL'}, - 'RMS_TEMPERATURE': {'DESCRIPTION': 'Root mean square residual of the ' - 'temperature', - 'GROUP': 'RMS_RES', - 'HEADER': 'rms[T]', - 'TYPE': 'RESIDUAL'}, - 'RMS_TKE': {'DESCRIPTION': 'Root-mean square residual of kinetic energy (SST ' - 'model).', - 'GROUP': 'RMS_RES', - 'HEADER': 'rms[k]', - 'TYPE': 'RESIDUAL'}, - 'RMS_UTOL': {'DESCRIPTION': 'Norm of displacement increment', - 'GROUP': 'RMS_RES', - 'HEADER': 'rms[U]', - 'TYPE': 'RESIDUAL'}, - 'RMS_VELOCITY-X': {'DESCRIPTION': 'Root-mean square residual of the velocity ' - 'x-component.', - 'GROUP': 'RMS_RES', - 'HEADER': 'rms[U]', - 'TYPE': 'RESIDUAL'}, - 'RMS_VELOCITY-Y': {'DESCRIPTION': 'Root-mean square residual of the velocity ' - 'y-component.', - 'GROUP': 'RMS_RES', - 'HEADER': 'rms[V]', - 'TYPE': 'RESIDUAL'}, - 'SENS_AOA': {'DESCRIPTION': 'Sensitivity of the objective function with ' - 'respect to the angle of attack (only for ' - 'compressible solver).', - 'GROUP': 'SENSITIVITY', - 'HEADER': 'Sens_AoA', - 'TYPE': 'COEFFICIENT'}, - 'SENS_E': {'DESCRIPTION': 'd Objective / d Elasticity modulus', - 'GROUP': 'SENSITIVITY', - 'HEADER': 'Sens[E]', - 'TYPE': 'DEFAULT'}, - 'SENS_GEO': {'DESCRIPTION': 'Sum of the geometrical sensitivities on all ' - 'markers set in MARKER_MONITORING.', - 'GROUP': 'SENSITIVITY', - 'HEADER': 'Sens_Geo', - 'TYPE': 'COEFFICIENT'}, - 'SENS_MACH': {'DESCRIPTION': 'Sensitivity of the objective function with ' - 'respect to the Mach number (only of ' - 'compressible solver).', - 'GROUP': 'SENSITIVITY', - 'HEADER': 'Sens_Mach', - 'TYPE': 'COEFFICIENT'}, - 'SENS_NU': {'DESCRIPTION': 'd Objective / d Poisson ratio', - 'GROUP': 'SENSITIVITY', - 'HEADER': 'Sens[Nu]', - 'TYPE': 'DEFAULT'}, - 'SENS_PRESS': {'DESCRIPTION': 'Sensitivity of the objective function with ' - 'respect to the far-field pressure.', - 'GROUP': 'SENSITIVITY', - 'HEADER': 'Sens_Press', - 'TYPE': 'COEFFICIENT'}, - 'SENS_PRESS_OUT': {'DESCRIPTION': 'Sensitivity of the objective function with ' - 'respect to the outlet pressure.', - 'GROUP': 'SENSITIVITY', - 'HEADER': 'Sens_Pout', - 'TYPE': 'COEFFICIENT'}, - 'SENS_TEMP': {'DESCRIPTION': 'Sensitivity of the objective function with ' - 'respect to the far-field temperature.', - 'GROUP': 'SENSITIVITY', - 'HEADER': 'Sens_Temp', - 'TYPE': 'COEFFICIENT'}, - 'SENS_VEL_IN': {'DESCRIPTION': 'Sensitivity of the objective function with ' - 'respect to the inlet velocity.', - 'GROUP': 'SENSITIVITY', - 'HEADER': 'Sens_Vin', - 'TYPE': 'COEFFICIENT'}, - 'SIDEFORCE': {'DESCRIPTION': 'Total sideforce coefficient on all surfaces set ' - 'with MARKER_MONITORING', - 'GROUP': 'AERO_COEFF', - 'HEADER': 'CSF', - 'TYPE': 'COEFFICIENT'}, - 'STREAMWISE_DP': {'DESCRIPTION': 'Pressure drop in streamwise periodic flow', - 'GROUP': 'STREAMWISE_PERIODIC', - 'HEADER': 'SWDeltaP', - 'TYPE': 'DEFAULT'}, - 'STREAMWISE_HEAT': {'DESCRIPTION': 'Integrated heat for streamwise periodic ' - 'flow', - 'GROUP': 'STREAMWISE_PERIODIC', - 'HEADER': 'SWHeat', - 'TYPE': 'DEFAULT'}, - 'STREAMWISE_MASSFLOW': {'DESCRIPTION': 'Massflow in streamwise periodic flow', - 'GROUP': 'STREAMWISE_PERIODIC', - 'HEADER': 'SWMassflow', - 'TYPE': 'DEFAULT'}, - 'STRESS_PENALTY': {'DESCRIPTION': 'Aggregate stress penalty', - 'GROUP': 'STRUCT_COEFF', - 'HEADER': 'StressPen', - 'TYPE': 'COEFFICIENT'}, - 'SURFACE_MACH': {'DESCRIPTION': 'Total average mach number on all markers set ' - 'in MARKER_ANALYZE', - 'GROUP': 'FLOW_COEFF', - 'HEADER': 'Avg_Mach', - 'TYPE': 'COEFFICIENT'}, - 'SURFACE_MASSFLOW': {'DESCRIPTION': 'Total average mass flow on all markers ' - 'set in MARKER_ANALYZE', - 'GROUP': 'FLOW_COEFF', - 'HEADER': 'Avg_Massflow', - 'TYPE': 'COEFFICIENT'}, - 'SURFACE_MOM_DISTORTION': {'DESCRIPTION': 'Total momentum distortion on all ' - 'markers set in MARKER_ANALYZE', - 'GROUP': 'FLOW_COEFF', - 'HEADER': 'Momentum_Distortion', - 'TYPE': 'COEFFICIENT'}, - 'SURFACE_PRESSURE_DROP': {'DESCRIPTION': 'Total pressure drop on all markers ' - 'set in MARKER_ANALYZE', - 'GROUP': 'FLOW_COEFF', - 'HEADER': 'Pressure_Drop', - 'TYPE': 'COEFFICIENT'}, - 'SURFACE_SECONDARY': {'DESCRIPTION': 'Total secondary strength on all markers ' - 'set in MARKER_ANALYZE', - 'GROUP': 'FLOW_COEFF', - 'HEADER': 'Secondary_Strength', - 'TYPE': 'COEFFICIENT'}, - 'SURFACE_SECOND_OVER_UNIFORM': {'DESCRIPTION': 'Total secondary over ' - 'uniformity on all markers set ' - 'in MARKER_ANALYZE', - 'GROUP': 'FLOW_COEFF', - 'HEADER': 'Secondary_Over_Uniformity', - 'TYPE': 'COEFFICIENT'}, - 'SURFACE_SPECIES_" + std::to_string(iVar': {'DESCRIPTION': 'Total average ' - 'species " + ' - 'std::to_string(iVar) ' - '+ " on all ' - 'markers set in ' - 'MARKER_ANALYZE', - 'GROUP': 'SPECIES_COEFF', - 'HEADER': 'Avg_Species_" + ' - 'std::to_string(iVar', - 'TYPE': 'COEFFICIENT'}, - 'SURFACE_SPECIES_VARIANCE': {'DESCRIPTION': 'Total species variance', - 'GROUP': 'SPECIES_COEFF', - 'HEADER': 'Species_Variance', - 'TYPE': 'DEFAULT'}, - 'SURFACE_STATIC_PRESSURE': {'DESCRIPTION': 'Total average pressure on all ' - 'markers set in MARKER_ANALYZE', - 'GROUP': 'FLOW_COEFF', - 'HEADER': 'Avg_Press', - 'TYPE': 'COEFFICIENT'}, - 'SURFACE_STATIC_TEMPERATURE': {'DESCRIPTION': 'Total average temperature on ' - 'all markers set in ' - 'MARKER_ANALYZE', - 'GROUP': 'FLOW_COEFF', - 'HEADER': 'Avg_Temp', - 'TYPE': 'COEFFICIENT'}, - 'SURFACE_TOTAL_PRESSURE': {'DESCRIPTION': 'Total average total pressure on ' - 'all markers set in MARKER_ANALYZE', - 'GROUP': 'FLOW_COEFF', - 'HEADER': 'Avg_TotalPress', - 'TYPE': 'COEFFICIENT'}, - 'SURFACE_TOTAL_TEMPERATURE': {'DESCRIPTION': 'Total average total temperature ' - 'all markers set in ' - 'MARKER_ANALYZE', - 'GROUP': 'FLOW_COEFF', - 'HEADER': 'Avg_TotalTemp', - 'TYPE': 'COEFFICIENT'}, - 'SURFACE_UNIFORMITY': {'DESCRIPTION': 'Total flow uniformity on all markers ' - 'set in MARKER_ANALYZE', - 'GROUP': 'FLOW_COEFF', - 'HEADER': 'Uniformity', - 'TYPE': 'COEFFICIENT'}, - 'TAVG_ADJOINT_SOLEXTRA': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_ADJOINT_SOLEXTRA', - 'HEADER': 'tavg[Adjoint_SolExtra]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_AVG_DENSITY': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_FLOW_COEFF', - 'HEADER': 'tavg[Avg_Density]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_AVG_ENTHALPY': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_FLOW_COEFF', - 'HEADER': 'tavg[Avg_Enthalpy]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_AVG_NORMALVEL': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_FLOW_COEFF', - 'HEADER': 'tavg[Avg_NormalVel]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_AVG_TEMPERATURE': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_HEAT', - 'HEADER': 'tavg[AvgTemp]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_BUFFET': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_AERO_COEFF', - 'HEADER': 'tavg[Buffet]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_COMBO': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_COMBO', - 'HEADER': 'tavg[ComboObj]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_DELTA_CL': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_FIXED_CL', - 'HEADER': 'tavg[Delta_CL]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_DRAG': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_AERO_COEFF', - 'HEADER': 'tavg[CD]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_D_ADJOINT_SOLEXTRA': {'DESCRIPTION': 'weighted time average derivative ' - 'value', - 'GROUP': 'TAVG_D_ADJOINT_SOLEXTRA', - 'HEADER': 'dtavg[Adjoint_SolExtra]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_AVG_DENSITY': {'DESCRIPTION': 'weighted time average derivative value', - 'GROUP': 'TAVG_D_FLOW_COEFF', - 'HEADER': 'dtavg[Avg_Density]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_AVG_ENTHALPY': {'DESCRIPTION': 'weighted time average derivative ' - 'value', - 'GROUP': 'TAVG_D_FLOW_COEFF', - 'HEADER': 'dtavg[Avg_Enthalpy]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_AVG_NORMALVEL': {'DESCRIPTION': 'weighted time average derivative ' - 'value', - 'GROUP': 'TAVG_D_FLOW_COEFF', - 'HEADER': 'dtavg[Avg_NormalVel]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_AVG_TEMPERATURE': {'DESCRIPTION': 'weighted time average derivative ' - 'value', - 'GROUP': 'TAVG_D_HEAT', - 'HEADER': 'dtavg[AvgTemp]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_BUFFET': {'DESCRIPTION': 'weighted time average derivative value', - 'GROUP': 'TAVG_D_AERO_COEFF', - 'HEADER': 'dtavg[Buffet]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_COMBO': {'DESCRIPTION': 'weighted time average derivative value', - 'GROUP': 'TAVG_D_COMBO', - 'HEADER': 'dtavg[ComboObj]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_DELTA_CL': {'DESCRIPTION': 'weighted time average derivative value', - 'GROUP': 'TAVG_D_FIXED_CL', - 'HEADER': 'dtavg[Delta_CL]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_DRAG': {'DESCRIPTION': 'weighted time average derivative value', - 'GROUP': 'TAVG_D_AERO_COEFF', - 'HEADER': 'dtavg[CD]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_EFFICIENCY': {'DESCRIPTION': 'weighted time average derivative value', - 'GROUP': 'TAVG_D_AERO_COEFF', - 'HEADER': 'dtavg[CEff]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_EQUIVALENT_AREA': {'DESCRIPTION': 'weighted time average derivative ' - 'value', - 'GROUP': 'TAVG_D_EQUIVALENT_AREA', - 'HEADER': 'dtavg[CEquiv_Area]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_FIGURE_OF_MERIT': {'DESCRIPTION': 'weighted time average derivative ' - 'value', - 'GROUP': 'TAVG_D_ROTATING_FRAME', - 'HEADER': 'dtavg[CMerit]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_FORCE_X': {'DESCRIPTION': 'weighted time average derivative value', - 'GROUP': 'TAVG_D_AERO_COEFF', - 'HEADER': 'dtavg[CFx]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_FORCE_Y': {'DESCRIPTION': 'weighted time average derivative value', - 'GROUP': 'TAVG_D_AERO_COEFF', - 'HEADER': 'dtavg[CFy]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_FORCE_Z': {'DESCRIPTION': 'weighted time average derivative value', - 'GROUP': 'TAVG_D_AERO_COEFF', - 'HEADER': 'dtavg[CFz]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_INVERSE_DESIGN_PRESSURE': {'DESCRIPTION': 'weighted time average ' - 'derivative value', - 'GROUP': 'TAVG_D_CP_DIFF', - 'HEADER': 'dtavg[Cp_Diff]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_LIFT': {'DESCRIPTION': 'weighted time average derivative value', - 'GROUP': 'TAVG_D_AERO_COEFF', - 'HEADER': 'dtavg[CL]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_MAXIMUM_HEATFLUX': {'DESCRIPTION': 'weighted time average derivative ' - 'value', - 'GROUP': 'TAVG_D_HEAT', - 'HEADER': 'dtavg[MaxHF]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_MOMENT_X': {'DESCRIPTION': 'weighted time average derivative value', - 'GROUP': 'TAVG_D_AERO_COEFF', - 'HEADER': 'dtavg[CMx]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_MOMENT_Y': {'DESCRIPTION': 'weighted time average derivative value', - 'GROUP': 'TAVG_D_AERO_COEFF', - 'HEADER': 'dtavg[CMy]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_MOMENT_Z': {'DESCRIPTION': 'weighted time average derivative value', - 'GROUP': 'TAVG_D_AERO_COEFF', - 'HEADER': 'dtavg[CMz]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_REFERENCE_GEOMETRY': {'DESCRIPTION': 'weighted time average ' - 'derivative value', - 'GROUP': 'TAVG_D_STRUCT_COEFF', - 'HEADER': 'dtavg[RefGeom]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_REFERENCE_NODE': {'DESCRIPTION': 'weighted time average derivative ' - 'value', - 'GROUP': 'TAVG_D_STRUCT_COEFF', - 'HEADER': 'dtavg[RefNode]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_SENS_AOA': {'DESCRIPTION': 'weighted time average derivative value', - 'GROUP': 'TAVG_D_SENSITIVITY', - 'HEADER': 'dtavg[Sens_AoA]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_SENS_GEO': {'DESCRIPTION': 'weighted time average derivative value', - 'GROUP': 'TAVG_D_SENSITIVITY', - 'HEADER': 'dtavg[Sens_Geo]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_SENS_MACH': {'DESCRIPTION': 'weighted time average derivative value', - 'GROUP': 'TAVG_D_SENSITIVITY', - 'HEADER': 'dtavg[Sens_Mach]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_SENS_PRESS': {'DESCRIPTION': 'weighted time average derivative value', - 'GROUP': 'TAVG_D_SENSITIVITY', - 'HEADER': 'dtavg[Sens_Press]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_SENS_PRESS_OUT': {'DESCRIPTION': 'weighted time average derivative ' - 'value', - 'GROUP': 'TAVG_D_SENSITIVITY', - 'HEADER': 'dtavg[Sens_Pout]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_SENS_TEMP': {'DESCRIPTION': 'weighted time average derivative value', - 'GROUP': 'TAVG_D_SENSITIVITY', - 'HEADER': 'dtavg[Sens_Temp]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_SENS_VEL_IN': {'DESCRIPTION': 'weighted time average derivative value', - 'GROUP': 'TAVG_D_SENSITIVITY', - 'HEADER': 'dtavg[Sens_Vin]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_SIDEFORCE': {'DESCRIPTION': 'weighted time average derivative value', - 'GROUP': 'TAVG_D_AERO_COEFF', - 'HEADER': 'dtavg[CSF]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_STRESS_PENALTY': {'DESCRIPTION': 'weighted time average derivative ' - 'value', - 'GROUP': 'TAVG_D_STRUCT_COEFF', - 'HEADER': 'dtavg[StressPen]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_SURFACE_MACH': {'DESCRIPTION': 'weighted time average derivative ' - 'value', - 'GROUP': 'TAVG_D_FLOW_COEFF', - 'HEADER': 'dtavg[Avg_Mach]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_SURFACE_MASSFLOW': {'DESCRIPTION': 'weighted time average derivative ' - 'value', - 'GROUP': 'TAVG_D_FLOW_COEFF', - 'HEADER': 'dtavg[Avg_Massflow]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_SURFACE_MOM_DISTORTION': {'DESCRIPTION': 'weighted time average ' - 'derivative value', - 'GROUP': 'TAVG_D_FLOW_COEFF', - 'HEADER': 'dtavg[Momentum_Distortion]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_SURFACE_PRESSURE_DROP': {'DESCRIPTION': 'weighted time average ' - 'derivative value', - 'GROUP': 'TAVG_D_FLOW_COEFF', - 'HEADER': 'dtavg[Pressure_Drop]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_SURFACE_SECONDARY': {'DESCRIPTION': 'weighted time average derivative ' - 'value', - 'GROUP': 'TAVG_D_FLOW_COEFF', - 'HEADER': 'dtavg[Secondary_Strength]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_SURFACE_SECOND_OVER_UNIFORM': {'DESCRIPTION': 'weighted time average ' - 'derivative value', - 'GROUP': 'TAVG_D_FLOW_COEFF', - 'HEADER': 'dtavg[Secondary_Over_Uniformity]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_SURFACE_SPECIES_" + std::to_string(iVar': {'DESCRIPTION': 'weighted ' - 'time ' - 'average ' - 'derivative ' - 'value', - 'GROUP': 'TAVG_D_SPECIES_COEFF', - 'HEADER': 'dtavg[Avg_Species_" ' - '+ ' - 'std::to_string(iVar]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_SURFACE_STATIC_PRESSURE': {'DESCRIPTION': 'weighted time average ' - 'derivative value', - 'GROUP': 'TAVG_D_FLOW_COEFF', - 'HEADER': 'dtavg[Avg_Press]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_SURFACE_STATIC_TEMPERATURE': {'DESCRIPTION': 'weighted time average ' - 'derivative value', - 'GROUP': 'TAVG_D_FLOW_COEFF', - 'HEADER': 'dtavg[Avg_Temp]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_SURFACE_TOTAL_PRESSURE': {'DESCRIPTION': 'weighted time average ' - 'derivative value', - 'GROUP': 'TAVG_D_FLOW_COEFF', - 'HEADER': 'dtavg[Avg_TotalPress]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_SURFACE_TOTAL_TEMPERATURE': {'DESCRIPTION': 'weighted time average ' - 'derivative value', - 'GROUP': 'TAVG_D_FLOW_COEFF', - 'HEADER': 'dtavg[Avg_TotalTemp]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_SURFACE_UNIFORMITY': {'DESCRIPTION': 'weighted time average ' - 'derivative value', - 'GROUP': 'TAVG_D_FLOW_COEFF', - 'HEADER': 'dtavg[Uniformity]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_THRUST': {'DESCRIPTION': 'weighted time average derivative value', - 'GROUP': 'TAVG_D_ROTATING_FRAME', - 'HEADER': 'dtavg[CT]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_TOPOL_COMPLIANCE': {'DESCRIPTION': 'weighted time average derivative ' - 'value', - 'GROUP': 'TAVG_D_STRUCT_COEFF', - 'HEADER': 'dtavg[TopComp]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_TOPOL_DISCRETENESS': {'DESCRIPTION': 'weighted time average ' - 'derivative value', - 'GROUP': 'TAVG_D_STRUCT_COEFF', - 'HEADER': 'dtavg[TopDisc]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_TORQUE': {'DESCRIPTION': 'weighted time average derivative value', - 'GROUP': 'TAVG_D_ROTATING_FRAME', - 'HEADER': 'dtavg[CQ]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_TOTAL_HEATFLUX': {'DESCRIPTION': 'weighted time average derivative ' - 'value', - 'GROUP': 'TAVG_D_HEAT', - 'HEADER': 'dtavg[HF]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_D_VOLUME_FRACTION': {'DESCRIPTION': 'weighted time average derivative ' - 'value', - 'GROUP': 'TAVG_D_STRUCT_COEFF', - 'HEADER': 'dtavg[VolFrac]', - 'TYPE': 'TAVG_D_COEFFICIENT'}, - 'TAVG_EFFICIENCY': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_AERO_COEFF', - 'HEADER': 'tavg[CEff]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_EQUIVALENT_AREA': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_EQUIVALENT_AREA', - 'HEADER': 'tavg[CEquiv_Area]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_FIGURE_OF_MERIT': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_ROTATING_FRAME', - 'HEADER': 'tavg[CMerit]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_FORCE_X': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_AERO_COEFF', - 'HEADER': 'tavg[CFx]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_FORCE_Y': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_AERO_COEFF', - 'HEADER': 'tavg[CFy]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_FORCE_Z': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_AERO_COEFF', - 'HEADER': 'tavg[CFz]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_INVERSE_DESIGN_PRESSURE': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_CP_DIFF', - 'HEADER': 'tavg[Cp_Diff]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_LIFT': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_AERO_COEFF', - 'HEADER': 'tavg[CL]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_MAXIMUM_HEATFLUX': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_HEAT', - 'HEADER': 'tavg[MaxHF]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_MOMENT_X': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_AERO_COEFF', - 'HEADER': 'tavg[CMx]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_MOMENT_Y': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_AERO_COEFF', - 'HEADER': 'tavg[CMy]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_MOMENT_Z': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_AERO_COEFF', - 'HEADER': 'tavg[CMz]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_REFERENCE_GEOMETRY': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_STRUCT_COEFF', - 'HEADER': 'tavg[RefGeom]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_REFERENCE_NODE': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_STRUCT_COEFF', - 'HEADER': 'tavg[RefNode]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_SENS_AOA': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_SENSITIVITY', - 'HEADER': 'tavg[Sens_AoA]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_SENS_GEO': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_SENSITIVITY', - 'HEADER': 'tavg[Sens_Geo]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_SENS_MACH': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_SENSITIVITY', - 'HEADER': 'tavg[Sens_Mach]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_SENS_PRESS': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_SENSITIVITY', - 'HEADER': 'tavg[Sens_Press]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_SENS_PRESS_OUT': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_SENSITIVITY', - 'HEADER': 'tavg[Sens_Pout]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_SENS_TEMP': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_SENSITIVITY', - 'HEADER': 'tavg[Sens_Temp]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_SENS_VEL_IN': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_SENSITIVITY', - 'HEADER': 'tavg[Sens_Vin]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_SIDEFORCE': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_AERO_COEFF', - 'HEADER': 'tavg[CSF]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_STRESS_PENALTY': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_STRUCT_COEFF', - 'HEADER': 'tavg[StressPen]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_SURFACE_MACH': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_FLOW_COEFF', - 'HEADER': 'tavg[Avg_Mach]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_SURFACE_MASSFLOW': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_FLOW_COEFF', - 'HEADER': 'tavg[Avg_Massflow]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_SURFACE_MOM_DISTORTION': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_FLOW_COEFF', - 'HEADER': 'tavg[Momentum_Distortion]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_SURFACE_PRESSURE_DROP': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_FLOW_COEFF', - 'HEADER': 'tavg[Pressure_Drop]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_SURFACE_SECONDARY': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_FLOW_COEFF', - 'HEADER': 'tavg[Secondary_Strength]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_SURFACE_SECOND_OVER_UNIFORM': {'DESCRIPTION': 'weighted time average ' - 'value', - 'GROUP': 'TAVG_FLOW_COEFF', - 'HEADER': 'tavg[Secondary_Over_Uniformity]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_SURFACE_SPECIES_" + std::to_string(iVar': {'DESCRIPTION': 'weighted ' - 'time average ' - 'value', - 'GROUP': 'TAVG_SPECIES_COEFF', - 'HEADER': 'tavg[Avg_Species_" ' - '+ ' - 'std::to_string(iVar]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_SURFACE_STATIC_PRESSURE': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_FLOW_COEFF', - 'HEADER': 'tavg[Avg_Press]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_SURFACE_STATIC_TEMPERATURE': {'DESCRIPTION': 'weighted time average ' - 'value', - 'GROUP': 'TAVG_FLOW_COEFF', - 'HEADER': 'tavg[Avg_Temp]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_SURFACE_TOTAL_PRESSURE': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_FLOW_COEFF', - 'HEADER': 'tavg[Avg_TotalPress]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_SURFACE_TOTAL_TEMPERATURE': {'DESCRIPTION': 'weighted time average ' - 'value', - 'GROUP': 'TAVG_FLOW_COEFF', - 'HEADER': 'tavg[Avg_TotalTemp]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_SURFACE_UNIFORMITY': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_FLOW_COEFF', - 'HEADER': 'tavg[Uniformity]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_THRUST': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_ROTATING_FRAME', - 'HEADER': 'tavg[CT]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_TOPOL_COMPLIANCE': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_STRUCT_COEFF', - 'HEADER': 'tavg[TopComp]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_TOPOL_DISCRETENESS': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_STRUCT_COEFF', - 'HEADER': 'tavg[TopDisc]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_TORQUE': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_ROTATING_FRAME', - 'HEADER': 'tavg[CQ]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_TOTAL_HEATFLUX': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_HEAT', - 'HEADER': 'tavg[HF]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'TAVG_VOLUME_FRACTION': {'DESCRIPTION': 'weighted time average value', - 'GROUP': 'TAVG_STRUCT_COEFF', - 'HEADER': 'tavg[VolFrac]', - 'TYPE': 'TAVG_COEFFICIENT'}, - 'THRUST': {'DESCRIPTION': 'Thrust coefficient', - 'GROUP': 'ROTATING_FRAME', - 'HEADER': 'CT', - 'TYPE': 'COEFFICIENT'}, - 'TOPOL_COMPLIANCE': {'DESCRIPTION': 'Structural compliance', - 'GROUP': 'STRUCT_COEFF', - 'HEADER': 'TopComp', - 'TYPE': 'COEFFICIENT'}, - 'TOPOL_DISCRETENESS': {'DESCRIPTION': 'Discreteness of the material ' - 'distribution', - 'GROUP': 'STRUCT_COEFF', - 'HEADER': 'TopDisc', - 'TYPE': 'COEFFICIENT'}, - 'TORQUE': {'DESCRIPTION': 'Torque coefficient', - 'GROUP': 'ROTATING_FRAME', - 'HEADER': 'CQ', - 'TYPE': 'COEFFICIENT'}, - 'TOTAL_HEATFLUX': {'DESCRIPTION': 'Total heatflux on all surfaces defined in ' - 'MARKER_MONITORING', - 'GROUP': 'HEAT', - 'HEADER': 'HF', - 'TYPE': 'COEFFICIENT'}, - 'VMS': {'DESCRIPTION': 'VMS', - 'GROUP': 'Maximum Von-Misses stress', - 'HEADER': 'VonMises', - 'TYPE': 'DEFAULT'}, - 'VOLUME_FRACTION': {'DESCRIPTION': 'Fraction of solid material', - 'GROUP': 'STRUCT_COEFF', - 'HEADER': 'VolFrac', - 'TYPE': 'COEFFICIENT'}} +history_header_map = { + "ADJOINT_DISP_X": { + "DESCRIPTION": "Root-mean square residual of the adjoint " + "of the X displacements.", + "GROUP": "RMS_RES", + "HEADER": "rms[Ux_adj]", + "TYPE": "RESIDUAL", + }, + "ADJOINT_DISP_Y": { + "DESCRIPTION": "Root-mean square residual of the adjoint " + "of the Y displacements.", + "GROUP": "RMS_RES", + "HEADER": "rms[Uy_adj]", + "TYPE": "RESIDUAL", + }, + "ADJOINT_DISP_Z": { + "DESCRIPTION": "Root-mean square residual of the adjoint " + "of the Z displacements.", + "GROUP": "RMS_RES", + "HEADER": "rms[Uz_adj]", + "TYPE": "RESIDUAL", + }, + "ADJOINT_SOLEXTRA": { + "DESCRIPTION": "Adjoint value of the first extra " "Solution.", + "GROUP": "ADJOINT_SOLEXTRA", + "HEADER": "Adjoint_SolExtra", + "TYPE": "COEFFICIENT", + }, + "AOA": { + "DESCRIPTION": "Angle of attack", + "GROUP": "AOA", + "HEADER": "AoA", + "TYPE": "DEFAULT", + }, + "AVG_CFL": { + "DESCRIPTION": "Current average of the local CFL numbers", + "GROUP": "CFL_NUMBER", + "HEADER": "Avg CFL", + "TYPE": "DEFAULT", + }, + "AVG_DENSITY": { + "DESCRIPTION": "Total average density on all markers set in " "MARKER_ANALYZE", + "GROUP": "FLOW_COEFF", + "HEADER": "Avg_Density", + "TYPE": "COEFFICIENT", + }, + "AVG_ENTHALPY": { + "DESCRIPTION": "Total average enthalpy on all markers set in " "MARKER_ANALYZE", + "GROUP": "FLOW_COEFF", + "HEADER": "Avg_Enthalpy", + "TYPE": "COEFFICIENT", + }, + "AVG_NORMALVEL": { + "DESCRIPTION": "Total average normal velocity on all " + "markers set in MARKER_ANALYZE", + "GROUP": "FLOW_COEFF", + "HEADER": "Avg_NormalVel", + "TYPE": "COEFFICIENT", + }, + "AVG_TEMPERATURE": { + "DESCRIPTION": "Average temperature on all surfaces " + "defined in MARKER_MONITORING", + "GROUP": "HEAT", + "HEADER": "AvgTemp", + "TYPE": "COEFFICIENT", + }, + "BGS_ADJ_DENSITY": { + "DESCRIPTION": "BGS residual of the adjoint density.", + "GROUP": "BGS_RES", + "HEADER": "bgs[A_Rho]", + "TYPE": "RESIDUAL", + }, + "BGS_ADJ_DISP_X": { + "DESCRIPTION": "BGS residual of the adjoint X " "displacement.", + "GROUP": "BGS_RES", + "HEADER": "bgs[A_Ux]", + "TYPE": "RESIDUAL", + }, + "BGS_ADJ_DISP_Y": { + "DESCRIPTION": "BGS residual of the adjoint Y " "displacement.", + "GROUP": "BGS_RES", + "HEADER": "bgs[A_Uy]", + "TYPE": "RESIDUAL", + }, + "BGS_ADJ_DISP_Z": { + "DESCRIPTION": "BGS residual of the adjoint Z " "displacement.", + "GROUP": "BGS_RES", + "HEADER": "bgs[A_Uz]", + "TYPE": "RESIDUAL", + }, + "BGS_ADJ_DISSIPATION": { + "DESCRIPTION": "BGS residual of the adjoint " "dissipation.", + "GROUP": "BGS_RES", + "HEADER": "bgs[A_w]", + "TYPE": "RESIDUAL", + }, + "BGS_ADJ_ENERGY": { + "DESCRIPTION": "BGS residual of the adjoint energy.", + "GROUP": "BGS_RES", + "HEADER": "bgs[A_E]", + "TYPE": "RESIDUAL", + }, + "BGS_ADJ_MOMENTUM-X": { + "DESCRIPTION": "BGS residual of the adjoint momentum " "x-component", + "GROUP": "BGS_RES", + "HEADER": "bgs[A_RhoU]", + "TYPE": "RESIDUAL", + }, + "BGS_ADJ_MOMENTUM-Y": { + "DESCRIPTION": "BGS residual of the adjoint momentum " "y-component", + "GROUP": "BGS_RES", + "HEADER": "bgs[A_RhoV]", + "TYPE": "RESIDUAL", + }, + "BGS_ADJ_MOMENTUM-Z": { + "DESCRIPTION": "BGS residual of the adjoint momentum " "z-component", + "GROUP": "BGS_RES", + "HEADER": "bgs[A_RhoW]", + "TYPE": "RESIDUAL", + }, + "BGS_ADJ_NU_TILDE": { + "DESCRIPTION": "BGS residual of the adjoint nu tilde.", + "GROUP": "BGS_RES", + "HEADER": "bgs[A_nu]", + "TYPE": "RESIDUAL", + }, + "BGS_ADJ_PRESSURE": { + "DESCRIPTION": "BGS residual of the adjoint Pressure.", + "GROUP": "BGS_RES", + "HEADER": "bgs[A_Rho]", + "TYPE": "RESIDUAL", + }, + "BGS_ADJ_RAD_ENERGY": { + "DESCRIPTION": "BGS residual of the P1 radiative " "energy.", + "GROUP": "BGS_RES", + "HEADER": "bgs[A_P1]", + "TYPE": "RESIDUAL", + }, + 'BGS_ADJ_SPECIES_" + std::to_string(iVar': { + "DESCRIPTION": "BGS residual of " "the adjoint " "transported " "species.", + "GROUP": "BGS_RES", + "HEADER": 'bgs[A_rho*Y_" + ' "std::to_string(iVar) + " '"]', + "TYPE": "RESIDUAL", + }, + "BGS_ADJ_TEMPERATURE": { + "DESCRIPTION": "BGS residual of the adjoint " "temperature.", + "GROUP": "BGS_RES", + "HEADER": "bgs[A_T]", + "TYPE": "RESIDUAL", + }, + "BGS_ADJ_TKE": { + "DESCRIPTION": "BGS residual of the adjoint kinetic energy.", + "GROUP": "BGS_RES", + "HEADER": "bgs[A_k]", + "TYPE": "RESIDUAL", + }, + "BGS_ADJ_VELOCITY-X": { + "DESCRIPTION": "BGS residual of the adjoint Velocity " "x-component", + "GROUP": "BGS_RES", + "HEADER": "bgs[A_RhoU]", + "TYPE": "RESIDUAL", + }, + "BGS_ADJ_VELOCITY-Y": { + "DESCRIPTION": "BGS residual of the adjoint Velocity " "y-component", + "GROUP": "BGS_RES", + "HEADER": "bgs[A_RhoV]", + "TYPE": "RESIDUAL", + }, + "BGS_ADJ_VELOCITY-Z": { + "DESCRIPTION": "BGS residual of the adjoint Velocity " "z-component", + "GROUP": "BGS_RES", + "HEADER": "bgs[A_RhoW]", + "TYPE": "RESIDUAL", + }, + "BGS_DENSITY": { + "DESCRIPTION": "BGS residual of the density.", + "GROUP": "BGS_RES", + "HEADER": "bgs[Rho]", + "TYPE": "RESIDUAL", + }, + "BGS_DISP_X": { + "DESCRIPTION": "BGS residual of X displacement", + "GROUP": "BGS_RES", + "HEADER": "bgs[DispX]", + "TYPE": "RESIDUAL", + }, + "BGS_DISP_Y": { + "DESCRIPTION": "BGS residual of Y displacement", + "GROUP": "BGS_RES", + "HEADER": "bgs[DispY]", + "TYPE": "RESIDUAL", + }, + "BGS_DISP_Z": { + "DESCRIPTION": "BGS residual of Z displacement", + "GROUP": "BGS_RES", + "HEADER": "bgs[DispZ]", + "TYPE": "RESIDUAL", + }, + "BGS_DISSIPATION": { + "DESCRIPTION": "BGS residual of dissipation (SST model).", + "GROUP": "BGS_RES", + "HEADER": "bgs[w]", + "TYPE": "RESIDUAL", + }, + "BGS_ENERGY": { + "DESCRIPTION": "BGS residual of the energy.", + "GROUP": "BGS_RES", + "HEADER": "bgs[RhoE]", + "TYPE": "RESIDUAL", + }, + "BGS_MOMENTUM-X": { + "DESCRIPTION": "BGS residual of the momentum x-component.", + "GROUP": "BGS_RES", + "HEADER": "bgs[RhoU]", + "TYPE": "RESIDUAL", + }, + "BGS_MOMENTUM-Y": { + "DESCRIPTION": "BGS residual of the momentum y-component.", + "GROUP": "BGS_RES", + "HEADER": "bgs[RhoV]", + "TYPE": "RESIDUAL", + }, + "BGS_NU_TILDE": { + "DESCRIPTION": "BGS residual of nu tilde (SA model).", + "GROUP": "BGS_RES", + "HEADER": "bgs[nu]", + "TYPE": "RESIDUAL", + }, + "BGS_PRESSURE": { + "DESCRIPTION": "BGS residual of the pressure.", + "GROUP": "BGS_RES", + "HEADER": "bgs[P]", + "TYPE": "RESIDUAL", + }, + 'BGS_SPECIES_" + std::to_string(iVar': { + "DESCRIPTION": "BGS residual of " "transported species.", + "GROUP": "BGS_RES", + "HEADER": 'bgs[rho*Y_" + ' 'std::to_string(iVar)+"]', + "TYPE": "RESIDUAL", + }, + "BGS_TEMPERATURE": { + "DESCRIPTION": "Block-Gauss-Seidel residual of the " "temperature", + "GROUP": "BGS_RES", + "HEADER": "bgs[T]", + "TYPE": "RESIDUAL", + }, + "BGS_TKE": { + "DESCRIPTION": "BGS residual of kinetic energy (SST model).", + "GROUP": "BGS_RES", + "HEADER": "bgs[k]", + "TYPE": "RESIDUAL", + }, + "BGS_VELOCITY-X": { + "DESCRIPTION": "BGS residual of the velocity x-component.", + "GROUP": "BGS_RES", + "HEADER": "bgs[U]", + "TYPE": "RESIDUAL", + }, + "BGS_VELOCITY-Y": { + "DESCRIPTION": "BGS residual of the velocity y-component.", + "GROUP": "BGS_RES", + "HEADER": "bgs[V]", + "TYPE": "RESIDUAL", + }, + "BGS_VELOCITY-Z": { + "DESCRIPTION": "BGS residual of the velocity z-component.", + "GROUP": "BGS_RES", + "HEADER": "bgs[W]", + "TYPE": "RESIDUAL", + }, + "BUFFET": { + "DESCRIPTION": "Buffet sensor", + "GROUP": "AERO_COEFF", + "HEADER": "Buffet", + "TYPE": "COEFFICIENT", + }, + "CFL_NUMBER": { + "DESCRIPTION": "Current value of the CFL number", + "GROUP": "CFL_NUMBER", + "HEADER": "CFL number", + "TYPE": "DEFAULT", + }, + "CHANGE_IN_AOA": { + "DESCRIPTION": "Last change in Angle of Attack by Fixed CL " "Driver", + "GROUP": "FIXED_CL", + "HEADER": "Change_in_AOA", + "TYPE": "RESIDUAL", + }, + "CL_DRIVER_COMMAND": { + "DESCRIPTION": "CL Driver's control command", + "GROUP": "FIXED_CL", + "HEADER": "CL_Driver_Command", + "TYPE": "RESIDUAL", + }, + "COMBO": { + "DESCRIPTION": "Combined obj. function value.", + "GROUP": "COMBO", + "HEADER": "ComboObj", + "TYPE": "COEFFICIENT", + }, + "DEFORM_ITER": { + "DESCRIPTION": "Linear solver iterations for the mesh " "deformation", + "GROUP": "DEFORM", + "HEADER": "DeformIter", + "TYPE": "DEFAULT", + }, + "DEFORM_MAX_VOLUME": { + "DESCRIPTION": "Maximum volume in the mesh", + "GROUP": "DEFORM", + "HEADER": "MaxVolume", + "TYPE": "DEFAULT", + }, + "DEFORM_MIN_VOLUME": { + "DESCRIPTION": "Minimum volume in the mesh", + "GROUP": "DEFORM", + "HEADER": "MinVolume", + "TYPE": "DEFAULT", + }, + "DEFORM_RESIDUAL": { + "DESCRIPTION": "Residual of the linear solver for the " "mesh deformation", + "GROUP": "DEFORM", + "HEADER": "DeformRes", + "TYPE": "DEFAULT", + }, + "DELTA_CL": { + "DESCRIPTION": "Difference between Target CL and current CL", + "GROUP": "FIXED_CL", + "HEADER": "Delta_CL", + "TYPE": "COEFFICIENT", + }, + "DRAG": { + "DESCRIPTION": "Total drag coefficient on all surfaces set with " + "MARKER_MONITORING", + "GROUP": "AERO_COEFF", + "HEADER": "CD", + "TYPE": "COEFFICIENT", + }, + "D_ADJOINT_SOLEXTRA": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_ADJOINT_SOLEXTRA", + "HEADER": "d[Adjoint_SolExtra]", + "TYPE": "D_COEFFICIENT", + }, + "D_AVG_DENSITY": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_FLOW_COEFF", + "HEADER": "d[Avg_Density]", + "TYPE": "D_COEFFICIENT", + }, + "D_AVG_ENTHALPY": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_FLOW_COEFF", + "HEADER": "d[Avg_Enthalpy]", + "TYPE": "D_COEFFICIENT", + }, + "D_AVG_NORMALVEL": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_FLOW_COEFF", + "HEADER": "d[Avg_NormalVel]", + "TYPE": "D_COEFFICIENT", + }, + "D_AVG_TEMPERATURE": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_HEAT", + "HEADER": "d[AvgTemp]", + "TYPE": "D_COEFFICIENT", + }, + "D_BUFFET": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_AERO_COEFF", + "HEADER": "d[Buffet]", + "TYPE": "D_COEFFICIENT", + }, + "D_COMBO": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_COMBO", + "HEADER": "d[ComboObj]", + "TYPE": "D_COEFFICIENT", + }, + "D_DELTA_CL": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_FIXED_CL", + "HEADER": "d[Delta_CL]", + "TYPE": "D_COEFFICIENT", + }, + "D_DRAG": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_AERO_COEFF", + "HEADER": "d[CD]", + "TYPE": "D_COEFFICIENT", + }, + "D_EFFICIENCY": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_AERO_COEFF", + "HEADER": "d[CEff]", + "TYPE": "D_COEFFICIENT", + }, + "D_EQUIVALENT_AREA": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_EQUIVALENT_AREA", + "HEADER": "d[CEquiv_Area]", + "TYPE": "D_COEFFICIENT", + }, + "D_FIGURE_OF_MERIT": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_ROTATING_FRAME", + "HEADER": "d[CMerit]", + "TYPE": "D_COEFFICIENT", + }, + "D_FORCE_X": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_AERO_COEFF", + "HEADER": "d[CFx]", + "TYPE": "D_COEFFICIENT", + }, + "D_FORCE_Y": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_AERO_COEFF", + "HEADER": "d[CFy]", + "TYPE": "D_COEFFICIENT", + }, + "D_FORCE_Z": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_AERO_COEFF", + "HEADER": "d[CFz]", + "TYPE": "D_COEFFICIENT", + }, + "D_INVERSE_DESIGN_PRESSURE": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_CP_DIFF", + "HEADER": "d[Cp_Diff]", + "TYPE": "D_COEFFICIENT", + }, + "D_LIFT": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_AERO_COEFF", + "HEADER": "d[CL]", + "TYPE": "D_COEFFICIENT", + }, + "D_MAXIMUM_HEATFLUX": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_HEAT", + "HEADER": "d[MaxHF]", + "TYPE": "D_COEFFICIENT", + }, + "D_MOMENT_X": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_AERO_COEFF", + "HEADER": "d[CMx]", + "TYPE": "D_COEFFICIENT", + }, + "D_MOMENT_Y": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_AERO_COEFF", + "HEADER": "d[CMy]", + "TYPE": "D_COEFFICIENT", + }, + "D_MOMENT_Z": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_AERO_COEFF", + "HEADER": "d[CMz]", + "TYPE": "D_COEFFICIENT", + }, + "D_REFERENCE_GEOMETRY": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_STRUCT_COEFF", + "HEADER": "d[RefGeom]", + "TYPE": "D_COEFFICIENT", + }, + "D_REFERENCE_NODE": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_STRUCT_COEFF", + "HEADER": "d[RefNode]", + "TYPE": "D_COEFFICIENT", + }, + "D_SENS_AOA": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_SENSITIVITY", + "HEADER": "d[Sens_AoA]", + "TYPE": "D_COEFFICIENT", + }, + "D_SENS_GEO": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_SENSITIVITY", + "HEADER": "d[Sens_Geo]", + "TYPE": "D_COEFFICIENT", + }, + "D_SENS_MACH": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_SENSITIVITY", + "HEADER": "d[Sens_Mach]", + "TYPE": "D_COEFFICIENT", + }, + "D_SENS_PRESS": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_SENSITIVITY", + "HEADER": "d[Sens_Press]", + "TYPE": "D_COEFFICIENT", + }, + "D_SENS_PRESS_OUT": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_SENSITIVITY", + "HEADER": "d[Sens_Pout]", + "TYPE": "D_COEFFICIENT", + }, + "D_SENS_TEMP": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_SENSITIVITY", + "HEADER": "d[Sens_Temp]", + "TYPE": "D_COEFFICIENT", + }, + "D_SENS_VEL_IN": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_SENSITIVITY", + "HEADER": "d[Sens_Vin]", + "TYPE": "D_COEFFICIENT", + }, + "D_SIDEFORCE": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_AERO_COEFF", + "HEADER": "d[CSF]", + "TYPE": "D_COEFFICIENT", + }, + "D_STRESS_PENALTY": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_STRUCT_COEFF", + "HEADER": "d[StressPen]", + "TYPE": "D_COEFFICIENT", + }, + "D_SURFACE_MACH": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_FLOW_COEFF", + "HEADER": "d[Avg_Mach]", + "TYPE": "D_COEFFICIENT", + }, + "D_SURFACE_MASSFLOW": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_FLOW_COEFF", + "HEADER": "d[Avg_Massflow]", + "TYPE": "D_COEFFICIENT", + }, + "D_SURFACE_MOM_DISTORTION": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_FLOW_COEFF", + "HEADER": "d[Momentum_Distortion]", + "TYPE": "D_COEFFICIENT", + }, + "D_SURFACE_PRESSURE_DROP": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_FLOW_COEFF", + "HEADER": "d[Pressure_Drop]", + "TYPE": "D_COEFFICIENT", + }, + "D_SURFACE_SECONDARY": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_FLOW_COEFF", + "HEADER": "d[Secondary_Strength]", + "TYPE": "D_COEFFICIENT", + }, + "D_SURFACE_SECOND_OVER_UNIFORM": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_FLOW_COEFF", + "HEADER": "d[Secondary_Over_Uniformity]", + "TYPE": "D_COEFFICIENT", + }, + 'D_SURFACE_SPECIES_" + std::to_string(iVar': { + "DESCRIPTION": "Derivative " "value", + "GROUP": "D_SPECIES_COEFF", + "HEADER": 'd[Avg_Species_" + ' "std::to_string(iVar]", + "TYPE": "D_COEFFICIENT", + }, + "D_SURFACE_STATIC_PRESSURE": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_FLOW_COEFF", + "HEADER": "d[Avg_Press]", + "TYPE": "D_COEFFICIENT", + }, + "D_SURFACE_STATIC_TEMPERATURE": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_FLOW_COEFF", + "HEADER": "d[Avg_Temp]", + "TYPE": "D_COEFFICIENT", + }, + "D_SURFACE_TOTAL_PRESSURE": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_FLOW_COEFF", + "HEADER": "d[Avg_TotalPress]", + "TYPE": "D_COEFFICIENT", + }, + "D_SURFACE_TOTAL_TEMPERATURE": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_FLOW_COEFF", + "HEADER": "d[Avg_TotalTemp]", + "TYPE": "D_COEFFICIENT", + }, + "D_SURFACE_UNIFORMITY": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_FLOW_COEFF", + "HEADER": "d[Uniformity]", + "TYPE": "D_COEFFICIENT", + }, + "D_THRUST": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_ROTATING_FRAME", + "HEADER": "d[CT]", + "TYPE": "D_COEFFICIENT", + }, + "D_TOPOL_COMPLIANCE": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_STRUCT_COEFF", + "HEADER": "d[TopComp]", + "TYPE": "D_COEFFICIENT", + }, + "D_TOPOL_DISCRETENESS": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_STRUCT_COEFF", + "HEADER": "d[TopDisc]", + "TYPE": "D_COEFFICIENT", + }, + "D_TORQUE": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_ROTATING_FRAME", + "HEADER": "d[CQ]", + "TYPE": "D_COEFFICIENT", + }, + "D_TOTAL_HEATFLUX": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_HEAT", + "HEADER": "d[HF]", + "TYPE": "D_COEFFICIENT", + }, + "D_VOLUME_FRACTION": { + "DESCRIPTION": "Derivative value", + "GROUP": "D_STRUCT_COEFF", + "HEADER": "d[VolFrac]", + "TYPE": "D_COEFFICIENT", + }, + "EFFICIENCY": { + "DESCRIPTION": "Total lift-to-drag ratio on all surfaces set " + "with MARKER_MONITORING", + "GROUP": "AERO_COEFF", + "HEADER": "CEff", + "TYPE": "COEFFICIENT", + }, + "EQUIVALENT_AREA": { + "DESCRIPTION": "Equivalent area", + "GROUP": "EQUIVALENT_AREA", + "HEADER": "CEquiv_Area", + "TYPE": "COEFFICIENT", + }, + "FIGURE_OF_MERIT": { + "DESCRIPTION": "Thrust over torque", + "GROUP": "ROTATING_FRAME", + "HEADER": "CMerit", + "TYPE": "COEFFICIENT", + }, + "FORCE_X": { + "DESCRIPTION": "Total force x-component on all surfaces set with " + "MARKER_MONITORING", + "GROUP": "AERO_COEFF", + "HEADER": "CFx", + "TYPE": "COEFFICIENT", + }, + "FORCE_Y": { + "DESCRIPTION": "Total force y-component on all surfaces set with " + "MARKER_MONITORING", + "GROUP": "AERO_COEFF", + "HEADER": "CFy", + "TYPE": "COEFFICIENT", + }, + "FORCE_Z": { + "DESCRIPTION": "Total force z-component on all surfaces set with " + "MARKER_MONITORING", + "GROUP": "AERO_COEFF", + "HEADER": "CFz", + "TYPE": "COEFFICIENT", + }, + "INVERSE_DESIGN_PRESSURE": { + "DESCRIPTION": "Cp difference for inverse design", + "GROUP": "CP_DIFF", + "HEADER": "Cp_Diff", + "TYPE": "COEFFICIENT", + }, + "LIFT": { + "DESCRIPTION": "Total lift coefficient on all surfaces set with " + "MARKER_MONITORING", + "GROUP": "AERO_COEFF", + "HEADER": "CL", + "TYPE": "COEFFICIENT", + }, + "LINSOL_ITER": { + "DESCRIPTION": "Number of iterations of the linear solver.", + "GROUP": "LINSOL", + "HEADER": "LinSolIter", + "TYPE": "DEFAULT", + }, + "LINSOL_ITER_SPECIES": { + "DESCRIPTION": "Number of iterations of the linear " + "solver for species solver.", + "GROUP": "LINSOL", + "HEADER": "LinSolIterSpecies", + "TYPE": "DEFAULT", + }, + "LINSOL_ITER_TURB": { + "DESCRIPTION": "Number of iterations of the linear " "solver for turbulence.", + "GROUP": "LINSOL", + "HEADER": "LinSolIterTurb", + "TYPE": "DEFAULT", + }, + "LINSOL_RESIDUAL": { + "DESCRIPTION": "Residual of the linear solver.", + "GROUP": "LINSOL", + "HEADER": "LinSolRes", + "TYPE": "DEFAULT", + }, + "LINSOL_RESIDUAL_SPECIES": { + "DESCRIPTION": "Residual of the linear solver for " "species solver.", + "GROUP": "LINSOL", + "HEADER": "LinSolResSpecies", + "TYPE": "DEFAULT", + }, + "LINSOL_RESIDUAL_TURB": { + "DESCRIPTION": "Residual of the linear solver for " "turbulence.", + "GROUP": "LINSOL", + "HEADER": "LinSolResTurb", + "TYPE": "DEFAULT", + }, + "LOAD_INCREMENT": { + "DESCRIPTION": "LOAD_INCREMENT", + "GROUP": "Percent of total load (incremental", + "HEADER": "Load[%]", + "TYPE": "DEFAULT", + }, + "LOAD_RAMP": { + "DESCRIPTION": "LOAD_RAMP", + "GROUP": "Fraction of total load (ramped", + "HEADER": "Load_Ramp", + "TYPE": "DEFAULT", + }, + "MAXIMUM_HEATFLUX": { + "DESCRIPTION": "Maximum heatflux on all surfaces defined " + "in MARKER_MONITORING", + "GROUP": "HEAT", + "HEADER": "MaxHF", + "TYPE": "COEFFICIENT", + }, + "MAX_ADJ_DENSITY": { + "DESCRIPTION": "Maximum residual of the adjoint density.", + "GROUP": "MAX_RES", + "HEADER": "max[A_Rho]", + "TYPE": "RESIDUAL", + }, + "MAX_ADJ_DISSIPATION": { + "DESCRIPTION": "Maximum residual of the adjoint " "dissipation.", + "GROUP": "MAX_RES", + "HEADER": "max[A_w]", + "TYPE": "RESIDUAL", + }, + "MAX_ADJ_ENERGY": { + "DESCRIPTION": "Maximum residual of the adjoint energy.", + "GROUP": "MAX_RES", + "HEADER": "max[A_E]", + "TYPE": "RESIDUAL", + }, + "MAX_ADJ_MOMENTUM-X": { + "DESCRIPTION": "Maximum residual of the adjoint " "momentum x-component", + "GROUP": "MAX_RES", + "HEADER": "max[A_RhoU]", + "TYPE": "RESIDUAL", + }, + "MAX_ADJ_MOMENTUM-Y": { + "DESCRIPTION": "Maximum residual of the adjoint " "momentum y-component", + "GROUP": "MAX_RES", + "HEADER": "max[A_RhoV]", + "TYPE": "RESIDUAL", + }, + "MAX_ADJ_MOMENTUM-Z": { + "DESCRIPTION": "Maximum residual of the adjoint " "momentum z-component", + "GROUP": "MAX_RES", + "HEADER": "max[A_RhoW]", + "TYPE": "RESIDUAL", + }, + "MAX_ADJ_NU_TILDE": { + "DESCRIPTION": "Maximum residual of the adjoint nu " "tilde.", + "GROUP": "MAX_RES", + "HEADER": "max[A_nu]", + "TYPE": "RESIDUAL", + }, + "MAX_ADJ_PRESSURE": { + "DESCRIPTION": "Maximum residual of the adjoint " "Pressure.", + "GROUP": "MAX_RES", + "HEADER": "max[A_Rho]", + "TYPE": "RESIDUAL", + }, + 'MAX_ADJ_SPECIES_" + std::to_string(iVar': { + "DESCRIPTION": "Maximum residual " "of the adjoint " "transported " "species.", + "GROUP": "MAX_RES", + "HEADER": 'max[A_rho*Y_" + ' "std::to_string(iVar) + " '"]', + "TYPE": "RESIDUAL", + }, + "MAX_ADJ_TEMPERATURE": { + "DESCRIPTION": "Maximum residual of the temperature.", + "GROUP": "MAX_RES", + "HEADER": "max[A_T]", + "TYPE": "RESIDUAL", + }, + "MAX_ADJ_TKE": { + "DESCRIPTION": "Maximum residual of the adjoint kinetic " "energy.", + "GROUP": "MAX_RES", + "HEADER": "max[A_k]", + "TYPE": "RESIDUAL", + }, + "MAX_ADJ_VELOCITY-X": { + "DESCRIPTION": "Maximum residual of the adjoint " "Velocity x-component", + "GROUP": "MAX_RES", + "HEADER": "max[A_RhoU]", + "TYPE": "RESIDUAL", + }, + "MAX_ADJ_VELOCITY-Y": { + "DESCRIPTION": "Maximum residual of the adjoint " "Velocity y-component", + "GROUP": "MAX_RES", + "HEADER": "max[A_RhoV]", + "TYPE": "RESIDUAL", + }, + "MAX_ADJ_VELOCITY-Z": { + "DESCRIPTION": "Maximum residual of the adjoint " "Velocity z-component", + "GROUP": "MAX_RES", + "HEADER": "max[A_RhoW]", + "TYPE": "RESIDUAL", + }, + "MAX_CFL": { + "DESCRIPTION": "Current maximum of the local CFL numbers", + "GROUP": "CFL_NUMBER", + "HEADER": "Max CFL", + "TYPE": "DEFAULT", + }, + "MAX_DELTA_TIME": { + "DESCRIPTION": "Current maximum local time step", + "GROUP": "CFL_NUMBER", + "HEADER": "Max DT", + "TYPE": "DEFAULT", + }, + "MAX_DENSITY": { + "DESCRIPTION": "Maximum square residual of the density.", + "GROUP": "MAX_RES", + "HEADER": "max[Rho]", + "TYPE": "RESIDUAL", + }, + "MAX_DISSIPATION": { + "DESCRIPTION": "Maximum residual of dissipation (SST " "model).", + "GROUP": "MAX_RES", + "HEADER": "max[w]", + "TYPE": "RESIDUAL", + }, + "MAX_ENERGY": { + "DESCRIPTION": "Maximum residual of the energy.", + "GROUP": "MAX_RES", + "HEADER": "max[RhoE]", + "TYPE": "RESIDUAL", + }, + "MAX_MOMENTUM-X": { + "DESCRIPTION": "Maximum square residual of the momentum " "x-component.", + "GROUP": "MAX_RES", + "HEADER": "max[RhoU]", + "TYPE": "RESIDUAL", + }, + "MAX_MOMENTUM-Y": { + "DESCRIPTION": "Maximum square residual of the momentum " "y-component.", + "GROUP": "MAX_RES", + "HEADER": "max[RhoV]", + "TYPE": "RESIDUAL", + }, + "MAX_NU_TILDE": { + "DESCRIPTION": "Maximum residual of nu tilde (SA model).", + "GROUP": "MAX_RES", + "HEADER": "max[nu]", + "TYPE": "RESIDUAL", + }, + "MAX_PRESSURE": { + "DESCRIPTION": "Maximum residual of the pressure.", + "GROUP": "MAX_RES", + "HEADER": "max[P]", + "TYPE": "RESIDUAL", + }, + 'MAX_SPECIES_" + std::to_string(iVar': { + "DESCRIPTION": "Maximum residual of " "transported species.", + "GROUP": "MAX_RES", + "HEADER": 'max[rho*Y_" + ' 'std::to_string(iVar)+"]', + "TYPE": "RESIDUAL", + }, + "MAX_TEMPERATURE": { + "DESCRIPTION": "Maximum residual of the temperature", + "GROUP": "MAX_RES", + "HEADER": "max[T]", + "TYPE": "RESIDUAL", + }, + "MAX_TKE": { + "DESCRIPTION": "Maximum residual of kinetic energy (SST model).", + "GROUP": "MAX_RES", + "HEADER": "max[k]", + "TYPE": "RESIDUAL", + }, + "MAX_VELOCITY-X": { + "DESCRIPTION": "Maximum residual of the velocity " "x-component.", + "GROUP": "MAX_RES", + "HEADER": "max[U]", + "TYPE": "RESIDUAL", + }, + "MAX_VELOCITY-Y": { + "DESCRIPTION": "Maximum residual of the velocity " "y-component.", + "GROUP": "MAX_RES", + "HEADER": "max[V]", + "TYPE": "RESIDUAL", + }, + "MAX_VELOCITY-Z": { + "DESCRIPTION": "Maximum residual of the velocity " "z-component.", + "GROUP": "MAX_RES", + "HEADER": "max[W]", + "TYPE": "RESIDUAL", + }, + "MIN_CFL": { + "DESCRIPTION": "Current minimum of the local CFL numbers", + "GROUP": "CFL_NUMBER", + "HEADER": "Min CFL", + "TYPE": "DEFAULT", + }, + "MIN_DELTA_TIME": { + "DESCRIPTION": "Current minimum local time step", + "GROUP": "CFL_NUMBER", + "HEADER": "Min DT", + "TYPE": "DEFAULT", + }, + "MOMENT_X": { + "DESCRIPTION": "Total momentum x-component on all surfaces set " + "with MARKER_MONITORING", + "GROUP": "AERO_COEFF", + "HEADER": "CMx", + "TYPE": "COEFFICIENT", + }, + "MOMENT_Y": { + "DESCRIPTION": "Total momentum y-component on all surfaces set " + "with MARKER_MONITORING", + "GROUP": "AERO_COEFF", + "HEADER": "CMy", + "TYPE": "COEFFICIENT", + }, + "MOMENT_Z": { + "DESCRIPTION": "Total momentum z-component on all surfaces set " + "with MARKER_MONITORING", + "GROUP": "AERO_COEFF", + "HEADER": "CMz", + "TYPE": "COEFFICIENT", + }, + "PREV_AOA": { + "DESCRIPTION": "Angle of Attack at the previous iteration of the " + "Fixed CL driver", + "GROUP": "FIXED_CL", + "HEADER": "Previous_AOA", + "TYPE": "DEFAULT", + }, + "REFERENCE_GEOMETRY": { + "DESCRIPTION": "L2 norm of difference wrt reference " "geometry", + "GROUP": "STRUCT_COEFF", + "HEADER": "RefGeom", + "TYPE": "COEFFICIENT", + }, + "REFERENCE_NODE": { + "DESCRIPTION": "Distance to reference node", + "GROUP": "STRUCT_COEFF", + "HEADER": "RefNode", + "TYPE": "COEFFICIENT", + }, + "RMS_ADJ_DENSITY": { + "DESCRIPTION": "Root-mean square residual of the adjoint " "density.", + "GROUP": "RMS_RES", + "HEADER": "rms[A_Rho]", + "TYPE": "RESIDUAL", + }, + "RMS_ADJ_DISSIPATION": { + "DESCRIPTION": "Root-mean square residual of the " "adjoint dissipation.", + "GROUP": "RMS_RES", + "HEADER": "rms[A_w]", + "TYPE": "RESIDUAL", + }, + "RMS_ADJ_ENERGY": { + "DESCRIPTION": "Root-mean square residual of the adjoint " "energy.", + "GROUP": "RMS_RES", + "HEADER": "rms[A_E]", + "TYPE": "RESIDUAL", + }, + "RMS_ADJ_MOMENTUM-X": { + "DESCRIPTION": "Root-mean square residual of the " + "adjoint momentum x-component.", + "GROUP": "RMS_RES", + "HEADER": "rms[A_RhoU]", + "TYPE": "RESIDUAL", + }, + "RMS_ADJ_MOMENTUM-Y": { + "DESCRIPTION": "Root-mean square residual of the " + "adjoint momentum y-component.", + "GROUP": "RMS_RES", + "HEADER": "rms[A_RhoV]", + "TYPE": "RESIDUAL", + }, + "RMS_ADJ_MOMENTUM-Z": { + "DESCRIPTION": "Root-mean square residual of the " + "adjoint momentum z-component.", + "GROUP": "RMS_RES", + "HEADER": "rms[A_RhoW]", + "TYPE": "RESIDUAL", + }, + "RMS_ADJ_NU_TILDE": { + "DESCRIPTION": "Root-mean square residual of the adjoint " "nu tilde.", + "GROUP": "RMS_RES", + "HEADER": "rms[A_nu]", + "TYPE": "RESIDUAL", + }, + "RMS_ADJ_PRESSURE": { + "DESCRIPTION": "Root-mean square residual of the adjoint " "Pressure.", + "GROUP": "RMS_RES", + "HEADER": "rms[A_P]", + "TYPE": "RESIDUAL", + }, + "RMS_ADJ_RAD_ENERGY": { + "DESCRIPTION": "Root-mean square residual of the P1 " "radiative energy.", + "GROUP": "RMS_RES", + "HEADER": "rms[A_P1]", + "TYPE": "RESIDUAL", + }, + 'RMS_ADJ_SPECIES_" + std::to_string(iVar': { + "DESCRIPTION": "Root-mean square " + "residual of the " + "adjoint " + "transported " + "species.", + "GROUP": "RMS_RES", + "HEADER": 'rms[A_rho*Y_" + ' "std::to_string(iVar) + " '"]', + "TYPE": "RESIDUAL", + }, + "RMS_ADJ_TEMPERATURE": { + "DESCRIPTION": "Root-mean square residual of the " "adjoint temperature.", + "GROUP": "RMS_RES", + "HEADER": "rms[A_T]", + "TYPE": "RESIDUAL", + }, + "RMS_ADJ_TKE": { + "DESCRIPTION": "Root-mean square residual of the adjoint " "kinetic energy.", + "GROUP": "RMS_RES", + "HEADER": "rms[A_k]", + "TYPE": "RESIDUAL", + }, + "RMS_ADJ_VELOCITY-X": { + "DESCRIPTION": "Root-mean square residual of the " + "adjoint Velocity x-component.", + "GROUP": "RMS_RES", + "HEADER": "rms[A_U]", + "TYPE": "RESIDUAL", + }, + "RMS_ADJ_VELOCITY-Y": { + "DESCRIPTION": "Root-mean square residual of the " + "adjoint Velocity y-component.", + "GROUP": "RMS_RES", + "HEADER": "rms[A_V]", + "TYPE": "RESIDUAL", + }, + "RMS_ADJ_VELOCITY-Z": { + "DESCRIPTION": "Root-mean square residual of the " + "adjoint Velocity z-component.", + "GROUP": "RMS_RES", + "HEADER": "rms[A_W]", + "TYPE": "RESIDUAL", + }, + "RMS_DENSITY": { + "DESCRIPTION": "Root-mean square residual of the density.", + "GROUP": "RMS_RES", + "HEADER": "rms[Rho]", + "TYPE": "RESIDUAL", + }, + "RMS_DISP_X": { + "DESCRIPTION": "Residual of X displacement", + "GROUP": "RMS_RES", + "HEADER": "rms[DispX]", + "TYPE": "RESIDUAL", + }, + "RMS_DISP_Y": { + "DESCRIPTION": "Residual of Y displacement", + "GROUP": "RMS_RES", + "HEADER": "rms[DispY]", + "TYPE": "RESIDUAL", + }, + "RMS_DISP_Z": { + "DESCRIPTION": "Residual of Z displacement", + "GROUP": "RMS_RES", + "HEADER": "rms[DispZ]", + "TYPE": "RESIDUAL", + }, + "RMS_DISSIPATION": { + "DESCRIPTION": "Root-mean square residual of dissipation " "(SST model).", + "GROUP": "RMS_RES", + "HEADER": "rms[w]", + "TYPE": "RESIDUAL", + }, + "RMS_ENERGY": { + "DESCRIPTION": "Root-mean square residual of the energy.", + "GROUP": "RMS_RES", + "HEADER": "rms[RhoE]", + "TYPE": "RESIDUAL", + }, + "RMS_ETOL": { + "DESCRIPTION": "Norm of energy/work increment", + "GROUP": "RMS_RES", + "HEADER": "rms[E]", + "TYPE": "RESIDUAL", + }, + "RMS_MOMENTUM-X": { + "DESCRIPTION": "Root-mean square residual of the momentum " "x-component.", + "GROUP": "RMS_RES", + "HEADER": "rms[RhoU]", + "TYPE": "RESIDUAL", + }, + "RMS_MOMENTUM-Y": { + "DESCRIPTION": "Root-mean square residual of the momentum " "y-component.", + "GROUP": "RMS_RES", + "HEADER": "rms[RhoV]", + "TYPE": "RESIDUAL", + }, + "RMS_NU_TILDE": { + "DESCRIPTION": "Root-mean square residual of nu tilde (SA " "model).", + "GROUP": "RMS_RES", + "HEADER": "rms[nu]", + "TYPE": "RESIDUAL", + }, + "RMS_PRESSURE": { + "DESCRIPTION": "Root-mean square residual of the pressure.", + "GROUP": "RMS_RES", + "HEADER": "rms[P]", + "TYPE": "RESIDUAL", + }, + "RMS_RTOL": { + "DESCRIPTION": "Norm of residual", + "GROUP": "RMS_RES", + "HEADER": "rms[R]", + "TYPE": "RESIDUAL", + }, + 'RMS_SPECIES_" + std::to_string(iVar': { + "DESCRIPTION": "Root-mean square " "residual of " "transported species.", + "GROUP": "RMS_RES", + "HEADER": 'rms[rho*Y_" + ' 'std::to_string(iVar)+"]', + "TYPE": "RESIDUAL", + }, + "RMS_TEMPERATURE": { + "DESCRIPTION": "Root mean square residual of the " "temperature", + "GROUP": "RMS_RES", + "HEADER": "rms[T]", + "TYPE": "RESIDUAL", + }, + "RMS_TKE": { + "DESCRIPTION": "Root-mean square residual of kinetic energy (SST " "model).", + "GROUP": "RMS_RES", + "HEADER": "rms[k]", + "TYPE": "RESIDUAL", + }, + "RMS_UTOL": { + "DESCRIPTION": "Norm of displacement increment", + "GROUP": "RMS_RES", + "HEADER": "rms[U]", + "TYPE": "RESIDUAL", + }, + "RMS_VELOCITY-X": { + "DESCRIPTION": "Root-mean square residual of the velocity " "x-component.", + "GROUP": "RMS_RES", + "HEADER": "rms[U]", + "TYPE": "RESIDUAL", + }, + "RMS_VELOCITY-Y": { + "DESCRIPTION": "Root-mean square residual of the velocity " "y-component.", + "GROUP": "RMS_RES", + "HEADER": "rms[V]", + "TYPE": "RESIDUAL", + }, + "SENS_AOA": { + "DESCRIPTION": "Sensitivity of the objective function with " + "respect to the angle of attack (only for " + "compressible solver).", + "GROUP": "SENSITIVITY", + "HEADER": "Sens_AoA", + "TYPE": "COEFFICIENT", + }, + "SENS_E": { + "DESCRIPTION": "d Objective / d Elasticity modulus", + "GROUP": "SENSITIVITY", + "HEADER": "Sens[E]", + "TYPE": "DEFAULT", + }, + "SENS_GEO": { + "DESCRIPTION": "Sum of the geometrical sensitivities on all " + "markers set in MARKER_MONITORING.", + "GROUP": "SENSITIVITY", + "HEADER": "Sens_Geo", + "TYPE": "COEFFICIENT", + }, + "SENS_MACH": { + "DESCRIPTION": "Sensitivity of the objective function with " + "respect to the Mach number (only of " + "compressible solver).", + "GROUP": "SENSITIVITY", + "HEADER": "Sens_Mach", + "TYPE": "COEFFICIENT", + }, + "SENS_NU": { + "DESCRIPTION": "d Objective / d Poisson ratio", + "GROUP": "SENSITIVITY", + "HEADER": "Sens[Nu]", + "TYPE": "DEFAULT", + }, + "SENS_PRESS": { + "DESCRIPTION": "Sensitivity of the objective function with " + "respect to the far-field pressure.", + "GROUP": "SENSITIVITY", + "HEADER": "Sens_Press", + "TYPE": "COEFFICIENT", + }, + "SENS_PRESS_OUT": { + "DESCRIPTION": "Sensitivity of the objective function with " + "respect to the outlet pressure.", + "GROUP": "SENSITIVITY", + "HEADER": "Sens_Pout", + "TYPE": "COEFFICIENT", + }, + "SENS_TEMP": { + "DESCRIPTION": "Sensitivity of the objective function with " + "respect to the far-field temperature.", + "GROUP": "SENSITIVITY", + "HEADER": "Sens_Temp", + "TYPE": "COEFFICIENT", + }, + "SENS_VEL_IN": { + "DESCRIPTION": "Sensitivity of the objective function with " + "respect to the inlet velocity.", + "GROUP": "SENSITIVITY", + "HEADER": "Sens_Vin", + "TYPE": "COEFFICIENT", + }, + "SIDEFORCE": { + "DESCRIPTION": "Total sideforce coefficient on all surfaces set " + "with MARKER_MONITORING", + "GROUP": "AERO_COEFF", + "HEADER": "CSF", + "TYPE": "COEFFICIENT", + }, + "STREAMWISE_DP": { + "DESCRIPTION": "Pressure drop in streamwise periodic flow", + "GROUP": "STREAMWISE_PERIODIC", + "HEADER": "SWDeltaP", + "TYPE": "DEFAULT", + }, + "STREAMWISE_HEAT": { + "DESCRIPTION": "Integrated heat for streamwise periodic " "flow", + "GROUP": "STREAMWISE_PERIODIC", + "HEADER": "SWHeat", + "TYPE": "DEFAULT", + }, + "STREAMWISE_MASSFLOW": { + "DESCRIPTION": "Massflow in streamwise periodic flow", + "GROUP": "STREAMWISE_PERIODIC", + "HEADER": "SWMassflow", + "TYPE": "DEFAULT", + }, + "STRESS_PENALTY": { + "DESCRIPTION": "Aggregate stress penalty", + "GROUP": "STRUCT_COEFF", + "HEADER": "StressPen", + "TYPE": "COEFFICIENT", + }, + "SURFACE_MACH": { + "DESCRIPTION": "Total average mach number on all markers set " + "in MARKER_ANALYZE", + "GROUP": "FLOW_COEFF", + "HEADER": "Avg_Mach", + "TYPE": "COEFFICIENT", + }, + "SURFACE_MASSFLOW": { + "DESCRIPTION": "Total average mass flow on all markers " + "set in MARKER_ANALYZE", + "GROUP": "FLOW_COEFF", + "HEADER": "Avg_Massflow", + "TYPE": "COEFFICIENT", + }, + "SURFACE_MOM_DISTORTION": { + "DESCRIPTION": "Total momentum distortion on all " + "markers set in MARKER_ANALYZE", + "GROUP": "FLOW_COEFF", + "HEADER": "Momentum_Distortion", + "TYPE": "COEFFICIENT", + }, + "SURFACE_PRESSURE_DROP": { + "DESCRIPTION": "Total pressure drop on all markers " "set in MARKER_ANALYZE", + "GROUP": "FLOW_COEFF", + "HEADER": "Pressure_Drop", + "TYPE": "COEFFICIENT", + }, + "SURFACE_SECONDARY": { + "DESCRIPTION": "Total secondary strength on all markers " + "set in MARKER_ANALYZE", + "GROUP": "FLOW_COEFF", + "HEADER": "Secondary_Strength", + "TYPE": "COEFFICIENT", + }, + "SURFACE_SECOND_OVER_UNIFORM": { + "DESCRIPTION": "Total secondary over " + "uniformity on all markers set " + "in MARKER_ANALYZE", + "GROUP": "FLOW_COEFF", + "HEADER": "Secondary_Over_Uniformity", + "TYPE": "COEFFICIENT", + }, + 'SURFACE_SPECIES_" + std::to_string(iVar': { + "DESCRIPTION": "Total average " + 'species " + ' + "std::to_string(iVar) " + '+ " on all ' + "markers set in " + "MARKER_ANALYZE", + "GROUP": "SPECIES_COEFF", + "HEADER": 'Avg_Species_" + ' "std::to_string(iVar", + "TYPE": "COEFFICIENT", + }, + "SURFACE_SPECIES_VARIANCE": { + "DESCRIPTION": "Total species variance", + "GROUP": "SPECIES_COEFF", + "HEADER": "Species_Variance", + "TYPE": "DEFAULT", + }, + "SURFACE_STATIC_PRESSURE": { + "DESCRIPTION": "Total average pressure on all " "markers set in MARKER_ANALYZE", + "GROUP": "FLOW_COEFF", + "HEADER": "Avg_Press", + "TYPE": "COEFFICIENT", + }, + "SURFACE_STATIC_TEMPERATURE": { + "DESCRIPTION": "Total average temperature on " + "all markers set in " + "MARKER_ANALYZE", + "GROUP": "FLOW_COEFF", + "HEADER": "Avg_Temp", + "TYPE": "COEFFICIENT", + }, + "SURFACE_TOTAL_PRESSURE": { + "DESCRIPTION": "Total average total pressure on " + "all markers set in MARKER_ANALYZE", + "GROUP": "FLOW_COEFF", + "HEADER": "Avg_TotalPress", + "TYPE": "COEFFICIENT", + }, + "SURFACE_TOTAL_TEMPERATURE": { + "DESCRIPTION": "Total average total temperature " + "all markers set in " + "MARKER_ANALYZE", + "GROUP": "FLOW_COEFF", + "HEADER": "Avg_TotalTemp", + "TYPE": "COEFFICIENT", + }, + "SURFACE_UNIFORMITY": { + "DESCRIPTION": "Total flow uniformity on all markers " "set in MARKER_ANALYZE", + "GROUP": "FLOW_COEFF", + "HEADER": "Uniformity", + "TYPE": "COEFFICIENT", + }, + "TAVG_ADJOINT_SOLEXTRA": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_ADJOINT_SOLEXTRA", + "HEADER": "tavg[Adjoint_SolExtra]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_AVG_DENSITY": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_FLOW_COEFF", + "HEADER": "tavg[Avg_Density]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_AVG_ENTHALPY": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_FLOW_COEFF", + "HEADER": "tavg[Avg_Enthalpy]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_AVG_NORMALVEL": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_FLOW_COEFF", + "HEADER": "tavg[Avg_NormalVel]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_AVG_TEMPERATURE": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_HEAT", + "HEADER": "tavg[AvgTemp]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_BUFFET": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_AERO_COEFF", + "HEADER": "tavg[Buffet]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_COMBO": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_COMBO", + "HEADER": "tavg[ComboObj]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_DELTA_CL": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_FIXED_CL", + "HEADER": "tavg[Delta_CL]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_DRAG": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_AERO_COEFF", + "HEADER": "tavg[CD]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_D_ADJOINT_SOLEXTRA": { + "DESCRIPTION": "weighted time average derivative " "value", + "GROUP": "TAVG_D_ADJOINT_SOLEXTRA", + "HEADER": "dtavg[Adjoint_SolExtra]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_AVG_DENSITY": { + "DESCRIPTION": "weighted time average derivative value", + "GROUP": "TAVG_D_FLOW_COEFF", + "HEADER": "dtavg[Avg_Density]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_AVG_ENTHALPY": { + "DESCRIPTION": "weighted time average derivative " "value", + "GROUP": "TAVG_D_FLOW_COEFF", + "HEADER": "dtavg[Avg_Enthalpy]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_AVG_NORMALVEL": { + "DESCRIPTION": "weighted time average derivative " "value", + "GROUP": "TAVG_D_FLOW_COEFF", + "HEADER": "dtavg[Avg_NormalVel]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_AVG_TEMPERATURE": { + "DESCRIPTION": "weighted time average derivative " "value", + "GROUP": "TAVG_D_HEAT", + "HEADER": "dtavg[AvgTemp]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_BUFFET": { + "DESCRIPTION": "weighted time average derivative value", + "GROUP": "TAVG_D_AERO_COEFF", + "HEADER": "dtavg[Buffet]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_COMBO": { + "DESCRIPTION": "weighted time average derivative value", + "GROUP": "TAVG_D_COMBO", + "HEADER": "dtavg[ComboObj]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_DELTA_CL": { + "DESCRIPTION": "weighted time average derivative value", + "GROUP": "TAVG_D_FIXED_CL", + "HEADER": "dtavg[Delta_CL]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_DRAG": { + "DESCRIPTION": "weighted time average derivative value", + "GROUP": "TAVG_D_AERO_COEFF", + "HEADER": "dtavg[CD]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_EFFICIENCY": { + "DESCRIPTION": "weighted time average derivative value", + "GROUP": "TAVG_D_AERO_COEFF", + "HEADER": "dtavg[CEff]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_EQUIVALENT_AREA": { + "DESCRIPTION": "weighted time average derivative " "value", + "GROUP": "TAVG_D_EQUIVALENT_AREA", + "HEADER": "dtavg[CEquiv_Area]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_FIGURE_OF_MERIT": { + "DESCRIPTION": "weighted time average derivative " "value", + "GROUP": "TAVG_D_ROTATING_FRAME", + "HEADER": "dtavg[CMerit]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_FORCE_X": { + "DESCRIPTION": "weighted time average derivative value", + "GROUP": "TAVG_D_AERO_COEFF", + "HEADER": "dtavg[CFx]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_FORCE_Y": { + "DESCRIPTION": "weighted time average derivative value", + "GROUP": "TAVG_D_AERO_COEFF", + "HEADER": "dtavg[CFy]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_FORCE_Z": { + "DESCRIPTION": "weighted time average derivative value", + "GROUP": "TAVG_D_AERO_COEFF", + "HEADER": "dtavg[CFz]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_INVERSE_DESIGN_PRESSURE": { + "DESCRIPTION": "weighted time average " "derivative value", + "GROUP": "TAVG_D_CP_DIFF", + "HEADER": "dtavg[Cp_Diff]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_LIFT": { + "DESCRIPTION": "weighted time average derivative value", + "GROUP": "TAVG_D_AERO_COEFF", + "HEADER": "dtavg[CL]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_MAXIMUM_HEATFLUX": { + "DESCRIPTION": "weighted time average derivative " "value", + "GROUP": "TAVG_D_HEAT", + "HEADER": "dtavg[MaxHF]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_MOMENT_X": { + "DESCRIPTION": "weighted time average derivative value", + "GROUP": "TAVG_D_AERO_COEFF", + "HEADER": "dtavg[CMx]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_MOMENT_Y": { + "DESCRIPTION": "weighted time average derivative value", + "GROUP": "TAVG_D_AERO_COEFF", + "HEADER": "dtavg[CMy]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_MOMENT_Z": { + "DESCRIPTION": "weighted time average derivative value", + "GROUP": "TAVG_D_AERO_COEFF", + "HEADER": "dtavg[CMz]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_REFERENCE_GEOMETRY": { + "DESCRIPTION": "weighted time average " "derivative value", + "GROUP": "TAVG_D_STRUCT_COEFF", + "HEADER": "dtavg[RefGeom]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_REFERENCE_NODE": { + "DESCRIPTION": "weighted time average derivative " "value", + "GROUP": "TAVG_D_STRUCT_COEFF", + "HEADER": "dtavg[RefNode]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_SENS_AOA": { + "DESCRIPTION": "weighted time average derivative value", + "GROUP": "TAVG_D_SENSITIVITY", + "HEADER": "dtavg[Sens_AoA]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_SENS_GEO": { + "DESCRIPTION": "weighted time average derivative value", + "GROUP": "TAVG_D_SENSITIVITY", + "HEADER": "dtavg[Sens_Geo]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_SENS_MACH": { + "DESCRIPTION": "weighted time average derivative value", + "GROUP": "TAVG_D_SENSITIVITY", + "HEADER": "dtavg[Sens_Mach]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_SENS_PRESS": { + "DESCRIPTION": "weighted time average derivative value", + "GROUP": "TAVG_D_SENSITIVITY", + "HEADER": "dtavg[Sens_Press]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_SENS_PRESS_OUT": { + "DESCRIPTION": "weighted time average derivative " "value", + "GROUP": "TAVG_D_SENSITIVITY", + "HEADER": "dtavg[Sens_Pout]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_SENS_TEMP": { + "DESCRIPTION": "weighted time average derivative value", + "GROUP": "TAVG_D_SENSITIVITY", + "HEADER": "dtavg[Sens_Temp]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_SENS_VEL_IN": { + "DESCRIPTION": "weighted time average derivative value", + "GROUP": "TAVG_D_SENSITIVITY", + "HEADER": "dtavg[Sens_Vin]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_SIDEFORCE": { + "DESCRIPTION": "weighted time average derivative value", + "GROUP": "TAVG_D_AERO_COEFF", + "HEADER": "dtavg[CSF]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_STRESS_PENALTY": { + "DESCRIPTION": "weighted time average derivative " "value", + "GROUP": "TAVG_D_STRUCT_COEFF", + "HEADER": "dtavg[StressPen]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_SURFACE_MACH": { + "DESCRIPTION": "weighted time average derivative " "value", + "GROUP": "TAVG_D_FLOW_COEFF", + "HEADER": "dtavg[Avg_Mach]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_SURFACE_MASSFLOW": { + "DESCRIPTION": "weighted time average derivative " "value", + "GROUP": "TAVG_D_FLOW_COEFF", + "HEADER": "dtavg[Avg_Massflow]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_SURFACE_MOM_DISTORTION": { + "DESCRIPTION": "weighted time average " "derivative value", + "GROUP": "TAVG_D_FLOW_COEFF", + "HEADER": "dtavg[Momentum_Distortion]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_SURFACE_PRESSURE_DROP": { + "DESCRIPTION": "weighted time average " "derivative value", + "GROUP": "TAVG_D_FLOW_COEFF", + "HEADER": "dtavg[Pressure_Drop]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_SURFACE_SECONDARY": { + "DESCRIPTION": "weighted time average derivative " "value", + "GROUP": "TAVG_D_FLOW_COEFF", + "HEADER": "dtavg[Secondary_Strength]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_SURFACE_SECOND_OVER_UNIFORM": { + "DESCRIPTION": "weighted time average " "derivative value", + "GROUP": "TAVG_D_FLOW_COEFF", + "HEADER": "dtavg[Secondary_Over_Uniformity]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + 'TAVG_D_SURFACE_SPECIES_" + std::to_string(iVar': { + "DESCRIPTION": "weighted " "time " "average " "derivative " "value", + "GROUP": "TAVG_D_SPECIES_COEFF", + "HEADER": 'dtavg[Avg_Species_" ' "+ " "std::to_string(iVar]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_SURFACE_STATIC_PRESSURE": { + "DESCRIPTION": "weighted time average " "derivative value", + "GROUP": "TAVG_D_FLOW_COEFF", + "HEADER": "dtavg[Avg_Press]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_SURFACE_STATIC_TEMPERATURE": { + "DESCRIPTION": "weighted time average " "derivative value", + "GROUP": "TAVG_D_FLOW_COEFF", + "HEADER": "dtavg[Avg_Temp]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_SURFACE_TOTAL_PRESSURE": { + "DESCRIPTION": "weighted time average " "derivative value", + "GROUP": "TAVG_D_FLOW_COEFF", + "HEADER": "dtavg[Avg_TotalPress]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_SURFACE_TOTAL_TEMPERATURE": { + "DESCRIPTION": "weighted time average " "derivative value", + "GROUP": "TAVG_D_FLOW_COEFF", + "HEADER": "dtavg[Avg_TotalTemp]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_SURFACE_UNIFORMITY": { + "DESCRIPTION": "weighted time average " "derivative value", + "GROUP": "TAVG_D_FLOW_COEFF", + "HEADER": "dtavg[Uniformity]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_THRUST": { + "DESCRIPTION": "weighted time average derivative value", + "GROUP": "TAVG_D_ROTATING_FRAME", + "HEADER": "dtavg[CT]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_TOPOL_COMPLIANCE": { + "DESCRIPTION": "weighted time average derivative " "value", + "GROUP": "TAVG_D_STRUCT_COEFF", + "HEADER": "dtavg[TopComp]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_TOPOL_DISCRETENESS": { + "DESCRIPTION": "weighted time average " "derivative value", + "GROUP": "TAVG_D_STRUCT_COEFF", + "HEADER": "dtavg[TopDisc]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_TORQUE": { + "DESCRIPTION": "weighted time average derivative value", + "GROUP": "TAVG_D_ROTATING_FRAME", + "HEADER": "dtavg[CQ]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_TOTAL_HEATFLUX": { + "DESCRIPTION": "weighted time average derivative " "value", + "GROUP": "TAVG_D_HEAT", + "HEADER": "dtavg[HF]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_D_VOLUME_FRACTION": { + "DESCRIPTION": "weighted time average derivative " "value", + "GROUP": "TAVG_D_STRUCT_COEFF", + "HEADER": "dtavg[VolFrac]", + "TYPE": "TAVG_D_COEFFICIENT", + }, + "TAVG_EFFICIENCY": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_AERO_COEFF", + "HEADER": "tavg[CEff]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_EQUIVALENT_AREA": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_EQUIVALENT_AREA", + "HEADER": "tavg[CEquiv_Area]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_FIGURE_OF_MERIT": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_ROTATING_FRAME", + "HEADER": "tavg[CMerit]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_FORCE_X": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_AERO_COEFF", + "HEADER": "tavg[CFx]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_FORCE_Y": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_AERO_COEFF", + "HEADER": "tavg[CFy]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_FORCE_Z": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_AERO_COEFF", + "HEADER": "tavg[CFz]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_INVERSE_DESIGN_PRESSURE": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_CP_DIFF", + "HEADER": "tavg[Cp_Diff]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_LIFT": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_AERO_COEFF", + "HEADER": "tavg[CL]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_MAXIMUM_HEATFLUX": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_HEAT", + "HEADER": "tavg[MaxHF]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_MOMENT_X": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_AERO_COEFF", + "HEADER": "tavg[CMx]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_MOMENT_Y": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_AERO_COEFF", + "HEADER": "tavg[CMy]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_MOMENT_Z": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_AERO_COEFF", + "HEADER": "tavg[CMz]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_REFERENCE_GEOMETRY": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_STRUCT_COEFF", + "HEADER": "tavg[RefGeom]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_REFERENCE_NODE": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_STRUCT_COEFF", + "HEADER": "tavg[RefNode]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_SENS_AOA": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_SENSITIVITY", + "HEADER": "tavg[Sens_AoA]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_SENS_GEO": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_SENSITIVITY", + "HEADER": "tavg[Sens_Geo]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_SENS_MACH": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_SENSITIVITY", + "HEADER": "tavg[Sens_Mach]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_SENS_PRESS": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_SENSITIVITY", + "HEADER": "tavg[Sens_Press]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_SENS_PRESS_OUT": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_SENSITIVITY", + "HEADER": "tavg[Sens_Pout]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_SENS_TEMP": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_SENSITIVITY", + "HEADER": "tavg[Sens_Temp]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_SENS_VEL_IN": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_SENSITIVITY", + "HEADER": "tavg[Sens_Vin]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_SIDEFORCE": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_AERO_COEFF", + "HEADER": "tavg[CSF]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_STRESS_PENALTY": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_STRUCT_COEFF", + "HEADER": "tavg[StressPen]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_SURFACE_MACH": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_FLOW_COEFF", + "HEADER": "tavg[Avg_Mach]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_SURFACE_MASSFLOW": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_FLOW_COEFF", + "HEADER": "tavg[Avg_Massflow]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_SURFACE_MOM_DISTORTION": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_FLOW_COEFF", + "HEADER": "tavg[Momentum_Distortion]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_SURFACE_PRESSURE_DROP": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_FLOW_COEFF", + "HEADER": "tavg[Pressure_Drop]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_SURFACE_SECONDARY": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_FLOW_COEFF", + "HEADER": "tavg[Secondary_Strength]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_SURFACE_SECOND_OVER_UNIFORM": { + "DESCRIPTION": "weighted time average " "value", + "GROUP": "TAVG_FLOW_COEFF", + "HEADER": "tavg[Secondary_Over_Uniformity]", + "TYPE": "TAVG_COEFFICIENT", + }, + 'TAVG_SURFACE_SPECIES_" + std::to_string(iVar': { + "DESCRIPTION": "weighted " "time average " "value", + "GROUP": "TAVG_SPECIES_COEFF", + "HEADER": 'tavg[Avg_Species_" ' "+ " "std::to_string(iVar]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_SURFACE_STATIC_PRESSURE": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_FLOW_COEFF", + "HEADER": "tavg[Avg_Press]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_SURFACE_STATIC_TEMPERATURE": { + "DESCRIPTION": "weighted time average " "value", + "GROUP": "TAVG_FLOW_COEFF", + "HEADER": "tavg[Avg_Temp]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_SURFACE_TOTAL_PRESSURE": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_FLOW_COEFF", + "HEADER": "tavg[Avg_TotalPress]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_SURFACE_TOTAL_TEMPERATURE": { + "DESCRIPTION": "weighted time average " "value", + "GROUP": "TAVG_FLOW_COEFF", + "HEADER": "tavg[Avg_TotalTemp]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_SURFACE_UNIFORMITY": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_FLOW_COEFF", + "HEADER": "tavg[Uniformity]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_THRUST": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_ROTATING_FRAME", + "HEADER": "tavg[CT]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_TOPOL_COMPLIANCE": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_STRUCT_COEFF", + "HEADER": "tavg[TopComp]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_TOPOL_DISCRETENESS": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_STRUCT_COEFF", + "HEADER": "tavg[TopDisc]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_TORQUE": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_ROTATING_FRAME", + "HEADER": "tavg[CQ]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_TOTAL_HEATFLUX": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_HEAT", + "HEADER": "tavg[HF]", + "TYPE": "TAVG_COEFFICIENT", + }, + "TAVG_VOLUME_FRACTION": { + "DESCRIPTION": "weighted time average value", + "GROUP": "TAVG_STRUCT_COEFF", + "HEADER": "tavg[VolFrac]", + "TYPE": "TAVG_COEFFICIENT", + }, + "THRUST": { + "DESCRIPTION": "Thrust coefficient", + "GROUP": "ROTATING_FRAME", + "HEADER": "CT", + "TYPE": "COEFFICIENT", + }, + "TOPOL_COMPLIANCE": { + "DESCRIPTION": "Structural compliance", + "GROUP": "STRUCT_COEFF", + "HEADER": "TopComp", + "TYPE": "COEFFICIENT", + }, + "TOPOL_DISCRETENESS": { + "DESCRIPTION": "Discreteness of the material " "distribution", + "GROUP": "STRUCT_COEFF", + "HEADER": "TopDisc", + "TYPE": "COEFFICIENT", + }, + "TORQUE": { + "DESCRIPTION": "Torque coefficient", + "GROUP": "ROTATING_FRAME", + "HEADER": "CQ", + "TYPE": "COEFFICIENT", + }, + "TOTAL_HEATFLUX": { + "DESCRIPTION": "Total heatflux on all surfaces defined in " "MARKER_MONITORING", + "GROUP": "HEAT", + "HEADER": "HF", + "TYPE": "COEFFICIENT", + }, + "VMS": { + "DESCRIPTION": "VMS", + "GROUP": "Maximum Von-Misses stress", + "HEADER": "VonMises", + "TYPE": "DEFAULT", + }, + "VOLUME_FRACTION": { + "DESCRIPTION": "Fraction of solid material", + "GROUP": "STRUCT_COEFF", + "HEADER": "VolFrac", + "TYPE": "COEFFICIENT", + }, +} diff --git a/SU2_PY/SU2/io/redirect.py b/SU2_PY/SU2/io/redirect.py index 9f2d4e4f4ac..b81a80d2e82 100644 --- a/SU2_PY/SU2/io/redirect.py +++ b/SU2_PY/SU2/io/redirect.py @@ -37,34 +37,35 @@ # ------------------------------------------------------------------- # original source: http://stackoverflow.com/questions/6796492/python-temporarily-redirect-stdout-stderr class output(object): - ''' with SU2.io.redirect_output(stdout,stderr) + """with SU2.io.redirect_output(stdout,stderr) - Temporarily redirects sys.stdout and sys.stderr when used in - a 'with' contextmanager + Temporarily redirects sys.stdout and sys.stderr when used in + a 'with' contextmanager - Example: - with SU2.io.redirect_output('stdout.txt','stderr.txt'): - sys.stdout.write("standard out") - sys.stderr.write("stanrard error") - # code - #: with output redirection + Example: + with SU2.io.redirect_output('stdout.txt','stderr.txt'): + sys.stdout.write("standard out") + sys.stderr.write("stanrard error") + # code + #: with output redirection - Inputs: - stdout - None, a filename, or a file stream - stderr - None, a filename, or a file stream - None will not redirect outptu + Inputs: + stdout - None, a filename, or a file stream + stderr - None, a filename, or a file stream + None will not redirect outptu + + """ - ''' def __init__(self, stdout=None, stderr=None): _newout = False _newerr = False - if isinstance(stdout,str): - stdout = open(stdout,'a') + if isinstance(stdout, str): + stdout = open(stdout, "a") _newout = True - if isinstance(stderr,str): - stderr = open(stderr,'a') + if isinstance(stderr, str): + stderr = open(stderr, "a") _newerr = True self._stdout = stdout or sys.stdout @@ -74,11 +75,13 @@ def __init__(self, stdout=None, stderr=None): def __enter__(self): self.old_stdout, self.old_stderr = sys.stdout, sys.stderr - self.old_stdout.flush(); self.old_stderr.flush() + self.old_stdout.flush() + self.old_stderr.flush() sys.stdout, sys.stderr = self._stdout, self._stderr def __exit__(self, exc_type, exc_value, traceback): - self._stdout.flush(); self._stderr.flush() + self._stdout.flush() + self._stderr.flush() sys.stdout = self.old_stdout sys.stderr = self.old_stderr @@ -87,6 +90,7 @@ def __exit__(self, exc_type, exc_value, traceback): if self._newerr: self._stderr.close() + #: class output() @@ -94,83 +98,87 @@ def __exit__(self, exc_type, exc_value, traceback): # Folder Redirection # ------------------------------------------------------------------- class folder(object): - ''' with SU2.io.redirect_folder(folder,pull,link,force) as push - - Temporarily redirects to a working folder, pulling - and pushing needed files + """with SU2.io.redirect_folder(folder,pull,link,force) as push - Example: + Temporarily redirects to a working folder, pulling + and pushing needed files - folder = 'temp' - pull = ['file1.txt','file2.txt'] - link = ['file3.big'] - force = True + Example: - # original path - import os - print(os.getcwd()) + folder = 'temp' + pull = ['file1.txt','file2.txt'] + link = ['file3.big'] + force = True - # enter folder - with SU2.io.redirect_folder(folder,pull,link,force) as push: - print(os.getcwd()) - # code - push.append('file4.txt') - #: with folder redirection + # original path + import os + print(os.getcwd()) - # returned to original path + # enter folder + with SU2.io.redirect_folder(folder,pull,link,force) as push: print(os.getcwd()) - - Inputs: - folder - working folder, relative or absolute - pull - list of files to pull (copy to working folder) - link - list of files to link (symbolic link in working folder) - force - True/False overwrite existing files in working folder - - Targets: - push - list of files to push (copy to originating path) - - Notes: - push must be appended or extended, not overwritten - links in Windows not supported, will simply copy - ''' - - def __init__(self, folder, pull=None, link=None, force=True ): - ''' folder redirection initialization - see help( folder ) for more info - ''' - - if pull is None: pull = [] - if link is None: link = [] - - if not isinstance(pull,list) : pull = [pull] - if not isinstance(link,list) : link = [link] + # code + push.append('file4.txt') + #: with folder redirection + + # returned to original path + print(os.getcwd()) + + Inputs: + folder - working folder, relative or absolute + pull - list of files to pull (copy to working folder) + link - list of files to link (symbolic link in working folder) + force - True/False overwrite existing files in working folder + + Targets: + push - list of files to push (copy to originating path) + + Notes: + push must be appended or extended, not overwritten + links in Windows not supported, will simply copy + """ + + def __init__(self, folder, pull=None, link=None, force=True): + """folder redirection initialization + see help( folder ) for more info + """ + + if pull is None: + pull = [] + if link is None: + link = [] + + if not isinstance(pull, list): + pull = [pull] + if not isinstance(link, list): + link = [link] origin = os.getcwd() - origin = os.path.abspath(origin).rstrip('/')+'/' - folder = os.path.abspath(folder).rstrip('/')+'/' + origin = os.path.abspath(origin).rstrip("/") + "/" + folder = os.path.abspath(folder).rstrip("/") + "/" self.origin = origin self.folder = folder - self.pull = copy.deepcopy(pull) - self.push = [] - self.link = copy.deepcopy(link) - self.force = force + self.pull = copy.deepcopy(pull) + self.push = [] + self.link = copy.deepcopy(link) + self.force = force def __enter__(self): origin = self.origin # absolute path folder = self.folder # absolute path - pull = self.pull - push = self.push - link = self.link - force = self.force + pull = self.pull + push = self.push + link = self.link + force = self.force # check for no folder change if folder == origin: return [] # relative folder path - #relative = os.path.relpath(folder,origin) + # relative = os.path.relpath(folder,origin) # check, make folder if not os.path.exists(folder): @@ -180,23 +188,29 @@ def __enter__(self): for name in pull: old_name = os.path.abspath(name) new_name = os.path.split(name)[-1] - new_name = os.path.join(folder,new_name) - if old_name == new_name: continue - if os.path.exists( new_name ): - if force: os.remove( new_name ) - else: continue - shutil.copy(old_name,new_name) + new_name = os.path.join(folder, new_name) + if old_name == new_name: + continue + if os.path.exists(new_name): + if force: + os.remove(new_name) + else: + continue + shutil.copy(old_name, new_name) # make links for name in link: old_name = os.path.abspath(name) new_name = os.path.split(name)[-1] - new_name = os.path.join(folder,new_name) - if old_name == new_name: continue - if os.path.exists( new_name ): - if force: os.remove( new_name ) - else: continue - make_link(old_name,new_name) + new_name = os.path.join(folder, new_name) + if old_name == new_name: + continue + if os.path.exists(new_name): + if force: + os.remove(new_name) + else: + continue + make_link(old_name, new_name) # change directory os.chdir(folder) @@ -208,8 +222,8 @@ def __exit__(self, exc_type, exc_value, traceback): origin = self.origin folder = self.folder - push = self.push - force = self.force + push = self.push + force = self.force # check for no folder change if folder == origin: @@ -220,26 +234,33 @@ def __exit__(self, exc_type, exc_value, traceback): old_name = os.path.abspath(name) name = os.path.split(name)[-1] - new_name = os.path.join(origin,name) + new_name = os.path.join(origin, name) # links if os.path.islink(old_name): source = os.path.realpath(old_name) - if source == new_name: continue - if os.path.exists( new_name ): - if force: os.remove( new_name ) - else: continue - make_link(source,new_name) + if source == new_name: + continue + if os.path.exists(new_name): + if force: + os.remove(new_name) + else: + continue + make_link(source, new_name) # moves else: - if old_name == new_name: continue - if os.path.exists( new_name ): - if force: os.remove( new_name ) - else: continue - shutil.move(old_name,new_name) + if old_name == new_name: + continue + if os.path.exists(new_name): + if force: + os.remove(new_name) + else: + continue + shutil.move(old_name, new_name) # change directory os.chdir(origin) + #: class folder() diff --git a/SU2_PY/SU2/io/state.py b/SU2_PY/SU2/io/state.py index 5350df9fdbc..3203c10a012 100644 --- a/SU2_PY/SU2/io/state.py +++ b/SU2_PY/SU2/io/state.py @@ -30,8 +30,17 @@ # ---------------------------------------------------------------------- import os, sys, shutil, copy, time -from ..io import expand_part, expand_zones, expand_time, get_adjointSuffix, add_suffix, \ - get_specialCases, Config, expand_multipoint, optnames_multi +from ..io import ( + expand_part, + expand_zones, + expand_time, + get_adjointSuffix, + add_suffix, + get_specialCases, + Config, + expand_multipoint, + optnames_multi, +) from ..util import bunch from ..util import ordered_bunch @@ -40,82 +49,92 @@ # State Factory # ---------------------------------------------------------------------- -def State_Factory(state=None,config=None): - """ state = SU2.io.State() - - Starts a state class, an extension of ordered_bunch(). - Stores data generated while traversing SU2 tool chain - - Fields: - FUNCTIONS - ordered bunch of objective function values - GRADIENTS - ordered bunch of gradient value lists - VARIABLES - ordered bunch of variables - FILES - ordered bunch of file types - HISTORY - ordered bunch of history information - - Fields can be accessed by item or attribute - ie: state['FUNCTIONS'] or state.FUNCTIONS - - Methods: - update() - updates self with another state - pullnlink() - returns files to pull and link - design_vector() - vectorizes design variables - find_files() - finds existing mesh and solutions - - Example of a filled state: - FUNCTIONS: - LIFT: 0.2353065809 - DRAG: 0.042149736 - SIDEFORCE: 0.0 - MOMENT_X: 0.0 - MOMENT_Y: 0.0 - MOMENT_Z: 0.046370243 - FORCE_X: 0.0370065195 - FORCE_Y: 0.2361700759 - FORCE_Z: 0.0 - EFFICIENCY: 5.5826347517 - GRADIENTS: - DRAG: [0.133697, 0.41473, 0.698497, (...) - VARIABLES: - DV_VALUE_NEW: [0.002, 0.002, 0.002, (...) - FILES: - MESH: mesh.su2 - DIRECT: solution_flow.dat - ADJOINT_DRAG: solution_adj_cd.dat - FLOW_META: flow.meta - MULTIPOINT_DIRECT: [solution_flow_point0.dat solution_flow_point1.dat, ...] - MULTIPOINT_ADJOINT_DRAG: [solution_adj_point0_cd.dat solution_adj_point1_cd.dat, ...] - MULTIPOINT_MESH_FILENAME: [mesh_0.su2, mesh_1.su2, ... ] - MULTIPOINT_FLOW_META: [flow_point0.meta, flow_point1.meta, ...] - HISTORY: - DIRECT: {ITERATION=[1.0, 2.0, 3.0, (...) - ADJOINT_DRAG: {ITERATION=[1.0, 2.0, 3.0, (...) - WND_CAUCHY_DATA: - TIME_ITER - UNST_ADJOINT_ITER - ITER_AVERAGE_OBJ + +def State_Factory(state=None, config=None): + """state = SU2.io.State() + + Starts a state class, an extension of ordered_bunch(). + Stores data generated while traversing SU2 tool chain + + Fields: + FUNCTIONS - ordered bunch of objective function values + GRADIENTS - ordered bunch of gradient value lists + VARIABLES - ordered bunch of variables + FILES - ordered bunch of file types + HISTORY - ordered bunch of history information + + Fields can be accessed by item or attribute + ie: state['FUNCTIONS'] or state.FUNCTIONS + + Methods: + update() - updates self with another state + pullnlink() - returns files to pull and link + design_vector() - vectorizes design variables + find_files() - finds existing mesh and solutions + + Example of a filled state: + FUNCTIONS: + LIFT: 0.2353065809 + DRAG: 0.042149736 + SIDEFORCE: 0.0 + MOMENT_X: 0.0 + MOMENT_Y: 0.0 + MOMENT_Z: 0.046370243 + FORCE_X: 0.0370065195 + FORCE_Y: 0.2361700759 + FORCE_Z: 0.0 + EFFICIENCY: 5.5826347517 + GRADIENTS: + DRAG: [0.133697, 0.41473, 0.698497, (...) + VARIABLES: + DV_VALUE_NEW: [0.002, 0.002, 0.002, (...) + FILES: + MESH: mesh.su2 + DIRECT: solution_flow.dat + ADJOINT_DRAG: solution_adj_cd.dat + FLOW_META: flow.meta + MULTIPOINT_DIRECT: [solution_flow_point0.dat solution_flow_point1.dat, ...] + MULTIPOINT_ADJOINT_DRAG: [solution_adj_point0_cd.dat solution_adj_point1_cd.dat, ...] + MULTIPOINT_MESH_FILENAME: [mesh_0.su2, mesh_1.su2, ... ] + MULTIPOINT_FLOW_META: [flow_point0.meta, flow_point1.meta, ...] + HISTORY: + DIRECT: {ITERATION=[1.0, 2.0, 3.0, (...) + ADJOINT_DRAG: {ITERATION=[1.0, 2.0, 3.0, (...) + WND_CAUCHY_DATA: + TIME_ITER + UNST_ADJOINT_ITER + ITER_AVERAGE_OBJ """ - if isinstance(state,Config) and not config: + if isinstance(state, Config) and not config: config = state state = None if not state is None: - assert isinstance(state,State) , 'input is must be a state instance' + assert isinstance(state, State), "input is must be a state instance" return state NewClass = State() - for key in ['FUNCTIONS','GRADIENTS','VARIABLES','FILES','HISTORY','WND_CAUCHY_DATA']: + for key in [ + "FUNCTIONS", + "GRADIENTS", + "VARIABLES", + "FILES", + "HISTORY", + "WND_CAUCHY_DATA", + ]: NewClass[key] = ordered_bunch() if config: NewClass.find_files(config) # WND_Convergence Data - NewClass['WND_CAUCHY_DATA'] = {'TIME_ITER': config['TIME_ITER'], - 'UNST_ADJOINT_ITER': config['UNST_ADJOINT_ITER'], - 'ITER_AVERAGE_OBJ': config['ITER_AVERAGE_OBJ']} + NewClass["WND_CAUCHY_DATA"] = { + "TIME_ITER": config["TIME_ITER"], + "UNST_ADJOINT_ITER": config["UNST_ADJOINT_ITER"], + "ITER_AVERAGE_OBJ": config["ITER_AVERAGE_OBJ"], + } return NewClass @@ -124,155 +143,157 @@ def State_Factory(state=None,config=None): # State Class # ---------------------------------------------------------------------- + class State(ordered_bunch): - """ state = SU2.io.state.State() + """state = SU2.io.state.State() - This is the State class that should be generated with the - Factory Function SU2.io.state.State_Factory() + This is the State class that should be generated with the + Factory Function SU2.io.state.State_Factory() - Parameters: - none, should be loaded with State_Factory() + Parameters: + none, should be loaded with State_Factory() - Methods: - update() - updates self with another state - pullnlink() - returns files to pull and link - design_vector() - vectorizes design variables - find_files() - finds existing mesh and solutions + Methods: + update() - updates self with another state + pullnlink() - returns files to pull and link + design_vector() - vectorizes design variables + find_files() - finds existing mesh and solutions """ _timestamp = 0 - def update(self,ztate): - """ Updates self given another state - """ + def update(self, ztate): + """Updates self given another state""" - if not ztate: return - assert isinstance(ztate,State) , 'must update with another State-type' + if not ztate: + return + assert isinstance(ztate, State), "must update with another State-type" for key in self.keys(): - if isinstance(ztate[key],dict): - self[key].update( ztate[key] ) + if isinstance(ztate[key], dict): + self[key].update(ztate[key]) elif ztate[key]: self[key] = ztate[key] self.set_timestamp() - def __repr__(self): return self.__str__() def __str__(self): - output = 'STATE:' + output = "STATE:" for k1, v1 in self.items(): - output += '\n %s:' % k1 - if isinstance(v1,dict): + output += "\n %s:" % k1 + if isinstance(v1, dict): for k2, v2 in v1.items(): - output += '\n %s: %s' % (k2,v2) + output += "\n %s: %s" % (k2, v2) else: - output += '\n %s' % v1 + output += "\n %s" % v1 return output - def pullnlink(self,config): - """ pull,link = SU2.io.State.pullnlink(config) - returns lists pull and link of files for folder - redirection, based on a given config + def pullnlink(self, config): + """pull,link = SU2.io.State.pullnlink(config) + returns lists pull and link of files for folder + redirection, based on a given config """ - pull = []; link = [] + pull = [] + link = [] # choose files to pull and link for key, value in self.FILES.items(): # link big files - if key == 'MESH': + if key == "MESH": # mesh (merged or partitioned) - value = expand_part(value,config) + value = expand_part(value, config) link.extend(value) - elif key == 'DIRECT': + elif key == "DIRECT": # direct solution - value = expand_zones(value,config) - value = expand_time(value,config) + value = expand_zones(value, config) + value = expand_time(value, config) link.extend(value) - elif 'ADJOINT_' in key and (not 'MULTIPOINT' in key): + elif "ADJOINT_" in key and (not "MULTIPOINT" in key): # adjoint solution - value = expand_zones(value,config) - value = expand_time(value,config) + value = expand_zones(value, config) + value = expand_time(value, config) link.extend(value) - elif 'MULTIPOINT' in key: + elif "MULTIPOINT" in key: # multipoint files - if key != 'MULTIPOINT_MESH_FILENAME': + if key != "MULTIPOINT_MESH_FILENAME": # DIRECT and ADJOINT files - value = expand_zones(value,config) - value = expand_time(value,config) + value = expand_zones(value, config) + value = expand_time(value, config) for elem in value: if elem: link.append(elem) - #elif key == 'STABILITY': - #pass + # elif key == 'STABILITY': + # pass # copy all other files else: pull.append(value) #: for each filename - return pull,link + return pull, link def design_vector(self): - """ vectorizes State.VARIABLES - """ + """vectorizes State.VARIABLES""" vector = [] for value in self.VARIABLES.values(): - if isinstance(value,dict): + if isinstance(value, dict): for v in value.values(): vector.append(v) - elif not isinstance(value,list): + elif not isinstance(value, list): value = [value] vector.extend(value) return vector - def find_files(self,config): - """ SU2.io.State.find_files(config) - finds mesh and solution files for a given config. - updates state.FILES with filenames. - files already logged in state are not overridden. - will ignore solutions if config.RESTART_SOL == 'NO'. + def find_files(self, config): + """SU2.io.State.find_files(config) + finds mesh and solution files for a given config. + updates state.FILES with filenames. + files already logged in state are not overridden. + will ignore solutions if config.RESTART_SOL == 'NO'. """ files = self.FILES - mesh_name = config.MESH_FILENAME - if config.get('READ_BINARY_RESTART', 'YES') == 'NO': - if not 'RESTART_ASCII' in config.get('OUTPUT_FILES',['RESTART']): - print ('RESTART_ASCII must be in OUTPUT_FILES if READ_BINARY_RESTART is set to NO') + mesh_name = config.MESH_FILENAME + if config.get("READ_BINARY_RESTART", "YES") == "NO": + if not "RESTART_ASCII" in config.get("OUTPUT_FILES", ["RESTART"]): + print( + "RESTART_ASCII must be in OUTPUT_FILES if READ_BINARY_RESTART is set to NO" + ) sys.exit() - direct_name = config.SOLUTION_FILENAME - adjoint_name = config.SOLUTION_ADJ_FILENAME + direct_name = config.SOLUTION_FILENAME + adjoint_name = config.SOLUTION_ADJ_FILENAME - if 'RESTART_ASCII' in config.get('OUTPUT_FILES', ['RESTART']): - direct_name = direct_name.split('.')[0] + '.csv' - adjoint_name = adjoint_name.split('.')[0] + '.csv' + if "RESTART_ASCII" in config.get("OUTPUT_FILES", ["RESTART"]): + direct_name = direct_name.split(".")[0] + ".csv" + adjoint_name = adjoint_name.split(".")[0] + ".csv" else: - direct_name = direct_name.split('.')[0] + '.dat' - adjoint_name = adjoint_name.split('.')[0] + '.dat' + direct_name = direct_name.split(".")[0] + ".dat" + adjoint_name = adjoint_name.split(".")[0] + ".dat" - targetea_name = 'TargetEA.dat' - targetcp_name = 'TargetCp.dat' - targetheatflux_name = 'TargetHeatFlux.dat' + targetea_name = "TargetEA.dat" + targetcp_name = "TargetCp.dat" + targetheatflux_name = "TargetHeatFlux.dat" adj_map = get_adjointSuffix() - restart = config.RESTART_SOL == 'YES' + restart = config.RESTART_SOL == "YES" special_cases = get_specialCases(config) - if config.get('OPT_OBJECTIVE'): - def_objs = config['OPT_OBJECTIVE'] + if config.get("OPT_OBJECTIVE"): + def_objs = config["OPT_OBJECTIVE"] objectives = def_objs.keys() multipoint = any(elem in optnames_multi for elem in objectives) else: multipoint = False - def register_file(label,filename): + def register_file(label, filename): if not label in files: - if label.split('_')[0] in ['DIRECT', 'ADJOINT']: + if label.split("_")[0] in ["DIRECT", "ADJOINT"]: names = expand_zones(filename, config) found = False for name in names: @@ -284,107 +305,121 @@ def register_file(label,filename): if found: files[label] = filename - print('Found: %s' % filename) + print("Found: %s" % filename) - elif label.split('_')[0] in ['MULTIPOINT']: + elif label.split("_")[0] in ["MULTIPOINT"]: # if multipoint, list of files needs to be added - file_list= []; + file_list = [] for name in filename: if os.path.exists(name): file_list.append(name) - print('Found: %s' % name) + print("Found: %s" % name) else: # if file doesn't exist, enter empty string as placeholder - file_list.append('') - # If even one of the multipoint files is found, add the list + file_list.append("") + # If even one of the multipoint files is found, add the list if any(file for file in file_list): files[label] = file_list else: if os.path.exists(filename): files[label] = filename - print('Found: %s' % filename) + print("Found: %s" % filename) else: - if label.split("_")[0] in ['DIRECT', 'ADJOINT']: + if label.split("_")[0] in ["DIRECT", "ADJOINT"]: for name in expand_zones(files[label], config): - assert os.path.exists(name), 'state expected file: %s' % filename - elif label.split('_')[0] in ['MULTIPOINT']: + assert os.path.exists(name), ( + "state expected file: %s" % filename + ) + elif label.split("_")[0] in ["MULTIPOINT"]: for name in expand_zones(files[label], config): if name: if not os.path.exists(name): - raise AssertionError('state expected file: %s' % name) + raise AssertionError("state expected file: %s" % name) else: - assert os.path.exists(files[label]) , 'state expected file: %s' % filename + assert os.path.exists(files[label]), ( + "state expected file: %s" % filename + ) + #: register_file() # mesh if multipoint: - mesh_list = [elem.strip() for elem in config['MULTIPOINT_MESH_FILENAME'].replace("(", "").replace(")", "").split(',')] + mesh_list = [ + elem.strip() + for elem in config["MULTIPOINT_MESH_FILENAME"] + .replace("(", "") + .replace(")", "") + .split(",") + ] if len(set(mesh_list)) > 1: # Only register MULTIPOINT_MESH_FILENAME if multiple meshes are specified - register_file('MULTIPOINT_MESH_FILENAME', mesh_list) + register_file("MULTIPOINT_MESH_FILENAME", mesh_list) mesh_name = mesh_list[0] - register_file('MESH',mesh_name) + register_file("MESH", mesh_name) # old style restart - if not 'RESTART_FILE_1' in files.keys(): + if not "RESTART_FILE_1" in files.keys(): # direct solutions if restart: - register_file('DIRECT',direct_name) + register_file("DIRECT", direct_name) if multipoint: - name_list = expand_multipoint(direct_name,config) - name_list = expand_zones(name_list,config) - register_file('MULTIPOINT_DIRECT',name_list) + name_list = expand_multipoint(direct_name, config) + name_list = expand_zones(name_list, config) + register_file("MULTIPOINT_DIRECT", name_list) # flow meta data file if restart: - register_file('FLOW_META','flow.meta') + register_file("FLOW_META", "flow.meta") if multipoint: - name_list = expand_multipoint('flow.meta',config) - register_file('MULTIPOINT_FLOW_META',name_list) + name_list = expand_multipoint("flow.meta", config) + register_file("MULTIPOINT_FLOW_META", name_list) # adjoint solutions if restart: for obj, suff in adj_map.items(): - ADJ_LABEL = 'ADJOINT_' + obj - adjoint_name_suffixed = add_suffix(adjoint_name,suff) - register_file(ADJ_LABEL,adjoint_name_suffixed) + ADJ_LABEL = "ADJOINT_" + obj + adjoint_name_suffixed = add_suffix(adjoint_name, suff) + register_file(ADJ_LABEL, adjoint_name_suffixed) if multipoint: - name_list = expand_zones(add_suffix(expand_multipoint(adjoint_name,config), suff), config) - multipoint_adj_name = 'MULTIPOINT_' + ADJ_LABEL + name_list = expand_zones( + add_suffix(expand_multipoint(adjoint_name, config), suff), + config, + ) + multipoint_adj_name = "MULTIPOINT_" + ADJ_LABEL register_file(multipoint_adj_name, name_list) # equivalent area - if 'EQUIV_AREA' in special_cases: - register_file('TARGET_EA',targetea_name) + if "EQUIV_AREA" in special_cases: + register_file("TARGET_EA", targetea_name) # pressure inverse design - if 'INV_DESIGN_CP' in special_cases: - register_file('TARGET_CP',targetcp_name) + if "INV_DESIGN_CP" in special_cases: + register_file("TARGET_CP", targetcp_name) # heat flux inverse design - if 'INV_DESIGN_HEATFLUX' in special_cases: - register_file('TARGET_HEATFLUX',targetheatflux_name) + if "INV_DESIGN_HEATFLUX" in special_cases: + register_file("TARGET_HEATFLUX", targetheatflux_name) return - def __setitem__(self,k,v): + def __setitem__(self, k, v): if self._initialized: self.set_timestamp() - super(State,self).__setitem__(k,v) + super(State, self).__setitem__(k, v) def set_timestamp(self): self._timestamp = time.time() def tic(self): - """ timestamp = State.tic() - returns the time that this state was last modified + """timestamp = State.tic() + returns the time that this state was last modified """ return self._timestamp - def toc(self,timestamp): - """ updated = State.toc(timestamp) - returns True if state was modified since last timestamp + def toc(self, timestamp): + """updated = State.toc(timestamp) + returns True if state was modified since last timestamp """ return self._timestamp > timestamp diff --git a/SU2_PY/SU2/io/tools.py b/SU2_PY/SU2/io/tools.py index 00a52e16cd2..52b51d9ae54 100755 --- a/SU2_PY/SU2/io/tools.py +++ b/SU2_PY/SU2/io/tools.py @@ -38,9 +38,10 @@ # Read SU2_DOT Gradient Values # ------------------------------------------------------------------- -def read_gradients( Grad_filename , scale = 1.0): - """ reads the raw gradients from the gradient file - returns a list of floats + +def read_gradients(Grad_filename, scale=1.0): + """reads the raw gradients from the gradient file + returns a list of floats """ # open file and skip first line @@ -58,6 +59,7 @@ def read_gradients( Grad_filename , scale = 1.0): return grad_vals + #: def read_gradients() @@ -65,34 +67,36 @@ def read_gradients( Grad_filename , scale = 1.0): # Read All Data from a Plot File # ------------------------------------------------------------------- -def read_plot( filename ): - """ reads a plot file - returns an ordered bunch with the headers for keys - and a list of each header's floats for values. + +def read_plot(filename): + """reads a plot file + returns an ordered bunch with the headers for keys + and a list of each header's floats for values. """ - extension = os.path.splitext( filename )[1] + extension = os.path.splitext(filename)[1] # open history file plot_file = open(filename) # title? line = plot_file.readline() - if line.startswith('TITLE'): - title = line.split('=')[1] .strip() # not used right now + if line.startswith("TITLE"): + title = line.split("=")[1].strip() # not used right now line = plot_file.readline() - if line.startswith('VARIABLES'): - line = plot_file.readline() + if line.startswith("VARIABLES"): + line = plot_file.readline() line = line.split(",") - Variables = [ x.strip().strip('"') for x in line ] + Variables = [x.strip().strip('"') for x in line] n_Vars = len(Variables) # initialize plot data dictionary plot_data = ordered_bunch.fromkeys(Variables) # must default each value to avoid pointer problems - for key in plot_data.keys(): plot_data[key] = [] + for key in plot_data.keys(): + plot_data[key] = [] # zone list zones = [] @@ -104,26 +108,26 @@ def read_plot( filename ): if not line: break - #zone? - if line.startswith('ZONE'): - zone = line.split('=')[1].strip('" ') + # zone? + if line.startswith("ZONE"): + zone = line.split("=")[1].strip('" ') zones.append(zone) continue # split line - line_data = line.strip().split(',') - line_data = [ float(x.strip()) for x in line_data ] + line_data = line.strip().split(",") + line_data = [float(x.strip()) for x in line_data] # store to dictionary for i_Var in range(n_Vars): this_variable = Variables[i_Var] - plot_data[this_variable] = plot_data[this_variable] + [ line_data[i_Var] ] + plot_data[this_variable] = plot_data[this_variable] + [line_data[i_Var]] #: for each line # check for number of zones if len(zones) > 1: - raise IOError('multiple zones not supported') + raise IOError("multiple zones not supported") # done plot_file.close() @@ -134,18 +138,19 @@ def read_plot( filename ): # Read All Data from History File # ------------------------------------------------------------------- -def read_history( History_filename, nZones = 1): - """ reads a history file - returns an ordered bunch with the history file headers for keys - and a list of each header's floats for values. - if header is an optimization objective, its name is mapped to - the optimization name. - Iter and Time(min) headers are mapped to ITERATION and TIME - respectively. + +def read_history(History_filename, nZones=1): + """reads a history file + returns an ordered bunch with the history file headers for keys + and a list of each header's floats for values. + if header is an optimization objective, its name is mapped to + the optimization name. + Iter and Time(min) headers are mapped to ITERATION and TIME + respectively. """ # read plot file - plot_data = read_plot( History_filename ) + plot_data = read_plot(History_filename) # initialize history data dictionary history_data = ordered_bunch() @@ -155,39 +160,41 @@ def read_history( History_filename, nZones = 1): var = key for field in historyOutFields: - if key == historyOutFields[field]['HEADER'] and nZones == 1: + if key == historyOutFields[field]["HEADER"] and nZones == 1: var = field - if key.split('[')[0] == historyOutFields[field]['HEADER'] and nZones > 1: - var = field + '[' + key.split('[')[1] + if key.split("[")[0] == historyOutFields[field]["HEADER"] and nZones > 1: + var = field + "[" + key.split("[")[1] history_data[var] = plot_data[key] return history_data -#: def read_history() +#: def read_history() # ------------------------------------------------------------------- # Define Dictionary Map for Header Names # ------------------------------------------------------------------- -def get_headerMap(nZones = 1): + +def get_headerMap(nZones=1): headerMap = dict() for outputField in historyOutFields: - headerMap[outputField] = historyOutFields[outputField]['HEADER'] + headerMap[outputField] = historyOutFields[outputField]["HEADER"] return headerMap -def getTurboPerfIndex(nZones = 1): - if int(nZones) > 1: - index = int(nZones) + int(int(nZones)/2.0) + 1 - else: - index = 1 - return index +def getTurboPerfIndex(nZones=1): + + if int(nZones) > 1: + index = int(nZones) + int(int(nZones) / 2.0) + 1 + else: + index = 1 + return index #: def get_headerMap() @@ -199,66 +206,71 @@ def getTurboPerfIndex(nZones = 1): #: optnames_stab -optnames_stab = [ "D_LIFT_D_ALPHA" , - "D_DRAG_D_ALPHA" , - "D_SIDEFORCE_D_ALPHA" , - "D_MOMENT_X_D_ALPHA" , - "D_MOMENT_Y_D_ALPHA" , - "D_MOMENT_Z_D_ALPHA" , - ] +optnames_stab = [ + "D_LIFT_D_ALPHA", + "D_DRAG_D_ALPHA", + "D_SIDEFORCE_D_ALPHA", + "D_MOMENT_X_D_ALPHA", + "D_MOMENT_Y_D_ALPHA", + "D_MOMENT_Z_D_ALPHA", +] #: Multipoint Optimizer Function Names # optnames_multi = ['{}_{}'.format('MULTIPOINT', a) for a in optnames_aero] -optnames_multi = [ "MULTIPOINT_LIFT" , - "MULTIPOINT_DRAG" , - "MULTIPOINT_SIDEFORCE" , - "MULTIPOINT_MOMENT_X" , - "MULTIPOINT_MOMENT_Y" , - "MULTIPOINT_MOMENT_Z" , - "MULTIPOINT_CUSTOM_OBJFUNC"] +optnames_multi = [ + "MULTIPOINT_LIFT", + "MULTIPOINT_DRAG", + "MULTIPOINT_SIDEFORCE", + "MULTIPOINT_MOMENT_X", + "MULTIPOINT_MOMENT_Y", + "MULTIPOINT_MOMENT_Z", + "MULTIPOINT_CUSTOM_OBJFUNC", +] # Geometric Optimizer Function Names -optnames_geo = [ "AIRFOIL_AREA" , - "AIRFOIL_THICKNESS" , - "AIRFOIL_CHORD" , - "AIRFOIL_LE_RADIUS" , - "AIRFOIL_TOC" , - "AIRFOIL_ALPHA" , - "FUSELAGE_VOLUME" , - "FUSELAGE_WETTED_AREA" , - "FUSELAGE_MIN_WIDTH" , - "FUSELAGE_MAX_WIDTH" , - "FUSELAGE_MIN_WATERLINE_WIDTH" , - "FUSELAGE_MAX_WATERLINE_WIDTH" , - "FUSELAGE_MIN_HEIGHT" , - "FUSELAGE_MAX_HEIGHT" , - "FUSELAGE_MAX_CURVATURE" , - "WING_VOLUME" , - "WING_MIN_THICKNESS" , - "WING_MAX_THICKNESS" , - "WING_MIN_CHORD" , - "WING_MAX_CHORD" , - "WING_MIN_LE_RADIUS" , - "WING_MAX_LE_RADIUS" , - "WING_MIN_TOC" , - "WING_MAX_TOC" , - "WING_OBJFUN_MIN_TOC" , - "WING_MAX_TWIST" , - "WING_MAX_CURVATURE" , - "WING_MAX_DIHEDRAL" , - "NACELLE_VOLUME" , - "NACELLE_MIN_THICKNESS" , - "NACELLE_MAX_THICKNESS" , - "NACELLE_MIN_CHORD" , - "NACELLE_MAX_CHORD" , - "NACELLE_MIN_LE_RADIUS" , - "NACELLE_MAX_LE_RADIUS" , - "NACELLE_MIN_TOC" , - "NACELLE_MAX_TOC" , - "NACELLE_OBJFUN_MIN_TOC" , - "NACELLE_MAX_TWIST" ] +optnames_geo = [ + "AIRFOIL_AREA", + "AIRFOIL_THICKNESS", + "AIRFOIL_CHORD", + "AIRFOIL_LE_RADIUS", + "AIRFOIL_TOC", + "AIRFOIL_ALPHA", + "FUSELAGE_VOLUME", + "FUSELAGE_WETTED_AREA", + "FUSELAGE_MIN_WIDTH", + "FUSELAGE_MAX_WIDTH", + "FUSELAGE_MIN_WATERLINE_WIDTH", + "FUSELAGE_MAX_WATERLINE_WIDTH", + "FUSELAGE_MIN_HEIGHT", + "FUSELAGE_MAX_HEIGHT", + "FUSELAGE_MAX_CURVATURE", + "WING_VOLUME", + "WING_MIN_THICKNESS", + "WING_MAX_THICKNESS", + "WING_MIN_CHORD", + "WING_MAX_CHORD", + "WING_MIN_LE_RADIUS", + "WING_MAX_LE_RADIUS", + "WING_MIN_TOC", + "WING_MAX_TOC", + "WING_OBJFUN_MIN_TOC", + "WING_MAX_TWIST", + "WING_MAX_CURVATURE", + "WING_MAX_DIHEDRAL", + "NACELLE_VOLUME", + "NACELLE_MIN_THICKNESS", + "NACELLE_MAX_THICKNESS", + "NACELLE_MIN_CHORD", + "NACELLE_MAX_CHORD", + "NACELLE_MIN_LE_RADIUS", + "NACELLE_MAX_LE_RADIUS", + "NACELLE_MIN_TOC", + "NACELLE_MAX_TOC", + "NACELLE_OBJFUN_MIN_TOC", + "NACELLE_MAX_TWIST", +] PerStation = [] for i in range(20): @@ -278,16 +290,18 @@ def getTurboPerfIndex(nZones = 1): #: optnames_geo # per-surface functions -per_surface_map = {"LIFT" : "CL" , - "DRAG" : "CD" , - "SIDEFORCE" : "CSF" , - "MOMENT_X" : "CMx" , - "MOMENT_Y" : "CMy" , - "MOMENT_Z" : "CMz" , - "FORCE_X" : "CFx" , - "FORCE_Y" : "CFy" , - "FORCE_Z" : "CFz" , - "EFFICIENCY" : "CL/CD" } +per_surface_map = { + "LIFT": "CL", + "DRAG": "CD", + "SIDEFORCE": "CSF", + "MOMENT_X": "CMx", + "MOMENT_Y": "CMy", + "MOMENT_Z": "CMz", + "FORCE_X": "CFx", + "FORCE_Y": "CFy", + "FORCE_Z": "CFz", + "EFFICIENCY": "CL/CD", +} # ------------------------------------------------------------------- # Include per-surface output from History File @@ -297,29 +311,35 @@ def update_persurface(config, state): header_map = get_headerMap() for base in per_surface_map: base2 = per_surface_map[base] - for marker in config['MARKER_MONITORING']: - if not (base2+'_'+marker) in header_map: - header_map[base2+'_'+marker] = base2+'_'+marker + for marker in config["MARKER_MONITORING"]: + if not (base2 + "_" + marker) in header_map: + header_map[base2 + "_" + marker] = base2 + "_" + marker # Update the function values in state to include the per-surface quantities - if 'DIRECT' in state['HISTORY']: + if "DIRECT" in state["HISTORY"]: for base in per_surface_map: base2 = per_surface_map[base] - for marker in config['MARKER_MONITORING']: - if (base2+'_'+marker) in state['HISTORY']['DIRECT']: - state['FUNCTIONS'][base2+'_'+marker] = state['HISTORY']['DIRECT'][base2+'_'+marker][-1] + for marker in config["MARKER_MONITORING"]: + if (base2 + "_" + marker) in state["HISTORY"]["DIRECT"]: + state["FUNCTIONS"][base2 + "_" + marker] = state["HISTORY"][ + "DIRECT" + ][base2 + "_" + marker][-1] + # ------------------------------------------------------------------- # Read Aerodynamic Function Values from History File # ------------------------------------------------------------------- -def read_aerodynamics( History_filename , nZones = 1, special_cases=[], final_avg=0, wnd_fct = 'SQUARE' ): - """ values = read_aerodynamics(historyname, special_cases=[]) - read aerodynamic function values from history file - Outputs: - dictionary with function keys and thier values - if special cases has 'TIME_MARCHING', returns time averaged data - otherwise returns final value from history file +def read_aerodynamics( + History_filename, nZones=1, special_cases=[], final_avg=0, wnd_fct="SQUARE" +): + """values = read_aerodynamics(historyname, special_cases=[]) + read aerodynamic function values from history file + + Outputs: + dictionary with function keys and thier values + if special cases has 'TIME_MARCHING', returns time averaged data + otherwise returns final value from history file """ # read the history data @@ -330,69 +350,101 @@ def read_aerodynamics( History_filename , nZones = 1, special_cases=[], final_av for this_objfun in historyOutFields: if nZones == 1: if this_objfun in history_data: - if historyOutFields[this_objfun]['TYPE'] == 'COEFFICIENT' or historyOutFields[this_objfun]['TYPE'] == 'D_COEFFICIENT': + if ( + historyOutFields[this_objfun]["TYPE"] == "COEFFICIENT" + or historyOutFields[this_objfun]["TYPE"] == "D_COEFFICIENT" + ): Func_Values[this_objfun] = history_data[this_objfun] else: for iZone in range(nZones): - if this_objfun + '[' + str(iZone) + ']' in history_data: - if historyOutFields[this_objfun]['TYPE'] == 'COEFFICIENT' or historyOutFields[this_objfun]['TYPE'] == 'D_COEFFICIENT': - Func_Values[this_objfun + '[' + str(iZone) + ']'] = history_data[this_objfun + '[' + str(iZone) + ']'] - - if 'TIME_MARCHING' in special_cases: + if this_objfun + "[" + str(iZone) + "]" in history_data: + if ( + historyOutFields[this_objfun]["TYPE"] == "COEFFICIENT" + or historyOutFields[this_objfun]["TYPE"] == "D_COEFFICIENT" + ): + Func_Values[ + this_objfun + "[" + str(iZone) + "]" + ] = history_data[this_objfun + "[" + str(iZone) + "]"] + + if "TIME_MARCHING" in special_cases: # for unsteady cases, average time-accurate objective function values for key, value in Func_Values.items(): - if historyOutFields[key]['TYPE'] == 'COEFFICIENT': - if not history_data.get('TAVG_'+ key): - raise KeyError('Key ' + historyOutFields['TAVG_'+ key]['HEADER'] + ' was not found in history output.') - Func_Values[key] = history_data['TAVG_'+ key][-1] - elif historyOutFields[key]['TYPE'] == 'D_COEFFICIENT': - if not history_data.get('TAVG_' + key): - raise KeyError('Key ' + historyOutFields['TAVG_' + key]['HEADER'] + ' was not found in history output.') - Func_Values[key] = history_data['TAVG_' + key][-1] + if historyOutFields[key]["TYPE"] == "COEFFICIENT": + if not history_data.get("TAVG_" + key): + raise KeyError( + "Key " + + historyOutFields["TAVG_" + key]["HEADER"] + + " was not found in history output." + ) + Func_Values[key] = history_data["TAVG_" + key][-1] + elif historyOutFields[key]["TYPE"] == "D_COEFFICIENT": + if not history_data.get("TAVG_" + key): + raise KeyError( + "Key " + + historyOutFields["TAVG_" + key]["HEADER"] + + " was not found in history output." + ) + Func_Values[key] = history_data["TAVG_" + key][-1] else: # in steady cases take only last value. for key, value in Func_Values.iteritems(): if not history_data.get(key): - raise KeyError('Key ' + historyOutFields[key]['HEADER'] + ' was not found in history output.') + raise KeyError( + "Key " + + historyOutFields[key]["HEADER"] + + " was not found in history output." + ) Func_Values[key] = value[-1] return Func_Values + #: def read_aerodynamics() # ------------------------------------------------------------------- # Get Objective Function Sign # ------------------------------------------------------------------- -def get_objectiveSign( ObjFun_name ): - """ returns -1 for maximization problems: - LIFT - EFFICIENCY - THRUST - FIGURE_OF_MERIT - MASS_FLOW_RATE - SURFACE_TOTAL_PRESSURE - SURFACE_STATIC_PRESSURE - SURFACE_MASSFLOW - SURFACE_MACH - TOTAL_STATIC_EFFICIENCY - returns +1 otherwise + +def get_objectiveSign(ObjFun_name): + """returns -1 for maximization problems: + LIFT + EFFICIENCY + THRUST + FIGURE_OF_MERIT + MASS_FLOW_RATE + SURFACE_TOTAL_PRESSURE + SURFACE_STATIC_PRESSURE + SURFACE_MASSFLOW + SURFACE_MACH + TOTAL_STATIC_EFFICIENCY + returns +1 otherwise """ # flip sign for maximization problems - if ObjFun_name == "LIFT" : return -1.0 - if ObjFun_name == "EFFICIENCY" : return -1.0 - if ObjFun_name == "THRUST" : return -1.0 - if ObjFun_name == "FIGURE_OF_MERIT" : return -1.0 - if ObjFun_name == "SURFACE_TOTAL_PRESSURE" : return -1.0 - if ObjFun_name == "SURFACE_STATIC_PRESSURE" : return -1.0 - if ObjFun_name == "SURFACE_MASSFLOW" : return -1.0 - if ObjFun_name == "SURFACE_MACH" : return -1.0 - if ObjFun_name == "TOTAL_STATIC_EFFICIENCY" :return -1.0 + if ObjFun_name == "LIFT": + return -1.0 + if ObjFun_name == "EFFICIENCY": + return -1.0 + if ObjFun_name == "THRUST": + return -1.0 + if ObjFun_name == "FIGURE_OF_MERIT": + return -1.0 + if ObjFun_name == "SURFACE_TOTAL_PRESSURE": + return -1.0 + if ObjFun_name == "SURFACE_STATIC_PRESSURE": + return -1.0 + if ObjFun_name == "SURFACE_MASSFLOW": + return -1.0 + if ObjFun_name == "SURFACE_MACH": + return -1.0 + if ObjFun_name == "TOTAL_STATIC_EFFICIENCY": + return -1.0 # otherwise return 1.0 + #: def get_objectiveSign() @@ -400,16 +452,17 @@ def get_objectiveSign( ObjFun_name ): # Get Constraint Sign # ------------------------------------------------------------------- -def get_constraintSign( sign ): - """ gets +/-1 given a constraint sign < or > respectively - inequality constraint is posed as c(x) < 0 + +def get_constraintSign(sign): + """gets +/-1 given a constraint sign < or > respectively + inequality constraint is posed as c(x) < 0 """ - sign_map = { '>' : -1.0 , - '<' : +1.0 } - assert not sign=='=' , 'Sign "=" not valid' + sign_map = {">": -1.0, "<": +1.0} + assert not sign == "=", 'Sign "=" not valid' return sign_map[sign] + #: def get_constraintSign() @@ -417,68 +470,72 @@ def get_constraintSign( sign ): # Get Adjoint Filename Suffix # ------------------------------------------------------------------- + def get_adjointSuffix(objective_function=None): - """ gets the adjoint suffix given an objective function """ + """gets the adjoint suffix given an objective function""" # adjoint name map - name_map = { "DRAG" : "cd" , - "LIFT" : "cl" , - "SIDEFORCE" : "csf" , - "MOMENT_X" : "cmx" , - "MOMENT_Y" : "cmy" , - "MOMENT_Z" : "cmz" , - "FORCE_X" : "cfx" , - "FORCE_Y" : "cfy" , - "FORCE_Z" : "cfz" , - "EFFICIENCY" : "eff" , - "INVERSE_DESIGN_PRESSURE" : "invpress" , - "INVERSE_DESIGN_HEAT" : "invheat" , - "MAXIMUM_HEATFLUX" : "maxheat" , - "TOTAL_HEATFLUX" : "totheat" , - "EQUIVALENT_AREA" : "ea" , - "NEARFIELD_PRESSURE" : "nfp" , - "THRUST" : "ct" , - "TORQUE" : "cq" , - "FIGURE_OF_MERIT" : "merit" , - "BUFFET" : "buffet" , - "SURFACE_TOTAL_PRESSURE" : "pt" , - "SURFACE_STATIC_PRESSURE" : "pe" , - "SURFACE_MASSFLOW" : "mfr" , - "SURFACE_MACH" : "mach" , - "SURFACE_UNIFORMITY" : "uniform" , - "SURFACE_SECONDARY" : "second" , - "SURFACE_MOM_DISTORTION" : "distort" , - "SURFACE_SECOND_OVER_UNIFORM" : "sou" , - "SURFACE_PRESSURE_DROP" : "dp" , - "CUSTOM_OBJFUNC" : "custom" , - "KINETIC_ENERGY_LOSS" : "ke" , - "TOTAL_PRESSURE_LOSS" : "pl" , - "ENTROPY_GENERATION" : "entg" , - "EULERIAN_WORK" : "ew" , - "FLOW_ANGLE_OUT" : "fao" , - "FLOW_ANGLE_IN" : "fai" , - "MASS_FLOW_OUT" : "mfo" , - "MASS_FLOW_IN" : "mfi" , - "TOTAL_EFFICIENCY" : "teff" , - "TOTAL_STATIC_EFFICIENCY" : "tseff" , - "COMBO" : "combo"} + name_map = { + "DRAG": "cd", + "LIFT": "cl", + "SIDEFORCE": "csf", + "MOMENT_X": "cmx", + "MOMENT_Y": "cmy", + "MOMENT_Z": "cmz", + "FORCE_X": "cfx", + "FORCE_Y": "cfy", + "FORCE_Z": "cfz", + "EFFICIENCY": "eff", + "INVERSE_DESIGN_PRESSURE": "invpress", + "INVERSE_DESIGN_HEAT": "invheat", + "MAXIMUM_HEATFLUX": "maxheat", + "TOTAL_HEATFLUX": "totheat", + "EQUIVALENT_AREA": "ea", + "NEARFIELD_PRESSURE": "nfp", + "THRUST": "ct", + "TORQUE": "cq", + "FIGURE_OF_MERIT": "merit", + "BUFFET": "buffet", + "SURFACE_TOTAL_PRESSURE": "pt", + "SURFACE_STATIC_PRESSURE": "pe", + "SURFACE_MASSFLOW": "mfr", + "SURFACE_MACH": "mach", + "SURFACE_UNIFORMITY": "uniform", + "SURFACE_SECONDARY": "second", + "SURFACE_MOM_DISTORTION": "distort", + "SURFACE_SECOND_OVER_UNIFORM": "sou", + "SURFACE_PRESSURE_DROP": "dp", + "CUSTOM_OBJFUNC": "custom", + "KINETIC_ENERGY_LOSS": "ke", + "TOTAL_PRESSURE_LOSS": "pl", + "ENTROPY_GENERATION": "entg", + "EULERIAN_WORK": "ew", + "FLOW_ANGLE_OUT": "fao", + "FLOW_ANGLE_IN": "fai", + "MASS_FLOW_OUT": "mfo", + "MASS_FLOW_IN": "mfi", + "TOTAL_EFFICIENCY": "teff", + "TOTAL_STATIC_EFFICIENCY": "tseff", + "COMBO": "combo", + } # if none or false, return map if not objective_function: return name_map else: # remove white space - objective = ''.join(objective_function.split()) + objective = "".join(objective_function.split()) objective = objective.split(",") nObj = len(objective) - if (nObj>1): + if nObj > 1: return "combo" if objective[0] in name_map: return name_map[objective[0]] # otherwise... else: - raise Exception('Unrecognized adjoint function name') + raise Exception("Unrecognized adjoint function name") + #: def get_adjointSuffix() @@ -486,388 +543,483 @@ def get_adjointSuffix(objective_function=None): # Add a Suffix # ------------------------------------------------------------------- -def add_suffix(base_name,suffix): - """ suffix_name = add_suffix(base_name,suffix) - adds suffix to a filename, accounting for file type extension - example: - base_name = 'input.txt' - suffix = 'new' - suffix_name = 'input_new.txt' + +def add_suffix(base_name, suffix): + """suffix_name = add_suffix(base_name,suffix) + adds suffix to a filename, accounting for file type extension + example: + base_name = 'input.txt' + suffix = 'new' + suffix_name = 'input_new.txt' """ if isinstance(base_name, list): suffix_name = [] for name in base_name: name_split = os.path.splitext(name) - suffix_name.append(name_split[0] + '_' + suffix + name_split[1]) + suffix_name.append(name_split[0] + "_" + suffix + name_split[1]) else: base_name = os.path.splitext(base_name) - suffix_name = base_name[0] + '_' + suffix + base_name[1] + suffix_name = base_name[0] + "_" + suffix + base_name[1] return suffix_name -#: def add_suffix() +#: def add_suffix() # ------------------------------------------------------------------- # Get Design Variable ID Map # ------------------------------------------------------------------- + def get_dvMap(): - """ get dictionary that maps design variable - kind id number to name """ - dv_map = { 0 : "NO_DEFORMATION" , - 1 : "TRANSLATION" , - 2 : "ROTATION" , - 3 : "SCALE" , - 10 : "FFD_SETTING" , - 11 : "FFD_CONTROL_POINT" , - 12 : "FFD_NACELLE" , - 13 : "FFD_GULL" , - 14 : "FFD_CAMBER" , - 15 : "FFD_TWIST" , - 16 : "FFD_THICKNESS" , - 18 : "FFD_ROTATION" , - 19 : "FFD_CONTROL_POINT_2D" , - 20 : "FFD_CAMBER_2D" , - 21 : "FFD_THICKNESS_2D" , - 22 : "FFD_TWIST_2D" , - 23 : "FFD_CONTROL_SURFACE" , - 24 : "FFD_ANGLE_OF_ATTACK" , - 30 : "HICKS_HENNE" , - 31 : "PARABOLIC" , - 32 : "NACA_4DIGITS" , - 33 : "AIRFOIL" , - 34 : "CST" , - 35 : "SURFACE_BUMP" , - 36 : "SURFACE_FILE" , - 40 : "DV_EFIELD" , - 41 : "DV_YOUNG" , - 42 : "DV_POISSON" , - 43 : "DV_RHO" , - 44 : "DV_RHO_DL" , - 50 : "TRANSLATE_GRID" , - 51 : "ROTATE_GRID" , - 52 : "SCALE_GRID" , - 101 : "ANGLE_OF_ATTACK" } + """get dictionary that maps design variable + kind id number to name""" + dv_map = { + 0: "NO_DEFORMATION", + 1: "TRANSLATION", + 2: "ROTATION", + 3: "SCALE", + 10: "FFD_SETTING", + 11: "FFD_CONTROL_POINT", + 12: "FFD_NACELLE", + 13: "FFD_GULL", + 14: "FFD_CAMBER", + 15: "FFD_TWIST", + 16: "FFD_THICKNESS", + 18: "FFD_ROTATION", + 19: "FFD_CONTROL_POINT_2D", + 20: "FFD_CAMBER_2D", + 21: "FFD_THICKNESS_2D", + 22: "FFD_TWIST_2D", + 23: "FFD_CONTROL_SURFACE", + 24: "FFD_ANGLE_OF_ATTACK", + 30: "HICKS_HENNE", + 31: "PARABOLIC", + 32: "NACA_4DIGITS", + 33: "AIRFOIL", + 34: "CST", + 35: "SURFACE_BUMP", + 36: "SURFACE_FILE", + 40: "DV_EFIELD", + 41: "DV_YOUNG", + 42: "DV_POISSON", + 43: "DV_RHO", + 44: "DV_RHO_DL", + 50: "TRANSLATE_GRID", + 51: "ROTATE_GRID", + 52: "SCALE_GRID", + 101: "ANGLE_OF_ATTACK", + } return dv_map + #: def get_dvMap() # ------------------------------------------------------------------- # Get Design Variable Kind Name from ID # ------------------------------------------------------------------- -def get_dvKind( kindID ): - """ get design variable kind name from id number """ +def get_dvKind(kindID): + """get design variable kind name from id number""" dv_map = get_dvMap() try: - return dv_map[ kindID ] + return dv_map[kindID] except KeyError: - raise Exception('Unrecognized Design Variable ID') + raise Exception("Unrecognized Design Variable ID") + + # def get_dvKind() # ------------------------------------------------------------------- # Get Design Variable Kind ID from Name # ------------------------------------------------------------------- -def get_dvID( kindName ): - """ get design variable kind id number from name """ +def get_dvID(kindName): + """get design variable kind id number from name""" dv_map = get_dvMap() - id_map = dict((v,k) for (k,v) in dv_map.items()) + id_map = dict((v, k) for (k, v) in dv_map.items()) try: - return id_map[ kindName ] + return id_map[kindName] except KeyError: - raise Exception('Unrecognized Design Variable Name: %s' , kindName) -#: def get_dvID() + raise Exception("Unrecognized Design Variable Name: %s", kindName) +#: def get_dvID() + # ------------------------------------------------------------------- # Get Gradient File Header # ------------------------------------------------------------------- -def get_gradFileFormat(grad_type,plot_format,kindID,special_cases=[]): + +def get_gradFileFormat(grad_type, plot_format, kindID, special_cases=[]): # start header, build a list of strings and join at the end - header = [] + header = [] write_format = [] # handle plot formating - if (plot_format == 'TECPLOT'): - header.append('VARIABLES=') - elif (plot_format == 'CSV'): + if plot_format == "TECPLOT": + header.append("VARIABLES=") + elif plot_format == "CSV": pass - else: raise Exception('output plot format not recognized') + else: + raise Exception("output plot format not recognized") # Case: continuous adjoint - if grad_type == 'CONTINUOUS_ADJOINT': + if grad_type == "CONTINUOUS_ADJOINT": header.append(r'"iVar","Gradient","FinDiff_Step"') - write_format.append(r'%4d, %.10f, %f') + write_format.append(r"%4d, %.10f, %f") # Case: finite difference - elif grad_type == 'FINITE_DIFFERENCE': - header.append(r'"iVar","Grad_CL","Grad_CD","Grad_CSF","Grad_CMx","Grad_CMy","Grad_CMz","Grad_CFx","Grad_CFy","Grad_CFz","Grad_CL/CD","Grad_Custom_ObjFunc","Grad_HeatFlux_Total","Grad_HeatFlux_Maximum","Grad_Temperature_Total"') - write_format.append(r'%4d, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f') + elif grad_type == "FINITE_DIFFERENCE": + header.append( + r'"iVar","Grad_CL","Grad_CD","Grad_CSF","Grad_CMx","Grad_CMy","Grad_CMz","Grad_CFx","Grad_CFy","Grad_CFz","Grad_CL/CD","Grad_Custom_ObjFunc","Grad_HeatFlux_Total","Grad_HeatFlux_Maximum","Grad_Temperature_Total"' + ) + write_format.append( + r"%4d, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f" + ) for key in special_cases: - if key == "ROTATING_FRAME" : + if key == "ROTATING_FRAME": header.append(r',"Grad_CMerit","Grad_CT","Grad_CQ"') write_format.append(", %.10f, %.10f, %.10f") - if key == "EQUIV_AREA" : + if key == "EQUIV_AREA": header.append(r',"Grad_CEquivArea","Grad_CNearFieldOF"') write_format.append(", %.10f, %.10f") - if key == "ENGINE" : - header.append(r',"Grad_AeroCDrag","Grad_SolidCDrag","Grad_Radial_Distortion","Grad_Circumferential_Distortion"') + if key == "ENGINE": + header.append( + r',"Grad_AeroCDrag","Grad_SolidCDrag","Grad_Radial_Distortion","Grad_Circumferential_Distortion"' + ) write_format.append(", %.10f, %.10f, %.10f, %.10f") - if key == "1D_OUTPUT" : - header.append(r',"Grad_Avg_TotalPress","Grad_Avg_Mach","Grad_Avg_Temperature","Grad_MassFlowRate","Grad_Avg_Pressure","Grad_Avg_Density","Grad_Avg_Velocity","Grad_Avg_Enthalpy"') - write_format.append(", %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f") - if key == "INV_DESIGN_CP" : + if key == "1D_OUTPUT": + header.append( + r',"Grad_Avg_TotalPress","Grad_Avg_Mach","Grad_Avg_Temperature","Grad_MassFlowRate","Grad_Avg_Pressure","Grad_Avg_Density","Grad_Avg_Velocity","Grad_Avg_Enthalpy"' + ) + write_format.append( + ", %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f" + ) + if key == "INV_DESIGN_CP": header.append(r',"Grad_Cp_Diff"') write_format.append(", %.10f") - if key == "INV_DESIGN_HEATFLUX" : + if key == "INV_DESIGN_HEATFLUX": header.append(r',"Grad_HeatFlux_Diff"') write_format.append(", %.10f") # otherwise... - else: raise Exception('Unrecognized Gradient Type') + else: + raise Exception("Unrecognized Gradient Type") # design variable parameters - if kindID == "FFD_CONTROL_POINT_2D" : + if kindID == "FFD_CONTROL_POINT_2D": header.append(r',"FFD_Box_ID","xIndex","yIndex","xAxis","yAxis"') - write_format.append(r', %s, %s, %s, %s, %s') - elif kindID == "FFD_CAMBER_2D" : + write_format.append(r", %s, %s, %s, %s, %s") + elif kindID == "FFD_CAMBER_2D": header.append(r',"FFD_Box_ID","xIndex"') - write_format.append(r', %s, %s') - elif kindID == "FFD_THICKNESS_2D" : + write_format.append(r", %s, %s") + elif kindID == "FFD_THICKNESS_2D": header.append(r',"FFD_Box_ID","xIndex"') - write_format.append(r', %s, %s') - elif kindID == "HICKS_HENNE" : + write_format.append(r", %s, %s") + elif kindID == "HICKS_HENNE": header.append(r',"Up/Down","Loc_Max"') - write_format.append(r', %s, %s') - elif kindID == "SURFACE_BUMP" : + write_format.append(r", %s, %s") + elif kindID == "SURFACE_BUMP": header.append(r',"Loc_Start","Loc_End","Loc_Max"') - write_format.append(r', %s, %s, %s') - elif kindID == "CST" : + write_format.append(r", %s, %s, %s") + elif kindID == "CST": header.append(r',"Up/Down","Kulfan number", "Total Kulfan numbers"') - write_format.append(r', %s, %s', '%s') - elif kindID == "FAIRING" : + write_format.append(r", %s, %s", "%s") + elif kindID == "FAIRING": header.append(r',"ControlPoint_Index","Theta_Disp","R_Disp"') - write_format.append(r', %s, %s, %s') - elif kindID == "NACA_4DIGITS" : + write_format.append(r", %s, %s, %s") + elif kindID == "NACA_4DIGITS": header.append(r',"1st_digit","2nd_digit","3rd&4th_digits"') - write_format.append(r', %s, %s, %s') - elif kindID == "TRANSLATION" : + write_format.append(r", %s, %s, %s") + elif kindID == "TRANSLATION": header.append(r',"x_Disp","y_Disp","z_Disp"') - write_format.append(r', %s, %s, %s') - elif kindID == "ROTATION" : + write_format.append(r", %s, %s, %s") + elif kindID == "ROTATION": header.append(r',"x_Orig","y_Orig","z_Orig","x_End","y_End","z_End"') - write_format.append(r', %s, %s, %s, %s, %s, %s') - elif kindID == "FFD_CONTROL_POINT" : - header.append(r',"FFD_Box_ID","xIndex","yIndex","zIndex","xAxis","yAxis","zAxis"') - write_format.append(r', %s, %s, %s, %s, %s, %s, %s') - elif kindID == "FFD_DIHEDRAL_ANGLE" : - header.append(r',"FFD_Box_ID","x_Orig","y_Orig","z_Orig","x_End","y_End","z_End"') - write_format.append(r', %s, %s, %s, %s, %s, %s, %s') - elif kindID == "FFD_TWIST_ANGLE" : - header.append(r',"FFD_Box_ID","x_Orig","y_Orig","z_Orig","x_End","y_End","z_End"') - write_format.append(r', %s, %s, %s, %s, %s, %s, %s') - elif kindID == "FFD_ROTATION" : - header.append(r',"FFD_Box_ID","x_Orig","y_Orig","z_Orig","x_End","y_End","z_End"') - write_format.append(r', %s, %s, %s, %s, %s, %s, %s') - elif kindID == "FFD_CAMBER" : + write_format.append(r", %s, %s, %s, %s, %s, %s") + elif kindID == "FFD_CONTROL_POINT": + header.append( + r',"FFD_Box_ID","xIndex","yIndex","zIndex","xAxis","yAxis","zAxis"' + ) + write_format.append(r", %s, %s, %s, %s, %s, %s, %s") + elif kindID == "FFD_DIHEDRAL_ANGLE": + header.append( + r',"FFD_Box_ID","x_Orig","y_Orig","z_Orig","x_End","y_End","z_End"' + ) + write_format.append(r", %s, %s, %s, %s, %s, %s, %s") + elif kindID == "FFD_TWIST_ANGLE": + header.append( + r',"FFD_Box_ID","x_Orig","y_Orig","z_Orig","x_End","y_End","z_End"' + ) + write_format.append(r", %s, %s, %s, %s, %s, %s, %s") + elif kindID == "FFD_ROTATION": + header.append( + r',"FFD_Box_ID","x_Orig","y_Orig","z_Orig","x_End","y_End","z_End"' + ) + write_format.append(r", %s, %s, %s, %s, %s, %s, %s") + elif kindID == "FFD_CAMBER": header.append(r',"FFD_Box_ID","xIndex","yIndex"') - write_format.append(r', %s, %s, %s') - elif kindID == "FFD_THICKNESS" : + write_format.append(r", %s, %s, %s") + elif kindID == "FFD_THICKNESS": header.append(r',"FFD_Box_ID","xIndex","yIndex"') - write_format.append(r', %s, %s, %s') - elif kindID == "ANGLE_OF_ATTACK" : pass - elif kindID == "FFD_ANGLE_OF_ATTACK" : pass + write_format.append(r", %s, %s, %s") + elif kindID == "ANGLE_OF_ATTACK": + pass + elif kindID == "FFD_ANGLE_OF_ATTACK": + pass # otherwise... - else: raise Exception('Unrecognized Design Variable Kind') + else: + raise Exception("Unrecognized Design Variable Kind") # finite difference step - if grad_type == 'FINITE_DIFFERENCE': + if grad_type == "FINITE_DIFFERENCE": header.append(r',"FinDiff_Step"') - write_format.append(r', %.10f') + write_format.append(r", %.10f") # finish format - header.append('\n') - write_format.append('\n') + header.append("\n") + write_format.append("\n") - header = ''.join(header) - write_format = ''.join(write_format) + header = "".join(header) + write_format = "".join(write_format) - return [header,write_format] + return [header, write_format] -#: def get_gradFileFormat() +#: def get_gradFileFormat() # ------------------------------------------------------------------- # Get Optimization File Header # ------------------------------------------------------------------- -def get_optFileFormat(plot_format,special_cases=None, nZones = 1): - if special_cases is None: special_cases = [] +def get_optFileFormat(plot_format, special_cases=None, nZones=1): + + if special_cases is None: + special_cases = [] # start header, build a list of strings and join at the end - header_list = [] - header_format = '' - write_format = [] + header_list = [] + header_format = "" + write_format = [] # handle plot formating - if (plot_format == 'TECPLOT'): - header_format = header_format + 'VARIABLES=' - elif (plot_format == 'CSV'): + if plot_format == "TECPLOT": + header_format = header_format + "VARIABLES=" + elif plot_format == "CSV": pass - else: raise Exception('output plot format not recognized') + else: + raise Exception("output plot format not recognized") # start header - header_list.extend(["Iteration","CL","CD","CSF","CMx","CMy","CMz","CFx","CFy","CFz","CL/CD","Custom_ObjFunc","HeatFlux_Total","HeatFlux_Maximum","Temperature_Total"]) - write_format.append(r'%4d, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f') + header_list.extend( + [ + "Iteration", + "CL", + "CD", + "CSF", + "CMx", + "CMy", + "CMz", + "CFx", + "CFy", + "CFz", + "CL/CD", + "Custom_ObjFunc", + "HeatFlux_Total", + "HeatFlux_Maximum", + "Temperature_Total", + ] + ) + write_format.append( + r"%4d, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f" + ) # special cases for key in special_cases: - if key == "ROTATING_FRAME" : - header_list.extend(["CMerit","CT","CQ"]) - write_format.append(r', %.10f, %.10f, %.10f') - if key == "EQUIV_AREA" : - header_list.extend(["CEquivArea","CNearFieldOF"]) - write_format.append(r', %.10f, %.10f') - if key == "ENGINE" : - header_list.extend(["AeroCDrag","SolidCDrag","Radial_Distortion","Circumferential_Distortion"]) - write_format.append(r', %.10f, %.10f, %.10f, %.10f') + if key == "ROTATING_FRAME": + header_list.extend(["CMerit", "CT", "CQ"]) + write_format.append(r", %.10f, %.10f, %.10f") + if key == "EQUIV_AREA": + header_list.extend(["CEquivArea", "CNearFieldOF"]) + write_format.append(r", %.10f, %.10f") + if key == "ENGINE": + header_list.extend( + [ + "AeroCDrag", + "SolidCDrag", + "Radial_Distortion", + "Circumferential_Distortion", + ] + ) + write_format.append(r", %.10f, %.10f, %.10f, %.10f") if key == "1D_OUTPUT": - header_list.extend(["AreaAvg_TotalPress","AreaAvg_Mach","AreaAvg_Temperature","MassFlowRate","Avg_Pressure","Avg_Density","Avg_Velocity","Avg_Enthalpy"]) - write_format.append(r', %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f') - if key == "INV_DESIGN_CP" : + header_list.extend( + [ + "AreaAvg_TotalPress", + "AreaAvg_Mach", + "AreaAvg_Temperature", + "MassFlowRate", + "Avg_Pressure", + "Avg_Density", + "Avg_Velocity", + "Avg_Enthalpy", + ] + ) + write_format.append( + r", %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f" + ) + if key == "INV_DESIGN_CP": header_list.extend(["Cp_Diff"]) - write_format.append(r', %.10f') - if key == "INV_DESIGN_HEATFLUX" : + write_format.append(r", %.10f") + if key == "INV_DESIGN_HEATFLUX": header_list.extend(["HeatFlux_Diff"]) - write_format.append(r', %.10f') + write_format.append(r", %.10f") # finish formats - header_format = (header_format) + ('"') + ('","').join(header_list) + ('"') + (' \n') - write_format = ''.join(write_format) + ' \n' + header_format = ( + (header_format) + ('"') + ('","').join(header_list) + ('"') + (" \n") + ) + write_format = "".join(write_format) + " \n" # build list of objective function names header_vars = [] map_dict = get_headerMap(nZones) for variable in header_list: - assert variable in map_dict, 'unrecognized header variable' + assert variable in map_dict, "unrecognized header variable" header_vars.append(map_dict[variable]) # done - return [header_format,header_vars,write_format] + return [header_format, header_vars, write_format] -#: def get_optFileFormat() +#: def get_optFileFormat() # ------------------------------------------------------------------- # Get Extension Name # ------------------------------------------------------------------- + def get_extension(output_format): - if (output_format == "PARAVIEW") : return ".csv" - if (output_format == "PARAVIEW_BINARY") : return ".csv" - if (output_format == "TECPLOT") : return ".dat" - if (output_format == "TECPLOT_BINARY") : return ".szplt" - if (output_format == "SOLUTION") : return ".dat" - if (output_format == "RESTART") : return ".dat" - if (output_format == "CONFIG") : return ".cfg" - if (output_format == "CSV") : return ".csv" + if output_format == "PARAVIEW": + return ".csv" + if output_format == "PARAVIEW_BINARY": + return ".csv" + if output_format == "TECPLOT": + return ".dat" + if output_format == "TECPLOT_BINARY": + return ".szplt" + if output_format == "SOLUTION": + return ".dat" + if output_format == "RESTART": + return ".dat" + if output_format == "CONFIG": + return ".cfg" + if output_format == "CSV": + return ".csv" # otherwise raise Exception("Output Format Unknown") -#: def get_extension() +#: def get_extension() # ------------------------------------------------------------------- # Check Special Case # ------------------------------------------------------------------- def get_specialCases(config): - """ returns a list of special physical problems that were - specified in the config file, and set to 'yes' + """returns a list of special physical problems that were + specified in the config file, and set to 'yes' """ - all_special_cases = [ 'ROTATING_FRAME' , - 'EQUIV_AREA' , - '1D_OUTPUT' , - 'INV_DESIGN_CP' , - 'INV_DESIGN_HEATFLUX' ] + all_special_cases = [ + "ROTATING_FRAME", + "EQUIV_AREA", + "1D_OUTPUT", + "INV_DESIGN_CP", + "INV_DESIGN_HEATFLUX", + ] special_cases = [] for key in all_special_cases: - if key in config and config[key] == 'YES': + if key in config and config[key] == "YES": special_cases.append(key) - if 'SOLVER' in config and config['SOLVER'] == key: + if "SOLVER" in config and config["SOLVER"] == key: special_cases.append(key) - if config.get('TIME_MARCHING','NO') != 'NO': - special_cases.append('TIME_MARCHING') + if config.get("TIME_MARCHING", "NO") != "NO": + special_cases.append("TIME_MARCHING") # no support for more than one special case if len(special_cases) > 1: - error_str = 'Currently cannot support ' + ' and '.join(special_cases) + ' at once' + error_str = ( + "Currently cannot support " + " and ".join(special_cases) + " at once" + ) raise Exception(error_str) # Special case for harmonic balance - if 'TIME_MARCHING' in config and config['TIME_MARCHING'] == 'HARMONIC_BALANCE': - special_cases.append('HARMONIC_BALANCE') + if "TIME_MARCHING" in config and config["TIME_MARCHING"] == "HARMONIC_BALANCE": + special_cases.append("HARMONIC_BALANCE") # Special case for rotating frame - if 'GRID_MOVEMENT_KIND' in config and config['GRID_MOVEMENT_KIND'] == 'ROTATING_FRAME': - special_cases.append('ROTATING_FRAME') + if ( + "GRID_MOVEMENT_KIND" in config + and config["GRID_MOVEMENT_KIND"] == "ROTATING_FRAME" + ): + special_cases.append("ROTATING_FRAME") return special_cases + #: def get_specialCases() # ------------------------------------------------------------------- # Check Fluid Structure Interaction # ------------------------------------------------------------------- def get_multizone(config): - """ returns a list of special physical problems that were - specified in the config file, and set to 'yes' + """returns a list of special physical problems that were + specified in the config file, and set to 'yes' """ - all_multizone_problems = ['FLUID_STRUCTURE_INTERACTION'] + all_multizone_problems = ["FLUID_STRUCTURE_INTERACTION"] multizone = [] for key in all_multizone_problems: - if 'SOLVER' in config and config['SOLVER'] == key: + if "SOLVER" in config and config["SOLVER"] == key: multizone.append(key) return multizone + #: def get_multizone() -def next_folder(folder_format,num_format='%03d'): - """ folder = next_folder(folder_format,num_format='%03d') - finds the next folder with given format +def next_folder(folder_format, num_format="%03d"): + """folder = next_folder(folder_format,num_format='%03d') + finds the next folder with given format - Inputs: - folder_format - folder name with wild card (*) to mark expansion - num_format - %d formating to expand the wild card with + Inputs: + folder_format - folder name with wild card (*) to mark expansion + num_format - %d formating to expand the wild card with - Outputs: - folder - a folder with the next index number inserted in - the wild card, first index is 1 + Outputs: + folder - a folder with the next index number inserted in + the wild card, first index is 1 """ - assert '*' in folder_format , 'wildcard (*) missing in folder_format name' + assert "*" in folder_format, "wildcard (*) missing in folder_format name" folders = glob.glob(folder_format) - split = folder_format.split('*') - folder = folder_format.replace('*',num_format) + split = folder_format.split("*") + folder = folder_format.replace("*", num_format) if folders: # find folder number, could be done with regex... @@ -881,7 +1033,7 @@ def next_folder(folder_format,num_format='%03d'): max_i = int(max_folder) # increment folder number - folder = folder % (max_i+1) + folder = folder % (max_i + 1) else: # first folder, number 1 folder = folder % 1 @@ -889,23 +1041,27 @@ def next_folder(folder_format,num_format='%03d'): return folder -def expand_part(name,config): +def expand_part(name, config): names = [name] return names -def expand_time(name,config): - if 'TIME_MARCHING' in get_specialCases(config): - n_time = config['UNST_ADJOINT_ITER'] + +def expand_time(name, config): + if "TIME_MARCHING" in get_specialCases(config): + n_time = config["UNST_ADJOINT_ITER"] n_start_time = 0 - if config.get('TIME_DOMAIN', 'NO') == 'YES' and config.get('RESTART_SOL','NO') == 'YES': - n_start_time = int(config['RESTART_ITER']) + if ( + config.get("TIME_DOMAIN", "NO") == "YES" + and config.get("RESTART_SOL", "NO") == "YES" + ): + n_start_time = int(config["RESTART_ITER"]) if not isinstance(name, list): - name_pat = add_suffix(name,'%05d') - names = [name_pat%i for i in range(n_start_time, n_time)] + name_pat = add_suffix(name, "%05d") + names = [name_pat % i for i in range(n_start_time, n_time)] else: for n in range(len(name)): - name_pat = add_suffix(name[n], '%05d') - names = [name_pat%i for i in range(n_start_time, n_time)] + name_pat = add_suffix(name[n], "%05d") + names = [name_pat % i for i in range(n_start_time, n_time)] else: if not isinstance(name, list): names = [name] @@ -913,16 +1069,17 @@ def expand_time(name,config): names = name return names + def expand_zones(name, config): names = [] if int(config.NZONES) > 1: if not isinstance(name, list): - name_pat = add_suffix(name,'%d') - names = [name_pat%i for i in range(int(config.NZONES))] + name_pat = add_suffix(name, "%d") + names = [name_pat % i for i in range(int(config.NZONES))] else: for n in range(len(name)): - name_pat = add_suffix(name[n], '%d') - names.extend([name_pat%i for i in range(int(config.NZONES))]) + name_pat = add_suffix(name[n], "%d") + names.extend([name_pat % i for i in range(int(config.NZONES))]) else: if not isinstance(name, list): @@ -931,34 +1088,35 @@ def expand_zones(name, config): names = name return names -def expand_multipoint(name,config): - def_objs = config['OPT_OBJECTIVE'] + +def expand_multipoint(name, config): + def_objs = config["OPT_OBJECTIVE"] objectives = def_objs.keys() names = [] - n_multipoint = len(config['MULTIPOINT_WEIGHT'].split(',')) + n_multipoint = len(config["MULTIPOINT_WEIGHT"].split(",")) if any(elem in optnames_multi for elem in objectives): if not isinstance(name, list): - if '_point0' not in name: - name_pat = add_suffix(name,'point%d') - names = [name_pat%i for i in range(n_multipoint)] + if "_point0" not in name: + name_pat = add_suffix(name, "point%d") + names = [name_pat % i for i in range(n_multipoint)] else: - name_parts = name.split('_point0') + name_parts = name.split("_point0") name_base = name_parts[0] name_suff = name_parts[1] - name_pat = name_base + '_point%d' + name_suff - names = [name_pat%i for i in range(n_multipoint)] + name_pat = name_base + "_point%d" + name_suff + names = [name_pat % i for i in range(n_multipoint)] else: for n in range(len(name)): - if '_point0' not in name: - name_pat = add_suffix(name[n], 'point%d') - names.extend([name_pat%i for i in range(n_multipoint)]) + if "_point0" not in name: + name_pat = add_suffix(name[n], "point%d") + names.extend([name_pat % i for i in range(n_multipoint)]) else: - name_parts = name[n].split('_point0') + name_parts = name[n].split("_point0") name_base = name_parts[0] name_suff = name_parts[1] - name_pat = name_base + '_point%d' + name_suff - names.extend([name_pat%i for i in range(n_multipoint)]) + name_pat = name_base + "_point%d" + name_suff + names.extend([name_pat % i for i in range(n_multipoint)]) else: if not isinstance(name, list): names = [name] @@ -967,23 +1125,23 @@ def expand_multipoint(name,config): return names +def make_link(src, dst): + """make_link(src,dst) + makes a relative link + Inputs: + src - source file + dst - destination to place link -def make_link(src,dst): - """ make_link(src,dst) - makes a relative link - Inputs: - src - source file - dst - destination to place link - - Windows links currently unsupported, will copy file instead + Windows links currently unsupported, will copy file instead """ - if os.path.exists(src): # , 'source file does not exist \n%s' % src + if os.path.exists(src): # , 'source file does not exist \n%s' % src - if os.name == 'nt': + if os.name == "nt": # can't make a link in windows, need to look for other options - if os.path.exists(dst): os.remove(dst) - shutil.copy(src,dst) + if os.path.exists(dst): + os.remove(dst) + shutil.copy(src, dst) else: # find real file, incase source itself is a link @@ -994,91 +1152,99 @@ def make_link(src,dst): dst = os.path.normpath(dst) # check for self referencing - if src == dst: return + if src == dst: + return # find relative folder path - srcfolder = os.path.join( os.path.split(src)[0] ) + '/' - dstfolder = os.path.join( os.path.split(dst)[0] ) + '/' - srcfolder = os.path.relpath(srcfolder,dstfolder) - src = os.path.join( srcfolder, os.path.split(src)[1] ) + srcfolder = os.path.join(os.path.split(src)[0]) + "/" + dstfolder = os.path.join(os.path.split(dst)[0]) + "/" + srcfolder = os.path.relpath(srcfolder, dstfolder) + src = os.path.join(srcfolder, os.path.split(src)[1]) # make unix link - if os.path.exists(dst): os.remove(dst) - os.symlink(src,dst) - -def restart2solution(config,state={}): - """ restart2solution(config,state={}) - moves restart file to solution file, - optionally updates state - direct or adjoint is read from config - adjoint objective is read from config + if os.path.exists(dst): + os.remove(dst) + os.symlink(src, dst) + + +def restart2solution(config, state={}): + """restart2solution(config,state={}) + moves restart file to solution file, + optionally updates state + direct or adjoint is read from config + adjoint objective is read from config """ # direct solution - if config.MATH_PROBLEM == 'DIRECT': - restart = config.RESTART_FILENAME + if config.MATH_PROBLEM == "DIRECT": + restart = config.RESTART_FILENAME solution = config.SOLUTION_FILENAME - restart = restart.split('.')[0] - solution = solution.split('.')[0] + restart = restart.split(".")[0] + solution = solution.split(".")[0] - if 'RESTART_ASCII' in config.get('OUTPUT_FILES', ['RESTART_BINARY']): - restart += '.csv' - solution += '.csv' + if "RESTART_ASCII" in config.get("OUTPUT_FILES", ["RESTART_BINARY"]): + restart += ".csv" + solution += ".csv" else: - restart += '.dat' - solution += '.dat' + restart += ".dat" + solution += ".dat" # expand zones - restarts = expand_zones(restart,config) - solutions = expand_zones(solution,config) + restarts = expand_zones(restart, config) + solutions = expand_zones(solution, config) # expand unsteady time - restarts = expand_time(restarts,config) - solutions = expand_time(solutions,config) + restarts = expand_time(restarts, config) + solutions = expand_time(solutions, config) # move - for res,sol in zip(restarts,solutions): + for res, sol in zip(restarts, solutions): if os.path.exists(res): - shutil.move( res , sol ) + shutil.move(res, sol) # update state if state: state.FILES.DIRECT = solution - if os.path.exists('flow.meta'): - state.FILES.FLOW_META = 'flow.meta' + if os.path.exists("flow.meta"): + state.FILES.FLOW_META = "flow.meta" # adjoint solution - elif any([config.MATH_PROBLEM == 'CONTINUOUS_ADJOINT', config.MATH_PROBLEM == 'DISCRETE_ADJOINT']): - restart = config.RESTART_ADJ_FILENAME + elif any( + [ + config.MATH_PROBLEM == "CONTINUOUS_ADJOINT", + config.MATH_PROBLEM == "DISCRETE_ADJOINT", + ] + ): + restart = config.RESTART_ADJ_FILENAME solution = config.SOLUTION_ADJ_FILENAME - restart = restart.split('.')[0] - solution = solution.split('.')[0] + restart = restart.split(".")[0] + solution = solution.split(".")[0] - if 'RESTART_ASCII' in config.get('OUTPUT_FILES', ['RESTART_BINARY']): - restart += '.csv' - solution += '.csv' + if "RESTART_ASCII" in config.get("OUTPUT_FILES", ["RESTART_BINARY"]): + restart += ".csv" + solution += ".csv" else: - restart += '.dat' - solution += '.dat' + restart += ".dat" + solution += ".dat" # add suffix func_name = config.OBJECTIVE_FUNCTION - suffix = get_adjointSuffix(func_name) - restart = add_suffix(restart,suffix) - solution = add_suffix(solution,suffix) + suffix = get_adjointSuffix(func_name) + restart = add_suffix(restart, suffix) + solution = add_suffix(solution, suffix) # expand zones - restarts = expand_zones(restart,config) - solutions = expand_zones(solution,config) + restarts = expand_zones(restart, config) + solutions = expand_zones(solution, config) # expand unsteady time - restarts = expand_time(restarts,config) - solutions = expand_time(solutions,config) + restarts = expand_time(restarts, config) + solutions = expand_time(solutions, config) # move - for res,sol in zip(restarts,solutions): - shutil.move( res , sol ) + for res, sol in zip(restarts, solutions): + shutil.move(res, sol) # udpate state if "," in func_name: - func_name="COMBO" - ADJ_NAME = 'ADJOINT_' + func_name - if state: state.FILES[ADJ_NAME] = solution + func_name = "COMBO" + ADJ_NAME = "ADJOINT_" + func_name + if state: + state.FILES[ADJ_NAME] = solution else: - raise Exception('unknown math problem') - + raise Exception("unknown math problem") diff --git a/SU2_PY/SU2/opt/project.py b/SU2_PY/SU2/opt/project.py index f8cd6cd218e..b5b4c301780 100644 --- a/SU2_PY/SU2/opt/project.py +++ b/SU2_PY/SU2/opt/project.py @@ -34,13 +34,14 @@ import os, sys, shutil, copy, glob, time import numpy as np -from .. import io as su2io +from .. import io as su2io from .. import eval as su2eval from .. import util as su2util from ..io import redirect_folder from ..io import historyOutFields from warnings import warn, simplefilter -#simplefilter(Warning,'ignore') + +# simplefilter(Warning,'ignore') inf = 1.0e20 @@ -49,61 +50,61 @@ # Project Class # ------------------------------------------------------------------- + class Project(object): - """ project = SU2.opt.Project(self,config,state=None, - designs=[],folder='.') - - Starts a project class to manage multiple designs - - Runs multiple design classes, avoiding redundancy - Looks for closest design on restart - Currently only based on DV_VALUE_NEW - Exposes all methods of SU2.eval.design - - Attributes: - config - base config - state - base state - files - base files - designs - list of designs - folder - project working folder - results - project design results - - Methods: - Optimizer Interface - The following methods take a design vector for input - as a list (shape n) or numpy array (shape n or nx1 or 1xn). - Values are returned as floats or lists or lists of lists. - See SU2.eval.obj_f, etc for more detail. - - obj_f(dvs) - objective function : float - obj_df(dvs) - objective function derivatives : list - con_ceq(dvs) - equality constraints : list - con_dceq(dvs) - equality constraint derivatives : list[list] - con_cieq(dvs) - inequality constraints : list - con_dcieq(dvs) - inequality constraint gradients : list[list] - - Functional Interface - The following methods take an objective function name for input. - func(func_name,config) - function of specified name - grad(func_name,method,config) - gradient of specified name, - where method is 'CONTINUOUS_ADJOINT' or 'FINDIFF' - setup config for given dvs with - config = project.unpack_dvs(dvs) + """project = SU2.opt.Project(self,config,state=None, + designs=[],folder='.') + + Starts a project class to manage multiple designs + + Runs multiple design classes, avoiding redundancy + Looks for closest design on restart + Currently only based on DV_VALUE_NEW + Exposes all methods of SU2.eval.design + + Attributes: + config - base config + state - base state + files - base files + designs - list of designs + folder - project working folder + results - project design results + + Methods: + Optimizer Interface + The following methods take a design vector for input + as a list (shape n) or numpy array (shape n or nx1 or 1xn). + Values are returned as floats or lists or lists of lists. + See SU2.eval.obj_f, etc for more detail. + + obj_f(dvs) - objective function : float + obj_df(dvs) - objective function derivatives : list + con_ceq(dvs) - equality constraints : list + con_dceq(dvs) - equality constraint derivatives : list[list] + con_cieq(dvs) - inequality constraints : list + con_dcieq(dvs) - inequality constraint gradients : list[list] + + Functional Interface + The following methods take an objective function name for input. + func(func_name,config) - function of specified name + grad(func_name,method,config) - gradient of specified name, + where method is 'CONTINUOUS_ADJOINT' or 'FINDIFF' + setup config for given dvs with + config = project.unpack_dvs(dvs) """ - _design_folder = 'DESIGNS/DSN_*' - _design_number = '%03d' - + _design_folder = "DESIGNS/DSN_*" + _design_number = "%03d" - def __init__( self, config, state=None , - designs=None, folder='.' , - warn = True ): + def __init__(self, config, state=None, designs=None, folder=".", warn=True): - folder = folder.rstrip('/')+'/' - if '*' in folder: folder = su2io.next_folder(folder) - if designs is None: designs = [] + folder = folder.rstrip("/") + "/" + if "*" in folder: + folder = su2io.next_folder(folder) + if designs is None: + designs = [] - print('New Project: %s' % (folder)) + print("New Project: %s" % (folder)) # setup config config = copy.deepcopy(config) @@ -111,22 +112,22 @@ def __init__( self, config, state=None , # data_dict creation does not preserve the ordering of the config file. # This section ensures that the order of markers and objectives match # It is only needed when more than one objective is used. - def_objs = config['OPT_OBJECTIVE'] - if len(def_objs)>1: + def_objs = config["OPT_OBJECTIVE"] + if len(def_objs) > 1: objectives = def_objs.keys() marker_monitoring = [] weights = [] for i_obj, this_obj in enumerate(objectives): - marker_monitoring+=[def_objs[this_obj]['MARKER']] - weights+=[str(def_objs[this_obj]['SCALE'])] - config['MARKER_MONITORING'] = marker_monitoring - config['OBJECTIVE_WEIGHT'] = ",".join(weights) - config['OBJECTIVE_FUNCTION'] = ",".join(objectives) + marker_monitoring += [def_objs[this_obj]["MARKER"]] + weights += [str(def_objs[this_obj]["SCALE"])] + config["MARKER_MONITORING"] = marker_monitoring + config["OBJECTIVE_WEIGHT"] = ",".join(weights) + config["OBJECTIVE_FUNCTION"] = ",".join(objectives) for this_obj in def_objs: if this_obj in su2io.optnames_multi: - this_obj = this_obj.split('_')[1] - group = historyOutFields[this_obj]['GROUP'] + this_obj = this_obj.split("_")[1] + group = historyOutFields[this_obj]["GROUP"] if not group in config.HISTORY_OUTPUT: config.HISTORY_OUTPUT.append(group) @@ -134,76 +135,80 @@ def __init__( self, config, state=None , if state is None: state = su2io.State() else: - state = copy.deepcopy(state) - state = su2io.State(state) + state = copy.deepcopy(state) + state = su2io.State(state) state.find_files(config) - if 'MESH' not in state.FILES: - raise Exception('Could not find mesh file: %s' % config.MESH_FILENAME) + if "MESH" not in state.FILES: + raise Exception("Could not find mesh file: %s" % config.MESH_FILENAME) - self.config = config # base config - self.state = state # base state - self.files = state.FILES # base files - self.designs = designs # design list - self.folder = folder # project folder - self.results = su2util.ordered_bunch() # project design results + self.config = config # base config + self.state = state # base state + self.files = state.FILES # base files + self.designs = designs # design list + self.folder = folder # project folder + self.results = su2util.ordered_bunch() # project design results # output filenames - self.filename = 'project.pkl' - self.results_filename = 'results.pkl' + self.filename = "project.pkl" + self.results_filename = "results.pkl" # initialize folder with files - pull,link = state.pullnlink(config) + pull, link = state.pullnlink(config) - with redirect_folder(folder,pull,link,force=True): + with redirect_folder(folder, pull, link, force=True): # look for existing designs folders = glob.glob(self._design_folder) - if len(folders)>0: - sys.stdout.write('Removing old designs in 10s.') + if len(folders) > 0: + sys.stdout.write("Removing old designs in 10s.") sys.stdout.flush() - if warn: time.sleep(10) - sys.stdout.write(' Done!\n\n') - for f in folders: shutil.rmtree(f) + if warn: + time.sleep(10) + sys.stdout.write(" Done!\n\n") + for f in folders: + shutil.rmtree(f) #: if existing designs # save project - su2io.save_data(self.filename,self) + su2io.save_data(self.filename, self) return - def _eval(self,config,func,*args): - """ evalautes a config, checking for existing designs - """ + def _eval(self, config, func, *args): + """evalautes a config, checking for existing designs""" - konfig = copy.deepcopy(config) # design config - config = self.config # project config - state = self.state # project state - folder = self.folder # project folder + konfig = copy.deepcopy(config) # design config + config = self.config # project config + state = self.state # project state + folder = self.folder # project folder filename = self.filename # check folder - assert os.path.exists(folder) , 'cannot find project folder %s' % folder + assert os.path.exists(folder), "cannot find project folder %s" % folder # list project files to pull and link - pull,link = state.pullnlink(config) + pull, link = state.pullnlink(config) # project folder redirection, don't overwrite files - with redirect_folder(folder,pull,link,force=False) as push: + with redirect_folder(folder, pull, link, force=False) as push: # start design design = self.new_design(konfig) - if config.get('CONSOLE','VERBOSE') == 'VERBOSE': - print(os.path.join(self.folder,design.folder)) + if config.get("CONSOLE", "VERBOSE") == "VERBOSE": + print(os.path.join(self.folder, design.folder)) timestamp = design.state.tic() # set right option in design config. - if konfig.get('TIME_DOMAIN', 'NO') == 'YES' and konfig.get('RESTART_SOL', 'NO') == 'YES': - design.config['RESTART_SOL'] = 'YES' + if ( + konfig.get("TIME_DOMAIN", "NO") == "YES" + and konfig.get("RESTART_SOL", "NO") == "YES" + ): + design.config["RESTART_SOL"] = "YES" # run design+ - vals = design._eval(func,*args) + vals = design._eval(func, *args) # check for update if design.state.toc(timestamp): @@ -215,7 +220,7 @@ def _eval(self,config,func,*args): self.plot_results() # save data - su2io.save_data(filename,self) + su2io.save_data(filename, self) #: if updated @@ -224,157 +229,160 @@ def _eval(self,config,func,*args): # done, return output return vals - def unpack_dvs(self,dvs): + def unpack_dvs(self, dvs): dvs = copy.deepcopy(dvs) - konfig = copy.deepcopy( self.config ) - if isinstance(dvs, np.ndarray): dvs = dvs.tolist() + konfig = copy.deepcopy(self.config) + if isinstance(dvs, np.ndarray): + dvs = dvs.tolist() konfig.unpack_dvs(dvs) return konfig, dvs - def obj_f(self,dvs): + def obj_f(self, dvs): func = su2eval.obj_f - konfig,dvs = self.unpack_dvs(dvs) - return self._eval(konfig, func,dvs) + konfig, dvs = self.unpack_dvs(dvs) + return self._eval(konfig, func, dvs) - def obj_df(self,dvs): + def obj_df(self, dvs): func = su2eval.obj_df - konfig,dvs = self.unpack_dvs(dvs) - return self._eval(konfig, func,dvs) + konfig, dvs = self.unpack_dvs(dvs) + return self._eval(konfig, func, dvs) - def con_ceq(self,dvs): + def con_ceq(self, dvs): func = su2eval.con_ceq - konfig,dvs = self.unpack_dvs(dvs) - return self._eval(konfig, func,dvs) + konfig, dvs = self.unpack_dvs(dvs) + return self._eval(konfig, func, dvs) - def con_dceq(self,dvs): + def con_dceq(self, dvs): func = su2eval.con_dceq - konfig,dvs = self.unpack_dvs(dvs) - return self._eval(konfig, func,dvs) + konfig, dvs = self.unpack_dvs(dvs) + return self._eval(konfig, func, dvs) - def con_cieq(self,dvs): + def con_cieq(self, dvs): func = su2eval.con_cieq - konfig,dvs = self.unpack_dvs(dvs) - return self._eval(konfig, func,dvs) + konfig, dvs = self.unpack_dvs(dvs) + return self._eval(konfig, func, dvs) - def con_dcieq(self,dvs): + def con_dcieq(self, dvs): func = su2eval.con_dcieq - konfig,dvs = self.unpack_dvs(dvs) - return self._eval(konfig, func,dvs) + konfig, dvs = self.unpack_dvs(dvs) + return self._eval(konfig, func, dvs) - def func(self,func_name,config): + def func(self, func_name, config): func = su2eval.func konfig = copy.deepcopy(config) return self._eval(konfig, func, func_name) - def grad(self,func_name,method,config): + def grad(self, func_name, method, config): func = su2eval.grad konfig = copy.deepcopy(config) - return self._eval(konfig, func, func_name,method) + return self._eval(konfig, func, func_name, method) - def user(self,user_func,config,*args): + def user(self, user_func, config, *args): raise NotImplementedError - #return self._eval(config, user_func,*args) + # return self._eval(config, user_func,*args) - def add_design(self,config): - #func = su2eval.touch # hack - TWL + def add_design(self, config): + # func = su2eval.touch # hack - TWL func = su2eval.skip konfig = copy.deepcopy(config) return self._eval(konfig, func) - def new_design(self,config): - """ finds an existing design for given config - or starts a new design with a closest design - used for restart data + def new_design(self, config): + """finds an existing design for given config + or starts a new design with a closest design + used for restart data """ - # local konfig + # local konfig konfig = copy.deepcopy(config) # find closest design - closest,delta = self.closest_design(konfig) + closest, delta = self.closest_design(konfig) # found existing design if delta == 0.0 and closest: design = closest # start new design else: - design = self.init_design(konfig,closest) + design = self.init_design(konfig, closest) #: if new design return design - def get_design(self,config): + def get_design(self, config): konfig = copy.deepcopy(config) - closest,delta = self.closest_design(konfig) + closest, delta = self.closest_design(konfig) if delta == 0.0 and closest: design = closest else: - raise Exception('design not found for this config') + raise Exception("design not found for this config") return design - def closest_design(self,config): - """ looks for an existing or closest design - given a config + def closest_design(self, config): + """looks for an existing or closest design + given a config """ designs = self.designs - keys_check = ['DV_VALUE_NEW'] + keys_check = ["DV_VALUE_NEW"] if not designs: - return [] , inf + return [], inf diffs = [] for this_design in designs: this_config = this_design.config - distance = config.dist(this_config,keys_check) + distance = config.dist(this_config, keys_check) diffs.append(distance) #: for each design # pick closest design i_min = np.argmin(diffs) - delta = diffs[i_min] + delta = diffs[i_min] closest = designs[i_min] return closest, delta - def init_design(self,config,closest=None): - """ starts a new design - works in project folder + def init_design(self, config, closest=None): + """starts a new design + works in project folder """ konfig = copy.deepcopy(config) - ztate = copy.deepcopy(self.state) - if closest is None: closest = [] + ztate = copy.deepcopy(self.state) + if closest is None: + closest = [] # use closest design as seed if closest: # copy useful state info seed_folder = closest.folder - seed_files = closest.files + seed_files = closest.files for key in seed_files.keys(): # ignore mesh - if key == 'MESH': continue + if key == "MESH": + continue # build file path name = seed_files[key] - if isinstance(name,list): + if isinstance(name, list): built_name = [] for elem in name: - built_name.append(os.path.join(seed_folder,elem)) + built_name.append(os.path.join(seed_folder, elem)) ztate.FILES[key] = built_name else: - name = os.path.join(seed_folder,name) + name = os.path.join(seed_folder, name) # update pull files ztate.FILES[key] = name # name new folder - folder = self._design_folder.replace('*',self._design_number) + folder = self._design_folder.replace("*", self._design_number) folder = folder % (len(self.designs) + 1) # start new design (pulls files to folder) - design = su2eval.Design(konfig,ztate,folder) + design = su2eval.Design(konfig, ztate, folder) # update local state filenames ( ??? why not in Design() ) for key in design.files: name = design.files[key] - if isinstance(name,list): + if isinstance(name, list): built_name = [] for elem in name: built_name.append(os.path.split(elem)[-1]) @@ -388,22 +396,22 @@ def init_design(self,config,closest=None): return design - def compile_results(self,default=np.nan): - """ results = SU2.opt.Project.compile_results(default=np.nan) - builds a Bunch() of design results + def compile_results(self, default=np.nan): + """results = SU2.opt.Project.compile_results(default=np.nan) + builds a Bunch() of design results - Inputs: - default - value for missing values + Inputs: + default - value for missing values - Outputs: - results - state with items filled with list of - values ordered by each design iteration. + Outputs: + results - state with items filled with list of + values ordered by each design iteration. - results.VARIABLES - results.FUNCTIONS - results.GRADIENTS - results.HISTORY.DIRECT - results.HISTORY.ADJOINT_* + results.VARIABLES + results.FUNCTIONS + results.GRADIENTS + results.HISTORY.DIRECT + results.HISTORY.ADJOINT_* """ @@ -415,7 +423,7 @@ def compile_results(self,default=np.nan): n_dv = 0 # populate fields - for i,design in enumerate(self.designs): + for i, design in enumerate(self.designs): for key in design.state.FUNCTIONS.keys(): results.FUNCTIONS[key] = [] for key in design.state.GRADIENTS.keys(): @@ -425,20 +433,20 @@ def compile_results(self,default=np.nan): results.HISTORY[TYPE] = su2util.ordered_bunch() for key in design.state.HISTORY[TYPE].keys(): results.HISTORY[TYPE][key] = [] - this_ndv = len( design.state.design_vector() ) + this_ndv = len(design.state.design_vector()) # check design vectors are of same length if i == 0: n_dv = this_ndv else: if n_dv != this_ndv: - warn('different dv vector length during compile_results()') + warn("different dv vector length during compile_results()") #: for each design # populate results for design in self.designs: this_designvector = design.state.design_vector() - results.VARIABLES.append( this_designvector ) + results.VARIABLES.append(this_designvector) for key in results.FUNCTIONS.keys(): if key in design.state.FUNCTIONS: new_func = design.state.FUNCTIONS[key] @@ -449,14 +457,16 @@ def compile_results(self,default=np.nan): if key in design.state.GRADIENTS: new_grad = design.state.GRADIENTS[key] else: - new_grad = [default] * len( this_designvector ) + new_grad = [default] * len(this_designvector) results.GRADIENTS[key].append(new_grad) for TYPE in results.HISTORY.keys(): for key in results.HISTORY[TYPE].keys(): if key in results.FUNCTIONS.keys(): new_func = results.FUNCTIONS[key][-1] - elif ( TYPE in design.state.HISTORY.keys() and - key in design.state.HISTORY[TYPE].keys() ): + elif ( + TYPE in design.state.HISTORY.keys() + and key in design.state.HISTORY[TYPE].keys() + ): new_func = design.state.HISTORY[TYPE][key][-1] else: new_func = default @@ -465,52 +475,52 @@ def compile_results(self,default=np.nan): # save self.results = results - su2io.save_data(filename,results) + su2io.save_data(filename, results) return self.results def deep_compile(self): - """ Project.deep_compile() - recompiles project using design files saved in each design folder - useful if designs were run outside of project class + """Project.deep_compile() + recompiles project using design files saved in each design folder + useful if designs were run outside of project class """ project_folder = self.folder designs = self.designs with su2io.redirect_folder(project_folder): - for i_dsn,design in enumerate(designs): - design_filename = os.path.join(design.folder,design.filename) + for i_dsn, design in enumerate(designs): + design_filename = os.path.join(design.folder, design.filename) self.designs[i_dsn] = su2io.load_data(design_filename) self.compile_results() - su2io.save_data(self.filename,self) + su2io.save_data(self.filename, self) return def plot_results(self): - """ writes a tecplot file for plotting design results - """ + """writes a tecplot file for plotting design results""" output_format = self.config.TABULAR_FORMAT - functions = self.results.FUNCTIONS - history = self.results.HISTORY + functions = self.results.FUNCTIONS + history = self.results.HISTORY results_plot = su2util.ordered_bunch() - results_plot.EVALUATION = range(1,len(self.designs)+1) + results_plot.EVALUATION = range(1, len(self.designs) + 1) results_plot.update(functions) - results_plot.update(history.get('DIRECT',{})) + results_plot.update(history.get("DIRECT", {})) - if (output_format == 'CSV'): - su2util.write_plot('history_project.csv',output_format,results_plot) + if output_format == "CSV": + su2util.write_plot("history_project.csv", output_format, results_plot) else: - su2util.write_plot('history_project.dat',output_format,results_plot) + su2util.write_plot("history_project.dat", output_format, results_plot) def save(self): with su2io.redirect_folder(self.folder): - su2io.save_data(self.filename,self) + su2io.save_data(self.filename, self) def __repr__(self): - return ' with %i ' % len(self.designs) + return " with %i " % len(self.designs) + def __str__(self): output = self.__repr__() return output diff --git a/SU2_PY/SU2/opt/scipy_tools.py b/SU2_PY/SU2/opt/scipy_tools.py index 012d785e22d..3dbe18f83bc 100644 --- a/SU2_PY/SU2/opt/scipy_tools.py +++ b/SU2_PY/SU2/opt/scipy_tools.py @@ -39,442 +39,488 @@ # Scipy SLSQP # ------------------------------------------------------------------- -def scipy_slsqp(project,x0=None,xb=None,its=100,accu=1e-10,grads=True): - """ result = scipy_slsqp(project,x0=[],xb=[],its=100,accu=1e-10) - Runs the Scipy implementation of SLSQP with - an SU2 project +def scipy_slsqp(project, x0=None, xb=None, its=100, accu=1e-10, grads=True): + """result = scipy_slsqp(project,x0=[],xb=[],its=100,accu=1e-10) - Inputs: - project - an SU2 project - x0 - optional, initial guess - xb - optional, design variable bounds - its - max outer iterations, default 100 - accu - accuracy, default 1e-10 + Runs the Scipy implementation of SLSQP with + an SU2 project - Outputs: - result - the outputs from scipy.fmin_slsqp + Inputs: + project - an SU2 project + x0 - optional, initial guess + xb - optional, design variable bounds + its - max outer iterations, default 100 + accu - accuracy, default 1e-10 + + Outputs: + result - the outputs from scipy.fmin_slsqp """ # import scipy optimizer from scipy.optimize import fmin_slsqp # handle input cases - if x0 is None: x0 = [] - if xb is None: xb = [] + if x0 is None: + x0 = [] + if xb is None: + xb = [] # function handles - func = obj_f - f_eqcons = con_ceq - f_ieqcons = con_cieq + func = obj_f + f_eqcons = con_ceq + f_ieqcons = con_cieq # gradient handles - if project.config.get('GRADIENT_METHOD','NONE') == 'NONE': - fprime = None - fprime_eqcons = None + if project.config.get("GRADIENT_METHOD", "NONE") == "NONE": + fprime = None + fprime_eqcons = None fprime_ieqcons = None else: - fprime = obj_df - fprime_eqcons = con_dceq + fprime = obj_df + fprime_eqcons = con_dceq fprime_ieqcons = con_dcieq # number of design variables - dv_size = project.config['DEFINITION_DV']['SIZE'] - n_dv = sum( dv_size) + dv_size = project.config["DEFINITION_DV"]["SIZE"] + n_dv = sum(dv_size) project.n_dv = n_dv # Initial guess - if not x0: x0 = [0.0]*n_dv + if not x0: + x0 = [0.0] * n_dv # prescale x0 - dv_scales = project.config['DEFINITION_DV']['SCALE'] + dv_scales = project.config["DEFINITION_DV"]["SCALE"] k = 0 for i, dv_scl in enumerate(dv_scales): for j in range(dv_size[i]): - x0[k] =x0[k]/dv_scl; + x0[k] = x0[k] / dv_scl k = k + 1 # scale accuracy - obj = project.config['OPT_OBJECTIVE'] + obj = project.config["OPT_OBJECTIVE"] obj_scale = [] for this_obj in obj.keys(): - obj_scale = obj_scale + [obj[this_obj]['SCALE']] + obj_scale = obj_scale + [obj[this_obj]["SCALE"]] # Only scale the accuracy for single-objective problems: - if len(obj.keys())==1: - accu = accu*obj_scale[0] + if len(obj.keys()) == 1: + accu = accu * obj_scale[0] # scale accuracy eps = 1.0e-04 # optimizer summary - sys.stdout.write('Sequential Least SQuares Programming (SLSQP) parameters:\n') - sys.stdout.write('Number of design variables: ' + str(len(dv_size)) + ' ( ' + str(n_dv) + ' ) \n' ) - sys.stdout.write('Objective function scaling factor: ' + str(obj_scale) + '\n') - sys.stdout.write('Maximum number of iterations: ' + str(its) + '\n') - sys.stdout.write('Requested accuracy: ' + str(accu) + '\n') - sys.stdout.write('Initial guess for the independent variable(s): ' + str(x0) + '\n') - sys.stdout.write('Lower and upper bound for each independent variable: ' + str(xb) + '\n\n') + sys.stdout.write("Sequential Least SQuares Programming (SLSQP) parameters:\n") + sys.stdout.write( + "Number of design variables: " + str(len(dv_size)) + " ( " + str(n_dv) + " ) \n" + ) + sys.stdout.write("Objective function scaling factor: " + str(obj_scale) + "\n") + sys.stdout.write("Maximum number of iterations: " + str(its) + "\n") + sys.stdout.write("Requested accuracy: " + str(accu) + "\n") + sys.stdout.write("Initial guess for the independent variable(s): " + str(x0) + "\n") + sys.stdout.write( + "Lower and upper bound for each independent variable: " + str(xb) + "\n\n" + ) # Run Optimizer - outputs = fmin_slsqp( x0 = x0 , - func = func , - f_eqcons = f_eqcons , - f_ieqcons = f_ieqcons , - fprime = fprime , - fprime_eqcons = fprime_eqcons , - fprime_ieqcons = fprime_ieqcons , - args = (project,) , - bounds = xb , - iter = its , - iprint = 2 , - full_output = True , - acc = accu , - epsilon = eps ) + outputs = fmin_slsqp( + x0=x0, + func=func, + f_eqcons=f_eqcons, + f_ieqcons=f_ieqcons, + fprime=fprime, + fprime_eqcons=fprime_eqcons, + fprime_ieqcons=fprime_ieqcons, + args=(project,), + bounds=xb, + iter=its, + iprint=2, + full_output=True, + acc=accu, + epsilon=eps, + ) # Done return outputs + # ------------------------------------------------------------------- # Scipy CG # ------------------------------------------------------------------- -def scipy_cg(project,x0=None,xb=None,its=100,accu=1e-10,grads=True): - """ result = scipy_cg(project,x0=[],xb=[],its=100,accu=1e-10) - Runs the Scipy implementation of CG with - an SU2 project +def scipy_cg(project, x0=None, xb=None, its=100, accu=1e-10, grads=True): + """result = scipy_cg(project,x0=[],xb=[],its=100,accu=1e-10) + + Runs the Scipy implementation of CG with + an SU2 project - Inputs: - project - an SU2 project - x0 - optional, initial guess - xb - optional, design variable bounds - its - max outer iterations, default 100 - accu - accuracy, default 1e-10 + Inputs: + project - an SU2 project + x0 - optional, initial guess + xb - optional, design variable bounds + its - max outer iterations, default 100 + accu - accuracy, default 1e-10 - Outputs: - result - the outputs from scipy.fmin_slsqp + Outputs: + result - the outputs from scipy.fmin_slsqp """ # import scipy optimizer from scipy.optimize import fmin_cg # handle input cases - if x0 is None: x0 = [] - if xb is None: xb = [] + if x0 is None: + x0 = [] + if xb is None: + xb = [] # function handles - func = obj_f + func = obj_f # gradient handles - if project.config.get('GRADIENT_METHOD','NONE') == 'NONE': - fprime = None + if project.config.get("GRADIENT_METHOD", "NONE") == "NONE": + fprime = None else: - fprime = obj_df + fprime = obj_df # number of design variables - n_dv = len( project.config['DEFINITION_DV']['KIND'] ) + n_dv = len(project.config["DEFINITION_DV"]["KIND"]) project.n_dv = n_dv # Initial guess - if not x0: x0 = [0.0]*n_dv + if not x0: + x0 = [0.0] * n_dv # prescale x0 - dv_scales = project.config['DEFINITION_DV']['SCALE'] - x0 = [ x0[i]/dv_scl for i,dv_scl in enumerate(dv_scales) ] + dv_scales = project.config["DEFINITION_DV"]["SCALE"] + x0 = [x0[i] / dv_scl for i, dv_scl in enumerate(dv_scales)] # scale accuracy - obj = project.config['OPT_OBJECTIVE'] - obj_scale = obj[obj.keys()[0]]['SCALE'] - accu = accu*obj_scale + obj = project.config["OPT_OBJECTIVE"] + obj_scale = obj[obj.keys()[0]]["SCALE"] + accu = accu * obj_scale # scale accuracy eps = 1.0e-04 # optimizer summary - sys.stdout.write('Conjugate gradient (CG) parameters:\n') - sys.stdout.write('Number of design variables: ' + str(n_dv) + '\n') - sys.stdout.write('Objective function scaling factor: ' + str(obj_scale) + '\n') - sys.stdout.write('Maximum number of iterations: ' + str(its) + '\n') - sys.stdout.write('Requested accuracy: ' + str(accu) + '\n') - sys.stdout.write('Initial guess for the independent variable(s): ' + str(x0) + '\n') - sys.stdout.write('Lower and upper bound for each independent variable: ' + str(xb) + '\n\n') + sys.stdout.write("Conjugate gradient (CG) parameters:\n") + sys.stdout.write("Number of design variables: " + str(n_dv) + "\n") + sys.stdout.write("Objective function scaling factor: " + str(obj_scale) + "\n") + sys.stdout.write("Maximum number of iterations: " + str(its) + "\n") + sys.stdout.write("Requested accuracy: " + str(accu) + "\n") + sys.stdout.write("Initial guess for the independent variable(s): " + str(x0) + "\n") + sys.stdout.write( + "Lower and upper bound for each independent variable: " + str(xb) + "\n\n" + ) # Evaluate the objective function (only 1st iteration) - obj_f(x0,project) + obj_f(x0, project) # Run Optimizer - outputs = fmin_cg( x0 = x0 , - f = func , - fprime = fprime , - args = (project,) , - gtol = accu , - epsilon = eps , - maxiter = its , - full_output = True , - disp = True , - retall = True ) - + outputs = fmin_cg( + x0=x0, + f=func, + fprime=fprime, + args=(project,), + gtol=accu, + epsilon=eps, + maxiter=its, + full_output=True, + disp=True, + retall=True, + ) # Done return outputs + # ------------------------------------------------------------------- # Scipy BFGS # ------------------------------------------------------------------- -def scipy_bfgs(project,x0=None,xb=None,its=100,accu=1e-10,grads=True): - """ result = scipy_bfgs(project,x0=[],xb=[],its=100,accu=1e-10) - Runs the Scipy implementation of BFGS with - an SU2 project +def scipy_bfgs(project, x0=None, xb=None, its=100, accu=1e-10, grads=True): + """result = scipy_bfgs(project,x0=[],xb=[],its=100,accu=1e-10) - Inputs: - project - an SU2 project - x0 - optional, initial guess - xb - optional, design variable bounds - its - max outer iterations, default 100 - accu - accuracy, default 1e-10 + Runs the Scipy implementation of BFGS with + an SU2 project - Outputs: - result - the outputs from scipy.fmin_slsqp + Inputs: + project - an SU2 project + x0 - optional, initial guess + xb - optional, design variable bounds + its - max outer iterations, default 100 + accu - accuracy, default 1e-10 + + Outputs: + result - the outputs from scipy.fmin_slsqp """ # import scipy optimizer from scipy.optimize import fmin_bfgs # handle input cases - if x0 is None: x0 = [] - if xb is None: xb = [] + if x0 is None: + x0 = [] + if xb is None: + xb = [] # function handles - func = obj_f + func = obj_f # gradient handles - if project.config.get('GRADIENT_METHOD','NONE') == 'NONE': - fprime = None + if project.config.get("GRADIENT_METHOD", "NONE") == "NONE": + fprime = None else: - fprime = obj_df + fprime = obj_df # number of design variables - n_dv = len( project.config['DEFINITION_DV']['KIND'] ) + n_dv = len(project.config["DEFINITION_DV"]["KIND"]) project.n_dv = n_dv # Initial guess - if not x0: x0 = [0.0]*n_dv + if not x0: + x0 = [0.0] * n_dv # prescale x0 - dv_scales = project.config['DEFINITION_DV']['SCALE'] - x0 = [ x0[i]/dv_scl for i,dv_scl in enumerate(dv_scales) ] + dv_scales = project.config["DEFINITION_DV"]["SCALE"] + x0 = [x0[i] / dv_scl for i, dv_scl in enumerate(dv_scales)] # scale accuracy - obj = project.config['OPT_OBJECTIVE'] - obj_scale = obj[obj.keys()[0]]['SCALE'] - accu = accu*obj_scale + obj = project.config["OPT_OBJECTIVE"] + obj_scale = obj[obj.keys()[0]]["SCALE"] + accu = accu * obj_scale # scale accuracy eps = 1.0e-04 # optimizer summary - sys.stdout.write('Broyden-Fletcher-Goldfarb-Shanno (BFGS) parameters:\n') - sys.stdout.write('Number of design variables: ' + str(n_dv) + '\n') - sys.stdout.write('Objective function scaling factor: ' + str(obj_scale) + '\n') - sys.stdout.write('Maximum number of iterations: ' + str(its) + '\n') - sys.stdout.write('Requested accuracy: ' + str(accu) + '\n') - sys.stdout.write('Initial guess for the independent variable(s): ' + str(x0) + '\n') - sys.stdout.write('Lower and upper bound for each independent variable: ' + str(xb) + '\n\n') + sys.stdout.write("Broyden-Fletcher-Goldfarb-Shanno (BFGS) parameters:\n") + sys.stdout.write("Number of design variables: " + str(n_dv) + "\n") + sys.stdout.write("Objective function scaling factor: " + str(obj_scale) + "\n") + sys.stdout.write("Maximum number of iterations: " + str(its) + "\n") + sys.stdout.write("Requested accuracy: " + str(accu) + "\n") + sys.stdout.write("Initial guess for the independent variable(s): " + str(x0) + "\n") + sys.stdout.write( + "Lower and upper bound for each independent variable: " + str(xb) + "\n\n" + ) # Evaluate the objective function (only 1st iteration) - obj_f(x0,project) + obj_f(x0, project) # Run Optimizer - outputs = fmin_bfgs( x0 = x0 , - f = func , - fprime = fprime , - args = (project,) , - gtol = accu , - epsilon = eps , - maxiter = its , - full_output = True , - disp = True , - retall = True ) + outputs = fmin_bfgs( + x0=x0, + f=func, + fprime=fprime, + args=(project,), + gtol=accu, + epsilon=eps, + maxiter=its, + full_output=True, + disp=True, + retall=True, + ) # Done return outputs -def scipy_powell(project,x0=None,xb=None,its=100,accu=1e-10,grads=False): - """ result = scipy_powell(project,x0=[],xb=[],its=100,accu=1e-10) - Runs the Scipy implementation of Powell's method with - an SU2 project +def scipy_powell(project, x0=None, xb=None, its=100, accu=1e-10, grads=False): + """result = scipy_powell(project,x0=[],xb=[],its=100,accu=1e-10) + + Runs the Scipy implementation of Powell's method with + an SU2 project - Inputs: - project - an SU2 project - x0 - optional, initial guess - xb - optional, design variable bounds - its - max outer iterations, default 100 - accu - accuracy, default 1e-10 + Inputs: + project - an SU2 project + x0 - optional, initial guess + xb - optional, design variable bounds + its - max outer iterations, default 100 + accu - accuracy, default 1e-10 - Outputs: - result - the outputs from scipy.fmin_slsqp + Outputs: + result - the outputs from scipy.fmin_slsqp """ # import scipy optimizer from scipy.optimize import fmin_powell # handle input cases - if x0 is None: x0 = [] + if x0 is None: + x0 = [] # function handles - func = obj_f + func = obj_f # number of design variables - n_dv = len( project.config['DEFINITION_DV']['KIND'] ) + n_dv = len(project.config["DEFINITION_DV"]["KIND"]) project.n_dv = n_dv # Initial guess - if not x0: x0 = [0.0]*n_dv + if not x0: + x0 = [0.0] * n_dv # prescale x0 - dv_scales = project.config['DEFINITION_DV']['SCALE'] - x0 = [ x0[i]/dv_scl for i,dv_scl in enumerate(dv_scales) ] + dv_scales = project.config["DEFINITION_DV"]["SCALE"] + x0 = [x0[i] / dv_scl for i, dv_scl in enumerate(dv_scales)] # scale accuracy - obj = project.config['OPT_OBJECTIVE'] - obj_scale = obj[obj.keys()[0]]['SCALE'] - accu = accu*obj_scale + obj = project.config["OPT_OBJECTIVE"] + obj_scale = obj[obj.keys()[0]]["SCALE"] + accu = accu * obj_scale # scale accuracy eps = 1.0e-04 # optimizer summary - sys.stdout.write('Powells method parameters:\n') - sys.stdout.write('Number of design variables: ' + str(n_dv) + '\n') - sys.stdout.write('Objective function scaling factor: ' + str(obj_scale) + '\n') - sys.stdout.write('Maximum number of iterations: ' + str(its) + '\n') - sys.stdout.write('Requested accuracy: ' + str(accu) + '\n') + sys.stdout.write("Powells method parameters:\n") + sys.stdout.write("Number of design variables: " + str(n_dv) + "\n") + sys.stdout.write("Objective function scaling factor: " + str(obj_scale) + "\n") + sys.stdout.write("Maximum number of iterations: " + str(its) + "\n") + sys.stdout.write("Requested accuracy: " + str(accu) + "\n") # Evaluate the objective function (only 1st iteration) - obj_f(x0,project) + obj_f(x0, project) # Run Optimizer - outputs = fmin_powell( x0 = x0 , - func = func , - args = (project,) , - ftol = accu , - maxiter = its , - full_output = True , - disp = True , - retall = True ) + outputs = fmin_powell( + x0=x0, + func=func, + args=(project,), + ftol=accu, + maxiter=its, + full_output=True, + disp=True, + retall=True, + ) # Done return outputs -def obj_f(x,project): - """ obj = obj_f(x,project) - Objective Function - SU2 Project interface to scipy.fmin_slsqp +def obj_f(x, project): + """obj = obj_f(x,project) - su2: minimize f(x), list[nobj] - scipy_slsqp: minimize f(x), float + Objective Function + SU2 Project interface to scipy.fmin_slsqp + + su2: minimize f(x), list[nobj] + scipy_slsqp: minimize f(x), float """ obj_list = project.obj_f(x) obj = 0 for this_obj in obj_list: - obj = obj+this_obj + obj = obj + this_obj return obj -def obj_df(x,project): - """ dobj = obj_df(x,project) - Objective Function Gradients - SU2 Project interface to scipy.fmin_slsqp +def obj_df(x, project): + """dobj = obj_df(x,project) + + Objective Function Gradients + SU2 Project interface to scipy.fmin_slsqp - su2: df(x), list[nobj x dim] - scipy_slsqp: df(x), ndarray[dim] + su2: df(x), list[nobj x dim] + scipy_slsqp: df(x), ndarray[dim] """ dobj_list = project.obj_df(x) - dobj=[0.0]*len(dobj_list[0]) + dobj = [0.0] * len(dobj_list[0]) for this_dobj in dobj_list: - idv=0 + idv = 0 for this_dv_dobj in this_dobj: - dobj[idv] = dobj[idv]+this_dv_dobj; - idv+=1 - dobj = array( dobj ) + dobj[idv] = dobj[idv] + this_dv_dobj + idv += 1 + dobj = array(dobj) return dobj -def con_ceq(x,project): - """ cons = con_ceq(x,project) - Equality Constraint Functions - SU2 Project interface to scipy.fmin_slsqp +def con_ceq(x, project): + """cons = con_ceq(x,project) - su2: ceq(x) = 0.0, list[nceq] - scipy_slsqp: ceq(x) = 0.0, ndarray[nceq] + Equality Constraint Functions + SU2 Project interface to scipy.fmin_slsqp + + su2: ceq(x) = 0.0, list[nceq] + scipy_slsqp: ceq(x) = 0.0, ndarray[nceq] """ cons = project.con_ceq(x) - if cons: cons = array(cons) - else: cons = zeros([0]) + if cons: + cons = array(cons) + else: + cons = zeros([0]) return cons -def con_dceq(x,project): - """ dcons = con_dceq(x,project) - Equality Constraint Gradients - SU2 Project interface to scipy.fmin_slsqp +def con_dceq(x, project): + """dcons = con_dceq(x,project) - su2: dceq(x), list[nceq x dim] - scipy_slsqp: dceq(x), ndarray[nceq x dim] + Equality Constraint Gradients + SU2 Project interface to scipy.fmin_slsqp + + su2: dceq(x), list[nceq x dim] + scipy_slsqp: dceq(x), ndarray[nceq x dim] """ dcons = project.con_dceq(x) dim = project.n_dv - if dcons: dcons = array(dcons) - else: dcons = zeros([0,dim]) + if dcons: + dcons = array(dcons) + else: + dcons = zeros([0, dim]) return dcons -def con_cieq(x,project): - """ cons = con_cieq(x,project) - Inequality Constraints - SU2 Project interface to scipy.fmin_slsqp +def con_cieq(x, project): + """cons = con_cieq(x,project) - su2: cieq(x) < 0.0, list[ncieq] - scipy_slsqp: cieq(x) > 0.0, ndarray[ncieq] + Inequality Constraints + SU2 Project interface to scipy.fmin_slsqp + + su2: cieq(x) < 0.0, list[ncieq] + scipy_slsqp: cieq(x) > 0.0, ndarray[ncieq] """ cons = project.con_cieq(x) - if cons: cons = array(cons) - else: cons = zeros([0]) + if cons: + cons = array(cons) + else: + cons = zeros([0]) return -cons -def con_dcieq(x,project): - """ dcons = con_dcieq(x,project) - Inequality Constraint Gradients - SU2 Project interface to scipy.fmin_slsqp +def con_dcieq(x, project): + """dcons = con_dcieq(x,project) - su2: dcieq(x), list[ncieq x dim] - scipy_slsqp: dcieq(x), ndarray[ncieq x dim] + Inequality Constraint Gradients + SU2 Project interface to scipy.fmin_slsqp + + su2: dcieq(x), list[ncieq x dim] + scipy_slsqp: dcieq(x), ndarray[ncieq x dim] """ dcons = project.con_dcieq(x) dim = project.n_dv - if dcons: dcons = array(dcons) - else: dcons = zeros([0,dim]) + if dcons: + dcons = array(dcons) + else: + dcons = zeros([0, dim]) return -dcons diff --git a/SU2_PY/SU2/run/__init__.py b/SU2_PY/SU2/run/__init__.py index 0e092f51e71..7396a698fd1 100644 --- a/SU2_PY/SU2/run/__init__.py +++ b/SU2_PY/SU2/run/__init__.py @@ -1,17 +1,10 @@ # SU2/run/__init__.py -from .interface import ( - build_command , - run_command , - CFD , - DEF , - DOT , - SOL , - SOL_FSI) +from .interface import build_command, run_command, CFD, DEF, DOT, SOL, SOL_FSI -from .direct import direct -from .adjoint import adjoint +from .direct import direct +from .adjoint import adjoint from .projection import projection -from .deform import deform -from .geometry import geometry -from .merge import merge +from .deform import deform +from .geometry import geometry +from .merge import merge diff --git a/SU2_PY/SU2/run/adjoint.py b/SU2_PY/SU2/run/adjoint.py index 42a18d7b14e..a9bd9b32b9a 100644 --- a/SU2_PY/SU2/run/adjoint.py +++ b/SU2_PY/SU2/run/adjoint.py @@ -31,78 +31,83 @@ import copy -from .. import io as su2io -from .merge import merge as su2merge -from .interface import CFD as SU2_CFD +from .. import io as su2io +from .merge import merge as su2merge +from .interface import CFD as SU2_CFD # ---------------------------------------------------------------------- # Adjoint Simulation # ---------------------------------------------------------------------- -def adjoint( config ): - """ info = SU2.run.adjoint(config) - Runs an adjoint analysis with: - SU2.run.decomp() - SU2.run.CFD() - SU2.run.merge() +def adjoint(config): + """info = SU2.run.adjoint(config) - Assumptions: - Does not run Gradient Projection - Does not rename restart filename to solution filename - Adds 'adjoint' suffix to convergence filename + Runs an adjoint analysis with: + SU2.run.decomp() + SU2.run.CFD() + SU2.run.merge() - Outputs: - info - SU2 State with keys: - HISTORY.ADJOINT_NAME - FILES.ADJOINT_NAME + Assumptions: + Does not run Gradient Projection + Does not rename restart filename to solution filename + Adds 'adjoint' suffix to convergence filename - Updates: - config.MATH_PROBLEM + Outputs: + info - SU2 State with keys: + HISTORY.ADJOINT_NAME + FILES.ADJOINT_NAME - Executes in: - ./ + Updates: + config.MATH_PROBLEM + + Executes in: + ./ """ # local copy konfig = copy.deepcopy(config) # setup problem - if konfig.get('GRADIENT_METHOD', 'CONTINUOUS_ADJOINT') == 'DISCRETE_ADJOINT': - konfig['MATH_PROBLEM'] = 'DISCRETE_ADJOINT' + if konfig.get("GRADIENT_METHOD", "CONTINUOUS_ADJOINT") == "DISCRETE_ADJOINT": + konfig["MATH_PROBLEM"] = "DISCRETE_ADJOINT" else: - konfig['MATH_PROBLEM'] = 'CONTINUOUS_ADJOINT' + konfig["MATH_PROBLEM"] = "CONTINUOUS_ADJOINT" - konfig['CONV_FILENAME'] = konfig['CONV_FILENAME'] + '_adjoint' + konfig["CONV_FILENAME"] = konfig["CONV_FILENAME"] + "_adjoint" # Run Solution SU2_CFD(konfig) # merge - konfig['SOLUTION_ADJ_FILENAME'] = konfig['RESTART_ADJ_FILENAME'] + konfig["SOLUTION_ADJ_FILENAME"] = konfig["RESTART_ADJ_FILENAME"] su2merge(konfig) # filenames - plot_format = konfig.get('TABULAR_FORMAT', 'CSV') - plot_extension = su2io.get_extension(plot_format) - history_filename = konfig['CONV_FILENAME'] + plot_extension - special_cases = su2io.get_specialCases(konfig) + plot_format = konfig.get("TABULAR_FORMAT", "CSV") + plot_extension = su2io.get_extension(plot_format) + history_filename = konfig["CONV_FILENAME"] + plot_extension + special_cases = su2io.get_specialCases(konfig) # get history - history = su2io.read_history( history_filename, config.NZONES ) + history = su2io.read_history(history_filename, config.NZONES) # update super config - config.update({ 'MATH_PROBLEM' : konfig['MATH_PROBLEM'] , - 'OBJECTIVE_FUNCTION' : konfig['OBJECTIVE_FUNCTION'] }) + config.update( + { + "MATH_PROBLEM": konfig["MATH_PROBLEM"], + "OBJECTIVE_FUNCTION": konfig["OBJECTIVE_FUNCTION"], + } + ) # files out - objective = konfig['OBJECTIVE_FUNCTION'] + objective = konfig["OBJECTIVE_FUNCTION"] if "," in objective: - objective="COMBO" - adj_title = 'ADJOINT_' + objective - suffix = su2io.get_adjointSuffix(objective) - restart_name = konfig['RESTART_FILENAME'] - restart_name = su2io.add_suffix(restart_name,suffix) + objective = "COMBO" + adj_title = "ADJOINT_" + objective + suffix = su2io.get_adjointSuffix(objective) + restart_name = konfig["RESTART_FILENAME"] + restart_name = su2io.add_suffix(restart_name, suffix) # info out info = su2io.State() diff --git a/SU2_PY/SU2/run/deform.py b/SU2_PY/SU2/run/deform.py index 2c8de878a15..6f2638672bf 100644 --- a/SU2_PY/SU2/run/deform.py +++ b/SU2_PY/SU2/run/deform.py @@ -31,7 +31,7 @@ import copy -from .. import io as su2io +from .. import io as su2io from .interface import DEF as SU2_DEF @@ -39,66 +39,75 @@ # Mesh Deformation # ---------------------------------------------------------------------- -def deform ( config, dv_new=None, dv_old=None ): - """ info = SU2.run.deform(config,dv_new=[],dv_old=[]) - Deforms mesh with: - SU2.run.decomp() - SU2.run.DEF() +def deform(config, dv_new=None, dv_old=None): + """info = SU2.run.deform(config,dv_new=[],dv_old=[]) - Assumptions: - If optional dv_new ommitted, config is setup for deformation - If using dv_old, must provide dv_new - Adds 'deform' suffix to mesh output name + Deforms mesh with: + SU2.run.decomp() + SU2.run.DEF() - Outputs: - info - SU2 State with keys: - HISTORY.ADJOINT_NAME - FILES.ADJOINT_NAME + Assumptions: + If optional dv_new ommitted, config is setup for deformation + If using dv_old, must provide dv_new + Adds 'deform' suffix to mesh output name - Updates: - config.MESH_FILENAME - config.DV_VALUE_OLD = config.DV_VALUE_NEW + Outputs: + info - SU2 State with keys: + HISTORY.ADJOINT_NAME + FILES.ADJOINT_NAME - Executes in: - ./ + Updates: + config.MESH_FILENAME + config.DV_VALUE_OLD = config.DV_VALUE_NEW + + Executes in: + ./ """ - if dv_new is None: dv_new = [] - if dv_old is None: dv_old = [] + if dv_new is None: + dv_new = [] + if dv_old is None: + dv_old = [] # error check - if dv_old and not dv_new: raise Exception('must provide dv_old with dv_new') + if dv_old and not dv_new: + raise Exception("must provide dv_old with dv_new") # local copy konfig = copy.deepcopy(config) # unpack design variables - if dv_new: konfig.unpack_dvs(dv_new,dv_old) + if dv_new: + konfig.unpack_dvs(dv_new, dv_old) # redundancy check - if konfig['DV_VALUE_NEW'] == konfig['DV_VALUE_OLD']: + if konfig["DV_VALUE_NEW"] == konfig["DV_VALUE_OLD"]: info = su2io.State() info.FILES.MESH = konfig.MESH_FILENAME info.VARIABLES.DV_VALUE_NEW = konfig.DV_VALUE_NEW return info # setup mesh name - suffix = 'deform' - mesh_name = konfig['MESH_FILENAME'] - meshname_suffixed = su2io.add_suffix( mesh_name , suffix ) - konfig['MESH_OUT_FILENAME'] = meshname_suffixed + suffix = "deform" + mesh_name = konfig["MESH_FILENAME"] + meshname_suffixed = su2io.add_suffix(mesh_name, suffix) + konfig["MESH_OUT_FILENAME"] = meshname_suffixed # Run Deformation SU2_DEF(konfig) # update super config - config.update({ 'MESH_FILENAME' : konfig['MESH_OUT_FILENAME'] , - 'DV_KIND' : konfig['DV_KIND'] , - 'DV_MARKER' : konfig['DV_MARKER'] , - 'DV_PARAM' : konfig['DV_PARAM'] , - 'DV_VALUE_OLD' : konfig['DV_VALUE_NEW'] , - 'DV_VALUE_NEW' : konfig['DV_VALUE_NEW'] }) + config.update( + { + "MESH_FILENAME": konfig["MESH_OUT_FILENAME"], + "DV_KIND": konfig["DV_KIND"], + "DV_MARKER": konfig["DV_MARKER"], + "DV_PARAM": konfig["DV_PARAM"], + "DV_VALUE_OLD": konfig["DV_VALUE_NEW"], + "DV_VALUE_NEW": konfig["DV_VALUE_NEW"], + } + ) # not modified: config['MESH_OUT_FILENAME'] # info out @@ -108,4 +117,5 @@ def deform ( config, dv_new=None, dv_old=None ): return info + #: def deform() diff --git a/SU2_PY/SU2/run/direct.py b/SU2_PY/SU2/run/direct.py index 6ce9dd050d9..2bbe23b1884 100644 --- a/SU2_PY/SU2/run/direct.py +++ b/SU2_PY/SU2/run/direct.py @@ -31,47 +31,48 @@ import copy -from .. import io as su2io -from .merge import merge as su2merge -from .interface import CFD as SU2_CFD +from .. import io as su2io +from .merge import merge as su2merge +from .interface import CFD as SU2_CFD # ---------------------------------------------------------------------- # Direct Simulation # ---------------------------------------------------------------------- -def direct ( config ): - """ info = SU2.run.direct(config) - Runs an adjoint analysis with: - SU2.run.decomp() - SU2.run.CFD() - SU2.run.merge() +def direct(config): + """info = SU2.run.direct(config) - Assumptions: - Does not rename restart filename to solution filename - Adds 'direct' suffix to convergence filename + Runs an adjoint analysis with: + SU2.run.decomp() + SU2.run.CFD() + SU2.run.merge() - Outputs: - info - SU2 State with keys: - FUNCTIONS - HISTORY.DIRECT - FILES.DIRECT + Assumptions: + Does not rename restart filename to solution filename + Adds 'direct' suffix to convergence filename - Updates: - config.MATH_PROBLEM + Outputs: + info - SU2 State with keys: + FUNCTIONS + HISTORY.DIRECT + FILES.DIRECT - Executes in: - ./ + Updates: + config.MATH_PROBLEM + + Executes in: + ./ """ # local copy konfig = copy.deepcopy(config) # setup direct problem - konfig['MATH_PROBLEM'] = 'DIRECT' - konfig['CONV_FILENAME'] = konfig['CONV_FILENAME'] + '_direct' + konfig["MATH_PROBLEM"] = "DIRECT" + konfig["CONV_FILENAME"] = konfig["CONV_FILENAME"] + "_direct" - direct_diff = konfig.get('DIRECT_DIFF','NO') == "YES" + direct_diff = konfig.get("DIRECT_DIFF", "NO") == "YES" # Run Solution SU2_CFD(konfig) @@ -80,61 +81,73 @@ def direct ( config ): multizone_cases = su2io.get_multizone(konfig) # merge - konfig['SOLUTION_FILENAME'] = konfig['RESTART_FILENAME'] - if 'FLUID_STRUCTURE_INTERACTION' in multizone_cases: - konfig['SOLUTION_FILENAME'] = konfig['RESTART_FILENAME'] + konfig["SOLUTION_FILENAME"] = konfig["RESTART_FILENAME"] + if "FLUID_STRUCTURE_INTERACTION" in multizone_cases: + konfig["SOLUTION_FILENAME"] = konfig["RESTART_FILENAME"] # filenames - plot_format = konfig.get('TABULAR_FORMAT', 'CSV') - plot_extension = su2io.get_extension(plot_format) + plot_format = konfig.get("TABULAR_FORMAT", "CSV") + plot_extension = su2io.get_extension(plot_format) # adapt the history_filename, if a restart solution is chosen # check for 'RESTART_ITER' is to avoid forced restart situation in "compute_polar.py"... - if konfig.get('RESTART_SOL','NO') == 'YES' and konfig.get('RESTART_ITER',1) != 1: - if konfig.get('CONFIG_LIST',[]) != []: - konfig['CONV_FILENAME'] = 'config_CFD' # master cfg is always config_CFD. Hardcoded names are prob nt ideal. - restart_iter = '_'+str(konfig['RESTART_ITER']).zfill(5) - history_filename = konfig['CONV_FILENAME'] + restart_iter + plot_extension + if konfig.get("RESTART_SOL", "NO") == "YES" and konfig.get("RESTART_ITER", 1) != 1: + if konfig.get("CONFIG_LIST", []) != []: + konfig[ + "CONV_FILENAME" + ] = "config_CFD" # master cfg is always config_CFD. Hardcoded names are prob nt ideal. + restart_iter = "_" + str(konfig["RESTART_ITER"]).zfill(5) + history_filename = konfig["CONV_FILENAME"] + restart_iter + plot_extension else: - if konfig.get('CONFIG_LIST',[]) != []: - konfig['CONV_FILENAME'] = 'config_CFD' - history_filename = konfig['CONV_FILENAME'] + plot_extension - + if konfig.get("CONFIG_LIST", []) != []: + konfig["CONV_FILENAME"] = "config_CFD" + history_filename = konfig["CONV_FILENAME"] + plot_extension - special_cases = su2io.get_specialCases(konfig) + special_cases = su2io.get_specialCases(konfig) # averaging final iterations - final_avg = config.get('ITER_AVERAGE_OBJ',0) + final_avg = config.get("ITER_AVERAGE_OBJ", 0) # get chosen windowing function, default is square - wnd_fct = config.get('WINDOW_FUNCTION', 'SQUARE') + wnd_fct = config.get("WINDOW_FUNCTION", "SQUARE") # get history and objectives - history = su2io.read_history( history_filename , config.NZONES) - aerodynamics = su2io.read_aerodynamics( history_filename , config.NZONES, special_cases, final_avg, wnd_fct ) + history = su2io.read_history(history_filename, config.NZONES) + aerodynamics = su2io.read_aerodynamics( + history_filename, config.NZONES, special_cases, final_avg, wnd_fct + ) # update super config - config.update({ 'MATH_PROBLEM' : konfig['MATH_PROBLEM'] }) + config.update({"MATH_PROBLEM": konfig["MATH_PROBLEM"]}) # info out info = su2io.State() - info.FUNCTIONS.update( aerodynamics ) - info.FILES.DIRECT = konfig['RESTART_FILENAME'] - if 'INV_DESIGN_CP' in special_cases: - info.FILES.TARGET_CP = 'TargetCp.dat' - if 'INV_DESIGN_HEATFLUX' in special_cases: - info.FILES.TARGET_HEATFLUX = 'TargetHeatFlux.dat' + info.FUNCTIONS.update(aerodynamics) + info.FILES.DIRECT = konfig["RESTART_FILENAME"] + if "INV_DESIGN_CP" in special_cases: + info.FILES.TARGET_CP = "TargetCp.dat" + if "INV_DESIGN_HEATFLUX" in special_cases: + info.FILES.TARGET_HEATFLUX = "TargetHeatFlux.dat" info.HISTORY.DIRECT = history - '''If WINDOW_CAUCHY_CRIT is activated and the time marching converged before the final time has been reached, - store the information for the adjoint run''' - if config.get('WINDOW_CAUCHY_CRIT', 'NO') == 'YES' and config.TIME_MARCHING != 'NO': - konfig['TIME_ITER'] = int(info.HISTORY.DIRECT.Time_Iter[-1] + 1) # update the last iteration - if konfig['UNST_ADJOINT_ITER'] > konfig['TIME_ITER']: - konfig['ITER_AVERAGE_OBJ'] = max(0,konfig['ITER_AVERAGE_OBJ'] -(konfig['UNST_ADJOINT_ITER']-konfig['TIME_ITER'])) - konfig['UNST_ADJOINT_ITER'] = konfig['TIME_ITER'] - - info['WND_CAUCHY_DATA'] = {'TIME_ITER': konfig['TIME_ITER'], 'UNST_ADJOINT_ITER': konfig['UNST_ADJOINT_ITER'], - 'ITER_AVERAGE_OBJ': konfig['ITER_AVERAGE_OBJ']} + """If WINDOW_CAUCHY_CRIT is activated and the time marching converged before the final time has been reached, + store the information for the adjoint run""" + if config.get("WINDOW_CAUCHY_CRIT", "NO") == "YES" and config.TIME_MARCHING != "NO": + konfig["TIME_ITER"] = int( + info.HISTORY.DIRECT.Time_Iter[-1] + 1 + ) # update the last iteration + if konfig["UNST_ADJOINT_ITER"] > konfig["TIME_ITER"]: + konfig["ITER_AVERAGE_OBJ"] = max( + 0, + konfig["ITER_AVERAGE_OBJ"] + - (konfig["UNST_ADJOINT_ITER"] - konfig["TIME_ITER"]), + ) + konfig["UNST_ADJOINT_ITER"] = konfig["TIME_ITER"] + + info["WND_CAUCHY_DATA"] = { + "TIME_ITER": konfig["TIME_ITER"], + "UNST_ADJOINT_ITER": konfig["UNST_ADJOINT_ITER"], + "ITER_AVERAGE_OBJ": konfig["ITER_AVERAGE_OBJ"], + } su2merge(konfig) diff --git a/SU2_PY/SU2/run/geometry.py b/SU2_PY/SU2/run/geometry.py index 5180d6862b0..63ccef8c88f 100644 --- a/SU2_PY/SU2/run/geometry.py +++ b/SU2_PY/SU2/run/geometry.py @@ -31,66 +31,68 @@ import copy -from .. import io as su2io -from .interface import GEO as SU2_GEO +from .. import io as su2io +from .interface import GEO as SU2_GEO from ..util import ordered_bunch # ---------------------------------------------------------------------- # Direct Simulation # ---------------------------------------------------------------------- -def geometry ( config , step = 1e-3 ): - """ info = SU2.run.geometry(config) - Runs an geometry analysis with: - SU2.run.decomp() - SU2.run.GEO() +def geometry(config, step=1e-3): + """info = SU2.run.geometry(config) - Assumptions: - Performs both function and gradient analysis + Runs an geometry analysis with: + SU2.run.decomp() + SU2.run.GEO() - Inputs: - config - an SU2 configuration - step - gradient finite difference step if config.GEO_MODE=GRADIENT + Assumptions: + Performs both function and gradient analysis - Outputs: - info - SU2 State with keys: - FUNCTIONS - GRADIENTS + Inputs: + config - an SU2 configuration + step - gradient finite difference step if config.GEO_MODE=GRADIENT - Updates: + Outputs: + info - SU2 State with keys: + FUNCTIONS + GRADIENTS - Executes in: - ./ + Updates: + + Executes in: + ./ """ # local copy konfig = copy.deepcopy(config) # unpack - function_name = konfig['GEO_PARAM'] - tabular_format = konfig.get('TABULAR_FORMAT', 'CSV') - func_filename = konfig['VALUE_OBJFUNC_FILENAME'] - grad_filename = konfig['GRAD_OBJFUNC_FILENAME'] - - if tabular_format == 'CSV': - func_filename = func_filename.split('.')[0] + '.csv' - grad_filename = grad_filename.split('.')[0] + '.csv' + function_name = konfig["GEO_PARAM"] + tabular_format = konfig.get("TABULAR_FORMAT", "CSV") + func_filename = konfig["VALUE_OBJFUNC_FILENAME"] + grad_filename = konfig["GRAD_OBJFUNC_FILENAME"] + + if tabular_format == "CSV": + func_filename = func_filename.split(".")[0] + ".csv" + grad_filename = grad_filename.split(".")[0] + ".csv" else: - func_filename = func_filename.split('.')[0] + '.dat' - grad_filename = grad_filename.split('.')[0] + '.dat' - + func_filename = func_filename.split(".")[0] + ".dat" + grad_filename = grad_filename.split(".")[0] + ".dat" # choose dv values - Definition_DV = konfig['DEFINITION_DV'] - n_DV = len(Definition_DV['KIND']) - if isinstance(step,list): - assert len(step) == n_DV , 'unexpected step vector length' + Definition_DV = konfig["DEFINITION_DV"] + n_DV = len(Definition_DV["KIND"]) + if isinstance(step, list): + assert len(step) == n_DV, "unexpected step vector length" else: - step = [step]*n_DV - dv_old = [0.0]*n_DV # SU2_DOT input requirement, assumes linear superposition of design variables + step = [step] * n_DV + dv_old = [ + 0.0 + ] * n_DV # SU2_DOT input requirement, assumes linear superposition of design variables dv_new = step - konfig.unpack_dvs(dv_new,dv_old) + konfig.unpack_dvs(dv_new, dv_old) # Run Solution SU2_GEO(konfig) @@ -99,15 +101,15 @@ def geometry ( config , step = 1e-3 ): info = su2io.State() # get function values - if konfig.GEO_MODE == 'FUNCTION': + if konfig.GEO_MODE == "FUNCTION": functions = su2io.tools.read_plot(func_filename) - for key,value in functions.items(): + for key, value in functions.items(): functions[key] = value[0] - info.FUNCTIONS.update( functions ) + info.FUNCTIONS.update(functions) # get gradient_values - if konfig.GEO_MODE == 'GRADIENT': + if konfig.GEO_MODE == "GRADIENT": gradients = su2io.tools.read_plot(grad_filename) - info.GRADIENTS.update( gradients ) + info.GRADIENTS.update(gradients) return info diff --git a/SU2_PY/SU2/run/interface.py b/SU2_PY/SU2/run/interface.py index cf9df54768f..330e66ba93f 100644 --- a/SU2_PY/SU2/run/interface.py +++ b/SU2_PY/SU2/run/interface.py @@ -38,196 +38,206 @@ # Setup # ------------------------------------------------------------ -SU2_RUN = os.environ['SU2_RUN'] -sys.path.append( SU2_RUN ) -quote = '"' if sys.platform == 'win32' else '' +SU2_RUN = os.environ["SU2_RUN"] +sys.path.append(SU2_RUN) +quote = '"' if sys.platform == "win32" else "" # SU2 suite run command template -base_Command = os.path.join(SU2_RUN, '%s') +base_Command = os.path.join(SU2_RUN, "%s") # check for slurm -slurm_job = 'SLURM_JOBID' in os.environ +slurm_job = "SLURM_JOBID" in os.environ # Check for custom mpi command -user_defined = 'SU2_MPI_COMMAND' in os.environ +user_defined = "SU2_MPI_COMMAND" in os.environ # set mpi command if user_defined: - mpi_Command = os.environ['SU2_MPI_COMMAND'] + mpi_Command = os.environ["SU2_MPI_COMMAND"] elif slurm_job: - mpi_Command = 'srun -n %i %s' -elif not which('mpirun') is None: - mpi_Command = 'mpirun -n %i %s' -elif not which('mpiexec') is None: - mpi_Command = 'mpiexec -n %i %s' + mpi_Command = "srun -n %i %s" +elif not which("mpirun") is None: + mpi_Command = "mpirun -n %i %s" +elif not which("mpiexec") is None: + mpi_Command = "mpiexec -n %i %s" else: - mpi_Command = '' + mpi_Command = "" from .. import EvaluationFailure, DivergenceFailure + return_code_map = { - 1 : EvaluationFailure , - 2 : DivergenceFailure , + 1: EvaluationFailure, + 2: DivergenceFailure, } # ------------------------------------------------------------ # SU2 Suite Interface Functions # ------------------------------------------------------------ + def CFD(config): - """ run SU2_CFD - partitions set by config.NUMBER_PART + """run SU2_CFD + partitions set by config.NUMBER_PART """ konfig = copy.deepcopy(config) - direct_diff = not konfig.get('DIRECT_DIFF',"") in ["NONE", ""] + direct_diff = not konfig.get("DIRECT_DIFF", "") in ["NONE", ""] - auto_diff = konfig.MATH_PROBLEM == 'DISCRETE_ADJOINT' + auto_diff = konfig.MATH_PROBLEM == "DISCRETE_ADJOINT" if direct_diff: - tempname = 'config_CFD_DIRECTDIFF.cfg' + tempname = "config_CFD_DIRECTDIFF.cfg" konfig.dump(tempname) - processes = konfig['NUMBER_PART'] + processes = konfig["NUMBER_PART"] - the_Command = 'SU2_CFD_DIRECTDIFF%s %s' % (quote, tempname) + the_Command = "SU2_CFD_DIRECTDIFF%s %s" % (quote, tempname) elif auto_diff: - tempname = 'config_CFD_AD.cfg' + tempname = "config_CFD_AD.cfg" konfig.dump(tempname) - processes = konfig['NUMBER_PART'] + processes = konfig["NUMBER_PART"] - the_Command = 'SU2_CFD_AD%s %s' % (quote, tempname) + the_Command = "SU2_CFD_AD%s %s" % (quote, tempname) else: - tempname = 'config_CFD.cfg' + tempname = "config_CFD.cfg" konfig.dump(tempname) - processes = konfig['NUMBER_PART'] + processes = konfig["NUMBER_PART"] - the_Command = 'SU2_CFD%s %s' % (quote, tempname) + the_Command = "SU2_CFD%s %s" % (quote, tempname) - the_Command = build_command( the_Command, processes ) - run_command( the_Command ) + the_Command = build_command(the_Command, processes) + run_command(the_Command) - #os.remove(tempname) + # os.remove(tempname) return + def DEF(config): - """ run SU2_DEF - partitions set by config.NUMBER_PART - forced to run in serial, expects merged mesh input + """run SU2_DEF + partitions set by config.NUMBER_PART + forced to run in serial, expects merged mesh input """ konfig = copy.deepcopy(config) - tempname = 'config_DEF.cfg' + tempname = "config_DEF.cfg" konfig.dump(tempname) # must run with rank 1 - processes = konfig['NUMBER_PART'] + processes = konfig["NUMBER_PART"] - the_Command = 'SU2_DEF%s %s' % (quote, tempname) - the_Command = build_command( the_Command, processes ) - run_command( the_Command ) + the_Command = "SU2_DEF%s %s" % (quote, tempname) + the_Command = build_command(the_Command, processes) + run_command(the_Command) - #os.remove(tempname) + # os.remove(tempname) return + def DOT(config): - """ run SU2_DOT - partitions set by config.NUMBER_PART + """run SU2_DOT + partitions set by config.NUMBER_PART """ konfig = copy.deepcopy(config) - auto_diff = konfig.MATH_PROBLEM == 'DISCRETE_ADJOINT' or konfig.get('AUTO_DIFF','NO') == 'YES' + auto_diff = ( + konfig.MATH_PROBLEM == "DISCRETE_ADJOINT" + or konfig.get("AUTO_DIFF", "NO") == "YES" + ) if auto_diff: - tempname = 'config_DOT_AD.cfg' + tempname = "config_DOT_AD.cfg" konfig.dump(tempname) - processes = konfig['NUMBER_PART'] + processes = konfig["NUMBER_PART"] - the_Command = 'SU2_DOT_AD%s %s' % (quote, tempname) + the_Command = "SU2_DOT_AD%s %s" % (quote, tempname) else: - tempname = 'config_DOT.cfg' + tempname = "config_DOT.cfg" konfig.dump(tempname) - processes = konfig['NUMBER_PART'] + processes = konfig["NUMBER_PART"] - the_Command = 'SU2_DOT%s %s' % (quote, tempname) + the_Command = "SU2_DOT%s %s" % (quote, tempname) - the_Command = build_command( the_Command, processes ) - run_command( the_Command ) + the_Command = build_command(the_Command, processes) + run_command(the_Command) - #os.remove(tempname) + # os.remove(tempname) return + def GEO(config): - """ run SU2_GEO - partitions set by config.NUMBER_PART - forced to run in serial + """run SU2_GEO + partitions set by config.NUMBER_PART + forced to run in serial """ konfig = copy.deepcopy(config) - tempname = 'config_GEO.cfg' + tempname = "config_GEO.cfg" konfig.dump(tempname) # must run with rank 1 - processes = konfig['NUMBER_PART'] + processes = konfig["NUMBER_PART"] - the_Command = 'SU2_GEO%s %s' % (quote, tempname) - the_Command = build_command( the_Command , processes ) - run_command( the_Command ) + the_Command = "SU2_GEO%s %s" % (quote, tempname) + the_Command = build_command(the_Command, processes) + run_command(the_Command) - #os.remove(tempname) + # os.remove(tempname) return + def SOL(config): - """ run SU2_SOL - partitions set by config.NUMBER_PART + """run SU2_SOL + partitions set by config.NUMBER_PART """ konfig = copy.deepcopy(config) - tempname = 'config_SOL.cfg' + tempname = "config_SOL.cfg" konfig.dump(tempname) # must run with rank 1 - processes = konfig['NUMBER_PART'] + processes = konfig["NUMBER_PART"] - the_Command = 'SU2_SOL%s %s' % (quote, tempname) - the_Command = build_command( the_Command , processes ) - run_command( the_Command ) + the_Command = "SU2_SOL%s %s" % (quote, tempname) + the_Command = build_command(the_Command, processes) + run_command(the_Command) - #os.remove(tempname) + # os.remove(tempname) return + def SOL_FSI(config): - """ run SU2_SOL for FSI problems - partitions set by config.NUMBER_PART + """run SU2_SOL for FSI problems + partitions set by config.NUMBER_PART """ konfig = copy.deepcopy(config) - tempname = 'config_SOL.cfg' + tempname = "config_SOL.cfg" konfig.dump(tempname) # must run with rank 1 - processes = konfig['NUMBER_PART'] + processes = konfig["NUMBER_PART"] - the_Command = 'SU2_SOL%s %s 2' % (quote, tempname) - the_Command = build_command( the_Command , processes ) - run_command( the_Command ) + the_Command = "SU2_SOL%s %s 2" % (quote, tempname) + the_Command = build_command(the_Command, processes) + run_command(the_Command) - #os.remove(tempname) + # os.remove(tempname) return @@ -236,33 +246,43 @@ def SOL_FSI(config): # Helper functions # ------------------------------------------------------------ -def build_command( the_Command , processes=0 ): - """ builds an mpi command for given number of processes """ + +def build_command(the_Command, processes=0): + """builds an mpi command for given number of processes""" the_Command = quote + (base_Command % the_Command) if processes > 1: if not mpi_Command: - raise RuntimeError('could not find an mpi interface') - the_Command = mpi_Command % (processes,the_Command) + raise RuntimeError("could not find an mpi interface") + the_Command = mpi_Command % (processes, the_Command) return the_Command -def run_command( Command ): - """ runs os command with subprocess - checks for errors from command + +def run_command(Command): + """runs os command with subprocess + checks for errors from command """ sys.stdout.flush() - proc = subprocess.Popen( Command, shell=True , - stdout=sys.stdout , - stderr=subprocess.PIPE ) + proc = subprocess.Popen( + Command, shell=True, stdout=sys.stdout, stderr=subprocess.PIPE + ) return_code = proc.wait() message = proc.stderr.read().decode() if return_code < 0: - message = "SU2 process was terminated by signal '%s'\n%s" % (-return_code,message) + message = "SU2 process was terminated by signal '%s'\n%s" % ( + -return_code, + message, + ) raise SystemExit(message) elif return_code > 0: - message = "Path = %s\nCommand = %s\nSU2 process returned error '%s'\n%s" % (os.path.abspath(','),Command,return_code,message) + message = "Path = %s\nCommand = %s\nSU2 process returned error '%s'\n%s" % ( + os.path.abspath(","), + Command, + return_code, + message, + ) if return_code in return_code_map.keys(): exception = return_code_map[return_code] else: @@ -272,4 +292,3 @@ def run_command( Command ): sys.stdout.write(message) return return_code - diff --git a/SU2_PY/SU2/run/merge.py b/SU2_PY/SU2/run/merge.py index e520df3b440..2e66d14cfc3 100644 --- a/SU2_PY/SU2/run/merge.py +++ b/SU2_PY/SU2/run/merge.py @@ -28,7 +28,7 @@ # ---------------------------------------------------------------------- import os, sys, shutil, copy -from .. import io as su2io +from .. import io as su2io from .interface import SOL as SU2_SOL from .interface import SOL_FSI as SU2_SOL_FSI @@ -36,32 +36,33 @@ # Merge Mesh # ---------------------------------------------------------------------- -def merge( config ): - """ info = SU2.run.merge(config) - Merges mesh with: - SU2.run.SOL() (volume merging) - internal scripts (surface merging) +def merge(config): + """info = SU2.run.merge(config) - Assumptions: - config.NUMBER_PART is set - Skip if config.NUMBER_PART > 1 + Merges mesh with: + SU2.run.SOL() (volume merging) + internal scripts (surface merging) - Inputs: - config - an SU2 config + Assumptions: + config.NUMBER_PART is set + Skip if config.NUMBER_PART > 1 - Ouputs: - info - an empty SU2 State + Inputs: + config - an SU2 config - Executes in: - ./ + Ouputs: + info - an empty SU2 State + + Executes in: + ./ """ # local copy konfig = copy.deepcopy(config) # check if needed - partitions = konfig['NUMBER_PART'] + partitions = konfig["NUMBER_PART"] if partitions <= 1: return su2io.State() @@ -72,10 +73,10 @@ def merge( config ): multizone_cases = su2io.get_multizone(konfig) # # MERGING # # - if 'FLUID_STRUCTURE_INTERACTION' in multizone_cases: + if "FLUID_STRUCTURE_INTERACTION" in multizone_cases: merge_multizone(konfig) else: - if 'WRT_UNSTEADY' in special_cases: + if "WRT_UNSTEADY" in special_cases: merge_unsteady(konfig) else: merge_solution(konfig) @@ -85,38 +86,45 @@ def merge( config ): return info + #: merge -def merge_unsteady( config, begintime=0, endtime=None ): + +def merge_unsteady(config, begintime=0, endtime=None): if not endtime: endtime = config.EXT_ITER # SU2_SOL handles unsteady volume merge - merge_solution( config ) + merge_solution(config) return + #: def merge_unsteady() -def merge_solution( config ): - """ SU2.io.merge.merge_solution(config) - general volume surface merging with SU2_SOL + +def merge_solution(config): + """SU2.io.merge.merge_solution(config) + general volume surface merging with SU2_SOL """ - SU2_SOL( config ) + SU2_SOL(config) return + #: merge_solution( config ) -def merge_multizone( config, begintime=0, endtime=None ): + +def merge_multizone(config, begintime=0, endtime=None): if not endtime: endtime = config.TIME_ITER - SU2_SOL_FSI( config ) + SU2_SOL_FSI(config) return + #: merge_solution( config ) diff --git a/SU2_PY/SU2/run/projection.py b/SU2_PY/SU2/run/projection.py index 6b4ced709bf..fb39aa863a7 100644 --- a/SU2_PY/SU2/run/projection.py +++ b/SU2_PY/SU2/run/projection.py @@ -31,7 +31,7 @@ import os, sys, shutil, copy -from .. import io as su2io +from .. import io as su2io from .. import util as su2util from .interface import DOT as SU2_DOT @@ -40,54 +40,59 @@ # Gradient Projection # ---------------------------------------------------------------------- -def projection( config, state={}, step = 1e-3 ): - """ info = SU2.run.projection(config,state,step=1e-3) - Runs an gradient projection with: - SU2.run.decomp() - SU2.run.DOT() +def projection(config, state={}, step=1e-3): + """info = SU2.run.projection(config,state,step=1e-3) - Assumptions: - Writes tecplot file of gradients - Adds objective suffix to gradient plot filename + Runs an gradient projection with: + SU2.run.decomp() + SU2.run.DOT() - Inputs: - config - an SU2 config - state - only required when using external custom DV - step - a float or list of floats for geometry sensitivity - finite difference step + Assumptions: + Writes tecplot file of gradients + Adds objective suffix to gradient plot filename - Outputs: - info - SU2 State with keys: - GRADIENTS. + Inputs: + config - an SU2 config + state - only required when using external custom DV + step - a float or list of floats for geometry sensitivity + finite difference step - Updates: - config.MATH_PROBLEM + Outputs: + info - SU2 State with keys: + GRADIENTS. - Executes in: - ./ + Updates: + config.MATH_PROBLEM + + Executes in: + ./ """ # local copy konfig = copy.deepcopy(config) # choose dv values - Definition_DV = konfig['DEFINITION_DV'] - n_DV = sum(Definition_DV['SIZE']) - if isinstance(step,list): - assert len(step) == n_DV , 'unexpected step vector length' + Definition_DV = konfig["DEFINITION_DV"] + n_DV = sum(Definition_DV["SIZE"]) + if isinstance(step, list): + assert len(step) == n_DV, "unexpected step vector length" else: - step = [step]*n_DV - dv_old = [0.0]*n_DV # SU2_DOT input requirement, assumes linear superposition of design variables + step = [step] * n_DV + dv_old = [ + 0.0 + ] * n_DV # SU2_DOT input requirement, assumes linear superposition of design variables dv_new = step - konfig.unpack_dvs(dv_new,dv_old) + konfig.unpack_dvs(dv_new, dv_old) # filenames - objective = konfig['OBJECTIVE_FUNCTION'] - grad_filename = konfig['GRAD_OBJFUNC_FILENAME'] - output_format = konfig.get('TABULAR_FORMAT', 'CSV') + objective = konfig["OBJECTIVE_FUNCTION"] + grad_filename = konfig["GRAD_OBJFUNC_FILENAME"] + output_format = konfig.get("TABULAR_FORMAT", "CSV") plot_extension = su2io.get_extension(output_format) - adj_suffix = su2io.get_adjointSuffix(objective) - grad_plotname = os.path.splitext(grad_filename)[0] + '_' + adj_suffix + plot_extension + adj_suffix = su2io.get_adjointSuffix(objective) + grad_plotname = ( + os.path.splitext(grad_filename)[0] + "_" + adj_suffix + plot_extension + ) # Run Projection SU2_DOT(konfig) @@ -100,19 +105,19 @@ def projection( config, state={}, step = 1e-3 ): # Write Gradients data_plot = su2util.ordered_bunch() - data_plot['VARIABLE'] = range(len(raw_gradients)) - data_plot['GRADIENT'] = raw_gradients - data_plot['FINDIFF_STEP'] = step - su2util.write_plot(grad_plotname,output_format,data_plot) + data_plot["VARIABLE"] = range(len(raw_gradients)) + data_plot["GRADIENT"] = raw_gradients + data_plot["FINDIFF_STEP"] = step + su2util.write_plot(grad_plotname, output_format, data_plot) # gradient output dictionary - objective = objective.split(',') - if (len(objective)>1 ): - objective = ['COMBO'] + objective = objective.split(",") + if len(objective) > 1: + objective = ["COMBO"] - gradients = { objective[0] : raw_gradients } + gradients = {objective[0]: raw_gradients} # info out - info.GRADIENTS.update( gradients ) + info.GRADIENTS.update(gradients) return info diff --git a/SU2_PY/SU2/util/__init__.py b/SU2_PY/SU2/util/__init__.py index 27184c17739..6819e27197f 100644 --- a/SU2_PY/SU2/util/__init__.py +++ b/SU2_PY/SU2/util/__init__.py @@ -1,8 +1,8 @@ -from .switch import switch -from .bunch import Bunch as bunch -from .ordered_dict import OrderedDict as ordered_dict +from .switch import switch +from .bunch import Bunch as bunch +from .ordered_dict import OrderedDict as ordered_dict from .ordered_bunch import OrderedBunch as ordered_bunch -from .plot import write_plot, tecplot, paraview -from .lhc_unif import lhc_unif -from .mp_eval import mp_eval -from .which import which +from .plot import write_plot, tecplot, paraview +from .lhc_unif import lhc_unif +from .mp_eval import mp_eval +from .which import which diff --git a/SU2_PY/SU2/util/bunch.py b/SU2_PY/SU2/util/bunch.py index 603671fed53..f2bf6f87824 100644 --- a/SU2_PY/SU2/util/bunch.py +++ b/SU2_PY/SU2/util/bunch.py @@ -1,7 +1,7 @@ #!/usr/bin/env python """ Bunch is a subclass of dict with attribute-style access. - + >>> b = Bunch() >>> b.hello = 'world' >>> b.hello @@ -14,99 +14,100 @@ True >>> b.foo is b['foo'] True - + It is safe to import * from this module: - + __all__ = ('Bunch', 'bunchify','unbunchify') - + un/bunchify provide dictionary conversion; Bunches can also be converted via Bunch.to/fromDict(). - + original source: https://pypi.python.org/pypi/bunch """ + class Bunch(dict): - """ A dictionary that provides attribute-style access. - - >>> b = Bunch() - >>> b.hello = 'world' - >>> b.hello - 'world' - >>> b['hello'] += "!" - >>> b.hello - 'world!' - >>> b.foo = Bunch(lol=True) - >>> b.foo.lol - True - >>> b.foo is b['foo'] - True - - A Bunch is a subclass of dict; it supports all the methods a dict does... - - >>> b.keys() - ['foo', 'hello'] - - Including update()... - - >>> b.update({ 'ponies': 'are pretty!' }, hello=42) - >>> print(repr(b)) - Bunch(foo=Bunch(lol=True), hello=42, ponies='are pretty!') - - As well as iteration... - - >>> [ (k,b[k]) for k in b ] - [('ponies', 'are pretty!'), ('foo', Bunch(lol=True)), ('hello', 42)] - - And "splats". - - >>> "The {knights} who say {ni}!".format(**Bunch(knights='lolcats', ni='can haz')) - 'The lolcats who say can haz!' - - See unbunchify/Bunch.toDict, bunchify/Bunch.fromDict for notes about conversion. + """A dictionary that provides attribute-style access. + + >>> b = Bunch() + >>> b.hello = 'world' + >>> b.hello + 'world' + >>> b['hello'] += "!" + >>> b.hello + 'world!' + >>> b.foo = Bunch(lol=True) + >>> b.foo.lol + True + >>> b.foo is b['foo'] + True + + A Bunch is a subclass of dict; it supports all the methods a dict does... + + >>> b.keys() + ['foo', 'hello'] + + Including update()... + + >>> b.update({ 'ponies': 'are pretty!' }, hello=42) + >>> print(repr(b)) + Bunch(foo=Bunch(lol=True), hello=42, ponies='are pretty!') + + As well as iteration... + + >>> [ (k,b[k]) for k in b ] + [('ponies', 'are pretty!'), ('foo', Bunch(lol=True)), ('hello', 42)] + + And "splats". + + >>> "The {knights} who say {ni}!".format(**Bunch(knights='lolcats', ni='can haz')) + 'The lolcats who say can haz!' + + See unbunchify/Bunch.toDict, bunchify/Bunch.fromDict for notes about conversion. """ - + def __contains__(self, k): - """ >>> b = Bunch(ponies='are pretty!') - >>> 'ponies' in b - True - >>> 'foo' in b - False - >>> b['foo'] = 42 - >>> 'foo' in b - True - >>> b.hello = 'hai' - >>> 'hello' in b - True + """>>> b = Bunch(ponies='are pretty!') + >>> 'ponies' in b + True + >>> 'foo' in b + False + >>> b['foo'] = 42 + >>> 'foo' in b + True + >>> b.hello = 'hai' + >>> 'hello' in b + True """ try: return hasattr(self, k) or dict.__contains__(self, k) except: return False - - # only called if k not found in normal places + + # only called if k not found in normal places def __getattr__(self, k): - """ Gets key if it exists, otherwise throws AttributeError. - - nb. __getattr__ is only called if key is not found in normal places. - - >>> b = Bunch(bar='baz', lol={}) - >>> b.foo - Traceback (most recent call last): - ... - AttributeError: foo - - >>> b.bar - 'baz' - >>> getattr(b, 'bar') - 'baz' - >>> b['bar'] - 'baz' - - >>> b.lol is b['lol'] - True - >>> b.lol is getattr(b, 'lol') - True + """Gets key if it exists, otherwise throws AttributeError. + + nb. __getattr__ is only called if key is not found in normal places. + + >>> b = Bunch(bar='baz', lol={}) + >>> b.foo + Traceback (most recent call last): + ... + AttributeError: foo + + >>> b.bar + 'baz' + >>> getattr(b, 'bar') + 'baz' + >>> b['bar'] + 'baz' + + >>> b.lol is b['lol'] + True + >>> b.lol is getattr(b, 'lol') + True """ try: # Throws exception if not in prototype chain @@ -116,22 +117,22 @@ def __getattr__(self, k): return self[k] except KeyError: raise AttributeError(k) - + def __setattr__(self, k, v): - """ Sets attribute k if it exists, otherwise sets key k. A KeyError - raised by set-item (only likely if you subclass Bunch) will - propagate as an AttributeError instead. - - >>> b = Bunch(foo='bar', this_is='useful when subclassing') - >>> b.values #doctest: +ELLIPSIS - - >>> b.values = 'uh oh' - >>> b.values - 'uh oh' - >>> b['values'] - Traceback (most recent call last): - ... - KeyError: 'values' + """Sets attribute k if it exists, otherwise sets key k. A KeyError + raised by set-item (only likely if you subclass Bunch) will + propagate as an AttributeError instead. + + >>> b = Bunch(foo='bar', this_is='useful when subclassing') + >>> b.values #doctest: +ELLIPSIS + + >>> b.values = 'uh oh' + >>> b.values + 'uh oh' + >>> b['values'] + Traceback (most recent call last): + ... + KeyError: 'values' """ try: # Throws exception if not in prototype chain @@ -143,22 +144,22 @@ def __setattr__(self, k, v): raise AttributeError(k) else: object.__setattr__(self, k, v) - + def __delattr__(self, k): - """ Deletes attribute k if it exists, otherwise deletes key k. A KeyError - raised by deleting the key--such as when the key is missing--will - propagate as an AttributeError instead. - - >>> b = Bunch(lol=42) - >>> del b.values - Traceback (most recent call last): - ... - AttributeError: 'Bunch' object attribute 'values' is read-only - >>> del b.lol - >>> b.lol - Traceback (most recent call last): - ... - AttributeError: lol + """Deletes attribute k if it exists, otherwise deletes key k. A KeyError + raised by deleting the key--such as when the key is missing--will + propagate as an AttributeError instead. + + >>> b = Bunch(lol=42) + >>> del b.values + Traceback (most recent call last): + ... + AttributeError: 'Bunch' object attribute 'values' is read-only + >>> del b.lol + >>> b.lol + Traceback (most recent call last): + ... + AttributeError: lol """ try: # Throws exception if not in prototype chain @@ -170,56 +171,54 @@ def __delattr__(self, k): raise AttributeError(k) else: object.__delattr__(self, k) - + def toDict(self): - """ Recursively converts a bunch back into a dictionary. - - >>> b = Bunch(foo=Bunch(lol=True), hello=42, ponies='are pretty!') - >>> b.toDict() - {'ponies': 'are pretty!', 'foo': {'lol': True}, 'hello': 42} - - See unbunchify for more info. + """Recursively converts a bunch back into a dictionary. + + >>> b = Bunch(foo=Bunch(lol=True), hello=42, ponies='are pretty!') + >>> b.toDict() + {'ponies': 'are pretty!', 'foo': {'lol': True}, 'hello': 42} + + See unbunchify for more info. """ return unbunchify(self) - + def __repr__(self): - """ Invertible* string-form of a Bunch. - - >>> b = Bunch(foo=Bunch(lol=True), hello=42, ponies='are pretty!') - >>> print(repr(b)) - Bunch(foo=Bunch(lol=True), hello=42, ponies='are pretty!') - >>> eval(repr(b)) - Bunch(foo=Bunch(lol=True), hello=42, ponies='are pretty!') - - (*) Invertible so long as collection contents are each repr-invertible. + """Invertible* string-form of a Bunch. + + >>> b = Bunch(foo=Bunch(lol=True), hello=42, ponies='are pretty!') + >>> print(repr(b)) + Bunch(foo=Bunch(lol=True), hello=42, ponies='are pretty!') + >>> eval(repr(b)) + Bunch(foo=Bunch(lol=True), hello=42, ponies='are pretty!') + + (*) Invertible so long as collection contents are each repr-invertible. """ keys = self.keys() keys.sort() - args = ', '.join(['%s=%r' % (key, self[key]) for key in keys]) - return '%s(%s)' % (self.__class__.__name__, args) - + args = ", ".join(["%s=%r" % (key, self[key]) for key in keys]) + return "%s(%s)" % (self.__class__.__name__, args) + def __str__(self): - """ String-form of a OrderedBunch. - """ + """String-form of a OrderedBunch.""" keys = self.keys() keys.sort() - args = ', '.join(['%s=%r' % (key, self[key]) for key in keys]) - return '{%s}' % args - + args = ", ".join(["%s=%r" % (key, self[key]) for key in keys]) + return "{%s}" % args + @staticmethod def fromDict(d): - """ Recursively transforms a dictionary into a Bunch via copy. - - >>> b = Bunch.fromDict({'urmom': {'sez': {'what': 'what'}}}) - >>> b.urmom.sez.what - 'what' - - See bunchify for more info. + """Recursively transforms a dictionary into a Bunch via copy. + + >>> b = Bunch.fromDict({'urmom': {'sez': {'what': 'what'}}}) + >>> b.urmom.sez.what + 'what' + + See bunchify for more info. """ return bunchify(d) - # While we could convert abstract types like Mapping or Iterable, I think # bunchify is more likely to "do what you mean" if it is conservative about # casting (ex: isinstance(str,Iterable) == True ). @@ -227,54 +226,56 @@ def fromDict(d): # Should you disagree, it is not difficult to duplicate this function with # more aggressive coercion to suit your own purposes. + def bunchify(x): - """ Recursively transforms a dictionary into a Bunch via copy. - - >>> b = bunchify({'urmom': {'sez': {'what': 'what'}}}) - >>> b.urmom.sez.what - 'what' - - bunchify can handle intermediary dicts, lists and tuples (as well as - their subclasses), but ymmv on custom datatypes. - - >>> b = bunchify({ 'lol': ('cats', {'hah':'i win again'}), - ... 'hello': [{'french':'salut', 'german':'hallo'}] }) - >>> b.hello[0].french - 'salut' - >>> b.lol[1].hah - 'i win again' - - nb. As dicts are not hashable, they cannot be nested in sets/frozensets. + """Recursively transforms a dictionary into a Bunch via copy. + + >>> b = bunchify({'urmom': {'sez': {'what': 'what'}}}) + >>> b.urmom.sez.what + 'what' + + bunchify can handle intermediary dicts, lists and tuples (as well as + their subclasses), but ymmv on custom datatypes. + + >>> b = bunchify({ 'lol': ('cats', {'hah':'i win again'}), + ... 'hello': [{'french':'salut', 'german':'hallo'}] }) + >>> b.hello[0].french + 'salut' + >>> b.lol[1].hah + 'i win again' + + nb. As dicts are not hashable, they cannot be nested in sets/frozensets. """ if isinstance(x, dict): - return Bunch( (k, bunchify(v)) for k,v in x.iteritems() ) + return Bunch((k, bunchify(v)) for k, v in x.iteritems()) elif isinstance(x, (list, tuple)): - return type(x)( bunchify(v) for v in x ) + return type(x)(bunchify(v) for v in x) else: return x + def unbunchify(x): - """ Recursively converts a Bunch into a dictionary. - - >>> b = Bunch(foo=Bunch(lol=True), hello=42, ponies='are pretty!') - >>> unbunchify(b) - {'ponies': 'are pretty!', 'foo': {'lol': True}, 'hello': 42} - - unbunchify will handle intermediary dicts, lists and tuples (as well as - their subclasses), but ymmv on custom datatypes. - - >>> b = Bunch(foo=['bar', Bunch(lol=True)], hello=42, - ... ponies=('are pretty!', Bunch(lies='are trouble!'))) - >>> unbunchify(b) #doctest: +NORMALIZE_WHITESPACE - {'ponies': ('are pretty!', {'lies': 'are trouble!'}), - 'foo': ['bar', {'lol': True}], 'hello': 42} - - nb. As dicts are not hashable, they cannot be nested in sets/frozensets. + """Recursively converts a Bunch into a dictionary. + + >>> b = Bunch(foo=Bunch(lol=True), hello=42, ponies='are pretty!') + >>> unbunchify(b) + {'ponies': 'are pretty!', 'foo': {'lol': True}, 'hello': 42} + + unbunchify will handle intermediary dicts, lists and tuples (as well as + their subclasses), but ymmv on custom datatypes. + + >>> b = Bunch(foo=['bar', Bunch(lol=True)], hello=42, + ... ponies=('are pretty!', Bunch(lies='are trouble!'))) + >>> unbunchify(b) #doctest: +NORMALIZE_WHITESPACE + {'ponies': ('are pretty!', {'lies': 'are trouble!'}), + 'foo': ['bar', {'lol': True}], 'hello': 42} + + nb. As dicts are not hashable, they cannot be nested in sets/frozensets. """ if isinstance(x, dict): - return dict( (k, unbunchify(v)) for k,v in x.iteritems() ) + return dict((k, unbunchify(v)) for k, v in x.iteritems()) elif isinstance(x, (list, tuple)): - return type(x)( unbunchify(v) for v in x ) + return type(x)(unbunchify(v) for v in x) else: return x @@ -286,116 +287,110 @@ def unbunchify(x): import json except ImportError: import simplejson as json - + def toJSON(self, **options): - """ Serializes this Bunch to JSON. Accepts the same keyword options as `json.dumps()`. - - >>> b = Bunch(foo=Bunch(lol=True), hello=42, ponies='are pretty!') - >>> json.dumps(b) - '{"ponies": "are pretty!", "foo": {"lol": true}, "hello": 42}' - >>> b.toJSON() - '{"ponies": "are pretty!", "foo": {"lol": true}, "hello": 42}' + """Serializes this Bunch to JSON. Accepts the same keyword options as `json.dumps()`. + + >>> b = Bunch(foo=Bunch(lol=True), hello=42, ponies='are pretty!') + >>> json.dumps(b) + '{"ponies": "are pretty!", "foo": {"lol": true}, "hello": 42}' + >>> b.toJSON() + '{"ponies": "are pretty!", "foo": {"lol": true}, "hello": 42}' """ return json.dumps(self, **options) - + Bunch.toJSON = toJSON - + except ImportError: pass - - try: # Attempt to register ourself with PyYAML as a representer import yaml from yaml.representer import Representer, SafeRepresenter - + def from_yaml(loader, node): - """ PyYAML support for Bunches using the tag `!bunch` and `!bunch.Bunch`. - - >>> import yaml - >>> yaml.load(''' - ... Flow style: !bunch.Bunch { Clark: Evans, Brian: Ingerson, Oren: Ben-Kiki } - ... Block style: !bunch - ... Clark : Evans - ... Brian : Ingerson - ... Oren : Ben-Kiki - ... ''') #doctest: +NORMALIZE_WHITESPACE - {'Flow style': Bunch(Brian='Ingerson', Clark='Evans', Oren='Ben-Kiki'), - 'Block style': Bunch(Brian='Ingerson', Clark='Evans', Oren='Ben-Kiki')} - - This module registers itself automatically to cover both Bunch and any - subclasses. Should you want to customize the representation of a subclass, - simply register it with PyYAML yourself. + """PyYAML support for Bunches using the tag `!bunch` and `!bunch.Bunch`. + + >>> import yaml + >>> yaml.load(''' + ... Flow style: !bunch.Bunch { Clark: Evans, Brian: Ingerson, Oren: Ben-Kiki } + ... Block style: !bunch + ... Clark : Evans + ... Brian : Ingerson + ... Oren : Ben-Kiki + ... ''') #doctest: +NORMALIZE_WHITESPACE + {'Flow style': Bunch(Brian='Ingerson', Clark='Evans', Oren='Ben-Kiki'), + 'Block style': Bunch(Brian='Ingerson', Clark='Evans', Oren='Ben-Kiki')} + + This module registers itself automatically to cover both Bunch and any + subclasses. Should you want to customize the representation of a subclass, + simply register it with PyYAML yourself. """ data = Bunch() yield data value = loader.construct_mapping(node) data.update(value) - - + def to_yaml_safe(dumper, data): - """ Converts Bunch to a normal mapping node, making it appear as a - dict in the YAML output. - - >>> b = Bunch(foo=['bar', Bunch(lol=True)], hello=42) - >>> import yaml - >>> yaml.safe_dump(b, default_flow_style=True) - '{foo: [bar, {lol: true}], hello: 42}\\n' + """Converts Bunch to a normal mapping node, making it appear as a + dict in the YAML output. + + >>> b = Bunch(foo=['bar', Bunch(lol=True)], hello=42) + >>> import yaml + >>> yaml.safe_dump(b, default_flow_style=True) + '{foo: [bar, {lol: true}], hello: 42}\\n' """ return dumper.represent_dict(data) - + def to_yaml(dumper, data): - """ Converts Bunch to a representation node. - - >>> b = Bunch(foo=['bar', Bunch(lol=True)], hello=42) - >>> import yaml - >>> yaml.dump(b, default_flow_style=True) - '!bunch.Bunch {foo: [bar, !bunch.Bunch {lol: true}], hello: 42}\\n' + """Converts Bunch to a representation node. + + >>> b = Bunch(foo=['bar', Bunch(lol=True)], hello=42) + >>> import yaml + >>> yaml.dump(b, default_flow_style=True) + '!bunch.Bunch {foo: [bar, !bunch.Bunch {lol: true}], hello: 42}\\n' """ - return dumper.represent_mapping(u'!bunch.Bunch', data) - - - yaml.add_constructor(u'!bunch', from_yaml) - yaml.add_constructor(u'!bunch.Bunch', from_yaml) - + return dumper.represent_mapping("!bunch.Bunch", data) + + yaml.add_constructor("!bunch", from_yaml) + yaml.add_constructor("!bunch.Bunch", from_yaml) + SafeRepresenter.add_representer(Bunch, to_yaml_safe) SafeRepresenter.add_multi_representer(Bunch, to_yaml_safe) - + Representer.add_representer(Bunch, to_yaml) Representer.add_multi_representer(Bunch, to_yaml) - - + # Instance methods for YAML conversion def toYAML(self, **options): - """ Serializes this Bunch to YAML, using `yaml.safe_dump()` if - no `Dumper` is provided. See the PyYAML documentation for more info. - - >>> b = Bunch(foo=['bar', Bunch(lol=True)], hello=42) - >>> import yaml - >>> yaml.safe_dump(b, default_flow_style=True) - '{foo: [bar, {lol: true}], hello: 42}\\n' - >>> b.toYAML(default_flow_style=True) - '{foo: [bar, {lol: true}], hello: 42}\\n' - >>> yaml.dump(b, default_flow_style=True) - '!bunch.Bunch {foo: [bar, !bunch.Bunch {lol: true}], hello: 42}\\n' - >>> b.toYAML(Dumper=yaml.Dumper, default_flow_style=True) - '!bunch.Bunch {foo: [bar, !bunch.Bunch {lol: true}], hello: 42}\\n' + """Serializes this Bunch to YAML, using `yaml.safe_dump()` if + no `Dumper` is provided. See the PyYAML documentation for more info. + + >>> b = Bunch(foo=['bar', Bunch(lol=True)], hello=42) + >>> import yaml + >>> yaml.safe_dump(b, default_flow_style=True) + '{foo: [bar, {lol: true}], hello: 42}\\n' + >>> b.toYAML(default_flow_style=True) + '{foo: [bar, {lol: true}], hello: 42}\\n' + >>> yaml.dump(b, default_flow_style=True) + '!bunch.Bunch {foo: [bar, !bunch.Bunch {lol: true}], hello: 42}\\n' + >>> b.toYAML(Dumper=yaml.Dumper, default_flow_style=True) + '!bunch.Bunch {foo: [bar, !bunch.Bunch {lol: true}], hello: 42}\\n' """ opts = dict(indent=4, default_flow_style=False) opts.update(options) - if 'Dumper' not in opts: + if "Dumper" not in opts: return yaml.safe_dump(self, **opts) else: return yaml.dump(self, **opts) - + def fromYAML(*args, **kwargs): - return bunchify( yaml.load(*args, **kwargs) ) - + return bunchify(yaml.load(*args, **kwargs)) + Bunch.toYAML = Bunch.__repr__ = toYAML Bunch.fromYAML = staticmethod(fromYAML) - + except ImportError: pass - diff --git a/SU2_PY/SU2/util/filter_adjoint.py b/SU2_PY/SU2/util/filter_adjoint.py index b59283535dd..a7e1df79247 100644 --- a/SU2_PY/SU2/util/filter_adjoint.py +++ b/SU2_PY/SU2/util/filter_adjoint.py @@ -38,6 +38,7 @@ # plotting with matplotlib try: import pylab as plt + pylab_imported = True except ImportError: pylab_imported = False @@ -49,24 +50,43 @@ def main(): # Command Line Options - parser=OptionParser() - parser.add_option( "-f", "--file", dest="filename", - help="read config from FILE", metavar="FILE" ) - parser.add_option( "-t", "--type", dest="filter_type", default='LAPLACE', - help="apply filter TYPE", metavar="TYPE" ) - parser.add_option( "-m", "--marker", dest="marker_name", default='airfoil', - help="use marker named TAG", metavar="TAG" ) - parser.add_option( "-c", "--chord", dest="chord_length", default=1.0, - help="reference CHORD length", metavar="CHORD" ) - - (options, args)=parser.parse_args() - options.chord_length = float( options.chord_length ) + parser = OptionParser() + parser.add_option( + "-f", "--file", dest="filename", help="read config from FILE", metavar="FILE" + ) + parser.add_option( + "-t", + "--type", + dest="filter_type", + default="LAPLACE", + help="apply filter TYPE", + metavar="TYPE", + ) + parser.add_option( + "-m", + "--marker", + dest="marker_name", + default="airfoil", + help="use marker named TAG", + metavar="TAG", + ) + parser.add_option( + "-c", + "--chord", + dest="chord_length", + default=1.0, + help="reference CHORD length", + metavar="CHORD", + ) + + (options, args) = parser.parse_args() + options.chord_length = float(options.chord_length) # run filter - process_surface_adjoint( options.filename , - options.filter_type , - options.marker_name , - options.chord_length ) + process_surface_adjoint( + options.filename, options.filter_type, options.marker_name, options.chord_length + ) + #: def main() @@ -74,57 +94,55 @@ def main(): # ------------------------------------------------------------------- # PROCESS SURFACE ADJOINT # ------------------------------------------------------------------- -def process_surface_adjoint( config_filename , - filter_type='LAPLACE' , - marker_name='airfoil' , - chord_length=1.0 ): +def process_surface_adjoint( + config_filename, filter_type="LAPLACE", marker_name="airfoil", chord_length=1.0 +): - print('') - print('-------------------------------------------------------------------------') - print('| SU2 Suite (Process Surface Adjoint) |') - print('-------------------------------------------------------------------------') - print('') + print("") + print("-------------------------------------------------------------------------") + print("| SU2 Suite (Process Surface Adjoint) |") + print("-------------------------------------------------------------------------") + print("") # some other defaults - c_clip = 0.01 # percent chord to truncate - fft_copy = 5 # number of times to copy the fft signal - smth_len = 0.05 # percent chord smoothing window length - lapl_len = 1e-4 # laplace smoothing parameter + c_clip = 0.01 # percent chord to truncate + fft_copy = 5 # number of times to copy the fft signal + smth_len = 0.05 # percent chord smoothing window length + lapl_len = 1e-4 # laplace smoothing parameter # read config file config_data = libSU2.Get_ConfigParams(config_filename) - surface_filename = config_data['SURFACE_ADJ_FILENAME'] + '.csv' + surface_filename = config_data["SURFACE_ADJ_FILENAME"] + ".csv" print(surface_filename) - mesh_filename = config_data['MESH_FILENAME'] - gradient = config_data['OBJECTIVE_FUNCTION'] + mesh_filename = config_data["MESH_FILENAME"] + gradient = config_data["OBJECTIVE_FUNCTION"] - print('Config filename = %s' % config_filename) - print('Surface filename = %s' % surface_filename) - print('Filter Type = %s' % filter_type) + print("Config filename = %s" % config_filename) + print("Surface filename = %s" % surface_filename) + print("Filter Type = %s" % filter_type) # read adjoint data - adj_data = np.genfromtxt( surface_filename , - dtype = float , - delimiter = ',' , - skip_header = 1 ) + adj_data = np.genfromtxt( + surface_filename, dtype=float, delimiter=",", skip_header=1 + ) # read mesh data mesh_data = libSU2_mesh.Read_Mesh(mesh_filename) # proces adjoint data - P = map(int, adj_data[:,0] ) - X = adj_data[:,6].copy() - Y = adj_data[:,7].copy() - Sens = adj_data[:,1].copy() - PsiRho = adj_data[:,2].copy() - I = range(0,len(P)) # important - for unsorting durring write + P = map(int, adj_data[:, 0]) + X = adj_data[:, 6].copy() + Y = adj_data[:, 7].copy() + Sens = adj_data[:, 1].copy() + PsiRho = adj_data[:, 2].copy() + I = range(0, len(P)) # important - for unsorting durring write # store in dict by point index - adj_data_dict = dict( zip( P , zip(X,Y,Sens,PsiRho,I) ) ) + adj_data_dict = dict(zip(P, zip(X, Y, Sens, PsiRho, I))) # sort airfoil points - iP_sorted,_ = libSU2_mesh.sort_Airfoil(mesh_data,marker_name) - assert(len(iP_sorted) == len(P)) + iP_sorted, _ = libSU2_mesh.sort_Airfoil(mesh_data, marker_name) + assert len(iP_sorted) == len(P) # rebuild airfoil loop i = 0 @@ -132,56 +150,59 @@ def process_surface_adjoint( config_filename , # the adjoint data entry this_adj_data = adj_data_dict[this_P] # re-sort - P[i] = this_P - X[i] = this_adj_data[0] - Y[i] = this_adj_data[1] - Sens[i] = this_adj_data[2] + P[i] = this_P + X[i] = this_adj_data[0] + Y[i] = this_adj_data[1] + Sens[i] = this_adj_data[2] PsiRho[i] = this_adj_data[3] - I[i] = this_adj_data[4] + I[i] = this_adj_data[4] # next - i = i+1 + i = i + 1 #: for each point # calculate arc length - S = np.sqrt( np.diff(X)**2 + np.diff(Y)**2 ) / chord_length - S = np.cumsum( np.hstack([ 0 , S ]) ) + S = np.sqrt(np.diff(X) ** 2 + np.diff(Y) ** 2) / chord_length + S = np.cumsum(np.hstack([0, S])) # tail trucating, by arc length - I_clip_lo = S < S[0] + c_clip + I_clip_lo = S < S[0] + c_clip I_clip_hi = S > S[-1] - c_clip - S_clip = S.copy() + S_clip = S.copy() Sens_clip = Sens.copy() Sens_clip[I_clip_hi] = Sens_clip[I_clip_hi][0] Sens_clip[I_clip_lo] = Sens_clip[I_clip_lo][-1] - # some edge length statistics dS_clip = np.diff(S_clip) - min_dS = np.min ( dS_clip ) - mean_dS = np.mean( dS_clip ) - max_dS = np.max ( dS_clip ) - #print 'min_dS = %.4e ; mean_dS = %.4e ; max_dS = %.4e' % ( min_dS , mean_dS , max_dS ) + min_dS = np.min(dS_clip) + mean_dS = np.mean(dS_clip) + max_dS = np.max(dS_clip) + # print 'min_dS = %.4e ; mean_dS = %.4e ; max_dS = %.4e' % ( min_dS , mean_dS , max_dS ) # -------------------------------------------- # APPLY FILTER - if filter_type == 'FOURIER': - Freq_notch = [ 1/max_dS, np.inf ] # the notch frequencies - Sens_filter,Frequency,Power = fft_filter( S_clip,Sens_clip, Freq_notch, fft_copy ) - #Sens_filter = smooth(S_clip,Sens_filter, 0.03,'blackman') # post smoothing - - elif filter_type == 'WINDOW': - Sens_filter = window( S_clip, Sens_clip, smth_len, 'blackman' ) - - elif filter_type == 'LAPLACE': - Sens_filter = laplace( S_clip, Sens_clip, lapl_len ) - - elif filter_type == 'SHARPEN': - Sens_smooth = smooth( S_clip, Sens_clip , smth_len/5, 'blackman' ) # pre smoothing - Sens_smoother = smooth( S_clip, Sens_smooth, smth_len , 'blackman' ) - Sens_filter = Sens_smooth + (Sens_smooth - Sens_smoother) # sharpener + if filter_type == "FOURIER": + Freq_notch = [1 / max_dS, np.inf] # the notch frequencies + Sens_filter, Frequency, Power = fft_filter( + S_clip, Sens_clip, Freq_notch, fft_copy + ) + # Sens_filter = smooth(S_clip,Sens_filter, 0.03,'blackman') # post smoothing + + elif filter_type == "WINDOW": + Sens_filter = window(S_clip, Sens_clip, smth_len, "blackman") + + elif filter_type == "LAPLACE": + Sens_filter = laplace(S_clip, Sens_clip, lapl_len) + + elif filter_type == "SHARPEN": + Sens_smooth = smooth( + S_clip, Sens_clip, smth_len / 5, "blackman" + ) # pre smoothing + Sens_smoother = smooth(S_clip, Sens_smooth, smth_len, "blackman") + Sens_filter = Sens_smooth + (Sens_smooth - Sens_smoother) # sharpener else: - raise Exception('unknown filter type') + raise Exception("unknown filter type") # -------------------------------------------- # PLOTTING @@ -191,50 +212,50 @@ def process_surface_adjoint( config_filename , # start plot fig = plt.figure(gradient) plt.clf() - #if not fig.axes: # for comparing two filter calls - #plt.subplot(1,1,1) - #ax = fig.axes[0] - #if len(ax.lines) == 4: - #ax.lines.pop(0) - #ax.lines.pop(0) + # if not fig.axes: # for comparing two filter calls + # plt.subplot(1,1,1) + # ax = fig.axes[0] + # if len(ax.lines) == 4: + # ax.lines.pop(0) + # ax.lines.pop(0) # SENSITIVITY - plt.plot(S ,Sens ,color='b') # original - plt.plot(S_clip,Sens_filter,color='r') # filtered + plt.plot(S, Sens, color="b") # original + plt.plot(S_clip, Sens_filter, color="r") # filtered - plt.xlim(-0.1,2.1) - plt.ylim(-5,5) - plt.xlabel('Arc Length') - plt.ylabel('Surface Sensitivity') + plt.xlim(-0.1, 2.1) + plt.ylim(-5, 5) + plt.xlabel("Arc Length") + plt.ylabel("Surface Sensitivity") - #if len(ax.lines) == 4: - #seq = [2, 2, 7, 2] - #ax.lines[0].set_dashes(seq) - #ax.lines[1].set_dashes(seq) + # if len(ax.lines) == 4: + # seq = [2, 2, 7, 2] + # ax.lines[0].set_dashes(seq) + # ax.lines[1].set_dashes(seq) - plot_filename = os.path.splitext(surface_filename)[0] + '.png' - plt.savefig('Sens_'+plot_filename,dpi=300) + plot_filename = os.path.splitext(surface_filename)[0] + ".png" + plt.savefig("Sens_" + plot_filename, dpi=300) # zoom in - plt.ylim(-0.4,0.4) - plt.savefig('Sens_zoom_'+plot_filename,dpi=300) + plt.ylim(-0.4, 0.4) + plt.savefig("Sens_zoom_" + plot_filename, dpi=300) # SPECTRAL - if filter_type == 'FOURIER': + if filter_type == "FOURIER": - plt.figure('SPECTRAL') + plt.figure("SPECTRAL") plt.clf() - plt.plot(Frequency,Power) + plt.plot(Frequency, Power) - #plt.xlim(0,Freq_notch[0]+10) - plt.xlim(0,200) - plt.ylim(0,0.15) + # plt.xlim(0,Freq_notch[0]+10) + plt.xlim(0, 200) + plt.ylim(0, 0.15) - plt.xlabel('Frequency (1/C)') - plt.ylabel('Surface Sensitivity Spectal Power') + plt.xlabel("Frequency (1/C)") + plt.ylabel("Surface Sensitivity Spectal Power") - plt.savefig('Spectral_'+plot_filename,dpi=300) + plt.savefig("Spectral_" + plot_filename, dpi=300) #: if spectral plot @@ -244,12 +265,12 @@ def process_surface_adjoint( config_filename , # SAVE SURFACE FILE # reorder back to input surface points - Sens_out = np.zeros(len(S)) - Sens_out[I] = Sens_filter # left over from sort - adj_data[:,1] = Sens_out + Sens_out = np.zeros(len(S)) + Sens_out[I] = Sens_filter # left over from sort + adj_data[:, 1] = Sens_out # get surface header - surface_orig = open(surface_filename,'r') + surface_orig = open(surface_filename, "r") header = surface_orig.readline() surface_orig.close() @@ -258,31 +279,33 @@ def process_surface_adjoint( config_filename , prefix_names = prefix_names.values() # add filter prefix, before adjoint prefix - surface_filename_split = surface_filename.rstrip('.csv').split('_') + surface_filename_split = surface_filename.rstrip(".csv").split("_") if surface_filename_split[-1] in prefix_names: - surface_filename_split = surface_filename_split[0:-1] + ['filtered'] + [surface_filename_split[-1]] + surface_filename_split = ( + surface_filename_split[0:-1] + ["filtered"] + [surface_filename_split[-1]] + ) else: - surface_filename_split = surface_filename_split + ['filtered'] - surface_filename_new = '_'.join(surface_filename_split) + '.csv' + surface_filename_split = surface_filename_split + ["filtered"] + surface_filename_new = "_".join(surface_filename_split) + ".csv" # write filtered surface file (only updates Sensitivity) - surface_new = open(surface_filename_new,'w') + surface_new = open(surface_filename_new, "w") surface_new.write(header) for row in adj_data: - for i,value in enumerate(row): + for i, value in enumerate(row): if i > 0: - surface_new.write(', ') + surface_new.write(", ") if i == 0: - surface_new.write('%i' % value ) + surface_new.write("%i" % value) else: - surface_new.write('%.16e' % value ) - surface_new.write('\n') + surface_new.write("%.16e" % value) + surface_new.write("\n") surface_new.close() + print("") + print("----------------- Exit Success (Process Surface Adjoint) ----------------") + print("") - print('') - print('----------------- Exit Success (Process Surface Adjoint) ----------------') - print('') #: def process_surface_adjoint() @@ -291,45 +314,48 @@ def process_surface_adjoint( config_filename , # LAPLACIAN SMOOTHING # ------------------------------------------------------------------- -def laplace(t,x,e): - ''' Laplacian filter - input: - t - time sample vector - x - signal vector x(t) - e - smoother coefficient (e>0) - output: - y: smoothed signal at t - ''' +def laplace(t, x, e): + """Laplacian filter + input: + t - time sample vector + x - signal vector x(t) + e - smoother coefficient (e>0) + + output: + y: smoothed signal at t + """ n_x = len(x) # padding - t_1 = t[ 0] + t[-2]-t[-1] - t_2 = t[-1] + t[ 1]-t[ 0] - t_p = np.hstack([ t_1 , t , t_2 ]) - x_p = np.hstack([ x[0] , x , x[-1] ]) + t_1 = t[0] + t[-2] - t[-1] + t_2 = t[-1] + t[1] - t[0] + t_p = np.hstack([t_1, t, t_2]) + x_p = np.hstack([x[0], x, x[-1]]) # finite differencing - dt_f = t_p[2: ] - t_p[1:-1] + dt_f = t_p[2:] - t_p[1:-1] dt_b = t_p[1:-1] - t_p[0:-2] - dt_c = t_p[2: ] - t_p[0:-2] + dt_c = t_p[2:] - t_p[0:-2] # diagonal coefficients - Coeff = e * 2.0 / (dt_b*dt_f*dt_c) - diag_c = Coeff*dt_c - diag_f = -Coeff*dt_b - diag_b = -Coeff*dt_f + Coeff = e * 2.0 / (dt_b * dt_f * dt_c) + diag_c = Coeff * dt_c + diag_f = -Coeff * dt_b + diag_b = -Coeff * dt_f # system matrix - A = ( np.diag(diag_c , 0) + - np.diag(diag_f[0:-1], 1) + - np.diag(diag_b[1: ],-1) + - np.diag(np.ones(n_x), 0) ) + A = ( + np.diag(diag_c, 0) + + np.diag(diag_f[0:-1], 1) + + np.diag(diag_b[1:], -1) + + np.diag(np.ones(n_x), 0) + ) # periodic conditions - #A[1,-1] = dt_b[0] - #A[-1,1] = dt_f[-1] + # A[1,-1] = dt_b[0] + # A[-1,1] = dt_f[-1] # rhs b = np.array([x]).T @@ -338,26 +364,27 @@ def laplace(t,x,e): # signal start i_d = 0 - A[i_d,:] = 0.0 - A[i_d,i_d] = 1.0 # dirichlet - #A[i_d,i_d+1] = 1.0 # neuman - #A[i_d,i_d] = -1.0 - #b[i_d] = 0.0 #x[i_d+1]-x[i_d] + A[i_d, :] = 0.0 + A[i_d, i_d] = 1.0 # dirichlet + # A[i_d,i_d+1] = 1.0 # neuman + # A[i_d,i_d] = -1.0 + # b[i_d] = 0.0 #x[i_d+1]-x[i_d] # signal end - i_d = n_x-1 - A[i_d,:] = 0.0 - A[i_d,i_d] = 1.0 # dirichlet - #A[i_d,i_d] = 1.0 # neuman - #A[i_d,i_d-1] = -1.0 - #b[i_d] = 0.0 #x[i_d]-x[i_d-1] + i_d = n_x - 1 + A[i_d, :] = 0.0 + A[i_d, i_d] = 1.0 # dirichlet + # A[i_d,i_d] = 1.0 # neuman + # A[i_d,i_d-1] = -1.0 + # b[i_d] = 0.0 #x[i_d]-x[i_d-1] # solve - y = np.linalg.solve(A,b) - y = y[:,0] + y = np.linalg.solve(A, b) + y = y[:, 0] return y + #: def laplace @@ -365,54 +392,55 @@ def laplace(t,x,e): # FFT NOTCH FILTER # ------------------------------------------------------------------- -def fft_filter(t,x,n,c=1): - ''' Notch filter with Fast Fourier Transform - input: - t = input time vector - x = input signal vector - n = [low,high] frequency range to supress - c = number of times to duplicate signal - output: - y = smoothed signal at t +def fft_filter(t, x, n, c=1): + """Notch filter with Fast Fourier Transform + input: + t = input time vector + x = input signal vector + n = [low,high] frequency range to supress + c = number of times to duplicate signal - signal will be interpolated to constant spacing - ''' + output: + y = smoothed signal at t + + signal will be interpolated to constant spacing + """ - assert(c>0) + assert c > 0 # choose sampling frequency - min_dt = np.min( np.diff(t) ) - Ts = min_dt/2 - Fs = 1/Ts + min_dt = np.min(np.diff(t)) + Ts = min_dt / 2 + Fs = 1 / Ts # interpolate to constant spacing - nt_lin = int( t[-1]/Ts ) - t_lin = np.linspace(0,t[-1],nt_lin) - x_lin = np.interp(t_lin,t,x) + nt_lin = int(t[-1] / Ts) + t_lin = np.linspace(0, t[-1], nt_lin) + x_lin = np.interp(t_lin, t, x) # pad last index - t_lin = np.hstack([ t_lin , t_lin[0:10]+t_lin[-1] ]) - x_lin = np.hstack([ x_lin , np.ones(10)*x_lin[-1] ]) + t_lin = np.hstack([t_lin, t_lin[0:10] + t_lin[-1]]) + x_lin = np.hstack([x_lin, np.ones(10) * x_lin[-1]]) # copy signal - for ic in range(c-1): - t_lin = np.hstack([ t_lin[0:-2] , t_lin[1:]+t_lin[-1] ]) - x_lin = np.hstack([ x_lin[0:-2] , x_lin[1:] ]) + for ic in range(c - 1): + t_lin = np.hstack([t_lin[0:-2], t_lin[1:] + t_lin[-1]]) + x_lin = np.hstack([x_lin[0:-2], x_lin[1:]]) nt = len(t_lin) # perform fourier transform - nxtpow2 = int(math.log(nt, 2))+1 # next power of 2 - nfft = 2**nxtpow2 # fft efficiency - P = np.fft.rfft(x_lin,nfft) # the transform - a = np.angle(P) # complex - p = np.absolute(P) # complex - p = p/nt # normalize - p = 2*p[0:(nfft/2)] # symmetric - a = a[0:(nfft/2)] # symmetric + nxtpow2 = int(math.log(nt, 2)) + 1 # next power of 2 + nfft = 2**nxtpow2 # fft efficiency + P = np.fft.rfft(x_lin, nfft) # the transform + a = np.angle(P) # complex + p = np.absolute(P) # complex + p = p / nt # normalize + p = 2 * p[0 : (nfft / 2)] # symmetric + a = a[0 : (nfft / 2)] # symmetric # frequency domain - F = np.arange(0,nfft/2) * Fs/nfft + F = np.arange(0, nfft / 2) * Fs / nfft # for return Freq = F.copy() @@ -421,30 +449,31 @@ def fft_filter(t,x,n,c=1): # THE NOTCH FILTER # filter multiplier - k = np.ones(nfft/2) + k = np.ones(nfft / 2) # clip power within notch frequencies - I_fil = np.logical_and( F>n[0] , F n[0], F < n[1]) k[I_fil] = 0.0 # change the power spectrum - p = p*k + p = p * k # For Return Pow = p.copy() # untransform - p = p*nt/2. - p = np.hstack( [ p , p[::-1] ] ) - a = np.hstack( [ a , -a[::-1] ] ) - P = p*(np.cos(a) + 1j*np.sin(a)) - y_lin = np.fft.irfft(P,nfft) # the inverse transform + p = p * nt / 2.0 + p = np.hstack([p, p[::-1]]) + a = np.hstack([a, -a[::-1]]) + P = p * (np.cos(a) + 1j * np.sin(a)) + y_lin = np.fft.irfft(P, nfft) # the inverse transform y_lin = y_lin[0:nt] # interpolate back to given t - y = np.interp(t,t_lin,y_lin) + y = np.interp(t, t_lin, y_lin) + + return y, Freq, Pow - return y,Freq,Pow # def: fft_filter() @@ -453,7 +482,8 @@ def fft_filter(t,x,n,c=1): # WINDOWED SMOOTHING # ------------------------------------------------------------------- -def window(t,x,window_delta,window='hanning'): + +def window(t, x, window_delta, window="hanning"): """Smooth the data using a window with requested size and shape original source: @@ -474,39 +504,42 @@ def window(t,x,window_delta,window='hanning'): if x.ndim != 1: raise ValueError("smooth only accepts 1 dimension arrays.") - if window not in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']: - raise ValueError("Window is not of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'") + if window not in ["flat", "hanning", "hamming", "bartlett", "blackman"]: + raise ValueError( + "Window is not of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'" + ) # interpolate to constant time sample width - min_dt = np.min( np.diff(t) ) - Ts = min_dt/2 - nt_lin = int( t[-1]/Ts ) - t_lin = np.linspace(0,t[-1],nt_lin) - x_lin = np.interp(t_lin,t,x) + min_dt = np.min(np.diff(t)) + Ts = min_dt / 2 + nt_lin = int(t[-1] / Ts) + t_lin = np.linspace(0, t[-1], nt_lin) + x_lin = np.interp(t_lin, t, x) # window sample length - window_len = int( window_delta / Ts ) + window_len = int(window_delta / Ts) # padding - s=np.r_[x_lin[window_len-1:0:-1],x_lin,x_lin[-1:-window_len:-1]] + s = np.r_[x_lin[window_len - 1 : 0 : -1], x_lin, x_lin[-1:-window_len:-1]] # window template - if window == 'flat': #moving average - w=np.ones(window_len,'d') + if window == "flat": # moving average + w = np.ones(window_len, "d") else: - w=eval('np.'+window+'(window_len)') + w = eval("np." + window + "(window_len)") # the filter - y_lin = np.convolve(w/w.sum(),s,mode='valid') + y_lin = np.convolve(w / w.sum(), s, mode="valid") # remove padding - y_lin = y_lin[((window_len-1)/2):-(window_len/2)] + y_lin = y_lin[((window_len - 1) / 2) : -(window_len / 2)] # interpolate back to given t - y = np.interp(t,t_lin,y_lin) + y = np.interp(t, t_lin, y_lin) return y + #: def window() @@ -514,7 +547,5 @@ def window(t,x,window_delta,window='hanning'): # Run Main from Command Line # ----------------------------------------------------------------- -if __name__ == '__main__': +if __name__ == "__main__": main() - - diff --git a/SU2_PY/SU2/util/lhc_unif.py b/SU2_PY/SU2/util/lhc_unif.py index 6ede6ff694b..84cadb64543 100644 --- a/SU2_PY/SU2/util/lhc_unif.py +++ b/SU2_PY/SU2/util/lhc_unif.py @@ -1,89 +1,91 @@ import numpy as np -def lhc_unif(XB,NS,XI=None,maxits=10): - ''' XS = lhc_unif(XB,NS,XI=None,maxits=10): - - Latin Hypercube Sampling with uniform density - Iterates to maximize minimum L2 distance - Accepts an array of points to respect while sampling - - Inputs: - XB - ndim x 2 array of [lower,upper] bounds - NS - number of new points to sample - XI = None - ni x ndim array of initial points to respect - maxits = 10 - maximum number of iterations - - Outputs: - XS - ns x ndim array of sampled points - ''' - + +def lhc_unif(XB, NS, XI=None, maxits=10): + """XS = lhc_unif(XB,NS,XI=None,maxits=10): + + Latin Hypercube Sampling with uniform density + Iterates to maximize minimum L2 distance + Accepts an array of points to respect while sampling + + Inputs: + XB - ndim x 2 array of [lower,upper] bounds + NS - number of new points to sample + XI = None - ni x ndim array of initial points to respect + maxits = 10 - maximum number of iterations + + Outputs: + XS - ns x ndim array of sampled points + """ + # dimension XB = np.atleast_2d(XB) ND = XB.shape[0] - + # initial points to respect if XI is None: - XI = np.empty([0,ND]) + XI = np.empty([0, ND]) else: XI = np.atleast_2d(XI) - + # output points XO = [] - + # initialize - mindiff = 0; - + mindiff = 0 + # maximize minimum distance for it in range(maxits): - + # samples - S = np.zeros([NS,ND]) - + S = np.zeros([NS, ND]) + # populate samples for i_d in range(ND): - S[:,i_d] = ( np.random.random([1,NS]) + np.random.permutation(NS) ) / NS - XS = S*(XB[:,1]-XB[:,0]) + XB[:,0] - + S[:, i_d] = (np.random.random([1, NS]) + np.random.permutation(NS)) / NS + XS = S * (XB[:, 1] - XB[:, 0]) + XB[:, 0] + # add initial points - XX = np.vstack([ XI , XS ]) - + XX = np.vstack([XI, XS]) + # calc distances vecdiff = vec_dist(XX)[0] - + # update if vecdiff > mindiff: mindiff = vecdiff XO = XX - + #: for iterate - + return XO -def vec_dist(X,P=None): - ''' calculates distance between points in matrix X - with each other, or optionally to given point P - returns min, max and matrix/vector of distances - ''' - + +def vec_dist(X, P=None): + """calculates distance between points in matrix X + with each other, or optionally to given point P + returns min, max and matrix/vector of distances + """ + # distance matrix among X if P is None: - - nK,nD = X.shape - - d = np.zeros([nK,nK,nD]) + + nK, nD = X.shape + + d = np.zeros([nK, nK, nD]) for iD in range(nD): - d[:,:,iD] = np.array([X[:,iD]])-np.array([X[:,iD]]).T - D = np.sqrt( np.sum( d**2 , 2 ) ) - - diag_inf = np.diag( np.ones([nK])*np.inf ) - dmin = np.min(np.min( D + diag_inf )) - dmax = np.max(np.max( D )) - + d[:, :, iD] = np.array([X[:, iD]]) - np.array([X[:, iD]]).T + D = np.sqrt(np.sum(d**2, 2)) + + diag_inf = np.diag(np.ones([nK]) * np.inf) + dmin = np.min(np.min(D + diag_inf)) + dmax = np.max(np.max(D)) + # distance vector to P else: - assert P.shape[0] == 1 , 'P must be a horizontal vector' - D = np.array([ np.sqrt( np.sum( (X-P)**2 , 1 ) ) ]).T + assert P.shape[0] == 1, "P must be a horizontal vector" + D = np.array([np.sqrt(np.sum((X - P) ** 2, 1))]).T dmin = D.min() dmax = D.max() - - return (dmin,dmax,D) \ No newline at end of file + + return (dmin, dmax, D) diff --git a/SU2_PY/SU2/util/misc.py b/SU2_PY/SU2/util/misc.py index e90e901da33..aa5bbab5b0f 100644 --- a/SU2_PY/SU2/util/misc.py +++ b/SU2_PY/SU2/util/misc.py @@ -1,18 +1,17 @@ - import numpy as np -def check_array(A,oned_as='row'): - ''' ensures A is an array and at least of rank 2 - ''' - if not isinstance(A,np.ndarray): + +def check_array(A, oned_as="row"): + """ensures A is an array and at least of rank 2""" + if not isinstance(A, np.ndarray): A = np.array(A) if np.rank(A) < 2: A = np.array(np.matrix(A)) - if oned_as == 'row': + if oned_as == "row": pass - elif oned_as == 'col': + elif oned_as == "col": A = A.T else: raise Exception("oned_as must be 'row' or 'col' ") - - return A \ No newline at end of file + + return A diff --git a/SU2_PY/SU2/util/mp_eval.py b/SU2_PY/SU2/util/mp_eval.py index b97583d894e..2e9414d6928 100644 --- a/SU2_PY/SU2/util/mp_eval.py +++ b/SU2_PY/SU2/util/mp_eval.py @@ -7,123 +7,122 @@ # In Py3, range corresponds to Py2 xrange xrange = range + class mp_eval(object): - - def __init__(self,function,num_procs=None): - + def __init__(self, function, num_procs=None): + self.__name__ = function.__name__ - - tasks = mp.JoinableQueue() - results = mp.Queue() + + tasks = mp.JoinableQueue() + results = mp.Queue() function = TaskMaster(function) - + if num_procs is None: num_procs = mp.cpu_count() - - procs = [ QueueMaster( tasks, results, function ) - for i in xrange(num_procs) ] - - self.tasks = tasks - self.results = results + + procs = [QueueMaster(tasks, results, function) for i in xrange(num_procs)] + + self.tasks = tasks + self.results = results self.function = function - self.procs = procs - + self.procs = procs + return - - def __call__(self,inputs): - - tasks = self.tasks + + def __call__(self, inputs): + + tasks = self.tasks results = self.results - - if isinstance(inputs,np.ndarray): + + if isinstance(inputs, np.ndarray): n_inputs = inputs.shape[0] - elif isinstance(inputs,list): + elif isinstance(inputs, list): n_inputs = len(inputs) else: - raise Exception('unsupported input') - - for i_input,this_input in enumerate(inputs): - this_job = { 'index' : i_input , - 'input' : this_input , - 'result' : None } - tasks.put( this_job ) - #end + raise Exception("unsupported input") + + for i_input, this_input in enumerate(inputs): + this_job = {"index": i_input, "input": this_input, "result": None} + tasks.put(this_job) + # end # wait for tasks - tasks.join() - + tasks.join() + # pull results - result_list = [ [] ]*n_inputs + result_list = [[]] * n_inputs for i in xrange(n_inputs): result = results.get() - i_result = result['index'] - result_list[i_result] = result['result'] - + i_result = result["index"] + result_list[i_result] = result["result"] + return result_list def __del__(self): - + for proc in self.procs: self.tasks.put(None) - self.tasks.join() - + self.tasks.join() + return -class QueueMaster(mp.Process): - def __init__(self,task_queue,result_queue,task_class=None): +class QueueMaster(mp.Process): + def __init__(self, task_queue, result_queue, task_class=None): mp.Process.__init__(self) - self.task_queue = task_queue + self.task_queue = task_queue self.result_queue = result_queue - self.task_class = task_class - self.daemon = True + self.task_class = task_class + self.daemon = True self.start() def run(self): proc_name = self.name parentPID = os.getppid() - + while True: - + if os.getppid() != parentPID: - break # parent died + break # parent died this_job = self.task_queue.get() if this_job is None: self.task_queue.task_done() - break # kill signal - - this_input = this_job['input'] - this_task = self.task_class + break # kill signal + + this_input = this_job["input"] + this_task = self.task_class this_data = this_task(*this_input) - this_job['result'] = this_data + this_job["result"] = this_data self.result_queue.put(this_job) - + self.task_queue.task_done() - + #: while alive - + return + class TaskMaster(object): - def __init__(self, func): - self.func = func - def __call__(self, *arg, **kwarg): + self.func = func + + def __call__(self, *arg, **kwarg): # makes object callable result = self.func(*arg, **kwarg) return result + def __str__(self): - return '%s' % self.func + return "%s" % self.func # pickling - #def __getstate__(self): - #dict = self.__dict__.copy() - #data_dict = cloudpickle.dumps(dict) - #return data_dict - - #def __setstate__(self,data_dict): - #self.__dict__ = pickle.loads(data_dict) - #return + # def __getstate__(self): + # dict = self.__dict__.copy() + # data_dict = cloudpickle.dumps(dict) + # return data_dict + + # def __setstate__(self,data_dict): + # self.__dict__ = pickle.loads(data_dict) + # return diff --git a/SU2_PY/SU2/util/ordered_bunch.py b/SU2_PY/SU2/util/ordered_bunch.py index bc615ffdab0..e763bea6969 100644 --- a/SU2_PY/SU2/util/ordered_bunch.py +++ b/SU2_PY/SU2/util/ordered_bunch.py @@ -1,7 +1,7 @@ #!/usr/bin/env python """ OrderedBunch is a subclass of OrderedDict with attribute-style access. - + >>> b = OrderedBunch() >>> b.hello = 'world' >>> b.hello @@ -14,14 +14,14 @@ True >>> b.foo is b['foo'] True - + It is safe to import * from this module: - + __all__ = ('OrderedBunch', 'ordered_bunchify','ordered_unbunchify') - + ordered_un/bunchify provide dictionary conversion; Bunches can also be converted via OrderedBunch.to/fromOrderedDict(). - + original source: https://pypi.python.org/pypi/bunch """ @@ -29,101 +29,100 @@ from .ordered_dict import OrderedDict ## Compatability Issues... -#try: +# try: # from collections import OrderedDict -#except ImportError: +# except ImportError: # from ordered_dict import OrderedDict class OrderedBunch(OrderedDict): - """ A dictionary that provides attribute-style access. - - >>> b = OrderedBunch() - >>> b.hello = 'world' - >>> b.hello - 'world' - >>> b['hello'] += "!" - >>> b.hello - 'world!' - >>> b.foo = OrderedBunch(lol=True) - >>> b.foo.lol - True - >>> b.foo is b['foo'] - True - - A OrderedBunch is a subclass of dict; it supports all the methods a dict does... - - >>> b.keys() - ['foo', 'hello'] - - Including update()... - - >>> b.update({ 'ponies': 'are pretty!' }, hello=42) - >>> print(repr(b)) - OrderedBunch(foo=OrderedBunch(lol=True), hello=42, ponies='are pretty!') - - As well as iteration... - - >>> [ (k,b[k]) for k in b ] - [('ponies', 'are pretty!'), ('foo', OrderedBunch(lol=True)), ('hello', 42)] - - And "splats". - - >>> "The {knights} who say {ni}!".format(**OrderedBunch(knights='lolcats', ni='can haz')) - 'The lolcats who say can haz!' - - See ordered_unbunchify/OrderedBunch.toOrderedDict, ordered_bunchify/OrderedBunch.fromOrderedDict for notes about conversion. + """A dictionary that provides attribute-style access. + + >>> b = OrderedBunch() + >>> b.hello = 'world' + >>> b.hello + 'world' + >>> b['hello'] += "!" + >>> b.hello + 'world!' + >>> b.foo = OrderedBunch(lol=True) + >>> b.foo.lol + True + >>> b.foo is b['foo'] + True + + A OrderedBunch is a subclass of dict; it supports all the methods a dict does... + + >>> b.keys() + ['foo', 'hello'] + + Including update()... + + >>> b.update({ 'ponies': 'are pretty!' }, hello=42) + >>> print(repr(b)) + OrderedBunch(foo=OrderedBunch(lol=True), hello=42, ponies='are pretty!') + + As well as iteration... + + >>> [ (k,b[k]) for k in b ] + [('ponies', 'are pretty!'), ('foo', OrderedBunch(lol=True)), ('hello', 42)] + + And "splats". + + >>> "The {knights} who say {ni}!".format(**OrderedBunch(knights='lolcats', ni='can haz')) + 'The lolcats who say can haz!' + + See ordered_unbunchify/OrderedBunch.toOrderedDict, ordered_bunchify/OrderedBunch.fromOrderedDict for notes about conversion. """ - + _initialized = False - - def __init__(self,*args,**kwarg): - """ initializes the ordered dict - """ - super(OrderedBunch,self).__init__(*args,**kwarg) + + def __init__(self, *args, **kwarg): + """initializes the ordered dict""" + super(OrderedBunch, self).__init__(*args, **kwarg) self._initialized = True - + def __contains__(self, k): - """ >>> b = OrderedBunch(ponies='are pretty!') - >>> 'ponies' in b - True - >>> 'foo' in b - False - >>> b['foo'] = 42 - >>> 'foo' in b - True - >>> b.hello = 'hai' - >>> 'hello' in b - True + """>>> b = OrderedBunch(ponies='are pretty!') + >>> 'ponies' in b + True + >>> 'foo' in b + False + >>> b['foo'] = 42 + >>> 'foo' in b + True + >>> b.hello = 'hai' + >>> 'hello' in b + True """ try: return hasattr(self, k) or dict.__contains__(self, k) except: return False - - # only called if k not found in normal places + + # only called if k not found in normal places def __getattr__(self, k): - """ Gets key if it exists, otherwise throws AttributeError. - - nb. __getattr__ is only called if key is not found in normal places. - - >>> b = OrderedBunch(bar='baz', lol={}) - >>> b.foo - Traceback (most recent call last): - ... - AttributeError: foo - - >>> b.bar - 'baz' - >>> getattr(b, 'bar') - 'baz' - >>> b['bar'] - 'baz' - - >>> b.lol is b['lol'] - True - >>> b.lol is getattr(b, 'lol') - True + """Gets key if it exists, otherwise throws AttributeError. + + nb. __getattr__ is only called if key is not found in normal places. + + >>> b = OrderedBunch(bar='baz', lol={}) + >>> b.foo + Traceback (most recent call last): + ... + AttributeError: foo + + >>> b.bar + 'baz' + >>> getattr(b, 'bar') + 'baz' + >>> b['bar'] + 'baz' + + >>> b.lol is b['lol'] + True + >>> b.lol is getattr(b, 'lol') + True """ try: # Throws exception if not in prototype chain @@ -133,28 +132,28 @@ def __getattr__(self, k): return self[k] except KeyError: raise AttributeError(k) - + def __setattr__(self, k, v): - """ Sets attribute k if it exists, otherwise sets key k. A KeyError - raised by set-item (only likely if you subclass OrderedBunch) will - propagate as an AttributeError instead. - - >>> b = OrderedBunch(foo='bar', this_is='useful when subclassing') - >>> b.values #doctest: +ELLIPSIS - - >>> b.values = 'uh oh' - >>> b.values - 'uh oh' - >>> b['values'] - Traceback (most recent call last): - ... - KeyError: 'values' + """Sets attribute k if it exists, otherwise sets key k. A KeyError + raised by set-item (only likely if you subclass OrderedBunch) will + propagate as an AttributeError instead. + + >>> b = OrderedBunch(foo='bar', this_is='useful when subclassing') + >>> b.values #doctest: +ELLIPSIS + + >>> b.values = 'uh oh' + >>> b.values + 'uh oh' + >>> b['values'] + Traceback (most recent call last): + ... + KeyError: 'values' """ - + if not self._initialized: # for OrderedDict initialization return object.__setattr__(self, k, v) - + try: # Throws exception if not in prototype chain object.__getattribute__(self, k) @@ -165,22 +164,22 @@ def __setattr__(self, k, v): raise AttributeError(k) else: object.__setattr__(self, k, v) - + def __delattr__(self, k): - """ Deletes attribute k if it exists, otherwise deletes key k. A KeyError - raised by deleting the key--such as when the key is missing--will - propagate as an AttributeError instead. - - >>> b = OrderedBunch(lol=42) - >>> del b.values - Traceback (most recent call last): - ... - AttributeError: 'OrderedBunch' object attribute 'values' is read-only - >>> del b.lol - >>> b.lol - Traceback (most recent call last): - ... - AttributeError: lol + """Deletes attribute k if it exists, otherwise deletes key k. A KeyError + raised by deleting the key--such as when the key is missing--will + propagate as an AttributeError instead. + + >>> b = OrderedBunch(lol=42) + >>> del b.values + Traceback (most recent call last): + ... + AttributeError: 'OrderedBunch' object attribute 'values' is read-only + >>> del b.lol + >>> b.lol + Traceback (most recent call last): + ... + AttributeError: lol """ try: # Throws exception if not in prototype chain @@ -192,54 +191,52 @@ def __delattr__(self, k): raise AttributeError(k) else: object.__delattr__(self, k) - + def toOrderedDict(self): - """ Recursively converts a bunch back into a dictionary. - - >>> b = OrderedBunch(OrderedBunchunch(lol=True), hello=42, ponies='are pretty!') - >>> b.toOrderedDict() - {'ponies': 'are pretty!', 'foo': {'lol': True}, 'hello': 42} - - See ordered_unbunchify for more info. + """Recursively converts a bunch back into a dictionary. + + >>> b = OrderedBunch(OrderedBunchunch(lol=True), hello=42, ponies='are pretty!') + >>> b.toOrderedDict() + {'ponies': 'are pretty!', 'foo': {'lol': True}, 'hello': 42} + + See ordered_unbunchify for more info. """ return ordered_unbunchify(self) - + def __repr__(self): - """ Invertible* string-form of a OrderedBunch. - - >>> b = OrderedBunch(foo=OrderedBunch(lol=True), hello=42, ponies='are pretty!') - >>> print(repr(b)) - OrderedBunch(foo=OrderedBunch(lol=True), hello=42, ponies='are pretty!') - >>> eval(repr(b)) - OrderedBunch(foo=OrderedBunch(lol=True), hello=42, ponies='are pretty!') - - (*) Invertible so long as collection contents are each repr-invertible. + """Invertible* string-form of a OrderedBunch. + + >>> b = OrderedBunch(foo=OrderedBunch(lol=True), hello=42, ponies='are pretty!') + >>> print(repr(b)) + OrderedBunch(foo=OrderedBunch(lol=True), hello=42, ponies='are pretty!') + >>> eval(repr(b)) + OrderedBunch(foo=OrderedBunch(lol=True), hello=42, ponies='are pretty!') + + (*) Invertible so long as collection contents are each repr-invertible. """ keys = self.keys() - args = ', '.join(['%s=%r' % (key, self[key]) for key in keys]) - return '%s(%s)' % (self.__class__.__name__, args) - + args = ", ".join(["%s=%r" % (key, self[key]) for key in keys]) + return "%s(%s)" % (self.__class__.__name__, args) + def __str__(self): - """ String-form of a Bunch. - """ + """String-form of a Bunch.""" keys = self.keys() - args = ', '.join(['%s=%r' % (key, self[key]) for key in keys]) - return '{%s}' % args - + args = ", ".join(["%s=%r" % (key, self[key]) for key in keys]) + return "{%s}" % args + @staticmethod def fromOrderedDict(d): - """ Recursively transforms a dictionary into a OrderedBunch via copy. - - >>> b = OrderedBunch.fromOrderedDict({'urmom': {'sez': {'what': 'what'}}}) - >>> b.urmom.sez.what - 'what' - - See ordered_bunchify for more info. + """Recursively transforms a dictionary into a OrderedBunch via copy. + + >>> b = OrderedBunch.fromOrderedDict({'urmom': {'sez': {'what': 'what'}}}) + >>> b.urmom.sez.what + 'what' + + See ordered_bunchify for more info. """ return ordered_bunchify(d) - # While we could convert abstract types like Mapping or Iterable, I think # ordered_bunchify is more likely to "do what you mean" if it is conservative about # casting (ex: isinstance(str,Iterable) == True ). @@ -247,56 +244,58 @@ def fromOrderedDict(d): # Should you disagree, it is not difficult to duplicate this function with # more aggressive coercion to suit your own purposes. + def ordered_bunchify(x): - """ Recursively transforms a dictionary into a OrderedBunch via copy. - - >>> b = ordered_bunchify({'urmom': {'sez': {'what': 'what'}}}) - >>> b.urmom.sez.what - 'what' - - ordered_bunchify can handle intermediary dicts, lists and tuples (as well as - their subclasses), but ymmv on custom datatypes. - - >>> b = ordered_bunchify({ 'lol': ('cats', {'hah':'i win again'}), - ... 'hello': [{'french':'salut', 'german':'hallo'}] }) - >>> b.hello[0].french - 'salut' - >>> b.lol[1].hah - 'i win again' - - nb. As dicts are not hashable, they cannot be nested in sets/frozensets. + """Recursively transforms a dictionary into a OrderedBunch via copy. + + >>> b = ordered_bunchify({'urmom': {'sez': {'what': 'what'}}}) + >>> b.urmom.sez.what + 'what' + + ordered_bunchify can handle intermediary dicts, lists and tuples (as well as + their subclasses), but ymmv on custom datatypes. + + >>> b = ordered_bunchify({ 'lol': ('cats', {'hah':'i win again'}), + ... 'hello': [{'french':'salut', 'german':'hallo'}] }) + >>> b.hello[0].french + 'salut' + >>> b.lol[1].hah + 'i win again' + + nb. As dicts are not hashable, they cannot be nested in sets/frozensets. """ if isinstance(x, dict): - return OrderedBunch( (k, ordered_bunchify(v)) for k,v in x.iteritems() ) + return OrderedBunch((k, ordered_bunchify(v)) for k, v in x.iteritems()) elif isinstance(x, (list, tuple)): - return type(x)( ordered_bunchify(v) for v in x ) + return type(x)(ordered_bunchify(v) for v in x) else: return x + def ordered_unbunchify(x): - """ Recursively converts a OrderedBunch into a dictionary. - - >>> b = OrderedBunch(foo=OrderedBunch(lol=True), hello=42, ponies='are pretty!') - >>> ordered_unbunchify(b) - {'ponies': 'are pretty!', 'foo': {'lol': True}, 'hello': 42} - - ordered_unbunchify will handle intermediary dicts, lists and tuples (as well as - their subclasses), but ymmv on custom datatypes. - - >>> b = OrderedBunch(foo=['bar', OrderedBunch(lol=True)], hello=42, - ... ponies=('are pretty!', OrderedBunch(lies='are trouble!'))) - >>> ordered_unbunchify(b) #doctest: +NORMALIZE_WHITESPACE - {'ponies': ('are pretty!', {'lies': 'are trouble!'}), - 'foo': ['bar', {'lol': True}], 'hello': 42} - - nb. As dicts are not hashable, they cannot be nested in sets/frozensets. + """Recursively converts a OrderedBunch into a dictionary. + + >>> b = OrderedBunch(foo=OrderedBunch(lol=True), hello=42, ponies='are pretty!') + >>> ordered_unbunchify(b) + {'ponies': 'are pretty!', 'foo': {'lol': True}, 'hello': 42} + + ordered_unbunchify will handle intermediary dicts, lists and tuples (as well as + their subclasses), but ymmv on custom datatypes. + + >>> b = OrderedBunch(foo=['bar', OrderedBunch(lol=True)], hello=42, + ... ponies=('are pretty!', OrderedBunch(lies='are trouble!'))) + >>> ordered_unbunchify(b) #doctest: +NORMALIZE_WHITESPACE + {'ponies': ('are pretty!', {'lies': 'are trouble!'}), + 'foo': ['bar', {'lol': True}], 'hello': 42} + + nb. As dicts are not hashable, they cannot be nested in sets/frozensets. """ if isinstance(x, OrderedDict): - return OrderedDict( (k, ordered_unbunchify(v)) for k,v in x.iteritems() ) + return OrderedDict((k, ordered_unbunchify(v)) for k, v in x.iteritems()) elif isinstance(x, dict): - return dict( (k, ordered_unbunchify(v)) for k,v in x.iteritems() ) + return dict((k, ordered_unbunchify(v)) for k, v in x.iteritems()) elif isinstance(x, (list, tuple)): - return type(x)( ordered_unbunchify(v) for v in x ) + return type(x)(ordered_unbunchify(v) for v in x) else: return x @@ -308,115 +307,110 @@ def ordered_unbunchify(x): import json except ImportError: import simplejson as json - + def toJSON(self, **options): - """ Serializes this OrderedBunch to JSON. Accepts the same keyword options as `json.dumps()`. - - >>> b = OrderedBunch(foo=OrderedBunch(lol=True), hello=42, ponies='are pretty!') - >>> json.dumps(b) - '{"ponies": "are pretty!", "foo": {"lol": true}, "hello": 42}' - >>> b.toJSON() - '{"ponies": "are pretty!", "foo": {"lol": true}, "hello": 42}' + """Serializes this OrderedBunch to JSON. Accepts the same keyword options as `json.dumps()`. + + >>> b = OrderedBunch(foo=OrderedBunch(lol=True), hello=42, ponies='are pretty!') + >>> json.dumps(b) + '{"ponies": "are pretty!", "foo": {"lol": true}, "hello": 42}' + >>> b.toJSON() + '{"ponies": "are pretty!", "foo": {"lol": true}, "hello": 42}' """ return json.dumps(self, **options) - + OrderedBunch.toJSON = toJSON - + except ImportError: pass - - try: # Attempt to register ourself with PyYAML as a representer import yaml from yaml.representer import Representer, SafeRepresenter - + def from_yaml(loader, node): - """ PyYAML support for Bunches using the tag `!bunch` and `!bunch.OrderedBunch`. - - >>> import yaml - >>> yaml.load(''' - ... Flow style: !bunch.OrderedBunch { Clark: Evans, Brian: Ingerson, Oren: Ben-Kiki } - ... Block style: !bunch - ... Clark : Evans - ... Brian : Ingerson - ... Oren : Ben-Kiki - ... ''') #doctest: +NORMALIZE_WHITESPACE - {'Flow style': OrderedBunch(Brian='Ingerson', Clark='Evans', Oren='Ben-Kiki'), - 'Block style': OrderedBunch(Brian='Ingerson', Clark='Evans', Oren='Ben-Kiki')} - - This module registers itself automatically to cover both OrderedBunch and any - subclasses. Should you want to customize the representation of a subclass, - simply register it with PyYAML yourself. + """PyYAML support for Bunches using the tag `!bunch` and `!bunch.OrderedBunch`. + + >>> import yaml + >>> yaml.load(''' + ... Flow style: !bunch.OrderedBunch { Clark: Evans, Brian: Ingerson, Oren: Ben-Kiki } + ... Block style: !bunch + ... Clark : Evans + ... Brian : Ingerson + ... Oren : Ben-Kiki + ... ''') #doctest: +NORMALIZE_WHITESPACE + {'Flow style': OrderedBunch(Brian='Ingerson', Clark='Evans', Oren='Ben-Kiki'), + 'Block style': OrderedBunch(Brian='Ingerson', Clark='Evans', Oren='Ben-Kiki')} + + This module registers itself automatically to cover both OrderedBunch and any + subclasses. Should you want to customize the representation of a subclass, + simply register it with PyYAML yourself. """ data = OrderedBunch() yield data value = loader.construct_mapping(node) data.update(value) - - + def to_yaml_safe(dumper, data): - """ Converts OrderedBunch to a normal mapping node, making it appear as a - dict in the YAML output. - - >>> b = OrderedBunch(foo=['bar', OrderedBunch(lol=True)], hello=42) - >>> import yaml - >>> yaml.safe_dump(b, default_flow_style=True) - '{foo: [bar, {lol: true}], hello: 42}\\n' + """Converts OrderedBunch to a normal mapping node, making it appear as a + dict in the YAML output. + + >>> b = OrderedBunch(foo=['bar', OrderedBunch(lol=True)], hello=42) + >>> import yaml + >>> yaml.safe_dump(b, default_flow_style=True) + '{foo: [bar, {lol: true}], hello: 42}\\n' """ return dumper.represent_dict(data) - + def to_yaml(dumper, data): - """ Converts OrderedBunch to a representation node. - - >>> b = OrderedBunch(foo=['bar', OrderedBunch(lol=True)], hello=42) - >>> import yaml - >>> yaml.dump(b, default_flow_style=True) - '!bunch.OrderedBunch {foo: [bar, !bunch.OrderedBunch {lol: true}], hello: 42}\\n' + """Converts OrderedBunch to a representation node. + + >>> b = OrderedBunch(foo=['bar', OrderedBunch(lol=True)], hello=42) + >>> import yaml + >>> yaml.dump(b, default_flow_style=True) + '!bunch.OrderedBunch {foo: [bar, !bunch.OrderedBunch {lol: true}], hello: 42}\\n' """ - return dumper.represent_mapping(u'!orderedbunch.OrderedBunch', data) - - - yaml.add_constructor(u'!orderedbunch', from_yaml) - yaml.add_constructor(u'!orderedbunch.OrderedBunch', from_yaml) - + return dumper.represent_mapping("!orderedbunch.OrderedBunch", data) + + yaml.add_constructor("!orderedbunch", from_yaml) + yaml.add_constructor("!orderedbunch.OrderedBunch", from_yaml) + SafeRepresenter.add_representer(OrderedBunch, to_yaml_safe) SafeRepresenter.add_multi_representer(OrderedBunch, to_yaml_safe) - + Representer.add_representer(OrderedBunch, to_yaml) Representer.add_multi_representer(OrderedBunch, to_yaml) - - + # Instance methods for YAML conversion def toYAML(self, **options): - """ Serializes this OrderedBunch to YAML, using `yaml.safe_dump()` if - no `Dumper` is provided. See the PyYAML documentation for more info. - - >>> b = OrderedBunch(foo=['bar', OrderedBunch(lol=True)], hello=42) - >>> import yaml - >>> yaml.safe_dump(b, default_flow_style=True) - '{foo: [bar, {lol: true}], hello: 42}\\n' - >>> b.toYAML(default_flow_style=True) - '{foo: [bar, {lol: true}], hello: 42}\\n' - >>> yaml.dump(b, default_flow_style=True) - '!bunch.OrderedBunch {foo: [bar, !bunch.OrderedBunch {lol: true}], hello: 42}\\n' - >>> b.toYAML(Dumper=yaml.Dumper, default_flow_style=True) - '!bunch.OrderedBunch {foo: [bar, !bunch.OrderedBunch {lol: true}], hello: 42}\\n' + """Serializes this OrderedBunch to YAML, using `yaml.safe_dump()` if + no `Dumper` is provided. See the PyYAML documentation for more info. + + >>> b = OrderedBunch(foo=['bar', OrderedBunch(lol=True)], hello=42) + >>> import yaml + >>> yaml.safe_dump(b, default_flow_style=True) + '{foo: [bar, {lol: true}], hello: 42}\\n' + >>> b.toYAML(default_flow_style=True) + '{foo: [bar, {lol: true}], hello: 42}\\n' + >>> yaml.dump(b, default_flow_style=True) + '!bunch.OrderedBunch {foo: [bar, !bunch.OrderedBunch {lol: true}], hello: 42}\\n' + >>> b.toYAML(Dumper=yaml.Dumper, default_flow_style=True) + '!bunch.OrderedBunch {foo: [bar, !bunch.OrderedBunch {lol: true}], hello: 42}\\n' """ opts = dict(indent=4, default_flow_style=False) opts.update(options) - if 'Dumper' not in opts: + if "Dumper" not in opts: return yaml.safe_dump(self, **opts) else: return yaml.dump(self, **opts) - + def fromYAML(*args, **kwargs): - return ordered_bunchify( yaml.load(*args, **kwargs) ) - + return ordered_bunchify(yaml.load(*args, **kwargs)) + OrderedBunch.toYAML = OrderedBunch.__repr__ = toYAML OrderedBunch.fromYAML = staticmethod(fromYAML) - + except ImportError: pass diff --git a/SU2_PY/SU2/util/ordered_dict.py b/SU2_PY/SU2/util/ordered_dict.py index 0813b65a13a..c2d244f4b50 100644 --- a/SU2_PY/SU2/util/ordered_dict.py +++ b/SU2_PY/SU2/util/ordered_dict.py @@ -1,4 +1,3 @@ - """ Backport of OrderedDict() class that runs on Python 2.4, 2.5, 2.6, 2.7 and pypy. Passes Python2.7's test suite and incorporates all the latest updates. {{{ http://code.activestate.com/recipes/576693/ (r9) @@ -21,6 +20,7 @@ class OrderedDict(dict): """Dictionary that remembers insertion order""" + # An inherited dict maps keys to values. # The inherited dict provides __getitem__, __len__, __contains__, and get. # The remaining methods are order-aware. @@ -32,23 +32,23 @@ class OrderedDict(dict): # Each link is stored as a list of length three: [PREV, NEXT, KEY]. def __init__(self, *args, **kwds): - '''Initialize an ordered dictionary. Signature is the same as for + """Initialize an ordered dictionary. Signature is the same as for regular dictionaries, but keyword arguments are not recommended because their insertion order is arbitrary. - ''' + """ if len(args) > 1: - raise TypeError('expected at most 1 arguments, got %d' % len(args)) + raise TypeError("expected at most 1 arguments, got %d" % len(args)) try: self.__root except AttributeError: - self.__root = root = [] # sentinel node + self.__root = root = [] # sentinel node root[:] = [root, root, None] self.__map = {} self.__update(*args, **kwds) def __setitem__(self, key, value, dict_setitem=dict.__setitem__): - 'od.__setitem__(i, y) <==> od[i]=y' + "od.__setitem__(i, y) <==> od[i]=y" # Setting a new item creates a new link which goes at the end of the linked # list, and the inherited dictionary is updated with the new key/value pair. if key not in self: @@ -58,7 +58,7 @@ def __setitem__(self, key, value, dict_setitem=dict.__setitem__): dict_setitem(self, key, value) def __delitem__(self, key, dict_delitem=dict.__delitem__): - 'od.__delitem__(y) <==> del od[y]' + "od.__delitem__(y) <==> del od[y]" # Deleting an existing item uses self.__map to find the link which is # then removed by updating the links in the predecessor and successor nodes. dict_delitem(self, key) @@ -67,7 +67,7 @@ def __delitem__(self, key, dict_delitem=dict.__delitem__): link_next[0] = link_prev def __iter__(self): - 'od.__iter__() <==> iter(od)' + "od.__iter__() <==> iter(od)" root = self.__root curr = root[1] while curr is not root: @@ -75,7 +75,7 @@ def __iter__(self): curr = curr[1] def __reversed__(self): - 'od.__reversed__() <==> reversed(od)' + "od.__reversed__() <==> reversed(od)" root = self.__root curr = root[0] while curr is not root: @@ -83,7 +83,7 @@ def __reversed__(self): curr = curr[0] def clear(self): - 'od.clear() -> None. Remove all items from od.' + "od.clear() -> None. Remove all items from od." try: for node in self.__map.itervalues(): del node[:] @@ -95,12 +95,12 @@ def clear(self): dict.clear(self) def popitem(self, last=True): - '''od.popitem() -> (k, v), return and remove a (key, value) pair. + """od.popitem() -> (k, v), return and remove a (key, value) pair. Pairs are returned in LIFO order if last is true or FIFO order if false. - ''' + """ if not self: - raise KeyError('dictionary is empty') + raise KeyError("dictionary is empty") root = self.__root if last: link = root[0] @@ -120,45 +120,47 @@ def popitem(self, last=True): # -- the following methods do not depend on the internal structure -- def keys(self): - 'od.keys() -> list of keys in od' + "od.keys() -> list of keys in od" return list(self) def values(self): - 'od.values() -> list of values in od' + "od.values() -> list of values in od" return [self[key] for key in self] def items(self): - 'od.items() -> list of (key, value) pairs in od' + "od.items() -> list of (key, value) pairs in od" return [(key, self[key]) for key in self] def iterkeys(self): - 'od.iterkeys() -> an iterator over the keys in od' + "od.iterkeys() -> an iterator over the keys in od" return iter(self) def itervalues(self): - 'od.itervalues -> an iterator over the values in od' + "od.itervalues -> an iterator over the values in od" for k in self: yield self[k] def iteritems(self): - 'od.iteritems -> an iterator over the (key, value) items in od' + "od.iteritems -> an iterator over the (key, value) items in od" for k in self: yield (k, self[k]) def update(*args, **kwds): - '''od.update(E, **F) -> None. Update od from dict/iterable E and F. + """od.update(E, **F) -> None. Update od from dict/iterable E and F. If E is a dict instance, does: for k in E: od[k] = E[k] If E has a .keys() method, does: for k in E.keys(): od[k] = E[k] Or if E is an iterable of items, does: for k, v in E: od[k] = v In either case, this is followed by: for k, v in F.items(): od[k] = v - ''' + """ if len(args) > 2: - raise TypeError('update() takes at most 2 positional ' - 'arguments (%d given)' % (len(args),)) + raise TypeError( + "update() takes at most 2 positional " + "arguments (%d given)" % (len(args),) + ) elif not args: - raise TypeError('update() takes at least 1 argument (0 given)') + raise TypeError("update() takes at least 1 argument (0 given)") self = args[0] # Make progressively weaker assumptions about "other" other = () @@ -167,7 +169,7 @@ def update(*args, **kwds): if isinstance(other, dict): for key in other: self[key] = other[key] - elif hasattr(other, 'keys'): + elif hasattr(other, "keys"): for key in other.keys(): self[key] = other[key] else: @@ -181,10 +183,10 @@ def update(*args, **kwds): __marker = object() def pop(self, key, default=__marker): - '''od.pop(k[,d]) -> v, remove specified key and return the corresponding value. + """od.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised. - ''' + """ if key in self: result = self[key] del self[key] @@ -194,27 +196,27 @@ def pop(self, key, default=__marker): return default def setdefault(self, key, default=None): - 'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od' + "od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od" if key in self: return self[key] self[key] = default return default def __repr__(self, _repr_running={}): - 'od.__repr__() <==> repr(od)' + "od.__repr__() <==> repr(od)" call_key = id(self), _get_ident() if call_key in _repr_running: - return '...' + return "..." _repr_running[call_key] = 1 try: if not self: - return '%s()' % (self.__class__.__name__,) - return '%s(%r)' % (self.__class__.__name__, self.items()) + return "%s()" % (self.__class__.__name__,) + return "%s(%r)" % (self.__class__.__name__, self.items()) finally: del _repr_running[call_key] def __reduce__(self): - 'Return state information for pickling' + "Return state information for pickling" items = [[k, self[k]] for k in self] inst_dict = vars(self).copy() for k in vars(OrderedDict()): @@ -224,27 +226,27 @@ def __reduce__(self): return self.__class__, (items,) def copy(self): - 'od.copy() -> a shallow copy of od' + "od.copy() -> a shallow copy of od" return self.__class__(self) @classmethod def fromkeys(cls, iterable, value=None): - '''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S + """OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S and values equal to v (which defaults to None). - ''' + """ d = cls() for key in iterable: d[key] = value return d def __eq__(self, other): - '''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive + """od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive while comparison to a regular mapping is order-insensitive. - ''' + """ if isinstance(other, OrderedDict): - return len(self)==len(other) and self.items() == other.items() + return len(self) == len(other) and self.items() == other.items() return dict.__eq__(self, other) def __ne__(self, other): @@ -263,4 +265,6 @@ def viewvalues(self): def viewitems(self): "od.viewitems() -> a set-like object providing a view on od's items" return ItemsView(self) + + ## end of http://code.activestate.com/recipes/576693/ }}} diff --git a/SU2_PY/SU2/util/plot.py b/SU2_PY/SU2/util/plot.py index d07a510f37d..1591c7849e1 100644 --- a/SU2_PY/SU2/util/plot.py +++ b/SU2_PY/SU2/util/plot.py @@ -26,67 +26,71 @@ # License along with SU2. If not, see . -def write_plot(filename,plot_format,data_plot,keys_plot=None): - """ write_plot(filename,plot_format,data_plot,keys_plot=[]) - writes a tecplot or paraview plot of dictionary data - data_plot is a dictionary of lists with equal length - if data_plot is an ordered dictionary, will output in order - otherwise use keys_plot to specify the order of output +def write_plot(filename, plot_format, data_plot, keys_plot=None): + """write_plot(filename,plot_format,data_plot,keys_plot=[]) + writes a tecplot or paraview plot of dictionary data + data_plot is a dictionary of lists with equal length + if data_plot is an ordered dictionary, will output in order + otherwise use keys_plot to specify the order of output """ default_spacing = 16 - indent_spacing = 0 + indent_spacing = 0 - if keys_plot is None: keys_plot = [] + if keys_plot is None: + keys_plot = [] if not keys_plot: keys_plot = data_plot.keys() - keys_print = [ '"'+key+'"' for key in keys_plot ] + keys_print = ['"' + key + '"' for key in keys_plot] keys_space = [default_spacing] * len(keys_plot) - header = '' - if (plot_format == 'TECPLOT'): - header = 'VARIABLES=' + header = "" + if plot_format == "TECPLOT": + header = "VARIABLES=" indent_spacing += 10 - indent_spacing = ' '*indent_spacing + indent_spacing = " " * indent_spacing n_lines = 0 - for i,key in enumerate(keys_plot): + for i, key in enumerate(keys_plot): # check vector lengths value = data_plot[key] if i == 0: n_lines = len(value) else: - assert n_lines == len(value) , 'unequal plot vector lengths' + assert n_lines == len(value), "unequal plot vector lengths" # check spacing if len(key) > keys_space[i]: keys_space[i] = len(key) keys_space[i] = "%-" + str(keys_space[i]) + "s" - plotfile = open(filename,'w') + plotfile = open(filename, "w") plotfile.write(header) - for i,key in enumerate(keys_print): - if i > 0: plotfile.write(", ") + for i, key in enumerate(keys_print): + if i > 0: + plotfile.write(", ") plotfile.write(keys_space[i] % key) - plotfile.write('\n') + plotfile.write("\n") for i_line in range(n_lines): plotfile.write(indent_spacing) - for j,key in enumerate(keys_plot): + for j, key in enumerate(keys_plot): value = data_plot[key] - if j > 0: plotfile.write(", ") + if j > 0: + plotfile.write(", ") plotfile.write(keys_space[j] % value[i_line]) - plotfile.write('\n') + plotfile.write("\n") plotfile.close() return -def tecplot(filename,data_plot,keys_plot=[]): - write_plot(filename,'TECPLOT',data_plot,keys_plot) -def paraview(filename,data_plot,keys_plot=[]): - write_plot(filename,'CSV',data_plot,keys_plot) +def tecplot(filename, data_plot, keys_plot=[]): + write_plot(filename, "TECPLOT", data_plot, keys_plot) + +def paraview(filename, data_plot, keys_plot=[]): + write_plot(filename, "CSV", data_plot, keys_plot) diff --git a/SU2_PY/SU2/util/polarSweepLib.py b/SU2_PY/SU2/util/polarSweepLib.py index 7d79f1b3dde..f242769a43a 100755 --- a/SU2_PY/SU2/util/polarSweepLib.py +++ b/SU2_PY/SU2/util/polarSweepLib.py @@ -1,4 +1,3 @@ - # \file polarSweepLib.py # \brief Functions library for compute_polar.py script. # \author E Arad @@ -28,979 +27,1188 @@ from numpy import * -def parLocator(keyWord,b,n,iDoNot,verbose): +def parLocator(keyWord, b, n, iDoNot, verbose): -#---- -- locate the relevant line in base input file -# --- do not select line iDoNot (unless it is -1) -# - keyWord=keyWord.lower() - iFocus=-1 + # ---- -- locate the relevant line in base input file + # --- do not select line iDoNot (unless it is -1) + # + keyWord = keyWord.lower() + iFocus = -1 icol = -1 for i in range(1, n): - lineString=str(b[i]).lower() -# check if : exist in line + lineString = str(b[i]).lower() + # check if : exist in line try: - icol=lineString.index(':') + icol = lineString.index(":") except ValueError: - pass # do nothing - if icol > -1 : -# verify that this line was not commented out + pass # do nothing + if icol > -1: + # verify that this line was not commented out try: - ii=lineString[:icol-1].index('#') - pass # do nothing + ii = lineString[: icol - 1].index("#") + pass # do nothing except ValueError: -# This line wasn't commented out + # This line wasn't commented out try: - ii=lineString.index(keyWord) + ii = lineString.index(keyWord) if i != iDoNot: -# string.index and not string.find is used here, since index raises -# exception when search is failed + # string.index and not string.find is used here, since index raises + # exception when search is failed if verbose: - print('parLocator: '+str(i)+' found: '+str(b[i])) - iFocus=i + print("parLocator: " + str(i) + " found: " + str(b[i])) + iFocus = i break else: - iFocus=-1 + iFocus = -1 except ValueError: - pass # do nothing + pass # do nothing if iFocus == -1: if verbose: - print('parLocator: Keyword ->'+str(keyWord)+'<- not found') + print("parLocator: Keyword ->" + str(keyWord) + "<- not found") return iFocus -def stringLocator(keyWord,b,n,verbose): -#---- -- locate the relevant line in a file -# - keyWord=keyWord.lower() - iFocus=-1 +def stringLocator(keyWord, b, n, verbose): + + # ---- -- locate the relevant line in a file + # + keyWord = keyWord.lower() + iFocus = -1 for i in range(1, n): - lineString=str(b[i]).lower() + lineString = str(b[i]).lower() try: - ii=lineString.index(keyWord) + ii = lineString.index(keyWord) if verbose: - print('parLocator: '+str(i)+' found: '+str(b[i])) - iFocus=i + print("parLocator: " + str(i) + " found: " + str(b[i])) + iFocus = i break except ValueError: - pass # do nothing + pass # do nothing if iFocus == -1: if verbose: - print('parLocator: Keyword ->'+str(keyWord)+'<- not found') + print("parLocator: Keyword ->" + str(keyWord) + "<- not found") return iFocus -def readList(dataFile,iLine,verbose): +def readList(dataFile, iLine, verbose): from numpy import size -# -#----read list from file to a local float list -# - listDataLine=dataFile[iLine] - icol=listDataLine.index(':') - Data=listDataLine[icol+1:] - lData=Data.split(',') - nData=size(lData) + + # + # ----read list from file to a local float list + # + listDataLine = dataFile[iLine] + icol = listDataLine.index(":") + Data = listDataLine[icol + 1 :] + lData = Data.split(",") + nData = size(lData) if verbose: - print('readList nData = '+str(nData)) - fData=map(float,lData) + print("readList nData = " + str(nData)) + fData = map(float, lData) return list(fData), nData -def readParameter(dataFile,nLines,keyWord,iDoNot,verbose): + +def readParameter(dataFile, nLines, keyWord, iDoNot, verbose): from numpy import size -# -#----read a parameter from a file-list -# - keyWord=keyWord.lower() - ipar = parLocator(keyWord,dataFile,nLines,iDoNot,verbose) + + # + # ----read a parameter from a file-list + # + keyWord = keyWord.lower() + ipar = parLocator(keyWord, dataFile, nLines, iDoNot, verbose) if ipar == -1: if verbose: - print(' failed to locate '+keyWord+' in base input file; Set value to 1') + print( + " failed to locate " + keyWord + " in base input file; Set value to 1" + ) paVal = 1 else: - paLine=dataFile[ipar] - icol=paLine.index(':') + paLine = dataFile[ipar] + icol = paLine.index(":") try: - iComment=paLine.index('#') - paVal=paLine[icol+1:iComment-1].lower() + iComment = paLine.index("#") + paVal = paLine[icol + 1 : iComment - 1].lower() except ValueError: - paVal=paLine[icol+1:].lower() + paVal = paLine[icol + 1 :].lower() if verbose: if ipar != -1: - print(keyWord + ' = ' + paVal) + print(keyWord + " = " + paVal) - return paVal,ipar + return paVal, ipar -def setContribution(dataFile,nLines,keyWord,iDoNot,verbose): + +def setContribution(dataFile, nLines, keyWord, iDoNot, verbose): from numpy import size import string -# -# default values -# - nameText='' + + # + # default values + # + nameText = "" removeContribution = False -# -#----Determine if a given amily contribute to force -# -# Start by locating lines setting contribution -# - keyWord=keyWord.lower() - ipar = parLocator(keyWord,dataFile,nLines,iDoNot,verbose) + # + # ----Determine if a given amily contribute to force + # + # Start by locating lines setting contribution + # + keyWord = keyWord.lower() + ipar = parLocator(keyWord, dataFile, nLines, iDoNot, verbose) if ipar == -1: if verbose: - print(' failed to locate '+keyWord+' in base input file; Set value to 1') + print( + " failed to locate " + keyWord + " in base input file; Set value to 1" + ) paVal = 1 else: - paLine=dataFile[ipar] - icol=paLine.index(':') + paLine = dataFile[ipar] + icol = paLine.index(":") -# Now identify the first part of this line + # Now identify the first part of this line firstPart = paLine[0:icol] -# now find out where the standard text ends - iBF=firstPart.lower().index('family')+6 - nameText=string.join( firstPart[iBF:].split(), "") + # now find out where the standard text ends + iBF = firstPart.lower().index("family") + 6 + nameText = string.join(firstPart[iBF:].split(), "") -# component name located. Now check about its contribution + # component name located. Now check about its contribution try: - iComment=paLine.index('#') - secondPart=paLine[icol+1:iComment-1].lower() + iComment = paLine.index("#") + secondPart = paLine[icol + 1 : iComment - 1].lower() except ValueError: - secondPart=paLine[icol+1:].lower() + secondPart = paLine[icol + 1 :].lower() -# find the second colon of this line - icol2=secondPart.index(':') + # find the second colon of this line + icol2 = secondPart.index(":") try: - iComment=secondPart.index('#') - yesNoText=secondPart[icol2+1:iComment-1].lower() + iComment = secondPart.index("#") + yesNoText = secondPart[icol2 + 1 : iComment - 1].lower() except ValueError: - yesNoText=secondPart[icol2+1:].lower() + yesNoText = secondPart[icol2 + 1 :].lower() try: - noFound=yesNoText.lower().index('no') + noFound = yesNoText.lower().index("no") removeContribution = True except ValueError: - removeContribution = False + removeContribution = False if verbose: if ipar != -1: - print(' part: '+nameText+' remove contribution: '+str(removeContribution)) + print( + " part: " + + nameText + + " remove contribution: " + + str(removeContribution) + ) - return nameText,removeContribution,ipar + return nameText, removeContribution, ipar -def setPolaraType(ctrl,nc,verbose): +def setPolaraType(ctrl, nc, verbose): -# scan the control file and determine polara type and angles -# Determine pitch direction from control file -# --------------------------------------------------- + # scan the control file and determine polara type and angles + # Determine pitch direction from control file + # --------------------------------------------------- - keyWordPitchAxis='pitch axis' - iPA = parLocator(keyWordPitchAxis,ctrl,nc,-1,verbose) + keyWordPitchAxis = "pitch axis" + iPA = parLocator(keyWordPitchAxis, ctrl, nc, -1, verbose) if iPA == -1: - PA='z' # This is the default + PA = "z" # This is the default else: - paLine=ctrl[iPA] - icol=paLine.index(':') - paVal=paLine[icol+1:].lower() - zFound = 'z' in paVal + paLine = ctrl[iPA] + icol = paLine.index(":") + paVal = paLine[icol + 1 :].lower() + zFound = "z" in paVal if zFound: - PA='z' + PA = "z" else: - yFound = 'y' in paVal + yFound = "y" in paVal if yFound: - PA='y' + PA = "y" else: - raise SystemExit('ERROR in control file: only Y or Z can be given for control keyWord ->'+keyWordPitchAxis+'<-') + raise SystemExit( + "ERROR in control file: only Y or Z can be given for control keyWord ->" + + keyWordPitchAxis + + "<-" + ) if verbose: - print('Pitch axis is '+PA.upper()) -# -# angles definitions: -# alpha ... angle of attack -# beta ... side-slip angle -# phi ... roll angle -# -# Note: Actually alpha here is the angle of rotation about the above-defined pitch axis -# Thus, by replacing the pitch-axis, all that is said here about alpha is actually for beta -# -# Several combinations of angles are possible: -#------------------------------------------------ -# 1. Polar-sweep in alpha per given phi ...... polarVar = aoa -# 2. Polar-sweep in alpha per given beta (side slip angle) ...... polarVar = aoa -# 3. Polar-sweep in phi per given alpha ...... polarVar = phi -# 4. Mach ramp (single values for alpha, phi or both permitted) ... polarVar = MachRampNumbers -# -# Note: Seting a list of both phi and beta is impossible -# For mach ramp you can specify alpha, phi (or both), but not a list of either of them -# -# Now let us find out which angles are specified in the control file, to figure out polarSweepType and polarVar -# - keyWordListAOA='angles of attack' - iListAOA = parLocator(keyWordListAOA,ctrl,nc,-1,verbose) - keyWordListPhi='roll angles' - iListPhi = parLocator(keyWordListPhi,ctrl,nc,-1,verbose) - keyWordListBeta='side slip angle' - iListBeta = parLocator(keyWordListBeta,ctrl,nc,-1,verbose) - keyWordListMRN='mach ramp numbers' - iListMRN = parLocator(keyWordListMRN,ctrl,nc,-1,verbose) - -# -# Check first if this is a Mach ramp session -# - if iListMRN > -1 : - polarSweepType=4 ; # This is a Mach rmp session - polarVar='MachRampNumbers' - MachList,nMach=readList(ctrl,iListMRN,verbose); -# -# Now check if any angle was specified -# - if iListBeta == -1 : - nBeta=0 ; beta=[ ]; - velDirOption = 1; # Velocity dirction vector v(alpha,phi). May be overwritten below - else: - beta,nBeta=readList(ctrl,iListBeta,verbose) - velDirOption = 2; # Velocity dirction vector v(alpha,beta) - if nBeta > 1 : - raise SystemExit('ERROR in control file: >>>>>>>> nBeta > 1 in a Mach Ramp session <<<<<<<<') - - if iListAOA == -1: - if velDirOption == 2 : - alpha = [0.0]; nAalpha =1; - else: - alpha =[ ] ; nAalpha=0; - velDirOption = 0; # No specification of Velocity dirction vector. May be overwritten below - else: - alpha,nAalpha=readList(ctrl,iListAOA,verbose) - if nAalpha > 1 : - raise SystemExit('ERROR in control file: >>>>>>>> nAlpha > 1 in a Mach Ramp session <<<<<<<<') - - if iListPhi == -1 : - if velDirOption != 1 : - phi = [ ] ; nPhi = 0; - else: - phi = [0.0] ; nPhi = 1; - else: - phi,nPhi=readList(ctrl,iListPhi,verbose); - if nPhi > 1 : - raise SystemExit('ERROR in control file: >>>>>>>> nPhi > 1 in a Mach Ramp session <<<<<<<<') - if velDirOption == 0 : - # if phi is specified, then this is a alpha,phi case, with alpha = 0 - velDirOption = 1; alpha = [0.0]; nAalpha =1; - - - - if nPhi + nBeta >= 2 : - raise SystemExit('ERROR in control file: >>>>>>>> Both phi and Beta specified (in a Mach Ramp session) <<<<<<<<') - - + print("Pitch axis is " + PA.upper()) + # + # angles definitions: + # alpha ... angle of attack + # beta ... side-slip angle + # phi ... roll angle + # + # Note: Actually alpha here is the angle of rotation about the above-defined pitch axis + # Thus, by replacing the pitch-axis, all that is said here about alpha is actually for beta + # + # Several combinations of angles are possible: + # ------------------------------------------------ + # 1. Polar-sweep in alpha per given phi ...... polarVar = aoa + # 2. Polar-sweep in alpha per given beta (side slip angle) ...... polarVar = aoa + # 3. Polar-sweep in phi per given alpha ...... polarVar = phi + # 4. Mach ramp (single values for alpha, phi or both permitted) ... polarVar = MachRampNumbers + # + # Note: Seting a list of both phi and beta is impossible + # For mach ramp you can specify alpha, phi (or both), but not a list of either of them + # + # Now let us find out which angles are specified in the control file, to figure out polarSweepType and polarVar + # + keyWordListAOA = "angles of attack" + iListAOA = parLocator(keyWordListAOA, ctrl, nc, -1, verbose) + keyWordListPhi = "roll angles" + iListPhi = parLocator(keyWordListPhi, ctrl, nc, -1, verbose) + keyWordListBeta = "side slip angle" + iListBeta = parLocator(keyWordListBeta, ctrl, nc, -1, verbose) + keyWordListMRN = "mach ramp numbers" + iListMRN = parLocator(keyWordListMRN, ctrl, nc, -1, verbose) + + # + # Check first if this is a Mach ramp session + # + if iListMRN > -1: + polarSweepType = 4 + # This is a Mach rmp session + polarVar = "MachRampNumbers" + MachList, nMach = readList(ctrl, iListMRN, verbose) + # + # Now check if any angle was specified + # + if iListBeta == -1: + nBeta = 0 + beta = [] + velDirOption = 1 + # Velocity dirction vector v(alpha,phi). May be overwritten below + else: + beta, nBeta = readList(ctrl, iListBeta, verbose) + velDirOption = 2 + # Velocity dirction vector v(alpha,beta) + if nBeta > 1: + raise SystemExit( + "ERROR in control file: >>>>>>>> nBeta > 1 in a Mach Ramp session <<<<<<<<" + ) + + if iListAOA == -1: + if velDirOption == 2: + alpha = [0.0] + nAalpha = 1 + else: + alpha = [] + nAalpha = 0 + velDirOption = 0 + # No specification of Velocity dirction vector. May be overwritten below + else: + alpha, nAalpha = readList(ctrl, iListAOA, verbose) + if nAalpha > 1: + raise SystemExit( + "ERROR in control file: >>>>>>>> nAlpha > 1 in a Mach Ramp session <<<<<<<<" + ) + + if iListPhi == -1: + if velDirOption != 1: + phi = [] + nPhi = 0 + else: + phi = [0.0] + nPhi = 1 + else: + phi, nPhi = readList(ctrl, iListPhi, verbose) + if nPhi > 1: + raise SystemExit( + "ERROR in control file: >>>>>>>> nPhi > 1 in a Mach Ramp session <<<<<<<<" + ) + if velDirOption == 0: + # if phi is specified, then this is a alpha,phi case, with alpha = 0 + velDirOption = 1 + alpha = [0.0] + nAalpha = 1 + + if nPhi + nBeta >= 2: + raise SystemExit( + "ERROR in control file: >>>>>>>> Both phi and Beta specified (in a Mach Ramp session) <<<<<<<<" + ) else: -# -# this is not a mach ramp - MachList=[ ]; nMach=0; -# -# So, this is a polar-sweep and not mach ramp. -# Now find out polarSweepType (1,2,or 3) -# - - if iListPhi == -1 : - if iListBeta == -1 : - polarSweepType=1 ; - polarVar='aoa' ; # phi/beta not found. Polar sweep in alpha for phi=beta=0 - velDirOption = 1; # Velocity dirction vector v(alpha,phi). - phi = [0.0] ; nPhi = 1; - nBeta=0 ; beta=[ ]; + # + # this is not a mach ramp + MachList = [] + nMach = 0 + # + # So, this is a polar-sweep and not mach ramp. + # Now find out polarSweepType (1,2,or 3) + # + + if iListPhi == -1: + if iListBeta == -1: + polarSweepType = 1 + polarVar = "aoa" + # phi/beta not found. Polar sweep in alpha for phi=beta=0 + velDirOption = 1 + # Velocity dirction vector v(alpha,phi). + phi = [0.0] + nPhi = 1 + nBeta = 0 + beta = [] else: -# beta was found in control file, phi is not there; check how about alpha - nPhi = 0 ; phi=[ ]; - polarSweepType=2 ; - polarVar='aoa' ; - velDirOption = 2; # Velocity dirction vector v(alpha,beta). - beta,nBeta=readList(ctrl,iListBeta,verbose) - if nBeta > 1 : - raise SystemExit('ERROR in control file: nBeta > 1. For polar sweep in beta exchange pitch-axis and use aoa') - - if iListAOA == -1 : - raise SystemExit('ERROR in control file: phi and alpha are missing. Polar sweep not defined') - - alpha,nAalpha=readList(ctrl,iListAOA,verbose) + # beta was found in control file, phi is not there; check how about alpha + nPhi = 0 + phi = [] + polarSweepType = 2 + polarVar = "aoa" + velDirOption = 2 + # Velocity dirction vector v(alpha,beta). + beta, nBeta = readList(ctrl, iListBeta, verbose) + if nBeta > 1: + raise SystemExit( + "ERROR in control file: nBeta > 1. For polar sweep in beta exchange pitch-axis and use aoa" + ) + + if iListAOA == -1: + raise SystemExit( + "ERROR in control file: phi and alpha are missing. Polar sweep not defined" + ) + + alpha, nAalpha = readList(ctrl, iListAOA, verbose) else: -# -# phi was found in control file, so beta must not be there -# + # + # phi was found in control file, so beta must not be there + # if iListBeta > -1: - raise SystemExit('ERROR in control file: both phi and beta specified. Polar sweep not defined ') - - nBeta=0 ; beta=[ ]; - velDirOption = 1; # Velocity dirction vector v(alpha,phi). -# -# Check now if alpha appears -# - if iListAOA == -1 : -# -# phi found in control file, but alpha is missing, so it is a polar-sweep in phi with alpha=0 -# - polarSweepType=3 ; - polarVar='phi' ; alpha =[0.0] ; nAalpha=1 + raise SystemExit( + "ERROR in control file: both phi and beta specified. Polar sweep not defined " + ) + + nBeta = 0 + beta = [] + velDirOption = 1 + # Velocity dirction vector v(alpha,phi). + # + # Check now if alpha appears + # + if iListAOA == -1: + # + # phi found in control file, but alpha is missing, so it is a polar-sweep in phi with alpha=0 + # + polarSweepType = 3 + polarVar = "phi" + alpha = [0.0] + nAalpha = 1 else: -# -# Both alpha and phi found in control file. Find out which one is a list -# - alpha,nAalpha=readList(ctrl,iListAOA,verbose) + # + # Both alpha and phi found in control file. Find out which one is a list + # + alpha, nAalpha = readList(ctrl, iListAOA, verbose) - phi,nPhi=readList(ctrl,iListPhi,verbose) + phi, nPhi = readList(ctrl, iListPhi, verbose) if nAalpha == 1: - if nPhi > 1 : - polarSweepType=3 - polarVar='phi' + if nPhi > 1: + polarSweepType = 3 + polarVar = "phi" else: - polarSweepType=1 - polarVar='aoa' + polarSweepType = 1 + polarVar = "aoa" - nBeta=0; beta=[ ]; + nBeta = 0 + beta = [] else: -# -#-----that is nAlpha > 1 -# - if nPhi > 1 : - raise SystemExit('ERROR in control file: read lists in both alpha and phi. Polar sweep not defined ') - - polarSweepType=1 ; - polarVar='aoa'; nBeta=0; beta=[ ]; - -# -# Here we end the long if cycle, refrring to Mach ramp or angle sweep - -#------------------------------------------------------------------------------------------- + # + # -----that is nAlpha > 1 + # + if nPhi > 1: + raise SystemExit( + "ERROR in control file: read lists in both alpha and phi. Polar sweep not defined " + ) + + polarSweepType = 1 + polarVar = "aoa" + nBeta = 0 + beta = [] + + # + # Here we end the long if cycle, refrring to Mach ramp or angle sweep + + # ------------------------------------------------------------------------------------------- if verbose: - if polarSweepType == 1 : - print('Sweep type: '+str(polarSweepType)+' in alpha. nAalpha = '+str(nAalpha)+' phi = '+str(phi)) - elif polarSweepType == 2 : - print('Sweep type: '+str(polarSweepType)+' in alpha. nAalpha = '+str(nAalpha)+' beta = '+str(beta)) - elif polarSweepType == 3 : - print('Sweep type: '+str(polarSweepType)+' in phi. nPhi = '+str(nPhi)+' alpha = ',str(alpha)) - elif polarSweepType == 4 : - print('Sweep type: '+str(polarSweepType)+' in Mach. nMach = '+str(nMach)) - - return PA,polarSweepType,velDirOption,nAalpha,nBeta,nPhi,nMach,alpha,beta,phi,MachList,polarVar - -def setVelDir(velDirOption,PA,alphar,phir,betar): - -# set the velocity direction - from numpy import sin,cos,tan,size - -# -# Check for alpha and if we are dealing with values greater than 88deg (near 90) -# In such cases cases change to sin cos formualtion -# - - a88=1.5359 # 88 degrees - if velDirOption == 2 : - - if PA == 'z': - if alphar < a88 : - dv1 = [cos(betar) for x in alphar] - dv2 = tan(alphar)*cos(betar) + if polarSweepType == 1: + print( + "Sweep type: " + + str(polarSweepType) + + " in alpha. nAalpha = " + + str(nAalpha) + + " phi = " + + str(phi) + ) + elif polarSweepType == 2: + print( + "Sweep type: " + + str(polarSweepType) + + " in alpha. nAalpha = " + + str(nAalpha) + + " beta = " + + str(beta) + ) + elif polarSweepType == 3: + print( + "Sweep type: " + + str(polarSweepType) + + " in phi. nPhi = " + + str(nPhi) + + " alpha = ", + str(alpha), + ) + elif polarSweepType == 4: + print( + "Sweep type: " + str(polarSweepType) + " in Mach. nMach = " + str(nMach) + ) + + return ( + PA, + polarSweepType, + velDirOption, + nAalpha, + nBeta, + nPhi, + nMach, + alpha, + beta, + phi, + MachList, + polarVar, + ) + + +def setVelDir(velDirOption, PA, alphar, phir, betar): + + # set the velocity direction + from numpy import sin, cos, tan, size + + # + # Check for alpha and if we are dealing with values greater than 88deg (near 90) + # In such cases cases change to sin cos formualtion + # + + a88 = 1.5359 # 88 degrees + if velDirOption == 2: + + if PA == "z": + if alphar < a88: + dv1 = [cos(betar) for x in alphar] + dv2 = tan(alphar) * cos(betar) dv3 = [sin(betar) for x in alphar] else: - dv1 = cos(betar)*cos(alphar) - dv2 = sin(alphar)*cos(betar) - dv3 = sin(betar)*cos(alphar) + dv1 = cos(betar) * cos(alphar) + dv2 = sin(alphar) * cos(betar) + dv3 = sin(betar) * cos(alphar) else: - if alphar < a88 : - dv1 = [cos(betar) for x in alphar] - dv2 = [sin(betar) for x in alphar] - dv3 = tan(alphar)*cos(betar) + if alphar < a88: + dv1 = [cos(betar) for x in alphar] + dv2 = [sin(betar) for x in alphar] + dv3 = tan(alphar) * cos(betar) else: - dv1 = cos(betar)*cos(alphar) - dv2 = sin(betar)*cos(alphar) - dv3 = sin(alphar)*cos(betar) + dv1 = cos(betar) * cos(alphar) + dv2 = sin(betar) * cos(alphar) + dv3 = sin(alphar) * cos(betar) else: - if size(alphar) > size(phir) : - dummyVec=alphar + if size(alphar) > size(phir): + dummyVec = alphar else: - dummyVec=phir + dummyVec = phir - if PA == 'z': - if alphar < a88 : - dv1=[1.0 for x in dummyVec ] - dv2=tan(alphar)*cos(phir) - dv3=tan(alphar)*sin(phir) + if PA == "z": + if alphar < a88: + dv1 = [1.0 for x in dummyVec] + dv2 = tan(alphar) * cos(phir) + dv3 = tan(alphar) * sin(phir) else: - if size(alphar) > 1 : - dv1= cos(alphar) + if size(alphar) > 1: + dv1 = cos(alphar) else: - dv1=[cos(alphar) for x in dummyVec ] + dv1 = [cos(alphar) for x in dummyVec] - dv2=sin(alphar)*cos(phir) - dv3=sin(alphar)*sin(phir) + dv2 = sin(alphar) * cos(phir) + dv3 = sin(alphar) * sin(phir) else: - if alphar < a88 : - dv1=[1.0 for x in dummyVec ] - dv2=tan(alphar)*sin(phir) - dv3=tan(alphar)*cos(phir) - else: - if size(alphar) > 1 : - dv1= cos(alphar) - else: - dv1=[cos(alphar) for x in dummyVec ] - dv2=sin(alphar)*sin(phir) - dv3=sin(alphar)*cos(phir) - - return dv1,dv2,dv3 - -def processAddAngle(addRunStr,nPolara,parAngle,angleEqualCriterion): -# -#--------------------------------------------------------------------- -# Process the list of interactively added angles. -# Note that parAngle can receive also MachList -#-------------------------------------------------------------------- + if alphar < a88: + dv1 = [1.0 for x in dummyVec] + dv2 = tan(alphar) * sin(phir) + dv3 = tan(alphar) * cos(phir) + else: + if size(alphar) > 1: + dv1 = cos(alphar) + else: + dv1 = [cos(alphar) for x in dummyVec] + dv2 = sin(alphar) * sin(phir) + dv3 = sin(alphar) * cos(phir) + + return dv1, dv2, dv3 -#------------ create a list out of entered angles +def processAddAngle(addRunStr, nPolara, parAngle, angleEqualCriterion): + # + # --------------------------------------------------------------------- + # Process the list of interactively added angles. + # Note that parAngle can receive also MachList + # -------------------------------------------------------------------- - addRunList=addRunStr.split(',') - fAddRunListRaw=map(float,addRunList) - fAddRunList=sort(fAddRunListRaw) - nAddRun=size(fAddRunList) + # ------------ create a list out of entered angles -#------- By default, do not compute the cases in input file, since they were computed already + addRunList = addRunStr.split(",") + fAddRunListRaw = map(float, addRunList) + fAddRunList = sort(fAddRunListRaw) + nAddRun = size(fAddRunList) - computeCase=[False for j in range(0,nPolara+nAddRun)] - rerunCase = [False for j in range(0,nPolara+nAddRun)] + # ------- By default, do not compute the cases in input file, since they were computed already + computeCase = [False for j in range(0, nPolara + nAddRun)] + rerunCase = [False for j in range(0, nPolara + nAddRun)] -#----- Now, for each new angle/Mach verify if it is a rerun or inserted new value + # ----- Now, for each new angle/Mach verify if it is a rerun or inserted new value - closestAngle=[0 for i in range(0,nAddRun)] - for i in range(0,nAddRun): + closestAngle = [0 for i in range(0, nAddRun)] + for i in range(0, nAddRun): - diff=[abs(fAddRunList[i]-x) for x in parAngle] - iClose=diff.index(min(diff)) - closestAngle[i]=parAngle[iClose] + diff = [abs(fAddRunList[i] - x) for x in parAngle] + iClose = diff.index(min(diff)) + closestAngle[i] = parAngle[iClose] if min(diff) < angleEqualCriterion: - computeCase[iClose]=True - rerunCase[iClose]=True + computeCase[iClose] = True + rerunCase[iClose] = True else: if fAddRunList[i] > closestAngle[i]: - ii=iClose+1 + ii = iClose + 1 else: - ii=iClose + ii = iClose - tmpAng1=parAngle[:ii] + tmpAng1 = parAngle[:ii] tmpAng1.append(fAddRunList[i]) - tmpAng2=parAngle[ii:] + tmpAng2 = parAngle[ii:] tmpAng1.extend(tmpAng2) - parAngle=tmpAng1 - nPolara=nPolara+1 - computeCase[ii]=True + parAngle = tmpAng1 + nPolara = nPolara + 1 + computeCase[ii] = True + return nPolara, parAngle, computeCase, rerunCase - return nPolara,parAngle,computeCase,rerunCase -def updatedControlFile(ctrl,nc,parAngle,ctrlFile,verbose): +def updatedControlFile(ctrl, nc, parAngle, ctrlFile, verbose): -# generate a modified control file for case with addRun options + # generate a modified control file for case with addRun options import os -# -#-- get a proper list of updated parameter-angle - st1=str(parAngle) - updatedAngleList=st1[1:-1] -# Now let us find out which angles are specified in the control file, to figure out polarSweepType and polarVar -# - keyWordListAOA='angles of attack' - iListAOA = parLocator(keyWordListAOA,ctrl,nc,-1,verbose) - keyWordListPhi='roll angles' - iListPhi = parLocator(keyWordListPhi,ctrl,nc,-1,verbose) - keyWordListBeta='side slip angle' - iListBeta = parLocator(keyWordListBeta,ctrl,nc,-1,verbose) - keyWordListMRN='mach ramp numbers' - iListMRN = parLocator(keyWordListMRN,ctrl,nc,-1,verbose) -# -# Check first if this is a Mach ramp session -# - if iListMRN > -1 : - polarSweepType=4 ; # This is a Mach rmp session - polarVar='MachRampNumbers' - MachList,nMach=readList(ctrl,iListMRN,verbose); -# -# Now check if any angle was specified -# - if iListBeta == -1 : - nBeta=0 ; beta=[ ]; - velDirOption = 1; # Velocity dirction vector v(alpha,phi). May be overwritten below - else: - beta,nBeta=readList(ctrl,iListBeta,verbose) - velDirOption = 2; # Velocity dirction vector v(alpha,beta) - if nBeta > 1 : - raise SystemExit('ERROR in control file: >>>>>>>> nBeta > 1 in a Mach Ramp session <<<<<<<<') - - if iListAOA == -1: - if velDirOption == 2 : - alpha = [0.0]; nAalpha =1; - else: - alpha =[ ] ; nAalpha=0; - velDirOption = 0; # No specification of Velocity dirction vector. May be overwritten below - else: - alpha,nAalpha=readList(ctrl,iListAOA,verbose) - if nAalpha > 1 : - raise SystemExit('ERROR in control file: >>>>>>>> nAlpha > 1 in a Mach Ramp session <<<<<<<<') - - if iListPhi == -1 : - if velDirOption != 1 : - phi = [ ] ; nPhi = 0; - else: - phi = [0.0] ; nPhi = 1; - else: - phi,nPhi=readList(ctrl,iListPhi,verbose); - if nPhi > 1 : - raise SystemExit('ERROR in control file: >>>>>>>> nPhi > 1 in a Mach Ramp session <<<<<<<<') - if velDirOption == 0 : -# if phi is specified, then this is a alpha,phi case, with alpha = 0 - velDirOption = 1; alpha = [0.0]; nAalpha =1; - - if nPhi + nBeta >= 2 : - raise SystemExit('ERROR in control file: >>>>>>>> Both phi and Beta specified (in a Mach Ramp session) <<<<<<<<') - - ctrl[iListMRN]=' Mach ramp numbers : '+updatedAngleList+'\n' - else: -# -# this is not a mach ramp - MachList=[ ]; nMach=0; - if iListPhi == -1 : - if iListBeta == -1 : - polarSweepType=1 ; - polarVar='aoa' ; # phi/beta not found. Polar sweep in alpha for phi=beta=0 - phi = [0.0] ; nPhi = 1; - nBeta=0 ; beta=[ ]; + # + # -- get a proper list of updated parameter-angle + st1 = str(parAngle) + updatedAngleList = st1[1:-1] + # Now let us find out which angles are specified in the control file, to figure out polarSweepType and polarVar + # + keyWordListAOA = "angles of attack" + iListAOA = parLocator(keyWordListAOA, ctrl, nc, -1, verbose) + keyWordListPhi = "roll angles" + iListPhi = parLocator(keyWordListPhi, ctrl, nc, -1, verbose) + keyWordListBeta = "side slip angle" + iListBeta = parLocator(keyWordListBeta, ctrl, nc, -1, verbose) + keyWordListMRN = "mach ramp numbers" + iListMRN = parLocator(keyWordListMRN, ctrl, nc, -1, verbose) + # + # Check first if this is a Mach ramp session + # + if iListMRN > -1: + polarSweepType = 4 + # This is a Mach rmp session + polarVar = "MachRampNumbers" + MachList, nMach = readList(ctrl, iListMRN, verbose) + # + # Now check if any angle was specified + # + if iListBeta == -1: + nBeta = 0 + beta = [] + velDirOption = 1 + # Velocity dirction vector v(alpha,phi). May be overwritten below + else: + beta, nBeta = readList(ctrl, iListBeta, verbose) + velDirOption = 2 + # Velocity dirction vector v(alpha,beta) + if nBeta > 1: + raise SystemExit( + "ERROR in control file: >>>>>>>> nBeta > 1 in a Mach Ramp session <<<<<<<<" + ) + + if iListAOA == -1: + if velDirOption == 2: + alpha = [0.0] + nAalpha = 1 else: -# beta was found in control file, phi is not there; check how about alpha - nPhi = 0 ; phi=[ ]; - polarSweepType=2 ; - polarVar='aoa' ; - beta,nBeta=readList(ctrl,iListBeta,verbose) - if nBeta > 1 : - raise SystemExit('ERROR in control file: nBeta > 1. For polar sweep in beta exchange pitch-axis and use aoa') - - if iListAOA == -1 : - raise SystemExit('ERROR in control file: phi and alpha are missing. Polar sweep not defined') + alpha = [] + nAalpha = 0 + velDirOption = 0 + # No specification of Velocity dirction vector. May be overwritten below + else: + alpha, nAalpha = readList(ctrl, iListAOA, verbose) + if nAalpha > 1: + raise SystemExit( + "ERROR in control file: >>>>>>>> nAlpha > 1 in a Mach Ramp session <<<<<<<<" + ) + + if iListPhi == -1: + if velDirOption != 1: + phi = [] + nPhi = 0 + else: + phi = [0.0] + nPhi = 1 + else: + phi, nPhi = readList(ctrl, iListPhi, verbose) + if nPhi > 1: + raise SystemExit( + "ERROR in control file: >>>>>>>> nPhi > 1 in a Mach Ramp session <<<<<<<<" + ) + if velDirOption == 0: + # if phi is specified, then this is a alpha,phi case, with alpha = 0 + velDirOption = 1 + alpha = [0.0] + nAalpha = 1 + + if nPhi + nBeta >= 2: + raise SystemExit( + "ERROR in control file: >>>>>>>> Both phi and Beta specified (in a Mach Ramp session) <<<<<<<<" + ) + + ctrl[iListMRN] = " Mach ramp numbers : " + updatedAngleList + "\n" - alpha,nAalpha=readList(ctrl,iListAOA,verbose) - ctrl[iListAOA]=' angles of attack : '+updatedAngleList+'\n' + else: + # + # this is not a mach ramp + MachList = [] + nMach = 0 + if iListPhi == -1: + if iListBeta == -1: + polarSweepType = 1 + polarVar = "aoa" + # phi/beta not found. Polar sweep in alpha for phi=beta=0 + phi = [0.0] + nPhi = 1 + nBeta = 0 + beta = [] + else: + # beta was found in control file, phi is not there; check how about alpha + nPhi = 0 + phi = [] + polarSweepType = 2 + polarVar = "aoa" + beta, nBeta = readList(ctrl, iListBeta, verbose) + if nBeta > 1: + raise SystemExit( + "ERROR in control file: nBeta > 1. For polar sweep in beta exchange pitch-axis and use aoa" + ) + + if iListAOA == -1: + raise SystemExit( + "ERROR in control file: phi and alpha are missing. Polar sweep not defined" + ) + + alpha, nAalpha = readList(ctrl, iListAOA, verbose) + ctrl[iListAOA] = " angles of attack : " + updatedAngleList + "\n" else: -# phi was found in control file, so beta must not be there + # phi was found in control file, so beta must not be there if iListBeta > -1: - raise SystemExit('ERROR in control file: both phi and beta specified. Polar sweep not defined ') - - nBeta=0 ; beta=[ ]; -# Check now if alpha appears - if iListAOA == -1 : -# phi found in control file, but alpha is missing, so it is a polar-sweep in phi with alpha=0 - polarSweepType=3 ; - polarVar='phi' ; alpha =[0.0] ; nAalpha=1 + raise SystemExit( + "ERROR in control file: both phi and beta specified. Polar sweep not defined " + ) + + nBeta = 0 + beta = [] + # Check now if alpha appears + if iListAOA == -1: + # phi found in control file, but alpha is missing, so it is a polar-sweep in phi with alpha=0 + polarSweepType = 3 + polarVar = "phi" + alpha = [0.0] + nAalpha = 1 else: -# -# Both alpha and phi found in control file. Find out which one is a list -# - alpha,nAalpha=readList(ctrl,iListAOA,verbose) - if nAalpha > 1 : - ctrl[iListAOA]=' angles of attack : '+updatedAngleList+'\n' - - phi,nPhi=readList(ctrl,iListPhi,verbose) + # + # Both alpha and phi found in control file. Find out which one is a list + # + alpha, nAalpha = readList(ctrl, iListAOA, verbose) + if nAalpha > 1: + ctrl[iListAOA] = " angles of attack : " + updatedAngleList + "\n" + + phi, nPhi = readList(ctrl, iListPhi, verbose) if nPhi > 1: - ctrl[iListPhi]=' roll angles : '+updatedAngleList+'\n' + ctrl[iListPhi] = " roll angles : " + updatedAngleList + "\n" -# Prepare a backup of control file + # Prepare a backup of control file - shutil.copy2(ctrlFile, ctrlFile+'.bck') -# -# --- Write down the updated file - fc=open(ctrlFile,'w') + shutil.copy2(ctrlFile, ctrlFile + ".bck") + # + # --- Write down the updated file + fc = open(ctrlFile, "w") fc.writelines(ctrl) fc.close() - print('More cases were added. Original ctrl file saved at '+ctrlFile+'.bck File '+ctrlFile+' updated') - + print( + "More cases were added. Original ctrl file saved at " + + ctrlFile + + ".bck File " + + ctrlFile + + " updated" + ) return -def retrievePhysicalData(b,n,polarSweepType,verbose): -# scan the control file and retrieve physical data parameters and their location -# Included are Mach and reynolds number (non-dim group) -# Pref, rho_ref, Tref (ref group) -# --------------------------------------------------- -# -# physical data, needed for Mach ramp -# - keyWord='mach for coefficients' - MachNumCoef,iparMcoeff=readParameter(b,n,keyWord,-1,verbose) - keyWord='mach' - MachNum,iprMach=readParameter(b,n,keyWord,iparMcoeff,verbose) # look for Mach, but avoid Mach for coefficients - keyWord='reynolds length (in meter)' - ReNumRefLength,iprDRe=readParameter(b,n,keyWord,-1,verbose) - keyWord='reynolds' - ReNum,iprRe=readParameter(b,n,keyWord,iprDRe,verbose) - sNonDimNum=[MachNum,MachNumCoef,ReNum,ReNumRefLength] - nonDimNum=map(float,sNonDimNum) - nonDimNumLoc=[iprMach,iparMcoeff,iprRe,iprDRe] -# -# the next set of parameters might, or might not appear in base input file -# If they appear, they should be updated in a Mach ramp. All 3 of them are needed. -# +def retrievePhysicalData(b, n, polarSweepType, verbose): + + # scan the control file and retrieve physical data parameters and their location + # Included are Mach and reynolds number (non-dim group) + # Pref, rho_ref, Tref (ref group) + # --------------------------------------------------- + # + # physical data, needed for Mach ramp + # + keyWord = "mach for coefficients" + MachNumCoef, iparMcoeff = readParameter(b, n, keyWord, -1, verbose) + keyWord = "mach" + MachNum, iprMach = readParameter( + b, n, keyWord, iparMcoeff, verbose + ) # look for Mach, but avoid Mach for coefficients + keyWord = "reynolds length (in meter)" + ReNumRefLength, iprDRe = readParameter(b, n, keyWord, -1, verbose) + keyWord = "reynolds" + ReNum, iprRe = readParameter(b, n, keyWord, iprDRe, verbose) + sNonDimNum = [MachNum, MachNumCoef, ReNum, ReNumRefLength] + nonDimNum = map(float, sNonDimNum) + nonDimNumLoc = [iprMach, iparMcoeff, iprRe, iprDRe] + # + # the next set of parameters might, or might not appear in base input file + # If they appear, they should be updated in a Mach ramp. All 3 of them are needed. + # refParNo = 0 - keyWord='Reference pressure (in Pa)' - pRef,iprPr=readParameter(b,n,keyWord,-1,verbose) - if iprPr > -1 : - refParNo =refParNo + 1; + keyWord = "Reference pressure (in Pa)" + pRef, iprPr = readParameter(b, n, keyWord, -1, verbose) + if iprPr > -1: + refParNo = refParNo + 1 - keyWord='Reference density (in kg/m^3)' - rhoRef,iprRho=readParameter(b,n,keyWord,-1,verbose) + keyWord = "Reference density (in kg/m^3)" + rhoRef, iprRho = readParameter(b, n, keyWord, -1, verbose) if iprRho > -1: - refParNo =refParNo + 1; + refParNo = refParNo + 1 - keyWord='Reference temperature (in K)' - TRef,iprT=readParameter(b,n,keyWord,-1,verbose) + keyWord = "Reference temperature (in K)" + TRef, iprT = readParameter(b, n, keyWord, -1, verbose) if iprT > -1: - refParNo =refParNo + 1; + refParNo = refParNo + 1 - if refParNo == 3 : + if refParNo == 3: refParExist = True - elif refParNo == 0 : + elif refParNo == 0: refParExist = False else: - if polarSweepType == 4 : - raise SystemExit('ERROR in control file: in Mach ramp, base file should include (Pr,rho_r,Tr) or none of them') + if polarSweepType == 4: + raise SystemExit( + "ERROR in control file: in Mach ramp, base file should include (Pr,rho_r,Tr) or none of them" + ) if refParExist: - sRefPar=[pRef,rhoRef,TRef] - refPar=map(float,sRefPar) - refParLoc=[iprPr,iprRho,iprT] -# -# Thermodynamic properties -# - keyWord='Constant specific heat ratio' - gamma,iprGamma=readParameter(b,n,keyWord,-1,verbose) - keyWord='Gas constant (J/(kg K))' - rGas,iprGasC=readParameter(b,n,keyWord,-1,verbose) - keyWord='Free stream temperature (in K)' - TFreeS,iprTFreeS=readParameter(b,n,keyWord,-1,verbose) - - sThermoPar=[gamma,rGas,TFreeS] - thermoPar=map(float,sThermoPar) - thermoParLoc=[iprGamma,iprGasC,iprTFreeS] + sRefPar = [pRef, rhoRef, TRef] + refPar = map(float, sRefPar) + refParLoc = [iprPr, iprRho, iprT] + # + # Thermodynamic properties + # + keyWord = "Constant specific heat ratio" + gamma, iprGamma = readParameter(b, n, keyWord, -1, verbose) + keyWord = "Gas constant (J/(kg K))" + rGas, iprGasC = readParameter(b, n, keyWord, -1, verbose) + keyWord = "Free stream temperature (in K)" + TFreeS, iprTFreeS = readParameter(b, n, keyWord, -1, verbose) + + sThermoPar = [gamma, rGas, TFreeS] + thermoPar = map(float, sThermoPar) + thermoParLoc = [iprGamma, iprGasC, iprTFreeS] if verbose: - print('base case parameters of Mach ramp') - print('---------------------------------') - print(' M = '+sNonDimNum[0]+' Reynolds = '+sNonDimNum[2]) + print("base case parameters of Mach ramp") + print("---------------------------------") + print(" M = " + sNonDimNum[0] + " Reynolds = " + sNonDimNum[2]) if refParExist: - print(' Pref = '+str(refPar[0])+' rhor = '+str(refPar[1])+' Tr = '+str(refPar[2])) - print(' gamma = '+str(thermoPar[0])+ ' Gas Const = '+str(thermoPar[1])+' T_freeStream = '+str(thermoPar[2])) - - - return nonDimNum,nonDimNumLoc,refParExist,refPar,refParLoc,thermoPar,thermoParLoc + print( + " Pref = " + + str(refPar[0]) + + " rhor = " + + str(refPar[1]) + + " Tr = " + + str(refPar[2]) + ) + print( + " gamma = " + + str(thermoPar[0]) + + " Gas Const = " + + str(thermoPar[1]) + + " T_freeStream = " + + str(thermoPar[2]) + ) + + return ( + nonDimNum, + nonDimNumLoc, + refParExist, + refPar, + refParLoc, + thermoPar, + thermoParLoc, + ) + + +def fMachIsentropic(Mach, Gamma): + + # Isentropic relation of Mach + # --------------------------------------------------- + # + fMach = 1.0 + (Gamma - 1.0) / 2.0 * Mach * Mach + return fMach -def fMachIsentropic(Mach,Gamma): -# Isentropic relation of Mach -# --------------------------------------------------- -# - fMach = 1.0 + (Gamma-1.0)/2.0*Mach*Mach; - return fMach # # -def extractUy(filename,outFile,inDepVar,depVar,verbose): +def extractUy(filename, outFile, inDepVar, depVar, verbose): import os import sys + # --------------- read the file -#--------------- read the file - - fc=open(filename,'r') - data=fc.readlines() - nc=size(data) + fc = open(filename, "r") + data = fc.readlines() + nc = size(data) fc.close() - print(str(nc)+' lines were written from file '+filename+'. File closed') + print(str(nc) + " lines were written from file " + filename + ". File closed") -# --------------Retreive the variables names in the Tecplot file + # --------------Retreive the variables names in the Tecplot file - ivb=stringLocator('VARIABLES',data,nc,verbose) + ivb = stringLocator("VARIABLES", data, nc, verbose) if ivb == -1: - raise SystemExit('ERROR: failed to trace VARIABLES list in input file') + raise SystemExit("ERROR: failed to trace VARIABLES list in input file") - izo=stringLocator('ZONE',data,nc,verbose) + izo = stringLocator("ZONE", data, nc, verbose) if izo == -1: - raise SystemExit('ERROR: failed to trace ZONE list in input file') + raise SystemExit("ERROR: failed to trace ZONE list in input file") - izo=izo-1 # last variables line - print('list of variables traced between lines '+str(ivb)+' and ',str(izo)) + izo = izo - 1 # last variables line + print("list of variables traced between lines " + str(ivb) + " and ", str(izo)) - varListLines=data[ivb:izo] - nV=len(varListLines) - varList=[] - iX=-1 - iY=-1 + varListLines = data[ivb:izo] + nV = len(varListLines) + varList = [] + iX = -1 + iY = -1 for i in range(0, nV): - i1=varListLines[i].index('"')+1 - i2=varListLines[i].rindex('"') + i1 = varListLines[i].index('"') + 1 + i2 = varListLines[i].rindex('"') varList.append(varListLines[i][i1:i2]) if iX == -1: try: - ifound= varList[i].index(inDepVar) - iX=i + ifound = varList[i].index(inDepVar) + iX = i except ValueError: - pass # do nothing + pass # do nothing if iY == -1: try: - ifound= varList[i].index(depVar) - iY=i + ifound = varList[i].index(depVar) + iY = i except ValueError: - pass # do nothing - - print('inDepVar: '+inDepVar+' : '+str(iX+1)+' . DepVar: '+depVar+' : '+str(iY+1)+' of '+str(nV)+' variables') - -# find out how many nodes - - inodes=stringLocator('Nodes',data,nc,verbose) + pass # do nothing + + print( + "inDepVar: " + + inDepVar + + " : " + + str(iX + 1) + + " . DepVar: " + + depVar + + " : " + + str(iY + 1) + + " of " + + str(nV) + + " variables" + ) + + # find out how many nodes + + inodes = stringLocator("Nodes", data, nc, verbose) if inodes == -1: - raise SystemExit('ERROR: failed to trace nodes in input file') - - i1=data[inodes].index('=')+1 - i2=data[inodes].index(',') - Nodes=int(data[inodes][i1:i2]) - print('Nodes = ',str(Nodes)) -# -# now map the whole matrix -# - i1=inodes+3 - i2=i1+Nodes - X=[]; Y=[] - for i in range(i1+1, i2): - ff=map(float,data[i][1:-1].split(' ')) + raise SystemExit("ERROR: failed to trace nodes in input file") + + i1 = data[inodes].index("=") + 1 + i2 = data[inodes].index(",") + Nodes = int(data[inodes][i1:i2]) + print("Nodes = ", str(Nodes)) + # + # now map the whole matrix + # + i1 = inodes + 3 + i2 = i1 + Nodes + X = [] + Y = [] + for i in range(i1 + 1, i2): + ff = map(float, data[i][1:-1].split(" ")) X.append(ff[iX]) Y.append(ff[iY]) - nP=len(X) + nP = len(X) -#------ sorting by X + # ------ sorting by X - ind = lexsort((Y,X)) - Xs=take(X,ind) - Ys=take(Y,ind) -# write down to a simple 2-columns file - foc=open(outFile,'w') - fileHeader = ' '+inDepVar+' '+depVar - foc.write('% '+fileHeader+' \n% -----------------------------------\n%\n') - for i in range(0,nP): - Line1= ' %10.5f %14.5g '%(Xs[i],Ys[i])+' \n' + ind = lexsort((Y, X)) + Xs = take(X, ind) + Ys = take(Y, ind) + # write down to a simple 2-columns file + foc = open(outFile, "w") + fileHeader = " " + inDepVar + " " + depVar + foc.write("% " + fileHeader + " \n% -----------------------------------\n%\n") + for i in range(0, nP): + Line1 = " %10.5f %14.5g " % (Xs[i], Ys[i]) + " \n" foc.write(Line1) foc.close() + # numpy.plot(Xs,Ys,"-b") # -def loadArray(Fin,nCol): -# -# load a polar-sweep file as an array -# - f=open(Fin,'r') - b=f.readlines() - n=size(b) +def loadArray(Fin, nCol): + # + # load a polar-sweep file as an array + # + f = open(Fin, "r") + b = f.readlines() + n = size(b) f.close() -# - data=[] - nd=0; - for i in range(0,n): - sline=b[i].replace(' ',' ').replace(' ',' ').replace(' ',' ').replace(' ',' ').strip().split(' ') - sv=size(sline) + # + data = [] + nd = 0 + for i in range(0, n): + sline = ( + b[i] + .replace(" ", " ") + .replace(" ", " ") + .replace(" ", " ") + .replace(" ", " ") + .strip() + .split(" ") + ) + sv = size(sline) if sv == nCol: try: - dd=map(float,sline) + dd = map(float, sline) data.append(dd) - nd=nd+1; + nd = nd + 1 except ValueError: - pass # do nothing - - return data,nd - -def locateSteps(d,nd,nCol): -# -# read polarsweep files and identify steps -# - eps=0.001 - nColD=nCol-2 # cxbase and quality are not checked - a=array(d) - dx=diff(a[:,0],n=1,axis=0) - nStairs=[] - for ic in range(1,nColD): - dy=diff(a[:,ic],n=1,axis=0) - dydx=dy/dx - adydx=abs(dydx) - madydx=adydx.mean(axis=0) - mmxadydx=max(adydx) - mmnadydx=min(adydx) - madydx2=(mmxadydx+mmnadydx)/2 - iic=where(adydx 0: - fst=open('stairs','w') - fst.write('% \n% Polara stairs report \n% \n') - fst.write('% Note that the identified number might be something between the correct number of stairs \n') - fst.write('% and 2X this number since since 2 criteria are added in the search script \n \n ') - Headers=['CX ','CY ','CZ ','Cmx','Cmy','Cmz'] - for ic in range(0,nColD-1): - refLine1= Headers[ic]+': Number of stairs identified: %i \n '%(nStairs[ic]) - fst.write(refLine1) + fst = open("stairs", "w") + fst.write("% \n% Polara stairs report \n% \n") + fst.write( + "% Note that the identified number might be something between the correct number of stairs \n" + ) + fst.write( + "% and 2X this number since since 2 criteria are added in the search script \n \n " + ) + Headers = ["CX ", "CY ", "CZ ", "Cmx", "Cmy", "Cmz"] + for ic in range(0, nColD - 1): + refLine1 = Headers[ic] + ": Number of stairs identified: %i \n " % ( + nStairs[ic] + ) + fst.write(refLine1) fst.close() - return nStairs,nStM + return nStairs, nStM + def find_index(ar, eps): -# -# locate array components that are > eps -# - ia=[] + # + # locate array components that are > eps + # + ia = [] for i, v in enumerate(ar): if v > eps: ia.append(i) return ia -def testComponentSum(cbdOutput,verbose): -# -# check cbd summation -# - coeffNames=['Cfx','Cfy','Cfz','Cmx','Cmy','Cmz'] +def testComponentSum(cbdOutput, verbose): + # + # check cbd summation + # + + coeffNames = ["Cfx", "Cfy", "Cfz", "Cmx", "Cmy", "Cmz"] try: - fd=open(cbdOutput,'r'); - d=fd.readlines() - nd=size(d) + fd = open(cbdOutput, "r") + d = fd.readlines() + nd = size(d) fd.close() if verbose: - print('CBD file '+cbdOutput+' loaded by testComponentSum') + print("CBD file " + cbdOutput + " loaded by testComponentSum") except IOError: - raise SystemExit('testComponentSum: Failed to find file '+cbdOutput) - -# now read the numerical values from the cdb file - - data,nd=loadArray(cbdOutput,6) -# transpose the array - td=zip(*data) -# now check correct som for each variable - eps=0.01 - errorA=[] - sumD=[] - for i in range(0,6): - fsumD=sum(td[i][:-1]) + raise SystemExit("testComponentSum: Failed to find file " + cbdOutput) + + # now read the numerical values from the cdb file + + data, nd = loadArray(cbdOutput, 6) + # transpose the array + td = zip(*data) + # now check correct som for each variable + eps = 0.01 + errorA = [] + sumD = [] + for i in range(0, 6): + fsumD = sum(td[i][:-1]) sumD.append(fsumD) - if abs(td[i][nd-1]) > eps: - error=abs((fsumD-td[i][nd-1])/td[i][nd-1]) + if abs(td[i][nd - 1]) > eps: + error = abs((fsumD - td[i][nd - 1]) / td[i][nd - 1]) else: - error=0 + error = 0 errorA.append(error) - iErr=find_index(errorA, 0.005) - nER=size(iErr) + iErr = find_index(errorA, 0.005) + nER = size(iErr) if nER > 0: - print('testComponentSum: Error is components sumation in file '+cbdOutput) - for i in range(0,nER): - print('Error found in '+coeffNames[iErr[i]]+' Error = '+str(100*errorA[iErr[i]])+' %') - - corrDataLine=' %12.5e %12.5e %12.5e %12.5e %12.5e %12.5e '%(sumD[0],sumD[1], - sumD[2],sumD[3],sumD[4],sumD[5]) + print("testComponentSum: Error is components sumation in file " + cbdOutput) + for i in range(0, nER): + print( + "Error found in " + + coeffNames[iErr[i]] + + " Error = " + + str(100 * errorA[iErr[i]]) + + " %" + ) + + corrDataLine = " %12.5e %12.5e %12.5e %12.5e %12.5e %12.5e " % ( + sumD[0], + sumD[1], + sumD[2], + sumD[3], + sumD[4], + sumD[5], + ) else: - corrDataLine=' ' - return nER,corrDataLine + corrDataLine = " " + return nER, corrDataLine + -def retreiveNumPar(ctrl,nc,keyWord,parType,verbose): +def retreiveNumPar(ctrl, nc, keyWord, parType, verbose): # get the parameter from the control file. Set it to unity if not found # parType: 1 -> integer 2 -> float -# - ipar = parLocator(keyWord,ctrl,nc,-1,verbose) + # + ipar = parLocator(keyWord, ctrl, nc, -1, verbose) if ipar == -1: - # default value + # default value if parType == 1: parVal = 1 else: parVal = 1.0 else: - PARLine=ctrl[ipar] - icol=PARLine.index(':') + PARLine = ctrl[ipar] + icol = PARLine.index(":") if parType == 1: - parVal= int(PARLine[icol+1:]) + parVal = int(PARLine[icol + 1 :]) else: - parVal=float(PARLine[icol+1:]) + parVal = float(PARLine[icol + 1 :]) return parVal + # ----------------------------------------------------- -def loadData(filename,delim): -# read a 2D data from a file, separated by delim -# (may be , (comma) or ' ' (space ) -# -# do array(dout) (in calling) to obtain result as an array (numpy imported) -# dout=loadData(filename,delim) -# v=array(dout) + +def loadData(filename, delim): + # read a 2D data from a file, separated by delim + # (may be , (comma) or ' ' (space ) + # + # do array(dout) (in calling) to obtain result as an array (numpy imported) + # dout=loadData(filename,delim) + # v=array(dout) import csv -# import numpy - data=[] - with open(filename, 'rb') as f: -#-avoid NULL error + # import numpy - reader = csv.reader((line.replace('\0','').replace(' ',' ').replace(' ',' ').strip() for line in f),delimiter=delim) + data = [] + with open(filename, "rb") as f: + # -avoid NULL error - data=[' '] + reader = csv.reader( + ( + line.replace("\0", "").replace(" ", " ").replace(" ", " ").strip() + for line in f + ), + delimiter=delim, + ) + + data = [" "] for row in reader: try: data.append(map(float, row)) except ValueError: - print('Line doesnt match map float: ') + print("Line doesnt match map float: ") print(row) # check square matrix - N1=len(data[0]) - dout=[] - for i in range(1,len(data)): + N1 = len(data[0]) + dout = [] + for i in range(1, len(data)): if N1 <= 1: - N1=len(data[i]) - if len(data[i]) != N1 : - print('WARNING: Line '+str(i)+': size does not match. Skipped') + N1 = len(data[i]) + if len(data[i]) != N1: + print("WARNING: Line " + str(i) + ": size does not match. Skipped") else: dout.append(data[i]) - #adout=array(dout) + # adout=array(dout) return dout - - - diff --git a/SU2_PY/SU2/util/switch.py b/SU2_PY/SU2/util/switch.py index b42eaf6e9dd..821b6568a67 100644 --- a/SU2_PY/SU2/util/switch.py +++ b/SU2_PY/SU2/util/switch.py @@ -1,35 +1,36 @@ # ------------------------------------------------------------------- # Switch Class -# ------------------------------------------------------------------- +# ------------------------------------------------------------------- # source: Brian Beck, PSF License, ActiveState Code # http://code.activestate.com/recipes/410692/ + class switch(object): - """ Readable switch construction - - Example: - - c = 'z' - for case in switch(c): - if case('a'): pass # only necessary if the rest of the suite is empty - if case('b'): pass - # ... - if case('y'): pass - if case('z'): - print("c is lowercase!") - break - if case('A'): pass - # ... - if case('Z'): - print("c is uppercase!") - break - if case(): # default - print("I dunno what c was!") - - source: Brian Beck, PSF License, ActiveState Code - http://code.activestate.com/recipes/410692/ + """Readable switch construction + + Example: + + c = 'z' + for case in switch(c): + if case('a'): pass # only necessary if the rest of the suite is empty + if case('b'): pass + # ... + if case('y'): pass + if case('z'): + print("c is lowercase!") + break + if case('A'): pass + # ... + if case('Z'): + print("c is uppercase!") + break + if case(): # default + print("I dunno what c was!") + + source: Brian Beck, PSF License, ActiveState Code + http://code.activestate.com/recipes/410692/ """ - + def __init__(self, value): self.value = value self.fall = False @@ -38,15 +39,16 @@ def __iter__(self): """Return the match method once, then stop""" yield self.match raise StopIteration - + def match(self, *args): """Indicate whether or not to enter a case suite""" if self.fall or not args: return True - elif self.value in args: + elif self.value in args: self.fall = True return True else: return False - + + #: class switch() diff --git a/SU2_PY/SU2/util/which.py b/SU2_PY/SU2/util/which.py index 512c7e954e1..115b7905a88 100644 --- a/SU2_PY/SU2/util/which.py +++ b/SU2_PY/SU2/util/which.py @@ -28,14 +28,15 @@ import os + def which(program): - """ which(program_name) - finds the location of the program_name if it is on PATH - returns None if program cannot be found - does not test for .exe extension on windows + """which(program_name) + finds the location of the program_name if it is on PATH + returns None if program cannot be found + does not test for .exe extension on windows - original source: - http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python + original source: + http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python """ fpath, fname = os.path.split(program) @@ -45,15 +46,13 @@ def which(program): else: for path in os.environ["PATH"].split(os.pathsep): path = path.strip('"') - for ext in ['','.exe','.bat']: - exe_file = os.path.join(path, (program+ext)) + for ext in ["", ".exe", ".bat"]: + exe_file = os.path.join(path, (program + ext)) if is_exe(exe_file): return exe_file return None + def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) - - - diff --git a/SU2_PY/SU2_CFD.py b/SU2_PY/SU2_CFD.py index 22e58169db8..39c0eab38fb 100755 --- a/SU2_PY/SU2_CFD.py +++ b/SU2_PY/SU2_CFD.py @@ -30,85 +30,147 @@ # ---------------------------------------------------------------------- from __future__ import division, print_function, absolute_import -from optparse import OptionParser # use a parser for configuration -import SU2 # imports SU2 python tools -import pysu2 # imports the SU2 wrapped module +from optparse import OptionParser # use a parser for configuration +import SU2 # imports SU2 python tools +import pysu2 # imports the SU2 wrapped module # ------------------------------------------------------------------- # Main # ------------------------------------------------------------------- + def main(): - # Command line options - parser=OptionParser() - parser.add_option("-f", "--file", dest="filename", help="Read config from FILE", metavar="FILE") - parser.add_option("--nDim", dest="nDim", default=2, help="Define the number of DIMENSIONS", - metavar="DIMENSIONS") - parser.add_option("--nZone", dest="nZone", default=1, help="Define the number of ZONES", metavar="NZONE") - parser.add_option("--parallel", action="store_true", - help="Specify if we need to initialize MPI", dest="with_MPI", default=False) - parser.add_option("--fsi", dest="fsi", default="False", help="Launch the FSI driver", metavar="FSI") - parser.add_option("--fem", dest="fem", default="False", help="Launch the FEM driver (General driver)", metavar="FEM") - parser.add_option("--harmonic_balance", dest="harmonic_balance", default="False", - help="Launch the Harmonic Balance (HB) driver", metavar="HB") - parser.add_option("--poisson_equation", dest="poisson_equation", default="False", - help="Launch the poisson equation driver (General driver)", metavar="POIS_EQ") - parser.add_option("--wave_equation", dest="wave_equation", default="False", - help="Launch the wave equation driver (General driver)", metavar="WAVE_EQ") - parser.add_option("--heat_equation", dest="heat_equation", default="False", - help="Launch the heat equation driver (General driver)", metavar="HEAT_EQ") - - (options, args) = parser.parse_args() - options.nDim = int( options.nDim ) - options.nZone = int( options.nZone ) - options.fsi = options.fsi.upper() == 'TRUE' - options.fem = options.fem.upper() == 'TRUE' - options.harmonic_balance = options.harmonic_balance.upper() == 'TRUE' - options.poisson_equation = options.poisson_equation.upper() == 'TRUE' - options.wave_equation = options.wave_equation.upper() == 'TRUE' - options.heat_equation = options.heat_equation.upper() == 'TRUE' - - if options.filename == None: - raise Exception("No config file provided. Use -f flag") - - if options.with_MPI == True: - from mpi4py import MPI # use mpi4py for parallel run (also valid for serial) - comm = MPI.COMM_WORLD - else: - comm = 0 - - # Initialize the corresponding driver of SU2, this includes solver preprocessing - try: - if (options.nZone == 1) and ( options.fem or options.poisson_equation or options.wave_equation or options.heat_equation ): - SU2Driver = pysu2.CSinglezoneDriver(options.filename, options.nZone, comm); - elif options.harmonic_balance: - SU2Driver = pysu2.CHBDriver(options.filename, options.nZone, comm); - elif (options.nZone >= 2): - SU2Driver = pysu2.CMultizoneDriver(options.filename, options.nZone, comm); - else: - SU2Driver = pysu2.CSinglezoneDriver(options.filename, options.nZone, comm); - except TypeError as exception: - print('A TypeError occured in pysu2.CDriver : ',exception) + # Command line options + parser = OptionParser() + parser.add_option( + "-f", "--file", dest="filename", help="Read config from FILE", metavar="FILE" + ) + parser.add_option( + "--nDim", + dest="nDim", + default=2, + help="Define the number of DIMENSIONS", + metavar="DIMENSIONS", + ) + parser.add_option( + "--nZone", + dest="nZone", + default=1, + help="Define the number of ZONES", + metavar="NZONE", + ) + parser.add_option( + "--parallel", + action="store_true", + help="Specify if we need to initialize MPI", + dest="with_MPI", + default=False, + ) + parser.add_option( + "--fsi", + dest="fsi", + default="False", + help="Launch the FSI driver", + metavar="FSI", + ) + parser.add_option( + "--fem", + dest="fem", + default="False", + help="Launch the FEM driver (General driver)", + metavar="FEM", + ) + parser.add_option( + "--harmonic_balance", + dest="harmonic_balance", + default="False", + help="Launch the Harmonic Balance (HB) driver", + metavar="HB", + ) + parser.add_option( + "--poisson_equation", + dest="poisson_equation", + default="False", + help="Launch the poisson equation driver (General driver)", + metavar="POIS_EQ", + ) + parser.add_option( + "--wave_equation", + dest="wave_equation", + default="False", + help="Launch the wave equation driver (General driver)", + metavar="WAVE_EQ", + ) + parser.add_option( + "--heat_equation", + dest="heat_equation", + default="False", + help="Launch the heat equation driver (General driver)", + metavar="HEAT_EQ", + ) + + (options, args) = parser.parse_args() + options.nDim = int(options.nDim) + options.nZone = int(options.nZone) + options.fsi = options.fsi.upper() == "TRUE" + options.fem = options.fem.upper() == "TRUE" + options.harmonic_balance = options.harmonic_balance.upper() == "TRUE" + options.poisson_equation = options.poisson_equation.upper() == "TRUE" + options.wave_equation = options.wave_equation.upper() == "TRUE" + options.heat_equation = options.heat_equation.upper() == "TRUE" + + if options.filename == None: + raise Exception("No config file provided. Use -f flag") + if options.with_MPI == True: - print('ERROR : You are trying to initialize MPI with a serial build of the wrapper. Please, remove the --parallel option that is incompatible with a serial build.') + from mpi4py import MPI # use mpi4py for parallel run (also valid for serial) + + comm = MPI.COMM_WORLD else: - print('ERROR : You are trying to launch a computation without initializing MPI but the wrapper has been built in parallel. Please add the --parallel option in order to initialize MPI for the wrapper.') - return + comm = 0 + + # Initialize the corresponding driver of SU2, this includes solver preprocessing + try: + if (options.nZone == 1) and ( + options.fem + or options.poisson_equation + or options.wave_equation + or options.heat_equation + ): + SU2Driver = pysu2.CSinglezoneDriver(options.filename, options.nZone, comm) + elif options.harmonic_balance: + SU2Driver = pysu2.CHBDriver(options.filename, options.nZone, comm) + elif options.nZone >= 2: + SU2Driver = pysu2.CMultizoneDriver(options.filename, options.nZone, comm) + else: + SU2Driver = pysu2.CSinglezoneDriver(options.filename, options.nZone, comm) + except TypeError as exception: + print("A TypeError occured in pysu2.CDriver : ", exception) + if options.with_MPI == True: + print( + "ERROR : You are trying to initialize MPI with a serial build of the wrapper. Please, remove the --parallel option that is incompatible with a serial build." + ) + else: + print( + "ERROR : You are trying to launch a computation without initializing MPI but the wrapper has been built in parallel. Please add the --parallel option in order to initialize MPI for the wrapper." + ) + return + + # Launch the solver for the entire computation + SU2Driver.StartSolver() - # Launch the solver for the entire computation - SU2Driver.StartSolver() + # Postprocess the solver and exit cleanly + SU2Driver.Postprocessing() - # Postprocess the solver and exit cleanly - SU2Driver.Postprocessing() + if SU2Driver != None: + del SU2Driver - if SU2Driver != None: - del SU2Driver # ------------------------------------------------------------------- # Run Main Program # ------------------------------------------------------------------- # this is only accessed if running from command prompt -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/SU2_PY/SU2_Nastran/pysu2_nastran.py b/SU2_PY/SU2_Nastran/pysu2_nastran.py index 216bc22740f..e629d3d6d5a 100644 --- a/SU2_PY/SU2_Nastran/pysu2_nastran.py +++ b/SU2_PY/SU2_Nastran/pysu2_nastran.py @@ -37,1007 +37,1142 @@ # Config class # ---------------------------------------------------------------------- -class ImposedMotionClass: - - def __init__(self,time0,typeOfMotion,parameters,mode): - - self.time0 = time0 - self.typeOfMotion = typeOfMotion - self.mode = mode - - self.amplitude = parameters["AMPLITUDE"] - self.timeStart = parameters["TIME_START"] - if "TIME_STOP" in parameters.keys(): - self.timeStop = parameters["TIME_STOP"] - else: - self.timeStop = inf - - if self.typeOfMotion == "SINUSOIDAL": - self.bias = parameters["BIAS"] - self.frequency = parameters["FREQUENCY"] - - elif self.typeOfMotion == "BLENDED_STEP": - self.kmax = parameters["K_MAX"] - self.vinf = parameters["V_INF"] - self.lref = parameters["L_REF"] - self.tmax = 2*pi/self.kmax*self.lref/self.vinf - self.omega0 = 1/2*self.kmax - - else: - raise Exception('Imposed function {} not found, please implement it in pysu2_nastran.py'.format(self.tipo)) +class ImposedMotionClass: + def __init__(self, time0, typeOfMotion, parameters, mode): - def GetDispl(self,time): - time = time - self.time0 - self.timeStart - if self.typeOfMotion == "SINUSOIDAL": - if (time < 0.0) or (time > self.timeStop): - return 0.0 - return self.bias+self.amplitude*sin(2*pi*self.frequency*time) - - if self.typeOfMotion == "BLENDED_STEP": - if (time < 0.0) or (time > self.timeStop): - return 0.0 - if time < self.tmax: - return self.amplitude/2.0*(1.0-cos(self.omega0*time*self.vinf/self.lref)) - return self.amplitude - - - def GetVel(self,time): - time = time - self.time0 - self.timeStart - - if self.typeOfMotion == "SINUSOIDAL": - if (time < 0.0) or (time > self.timeStop): - return 0.0 - return self.amplitude*cos(2*pi*self.frequency*time)*2*pi*self.frequency + self.time0 = time0 + self.typeOfMotion = typeOfMotion + self.mode = mode - if self.typeOfMotion == "BLENDED_STEP": - if (time < 0.0) or (time > self.timeStop): - return 0.0 - if time < self.tmax: - return self.amplitude/2.0*sin(self.omega0*time*self.vinf/self.lref)*(self.omega0*self.vinf/self.lref) - return 0.0 + self.amplitude = parameters["AMPLITUDE"] + self.timeStart = parameters["TIME_START"] + if "TIME_STOP" in parameters.keys(): + self.timeStop = parameters["TIME_STOP"] + else: + self.timeStop = inf - def GetAcc(self,time): - time = time - self.time0 - self.timeStart + if self.typeOfMotion == "SINUSOIDAL": + self.bias = parameters["BIAS"] + self.frequency = parameters["FREQUENCY"] - if self.typeOfMotion == "SINUSOIDAL": - if (time < 0.0) or (time > self.timeStop): - return 0.0 - return -self.amplitude*sin(2*pi*self.frequency*time)*(2*pi*self.frequency)**2 + elif self.typeOfMotion == "BLENDED_STEP": + self.kmax = parameters["K_MAX"] + self.vinf = parameters["V_INF"] + self.lref = parameters["L_REF"] + self.tmax = 2 * pi / self.kmax * self.lref / self.vinf + self.omega0 = 1 / 2 * self.kmax - if self.typeOfMotion == "BLENDED_STEP": - if (time < 0.0) or (time > self.timeStop): - return 0.0 - if time < self.tmax: - return self.amplitude/2.0*cos(self.omega0*time*self.vinf/self.lref)*(self.omega0*self.vinf/self.lref)**2 - return 0.0 + else: + raise Exception( + "Imposed function {} not found, please implement it in pysu2_nastran.py".format( + self.tipo + ) + ) + + def GetDispl(self, time): + time = time - self.time0 - self.timeStart + if self.typeOfMotion == "SINUSOIDAL": + if (time < 0.0) or (time > self.timeStop): + return 0.0 + return self.bias + self.amplitude * sin(2 * pi * self.frequency * time) + + if self.typeOfMotion == "BLENDED_STEP": + if (time < 0.0) or (time > self.timeStop): + return 0.0 + if time < self.tmax: + return ( + self.amplitude + / 2.0 + * (1.0 - cos(self.omega0 * time * self.vinf / self.lref)) + ) + return self.amplitude + + def GetVel(self, time): + time = time - self.time0 - self.timeStart + + if self.typeOfMotion == "SINUSOIDAL": + if (time < 0.0) or (time > self.timeStop): + return 0.0 + return ( + self.amplitude + * cos(2 * pi * self.frequency * time) + * 2 + * pi + * self.frequency + ) + + if self.typeOfMotion == "BLENDED_STEP": + if (time < 0.0) or (time > self.timeStop): + return 0.0 + if time < self.tmax: + return ( + self.amplitude + / 2.0 + * sin(self.omega0 * time * self.vinf / self.lref) + * (self.omega0 * self.vinf / self.lref) + ) + return 0.0 + + def GetAcc(self, time): + time = time - self.time0 - self.timeStart + + if self.typeOfMotion == "SINUSOIDAL": + if (time < 0.0) or (time > self.timeStop): + return 0.0 + return ( + -self.amplitude + * sin(2 * pi * self.frequency * time) + * (2 * pi * self.frequency) ** 2 + ) + + if self.typeOfMotion == "BLENDED_STEP": + if (time < 0.0) or (time > self.timeStop): + return 0.0 + if time < self.tmax: + return ( + self.amplitude + / 2.0 + * cos(self.omega0 * time * self.vinf / self.lref) + * (self.omega0 * self.vinf / self.lref) ** 2 + ) + return 0.0 class RefSystem: + def __init__(self): + self.CID = 0 + self.RID = 0 + self.Origin = np.array([[0.0], [0.0], [0.0]]) + self.Rot = np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]) - def __init__(self): - self.CID = 0 - self.RID = 0 - self.Origin = np.array([[0.],[0.],[0.]]) - self.Rot = np.array([[0.,0.,0.],[0.,0.,0.],[0.,0.,0.]]) + def SetOrigin(self, A): + AX, AY, AZ = A + self.Origin[0] = AX + self.Origin[1] = AY + self.Origin[2] = AZ - def SetOrigin(self,A): - AX , AY , AZ = A - self.Origin[0] = AX - self.Origin[1] = AY - self.Origin[2] = AZ + def SetRotMatrix(self, x, y, z): + self.Rot = np.array( + [[x[0], y[0], z[0]], [x[1], y[1], z[1]], [x[2], y[2], z[2]]] + ) - def SetRotMatrix(self,x,y,z): - self.Rot = np.array([[x[0],y[0],z[0]],[x[1],y[1],z[1]],[x[2],y[2],z[2]]]) + def SetCID(self, CID): + self.CID = CID - def SetCID(self,CID): - self.CID = CID + def SetRID(self, RID): + self.RID = RID - def SetRID(self,RID): - self.RID = RID + def GetOrigin(self): + return self.Origin - def GetOrigin(self): - return self.Origin + def GetRotMatrix(self): + return self.Rot - def GetRotMatrix(self): - return self.Rot + def GetRID(self): + return self.RID - def GetRID(self): - return self.RID + def GetCID(self): + return self.CID - def GetCID(self): - return self.CID class Point: - """ - Class containing data regarding all the structural nodes. - Coord0: Coordinates at the initial time iteration. - Coord: Coordinates at the current time iteration. - Coord_n: Coordinates at the previous time iteration. - Vel: Velocity at the current time iteration. - Vel_n: Velocity at the previous time iteration. - Force: Nodal force provided by the aerodynamics. - ID: ID of the node. - CP: Coordinate system definition of the position. - CD: Coordinate system definition of the output coming from Nastran. - """ - - def __init__(self): - self.Coord0 = np.zeros((3,1)) - self.Coord = np.zeros((3,1)) - self.Coord_n = np.zeros((3,1)) - self.Vel = np.zeros((3,1)) - self.Vel_n = np.zeros((3,1)) - self.Force = np.zeros((3,1)) - self.ID = 0 - self.CP = 0 - self.CD = 0 - - def GetCoord0(self): - return self.Coord0 - - def GetCoord(self): - return self.Coord - - def GetCoord_n(self): - return self.Coord_n - - def GetVel(self): - return self.Vel - - def GetVel_n(self): - return self.Vel_n - - def GetForce(self): - return self.Force - - def GetID(self): - return self.ID - - def GetCP(self): - return self.CP - - def GetCD(self): - return self.CD - - def SetCoord0(self, val_Coord): - x, y, z = val_Coord - self.Coord0[0] = x - self.Coord0[1] = y - self.Coord0[2] = z - - def SetCoord(self, val_Coord): - x, y, z = val_Coord - self.Coord[0] = x - self.Coord[1] = y - self.Coord[2] = z - - def SetCoord_n(self, val_Coord): - x, y, z = val_Coord - self.Coord_n[0] = x - self.Coord_n[1] = y - self.Coord_n[2] = z - - def SetVel(self, val_Vel): - vx, vy, vz = val_Vel - self.Vel[0] = vx - self.Vel[1] = vy - self.Vel[2] = vz - - def SetVel_n(self, val_Vel): - vx, vy, vz = val_Vel - self.Vel_n[0] = vx - self.Vel_n[1] = vy - self.Vel_n[2] = vz - - def SetForce(self, val_Force): - fx, fy, fz = val_Force - self.Force[0] = fx - self.Force[1] = fy - self.Force[2] = fz - - def SetID(self, ID): - self.ID = ID - - def SetCP(self,CP): - self.CP = CP - - def SetCD(self,CD): - self.CD = CD - - def updateCoordVel(self): - self.Coord_n = np.copy(self.Coord) - self.Vel_n = np.copy(self.Vel) - -class Solver: - """ - Structural solver main class. - It contains all the required methods for the coupling with SU2. - """ - - def __init__(self, config_fileName, ImposedMotion): """ - Constructor of the structural solver class. + Class containing data regarding all the structural nodes. + Coord0: Coordinates at the initial time iteration. + Coord: Coordinates at the current time iteration. + Coord_n: Coordinates at the previous time iteration. + Vel: Velocity at the current time iteration. + Vel_n: Velocity at the previous time iteration. + Force: Nodal force provided by the aerodynamics. + ID: ID of the node. + CP: Coordinate system definition of the position. + CD: Coordinate system definition of the output coming from Nastran. """ - self.Config_file = config_fileName - self.Config = {} - - print("\n") - print(" Configuring the structural tester solver for FSI simulation ".center(80,"-")) - self.__readConfig() - - self.Mesh_file = self.Config['MESH_FILE'] - self.Punch_file = self.Config['PUNCH_FILE'] - self.FSI_marker = self.Config['MOVING_MARKER'] - self.Unsteady = (self.Config['TIME_MARCHING']=="YES") - self.ImposedMotion = ImposedMotion - if self.Unsteady: - print('Dynamic computation.') - self.nDof = self.Config['NMODES'] - print("Reading number of modes from file") - - - # Structural properties - print("Reading the modal and stiffnes matrix from file") - self.ModalDamping = self.Config['MODAL_DAMPING'] - if self.ModalDamping == 0: - print("The structural model is undamped") - else: - print("Assuming {}% of modal damping".format(self.ModalDamping*100)) - - self.deltaT = self.Config['DELTA_T'] - self.rhoAlphaGen = self.Config['RHO'] - - self.nPoint = int() - self.nMarker = int() - self.nRefSys = int() - self.node = [] - self.markers = {} - self.refsystems = [] - self.ImposedMotionToSet = True - self.ImposedMotionFunction = [] - - print("\n") - print(" Reading the mesh ".center(80,"-")) - self.__readNastranMesh() - - print("\n") - print(" Creating the structural model ".center(80,"-")) - self.__setStructuralMatrices() - - print("\n") - print(" Setting the integration parameters ".center(80,"-")) - self.__setIntegrationParameters() - self.__setInitialConditions() - - # Prepare the output file - if self.Config["RESTART_SOL"]=="NO": - histFile = open('StructHistoryModal.dat', "w") - header = 'Time\t' + 'Time Iteration\t' + 'FSI Iteration\t' - for imode in range(self.nDof): - header = header + 'q' + str(imode+1) + '\t' + 'qdot' + str(imode+1) + '\t' + 'qddot' + str(imode+1) + '\t' - header = header + '\n' - histFile.write(header) - histFile.close() - else: - self.__setRestart() - - def __readConfig(self): - """ - This methods obtains the configuration options from the structural solver input - file. - """ - - with open(self.Config_file) as configfile: - while 1: - line = configfile.readline() - if not line: - break - - # remove line returns - line = line.strip('\r\n') - # make sure it has useful data - if (not "=" in line) or (line[0] == '%'): - continue - # split across equal sign - line = line.split("=",1) - this_param = line[0].strip() - this_value = line[1].strip() - - #integer values - if (this_param == "NMODES") or \ - (this_param == "RESTART_ITER"): - self.Config[this_param] = int(this_value) - - - #float values - elif (this_param == "DELTA_T") or \ - (this_param == "MODAL_DAMPING") or \ - (this_param == "RHO"): - self.Config[this_param] = float(this_value) - - - #string values - elif (this_param == "TIME_MARCHING") or \ - (this_param == "MESH_FILE") or \ - (this_param == "PUNCH_FILE") or \ - (this_param == "RESTART_SOL") or \ - (this_param == "MOVING_MARKER"): - self.Config[this_param] = this_value - - - #lists values - elif (this_param == "INITIAL_MODES") or \ - (this_param == "IMPOSED_MODES") or \ - (this_param == "IMPOSED_PARAMETERS"): - self.Config[this_param] = eval(this_value) + def __init__(self): + self.Coord0 = np.zeros((3, 1)) + self.Coord = np.zeros((3, 1)) + self.Coord_n = np.zeros((3, 1)) + self.Vel = np.zeros((3, 1)) + self.Vel_n = np.zeros((3, 1)) + self.Force = np.zeros((3, 1)) + self.ID = 0 + self.CP = 0 + self.CD = 0 + def GetCoord0(self): + return self.Coord0 - else: - raise Exception('{} is an invalid option !'.format(this_param)) - - - - def __readNastranMesh(self): - """ - This method reads the nastran 3D mesh. - """ - - def nastran_float(s): - if s.find('E') == -1: - s = s.replace('-','e-') - s = s.replace('+','e+') - if s[0] == 'e': - s = s[1:] - return float(s) - - self.nMarker = 0 - self.nPoint = 0 - self.nRefSys = 0 - - with open(self.Mesh_file,'r') as meshfile: - print('Opened mesh file ' + self.Mesh_file + '.') - while 1: - line = meshfile.readline() - if not line: - break - - pos = line.find('GRID') - if pos == 30: - line = line.strip('\r\n') - self.node.append(Point()) - line = line[30:] - ID = int(line[8:16]) - CP = self.__checkBlankField(line[16:24]) - x = nastran_float(line[24:32]) - y = nastran_float(line[32:40]) - z = nastran_float(line[40:48]) - if CP != 0: - for iRefSys in range(self.nRefSys): - if self.refsystems[iRefSys].GetCID()==CP: - break - if self.refsystems[iRefSys].GetCID()!=CP: - raise Exception('Definition reference {} system not found'.format(CP)) - DeltaPos = self.refsystems[iRefSys].GetOrigin() - RotatedPos = self.refsystems[iRefSys].GetRotMatrix().dot(np.array([[x],[y],[z]])) - x = RotatedPos[0]+DeltaPos[0] - y = RotatedPos[1]+DeltaPos[1] - z = RotatedPos[2]+DeltaPos[2] - CD = self.__checkBlankField(line[48:56]) - self.node[self.nPoint].SetCoord((x,y,z)) - self.node[self.nPoint].SetID(ID) - self.node[self.nPoint].SetCP(CP) - self.node[self.nPoint].SetCD(CD) - self.node[self.nPoint].SetCoord0((x,y,z)) - self.node[self.nPoint].SetCoord_n((x,y,z)) - self.nPoint += 1 - continue - - pos = line.find('CORD2R') - if pos == 30: - line = line.strip('\r\n') - self.refsystems.append(RefSystem()) - line = line[30:] - CID = int(line[8:16]) - self.refsystems[self.nRefSys].SetCID(CID) - RID = int(line[16:24]) - if RID!=0: - raise Exception('ERROR: Reference system {} must be defined with respect to global reference system'.format(CID)) - self.refsystems[self.nRefSys].SetRID(RID) - AX = nastran_float(line[24:32]) - AY = nastran_float(line[32:40]) - AZ = nastran_float(line[40:48]) - BX = nastran_float(line[48:56]) - BY = nastran_float(line[56:64]) - BZ = nastran_float(line[64:72]) - z_direction = np.array([BX-AX,BY-AY,BZ-AZ]) - z_direction = z_direction/linalg.norm(z_direction) - line = meshfile.readline() - line = line.strip('\r\n') - line = line[30:] - CX = nastran_float(line[8:16]) - CY = nastran_float(line[16:24]) - CZ = nastran_float(line[24:32]) - y_direction = np.cross(z_direction,[CX-AX,CY-AY,CZ-AZ]) - y_direction = y_direction/linalg.norm(y_direction) - x_direction = np.cross(y_direction,z_direction) - x_direction = x_direction/linalg.norm(x_direction) - self.refsystems[self.nRefSys].SetRotMatrix(x_direction,y_direction,z_direction) - self.refsystems[self.nRefSys].SetOrigin((AX,AY,AZ)) - self.nRefSys += 1 - continue - - pos = line.find("SET1") - if pos == 30: - line = line.strip('\r\n') - line = line[37:] - line = line.split() - existValue = True - markerTag = line.pop(0) - self.markers[markerTag] = [] - while existValue: - if line[0] == "+": - line = meshfile.readline() - line = line.strip('\r\n') - line = line[37:] - line = line.split() - ID = int(line.pop(0)) - for iPoint in range(self.nPoint): - if self.node[iPoint].GetID() == ID: - break - if (iPoint == (self.nPoint-1)) and (self.node[iPoint].GetID() != ID): - raise Exception("Point {} in the set {} was not found in the mesh".format(ID,markerTag)) - self.markers[markerTag].append(iPoint) - existValue = len(line)>=1 - self.nMarker += 1 - continue - - if not any(self.FSI_marker in key for key in self.markers.keys()): - raise Exception("The FSI marker was not found in the available sets") - - self.markers[self.FSI_marker].sort() - - print("Number of points: {}".format(self.nPoint)) - print("Number of markers: {}".format(self.nMarker)) - print("Number of reference systems: {}".format(self.nRefSys)) - print("Moving marker: {}".format(self.FSI_marker)) - print("Number of points in the moving marker".format(len(self.markers[self.FSI_marker]))) - - def __checkBlankField(self, string): - """ - This method considers that Nastran apply 0 when the reference system is not specified - """ - - if string == ' '*8: - return int(0) - return int(string) + def GetCoord(self): + return self.Coord + def GetCoord_n(self): + return self.Coord_n - def __setStructuralMatrices(self): - """ - This method reads the punch file and obtains the modal shapes and modal stiffnesses. - """ - - self.M = np.zeros((self.nDof, self.nDof)) - self.K = np.zeros((self.nDof, self.nDof)) - self.C = np.zeros((self.nDof, self.nDof)) - - self.q = np.zeros((self.nDof, 1)) - self.qdot = np.zeros((self.nDof, 1)) - self.qddot = np.zeros((self.nDof, 1)) - self.a = np.zeros((self.nDof, 1)) - - self.q_n = np.zeros((self.nDof, 1)) - self.qdot_n = np.zeros((self.nDof, 1)) - self.qddot_n = np.zeros((self.nDof, 1)) - self.a_n = np.zeros((self.nDof, 1)) - - self.F = np.zeros((self.nDof, 1)) - - self.Ux = np.zeros((self.nPoint,self.nDof)) - self.Uy = np.zeros((self.nPoint,self.nDof)) - self.Uz = np.zeros((self.nPoint,self.nDof)) - - with open(self.Punch_file,'r') as punchfile: - print('Opened punch file ' + self.Punch_file + '.') - while 1: - line = punchfile.readline() - if not line: - break - - pos = line.find('MODE ') - if pos != -1: - line = line.strip('\r\n').split() - n = int(line[5]) - imode = n-1 - k_i = float(line[2]) - self.M[imode][imode] = 1 - self.K[imode][imode] = k_i - w_i = sqrt(k_i) - self.C[imode][imode] = 2 * self.ModalDamping * w_i - iPoint = 0 - for indexIter in range(self.nPoint): - line = punchfile.readline() - line = line.strip('\r\n').split() - if line[1]=='G': - ux = float(line[2]) - uy = float(line[3]) - uz = float(line[4]) - if self.node[iPoint].GetCD()!=0: - for iRefSys in range(self.nRefSys): - if self.refsystems[iRefSys].GetCID()==self.node[iPoint].GetCD(): - break - if self.refsystems[iRefSys].GetCID()!=self.node[iPoint].GetCD(): - raise Exception('Output reference {} system not found'.format(self.node[iPoint].GetCD())) - RotatedOutput = self.refsystems[iRefSys].GetRotMatrix().dot(np.array([[ux],[uy],[uz]])) - ux = RotatedOutput[0] - uy = RotatedOutput[1] - uz = RotatedOutput[2] - self.Ux[iPoint][imode] = ux - self.Uy[iPoint][imode] = uy - self.Uz[iPoint][imode] = uz - iPoint = iPoint + 1 - line = punchfile.readline() - if line[1]=='S': - line = punchfile.readline() - - if n == self.nDof: - break - - self.__setNonDiagonalStructuralMatrices() - - self.UxT = self.Ux.transpose() - self.UyT = self.Uy.transpose() - self.UzT = self.Uz.transpose() - - if n= eps: - St = self.__TangentOperator() - Deltaq = -1*(linalg.solve(St,res)) - self.q += Deltaq - self.qdot += self.gammaPrime*Deltaq - self.qddot += self.betaPrime*Deltaq - res = self.__ComputeResidual() - - self.a += (1-self.alpha_f)/(1-self.alpha_m)*self.qddot - else: - if self.ImposedMotionToSet: + print("Assuming {}% of modal damping".format(self.ModalDamping * 100)) + + self.deltaT = self.Config["DELTA_T"] + self.rhoAlphaGen = self.Config["RHO"] + + self.nPoint = int() + self.nMarker = int() + self.nRefSys = int() + self.node = [] + self.markers = {} + self.refsystems = [] + self.ImposedMotionToSet = True + self.ImposedMotionFunction = [] + + print("\n") + print(" Reading the mesh ".center(80, "-")) + self.__readNastranMesh() + + print("\n") + print(" Creating the structural model ".center(80, "-")) + self.__setStructuralMatrices() + + print("\n") + print(" Setting the integration parameters ".center(80, "-")) + self.__setIntegrationParameters() + self.__setInitialConditions() + + # Prepare the output file if self.Config["RESTART_SOL"] == "NO": - # If yes we already set it in the __setRestart function - self.timeStartCoupling = time - iImposedFunc = 0 - for imode in self.Config["IMPOSED_MODES"].keys(): - for isuperposed in range(len(self.Config["IMPOSED_MODES"][imode])): - typeOfMotion = self.Config["IMPOSED_MODES"][imode][isuperposed] - parameters = self.Config["IMPOSED_PARAMETERS"][imode][isuperposed] - self.ImposedMotionFunction.append(ImposedMotionClass(self.timeStartCoupling, typeOfMotion, parameters, imode)) - iImposedFunc += 1 - self.ImposedMotionToSet = False - for iImposedFunc in range(len(self.ImposedMotionFunction)): - imode = self.ImposedMotionFunction[iImposedFunc].mode - self.q[imode] += self.ImposedMotionFunction[iImposedFunc].GetDispl(time) - self.qdot[imode] += self.ImposedMotionFunction[iImposedFunc].GetVel(time) - self.qddot[imode] += self.ImposedMotionFunction[iImposedFunc].GetAcc(time) - self.a = np.copy(self.qddot) - - - def __SetLoads(self): - """ - This method uses the nodal forces and the mode shapes to obtain the modal forces. - """ - nodeList = self.markers[self.FSI_marker] - FX = np.zeros((self.nPoint, 1)) - FY = np.zeros((self.nPoint, 1)) - FZ = np.zeros((self.nPoint, 1)) - for iPoint in nodeList: - Force = self.node[iPoint].GetForce() - FX[iPoint] = float(Force[0]) - FY[iPoint] = float(Force[1]) - FZ[iPoint] = float(Force[2]) - self.F = self.UxT.dot(FX) + self.UyT.dot(FY) + self.UzT.dot(FZ) - - def __ComputeResidual(self): - """ - This method computes the residual for integration. - """ - - res = self.M.dot(self.qddot) + self.C.dot(self.qdot) + self.K.dot(self.q) - self.F - - return res - - def __TangentOperator(self): - """ - This method computes the tangent operator for solution. - """ - - # The problem is linear, so the tangent operator is straightforward. - St = self.betaPrime*self.M + self.gammaPrime*self.C + self.K - - return St - - def exit(self): - """ - This method cleanly exits the structural solver. - """ - - print("\n**************** Exiting the structural tester solver ****************") - - def run(self,time): - """ - This method is the main function for advancing the solution of one time step. - """ - self.__temporalIteration(time) - header = 'Time\t' - for imode in range(min([self.nDof,5])): - header = header + 'q' + str(imode+1) + '\t' + 'qdot' + str(imode+1) + '\t' + 'qddot' + str(imode+1) + '\t' - header = header + '\n' - print(header) - line = '{:6.4f}'.format(time) + '\t' - for imode in range(min([self.nDof,5])): - line = line + '{:6.4f}'.format(float(self.q[imode])) + '\t' + '{:6.4f}'.format(float(self.qdot[imode])) + '\t' + '{:6.4f}'.format(float(self.qddot[imode])) + '\t' - line = line + '\n' - print(line) - self.__computeInterfacePosVel(False) - - def activateMode(self, iMode): - """ - This method is used to artificially set only one mode activated, thus - with non zero amplitude. - """ - self.__reset(self.q) - self.q[iMode] = 1.0 - self.__computeInterfacePosVel(True) - - def setInitialDisplacements(self): - """ - This method provides public access to the method __computeInterfacePosVel and - sets velocities for previous time steps. - """ - - self.__computeInterfacePosVel(True) - - def writeSolution(self, time, timeIter, FSIIter): - """ - This method is the main function for output. It writes the file StructHistoryModal.dat - """ - - # Modal History - histFile = open('StructHistoryModal.dat', "a") - line = str(time) + '\t' + str(timeIter) + '\t' + str(FSIIter) + '\t' - for imode in range(self.nDof): - line = line + str(float(self.q[imode])) + '\t' + str(float(self.qdot[imode])) + '\t' + str(float(self.qddot[imode])) + '\t' - line = line + '\n' - histFile.write(line) - histFile.close() - - def updateSolution(self): - """ - This method updates the solution. - """ - - self.q_n = np.copy(self.q) - self.qdot_n = np.copy(self.qdot) - self.qddot_n = np.copy(self.qddot) - self.a_n = np.copy(self.a) - self.__reset(self.q) - self.__reset(self.qdot) - self.__reset(self.qddot) - self.__reset(self.a) - - for iPoint in range(self.nPoint): - self.node[iPoint].updateCoordVel() - - - def applyload(self, iVertex, fx, fy, fz): - """ - This method can be accessed from outside to set the nodal forces. - """ - iPoint = self.getVertexGlobalIndex(self.FSI_marker, iVertex) - self.node[iPoint].SetForce((fx,fy,fz)) + histFile = open("StructHistoryModal.dat", "w") + header = "Time\t" + "Time Iteration\t" + "FSI Iteration\t" + for imode in range(self.nDof): + header = ( + header + + "q" + + str(imode + 1) + + "\t" + + "qdot" + + str(imode + 1) + + "\t" + + "qddot" + + str(imode + 1) + + "\t" + ) + header = header + "\n" + histFile.write(header) + histFile.close() + else: + self.__setRestart() + + def __readConfig(self): + """ + This methods obtains the configuration options from the structural solver input + file. + """ + + with open(self.Config_file) as configfile: + while 1: + line = configfile.readline() + if not line: + break - def getNumberOfModes(self): - """ - This method provides the number of degrees of freedom used in - the structural solver. - """ - return self.nDof + # remove line returns + line = line.strip("\r\n") + # make sure it has useful data + if (not "=" in line) or (line[0] == "%"): + continue + # split across equal sign + line = line.split("=", 1) + this_param = line[0].strip() + this_value = line[1].strip() + + # integer values + if (this_param == "NMODES") or (this_param == "RESTART_ITER"): + self.Config[this_param] = int(this_value) + + # float values + elif ( + (this_param == "DELTA_T") + or (this_param == "MODAL_DAMPING") + or (this_param == "RHO") + ): + self.Config[this_param] = float(this_value) + + # string values + elif ( + (this_param == "TIME_MARCHING") + or (this_param == "MESH_FILE") + or (this_param == "PUNCH_FILE") + or (this_param == "RESTART_SOL") + or (this_param == "MOVING_MARKER") + ): + self.Config[this_param] = this_value + + # lists values + elif ( + (this_param == "INITIAL_MODES") + or (this_param == "IMPOSED_MODES") + or (this_param == "IMPOSED_PARAMETERS") + ): + self.Config[this_param] = eval(this_value) + + else: + raise Exception("{} is an invalid option !".format(this_param)) + + def __readNastranMesh(self): + """ + This method reads the nastran 3D mesh. + """ + + def nastran_float(s): + if s.find("E") == -1: + s = s.replace("-", "e-") + s = s.replace("+", "e+") + if s[0] == "e": + s = s[1:] + return float(s) + + self.nMarker = 0 + self.nPoint = 0 + self.nRefSys = 0 + + with open(self.Mesh_file, "r") as meshfile: + print("Opened mesh file " + self.Mesh_file + ".") + while 1: + line = meshfile.readline() + if not line: + break - def getFSIMarkerID(self): - """ - This method provides the ID of the interface marker - """ - return self.FSI_marker + pos = line.find("GRID") + if pos == 30: + line = line.strip("\r\n") + self.node.append(Point()) + line = line[30:] + ID = int(line[8:16]) + CP = self.__checkBlankField(line[16:24]) + x = nastran_float(line[24:32]) + y = nastran_float(line[32:40]) + z = nastran_float(line[40:48]) + if CP != 0: + for iRefSys in range(self.nRefSys): + if self.refsystems[iRefSys].GetCID() == CP: + break + if self.refsystems[iRefSys].GetCID() != CP: + raise Exception( + "Definition reference {} system not found".format(CP) + ) + DeltaPos = self.refsystems[iRefSys].GetOrigin() + RotatedPos = ( + self.refsystems[iRefSys] + .GetRotMatrix() + .dot(np.array([[x], [y], [z]])) + ) + x = RotatedPos[0] + DeltaPos[0] + y = RotatedPos[1] + DeltaPos[1] + z = RotatedPos[2] + DeltaPos[2] + CD = self.__checkBlankField(line[48:56]) + self.node[self.nPoint].SetCoord((x, y, z)) + self.node[self.nPoint].SetID(ID) + self.node[self.nPoint].SetCP(CP) + self.node[self.nPoint].SetCD(CD) + self.node[self.nPoint].SetCoord0((x, y, z)) + self.node[self.nPoint].SetCoord_n((x, y, z)) + self.nPoint += 1 + continue + + pos = line.find("CORD2R") + if pos == 30: + line = line.strip("\r\n") + self.refsystems.append(RefSystem()) + line = line[30:] + CID = int(line[8:16]) + self.refsystems[self.nRefSys].SetCID(CID) + RID = int(line[16:24]) + if RID != 0: + raise Exception( + "ERROR: Reference system {} must be defined with respect to global reference system".format( + CID + ) + ) + self.refsystems[self.nRefSys].SetRID(RID) + AX = nastran_float(line[24:32]) + AY = nastran_float(line[32:40]) + AZ = nastran_float(line[40:48]) + BX = nastran_float(line[48:56]) + BY = nastran_float(line[56:64]) + BZ = nastran_float(line[64:72]) + z_direction = np.array([BX - AX, BY - AY, BZ - AZ]) + z_direction = z_direction / linalg.norm(z_direction) + line = meshfile.readline() + line = line.strip("\r\n") + line = line[30:] + CX = nastran_float(line[8:16]) + CY = nastran_float(line[16:24]) + CZ = nastran_float(line[24:32]) + y_direction = np.cross(z_direction, [CX - AX, CY - AY, CZ - AZ]) + y_direction = y_direction / linalg.norm(y_direction) + x_direction = np.cross(y_direction, z_direction) + x_direction = x_direction / linalg.norm(x_direction) + self.refsystems[self.nRefSys].SetRotMatrix( + x_direction, y_direction, z_direction + ) + self.refsystems[self.nRefSys].SetOrigin((AX, AY, AZ)) + self.nRefSys += 1 + continue + + pos = line.find("SET1") + if pos == 30: + line = line.strip("\r\n") + line = line[37:] + line = line.split() + existValue = True + markerTag = line.pop(0) + self.markers[markerTag] = [] + while existValue: + if line[0] == "+": + line = meshfile.readline() + line = line.strip("\r\n") + line = line[37:] + line = line.split() + ID = int(line.pop(0)) + for iPoint in range(self.nPoint): + if self.node[iPoint].GetID() == ID: + break + if (iPoint == (self.nPoint - 1)) and ( + self.node[iPoint].GetID() != ID + ): + raise Exception( + "Point {} in the set {} was not found in the mesh".format( + ID, markerTag + ) + ) + self.markers[markerTag].append(iPoint) + existValue = len(line) >= 1 + self.nMarker += 1 + continue + + if not any(self.FSI_marker in key for key in self.markers.keys()): + raise Exception("The FSI marker was not found in the available sets") + + self.markers[self.FSI_marker].sort() + + print("Number of points: {}".format(self.nPoint)) + print("Number of markers: {}".format(self.nMarker)) + print("Number of reference systems: {}".format(self.nRefSys)) + print("Moving marker: {}".format(self.FSI_marker)) + print( + "Number of points in the moving marker".format( + len(self.markers[self.FSI_marker]) + ) + ) + + def __checkBlankField(self, string): + """ + This method considers that Nastran apply 0 when the reference system is not specified + """ + + if string == " " * 8: + return int(0) + return int(string) + + def __setStructuralMatrices(self): + """ + This method reads the punch file and obtains the modal shapes and modal stiffnesses. + """ + + self.M = np.zeros((self.nDof, self.nDof)) + self.K = np.zeros((self.nDof, self.nDof)) + self.C = np.zeros((self.nDof, self.nDof)) + + self.q = np.zeros((self.nDof, 1)) + self.qdot = np.zeros((self.nDof, 1)) + self.qddot = np.zeros((self.nDof, 1)) + self.a = np.zeros((self.nDof, 1)) + + self.q_n = np.zeros((self.nDof, 1)) + self.qdot_n = np.zeros((self.nDof, 1)) + self.qddot_n = np.zeros((self.nDof, 1)) + self.a_n = np.zeros((self.nDof, 1)) + + self.F = np.zeros((self.nDof, 1)) + + self.Ux = np.zeros((self.nPoint, self.nDof)) + self.Uy = np.zeros((self.nPoint, self.nDof)) + self.Uz = np.zeros((self.nPoint, self.nDof)) + + with open(self.Punch_file, "r") as punchfile: + print("Opened punch file " + self.Punch_file + ".") + while 1: + line = punchfile.readline() + if not line: + break - def getNumberOfSolidInterfaceNodes(self, markerID): + pos = line.find("MODE ") + if pos != -1: + line = line.strip("\r\n").split() + n = int(line[5]) + imode = n - 1 + k_i = float(line[2]) + self.M[imode][imode] = 1 + self.K[imode][imode] = k_i + w_i = sqrt(k_i) + self.C[imode][imode] = 2 * self.ModalDamping * w_i + iPoint = 0 + for indexIter in range(self.nPoint): + line = punchfile.readline() + line = line.strip("\r\n").split() + if line[1] == "G": + ux = float(line[2]) + uy = float(line[3]) + uz = float(line[4]) + if self.node[iPoint].GetCD() != 0: + for iRefSys in range(self.nRefSys): + if ( + self.refsystems[iRefSys].GetCID() + == self.node[iPoint].GetCD() + ): + break + if ( + self.refsystems[iRefSys].GetCID() + != self.node[iPoint].GetCD() + ): + raise Exception( + "Output reference {} system not found".format( + self.node[iPoint].GetCD() + ) + ) + RotatedOutput = ( + self.refsystems[iRefSys] + .GetRotMatrix() + .dot(np.array([[ux], [uy], [uz]])) + ) + ux = RotatedOutput[0] + uy = RotatedOutput[1] + uz = RotatedOutput[2] + self.Ux[iPoint][imode] = ux + self.Uy[iPoint][imode] = uy + self.Uz[iPoint][imode] = uz + iPoint = iPoint + 1 + line = punchfile.readline() + if line[1] == "S": + line = punchfile.readline() + + if n == self.nDof: + break + + self.__setNonDiagonalStructuralMatrices() + + self.UxT = self.Ux.transpose() + self.UyT = self.Uy.transpose() + self.UzT = self.Uz.transpose() + + if n < self.nDof: + raise Exception( + "ERROR: available {} degrees of freedom instead of {} as requested".format( + n, self.nDof + ) + ) + else: + print("Using {} degrees of freedom".format(n)) + + def __setNonDiagonalStructuralMatrices(self): + """ + This method is part of an advanced feature of this solver that allows to set + nondiagonal matrices for the structural modes. + """ + + K_updated = self.__readNonDiagonalMatrix("NDK") + M_updated = self.__readNonDiagonalMatrix("NDM") + C_updated = self.__readNonDiagonalMatrix("NDC") + if K_updated and M_updated and (not C_updated): + print("Setting modal damping") + self.__setNonDiagonalDamping() + elif (not K_updated) and (not M_updated): + print("Modal stiffness and mass matrices are diagonal") + elif (not K_updated) and M_updated: + raise Exception("Non-Diagonal stiffness matrix is missing") + elif (not M_updated) and K_updated: + raise Exception("Non-Diagonal mass matrix is missing") + + def __readNonDiagonalMatrix(self, keyword): + """ + This method reads from the punch file the definition of nondiagonal structural + matrices. + """ + + matrixUpdated = False + + with open(self.Punch_file, "r") as punchfile: + + while 1: + line = punchfile.readline() + if not line: + break - return len(self.markers[markerID]) + pos = line.find(keyword) + if pos != -1: + while 1: + line = punchfile.readline() + line = line.strip("\r\n").split() + if line[0] != "-CONT-": + i = int(line[0]) - 1 + j = 0 + el = line[1:] + ne = len(el) + elif line[0] == "-CONT-": + el = line[1:] + ne = len(el) + if keyword == "NDK": + self.K[i][j : j + ne] = np.array(el) + elif keyword == "NDM": + self.M[i][j : j + ne] = np.array(el) + elif keyword == "NDC": + self.C[i][j : j + ne] = np.array(el) + j = j + ne + if i + 1 == self.nDof and j == self.nDof: + matrixUpdated = True + break + + return matrixUpdated + + def __setNonDiagonalDamping(self): + + D, V = linalg.eig(self.K, self.M) + D = D.real + D = np.sqrt(D) + Mmodal = ((V.transpose()).dot(self.M)).dot(V) + Mmodal = np.diag(Mmodal) + C = 2 * self.ModalDamping * np.multiply(D, Mmodal) + C = np.diag(C) + Vinv = linalg.inv(V) + C = C.dot(Vinv) + VinvT = Vinv.transpose() + self.C = VinvT.dot(C) + + def __setIntegrationParameters(self): + """ + This method uses the time step size to define the integration parameters. + """ + + self.alpha_m = (2.0 * self.rhoAlphaGen - 1.0) / (self.rhoAlphaGen + 1.0) + self.alpha_f = (self.rhoAlphaGen) / (self.rhoAlphaGen + 1.0) + self.gamma = 0.5 + self.alpha_f - self.alpha_m + self.beta = 0.25 * (self.gamma + 0.5) ** 2 + + self.gammaPrime = self.gamma / (self.deltaT * self.beta) + self.betaPrime = (1.0 - self.alpha_m) / ( + (self.deltaT**2) * self.beta * (1.0 - self.alpha_f) + ) + + print("Time integration with the alpha-generalized algorithm.") + print("rho : {}".format(self.rhoAlphaGen)) + print("alpha_m : {}".format(self.alpha_m)) + print("alpha_f : {}".format(self.alpha_f)) + print("gamma : {}".format(self.gamma)) + print("beta : {}".format(self.beta)) + print("gammaPrime : {}".format(self.gammaPrime)) + print("betaPrime : {}".format(self.betaPrime)) + + def __setInitialConditions(self): + """ + This method uses the list of initial modal amplitudes to set the initial conditions + """ + + print("Setting initial conditions.") + + print("Using modal amplitudes from config file") + for imode in range(self.nDof): + if imode in self.Config["INITIAL_MODES"].keys(): + self.q[imode] = float(self.Config["INITIAL_MODES"][imode]) + self.q_n[imode] = float(self.Config["INITIAL_MODES"][imode]) + + RHS = np.zeros((self.nDof, 1)) + RHS += self.F + RHS -= self.C.dot(self.qdot) + RHS -= self.K.dot(self.q) + self.qddot = linalg.solve(self.M, RHS) + self.qddot_n = np.copy(self.qddot) + self.a = np.copy(self.qddot) + self.a_n = np.copy(self.qddot) + + def __reset(self, vector): + """ + This method set to zero any vector. + """ + + for ii in range(vector.shape[0]): + vector[ii] = 0.0 + + def __computeInterfacePosVel(self, initialize): + """ + This method uses the mode shapes to compute, based on the modal velocities, the + nodal velocities at the interface. + """ + + # Multiply the modal matrices with modal amplitudes + X_vel = self.Ux.dot(self.qdot) + Y_vel = self.Uy.dot(self.qdot) + Z_vel = self.Uz.dot(self.qdot) + + X_disp = self.Ux.dot(self.q) + Y_disp = self.Uy.dot(self.q) + Z_disp = self.Uz.dot(self.q) + + for iPoint in range(self.nPoint): + coord0 = self.node[iPoint].GetCoord0() + self.node[iPoint].SetCoord( + ( + X_disp[iPoint] + coord0[0], + Y_disp[iPoint] + coord0[1], + Z_disp[iPoint] + coord0[2], + ) + ) + self.node[iPoint].SetVel((X_vel[iPoint], Y_vel[iPoint], Z_vel[iPoint])) + + if initialize: + self.node[iPoint].SetCoord_n( + ( + X_disp[iPoint] + coord0[0], + Y_disp[iPoint] + coord0[1], + Z_disp[iPoint] + coord0[2], + ) + ) + self.node[iPoint].SetVel_n( + (X_vel[iPoint], Y_vel[iPoint], Z_vel[iPoint]) + ) + + def __setRestart(self): + """ + This method sets all the variables needed for the correct restart. + """ + + # read the Structhistory to obtain the mode amplitudes + nM1Set = False + nSet = False + firstLineRead = False + couplingLineRead = False + + with open("StructHistoryModal.dat", "r") as file: + print("Opened history file StructHistoryModal.dat.") + line = file.readline() + while 1: + line = file.readline() + if not line: + break + line = line.strip("\r\n").split() + + # The old time_0 for imposed motion can either be the first line of the StructHistoryModal, if TimeIterTreshold was -1 (immediate coupling), or the second line. In the former case, time_0 is 0.0, so it is easy to recognize it + if not firstLineRead: + firstLineRead = True + if float(line[0]) == 0.0: + couplingLineRead = True + self.timeStartCoupling = 0.0 + else: + if couplingLineRead: + pass + else: + self.timeStartCoupling = float(line[0]) + couplingLineRead = True + + if int(line[1]) == (self.Config["RESTART_ITER"] - 2): + index = 0 + for index_mode in range(self.nDof): + self.q[index_mode] = float(line[index + 3]) + self.qdot[index_mode] = float(line[index + 4]) + self.qddot[index_mode] = float(line[index + 5]) + index += 3 + del index + # push back the mode amplitudes velocities and accelerations + self.__computeInterfacePosVel(True) + self.q_n = np.copy(self.q) + self.qdot_n = np.copy(self.qdot) + self.qddot_n = np.copy(self.qddot) + self.a_n = np.copy(self.a) + nM1Set = True + if int(line[1]) == (self.Config["RESTART_ITER"] - 1): + index = 0 + for index_mode in range(self.nDof): + self.q[index_mode] = float(line[index + 3]) + self.qdot[index_mode] = float(line[index + 4]) + self.qddot[index_mode] = float(line[index + 5]) + index += 3 + del index + self.__computeInterfacePosVel(False) + nSet = True + break - def getVertexGlobalIndex(self, markerID, iVertex): + if (not nM1Set) or (not nSet): + raise Exception( + "The restart iteration was not found in the structural history" + ) - # This solver is serial, thus global=local - return self.markers[markerID][iVertex] + def __temporalIteration(self, time): + """ + This method integrates in time the solution. + """ - def getInterfaceNodePosInit(self, markerID, iVertex): + self.__reset(self.q) + self.__reset(self.qdot) + self.__reset(self.qddot) + self.__reset(self.a) - iPoint = self.markers[markerID][iVertex] - Coord0 = self.node[iPoint].GetCoord0() - return Coord0 + if not self.ImposedMotion: + eps = 1e-6 - def getInterfaceNodeDisp(self, markerID, iVertex): + self.__SetLoads() - iPoint = self.markers[markerID][iVertex] - Coord = self.node[iPoint].GetCoord() - Coord0 = self.node[iPoint].GetCoord0() - return (Coord-Coord0) + # Prediction step - def getInterfaceNodeVel(self, markerID, iVertex): + self.a += (self.alpha_f) / (1 - self.alpha_m) * self.qddot_n + self.a -= (self.alpha_m) / (1 - self.alpha_m) * self.a_n - iPoint = self.markers[markerID][iVertex] - Vel = self.node[iPoint].GetVel() - return Vel + self.q = np.copy(self.q_n) + self.q += self.deltaT * self.qdot_n + self.q += (0.5 - self.beta) * self.deltaT * self.deltaT * self.a_n + self.q += self.deltaT * self.deltaT * self.beta * self.a - def getInterfaceNodeVelNm1(self, markerID, iVertex): + self.qdot = np.copy(self.qdot_n) + self.qdot += (1 - self.gamma) * self.deltaT * self.a_n + self.qdot += self.deltaT * self.gamma * self.a - iPoint = self.markers[markerID][iVertex] - Vel = self.node[iPoint].GetVel_n() - return Vel + # Correction step + res = self.__ComputeResidual() - def IsAHaloNode(self, markerID, iVertex): + while linalg.norm(res) >= eps: + St = self.__TangentOperator() + Deltaq = -1 * (linalg.solve(St, res)) + self.q += Deltaq + self.qdot += self.gammaPrime * Deltaq + self.qddot += self.betaPrime * Deltaq + res = self.__ComputeResidual() - # There are no halo nodes in this solver as it is serial - iPoint = self.markers[markerID][iVertex] - halo = False - return halo + self.a += (1 - self.alpha_f) / (1 - self.alpha_m) * self.qddot + else: + if self.ImposedMotionToSet: + if self.Config["RESTART_SOL"] == "NO": + # If yes we already set it in the __setRestart function + self.timeStartCoupling = time + iImposedFunc = 0 + for imode in self.Config["IMPOSED_MODES"].keys(): + for isuperposed in range(len(self.Config["IMPOSED_MODES"][imode])): + typeOfMotion = self.Config["IMPOSED_MODES"][imode][isuperposed] + parameters = self.Config["IMPOSED_PARAMETERS"][imode][ + isuperposed + ] + self.ImposedMotionFunction.append( + ImposedMotionClass( + self.timeStartCoupling, typeOfMotion, parameters, imode + ) + ) + iImposedFunc += 1 + self.ImposedMotionToSet = False + for iImposedFunc in range(len(self.ImposedMotionFunction)): + imode = self.ImposedMotionFunction[iImposedFunc].mode + self.q[imode] += self.ImposedMotionFunction[iImposedFunc].GetDispl(time) + self.qdot[imode] += self.ImposedMotionFunction[iImposedFunc].GetVel( + time + ) + self.qddot[imode] += self.ImposedMotionFunction[iImposedFunc].GetAcc( + time + ) + self.a = np.copy(self.qddot) + + def __SetLoads(self): + """ + This method uses the nodal forces and the mode shapes to obtain the modal forces. + """ + nodeList = self.markers[self.FSI_marker] + FX = np.zeros((self.nPoint, 1)) + FY = np.zeros((self.nPoint, 1)) + FZ = np.zeros((self.nPoint, 1)) + for iPoint in nodeList: + Force = self.node[iPoint].GetForce() + FX[iPoint] = float(Force[0]) + FY[iPoint] = float(Force[1]) + FZ[iPoint] = float(Force[2]) + self.F = self.UxT.dot(FX) + self.UyT.dot(FY) + self.UzT.dot(FZ) + + def __ComputeResidual(self): + """ + This method computes the residual for integration. + """ + + res = ( + self.M.dot(self.qddot) + self.C.dot(self.qdot) + self.K.dot(self.q) - self.F + ) + + return res + + def __TangentOperator(self): + """ + This method computes the tangent operator for solution. + """ + + # The problem is linear, so the tangent operator is straightforward. + St = self.betaPrime * self.M + self.gammaPrime * self.C + self.K + + return St + + def exit(self): + """ + This method cleanly exits the structural solver. + """ + + print( + "\n**************** Exiting the structural tester solver ****************" + ) + + def run(self, time): + """ + This method is the main function for advancing the solution of one time step. + """ + self.__temporalIteration(time) + header = "Time\t" + for imode in range(min([self.nDof, 5])): + header = ( + header + + "q" + + str(imode + 1) + + "\t" + + "qdot" + + str(imode + 1) + + "\t" + + "qddot" + + str(imode + 1) + + "\t" + ) + header = header + "\n" + print(header) + line = "{:6.4f}".format(time) + "\t" + for imode in range(min([self.nDof, 5])): + line = ( + line + + "{:6.4f}".format(float(self.q[imode])) + + "\t" + + "{:6.4f}".format(float(self.qdot[imode])) + + "\t" + + "{:6.4f}".format(float(self.qddot[imode])) + + "\t" + ) + line = line + "\n" + print(line) + self.__computeInterfacePosVel(False) + + def activateMode(self, iMode): + """ + This method is used to artificially set only one mode activated, thus + with non zero amplitude. + """ + self.__reset(self.q) + self.q[iMode] = 1.0 + self.__computeInterfacePosVel(True) + + def setInitialDisplacements(self): + """ + This method provides public access to the method __computeInterfacePosVel and + sets velocities for previous time steps. + """ + + self.__computeInterfacePosVel(True) + + def writeSolution(self, time, timeIter, FSIIter): + """ + This method is the main function for output. It writes the file StructHistoryModal.dat + """ + + # Modal History + histFile = open("StructHistoryModal.dat", "a") + line = str(time) + "\t" + str(timeIter) + "\t" + str(FSIIter) + "\t" + for imode in range(self.nDof): + line = ( + line + + str(float(self.q[imode])) + + "\t" + + str(float(self.qdot[imode])) + + "\t" + + str(float(self.qddot[imode])) + + "\t" + ) + line = line + "\n" + histFile.write(line) + histFile.close() + + def updateSolution(self): + """ + This method updates the solution. + """ + + self.q_n = np.copy(self.q) + self.qdot_n = np.copy(self.qdot) + self.qddot_n = np.copy(self.qddot) + self.a_n = np.copy(self.a) + self.__reset(self.q) + self.__reset(self.qdot) + self.__reset(self.qddot) + self.__reset(self.a) + + for iPoint in range(self.nPoint): + self.node[iPoint].updateCoordVel() + + def applyload(self, iVertex, fx, fy, fz): + """ + This method can be accessed from outside to set the nodal forces. + """ + iPoint = self.getVertexGlobalIndex(self.FSI_marker, iVertex) + self.node[iPoint].SetForce((fx, fy, fz)) + + def getNumberOfModes(self): + """ + This method provides the number of degrees of freedom used in + the structural solver. + """ + return self.nDof + + def getFSIMarkerID(self): + """ + This method provides the ID of the interface marker + """ + return self.FSI_marker + + def getNumberOfSolidInterfaceNodes(self, markerID): + + return len(self.markers[markerID]) + + def getVertexGlobalIndex(self, markerID, iVertex): + + # This solver is serial, thus global=local + return self.markers[markerID][iVertex] + + def getInterfaceNodePosInit(self, markerID, iVertex): + + iPoint = self.markers[markerID][iVertex] + Coord0 = self.node[iPoint].GetCoord0() + return Coord0 + + def getInterfaceNodeDisp(self, markerID, iVertex): + + iPoint = self.markers[markerID][iVertex] + Coord = self.node[iPoint].GetCoord() + Coord0 = self.node[iPoint].GetCoord0() + return Coord - Coord0 + + def getInterfaceNodeVel(self, markerID, iVertex): + + iPoint = self.markers[markerID][iVertex] + Vel = self.node[iPoint].GetVel() + return Vel + + def getInterfaceNodeVelNm1(self, markerID, iVertex): + + iPoint = self.markers[markerID][iVertex] + Vel = self.node[iPoint].GetVel_n() + return Vel + + def IsAHaloNode(self, markerID, iVertex): + + # There are no halo nodes in this solver as it is serial + iPoint = self.markers[markerID][iVertex] + halo = False + return halo diff --git a/SU2_PY/change_version_number.py b/SU2_PY/change_version_number.py index e08811e006b..4786a9eedd3 100755 --- a/SU2_PY/change_version_number.py +++ b/SU2_PY/change_version_number.py @@ -28,37 +28,50 @@ # make print(*args) function available in PY2.6+, does'nt work on PY < 2.6 from __future__ import print_function from optparse import OptionParser + # Run the script from the base directory (ie $SU2HOME). Grep will search directories recursively for matches in version number -import os,sys +import os, sys parser = OptionParser() -parser.add_option("-v", "--version", dest="version", - help="the new version number", metavar="VERSION") -parser.add_option("-r", "--releasename", dest="releasename", - help="Name of the new release", metavar="RELEASENAME") -parser.add_option("-y", action="store_true", dest="yes", help="Answer yes to all questions", metavar="YES") -(options, args)=parser.parse_args() +parser.add_option( + "-v", "--version", dest="version", help="the new version number", metavar="VERSION" +) +parser.add_option( + "-r", + "--releasename", + dest="releasename", + help="Name of the new release", + metavar="RELEASENAME", +) +parser.add_option( + "-y", + action="store_true", + dest="yes", + help="Answer yes to all questions", + metavar="YES", +) +(options, args) = parser.parse_args() if not options.version: parser.error("new version number must be provided with -v option") -oldvers = '7.5.1 "Blackbird"' -oldvers_q= r'7.5.1 \"Blackbird\"' -newvers = str(options.version) + ' "' + str(options.releasename) + '"' -newvers_q= str(options.version) + ' \\"' + str(options.releasename) + '\\"' -#oldvers = 'Copyright 2012-2023, SU2' -#oldvers_q = oldvers -#newvers = 'Copyright 2012-2023, SU2' -#newvers_q = newvers +oldvers = '7.5.1 "Blackbird"' +oldvers_q = r"7.5.1 \"Blackbird\"" +newvers = str(options.version) + ' "' + str(options.releasename) + '"' +newvers_q = str(options.version) + ' \\"' + str(options.releasename) + '\\"' +# oldvers = 'Copyright 2012-2023, SU2' +# oldvers_q = oldvers +# newvers = 'Copyright 2012-2023, SU2' +# newvers_q = newvers if sys.version_info[0] > 2: - # In PY3, raw_input is replaced with input. - # For original input behaviour, just write eval(input()) - raw_input = input + # In PY3, raw_input is replaced with input. + # For original input behaviour, just write eval(input()) + raw_input = input -if os.path.exists('version.txt'): - os.remove('version.txt') +if os.path.exists("version.txt"): + os.remove("version.txt") # Grep flag cheatsheet: # -I : Ignore binary files @@ -67,35 +80,41 @@ # -r : search directory recursively # -v : Omit search string (.svn omitted, line containing ISC is CGNS related) -#TODO: replace with portable instructions. This works only on unix systems -os.system("grep -IFwr '%s' *|grep -vF '.svn' |grep -v ISC > version.txt"%oldvers) -os.system("grep -IFwr '%s' --exclude='version.txt' *|grep -vF '.svn' |grep -v ISC >> version.txt"%oldvers_q) +# TODO: replace with portable instructions. This works only on unix systems +os.system("grep -IFwr '%s' *|grep -vF '.svn' |grep -v ISC > version.txt" % oldvers) +os.system( + "grep -IFwr '%s' --exclude='version.txt' *|grep -vF '.svn' |grep -v ISC >> version.txt" + % oldvers_q +) # Create a list of files to adjust filelist = [] -f = open('version.txt','r') +f = open("version.txt", "r") for line in f.readlines(): - candidate = line.split(':')[0] - if not candidate in filelist: - filelist.append(candidate) + candidate = line.split(":")[0] + if not candidate in filelist: + filelist.append(candidate) f.close() print(filelist) # Prompt user before continuing -yorn = '' -while(not yorn.lower()=='y' and not options.yes): - yorn = raw_input('Replace %s with %s and %s with %s in the listed files? [Y/N]: '%(oldvers,newvers, oldvers_q, newvers_q)) - if yorn.lower()=='n': - print('The file version.txt contains matches of oldvers') - sys.exit() +yorn = "" +while not yorn.lower() == "y" and not options.yes: + yorn = raw_input( + "Replace %s with %s and %s with %s in the listed files? [Y/N]: " + % (oldvers, newvers, oldvers_q, newvers_q) + ) + if yorn.lower() == "n": + print("The file version.txt contains matches of oldvers") + sys.exit() # Loop through and correct all files for fname in filelist: - s = open(fname,'r').read() - s_new = s.replace(oldvers,newvers) - s_new = s_new.replace(oldvers_q, newvers_q) - f = open(fname,'w') - f.write(s_new) - f.close() + s = open(fname, "r").read() + s_new = s.replace(oldvers, newvers) + s_new = s_new.replace(oldvers_q, newvers_q) + f = open(fname, "w") + f.write(s_new) + f.close() -os.system('rm -rf version.txt') +os.system("rm -rf version.txt") diff --git a/SU2_PY/compute_multipoint.py b/SU2_PY/compute_multipoint.py index d4e41067a3d..e4641791028 100755 --- a/SU2_PY/compute_multipoint.py +++ b/SU2_PY/compute_multipoint.py @@ -33,17 +33,24 @@ # Command Line Options parser = OptionParser() -parser.add_option("-f", "--file", dest="filename", - help="read config from FILE", metavar="FILE") -parser.add_option("-n", "--partitions", dest="partitions", default=2, - help="number of PARTITIONS", metavar="PARTITIONS") +parser.add_option( + "-f", "--file", dest="filename", help="read config from FILE", metavar="FILE" +) +parser.add_option( + "-n", + "--partitions", + dest="partitions", + default=2, + help="number of PARTITIONS", + metavar="PARTITIONS", +) -(options, args)=parser.parse_args() -options.partitions = int( options.partitions ) +(options, args) = parser.parse_args() +options.partitions = int(options.partitions) # load config, start state config = SU2.io.Config(options.filename) -state = SU2.io.State() +state = SU2.io.State() # prepare config config.NUMBER_PART = options.partitions @@ -52,8 +59,10 @@ state.find_files(config) # run su2 -multipoint_drag = SU2.eval.func('MULTIPOINT_DRAG',config,state) -grad_multipoint_drag= SU2.eval.grad('MULTIPOINT_DRAG','CONTINUOUS_ADJOINT',config,state) +multipoint_drag = SU2.eval.func("MULTIPOINT_DRAG", config, state) +grad_multipoint_drag = SU2.eval.grad( + "MULTIPOINT_DRAG", "CONTINUOUS_ADJOINT", config, state +) -print('MULTIPOINT_DRAG =', multipoint_drag) -print('GRADIENT MULTIPOINT_DRAG =', grad_multipoint_drag) +print("MULTIPOINT_DRAG =", multipoint_drag) +print("GRADIENT MULTIPOINT_DRAG =", grad_multipoint_drag) diff --git a/SU2_PY/compute_polar.py b/SU2_PY/compute_polar.py index af8562caaf7..dd974e37293 100755 --- a/SU2_PY/compute_polar.py +++ b/SU2_PY/compute_polar.py @@ -27,7 +27,7 @@ # # # Several combinations of angles are possible: -#------------------------------------------------ +# ------------------------------------------------ # 1. Polar-sweep in alpha per given phi ...... polarVar = aoa # 2. Polar-sweep in alpha per given beta (side slip angle) ...... polarVar = aoa # 3. Polar-sweep in phi per given alpha ...... polarVar = phi @@ -42,113 +42,197 @@ # imports import os, sys, shutil from optparse import OptionParser -sys.path.append(os.environ['SU2_RUN']) + +sys.path.append(os.environ["SU2_RUN"]) import SU2 import SU2.util.polarSweepLib as psl import copy import numpy as np + def main(): # Command Line Options parser = OptionParser() - parser.add_option("-c", "--ctrl", dest="ctrlFile", - help="reads polar control parameters from FILE (default:polarCtrl.in) ", - metavar="FILE", default="polarCtrl.in") - parser.add_option("-n", "--partitions", dest="partitions", default=2, - help="number of PARTITIONS", metavar="PARTITIONS") - parser.add_option("-i", "--iterations", dest="iterations", default=-1, - help="number of ITERATIONS", metavar="ITERATIONS") - parser.add_option("-d", "--dimension", dest="geomDim", default=2, - help="Geometry dimension (2 or 3)", metavar="geomDim") - parser.add_option("-w", "--Wind", action="store_true", dest="Wind", default=False, - help=" Wind system (default is body system)") - parser.add_option("-v", "--Verbose", action="store_true", dest="verbose", default=False, - help=" Verbose printout (if activated)") + parser.add_option( + "-c", + "--ctrl", + dest="ctrlFile", + help="reads polar control parameters from FILE (default:polarCtrl.in) ", + metavar="FILE", + default="polarCtrl.in", + ) + parser.add_option( + "-n", + "--partitions", + dest="partitions", + default=2, + help="number of PARTITIONS", + metavar="PARTITIONS", + ) + parser.add_option( + "-i", + "--iterations", + dest="iterations", + default=-1, + help="number of ITERATIONS", + metavar="ITERATIONS", + ) + parser.add_option( + "-d", + "--dimension", + dest="geomDim", + default=2, + help="Geometry dimension (2 or 3)", + metavar="geomDim", + ) + parser.add_option( + "-w", + "--Wind", + action="store_true", + dest="Wind", + default=False, + help=" Wind system (default is body system)", + ) + parser.add_option( + "-v", + "--Verbose", + action="store_true", + dest="verbose", + default=False, + help=" Verbose printout (if activated)", + ) (options, args) = parser.parse_args() options.partitions = int(options.partitions) options.iterations = int(options.iterations) options.geomDim = int(options.geomDim) - d2r = np.pi/180 + d2r = np.pi / 180 # sweepOption = [] - sweepOption.append(' Polar sweep type: 1. Sweep in AOA per given roll angle') - sweepOption.append(' Polar sweep type: 2. Sweep in AOA per given sideslip-angle') - sweepOption.append(' Polar sweep type: 3. Sweep in phi per given AOA') - sweepOption.append(' Polar sweep type: 4. Mach ramp (single- value AOA and sideslip-angle') + sweepOption.append(" Polar sweep type: 1. Sweep in AOA per given roll angle") + sweepOption.append(" Polar sweep type: 2. Sweep in AOA per given sideslip-angle") + sweepOption.append(" Polar sweep type: 3. Sweep in phi per given AOA") + sweepOption.append( + " Polar sweep type: 4. Mach ramp (single- value AOA and sideslip-angle" + ) # - #--------------- now read the parameters control file and parse it + # --------------- now read the parameters control file and parse it - fc = open(options.ctrlFile, 'r') + fc = open(options.ctrlFile, "r") ctrl = fc.readlines() nc = np.size(ctrl) fc.close() - print(str(nc)+" lines read from control file: "+options.ctrlFile) - - PA, polarSweepType, velDirOption, nAlpha, nBeta, nPhi, nMach, \ - alpha, beta, phi, MachList, polarVar = \ - psl.setPolaraType(ctrl, nc, options.verbose) + print(str(nc) + " lines read from control file: " + options.ctrlFile) + + ( + PA, + polarSweepType, + velDirOption, + nAlpha, + nBeta, + nPhi, + nMach, + alpha, + beta, + phi, + MachList, + polarVar, + ) = psl.setPolaraType(ctrl, nc, options.verbose) if options.verbose: - velDirOptionLegend = ['V(alpha,phi)', 'V(alpha,beta)'] - print('>>> Control file details: Pitch axis is '+\ - PA+'. Polar sweep type is '+str(polarSweepType)+\ - '; polarVar = '+polarVar) - print('>>> Velocity definiton: '+velDirOptionLegend[velDirOption-1]) - print('>>> nAalpha = '+str(nAlpha)+'; nBeta = '+str(nBeta)+\ - '; nPhi = '+str(nPhi)+'; nMach = '+str(nMach)) + velDirOptionLegend = ["V(alpha,phi)", "V(alpha,beta)"] + print( + ">>> Control file details: Pitch axis is " + + PA + + ". Polar sweep type is " + + str(polarSweepType) + + "; polarVar = " + + polarVar + ) + print(">>> Velocity definiton: " + velDirOptionLegend[velDirOption - 1]) + print( + ">>> nAalpha = " + + str(nAlpha) + + "; nBeta = " + + str(nBeta) + + "; nPhi = " + + str(nPhi) + + "; nMach = " + + str(nMach) + ) if polarSweepType < 4: nPolara = max(nAlpha, nPhi) else: nPolara = nMach - #-------------Configuration base file ---------------------- - inputbaseFileString = 'input base file' + # -------------Configuration base file ---------------------- + inputbaseFileString = "input base file" keyWordInputbaseFile = inputbaseFileString.lower() iBaseInputF = psl.parLocator(keyWordInputbaseFile, ctrl, nc, -1, options.verbose) bIFLine = ctrl[iBaseInputF] - icol = bIFLine.index(':') - sBIF = bIFLine[icol+1:] - inputbaseFile = sBIF.strip(' ') - inputbaseFile = inputbaseFile.strip('\n') - - print(' ') - print('--------------------------------------------------------------------------------------') - print(' ') - print('Configuration file: ' + inputbaseFile) - print('PolarSweepType = '+str(polarSweepType)+' Polar sweep in '+polarVar+' using '+\ - str(nPolara)+' angles/Mach No ') - print(' ') - print('--------------------------------------------------------------------------------------') - print(' ') + icol = bIFLine.index(":") + sBIF = bIFLine[icol + 1 :] + inputbaseFile = sBIF.strip(" ") + inputbaseFile = inputbaseFile.strip("\n") + + print(" ") + print( + "--------------------------------------------------------------------------------------" + ) + print(" ") + print("Configuration file: " + inputbaseFile) + print( + "PolarSweepType = " + + str(polarSweepType) + + " Polar sweep in " + + polarVar + + " using " + + str(nPolara) + + " angles/Mach No " + ) + print(" ") + print( + "--------------------------------------------------------------------------------------" + ) + print(" ") if polarSweepType == 4: - nPolara = 1 # prevent angles inner loop + nPolara = 1 # prevent angles inner loop if options.geomDim not in [2, 3]: - raise SystemExit('ERROR: dimension can be either 2 or 3 (-d parameter) ') + raise SystemExit("ERROR: dimension can be either 2 or 3 (-d parameter) ") if options.Wind: - outSystem = 'Wind' + outSystem = "Wind" else: - outSystem = 'Body' + outSystem = "Body" print(" ") - print("===============================================================================") - print(" Polar sweep in "+str(options.geomDim)+"D ; output in "+outSystem+" system") - print("===============================================================================") + print( + "===============================================================================" + ) + print( + " Polar sweep in " + + str(options.geomDim) + + "D ; output in " + + outSystem + + " system" + ) + print( + "===============================================================================" + ) print(" ") # load config, start state config = SU2.io.Config(inputbaseFile) state = SU2.io.State() # Set SU2 defaults units, if definitions are not included in the cfg file - if 'SYSTEM_MEASUREMENTS' not in config: - config.SYSTEM_MEASUREMENTS = 'SI' - if config.SOLVER == 'NAVIER_STOKES': - if 'REYNOLDS_LENGTH' not in config: + if "SYSTEM_MEASUREMENTS" not in config: + config.SYSTEM_MEASUREMENTS = "SI" + if config.SOLVER == "NAVIER_STOKES": + if "REYNOLDS_LENGTH" not in config: config.REYNOLDS_LENGTH = 1.0 # prepare config @@ -164,14 +248,14 @@ def main(): results = SU2.util.bunch() if nMach == 0: - if 'MACH_NUMBER' in config: + if "MACH_NUMBER" in config: MachList.append(config.MACH_NUMBER) else: MachList.append(0.5) nMach = 1 if nAlpha == 0: - if 'AOA' in config: + if "AOA" in config: alpha.append(config.AOA) else: alpha.append(0.0) @@ -186,30 +270,30 @@ def main(): if nBeta == 0: if noPhi_in_CTRL: - if 'SIDESLIP_ANGLE' in config: + if "SIDESLIP_ANGLE" in config: beta.append(config.SIDESLIP_ANGLE) else: beta.append(0.0) nBeta = 1 else: if polarSweepType < 4: # alpha sweep with phi set - tAlpha = [np.tan(d2r*x) for x in alpha] - tPhi = [np.tan(d2r*x) for x in phi] - tb = [x*y for y in tAlpha for x in tPhi] - beta = [np.arctan(x)/d2r for x in tb] + tAlpha = [np.tan(d2r * x) for x in alpha] + tPhi = [np.tan(d2r * x) for x in phi] + tb = [x * y for y in tAlpha for x in tPhi] + beta = [np.arctan(x) / d2r for x in tb] nBeta = np.size(beta) - else: # Mach ramp - if 'SIDESLIP_ANGLE' in config: + else: # Mach ramp + if "SIDESLIP_ANGLE" in config: beta.append(config.SIDESLIP_ANGLE) else: beta.append(0.0) nBeta = 1 if options.verbose: - print('>>> alpha: '+str(alpha)) - print('>>> beta: '+str(beta)) - print('>>> phi: '+str(phi)) - print('>>> Mach '+str(MachList)) + print(">>> alpha: " + str(alpha)) + print(">>> beta: " + str(beta)) + print(">>> phi: " + str(phi)) + print(">>> Mach " + str(MachList)) results.AOA = alpha results.MACH = MachList @@ -232,96 +316,104 @@ def main(): results.MOMENT_Z = [] if polarSweepType == 4: - outFile = 'machRamp_aoa' + str(alpha[0]) + '.dat' + outFile = "machRamp_aoa" + str(alpha[0]) + ".dat" else: - outFile = 'Polar_M' + str(MachList[0]) + '.dat' + outFile = "Polar_M" + str(MachList[0]) + ".dat" bufsize = 12 # - #----------- Prepare output header --------------- + # ----------- Prepare output header --------------- # - if config.SYSTEM_MEASUREMENTS == 'SI': - length_dimension = 'm' + if config.SYSTEM_MEASUREMENTS == "SI": + length_dimension = "m" else: - length_dimension = 'in' - f = open(outFile, 'w', bufsize) + length_dimension = "in" + f = open(outFile, "w", bufsize) if options.verbose: - print('Opening polar sweep file: ' + outFile) - f.write('% \n% Main coefficients for a polar sweep \n% \n% ') - f.write(sweepOption[polarSweepType-1]) + print("Opening polar sweep file: " + outFile) + f.write("% \n% Main coefficients for a polar sweep \n% \n% ") + f.write(sweepOption[polarSweepType - 1]) if polarSweepType == 1: - satxt = ' ; Roll angle = %7.2f '%(phi[0]) + satxt = " ; Roll angle = %7.2f " % (phi[0]) elif polarSweepType == 2: - satxt = ' ; Sideslip angle = %7.2f '%(beta[0]) + satxt = " ; Sideslip angle = %7.2f " % (beta[0]) elif polarSweepType == 3: - satxt = ' ; AOA = %7.2f '%(alpha[0]) + satxt = " ; AOA = %7.2f " % (alpha[0]) elif polarSweepType == 4: - satxt = ' ; AOA = %7.2f Side slip angle = %7.2f ; '%(alpha[0], beta[0]) + satxt = " ; AOA = %7.2f Side slip angle = %7.2f ; " % (alpha[0], beta[0]) f.write(satxt) - f.write('\n% \n') - f.write('% ================== Reference parameteres ======================\n%\n') + f.write("\n% \n") + f.write("% ================== Reference parameteres ======================\n%\n") XR = config.REF_ORIGIN_MOMENT_X YR = config.REF_ORIGIN_MOMENT_Y ZR = config.REF_ORIGIN_MOMENT_Z - f.write('% Reference point for moments : [ ') - line_text = '%s , %s , %s ] [ %s ] '%(XR, YR, ZR, length_dimension) + f.write("% Reference point for moments : [ ") + line_text = "%s , %s , %s ] [ %s ] " % (XR, YR, ZR, length_dimension) f.write(line_text) - f.write('\n') - f.write('% Reference area and length: ') - line_text = 'Aref : %s Lref : %s [ %s ] '%(config.REF_AREA, config.REF_AREA, length_dimension) + f.write("\n") + f.write("% Reference area and length: ") + line_text = "Aref : %s Lref : %s [ %s ] " % ( + config.REF_AREA, + config.REF_AREA, + length_dimension, + ) f.write(line_text) - f.write('\n% ') - line_text = 'Mach : %7.2f , '%(config.MACH_NUMBER) + f.write("\n% ") + line_text = "Mach : %7.2f , " % (config.MACH_NUMBER) f.write(line_text) - if config.SOLVER == 'NAVIER_STOKES': - line_text = 'Reynolds Number : %s '%(config.REYNOLDS_NUMBER) + if config.SOLVER == "NAVIER_STOKES": + line_text = "Reynolds Number : %s " % (config.REYNOLDS_NUMBER) f.write(line_text) - line_text = 'Reynolds length : %s [ %s ] '%(config.REYNOLDS_LENGTH, length_dimension) + line_text = "Reynolds length : %s [ %s ] " % ( + config.REYNOLDS_LENGTH, + length_dimension, + ) else: - line_text = 'Physical problem : %s '%( config.SOLVER) + line_text = "Physical problem : %s " % (config.SOLVER) f.write(line_text) - f.write('\n% ') - rho = float(config.FREESTREAM_PRESSURE)/\ - (float(config.GAS_CONSTANT)*float(config.FREESTREAM_TEMPERATURE)) - line_text = 'Reference pressure : %s ,'%(config.FREESTREAM_PRESSURE) + f.write("\n% ") + rho = float(config.FREESTREAM_PRESSURE) / ( + float(config.GAS_CONSTANT) * float(config.FREESTREAM_TEMPERATURE) + ) + line_text = "Reference pressure : %s ," % (config.FREESTREAM_PRESSURE) f.write(line_text) - line_text = ' Reference density : %7.4f , '%(rho) + line_text = " Reference density : %7.4f , " % (rho) f.write(line_text) - line_text = ' Reference Temperature : %s '%(config.FREESTREAM_TEMPERATURE) + line_text = " Reference Temperature : %s " % (config.FREESTREAM_TEMPERATURE) f.write(line_text) - f.write('\n% ') - line_text = 'Constant specific heat ratio : %s , '%(config.GAMMA_VALUE) + f.write("\n% ") + line_text = "Constant specific heat ratio : %s , " % (config.GAMMA_VALUE) f.write(line_text) - line_text = 'Gas constant : %s '%(config.GAS_CONSTANT) + line_text = "Gas constant : %s " % (config.GAS_CONSTANT) f.write(line_text) - f.write('\n% ') - line_text = 'Grid file : %s '%(config.MESH_FILENAME) + f.write("\n% ") + line_text = "Grid file : %s " % (config.MESH_FILENAME) f.write(line_text) - f.write('\n% ') + f.write("\n% ") symmmetry_exists = False - if 'MARKER_SYM' in config: - if config.MARKER_SYM != 'NONE': + if "MARKER_SYM" in config: + if config.MARKER_SYM != "NONE": symmmetry_exists = True if symmmetry_exists: - line_text = 'Symmetry surface : yes' + line_text = "Symmetry surface : yes" else: - line_text = 'Symmetry surface : no' + line_text = "Symmetry surface : no" f.write(line_text) - f.write('\n% \n') + f.write("\n% \n") # ----------------- end reference parameter section -------------- if options.Wind: - f.write('% AOA, Mach, CL, CD, ') + f.write("% AOA, Mach, CL, CD, ") if options.geomDim == 3: - f.write('CY, ') + f.write("CY, ") else: if options.geomDim == 2: - f.write('% AOA, Mach, CX, CY, ') + f.write("% AOA, Mach, CX, CY, ") else: - f.write('% AOA, Mach, CX, CZ, CY, ') + f.write("% AOA, Mach, CX, CZ, CY, ") if options.geomDim == 3: - f.write('Cmx, Cmz, Cmy \n') + f.write("Cmx, Cmz, Cmy \n") else: - f.write(' Cmz \n') + f.write(" Cmz \n") firstSweepPoint = True # iterate mach @@ -340,35 +432,39 @@ def main(): SIDESLIP_ANGLE = beta[0] if options.verbose: - print('Sweep step '+str(j)+': Mach = '+str(MachNumber)+\ - ', aoa = ', str(AngleAttack)+', beta = '+str(SIDESLIP_ANGLE)) + print( + "Sweep step " + str(j) + ": Mach = " + str(MachNumber) + ", aoa = ", + str(AngleAttack) + ", beta = " + str(SIDESLIP_ANGLE), + ) # local config and state konfig = copy.deepcopy(config) # enable restart in polar sweep - konfig.DISCARD_INFILES = 'YES' + konfig.DISCARD_INFILES = "YES" ztate = copy.deepcopy(state) # # The eval functions below requires definition of various optimization # variables, though we are handling here only a direct solution. # So, if they are missing in the cfg file (and only then), some dummy values are # introduced here - if 'OBJECTIVE_FUNCTION' not in konfig: - konfig.OBJECTIVE_FUNCTION = 'DRAG' - if 'DV_KIND' not in konfig: - konfig.DV_KIND = ['FFD_SETTING'] - if 'DV_PARAM' not in konfig: - konfig.DV_PARAM = {'FFDTAG': ['1'], 'PARAM': [[0.0, 0.5]], 'SIZE': [1]} - if 'DEFINITION_DV' not in konfig: - konfig.DEFINITION_DV = {'FFDTAG': [[]], - 'KIND': ['HICKS_HENNE'], - 'MARKER': [['WING']], - 'PARAM': [[0.0, 0.05]], - 'SCALE': [1.0], - 'SIZE': [1]} - if 'OPT_OBJECTIVE' not in konfig: + if "OBJECTIVE_FUNCTION" not in konfig: + konfig.OBJECTIVE_FUNCTION = "DRAG" + if "DV_KIND" not in konfig: + konfig.DV_KIND = ["FFD_SETTING"] + if "DV_PARAM" not in konfig: + konfig.DV_PARAM = {"FFDTAG": ["1"], "PARAM": [[0.0, 0.5]], "SIZE": [1]} + if "DEFINITION_DV" not in konfig: + konfig.DEFINITION_DV = { + "FFDTAG": [[]], + "KIND": ["HICKS_HENNE"], + "MARKER": [["WING"]], + "PARAM": [[0.0, 0.05]], + "SCALE": [1.0], + "SIZE": [1], + } + if "OPT_OBJECTIVE" not in konfig: obj = {} - obj['DRAG'] = {'SCALE':1.e-2, 'OBJTYPE':'DEFAULT', 'MARKER': 'None'} + obj["DRAG"] = {"SCALE": 1.0e-2, "OBJTYPE": "DEFAULT", "MARKER": "None"} konfig.OPT_OBJECTIVE = obj # # --------- end of dummy optimization variables definition section --------- @@ -378,42 +474,42 @@ def main(): konfig.AOA = AngleAttack konfig.SIDESLIP_ANGLE = SIDESLIP_ANGLE konfig.MACH_NUMBER = MachNumber - caseName = 'DIRECT_M_' + str(MachNumber) + '_AOA_' + str(AngleAttack) - print('Mach = ', konfig.MACH_NUMBER, 'AOA = ', konfig.AOA) - print('case :' + caseName) + caseName = "DIRECT_M_" + str(MachNumber) + "_AOA_" + str(AngleAttack) + print("Mach = ", konfig.MACH_NUMBER, "AOA = ", konfig.AOA) + print("case :" + caseName) if firstSweepPoint: # if caseName exists copy the restart file from it for run continuation # Continue from previous sweep point if this is not he first if os.path.isdir(caseName): - command = 'cp '+caseName+'/'+config.SOLUTION_FILENAME+' .' + command = "cp " + caseName + "/" + config.SOLUTION_FILENAME + " ." if options.verbose: print(command) - shutil.copy2(caseName+'/'+config.SOLUTION_FILENAME, os.getcwd()) - konfig.RESTART_SOL = 'YES' + shutil.copy2(caseName + "/" + config.SOLUTION_FILENAME, os.getcwd()) + konfig.RESTART_SOL = "YES" else: - konfig.RESTART_SOL = 'NO' + konfig.RESTART_SOL = "NO" firstSweepPoint = False else: - konfig.RESTART_SOL = 'YES' - if konfig.RESTART_SOL == 'YES': + konfig.RESTART_SOL = "YES" + if konfig.RESTART_SOL == "YES": ztate.FILES.DIRECT = config.SOLUTION_FILENAME # run su2 if options.Wind: - drag = SU2.eval.func('DRAG', konfig, ztate) - lift = SU2.eval.func('LIFT', konfig, ztate) + drag = SU2.eval.func("DRAG", konfig, ztate) + lift = SU2.eval.func("LIFT", konfig, ztate) if options.geomDim == 3: - sideforce = SU2.eval.func('SIDEFORCE', konfig, ztate) + sideforce = SU2.eval.func("SIDEFORCE", konfig, ztate) else: - force_x = SU2.eval.func('FORCE_X', konfig, ztate) - force_y = SU2.eval.func('FORCE_Y', konfig, ztate) + force_x = SU2.eval.func("FORCE_X", konfig, ztate) + force_y = SU2.eval.func("FORCE_Y", konfig, ztate) if options.geomDim == 3: - force_z = SU2.eval.func('FORCE_Z', konfig, ztate) + force_z = SU2.eval.func("FORCE_Z", konfig, ztate) - momentz = SU2.eval.func('MOMENT_Z', konfig, ztate) + momentz = SU2.eval.func("MOMENT_Z", konfig, ztate) if options.geomDim == 3: - momentx = SU2.eval.func('MOMENT_X', konfig, ztate) - momenty = SU2.eval.func('MOMENT_Y', konfig, ztate) + momentx = SU2.eval.func("MOMENT_X", konfig, ztate) + momenty = SU2.eval.func("MOMENT_Y", konfig, ztate) # append results @@ -433,64 +529,73 @@ def main(): results.MOMENT_X.append(momentx) results.MOMENT_Y.append(momenty) - output = ' ' + str(AngleAttack) + ", "+str(MachNumber)+", " + output = " " + str(AngleAttack) + ", " + str(MachNumber) + ", " if options.Wind: - output = output+ str(lift) + ", " + str(drag) + output = output + str(lift) + ", " + str(drag) if options.geomDim == 3: - output = output+", "+str(sideforce) + output = output + ", " + str(sideforce) else: if options.geomDim == 2: - output = output+ str(force_x) + ", " + str(force_y) + output = output + str(force_x) + ", " + str(force_y) else: - output = output + str(force_x) + ", " + str(force_z) + ", " + str(force_y) + output = ( + output + + str(force_x) + + ", " + + str(force_z) + + ", " + + str(force_y) + ) if options.geomDim == 3: output = output + ", " + str(momentx) + ", " + str(momentz) + ", " output = output + str(momenty) + " \n" else: - output = output+", "+str(momentz)+" \n" + output = output + ", " + str(momentz) + " \n" f.write(output) # save data - SU2.io.save_data('results.pkl', results) - shutil.copy2('results.pkl', 'DIRECT') - shutil.copy2(config.SOLUTION_FILENAME, 'DIRECT') + SU2.io.save_data("results.pkl", results) + shutil.copy2("results.pkl", "DIRECT") + shutil.copy2(config.SOLUTION_FILENAME, "DIRECT") if os.path.isdir(caseName): - command = 'cat '+caseName+\ - '/history_direct.dat DIRECT/history_direct.dat > tmp && mv tmp '+\ - 'DIRECT/history_direct.dat' + command = ( + "cat " + + caseName + + "/history_direct.dat DIRECT/history_direct.dat > tmp && mv tmp " + + "DIRECT/history_direct.dat" + ) if options.verbose: print(command) os.system(command) shutil.rmtree(caseName) - command = 'cp -p -R DIRECT '+caseName + command = "cp -p -R DIRECT " + caseName if options.verbose: print(command) - shutil.copytree('DIRECT', caseName) + shutil.copytree("DIRECT", caseName) # Close open file f.close() - if os.path.isdir('DIRECT'): - shutil.rmtree('DIRECT') + if os.path.isdir("DIRECT"): + shutil.rmtree("DIRECT") if os.path.isfile(config.SOLUTION_FILENAME): os.remove(config.SOLUTION_FILENAME) - if os.path.isfile('results.pkl'): - os.remove('results.pkl') - print('Post sweep cleanup completed') + if os.path.isfile("results.pkl"): + os.remove("results.pkl") + print("Post sweep cleanup completed") # sys.exit(0) - #----------------------------------------------------------# + # ----------------------------------------------------------# #: for each angle # plotting - #plt.figure() - #plt.plot( results.MACH_NUMBER, results.AOA , results.LIFT , results.DRAG ) - #plt.show() - + # plt.figure() + # plt.plot( results.MACH_NUMBER, results.AOA , results.LIFT , results.DRAG ) + # plt.show() if __name__ == "__main__": diff --git a/SU2_PY/compute_stability.py b/SU2_PY/compute_stability.py index d2284274df0..b727782d7de 100755 --- a/SU2_PY/compute_stability.py +++ b/SU2_PY/compute_stability.py @@ -34,35 +34,50 @@ # Command Line Options parser = OptionParser() -parser.add_option("-f", "--file", dest="filename", - help="read config from FILE", metavar="FILE") -parser.add_option("-n", "--partitions", dest="partitions", default=2, - help="number of PARTITIONS", metavar="PARTITIONS") -parser.add_option("-i", "--iterations", dest="iterations", default=99999, - help="number of ITERATIONS", metavar="ITERATIONS") +parser.add_option( + "-f", "--file", dest="filename", help="read config from FILE", metavar="FILE" +) +parser.add_option( + "-n", + "--partitions", + dest="partitions", + default=2, + help="number of PARTITIONS", + metavar="PARTITIONS", +) +parser.add_option( + "-i", + "--iterations", + dest="iterations", + default=99999, + help="number of ITERATIONS", + metavar="ITERATIONS", +) -(options, args)=parser.parse_args() -options.partitions = int( options.partitions ) -options.iterations = int( options.iterations ) +(options, args) = parser.parse_args() +options.partitions = int(options.partitions) +options.iterations = int(options.iterations) # load config, start state config = SU2.io.Config(options.filename) -state = SU2.io.State() +state = SU2.io.State() # prepare config config.NUMBER_PART = options.partitions -config.EXT_ITER = options.iterations +config.EXT_ITER = options.iterations # find solution files if they exist state.find_files(config) # run su2 -drag_alpha = SU2.eval.func('D_DRAG_D_ALPHA',config,state) -moment_y_alpha= SU2.eval.func('D_MOMENT_Z_D_ALPHA',config,state) +drag_alpha = SU2.eval.func("D_DRAG_D_ALPHA", config, state) +moment_y_alpha = SU2.eval.func("D_MOMENT_Z_D_ALPHA", config, state) -grad_moment_y_alpha= SU2.eval.grad('D_MOMENT_Z_D_ALPHA','CONTINUOUS_ADJOINT',config,state) +grad_moment_y_alpha = SU2.eval.grad( + "D_MOMENT_Z_D_ALPHA", "CONTINUOUS_ADJOINT", config, state +) -print('D_DRAG_D_ALPHA =' , drag_alpha) -print('D_MOMENT_Y_D_ALPHA =' , moment_y_alpha) +print("D_DRAG_D_ALPHA =", drag_alpha) +print("D_MOMENT_Y_D_ALPHA =", moment_y_alpha) -print('DD_MOMENT_Y_D_ALPHA_D_X =', grad_moment_y_alpha) +print("DD_MOMENT_Y_D_ALPHA_D_X =", grad_moment_y_alpha) diff --git a/SU2_PY/compute_uncertainty.py b/SU2_PY/compute_uncertainty.py index 3d2f0905aeb..1184719deef 100755 --- a/SU2_PY/compute_uncertainty.py +++ b/SU2_PY/compute_uncertainty.py @@ -32,57 +32,81 @@ import shutil import copy import os.path -sys.path.append(os.environ['SU2_RUN']) + +sys.path.append(os.environ["SU2_RUN"]) import SU2 + def main(): -# Command Line Options + # Command Line Options parser = OptionParser() - parser.add_option("-f", "--file", dest="filename", - help="read config from FILE", metavar="FILE") - parser.add_option("-n", "--partitions", dest="partitions", default=1, - help="number of PARTITIONS", metavar="PARTITIONS") - parser.add_option("-u", "--underRelaxation", dest="uq_urlx", default=0.1, - help="under relaxation factor", metavar="UQ_URLX") - parser.add_option("-b", "--deltaB", dest="uq_delta_b", default=1.0, - help="magnitude of perturbation", metavar="UQ_DELTA_B") - - (options, args)=parser.parse_args() - options.partitions = int( options.partitions ) + parser.add_option( + "-f", "--file", dest="filename", help="read config from FILE", metavar="FILE" + ) + parser.add_option( + "-n", + "--partitions", + dest="partitions", + default=1, + help="number of PARTITIONS", + metavar="PARTITIONS", + ) + parser.add_option( + "-u", + "--underRelaxation", + dest="uq_urlx", + default=0.1, + help="under relaxation factor", + metavar="UQ_URLX", + ) + parser.add_option( + "-b", + "--deltaB", + dest="uq_delta_b", + default=1.0, + help="magnitude of perturbation", + metavar="UQ_DELTA_B", + ) + + (options, args) = parser.parse_args() + options.partitions = int(options.partitions) # check the typecasting - options.beta_delta = float( options.uq_delta_b ) + options.beta_delta = float(options.uq_delta_b) options.urlx = float(options.uq_urlx) # load config, start state config = SU2.io.Config(options.filename) - state = SU2.io.State() + state = SU2.io.State() # find solution files if they exist state.find_files(config) # prepare config config.NUMBER_PART = options.partitions - config.SST_OPTIONS = 'UQ' + config.SST_OPTIONS = "UQ" config.UQ_DELTA_B = options.beta_delta config.UQ_URLX = options.urlx - config.UQ_PERMUTE = 'NO' - + config.UQ_PERMUTE = "NO" # perform eigenvalue perturbations - for comp in range(1,4): - print('\n\n =================== Performing ' + str(comp) + ' Component Perturbation =================== \n\n') + for comp in range(1, 4): + print( + "\n\n =================== Performing " + + str(comp) + + " Component Perturbation =================== \n\n" + ) # make copies konfig = copy.deepcopy(config) - ztate = copy.deepcopy(state) + ztate = copy.deepcopy(state) # set componentality konfig.UQ_COMPONENT = comp # send output to a folder - folderName = str(comp)+'c/' + folderName = str(comp) + "c/" if os.path.isdir(folderName): - shutil.rmtree(folderName) + shutil.rmtree(folderName) os.mkdir(folderName) sendOutputFiles(konfig, folderName) @@ -95,19 +119,20 @@ def main(): info = SU2.run.merge(konfig) ztate.update(info) - - print('\n\n =================== Performing p1c1 Component Perturbation =================== \n\n') + print( + "\n\n =================== Performing p1c1 Component Perturbation =================== \n\n" + ) # make copies konfig = copy.deepcopy(config) - ztate = copy.deepcopy(state) + ztate = copy.deepcopy(state) # set componentality konfig.UQ_COMPONENT = 1 - konfig.UQ_PERMUTE = 'YES' + konfig.UQ_PERMUTE = "YES" # send output to a folder - folderName = 'p1c1/' + folderName = "p1c1/" if os.path.isdir(folderName): shutil.rmtree(folderName) os.mkdir(folderName) @@ -122,18 +147,20 @@ def main(): info = SU2.run.merge(konfig) state.update(info) - print('\n\n =================== Performing p1c2 Component Perturbation =================== \n\n') + print( + "\n\n =================== Performing p1c2 Component Perturbation =================== \n\n" + ) # make copies konfig = copy.deepcopy(config) - ztate = copy.deepcopy(state) + ztate = copy.deepcopy(state) # set componentality konfig.UQ_COMPONENT = 2 - konfig.UQ_PERMUTE = 'YES' + konfig.UQ_PERMUTE = "YES" # send output to a folder - folderName = 'p1c2/' + folderName = "p1c2/" if os.path.isdir(folderName): shutil.rmtree(folderName) os.mkdir(folderName) @@ -148,9 +175,10 @@ def main(): info = SU2.run.merge(konfig) ztate.update(info) -def sendOutputFiles( config, folderName = ''): + +def sendOutputFiles(config, folderName=""): config.CONV_FILENAME = folderName + config.CONV_FILENAME - #config.BREAKDOWN_FILENAME = folderName + config.BREAKDOWN_FILENAME + # config.BREAKDOWN_FILENAME = folderName + config.BREAKDOWN_FILENAME config.RESTART_FILENAME = folderName + config.RESTART_FILENAME config.VOLUME_FILENAME = folderName + config.VOLUME_FILENAME config.SURFACE_FILENAME = folderName + config.SURFACE_FILENAME diff --git a/SU2_PY/config_gui.py b/SU2_PY/config_gui.py index 3cf13878c7a..293a6c92c9f 100755 --- a/SU2_PY/config_gui.py +++ b/SU2_PY/config_gui.py @@ -38,282 +38,328 @@ # Values of ctrldict are lists (optlist) of lists (option_data) # option_data takes the form [option_name, option_value, StaticText,Control] -class YesNoBox(wx.CheckBox): - '''The regular checkbox returns True or False, this one returns YES or NO to match the SU2 config format.''' - - def __init__(self, parent, *args, **kwargs): - wx.CheckBox.__init__(self, parent, *args, **kwargs) - - def GetValue(self): - if self.Value: - return "YES" - else: - return "NO" - - def SetValue(self,stringval): - if stringval=="YES": - self.Value=True - else: - self.Value=False - -class LabeledComboBox(): - '''Wrap a StaticText and TextCtrl into a single object''' - - def __init__(self,parent,option_name,txtlabel,option_default,option_values,option_type,option_description): - self.label = wx.StaticText(parent,label=txtlabel+", "+option_type) - self.option_name = option_name - self.control = wx.ComboBox(parent,value=option_default,choices=option_values) - self.control.SetSize((400,20)) - self.sizer = wx.BoxSizer(wx.HORIZONTAL) - self.sizer.Add(self.label,wx.EXPAND) - self.sizer.AddSpacer(20) - self.sizer.Add(self.control,wx.EXPAND) - self.sizer.SetMinSize((400,20)) - - self.option_default = option_default - self.option_type = option_type - self.option_description = option_description - - def GetSizer(self): - return self.sizer - - def GetValue(self): - return self.control.GetValue() - - def SetValue(self,val): - self.control.SetValue(val) - def SetDefaultValue(self): - self.control.SetValue(self.option_default) +class YesNoBox(wx.CheckBox): + """The regular checkbox returns True or False, this one returns YES or NO to match the SU2 config format.""" - def GetCtrl(self): - return self.control + def __init__(self, parent, *args, **kwargs): + wx.CheckBox.__init__(self, parent, *args, **kwargs) -class LabeledTextCtrl(): - '''Wrap a StaticText and TextCtrl into a single object''' + def GetValue(self): + if self.Value: + return "YES" + else: + return "NO" - def __init__(self,parent,option_name,txtlabel,option_default,option_type): - self.label = wx.StaticText(parent,label=txtlabel+", "+option_type) - self.option_name = option_name - self.control = wx.TextCtrl(parent,value=option_default) - self.control.SetSize((400,20)) - self.sizer = wx.BoxSizer(wx.HORIZONTAL) - self.sizer.Add(self.label,wx.EXPAND) - self.sizer.AddSpacer(20) - self.sizer.Add(self.control,wx.EXPAND) - self.sizer.SetMinSize((400,20)) + def SetValue(self, stringval): + if stringval == "YES": + self.Value = True + else: + self.Value = False - self.option_default = option_default - self.option_type = option_type - def GetSizer(self): - return self.sizer +class LabeledComboBox: + """Wrap a StaticText and TextCtrl into a single object""" - def GetValue(self): - return self.control.GetValue() + def __init__( + self, + parent, + option_name, + txtlabel, + option_default, + option_values, + option_type, + option_description, + ): + self.label = wx.StaticText(parent, label=txtlabel + ", " + option_type) + self.option_name = option_name + self.control = wx.ComboBox(parent, value=option_default, choices=option_values) + self.control.SetSize((400, 20)) + self.sizer = wx.BoxSizer(wx.HORIZONTAL) + self.sizer.Add(self.label, wx.EXPAND) + self.sizer.AddSpacer(20) + self.sizer.Add(self.control, wx.EXPAND) + self.sizer.SetMinSize((400, 20)) - def SetValue(self,val): - self.control.SetValue(val) + self.option_default = option_default + self.option_type = option_type + self.option_description = option_description - def SetDefaultValue(self): - self.control.SetValue(self.option_default) + def GetSizer(self): + return self.sizer - def GetCtrl(self): - return self.control + def GetValue(self): + return self.control.GetValue() -class config_gui(wx.Frame): - def __init__(self,option_data): + def SetValue(self, val): + self.control.SetValue(val) - # wx Initialization - wx.Frame.__init__(self, None, title="SU2 config file editor") + def SetDefaultValue(self): + self.control.SetValue(self.option_default) - # Define the main sizers - self.frame_sizer = wx.BoxSizer(wx.HORIZONTAL) - self.main_sizer = wx.BoxSizer(wx.HORIZONTAL) - self.left_sizer = wx.BoxSizer(wx.VERTICAL) - self.right_sizer = wx.BoxSizer(wx.VERTICAL) + def GetCtrl(self): + return self.control - # Use a scrolled panel on the right side - self.main_panel = wx.Panel(self) - self.scroll_sizer = wx.BoxSizer(wx.VERTICAL) - self.right_panel = sp.ScrolledPanel(self.main_panel,size=(500,500)) - self.right_panel.SetupScrolling() - # Left side - list of option categories - self.list_ctrl = wx.ListCtrl(self.main_panel,style=wx.LC_REPORT|wx.BORDER_SUNKEN,size=(300,600)) - self.list_ctrl.InsertColumn(0, 'Option Category') +class LabeledTextCtrl: + """Wrap a StaticText and TextCtrl into a single object""" - bigfont = wx.Font(20,wx.MODERN,wx.NORMAL,wx.BOLD) + def __init__(self, parent, option_name, txtlabel, option_default, option_type): + self.label = wx.StaticText(parent, label=txtlabel + ", " + option_type) + self.option_name = option_name + self.control = wx.TextCtrl(parent, value=option_default) + self.control.SetSize((400, 20)) + self.sizer = wx.BoxSizer(wx.HORIZONTAL) + self.sizer.Add(self.label, wx.EXPAND) + self.sizer.AddSpacer(20) + self.sizer.Add(self.control, wx.EXPAND) + self.sizer.SetMinSize((400, 20)) - # Read the option_data and build controls - self.ctrldict = {} - self.optlabels = {} - for j,category in enumerate(option_data): + self.option_default = option_default + self.option_type = option_type - self.list_ctrl.InsertStringItem(j, category) # Add category to left size list + def GetSizer(self): + return self.sizer - self.optlabels[category] = wx.StaticText(self.right_panel,label=category) - self.optlabels[category].SetFont(bigfont) + def GetValue(self): + return self.control.GetValue() - if j>0: - self.scroll_sizer.AddSpacer(20) - self.scroll_sizer.Add(self.optlabels[category],wx.EXPAND) + def SetValue(self, val): + self.control.SetValue(val) - self.ctrldict[category] = [] - yctr = 0 - for j,opt in enumerate(option_data[category]): - if opt.option_type in ["EnumOption","MathProblem","SpecialOption","ConvectOption"]: - self.ctrldict[category].append(LabeledComboBox(self.right_panel,opt.option_name,opt.option_name,opt.option_default,opt.option_values,opt.option_type,opt.option_description)) - else: - self.ctrldict[category].append(LabeledTextCtrl(self.right_panel,opt.option_name,opt.option_name,opt.option_default,opt.option_type)) - - for control in self.ctrldict[category]: - self.scroll_sizer.Add(control.GetSizer(),wx.EXPAND) # Add each control to the sizer - self.lastctrl = control.GetCtrl() - - # Set right_panel to scroll vertically - self.right_panel.SetSizer(self.scroll_sizer) - - # Set up menu - menuBar = wx.MenuBar() - m_file = wx.Menu() - m_save = m_file.Append(wx.ID_SAVE, "&Save", "Save an SU2 .cfg file") - m_open = m_file.Append(wx.ID_OPEN, "&Open", "Load an SU2 .cfg file") - m_exit = m_file.Append(wx.ID_EXIT, "E&xit", "Close window and exit program.") - - menuBar.Append(m_file, "&File") - self.SetMenuBar(menuBar) - self.CreateStatusBar() - - # Specify which functions to call when stuff is changed - self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.list_click, self.list_ctrl) - self.Bind(wx.EVT_MENU, self.OnSave, m_save) - self.Bind(wx.EVT_MENU, self.OnOpen, m_open) - self.Bind(wx.EVT_SIZE, self.OnResize) - self.right_panel.SetAutoLayout(1) - - # Add it all to the panel and draw - self.left_sizer.SetMinSize((300,600)) - self.right_sizer.SetMinSize((300,600)) - self.list_ctrl.SetColumnWidth(0,500) - - self.left_sizer.Add(self.list_ctrl,0,wx.EXPAND) - self.right_sizer.Add(self.right_panel,0,wx.EXPAND) - self.main_sizer.Add(self.left_sizer,0,wx.EXPAND) - self.main_sizer.Add(self.right_sizer,0,wx.EXPAND) - self.frame_sizer.Add(self.main_sizer,0,wx.EXPAND) - - self.main_panel.SetSizer(self.main_sizer) - self.SetSizer(self.frame_sizer) - self.SetInitialSize() - - def OnCheck(self,event): - print(event) - print(dir(event)) - print(event.GetEventObject()) - print(event.GetEventObject().GetValue()) - - def OnResize(self,event): - # There is surely a better way to do this.... - framesize = self.GetSize() - self.main_panel.SetSize(framesize) - self.list_ctrl.SetSize((300,framesize[1]-50)) - self.right_panel.SetSize((framesize[0]-300,framesize[1]-50)) - - - def OnSave(self,event): - - # Dialog to set output filename - SaveDialog = wx.FileDialog(self,style=wx.FD_SAVE,wildcard='*.cfg') - SaveDialog.ShowModal() - outfile = SaveDialog.GetPath() - - f = open(outfile,'w') - - for category,optlist in self.ctrldict.items(): - f.write('%% %s \n'%category) - for option in optlist: - value = option.GetValue() - if not value=="": - f.write('%s=%s\n'%(option.option_name,option.GetValue())) - f.close() - - def OnOpen(self,event): - - # Dialog to select file - OpenDialog = wx.FileDialog(self,wildcard='*.cfg') - OpenDialog.ShowModal() - infile = OpenDialog.GetPath() - - # Open file, Load values into a dictionary - cfgfile = open(infile,'r') - infiledict = {} - lines = cfgfile.readlines() - for line in lines: - if (line[0]=='%' or line.find('=')==-1): # Skip lines w/o = sign - continue - else: # Get value - key,val=[text.strip() for text in line.split('=')] - key = key.upper() # AoA should work as well as AOA - infiledict[key] = val - - # Loop through controls and set them to the new values - for category,optlist in self.ctrldict.items(): - for option in optlist: - if option.option_name in infiledict: - option.SetValue(infiledict[option.option_name]) - else: - option.SetValue("") - - def OnClose(self,event): - sys.exit(1) + def SetDefaultValue(self): + self.control.SetValue(self.option_default) - def OnAbout(self,event): - print("OnAbout") + def GetCtrl(self): + return self.control - def list_click(self, event): - category = event.GetText() - - self.right_panel.ScrollChildIntoView(self.lastctrl) - self.right_panel.ScrollChildIntoView(self.optlabels[category]) +class config_gui(wx.Frame): + def __init__(self, option_data): + + # wx Initialization + wx.Frame.__init__(self, None, title="SU2 config file editor") + + # Define the main sizers + self.frame_sizer = wx.BoxSizer(wx.HORIZONTAL) + self.main_sizer = wx.BoxSizer(wx.HORIZONTAL) + self.left_sizer = wx.BoxSizer(wx.VERTICAL) + self.right_sizer = wx.BoxSizer(wx.VERTICAL) + + # Use a scrolled panel on the right side + self.main_panel = wx.Panel(self) + self.scroll_sizer = wx.BoxSizer(wx.VERTICAL) + self.right_panel = sp.ScrolledPanel(self.main_panel, size=(500, 500)) + self.right_panel.SetupScrolling() + + # Left side - list of option categories + self.list_ctrl = wx.ListCtrl( + self.main_panel, style=wx.LC_REPORT | wx.BORDER_SUNKEN, size=(300, 600) + ) + self.list_ctrl.InsertColumn(0, "Option Category") + + bigfont = wx.Font(20, wx.MODERN, wx.NORMAL, wx.BOLD) + + # Read the option_data and build controls + self.ctrldict = {} + self.optlabels = {} + for j, category in enumerate(option_data): + + self.list_ctrl.InsertStringItem( + j, category + ) # Add category to left size list + + self.optlabels[category] = wx.StaticText(self.right_panel, label=category) + self.optlabels[category].SetFont(bigfont) + + if j > 0: + self.scroll_sizer.AddSpacer(20) + self.scroll_sizer.Add(self.optlabels[category], wx.EXPAND) + + self.ctrldict[category] = [] + yctr = 0 + for j, opt in enumerate(option_data[category]): + if opt.option_type in [ + "EnumOption", + "MathProblem", + "SpecialOption", + "ConvectOption", + ]: + self.ctrldict[category].append( + LabeledComboBox( + self.right_panel, + opt.option_name, + opt.option_name, + opt.option_default, + opt.option_values, + opt.option_type, + opt.option_description, + ) + ) + else: + self.ctrldict[category].append( + LabeledTextCtrl( + self.right_panel, + opt.option_name, + opt.option_name, + opt.option_default, + opt.option_type, + ) + ) + + for control in self.ctrldict[category]: + self.scroll_sizer.Add( + control.GetSizer(), wx.EXPAND + ) # Add each control to the sizer + self.lastctrl = control.GetCtrl() + + # Set right_panel to scroll vertically + self.right_panel.SetSizer(self.scroll_sizer) + + # Set up menu + menuBar = wx.MenuBar() + m_file = wx.Menu() + m_save = m_file.Append(wx.ID_SAVE, "&Save", "Save an SU2 .cfg file") + m_open = m_file.Append(wx.ID_OPEN, "&Open", "Load an SU2 .cfg file") + m_exit = m_file.Append(wx.ID_EXIT, "E&xit", "Close window and exit program.") + + menuBar.Append(m_file, "&File") + self.SetMenuBar(menuBar) + self.CreateStatusBar() + + # Specify which functions to call when stuff is changed + self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.list_click, self.list_ctrl) + self.Bind(wx.EVT_MENU, self.OnSave, m_save) + self.Bind(wx.EVT_MENU, self.OnOpen, m_open) + self.Bind(wx.EVT_SIZE, self.OnResize) + self.right_panel.SetAutoLayout(1) + + # Add it all to the panel and draw + self.left_sizer.SetMinSize((300, 600)) + self.right_sizer.SetMinSize((300, 600)) + self.list_ctrl.SetColumnWidth(0, 500) + + self.left_sizer.Add(self.list_ctrl, 0, wx.EXPAND) + self.right_sizer.Add(self.right_panel, 0, wx.EXPAND) + self.main_sizer.Add(self.left_sizer, 0, wx.EXPAND) + self.main_sizer.Add(self.right_sizer, 0, wx.EXPAND) + self.frame_sizer.Add(self.main_sizer, 0, wx.EXPAND) + + self.main_panel.SetSizer(self.main_sizer) + self.SetSizer(self.frame_sizer) + self.SetInitialSize() + + def OnCheck(self, event): + print(event) + print(dir(event)) + print(event.GetEventObject()) + print(event.GetEventObject().GetValue()) + + def OnResize(self, event): + # There is surely a better way to do this.... + framesize = self.GetSize() + self.main_panel.SetSize(framesize) + self.list_ctrl.SetSize((300, framesize[1] - 50)) + self.right_panel.SetSize((framesize[0] - 300, framesize[1] - 50)) + + def OnSave(self, event): + + # Dialog to set output filename + SaveDialog = wx.FileDialog(self, style=wx.FD_SAVE, wildcard="*.cfg") + SaveDialog.ShowModal() + outfile = SaveDialog.GetPath() + + f = open(outfile, "w") + + for category, optlist in self.ctrldict.items(): + f.write("%% %s \n" % category) + for option in optlist: + value = option.GetValue() + if not value == "": + f.write("%s=%s\n" % (option.option_name, option.GetValue())) + f.close() + + def OnOpen(self, event): + + # Dialog to select file + OpenDialog = wx.FileDialog(self, wildcard="*.cfg") + OpenDialog.ShowModal() + infile = OpenDialog.GetPath() + + # Open file, Load values into a dictionary + cfgfile = open(infile, "r") + infiledict = {} + lines = cfgfile.readlines() + for line in lines: + if line[0] == "%" or line.find("=") == -1: # Skip lines w/o = sign + continue + else: # Get value + key, val = [text.strip() for text in line.split("=")] + key = key.upper() # AoA should work as well as AOA + infiledict[key] = val + + # Loop through controls and set them to the new values + for category, optlist in self.ctrldict.items(): + for option in optlist: + if option.option_name in infiledict: + option.SetValue(infiledict[option.option_name]) + else: + option.SetValue("") + + def OnClose(self, event): + sys.exit(1) + + def OnAbout(self, event): + print("OnAbout") + + def list_click(self, event): + + category = event.GetText() + + self.right_panel.ScrollChildIntoView(self.lastctrl) + self.right_panel.ScrollChildIntoView(self.optlabels[category]) def prepare_data(): - """ Method to get configuration data from source files. - Outputs a dictionary of categories as keys and lists of config_options as values - """ - - # These variables should point to the configuration files - su2_basedir = os.environ['SU2_HOME'] - config_cpp = os.path.join(su2_basedir,'Common/src/config_structure.cpp') - config_hpp = os.path.join(su2_basedir,'Common/include/option_structure.hpp') - - # Check that files exist - if not os.path.isfile(config_cpp): - sys.exit('Could not find cpp file, please check that su2_basedir is set correctly in config_gui.py') - if not os.path.isfile(config_hpp): - sys.exit('Could not find hpp file, please check that su2_basedir is set correctly in config_gui.py') - - # Run the parser - option_list = parse_config(config_cpp, config_hpp) - - # Organize data into dictionary with categories as keys - option_data = {} - for opt in option_list: - if not opt.option_category in option_data: - option_data[opt.option_category] = [] - option_data[opt.option_category].append(opt) - - return option_data - -if __name__=="__main__": - - # Read source files, get option data - option_data = prepare_data() - - # Launch GUI - app = wx.App(None) - frame = config_gui(option_data) - frame.Show() - app.MainLoop() + """Method to get configuration data from source files. + Outputs a dictionary of categories as keys and lists of config_options as values + """ + + # These variables should point to the configuration files + su2_basedir = os.environ["SU2_HOME"] + config_cpp = os.path.join(su2_basedir, "Common/src/config_structure.cpp") + config_hpp = os.path.join(su2_basedir, "Common/include/option_structure.hpp") + + # Check that files exist + if not os.path.isfile(config_cpp): + sys.exit( + "Could not find cpp file, please check that su2_basedir is set correctly in config_gui.py" + ) + if not os.path.isfile(config_hpp): + sys.exit( + "Could not find hpp file, please check that su2_basedir is set correctly in config_gui.py" + ) + + # Run the parser + option_list = parse_config(config_cpp, config_hpp) + + # Organize data into dictionary with categories as keys + option_data = {} + for opt in option_list: + if not opt.option_category in option_data: + option_data[opt.option_category] = [] + option_data[opt.option_category].append(opt) + + return option_data + + +if __name__ == "__main__": + + # Read source files, get option data + option_data = prepare_data() + + # Launch GUI + app = wx.App(None) + frame = config_gui(option_data) + frame.Show() + app.MainLoop() diff --git a/SU2_PY/continuous_adjoint.py b/SU2_PY/continuous_adjoint.py index 071f4b9a4ea..bf3358cbe8f 100755 --- a/SU2_PY/continuous_adjoint.py +++ b/SU2_PY/continuous_adjoint.py @@ -27,39 +27,69 @@ import os, sys from optparse import OptionParser -sys.path.append(os.environ['SU2_RUN']) + +sys.path.append(os.environ["SU2_RUN"]) import SU2 # ------------------------------------------------------------------- # Main # ------------------------------------------------------------------- + def main(): # Command Line Options - parser=OptionParser() - parser.add_option("-f", "--file", dest="filename", - help="read config from FILE", metavar="FILE") - parser.add_option("-n", "--partitions", dest="partitions", default=1, - help="number of PARTITIONS", metavar="PARTITIONS") - parser.add_option("-c", "--compute", dest="compute", default="True", - help="COMPUTE direct and adjoint problem", metavar="COMPUTE") - parser.add_option("-s", "--step", dest="step", default=1E-4, - help="DOT finite difference STEP", metavar="STEP") - parser.add_option("-z", "--zones", dest="nzones", default="1", - help="Number of Zones", metavar="ZONES") - - (options, args)=parser.parse_args() - options.partitions = int( options.partitions ) - options.step = float( options.step ) - options.compute = options.compute.upper() == 'TRUE' - options.nzones = int( options.nzones ) - - continuous_adjoint( options.filename , - options.partitions , - options.compute , - options.step , - options.nzones ) + parser = OptionParser() + parser.add_option( + "-f", "--file", dest="filename", help="read config from FILE", metavar="FILE" + ) + parser.add_option( + "-n", + "--partitions", + dest="partitions", + default=1, + help="number of PARTITIONS", + metavar="PARTITIONS", + ) + parser.add_option( + "-c", + "--compute", + dest="compute", + default="True", + help="COMPUTE direct and adjoint problem", + metavar="COMPUTE", + ) + parser.add_option( + "-s", + "--step", + dest="step", + default=1e-4, + help="DOT finite difference STEP", + metavar="STEP", + ) + parser.add_option( + "-z", + "--zones", + dest="nzones", + default="1", + help="Number of Zones", + metavar="ZONES", + ) + + (options, args) = parser.parse_args() + options.partitions = int(options.partitions) + options.step = float(options.step) + options.compute = options.compute.upper() == "TRUE" + options.nzones = int(options.nzones) + + continuous_adjoint( + options.filename, + options.partitions, + options.compute, + options.step, + options.nzones, + ) + #: def main() @@ -68,31 +98,28 @@ def main(): # Continuous Adjoint # ------------------------------------------------------------------- -def continuous_adjoint( filename , - partitions = 0 , - compute = True , - step = 1e-4 , - nzones = 1 ): + +def continuous_adjoint(filename, partitions=0, compute=True, step=1e-4, nzones=1): # Config config = SU2.io.Config(filename) config.NUMBER_PART = partitions - config.NZONES = int( nzones ) + config.NZONES = int(nzones) # State state = SU2.io.State() # Force CSV output in order to compute gradients - if not 'OUTPUT_FILES' in config: - config['OUTPUT_FILES'] = ['RESTART'] + if not "OUTPUT_FILES" in config: + config["OUTPUT_FILES"] = ["RESTART"] - if not 'SURFACE_CSV' in config['OUTPUT_FILES']: - config['OUTPUT_FILES'].append('SURFACE_CSV') + if not "SURFACE_CSV" in config["OUTPUT_FILES"]: + config["OUTPUT_FILES"].append("SURFACE_CSV") # check for existing files if not compute: - config.RESTART_SOL = 'YES' + config.RESTART_SOL = "YES" state.find_files(config) else: state.FILES.MESH = config.MESH_FILENAME @@ -101,7 +128,7 @@ def continuous_adjoint( filename , if compute: info = SU2.run.direct(config) state.update(info) - SU2.io.restart2solution(config,state) + SU2.io.restart2solution(config, state) # Adjoint Solution @@ -109,21 +136,20 @@ def continuous_adjoint( filename , if compute: info = SU2.run.adjoint(config) state.update(info) - info = SU2.run.projection(config,state, step) + info = SU2.run.projection(config, state, step) state.update(info) return state + #: continuous_adjoint() # ------------------------------------------------------------------- # Alternate Forumulation # ------------------------------------------------------------------- -def continuous_design( filename , - partitions = 0 , - compute = True , - step = 1e-4 ): + +def continuous_design(filename, partitions=0, compute=True, step=1e-4): # TODO: # step @@ -144,7 +170,7 @@ def continuous_design( filename , state.FILES.MESH = config.MESH_FILENAME # Adjoint Gradient - grads = SU2.eval.grad( ADJ_NAME, 'CONTINUOUS_ADJOINT', config, state ) + grads = SU2.eval.grad(ADJ_NAME, "CONTINUOUS_ADJOINT", config, state) return state @@ -154,6 +180,5 @@ def continuous_design( filename , # ------------------------------------------------------------------- # this is only accessed if running from command prompt -if __name__ == '__main__': +if __name__ == "__main__": main() - diff --git a/SU2_PY/convert_to_csv.py b/SU2_PY/convert_to_csv.py index c3811b6627e..32b13cace83 100755 --- a/SU2_PY/convert_to_csv.py +++ b/SU2_PY/convert_to_csv.py @@ -28,17 +28,24 @@ from optparse import OptionParser import os -parser = OptionParser(usage = "%prog -i INPUT_FILE", - description = 'This script converts SU2 ASCII restart files generated with a version prior v7 to the CSV format') -parser.add_option("-i", "--inputfile", dest="infile", - help="ASCII restart file (*.dat)", metavar="INPUT_FILE") -(options, args)=parser.parse_args() +parser = OptionParser( + usage="%prog -i INPUT_FILE", + description="This script converts SU2 ASCII restart files generated with a version prior v7 to the CSV format", +) +parser.add_option( + "-i", + "--inputfile", + dest="infile", + help="ASCII restart file (*.dat)", + metavar="INPUT_FILE", +) +(options, args) = parser.parse_args() infile = open(options.infile, "r") -out_name = options.infile.split('.')[0] + ".csv" -if (os.path.isfile(out_name)): - print('File ' + out_name + ' already exists.') +out_name = options.infile.split(".")[0] + ".csv" +if os.path.isfile(out_name): + print("File " + out_name + " already exists.") exit(1) outfile = open(out_name, "w") @@ -50,8 +57,8 @@ line = line.split() for i, val in enumerate(line): outfile.write(val.strip()) - if i != len(line)-1: - outfile.write(', ') - outfile.write('\n') + if i != len(line) - 1: + outfile.write(", ") + outfile.write("\n") -print('Converted ' + options.infile + ' to ' + out_name) +print("Converted " + options.infile + " to " + out_name) diff --git a/SU2_PY/direct_differentiation.py b/SU2_PY/direct_differentiation.py index c885a58eaec..d81eef0f83a 100755 --- a/SU2_PY/direct_differentiation.py +++ b/SU2_PY/direct_differentiation.py @@ -28,34 +28,56 @@ from __future__ import division, print_function, absolute_import import os, sys, shutil from optparse import OptionParser -sys.path.append(os.environ['SU2_RUN']) + +sys.path.append(os.environ["SU2_RUN"]) import SU2 # ------------------------------------------------------------------- # Main # ------------------------------------------------------------------- + def main(): parser = OptionParser() - parser.add_option("-f", "--file", dest="filename", - help="read config from FILE", metavar="FILE") - parser.add_option("-n", "--partitions", dest="partitions", default=1, - help="number of PARTITIONS", metavar="PARTITIONS") - parser.add_option("-q", "--quiet", dest="quiet", default='False', - help="output QUIET to log files", metavar="QUIET") - parser.add_option("-z", "--zones", dest="nzones", default="1", - help="Number of Zones", metavar="ZONES") - - (options, args)=parser.parse_args() - options.partitions = int( options.partitions ) - options.quiet = options.quiet.upper() == 'TRUE' - options.nzones = int( options.nzones ) - - direct_differentiation( options.filename , - options.partitions , - options.quiet , - options.nzones ) + parser.add_option( + "-f", "--file", dest="filename", help="read config from FILE", metavar="FILE" + ) + parser.add_option( + "-n", + "--partitions", + dest="partitions", + default=1, + help="number of PARTITIONS", + metavar="PARTITIONS", + ) + parser.add_option( + "-q", + "--quiet", + dest="quiet", + default="False", + help="output QUIET to log files", + metavar="QUIET", + ) + parser.add_option( + "-z", + "--zones", + dest="nzones", + default="1", + help="Number of Zones", + metavar="ZONES", + ) + + (options, args) = parser.parse_args() + options.partitions = int(options.partitions) + options.quiet = options.quiet.upper() == "TRUE" + options.nzones = int(options.nzones) + + direct_differentiation( + options.filename, options.partitions, options.quiet, options.nzones + ) + + #: def main() @@ -63,18 +85,16 @@ def main(): # Direct Differentation Function # ------------------------------------------------------------------- -def direct_differentiation( filename , - partitions = 0 , - quiet = False , - nzones = 1 ): + +def direct_differentiation(filename, partitions=0, quiet=False, nzones=1): # Config config = SU2.io.Config(filename) config.NUMBER_PART = partitions - config.NZONES = int(nzones) - config["DIRECT_DIFF"] = 'DESIGN_VARIABLES' + config.NZONES = int(nzones) + config["DIRECT_DIFF"] = "DESIGN_VARIABLES" if quiet: - config.CONSOLE = 'CONCISE' + config.CONSOLE = "CONCISE" # State state = SU2.io.State() @@ -82,44 +102,59 @@ def direct_differentiation( filename , foundDerivativeField = False for fields in SU2.io.historyOutFields: - group = SU2.io.historyOutFields[fields]['GROUP'] + group = SU2.io.historyOutFields[fields]["GROUP"] if group in config.HISTORY_OUTPUT: - if SU2.io.historyOutFields[fields]['TYPE'] == 'D_COEFFICIENT': + if SU2.io.historyOutFields[fields]["TYPE"] == "D_COEFFICIENT": foundDerivativeField = True if not foundDerivativeField: - sys.exit('No derivative field found in HISTORY_OUTPUT') + sys.exit("No derivative field found in HISTORY_OUTPUT") # link restart files to subfolder DIRECTDIFF, if restart solution is selected - if config.get('TIME_DOMAIN', 'NO') == 'YES' and config.get('RESTART_SOL', 'NO') == 'YES': + if ( + config.get("TIME_DOMAIN", "NO") == "YES" + and config.get("RESTART_SOL", "NO") == "YES" + ): # check if directory DIRECTDIFF/DIRECT exists, if not, create - if not os.path.isdir('DIRECTDIFF/DIRECT'): - if not os.path.isdir('DIRECTDIFF'): - os.mkdir('DIRECTDIFF') - os.mkdir('DIRECTDIFF/DIRECT') - - restart_name = config['RESTART_FILENAME'].split('.')[0] - restart_filename = restart_name + '_' + str(int(config['RESTART_ITER']) - 1).zfill(5) + '.dat' - if not os.path.isfile('DIRECTDIFF/DIRECT/' + restart_filename): - #throw, if restart file does not exist + if not os.path.isdir("DIRECTDIFF/DIRECT"): + if not os.path.isdir("DIRECTDIFF"): + os.mkdir("DIRECTDIFF") + os.mkdir("DIRECTDIFF/DIRECT") + + restart_name = config["RESTART_FILENAME"].split(".")[0] + restart_filename = ( + restart_name + "_" + str(int(config["RESTART_ITER"]) - 1).zfill(5) + ".dat" + ) + if not os.path.isfile("DIRECTDIFF/DIRECT/" + restart_filename): + # throw, if restart file does not exist if not os.path.isfile(restart_filename): - sys.exit("Error: Restart file <" + restart_filename + "> not found." ) - shutil.copyfile(restart_filename, 'DIRECTDIFF/DIRECT/' + restart_filename) + sys.exit("Error: Restart file <" + restart_filename + "> not found.") + shutil.copyfile(restart_filename, "DIRECTDIFF/DIRECT/" + restart_filename) # use only, if time integration is second order - if config.get('TIME_MARCHING', 'NO') == 'DUAL_TIME_STEPPING-2ND_ORDER': - restart_filename = restart_name + '_' + str(int(config['RESTART_ITER']) - 2).zfill(5) + '.dat' - if not os.path.isfile('DIRECTDIFF/DIRECT/' + restart_filename): + if config.get("TIME_MARCHING", "NO") == "DUAL_TIME_STEPPING-2ND_ORDER": + restart_filename = ( + restart_name + + "_" + + str(int(config["RESTART_ITER"]) - 2).zfill(5) + + ".dat" + ) + if not os.path.isfile("DIRECTDIFF/DIRECT/" + restart_filename): # throw, if restart file does not exist if not os.path.isfile(restart_filename): - sys.exit("Error: Restart file <" + restart_filename + "> not found.") - shutil.copyfile(restart_filename, 'DIRECTDIFF/DIRECT/' + restart_filename) + sys.exit( + "Error: Restart file <" + restart_filename + "> not found." + ) + shutil.copyfile( + restart_filename, "DIRECTDIFF/DIRECT/" + restart_filename + ) # Direct Differentiation Gradients - SU2.eval.gradients.directdiff(config,state) + SU2.eval.gradients.directdiff(config, state) return state + #: finite_differences() @@ -128,5 +163,5 @@ def direct_differentiation( filename , # ------------------------------------------------------------------- # this is only accessed if running from command prompt -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/SU2_PY/discrete_adjoint.py b/SU2_PY/discrete_adjoint.py index 816e3a1d68c..8afb09b2555 100755 --- a/SU2_PY/discrete_adjoint.py +++ b/SU2_PY/discrete_adjoint.py @@ -27,44 +27,76 @@ import os, sys, copy from optparse import OptionParser -sys.path.append(os.environ['SU2_RUN']) + +sys.path.append(os.environ["SU2_RUN"]) import SU2 # ------------------------------------------------------------------- # Main # ------------------------------------------------------------------- + def main(): # Command Line Options - parser=OptionParser() - parser.add_option("-f", "--file", dest="filename", - help="read config from FILE", metavar="FILE") - parser.add_option("-n", "--partitions", dest="partitions", default=1, - help="number of PARTITIONS", metavar="PARTITIONS") - parser.add_option("-s", "--step", dest="step", default=1E-4, - help="DOT finite difference STEP", metavar="STEP") - parser.add_option("-v", "--validate", dest="validate", default="False", - help="Validate the gradient using direct diff. mode", metavar="VALIDATION") - parser.add_option("-z", "--zones", dest="nzones", default="1", - help="Number of Zones", metavar="ZONES") - parser.add_option("-m", "--mode", dest="mode", default="all", - help="Determine the calculation mode \n : compute primal & adjoint problem & gradient (DEFAULT) \n : compute adjoint (with primal restart) & gradient \n : compute gradient (with primal and adjoint restarts)", metavar="MODE") - - (options, args)=parser.parse_args() - options.partitions = int( options.partitions ) - options.step = float( options.step ) - options.validate = options.validate.upper() == 'TRUE' - options.nzones = int( options.nzones ) + parser = OptionParser() + parser.add_option( + "-f", "--file", dest="filename", help="read config from FILE", metavar="FILE" + ) + parser.add_option( + "-n", + "--partitions", + dest="partitions", + default=1, + help="number of PARTITIONS", + metavar="PARTITIONS", + ) + parser.add_option( + "-s", + "--step", + dest="step", + default=1e-4, + help="DOT finite difference STEP", + metavar="STEP", + ) + parser.add_option( + "-v", + "--validate", + dest="validate", + default="False", + help="Validate the gradient using direct diff. mode", + metavar="VALIDATION", + ) + parser.add_option( + "-z", + "--zones", + dest="nzones", + default="1", + help="Number of Zones", + metavar="ZONES", + ) + parser.add_option( + "-m", + "--mode", + dest="mode", + default="all", + help="Determine the calculation mode \n : compute primal & adjoint problem & gradient (DEFAULT) \n : compute adjoint (with primal restart) & gradient \n : compute gradient (with primal and adjoint restarts)", + metavar="MODE", + ) + + (options, args) = parser.parse_args() + options.partitions = int(options.partitions) + options.step = float(options.step) + options.validate = options.validate.upper() == "TRUE" + options.nzones = int(options.nzones) if options.mode != "all" and options.mode != "adj" and options.mode != "grad": - sys.exit('Infeasible input for --mode. Use --help for more information') + sys.exit("Infeasible input for --mode. Use --help for more information") + + discrete_adjoint( + options.filename, options.partitions, options.step, options.nzones, options.mode + ) - discrete_adjoint( options.filename , - options.partitions , - options.step , - options.nzones , - options.mode) #: def main() @@ -73,24 +105,21 @@ def main(): # Discrete Adjoint # ------------------------------------------------------------------- -def discrete_adjoint( filename , - partitions = 0 , - step = 1e-4 , - nzones = 1, - mode = "all"): + +def discrete_adjoint(filename, partitions=0, step=1e-4, nzones=1, mode="all"): # Config config = SU2.io.Config(filename) config.NUMBER_PART = partitions - config.NZONES = int( nzones ) + config.NZONES = int(nzones) # State state = SU2.io.State() - config['GRADIENT_METHOD'] = 'DISCRETE_ADJOINT' + config["GRADIENT_METHOD"] = "DISCRETE_ADJOINT" # check for existing files if mode == "grad": - config.RESTART_SOL = 'YES' + config.RESTART_SOL = "YES" state.find_files(config) else: state.FILES.MESH = config.MESH_FILENAME @@ -105,48 +134,54 @@ def discrete_adjoint( filename , # Update konfig konfig = copy.deepcopy(config) - if konfig.get('WINDOW_CAUCHY_CRIT', 'NO') == 'YES' and konfig.TIME_MARCHING != 'NO': - konfig['TIME_ITER'] = info.WND_CAUCHY_DATA['TIME_ITER'] - konfig['ITER_AVERAGE_OBJ'] = info.WND_CAUCHY_DATA['ITER_AVERAGE_OBJ'] - konfig['UNST_ADJOINT_ITER'] = info.WND_CAUCHY_DATA['UNST_ADJOINT_ITER'] + if ( + konfig.get("WINDOW_CAUCHY_CRIT", "NO") == "YES" + and konfig.TIME_MARCHING != "NO" + ): + konfig["TIME_ITER"] = info.WND_CAUCHY_DATA["TIME_ITER"] + konfig["ITER_AVERAGE_OBJ"] = info.WND_CAUCHY_DATA["ITER_AVERAGE_OBJ"] + konfig["UNST_ADJOINT_ITER"] = info.WND_CAUCHY_DATA["UNST_ADJOINT_ITER"] - SU2.io.restart2solution(konfig,state) + SU2.io.restart2solution(konfig, state) # Adjoint Solution # Run all-at-once if mode == "all" or mode == "adj": restart_sol_activated = False - if konfig.get('TIME_DOMAIN','NO') == 'YES' and konfig.get('RESTART_SOL','NO') == 'YES': + if ( + konfig.get("TIME_DOMAIN", "NO") == "YES" + and konfig.get("RESTART_SOL", "NO") == "YES" + ): restart_sol_activated = True - original_time_iter = konfig['TIME_ITER'] - konfig['TIME_ITER'] = konfig['TIME_ITER'] - int(konfig['RESTART_ITER']) - konfig.RESTART_SOL = 'NO' + original_time_iter = konfig["TIME_ITER"] + konfig["TIME_ITER"] = konfig["TIME_ITER"] - int(konfig["RESTART_ITER"]) + konfig.RESTART_SOL = "NO" info = SU2.run.adjoint(konfig) state.update(info) # Workaround, since expandTime relies on UNST_ADJOINT_ITER to determine number of solution files. if restart_sol_activated: - konfig['UNST_ADJOINT_ITER'] = original_time_iter - int(konfig['RESTART_ITER']) - SU2.io.restart2solution(konfig,state) + konfig["UNST_ADJOINT_ITER"] = original_time_iter - int( + konfig["RESTART_ITER"] + ) + SU2.io.restart2solution(konfig, state) # reset changed time-iter values for the remaining program to original values # Gradient Projection - info = SU2.run.projection(konfig,step) + info = SU2.run.projection(konfig, step) state.update(info) return state + #: continuous_adjoint() # ------------------------------------------------------------------- # Alternate Formulation # ------------------------------------------------------------------- -def discrete_design( filename , - partitions = 0 , - compute = True , - step = 1e-4 , - validation = False): + +def discrete_design(filename, partitions=0, compute=True, step=1e-4, validation=False): # TODO: # step @@ -155,7 +190,7 @@ def discrete_design( filename , config = SU2.io.Config(filename) config.NUMBER_PART = partitions - config['GRADIENT_METHOD'] = 'DISCRETE_ADJOINT' + config["GRADIENT_METHOD"] = "DISCRETE_ADJOINT" ADJ_NAME = config.OBJECTIVE_FUNCTION @@ -166,49 +201,45 @@ def discrete_design( filename , grads_directdiff = [] -# if validation: -# state_directdiff.find_files(config) -# konfig = copy.deepcopy(config) -# konfig['DIRECT_DIFF'] = "DESIGN_VARIABLES" -# grad_directdiff = SU2.eval.gradients.directdiff(konfig,state_directdiff) -# state['FILES']['DIRECT'] = 'DIRECTDIFF/' + state_directdiff['FILES']['DIRECT'] -# state['FUNCTIONS'] = state_directdiff['FUNCTIONS'] + # if validation: + # state_directdiff.find_files(config) + # konfig = copy.deepcopy(config) + # konfig['DIRECT_DIFF'] = "DESIGN_VARIABLES" + # grad_directdiff = SU2.eval.gradients.directdiff(konfig,state_directdiff) + # state['FILES']['DIRECT'] = 'DIRECTDIFF/' + state_directdiff['FILES']['DIRECT'] + # state['FUNCTIONS'] = state_directdiff['FUNCTIONS'] # check for existing files - if any([not compute, validation]) : + if any([not compute, validation]): state.find_files(config) else: state.FILES.MESH = config.MESH_FILENAME # Adjoint Gradient - grads = SU2.eval.grad( ADJ_NAME, config['GRADIENT_METHOD'], config, state ) - -# if validation: -# Definition_DV = config['DEFINITION_DV'] -# n_dv = len(Definition_DV['KIND']) -# grads_dd = grad_directdiff[ADJ_NAME] -# print("Validation Summary") -# print("--------------------------") -# print("VARIABLE " + "DISCRETE ADJOINT" + " DIRECT DIFFERENTIATION" + " ERROR (%)") -# for idv in range(n_dv): -# if abs(grads[idv]) > abs(grads_dd[idv]): -# this_err = abs(grads[idv]/grads_dd[idv]) -# else: -# this_err = abs(grads_dd[idv]/grads[idv]) - -# print(str(idv) + " " + str(grads[idv]) + " " + str(grads_dd[idv]) + " " + str((this_err-1)*100) + ' %') - + grads = SU2.eval.grad(ADJ_NAME, config["GRADIENT_METHOD"], config, state) + + # if validation: + # Definition_DV = config['DEFINITION_DV'] + # n_dv = len(Definition_DV['KIND']) + # grads_dd = grad_directdiff[ADJ_NAME] + # print("Validation Summary") + # print("--------------------------") + # print("VARIABLE " + "DISCRETE ADJOINT" + " DIRECT DIFFERENTIATION" + " ERROR (%)") + # for idv in range(n_dv): + # if abs(grads[idv]) > abs(grads_dd[idv]): + # this_err = abs(grads[idv]/grads_dd[idv]) + # else: + # this_err = abs(grads_dd[idv]/grads[idv]) + + # print(str(idv) + " " + str(grads[idv]) + " " + str(grads_dd[idv]) + " " + str((this_err-1)*100) + ' %') return state - - # ------------------------------------------------------------------- # Run Main Program # ------------------------------------------------------------------- # this is only accessed if running from command prompt -if __name__ == '__main__': +if __name__ == "__main__": main() - diff --git a/SU2_PY/documentation.txt b/SU2_PY/documentation.txt index 70cb6ba69e5..d4ef8e157fb 100644 --- a/SU2_PY/documentation.txt +++ b/SU2_PY/documentation.txt @@ -1,4 +1,4 @@ -goals - +goals - cascading levels of functionality lower levels stand on their own, and provide usefulness to higher levels when asked @@ -43,7 +43,7 @@ SU2.run.deform(config,dv_new=[]) pointer updated config 'MESH_FILENAME' = 'MESH_FILENAME'+'_deform' 'DV_VALUE_OLD' = 'DV_VALUE_NEW' - + SU2.run.direct(config) checks decomp ensures config: @@ -56,12 +56,12 @@ SU2.run.direct(config) 'FUNCTIONS' - dict of function:value 'HISTORY' - dict of col_header:iteration history 'FILES' - dict of useful file names - + SU2.run.adjoint(config) checks decomp ensures config: 'MATH_PROBLEM' = 'CONTINUOUS_ADJOINT' - 'CONV_FILENAME' = 'CONFIG_FILENAME' + '_adjoint' + 'CONV_FILENAME' = 'CONFIG_FILENAME' + '_adjoint' run CFD read history does not move restart to solution @@ -69,7 +69,7 @@ SU2.run.adjoint(config) returns dictionary 'info' with keys: 'HISTORY' - dict of col_header:iteration history 'FILES' - dict of useful file names - + SU2.run.projection(config,step=1e-4) assumes linear superposition of design variables checks decomp @@ -85,7 +85,7 @@ SU2.run.projection(config,step=1e-4) level2 - objective and gradient analysis, redundancy protection upstream pointer update of config and state config - controls SU2 -state - stores design information +state - stores design information STATE FILES @@ -107,7 +107,7 @@ STATE LIFT DRAG MOMENT_Z - + SU2.eval.functions.function() aliased to SU2.eval.func() runs the aerodynamics and geometry control functions @@ -121,11 +121,11 @@ SU2.eval.functions.aerodynamics() direct solution evaluates each step in its own folder, returning state.FILES to the super folder updates config and state by pointer - + SU2.eval.functions.geometry() todo ... - + SU2.eval.gradients.gradient() aliased to SU2.eval.grad() @@ -136,17 +136,17 @@ SU2.eval.gradients.adjoint() adjoint solution evaluates each step in its own folder, returning state.FILES to the super folder updates config and state by pointer - - + + SU2.eval.gradients.findiff() runs with redundancy protection (using state): functions() decom, deform, direct finite difference evaluation of functions() - finite difference steps performed in the FINDIFF folder, removed when completed + finite difference steps performed in the FINDIFF folder, removed when completed updates config and state by pointer - + level3 - design management major assumption - one design, one config, one state start a new design if a new config is needed @@ -167,8 +167,8 @@ SU2.eval.design(config,state,folder) con_dceq() equality constraint derivatives con_cieq() inequality constraints con_dcieq() inequality constraint gradients - - + + level4 - project managent SU2.opt.project(config,state,folder) runs multiple design classes, again avoiding redundancy @@ -179,7 +179,7 @@ SU2.opt.project(config,state,folder) level5 - optimization SU2.opt.scipy_slsqp(project) sets up and runs a scipy slsqp optimization - + FILE IO level0 - in/out/mod @@ -192,14 +192,14 @@ class SU2.io.config(dict) config.unpack_dvs(dv_new.dv_old) config.__diff__(konfig) config.__eq__(konfig) - + config.read_history() config.read_aerodynamics() config.rename_restart() - + SU2.io.read_history( name ) SU2.io.read_aerodynamics( hist_name, special_cases ) - + level1 - files translate,modify,plotting SU2.io.add_suffix(name,suffix) @@ -207,15 +207,3 @@ SU2.io.resurrect_restart(config,state) SU2.io.plot.adjoint_gradient(config,grad_dict) SU2.io.plot.findiff_gradient(config,grad_dict) - - - - - - - - - - - - diff --git a/SU2_PY/finite_differences.py b/SU2_PY/finite_differences.py index 6777d50e068..d6684b3706b 100755 --- a/SU2_PY/finite_differences.py +++ b/SU2_PY/finite_differences.py @@ -27,34 +27,56 @@ import os, sys from optparse import OptionParser -sys.path.append(os.environ['SU2_RUN']) + +sys.path.append(os.environ["SU2_RUN"]) import SU2 # ------------------------------------------------------------------- # Main # ------------------------------------------------------------------- + def main(): parser = OptionParser() - parser.add_option("-f", "--file", dest="filename", - help="read config from FILE", metavar="FILE") - parser.add_option("-n", "--partitions", dest="partitions", default=1, - help="number of PARTITIONS", metavar="PARTITIONS") - parser.add_option("-q", "--quiet", dest="quiet", default='False', - help="output QUIET to log files", metavar="QUIET") - parser.add_option("-z", "--zones", dest="nzones", default="1", - help="Number of Zones", metavar="ZONES") - - (options, args)=parser.parse_args() - options.partitions = int( options.partitions ) - options.quiet = options.quiet.upper() == 'TRUE' - options.nzones = int( options.nzones ) - - finite_differences( options.filename , - options.partitions , - options.quiet , - options.nzones ) + parser.add_option( + "-f", "--file", dest="filename", help="read config from FILE", metavar="FILE" + ) + parser.add_option( + "-n", + "--partitions", + dest="partitions", + default=1, + help="number of PARTITIONS", + metavar="PARTITIONS", + ) + parser.add_option( + "-q", + "--quiet", + dest="quiet", + default="False", + help="output QUIET to log files", + metavar="QUIET", + ) + parser.add_option( + "-z", + "--zones", + dest="nzones", + default="1", + help="Number of Zones", + metavar="ZONES", + ) + + (options, args) = parser.parse_args() + options.partitions = int(options.partitions) + options.quiet = options.quiet.upper() == "TRUE" + options.nzones = int(options.nzones) + + finite_differences( + options.filename, options.partitions, options.quiet, options.nzones + ) + + #: def main() @@ -62,42 +84,55 @@ def main(): # Finite Differences Function # ------------------------------------------------------------------- -def finite_differences( filename , - partitions = 0 , - quiet = False , - nzones = 1 ): + +def finite_differences(filename, partitions=0, quiet=False, nzones=1): # Config config = SU2.io.Config(filename) config.NUMBER_PART = partitions - config.NZONES = int( nzones ) + config.NZONES = int(nzones) if quiet: - config.CONSOLE = 'CONCISE' + config.CONSOLE = "CONCISE" # State state = SU2.io.State() state.find_files(config) # add restart files to state.FILES - if config.get('TIME_DOMAIN', 'NO') == 'YES' and config.get('RESTART_SOL', 'NO') == 'YES': - restart_name = config['RESTART_FILENAME'].split('.')[0] - restart_filename = restart_name + '_' + str(int(config['RESTART_ITER'])-1).zfill(5) + '.dat' - if not os.path.isfile(restart_filename): # throw, if restart files does not exist + if ( + config.get("TIME_DOMAIN", "NO") == "YES" + and config.get("RESTART_SOL", "NO") == "YES" + ): + restart_name = config["RESTART_FILENAME"].split(".")[0] + restart_filename = ( + restart_name + "_" + str(int(config["RESTART_ITER"]) - 1).zfill(5) + ".dat" + ) + if not os.path.isfile( + restart_filename + ): # throw, if restart files does not exist sys.exit("Error: Restart file <" + restart_filename + "> not found.") - state['FILES']['RESTART_FILE_1'] = restart_filename + state["FILES"]["RESTART_FILE_1"] = restart_filename # use only, if time integration is second order - if config.get('TIME_MARCHING', 'NO') == 'DUAL_TIME_STEPPING-2ND_ORDER': - restart_filename = restart_name + '_' + str(int(config['RESTART_ITER'])-2).zfill(5) + '.dat' - if not os.path.isfile(restart_filename): # throw, if restart files does not exist + if config.get("TIME_MARCHING", "NO") == "DUAL_TIME_STEPPING-2ND_ORDER": + restart_filename = ( + restart_name + + "_" + + str(int(config["RESTART_ITER"]) - 2).zfill(5) + + ".dat" + ) + if not os.path.isfile( + restart_filename + ): # throw, if restart files does not exist sys.exit("Error: Restart file <" + restart_filename + "> not found.") - state['FILES']['RESTART_FILE_2'] =restart_filename + state["FILES"]["RESTART_FILE_2"] = restart_filename # Finite Difference Gradients - SU2.eval.gradients.findiff(config,state) + SU2.eval.gradients.findiff(config, state) return state + #: finite_differences() @@ -106,5 +141,5 @@ def finite_differences( filename , # ------------------------------------------------------------------- # this is only accessed if running from command prompt -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/SU2_PY/fsi_computation.py b/SU2_PY/fsi_computation.py index 0735485a18f..4e644b49b24 100644 --- a/SU2_PY/fsi_computation.py +++ b/SU2_PY/fsi_computation.py @@ -34,194 +34,226 @@ import shutil import copy import time as timer -from math import * # use mathematical expressions -from optparse import OptionParser # use a parser for configuration +from math import * # use mathematical expressions +from optparse import OptionParser # use a parser for configuration # imports the CFD (SU2) module for FSI computation import pysu2 -import FSI_tools as FSI # imports FSI python tools +import FSI_tools as FSI # imports FSI python tools # ------------------------------------------------------------------- # Main # ------------------------------------------------------------------- + def main(): - # --- Get the FSI conig file name form the command line options --- # - parser=OptionParser() - parser.add_option("-f", "--file", dest="filename", - help="read config from FILE", metavar="FILE") - parser.add_option("--parallel", action="store_true", - help="Specify if we need to initialize MPI", dest="with_MPI", default=False) - - (options, args)=parser.parse_args() - - if options.with_MPI: - from mpi4py import MPI # MPI is initialized from now by python and can be continued in C++ - comm = MPI.COMM_WORLD - myid = comm.Get_rank() - numberPart = comm.Get_size() - have_MPI = True - else: - comm = 0 - myid = 0 - numberPart = 1 - have_MPI = False - - rootProcess = 0 - - # --- Set the working directory --- # - if myid == rootProcess: - if os.getcwd() not in sys.path: - sys.path.append(os.getcwd()) - print("Setting working directory : {}".format(os.getcwd())) - else: - print("Working directory is set to {}".format(os.getcwd())) - - if have_MPI: - comm.barrier() - - # starts timer - start = timer.time() - - confFile = str(options.filename) - - FSI_config = FSI.FSIConfig(confFile, comm) # FSI configuration file - CFD_ConFile = FSI_config['CFD_CONFIG_FILE_NAME'] # CFD configuration file - CSD_ConFile = FSI_config['CSD_CONFIG_FILE_NAME'] # CSD configuration file - - CSD_Solver = FSI_config['CSD_SOLVER'] # CSD solver - - if have_MPI: - comm.barrier() - - # --- Initialize the fluid solver --- # - if myid == rootProcess: - print("\n") - print(" Initializing fluid solver ".center(80,"*")) - try: - FluidSolver = pysu2.CSinglezoneDriver(CFD_ConFile, 1, comm) - except TypeError as exception: - print('A TypeError occured in pysu2.CSinglezoneDriver : ',exception) - if have_MPI: - print('ERROR : You are trying to initialize MPI with a serial build of the wrapper. Please, remove the --parallel option that is incompatible with a serial build.') + # --- Get the FSI conig file name form the command line options --- # + parser = OptionParser() + parser.add_option( + "-f", "--file", dest="filename", help="read config from FILE", metavar="FILE" + ) + parser.add_option( + "--parallel", + action="store_true", + help="Specify if we need to initialize MPI", + dest="with_MPI", + default=False, + ) + + (options, args) = parser.parse_args() + + if options.with_MPI: + from mpi4py import ( + MPI, + ) # MPI is initialized from now by python and can be continued in C++ + + comm = MPI.COMM_WORLD + myid = comm.Get_rank() + numberPart = comm.Get_size() + have_MPI = True else: - print('ERROR : You are trying to launch a computation without initializing MPI but the wrapper has been built in parallel. Please add the --parallel option in order to initialize MPI for the wrapper.') - return + comm = 0 + myid = 0 + numberPart = 1 + have_MPI = False - if have_MPI: - comm.barrier() + rootProcess = 0 - # --- Initialize the solid solver --- # - # Serial solvers - if CSD_Solver in ["NATIVE"]: + # --- Set the working directory --- # if myid == rootProcess: - print("\n") - print(" Initializing solid solver ".center(80,"*")) - if CSD_Solver == 'NATIVE': - from SU2_Nastran import pysu2_nastran - if FSI_config["IMPOSED_MOTION"] == "NO": - SolidSolver = pysu2_nastran.Solver(CSD_ConFile,False) + if os.getcwd() not in sys.path: + sys.path.append(os.getcwd()) + print("Setting working directory : {}".format(os.getcwd())) else: - SolidSolver = pysu2_nastran.Solver(CSD_ConFile,True) - else: - SolidSolver = None - # Parallel solvers - # For now we are only using serial solvers - else: - raise Exception('\n Invalid solid solver option') - - if have_MPI: - comm.barrier() - - # --- Initialize and set the FSI interface (coupling environement) --- # - if myid == rootProcess: - print("\n") - print(" Initializing FSI interface ".center(80,"*")) - if have_MPI: - comm.barrier() - FSIInterface = FSI.Interface(FSI_config, FluidSolver, SolidSolver, have_MPI) - - if myid == rootProcess: - print("\n") - print(" Connect fluid and solid solvers ".center(80,"*")) - if have_MPI: - comm.barrier() - FSIInterface.connect(FSI_config, FluidSolver, SolidSolver) - - if myid == rootProcess: - print("\n") - print(" Mapping fluid-solid interfaces ".center(80,"*")) - if have_MPI: - comm.barrier() - FSIInterface.interfaceMapping(FluidSolver, SolidSolver, FSI_config) - - if have_MPI: - comm.barrier() - - if FSI_config["MAPPING_MODES"] == "NO": - # --- Launch a steady or unsteady FSI computation --- # - if FSI_config['TIME_MARCHING'] == "YES": - try: - FSIInterface.UnsteadyFSI(FSI_config, FluidSolver, SolidSolver) - except NameError as exception: - if myid == rootProcess: - print('An NameError occured in FSIInterface.UnsteadyFSI : ',exception) - except TypeError as exception: - if myid == rootProcess: - print('A TypeError occured in FSIInterface.UnsteadyFSI : ',exception) - except KeyboardInterrupt as exception : - if myid == rootProcess: - print('A KeyboardInterrupt occured in FSIInterface.UnsteadyFSI : ',exception) - else: - try: - FSIInterface.SteadyFSI(FSI_config, FluidSolver, SolidSolver) - except NameError as exception: - if myid == rootProcess: - print('An NameError occured in FSIInterface.SteadyFSI : ',exception) - except TypeError as exception: - if myid == rootProcess: - print('A TypeError occured in FSIInterface.SteadyFSI : ',exception) - except KeyboardInterrupt as exception : - if myid == rootProcess: - print('A KeyboardInterrupt occured in FSIInterface.SteadyFSI : ',exception) - else: + print("Working directory is set to {}".format(os.getcwd())) + + if have_MPI: + comm.barrier() + + # starts timer + start = timer.time() + + confFile = str(options.filename) + + FSI_config = FSI.FSIConfig(confFile, comm) # FSI configuration file + CFD_ConFile = FSI_config["CFD_CONFIG_FILE_NAME"] # CFD configuration file + CSD_ConFile = FSI_config["CSD_CONFIG_FILE_NAME"] # CSD configuration file + + CSD_Solver = FSI_config["CSD_SOLVER"] # CSD solver + + if have_MPI: + comm.barrier() + + # --- Initialize the fluid solver --- # + if myid == rootProcess: + print("\n") + print(" Initializing fluid solver ".center(80, "*")) try: - FSIInterface.MapModes(FSI_config, FluidSolver, SolidSolver) - except NameError as exception: - if myid == rootProcess: - print('An NameError occured in FSIInterface.MapModes : ',exception) + FluidSolver = pysu2.CSinglezoneDriver(CFD_ConFile, 1, comm) except TypeError as exception: - if myid == rootProcess: - print('A TypeError occured in FSIInterface.MapModes : ',exception) - except KeyboardInterrupt as exception : - if myid == rootProcess: - print('A KeyboardInterrupt occured in FSIInterface.MapModes : ',exception) + print("A TypeError occured in pysu2.CSinglezoneDriver : ", exception) + if have_MPI: + print( + "ERROR : You are trying to initialize MPI with a serial build of the wrapper. Please, remove the --parallel option that is incompatible with a serial build." + ) + else: + print( + "ERROR : You are trying to launch a computation without initializing MPI but the wrapper has been built in parallel. Please add the --parallel option in order to initialize MPI for the wrapper." + ) + return - if have_MPI: - comm.barrier() + if have_MPI: + comm.barrier() - # --- Exit cleanly the fluid and solid solvers --- # - FluidSolver.Postprocessing() - if myid == rootProcess: - SolidSolver.exit() + # --- Initialize the solid solver --- # + # Serial solvers + if CSD_Solver in ["NATIVE"]: + if myid == rootProcess: + print("\n") + print(" Initializing solid solver ".center(80, "*")) + if CSD_Solver == "NATIVE": + from SU2_Nastran import pysu2_nastran + + if FSI_config["IMPOSED_MOTION"] == "NO": + SolidSolver = pysu2_nastran.Solver(CSD_ConFile, False) + else: + SolidSolver = pysu2_nastran.Solver(CSD_ConFile, True) + else: + SolidSolver = None + # Parallel solvers + # For now we are only using serial solvers + else: + raise Exception("\n Invalid solid solver option") + + if have_MPI: + comm.barrier() + + # --- Initialize and set the FSI interface (coupling environement) --- # + if myid == rootProcess: + print("\n") + print(" Initializing FSI interface ".center(80, "*")) + if have_MPI: + comm.barrier() + FSIInterface = FSI.Interface(FSI_config, FluidSolver, SolidSolver, have_MPI) + + if myid == rootProcess: + print("\n") + print(" Connect fluid and solid solvers ".center(80, "*")) + if have_MPI: + comm.barrier() + FSIInterface.connect(FSI_config, FluidSolver, SolidSolver) + + if myid == rootProcess: + print("\n") + print(" Mapping fluid-solid interfaces ".center(80, "*")) + if have_MPI: + comm.barrier() + FSIInterface.interfaceMapping(FluidSolver, SolidSolver, FSI_config) - if have_MPI: - comm.barrier() + if have_MPI: + comm.barrier() + + if FSI_config["MAPPING_MODES"] == "NO": + # --- Launch a steady or unsteady FSI computation --- # + if FSI_config["TIME_MARCHING"] == "YES": + try: + FSIInterface.UnsteadyFSI(FSI_config, FluidSolver, SolidSolver) + except NameError as exception: + if myid == rootProcess: + print( + "An NameError occured in FSIInterface.UnsteadyFSI : ", exception + ) + except TypeError as exception: + if myid == rootProcess: + print( + "A TypeError occured in FSIInterface.UnsteadyFSI : ", exception + ) + except KeyboardInterrupt as exception: + if myid == rootProcess: + print( + "A KeyboardInterrupt occured in FSIInterface.UnsteadyFSI : ", + exception, + ) + else: + try: + FSIInterface.SteadyFSI(FSI_config, FluidSolver, SolidSolver) + except NameError as exception: + if myid == rootProcess: + print( + "An NameError occured in FSIInterface.SteadyFSI : ", exception + ) + except TypeError as exception: + if myid == rootProcess: + print("A TypeError occured in FSIInterface.SteadyFSI : ", exception) + except KeyboardInterrupt as exception: + if myid == rootProcess: + print( + "A KeyboardInterrupt occured in FSIInterface.SteadyFSI : ", + exception, + ) + else: + try: + FSIInterface.MapModes(FSI_config, FluidSolver, SolidSolver) + except NameError as exception: + if myid == rootProcess: + print("An NameError occured in FSIInterface.MapModes : ", exception) + except TypeError as exception: + if myid == rootProcess: + print("A TypeError occured in FSIInterface.MapModes : ", exception) + except KeyboardInterrupt as exception: + if myid == rootProcess: + print( + "A KeyboardInterrupt occured in FSIInterface.MapModes : ", exception + ) + + if have_MPI: + comm.barrier() + + # --- Exit cleanly the fluid and solid solvers --- # + FluidSolver.Postprocessing() + if myid == rootProcess: + SolidSolver.exit() + + if have_MPI: + comm.barrier() - # stops timer - stop = timer.time() - elapsedTime = stop-start + # stops timer + stop = timer.time() + elapsedTime = stop - start - if myid == rootProcess: - print("\n Computation successfully performed in {} seconds.".format(elapsedTime)) + if myid == rootProcess: + print( + "\n Computation successfully performed in {} seconds.".format(elapsedTime) + ) + + return - return # ------------------------------------------------------------------- # Run Main Program # ------------------------------------------------------------------- # --- This is only accessed if running from command prompt --- # -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/SU2_PY/merge_solution.py b/SU2_PY/merge_solution.py index e7a0c3954e5..87f7ae06f1b 100755 --- a/SU2_PY/merge_solution.py +++ b/SU2_PY/merge_solution.py @@ -32,36 +32,44 @@ # Main # ------------------------------------------------------------------- + def main(): parser = OptionParser() - parser.add_option("-f", "--file", dest="filename", - help="read config from FILE", metavar="FILE") - parser.add_option("-n", "--partitions", dest="partitions", default=-1, - help="number of PARTITIONS", metavar="PARTITIONS") + parser.add_option( + "-f", "--file", dest="filename", help="read config from FILE", metavar="FILE" + ) + parser.add_option( + "-n", + "--partitions", + dest="partitions", + default=-1, + help="number of PARTITIONS", + metavar="PARTITIONS", + ) - (options, args)=parser.parse_args() + (options, args) = parser.parse_args() options.partitions = int(options.partitions) - merge_solution( options.filename , - options.partitions ) + merge_solution(options.filename, options.partitions) # ------------------------------------------------------------------- # MERGE SOLUTION # ------------------------------------------------------------------- -def merge_solution( filename , - partitions = -1 ): + +def merge_solution(filename, partitions=-1): config = SU2.io.Config(filename) - if partitions > -1 : + if partitions > -1: config.NUMBER_PART = partitions SU2.run.merge(config) + #: def merge_solution() -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/SU2_PY/mesh_deformation.py b/SU2_PY/mesh_deformation.py index 37eecb19544..b77b0269d0c 100755 --- a/SU2_PY/mesh_deformation.py +++ b/SU2_PY/mesh_deformation.py @@ -27,28 +27,38 @@ import os, sys from optparse import OptionParser -sys.path.append(os.environ['SU2_RUN']) + +sys.path.append(os.environ["SU2_RUN"]) import SU2 # ------------------------------------------------------------------- # Main # ------------------------------------------------------------------- + def main(): # Command Line Options parser = OptionParser() - parser.add_option("-f", "--file", dest="filename", - help="read config from FILE", metavar="FILE") - parser.add_option("-n", "--partitions", dest="partitions", default=2, - help="number of PARTITIONS", metavar="PARTITIONS") - - (options, args)=parser.parse_args() - options.partitions = int( options.partitions ) + parser.add_option( + "-f", "--file", dest="filename", help="read config from FILE", metavar="FILE" + ) + parser.add_option( + "-n", + "--partitions", + dest="partitions", + default=2, + help="number of PARTITIONS", + metavar="PARTITIONS", + ) + + (options, args) = parser.parse_args() + options.partitions = int(options.partitions) # Run Parallel Comutation - mesh_deformation ( options.filename , - options.partitions ) + mesh_deformation(options.filename, options.partitions) + + #: def main() @@ -56,8 +66,8 @@ def main(): # Parallel Computation Function # ------------------------------------------------------------------- -def mesh_deformation( filename , - partitions = 2 ): + +def mesh_deformation(filename, partitions=2): # Config config = SU2.io.Config(filename) @@ -75,6 +85,7 @@ def mesh_deformation( filename , return state + #: mesh_deformation() @@ -83,7 +94,5 @@ def mesh_deformation( filename , # ------------------------------------------------------------------- # this is only accessed if running from command prompt -if __name__ == '__main__': +if __name__ == "__main__": main() - - diff --git a/SU2_PY/package_tests.py b/SU2_PY/package_tests.py index b15f475b408..186f86e4ec5 100755 --- a/SU2_PY/package_tests.py +++ b/SU2_PY/package_tests.py @@ -29,7 +29,8 @@ from __future__ import print_function import os, sys, copy -sys.path.append(os.environ['SU2_RUN']) + +sys.path.append(os.environ["SU2_RUN"]) import SU2 from collections import OrderedDict @@ -58,89 +59,97 @@ def main(): - #io0() # working - #io1() - #level0() # working - #level1() # working - #level2() # working - #level3() # working - #level4() # working - #level5() # working + # io0() # working + # io1() + # level0() # working + # level1() # working + # level2() # working + # level3() # working + # level4() # working + # level5() # working + + print("DONE!") - print('DONE!') def io0(): - folder='test_io0'; pull='config_NACA0012.cfg'; link='mesh_NACA0012.su2' - with SU2.io.redirect_folder(folder,pull,link): + folder = "test_io0" + pull = "config_NACA0012.cfg" + link = "mesh_NACA0012.su2" + with SU2.io.redirect_folder(folder, pull, link): - config_name = 'config_NACA0012.cfg' + config_name = "config_NACA0012.cfg" config = SU2.io.Config(filename=config_name) print(config) - config.ADAPT_CYCLES - config['ADAPT_CYCLES'] + config["ADAPT_CYCLES"] - config.dump('out.cfg') + config.dump("out.cfg") konfig = copy.deepcopy(config) - konfig['TASKS'] = ['TEST'] - konfig['NUMBER_PART'] = 0 + konfig["TASKS"] = ["TEST"] + konfig["NUMBER_PART"] = 0 config_diff = config.diff(konfig) print(config_diff) - wait = 0 + def io1(): option = SU2.io.config.MathProblem() - option = 'DIRECT' + option = "DIRECT" wait = 0 + def level0(): - folder='test_level0'; pull='config_NACA0012.cfg'; link='mesh_NACA0012.su2' - with SU2.io.redirect_folder(folder,pull,link): + folder = "test_level0" + pull = "config_NACA0012.cfg" + link = "mesh_NACA0012.su2" + with SU2.io.redirect_folder(folder, pull, link): # Setup - config_name = 'config_NACA0012.cfg' + config_name = "config_NACA0012.cfg" config = SU2.io.Config(config_name) config.EXT_ITER = 9 config.NUMBER_PART = 2 SU2.run.CFD(config) + def level1(): - folder='test_level1'; pull='config_NACA0012.cfg'; link='mesh_NACA0012.su2' - with SU2.io.redirect_folder(folder,pull,link): + folder = "test_level1" + pull = "config_NACA0012.cfg" + link = "mesh_NACA0012.su2" + with SU2.io.redirect_folder(folder, pull, link): # Setup - config_name = 'config_NACA0012.cfg' + config_name = "config_NACA0012.cfg" config = SU2.io.Config(config_name) - config['NUMBER_PART'] = 2 - config['EXT_ITER'] = 9 + config["NUMBER_PART"] = 2 + config["EXT_ITER"] = 9 state = SU2.io.State() # Deformation - dv_new = [0.002]*38 - info = SU2.run.deform(config,dv_new) + dv_new = [0.002] * 38 + info = SU2.run.deform(config, dv_new) state.update(info) # Direct Solution info = SU2.run.direct(config) state.update(info) - SU2.io.restart2solution(config,state) + SU2.io.restart2solution(config, state) # Adjoint Solution info = SU2.run.adjoint(config) state.update(info) - SU2.io.restart2solution(config,state) + SU2.io.restart2solution(config, state) # Gradient Projection info = SU2.run.projection(config) @@ -148,143 +157,159 @@ def level1(): print(state) - SU2.io.save_data('state.pkl',state) - data = SU2.io.load_data('state.pkl') + SU2.io.save_data("state.pkl", state) + data = SU2.io.load_data("state.pkl") - SU2.io.save_data('config.pkl',config) - data = SU2.io.load_data('config.pkl') + SU2.io.save_data("config.pkl", config) + data = SU2.io.load_data("config.pkl") wait = 0 + def level2(): - folder='test_level2'; pull='config_NACA0012.cfg'; link='mesh_NACA0012.su2' - with SU2.io.redirect_folder(folder,pull,link): + folder = "test_level2" + pull = "config_NACA0012.cfg" + link = "mesh_NACA0012.su2" + with SU2.io.redirect_folder(folder, pull, link): # Setup - config_name = 'config_NACA0012.cfg' + config_name = "config_NACA0012.cfg" config = SU2.io.Config(config_name) - config['NUMBER_PART'] = 2 - config['EXT_ITER'] = 9 - dv_new = [0.0]*38 - #dv_new[10] = 0.05 + config["NUMBER_PART"] = 2 + config["EXT_ITER"] = 9 + dv_new = [0.0] * 38 + # dv_new[10] = 0.05 config.unpack_dvs(dv_new) state = SU2.io.State() - #with SU2.io.redirect.folder(folder='JOB_001',link='mesh_NACA0012.su2'): + # with SU2.io.redirect.folder(folder='JOB_001',link='mesh_NACA0012.su2'): # grad = SU2.eval.grad( 'DRAG', 'FINDIFF', config, state ) - with SU2.io.redirect_folder(folder='JOB_001',link='mesh_NACA0012.su2'): - func = SU2.eval.func( 'LIFT', config, state ) - grads = SU2.eval.grad( 'LIFT', 'CONTINUOUS_ADJOINT', config, state ) + with SU2.io.redirect_folder(folder="JOB_001", link="mesh_NACA0012.su2"): + func = SU2.eval.func("LIFT", config, state) + grads = SU2.eval.grad("LIFT", "CONTINUOUS_ADJOINT", config, state) - with SU2.io.redirect_folder(folder='JOB_001',link='mesh_NACA0012.su2'): - func = SU2.eval.func( 'DRAG', config, state ) # will not run direct - grads = SU2.eval.grad( 'LIFT', 'CONTINUOUS_ADJOINT', config, state ) # will not run adjoint - grads = SU2.eval.grad( 'DRAG', 'CONTINUOUS_ADJOINT', config, state ) # will run adjoint + with SU2.io.redirect_folder(folder="JOB_001", link="mesh_NACA0012.su2"): + func = SU2.eval.func("DRAG", config, state) # will not run direct + grads = SU2.eval.grad( + "LIFT", "CONTINUOUS_ADJOINT", config, state + ) # will not run adjoint + grads = SU2.eval.grad( + "DRAG", "CONTINUOUS_ADJOINT", config, state + ) # will run adjoint wait = 0 + def level3(): - folder='test_level3'; pull='config_NACA0012.cfg'; link='mesh_NACA0012.su2' - with SU2.io.redirect_folder(folder,pull,link): + folder = "test_level3" + pull = "config_NACA0012.cfg" + link = "mesh_NACA0012.su2" + with SU2.io.redirect_folder(folder, pull, link): # Setup - config_name = 'config_NACA0012.cfg' + config_name = "config_NACA0012.cfg" config = SU2.io.Config(config_name) - config['NUMBER_PART'] = 2 - config['EXT_ITER'] = 9 + config["NUMBER_PART"] = 2 + config["EXT_ITER"] = 9 # initialize design state state = SU2.io.State() state.find_files(config) # start design - design = SU2.eval.Design(config,state) + design = SU2.eval.Design(config, state) # run design with dv change - dv_new = [0.0]*38 + dv_new = [0.0] * 38 vals = design.obj_f(dv_new) vals = design.obj_df(dv_new) vals = design.con_ceq(dv_new) vals = design.con_dceq(dv_new) vals = design.con_cieq(dv_new) vals = design.con_dcieq(dv_new) - vals = design.func('LIFT') - vals = design.grad('LIFT','CONTINUOUS_ADJOINT') + vals = design.func("LIFT") + vals = design.grad("LIFT", "CONTINUOUS_ADJOINT") - SU2.io.save_data('design.pkl',design) - data = SU2.io.load_data('design.pkl') + SU2.io.save_data("design.pkl", design) + data = SU2.io.load_data("design.pkl") wait = 0 + def level4(): - folder='test_level4'; pull='config_NACA0012.cfg'; link='mesh_NACA0012.su2' - with SU2.io.redirect_folder(folder,pull,link): + folder = "test_level4" + pull = "config_NACA0012.cfg" + link = "mesh_NACA0012.su2" + with SU2.io.redirect_folder(folder, pull, link): # Setup - config_name = 'config_NACA0012.cfg' + config_name = "config_NACA0012.cfg" config = SU2.io.Config(config_name) - config['NUMBER_PART'] = 2 - config['EXT_ITER'] = 9 - config.CONSOLE = 'QUIET' + config["NUMBER_PART"] = 2 + config["EXT_ITER"] = 9 + config.CONSOLE = "QUIET" # initialize design state state = SU2.io.State() state.find_files(config) # initialize project - project = SU2.opt.Project(config,state) + project = SU2.opt.Project(config, state) # run project with dv changes - dv_new = [0.0]*38 + dv_new = [0.0] * 38 vals = project.obj_f(dv_new) vals = project.obj_df(dv_new) - dv_new = [-0.005]*38 + dv_new = [-0.005] * 38 vals = project.obj_f(dv_new) - dv_new = [0.0]*38 + dv_new = [0.0] * 38 dv_new[9] = -0.02 vals = project.obj_f(dv_new) - dv_new = [0.005]*38 - vals = project.obj_f(dv_new) # will not rerun solutions + dv_new = [0.005] * 38 + vals = project.obj_f(dv_new) # will not rerun solutions - SU2.io.save_data('project.pkl',project) - data = SU2.io.load_data('project.pkl') + SU2.io.save_data("project.pkl", project) + data = SU2.io.load_data("project.pkl") data = project.data wait = 0 print("Done!") + def level5(): - folder='test_level5'; pull='config_NACA0012.cfg'; link='mesh_NACA0012.su2' - with SU2.io.redirect_folder(folder,pull,link): + folder = "test_level5" + pull = "config_NACA0012.cfg" + link = "mesh_NACA0012.su2" + with SU2.io.redirect_folder(folder, pull, link): # Setup - config_name = 'config_NACA0012.cfg' + config_name = "config_NACA0012.cfg" config = SU2.io.Config(config_name) - config['NUMBER_PART'] = 2 - config['EXT_ITER'] = 9 - config['CONSOLE'] = 'CONCISE' + config["NUMBER_PART"] = 2 + config["EXT_ITER"] = 9 + config["CONSOLE"] = "CONCISE" # set optimization problem obj = {} - obj['DRAG'] = {'SCALE':1.e-2} + obj["DRAG"] = {"SCALE": 1.0e-2} cons = {} - cons['EQUALITY'] = {} - cons['INEQUALITY'] = {} - cons['INEQUALITY']['LIFT'] = {'SIGN':'>','VALUE':0.328188,'SCALE':1e-1} - cons['INEQUALITY']['MOMENT_Z'] = {'SIGN':'>','VALUE':0.034068,'SCALE':1e-2} + cons["EQUALITY"] = {} + cons["INEQUALITY"] = {} + cons["INEQUALITY"]["LIFT"] = {"SIGN": ">", "VALUE": 0.328188, "SCALE": 1e-1} + cons["INEQUALITY"]["MOMENT_Z"] = {"SIGN": ">", "VALUE": 0.034068, "SCALE": 1e-2} def_dv = config.DEFINITION_DV - n_dv = sum(def_dv['KIND']) - def_dv['SCALE'] = [1.e0]*n_dv + n_dv = sum(def_dv["KIND"]) + def_dv["SCALE"] = [1.0e0] * n_dv - config.OPT_OBJECTIVE = obj + config.OPT_OBJECTIVE = obj config.OPT_CONSTRAINT = cons # initialize design state @@ -292,17 +317,18 @@ def level5(): state.find_files(config) # initialize project - project = SU2.opt.Project(config,state) + project = SU2.opt.Project(config, state) # optimization setup - x0 = [0.0]*n_dv - xb = [] #[[-0.02,0.02]]*n_dv + x0 = [0.0] * n_dv + xb = [] # [[-0.02,0.02]]*n_dv its = 20 # optimize - SU2.opt.SLSQP(project,x0,xb,its) + SU2.opt.SLSQP(project, x0, xb, its) wait = 0 -if __name__ == '__main__': + +if __name__ == "__main__": main() diff --git a/SU2_PY/parallel_computation.py b/SU2_PY/parallel_computation.py index 001ce0c5eba..a20a5bfb088 100755 --- a/SU2_PY/parallel_computation.py +++ b/SU2_PY/parallel_computation.py @@ -27,34 +27,48 @@ import os, sys from optparse import OptionParser -sys.path.append(os.environ['SU2_RUN']) + +sys.path.append(os.environ["SU2_RUN"]) import SU2 # ------------------------------------------------------------------- # Main # ------------------------------------------------------------------- + def main(): # Command Line Options - parser=OptionParser() - parser.add_option("-f", "--file", dest="filename", - help="read config from FILE", metavar="FILE") - parser.add_option("-n", "--partitions", dest="partitions", default=2, - help="number of PARTITIONS", metavar="PARTITIONS") - parser.add_option("-c", "--compute", dest="compute", default="True", - help="COMPUTE direct and adjoint problem", metavar="COMPUTE") - - (options, args)=parser.parse_args() - options.partitions = int( options.partitions ) - options.compute = options.compute.upper() == 'TRUE' + parser = OptionParser() + parser.add_option( + "-f", "--file", dest="filename", help="read config from FILE", metavar="FILE" + ) + parser.add_option( + "-n", + "--partitions", + dest="partitions", + default=2, + help="number of PARTITIONS", + metavar="PARTITIONS", + ) + parser.add_option( + "-c", + "--compute", + dest="compute", + default="True", + help="COMPUTE direct and adjoint problem", + metavar="COMPUTE", + ) + + (options, args) = parser.parse_args() + options.partitions = int(options.partitions) + options.compute = options.compute.upper() == "TRUE" if options.filename == None: raise Exception("No config file provided. Use -f flag") - parallel_computation( options.filename , - options.partitions , - options.compute ) + parallel_computation(options.filename, options.partitions, options.compute) + #: def main() @@ -63,9 +77,8 @@ def main(): # CFD Solution # ------------------------------------------------------------------- -def parallel_computation( filename , - partitions = 0 , - compute = True ): + +def parallel_computation(filename, partitions=0, compute=True): # Config config = SU2.io.Config(filename) @@ -89,15 +102,16 @@ def parallel_computation( filename , state.update(info) # Solution merging - if config.MATH_PROBLEM == 'DIRECT': + if config.MATH_PROBLEM == "DIRECT": config.SOLUTION_FILENAME = config.RESTART_FILENAME - elif config.MATH_PROBLEM in ['CONTINUOUS_ADJOINT', 'DISCRETE_ADJOINT']: + elif config.MATH_PROBLEM in ["CONTINUOUS_ADJOINT", "DISCRETE_ADJOINT"]: config.SOLUTION_ADJ_FILENAME = config.RESTART_ADJ_FILENAME info = SU2.run.merge(config) state.update(info) return state + #: parallel_computation() @@ -106,6 +120,5 @@ def parallel_computation( filename , # ------------------------------------------------------------------- # this is only accessed if running from command prompt -if __name__ == '__main__': +if __name__ == "__main__": main() - diff --git a/SU2_PY/parallel_computation_fsi.py b/SU2_PY/parallel_computation_fsi.py index e0983038149..20a33338240 100755 --- a/SU2_PY/parallel_computation_fsi.py +++ b/SU2_PY/parallel_computation_fsi.py @@ -27,34 +27,48 @@ import os, sys, shutil, copy from optparse import OptionParser -sys.path.append(os.environ['SU2_RUN']) + +sys.path.append(os.environ["SU2_RUN"]) import SU2 # ------------------------------------------------------------------- # Main # ------------------------------------------------------------------- + def main(): # Command Line Options - parser=OptionParser() - parser.add_option("-f", "--file", dest="filename", - help="read config from FILE", metavar="FILE") - parser.add_option("-n", "--partitions", dest="partitions", default=2, - help="number of PARTITIONS", metavar="PARTITIONS") - parser.add_option("-c", "--compute", dest="compute", default="True", - help="COMPUTE direct and adjoint problem", metavar="COMPUTE") - - (options, args)=parser.parse_args() - options.partitions = int( options.partitions ) - options.compute = options.compute.upper() == 'TRUE' + parser = OptionParser() + parser.add_option( + "-f", "--file", dest="filename", help="read config from FILE", metavar="FILE" + ) + parser.add_option( + "-n", + "--partitions", + dest="partitions", + default=2, + help="number of PARTITIONS", + metavar="PARTITIONS", + ) + parser.add_option( + "-c", + "--compute", + dest="compute", + default="True", + help="COMPUTE direct and adjoint problem", + metavar="COMPUTE", + ) + + (options, args) = parser.parse_args() + options.partitions = int(options.partitions) + options.compute = options.compute.upper() == "TRUE" if options.filename == None: raise Exception("No config file provided. Use -f flag") - parallel_computation( options.filename , - options.partitions , - options.compute ) + parallel_computation(options.filename, options.partitions, options.compute) + #: def main() @@ -63,9 +77,8 @@ def main(): # CFD Solution # ------------------------------------------------------------------- -def parallel_computation( filename , - partitions = 0 , - compute = True ): + +def parallel_computation(filename, partitions=0, compute=True): # Config config = SU2.io.Config(filename) @@ -85,9 +98,9 @@ def parallel_computation( filename , state.update(info) # Solution merging - if config.SOLVER == 'FEM_ELASTICITY': + if config.SOLVER == "FEM_ELASTICITY": config.SOLUTION_FILENAME = config.RESTART_FILENAME - elif config.SOLVER == 'FLUID_STRUCTURE_INTERACTION': + elif config.SOLVER == "FLUID_STRUCTURE_INTERACTION": config.SOLUTION_FILENAME = config.RESTART_FILENAME config.SOLUTION_FILENAME = config.RESTART_FILENAME @@ -96,6 +109,7 @@ def parallel_computation( filename , return state + #: parallel_computation() @@ -104,6 +118,5 @@ def parallel_computation( filename , # ------------------------------------------------------------------- # this is only accessed if running from command prompt -if __name__ == '__main__': +if __name__ == "__main__": main() - diff --git a/SU2_PY/parse_config.py b/SU2_PY/parse_config.py index 66d386d68f2..aa57502a683 100755 --- a/SU2_PY/parse_config.py +++ b/SU2_PY/parse_config.py @@ -28,226 +28,275 @@ # make print(*args) function available in PY2.6+, does'nt work on PY < 2.6 from __future__ import print_function -import os,sys,xlwt +import os, sys, xlwt # note: requires xlwt for spreadsheet output # http://pypi.python.org/pypi/xlwt -class config_option: - option_name = "" - option_type = "" - option_category = "" - option_values = [] - option_default = "" - option_description = "" - - def __init__(self,name,otype,category,values,default,description): - self.option_name = name - self.option_type = otype - self.option_category = category - self.option_values = values - self.option_default = default - self.option_description = description - - def print_data(self): - print('Option Name: %s '% self.option_name) - print('Option Type: %s '% self.option_type) - print('Option Category: %s '% self.option_category) - print('Option values: ', self.option_values) - print('Option default: %s'% self.option_default) - print('Option description: %s '% self.option_description) - print('') - -def parse_config(config_cpp, config_hpp): - - # List of option types - option_types = ['AddEnumOption', 'AddMathProblem', 'AddSpecialOption', 'AddScalarOption', 'AddMarkerOption', 'AddMarkerPeriodic', 'AddMarkerDirichlet', 'AddMarkerInlet', 'AddMarkerOutlet', 'AddMarkerDisplacement', 'AddMarkerLoad', 'AddMarkerFlowLoad', 'AddArrayOption', 'AddListOption', 'AddConvectOption', 'AddEnumListOption', 'AddDVParamOption'] - - # Build a dictionary of enum options from hpp file - enum_options = {} - f = open(config_hpp,'r') - while(1): # Find beginning of enum definitions - s = f.readline() - if s.find('BEGIN_CONFIG_ENUMS') >-1: - break - while(1): - s = f.readline() - if s.find('END_CONFIG_ENUMS')>-1: - break # Reached end - - if s.find('CCreateMap')>-1: - dict_key = (s.split('=')[0]).split('>')[1].strip() - dict_val = [] - while(1): - s2 = f.readline() - thisval = s2.split('"')[1] - dict_val.append(thisval) - if s2.find(';')>-1: - break; - enum_options[dict_key] = dict_val - f.close() - - # Temporary: For now, build a list of all of the schemes - scheme_list = enum_options['Upwind_Map'] - scheme_list.extend(enum_options['Centered_Map'][1:]) - # Read the Options section of config_structure.cpp into a list of strings - lines = [] - f = open(config_cpp,'r') - while(1): - s = f.readline() - if s.find('BEGIN_CONFIG_OPTIONS')>-1: - break - while(1): - s = f.readline() - # Check if we've reached the end - if s.find('END_CONFIG_OPTIONS')>-1: - break - lines.append(s) - f.close() - - option_list = [] - present_category = "None" - #----- Main text parsing loop ----- - for j,line in enumerate(lines): - - # Check for a category description - if line.find('CONFIG_CATEGORY')>-1: - present_category = line.split(':')[1].strip().strip('*/').strip() - print(present_category) - - # Check for an option type - for option_type in option_types: - if line.find(option_type)>-1: # Found an option - # Get option name - name = line.split('"')[1] - - # Permitted values - values = ['YES','NO'] - if option_type=='AddEnumOption': - try: - enum_mapname = line.split(',')[2].strip() - values = enum_options[enum_mapname] - except KeyError: - print("KeyError, key=%s"%enum_mapname) - print("enum_options: ",enum_options) - sys.exit(1) - except TypeError: - print("TypeError, key=%s"%enum_mapname) - print("enum_options: ",enum_options) - sys.exit(1) - elif option_type=='AddMathProblem': - values = ['DIRECT','CONTINUOUS_ADJOINT','LINEARIZED'] - elif option_type=='AddScalarOption': - values = ['A scalar constant'] - elif option_type in ('AddMarkerOption', 'AddMarkerPeriodic', 'AddMarkerDirichlet', 'AddMarkerInlet', 'AddMarkerOutlet', 'AddMarkerDisplacement', 'AddMarkerLoad', 'AddMarkerFlowLoad'): - values = ['Valid marker name from grid file'] - elif option_type == 'AddArrayOption': - values = ['Array'] - elif option_type == 'AddListOption': - values = ['List'] - elif option_type == 'AddConvectOption': - values = scheme_list - print("Convect Option: ", name) - elif option_type == 'AddEnumListOption': - values = ['Enum list'] - elif option_type == 'AddDVParamOption': - values = ['DV Param'] - - # A first pass at finding the default value (Check the last item in parenthesis) - jdefault = j - while(lines[jdefault].find(';')==-1): - jdefault = jdefault+1 - default = lines[jdefault].strip().strip(');').split(',')[-1].strip().strip('"') - - # A whole bunch of corrections for what the default should be... - if default.find('string("')==0: - default = default.split('"')[1] - if default=="default_vec_3d": - default = '(1.0, 100.0, 1.0)' - if default=="default_vec_6d": - default = '( -1E15, -1E15, -1E15, 1E15, 1E15, 1E15 )' - if option_type == "AddMathProblem": - default = 'DIRECT' - if option_type == "AddConvectOption": - default = 'ROE-1ST_ORDER' - if default == 'RK_Alpha_Step': - default = '( 0.66667, 0.66667, 1.000000 )' - if default == 'RK_Beta_Step': - default = '( 1.00000, 0.00000, 0.00000 )' - - if default=='false': - default='NO' - elif default=='true': - default='YES' - - # Check for a description tag - description = "No description" - if lines[j-1].find('DESCRIPTION')>-1: - description = lines[j-1].split(':')[1].strip().strip('*/').strip() - - # Add a new option - option_list.append(config_option(name,option_type[3:],present_category,values,default,description)) - - break - - return option_list - -def print_all(option_list): - # Dumps the option list to screen - for option in option_list: - option.print_data() - -def make_spreadsheet(filename, option_list): - - wbk = xlwt.Workbook() - sheet_name = "" - jp = 0 - for j,opt in enumerate(option_list): - jp = jp+1 - if not sheet_name==opt.option_category: - # Create new sheet for new category - sheet_name = opt.option_category - sheet = wbk.add_sheet(sheet_name[:31].replace('/','-')) - - # Write spreadsheet header - sheet.write(0,0,'Option Name') - sheet.write(0,1,'Option Type') - sheet.write(0,2,'Option Category') - sheet.write(0,3,'Option Values') - sheet.write(0,4,'Option Default') - sheet.write(0,5,'Option Description') - jp = 1 - - - sheet.write(jp,0,opt.option_name) - sheet.write(jp,1,opt.option_type) - sheet.write(jp,2,opt.option_category) - sheet.write(jp,3,(',').join(opt.option_values)) - sheet.write(jp,4,opt.option_default) - sheet.write(jp,5,opt.option_description) - - wbk.save(filename) +class config_option: + option_name = "" + option_type = "" + option_category = "" + option_values = [] + option_default = "" + option_description = "" + + def __init__(self, name, otype, category, values, default, description): + self.option_name = name + self.option_type = otype + self.option_category = category + self.option_values = values + self.option_default = default + self.option_description = description + + def print_data(self): + print("Option Name: %s " % self.option_name) + print("Option Type: %s " % self.option_type) + print("Option Category: %s " % self.option_category) + print("Option values: ", self.option_values) + print("Option default: %s" % self.option_default) + print("Option description: %s " % self.option_description) + print("") +def parse_config(config_cpp, config_hpp): -if __name__=="__main__": + # List of option types + option_types = [ + "AddEnumOption", + "AddMathProblem", + "AddSpecialOption", + "AddScalarOption", + "AddMarkerOption", + "AddMarkerPeriodic", + "AddMarkerDirichlet", + "AddMarkerInlet", + "AddMarkerOutlet", + "AddMarkerDisplacement", + "AddMarkerLoad", + "AddMarkerFlowLoad", + "AddArrayOption", + "AddListOption", + "AddConvectOption", + "AddEnumListOption", + "AddDVParamOption", + ] + + # Build a dictionary of enum options from hpp file + enum_options = {} + f = open(config_hpp, "r") + while 1: # Find beginning of enum definitions + s = f.readline() + if s.find("BEGIN_CONFIG_ENUMS") > -1: + break + while 1: + s = f.readline() + if s.find("END_CONFIG_ENUMS") > -1: + break # Reached end + + if s.find("CCreateMap") > -1: + dict_key = (s.split("=")[0]).split(">")[1].strip() + dict_val = [] + while 1: + s2 = f.readline() + thisval = s2.split('"')[1] + dict_val.append(thisval) + if s2.find(";") > -1: + break + enum_options[dict_key] = dict_val + f.close() + + # Temporary: For now, build a list of all of the schemes + scheme_list = enum_options["Upwind_Map"] + scheme_list.extend(enum_options["Centered_Map"][1:]) + # Read the Options section of config_structure.cpp into a list of strings + lines = [] + f = open(config_cpp, "r") + while 1: + s = f.readline() + if s.find("BEGIN_CONFIG_OPTIONS") > -1: + break + while 1: + s = f.readline() + # Check if we've reached the end + if s.find("END_CONFIG_OPTIONS") > -1: + break + lines.append(s) + f.close() + + option_list = [] + present_category = "None" + # ----- Main text parsing loop ----- + for j, line in enumerate(lines): + + # Check for a category description + if line.find("CONFIG_CATEGORY") > -1: + present_category = line.split(":")[1].strip().strip("*/").strip() + print(present_category) + + # Check for an option type + for option_type in option_types: + if line.find(option_type) > -1: # Found an option + # Get option name + name = line.split('"')[1] + + # Permitted values + values = ["YES", "NO"] + if option_type == "AddEnumOption": + try: + enum_mapname = line.split(",")[2].strip() + values = enum_options[enum_mapname] + except KeyError: + print("KeyError, key=%s" % enum_mapname) + print("enum_options: ", enum_options) + sys.exit(1) + except TypeError: + print("TypeError, key=%s" % enum_mapname) + print("enum_options: ", enum_options) + sys.exit(1) + elif option_type == "AddMathProblem": + values = ["DIRECT", "CONTINUOUS_ADJOINT", "LINEARIZED"] + elif option_type == "AddScalarOption": + values = ["A scalar constant"] + elif option_type in ( + "AddMarkerOption", + "AddMarkerPeriodic", + "AddMarkerDirichlet", + "AddMarkerInlet", + "AddMarkerOutlet", + "AddMarkerDisplacement", + "AddMarkerLoad", + "AddMarkerFlowLoad", + ): + values = ["Valid marker name from grid file"] + elif option_type == "AddArrayOption": + values = ["Array"] + elif option_type == "AddListOption": + values = ["List"] + elif option_type == "AddConvectOption": + values = scheme_list + print("Convect Option: ", name) + elif option_type == "AddEnumListOption": + values = ["Enum list"] + elif option_type == "AddDVParamOption": + values = ["DV Param"] + + # A first pass at finding the default value (Check the last item in parenthesis) + jdefault = j + while lines[jdefault].find(";") == -1: + jdefault = jdefault + 1 + default = ( + lines[jdefault] + .strip() + .strip(");") + .split(",")[-1] + .strip() + .strip('"') + ) + + # A whole bunch of corrections for what the default should be... + if default.find('string("') == 0: + default = default.split('"')[1] + if default == "default_vec_3d": + default = "(1.0, 100.0, 1.0)" + if default == "default_vec_6d": + default = "( -1E15, -1E15, -1E15, 1E15, 1E15, 1E15 )" + if option_type == "AddMathProblem": + default = "DIRECT" + if option_type == "AddConvectOption": + default = "ROE-1ST_ORDER" + if default == "RK_Alpha_Step": + default = "( 0.66667, 0.66667, 1.000000 )" + if default == "RK_Beta_Step": + default = "( 1.00000, 0.00000, 0.00000 )" + + if default == "false": + default = "NO" + elif default == "true": + default = "YES" + + # Check for a description tag + description = "No description" + if lines[j - 1].find("DESCRIPTION") > -1: + description = lines[j - 1].split(":")[1].strip().strip("*/").strip() + + # Add a new option + option_list.append( + config_option( + name, + option_type[3:], + present_category, + values, + default, + description, + ) + ) + + break + + return option_list - # These variables should point to the configuration files - su2_home = os.environ['SU2_HOME'] - config_cpp = os.path.join(su2_home,'Common/src/config_structure.cpp') - config_hpp = os.path.join(su2_home,'Common/include/option_structure.hpp') - # Check that files exist - if not os.path.isfile(config_cpp): - sys.exit('Could not find cpp file, please check that su2_basedir is set correctly in parse_config.py') - if not os.path.isfile(config_hpp): - sys.exit('Could not find hpp file, please check that su2_basedir is set correctly in parse_config.py') +def print_all(option_list): + # Dumps the option list to screen + for option in option_list: + option.print_data() - # Run the parser - option_list = parse_config(config_cpp, config_hpp) - # Dump parsed data to screen - print_all(option_list) +def make_spreadsheet(filename, option_list): - #make_spreadsheet('out.xls',option_list) + wbk = xlwt.Workbook() + + sheet_name = "" + jp = 0 + for j, opt in enumerate(option_list): + jp = jp + 1 + if not sheet_name == opt.option_category: + # Create new sheet for new category + sheet_name = opt.option_category + sheet = wbk.add_sheet(sheet_name[:31].replace("/", "-")) + + # Write spreadsheet header + sheet.write(0, 0, "Option Name") + sheet.write(0, 1, "Option Type") + sheet.write(0, 2, "Option Category") + sheet.write(0, 3, "Option Values") + sheet.write(0, 4, "Option Default") + sheet.write(0, 5, "Option Description") + jp = 1 + + sheet.write(jp, 0, opt.option_name) + sheet.write(jp, 1, opt.option_type) + sheet.write(jp, 2, opt.option_category) + sheet.write(jp, 3, (",").join(opt.option_values)) + sheet.write(jp, 4, opt.option_default) + sheet.write(jp, 5, opt.option_description) + + wbk.save(filename) + + +if __name__ == "__main__": + + # These variables should point to the configuration files + su2_home = os.environ["SU2_HOME"] + config_cpp = os.path.join(su2_home, "Common/src/config_structure.cpp") + config_hpp = os.path.join(su2_home, "Common/include/option_structure.hpp") + + # Check that files exist + if not os.path.isfile(config_cpp): + sys.exit( + "Could not find cpp file, please check that su2_basedir is set correctly in parse_config.py" + ) + if not os.path.isfile(config_hpp): + sys.exit( + "Could not find hpp file, please check that su2_basedir is set correctly in parse_config.py" + ) + + # Run the parser + option_list = parse_config(config_cpp, config_hpp) + + # Dump parsed data to screen + print_all(option_list) + + # make_spreadsheet('out.xls',option_list) diff --git a/SU2_PY/profiling.py b/SU2_PY/profiling.py index d257257f520..a8894197ffd 100755 --- a/SU2_PY/profiling.py +++ b/SU2_PY/profiling.py @@ -32,69 +32,82 @@ from matplotlib import mlab parser = OptionParser() -parser.add_option("-f", "--file", dest="file", - help="profiling CSV file", metavar="FILE") -(options, args)=parser.parse_args() +parser.add_option( + "-f", "--file", dest="file", help="profiling CSV file", metavar="FILE" +) +(options, args) = parser.parse_args() # Store the file name filename = options.file # Load the csv file with the profiling data -profile = mlab.csv2rec(filename, comments='#', skiprows=0, checkrows=0) +profile = mlab.csv2rec(filename, comments="#", skiprows=0, checkrows=0) # Get total number of groups maxID = 0 for val in range(len(profile.function_name)): - if profile.function_id[val] > maxID: - maxID = profile.function_id[val] + if profile.function_id[val] > maxID: + maxID = profile.function_id[val] # Get some arrays for sorting out the groups -labels = [[] for i in range(maxID)] -fracs = [[] for i in range(maxID)] +labels = [[] for i in range(maxID)] +fracs = [[] for i in range(maxID)] explode = [[] for i in range(maxID)] -calls = [[] for i in range(maxID)] +calls = [[] for i in range(maxID)] # Process the profiling data into group IDs for val in range(len(profile.function_name)): - labels[profile.function_id[val]-1].append(profile.function_name[val]) - fracs[profile.function_id[val]-1].append(profile.avg_total_time[val]) - explode[profile.function_id[val]-1].append(0) - calls[profile.function_id[val]-1].append(profile.n_calls[val]) + labels[profile.function_id[val] - 1].append(profile.function_name[val]) + fracs[profile.function_id[val] - 1].append(profile.avg_total_time[val]) + explode[profile.function_id[val] - 1].append(0) + calls[profile.function_id[val] - 1].append(profile.n_calls[val]) # Loop over each of the group IDs and make figures for val in range(maxID): - #Create a Pie chart to see the time spent in each subroutine - fig = plt.figure(figsize=[18, 8]) - ax = fig.add_subplot(121) - ax.set_title("Total Time Spent in Each Function"); - - # Sort the pieces to make it pretty - fracs[val], labels[val],calls[val] = (list(x) for x in zip(*sorted(zip(fracs[val], labels[val], calls[val])))) - - # Call to make the pie chart - pie_wedge_collection = ax.pie(fracs[val], explode=explode[val], labels=labels[val],labeldistance=1.05, autopct='%1.1f%%', shadow=False, startangle=0); - for pie_wedge in pie_wedge_collection[0]: - pie_wedge.set_edgecolor('white') - - # Sort the number of calls again for the bar chart - calls[val], labels[val] = (list(x) for x in zip(*sorted(zip(calls[val], labels[val])))) - - # Create a bar chart for the number of function calls - ax = fig.add_subplot(122) - ax.set_title("Number of Function Calls"); - width = 0.35 - ax.bar(range(len(calls[val])), calls[val], width=width) - ax.set_xticks(np.arange(len(calls[val])) + width/2) - ax.set_xticklabels(labels[val]) - ax.set_xlabel('Function') - ax.set_ylabel('Calls') - fig.autofmt_xdate() - fig.subplots_adjust(wspace=0.5) - - # Save a figure for this group - filename = 'profile_group_' + str(val) + '.png' - fig.savefig(filename,format='png') - - # Uncomment the next line to open the plots on the screen - show() + # Create a Pie chart to see the time spent in each subroutine + fig = plt.figure(figsize=[18, 8]) + ax = fig.add_subplot(121) + ax.set_title("Total Time Spent in Each Function") + + # Sort the pieces to make it pretty + fracs[val], labels[val], calls[val] = ( + list(x) for x in zip(*sorted(zip(fracs[val], labels[val], calls[val]))) + ) + + # Call to make the pie chart + pie_wedge_collection = ax.pie( + fracs[val], + explode=explode[val], + labels=labels[val], + labeldistance=1.05, + autopct="%1.1f%%", + shadow=False, + startangle=0, + ) + for pie_wedge in pie_wedge_collection[0]: + pie_wedge.set_edgecolor("white") + + # Sort the number of calls again for the bar chart + calls[val], labels[val] = ( + list(x) for x in zip(*sorted(zip(calls[val], labels[val]))) + ) + + # Create a bar chart for the number of function calls + ax = fig.add_subplot(122) + ax.set_title("Number of Function Calls") + width = 0.35 + ax.bar(range(len(calls[val])), calls[val], width=width) + ax.set_xticks(np.arange(len(calls[val])) + width / 2) + ax.set_xticklabels(labels[val]) + ax.set_xlabel("Function") + ax.set_ylabel("Calls") + fig.autofmt_xdate() + fig.subplots_adjust(wspace=0.5) + + # Save a figure for this group + filename = "profile_group_" + str(val) + ".png" + fig.savefig(filename, format="png") + + # Uncomment the next line to open the plots on the screen + show() diff --git a/SU2_PY/pySU2/numpy.i b/SU2_PY/pySU2/numpy.i index e86dfc47137..b8fdaeb1f0c 100644 --- a/SU2_PY/pySU2/numpy.i +++ b/SU2_PY/pySU2/numpy.i @@ -3164,4 +3164,3 @@ #endif #endif /* SWIGPYTHON */ - diff --git a/SU2_PY/set_ffd_design_var.py b/SU2_PY/set_ffd_design_var.py index d9cef1d8387..6c5c798c3ad 100755 --- a/SU2_PY/set_ffd_design_var.py +++ b/SU2_PY/set_ffd_design_var.py @@ -32,217 +32,391 @@ from numpy import * parser = OptionParser() -parser.add_option("-i", "--iDegree", dest="iDegree", default=4, - help="i degree of the FFD box", metavar="IDEGREE") -parser.add_option("-j", "--jDegree", dest="jDegree", default=4, - help="j degree of the FFD box", metavar="JDEGREE") -parser.add_option("-k", "--kDegree", dest="kDegree", default=1, - help="k degree of the FFD box", metavar="KDEGREE") -parser.add_option("-b", "--ffdid", dest="ffd_id", default=0, - help="ID of the FFD box", metavar="FFD_ID") -parser.add_option("-m", "--marker", dest="marker", - help="marker name of the design surface", metavar="MARKER") -parser.add_option("-a", "--axis", dest="axis", - help="axis to define twist 'x_Orig, y_Orig, z_Orig, x_End, y_End, z_End'", metavar="AXIS") -parser.add_option("-s", "--scale", dest="scale", default=1.0, - help="scale factor for the bump functions", metavar="SCALE") -parser.add_option("-d", "--dimension", dest="dimension", default=3.0, - help="dimension of the problem", metavar="DIMENSION") - -(options, args)=parser.parse_args() +parser.add_option( + "-i", + "--iDegree", + dest="iDegree", + default=4, + help="i degree of the FFD box", + metavar="IDEGREE", +) +parser.add_option( + "-j", + "--jDegree", + dest="jDegree", + default=4, + help="j degree of the FFD box", + metavar="JDEGREE", +) +parser.add_option( + "-k", + "--kDegree", + dest="kDegree", + default=1, + help="k degree of the FFD box", + metavar="KDEGREE", +) +parser.add_option( + "-b", + "--ffdid", + dest="ffd_id", + default=0, + help="ID of the FFD box", + metavar="FFD_ID", +) +parser.add_option( + "-m", + "--marker", + dest="marker", + help="marker name of the design surface", + metavar="MARKER", +) +parser.add_option( + "-a", + "--axis", + dest="axis", + help="axis to define twist 'x_Orig, y_Orig, z_Orig, x_End, y_End, z_End'", + metavar="AXIS", +) +parser.add_option( + "-s", + "--scale", + dest="scale", + default=1.0, + help="scale factor for the bump functions", + metavar="SCALE", +) +parser.add_option( + "-d", + "--dimension", + dest="dimension", + default=3.0, + help="dimension of the problem", + metavar="DIMENSION", +) + +(options, args) = parser.parse_args() # Process options -options.iOrder = int(options.iDegree) + 1 -options.jOrder = int(options.jDegree) + 1 -options.kOrder = int(options.kDegree) + 1 -options.ffd_id = str(options.ffd_id) +options.iOrder = int(options.iDegree) + 1 +options.jOrder = int(options.jDegree) + 1 +options.kOrder = int(options.kDegree) + 1 +options.ffd_id = str(options.ffd_id) options.marker = str(options.marker) options.axis = str(options.axis) -options.scale = float(options.scale) -options.dim = int(options.dimension) +options.scale = float(options.scale) +options.dim = int(options.dimension) if options.dim == 3: - print(" ") - print("% FFD_CONTROL_POINT (X)") - - iVariable = 0 - dvList = "DEFINITION_DV= " - for kIndex in range(options.kOrder): + print(" ") + print("% FFD_CONTROL_POINT (X)") + + iVariable = 0 + dvList = "DEFINITION_DV= " + for kIndex in range(options.kOrder): + for jIndex in range(options.jOrder): + for iIndex in range(options.iOrder): + iVariable = iVariable + 1 + dvList = ( + dvList + + "( 11, " + + str(options.scale) + + " | " + + options.marker + + " | " + ) + dvList = ( + dvList + + options.ffd_id + + ", " + + str(iIndex) + + ", " + + str(jIndex) + + ", " + + str(kIndex) + + ", 1.0, 0.0, 0.0 )" + ) + if iVariable < (options.iOrder * (options.jOrder) * options.kOrder): + dvList = dvList + "; " + + print(dvList) + + print(" ") + print("% FFD_CONTROL_POINT (Y)") + + iVariable = 0 + dvList = "DEFINITION_DV= " + for kIndex in range(options.kOrder): + for jIndex in range(options.jOrder): + for iIndex in range(options.iOrder): + iVariable = iVariable + 1 + dvList = ( + dvList + + "( 11, " + + str(options.scale) + + " | " + + options.marker + + " | " + ) + dvList = ( + dvList + + options.ffd_id + + ", " + + str(iIndex) + + ", " + + str(jIndex) + + ", " + + str(kIndex) + + ", 0.0, 1.0, 0.0 )" + ) + if iVariable < (options.iOrder * (options.jOrder) * options.kOrder): + dvList = dvList + "; " + + print(dvList) + + print(" ") + print("% FFD_CONTROL_POINT (Z)") + + iVariable = 0 + dvList = "DEFINITION_DV= " + for kIndex in range(options.kOrder): + for jIndex in range(options.jOrder): + for iIndex in range(options.iOrder): + iVariable = iVariable + 1 + dvList = ( + dvList + + "( 11, " + + str(options.scale) + + " | " + + options.marker + + " | " + ) + dvList = ( + dvList + + options.ffd_id + + ", " + + str(iIndex) + + ", " + + str(jIndex) + + ", " + + str(kIndex) + + ", 0.0, 0.0, 1.0 )" + ) + if iVariable < (options.iOrder * (options.jOrder) * options.kOrder): + dvList = dvList + "; " + + print(dvList) + + print(" ") + print("% FFD_NACELLE (RHO)") + + iVariable = 0 + dvList = "DEFINITION_DV= " + for kIndex in range(options.kOrder): + for jIndex in range(1 + options.jOrder / 2): + for iIndex in range(options.iOrder): + iVariable = iVariable + 1 + dvList = ( + dvList + + "( 12, " + + str(options.scale) + + " | " + + options.marker + + " | " + ) + dvList = ( + dvList + + options.ffd_id + + ", " + + str(iIndex) + + ", " + + str(jIndex) + + ", " + + str(kIndex) + + ", 1.0, 0.0 )" + ) + if iVariable < ( + options.iOrder * (1 + options.jOrder / 2) * options.kOrder + ): + dvList = dvList + "; " + + print(dvList) + + print(" ") + print("% FFD_NACELLE (PHI)") + + iVariable = 0 + dvList = "DEFINITION_DV= " + for kIndex in range(options.kOrder): + for jIndex in range(1 + options.jOrder / 2): + for iIndex in range(options.iOrder): + iVariable = iVariable + 1 + dvList = ( + dvList + + "( 12, " + + str(options.scale) + + " | " + + options.marker + + " | " + ) + dvList = ( + dvList + + options.ffd_id + + ", " + + str(iIndex) + + ", " + + str(jIndex) + + ", " + + str(kIndex) + + ", 0.0, 1.0 )" + ) + if iVariable < ( + options.iOrder * (1 + options.jOrder / 2) * options.kOrder + ): + dvList = dvList + "; " + + print(dvList) + + print(" ") + print("% FFD_CONTROL_POINT (Z) (MULTIPLE INTERSECTIONS)") + + iVariable = 0 + dvList = "DEFINITION_DV= " + for kIndex in range(options.kOrder - 4): + for jIndex in range(options.jOrder - 4): + for iIndex in range(options.iOrder - 4): + iVariable = iVariable + 1 + dvList = ( + dvList + + "( 11, " + + str(options.scale) + + " | " + + options.marker + + " | " + ) + dvList = ( + dvList + + options.ffd_id + + ", " + + str(iIndex + 2) + + ", " + + str(jIndex + 2) + + ", " + + str(kIndex + 2) + + ", 0.0, 0.0, 1.0 )" + ) + if iVariable < (options.iOrder * (options.jOrder) * options.kOrder): + dvList = dvList + "; " + + print(dvList) + + print(" ") + print("% FFD_CAMBER, FFD_TWIST, FFD_THICKNESS") + + iVariable = 0 + dvList = "DEFINITION_DV= " for jIndex in range(options.jOrder): - for iIndex in range(options.iOrder): - iVariable = iVariable + 1 - dvList = dvList + "( 11, " + str(options.scale) + " | " + options.marker + " | " - dvList = dvList + options.ffd_id + ", " + str(iIndex) + ", " + str(jIndex) + ", " + str(kIndex) + ", 1.0, 0.0, 0.0 )" - if iVariable < (options.iOrder*(options.jOrder)*options.kOrder): - dvList = dvList + "; " - - - print(dvList) - - print(" ") - print("% FFD_CONTROL_POINT (Y)") - - iVariable = 0 - dvList = "DEFINITION_DV= " - for kIndex in range(options.kOrder): + for iIndex in range(options.iOrder): + iVariable = iVariable + 1 + dvList = ( + dvList + "( 14, " + str(options.scale) + " | " + options.marker + " | " + ) + dvList = ( + dvList + options.ffd_id + ", " + str(iIndex) + ", " + str(jIndex) + " )" + ) + dvList = dvList + "; " + iVariable = 0 for jIndex in range(options.jOrder): - for iIndex in range(options.iOrder): iVariable = iVariable + 1 - dvList = dvList + "( 11, " + str(options.scale) + " | " + options.marker + " | " - dvList = dvList + options.ffd_id + ", " + str(iIndex) + ", " + str(jIndex) + ", " + str(kIndex) + ", 0.0, 1.0, 0.0 )" - if iVariable < (options.iOrder*(options.jOrder)*options.kOrder): - dvList = dvList + "; " - - - print(dvList) - - print(" ") - print("% FFD_CONTROL_POINT (Z)") - - iVariable = 0 - dvList = "DEFINITION_DV= " - for kIndex in range(options.kOrder): + dvList = dvList + "( 15, " + str(options.scale) + " | " + options.marker + " | " + dvList = ( + dvList + options.ffd_id + ", " + str(jIndex) + ", " + options.axis + " )" + ) + if iVariable < (options.jOrder): + dvList = dvList + "; " + iVariable = 0 for jIndex in range(options.jOrder): - for iIndex in range(options.iOrder): - iVariable = iVariable + 1 - dvList = dvList + "( 11, " + str(options.scale) + " | " + options.marker + " | " - dvList = dvList + options.ffd_id + ", " + str(iIndex) + ", " + str(jIndex) + ", " + str(kIndex) + ", 0.0, 0.0, 1.0 )" - if iVariable < (options.iOrder*(options.jOrder)*options.kOrder): - dvList = dvList + "; " - - - print(dvList) - - print(" ") - print("% FFD_NACELLE (RHO)") - - iVariable = 0 - dvList = "DEFINITION_DV= " - for kIndex in range(options.kOrder): - for jIndex in range(1+options.jOrder/2): - for iIndex in range(options.iOrder): - iVariable = iVariable + 1 - dvList = dvList + "( 12, " + str(options.scale) + " | " + options.marker + " | " - dvList = dvList + options.ffd_id + ", " + str(iIndex) + ", " + str(jIndex) + ", " + str(kIndex) + ", 1.0, 0.0 )" - if iVariable < (options.iOrder*(1+options.jOrder/2)*options.kOrder): - dvList = dvList + "; " - - - print(dvList) - - print(" ") - print("% FFD_NACELLE (PHI)") - - iVariable = 0 - dvList = "DEFINITION_DV= " - for kIndex in range(options.kOrder): - for jIndex in range(1+options.jOrder/2): - for iIndex in range(options.iOrder): - iVariable = iVariable + 1 - dvList = dvList + "( 12, " + str(options.scale) + " | " + options.marker + " | " - dvList = dvList + options.ffd_id + ", " + str(iIndex) + ", " + str(jIndex) + ", " + str(kIndex) + ", 0.0, 1.0 )" - if iVariable < (options.iOrder*(1+options.jOrder/2)*options.kOrder): - dvList = dvList + "; " - - - print(dvList) - - print(" ") - print("% FFD_CONTROL_POINT (Z) (MULTIPLE INTERSECTIONS)") - - iVariable = 0 - dvList = "DEFINITION_DV= " - for kIndex in range(options.kOrder-4): - for jIndex in range(options.jOrder-4): - for iIndex in range(options.iOrder-4): - iVariable = iVariable + 1 - dvList = dvList + "( 11, " + str(options.scale) + " | " + options.marker + " | " - dvList = dvList + options.ffd_id + ", " + str(iIndex+2) + ", " + str(jIndex+2) + ", " + str(kIndex+2) + ", 0.0, 0.0, 1.0 )" - if iVariable < (options.iOrder*(options.jOrder)*options.kOrder): - dvList = dvList + "; " - - - print(dvList) - - print(" ") - print("% FFD_CAMBER, FFD_TWIST, FFD_THICKNESS") - - iVariable = 0 - dvList = "DEFINITION_DV= " - for jIndex in range(options.jOrder): - for iIndex in range(options.iOrder): - iVariable = iVariable + 1 - dvList = dvList + "( 14, " + str(options.scale) + " | " + options.marker + " | " - dvList = dvList + options.ffd_id + ", " + str(iIndex) + ", " + str(jIndex) + " )" - dvList = dvList + "; " - iVariable = 0 - for jIndex in range(options.jOrder): - iVariable = iVariable + 1 - dvList = dvList + "( 15, " + str(options.scale) + " | " + options.marker + " | " - dvList = dvList + options.ffd_id + ", " + str(jIndex) + ", " + options.axis + " )" - if iVariable < (options.jOrder): - dvList = dvList + "; " - iVariable = 0 - for jIndex in range(options.jOrder): - for iIndex in range(options.iOrder): - iVariable = iVariable + 1 - dvList = dvList + "( 16, " + str(options.scale) + " | " + options.marker + " | " - dvList = dvList + options.ffd_id + ", " + str(iIndex) + ", " + str(jIndex) + " )" - dvList = dvList + "; " - - - - print(dvList) + for iIndex in range(options.iOrder): + iVariable = iVariable + 1 + dvList = ( + dvList + "( 16, " + str(options.scale) + " | " + options.marker + " | " + ) + dvList = ( + dvList + options.ffd_id + ", " + str(iIndex) + ", " + str(jIndex) + " )" + ) + dvList = dvList + "; " + + print(dvList) if options.dim == 2: - print(" ") - print("% FFD_CONTROL_POINT_2D (X)") + print(" ") + print("% FFD_CONTROL_POINT_2D (X)") - iVariable = 0 - dvList = "DEFINITION_DV= " - for jIndex in range(options.jOrder): + iVariable = 0 + dvList = "DEFINITION_DV= " + for jIndex in range(options.jOrder): + for iIndex in range(options.iOrder): + iVariable = iVariable + 1 + dvList = ( + dvList + "( 19, " + str(options.scale) + " | " + options.marker + " | " + ) + dvList = ( + dvList + + options.ffd_id + + ", " + + str(iIndex) + + ", " + + str(jIndex) + + ", 1.0, 0.0 )" + ) + if iVariable < (options.iOrder * options.jOrder): + dvList = dvList + "; " + + print(dvList) + + print(" ") + print("% FFD_CONTROL_POINT_2D (Y)") + + iVariable = 0 + dvList = "DEFINITION_DV= " + for jIndex in range(options.jOrder): + for iIndex in range(options.iOrder): + iVariable = iVariable + 1 + dvList = ( + dvList + "( 19, " + str(options.scale) + " | " + options.marker + " | " + ) + dvList = ( + dvList + + options.ffd_id + + ", " + + str(iIndex) + + ", " + + str(jIndex) + + ", 0.0, 1.0 )" + ) + if iVariable < (options.iOrder * options.jOrder): + dvList = dvList + "; " + + print(dvList) + + print(" ") + print("FFD_CAMBER_2D & FFD_THICKNESS_2D") + + iVariable = 0 + dvList = "DEFINITION_DV= " for iIndex in range(options.iOrder): - iVariable = iVariable + 1 - dvList = dvList + "( 19, " + str(options.scale) + " | " + options.marker + " | " - dvList = dvList + options.ffd_id + ", " + str(iIndex) + ", " + str(jIndex) + ", 1.0, 0.0 )" - if iVariable < (options.iOrder*options.jOrder): + iVariable = iVariable + 1 + dvList = dvList + "( 20, " + str(options.scale) + " | " + options.marker + " | " + dvList = dvList + options.ffd_id + ", " + str(iIndex) + " )" dvList = dvList + "; " - - print(dvList) - - print(" ") - print("% FFD_CONTROL_POINT_2D (Y)") - - iVariable = 0 - dvList = "DEFINITION_DV= " - for jIndex in range(options.jOrder): + iVariable = 0 for iIndex in range(options.iOrder): - iVariable = iVariable + 1 - dvList = dvList + "( 19, " + str(options.scale) + " | " + options.marker + " | " - dvList = dvList + options.ffd_id + ", " + str(iIndex) + ", " + str(jIndex) + ", 0.0, 1.0 )" - if iVariable < (options.iOrder*options.jOrder): - dvList = dvList + "; " + iVariable = iVariable + 1 + dvList = dvList + "( 21, " + str(options.scale) + " | " + options.marker + " | " + dvList = dvList + options.ffd_id + ", " + str(iIndex) + " )" + if iVariable < (options.iOrder): + dvList = dvList + "; " - print(dvList) - - print(" ") - print("FFD_CAMBER_2D & FFD_THICKNESS_2D") - - iVariable = 0 - dvList = "DEFINITION_DV= " - for iIndex in range(options.iOrder): - iVariable = iVariable + 1 - dvList = dvList + "( 20, " + str(options.scale) + " | " + options.marker + " | " - dvList = dvList + options.ffd_id + ", " + str(iIndex) + " )" - dvList = dvList + "; " - iVariable = 0 - for iIndex in range(options.iOrder): - iVariable = iVariable + 1 - dvList = dvList + "( 21, " + str(options.scale) + " | " + options.marker + " | " - dvList = dvList + options.ffd_id + ", " + str(iIndex) + " )" - if iVariable < (options.iOrder): - dvList = dvList + "; " - - print(dvList) + print(dvList) diff --git a/SU2_PY/shape_optimization.py b/SU2_PY/shape_optimization.py index 34397c4e708..20cf15d4038 100755 --- a/SU2_PY/shape_optimization.py +++ b/SU2_PY/shape_optimization.py @@ -27,124 +27,247 @@ import os, sys, shutil from optparse import OptionParser -sys.path.append(os.environ['SU2_RUN']) + +sys.path.append(os.environ["SU2_RUN"]) import SU2 # ------------------------------------------------------------------- # Main # ------------------------------------------------------------------- + def main(): - parser=OptionParser() - parser.add_option("-f", "--file", dest="filename", - help="read config from FILE", metavar="FILE") - parser.add_option("-r", "--name", dest="projectname", default='', - help="try to restart from project file NAME", metavar="NAME") - parser.add_option("-n", "--partitions", dest="partitions", default=1, - help="number of PARTITIONS", metavar="PARTITIONS") - parser.add_option("-g", "--gradient", dest="gradient", default="DISCRETE_ADJOINT", - help="Method for computing the GRADIENT (CONTINUOUS_ADJOINT, DISCRETE_ADJOINT, FINDIFF, NONE)", metavar="GRADIENT") - parser.add_option("-o", "--optimization", dest="optimization", default="SLSQP", - help="OPTIMIZATION techique (SLSQP, CG, BFGS, POWELL)", metavar="OPTIMIZATION") - parser.add_option("-q", "--quiet", dest="quiet", default="True", - help="True/False Quiet all SU2 output (optimizer output only)", metavar="QUIET") - parser.add_option("-z", "--zones", dest="nzones", default="1", - help="Number of Zones", metavar="ZONES") - - - (options, args)=parser.parse_args() + parser = OptionParser() + parser.add_option( + "-f", "--file", dest="filename", help="read config from FILE", metavar="FILE" + ) + parser.add_option( + "-r", + "--name", + dest="projectname", + default="", + help="try to restart from project file NAME", + metavar="NAME", + ) + parser.add_option( + "-n", + "--partitions", + dest="partitions", + default=1, + help="number of PARTITIONS", + metavar="PARTITIONS", + ) + parser.add_option( + "-g", + "--gradient", + dest="gradient", + default="DISCRETE_ADJOINT", + help="Method for computing the GRADIENT (CONTINUOUS_ADJOINT, DISCRETE_ADJOINT, FINDIFF, NONE)", + metavar="GRADIENT", + ) + parser.add_option( + "-o", + "--optimization", + dest="optimization", + default="SLSQP", + help="OPTIMIZATION techique (SLSQP, CG, BFGS, POWELL)", + metavar="OPTIMIZATION", + ) + parser.add_option( + "-q", + "--quiet", + dest="quiet", + default="True", + help="True/False Quiet all SU2 output (optimizer output only)", + metavar="QUIET", + ) + parser.add_option( + "-z", + "--zones", + dest="nzones", + default="1", + help="Number of Zones", + metavar="ZONES", + ) + + (options, args) = parser.parse_args() # process inputs - options.partitions = int( options.partitions ) - options.quiet = options.quiet.upper() == 'TRUE' - options.gradient = options.gradient.upper() - options.nzones = int( options.nzones ) - - sys.stdout.write('\n-------------------------------------------------------------------------\n') - sys.stdout.write('| ___ _ _ ___ |\n') - sys.stdout.write('| / __| | | |_ ) Release 7.5.1 \"Blackbird\" |\n') - sys.stdout.write('| \\__ \\ |_| |/ / |\n') - sys.stdout.write('| |___/\\___//___| Aerodynamic Shape Optimization Script |\n') - sys.stdout.write('| |\n') - sys.stdout.write('-------------------------------------------------------------------------\n') - sys.stdout.write('| SU2 Project Website: https://su2code.github.io |\n') - sys.stdout.write('| |\n') - sys.stdout.write('| The SU2 Project is maintained by the SU2 Foundation |\n') - sys.stdout.write('| (http://su2foundation.org) |\n') - sys.stdout.write('-------------------------------------------------------------------------\n') - sys.stdout.write('| Copyright 2012-2023, SU2 Contributors (cf. AUTHORS.md) |\n') - sys.stdout.write('| |\n') - sys.stdout.write('| SU2 is free software; you can redistribute it and/or |\n') - sys.stdout.write('| modify it under the terms of the GNU Lesser General Public |\n') - sys.stdout.write('| License as published by the Free Software Foundation; either |\n') - sys.stdout.write('| version 2.1 of the License, or (at your option) any later version. |\n') - sys.stdout.write('| |\n') - sys.stdout.write('| SU2 is distributed in the hope that it will be useful, |\n') - sys.stdout.write('| but WITHOUT ANY WARRANTY; without even the implied warranty of |\n') - sys.stdout.write('| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |\n') - sys.stdout.write('| Lesser General Public License for more details. |\n') - sys.stdout.write('| |\n') - sys.stdout.write('| You should have received a copy of the GNU Lesser General Public |\n') - sys.stdout.write('| License along with SU2. If not, see . |\n') - sys.stdout.write('-------------------------------------------------------------------------\n') - - shape_optimization( options.filename , - options.projectname , - options.partitions , - options.gradient , - options.optimization , - options.quiet , - options.nzones ) + options.partitions = int(options.partitions) + options.quiet = options.quiet.upper() == "TRUE" + options.gradient = options.gradient.upper() + options.nzones = int(options.nzones) + + sys.stdout.write( + "\n-------------------------------------------------------------------------\n" + ) + sys.stdout.write( + "| ___ _ _ ___ |\n" + ) + sys.stdout.write( + '| / __| | | |_ ) Release 7.5.1 "Blackbird" |\n' + ) + sys.stdout.write( + "| \\__ \\ |_| |/ / |\n" + ) + sys.stdout.write( + "| |___/\\___//___| Aerodynamic Shape Optimization Script |\n" + ) + sys.stdout.write( + "| |\n" + ) + sys.stdout.write( + "-------------------------------------------------------------------------\n" + ) + sys.stdout.write( + "| SU2 Project Website: https://su2code.github.io |\n" + ) + sys.stdout.write( + "| |\n" + ) + sys.stdout.write( + "| The SU2 Project is maintained by the SU2 Foundation |\n" + ) + sys.stdout.write( + "| (http://su2foundation.org) |\n" + ) + sys.stdout.write( + "-------------------------------------------------------------------------\n" + ) + sys.stdout.write( + "| Copyright 2012-2023, SU2 Contributors (cf. AUTHORS.md) |\n" + ) + sys.stdout.write( + "| |\n" + ) + sys.stdout.write( + "| SU2 is free software; you can redistribute it and/or |\n" + ) + sys.stdout.write( + "| modify it under the terms of the GNU Lesser General Public |\n" + ) + sys.stdout.write( + "| License as published by the Free Software Foundation; either |\n" + ) + sys.stdout.write( + "| version 2.1 of the License, or (at your option) any later version. |\n" + ) + sys.stdout.write( + "| |\n" + ) + sys.stdout.write( + "| SU2 is distributed in the hope that it will be useful, |\n" + ) + sys.stdout.write( + "| but WITHOUT ANY WARRANTY; without even the implied warranty of |\n" + ) + sys.stdout.write( + "| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |\n" + ) + sys.stdout.write( + "| Lesser General Public License for more details. |\n" + ) + sys.stdout.write( + "| |\n" + ) + sys.stdout.write( + "| You should have received a copy of the GNU Lesser General Public |\n" + ) + sys.stdout.write( + "| License along with SU2. If not, see . |\n" + ) + sys.stdout.write( + "-------------------------------------------------------------------------\n" + ) + + shape_optimization( + options.filename, + options.projectname, + options.partitions, + options.gradient, + options.optimization, + options.quiet, + options.nzones, + ) + #: main() -def shape_optimization( filename , - projectname = '' , - partitions = 0 , - gradient = 'CONTINUOUS_ADJOINT' , - optimization = 'SLSQP' , - quiet = False , - nzones = 1 ): + +def shape_optimization( + filename, + projectname="", + partitions=0, + gradient="CONTINUOUS_ADJOINT", + optimization="SLSQP", + quiet=False, + nzones=1, +): # Config config = SU2.io.Config(filename) config.NUMBER_PART = partitions - config.NZONES = int( nzones ) - if quiet: config.CONSOLE = 'CONCISE' + config.NZONES = int(nzones) + if quiet: + config.CONSOLE = "CONCISE" config.GRADIENT_METHOD = gradient - its = int ( config.OPT_ITERATIONS ) # number of opt iterations - bound_upper = float ( config.OPT_BOUND_UPPER ) # variable bound to be scaled by the line search - bound_lower = float ( config.OPT_BOUND_LOWER ) # variable bound to be scaled by the line search - relax_factor = float ( config.OPT_RELAX_FACTOR ) # line search scale - gradient_factor = float ( config.OPT_GRADIENT_FACTOR ) # objective function and gradient scale - def_dv = config.DEFINITION_DV # complete definition of the desing variable - n_dv = sum(def_dv['SIZE']) # number of design variables - accu = float ( config.OPT_ACCURACY ) * gradient_factor # optimizer accuracy - x0 = [0.0]*n_dv # initial design - xb_low = [float(bound_lower)/float(relax_factor)]*n_dv # lower dv bound it includes the line search acceleration factor - xb_up = [float(bound_upper)/float(relax_factor)]*n_dv # upper dv bound it includes the line search acceleration fa - xb = list(zip(xb_low, xb_up)) # design bounds + its = int(config.OPT_ITERATIONS) # number of opt iterations + bound_upper = float( + config.OPT_BOUND_UPPER + ) # variable bound to be scaled by the line search + bound_lower = float( + config.OPT_BOUND_LOWER + ) # variable bound to be scaled by the line search + relax_factor = float(config.OPT_RELAX_FACTOR) # line search scale + gradient_factor = float( + config.OPT_GRADIENT_FACTOR + ) # objective function and gradient scale + def_dv = config.DEFINITION_DV # complete definition of the desing variable + n_dv = sum(def_dv["SIZE"]) # number of design variables + accu = float(config.OPT_ACCURACY) * gradient_factor # optimizer accuracy + x0 = [0.0] * n_dv # initial design + xb_low = [ + float(bound_lower) / float(relax_factor) + ] * n_dv # lower dv bound it includes the line search acceleration factor + xb_up = [ + float(bound_upper) / float(relax_factor) + ] * n_dv # upper dv bound it includes the line search acceleration fa + xb = list(zip(xb_low, xb_up)) # design bounds # State state = SU2.io.State() state.find_files(config) # add restart files to state.FILES - if config.get('TIME_DOMAIN', 'NO') == 'YES' and config.get('RESTART_SOL', 'NO') == 'YES' and gradient != 'CONTINUOUS_ADJOINT': - restart_name = config['RESTART_FILENAME'].split('.')[0] - restart_filename = restart_name + '_' + str(int(config['RESTART_ITER'])-1).zfill(5) + '.dat' - if not os.path.isfile(restart_filename): # throw, if restart files does not exist + if ( + config.get("TIME_DOMAIN", "NO") == "YES" + and config.get("RESTART_SOL", "NO") == "YES" + and gradient != "CONTINUOUS_ADJOINT" + ): + restart_name = config["RESTART_FILENAME"].split(".")[0] + restart_filename = ( + restart_name + "_" + str(int(config["RESTART_ITER"]) - 1).zfill(5) + ".dat" + ) + if not os.path.isfile( + restart_filename + ): # throw, if restart files does not exist sys.exit("Error: Restart file <" + restart_filename + "> not found.") - state['FILES']['RESTART_FILE_1'] = restart_filename + state["FILES"]["RESTART_FILE_1"] = restart_filename # use only, if time integration is second order - if config.get('TIME_MARCHING', 'NO') == 'DUAL_TIME_STEPPING-2ND_ORDER': - restart_filename = restart_name + '_' + str(int(config['RESTART_ITER'])-2).zfill(5) + '.dat' - if not os.path.isfile(restart_filename): # throw, if restart files does not exist + if config.get("TIME_MARCHING", "NO") == "DUAL_TIME_STEPPING-2ND_ORDER": + restart_filename = ( + restart_name + + "_" + + str(int(config["RESTART_ITER"]) - 2).zfill(5) + + ".dat" + ) + if not os.path.isfile( + restart_filename + ): # throw, if restart files does not exist sys.exit("Error: Restart file <" + restart_filename + "> not found.") - state['FILES']['RESTART_FILE_2'] =restart_filename - + state["FILES"]["RESTART_FILE_2"] = restart_filename # Project @@ -152,25 +275,25 @@ def shape_optimization( filename , project = SU2.io.load_data(projectname) project.config = config else: - project = SU2.opt.Project(config,state) + project = SU2.opt.Project(config, state) # Optimize - if optimization == 'SLSQP': - SU2.opt.SLSQP(project,x0,xb,its,accu) - if optimization == 'CG': - SU2.opt.CG(project,x0,xb,its,accu) - if optimization == 'BFGS': - SU2.opt.BFGS(project,x0,xb,its,accu) - if optimization == 'POWELL': - SU2.opt.POWELL(project,x0,xb,its,accu) - + if optimization == "SLSQP": + SU2.opt.SLSQP(project, x0, xb, its, accu) + if optimization == "CG": + SU2.opt.CG(project, x0, xb, its, accu) + if optimization == "BFGS": + SU2.opt.BFGS(project, x0, xb, its, accu) + if optimization == "POWELL": + SU2.opt.POWELL(project, x0, xb, its, accu) # rename project file if projectname: - shutil.move('project.pkl',projectname) + shutil.move("project.pkl", projectname) return project + #: shape_optimization() @@ -179,6 +302,5 @@ def shape_optimization( filename , # ------------------------------------------------------------------- # this is only accessed if running from command prompt -if __name__ == '__main__': +if __name__ == "__main__": main() - diff --git a/SU2_PY/topology_optimization.py b/SU2_PY/topology_optimization.py index c8b211c93e6..45a8818d4ac 100755 --- a/SU2_PY/topology_optimization.py +++ b/SU2_PY/topology_optimization.py @@ -45,26 +45,26 @@ ####### SETUP ####### -obj_scale = 1/1.25e-3 # scale the objective so that it starts at 1-4 -con_scale = 1/0.5 # 1 over upper bound (e.g. max volume) -var_scale = 1.0 # variable scale +obj_scale = 1 / 1.25e-3 # scale the objective so that it starts at 1-4 +con_scale = 1 / 0.5 # 1 over upper bound (e.g. max volume) +var_scale = 1.0 # variable scale # maximum number of iterations maxJev_t = 1000 # max iters for gray initialization, i.e. soft filter settings maxJev_i = 200 # num iters between updates of the filter settings and constraint penalty factor -nJev_u = 40 +nJev_u = 40 # tolerances -ftol_u = 1e-5 # during updates -ftol_f = 1e-7 # final iteration +ftol_u = 1e-5 # during updates +ftol_f = 1e-7 # final iteration # the exterior penalty method is used to impose the constraint, # this is the maximum constraint violation, below it the penalty factor is not increased -htol = 5e-3 +htol = 5e-3 # general options for L-BFGS-B -options={'disp': True, 'maxcor': 10, 'ftol': ftol_u, 'gtol': 1e-18} +options = {"disp": True, "maxcor": 10, "ftol": ftol_u, "gtol": 1e-18} # these are the commands for the direct and adjoint runs, modify to run parallel commands = ["SU2_CFD ", "SU2_CFD_AD "] @@ -85,344 +85,409 @@ ####### SU2 Driver ####### + class Driver: - def __init__(self,commands,inputFile,configFiles,outputFiles): - self._inputFile = inputFile - self._objValFile = "history.csv" - self._objDerFile = outputFiles[0] - self._conValFile = "history.csv" - self._conDerFile = outputFiles[1] - self._objValCommand = commands[0]+configFiles[0]+" > objval.stdout" - self._objDerCommand = commands[1]+configFiles[1]+" > objder.stdout" - self._conDerCommand = commands[1]+configFiles[2]+" > conval.stdout" - #end - - def _assert_isfinite(self,val): - if math.isinf(val) or math.isnan(val): - raise ValueError - #end - - def _write_input(self,x): - fid = open(self._inputFile,"w") - lines = ["\n"] - for val in x: - lines.append("0 0 0 0 0 "+str(val/var_scale)+"\n") - #end - fid.writelines(lines) - fid.close() - #end - - def obj_val(self,x): - # write inputs - self._write_input(x) - - # clear previous output and run direct solver - try: os.remove(self._objValFile) - except: pass - - try: - sp.call(self._objValCommand,shell=True) - with open(self._objValFile,"r") as fid: - lines = fid.readlines() - for col,name in enumerate(lines[0].split(",")): - if "TopComp" in name: - val = float(lines[1].split(",")[col]) - break - # the return code of mpirun is useless, we test the value of the function - self._assert_isfinite(val) - except: - raise RuntimeError("Objective function evaluation failed") - #end - - return val*obj_scale - #end - - def obj_der(self,x): - # inputs written in obj_val_driver - - # clear previous output and run direct solver - try: os.remove(self._objDerFile) - except: pass - N = x.shape[0] - y = np.ndarray((N,)) - - try: - # main command - sp.call(self._objDerCommand,shell=True) - - fid = open(self._objDerFile,"r"); lines = fid.readlines(); fid.close() - for i in range(N): - val = float(lines[i][0:-1]) - self._assert_isfinite(val) - y[i] = val*obj_scale/var_scale - #end - except: - raise RuntimeError("Objective gradient evaluation failed") - #end - - return y - #end - - def con_val(self,x): - # inputs written in obj_val_driver - - try: - with open(self._conValFile,"r") as fid: - lines = fid.readlines() - for col,name in enumerate(lines[0].split(",")): - if "VolFrac" in name: - val = float(lines[1].split(",")[col]) - break - self._assert_isfinite(val) - except: - raise RuntimeError("Constraint function evaluation failed") - #end - - return val*con_scale-1 - #end - - def con_der(self,x): - # inputs written in obj_val_driver - - # clear previous output and run solver - try: os.remove(self._conDerFile) - except: pass - N = x.shape[0] - y = np.ndarray((N,)) - - # read result - try: - sp.call(self._conDerCommand,shell=True) - - fid = open(self._conDerFile,"r"); lines = fid.readlines(); fid.close() - for i in range(N): - val = float(lines[i][0:-1]) - self._assert_isfinite(val) - y[i] = val*con_scale/var_scale - #end - except: - raise RuntimeError("Constraint function evaluation failed") - #end - - return y - #end -#end + def __init__(self, commands, inputFile, configFiles, outputFiles): + self._inputFile = inputFile + self._objValFile = "history.csv" + self._objDerFile = outputFiles[0] + self._conValFile = "history.csv" + self._conDerFile = outputFiles[1] + self._objValCommand = commands[0] + configFiles[0] + " > objval.stdout" + self._objDerCommand = commands[1] + configFiles[1] + " > objder.stdout" + self._conDerCommand = commands[1] + configFiles[2] + " > conval.stdout" + + # end + + def _assert_isfinite(self, val): + if math.isinf(val) or math.isnan(val): + raise ValueError + + # end + + def _write_input(self, x): + fid = open(self._inputFile, "w") + lines = ["\n"] + for val in x: + lines.append("0 0 0 0 0 " + str(val / var_scale) + "\n") + # end + fid.writelines(lines) + fid.close() + + # end + + def obj_val(self, x): + # write inputs + self._write_input(x) + + # clear previous output and run direct solver + try: + os.remove(self._objValFile) + except: + pass + + try: + sp.call(self._objValCommand, shell=True) + with open(self._objValFile, "r") as fid: + lines = fid.readlines() + for col, name in enumerate(lines[0].split(",")): + if "TopComp" in name: + val = float(lines[1].split(",")[col]) + break + # the return code of mpirun is useless, we test the value of the function + self._assert_isfinite(val) + except: + raise RuntimeError("Objective function evaluation failed") + # end + + return val * obj_scale + + # end + + def obj_der(self, x): + # inputs written in obj_val_driver + + # clear previous output and run direct solver + try: + os.remove(self._objDerFile) + except: + pass + N = x.shape[0] + y = np.ndarray((N,)) + + try: + # main command + sp.call(self._objDerCommand, shell=True) + + fid = open(self._objDerFile, "r") + lines = fid.readlines() + fid.close() + for i in range(N): + val = float(lines[i][0:-1]) + self._assert_isfinite(val) + y[i] = val * obj_scale / var_scale + # end + except: + raise RuntimeError("Objective gradient evaluation failed") + # end + + return y + + # end + + def con_val(self, x): + # inputs written in obj_val_driver + + try: + with open(self._conValFile, "r") as fid: + lines = fid.readlines() + for col, name in enumerate(lines[0].split(",")): + if "VolFrac" in name: + val = float(lines[1].split(",")[col]) + break + self._assert_isfinite(val) + except: + raise RuntimeError("Constraint function evaluation failed") + # end + + return val * con_scale - 1 + + # end + + def con_der(self, x): + # inputs written in obj_val_driver + + # clear previous output and run solver + try: + os.remove(self._conDerFile) + except: + pass + N = x.shape[0] + y = np.ndarray((N,)) + + # read result + try: + sp.call(self._conDerCommand, shell=True) + + fid = open(self._conDerFile, "r") + lines = fid.readlines() + fid.close() + for i in range(N): + val = float(lines[i][0:-1]) + self._assert_isfinite(val) + y[i] = val * con_scale / var_scale + # end + except: + raise RuntimeError("Constraint function evaluation failed") + # end + + return y + + # end + + +# end ####### Helpers ####### # updates the parameters in the config files -def update_settings(fnames,params): - for fname in fnames: - fid = open(fname,"r"); lines = fid.readlines(); fid.close() +def update_settings(fnames, params): + for fname in fnames: + fid = open(fname, "r") + lines = fid.readlines() + fid.close() - for param in params: - for i in range(len(lines)): - if lines[i].startswith(param.name()): - lines[i] = param.name()+"= "+repr(param.value())+"\n" - break - #end - #end - #end + for param in params: + for i in range(len(lines)): + if lines[i].startswith(param.name()): + lines[i] = param.name() + "= " + repr(param.value()) + "\n" + break + # end + # end + # end - fid = open(fname,"w"); fid.writelines(lines); fid.close() - #end -#end + fid = open(fname, "w") + fid.writelines(lines) + fid.close() + # end + + +# end # use a list as a function class ValueList: - def __init__(self,values): - self._values = values - self._ub = len(values)-1 - def val(self,idx): - return self._values[min(idx,self._ub)] -#end + def __init__(self, values): + self._values = values + self._ub = len(values) - 1 + + def val(self, idx): + return self._values[min(idx, self._ub)] + + +# end # helper class to hold parameters that are ramped class IncrParam: - def __init__(self,name,init,incr,maxi,func=None): - self._name = name - self._init = init - self._incr = incr - self._maxi = maxi - self._func = func - self._value = 0 - self.reset() - #end - - def name(self): - return self._name - - def reset(self): - self._value = self._init - - def update(self): - self._value = min(self._value+self._incr,self._maxi) - - def finished(self): - return self._value == self._maxi - - def value(self): - if self._func == None: - return self._value - else: - return self._func(self._value) - #end - #end -#end + def __init__(self, name, init, incr, maxi, func=None): + self._name = name + self._init = init + self._incr = incr + self._maxi = maxi + self._func = func + self._value = 0 + self.reset() + + # end + + def name(self): + return self._name + + def reset(self): + self._value = self._init + + def update(self): + self._value = min(self._value + self._incr, self._maxi) + + def finished(self): + return self._value == self._maxi + + def value(self): + if self._func == None: + return self._value + else: + return self._func(self._value) + # end + + # end + + +# end # Exterior penalty method wrapper class ExteriorPenaltyMethod: - def __init__(self,driver,r0=8,rmax=1024,c=2): - self._driver = driver - self._r = r0 - self._c = c - self._rmax = rmax - self._fval = 0 - self._hval = 0 - # timers - self._funTime = 0 - self._jacTime = 0 - #end - - def fun(self,x): - self._funTime -= time.time() - f = self._driver.obj_val(x) - h = self._driver.con_val(x) - self._funTime += time.time() - self._fval = f - self._hval = h - return f+self._r*max(0.0,h)*h - #end - - def jac(self,x): - self._jacTime -= time.time() - df = self._driver.obj_der(x) - dh = self._driver.con_der(x) - self._jacTime += time.time() - - # log current values of f and h - hisfile.write(repr(self._fval)+" "+repr(self._hval)+"\n") - hisfile.flush() - - return df+2*self._r*max(0.0,self._hval)*dh - #end - - def update(self): - self._r = min(self._r*self._c,self._rmax) - #end -#end + def __init__(self, driver, r0=8, rmax=1024, c=2): + self._driver = driver + self._r = r0 + self._c = c + self._rmax = rmax + self._fval = 0 + self._hval = 0 + # timers + self._funTime = 0 + self._jacTime = 0 + + # end + + def fun(self, x): + self._funTime -= time.time() + f = self._driver.obj_val(x) + h = self._driver.con_val(x) + self._funTime += time.time() + self._fval = f + self._hval = h + return f + self._r * max(0.0, h) * h + + # end + + def jac(self, x): + self._jacTime -= time.time() + df = self._driver.obj_der(x) + dh = self._driver.con_der(x) + self._jacTime += time.time() + + # log current values of f and h + hisfile.write(repr(self._fval) + " " + repr(self._hval) + "\n") + hisfile.flush() + + return df + 2 * self._r * max(0.0, self._hval) * dh + + # end + + def update(self): + self._r = min(self._r * self._c, self._rmax) + + # end + + +# end ####### RUN OPTIMIZATION ####### paramValues = ValueList(filterParam) -params = [IncrParam("TOPOL_OPTIM_KERNEL_PARAM",0,1,len(filterParam)-1,paramValues.val)] +params = [ + IncrParam("TOPOL_OPTIM_KERNEL_PARAM", 0, 1, len(filterParam) - 1, paramValues.val) +] -obj = ExteriorPenaltyMethod(Driver(commands,inputFile,fnames,outputFiles)) +obj = ExteriorPenaltyMethod(Driver(commands, inputFile, fnames, outputFiles)) -logfile = open("optimization.log","w") -hisfile = open("optimization.his","w") +logfile = open("optimization.log", "w") +hisfile = open("optimization.his", "w") line = "### Optimization Started ###\n" -print(line); logfile.write(line+"\n"); logfile.flush() +print(line) +logfile.write(line + "\n") +logfile.flush() totTime = -time.time() -nJacEval = 0; nFunEval = 0; itCount = 0; +nJacEval = 0 +nFunEval = 0 +itCount = 0 # initial values and bounds -fid = open(inputFile,"r"); N = len(fid.readlines())-1; fid.close() -x = np.ones((N,))*var_scale/con_scale +fid = open(inputFile, "r") +N = len(fid.readlines()) - 1 +fid.close() +x = np.ones((N,)) * var_scale / con_scale lb = np.zeros((N,)) -ub = np.ones((N,))*var_scale -bounds = np.array((lb,ub),float).transpose() +ub = np.ones((N,)) * var_scale +bounds = np.array((lb, ub), float).transpose() ## 1st Phase: Run with "gray" filter settings ## # get the constraint and function within some tolerance line = "1: Gray filter (initialization)" -print(line); logfile.write(line+"\n"); logfile.flush() +print(line) +logfile.write(line + "\n") +logfile.flush() -update_settings(fnames,params) +update_settings(fnames, params) success = False while nJacEval < maxJev_i: - options["maxiter"] = min(nJev_u,maxJev_i-nJacEval) - - optimum = scipy.optimize.minimize(obj.fun, x, method="L-BFGS-B", jac=obj.jac, - bounds=bounds, options=options) - itCount += 1 - x = optimum.x - nJacEval += optimum.nit - nFunEval += optimum.nfev - - line = " Iter {:d}: f= {:f} h= {:e} r= {:f} nfev= {:d} njev= {:d}".\ - format(itCount, obj._fval, obj._hval, obj._r, optimum.nfev, optimum.nit) - print(line); logfile.write(line+"\n"); logfile.flush() - - if obj._hval > htol: # increase penalty - obj.update() - elif optimum.success: # check convergence - success = True - break - else: # continue until convergence or maxJev_i - pass - #end -#end + options["maxiter"] = min(nJev_u, maxJev_i - nJacEval) + + optimum = scipy.optimize.minimize( + obj.fun, x, method="L-BFGS-B", jac=obj.jac, bounds=bounds, options=options + ) + itCount += 1 + x = optimum.x + nJacEval += optimum.nit + nFunEval += optimum.nfev + + line = " Iter {:d}: f= {:f} h= {:e} r= {:f} nfev= {:d} njev= {:d}".format( + itCount, obj._fval, obj._hval, obj._r, optimum.nfev, optimum.nit + ) + print(line) + logfile.write(line + "\n") + logfile.flush() + + if obj._hval > htol: # increase penalty + obj.update() + elif optimum.success: # check convergence + success = True + break + else: # continue until convergence or maxJev_i + pass + # end +# end tmp = inputFile.split(".") -shutil.copy(inputFile,tmp[0]+"_gray."+tmp[1]) +shutil.copy(inputFile, tmp[0] + "_gray." + tmp[1]) -if not(success): - line = " Initialization did not converge to desired tolerances" - print(line); logfile.write(line+"\n"); logfile.flush() -#end +if not (success): + line = " Initialization did not converge to desired tolerances" + print(line) + logfile.write(line + "\n") + logfile.flush() +# end ## 2nd Phase: Make filter more "black-white" ## line = "\n2: Black-White filter" -print(line); logfile.write(line+"\n"); logfile.flush() +print(line) +logfile.write(line + "\n") +logfile.flush() options["maxiter"] = nJev_u finalIter = False -while nJacEval < maxJev_t and not(finalIter): - finalIter = True - for i in range(len(params)): - params[i].update() - finalIter &= params[i].finished() - #end - update_settings(fnames,params) - if obj._hval > htol: obj.update() - - options["ftol"] = (ftol_u,ftol_f)[int(finalIter)] - options["maxiter"] = max(nJev_u,(maxJev_t-nJacEval)*int(finalIter)) - - optimum = scipy.optimize.minimize(obj.fun, x, method="L-BFGS-B", jac=obj.jac, - bounds=bounds, options=options) - itCount += 1 - x = optimum.x - nJacEval += optimum.nit - nFunEval += optimum.nfev - - line = " Iter {:d}: f= {:f} h= {:e} r= {:f} nfev= {:d} njev= {:d}".\ - format(itCount, obj._fval, obj._hval, obj._r, optimum.nfev, optimum.nit) - print(line); logfile.write(line+"\n"); logfile.flush() -#end +while nJacEval < maxJev_t and not (finalIter): + finalIter = True + for i in range(len(params)): + params[i].update() + finalIter &= params[i].finished() + # end + update_settings(fnames, params) + if obj._hval > htol: + obj.update() + + options["ftol"] = (ftol_u, ftol_f)[int(finalIter)] + options["maxiter"] = max(nJev_u, (maxJev_t - nJacEval) * int(finalIter)) + + optimum = scipy.optimize.minimize( + obj.fun, x, method="L-BFGS-B", jac=obj.jac, bounds=bounds, options=options + ) + itCount += 1 + x = optimum.x + nJacEval += optimum.nit + nFunEval += optimum.nfev + + line = " Iter {:d}: f= {:f} h= {:e} r= {:f} nfev= {:d} njev= {:d}".format( + itCount, obj._fval, obj._hval, obj._r, optimum.nfev, optimum.nit + ) + print(line) + logfile.write(line + "\n") + logfile.flush() +# end tmp = inputFile.split(".") -shutil.copy(inputFile,tmp[0]+"_bw."+tmp[1]) +shutil.copy(inputFile, tmp[0] + "_bw." + tmp[1]) success = finalIter and obj._hval < htol and optimum.success totTime += time.time() -line = "\n### Optimization Finished ###\n"+\ - "Summary: "+("Failure\n","Success\n")[int(success)]+\ - " fval: {:f} hval: {:e}\n".format(obj._fval,obj._hval)+\ - "Details:\n"+\ - " iter: {:d} ttot: {:f}s\n".format(itCount,totTime)+\ - " nfev: {:d} tfev: {:f}s\n".format(nFunEval,obj._funTime)+\ - " njev: {:d} tjev: {:f}s\n".format(nJacEval,obj._jacTime) -print(line); logfile.write(line+"\n") +line = ( + "\n### Optimization Finished ###\n" + + "Summary: " + + ("Failure\n", "Success\n")[int(success)] + + " fval: {:f} hval: {:e}\n".format(obj._fval, obj._hval) + + "Details:\n" + + " iter: {:d} ttot: {:f}s\n".format(itCount, totTime) + + " nfev: {:d} tfev: {:f}s\n".format(nFunEval, obj._funTime) + + " njev: {:d} tjev: {:f}s\n".format(nJacEval, obj._jacTime) +) +print(line) +logfile.write(line + "\n") logfile.close() hisfile.close() - diff --git a/SU2_PY/updateHistoryMap.py b/SU2_PY/updateHistoryMap.py index 8f4dca9972e..d391dfa9d83 100644 --- a/SU2_PY/updateHistoryMap.py +++ b/SU2_PY/updateHistoryMap.py @@ -26,79 +26,82 @@ # License along with SU2. If not, see . import os, pprint -su2_home = os.environ['SU2_HOME'] +su2_home = os.environ["SU2_HOME"] -fileList = ['CFlowOutput.cpp', -'CFlowIncOutput.cpp', -'CFlowCompOutput.cpp', -'CHeatOutput.cpp', -'CFlowCompFEMOutput.cpp', -'CElasticityOutput.cpp', -'CAdjFlowOutput.cpp', -'CAdjHeatOutput.cpp', -'CAdjFlowIncOutput.cpp', -'CAdjFlowCompOutput.cpp', -'CAdjElasticityOutput.cpp'] +fileList = [ + "CFlowOutput.cpp", + "CFlowIncOutput.cpp", + "CFlowCompOutput.cpp", + "CHeatOutput.cpp", + "CFlowCompFEMOutput.cpp", + "CElasticityOutput.cpp", + "CAdjFlowOutput.cpp", + "CAdjHeatOutput.cpp", + "CAdjFlowIncOutput.cpp", + "CAdjFlowCompOutput.cpp", + "CAdjElasticityOutput.cpp", +] + +fileList = [os.path.join(su2_home, "SU2_CFD/src/output/" + i) for i in fileList] -fileList = [os.path.join(su2_home, 'SU2_CFD/src/output/' + i) for i in fileList] def parse_output(files): outputFields = dict() for file in files: - print('Parsing ' + file) - f = open(file,'r') - while(1): - s = f.readline().strip(' ') + print("Parsing " + file) + f = open(file, "r") + while 1: + s = f.readline().strip(" ") if not s: break - if s.startswith('AddHistoryOutput('): - s = s.replace('AddHistoryOutput', '').strip('()').split(',') + if s.startswith("AddHistoryOutput("): + s = s.replace("AddHistoryOutput", "").strip("()").split(",") curOutputField = dict() name = s[0].strip(' ()"\n;') - curOutputField['HEADER'] = s[1].strip(' ()"\n;') - curOutputField['GROUP'] = s[3].strip(' ()"\n;') - curOutputField['DESCRIPTION'] = s[4].strip(' ()"\n;') + curOutputField["HEADER"] = s[1].strip(' ()"\n;') + curOutputField["GROUP"] = s[3].strip(' ()"\n;') + curOutputField["DESCRIPTION"] = s[4].strip(' ()"\n;') if len(s) == 6: - curOutputField['TYPE'] = s[5].strip(' ()"\n;').split('::')[1] + curOutputField["TYPE"] = s[5].strip(' ()"\n;').split("::")[1] else: - curOutputField['TYPE'] = 'DEFAULT' + curOutputField["TYPE"] = "DEFAULT" outputFields[name] = curOutputField f.close() addedOutputFields = dict() for field in outputFields: - if outputFields[field]['TYPE'] == 'COEFFICIENT': + if outputFields[field]["TYPE"] == "COEFFICIENT": curOutputField = dict() - name = 'D_' + field - curOutputField['HEADER'] = 'd[' + outputFields[field]['HEADER'] + ']' - curOutputField['GROUP'] = 'D_' + outputFields[field]['GROUP'] - curOutputField['TYPE'] = 'D_COEFFICIENT' - curOutputField['DESCRIPTION'] = 'Derivative value' + name = "D_" + field + curOutputField["HEADER"] = "d[" + outputFields[field]["HEADER"] + "]" + curOutputField["GROUP"] = "D_" + outputFields[field]["GROUP"] + curOutputField["TYPE"] = "D_COEFFICIENT" + curOutputField["DESCRIPTION"] = "Derivative value" addedOutputFields[name] = curOutputField - name = 'TAVG_' + field + name = "TAVG_" + field curOutputField = dict() - curOutputField['HEADER'] = 'tavg[' + outputFields[field]['HEADER'] + ']' - curOutputField['GROUP'] = 'TAVG_' + outputFields[field]['GROUP'] - curOutputField['TYPE'] = 'TAVG_COEFFICIENT' - curOutputField['DESCRIPTION'] = 'weighted time average value' + curOutputField["HEADER"] = "tavg[" + outputFields[field]["HEADER"] + "]" + curOutputField["GROUP"] = "TAVG_" + outputFields[field]["GROUP"] + curOutputField["TYPE"] = "TAVG_COEFFICIENT" + curOutputField["DESCRIPTION"] = "weighted time average value" addedOutputFields[name] = curOutputField - name = 'TAVG_D_' + field + name = "TAVG_D_" + field curOutputField = dict() - curOutputField['HEADER'] = 'dtavg[' + outputFields[field]['HEADER'] + ']' - curOutputField['GROUP'] = 'TAVG_D_' + outputFields[field]['GROUP'] - curOutputField['TYPE'] = 'TAVG_D_COEFFICIENT' - curOutputField['DESCRIPTION'] = 'weighted time average derivative value' + curOutputField["HEADER"] = "dtavg[" + outputFields[field]["HEADER"] + "]" + curOutputField["GROUP"] = "TAVG_D_" + outputFields[field]["GROUP"] + curOutputField["TYPE"] = "TAVG_D_COEFFICIENT" + curOutputField["DESCRIPTION"] = "weighted time average derivative value" addedOutputFields[name] = curOutputField - outputFields.update(addedOutputFields) - f = open(os.path.join(su2_home, 'SU2_PY/SU2/io/historyMap.py'), 'w') - f.write('history_header_map = ') + f = open(os.path.join(su2_home, "SU2_PY/SU2/io/historyMap.py"), "w") + f.write("history_header_map = ") pprint.pprint(outputFields, f) f.close() + parse_output(fileList) diff --git a/SU2_SOL/include/SU2_SOL.hpp b/SU2_SOL/include/SU2_SOL.hpp index 8be627e7f17..47e9c842f15 100644 --- a/SU2_SOL/include/SU2_SOL.hpp +++ b/SU2_SOL/include/SU2_SOL.hpp @@ -26,7 +26,6 @@ * License along with SU2. If not, see . */ - #pragma once #include "../../Common/include/parallelization/mpi_structure.hpp" @@ -37,7 +36,7 @@ #include "../../Common/include/geometry/CPhysicalGeometry.hpp" #include "../../Common/include/CConfig.hpp" - -void WriteFiles(CConfig *config, CGeometry* geometry, CSolver** solver_container, COutput* output, unsigned long TimeIter); +void WriteFiles(CConfig* config, CGeometry* geometry, CSolver** solver_container, COutput* output, + unsigned long TimeIter); using namespace std; diff --git a/SU2_SOL/src/SU2_SOL.cpp b/SU2_SOL/src/SU2_SOL.cpp index cf71364744e..feeeb4ca74a 100644 --- a/SU2_SOL/src/SU2_SOL.cpp +++ b/SU2_SOL/src/SU2_SOL.cpp @@ -25,13 +25,11 @@ * License along with SU2. If not, see . */ - #include "../include/SU2_SOL.hpp" using namespace std; -int main(int argc, char *argv[]) { - +int main(int argc, char* argv[]) { unsigned short iZone, iInst; su2double StartTime = 0.0, StopTime = 0.0, UsedTime = 0.0; @@ -39,7 +37,7 @@ int main(int argc, char *argv[]) { /*--- MPI initialization ---*/ - SU2_MPI::Init(&argc,&argv); + SU2_MPI::Init(&argc, &argv); SU2_MPI::Comm MPICommunicator = SU2_MPI::GetComm(); const int rank = SU2_MPI::GetRank(); @@ -47,32 +45,35 @@ int main(int argc, char *argv[]) { /*--- Pointer to different structures that will be used throughout the entire code ---*/ - COutput **output = nullptr; - CGeometry ***geometry_container = nullptr; - CSolver ***solver_container = nullptr; - CConfig **config_container = nullptr; - CConfig *driver_config = nullptr; - unsigned short *nInst = nullptr; + COutput** output = nullptr; + CGeometry*** geometry_container = nullptr; + CSolver*** solver_container = nullptr; + CConfig** config_container = nullptr; + CConfig* driver_config = nullptr; + unsigned short* nInst = nullptr; /*--- Load in the number of zones and spatial dimensions in the mesh file (if no config file is specified, default.cfg is used) ---*/ - if (argc == 2 || argc == 3) { strcpy(config_file_name,argv[1]); } - else { strcpy(config_file_name, "default.cfg"); } + if (argc == 2 || argc == 3) { + strcpy(config_file_name, argv[1]); + } else { + strcpy(config_file_name, "default.cfg"); + } - CConfig *config = nullptr; + CConfig* config = nullptr; config = new CConfig(config_file_name, SU2_COMPONENT::SU2_SOL); const auto nZone = config->GetnZone(); /*--- Definition of the containers per zones ---*/ - solver_container = new CSolver**[nZone] (); - config_container = new CConfig*[nZone] (); - geometry_container = new CGeometry**[nZone] (); + solver_container = new CSolver**[nZone](); + config_container = new CConfig*[nZone](); + geometry_container = new CGeometry**[nZone](); nInst = new unsigned short[nZone]; driver_config = nullptr; - output = new COutput*[nZone] (); + output = new COutput*[nZone](); for (iZone = 0; iZone < nZone; iZone++) { nInst[iZone] = 1; @@ -92,21 +93,19 @@ int main(int argc, char *argv[]) { differential equation on a single block, unstructured mesh. ---*/ for (iZone = 0; iZone < nZone; iZone++) { - /*--- Definition of the configuration option class for all zones. In this constructor, the input configuration file is parsed and all options are read and stored. ---*/ - if (driver_config->GetnConfigFiles() > 0){ + if (driver_config->GetnConfigFiles() > 0) { strcpy(zone_file_name, driver_config->GetConfigFilename(iZone).c_str()); config_container[iZone] = new CConfig(driver_config, zone_file_name, SU2_COMPONENT::SU2_SOL, iZone, nZone, true); - } - else{ - config_container[iZone] = new CConfig(driver_config, config_file_name, SU2_COMPONENT::SU2_SOL, iZone, nZone, true); + } else { + config_container[iZone] = + new CConfig(driver_config, config_file_name, SU2_COMPONENT::SU2_SOL, iZone, nZone, true); } config_container[iZone]->SetMPICommunicator(MPICommunicator); - } /*--- Set the multizone part of the problem. ---*/ @@ -119,7 +118,6 @@ int main(int argc, char *argv[]) { /*--- Read the geometry for each zone ---*/ for (iZone = 0; iZone < nZone; iZone++) { - /*--- Determine whether or not the FEM solver is used, which decides the type of geometry classes that are instantiated. ---*/ const bool fem_solver = config_container[iZone]->GetFEMSolver(); @@ -131,8 +129,7 @@ int main(int argc, char *argv[]) { geometry_container[iZone] = new CGeometry*[nInst[iZone]]; solver_container[iZone] = new CSolver*[nInst[iZone]]; - for (iInst = 0; iInst < nInst[iZone]; iInst++){ - + for (iInst = 0; iInst < nInst[iZone]; iInst++) { /*--- Allocate solver. ---*/ solver_container[iZone][iInst] = nullptr; @@ -140,7 +137,7 @@ int main(int argc, char *argv[]) { /*--- Definition of the geometry class to store the primal grid in the partitioning process. ---*/ - CGeometry *geometry_aux = nullptr; + CGeometry* geometry_aux = nullptr; /*--- All ranks process the grid and call ParMETIS for partitioning ---*/ @@ -148,8 +145,10 @@ int main(int argc, char *argv[]) { /*--- Color the initial grid and set the send-receive domains (ParMETIS) ---*/ - if ( fem_solver ) geometry_aux->SetColorFEMGrid_Parallel(config_container[iZone]); - else geometry_aux->SetColorGrid_Parallel(config_container[iZone]); + if (fem_solver) + geometry_aux->SetColorFEMGrid_Parallel(config_container[iZone]); + else + geometry_aux->SetColorGrid_Parallel(config_container[iZone]); /*--- Allocate the memory of the current domain, and divide the grid between the nodes ---*/ @@ -157,15 +156,14 @@ int main(int argc, char *argv[]) { /*--- Build the grid data structures using the ParMETIS coloring. ---*/ - if( fem_solver ) { - switch( config_container[iZone]->GetKind_FEM_Flow() ) { + if (fem_solver) { + switch (config_container[iZone]->GetKind_FEM_Flow()) { case DG: { geometry_container[iZone][iInst] = new CMeshFEM_DG(geometry_aux, config_container[iZone]); break; } } - } - else { + } else { geometry_container[iZone][iInst] = new CPhysicalGeometry(geometry_aux, config_container[iZone]); } @@ -183,7 +181,7 @@ int main(int argc, char *argv[]) { /*--- Create the vertex structure (required for MPI) ---*/ - if (rank == MASTER_NODE) cout << "Identify vertices." <SetVertex(config_container[iZone]); /*--- Store the global to local mapping after preprocessing. ---*/ @@ -193,15 +191,15 @@ int main(int argc, char *argv[]) { /*--- Create the point-to-point MPI communication structures for the fvm solver. ---*/ - if (!fem_solver) geometry_container[iZone][iInst]->PreprocessP2PComms(geometry_container[iZone][iInst], config_container[iZone]); + if (!fem_solver) + geometry_container[iZone][iInst]->PreprocessP2PComms(geometry_container[iZone][iInst], config_container[iZone]); /* Test for a fem solver, because some more work must be done. */ if (fem_solver) { - /*--- Carry out a dynamic cast to CMeshFEM_DG, such that it is not needed to define all virtual functions in the base class CGeometry. ---*/ - CMeshFEM_DG *DGMesh = dynamic_cast(geometry_container[iZone][iInst]); + CMeshFEM_DG* DGMesh = dynamic_cast(geometry_container[iZone][iInst]); /*--- Determine the standard elements for the volume elements. ---*/ if (rank == MASTER_NODE) cout << "Creating standard volume elements." << endl; @@ -213,7 +211,6 @@ int main(int argc, char *argv[]) { DGMesh->CreateFaces(config_container[iZone]); } } - } const bool fsi = config_container[ZONE_0]->GetFSI_Simulation(); @@ -224,17 +221,15 @@ int main(int argc, char *argv[]) { StartTime = SU2_MPI::Wtime(); if (rank == MASTER_NODE) - cout << endl <<"------------------------- Solution Postprocessing -----------------------" << endl; + cout << endl << "------------------------- Solution Postprocessing -----------------------" << endl; /*--- Check whether this is an FSI, fluid unsteady, harmonic balance or structural dynamic simulation and call the solution merging routines accordingly.---*/ if (multizone) { - bool TimeDomain = driver_config->GetTime_Domain(); - if (TimeDomain){ - + if (TimeDomain) { su2double Physical_dt, Physical_t; unsigned long TimeIter = 0; bool StopCalc = false; @@ -243,83 +238,81 @@ int main(int argc, char *argv[]) { Physical_dt = driver_config->GetTime_Step(); /*--- Check for an unsteady restart. Update TimeIter if necessary. ---*/ - if (driver_config->GetRestart()){ + if (driver_config->GetRestart()) { TimeIter = driver_config->GetRestart_Iter(); } /*--- Instantiate the solvers for each zone. ---*/ - for (iZone = 0; iZone < nZone; iZone++){ + for (iZone = 0; iZone < nZone; iZone++) { config_container[iZone]->SetiInst(INST_0); config_container[iZone]->SetTimeIter(TimeIter); - solver_container[iZone][INST_0] = new CBaselineSolver(geometry_container[iZone][INST_0], config_container[iZone]); + solver_container[iZone][INST_0] = + new CBaselineSolver(geometry_container[iZone][INST_0], config_container[iZone]); - output[iZone] = new CBaselineOutput(config_container[iZone], geometry_container[iZone][INST_0]->GetnDim(), solver_container[iZone][INST_0]); + output[iZone] = new CBaselineOutput(config_container[iZone], geometry_container[iZone][INST_0]->GetnDim(), + solver_container[iZone][INST_0]); output[iZone]->PreprocessVolumeOutput(config_container[iZone]); output[iZone]->PreprocessHistoryOutput(config_container[iZone], false); - } /*--- Loop over the whole time domain ---*/ while (TimeIter < driver_config->GetnTime_Iter()) { - /*--- Check if the maximum time has been surpassed. ---*/ - Physical_t = (TimeIter+1)*Physical_dt; - if (Physical_t >= driver_config->GetMax_Time()) - StopCalc = true; - - if ((TimeIter+1 == driver_config->GetnTime_Iter()) || // The last time iteration - (StopCalc) || // We have surpassed the requested time - ((TimeIter == 0) || (TimeIter % config_container[ZONE_0]->GetVolumeOutputFrequency(0) == 0)) // The iteration has been requested - ){ - if (rank == MASTER_NODE) cout << "Writing the volume solution for time step " << TimeIter << ", t = " << Physical_t << " s ." << endl; + Physical_t = (TimeIter + 1) * Physical_dt; + if (Physical_t >= driver_config->GetMax_Time()) StopCalc = true; + + if ((TimeIter + 1 == driver_config->GetnTime_Iter()) || // The last time iteration + (StopCalc) || // We have surpassed the requested time + ((TimeIter == 0) || (TimeIter % config_container[ZONE_0]->GetVolumeOutputFrequency(0) == + 0)) // The iteration has been requested + ) { + if (rank == MASTER_NODE) + cout << "Writing the volume solution for time step " << TimeIter << ", t = " << Physical_t << " s ." + << endl; /*--- Load the restart for all the zones. ---*/ - for (iZone = 0; iZone < nZone; iZone++){ - + for (iZone = 0; iZone < nZone; iZone++) { /*--- Set the current iteration number in the config class. ---*/ config_container[iZone]->SetTimeIter(TimeIter); /*--- So far, only enabled for single-instance problems ---*/ config_container[iZone]->SetiInst(INST_0); - solver_container[iZone][INST_0]->LoadRestart(geometry_container[iZone], &solver_container[iZone], config_container[iZone], TimeIter, true); + solver_container[iZone][INST_0]->LoadRestart(geometry_container[iZone], &solver_container[iZone], + config_container[iZone], TimeIter, true); } - - for (iZone = 0; iZone < nZone; iZone++){ - - WriteFiles(config_container[iZone], geometry_container[iZone][INST_0], &solver_container[iZone][INST_0], output[iZone], TimeIter); - + for (iZone = 0; iZone < nZone; iZone++) { + WriteFiles(config_container[iZone], geometry_container[iZone][INST_0], &solver_container[iZone][INST_0], + output[iZone], TimeIter); } } TimeIter++; if (StopCalc) break; } - } - else { - + } else { /*--- Steady simulation: merge the solution files for each zone. ---*/ for (iZone = 0; iZone < nZone; iZone++) { config_container[iZone]->SetiInst(INST_0); /*--- Definition of the solution class ---*/ - solver_container[iZone][INST_0] = new CBaselineSolver(geometry_container[iZone][INST_0], config_container[iZone]); - solver_container[iZone][INST_0]->LoadRestart(geometry_container[iZone], &solver_container[iZone], config_container[iZone], 0, true); - output[iZone] = new CBaselineOutput(config_container[iZone], geometry_container[iZone][INST_0]->GetnDim(), solver_container[iZone][INST_0]); + solver_container[iZone][INST_0] = + new CBaselineSolver(geometry_container[iZone][INST_0], config_container[iZone]); + solver_container[iZone][INST_0]->LoadRestart(geometry_container[iZone], &solver_container[iZone], + config_container[iZone], 0, true); + output[iZone] = new CBaselineOutput(config_container[iZone], geometry_container[iZone][INST_0]->GetnDim(), + solver_container[iZone][INST_0]); output[iZone]->PreprocessVolumeOutput(config_container[iZone]); output[iZone]->PreprocessHistoryOutput(config_container[iZone], false); - } - for (iZone = 0; iZone < nZone; iZone++){ - - WriteFiles(config_container[iZone], geometry_container[iZone][INST_0], &solver_container[iZone][INST_0], output[iZone], 0); - + for (iZone = 0; iZone < nZone; iZone++) { + WriteFiles(config_container[iZone], geometry_container[iZone][INST_0], &solver_container[iZone][INST_0], + output[iZone], 0); } } - } - else if (fsi){ - - if (nZone < 2){ - SU2_MPI::Error("For multizone computations, please add the number of zones as a second argument for SU2_SOL.", CURRENT_FUNCTION); + } else if (fsi) { + if (nZone < 2) { + SU2_MPI::Error("For multizone computations, please add the number of zones as a second argument for SU2_SOL.", + CURRENT_FUNCTION); } su2double Physical_dt, Physical_t; @@ -328,29 +321,25 @@ int main(int argc, char *argv[]) { bool SolutionInstantiatedFlow = false, SolutionInstantiatedFEM = false; /*--- Check for an unsteady restart. Update ExtIter if necessary. ---*/ - if (config_container[ZONE_0]->GetRestart()){ + if (config_container[ZONE_0]->GetRestart()) { TimeIterFlow = config_container[ZONE_0]->GetRestart_Iter(); TimeIterFEM = config_container[ZONE_1]->GetRestart_Iter(); if (TimeIterFlow != TimeIterFEM) { - SU2_MPI::Error("For multizone computations, please add the number of zones as a second argument for SU2_SOL.", CURRENT_FUNCTION); - } - else { + SU2_MPI::Error("For multizone computations, please add the number of zones as a second argument for SU2_SOL.", + CURRENT_FUNCTION); + } else { TimeIter = TimeIterFlow; } } - while (TimeIter < config_container[ZONE_0]->GetnTime_Iter()) { - /*--- Check several conditions in order to merge the correct time step files. ---*/ Physical_dt = config_container[ZONE_0]->GetDelta_UnstTime(); - Physical_t = (TimeIter+1)*Physical_dt; - if (Physical_t >= config_container[ZONE_0]->GetTotal_UnstTime()) - StopCalc = true; + Physical_t = (TimeIter + 1) * Physical_dt; + if (Physical_t >= config_container[ZONE_0]->GetTotal_UnstTime()) StopCalc = true; - if ( - ((TimeIter+1 == config_container[ZONE_0]->GetnTime_Iter()) || + if (((TimeIter + 1 == config_container[ZONE_0]->GetnTime_Iter()) || ((TimeIter % config_container[ZONE_0]->GetVolumeOutputFrequency(0) == 0) && (TimeIter != 0) && !((config_container[ZONE_0]->GetTime_Marching() == TIME_MARCHING::DT_STEPPING_1ST) || (config_container[ZONE_0]->GetTime_Marching() == TIME_MARCHING::DT_STEPPING_2ND))) || @@ -361,13 +350,11 @@ int main(int argc, char *argv[]) { && - ((TimeIter+1 == config_container[ZONE_1]->GetnTime_Iter()) || - (StopCalc) || + ((TimeIter + 1 == config_container[ZONE_1]->GetnTime_Iter()) || (StopCalc) || ((config_container[ZONE_1]->GetTime_Domain()) && ((TimeIter == 0) || (TimeIter % config_container[ZONE_1]->GetVolumeOutputFrequency(0) == 0)))) - ){ - + ) { /*--- Set the current iteration number in the config class. ---*/ config_container[ZONE_0]->SetTimeIter(TimeIter); config_container[ZONE_1]->SetTimeIter(TimeIter); @@ -377,38 +364,46 @@ int main(int argc, char *argv[]) { /*--- For the fluid zone (ZONE_0) ---*/ /*--- Either instantiate the solution class or load a restart file. ---*/ if (SolutionInstantiatedFlow == false && - (TimeIter == 0 || ((config_container[ZONE_0]->GetRestart() && (SU2_TYPE::Int(TimeIter) == SU2_TYPE::Int(config_container[ZONE_0]->GetRestart_Iter()))) || - TimeIter % config_container[ZONE_0]->GetVolumeOutputFrequency(0) == 0 || - TimeIter+1 == config_container[ZONE_0]->GetnTime_Iter()))) { - solver_container[ZONE_0][INST_0] = new CBaselineSolver(geometry_container[ZONE_0][INST_0], config_container[ZONE_0]); - output[ZONE_0] = new CBaselineOutput(config_container[ZONE_0], geometry_container[ZONE_0][INST_0]->GetnDim(), solver_container[ZONE_0][INST_0]); + (TimeIter == 0 || + ((config_container[ZONE_0]->GetRestart() && + (SU2_TYPE::Int(TimeIter) == SU2_TYPE::Int(config_container[ZONE_0]->GetRestart_Iter()))) || + TimeIter % config_container[ZONE_0]->GetVolumeOutputFrequency(0) == 0 || + TimeIter + 1 == config_container[ZONE_0]->GetnTime_Iter()))) { + solver_container[ZONE_0][INST_0] = + new CBaselineSolver(geometry_container[ZONE_0][INST_0], config_container[ZONE_0]); + output[ZONE_0] = new CBaselineOutput(config_container[ZONE_0], geometry_container[ZONE_0][INST_0]->GetnDim(), + solver_container[ZONE_0][INST_0]); output[ZONE_0]->PreprocessVolumeOutput(config_container[ZONE_0]); output[ZONE_0]->PreprocessHistoryOutput(config_container[ZONE_0], false); SolutionInstantiatedFlow = true; } - solver_container[ZONE_0][INST_0]->LoadRestart_FSI(geometry_container[ZONE_0][INST_0], config_container[ZONE_0], TimeIter); - + solver_container[ZONE_0][INST_0]->LoadRestart_FSI(geometry_container[ZONE_0][INST_0], config_container[ZONE_0], + TimeIter); /*--- For the structural zone (ZONE_1) ---*/ /*--- Either instantiate the solution class or load a restart file. ---*/ /*--- Either instantiate the solution class or load a restart file. ---*/ if (SolutionInstantiatedFEM == false && - (TimeIter == 0 || ((config_container[ZONE_1]->GetRestart() && (SU2_TYPE::Int(TimeIter) == SU2_TYPE::Int(config_container[ZONE_1]->GetRestart_Iter()))) || - TimeIter % config_container[ZONE_1]->GetVolumeOutputFrequency(0) == 0 || - TimeIter+1 == config_container[ZONE_1]->GetnTime_Iter()))) { - solver_container[ZONE_1][INST_0] = new CBaselineSolver(geometry_container[ZONE_1][INST_0], config_container[ZONE_1]); - output[ZONE_1] = new CBaselineOutput(config_container[ZONE_1], geometry_container[ZONE_1][INST_0]->GetnDim(), solver_container[ZONE_1][INST_0]); + (TimeIter == 0 || + ((config_container[ZONE_1]->GetRestart() && + (SU2_TYPE::Int(TimeIter) == SU2_TYPE::Int(config_container[ZONE_1]->GetRestart_Iter()))) || + TimeIter % config_container[ZONE_1]->GetVolumeOutputFrequency(0) == 0 || + TimeIter + 1 == config_container[ZONE_1]->GetnTime_Iter()))) { + solver_container[ZONE_1][INST_0] = + new CBaselineSolver(geometry_container[ZONE_1][INST_0], config_container[ZONE_1]); + output[ZONE_1] = new CBaselineOutput(config_container[ZONE_1], geometry_container[ZONE_1][INST_0]->GetnDim(), + solver_container[ZONE_1][INST_0]); output[ZONE_1]->PreprocessVolumeOutput(config_container[ZONE_1]); SolutionInstantiatedFEM = true; } - solver_container[ZONE_1][INST_0]->LoadRestart_FSI(geometry_container[ZONE_1][INST_0], config_container[ZONE_1], TimeIter); + solver_container[ZONE_1][INST_0]->LoadRestart_FSI(geometry_container[ZONE_1][INST_0], config_container[ZONE_1], + TimeIter); if (rank == MASTER_NODE) cout << "Writing the volume solution for time step " << TimeIter << "." << endl; - for (iZone = 0; iZone < nZone; iZone++){ - - WriteFiles(config_container[iZone], geometry_container[iZone][INST_0], &solver_container[iZone][INST_0], output[iZone], TimeIter); - + for (iZone = 0; iZone < nZone; iZone++) { + WriteFiles(config_container[iZone], geometry_container[iZone][INST_0], &solver_container[iZone][INST_0], + output[iZone], TimeIter); } } @@ -417,70 +412,63 @@ int main(int argc, char *argv[]) { } } else if (fem_solver) { - if (config->GetTime_Domain()) { - /*--- Unsteady DG simulation: merge all unsteady time steps. First, find the frequency and total number of files to write. ---*/ su2double Physical_dt, Physical_t; unsigned long TimeIter = 0; bool StopCalc = false; - bool *SolutionInstantiated = new bool[nZone]; + bool* SolutionInstantiated = new bool[nZone]; - for (iZone = 0; iZone < nZone; iZone++) - SolutionInstantiated[iZone] = false; + for (iZone = 0; iZone < nZone; iZone++) SolutionInstantiated[iZone] = false; /*--- Check for an unsteady restart. Update ExtIter if necessary. ---*/ if (config_container[ZONE_0]->GetTime_Domain() && config_container[ZONE_0]->GetRestart()) TimeIter = config_container[ZONE_0]->GetRestart_Iter(); while (TimeIter < config_container[ZONE_0]->GetnTime_Iter()) { - /*--- Check several conditions in order to merge the correct time step files. ---*/ Physical_dt = config_container[ZONE_0]->GetDelta_UnstTime(); - Physical_t = (TimeIter+1)*Physical_dt; - if (Physical_t >= config_container[ZONE_0]->GetTotal_UnstTime()) - StopCalc = true; + Physical_t = (TimeIter + 1) * Physical_dt; + if (Physical_t >= config_container[ZONE_0]->GetTotal_UnstTime()) StopCalc = true; - if ((TimeIter+1 == config_container[ZONE_0]->GetnTime_Iter()) || + if ((TimeIter + 1 == config_container[ZONE_0]->GetnTime_Iter()) || ((TimeIter % config_container[ZONE_0]->GetVolumeOutputFrequency(0) == 0) && (TimeIter != 0) && !(config_container[ZONE_0]->GetTime_Marching() == TIME_MARCHING::TIME_STEPPING)) || (StopCalc) || ((config_container[ZONE_0]->GetTime_Marching() == TIME_MARCHING::TIME_STEPPING) && ((TimeIter == 0) || (TimeIter % config_container[ZONE_0]->GetVolumeOutputFrequency(0) == 0)))) { + /*--- Read in the restart file for this time step ---*/ + for (iZone = 0; iZone < nZone; iZone++) { + /*--- Set the current iteration number in the config class. ---*/ + config_container[iZone]->SetTimeIter(TimeIter); - /*--- Read in the restart file for this time step ---*/ - for (iZone = 0; iZone < nZone; iZone++) { - - /*--- Set the current iteration number in the config class. ---*/ - config_container[iZone]->SetTimeIter(TimeIter); - - /*--- Either instantiate the solution class or load a restart file. ---*/ - if (SolutionInstantiated[iZone] == false && - (TimeIter == 0 || - (config_container[ZONE_0]->GetRestart() && ((long)TimeIter == SU2_TYPE::Int(config_container[ZONE_0]->GetRestart_Iter()) || - TimeIter % config_container[ZONE_0]->GetVolumeOutputFrequency(0) == 0 || - TimeIter+1 == config_container[ZONE_0]->GetnTime_Iter())))) { - - solver_container[iZone][INST_0] = new CBaselineSolver_FEM(geometry_container[iZone][INST_0], config_container[iZone]); - output[iZone] = new CBaselineOutput(config_container[ZONE_0], geometry_container[ZONE_0][INST_0]->GetnDim(), solver_container[ZONE_0][INST_0]); - output[iZone]->PreprocessVolumeOutput(config_container[ZONE_0]); - output[iZone]->PreprocessHistoryOutput(config_container[ZONE_0], false); - SolutionInstantiated[iZone] = true; - } - solver_container[iZone][INST_0]->LoadRestart(&geometry_container[iZone][INST_0], &solver_container[iZone], - config_container[iZone], (int)TimeIter, true); - } - - if (rank == MASTER_NODE) - cout << "Writing the volume solution for time step " << TimeIter << "." << endl; - - for (iZone = 0; iZone < nZone; iZone++){ + /*--- Either instantiate the solution class or load a restart file. ---*/ + if (SolutionInstantiated[iZone] == false && + (TimeIter == 0 || (config_container[ZONE_0]->GetRestart() && + ((long)TimeIter == SU2_TYPE::Int(config_container[ZONE_0]->GetRestart_Iter()) || + TimeIter % config_container[ZONE_0]->GetVolumeOutputFrequency(0) == 0 || + TimeIter + 1 == config_container[ZONE_0]->GetnTime_Iter())))) { + solver_container[iZone][INST_0] = + new CBaselineSolver_FEM(geometry_container[iZone][INST_0], config_container[iZone]); + output[iZone] = + new CBaselineOutput(config_container[ZONE_0], geometry_container[ZONE_0][INST_0]->GetnDim(), + solver_container[ZONE_0][INST_0]); + output[iZone]->PreprocessVolumeOutput(config_container[ZONE_0]); + output[iZone]->PreprocessHistoryOutput(config_container[ZONE_0], false); + SolutionInstantiated[iZone] = true; + } + solver_container[iZone][INST_0]->LoadRestart(&geometry_container[iZone][INST_0], &solver_container[iZone], + config_container[iZone], (int)TimeIter, true); + } - WriteFiles(config_container[iZone], geometry_container[iZone][INST_0], &solver_container[iZone][INST_0], output[iZone], TimeIter); + if (rank == MASTER_NODE) cout << "Writing the volume solution for time step " << TimeIter << "." << endl; - } + for (iZone = 0; iZone < nZone; iZone++) { + WriteFiles(config_container[iZone], geometry_container[iZone][INST_0], &solver_container[iZone][INST_0], + output[iZone], TimeIter); + } } TimeIter++; @@ -488,55 +476,50 @@ int main(int argc, char *argv[]) { } } else { + /*--- Steady simulation: merge the single solution file. ---*/ - /*--- Steady simulation: merge the single solution file. ---*/ - - for (iZone = 0; iZone < nZone; iZone++) { - /*--- Definition of the solution class ---*/ - - solver_container[iZone][INST_0] = new CBaselineSolver_FEM(geometry_container[iZone][INST_0], config_container[iZone]); - output[iZone] = new CBaselineOutput(config_container[ZONE_0], geometry_container[ZONE_0][INST_0]->GetnDim(), solver_container[ZONE_0][INST_0]); - output[iZone]->PreprocessVolumeOutput(config_container[ZONE_0]); - output[iZone]->PreprocessHistoryOutput(config_container[ZONE_0], false); - solver_container[iZone][INST_0]->LoadRestart(&geometry_container[iZone][INST_0], &solver_container[iZone], config_container[iZone], 0, true); - } - - for (iZone = 0; iZone < nZone; iZone++){ + for (iZone = 0; iZone < nZone; iZone++) { + /*--- Definition of the solution class ---*/ - WriteFiles(config_container[iZone], geometry_container[iZone][INST_0], &solver_container[iZone][INST_0], output[iZone], 0); + solver_container[iZone][INST_0] = + new CBaselineSolver_FEM(geometry_container[iZone][INST_0], config_container[iZone]); + output[iZone] = new CBaselineOutput(config_container[ZONE_0], geometry_container[ZONE_0][INST_0]->GetnDim(), + solver_container[ZONE_0][INST_0]); + output[iZone]->PreprocessVolumeOutput(config_container[ZONE_0]); + output[iZone]->PreprocessHistoryOutput(config_container[ZONE_0], false); + solver_container[iZone][INST_0]->LoadRestart(&geometry_container[iZone][INST_0], &solver_container[iZone], + config_container[iZone], 0, true); + } + for (iZone = 0; iZone < nZone; iZone++) { + WriteFiles(config_container[iZone], geometry_container[iZone][INST_0], &solver_container[iZone][INST_0], + output[iZone], 0); + } } - } - - } - else { + } else { if (config_container[ZONE_0]->GetTime_Domain()) { - /*--- Unsteady simulation: merge all unsteady time steps. First, find the frequency and total number of files to write. ---*/ su2double Physical_dt, Physical_t; unsigned long TimeIter = 0; bool StopCalc = false; - bool *SolutionInstantiated = new bool[nZone]; + bool* SolutionInstantiated = new bool[nZone]; - for (iZone = 0; iZone < nZone; iZone++) - SolutionInstantiated[iZone] = false; + for (iZone = 0; iZone < nZone; iZone++) SolutionInstantiated[iZone] = false; /*--- Check for an unsteady restart. Update ExtIter if necessary. ---*/ if (config_container[ZONE_0]->GetTime_Domain() && config_container[ZONE_0]->GetRestart()) TimeIter = config_container[ZONE_0]->GetRestart_Iter(); while (TimeIter < config_container[ZONE_0]->GetnTime_Iter()) { - /*--- Check several conditions in order to merge the correct time step files. ---*/ Physical_dt = config_container[ZONE_0]->GetTime_Step(); - Physical_t = (TimeIter+1)*Physical_dt; - if (Physical_t >= config_container[ZONE_0]->GetMax_Time()) - StopCalc = true; + Physical_t = (TimeIter + 1) * Physical_dt; + if (Physical_t >= config_container[ZONE_0]->GetMax_Time()) StopCalc = true; - if ((TimeIter+1 == config_container[ZONE_0]->GetnTime_Iter()) || + if ((TimeIter + 1 == config_container[ZONE_0]->GetnTime_Iter()) || ((TimeIter % config_container[ZONE_0]->GetVolumeOutputFrequency(0) == 0) && (TimeIter != 0) && !((config_container[ZONE_0]->GetTime_Marching() == TIME_MARCHING::DT_STEPPING_1ST) || (config_container[ZONE_0]->GetTime_Marching() == TIME_MARCHING::DT_STEPPING_2ND))) || @@ -544,41 +527,37 @@ int main(int argc, char *argv[]) { (((config_container[ZONE_0]->GetTime_Marching() == TIME_MARCHING::DT_STEPPING_1ST) || (config_container[ZONE_0]->GetTime_Marching() == TIME_MARCHING::DT_STEPPING_2ND)) && ((TimeIter == 0) || (TimeIter % config_container[ZONE_0]->GetVolumeOutputFrequency(0) == 0)))) { + /*--- Read in the restart file for this time step ---*/ + for (iZone = 0; iZone < nZone; iZone++) { + /*--- Set the current iteration number in the config class. ---*/ + config_container[iZone]->SetTimeIter(TimeIter); + /*--- Either instantiate the solution class or load a restart file. ---*/ + if (SolutionInstantiated[iZone] == false && + (TimeIter == 0 || (config_container[ZONE_0]->GetRestart() && + ((long)TimeIter == SU2_TYPE::Int(config_container[ZONE_0]->GetRestart_Iter()) || + TimeIter % config_container[ZONE_0]->GetVolumeOutputFrequency(0) == 0 || + TimeIter + 1 == config_container[ZONE_0]->GetnTime_Iter())))) { + solver_container[iZone][INST_0] = + new CBaselineSolver(geometry_container[iZone][INST_0], config_container[iZone]); + output[iZone] = new CBaselineOutput(config_container[iZone], geometry_container[iZone][INST_0]->GetnDim(), + solver_container[iZone][INST_0]); + output[iZone]->PreprocessVolumeOutput(config_container[iZone]); + output[iZone]->PreprocessHistoryOutput(config_container[iZone], false); + + SolutionInstantiated[iZone] = true; + } + config_container[iZone]->SetiInst(INST_0); + solver_container[iZone][INST_0]->LoadRestart(geometry_container[iZone], &solver_container[iZone], + config_container[iZone], TimeIter, true); + } + if (rank == MASTER_NODE) cout << "Writing the volume solution for time step " << TimeIter << "." << endl; - /*--- Read in the restart file for this time step ---*/ - for (iZone = 0; iZone < nZone; iZone++) { - - /*--- Set the current iteration number in the config class. ---*/ - config_container[iZone]->SetTimeIter(TimeIter); - - /*--- Either instantiate the solution class or load a restart file. ---*/ - if (SolutionInstantiated[iZone] == false && - (TimeIter == 0 || (config_container[ZONE_0]->GetRestart() && ((long)TimeIter == SU2_TYPE::Int(config_container[ZONE_0]->GetRestart_Iter()) || - TimeIter % config_container[ZONE_0]->GetVolumeOutputFrequency(0) == 0 || - TimeIter+1 == config_container[ZONE_0]->GetnTime_Iter())))) { - solver_container[iZone][INST_0] = new CBaselineSolver(geometry_container[iZone][INST_0], config_container[iZone]); - output[iZone] = new CBaselineOutput(config_container[iZone], geometry_container[iZone][INST_0]->GetnDim(), solver_container[iZone][INST_0]); - output[iZone]->PreprocessVolumeOutput(config_container[iZone]); - output[iZone]->PreprocessHistoryOutput(config_container[iZone], false); - - SolutionInstantiated[iZone] = true; - } - config_container[iZone]->SetiInst(INST_0); - solver_container[iZone][INST_0]->LoadRestart(geometry_container[iZone], &solver_container[iZone], config_container[iZone], TimeIter, true); - } - - if (rank == MASTER_NODE) - cout << "Writing the volume solution for time step " << TimeIter << "." << endl; - - for (iZone = 0; iZone < nZone; iZone++){ - - WriteFiles(config_container[iZone], geometry_container[iZone][INST_0], &solver_container[iZone][INST_0], output[iZone], TimeIter); - - } - - + for (iZone = 0; iZone < nZone; iZone++) { + WriteFiles(config_container[iZone], geometry_container[iZone][INST_0], &solver_container[iZone][INST_0], + output[iZone], TimeIter); + } } TimeIter++; @@ -588,19 +567,19 @@ int main(int argc, char *argv[]) { } else if (config_container[ZONE_0]->GetTime_Marching() == TIME_MARCHING::HARMONIC_BALANCE) { - /*--- Read in the restart file for this time step ---*/ for (iZone = 0; iZone < nZone; iZone++) { - - for (iInst = 0; iInst < nInst[iZone]; iInst++){ - + for (iInst = 0; iInst < nInst[iZone]; iInst++) { config_container[iZone]->SetiInst(iInst); config_container[iZone]->SetTimeIter(iInst); /*--- Either instantiate the solution class or load a restart file. ---*/ - solver_container[iZone][iInst] = new CBaselineSolver(geometry_container[iZone][iInst], config_container[iZone]); - solver_container[iZone][iInst]->LoadRestart(geometry_container[iZone], &solver_container[iZone], config_container[iZone], iInst, true); - output[iZone] = new CBaselineOutput(config_container[iZone], geometry_container[iZone][iInst]->GetnDim(), solver_container[iZone][iInst]); + solver_container[iZone][iInst] = + new CBaselineSolver(geometry_container[iZone][iInst], config_container[iZone]); + solver_container[iZone][iInst]->LoadRestart(geometry_container[iZone], &solver_container[iZone], + config_container[iZone], iInst, true); + output[iZone] = new CBaselineOutput(config_container[iZone], geometry_container[iZone][iInst]->GetnDim(), + solver_container[iZone][iInst]); output[iZone]->PreprocessVolumeOutput(config_container[iZone]); output[iZone]->PreprocessHistoryOutput(config_container[iZone], false); @@ -609,17 +588,14 @@ int main(int argc, char *argv[]) { cout << "Storing the volume solution for time instance " << iInst << "." << endl; } - WriteFiles(config_container[iZone], geometry_container[iZone][iInst], &solver_container[iZone][iInst], output[iZone], iInst); - + WriteFiles(config_container[iZone], geometry_container[iZone][iInst], &solver_container[iZone][iInst], + output[iZone], iInst); } - } - } - else if (config_container[ZONE_0]->GetTime_Domain()){ - + else if (config_container[ZONE_0]->GetTime_Domain()) { /*--- Dynamic simulation: merge all unsteady time steps. First, find the frequency and total number of files to write. ---*/ @@ -628,117 +604,112 @@ int main(int argc, char *argv[]) { bool StopCalc = false; bool SolutionInstantiated = false; - /*--- Check for an dynamic restart (structural analysis). Update ExtIter if necessary. ---*/ - if (config_container[ZONE_0]->GetKind_Solver() == MAIN_SOLVER::FEM_ELASTICITY && config_container[ZONE_0]->GetRestart()) + if (config_container[ZONE_0]->GetKind_Solver() == MAIN_SOLVER::FEM_ELASTICITY && + config_container[ZONE_0]->GetRestart()) TimeIter = config_container[ZONE_0]->GetRestart_Iter(); while (TimeIter < config_container[ZONE_0]->GetnTime_Iter()) { - /*--- Check several conditions in order to merge the correct time step files. ---*/ /*--- If the solver is structural, the total and delta_t are obtained from different functions. ---*/ Physical_dt = config_container[ZONE_0]->GetTime_Step(); - Physical_t = (TimeIter+1)*Physical_dt; - if (Physical_t >= config_container[ZONE_0]->GetMax_Time()) - StopCalc = true; + Physical_t = (TimeIter + 1) * Physical_dt; + if (Physical_t >= config_container[ZONE_0]->GetMax_Time()) StopCalc = true; - if ((TimeIter+1 == config_container[ZONE_0]->GetnTime_Iter()) || - (StopCalc) || + if ((TimeIter + 1 == config_container[ZONE_0]->GetnTime_Iter()) || (StopCalc) || ((config_container[ZONE_0]->GetTime_Domain()) && ((TimeIter == 0) || (TimeIter % config_container[ZONE_0]->GetVolumeOutputFrequency(0) == 0)))) { + /*--- Set the current iteration number in the config class. ---*/ + config_container[ZONE_0]->SetTimeIter(TimeIter); + + /*--- Read in the restart file for this time step ---*/ + for (iZone = 0; iZone < nZone; iZone++) { + /*--- Either instantiate the solution class or load a restart file. ---*/ + if (SolutionInstantiated == false && + (TimeIter == 0 || + ((config_container[ZONE_0]->GetRestart() && + (SU2_TYPE::Int(TimeIter) == SU2_TYPE::Int(config_container[ZONE_0]->GetRestart_Iter()))) || + TimeIter % config_container[ZONE_0]->GetVolumeOutputFrequency(0) == 0 || + TimeIter + 1 == config_container[ZONE_0]->GetnTime_Iter()))) { + solver_container[iZone][INST_0] = + new CBaselineSolver(geometry_container[iZone][INST_0], config_container[iZone]); + output[iZone] = new CBaselineOutput(config_container[iZone], geometry_container[iZone][INST_0]->GetnDim(), + solver_container[iZone][INST_0]); + output[iZone]->PreprocessVolumeOutput(config_container[iZone]); + output[iZone]->PreprocessHistoryOutput(config_container[iZone], false); + + SolutionInstantiated = true; + } + config_container[iZone]->SetiInst(INST_0); + solver_container[iZone][INST_0]->LoadRestart(geometry_container[iZone], &solver_container[iZone], + config_container[iZone], TimeIter, true); + } - /*--- Set the current iteration number in the config class. ---*/ - config_container[ZONE_0]->SetTimeIter(TimeIter); - - /*--- Read in the restart file for this time step ---*/ - for (iZone = 0; iZone < nZone; iZone++) { - - /*--- Either instantiate the solution class or load a restart file. ---*/ - if (SolutionInstantiated == false && - (TimeIter == 0 || ((config_container[ZONE_0]->GetRestart() && (SU2_TYPE::Int(TimeIter) == SU2_TYPE::Int(config_container[ZONE_0]->GetRestart_Iter()))) || - TimeIter % config_container[ZONE_0]->GetVolumeOutputFrequency(0) == 0 || - TimeIter+1 == config_container[ZONE_0]->GetnTime_Iter()))) { - solver_container[iZone][INST_0] = new CBaselineSolver(geometry_container[iZone][INST_0], config_container[iZone]); - output[iZone] = new CBaselineOutput(config_container[iZone], geometry_container[iZone][INST_0]->GetnDim(), solver_container[iZone][INST_0]); - output[iZone]->PreprocessVolumeOutput(config_container[iZone]); - output[iZone]->PreprocessHistoryOutput(config_container[iZone], false); - - SolutionInstantiated = true; - } - config_container[iZone]->SetiInst(INST_0); - solver_container[iZone][INST_0]->LoadRestart(geometry_container[iZone], &solver_container[iZone], config_container[iZone], TimeIter, true); - } - - if (rank == MASTER_NODE) - cout << "Writing the volume solution for time step " << TimeIter << "." << endl; - for (iZone = 0; iZone < nZone; iZone++){ - - WriteFiles(config_container[iZone], geometry_container[iZone][INST_0], &solver_container[iZone][INST_0], output[iZone], TimeIter); - - } + if (rank == MASTER_NODE) cout << "Writing the volume solution for time step " << TimeIter << "." << endl; + for (iZone = 0; iZone < nZone; iZone++) { + WriteFiles(config_container[iZone], geometry_container[iZone][INST_0], &solver_container[iZone][INST_0], + output[iZone], TimeIter); + } } TimeIter++; if (StopCalc) break; } - } + } else { - /*--- Steady simulation: merge the single solution file. ---*/ for (iZone = 0; iZone < nZone; iZone++) { config_container[iZone]->SetiInst(INST_0); /*--- Definition of the solution class ---*/ - solver_container[iZone][INST_0] = new CBaselineSolver(geometry_container[iZone][INST_0], config_container[iZone]); - solver_container[iZone][INST_0]->LoadRestart(geometry_container[iZone], &solver_container[iZone], config_container[iZone], 0, true); - output[iZone] = new CBaselineOutput(config_container[iZone], geometry_container[iZone][INST_0]->GetnDim(), solver_container[iZone][INST_0]); + solver_container[iZone][INST_0] = + new CBaselineSolver(geometry_container[iZone][INST_0], config_container[iZone]); + solver_container[iZone][INST_0]->LoadRestart(geometry_container[iZone], &solver_container[iZone], + config_container[iZone], 0, true); + output[iZone] = new CBaselineOutput(config_container[iZone], geometry_container[iZone][INST_0]->GetnDim(), + solver_container[iZone][INST_0]); output[iZone]->PreprocessVolumeOutput(config_container[iZone]); output[iZone]->PreprocessHistoryOutput(config_container[iZone], false); - } - for (iZone = 0; iZone < nZone; iZone++){ - - WriteFiles(config_container[iZone], geometry_container[iZone][INST_0], &solver_container[iZone][INST_0], output[iZone], 0); - + for (iZone = 0; iZone < nZone; iZone++) { + WriteFiles(config_container[iZone], geometry_container[iZone][INST_0], &solver_container[iZone][INST_0], + output[iZone], 0); } } - } delete config; config = nullptr; if (rank == MASTER_NODE) - cout << endl <<"------------------------- Solver Postprocessing -------------------------" << endl; + cout << endl << "------------------------- Solver Postprocessing -------------------------" << endl; if (geometry_container != nullptr) { for (iZone = 0; iZone < nZone; iZone++) { - for (iInst = 0; iInst < nInst[iZone]; iInst++){ + for (iInst = 0; iInst < nInst[iZone]; iInst++) { if (geometry_container[iZone][iInst] != nullptr) { delete geometry_container[iZone][iInst]; } } - if (geometry_container[iZone] != nullptr) - delete [] geometry_container[iZone]; + if (geometry_container[iZone] != nullptr) delete[] geometry_container[iZone]; } - delete [] geometry_container; + delete[] geometry_container; } if (rank == MASTER_NODE) cout << "Deleted CGeometry container." << endl; if (solver_container != nullptr) { for (iZone = 0; iZone < nZone; iZone++) { - for (iInst = 0; iInst < nInst[iZone]; iInst++){ + for (iInst = 0; iInst < nInst[iZone]; iInst++) { if (solver_container[iZone][iInst] != nullptr) { delete solver_container[iZone][iInst]; } } - if (solver_container[iZone] != nullptr) - delete [] solver_container[iZone]; + if (solver_container[iZone] != nullptr) delete[] solver_container[iZone]; } - delete [] solver_container; + delete[] solver_container; } if (rank == MASTER_NODE) cout << "Deleted CSolver class." << endl; @@ -748,7 +719,7 @@ int main(int argc, char *argv[]) { delete config_container[iZone]; } } - delete [] config_container; + delete[] config_container; } if (rank == MASTER_NODE) cout << "Deleted CConfig container." << endl; @@ -758,7 +729,7 @@ int main(int argc, char *argv[]) { delete output[iZone]; } } - delete [] output; + delete[] output; } if (rank == MASTER_NODE) cout << "Deleted COutput class." << endl; @@ -769,16 +740,19 @@ int main(int argc, char *argv[]) { /*--- Compute/print the total time for performance benchmarking. ---*/ - UsedTime = StopTime-StartTime; + UsedTime = StopTime - StartTime; if (rank == MASTER_NODE) { - cout << "\nCompleted in " << fixed << UsedTime << " seconds on "<< size; - if (size == 1) cout << " core." << endl; else cout << " cores." << endl; + cout << "\nCompleted in " << fixed << UsedTime << " seconds on " << size; + if (size == 1) + cout << " core." << endl; + else + cout << " cores." << endl; } /*--- Exit the solver cleanly ---*/ if (rank == MASTER_NODE) - cout << endl <<"------------------------- Exit Success (SU2_SOL) ------------------------" << endl << endl; + cout << endl << "------------------------- Exit Success (SU2_SOL) ------------------------" << endl << endl; /*--- Finalize MPI parallelization ---*/ SU2_MPI::Finalize(); @@ -786,8 +760,8 @@ int main(int argc, char *argv[]) { return EXIT_SUCCESS; } -void WriteFiles(CConfig *config, CGeometry* geometry, CSolver** solver_container, COutput *output, unsigned long TimeIter){ - +void WriteFiles(CConfig* config, CGeometry* geometry, CSolver** solver_container, COutput* output, + unsigned long TimeIter) { /*--- Load history data (volume output might require some values) --- */ output->SetHistory_Output(geometry, solver_container, config, TimeIter, 0, 0); @@ -802,12 +776,10 @@ void WriteFiles(CConfig *config, CGeometry* geometry, CSolver** solver_container output->SetSurface_Filename(config->GetSurfCoeff_FileName()); - for (unsigned short iFile = 0; iFile < config->GetnVolumeOutputFiles(); iFile++){ + for (unsigned short iFile = 0; iFile < config->GetnVolumeOutputFiles(); iFile++) { auto FileFormat = config->GetVolumeOutputFiles(); - if (FileFormat[iFile] != OUTPUT_TYPE::RESTART_ASCII && - FileFormat[iFile] != OUTPUT_TYPE::RESTART_BINARY && + if (FileFormat[iFile] != OUTPUT_TYPE::RESTART_ASCII && FileFormat[iFile] != OUTPUT_TYPE::RESTART_BINARY && FileFormat[iFile] != OUTPUT_TYPE::CSV) output->WriteToFile(config, geometry, FileFormat[iFile]); } - } diff --git a/UnitTests/Common/containers/CLookupTable_tests.cpp b/UnitTests/Common/containers/CLookupTable_tests.cpp index 22cb17e393e..f17049ec341 100644 --- a/UnitTests/Common/containers/CLookupTable_tests.cpp +++ b/UnitTests/Common/containers/CLookupTable_tests.cpp @@ -35,25 +35,23 @@ #include "../../../Common/include/containers/CLookUpTable.hpp" #include "../../../Common/include/containers/CFileReaderLUT.hpp" - TEST_CASE("LUTreader", "[tabulated chemistry]") { - /*--- smaller and trivial lookup table ---*/ - CLookUpTable look_up_table("src/SU2/UnitTests/Common/containers/lookuptable.drg","ProgressVariable","EnthalpyTot"); + CLookUpTable look_up_table("src/SU2/UnitTests/Common/containers/lookuptable.drg", "ProgressVariable", "EnthalpyTot"); /*--- string names of the controlling variables ---*/ string name_CV1 = "ProgressVariable"; string name_CV2 = "EnthalpyTot"; - /*--- look up a single value for density ---*/ + /*--- look up a single value for density ---*/ su2double prog = 0.55; su2double enth = -0.5; string look_up_tag = "Density"; su2double look_up_dat; - look_up_table.LookUp_XY(look_up_tag, &look_up_dat, prog, enth); + look_up_table.LookUp_XY(look_up_tag, &look_up_dat, prog, enth); CHECK(look_up_dat == Approx(1.02)); /*--- look up a single value for viscosity ---*/ @@ -61,11 +59,11 @@ TEST_CASE("LUTreader", "[tabulated chemistry]") { prog = 0.6; enth = 0.9; look_up_tag = "Viscosity"; - look_up_table.LookUp_XY(look_up_tag, &look_up_dat, prog, enth); + look_up_table.LookUp_XY(look_up_tag, &look_up_dat, prog, enth); CHECK(look_up_dat == Approx(0.0000674286)); /* find the table limits */ - + auto limitsEnth = look_up_table.GetTableLimitsY(); CHECK(SU2_TYPE::GetValue(*limitsEnth.first) == Approx(-1.0)); CHECK(SU2_TYPE::GetValue(*limitsEnth.second) == Approx(1.0)); @@ -79,43 +77,42 @@ TEST_CASE("LUTreader", "[tabulated chemistry]") { prog = 1.10; enth = 1.1; look_up_tag = "Density"; - look_up_table.LookUp_XY(look_up_tag, &look_up_dat, prog, enth); + look_up_table.LookUp_XY(look_up_tag, &look_up_dat, prog, enth); CHECK(look_up_dat == Approx(1.1738796125)); - } TEST_CASE("LUTreader_3D", "[tabulated chemistry]") { - /*--- smaller and trivial lookup table ---*/ - - CLookUpTable look_up_table("src/SU2/UnitTests/Common/containers/lookuptable_3D.drg","ProgressVariable","EnthalpyTot"); + + CLookUpTable look_up_table("src/SU2/UnitTests/Common/containers/lookuptable_3D.drg", "ProgressVariable", + "EnthalpyTot"); /*--- string names of the controlling variables ---*/ string name_CV1 = "ProgressVariable"; string name_CV2 = "EnthalpyTot"; - /*--- look up a single value for density ---*/ + /*--- look up a single value for density ---*/ su2double prog = 0.55; - su2double enth = -0.5; + su2double enth = -0.5; su2double mfrac = 0.5; string look_up_tag = "Density"; su2double look_up_dat; - look_up_table.LookUp_XYZ(look_up_tag, &look_up_dat, prog, enth, mfrac); + look_up_table.LookUp_XYZ(look_up_tag, &look_up_dat, prog, enth, mfrac); CHECK(look_up_dat == Approx(1.02)); /*--- look up a single value for viscosity ---*/ prog = 0.6; - enth = 0.9; + enth = 0.9; mfrac = 0.8; look_up_tag = "Viscosity"; - look_up_table.LookUp_XYZ(look_up_tag, &look_up_dat, prog, enth, mfrac); + look_up_table.LookUp_XYZ(look_up_tag, &look_up_dat, prog, enth, mfrac); CHECK(look_up_dat == Approx(0.0000674286)); /* find the table limits */ - + auto limitsEnth = look_up_table.GetTableLimitsY(); CHECK(SU2_TYPE::GetValue(*limitsEnth.first) == Approx(-1.0)); CHECK(SU2_TYPE::GetValue(*limitsEnth.second) == Approx(1.0)); @@ -130,7 +127,6 @@ TEST_CASE("LUTreader_3D", "[tabulated chemistry]") { enth = 1.1; mfrac = 2.0; look_up_tag = "Density"; - look_up_table.LookUp_XYZ(look_up_tag, &look_up_dat, prog, enth, mfrac); + look_up_table.LookUp_XYZ(look_up_tag, &look_up_dat, prog, enth, mfrac); CHECK(look_up_dat == Approx(1.1738796125)); - } diff --git a/UnitTests/Common/geometry/CGeometry_test.cpp b/UnitTests/Common/geometry/CGeometry_test.cpp index be8992699c1..edd24e82ec0 100644 --- a/UnitTests/Common/geometry/CGeometry_test.cpp +++ b/UnitTests/Common/geometry/CGeometry_test.cpp @@ -30,44 +30,41 @@ std::unique_ptr TestCase; -TEST_CASE("Geometry constructor", "[Geometry]"){ - +TEST_CASE("Geometry constructor", "[Geometry]") { cout.rdbuf(nullptr); TestCase = std::unique_ptr(new UnitQuadTestCase()); TestCase->InitConfig(); - auto aux_geometry = std::unique_ptr(new CPhysicalGeometry(TestCase->config.get(), 0, 1)); + auto aux_geometry = std::unique_ptr(new CPhysicalGeometry(TestCase->config.get(), 0, 1)); - CHECK(aux_geometry->GetnPoint() == 125); - CHECK(aux_geometry->GetnElem() == 64); + CHECK(aux_geometry->GetnPoint() == 125); + CHECK(aux_geometry->GetnElem() == 64); CHECK(aux_geometry->GetnElemHexa() == 64); - CHECK(aux_geometry->GetnEdge() == 0); + CHECK(aux_geometry->GetnEdge() == 0); CHECK(aux_geometry->GetnElem_Bound(0) == 16); CHECK(aux_geometry->GetnElem_Bound(5) == 16); TestCase->geometry = std::unique_ptr(new CPhysicalGeometry(aux_geometry.get(), TestCase->config.get())); - CHECK(TestCase->geometry->GetnPoint() == 125); - CHECK(TestCase->geometry->GetnElem() == 64); + CHECK(TestCase->geometry->GetnPoint() == 125); + CHECK(TestCase->geometry->GetnElem() == 64); CHECK(TestCase->geometry->GetnElemHexa() == 64); - CHECK(TestCase->geometry->GetnEdge() == 0); + CHECK(TestCase->geometry->GetnEdge() == 0); CHECK(TestCase->geometry->GetnElem_Bound(0) == 16); CHECK(TestCase->geometry->GetnElem_Bound(5) == 16); cout.rdbuf(TestCase->orig_buf); - } -TEST_CASE("Set Send/Recv", "[Geometry]"){ +TEST_CASE("Set Send/Recv", "[Geometry]") { TestCase->geometry->SetSendReceive(TestCase->config.get()); /*---- No check yet, since unit tests run in serial at the moment ---*/ } -TEST_CASE("Set Boundaries", "[Geometry]"){ - +TEST_CASE("Set Boundaries", "[Geometry]") { TestCase->geometry->SetBoundaries(TestCase->config.get()); CHECK(TestCase->config->GetMarker_All_KindBC(0) == CUSTOM_BOUNDARY); @@ -76,75 +73,63 @@ TEST_CASE("Set Boundaries", "[Geometry]"){ CHECK(TestCase->config->GetSolid_Wall(3)); } -TEST_CASE("Set Point Connectivity", "[Geometry]"){ - +TEST_CASE("Set Point Connectivity", "[Geometry]") { TestCase->geometry->SetPoint_Connectivity(); - CHECK(TestCase->geometry->nodes->GetnElem(55) == 4); - CHECK(TestCase->geometry->nodes->GetElem(30, 2) == 16); - CHECK(TestCase->geometry->nodes->GetnNeighbor(3) == 4); - CHECK(TestCase->geometry->nodes->GetPoint(99, 2) == 98); + CHECK(TestCase->geometry->nodes->GetnElem(55) == 4); + CHECK(TestCase->geometry->nodes->GetElem(30, 2) == 16); + CHECK(TestCase->geometry->nodes->GetnNeighbor(3) == 4); + CHECK(TestCase->geometry->nodes->GetPoint(99, 2) == 98); } -TEST_CASE("Set elem connectivity", "[Geometry]"){ - +TEST_CASE("Set elem connectivity", "[Geometry]") { TestCase->geometry->SetElement_Connectivity(); CHECK(TestCase->geometry->elem[14]->GetnFaces() == 6); CHECK(TestCase->geometry->elem[14]->GetNeighbor_Elements(1) == 15); - } -TEST_CASE("Set bound volume", "[Geometry]"){ - +TEST_CASE("Set bound volume", "[Geometry]") { TestCase->geometry->SetBoundVolume(); CHECK(TestCase->geometry->bound[0][10]->GetDomainElement() == 40); CHECK(TestCase->geometry->bound[4][10]->GetDomainElement() == 10); - } -TEST_CASE("Set Edges", "[Geometry]"){ - +TEST_CASE("Set Edges", "[Geometry]") { TestCase->geometry->SetEdges(); CHECK(TestCase->geometry->edges->GetnNodes() == 2); - CHECK(TestCase->geometry->edges->GetNode(42,0) == 15); - CHECK(TestCase->geometry->edges->GetNode(87,1) == 57); - + CHECK(TestCase->geometry->edges->GetNode(42, 0) == 15); + CHECK(TestCase->geometry->edges->GetNode(87, 1) == 57); } -TEST_CASE("Set vertex", "[Geometry]"){ - +TEST_CASE("Set vertex", "[Geometry]") { TestCase->geometry->SetVertex(TestCase->config.get()); CHECK(TestCase->geometry->GetnVertex(0) == 25); CHECK(TestCase->geometry->vertex[0][20]->GetNode() == 100); CHECK(TestCase->geometry->nodes->GetVertex(100, 0) == 20); CHECK(TestCase->geometry->nodes->GetVertex(1, 0) == -1); - } -TEST_CASE("Set control volume", "[Geometry]"){ - +TEST_CASE("Set control volume", "[Geometry]") { TestCase->geometry->SetControlVolume(TestCase->config.get(), ALLOCATE); CHECK(TestCase->geometry->elem[42]->GetCG(0) == 0.625); - CHECK(TestCase->geometry->elem[3]->GetCG(1) == 0.125); + CHECK(TestCase->geometry->elem[3]->GetCG(1) == 0.125); CHECK(TestCase->geometry->elem[25]->GetCG(2) == 0.375); CHECK(TestCase->geometry->nodes->GetVolume(42) == Approx(0.015625)); CHECK(TestCase->geometry->edges->GetNormal(32)[0] == 0.03125); - CHECK(TestCase->geometry->edges->GetNormal(5)[1] == 0.0); + CHECK(TestCase->geometry->edges->GetNormal(5)[1] == 0.0); CHECK(TestCase->geometry->edges->GetNormal(10)[2] == 0.03125); CHECK(TestCase->config->GetDomainVolume() == Approx(1.0)); - } -TEST_CASE("Set bound control volume", "[Geometry]"){ - +TEST_CASE("Set bound control volume", "[Geometry]") { TestCase->geometry->SetBoundControlVolume(TestCase->config.get(), ALLOCATE); CHECK(TestCase->geometry->bound[1][4]->GetCG(0) == 1.0); @@ -153,6 +138,5 @@ TEST_CASE("Set bound control volume", "[Geometry]"){ CHECK(TestCase->geometry->vertex[0][4]->GetNormal()[0] == -0.0625); CHECK(TestCase->geometry->vertex[3][2]->GetNormal()[1] == -0.0625); - CHECK(TestCase->geometry->vertex[5][3]->GetNormal()[2] == 0.03125); - + CHECK(TestCase->geometry->vertex[5][3]->GetNormal()[2] == 0.03125); } diff --git a/UnitTests/Common/geometry/dual_grid/CDualGrid_tests.cpp b/UnitTests/Common/geometry/dual_grid/CDualGrid_tests.cpp index a0eb34f1a22..2193446fe84 100644 --- a/UnitTests/Common/geometry/dual_grid/CDualGrid_tests.cpp +++ b/UnitTests/Common/geometry/dual_grid/CDualGrid_tests.cpp @@ -32,41 +32,47 @@ #include "../../../Common/include/geometry/dual_grid/CVertex.hpp" TEST_CASE("Volume Computation", "[Dual Grid]") { - su2double Coord_FaceiPoint[3]; su2double Coord_FaceElem_CG[3]; su2double Coord_Elem_CG[3]; su2double Coord_Edge_CG[3]; su2double scaling = 100; - Coord_FaceiPoint[0] = scaling*0.664995; Coord_FaceiPoint[1] = scaling*1.1462; Coord_FaceiPoint[2] = scaling*0.00926223; - Coord_FaceElem_CG[0] = scaling*0.655997; Coord_FaceElem_CG[1] = scaling*1.13054; Coord_FaceElem_CG[2] = scaling*0.00945181; - Coord_Elem_CG[0] = scaling*0.653846; Coord_Elem_CG[1] = scaling*1.12927; Coord_Elem_CG[2] = scaling*0.00835789; - Coord_Edge_CG[0] = scaling*0.664943; Coord_Edge_CG[1] = scaling*1.14623; Coord_Edge_CG[2] = scaling*0.00935524; + Coord_FaceiPoint[0] = scaling * 0.664995; + Coord_FaceiPoint[1] = scaling * 1.1462; + Coord_FaceiPoint[2] = scaling * 0.00926223; + Coord_FaceElem_CG[0] = scaling * 0.655997; + Coord_FaceElem_CG[1] = scaling * 1.13054; + Coord_FaceElem_CG[2] = scaling * 0.00945181; + Coord_Elem_CG[0] = scaling * 0.653846; + Coord_Elem_CG[1] = scaling * 1.12927; + Coord_Elem_CG[2] = scaling * 0.00835789; + Coord_Edge_CG[0] = scaling * 0.664943; + Coord_Edge_CG[1] = scaling * 1.14623; + Coord_Edge_CG[2] = scaling * 0.00935524; - SECTION("2D Edge"){ + SECTION("2D Edge") { su2double volume = CEdge::GetVolume(Coord_FaceiPoint, Coord_Edge_CG, Coord_Elem_CG); REQUIRE(volume == Approx(0.00607415)); } - SECTION("3D Edge"){ + SECTION("3D Edge") { su2double volume = CEdge::GetVolume(Coord_FaceiPoint, Coord_Edge_CG, Coord_FaceElem_CG, Coord_Elem_CG); REQUIRE(volume == Approx(0.000546832)); } CVertex vertex2d(0, 2); - SECTION("2D Vertex"){ + SECTION("2D Vertex") { vertex2d.SetNodes_Coord(Coord_Edge_CG, Coord_Elem_CG); REQUIRE(vertex2d.GetNormal()[0] == Approx(-1.696)); REQUIRE(vertex2d.GetNormal()[1] == Approx(1.1097)); } CVertex vertex3d(0, 3); - SECTION("3D Vertex"){ + SECTION("3D Vertex") { vertex3d.SetNodes_Coord(Coord_Edge_CG, Coord_FaceElem_CG, Coord_Elem_CG); REQUIRE(vertex3d.GetNormal()[0] == Approx(-0.0864312)); REQUIRE(vertex3d.GetNormal()[1] == Approx(0.0499696)); REQUIRE(vertex3d.GetNormal()[2] == Approx(0.111938)); } - } diff --git a/UnitTests/Common/geometry/primal_grid/CPrimalGrid_tests.cpp b/UnitTests/Common/geometry/primal_grid/CPrimalGrid_tests.cpp index e8282665a60..5323fc0da56 100644 --- a/UnitTests/Common/geometry/primal_grid/CPrimalGrid_tests.cpp +++ b/UnitTests/Common/geometry/primal_grid/CPrimalGrid_tests.cpp @@ -31,36 +31,50 @@ #include "../../../Common/include/geometry/primal_grid/CHexahedron.hpp" TEST_CASE("Center of gravity computation", "[Primal Grid]") { - const int nDim = 3; - su2double **coordinates = new su2double*[8]; - for (int i = 0; i < 8; i++){ + su2double** coordinates = new su2double*[8]; + for (int i = 0; i < 8; i++) { coordinates[i] = new su2double[nDim]; } - coordinates[0][0] = 7.946516948817000e-01; coordinates[0][1] = 0.000000000000000e+00; coordinates[0][2] = -1.530741281331000e-03; - coordinates[1][0] = 7.946538480939001e-01; coordinates[1][1] = 0.000000000000000e+00; coordinates[1][2] = -1.554823763559000e-03; - coordinates[2][0] = 4.613089666440000e-01; coordinates[2][1] = 0.000000000000000e+00; coordinates[2][2] = -3.089699212314000e-03; - coordinates[3][0] = 7.831152624057000e-01; coordinates[3][1] = 0.000000000000000e+00; coordinates[3][2] = -1.530741281331000e-03; - coordinates[4][0] = 8.322953467911001e-01; coordinates[4][1] = 1.324931278110000e-01; coordinates[4][2] = -1.456502113362000e-03; - coordinates[5][0] = 8.322984569865000e-01; coordinates[5][1] = 1.336230857244000e-01; coordinates[5][2] = -1.480923128397000e-03; - coordinates[6][0] = 8.213630099601000e-01; coordinates[6][1] = 1.326360771765000e-01; coordinates[6][2] = -2.941176615903000e-03; - coordinates[7][0] = 8.213597801418000e-01; coordinates[7][1] = 1.326371537826000e-01; coordinates[7][2] = -2.916814216089000e-03; + coordinates[0][0] = 7.946516948817000e-01; + coordinates[0][1] = 0.000000000000000e+00; + coordinates[0][2] = -1.530741281331000e-03; + coordinates[1][0] = 7.946538480939001e-01; + coordinates[1][1] = 0.000000000000000e+00; + coordinates[1][2] = -1.554823763559000e-03; + coordinates[2][0] = 4.613089666440000e-01; + coordinates[2][1] = 0.000000000000000e+00; + coordinates[2][2] = -3.089699212314000e-03; + coordinates[3][0] = 7.831152624057000e-01; + coordinates[3][1] = 0.000000000000000e+00; + coordinates[3][2] = -1.530741281331000e-03; + coordinates[4][0] = 8.322953467911001e-01; + coordinates[4][1] = 1.324931278110000e-01; + coordinates[4][2] = -1.456502113362000e-03; + coordinates[5][0] = 8.322984569865000e-01; + coordinates[5][1] = 1.336230857244000e-01; + coordinates[5][2] = -1.480923128397000e-03; + coordinates[6][0] = 8.213630099601000e-01; + coordinates[6][1] = 1.326360771765000e-01; + coordinates[6][2] = -2.941176615903000e-03; + coordinates[7][0] = 8.213597801418000e-01; + coordinates[7][1] = 1.326371537826000e-01; + coordinates[7][2] = -2.916814216089000e-03; -#define REQUIRE_CG(name, x, y, z) \ - name.SetCoord_CG(nDim, coordinates); \ +#define REQUIRE_CG(name, x, y, z) \ + name.SetCoord_CG(nDim, coordinates); \ REQUIRE(name.GetCG(0) == Approx(x)); \ REQUIRE(name.GetCG(1) == Approx(y)); \ REQUIRE(name.GetCG(2) == Approx(z)); // It is sufficient to test the CG computation for Hexahedron. // Routine is the same for all elements (impl. in CPrimalGrid) - CHexahedron hexa(0,1,2,3,4,5,6,7); + CHexahedron hexa(0, 1, 2, 3, 4, 5, 6, 7); REQUIRE_CG(hexa, 0.7676307957, 0.0664236806, -0.0020626777); - for (int i = 0; i < 8; i++){ - delete [] coordinates[i]; + for (int i = 0; i < 8; i++) { + delete[] coordinates[i]; } - delete [] coordinates; - + delete[] coordinates; } diff --git a/UnitTests/Common/simple_ad_test.cpp b/UnitTests/Common/simple_ad_test.cpp index 3fc3dc0da29..32e2b22db83 100644 --- a/UnitTests/Common/simple_ad_test.cpp +++ b/UnitTests/Common/simple_ad_test.cpp @@ -31,9 +31,7 @@ #include "../../Common/include/basic_types/datatype_structure.hpp" -su2double func(const su2double& x) { - return x * x * x; -} +su2double func(const su2double& x) { return x * x * x; } /*--- * This test case is based off of Tutorial 2 in the CoDiPack @@ -42,7 +40,6 @@ su2double func(const su2double& x) { * SU2 wrapper functions have been substituted for the CoDiPack calls. * ---*/ TEST_CASE("Simple AD Test", "[AD tests]") { - su2double x = 4.0; AD::StartRecording(); diff --git a/UnitTests/Common/simple_directdiff_test.cpp b/UnitTests/Common/simple_directdiff_test.cpp index 8cc0772d624..2b97810dd28 100644 --- a/UnitTests/Common/simple_directdiff_test.cpp +++ b/UnitTests/Common/simple_directdiff_test.cpp @@ -31,9 +31,7 @@ #include "../../Common/include/basic_types/datatype_structure.hpp" -su2double func(const su2double& x) { - return x * x * x; -} +su2double func(const su2double& x) { return x * x * x; } /*--- * This test case is based off of Tutorial 1 in the CoDiPack diff --git a/UnitTests/Common/toolboxes/C1DInterpolation_tests.cpp b/UnitTests/Common/toolboxes/C1DInterpolation_tests.cpp index 379c653d7ae..026763295fb 100644 --- a/UnitTests/Common/toolboxes/C1DInterpolation_tests.cpp +++ b/UnitTests/Common/toolboxes/C1DInterpolation_tests.cpp @@ -31,24 +31,23 @@ #include #include "../../../Common/include/toolboxes/C1DInterpolation.hpp" -su2double myPoly(su2double x) { return 1 + x*(-1 + x*(-1 + x)); } +su2double myPoly(su2double x) { return 1 + x * (-1 + x * (-1 + x)); } TEST_CASE("C1DInterpolation", "[Toolboxes]") { - std::vector x{{-1.5, -1.0, -0.8, -0.6, -0.4, -0.2, 0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 2.0}}, y; for (auto v : x) y.push_back(myPoly(v)); /*--- piece-wise linear ---*/ - CLinearInterpolation L(x,y); + CLinearInterpolation L(x, y); /*--- natural spline ---*/ - CCubicSpline S0(x,y); + CCubicSpline S0(x, y); /*--- analytical end conditions ---*/ - CCubicSpline S1(x,y, CCubicSpline::SECOND, -11.0, CCubicSpline::FIRST, 7.0); + CCubicSpline S1(x, y, CCubicSpline::SECOND, -11.0, CCubicSpline::FIRST, 7.0); - CCubicSpline S2(x,y, CCubicSpline::FIRST, 8.75, CCubicSpline::SECOND, 10.0); + CCubicSpline S2(x, y, CCubicSpline::FIRST, 8.75, CCubicSpline::SECOND, 10.0); /*--- at the knots ---*/ for (auto v : x) { @@ -59,7 +58,7 @@ TEST_CASE("C1DInterpolation", "[Toolboxes]") { } /*--- away from the knots ---*/ - for (auto& v : x) v = std::min(v+0.1, 2.0); + for (auto& v : x) v = std::min(v + 0.1, 2.0); for (auto v : x) { auto ref = myPoly(v); @@ -69,8 +68,7 @@ TEST_CASE("C1DInterpolation", "[Toolboxes]") { } /*--- Checks that intervals are mapped correctly ---*/ - for (size_t i = 1; i < x.size()-2; ++i) { - CHECK(L(x[i]) == Approx(0.5*(y[i]+y[i+1]))); + for (size_t i = 1; i < x.size() - 2; ++i) { + CHECK(L(x[i]) == Approx(0.5 * (y[i] + y[i + 1]))); } } - diff --git a/UnitTests/Common/toolboxes/CQuasiNewtonInvLeastSquares_tests.cpp b/UnitTests/Common/toolboxes/CQuasiNewtonInvLeastSquares_tests.cpp index d27e55cfd20..2d336ce7db9 100644 --- a/UnitTests/Common/toolboxes/CQuasiNewtonInvLeastSquares_tests.cpp +++ b/UnitTests/Common/toolboxes/CQuasiNewtonInvLeastSquares_tests.cpp @@ -33,48 +33,40 @@ struct Problem { static constexpr int N = 4; - const passivedouble coeffs[N][N] = {{0.5, -0.7, 0.2, 3.0}, - {1.0, -0.2, -0.6, 0.0}, - {0.1, 0.2, 3.14, -1.0}, - {-1.0, -0.4, 0.0, 1.6}}; + const passivedouble coeffs[N][N] = { + {0.5, -0.7, 0.2, 3.0}, {1.0, -0.2, -0.6, 0.0}, {0.1, 0.2, 3.14, -1.0}, {-1.0, -0.4, 0.0, 1.6}}; /*--- Row sum, sol should be {1.0}. ---*/ const passivedouble rhs[N] = {3.0, 0.2, 2.44, 0.2}; passivedouble sol[N] = {0.0}; - template + template void iterate(const T& x) { - for(int i=0; i +template void iterate(P& p, Q& q) { p.iterate(q); - for(int i=0; i qnils(Problem::N+1, Problem::N, 1); + CQuasiNewtonInvLeastSquares qnils(Problem::N + 1, Problem::N, 1); /*--- Solve ---*/ - for(int i=0; i<=Problem::N; ++i) - iterate(p, qnils); + for (int i = 0; i <= Problem::N; ++i) iterate(p, qnils); /*--- Check we solved in N+1 iterations. ---*/ - for(int i=0; i nd3(Nd_MPI_Environment(), nd2); /*-- Check gathered structure, non-const look-up. --*/ - REQUIRE( nd3.size() == size ); - for(size_t r=0; r& nd3_const = nd3; - REQUIRE( nd3_const.size() == size ); - for(size_t r=0; r a1( - std::make_pair( (size_t)(3+rank), [rank,A](int i) { - return (unsigned long)(2+rank+i); - }) - ); + NdFlattener<1, unsigned long> a1( + std::make_pair((size_t)(3 + rank), [rank, A](int i) { return (unsigned long)(2 + rank + i); })); const NdFlattener<1, unsigned long>& a1_const = a1; - REQUIRE( a1.size() == 3 + rank ); - for(size_t i=0; i<3+rank; i++){ - REQUIRE( a1[i] == 2 + rank + i ); - REQUIRE( a1_const[i] == 2 + rank + i ); + REQUIRE(a1.size() == 3 + rank); + for (size_t i = 0; i < 3 + rank; i++) { + REQUIRE(a1[i] == 2 + rank + i); + REQUIRE(a1_const[i] == 2 + rank + i); } a1[0] = 1; - REQUIRE( a1_const.data()[0] == 1 ); + REQUIRE(a1_const.data()[0] == 1); a1.data()[0] = 2 + rank; - REQUIRE( a1_const[0] == 2 + rank ); + REQUIRE(a1_const[0] == 2 + rank); const NdFlattener<2, unsigned long> a2_const(Nd_MPI_Environment(MPI_UNSIGNED_LONG), a1); - REQUIRE( a2_const.size() == size ); - for(size_t r=0; r +template struct arithmeticFun { - static T f(T A, T B, T C, T D, U x, U y) { - return pow( (A+B-x*C)/y + pow(A*x-C/D, y), D); - } + static T f(T A, T B, T C, T D, U x, U y) { return pow((A + B - x * C) / y + pow(A * x - C / D, y), D); } }; -template +template struct logicFun { static T f(T A, T B, T C, T D, U x, U y) { // (B < A || B >= C) && ... - return fmax(B < A, B >= fmin(C,-D)) * (abs(A) == abs(x)) * (abs(C) != abs(y)); + return fmax(B < A, B >= fmin(C, -D)) * (abs(A) == abs(x)) * (abs(C) != abs(y)); } }; -template class Fun, class T, class U> +template