diff --git a/.clang-format b/.clang-format index a982b92..293b66b 100644 --- a/.clang-format +++ b/.clang-format @@ -1,3 +1,10 @@ +# SPDX-FileCopyrightText: 2021 SeisSol Group +# +# SPDX-License-Identifier: BSD-3-Clause +# SPDX-LicenseComments: Full text under /LICENSE and /LICENSES/ +# +# SPDX-FileContributor: Author lists in /AUTHORS and /CITATION.cff + Language: Cpp AccessModifierOffset: -4 AlignAfterOpenBracket: Align @@ -19,9 +26,9 @@ AllowShortLoopsOnASingleLine: false AlwaysBreakAfterDefinitionReturnType: None AlwaysBreakAfterReturnType: None AlwaysBreakBeforeMultilineStrings: false -AlwaysBreakTemplateDeclarations: MultiLine -BinPackArguments: true -BinPackParameters: true +AlwaysBreakTemplateDeclarations: Yes +BinPackArguments: false +BinPackParameters: false BraceWrapping: AfterCaseLabel: false AfterClass: false @@ -63,19 +70,22 @@ ForEachMacros: - foreach - Q_FOREACH - BOOST_FOREACH -IncludeBlocks: Preserve +IncludeBlocks: Regroup IncludeCategories: + # keep the doctest headers in front + - Regex: '^(<|")doctest' + Priority: 1 - Regex: '^"(llvm|llvm-c|clang|clang-c)/' - Priority: 2 - - Regex: '^(<|"(gtest|gmock|isl|json)/)' Priority: 3 + - Regex: '^(<|"(gtest|gmock|isl|json)/)' + Priority: 4 - Regex: '.*' - Priority: 1 + Priority: 2 IncludeIsMainRegex: '(Test)?$' IndentCaseLabels: false IndentPPDirectives: None -IndentWidth: 4 -IndentWrappedFunctionNames: false +IndentWidth: 2 +IndentWrappedFunctionNames: true JavaScriptQuotes: Leave JavaScriptWrapImports: true KeepEmptyLinesAtTheStartOfBlocks: true @@ -96,6 +106,7 @@ PenaltyBreakTemplateDeclaration: 10 PenaltyExcessCharacter: 1000000 PenaltyReturnTypeOnItsOwnLine: 60 PointerAlignment: Left +QualifierAlignment: Left ReflowComments: true SortIncludes: true SortUsingDeclarations: true @@ -121,4 +132,3 @@ StatementMacros: - QT_REQUIRE_VERSION TabWidth: 8 UseTab: Never - diff --git a/.flake8 b/.flake8 new file mode 100644 index 0000000..d3db4a8 --- /dev/null +++ b/.flake8 @@ -0,0 +1,20 @@ +# SPDX-FileCopyrightText: 2024 SeisSol Group +# +# SPDX-License-Identifier: BSD-3-Clause +# SPDX-LicenseComments: Full text under /LICENSE and /LICENSES/ +# +# SPDX-FileContributor: Author lists in /AUTHORS and /CITATION.cff + +# reason for rule exclusion: +# * BLK100: conflicts with isort, i.e. I001,..,I005 (which is more important to be adhered) +# * E501: hard to enforce; makes tensor operations partially unreadable +# * E731: decreases readability +# * E203: decreases readability; actually applied by black +# +# reason(s) for directory exclusion: +# * preprocessing: TODO, to be exluded from the repository +# * postprocessing: TODO, to be exluded from the repository +# * submodules: submodules, need to be handled separately + +[flake8] +extend-ignore = BLK100,E501,E731,E203 diff --git a/.gitignore b/.gitignore index 4ef2462..cc8b2fd 100644 --- a/.gitignore +++ b/.gitignore @@ -38,4 +38,3 @@ build*/ *.exe *.out *.app - diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..cc8dd71 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,89 @@ +# SPDX-FileCopyrightText: 2025 SeisSol Group +# +# SPDX-License-Identifier: BSD-3-Clause +# SPDX-LicenseComments: Full text under /LICENSE and /LICENSES/ +# +# SPDX-FileContributor: Author lists in /AUTHORS and /CITATION.cff + +--- + +repos: +- repo: https://github.com/pre-commit/pre-commit-hooks + rev: v6.0.0 + hooks: + - id: check-merge-conflict + name: '[GENERIC] merge conflict check' + - id: check-symlinks + name: '[GENERIC] symlink check' + - id: destroyed-symlinks + name: '[GENERIC] detect broken symlinks' + - id: detect-private-key + name: '[GENERIC] detect private keys uploaded by accident' + - id: check-case-conflict + name: '[GENERIC] detect OS file naming case conflicts' + - id: check-executables-have-shebangs + name: '[GENERIC] check for shebangs in executable files' + - id: check-illegal-windows-names + name: '[GENERIC] detect illegal Windows file names' + - id: check-json + name: '[JSON] check' + - id: check-xml + name: '[XML] check' + +- repo: https://github.com/DavidAnson/markdownlint-cli2 + rev: v0.18.1 + hooks: + - id: markdownlint-cli2 + name: '[MARKDOWN] lint' + +#- repo: https://github.com/fsfe/reuse-tool +# rev: v6.0.0 +# hooks: +# - id: reuse +# name: '[GENERIC] REUSE compatibiltiy' + +- repo: https://github.com/psf/black-pre-commit-mirror + rev: 25.1.0 + hooks: + - id: black + files: ^(?!preprocessing|postprocessing) + name: '[PYTHON] black' +- repo: https://github.com/pycqa/isort + rev: 6.0.1 + hooks: + - id: isort + files: ^(?!preprocessing|postprocessing) + args: ["--profile", "black"] + name: '[PYTHON] isort' +- repo: https://github.com/pycqa/bandit + rev: 1.8.6 + hooks: + - id: bandit + args: ["--confidence-level", "high", "--severity-level", "high"] + name: '[PYTHON] bandit' +- repo: https://github.com/pycqa/flake8 + rev: '7.3.0' + hooks: + - id: flake8 + files: ^(?!preprocessing|postprocessing) + name: '[PYTHON] Flake8' + +- repo: https://github.com/sphinx-contrib/sphinx-lint + rev: 'v1.0.0' + hooks: + - id: sphinx-lint + name: '[SPHINX/RST] sphinx lint' + +- repo: https://github.com/pre-commit/mirrors-clang-format + rev: 'v21.1.0' + hooks: + - id: clang-format + name: '[C++] clang-format' + +- repo: https://github.com/pre-commit/pre-commit-hooks + rev: v6.0.0 + hooks: + - id: end-of-file-fixer + name: '[GENERIC] newline eof' + - id: trailing-whitespace + name: '[GENERIC] remove trailing whitespace' diff --git a/CMakeLists.txt b/CMakeLists.txt index 4cc55a3..173a4f3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -257,7 +257,7 @@ if(EASICUBE) set_target_properties (easicube PROPERTIES INSTALL_RPATH_USE_LINK_PATH TRUE ) - + install (TARGETS easicube) else() message(WARNING "easicube needs easi to be compiled with ASAGI. Since this is not the case, easicube will be skipped.") diff --git a/README.md b/README.md index 15a8978..901af05 100644 --- a/README.md +++ b/README.md @@ -2,15 +2,20 @@ [![Documentation Status](https://readthedocs.org/projects/easyinit/badge/?version=latest)](https://easyinit.readthedocs.io/en/latest/?badge=latest) - -easi is a library for the **E**asy **I**nitialization of models in three (or less or more) dimensional domains. -The purpose of easi is to evaluate functions f : R^m -> R^n, +easi is a library for the **E**asy **I**nitialization of models +in three (or less or more) dimensional domains. +The purpose of easi is to evaluate functions $f : R^m \rightarrow R^n$, which are described in a [YAML](http://yaml.org) configuration file. In grid-based simulation software, such as [SeisSol](http://www.seissol.org>), easi may be used to define models. -In SeisSol, the function f maps every point in space (say x,y,z) to a vector of parameters (e.g. ρ, μ, and λ), +In SeisSol, the function $f$ maps every point in space +(say $x,y,z$) to a vector of parameters (e.g. $\rho$, $\mu$, and $\lambda$), which define a rheological model. -Here, over 5000 lines of model-specific Fortran code could be replaced with YAML files. +Here, over 5000 lines of model-specific Fortran +code could be replaced with YAML files. ## Documentation -The reference documentation can be found on [Read the Docs](https://easyinit.readthedocs.io) or be downloaded as [PDF manual](http://readthedocs.org/projects/easyinit/downloads/pdf/latest/). + +The reference documentation can be found on +[Read the Docs](https://easyinit.readthedocs.io) +or be downloaded as a [PDF manual](http://readthedocs.org/projects/easyinit/downloads/pdf/latest/). diff --git a/cmake/FindFILESYSTEM.cmake b/cmake/FindFILESYSTEM.cmake index 7bb6a50..981fe8e 100644 --- a/cmake/FindFILESYSTEM.cmake +++ b/cmake/FindFILESYSTEM.cmake @@ -6,7 +6,7 @@ # # NOTE: it is not an official cmake search file # authors: Carsten Uphoff, Ravil Dorozhinskii -# email: uphoff@in.tum.de, ravil.dorozhinskii@tum.de +# email: uphoff@in.tum.de, ravil.dorozhinskii@tum.de # diff --git a/cmake/FindNetCDF.cmake b/cmake/FindNetCDF.cmake index 5a4d3ab..8a88a00 100644 --- a/cmake/FindNetCDF.cmake +++ b/cmake/FindNetCDF.cmake @@ -141,4 +141,3 @@ include(FindPackageHandleStandardArgs) find_package_handle_standard_args(NetCDF REQUIRED_VARS NetCDF_LIBRARY NetCDF_INCLUDE_DIR VERSION_VAR NetCDF_VERSION) - diff --git a/cmake/easiConfig.cmake.in b/cmake/easiConfig.cmake.in index 82a2f34..173752f 100644 --- a/cmake/easiConfig.cmake.in +++ b/cmake/easiConfig.cmake.in @@ -16,4 +16,3 @@ endif() if (NOT TARGET easi::easi) include ("${CMAKE_CURRENT_LIST_DIR}/easiTargets.cmake") endif () - diff --git a/doc/Makefile b/doc/Makefile index 298ea9e..5128596 100644 --- a/doc/Makefile +++ b/doc/Makefile @@ -16,4 +16,4 @@ help: # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile - @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) \ No newline at end of file + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) diff --git a/doc/builders.rst b/doc/builders.rst index 2434eca..5564121 100644 --- a/doc/builders.rst +++ b/doc/builders.rst @@ -13,7 +13,7 @@ Defines parameters at nodes, which are interpolated inbetween nodes. !LayeredModel map: # Mapping to 1D (root component) - interpolation: (lower|upper|linear) + interpolation: (lower|upper|linear) parameters: [, , ...] # order of dimension nodes: : [, , ...] # key: node position, value: dimension values diff --git a/doc/compiling_dependencies.rst b/doc/compiling_dependencies.rst index 65babc3..47758a1 100644 --- a/doc/compiling_dependencies.rst +++ b/doc/compiling_dependencies.rst @@ -21,7 +21,7 @@ Alternatively for gcc compilers on SupermucNG: export CC=mpigcc 2. Asagi - + See https://seissol.readthedocs.io/en/latest/asagi.html. 3. yaml-cpp @@ -32,7 +32,7 @@ On SupermucNG and with intel compilers: module load yaml-cpp/0.7.0-intel21 - + Alternatively you can build from source: .. code-block:: bash @@ -46,15 +46,15 @@ Alternatively you can build from source: make -j 4 make install cd ../.. - -4. ImpalaJIT + +4. ImpalaJIT .. code-block:: bash git clone git@github.com:uphoffc/ImpalaJIT # git clone https://github.com/uphoffc/ImpalaJIT.git - cd ImpalaJIT + cd ImpalaJIT mkdir build && cd build cmake .. -DCMAKE_INSTALL_PREFIX=$HOME make -j 4 @@ -73,4 +73,3 @@ Alternatively you can build from source: make local cp -r install/* ~ cd .. - diff --git a/doc/conf.py b/doc/conf.py index 61b2de1..abfe4b0 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -19,14 +19,14 @@ # -- Project information ----------------------------------------------------- -project = 'easi' -copyright = '2018, Carsten Uphoff' -author = 'Carsten Uphoff' +project = "easi" +copyright = "2018, Carsten Uphoff" +author = "Carsten Uphoff" # The short X.Y version -version = '' +version = "" # The full version, including alpha/beta/rc tags -release = '' +release = "" # -- General configuration --------------------------------------------------- @@ -39,20 +39,20 @@ # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ - 'sphinx.ext.mathjax', + "sphinx.ext.mathjax", ] # Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] +templates_path = ["_templates"] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] -source_suffix = '.rst' +source_suffix = ".rst" # The master toctree document. -master_doc = 'index' +master_doc = "index" # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. @@ -64,7 +64,7 @@ # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. -exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] +exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] # The name of the Pygments (syntax highlighting) style to use. pygments_style = None @@ -75,7 +75,7 @@ # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # -html_theme = 'sphinx_rtd_theme' +html_theme = "sphinx_rtd_theme" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the @@ -86,7 +86,7 @@ # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] +html_static_path = ["_static"] # Custom sidebar templates, must be a dictionary that maps document names # to template names. @@ -102,7 +102,7 @@ # -- Options for HTMLHelp output --------------------------------------------- # Output file base name for HTML help builder. -htmlhelp_basename = 'easidoc' +htmlhelp_basename = "easidoc" # -- Options for LaTeX output ------------------------------------------------ @@ -111,15 +111,12 @@ # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. # # 'preamble': '', - # Latex figure (float) alignment # # 'figure_align': 'htbp', @@ -129,8 +126,7 @@ # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ - (master_doc, 'easi.tex', 'easi Documentation', - 'Carsten Uphoff', 'manual'), + (master_doc, "easi.tex", "easi Documentation", "Carsten Uphoff", "manual"), ] @@ -138,10 +134,7 @@ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). -man_pages = [ - (master_doc, 'easi', 'easi Documentation', - [author], 1) -] +man_pages = [(master_doc, "easi", "easi Documentation", [author], 1)] # -- Options for Texinfo output ---------------------------------------------- @@ -150,9 +143,15 @@ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - (master_doc, 'easi', 'easi Documentation', - author, 'easi', 'One line description of project.', - 'Miscellaneous'), + ( + master_doc, + "easi", + "easi Documentation", + author, + "easi", + "One line description of project.", + "Miscellaneous", + ), ] @@ -171,7 +170,7 @@ # epub_uid = '' # A list of files that should not be packed into the epub file. -epub_exclude_files = ['search.html'] +epub_exclude_files = ["search.html"] # -- Extension configuration ------------------------------------------------- diff --git a/doc/getting_started.rst b/doc/getting_started.rst index d5da46c..77c4697 100644 --- a/doc/getting_started.rst +++ b/doc/getting_started.rst @@ -69,7 +69,7 @@ For example, such a configuration file could look like the following: -3000.0: [2700.0, 2.1168e10, 2.7891e10] -6000.0: [2870.0, 3.1041e10, 3.8591e10] -31000.0: [3500.0, 3.9847e10, 4.3525e10] - -50000.0: [3200.0, 6.4800e10, 6.5088e10] + -50000.0: [3200.0, 6.4800e10, 6.5088e10] Here, all points with y-coordinate inbetween -5 km and +5 km would be assigned constant model parameters. For all other points, a linear @@ -85,7 +85,7 @@ Here, we may use the YAMLParser class which creates models from YAML configurati :linenos: easi::YAMLParser parser(3); - easi::Component* model = parser.parse("test.yaml"); + easi::Component* model = parser.parse("test.yaml"); The argument in YAMLParser's constructor is the dimension of the input vectors. Here, we take 3 as we want to query our model in a 3-dimensional space. @@ -116,7 +116,7 @@ structs, and hence we use an ArrayOfStructsAdapter. (Note that additional adapters can be implemented by overriding the class ResultAdapter.) .. code-block:: cpp - + struct ElasticMaterial { double lambda, mu, rho; }; @@ -158,23 +158,23 @@ The whole sample code is listed in the following: query.x(1,1) = 3.0; query.x(1,2) = -4.0; query.group(1) = 1; - + easi::YAMLParser parser(3); - easi::Component* model = parser.parse("test.yaml"); - + easi::Component* model = parser.parse("test.yaml"); + ElasticMaterial material[2]; easi::ArrayOfStructsAdapter adapter(material); adapter.addBindingPoint("lambda", &ElasticMaterial::lambda); adapter.addBindingPoint("mu", &ElasticMaterial::mu); adapter.addBindingPoint("rho", &ElasticMaterial::rho); - + model->evaluate(query, adapter); - + delete model; - + for (unsigned j = 0; j < 2; ++j) { std::cout << material[j].lambda << " " << material[j].mu << " " << material[j].rho << std::endl; - } + } return 0; } diff --git a/doc/maps.rst b/doc/maps.rst index 381d898..fa3a40a 100644 --- a/doc/maps.rst +++ b/doc/maps.rst @@ -96,7 +96,12 @@ Assigns a value using a polynomial for every parameter. FunctionMap ----------- -Implements a mapping described by an ImpalaJIT function. +Implements a mapping described by an ImpalaJIT function; +that is a function supporting all C math functions, floating point operations, if-else, and return. +Local variables are also supported. + +Only enabled if Lua is compiled in. +(NOTE: ImpalaJIT as dependency is only required for easi below version 1.5.0) .. code-block:: YAML @@ -121,12 +126,57 @@ Implements a mapping described by an ImpalaJIT function. The must an be ImpalaJIT function (without surrounding curly braces). The function gets passed all input dimensions automatically. -**Known limitations:** +**Known limitations (due to the ImpalaJIT syntax):** - No comments (// or /\* \*/) - No exponential notation (use pow(10.,3.) instead of 1e3) - No 'else if' (use else { if () {}}). +LuaMap +------ + +A Lua function. + +The function needs to be called ``f`` and accept a single input parameter. +This input parameter will contain all input variables in a dictionary. +The output variables are defined by the extra ``returns`` field. + +.. code-block:: YAML + + !LuaMap + returns: [outvar1, ..., outvarN] + function: | + function f(coords) + # use like e.g. coords["x"], coords["y"], coords["z"] + + # code + + return { + "outvar1": value1, + ... + "outvarN": valueN, + } + end function + +:Domain: + *inherited* +:Codomain: + given in ``returns`` +:Example: + Given input dimensions are x,y,z. Same example as for the ``FunctionMap``. + .. code-block:: YAML + + !LuaMap + returns: [p] + function: | + function f(x) + return { + "p": x["x"] * x["y"] * x["z"], + } + end function + + Will return :math:`p = x \cdot y \cdot z`. + ASAGI ----- @@ -219,7 +269,7 @@ ratio R (where :math:`R=1/(1+S)`), the effective confining stress :math:`s2ratio = (s_2-s_3)/(s_1-s_3)`, where :math:`s_1>s_2>s_3` are the principal stress magnitudes, following the procedure described in Ulrich et al. (2019), methods section 'Initial Stress'. To prescribe R, static and dynamic friction -(mu\_s and mu\_d) as well as cohesion are required. +(mu\_s and mu\_d) as well as cohesion are required. .. code-block:: YAML @@ -253,12 +303,12 @@ Assuming mu_d=0.6, S_v = 1 favours normal faulting on a 60° dipping fault plane S_v = 2 favours strike-slip faulting on a vertical fault plane making an angle of 30° with SH_max and S_v = 3 favours reverse faulting on a 30° dipping fault plane striking SH_max. -The principal stress magnitudes are prescribed by the relative fault strength S (related to the relative prestress ratio R by :math:`R=1/(1+S)`), +The principal stress magnitudes are prescribed by the relative fault strength S (related to the relative prestress ratio R by :math:`R=1/(1+S)`), the vertical stress sig_zz and the stress shape ratio :math:`s2ratio = (s_2-s_3)/(s_1-s_3)`, where :math:`s_1>s_2>s_3` are the principal stress magnitudes, following the procedure described in Ulrich et al. (2019), methods section 'Initial Stress'. To prescribe S, static and dynamic friction -(mu\_s and mu\_d) as well as cohesion are required. +(mu\_s and mu\_d) as well as cohesion are required. @@ -334,7 +384,7 @@ Evaluates application-defined functions. :Example: We want to create a function which takes three input parameters and supplies two output parameters: - + .. code-block:: cpp #include "easi/util/MagicStruct.h" @@ -358,7 +408,7 @@ Evaluates application-defined functions. SELF_AWARE_STRUCT(Special::in, i1, i2, i3) SELF_AWARE_STRUCT(Special::out, o1, o2) - + Register this file with the parser: .. code-block:: cpp diff --git a/examples/2_prem.yaml b/examples/2_prem.yaml index eab32e4..dc96e67 100644 --- a/examples/2_prem.yaml +++ b/examples/2_prem.yaml @@ -128,4 +128,3 @@ components: vp: 1.450 vs: 0.000 components: *PREM2SeisSol - diff --git a/examples/6_lua.yaml b/examples/6_lua.yaml index 91549f3..4d3fbc5 100644 --- a/examples/6_lua.yaml +++ b/examples/6_lua.yaml @@ -16,4 +16,4 @@ components: !LuaMap return { effectiveConfiningStress = 2670.0 * 0.21 * 9.8 * math.min(-100.0, x["elevation"] + x["z"]) } - end \ No newline at end of file + end diff --git a/examples/7_gassmann.yaml b/examples/7_gassmann.yaml index 6008f15..8f91bc5 100644 --- a/examples/7_gassmann.yaml +++ b/examples/7_gassmann.yaml @@ -6,7 +6,7 @@ parameters: [bulk_solid, bulk_fluid, porosity, rho, rho_fluid, mu, lambda] model: !Include 7_poroelastic.yaml ### Evaluate Gassmann equivalent as FunctionMap (requires ImpalaJIT) #components: !FunctionMap -# map: +# map: # rho: return porosity * rho_fluid + (1-porosity) * rho; # mu: return mu; # lambda: | @@ -20,17 +20,15 @@ model: !Include 7_poroelastic.yaml components: !LuaMap returns: [rho, mu, lambda] function: - function f(x) + function f(x) bulk_matrix = x["lambda"] + 2.0/3.0 * x["mu"] a = (1 - bulk_matrix / x["bulk_solid"])^2 b = x["porosity"] / x["bulk_fluid"] c = (1 - x["porosity"]) / x["bulk_solid"] d = bulk_matrix / (x["bulk_solid"])^2 - return { + return { rho = x["porosity"] * x["rho_fluid"] + (1-x["porosity"]) * x["rho"], mu = x["mu"], lambda = bulk_matrix + a / (b + c - d) } end - - diff --git a/examples/7_poroelastic.yaml b/examples/7_poroelastic.yaml index a162ede..d8cc1e0 100644 --- a/examples/7_poroelastic.yaml +++ b/examples/7_poroelastic.yaml @@ -2,7 +2,7 @@ components: - !GroupFilter groups: [1] - components: + components: map: rho: 2.39e3 bulk_solid: 22.6e9 @@ -24,7 +24,7 @@ components: mu: 0.695e9 permeability: 2.00e-12 tortuosity: 1 - porosity: 0.4 + porosity: 0.4 rho_fluid: 1.03e3 bulk_fluid: 2.3e9 viscosity: 6.9e-4 diff --git a/examples/integralToLayeredModel.py b/examples/integralToLayeredModel.py index 6bf5c18..f8fbab7 100644 --- a/examples/integralToLayeredModel.py +++ b/examples/integralToLayeredModel.py @@ -8,17 +8,17 @@ # Linear interpolation with nodes z_k: I_k is equivalent, because # sigma_zz = z*(I_k-I_{k+1})/(z_k-z_{k+1}) + (z_k*I_{k+1}-z_{k+1}*I_k)/(z_k-z_{k+1}) # = I_k + (z-z_k)*\rho_k*g. -# The last z-coordinate +# The last z-coordinate -layers = [0.0, -2000.0, -6000.0, -12000.0, -23000.0, -100000.0, float('inf')] -rho = [1000.0, 2720.0, 2860.0, 3050.0, 3300.0, float('inf')] +layers = [0.0, -2000.0, -6000.0, -12000.0, -23000.0, -100000.0, float("inf")] +rho = [1000.0, 2720.0, 2860.0, 3050.0, 3300.0, float("inf")] integral = 0.0 -print('!LayeredModel') -print('map: ??') -print('interpolation: linear') -print('parameters: [s_zz}') -print('nodes:') -for i in range(len(layers)-1): - print(' {}: [{}]'.format(layers[i], integral)) - integral = integral + (layers[i+1]-layers[i]) * rho[i] * 9.8 +print("!LayeredModel") +print("map: ??") +print("interpolation: linear") +print("parameters: [s_zz}") +print("nodes:") +for i in range(len(layers) - 1): + print(" {}: [{}]".format(layers[i], integral)) + integral = integral + (layers[i + 1] - layers[i]) * rho[i] * 9.8 diff --git a/external/lua51/lmathx.c b/external/lua51/lmathx.c index cd61819..1bca164 100644 --- a/external/lua51/lmathx.c +++ b/external/lua51/lmathx.c @@ -1,270 +1,244 @@ /* -* lmathx.c -* C99 math functions for Lua -* Luiz Henrique de Figueiredo -* 04 Apr 2010 22:53:32 -* This code is hereby placed in the public domain. -*/ + * lmathx.c + * C99 math functions for Lua + * Luiz Henrique de Figueiredo + * 04 Apr 2010 22:53:32 + * This code is hereby placed in the public domain. + */ #define _GNU_SOURCE 1 -#include -#include - +#include "lauxlib.h" #include "lua.h" #include "lualib.h" -#include "lauxlib.h" -#define A(i) luaL_checknumber(L,i) +#include +#include -static int Lacosh(lua_State *L) -{ - lua_pushnumber(L,acosh(A(1))); +#define A(i) luaL_checknumber(L, i) + +static int Lacosh(lua_State* L) { + lua_pushnumber(L, acosh(A(1))); return 1; } -static int Lasinh(lua_State *L) -{ - lua_pushnumber(L,asinh(A(1))); +static int Lasinh(lua_State* L) { + lua_pushnumber(L, asinh(A(1))); return 1; } -static int Latanh(lua_State *L) -{ - lua_pushnumber(L,atanh(A(1))); +static int Latanh(lua_State* L) { + lua_pushnumber(L, atanh(A(1))); return 1; } -static int Lcbrt(lua_State *L) -{ - lua_pushnumber(L,cbrt(A(1))); +static int Lcbrt(lua_State* L) { + lua_pushnumber(L, cbrt(A(1))); return 1; } -static int Lcopysign(lua_State *L) -{ - lua_pushnumber(L,copysign(A(1),A(2))); +static int Lcopysign(lua_State* L) { + lua_pushnumber(L, copysign(A(1), A(2))); return 1; } -static int Lerf(lua_State *L) -{ - lua_pushnumber(L,erf(A(1))); +static int Lerf(lua_State* L) { + lua_pushnumber(L, erf(A(1))); return 1; } -static int Lerfc(lua_State *L) -{ - lua_pushnumber(L,erfc(A(1))); +static int Lerfc(lua_State* L) { + lua_pushnumber(L, erfc(A(1))); return 1; } -static int Lexp2(lua_State *L) -{ - lua_pushnumber(L,exp2(A(1))); +static int Lexp2(lua_State* L) { + lua_pushnumber(L, exp2(A(1))); return 1; } -static int Lexpm1(lua_State *L) -{ - lua_pushnumber(L,expm1(A(1))); +static int Lexpm1(lua_State* L) { + lua_pushnumber(L, expm1(A(1))); return 1; } -static int Lfdim(lua_State *L) -{ - lua_pushnumber(L,fdim(A(1),A(2))); +static int Lfdim(lua_State* L) { + lua_pushnumber(L, fdim(A(1), A(2))); return 1; } -static int Lfma(lua_State *L) -{ - lua_pushnumber(L,fma(A(1),A(2),A(3))); +static int Lfma(lua_State* L) { + lua_pushnumber(L, fma(A(1), A(2), A(3))); return 1; } -static int Lfmax(lua_State *L) -{ - int i,n=lua_gettop(L); - lua_Number m=A(1); - for (i=2; i<=n; i++) m=fmax(m,A(i)); - lua_pushnumber(L,m); - return 1; +static int Lfmax(lua_State* L) { + int i, n = lua_gettop(L); + lua_Number m = A(1); + for (i = 2; i <= n; i++) + m = fmax(m, A(i)); + lua_pushnumber(L, m); + return 1; } -static int Lfmin(lua_State *L) -{ - int i,n=lua_gettop(L); - lua_Number m=A(1); - for (i=2; i<=n; i++) m=fmin(m,A(i)); - lua_pushnumber(L,m); - return 1; +static int Lfmin(lua_State* L) { + int i, n = lua_gettop(L); + lua_Number m = A(1); + for (i = 2; i <= n; i++) + m = fmin(m, A(i)); + lua_pushnumber(L, m); + return 1; } -static int Lfpclassify(lua_State *L) -{ - switch (fpclassify(A(1))) - { - case FP_INFINITE: lua_pushliteral(L,"inf"); break; - case FP_NAN: lua_pushliteral(L,"nan"); break; - case FP_NORMAL: lua_pushliteral(L,"normal"); break; - case FP_SUBNORMAL: lua_pushliteral(L,"subnormal"); break; - case FP_ZERO: lua_pushliteral(L,"zero"); break; - } - return 1; +static int Lfpclassify(lua_State* L) { + switch (fpclassify(A(1))) { + case FP_INFINITE: + lua_pushliteral(L, "inf"); + break; + case FP_NAN: + lua_pushliteral(L, "nan"); + break; + case FP_NORMAL: + lua_pushliteral(L, "normal"); + break; + case FP_SUBNORMAL: + lua_pushliteral(L, "subnormal"); + break; + case FP_ZERO: + lua_pushliteral(L, "zero"); + break; + } + return 1; } -static int Lhypot(lua_State *L) -{ - lua_pushnumber(L,hypot(A(1),A(2))); +static int Lhypot(lua_State* L) { + lua_pushnumber(L, hypot(A(1), A(2))); return 1; } -static int Lisfinite(lua_State *L) -{ - lua_pushboolean(L,isfinite(A(1))); +static int Lisfinite(lua_State* L) { + lua_pushboolean(L, isfinite(A(1))); return 1; } -static int Lisinf(lua_State *L) -{ - lua_pushboolean(L,isinf(A(1))); +static int Lisinf(lua_State* L) { + lua_pushboolean(L, isinf(A(1))); return 1; } -static int Lisnan(lua_State *L) -{ - lua_pushboolean(L,isnan(A(1))); +static int Lisnan(lua_State* L) { + lua_pushboolean(L, isnan(A(1))); return 1; } -static int Lisnormal(lua_State *L) -{ - lua_pushboolean(L,isnormal(A(1))); +static int Lisnormal(lua_State* L) { + lua_pushboolean(L, isnormal(A(1))); return 1; } -static int Llgamma(lua_State *L) -{ - lua_pushnumber(L,lgamma(A(1))); +static int Llgamma(lua_State* L) { + lua_pushnumber(L, lgamma(A(1))); return 1; } -static int Llog1p(lua_State *L) -{ - lua_pushnumber(L,log1p(A(1))); +static int Llog1p(lua_State* L) { + lua_pushnumber(L, log1p(A(1))); return 1; } -static int Llog2(lua_State *L) -{ - lua_pushnumber(L,log2(A(1))); +static int Llog2(lua_State* L) { + lua_pushnumber(L, log2(A(1))); return 1; } -static int Llogb(lua_State *L) -{ - lua_pushnumber(L,logb(A(1))); +static int Llogb(lua_State* L) { + lua_pushnumber(L, logb(A(1))); return 1; } -static int Lnearbyint(lua_State *L) -{ - lua_pushnumber(L,nearbyint(A(1))); +static int Lnearbyint(lua_State* L) { + lua_pushnumber(L, nearbyint(A(1))); return 1; } -static int Lnextafter(lua_State *L) -{ - lua_pushnumber(L,nextafter(A(1),A(2))); +static int Lnextafter(lua_State* L) { + lua_pushnumber(L, nextafter(A(1), A(2))); return 1; } -static int Lremainder(lua_State *L) -{ - lua_pushnumber(L,remainder(A(1),A(2))); +static int Lremainder(lua_State* L) { + lua_pushnumber(L, remainder(A(1), A(2))); return 1; } -static int Lrint(lua_State *L) -{ - lua_pushnumber(L,rint(A(1))); +static int Lrint(lua_State* L) { + lua_pushnumber(L, rint(A(1))); return 1; } -static int Lround(lua_State *L) -{ - lua_pushnumber(L,round(A(1))); +static int Lround(lua_State* L) { + lua_pushnumber(L, round(A(1))); return 1; } -static int Lscalbn(lua_State *L) -{ - lua_pushnumber(L,scalbn(A(1),(int)A(2))); +static int Lscalbn(lua_State* L) { + lua_pushnumber(L, scalbn(A(1), (int)A(2))); return 1; } -static int Lsignbit(lua_State *L) -{ - lua_pushboolean(L,signbit(A(1))); +static int Lsignbit(lua_State* L) { + lua_pushboolean(L, signbit(A(1))); return 1; } -static int Ltgamma(lua_State *L) -{ - lua_pushnumber(L,tgamma(A(1))); +static int Ltgamma(lua_State* L) { + lua_pushnumber(L, tgamma(A(1))); return 1; } -static int Ltrunc(lua_State *L) -{ - lua_pushnumber(L,trunc(A(1))); +static int Ltrunc(lua_State* L) { + lua_pushnumber(L, trunc(A(1))); return 1; } -static const luaL_Reg R[] = -{ - { "acosh", Lacosh }, - { "asinh", Lasinh }, - { "atanh", Latanh }, - { "cbrt", Lcbrt }, - { "copysign", Lcopysign }, - { "erfc", Lerfc }, - { "erf", Lerf }, - { "exp2", Lexp2 }, - { "expm1", Lexpm1 }, - { "fdim", Lfdim }, - { "fma", Lfma }, - { "fmax", Lfmax }, - { "fmin", Lfmin }, - { "fpclassify", Lfpclassify }, - { "gamma", Ltgamma }, - { "hypot", Lhypot }, - { "isfinite", Lisfinite }, - { "isinf", Lisinf }, - { "isnan", Lisnan }, - { "isnormal", Lisnormal }, - { "lgamma", Llgamma }, - { "log1p", Llog1p }, - { "log2", Llog2 }, - { "logb", Llogb }, - { "nearbyint", Lnearbyint }, - { "nextafter", Lnextafter }, - { "remainder", Lremainder }, - { "rint", Lrint }, - { "round", Lround }, - { "scalbn", Lscalbn }, - { "signbit", Lsignbit }, - { "trunc", Ltrunc }, - { NULL, NULL } -}; - +static const luaL_Reg R[] = {{"acosh", Lacosh}, + {"asinh", Lasinh}, + {"atanh", Latanh}, + {"cbrt", Lcbrt}, + {"copysign", Lcopysign}, + {"erfc", Lerfc}, + {"erf", Lerf}, + {"exp2", Lexp2}, + {"expm1", Lexpm1}, + {"fdim", Lfdim}, + {"fma", Lfma}, + {"fmax", Lfmax}, + {"fmin", Lfmin}, + {"fpclassify", Lfpclassify}, + {"gamma", Ltgamma}, + {"hypot", Lhypot}, + {"isfinite", Lisfinite}, + {"isinf", Lisinf}, + {"isnan", Lisnan}, + {"isnormal", Lisnormal}, + {"lgamma", Llgamma}, + {"log1p", Llog1p}, + {"log2", Llog2}, + {"logb", Llogb}, + {"nearbyint", Lnearbyint}, + {"nextafter", Lnextafter}, + {"remainder", Lremainder}, + {"rint", Lrint}, + {"round", Lround}, + {"scalbn", Lscalbn}, + {"signbit", Lsignbit}, + {"trunc", Ltrunc}, + {NULL, NULL}}; -LUALIB_API int luaopen_mathx(lua_State *L) -{ - luaL_register(L,LUA_MATHLIBNAME,R); - lua_pushnumber(L,INFINITY); - lua_setfield(L,-2,"infinity"); - lua_pushnumber(L,NAN); - lua_setfield(L,-2,"nan"); - return 1; +LUALIB_API int luaopen_mathx(lua_State* L) { + luaL_register(L, LUA_MATHLIBNAME, R); + lua_pushnumber(L, INFINITY); + lua_setfield(L, -2, "infinity"); + lua_pushnumber(L, NAN); + lua_setfield(L, -2, "nan"); + return 1; } diff --git a/external/lua52/lmathx.c b/external/lua52/lmathx.c index 932b4b2..e6e89d0 100644 --- a/external/lua52/lmathx.c +++ b/external/lua52/lmathx.c @@ -1,271 +1,245 @@ /* -* lmathx.c -* C99 math functions for Lua -* Luiz Henrique de Figueiredo -* 19 Apr 2012 19:29:09 -* This code is hereby placed in the public domain. -*/ + * lmathx.c + * C99 math functions for Lua + * Luiz Henrique de Figueiredo + * 19 Apr 2012 19:29:09 + * This code is hereby placed in the public domain. + */ #define _GNU_SOURCE 1 -#include -#include - +#include "lauxlib.h" #include "lua.h" #include "lualib.h" -#include "lauxlib.h" -#define A(i) luaL_checknumber(L,i) +#include +#include -static int Lacosh(lua_State *L) -{ - lua_pushnumber(L,acosh(A(1))); +#define A(i) luaL_checknumber(L, i) + +static int Lacosh(lua_State* L) { + lua_pushnumber(L, acosh(A(1))); return 1; } -static int Lasinh(lua_State *L) -{ - lua_pushnumber(L,asinh(A(1))); +static int Lasinh(lua_State* L) { + lua_pushnumber(L, asinh(A(1))); return 1; } -static int Latanh(lua_State *L) -{ - lua_pushnumber(L,atanh(A(1))); +static int Latanh(lua_State* L) { + lua_pushnumber(L, atanh(A(1))); return 1; } -static int Lcbrt(lua_State *L) -{ - lua_pushnumber(L,cbrt(A(1))); +static int Lcbrt(lua_State* L) { + lua_pushnumber(L, cbrt(A(1))); return 1; } -static int Lcopysign(lua_State *L) -{ - lua_pushnumber(L,copysign(A(1),A(2))); +static int Lcopysign(lua_State* L) { + lua_pushnumber(L, copysign(A(1), A(2))); return 1; } -static int Lerf(lua_State *L) -{ - lua_pushnumber(L,erf(A(1))); +static int Lerf(lua_State* L) { + lua_pushnumber(L, erf(A(1))); return 1; } -static int Lerfc(lua_State *L) -{ - lua_pushnumber(L,erfc(A(1))); +static int Lerfc(lua_State* L) { + lua_pushnumber(L, erfc(A(1))); return 1; } -static int Lexp2(lua_State *L) -{ - lua_pushnumber(L,exp2(A(1))); +static int Lexp2(lua_State* L) { + lua_pushnumber(L, exp2(A(1))); return 1; } -static int Lexpm1(lua_State *L) -{ - lua_pushnumber(L,expm1(A(1))); +static int Lexpm1(lua_State* L) { + lua_pushnumber(L, expm1(A(1))); return 1; } -static int Lfdim(lua_State *L) -{ - lua_pushnumber(L,fdim(A(1),A(2))); +static int Lfdim(lua_State* L) { + lua_pushnumber(L, fdim(A(1), A(2))); return 1; } -static int Lfma(lua_State *L) -{ - lua_pushnumber(L,fma(A(1),A(2),A(3))); +static int Lfma(lua_State* L) { + lua_pushnumber(L, fma(A(1), A(2), A(3))); return 1; } -static int Lfmax(lua_State *L) -{ - int i,n=lua_gettop(L); - lua_Number m=A(1); - for (i=2; i<=n; i++) m=fmax(m,A(i)); - lua_pushnumber(L,m); - return 1; +static int Lfmax(lua_State* L) { + int i, n = lua_gettop(L); + lua_Number m = A(1); + for (i = 2; i <= n; i++) + m = fmax(m, A(i)); + lua_pushnumber(L, m); + return 1; } -static int Lfmin(lua_State *L) -{ - int i,n=lua_gettop(L); - lua_Number m=A(1); - for (i=2; i<=n; i++) m=fmin(m,A(i)); - lua_pushnumber(L,m); - return 1; +static int Lfmin(lua_State* L) { + int i, n = lua_gettop(L); + lua_Number m = A(1); + for (i = 2; i <= n; i++) + m = fmin(m, A(i)); + lua_pushnumber(L, m); + return 1; } -static int Lfpclassify(lua_State *L) -{ - switch (fpclassify(A(1))) - { - case FP_INFINITE: lua_pushliteral(L,"inf"); break; - case FP_NAN: lua_pushliteral(L,"nan"); break; - case FP_NORMAL: lua_pushliteral(L,"normal"); break; - case FP_SUBNORMAL: lua_pushliteral(L,"subnormal"); break; - case FP_ZERO: lua_pushliteral(L,"zero"); break; - } - return 1; +static int Lfpclassify(lua_State* L) { + switch (fpclassify(A(1))) { + case FP_INFINITE: + lua_pushliteral(L, "inf"); + break; + case FP_NAN: + lua_pushliteral(L, "nan"); + break; + case FP_NORMAL: + lua_pushliteral(L, "normal"); + break; + case FP_SUBNORMAL: + lua_pushliteral(L, "subnormal"); + break; + case FP_ZERO: + lua_pushliteral(L, "zero"); + break; + } + return 1; } -static int Lhypot(lua_State *L) -{ - lua_pushnumber(L,hypot(A(1),A(2))); +static int Lhypot(lua_State* L) { + lua_pushnumber(L, hypot(A(1), A(2))); return 1; } -static int Lisfinite(lua_State *L) -{ - lua_pushboolean(L,isfinite(A(1))); +static int Lisfinite(lua_State* L) { + lua_pushboolean(L, isfinite(A(1))); return 1; } -static int Lisinf(lua_State *L) -{ - lua_pushboolean(L,isinf(A(1))); +static int Lisinf(lua_State* L) { + lua_pushboolean(L, isinf(A(1))); return 1; } -static int Lisnan(lua_State *L) -{ - lua_pushboolean(L,isnan(A(1))); +static int Lisnan(lua_State* L) { + lua_pushboolean(L, isnan(A(1))); return 1; } -static int Lisnormal(lua_State *L) -{ - lua_pushboolean(L,isnormal(A(1))); +static int Lisnormal(lua_State* L) { + lua_pushboolean(L, isnormal(A(1))); return 1; } -static int Llgamma(lua_State *L) -{ - lua_pushnumber(L,lgamma(A(1))); +static int Llgamma(lua_State* L) { + lua_pushnumber(L, lgamma(A(1))); return 1; } -static int Llog1p(lua_State *L) -{ - lua_pushnumber(L,log1p(A(1))); +static int Llog1p(lua_State* L) { + lua_pushnumber(L, log1p(A(1))); return 1; } -static int Llog2(lua_State *L) -{ - lua_pushnumber(L,log2(A(1))); +static int Llog2(lua_State* L) { + lua_pushnumber(L, log2(A(1))); return 1; } -static int Llogb(lua_State *L) -{ - lua_pushnumber(L,logb(A(1))); +static int Llogb(lua_State* L) { + lua_pushnumber(L, logb(A(1))); return 1; } -static int Lnearbyint(lua_State *L) -{ - lua_pushnumber(L,nearbyint(A(1))); +static int Lnearbyint(lua_State* L) { + lua_pushnumber(L, nearbyint(A(1))); return 1; } -static int Lnextafter(lua_State *L) -{ - lua_pushnumber(L,nextafter(A(1),A(2))); +static int Lnextafter(lua_State* L) { + lua_pushnumber(L, nextafter(A(1), A(2))); return 1; } -static int Lremainder(lua_State *L) -{ - lua_pushnumber(L,remainder(A(1),A(2))); +static int Lremainder(lua_State* L) { + lua_pushnumber(L, remainder(A(1), A(2))); return 1; } -static int Lrint(lua_State *L) -{ - lua_pushnumber(L,rint(A(1))); +static int Lrint(lua_State* L) { + lua_pushnumber(L, rint(A(1))); return 1; } -static int Lround(lua_State *L) -{ - lua_pushnumber(L,round(A(1))); +static int Lround(lua_State* L) { + lua_pushnumber(L, round(A(1))); return 1; } -static int Lscalbn(lua_State *L) -{ - lua_pushnumber(L,scalbn(A(1),(int)A(2))); +static int Lscalbn(lua_State* L) { + lua_pushnumber(L, scalbn(A(1), (int)A(2))); return 1; } -static int Lsignbit(lua_State *L) -{ - lua_pushboolean(L,signbit(A(1))); +static int Lsignbit(lua_State* L) { + lua_pushboolean(L, signbit(A(1))); return 1; } -static int Ltgamma(lua_State *L) -{ - lua_pushnumber(L,tgamma(A(1))); +static int Ltgamma(lua_State* L) { + lua_pushnumber(L, tgamma(A(1))); return 1; } -static int Ltrunc(lua_State *L) -{ - lua_pushnumber(L,trunc(A(1))); +static int Ltrunc(lua_State* L) { + lua_pushnumber(L, trunc(A(1))); return 1; } -static const luaL_Reg R[] = -{ - { "acosh", Lacosh }, - { "asinh", Lasinh }, - { "atanh", Latanh }, - { "cbrt", Lcbrt }, - { "copysign", Lcopysign }, - { "erfc", Lerfc }, - { "erf", Lerf }, - { "exp2", Lexp2 }, - { "expm1", Lexpm1 }, - { "fdim", Lfdim }, - { "fma", Lfma }, - { "fmax", Lfmax }, - { "fmin", Lfmin }, - { "fpclassify", Lfpclassify }, - { "gamma", Ltgamma }, - { "hypot", Lhypot }, - { "isfinite", Lisfinite }, - { "isinf", Lisinf }, - { "isnan", Lisnan }, - { "isnormal", Lisnormal }, - { "lgamma", Llgamma }, - { "log1p", Llog1p }, - { "log2", Llog2 }, - { "logb", Llogb }, - { "nearbyint", Lnearbyint }, - { "nextafter", Lnextafter }, - { "remainder", Lremainder }, - { "rint", Lrint }, - { "round", Lround }, - { "scalbn", Lscalbn }, - { "signbit", Lsignbit }, - { "trunc", Ltrunc }, - { NULL, NULL } -}; - +static const luaL_Reg R[] = {{"acosh", Lacosh}, + {"asinh", Lasinh}, + {"atanh", Latanh}, + {"cbrt", Lcbrt}, + {"copysign", Lcopysign}, + {"erfc", Lerfc}, + {"erf", Lerf}, + {"exp2", Lexp2}, + {"expm1", Lexpm1}, + {"fdim", Lfdim}, + {"fma", Lfma}, + {"fmax", Lfmax}, + {"fmin", Lfmin}, + {"fpclassify", Lfpclassify}, + {"gamma", Ltgamma}, + {"hypot", Lhypot}, + {"isfinite", Lisfinite}, + {"isinf", Lisinf}, + {"isnan", Lisnan}, + {"isnormal", Lisnormal}, + {"lgamma", Llgamma}, + {"log1p", Llog1p}, + {"log2", Llog2}, + {"logb", Llogb}, + {"nearbyint", Lnearbyint}, + {"nextafter", Lnextafter}, + {"remainder", Lremainder}, + {"rint", Lrint}, + {"round", Lround}, + {"scalbn", Lscalbn}, + {"signbit", Lsignbit}, + {"trunc", Ltrunc}, + {NULL, NULL}}; -LUALIB_API int luaopen_mathx(lua_State *L) -{ - lua_getglobal(L,LUA_MATHLIBNAME); - luaL_setfuncs(L,R,0); - lua_pushnumber(L,INFINITY); - lua_setfield(L,-2,"infinity"); - lua_pushnumber(L,NAN); - lua_setfield(L,-2,"nan"); - return 1; +LUALIB_API int luaopen_mathx(lua_State* L) { + lua_getglobal(L, LUA_MATHLIBNAME); + luaL_setfuncs(L, R, 0); + lua_pushnumber(L, INFINITY); + lua_setfield(L, -2, "infinity"); + lua_pushnumber(L, NAN); + lua_setfield(L, -2, "nan"); + return 1; } diff --git a/external/lua53/lmathx.c b/external/lua53/lmathx.c index a727eb6..e4a684c 100644 --- a/external/lua53/lmathx.c +++ b/external/lua53/lmathx.c @@ -1,438 +1,438 @@ /* -* lmathx.c -* C99 math functions for Lua 5.3 -* Luiz Henrique de Figueiredo -* 24 Jun 2015 09:51:50 -* This code is hereby placed in the public domain. -*/ + * lmathx.c + * C99 math functions for Lua 5.3 + * Luiz Henrique de Figueiredo + * 24 Jun 2015 09:51:50 + * This code is hereby placed in the public domain. + */ -#include - -#include "lua.h" #include "lauxlib.h" +#include "lua.h" -#define MYNAME "mathx" -#define MYVERSION MYNAME " library for " LUA_VERSION " / Jun 2015" +#include -#define A(i) luaL_checknumber(L,i) -#define I(i) ((int)luaL_checkinteger(L,i)) +#define MYNAME "mathx" +#define MYVERSION MYNAME " library for " LUA_VERSION " / Jun 2015" + +#define A(i) luaL_checknumber(L, i) +#define I(i) ((int)luaL_checkinteger(L, i)) #undef PI -#define PI (l_mathop(3.141592653589793238462643383279502884)) -#define rad(x) ((x)*(PI/l_mathop(180.0))) -#define deg(x) ((x)*(l_mathop(180.0)/PI)) +#define PI (l_mathop(3.141592653589793238462643383279502884)) +#define rad(x) ((x) * (PI / l_mathop(180.0))) +#define deg(x) ((x) * (l_mathop(180.0) / PI)) -static int Lfmax(lua_State *L) /** fmax */ +static int Lfmax(lua_State* L) /** fmax */ { - int i,n=lua_gettop(L); - lua_Number m=A(1); - for (i=2; i<=n; i++) m=l_mathop(fmax)(m,A(i)); - lua_pushnumber(L,m); - return 1; + int i, n = lua_gettop(L); + lua_Number m = A(1); + for (i = 2; i <= n; i++) + m = l_mathop(fmax)(m, A(i)); + lua_pushnumber(L, m); + return 1; } -static int Lfmin(lua_State *L) /** fmin */ +static int Lfmin(lua_State* L) /** fmin */ { - int i,n=lua_gettop(L); - lua_Number m=A(1); - for (i=2; i<=n; i++) m=l_mathop(fmin)(m,A(i)); - lua_pushnumber(L,m); - return 1; + int i, n = lua_gettop(L); + lua_Number m = A(1); + for (i = 2; i <= n; i++) + m = l_mathop(fmin)(m, A(i)); + lua_pushnumber(L, m); + return 1; } -static int Lfrexp(lua_State *L) /** frexp */ +static int Lfrexp(lua_State* L) /** frexp */ { - int e; - lua_pushnumber(L,l_mathop(frexp)(A(1),&e)); - lua_pushinteger(L,e); - return 2; + int e; + lua_pushnumber(L, l_mathop(frexp)(A(1), &e)); + lua_pushinteger(L, e); + return 2; } -static int Lldexp(lua_State *L) /** ldexp */ +static int Lldexp(lua_State* L) /** ldexp */ { - lua_pushnumber(L,l_mathop(ldexp)(A(1),I(2))); - return 1; + lua_pushnumber(L, l_mathop(ldexp)(A(1), I(2))); + return 1; } -static int Lmodf(lua_State *L) /** modf */ +static int Lmodf(lua_State* L) /** modf */ { - lua_Number ip; - lua_Number fp=l_mathop(modf)(A(1),&ip); - lua_pushnumber(L,ip); - lua_pushnumber(L,fp); - return 2; + lua_Number ip; + lua_Number fp = l_mathop(modf)(A(1), &ip); + lua_pushnumber(L, ip); + lua_pushnumber(L, fp); + return 2; } -static int Lfabs(lua_State *L) /** fabs */ +static int Lfabs(lua_State* L) /** fabs */ { - lua_pushnumber(L,l_mathop(fabs)(A(1))); - return 1; + lua_pushnumber(L, l_mathop(fabs)(A(1))); + return 1; } -static int Lacos(lua_State *L) /** acos */ +static int Lacos(lua_State* L) /** acos */ { - lua_pushnumber(L,l_mathop(acos)(A(1))); - return 1; + lua_pushnumber(L, l_mathop(acos)(A(1))); + return 1; } -static int Lacosh(lua_State *L) /** acosh */ +static int Lacosh(lua_State* L) /** acosh */ { - lua_pushnumber(L,l_mathop(acosh)(A(1))); - return 1; + lua_pushnumber(L, l_mathop(acosh)(A(1))); + return 1; } -static int Lasin(lua_State *L) /** asin */ +static int Lasin(lua_State* L) /** asin */ { - lua_pushnumber(L,l_mathop(asin)(A(1))); - return 1; + lua_pushnumber(L, l_mathop(asin)(A(1))); + return 1; } -static int Lasinh(lua_State *L) /** asinh */ +static int Lasinh(lua_State* L) /** asinh */ { - lua_pushnumber(L,l_mathop(asinh)(A(1))); - return 1; + lua_pushnumber(L, l_mathop(asinh)(A(1))); + return 1; } -static int Latan(lua_State *L) /** atan */ +static int Latan(lua_State* L) /** atan */ { - int n=lua_gettop(L); - if (n==1) - lua_pushnumber(L,l_mathop(atan)(A(1))); - else - lua_pushnumber(L,l_mathop(atan2)(A(1),A(2))); - return 1; + int n = lua_gettop(L); + if (n == 1) + lua_pushnumber(L, l_mathop(atan)(A(1))); + else + lua_pushnumber(L, l_mathop(atan2)(A(1), A(2))); + return 1; } -static int Latan2(lua_State *L) /** atan2 */ +static int Latan2(lua_State* L) /** atan2 */ { - lua_pushnumber(L,l_mathop(atan2)(A(1),A(2))); - return 1; + lua_pushnumber(L, l_mathop(atan2)(A(1), A(2))); + return 1; } -static int Latanh(lua_State *L) /** atanh */ +static int Latanh(lua_State* L) /** atanh */ { - lua_pushnumber(L,l_mathop(atanh)(A(1))); - return 1; + lua_pushnumber(L, l_mathop(atanh)(A(1))); + return 1; } -static int Lcbrt(lua_State *L) /** cbrt */ +static int Lcbrt(lua_State* L) /** cbrt */ { - lua_pushnumber(L,l_mathop(cbrt)(A(1))); - return 1; + lua_pushnumber(L, l_mathop(cbrt)(A(1))); + return 1; } -static int Lceil(lua_State *L) /** ceil */ +static int Lceil(lua_State* L) /** ceil */ { - lua_pushnumber(L,l_mathop(ceil)(A(1))); - return 1; + lua_pushnumber(L, l_mathop(ceil)(A(1))); + return 1; } -static int Lcopysign(lua_State *L) /** copysign */ +static int Lcopysign(lua_State* L) /** copysign */ { - lua_pushnumber(L,l_mathop(copysign)(A(1),A(2))); - return 1; + lua_pushnumber(L, l_mathop(copysign)(A(1), A(2))); + return 1; } -static int Lcos(lua_State *L) /** cos */ +static int Lcos(lua_State* L) /** cos */ { - lua_pushnumber(L,l_mathop(cos)(A(1))); - return 1; + lua_pushnumber(L, l_mathop(cos)(A(1))); + return 1; } -static int Lcosh(lua_State *L) /** cosh */ +static int Lcosh(lua_State* L) /** cosh */ { - lua_pushnumber(L,l_mathop(cosh)(A(1))); - return 1; + lua_pushnumber(L, l_mathop(cosh)(A(1))); + return 1; } -static int Ldeg(lua_State *L) /** deg */ +static int Ldeg(lua_State* L) /** deg */ { - lua_pushnumber(L,deg(A(1))); - return 1; + lua_pushnumber(L, deg(A(1))); + return 1; } -static int Lerf(lua_State *L) /** erf */ +static int Lerf(lua_State* L) /** erf */ { - lua_pushnumber(L,l_mathop(erf)(A(1))); - return 1; + lua_pushnumber(L, l_mathop(erf)(A(1))); + return 1; } -static int Lerfc(lua_State *L) /** erfc */ +static int Lerfc(lua_State* L) /** erfc */ { - lua_pushnumber(L,l_mathop(erfc)(A(1))); - return 1; + lua_pushnumber(L, l_mathop(erfc)(A(1))); + return 1; } -static int Lexp(lua_State *L) /** exp */ +static int Lexp(lua_State* L) /** exp */ { - lua_pushnumber(L,l_mathop(exp)(A(1))); - return 1; + lua_pushnumber(L, l_mathop(exp)(A(1))); + return 1; } -static int Lexp2(lua_State *L) /** exp2 */ +static int Lexp2(lua_State* L) /** exp2 */ { - lua_pushnumber(L,l_mathop(exp2)(A(1))); - return 1; + lua_pushnumber(L, l_mathop(exp2)(A(1))); + return 1; } -static int Lexpm1(lua_State *L) /** expm1 */ +static int Lexpm1(lua_State* L) /** expm1 */ { - lua_pushnumber(L,l_mathop(expm1)(A(1))); - return 1; + lua_pushnumber(L, l_mathop(expm1)(A(1))); + return 1; } -static int Lfdim(lua_State *L) /** fdim */ +static int Lfdim(lua_State* L) /** fdim */ { - lua_pushnumber(L,l_mathop(fdim)(A(1),A(2))); - return 1; + lua_pushnumber(L, l_mathop(fdim)(A(1), A(2))); + return 1; } -static int Lfloor(lua_State *L) /** floor */ +static int Lfloor(lua_State* L) /** floor */ { - lua_pushnumber(L,l_mathop(floor)(A(1))); - return 1; + lua_pushnumber(L, l_mathop(floor)(A(1))); + return 1; } -static int Lfma(lua_State *L) /** fma */ +static int Lfma(lua_State* L) /** fma */ { - lua_pushnumber(L,l_mathop(fma)(A(1),A(2),A(3))); - return 1; + lua_pushnumber(L, l_mathop(fma)(A(1), A(2), A(3))); + return 1; } -static int Lfmod(lua_State *L) /** fmod */ +static int Lfmod(lua_State* L) /** fmod */ { - lua_pushnumber(L,l_mathop(fmod)(A(1),A(2))); - return 1; + lua_pushnumber(L, l_mathop(fmod)(A(1), A(2))); + return 1; } -static int Lgamma(lua_State *L) /** gamma */ +static int Lgamma(lua_State* L) /** gamma */ { - lua_pushnumber(L,l_mathop(tgamma)(A(1))); - return 1; + lua_pushnumber(L, l_mathop(tgamma)(A(1))); + return 1; } -static int Lhypot(lua_State *L) /** hypot */ +static int Lhypot(lua_State* L) /** hypot */ { - lua_pushnumber(L,l_mathop(hypot)(A(1),A(2))); - return 1; + lua_pushnumber(L, l_mathop(hypot)(A(1), A(2))); + return 1; } -static int Lisfinite(lua_State *L) /** isfinite */ +static int Lisfinite(lua_State* L) /** isfinite */ { - lua_pushboolean(L,isfinite(A(1))); - return 1; + lua_pushboolean(L, isfinite(A(1))); + return 1; } -static int Lisinf(lua_State *L) /** isinf */ +static int Lisinf(lua_State* L) /** isinf */ { - lua_pushboolean(L,isinf(A(1))); - return 1; + lua_pushboolean(L, isinf(A(1))); + return 1; } -static int Lisnan(lua_State *L) /** isnan */ +static int Lisnan(lua_State* L) /** isnan */ { - lua_pushboolean(L,isnan(A(1))); - return 1; + lua_pushboolean(L, isnan(A(1))); + return 1; } -static int Lisnormal(lua_State *L) /** isnormal */ +static int Lisnormal(lua_State* L) /** isnormal */ { - lua_pushboolean(L,isnormal(A(1))); - return 1; + lua_pushboolean(L, isnormal(A(1))); + return 1; } -static int Llgamma(lua_State *L) /** lgamma */ +static int Llgamma(lua_State* L) /** lgamma */ { - lua_pushnumber(L,l_mathop(lgamma)(A(1))); - return 1; + lua_pushnumber(L, l_mathop(lgamma)(A(1))); + return 1; } -static int Llog(lua_State *L) /** log */ +static int Llog(lua_State* L) /** log */ { - int n=lua_gettop(L); - if (n==1) - lua_pushnumber(L,l_mathop(log)(A(1))); - else - { - lua_Number b=A(2); - if (b==10.0) - lua_pushnumber(L,l_mathop(log10)(A(1))); - else if (b==2.0) - lua_pushnumber(L,l_mathop(log2)(A(1))); - else - lua_pushnumber(L,l_mathop(log)(A(1))/l_mathop(log)(b)); - } - return 1; + int n = lua_gettop(L); + if (n == 1) + lua_pushnumber(L, l_mathop(log)(A(1))); + else { + lua_Number b = A(2); + if (b == 10.0) + lua_pushnumber(L, l_mathop(log10)(A(1))); + else if (b == 2.0) + lua_pushnumber(L, l_mathop(log2)(A(1))); + else + lua_pushnumber(L, l_mathop(log)(A(1)) / l_mathop(log)(b)); + } + return 1; } -static int Llog10(lua_State *L) /** log10 */ +static int Llog10(lua_State* L) /** log10 */ { - lua_pushnumber(L,l_mathop(log10)(A(1))); - return 1; + lua_pushnumber(L, l_mathop(log10)(A(1))); + return 1; } -static int Llog1p(lua_State *L) /** log1p */ +static int Llog1p(lua_State* L) /** log1p */ { - lua_pushnumber(L,l_mathop(log1p)(A(1))); - return 1; + lua_pushnumber(L, l_mathop(log1p)(A(1))); + return 1; } -static int Llog2(lua_State *L) /** log2 */ +static int Llog2(lua_State* L) /** log2 */ { - lua_pushnumber(L,l_mathop(log2)(A(1))); - return 1; + lua_pushnumber(L, l_mathop(log2)(A(1))); + return 1; } -static int Llogb(lua_State *L) /** logb */ +static int Llogb(lua_State* L) /** logb */ { - lua_pushnumber(L,l_mathop(logb)(A(1))); - return 1; + lua_pushnumber(L, l_mathop(logb)(A(1))); + return 1; } -static int Lnearbyint(lua_State *L) /** nearbyint */ +static int Lnearbyint(lua_State* L) /** nearbyint */ { - lua_pushnumber(L,l_mathop(nearbyint)(A(1))); - return 1; + lua_pushnumber(L, l_mathop(nearbyint)(A(1))); + return 1; } -static int Lnextafter(lua_State *L) /** nextafter */ +static int Lnextafter(lua_State* L) /** nextafter */ { - lua_pushnumber(L,l_mathop(nextafter)(A(1),A(2))); - return 1; + lua_pushnumber(L, l_mathop(nextafter)(A(1), A(2))); + return 1; } -static int Lpow(lua_State *L) /** pow */ +static int Lpow(lua_State* L) /** pow */ { - lua_pushnumber(L,l_mathop(pow)(A(1),A(2))); - return 1; + lua_pushnumber(L, l_mathop(pow)(A(1), A(2))); + return 1; } -static int Lrad(lua_State *L) /** rad */ +static int Lrad(lua_State* L) /** rad */ { - lua_pushnumber(L,rad(A(1))); - return 1; + lua_pushnumber(L, rad(A(1))); + return 1; } -static int Lremainder(lua_State *L) /** remainder */ +static int Lremainder(lua_State* L) /** remainder */ { - lua_pushnumber(L,l_mathop(remainder)(A(1),A(2))); - return 1; + lua_pushnumber(L, l_mathop(remainder)(A(1), A(2))); + return 1; } -static int Lround(lua_State *L) /** round */ +static int Lround(lua_State* L) /** round */ { - lua_pushnumber(L,l_mathop(round)(A(1))); - return 1; + lua_pushnumber(L, l_mathop(round)(A(1))); + return 1; } -static int Lscalbn(lua_State *L) /** scalbn */ +static int Lscalbn(lua_State* L) /** scalbn */ { - lua_pushnumber(L,l_mathop(scalbn)(A(1),A(2))); - return 1; + lua_pushnumber(L, l_mathop(scalbn)(A(1), A(2))); + return 1; } -static int Lsin(lua_State *L) /** sin */ +static int Lsin(lua_State* L) /** sin */ { - lua_pushnumber(L,l_mathop(sin)(A(1))); - return 1; + lua_pushnumber(L, l_mathop(sin)(A(1))); + return 1; } -static int Lsinh(lua_State *L) /** sinh */ +static int Lsinh(lua_State* L) /** sinh */ { - lua_pushnumber(L,l_mathop(sinh)(A(1))); - return 1; + lua_pushnumber(L, l_mathop(sinh)(A(1))); + return 1; } -static int Lsqrt(lua_State *L) /** sqrt */ +static int Lsqrt(lua_State* L) /** sqrt */ { - lua_pushnumber(L,l_mathop(sqrt)(A(1))); - return 1; + lua_pushnumber(L, l_mathop(sqrt)(A(1))); + return 1; } -static int Ltan(lua_State *L) /** tan */ +static int Ltan(lua_State* L) /** tan */ { - lua_pushnumber(L,l_mathop(tan)(A(1))); - return 1; + lua_pushnumber(L, l_mathop(tan)(A(1))); + return 1; } -static int Ltanh(lua_State *L) /** tanh */ +static int Ltanh(lua_State* L) /** tanh */ { - lua_pushnumber(L,l_mathop(tanh)(A(1))); - return 1; + lua_pushnumber(L, l_mathop(tanh)(A(1))); + return 1; } -static int Ltrunc(lua_State *L) /** trunc */ +static int Ltrunc(lua_State* L) /** trunc */ { - lua_pushnumber(L,l_mathop(trunc)(A(1))); - return 1; + lua_pushnumber(L, l_mathop(trunc)(A(1))); + return 1; } -static const luaL_Reg R[] = -{ - { "fabs", Lfabs }, - { "acos", Lacos }, - { "acosh", Lacosh }, - { "asin", Lasin }, - { "asinh", Lasinh }, - { "atan", Latan }, - { "atan2", Latan2 }, - { "atanh", Latanh }, - { "cbrt", Lcbrt }, - { "ceil", Lceil }, - { "copysign", Lcopysign }, - { "cos", Lcos }, - { "cosh", Lcosh }, - { "deg", Ldeg }, - { "erf", Lerf }, - { "erfc", Lerfc }, - { "exp", Lexp }, - { "exp2", Lexp2 }, - { "expm1", Lexpm1 }, - { "fdim", Lfdim }, - { "floor", Lfloor }, - { "fma", Lfma }, - { "fmax", Lfmax }, - { "fmin", Lfmin }, - { "fmod", Lfmod }, - { "frexp", Lfrexp }, - { "gamma", Lgamma }, - { "hypot", Lhypot }, - { "isfinite", Lisfinite }, - { "isinf", Lisinf }, - { "isnan", Lisnan }, - { "isnormal", Lisnormal }, - { "ldexp", Lldexp }, - { "lgamma", Llgamma }, - { "log", Llog }, - { "log10", Llog10 }, - { "log1p", Llog1p }, - { "log2", Llog2 }, - { "logb", Llogb }, - { "modf", Lmodf }, - { "nearbyint", Lnearbyint }, - { "nextafter", Lnextafter }, - { "pow", Lpow }, - { "rad", Lrad }, - { "remainder", Lremainder }, - { "round", Lround }, - { "scalbn", Lscalbn }, - { "sin", Lsin }, - { "sinh", Lsinh }, - { "sqrt", Lsqrt }, - { "tan", Ltan }, - { "tanh", Ltanh }, - { "trunc", Ltrunc }, - { NULL, NULL } -}; - -LUALIB_API int luaopen_mathx(lua_State *L) -{ - luaL_newlib(L,R); - lua_pushliteral(L,"version"); /** version */ - lua_pushliteral(L,MYVERSION); - lua_settable(L,-3); - lua_pushnumber(L,INFINITY); lua_setfield(L,-2,"inf"); - lua_pushnumber(L,NAN); lua_setfield(L,-2,"nan"); - lua_pushnumber(L,PI); lua_setfield(L,-2,"pi"); - return 1; +static const luaL_Reg R[] = {{"fabs", Lfabs}, + {"acos", Lacos}, + {"acosh", Lacosh}, + {"asin", Lasin}, + {"asinh", Lasinh}, + {"atan", Latan}, + {"atan2", Latan2}, + {"atanh", Latanh}, + {"cbrt", Lcbrt}, + {"ceil", Lceil}, + {"copysign", Lcopysign}, + {"cos", Lcos}, + {"cosh", Lcosh}, + {"deg", Ldeg}, + {"erf", Lerf}, + {"erfc", Lerfc}, + {"exp", Lexp}, + {"exp2", Lexp2}, + {"expm1", Lexpm1}, + {"fdim", Lfdim}, + {"floor", Lfloor}, + {"fma", Lfma}, + {"fmax", Lfmax}, + {"fmin", Lfmin}, + {"fmod", Lfmod}, + {"frexp", Lfrexp}, + {"gamma", Lgamma}, + {"hypot", Lhypot}, + {"isfinite", Lisfinite}, + {"isinf", Lisinf}, + {"isnan", Lisnan}, + {"isnormal", Lisnormal}, + {"ldexp", Lldexp}, + {"lgamma", Llgamma}, + {"log", Llog}, + {"log10", Llog10}, + {"log1p", Llog1p}, + {"log2", Llog2}, + {"logb", Llogb}, + {"modf", Lmodf}, + {"nearbyint", Lnearbyint}, + {"nextafter", Lnextafter}, + {"pow", Lpow}, + {"rad", Lrad}, + {"remainder", Lremainder}, + {"round", Lround}, + {"scalbn", Lscalbn}, + {"sin", Lsin}, + {"sinh", Lsinh}, + {"sqrt", Lsqrt}, + {"tan", Ltan}, + {"tanh", Ltanh}, + {"trunc", Ltrunc}, + {NULL, NULL}}; + +LUALIB_API int luaopen_mathx(lua_State* L) { + luaL_newlib(L, R); + lua_pushliteral(L, "version"); /** version */ + lua_pushliteral(L, MYVERSION); + lua_settable(L, -3); + lua_pushnumber(L, INFINITY); + lua_setfield(L, -2, "inf"); + lua_pushnumber(L, NAN); + lua_setfield(L, -2, "nan"); + lua_pushnumber(L, PI); + lua_setfield(L, -2, "pi"); + return 1; } diff --git a/include/easi/Component.h b/include/easi/Component.h index 2a5d31f..696047f 100644 --- a/include/easi/Component.h +++ b/include/easi/Component.h @@ -12,39 +12,39 @@ namespace easi { class Component { -public: - virtual ~Component() {} + public: + virtual ~Component() {} - virtual void evaluate(Query& query, ResultAdapter& result) = 0; - virtual bool accept(int group, Slice const& x) const = 0; - virtual bool acceptAlways() const = 0; + virtual void evaluate(Query& query, ResultAdapter& result) = 0; + virtual bool accept(int group, const Slice& x) const = 0; + virtual bool acceptAlways() const = 0; - inline std::set const& in() const { return m_in; } - inline std::set const& out() const { return m_out; } - inline unsigned dimDomain() const { return m_in.size(); } - inline unsigned dimCodomain() const { return m_out.size(); } + inline const std::set& in() const { return m_in; } + inline const std::set& out() const { return m_out; } + inline unsigned dimDomain() const { return m_in.size(); } + inline unsigned dimCodomain() const { return m_out.size(); } - inline void setFileReference(std::string const& fileReference) { - m_fileReference = fileReference; - } + inline void setFileReference(const std::string& fileReference) { + m_fileReference = fileReference; + } - inline std::string addFileReference(std::string const& what_arg) { - std::stringstream s; - s << m_fileReference << ": " << what_arg; - return s.str(); - } + inline std::string addFileReference(const std::string& what_arg) { + std::stringstream s; + s << m_fileReference << ": " << what_arg; + return s.str(); + } - inline virtual std::set suppliedParameters() { return out(); } + inline virtual std::set suppliedParameters() { return out(); } -protected: - inline void setIn(std::set const& parameters) { m_in = parameters; } - inline void setOut(std::set const& parameters) { m_out = parameters; } + protected: + inline void setIn(const std::set& parameters) { m_in = parameters; } + inline void setOut(const std::set& parameters) { m_out = parameters; } - std::string m_fileReference; + std::string m_fileReference; -private: - std::set m_in; - std::set m_out; + private: + std::set m_in; + std::set m_out; }; } // namespace easi diff --git a/include/easi/Query.h b/include/easi/Query.h index 9074f5e..17ed640 100644 --- a/include/easi/Query.h +++ b/include/easi/Query.h @@ -7,17 +7,17 @@ namespace easi { struct Query { - Vector group; - Matrix x; - Vector index; + Vector group; + Matrix x; + Vector index; - Query(unsigned numPoints, unsigned dimDomain, bool initIndices = true); + Query(unsigned numPoints, unsigned dimDomain, bool initIndices = true); - inline unsigned numPoints() const { return x.rows(); } - inline unsigned dimDomain() const { return x.cols(); } + inline unsigned numPoints() const { return x.rows(); } + inline unsigned dimDomain() const { return x.cols(); } - Query shallowCopy(); - void clear(); + Query shallowCopy(); + void clear(); }; } // namespace easi diff --git a/include/easi/ResultAdapter.h b/include/easi/ResultAdapter.h index 5399500..ea36d30 100644 --- a/include/easi/ResultAdapter.h +++ b/include/easi/ResultAdapter.h @@ -12,141 +12,144 @@ namespace easi { class ResultAdapter { -public: - inline virtual ~ResultAdapter() {} - virtual void set(std::string const& parameter, Vector const& index, - Slice const& value) = 0; - virtual bool isSubset(std::set const& parameters) const = 0; - virtual ResultAdapter* subsetAdapter(std::set const& subset) = 0; - virtual unsigned numberOfParameters() const = 0; - virtual std::set parameters() const = 0; + public: + inline virtual ~ResultAdapter() {} + virtual void set(const std::string& parameter, + const Vector& index, + const Slice& value) = 0; + virtual bool isSubset(const std::set& parameters) const = 0; + virtual ResultAdapter* subsetAdapter(const std::set& subset) = 0; + virtual unsigned numberOfParameters() const = 0; + virtual std::set parameters() const = 0; }; -template class ArrayOfStructsAdapter : public ResultAdapter { -public: - ArrayOfStructsAdapter(T* arrayOfStructs) : m_arrayOfStructs(arrayOfStructs) {} - virtual ~ArrayOfStructsAdapter() {} - - void addBindingPoint(std::string const& parameter, double T::*pointerToMember) { - m_bindingPoint[parameter] = m_parameter.size(); - m_parameter.push_back(pointerToMember); - } - - int bindingPoint(std::string const& parameter) const { - auto it = m_bindingPoint.find(parameter); - return (it != m_bindingPoint.end()) ? it->second : -1; - } - - virtual bool isSubset(std::set const& parameters) const { - for (auto const& kv : m_bindingPoint) { - if (parameters.find(kv.first) == parameters.end()) { - return false; - } - } - return true; +template +class ArrayOfStructsAdapter : public ResultAdapter { + public: + ArrayOfStructsAdapter(T* arrayOfStructs) : m_arrayOfStructs(arrayOfStructs) {} + virtual ~ArrayOfStructsAdapter() {} + + void addBindingPoint(const std::string& parameter, double T::* pointerToMember) { + m_bindingPoint[parameter] = m_parameter.size(); + m_parameter.push_back(pointerToMember); + } + + int bindingPoint(const std::string& parameter) const { + auto it = m_bindingPoint.find(parameter); + return (it != m_bindingPoint.end()) ? it->second : -1; + } + + virtual bool isSubset(const std::set& parameters) const { + for (const auto& kv : m_bindingPoint) { + if (parameters.find(kv.first) == parameters.end()) { + return false; + } } - - virtual void set(std::string const& parameter, Vector const& index, - Slice const& value) { - assert(value.size() == index.size()); - - int bp = bindingPoint(parameter); - if (bp >= 0) { - for (unsigned i = 0; i < index.size(); ++i) { - m_arrayOfStructs[index(i)].*m_parameter[bp] = value(i); - } - } + return true; + } + + virtual void + set(const std::string& parameter, const Vector& index, const Slice& value) { + assert(value.size() == index.size()); + + int bp = bindingPoint(parameter); + if (bp >= 0) { + for (unsigned i = 0; i < index.size(); ++i) { + m_arrayOfStructs[index(i)].*m_parameter[bp] = value(i); + } } - - virtual ResultAdapter* subsetAdapter(std::set const& subset) { - ArrayOfStructsAdapter* result = new ArrayOfStructsAdapter(m_arrayOfStructs); - for (auto it = subset.cbegin(); it != subset.cend(); ++it) { - int bp = bindingPoint(*it); - if (bp >= 0) { - result->addBindingPoint(*it, m_parameter[bp]); - } - } - return result; + } + + virtual ResultAdapter* subsetAdapter(const std::set& subset) { + ArrayOfStructsAdapter* result = new ArrayOfStructsAdapter(m_arrayOfStructs); + for (auto it = subset.cbegin(); it != subset.cend(); ++it) { + int bp = bindingPoint(*it); + if (bp >= 0) { + result->addBindingPoint(*it, m_parameter[bp]); + } } + return result; + } - virtual unsigned numberOfParameters() const { return m_parameter.size(); } + virtual unsigned numberOfParameters() const { return m_parameter.size(); } - virtual std::set parameters() const { - std::set params; - for (auto const& kv : m_bindingPoint) { - params.insert(kv.first); - } - return params; + virtual std::set parameters() const { + std::set params; + for (const auto& kv : m_bindingPoint) { + params.insert(kv.first); } + return params; + } -private: - T* m_arrayOfStructs; - std::unordered_map m_bindingPoint; - std::vector m_parameter; + private: + T* m_arrayOfStructs; + std::unordered_map m_bindingPoint; + std::vector m_parameter; }; -template class ArraysAdapter : public ResultAdapter { -public: - virtual ~ArraysAdapter() {} - - void addBindingPoint(std::string const& parameter, Float* array, unsigned stride = 1) { - m_bindingPoint[parameter] = m_arrays.size(); - m_arrays.push_back(array); - m_strides.push_back(stride); - } - - virtual int bindingPoint(std::string const& parameter) const { - auto it = m_bindingPoint.find(parameter); - return (it != m_bindingPoint.end()) ? it->second : -1; +template +class ArraysAdapter : public ResultAdapter { + public: + virtual ~ArraysAdapter() {} + + void addBindingPoint(const std::string& parameter, Float* array, unsigned stride = 1) { + m_bindingPoint[parameter] = m_arrays.size(); + m_arrays.push_back(array); + m_strides.push_back(stride); + } + + virtual int bindingPoint(const std::string& parameter) const { + auto it = m_bindingPoint.find(parameter); + return (it != m_bindingPoint.end()) ? it->second : -1; + } + + virtual bool isSubset(const std::set& parameters) const { + for (const auto& kv : m_bindingPoint) { + if (parameters.find(kv.first) == parameters.end()) { + return false; + } } - - virtual bool isSubset(std::set const& parameters) const { - for (auto const& kv : m_bindingPoint) { - if (parameters.find(kv.first) == parameters.end()) { - return false; - } - } - return true; + return true; + } + + virtual void + set(const std::string& parameter, const Vector& index, const Slice& value) { + assert(value.size() == index.size()); + + int bp = bindingPoint(parameter); + if (bp >= 0) { + unsigned stride = m_strides[bp]; + for (unsigned i = 0; i < index.size(); ++i) { + m_arrays[bp][index(i) * stride] = static_cast(value(i)); + } } - - virtual void set(std::string const& parameter, Vector const& index, - Slice const& value) { - assert(value.size() == index.size()); - - int bp = bindingPoint(parameter); - if (bp >= 0) { - unsigned stride = m_strides[bp]; - for (unsigned i = 0; i < index.size(); ++i) { - m_arrays[bp][index(i) * stride] = static_cast(value(i)); - } - } - } - - virtual ResultAdapter* subsetAdapter(std::set const& subset) { - ArraysAdapter* result = new ArraysAdapter; - for (auto it = subset.cbegin(); it != subset.cend(); ++it) { - int bp = bindingPoint(*it); - if (bp >= 0) { - result->addBindingPoint(*it, m_arrays[bp], m_strides[bp]); - } - } - return result; + } + + virtual ResultAdapter* subsetAdapter(const std::set& subset) { + ArraysAdapter* result = new ArraysAdapter; + for (auto it = subset.cbegin(); it != subset.cend(); ++it) { + int bp = bindingPoint(*it); + if (bp >= 0) { + result->addBindingPoint(*it, m_arrays[bp], m_strides[bp]); + } } + return result; + } - virtual unsigned numberOfParameters() const { return m_arrays.size(); } + virtual unsigned numberOfParameters() const { return m_arrays.size(); } - virtual std::set parameters() const { - std::set params; - for (auto const& kv : m_bindingPoint) { - params.insert(kv.first); - } - return params; + virtual std::set parameters() const { + std::set params; + for (const auto& kv : m_bindingPoint) { + params.insert(kv.first); } + return params; + } -private: - std::unordered_map m_bindingPoint; - std::vector m_arrays; - std::vector m_strides; + private: + std::unordered_map m_bindingPoint; + std::vector m_arrays; + std::vector m_strides; }; } // namespace easi diff --git a/include/easi/YAMLParser.h b/include/easi/YAMLParser.h index 197fa40..a3783f8 100644 --- a/include/easi/YAMLParser.h +++ b/include/easi/YAMLParser.h @@ -3,14 +3,13 @@ #include "parser/YAMLAbstractParser.h" -#include -#include - #include #include #include #include +#include #include +#include namespace easi { @@ -18,45 +17,47 @@ class AsagiReader; class Component; class YAMLParser : public YAMLAbstractParser { -public: - using CreateFunction = Component*(YAML::Node const&, std::set const&, - YAMLAbstractParser*); - template - using ParseFunction = void(T* component, YAML::Node const&, std::set const&, - YAMLAbstractParser*); + public: + using CreateFunction = Component*(const YAML::Node&, + const std::set&, + YAMLAbstractParser*); + template + using ParseFunction = + void(T* component, const YAML::Node&, const std::set&, YAMLAbstractParser*); - YAMLParser(unsigned dimDomain, AsagiReader* externalAsagiReader = nullptr, - char firstVariable = 'x'); - YAMLParser(const std::set& variables, - AsagiReader* externalAsagiReader = nullptr); - virtual ~YAMLParser(); + YAMLParser(unsigned dimDomain, + AsagiReader* externalAsagiReader = nullptr, + char firstVariable = 'x'); + YAMLParser(const std::set& variables, AsagiReader* externalAsagiReader = nullptr); + virtual ~YAMLParser(); - void registerType(std::string const& tag, std::function create); - template void registerType(std::string const& tag, ParseFunction parse) { - auto create = [p = std::move(parse)](YAML::Node const& node, - std::set const& in, - YAMLAbstractParser* parser) { - T* component = new T; - p(component, node, in, parser); - return component; - }; - registerType(tag, create); - } + void registerType(const std::string& tag, std::function create); + template + void registerType(const std::string& tag, ParseFunction parse) { + auto create = [p = std::move(parse)](const YAML::Node& node, + const std::set& in, + YAMLAbstractParser* parser) { + T* component = new T; + p(component, node, in, parser); + return component; + }; + registerType(tag, create); + } - Component* parse(std::string const& fileName) override; - Component* parse(YAML::Node const& node, std::set const& in) override; - inline AsagiReader* asagiReader() override { return m_asagiReader; } - inline std::string currentFileName() override { return m_currentFileName; } + Component* parse(const std::string& fileName) override; + Component* parse(const YAML::Node& node, const std::set& in) override; + inline AsagiReader* asagiReader() override { return m_asagiReader; } + inline std::string currentFileName() override { return m_currentFileName; } - std::vector getFileNameList(); + std::vector getFileNameList(); -private: - std::set m_in; - std::unordered_map> m_creators; - AsagiReader* m_asagiReader; - bool m_externalAsagiReader; - std::string m_currentFileName; - std::unordered_set m_fileNames; + private: + std::set m_in; + std::unordered_map> m_creators; + AsagiReader* m_asagiReader; + bool m_externalAsagiReader; + std::string m_currentFileName; + std::unordered_set m_fileNames; }; } // namespace easi diff --git a/include/easi/component/ASAGI.h b/include/easi/component/ASAGI.h index a3cc276..2902116 100644 --- a/include/easi/component/ASAGI.h +++ b/include/easi/component/ASAGI.h @@ -5,7 +5,6 @@ #include "easi/util/Slice.h" #include - #include #include #include @@ -13,37 +12,39 @@ namespace easi { class ASAGI : public Grid { -public: - static unsigned const MaxDimensions = 6; - - inline virtual ~ASAGI() { - delete m_grid; - delete[] m_permutation; - } - - virtual bool accept(int, Slice const& x) const; - inline virtual bool acceptAlways() const { return false; } - - void setGrid(std::set const& in, std::vector const& parameters, - asagi::Grid* grid, unsigned numberOfThreads); - - void getNearestNeighbour(Slice const& x, double* buffer); - void getNeighbours(Slice const& x, double* weights, double* buffer); - inline unsigned permutation(unsigned index) const { return m_permutation[index]; } - -protected: - inline virtual unsigned numberOfThreads() const { return m_numberOfThreads; } - -private: - asagi::Grid* m_grid = nullptr; - unsigned* m_permutation = nullptr; - unsigned m_numberOfThreads; - unsigned m_numValues; - - double m_min[MaxDimensions]; - double m_max[MaxDimensions]; - double m_delta[MaxDimensions]; - double m_deltaInv[MaxDimensions]; + public: + static const unsigned MaxDimensions = 6; + + inline virtual ~ASAGI() { + delete m_grid; + delete[] m_permutation; + } + + virtual bool accept(int, const Slice& x) const; + inline virtual bool acceptAlways() const { return false; } + + void setGrid(const std::set& in, + const std::vector& parameters, + asagi::Grid* grid, + unsigned numberOfThreads); + + void getNearestNeighbour(const Slice& x, double* buffer); + void getNeighbours(const Slice& x, double* weights, double* buffer); + inline unsigned permutation(unsigned index) const { return m_permutation[index]; } + + protected: + inline virtual unsigned numberOfThreads() const { return m_numberOfThreads; } + + private: + asagi::Grid* m_grid = nullptr; + unsigned* m_permutation = nullptr; + unsigned m_numberOfThreads; + unsigned m_numValues; + + double m_min[MaxDimensions]; + double m_max[MaxDimensions]; + double m_delta[MaxDimensions]; + double m_deltaInv[MaxDimensions]; }; } // namespace easi diff --git a/include/easi/component/AffineMap.h b/include/easi/component/AffineMap.h index dd35fd6..e66c082 100644 --- a/include/easi/component/AffineMap.h +++ b/include/easi/component/AffineMap.h @@ -12,21 +12,22 @@ namespace easi { class AffineMap : public Map { -public: - typedef std::map> Transformation; - typedef std::map Translation; + public: + typedef std::map> Transformation; + typedef std::map Translation; - inline virtual ~AffineMap() {} + inline virtual ~AffineMap() {} - void setMap(std::set const& in, Transformation const& matrix, - Translation const& translation); + void setMap(const std::set& in, + const Transformation& matrix, + const Translation& translation); -protected: - virtual Matrix map(Matrix& x); + protected: + virtual Matrix map(Matrix& x); -private: - Matrix m_matrix; - Vector m_translation; + private: + Matrix m_matrix; + Vector m_translation; }; } // namespace easi diff --git a/include/easi/component/AndersonianStress.h b/include/easi/component/AndersonianStress.h index 46c5aff..3ffb4d6 100644 --- a/include/easi/component/AndersonianStress.h +++ b/include/easi/component/AndersonianStress.h @@ -9,23 +9,23 @@ namespace easi { struct AndersonianStress { - struct in { - double mu_d, mu_s, SH_max, sig_zz, cohesion, S, s2ratio, S_v; - }; - in i; + struct in { + double mu_d, mu_s, SH_max, sig_zz, cohesion, S, s2ratio, S_v; + }; + in i; - struct out { - double b_xx, b_yy, b_zz, b_xy, b_yz, b_xz; - }; - out o; + struct out { + double b_xx, b_yy, b_zz, b_xy, b_yz, b_xz; + }; + out o; - void evaluate(); + void evaluate(); }; } // namespace easi -SELF_AWARE_STRUCT(easi::AndersonianStress::in, mu_d, mu_s, SH_max, sig_zz, cohesion, S, s2ratio, - S_v) +SELF_AWARE_STRUCT( + easi::AndersonianStress::in, mu_d, mu_s, SH_max, sig_zz, cohesion, S, s2ratio, S_v) SELF_AWARE_STRUCT(easi::AndersonianStress::out, b_xx, b_yy, b_zz, b_xy, b_yz, b_xz) #endif diff --git a/include/easi/component/Any.h b/include/easi/component/Any.h index 56980a2..ba61d47 100644 --- a/include/easi/component/Any.h +++ b/include/easi/component/Any.h @@ -6,11 +6,11 @@ namespace easi { class Any : public Filter { -public: - inline virtual ~Any() {} + public: + inline virtual ~Any() {} - using Filter::setInOut; // Make setInOut public - inline virtual bool accept(int, Slice const&) const { return true; } + using Filter::setInOut; // Make setInOut public + inline virtual bool accept(int, const Slice&) const { return true; } }; } // namespace easi diff --git a/include/easi/component/Composite.h b/include/easi/component/Composite.h index bb02b7d..246cd0b 100644 --- a/include/easi/component/Composite.h +++ b/include/easi/component/Composite.h @@ -12,38 +12,40 @@ namespace easi { class ResultAdapter; struct Query; -template class Slice; +template +class Slice; class Composite : public Component { -public: - using iterator = typename std::vector::iterator; - using const_iterator = typename std::vector::const_iterator; + public: + using iterator = typename std::vector::iterator; + using const_iterator = typename std::vector::const_iterator; - virtual ~Composite(); + virtual ~Composite(); - virtual void add(Component* component); + virtual void add(Component* component); - inline virtual iterator begin() { return m_components.begin(); } - inline virtual const_iterator cbegin() const { return m_components.cbegin(); } + inline virtual iterator begin() { return m_components.begin(); } + inline virtual const_iterator cbegin() const { return m_components.cbegin(); } - inline virtual iterator end() { return m_components.end(); } - inline virtual const_iterator cend() const { return m_components.cend(); } + inline virtual iterator end() { return m_components.end(); } + inline virtual const_iterator cend() const { return m_components.cend(); } - virtual void evaluate(Query& query, ResultAdapter& result); + virtual void evaluate(Query& query, ResultAdapter& result); - std::string addMissingParameters(std::string const& what_arg, std::set expected, - std::set supplied); + std::string addMissingParameters(const std::string& what_arg, + std::set expected, + std::set supplied); - virtual std::set suppliedParameters(); + virtual std::set suppliedParameters(); - std::size_t componentCount() { return m_components.size(); } + std::size_t componentCount() { return m_components.size(); } -protected: - virtual Matrix map(Matrix& x) = 0; + protected: + virtual Matrix map(Matrix& x) = 0; -private: - void couldNotFindModelError(int group, Slice const& y); - std::vector m_components; + private: + void couldNotFindModelError(int group, const Slice& y); + std::vector m_components; }; } // namespace easi diff --git a/include/easi/component/ConstantMap.h b/include/easi/component/ConstantMap.h index 1dbc502..596cc36 100644 --- a/include/easi/component/ConstantMap.h +++ b/include/easi/component/ConstantMap.h @@ -11,18 +11,18 @@ namespace easi { class ConstantMap : public Map { -public: - typedef std::map OutMap; + public: + typedef std::map OutMap; - virtual ~ConstantMap() {} + virtual ~ConstantMap() {} - virtual Matrix map(Matrix& x); + virtual Matrix map(Matrix& x); - using Component::setIn; // Make setIn public - void setMap(OutMap const& outMap); + using Component::setIn; // Make setIn public + void setMap(const OutMap& outMap); -private: - std::vector m_values; + private: + std::vector m_values; }; } // namespace easi diff --git a/include/easi/component/DomainFilter.h b/include/easi/component/DomainFilter.h index 607542a..90640aa 100644 --- a/include/easi/component/DomainFilter.h +++ b/include/easi/component/DomainFilter.h @@ -11,29 +11,30 @@ namespace easi { -template class Slice; +template +class Slice; class AxisAlignedCuboidalDomainFilter : public Filter { -public: - using Limits = std::map>; + public: + using Limits = std::map>; - virtual bool accept(int, Slice const& x) const; - void setDomain(Limits const& limits); + virtual bool accept(int, const Slice& x) const; + void setDomain(const Limits& limits); -private: - std::vector> m_limits; + private: + std::vector> m_limits; }; class SphericalDomainFilter : public Filter { -public: - using Centre = std::map; + public: + using Centre = std::map; - virtual bool accept(int, Slice const& x) const; - void setDomain(double radius, Centre const& centre); + virtual bool accept(int, const Slice& x) const; + void setDomain(double radius, const Centre& centre); -private: - double m_radius2; - Vector m_centre; + private: + double m_radius2; + Vector m_centre; }; } // namespace easi diff --git a/include/easi/component/EvalModel.h b/include/easi/component/EvalModel.h index b0d539b..e046698 100644 --- a/include/easi/component/EvalModel.h +++ b/include/easi/component/EvalModel.h @@ -14,22 +14,23 @@ class ResultAdapter; struct Query; class EvalModel : public Map { -public: - inline virtual ~EvalModel() { delete m_model; } - - virtual void evaluate(Query& query, ResultAdapter& result); - void setModel(std::set const& in, std::set const& out, - Component* model) { - setIn(in); - setOut(out); - m_model = model; - } - -protected: - inline virtual Matrix map(Matrix& x) { return x; } - -private: - Component* m_model; + public: + inline virtual ~EvalModel() { delete m_model; } + + virtual void evaluate(Query& query, ResultAdapter& result); + void setModel(const std::set& in, + const std::set& out, + Component* model) { + setIn(in); + setOut(out); + m_model = model; + } + + protected: + inline virtual Matrix map(Matrix& x) { return x; } + + private: + Component* m_model; }; } // namespace easi diff --git a/include/easi/component/Filter.h b/include/easi/component/Filter.h index 539fb29..2b6779f 100644 --- a/include/easi/component/Filter.h +++ b/include/easi/component/Filter.h @@ -6,18 +6,18 @@ namespace easi { class Filter : public Composite { -public: - inline virtual ~Filter() {} + public: + inline virtual ~Filter() {} - inline virtual bool acceptAlways() const { return false; } + inline virtual bool acceptAlways() const { return false; } -protected: - inline void setInOut(std::set const& inout) { - setIn(inout); - setOut(inout); - } + protected: + inline void setInOut(const std::set& inout) { + setIn(inout); + setOut(inout); + } - inline virtual Matrix map(Matrix& x) { return x; } + inline virtual Matrix map(Matrix& x) { return x; } }; } // namespace easi diff --git a/include/easi/component/Grid.h b/include/easi/component/Grid.h index 78e382c..3a8da7a 100644 --- a/include/easi/component/Grid.h +++ b/include/easi/component/Grid.h @@ -11,91 +11,93 @@ namespace easi { -template class Grid : public Map { -public: - enum InterpolationType { Nearest, Linear }; +template +class Grid : public Map { + public: + enum InterpolationType { Nearest, Linear }; - virtual ~Grid() {} + virtual ~Grid() {} - virtual Matrix map(Matrix& x); + virtual Matrix map(Matrix& x); - void setInterpolationType(std::string const& interpolationType); - void setInterpolationType(enum InterpolationType interpolationType) { - m_interpolationType = interpolationType; - } + void setInterpolationType(const std::string& interpolationType); + void setInterpolationType(enum InterpolationType interpolationType) { + m_interpolationType = interpolationType; + } - void getNearestNeighbour(Slice const& x, double* buffer) { - static_cast(this)->getNearestNeighbour(x, buffer); - } + void getNearestNeighbour(const Slice& x, double* buffer) { + static_cast(this)->getNearestNeighbour(x, buffer); + } - void getNeighbours(Slice const& x, double* weights, double* buffer) { - static_cast(this)->getNeighbours(x, weights, buffer); - } - unsigned permutation(unsigned index) const { - return static_cast(this)->permutation(index); - } + void getNeighbours(const Slice& x, double* weights, double* buffer) { + static_cast(this)->getNeighbours(x, weights, buffer); + } + unsigned permutation(unsigned index) const { + return static_cast(this)->permutation(index); + } -protected: - virtual unsigned numberOfThreads() const = 0; + protected: + virtual unsigned numberOfThreads() const = 0; -private: - enum InterpolationType m_interpolationType = Linear; + private: + enum InterpolationType m_interpolationType = Linear; }; -template Matrix Grid::map(Matrix& x) { - Matrix y(x.rows(), dimCodomain()); +template +Matrix Grid::map(Matrix& x) { + Matrix y(x.rows(), dimCodomain()); #ifdef _OPENMP #pragma omp parallel num_threads(numberOfThreads()) shared(x, y) #endif - { - double* neighbours = new double[(1 << dimDomain()) * dimCodomain()]; - double* weights = new double[dimDomain()]; + { + double* neighbours = new double[(1 << dimDomain()) * dimCodomain()]; + double* weights = new double[dimDomain()]; #ifdef _OPENMP #pragma omp for #endif - for (unsigned i = 0; i < x.rows(); ++i) { - if (m_interpolationType == Linear) { - getNeighbours(x.rowSlice(i), weights, neighbours); - - // linear interpolation - for (int d = static_cast(dimDomain()) - 1; d >= 0; --d) { - for (int p = 0; p < (1 << d); ++p) { - for (int v = 0; v < static_cast(dimCodomain()); ++v) { - neighbours[p * dimCodomain() + v] = - neighbours[p * dimCodomain() + v] * (1.0 - weights[d]) + - neighbours[((1 << d) + p) * dimCodomain() + v] * weights[d]; - } - } - } - } else { - getNearestNeighbour(x.rowSlice(i), neighbours); - } + for (unsigned i = 0; i < x.rows(); ++i) { + if (m_interpolationType == Linear) { + getNeighbours(x.rowSlice(i), weights, neighbours); + // linear interpolation + for (int d = static_cast(dimDomain()) - 1; d >= 0; --d) { + for (int p = 0; p < (1 << d); ++p) { for (int v = 0; v < static_cast(dimCodomain()); ++v) { - y(i, permutation(v)) = neighbours[v]; + neighbours[p * dimCodomain() + v] = + neighbours[p * dimCodomain() + v] * (1.0 - weights[d]) + + neighbours[((1 << d) + p) * dimCodomain() + v] * weights[d]; } + } } + } else { + getNearestNeighbour(x.rowSlice(i), neighbours); + } - delete[] weights; - delete[] neighbours; + for (int v = 0; v < static_cast(dimCodomain()); ++v) { + y(i, permutation(v)) = neighbours[v]; + } } - return y; + delete[] weights; + delete[] neighbours; + } + + return y; } template -void Grid::setInterpolationType(std::string const& interpolationType) { - std::string iType = interpolationType; - std::transform(iType.begin(), iType.end(), iType.begin(), ::tolower); - if (iType == "nearest") { - setInterpolationType(Nearest); - } else if (iType == "linear") { - setInterpolationType(Linear); - } else { - std::stringstream ss; - ss << "Invalid interpolation type " << interpolationType << "."; - throw std::invalid_argument(ss.str()); - } +void Grid::setInterpolationType(const std::string& interpolationType) { + std::string iType = interpolationType; + std::transform(iType.begin(), iType.end(), iType.begin(), ::tolower); + if (iType == "nearest") { + setInterpolationType(Nearest); + } else if (iType == "linear") { + setInterpolationType(Linear); + } else { + std::stringstream ss; + ss << "Invalid interpolation type " << interpolationType << "."; + throw std::invalid_argument(ss.str()); + } } } // namespace easi diff --git a/include/easi/component/GroupFilter.h b/include/easi/component/GroupFilter.h index d143b7a..7747af4 100644 --- a/include/easi/component/GroupFilter.h +++ b/include/easi/component/GroupFilter.h @@ -9,18 +9,18 @@ namespace easi { class GroupFilter : public Filter { -public: - inline virtual ~GroupFilter() {} + public: + inline virtual ~GroupFilter() {} - virtual bool accept(int group, Slice const&) const { - return m_groups.find(group) != m_groups.end(); - } + virtual bool accept(int group, const Slice&) const { + return m_groups.find(group) != m_groups.end(); + } - using Filter::setInOut; // Make setInOut public - inline void setGroups(std::set const& groups) { m_groups = groups; } + using Filter::setInOut; // Make setInOut public + inline void setGroups(const std::set& groups) { m_groups = groups; } -private: - std::set m_groups; + private: + std::set m_groups; }; } // namespace easi diff --git a/include/easi/component/LayeredModelBuilder.h b/include/easi/component/LayeredModelBuilder.h index 45cadff..9bbba43 100644 --- a/include/easi/component/LayeredModelBuilder.h +++ b/include/easi/component/LayeredModelBuilder.h @@ -13,30 +13,30 @@ class Component; class Map; class LayeredModelBuilder { -public: - enum InterpolationType { Lower, Upper, Linear }; - using Nodes = std::map>; - using Parameters = std::vector; - - inline void setMap(Map* map) { m_map = map; } - void setInterpolationType(std::string const& interpolationType); - inline void setInterpolationType(enum InterpolationType interpolationType) { - m_interpolationType = interpolationType; - } - void setNodes(Nodes const& nodes); - inline void setParameters(Parameters const& parameters) { m_parameters = parameters; } - - Component* getResult(); - -private: - Component* createModel(const std::optional& lower, - const std::optional& upper, - std::set const& in); - - Map* m_map = nullptr; - enum InterpolationType m_interpolationType; - Nodes m_nodes; - Parameters m_parameters; + public: + enum InterpolationType { Lower, Upper, Linear }; + using Nodes = std::map>; + using Parameters = std::vector; + + inline void setMap(Map* map) { m_map = map; } + void setInterpolationType(const std::string& interpolationType); + inline void setInterpolationType(enum InterpolationType interpolationType) { + m_interpolationType = interpolationType; + } + void setNodes(const Nodes& nodes); + inline void setParameters(const Parameters& parameters) { m_parameters = parameters; } + + Component* getResult(); + + private: + Component* createModel(const std::optional& lower, + const std::optional& upper, + const std::set& in); + + Map* m_map = nullptr; + enum InterpolationType m_interpolationType; + Nodes m_nodes; + Parameters m_parameters; }; } // namespace easi diff --git a/include/easi/component/LuaMap.h b/include/easi/component/LuaMap.h index 3192322..4fee6e9 100644 --- a/include/easi/component/LuaMap.h +++ b/include/easi/component/LuaMap.h @@ -2,16 +2,14 @@ #define EASI_LUAMAP_H #ifdef EASI_USE_LUA +#include "easi/component/Map.h" +#include "easi/util/Matrix.h" + #include #include #include #include - - -#include "easi/component/Map.h" -#include "easi/util/Matrix.h" - // Forward declaration to avoid including all Lua headers struct lua_State; @@ -19,21 +17,22 @@ namespace easi { double getField(lua_State* L, const std::string& key); class LuaMap : public Map { -public: - void setMap(const std::set& in, - const std::set& returns, - const std::string& function); - - ~LuaMap() override; -protected: - Matrix map(Matrix& x) override; - -private: - void executeLuaFunction(const Matrix& x, Matrix& y); - std::string function; - std::vector idxToInputName; - std::vector idxToOutputName; - std::vector luaStates; + public: + void setMap(const std::set& in, + const std::set& returns, + const std::string& function); + + ~LuaMap() override; + + protected: + Matrix map(Matrix& x) override; + + private: + void executeLuaFunction(const Matrix& x, Matrix& y); + std::string function; + std::vector idxToInputName; + std::vector idxToOutputName; + std::vector luaStates; }; } // namespace easi diff --git a/include/easi/component/Map.h b/include/easi/component/Map.h index 81a7c9e..94d7191 100644 --- a/include/easi/component/Map.h +++ b/include/easi/component/Map.h @@ -6,11 +6,11 @@ namespace easi { class Map : public Composite { -public: - virtual ~Map() {} + public: + virtual ~Map() {} - inline virtual bool accept(int, Slice const&) const { return true; } - inline virtual bool acceptAlways() const { return true; } + inline virtual bool accept(int, const Slice&) const { return true; } + inline virtual bool acceptAlways() const { return true; } }; } // namespace easi diff --git a/include/easi/component/OptimalStress.h b/include/easi/component/OptimalStress.h index 1c2a17d..4613d55 100644 --- a/include/easi/component/OptimalStress.h +++ b/include/easi/component/OptimalStress.h @@ -9,23 +9,31 @@ namespace easi { struct OptimalStress { - struct in { - double mu_d, mu_s, strike, dip, rake, effectiveConfiningStress, cohesion, R, s2ratio; - }; - in i; + struct in { + double mu_d, mu_s, strike, dip, rake, effectiveConfiningStress, cohesion, R, s2ratio; + }; + in i; - struct out { - double b_xx, b_yy, b_zz, b_xy, b_yz, b_xz; - }; - out o; + struct out { + double b_xx, b_yy, b_zz, b_xy, b_yz, b_xz; + }; + out o; - void evaluate(); + void evaluate(); }; } // namespace easi -SELF_AWARE_STRUCT(easi::OptimalStress::in, mu_d, mu_s, strike, dip, rake, effectiveConfiningStress, - cohesion, R, s2ratio) +SELF_AWARE_STRUCT(easi::OptimalStress::in, + mu_d, + mu_s, + strike, + dip, + rake, + effectiveConfiningStress, + cohesion, + R, + s2ratio) SELF_AWARE_STRUCT(easi::OptimalStress::out, b_xx, b_yy, b_zz, b_xy, b_yz, b_xz) #endif diff --git a/include/easi/component/PolynomialMap.h b/include/easi/component/PolynomialMap.h index 2c5da9e..bbd13d2 100644 --- a/include/easi/component/PolynomialMap.h +++ b/include/easi/component/PolynomialMap.h @@ -12,18 +12,18 @@ namespace easi { class PolynomialMap : public Map { -public: - using OutMap = std::map>; + public: + using OutMap = std::map>; - inline virtual ~PolynomialMap() {} + inline virtual ~PolynomialMap() {} - void setMap(std::set const& in, OutMap const& outMap); + void setMap(const std::set& in, const OutMap& outMap); -protected: - virtual Matrix map(Matrix& x); + protected: + virtual Matrix map(Matrix& x); -private: - Matrix m_coeffs; + private: + Matrix m_coeffs; }; } // namespace easi diff --git a/include/easi/component/SCECFile.h b/include/easi/component/SCECFile.h index a4d4f19..83b94e9 100644 --- a/include/easi/component/SCECFile.h +++ b/include/easi/component/SCECFile.h @@ -10,30 +10,31 @@ namespace easi { -template class Slice; +template +class Slice; class SCECFile : public Grid { -public: - SCECFile(); - inline virtual ~SCECFile() { delete m_grid; } + public: + SCECFile(); + inline virtual ~SCECFile() { delete m_grid; } - void setMap(std::set const& in, std::string const& fileName); + void setMap(const std::set& in, const std::string& fileName); - inline void getNearestNeighbour(Slice const& x, double* buffer) { - m_grid->getNearestNeighbour(x, buffer); - } - inline void getNeighbours(Slice const& x, double* weights, double* buffer) { - m_grid->getNeighbours(x, weights, buffer); - } - inline unsigned permutation(unsigned index) const { return index; } + inline void getNearestNeighbour(const Slice& x, double* buffer) { + m_grid->getNearestNeighbour(x, buffer); + } + inline void getNeighbours(const Slice& x, double* weights, double* buffer) { + m_grid->getNeighbours(x, weights, buffer); + } + inline unsigned permutation(unsigned index) const { return index; } -protected: - inline virtual unsigned numberOfThreads() const { return 1; } + protected: + inline virtual unsigned numberOfThreads() const { return 1; } -private: - void readSCECFile(std::string const& fileName); + private: + void readSCECFile(const std::string& fileName); - RegularGrid* m_grid = nullptr; + RegularGrid* m_grid = nullptr; }; } // namespace easi diff --git a/include/easi/component/Special.h b/include/easi/component/Special.h index a41176e..f965050 100644 --- a/include/easi/component/Special.h +++ b/include/easi/component/Special.h @@ -8,22 +8,30 @@ namespace easi { struct STRESS_STR_DIP_SLIP_AM { - struct in { - double mu_d, mu_s, strike, dip, s_zz, cohesion, R, DipSlipFaulting, s2ratio; - }; - in i; + struct in { + double mu_d, mu_s, strike, dip, s_zz, cohesion, R, DipSlipFaulting, s2ratio; + }; + in i; - struct out { - double b_xx, b_yy, b_zz, b_xy, b_yz, b_xz; - }; - out o; + struct out { + double b_xx, b_yy, b_zz, b_xy, b_yz, b_xz; + }; + out o; - void evaluate(); + void evaluate(); }; } // namespace easi -SELF_AWARE_STRUCT(easi::STRESS_STR_DIP_SLIP_AM::in, mu_d, mu_s, strike, dip, s_zz, cohesion, R, - DipSlipFaulting, s2ratio) +SELF_AWARE_STRUCT(easi::STRESS_STR_DIP_SLIP_AM::in, + mu_d, + mu_s, + strike, + dip, + s_zz, + cohesion, + R, + DipSlipFaulting, + s2ratio) SELF_AWARE_STRUCT(easi::STRESS_STR_DIP_SLIP_AM::out, b_xx, b_yy, b_zz, b_xy, b_yz, b_xz) #endif diff --git a/include/easi/component/SpecialMap.h b/include/easi/component/SpecialMap.h index 43fc251..d5b0f01 100644 --- a/include/easi/component/SpecialMap.h +++ b/include/easi/component/SpecialMap.h @@ -11,78 +11,80 @@ #include namespace easi { -template class SpecialMap : public Map { -public: - virtual ~SpecialMap() {} +template +class SpecialMap : public Map { + public: + virtual ~SpecialMap() {} - void setMap(std::map const& constants); + void setMap(const std::map& constants); -protected: - virtual Matrix map(Matrix& x); + protected: + virtual Matrix map(Matrix& x); -private: - int m_inBPs[get_number_of_members()]; - int m_outBPs[get_number_of_members()]; + private: + int m_inBPs[get_number_of_members()]; + int m_outBPs[get_number_of_members()]; - Special m_prototype; + Special m_prototype; }; -template Matrix SpecialMap::map(Matrix& x) { - assert(x.cols() == dimDomain()); - - Special special = m_prototype; - double* input[get_number_of_members()]; - double* output[get_number_of_members()]; - for (unsigned j = 0; j < dimDomain(); ++j) { - input[j] = &(special.i.*get_pointer_to_member(m_inBPs[j])); - } - for (unsigned j = 0; j < dimCodomain(); ++j) { - output[j] = &(special.o.*get_pointer_to_member(m_outBPs[j])); +template +Matrix SpecialMap::map(Matrix& x) { + assert(x.cols() == dimDomain()); + + Special special = m_prototype; + double* input[get_number_of_members()]; + double* output[get_number_of_members()]; + for (unsigned j = 0; j < dimDomain(); ++j) { + input[j] = &(special.i.*get_pointer_to_member(m_inBPs[j])); + } + for (unsigned j = 0; j < dimCodomain(); ++j) { + output[j] = &(special.o.*get_pointer_to_member(m_outBPs[j])); + } + + Matrix y(x.rows(), dimCodomain()); + for (unsigned i = 0; i < y.rows(); ++i) { + for (unsigned j = 0; j < x.cols(); ++j) { + *(input[j]) = x(i, j); } - - Matrix y(x.rows(), dimCodomain()); - for (unsigned i = 0; i < y.rows(); ++i) { - for (unsigned j = 0; j < x.cols(); ++j) { - *(input[j]) = x(i, j); - } - special.evaluate(); - for (unsigned j = 0; j < y.cols(); ++j) { - y(i, j) = *(output[j]); - } + special.evaluate(); + for (unsigned j = 0; j < y.cols(); ++j) { + y(i, j) = *(output[j]); } - return y; - return Matrix(); + } + return y; + return Matrix(); } template -void SpecialMap::setMap(std::map const& constants) { - setOut(memberNamesToSet()); - - std::set in = memberNamesToSet(); - for (auto const& kv : constants) { - int bp = get_binding_point(kv.first); - if (bp < 0) { - std::stringstream ss; - ss << "Unknown constant " << kv.first << "."; - throw std::invalid_argument(addFileReference(ss.str())); - } - m_prototype.i.*get_pointer_to_member(bp) = kv.second; - in.erase(kv.first); - } - - setIn(in); - - unsigned d = 0; - for (auto const& i : in) { - int bp = get_binding_point(i); - m_inBPs[d++] = bp; - } - - d = 0; - for (auto const& o : out()) { - int bp = get_binding_point(o); - m_outBPs[d++] = bp; +void SpecialMap::setMap(const std::map& constants) { + setOut(memberNamesToSet()); + + std::set in = memberNamesToSet(); + for (const auto& kv : constants) { + int bp = get_binding_point(kv.first); + if (bp < 0) { + std::stringstream ss; + ss << "Unknown constant " << kv.first << "."; + throw std::invalid_argument(addFileReference(ss.str())); } + m_prototype.i.*get_pointer_to_member(bp) = kv.second; + in.erase(kv.first); + } + + setIn(in); + + unsigned d = 0; + for (const auto& i : in) { + int bp = get_binding_point(i); + m_inBPs[d++] = bp; + } + + d = 0; + for (const auto& o : out()) { + int bp = get_binding_point(o); + m_outBPs[d++] = bp; + } } } // namespace easi diff --git a/include/easi/component/Switch.h b/include/easi/component/Switch.h index d8f9fd8..e71a9fd 100644 --- a/include/easi/component/Switch.h +++ b/include/easi/component/Switch.h @@ -13,26 +13,27 @@ namespace easi { class Component; class ResultAdapter; struct Query; -template class Slice; +template +class Slice; class Switch : public Filter { -public: - inline virtual ~Switch() {} + public: + inline virtual ~Switch() {} - virtual void evaluate(Query& query, ResultAdapter& result); - inline virtual bool accept(int group, Slice const&) const { return true; } - inline virtual bool acceptAlways() const { return true; } + virtual void evaluate(Query& query, ResultAdapter& result); + inline virtual bool accept(int group, const Slice&) const { return true; } + inline virtual bool acceptAlways() const { return true; } - virtual void add(Component* component, std::set const& restrictions); + virtual void add(Component* component, const std::set& restrictions); - using Filter::setInOut; + using Filter::setInOut; -protected: - using Composite::add; // Make add protected + protected: + using Composite::add; // Make add protected -private: - std::vector> m_restrictions; - std::set m_parameters; + private: + std::vector> m_restrictions; + std::set m_parameters; }; } // namespace easi diff --git a/include/easi/parser/YAMLAbstractParser.h b/include/easi/parser/YAMLAbstractParser.h index 4f86f8a..718ece5 100644 --- a/include/easi/parser/YAMLAbstractParser.h +++ b/include/easi/parser/YAMLAbstractParser.h @@ -3,20 +3,19 @@ #include "easi/Component.h" -#include - #include #include +#include namespace easi { class AsagiReader; class YAMLAbstractParser { -public: - virtual ~YAMLAbstractParser() {} - virtual Component* parse(std::string const& fileName) = 0; - virtual Component* parse(YAML::Node const& node, std::set const& in) = 0; - virtual AsagiReader* asagiReader() = 0; - virtual std::string currentFileName() = 0; + public: + virtual ~YAMLAbstractParser() {} + virtual Component* parse(const std::string& fileName) = 0; + virtual Component* parse(const YAML::Node& node, const std::set& in) = 0; + virtual AsagiReader* asagiReader() = 0; + virtual std::string currentFileName() = 0; }; } // namespace easi diff --git a/include/easi/parser/YAMLComponentParsers.h b/include/easi/parser/YAMLComponentParsers.h index de97fc5..096fee2 100644 --- a/include/easi/parser/YAMLComponentParsers.h +++ b/include/easi/parser/YAMLComponentParsers.h @@ -7,9 +7,9 @@ #include "easi/component/ConstantMap.h" #include "easi/component/DomainFilter.h" #include "easi/component/EvalModel.h" -#include "easi/component/LuaMap.h" #include "easi/component/GroupFilter.h" #include "easi/component/LayeredModelBuilder.h" +#include "easi/component/LuaMap.h" #include "easi/component/OptimalStress.h" #include "easi/component/PolynomialMap.h" #include "easi/component/SCECFile.h" @@ -22,76 +22,111 @@ #include "easi/component/ASAGI.h" #endif -#include - #include #include #include +#include namespace easi { -void parse_Component(Component* component, YAML::Node const& node, std::set const&, +void parse_Component(Component* component, + const YAML::Node& node, + const std::set&, YAMLAbstractParser* parser); -void parse_Composite(Composite* component, YAML::Node const& node, std::set const& in, +void parse_Composite(Composite* component, + const YAML::Node& node, + const std::set& in, YAMLAbstractParser* parser); -void parse_Switch(Switch* component, YAML::Node const& node, std::set const& in, +void parse_Switch(Switch* component, + const YAML::Node& node, + const std::set& in, YAMLAbstractParser* parser); -void parse_Filter(Filter* component, YAML::Node const& node, std::set const& in, +void parse_Filter(Filter* component, + const YAML::Node& node, + const std::set& in, YAMLAbstractParser* parser); -void parse_Any(Any* component, YAML::Node const& node, std::set const& in, +void parse_Any(Any* component, + const YAML::Node& node, + const std::set& in, YAMLAbstractParser* parser); -void parse_GroupFilter(GroupFilter* component, YAML::Node const& node, - std::set const& in, YAMLAbstractParser* parser); +void parse_GroupFilter(GroupFilter* component, + const YAML::Node& node, + const std::set& in, + YAMLAbstractParser* parser); void parse_AxisAlignedCuboidalDomainFilter(AxisAlignedCuboidalDomainFilter* component, - YAML::Node const& node, std::set const& in, + const YAML::Node& node, + const std::set& in, YAMLAbstractParser* parser); -void parse_SphericalDomainFilter(SphericalDomainFilter* component, YAML::Node const& node, - std::set const& in, YAMLAbstractParser* parser); -void parse_Map(Map* component, YAML::Node const& node, std::set const& in, +void parse_SphericalDomainFilter(SphericalDomainFilter* component, + const YAML::Node& node, + const std::set& in, + YAMLAbstractParser* parser); +void parse_Map(Map* component, + const YAML::Node& node, + const std::set& in, YAMLAbstractParser* parser); -void parse_ConstantMap(ConstantMap* component, YAML::Node const& node, - std::set const& in, YAMLAbstractParser* parser); -void parse_AffineMap(AffineMap* component, YAML::Node const& node, std::set const& in, +void parse_ConstantMap(ConstantMap* component, + const YAML::Node& node, + const std::set& in, + YAMLAbstractParser* parser); +void parse_AffineMap(AffineMap* component, + const YAML::Node& node, + const std::set& in, YAMLAbstractParser* parser); #ifdef EASI_USE_LUA -void parse_LuaMap(LuaMap* component, YAML::Node const& node, - std::set const& in, YAMLAbstractParser* parser); -void parse_FunctionMapToLua(LuaMap* component, YAML::Node const& node, - std::set const& in, YAMLAbstractParser* parser); +void parse_LuaMap(LuaMap* component, + YAML::Node const& node, + std::set const& in, + YAMLAbstractParser* parser); +void parse_FunctionMapToLua(LuaMap* component, + const YAML::Node& node, + const std::set& in, + YAMLAbstractParser* parser); #endif -void parse_PolynomialMap(PolynomialMap* component, YAML::Node const& node, - std::set const& in, YAMLAbstractParser* parser); -void parse_SCECFile(SCECFile* component, YAML::Node const& node, std::set const& in, +void parse_PolynomialMap(PolynomialMap* component, + YAML::Node const& node, + std::set const& in, + YAMLAbstractParser* parser); +void parse_SCECFile(SCECFile* component, + const YAML::Node& node, + const std::set& in, YAMLAbstractParser* parser); #ifdef EASI_USE_ASAGI -void parse_ASAGI(ASAGI* component, YAML::Node const& node, std::set const& in, +void parse_ASAGI(ASAGI* component, + YAML::Node const& node, + std::set const& in, YAMLAbstractParser* parser); #endif -void parse_EvalModel(EvalModel* component, YAML::Node const& node, std::set const& in, +void parse_EvalModel(EvalModel* component, + YAML::Node const& node, + std::set const& in, YAMLAbstractParser* parser); -Component* create_LayeredModel(YAML::Node const& node, std::set const& in, +Component* create_LayeredModel(const YAML::Node& node, + const std::set& in, YAMLAbstractParser* parser); -Component* create_Include(YAML::Node const& node, std::set const& in, +Component* create_Include(const YAML::Node& node, + const std::set& in, YAMLAbstractParser* parser); template -Component* create_Special(YAML::Node const& node, std::set const& in, +Component* create_Special(const YAML::Node& node, + const std::set& in, YAMLAbstractParser* parser) { - checkType(node, "constants", {YAML::NodeType::Map}, false); + checkType(node, "constants", {YAML::NodeType::Map}, false); - std::map constants; - if (node["constants"]) { - constants = node["constants"].as>(); - } + std::map constants; + if (node["constants"]) { + constants = node["constants"].as>(); + } - SpecialMap* component = new SpecialMap; - component->setMap(constants); + SpecialMap* component = new SpecialMap; + component->setMap(constants); - parse_Map(component, node, in, parser); + parse_Map(component, node, in, parser); - return component; + return component; } } // namespace easi diff --git a/include/easi/parser/YAMLHelpers.h b/include/easi/parser/YAMLHelpers.h index f869598..f159341 100644 --- a/include/easi/parser/YAMLHelpers.h +++ b/include/easi/parser/YAMLHelpers.h @@ -1,78 +1,85 @@ #ifndef EASI_PARSER_YAMLHELPERS_H_ #define EASI_PARSER_YAMLHELPERS_H_ -#include - #include #include #include #include #include +#include namespace YAML { -template struct convert; +template +struct convert; } namespace easi { class Component; -template class Matrix; -template class Vector; +template +class Matrix; +template +class Vector; -void checkExistence(YAML::Node const& node, std::string const& name); -void checkType(YAML::Node const& node, std::string const& name, - std::set const& types, bool required = true); +void checkExistence(const YAML::Node& node, const std::string& name); +void checkType(const YAML::Node& node, + const std::string& name, + const std::set& types, + bool required = true); -template T* upcast(YAML::Node const& node, Component* component) { - T* up = dynamic_cast(component); - if (up == nullptr) { - std::stringstream ss; - ss << node.Tag() << ": Failed upcast."; - throw YAML::Exception(node.Mark(), ss.str()); - } - return up; +template +T* upcast(const YAML::Node& node, Component* component) { + T* up = dynamic_cast(component); + if (up == nullptr) { + std::stringstream ss; + ss << node.Tag() << ": Failed upcast."; + throw YAML::Exception(node.Mark(), ss.str()); + } + return up; } } // namespace easi namespace YAML { -template struct convert> { - static bool decode(Node const& node, easi::Vector& rhs) { - if (!node.IsSequence()) { - return false; - } - rhs.reallocate(node.size()); +template +struct convert> { + static bool decode(const Node& node, easi::Vector& rhs) { + if (!node.IsSequence()) { + return false; + } + rhs.reallocate(node.size()); - for (std::size_t i = 0; i < node.size(); ++i) { - rhs(i) = node[i].as(); - } - return true; + for (std::size_t i = 0; i < node.size(); ++i) { + rhs(i) = node[i].as(); } + return true; + } }; -template struct convert> { - static bool decode(Node const& node, easi::Matrix& rhs) { - std::size_t rows = node.size(); - if (!node.IsSequence() || rows == 0) { - return false; - } - std::size_t maxCols = 0; - for (std::size_t i = 0; i < node.size(); ++i) { - if (!node.IsSequence()) { - return false; - } - maxCols = std::max(maxCols, node[i].size()); - } - rhs.reallocate(rows, maxCols); +template +struct convert> { + static bool decode(const Node& node, easi::Matrix& rhs) { + std::size_t rows = node.size(); + if (!node.IsSequence() || rows == 0) { + return false; + } + std::size_t maxCols = 0; + for (std::size_t i = 0; i < node.size(); ++i) { + if (!node.IsSequence()) { + return false; + } + maxCols = std::max(maxCols, node[i].size()); + } + rhs.reallocate(rows, maxCols); - for (std::size_t i = 0; i < node.size(); ++i) { - for (std::size_t j = 0; j < node[i].size(); ++j) { - rhs(i, j) = node[i][j].as(); - } - } - return true; + for (std::size_t i = 0; i < node.size(); ++i) { + for (std::size_t j = 0; j < node[i].size(); ++j) { + rhs(i, j) = node[i][j].as(); + } } + return true; + } }; } // namespace YAML diff --git a/include/easi/util/AsagiReader.h b/include/easi/util/AsagiReader.h index 735c97b..5b336ca 100644 --- a/include/easi/util/AsagiReader.h +++ b/include/easi/util/AsagiReader.h @@ -6,10 +6,10 @@ namespace easi { class AsagiReader { -public: - inline virtual ~AsagiReader() {} - virtual asagi::Grid* open(char const* file, char const* varname); - inline virtual unsigned numberOfThreads() const { return 1; } + public: + inline virtual ~AsagiReader() {} + virtual asagi::Grid* open(const char* file, const char* varname); + inline virtual unsigned numberOfThreads() const { return 1; } }; } // namespace easi diff --git a/include/easi/util/ImpalaHandler.h b/include/easi/util/ImpalaHandler.h index 866165e..1855b52 100644 --- a/include/easi/util/ImpalaHandler.h +++ b/include/easi/util/ImpalaHandler.h @@ -7,7 +7,8 @@ namespace easi { -std::string convertImpalaToLua(const std::unordered_map& code, const std::vector& in); +std::string convertImpalaToLua(const std::unordered_map& code, + const std::vector& in); } // namespace easi diff --git a/include/easi/util/Magic.h b/include/easi/util/Magic.h index 49e7e5a..67f74ea 100644 --- a/include/easi/util/Magic.h +++ b/include/easi/util/Magic.h @@ -2,61 +2,125 @@ #define EASI_UTIL_MAGIC_H_ #define MAGIC_EXPAND(X) X -#define MAGIC_CONCATENATE(a,b) MAGIC_CONCATENATE_1(a,b) -#define MAGIC_CONCATENATE_1(a,b) MAGIC_CONCATENATE_2(a,b) -#define MAGIC_CONCATENATE_2(a,b) a##b +#define MAGIC_CONCATENATE(a, b) MAGIC_CONCATENATE_1(a, b) +#define MAGIC_CONCATENATE_1(a, b) MAGIC_CONCATENATE_2(a, b) +#define MAGIC_CONCATENATE_2(a, b) a##b #define MAGIC_NARG(...) MAGIC_NARG_(__VA_ARGS__, MAGIC_RSEQ_N()) #define MAGIC_NARG_(...) MAGIC_EXPAND(MAGIC_ARG_N(__VA_ARGS__)) -#define MAGIC_ARG_N(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, N, ...) N -#define MAGIC_RSEQ_N() 20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0 +#define MAGIC_ARG_N(_1, \ + _2, \ + _3, \ + _4, \ + _5, \ + _6, \ + _7, \ + _8, \ + _9, \ + _10, \ + _11, \ + _12, \ + _13, \ + _14, \ + _15, \ + _16, \ + _17, \ + _18, \ + _19, \ + _20, \ + N, \ + ...) \ + N +#define MAGIC_RSEQ_N() 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 -#define MAGIC_FOR_EACH_1(N, macro, prefix, first) macro(N-1, prefix, first) -#define MAGIC_FOR_EACH_2(N, macro, prefix, first, ...) macro(N-2, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_1(N, macro, prefix, __VA_ARGS__)) -#define MAGIC_FOR_EACH_3(N, macro, prefix, first, ...) macro(N-3, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_2(N, macro, prefix, __VA_ARGS__)) -#define MAGIC_FOR_EACH_4(N, macro, prefix, first, ...) macro(N-4, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_3(N, macro, prefix, __VA_ARGS__)) -#define MAGIC_FOR_EACH_5(N, macro, prefix, first, ...) macro(N-5, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_4(N, macro, prefix, __VA_ARGS__)) -#define MAGIC_FOR_EACH_6(N, macro, prefix, first, ...) macro(N-6, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_5(N, macro, prefix, __VA_ARGS__)) -#define MAGIC_FOR_EACH_7(N, macro, prefix, first, ...) macro(N-7, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_6(N, macro, prefix, __VA_ARGS__)) -#define MAGIC_FOR_EACH_8(N, macro, prefix, first, ...) macro(N-8, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_7(N, macro, prefix, __VA_ARGS__)) -#define MAGIC_FOR_EACH_9(N, macro, prefix, first, ...) macro(N-9, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_8(N, macro, prefix, __VA_ARGS__)) -#define MAGIC_FOR_EACH_10(N, macro, prefix, first, ...) macro(N-10, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_9(N, macro, prefix, __VA_ARGS__)) -#define MAGIC_FOR_EACH_11(N, macro, prefix, first, ...) macro(N-11, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_10(N, macro, prefix, __VA_ARGS__)) -#define MAGIC_FOR_EACH_12(N, macro, prefix, first, ...) macro(N-12, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_11(N, macro, prefix, __VA_ARGS__)) -#define MAGIC_FOR_EACH_13(N, macro, prefix, first, ...) macro(N-13, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_12(N, macro, prefix, __VA_ARGS__)) -#define MAGIC_FOR_EACH_14(N, macro, prefix, first, ...) macro(N-14, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_13(N, macro, prefix, __VA_ARGS__)) -#define MAGIC_FOR_EACH_15(N, macro, prefix, first, ...) macro(N-15, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_14(N, macro, prefix, __VA_ARGS__)) -#define MAGIC_FOR_EACH_16(N, macro, prefix, first, ...) macro(N-16, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_15(N, macro, prefix, __VA_ARGS__)) -#define MAGIC_FOR_EACH_17(N, macro, prefix, first, ...) macro(N-17, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_16(N, macro, prefix, __VA_ARGS__)) -#define MAGIC_FOR_EACH_18(N, macro, prefix, first, ...) macro(N-18, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_17(N, macro, prefix, __VA_ARGS__)) -#define MAGIC_FOR_EACH_19(N, macro, prefix, first, ...) macro(N-19, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_18(N, macro, prefix, __VA_ARGS__)) -#define MAGIC_FOR_EACH_20(N, macro, prefix, first, ...) macro(N-20, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_19(N, macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_1(N, macro, prefix, first) macro(N - 1, prefix, first) +#define MAGIC_FOR_EACH_2(N, macro, prefix, first, ...) \ + macro(N - 2, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_1(N, macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_3(N, macro, prefix, first, ...) \ + macro(N - 3, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_2(N, macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_4(N, macro, prefix, first, ...) \ + macro(N - 4, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_3(N, macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_5(N, macro, prefix, first, ...) \ + macro(N - 5, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_4(N, macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_6(N, macro, prefix, first, ...) \ + macro(N - 6, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_5(N, macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_7(N, macro, prefix, first, ...) \ + macro(N - 7, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_6(N, macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_8(N, macro, prefix, first, ...) \ + macro(N - 8, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_7(N, macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_9(N, macro, prefix, first, ...) \ + macro(N - 9, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_8(N, macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_10(N, macro, prefix, first, ...) \ + macro(N - 10, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_9(N, macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_11(N, macro, prefix, first, ...) \ + macro(N - 11, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_10(N, macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_12(N, macro, prefix, first, ...) \ + macro(N - 12, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_11(N, macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_13(N, macro, prefix, first, ...) \ + macro(N - 13, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_12(N, macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_14(N, macro, prefix, first, ...) \ + macro(N - 14, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_13(N, macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_15(N, macro, prefix, first, ...) \ + macro(N - 15, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_14(N, macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_16(N, macro, prefix, first, ...) \ + macro(N - 16, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_15(N, macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_17(N, macro, prefix, first, ...) \ + macro(N - 17, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_16(N, macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_18(N, macro, prefix, first, ...) \ + macro(N - 18, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_17(N, macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_19(N, macro, prefix, first, ...) \ + macro(N - 19, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_18(N, macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_20(N, macro, prefix, first, ...) \ + macro(N - 20, prefix, first) MAGIC_EXPAND(MAGIC_FOR_EACH_19(N, macro, prefix, __VA_ARGS__)) #define MAGIC_FOR_EACH_COMMA_SEPARATED_1(macro, prefix, first) macro(prefix, first) -#define MAGIC_FOR_EACH_COMMA_SEPARATED_2(macro, prefix, first, ...) macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_1(macro, prefix, __VA_ARGS__)) -#define MAGIC_FOR_EACH_COMMA_SEPARATED_3(macro, prefix, first, ...) macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_2(macro, prefix, __VA_ARGS__)) -#define MAGIC_FOR_EACH_COMMA_SEPARATED_4(macro, prefix, first, ...) macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_3(macro, prefix, __VA_ARGS__)) -#define MAGIC_FOR_EACH_COMMA_SEPARATED_5(macro, prefix, first, ...) macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_4(macro, prefix, __VA_ARGS__)) -#define MAGIC_FOR_EACH_COMMA_SEPARATED_6(macro, prefix, first, ...) macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_5(macro, prefix, __VA_ARGS__)) -#define MAGIC_FOR_EACH_COMMA_SEPARATED_7(macro, prefix, first, ...) macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_6(macro, prefix, __VA_ARGS__)) -#define MAGIC_FOR_EACH_COMMA_SEPARATED_8(macro, prefix, first, ...) macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_7(macro, prefix, __VA_ARGS__)) -#define MAGIC_FOR_EACH_COMMA_SEPARATED_9(macro, prefix, first, ...) macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_8(macro, prefix, __VA_ARGS__)) -#define MAGIC_FOR_EACH_COMMA_SEPARATED_10(macro, prefix, first, ...) macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_9(macro, prefix, __VA_ARGS__)) -#define MAGIC_FOR_EACH_COMMA_SEPARATED_11(macro, prefix, first, ...) macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_10(macro, prefix, __VA_ARGS__)) -#define MAGIC_FOR_EACH_COMMA_SEPARATED_12(macro, prefix, first, ...) macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_11(macro, prefix, __VA_ARGS__)) -#define MAGIC_FOR_EACH_COMMA_SEPARATED_13(macro, prefix, first, ...) macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_12(macro, prefix, __VA_ARGS__)) -#define MAGIC_FOR_EACH_COMMA_SEPARATED_14(macro, prefix, first, ...) macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_13(macro, prefix, __VA_ARGS__)) -#define MAGIC_FOR_EACH_COMMA_SEPARATED_15(macro, prefix, first, ...) macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_14(macro, prefix, __VA_ARGS__)) -#define MAGIC_FOR_EACH_COMMA_SEPARATED_16(macro, prefix, first, ...) macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_15(macro, prefix, __VA_ARGS__)) -#define MAGIC_FOR_EACH_COMMA_SEPARATED_17(macro, prefix, first, ...) macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_16(macro, prefix, __VA_ARGS__)) -#define MAGIC_FOR_EACH_COMMA_SEPARATED_18(macro, prefix, first, ...) macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_17(macro, prefix, __VA_ARGS__)) -#define MAGIC_FOR_EACH_COMMA_SEPARATED_19(macro, prefix, first, ...) macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_18(macro, prefix, __VA_ARGS__)) -#define MAGIC_FOR_EACH_COMMA_SEPARATED_20(macro, prefix, first, ...) macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_19(macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_COMMA_SEPARATED_2(macro, prefix, first, ...) \ + macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_1(macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_COMMA_SEPARATED_3(macro, prefix, first, ...) \ + macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_2(macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_COMMA_SEPARATED_4(macro, prefix, first, ...) \ + macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_3(macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_COMMA_SEPARATED_5(macro, prefix, first, ...) \ + macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_4(macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_COMMA_SEPARATED_6(macro, prefix, first, ...) \ + macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_5(macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_COMMA_SEPARATED_7(macro, prefix, first, ...) \ + macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_6(macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_COMMA_SEPARATED_8(macro, prefix, first, ...) \ + macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_7(macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_COMMA_SEPARATED_9(macro, prefix, first, ...) \ + macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_8(macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_COMMA_SEPARATED_10(macro, prefix, first, ...) \ + macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_9(macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_COMMA_SEPARATED_11(macro, prefix, first, ...) \ + macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_10(macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_COMMA_SEPARATED_12(macro, prefix, first, ...) \ + macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_11(macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_COMMA_SEPARATED_13(macro, prefix, first, ...) \ + macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_12(macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_COMMA_SEPARATED_14(macro, prefix, first, ...) \ + macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_13(macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_COMMA_SEPARATED_15(macro, prefix, first, ...) \ + macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_14(macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_COMMA_SEPARATED_16(macro, prefix, first, ...) \ + macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_15(macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_COMMA_SEPARATED_17(macro, prefix, first, ...) \ + macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_16(macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_COMMA_SEPARATED_18(macro, prefix, first, ...) \ + macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_17(macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_COMMA_SEPARATED_19(macro, prefix, first, ...) \ + macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_18(macro, prefix, __VA_ARGS__)) +#define MAGIC_FOR_EACH_COMMA_SEPARATED_20(macro, prefix, first, ...) \ + macro(prefix, first), MAGIC_EXPAND(MAGIC_FOR_EACH_COMMA_SEPARATED_19(macro, prefix, __VA_ARGS__)) -#define MAGIC_FOR_EACH_(N, macro, prefix, ...) MAGIC_CONCATENATE(MAGIC_FOR_EACH_, N)(N, macro, prefix, __VA_ARGS__) -#define MAGIC_FOR_EACH(macro, prefix, ...) MAGIC_FOR_EACH_(MAGIC_NARG(__VA_ARGS__), macro, prefix, __VA_ARGS__) +#define MAGIC_FOR_EACH_(N, macro, prefix, ...) \ + MAGIC_CONCATENATE(MAGIC_FOR_EACH_, N)(N, macro, prefix, __VA_ARGS__) +#define MAGIC_FOR_EACH(macro, prefix, ...) \ + MAGIC_FOR_EACH_(MAGIC_NARG(__VA_ARGS__), macro, prefix, __VA_ARGS__) -#define MAGIC_FOR_EACH_COMMA_SEPARATED_(N, macro, prefix, ...) MAGIC_CONCATENATE(MAGIC_FOR_EACH_COMMA_SEPARATED_, N)(macro, prefix, __VA_ARGS__) -#define MAGIC_FOR_EACH_COMMA_SEPARATED(macro, prefix, ...) MAGIC_FOR_EACH_COMMA_SEPARATED_(MAGIC_NARG(__VA_ARGS__), macro, prefix, __VA_ARGS__) +#define MAGIC_FOR_EACH_COMMA_SEPARATED_(N, macro, prefix, ...) \ + MAGIC_CONCATENATE(MAGIC_FOR_EACH_COMMA_SEPARATED_, N)(macro, prefix, __VA_ARGS__) +#define MAGIC_FOR_EACH_COMMA_SEPARATED(macro, prefix, ...) \ + MAGIC_FOR_EACH_COMMA_SEPARATED_(MAGIC_NARG(__VA_ARGS__), macro, prefix, __VA_ARGS__) #endif diff --git a/include/easi/util/MagicStruct.h b/include/easi/util/MagicStruct.h index 289e012..b0faa59 100644 --- a/include/easi/util/MagicStruct.h +++ b/include/easi/util/MagicStruct.h @@ -2,26 +2,32 @@ #define EASI_UTIL_MAGICSTRUCT_H_ #include "Magic.h" + #include #include #include namespace easi { -template static std::string const* get_member_names(); -template static int get_binding_point(std::string const& member); -template constexpr static int get_number_of_members(); -template static double T::*get_pointer_to_member(int bp); - -template static std::set memberNamesToSet() { - std::string const* begin = get_member_names(); - std::string const* end = begin + get_number_of_members(); - - std::set s; - for (std::string const* it = begin; it != end; ++it) { - s.insert(*it); - } - return s; +template +static const std::string* get_member_names(); +template +static int get_binding_point(const std::string& member); +template +constexpr static int get_number_of_members(); +template +static double T::* get_pointer_to_member(int bp); + +template +static std::set memberNamesToSet() { + const std::string* begin = get_member_names(); + const std::string* end = begin + get_number_of_members(); + + std::set s; + for (const std::string* it = begin; it != end; ++it) { + s.insert(*it); + } + return s; } } // namespace easi @@ -29,23 +35,29 @@ template static std::set memberNamesToSet() { #define SAS_TOSTRING(STRUCT, X) #X #define SAS_TOPOINTERTOMEMBER(STRUCT, X) &STRUCT::X #define SELF_AWARE_STRUCT(STRUCT, ...) \ - namespace easi { \ - template <> std::string const* get_member_names() { \ - static std::string const names[] = { \ - MAGIC_FOR_EACH_COMMA_SEPARATED(SAS_TOSTRING, STRUCT, __VA_ARGS__)}; \ - return names; \ - } \ - template <> int get_binding_point(std::string const& field) { \ - std::string const* names = get_member_names(); \ - std::string const* it = std::find(names, names + MAGIC_NARG(__VA_ARGS__), field); \ - return (it != names + MAGIC_NARG(__VA_ARGS__)) ? std::distance(names, it) : -1; \ - } \ - template <> constexpr int get_number_of_members() { return MAGIC_NARG(__VA_ARGS__); } \ - template <> double STRUCT::*get_pointer_to_member(int bp) { \ - static double STRUCT::*const ptrToMember[] = { \ - MAGIC_FOR_EACH_COMMA_SEPARATED(SAS_TOPOINTERTOMEMBER, STRUCT, __VA_ARGS__)}; \ - return ptrToMember[bp]; \ - } \ - } + namespace easi { \ + template <> \ + std::string const* get_member_names() { \ + static std::string const names[] = { \ + MAGIC_FOR_EACH_COMMA_SEPARATED(SAS_TOSTRING, STRUCT, __VA_ARGS__)}; \ + return names; \ + } \ + template <> \ + int get_binding_point(std::string const& field) { \ + std::string const* names = get_member_names(); \ + std::string const* it = std::find(names, names + MAGIC_NARG(__VA_ARGS__), field); \ + return (it != names + MAGIC_NARG(__VA_ARGS__)) ? std::distance(names, it) : -1; \ + } \ + template <> \ + constexpr int get_number_of_members() { \ + return MAGIC_NARG(__VA_ARGS__); \ + } \ + template <> \ + double STRUCT::* get_pointer_to_member(int bp) { \ + static double STRUCT::* const ptrToMember[] = { \ + MAGIC_FOR_EACH_COMMA_SEPARATED(SAS_TOPOINTERTOMEMBER, STRUCT, __VA_ARGS__)}; \ + return ptrToMember[bp]; \ + } \ + } #endif diff --git a/include/easi/util/Matrix.h b/include/easi/util/Matrix.h index f06bf07..50d88b7 100644 --- a/include/easi/util/Matrix.h +++ b/include/easi/util/Matrix.h @@ -8,103 +8,110 @@ namespace easi { -template class Matrix { -public: - Matrix(); - Matrix(unsigned rows, unsigned cols); +template +class Matrix { + public: + Matrix(); + Matrix(unsigned rows, unsigned cols); - void reallocate(unsigned rows, unsigned cols); - void clear(); + void reallocate(unsigned rows, unsigned cols); + void clear(); - Matrix block(unsigned rows, unsigned cols) const; - Matrix transposed() const; + Matrix block(unsigned rows, unsigned cols) const; + Matrix transposed() const; - unsigned rows() const { return m_rows; } - unsigned cols() const { return m_cols; } + unsigned rows() const { return m_rows; } + unsigned cols() const { return m_cols; } - inline T& operator()(unsigned i, unsigned j) { return *(m_data.get() + i + j * m_ld); } - inline T const& operator()(unsigned i, unsigned j) const { - return *(m_data.get() + i + j * m_ld); - } + inline T& operator()(unsigned i, unsigned j) { return *(m_data.get() + i + j * m_ld); } + inline const T& operator()(unsigned i, unsigned j) const { + return *(m_data.get() + i + j * m_ld); + } - Slice rowSlice(unsigned index) { return Slice(m_ld, m_cols, m_data.get() + index); } - Slice colSlice(unsigned index) { return Slice(1, m_rows, m_data.get() + index * m_ld); } + Slice rowSlice(unsigned index) { return Slice(m_ld, m_cols, m_data.get() + index); } + Slice colSlice(unsigned index) { return Slice(1, m_rows, m_data.get() + index * m_ld); } -private: - unsigned m_rows, m_cols, m_ld; + private: + unsigned m_rows, m_cols, m_ld; - std::shared_ptr m_data; + std::shared_ptr m_data; }; -template Matrix::Matrix() : m_rows(0), m_cols(0), m_ld(0), m_data(nullptr) {} +template +Matrix::Matrix() : m_rows(0), m_cols(0), m_ld(0), m_data(nullptr) {} template Matrix::Matrix(unsigned rows, unsigned cols) : m_rows(rows), m_cols(cols), m_ld(rows), m_data(new T[rows * cols], std::default_delete()) {} -template void Matrix::reallocate(unsigned rows, unsigned cols) { - m_rows = rows; - m_cols = cols; - m_ld = rows; - m_data = std::shared_ptr(new T[rows * cols], std::default_delete()); +template +void Matrix::reallocate(unsigned rows, unsigned cols) { + m_rows = rows; + m_cols = cols; + m_ld = rows; + m_data = std::shared_ptr(new T[rows * cols], std::default_delete()); } -template void Matrix::clear() { - m_rows = 0; - m_cols = 0; - m_ld = 0; - m_data = nullptr; +template +void Matrix::clear() { + m_rows = 0; + m_cols = 0; + m_ld = 0; + m_data = nullptr; } -template Matrix Matrix::block(unsigned rows, unsigned cols) const { - if (rows <= m_rows && cols <= m_cols) { - Matrix result(*this); - result.m_rows = rows; - result.m_cols = cols; +template +Matrix Matrix::block(unsigned rows, unsigned cols) const { + if (rows <= m_rows && cols <= m_cols) { + Matrix result(*this); + result.m_rows = rows; + result.m_cols = cols; - return result; - } + return result; + } - Matrix result(rows, cols); - for (unsigned j = 0; j < m_cols; ++j) { - for (unsigned i = 0; i < m_rows; ++i) { - result(i, j) = operator()(i, j); - } + Matrix result(rows, cols); + for (unsigned j = 0; j < m_cols; ++j) { + for (unsigned i = 0; i < m_rows; ++i) { + result(i, j) = operator()(i, j); } - for (unsigned j = m_cols; j < result.m_cols; ++j) { - for (unsigned i = m_rows; i < result.m_rows; ++i) { - result(i, j) = static_cast(0); - } + } + for (unsigned j = m_cols; j < result.m_cols; ++j) { + for (unsigned i = m_rows; i < result.m_rows; ++i) { + result(i, j) = static_cast(0); } - return result; + } + return result; } -template Matrix Matrix::transposed() const { - Matrix result(m_cols, m_rows); - for (unsigned j = 0; j < result.m_cols; ++j) { - for (unsigned i = 0; i < result.m_rows; ++i) { - result(i, j) = operator()(j, i); - } +template +Matrix Matrix::transposed() const { + Matrix result(m_cols, m_rows); + for (unsigned j = 0; j < result.m_cols; ++j) { + for (unsigned i = 0; i < result.m_rows; ++i) { + result(i, j) = operator()(j, i); } - return result; + } + return result; } // TODO: Replace by something proper -template Matrix operator*(Matrix const& A, Matrix const& B) { - assert(A.cols() == B.rows()); - - Matrix C(A.rows(), B.cols()); - for (unsigned j = 0; j < C.cols(); ++j) { - for (unsigned i = 0; i < C.rows(); ++i) { - C(i, j) = static_cast(0); - for (unsigned k = 0; k < A.cols(); ++k) { - C(i, j) += A(i, k) * B(k, j); - } - } +template +Matrix operator*(const Matrix& A, const Matrix& B) { + assert(A.cols() == B.rows()); + + Matrix C(A.rows(), B.cols()); + for (unsigned j = 0; j < C.cols(); ++j) { + for (unsigned i = 0; i < C.rows(); ++i) { + C(i, j) = static_cast(0); + for (unsigned k = 0; k < A.cols(); ++k) { + C(i, j) += A(i, k) * B(k, j); + } } + } - return C; + return C; } } // namespace easi diff --git a/include/easi/util/Print.h b/include/easi/util/Print.h index 6951e59..f23ac31 100644 --- a/include/easi/util/Print.h +++ b/include/easi/util/Print.h @@ -8,15 +8,15 @@ namespace easi { template -void printWithSeparator(T const& vectorLike, std::ostream& os, std::string const& separator = ",") { - auto it = vectorLike.cbegin(); - auto end = vectorLike.cend(); - if (it != end) { - os << *it++; - } - while (it != end) { - os << separator << *it++; - } +void printWithSeparator(const T& vectorLike, std::ostream& os, const std::string& separator = ",") { + auto it = vectorLike.cbegin(); + auto end = vectorLike.cend(); + if (it != end) { + os << *it++; + } + while (it != end) { + os << separator << *it++; + } } } // namespace easi diff --git a/include/easi/util/RegularGrid.h b/include/easi/util/RegularGrid.h index 53c8ec8..7568dc2 100644 --- a/include/easi/util/RegularGrid.h +++ b/include/easi/util/RegularGrid.h @@ -3,29 +3,30 @@ namespace easi { -template class Slice; +template +class Slice; class RegularGrid { -public: - static unsigned const MaxDimensions = 6; - - inline ~RegularGrid() { delete[] m_values; } - - void allocate(unsigned const* numGridPoints, unsigned dimensions, unsigned numValues); - void setVolume(double const* min, double const* max); - double* operator()(unsigned const* index); - - void getNearestNeighbour(Slice const& x, double* buffer); - void getNeighbours(Slice const& x, double* weights, double* buffer); - -private: - double* m_values = nullptr; - unsigned m_dimensions = 0; - unsigned m_numValues = 0; - double m_min[MaxDimensions]; - double m_max[MaxDimensions]; - unsigned m_num[MaxDimensions]; - double m_delta[MaxDimensions]; + public: + static const unsigned MaxDimensions = 6; + + inline ~RegularGrid() { delete[] m_values; } + + void allocate(const unsigned* numGridPoints, unsigned dimensions, unsigned numValues); + void setVolume(const double* min, const double* max); + double* operator()(const unsigned* index); + + void getNearestNeighbour(const Slice& x, double* buffer); + void getNeighbours(const Slice& x, double* weights, double* buffer); + + private: + double* m_values = nullptr; + unsigned m_dimensions = 0; + unsigned m_numValues = 0; + double m_min[MaxDimensions]; + double m_max[MaxDimensions]; + unsigned m_num[MaxDimensions]; + double m_delta[MaxDimensions]; }; } // namespace easi diff --git a/include/easi/util/Slice.h b/include/easi/util/Slice.h index 25346b0..c83c4a5 100644 --- a/include/easi/util/Slice.h +++ b/include/easi/util/Slice.h @@ -3,18 +3,19 @@ namespace easi { -template class Slice { -public: - Slice(unsigned offset, unsigned size, double* data) - : m_offset(offset), m_size(size), m_data(data) {} +template +class Slice { + public: + Slice(unsigned offset, unsigned size, double* data) + : m_offset(offset), m_size(size), m_data(data) {} - inline T& operator()(unsigned i) { return m_data[i * m_offset]; } - inline T const& operator()(unsigned i) const { return m_data[i * m_offset]; } - inline unsigned size() const { return m_size; } + inline T& operator()(unsigned i) { return m_data[i * m_offset]; } + inline const T& operator()(unsigned i) const { return m_data[i * m_offset]; } + inline unsigned size() const { return m_size; } -private: - unsigned m_offset, m_size; - T* m_data; + private: + unsigned m_offset, m_size; + T* m_data; }; } // namespace easi diff --git a/include/easi/util/Vector.h b/include/easi/util/Vector.h index aa23fc3..0b6d8a1 100644 --- a/include/easi/util/Vector.h +++ b/include/easi/util/Vector.h @@ -5,16 +5,17 @@ namespace easi { -template class Vector : public Matrix { -public: - Vector() : Matrix() {} - Vector(unsigned rows) : Matrix(rows, 1) {} +template +class Vector : public Matrix { + public: + Vector() : Matrix() {} + Vector(unsigned rows) : Matrix(rows, 1) {} - void reallocate(unsigned size) { Matrix::reallocate(size, 1); } + void reallocate(unsigned size) { Matrix::reallocate(size, 1); } - inline T& operator()(unsigned i) { return Matrix::operator()(i, 0); } - inline T const& operator()(unsigned i) const { return Matrix::operator()(i, 0); } - inline unsigned size() const { return Matrix::rows(); } + inline T& operator()(unsigned i) { return Matrix::operator()(i, 0); } + inline const T& operator()(unsigned i) const { return Matrix::operator()(i, 0); } + inline unsigned size() const { return Matrix::rows(); } }; } // namespace easi diff --git a/python_bindings/README.md b/python_bindings/README.md index e930702..0434d58 100644 --- a/python_bindings/README.md +++ b/python_bindings/README.md @@ -1,3 +1,4 @@ # A python wrapper for easi -see https://easyinit.readthedocs.io/en/latest/python_bindings.html +see [the documentation](https://easyinit.readthedocs.io/en/latest/python_bindings.html) +for more infos. diff --git a/python_bindings/easi_wrapper.cpp b/python_bindings/easi_wrapper.cpp index 392be15..f7cb0ac 100644 --- a/python_bindings/easi_wrapper.cpp +++ b/python_bindings/easi_wrapper.cpp @@ -19,70 +19,72 @@ void finalizeMPI() { MPI_Finalize(); } void version(py::module& m) { m.attr("__version__") = EASI_VERSION; } struct OutputStruc { - double parameter; + double parameter; }; py::array_t evaluate_model_one_parameter(py::array_t coordinates, py::array_t groups, const std::string parameter_name, const std::string& yaml_file) { - // Obtain buffer pointers - auto coords_buf = coordinates.request(); - auto groups_buf = groups.request(); + // Obtain buffer pointers + auto coords_buf = coordinates.request(); + auto groups_buf = groups.request(); - if (coords_buf.ndim != 2 || coords_buf.shape[1] != 3) { - throw std::runtime_error("Input array must be of shape (npoints, 3)"); - } + if (coords_buf.ndim != 2 || coords_buf.shape[1] != 3) { + throw std::runtime_error("Input array must be of shape (npoints, 3)"); + } - int npoints = coords_buf.shape[0]; + int npoints = coords_buf.shape[0]; - easi::Query query(npoints, 3); + easi::Query query(npoints, 3); - for (int i = 0; i < npoints; ++i) { - for (int j = 0; j < 3; ++j) { - query.x(i, j) = coordinates.at(i, j); - } - query.group(i) = groups.at(i); + for (int i = 0; i < npoints; ++i) { + for (int j = 0; j < 3; ++j) { + query.x(i, j) = coordinates.at(i, j); } + query.group(i) = groups.at(i); + } - easi::YAMLParser parser(3); - easi::Component* model_stress = parser.parse(yaml_file.c_str()); + easi::YAMLParser parser(3); + easi::Component* model_stress = parser.parse(yaml_file.c_str()); - std::vector myOutputStruc(npoints); - easi::ArrayOfStructsAdapter adapter(myOutputStruc.data()); - adapter.addBindingPoint(parameter_name.c_str(), &OutputStruc::parameter); + std::vector myOutputStruc(npoints); + easi::ArrayOfStructsAdapter adapter(myOutputStruc.data()); + adapter.addBindingPoint(parameter_name.c_str(), &OutputStruc::parameter); - model_stress->evaluate(query, adapter); + model_stress->evaluate(query, adapter); - delete model_stress; + delete model_stress; - // Create a new NumPy array to store the result - py::array_t result_array(npoints); - auto result_buf = result_array.request(); + // Create a new NumPy array to store the result + py::array_t result_array(npoints); + auto result_buf = result_array.request(); - for (size_t i = 0; i < npoints; ++i) { - result_array.mutable_at(i) = myOutputStruc[i].parameter; - } - return result_array; + for (size_t i = 0; i < npoints; ++i) { + result_array.mutable_at(i) = myOutputStruc[i].parameter; + } + return result_array; } -py::dict evaluate_model(py::array_t coordinates, py::array_t groups, - const std::vector& parameters, const std::string& yaml_file) { - // Create a Python dictionary to hold the results - py::dict result_dict; - - for (const auto& parameter_name : parameters) { - result_dict[parameter_name.c_str()] = - evaluate_model_one_parameter(coordinates, groups, parameter_name, yaml_file); - } - return result_dict; +py::dict evaluate_model(py::array_t coordinates, + py::array_t groups, + const std::vector& parameters, + const std::string& yaml_file) { + // Create a Python dictionary to hold the results + py::dict result_dict; + + for (const auto& parameter_name : parameters) { + result_dict[parameter_name.c_str()] = + evaluate_model_one_parameter(coordinates, groups, parameter_name, yaml_file); + } + return result_dict; } void initializeModule(py::module& m) { - // Call initializeMPI when the module is loaded - initializeMPI(); - m.def("finalizeMPI", &finalizeMPI, "Finalize MPI"); - m.def("evaluate_model", &evaluate_model, R"pbdoc( + // Call initializeMPI when the module is loaded + initializeMPI(); + m.def("finalizeMPI", &finalizeMPI, "Finalize MPI"); + m.def("evaluate_model", &evaluate_model, R"pbdoc( Evaluate Easi model for given coordinates and parameters. Parameters: @@ -94,7 +96,7 @@ void initializeModule(py::module& m) { Returns: - Dict[str, numpy.ndarray]: Dictionary containing parameter names as keys and result arrays as values. )pbdoc"); - version(m); + version(m); } PYBIND11_MODULE(easi, m) { initializeModule(m); } diff --git a/src/Query.cpp b/src/Query.cpp index aa55c91..ac4d84a 100644 --- a/src/Query.cpp +++ b/src/Query.cpp @@ -4,22 +4,22 @@ namespace easi { Query::Query(unsigned numPoints, unsigned dimDomain, bool initIndices) : group(numPoints), x(numPoints, dimDomain), index(numPoints) { - if (initIndices) { - for (unsigned i = 0; i < numPoints; ++i) { - index(i) = i; - } + if (initIndices) { + for (unsigned i = 0; i < numPoints; ++i) { + index(i) = i; } + } } Query Query::shallowCopy() { - Query copy = *this; - return copy; + Query copy = *this; + return copy; } void Query::clear() { - group.clear(); - x.clear(); - index.clear(); + group.clear(); + x.clear(); + index.clear(); } } // namespace easi diff --git a/src/YAMLParser.cpp b/src/YAMLParser.cpp index cb13b5f..10fbc30 100644 --- a/src/YAMLParser.cpp +++ b/src/YAMLParser.cpp @@ -1,9 +1,11 @@ #include "easi/YAMLParser.h" + #include "easi/Component.h" #include "easi/component/AndersonianStress.h" #include "easi/component/OptimalStress.h" #include "easi/component/Special.h" #include "easi/parser/YAMLComponentParsers.h" + #include #ifdef EASI_USE_ASAGI @@ -30,121 +32,117 @@ namespace fs = std::filesystem; #endif namespace { - std::set makeVariables(std::size_t count, char first) { - std::set variables; - for (std::size_t i = 0; i < count; ++i) { - variables.insert(std::string(1, first + i)); - } - return variables; - } +std::set makeVariables(std::size_t count, char first) { + std::set variables; + for (std::size_t i = 0; i < count; ++i) { + variables.insert(std::string(1, first + i)); + } + return variables; } +} // namespace namespace easi { YAMLParser::YAMLParser(unsigned dimDomain, AsagiReader* externalAsagiReader, char firstVariable) - : YAMLParser(makeVariables(dimDomain, firstVariable), externalAsagiReader) { -} + : YAMLParser(makeVariables(dimDomain, firstVariable), externalAsagiReader) {} YAMLParser::YAMLParser(const std::set& variables, AsagiReader* externalAsagiReader) - : m_in(variables), m_asagiReader(externalAsagiReader), m_externalAsagiReader(externalAsagiReader != nullptr) { - registerType("!Switch", parse_Switch); - registerType("!ConstantMap", parse_ConstantMap); - registerType("!PolynomialMap", parse_PolynomialMap); - registerType("!Any", parse_Any); - registerType("!IdentityMap", parse_Any); - registerType("!GroupFilter", parse_GroupFilter); - registerType("!AxisAlignedCuboidalDomainFilter", parse_AxisAlignedCuboidalDomainFilter); - registerType("!SphericalDomainFilter", parse_SphericalDomainFilter); - registerType("!AffineMap", parse_AffineMap); + : m_in(variables), m_asagiReader(externalAsagiReader), + m_externalAsagiReader(externalAsagiReader != nullptr) { + registerType("!Switch", parse_Switch); + registerType("!ConstantMap", parse_ConstantMap); + registerType("!PolynomialMap", parse_PolynomialMap); + registerType("!Any", parse_Any); + registerType("!IdentityMap", parse_Any); + registerType("!GroupFilter", parse_GroupFilter); + registerType("!AxisAlignedCuboidalDomainFilter", parse_AxisAlignedCuboidalDomainFilter); + registerType("!SphericalDomainFilter", parse_SphericalDomainFilter); + registerType("!AffineMap", parse_AffineMap); #if defined(EASI_USE_LUA) - registerType("!FunctionMap", parse_FunctionMapToLua); - registerType("!LuaMap", parse_LuaMap); + registerType("!FunctionMap", parse_FunctionMapToLua); + registerType("!LuaMap", parse_LuaMap); #endif - registerType("!SCECFile", parse_SCECFile); + registerType("!SCECFile", parse_SCECFile); #ifdef EASI_USE_ASAGI - registerType("!ASAGI", parse_ASAGI); + registerType("!ASAGI", parse_ASAGI); #endif - registerType("!LayeredModel", create_LayeredModel); - registerType("!Include", create_Include); - registerType("!EvalModel", parse_EvalModel); - - if (!m_externalAsagiReader) { - m_asagiReader = new AsagiReader; - } - - // Specials - registerType("!STRESS_STR_DIP_SLIP_AM", create_Special); - registerType("!OptimalStress", create_Special); - registerType("!AndersonianStress", create_Special); + registerType("!LayeredModel", create_LayeredModel); + registerType("!Include", create_Include); + registerType("!EvalModel", parse_EvalModel); + + if (!m_externalAsagiReader) { + m_asagiReader = new AsagiReader; + } + + // Specials + registerType("!STRESS_STR_DIP_SLIP_AM", create_Special); + registerType("!OptimalStress", create_Special); + registerType("!AndersonianStress", create_Special); } YAMLParser::~YAMLParser() { - if (!m_externalAsagiReader) { - delete m_asagiReader; - } + if (!m_externalAsagiReader) { + delete m_asagiReader; + } } -void YAMLParser::registerType(std::string const& tag, std::function create) { - m_creators[tag] = std::move(create); +void YAMLParser::registerType(const std::string& tag, std::function create) { + m_creators[tag] = std::move(create); } -Component* YAMLParser::parse(std::string const& fileName) { - Component* root; - try { - const auto lastFileName = m_currentFileName; - const auto lastPath = fs::path(lastFileName); - const auto nextPath = fs::path(fileName); - const auto loadFileName = [&]() { - if (nextPath.is_relative()) { - // remove file - return lastPath.parent_path() / nextPath; - } - else { - return nextPath; - } - }(); - if (fs::exists(loadFileName)) { - m_currentFileName = fs::canonical(loadFileName); - } - else if (fs::exists(nextPath)) { - m_currentFileName = fs::canonical(nextPath); - } - else { - m_currentFileName = nextPath; - } - m_fileNames.insert(m_currentFileName); - YAML::Node config = YAML::LoadFile(m_currentFileName); - root = parse(config, m_in); - m_currentFileName = lastFileName; - } catch (YAML::Exception const& e) { - std::cerr << fileName << ": " << e.what() << std::endl; - throw std::runtime_error("Error while parsing easi model file."); +Component* YAMLParser::parse(const std::string& fileName) { + Component* root; + try { + const auto lastFileName = m_currentFileName; + const auto lastPath = fs::path(lastFileName); + const auto nextPath = fs::path(fileName); + const auto loadFileName = [&]() { + if (nextPath.is_relative()) { + // remove file + return lastPath.parent_path() / nextPath; + } else { + return nextPath; + } + }(); + if (fs::exists(loadFileName)) { + m_currentFileName = fs::canonical(loadFileName); + } else if (fs::exists(nextPath)) { + m_currentFileName = fs::canonical(nextPath); + } else { + m_currentFileName = nextPath; } - - return root; + m_fileNames.insert(m_currentFileName); + YAML::Node config = YAML::LoadFile(m_currentFileName); + root = parse(config, m_in); + m_currentFileName = lastFileName; + } catch (const YAML::Exception& e) { + std::cerr << fileName << ": " << e.what() << std::endl; + throw std::runtime_error("Error while parsing easi model file."); + } + + return root; } -Component* YAMLParser::parse(YAML::Node const& node, std::set const& in) { - auto creator = m_creators.find(node.Tag()); - - if (creator == m_creators.end()) { - throw std::invalid_argument("Unknown tag " + node.Tag()); - } - - Component* component = nullptr; - try { - component = creator->second(node, in, this); - } catch (std::invalid_argument const& e) { - std::stringstream ss; - ss << e.what() << std::endl << node; - throw YAML::Exception(node.Mark(), ss.str()); - } - return component; +Component* YAMLParser::parse(const YAML::Node& node, const std::set& in) { + auto creator = m_creators.find(node.Tag()); + + if (creator == m_creators.end()) { + throw std::invalid_argument("Unknown tag " + node.Tag()); + } + + Component* component = nullptr; + try { + component = creator->second(node, in, this); + } catch (const std::invalid_argument& e) { + std::stringstream ss; + ss << e.what() << std::endl << node; + throw YAML::Exception(node.Mark(), ss.str()); + } + return component; } std::vector YAMLParser::getFileNameList() { - return std::vector(m_fileNames.begin(), m_fileNames.end()); + return std::vector(m_fileNames.begin(), m_fileNames.end()); } } // namespace easi - diff --git a/src/component/ASAGI.cpp b/src/component/ASAGI.cpp index 866ed84..a3fe85d 100644 --- a/src/component/ASAGI.cpp +++ b/src/component/ASAGI.cpp @@ -1,4 +1,5 @@ #include "easi/component/ASAGI.h" + #include "easi/util/Print.h" #include @@ -9,90 +10,92 @@ namespace easi { -bool ASAGI::accept(int, Slice const& x) const { - bool acc = true; - for (unsigned d = 0; d < m_grid->getDimensions(); ++d) { - acc = acc && (x(d) >= m_min[d]) && (x(d) <= m_max[d]); - } - return acc; +bool ASAGI::accept(int, const Slice& x) const { + bool acc = true; + for (unsigned d = 0; d < m_grid->getDimensions(); ++d) { + acc = acc && (x(d) >= m_min[d]) && (x(d) <= m_max[d]); + } + return acc; } -void ASAGI::setGrid(std::set const& in, std::vector const& parameters, - asagi::Grid* grid, unsigned numberOfThreads) { - setIn(in); - if (dimDomain() != grid->getDimensions()) { - std::ostringstream os; - os << "ASAGI requires " << grid->getDimensions() << "D input (got "; - printWithSeparator(in, os); - os << ")."; - throw std::invalid_argument(addFileReference(os.str())); - } - if (dimDomain() > MaxDimensions) { - throw std::runtime_error(addFileReference("Unsupported number of dimensions for ASAGI.")); - } +void ASAGI::setGrid(const std::set& in, + const std::vector& parameters, + asagi::Grid* grid, + unsigned numberOfThreads) { + setIn(in); + if (dimDomain() != grid->getDimensions()) { + std::ostringstream os; + os << "ASAGI requires " << grid->getDimensions() << "D input (got "; + printWithSeparator(in, os); + os << ")."; + throw std::invalid_argument(addFileReference(os.str())); + } + if (dimDomain() > MaxDimensions) { + throw std::runtime_error(addFileReference("Unsupported number of dimensions for ASAGI.")); + } - std::set out; - out.insert(parameters.begin(), parameters.end()); - setOut(out); - m_numValues = grid->getVarSize() / sizeof(float); - if (dimCodomain() != m_numValues) { - std::ostringstream os; - os << "ASAGI supplies " << m_numValues << "D output (got "; - printWithSeparator(out, os); - os << ")."; - throw std::invalid_argument(addFileReference(os.str())); - } + std::set out; + out.insert(parameters.begin(), parameters.end()); + setOut(out); + m_numValues = grid->getVarSize() / sizeof(float); + if (dimCodomain() != m_numValues) { + std::ostringstream os; + os << "ASAGI supplies " << m_numValues << "D output (got "; + printWithSeparator(out, os); + os << ")."; + throw std::invalid_argument(addFileReference(os.str())); + } - delete m_grid; - m_grid = grid; - m_numberOfThreads = numberOfThreads; + delete m_grid; + m_grid = grid; + m_numberOfThreads = numberOfThreads; - for (unsigned d = 0; d < grid->getDimensions(); ++d) { - m_min[d] = grid->getMin(d); - m_max[d] = grid->getMax(d); - m_delta[d] = grid->getDelta(d); - m_deltaInv[d] = 1.0 / m_delta[d]; - } + for (unsigned d = 0; d < grid->getDimensions(); ++d) { + m_min[d] = grid->getMin(d); + m_max[d] = grid->getMax(d); + m_delta[d] = grid->getDelta(d); + m_deltaInv[d] = 1.0 / m_delta[d]; + } - delete[] m_permutation; - m_permutation = new unsigned[m_numValues]; - unsigned* perm = m_permutation; - for (auto const& p : parameters) { - auto it = std::find(out.begin(), out.end(), p); - *perm++ = std::distance(out.begin(), it); - } + delete[] m_permutation; + m_permutation = new unsigned[m_numValues]; + unsigned* perm = m_permutation; + for (const auto& p : parameters) { + auto it = std::find(out.begin(), out.end(), p); + *perm++ = std::distance(out.begin(), it); + } } -void ASAGI::getNearestNeighbour(Slice const& x, double* buffer) { - double pos[MaxDimensions]; - float* bufferSP = reinterpret_cast(buffer); - for (unsigned d = 0; d < m_grid->getDimensions(); ++d) { - pos[d] = x(d); - } - m_grid->getBuf(bufferSP, pos); - for (int j = m_numValues - 1; j >= 0; --j) { - buffer[j] = static_cast(bufferSP[j]); - } +void ASAGI::getNearestNeighbour(const Slice& x, double* buffer) { + double pos[MaxDimensions]; + float* bufferSP = reinterpret_cast(buffer); + for (unsigned d = 0; d < m_grid->getDimensions(); ++d) { + pos[d] = x(d); + } + m_grid->getBuf(bufferSP, pos); + for (int j = m_numValues - 1; j >= 0; --j) { + buffer[j] = static_cast(bufferSP[j]); + } } -void ASAGI::getNeighbours(Slice const& x, double* weights, double* buffer) { - double lowPos[MaxDimensions]; +void ASAGI::getNeighbours(const Slice& x, double* weights, double* buffer) { + double lowPos[MaxDimensions]; + for (unsigned d = 0; d < m_grid->getDimensions(); ++d) { + lowPos[d] = m_min[d] + std::floor((x(d) - m_min[d]) * m_deltaInv[d]) * m_delta[d]; + weights[d] = (x(d) - lowPos[d]) * m_deltaInv[d]; + } + + double pos[MaxDimensions]; + for (unsigned i = 0; i < (1u << m_grid->getDimensions()); ++i) { + float* bufferSP = reinterpret_cast(buffer + i * m_numValues); for (unsigned d = 0; d < m_grid->getDimensions(); ++d) { - lowPos[d] = m_min[d] + std::floor((x(d) - m_min[d]) * m_deltaInv[d]) * m_delta[d]; - weights[d] = (x(d) - lowPos[d]) * m_deltaInv[d]; + pos[d] = std::min(lowPos[d] + ((i & (1 << d)) >> d) * m_delta[d], m_max[d]); } - - double pos[MaxDimensions]; - for (unsigned i = 0; i < (1u << m_grid->getDimensions()); ++i) { - float* bufferSP = reinterpret_cast(buffer + i * m_numValues); - for (unsigned d = 0; d < m_grid->getDimensions(); ++d) { - pos[d] = std::min(lowPos[d] + ((i & (1 << d)) >> d) * m_delta[d], m_max[d]); - } - m_grid->getBuf(bufferSP, pos); - for (int j = m_numValues - 1; j >= 0; --j) { - buffer[i * m_numValues + j] = static_cast(bufferSP[j]); - } + m_grid->getBuf(bufferSP, pos); + for (int j = m_numValues - 1; j >= 0; --j) { + buffer[i * m_numValues + j] = static_cast(bufferSP[j]); } + } } } // namespace easi diff --git a/src/component/AffineMap.cpp b/src/component/AffineMap.cpp index 79642f8..4a84805 100644 --- a/src/component/AffineMap.cpp +++ b/src/component/AffineMap.cpp @@ -7,59 +7,60 @@ namespace easi { Matrix AffineMap::map(Matrix& x) { - Matrix y = x * m_matrix; - for (unsigned i = 0; i < y.rows(); ++i) { - for (unsigned j = 0; j < y.cols(); ++j) { - y(i, j) += m_translation(j); - } + Matrix y = x * m_matrix; + for (unsigned i = 0; i < y.rows(); ++i) { + for (unsigned j = 0; j < y.cols(); ++j) { + y(i, j) += m_translation(j); } - return y; + } + return y; } -void AffineMap::setMap(std::set const& in, Transformation const& matrix, - Translation const& translation) { - if (matrix.size() != translation.size()) { - throw std::invalid_argument( - addFileReference("Matrix and translation must have the same size in an affine map.")); - } +void AffineMap::setMap(const std::set& in, + const Transformation& matrix, + const Translation& translation) { + if (matrix.size() != translation.size()) { + throw std::invalid_argument( + addFileReference("Matrix and translation must have the same size in an affine map.")); + } - setIn(in); + setIn(in); - std::set out; - unsigned nCoeffs = std::numeric_limits::max(); - for (auto const& kv : matrix) { - out.insert(kv.first); - if (nCoeffs != std::numeric_limits::max() && kv.second.size() != nCoeffs) { - throw std::invalid_argument( - addFileReference("The matrix in a affine map must have the same number of " - "coefficients for each entry.")); - } - nCoeffs = kv.second.size(); + std::set out; + unsigned nCoeffs = std::numeric_limits::max(); + for (const auto& kv : matrix) { + out.insert(kv.first); + if (nCoeffs != std::numeric_limits::max() && kv.second.size() != nCoeffs) { + throw std::invalid_argument( + addFileReference("The matrix in a affine map must have the same number of " + "coefficients for each entry.")); } - setOut(out); + nCoeffs = kv.second.size(); + } + setOut(out); - if (nCoeffs != dimDomain()) { - throw std::invalid_argument(addFileReference( - "Number of matrix entries does not match number of input parameters.")); - } + if (nCoeffs != dimDomain()) { + throw std::invalid_argument( + addFileReference("Number of matrix entries does not match number of input parameters.")); + } - m_matrix.reallocate(dimDomain(), dimCodomain()); - m_translation.reallocate(dimCodomain()); - - unsigned col = 0; - for (auto const& kv : matrix) { - unsigned row = 0; - for (auto const& v : kv.second) { - m_matrix(row, col) = v; - ++row; - } - ++col; - } + m_matrix.reallocate(dimDomain(), dimCodomain()); + m_translation.reallocate(dimCodomain()); + unsigned col = 0; + for (const auto& kv : matrix) { unsigned row = 0; - for (auto const& kv : translation) { - m_translation(row++) = kv.second; + for (const auto& v : kv.second) { + m_matrix(row, col) = v; + ++row; } + ++col; + } + + unsigned row = 0; + for (const auto& kv : translation) { + m_translation(row++) = kv.second; + } } } // namespace easi diff --git a/src/component/AndersonianStress.cpp b/src/component/AndersonianStress.cpp index 52f06c3..d301601 100644 --- a/src/component/AndersonianStress.cpp +++ b/src/component/AndersonianStress.cpp @@ -6,53 +6,53 @@ namespace easi { // COMPUTE NORMALIZED STRESS FOLLOWING THE METHOD OF Ulrich et al. (2018) void AndersonianStress::evaluate() { - double const pi = 3.141592653589793; - // most favorable direction (A4, AM2003) - double Phi = pi / 4.0 - 0.5 * atan(i.mu_s); - double SHmax_rad = i.SH_max * pi / 180.0; - double s2 = sin(2.0 * Phi); - double c2 = cos(2.0 * Phi); - double alpha = (2.0 * i.s2ratio - 1.0) / 3.0; - // we assume that szz is the effectiveConfiningStress = sii/3 which is not necessarily true, - // but then we scale the stress to get b_zz = szz - double effectiveConfiningStress = std::fabs(i.sig_zz); - double R = 1.0 / (1.0 + i.S); - double ds = (i.mu_d * effectiveConfiningStress + - R * (i.cohesion + (i.mu_s - i.mu_d) * effectiveConfiningStress)) / - (s2 + i.mu_d * (alpha + c2) + R * (i.mu_s - i.mu_d) * (alpha + c2)); - double sm = effectiveConfiningStress - alpha * ds; - // sii are all positive - double s11 = sm + ds; - double s22 = sm - ds + 2.0 * ds * i.s2ratio; - double s33 = sm - ds; - double S_hmax, S_hmin, S_v; - if (i.S_v == 1) { - S_hmax = s22; - S_hmin = s33; - S_v = s11; + const double pi = 3.141592653589793; + // most favorable direction (A4, AM2003) + double Phi = pi / 4.0 - 0.5 * atan(i.mu_s); + double SHmax_rad = i.SH_max * pi / 180.0; + double s2 = sin(2.0 * Phi); + double c2 = cos(2.0 * Phi); + double alpha = (2.0 * i.s2ratio - 1.0) / 3.0; + // we assume that szz is the effectiveConfiningStress = sii/3 which is not necessarily true, + // but then we scale the stress to get b_zz = szz + double effectiveConfiningStress = std::fabs(i.sig_zz); + double R = 1.0 / (1.0 + i.S); + double ds = (i.mu_d * effectiveConfiningStress + + R * (i.cohesion + (i.mu_s - i.mu_d) * effectiveConfiningStress)) / + (s2 + i.mu_d * (alpha + c2) + R * (i.mu_s - i.mu_d) * (alpha + c2)); + double sm = effectiveConfiningStress - alpha * ds; + // sii are all positive + double s11 = sm + ds; + double s22 = sm - ds + 2.0 * ds * i.s2ratio; + double s33 = sm - ds; + double S_hmax, S_hmin, S_v; + if (i.S_v == 1) { + S_hmax = s22; + S_hmin = s33; + S_v = s11; + } else { + if (i.S_v == 2) { + S_hmax = s11; + S_hmin = s33; + S_v = s22; } else { - if (i.S_v == 2) { - S_hmax = s11; - S_hmin = s33; - S_v = s22; - } else { - S_hmax = s11; - S_hmin = s22; - S_v = s33; - } + S_hmax = s11; + S_hmin = s22; + S_v = s33; } + } - double cs = cos(SHmax_rad); - double ss = sin(SHmax_rad); + double cs = cos(SHmax_rad); + double ss = sin(SHmax_rad); - // minus signs added to fall back to SeisSol convention (compressive stress<0) + // minus signs added to fall back to SeisSol convention (compressive stress<0) - o.b_xx = -(cs * cs * S_hmin + ss * ss * S_hmax) * effectiveConfiningStress / S_v; - o.b_xy = -cs * ss * (S_hmax - S_hmin) * effectiveConfiningStress / S_v; - o.b_xz = 0; - o.b_yy = -(ss * ss * S_hmin + cs * cs * S_hmax) * effectiveConfiningStress / S_v; - o.b_yz = 0; - o.b_zz = -effectiveConfiningStress; + o.b_xx = -(cs * cs * S_hmin + ss * ss * S_hmax) * effectiveConfiningStress / S_v; + o.b_xy = -cs * ss * (S_hmax - S_hmin) * effectiveConfiningStress / S_v; + o.b_xz = 0; + o.b_yy = -(ss * ss * S_hmin + cs * cs * S_hmax) * effectiveConfiningStress / S_v; + o.b_yz = 0; + o.b_zz = -effectiveConfiningStress; } } // namespace easi diff --git a/src/component/Composite.cpp b/src/component/Composite.cpp index 235c3bf..987119f 100644 --- a/src/component/Composite.cpp +++ b/src/component/Composite.cpp @@ -1,4 +1,5 @@ #include "easi/component/Composite.h" + #include "easi/Query.h" #include "easi/ResultAdapter.h" #include "easi/util/Print.h" @@ -15,147 +16,150 @@ namespace easi { Composite::~Composite() { - std::for_each(begin(), end(), [](Component*& component) { delete component; }); + std::for_each(begin(), end(), [](Component*& component) { delete component; }); } void Composite::add(Component* component) { - if (out() != component->in()) { - std::ostringstream os; - os << "The input parameters of a component ("; - printWithSeparator(component->in(), os); - os << ") added to a composite are incompatible (should be "; - printWithSeparator(out(), os); - os << ")."; - throw std::invalid_argument(addFileReference(os.str())); - } - - m_components.push_back(component); + if (out() != component->in()) { + std::ostringstream os; + os << "The input parameters of a component ("; + printWithSeparator(component->in(), os); + os << ") added to a composite are incompatible (should be "; + printWithSeparator(out(), os); + os << ")."; + throw std::invalid_argument(addFileReference(os.str())); + } + + m_components.push_back(component); } void Composite::evaluate(Query& query, ResultAdapter& result) { - // Map dimensions - Matrix y = map(query.x); - - // Find model for each point - unsigned nComponents = m_components.size(); - if (nComponents == 0) { - if (!result.isSubset(out())) { - throw std::invalid_argument(addFileReference(addMissingParameters( - "Component does not supply all required parameters.", result.parameters(), out()))); - } - unsigned col = 0; - for (std::string const& param : out()) { - result.set(param, query.index, y.colSlice(col)); - ++col; - } - } else if (nComponents == 1) { - if (query.numPoints() > 0) { - if (!m_components[0]->acceptAlways()) { - for (unsigned i = 0; i < query.numPoints(); ++i) { - if (!m_components[0]->accept(query.group(i), y.rowSlice(i))) { - couldNotFindModelError(query.group(i), y.rowSlice(i)); - } - } - } - query.x = y; - m_components[0]->evaluate(query, result); - } - } else { - unsigned* model = new unsigned[query.numPoints() + nComponents]; - unsigned* modelCount = model + query.numPoints(); - std::for_each(modelCount, modelCount + nComponents, [](unsigned& x) { x = 0; }); + // Map dimensions + Matrix y = map(query.x); + + // Find model for each point + unsigned nComponents = m_components.size(); + if (nComponents == 0) { + if (!result.isSubset(out())) { + throw std::invalid_argument(addFileReference(addMissingParameters( + "Component does not supply all required parameters.", result.parameters(), out()))); + } + unsigned col = 0; + for (const std::string& param : out()) { + result.set(param, query.index, y.colSlice(col)); + ++col; + } + } else if (nComponents == 1) { + if (query.numPoints() > 0) { + if (!m_components[0]->acceptAlways()) { for (unsigned i = 0; i < query.numPoints(); ++i) { - unsigned c = 0; - for (; c < nComponents; ++c) { - if (m_components[c]->accept(query.group(i), y.rowSlice(i))) { - model[i] = c; - ++modelCount[c]; - break; - } - } - if (c == nComponents) { - couldNotFindModelError(query.group(i), y.rowSlice(i)); - } + if (!m_components[0]->accept(query.group(i), y.rowSlice(i))) { + couldNotFindModelError(query.group(i), y.rowSlice(i)); + } } - - // Allocate queries - void* queriesMemory = operator new[](nComponents * sizeof(Query)); - Query* queries = static_cast(queriesMemory); - for (unsigned c = 0; c < nComponents; ++c) { - new (&queries[c]) Query(modelCount[c], dimCodomain(), false); + } + query.x = y; + m_components[0]->evaluate(query, result); + } + } else { + unsigned* model = new unsigned[query.numPoints() + nComponents]; + unsigned* modelCount = model + query.numPoints(); + std::for_each(modelCount, modelCount + nComponents, [](unsigned& x) { x = 0; }); + for (unsigned i = 0; i < query.numPoints(); ++i) { + unsigned c = 0; + for (; c < nComponents; ++c) { + if (m_components[c]->accept(query.group(i), y.rowSlice(i))) { + model[i] = c; + ++modelCount[c]; + break; } + } + if (c == nComponents) { + couldNotFindModelError(query.group(i), y.rowSlice(i)); + } + } - // Copy points to queries - std::for_each(modelCount, modelCount + nComponents, [](unsigned& x) { x = 0; }); - for (unsigned i = 0; i < query.numPoints(); ++i) { - Query& target = queries[model[i]]; - unsigned& mc = modelCount[model[i]]; - - target.group(mc) = query.group(i); - for (unsigned d = 0; d < dimCodomain(); ++d) { - target.x(mc, d) = y(i, d); - } - target.index(mc) = query.index(i); - ++mc; - } + // Allocate queries + void* queriesMemory = operator new[](nComponents * sizeof(Query)); + Query* queries = static_cast(queriesMemory); + for (unsigned c = 0; c < nComponents; ++c) { + new (&queries[c]) Query(modelCount[c], dimCodomain(), false); + } - // Cleanup query and temporary data - delete[] model; - y.clear(); - query.clear(); + // Copy points to queries + std::for_each(modelCount, modelCount + nComponents, [](unsigned& x) { x = 0; }); + for (unsigned i = 0; i < query.numPoints(); ++i) { + Query& target = queries[model[i]]; + unsigned& mc = modelCount[model[i]]; + + target.group(mc) = query.group(i); + for (unsigned d = 0; d < dimCodomain(); ++d) { + target.x(mc, d) = y(i, d); + } + target.index(mc) = query.index(i); + ++mc; + } - // Evaluate submodels - for (unsigned c = 0; c < nComponents; ++c) { - if (queries[c].numPoints() > 0) { - m_components[c]->evaluate(queries[c], result); - } - } + // Cleanup query and temporary data + delete[] model; + y.clear(); + query.clear(); - // Delete queries - for (unsigned c = 0; c < nComponents; ++c) { - queries[c].~Query(); - } - operator delete[](queriesMemory); + // Evaluate submodels + for (unsigned c = 0; c < nComponents; ++c) { + if (queries[c].numPoints() > 0) { + m_components[c]->evaluate(queries[c], result); + } } -} -void Composite::couldNotFindModelError(int group, Slice const& y) { - std::stringstream ss; - ss << "Could not find model for point [ "; - for (unsigned d = 0; d < y.size(); ++d) { - ss << y(d) << " "; + // Delete queries + for (unsigned c = 0; c < nComponents; ++c) { + queries[c].~Query(); } - ss << "] in group " << group << "."; - throw std::runtime_error(addFileReference(ss.str())); + operator delete[](queriesMemory); + } +} + +void Composite::couldNotFindModelError(int group, const Slice& y) { + std::stringstream ss; + ss << "Could not find model for point [ "; + for (unsigned d = 0; d < y.size(); ++d) { + ss << y(d) << " "; + } + ss << "] in group " << group << "."; + throw std::runtime_error(addFileReference(ss.str())); } -std::string Composite::addMissingParameters(std::string const& what_arg, +std::string Composite::addMissingParameters(const std::string& what_arg, std::set expected, std::set supplied) { - std::set missing; - std::set_difference(expected.begin(), expected.end(), supplied.begin(), supplied.end(), - std::inserter(missing, missing.begin())); - - std::stringstream s; - s << what_arg << " Missing: {"; - printWithSeparator(missing, s); - s << "}."; - return s.str(); + std::set missing; + std::set_difference(expected.begin(), + expected.end(), + supplied.begin(), + supplied.end(), + std::inserter(missing, missing.begin())); + + std::stringstream s; + s << what_arg << " Missing: {"; + printWithSeparator(missing, s); + s << "}."; + return s.str(); } std::set Composite::suppliedParameters() { - if (m_components.empty()) { - return Component::suppliedParameters(); - } - - return std::accumulate(begin(), end(), std::set(), - [](std::set& a, Component*& b) { - std::set supplied; - auto c = b->suppliedParameters(); - std::set_union(a.begin(), a.end(), c.begin(), c.end(), - std::inserter(supplied, supplied.begin())); - return supplied; - }); + if (m_components.empty()) { + return Component::suppliedParameters(); + } + + return std::accumulate( + begin(), end(), std::set(), [](std::set& a, Component*& b) { + std::set supplied; + auto c = b->suppliedParameters(); + std::set_union( + a.begin(), a.end(), c.begin(), c.end(), std::inserter(supplied, supplied.begin())); + return supplied; + }); } } // namespace easi diff --git a/src/component/ConstantMap.cpp b/src/component/ConstantMap.cpp index a859836..aad85e3 100644 --- a/src/component/ConstantMap.cpp +++ b/src/component/ConstantMap.cpp @@ -7,28 +7,28 @@ namespace easi { Matrix ConstantMap::map(Matrix& x) { - Matrix y(x.rows(), dimCodomain()); - auto j = 0; - for (auto const& value : m_values) { - for (unsigned i = 0; i < x.rows(); ++i) { - y(i, j) = value; - } - ++j; + Matrix y(x.rows(), dimCodomain()); + auto j = 0; + for (const auto& value : m_values) { + for (unsigned i = 0; i < x.rows(); ++i) { + y(i, j) = value; } + ++j; + } - return y; + return y; } -void ConstantMap::setMap(OutMap const& outMap) { - m_values.clear(); - std::set out; - for (auto const& kv : outMap) { - out.insert(kv.first); - m_values.push_back(kv.second); - } - setOut(out); +void ConstantMap::setMap(const OutMap& outMap) { + m_values.clear(); + std::set out; + for (const auto& kv : outMap) { + out.insert(kv.first); + m_values.push_back(kv.second); + } + setOut(out); - assert(dimCodomain() == m_values.size()); + assert(dimCodomain() == m_values.size()); } } // namespace easi diff --git a/src/component/DomainFilter.cpp b/src/component/DomainFilter.cpp index c78793f..144dcef 100644 --- a/src/component/DomainFilter.cpp +++ b/src/component/DomainFilter.cpp @@ -1,4 +1,5 @@ #include "easi/component/DomainFilter.h" + #include "easi/util/Slice.h" #include @@ -6,43 +7,43 @@ namespace easi { -bool AxisAlignedCuboidalDomainFilter::accept(int, Slice const& x) const { - bool acc = true; - for (unsigned d = 0; d < dimDomain(); ++d) { - acc = acc && (x(d) >= m_limits[d].first) && (x(d) <= m_limits[d].second); - } - return acc; +bool AxisAlignedCuboidalDomainFilter::accept(int, const Slice& x) const { + bool acc = true; + for (unsigned d = 0; d < dimDomain(); ++d) { + acc = acc && (x(d) >= m_limits[d].first) && (x(d) <= m_limits[d].second); + } + return acc; } -void AxisAlignedCuboidalDomainFilter::setDomain(Limits const& limits) { - m_limits.clear(); - std::set inout; - for (auto const& kv : limits) { - inout.insert(kv.first); - m_limits.push_back(kv.second); - } - setInOut(inout); +void AxisAlignedCuboidalDomainFilter::setDomain(const Limits& limits) { + m_limits.clear(); + std::set inout; + for (const auto& kv : limits) { + inout.insert(kv.first); + m_limits.push_back(kv.second); + } + setInOut(inout); } -bool SphericalDomainFilter::accept(int, Slice const& x) const { - double distance2 = 0.0; - for (unsigned d = 0; d < dimDomain(); ++d) { - double diff = x(d) - m_centre(d); - distance2 += diff * diff; - } - return distance2 <= m_radius2; +bool SphericalDomainFilter::accept(int, const Slice& x) const { + double distance2 = 0.0; + for (unsigned d = 0; d < dimDomain(); ++d) { + double diff = x(d) - m_centre(d); + distance2 += diff * diff; + } + return distance2 <= m_radius2; } -void SphericalDomainFilter::setDomain(double radius, Centre const& centre) { - m_radius2 = radius * radius; - m_centre.reallocate(centre.size()); - std::set inout; - unsigned d = 0; - for (auto const& kv : centre) { - inout.insert(kv.first); - m_centre(d++) = kv.second; - } - setInOut(inout); +void SphericalDomainFilter::setDomain(double radius, const Centre& centre) { + m_radius2 = radius * radius; + m_centre.reallocate(centre.size()); + std::set inout; + unsigned d = 0; + for (const auto& kv : centre) { + inout.insert(kv.first); + m_centre(d++) = kv.second; + } + setInOut(inout); } } // namespace easi diff --git a/src/component/EvalModel.cpp b/src/component/EvalModel.cpp index 959eff9..1c79186 100644 --- a/src/component/EvalModel.cpp +++ b/src/component/EvalModel.cpp @@ -1,4 +1,5 @@ #include "easi/component/EvalModel.h" + #include "easi/Query.h" #include "easi/ResultAdapter.h" #include "easi/component/Composite.h" @@ -8,25 +9,25 @@ namespace easi { void EvalModel::evaluate(Query& query, ResultAdapter& result) { - Query subQuery = query.shallowCopy(); - - // create a new index vector here (do not override the old one for the Composite::evaluate later) - Vector newIndices(subQuery.x.rows()); - for (unsigned i = 0; i < subQuery.x.rows(); ++i) { - newIndices(i) = i; - } - subQuery.index = newIndices; - - Matrix y(subQuery.x.rows(), dimCodomain()); - ArraysAdapter<> adapter; - unsigned col = 0; - for (auto const& o : out()) { - adapter.addBindingPoint(o, &y(0, col++)); - } - m_model->evaluate(subQuery, adapter); - query.x = y; - - Composite::evaluate(query, result); + Query subQuery = query.shallowCopy(); + + // create a new index vector here (do not override the old one for the Composite::evaluate later) + Vector newIndices(subQuery.x.rows()); + for (unsigned i = 0; i < subQuery.x.rows(); ++i) { + newIndices(i) = i; + } + subQuery.index = newIndices; + + Matrix y(subQuery.x.rows(), dimCodomain()); + ArraysAdapter<> adapter; + unsigned col = 0; + for (const auto& o : out()) { + adapter.addBindingPoint(o, &y(0, col++)); + } + m_model->evaluate(subQuery, adapter); + query.x = y; + + Composite::evaluate(query, result); } } // namespace easi diff --git a/src/component/LayeredModelBuilder.cpp b/src/component/LayeredModelBuilder.cpp index e55f5a1..3dad4c8 100644 --- a/src/component/LayeredModelBuilder.cpp +++ b/src/component/LayeredModelBuilder.cpp @@ -1,4 +1,5 @@ #include "easi/component/LayeredModelBuilder.h" + #include "easi/component/DomainFilter.h" #include "easi/component/Map.h" #include "easi/component/PolynomialMap.h" @@ -17,116 +18,118 @@ namespace easi { class Component; -void LayeredModelBuilder::setInterpolationType(std::string const& interpolationType) { - std::string iType = interpolationType; - std::transform(iType.begin(), iType.end(), iType.begin(), ::tolower); - if (iType == "lower") { - setInterpolationType(Lower); - } else if (iType == "upper") { - setInterpolationType(Upper); - } else if (iType == "linear") { - setInterpolationType(Linear); - } else { - std::stringstream ss; - ss << "Invalid interpolation type " << interpolationType << "."; - throw std::invalid_argument(ss.str()); - } +void LayeredModelBuilder::setInterpolationType(const std::string& interpolationType) { + std::string iType = interpolationType; + std::transform(iType.begin(), iType.end(), iType.begin(), ::tolower); + if (iType == "lower") { + setInterpolationType(Lower); + } else if (iType == "upper") { + setInterpolationType(Upper); + } else if (iType == "linear") { + setInterpolationType(Linear); + } else { + std::stringstream ss; + ss << "Invalid interpolation type " << interpolationType << "."; + throw std::invalid_argument(ss.str()); + } } -void LayeredModelBuilder::setNodes(Nodes const& nodes) { - auto nParams = nodes.begin()->second.size(); - for (Nodes::const_iterator it = nodes.begin(); it != nodes.end(); ++it) { - if (it->second.size() != nParams) { - throw std::invalid_argument("The number of parameters must be equal for every node."); - } +void LayeredModelBuilder::setNodes(const Nodes& nodes) { + auto nParams = nodes.begin()->second.size(); + for (Nodes::const_iterator it = nodes.begin(); it != nodes.end(); ++it) { + if (it->second.size() != nParams) { + throw std::invalid_argument("The number of parameters must be equal for every node."); } - m_nodes = nodes; + } + m_nodes = nodes; } Component* LayeredModelBuilder::getResult() { - for (auto it = m_nodes.begin(); it != m_nodes.end(); ++it) { - if (std::isnan(it->first)) { - throw std::invalid_argument("Not a number nodes are forbidden."); - } else if (m_interpolationType == Linear && std::isinf(it->first)) { - throw std::invalid_argument("Infinite nodes are forbidden for interpolation = linear."); - } - } - - std::optional previous = std::nullopt; - for (const auto& node : m_nodes) { - m_map->add(createModel(previous, node, m_map->out())); - previous.emplace(node); + for (auto it = m_nodes.begin(); it != m_nodes.end(); ++it) { + if (std::isnan(it->first)) { + throw std::invalid_argument("Not a number nodes are forbidden."); + } else if (m_interpolationType == Linear && std::isinf(it->first)) { + throw std::invalid_argument("Infinite nodes are forbidden for interpolation = linear."); } + } - m_map->add(createModel(previous, std::nullopt, m_map->out())); + std::optional previous = std::nullopt; + for (const auto& node : m_nodes) { + m_map->add(createModel(previous, node, m_map->out())); + previous.emplace(node); + } - return m_map; + m_map->add(createModel(previous, std::nullopt, m_map->out())); + + return m_map; } Component* LayeredModelBuilder::createModel(const std::optional& lower, const std::optional& upper, - std::set const& in) { - if (in.size() != 1) { - std::ostringstream os; - os << "Layered model requires 1D input (got "; - printWithSeparator(in, os); - os << ")."; - throw std::invalid_argument(os.str()); - } - - enum InterpolationType interpolationType; - if (!lower.has_value()) { - interpolationType = Upper; - } else if (!upper.has_value()) { - interpolationType = Lower; - } else { - interpolationType = m_interpolationType; - } - - const double lowerLimit = lower.has_value() ? lower.value().first : -std::numeric_limits::infinity(); - const double upperLimit = upper.has_value() ? upper.value().first : std::numeric_limits::infinity(); - auto nParams = lower.has_value() ? lower.value().second.size() : upper.value().second.size(); - - if (m_parameters.size() != nParams) { - throw std::invalid_argument("Number of parameters must match number of node entries."); - } - - unsigned nTerms = 1; - if (interpolationType == Linear) { - nTerms = 2; + const std::set& in) { + if (in.size() != 1) { + std::ostringstream os; + os << "Layered model requires 1D input (got "; + printWithSeparator(in, os); + os << ")."; + throw std::invalid_argument(os.str()); + } + + enum InterpolationType interpolationType; + if (!lower.has_value()) { + interpolationType = Upper; + } else if (!upper.has_value()) { + interpolationType = Lower; + } else { + interpolationType = m_interpolationType; + } + + const double lowerLimit = + lower.has_value() ? lower.value().first : -std::numeric_limits::infinity(); + const double upperLimit = + upper.has_value() ? upper.value().first : std::numeric_limits::infinity(); + auto nParams = lower.has_value() ? lower.value().second.size() : upper.value().second.size(); + + if (m_parameters.size() != nParams) { + throw std::invalid_argument("Number of parameters must match number of node entries."); + } + + unsigned nTerms = 1; + if (interpolationType == Linear) { + nTerms = 2; + } + PolynomialMap::OutMap coeffs; + for (const auto& param : m_parameters) { + coeffs[param].resize(nTerms); + } + if (interpolationType == Linear) { + for (unsigned i = 0; i < nParams; ++i) { + coeffs[m_parameters[i]][0] = (lower.value().second[i] - upper.value().second[i]) / + (lower.value().first - upper.value().first); + coeffs[m_parameters[i]][1] = (-upper.value().first * lower.value().second[i] + + lower.value().first * upper.value().second[i]) / + (lower.value().first - upper.value().first); } - PolynomialMap::OutMap coeffs; - for (auto const& param : m_parameters) { - coeffs[param].resize(nTerms); + } else if (interpolationType == Upper) { + for (unsigned i = 0; i < nParams; ++i) { + coeffs[m_parameters[i]][0] = upper.value().second[i]; } - if (interpolationType == Linear) { - for (unsigned i = 0; i < nParams; ++i) { - coeffs[m_parameters[i]][0] = - (lower.value().second[i] - upper.value().second[i]) / (lower.value().first - upper.value().first); - coeffs[m_parameters[i]][1] = - (-upper.value().first * lower.value().second[i] + lower.value().first * upper.value().second[i]) / - (lower.value().first - upper.value().first); - } - } else if (interpolationType == Upper) { - for (unsigned i = 0; i < nParams; ++i) { - coeffs[m_parameters[i]][0] = upper.value().second[i]; - } - } else { - for (unsigned i = 0; i < nParams; ++i) { - coeffs[m_parameters[i]][0] = lower.value().second[i]; - } + } else { + for (unsigned i = 0; i < nParams; ++i) { + coeffs[m_parameters[i]][0] = lower.value().second[i]; } + } - PolynomialMap* model = new PolynomialMap; - model->setMap(in, coeffs); + PolynomialMap* model = new PolynomialMap; + model->setMap(in, coeffs); - AxisAlignedCuboidalDomainFilter::Limits limits; - limits[*in.cbegin()] = std::pair(lowerLimit, upperLimit); - AxisAlignedCuboidalDomainFilter* domainFilter = new AxisAlignedCuboidalDomainFilter; - domainFilter->setDomain(limits); - domainFilter->add(model); + AxisAlignedCuboidalDomainFilter::Limits limits; + limits[*in.cbegin()] = std::pair(lowerLimit, upperLimit); + AxisAlignedCuboidalDomainFilter* domainFilter = new AxisAlignedCuboidalDomainFilter; + domainFilter->setDomain(limits); + domainFilter->add(model); - return domainFilter; + return domainFilter; } } // namespace easi diff --git a/src/component/LuaMap.cpp b/src/component/LuaMap.cpp index 2b2c82e..469cf1f 100644 --- a/src/component/LuaMap.cpp +++ b/src/component/LuaMap.cpp @@ -1,11 +1,12 @@ #include "easi/component/LuaMap.h" + #include #ifdef EASI_USE_LUA extern "C" { +#include #include #include -#include } #include #include @@ -24,163 +25,150 @@ namespace { static void loadLmathx(lua_State* L) { #if LUA_VERSION_NUM < 502 - lua_pushcfunction(L, luaopen_mathx); - lua_pushliteral(L, "mathx"); - lua_call(L, 1, 0); + lua_pushcfunction(L, luaopen_mathx); + lua_pushliteral(L, "mathx"); + lua_call(L, 1, 0); #else - luaL_requiref(L, "mathx", luaopen_mathx, 1); - lua_pop(L, 1); + luaL_requiref(L, "mathx", luaopen_mathx, 1); + lua_pop(L, 1); #endif } static std::string loadCodeLmathX() { - // cf. example code for mathx: for Lua 5.3 and upwards, we need to supplement the math table. - // (for 5.2 and lower, that's done automatically) + // cf. example code for mathx: for Lua 5.3 and upwards, we need to supplement the math table. + // (for 5.2 and lower, that's done automatically) #if LUA_VERSION_NUM < 503 - return ""; + return ""; #else - return "for fname,fval in pairs(mathx) do math[fname] = fval end;\n"; + return "for fname,fval in pairs(mathx) do math[fname] = fval end;\n"; #endif - return ""; + return ""; } -} +} // namespace #else namespace { -static void loadLmathx(lua_State* L) { -} +static void loadLmathx(lua_State* L) {} -static std::string loadCodeLmathX() { - return ""; -} -} +static std::string loadCodeLmathX() { return ""; } +} // namespace #endif namespace easi { double getField(lua_State* L, const std::string& key) { - lua_pushstring(L, key.data()); - lua_gettable(L, -2); - if (!lua_isnumber(L, -1)) { - std::cerr - << "Tried key " - << key - << " but it did not return a number." - << std::endl; - std::abort(); - } - const auto result = lua_tonumber(L, -1); - lua_pop(L, 1); - return result; + lua_pushstring(L, key.data()); + lua_gettable(L, -2); + if (!lua_isnumber(L, -1)) { + std::cerr << "Tried key " << key << " but it did not return a number." << std::endl; + std::abort(); + } + const auto result = lua_tonumber(L, -1); + lua_pop(L, 1); + return result; } -void LuaMap::executeLuaFunction(const Matrix& x, - Matrix& y) { +void LuaMap::executeLuaFunction(const Matrix& x, Matrix& y) { #ifdef _OPENMP - const auto numStates = omp_get_max_threads(); + const auto numStates = omp_get_max_threads(); #else - const auto numStates = 1; + const auto numStates = 1; #endif - if (luaStates.size() < numStates) { - luaStates.resize(numStates); - } + if (luaStates.size() < numStates) { + luaStates.resize(numStates); + } #ifdef _OPENMP #pragma omp parallel #endif - { + { #ifdef _OPENMP - auto& luaState = luaStates[omp_get_thread_num()]; + auto& luaState = luaStates[omp_get_thread_num()]; #else - auto& luaState = luaStates[0]; + auto& luaState = luaStates[0]; #endif - if (luaState == nullptr) { - luaState = luaL_newstate(); - luaL_openlibs(luaState); - - loadLmathx(luaState); - - const auto status = luaL_dostring(luaState, function.data()); - if (status != 0) { - std::cerr - << "Couldn't load script: " - << lua_tostring(luaState, -1); - std::abort(); - } - } - - // Save stack size - const auto top = lua_gettop(luaState); + if (luaState == nullptr) { + luaState = luaL_newstate(); + luaL_openlibs(luaState); + + loadLmathx(luaState); + + const auto status = luaL_dostring(luaState, function.data()); + if (status != 0) { + std::cerr << "Couldn't load script: " << lua_tostring(luaState, -1); + std::abort(); + } + } + + // Save stack size + const auto top = lua_gettop(luaState); #ifdef _OPENMP #pragma omp for #endif - for (unsigned row = 0; row < y.rows(); ++row) { - // Push function and arguments to stack - lua_getglobal(luaState, "f"); // the function - - // Add table as input: x holds coordinates - lua_newtable(luaState); - - for (int i = 0; i < x.cols(); ++i) { - // Support x[1] indexing - lua_pushnumber(luaState, i+1); - lua_pushnumber(luaState, x(row, i)); - lua_rawset(luaState, -3); - - // Support x["x"] indexing - lua_pushstring(luaState, idxToInputName[i].data()); - lua_pushnumber(luaState, x(row, i)); - lua_rawset(luaState, -3); - } - - if (lua_pcall(luaState, 1, 1, 0) != 0) { - std::cerr - << "Error running function f " - << lua_tostring(luaState, -1) - << " :::: f given by: " << function - << std::endl; - std::abort(); - } - - for (unsigned col = 0; col < y.cols(); ++col) { - y(row, col) = getField(luaState, idxToOutputName[col]); - } - - // Reset stack size to value before function call - // This should avoid stack overflows - lua_settop(luaState, top); - } + for (unsigned row = 0; row < y.rows(); ++row) { + // Push function and arguments to stack + lua_getglobal(luaState, "f"); // the function + + // Add table as input: x holds coordinates + lua_newtable(luaState); + + for (int i = 0; i < x.cols(); ++i) { + // Support x[1] indexing + lua_pushnumber(luaState, i + 1); + lua_pushnumber(luaState, x(row, i)); + lua_rawset(luaState, -3); + + // Support x["x"] indexing + lua_pushstring(luaState, idxToInputName[i].data()); + lua_pushnumber(luaState, x(row, i)); + lua_rawset(luaState, -3); + } + + if (lua_pcall(luaState, 1, 1, 0) != 0) { + std::cerr << "Error running function f " << lua_tostring(luaState, -1) + << " :::: f given by: " << function << std::endl; + std::abort(); + } + + for (unsigned col = 0; col < y.cols(); ++col) { + y(row, col) = getField(luaState, idxToOutputName[col]); + } + + // Reset stack size to value before function call + // This should avoid stack overflows + lua_settop(luaState, top); } + } } Matrix LuaMap::map(Matrix& x) { - assert(x.cols() == dimDomain()); + assert(x.cols() == dimDomain()); - Matrix y(x.rows(), dimCodomain()); - executeLuaFunction(x, y); - return y; + Matrix y(x.rows(), dimCodomain()); + executeLuaFunction(x, y); + return y; } void LuaMap::setMap(const std::set& in, const std::set& out, const std::string& newFunction) { - setIn(in); - setOut(out); - function = loadCodeLmathX() + newFunction; - for (const auto& i: in) { - idxToInputName.push_back(i); - } - for (const auto& o : out) { - idxToOutputName.push_back(o); - } + setIn(in); + setOut(out); + function = loadCodeLmathX() + newFunction; + for (const auto& i : in) { + idxToInputName.push_back(i); + } + for (const auto& o : out) { + idxToOutputName.push_back(o); + } } LuaMap::~LuaMap() { - for (auto* luaState : luaStates) { - lua_close(luaState); - } + for (auto* luaState : luaStates) { + lua_close(luaState); + } } } // namespace easi diff --git a/src/component/OptimalStress.cpp b/src/component/OptimalStress.cpp index d8c5efd..508dfce 100644 --- a/src/component/OptimalStress.cpp +++ b/src/component/OptimalStress.cpp @@ -6,83 +6,83 @@ namespace easi { // COMPUTE NORMALIZED STRESS FOLLOWING THE METHOD OF Ulrich et al. (2018) void OptimalStress::evaluate() { - double const pi = 3.141592653589793; - // most favorable direction (A4, AM2003) - double Phi = pi / 4.0 - 0.5 * atan(i.mu_s); - double strike_rad = i.strike * pi / 180.0; - double dip_rad = i.dip * pi / 180.0; - double rake_rad = i.rake * pi / 180.0; - double s2 = sin(2.0 * Phi); - double c2 = cos(2.0 * Phi); - double alpha = (2.0 * i.s2ratio - 1.0) / 3.0; - double effectiveConfiningStress = std::fabs(i.effectiveConfiningStress); + const double pi = 3.141592653589793; + // most favorable direction (A4, AM2003) + double Phi = pi / 4.0 - 0.5 * atan(i.mu_s); + double strike_rad = i.strike * pi / 180.0; + double dip_rad = i.dip * pi / 180.0; + double rake_rad = i.rake * pi / 180.0; + double s2 = sin(2.0 * Phi); + double c2 = cos(2.0 * Phi); + double alpha = (2.0 * i.s2ratio - 1.0) / 3.0; + double effectiveConfiningStress = std::fabs(i.effectiveConfiningStress); - double ds = (i.mu_d * effectiveConfiningStress + - i.R * (i.cohesion + (i.mu_s - i.mu_d) * effectiveConfiningStress)) / - (s2 + i.mu_d * (alpha + c2) + i.R * (i.mu_s - i.mu_d) * (alpha + c2)); - double sm = effectiveConfiningStress - alpha * ds; - // sii are all positive - double s11 = sm + ds; - double s22 = sm - ds + 2.0 * ds * i.s2ratio; - double s33 = sm - ds; + double ds = (i.mu_d * effectiveConfiningStress + + i.R * (i.cohesion + (i.mu_s - i.mu_d) * effectiveConfiningStress)) / + (s2 + i.mu_d * (alpha + c2) + i.R * (i.mu_s - i.mu_d) * (alpha + c2)); + double sm = effectiveConfiningStress - alpha * ds; + // sii are all positive + double s11 = sm + ds; + double s22 = sm - ds + 2.0 * ds * i.s2ratio; + double s33 = sm - ds; - double cd = cos(-Phi); - double sd = sin(-Phi); + double cd = cos(-Phi); + double sd = sin(-Phi); - double cr = cos(rake_rad); - double sr = sin(rake_rad); + double cr = cos(rake_rad); + double sr = sin(rake_rad); - double ci = cos(dip_rad); - double si = sin(dip_rad); + double ci = cos(dip_rad); + double si = sin(dip_rad); - double cs = cos(strike_rad); - double ss = sin(strike_rad); + double cs = cos(strike_rad); + double ss = sin(strike_rad); - o.b_xx = -((ci * ci * s11 * sr * sr + s33 * si * si) * cd * cd + - 2 * ci * sd * si * sr * (s33 - s11) * cd + - (s33 * sd * sd * sr * sr + cr * cr * s22) * ci * ci + sd * sd * si * si * s11) * - cs * cs + - 2 * cr * cs * - (cd * cd * ci * sr * s11 + sd * si * (s33 - s11) * cd - - ci * sr * (-s33 * sd * sd + s22)) * - ss - - ss * ss * (cd * cd * cr * cr * s11 + cr * cr * s33 * sd * sd + s22 * sr * sr); - o.b_xy = cr * - (cd * cd * ci * sr * s11 + sd * si * (s33 - s11) * cd - - ci * sr * (-s33 * sd * sd + s22)) * - cs * cs + - ss * - ((-cd * cd * s11 + ci * ci * s22 - s33 * sd * sd) * cr * cr + - (ci * ci * s11 * sr * sr + s33 * si * si) * cd * cd + - 2 * ci * sd * si * sr * (s33 - s11) * cd + s33 * ci * ci * sd * sd * sr * sr + - sd * sd * si * si * s11 - s22 * sr * sr) * - cs - - ss * ss * cr * - (cd * cd * ci * sr * s11 + sd * si * (s33 - s11) * cd - - ci * sr * (-s33 * sd * sd + s22)); - o.b_xz = cd * cs * sd * sr * (s33 - s11) * si * si - - ((cs * (-s11 * sr * sr + s33) * ci + cr * sr * ss * s11) * cd * cd - - cs * ((s33 * sr * sr - s11) * sd * sd + cr * cr * s22) * ci - - cr * sr * ss * (-s33 * sd * sd + s22)) * - si - - cd * ci * sd * (ci * cs * sr - cr * ss) * (s33 - s11); - o.b_yy = -((ci * ci * s11 * sr * sr + s33 * si * si) * cd * cd + - 2 * ci * sd * si * sr * (s33 - s11) * cd + - (s33 * sd * sd * sr * sr + cr * cr * s22) * ci * ci + sd * sd * si * si * s11) * - ss * ss - - 2 * cr * cs * - (cd * cd * ci * sr * s11 + sd * si * (s33 - s11) * cd - - ci * sr * (-s33 * sd * sd + s22)) * - ss - - cs * cs * (cd * cd * cr * cr * s11 + cr * cr * s33 * sd * sd + s22 * sr * sr); - o.b_yz = -cd * sd * sr * ss * (s33 - s11) * si * si - - ((-ss * (-s11 * sr * sr + s33) * ci + cr * cs * sr * s11) * cd * cd + - ss * ((s33 * sr * sr - s11) * sd * sd + cr * cr * s22) * ci - - cr * cs * sr * (-s33 * sd * sd + s22)) * - si + - cd * ci * sd * (ci * sr * ss + cr * cs) * (s33 - s11); - o.b_zz = -(cd * cd * s11 * sr * sr + s33 * sd * sd * sr * sr + cr * cr * s22) * si * si - - 2 * cd * ci * sd * sr * (s11 - s33) * si - ci * ci * (cd * cd * s33 + s11 * sd * sd); + o.b_xx = -((ci * ci * s11 * sr * sr + s33 * si * si) * cd * cd + + 2 * ci * sd * si * sr * (s33 - s11) * cd + + (s33 * sd * sd * sr * sr + cr * cr * s22) * ci * ci + sd * sd * si * si * s11) * + cs * cs + + 2 * cr * cs * + (cd * cd * ci * sr * s11 + sd * si * (s33 - s11) * cd - + ci * sr * (-s33 * sd * sd + s22)) * + ss - + ss * ss * (cd * cd * cr * cr * s11 + cr * cr * s33 * sd * sd + s22 * sr * sr); + o.b_xy = + cr * + (cd * cd * ci * sr * s11 + sd * si * (s33 - s11) * cd - + ci * sr * (-s33 * sd * sd + s22)) * + cs * cs + + ss * + ((-cd * cd * s11 + ci * ci * s22 - s33 * sd * sd) * cr * cr + + (ci * ci * s11 * sr * sr + s33 * si * si) * cd * cd + + 2 * ci * sd * si * sr * (s33 - s11) * cd + s33 * ci * ci * sd * sd * sr * sr + + sd * sd * si * si * s11 - s22 * sr * sr) * + cs - + ss * ss * cr * + (cd * cd * ci * sr * s11 + sd * si * (s33 - s11) * cd - ci * sr * (-s33 * sd * sd + s22)); + o.b_xz = cd * cs * sd * sr * (s33 - s11) * si * si - + ((cs * (-s11 * sr * sr + s33) * ci + cr * sr * ss * s11) * cd * cd - + cs * ((s33 * sr * sr - s11) * sd * sd + cr * cr * s22) * ci - + cr * sr * ss * (-s33 * sd * sd + s22)) * + si - + cd * ci * sd * (ci * cs * sr - cr * ss) * (s33 - s11); + o.b_yy = -((ci * ci * s11 * sr * sr + s33 * si * si) * cd * cd + + 2 * ci * sd * si * sr * (s33 - s11) * cd + + (s33 * sd * sd * sr * sr + cr * cr * s22) * ci * ci + sd * sd * si * si * s11) * + ss * ss - + 2 * cr * cs * + (cd * cd * ci * sr * s11 + sd * si * (s33 - s11) * cd - + ci * sr * (-s33 * sd * sd + s22)) * + ss - + cs * cs * (cd * cd * cr * cr * s11 + cr * cr * s33 * sd * sd + s22 * sr * sr); + o.b_yz = -cd * sd * sr * ss * (s33 - s11) * si * si - + ((-ss * (-s11 * sr * sr + s33) * ci + cr * cs * sr * s11) * cd * cd + + ss * ((s33 * sr * sr - s11) * sd * sd + cr * cr * s22) * ci - + cr * cs * sr * (-s33 * sd * sd + s22)) * + si + + cd * ci * sd * (ci * sr * ss + cr * cs) * (s33 - s11); + o.b_zz = -(cd * cd * s11 * sr * sr + s33 * sd * sd * sr * sr + cr * cr * s22) * si * si - + 2 * cd * ci * sd * sr * (s11 - s33) * si - ci * ci * (cd * cd * s33 + s11 * sd * sd); } } // namespace easi diff --git a/src/component/PolynomialMap.cpp b/src/component/PolynomialMap.cpp index ef9dbef..af2b024 100644 --- a/src/component/PolynomialMap.cpp +++ b/src/component/PolynomialMap.cpp @@ -1,4 +1,5 @@ #include "easi/component/PolynomialMap.h" + #include "easi/util/Print.h" #include @@ -10,53 +11,53 @@ namespace easi { // Implements Horner's method Matrix PolynomialMap::map(Matrix& x) { - Matrix y(x.rows(), m_coeffs.cols()); - for (unsigned j = 0; j < m_coeffs.cols(); ++j) { - for (unsigned i = 0; i < x.rows(); ++i) { - y(i, j) = m_coeffs(0, j); - } - for (unsigned k = 1; k < m_coeffs.rows(); ++k) { - for (unsigned i = 0; i < x.rows(); ++i) { - y(i, j) = m_coeffs(k, j) + y(i, j) * x(i, 0); - } - } + Matrix y(x.rows(), m_coeffs.cols()); + for (unsigned j = 0; j < m_coeffs.cols(); ++j) { + for (unsigned i = 0; i < x.rows(); ++i) { + y(i, j) = m_coeffs(0, j); + } + for (unsigned k = 1; k < m_coeffs.rows(); ++k) { + for (unsigned i = 0; i < x.rows(); ++i) { + y(i, j) = m_coeffs(k, j) + y(i, j) * x(i, 0); + } } + } - return y; + return y; } -void PolynomialMap::setMap(std::set const& in, OutMap const& outMap) { - setIn(in); - if (dimDomain() != 1) { - std::ostringstream os; - os << "Polynomial map requires 1D input (got "; - printWithSeparator(in, os); - os << ")."; - throw std::invalid_argument(addFileReference(os.str())); - } - - std::set out; - unsigned nCoeffs = std::numeric_limits::max(); - for (auto const& kv : outMap) { - out.insert(kv.first); - if (nCoeffs != std::numeric_limits::max() && kv.second.size() != nCoeffs) { - throw std::invalid_argument(addFileReference( - "All parameters in a polynomial map must have the same number of coefficients.")); - } - nCoeffs = kv.second.size(); +void PolynomialMap::setMap(const std::set& in, const OutMap& outMap) { + setIn(in); + if (dimDomain() != 1) { + std::ostringstream os; + os << "Polynomial map requires 1D input (got "; + printWithSeparator(in, os); + os << ")."; + throw std::invalid_argument(addFileReference(os.str())); + } + + std::set out; + unsigned nCoeffs = std::numeric_limits::max(); + for (const auto& kv : outMap) { + out.insert(kv.first); + if (nCoeffs != std::numeric_limits::max() && kv.second.size() != nCoeffs) { + throw std::invalid_argument(addFileReference( + "All parameters in a polynomial map must have the same number of coefficients.")); } - setOut(out); - - m_coeffs.reallocate(nCoeffs, outMap.size()); - unsigned col = 0; - for (auto const& kv : outMap) { - unsigned row = 0; - for (auto const& v : kv.second) { - m_coeffs(row, col) = v; - ++row; - } - ++col; + nCoeffs = kv.second.size(); + } + setOut(out); + + m_coeffs.reallocate(nCoeffs, outMap.size()); + unsigned col = 0; + for (const auto& kv : outMap) { + unsigned row = 0; + for (const auto& v : kv.second) { + m_coeffs(row, col) = v; + ++row; } + ++col; + } } } // namespace easi diff --git a/src/component/SCECFile.cpp b/src/component/SCECFile.cpp index 9ba54a1..8af651a 100644 --- a/src/component/SCECFile.cpp +++ b/src/component/SCECFile.cpp @@ -1,4 +1,5 @@ #include "easi/component/SCECFile.h" + #include "easi/util/Print.h" #include @@ -7,71 +8,71 @@ namespace easi { SCECFile::SCECFile() { - // 0 1 2 3 4 5 - // 6 7 - std::set out{{"cohesion", "d_c", "forced_rupture_time", "mu_d", "mu_s", "s_dip", - "s_normal", "s_strike"}}; - setOut(out); + // 0 1 2 3 4 5 + // 6 7 + std::set out{ + {"cohesion", "d_c", "forced_rupture_time", "mu_d", "mu_s", "s_dip", "s_normal", "s_strike"}}; + setOut(out); } -void SCECFile::setMap(std::set const& in, std::string const& fileName) { - setIn(in); - if (dimDomain() != 2) { - std::ostringstream os; - os << "SCECFile requires 2D input (got "; - printWithSeparator(in, os); - os << ")."; - throw std::invalid_argument(addFileReference(os.str())); - } +void SCECFile::setMap(const std::set& in, const std::string& fileName) { + setIn(in); + if (dimDomain() != 2) { + std::ostringstream os; + os << "SCECFile requires 2D input (got "; + printWithSeparator(in, os); + os << ")."; + throw std::invalid_argument(addFileReference(os.str())); + } - readSCECFile(fileName); + readSCECFile(fileName); } -void SCECFile::readSCECFile(std::string const& fileName) { - m_grid = new RegularGrid; +void SCECFile::readSCECFile(const std::string& fileName) { + m_grid = new RegularGrid; - std::ifstream in(fileName, std::ifstream::in); + std::ifstream in(fileName, std::ifstream::in); - if (!in.good()) { - throw std::runtime_error(addFileReference("Could not open " + fileName + " for reading.")); - } + if (!in.good()) { + throw std::runtime_error(addFileReference("Could not open " + fileName + " for reading.")); + } - std::string dummyLine; - double dummyVal; - int dummyVal2; - unsigned numGridPoints[2]; - double min[2]; - double max[2]; - in >> dummyVal2 >> dummyVal2; // skip random seed line - in >> numGridPoints[0] >> numGridPoints[1] >> max[0] >> max[1]; + std::string dummyLine; + double dummyVal; + int dummyVal2; + unsigned numGridPoints[2]; + double min[2]; + double max[2]; + in >> dummyVal2 >> dummyVal2; // skip random seed line + in >> numGridPoints[0] >> numGridPoints[1] >> max[0] >> max[1]; - for (unsigned i = 0; i < 2; ++i) { - min[i] = 0.0; - ++numGridPoints[i]; // number of cells -> number of grid points - } - in >> dummyVal2 >> dummyVal2 >> dummyVal >> dummyVal >> dummyVal >> - dummyVal; // skip hypocentre line + for (unsigned i = 0; i < 2; ++i) { + min[i] = 0.0; + ++numGridPoints[i]; // number of cells -> number of grid points + } + in >> dummyVal2 >> dummyVal2 >> dummyVal >> dummyVal >> dummyVal >> + dummyVal; // skip hypocentre line - m_grid->allocate(numGridPoints, 2, dimCodomain()); - m_grid->setVolume(min, max); + m_grid->allocate(numGridPoints, 2, dimCodomain()); + m_grid->setVolume(min, max); - unsigned nGridPoints = numGridPoints[0] * numGridPoints[1]; + unsigned nGridPoints = numGridPoints[0] * numGridPoints[1]; - for (unsigned line = 0; line < nGridPoints; ++line) { - unsigned idx[2]; - in >> idx[0] >> idx[1] >> dummyVal >> dummyVal; - double* gridPtr = (*m_grid)(idx); - in >> gridPtr[6] // normal stress - >> gridPtr[7] // shear stress along strike - >> gridPtr[5] // shear stress along dip - >> dummyVal // shear stress along strike / normal stress - >> dummyVal // shear stress along dip / normal stress - >> gridPtr[4] // static coefficient of friction - >> gridPtr[3] // dynamic coefficient of friction - >> gridPtr[1] // slip weakening critical distance - >> gridPtr[0] // cohesion - >> gridPtr[2]; // time of forced rupture - } + for (unsigned line = 0; line < nGridPoints; ++line) { + unsigned idx[2]; + in >> idx[0] >> idx[1] >> dummyVal >> dummyVal; + double* gridPtr = (*m_grid)(idx); + in >> gridPtr[6] // normal stress + >> gridPtr[7] // shear stress along strike + >> gridPtr[5] // shear stress along dip + >> dummyVal // shear stress along strike / normal stress + >> dummyVal // shear stress along dip / normal stress + >> gridPtr[4] // static coefficient of friction + >> gridPtr[3] // dynamic coefficient of friction + >> gridPtr[1] // slip weakening critical distance + >> gridPtr[0] // cohesion + >> gridPtr[2]; // time of forced rupture + } } } // namespace easi diff --git a/src/component/Special.cpp b/src/component/Special.cpp index 7f51233..74f8b73 100644 --- a/src/component/Special.cpp +++ b/src/component/Special.cpp @@ -9,81 +9,78 @@ namespace easi { // fault This module is deprecated: use OptimalStress instead We nevertheless keep it to be able to // run the exact Sumatra SC simulation with the lastest SeisSol void STRESS_STR_DIP_SLIP_AM::evaluate() { - double const pi = 3.141592653589793; - // most favorable direction (A4, AM2003) - double Phi = pi / 4.0 - 0.5 * atan(i.mu_s); - double strike_rad = i.strike * pi / 180.0; - double dip_rad = i.dip * pi / 180.0; - double phi_xyz = Phi - dip_rad; - double s2 = sin(2.0 * Phi); - double c2 = cos(2.0 * Phi); - double c2xyz = cos(2.0 * phi_xyz); - double c2bis = c2 - c2xyz; - double szzInv = 1.0 / i.s_zz; + const double pi = 3.141592653589793; + // most favorable direction (A4, AM2003) + double Phi = pi / 4.0 - 0.5 * atan(i.mu_s); + double strike_rad = i.strike * pi / 180.0; + double dip_rad = i.dip * pi / 180.0; + double phi_xyz = Phi - dip_rad; + double s2 = sin(2.0 * Phi); + double c2 = cos(2.0 * Phi); + double c2xyz = cos(2.0 * phi_xyz); + double c2bis = c2 - c2xyz; + double szzInv = 1.0 / i.s_zz; - if (fabs(i.DipSlipFaulting) <= std::numeric_limits::epsilon()) { - double ds = (i.mu_d * i.s_zz + i.R * (i.cohesion + (i.mu_s - i.mu_d) * i.s_zz)) / - (s2 + i.mu_d * c2 + i.R * (i.mu_s - i.mu_d) * c2); - double sm = i.s_zz; - double s11 = sm + ds; - double s22 = sm - ds + 2.0 * ds * i.s2ratio; - double s33 = sm - ds; + if (fabs(i.DipSlipFaulting) <= std::numeric_limits::epsilon()) { + double ds = (i.mu_d * i.s_zz + i.R * (i.cohesion + (i.mu_s - i.mu_d) * i.s_zz)) / + (s2 + i.mu_d * c2 + i.R * (i.mu_s - i.mu_d) * c2); + double sm = i.s_zz; + double s11 = sm + ds; + double s22 = sm - ds + 2.0 * ds * i.s2ratio; + double s33 = sm - ds; - double cd = cos(Phi); - double sd = sin(Phi); + double cd = cos(Phi); + double sd = sin(Phi); - double ci = cos(dip_rad); - double si = sin(dip_rad); + double ci = cos(dip_rad); + double si = sin(dip_rad); - double cs = cos(strike_rad); - double ss = sin(strike_rad); + double cs = cos(strike_rad); + double ss = sin(strike_rad); - o.b_xx = - szzInv * (cd * cd * cs * cs * s33 * si * si + cs * cs * s11 * sd * sd * si * si + - 2 * cd * cs * s11 * sd * si * ss - 2 * cd * cs * s33 * sd * si * ss + - cd * cd * s11 * ss * ss + ci * ci * cs * cs * s22 + s33 * sd * sd * ss * ss); - o.b_xy = - szzInv * (-cd * cd * cs * s33 * si * si * ss - cs * s11 * sd * sd * si * si * ss + - cd * cs * cs * s11 * sd * si - cd * cs * cs * s33 * sd * si - - cd * s11 * sd * si * ss * ss + cd * s33 * sd * si * ss * ss + - cd * cd * cs * s11 * ss - ci * ci * cs * s22 * ss + cs * s33 * sd * sd * ss); - o.b_xz = szzInv * (cd * cd * ci * cs * s33 * si + ci * cs * s11 * sd * sd * si + - cd * ci * s11 * sd * ss - cd * ci * s33 * sd * ss - cs * ci * s22 * si); - o.b_yy = - szzInv * (cd * cd * s33 * si * si * ss * ss + s11 * sd * sd * si * si * ss * ss - - 2 * cd * cs * s11 * sd * si * ss + 2 * cd * cs * s33 * sd * si * ss + - cd * cd * cs * cs * s11 + ci * ci * s22 * ss * ss + cs * cs * s33 * sd * sd); - o.b_yz = szzInv * (-cd * cd * ci * s33 * si * ss - ci * s11 * sd * sd * si * ss + - cd * ci * cs * s11 * sd - cd * ci * cs * s33 * sd + ss * ci * s22 * si); - o.b_zz = szzInv * (cd * cd * ci * ci * s33 + ci * ci * s11 * sd * sd + si * si * s22); + o.b_xx = szzInv * (cd * cd * cs * cs * s33 * si * si + cs * cs * s11 * sd * sd * si * si + + 2 * cd * cs * s11 * sd * si * ss - 2 * cd * cs * s33 * sd * si * ss + + cd * cd * s11 * ss * ss + ci * ci * cs * cs * s22 + s33 * sd * sd * ss * ss); + o.b_xy = szzInv * (-cd * cd * cs * s33 * si * si * ss - cs * s11 * sd * sd * si * si * ss + + cd * cs * cs * s11 * sd * si - cd * cs * cs * s33 * sd * si - + cd * s11 * sd * si * ss * ss + cd * s33 * sd * si * ss * ss + + cd * cd * cs * s11 * ss - ci * ci * cs * s22 * ss + cs * s33 * sd * sd * ss); + o.b_xz = szzInv * (cd * cd * ci * cs * s33 * si + ci * cs * s11 * sd * sd * si + + cd * ci * s11 * sd * ss - cd * ci * s33 * sd * ss - cs * ci * s22 * si); + o.b_yy = szzInv * (cd * cd * s33 * si * si * ss * ss + s11 * sd * sd * si * si * ss * ss - + 2 * cd * cs * s11 * sd * si * ss + 2 * cd * cs * s33 * sd * si * ss + + cd * cd * cs * cs * s11 + ci * ci * s22 * ss * ss + cs * cs * s33 * sd * sd); + o.b_yz = szzInv * (-cd * cd * ci * s33 * si * ss - ci * s11 * sd * sd * si * ss + + cd * ci * cs * s11 * sd - cd * ci * cs * s33 * sd + ss * ci * s22 * si); + o.b_zz = szzInv * (cd * cd * ci * ci * s33 + ci * ci * s11 * sd * sd + si * si * s22); - } else { + } else { - /* ds (delta_sigma) is deduced from R (A5, Aochi and Madariaga 2003), - * assuming that sig1 and sig3 are in the yz plane - * sigzz and sigma_ini are then related by a phi+dip rotation (using A3, AM03) - * s_zz = sm - ds * cos(2.*(Phi+dip_rad)) - * Now we have to assume that P = sm (not any more equal to s_zz) - * and we can obtain the new expression of ds: */ - double ds = (i.mu_d * i.s_zz + i.R * (i.cohesion + (i.mu_s - i.mu_d) * i.s_zz)) / - (s2 + i.mu_d * c2bis + i.R * (i.mu_s - i.mu_d) * c2bis); - double sm = i.s_zz + ds * c2xyz; + /* ds (delta_sigma) is deduced from R (A5, Aochi and Madariaga 2003), + * assuming that sig1 and sig3 are in the yz plane + * sigzz and sigma_ini are then related by a phi+dip rotation (using A3, AM03) + * s_zz = sm - ds * cos(2.*(Phi+dip_rad)) + * Now we have to assume that P = sm (not any more equal to s_zz) + * and we can obtain the new expression of ds: */ + double ds = (i.mu_d * i.s_zz + i.R * (i.cohesion + (i.mu_s - i.mu_d) * i.s_zz)) / + (s2 + i.mu_d * c2bis + i.R * (i.mu_s - i.mu_d) * c2bis); + double sm = i.s_zz + ds * c2xyz; - double s11 = sm + ds; - double s22 = sm - ds + 2.0 * ds * i.s2ratio; - double s33 = sm - ds; - double cd = cos(phi_xyz); - double sd = sin(phi_xyz); - double cs = cos(strike_rad); - double ss = sin(strike_rad); + double s11 = sm + ds; + double s22 = sm - ds + 2.0 * ds * i.s2ratio; + double s33 = sm - ds; + double cd = cos(phi_xyz); + double sd = sin(phi_xyz); + double cs = cos(strike_rad); + double ss = sin(strike_rad); - o.b_xx = szzInv * (cd * cd * cs * cs * s11 + cs * cs * s33 * sd * sd + ss * ss * s22); - o.b_yy = szzInv * (cd * cd * s11 * ss * ss + s33 * sd * sd * ss * ss + cs * cs * s22); - o.b_zz = szzInv * (cd * cd * s33 + sd * sd * s11); - o.b_xy = szzInv * (-cd * cd * cs * s11 * ss - cs * s33 * sd * sd * ss + ss * s22 * cs); - o.b_yz = szzInv * (-ss * cd * s11 * sd + ss * sd * s33 * cd); - o.b_xz = szzInv * (cs * cd * s11 * sd - cs * sd * s33 * cd); - } + o.b_xx = szzInv * (cd * cd * cs * cs * s11 + cs * cs * s33 * sd * sd + ss * ss * s22); + o.b_yy = szzInv * (cd * cd * s11 * ss * ss + s33 * sd * sd * ss * ss + cs * cs * s22); + o.b_zz = szzInv * (cd * cd * s33 + sd * sd * s11); + o.b_xy = szzInv * (-cd * cd * cs * s11 * ss - cs * s33 * sd * sd * ss + ss * s22 * cs); + o.b_yz = szzInv * (-ss * cd * s11 * sd + ss * sd * s33 * cd); + o.b_xz = szzInv * (cs * cd * s11 * sd - cs * sd * s33 * cd); + } } } // namespace easi diff --git a/src/component/Switch.cpp b/src/component/Switch.cpp index 507c0df..4123032 100644 --- a/src/component/Switch.cpp +++ b/src/component/Switch.cpp @@ -1,4 +1,5 @@ #include "easi/component/Switch.h" + #include "easi/Component.h" #include "easi/Query.h" #include "easi/ResultAdapter.h" @@ -11,42 +12,45 @@ namespace easi { -void Switch::add(Component* component, std::set const& restrictions) { - std::set overlap; - std::set_intersection(restrictions.begin(), restrictions.end(), m_parameters.begin(), - m_parameters.end(), std::inserter(overlap, overlap.end())); - if (overlap.size() != 0) { - std::stringstream s; - s << "Switch requires a partition of parameters. The parameters {"; - printWithSeparator(overlap, s); - s << "} were specified in multiple branches."; - throw std::invalid_argument(addFileReference(s.str())); - } +void Switch::add(Component* component, const std::set& restrictions) { + std::set overlap; + std::set_intersection(restrictions.begin(), + restrictions.end(), + m_parameters.begin(), + m_parameters.end(), + std::inserter(overlap, overlap.end())); + if (overlap.size() != 0) { + std::stringstream s; + s << "Switch requires a partition of parameters. The parameters {"; + printWithSeparator(overlap, s); + s << "} were specified in multiple branches."; + throw std::invalid_argument(addFileReference(s.str())); + } - Composite::add(component); - m_restrictions.push_back(restrictions); - for (auto const& r : restrictions) { - m_parameters.insert(r); - } + Composite::add(component); + m_restrictions.push_back(restrictions); + for (const auto& r : restrictions) { + m_parameters.insert(r); + } } void Switch::evaluate(Query& query, ResultAdapter& result) { - if (!result.isSubset(m_parameters)) { - throw std::invalid_argument(addFileReference(addMissingParameters( - "Switch is not complete with respect to request.", result.parameters(), m_parameters))); - } + if (!result.isSubset(m_parameters)) { + throw std::invalid_argument(addFileReference(addMissingParameters( + "Switch is not complete with respect to request.", result.parameters(), m_parameters))); + } - // Evaluate submodels - iterator c = begin(); - auto r = m_restrictions.cbegin(); - for (; c != end() && r != m_restrictions.cend(); ++c, ++r) { - Query subQuery = query.shallowCopy(); - ResultAdapter* subResult = result.subsetAdapter(*r); - if (subResult->numberOfParameters() > 0) { - (*c)->evaluate(subQuery, *subResult); - } - delete subResult; + // Evaluate submodels + iterator c = begin(); + auto r = m_restrictions.cbegin(); + for (; c != end() && r != m_restrictions.cend(); ++c, ++r) { + Query subQuery = query.shallowCopy(); + ResultAdapter* subResult = result.subsetAdapter(*r); + if (subResult->numberOfParameters() > 0) { + (*c)->evaluate(subQuery, *subResult); } + delete subResult; + } } } // namespace easi diff --git a/src/parser/YAMLComponentParsers.cpp b/src/parser/YAMLComponentParsers.cpp index 68d8d3e..e52e716 100644 --- a/src/parser/YAMLComponentParsers.cpp +++ b/src/parser/YAMLComponentParsers.cpp @@ -1,13 +1,13 @@ #include "easi/parser/YAMLComponentParsers.h" + #include "easi/util/ImpalaHandler.h" #ifdef EASI_USE_ASAGI #include "easi/util/AsagiReader.h" #endif -#include - #include +#include #ifdef EXPERIMENTAL_FS #include @@ -22,304 +22,339 @@ namespace fs = std::filesystem; #endif namespace { - static std::string getFileName(const std::string& entry, easi::YAMLAbstractParser* parser) { - const auto entryPath = fs::path(entry); - if (entryPath.is_relative()) { - // remove file - const auto filePath = fs::path(parser->currentFileName()); - const auto newPath = filePath.parent_path() / entryPath; - if (fs::exists(newPath)) { - return fs::canonical(newPath); - } - else { - return entryPath; - } - } - else { - return entryPath; - } +static std::string getFileName(const std::string& entry, easi::YAMLAbstractParser* parser) { + const auto entryPath = fs::path(entry); + if (entryPath.is_relative()) { + // remove file + const auto filePath = fs::path(parser->currentFileName()); + const auto newPath = filePath.parent_path() / entryPath; + if (fs::exists(newPath)) { + return fs::canonical(newPath); + } else { + return entryPath; } + } else { + return entryPath; + } } +} // namespace namespace easi { -void parse_Component(Component* component, YAML::Node const& node, std::set const&, +void parse_Component(Component* component, + const YAML::Node& node, + const std::set&, YAMLAbstractParser* parser) { - std::stringstream s; - s << parser->currentFileName() << "@" << node.Mark().line + 1; - component->setFileReference(s.str()); + std::stringstream s; + s << parser->currentFileName() << "@" << node.Mark().line + 1; + component->setFileReference(s.str()); } -void parse_Composite(Composite* component, YAML::Node const& node, std::set const& in, +void parse_Composite(Composite* component, + const YAML::Node& node, + const std::set& in, YAMLAbstractParser* parser) { - if (node["components"]) { - if (node["components"].IsSequence()) { - for (YAML::const_iterator it = node["components"].begin(); - it != node["components"].end(); ++it) { - Component* child = parser->parse(*it, component->out()); - component->add(child); - } - } else { - Component* child = parser->parse(node["components"], component->out()); - component->add(child); - } + if (node["components"]) { + if (node["components"].IsSequence()) { + for (YAML::const_iterator it = node["components"].begin(); it != node["components"].end(); + ++it) { + Component* child = parser->parse(*it, component->out()); + component->add(child); + } + } else { + Component* child = parser->parse(node["components"], component->out()); + component->add(child); } - parse_Component(component, node, in, parser); + } + parse_Component(component, node, in, parser); } -void parse_Switch(Switch* component, YAML::Node const& node, std::set const& in, +void parse_Switch(Switch* component, + const YAML::Node& node, + const std::set& in, YAMLAbstractParser* parser) { - component->setInOut(in); - for (YAML::const_iterator it = node.begin(); it != node.end(); ++it) { - Component* child = parser->parse(it->second, component->out()); - std::set restrictions; - if (it->first.IsSequence()) { - std::vector restrictionSeq = it->first.as>(); - restrictions.insert(restrictionSeq.begin(), restrictionSeq.end()); - } else { - restrictions.insert(it->first.as()); - } - component->add(child, restrictions); + component->setInOut(in); + for (YAML::const_iterator it = node.begin(); it != node.end(); ++it) { + Component* child = parser->parse(it->second, component->out()); + std::set restrictions; + if (it->first.IsSequence()) { + std::vector restrictionSeq = it->first.as>(); + restrictions.insert(restrictionSeq.begin(), restrictionSeq.end()); + } else { + restrictions.insert(it->first.as()); } + component->add(child, restrictions); + } - // Do not call Composite parser, as we don't want to inherit the "components" parameter - parse_Component(component, node, in, parser); + // Do not call Composite parser, as we don't want to inherit the "components" parameter + parse_Component(component, node, in, parser); } -void parse_Filter(Filter* component, YAML::Node const& node, std::set const& in, +void parse_Filter(Filter* component, + const YAML::Node& node, + const std::set& in, YAMLAbstractParser* parser) { - parse_Composite(component, node, in, parser); + parse_Composite(component, node, in, parser); } -void parse_Any(Any* component, YAML::Node const& node, std::set const& in, +void parse_Any(Any* component, + const YAML::Node& node, + const std::set& in, YAMLAbstractParser* parser) { - component->setInOut(in); - parse_Filter(component, node, in, parser); + component->setInOut(in); + parse_Filter(component, node, in, parser); } -void parse_GroupFilter(GroupFilter* component, YAML::Node const& node, - std::set const& in, YAMLAbstractParser* parser) { - checkType(node, "groups", {YAML::NodeType::Scalar, YAML::NodeType::Sequence}); - - std::set groups; - if (node["groups"].IsScalar()) { - groups.insert(node["groups"].as()); - } else { - std::vector groupSeq = node["groups"].as>(); - groups.insert(groupSeq.begin(), groupSeq.end()); - } - - component->setInOut(in); - component->setGroups(groups); - parse_Filter(component, node, in, parser); +void parse_GroupFilter(GroupFilter* component, + const YAML::Node& node, + const std::set& in, + YAMLAbstractParser* parser) { + checkType(node, "groups", {YAML::NodeType::Scalar, YAML::NodeType::Sequence}); + + std::set groups; + if (node["groups"].IsScalar()) { + groups.insert(node["groups"].as()); + } else { + std::vector groupSeq = node["groups"].as>(); + groups.insert(groupSeq.begin(), groupSeq.end()); + } + + component->setInOut(in); + component->setGroups(groups); + parse_Filter(component, node, in, parser); } void parse_AxisAlignedCuboidalDomainFilter(AxisAlignedCuboidalDomainFilter* component, - YAML::Node const& node, std::set const& in, + const YAML::Node& node, + const std::set& in, YAMLAbstractParser* parser) { - checkType(node, "limits", {YAML::NodeType::Map}); + checkType(node, "limits", {YAML::NodeType::Map}); - AxisAlignedCuboidalDomainFilter::Limits limits = - node["limits"].as(); - component->setDomain(limits); + AxisAlignedCuboidalDomainFilter::Limits limits = + node["limits"].as(); + component->setDomain(limits); - parse_Filter(component, node, in, parser); + parse_Filter(component, node, in, parser); } -void parse_SphericalDomainFilter(SphericalDomainFilter* component, YAML::Node const& node, - std::set const& in, YAMLAbstractParser* parser) { - checkType(node, "radius", {YAML::NodeType::Scalar}); - checkType(node, "centre", {YAML::NodeType::Map}); +void parse_SphericalDomainFilter(SphericalDomainFilter* component, + const YAML::Node& node, + const std::set& in, + YAMLAbstractParser* parser) { + checkType(node, "radius", {YAML::NodeType::Scalar}); + checkType(node, "centre", {YAML::NodeType::Map}); - double radius = node["radius"].as(); - SphericalDomainFilter::Centre centre = node["centre"].as(); + double radius = node["radius"].as(); + SphericalDomainFilter::Centre centre = node["centre"].as(); - component->setDomain(radius, centre); + component->setDomain(radius, centre); - parse_Filter(component, node, in, parser); + parse_Filter(component, node, in, parser); } -void parse_Map(Map* component, YAML::Node const& node, std::set const& in, +void parse_Map(Map* component, + const YAML::Node& node, + const std::set& in, YAMLAbstractParser* parser) { - parse_Composite(component, node, in, parser); + parse_Composite(component, node, in, parser); } -void parse_ConstantMap(ConstantMap* component, YAML::Node const& node, - std::set const& in, YAMLAbstractParser* parser) { - checkType(node, "map", {YAML::NodeType::Map}); +void parse_ConstantMap(ConstantMap* component, + const YAML::Node& node, + const std::set& in, + YAMLAbstractParser* parser) { + checkType(node, "map", {YAML::NodeType::Map}); - ConstantMap::OutMap outMap = node["map"].as(); + ConstantMap::OutMap outMap = node["map"].as(); - component->setIn(in); - component->setMap(outMap); - parse_Map(component, node, in, parser); + component->setIn(in); + component->setMap(outMap); + parse_Map(component, node, in, parser); } -void parse_AffineMap(AffineMap* component, YAML::Node const& node, std::set const& in, +void parse_AffineMap(AffineMap* component, + const YAML::Node& node, + const std::set& in, YAMLAbstractParser* parser) { - checkType(node, "matrix", {YAML::NodeType::Map}); - checkType(node, "translation", {YAML::NodeType::Map}); + checkType(node, "matrix", {YAML::NodeType::Map}); + checkType(node, "translation", {YAML::NodeType::Map}); - AffineMap::Transformation matrix = node["matrix"].as(); - AffineMap::Translation translation = node["translation"].as(); + AffineMap::Transformation matrix = node["matrix"].as(); + AffineMap::Translation translation = node["translation"].as(); - component->setMap(in, matrix, translation); + component->setMap(in, matrix, translation); - parse_Map(component, node, in, parser); + parse_Map(component, node, in, parser); } #ifdef EASI_USE_LUA -void parse_LuaMap(LuaMap* component, YAML::Node const& node, - std::set const& in, YAMLAbstractParser* parser) { - checkType(node, "returns", {YAML::NodeType::Scalar, YAML::NodeType::Sequence}); +void parse_LuaMap(LuaMap* component, + YAML::Node const& node, + std::set const& in, + YAMLAbstractParser* parser) { + checkType(node, "returns", {YAML::NodeType::Scalar, YAML::NodeType::Sequence}); - std::set returns; - if (node["returns"].IsScalar()) { - returns.insert(node["returns"].as()); - } else { - const auto returnSeq = node["returns"].as>(); - returns.insert(returnSeq.begin(), returnSeq.end()); - } + std::set returns; + if (node["returns"].IsScalar()) { + returns.insert(node["returns"].as()); + } else { + const auto returnSeq = node["returns"].as>(); + returns.insert(returnSeq.begin(), returnSeq.end()); + } - checkType(node, "function", {YAML::NodeType::Scalar}); + checkType(node, "function", {YAML::NodeType::Scalar}); - const auto function = node["function"].as(); + const auto function = node["function"].as(); - component->setMap(in, returns, function); - parse_Map(component, node, in, parser); + component->setMap(in, returns, function); + parse_Map(component, node, in, parser); } -void parse_FunctionMapToLua(LuaMap* component, YAML::Node const& node, - std::set const& in, YAMLAbstractParser* parser) { - checkType(node, "map", {YAML::NodeType::Map}); +void parse_FunctionMapToLua(LuaMap* component, + const YAML::Node& node, + const std::set& in, + YAMLAbstractParser* parser) { + checkType(node, "map", {YAML::NodeType::Map}); - const auto precode = node["map"].as>(); + const auto precode = node["map"].as>(); - const auto code = std::unordered_map(precode.begin(), precode.end()); + const auto code = std::unordered_map(precode.begin(), precode.end()); - const auto luaCode = convertImpalaToLua(code, std::vector(in.begin(), in.end())); + const auto luaCode = convertImpalaToLua(code, std::vector(in.begin(), in.end())); - std::set returns; - for (const auto& [var, _] : code) { - returns.insert(var); - } + std::set returns; + for (const auto& [var, _] : code) { + returns.insert(var); + } - component->setMap(in, returns, luaCode); - parse_Map(component, node, in, parser); + component->setMap(in, returns, luaCode); + parse_Map(component, node, in, parser); } #endif -void parse_PolynomialMap(PolynomialMap* component, YAML::Node const& node, - std::set const& in, YAMLAbstractParser* parser) { - checkType(node, "map", {YAML::NodeType::Map}); +void parse_PolynomialMap(PolynomialMap* component, + YAML::Node const& node, + std::set const& in, + YAMLAbstractParser* parser) { + checkType(node, "map", {YAML::NodeType::Map}); - PolynomialMap::OutMap coeffs = node["map"].as(); - component->setMap(in, coeffs); + PolynomialMap::OutMap coeffs = node["map"].as(); + component->setMap(in, coeffs); - parse_Map(component, node, in, parser); + parse_Map(component, node, in, parser); } template -void parse_Grid(Grid* component, YAML::Node const& node, std::set const& in, +void parse_Grid(Grid* component, + const YAML::Node& node, + const std::set& in, YAMLAbstractParser* parser) { - if (node["interpolation"]) { - std::string interpolation = node["interpolation"].as(); - component->setInterpolationType(interpolation); - } + if (node["interpolation"]) { + std::string interpolation = node["interpolation"].as(); + component->setInterpolationType(interpolation); + } - parse_Map(component, node, in, parser); + parse_Map(component, node, in, parser); } -void parse_SCECFile(SCECFile* component, YAML::Node const& node, std::set const& in, +void parse_SCECFile(SCECFile* component, + const YAML::Node& node, + const std::set& in, YAMLAbstractParser* parser) { - checkType(node, "file", {YAML::NodeType::Scalar}); + checkType(node, "file", {YAML::NodeType::Scalar}); - const auto fileName = node["file"].as(); - const auto realFileName = getFileName(fileName, parser); - component->setMap(in, realFileName); + const auto fileName = node["file"].as(); + const auto realFileName = getFileName(fileName, parser); + component->setMap(in, realFileName); - parse_Grid(component, node, in, parser); + parse_Grid(component, node, in, parser); } #ifdef EASI_USE_ASAGI -void parse_ASAGI(ASAGI* component, YAML::Node const& node, std::set const& in, +void parse_ASAGI(ASAGI* component, + YAML::Node const& node, + std::set const& in, YAMLAbstractParser* parser) { - checkType(node, "file", {YAML::NodeType::Scalar}); - checkType(node, "parameters", {YAML::NodeType::Sequence}); + checkType(node, "file", {YAML::NodeType::Scalar}); + checkType(node, "parameters", {YAML::NodeType::Sequence}); - auto parameters = node["parameters"].as>(); + auto parameters = node["parameters"].as>(); - std::string varName = "data"; - if (node["var"]) { - varName = node["var"].as(); - } + std::string varName = "data"; + if (node["var"]) { + varName = node["var"].as(); + } - const auto fileName = node["file"].as(); - const auto realFileName = getFileName(fileName, parser); - asagi::Grid* grid = parser->asagiReader()->open(realFileName.c_str(), varName.c_str()); + const auto fileName = node["file"].as(); + const auto realFileName = getFileName(fileName, parser); + asagi::Grid* grid = parser->asagiReader()->open(realFileName.c_str(), varName.c_str()); - component->setGrid(in, parameters, grid, parser->asagiReader()->numberOfThreads()); + component->setGrid(in, parameters, grid, parser->asagiReader()->numberOfThreads()); - parse_Grid(component, node, in, parser); + parse_Grid(component, node, in, parser); } #endif -void parse_EvalModel(EvalModel* component, YAML::Node const& node, std::set const& in, +void parse_EvalModel(EvalModel* component, + YAML::Node const& node, + std::set const& in, YAMLAbstractParser* parser) { - checkExistence(node, "model"); - checkType(node, "parameters", {YAML::NodeType::Sequence}); - - Component* model = parser->parse(node["model"], in); - auto parameters = node["parameters"].as>(); - std::set out; - for (auto const& p : parameters) { - out.insert(p); - } + checkExistence(node, "model"); + checkType(node, "parameters", {YAML::NodeType::Sequence}); - component->setModel(in, out, model); + Component* model = parser->parse(node["model"], in); + auto parameters = node["parameters"].as>(); + std::set out; + for (const auto& p : parameters) { + out.insert(p); + } - parse_Map(component, node, in, parser); + component->setModel(in, out, model); + + parse_Map(component, node, in, parser); } -Component* create_LayeredModel(YAML::Node const& node, std::set const& in, +Component* create_LayeredModel(const YAML::Node& node, + const std::set& in, YAMLAbstractParser* parser) { - LayeredModelBuilder builder; - - checkExistence(node, "map"); - checkType(node, "interpolation", {YAML::NodeType::Scalar}); - checkType(node, "nodes", {YAML::NodeType::Map}); - checkType(node, "parameters", {YAML::NodeType::Sequence}); - - Component* rawMap = parser->parse(node["map"], in); - Map* map = upcast(node, rawMap); - std::string interpolation = node["interpolation"].as(); - LayeredModelBuilder::Nodes nodes = node["nodes"].as(); - LayeredModelBuilder::Parameters parameters = - node["parameters"].as(); - - if (map->componentCount() > 0) { - // Add another wrapper around the map---as the components would only stack otherwise - // (thus causing bugs) - - auto* mapWrapper = new EvalModel(); - // NOTE: suppliedParameters yields the actual output variables of a Composite with sub Components - // (out only contains the pre-post-component-application parameters) - mapWrapper->setModel(map->in(), map->suppliedParameters(), map); - - map = mapWrapper; - } - - builder.setMap(map); - builder.setInterpolationType(interpolation); - builder.setNodes(nodes); - builder.setParameters(parameters); - - return builder.getResult(); + LayeredModelBuilder builder; + + checkExistence(node, "map"); + checkType(node, "interpolation", {YAML::NodeType::Scalar}); + checkType(node, "nodes", {YAML::NodeType::Map}); + checkType(node, "parameters", {YAML::NodeType::Sequence}); + + Component* rawMap = parser->parse(node["map"], in); + Map* map = upcast(node, rawMap); + std::string interpolation = node["interpolation"].as(); + LayeredModelBuilder::Nodes nodes = node["nodes"].as(); + LayeredModelBuilder::Parameters parameters = + node["parameters"].as(); + + if (map->componentCount() > 0) { + // Add another wrapper around the map---as the components would only stack otherwise + // (thus causing bugs) + + auto* mapWrapper = new EvalModel(); + // NOTE: suppliedParameters yields the actual output variables of a Composite with sub + // Components (out only contains the pre-post-component-application parameters) + mapWrapper->setModel(map->in(), map->suppliedParameters(), map); + + map = mapWrapper; + } + + builder.setMap(map); + builder.setInterpolationType(interpolation); + builder.setNodes(nodes); + builder.setParameters(parameters); + + return builder.getResult(); } -Component* create_Include(YAML::Node const& node, std::set const& in, +Component* create_Include(const YAML::Node& node, + const std::set& in, YAMLAbstractParser* parser) { - return parser->parse(node.as()); + return parser->parse(node.as()); } } // namespace easi diff --git a/src/parser/YAMLHelpers.cpp b/src/parser/YAMLHelpers.cpp index ec9d664..0a5e87d 100644 --- a/src/parser/YAMLHelpers.cpp +++ b/src/parser/YAMLHelpers.cpp @@ -2,24 +2,26 @@ namespace easi { -void checkExistence(YAML::Node const& node, std::string const& name) { - std::stringstream ss; - if (node.IsScalar() || !node[name]) { - ss << node.Tag() << ": Parameter '" << name << "' is missing." << std::endl << node; - throw YAML::Exception(node.Mark(), ss.str()); - } +void checkExistence(const YAML::Node& node, const std::string& name) { + std::stringstream ss; + if (node.IsScalar() || !node[name]) { + ss << node.Tag() << ": Parameter '" << name << "' is missing." << std::endl << node; + throw YAML::Exception(node.Mark(), ss.str()); + } } -void checkType(YAML::Node const& node, std::string const& name, - std::set const& types, bool required) { - std::stringstream ss; - if (required) { - checkExistence(node, name); - } - if (node[name] && types.find(node[name].Type()) == types.end()) { - ss << node.Tag() << ": Parameter '" << name << "' has wrong type." << std::endl << node; - throw YAML::Exception(node.Mark(), ss.str()); - } +void checkType(const YAML::Node& node, + const std::string& name, + const std::set& types, + bool required) { + std::stringstream ss; + if (required) { + checkExistence(node, name); + } + if (node[name] && types.find(node[name].Type()) == types.end()) { + ss << node.Tag() << ": Parameter '" << name << "' has wrong type." << std::endl << node; + throw YAML::Exception(node.Mark(), ss.str()); + } } } // namespace easi diff --git a/src/util/AsagiReader.cpp b/src/util/AsagiReader.cpp index f08ae95..f0ddc96 100644 --- a/src/util/AsagiReader.cpp +++ b/src/util/AsagiReader.cpp @@ -5,24 +5,24 @@ namespace easi { -asagi::Grid* AsagiReader::open(char const* file, char const* varname) { - asagi::Grid* grid = asagi::Grid::createArray(); - grid->setParam("VALUE_POSITION", "VERTEX_CENTERED"); - grid->setParam("VARIABLE", varname); +asagi::Grid* AsagiReader::open(const char* file, const char* varname) { + asagi::Grid* grid = asagi::Grid::createArray(); + grid->setParam("VALUE_POSITION", "VERTEX_CENTERED"); + grid->setParam("VARIABLE", varname); - asagi::Grid::Error err = grid->open(file); - if (err != ::asagi::Grid::SUCCESS) { - std::ostringstream os; - os << "Could not open " << file << " with ASAGI: "; - if (err == asagi::Grid::VAR_NOT_FOUND) { - os << "Could not find variable \"" << varname << "\"."; - } else { - os << "Error code " << err << "."; - } - throw std::runtime_error(os.str()); + asagi::Grid::Error err = grid->open(file); + if (err != ::asagi::Grid::SUCCESS) { + std::ostringstream os; + os << "Could not open " << file << " with ASAGI: "; + if (err == asagi::Grid::VAR_NOT_FOUND) { + os << "Could not find variable \"" << varname << "\"."; + } else { + os << "Error code " << err << "."; } + throw std::runtime_error(os.str()); + } - return grid; + return grid; } } // namespace easi diff --git a/src/util/ImpalaHandler.cpp b/src/util/ImpalaHandler.cpp index bfeb53a..fb3d708 100644 --- a/src/util/ImpalaHandler.cpp +++ b/src/util/ImpalaHandler.cpp @@ -1,5 +1,7 @@ #include "easi/util/ImpalaHandler.h" + #include +#include #include #include #include @@ -8,426 +10,393 @@ #include #include -#include - namespace { enum class TokenType { - Variable, - Constant, - Comma, - Assign, - If, - Else, - Return, - OperatorAdd, - OperatorSub, - OperatorMul, - OperatorDiv, - OperatorOr, - OperatorAnd, - OperatorCompareEq, - OperatorCompareNe, - OperatorCompareLt, - OperatorCompareLe, - OperatorCompareGt, - OperatorCompareGe, - SectionOpen, - SectionClose, - BracketOpen, - BracketClose, - Semicolon + Variable, + Constant, + Comma, + Assign, + If, + Else, + Return, + OperatorAdd, + OperatorSub, + OperatorMul, + OperatorDiv, + OperatorOr, + OperatorAnd, + OperatorCompareEq, + OperatorCompareNe, + OperatorCompareLt, + OperatorCompareLe, + OperatorCompareGt, + OperatorCompareGe, + SectionOpen, + SectionClose, + BracketOpen, + BracketClose, + Semicolon }; struct Token { - TokenType type; - std::string value; + TokenType type; + std::string value; }; std::vector tokenizeImpala(const std::string& code) { - std::size_t pos = 0; - const static std::regex constantRegex("^[0-9]+(?:\\.[0-9]*)?"); - const static std::regex variableRegex("^([A-Za-z][A-Za-z0-9_]*)"); - const static std::regex whitespaceRegex("^\\s+"); - std::vector tokens; - // sort by length (descending) - const static std::vector> standardTokens = { - {"return", TokenType::Return}, - {"else", TokenType::Else}, - {"if", TokenType::If}, - {"==", TokenType::OperatorCompareEq}, - {"!=", TokenType::OperatorCompareNe}, - {"<=", TokenType::OperatorCompareLe}, - {">=", TokenType::OperatorCompareGe}, - {"&&", TokenType::OperatorAnd}, - {"||", TokenType::OperatorOr}, - {"<", TokenType::OperatorCompareLt}, - {">", TokenType::OperatorCompareGt}, - {"+", TokenType::OperatorAdd}, - {"-", TokenType::OperatorSub}, - {"*", TokenType::OperatorMul}, - {"/", TokenType::OperatorDiv}, - {",", TokenType::Comma}, - {"=", TokenType::Assign}, - {";", TokenType::Semicolon}, - {"(", TokenType::BracketOpen}, - {")", TokenType::BracketClose}, - {"{", TokenType::SectionOpen}, - {"}", TokenType::SectionClose}, - }; - while (pos < code.size()) { - bool found = false; - for (const auto& [token, type] : standardTokens) { - if (pos + token.size() <= code.size()) { - const auto parsed = code.substr(pos, token.size()); - if (parsed == token) { - tokens.emplace_back(Token{ - type, token - }); - pos += token.size(); - found = true; - break; - } - } - } - if (!found) { - std::smatch match; - if (std::regex_search(code.begin() + pos, code.end(), match, constantRegex)) { - const auto token = match[0].str(); - tokens.emplace_back(Token{ - TokenType::Constant, - token - }); - pos += token.size(); - } - else if (std::regex_search(code.begin() + pos, code.end(), match, variableRegex)) { - const auto token = match[0].str(); - tokens.emplace_back(Token{ - TokenType::Variable, - token - }); - pos += token.size(); - } - else if (std::regex_search(code.begin() + pos, code.end(), match, whitespaceRegex)) { - const auto token = match[0].str(); - pos += token.size(); - } - else { - throw std::runtime_error("Tokenization error: " + code.substr(pos)); - } + std::size_t pos = 0; + const static std::regex constantRegex("^[0-9]+(?:\\.[0-9]*)?"); + const static std::regex variableRegex("^([A-Za-z][A-Za-z0-9_]*)"); + const static std::regex whitespaceRegex("^\\s+"); + std::vector tokens; + // sort by length (descending) + const static std::vector> standardTokens = { + {"return", TokenType::Return}, + {"else", TokenType::Else}, + {"if", TokenType::If}, + {"==", TokenType::OperatorCompareEq}, + {"!=", TokenType::OperatorCompareNe}, + {"<=", TokenType::OperatorCompareLe}, + {">=", TokenType::OperatorCompareGe}, + {"&&", TokenType::OperatorAnd}, + {"||", TokenType::OperatorOr}, + {"<", TokenType::OperatorCompareLt}, + {">", TokenType::OperatorCompareGt}, + {"+", TokenType::OperatorAdd}, + {"-", TokenType::OperatorSub}, + {"*", TokenType::OperatorMul}, + {"/", TokenType::OperatorDiv}, + {",", TokenType::Comma}, + {"=", TokenType::Assign}, + {";", TokenType::Semicolon}, + {"(", TokenType::BracketOpen}, + {")", TokenType::BracketClose}, + {"{", TokenType::SectionOpen}, + {"}", TokenType::SectionClose}, + }; + while (pos < code.size()) { + bool found = false; + for (const auto& [token, type] : standardTokens) { + if (pos + token.size() <= code.size()) { + const auto parsed = code.substr(pos, token.size()); + if (parsed == token) { + tokens.emplace_back(Token{type, token}); + pos += token.size(); + found = true; + break; } + } + } + if (!found) { + std::smatch match; + if (std::regex_search(code.begin() + pos, code.end(), match, constantRegex)) { + const auto token = match[0].str(); + tokens.emplace_back(Token{TokenType::Constant, token}); + pos += token.size(); + } else if (std::regex_search(code.begin() + pos, code.end(), match, variableRegex)) { + const auto token = match[0].str(); + tokens.emplace_back(Token{TokenType::Variable, token}); + pos += token.size(); + } else if (std::regex_search(code.begin() + pos, code.end(), match, whitespaceRegex)) { + const auto token = match[0].str(); + pos += token.size(); + } else { + throw std::runtime_error("Tokenization error: " + code.substr(pos)); + } } - return tokens; + } + return tokens; } struct ParserState { - std::ostringstream output; - std::vector tokens; - std::size_t tokenPosition; - std::unordered_set variables; - std::unordered_set localVariables; - - ParserState(const std::vector& tokens) : tokens(tokens), tokenPosition(0) {} + std::ostringstream output; + std::vector tokens; + std::size_t tokenPosition; + std::unordered_set variables; + std::unordered_set localVariables; - bool probeMulti(const std::vector& type) { - if (type.empty()) { - return true; - } - - if (tokens.size() <= tokenPosition + type.size() - 1) { - throw std::runtime_error("Out of tokens"); - } + ParserState(const std::vector& tokens) : tokens(tokens), tokenPosition(0) {} - bool tokensMatch = true; - for (std::size_t i = 0; i < type.size(); ++i) { - tokensMatch &= tokens[tokenPosition + i].type == type[i]; - } - return tokensMatch; + bool probeMulti(const std::vector& type) { + if (type.empty()) { + return true; } - bool probeConsumeMulti(const std::vector& type) { - const auto probeResult = probeMulti(type); - if (probeResult) { - tokenPosition += type.size(); - } - return probeResult; + if (tokens.size() <= tokenPosition + type.size() - 1) { + throw std::runtime_error("Out of tokens"); } - std::vector expectMulti(const std::vector& type) { - if (type.empty()) { - return {}; - } - - if (tokens.size() <= tokenPosition + type.size() - 1) { - throw std::runtime_error("Out of tokens"); - } - - for (std::size_t i = 0; i < type.size(); ++i) { - if (tokens[tokenPosition + i].type != type[i]) { - throw std::runtime_error("Unexpected token: " + tokens[tokenPosition + i].value + " " + std::to_string(static_cast(tokens[tokenPosition + i].type)) + "; wanted:" + std::to_string(static_cast(type[i]))); - } - } - - std::vector strings(type.size()); - for (std::size_t i = 0; i < type.size(); ++i) { - strings[i] = tokens[tokenPosition + i].value; - } - tokenPosition += type.size(); - return strings; + bool tokensMatch = true; + for (std::size_t i = 0; i < type.size(); ++i) { + tokensMatch &= tokens[tokenPosition + i].type == type[i]; } + return tokensMatch; + } - bool probe(TokenType type) { - return probeMulti({type}); + bool probeConsumeMulti(const std::vector& type) { + const auto probeResult = probeMulti(type); + if (probeResult) { + tokenPosition += type.size(); } + return probeResult; + } - bool probeConsume(TokenType type) { - return probeConsumeMulti({type}); + std::vector expectMulti(const std::vector& type) { + if (type.empty()) { + return {}; } - std::string expect(TokenType type) { - return expectMulti({type})[0]; + if (tokens.size() <= tokenPosition + type.size() - 1) { + throw std::runtime_error("Out of tokens"); } - template - void parseList(F&& elementParse) { - expect(TokenType::BracketOpen); - std::size_t index = 0; - if (!probeConsume(TokenType::BracketClose)) { - elementParse(index); - ++index; - while(!probeConsume(TokenType::BracketClose)) { - expect(TokenType::Comma); - elementParse(index); - ++index; - } - } + for (std::size_t i = 0; i < type.size(); ++i) { + if (tokens[tokenPosition + i].type != type[i]) { + throw std::runtime_error("Unexpected token: " + tokens[tokenPosition + i].value + " " + + std::to_string(static_cast(tokens[tokenPosition + i].type)) + + "; wanted:" + std::to_string(static_cast(type[i]))); + } } - void parseBody() { - expect(TokenType::SectionOpen); - while(!probeConsume(TokenType::SectionClose)) { - if (probe(TokenType::If)) { - parseIf(); - } - else if (probe(TokenType::Return)) { - parseReturn(); - expect(TokenType::Semicolon); - output << ";"; - } - else if (probeMulti({TokenType::Variable, TokenType::Assign})) { - parseStatement(); - expect(TokenType::Semicolon); - output << ";"; - } - else { - parseExpression(); - expect(TokenType::Semicolon); - output << ";"; - } - } + std::vector strings(type.size()); + for (std::size_t i = 0; i < type.size(); ++i) { + strings[i] = tokens[tokenPosition + i].value; } - - void parseIf() { - expect(TokenType::If); - output << "if ("; - parseBoolean(); - output << ") then "; - parseBody(); - if (probeConsume(TokenType::Else)) { - output << " else "; - parseBody(); - } - output << " end "; + tokenPosition += type.size(); + return strings; + } + + bool probe(TokenType type) { return probeMulti({type}); } + + bool probeConsume(TokenType type) { return probeConsumeMulti({type}); } + + std::string expect(TokenType type) { return expectMulti({type})[0]; } + + template + void parseList(F&& elementParse) { + expect(TokenType::BracketOpen); + std::size_t index = 0; + if (!probeConsume(TokenType::BracketClose)) { + elementParse(index); + ++index; + while (!probeConsume(TokenType::BracketClose)) { + expect(TokenType::Comma); + elementParse(index); + ++index; + } } - - void parseReturn() { - expect(TokenType::Return); - output << " do return "; + } + + void parseBody() { + expect(TokenType::SectionOpen); + while (!probeConsume(TokenType::SectionClose)) { + if (probe(TokenType::If)) { + parseIf(); + } else if (probe(TokenType::Return)) { + parseReturn(); + expect(TokenType::Semicolon); + output << ";"; + } else if (probeMulti({TokenType::Variable, TokenType::Assign})) { + parseStatement(); + expect(TokenType::Semicolon); + output << ";"; + } else { parseExpression(); - output << " end "; + expect(TokenType::Semicolon); + output << ";"; + } } - - void parseStatement() { - const auto variable = expect(TokenType::Variable); - // TODO: remove once out of scope? - localVariables.insert(variable); - expect(TokenType::Assign); - output << variable << " = "; - parseExpression(); + } + + void parseIf() { + expect(TokenType::If); + output << "if ("; + parseBoolean(); + output << ") then "; + parseBody(); + if (probeConsume(TokenType::Else)) { + output << " else "; + parseBody(); } - - void parseFunctionCall() { - const std::string functionName = expect(TokenType::Variable); - output << "math." << functionName << "("; - parseList([this](std::size_t index) { - if (index > 0) { - output << ", "; - } - parseExpression(); - }); - output << ")"; + output << " end "; + } + + void parseReturn() { + expect(TokenType::Return); + output << " do return "; + parseExpression(); + output << " end "; + } + + void parseStatement() { + const auto variable = expect(TokenType::Variable); + // TODO: remove once out of scope? + localVariables.insert(variable); + expect(TokenType::Assign); + output << variable << " = "; + parseExpression(); + } + + void parseFunctionCall() { + const std::string functionName = expect(TokenType::Variable); + output << "math." << functionName << "("; + parseList([this](std::size_t index) { + if (index > 0) { + output << ", "; + } + parseExpression(); + }); + output << ")"; + } + + void parseAtomExpression() { + output << "("; + if (probeConsume(TokenType::BracketOpen)) { + parseExpression(); + expect(TokenType::BracketClose); + } else if (probeMulti({TokenType::Variable, TokenType::BracketOpen})) { + parseFunctionCall(); + } else if (probe(TokenType::Variable)) { + const auto variable = expect(TokenType::Variable); + if (variables.find(variable) != variables.end()) { + output << "__in[\"" << variable << "\"]"; + } else if (localVariables.find(variable) != localVariables.end()) { + output << variable; + } else { + throw std::runtime_error("Unknown variable: " + variable); + } + } else if (probe(TokenType::Constant)) { + output << expect(TokenType::Constant); + } else { + throw std::runtime_error("Unexpected token when parsing expression: " + + tokens[tokenPosition].value); } + output << ")"; + } - void parseAtomExpression() { - output << "("; - if (probeConsume(TokenType::BracketOpen)) { - parseExpression(); - expect(TokenType::BracketClose); - } - else if (probeMulti({TokenType::Variable, TokenType::BracketOpen})) { - parseFunctionCall(); - } - else if (probe(TokenType::Variable)) { - const auto variable = expect(TokenType::Variable); - if (variables.find(variable) != variables.end()) { - output << "__in[\"" << variable << "\"]"; - } - else if (localVariables.find(variable) != localVariables.end()) { - output << variable; - } - else { - throw std::runtime_error("Unknown variable: " + variable); - } - } - else if (probe(TokenType::Constant)) { - output << expect(TokenType::Constant); - } - else { - throw std::runtime_error("Unexpected token when parsing expression: " + tokens[tokenPosition].value); - } - output << ")"; + void parseUnaryExpression() { + output << "("; + if (probeConsume(TokenType::OperatorAdd)) { + output << "+"; } - - void parseUnaryExpression() { - output << "("; - if (probeConsume(TokenType::OperatorAdd)) { - output << "+"; - } - if (probeConsume(TokenType::OperatorSub)) { - output << "-"; - } - parseAtomExpression(); - output << ")"; + if (probeConsume(TokenType::OperatorSub)) { + output << "-"; } - - void parseMulExpression() { - output << "("; - parseUnaryExpression(); - if (probeConsume(TokenType::OperatorMul)) { - output << " * "; - parseMulExpression(); - } - if (probeConsume(TokenType::OperatorDiv)) { - output << " / "; - parseMulExpression(); - } - output << ")"; + parseAtomExpression(); + output << ")"; + } + + void parseMulExpression() { + output << "("; + parseUnaryExpression(); + if (probeConsume(TokenType::OperatorMul)) { + output << " * "; + parseMulExpression(); } - - void parseAddExpression() { - output << "("; - parseMulExpression(); - if (probeConsume(TokenType::OperatorAdd)) { - output << " + "; - parseAddExpression(); - } - if (probeConsume(TokenType::OperatorSub)) { - output << " - "; - parseAddExpression(); - } - output << ")"; + if (probeConsume(TokenType::OperatorDiv)) { + output << " / "; + parseMulExpression(); } - - void parseExpression() { - parseAddExpression(); + output << ")"; + } + + void parseAddExpression() { + output << "("; + parseMulExpression(); + if (probeConsume(TokenType::OperatorAdd)) { + output << " + "; + parseAddExpression(); } - - void parseAtomBoolean() { - output << "("; - if (probeConsume(TokenType::BracketOpen)) { - parseBoolean(); - expect(TokenType::BracketClose); - } - else { - parseExpression(); - if (probeConsume(TokenType::OperatorCompareEq)) { - output << " == "; - } - else if (probeConsume(TokenType::OperatorCompareNe)) { - output << " ~= "; - } - else if (probeConsume(TokenType::OperatorCompareLe)) { - output << " <= "; - } - else if (probeConsume(TokenType::OperatorCompareLt)) { - output << " < "; - } - else if (probeConsume(TokenType::OperatorCompareGe)) { - output << " >= "; - } - else if (probeConsume(TokenType::OperatorCompareGt)) { - output << " > "; - } - else { - throw std::runtime_error("No comparison operator given"); - } - parseExpression(); - } - output << ")"; + if (probeConsume(TokenType::OperatorSub)) { + output << " - "; + parseAddExpression(); } - - void parseAndBoolean() { - output << "("; - parseAtomBoolean(); - if (probeConsume(TokenType::OperatorAnd)) { - output << " and "; - parseAndBoolean(); - } - output << ")"; + output << ")"; + } + + void parseExpression() { parseAddExpression(); } + + void parseAtomBoolean() { + output << "("; + if (probeConsume(TokenType::BracketOpen)) { + parseBoolean(); + expect(TokenType::BracketClose); + } else { + parseExpression(); + if (probeConsume(TokenType::OperatorCompareEq)) { + output << " == "; + } else if (probeConsume(TokenType::OperatorCompareNe)) { + output << " ~= "; + } else if (probeConsume(TokenType::OperatorCompareLe)) { + output << " <= "; + } else if (probeConsume(TokenType::OperatorCompareLt)) { + output << " < "; + } else if (probeConsume(TokenType::OperatorCompareGe)) { + output << " >= "; + } else if (probeConsume(TokenType::OperatorCompareGt)) { + output << " > "; + } else { + throw std::runtime_error("No comparison operator given"); + } + parseExpression(); } - - void parseOrBoolean() { - output << "("; - parseAndBoolean(); - if (probeConsume(TokenType::OperatorOr)) { - output << " or "; - parseOrBoolean(); - } - output << ")"; + output << ")"; + } + + void parseAndBoolean() { + output << "("; + parseAtomBoolean(); + if (probeConsume(TokenType::OperatorAnd)) { + output << " and "; + parseAndBoolean(); } - - void parseBoolean() { - parseOrBoolean(); + output << ")"; + } + + void parseOrBoolean() { + output << "("; + parseAndBoolean(); + if (probeConsume(TokenType::OperatorOr)) { + output << " or "; + parseOrBoolean(); } + output << ")"; + } + + void parseBoolean() { parseOrBoolean(); } }; -std::string getLuaCode(const std::string& functionName, const std::vector& tokens, const std::vector& in) { - ParserState state(tokens); - state.variables = std::unordered_set(in.begin(), in.end()); - state.output << " function " << functionName << "(__in) "; - state.parseBody(); - state.output << " end "; - return state.output.str(); +std::string getLuaCode(const std::string& functionName, + const std::vector& tokens, + const std::vector& in) { + ParserState state(tokens); + state.variables = std::unordered_set(in.begin(), in.end()); + state.output << " function " << functionName << "(__in) "; + state.parseBody(); + state.output << " end "; + return state.output.str(); } -} +} // namespace namespace easi { -std::string convertImpalaToLua(const std::unordered_map& code, const std::vector& in) { - std::ostringstream outstream; - outstream << "function f(__in__main) "; - for (const auto& [variable, function] : code) { - auto tokens = tokenizeImpala("{" + function + "}"); - const auto luaFunction = getLuaCode("__compute__" + variable, tokens, in); - outstream << luaFunction; - } - outstream << " return { "; - for (const auto& [variable, function] : code) { - outstream << variable << " = __compute__" << variable << "(__in__main),"; - } - outstream << "} end"; - return outstream.str(); +std::string convertImpalaToLua(const std::unordered_map& code, + const std::vector& in) { + std::ostringstream outstream; + outstream << "function f(__in__main) "; + for (const auto& [variable, function] : code) { + auto tokens = tokenizeImpala("{" + function + "}"); + const auto luaFunction = getLuaCode("__compute__" + variable, tokens, in); + outstream << luaFunction; + } + outstream << " return { "; + for (const auto& [variable, function] : code) { + outstream << variable << " = __compute__" << variable << "(__in__main),"; + } + outstream << "} end"; + return outstream.str(); } } // namespace easi diff --git a/src/util/RegularGrid.cpp b/src/util/RegularGrid.cpp index 6cb3720..d6b5f29 100644 --- a/src/util/RegularGrid.cpp +++ b/src/util/RegularGrid.cpp @@ -1,4 +1,5 @@ #include "easi/util/RegularGrid.h" + #include "easi/util/Slice.h" #include @@ -8,87 +9,87 @@ namespace easi { -void RegularGrid::allocate(unsigned const* numGridPoints, unsigned dimensions, unsigned numValues) { - if (dimensions > MaxDimensions) { - throw std::runtime_error("Unsupported number of dimensions for RegularGrid."); - } - m_dimensions = dimensions; - m_numValues = numValues; - unsigned size = m_numValues; - for (unsigned d = 0; d < m_dimensions; ++d) { - m_num[d] = numGridPoints[d]; - size *= m_num[d]; - } - m_values = new double[size]; +void RegularGrid::allocate(const unsigned* numGridPoints, unsigned dimensions, unsigned numValues) { + if (dimensions > MaxDimensions) { + throw std::runtime_error("Unsupported number of dimensions for RegularGrid."); + } + m_dimensions = dimensions; + m_numValues = numValues; + unsigned size = m_numValues; + for (unsigned d = 0; d < m_dimensions; ++d) { + m_num[d] = numGridPoints[d]; + size *= m_num[d]; + } + m_values = new double[size]; } -void RegularGrid::setVolume(double const* min, double const* max) { - for (unsigned d = 0; d < m_dimensions; ++d) { - m_min[d] = min[d]; - m_max[d] = max[d]; - m_delta[d] = (max[d] - min[d]) / (m_num[d] - 1); - } +void RegularGrid::setVolume(const double* min, const double* max) { + for (unsigned d = 0; d < m_dimensions; ++d) { + m_min[d] = min[d]; + m_max[d] = max[d]; + m_delta[d] = (max[d] - min[d]) / (m_num[d] - 1); + } } -double* RegularGrid::operator()(unsigned const* index) { - unsigned stride = 1; - unsigned idx = 0; - for (unsigned d = 0; d < m_dimensions; ++d) { - idx += index[d] * stride; - stride *= m_num[d]; - } - return m_values + m_numValues * idx; +double* RegularGrid::operator()(const unsigned* index) { + unsigned stride = 1; + unsigned idx = 0; + for (unsigned d = 0; d < m_dimensions; ++d) { + idx += index[d] * stride; + stride *= m_num[d]; + } + return m_values + m_numValues * idx; } -void RegularGrid::getNearestNeighbour(Slice const& x, double* buffer) { - assert(x.size() == m_dimensions); +void RegularGrid::getNearestNeighbour(const Slice& x, double* buffer) { + assert(x.size() == m_dimensions); - unsigned idx[MaxDimensions]; - for (unsigned d = 0; d < m_dimensions; ++d) { - if (x(d) < m_min[d]) { - idx[d] = 0; - } else if (x(d) >= m_max[d]) { - idx[d] = m_num[d] - 1; - } else { - double xn = (x(d) - m_min[d]) / m_delta[d]; - idx[d] = std::round(xn); - } + unsigned idx[MaxDimensions]; + for (unsigned d = 0; d < m_dimensions; ++d) { + if (x(d) < m_min[d]) { + idx[d] = 0; + } else if (x(d) >= m_max[d]) { + idx[d] = m_num[d] - 1; + } else { + double xn = (x(d) - m_min[d]) / m_delta[d]; + idx[d] = std::round(xn); } + } - double* values = operator()(idx); - for (unsigned v = 0; v < m_numValues; ++v) { - buffer[v] = values[v]; - } + double* values = operator()(idx); + for (unsigned v = 0; v < m_numValues; ++v) { + buffer[v] = values[v]; + } } -void RegularGrid::getNeighbours(Slice const& x, double* weights, double* buffer) { - assert(x.size() == m_dimensions); +void RegularGrid::getNeighbours(const Slice& x, double* weights, double* buffer) { + assert(x.size() == m_dimensions); - unsigned idxBase[MaxDimensions]; - for (unsigned d = 0; d < m_dimensions; ++d) { - if (x(d) < m_min[d]) { - idxBase[d] = 0; - weights[d] = 0.0; - } else if (x(d) >= m_max[d]) { - idxBase[d] = m_num[d] - 1; - weights[d] = 1.0; - } else { - double xn = (x(d) - m_min[d]) / m_delta[d]; - idxBase[d] = xn; - weights[d] = xn - idxBase[d]; - } + unsigned idxBase[MaxDimensions]; + for (unsigned d = 0; d < m_dimensions; ++d) { + if (x(d) < m_min[d]) { + idxBase[d] = 0; + weights[d] = 0.0; + } else if (x(d) >= m_max[d]) { + idxBase[d] = m_num[d] - 1; + weights[d] = 1.0; + } else { + double xn = (x(d) - m_min[d]) / m_delta[d]; + idxBase[d] = xn; + weights[d] = xn - idxBase[d]; } + } - unsigned idx[MaxDimensions]; - for (unsigned i = 0; i < (1u << m_dimensions); ++i) { - for (unsigned d = 0; d < m_dimensions; ++d) { - idx[d] = std::min(idxBase[d] + ((i & (1 << d)) >> d), m_num[d] - 1); - } - double* values = operator()(idx); - for (unsigned v = 0; v < m_numValues; ++v) { - buffer[i * m_numValues + v] = values[v]; - } + unsigned idx[MaxDimensions]; + for (unsigned i = 0; i < (1u << m_dimensions); ++i) { + for (unsigned d = 0; d < m_dimensions; ++d) { + idx[d] = std::min(idxBase[d] + ((i & (1 << d)) >> d), m_num[d] - 1); + } + double* values = operator()(idx); + for (unsigned v = 0; v < m_numValues; ++v) { + buffer[i * m_numValues + v] = values[v]; } + } } } // namespace easi diff --git a/tests/0_constant.cpp b/tests/0_constant.cpp index b234431..479669f 100644 --- a/tests/0_constant.cpp +++ b/tests/0_constant.cpp @@ -1,19 +1,19 @@ #include "easitest.h" int main(int argc, char** argv) { - assert(argc == 2); + assert(argc == 2); - easi::Query query = createQuery<3>({{1, {1.0, 2.0, 3.0}}, {2, {-3.0, -2.0, -1.0}}}); + easi::Query query = createQuery<3>({{1, {1.0, 2.0, 3.0}}, {2, {-3.0, -2.0, -1.0}}}); - auto material = elasticModel(argv[1], query); + auto material = elasticModel(argv[1], query); - assert(material[0].lambda == 1.0); - assert(material[0].mu == 2.0); - assert(material[0].rho == 3.0); + assert(material[0].lambda == 1.0); + assert(material[0].mu == 2.0); + assert(material[0].rho == 3.0); - assert(material[1].lambda == 1.0); - assert(material[1].mu == 2.0); - assert(material[1].rho == 3.0); + assert(material[1].lambda == 1.0); + assert(material[1].mu == 2.0); + assert(material[1].rho == 3.0); - return 0; + return 0; } diff --git a/tests/101_asagi.cpp b/tests/101_asagi.cpp index 599c16f..b207607 100644 --- a/tests/101_asagi.cpp +++ b/tests/101_asagi.cpp @@ -1,39 +1,40 @@ #include "easitest.h" + #include int main(int argc, char** argv) { - assert(argc == 2); + assert(argc == 2); - MPI_Init(&argc, &argv); + MPI_Init(&argc, &argv); - easi::Query query = createQuery<3>({{1, {2.0, -1.0, 0.0}}, - {1, {3.0, 0.0, 0.0}}, - {1, {2.5, -0.5, 0.0}}, - {1, {2.75, -0.25, 0.0}}, - {1, {2.6, -0.25, 0.0}}}); - auto material = elasticModel(argv[1], query); + easi::Query query = createQuery<3>({{1, {2.0, -1.0, 0.0}}, + {1, {3.0, 0.0, 0.0}}, + {1, {2.5, -0.5, 0.0}}, + {1, {2.75, -0.25, 0.0}}, + {1, {2.6, -0.25, 0.0}}}); + auto material = elasticModel(argv[1], query); - assert(equal(material[0].rho, 1.0)); - assert(equal(material[0].mu, -1.0)); - assert(equal(material[0].lambda, 10.0)); + assert(equal(material[0].rho, 1.0)); + assert(equal(material[0].mu, -1.0)); + assert(equal(material[0].lambda, 10.0)); - assert(equal(material[1].rho, 6.0)); - assert(equal(material[1].mu, -6.0)); - assert(equal(material[1].lambda, 15.0)); + assert(equal(material[1].rho, 6.0)); + assert(equal(material[1].mu, -6.0)); + assert(equal(material[1].lambda, 15.0)); - assert(equal(material[2].rho, 3.5)); - assert(equal(material[2].mu, -3.5)); - assert(equal(material[2].lambda, 12.5)); + assert(equal(material[2].rho, 3.5)); + assert(equal(material[2].mu, -3.5)); + assert(equal(material[2].lambda, 12.5)); - assert(equal(material[3].rho, 4.75)); - assert(equal(material[3].mu, -4.75)); - assert(equal(material[3].lambda, 13.75)); + assert(equal(material[3].rho, 4.75)); + assert(equal(material[3].mu, -4.75)); + assert(equal(material[3].lambda, 13.75)); - assert(equal(material[4].rho, 4.45)); - assert(equal(material[4].mu, -4.45)); - assert(equal(material[4].lambda, 13.45)); + assert(equal(material[4].rho, 4.45)); + assert(equal(material[4].mu, -4.45)); + assert(equal(material[4].lambda, 13.45)); - MPI_Finalize(); + MPI_Finalize(); - return 0; + return 0; } diff --git a/tests/101_asagi_nearest.cpp b/tests/101_asagi_nearest.cpp index 12e64c4..532f146 100644 --- a/tests/101_asagi_nearest.cpp +++ b/tests/101_asagi_nearest.cpp @@ -1,39 +1,40 @@ #include "easitest.h" + #include int main(int argc, char** argv) { - assert(argc == 2); + assert(argc == 2); - MPI_Init(&argc, &argv); + MPI_Init(&argc, &argv); - easi::Query query = createQuery<3>({{1, {2.0, -1.0, 0.0}}, - {1, {3.0, 0.0, 0.0}}, - {1, {2.5, -0.5, 0.0}}, - {1, {2.75, -0.25, 0.0}}, - {1, {2.6, -0.25, 0.0}}}); - auto material = elasticModel(argv[1], query); + easi::Query query = createQuery<3>({{1, {2.0, -1.0, 0.0}}, + {1, {3.0, 0.0, 0.0}}, + {1, {2.5, -0.5, 0.0}}, + {1, {2.75, -0.25, 0.0}}, + {1, {2.6, -0.25, 0.0}}}); + auto material = elasticModel(argv[1], query); - assert(equal(material[0].rho, 1.0)); - assert(equal(material[0].mu, -1.0)); - assert(equal(material[0].lambda, 10.0)); + assert(equal(material[0].rho, 1.0)); + assert(equal(material[0].mu, -1.0)); + assert(equal(material[0].lambda, 10.0)); - assert(equal(material[1].rho, 6.0)); - assert(equal(material[1].mu, -6.0)); - assert(equal(material[1].lambda, 15.0)); + assert(equal(material[1].rho, 6.0)); + assert(equal(material[1].mu, -6.0)); + assert(equal(material[1].lambda, 15.0)); - assert(equal(material[2].rho, 5.0)); - assert(equal(material[2].mu, -5.0)); - assert(equal(material[2].lambda, 14.0)); + assert(equal(material[2].rho, 5.0)); + assert(equal(material[2].mu, -5.0)); + assert(equal(material[2].lambda, 14.0)); - assert(equal(material[3].rho, 6.0)); - assert(equal(material[3].mu, -6.0)); - assert(equal(material[3].lambda, 15.0)); + assert(equal(material[3].rho, 6.0)); + assert(equal(material[3].mu, -6.0)); + assert(equal(material[3].lambda, 15.0)); - assert(equal(material[4].rho, 5.0)); - assert(equal(material[4].mu, -5.0)); - assert(equal(material[4].lambda, 14.0)); + assert(equal(material[4].rho, 5.0)); + assert(equal(material[4].mu, -5.0)); + assert(equal(material[4].lambda, 14.0)); - MPI_Finalize(); + MPI_Finalize(); - return 0; + return 0; } diff --git a/tests/1_groups.cpp b/tests/1_groups.cpp index 8bc7269..2a67095 100644 --- a/tests/1_groups.cpp +++ b/tests/1_groups.cpp @@ -1,24 +1,24 @@ #include "easitest.h" int main(int argc, char** argv) { - assert(argc == 2); + assert(argc == 2); - easi::Query query = - createQuery<3>({{1, {1.0, 2.0, 3.0}}, {2, {-3.0, -2.0, -1.0}}, {1, {-1.0, -2.0, -3.0}}}); + easi::Query query = + createQuery<3>({{1, {1.0, 2.0, 3.0}}, {2, {-3.0, -2.0, -1.0}}, {1, {-1.0, -2.0, -3.0}}}); - auto material = elasticModel(argv[1], query); + auto material = elasticModel(argv[1], query); - assert(equal(material[0].rho, 2600.0)); - assert(equal(material[0].mu, 1.04e10)); - assert(equal(material[0].lambda, 2.08e10)); + assert(equal(material[0].rho, 2600.0)); + assert(equal(material[0].mu, 1.04e10)); + assert(equal(material[0].lambda, 2.08e10)); - assert(equal(material[1].rho, 2700.0)); - assert(equal(material[1].mu, 3.23980992e10)); - assert(equal(material[1].lambda, 3.24038016e10)); + assert(equal(material[1].rho, 2700.0)); + assert(equal(material[1].mu, 3.23980992e10)); + assert(equal(material[1].lambda, 3.24038016e10)); - assert(equal(material[2].rho, 2600.0)); - assert(equal(material[2].mu, 1.04e10)); - assert(equal(material[2].lambda, 2.08e10)); + assert(equal(material[2].rho, 2600.0)); + assert(equal(material[2].mu, 1.04e10)); + assert(equal(material[2].lambda, 2.08e10)); - return 0; + return 0; } diff --git a/tests/26_function.cpp b/tests/26_function.cpp index e30aa02..7c5a6e0 100644 --- a/tests/26_function.cpp +++ b/tests/26_function.cpp @@ -1,64 +1,65 @@ #include "easitest.h" + #include void model(double z, double params[9]) { - params[0] = 2670.0; - params[1] = 32038120320.0; - params[2] = 32043759360.0; + params[0] = 2670.0; + params[1] = 32038120320.0; + params[2] = 32043759360.0; - double b11 = 0.926793; - double b33 = 1.073206; - double b13 = -0.169029; + double b11 = 0.926793; + double b33 = 1.073206; + double b13 = -0.169029; - double Pf = 9800.0 * fabs(z); - double omega; - if (z >= -15000.0) { - omega = 1.0; - } else if (z <= -15000.0 && z >= -20000.0) { - omega = (20000.0 - fabs(z)) / 5000.0; - } else { - omega = 0.0; - } + double Pf = 9800.0 * fabs(z); + double omega; + if (z >= -15000.0) { + omega = 1.0; + } else if (z <= -15000.0 && z >= -20000.0) { + omega = (20000.0 - fabs(z)) / 5000.0; + } else { + omega = 0.0; + } - double* stress = params + 3; + double* stress = params + 3; - stress[2] = -2670.0 * 9.8 * fabs(z); - stress[0] = omega * (b11 * (stress[2] + Pf) - Pf) + (1.0 - omega) * stress[2]; - stress[1] = omega * (b33 * (stress[2] + Pf) - Pf) + (1.0 - omega) * stress[2]; - stress[3] = omega * (b13 * (stress[2] + Pf)); - stress[4] = 0.0; - stress[5] = 0.0; + stress[2] = -2670.0 * 9.8 * fabs(z); + stress[0] = omega * (b11 * (stress[2] + Pf) - Pf) + (1.0 - omega) * stress[2]; + stress[1] = omega * (b33 * (stress[2] + Pf) - Pf) + (1.0 - omega) * stress[2]; + stress[3] = omega * (b13 * (stress[2] + Pf)); + stress[4] = 0.0; + stress[5] = 0.0; - stress[0] += Pf; - stress[1] += Pf; - stress[2] += Pf; + stress[0] += Pf; + stress[1] += Pf; + stress[2] += Pf; } -void assertEqual(double z, unsigned index, std::vector> const& material) { - double params[9]; - model(z, params); +void assertEqual(double z, unsigned index, const std::vector>& material) { + double params[9]; + model(z, params); - for (unsigned i = 0; i < 9; ++i) { - assert(equal(material[i][index], params[i], std::numeric_limits::epsilon())); - } + for (unsigned i = 0; i < 9; ++i) { + assert(equal(material[i][index], params[i], std::numeric_limits::epsilon())); + } } int main(int argc, char** argv) { - assert(argc == 2); + assert(argc == 2); - easi::Query query = createQuery<3>({{1, {3.0, 0.0, -20000.0}}, - {1, {-5.0, -100.0, -16000.0}}, - {1, {9.0, -1000.0, 100000.0}}, - {1, {9.0, -1000.0, -100000.0}}}); + easi::Query query = createQuery<3>({{1, {3.0, 0.0, -20000.0}}, + {1, {-5.0, -100.0, -16000.0}}, + {1, {9.0, -1000.0, 100000.0}}, + {1, {9.0, -1000.0, -100000.0}}}); - std::vector parameters{"rho", "mu", "lambda", "s_xx", "s_yy", - "s_zz", "s_xy", "s_yz", "s_xz"}; - auto material = genericModel(argv[1], query, parameters); + std::vector parameters{ + "rho", "mu", "lambda", "s_xx", "s_yy", "s_zz", "s_xy", "s_yz", "s_xz"}; + auto material = genericModel(argv[1], query, parameters); - assertEqual(-20000.0, 0, material); - assertEqual(-16000.0, 1, material); - assertEqual(100000.0, 2, material); - assertEqual(-100000.0, 3, material); + assertEqual(-20000.0, 0, material); + assertEqual(-16000.0, 1, material); + assertEqual(100000.0, 2, material); + assertEqual(-100000.0, 3, material); - return 0; + return 0; } diff --git a/tests/2_prem.cpp b/tests/2_prem.cpp index f1eab86..d65c31a 100644 --- a/tests/2_prem.cpp +++ b/tests/2_prem.cpp @@ -1,4 +1,5 @@ #include "easitest.h" + #include /* Uses error propagation rules from http://lectureonline.cl.msu.edu/~mmp/labs/error/e2.htm @@ -8,65 +9,64 @@ * (2*rho*vs*dvs)^2 + (4*rho*vp*dvp)^2] */ class Converter { -public: - Converter(double rho, double vp, double vs, double d) - : m_rho(rho), m_vp(vp), m_vs(vs), m_d(d) {} + public: + Converter(double rho, double vp, double vs, double d) : m_rho(rho), m_vp(vp), m_vs(vs), m_d(d) {} - double rho() const { return 1.0e3 * m_rho; } - double mu() const { return 1.0e9 * m_rho * pow(m_vs, 2.); } - double lambda() const { return 1.0e9 * m_rho * (pow(m_vp, 2.) - 2. * pow(m_vs, 2.)); } + double rho() const { return 1.0e3 * m_rho; } + double mu() const { return 1.0e9 * m_rho * pow(m_vs, 2.); } + double lambda() const { return 1.0e9 * m_rho * (pow(m_vp, 2.) - 2. * pow(m_vs, 2.)); } - double drho() const { return 1.0e3 * m_d; } - double dmu() const { - return 1.0e9 * sqrt(pow(pow(m_vs, 2.) * m_d, 2.) + pow(2.0 * m_rho * m_vs * m_d, 2.)); - } - double dlambda() const { - return 1.0e9 * - sqrt(pow((pow(m_vp, 2.) - 2. * pow(m_vs, 2.)) * m_d, 2.) + - pow(2.0 * m_rho * m_vp * m_d, 2.) + pow(-2.0 * 2.0 * m_rho * m_vs * m_d, 2.)); - } + double drho() const { return 1.0e3 * m_d; } + double dmu() const { + return 1.0e9 * sqrt(pow(pow(m_vs, 2.) * m_d, 2.) + pow(2.0 * m_rho * m_vs * m_d, 2.)); + } + double dlambda() const { + return 1.0e9 * + sqrt(pow((pow(m_vp, 2.) - 2. * pow(m_vs, 2.)) * m_d, 2.) + + pow(2.0 * m_rho * m_vp * m_d, 2.) + pow(-2.0 * 2.0 * m_rho * m_vs * m_d, 2.)); + } -private: - double m_rho, m_vp, m_vs, m_d; + private: + double m_rho, m_vp, m_vs, m_d; }; -void assertEqual(ElasticMaterial const& material, Converter const& converter) { - assert(equal(material.rho, converter.rho(), converter.drho())); - assert(equal(material.mu, converter.mu(), converter.dmu())); - assert(equal(material.lambda, converter.lambda(), converter.dlambda())); +void assertEqual(const ElasticMaterial& material, const Converter& converter) { + assert(equal(material.rho, converter.rho(), converter.drho())); + assert(equal(material.mu, converter.mu(), converter.dmu())); + assert(equal(material.lambda, converter.lambda(), converter.dlambda())); } int main(int argc, char** argv) { - assert(argc == 2); + assert(argc == 2); - easi::Query query = createQuery<3>({ - {1, {1000000.0, 0.0, 0.0}}, // Inner core - {1, {2000000.0, 0.0, 0.0}}, // Outer core - {1, {3500000.0, 0.0, 0.0}}, // Lower mantle (1) - {1, {4000000.0, 0.0, 0.0}}, // Lower mantle (2) - {1, {5650000.0, 0.0, 0.0}}, // Lower mantle (3) - {1, {5736000.0, 0.0, 0.0}}, // Transition zone (1) - {1, {5821000.0, 0.0, 0.0}}, // Transition zone (2) - {1, {6016000.0, 0.0, 0.0}}, // Transition zone (3) - {1, {6356000.0, 0.0, 0.0}}, // Crust (1) - {1, {6368000.0, 0.0, 0.0}}, // Crust (2) - {1, {6371000.0, 0.0, 0.0}} // Ocean - }); + easi::Query query = createQuery<3>({ + {1, {1000000.0, 0.0, 0.0}}, // Inner core + {1, {2000000.0, 0.0, 0.0}}, // Outer core + {1, {3500000.0, 0.0, 0.0}}, // Lower mantle (1) + {1, {4000000.0, 0.0, 0.0}}, // Lower mantle (2) + {1, {5650000.0, 0.0, 0.0}}, // Lower mantle (3) + {1, {5736000.0, 0.0, 0.0}}, // Transition zone (1) + {1, {5821000.0, 0.0, 0.0}}, // Transition zone (2) + {1, {6016000.0, 0.0, 0.0}}, // Transition zone (3) + {1, {6356000.0, 0.0, 0.0}}, // Crust (1) + {1, {6368000.0, 0.0, 0.0}}, // Crust (2) + {1, {6371000.0, 0.0, 0.0}} // Ocean + }); - auto material = elasticModel(argv[1], query); + auto material = elasticModel(argv[1], query); - // Assertions are based on tables given in Dziewonski and Anderson paper. - assertEqual(material[0], Converter(12.87073, 11.10542, 3.55823, 1e-4)); // r=1000000 - assertEqual(material[1], Converter(11.65478, 9.83496, 0.0, 1e-4)); // r=2000000 - assertEqual(material[2], Converter(5.55641, 13.71168, 7.26486, 1e-4)); // r=3500000 - assertEqual(material[3], Converter(5.30724, 13.24532, 7.09974, 1e-4)); // r=4000000 - assertEqual(material[4], Converter(4.41241, 10.91005, 6.09418, 1e-4)); // r=5650000 - assertEqual(material[5], Converter(3.98399, 10.21203, 5.54311, 1e-4)); // r=5736000 - assertEqual(material[6], Converter(3.91282, 9.90185, 5.37014, 1e-4)); // r=5821000 - assertEqual(material[7], Converter(3.51639, 8.81867, 4.73840, 1e-4)); // r=6016000 - assertEqual(material[8], Converter(2.90000, 6.80000, 3.90000, 1e-4)); // r=6356000 - assertEqual(material[9], Converter(2.60000, 5.80000, 3.20000, 1e-4)); // r=6368000 - assertEqual(material[10], Converter(1.02000, 1.45000, 0.0, 1e-4)); // r=6371000 + // Assertions are based on tables given in Dziewonski and Anderson paper. + assertEqual(material[0], Converter(12.87073, 11.10542, 3.55823, 1e-4)); // r=1000000 + assertEqual(material[1], Converter(11.65478, 9.83496, 0.0, 1e-4)); // r=2000000 + assertEqual(material[2], Converter(5.55641, 13.71168, 7.26486, 1e-4)); // r=3500000 + assertEqual(material[3], Converter(5.30724, 13.24532, 7.09974, 1e-4)); // r=4000000 + assertEqual(material[4], Converter(4.41241, 10.91005, 6.09418, 1e-4)); // r=5650000 + assertEqual(material[5], Converter(3.98399, 10.21203, 5.54311, 1e-4)); // r=5736000 + assertEqual(material[6], Converter(3.91282, 9.90185, 5.37014, 1e-4)); // r=5821000 + assertEqual(material[7], Converter(3.51639, 8.81867, 4.73840, 1e-4)); // r=6016000 + assertEqual(material[8], Converter(2.90000, 6.80000, 3.90000, 1e-4)); // r=6356000 + assertEqual(material[9], Converter(2.60000, 5.80000, 3.20000, 1e-4)); // r=6368000 + assertEqual(material[10], Converter(1.02000, 1.45000, 0.0, 1e-4)); // r=6371000 - return 0; + return 0; } diff --git a/tests/33_layered_constant.cpp b/tests/33_layered_constant.cpp index 41e507c..6682f59 100644 --- a/tests/33_layered_constant.cpp +++ b/tests/33_layered_constant.cpp @@ -1,44 +1,44 @@ #include "easitest.h" void model(double y, double params[3]) { - params[0] = 2670.0; - if (y <= -800.0) { - params[1] = 2.816717568E+10; - params[2] = 2.817615756E+10; - } else if (y >= -800.0 && y <= 800.0) { - params[1] = 1.251489075E+10; - params[2] = 1.251709350E+10; - } else { - params[1] = 3.203812032E+10; - params[2] = 3.204375936E+10; - } + params[0] = 2670.0; + if (y <= -800.0) { + params[1] = 2.816717568E+10; + params[2] = 2.817615756E+10; + } else if (y >= -800.0 && y <= 800.0) { + params[1] = 1.251489075E+10; + params[2] = 1.251709350E+10; + } else { + params[1] = 3.203812032E+10; + params[2] = 3.204375936E+10; + } } -void assertEqual(double y, ElasticMaterial const& material) { - double params[3]; - model(y, params); +void assertEqual(double y, const ElasticMaterial& material) { + double params[3]; + model(y, params); - assert(equal(material.rho, params[0])); - assert(equal(material.mu, params[1])); - assert(equal(material.lambda, params[2])); + assert(equal(material.rho, params[0])); + assert(equal(material.mu, params[1])); + assert(equal(material.lambda, params[2])); } int main(int argc, char** argv) { - assert(argc == 2); + assert(argc == 2); - easi::Query query = createQuery<3>({{1, {0.0, -1000.0, 0.0}}, - {1, {0.0, -800.0, 0.0}}, - {1, {0.0, 0.0, 0.0}}, - {1, {0.0, 800.0, 0.0}}, - {1, {0.0, 1000.0, 0.0}}}); + easi::Query query = createQuery<3>({{1, {0.0, -1000.0, 0.0}}, + {1, {0.0, -800.0, 0.0}}, + {1, {0.0, 0.0, 0.0}}, + {1, {0.0, 800.0, 0.0}}, + {1, {0.0, 1000.0, 0.0}}}); - auto material = elasticModel(argv[1], query); + auto material = elasticModel(argv[1], query); - assertEqual(-1000.0, material[0]); - assertEqual(-800.0, material[1]); - assertEqual(0.0, material[2]); - assertEqual(800.0, material[3]); - assertEqual(1000.0, material[4]); + assertEqual(-1000.0, material[0]); + assertEqual(-800.0, material[1]); + assertEqual(0.0, material[2]); + assertEqual(800.0, material[3]); + assertEqual(1000.0, material[4]); - return 0; + return 0; } diff --git a/tests/3_layered_linear.cpp b/tests/3_layered_linear.cpp index 3187022..ab7e7f6 100644 --- a/tests/3_layered_linear.cpp +++ b/tests/3_layered_linear.cpp @@ -1,37 +1,37 @@ #include "easitest.h" int main(int argc, char** argv) { - assert(argc == 2); + assert(argc == 2); - easi::Query query = createQuery<3>({ - {1, {0.0, 0.0, 0.0}}, - {1, {0.0, 0.0, -2000.0}}, - {1, {0.0, 0.0, -2100.0}}, - {1, {0.0, 0.0, -2500.0}}, - {1, {0.0, 0.0, -50000.0}}, - }); + easi::Query query = createQuery<3>({ + {1, {0.0, 0.0, 0.0}}, + {1, {0.0, 0.0, -2000.0}}, + {1, {0.0, 0.0, -2100.0}}, + {1, {0.0, 0.0, -2500.0}}, + {1, {0.0, 0.0, -50000.0}}, + }); - auto material = elasticModel(argv[1], query); + auto material = elasticModel(argv[1], query); - assert(equal(material[0].rho, 2600.0)); - assert(equal(material[0].mu, 1.04e10)); - assert(equal(material[0].lambda, 2.08e10)); + assert(equal(material[0].rho, 2600.0)); + assert(equal(material[0].mu, 1.04e10)); + assert(equal(material[0].lambda, 2.08e10)); - assert(equal(material[1].rho, 2700.0)); - assert(equal(material[1].mu, 3.24e10)); - assert(equal(material[1].lambda, 3.24e10)); + assert(equal(material[1].rho, 2700.0)); + assert(equal(material[1].mu, 3.24e10)); + assert(equal(material[1].lambda, 3.24e10)); - assert(equal(material[2].rho, 2730.0)); - assert(equal(material[2].mu, 3.396e10)); - assert(equal(material[2].lambda, 3.036e10)); + assert(equal(material[2].rho, 2730.0)); + assert(equal(material[2].mu, 3.396e10)); + assert(equal(material[2].lambda, 3.036e10)); - assert(equal(material[3].rho, 2850.0)); - assert(equal(material[3].mu, 4.02e10)); - assert(equal(material[3].lambda, 2.22e10)); + assert(equal(material[3].rho, 2850.0)); + assert(equal(material[3].mu, 4.02e10)); + assert(equal(material[3].lambda, 2.22e10)); - assert(equal(material[4].rho, 3000.0)); - assert(equal(material[4].mu, 4.80e10)); - assert(equal(material[4].lambda, 1.20e10)); + assert(equal(material[4].rho, 3000.0)); + assert(equal(material[4].mu, 4.80e10)); + assert(equal(material[4].lambda, 1.20e10)); - return 0; + return 0; } diff --git a/tests/4_lua.cpp b/tests/4_lua.cpp index 63e4bd5..981e473 100644 --- a/tests/4_lua.cpp +++ b/tests/4_lua.cpp @@ -1,34 +1,33 @@ #include "easitest.h" + #include double rho(double y) { return 1600. + 59.5 * pow(y, 1. / 3.); } double lambda(double y) { return pow(260. + 30 * sqrt(y), 2.) * (1600. + 59.5 * pow(y, 1. / 3.)); } int main(int argc, char** argv) { - assert(argc == 2); + assert(argc == 2); - easi::Query query = createQuery<3>({{7, {0.0, 0.0, 0.0}}, - {5, {0.0, 10.0, 0.0}}, - {4, {0.0, 20.0, 0.0}}, - {3, {0.0, 25.0, 0.0}}}); + easi::Query query = createQuery<3>( + {{7, {0.0, 0.0, 0.0}}, {5, {0.0, 10.0, 0.0}}, {4, {0.0, 20.0, 0.0}}, {3, {0.0, 25.0, 0.0}}}); - auto material = elasticModel(argv[1], query); + auto material = elasticModel(argv[1], query); - assert(equal(material[0].rho, 2500.0)); - assert(equal(material[0].mu, 0.0)); - assert(equal(material[0].lambda, 1.96e10)); + assert(equal(material[0].rho, 2500.0)); + assert(equal(material[0].mu, 0.0)); + assert(equal(material[0].lambda, 1.96e10)); - assert(equal(material[1].rho, rho(10.0))); - assert(equal(material[1].mu, 0.0)); - assert(equal(material[1].lambda, lambda(10.0))); + assert(equal(material[1].rho, rho(10.0))); + assert(equal(material[1].mu, 0.0)); + assert(equal(material[1].lambda, lambda(10.0))); - assert(equal(material[2].rho, rho(20.0))); - assert(equal(material[2].mu, 0.0)); - assert(equal(material[2].lambda, lambda(20.0))); + assert(equal(material[2].rho, rho(20.0))); + assert(equal(material[2].mu, 0.0)); + assert(equal(material[2].lambda, lambda(20.0))); - assert(equal(material[3].rho, rho(25.0))); - assert(equal(material[3].mu, 0.0)); - assert(equal(material[3].lambda, lambda(25.0))); + assert(equal(material[3].rho, rho(25.0))); + assert(equal(material[3].mu, 0.0)); + assert(equal(material[3].lambda, lambda(25.0))); - return 0; + return 0; } diff --git a/tests/5_function.cpp b/tests/5_function.cpp index 2108d21..3f07f2d 100644 --- a/tests/5_function.cpp +++ b/tests/5_function.cpp @@ -1,4 +1,5 @@ #include "easitest.h" + #include double rho(double y) { return 1600. + 59.5 * pow(y, 1. / 3.); } @@ -6,30 +7,28 @@ double rho(double y) { return 1600. + 59.5 * pow(y, 1. / 3.); } double lambda(double y) { return pow(260. + 30 * sqrt(y), 2.) * (1600. + 59.5 * pow(y, 1. / 3.)); } int main(int argc, char** argv) { - assert(argc == 2); + assert(argc == 2); - easi::Query query = createQuery<3>({{7, {0.0, 0.0, 0.0}}, - {5, {0.0, 10.0, 0.0}}, - {4, {0.0, 20.0, 0.0}}, - {3, {0.0, 25.0, 0.0}}}); + easi::Query query = createQuery<3>( + {{7, {0.0, 0.0, 0.0}}, {5, {0.0, 10.0, 0.0}}, {4, {0.0, 20.0, 0.0}}, {3, {0.0, 25.0, 0.0}}}); - auto material = elasticModel(argv[1], query); + auto material = elasticModel(argv[1], query); - assert(equal(material[0].rho, 2500.0)); - assert(equal(material[0].mu, 0.0)); - assert(equal(material[0].lambda, 1.96e10)); + assert(equal(material[0].rho, 2500.0)); + assert(equal(material[0].mu, 0.0)); + assert(equal(material[0].lambda, 1.96e10)); - assert(equal(material[1].rho, rho(10.0))); - assert(equal(material[1].mu, 0.0)); - assert(equal(material[1].lambda, lambda(10.0))); + assert(equal(material[1].rho, rho(10.0))); + assert(equal(material[1].mu, 0.0)); + assert(equal(material[1].lambda, lambda(10.0))); - assert(equal(material[2].rho, rho(20.0))); - assert(equal(material[2].mu, 0.0)); - assert(equal(material[2].lambda, lambda(20.0))); + assert(equal(material[2].rho, rho(20.0))); + assert(equal(material[2].mu, 0.0)); + assert(equal(material[2].lambda, lambda(20.0))); - assert(equal(material[3].rho, rho(25.0))); - assert(equal(material[3].mu, 0.0)); - assert(equal(material[3].lambda, lambda(25.0))); + assert(equal(material[3].rho, rho(25.0))); + assert(equal(material[3].mu, 0.0)); + assert(equal(material[3].lambda, lambda(25.0))); - return 0; + return 0; } diff --git a/tests/6_lua.cpp b/tests/6_lua.cpp index 20f2d4d..1f93e0e 100644 --- a/tests/6_lua.cpp +++ b/tests/6_lua.cpp @@ -1,34 +1,30 @@ #include "easitest.h" + #include double effectiveConfiningStress(double z) { - const double elevation = 100; - return 2670.0 * 0.21 * 9.8 * std::min(-100.0, elevation + z); + const double elevation = 100; + return 2670.0 * 0.21 * 9.8 * std::min(-100.0, elevation + z); } int main(int argc, char** argv) { - assert(argc == 2); - - easi::Query query = createQuery<3>({ - {0, {0.0, 0.0, -180.0}}, - {0, {0.0, 0.0, -190.0}}, - {0, {0.0, 0.0, -200.0}}, - {0, {0.0, 0.0, -210.0}}, - {0, {0.0, 0.0, -220.0}}, - {0, {0.0, 0.0, -230.0}} - }); - std::vector parameters{"effectiveConfiningStress"}; - auto stress = genericModel(argv[1], query, parameters); - - double curVal = -180; - for (auto& s : stress[0]) { - constexpr double eps = 10e-15; - assert(std::abs(s - effectiveConfiningStress(curVal)) <= eps); - curVal -= 10.0; - } - - - - return 0; + assert(argc == 2); + + easi::Query query = createQuery<3>({{0, {0.0, 0.0, -180.0}}, + {0, {0.0, 0.0, -190.0}}, + {0, {0.0, 0.0, -200.0}}, + {0, {0.0, 0.0, -210.0}}, + {0, {0.0, 0.0, -220.0}}, + {0, {0.0, 0.0, -230.0}}}); + std::vector parameters{"effectiveConfiningStress"}; + auto stress = genericModel(argv[1], query, parameters); + + double curVal = -180; + for (auto& s : stress[0]) { + constexpr double eps = 10e-15; + assert(std::abs(s - effectiveConfiningStress(curVal)) <= eps); + curVal -= 10.0; + } + + return 0; } - diff --git a/tests/easitest.cpp b/tests/easitest.cpp index b5e695f..e07516a 100644 --- a/tests/easitest.cpp +++ b/tests/easitest.cpp @@ -8,47 +8,47 @@ #include bool equal(double value, double ref, double eps) { - bool isEqual = fabs(ref - value) <= eps; - if (!isEqual) { - std::cerr << std::setprecision(16) << "Expected: " << ref << "; actual: " << value - << "; error: " << fabs(ref - value) << std::endl; - } - return isEqual; + bool isEqual = fabs(ref - value) <= eps; + if (!isEqual) { + std::cerr << std::setprecision(16) << "Expected: " << ref << "; actual: " << value + << "; error: " << fabs(ref - value) << std::endl; + } + return isEqual; } -std::vector elasticModel(std::string const& fileName, easi::Query& query) { - easi::YAMLParser parser(query.dimDomain()); - easi::Component* model = parser.parse(fileName); +std::vector elasticModel(const std::string& fileName, easi::Query& query) { + easi::YAMLParser parser(query.dimDomain()); + easi::Component* model = parser.parse(fileName); - std::vector material(query.numPoints()); - easi::ArrayOfStructsAdapter adapter(material.data()); - adapter.addBindingPoint("lambda", &ElasticMaterial::lambda); - adapter.addBindingPoint("mu", &ElasticMaterial::mu); - adapter.addBindingPoint("rho", &ElasticMaterial::rho); + std::vector material(query.numPoints()); + easi::ArrayOfStructsAdapter adapter(material.data()); + adapter.addBindingPoint("lambda", &ElasticMaterial::lambda); + adapter.addBindingPoint("mu", &ElasticMaterial::mu); + adapter.addBindingPoint("rho", &ElasticMaterial::rho); - model->evaluate(query, adapter); - delete model; + model->evaluate(query, adapter); + delete model; - return material; + return material; } -std::vector> genericModel(std::string const& fileName, easi::Query& query, - std::vector const& parameters) { - easi::YAMLParser parser(query.dimDomain()); - easi::Component* model = parser.parse(fileName); - - easi::ArraysAdapter<> adapter; - std::vector> material(parameters.size()); - auto it = material.begin(); - for (auto const& p : parameters) { - it->resize(query.numPoints()); - adapter.addBindingPoint(p, it->data()); - ++it; - } - - model->evaluate(query, adapter); - delete model; - - return material; +std::vector> genericModel(const std::string& fileName, + easi::Query& query, + const std::vector& parameters) { + easi::YAMLParser parser(query.dimDomain()); + easi::Component* model = parser.parse(fileName); + + easi::ArraysAdapter<> adapter; + std::vector> material(parameters.size()); + auto it = material.begin(); + for (const auto& p : parameters) { + it->resize(query.numPoints()); + adapter.addBindingPoint(p, it->data()); + ++it; + } + + model->evaluate(query, adapter); + delete model; + + return material; } - diff --git a/tests/easitest.h b/tests/easitest.h index 4521789..a027090 100644 --- a/tests/easitest.h +++ b/tests/easitest.h @@ -1,40 +1,48 @@ #ifndef EASITEST_H_ #define EASITEST_H_ +#include #include #include #include #include #include -#include struct ElasticMaterial { - double lambda, mu, rho; + double lambda, mu, rho; }; template -easi::Query createQuery(std::vector>> const& values) { - unsigned numPoints = values.size(); - easi::Query query(numPoints, DIM); - for (unsigned n = 0; n < numPoints; ++n) { - query.group(n) = values[n].first; - for (unsigned d = 0; d < DIM; ++d) { - query.x(n, d) = values[n].second[d]; - } +easi::Query createQuery(const std::vector>>& values) { + unsigned numPoints = values.size(); + easi::Query query(numPoints, DIM); + for (unsigned n = 0; n < numPoints; ++n) { + query.group(n) = values[n].first; + for (unsigned d = 0; d < DIM; ++d) { + query.x(n, d) = values[n].second[d]; } + } - return query; + return query; } bool equal(double v1, double v2, double eps = std::numeric_limits::epsilon()); -std::vector elasticModel(std::string const& fileName, easi::Query& query); -std::vector> genericModel(std::string const& fileName, easi::Query& query, - std::vector const& parameters); +std::vector elasticModel(const std::string& fileName, easi::Query& query); +std::vector> genericModel(const std::string& fileName, + easi::Query& query, + const std::vector& parameters); extern "C" { -extern void STRESS_STR_DIP_SLIP_AM(double mu_dy, double mu_st, double strike, double dip, - double sigmazz, double cohesion, double R, - double DipSlipFaulting, double s2ratio, double* bii); +extern void STRESS_STR_DIP_SLIP_AM(double mu_dy, + double mu_st, + double strike, + double dip, + double sigmazz, + double cohesion, + double R, + double DipSlipFaulting, + double s2ratio, + double* bii); } #endif diff --git a/tests/f_120_sumatra.cpp b/tests/f_120_sumatra.cpp index d50d057..8f30d0e 100644 --- a/tests/f_120_sumatra.cpp +++ b/tests/f_120_sumatra.cpp @@ -1,121 +1,122 @@ -#include "easitest.h" - #include "easi/component/Special.h" +#include "easitest.h" #include void model(double x, double y, double z, double params[6]) { - double xS1 = 5.0000000000e+05; - double yS1 = 4.4212739025e+05; - double xS2 = 4.4461626476e+05; - double yS2 = 6.0795713230e+05; - double strike; - if (y - yS1 < x - xS1) { - strike = 309.0; - } else if (y - yS2 < x - xS2) { - double alpha = ((y - x) - (yS1 - xS1)) / ((yS2 - xS2) - (yS1 - xS1)); - strike = (1.0 - alpha) * 309.0 + alpha * 330.0; - } else { - strike = 330.0; - } + double xS1 = 5.0000000000e+05; + double yS1 = 4.4212739025e+05; + double xS2 = 4.4461626476e+05; + double yS2 = 6.0795713230e+05; + double strike; + if (y - yS1 < x - xS1) { + strike = 309.0; + } else if (y - yS2 < x - xS2) { + double alpha = ((y - x) - (yS1 - xS1)) / ((yS2 - xS2) - (yS1 - xS1)); + strike = (1.0 - alpha) * 309.0 + alpha * 330.0; + } else { + strike = 330.0; + } - double bii[6]; - STRESS_STR_DIP_SLIP_AM(0.25, 0.3, strike, 8.0, 555562000.0, 0.4e6, 0.7, 1.0, 0.5, bii); + double bii[6]; + STRESS_STR_DIP_SLIP_AM(0.25, 0.3, strike, 8.0, 555562000.0, 0.4e6, 0.7, 1.0, 0.5, bii); - easi::STRESS_STR_DIP_SLIP_AM test; - test.i.mu_d = 0.25; - test.i.mu_s = 0.3; - test.i.strike = strike; - test.i.dip = 8.0; - test.i.s_zz = 555562000.0; - test.i.cohesion = 0.4e6; - test.i.R = 0.7; - test.i.DipSlipFaulting = 1.0; - test.i.s2ratio = 0.5; - test.evaluate(); - assert(equal(test.o.b_xx, bii[0])); - assert(equal(test.o.b_yy, bii[1])); - assert(equal(test.o.b_zz, bii[2])); - assert(equal(test.o.b_xy, bii[3])); - assert(equal(test.o.b_yz, bii[4])); - assert(equal(test.o.b_xz, bii[5])); + easi::STRESS_STR_DIP_SLIP_AM test; + test.i.mu_d = 0.25; + test.i.mu_s = 0.3; + test.i.strike = strike; + test.i.dip = 8.0; + test.i.s_zz = 555562000.0; + test.i.cohesion = 0.4e6; + test.i.R = 0.7; + test.i.DipSlipFaulting = 1.0; + test.i.s2ratio = 0.5; + test.evaluate(); + assert(equal(test.o.b_xx, bii[0])); + assert(equal(test.o.b_yy, bii[1])); + assert(equal(test.o.b_zz, bii[2])); + assert(equal(test.o.b_xy, bii[3])); + assert(equal(test.o.b_yz, bii[4])); + assert(equal(test.o.b_xz, bii[5])); - double const g = 9.8; - double layers[] = {0.0, -2000.0, -6000.0, -12000.0, -23000.0, -100.0e6}; - double rho[] = {1000.0, 2720.0, 2860.0, 3050.0, 3300.0, 3375.0}; - double sigzz = 0.0; - for (unsigned i = 1; i < sizeof(layers) / sizeof(double); ++i) { - if (z > layers[i]) { - sigzz += rho[i - 1] * (z - layers[i - 1]) * g; - break; - } else { - sigzz += rho[i - 1] * (layers[i] - layers[i - 1]) * g; - } - } - double alpha = 0.0; - if (z >= -5000.0) { - alpha = 0.0; - } else if (z >= -10000.0) { - alpha = -1.0 - z / 5000.0; + const double g = 9.8; + double layers[] = {0.0, -2000.0, -6000.0, -12000.0, -23000.0, -100.0e6}; + double rho[] = {1000.0, 2720.0, 2860.0, 3050.0, 3300.0, 3375.0}; + double sigzz = 0.0; + for (unsigned i = 1; i < sizeof(layers) / sizeof(double); ++i) { + if (z > layers[i]) { + sigzz += rho[i - 1] * (z - layers[i - 1]) * g; + break; } else { - alpha = 1.0; + sigzz += rho[i - 1] * (layers[i] - layers[i - 1]) * g; } - double Pf = -1000.0 * 9.8 * z * (1.0 + alpha); + } + double alpha = 0.0; + if (z >= -5000.0) { + alpha = 0.0; + } else if (z >= -10000.0) { + alpha = -1.0 - z / 5000.0; + } else { + alpha = 1.0; + } + double Pf = -1000.0 * 9.8 * z * (1.0 + alpha); - double Rz = 0.0; - if (z < -25000.0) { - Rz = (-z - 25000.0) / 150000.0; - } - double Omega = fmax(0.0, fmin(1.0, 1.0 - Rz)); + double Rz = 0.0; + if (z < -25000.0) { + Rz = (-z - 25000.0) / 150000.0; + } + double Omega = fmax(0.0, fmin(1.0, 1.0 - Rz)); - params[2] = sigzz; - params[0] = Omega * (bii[0] * (params[2] + Pf) - Pf) + (1.0 - Omega) * params[2]; - params[1] = Omega * (bii[1] * (params[2] + Pf) - Pf) + (1.0 - Omega) * params[2]; - params[3] = Omega * (bii[3] * (params[2] + Pf)); - params[4] = Omega * (bii[4] * (params[2] + Pf)); - params[5] = Omega * (bii[5] * (params[2] + Pf)); - params[0] += Pf; - params[1] += Pf; - params[2] += Pf; + params[2] = sigzz; + params[0] = Omega * (bii[0] * (params[2] + Pf) - Pf) + (1.0 - Omega) * params[2]; + params[1] = Omega * (bii[1] * (params[2] + Pf) - Pf) + (1.0 - Omega) * params[2]; + params[3] = Omega * (bii[3] * (params[2] + Pf)); + params[4] = Omega * (bii[4] * (params[2] + Pf)); + params[5] = Omega * (bii[5] * (params[2] + Pf)); + params[0] += Pf; + params[1] += Pf; + params[2] += Pf; } -void assertEqual(easi::Matrix const& x, unsigned index, - std::vector> const& material) { - double params[6]; - model(x(index, 0), x(index, 1), x(index, 2), params); +void assertEqual(const easi::Matrix& x, + unsigned index, + const std::vector>& material) { + double params[6]; + model(x(index, 0), x(index, 1), x(index, 2), params); - for (unsigned i = 0; i < 6; ++i) { - assert(equal(material[i][index], params[i], - std::max(1.e-6, 10.0 * fabs(std::numeric_limits::epsilon() * params[i])))); - } + for (unsigned i = 0; i < 6; ++i) { + assert(equal(material[i][index], + params[i], + std::max(1.e-6, 10.0 * fabs(std::numeric_limits::epsilon() * params[i])))); + } } int main(int argc, char** argv) { - assert(argc == 2); + assert(argc == 2); - easi::Query query = createQuery<3>({{1, {0.0, 0.0, -1400.0}}, - {1, {0.0, 0.0, -50000.0}}, - {1, {0.0, 0.0, -49000.0}}, - {1, {0.0, 0.0, -3000.0}}, - {1, {0.0, 0.0, -22000.0}}, - {1, {50000.0, 0.0, -1400.0}}, - {1, {50000.0, 0.0, -50000.0}}, - {1, {50000.0, 0.0, -49000.0}}, - {1, {50000.0, 0.0, -3000.0}}, - {1, {50000.0, 0.0, -22000.0}}, - {1, {0.0, 100000.0, -1400.0}}, - {1, {0.0, 100000.0, -50000.0}}, - {1, {0.0, 100000.0, -49000.0}}, - {1, {0.0, 100000.0, -3000.0}}, - {1, {0.0, 100000.0, -22000.0}}, - {1, {0.0, 0.0, 0.0}}}); - easi::Query queryRef = query; - std::vector parameters{"s_xx", "s_yy", "s_zz", "s_xy", "s_yz", "s_xz"}; - auto material = genericModel(argv[1], query, parameters); + easi::Query query = createQuery<3>({{1, {0.0, 0.0, -1400.0}}, + {1, {0.0, 0.0, -50000.0}}, + {1, {0.0, 0.0, -49000.0}}, + {1, {0.0, 0.0, -3000.0}}, + {1, {0.0, 0.0, -22000.0}}, + {1, {50000.0, 0.0, -1400.0}}, + {1, {50000.0, 0.0, -50000.0}}, + {1, {50000.0, 0.0, -49000.0}}, + {1, {50000.0, 0.0, -3000.0}}, + {1, {50000.0, 0.0, -22000.0}}, + {1, {0.0, 100000.0, -1400.0}}, + {1, {0.0, 100000.0, -50000.0}}, + {1, {0.0, 100000.0, -49000.0}}, + {1, {0.0, 100000.0, -3000.0}}, + {1, {0.0, 100000.0, -22000.0}}, + {1, {0.0, 0.0, 0.0}}}); + easi::Query queryRef = query; + std::vector parameters{"s_xx", "s_yy", "s_zz", "s_xy", "s_yz", "s_xz"}; + auto material = genericModel(argv[1], query, parameters); - for (unsigned i = 0; i < 15; ++i) { - assertEqual(query.x, i, material); - } + for (unsigned i = 0; i < 15; ++i) { + assertEqual(query.x, i, material); + } - return 0; + return 0; } diff --git a/tests/f_16_scec.cpp b/tests/f_16_scec.cpp index 24e45fd..33b7c26 100644 --- a/tests/f_16_scec.cpp +++ b/tests/f_16_scec.cpp @@ -1,74 +1,77 @@ #include "easitest.h" + #include void model(double x, double z, double params[9]) { - params[0] = 0.0; // s_xx - params[2] = 0.0; // s_zz - params[5] = 0.0; // s_xz - params[4] = 0.0; // s_yz - params[1] = -6.000000E+07; // s_yy - params[6] = 6.770000E-01; // mu_s - params[7] = 3.730000E-01; // mu_d - params[8] = 4.000000E-01; // d_c - params[10] = 1.000000E+09; // forced_rupture_time + params[0] = 0.0; // s_xx + params[2] = 0.0; // s_zz + params[5] = 0.0; // s_xz + params[4] = 0.0; // s_yz + params[1] = -6.000000E+07; // s_yy + params[6] = 6.770000E-01; // mu_s + params[7] = 3.730000E-01; // mu_d + params[8] = 4.000000E-01; // d_c + params[10] = 1.000000E+09; // forced_rupture_time - z *= -1.0; + z *= -1.0; - if (x <= 0.0 && z <= 0.0) { - params[3] = 2.509795E+07; // s_xy - params[9] = -4.000000E+06; // cohesion - } else if (x <= 75.0 && z <= 0.0) { - double xi = x / 75.0; - params[3] = 2.509795E+07 * (1.0 - xi) + 2.523141E+07 * xi; // s_xy - params[9] = -4.000000E+06; // cohesion - } else if (x >= 75.0 && x <= 150.0 && z >= 150.0 && z <= 225.0) { - double xi = (x - 75.0) / 75.0; - double eta = (z - 150.0) / 75.0; - params[3] = (2.444593E+07 * (1.0 - eta) + 2.445351E+07 * eta) * (1.0 - xi) + - (2.488395E+07 * (1.0 - eta) + 2.498051E+07 * eta) * xi; // s_xy - params[9] = -((3.800000E+06 * (1.0 - eta) + 3.700000E+06 * eta) * (1.0 - xi) + - (3.800000E+06 * (1.0 - eta) + 3.700000E+06 * eta) * xi); // cohesion - } else { - params[3] = 2.498051E+07; // s_xy - params[9] = -3.700000E+06; // cohesion - } + if (x <= 0.0 && z <= 0.0) { + params[3] = 2.509795E+07; // s_xy + params[9] = -4.000000E+06; // cohesion + } else if (x <= 75.0 && z <= 0.0) { + double xi = x / 75.0; + params[3] = 2.509795E+07 * (1.0 - xi) + 2.523141E+07 * xi; // s_xy + params[9] = -4.000000E+06; // cohesion + } else if (x >= 75.0 && x <= 150.0 && z >= 150.0 && z <= 225.0) { + double xi = (x - 75.0) / 75.0; + double eta = (z - 150.0) / 75.0; + params[3] = (2.444593E+07 * (1.0 - eta) + 2.445351E+07 * eta) * (1.0 - xi) + + (2.488395E+07 * (1.0 - eta) + 2.498051E+07 * eta) * xi; // s_xy + params[9] = -((3.800000E+06 * (1.0 - eta) + 3.700000E+06 * eta) * (1.0 - xi) + + (3.800000E+06 * (1.0 - eta) + 3.700000E+06 * eta) * xi); // cohesion + } else { + params[3] = 2.498051E+07; // s_xy + params[9] = -3.700000E+06; // cohesion + } } -void assertEqual(double x, double z, unsigned index, - std::vector> const& material) { - double params[11]; - model(x, z, params); +void assertEqual(double x, + double z, + unsigned index, + const std::vector>& material) { + double params[11]; + model(x, z, params); - for (unsigned i = 0; i < 11; ++i) { - assert(equal(material[i][index], params[i], - fabs(std::numeric_limits::epsilon() * params[i]))); - } + for (unsigned i = 0; i < 11; ++i) { + assert(equal( + material[i][index], params[i], fabs(std::numeric_limits::epsilon() * params[i]))); + } } int main(int argc, char** argv) { - assert(argc == 2); + assert(argc == 2); - easi::Query query = createQuery<3>({{1, {-5.0, 0.0, 5.0}}, - {1, {25.0, 0.0, 5.0}}, - {1, {100.0, 0.0, -200.0}}, - {1, {1000.0, 0.0, -1000.0}}}); - std::vector parameters{"s_xx", - "s_yy", - "s_zz", - "s_xy", - "s_yz", - "s_xz", - "mu_s", - "mu_d", - "d_c", - "cohesion", - "forced_rupture_time"}; - auto material = genericModel(argv[1], query, parameters); + easi::Query query = createQuery<3>({{1, {-5.0, 0.0, 5.0}}, + {1, {25.0, 0.0, 5.0}}, + {1, {100.0, 0.0, -200.0}}, + {1, {1000.0, 0.0, -1000.0}}}); + std::vector parameters{"s_xx", + "s_yy", + "s_zz", + "s_xy", + "s_yz", + "s_xz", + "mu_s", + "mu_d", + "d_c", + "cohesion", + "forced_rupture_time"}; + auto material = genericModel(argv[1], query, parameters); - assertEqual(-5.0, 5.0, 0, material); - assertEqual(25.0, 5.0, 1, material); - assertEqual(100.0, -200.0, 2, material); - assertEqual(1000.0, -1000.0, 3, material); + assertEqual(-5.0, 5.0, 0, material); + assertEqual(25.0, 5.0, 1, material); + assertEqual(100.0, -200.0, 2, material); + assertEqual(1000.0, -1000.0, 3, material); - return 0; + return 0; } diff --git a/tests/supplied_parameters.cpp b/tests/supplied_parameters.cpp index 00c4b2f..23fa34e 100644 --- a/tests/supplied_parameters.cpp +++ b/tests/supplied_parameters.cpp @@ -1,23 +1,36 @@ #include "easi/YAMLParser.h" + #include int main(int argc, char** argv) { - assert(argc == 2); + assert(argc == 2); - easi::YAMLParser parser(3); - easi::Component* model = parser.parse(argv[1]); + easi::YAMLParser parser(3); + easi::Component* model = parser.parse(argv[1]); - std::set supplied = model->suppliedParameters(); - std::set expected = {"rho", "mu", "lambda", "plastCo", "bulkFriction", "s_xx", - "s_yy", "s_zz", "s_xy", "s_yz", "s_xz"}; + std::set supplied = model->suppliedParameters(); + std::set expected = {"rho", + "mu", + "lambda", + "plastCo", + "bulkFriction", + "s_xx", + "s_yy", + "s_zz", + "s_xy", + "s_yz", + "s_xz"}; - std::set missing; - std::set_difference(expected.begin(), expected.end(), supplied.begin(), supplied.end(), - std::inserter(missing, missing.begin())); + std::set missing; + std::set_difference(expected.begin(), + expected.end(), + supplied.begin(), + supplied.end(), + std::inserter(missing, missing.begin())); - assert(missing.empty()); + assert(missing.empty()); - delete model; + delete model; - return 0; + return 0; } diff --git a/tools/benchmark.py b/tools/benchmark.py index 2c3d916..6d435db 100755 --- a/tools/benchmark.py +++ b/tools/benchmark.py @@ -5,36 +5,38 @@ import subprocess cmdLineParser = argparse.ArgumentParser() -cmdLineParser.add_argument('-N', type=int, required=True) -cmdLineParser.add_argument('--easicube', type=str, default='../build/easicube') -cmdLineParser.add_argument('--example_dir', type=str, default='../examples') +cmdLineParser.add_argument("-N", type=int, required=True) +cmdLineParser.add_argument("--easicube", type=str, default="../build/easicube") +cmdLineParser.add_argument("--example_dir", type=str, default="../examples") args = cmdLineParser.parse_args() + class Example(object): def __init__(self, name, frm, to): self.name = name self.frm = frm self.to = to + examples = [ - Example('0_constant', [0.0, 0.0, 0.0], [1.0, 1.0, 1.0]), - Example('2_prem', [0.0, 0.0, 0.0], [3678298.565, 3678298.565, 3678298.565]), - Example('3_layered_linear', [0.0, 0.0, -4000.0], [1.0, 1.0, 0.0]), - Example('5_function', [0.0, 0.0, 0.0], [1.0, 25.0, 1.0]), - Example('26_function', [-10.0, -1000.0, -100000.0], [10.0, 0.0, 100000.0]), - Example('33_layered_constant', [0.0, -1000.0, 0.0], [1.0, 1000.0, 1.0]), - Example('f_16_scec', [-5.0, 0.0, -1000.0], [1000.0, 1.0, 5.0]), - Example('f_120_sumatra', [0.0, 0.0, -50000.0], [50000.0, 100000.0, 0.0]) + Example("0_constant", [0.0, 0.0, 0.0], [1.0, 1.0, 1.0]), + Example("2_prem", [0.0, 0.0, 0.0], [3678298.565, 3678298.565, 3678298.565]), + Example("3_layered_linear", [0.0, 0.0, -4000.0], [1.0, 1.0, 0.0]), + Example("5_function", [0.0, 0.0, 0.0], [1.0, 25.0, 1.0]), + Example("26_function", [-10.0, -1000.0, -100000.0], [10.0, 0.0, 100000.0]), + Example("33_layered_constant", [0.0, -1000.0, 0.0], [1.0, 1000.0, 1.0]), + Example("f_16_scec", [-5.0, 0.0, -1000.0], [1000.0, 1.0, 5.0]), + Example("f_120_sumatra", [0.0, 0.0, -50000.0], [50000.0, 100000.0, 0.0]), ] -print('example,npars,npoints,tsetup,teval') +print("example,npars,npoints,tsetup,teval") for example in examples: - print(example.name, end=',', flush=True) - spec = '{{from: [{}], to: [{}], N: [{}]}}'.format( - ','.join(map(str, example.frm)), - ','.join(map(str, example.to)), - ','.join(map(str, [args.N]*len(example.frm))) - ) - fileName = os.path.join(args.example_dir, example.name + '.yaml') + print(example.name, end=",", flush=True) + spec = "{{from: [{}], to: [{}], N: [{}]}}".format( + ",".join(map(str, example.frm)), + ",".join(map(str, example.to)), + ",".join(map(str, [args.N] * len(example.frm))), + ) + fileName = os.path.join(args.example_dir, example.name + ".yaml") subprocess.run([args.easicube, spec, fileName]) diff --git a/tools/easicube.cpp b/tools/easicube.cpp index 18bfd58..d446dfe 100644 --- a/tools/easicube.cpp +++ b/tools/easicube.cpp @@ -5,237 +5,233 @@ #include "easi/util/Matrix.h" #include "easi/util/Vector.h" -#include -#include -#include -#include - #include #include #include #include #include // IWYU pragma: keep #include +#include #include #include #include #include +#include +#include +#include #ifdef EASI_USE_ASAGI #include "mpi.h" #else -void MPI_Init(int *argc, char ***argv) {}; +void MPI_Init(int* argc, char*** argv) {}; void MPI_Finalize() {}; #endif void check_err(int const stat, int const line, char const* file) { - if (stat != NC_NOERR) { - fprintf(stderr, "line %d of %s: %s\n", line, file, nc_strerror(stat)); - fflush(stderr); - exit(1); - } + if (stat != NC_NOERR) { + fprintf(stderr, "line %d of %s: %s\n", line, file, nc_strerror(stat)); + fflush(stderr); + exit(1); + } } int main(int argc, char** argv) { - MPI_Init(&argc, &argv); - if (argc < 3) { - std::cerr << "Usage: easicube \"{from: [...], to: [...], N: [...], parameters: [...], " - "group: ...}\" []" - << std::endl; - std::cerr << " from, to: corner points of cube" << std::endl; - std::cerr << " N: number of grid points in each dimension" << std::endl; - std::cerr << " parameters: parameters that shall be queried from the model (optional)" - << std::endl; - std::cerr << " group: group number (optional)" << std::endl; - return -1; + MPI_Init(&argc, &argv); + if (argc < 3) { + std::cerr << "Usage: easicube \"{from: [...], to: [...], N: [...], parameters: [...], " + "group: ...}\" []" + << std::endl; + std::cerr << " from, to: corner points of cube" << std::endl; + std::cerr << " N: number of grid points in each dimension" << std::endl; + std::cerr << " parameters: parameters that shall be queried from the model (optional)" + << std::endl; + std::cerr << " group: group number (optional)" << std::endl; + return -1; + } + std::string modelFile(argv[2]); + std::string basename; + if (argc >= 4) { + basename = std::string(argv[3]); + } + + std::vector from, to; + std::vector N; + YAML::Node config = YAML::Load(argv[1]); + try { + from = config["from"].as>(); + to = config["to"].as>(); + N = config["N"].as>(); + } catch (std::exception& e) { + std::cerr << "Error while parsing required arguments from, to, and N: " << e.what() + << std::endl; + return -1; + } + unsigned group = 0; + if (config["group"]) { + group = config["group"].as(); + } + std::vector parameters; + if (config["parameters"]) { + parameters = config["parameters"].as>(); + } + + if (from.size() != 3 || to.size() != 3 || N.size() != 3) { + std::cerr << "from, to, and N must have 3 dimensions" << std::endl; + return -1; + } + for (unsigned n : N) { + if (n < 2) { + std::cerr << "number of grid points in each dimension should be greater than 1" << std::endl; + return -1; } - std::string modelFile(argv[2]); - std::string basename; - if (argc >= 4) { - basename = std::string(argv[3]); + } + unsigned nGP = 1; + for (unsigned n : N) { + nGP *= n; + } + unsigned dim = N.size(); + + std::vector h; + for (unsigned d = 0; d < dim; ++d) { + h.push_back((to[d] - from[d]) / (N[d] - 1)); + } + + auto parseStart = std::chrono::high_resolution_clock::now(); + auto parser = easi::YAMLParser(dim); + easi::Component* model = parser.parse(modelFile); + auto parseEnd = std::chrono::high_resolution_clock::now(); + + auto query = easi::Query(nGP, dim); + for (unsigned k = 0; k < N[2]; ++k) { + for (unsigned j = 0; j < N[1]; ++j) { + for (unsigned i = 0; i < N[0]; ++i) { + unsigned index = i + j * N[0] + k * N[0] * N[1]; + query.group(index) = group; + query.x(index, 0) = from[0] + i * h[0]; + query.x(index, 1) = from[1] + j * h[1]; + query.x(index, 2) = from[2] + k * h[2]; + } } - - std::vector from, to; - std::vector N; - YAML::Node config = YAML::Load(argv[1]); - try { - from = config["from"].as>(); - to = config["to"].as>(); - N = config["N"].as>(); - } catch (std::exception& e) { - std::cerr << "Error while parsing required arguments from, to, and N: " << e.what() - << std::endl; - return -1; - } - unsigned group = 0; - if (config["group"]) { - group = config["group"].as(); - } - std::vector parameters; - if (config["parameters"]) { - parameters = config["parameters"].as>(); - } - - if (from.size() != 3 || to.size() != 3 || N.size() != 3) { - std::cerr << "from, to, and N must have 3 dimensions" << std::endl; - return -1; + } + + if (parameters.empty()) { + auto supplied = model->suppliedParameters(); + parameters = std::vector(supplied.begin(), supplied.end()); + } + auto adapter = easi::ArraysAdapter<>{}; + auto material = std::vector>(parameters.size()); + auto it = material.begin(); + for (const auto& p : parameters) { + it->resize(query.numPoints()); + adapter.addBindingPoint(p, it->data()); + ++it; + } + + auto evalStart = std::chrono::high_resolution_clock::now(); + model->evaluate(query, adapter); + auto evalEnd = std::chrono::high_resolution_clock::now(); + delete model; + + std::cout << parameters.size() << "," << nGP << "," + << std::chrono::duration_cast(parseEnd - parseStart).count() * + 1.0e-9 + << "," + << std::chrono::duration_cast(evalEnd - evalStart).count() * + 1.0e-9 + << std::endl; + + /// Write xdmf + + if (!basename.empty()) { + std::ofstream ofs(basename + ".xdmf", std::ofstream::out); + + ofs << "\n" + << "\n" + << "\n" + << " \n" + << " \n" + << " \n" + << " \n" + << " \n" + << " " << from[2] << " " << from[1] << " " << from[0] << "\n" + << " \n" + << " \n" + << " " << h[2] << " " << h[1] << " " << h[0] << "\n" + << " \n" + << " \n"; + for (const auto& p : parameters) { + ofs << " \n" + << " " << basename << ".nc:/" << p + << "\n" + << " \n"; } - for (unsigned n : N) { - if (n < 2) { - std::cerr << "number of grid points in each dimension should be greater than 1" - << std::endl; - return -1; - } + ofs << " \n" + << " \n" + << "\n"; + + ofs.close(); + + /// Write netcdf + + int stat; /* return status */ + int ncid; /* netCDF id */ + + /* dimension ids */ + int x_dim; + int y_dim; + int z_dim; + + /* dimension lengths */ + size_t x_len = N[0]; + size_t y_len = N[1]; + size_t z_len = N[2]; + + /* enter define mode */ + stat = nc_create(std::string(basename + ".nc").c_str(), NC_NETCDF4, &ncid); + check_err(stat, __LINE__, __FILE__); + + /* define dimensions */ + stat = nc_def_dim(ncid, "x", x_len, &x_dim); + check_err(stat, __LINE__, __FILE__); + stat = nc_def_dim(ncid, "y", y_len, &y_dim); + check_err(stat, __LINE__, __FILE__); + stat = nc_def_dim(ncid, "z", z_len, &z_dim); + check_err(stat, __LINE__, __FILE__); + + /* define variables */ + + std::unordered_map ids; + for (const auto& p : parameters) { + int dims[3]; + dims[0] = z_dim; + dims[1] = y_dim; + dims[2] = x_dim; + + stat = nc_def_var(ncid, p.c_str(), NC_DOUBLE, 3, dims, &ids[p]); + check_err(stat, __LINE__, __FILE__); } - unsigned nGP = 1; - for (unsigned n : N) { - nGP *= n; - } - unsigned dim = N.size(); - std::vector h; - for (unsigned d = 0; d < dim; ++d) { - h.push_back((to[d] - from[d]) / (N[d] - 1)); - } + /* leave define mode */ + stat = nc_enddef(ncid); + check_err(stat, __LINE__, __FILE__); - auto parseStart = std::chrono::high_resolution_clock::now(); - auto parser = easi::YAMLParser(dim); - easi::Component* model = parser.parse(modelFile); - auto parseEnd = std::chrono::high_resolution_clock::now(); - - auto query = easi::Query(nGP, dim); - for (unsigned k = 0; k < N[2]; ++k) { - for (unsigned j = 0; j < N[1]; ++j) { - for (unsigned i = 0; i < N[0]; ++i) { - unsigned index = i + j * N[0] + k * N[0] * N[1]; - query.group(index) = group; - query.x(index, 0) = from[0] + i * h[0]; - query.x(index, 1) = from[1] + j * h[1]; - query.x(index, 2) = from[2] + k * h[2]; - } - } - } + /* assign variable data */ - if (parameters.empty()) { - auto supplied = model->suppliedParameters(); - parameters = std::vector(supplied.begin(), supplied.end()); - } - auto adapter = easi::ArraysAdapter<>{}; - auto material = std::vector>(parameters.size()); - auto it = material.begin(); - for (auto const& p : parameters) { - it->resize(query.numPoints()); - adapter.addBindingPoint(p, it->data()); - ++it; + it = material.begin(); + for (const auto& p : parameters) { + stat = nc_put_var_double(ncid, ids[p], it->data()); + ++it; } - auto evalStart = std::chrono::high_resolution_clock::now(); - model->evaluate(query, adapter); - auto evalEnd = std::chrono::high_resolution_clock::now(); - delete model; - - std::cout - << parameters.size() << "," << nGP << "," - << std::chrono::duration_cast(parseEnd - parseStart).count() * - 1.0e-9 - << "," - << std::chrono::duration_cast(evalEnd - evalStart).count() * - 1.0e-9 - << std::endl; - - /// Write xdmf - - if (!basename.empty()) { - std::ofstream ofs(basename + ".xdmf", std::ofstream::out); - - ofs << "\n" - << "\n" - << "\n" - << " \n" - << " \n" - << " \n" - << " \n" - << " \n" - << " " << from[2] << " " << from[1] << " " << from[0] << "\n" - << " \n" - << " \n" - << " " << h[2] << " " << h[1] << " " << h[0] << "\n" - << " \n" - << " \n"; - for (auto const& p : parameters) { - ofs << " \n" - << " " << basename << ".nc:/" << p - << "\n" - << " \n"; - } - ofs << " \n" - << " \n" - << "\n"; - - ofs.close(); - - /// Write netcdf - - int stat; /* return status */ - int ncid; /* netCDF id */ - - /* dimension ids */ - int x_dim; - int y_dim; - int z_dim; - - /* dimension lengths */ - size_t x_len = N[0]; - size_t y_len = N[1]; - size_t z_len = N[2]; - - /* enter define mode */ - stat = nc_create(std::string(basename + ".nc").c_str(), NC_NETCDF4, &ncid); - check_err(stat, __LINE__, __FILE__); - - /* define dimensions */ - stat = nc_def_dim(ncid, "x", x_len, &x_dim); - check_err(stat, __LINE__, __FILE__); - stat = nc_def_dim(ncid, "y", y_len, &y_dim); - check_err(stat, __LINE__, __FILE__); - stat = nc_def_dim(ncid, "z", z_len, &z_dim); - check_err(stat, __LINE__, __FILE__); - - /* define variables */ - - std::unordered_map ids; - for (auto const& p : parameters) { - int dims[3]; - dims[0] = z_dim; - dims[1] = y_dim; - dims[2] = x_dim; - - stat = nc_def_var(ncid, p.c_str(), NC_DOUBLE, 3, dims, &ids[p]); - check_err(stat, __LINE__, __FILE__); - } - - /* leave define mode */ - stat = nc_enddef(ncid); - check_err(stat, __LINE__, __FILE__); - - /* assign variable data */ - - it = material.begin(); - for (auto const& p : parameters) { - stat = nc_put_var_double(ncid, ids[p], it->data()); - ++it; - } - - stat = nc_close(ncid); - check_err(stat, __LINE__, __FILE__); - } + stat = nc_close(ncid); + check_err(stat, __LINE__, __FILE__); + } - MPI_Finalize(); - return 0; + MPI_Finalize(); + return 0; }