diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml new file mode 100644 index 0000000..f4a806b --- /dev/null +++ b/.gitlab-ci.yml @@ -0,0 +1,72 @@ +.builds: + stage: build + allow_failure: true + script: + - echo "free -h" + - free -h + - echo "grep -c ^processor /proc/cpuinfo" + - grep -c ^processor /proc/cpuinfo + - cd build + - cmake -DCMAKE_BUILD_TYPE:STRING=Release -DRUNNING_IN_CI=ON .. + - make + artifacts: + paths: + - build + expire_in: 1 day + +build:testing_gcc: + extends: .builds + image: registry.gitlab.com/tjunge/muspectretest:debian_testing + +build:testing_clang: + extends: .builds + image: registry.gitlab.com/tjunge/muspectretest:debian_testing + +build:stable_gcc: + extends: .builds + image: registry.gitlab.com/tjunge/muspectretest:debian_stable + +build:ubuntu16.04_gcc: + extends: .builds + image: registry.gitlab.com/tjunge/muspectretest:ubuntu16.04 + +.tests: + stage: test + script: + - ls + - cd build + - ls -a + - make test + - ls -ltr + - ls Testing + artifacts: + when: on_failure + paths: + - build/test_results*.xml + reports: + junit: + - build/test_results*.xml + +test:testing_gcc: + image: registry.gitlab.com/tjunge/muspectretest:debian_testing + extends: .tests + dependencies: + - build:testing_gcc + +test:testing_clang: + image: registry.gitlab.com/tjunge/muspectretest:debian_testing + extends: .tests + dependencies: + - build:testing_clang + +test:stable_gcc: + image: registry.gitlab.com/tjunge/muspectretest:debian_stable + extends: .tests + dependencies: + - build:stable_gcc + +test:ubuntu16.04_gcc: + image: registry.gitlab.com/tjunge/muspectretest:ubuntu16.04 + extends: .tests + dependencies: + - build:ubuntu16.04_gcc diff --git a/CMakeLists.txt b/CMakeLists.txt index 416ab8b..afdda1e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,299 +1,161 @@ # ============================================================================= # file CMakeLists.txt # # @author Till Junge # # @date 08 Jan 2018 # # @brief Main configuration file # # @section LICENSE # # Copyright © 2018 Till Junge # # µSpectre is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation, either version 3, or (at # your option) any later version. # # µSpectre is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with µSpectre; see the file COPYING. If not, write to the # Free Software Foundation, Inc., 59 Temple Place - Suite 330, # Boston, MA 02111-1307, USA. # # Additional permission under GNU GPL version 3 section 7 # # If you modify this Program, or any covered work, by linking or combining it # with proprietary FFT implementations or numerical libraries, containing parts # covered by the terms of those libraries' licenses, the licensors of this # Program grant you additional permission to convey the resulting work. # ============================================================================= -cmake_minimum_required(VERSION 3.0.0) +cmake_minimum_required(VERSION 3.5.0) -project(µSpectre) +project(muSpectre) -set(CMAKE_CXX_STANDARD 14) -set(CMAKE_CXX_STANDARD_REQUIRED ON) +# ------------------------------------------------------------------------------ set(CMAKE_EXPORT_COMPILE_COMMANDS ON) set(BUILD_SHARED_LIBS ON) set(MUSPECTRE_PYTHON_MAJOR_VERSION 3) - -add_compile_options(-Wall -Wextra -Weffc++) - set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_SOURCE_DIR}/cmake) -set(MAKE_DOC_TARGET "OFF" CACHE BOOL "If on, a target dev_doc (which builds the documentation) is added") -set(MAKE_TESTS "ON" CACHE BOOL "If on, several ctest targets will be built automatically") -set(MAKE_EXAMPLES "ON" CACHE BOOL "If on, the executables in the bin folder will be compiled") -set(MAKE_BENCHMARKS "ON" CACHE BOOL "If on, the benchmarks will be compiled") -set(MPI_PARALLEL "OFF" CACHE BOOL "If on, MPI-parallel solvers become available") -set(SPLIT_CELL "OFF" CACHE BOOL "if on, split cell and the cgal intersection calculator is accsessible ") -set(RUNNING_IN_CI "OFF" CACHE INTERNAL "changes output format for tests") -if(${MAKE_TESTS}) - enable_testing() - find_package(Boost COMPONENTS unit_test_framework REQUIRED) -endif(${MAKE_TESTS}) +# ------------------------------------------------------------------------------ +option(MUSPECTRE_MAKE_DOC_TARGET "If on, a target dev_doc (which builds the documentation) is added" OFF) +option(MUSPECTRE_MAKE_TESTS "If on, several ctest targets will be built automatically" ON) +option(MUSPECTRE_MAKE_EXAMPLES "If on, the executables in the bin folder will be compiled" ON) +option(MUSPECTRE_MAKE_BENCHMARKS "If on, the benchmarks will be compiled" ON) +option(MUSPECTRE_MPI_PARALLEL "If on, MPI-parallel solvers become available" OFF) +set(MUCHOICE "muSpectre" CACHE STRING "Which µLevel is required") +set_property(CACHE MUCHOICE PROPERTY STRINGS + "muGrid" + "muFFT" + "muSpectre" + ) -if(${MPI_PARALLEL}) - add_definitions(-DWITH_MPI) - find_package(MPI) - if (NOT ${MPI_FOUND}) - message(SEND_ERROR "You chose MPI but CMake cannot find the MPI package") - endif(NOT ${MPI_FOUND}) -endif(${MPI_PARALLEL}) +set(SPLIT_CELL "OFF" CACHE BOOL "if on, split cell and the cgal intersection calculator is accsessible ") +set(MUSPECTRE_RUNNING_IN_CI "OFF" CACHE INTERNAL "changes output format for tests") + +set(MUSPECTRE_NAMESPACE "${MUCHOICE}::") +set(MUSPECTE_TARGETS_EXPORT ${MUCHOICE}Targets) +set(MUGRID_NAMESPACE ${MUSPECTRE_NAMESPCE}) +set(MUGRID_TARGETS_EXPORT ${MUSPECTRE_TARGETS_EXPORT}) +set(MUFFT_NAMESPACE ${MUGRID_NAMESPACE}) +set(MUFFT_TARGETS_EXPORT ${MUGRID_TARGETS_EXPORT}) + +if(MUSPECTRE_MUFFT_ONLY OR MUSPECTRE_MUGRID_ONLY) + set(MUSPECTRE_MAKE_TESTS OFF CACHE BOOL "" FORCE) + set(MUSPECTRE_MAKE_EXAMPLES OFF CACHE BOOL "" FORCE) +endif() +# ------------------------------------------------------------------------------ include(muspectreTools) +include(muTools) include(cpplint) +mark_as_advanced_prefix(CPPLINT) -string( TOLOWER "${CMAKE_BUILD_TYPE}" build_type ) -if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang" OR "${CMAKE_CXX_COMPILER_ID}" STREQUAL "AppleClang") - # using Clang - add_compile_options(-Wno-missing-braces) - if ("debug" STREQUAL "${build_type}") - add_compile_options(-O0) - endif() -elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") - # using GCC - add_compile_options(-Wno-non-virtual-dtor) - add_compile_options(-march=native) - if (("relwithdebinfo" STREQUAL "${build_type}") OR ("release" STREQUAL "${build_type}" )) - add_compile_options(-march=native) - endif() - if ("debug" STREQUAL "${build_type}" ) - add_compile_options(-O0) - endif() -elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Intel") - # using Intel C++ -elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") - # using Visual Studio C++ -endif() - -# Do not trust old gcc. the std::optional has memory bugs -if(${CMAKE_COMPILER_IS_GNUCC}) - if(${CMAKE_CXX_COMPILER_VERSION} VERSION_LESS 6.0.0) - add_definitions(-DNO_EXPERIMENTAL) - endif() -endif() +muSpectre_set_global_compile_options() +# ------------------------------------------------------------------------------ add_external_package(Eigen3 VERSION 3.3.0 CONFIG) - add_external_package(pybind11 VERSION 2.2 CONFIG) find_package(PythonLibsNew ${MUSPECTRE_PYTHON_MAJOR_VERSION} MODULE REQUIRED) + if(${SPLIT_CELL}) add_external_package(CGAL VERSION 4.12 CONFIG) endif() -include_directories( - ${CMAKE_SOURCE_DIR}/src - ${CMAKE_SOURCE_DIR} - ) +add_subdirectory(external) + +# ------------------------------------------------------------------------------ if(APPLE) - include_directories(${CMAKE_INSTALL_PREFIX}/include ${Boost_INCLUDE_DIRS}) + include_directories( + ${CMAKE_INSTALL_PREFIX}/include + ${Boost_INCLUDE_DIRS}) endif() + #build tests (these are before we add -Werror to the compile options) if (${MAKE_TESTS}) ############################################################################## # build library tests file( GLOB TEST_SRCS "${CMAKE_SOURCE_DIR}/tests/test_*.cc") if(${SPLIT_CELL}) file( GLOB SPLIT_TEST_SRCS "${CMAKE_SOURCE_DIR}/tests/split_test_*.cc") list (APPEND TEST_SRCS ${SPLIT_TEST_SRCS}) endif(${SPLIT_CELL}) add_executable(main_test_suite tests/main_test_suite.cc ${TEST_SRCS}) target_link_libraries(main_test_suite ${Boost_LIBRARIES} muSpectre mpfr) - - - muSpectre_add_test(main_test_suite TYPE BOOST main_test_suite --report_level=detailed) - - add_executable(mattb_test tests/main_test_suite tests/test_materials_toolbox.cc) - target_link_libraries(mattb_test ${Boost_LIBRARIES} muSpectre) - muSpectre_add_test(mattb_test TYPE BOOST mattb_test --report_level=detailed) - - # build header tests - file( GLOB HEADER_TEST_SRCS "${CMAKE_SOURCE_DIR}/tests/header_test_*.cc") - foreach(header_test ${HEADER_TEST_SRCS}) - get_filename_component(header_test_name ${header_test} NAME_WE) - string(SUBSTRING ${header_test_name} 12 -1 test_name) - list(APPEND header_tests ${test_name}) - add_executable(${test_name} tests/main_test_suite.cc ${header_test}) - target_link_libraries(${test_name} ${Boost_LIBRARIES} Eigen3::Eigen) - target_include_directories(${test_name} INTERFACE ${muSpectre_INCLUDES}) - muSpectre_add_test(${test_name} TYPE BOOST ${test_name} - --report_level=detailed) - endforeach(header_test ${HEADER_TEST_SRCS}) - - add_custom_target(header_tests) - add_dependencies(header_tests ${header_tests}) - - ############################################################################## - # build py_comparison tests - file (GLOB PY_COMP_TEST_SRCS "${CMAKE_SOURCE_DIR}/tests/py_comparison_*.cc") - - find_package(PythonInterp ${MUSPECTRE_PYTHON_MAJOR_VERSION} REQUIRED) - foreach(py_comp_test ${PY_COMP_TEST_SRCS}) - get_filename_component(py_comp_test_fname ${py_comp_test} NAME_WE) - - string (SUBSTRING ${py_comp_test_fname} 19 -1 py_comp_test_name) - - pybind11_add_module(${py_comp_test_name} ${py_comp_test}) - target_include_directories(${py_comp_test_name} PUBLIC - ${PYTHON_INCLUDE_DIRS}) - target_link_libraries(${py_comp_test_name} PRIVATE muSpectre) - configure_file( - tests/${py_comp_test_fname}.py - "${CMAKE_BINARY_DIR}/${py_comp_test_fname}.py" - COPYONLY) - muSpectre_add_test(${py_comp_test_fname} - TYPE PYTHON ${py_comp_test_fname}.py) - - endforeach(py_comp_test ${PY_COMP_TEST_SRCS}) - - ############################################################################## - # copy python test - file( GLOB PY_TEST_SRCS "${CMAKE_SOURCE_DIR}/tests/python_*.py") - - foreach(pytest ${PY_TEST_SRCS}) - get_filename_component(pytest_name ${pytest} NAME) - configure_file( - ${pytest} - "${CMAKE_BINARY_DIR}/${pytest_name}" - COPYONLY) - endforeach(pytest ${PY_TEST_SRCS}) - muSpectre_add_test(python_binding_test TYPE PYTHON python_binding_tests.py) - - if(${MPI_PARALLEL}) - ############################################################################ - # add MPI tests - file( GLOB TEST_SRCS "${CMAKE_SOURCE_DIR}/tests/mpi_test_*.cc") - - add_executable(mpi_main_test_suite tests/mpi_main_test_suite.cc ${TEST_SRCS}) - target_link_libraries(mpi_main_test_suite ${Boost_LIBRARIES} muSpectre) - - muSpectre_add_test(mpi_main_test_suite1 TYPE BOOST MPI_NB_PROCS 1 - mpi_main_test_suite --report_level=detailed) - muSpectre_add_test(mpi_main_test_suite2 TYPE BOOST MPI_NB_PROCS 2 - mpi_main_test_suite --report_level=detailed) - - muSpectre_add_test(python_mpi_binding_test1 TYPE PYTHON MPI_NB_PROCS 1 - python_mpi_binding_tests.py) - muSpectre_add_test(python_mpi_binding_test2 TYPE PYTHON MPI_NB_PROCS 2 - python_mpi_binding_tests.py) - endif(${MPI_PARALLEL}) -endif(${MAKE_TESTS}) +if (${MUSPECTRE_MAKE_TESTS}) + enable_testing() + add_subdirectory(tests) +endif() ################################################################################ # compile the library -add_compile_options( -Werror) -add_subdirectory( - ${CMAKE_SOURCE_DIR}/src/ - ) -add_subdirectory( - ${CMAKE_SOURCE_DIR}/language_bindings/ - ) +add_compile_options(-Werror) +add_subdirectory(${CMAKE_SOURCE_DIR}/src) +if(MUCHOICE MATCHES "muSpectre") + add_subdirectory(${CMAKE_SOURCE_DIR}/language_bindings) +endif() -if (${MAKE_DOC_TARGET}) - add_subdirectory( - ${CMAKE_SOURCE_DIR}/doc/ - ) +if (${MUSPECTRE_MAKE_DOC_TARGET}) + add_subdirectory(${CMAKE_SOURCE_DIR}/doc) endif() ################################################################################ -if (${MAKE_EXAMPLES}) - #compile executables - - set(binaries - ${CMAKE_SOURCE_DIR}/bin/demonstrator1.cc - ${CMAKE_SOURCE_DIR}/bin/demonstrator_dynamic_solve.cc - ${CMAKE_SOURCE_DIR}/bin/demonstrator2.cc - ${CMAKE_SOURCE_DIR}/bin/hyper-elasticity.cc - ${CMAKE_SOURCE_DIR}/bin/small_case.cc) - - if (${MPI_PARALLEL}) - set (binaries - ${binaries} - ${CMAKE_SOURCE_DIR}/bin/demonstrator_mpi.cc - ) - endif (${MPI_PARALLEL}) - - foreach(binaryfile ${binaries}) - get_filename_component(binaryname ${binaryfile} NAME_WE) - add_executable(${binaryname} ${binaryfile}) - - target_link_libraries(${binaryname} ${Boost_LIBRARIES} muSpectre) - endforeach(binaryfile ${binaries}) - - # or copy them - file (GLOB pybins "${CMAKE_SOURCE_DIR}/bin/*.py") - foreach(pybin ${pybins}) - - get_filename_component(binaryname ${pybin} NAME_WE) - configure_file( - ${pybin} - "${CMAKE_BINARY_DIR}/${binaryname}.py" - COPYONLY) - endforeach(pybin ${pybins}) - - # additional files to copy - set (FILES_FOR_COPY - ${CMAKE_SOURCE_DIR}/bin/odd_image.npz) - - foreach(FILE_FOR_COPY ${FILES_FOR_COPY}) - - get_filename_component(binaryname ${FILE_FOR_COPY} NAME) - configure_file( - ${FILE_FOR_COPY} - "${CMAKE_BINARY_DIR}/${binaryname}" - COPYONLY) - endforeach(FILE_FOR_COPY ${FILES_FOR_COPY}) - -endif (${MAKE_EXAMPLES}) - +if(${MUSPECTRE_MAKE_EXAMPLES} AND ${MUCHOICE} MATCHES "muSpectre") + add_subdirectory(${CMAKE_SOURCE_DIR}/bin) +endif() ################################################################################ # compile benchmarks -if(${MAKE_BENCHMARKS}) +if(${MUSPECTRE_MAKE_BENCHMARKS}) file(GLOB benchmarks "${CMAKE_SOURCE_DIR}/benchmarks/benchmark*cc") foreach(benchmark ${benchmarks}) get_filename_component(benchmark_name ${benchmark} NAME_WE) add_executable(${benchmark_name} ${benchmark}) target_link_libraries(${benchmark_name} ${BOOST_LIBRARIES} muSpectre) endforeach(benchmark ${benchmark}) -endif(${MAKE_BENCHMARKS}) - +endif() -cpplint_add_subdirectory("${CMAKE_SOURCE_DIR}/src" "") -cpplint_add_subdirectory("${CMAKE_SOURCE_DIR}/tests" "") -cpplint_add_subdirectory("${CMAKE_SOURCE_DIR}/language_bindings" "") -cpplint_add_subdirectory("${CMAKE_SOURCE_DIR}/bin" "--filter=-build/namespaces") +if(MUCHOICE MATCHES "muGrid") + cpplint_add_subdirectory("${CMAKE_SOURCE_DIR}/src/libmugrid" "") +elseif(MUCHOICE MATCHES "muFFT") + cpplint_add_subdirectory("${CMAKE_SOURCE_DIR}/src/libmugrid" "") + cpplint_add_subdirectory("${CMAKE_SOURCE_DIR}/src/libmufft" "") +else() + cpplint_add_subdirectory("${CMAKE_SOURCE_DIR}/src" "") + cpplint_add_subdirectory("${CMAKE_SOURCE_DIR}/tests" "") + cpplint_add_subdirectory("${CMAKE_SOURCE_DIR}/language_bindings" "") + cpplint_add_subdirectory("${CMAKE_SOURCE_DIR}/bin" "--filter=-build/namespaces") +endif() diff --git a/Jenkinsfile b/Jenkinsfile index 475f59f..c134c0f 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -1,218 +1,218 @@ pipeline { parameters {string(defaultValue: '', description: 'api-token', name: 'API_TOKEN') string(defaultValue: '', description: 'Token for readthedocs', name: 'RTD_TOKEN') string(defaultValue: '', description: 'buildable phid', name: 'TARGET_PHID') string(defaultValue: 'docker_debian_testing', description: 'docker file to use', name: 'DOCKERFILE') string(defaultValue: '', description: 'Commit id', name: 'COMMIT_ID') } agent any environment { OMPI_MCA_plm = 'isolated' OMPI_MCA_btl = 'tcp,self' } options { disableConcurrentBuilds() } stages { stage ('wipe build') { when { anyOf{ changeset glob: "**/*.cmake" changeset glob: "**/CMakeLists.txt" } } steps { sh ' rm -rf build_*' } } stage ('configure') { parallel { stage ('docker_debian_testing') { agent { dockerfile { filename 'docker_debian_testing' dir 'dockerfiles' } } steps { configure('docker_debian_testing') } } stage ('docker_debian_stable') { agent { dockerfile { filename 'docker_debian_stable' dir 'dockerfiles' } } steps { configure('docker_debian_stable') } } } } stage ('build') { parallel { stage ('docker_debian_testing') { agent { dockerfile { filename 'docker_debian_testing' dir 'dockerfiles' } } steps { build('docker_debian_testing') } } stage ('docker_debian_stable') { agent { dockerfile { filename 'docker_debian_stable' dir 'dockerfiles' } } steps { build('docker_debian_stable') } } } } stage ('Warnings gcc') { steps { warnings(consoleParsers: [[parserName: 'GNU Make + GNU C Compiler (gcc)']]) } } stage ('test') { parallel { //////////////////////////////////////////////////// stage ('docker_debian_testing') { agent { dockerfile { filename 'docker_debian_testing' dir 'dockerfiles' } } steps { run_test('docker_debian_testing', 'g++') run_test('docker_debian_testing', 'clang++') } post { always { collect_test_results('docker_debian_testing', 'g++') collect_test_results('docker_debian_testing', 'clang++') } } } //////////////////////////////////////////////////// stage ('docker_debian_stable') { agent { dockerfile { filename 'docker_debian_stable' dir 'dockerfiles' } } steps { run_test('docker_debian_stable', 'g++') run_test('docker_debian_stable', 'clang++') } post { always { collect_test_results('docker_debian_stable', 'g++') collect_test_results('docker_debian_stable', 'clang++') } } } } } } post { always { createartifact() } success { send_fail_pass('pass') trigger_readthedocs() } unsuccessful { send_fail_pass('fail') } } } def configure(container_name) { def BUILD_DIR = "build_${container_name}" for (CXX_COMPILER in ["g++", "clang++"]) { sh """ mkdir -p ${BUILD_DIR}_${CXX_COMPILER} cd ${BUILD_DIR}_${CXX_COMPILER} -CXX=${CXX_COMPILER} cmake -DCMAKE_BUILD_TYPE:STRING=Release -DRUNNING_IN_CI=ON .. +CXX=${CXX_COMPILER} cmake -DCMAKE_BUILD_TYPE:STRING=Release -DMUSPECTRE_RUNNING_IN_CI=ON .. """ } } def build(container_name) { def BUILD_DIR = "build_${container_name}" for (CXX_COMPILER in ["g++", "clang++"]) { sh "make -C ${BUILD_DIR}_${CXX_COMPILER}" } } def run_test(container_name, cxx_compiler) { def BUILD_DIR = "build_${container_name}" sh "cd ${BUILD_DIR}_${cxx_compiler} && ctest || true" } def send_fail_pass(state) { sh """ set +x curl https://c4science.ch/api/harbormaster.sendmessage \ -d api.token=${API_TOKEN} \ -d buildTargetPHID=${TARGET_PHID} \ -d type=${state} """ } def trigger_readthedocs() { sh """ set +x curl -X POST \ -d "token=${RTD_TOKEN}" \ -d "branches=master" \ https://readthedocs.org/api/v2/webhook/muspectre/26537/ curl -X POST \ -d "token=${RTD_TOKEN}" \ https://readthedocs.org/api/v2/webhook/muspectre/26537/ """ } def collect_test_results(container_name, cxx_compiler) { def BUILD_DIR = "build_${container_name}" junit "${BUILD_DIR}_${cxx_compiler}/test_results*.xml" } def createartifact() { sh """ set +x curl https://c4science.ch/api/harbormaster.createartifact \ -d api.token=${API_TOKEN} \ -d buildTargetPHID=${TARGET_PHID} \ -d artifactKey="Jenkins URI" \ -d artifactType=uri \ -d artifactData[uri]=${BUILD_URL} \ -d artifactData[name]="View Jenkins result" \ -d artifactData[ui.external]=1 """ } diff --git a/bin/CMakeLists.txt b/bin/CMakeLists.txt new file mode 100644 index 0000000..eb3a8a2 --- /dev/null +++ b/bin/CMakeLists.txt @@ -0,0 +1,81 @@ +# ============================================================================= +# file CMakeLists.txt +# +# @author Till Junge +# +# @date 08 Jan 2018 +# +# @brief Main configuration file +# +# @section LICENSE +# +# Copyright © 2018 Till Junge +# +# µSpectre is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public License as +# published by the Free Software Foundation, either version 3, or (at +# your option) any later version. +# +# µSpectre is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with µSpectre; see the file COPYING. If not, write to the +# Free Software Foundation, Inc., 59 Temple Place - Suite 330, +# Boston, MA 02111-1307, USA. +# +# Additional permission under GNU GPL version 3 section 7 +# +# If you modify this Program, or any covered work, by linking or combining it +# with proprietary FFT implementations or numerical libraries, containing parts +# covered by the terms of those libraries' licenses, the licensors of this +# Program grant you additional permission to convey the resulting work. +# ============================================================================= + +#compile executables + +set(binaries + demonstrator1.cc + demonstrator_dynamic_solve.cc + demonstrator2.cc + hyper-elasticity.cc + small_case.cc + ) + +if(${MUSPECTRE_MPI_PARALLEL}) + list(APPEND binaries + demonstrator_mpi.cc + ) +endif() + +foreach(binaryfile ${binaries}) + get_filename_component(binaryname ${binaryfile} NAME_WE) + add_executable(${binaryname} ${binaryfile}) + target_link_libraries(${binaryname} PRIVATE ${MUSPECTRE_NAMESPACE}muSpectre cxxopts) + + muTools_move_to_project(${binaryname}) +endforeach() + +# or copy them +file(GLOB pybins "${CMAKE_SOURCE_DIR}/bin/*.py") +foreach(pybin ${pybins}) + get_filename_component(binaryname ${pybin} NAME_WE) + configure_file( + ${pybin} + "${CMAKE_BINARY_DIR}/${binaryname}.py" + COPYONLY) +endforeach() + +# additional files to copy +set(FILES_FOR_COPY + ${CMAKE_CURRENT_SOURCE_DIR}/odd_image.npz) + +foreach(file_for_copy ${FILES_FOR_COPY}) + get_filename_component(binaryname ${file_for_copy} NAME) + configure_file( + ${file_for_copy} + "${PROJECT_BINARY_DIR}/${binaryname}" + COPYONLY) +endforeach() diff --git a/bin/demonstrator1.cc b/bin/demonstrator1.cc index 75922ce..4810549 100644 --- a/bin/demonstrator1.cc +++ b/bin/demonstrator1.cc @@ -1,142 +1,144 @@ /** * @file demonstrator1.cc * * @author Till Junge * * @date 03 Jan 2018 * * @brief larger problem to show off * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include #include #include #include "external/cxxopts.hpp" -#include "common/common.hh" -#include "common/ccoord_operations.hh" +#include "common/muSpectre_common.hh" +#include #include "cell/cell_factory.hh" #include "materials/material_linear_elastic1.hh" #include "solver/deprecated_solvers.hh" #include "solver/deprecated_solver_cg.hh" using opt_ptr = std::unique_ptr; opt_ptr parse_args(int argc, char ** argv) { opt_ptr options = std::make_unique(argv[0], "Tests MPI fft scalability"); try { options->add_options()("0,N0", "number of rows", cxxopts::value(), "N0")("h,help", "print help")( "positional", "Positional arguments: these are the arguments that are entered " "without an option", cxxopts::value>()); options->parse_positional(std::vector{"N0", "positional"}); options->parse(argc, argv); if (options->count("help")) { std::cout << options->help({"", "Group"}) << std::endl; exit(0); } if (options->count("N0") != 1) { throw cxxopts::OptionException("Parameter N0 missing"); } else if ((*options)["N0"].as() % 2 != 1) { throw cxxopts::OptionException("N0 must be odd"); } else if (options->count("positional") > 0) { throw cxxopts::OptionException("There are too many positional arguments"); } } catch (const cxxopts::OptionException & e) { std::cout << "Error parsing options: " << e.what() << std::endl; exit(1); } return options; } +using namespace muFFT; +using namespace muGrid; using namespace muSpectre; int main(int argc, char * argv[]) { banner("demonstrator1", 2018, "Till Junge "); auto options{parse_args(argc, argv)}; auto & opt{*options}; const Dim_t size{opt["N0"].as()}; constexpr Real fsize{1.}; constexpr Dim_t dim{3}; const Dim_t nb_dofs{ipow(size, dim) * ipow(dim, 2)}; std::cout << "Number of dofs: " << nb_dofs << std::endl; constexpr Formulation form{Formulation::finite_strain}; const Rcoord_t lengths{CcoordOps::get_cube(fsize)}; const Ccoord_t resolutions{CcoordOps::get_cube(size)}; auto cell{make_cell(resolutions, lengths, form)}; constexpr Real E{1.0030648180242636}; constexpr Real nu{0.29930675909878679}; using Material_t = MaterialLinearElastic1; auto & Material_soft{Material_t::make(cell, "soft", E, nu)}; auto & Material_hard{Material_t::make(cell, "hard", 10 * E, nu)}; int counter{0}; for (const auto && pixel : cell) { int sum = 0; for (Dim_t i = 0; i < dim; ++i) { sum += pixel[i] * 2 / resolutions[i]; } if (sum == 0) { Material_hard.add_pixel(pixel); counter++; } else { Material_soft.add_pixel(pixel); } } std::cout << counter << " Pixel out of " << cell.size() << " are in the hard material" << std::endl; cell.initialise(FFT_PlanFlags::measure); constexpr Real newton_tol{1e-4}; constexpr Real cg_tol{1e-7}; const Uint maxiter = nb_dofs; Grad_t DeltaF{Grad_t::Zero()}; DeltaF(0, 1) = .1; Dim_t verbose{1}; auto start = std::chrono::high_resolution_clock::now(); GradIncrements grads{DeltaF}; DeprecatedSolverCG cg{cell, cg_tol, maxiter, static_cast(verbose)}; deprecated_newton_cg(cell, grads, cg, newton_tol, verbose); std::chrono::duration dur = std::chrono::high_resolution_clock::now() - start; std::cout << "Resolution time = " << dur.count() << "s" << std::endl; return 0; } diff --git a/bin/demonstrator2.cc b/bin/demonstrator2.cc index e10dddc..cc26d35 100644 --- a/bin/demonstrator2.cc +++ b/bin/demonstrator2.cc @@ -1,97 +1,99 @@ /** * @file demonstrator1.cc * * @author Till Junge * * @date 03 Jan 2018 * * @brief larger problem to show off * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include #include #include -#include "common/common.hh" -#include "common/ccoord_operations.hh" +#include "common/muSpectre_common.hh" #include "cell/cell_factory.hh" #include "materials/material_linear_elastic1.hh" #include "solver/solvers.hh" #include "solver/solver_cg.hh" +#include + using namespace muSpectre; +using namespace muGrid; int main() { banner("demonstrator1", 2018, "Till Junge "); constexpr Dim_t dim{2}; constexpr Formulation form{Formulation::finite_strain}; const Rcoord_t lengths{5.2, 8.3}; const Ccoord_t resolutions{5, 7}; auto cell{make_cell(resolutions, lengths, form)}; constexpr Real E{1.0030648180242636}; constexpr Real nu{0.29930675909878679}; using Material_t = MaterialLinearElastic1; auto & soft{Material_t::make(cell, "soft", E, nu)}; auto & hard{Material_t::make(cell, "hard", 10 * E, nu)}; int counter{0}; for (const auto && pixel : cell) { if (counter < 3) { hard.add_pixel(pixel); counter++; } else { soft.add_pixel(pixel); } } std::cout << counter << " Pixel out of " << cell.size() << " are in the hard material" << std::endl; cell.initialise(); constexpr Real newton_tol{1e-4}; constexpr Real cg_tol{1e-7}; const size_t maxiter = 100; Eigen::MatrixXd DeltaF{Eigen::MatrixXd::Zero(dim, dim)}; DeltaF(0, 1) = .1; Dim_t verbose{1}; auto start = std::chrono::high_resolution_clock::now(); SolverCG cg{cell, cg_tol, maxiter, static_cast(verbose)}; auto res = de_geus(cell, DeltaF, cg, newton_tol, verbose); std::chrono::duration dur = std::chrono::high_resolution_clock::now() - start; std::cout << "Resolution time = " << dur.count() << "s" << std::endl; std::cout << res.grad.transpose() << std::endl; return 0; } diff --git a/bin/demonstrator_dynamic_solve.cc b/bin/demonstrator_dynamic_solve.cc index 27de556..d19defd 100644 --- a/bin/demonstrator_dynamic_solve.cc +++ b/bin/demonstrator_dynamic_solve.cc @@ -1,142 +1,145 @@ /** * @file demonstrator1.cc * * @author Till Junge * * @date 03 Jan 2018 * * @brief larger problem to show off * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include #include #include #include "external/cxxopts.hpp" -#include "common/common.hh" -#include "common/ccoord_operations.hh" +#include "common/muSpectre_common.hh" #include "cell/cell_factory.hh" #include "materials/material_linear_elastic1.hh" #include "solver/solvers.hh" #include "solver/solver_cg.hh" +#include + using opt_ptr = std::unique_ptr; opt_ptr parse_args(int argc, char ** argv) { opt_ptr options = std::make_unique(argv[0], "Tests MPI fft scalability"); try { options->add_options()("0,N0", "number of rows", cxxopts::value(), "N0")("h,help", "print help")( "positional", "Positional arguments: these are the arguments that are entered " "without an option", cxxopts::value>()); options->parse_positional(std::vector{"N0", "positional"}); options->parse(argc, argv); if (options->count("help")) { std::cout << options->help({"", "Group"}) << std::endl; exit(0); } if (options->count("N0") != 1) { throw cxxopts::OptionException("Parameter N0 missing"); } else if ((*options)["N0"].as() % 2 != 1) { throw cxxopts::OptionException("N0 must be odd"); } else if (options->count("positional") > 0) { throw cxxopts::OptionException("There are too many positional arguments"); } } catch (const cxxopts::OptionException & e) { std::cout << "Error parsing options: " << e.what() << std::endl; exit(1); } return options; } using namespace muSpectre; +using namespace muGrid; +using namespace muFFT; int main(int argc, char * argv[]) { banner("demonstrator1", 2018, "Till Junge "); auto options{parse_args(argc, argv)}; auto & opt{*options}; const Dim_t size{opt["N0"].as()}; constexpr Real fsize{1.}; constexpr Dim_t dim{3}; const Dim_t nb_dofs{ipow(size, dim) * ipow(dim, 2)}; std::cout << "Number of dofs: " << nb_dofs << std::endl; constexpr Formulation form{Formulation::finite_strain}; const Rcoord_t lengths{CcoordOps::get_cube(fsize)}; const Ccoord_t resolutions{CcoordOps::get_cube(size)}; auto cell{make_cell(resolutions, lengths, form)}; constexpr Real E{1.0030648180242636}; constexpr Real nu{0.29930675909878679}; using Material_t = MaterialLinearElastic1; auto & Material_soft{Material_t::make(cell, "soft", E, nu)}; auto & Material_hard{Material_t::make(cell, "hard", 10 * E, nu)}; int counter{0}; for (const auto && pixel : cell) { int sum = 0; for (Dim_t i = 0; i < dim; ++i) { sum += pixel[i] * 2 / resolutions[i]; } if (sum == 0) { Material_hard.add_pixel(pixel); counter++; } else { Material_soft.add_pixel(pixel); } } std::cout << counter << " Pixel out of " << cell.size() << " are in the hard material" << std::endl; cell.initialise(FFT_PlanFlags::measure); constexpr Real newton_tol{1e-4}; constexpr Real cg_tol{1e-7}; const Uint maxiter = nb_dofs; Eigen::MatrixXd DeltaF{Eigen::MatrixXd::Zero(dim, dim)}; DeltaF(0, 1) = .1; Dim_t verbose{1}; auto start = std::chrono::high_resolution_clock::now(); LoadSteps_t loads{DeltaF}; SolverCG cg{cell, cg_tol, maxiter, static_cast(verbose)}; newton_cg(cell, loads, cg, newton_tol, verbose); std::chrono::duration dur = std::chrono::high_resolution_clock::now() - start; std::cout << "Resolution time = " << dur.count() << "s" << std::endl; return 0; } diff --git a/bin/demonstrator_mpi.cc b/bin/demonstrator_mpi.cc index 1cbf1c1..f61cedd 100644 --- a/bin/demonstrator_mpi.cc +++ b/bin/demonstrator_mpi.cc @@ -1,156 +1,159 @@ /** * file demonstrator_mpi.cc * * @author Till Junge * * @date 04 Apr 2018 * * @brief MPI parallel demonstration problem * * @section LICENSE * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#include -#include -#include #include "external/cxxopts.hpp" -#include "common/common.hh" -#include "common/ccoord_operations.hh" +#include "common/muSpectre_common.hh" #include "cell/cell_factory.hh" #include "materials/material_linear_elastic1.hh" #include "solver/solvers.hh" #include "solver/solver_cg.hh" + +#include + +#include +#include +#include + using opt_ptr = std::unique_ptr; opt_ptr parse_args(int argc, char ** argv) { opt_ptr options = std::make_unique(argv[0], "Tests MPI fft scalability"); try { options->add_options()("0,N0", "number of rows", cxxopts::value(), "N0")("h,help", "print help")( "positional", "Positional arguments: these are the arguments that are entered " "without an option", cxxopts::value>()); options->parse_positional(std::vector{"N0", "positional"}); options->parse(argc, argv); if (options->count("help")) { std::cout << options->help({"", "Group"}) << std::endl; exit(0); } if (options->count("N0") != 1) { throw cxxopts::OptionException("Parameter N0 missing"); } else if ((*options)["N0"].as() % 2 != 1) { throw cxxopts::OptionException("N0 must be odd"); } else if (options->count("positional") > 0) { throw cxxopts::OptionException("There are too many positional arguments"); } } catch (const cxxopts::OptionException & e) { std::cout << "Error parsing options: " << e.what() << std::endl; exit(1); } return options; } using namespace muSpectre; int main(int argc, char * argv[]) { banner("demonstrator mpi", 2018, "Till Junge "); auto options{parse_args(argc, argv)}; auto & opt{*options}; const Dim_t size{opt["N0"].as()}; constexpr Real fsize{1.}; constexpr Dim_t dim{3}; - const Dim_t nb_dofs{ipow(size, dim) * ipow(dim, 2)}; + const Dim_t nb_dofs{muGrid::ipow(size, dim) * muGrid::ipow(dim, 2)}; std::cout << "Number of dofs: " << nb_dofs << std::endl; constexpr Formulation form{Formulation::finite_strain}; - const Rcoord_t lengths{CcoordOps::get_cube(fsize)}; - const Ccoord_t resolutions{CcoordOps::get_cube(size)}; + const Rcoord_t lengths{muGrid::CcoordOps::get_cube(fsize)}; + const Ccoord_t resolutions{muGrid::CcoordOps::get_cube(size)}; { - Communicator comm{MPI_COMM_WORLD}; + muFFT::Communicator comm{MPI_COMM_WORLD}; MPI_Init(&argc, &argv); auto cell{make_parallel_cell(resolutions, lengths, form, comm)}; constexpr Real E{1.0030648180242636}; constexpr Real nu{0.29930675909878679}; using Material_t = MaterialLinearElastic1; auto Material_soft{std::make_unique("soft", E, nu)}; auto Material_hard{std::make_unique("hard", 10 * E, nu)}; int counter{0}; for (const auto && pixel : cell) { int sum = 0; for (Dim_t i = 0; i < dim; ++i) { sum += pixel[i] * 2 / resolutions[i]; } if (sum == 0) { Material_hard->add_pixel(pixel); counter++; } else { Material_soft->add_pixel(pixel); } } if (comm.rank() == 0) { std::cout << counter << " Pixel out of " << cell.size() << " are in the hard material" << std::endl; } cell.add_material(std::move(Material_soft)); cell.add_material(std::move(Material_hard)); - cell.initialise(FFT_PlanFlags::measure); + cell.initialise(muFFT::FFT_PlanFlags::measure); constexpr Real newton_tol{1e-4}; constexpr Real cg_tol{1e-7}; const Uint maxiter = nb_dofs; Eigen::MatrixXd DeltaF{Eigen::MatrixXd::Zero(dim, dim)}; DeltaF(0, 1) = .1; Dim_t verbose{1}; auto start = std::chrono::high_resolution_clock::now(); LoadSteps_t grads{DeltaF}; SolverCG cg{cell, cg_tol, maxiter, static_cast(verbose)}; de_geus(cell, grads, cg, newton_tol, verbose); std::chrono::duration dur = std::chrono::high_resolution_clock::now() - start; if (comm.rank() == 0) { std::cout << "Resolution time = " << dur.count() << "s" << std::endl; } MPI_Barrier(comm.get_mpi_comm()); } MPI_Finalize(); return 0; } diff --git a/bin/hyper-elasticity.cc b/bin/hyper-elasticity.cc index 005f41a..f505e0c 100644 --- a/bin/hyper-elasticity.cc +++ b/bin/hyper-elasticity.cc @@ -1,91 +1,92 @@ /** * @file hyper-elasticity.cc * * @author Till Junge * * @date 16 Jan 2018 * * @brief Recreation of GooseFFT's hyper-elasticity.py calculation * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "cell/cell_factory.hh" #include "materials/material_linear_elastic1.hh" #include "solver/solvers.hh" #include "solver/solver_cg.hh" #include #include using namespace muSpectre; +using namespace muGrid; int main() { constexpr Dim_t dim{3}; constexpr Ccoord_t N{CcoordOps::get_cube(11)}; constexpr Rcoord_t lens{CcoordOps::get_cube(1.)}; constexpr Dim_t incl_size{3}; auto cell{make_cell(N, lens, Formulation::small_strain)}; // constexpr Real K_hard{8.33}, K_soft{.833}; // constexpr Real mu_hard{3.86}, mu_soft{.386}; // auto E = [](Real K, Real G) {return 9*K*G / (3*K+G);}; //G is mu // auto nu= [](Real K, Real G) {return (3*K-2*G) / (2*(3*K+G));}; // auto & hard{MaterialLinearElastic1::make(cell, "hard", // E(K_hard, mu_hard), // nu(K_hard, mu_hard))}; // auto & soft{MaterialLinearElastic1::make(cell, "soft", // E(K_soft, mu_soft), // nu(K_soft, mu_soft))}; Real ex{1e-5}; using Mat_t = MaterialLinearElastic1; auto & hard{Mat_t::make(cell, "hard", 210. * ex, .33)}; auto & soft{Mat_t::make(cell, "soft", 70. * ex, .33)}; for (auto pixel : cell) { if ((pixel[0] >= N[0] - incl_size) && (pixel[1] < incl_size) && (pixel[2] >= N[2] - incl_size)) { hard.add_pixel(pixel); } else { soft.add_pixel(pixel); } } std::cout << hard.size() << " pixels in the inclusion" << std::endl; cell.initialise(); constexpr Real cg_tol{1e-8}, newton_tol{1e-5}; constexpr Dim_t maxiter{200}; constexpr Dim_t verbose{1}; Eigen::MatrixXd dF_bar{Eigen::MatrixXd::Zero(dim, dim)}; dF_bar(0, 1) = 1.; SolverCG cg{cell, cg_tol, maxiter, verbose}; auto optimize_res = de_geus(cell, dF_bar, cg, newton_tol, verbose); std::cout << "nb_cg: " << optimize_res.nb_fev << std::endl; std::cout << optimize_res.grad.transpose().block(0, 0, 10, 9) << std::endl; return 0; } diff --git a/bin/small_case.cc b/bin/small_case.cc index 9b1f57a..485ebfd 100644 --- a/bin/small_case.cc +++ b/bin/small_case.cc @@ -1,83 +1,83 @@ /** * @file small_case.cc * * @author Till Junge * * @date 12 Jan 2018 * * @brief small case for debugging * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#include "common/common.hh" -#include "common/iterators.hh" +#include "common/muSpectre_common.hh" #include "cell/cell_factory.hh" #include "materials/material_linear_elastic1.hh" #include "solver/solvers.hh" #include "solver/solver_cg.hh" +#include #include using namespace muSpectre; int main() { constexpr Dim_t dim{twoD}; Ccoord_t resolution{11, 11}; Rcoord_t lengths{ - CcoordOps::get_cube(11.)}; // {5.2e-9, 8.3e-9, 8.3e-9}; + muGrid::CcoordOps::get_cube(11.)}; // {5.2e-9, 8.3e-9, 8.3e-9}; Formulation form{Formulation::finite_strain}; auto rve{make_cell(resolution, lengths, form)}; auto & hard{MaterialLinearElastic1::make(rve, "hard", 210., .33)}; auto & soft{MaterialLinearElastic1::make(rve, "soft", 70., .33)}; for (auto && tup : akantu::enumerate(rve)) { auto & i = std::get<0>(tup); auto & pixel = std::get<1>(tup); if (i < 3) { hard.add_pixel(pixel); } else { soft.add_pixel(pixel); } } rve.initialise(); Real tol{1e-6}; Eigen::MatrixXd Del0{}; Del0 << 0, .1, 0, 0; Uint maxiter{31}; Dim_t verbose{3}; SolverCG cg{rve, tol, maxiter, static_cast(verbose)}; auto res = de_geus(rve, Del0, cg, tol, verbose); std::cout << res.grad.transpose() << std::endl; return 0; } diff --git a/cmake/FindFFTW3.cmake b/cmake/FindFFTW3.cmake new file mode 100644 index 0000000..3c38cf1 --- /dev/null +++ b/cmake/FindFFTW3.cmake @@ -0,0 +1,173 @@ +# - Find the FFTW3 library +# +# Usage: +# find_package(FFTW [REQUIRED] [QUIET] ) +# +# It sets the following variables: +# FFTW3_FOUND ... true if fftw is found on the system +# FFTW3_LIBRARIES ... full path to fftw library +# FFTW3_INCLUDES ... fftw include directory +# +# The following variables will be checked by the function +# FFTW3_USE_STATIC_LIBS ... if true, only static libraries are found +# FFTW3_ROOT ... if set, the libraries are exclusively searched +# under this path +# FFTW3_LIBRARY ... fftw library to use +# FFTW3_INCLUDE_DIR ... fftw include directory +# + +#If environment variable FFTWDIR is specified, it has same effect as FFTW3_ROOT +if(NOT FFTW3_ROOT AND ENV{FFTWDIR}) + set(FFTW3_ROOT $ENV{FFTWDIR}) +endif() + +set(_FFTW3_PRECISIONS "double" "float" "quad") +set(_FFTW3_IMPLEMENTATIONS "sequential" "mpi" "openmp" "threads") + +if(NOT FFTW3_FIND_COMPONENTS) + set(FFTW3_FIND_COMPONENTS "double" "float" "quad") +endif() + +set(_precisions) +set(_implementations) +foreach(_comp ${FFTW3_FIND_COMPONENTS}) + list(FIND _FFTW3_PRECISIONS ${_comp} _pos) + if(NOT _pos EQUAL -1) + list(APPEND _precisions ${_comp}) + else() + list(APPEND _implementations ${_comp}) + endif() +endforeach() + +if("${_implementations}" STREQUAL "") + set(_implementations "sequential") +endif() + +# Check if we can use PkgConfig +find_package(PkgConfig) + +#Determine from PKG +if(PKG_CONFIG_FOUND AND NOT FFTW3_ROOT ) + pkg_check_modules(PKG_FFTW QUIET "fftw3" ) + mark_as_advanced(pkgcfg_lib_PKG_FFTW3_fftw3) +endif() + +#Check whether to search static or dynamic libs +set(CMAKE_FIND_LIBRARY_SUFFIXES_SAV ${CMAKE_FIND_LIBRARY_SUFFIXES}) + +if(${FFTW3_USE_STATIC_LIBS}) + set(CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_STATIC_LIBRARY_SUFFIX}) + set(_import_type STATIC) +else() + set(CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_SHARED_LIBRARY_SUFFIX}) + set(_import_type SHARED) +endif() + +set(_precision_double) +set(_precision_simple "f") +set(_precision_quad "l") + +set(_needed_vars) +foreach(_impl ${_implementations}) + if("${_impl}" STREQUAL "sequential") + set(_suffix) + set(_namespace) + elseif("${_impl}" STREQUAL "openmp") + set(_suffix "_omp") + set(_namespace "::${_impl}") + else() + set(_suffix "_${_impl}") + set(_namespace "::${_impl}") + endif() + + set(_include_suffix) + if("${_impl}" STREQUAL "mpi") + set(_include_suffix "-mpi") + endif() + find_path( + FFTW3_${_impl}_INCLUDE_DIRS + NAMES "fftw3${_include_suffix}.h" + PATHS ${FFTW3_ROOT} ${LIB_INSTALL_DIR} + HINTS ${PKG_FFTW3_PREFIX} ${PKG_FFTW3_LIBRARY_DIRS} + PATH_SUFFIXES "include" + ) + + mark_as_advanced(FFTW3_${_impl}_INCLUDE_DIRS) + + list(APPEND _needed_vars + FFTW3_${_impl}_INCLUDE_DIRS + FFTW3_${_impl}_LIBRARIES + ) + set(FFTW3_${_impl}_LIBRARIES) + + foreach(_prec ${_precisions}) + set(_lib FFTW3_${_prec}_${_impl}_LIBRARY) + + find_library( + ${_lib} + NAMES "fftw3${_precision_${_prec}}${_suffix}" + PATHS ${FFTW3_ROOT} ${LIB_INSTALL_DIR} + HINTS ${PKG_FFTW3_PREFIX} ${PKG_FFTW3_LIBRARY_DIRS} + PATH_SUFFIXES "lib" "lib64" + ) + + + if(${_lib}) + list(APPEND FFTW3_${_impl}_LIBRARIES ${${_lib}}) + + add_library(fftw3::${_prec}${_namespace} ${_import_type} IMPORTED) + set_target_properties(fftw3::${_prec}${_namespace} PROPERTIES + INTERFACE_INCLUDE_DIRECTORIES ${FFTW3_${_impl}_INCLUDE_DIRS} + IMPORTED_LOCATION ${${_lib}}) + + set(FFTW3_${_prec}_FOUND TRUE) + set(FFTW3_${_impl}_FOUND TRUE) + if(NOT DEFINED _fftw_version OR NOT _fftw_version) + file(WRITE "${PROJECT_BINARY_DIR}/_fftw_version.c" + "#include + #include + + int main() { + printf(\"%s\", fftw_version); + return 0; + }") + + try_run(_res _compile + ${PROJECT_BINARY_DIR} + "${PROJECT_BINARY_DIR}/_fftw_version.c" + CMAKE_FLAGS "-DINCLUDE_DIRECTORIES:STRING=${FFTW3_${_impl}_INCLUDE_DIRS}" + LINK_LIBRARIES ${${_lib}} + RUN_OUTPUT_VARIABLE _fftw_version + COMPILE_OUTPUT_VARIABLE _compile_out + ) + + if(_fftw_version) + string(REGEX MATCH "[0-9.]+" _fftw_version ${_fftw_version}) + endif() + endif() + endif() + mark_as_advanced(FFTW3_${_prec}_${_impl}_LIBRARY) + endforeach() +endforeach() + +if(FFTW3_sequential_INCLUDE_DIRS) + set(FFTW3_INCLUDE_DIRS ${FFTW3_sequential_INCLUDE_DIRS} + CACHE PATH "Path to the include of fftw" FORCE) + list(APPEND _needed_vars FFTW3_INCLUDE_DIRS) + mark_as_advanced(FFTW3_INCLUDE_DIRS) +endif() + +if(FFTW3_sequential_LIBRARIES) + set(FFTW3_LIBRARIES ${FFTW3_sequential_LIBRARIES} + CACHE PATH "FFTW libraries" FORCE) + list(APPEND _needed_vars FFTW3_LIBRARIES) + mark_as_advanced(FFTW3_LIBRARIES) +endif() + +set(CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_FIND_LIBRARY_SUFFIXES_SAV}) + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(FFTW3 + REQUIRED_VARS ${_needed_vars} + VERSION_VAR _fftw_version + HANDLE_COMPONENTS) diff --git a/cmake/muTools.cmake b/cmake/muTools.cmake new file mode 100644 index 0000000..6bcb276 --- /dev/null +++ b/cmake/muTools.cmake @@ -0,0 +1,156 @@ +#============================================================================== +# file muspectreTools.cmake +# +# @author Nicolas Richart +# +# @date 11 Jan 2018 +# +# @brief some tool to help to do stuff with cmake in µSpectre +# +# @section LICENSE +# +# Copyright © 2018 Till Junge +# +# µSpectre is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation, either version 3, or (at +# your option) any later version. +# +# µSpectre is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with µSpectre; see the file COPYING. If not, write to the +# Free Software Foundation, Inc., 59 Temple Place - Suite 330, +# Boston, MA 02111-1307, USA. +# + +#[=[.rst: +µTools +------ + +Common cmake function to the µ* projects + +:: + +muTools_move_to_project(target) + +Moves the output of a given target to the root PROJECT_BINARY_DIR + +:: + +muTools_add_test(test_name + [HEADER_ONLY] + [TYPE BOOST|PYTHON] + [MPI_NB_PROCS] + [TARGET] + [SOURCES] + [LINK_LIBRARIES libraries|targets] + ) + + +]=] +# + + +function(muTools_move_to_project target) + get_property(_output_name TARGET ${target} PROPERTY OUTPUT_NAME) + get_filename_component(_output_name_exe "${_output_name}" NAME) + file(RELATIVE_PATH _output_name + ${CMAKE_CURRENT_BINARY_DIR} "${PROJECT_BINARY_DIR}/${target}") + set_property(TARGET ${target} + PROPERTY OUTPUT_NAME "${_output_name}") +endfunction() + +# ------------------------------------------------------------------------------ +function(muTools_add_test test_name) + include(CMakeParseArguments) + + set(_mat_flags + HEADER_ONLY + ) + set(_mat_one_variables + TYPE + MPI_NB_PROCS + TARGET + TEST_LIST + ) + set(_mat_multi_variables + SOURCES + LINK_LIBRARIES + ) + + cmake_parse_arguments(_mat_args + "${_mat_flags}" + "${_mat_one_variables}" + "${_mat_multi_variables}" + ${ARGN} + ) + + if ("${_mat_args_TYPE}" STREQUAL "BOOST") + elseif("${_mat_args_TYPE}" STREQUAL "PYTHON") + else () + message (SEND_ERROR "Can only handle types 'BOOST' and 'PYTHON'") + endif ("${_mat_args_TYPE}" STREQUAL "BOOST") + + if ("${_mat_args_TYPE}" STREQUAL "BOOST") + if(DEFINED _mat_args_TARGET) + set(target_test_name ${_mat_args_TARGET}) + else() + set(target_test_name ${test_name}) + endif() + + if(NOT TARGET ${target_test_name}) + add_executable(${target_test_name} ${_mat_args_SOURCES}) + if(_mat_args_TEST_LIST) + set(_tmp ${${_mat_args_TEST_LIST}}) + list(APPEND _tmp ${target_test_name}) + set(${_mat_args_TEST_LIST} ${_tmp} PARENT_SCOPE) + endif() + muTools_move_to_project(${target_test_name}) + + target_link_libraries(${target_test_name} + PRIVATE ${Boost_LIBRARIES} cxxopts ${_mat_args_LINK_LIBRARIES}) + + if(_mat_HEADER_ONLY) + foreach(_target ${_mat_args_LINK_LIBRARIES}) + if(TARGET ${_target}) + get_target_property(_features ${_target} INTERFACE_COMPILE_FEATURES) + target_compile_features(${target_test_name} + PRIVATE ${_features}) + endif() + endforeach() + endif() + endif() + endif() + + if ("${_mat_args_TYPE}" STREQUAL "BOOST") + set(_exe $ ${_mat_args_UNPARSED_ARGUMENTS}) + else() + set(_exe ${_mat_args_UNPARSED_ARGUMENTS}) + endif() + + + if (${MUSPECTRE_RUNNING_IN_CI}) + if ("${_mat_args_TYPE}" STREQUAL "BOOST") + list(APPEND _exe "--logger=JUNIT,all,test_results_${test_name}.xml") + elseif("${_mat_args_TYPE}" STREQUAL "PYTHON") + set(_exe ${PYTHON_EXECUTABLE} -m pytest --junitxml test_results_${test_name}.xml ${_exe}) + endif ("${_mat_args_TYPE}" STREQUAL "BOOST") + else () + if("${_mat_args_TYPE}" STREQUAL "PYTHON") + set(_exe ${PYTHON_EXECUTABLE} ${_exe}) + endif ("${_mat_args_TYPE}" STREQUAL "PYTHON") + endif (${MUSPECTRE_RUNNING_IN_CI}) + + if(${_mat_args_MPI_NB_PROCS}) + set(_exe ${MPIEXEC_EXECUTABLE} ${MPIEXEC_PREFLAGS} ${MPIEXEC_NUMPROC_FLAG} ${_mat_args_MPI_NB_PROCS} ${_exe}) + endif(${_mat_args_MPI_NB_PROCS}) + + add_test( + NAME ${test_name} + COMMAND ${_exe} + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) +endfunction() diff --git a/cmake/muspectreTools.cmake b/cmake/muspectreTools.cmake index 753bcae..d64cc92 100644 --- a/cmake/muspectreTools.cmake +++ b/cmake/muspectreTools.cmake @@ -1,262 +1,259 @@ #============================================================================== # file muspectreTools.cmake # # @author Nicolas Richart # # @date 11 Jan 2018 # # @brief some tool to help to do stuff with cmake in µSpectre # # @section LICENSE # # Copyright © 2018 Till Junge # # µSpectre is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation, either version 3, or (at # your option) any later version. # # µSpectre is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with µSpectre; see the file COPYING. If not, write to the # Free Software Foundation, Inc., 59 Temple Place - Suite 330, # Boston, MA 02111-1307, USA. # #[=[.rst: µSpectreTools ------------- This module provide some helper functions for µSpectre :: download_external_project(project_name URL BACKEND [TAG ] [THIRD_PARTY_SRC_DIR ] [NO_UPDATE] ) Downloads the external project based on the uri ``THIRD_PARTY_SRC_DIR `` Specifies where to download the source ``NO_UPDATE`` Does not try to update existing download :: mark_as_advanced_prefix(prefix) Marks as advanced all variables whoes names start with prefix :: add_external_dep(package [IGNORE_SYSTEM] [VERSION ] [...]) Tries to find the external package and if not found but a local ${package}.cmake files exists, it includes it. The extra arguments are passed to find_package() ``IGNORE_SYSTEM`` does not do the find_package ``VERSION`` Specifies the required minimum version ]=] # +if(MUSPECTRETOOLS_INCLUDED) + return() +endif() +set(MUSPECTRETOOLS_INCLUDED TRUE) + function(download_external_project project_name) include(CMakeParseArguments) set(_dep_flags NO_UPDATE) set(_dep_one_variables URL TAG BACKEND THIRD_PARTY_SRC_DIR ) set(_dep_multi_variables) cmake_parse_arguments(_dep_args "${_dep_flags}" "${_dep_one_variables}" "${_dep_multi_variables}" ${ARGN} ) if(NOT _dep_args_URL) message(FATAL_ERROR "You have to provide a URL for the project ${project_name}") endif() if(NOT _dep_args_BACKEND) message(FATAL_ERROR "You have to provide a backend to download ${project_name}") endif() if(_dep_args_TAG) set(_ep_tag "${_dep_args_BACKEND}_TAG ${_dep_args_TAG}") endif() set(_src_dir ${PROJECT_SOURCE_DIR}/third-party/${project_name}) if (_dep_args_THIRD_PARTY_SRC_DIR) set(_src_dir ${_dep_args_THIRD_PARTY_SRC_DIR}/${project_name}) endif() if(EXISTS ${_src_dir}/.DOWNLOAD_SUCCESS AND _dep_args_NO_UPDATE) return() endif() set(_working_dir ${PROJECT_BINARY_DIR}/third-party/${project_name}-download) file(WRITE ${_working_dir}/CMakeLists.txt " cmake_minimum_required(VERSION 3.1) project(${project_name}-download NONE) include(ExternalProject) ExternalProject_Add(${project_name} SOURCE_DIR ${_src_dir} BINARY_DIR ${_working_dir} ${_dep_args_BACKEND}_REPOSITORY ${_dep_args_URL} ${_ep_tag} CONFIGURE_COMMAND \"\" BUILD_COMMAND \"\" INSTALL_COMMAND \"\" TEST_COMMAND \"\" ) ") message(STATUS "Downloading ${project_name} ${_dep_args_GIT_TAG}") execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" . RESULT_VARIABLE _result WORKING_DIRECTORY ${_working_dir} OUTPUT_FILE ${_working_dir}/configure-out.log ERROR_FILE ${_working_dir}/configure-error.log) if(_result) message(FATAL_ERROR "Something went wrong (${_result}) during the download" " process of ${project_name} check the file" " ${_working_dir}/configure-error.log for more details:") file(STRINGS "${_working_dir}/configure-error.log" ERROR_MSG) message("${ERROR_MSG}") endif() execute_process(COMMAND "${CMAKE_COMMAND}" --build . RESULT_VARIABLE _result WORKING_DIRECTORY ${_working_dir} OUTPUT_FILE ${_working_dir}/build-out.log ERROR_FILE ${_working_dir}/build-error.log) if(_result) message(FATAL_ERROR "Something went wrong (${_result}) during the download" " process of ${project_name} check the file" " ${_working_dir}/build-error.log for more details") endif() file(WRITE ${_src_dir}/.DOWNLOAD_SUCCESS "") endfunction() # ------------------------------------------------------------------------------ function(mark_as_advanced_prefix prefix) get_property(_list DIRECTORY PROPERTY VARIABLES) foreach(_var ${_list}) - if(${_var} MATCHES "^${prefix}.*") + if("${_var}" MATCHES "^${prefix}") mark_as_advanced(${_var}) endif() endforeach() endfunction() # ------------------------------------------------------------------------------ function(add_external_package package) include(CMakeParseArguments) set(_cmake_includes ${PROJECT_SOURCE_DIR}/cmake) set(_${package}_external_dir ${PROJECT_BINARY_DIR}/external) set(_aep_flags IGNORE_SYSTEM ) set(_aep_one_variables VERSION ) set(_aep_multi_variables) cmake_parse_arguments(_aep_args "${_aep_flags}" "${_aep_one_variables}" "${_aep_multi_variables}" ${ARGN} ) if(_aep_args_VERSION) set(_${package}_version ${_aep_args_VERSION}) endif() if(NOT EXISTS ${_cmake_includes}/${package}.cmake) set(_required REQUIRED) endif() if(NOT _aep_args_IGNORE_SYSTEM) find_package(${package} ${_${package}_version} ${_required} ${_aep_UNPARSED_ARGUMENTS} QUIET) if(${package}_FOUND AND NOT ${package}_FOUND_EXTERNAL) + string(TOUPPER ${package} u_package) + mark_as_advanced_prefix(${package}) + mark_as_advanced_prefix(${u_package}) return() endif() endif() if(EXISTS ${_cmake_includes}/${package}.cmake) include(${_cmake_includes}/${package}.cmake) endif() + + string(TOUPPER ${package} u_package) + mark_as_advanced_prefix(${package}) + mark_as_advanced_prefix(${u_package}) endfunction() - -function(muSpectre_add_test test_name) - include(CMakeParseArguments) - - set(_mat_flags - ) - set(_mat_one_variables - TYPE - MPI_NB_PROCS - ) - set(_mat_multi_variables) - - cmake_parse_arguments(_mat_args - "${_mat_flags}" - "${_mat_one_variables}" - "${_mat_multi_variables}" - ${ARGN} - ) - - if ("${_mat_args_TYPE}" STREQUAL "BOOST") - elseif("${_mat_args_TYPE}" STREQUAL "PYTHON") - else () - message (SEND_ERROR "Can only handle types 'BOOST' and 'PYTHON'") - endif ("${_mat_args_TYPE}" STREQUAL "BOOST") - - set(_exe ${_mat_args_UNPARSED_ARGUMENTS}) - if (${RUNNING_IN_CI}) - if ("${_mat_args_TYPE}" STREQUAL "BOOST") - LIST(APPEND _exe "--logger=JUNIT,all,test_results_${test_name}.xml") - elseif("${_mat_args_TYPE}" STREQUAL "PYTHON") - set(_exe ${PYTHON_EXECUTABLE} -m pytest --junitxml test_results_${test_name}.xml ${_exe}) - endif ("${_mat_args_TYPE}" STREQUAL "BOOST") - else () - if("${_mat_args_TYPE}" STREQUAL "PYTHON") - set(_exe ${PYTHON_EXECUTABLE} ${_exe}) - endif ("${_mat_args_TYPE}" STREQUAL "PYTHON") - endif (${RUNNING_IN_CI}) - - if(${_mat_args_MPI_NB_PROCS}) - set(_exe ${MPIEXEC_EXECUTABLE} ${MPIEXEC_PREFLAGS} ${MPIEXEC_NUMPROC_FLAG} ${_mat_args_MPI_NB_PROCS} ${_exe}) - endif(${_mat_args_MPI_NB_PROCS}) - - add_test(${test_name} ${_exe}) +# ------------------------------------------------------------------------------ +function(muSpectre_set_global_compile_options) + add_compile_options(-Wall -Wextra -Weffc++) + + string(TOLOWER "${CMAKE_BUILD_TYPE}" build_type ) + if ("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang") + # using Clang + add_compile_options(-Wno-missing-braces) + if ("debug" STREQUAL "${build_type}") + add_compile_options(-O0) + endif() + elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") + # using GCC + add_compile_options(-Wno-non-virtual-dtor) + add_compile_options(-march=native) + if (("relwithdebinfo" STREQUAL "${build_type}") OR ("release" STREQUAL "${build_type}" )) + add_compile_options(-march=native) + endif() + if ("debug" STREQUAL "${build_type}" ) + add_compile_options(-O0 -g3 -ggdb3) + endif() + elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Intel") + # using Intel C++ + elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") + # using Visual Studio C++ + endif() endfunction() + +# ------------------------------------------------------------------------------ diff --git a/doc/dev-docs/source/CodingConvention.rst b/doc/dev-docs/source/CodingConvention.rst index 36563f7..b5ebcc1 100644 --- a/doc/dev-docs/source/CodingConvention.rst +++ b/doc/dev-docs/source/CodingConvention.rst @@ -1,3080 +1,3080 @@ Coding Convention ~~~~~~~~~~~~~~~~~ .. contents:: :local: Objectives of the Convention **************************** *µ*\Spectre is a collaborative project and these coding conventions aim to make reading and understanding its code as pain-free as possible, while ensuring the four main requirements of the library #. Versatility #. Efficiency #. Reliability #. Ease-of-use *Versatility* requires that the core of the code, i.e., the data structures and fundamental algorithms be written in a generic fashion. The genericity cannot come at the cost of the second requirement -- *Efficiency* -- which is the reason why the material base classes make extensive use of template metaprogramming and expression templates. *Reliability* can only be enforced through good unit testing with high test coverage, and *ease-of-use* relies on a good documentation for developers and users alike. Review of submitted code is the main mechanism to enforce the coding conventions. .. _structure: Structure ********* This section contains planned features that are not yet implemented, but that need to be considered during the development effort. The goal of this section is to define a maintainable and testable architecture for *µ*\Spectre. In order to achieve this, the software is segmented in modules that perform one testable task each and are linked through well defined interfaces. This way, when the implementation of a module changes, the other modules do not need to be adapted, as long as the interfaces are respected. In the case of *µ*\Spectre, the central task is the evaluation of RVEs, referred to as the core library, and there are the different language bindings, and the FEM plugins. This segmentation to obtain maintainability and testability follows the *Don't repeat yourself!* (DRY) principle stated as *"Every piece of knowledge must have a single, unambiguous, authoritative representation within a system"* by `Hunt (2000)`_: Since all algorithms and procedures are implemented only once and only in the core library, there is only one unit test per feature to implement and maintain. Unit tests for the language bindings do not need to retest these features and test merely correct wrapping and proper memory management. An exception to this rule are tests that are more convenient to implement in any of the bound languages rather than in a C++ test (e.g. the FFT module is tested in python against `numpy.fft `_ as reference. Figure `1`_ shows a schematic of the projected structure and identifies a chain of three modules, where each new module depends on the previous one. The first module contains only existing external (third-party) FFT implementations and is not part of the development effort for this project. The block is listed for clarity since the choices made here determine the type of machines the final code can run on. The second module consists of i) the core library, which encapsulates the implementation of the spectral homogenisation method and represents the major projected development and maintenance effort, as well as ii) a set of language bindings. This second module allows single-scale RVE computations directly in most of the popular computing environments. It furthermore allows to rapidly prototype a simulation in a convenient interactive environment such as Jupyter or Matlab, and scale it up to a computing cluster when necessary using the same software. The third and last module is a collection of plugins for multiple open-source and commercial FEM codes and provides coupled concurrent multiscale computation capabilities in the spirit of FE². .. _`1` : .. figure:: ../MainSchema.png Figure 1: Principal modules of the platform. Boxes with dashed lines mark optional modules. External libraries refer to established and well-tested existing third-party FFT implementations. The core library *µ*\Spectre represents the main development objective of this project and will be written in modern C++14 and wrapped in language bindings for Fortran, Python, and Matlab in order to be usable for single-scale computations by most researchers in their favourite computing environment. Plugins for multiple open-source and commercial FEM codes will use either the core library directly (Akantu, OOFEM), the Fortran language binding (ANSYS, Abaqus), or the Python language binding (FEniCS). Documentation ************* There are two types of Documentation for *µ*\Spectre: on the one hand, there is this monograph which is supposed to serve as reference manual to understand, and use the library and its extensions, and to look up APIs and data structures. On the other hand, there is in-code documentation helping the developer to understand the role of functions, variables, member (function)s and steps in algorithms. The in-code documentation uses the syntax of `the doxygen documentation generator `_, as its lightweight markup language is very readable in the code and allows to generate the standalone API documentation in :ref:`Reference`. All lengthier, text-based documentation is written for `Sphinx `_ in `reStructuredText `_. This allows to write longer, more expressive texts, such as this convention or the :ref:`tutorials`. Testing ******* *Every* feature in *µ*\Spectre's core library is supposed to be unit tested, and a missing test is considered a bug. Core library features are unit tested in the C++ unit tests (preferred option) or the python unit tests (both within the ``tests`` folder), because external contributors should not be expected to compile all the language bindings. The unit tests typically use the `Boost unit test framework `_ to define C++ test cases and python's `unittest `_ module for python tests. If necessary, standalone tests can be added by contributors, provided that they are added as ``ctest`` targets to the project's main CMake file. See in the ``tests`` folder for examples regarding the tests. .. _`cpp coding style and convention`: C++ Coding Style and Convention ******************************* These are heavily inspired by the `Google C++ Style Guide `_ but are *not compatible* with it. These guidelines mostly establish a common vocabulary to write common code and do not give advice for efficient programming practices. For that, follow Scott Meyers book :ref:`Effective Modern C++ `. As far as possible, the guidelines given in that book are also enforced by the ``-Weffc++`` compile flag. The goals of this style guide are: Style rules should pull their weight The benefit of a style rule must be large enough to justify asking all of our engineers to remember it. The benefit is measured relative to the code base we would get without the rule, so a rule against a very harmful practice may still have a small benefit if people are unlikely to do it anyway. This principle mostly explains the rules we don’t have, rather than the rules we do: for example, ``goto`` contravenes many of the following principles, but is already vanishingly rare, so the Style Guide doesn’t discuss it. Optimise for the reader, not the writer Our core library (and most individual components submitted to it) is expected to continue for quite some time, and we will hopefully attract more external contributors. As a result, more time will be spent reading most of our code than writing it. We explicitly choose to optimise for the experience of our average contributor reading, maintaining, and debugging code in our code base rather than ease when writing said code. "Leave a trace for the reader" is a particularly common sub-point of this principle: When something surprising or unusual is happening in a snippet of code (for example, use of raw pointers in the ``FFTEngine`` classes), leaving textual hints for the reader at the point of use is valuable. Use explicit traces of ownership of objects on the heap using smart pointers such as ``std::unique_ptr`` and ``std::shared_ptr``. Be consistent with existing code Using one style consistently through our code base lets us focus on other (more important) issues. Consistency also allows for automation: tools that format your code or adjust your ``#includes`` only work properly when your code is consistent with the expectations of the tooling. In many cases, rules that are attributed to "Be Consistent" boil down to "Just pick one and stop worrying about it"; the potential value of allowing flexibility on these points is outweighed by the cost of having people argue over them. Be consistent with the broader C++ community when appropriate Consistency with the way other organisations use C++ has value for the same reasons as consistency within our code base. If a feature in the C++ standard solves a problem, or if some idiom is widely known and accepted, that's an argument for using it. However, sometimes standard features and idioms are flawed, or were just designed without our efficiency needs in mind. In those cases (as described below) it's appropriate to constrain or ban standard features. Avoid surprising or dangerous constructs C++ has features that are more surprising or dangerous than one might think at a glance. Some style guide restrictions are in place to prevent falling into these pitfalls. There is a high bar for style guide waivers on such restrictions, because waiving such rules often directly risks compromising program correctness. Avoid constructs that our average C++ programmer would find tricky or hard to maintain in the constitutive laws and solvers C++ has features that may not be generally appropriate because of the complexity they introduce to the code. In the core library, where we make heavy use of template metaprogramming and expression templates for efficiency, it totally fine to use trickier language constructs, because any benefits of more complex implementation are multiplied widely by usage, and the cost in understanding the complexity does not need to be paid by the average contributor who writes a new material or solver. When in doubt, waivers to rules of this type can be sought by asking on the `discussion forum `_. Concede to optimisation when necessary Performance is the overwhelming priority in the **core library** (i.e., data structures and low level algorithms that the typical user relies on often, but rarely uses directly). If performance optimisation is in conflict with other principles in this document, optimise. Header Files ============ In general, every ``.cc`` file should have an associated ``.hh`` file. There are some common exceptions, such as unit tests and small ``.cc`` files containing just a ``main()`` function (e.g., see in the ``bin`` folder). Correct use of header files can make a huge difference to the readability, size and performance of your code. The following rules will guide you through the various pitfalls of using header files. .. _`self-contained headers`: Self-contained Headers ---------------------- Header files should be self-contained (compile on their own) and end in ``.hh``. There should not be any non-header files that are meant for inclusion. All header files should be self-contained. Users and refactoring tools should not have to adhere to special conditions to include the header. Specifically, a header should have header guards and include all other headers it needs. Prefer placing the definitions for inline functions in the same file as their declarations. The definitions of these constructs must be included into every ``.cc`` file that uses them, or the program may fail to link in some build configurations. If declarations and definitions are in different files, including the former should transitively include the latter. Do not move these definitions to separately included header files (``-inl.hh``); this practice was common in the past, but is no longer allowed. As an exception, a template that is explicitly instantiated for all relevant sets of template arguments, or that is a private implementation detail of a class, is allowed to be defined in the one and only ``.cc`` file that instantiates the template, see ``material_linear_elastic1.cc`` for an example. .. _`define guard`: The ``#define`` Guard --------------------- All header files should have ``#define`` guards to prevent multiple inclusion. The format of the symbol name should be ``CLASS_NAME_H`` (all caps with underscores), where ``ClassName`` (CamelCase) is the main class declared it the header file. Make sure to use unique file names to avoid triggering the wrong ``#define`` guard. Forward Declarations -------------------- Use forward declarations of *µ*\Spectre entities where it avoids ``include``\s and saves compile time. A "forward declaration" is a declaration of a class, function, or template without an associated definition. Pros: - Forward declarations can save compile time, as ``#include``\s force the compiler to open more files and process more input. - Forward declarations can save on unnecessary recompilation. ``#include``\s can force your code to be recompiled more often, due to unrelated changes in the header. Cons: - Forward declarations can hide a dependency, allowing user code to skip necessary recompilation when headers change. - A forward declaration may be broken by subsequent changes to the library. Forward declarations of functions and templates can prevent the header owners from making otherwise-compatible changes to their APIs, such as widening a parameter type, adding a template parameter with a default value, or migrating to a new namespace. - Forward declaring symbols from namespace std:: yields undefined behaviour. - It can be difficult to determine whether a forward declaration or a full ``#include`` is needed. Replacing an ``#include`` with a forward declaration can silently change the meaning of code: .. code-block:: c++ // b.hh: struct B {}; struct D : B {}; // good_user.cc: #include "b.hh" void f(B*); void f(void*); void test(D* x) { f(x); } // calls f(B*) If the #include was replaced with forward declarations for ``B`` and ``D``, ``test()`` would call ``f(void*)``. - Forward declaring multiple symbols from a header can be more verbose than simply ``#include``\ing the header. Try to avoid forward declarations of entities defined in another project. .. _`inline functions`: Inline Functions ---------------- Use inline functions for performance-critical code. Also, templated member functions that that cannot be explicitly instantiated need to be declared inline. Names and Order of Includes --------------------------- All of a project's header files should be listed as descendants of the project's source directory without use of UNIX directory shortcuts ``.`` (the current directory) or ``..`` (the parent directory). For example, ``muSpectre/src/common/ccoord_operations.hh`` should be included as: .. code-block:: c++ - #include "common/ccoord_operations.hh" + #include Use the following order for includes to avoid hidden dependencies: #. *µ*\Spectre headers #. A blank line #. Other libraries' headers #. A blank line #. C++ system headers With this ordering, if a *µ*\Spectre header omits any necessary includes, the build will break. Thus, this rule ensures that build breaks show up first for the people working on these files, not for innocent people in different places. You should include all the headers that define the symbols you rely upon, except in the case of forward declaration. If you rely on symbols from ``bar.hh``, don't count on the fact that you included ``foo.hh`` which (currently) includes ``bar.hh``: include ``bar.hh`` yourself, unless ``foo.hh`` explicitly demonstrates its intent to provide you the symbols of ``bar.hh``. However, any includes present in the related header do not need to be included again in the related ``.cc`` (i.e., ``foo.cc`` can rely on ``foo.hh``'s includes). Scoping ======= .. _namespaces: Namespaces ---------- With few exceptions, place code in the namespace ``muSpectre``. All other (subordinate) namespaces should have unique, expressive names based on their purpose. Do not use using-directives (e.g. ``using namespace foo``) within the core library (but feel free to do so in the executables in the ``bin`` folder). Do not use inline namespaces. For unnamed namespaces, see :ref:`unnamed`. Definition: Namespaces subdivide the global scope into distinct, named scopes, and so are useful for preventing name collisions in the global scope. Pros: - Namespaces provide a method for preventing name conflicts in large programs while allowing most code to use reasonably short names. For example, if two different projects have a class ``Foo`` in the global scope, these symbols may collide at compile time or at runtime. If each project places their code in a namespace, ``project1::Foo`` and ``project2::Foo`` are now distinct symbols that do not collide, and code within each project's namespace can continue to refer to Foo without the prefix. - Inline namespaces automatically place their names in the enclosing scope. Consider the following snippet, for example: .. code-block:: c++ namespace outer { inline namespace inner { void foo(); } // namespace inner } // namespace outer The expressions ``outer::inner::foo()`` and ``outer::foo()`` are interchangeable. Inline namespaces are primarily intended for ABI compatibility across versions. Cons: - Inline namespaces, in particular, can be confusing because names aren't actually restricted to the namespace where they are declared. They are only useful as part of some larger versioning policy. - In some contexts, it's necessary to repeatedly refer to symbols by their fully-qualified names. For deeply-nested namespaces, this can add a lot of clutter. Decision: Namespaces should be used as follows: - Follow the rules on :ref:`namespace names`. - Terminate namespaces with comments as shown in the given examples. - Namespaces wrap the entire source file after includes and forward declarations of classes from other namespaces. .. code-block:: c++ // In the .hh file namespace mynamespace { // All declarations are within the namespace scope. // Notice the lack of indentation. class MyClass { public: ... void Foo(); }; } // namespace mynamespace // In the .cc file namespace mynamespace { // Definition of functions is within scope of the namespace. void MyClass::Foo() { ... } } // namespace mynamespace More complex ``.cc`` files might have additional details, using-declarations. .. code-block:: c++ #include "a.h" namespace mynamespace { using ::foo::bar; ...code for mynamespace... // Code goes against the left margin. } // namespace mynamespace - Do not declare anything in namespace ``std``, including forward declarations of standard library classes. Declaring entities in namespace ``std`` is undefined behaviour, i.e., not portable. To declare entities from the standard library, include the appropriate header file. - You may not use a *using-directive* to make all names from a namespace available (namespace clobbering). .. code-block:: c++ // Forbidden -- This pollutes the namespace. using namespace foo; - Do not use *namespace aliases* at namespace scope in header files except in explicitly marked internal-only namespaces, because anything imported into a namespace in a header file becomes part of the public API exported by that file. .. code-block:: c++ // Shorten access to some commonly used names in .cc files. namespace baz = ::foo::bar::baz; // Shorten access to some commonly used names (in a .h file). namespace librarian { namespace impl { // Internal, not part of the API. namespace sidetable = ::pipeline_diagnostics::sidetable; } // namespace impl inline void my_inline_function() { // namespace alias local to a function (or method). namespace baz = ::foo::bar::baz; ... } } // namespace librarian - Do not use inline namespaces. .. _unnamed: Unnamed Namespaces and Static Variables --------------------------------------- When definitions in a ``.cc`` file do not need to be referenced outside that file, place them in an unnamed namespace or declare them static. Do not use either of these constructs in ``.hh`` files. All declarations can be given internal linkage by placing them in unnamed namespaces. Functions and variables can also be given internal linkage by declaring them static. This means that anything you're declaring can't be accessed from another file. If a different file declares something with the same name, then the two entities are completely independent. Use of internal linkage in ``.cc`` files is encouraged for all code that does not need to be referenced elsewhere. Do not use internal linkage in ``.hh`` files. Format unnamed namespaces like named namespaces. In the terminating comment, leave the namespace name empty: .. code-block:: c++ namespace { ... } // namespace Nonmember, Static Member, and Global Functions ---------------------------------------------- Prefer placing nonmember functions in a namespace; use completely global functions rarely. Note: placing functions in a namespace keeps them globally accessible, the goal of this is not to suppress the use of non-member functions but rather to avoid polluting the global and ``muSpectre`` namespace by grouping them together in thematic namespaces, see for instance the namespace ``MatTB`` in ``materials/materials_toolbox.cc``. Do not use a class simply to group static functions, unless they are function templates which need to be partially specialised. Otherwise, static methods of a class should generally be closely related to instances of the class or the class's static data. Pros: Nonmember and static member functions can be useful in some situations. Putting nonmember functions in a namespace avoids polluting the global namespace. Cons: Nonmember and static member functions may make more sense as members of a new class, especially if they access external resources or have significant dependencies. Decision: Sometimes it is useful to define a function not bound to a class instance. Such a function can be either a static member or a nonmember function. Nonmember functions should not depend on external variables, and should nearly always exist in a namespace. Do not create classes only to group static member functions, unless they are function templates which need to be partially specialised; otherwise, this is no different than just giving the function names a common prefix, and such grouping is usually unnecessary anyway. If you define a nonmember function and it is only needed in its ``.cc`` file, use :ref:`internal linkage ` to limit its scope. Local Variables --------------- Place a function's variables in the narrowest scope possible, and initialise variables in the declaration. C++ allows you to declare variables anywhere in a function. We encourage you to declare them in as local a scope as possible, and as close to the first use as possible. This makes it easier for the reader to find the declaration and see what type the variable is and what it was initialised to. In particular, initialisation should be used instead of declaration and assignment, e.g.: .. code-block:: c++ int i; i = f(); // Bad -- initialisation separate from declaration. int j{g()}; // Good -- declaration has initialisation. std::vector v; v.push_back(1); // Prefer initialising using brace initialisation. v.push_back(2); std::vector v = {1, 2}; // Good -- v starts initialised. Prefer C++11-style universal initialisation (``int i{0}``) over legacy initialisation (``int i = 0``). Variables needed for ``if``, ``while`` and ``for`` statements should normally be declared within those statements, so that such variables are confined to those scopes. E.g.: .. code-block:: c++ for (size_t i{0}; i < DimS; ++i) { ... } There is one caveat: if the variable is an object, its constructor is invoked every time it enters scope and is created, and its destructor is invoked every time it goes out of scope. .. code-block:: c++ // Inefficient implementation: for (int i = 0; i < 1000000; ++i) { Foo f; // My ctor and dtor get called 1000000 times each. f.do_something(i); } It may be more efficient to declare such a variable used in a loop outside that loop: .. code-block:: c++ Foo f; // My ctor and dtor get called once each. for (int i = 0; i < 1000000; ++i) { f.do_something(i); } Static and Global Variables --------------------------- Objects with `static storage duration `_ are forbidden unless they are `trivially destructible `_. Informally this means that the destructor does not do anything, even taking member and base destructors into account. More formally it means that the type has no user-defined or virtual destructor and that all bases and non-static members are trivially destructible. Static function-local variables may use dynamic initialisation. Use of dynamic initialisation for static class member variables or variables at namespace scope is discouraged, but allowed in limited circumstances; see below for details. As a rule of thumb: a global variable satisfies these requirements if its declaration, considered in isolation, could be ``constexpr``. Definition: Every object has a *storage duration*, which correlates with its lifetime. Objects with static storage duration live from the point of their initialisation until the end of the program. Such objects appear as variables at namespace scope ("global variables"), as static data members of classes, or as function-local variables that are declared with the ``static`` specifier. Function-local static variables are initialised when control first passes through their declaration; all other objects with static storage duration are initialised as part of program start-up. All objects with static storage duration are destroyed at program exit (which happens before unjoined threads are terminated). Initialisation may be *dynamic*, which means that something non-trivial happens during initialisation. (For example, consider a constructor that allocates memory, or a variable that is initialised with the current process ID.) The other kind of initialisation is *static* initialisation. The two aren't quite opposites, though: static initialisation *always* happens to objects with static storage duration (initialising the object either to a given constant or to a representation consisting of all bytes set to zero), whereas dynamic initialisation happens after that, if required. Pros: Global and static variables are very useful for a large number of applications: named constants, auxiliary data structures internal to some translation unit, command-line flags, logging, registration mechanisms, background infrastructure, etc. Cons: Global and static variables that use dynamic initialisation or have non-trivial destructors create complexity that can easily lead to hard-to-find bugs. Dynamic initialisation is not ordered across translation units, and neither is destruction (except that destruction happens in reverse order of initialisation). When one initialisation refers to another variable with static storage duration, it is possible that this causes an object to be accessed before its lifetime has begun (or after its lifetime has ended). Moreover, when a program starts threads that are not joined at exit, those threads may attempt to access objects after their lifetime has ended if their destructor has already run. Decision: Decision on destruction When destructors are trivial, their execution is not subject to ordering at all (they are effectively not "run"); otherwise we are exposed to the risk of accessing objects after the end of their lifetime. Therefore, we only allow objects with static storage duration if they are trivially destructible. Fundamental types (like pointers and int) are trivially destructible, as are arrays of trivially destructible types. Note that variables marked with ``constexpr`` are trivially destructible. .. code-block:: c++ const int kNum{10}; // allowed struct X { int n; }; const X kX[]{{1}, {2}, {3}}; // allowed void foo() { static const char* const kMessages[]{"hello", "world"}; // allowed } // allowed: constexpr guarantees trivial destructor constexpr std::array kArray {{1, 2, 3}}; .. code-block:: c++ // bad: non-trivial destructor const string kFoo("foo"); // bad for the same reason, even though kBar is a reference (the // rule also applies to lifetime-extended temporary objects) const string& kBar(StrCat("a", "b", "c")); void bar() { // bad: non-trivial destructor static std::map kData{{1, 0}, {2, 0}, {3, 0}}; } Note that references are not objects, and thus they are not subject to the constraints on destructibility. The constraint on dynamic initialisation still applies, though. In particular, a function-local static reference of the form ``static T& t = *new T``; is allowed. Decision on initialisation Initialisation is a more complex topic. This is because we must not only consider whether class constructors execute, but we must also consider the evaluation of the initialiser: .. code-block:: c++ int n{5}; // fine int m{f()}; // ? (depends on f) Foo x; // ? (depends on Foo::Foo) Bar y{g()}; // ? (depends on g and on Bar::Bar) All but the first statement expose us to indeterminate initialisation ordering. The concept we are looking for is called *constant initialisation* in the formal language of the C++ standard. It means that the initialising expression is a constant expression, and if the object is initialised by a constructor call, then the constructor must be specified as ``constexpr``, too: .. code-block:: c++ struct Foo { constexpr Foo(int) {} }; int n{5}; // fine, 5 is a constant expression Foo x(2); // fine, 2 is a constant expression and the chosen constructor is constexpr Foo a[] { Foo(1), Foo(2), Foo(3) }; // fine Constant initialisation is always allowed. Constant initialisation of static storage duration variables should be marked with ``constexpr``. Any non-local static storage duration variable that is not so marked should be presumed to have dynamic initialisation, and reviewed very carefully. By contrast, the following initialisations are problematic: .. code-block:: c++ time_t time(time_t*); // not ``constexpr``! int f(); // not ``constexpr``! struct Bar { Bar() {} }; time_t m{time(nullptr)}; // initialising expression not a constant expression Foo y(f()); // ditto Bar b; // chosen constructor Bar::Bar() not ``constexpr`` Dynamic initialisation of nonlocal variables is discouraged, and in general it is forbidden. However, we do permit it if no aspect of the program depends on the sequencing of this initialisation with respect to all other initialisations. Under those restrictions, the ordering of the initialisation does not make an observable difference. For example: .. code-block:: c++ int p{getpid()}; // allowed, as long as no other static variable // uses p in its own initialisation Dynamic initialisation of static local variables is allowed (and common). Common patterns - Global strings: if you require a global or static string constant, consider using a simple character array, or a char pointer to the first element of a string literal. String literals have static storage duration already and are usually sufficient. - Maps, sets, and other dynamic containers: if you require a static, fixed collection, such as a set to search against or a lookup table, you cannot use the dynamic containers from the standard library as a static variable, since they have non-trivial destructors. Instead, consider a simple array of trivial types, e.g. an array of arrays of ``int`` (for a "map from ``int`` to ``int``"), or an array of pairs (e.g. pairs of ``int`` and ``const char*``). For small collections, linear search is entirely sufficient (and efficient, due to memory locality). If necessary, keep the collection in sorted order and use a binary search algorithm. If you do really prefer a dynamic container from the standard library, consider using a function-local static pointer, as described below. - Smart pointers (``std::unique_ptr``, ``std::shared_ptr``): smart pointers execute cleanup during destruction and are therefore forbidden. Consider whether your use case fits into one of the other patterns described in this section. One simple solution is to use a plain pointer to a dynamically allocated object and never delete it (see last item). - Static variables of custom types: if you require ``static``, constant data of a type that you need to define yourself, give the type a trivial destructor and a ``constexpr`` constructor. - If all else fails, you can create an object dynamically and never delete it by binding the pointer to a function-local static pointer variable: ``static const auto* const impl = new T(args...)``; (If the initialisation is more complex, it can be moved into a function or lambda expression.) ``thread_local`` Variables -------------------------- ``thread_local`` variables that aren't declared inside a function must be initialised with a true compile-time constant. Prefer ``thread_local`` over other ways of defining thread-local data. Definition: Starting with C++11, variables can be declared with the ``thread_local`` specifier: .. code-block:: c++ thread_local Foo foo{...}; Such a variable is actually a collection of objects, so that when different threads access it, they are actually accessing different objects. ``thread_local`` variables are much like static storage duration variables in many respects. For instance, they can be declared at namespace scope, inside functions, or as static class members, but not as ordinary class members. ``thread_local`` variable instances are initialised much like static variables, except that they must be initialised separately for each thread, rather than once at program startup. This means that ``thread_local`` variables declared within a function are safe, but other ``thread_local`` variables are subject to the same initialisation-order issues as static variables (and more besides). ``thread_local`` variable instances are destroyed when their thread terminates, so they do not have the destruction-order issues of static variables. Pros: - Thread-local data is inherently safe from races (because only one thread can ordinarily access it), which makes ``thread_local`` useful for concurrent programming. - ``thread_local`` is the only standard-supported way of creating thread-local data. Cons: - Accessing a ``thread_local`` variable may trigger execution of an unpredictable and uncontrollable amount of other code. - ``thread_local`` variables are effectively global variables, and have all the drawbacks of global variables other than lack of thread-safety. - The memory consumed by a ``thread_local`` variable scales with the number of running threads (in the worst case), which can be quite large in a program. - An ordinary class member cannot be ``thread_local``. - ``thread_local`` may not be as efficient as certain compiler intrinsics. Decision: ``thread_local`` variables inside a function have no safety concerns, so they can be used without restriction. Note that you can use a function-scope ``thread_local`` to simulate a class- or namespace-scope ``thread_local`` by defining a function or static method that exposes it: .. code-block:: c++ Foo& MyThreadLocalFoo() { thread_local Foo result{ComplicatedInitialisation()}; return result; } ``thread_local`` variables at class or namespace scope must be initialised with a true compile-time constant (i.e. they must have no dynamic initialisation). To enforce this, ``thread_local`` variables at class or namespace scope must be annotated with ``constexpr``: .. code-block:: c++ constexpr thread_local Foo foo = ...; ``thread_local`` should be preferred over other mechanisms for defining thread-local data. Classes ======= Classes are the fundamental unit of code in C++. Naturally, we use them extensively. This section lists the main dos and don'ts you should follow when writing a class. Doing Work in Constructors -------------------------- Avoid virtual method calls in constructors, and avoid initialisation that can fail if you can't signal an error. Definition: It is possible to perform arbitrary initialisation in the body of the constructor. Pros: - No need to worry about whether the class has been initialised or not. - Objects that are fully initialised by constructor call can be const and may also be easier to use with standard containers or algorithms. Cons: - If the work calls virtual functions, these calls will not get dispatched to the subclass implementations. Future modification to your class can quietly introduce this problem even if your class is not currently subclassed, causing much confusion. - There is no easy way for constructors to signal errors, short of crashing the program (not always appropriate) or using exceptions. - If the work fails, we now have an object whose initialisation code failed, so it may be an unusual state requiring a ``bool is_valid()`` state checking mechanism (or similar) which is easy to forget to call. - You cannot take the address of a constructor, so whatever work is done in the constructor cannot easily be handed off to, for example, another thread. Decision: Constructors should never call virtual functions. If appropriate for your code , terminating the program may be an appropriate error handling response. Otherwise, consider a factory function or ``initialise()`` method as described in `TotW #42 `_ . Avoid ``initialise()`` methods on objects with no other states that affect which public methods may be called (semi-constructed objects of this form are particularly hard to work with correctly). .. _`implicit conversion`: Implicit Conversions -------------------- Do not define implicit conversions. Use the ``explicit`` keyword for conversion operators and single-argument constructors. Definition: Implicit conversions allow an object of one type (called the *source type*) to be used where a different type (called the *destination type*) is expected, such as when passing an ``int`` argument to a function that takes a ``double`` parameter. In addition to the implicit conversions defined by the language, users can define their own, by adding appropriate members to the class definition of the source or destination type. An implicit conversion in the source type is defined by a type conversion operator named after the destination type (e.g. ``operator bool()``). An implicit conversion in the destination type is defined by a constructor that can take the source type as its only argument (or only argument with no default value). The ``explicit`` keyword can be applied to a constructor or (since C++11) a conversion operator, to ensure that it can only be used when the destination type is explicit at the point of use, e.g. with a cast. This applies not only to implicit conversions, but to C++11's list initialisation syntax: .. code-block:: c++ class Foo { explicit Foo(int x, double y); ... }; void Func(Foo f); Func({42, 3.14}); // Error This kind of code isn't technically an implicit conversion, but the language treats it as one as far as ``explicit`` is concerned. Pros: - Implicit conversions can make a type more usable and expressive by eliminating the need to explicitly name a type when it's obvious. - Implicit conversions can be a simpler alternative to overloading, such as when a single function with a ``string_view`` parameter takes the place of separate overloads for ``string`` and ``const char*``. - List initialisation syntax is a concise and expressive way of initialising objects. Cons: - Implicit conversions can hide type-mismatch bugs, where the destination type does not match the user's expectation, or the user is unaware that any conversion will take place. - Implicit conversions can make code harder to read, particularly in the presence of overloading, by making it less obvious what code is actually getting called. - Constructors that take a single argument may accidentally be usable as implicit type conversions, even if they are not intended to do so. - When a single-argument constructor is not marked ``explicit``, there's no reliable way to tell whether it's intended to define an implicit conversion, or the author simply forgot to mark it. - It's not always clear which type should provide the conversion, and if they both do, the code becomes ambiguous. - List initialisation can suffer from the same problems if the destination type is implicit, particularly if the list has only a single element. Decision: Type conversion operators, and constructors that are callable with a single argument, must be marked ``explicit`` in the class definition. As an exception, copy and move constructors should not be ``explicit``, since they do not perform type conversion. Implicit conversions can sometimes be necessary and appropriate for types that are designed to transparently wrap other types. In that case, contact the `discussion forum `_. Constructors that cannot be called with a single argument may omit ``explicit``. Constructors that take a single ``std::initialiser_list`` parameter should also omit ``explicit``, in order to support copy-initialisation (e.g. ``MyType m{1, 2};``). .. _`copyable and movable types`: Copyable and Movable Types -------------------------- A class's public API should make explicit whether the class is copyable, move-only, or neither copyable nor movable. Support copying and/or moving if these operations are clear and meaningful for your type. Definition: A movable type is one that can be initialised and assigned from temporaries. A copyable type is one that can be initialised or assigned from any other object of the same type (so is also movable by definition), with the stipulation that the value of the source does not change. ``std::unique_ptr`` is an example of a movable but not copyable type (since the value of the source ``std::unique_ptr`` must be modified during assignment to the destination). ``int`` and ``string`` are examples of movable types that are also copyable. (For ``int``, the move and copy operations are the same; for ``string``, there exists a move operation that is less expensive than a copy.) For user-defined types, the copy behaviour is defined by the copy constructor and the copy-assignment operator. Move behaviour is defined by the move constructor and the move-assignment operator, if they exist, or by the copy constructor and the copy-assignment operator otherwise. The copy/move constructors can be implicitly invoked by the compiler in some situations, e.g. when passing objects by value. Pros: Objects of copyable and movable types can be passed and returned by value, which makes APIs simpler, safer, and more general. Unlike when passing objects by pointer or reference, there's no risk of confusion over ownership, lifetime, mutability, and similar issues, and no need to specify them in the contract. It also prevents non-local interactions between the client and the implementation, which makes them easier to understand, maintain, and optimise by the compiler. Further, such objects can be used with generic APIs that require pass-by-value, such as most containers, and they allow for additional flexibility in e.g., type composition. Copy/move constructors and assignment operators are usually easier to define correctly than alternatives like ``clone()``, ``copy_from()`` or ``swap()``, because they can be generated by the compiler, either implicitly or with ``= default``. They are concise, and ensure that all data members are copied. Copy and move constructors are also generally more efficient, because they don't require heap allocation or separate initialisation and assignment steps, and they're eligible for optimisations such as copy elision. Move operations allow the implicit and efficient transfer of resources out of rvalue objects. This allows a plainer coding style in some cases. Cons: Some types do not need to be copyable, and providing copy operations for such types can be confusing, nonsensical, or outright incorrect. Types representing singleton objects (Registerer), objects tied to a specific scope (Cleanup), or closely coupled to object identity (Mutex) cannot be copied meaningfully. Copy operations for base class types that are to be used polymorphically are hazardous, because use of them can lead to object slicing. Defaulted or carelessly-implemented copy operations can be incorrect, and the resulting bugs can be confusing and difficult to diagnose. Copy constructors are invoked implicitly, which makes the invocation easy to miss. This may cause confusion for programmers used to languages where pass-by-reference is conventional or mandatory. It may also encourage excessive copying, which can cause performance problems. Decision: Every class's public interface should make explicit which copy and move operations the class supports. This should usually take the form of explicitly declaring and/or deleting the appropriate operations in the public section of the declaration. Specifically, a copyable class should explicitly declare the copy operations, a move-only class should explicitly declare the move operations, and a non-copyable/movable class should explicitly delete the copy operations. Explicitly declaring or deleting all four copy/move operations is required. If you provide a copy or move assignment operator, you must also provide the corresponding constructor. .. code-block:: c++ class Copyable { public: //! Default constructor Copyable() = delete; //! Copy constructor Copyable(const Copyable &other); //! Move constructor Copyable(Copyable &&other) = delete; //! Destructor virtual ~Copyable() noexcept; //! Copy assignment operator Copyable& operator=(const Copyable &other); //! Move assignment operator Copyable& operator=(Copyable &&other) = delete; protected: ... private: ... }; class MoveOnly { public: //! Default constructor MoveOnly() = delete; //! Copy constructor MoveOnly(const MoveOnly &other) = delete; //! Move constructor MoveOnly(MoveOnly &&other); //! Destructor virtual ~MoveOnly() noexcept; //! Copy assignment operator MoveOnly& operator=(const MoveOnly &other) = delete; //! Move assignment operator MoveOnly& operator=(MoveOnly &&other); protected: ... private: ... }; class NotCopyableNorMovable { public: //! Default constructor NotCopyableNorMovable() = delete; //! Copy constructor NotCopyableNorMovable(const NotCopyableNorMovable &other) = delete; //! Move constructor NotCopyableNorMovable(NotCopyableNorMovable &&other); //! Destructor virtual ~NotCopyableNorMovable() noexcept; //! Copy assignment operator NotCopyableNorMovable& operator=(const NotCopyableNorMovable &other) = delete; //! Move assignment operator NotCopyableNorMovable& operator=(NotCopyableNorMovable &&other) = delete; protected: ... private: ... }; These declarations/deletions can be omitted only if they are obvious: for example, if a base class isn't copyable or movable, derived classes naturally won't be either. Similarly, a ``struct``'s copyability/movability is normally determined by the copyability/movability of its data members. Note that if you explicitly declare or delete any of the copy/move operations, the others are not obvious, and so this paragraph does not apply (in particular, the rules in this section that apply to ``class``\es also apply to ``struct``\s that declare or delete any copy/move operations). A type should not be copyable/movable if it incurs unexpected costs. Move operations for copyable types are strictly a performance optimisation and are a potential source of bugs and complexity, so define them if they have a chance of being more efficient than the corresponding copy operations. If your type provides copy operations, it is recommended that you design your class so that the default implementation of those operations is correct. Remember to review the correctness of any defaulted operations as you would any other code. .. _`structs vs classes`: Structs vs. Classes ------------------- Use a ``struct`` only for passive objects that carry data or collections of templated static member functions that need to be partially specialised; everything else is a ``class``. The ``struct`` and ``class`` keywords behave almost identically in C++. We add our own semantic meanings to each keyword, so you should use the appropriate keyword for the data-type you're defining. ``struct``\s should be used for passive objects that carry data, and may have associated constants, but lack any functionality other than access/setting the data members. The accessing/setting of fields is done by directly accessing the fields rather than through method invocations. Methods should only be used in templated static method-only ``struct``\s. See, e.g.: .. code-block:: c++ //! static inline implementation of Hooke's law template struct Hooke { /** * compute Lamé's first constant * @param young: Young's modulus * @param poisson: Poisson's ratio */ inline static constexpr Real compute_lambda(const Real & young, const Real & poisson) { return convert_elastic_modulus(young, poisson); } /** * compute Lamé's second constant (i.e., shear modulus) * @param young: Young's modulus * @param poisson: Poisson's ratio */ inline static constexpr Real compute_mu(const Real & young, const Real & poisson) { return convert_elastic_modulus(young, poisson); } /** * compute the bulk modulus * @param young: Young's modulus * @param poisson: Poisson's ratio */ inline static constexpr Real compute_K(const Real & young, const Real & poisson) { return convert_elastic_modulus(young, poisson); } /** * compute the stiffness tensor * @param lambda: Lamé's first constant * @param mu: Lamé's second constant (i.e., shear modulus) */ inline static Eigen::TensorFixedSize> compute_C(const Real & lambda, const Real & mu) { return lambda*Tensors::outer(Tensors::I2(),Tensors::I2()) + 2*mu*Tensors::I4S(); } /** * compute the stiffness tensor * @param lambda: Lamé's first constant * @param mu: Lamé's second constant (i.e., shear modulus) */ inline static T4Mat compute_C_T4(const Real & lambda, const Real & mu) { return lambda*Matrices::Itrac() + 2*mu*Matrices::Isymm(); } /** * return stress * @param lambda: First Lamé's constant * @param mu: Second Lamé's constant (i.e. shear modulus) * @param E: Green-Lagrange or small strain tensor */ template inline static decltype(auto) evaluate_stress(const Real & lambda, const Real & mu, s_t && E) { return E.trace()*lambda * Strain_t::Identity() + 2*mu*E; } /** * return stress and tangent stiffness * @param lambda: First Lamé's constant * @param mu: Second Lamé's constant (i.e. shear modulus) * @param E: Green-Lagrange or small strain tensor * @param C: stiffness tensor (Piola-Kirchhoff 2 (or σ) w.r.t to `E`) */ template inline static decltype(auto) evaluate_stress(const Real & lambda, const Real & mu, Tangent_t && C, s_t && E) { return std::make_tuple (std::move(evaluate_stress(lambda, mu, std::move(E))), std::move(C)); } }; The goal of such static member functions-only ``struct``\s is to instantiate a set of function templates with consistent template parameters without repeating those parameters. If more functionality is required, a ``class`` is more appropriate. If in doubt, make it a ``class``. For consistency with STL, you can use ``struct`` instead of ``class`` for functors and traits. .. _inheritance: Inheritance ----------- Composition is often more appropriate than inheritance. When using inheritance, make it ``public``. Definition: When a sub-class inherits from a base class, it includes the definitions of all the data and operations that the parent base class defines. In practice, inheritance is used in two major ways in C++: implementation inheritance, in which actual code is inherited by the child, and :ref:`interface inheritance `, in which only method names are inherited. Pros: Implementation inheritance reduces code size by re-using the base class code as it specializes an existing type. Because inheritance is a compile-time declaration, you and the compiler can understand the operation and detect errors. Interface inheritance can be used to programmatically enforce that a class expose a particular API. Again, the compiler can detect errors, in this case, when a class does not define a necessary method of the API. Cons: For implementation inheritance, because the code implementing a sub-class is spread between the base and the sub-class, it can be more difficult to understand an implementation. The sub-class cannot override functions that are not virtual, so the sub-class cannot change implementation. Decision: All inheritance should be ``public``. If you want to do private inheritance, you should be including an instance of the base class as a member instead. Do not overuse implementation inheritance. Composition is often more appropriate. Try to restrict use of inheritance to the "is-a" case: ``Bar`` subclasses ``Foo`` if it can reasonably be said that ``Bar`` "is a kind of" ``Foo``. Limit the use of protected to those member functions that might need to be accessed from subclasses. Note that :ref:`data members should be private `. Explicitly annotate overrides of virtual functions or virtual destructors with exactly one of either the ``override`` or (less frequently) ``override final`` specifier. Do not use ``virtual`` when declaring an ``override``. Rationale: A function or destructor marked ``override`` or ``final`` that is not an ``override`` of a base class virtual function will not compile, and this helps catch common errors. The specifiers serve as documentation; if no specifier is present, the reader has to check all ancestors of the class in question to determine if the function or destructor is ``virtual`` or not. Multiple Inheritance -------------------- Only very rarely is multiple implementation inheritance actually useful. We allow multiple inheritance only when at most one of the base classes has an implementation; all other base classes must be :ref:`pure interface ` classes. Definition: Multiple inheritance allows a sub-class to have more than one base class. We distinguish between base classes that are *pure interfaces* and those that have an *implementation*. Pros: Multiple implementation inheritance may let you re-use even more code than single inheritance (see :ref:`inheritance`). Cons: Only very rarely is multiple *implementation* inheritance actually useful. When multiple implementation inheritance seems like the solution, you can usually find a different, more explicit, and cleaner solution. Decision: Multiple inheritance is allowed only when all superclasses, with the possible exception of the first one, are :ref:`pure interfaces `. Note: There is an :ref:`exception ` to this rule on Windows. .. _interfaces: Interfaces ---------- Definition: A class is a pure interface if it meets the following requirements: - It has only public pure virtual (``= 0``) methods and static methods (but see below for destructor). - It may not have non-static data members. - It need not have any constructors defined. If a constructor is provided, it must take no arguments and it must be protected. - If it is a subclass, it may only be derived from classes that satisfy these conditions. An interface class can never be directly instantiated because of the pure virtual method(s) it declares. To make sure all implementations of the interface can be destroyed correctly, the interface must also declare a virtual destructor (in an exception to the first rule, this should not be pure). See *Stroustrup, The C++ Programming Language, 4th edition, 2014*, section 20.3 for details. Operator Overloading -------------------- Overload operators judiciously. Definition: C++ permits user code to `declare overloaded versions of the built-in operators `_ using the ``operator`` keyword, so long as one of the parameters is a user-defined type. The ``operator`` keyword also permits user code to define new kinds of literals using ``operator""``, and to define type-conversion functions such as ``operator bool()``. Pros: Operator overloading can make code more concise and intuitive by enabling user-defined types to behave the same as built-in types. Overloaded operators are the idiomatic names for certain operations (e.g. ``==``, ``<``, ``=``, and ``<<``), and adhering to those conventions can make user-defined types more readable and enable them to interoperate with libraries that expect those names. User-defined literals are a very concise notation for creating objects of user-defined types. Cons: - Providing a correct, consistent, and unsurprising set of operator overloads requires some care, and failure to do so can lead to confusion and bugs. - Overuse of operators can lead to obfuscated code, particularly if the overloaded operator's semantics don't follow convention. - The hazards of function overloading apply just as much to operator overloading, if not more so. - Operator overloads can fool our intuition into thinking that expensive operations are cheap, built-in operations. - Finding the call sites for overloaded operators may require a search tool that's aware of C++ syntax, rather than e.g. grep. - If you get the argument type of an overloaded operator wrong, you may get a different overload rather than a compiler error. For example, ``foo < bar`` may do one thing, while ``&foo < &bar`` does something totally different. - Certain operator overloads are inherently hazardous. Overloading unary ``&`` can cause the same code to have different meanings depending on whether the overload declaration is visible. Overloads of ``&&``, ``||``, and ``,`` (comma) cannot match the evaluation-order semantics of the built-in operators. - Operators are often defined outside the class, so there's a risk of different files introducing different definitions of the same operator. If both definitions are linked into the same binary, this results in undefined behavior, which can manifest as subtle run-time bugs. - User-defined literals allow the creation of new syntactic forms that are unfamiliar even to experienced C++ programmers. Decisions: Define overloaded operators only if their meaning is obvious, unsurprising, and consistent with the corresponding built-in operators. For example, use ``|`` as a bitwise- or logical-or, not as a shell-style pipe. Define operators only on your own types. More precisely, define them in the same headers, ``.cc`` files, and namespaces as the types they operate on. That way, the operators are available wherever the type is, minimising the risk of multiple definitions. If possible, avoid defining operators as templates, because they must satisfy this rule for any possible template arguments. If you define an operator, also define any related operators that make sense, and make sure they are defined consistently. For example, if you overload ``<``, overload all the comparison operators, and make sure ``<`` and ``>`` never return true for the same arguments. Prefer to define non-modifying binary operators as non-member functions. If a binary operator is defined as a class member, implicit conversions will apply to the right-hand argument, but not the left-hand one. It will confuse your users if ``a < b`` compiles but ``b < a`` doesn't. Don't go out of your way to avoid defining operator overloads. For example, prefer to define ``==``, ``=``, and ``<<``, rather than ``equals()``, ``copy_from()``, and ``print_to()``. Conversely, don't define operator overloads just because other libraries expect them. For example, if your type doesn't have a natural ordering, but you want to store it in a ``std::set``, use a custom comparator rather than overloading ``<``. Do not overload ``&&``, ``||``, ``,`` (comma), or unary ``&``. Type conversion operators are covered in :ref:`implicit conversion`. The ``=`` operator is covered in :ref:`copyable and movable types`. Overloading ``<<`` for use with streams is covered in :ref:`streams`. See also the rules on :ref:`function overloading `, which apply to operator overloading as well. .. _`access control`: Access Control -------------- Make data members ``protected``, unless they are ``static const`` (and follow the :ref:`naming convention for constants `). .. _`declaration order`: Declaration Order ----------------- Group similar declarations together, placing ``public`` parts earlier. A class definition should usually start with a ``public:`` section, followed by ``protected:``, then ``private:``. Omit sections that would be empty. Within each section, generally prefer grouping similar kinds of declarations together, and generally prefer the following order: types (including ``using``, and nested ``struct``\s and ``class``\es), constants, factory functions, constructors, assignment operators, destructor, all other methods, data members. Do not put large method definitions inline in the class definition. Trivial, performance-critical, or template methods may be defined inline. See :ref:`inline functions` for more details. Functions ========= Output Parameters ----------------- Prefer using return values rather than output parameters. If output-only parameters are used they should appear after input parameters. The output(s) of a C++ function is/are naturally provided via a (tuple of) return value and sometimes via output parameters. Prefer using return values and return value tuples over output parameters since they improve readability and oftentimes provide the same or better performance. Parameters are either input to the function, output from the function, or both. Input parameters are usually values or const references, while output and input/output parameters will be references to non-const. When ordering function parameters, put all input-only parameters before any output parameters. In particular, do not add new parameters to the end of the function just because they are new; place new input-only parameters before the output parameters. This is not a hard-and-fast rule. Parameters that are both input and output (often classes/structs) muddy the waters, and, as always, consistency with related functions may require you to bend the rule. Write Short Functions --------------------- Prefer small and focused functions. We recognise that long functions are sometimes appropriate, so no hard limit is placed on functions length. If a function exceeds about 40 lines, think about whether it can be broken up without harming the structure of the program. Even if your long function works perfectly now, someone modifying it in a few months may add new behaviour. This could result in bugs that are hard to find. Keeping your functions short and simple makes it easier for other people to read and modify your code. You could find long and complicated functions when working with some code. Do not be intimidated by modifying existing code: if working with such a function proves to be difficult, you find that errors are hard to debug, or you want to use a piece of it in several different contexts, consider breaking up the function into smaller and more manageable pieces. Reference Arguments ------------------- All input parameters passed by reference must be labelled ``const``, Output and input/output parameters can be passed as references, :ref:`smart pointers `, or ``std::optional``. **There are no raw pointers** within *µ*\Spectre, ever. Definition: In C, if a function needs to modify a variable, the parameter must use a pointer, e.g., ``int foo(int *pval)``. In C++, the function can alternatively declare a reference parameter: ``int foo(int &val)``. Pros: Defining a parameter as reference avoids ugly code like ``(*pval)++``. Necessary for some applications like copy constructors. Makes it clear, unlike with pointers, that a null pointer is not a possible value. Cons: References can be confusing to absolute beginners, as they have value syntax but pointer semantics. Decision: The one hard rule in *µ*\Spectre is that no raw pointers will be tolerated (with the obvious exception of interacting with third-party APIs). Pointers are to be considered a bug-generating relic of a darker time when ``goto`` statements were allowed to exist. If you need to mimic the questionable practice of passing a pointer that could be ``nullptr`` to indicate that there is no value, use ``std::optional``. .. _`function overloading`: Function Overloading -------------------- Use overloaded functions (including constructors) only if a reader looking at a call site can get a good idea of what is happening without having to first figure out exactly which overload is being called. Definition: You may write a function that takes a ``const string&`` and overload it with another that takes ``const char*``. However, in this case consider ``std::string_view`` instead. .. code-block:: c++ class MyClass { public: void Analyze(const string &text); void Analyze(const char *text, size_t textlen); }; Pros: Overloading can make code more intuitive by allowing an identically-named function to take different arguments. It may be necessary for templated code, and it can be convenient for Visitors. Cons: If a function is overloaded by the argument types alone, a reader may have to understand C++'s complex matching rules in order to tell what's going on. Also many people are confused by the semantics of inheritance if a derived class overrides only some of the variants of a function. Decision: You may overload a function when there are no semantic differences between variants, or when the differences are clear at the call site. If you are overloading a function to support variable number of arguments of the same type, consider making it take a STL container so that the user can use an :ref:`initialiser list ` to specify the arguments. Default Arguments ----------------- Default arguments are allowed on non-virtual functions when the default is guaranteed to always have the same value. Follow the same restrictions as for :ref:`function overloading `, and prefer overloaded functions if the readability gained with default arguments doesn't outweigh the downsides below. Pros: Often you have a function that uses default values, but occasionally you want to override the defaults. Default parameters allow an easy way to do this without having to define many functions for the rare exceptions. Compared to overloading the function, default arguments have a cleaner syntax, with less boilerplate and a clearer distinction between 'required' and 'optional' arguments. Cons: Defaulted arguments are another way to achieve the semantics of overloaded functions, so all the :ref:`reasons not to overload functions ` apply. The defaults for arguments in a virtual function call are determined by the static type of the target object, and there's no guarantee that all overrides of a given function declare the same defaults. Default parameters are re-evaluated at each call site, which can bloat the generated code. Readers may also expect the default's value to be fixed at the declaration instead of varying at each call. Function pointers are confusing in the presence of default arguments, since the function signature often doesn't match the call signature. Adding function overloads avoids these problems. Decision: Default arguments are banned on virtual functions, where they don't work properly, and in cases where the specified default might not evaluate to the same value depending on when it was evaluated. (For example, don't write ``void f(int n = counter++);``.) In some other cases, default arguments can improve the readability of their function declarations enough to overcome the downsides above, so they are allowed. Trailing Return Type Syntax --------------------------- Use trailing return types only where using the ordinary syntax (leading return types) is impractical or much less readable. Definition: C++ allows two different forms of function declarations. In the older form, the return type appears before the function name. For example: .. code-block:: c++ int foo(int x); The new form, introduced in C++11, uses the auto keyword before the function name and a trailing return type after the argument list. For example, the declaration above could equivalently be written: .. code-block:: c++ auto foo(int x) -> int; The trailing return type is in the function's scope. This doesn't make a difference for a simple case like int but it matters for more complicated cases, like types declared in class scope or types written in terms of the function parameters. Pros: Trailing return types are the only way to explicitly specify the return type of a :ref:`lambda expression `. In some cases the compiler is able to deduce a lambda's return type, but not in all cases. Even when the compiler can deduce it automatically, sometimes specifying it explicitly would be clearer for readers. Sometimes it's easier and more readable to specify a return type after the function's parameter list has already appeared. This is particularly true when the return type depends on template parameters. For example: .. code-block:: c++ template auto add(T t, U u) -> decltype(t + u); versus .. code-block:: c++ template decltype(declval() + declval()) add(T t, U u); Decision: In most cases, continue to use the older style of function declaration where the return type goes before the function name. Use the new trailing-return-type form only in cases where it's required (such as lambdas) or where, by putting the type after the function's parameter list, it allows you to write the type in a much more readable way. Ownership and linting ===================== There are various tricks and utilities that we use to make C++ code more robust, and various ways we use C++ that may differ from what you see elsewhere. .. _`ownership and smart pointers`: Ownership and Smart Pointers ---------------------------- Prefer to have single, fixed owners for dynamically allocated objects. Prefer to transfer ownership with smart pointers. Definition: "Ownership" is a bookkeeping technique for managing dynamically allocated memory (and other resources). The owner of a dynamically allocated object is an object or function that is responsible for ensuring that it is deleted when no longer needed. Ownership can sometimes be shared, in which case the last owner is typically responsible for deleting it. Even when ownership is not shared, it can be transferred from one piece of code to another. "Smart" pointers are classes that act like pointers, e.g. by overloading the ``*`` and ``->`` operators. Some smart pointer types can be used to automate ownership bookkeeping, to ensure these responsibilities are met. ``std::unique_ptr`` is a smart pointer type introduced in C++11, which expresses exclusive ownership of a dynamically allocated object; the object is deleted when the ``std::unique_ptr`` goes out of scope. It cannot be copied, but can be moved to represent ownership transfer. ``std::shared_ptr`` is a smart pointer type that expresses shared ownership of a dynamically allocated object. ``std::shared_ptrs`` can be copied; ownership of the object is shared among all copies, and the object is deleted when the last ``std::shared_ptr`` is destroyed. Pros: - It's virtually impossible to manage dynamically allocated memory without some sort of ownership logic. - Transferring ownership of an object can be cheaper than copying it (if copying it is even possible). - Transferring ownership can be simpler than 'borrowing' a pointer or reference, because it reduces the need to coordinate the lifetime of the object between the two users. - Smart pointers can improve readability by making ownership logic explicit, self-documenting, and unambiguous. - Smart pointers can eliminate manual ownership bookkeeping, simplifying the code and ruling out large classes of errors. - For const objects, shared ownership can be a simple and efficient alternative to deep copying. Cons: - Ownership must be represented and transferred via smart pointers. Pointer semantics are more complicated than value semantics, especially in APIs: you have to worry not just about ownership, but also aliasing, lifetime, and mutability, among other issues. - The performance costs of value semantics are often overestimated, so the performance benefits of ownership transfer might not justify the readability and complexity costs. - APIs that transfer ownership force their clients into a single memory management model. - Code using smart pointers is less explicit about where the resource releases take place. - Shared ownership can be a tempting alternative to careful ownership design, obfuscating the design of a system. - Shared ownership requires explicit bookkeeping at run-time, which can be costly. - In some cases (e.g. cyclic references), objects with shared ownership may never be deleted. Decision: If dynamic allocation is necessary, prefer to keep ownership with the code that allocated it. If other code needs momentary access to the object (i.e., there is no risk of the other code accessing it later, after the object may have been destroyed), consider passing it a reference without transferring ownership. Prefer to use ``std::unique_ptr`` to make ownership transfer explicit. For example: .. code-block:: c++ std::unique_ptr FooFactory(); void FooConsumer(std::unique_ptr ptr); Do not design your code to use shared ownership without a very good reason. One such reason is to avoid expensive copy operations. If you do use shared ownership, prefer to use ``std::shared_ptr``. Never use ``std::auto_ptr`` it has no longer any value. Instead, use ``std::unique_ptr``. cpplint ------- Use ``cpplint.py`` to detect style errors. ``cpplint.py`` is a tool that reads a source file and identifies many style errors. It is not perfect, and has both false positives and false negatives, but it is still a valuable tool. False positives can be ignored by putting ``// NOLINT`` at the end of the line or ``// NOLINTNEXTLINE`` in the previous line. Other C++ Features ================== Rvalue References ----------------- Use rvalue references to define move constructors and move assignment operators, or for perfect forwarding. Definition: Rvalue references are a type of reference that can only bind to temporary objects. The syntax is similar to traditional reference syntax. For example, ``void f(string&& s);`` declares a function whose argument is an rvalue reference to a ``string``. Pros: - Defining a move constructor (a constructor taking an rvalue reference to the class type) makes it possible to move a value instead of copying it. If ``v1`` is a ``std::vector``, for example, then auto ``v2(std::move(v1))`` will probably just result in some simple pointer manipulation instead of copying a large amount of data. In some cases this can result in a major performance improvement. - Rvalue references make it possible to write a generic function wrapper that forwards its arguments to another function, and works whether or not its arguments are temporary objects. (This is sometimes called "perfect forwarding".) - Rvalue references make it possible to implement types that are movable but not copyable, which can be useful for types that have no sensible definition of copying but where you might still want to pass them as function arguments, put them in containers, etc. - ``std::move`` is necessary to make effective use of some standard-library types, such as ``std::unique_ptr``. Decision: Use rvalue references to define move constructors and move assignment operators (as described in :ref:`Copyable and Movable Types `) and, in conjunction with ``std::forward``, to support perfect forwarding. You may use ``std::move`` to express moving a value from one object to another rather than copying it. Friends ------- We allow use of ``friend`` classes and functions, within reason. Friends should usually be defined in the same file so that the reader does not have to look in another file to find uses of the private members of a class. A common use of friend is to have a ``FooBuilder`` class be a friend of ``Foo`` so that it can construct the inner state of ``Foo`` correctly, without exposing this state to the world. Friends extend, but do not break, the encapsulation boundary of a class. In some cases this is better than making a member public when you want to give only one other class access to it. However, most classes should interact with other classes solely through their public members. Exceptions ---------- We use C++ exceptions extensively. Pros: - Exceptions allow higher levels of an application to decide how to handle "can't happen" failures in deeply nested functions, without the obscuring and error-prone bookkeeping of error codes. - Exceptions are used by most other modern languages. Using them in C++ would make it more consistent with Python, Java, and the C++ that others are familiar with. - Some third-party C++ libraries use exceptions, and turning them off internally makes it harder to integrate with those libraries. - Exceptions are the only way for a constructor to fail. We can simulate this with a factory function or an ``initialise()`` method, but these require heap allocation or a new "invalid" state, respectively. - Exceptions are really handy in testing frameworks. Cons: - When you add a throw statement to an existing function, you must examine all of its transitive callers. Either they must make at least the basic exception safety guarantee, or they must never catch the exception and be happy with the program terminating as a result. For instance, if ``f()`` calls ``g()`` calls ``h()``, and ``h`` throws an exception that ``f`` catches, ``g`` has to be careful or it may not clean up properly. - More generally, exceptions make the control flow of programs difficult to evaluate by looking at code: functions may return in places you don't expect. This causes maintainability and debugging difficulties. You can minimise this cost via some rules on how and where exceptions can be used, but at the cost of more that a developer needs to know and understand. - Exception safety requires both RAII and different coding practices. Lots of supporting machinery is needed to make writing correct exception-safe code easy. Further, to avoid requiring readers to understand the entire call graph, exception-safe code must isolate logic that writes to persistent state into a "commit" phase. This will have both benefits and costs (perhaps where you're forced to obfuscate code to isolate the commit). Allowing exceptions would force us to always pay those costs even when they're not worth it. - Turning on exceptions adds data to each binary produced, increasing compile time (probably slightly) and possibly increasing address space pressure. Decision: On their face, the benefits of using exceptions outweigh the costs, especially in new projects. Especially in a computational project, were we are perfectly happy to terminate if an exception is thrown. There is an :ref:`exception ` to this rule (no pun intended) for Windows code. noexcept -------- Specify ``noexcept`` when it is useful and correct. Definition: The ``noexcept`` specifier is used to specify whether a function will throw exceptions or not. If an exception escapes from a function marked ``noexcept``, the program crashes via ``std::terminate``. The ``noexcept`` operator performs a compile-time check that returns true if an expression is declared to not throw any exceptions. Pros: - Specifying move constructors as ``noexcept`` improves performance in some cases, e.g. ``std::vector::resize()`` moves rather than copies the objects if ``T``'s move constructor is ``noexcept``. - Specifying ``noexcept`` on a function can trigger compiler optimisations in environments where exceptions are enabled, e.g. compiler does not have to generate extra code for stack-unwinding, if it knows that no exceptions can be thrown due to a ``noexcept`` specifier. Cons: - It's hard, if not impossible, to undo ``noexcept`` because it eliminates a guarantee that callers may be relying on, in ways that are hard to detect. Decision: You should use ``noexcept`` when it is useful for performance if it accurately reflects the intended semantics of your function, i.e. that if an exception is somehow thrown from within the function body then it represents a fatal error. You can assume that ``noexcept`` on move constructors has a meaningful performance benefit. If you think there is significant performance benefit from specifying ``noexcept`` on some other function, feel free to use it. .. _`rtti`: Run-Time Type Information (RTTI) -------------------------------- When possible, avoid using Run Time Type Information (RTTI). Definition: RTTI allows a programmer to query the C++ class of an object at run time. This is done by use of ``typeid`` or ``dynamic_cast``. Cons: Querying the type of an object at run-time frequently means a design problem. Needing to know the type of an object at runtime is often an indication that the design of your class hierarchy is flawed. Undisciplined use of RTTI makes code hard to maintain. It can lead to type-based decision trees or switch statements scattered throughout the code, all of which must be examined when making further changes. Pros: RTTI can be very useful when interacting with duck-typed languages (like python) and when implementing efficient containers with polymorphic interfaces, see, e.g., *µ*\Spectre's ``FieldMap`` implementation. RTTI can be useful in some unit tests. For example, it is useful in tests of factory classes where the test has to verify that a newly created object has the expected dynamic type. It is also useful in managing the relationship between objects and their mocks. RTTI is useful when considering multiple abstract objects. Consider .. code-block:: c++ bool Base::Equal(Base* other) = 0; bool Derived::Equal(Base* other) { Derived* that = dynamic_cast(other); if (that == nullptr) { return false; } ... } Decision: RTTI has legitimate uses but is prone to abuse, so you must be careful when using it. You may use it freely in unit tests, but avoid it when possible in other code. In particular, think twice before using RTTI in new code. If you find yourself needing to write code that behaves differently based on the class of an object, consider one of the following alternatives to querying the type: - Virtual methods are the preferred way of executing different code paths depending on a specific subclass type. This puts the work within the object itself. - If the work belongs outside the object and instead in some processing code, consider a double-dispatch solution, such as the Visitor design pattern. This allows a facility outside the object itself to determine the type of class using the built-in type system. When the logic of a program guarantees that a given instance of a base class is in fact an instance of a particular derived class, then a ``dynamic_cast`` may be used freely on the object. Usually one can use a ``static_cast`` as an alternative in such situations. Decision trees based on type are a strong indication that your code is on the wrong track. .. code-block:: c++ if (typeid(*data) == typeid(D1)) { ... } else if (typeid(*data) == typeid(D2)) { ... } else if (typeid(*data) == typeid(D3)) { ... Code such as this usually breaks when additional subclasses are added to the class hierarchy. Moreover, when properties of a subclass change, it is difficult to find and modify all the affected code segments. Do not hand-implement an RTTI-like workaround. The arguments against RTTI apply just as much to workarounds like class hierarchies with type tags. Moreover, workarounds disguise your true intent. Casting ------- Use C++-style casts like ``static_cast(double_value)``, or brace initialisation for conversion of arithmetic types like ``int64 y{int64{1} << 42}``. Do not use cast formats like ``int y{(int)x}`` or ``int y{int(x)}`` (but the latter is okay when invoking a constructor of a class type). Definition: C++ introduced a different cast system from C that distinguishes the types of cast operations. Pros: The problem with C casts is the ambiguity of the operation; sometimes you are doing a conversion (e.g., ``(int)3.5``) and sometimes you are doing a cast (e.g., ``(int)"hello"``). Brace initialisation and C++ casts can often help avoid this ambiguity. Additionally, C++ casts are more visible when searching for them. Cons: The C++-style cast syntax is verbose Decision: Do not use C-style casts. Instead, use these C++-style casts when explicit type conversion is necessary. - Use brace initialisation to convert arithmetic types (e.g. ``int64{x}``). This is the safest approach because code will not compile if conversion can result in information loss. The syntax is also concise. - Use ``static_cast`` as the equivalent of a C-style cast that does value conversion, when you need to explicitly up-cast a pointer from a class to its superclass, or when you need to explicitly cast a pointer from a superclass to a subclass. In this last case, you must be sure your object is actually an instance of the subclass. - Use ``const_cast`` to remove the ``const`` qualifier (see :ref:`const`). **This indicates a serious design flaw if it happens in µSpectre and is to be considered a bug**. Only use this if third-party libraries force you to. - Use ``reinterpret_cast`` to do unsafe conversions of pointer types to and from integer and other pointer types. Use this only if you know what you are doing and you understand the aliasing issues. See the :ref:`RTTI ` section for guidance on the use of ``dynamic_cast``. .. _streams: Streams ------- Use streams where appropriate, and stick to "simple" usages. Overload ``<<`` for streaming only for types representing values, and write only the user-visible value, not any implementation details. Definition: Streams are the standard I/O abstraction in C++, as exemplified by the standard header ````. Pros: The ``<<`` and ``>>`` stream operators provide an API for formatted I/O that is easily learned, portable, reusable, and extensible. ``printf``, by contrast, doesn't even support string, to say nothing of user-defined types, and is very difficult to use portably. ``printf`` also obliges you to choose among the numerous slightly different versions of that function, and navigate the dozens of conversion specifiers. Streams provide first-class support for console I/O via ``std::cin``, ``std::cout``, ``std::cerr``, and ``std::clog``. The C APIs do as well, but are hampered by the need to manually buffer the input. Cons: - Stream formatting can be configured by mutating the state of the stream. Such mutations are persistent, so the behaviour of your code can be affected by the entire previous history of the stream, unless you go out of your way to restore it to a known state every time other code might have touched it. User code can not only modify the built-in state, it can add new state variables and behaviours through a registration system. - It is difficult to precisely control stream output, due to the above issues, the way code and data are mixed in streaming code, and the use of operator overloading (which may select a different overload than you expect). - The streams API is subtle and complex, so programmers must develop experience with it in order to use it effectively. - Resolving the many overloads of ``<<`` is extremely costly for the compiler. When used pervasively in a large code base, it can consume as much as 20% of the parsing and semantic analysis time. Decision: Use streams only when they are the best tool for the job. This is typically the case when the I/O is ad-hoc, local, human-readable, and targeted at other developers rather than end-users. Be consistent with the code around you, and with the code base as a whole; if there's an established tool for your problem, use that tool instead. In particular, logging libraries are usually a better choice than ``std::cerr`` or ``std::clog`` for diagnostic output. Overload ``<<`` as a streaming operator for your type only if your type represents a value, and ``<<`` writes out a human-readable string representation of that value. Avoid exposing implementation details in the output of ``<<``; if you need to print object internals for debugging, use named functions instead (a method named ``debug_string()`` is the most common convention). Preincrement and Predecrement ----------------------------- Use prefix form (``++i``) of the increment and decrement operators with iterators and other template objects. Definition: When a variable is incremented (``++i`` or ``i++``) or decremented (``--i`` or ``i--``) and the value of the expression is not used, one must decide whether to pre-increment (decrement) or post-increment (decrement). Pros: When the return value is ignored, the "pre" form (``++i``) is never less efficient than the "post" form (``i++``), and is often more efficient. This is because post-increment (or decrement) requires a copy of ``i`` to be made, which is the value of the expression. If ``i`` is an iterator or other non-scalar type, copying ``i`` could be expensive. Since the two types of increment behave the same when the value is ignored, why not just always pre-increment? Cons: The tradition developed, in C, of using post-increment when the expression value is not used, especially in for loops. Some find post-increment easier to read, since the "subject" (``i``) precedes the "verb" (``++``), just like in English. This is a dumb tradition and should be abolished. Decision: If the return value is ignored, a post-increment (post-decrement) is a bug. .. _`const`: Use of const ------------ Use ``const`` doggedly whenever it makes is correct. With C++11, ``constexpr`` is a better choice for some uses of ``const``. Definition: Declared variables and parameters can be preceded by the keyword ``const`` to indicate the variables are not changed (e.g., ``const int foo``). Class functions can have the ``const`` qualifier to indicate the function does not change the state of the class member variables (e.g., ``class Foo { int Bar(char c) const; };``). Pros: Easier for people to understand how variables are being used. Allows the compiler to do better type checking, and, conceivably, generate better code. Helps people convince themselves of program correctness because they know the functions they call are limited in how they can modify your variables. Helps people know what functions are safe to use without locks in multi-threaded programs. ``const`` is viral: if you pass a ``const`` variable to a function, that function must have ``const`` in its prototype. Cons: ``const`` can be problem when calling library functions, and require ``const_cast``. Decision: const variables, data members, methods and arguments add a level of compile-time type checking; it is better to detect errors as soon as possible. Therefore we strongly recommend that you use ``const`` whenever it is possible to do so: - If a function guarantees that it will not modify an argument passed by reference, the corresponding function parameter should be a reference-to-const (``const T&``). - Declare methods to be ``const`` whenever possible. Accessors should almost always be ``const``. Other methods should be ``const`` if they do not modify any data members, do not call any non-``const`` methods, and do not return a non-``const`` reference to a data member. - Consider making data members ``const`` whenever they do not need to be modified after construction. The ``mutable`` keyword is allowed but is unsafe when used with threads, so thread safety should be carefully considered first. Use of ``constexpr`` -------------------- In C++11, use ``constexpr`` to define true constants or to ensure constant initialisation. Definition: Some variables can be declared ``constexpr`` to indicate the variables are true constants, i.e. fixed at compilation/link time. Some functions and constructors can be declared ``constexpr`` which enables them to be used in defining a ``constexpr`` variable. Pros: Use of ``constexpr`` enables definition of constants with floating-point expressions rather than just literals; definition of constants of user-defined types; and definition of constants with function calls. Decision: ``constexpr`` definitions enable a more robust specification of the constant parts of an interface. Use ``constexpr`` to specify true constants and the functions that support their definitions. You can use ``constexpr`` to force inlining of functions. Integer Types ------------- We do not use the built-in C++ integer types in *µ*\Spectre, rather the alias ``Int``. If a part needs a variable of a different size, use a precise-width integer type from ````, such as ``int16_t``. If your variable represents a value that could ever be greater than or equal to 2³¹ (2GiB), use a 64-bit type such as ``int64_t``. Keep in mind that even if your value won't ever be too large for an ``Int``, it may be used in intermediate calculations which may require a larger type. When in doubt, choose a larger type. Definition: *µ*\Spectre does not specify the size of ``Int``. Assume it's 32 bits. Pros: Uniformity of declaration. Cons: The sizes of integral types in C++ can vary based on compiler and architecture. Decision: ```` defines types like ``int16_t``, ``uint32_t``, ``int64_t``, etc. You should always use those in preference to short, unsigned long long and the like, when you need a guarantee on the size of an integer. When appropriate, you are welcome to use standard types like ``size_t`` and ``petrify_t``. We use ``Int`` very often, for integers we know are not going to be too big, e.g., loop counters. Use plain old ``Int`` for such things. You should assume that an ``Int`` is at least 32 bits, but don't assume that it has more than 32 bits. If you need a 64-bit integer type, use ``int64_t`` or ``uint64_t``. For integers we know can be "big", use ``int64_t``. You should not use the unsigned integer types such as ``uint32_t``, unless there is a valid reason such as representing a bit pattern rather than a number, or you need defined overflow modulo 2ᴺ. In particular, do not use unsigned types to say a number will never be negative. Instead, use assertions for this. If your code is a container that returns a size, be sure to use a type that will accommodate any possible usage of your container. When in doubt, use a larger type rather than a smaller type. Use care when converting integer types. Integer conversions and promotions can cause undefined behaviour, leading to security bugs and other problems. On Unsigned Integers Unsigned integers are good for representing bitfields and modular arithmetic. Because of historical accident, the C++ standard also uses unsigned integers to represent the size of containers - many members of the standards body believe this to be a mistake, but it is effectively impossible to fix at this point. The fact that unsigned arithmetic doesn't model the behaviour of a simple integer, but is instead defined by the standard to model modular arithmetic (wrapping around on overflow/underflow), means that a significant class of bugs cannot be diagnosed by the compiler. In other cases, the defined behaviour impedes optimisation. That said, mixing signedness of integer types is responsible for an equally large class of problems. The best advice we can provide: try to use iterators and containers rather than pointers and sizes, try not to mix signedness, and try to avoid unsigned types (except for representing bitfields or modular arithmetic). Do not use an unsigned type merely to assert that a variable is non-negative. .. _`preprocessor macros`: Preprocessor Macros ------------------- Avoid defining macros, especially in headers; prefer inline functions, enums, and const variables. Do not use macros to define pieces of a C++ API. Be aware that if you do not have a **very** good reason to submit code with a macro, it will likely be rejected. Macros mean that the code you see is not the same as the code the compiler sees. This can introduce unexpected behaviour, especially since macros have global scope. The problems introduced by macros are especially severe when they are used to define pieces of a C++ API, and still more so for public APIs. Every error message from the compiler when developers incorrectly use that interface now must explain how the macros formed the interface. Refactoring and analysis tools have a dramatically harder time updating the interface. As a consequence, we specifically disallow using macros in this way. For example, avoid patterns like: .. code-block:: c++ class WOMBAT_TYPE(Foo) { // ... public: EXPAND_PUBLIC_WOMBAT_API(Foo) EXPAND_WOMBAT_COMPARISONS(Foo, ==, <) }; Luckily, macros are not nearly as necessary in C++ as they are in C. Instead of using a macro to inline performance-critical code, use an inline function. Instead of using a macro to store a constant, use a ``const`` or ``constexpr`` variable. Instead of using a macro to "abbreviate" a long variable name, use a reference. Instead of using a macro to conditionally compile code ... well, don't do that at all (except, of course, for the ``#define`` guards to prevent double inclusion of header files, and packages such as MPI). It makes testing much more difficult. Macros can do things these other techniques cannot, and you do see them in the code base, especially in the lower-level libraries. And some of their special features (like stringifying, concatenation, and so forth) are not available through the language proper. But before using a macro, consider carefully whether there's a non-macro way to achieve the same result. If you need to use a macro to define an interface, contact the `discussion forum `_. The following usage pattern will avoid many problems with macros; if you use macros, follow it whenever possible: - Don't define macros in a ``.hh`` file. - ``#define`` macros right before you use them, and ``#undef`` them right after. - Do not just ``#undef`` an existing macro before replacing it with your own; instead, pick a name that's likely to be unique. - Try not to use macros that expand to unbalanced C++ constructs, or at least document that behaviour well. - Prefer not using ``##`` to generate function/class/variable names. Exporting macros from headers (i.e. defining them in a header without ``#undef``\ing them before the end of the header) is extremely strongly discouraged. If you do export a macro from a header, it must have a globally unique name. To achieve this, it must be named with a prefix consisting of your project's namespace name (but upper case). ``0`` and ``nullptr``/``NULL`` ------------------------------ Use ``0`` for integers, ``0.`` for reals, ``nullptr`` for pointers, and ``'\0'`` for chars. For pointers (address values), there is a choice between ``0``, ``NULL``, and ``nullptr``. *µ*\Spectre only accepts ``nullptr``, as this provides type-safety. Use ``'\0'`` for the null character. Using the correct type makes the code more readable. sizeof ------ Prefer ``sizeof(varname)`` to ``sizeof(type)``. Use ``sizeof(varname)`` when you take the size of a particular variable. ``sizeof(varname)`` will update appropriately if someone changes the variable type either now or later. You may use ``sizeof(type)`` for code unrelated to any particular variable, such as code that manages an external or internal data format where a variable of an appropriate C++ type is not convenient. .. code-block:: c++ Struct data; memset(&data, 0, sizeof(data)); memset(&data, 0, sizeof(Struct)); if (raw_size < sizeof(int)) { LOG(ERROR) << "compressed record not big enough for count: " << raw_size; return false; } auto ---- Use auto to avoid type names that are noisy, obvious, or unimportant - cases where the type doesn't aid in clarity for the reader. Continue to use manifest type declarations only when it helps readability or you wish to override the type (important in the context of expression templates, see `Eigen C++11 and the auto keyword `_). Pros: - C++ type names can be long and cumbersome, especially when they involve templates or namespaces. - Long type names hinder readability. - When a C++ type name is repeated within a single declaration or a small code region, the repetition hinders readability and breaks the :ref:`DRY ` principle. - It is sometimes safer to let the type be specified by the type of the initialisation expression, since that avoids the possibility of unintended copies or type conversions. - Allows the use of universal references ``auto &&`` which allow to write efficient template expression code without sacrificing readability. Cons: - Sometimes code is clearer when types are manifest, especially when a variable's initialisation depends on things that were declared far away. In expressions like: .. code-block:: c++ auto foo = x.add_foo(); auto i = y.Find(key); - it may not be obvious what the resulting types are if the type of ``y`` isn't very well known, or if ``y`` was declared many lines earlier. - Programmers have to understand the difference between ``auto`` and ``const auto&`` or they'll get copies when they didn't mean to. Decision: ``auto`` is highly encouraged when it increases readability and reduces redundant code repetitions, particularly as described below. Not using ``auto`` in these conditions is to be considered a bug. Never initialise an ``auto``-typed variable with a braced initialiser list. Typical example cases where ``auto`` is appropriate: - For iterators and other long/cluttery type names, particularly when the type is clear from context (calls to ``find``, ``begin``, or ``end`` for instance). - When the type is clear from local context (in the same expression or within a few lines). Initialisation of a pointer or smart pointer with calls to ``new`` and ``std::make_unique`` commonly falls into this category, as does use of ``auto`` in a range-based loop over a container whose type is spelled out nearby. - When the type doesn't matter because it isn't being used for anything other than equality comparison. - When iterating over a map with a range-based loop (because it is often assumed that the correct type is ``std::pair`` whereas it is actually ``std::pair``). This is particularly well paired with local key and value aliases for ``.first`` and ``.second`` (often const-ref). .. code-block:: c++ for (const auto& item : some_map) { const KeyType& key = item.first; const ValType& value = item.second; // The rest of the loop can now just refer to key and value, // a reader can see the types in question, and we've avoided // the too-common case of extra copies in this iteration. } .. _`braced initialiser list`: Braced Initialiser List ----------------------- You may use braced initialiser lists. In C++03, aggregate types (arrays and structs with no constructor) could be initialised with braced initialiser lists. .. code-block:: c++ struct Point { int x; int y; }; Point p = {1, 2}; In C++11, this syntax was generalised, and any object type can now be created with a braced initialiser list, known as a braced-init-list in the C++ grammar. Here are a few examples of its use. .. code-block:: c++ // Vector takes a braced-init-list of elements. std::vector v{"foo", "bar"}; // Basically the same, ignoring some small technicalities. // You may choose to use either form. std::vector v = {"foo", "bar"}; // Usable with 'new' expressions. auto p = new std::vector{"foo", "bar"}; // A map can take a list of pairs. Nested braced-init-lists work. std::map m = {{1, "one"}, {2, "2"}}; // A braced-init-list can be implicitly converted to a return type. std::vector test_function() { return {1, 2, 3}; } // Iterate over a braced-init-list. for (int i : {-1, -2, -3}) {} // Call a function using a braced-init-list. void TestFunction2(std::vector v) {} TestFunction2({1, 2, 3}); A user-defined type can also define a constructor and/or assignment operator that take ``std::initialiser_list``, which is automatically created from braced-init-list: .. code-block:: c++ class MyType { public: // std::initialiser_list references the underlying init list. // It should be passed by value. MyType(std::initialiser_list init_list) { for (int i : init_list) append(i); } MyType& operator=(std::initialiser_list init_list) { clear(); for (int i : init_list) append(i); } }; MyType m{2, 3, 5, 7}; Finally, brace initialisation can also call ordinary constructors of data types, even if they do not have ``std::initialiser_list`` constructors. .. code-block:: c++ double d{1.23}; // Calls ordinary constructor as long as MyOtherType has no // std::initialiser_list constructor. class MyOtherType { public: explicit MyOtherType(string); MyOtherType(int, string); }; MyOtherType m = {1, "b"}; // If the constructor is explicit, you can't use the "= {}" form. MyOtherType m{"b"}; Never assign a braced-init-list to an ``auto`` local variable. In the single element case, what this means can be confusing. .. code-block:: c++ auto d = {1.23}; // d is a std::initialiser_list auto d = double{1.23}; // Good but weird -- d is a double, not a std::initialiser_list. See :ref:`braced initialiser list format` for formatting. .. _`lambda expressions`: Lambda expressions ------------------ Use lambda expressions where appropriate. Use explicit captures. Definition: Lambda expressions are a concise way of creating anonymous function objects. They're often useful when passing functions as arguments. For example: .. code-block:: c++ std::sort(v.begin(), v.end(), [](int x, int y) { return Weight(x) < Weight(y); }); They further allow capturing variables from the enclosing scope either explicitly by name, or implicitly using a default capture. Explicit captures require each variable to be listed, as either a value or reference capture: .. code-block:: c++ int weight{3}; int sum{0}; // Captures `weight` by value and `sum` by reference. std::for_each(v.begin(), v.end(), [weight, &sum](int x) { sum += weight * x; }); Default captures implicitly capture any variable referenced in the lambda body, including this if any members are used: .. code-block:: c++ const std::vector lookup_table = ...; std::vector indices = ...; // Captures `lookup_table` by reference, sorts `indices` by the value // of the associated element in `lookup_table`. std::sort(indices.begin(), indices.end(), [&](int a, int b) { return lookup_table[a] < lookup_table[b]; }); Lambdas were introduced in C++11 along with a set of utilities for working with function objects, such as the polymorphic wrapper ``std::function``. Pros: - Lambdas are much more concise than other ways of defining function objects to be passed to STL algorithms, which can be a readability improvement. - Appropriate use of default captures can remove redundancy and highlight important exceptions from the default. - Lambdas, ``std::function``, and ``std::bind`` can be used in combination as a general purpose callback mechanism; they make it easy to write functions that take bound functions as arguments. Cons: - Variable capture in lambdas can be a source of dangling-pointer bugs, particularly if a lambda escapes the current scope. - Default captures by value can be misleading because they do not prevent dangling-pointer bugs. Capturing a pointer by value doesn't cause a deep copy, so it often has the same lifetime issues as capture by reference. This is especially confusing when capturing ``this`` by value, since the use of ``this`` is often implicit. - It's possible for use of lambdas to get out of hand; very long nested anonymous functions can make code harder to understand. Decision: - Use lambda expressions where appropriate, with formatting as described below. - Use explicit captures if the lambda may escape the current scope. For example, instead of: .. code-block:: c++ { Foo foo; ... executor->schedule([&] { frobnicate(foo); }) ... } // BAD! The fact that the lambda makes use of a reference to `foo` and // possibly `this` (if `frobnicate` is a member function) may not be // apparent on a cursory inspection. If the lambda is invoked after // the function returns, that would be bad, because both `foo` // and the enclosing object could have been destroyed. prefer to write: .. code-block:: c++ { Foo foo; ... executor->schedule([&foo] { frobnicate(foo); }) ... } // BETTER - The compile will fail if `frobnicate` is a member // function, and it's clearer that `foo` is dangerously captured by // reference. - Do not usese default capture by reference (``[&]``). - Do not use default capture by value (``[=]``). - Keep unnamed lambdas short. If a lambda body is more than maybe five lines long, prefer to give the lambda a name, or to use a named function instead of a lambda. - Specify the return type of the lambda explicitly if that will make it more obvious to readers, as with ``auto``. Template metaprogramming ------------------------ Template metaprogramming is our tool to obtain both generic and efficient code. It can be complicated, but efficiency is the top priority in the core of *µ*\Spectre. Definition: Template metaprogramming refers to a family of techniques that exploit the fact that the C++ template instantiation mechanism is Turing complete and can be used to perform arbitrary compile-time computation in the type domain. Pros: Template metaprogramming allows extremely flexible interfaces that are type safe and high performance. Facilities like the `Boost unit test framework `_, ``std::tuple``, ``std::function``, and ``Boost.Spirit`` would be impossible without it. Cons: The techniques used in template metaprogramming are often obscure to anyone but language experts. Code that uses templates in complicated ways is demanding to read, and is hard to debug. Template metaprogramming often leads to extremely poor compiler time error messages: even if an interface is simple, the complicated implementation details become visible when the user does something wrong. Template metaprogramming interferes with large scale refactoring by making the job of refactoring tools harder. First, the template code is expanded in multiple contexts, and it's hard to verify that the transformation makes sense in all of them. Second, some refactoring tools work with an AST that only represents the structure of the code after template expansion. It can be difficult to automatically work back to the original source construct that needs to be rewritten. Decision: Template metaprogramming sometimes allows cleaner and easier-to-use interfaces than would be possible without it. It's best used in a small number of low level components where the extra maintenance burden is spread out over a large number of uses (i.e., the core of *µ*\Spectre, e.g. ``MaterialMuSpectre`` and the data structures). If you use template metaprogramming, you should expect to put considerable effort into minimising and isolating the complexity. You should hide metaprogramming as an implementation detail whenever possible, so that user-facing headers are readable, and you should make sure that tricky code is especially well commented. You should carefully document how the code is used, and you should say something about what the "generated" code looks like. Pay extra attention to the error messages that the compiler emits when users make mistakes. The error messages are part of your user interface, and your code should be tweaked as necessary so that the error messages are understandable and actionable from a user point of view. Boost ----- We try to depend on Boost as little as possible. The core library should not at all depend on Boost, while the tests use the `Boost unit test framework `_. There is one exception: For users with ancient compilers, Boost is used to emulate ``std::optional``. Do not add Boost dependencies. Definition: The `Boost library collection `_ is a popular collection of peer-reviewed, free, open-source C++ libraries. Pros: Boost code is generally very high-quality, is widely portable, and fills many important gaps in the C++ standard library, such as type traits and better binders. Cons: Boost can be tricky to install on certain systems C++14 ----- Use libraries and language extensions from C++14 when appropriate. C++14 contains significant improvements both to the language and libraries. Nonstandard Extensions ---------------------- Nonstandard extensions to C++ may not be used unless needed to fix compiler bugs. Compilers support various extensions that are not part of standard C++. Such extensions include GCC's ``__attribute__``. Cons: - Nonstandard extensions do not work in all compilers. Use of nonstandard extensions reduces portability of code. - Even if they are supported in all targeted compilers, the extensions are often not well-specified, and there may be subtle behaviour differences between compilers. - Nonstandard extensions add to the language features that a reader must know to understand the code. Decision: Do not use nonstandard extensions. Aliases ------- Public aliases are for the benefit of an API's user, and should be clearly documented. Definition: You can create names that are aliases of other entities: .. code-block:: c++ template using Bar = Foo; using other_namespace::Foo; In *µ*\Spectre, aliases are created with the ``using`` keyword and never with ``typedef``, because it provides a more consistent syntax with the rest of C++ and works with templates. Like other declarations, aliases declared in a header file are part of that header's public API unless they're in a function definition, in the private portion of a class, or in an explicitly-marked internal namespace. Aliases in such areas or in ``.cc`` files are implementation details (because client code can't refer to them), and are not restricted by this rule. Pros: - Aliases can improve readability by simplifying a long or complicated name. - Aliases can reduce duplication by naming in one place a type used repeatedly in an API, which might make it easier to change the type later. Cons: - When placed in a header where client code can refer to them, aliases increase the number of entities in that header's API, increasing its complexity. - Clients can easily rely on unintended details of public aliases, making changes difficult. - It can be tempting to create a public alias that is only intended for use in the implementation, without considering its impact on the API, or on maintainability. - Aliases can create risk of name collisions - Aliases can reduce readability by giving a familiar construct an unfamiliar name - Type aliases can create an unclear API contract: it is unclear whether the alias is guaranteed to be identical to the type it aliases, to have the same API, or only to be usable in specified narrow ways Decision: Don't put an alias in your public API just to save typing in the implementation; do so only if you intend it to be used by your clients. When defining a public alias, document the intent of the new name. This lets the user know whether they can treat the types as substitutable or whether more specific rules must be followed, and can help the implementation retain some degree of freedom to change the alias. Don't put namespace aliases in your public API. (See also :ref:`Namespaces `). For example, these aliases document how they are intended to be used in client code: .. code-block:: c++ namespace mynamespace { // Used to store field measurements. DataPoint may change from Bar* to some internal type. // Client code should treat it as an opaque pointer. using DataPoint = foo::Bar*; // A set of measurements. Just an alias for user convenience. using TimeSeries = std::unordered_set, DataPointComparator>; } // namespace mynamespace These aliases don't document intended use, and half of them aren't meant for client use: .. code-block:: c++ namespace mynamespace { // Bad: none of these say how they should be used. using DataPoint = foo::Bar*; using std::unordered_set; // Bad: just for local convenience using std::hash; // Bad: just for local convenience typedef unordered_set, DataPointComparator> TimeSeries; } // namespace mynamespace However, local convenience aliases are fine in function definitions, private sections of classes, explicitly marked internal namespaces, and in ``.cc`` files: .. code-block:: c++ // In a ``.cc`` file using foo::Bar; Naming ====== The most important consistency rules are those that govern naming. The style of a name immediately informs us what sort of thing the named entity is: a type, a variable, a function, a constant, a macro, etc., without requiring us to search for the declaration of that entity. The pattern-matching engine in our brains relies a great deal on these naming rules. Naming rules are pretty arbitrary, but we feel that consistency is more important than individual preferences in this area, so regardless of whether you find them sensible or not, the rules are the rules. .. _`general naming rules`: General Naming Rules -------------------- Names should be descriptive; avoid abbreviation. Give as descriptive a name as possible, within reason. Do not worry about saving horizontal space as it is far more important to make your code immediately understandable by a new reader. Do not use abbreviations that are ambiguous or unfamiliar to readers outside your project, and do not abbreviate by deleting letters within a word. Abbreviations that would be familiar to someone outside your project with relevant domain knowledge are OK. As a rule of thumb, an abbreviation is probably OK if it's listed in Wikipedia. A few good examples: .. code-block:: c++ int price_count_reader; // No abbreviation. int nb_params; // "nb" is a widespread convention. int nb_dns_connections; // Most people know what "DNS" stands for. int lstm_size; // "LSTM" is a common machine learning abbreviation. A few bad examples .. code-block:: c++ int n; // Meaningless. int nerr; // Ambiguous abbreviation. int n_comp_conns; // Ambiguous abbreviation. int wgc_connections; // Only your group knows what this stands for. int pc_reader; // Lots of things can be abbreviated "pc". int cstmr_id; // Deletes internal letters. FooBarRequestInfo fbri; // Not even a word. Note that certain universally-known abbreviations are OK, such as ``i`` for an iteration variable and ``T`` for a template parameter. For some symbols, this style guide recommends names to start with a capital letter and to have a capital letter for each new word (a.k.a. "CamelCase"). When abbreviations appear in such names, prefer to capitalise every letter of the abbreviation (i.e. ``FFTEngine``, not ``FftEngine``). Template parameters should follow the naming style for their category: type template parameters should follow the rules for type names, and non-type template parameters should follow the rules for ``constexpr`` variable names. File Names ---------- Filenames should be all lowercase and can include underscores (``_``). File names should indicate their content. Examples of acceptable file names: .. code-block:: sh my_useful_class.cc # implementation of MyUsefulClass my_useful_class.hh # interface and inlines of MyUsefulClass fft_utils.hh # declarations (header) for a bunch of FFT-related tools test_my_useful_class.cc // unittests for MyUsefulClass C++ files should end in ``.cc`` and header files should end in ``.hh`` (see also the section on :ref:`self-contained headers `). Do not use filenames that already exist in ``/usr/include`` or widely used libraries, such as ``db.hh``. In general, make your filenames very specific. For example, use ``http_server_logs.hh`` rather than ``logs.hh``. A very common case is to have a pair of files called, e.g., ``foo_bar.hh`` and ``foo_bar.cc``, defining a class called ``FooBar``. Inline functions must be in a ``.hh`` file. If your inline functions are very short, they should go directly into your ``.hh`` file. .. _`type names`: Type Names ---------- Type names start with a capital letter and have a capital letter for each new word (CamelCase), with no underscores: ``MyExcitingClass``, ``MyExcitingEnum``. The names of all types — classes, structs, type aliases, enums, and type template parameters — have the same naming convention. Type names should start with a capital letter and have a capital letter for each new word. No underscores. For example: .. code-block:: c++ // classes and structs class UrlTable { ... class UrlTableTester { ... struct UrlTableProperties { ... // using aliases using PropertiesMap_t = hash_map; // enums enum UrlTableErrors { ... There are two classes of very useful exception to above rules: - When using aliases, please append ``_t`` for alias types ``_ptr`` for alias (smart) pointers and ``_ref`` for alias references and ``std::reference_wrapper``\s. - In the specific context of type manipulations using the STL's type traits, it can help readability to follow the STL's convention of lowercase ``type_names_with_undenscores_t``. Variable Names -------------- The names of variables (including function parameters) and data members are all lowercase, with underscores between words. For instance: ``a_local_variable``, ``a_struct_data_member``, ``this->a_class_data_member``. Use class members exclusively with explicit mention of the ``this`` pointer. Common Variable names For example: .. code-block:: c++ string table_name; // OK - uses underscore. string tablename; // Bad - missing underscore. string tableName; // Bad - mixed case. ``struct`` and ``class`` Data Members ..................................... Data members of ``struct``\s and classes, both static and non-static, are named like ordinary nonmember variables. .. code-block:: c++ class TableInfo { ... private: string unique_name; // OK - underscore at end. static Field_t gradient; // OK. string tablename; // Bad - missing underscore. }; See :ref:`structs vs classes` for a discussion of when to use a struct versus a class. .. _`constant names`: ``constexpr`` and ``const`` Names --------------------------------- Variables declared ``constexpr`` and non-class template parameters are CamelCase, ``const`` are named like regular variables. Function Names -------------- Regular functions and methods are named like variables (lowercase ``name_with_underscore``). .. code-block:: c++ make_field() get_nb_components() compute_stresses() Distinguish (member) functions that compute something at non-trivial cost from simple accessors to internal variables, and ``constexpr static`` accessors: .. code-block:: c++ compute_stresses() // not an accessor, does actual work get_nb_components() // simple accessor sdim() // constexpr compile-time access .. _`namespace names`: Namespace Names --------------- The main namespace is ``muSpectre``. All subordinate namespaces are CamelCase. Avoid collisions between nested namespaces and well-known top-level namespaces. If a namespace is only used to hide unnecessary internal complications, put it in ``namespace internal`` or ``namespace *_internal`` to indicate that these are implementation details that the user does not have to bother with. Keep in mind that the :ref:`rule against abbreviated names ` applies to namespaces just as much as variable names. Code inside the namespace seldom needs to mention the namespace name, so there's usually no particular need for abbreviation anyway. Avoid nested namespaces that match well-known top-level namespaces. Collisions between namespace names can lead to surprising build breaks because of name lookup rules. In particular, do not create any nested ``std`` namespaces. Enumerator Names ---------------- Enumerators (for both scoped and unscoped enums) should be named like ``constexpr`` variables (CamelCase). Preferably, the individual enumerators should be named like constants. However, it is also acceptable to name them like macros. The enumeration name, UrlTableErrors (and AlternateUrlTableErrors), is a type, and therefore mixed case. .. code-block:: c++ //! Material laws can declare which type of strain measure they require and //! µSpectre will provide it enum class StrainMeasure { Gradient, //!< placement gradient (δy/δx) Infinitesimal, //!< small strain tensor .5(∇u + ∇uᵀ) GreenLagrange, //!< Green-Lagrange strain .5(Fᵀ·F - I) Biot, //!< Biot strain Log, //!< logarithmic strain Almansi, //!< Almansi strain RCauchyGreen, //!< Right Cauchy-Green tensor LCauchyGreen, //!< Left Cauchy-Green tensor no_strain_ //!< only for triggering static_assert }; Note that the last case, ``StrainMeasure::no_strain_`` is deliberately not named like an ``enum``, to indicate that it is an invalid state; Macro Names ----------- You're not really going to define a macro, are you? If you do, they're like this: ``MY_MACRO_THAT_SCARES_SMALL_CHILDREN_AND_ADULTS_ALIKE.`` Please see the :ref:`description of macros `; in general macros should not be used. However, if they are absolutely needed, then they should be named with all capitals and underscores. Be ready to argue the need for a macro in your submission, and prepare yourself for rejection if you do not have an overwhelmingly convincing reason. .. code-block:: c++ #define ROUND(x) ... #define PI_ROUNDED 3.0 Exceptions to Naming Rules -------------------------- Exceptions are classes and as such follow the :ref:`Type Names ` rules (CamelCase), but additionally end in ``Error``, e.g., ``ProjectionError``. Comments ======== Though a pain to write, comments are absolutely vital to keeping our code readable. The following rules describe what you should comment and where. But remember: while comments are very important, the best code is self-documenting. Giving sensible names to types and variables is much better than using obscure names that you must then explain through comments. When writing your comments, write for your audience: the next contributor who will need to understand your code. Be generous — the next one may be you! Comment Style ------------- Use either the ``//`` or ``/* ... */`` syntax for comments that are only relevant within their context (local comments for the reader/maintainer of your code) Use ``//!``, ``/** ... */``, and ``//!<`` syntax for doxygen comments (which will end up being compiled into the API :ref:`reference`), see `Doxygen `_ for details on doxygen. File Comments ------------- Start each file with license boilerplate. e.g., for file ``common.hh`` authored by John Doe: .. code-block:: c++ /** * @file common.hh * * @author John Doe * * @date 01 May 2017 * * @brief Small prototypes of commonly used types throughout µSpectre * * @section LICENSE * * Copyright © 2017 Till Junge, John Doe * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ Note on copyright: it is shared among the writers of the particular file, but chances are that in most cases, at least part of each new file contains ideas or even copied-and-pasted snippets from other files. Give the authors of those files also shared copyright. File comments describe the contents of a file. If a file declares, implements, or tests exactly one abstraction that is documented by a comment at the point of declaration, file comments are not required. All other files must have file comments. Every file should contain GPL boilerplate. Do not duplicate comments in both the ``.hh`` and the .cc. Duplicated comments diverge. .. _`class comments`: Class Comments -------------- Every non-obvious class declaration should have an accompanying comment that describes what it is for and how it should be used. .. code-block:: c++ /** * Virtual base class for all fields. A field represents * meta-information for the per-pixel storage for a scalar, vector * or tensor quantity and is therefore the abstract class defining * the field. It is used for type and size checking at runtime and * for storage of polymorphic pointers to fully typed and sized * fields. `FieldBase` (and its children) are templated with a * specific `FieldCollection` (derived from * `muSpectre::FieldCollectionBase`). A `FieldCollection` stores * multiple fields that all apply to the same set of * pixels. Addressing and managing the data for all pixels is * handled by the `FieldCollection`. Note that `FieldBase` does * not know anything about about mathematical operations on the * data or how to iterate over all pixels. Mapping the raw data * onto for instance Eigen maps and iterating over those is * handled by the `FieldMap`. */ template class FieldBase { ... }; The class comment should provide the reader with enough information to know how and when to use the class, as well as any additional considerations necessary to correctly use the class. Document the assumptions the class makes, if any. If an instance of the class can be accessed by multiple threads, take extra care to document the rules and invariants surrounding multithreaded use. The class comment is often a good place for a small example code snippet demonstrating a simple and focused usage of the class. When sufficiently separated (e.g. ``.hh`` and ``.cc`` files), comments describing the use of the class should go together with its interface definition; comments about the class operation and implementation should accompany the interface definition of the class's methods. Function Comments ----------------- Declaration comments describe use of the function; comments at the definition of a function describe operation. Function Declarations ..................... Every function declaration should have comments immediately preceding it that describe what the function does and how to use it. These comments should be descriptive ("Opens the file") rather than imperative ("Open the file"); the comment describes the function, it does not tell the function what to do. In general, these comments do not describe how the function performs its task. Instead, that should be left to comments in the function definition. Types of things to mention in comments at the function declaration: - What the inputs and outputs are. - For class member functions: whether the object remembers reference arguments beyond the duration of the method call, and whether it will free them or not. - If the function allocates memory that the caller must free. - Whether any of the arguments can be a null pointer. - If there are any performance implications of how a function is used. - If the function is re-entrant. What are its synchronisation assumptions? Here is an example: .. code-block:: c++ /** Returns an iterator for this table. It is the client's * responsibility to delete the iterator when it is done with it, * and it must not use the iterator once the GargantuanTable object * on which the iterator was created has been deleted. * * The iterator is initially positioned at the beginning of the table. * * This method is equivalent to: * Iterator* iter = table->NewIterator(); * iter->Seek(""); * return iter; * If you are going to immediately seek to another place in the * returned iterator, it will be faster to use NewIterator() * and avoid the extra seek. */ Iterator get_iterator() const; However, do not be unnecessarily verbose or state the completely obvious. When documenting function overrides, focus on the specifics of the override itself, rather than repeating the comment from the overridden function. In many of these cases, the override needs no additional documentation and thus only brief comments are required. When commenting constructors and destructors, remember that the person reading your code knows what constructors and destructors are for, so comments that just say something like "destroys this object" are not useful. Document what constructors do with their arguments (for example, if they take ownership of pointers), and what cleanup the destructor does. If this is trivial, just name it (``default constructor``, ``move constructor``, ``destructor`` etc). Function Definitions .................... If there is anything tricky about how a function does its job, the function definition should have an explanatory comment. For example, in the definition comment you might describe any coding tricks you use, give an overview of the steps you go through, or explain why you chose to implement the function in the way you did rather than using a viable alternative. For instance, you might mention why it must acquire a lock for the first half of the function but why it is not needed for the second half. Note you should not just repeat the comments given with the function declaration, in the ``.hh`` file or wherever. It's okay to recapitulate briefly what the function does, but the focus of the comments should be on how it does it. Variable Comments ----------------- In general the actual name of the variable should be descriptive enough to give a good idea of what the variable is used for, but we require a short description for the API documentation. Class Data Members .................. The purpose of each class data member (also called an instance variable or member variable) must be clear. If there are any invariants (special values, relationships between members, lifetime requirements) not clearly expressed by the type and name, they must be commented. However, if the type and name suffice (``int nb_events``;), a brief "number of events" is a sufficient comment: .. code-block:: c++ protected: const std::string name; //!< the field's unique name const size_t nb_components; //!< number of components per entry //! reference to the collection this field belongs to const FieldCollection & collection; size_t pad_size; //!< size of padding region at end of buffer Global Variables ................ All global variables should have a comment describing what they are, what they are used for, and (if unclear) why it needs to be global. For example: .. code-block:: c++ constexpr Dim_t oneD{1}; //!< constant for a one-dimensional problem constexpr Dim_t twoD{2}; //!< constant for a two-dimensional problem constexpr Dim_t threeD{3}; //!< constant for a three-dimensional problem constexpr Dim_t firstOrder{1}; //!< constant for vectors constexpr Dim_t secondOrder{2}; //!< constant second-order tensors constexpr Dim_t fourthOrder{4}; //!< constant fourth-order tensors Implementation Comments ------------------------ In your implementation you should have comments in tricky, non-obvious, interesting, or important parts of your code. Explanatory Comments Tricky or complicated code blocks should have comments before them. Example: .. code-block:: c++ /* original definition of the operator in de Geus et * al. (https://doi.org/10.1016/j.cma.2016.12.032). However, * they use a obscure definition of the double contraction * between fourth-order and second-order tensors that has a * built-in transpose operation (i.e., C = A:B <-> AᵢⱼₖₗBₗₖ = * Cᵢⱼ , note the inverted ₗₖ instead of ₖₗ), here, we define * the double contraction without the transposition. As a * result, this Projection operator produces the transpose of de * Geus's */ for (Dim_t im = 0; im < DimS; ++im) { for (Dim_t j = 0; j < DimS; ++j) { for (Dim_t l = 0; l < DimS; ++l) { get(G, im, j, l, im) = xi(j)*xi(l); } } } Line Comments ............. Also, lines that are non-obvious should get a comment at the end of the line. These end-of-line comments should be separated from the code by at least one space. Example: .. code-block:: c++ // If we have enough memory, mmap the data portion too. mmap_budget = max(0, mmap_budget - index_->length()); if (mmap_budget >= data_size_ && !MmapData(mmap_chunk_bytes, mlock)) return; // Error already logged. Note that there are both comments that describe what the code is doing, and comments that mention that an error has already been logged when the function returns. If you have several comments on subsequent lines, it can often be more readable to line them up: .. code-block:: c++ do_something(); // Comment here so the comments line up. do_somethingElseThatIsLonger(); // Two spaces between the code and the comment. { // One space before comment when opening a new scope is allowed, // thus the comment lines up with the following comments and code. do_somethingElse(); // Two spaces before line comments normally. } std::vector list{ // Comments in braced lists describe the next element... "First item", // .. and should be aligned appropriately. "Second item"}; do_something(); /* For trailing block comments, one space is fine. */ Self-describing code doesn't need a comment. The comment from the example above would be obvious: .. code-block:: c++ if (!IsAlreadyProcessed(element)) { Process(element); } Punctuation, Spelling and Grammar --------------------------------- Pay attention to punctuation, spelling, and grammar; it is easier to read well-written comments than badly written ones. Comments should be as readable as narrative text, with proper capitalisation and punctuation. In many cases, complete sentences are more readable than sentence fragments. Shorter comments, such as comments at the end of a line of code, can sometimes be less formal, but you should be consistent with your style. Although it can be frustrating to have a code reviewer point out that you are using a comma when you should be using a semicolon, it is very important that source code maintain a high level of clarity and readability. Proper punctuation, spelling, and grammar help with that goal. ``TODO`` Comments ----------------- Use ``TODO`` comments for code that is temporary, a short-term solution, or good-enough but not perfect. ``TODO``\s should include the string ``TODO`` in all caps, followed by the name, e-mail address, Phabricator task number or other identifier of the person or issue with the best context about the problem referenced by the ``TODO``. The main purpose is to have a consistent ``TODO`` that can be searched to find out how to get more details upon request. A ``TODO`` is not a commitment that the person referenced will fix the problem. Thus when you create a ``TODO`` with a name, it is almost always your name that is given. .. code-block:: c++ // TODO(kl@gmail.com): Use a "*" here for concatenation operator. // TODO(Zeke) change this to use relations. // TODO(T1234): remove the "Last visitors" feature If your ``TODO`` is of the form "At a future date do something" make sure that you either include a very specific date ("Fix by November 2005") or a very specific event ("Remove this code when all clients can handle XML responses."). Deprecation Comments -------------------- Mark deprecated interface points with ``DEPRECATED`` comments. You can mark an interface as deprecated by writing a comment containing the word ``DEPRECATED`` in all caps. The comment goes either before the declaration of the interface or on the same line as the declaration. After the word ``DEPRECATED``, write your name, e-mail address, or other identifier in parentheses. A deprecation comment must include simple, clear directions for people to fix their call sites. In C++, you can implement a deprecated function as an inline function that calls the new interface point. Marking an interface point ``DEPRECATED`` will not magically cause any call sites to change. If you want people to actually stop using the deprecated facility, you will have to fix the call sites yourself or recruit a crew to help you. New code should not contain calls to deprecated interface points. Use the new interface point instead. If you cannot understand the directions, find the person who created the deprecation and ask them for help using the new interface point. Formatting ========== Coding style and formatting are pretty arbitrary, but a project is much easier to follow if everyone uses the same style. Individuals may not agree with every aspect of the formatting rules, and some of the rules may take some getting used to, but it is important that all project contributors follow the style rules so that they can all read and understand everyone's code easily. To help you format code correctly, Google has created a `settings file `_ for emacs. Line Length ----------- Each line of text in your code should be at most 80 characters long. We recognise that this rule is controversial, but so much existing code already adheres to it, and we feel that consistency is important. Pros: Those who favour this rule argue that it is rude to force them to resize their windows and there is no need for anything longer. Some folks are used to having several code windows side-by-side, and thus don't have room to widen their windows in any case. People set up their work environment assuming a particular maximum window width, and 80 columns has been the traditional standard. Why change it? Cons: Proponents of change argue that a wider line can make code more readable. The 80-column limit is an hidebound throwback to 1960s mainframes; modern equipment has wide screens that can easily show longer lines. Decision: 80 characters is the maximum. Exception: Comment lines can be longer than 80 characters if it is not feasible to split them without harming readability, ease of cut and paste or auto-linking -- e.g. if a line contains an example command or a literal URL longer than 80 characters. Exception: A raw-string literal may have content that exceeds 80 characters. Except for test code, such literals should appear near the top of a file. Exception: An ``#include`` statement with a long path may exceed 80 columns. Exception: You needn't be concerned about :ref:`header guards ` that exceed the maximum length. Non-ASCII Characters -------------------- In comments and human-readable names in strings, non-ASCII characters should be used where they help readability, and must use UTF-8 formatting, e.g. .. code-block:: c++ /** * verification of resultant strains: subscript ₕ for hard and ₛ * for soft, Nₕ is nb_lays and Nₜₒₜ is resolutions, k is contrast * * Δl = εl = Δlₕ + Δlₛ = εₕlₕ+εₛlₛ * => ε = εₕ Nₕ/Nₜₒₜ + εₛ (Nₜₒₜ-Nₕ)/Nₜₒₜ * * σ is constant across all layers * σₕ = σₛ * => Eₕ εₕ = Eₛ εₛ * => εₕ = 1/k εₛ * => ε / (1/k Nₕ/Nₜₒₜ + (Nₜₒₜ-Nₕ)/Nₜₒₜ) = εₛ */ constexpr Real factor{1/contrast * Real(nb_lays)/resolutions[0] + 1.-nb_lays/Real(resolutions[0])}; .. code-block:: c++ template MaterialHyperElastoPlastic1:: MaterialHyperElastoPlastic1(std::string name, Real young, Real poisson, Real tau_y0, Real H) : Parent{name}, plast_flow_field("cumulated plastic flow εₚ", this->internal_fields), F_prev_field("Previous placement gradient Fᵗ", this->internal_fields), be_prev_field("Previous left Cauchy-Green deformation bₑᵗ", this->internal_fields), young{young}, poisson{poisson}, lambda{Hooke::compute_lambda(young, poisson)}, mu{Hooke::compute_mu(young, poisson)}, K{Hooke::compute_K(young, poisson)}, tau_y0{tau_y0}, H{H}, // the factor .5 comes from equation (18) in Geers 2003 // (https://doi.org/10.1016/j.cma.2003.07.014) C{0.5*Hooke::compute_C_T4(lambda, mu)}, internal_variables{F_prev_field.get_map(), be_prev_field.get_map(), plast_flow_field.get_map()} {} You shouldn't use the C++11 ``char16_t`` and ``char32_t`` character types, since they're for non-UTF-8 text. For similar reasons you also shouldn't use ``wchar_t``. Spaces vs. Tabs --------------- Use only spaces, and indent 2 spaces at a time. We use spaces for indentation. Do not use tabs in your code. You should set your editor to emit spaces when you hit the tab key. Function Declarations and Definitions ------------------------------------- Return type on the same line as function name, parameters on the same line if they fit. Wrap parameter lists which do not fit on a single line as you would wrap arguments in a function call. Functions look like this: .. code-block:: c++ ReturnType ClassName::function_name(Type par_name1, Type par_name2) { do_something(); } If you have too much text to fit on one line: .. code-block:: c++ ReturnType ClassName::really_long_function_name(Type par_name1, Type par_name2, Type par_name3) { do_something(); } or if you cannot fit even the first parameter, be reasonable, in the spirit of readability: .. code-block:: c++ template typename MatrixLikeFieldMap::const_reference MatrixLikeFieldMap:: operator[](const Ccoord & ccoord) const{ size_t index{}; index = this->collection.get_index(ccoord); return const_reference(this->get_ptr_to_entry(std::move(index))); } Some points to note: - Choose good parameter names. - If you cannot fit the return type and the function name on a single line, break between them. - If you break after the return type of a function declaration or definition, do not indent. - There is never a space between the function name and the open parenthesis. - There is never a space between the parentheses and the parameters. - The open curly brace is always on the end of the last line of the function declaration, not the start of the next line. - The close curly brace is either on the last line by itself or on the same line as the open curly brace. - There should be a space between the close parenthesis and the open curly brace. - All parameters should be aligned if possible. - Default indentation is 2 spaces. Unused parameters that might not be obvious must comment out the variable name in the function definition: .. code-block:: c++ class Shape { public: virtual void rotate(double radians) = 0; }; class Circle : public Shape { public: void rotate(double radians) override; }; void Circle::rotate(double /*radians*/) {} .. code-block:: c++ // Bad - if someone wants to implement later, it's not clear what the // variable means. void Circle::rotate(double) {} Attributes, and macros that expand to attributes, appear at the very beginning of the function declaration or definition, before the return type: Lambda Expressions ------------------ Format parameters and bodies as for any other function, and capture lists like other comma-separated lists. For by-reference captures, do not leave a space between the ampersand (&) and the variable name. .. code-block:: c++ int x = 0; auto x_plus_n = [&x](int n) -> int { return x + n; } Short lambdas may be written inline as function arguments. .. code-block:: c++ std::set blacklist = {7, 8, 9}; std::vector digits = {3, 9, 1, 8, 4, 7, 1}; digits.erase(std::remove_if(digits.begin(), digits.end(), [&blacklist](int i) { return blacklist.find(i) != blacklist.end(); }), digits.end()); Function Calls -------------- Either write the call all on a single line, wrap the arguments at the parenthesis, or use common sense to help readability. In the absence of other considerations, use the minimum number of lines, including placing multiple arguments on each line where appropriate. Function calls have the following format: .. code-block:: c++ result = do_something(argument1, argument2, argument3); If the arguments do not all fit on one line, they should be broken up onto multiple lines, with each subsequent line aligned with the first argument. Do not add spaces after the open parenthesis or before the close parenthesis: .. code-block:: c++ result = do_something(averyveryveryverylongargument1, argument2, argument3); Arguments may optionally all be placed on subsequent lines. .. code-block:: c++ if (...) { ... ... if (...) { bool result = do_something (argument1, argument2, argument3, argument4); ... } Put multiple arguments on a single line to reduce the number of lines necessary for calling a function unless there is a specific readability problem. Some find that formatting with strictly one argument on each line is more readable and simplifies editing of the arguments. However, we prioritise for the reader over the ease of editing arguments, and most readability problems are better addressed with the following techniques. If having multiple arguments in a single line decreases readability due to the complexity or confusing nature of the expressions that make up some arguments, try creating variables that capture those arguments in a descriptive name: .. code-block:: c++ int my_heuristic{scores[x] * y + bases[x]}; result = do_something(my_heuristic, x, y, z); Or put the confusing argument on its own line with an explanatory comment: .. code-block:: c++ result = do_something(scores[x] * y + bases[x], // Score heuristic. x, y, z); If there is still a case where one argument is significantly more readable on its own line, then put it on its own line. The decision should be specific to the argument which is made more readable rather than a general policy. Sometimes arguments form a structure that is important for readability. In those cases, feel free to format the arguments according to that structure: .. code-block:: c++ // Transform the widget by a 3x3 matrix. my_widget.transform(x1, x2, x3, y1, y2, y3, z1, z2, z3); .. _`braced initialiser list format`: Braced Initialiser List Format ------------------------------ Format a :ref:`braced initialiser list ` exactly like you would format a function call in its place. If the braced list follows a name (e.g. a type or variable name), format as if the ``{}`` were the parentheses of a function call with that name. If there is no name, assume a zero-length name. .. code-block:: c++ // Examples of braced init list on a single line. return {foo, bar}; function_call({foo, bar}); std::pair p{foo, bar}; // When you have to wrap. some_function( {"assume a zero-length name before {"}, some_other_function_parameter); SomeType variable{ some, other, values, {"assume a zero-length name before {"}, SomeOtherType{ "Very long string requiring the surrounding breaks.", some, other values}, SomeOtherType{"Slightly shorter string", some, other, values}}; SomeType variable{ "This is too long to fit all in one line"}; MyType m = { // Here, you could also break before {. superlongvariablename1, superlongvariablename2, {short, interior, list}, {interiorwrappinglist, interiorwrappinglist2}}; Conditionals ------------ .. code-block:: c++ Prefer no spaces inside parentheses. The if and else keywords belong on separate lines. if (condition) { // no spaces inside parentheses ... // 2 space indent. } else if (...) { // The else goes on the same line as the closing brace. ... } else { ... } Note that in all cases you must have a space between the if and the open parenthesis. You must also have a space between the close parenthesis and the curly brace. .. code-block:: c++ if(condition) { // Bad - space missing after IF. if (condition){ // Bad - space missing before {. if(condition){ // Doubly bad. .. code-block:: c++ if (condition) { // Good - proper space after IF and before {. Short conditional statements may be written on one line if this enhances readability. You may use this only when the line is brief and the statement does not use the else clause. You must still use curly braces, as they exclude a particularly dumb class of bugs. .. code-block:: c++ if (x == kFoo) {return new Foo()}; if (x == kBar) {return new Bar()}; This is not allowed when the if statement has an else: .. code-block:: c++ // Not allowed - IF statement on one line when there is an ELSE clause if (x) {do_this()}; else {do_that()}; Loops and Switch Statements --------------------------- Switch statements must use braces for blocks. Annotate non-trivial fall-through between cases. Empty loop bodies should use ``{continue;}``. ``case`` blocks in switch statements have curly braces which should be placed as shown below. If not conditional on an enumerated value, switch statements should always have a default case (in the case of an enumerated value, the compiler will warn you if any values are not handled). If the default case should never execute, treat this as an error. For example: .. code-block:: c++ switch (form) { case Formulation::finite_strain: { return StrainMeasure::Gradient; break; } case Formulation::small_strain: { return StrainMeasure::Infinitesimal; break; } default: return StrainMeasure::no_strain_; break; } Braces are required even for single-statement loops. .. code-block:: c++ for (int i = 0; i < kSomeNumber; ++i) std::cout << "I love you" << std::endl; // Bad! .. code-block:: c++ for (int i = 0; i < kSomeNumber; ++i) { std::cout << "I take it back" << std::endl; } // Good! Pointer and Reference Expressions --------------------------------- No spaces around period or arrow. Pointer operators may have trailing spaces. The following are examples of correctly-formatted pointer and reference expressions: .. code-block:: c++ x = *p; x = * p; // also ok p = &x; p = & x; x = r.y; x = r->y; Note that: - There are no spaces around the period or arrow when accessing a member. - Pointer operators have no space after the ``*`` or ``&``. Boolean Expressions ------------------- When you have a boolean expression that is longer than the standard line length, be consistent in how you break up the lines. In this example, the logical AND operator is always at the end of the lines: .. code-block:: c++ if (this_one_thing > this_other_thing && a_third_thing == a_fourth_thing && yet_another && last_one) { ... } Note that when the code wraps in this example, both of the && logical AND operators are at the end of the line. This is more common, though wrapping all operators at the beginning of the line is also allowed. Feel free to insert extra parentheses judiciously because they can be very helpful in increasing readability when used appropriately. Return Values ------------- Do not needlessly surround the return expression with parentheses. Use parentheses in ``return expr``; only where you would use them in ``x = expr``;. .. code-block:: c++ return result; // No parentheses in the simple case. // Parentheses OK to make a complex expression more readable. return (some_long_condition && another_condition); .. code-block:: c++ return (value); // You wouldn't write var = (value); return(result); // return is not a function! Variable and Array Initialisation --------------------------------- Use ``{}`` when possible, ``()`` when necessary, avoid ``=``. .. code-block:: c++ int x(3.5); int x{3}; string name{"Some Name"}; .. code-block:: c++ string name("Some Name"); // could have used non-narrowing {} int x = 3; // could have used non-narrowing {} string name = "Some Name"; // could have used non-narrowing {} Be careful when using a braced initialisation list ``{...}`` on a type with an ``std::initialiser_list`` constructor. A nonempty braced-init-list prefers the ``std::initialiser_list`` constructor whenever possible. Note that empty braces ``{}`` are special, and will call a default constructor if available. To force the non-``std::initialiser_list`` constructor, use parentheses instead of braces. .. code-block:: c++ std::vector v(100, 1); // A vector containing 100 items: All 1s. std::vector v{100, 1}; // A vector containing 2 items: 100 and 1. Also, the brace form prevents narrowing of integral types. This can prevent some types of programming errors. .. code-block:: c++ int pi(3.14); // OK -- pi == 3. int pi{3.14}; // Compile error: narrowing conversion. Preprocessor Directives ----------------------- The hash mark that starts a preprocessor directive should always be at the beginning of the line. Even when preprocessor directives are within the body of indented code, the directives should start at the beginning of the line. .. code-block:: c++ // Good - directives at beginning of line if (lopsided_score) { #if DISASTER_PENDING // Correct -- Starts at beginning of line DropEverything(); # if NOTIFY // OK but not required -- Spaces after # NotifyClient(); # endif #endif BackToNormal(); } .. code-block:: c++ // Bad - indented directives if (lopsided_score) { #if DISASTER_PENDING // Wrong! The "#if" should be at beginning of line DropEverything(); #endif // Wrong! Do not indent "#endif" BackToNormal(); } Class Format ------------ Sections in ``public``, ``protected`` and ``private`` order, each unindented. The basic format for a class definition (lacking the comments, see :ref:`class comments` for a discussion of what comments are needed) is: .. code-block:: c++ class MyClass : public OtherClass { public: // Note the 1 space indent! MyClass(); // Regular 2 space indent. explicit MyClass(int var); ~MyClass() {} void some_function(); void some_function_that_does_nothing() { } void set_some_var(int var) { some_var_ = var; } int some_var() const { return some_var_; } protected: bool SomeInternalFunction(); int some_var_; int some_other_var_; }; Things to note: - Any base class name should be on the same line as the subclass name, subject to the 80-column limit. - The ``public:``, ``protected:``, and ``private:`` keywords should not be indented. - Except for the first instance, these keywords should be preceded by a blank line. This rule is optional in small classes. - Do not leave a blank line after these keywords. - The public section should be first, followed by the protected and finally the private section. - See :ref:`declaration order` for rules on ordering declarations within each of these sections. Constructor Initialiser Lists ----------------------------- Constructor initialiser lists can be all on one line or with subsequent lines indented four spaces. The acceptable formats for initialiser lists are: .. code-block:: c++ // wrap before the colon and indent 2 spaces: MyClass::MyClass(int var) :some_var_(var), some_other_var_(var + 1) { do_something(); } // When the list spans multiple lines, put each member on its own line // and align them: MyClass::MyClass(int var) :some_var_(var), // 4 space indent some_other_var_(var + 1) { // lined up do_something(); } // As with any other code block, the close curly can be on the same // line as the open curly, if it fits. MyClass::MyClass(int var) :some_var_(var) {} Namespace Formatting -------------------- The contents of namespaces are indented normally. Namespaces add an extra level of indentation. For example, use: .. code-block:: c++ namespace { void foo() { // Correct. Extra indentation within namespace. ... } } // namespace Indent within a namespace: .. code-block:: c++ namespace { // Wrong! Not indented when it should not be. void foo() { ... } } // namespace When declaring nested namespaces, put each namespace on its own line. .. code-block:: c++ namespace foo { namespace bar { Horizontal Whitespace --------------------- Use of horizontal whitespace depends on location. Never put trailing whitespace at the end of a line. General ....... .. code-block:: c++ void f(bool b) { // Open braces should always have a space before them. ... int i{0}; // Semicolons usually have no space before them. // Spaces inside braces for braced-init-list are optional. If you use them, // put them on both sides! int x[] = { 0 }; int x[] = {0}; // Spaces after the colon in inheritance and initialiser lists. class Foo: public Bar { public: // For inline function implementations, put spaces between the braces // and the implementation itself. Foo(int b) : Bar(), baz_(b) {} // No spaces inside empty braces. void Reset() { baz_ = 0; } // Spaces separating braces from implementation. ... Adding trailing whitespace can cause extra work for others editing the same file, when they merge, as can removing existing trailing whitespace. So: Don't introduce trailing whitespace. Remove it if you're already changing that line, or do it in a separate clean-up operation (preferably when no-one else is working on the file). Loops and Conditionals ...................... .. code-block:: c++ if (b) { // Space after the keyword in conditions and loops. } else { // Spaces around else. } while (test) {} // There is usually no space inside parentheses. switch (i) { for (int i = 0; i < 5; ++i) { // Loops and conditions may have spaces inside parentheses, but this // is rare. Be consistent. switch ( i ) { if ( test ) { for ( int i{0}; i < 5; ++i ) { // For loops always have a space after the semicolon. They may have a space // before the semicolon, but this is rare. for ( ; i < 5 ; ++i) { ... // Range-based for loops always have a space before and after the colon. for (auto x : counts) { ... } switch (i) { case 1: // No space before colon in a switch case. ... case 2: break; // Use a space after a colon if there's code after it. Operators ......... .. code-block:: c++ // Assignment operators always have spaces around them. x = 0; // Other binary operators usually have spaces around them, but it's // OK to remove spaces around factors. Parentheses should have no // internal padding. v = w * x + y / z; v = w*x + y/z; v = w * (x + z); // No spaces separating unary operators and their arguments. x = -5; ++x; if (x && !y) ... Templates and Casts ................... .. code-block:: c++ // No spaces inside the angle brackets (< and >), before // <, or between >( in a cast std::vector x; y = static_cast(x); // Spaces between type and pointer are OK, but be consistent. std::vector x; Vertical Whitespace ------------------- Minimise use of vertical whitespace. This is more a principle than a rule: don't use blank lines when you don't have to. In particular, don't put more than one or two blank lines between functions, resist starting functions with a blank line, don't end functions with a blank line, and be discriminating with your use of blank lines inside functions. The basic principle is: The more code that fits on one screen, the easier it is to follow and understand the control flow of the program. Of course, readability can suffer from code being too dense as well as too spread out, so use your judgement. But in general, minimise use of vertical whitespace. Some rules of thumb to help when blank lines may be useful: - Blank lines at the beginning or end of a function very rarely help readability. - Blank lines inside a chain of if-else blocks may well help readability. Exceptions to the Rules ======================= The coding conventions described above are mandatory. However, like all good rules, these sometimes have exceptions, which we discuss here. Existing Non-conformant Code ---------------------------- You may diverge from the rules when dealing with code that does not conform to this style guide. If you find yourself modifying code that was written to specifications other than those presented by this guide, you may have to diverge from these rules in order to stay consistent with the local conventions in that code. If you are in doubt about how to do this, ask the original author or the person currently responsible for the code. Remember that consistency includes local consistency, too. .. _joke: Windows Code ------------ Just kidding. Parting Words ============= Use common sense and BE CONSISTENT. If you are editing code, take a few minutes to look at the code around you and determine its style. If they use spaces around their if clauses, you should, too. If their comments have little boxes of stars around them, make your comments have little boxes of stars around them too. The point of having style guidelines is to have a common vocabulary of coding so people can concentrate on what you are saying, rather than on how you are saying it. We present global style rules here so people know the vocabulary. But local style is also important. If code you add to a file looks drastically different from the existing code around it, the discontinuity throws readers out of their rhythm when they go to read it. Try to avoid this. OK, enough writing about writing code; the code itself is much more interesting. Have fun! Python Coding Style ******************* *µ*\Spectre is a C++ project with a thin Python wrapping. Try to follow the spirit of the :ref:`cpp coding style and convention`, as far as it fits into ``pep8``. in case of conflict, follow ``pep8`` References ********** .. _`Hunt (2000)` : Hunt (2000) A. Hunt. The pragmatic programmer : from journeyman to master. Addison-Wesley, Reading, Mass, 2000. ISBN 978-0-2016-1622-4. .. _`Meyers (2014)` : Meyers (2014) Scott Meyers. `Effective Modern C++ `_, O'Reilly Media, November 2014, ISBN 978-1491903995 diff --git a/doc/dev-docs/source/ConstitutiveLaws.rst b/doc/dev-docs/source/ConstitutiveLaws.rst index 9b6bc6a..cd49e9b 100644 --- a/doc/dev-docs/source/ConstitutiveLaws.rst +++ b/doc/dev-docs/source/ConstitutiveLaws.rst @@ -1,128 +1,128 @@ .. toctree:: :maxdepth: 2 :caption: Contents: .. _constitutive_laws: Constitutive Laws ~~~~~~~~~~~~~~~~~ .. toctree:: :maxdepth: 2 MaterialLinearElasticGeneric Testing Constitutive Laws ~~~~~~~~~~~~~~~~~~~~~~~~~ When writing new constitutive laws, the ability to evaluate the stress-strain behaviour and the tangent moduli is convenient, but *µ*\Spectre's material model makes it cumbersome to isolate and execute the :cpp:func:`evaluate_stress` and :cpp:func:`evaluate_stress_tangent` methods than any daughter class of :cpp:class:`MaterialMuSpectre` must implement (e.g., :cpp:func:`evaluate_stress() `). As a helper object, *µ*\Spectre offers the class :cpp:class:`MaterialEvaluator` to facilitate precisely this: A :cpp:class:`MaterialEvaluator` object can be constructed with a shared pointer to a :cpp:class:`MaterialBase` and exposes functions to evaluate just the stress, both the stress and tangent moduli, or a numerical approximation to the tangent moduli. For materials with internal history variables, :cpp:class:`MaterialEvaluator` also exposes the :cpp:func:`MaterialBase::save_history_variables()` method. As a convenience function, all daughter classes of :cpp:class:`MaterialMuSpectre` have the static factory function :cpp:func:`make_evaluator() ` to create a material and its evaluator at once. See the :ref:`reference` for the full class description. Python Usage Example ```````````````````` .. code-block:: python import numpy as np from muSpectre import material from muSpectre import Formulation # MaterialLinearElastic1 is standard linear elasticity while # MaterialLinearElastic2 has a per pixel eigenstrain which needs to be set LinMat1, LinMat2 = (material.MaterialLinearElastic1_2d, material.MaterialLinearElastic2_2d) young, poisson = 210e9, .33 # the factory returns a material and it's corresponding evaluator material1, evaluator1 = LinMat1.make_evaluator(young, poisson) # the material is empty (i.e., does not have any pixel/voxel), so a pixel # needs to be added. The coordinates are irrelevant, there just needs to # be one pixel. material1.add_pixel([0,0]) # the stress and tangent can be evaluated for finite strain F = np.array([[1., .01],[0, 1.0]]) P, K = evaluator1.evaluate_stress_tangent(F, Formulation.finite_strain) # or small strain eps = .5 * ((F-np.eye(2)) + (F-np.eye(2)).T) sigma, C = evaluator1.evaluate_stress_tangent(eps, Formulation.small_strain) # and the tangent can be checked against a numerical approximation Delta_x = 1e-6 num_C = evaluator1.estimate_tangent(eps, Formulation.small_strain, Delta_x) # Materials with per-pixel data behave similarly: the factory returns a # material and it's corresponding evaluator like before material2, evaluator2 = LinMat2.make_evaluator(young, poisson) # when adding the pixel, we now need to specify also the per-pixel data: eigenstrain = np.array([[.01, .002], [.002, 0.]]) material2.add_pixel([0,0], eigenstrain) C++ Usage Example ````````````````` .. code-block:: c++ #include"materials/material_linear_elastic2.hh" #include "materials/material_evaluator.hh" - #include "common/T4_map_proxy.hh" + #include #include "Eigen/Dense" using Mat_t = MaterialLinearElastic2; constexpr Real Young{210e9}; constexpr Real Poisson{.33}; auto mat_eval{Mat_t::make_evaluator(Young, Poisson)}; auto & mat{*std::get<0>(mat_eval)}; auto & evaluator{std::get<1>(mat_eval)}; using T2_t = Eigen::Matrix; using T4_t = T4Mat; const T2_t F{(T2_t::Random() - (T2_t::Ones() * .5)) * 1e-4 + T2_t::Identity()}; T2_t eigen_strain{[](auto x) { return 1e-4 * (x + x.transpose()); }(T2_t::Random() - T2_t::Ones() * .5)}; mat.add_pixel({}, eigen_strain); T2_t P{}; T4_t K{}; std::tie(P, K) = evaluator.evaluate_stress_tangent(F, Formulation::finite_strain); diff --git a/external/CMakeLists.txt b/external/CMakeLists.txt new file mode 100644 index 0000000..1c44d6b --- /dev/null +++ b/external/CMakeLists.txt @@ -0,0 +1,9 @@ +if(POLICY CMP0076) + cmake_policy(SET CMP0076 NEW) +endif() + +add_library(cxxopts INTERFACE) +target_sources(cxxopts INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/cxxopts.hpp) +set_property(TARGET cxxopts APPEND PROPERTY INTERFACE_INCLUDE_DIRECTORIES + $) + diff --git a/language_bindings/python/CMakeLists.txt b/language_bindings/python/CMakeLists.txt index 66c879a..e781563 100644 --- a/language_bindings/python/CMakeLists.txt +++ b/language_bindings/python/CMakeLists.txt @@ -1,103 +1,99 @@ #============================================================================== # file CMakeLists.txt # # @author Till Junge # # @date 08 Jan 2018 # # @brief configuration for python binding using pybind11 # # @section LICENSE # # Copyright © 2018 Till Junge # # µSpectre is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation, either version 3, or (at # your option) any later version. # # µSpectre is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with µSpectre; see the file COPYING. If not, write to the # Free Software Foundation, Inc., 59 Temple Place - Suite 330, # Boston, MA 02111-1307, USA. # # Additional permission under GNU GPL version 3 section 7 # # If you modify this Program, or any covered work, by linking or combining it # with proprietary FFT implementations or numerical libraries, containing parts # covered by the terms of those libraries' licenses, the licensors of this # Program grant you additional permission to convey the resulting work. # ============================================================================= # FIXME! The user should have a choice to configure this path. execute_process(COMMAND "${PYTHON_EXECUTABLE}" "-m" "site" "--user-site" RESULT_VARIABLE _PYTHON_SUCCESS OUTPUT_VARIABLE PYTHON_USER_SITE ERROR_VARIABLE _PYTHON_ERROR_VALUE) if(NOT _PYTHON_SUCCESS MATCHES 0) message(FATAL_ERROR "Python config failure:\n${_PYTHON_ERROR_VALUE}") endif() string(REGEX REPLACE "\n" "" PYTHON_USER_SITE ${PYTHON_USER_SITE}) set (PY_BINDING_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/bind_py_module.cc ${CMAKE_CURRENT_SOURCE_DIR}/bind_py_common.cc ${CMAKE_CURRENT_SOURCE_DIR}/bind_py_cell.cc ${CMAKE_CURRENT_SOURCE_DIR}/bind_py_material.cc ${CMAKE_CURRENT_SOURCE_DIR}/bind_py_material_orthotropic.cc ${CMAKE_CURRENT_SOURCE_DIR}/bind_py_material_anisotropic.cc ${CMAKE_CURRENT_SOURCE_DIR}/bind_py_material_linear_elastic1.cc ${CMAKE_CURRENT_SOURCE_DIR}/bind_py_material_linear_elastic2.cc ${CMAKE_CURRENT_SOURCE_DIR}/bind_py_material_linear_elastic3.cc ${CMAKE_CURRENT_SOURCE_DIR}/bind_py_material_linear_elastic4.cc ${CMAKE_CURRENT_SOURCE_DIR}/bind_py_material_hyper_elasto_plastic1.cc ${CMAKE_CURRENT_SOURCE_DIR}/bind_py_material_linear_elastic_generic.cc ${CMAKE_CURRENT_SOURCE_DIR}/bind_py_solvers.cc ${CMAKE_CURRENT_SOURCE_DIR}/bind_py_fftengine.cc ${CMAKE_CURRENT_SOURCE_DIR}/bind_py_projections.cc ${CMAKE_CURRENT_SOURCE_DIR}/bind_py_field_collection.cc ) if (${USE_FFTWMPI}) add_definitions(-DWITH_FFTWMPI) endif(${USE_FFTWMPI}) if (${USE_PFFT}) add_definitions(-DWITH_PFFT) endif(${USE_PFFT}) find_package(PythonLibsNew ${MUSPECTRE_PYTHON_MAJOR_VERSION} MODULE REQUIRED) # On OS X, add -Wno-deprecated-declarations IF(${CMAKE_SYSTEM_NAME} MATCHES "Darwin") add_compile_options(-Wno-deprecated-declarations) ENDIF(${CMAKE_SYSTEM_NAME} MATCHES "Darwin") pybind11_add_module(pyMuSpectreLib ${PY_BINDING_SRCS}) target_link_libraries(pyMuSpectreLib PRIVATE muSpectre) # Want to rename the output, so that the python module is called muSpectre set_target_properties(pyMuSpectreLib PROPERTIES OUTPUT_NAME _muSpectre) target_include_directories(pyMuSpectreLib PUBLIC ${PYTHON_INCLUDE_DIRS}) -<<<<<<< HEAD -add_custom_target(pyMuSpectre ALL SOURCES muSpectre/__init__.py muSpectre/fft.py) -======= add_custom_target(pyMuSpectre ALL SOURCES muSpectre/__init__.py muSpectre/fft.py) ->>>>>>> 6838d6519bc78fbb9d34b0cee844900d257e19fb add_custom_command(TARGET pyMuSpectre POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_SOURCE_DIR}/language_bindings/python/muSpectre $/muSpectre) install(TARGETS pyMuSpectreLib LIBRARY DESTINATION ${PYTHON_USER_SITE}) install(FILES muSpectre/__init__.py muSpectre/fft.py DESTINATION ${PYTHON_USER_SITE}/muSpectre) diff --git a/language_bindings/python/bind_py_cell.cc b/language_bindings/python/bind_py_cell.cc index d428675..0b050e6 100644 --- a/language_bindings/python/bind_py_cell.cc +++ b/language_bindings/python/bind_py_cell.cc @@ -1,307 +1,307 @@ /** * @file bind_py_cell.cc * * @author Till Junge * * @date 09 Jan 2018 * * @brief Python bindings for the cell factory function * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#include "common/common.hh" -#include "common/ccoord_operations.hh" +#include "common/muSpectre_common.hh" #include "cell/cell_factory.hh" #include "cell/cell_split_factory.hh" #include "cell/cell_base.hh" #include "cell/cell_split.hh" +#include #ifdef WITH_FFTWMPI -#include "fft/fftwmpi_engine.hh" +#include #endif #ifdef WITH_PFFT -#include "fft/pfft_engine.hh" +#include #endif #include #include #include -#include "pybind11/eigen.h" +#include #include #include using muSpectre::Ccoord_t; using muSpectre::Dim_t; using muSpectre::Formulation; using muSpectre::Rcoord_t; using pybind11::literals::operator""_a; namespace py = pybind11; /** * cell factory for specific FFT engine */ #ifdef WITH_MPI template void add_parallel_cell_factory_helper(py::module & mod, const char * name) { using Ccoord = Ccoord_t; using Rcoord = Rcoord_t; mod.def(name, [](Ccoord res, Rcoord lens, Formulation form, size_t comm) { - return make_parallel_cell, FFTEngine>( + return muSpectre::make_parallel_cell< + dim, dim, muSpectre::CellBase, FFTEngine>( std::move(res), std::move(lens), std::move(form), - std::move(Communicator(MPI_Comm(comm)))); + std::move(muFFT::Communicator(MPI_Comm(comm)))); }, - "resolutions"_a, "lengths"_a = CcoordOps::get_cube(1.), + "resolutions"_a, "lengths"_a = muGrid::CcoordOps::get_cube(1.), "formulation"_a = Formulation::finite_strain, "communicator"_a = size_t(MPI_COMM_SELF)); } #endif /** * the cell factory is only bound for default template parameters */ template void add_cell_factory_helper(py::module & mod) { using Ccoord = Ccoord_t; using Rcoord = Rcoord_t; mod.def("CellFactory", [](Ccoord res, Rcoord lens, Formulation form) { return muSpectre::make_cell_base_ptr_cell_base< dim, dim, muSpectre::CellBase>( std::move(res), std::move(lens), std::move(form)); }, "resolutions"_a, "lengths"_a = muSpectre::CcoordOps::get_cube(1.), "formulation"_a = Formulation::finite_strain); mod.def("CellFactorySplit", [](Ccoord res, Rcoord lens, Formulation form) { return muSpectre::make_cell_base_ptr_cell_split< dim, dim, muSpectre::CellBase>( std::move(res), std::move(lens), std::move(form)); }, - "resolutions"_a, - "lengths"_a = muSpectre::CcoordOps::get_cube(1.), + "resolutions"_a, "lengths"_a = muGrid::CcoordOps::get_cube(1.), "formulation"_a = Formulation::finite_strain); #ifdef WITH_FFTWMPI - add_parallel_cell_factory_helper>( + add_parallel_cell_factory_helper>( mod, "FFTWMPICellFactory"); #endif #ifdef WITH_PFFT - add_parallel_cell_factory_helper>(mod, - "PFFTCellFactory"); + add_parallel_cell_factory_helper>( + mod, "PFFTCellFactory"); #endif } void add_cell_factory(py::module & mod) { - add_cell_factory_helper(mod); - add_cell_factory_helper(mod); + add_cell_factory_helper(mod); + add_cell_factory_helper(mod); } /** * CellBase for which the material and spatial dimension are identical */ template void add_cell_base_helper(py::module & mod) { std::stringstream name_stream{}; name_stream << "CellBase" << dim << 'd'; const std::string name = name_stream.str(); using sys_t = muSpectre::CellBase; py::class_>(mod, name.c_str()) .def("__len__", &sys_t::size) .def("__iter__", [](sys_t & s) { return py::make_iterator(s.begin(), s.end()); }) .def("initialise", &sys_t::initialise, - "flags"_a = muSpectre::FFT_PlanFlags::estimate) + "flags"_a = muFFT::FFT_PlanFlags::estimate) .def( "directional_stiffness", [](sys_t & cell, py::EigenDRef & v) { if ((size_t(v.cols()) != cell.size() || size_t(v.rows()) != dim * dim)) { std::stringstream err{}; err << "need array of shape (" << dim * dim << ", " << cell.size() << ") but got (" << v.rows() << ", " << v.cols() << ")."; throw std::runtime_error(err.str()); } if (!cell.is_initialised()) { cell.initialise(); } const std::string out_name{"temp output for directional stiffness"}; const std::string in_name{"temp input for directional stiffness"}; constexpr bool create_tangent{true}; auto & K = cell.get_tangent(create_tangent); auto & input = cell.get_managed_T2_field(in_name); auto & output = cell.get_managed_T2_field(out_name); input.eigen() = v; cell.directional_stiffness(K, input, output); return output.eigen(); }, "δF"_a) .def("project", [](sys_t & cell, py::EigenDRef & v) { if ((size_t(v.cols()) != cell.size() || size_t(v.rows()) != dim * dim)) { std::stringstream err{}; err << "need array of shape (" << dim * dim << ", " << cell.size() << ") but got (" << v.rows() << ", " << v.cols() << ")."; throw std::runtime_error(err.str()); } if (!cell.is_initialised()) { cell.initialise(); } const std::string in_name{"temp input for projection"}; auto & input = cell.get_managed_T2_field(in_name); input.eigen() = v; cell.project(input); return input.eigen(); }, "field"_a) .def("get_strain", [](sys_t & s) { return s.get_strain().eigen(); }, py::return_value_policy::reference_internal) .def("get_stress", [](sys_t & s) { return Eigen::ArrayXXd(s.get_stress().eigen()); }) .def_property_readonly("size", &sys_t::size) .def("evaluate_stress_tangent", [](sys_t & cell, py::EigenDRef & v) { if ((size_t(v.cols()) != cell.size() || size_t(v.rows()) != dim * dim)) { std::stringstream err{}; err << "need array of shape (" << dim * dim << ", " << cell.size() << ") but got (" << v.rows() << ", " << v.cols() << ")."; throw std::runtime_error(err.str()); } auto & strain{cell.get_strain()}; strain.eigen() = v; auto stress_tgt{cell.evaluate_stress_tangent(strain)}; return std::tuple( std::get<0>(stress_tgt).eigen(), std::get<1>(stress_tgt).eigen()); }, "strain"_a) .def("evaluate_stress", [](sys_t & cell, py::EigenDRef & v) { if ((size_t(v.cols()) != cell.size() || size_t(v.rows()) != dim * dim)) { std::stringstream err{}; err << "need array of shape (" << dim * dim << ", " << cell.size() << ") but got (" << v.rows() << ", " << v.cols() << ")."; throw std::runtime_error(err.str()); } auto & strain{cell.get_strain()}; strain.eigen() = v; return cell.evaluate_stress(); }, "strain"_a, py::return_value_policy::reference_internal) .def("get_projection", &sys_t::get_projection) .def("get_subdomain_resolutions", &sys_t::get_subdomain_resolutions) .def("get_subdomain_locations", &sys_t::get_subdomain_locations) .def("get_domain_resolutions", &sys_t::get_domain_resolutions) .def("get_domain_lengths", &sys_t::get_domain_resolutions) .def("set_uniform_strain", [](sys_t & cell, py::EigenDRef & v) -> void { cell.set_uniform_strain(v); }, "strain"_a) .def("save_history_variables", &sys_t::save_history_variables); } template void add_cell_split_helper(py::module & mod) { std::stringstream name_stream{}; name_stream << "CellSplit" << dim << 'd'; const auto name{name_stream.str()}; using sys_split_t = muSpectre::CellSplit; using sys_t = muSpectre::CellBase; using Mat_t = muSpectre::MaterialBase; py::class_>(mod, name.c_str()) .def("make_precipitate", [](sys_split_t & cell, Mat_t & mat, std::vector> precipitate_vertices) { cell.make_automatic_precipitate(precipitate_vertices, mat); }, "material"_a, "vertices"_a) .def("complete_material_assignment", [](sys_split_t & cell, Mat_t & mat) { cell.complete_material_assignment(mat); }, "material"_a); } void add_cell_base(py::module & mod) { py::class_>(mod, "Cell") .def("get_globalised_internal_real_array", &muSpectre::Cell::get_globalised_internal_real_array, "unique_name"_a, "Convenience function to copy local (internal) fields of " "materials into a global field. At least one of the materials in " "the cell needs to contain an internal field named " "`unique_name`. If multiple materials contain such a field, they " "all need to be of same scalar type and same number of " "components. This does not work for split pixel cells or " "laminate pixel cells, as they can have multiple entries for the " "same pixel. Pixels for which no field named `unique_name` " "exists get an array of zeros." "\n" "Parameters:\n" "unique_name: fieldname to fill the global field with. At " "least one material must have such a field, or an " "Exception is raised.") .def("get_globalised_current_real_array", &muSpectre::Cell::get_globalised_current_real_array, "unique_name"_a) .def("get_globalised_old_real_array", &muSpectre::Cell::get_globalised_old_real_array, "unique_name"_a, "nb_steps_ago"_a = 1) .def("get_managed_real_array", &muSpectre::Cell::get_managed_real_array, "unique_name"_a, "nb_components"_a, "returns a field or nb_components real numbers per pixel"); add_cell_base_helper(mod); add_cell_base_helper(mod); } void add_cell_split(py::module & mod) { add_cell_split_helper(mod); add_cell_split_helper(mod); } void add_cell(py::module & mod) { add_cell_factory(mod); auto cell{mod.def_submodule("cell")}; cell.doc() = "bindings for cells and cell factories"; cell.def("scale_by_2", [](py::EigenDRef & v) { v *= 2; }); add_cell_base(cell); add_cell_split(cell); } diff --git a/language_bindings/python/bind_py_common.cc b/language_bindings/python/bind_py_common.cc index 17f85de..0681797 100644 --- a/language_bindings/python/bind_py_common.cc +++ b/language_bindings/python/bind_py_common.cc @@ -1,184 +1,182 @@ /** * @file bind_py_common.cc * * @author Till Junge * * @date 08 Jan 2018 * * @brief Python bindings for the common part of µSpectre * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#include "common/common.hh" -#include "common/ccoord_operations.hh" +#include "common/muSpectre_common.hh" +#include #include #include #include using muSpectre::Dim_t; using muSpectre::Real; using muSpectre::StressMeasure; using muSpectre::StrainMeasure; using muSpectre::Formulation; using pybind11::literals::operator""_a; namespace py = pybind11; template void add_get_cube_helper(py::module & mod) { std::stringstream name{}; name << "get_" << dim << "d_cube"; - mod.def(name.str().c_str(), &muSpectre::CcoordOps::get_cube, "size"_a, + mod.def(name.str().c_str(), &muGrid::CcoordOps::get_cube, "size"_a, "return a Ccoord with the value 'size' repeated in each dimension"); } template void add_get_hermitian_helper(py::module & mod) { - mod.def("get_hermitian_sizes", - &muSpectre::CcoordOps::get_hermitian_sizes, "full_sizes"_a, + mod.def("get_hermitian_sizes", &muGrid::CcoordOps::get_hermitian_sizes, + "full_sizes"_a, "return the hermitian sizes corresponding to the true sizes"); } template void add_get_ccoord_helper(py::module & mod) { - using Ccoord = muSpectre::Ccoord_t; + using Ccoord = muGrid::Ccoord_t; mod.def( "get_domain_ccoord", [](Ccoord resolutions, Dim_t index) { - return muSpectre::CcoordOps::get_ccoord(resolutions, Ccoord{}, - index); + return muGrid::CcoordOps::get_ccoord(resolutions, Ccoord{}, index); }, "resolutions"_a, "i"_a, "return the cell coordinate corresponding to the i'th cell in a grid of " "shape resolutions"); } void add_get_cube(py::module & mod) { add_get_cube_helper(mod); add_get_cube_helper(mod); add_get_cube_helper(mod); add_get_cube_helper(mod); add_get_hermitian_helper(mod); add_get_hermitian_helper(mod); add_get_ccoord_helper(mod); add_get_ccoord_helper(mod); } template void add_get_index_helper(py::module & mod) { - using Ccoord = muSpectre::Ccoord_t; + using Ccoord = muGrid::Ccoord_t; mod.def("get_domain_index", [](Ccoord sizes, Ccoord ccoord) { - return muSpectre::CcoordOps::get_index(sizes, Ccoord{}, - ccoord); + return muGrid::CcoordOps::get_index(sizes, Ccoord{}, ccoord); }, "sizes"_a, "ccoord"_a, "return the linear index corresponding to grid point 'ccoord' in a " "grid of size 'sizes'"); } void add_get_index(py::module & mod) { add_get_index_helper(mod); add_get_index_helper(mod); } template void add_Pixels_helper(py::module & mod) { std::stringstream name{}; name << "Pixels" << dim << "d"; - using Ccoord = muSpectre::Ccoord_t; - py::class_> Pixels(mod, name.str().c_str()); + using Ccoord = muGrid::Ccoord_t; + py::class_> Pixels(mod, name.str().c_str()); Pixels.def(py::init()); } void add_Pixels(py::module & mod) { - add_Pixels_helper(mod); - add_Pixels_helper(mod); + add_Pixels_helper(mod); + add_Pixels_helper(mod); } void add_common(py::module & mod) { py::enum_(mod, "Formulation") .value("finite_strain", Formulation::finite_strain) // "µSpectre handles a problem in terms of tranformation gradient F and" // " first Piola-Kirchhoff stress P") .value("small_strain", Formulation::small_strain); // "µSpectre handles a problem in terms of the infinitesimal strain " // "tensor ε and Cauchy stress σ"); py::enum_(mod, "SplitCell") // infroms of the µSpctre of the kind of cell split or not_split .value("laminate", muSpectre::SplitCell::laminate) .value("split", muSpectre::SplitCell::simple) .value("non_split", muSpectre::SplitCell::no); py::enum_(mod, "StressMeasure") .value("Cauchy", StressMeasure::Cauchy) .value("PK1", StressMeasure::PK1) .value("PK2", StressMeasure::PK2) .value("Kirchhoff", StressMeasure::Kirchhoff) .value("Biot", StressMeasure::Biot) .value("Mandel", StressMeasure::Mandel) .value("no_stress_", StressMeasure::no_stress_); py::enum_(mod, "StrainMeasure") .value("Gradient", StrainMeasure::Gradient) .value("Infinitesimal", StrainMeasure::Infinitesimal) .value("GreenLagrange", StrainMeasure::GreenLagrange) .value("Biot", StrainMeasure::Biot) .value("Log", StrainMeasure::Log) .value("Almansi", StrainMeasure::Almansi) .value("RCauchyGreen", StrainMeasure::RCauchyGreen) .value("LCauchyGreen", StrainMeasure::LCauchyGreen) .value("no_strain_", StrainMeasure::no_strain_); - py::enum_(mod, "FFT_PlanFlags") - .value("estimate", muSpectre::FFT_PlanFlags::estimate) - .value("measure", muSpectre::FFT_PlanFlags::measure) - .value("patient", muSpectre::FFT_PlanFlags::patient); + py::enum_(mod, "FFT_PlanFlags") + .value("estimate", muFFT::FFT_PlanFlags::estimate) + .value("measure", muFFT::FFT_PlanFlags::measure) + .value("patient", muFFT::FFT_PlanFlags::patient); py::enum_( mod, "FiniteDiff", "Distinguishes between different options of numerical differentiation;\n " " 1) 'forward' finite differences: ∂f/∂x ≈ (f(x+Δx) - f(x))/Δx\n 2) " "'backward' finite differences: ∂f/∂x ≈ (f(x) - f(x-Δx))/Δx\n 3) " "'centred' finite differences: ∂f/∂x ≈ (f(x+Δx) - f(x-Δx))/2Δx") .value("forward", muSpectre::FiniteDiff::forward) .value("backward", muSpectre::FiniteDiff::backward) .value("centred", muSpectre::FiniteDiff::centred); mod.def("banner", &muSpectre::banner, "name"_a, "year"_a, "copyright_holder"_a); add_get_cube(mod); add_Pixels(mod); add_get_index(mod); } diff --git a/language_bindings/python/bind_py_fftengine.cc b/language_bindings/python/bind_py_fftengine.cc index 56b1217..21b7508 100644 --- a/language_bindings/python/bind_py_fftengine.cc +++ b/language_bindings/python/bind_py_fftengine.cc @@ -1,122 +1,127 @@ /** * @file bind_py_fftengine.cc * * @author Till Junge * * @date 17 Jan 2018 * * @brief Python bindings for the FFT engines * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#include "fft/fftw_engine.hh" +#include "bind_py_declarations.hh" + +#include #ifdef WITH_FFTWMPI -#include "fft/fftwmpi_engine.hh" +#include #endif #ifdef WITH_PFFT -#include "fft/pfft_engine.hh" +#include #endif -#include "bind_py_declarations.hh" #include #include #include -using muSpectre::Ccoord_t; -using muSpectre::Complex; -using muSpectre::Dim_t; +using muGrid::Ccoord_t; +using muGrid::Complex; +using muGrid::Dim_t; using pybind11::literals::operator""_a; namespace py = pybind11; template void add_engine_helper(py::module & mod, std::string name) { using Ccoord = Ccoord_t; using ArrayXXc = Eigen::Array; py::class_(mod, name.c_str()) #ifdef WITH_MPI .def(py::init([](Ccoord res, Dim_t nb_components, size_t comm) { return new Engine(res, nb_components, - std::move(Communicator(MPI_Comm(comm)))); + std::move(muFFT::Communicator(MPI_Comm(comm)))); }), "resolutions"_a, "nb_components"_a, "communicator"_a = size_t(MPI_COMM_SELF)) #else .def(py::init()) #endif .def("fft", [](Engine & eng, py::EigenDRef v) { using Coll_t = typename Engine::GFieldCollection_t; using Field_t = typename Engine::Field_t; Coll_t coll{}; coll.initialise(eng.get_subdomain_resolutions(), eng.get_subdomain_locations()); - Field_t & temp{muSpectre::make_field( + Field_t & temp{muGrid::make_field( "temp_field", coll, eng.get_nb_components())}; temp.eigen() = v; return ArrayXXc{eng.fft(temp).eigen()}; }, "array"_a) .def("ifft", [](Engine & eng, py::EigenDRef v) { using Coll_t = typename Engine::GFieldCollection_t; using Field_t = typename Engine::Field_t; Coll_t coll{}; coll.initialise(eng.get_subdomain_resolutions(), eng.get_subdomain_locations()); - Field_t & temp{muSpectre::make_field( + Field_t & temp{muGrid::make_field( "temp_field", coll, eng.get_nb_components())}; eng.get_work_space().eigen() = v; eng.ifft(temp); return Eigen::ArrayXXd{temp.eigen()}; }, "array"_a) .def("initialise", &Engine::initialise, - "flags"_a = muSpectre::FFT_PlanFlags::estimate) + "flags"_a = muFFT::FFT_PlanFlags::estimate) .def("normalisation", &Engine::normalisation) .def("get_subdomain_resolutions", &Engine::get_subdomain_resolutions) .def("get_subdomain_locations", &Engine::get_subdomain_locations) .def("get_fourier_resolutions", &Engine::get_fourier_resolutions) .def("get_fourier_locations", &Engine::get_fourier_locations) .def("get_domain_resolutions", &Engine::get_domain_resolutions); } void add_fft_engines(py::module & mod) { auto fft{mod.def_submodule("fft")}; fft.doc() = "bindings for µSpectre's fft engines"; - add_engine_helper, muSpectre::twoD>( - fft, "FFTW_2d"); - add_engine_helper, - muSpectre::threeD>(fft, "FFTW_3d"); + add_engine_helper, muGrid::twoD>(fft, + "FFTW_2d"); + add_engine_helper, muGrid::threeD>( + fft, "FFTW_3d"); #ifdef WITH_FFTWMPI - add_engine_helper, twoD>(fft, "FFTWMPI_2d"); - add_engine_helper, threeD>(fft, "FFTWMPI_3d"); + add_engine_helper, muGrid::twoD>( + fft, "FFTWMPI_2d"); + add_engine_helper, muGrid::threeD>( + fft, "FFTWMPI_3d"); #endif #ifdef WITH_PFFT - add_engine_helper, twoD>(fft, "PFFT_2d"); - add_engine_helper, threeD>(fft, "PFFT_3d"); + add_engine_helper, muGrid::twoD>(fft, + "PFFT_2d"); + add_engine_helper, muGrid::threeD>( + fft, "PFFT_3d"); #endif add_projections(fft); } diff --git a/language_bindings/python/bind_py_field_collection.cc b/language_bindings/python/bind_py_field_collection.cc index 7d0c04d..3a5b81e 100644 --- a/language_bindings/python/bind_py_field_collection.cc +++ b/language_bindings/python/bind_py_field_collection.cc @@ -1,276 +1,276 @@ /** * file bind_py_field_collection.cc * * @author Till Junge * * @date 05 Jul 2018 * * @brief Python bindings for µSpectre field collections * * @section LICENSE * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#include "common/common.hh" -#include "common/field.hh" -#include "common/field_collection.hh" +#include "common/muSpectre_common.hh" +#include +#include #include #include #include #include #include using muSpectre::Complex; using muSpectre::Dim_t; using muSpectre::Int; using muSpectre::Real; using muSpectre::Uint; using pybind11::literals::operator""_a; namespace py = pybind11; template void add_field_collection(py::module & mod) { std::stringstream name_stream{}; name_stream << "_" << (FieldCollectionDerived::Global ? "Global" : "Local") << "FieldCollection_" << Dim << 'd'; const auto name{name_stream.str()}; - using FC_t = muSpectre::FieldCollectionBase; + using FC_t = muGrid::FieldCollectionBase; py::class_(mod, name.c_str()) .def("get_real_field", [](FC_t & field_collection, std::string unique_name) -> typename FC_t::template TypedField_t & { return field_collection.template get_typed_field( unique_name); }, "unique_name"_a, py::return_value_policy::reference_internal) .def("get_int_field", [](FC_t & field_collection, std::string unique_name) -> typename FC_t::template TypedField_t & { return field_collection.template get_typed_field(unique_name); }, "unique_name"_a, py::return_value_policy::reference_internal) .def("get_uint_field", [](FC_t & field_collection, std::string unique_name) -> typename FC_t::template TypedField_t & { return field_collection.template get_typed_field( unique_name); }, "unique_name"_a, py::return_value_policy::reference_internal) .def("get_complex_field", [](FC_t & field_collection, std::string unique_name) -> typename FC_t::template TypedField_t & { return field_collection.template get_typed_field( unique_name); }, "unique_name"_a, py::return_value_policy::reference_internal) .def("get_real_statefield", [](FC_t & field_collection, std::string unique_name) -> typename FC_t::template TypedStateField_t & { return field_collection.template get_typed_statefield( unique_name); }, "unique_name"_a, py::return_value_policy::reference_internal) .def("get_int_statefield", [](FC_t & field_collection, std::string unique_name) -> typename FC_t::template TypedStateField_t & { return field_collection.template get_typed_statefield( unique_name); }, "unique_name"_a, py::return_value_policy::reference_internal) .def("get_uint_statefield", [](FC_t & field_collection, std::string unique_name) -> typename FC_t::template TypedStateField_t & { return field_collection.template get_typed_statefield( unique_name); }, "unique_name"_a, py::return_value_policy::reference_internal) .def("get_complex_statefield", [](FC_t & field_collection, std::string unique_name) -> typename FC_t::template TypedStateField_t & { return field_collection.template get_typed_statefield( unique_name); }, "unique_name"_a, py::return_value_policy::reference_internal) .def_property_readonly( "field_names", &FC_t::get_field_names, "returns the names of all fields in this collection") .def_property_readonly("statefield_names", &FC_t::get_statefield_names, "returns the names of all state fields in this " "collection"); } namespace internal_fill { /** * Needed for static switch when adding fillers to fields (static * switch on whether they are global). Default case is for global * fields. */ template struct FillHelper { static void add_fill(PyField & py_field) { py_field.def( "fill_from_local", [](Field & field, const typename Field::LocalField_t & local) { field.fill_from_local(local); }, "local"_a, "Fills the content of a local field into a global field " "(modifies only the pixels that are not present in the " "local field"); } }; /** * Specialisation for local fields */ template struct FillHelper { static void add_fill(PyField & py_field) { py_field.def( "fill_from_global", [](Field & field, const typename Field::GlobalField_t & global) { field.fill_from_global(global); }, "global"_a, "Fills the content of a global field into a local field."); } }; } // namespace internal_fill template void add_field(py::module & mod, std::string dtype_name) { - using Field_t = muSpectre::TypedField; + using Field_t = muGrid::TypedField; std::stringstream name_stream{}; name_stream << (FieldCollection::Global ? "Global" : "Local") << "Field" << dtype_name << "_" << FieldCollection::spatial_dim(); std::string name{name_stream.str()}; using Ref_t = py::EigenDRef>; py::class_ py_field(mod, name.c_str()); py_field .def_property("array", [](Field_t & field) { return field.eigen(); }, [](Field_t & field, Ref_t mat) { field.eigen() = mat; }, "array of stored data") .def_property_readonly( "array", [](const Field_t & field) { return field.eigen(); }, "array of stored data") .def_property("vector", [](Field_t & field) { return field.eigenvec(); }, [](Field_t & field, Ref_t mat) { field.eigen() = mat; }, "flattened array of stored data") .def_property_readonly( "vector", [](const Field_t & field) { return field.eigenvec(); }, "flattened array of stored data"); using FillHelper_t = internal_fill::FillHelper; FillHelper_t::add_fill(py_field); } template void add_field_helper(py::module & mod) { std::stringstream name_stream{}; name_stream << (FieldCollection::Global ? "Global" : "Local") << "Field" << "_" << Dim; std::string name{name_stream.str()}; - using Field_t = muSpectre::internal::FieldBase; + using Field_t = muGrid::internal::FieldBase; py::class_(mod, name.c_str()) .def_property_readonly("name", &Field_t::get_name, "field name") .def_property_readonly("collection", &Field_t::get_collection, "Collection containing this field") .def_property_readonly("nb_components", &Field_t::get_nb_components, "number of scalars stored per pixel in this field") .def_property_readonly("stored_type", [](const Field_t & field) { return field.get_stored_typeid().name(); }, "fundamental type of scalars stored in this field") .def_property_readonly("size", &Field_t::size, "number of pixels in this field") .def("set_zero", &Field_t::set_zero, "Set all components in the field to zero"); add_field(mod, "Real"); add_field(mod, "Int"); } template void add_statefield(py::module & mod, std::string dtype_name) { - using StateField_t = muSpectre::TypedStateField; + using StateField_t = muGrid::TypedStateField; std::stringstream name_stream{}; name_stream << (FieldCollection::Global ? "Global" : "Local") << "StateField" << dtype_name << "_" << FieldCollection::spatial_dim(); std::string name{name_stream.str()}; py::class_(mod, name.c_str()) .def_property_readonly("current_field", &StateField_t::get_current_field, "returns the current field value") .def("get_old_field", &StateField_t::get_old_field, "nb_steps_ago"_a = 1, "returns the value this field held 'nb_steps_ago' steps ago", py::return_value_policy::reference_internal); } template void add_statefield_helper(py::module & mod) { std::stringstream name_stream{}; name_stream << (FieldCollection::Global ? "Global" : "Local") << "StateField" << "_" << Dim; std::string name{name_stream.str()}; - using StateField_t = muSpectre::StateFieldBase; + using StateField_t = muGrid::StateFieldBase; py::class_(mod, name.c_str()) .def_property_readonly("prefix", &StateField_t::get_prefix, "state field prefix") .def_property_readonly("collection", &StateField_t::get_collection, "Collection containing this field") .def_property_readonly("nb_memory", &StateField_t::get_nb_memory, "number of old states stored") .def_property_readonly( "stored_type", [](const StateField_t & field) { return field.get_stored_typeid().name(); }, "fundamental type of scalars stored in this field"); add_statefield(mod, "Real"); add_statefield(mod, "Int"); } template void add_field_collection_helper(py::module & mod) { - add_field_helper>(mod); - add_field_helper>(mod); + add_field_helper>(mod); + add_field_helper>(mod); - add_statefield_helper>(mod); - add_statefield_helper>(mod); + add_statefield_helper>(mod); + add_statefield_helper>(mod); - add_field_collection>(mod); - add_field_collection>(mod); + add_field_collection>(mod); + add_field_collection>(mod); } void add_field_collections(py::module & mod) { - add_field_collection_helper(mod); - add_field_collection_helper(mod); + add_field_collection_helper(mod); + add_field_collection_helper(mod); } diff --git a/language_bindings/python/bind_py_material.cc b/language_bindings/python/bind_py_material.cc index 9ab1b64..465a524 100644 --- a/language_bindings/python/bind_py_material.cc +++ b/language_bindings/python/bind_py_material.cc @@ -1,269 +1,276 @@ /** * @file bind_py_material.cc * * @author Till Junge * * @date 09 Jan 2018 * * @brief python bindings for µSpectre's materials * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#include "common/common.hh" #include "materials/material_anisotropic.hh" #include "materials/material_orthotropic.hh" #include "cell/cell_base.hh" #include "cell/cell_split.hh" +#include "common/muSpectre_common.hh" #include "materials/material_base.hh" #include "materials/material_evaluator.hh" #include #include #include #include #include using muSpectre::Dim_t; using muSpectre::Real; using pybind11::literals::operator""_a; namespace py = pybind11; /* ---------------------------------------------------------------------- */ template void add_material_linear_elastic_generic1_helper(py::module & mod); /* ---------------------------------------------------------------------- */ template void add_material_linear_elastic_generic2_helper(py::module & mod); template void add_material_base_helper(py::module & mod) { std::stringstream name_stream{}; name_stream << "MaterialBase" << dim << 'd'; const auto name{name_stream.str()}; using Mat_t = muSpectre::MaterialBase; py::class_(mod, name.c_str()); } /** * python binding for the optionally objective form of Hooke's law */ template void add_material_linear_elastic1_helper(py::module & mod); template void add_material_linear_elastic2_helper(py::module & mod); template void add_material_linear_elastic3_helper(py::module & mod); template void add_material_linear_elastic4_helper(py::module & mod); template void add_material_hyper_elasto_plastic1_helper(py::module & mod); template void add_material_anisotropic_helper(py::module & mod); template void add_material_orthotropic_helper(py::module & mod); /* ---------------------------------------------------------------------- */ template class PyMaterialBase : public muSpectre::MaterialBase { public: /* Inherit the constructors */ using Parent = muSpectre::MaterialBase; using Parent::Parent; /* Trampoline (need one for each virtual function) */ void save_history_variables() override { PYBIND11_OVERLOAD_PURE(void, // Return type Parent, // Parent class save_history_variables); // Name of function in C++ // (must match Python name) } /* Trampoline (need one for each virtual function) */ void initialise() override { PYBIND11_OVERLOAD_PURE( void, // Return type Parent, // Parent class initialise); // Name of function in C++ (must match Python name) } void compute_stresses(const typename Parent::StrainField_t & F, typename Parent::StressField_t & P, muSpectre::Formulation form, muSpectre::SplitCell is_cell_split) override { PYBIND11_OVERLOAD_PURE( void, // Return type Parent, // Parent class compute_stresses, // Name of function in C++ (must match Python name) F, P, form, is_cell_split); } void compute_stresses_tangent(const typename Parent::StrainField_t & F, typename Parent::StressField_t & P, typename Parent::TangentField_t & K, muSpectre::Formulation form, muSpectre::SplitCell is_cell_split) override { PYBIND11_OVERLOAD_PURE( void, /* Return type */ Parent, /* Parent class */ compute_stresses, /* Name of function in C++ (must match Python name) */ F, P, K, form, is_cell_split); } }; template void add_material_evaluator(py::module & mod) { std::stringstream name_stream{}; name_stream << "MaterialEvaluator_" << Dim << "d"; std::string name{name_stream.str()}; using MatEval_t = muSpectre::MaterialEvaluator; py::class_(mod, name.c_str()) .def(py::init>>()) .def("save_history_variables", &MatEval_t::save_history_variables, "for materials with state variables") .def("evaluate_stress", [](MatEval_t & mateval, py::EigenDRef & grad, muSpectre::Formulation form) { if ((grad.cols() != Dim) or (grad.rows() != Dim)) { std::stringstream err{}; err << "need matrix of shape (" << Dim << "×" << Dim << ") but got (" << grad.rows() << "×" << grad.cols() << ")."; throw std::runtime_error(err.str()); } return mateval.evaluate_stress(grad, form); }, "strain"_a, "formulation"_a, "Evaluates stress for a given strain and formulation " "(Piola-Kirchhoff 1 stress as a function of the placement gradient " "P = P(F) for formulation=Formulation.finite_strain and Cauchy " "stress as a function of the infinitesimal strain tensor σ = σ(ε) " "for formulation=Formulation.small_strain)") .def("evaluate_stress_tangent", [](MatEval_t & mateval, py::EigenDRef & grad, muSpectre::Formulation form) { if ((grad.cols() != Dim) or (grad.rows() != Dim)) { std::stringstream err{}; err << "need matrix of shape (" << Dim << "×" << Dim << ") but got (" << grad.rows() << "×" << grad.cols() << ")."; throw std::runtime_error(err.str()); } return mateval.evaluate_stress_tangent(grad, form); }, "strain"_a, "formulation"_a, "Evaluates stress and tangent moduli for a given strain and " "formulation (Piola-Kirchhoff 1 stress as a function of the " "placement gradient P = P(F) for " "formulation=Formulation.finite_strain and Cauchy stress as a " "function of the infinitesimal strain tensor σ = σ(ε) for " "formulation=Formulation.small_strain). The tangent moduli are K = " "∂P/∂F for formulation=Formulation.finite_strain and C = ∂σ/∂ε for " "formulation=Formulation.small_strain.") .def("estimate_tangent", [](MatEval_t & evaluator, py::EigenDRef & grad, muSpectre::Formulation form, const Real step, const muSpectre::FiniteDiff diff_type) { if ((grad.cols() != Dim) or (grad.rows() != Dim)) { std::stringstream err{}; err << "need matrix of shape (" << Dim << "×" << Dim << ") but got (" << grad.rows() << "×" << grad.cols() << ")."; throw std::runtime_error(err.str()); } return evaluator.estimate_tangent(grad, form, step, diff_type); }, "strain"_a, "formulation"_a, "Delta_x"_a, "difference_type"_a = muSpectre::FiniteDiff::centred, "Numerical estimate of the tangent modulus using finite " "differences. The finite difference scheme as well as the finite " "step size can be chosen. If there are no special circumstances, " "the default scheme of centred finite differences yields the most " "accurate results at an increased computational cost."); } template void add_material_helper(py::module & mod) { std::stringstream name_stream{}; name_stream << "MaterialBase_" << Dim << "d"; std::string name{name_stream.str()}; using Material = muSpectre::MaterialBase; using MaterialTrampoline = PyMaterialBase; - using FC_t = muSpectre::LocalFieldCollection; - using FCBase_t = muSpectre::FieldCollectionBase; + using FC_t = muGrid::LocalFieldCollection; + using FCBase_t = muGrid::FieldCollectionBase; py::class_>(mod, name.c_str()) .def(py::init()) .def("save_history_variables", &Material::save_history_variables) .def("list_fields", &Material::list_fields) .def("get_real_field", &Material::get_real_field, "field_name"_a, py::return_value_policy::reference_internal) .def("size", &Material::size) + .def("add_pixel", - [](Material & mat, muSpectre::Ccoord_t pix) { + [](Material & mat, muGrid::Ccoord_t pix) { mat.add_pixel(pix); }, "pixel"_a) .def("add_pixel_split", - [](Material & mat, muSpectre::Ccoord_t pix, + [](Material & mat, muGird::Ccoord_t pix, muSpectre::Real ratio) { mat.add_pixel_split(pix, ratio); }, "pixel"_a, "ratio"_a) .def_static( "make_C_Voigt_from_col", [](Eigen::Matrix & C_col) { return Material::make_C_voigt_from_col(C_col); }, "C_col"_a) + + .def( + "add_pixel", + [](Material & mat, muGrid::Ccoord_t pix) { mat.add_pixel(pix); }, + "pixel"_a) + .def_property_readonly("collection", [](Material & material) -> FCBase_t & { return material.get_collection(); }, "returns the field collection containing internal " "fields of this material"); add_material_linear_elastic1_helper(mod); add_material_linear_elastic2_helper(mod); add_material_linear_elastic3_helper(mod); add_material_linear_elastic4_helper(mod); add_material_hyper_elasto_plastic1_helper(mod); add_material_linear_elastic_generic1_helper(mod); add_material_linear_elastic_generic2_helper(mod); add_material_anisotropic_helper(mod); add_material_orthotropic_helper(mod); add_material_evaluator(mod); } void add_material(py::module & mod) { auto material{mod.def_submodule("material")}; material.doc() = "bindings for constitutive laws"; - add_material_helper(material); - add_material_helper(material); + add_material_helper(material); + add_material_helper(material); } diff --git a/language_bindings/python/bind_py_material_hyper_elasto_plastic1.cc b/language_bindings/python/bind_py_material_hyper_elasto_plastic1.cc index 6f022e0..65685ae 100644 --- a/language_bindings/python/bind_py_material_hyper_elasto_plastic1.cc +++ b/language_bindings/python/bind_py_material_hyper_elasto_plastic1.cc @@ -1,78 +1,78 @@ /** * @file bind_py_material_hyper_elasto_plastic1.cc * * @author Till Junge * * @date 29 Oct 2018 * * @brief python binding for MaterialHyperElastoPlastic1 * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ -#include "common/common.hh" +#include "common/muSpectre_common.hh" #include "materials/stress_transformations_Kirchhoff.hh" #include "materials/material_hyper_elasto_plastic1.hh" #include "cell/cell_base.hh" #include #include #include #include #include using muSpectre::Dim_t; using muSpectre::Real; using pybind11::literals::operator""_a; namespace py = pybind11; /** * python binding for the optionally objective form of Hooke's law * with per-pixel elastic properties */ template void add_material_hyper_elasto_plastic1_helper(py::module & mod) { std::stringstream name_stream{}; name_stream << "MaterialHyperElastoPlastic1_" << Dim << "d"; const auto name{name_stream.str()}; using Mat_t = muSpectre::MaterialHyperElastoPlastic1; using Cell_t = muSpectre::CellBase; py::class_, std::shared_ptr>( mod, name.c_str()) .def_static("make", [](Cell_t & cell, std::string name, Real Young, Real Poisson, Real tau_y0, Real h) -> Mat_t & { return Mat_t::make(cell, name, Young, Poisson, tau_y0, h); }, "cell"_a, "name"_a, "YoungModulus"_a, "PoissonRatio"_a, "τ_y₀"_a, "h"_a, py::return_value_policy::reference, py::keep_alive<1, 0>()) .def_static("make_evaluator", [](Real Young, Real Poisson, Real tau_y0, Real h) { return Mat_t::make_evaluator(Young, Poisson, tau_y0, h); }, "YoungModulus"_a, "PoissonRatio"_a, "τ_y₀"_a, "h"_a); } template void add_material_hyper_elasto_plastic1_helper(py::module &); template void add_material_hyper_elasto_plastic1_helper(py::module &); diff --git a/language_bindings/python/bind_py_material_linear_elastic1.cc b/language_bindings/python/bind_py_material_linear_elastic1.cc index 383fa09..2819d3c 100644 --- a/language_bindings/python/bind_py_material_linear_elastic1.cc +++ b/language_bindings/python/bind_py_material_linear_elastic1.cc @@ -1,73 +1,73 @@ /** * @file bind_py_material_linear_elastic1.cc * * @author Till Junge * * @date 29 Oct 2018 * * @brief python bindings for MaterialLinearElastic1 * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ -#include "common/common.hh" +#include "common/muSpectre_common.hh" #include "materials/material_linear_elastic1.hh" #include "cell/cell_base.hh" #include #include #include #include #include using muSpectre::Dim_t; using muSpectre::Real; using pybind11::literals::operator""_a; namespace py = pybind11; /** * python binding for the optionally objective form of Hooke's law */ template void add_material_linear_elastic1_helper(py::module & mod) { std::stringstream name_stream{}; name_stream << "MaterialLinearElastic1_" << dim << 'd'; const auto name{name_stream.str()}; using Mat_t = muSpectre::MaterialLinearElastic1; using Sys_t = muSpectre::CellBase; py::class_, std::shared_ptr>( mod, name.c_str()) .def_static("make", [](Sys_t & sys, std::string n, Real e, Real p) -> Mat_t & { return Mat_t::make(sys, n, e, p); }, "cell"_a, "name"_a, "Young"_a, "Poisson"_a, py::return_value_policy::reference, py::keep_alive<1, 0>()) .def_static("make_evaluator", [](Real e, Real p) { return Mat_t::make_evaluator(e, p); }, "Young"_a, "Poisson"_a) .def("get_C", [](Mat_t & mat) { return mat.get_C(); }); } template void add_material_linear_elastic1_helper(py::module &); template void add_material_linear_elastic1_helper(py::module &); diff --git a/language_bindings/python/bind_py_material_linear_elastic2.cc b/language_bindings/python/bind_py_material_linear_elastic2.cc index a1fb000..75aabaf 100644 --- a/language_bindings/python/bind_py_material_linear_elastic2.cc +++ b/language_bindings/python/bind_py_material_linear_elastic2.cc @@ -1,83 +1,83 @@ /** * @file bind_py_material_linear_elastic2.cc * * @author Till Junge * * @date 29 Oct 2018 * * @brief python bindings for MaterialLinearElastic2 * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ -#include "common/common.hh" +#include "common/muSpectre_common.hh" #include "materials/material_linear_elastic2.hh" #include "cell/cell_base.hh" #include #include #include #include #include using muSpectre::Dim_t; using muSpectre::Real; namespace py = pybind11; using pybind11::literals::operator""_a; /** * python binding for the optionally objective form of Hooke's law * with a per pixel eigenstrain */ template void add_material_linear_elastic2_helper(py::module & mod) { std::stringstream name_stream{}; name_stream << "MaterialLinearElastic2_" << dim << 'd'; const auto name{name_stream.str()}; using Mat_t = muSpectre::MaterialLinearElastic2; using Sys_t = muSpectre::CellBase; py::class_, std::shared_ptr>( mod, name.c_str()) .def_static("make", [](Sys_t & sys, std::string n, Real e, Real p) -> Mat_t & { return Mat_t::make(sys, n, e, p); }, "cell"_a, "name"_a, "Young"_a, "Poisson"_a, py::return_value_policy::reference, py::keep_alive<1, 0>()) .def("add_pixel", [](Mat_t & mat, muSpectre::Ccoord_t pix, py::EigenDRef & eig) { Eigen::Matrix eig_strain{eig}; mat.add_pixel(pix, eig_strain); }, "pixel"_a, "eigenstrain"_a) .def_static("make_evaluator", [](Real e, Real p) { return Mat_t::make_evaluator(e, p); }, "Young"_a, "Poisson"_a); } template void add_material_linear_elastic2_helper(py::module &); template void add_material_linear_elastic2_helper(py::module &); diff --git a/language_bindings/python/bind_py_material_linear_elastic3.cc b/language_bindings/python/bind_py_material_linear_elastic3.cc index d11346b..f29eb58 100644 --- a/language_bindings/python/bind_py_material_linear_elastic3.cc +++ b/language_bindings/python/bind_py_material_linear_elastic3.cc @@ -1,77 +1,77 @@ /** * @file bind_py_material_linear_elastic3.cc * * @author Till Junge * * @date 29 Oct 2018 * * @brief python bindings for MaterialLinearElastic3 * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ -#include "common/common.hh" +#include "common/muSpectre_common.hh" #include "materials/material_linear_elastic3.hh" #include "cell/cell_base.hh" #include #include #include #include #include using muSpectre::Dim_t; using muSpectre::Real; using pybind11::literals::operator""_a; namespace py = pybind11; /** * python binding for the optionally objective form of Hooke's law * with per-pixel elastic properties */ template void add_material_linear_elastic3_helper(py::module & mod) { std::stringstream name_stream{}; name_stream << "MaterialLinearElastic3_" << dim << 'd'; const auto name{name_stream.str()}; using Mat_t = muSpectre::MaterialLinearElastic3; using Sys_t = muSpectre::CellBase; py::class_, std::shared_ptr>( mod, name.c_str()) .def(py::init(), "name"_a) .def_static("make", [](Sys_t & sys, std::string n) -> Mat_t & { return Mat_t::make(sys, n); }, "cell"_a, "name"_a, py::return_value_policy::reference, py::keep_alive<1, 0>()) .def("add_pixel", [](Mat_t & mat, muSpectre::Ccoord_t pix, Real Young, Real Poisson) { mat.add_pixel(pix, Young, Poisson); }, "pixel"_a, "Young"_a, "Poisson"_a) .def_static("make_evaluator", []() { return Mat_t::make_evaluator(); }); } template void add_material_linear_elastic3_helper(py::module &); template void add_material_linear_elastic3_helper(py::module &); diff --git a/language_bindings/python/bind_py_material_linear_elastic4.cc b/language_bindings/python/bind_py_material_linear_elastic4.cc index 6134460..1167af1 100644 --- a/language_bindings/python/bind_py_material_linear_elastic4.cc +++ b/language_bindings/python/bind_py_material_linear_elastic4.cc @@ -1,77 +1,77 @@ /** * @file bind_py_material_linear_elastic4.cc * * @author Till Junge * * @date 29 Oct 2018 * * @brief python binding for MaterialLinearElastic4 * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ -#include "common/common.hh" +#include "common/muSpectre_common.hh" #include "materials/material_linear_elastic4.hh" #include "cell/cell_base.hh" #include #include #include #include #include using muSpectre::Dim_t; using muSpectre::Real; using pybind11::literals::operator""_a; namespace py = pybind11; /** * python binding for the optionally objective form of Hooke's law * with per-pixel elastic properties */ template void add_material_linear_elastic4_helper(py::module & mod) { std::stringstream name_stream{}; name_stream << "MaterialLinearElastic4_" << dim << 'd'; const auto name{name_stream.str()}; using Mat_t = muSpectre::MaterialLinearElastic4; using Sys_t = muSpectre::CellBase; py::class_, std::shared_ptr>( mod, name.c_str()) .def(py::init(), "name"_a) .def_static("make", [](Sys_t & sys, std::string n) -> Mat_t & { return Mat_t::make(sys, n); }, "cell"_a, "name"_a, py::return_value_policy::reference, py::keep_alive<1, 0>()) .def("add_pixel", [](Mat_t & mat, muSpectre::Ccoord_t pix, Real Young, Real Poisson) { mat.add_pixel(pix, Young, Poisson); }, "pixel"_a, "Young"_a, "Poisson"_a) .def_static("make_evaluator", []() { return Mat_t::make_evaluator(); }); } template void add_material_linear_elastic4_helper(py::module &); template void add_material_linear_elastic4_helper(py::module &); diff --git a/language_bindings/python/bind_py_projections.cc b/language_bindings/python/bind_py_projections.cc index ec82f6b..495c33b 100644 --- a/language_bindings/python/bind_py_projections.cc +++ b/language_bindings/python/bind_py_projections.cc @@ -1,191 +1,189 @@ /** * @file bind_py_projections.cc * * @author Till Junge * * @date 18 Jan 2018 * * @brief Python bindings for the Projection operators * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#include "fft/projection_small_strain.hh" -#include "fft/projection_finite_strain.hh" -#include "fft/projection_finite_strain_fast.hh" +#include "projection/projection_small_strain.hh" +#include "projection/projection_finite_strain.hh" +#include "projection/projection_finite_strain_fast.hh" -#include "fft/fftw_engine.hh" +#include #ifdef WITH_FFTWMPI -#include "fft/fftwmpi_engine.hh" +#include #endif #ifdef WITH_PFFT -#include "fft/pfft_engine.hh" +#include #endif #include #include #include #include #include -using muSpectre::Dim_t; +using muGrid::Dim_t; using muSpectre::ProjectionBase; using pybind11::literals::operator""_a; namespace py = pybind11; /** * "Trampoline" class for handling the pure virtual methods, see * [http://pybind11.readthedocs.io/en/stable/advanced/classes.html#overriding-virtual-functions-in-python] * for details */ template class PyProjectionBase : public ProjectionBase { public: //! base class using Parent = ProjectionBase; //! field type on which projection is applied using Field_t = typename Parent::Field_t; void apply_projection(Field_t & field) override { PYBIND11_OVERLOAD_PURE(void, Parent, apply_projection, field); } Eigen::Map get_operator() override { PYBIND11_OVERLOAD_PURE(Eigen::Map, Parent, get_operator); } }; template void add_proj_helper(py::module & mod, std::string name_start) { - using Ccoord = muSpectre::Ccoord_t; - using Rcoord = muSpectre::Rcoord_t; + using Ccoord = muGrid::Ccoord_t; + using Rcoord = muGrid::Rcoord_t; using Field_t = typename Proj::Field_t; static_assert(DimS == DimM, "currently only for DimS==DimM"); std::stringstream name{}; name << name_start << '_' << DimS << 'd'; py::class_(mod, name.str().c_str()) #ifdef WITH_MPI .def(py::init([](Ccoord res, Rcoord lengths, const std::string & fft, size_t comm) { if (fft == "fftw") { - auto engine = std::make_unique>( + auto engine = std::make_unique>( res, Proj::NbComponents(), - std::move(Communicator(MPI_Comm(comm)))); + std::move(muFFT::Communicator(MPI_Comm(comm)))); return Proj(std::move(engine), lengths); #else .def(py::init([](Ccoord res, Rcoord lengths, const std::string & fft) { if (fft == "fftw") { - auto engine = std::make_unique>( + auto engine = std::make_unique>( res, Proj::NbComponents()); return Proj(std::move(engine), lengths); #endif #ifdef WITH_FFTWMPI } else if (fft == "fftwmpi") { - auto engine = std::make_unique>( + auto engine = std::make_unique>( res, Proj::NbComponents(), - std::move(Communicator(MPI_Comm(comm)))); + std::move(muFFT::Communicator(MPI_Comm(comm)))); return Proj(std::move(engine), lengths); #endif #ifdef WITH_PFFT } else if (fft == "pfft") { - auto engine = std::make_unique>( + auto engine = std::make_unique>( res, Proj::NbComponents(), - std::move(Communicator(MPI_Comm(comm)))); + std::move(muFFT::Communicator(MPI_Comm(comm)))); return Proj(std::move(engine), lengths); #endif } else { throw std::runtime_error("Unknown FFT engine '" + fft + "' specified."); } }), "resolutions"_a, "lengths"_a, #ifdef WITH_MPI "fft"_a = "fftw", "communicator"_a = size_t(MPI_COMM_SELF)) #else "fft"_a = "fftw") #endif .def("initialise", &Proj::initialise, - "flags"_a = muSpectre::FFT_PlanFlags::estimate, + "flags"_a = muFFT::FFT_PlanFlags::estimate, "initialises the fft engine (plan the transform)") .def("apply_projection", [](Proj & proj, py::EigenDRef v) { - typename muSpectre::FFTEngineBase::GFieldCollection_t coll{}; - Eigen::Index subdomain_size = muSpectre::CcoordOps::get_size( - proj.get_subdomain_resolutions()); + typename muFFT::FFTEngineBase::GFieldCollection_t coll{}; + Eigen::Index subdomain_size = + muGrid::CcoordOps::get_size(proj.get_subdomain_resolutions()); if (v.rows() != DimS * DimM || v.cols() != subdomain_size) { throw std::runtime_error("Expected input array of shape (" + std::to_string(DimS * DimM) + ", " + std::to_string(subdomain_size) + "), but input array has shape (" + std::to_string(v.rows()) + ", " + std::to_string(v.cols()) + ")."); } coll.initialise(proj.get_subdomain_resolutions(), proj.get_subdomain_locations()); - Field_t & temp{muSpectre::make_field( + Field_t & temp{muGrid::make_field( "temp_field", coll, proj.get_nb_components())}; temp.eigen() = v; proj.apply_projection(temp); return Eigen::ArrayXXd{temp.eigen()}; }) .def("get_operator", &Proj::get_operator) .def( "get_formulation", &Proj::get_formulation, "return a Formulation enum indicating whether the projection is small" " or finite strain") .def("get_subdomain_resolutions", &Proj::get_subdomain_resolutions) .def("get_subdomain_locations", &Proj::get_subdomain_locations) .def("get_domain_resolutions", &Proj::get_domain_resolutions) .def("get_domain_lengths", &Proj::get_domain_resolutions); } void add_proj_dispatcher(py::module & mod) { + add_proj_helper, + muGrid::twoD>(mod, "ProjectionSmallStrain"); add_proj_helper< - muSpectre::ProjectionSmallStrain, - muSpectre::twoD>(mod, "ProjectionSmallStrain"); - add_proj_helper< - muSpectre::ProjectionSmallStrain, - muSpectre::threeD>(mod, "ProjectionSmallStrain"); + muSpectre::ProjectionSmallStrain, + muGrid::threeD>(mod, "ProjectionSmallStrain"); + add_proj_helper, + muGrid::twoD>(mod, "ProjectionFiniteStrain"); add_proj_helper< - muSpectre::ProjectionFiniteStrain, - muSpectre::twoD>(mod, "ProjectionFiniteStrain"); - add_proj_helper< - muSpectre::ProjectionFiniteStrain, - muSpectre::threeD>(mod, "ProjectionFiniteStrain"); + muSpectre::ProjectionFiniteStrain, + muGrid::threeD>(mod, "ProjectionFiniteStrain"); add_proj_helper< - muSpectre::ProjectionFiniteStrainFast, - muSpectre::twoD>(mod, "ProjectionFiniteStrainFast"); - add_proj_helper, - muSpectre::threeD>(mod, "ProjectionFiniteStrainFast"); + muSpectre::ProjectionFiniteStrainFast, + muGrid::twoD>(mod, "ProjectionFiniteStrainFast"); + add_proj_helper< + muSpectre::ProjectionFiniteStrainFast, + muGrid::threeD>(mod, "ProjectionFiniteStrainFast"); } void add_projections(py::module & mod) { add_proj_dispatcher(mod); } diff --git a/language_bindings/python/bind_py_solvers.cc b/language_bindings/python/bind_py_solvers.cc index 40be085..b37ea5b 100644 --- a/language_bindings/python/bind_py_solvers.cc +++ b/language_bindings/python/bind_py_solvers.cc @@ -1,147 +1,147 @@ /** * @file bind_py_solver.cc * * @author Till Junge * * @date 09 Jan 2018 * * @brief python bindings for the muSpectre solvers * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#include "common/common.hh" +#include "common/muSpectre_common.hh" #include "solver/solvers.hh" #include "solver/solver_cg.hh" #include "solver/solver_eigen.hh" #include #include #include using muSpectre::Dim_t; using muSpectre::OptimizeResult; using muSpectre::Real; using muSpectre::Uint; using pybind11::literals::operator""_a; namespace py = pybind11; /** * Solvers instanciated for cells with equal spatial and material dimension */ template void add_iterative_solver_helper(py::module & mod, std::string name) { py::class_(mod, name.c_str()) .def(py::init(), "cell"_a, "tol"_a, "maxiter"_a, "verbose"_a = false) .def("name", &Solver::get_name); } void add_iterative_solver(py::module & mod) { std::stringstream name{}; name << "SolverBase"; py::class_(mod, name.str().c_str()); add_iterative_solver_helper(mod, "SolverCG"); add_iterative_solver_helper(mod, "SolverCGEigen"); add_iterative_solver_helper(mod, "SolverGMRESEigen"); add_iterative_solver_helper( mod, "SolverBiCGSTABEigen"); add_iterative_solver_helper( mod, "SolverDGMRESEigen"); add_iterative_solver_helper( mod, "SolverMINRESEigen"); } void add_newton_cg_helper(py::module & mod) { const char name[]{"newton_cg"}; using solver = muSpectre::SolverBase; using grad = py::EigenDRef; using grad_vec = muSpectre::LoadSteps_t; mod.def(name, [](muSpectre::Cell & s, const grad & g, solver & so, Real nt, Real eqt, Dim_t verb) -> OptimizeResult { Eigen::MatrixXd tmp{g}; return newton_cg(s, tmp, so, nt, eqt, verb); }, "cell"_a, "ΔF₀"_a, "solver"_a, "newton_tol"_a, "equil_tol"_a, "verbose"_a = 0); mod.def(name, [](muSpectre::Cell & s, const grad_vec & g, solver & so, Real nt, Real eqt, Dim_t verb) -> std::vector { return newton_cg(s, g, so, nt, eqt, verb); }, "cell"_a, "ΔF₀"_a, "solver"_a, "newton_tol"_a, "equilibrium_tol"_a, "verbose"_a = 0); } void add_de_geus_helper(py::module & mod) { const char name[]{"de_geus"}; using solver = muSpectre::SolverBase; using grad = py::EigenDRef; using grad_vec = muSpectre::LoadSteps_t; mod.def(name, [](muSpectre::Cell & s, const grad & g, solver & so, Real nt, Real eqt, Dim_t verb) -> OptimizeResult { Eigen::MatrixXd tmp{g}; return de_geus(s, tmp, so, nt, eqt, verb); }, "cell"_a, "ΔF₀"_a, "solver"_a, "newton_tol"_a, "equilibrium_tol"_a, "verbose"_a = 0); mod.def(name, [](muSpectre::Cell & s, const grad_vec & g, solver & so, Real nt, Real eqt, Dim_t verb) -> std::vector { return de_geus(s, g, so, nt, eqt, verb); }, "cell"_a, "ΔF₀"_a, "solver"_a, "newton_tol"_a, "equilibrium_tol"_a, "verbose"_a = 0); } void add_solver_helper(py::module & mod) { add_newton_cg_helper(mod); add_de_geus_helper(mod); } void add_solvers(py::module & mod) { auto solvers{mod.def_submodule("solvers")}; solvers.doc() = "bindings for solvers"; py::class_(mod, "OptimizeResult") .def_readwrite("grad", &OptimizeResult::grad) .def_readwrite("stress", &OptimizeResult::stress) .def_readwrite("success", &OptimizeResult::success) .def_readwrite("status", &OptimizeResult::status) .def_readwrite("message", &OptimizeResult::message) .def_readwrite("nb_it", &OptimizeResult::nb_it) .def_readwrite("nb_fev", &OptimizeResult::nb_fev) .def_readwrite("formulation", &OptimizeResult::formulation); add_iterative_solver(solvers); add_solver_helper(solvers); } diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 0e3bc13..3f512c3 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1,92 +1,136 @@ # ============================================================================= # file CMakeLists.txt # # @author Till Junge # # @date 08 Jan 2018 # # @brief Configuration for libmuSpectre # # @section LICENSE # # Copyright © 2018 Till Junge # # µSpectre is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation, either version 3, or (at # your option) any later version. # # µSpectre is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with µSpectre; see the file COPYING. If not, write to the # Free Software Foundation, Inc., 59 Temple Place - Suite 330, # Boston, MA 02111-1307, USA. # # Additional permission under GNU GPL version 3 section 7 # # If you modify this Program, or any covered work, by linking or combining it # with proprietary FFT implementations or numerical libraries, containing parts # covered by the terms of those libraries' licenses, the licensors of this # Program grant you additional permission to convey the resulting work. # ============================================================================= -add_library(muSpectre "") -set("PRIVATE_MUSPECTRE_LIBS" "") +set(MUSPECTRE_TARGETS_EXPORT "${MUCHOICE}Targets") +set(MUFFT_TARGETS_EXPORT "${MUSPECTRE_TARGETS_EXPORT}") +set(MUGRID_TARGETS_EXPORT "${MUSPECTRE_TARGETS_EXPORT}") -add_subdirectory(common) -add_subdirectory(materials) -add_subdirectory(fft) -add_subdirectory(cell) -add_subdirectory(solver) +add_subdirectory(libmugrid) +if(MUCHOICE MATCHES "muGrid") + return() +endif() -if (${MPI_PARALLEL}) - target_link_libraries(muSpectre PUBLIC ${MPI_LIBRARIES}) - target_include_directories(muSpectre SYSTEM PUBLIC ${MPI_C_INCLUDE_PATH}) -endif(${MPI_PARALLEL}) +add_subdirectory(libmufft) +if(MUCHOICE MATCHES "muFFT") + return() +endif() -find_package(FFTW REQUIRED) +add_library(muSpectre "") +add_subdirectory(common) +add_subdirectory(materials) +add_subdirectory(projection) +add_subdirectory(cell) +add_subdirectory(solver) # The following checks whether std::optional exists and replaces it by # boost::optional if necessary include(CheckCXXSourceCompiles) check_cxx_source_compiles( "#include int main() { std::experimental::optional A{}; }" HAS_STD_OPTIONAL) -add_definitions(-DBAR) -if( NOT HAS_STD_OPTIONAL) - add_definitions(-DNO_EXPERIMENTAL) +if(NOT HAS_STD_OPTIONAL) + target_compile_definitions(muSpectre PUBLIC -DNO_EXPERIMENTAL) endif() -file(GLOB_RECURSE _headers RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "*.hh") +# Do not trust old gcc. the std::optional has memory bugs +if(${CMAKE_COMPILER_IS_GNUCC}) + if(${CMAKE_CXX_COMPILER_VERSION} VERSION_LESS 6.0.0) + add_definitions(-DNO_EXPERIMENTAL) + endif() +endif() +file(GLOB_RECURSE _headers RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "*.hh") list(APPEND muSpectre_SRC ${_headers}) + if(${SPLIT_CELL}) - set(muSpectre_INCLUDES ${FFTW_INCLUDES} ${CGAL_INCLUDE_DIR}) + set(muSpectre_INCLUDES ${CGAL_INCLUDE_DIR}) endif() -target_include_directories(muSpectre INTERFACE ${muSpectre_INCLUDES}) -target_link_libraries(muSpectre PRIVATE ${FFTW_LIBRARIES} ${PRIVATE_MUSPECTRE_LIBS}) if(${SPLIT_CELL}) target_link_libraries(muSpectre PUBLIC Eigen3::Eigen ${CGAL_LIBRARIES} ${GMP_LIBRARIES} mpfr) else() target_link_libraries(muSpectre PUBLIC Eigen3::Eigen) endif() +target_include_directories(muSpectre INTERFACE ${muSpectre_INCLUDES}) + +target_link_libraries(muSpectre PUBLIC Eigen3::Eigen) +target_link_libraries(muSpectre PUBLIC ${MUFFT_NAMESPACE}muFFT ${MUGIRD_NAMESPACE}muGrid) set_property(TARGET muSpectre PROPERTY PUBLIC_HEADER ${_headers}) +# defining exported include directories +target_include_directories(muSpectre + PRIVATE $ + INTERFACE $ + ) + +# small trick for build includes in public +set_property(TARGET muSpectre APPEND PROPERTY INTERFACE_INCLUDE_DIRECTORIES + $) + + +add_library(${MUSPECTRE_NAMESPACE}muSpectre ALIAS muSpectre) + +# ------------------------------------------------------------------------------ +if(NOT MUSPECTRE_TARGETS_EXPORT) + set(MUSPECTRE_TARGETS_EXPORT muSpectreTargets) +endif() + install(TARGETS muSpectre - LIBRARY DESTINATION lib - PUBLIC_HEADER DESTINATION include) + EXPORT ${MUSPECTRE_TARGETS_EXPORT} + LIBRARY DESTINATION lib + PUBLIC_HEADER DESTINATION include/libmuspectre) + +if("${MUSPECTRE_TARGETS_EXPORT}" STREQUAL "muSpectreTargets") + install(EXPORT ${MUSPECTRE_TARGETS_EXPORT} + NAMESPACE "${MUSPECTRE_NAMESPACE}" + DESTINATION share/cmake/${PROJECT_NAME} + COMPONENT dev) + + #Export for build tree + export(EXPORT ${MUSPECTRE_TARGETS_EXPORT} + NAMESPACE "${MUSPECTRE_NAMESPACE}" + FILE "${CMAKE_BINARY_DIR}/${MUSPECTRE_TARGETS_EXPORT}.cmake") +endif() diff --git a/src/cell/cell_base.cc b/src/cell/cell_base.cc index 1cbc1fb..541dea7 100644 --- a/src/cell/cell_base.cc +++ b/src/cell/cell_base.cc @@ -1,665 +1,670 @@ /* * @file cell_base.cc * * @author Till Junge * * @date 01 Nov 2017 * * @brief Implementation for cell base class * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "cell/cell_base.hh" -#include "common/ccoord_operations.hh" -#include "common/iterators.hh" -#include "common/tensor_algebra.hh" -#include "common/common.hh" + +#include +#include #include #include #include #include namespace muSpectre { /* ---------------------------------------------------------------------- */ template CellBase::CellBase(Projection_ptr projection_) : subdomain_resolutions{projection_->get_subdomain_resolutions()}, subdomain_locations{projection_->get_subdomain_locations()}, domain_resolutions{projection_->get_domain_resolutions()}, pixels(subdomain_resolutions, subdomain_locations), domain_lengths{projection_->get_domain_lengths()}, fields{std::make_unique()}, - F{make_field("Gradient", *this->fields)}, - P{make_field("Piola-Kirchhoff-1", *this->fields)}, + + F{muGrid::make_field("Gradient", *this->fields)}, + P{muGrid::make_field("Piola-Kirchhoff-1", + *this->fields)}, projection{std::move(projection_)}, is_cell_split{SplitCell::no} { // resize all global fields (strain, stress, etc) this->fields->initialise(this->subdomain_resolutions, this->subdomain_locations); } /** * turns out that the default move container in combination with * clang segfaults under certain (unclear) cicumstances, because the * move constructor of the optional appears to be busted in gcc * 7.2. Copying it (K) instead of moving it fixes the issue, and * since it is a reference, the cost is practically nil */ template CellBase::CellBase(CellBase && other) : subdomain_resolutions{std::move(other.subdomain_resolutions)}, subdomain_locations{std::move(other.subdomain_locations)}, domain_resolutions{std::move(other.domain_resolutions)}, pixels{std::move(other.pixels)}, domain_lengths{std::move( other.domain_lengths)}, fields{std::move(other.fields)}, F{other.F}, P{other.P}, K{other.K}, // this seems to segfault under clang if it's not a move materials{std::move(other.materials)}, projection{std::move( other.projection)} {} /* ---------------------------------------------------------------------- */ template typename CellBase::Material_t & CellBase::add_material(Material_ptr mat) { this->materials.push_back(std::move(mat)); return *this->materials.back(); } /* ---------------------------------------------------------------------- */ template auto CellBase::get_strain_vector() -> Vector_ref { return this->get_strain().eigenvec(); } /* ---------------------------------------------------------------------- */ template auto CellBase::get_stress_vector() const -> ConstVector_ref { return this->get_stress().eigenvec(); } /* ---------------------------------------------------------------------- */ template void CellBase::set_uniform_strain( const Eigen::Ref & strain) { if (not this->initialised) { this->initialise(); } this->F.get_map() = strain; } /* ---------------------------------------------------------------------- */ template auto CellBase::evaluate_stress() -> ConstVector_ref { if (not this->initialised) { this->initialise(); } for (auto & mat : this->materials) { mat->compute_stresses(this->F, this->P, this->get_formulation()); } return this->P.const_eigenvec(); } /* ---------------------------------------------------------------------- */ template auto CellBase::evaluate_stress_tangent() -> std::array { if (not this->initialised) { this->initialise(); } constexpr bool create_tangent{true}; this->get_tangent(create_tangent); for (auto & mat : this->materials) { mat->compute_stresses_tangent(this->F, this->P, this->K.value(), this->get_formulation()); } const TangentField_t & k = this->K.value(); return std::array{this->P.const_eigenvec(), k.const_eigenvec()}; } /* ---------------------------------------------------------------------- */ template auto CellBase::evaluate_projected_directional_stiffness( Eigen::Ref delF) -> Vector_ref { // the following const_cast should be safe, as long as the // constructed delF_field is const itself - const TypedField delF_field( + const muGrid::TypedField delF_field( "Proxied raw memory for strain increment", *this->fields, Eigen::Map(const_cast(delF.data()), delF.size()), this->F.get_nb_components()); if (!this->K) { throw std::runtime_error( "currently only implemented for cases where a stiffness matrix " "exists"); } if (delF.size() != this->get_nb_dof()) { std::stringstream err{}; - err << "input should be of size ndof = ¶(" << this->subdomain_resolutions + err << "input should be of size ndof = ¶("; + muGrid::operator<<(err, this->subdomain_resolutions) << ") × " << DimS << "² = " << this->get_nb_dof() << " but I got " << delF.size(); throw std::runtime_error(err.str()); } const std::string out_name{"δP; temp output for directional stiffness"}; auto & delP = this->get_managed_T2_field(out_name); auto Kmap{this->K.value().get().get_map()}; auto delPmap{delP.get_map()}; - MatrixFieldMap delFmap( + muGrid::MatrixFieldMap delFmap( delF_field); for (auto && tup : akantu::zip(Kmap, delFmap, delPmap)) { auto & k = std::get<0>(tup); auto & df = std::get<1>(tup); auto & dp = std::get<2>(tup); dp = Matrices::tensmult(k, df); } return Vector_ref(this->project(delP).data(), this->get_nb_dof()); } /* ---------------------------------------------------------------------- */ template std::array CellBase::get_strain_shape() const { return this->projection->get_strain_shape(); } /* ---------------------------------------------------------------------- */ template auto CellBase::evaluate_projection(Eigen::Ref P) -> Vector_ref { + using muGrid::operator<<; if (P.size() != this->get_nb_dof()) { std::stringstream err{}; err << "input should be of size ndof = ¶(" << this->subdomain_resolutions << ") × " << DimS << "² = " << this->get_nb_dof() << " but I got " << P.size(); throw std::runtime_error(err.str()); } const std::string out_name{"RHS; temp output for projection"}; auto & rhs = this->get_managed_T2_field(out_name); rhs.eigen() = P; return Vector_ref(this->project(rhs).data(), this->get_nb_dof()); } /* ---------------------------------------------------------------------- */ template void CellBase::apply_projection(Eigen::Ref vec) { - TypedField field("Proxy for projection", - *this->fields, vec, - this->F.get_nb_components()); + muGrid::TypedField field( + "Proxy for projection", *this->fields, vec, + this->F.get_nb_components()); this->projection->apply_projection(field); } /* ---------------------------------------------------------------------- */ template typename CellBase::FullResponse_t CellBase::evaluate_stress_tangent(StrainField_t & grad) { if (this->initialised == false) { this->initialise(); } //! High level compatibility checks if (grad.size() != this->F.size()) { throw std::runtime_error("Size mismatch"); } constexpr bool create_tangent{true}; this->get_tangent(create_tangent); for (auto & mat : this->materials) { mat->compute_stresses_tangent(grad, this->P, this->K.value(), this->get_formulation()); } return std::tie(this->P, this->K.value()); } /* ---------------------------------------------------------------------- */ template typename CellBase::StressField_t & CellBase::directional_stiffness(const TangentField_t & K, const StrainField_t & delF, StressField_t & delP) { for (auto && tup : akantu::zip(K.get_map(), delF.get_map(), delP.get_map())) { auto & k = std::get<0>(tup); auto & df = std::get<1>(tup); auto & dp = std::get<2>(tup); dp = Matrices::tensmult(k, df); } return this->project(delP); } /* ---------------------------------------------------------------------- */ template typename CellBase::Vector_ref CellBase::directional_stiffness_vec( const Eigen::Ref & delF) { if (!this->K) { throw std::runtime_error( "currently only implemented for cases where a stiffness matrix " "exists"); } if (delF.size() != this->get_nb_dof()) { std::stringstream err{}; - err << "input should be of size ndof = ¶(" << this->subdomain_resolutions + err << "input should be of size ndof = ¶("; + muGrid::operator<<(err, this->subdomain_resolutions) << ") × " << DimS << "² = " << this->get_nb_dof() << " but I got " << delF.size(); throw std::runtime_error(err.str()); } const std::string out_name{"temp output for directional stiffness"}; const std::string in_name{"temp input for directional stiffness"}; auto & out_tempref = this->get_managed_T2_field(out_name); auto & in_tempref = this->get_managed_T2_field(in_name); Vector_ref(in_tempref.data(), this->get_nb_dof()) = delF; this->directional_stiffness(this->K.value(), in_tempref, out_tempref); return Vector_ref(out_tempref.data(), this->get_nb_dof()); } /* ---------------------------------------------------------------------- */ template Eigen::ArrayXXd CellBase::directional_stiffness_with_copy( Eigen::Ref delF) { if (!this->K) { throw std::runtime_error( "currently only implemented for cases where a stiffness matrix " "exists"); } const std::string out_name{"temp output for directional stiffness"}; const std::string in_name{"temp input for directional stiffness"}; auto & out_tempref = this->get_managed_T2_field(out_name); auto & in_tempref = this->get_managed_T2_field(in_name); in_tempref.eigen() = delF; this->directional_stiffness(this->K.value(), in_tempref, out_tempref); return out_tempref.eigen(); } /* ---------------------------------------------------------------------- */ template typename CellBase::StressField_t & CellBase::project(StressField_t & field) { this->projection->apply_projection(field); return field; } /* ---------------------------------------------------------------------- */ template typename CellBase::StrainField_t & CellBase::get_strain() { if (this->initialised == false) { this->initialise(); } return this->F; } /* ---------------------------------------------------------------------- */ template const typename CellBase::StressField_t & CellBase::get_stress() const { return this->P; } /* ---------------------------------------------------------------------- */ template const typename CellBase::TangentField_t & CellBase::get_tangent(bool create) { if (!this->K) { if (create) { - this->K = - make_field("Tangent Stiffness", *this->fields); + this->K = muGrid::make_field("Tangent Stiffness", + *this->fields); } else { throw std::runtime_error("K does not exist"); } } return this->K.value(); } /* ---------------------------------------------------------------------- */ template typename CellBase::StrainField_t & CellBase::get_managed_T2_field(std::string unique_name) { if (!this->fields->check_field_exists(unique_name)) { - return make_field(unique_name, *this->fields); + return muGrid::make_field(unique_name, *this->fields); } else { return static_cast(this->fields->at(unique_name)); } } /* ---------------------------------------------------------------------- */ template auto CellBase::get_managed_real_field(std::string unique_name, size_t nb_components) -> Field_t & { if (!this->fields->check_field_exists(unique_name)) { - return make_field>(unique_name, *this->fields, - nb_components); + return muGrid::make_field>(unique_name, *this->fields, + nb_components); } else { auto & ret_ref{Field_t::check_ref(this->fields->at(unique_name))}; if (ret_ref.get_nb_components() != nb_components) { std::stringstream err{}; err << "Field '" << unique_name << "' already exists and it has " << ret_ref.get_nb_components() << " components. You asked for a field " << "with " << nb_components << "components."; throw std::runtime_error(err.str()); } return ret_ref; } } /* ---------------------------------------------------------------------- */ template template auto CellBase::globalised_field_helper( const std::string & unique_name, int nb_steps_ago) -> Field_t & { using LField_t = const typename Field_t::LocalField_t; // start by checking that the field exists at least once, and that // it always has th same number of components std::set nb_component_categories{}; std::vector> local_fields; auto check{[&unique_name](auto & coll) -> bool { if (IsStateField) { return coll.check_statefield_exists(unique_name); } else { return coll.check_field_exists(unique_name); } }}; - auto get = [&unique_name, &nb_steps_ago ]( - auto & coll) -> const typename LField_t::Base & { + auto get = [&unique_name, & + nb_steps_ago ](auto & coll) -> const typename LField_t::Base & { if (IsStateField) { using Coll_t = typename Material_t::MFieldCollection_t; - using TypedStateField_t = TypedStateField; + using TypedStateField_t = muGrid::TypedStateField; auto & statefield{coll.get_statefield(unique_name)}; auto & typed_statefield{TypedStateField_t::check_ref(statefield)}; const typename LField_t::Base & f1{ typed_statefield.get_old_field(nb_steps_ago)}; const typename LField_t::Base & f2{ typed_statefield.get_current_field()}; return (nb_steps_ago ? f1 : f2); } else { return coll[unique_name]; } }; for (auto & mat : this->materials) { auto & coll = mat->get_collection(); if (check(coll)) { const auto & field{LField_t::check_ref(get(coll))}; local_fields.emplace_back(field); nb_component_categories.insert(field.get_nb_components()); } } if (nb_component_categories.size() != 1) { const auto & nb_match{nb_component_categories.size()}; std::stringstream err_str{}; if (nb_match > 1) { err_str << "The fields named '" << unique_name << "' do not have the " << "same number of components in every material, which is a " << "requirement for globalising them! The following values were " << "found by material:" << std::endl; for (auto & mat : this->materials) { auto & coll = mat->get_collection(); if (coll.check_field_exists(unique_name)) { auto & field{LField_t::check_ref(coll[unique_name])}; err_str << field.get_nb_components() << " components in material '" << mat->get_name() << "'" << std::endl; } } } else { err_str << "The " << (IsStateField ? "state" : "") << "field named '" << unique_name << "' does not exist in " << "any of the materials and can therefore not be globalised!"; } throw std::runtime_error(err_str.str()); } const Dim_t nb_components{*nb_component_categories.begin()}; // get and prepare the field auto & field{this->get_managed_real_field(unique_name, nb_components)}; field.set_zero(); // fill it with local internal values for (auto & local_field : local_fields) { field.fill_from_local(local_field); } return field; } /* ---------------------------------------------------------------------- */ template auto CellBase::get_globalised_internal_real_field( const std::string & unique_name) -> Field_t & { constexpr bool IsStateField{false}; return this->template globalised_field_helper( unique_name, -1); // the -1 is a moot argument } /* ---------------------------------------------------------------------- */ template auto CellBase::get_globalised_current_real_field( const std::string & unique_name) -> Field_t & { constexpr bool IsStateField{true}; return this->template globalised_field_helper( unique_name, 0); } /* ---------------------------------------------------------------------- */ template auto CellBase::get_globalised_old_real_field( const std::string & unique_name, int nb_steps_ago) -> Field_t & { constexpr bool IsStateField{true}; return this->template globalised_field_helper( unique_name, nb_steps_ago); } /* ---------------------------------------------------------------------- */ template auto CellBase::get_managed_real_array(std::string unique_name, size_t nb_components) -> Array_ref { auto & field{this->get_managed_real_field(unique_name, nb_components)}; return Array_ref{field.data(), Dim_t(nb_components), Dim_t(field.size())}; } /* ---------------------------------------------------------------------- */ template auto CellBase::get_globalised_internal_real_array( const std::string & unique_name) -> Array_ref { auto & field{this->get_globalised_internal_real_field(unique_name)}; return Array_ref{field.data(), Dim_t(field.get_nb_components()), Dim_t(field.size())}; } /* ---------------------------------------------------------------------- */ template auto CellBase::get_globalised_current_real_array( const std::string & unique_prefix) -> Array_ref { auto & field{this->get_globalised_current_real_field(unique_prefix)}; return Array_ref{field.data(), Dim_t(field.get_nb_components()), Dim_t(field.size())}; } /* ---------------------------------------------------------------------- */ template auto CellBase::get_globalised_old_real_array( const std::string & unique_prefix, int nb_steps_ago) -> Array_ref { auto & field{ this->get_globalised_old_real_field(unique_prefix, nb_steps_ago)}; return Array_ref{field.data(), Dim_t(field.get_nb_components()), Dim_t(field.size())}; } /* ---------------------------------------------------------------------- */ template - void CellBase::initialise(FFT_PlanFlags flags) { + void CellBase::initialise(muFFT::FFT_PlanFlags flags) { // check that all pixels have been assigned exactly one material this->check_material_coverage(); for (auto && mat : this->materials) { mat->initialise(); } // initialise the projection and compute the fft plan this->projection->initialise(flags); this->initialised = true; } /* ---------------------------------------------------------------------- */ template void CellBase::save_history_variables() { for (auto && mat : this->materials) { mat->save_history_variables(); } } /* ---------------------------------------------------------------------- */ template typename CellBase::iterator CellBase::begin() { return this->pixels.begin(); } /* ---------------------------------------------------------------------- */ template typename CellBase::iterator CellBase::end() { return this->pixels.end(); } /* ---------------------------------------------------------------------- */ template auto CellBase::get_adaptor() -> Adaptor { return Adaptor(*this); } /* ---------------------------------------------------------------------- */ template void CellBase::check_material_coverage() { - auto nb_pixels = CcoordOps::get_size(this->subdomain_resolutions); + auto nb_pixels = muGrid::CcoordOps::get_size(this->subdomain_resolutions); std::vector *> assignments(nb_pixels, nullptr); for (auto & mat : this->materials) { for (auto & pixel : *mat) { - auto index = CcoordOps::get_index(this->subdomain_resolutions, - this->subdomain_locations, pixel); + auto index = muGrid::CcoordOps::get_index( + this->subdomain_resolutions, this->subdomain_locations, pixel); auto & assignment{assignments.at(index)}; if (assignment != nullptr) { std::stringstream err{}; - err << "Pixel " << pixel << "is already assigned to material '" - << assignment->get_name() + err << "Pixel "; + muGrid::operator<<(err, pixel) + << "is already assigned to material '" << assignment->get_name() << "' and cannot be reassigned to material '" << mat->get_name(); throw std::runtime_error(err.str()); } else { assignments[index] = mat.get(); } } } // find and identify unassigned pixels std::vector unassigned_pixels; for (size_t i = 0; i < assignments.size(); ++i) { if (assignments[i] == nullptr) { - unassigned_pixels.push_back(CcoordOps::get_ccoord( + unassigned_pixels.push_back(muGrid::CcoordOps::get_ccoord( this->subdomain_resolutions, this->subdomain_locations, i)); } } if (unassigned_pixels.size() != 0) { std::stringstream err{}; err << "The following pixels have were not assigned a material: "; for (auto & pixel : unassigned_pixels) { - err << pixel << ", "; + muGrid::operator<<(err, pixel) << ", "; } err << "and that cannot be handled"; throw std::runtime_error(err.str()); } } template Rcoord_t CellBase::get_pixel_lengths() const { auto nb_pixels = this->get_domain_resolutions(); auto length_pixels = this->get_domain_lengths(); Rcoord_t ret_val; for (int i = 0; i < DimS; i++) { ret_val[i] = length_pixels[i] / nb_pixels[i]; } return ret_val; } template Rcoord_t CellBase::get_pixel_coordinate(Ccoord_t & pixel) const { auto pixel_length = this->get_pixel_lengths(); Rcoord_t pixel_coordinate; for (int i = 0; i < DimS; i++) { pixel_coordinate[i] = pixel_length[i] * (pixel[i] + 0.5); // 0.5 is added to shift to the center of the pixel; } // return pixel_length * pixel; return pixel_coordinate; } template bool CellBase::is_inside(Rcoord_t point) { auto length_pixels = this->get_domain_lengths(); Dim_t counter = 1; for (int i = 0; i < DimS; i++) { if (point[i] < length_pixels[i]) { counter++; } } return counter == DimS; } template bool CellBase::is_inside(Ccoord_t pixel) { auto nb_pixels = this->get_domain_resolutions(); Dim_t counter = 1; for (int i = 0; i < DimS; i++) { if (pixel[i] < nb_pixels[i]) { counter++; } } return counter == DimS; } template Real CellBase::get_pixel_volume() { auto pixel_length = get_pixel_lengths(); Real Retval = 1.0; for (int i = 0; i < DimS; i++) { Retval *= pixel_length[i]; } return Retval; } template class CellBase; template class CellBase; } // namespace muSpectre diff --git a/src/cell/cell_base.hh b/src/cell/cell_base.hh index 1ac4d70..797d9bd 100644 --- a/src/cell/cell_base.hh +++ b/src/cell/cell_base.hh @@ -1,694 +1,704 @@ /** * @file cell_base.hh * * @author Till Junge * * @date 01 Nov 2017 * * @brief Base class representing a unit cell cell with single * projection operator * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_CELL_CELL_BASE_HH_ #define SRC_CELL_CELL_BASE_HH_ -#include "common/common.hh" -#include "common/ccoord_operations.hh" -#include "common/field.hh" -#include "common/utilities.hh" +#include "common/muSpectre_common.hh" #include "materials/material_base.hh" -#include "fft/projection_base.hh" +#include "projection/projection_base.hh" #include "cell/cell_traits.hh" +#include +#include + #include #include #include #include #include namespace muSpectre { /** * Cell adaptors implement the matrix-vector multiplication and * allow the system to be used like a sparse matrix in * conjugate-gradient-type solvers */ - template class CellAdaptor; + template + class CellAdaptor; /** * Base class for cells that is not templated and therefore can be * in solvers that see cells as runtime-polymorphic objects. This * allows the use of standard * (i.e. spectral-method-implementation-agnostic) solvers, as for * instance the scipy solvers */ class Cell { public: //! sparse matrix emulation using Adaptor = CellAdaptor; //! dynamic vector type for interactions with numpy/scipy/solvers etc. using Vector_t = Eigen::Matrix; //! dynamic matrix type for setting strains using Matrix_t = Eigen::Matrix; //! dynamic generic array type for interaction with numpy, i/o, etc template using Array_t = Eigen::Array; //! ref to dynamic generic array - template using Array_ref = Eigen::Map>; + template + using Array_ref = Eigen::Map>; //! ref to constant vector using ConstVector_ref = Eigen::Map; //! output vector reference for solvers using Vector_ref = Eigen::Map; //! Default constructor Cell() = default; //! Copy constructor Cell(const Cell & other) = default; //! Move constructor Cell(Cell && other) = default; //! Destructor virtual ~Cell() = default; //! Copy assignment operator Cell & operator=(const Cell & other) = default; //! Move assignment operator Cell & operator=(Cell && other) = default; //! for handling double initialisations right bool is_initialised() const { return this->initialised; } //! returns the number of degrees of freedom in the cell virtual Dim_t get_nb_dof() const = 0; //! number of pixels in the cell virtual size_t size() const = 0; //! return the communicator object - virtual const Communicator & get_communicator() const = 0; + virtual const muFFT::Communicator & get_communicator() const = 0; /** * formulation is hard set by the choice of the projection class */ virtual const Formulation & get_formulation() const = 0; /** * returns the material dimension of the problem */ virtual Dim_t get_material_dim() const = 0; /** * returns the number of rows and cols for the strain matrix type * (for full storage, the strain is stored in material_dim × * material_dim matrices, but in symmetriy storage, it is a column * vector) */ virtual std::array get_strain_shape() const = 0; /** * returns a writable map onto the strain field of this cell. This * corresponds to the unknowns in a typical solve cycle. */ virtual Vector_ref get_strain_vector() = 0; /** * returns a read-only map onto the stress field of this * cell. This corresponds to the intermediate (and finally, total) * solution in a typical solve cycle */ virtual ConstVector_ref get_stress_vector() const = 0; /** * evaluates and returns the stress for the currently set strain */ virtual ConstVector_ref evaluate_stress() = 0; /** * evaluates and returns the stress and stiffness for the currently set * strain */ virtual std::array evaluate_stress_tangent() = 0; /** * applies the projection operator in-place on the input vector */ virtual void apply_projection(Eigen::Ref vec) = 0; /** * evaluates the projection of the input field (this corresponds * to G:P in de Geus 2017, * http://dx.doi.org/10.1016/j.cma.2016.12.032). The first time, * this allocates the memory for the return value, and reuses it * on subsequent calls */ virtual Vector_ref evaluate_projection(Eigen::Ref P) = 0; /** * freezes all the history variables of the materials */ virtual void save_history_variables() = 0; /** * evaluates the directional and projected stiffness (this * corresponds to G:K:δF in de Geus 2017, * http://dx.doi.org/10.1016/j.cma.2016.12.032). It seems that * this operation needs to be implemented with a copy in oder to * be compatible with scipy and EigenCG etc (At the very least, * the copy is only made once) */ virtual Vector_ref evaluate_projected_directional_stiffness( Eigen::Ref delF) = 0; /** * returns a ref to a field named 'unique_name" of real values * managed by the cell. If the field does not yet exist, it is * created. * * @param unique_name name of the field. If the field already * exists, an array ref mapped onto it is returned. Else, a new * field with that name is created and returned- * * @param nb_components number of components to be stored *per * pixel*. For new fields any positive number can be chosen. When * accessing an existing field, this must correspond to the * existing field size, and a `std::runtime_error` is thrown if * this is not satisfied */ virtual Array_ref get_managed_real_array(std::string unique_name, size_t nb_components) = 0; /** * Convenience function to copy local (internal) fields of * materials into a global field. At least one of the materials in * the cell needs to contain an internal field named * `unique_name`. If multiple materials contain such a field, they * all need to be of same scalar type and same number of * components. This does not work for split pixel cells or * laminate pixel cells, as they can have multiple entries for the * same pixel. Pixels for which no field named `unique_name` * exists get an array of zeros. * * @param unique_name fieldname to fill the global field with. At * least one material must have such a field, or a * `std::runtime_error` is thrown */ virtual Array_ref get_globalised_internal_real_array(const std::string & unique_name) = 0; /** * Convenience function to copy local (internal) state fields * (current state) of materials into a global field. At least one * of the materials in the cell needs to contain an internal field * named `unique_name`. If multiple materials contain such a * field, they all need to be of same scalar type and same number * of components. This does not work for split pixel cells or * laminate pixel cells, as they can have multiple entries for the * same pixel. Pixels for which no field named `unique_name` * exists get an array of zeros. * * @param unique_name fieldname to fill the global field with. At * least one material must have such a field, or a * `std::runtime_error` is thrown */ virtual Array_ref get_globalised_current_real_array(const std::string & unique_name) = 0; /** * Convenience function to copy local (internal) state fields * (old state) of materials into a global field. At least one * of the materials in the cell needs to contain an internal field * named `unique_name`. If multiple materials contain such a * field, they all need to be of same scalar type and same number * of components. This does not work for split pixel cells or * laminate pixel cells, as they can have multiple entries for the * same pixel. Pixels for which no field named `unique_name` * exists get an array of zeros. * * @param unique_name fieldname to fill the global field with. At least one * material must have such a field, or a `std::runtime_error` is thrown * @param nb_steps_ago for history variables which remember more than a * single previous value, `nb_steps_ago` can be used to specify which old * value to access. */ virtual Array_ref get_globalised_old_real_array(const std::string & unique_name, int nb_steps_ago = 1) = 0; /** * set uniform strain (typically used to initialise problems */ virtual void set_uniform_strain(const Eigen::Ref &) = 0; //! get a sparse matrix view on the cell virtual Adaptor get_adaptor() = 0; protected: bool initialised{false}; //!< to handle double initialisation right private: }; //! DimS spatial dimension (dimension of problem //! DimM material_dimension (dimension of constitutive law) template class CellBase : public Cell { public: using Parent = Cell; using Ccoord = Ccoord_t; //!< cell coordinates type using Rcoord = Rcoord_t; //!< physical coordinates type //! global field collection - using FieldCollection_t = GlobalFieldCollection; + using FieldCollection_t = muGrid::GlobalFieldCollection; //! the collection is handled in a `std::unique_ptr` using Collection_ptr = std::unique_ptr; //! polymorphic base material type using Material_t = MaterialBase; //! materials handled through `std::unique_ptr`s using Material_ptr = std::unique_ptr; //! polymorphic base projection type using Projection_t = ProjectionBase; //! projections handled through `std::unique_ptr`s using Projection_ptr = std::unique_ptr; //! dynamic global fields - template using Field_t = TypedField; + template + using Field_t = muGrid::TypedField; //! expected type for strain fields using StrainField_t = - TensorField; + muGrid::TensorField; //! expected type for stress fields using StressField_t = - TensorField; + muGrid::TensorField; //! expected type for tangent stiffness fields using TangentField_t = - TensorField; + muGrid::TensorField; //! combined stress and tangent field using FullResponse_t = std::tuple; //! iterator type over all cell pixel's - using iterator = typename CcoordOps::Pixels::iterator; + using iterator = typename muGrid::CcoordOps::Pixels::iterator; //! dynamic vector type for interactions with numpy/scipy/solvers etc. using Vector_t = typename Parent::Vector_t; //! ref to constant vector using ConstVector_ref = typename Parent::ConstVector_ref; //! output vector reference for solvers using Vector_ref = typename Parent::Vector_ref; //! dynamic array type for interactions with numpy/scipy/solvers, etc. - template using Array_t = typename Parent::Array_t; + template + using Array_t = typename Parent::Array_t; //! dynamic array type for interactions with numpy/scipy/solvers, etc. - template using Array_ref = typename Parent::Array_ref; + template + using Array_ref = typename Parent::Array_ref; //! sparse matrix emulation using Adaptor = Parent::Adaptor; //! Default constructor CellBase() = delete; //! constructor using sizes and resolution explicit CellBase(Projection_ptr projection); //! Copy constructor CellBase(const CellBase & other) = delete; //! Move constructor CellBase(CellBase && other); //! Destructor virtual ~CellBase() = default; //! Copy assignment operator CellBase & operator=(const CellBase & other) = delete; //! Move assignment operator CellBase & operator=(CellBase && other) = default; /** * Materials can only be moved. This is to assure exclusive * ownership of any material by this cell */ Material_t & add_material(Material_ptr mat); /** * returns a writable map onto the strain field of this cell. This * corresponds to the unknowns in a typical solve cycle. */ Vector_ref get_strain_vector() override; /** * returns a read-only map onto the stress field of this * cell. This corresponds to the intermediate (and finally, total) * solution in a typical solve cycle */ ConstVector_ref get_stress_vector() const override; /** * evaluates and returns the stress for the currently set strain */ ConstVector_ref evaluate_stress() override; /** * evaluates and returns the stress and stiffness for the currently set * strain */ std::array evaluate_stress_tangent() override; /** * evaluates the projection of the input field (this corresponds * do G:P in de Geus 2017, * http://dx.doi.org/10.1016/j.cma.2016.12.032). The first time, * this allocates the memory for the return value, and reuses it * on subsequent calls */ - Vector_ref - evaluate_projection(Eigen::Ref P) override; + Vector_ref evaluate_projection(Eigen::Ref P) override; /** * evaluates the directional and projected stiffness (this * corresponds to G:K:δF in de Geus 2017, * http://dx.doi.org/10.1016/j.cma.2016.12.032). It seems that * this operation needs to be implemented with a copy in oder to * be compatible with scipy and EigenCG etc. (At the very least, * the copy is only made once) */ Vector_ref evaluate_projected_directional_stiffness( Eigen::Ref delF) override; //! return the template param DimM (required for polymorphic use of `Cell` Dim_t get_material_dim() const final { return DimM; } /** * returns the number of rows and cols for the strain matrix type * (for full storage, the strain is stored in material_dim × * material_dim matrices, but in symmetriy storage, it is a column * vector) */ std::array get_strain_shape() const final; /** * applies the projection operator in-place on the input vector */ void apply_projection(Eigen::Ref vec) final; /** * Reutrns the splitness status of the cell */ inline SplitCell get_splitness() { return this->is_cell_split; } /** * set uniform strain (typically used to initialise problems */ void set_uniform_strain(const Eigen::Ref &) override; /** * evaluate all materials */ virtual FullResponse_t evaluate_stress_tangent(StrainField_t & F); /** * evaluate directional stiffness (i.e. G:K:δF or G:K:δε) */ StressField_t & directional_stiffness(const TangentField_t & K, const StrainField_t & delF, StressField_t & delP); /** * vectorized version for eigen solvers, no copy, but only works * when fields have ArrayStore=false */ Vector_ref directional_stiffness_vec(const Eigen::Ref & delF); /** * Evaluate directional stiffness into a temporary array and * return a copy. This is a costly and wasteful interface to * directional_stiffness and should only be used for debugging or * in the python interface */ Eigen::ArrayXXd directional_stiffness_with_copy(Eigen::Ref delF); /** * Convenience function circumventing the neeed to use the * underlying projection */ StressField_t & project(StressField_t & field); //! returns a ref to the cell's strain field StrainField_t & get_strain(); //! returns a ref to the cell's stress field const StressField_t & get_stress() const; //! returns a ref to the cell's tangent stiffness field const TangentField_t & get_tangent(bool create = false); //! returns a ref to a temporary field managed by the cell StrainField_t & get_managed_T2_field(std::string unique_name); //! returns a ref to a temporary field of real values managed by the cell Field_t & get_managed_real_field(std::string unique_name, size_t nb_components); /** * returns a Array ref to a temporary field of real values managed by the * cell */ Array_ref get_managed_real_array(std::string unique_name, size_t nb_components) final; /** * returns a global field filled from local (internal) fields of * the materials. see `Cell::get_globalised_internal_real_array` for * details. */ Field_t & get_globalised_internal_real_field(const std::string & unique_name); /** * returns a global field filled from local (internal) statefields of * the materials. see `Cell::get_globalised_current_real_array` for * details. */ Field_t & get_globalised_current_real_field(const std::string & unique_name); /** * returns a global field filled from local (internal) statefields of * the materials. see `Cell::get_globalised_old_real_array` for * details. */ Field_t & get_globalised_old_real_field(const std::string & unique_name, int nb_steps_ago = 1); //! see `Cell::get_globalised_internal_real_array` for details - Array_ref get_globalised_internal_real_array( - const std::string & unique_name) final; + Array_ref + get_globalised_internal_real_array(const std::string & unique_name) final; //! see `Cell::get_globalised_current_reald_array` for details - Array_ref get_globalised_current_real_array( - const std::string & unique_name) final; + Array_ref + get_globalised_current_real_array(const std::string & unique_name) final; //! see `Cell::get_globalised_old_real_array` for details Array_ref get_globalised_old_real_array(const std::string & unique_name, int nb_steps_ago = 1) final; /** * general initialisation; initialises the projection and * fft_engine (i.e. infrastructure) but not the materials. These * need to be initialised separately */ - void initialise(FFT_PlanFlags flags = FFT_PlanFlags::estimate); + void + initialise(muFFT::FFT_PlanFlags flags = muFFT::FFT_PlanFlags::estimate); /** * for materials with state variables, these typically need to be * saved/updated an the end of each load increment, this function * calls this update for each material in the cell */ void save_history_variables() final; iterator begin(); //!< iterator to the first pixel iterator end(); //!< iterator past the last pixel //! number of pixels in the cell size_t size() const final { return pixels.size(); } //! return the subdomain resolutions of the cell const Ccoord & get_subdomain_resolutions() const { return this->subdomain_resolutions; } //! return the subdomain locations of the cell const Ccoord & get_subdomain_locations() const { return this->subdomain_locations; } //! return the domain resolutions of the cell const Ccoord & get_domain_resolutions() const { return this->domain_resolutions; } //! return the sizes of the cell const Rcoord & get_domain_lengths() const { return this->domain_lengths; } //! return the real space coordinates of the center of pixel Rcoord get_pixel_coordinate(Ccoord & pixel) const; //! return the physical dimension of a pixel Rcoord get_pixel_lengths() const; //! check if the pixel is inside of the cell bool is_inside(Rcoord point); //! check if the point is inside of the cell bool is_inside(Ccoord pixel); // calculate the volume of each pixel: Real get_pixel_volume(); /** * formulation is hard set by the choice of the projection class */ const Formulation & get_formulation() const final { return this->projection->get_formulation(); } /** * get a reference to the projection object. should only be * required for debugging */ Eigen::Map get_projection() { return this->projection->get_operator(); } //! returns the spatial size constexpr static Dim_t get_sdim() { return DimS; } //! return a sparse matrix adaptor to the cell Adaptor get_adaptor() override; //! returns the number of degrees of freedom in the cell - Dim_t get_nb_dof() const override { return this->size() * ipow(DimS, 2); }; + // returns the splitness status of the cell SplitCell get_splitness() const { return this->is_cell_split; } + Dim_t get_nb_dof() const override { + return this->size() * muGrid::ipow(DimS, 2); + }; + //! return the communicator object - const Communicator & get_communicator() const override { + const muFFT::Communicator & get_communicator() const override { return this->projection->get_communicator(); } protected: template Field_t & globalised_field_helper(const std::string & unique_name, int nb_steps_ago); //! make sure that every pixel is assigned to one and only one material virtual void check_material_coverage(); const Ccoord & subdomain_resolutions; //!< the cell's subdomain resolutions const Ccoord & subdomain_locations; //!< the cell's subdomain resolutions const Ccoord & domain_resolutions; //!< the cell's domain resolutions - CcoordOps::Pixels pixels; //!< helper to iterate over the pixels - const Rcoord & domain_lengths; //!< the cell's lengths + muGrid::CcoordOps::Pixels + pixels; //!< helper to iterate over the pixels + const Rcoord & domain_lengths; //!< the cell's lengths Collection_ptr fields; //!< handle for the global fields of the cell StrainField_t & F; //!< ref to strain field StressField_t & P; //!< ref to stress field //! Tangent field might not even be required; so this is an //! optional ref_wrapper instead of a ref optional> K{}; //! container of the materials present in the cell std::vector materials{}; Projection_ptr projection; //!< handle for the projection operator SplitCell is_cell_split{}; private: }; /** * lightweight resource handle wrapping a `muSpectre::Cell` or * a subclass thereof into `Eigen::EigenBase`, so it can be * interpreted as a sparse matrix by Eigen solvers */ template class CellAdaptor : public Eigen::EigenBase> { public: using Scalar = double; //!< sparse matrix traits using RealScalar = double; //!< sparse matrix traits using StorageIndex = int; //!< sparse matrix traits enum { ColsAtCompileTime = Eigen::Dynamic, MaxColsAtCompileTime = Eigen::Dynamic, RowsAtCompileTime = Eigen::Dynamic, MaxRowsAtCompileTime = Eigen::Dynamic, IsRowMajor = false }; //! constructor explicit CellAdaptor(Cell & cell) : cell{cell} {} //! returns the number of logical rows Eigen::Index rows() const { return this->cell.get_nb_dof(); } //! returns the number of logical columns Eigen::Index cols() const { return this->rows(); } //! implementation of the evaluation template Eigen::Product operator*(const Eigen::MatrixBase & x) const { return Eigen::Product( *this, x.derived()); } Cell & cell; //!< ref to the cell }; } // namespace muSpectre namespace Eigen { namespace internal { //! Implementation of `muSpectre::CellAdaptor` * `Eigen::DenseVector` //! through a specialization of `Eigen::internal::generic_product_impl`: template // GEMV stands for matrix-vector struct generic_product_impl : generic_product_impl_base> { //! undocumented typedef typename Product::Scalar Scalar; //! undocumented template static void scaleAndAddTo(Dest & dst, const CellAdaptor & lhs, const Rhs & rhs, const Scalar & /*alpha*/) { // This method should implement "dst += alpha * lhs * rhs" inplace, // however, for iterative solvers, alpha is always equal to 1, so // let's not bother about it. // Here we could simply call dst.noalias() += lhs.my_matrix() * rhs, dst.noalias() += const_cast(lhs) .cell.evaluate_projected_directional_stiffness(rhs); } }; } // namespace internal } // namespace Eigen #endif // SRC_CELL_CELL_BASE_HH_ diff --git a/src/cell/cell_factory.hh b/src/cell/cell_factory.hh index b399705..8a27ac7 100644 --- a/src/cell/cell_factory.hh +++ b/src/cell/cell_factory.hh @@ -1,159 +1,161 @@ /** * @file cell_factory.hh * * @author Till Junge * * @date 15 Dec 2017 * * @brief Cell factories to help create cells with ease * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_CELL_CELL_FACTORY_HH_ #define SRC_CELL_CELL_FACTORY_HH_ -#include "common/common.hh" -#include "common/ccoord_operations.hh" +#include "common/muSpectre_common.hh" #include "cell/cell_base.hh" -#include "fft/projection_finite_strain_fast.hh" -#include "fft/projection_small_strain.hh" -#include "fft/fftw_engine.hh" +#include "projection/projection_finite_strain_fast.hh" +#include "projection/projection_small_strain.hh" +#include +#include #ifdef WITH_MPI -#include "common/communicator.hh" -#include "fft/fftwmpi_engine.hh" +#include +#include #endif #include namespace muSpectre { /** * Create a unique ptr to a Projection operator (with appropriate * FFT_engine) to be used in a cell constructor */ - template > + template > inline std::unique_ptr> cell_input(Ccoord_t resolutions, Rcoord_t lengths, Formulation form) { auto fft_ptr{std::make_unique(resolutions, dof_for_formulation(form, DimS))}; switch (form) { case Formulation::finite_strain: { using Projection = ProjectionFiniteStrainFast; return std::make_unique(std::move(fft_ptr), lengths); break; } case Formulation::small_strain: { using Projection = ProjectionSmallStrain; return std::make_unique(std::move(fft_ptr), lengths); break; } default: { throw std::runtime_error("unknow formulation"); break; } } } /** * convenience function to create a cell (avoids having to build * and move the chain of unique_ptrs */ template , - typename FFTEngine = FFTWEngine> + typename FFTEngine = muFFT::FFTWEngine> inline Cell make_cell(Ccoord_t resolutions, Rcoord_t lengths, Formulation form) { auto && input = cell_input(resolutions, lengths, form); auto cell{Cell{std::move(input)}}; return cell; } template , typename FFTEngine = FFTWEngine> std::shared_ptr> make_cell_base_ptr_cell_base(Ccoord_t resolutions, Rcoord_t lengths, Formulation form) { auto && input = cell_input(resolutions, lengths, form); // auto cell{Cell{std::move(input)}}; return std::make_shared>(std::move(input)); } #ifdef WITH_MPI /** * Create a unique ptr to a parallel Projection operator (with appropriate * FFT_engine) to be used in a cell constructor */ - template > + template > inline std::unique_ptr> parallel_cell_input(Ccoord_t resolutions, Rcoord_t lengths, - Formulation form, const Communicator & comm) { + Formulation form, const muFFT::Communicator & comm) { auto fft_ptr{std::make_unique( resolutions, dof_for_formulation(form, DimM), comm)}; switch (form) { case Formulation::finite_strain: { using Projection = ProjectionFiniteStrainFast; return std::make_unique(std::move(fft_ptr), lengths); break; } case Formulation::small_strain: { using Projection = ProjectionSmallStrain; return std::make_unique(std::move(fft_ptr), lengths); break; } default: { throw std::runtime_error("unknown formulation"); break; } } } /** * convenience function to create a parallel cell (avoids having to build * and move the chain of unique_ptrs */ template , - typename FFTEngine = FFTWMPIEngine> + typename FFTEngine = muFFT::FFTWMPIEngine> inline Cell make_parallel_cell(Ccoord_t resolutions, Rcoord_t lengths, Formulation form, - const Communicator & comm) { + const muFFT::Communicator & comm) { auto && input = parallel_cell_input( resolutions, lengths, form, comm); auto cell{Cell{std::move(input)}}; return cell; } #endif /* WITH_MPI */ } // namespace muSpectre #endif // SRC_CELL_CELL_FACTORY_HH_ diff --git a/src/cell/cell_traits.hh b/src/cell/cell_traits.hh index 442e9b0..d1adda3 100644 --- a/src/cell/cell_traits.hh +++ b/src/cell/cell_traits.hh @@ -1,58 +1,59 @@ /** * @file cell_traits.hh * * @author Till Junge * * @date 19 Jan 2018 * * @brief Provides traits for Eigen solvers to be able to use Cells * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#include "common/common.hh" +#include "common/muSpectre_common.hh" #include #ifndef SRC_CELL_CELL_TRAITS_HH_ #define SRC_CELL_CELL_TRAITS_HH_ namespace muSpectre { - template class CellAdaptor; + template + class CellAdaptor; } // namespace muSpectre namespace Eigen { namespace internal { using Dim_t = muSpectre::Dim_t; //!< universal index type using Real = muSpectre::Real; //!< universal real value type template struct traits> : public Eigen::internal::traits> {}; } // namespace internal } // namespace Eigen #endif // SRC_CELL_CELL_TRAITS_HH_ diff --git a/src/common/common.cc b/src/common/common.cc index 062d3a8..f7e01c0 100644 --- a/src/common/common.cc +++ b/src/common/common.cc @@ -1,146 +1,147 @@ /** * @file common.cc * * @author Till Junge * * @date 15 Nov 2017 * * @brief Implementation for common functions * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#include "common/common.hh" +#include "common/muSpectre_common.hh" #include +#include namespace muSpectre { /* ---------------------------------------------------------------------- */ std::ostream & operator<<(std::ostream & os, Formulation f) { switch (f) { case Formulation::small_strain: { os << "small_strain"; break; } case Formulation::finite_strain: { os << "finite_strain"; break; } default: throw std::runtime_error("unknown formulation."); break; } return os; } /* ---------------------------------------------------------------------- */ std::ostream & operator<<(std::ostream & os, StressMeasure s) { switch (s) { case StressMeasure::Cauchy: { os << "Cauchy"; break; } case StressMeasure::PK1: { os << "PK1"; break; } case StressMeasure::PK2: { os << "PK2"; break; } case StressMeasure::Kirchhoff: { os << "Kirchhoff"; break; } case StressMeasure::Biot: { os << "Biot"; break; } case StressMeasure::Mandel: { os << "Mandel"; break; } default: throw std::runtime_error("a stress measure must be missing"); break; } return os; } /* ---------------------------------------------------------------------- */ std::ostream & operator<<(std::ostream & os, StrainMeasure s) { switch (s) { case StrainMeasure::Gradient: { os << "Gradient"; break; } case StrainMeasure::Infinitesimal: { os << "Infinitesimal"; break; } case StrainMeasure::GreenLagrange: { os << "Green-Lagrange"; break; } case StrainMeasure::Biot: { os << "Biot"; break; } case StrainMeasure::Log: { os << "Logarithmic"; break; } case StrainMeasure::Almansi: { os << "Almansi"; break; } case StrainMeasure::RCauchyGreen: { os << "Right Cauchy-Green"; break; } case StrainMeasure::LCauchyGreen: { os << "Left Cauchy-Green"; break; } default: throw std::runtime_error("a strain measure must be missing"); } return os; } /* ---------------------------------------------------------------------- */ void banner(std::string name, Uint year, std::string cpy_holder) { std::cout << std::endl << "µSpectre " << name << std::endl << "Copyright © " << year << " " << cpy_holder << std::endl << "This program comes with ABSOLUTELY NO WARRANTY." << std::endl << "This is free software, and you are welcome to redistribute it" << std::endl << "under certain conditions, see the license file." << std::endl << std::endl; } } // namespace muSpectre diff --git a/src/common/geometry.hh b/src/common/geometry.hh index eaaeb4f..9c8d3d6 100644 --- a/src/common/geometry.hh +++ b/src/common/geometry.hh @@ -1,502 +1,502 @@ /** * @file geometry.hh * * @author Till Junge * * @date 18 Apr 2018 * * @brief Geometric calculation helpers * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Emacs; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ -#include "common/common.hh" -#include "common/tensor_algebra.hh" -#include "common/eigen_tools.hh" +#include "common/muSpectre_common.hh" +#include +#include #include #include #include #ifndef SRC_COMMON_GEOMETRY_HH_ #define SRC_COMMON_GEOMETRY_HH_ namespace muSpectre { /** * The rotation matrices depend on the order in which we rotate * around different axes. See [[ * https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix ]] to * find the matrices */ enum class RotationOrder { Z, XZXEuler, XYXEuler, YXYEuler, YZYEuler, ZYZEuler, ZXZEuler, XZYTaitBryan, XYZTaitBryan, YXZTaitBryan, YZXTaitBryan, ZYXTaitBryan, ZXYTaitBryan }; namespace internal { template struct DefaultOrder { constexpr static RotationOrder value{RotationOrder::ZXYTaitBryan}; }; template <> struct DefaultOrder { constexpr static RotationOrder value{RotationOrder::Z}; }; } // namespace internal template class RotatorBase { public: using RotMat_t = Eigen::Matrix; //! Default constructor RotatorBase() = delete; explicit RotatorBase(const RotMat_t rotation_matrix_input) : rot_mat{rotation_matrix_input} {} //! Copy constructor RotatorBase(const RotatorBase & other) = default; //! Move constructor RotatorBase(RotatorBase && other) = default; //! Destructor virtual ~RotatorBase() = default; //! Copy assignment operator RotatorBase & operator=(const RotatorBase & other) = default; //! Move assignment operator RotatorBase & operator=(RotatorBase && other) = default; /** * Applies the rotation into the frame defined by the rotation * matrix * * @param input is a first-, second-, or fourth-rank tensor * (column vector, square matrix, or T4Matrix, or a Eigen::Map of * either of these, or an expression that evaluates into any of * these) */ template inline decltype(auto) rotate(In_t && input); /** * Applies the rotation back out from the frame defined by the * rotation matrix * * @param input is a first-, second-, or fourth-rank tensor * (column vector, square matrix, or T4Matrix, or a Eigen::Map of * either of these, or an expression that evaluates into any of * these) */ template inline decltype(auto) rotate_back(In_t && input); const RotMat_t & get_rot_mat() const { return this->rot_mat; } void set_rot_mat(const Eigen::Ref & mat_inp) { this->rot_mat = mat_inp; } protected: EIGEN_MAKE_ALIGNED_OPERATOR_NEW; RotMat_t rot_mat; }; template ::value> class RotatorAngle : public RotatorBase { static_assert(((Dim == twoD) and(Order == RotationOrder::Z)) or ((Dim == threeD) and(Order != RotationOrder::Z)), "In 2d, only order 'Z' makes sense. In 3d, it doesn't"); public: using Parent = RotatorBase; using Angles_t = Eigen::Matrix; using RotMat_t = Eigen::Matrix; //! Default constructor RotatorAngle() = delete; explicit RotatorAngle(const Eigen::Ref & angles_inp) : Parent(this->compute_rotation_matrix_angle(angles_inp)), angles{angles_inp} {} //! Copy constructor RotatorAngle(const RotatorAngle & other) = default; //! Move constructor RotatorAngle(RotatorAngle && other) = default; //! Destructor virtual ~RotatorAngle() = default; //! Copy assignment operator RotatorAngle & operator=(const RotatorAngle & other) = default; //! Move assignment operator RotatorAngle & operator=(RotatorAngle && other) = default; protected: inline RotMat_t compute_rotation_matrix_angle(Angles_t angles); inline RotMat_t compute_this_rotation_matrix_angle() { return compute_rotation_matrix(this->angles); } EIGEN_MAKE_ALIGNED_OPERATOR_NEW; Angles_t angles; private: }; /* ---------------------------------------------------------------------- */ namespace internal { template struct RotationMatrixComputerAngle {}; template struct RotationMatrixComputerAngle { constexpr static Dim_t Dim{twoD}; using RotMat_t = typename RotatorAngle::RotMat_t; using Angles_t = typename RotatorAngle::Angles_t; inline static decltype(auto) compute(const Eigen::Ref & angles) { static_assert(Order == RotationOrder::Z, "Two-d rotations can only be around the z axis"); return RotMat_t(Eigen::Rotation2Dd(angles(0))); } }; template struct RotationMatrixComputerAngle { constexpr static Dim_t Dim{threeD}; using RotMat_t = typename RotatorAngle::RotMat_t; using Angles_t = typename RotatorAngle::Angles_t; inline static decltype(auto) compute(const Eigen::Ref & angles) { static_assert(Order != RotationOrder::Z, "three-d rotations cannot only be around the z axis"); switch (Order) { case RotationOrder::ZXZEuler: { return RotMat_t( (Eigen::AngleAxisd(angles(0), Eigen::Vector3d::UnitZ()) * Eigen::AngleAxisd(angles(1), Eigen::Vector3d::UnitX()) * Eigen::AngleAxisd(angles(2), Eigen::Vector3d::UnitZ()))); break; } case RotationOrder::ZXYTaitBryan: { return RotMat_t( (Eigen::AngleAxisd(angles(0), Eigen::Vector3d::UnitZ()) * Eigen::AngleAxisd(angles(1), Eigen::Vector3d::UnitX()) * Eigen::AngleAxisd(angles(2), Eigen::Vector3d::UnitY()))); } default: { throw std::runtime_error("not yet implemented."); } } } }; } // namespace internal /* ---------------------------------------------------------------------- */ template auto RotatorAngle::compute_rotation_matrix_angle(Angles_t angles) -> RotMat_t { return internal::RotationMatrixComputerAngle::compute(angles); } /* ---------------------------------------------------------------------- */ /** * this class is used to make the vector a aligned to the vec b by means of a rotation system, the input for the constructor is the vector itself and the functions rotate and rotate back would be available as they exist in the parent class (RotatorBase) and can be used in order to do the functionality of the class */ template class RotatorTwoVec : public RotatorBase { public: using Parent = RotatorBase; using Vec_t = Eigen::Matrix; using RotMat_t = Eigen::Matrix; //! Default constructor RotatorTwoVec() = delete; RotatorTwoVec(Vec_t vec_a_inp, Vec_t vec_b_inp) : Parent(this->compute_rotation_matrix_TwoVec(vec_a_inp, vec_b_inp)), vec_ref{vec_a_inp}, vec_des{vec_b_inp} {} //! Copy constructor RotatorTwoVec(const RotatorTwoVec & other) = default; //! Move constructor RotatorTwoVec(RotatorTwoVec && other) = default; //! Destructor virtual ~RotatorTwoVec() = default; //! Copy assignment operator RotatorTwoVec & operator=(const RotatorTwoVec & other) = default; //! Move assignment operator RotatorTwoVec & operator=(RotatorTwoVec && other) = default; protected: inline RotMat_t compute_rotation_matrix_TwoVec(Vec_t vec_ref, Vec_t vec_des); inline RotMat_t compute_this_rotation_matrix_TwoVec() { return compute_rotation_matrix(this->vec_ref, this->vec_des); } EIGEN_MAKE_ALIGNED_OPERATOR_NEW; Vec_t vec_ref, vec_des; private: }; /* ---------------------------------------------------------------------- */ namespace internal { template struct RotationMatrixComputerTwoVec {}; template <> struct RotationMatrixComputerTwoVec { constexpr static Dim_t Dim{twoD}; using RotMat_t = typename RotatorTwoVec::RotMat_t; using Vec_t = typename RotatorTwoVec::Vec_t; inline static RotMat_t compute(Vec_t vec_ref, Vec_t vec_des) { Real v_ref_norm = sqrt(vec_ref(0) * vec_ref(0) + vec_ref(1) * vec_ref(1)); Real v_des_norm = sqrt(vec_des(0) * vec_des(0) + vec_des(1) * vec_des(1)); RotMat_t ret_mat; ret_mat(0, 0) = ret_mat(1, 1) = (((vec_ref(0) / v_ref_norm) * (vec_des(0) / v_des_norm)) + ((vec_des(1) / v_des_norm) * (vec_ref(1) / v_ref_norm))); ret_mat(1, 0) = (((vec_ref(0) / v_ref_norm) * (vec_des(1) / v_des_norm)) - ((vec_des(0) / v_des_norm) * (vec_ref(1) / v_ref_norm))); ret_mat(0, 1) = -ret_mat(1, 0); return ret_mat; } }; template <> struct RotationMatrixComputerTwoVec { constexpr static Dim_t Dim{threeD}; using RotMat_t = typename RotatorTwoVec::RotMat_t; using Vec_t = typename RotatorTwoVec::Vec_t; inline static RotMat_t compute(Vec_t vec_ref, Vec_t vec_des) { return Eigen::Quaternion::FromTwoVectors(vec_ref, vec_des) .normalized() .toRotationMatrix(); } }; } // namespace internal /* ---------------------------------------------------------------------- */ template auto RotatorTwoVec::compute_rotation_matrix_TwoVec(Vec_t vec_ref, Vec_t vec_des) -> RotMat_t { return internal::RotationMatrixComputerTwoVec::compute(vec_ref, vec_des); } /* ---------------------------------------------------------------------- */ /** * this class is used to make a vector aligned to x-axis of the coordinate system, the input for the constructor is the vector itself and the functions rotate and rotate back would be available as they exist in the parent class (RotatorBase) nad can be used in order to do the functionality of the class */ template class RotatorNormal : public RotatorBase { public: using Parent = RotatorBase; using Vec_t = Eigen::Matrix; using RotMat_t = Eigen::Matrix; //! Default constructor RotatorNormal() = delete; explicit RotatorNormal(Vec_t vec) : Parent(this->compute_rotation_matrix_normal(vec)), vec{vec} {} //! Copy constructor RotatorNormal(const RotatorNormal & other) = default; //! Move constructor RotatorNormal(RotatorNormal && other) = default; //! Destructor virtual ~RotatorNormal() = default; //! Copy assignment operator RotatorNormal & operator=(const RotatorNormal & other) = default; //! Move assignment operator RotatorNormal & operator=(RotatorNormal && other) = default; protected: inline RotMat_t compute_rotation_matrix_normal(Vec_t vec); inline RotMat_t compute_this_rotation_matrix_normal() { return compute_rotation_matrix_normal(this->vec); } EIGEN_MAKE_ALIGNED_OPERATOR_NEW; Vec_t vec; private: }; /* ---------------------------------------------------------------------- */ namespace internal { template struct RotationMatrixComputerNormal {}; template <> struct RotationMatrixComputerNormal { constexpr static Dim_t Dim{twoD}; using RotMat_t = typename RotatorTwoVec::RotMat_t; using Vec_t = typename RotatorTwoVec::Vec_t; inline static RotMat_t compute(Vec_t vec) { Real vec_norm = sqrt(vec(0) * vec(0) + vec(1) * vec(1)); Vec_t x; x << 1.0, 0.0; RotMat_t ret_mat; ret_mat(0, 0) = ret_mat(1, 1) = ((vec(0) / vec_norm) * x(0)); ret_mat(1, 0) = -(-(vec(1) / vec_norm) * x(0)); ret_mat(0, 1) = -ret_mat(1, 0); return ret_mat; } }; template <> struct RotationMatrixComputerNormal { constexpr static Dim_t Dim{threeD}; using RotMat_t = typename RotatorTwoVec::RotMat_t; using Vec_t = typename RotatorTwoVec::Vec_t; inline static RotMat_t compute(Vec_t vec) { Real eps = 0.1; Vec_t vec1 = vec / vec.norm(); Vec_t x(Vec_t::UnitX()); Vec_t y(Vec_t::UnitY()); Vec_t n_x = vec1.cross(x); Vec_t vec2 = ((n_x.norm() > eps) * n_x + (1 - (n_x.norm() > eps)) * (vec1.cross(y))); Vec_t vec3 = vec1.cross(vec2); RotMat_t ret_mat; ret_mat << vec1(0), vec2(0) / vec2.norm(), vec3(0) / vec3.norm(), vec1(1), vec2(1) / vec2.norm(), vec3(1) / vec3.norm(), vec1(2), vec2(2) / vec2.norm(), vec3(2) / vec3.norm(); return ret_mat; } }; } // namespace internal /* ---------------------------------------------------------------------- */ template auto RotatorNormal::compute_rotation_matrix_normal(Vec_t vec) -> RotMat_t { return internal::RotationMatrixComputerNormal::compute(vec); } /* ---------------------------------------------------------------------- */ namespace internal { template struct RotationHelper {}; /* ---------------------------------------------------------------------- */ template <> struct RotationHelper { template inline static decltype(auto) rotate(In_t && input, Rot_t && R) { return R * input; } }; /* ---------------------------------------------------------------------- */ template <> struct RotationHelper { template inline static decltype(auto) rotate(In_t && input, Rot_t && R) { return R * input * R.transpose(); } }; /* ---------------------------------------------------------------------- */ template <> struct RotationHelper { template inline static decltype(auto) rotate(In_t && input, Rot_t && R) { - constexpr Dim_t Dim{EigenCheck::tensor_dim::value}; + constexpr Dim_t Dim{muGrid::EigenCheck::tensor_dim::value}; auto && rotator_forward{ Matrices::outer_under(R.transpose(), R.transpose())}; auto && rotator_back = Matrices::outer_under(R, R); - // unclear behaviour. When I return this value as an - // expression, clange segfaults or returns an uninitialised - // tensor - return T4Mat(rotator_back * input * rotator_forward); + // Clarification. When I return this value as an + // expression, clang segfaults or returns an uninitialised + // tensor, hence the explicit cast into a T4Mat. + return muGrid::T4Mat(rotator_back * input * rotator_forward); } }; } // namespace internal /* ---------------------------------------------------------------------- */ template template auto RotatorBase::rotate(In_t && input) -> decltype(auto) { - constexpr Dim_t tensor_rank{EigenCheck::tensor_rank::value}; + constexpr Dim_t tensor_rank{muGrid::EigenCheck::tensor_rank::value}; return internal::RotationHelper::rotate( std::forward(input), this->rot_mat); } /* ---------------------------------------------------------------------- */ template template auto RotatorBase::rotate_back(In_t && input) -> decltype(auto) { - constexpr Dim_t tensor_rank{EigenCheck::tensor_rank::value}; + constexpr Dim_t tensor_rank{muGrid::EigenCheck::tensor_rank::value}; return internal::RotationHelper::rotate( std::forward(input), this->rot_mat.transpose()); } } // namespace muSpectre #endif // SRC_COMMON_GEOMETRY_HH_ diff --git a/src/common/common.hh b/src/common/muSpectre_common.hh similarity index 71% rename from src/common/common.hh rename to src/common/muSpectre_common.hh index 526ffb1..968df63 100644 --- a/src/common/common.hh +++ b/src/common/muSpectre_common.hh @@ -1,325 +1,255 @@ /** * @file common.hh * * @author Till Junge * * @date 01 May 2017 * * @brief Small definitions of commonly used types throughout µSpectre * * @section LICENSE * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#include -#include -#include -#include +#include +#include + +#include + #include -#include -#ifndef SRC_COMMON_COMMON_HH_ -#define SRC_COMMON_COMMON_HH_ +#ifndef SRC_COMMON_MUSPECTRE_COMMON_HH_ +#define SRC_COMMON_MUSPECTRE_COMMON_HH_ namespace muSpectre { - /** - * Eigen uses signed integers for dimensions. For consistency, - µSpectre uses them througout the code. needs to represent -1 for - eigen - */ - using Dim_t = int; + using muGrid::Dim_t; - constexpr Dim_t oneD{1}; //!< constant for a one-dimensional problem - constexpr Dim_t twoD{2}; //!< constant for a two-dimensional problem - constexpr Dim_t threeD{3}; //!< constant for a three-dimensional problem - constexpr Dim_t firstOrder{1}; //!< constant for vectors - constexpr Dim_t secondOrder{2}; //!< constant second-order tensors - constexpr Dim_t fourthOrder{4}; //!< constant fourth-order tensors + using muGrid::Complex; + using muGrid::Int; + using muGrid::Real; + using muGrid::Uint; - //@{ - //! @anchor scalars - //! Scalar types used for mathematical calculations - using Uint = unsigned int; - using Int = int; - using Real = double; - using Complex = std::complex; - //@} + using muGrid::oneD; + using muGrid::threeD; + using muGrid::twoD; - //! Ccoord_t are cell coordinates, i.e. integer coordinates - template - using Ccoord_t = std::array; - //! Real space coordinates - template - using Rcoord_t = std::array; + using muGrid::firstOrder; + using muGrid::fourthOrder; + using muGrid::secondOrder; - /** - * Allows inserting `muSpectre::Ccoord_t` and `muSpectre::Rcoord_t` - * into `std::ostream`s - */ - template - std::ostream & operator<<(std::ostream & os, - const std::array & index) { - os << "("; - for (size_t i = 0; i < dim - 1; ++i) { - os << index[i] << ", "; - } - os << index.back() << ")"; - return os; - } + using muGrid::Ccoord_t; + using muGrid::Rcoord_t; - //! element-wise division - template - Rcoord_t operator/(const Rcoord_t & a, const Rcoord_t & b) { - Rcoord_t retval{a}; - for (size_t i = 0; i < dim; ++i) { - retval[i] /= b[i]; - } - return retval; - } + using muGrid::apply; + using muGrid::optional; - //! element-wise division - template - Rcoord_t operator/(const Rcoord_t & a, const Ccoord_t & b) { - Rcoord_t retval{a}; - for (size_t i = 0; i < dim; ++i) { - retval[i] /= b[i]; - } - return retval; - } - - //! convenience definitions - constexpr Real pi{3.1415926535897932384626433}; - - //! compile-time potentiation required for field-size computations - template - constexpr R ipow(R base, I exponent) { - static_assert(std::is_integral::value, "Type must be integer"); - R retval{1}; - for (I i = 0; i < exponent; ++i) { - retval *= base; - } - return retval; - } + namespace Tensors = ::muGrid::Tensors; + namespace Matrices = ::muGrid::Matrices; /** * Copyright banner to be printed to the terminal by executables * Arguments are the executable's name, year of writing and the name * + address of the copyright holder */ void banner(std::string name, Uint year, std::string cpy_holder); - /** - * Planner flags for FFT (follows FFTW, hopefully this choice will - * be compatible with alternative FFT implementations) - * @enum muSpectre::FFT_PlanFlags - */ - enum class FFT_PlanFlags { - estimate, //!< cheapest plan for slowest execution - measure, //!< more expensive plan for fast execution - patient //!< very expensive plan for fastest execution - }; - //! continuum mechanics flags enum class Formulation { finite_strain, //!< causes evaluation in PK1(F) small_strain, //!< causes evaluation in σ(ε) small_strain_sym //!< symmetric storage as vector ε }; //! split cell flags enum class SplitCell { laminate, simple, no }; //! finite differences flags enum class FiniteDiff { forward, //!< ∂f/∂x ≈ (f(x+Δx) - f(x))/Δx backward, //!< ∂f/∂x ≈ (f(x) - f(x-Δx))/Δx centred //!< ∂f/∂x ≈ (f(x+Δx) - f(x-Δx))/2Δx }; /** * compile time computation of voigt vector */ template constexpr Dim_t vsize(Dim_t dim) { if (sym) { return (dim * (dim - 1) / 2 + dim); } else { return dim * dim; } } //! compute the number of degrees of freedom to store for the strain //! tenor given dimension dim constexpr Dim_t dof_for_formulation(const Formulation form, const Dim_t dim) { switch (form) { case Formulation::small_strain_sym: { return vsize(dim); break; } default: - return ipow(dim, 2); + return muGrid::ipow(dim, 2); break; } } //! inserts `muSpectre::Formulation`s into `std::ostream`s std::ostream & operator<<(std::ostream & os, Formulation f); /* ---------------------------------------------------------------------- */ //! Material laws can declare which type of stress measure they provide, //! and µSpectre will handle conversions enum class StressMeasure { Cauchy, //!< Cauchy stress σ PK1, //!< First Piola-Kirchhoff stress PK2, //!< Second Piola-Kirchhoff stress Kirchhoff, //!< Kirchhoff stress τ Biot, //!< Biot stress Mandel, //!< Mandel stress no_stress_ //!< only for triggering static_asserts }; //! inserts `muSpectre::StressMeasure`s into `std::ostream`s std::ostream & operator<<(std::ostream & os, StressMeasure s); /* ---------------------------------------------------------------------- */ //! Material laws can declare which type of strain measure they require and //! µSpectre will provide it enum class StrainMeasure { Gradient, //!< placement gradient (δy/δx) Infinitesimal, //!< small strain tensor .5(∇u + ∇uᵀ) GreenLagrange, //!< Green-Lagrange strain .5(Fᵀ·F - I) Biot, //!< Biot strain Log, //!< logarithmic strain Almansi, //!< Almansi strain RCauchyGreen, //!< Right Cauchy-Green tensor LCauchyGreen, //!< Left Cauchy-Green tensor no_strain_ //!< only for triggering static_assert }; //! inserts `muSpectre::StrainMeasure`s into `std::ostream`s std::ostream & operator<<(std::ostream & os, StrainMeasure s); /* ---------------------------------------------------------------------- */ /** * all isotropic elastic moduli to identify conversions, such as E * = µ(3λ + 2µ)/(λ+µ). For the full description, see * https://en.wikipedia.org/wiki/Lam%C3%A9_parameters * Not all the conversions are implemented, so please add as needed */ enum class ElasticModulus { Bulk, //!< Bulk modulus K K = Bulk, //!< alias for ``ElasticModulus::Bulk`` Young, //!< Young's modulus E E = Young, //!< alias for ``ElasticModulus::Young`` lambda, //!< Lamé's first parameter λ Shear, //!< Shear modulus G or µ G = Shear, //!< alias for ``ElasticModulus::Shear`` mu = Shear, //!< alias for ``ElasticModulus::Shear`` Poisson, //!< Poisson's ratio ν nu = Poisson, //!< alias for ``ElasticModulus::Poisson`` Pwave, //!< P-wave modulus M M = Pwave, //!< alias for ``ElasticModulus::Pwave`` no_modulus_ }; //!< only for triggering static_asserts /** * define comparison in order to exploit that moduli can be * expressed in terms of any two other moduli in any order (e.g. K * = K(E, ν) = K(ν, E) */ constexpr inline bool operator<(ElasticModulus A, ElasticModulus B) { return static_cast(A) < static_cast(B); } /* ---------------------------------------------------------------------- */ /** Compile-time function to g strain measure stored by muSpectre depending on the formulation **/ constexpr StrainMeasure get_stored_strain_type(Formulation form) { switch (form) { case Formulation::finite_strain: { return StrainMeasure::Gradient; break; } case Formulation::small_strain: { return StrainMeasure::Infinitesimal; break; } default: return StrainMeasure::no_strain_; break; } } /** Compile-time function to g stress measure stored by muSpectre depending on the formulation **/ constexpr StressMeasure get_stored_stress_type(Formulation form) { switch (form) { case Formulation::finite_strain: { return StressMeasure::PK1; break; } case Formulation::small_strain: { return StressMeasure::Cauchy; break; } default: return StressMeasure::no_stress_; break; } } /* ---------------------------------------------------------------------- */ /** Compile-time functions to get the stress and strain measures after they may have been modified by choosing a formulation. For instance, a law that expecs a Green-Lagrange strain as input will get the infinitesimal strain tensor instead in a small strain computation **/ constexpr StrainMeasure get_formulation_strain_type(Formulation form, StrainMeasure expected) { switch (form) { case Formulation::finite_strain: { return expected; break; } case Formulation::small_strain: { return get_stored_strain_type(form); break; } default: return StrainMeasure::no_strain_; break; } } } // namespace muSpectre -#ifndef EXPLICITLY_TURNED_ON_CXX17 -#include "common/utilities.hh" -#endif - -#endif // SRC_COMMON_COMMON_HH_ +#endif // SRC_COMMON_MUSPECTRE_COMMON_HH_ diff --git a/src/common/voigt_conversion.hh b/src/common/voigt_conversion.hh index 564a78a..8441aaa 100644 --- a/src/common/voigt_conversion.hh +++ b/src/common/voigt_conversion.hh @@ -1,170 +1,170 @@ /** * @file voigt_conversion.hh * * @author Till Junge * * @date 02 May 2017 * * @brief utilities to transform vector notation arrays into voigt notation * arrays and vice-versa * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Emacs; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #ifndef SRC_COMMON_VOIGT_CONVERSION_HH_ #define SRC_COMMON_VOIGT_CONVERSION_HH_ -#include "common/common.hh" +#include "common/muSpectre_common.hh" #include #include #include namespace muSpectre { /** * implements a bunch of static functions to convert between full * and Voigt notation of tensors */ template class VoigtConversion { public: VoigtConversion(); //! obtain a fourth order voigt matrix from a tensor template inline static void fourth_to_voigt(const Tens4 & t, Voigt & v); //! return a fourth order voigt matrix from a tensor template inline static Eigen::Matrix(dim), vsize(dim)> fourth_to_voigt(const Tens4 & t); //! return a fourth order non-symmetric voigt matrix from a tensor template inline static Eigen::Matrix(dim), vsize(dim)> fourth_to_2d(const Tens4 & t) { return fourth_to_voigt(t); } //! probably obsolete template inline static void second_to_voigt(const Tens2 & t, Voigt & v); //! probably obsolete template inline static void gradient_to_voigt_strain(const Tens2 & F, Voigt & v); //! probably obsolete template inline static void gradient_to_voigt_GreenLagrange_strain(const Tens2 & F, Voigt & v); //! probably obsolete template inline static void stress_from_voigt(const Voigt & v, Tens2 & sigma); static decltype(auto) get_vec_vec() { return vec_vec; } public: //! matrix of vector index I as function of tensor indices i,j static const Eigen::Matrix mat; //! matrix of vector index I as function of tensor indices i,j static const Eigen::Matrix sym_mat; //! array of matrix indices ij as function of vector index I static const Eigen::Matrix vec; //! factors to multiply the strain by for voigt notation static const Eigen::Matrix factors; /** * reordering between a row/column in voigt vs col-major matrix * (e.g., stiffness tensor) */ static const Eigen::Matrix vec_vec; }; //----------------------------------------------------------------------------// //----------------------------------------------------------------------------// template template inline void VoigtConversion::fourth_to_voigt(const Tens4 & t, Voigt & v) { // upper case indices for Voigt notation, lower case for standard tensorial for (Dim_t I = 0; I < vsize(dim); ++I) { auto && i = vec(I, 0); auto && j = vec(I, 1); for (Dim_t J = 0; J < vsize(dim); ++J) { auto && k = vec(J, 0); auto && l = vec(J, 1); v(I, J) = t(i, j, k, l); } } } //----------------------------------------------------------------------------// template template inline Eigen::Matrix(dim), vsize(dim)> VoigtConversion::fourth_to_voigt(const Tens4 & t) { using V_t = Eigen::Matrix(dim), vsize(dim)>; V_t temp; fourth_to_voigt(t, temp); return temp; } //----------------------------------------------------------------------------// template template inline void VoigtConversion::second_to_voigt(const Tens2 & F, Voigt & v) { for (Dim_t I = 0; I < vsize(dim); ++I) { auto && i = vec(I, 0); auto && j = vec(I, 1); v(I) = F(i, j); } } //----------------------------------------------------------------------------// template template inline void VoigtConversion::gradient_to_voigt_strain(const Tens2 & F, Voigt & v) { for (Dim_t I = 0; I < vsize(dim); ++I) { auto && i = vec(I, 0); auto && j = vec(I, 1); v(I) = (F(i, j) + F(j, i)) / 2 * factors(I); } } //----------------------------------------------------------------------------// template template inline void VoigtConversion::gradient_to_voigt_GreenLagrange_strain(const Tens2 & F, Voigt & v) { using mat = Eigen::Matrix; mat E = 0.5 * (F.transpose() * F - mat::Identity()); for (Dim_t I = 0; I < vsize(dim); ++I) { auto && i = vec(I, 0); auto && j = vec(I, 1); v(I) = E(i, j) * factors(I); } } } // namespace muSpectre #endif // SRC_COMMON_VOIGT_CONVERSION_HH_ diff --git a/src/fft/CMakeLists.txt b/src/fft/CMakeLists.txt deleted file mode 100644 index ae00e82..0000000 --- a/src/fft/CMakeLists.txt +++ /dev/null @@ -1,113 +0,0 @@ -# ============================================================================= -# file CMakeLists.txt -# -# @author Till Junge -# -# @date 08 Jan 2018 -# -# @brief configuration for fft-related files -# -# @section LICENSE -# -# Copyright © 2018 Till Junge -# -# µSpectre is free software; you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3, or (at -# your option) any later version. -# -# µSpectre is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with µSpectre; see the file COPYING. If not, write to the -# Free Software Foundation, Inc., 59 Temple Place - Suite 330, -# Boston, MA 02111-1307, USA. -# -# Additional permission under GNU GPL version 3 section 7 -# -# If you modify this Program, or any covered work, by linking or combining it -# with proprietary FFT implementations or numerical libraries, containing parts -# covered by the terms of those libraries' licenses, the licensors of this -# Program grant you additional permission to convey the resulting work. -# ============================================================================= - -################################################################################ -if (${MPI_PARALLEL}) - set(USE_FFTWMPI "ON" CACHE BOOL "If on, the mpi-parallel FFTW engine is built") - set(USE_PFFT "OFF" CACHE BOOL "If on, the mpi-parallel PFFT engine is built") - - ############################################################################## - if (${USE_FFTWMPI}) - find_package(FFTWMPI) - - if (NOT ${FFTWMPI_FOUND}) - message (SEND_ERROR "You chose FFTWMPI but CMake cannot find it") - endif (NOT ${FFTWMPI_FOUND}) - - list(APPEND PRIVATE_MUSPECTRE_LIBS - ${FFTWMPI_LIBRARIES}) - - target_include_directories(muSpectre PRIVATE ${FFTWMPI_INCLUDES}) - endif (${USE_FFTWMPI}) - - ############################################################################## - if (${USE_PFFT}) - find_package(PFFT) - - if (NOT ${PFFT_FOUND}) - message (SEND_ERROR "You chose PFFT but CMake cannot find it") - endif (NOT ${PFFT_FOUND}) - - list(APPEND PRIVATE_MUSPECTRE_LIBS - ${PFFT_LIBRARIES}) - - target_include_directories(muSpectre PUBLIC ${PFFT_INCLUDES}) - endif (${USE_PFFT}) - - ############################################################################## - if (NOT ${USE_FFTWMPI} AND NOT ${USE_PFFT}) - message (SEND_ERROR "You activated MPI but turned on none of the MPI-parallel FFT engines") - endif (NOT ${USE_FFTWMPI} AND NOT ${USE_PFFT}) - -endif(${MPI_PARALLEL}) - -set(PRIVATE_MUSPECTRE_LIBS ${PRIVATE_MUSPECTRE_LIBS} PARENT_SCOPE) - -if (${USE_FFTWMPI}) - add_definitions(-DWITH_FFTWMPI) -endif(${USE_FFTWMPI}) - -if (${USE_PFFT}) - add_definitions(-DWITH_PFFT) -endif(${USE_PFFT}) - - -set (fft_engine_SRC - ${CMAKE_CURRENT_SOURCE_DIR}/fft_utils.cc - ${CMAKE_CURRENT_SOURCE_DIR}/fft_engine_base.cc - ${CMAKE_CURRENT_SOURCE_DIR}/fftw_engine.cc - ${CMAKE_CURRENT_SOURCE_DIR}/projection_base.cc - ${CMAKE_CURRENT_SOURCE_DIR}/projection_default.cc - ${CMAKE_CURRENT_SOURCE_DIR}/projection_finite_strain.cc - ${CMAKE_CURRENT_SOURCE_DIR}/projection_small_strain.cc - ${CMAKE_CURRENT_SOURCE_DIR}/projection_finite_strain_fast.cc - ) - -if(${USE_FFTWMPI}) - set(fft_engine_SRC - ${fft_engine_SRC} - ${CMAKE_CURRENT_SOURCE_DIR}/fftwmpi_engine.cc - ) -endif(${USE_FFTWMPI}) - -if (${USE_PFFT}) - set(fft_engine_SRC - ${fft_engine_SRC} - ${CMAKE_CURRENT_SOURCE_DIR}/pfft_engine.cc - ) -endif(${USE_PFFT}) - -target_sources(muSpectre PRIVATE ${fft_engine_SRC}) diff --git a/src/libmufft/CMakeLists.txt b/src/libmufft/CMakeLists.txt new file mode 100644 index 0000000..1f77a74 --- /dev/null +++ b/src/libmufft/CMakeLists.txt @@ -0,0 +1,134 @@ +# ============================================================================= +# file CMakeLists.txt +# +# @author Nicolas Richart +# +# @date 24 Jan 2019 +# +# @brief Configuration for libmuFFT +# +# @section LICENSE +# +# Copyright © 2018 Till Junge +# +# µGrid is free software; you can redistribute it and/or modify it under the +# terms of the GNU Lesser General Public License as published by the Free +# Software Foundation, either version 3, or (at your option) any later version. +# +# µGrid is distributed in the hope that it will be useful, but WITHOUT ANY +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR +# A PARTICULAR PURPOSE. See the GNU General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with µGrid; see the file COPYING. If not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +# +# Additional permission under GNU GPL version 3 section 7 +# +# If you modify this Program, or any covered work, by linking or combining it +# with proprietary FFT implementations or numerical libraries, containing parts +# covered by the terms of those libraries' licenses, the licensors of this +# Program grant you additional permission to convey the resulting work. +# ============================================================================= +project(muFFT) +cmake_minimum_required(VERSION 3.5) + +add_library(muFFT "") + +set(mufft_SRCS + fft_utils.cc + fft_engine_base.cc + fftw_engine.cc + ) + +set(fft_engine_FFTWMPI_SRCS + fftwmpi_engine.cc + ) +set(fft_engine_PFFT_SRCS + pfft_engine.cc + ) + +find_package(FFTW3 COMPONENTS double REQUIRED) +target_link_libraries(muFFT PUBLIC fftw3::double) + +if(${MUSPECTRE_MPI_PARALLEL}) + find_package(MPI REQUIRED) + + target_link_libraries(muFFT PUBLIC ${MPI_LIBRARIES}) + target_include_directories(muFFT SYSTEM PUBLIC ${MPI_C_INCLUDE_PATH}) + target_compile_definitions(muFFT PUBLIC -DWITH_MPI) + + option(MUFFT_USE_FFTWMPI "If on, the mpi-parallel FFTW engine is built" ON) + option(MUFFT_USE_PFFT "If on, the mpi-parallel PFFT engine is built" OFF) + + set(_using_mpi FALSE) + foreach (_fft FFTWMPI PFFT) + if (${MUFFT_USE_${_fft}}) + if("${_fft}" STREQUAL "FFTWMPI") + find_package(FFTW3 COMPONENTS double mpi REQUIRED) + target_link_libraries(muFFT PUBLIC fftw3::double::mpi) + else() + find_package(${_fft} REQUIRED) + # TODO this private should perhaps become private + target_link_libraries(muFFT PUBLIC ${${_fft}_LIBRARIES}) + target_include_directories(muFFT PUBLIC ${${_fft}_INCLUDES}) + endif() + + target_compile_definitions(muFFT PUBLIC -DWITH_${_fft}) + + list(APPEND mufft_SRCS ${fft_engine_${_fft}_SRCS}) + set(_using_mpi TRUE) + endif() + endforeach() + ############################################################################## + if(NOT ${_using_mpi}) + message(SEND_ERROR "You activated MPI but turned on none of the MPI-parallel FFT engines") + endif() +endif() + +target_sources(muFFT PRIVATE ${mufft_SRCS}) +target_link_libraries(muFFT PUBLIC ${MUFFT_NAMESPACE}muGrid) + +# defining exported include directories +target_include_directories(muFFT + INTERFACE $ + ) + +# small trick for build includes in public +set_property(TARGET muFFT APPEND PROPERTY INTERFACE_INCLUDE_DIRECTORIES + $) + + +if(MUFFT_NAMESPACE) + add_library(${MUFFT_NAMESPACE}muFFT ALIAS muFFT) +endif() + +# ------------------------------------------------------------------------------ +if(NOT MUFFT_TARGETS_EXPORT) + set(MUFFT_TARGETS_EXPORT muFFTTargets) +endif() + +install(TARGETS muFFT + EXPORT ${MUFFT_TARGETS_EXPORT} + LIBRARY + DESTINATION lib + PUBLIC_HEADER + DESTINATION include/libmufft) + +if("${MUFFT_TARGETS_EXPORT}" STREQUAL "muFFTTargets") + if(MUFFT_NAMESPACE) + set(_namespace NAMESPACE ${MUFFT_NAMESPACE}) + else() + unset(_namespace) + endif() + + install(EXPORT ${MUFFT_TARGETS_EXPORT} + ${_namespace} + DESTINATION share/cmake/${PROJECT_NAME} + COMPONENT dev) + + #Export for build tree + export(EXPORT ${MUFFT_TARGETS_EXPORT} + ${_namespace} + FILE "${CMAKE_BINARY_DIR}/${MUFFT_TARGETS_EXPORT}.cmake") +endif() diff --git a/src/common/communicator.hh b/src/libmufft/communicator.hh similarity index 91% rename from src/common/communicator.hh rename to src/libmufft/communicator.hh index ca8ccdf..4993bb7 100644 --- a/src/common/communicator.hh +++ b/src/libmufft/communicator.hh @@ -1,155 +1,155 @@ /** * @file communicator.hh * * @author Lars Pastewka * * @date 07 Mar 2018 * * @brief abstraction layer for the distributed memory communicator object * * Copyright © 2017 Till Junge * - * µSpectre is free software; you can redistribute it and/or + * µFFT is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * - * µSpectre is distributed in the hope that it will be useful, but + * µFFT is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with µSpectre; see the file COPYING. If not, write to the + * along with µFFT; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#ifndef SRC_COMMON_COMMUNICATOR_HH_ -#define SRC_COMMON_COMMUNICATOR_HH_ +#ifndef SRC_LIBMUFFT_COMMUNICATOR_HH_ +#define SRC_LIBMUFFT_COMMUNICATOR_HH_ #ifdef WITH_MPI #include #endif -namespace muSpectre { +namespace muFFT { #ifdef WITH_MPI template decltype(auto) mpi_type() {} template <> inline decltype(auto) mpi_type() { return MPI_CHAR; } template <> inline decltype(auto) mpi_type() { // NOLINT return MPI_SHORT; } template <> inline decltype(auto) mpi_type() { return MPI_INT; } template <> inline decltype(auto) mpi_type() { // NOLINT return MPI_LONG; } template <> inline decltype(auto) mpi_type() { return MPI_UNSIGNED_CHAR; } template <> inline decltype(auto) mpi_type() { // NOLINT return MPI_UNSIGNED_SHORT; } template <> inline decltype(auto) mpi_type() { return MPI_UNSIGNED; } template <> inline decltype(auto) mpi_type() { // NOLINT return MPI_UNSIGNED_LONG; } template <> inline decltype(auto) mpi_type() { return MPI_FLOAT; } template <> inline decltype(auto) mpi_type() { return MPI_DOUBLE; } //! lightweight abstraction for the MPI communicator object class Communicator { public: using MPI_Comm_ref = std::remove_pointer_t &; explicit Communicator(MPI_Comm comm = MPI_COMM_NULL) : comm{*comm} {}; ~Communicator() {} //! get rank of present process int rank() const { if (&comm == MPI_COMM_NULL) return 0; int res; MPI_Comm_rank(&this->comm, &res); return res; } //! get total number of processes int size() const { if (&comm == MPI_COMM_NULL) return 1; int res; MPI_Comm_size(&this->comm, &res); return res; } //! sum reduction on scalar types template T sum(const T & arg) const { if (&comm == MPI_COMM_NULL) return arg; T res; MPI_Allreduce(&arg, &res, 1, mpi_type(), MPI_SUM, &this->comm); return res; } MPI_Comm get_mpi_comm() { return &this->comm; } private: MPI_Comm_ref comm; }; #else /* WITH_MPI */ //! stub communicator object that doesn't communicate anything class Communicator { public: Communicator() {} ~Communicator() {} //! get rank of present process int rank() const { return 0; } //! get total number of processes int size() const { return 1; } //! sum reduction on scalar types template T sum(const T & arg) const { return arg; } }; #endif -} // namespace muSpectre +} // namespace muFFT -#endif // SRC_COMMON_COMMUNICATOR_HH_ +#endif // SRC_LIBMUFFT_COMMUNICATOR_HH_ diff --git a/src/fft/fft_engine_base.cc b/src/libmufft/fft_engine_base.cc similarity index 74% rename from src/fft/fft_engine_base.cc rename to src/libmufft/fft_engine_base.cc index 3db922e..386cd9c 100644 --- a/src/fft/fft_engine_base.cc +++ b/src/libmufft/fft_engine_base.cc @@ -1,72 +1,73 @@ /** * @file fft_engine_base.cc * * @author Till Junge * * @date 03 Dec 2017 * * @brief implementation for FFT engine base class * * Copyright © 2017 Till Junge * - * µSpectre is free software; you can redistribute it and/or + * µFFT is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * - * µSpectre is distributed in the hope that it will be useful, but + * µFFT is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with µSpectre; see the file COPYING. If not, write to the + * along with µFFT; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#include "fft/fft_engine_base.hh" +#include "fft_engine_base.hh" -namespace muSpectre { +namespace muFFT { /* ---------------------------------------------------------------------- */ template FFTEngineBase::FFTEngineBase(Ccoord resolutions, Dim_t nb_components, Communicator comm) : comm{comm}, subdomain_resolutions{resolutions}, subdomain_locations{}, - fourier_resolutions{CcoordOps::get_hermitian_sizes(resolutions)}, + fourier_resolutions{ + muGrid::CcoordOps::get_hermitian_sizes(resolutions)}, fourier_locations{}, domain_resolutions{resolutions}, - work{make_field("work space", work_space_container, - nb_components)}, - norm_factor{1. / CcoordOps::get_size(domain_resolutions)}, + work{muGrid::make_field("work space", work_space_container, + nb_components)}, + norm_factor{1. / muGrid::CcoordOps::get_size(domain_resolutions)}, nb_components{nb_components} {} /* ---------------------------------------------------------------------- */ template void FFTEngineBase::initialise(FFT_PlanFlags /*plan_flags*/) { this->work_space_container.initialise(); } /* ---------------------------------------------------------------------- */ template size_t FFTEngineBase::size() const { - return CcoordOps::get_size(this->subdomain_resolutions); + return muGrid::CcoordOps::get_size(this->subdomain_resolutions); } /* ---------------------------------------------------------------------- */ template size_t FFTEngineBase::workspace_size() const { return this->work_space_container.size(); } - template class FFTEngineBase; - template class FFTEngineBase; + template class FFTEngineBase; + template class FFTEngineBase; -} // namespace muSpectre +} // namespace muFFT diff --git a/src/fft/fft_engine_base.hh b/src/libmufft/fft_engine_base.hh similarity index 89% rename from src/fft/fft_engine_base.hh rename to src/libmufft/fft_engine_base.hh index 4760f11..13c6445 100644 --- a/src/fft/fft_engine_base.hh +++ b/src/libmufft/fft_engine_base.hh @@ -1,186 +1,186 @@ /** * @file fft_engine_base.hh * * @author Till Junge * * @date 01 Dec 2017 * * @brief Interface for FFT engines * * Copyright © 2017 Till Junge * - * µSpectre is free software; you can redistribute it and/or + * µFFT is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * - * µSpectre is distributed in the hope that it will be useful, but + * µFFT is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with µSpectre; see the file COPYING. If not, write to the + * along with µFFT; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#ifndef SRC_FFT_FFT_ENGINE_BASE_HH_ -#define SRC_FFT_FFT_ENGINE_BASE_HH_ +#ifndef SRC_LIBMUFFT_FFT_ENGINE_BASE_HH_ +#define SRC_LIBMUFFT_FFT_ENGINE_BASE_HH_ -#include "common/common.hh" -#include "common/communicator.hh" -#include "common/field_collection.hh" +#include "mufft_common.hh" +#include "communicator.hh" +#include -namespace muSpectre { +namespace muFFT { /** * Virtual base class for FFT engines. To be implemented by all * FFT_engine implementations. */ template class FFTEngineBase { public: constexpr static Dim_t sdim{DimS}; //!< spatial dimension of the cell //! cell coordinates type using Ccoord = Ccoord_t; //! global FieldCollection - using GFieldCollection_t = GlobalFieldCollection; + using GFieldCollection_t = muGrid::GlobalFieldCollection; //! local FieldCollection (for Fourier-space pixels) - using LFieldCollection_t = LocalFieldCollection; + using LFieldCollection_t = muGrid::LocalFieldCollection; //! Field type on which to apply the projection - using Field_t = TypedField; + using Field_t = muGrid::TypedField; /** * Field type holding a Fourier-space representation of a * real-valued second-order tensor field */ - using Workspace_t = TypedField; + using Workspace_t = muGrid::TypedField; /** * iterator over Fourier-space discretisation point */ using iterator = typename LFieldCollection_t::iterator; //! Default constructor FFTEngineBase() = delete; //! Constructor with cell resolutions FFTEngineBase(Ccoord resolutions, Dim_t nb_components, Communicator comm = Communicator()); //! Copy constructor FFTEngineBase(const FFTEngineBase & other) = delete; //! Move constructor FFTEngineBase(FFTEngineBase && other) = default; //! Destructor virtual ~FFTEngineBase() = default; //! Copy assignment operator FFTEngineBase & operator=(const FFTEngineBase & other) = delete; //! Move assignment operator FFTEngineBase & operator=(FFTEngineBase && other) = default; //! compute the plan, etc virtual void initialise(FFT_PlanFlags /*plan_flags*/); //! forward transform (dummy for interface) virtual Workspace_t & fft(Field_t & /*field*/) = 0; //! inverse transform (dummy for interface) virtual void ifft(Field_t & /*field*/) const = 0; /** * iterators over only those pixels that exist in frequency space * (i.e. about half of all pixels, see rfft) */ //! returns an iterator to the first pixel in Fourier space inline iterator begin() { return this->work_space_container.begin(); } //! returns an iterator past to the last pixel in Fourier space inline iterator end() { return this->work_space_container.end(); } //! nb of pixels (mostly for debugging) size_t size() const; //! nb of pixels in Fourier space size_t workspace_size() const; //! return the communicator object const Communicator & get_communicator() const { return this->comm; } //! returns the process-local resolutions of the cell const Ccoord & get_subdomain_resolutions() const { return this->subdomain_resolutions; } //! returns the process-local locations of the cell const Ccoord & get_subdomain_locations() const { return this->subdomain_locations; } //! returns the process-local resolutions of the cell in Fourier space const Ccoord & get_fourier_resolutions() const { return this->fourier_resolutions; } //! returns the process-local locations of the cell in Fourier space const Ccoord & get_fourier_locations() const { return this->fourier_locations; } //! returns the resolutions of the cell const Ccoord & get_domain_resolutions() const { return this->domain_resolutions; } //! only required for testing and debugging LFieldCollection_t & get_field_collection() { return this->work_space_container; } //! only required for testing and debugging Workspace_t & get_work_space() { return this->work; } //! factor by which to multiply projection before inverse transform (this is //! typically 1/nb_pixels for so-called unnormalized transforms (see, //! e.g. //! http://www.fftw.org/fftw3_doc/Multi_002dDimensional-DFTs-of-Real-Data.html#Multi_002dDimensional-DFTs-of-Real-Data //! or https://docs.scipy.org/doc/numpy-1.13.0/reference/routines.fft.html //! . Rather than scaling the inverse transform (which would cost one more //! loop), FFT engines provide this value so it can be used in the //! projection operator (where no additional loop is required) inline Real normalisation() const { return norm_factor; } //! return the number of components per pixel Dim_t get_nb_components() const { return nb_components; } protected: /** * Field collection in which to store fields associated with * Fourier-space points */ Communicator comm; //!< communicator LFieldCollection_t work_space_container{}; Ccoord subdomain_resolutions; //!< resolutions of the process-local //!< (subdomain) portion of the cell Ccoord subdomain_locations; // !< location of the process-local (subdomain) // portion of the cell Ccoord fourier_resolutions; //!< resolutions of the process-local (subdomain) //!< portion of the Fourier transformed data Ccoord fourier_locations; // !< location of the process-local (subdomain) // portion of the Fourier transformed data const Ccoord domain_resolutions; //!< resolutions of the full domain of the cell Workspace_t & work; //!< field to store the Fourier transform of P const Real norm_factor; //!< normalisation coefficient of fourier transform Dim_t nb_components; private: }; -} // namespace muSpectre +} // namespace muFFT -#endif // SRC_FFT_FFT_ENGINE_BASE_HH_ +#endif // SRC_LIBMUFFT_FFT_ENGINE_BASE_HH_ diff --git a/src/fft/fft_utils.cc b/src/libmufft/fft_utils.cc similarity index 86% rename from src/fft/fft_utils.cc rename to src/libmufft/fft_utils.cc index 23f6e9d..986f0df 100644 --- a/src/fft/fft_utils.cc +++ b/src/libmufft/fft_utils.cc @@ -1,57 +1,57 @@ /** * @file fft_utils.cc * * @author Till Junge * * @date 11 Dec 2017 * * @brief implementation of fft utilities * * Copyright © 2017 Till Junge * - * µSpectre is free software; you can redistribute it and/or + * µFFT is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * - * µSpectre is distributed in the hope that it will be useful, but + * µFFT is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with µSpectre; see the file COPYING. If not, write to the + * along with µFFT; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#include "fft/fft_utils.hh" +#include "fft_utils.hh" -namespace muSpectre { +namespace muFFT { /* ---------------------------------------------------------------------- */ std::valarray fft_freqs(size_t nb_samples) { std::valarray retval(nb_samples); Int N = (nb_samples - 1) / 2 + 1; // needs to be signed int for neg freqs for (Int i = 0; i < N; ++i) { retval[i] = i; } for (Int i = N; i < Int(nb_samples); ++i) { retval[i] = -Int(nb_samples) / 2 + i - N; } return retval; } /* ---------------------------------------------------------------------- */ std::valarray fft_freqs(size_t nb_samples, Real length) { return fft_freqs(nb_samples) / length; } -} // namespace muSpectre +} // namespace muFFT diff --git a/src/fft/fft_utils.hh b/src/libmufft/fft_utils.hh similarity index 90% rename from src/fft/fft_utils.hh rename to src/libmufft/fft_utils.hh index 6ddf14b..356448e 100644 --- a/src/fft/fft_utils.hh +++ b/src/libmufft/fft_utils.hh @@ -1,131 +1,131 @@ /** * @file fft_utils.hh * * @author Till Junge * * @date 06 Dec 2017 * * @brief collection of functions used in the context of spectral operations * * Copyright © 2017 Till Junge * - * µSpectre is free software; you can redistribute it and/or + * µFFT is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * - * µSpectre is distributed in the hope that it will be useful, but + * µFFT is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with µSpectre; see the file COPYING. If not, write to the + * along with µFFT; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#ifndef SRC_FFT_FFT_UTILS_HH_ -#define SRC_FFT_FFT_UTILS_HH_ +#ifndef SRC_LIBMUFFT_FFT_UTILS_HH_ +#define SRC_LIBMUFFT_FFT_UTILS_HH_ -#include "common/common.hh" +#include "mufft_common.hh" #include #include #include -namespace muSpectre { +namespace muFFT { /** * compute fft frequencies (in time (or length) units of of sampling * periods), see numpy's fftfreq function for reference */ std::valarray fft_freqs(size_t nb_samples); /** * compute fft frequencies in correct length or time units. Here, * length refers to the total size of the domain over which the fft * is taken (for instance the length of an edge of an RVE) */ std::valarray fft_freqs(size_t nb_samples, Real length); /** * Get fft_freqs for a grid */ template inline std::array, dim> fft_freqs(Ccoord_t sizes, std::array lengths) { std::array, dim> retval{}; for (size_t i = 0; i < dim; ++i) { retval[i] = std::move(fft_freqs(sizes[i], lengths[i])); } return retval; } /** * simple class encapsulating the creation, and retrieval of * wave vectors */ template class FFT_freqs { public: //! return type for wave vectors using Vector = Eigen::Matrix; //! Default constructor FFT_freqs() = delete; //! constructor with problem sizes FFT_freqs(Ccoord_t sizes, std::array lengths) : freqs{fft_freqs(sizes, lengths)} {} //! Copy constructor FFT_freqs(const FFT_freqs & other) = delete; //! Move constructor FFT_freqs(FFT_freqs && other) = default; //! Destructor virtual ~FFT_freqs() = default; //! Copy assignment operator FFT_freqs & operator=(const FFT_freqs & other) = delete; //! Move assignment operator FFT_freqs & operator=(FFT_freqs && other) = default; //! get unnormalised wave vector (in sampling units) inline Vector get_xi(const Ccoord_t ccoord) const; //! get normalised wave vector inline Vector get_unit_xi(const Ccoord_t ccoord) const { auto && xi = this->get_xi(std::move(ccoord)); return xi / xi.norm(); } protected: //! container for frequencies ordered by spatial dimension const std::array, dim> freqs; private: }; template typename FFT_freqs::Vector FFT_freqs::get_xi(const Ccoord_t ccoord) const { Vector retval{}; for (Dim_t i = 0; i < dim; ++i) { retval(i) = this->freqs[i][ccoord[i]]; } return retval; } -} // namespace muSpectre +} // namespace muFFT -#endif // SRC_FFT_FFT_UTILS_HH_ +#endif // SRC_LIBMUFFT_FFT_UTILS_HH_ diff --git a/src/fft/fftw_engine.cc b/src/libmufft/fftw_engine.cc similarity index 86% rename from src/fft/fftw_engine.cc rename to src/libmufft/fftw_engine.cc index 5fc5db0..994e7e2 100644 --- a/src/fft/fftw_engine.cc +++ b/src/libmufft/fftw_engine.cc @@ -1,158 +1,161 @@ /** * @file fftw_engine.cc * * @author Till Junge * * @date 03 Dec 2017 * * @brief implements the fftw engine * * Copyright © 2017 Till Junge * - * µSpectre is free software; you can redistribute it and/or + * µFFT is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * - * µSpectre is distributed in the hope that it will be useful, but + * µFFT is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with µSpectre; see the file COPYING. If not, write to the + * along with µFFT; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#include "fft/fftw_engine.hh" -#include "common/ccoord_operations.hh" +#include "fftw_engine.hh" +#include -namespace muSpectre { +namespace muFFT { template FFTWEngine::FFTWEngine(Ccoord resolutions, Dim_t nb_components, Communicator comm) : Parent{resolutions, nb_components, comm} { - for (auto && pixel : CcoordOps::Pixels(this->fourier_resolutions)) { + for (auto && pixel : + muGrid::CcoordOps::Pixels(this->fourier_resolutions)) { this->work_space_container.add_pixel(pixel); } } /* ---------------------------------------------------------------------- */ template void FFTWEngine::initialise(FFT_PlanFlags plan_flags) { if (this->initialised) { throw std::runtime_error("double initialisation, will leak memory"); } Parent::initialise(plan_flags); const int & rank = Dim; std::array narr; const int * const n = &narr[0]; std::copy(this->subdomain_resolutions.begin(), this->subdomain_resolutions.end(), narr.begin()); int howmany = this->nb_components; // temporary buffer for plan size_t alloc_size = - (CcoordOps::get_size(this->subdomain_resolutions) * howmany); + (muGrid::CcoordOps::get_size(this->subdomain_resolutions) * howmany); Real * r_work_space = fftw_alloc_real(alloc_size); Real * in = r_work_space; const int * const inembed = nullptr; // nembed are tricky: they refer to physical layout int istride = howmany; int idist = 1; fftw_complex * out = reinterpret_cast(this->work.data()); const int * const onembed = nullptr; int ostride = howmany; int odist = idist; unsigned int flags; switch (plan_flags) { case FFT_PlanFlags::estimate: { flags = FFTW_ESTIMATE; break; } case FFT_PlanFlags::measure: { flags = FFTW_MEASURE; break; } case FFT_PlanFlags::patient: { flags = FFTW_PATIENT; break; } default: throw std::runtime_error("unknown planner flag type"); break; } this->plan_fft = fftw_plan_many_dft_r2c( rank, n, howmany, in, inembed, istride, idist, out, onembed, ostride, odist, FFTW_PRESERVE_INPUT | flags); if (this->plan_fft == nullptr) { throw std::runtime_error("Plan failed"); } fftw_complex * i_in = reinterpret_cast(this->work.data()); Real * i_out = r_work_space; this->plan_ifft = fftw_plan_many_dft_c2r(rank, n, howmany, i_in, inembed, istride, idist, i_out, onembed, ostride, odist, flags); if (this->plan_ifft == nullptr) { throw std::runtime_error("Plan failed"); } fftw_free(r_work_space); this->initialised = true; } /* ---------------------------------------------------------------------- */ template FFTWEngine::~FFTWEngine() noexcept { fftw_destroy_plan(this->plan_fft); fftw_destroy_plan(this->plan_ifft); // TODO(Till): We cannot run fftw_cleanup since subsequent FFTW calls will // fail but multiple FFT engines can be active at the same time. // fftw_cleanup(); } /* ---------------------------------------------------------------------- */ template typename FFTWEngine::Workspace_t & FFTWEngine::fft(Field_t & field) { if (this->plan_fft == nullptr) { throw std::runtime_error("fft plan not initialised"); } - if (field.size() != CcoordOps::get_size(this->subdomain_resolutions)) { + if (field.size() != + muGrid::CcoordOps::get_size(this->subdomain_resolutions)) { throw std::runtime_error("size mismatch"); } fftw_execute_dft_r2c(this->plan_fft, field.data(), reinterpret_cast(this->work.data())); return this->work; } /* ---------------------------------------------------------------------- */ template void FFTWEngine::ifft(Field_t & field) const { if (this->plan_ifft == nullptr) { throw std::runtime_error("ifft plan not initialised"); } - if (field.size() != CcoordOps::get_size(this->subdomain_resolutions)) { + if (field.size() != + muGrid::CcoordOps::get_size(this->subdomain_resolutions)) { throw std::runtime_error("size mismatch"); } fftw_execute_dft_c2r(this->plan_ifft, reinterpret_cast(this->work.data()), field.data()); } - template class FFTWEngine; - template class FFTWEngine; -} // namespace muSpectre + template class FFTWEngine; + template class FFTWEngine; +} // namespace muFFT diff --git a/src/fft/fftw_engine.hh b/src/libmufft/fftw_engine.hh similarity index 85% rename from src/fft/fftw_engine.hh rename to src/libmufft/fftw_engine.hh index e2d482e..616a506 100644 --- a/src/fft/fftw_engine.hh +++ b/src/libmufft/fftw_engine.hh @@ -1,96 +1,96 @@ /** * @file fftw_engine.hh * * @author Till Junge * * @date 03 Dec 2017 * * @brief FFT engine using FFTW * * Copyright © 2017 Till Junge * - * µSpectre is free software; you can redistribute it and/or + * µFFT is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * - * µSpectre is distributed in the hope that it will be useful, but + * µFFT is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with µSpectre; see the file COPYING. If not, write to the + * along with µFFT; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#ifndef SRC_FFT_FFTW_ENGINE_HH_ -#define SRC_FFT_FFTW_ENGINE_HH_ +#ifndef SRC_LIBMUFFT_FFTW_ENGINE_HH_ +#define SRC_LIBMUFFT_FFTW_ENGINE_HH_ -#include "fft/fft_engine_base.hh" +#include "fft_engine_base.hh" #include -namespace muSpectre { +namespace muFFT { /** - * implements the `muSpectre::FftEngine_Base` interface using the + * implements the `muFFT::FftEngine_Base` interface using the * FFTW library */ template class FFTWEngine : public FFTEngineBase { public: using Parent = FFTEngineBase; //!< base class using Ccoord = typename Parent::Ccoord; //!< cell coordinates type //! field for Fourier transform of second-order tensor using Workspace_t = typename Parent::Workspace_t; //! real-valued second-order tensor using Field_t = typename Parent::Field_t; //! Default constructor FFTWEngine() = delete; //! Constructor with cell resolutions FFTWEngine(Ccoord resolutions, Dim_t nb_components, Communicator comm = Communicator()); //! Copy constructor FFTWEngine(const FFTWEngine & other) = delete; //! Move constructor FFTWEngine(FFTWEngine && other) = default; //! Destructor virtual ~FFTWEngine() noexcept; //! Copy assignment operator FFTWEngine & operator=(const FFTWEngine & other) = delete; //! Move assignment operator FFTWEngine & operator=(FFTWEngine && other) = default; // compute the plan, etc void initialise(FFT_PlanFlags plan_flags) override; //! forward transform Workspace_t & fft(Field_t & field) override; //! inverse transform void ifft(Field_t & field) const override; protected: fftw_plan plan_fft{}; //!< holds the plan for forward fourier transform fftw_plan plan_ifft{}; //!< holds the plan for inverse fourier transform bool initialised{false}; //!< to prevent double initialisation }; -} // namespace muSpectre +} // namespace muFFT -#endif // SRC_FFT_FFTW_ENGINE_HH_ +#endif // SRC_LIBMUFFT_FFTW_ENGINE_HH_ diff --git a/src/fft/fftwmpi_engine.cc b/src/libmufft/fftwmpi_engine.cc similarity index 93% rename from src/fft/fftwmpi_engine.cc rename to src/libmufft/fftwmpi_engine.cc index b862339..cd28604 100644 --- a/src/fft/fftwmpi_engine.cc +++ b/src/libmufft/fftwmpi_engine.cc @@ -1,236 +1,238 @@ /** * @file fftwmpi_engine.cc * * @author Lars Pastewka * * @date 06 Mar 2017 * * @brief implements the MPI-parallel fftw engine * * Copyright © 2017 Till Junge * - * µSpectre is free software; you can redistribute it and/or + * µFFT is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * - * µSpectre is distributed in the hope that it will be useful, but + * µFFT is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with µSpectre; see the file COPYING. If not, write to the + * along with µFFT; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#include "fft/fftwmpi_engine.hh" -#include "common/ccoord_operations.hh" +#include "fftwmpi_engine.hh" +#include -namespace muSpectre { +namespace muFFT { template int FFTWMPIEngine::nb_engines{0}; template FFTWMPIEngine::FFTWMPIEngine(Ccoord resolutions, Dim_t nb_components, Communicator comm) : Parent{resolutions, nb_components, comm} { if (!this->nb_engines) fftw_mpi_init(); this->nb_engines++; std::array narr; std::copy(this->domain_resolutions.begin(), this->domain_resolutions.end(), narr.begin()); narr[Dim - 1] = this->domain_resolutions[Dim - 1] / 2 + 1; ptrdiff_t res_x, loc_x, res_y, loc_y; this->workspace_size = fftw_mpi_local_size_many_transposed( Dim, narr.data(), this->nb_components, FFTW_MPI_DEFAULT_BLOCK, FFTW_MPI_DEFAULT_BLOCK, this->comm.get_mpi_comm(), &res_x, &loc_x, &res_y, &loc_y); this->fourier_resolutions[1] = this->fourier_resolutions[0]; this->fourier_locations[1] = this->fourier_locations[0]; this->subdomain_resolutions[0] = res_x; this->subdomain_locations[0] = loc_x; this->fourier_resolutions[0] = res_y; this->fourier_locations[0] = loc_y; for (auto & n : this->subdomain_resolutions) { if (n == 0) { throw std::runtime_error("FFTW MPI planning returned zero resolution. " "You may need to run on fewer processes."); } } for (auto & n : this->fourier_resolutions) { if (n == 0) { throw std::runtime_error("FFTW MPI planning returned zero Fourier " "resolution. You may need to run on fewer " "processes."); } } for (auto && pixel : - std::conditional_t, - CcoordOps::Pixels>( + std::conditional_t, + muGrid::CcoordOps::Pixels>( this->fourier_resolutions, this->fourier_locations)) { this->work_space_container.add_pixel(pixel); } } /* ---------------------------------------------------------------------- */ template void FFTWMPIEngine::initialise(FFT_PlanFlags plan_flags) { if (this->initialised) { throw std::runtime_error("double initialisation, will leak memory"); } // Initialize parent after local resolutions have been determined and // work space has been initialized Parent::initialise(plan_flags); this->real_workspace = fftw_alloc_real(2 * this->workspace_size); // We need to check whether the workspace provided by our field is large // enough. MPI parallel FFTW may request a workspace size larger than the // nominal size of the complex buffer. if (static_cast(this->work.size() * this->nb_components) < this->workspace_size) { this->work.set_pad_size(this->workspace_size - this->nb_components * this->work.size()); } unsigned int flags; switch (plan_flags) { case FFT_PlanFlags::estimate: { flags = FFTW_ESTIMATE; break; } case FFT_PlanFlags::measure: { flags = FFTW_MEASURE; break; } case FFT_PlanFlags::patient: { flags = FFTW_PATIENT; break; } default: throw std::runtime_error("unknown planner flag type"); break; } std::array narr; std::copy(this->domain_resolutions.begin(), this->domain_resolutions.end(), narr.begin()); Real * in{this->real_workspace}; fftw_complex * out{reinterpret_cast(this->work.data())}; this->plan_fft = fftw_mpi_plan_many_dft_r2c( Dim, narr.data(), this->nb_components, FFTW_MPI_DEFAULT_BLOCK, FFTW_MPI_DEFAULT_BLOCK, in, out, this->comm.get_mpi_comm(), FFTW_MPI_TRANSPOSED_OUT | flags); if (this->plan_fft == nullptr) { throw std::runtime_error("r2c plan failed"); } fftw_complex * i_in = reinterpret_cast(this->work.data()); Real * i_out = this->real_workspace; this->plan_ifft = fftw_mpi_plan_many_dft_c2r( Dim, narr.data(), this->nb_components, FFTW_MPI_DEFAULT_BLOCK, FFTW_MPI_DEFAULT_BLOCK, i_in, i_out, this->comm.get_mpi_comm(), FFTW_MPI_TRANSPOSED_IN | flags); if (this->plan_ifft == nullptr) { throw std::runtime_error("c2r plan failed"); } this->initialised = true; } /* ---------------------------------------------------------------------- */ template FFTWMPIEngine::~FFTWMPIEngine() noexcept { if (this->real_workspace != nullptr) fftw_free(this->real_workspace); if (this->plan_fft != nullptr) fftw_destroy_plan(this->plan_fft); if (this->plan_ifft != nullptr) fftw_destroy_plan(this->plan_ifft); // TODO(junge): We cannot run fftw_mpi_cleanup since also calls fftw_cleanup // and any running FFTWEngine will fail afterwards. // this->nb_engines--; // if (!this->nb_engines) fftw_mpi_cleanup(); } /* ---------------------------------------------------------------------- */ template typename FFTWMPIEngine::Workspace_t & FFTWMPIEngine::fft(Field_t & field) { if (this->plan_fft == nullptr) { throw std::runtime_error("fft plan not initialised"); } - if (field.size() != CcoordOps::get_size(this->subdomain_resolutions)) { + if (field.size() != + muGrid::CcoordOps::get_size(this->subdomain_resolutions)) { throw std::runtime_error("size mismatch"); } // Copy non-padded field to padded real_workspace. // Transposed output of M x N x L transform for >= 3 dimensions is padded // M x N x 2*(L/2+1). ptrdiff_t fstride = (this->nb_components * this->subdomain_resolutions[Dim - 1]); ptrdiff_t wstride = (this->nb_components * 2 * (this->subdomain_resolutions[Dim - 1] / 2 + 1)); ptrdiff_t n = field.size() / this->subdomain_resolutions[Dim - 1]; auto fdata = field.data(); auto wdata = this->real_workspace; for (int i = 0; i < n; i++) { std::copy(fdata, fdata + fstride, wdata); fdata += fstride; wdata += wstride; } // Compute FFT fftw_mpi_execute_dft_r2c( this->plan_fft, this->real_workspace, reinterpret_cast(this->work.data())); return this->work; } /* ---------------------------------------------------------------------- */ template void FFTWMPIEngine::ifft(Field_t & field) const { if (this->plan_ifft == nullptr) { throw std::runtime_error("ifft plan not initialised"); } - if (field.size() != CcoordOps::get_size(this->subdomain_resolutions)) { + if (field.size() != + muGrid::CcoordOps::get_size(this->subdomain_resolutions)) { throw std::runtime_error("size mismatch"); } // Compute inverse FFT fftw_mpi_execute_dft_c2r( this->plan_ifft, reinterpret_cast(this->work.data()), this->real_workspace); // Copy non-padded field to padded real_workspace. // Transposed output of M x N x L transform for >= 3 dimensions is padded // M x N x 2*(L/2+1). ptrdiff_t fstride{this->nb_components * this->subdomain_resolutions[Dim - 1]}; ptrdiff_t wstride{this->nb_components * 2 * (this->subdomain_resolutions[Dim - 1] / 2 + 1)}; ptrdiff_t n(field.size() / this->subdomain_resolutions[Dim - 1]); auto fdata{field.data()}; auto wdata{this->real_workspace}; for (int i = 0; i < n; i++) { std::copy(wdata, wdata + fstride, fdata); fdata += fstride; wdata += wstride; } } template class FFTWMPIEngine; template class FFTWMPIEngine; -} // namespace muSpectre +} // namespace muFFT diff --git a/src/fft/fftwmpi_engine.hh b/src/libmufft/fftwmpi_engine.hh similarity index 86% rename from src/fft/fftwmpi_engine.hh rename to src/libmufft/fftwmpi_engine.hh index aecb4cd..3c75c5c 100644 --- a/src/fft/fftwmpi_engine.hh +++ b/src/libmufft/fftwmpi_engine.hh @@ -1,102 +1,102 @@ /** * @file fftwmpi_engine.hh * * @author Lars Pastewka * * @date 06 Mar 2017 * * @brief FFT engine using MPI-parallel FFTW * * Copyright © 2017 Till Junge * - * µSpectre is free software; you can redistribute it and/or + * µFFT is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * - * µSpectre is distributed in the hope that it will be useful, but + * µFFT is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with µSpectre; see the file COPYING. If not, write to the + * along with µFFT; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#ifndef SRC_FFT_FFTWMPI_ENGINE_HH_ -#define SRC_FFT_FFTWMPI_ENGINE_HH_ +#ifndef SRC_LIBMUFFT_FFTWMPI_ENGINE_HH_ +#define SRC_LIBMUFFT_FFTWMPI_ENGINE_HH_ -#include "fft/fft_engine_base.hh" +#include "fft_engine_base.hh" #include -namespace muSpectre { +namespace muFFT { /** - * implements the `muSpectre::FFTEngineBase` interface using the + * implements the `muFFT::FFTEngineBase` interface using the * FFTW library */ template class FFTWMPIEngine : public FFTEngineBase { public: using Parent = FFTEngineBase; //!< base class using Ccoord = typename Parent::Ccoord; //!< cell coordinates type //! field for Fourier transform of second-order tensor using Workspace_t = typename Parent::Workspace_t; //! real-valued second-order tensor using Field_t = typename Parent::Field_t; //! Default constructor FFTWMPIEngine() = delete; //! Constructor with system resolutions FFTWMPIEngine(Ccoord resolutions, Dim_t nb_components, Communicator comm = Communicator()); //! Copy constructor FFTWMPIEngine(const FFTWMPIEngine & other) = delete; //! Move constructor FFTWMPIEngine(FFTWMPIEngine && other) = default; //! Destructor virtual ~FFTWMPIEngine() noexcept; //! Copy assignment operator FFTWMPIEngine & operator=(const FFTWMPIEngine & other) = delete; //! Move assignment operator FFTWMPIEngine & operator=(FFTWMPIEngine && other) = default; // compute the plan, etc void initialise(FFT_PlanFlags plan_flags) override; //! forward transform Workspace_t & fft(Field_t & field) override; //! inverse transform void ifft(Field_t & field) const override; protected: static int nb_engines; //!< number of times this engine has been instatiated fftw_plan plan_fft{}; //!< holds the plan for forward fourier transform fftw_plan plan_ifft{}; //!< holds the plan for inverse fourier transform ptrdiff_t workspace_size{}; //!< size of workspace buffer returned by planner Real * real_workspace{}; //!< temporary real workspace that is correctly //!< padded bool initialised{false}; //!< to prevent double initialisation }; -} // namespace muSpectre +} // namespace muFFT -#endif // SRC_FFT_FFTWMPI_ENGINE_HH_ +#endif // SRC_LIBMUFFT_FFTWMPI_ENGINE_HH_ diff --git a/src/libmufft/mufft_common.hh b/src/libmufft/mufft_common.hh new file mode 100644 index 0000000..61f57ad --- /dev/null +++ b/src/libmufft/mufft_common.hh @@ -0,0 +1,70 @@ +/** + * @file mufft_common.hh + * + * @author Till Junge + * + * @date 24 Jan 2019 + * + * @brief Small definitions of commonly used types throughout µFFT + * + * Copyright © 2019 Till Junge + * + * µFFT is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3, or (at + * your option) any later version. + * + * µFFT is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with µFFT; see the file COPYING. If not, write to the + * Free Software Foundation, Inc., 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + * + * Additional permission under GNU GPL version 3 section 7 + * + * If you modify this Program, or any covered work, by linking or combining it + * with proprietary FFT implementations or numerical libraries, containing parts + * covered by the terms of those libraries' licenses, the licensors of this + * Program grant you additional permission to convey the resulting work. + */ + +#include + +#ifndef SRC_LIBMUFFT_MUFFT_COMMON_HH_ +#define SRC_LIBMUFFT_MUFFT_COMMON_HH_ + +namespace muFFT { + using muGrid::Dim_t; + + using muGrid::Complex; + using muGrid::Int; + using muGrid::Real; + using muGrid::Uint; + + using muGrid::Ccoord_t; + using muGrid::Rcoord_t; + + using muGrid::optional; + + using muGrid::oneD; + using muGrid::threeD; + using muGrid::twoD; + + /** + * Planner flags for FFT (follows FFTW, hopefully this choice will + * be compatible with alternative FFT implementations) + * @enum muFFT::FFT_PlanFlags + */ + enum class FFT_PlanFlags { + estimate, //!< cheapest plan for slowest execution + measure, //!< more expensive plan for fast execution + patient //!< very expensive plan for fastest execution + }; + +} // namespace muFFT + +#endif // SRC_LIBMUFFT_MUFFT_COMMON_HH_ diff --git a/src/fft/pfft_engine.cc b/src/libmufft/pfft_engine.cc similarity index 93% rename from src/fft/pfft_engine.cc rename to src/libmufft/pfft_engine.cc index 47d5ba8..3a7be19 100644 --- a/src/fft/pfft_engine.cc +++ b/src/libmufft/pfft_engine.cc @@ -1,244 +1,246 @@ /** * @file pfft_engine.cc * * @author Lars Pastewka * * @date 06 Mar 2017 * * @brief implements the MPI-parallel pfft engine * * Copyright © 2017 Till Junge * - * µSpectre is free software; you can redistribute it and/or + * µFFT is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * - * µSpectre is distributed in the hope that it will be useful, but + * µFFT is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with µSpectre; see the file COPYING. If not, write to the + * along with µFFT; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#include "fft/pfft_engine.hh" -#include "common/ccoord_operations.hh" +#include "pfft_engine.hh" +#include -namespace muSpectre { +namespace muFFT { template int PFFTEngine::nb_engines{0}; template PFFTEngine::PFFTEngine(Ccoord resolutions, Dim_t nb_components, Communicator comm) : Parent{resolutions, nb_components, comm}, mpi_comm{ comm.get_mpi_comm()} { if (!this->nb_engines) pfft_init(); this->nb_engines++; int size{comm.size()}; int dim_x{size}; int dim_y{1}; // Note: All TODOs below don't affect the function of the PFFT engine. It // presently uses slab decompositions, the TODOs are what needs to be done // to get stripe decomposition to work - but it does not work yet. Slab // vs stripe decomposition may have an impact on how the code scales. // TODO(pastewka): Enable this to enable 2d process mesh. This does not pass // tests. // if (DimS > 2) { if (false) { dim_y = static_cast(sqrt(size)); while ((size / dim_y) * dim_y != size) dim_y--; dim_x = size / dim_y; } // TODO(pastewka): Enable this to enable 2d process mesh. This does not pass // tests. if (DimS > 2) { if (false) { if (pfft_create_procmesh_2d(this->comm.get_mpi_comm(), dim_x, dim_y, &this->mpi_comm)) { throw std::runtime_error("Failed to create 2d PFFT process mesh."); } } std::array narr; std::copy(this->domain_resolutions.begin(), this->domain_resolutions.end(), narr.begin()); ptrdiff_t res[DimS], loc[DimS], fres[DimS], floc[DimS]; this->workspace_size = pfft_local_size_many_dft_r2c( DimS, narr.data(), narr.data(), narr.data(), this->nb_components, PFFT_DEFAULT_BLOCKS, PFFT_DEFAULT_BLOCKS, this->mpi_comm, PFFT_TRANSPOSED_OUT, res, loc, fres, floc); std::copy(res, res + DimS, this->subdomain_resolutions.begin()); std::copy(loc, loc + DimS, this->subdomain_locations.begin()); std::copy(fres, fres + DimS, this->fourier_resolutions.begin()); std::copy(floc, floc + DimS, this->fourier_locations.begin()); // TODO(pastewka): Enable this to enable 2d process mesh. This does not pass // tests. for (int i = 0; i < DimS-1; ++i) { for (int i = 0; i < 1; ++i) { std::swap(this->fourier_resolutions[i], this->fourier_resolutions[i + 1]); std::swap(this->fourier_locations[i], this->fourier_locations[i + 1]); } for (auto & n : this->subdomain_resolutions) { if (n == 0) { throw std::runtime_error("PFFT planning returned zero resolution. " "You may need to run on fewer processes."); } } for (auto & n : this->fourier_resolutions) { if (n == 0) { throw std::runtime_error("PFFT planning returned zero Fourier " "resolution. You may need to run on fewer " "processes."); } } for (auto && pixel : - std::conditional_t, + std::conditional_t, // TODO(pastewka): This should be the correct order // of dimension for a 2d process mesh, but tests // don't pass. CcoordOps::Pixels - CcoordOps::Pixels>( + muGrid::CcoordOps::Pixels>( this->fourier_resolutions, this->fourier_locations)) { this->work_space_container.add_pixel(pixel); } } /* ---------------------------------------------------------------------- */ template void PFFTEngine::initialise(FFT_PlanFlags plan_flags) { if (this->initialised) { throw std::runtime_error("double initialisation, will leak memory"); } // Initialize parent after local resolutions have been determined and // work space has been initialized Parent::initialise(plan_flags); this->real_workspace = pfft_alloc_real(2 * this->workspace_size); // We need to check whether the workspace provided by our field is large // enough. PFFT may request a workspace size larger than the nominal size // of the complex buffer. if (static_cast(this->work.size() * this->nb_components) < this->workspace_size) { this->work.set_pad_size(this->workspace_size - this->nb_components * this->work.size()); } unsigned int flags; switch (plan_flags) { case FFT_PlanFlags::estimate: { flags = PFFT_ESTIMATE; break; } case FFT_PlanFlags::measure: { flags = PFFT_MEASURE; break; } case FFT_PlanFlags::patient: { flags = PFFT_PATIENT; break; } default: throw std::runtime_error("unknown planner flag type"); break; } std::array narr; std::copy(this->domain_resolutions.begin(), this->domain_resolutions.end(), narr.begin()); Real * in{this->real_workspace}; pfft_complex * out{reinterpret_cast(this->work.data())}; this->plan_fft = pfft_plan_many_dft_r2c( DimS, narr.data(), narr.data(), narr.data(), this->nb_components, PFFT_DEFAULT_BLOCKS, PFFT_DEFAULT_BLOCKS, in, out, this->mpi_comm, PFFT_FORWARD, PFFT_TRANSPOSED_OUT | flags); if (this->plan_fft == nullptr) { throw std::runtime_error("r2c plan failed"); } pfft_complex * i_in{reinterpret_cast(this->work.data())}; Real * i_out{this->real_workspace}; this->plan_ifft = pfft_plan_many_dft_c2r( DimS, narr.data(), narr.data(), narr.data(), this->nb_components, PFFT_DEFAULT_BLOCKS, PFFT_DEFAULT_BLOCKS, i_in, i_out, this->mpi_comm, PFFT_BACKWARD, PFFT_TRANSPOSED_IN | flags); if (this->plan_ifft == nullptr) { throw std::runtime_error("c2r plan failed"); } this->initialised = true; } /* ---------------------------------------------------------------------- */ template PFFTEngine::~PFFTEngine() noexcept { if (this->real_workspace != nullptr) pfft_free(this->real_workspace); if (this->plan_fft != nullptr) pfft_destroy_plan(this->plan_fft); if (this->plan_ifft != nullptr) pfft_destroy_plan(this->plan_ifft); if (this->mpi_comm != this->comm.get_mpi_comm()) { MPI_Comm_free(&this->mpi_comm); } // TODO(Till): We cannot run fftw_mpi_cleanup since also calls fftw_cleanup // and any running FFTWEngine will fail afterwards. // this->nb_engines--; // if (!this->nb_engines) pfft_cleanup(); } /* ---------------------------------------------------------------------- */ template typename PFFTEngine::Workspace_t & PFFTEngine::fft(Field_t & field) { if (!this->plan_fft) { throw std::runtime_error("fft plan not allocated"); } - if (field.size() != CcoordOps::get_size(this->subdomain_resolutions)) { + if (field.size() != + muGrid::CcoordOps::get_size(this->subdomain_resolutions)) { throw std::runtime_error("size mismatch"); } // Copy field data to workspace buffer. This is necessary because workspace // buffer is larger than field buffer. std::copy(field.data(), field.data() + this->nb_components * field.size(), this->real_workspace); pfft_execute_dft_r2c(this->plan_fft, this->real_workspace, reinterpret_cast(this->work.data())); return this->work; } /* ---------------------------------------------------------------------- */ template void PFFTEngine::ifft(Field_t & field) const { if (!this->plan_ifft) { throw std::runtime_error("ifft plan not allocated"); } - if (field.size() != CcoordOps::get_size(this->subdomain_resolutions)) { + if (field.size() != + muGrid::CcoordOps::get_size(this->subdomain_resolutions)) { throw std::runtime_error("size mismatch"); } pfft_execute_dft_c2r(this->plan_ifft, reinterpret_cast(this->work.data()), this->real_workspace); std::copy(this->real_workspace, this->real_workspace + this->nb_components * field.size(), field.data()); } template class PFFTEngine; template class PFFTEngine; -} // namespace muSpectre +} // namespace muFFT diff --git a/src/fft/pfft_engine.hh b/src/libmufft/pfft_engine.hh similarity index 86% rename from src/fft/pfft_engine.hh rename to src/libmufft/pfft_engine.hh index d893469..4e97b38 100644 --- a/src/fft/pfft_engine.hh +++ b/src/libmufft/pfft_engine.hh @@ -1,105 +1,104 @@ /** * @file pfft_engine.hh * * @author Lars Pastewka * * @date 06 Mar 2017 * * @brief FFT engine using MPI-parallel PFFT * * Copyright © 2017 Till Junge * - * µSpectre is free software; you can redistribute it and/or + * µFFT is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * - * µSpectre is distributed in the hope that it will be useful, but + * µFFT is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with µSpectre; see the file COPYING. If not, write to the + * along with µFFT; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#ifndef SRC_FFT_PFFT_ENGINE_HH_ -#define SRC_FFT_PFFT_ENGINE_HH_ +#ifndef SRC_LIBMUFFT_PFFT_ENGINE_HH_ +#define SRC_LIBMUFFT_PFFT_ENGINE_HH_ -#include "common/communicator.hh" - -#include "fft/fft_engine_base.hh" +#include "communicator.hh" +#include "fft_engine_base.hh" #include -namespace muSpectre { +namespace muFFT { /** - * implements the `muSpectre::FFTEngineBase` interface using the + * implements the `muFFT::FFTEngineBase` interface using the * FFTW library */ template class PFFTEngine : public FFTEngineBase { public: using Parent = FFTEngineBase; //!< base class using Ccoord = typename Parent::Ccoord; //!< cell coordinates type //! field for Fourier transform of second-order tensor using Workspace_t = typename Parent::Workspace_t; //! real-valued second-order tensor using Field_t = typename Parent::Field_t; //! Default constructor PFFTEngine() = delete; //! Constructor with system resolutions PFFTEngine(Ccoord resolutions, Dim_t nb_components, Communicator comm = Communicator()); //! Copy constructor PFFTEngine(const PFFTEngine & other) = delete; //! Move constructor PFFTEngine(PFFTEngine && other) = default; //! Destructor virtual ~PFFTEngine() noexcept; //! Copy assignment operator PFFTEngine & operator=(const PFFTEngine & other) = delete; //! Move assignment operator PFFTEngine & operator=(PFFTEngine && other) = default; // compute the plan, etc void initialise(FFT_PlanFlags plan_flags) override; //! forward transform Workspace_t & fft(Field_t & field) override; //! inverse transform void ifft(Field_t & field) const override; protected: MPI_Comm mpi_comm; //! < MPI communicator static int nb_engines; //!< number of times this engine has been instatiated pfft_plan plan_fft{}; //!< holds the plan for forward fourier transform pfft_plan plan_ifft{}; //!< holds the plan for inverse fourier transform ptrdiff_t workspace_size{}; //!< size of workspace buffer returned by planner Real * real_workspace{}; //!< temporary real workspace that is correctly //!< padded bool initialised{false}; //!< to prevent double initialisation }; -} // namespace muSpectre +} // namespace muFFT -#endif // SRC_FFT_PFFT_ENGINE_HH_ +#endif // SRC_LIBMUFFT_PFFT_ENGINE_HH_ diff --git a/src/libmugrid/CMakeLists.txt b/src/libmugrid/CMakeLists.txt new file mode 100644 index 0000000..fee9ff1 --- /dev/null +++ b/src/libmugrid/CMakeLists.txt @@ -0,0 +1,112 @@ +# ============================================================================= +# file CMakeLists.txt +# +# @author Nicolas Richart +# +# @date 24 Jan 2019 +# +# @brief Configuration for libmuGrid +# +# @section LICENSE +# +# Copyright © 2018 Till Junge +# +# µGrid is free software; you can redistribute it and/or modify it under the +# terms of the GNU Lesser General Public License as published by the Free +# Software Foundation, either version 3, or (at your option) any later version. +# +# µGrid is distributed in the hope that it will be useful, but WITHOUT ANY +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR +# A PARTICULAR PURPOSE. See the GNU General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with µGrid; see the file COPYING. If not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +# +# Additional permission under GNU GPL version 3 section 7 +# +# If you modify this Program, or any covered work, by linking or combining it +# with proprietary FFT implementations or numerical libraries, containing parts +# covered by the terms of those libraries' licenses, the licensors of this +# Program grant you additional permission to convey the resulting work. +# ============================================================================= + +project(muGrid) +cmake_minimum_required(VERSION 3.5) + +if(POLICY CMP0076) + cmake_policy(SET CMP0076 NEW) +endif() + +set(mugrid_HDRS + ccoord_operations.hh + field_base.hh + field_collection_base.hh + field_collection_global.hh + field_collection.hh + field_collection_local.hh + field_helpers.hh + field.hh + field_map_base.hh + field_map_dynamic.hh + field_map.hh + field_map_matrixlike.hh + field_map_scalar.hh + field_map_tensor.hh + field_typed.hh + grid_common.hh + iterators.hh + statefield.hh + eigen_tools.hh + T4_map_proxy.hh + tensor_algebra.hh + ) + +add_library(muGrid INTERFACE) +#target_sources(muGrid INTERFACE ${mugrid_HDRS}) + +# defining external dependencies +target_link_libraries(muGrid INTERFACE Eigen3::Eigen) + +# defining exported include directories +target_include_directories(muGrid + INTERFACE $ + ) +# small trick for build includes in public +set_property(TARGET muGrid APPEND PROPERTY INTERFACE_INCLUDE_DIRECTORIES + $) + +target_compile_features(muGrid INTERFACE + cxx_auto_type cxx_constexpr cxx_decltype cxx_decltype_auto) + +if(MUGRID_NAMESPACE) + add_library(${MUGRID_NAMESPACE}muGrid ALIAS muGrid) +endif() + +# ------------------------------------------------------------------------------ +if(NOT MUGRID_TARGETS_EXPORT) + set(MUGRID_TARGETS_EXPORT muGridTargets) +endif() + +install(TARGETS muGrid + EXPORT ${MUGRID_TARGETS_EXPORT} + INCLUDES + DESTINATION include/libmugrid) + +install(FILES ${mugrid_HDRS} DESTINATION include/libmugrid) + +if("${MUGRID_TARGETS_EXPORT}" STREQUAL "muGridTargets") + if(MUGRID_NAMESPACE) + set(_namespace NAMESPACE ${MUGRID_NAMESPACE}) + endif() + + install(EXPORT ${MUGRID_TARGETS_EXPORT} + ${_namespace} + DESTINATION share/cmake/${PROJECT_NAME} + COMPONENT dev) + + #Export for build tree + export(EXPORT ${MUGRID_TARGETS_EXPORT} + ${_namespace} + FILE "${CMAKE_BINARY_DIR}/${MUGRID_TARGETS_EXPORT}.cmake") +endif() diff --git a/src/common/T4_map_proxy.hh b/src/libmugrid/T4_map_proxy.hh similarity index 89% rename from src/common/T4_map_proxy.hh rename to src/libmugrid/T4_map_proxy.hh index aa8ce5a..906d461 100644 --- a/src/common/T4_map_proxy.hh +++ b/src/libmugrid/T4_map_proxy.hh @@ -1,105 +1,106 @@ /** * @file T4_map_proxy.hh * * @author Till Junge * * @date 19 Nov 2017 * * @brief Map type to allow fourth-order tensor-like maps on 2D matrices * * Copyright © 2017 Till Junge * - * µSpectre is free software; you can redistribute it and/or + * µGrid is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * - * µSpectre is distributed in the hope that it will be useful, but + * µGrid is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with µSpectre; see the file COPYING. If not, write to the + * along with µGrid; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#ifndef SRC_COMMON_T4_MAP_PROXY_HH_ -#define SRC_COMMON_T4_MAP_PROXY_HH_ +#ifndef SRC_LIBMUGRID_T4_MAP_PROXY_HH_ +#define SRC_LIBMUGRID_T4_MAP_PROXY_HH_ -#include "common/eigen_tools.hh" +#include "eigen_tools.hh" #include #include #include -namespace muSpectre { +namespace muGrid { /** * simple adapter function to create a matrix that can be mapped as a tensor */ template using T4Mat = Eigen::Matrix; /** - * Map onto `muSpectre::T4Mat` + * Map onto `muGrid::T4Mat` */ template using T4MatMap = std::conditional_t>, Eigen::Map>>; template struct DimCounter {}; template struct DimCounter> { private: using Type = Eigen::MatrixBase; constexpr static Dim_t Rows{Type::RowsAtCompileTime}; public: static_assert(Rows != Eigen::Dynamic, "matrix type not statically sized"); static_assert(Rows == Type::ColsAtCompileTime, "matrix type not square"); constexpr static Dim_t value{ct_sqrt(Rows)}; static_assert(value * value == Rows, "Only integer numbers of dimensions allowed"); }; /** * provides index-based access to fourth-order Tensors represented * by square matrices */ template inline auto get(const Eigen::MatrixBase & t4, Dim_t i, Dim_t j, Dim_t k, Dim_t l) -> decltype(auto) { constexpr Dim_t Dim{DimCounter>::value}; const auto myColStride{(t4.colStride() == 1) ? t4.colStride() : t4.colStride() / Dim}; const auto myRowStride{(t4.rowStride() == 1) ? t4.rowStride() : t4.rowStride() / Dim}; return t4(i * myRowStride + j * myColStride, k * myRowStride + l * myColStride); } template inline auto get(Eigen::MatrixBase & t4, Dim_t i, Dim_t j, Dim_t k, Dim_t l) -> decltype(t4.coeffRef(i, j)) { constexpr Dim_t Dim{DimCounter>::value}; const auto myColStride{(t4.colStride() == 1) ? t4.colStride() : t4.colStride() / Dim}; const auto myRowStride{(t4.rowStride() == 1) ? t4.rowStride() : t4.rowStride() / Dim}; return t4.coeffRef(i * myRowStride + j * myColStride, k * myRowStride + l * myColStride); } -} // namespace muSpectre -#endif // SRC_COMMON_T4_MAP_PROXY_HH_ +} // namespace muGrid + +#endif // SRC_LIBMUGRID_T4_MAP_PROXY_HH_ diff --git a/src/common/ccoord_operations.hh b/src/libmugrid/ccoord_operations.hh similarity index 96% rename from src/common/ccoord_operations.hh rename to src/libmugrid/ccoord_operations.hh index 231b549..a31d33d 100644 --- a/src/common/ccoord_operations.hh +++ b/src/libmugrid/ccoord_operations.hh @@ -1,333 +1,333 @@ /** * @file ccoord_operations.hh * * @author Till Junge * * @date 29 Sep 2017 * * @brief common operations on pixel addressing * * Copyright © 2017 Till Junge * - * µSpectre is free software; you can redistribute it and/or + * µGrid is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * - * µSpectre is distributed in the hope that it will be useful, but + * µGrid is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with µSpectre; see the file COPYING. If not, write to the + * along with µGrid; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include #include #include #include #include -#include "common/common.hh" -#include "common/iterators.hh" +#include "grid_common.hh" +#include "iterators.hh" -#ifndef SRC_COMMON_CCOORD_OPERATIONS_HH_ -#define SRC_COMMON_CCOORD_OPERATIONS_HH_ +#ifndef SRC_LIBMUGRID_CCOORD_OPERATIONS_HH_ +#define SRC_LIBMUGRID_CCOORD_OPERATIONS_HH_ -namespace muSpectre { +namespace muGrid { namespace CcoordOps { namespace internal { //! simple helper returning the first argument and ignoring the second template constexpr T ret(T val, size_t /*dummy*/) { return val; } //! helper to build cubes template constexpr std::array cube_fun(T val, std::index_sequence) { return std::array{ret(val, I)...}; } //! computes hermitian size according to FFTW template constexpr Ccoord_t herm(const Ccoord_t & full_sizes, std::index_sequence) { return Ccoord_t{full_sizes[I]..., full_sizes.back() / 2 + 1}; } //! compute the stride in a direction of a row-major grid template constexpr Dim_t stride(const Ccoord_t & sizes, const size_t index) { static_assert(Dim > 0, "only for positive numbers of dimensions"); auto const diff{Dim - 1 - Dim_t(index)}; Dim_t ret_val{1}; for (Dim_t i{0}; i < diff; ++i) { ret_val *= sizes[Dim - 1 - i]; } return ret_val; } //! get all strides from a row-major grid (helper function) template constexpr Ccoord_t compute_strides(const Ccoord_t & sizes, std::index_sequence) { return Ccoord_t{stride(sizes, I)...}; } } // namespace internal //-----------------------------------------------------------------------// //! returns a grid of equal resolutions in each direction template constexpr std::array get_cube(T size) { return internal::cube_fun(size, std::make_index_sequence{}); } /* ---------------------------------------------------------------------- */ //! returns the hermition grid to correcsponding to a full grid template constexpr Ccoord_t get_hermitian_sizes(Ccoord_t full_sizes) { return internal::herm(full_sizes, std::make_index_sequence{}); } //! return physical vector of a cell of cubic pixels template Eigen::Matrix get_vector(const Ccoord_t & ccoord, Real pix_size = 1.) { Eigen::Matrix retval; for (size_t i = 0; i < dim; ++i) { retval[i] = pix_size * ccoord[i]; } return retval; } /* ---------------------------------------------------------------------- */ //! return physical vector of a cell of general pixels template Eigen::Matrix get_vector(const Ccoord_t & ccoord, Eigen::Matrix pix_size) { Eigen::Matrix retval = pix_size; for (size_t i = 0; i < dim; ++i) { retval[i] *= ccoord[i]; } return retval; } /* ---------------------------------------------------------------------- */ //! return physical vector of a cell of general pixels template Eigen::Matrix get_vector(const Ccoord_t & ccoord, const std::array & pix_size) { Eigen::Matrix retval{}; for (size_t i = 0; i < dim; ++i) { retval[i] = pix_size[i] * ccoord[i]; } return retval; } /* ---------------------------------------------------------------------- */ //! get all strides from a row-major grid template constexpr Ccoord_t get_default_strides(const Ccoord_t & sizes) { return internal::compute_strides(sizes, std::make_index_sequence{}); } //----------------------------------------------------------------------------// //! get the i-th pixel in a grid of size sizes template constexpr Ccoord_t get_ccoord(const Ccoord_t & resolutions, const Ccoord_t & locations, Dim_t index) { Ccoord_t retval{{0}}; Dim_t factor{1}; for (Dim_t i = dim - 1; i >= 0; --i) { retval[i] = index / factor % resolutions[i] + locations[i]; if (i != 0) { factor *= resolutions[i]; } } return retval; } //----------------------------------------------------------------------------// //! get the i-th pixel in a grid of size sizes template constexpr Ccoord_t get_ccoord(const Ccoord_t & resolutions, const Ccoord_t & locations, Dim_t index, std::index_sequence) { Ccoord_t ccoord{get_ccoord(resolutions, locations, index)}; return Ccoord_t({ccoord[I]...}); } //-----------------------------------------------------------------------// //! get the linear index of a pixel in a given grid template constexpr Dim_t get_index(const Ccoord_t & sizes, const Ccoord_t & locations, const Ccoord_t & ccoord) { Dim_t retval{0}; Dim_t factor{1}; for (Dim_t i = dim - 1; i >= 0; --i) { retval += (ccoord[i] - locations[i]) * factor; if (i != 0) { factor *= sizes[i]; } } return retval; } //-----------------------------------------------------------------------// //! get the linear index of a pixel given a set of strides template constexpr Dim_t get_index_from_strides(const Ccoord_t & strides, const Ccoord_t & ccoord) { Dim_t retval{0}; for (const auto & tup : akantu::zip(strides, ccoord)) { const auto & stride = std::get<0>(tup); const auto & ccord_ = std::get<1>(tup); retval += stride * ccord_; } return retval; } //-----------------------------------------------------------------------// //! get the number of pixels in a grid template constexpr size_t get_size(const Ccoord_t & sizes) { Dim_t retval{1}; for (size_t i = 0; i < dim; ++i) { retval *= sizes[i]; } return retval; } //-----------------------------------------------------------------------// //! get the number of pixels in a grid given its strides template constexpr size_t get_size_from_strides(const Ccoord_t & sizes, const Ccoord_t & strides) { return sizes[0] * strides[0]; } /* ---------------------------------------------------------------------- */ /** * centralises iterating over square (or cubic) discretisation * grids. The optional parameter pack `dmap` can be used to * specify the order of the axes in which to iterate over the * dimensions (i.e., dmap = 0, 1, 2 is rowmajor, and 0, 2, 1 would * be a custom order in which the second and third dimension are * transposed */ template class Pixels { public: //! constructor Pixels(const Ccoord_t & resolutions = Ccoord_t{}, const Ccoord_t & locations = Ccoord_t{}) : resolutions{resolutions}, locations{locations} {}; //! copy constructor Pixels(const Pixels & other) = default; //! assignment operator Pixels & operator=(const Pixels & other) = default; virtual ~Pixels() = default; /** * iterators over `Pixels` dereferences to cell coordinates */ class iterator { public: using value_type = Ccoord_t; //!< stl conformance using const_value_type = const value_type; //!< stl conformance using pointer = value_type *; //!< stl conformance using difference_type = std::ptrdiff_t; //!< stl conformance using iterator_category = std::forward_iterator_tag; //!< stl //!< conformance using reference = value_type; //!< stl conformance //! constructor explicit iterator(const Pixels & pixels, bool begin = true); virtual ~iterator() = default; //! dereferencing inline value_type operator*() const; //! pre-increment inline iterator & operator++(); //! inequality inline bool operator!=(const iterator & other) const; //! equality inline bool operator==(const iterator & other) const; protected: const Pixels & pixels; //!< ref to pixels in cell size_t index; //!< index of currect pointed-to pixel }; //! stl conformance inline iterator begin() const { return iterator(*this); } //! stl conformance inline iterator end() const { return iterator(*this, false); } //! stl conformance inline size_t size() const { return get_size(this->resolutions); } protected: Ccoord_t resolutions; //!< resolutions of this domain Ccoord_t locations; //!< locations of this domain }; /* ---------------------------------------------------------------------- */ template Pixels::iterator::iterator(const Pixels & pixels, bool begin) : pixels{pixels}, index{begin ? 0 : get_size(pixels.resolutions)} {} /* ---------------------------------------------------------------------- */ template typename Pixels::iterator::value_type Pixels::iterator::operator*() const { return get_ccoord(pixels.resolutions, pixels.locations, this->index, std::conditional_t, std::index_sequence>{}); } /* ---------------------------------------------------------------------- */ template bool Pixels::iterator:: operator!=(const iterator & other) const { return (this->index != other.index) || (&this->pixels != &other.pixels); } /* ---------------------------------------------------------------------- */ template bool Pixels::iterator:: operator==(const iterator & other) const { return !(*this != other); } /* ---------------------------------------------------------------------- */ template typename Pixels::iterator & Pixels::iterator:: operator++() { ++this->index; return *this; } } // namespace CcoordOps -} // namespace muSpectre +} // namespace muGrid -#endif // SRC_COMMON_CCOORD_OPERATIONS_HH_ +#endif // SRC_LIBMUGRID_CCOORD_OPERATIONS_HH_ diff --git a/src/common/utilities.hh b/src/libmugrid/cpp_compliance.hh similarity index 93% rename from src/common/utilities.hh rename to src/libmugrid/cpp_compliance.hh index 57ad212..709bc85 100644 --- a/src/common/utilities.hh +++ b/src/libmugrid/cpp_compliance.hh @@ -1,185 +1,190 @@ /** * @file utilities.hh * * @author Till Junge * * @date 17 Nov 2017 * * @brief additions to the standard name space to anticipate C++17 features * * Copyright © 2017 Till Junge * - * µSpectre is free software; you can redistribute it and/or + * µGrid is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * - * µSpectre is distributed in the hope that it will be useful, but + * µGrid is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with µSpectre; see the file COPYING. If not, write to the + * along with µGrid; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#ifndef SRC_COMMON_UTILITIES_HH_ -#define SRC_COMMON_UTILITIES_HH_ +#ifndef SRC_LIBMUGRID_CPP_COMPLIANCE_HH_ +#define SRC_LIBMUGRID_CPP_COMPLIANCE_HH_ #include #ifdef NO_EXPERIMENTAL #include #else #include #endif namespace std_replacement { namespace detail { template struct is_reference_wrapper : std::false_type {}; template struct is_reference_wrapper> : std::true_type {}; //! from cppreference template auto INVOKE(T Base::*pmf, Derived && ref, Args &&... args) noexcept(noexcept( (std::forward(ref).*pmf)(std::forward(args)...))) -> std::enable_if_t< std::is_function::value && std::is_base_of>::value, decltype((std::forward(ref).* pmf)(std::forward(args)...))> { return (std::forward(ref).*pmf)(std::forward(args)...); } //! from cppreference template auto INVOKE(T Base::*pmf, RefWrap && ref, Args &&... args) noexcept( noexcept((ref.get().*pmf)(std::forward(args)...))) -> std::enable_if_t< std::is_function::value && is_reference_wrapper>::value, decltype((ref.get().*pmf)(std::forward(args)...))> { return (ref.get().*pmf)(std::forward(args)...); } //! from cppreference template auto INVOKE(T Base::*pmf, Pointer && ptr, Args &&... args) noexcept(noexcept( ((*std::forward(ptr)).*pmf)(std::forward(args)...))) -> std::enable_if_t< std::is_function::value && !is_reference_wrapper>::value && !std::is_base_of>::value, decltype(((*std::forward(ptr)).* pmf)(std::forward(args)...))> { return ((*std::forward(ptr)).*pmf)(std::forward(args)...); } //! from cppreference template auto INVOKE(T Base::*pmd, Derived && ref) noexcept(noexcept(std::forward(ref).*pmd)) -> std::enable_if_t< !std::is_function::value && std::is_base_of>::value, decltype(std::forward(ref).*pmd)> { return std::forward(ref).*pmd; } //! from cppreference template auto INVOKE(T Base::*pmd, RefWrap && ref) noexcept(noexcept(ref.get().*pmd)) -> std::enable_if_t< !std::is_function::value && is_reference_wrapper>::value, decltype(ref.get().*pmd)> { return ref.get().*pmd; } //! from cppreference template auto INVOKE(T Base::*pmd, Pointer && ptr) noexcept( noexcept((*std::forward(ptr)).*pmd)) -> std::enable_if_t< !std::is_function::value && !is_reference_wrapper>::value && !std::is_base_of>::value, decltype((*std::forward(ptr)).*pmd)> { return (*std::forward(ptr)).*pmd; } //! from cppreference template auto INVOKE(F && f, Args &&... args) noexcept( noexcept(std::forward(f)(std::forward(args)...))) -> std::enable_if_t< !std::is_member_pointer>::value, decltype(std::forward(f)(std::forward(args)...))> { return std::forward(f)(std::forward(args)...); } } // namespace detail //! from cppreference template auto invoke(F && f, ArgTypes &&... args) // exception specification for QoI noexcept(noexcept(detail::INVOKE(std::forward(f), std::forward(args)...))) -> decltype(detail::INVOKE(std::forward(f), std::forward(args)...)) { return detail::INVOKE(std::forward(f), std::forward(args)...); } namespace detail { //! from cppreference template constexpr decltype(auto) apply_impl(F && f, Tuple && t, std::index_sequence) { return std_replacement::invoke(std::forward(f), std::get(std::forward(t))...); } } // namespace detail //! from cppreference template constexpr decltype(auto) apply(F && f, Tuple && t) { return detail::apply_impl( std::forward(f), std::forward(t), std::make_index_sequence< std::tuple_size>::value>{}); } } // namespace std_replacement -namespace muSpectre { +namespace muGrid { +#if __cplusplus < 201703L using std_replacement::apply; - /** * emulation `std::optional` (a C++17 feature) */ template #ifdef NO_EXPERIMENTAL using optional = typename boost::optional; #else using optional = typename std::experimental::optional; #endif -} // namespace muSpectre +#else + using std::apply; + using std::optional; +#endif + +} // namespace muGrid -#endif // SRC_COMMON_UTILITIES_HH_ +#endif // SRC_LIBMUGRID_CPP_COMPLIANCE_HH_ diff --git a/src/common/eigen_tools.hh b/src/libmugrid/eigen_tools.hh similarity index 97% rename from src/common/eigen_tools.hh rename to src/libmugrid/eigen_tools.hh index da757d8..4c0f43d 100644 --- a/src/common/eigen_tools.hh +++ b/src/libmugrid/eigen_tools.hh @@ -1,450 +1,450 @@ /** * @file eigen_tools.hh * * @author Till Junge * * @date 20 Sep 2017 * * @brief small tools to be used with Eigen * * Copyright © 2017 Till Junge * - * µSpectre is free software; you can redistribute it and/or + * µGrid is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * - * µSpectre is distributed in the hope that it will be useful, but + * µGrid is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with µSpectre; see the file COPYING. If not, write to the + * along with µGrid; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#ifndef SRC_COMMON_EIGEN_TOOLS_HH_ -#define SRC_COMMON_EIGEN_TOOLS_HH_ +#ifndef SRC_LIBMUGRID_EIGEN_TOOLS_HH_ +#define SRC_LIBMUGRID_EIGEN_TOOLS_HH_ -#include "common/common.hh" +#include "grid_common.hh" #include #include #include #include -namespace muSpectre { +namespace muGrid { /* ---------------------------------------------------------------------- */ namespace internal { //! Creates a Eigen::Sizes type for a Tensor defined by an order and dim template struct SizesByOrderHelper { //! type to use using Sizes = typename SizesByOrderHelper::Sizes; }; //! Creates a Eigen::Sizes type for a Tensor defined by an order and dim template struct SizesByOrderHelper<0, dim, dims...> { //! type to use using Sizes = Eigen::Sizes; }; } // namespace internal //! Creates a Eigen::Sizes type for a Tensor defined by an order and dim template struct SizesByOrder { static_assert(order > 0, "works only for order greater than zero"); //! `Eigen::Sizes` using Sizes = typename internal::SizesByOrderHelper::Sizes; }; /* ---------------------------------------------------------------------- */ namespace internal { /* ---------------------------------------------------------------------- */ //! Call a passed lambda with the unpacked sizes as arguments template struct CallSizesHelper { //! applies the call static decltype(auto) call(Fun_t && fun) { static_assert(order > 0, "can't handle empty sizes b)"); return CallSizesHelper::call(fun); } }; /* ---------------------------------------------------------------------- */ template //! Call a passed lambda with the unpacked sizes as arguments struct CallSizesHelper<0, Fun_t, dim, args...> { //! applies the call static decltype(auto) call(Fun_t && fun) { return fun(args...); } }; } // namespace internal /** * takes a lambda and calls it with the proper `Eigen::Sizes` * unpacked as arguments. Is used to call constructors of a * `Eigen::Tensor` or map thereof in a context where the spatial * dimension is templated */ template inline decltype(auto) call_sizes(Fun_t && fun) { static_assert(order > 1, "can't handle empty sizes"); return internal::CallSizesHelper::call( std::forward(fun)); } // compile-time square root static constexpr Dim_t ct_sqrt(Dim_t res, Dim_t l, Dim_t r) { if (l == r) { return r; } else { const auto mid = (r + l) / 2; if (mid * mid >= res) { return ct_sqrt(res, l, mid); } else { return ct_sqrt(res, mid + 1, r); } } } static constexpr Dim_t ct_sqrt(Dim_t res) { return ct_sqrt(res, 1, res); } namespace EigenCheck { /** * Structure to determine whether an expression can be evaluated * into a `Eigen::Matrix`, `Eigen::Array`, etc. and which helps * determine compile-time size */ template struct is_matrix { //! raw type for testing using T = std::remove_reference_t; //! evaluated test constexpr static bool value{ std::is_same::XprKind, Eigen::MatrixXpr>::value}; }; /** * Helper class to check whether an `Eigen::Array` or * `Eigen::Matrix` is statically sized */ template struct is_fixed { //! raw type for testing using T = std::remove_reference_t; //! evaluated test constexpr static bool value{T::SizeAtCompileTime != Eigen::Dynamic}; }; /** * Helper class to check whether an `Eigen::Array` or `Eigen::Matrix` is a * static-size and square. */ template struct is_square { //! raw type for testing using T = std::remove_reference_t; //! true if the object is square and statically sized constexpr static bool value{ (T::RowsAtCompileTime == T::ColsAtCompileTime) && is_fixed::value}; }; /** * computes the dimension from a second order tensor represented * square matrix or array */ template struct tensor_dim { //! raw type for testing using T = std::remove_reference_t; static_assert(is_matrix::value, "The type of t is not understood as an Eigen::Matrix"); static_assert(is_square::value, "t's matrix isn't square"); //! evaluated dimension constexpr static Dim_t value{T::RowsAtCompileTime}; }; //! computes the dimension from a fourth order tensor represented //! by a square matrix template struct tensor_4_dim { //! raw type for testing using T = std::remove_reference_t; static_assert(is_matrix::value, "The type of t is not understood as an Eigen::Matrix"); static_assert(is_square::value, "t's matrix isn't square"); //! evaluated dimension constexpr static Dim_t value{ct_sqrt(T::RowsAtCompileTime)}; static_assert(value * value == T::RowsAtCompileTime, "This is not a fourth-order tensor mapped on a square " "matrix"); }; namespace internal { template constexpr inline Dim_t get_rank() { constexpr bool is_vec{(nb_row == dim) and (nb_col == 1)}; constexpr bool is_mat{(nb_row == dim) and (nb_col == nb_row)}; constexpr bool is_ten{(nb_row == dim * dim) and (nb_col == dim * dim)}; static_assert(is_vec or is_mat or is_ten, "can't understand the data type as a first-, second-, or " "fourth-order tensor"); if (is_vec) { return firstOrder; } else if (is_mat) { return secondOrder; } else if (is_ten) { return fourthOrder; } } } // namespace internal /** * computes the rank of a tensor given the spatial dimension */ template struct tensor_rank { using T = std::remove_reference_t; static_assert(is_matrix::value, "The type of t is not understood as an Eigen::Matrix"); static constexpr Dim_t value{internal::get_rank()}; }; } // namespace EigenCheck namespace log_comp { //! Matrix type used for logarithm evaluation template using Mat_t = Eigen::Matrix; //! Vector type used for logarithm evaluation template using Vec_t = Eigen::Matrix; //! This is a static implementation of the explicit determination //! of log(Tensor) following Jog, C.S. J Elasticity (2008) 93: //! 141. https://doi.org/10.1007/s10659-008-9169-x /* ---------------------------------------------------------------------- */ template struct Proj { //! wrapped function (raison d'être) static inline decltype(auto) compute(const Vec_t & eigs, const Mat_t & T) { static_assert(dim > 0, "only works for positive dimensions"); return 1. / (eigs(i) - eigs(j)) * (T - eigs(j) * Mat_t::Identity()) * Proj::compute(eigs, T); } }; //! catch the case when there's nothing to do template struct Proj { //! wrapped function (raison d'être) static inline decltype(auto) compute(const Vec_t & eigs, const Mat_t & T) { static_assert(dim > 0, "only works for positive dimensions"); return Proj::compute(eigs, T); } }; //! catch the normal tail case template struct Proj { static constexpr Dim_t j{0}; //!< short-hand //! wrapped function (raison d'être) static inline decltype(auto) compute(const Vec_t & eigs, const Mat_t & T) { static_assert(dim > 0, "only works for positive dimensions"); return 1. / (eigs(i) - eigs(j)) * (T - eigs(j) * Mat_t::Identity()); } }; //! catch the tail case when the last dimension is i template struct Proj { static constexpr Dim_t i{0}; //!< short-hand static constexpr Dim_t j{1}; //!< short-hand //! wrapped function (raison d'être) static inline decltype(auto) compute(const Vec_t & eigs, const Mat_t & T) { static_assert(dim > 0, "only works for positive dimensions"); return 1. / (eigs(i) - eigs(j)) * (T - eigs(j) * Mat_t::Identity()); } }; //! catch the general tail case template <> struct Proj<1, 0, 0> { static constexpr Dim_t dim{1}; //!< short-hand static constexpr Dim_t i{0}; //!< short-hand static constexpr Dim_t j{0}; //!< short-hand //! wrapped function (raison d'être) static inline decltype(auto) compute(const Vec_t & /*eigs*/, const Mat_t & /*T*/) { return Mat_t::Identity(); } }; //! Product term template inline decltype(auto) P(const Vec_t & eigs, const Mat_t & T) { return Proj::compute(eigs, T); } //! sum term template struct Summand { //! wrapped function (raison d'être) static inline decltype(auto) compute(const Vec_t & eigs, const Mat_t & T) { return std::log(eigs(i)) * P(eigs, T) + Summand::compute(eigs, T); } }; //! sum term template struct Summand { static constexpr Dim_t i{0}; //!< short-hand //! wrapped function (raison d'être) static inline decltype(auto) compute(const Vec_t & eigs, const Mat_t & T) { return std::log(eigs(i)) * P(eigs, T); } }; //! sum implementation template inline decltype(auto) Sum(const Vec_t & eigs, const Mat_t & T) { return Summand::compute(eigs, T); } } // namespace log_comp /** * computes the matrix logarithm efficiently for dim=1, 2, or 3 for * a diagonizable tensor. For larger tensors, better use the direct * eigenvalue/vector computation */ template inline decltype(auto) logm(const log_comp::Mat_t & mat) { using Mat = log_comp::Mat_t; Eigen::SelfAdjointEigenSolver Solver{}; Solver.computeDirect(mat, Eigen::EigenvaluesOnly); return Mat{log_comp::Sum(Solver.eigenvalues(), mat)}; } /** * compute the spectral decomposition */ template inline decltype(auto) spectral_decomposition(const Eigen::MatrixBase & mat) { static_assert(Derived::SizeAtCompileTime != Eigen::Dynamic, "works only for static matrices"); static_assert(Derived::RowsAtCompileTime == Derived::ColsAtCompileTime, "works only for square matrices"); constexpr Dim_t dim{Derived::RowsAtCompileTime}; using Mat = log_comp::Mat_t; Eigen::SelfAdjointEigenSolver Solver{}; Solver.computeDirect(mat, Eigen::ComputeEigenvectors); return Solver; } /** * compute the matrix log. This may not be the most * efficient way to do this */ template using Decomp_t = Eigen::SelfAdjointEigenSolver>; template inline decltype(auto) logm_alt(const Decomp_t & spectral_decomp) { using Mat = log_comp::Mat_t; Mat retval{Mat::Zero()}; for (Dim_t i = 0; i < Dim; ++i) { const Real & val = spectral_decomp.eigenvalues()(i); auto & vec = spectral_decomp.eigenvectors().col(i); retval += std::log(val) * vec * vec.transpose(); } return retval; } template inline decltype(auto) logm_alt(const Eigen::MatrixBase & mat) { static_assert(Derived::SizeAtCompileTime != Eigen::Dynamic, "works only for static matrices"); static_assert(Derived::RowsAtCompileTime == Derived::ColsAtCompileTime, "works only for square matrices"); constexpr Dim_t dim{Derived::RowsAtCompileTime}; using Mat = log_comp::Mat_t; using Decomp_t = Eigen::SelfAdjointEigenSolver; Decomp_t decomp{spectral_decomposition(mat)}; return logm_alt(decomp); } /** * compute the matrix exponential. This may not be the most * efficient way to do this */ template inline decltype(auto) expm(const Decomp_t & spectral_decomp) { using Mat = log_comp::Mat_t; Mat retval{Mat::Zero()}; for (Dim_t i = 0; i < Dim; ++i) { const Real & val = spectral_decomp.eigenvalues()(i); auto & vec = spectral_decomp.eigenvectors().col(i); retval += std::exp(val) * vec * vec.transpose(); } return retval; } template inline decltype(auto) expm(const Eigen::MatrixBase & mat) { static_assert(Derived::SizeAtCompileTime != Eigen::Dynamic, "works only for static matrices"); static_assert(Derived::RowsAtCompileTime == Derived::ColsAtCompileTime, "works only for square matrices"); constexpr Dim_t Dim{Derived::RowsAtCompileTime}; using Mat = log_comp::Mat_t; using Decomp_t = Eigen::SelfAdjointEigenSolver; Decomp_t decomp{spectral_decomposition(mat)}; return expm(decomp); } -} // namespace muSpectre +} // namespace muGrid -#endif // SRC_COMMON_EIGEN_TOOLS_HH_ +#endif // SRC_LIBMUGRID_EIGEN_TOOLS_HH_ diff --git a/src/common/field.hh b/src/libmugrid/field.hh similarity index 97% rename from src/common/field.hh rename to src/libmugrid/field.hh index 2d3ca1f..d3d7776 100644 --- a/src/common/field.hh +++ b/src/libmugrid/field.hh @@ -1,666 +1,666 @@ /** * @file field.hh * * @author Till Junge * * @date 07 Sep 2017 * * @brief header-only implementation of a field for field collections * * Copyright © 2017 Till Junge * - * µSpectre is free software; you can redistribute it and/or + * µGrid is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * - * µSpectre is distributed in the hope that it will be useful, but + * µGrid is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with µSpectre; see the file COPYING. If not, write to the + * along with µGrid; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#ifndef SRC_COMMON_FIELD_HH_ -#define SRC_COMMON_FIELD_HH_ +#ifndef SRC_LIBMUGRID_FIELD_HH_ +#define SRC_LIBMUGRID_FIELD_HH_ -#include "common/T4_map_proxy.hh" -#include "common/field_typed.hh" +#include "T4_map_proxy.hh" +#include "field_typed.hh" #include #include #include #include #include #include #include #include #include -namespace muSpectre { +namespace muGrid { namespace internal { /* ---------------------------------------------------------------------- */ //! declaraton for friending template class FieldMap; /* ---------------------------------------------------------------------- */ /** * A `TypedSizedFieldBase` is the base class for fields that contain a * statically known number of scalars of a statically known type per pixel * in a `FieldCollection`. The actual data for all pixels is * stored in `TypedSizeFieldBase::values`. * `TypedSizedFieldBase` is the base class for `MatrixField` and * `TensorField`. */ template class TypedSizedFieldBase : public TypedField { friend class FieldMap; friend class FieldMap; public: //! for compatibility checks constexpr static auto nb_components{NbComponents}; using Parent = TypedField; //!< base class using Scalar = T; //!< for type checking using Base = typename Parent::Base; //!< root base class //! storage container using Storage_t = typename Parent::Storage_t; //! Plain type that is being mapped (Eigen lingo) using EigenRep_t = Eigen::Array; //! maps returned when iterating over field using EigenMap_t = Eigen::Map; //! maps returned when iterating over field using ConstEigenMap_t = Eigen::Map; //! constructor TypedSizedFieldBase(std::string unique_name, FieldCollection & collection); virtual ~TypedSizedFieldBase() = default; //! add a new value at the end of the field template inline void push_back(const Eigen::DenseBase & value); //! add a new scalar value at the end of the field template inline std::enable_if_t push_back(const T & value); /** * returns an upcasted reference to a field, or throws an * exception if the field is incompatible */ static TypedSizedFieldBase & check_ref(Base & other); /** * returns an upcasted reference to a field, or throws an * exception if the field is incompatible */ static const TypedSizedFieldBase & check_ref(const Base & other); //! return a map representing the entire field as a single `Eigen::Array` inline EigenMap_t eigen(); //! return a map representing the entire field as a single `Eigen::Array` inline ConstEigenMap_t eigen() const; /** * return a map representing the entire field as a single * dynamically sized `Eigen::Array` (for python bindings) */ inline typename Parent::EigenMap_t dyn_eigen() { return Parent::eigen(); } //! inner product between compatible fields template inline Real inner_product( const TypedSizedFieldBase & other) const; protected: //! returns a raw pointer to the entry, for `Eigen::Map` inline T * get_ptr_to_entry(const size_t && index); //! returns a raw pointer to the entry, for `Eigen::Map` inline const T * get_ptr_to_entry(const size_t && index) const; }; } // namespace internal /* ---------------------------------------------------------------------- */ /** * The `TensorField` is a subclass of - * `muSpectre::internal::TypedSizedFieldBase` that represents tensorial + * `muGrid::internal::TypedSizedFieldBase` that represents tensorial * fields, i.e. arbitrary-dimensional arrays with identical number of * rows/columns (that typically correspond to the spatial cartesian * dimensions). It is defined by the stored scalar type @a T, the tensorial * order @a order (often also called degree or rank) and the number of spatial * dimensions @a dim. */ template class TensorField : public internal::TypedSizedFieldBase { public: //! base class using Parent = internal::TypedSizedFieldBase; using Base = typename Parent::Base; //!< root base class //! polymorphic base class using Field_p = typename FieldCollection::Field_p; using Scalar = typename Parent::Scalar; //!< for type checking //! Copy constructor TensorField(const TensorField & other) = delete; //! Move constructor TensorField(TensorField && other) = delete; //! Destructor virtual ~TensorField() = default; //! Copy assignment operator TensorField & operator=(const TensorField & other) = delete; //! Move assignment operator TensorField & operator=(TensorField && other) = delete; //! return the order of the stored tensor inline Dim_t get_order() const; //! return the dimension of the stored tensor inline Dim_t get_dim() const; //! factory function template friend FieldType & make_field(std::string unique_name, CollectionType & collection, Args &&... args); //! return a reference or throw an exception if `other` is incompatible static TensorField & check_ref(Base & other) { return static_cast(Parent::check_ref(other)); } //! return a reference or throw an exception if `other` is incompatible static const TensorField & check_ref(const Base & other) { return static_cast(Parent::check_ref(other)); } /** * Convenience functions to return a map onto this field. A map allows * iteration over all pixels. The map's iterator returns an object that * represents the underlying mathematical structure of the field and * implements common linear algebra operations on it. * Specifically, this function returns * - A `MatrixFieldMap` with @a dim rows and one column if the tensorial * order @a order is unity. * - A `MatrixFieldMap` with @a dim rows and @a dim columns if the tensorial * order @a order is 2. * - A `T4MatrixFieldMap` if the tensorial order is 4. */ inline decltype(auto) get_map(); /** * Convenience functions to return a map onto this field. A map allows * iteration over all pixels. The map's iterator returns an object that * represents the underlying mathematical structure of the field and * implements common linear algebra operations on it. * Specifically, this function returns * - A `MatrixFieldMap` with @a dim rows and one column if the tensorial * order @a order is unity. * - A `MatrixFieldMap` with @a dim rows and @a dim columns if the tensorial * order @a order is 2. * - A `T4MatrixFieldMap` if the tensorial order is 4. */ inline decltype(auto) get_const_map(); /** * Convenience functions to return a map onto this field. A map allows * iteration over all pixels. The map's iterator returns an object that * represents the underlying mathematical structure of the field and * implements common linear algebra operations on it. * Specifically, this function returns * - A `MatrixFieldMap` with @a dim rows and one column if the tensorial * order @a order is unity. * - A `MatrixFieldMap` with @a dim rows and @a dim columns if the tensorial * order @a order is 2. * - A `T4MatrixFieldMap` if the tensorial order is 4. */ inline decltype(auto) get_map() const; /** * creates a `TensorField` same size and type as this, but all * entries are zero. Convenience function */ inline TensorField & get_zeros_like(std::string unique_name) const; protected: //! constructor protected! TensorField(std::string unique_name, FieldCollection & collection); private: }; /* ---------------------------------------------------------------------- */ /** - * The `MatrixField` is subclass of `muSpectre::internal::TypedSizedFieldBase` + * The `MatrixField` is subclass of `muGrid::internal::TypedSizedFieldBase` * that represents matrix fields, i.e. a two dimensional arrays, defined by * the stored scalar type @a T and the number of rows @a NbRow and columns * @a NbCol of the matrix. */ template class MatrixField : public internal::TypedSizedFieldBase { public: //! base class using Parent = internal::TypedSizedFieldBase; using Base = typename Parent::Base; //!< root base class //! polymorphic base field ptr to store using Field_p = std::unique_ptr>; //! Copy constructor MatrixField(const MatrixField & other) = delete; //! Move constructor MatrixField(MatrixField && other) = delete; //! Destructor virtual ~MatrixField() = default; //! Copy assignment operator MatrixField & operator=(const MatrixField & other) = delete; //! Move assignment operator MatrixField & operator=(MatrixField && other) = delete; //! returns the number of rows inline Dim_t get_nb_row() const; //! returns the number of columns inline Dim_t get_nb_col() const; //! factory function template friend FieldType & make_field(std::string unique_name, CollectionType & collection, Args &&... args); //! returns a `MatrixField` reference if `other` is a compatible field static MatrixField & check_ref(Base & other) { return static_cast(Parent::check_ref(other)); } //! returns a `MatrixField` reference if `other` is a compatible field static const MatrixField & check_ref(const Base & other) { return static_cast(Parent::check_ref(other)); } /** * Convenience functions to return a map onto this field. A map allows * iteration over all pixels. The map's iterator returns an object that * represents the underlying mathematical structure of the field and * implements common linear algebra operations on it. * Specifically, this function returns * - A `ScalarFieldMap` if @a NbRows and @a NbCols are unity. * - A `MatrixFieldMap` with @a NbRows rows and @a NbCols columns * otherwise. */ inline decltype(auto) get_map(); /** * Convenience functions to return a map onto this field. A map allows * iteration over all pixels. The map's iterator returns an object that * represents the underlying mathematical structure of the field and * implements common linear algebra operations on it. * Specifically, this function returns * - A `ScalarFieldMap` if @a NbRows and @a NbCols are unity. * - A `MatrixFieldMap` with @a NbRows rows and @a NbCols columns * otherwise. */ inline decltype(auto) get_const_map(); /** * Convenience functions to return a map onto this field. A map allows * iteration over all pixels. The map's iterator returns an object that * represents the underlying mathematical structure of the field and * implements common linear algebra operations on it. * Specifically, this function returns * - A `ScalarFieldMap` if @a NbRows and @a NbCols are unity. * - A `MatrixFieldMap` with @a NbRows rows and @a NbCols columns * otherwise. */ inline decltype(auto) get_map() const; /** * creates a `MatrixField` same size and type as this, but all * entries are zero. Convenience function */ inline MatrixField & get_zeros_like(std::string unique_name) const; protected: //! constructor protected! MatrixField(std::string unique_name, FieldCollection & collection); }; /* ---------------------------------------------------------------------- */ //! convenience alias ( template using ScalarField = MatrixField; /* ---------------------------------------------------------------------- */ // Implementations /* ---------------------------------------------------------------------- */ namespace internal { /* ---------------------------------------------------------------------- */ template TypedSizedFieldBase::TypedSizedFieldBase( std::string unique_name, FieldCollection & collection) : Parent(unique_name, collection, NbComponents) { static_assert( (std::is_arithmetic::value || std::is_same::value), "Use TypedSizedFieldBase for integer, real or complex scalars for T"); static_assert(NbComponents > 0, "Only fields with more than 0 components"); } /* ---------------------------------------------------------------------- */ template TypedSizedFieldBase & TypedSizedFieldBase::check_ref( Base & other) { if (typeid(T).hash_code() != other.get_stored_typeid().hash_code()) { std::stringstream err_str{}; err_str << "Cannot create a reference of type '" << typeid(T).name() << "' for field '" << other.get_name() << "' of type '" << other.get_stored_typeid().name() << "'"; throw std::runtime_error(err_str.str()); } // check size compatibility if (NbComponents != other.get_nb_components()) { std::stringstream err_str{}; err_str << "Cannot create a reference to a field with " << NbComponents << " components " << "for field '" << other.get_name() << "' with " << other.get_nb_components() << " components"; throw std::runtime_error{err_str.str()}; } return static_cast(other); } /* ---------------------------------------------------------------------- */ template const TypedSizedFieldBase & TypedSizedFieldBase::check_ref( const Base & other) { if (typeid(T).hash_code() != other.get_stored_typeid().hash_code()) { std::stringstream err_str{}; err_str << "Cannot create a reference of type '" << typeid(T).name() << "' for field '" << other.get_name() << "' of type '" << other.get_stored_typeid().name() << "'"; throw std::runtime_error(err_str.str()); } // check size compatibility if (NbComponents != other.get_nb_components()) { std::stringstream err_str{}; err_str << "Cannot create a reference toy a field with " << NbComponents << " components " << "for field '" << other.get_name() << "' with " << other.get_nb_components() << " components"; throw std::runtime_error{err_str.str()}; } return static_cast(other); } /* ---------------------------------------------------------------------- */ template auto TypedSizedFieldBase::eigen() -> EigenMap_t { return EigenMap_t(this->data(), NbComponents, this->size()); } /* ---------------------------------------------------------------------- */ template auto TypedSizedFieldBase::eigen() const -> ConstEigenMap_t { return ConstEigenMap_t(this->data(), NbComponents, this->size()); } /* ---------------------------------------------------------------------- */ template template Real TypedSizedFieldBase::inner_product( const TypedSizedFieldBase & other) const { return (this->eigen() * other.eigen()).sum(); } /* ---------------------------------------------------------------------- */ template T * TypedSizedFieldBase::get_ptr_to_entry( const size_t && index) { return this->data_ptr + NbComponents * std::move(index); } /* ---------------------------------------------------------------------- */ template const T * TypedSizedFieldBase::get_ptr_to_entry( const size_t && index) const { return this->data_ptr + NbComponents * std::move(index); } /* ---------------------------------------------------------------------- */ template template void TypedSizedFieldBase::push_back( const Eigen::DenseBase & value) { static_assert(Derived::SizeAtCompileTime == NbComponents, "You provided an array with the wrong number of entries."); static_assert((Derived::RowsAtCompileTime == 1) or (Derived::ColsAtCompileTime == 1), "You have not provided a column or row vector."); static_assert(not FieldCollection::Global, "You can only push_back data into local field " "collections."); for (Dim_t i = 0; i < NbComponents; ++i) { this->values.push_back(value(i)); } ++this->current_size; this->data_ptr = &this->values.front(); } /* ---------------------------------------------------------------------- */ template template std::enable_if_t TypedSizedFieldBase::push_back( const T & value) { static_assert(scalar_store, "SFINAE"); this->values.push_back(value); ++this->current_size; this->data_ptr = &this->values.front(); } } // namespace internal /* ---------------------------------------------------------------------- */ template TensorField::TensorField( std::string unique_name, FieldCollection & collection) : Parent(unique_name, collection) {} /* ---------------------------------------------------------------------- */ template Dim_t TensorField::get_order() const { return order; } /* ---------------------------------------------------------------------- */ template Dim_t TensorField::get_dim() const { return dim; } /* ---------------------------------------------------------------------- */ template MatrixField::MatrixField( std::string unique_name, FieldCollection & collection) : Parent(unique_name, collection) {} /* ---------------------------------------------------------------------- */ template Dim_t MatrixField::get_nb_col() const { return NbCol; } /* ---------------------------------------------------------------------- */ template Dim_t MatrixField::get_nb_row() const { return NbRow; } -} // namespace muSpectre +} // namespace muGrid -#include "common/field_map.hh" +#include "field_map.hh" -namespace muSpectre { +namespace muGrid { namespace internal { /* ---------------------------------------------------------------------- */ /** * defines the default mapped type obtained when calling - * `muSpectre::TensorField::get_map()` + * `muGrid::TensorField::get_map()` */ template struct tensor_map_type {}; /// specialisation for vectors template struct tensor_map_type { //! use this type using type = MatrixFieldMap; }; /// specialisation to second-order tensors (matrices) template struct tensor_map_type { //! use this type using type = MatrixFieldMap; }; /// specialisation to fourth-order tensors template struct tensor_map_type { //! use this type using type = T4MatrixFieldMap; }; /* ---------------------------------------------------------------------- */ /** * defines the default mapped type obtained when calling - * `muSpectre::MatrixField::get_map()` + * `muGrid::MatrixField::get_map()` */ template struct matrix_map_type { //! mapping type using type = MatrixFieldMap; }; //! specialisation to scalar fields template struct matrix_map_type { //! mapping type using type = ScalarFieldMap; }; } // namespace internal /* ---------------------------------------------------------------------- */ template auto TensorField::get_map() -> decltype(auto) { constexpr bool map_constness{false}; using RawMap_t = typename internal::tensor_map_type::type; return RawMap_t(*this); } /* ---------------------------------------------------------------------- */ template auto TensorField::get_const_map() -> decltype(auto) { constexpr bool map_constness{true}; using RawMap_t = typename internal::tensor_map_type::type; return RawMap_t(*this); } /* ---------------------------------------------------------------------- */ template auto TensorField::get_map() const -> decltype(auto) { constexpr bool map_constness{true}; using RawMap_t = typename internal::tensor_map_type::type; return RawMap_t(*this); } /* ---------------------------------------------------------------------- */ template auto TensorField::get_zeros_like( std::string unique_name) const -> TensorField & { return make_field(unique_name, this->collection); } /* ---------------------------------------------------------------------- */ template auto MatrixField::get_map() -> decltype(auto) { constexpr bool map_constness{false}; using RawMap_t = typename internal::matrix_map_type::type; return RawMap_t(*this); } /* ---------------------------------------------------------------------- */ template auto MatrixField::get_const_map() -> decltype(auto) { constexpr bool map_constness{true}; using RawMap_t = typename internal::matrix_map_type::type; return RawMap_t(*this); } /* ---------------------------------------------------------------------- */ template auto MatrixField::get_map() const -> decltype(auto) { constexpr bool map_constness{true}; using RawMap_t = typename internal::matrix_map_type::type; return RawMap_t(*this); } /* ---------------------------------------------------------------------- */ template auto MatrixField::get_zeros_like( std::string unique_name) const -> MatrixField & { return make_field(unique_name, this->collection); } -} // namespace muSpectre +} // namespace muGrid -#endif // SRC_COMMON_FIELD_HH_ +#endif // SRC_LIBMUGRID_FIELD_HH_ diff --git a/src/common/field_base.hh b/src/libmugrid/field_base.hh similarity index 94% rename from src/common/field_base.hh rename to src/libmugrid/field_base.hh index effa348..a497fc9 100644 --- a/src/common/field_base.hh +++ b/src/libmugrid/field_base.hh @@ -1,209 +1,209 @@ /** * file field_base.hh * * @author Till Junge * * @date 10 Apr 2018 * * @brief Virtual base class for fields * * Copyright © 2018 Till Junge * - * µSpectre is free software; you can redistribute it and/or + * µGrid is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * - * µSpectre is distributed in the hope that it will be useful, but + * µGrid is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with µSpectre; see the file COPYING. If not, write to the + * along with µGrid; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#ifndef SRC_COMMON_FIELD_BASE_HH_ -#define SRC_COMMON_FIELD_BASE_HH_ +#ifndef SRC_LIBMUGRID_FIELD_BASE_HH_ +#define SRC_LIBMUGRID_FIELD_BASE_HH_ #include #include -namespace muSpectre { +namespace muGrid { /* ---------------------------------------------------------------------- */ /** * base class for field collection-related exceptions */ class FieldCollectionError : public std::runtime_error { public: //! constructor explicit FieldCollectionError(const std::string & what) : std::runtime_error(what) {} //! constructor explicit FieldCollectionError(const char * what) : std::runtime_error(what) {} }; /// base class for field-related exceptions class FieldError : public FieldCollectionError { using Parent = FieldCollectionError; public: //! constructor explicit FieldError(const std::string & what) : Parent(what) {} //! constructor explicit FieldError(const char * what) : Parent(what) {} }; /** * Thrown when a associating a field map to and incompatible field * is attempted */ class FieldInterpretationError : public FieldError { public: //! constructor explicit FieldInterpretationError(const std::string & what) : FieldError(what) {} //! constructor explicit FieldInterpretationError(const char * what) : FieldError(what) {} }; namespace internal { /* ---------------------------------------------------------------------- */ /** * Virtual base class for all fields. A field represents * meta-information for the per-pixel storage for a scalar, vector * or tensor quantity and is therefore the abstract class defining * the field. It is used for type and size checking at runtime and * for storage of polymorphic pointers to fully typed and sized * fields. `FieldBase` (and its children) are templated with a * specific `FieldCollection` (derived from - * `muSpectre::FieldCollectionBase`). A `FieldCollection` stores + * `muGrid::FieldCollectionBase`). A `FieldCollection` stores * multiple fields that all apply to the same set of * pixels. Addressing and managing the data for all pixels is * handled by the `FieldCollection`. Note that `FieldBase` does * not know anything about about mathematical operations on the * data or how to iterate over all pixels. Mapping the raw data * onto for instance Eigen maps and iterating over those is * handled by the `FieldMap`. */ template class FieldBase { protected: //! constructor //! unique name (whithin Collection) //! number of components //! collection to which this field belongs (eg, material, cell) FieldBase(std::string unique_name, size_t nb_components, FieldCollection & collection); public: using collection_t = FieldCollection; //!< for type checks //! Copy constructor FieldBase(const FieldBase & other) = delete; //! Move constructor FieldBase(FieldBase && other) = delete; //! Destructor virtual ~FieldBase() = default; //! Copy assignment operator FieldBase & operator=(const FieldBase & other) = delete; //! Move assignment operator FieldBase & operator=(FieldBase && other) = delete; /* ---------------------------------------------------------------------- */ //! Identifying accessors //! return field name inline const std::string & get_name() const; //! return field type // inline const Field_t & get_type() const; //! return my collection (for iterating) inline const FieldCollection & get_collection() const; //! return number of components (e.g., dimensions) of this field inline const size_t & get_nb_components() const; //! return type_id of stored type virtual const std::type_info & get_stored_typeid() const = 0; //! number of pixels in the field virtual size_t size() const = 0; //! add a pad region to the end of the field buffer; required for //! using this as e.g. an FFT workspace virtual void set_pad_size(size_t pad_size_) = 0; //! pad region size virtual size_t get_pad_size() const { return this->pad_size; } //! initialise field to zero (do more complicated initialisations through //! fully typed maps) virtual void set_zero() = 0; //! give access to collections friend FieldCollection; //! give access to collection's base class using FParent_t = typename FieldCollection::Parent; friend FParent_t; protected: /* ---------------------------------------------------------------------- */ //! allocate memory etc virtual void resize(size_t size) = 0; const std::string name; //!< the field's unique name const size_t nb_components; //!< number of components per entry //! reference to the collection this field belongs to FieldCollection & collection; size_t pad_size; //!< size of padding region at end of buffer }; /* ---------------------------------------------------------------------- */ // Implementations /* ---------------------------------------------------------------------- */ template FieldBase::FieldBase(std::string unique_name, size_t nb_components_, FieldCollection & collection_) : name(unique_name), nb_components(nb_components_), collection(collection_), pad_size{0} {} /* ---------------------------------------------------------------------- */ template inline const std::string & FieldBase::get_name() const { return this->name; } /* ---------------------------------------------------------------------- */ template inline const FieldCollection & FieldBase::get_collection() const { return this->collection; } /* ---------------------------------------------------------------------- */ template inline const size_t & FieldBase::get_nb_components() const { return this->nb_components; } } // namespace internal -} // namespace muSpectre +} // namespace muGrid -#endif // SRC_COMMON_FIELD_BASE_HH_ +#endif // SRC_LIBMUGRID_FIELD_BASE_HH_ diff --git a/src/common/field_collection.hh b/src/libmugrid/field_collection.hh similarity index 74% copy from src/common/field_collection.hh copy to src/libmugrid/field_collection.hh index 7b057a5..586d95f 100644 --- a/src/common/field_collection.hh +++ b/src/libmugrid/field_collection.hh @@ -1,42 +1,42 @@ /** * @file field_collection.hh * * @author Till Junge * * @date 07 Sep 2017 * * @brief Provides pixel-iterable containers for scalar and tensorial fields, * addressable by field name * * Copyright © 2017 Till Junge * - * µSpectre is free software; you can redistribute it and/or + * µGrid is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * - * µSpectre is distributed in the hope that it will be useful, but + * µGrid is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with µSpectre; see the file COPYING. If not, write to the + * along with µGrid; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#ifndef SRC_COMMON_FIELD_COLLECTION_HH_ -#define SRC_COMMON_FIELD_COLLECTION_HH_ +#ifndef SRC_LIBMUGRID_FIELD_COLLECTION_HH_ +#define SRC_LIBMUGRID_FIELD_COLLECTION_HH_ -#include "common/field_collection_global.hh" -#include "common/field_collection_local.hh" +#include "field_collection_global.hh" +#include "field_collection_local.hh" -#endif // SRC_COMMON_FIELD_COLLECTION_HH_ +#endif // SRC_LIBMUGRID_FIELD_COLLECTION_HH_ diff --git a/src/common/field_collection_base.hh b/src/libmugrid/field_collection_base.hh similarity index 96% rename from src/common/field_collection_base.hh rename to src/libmugrid/field_collection_base.hh index fa3634d..37881fe 100644 --- a/src/common/field_collection_base.hh +++ b/src/libmugrid/field_collection_base.hh @@ -1,383 +1,383 @@ /** * @file field_collection_base.hh * * @author Till Junge * * @date 05 Nov 2017 * * @brief Base class for field collections * * Copyright © 2017 Till Junge * - * µSpectre is free software; you can redistribute it and/or + * µGrid is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * - * µSpectre is distributed in the hope that it will be useful, but + * µGrid is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with µSpectre; see the file COPYING. If not, write to the + * along with µGrid; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#ifndef SRC_COMMON_FIELD_COLLECTION_BASE_HH_ -#define SRC_COMMON_FIELD_COLLECTION_BASE_HH_ +#ifndef SRC_LIBMUGRID_FIELD_COLLECTION_BASE_HH_ +#define SRC_LIBMUGRID_FIELD_COLLECTION_BASE_HH_ -#include "common/common.hh" -#include "common/field.hh" -#include "common/statefield.hh" +#include "grid_common.hh" +#include "field.hh" +#include "statefield.hh" #include #include -namespace muSpectre { +namespace muGrid { /* ---------------------------------------------------------------------- */ /** `FieldCollectionBase` is the base class for collections of fields. All * fields in a field collection have the same number of pixels. The field * collection is templated with @a DimS is the spatial dimension (i.e. * whether the simulation domain is one, two or three-dimensional). * All fields within a field collection have a unique string identifier. * A `FieldCollectionBase` is therefore comparable to a dictionary of fields * that live on the same grid. * `FieldCollectionBase` has the specialisations `GlobalFieldCollection` and * `LocalFieldCollection`. */ template class FieldCollectionBase { public: //! polymorphic base type to store using Field_t = internal::FieldBase; template using TypedField_t = TypedField; using Field_p = std::unique_ptr; //!< stored type using StateField_t = StateFieldBase; template using TypedStateField_t = TypedStateField; using StateField_p = std::unique_ptr; using Ccoord = Ccoord_t; //!< cell coordinates type using Rcoord = Rcoord_t; //!< cell coordinates type //! Default constructor FieldCollectionBase(); //! Copy constructor FieldCollectionBase(const FieldCollectionBase & other) = delete; //! Move constructor FieldCollectionBase(FieldCollectionBase && other) = delete; //! Destructor virtual ~FieldCollectionBase() = default; //! Copy assignment operator FieldCollectionBase & operator=(const FieldCollectionBase & other) = delete; //! Move assignment operator FieldCollectionBase & operator=(FieldCollectionBase && other) = delete; //! Register a new field (fields need to be in heap, so I want to keep them //! as shared pointers void register_field(Field_p && field); //! Register a new field (fields need to be in heap, so I want to keep them //! as shared pointers void register_statefield(StateField_p && field); //! for return values of iterators constexpr inline static Dim_t spatial_dim(); //! for return values of iterators inline Dim_t get_spatial_dim() const; //! return names of all stored fields std::vector get_field_names() const { std::vector names{}; for (auto & tup : this->fields) { names.push_back(std::get<0>(tup)); } return names; } //! return names of all state fields std::vector get_statefield_names() const { std::vector names{}; for (auto & tup : this->statefields) { names.push_back(std::get<0>(tup)); } return names; } //! retrieve field by unique_name inline Field_t & operator[](std::string unique_name); //! retrieve field by unique_name with bounds checking inline Field_t & at(std::string unique_name); //! retrieve typed field by unique_name template inline TypedField_t & get_typed_field(std::string unique_name); //! retrieve state field by unique_prefix with bounds checking template inline TypedStateField_t & get_typed_statefield(std::string unique_prefix); //! retrieve state field by unique_prefix with bounds checking inline StateField_t & get_statefield(std::string unique_prefix) { return *(this->statefields.at(unique_prefix)); } //! retrieve state field by unique_prefix with bounds checking inline const StateField_t & get_statefield(std::string unique_prefix) const { return *(this->statefields.at(unique_prefix)); } /** * retrieve current value of typed state field by unique_prefix with * bounds checking */ template inline TypedField_t & get_current(std::string unique_prefix); /** * retrieve old value of typed state field by unique_prefix with * bounds checking */ template inline const TypedField_t & get_old(std::string unique_prefix, size_t nb_steps_ago = 1) const; //! returns size of collection, this refers to the number of pixels handled //! by the collection, not the number of fields inline size_t size() const { return this->size_; } //! check whether a field is present bool check_field_exists(const std::string & unique_name); //! check whether a field is present bool check_statefield_exists(const std::string & unique_prefix); //! check whether the collection is initialised bool initialised() const { return this->is_initialised; } /** * list the names of all fields */ std::vector list_fields() const; protected: std::map fields{}; //!< contains the field ptrs //! contains ptrs to state fields std::map statefields{}; bool is_initialised{false}; //!< to handle double initialisation correctly const Uint id; //!< unique identifier static Uint counter; //!< used to assign unique identifiers size_t size_{0}; //!< holds the number of pixels after initialisation }; /* ---------------------------------------------------------------------- */ template Uint FieldCollectionBase::counter{0}; /* ---------------------------------------------------------------------- */ template FieldCollectionBase::FieldCollectionBase() : id(counter++) {} /* ---------------------------------------------------------------------- */ template void FieldCollectionBase::register_field( Field_p && field) { if (this->check_field_exists(field->get_name())) { std::stringstream err_str; err_str << "a field named '" << field->get_name() << "' is already registered in this field collection. " << "Currently registered fields: "; std::string prelude{""}; for (const auto & name_field_pair : this->fields) { err_str << prelude << '\'' << name_field_pair.first << '\''; prelude = ", "; } throw FieldCollectionError(err_str.str()); } if (this->is_initialised) { field->resize(this->size()); } this->fields[field->get_name()] = std::move(field); } /* ---------------------------------------------------------------------- */ template void FieldCollectionBase::register_statefield( StateField_p && field) { auto && search_it = this->statefields.find(field->get_prefix()); auto && does_exist = search_it != this->statefields.end(); if (does_exist) { std::stringstream err_str; err_str << "a state field named '" << field->get_prefix() << "' is already registered in this field collection. " << "Currently registered fields: "; std::string prelude{""}; for (const auto & name_field_pair : this->statefields) { err_str << prelude << '\'' << name_field_pair.first << '\''; prelude = ", "; } throw FieldCollectionError(err_str.str()); } this->statefields[field->get_prefix()] = std::move(field); } /* ---------------------------------------------------------------------- */ template constexpr Dim_t FieldCollectionBase::spatial_dim() { return DimS; } /* ---------------------------------------------------------------------- */ template Dim_t FieldCollectionBase::get_spatial_dim() const { return DimS; } /* ---------------------------------------------------------------------- */ template auto FieldCollectionBase:: operator[](std::string unique_name) -> Field_t & { return *(this->fields[unique_name]); } /* ---------------------------------------------------------------------- */ template auto FieldCollectionBase::at(std::string unique_name) -> Field_t & { return *(this->fields.at(unique_name)); } /* ---------------------------------------------------------------------- */ template bool FieldCollectionBase::check_field_exists( const std::string & unique_name) { return this->fields.find(unique_name) != this->fields.end(); } /* ---------------------------------------------------------------------- */ template bool FieldCollectionBase::check_statefield_exists( const std::string & unique_prefix) { return this->statefields.find(unique_prefix) != this->statefields.end(); } //! retrieve typed field by unique_name template template auto FieldCollectionBase::get_typed_field( std::string unique_name) -> TypedField_t & { auto & unqualified_field{this->at(unique_name)}; if (unqualified_field.get_stored_typeid().hash_code() != typeid(T).hash_code()) { std::stringstream err{}; err << "Field '" << unique_name << "' is of type " << unqualified_field.get_stored_typeid().name() << ", but should be of type " << typeid(T).name() << std::endl; throw FieldCollectionError(err.str()); } return static_cast &>(unqualified_field); } /* ---------------------------------------------------------------------- */ //! retrieve state field by unique_prefix with bounds checking template template auto FieldCollectionBase::get_typed_statefield( std::string unique_prefix) -> TypedStateField_t & { auto & unqualified_statefield{this->get_statefield(unique_prefix)}; if (unqualified_statefield.get_stored_typeid().hash_code() != typeid(T).hash_code()) { std::stringstream err{}; err << "Statefield '" << unique_prefix << "' is of type " << unqualified_statefield.get_stored_typeid().name() << ", but should be of type " << typeid(T).name() << std::endl; throw FieldCollectionError(err.str()); } return static_cast &>(unqualified_statefield); } /* ---------------------------------------------------------------------- */ template std::vector FieldCollectionBase::list_fields() const { std::vector ret_val{}; for (auto & key_val : this->fields) { ret_val.push_back(key_val.first); } return ret_val; } /* ---------------------------------------------------------------------- */ template template auto FieldCollectionBase::get_current( std::string unique_prefix) -> TypedField_t & { auto & unqualified_statefield = this->get_statefield(unique_prefix); //! check for correct underlying fundamental type if (unqualified_statefield.get_stored_typeid().hash_code() != typeid(T).hash_code()) { std::stringstream err{}; err << "StateField '" << unique_prefix << "' is of type " << unqualified_statefield.get_stored_typeid().name() << ", but should be of type " << typeid(T).name() << std::endl; throw FieldCollectionError(err.str()); } using Typed_t = TypedStateField; auto & typed_field{static_cast(unqualified_statefield)}; return typed_field.get_current_field(); } /* ---------------------------------------------------------------------- */ /* ---------------------------------------------------------------------- */ template template auto FieldCollectionBase::get_old( std::string unique_prefix, size_t nb_steps_ago) const -> const TypedField_t & { auto & unqualified_statefield = this->get_statefield(unique_prefix); //! check for correct underlying fundamental type if (unqualified_statefield.get_stored_typeid().hash_code() != typeid(T).hash_code()) { std::stringstream err{}; err << "StateField '" << unique_prefix << "' is of type " << unqualified_statefield.get_stored_typeid().name() << ", but should be of type " << typeid(T).name() << std::endl; throw FieldCollectionError(err.str()); } using Typed_t = TypedStateField; auto & typed_field{static_cast(unqualified_statefield)}; return typed_field.get_old_field(nb_steps_ago); } -} // namespace muSpectre +} // namespace muGrid -#endif // SRC_COMMON_FIELD_COLLECTION_BASE_HH_ +#endif // SRC_LIBMUGRID_FIELD_COLLECTION_BASE_HH_ diff --git a/src/common/field_collection_global.hh b/src/libmugrid/field_collection_global.hh similarity index 94% rename from src/common/field_collection_global.hh rename to src/libmugrid/field_collection_global.hh index f209413..2b76852 100644 --- a/src/common/field_collection_global.hh +++ b/src/libmugrid/field_collection_global.hh @@ -1,216 +1,216 @@ /** * @file field_collection_global.hh * * @author Till Junge * * @date 05 Nov 2017 * * @brief FieldCollection base-class for global fields * * Copyright © 2017 Till Junge * - * µSpectre is free software; you can redistribute it and/or + * µGrid is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * - * µSpectre is distributed in the hope that it will be useful, but + * µGrid is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with µSpectre; see the file COPYING. If not, write to the + * along with µGrid; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#ifndef SRC_COMMON_FIELD_COLLECTION_GLOBAL_HH_ -#define SRC_COMMON_FIELD_COLLECTION_GLOBAL_HH_ +#ifndef SRC_LIBMUGRID_FIELD_COLLECTION_GLOBAL_HH_ +#define SRC_LIBMUGRID_FIELD_COLLECTION_GLOBAL_HH_ -#include "common/ccoord_operations.hh" -#include "common/field_collection_base.hh" +#include "ccoord_operations.hh" +#include "field_collection_base.hh" -namespace muSpectre { +namespace muGrid { /** * forward declaration */ template class LocalFieldCollection; /** `GlobalFieldCollection` derives from `FieldCollectionBase` and stores * global fields that live throughout the whole computational domain, i.e. * are defined for each pixel. */ template class GlobalFieldCollection : public FieldCollectionBase> { public: //! for compile time check constexpr static bool Global{true}; using Parent = FieldCollectionBase>; //!< base class //! helpful for functions that fill global fields from local fields using LocalFieldCollection_t = LocalFieldCollection; //! helpful for functions that fill global fields from local fields using GlobalFieldCollection_t = GlobalFieldCollection; using Ccoord = typename Parent::Ccoord; //!< cell coordinates type using Field_p = typename Parent::Field_p; //!< spatial coordinates type //! iterator over all pixels contained it the collection using iterator = typename CcoordOps::Pixels::iterator; //! Default constructor GlobalFieldCollection(); //! Copy constructor GlobalFieldCollection(const GlobalFieldCollection & other) = delete; //! Move constructor GlobalFieldCollection(GlobalFieldCollection && other) = default; //! Destructor virtual ~GlobalFieldCollection() = default; //! Copy assignment operator GlobalFieldCollection & operator=(const GlobalFieldCollection & other) = delete; //! Move assignment operator GlobalFieldCollection & operator=(GlobalFieldCollection && other) = default; /** allocate memory, etc. At this point, the collection is informed aboud the size and shape of the domain (through the sizes parameter). The job of initialise is to make sure that all fields are either of size 0, in which case they need to be allocated, or are of the same size as the product of 'sizes' (if standard strides apply) any field of a different size is wrong. TODO: check whether it makes sense to put a runtime check here **/ inline void initialise(Ccoord sizes, Ccoord locations); //! return subdomain resolutions inline const Ccoord & get_sizes() const; //! return subdomain locations inline const Ccoord & get_locations() const; //! returns the linear index corresponding to cell coordinates template inline size_t get_index(CcoordRef && ccoord) const; //! returns the cell coordinates corresponding to a linear index inline Ccoord get_ccoord(size_t index) const; inline iterator begin() const; //!< returns iterator to first pixel inline iterator end() const; //!< returns iterator past the last pixel //! return spatial dimension (template parameter) static constexpr inline Dim_t spatial_dim() { return DimS; } //! return globalness at compile time static constexpr inline bool is_global() { return Global; } protected: //! number of discretisation cells in each of the DimS spatial directions Ccoord sizes{}; //! subdomain locations (i.e. coordinates of hind bottom left corner of this //! subdomain) Ccoord locations{}; CcoordOps::Pixels pixels{}; //!< helper to iterate over the grid private: }; /* ---------------------------------------------------------------------- */ template GlobalFieldCollection::GlobalFieldCollection() : Parent() {} /* ---------------------------------------------------------------------- */ template void GlobalFieldCollection::initialise(Ccoord sizes, Ccoord locations) { if (this->is_initialised) { throw std::runtime_error("double initialisation"); } this->pixels = CcoordOps::Pixels(sizes, locations); this->size_ = CcoordOps::get_size(sizes); this->sizes = sizes; this->locations = locations; std::for_each( std::begin(this->fields), std::end(this->fields), [this](auto && item) { auto && field = *item.second; const auto field_size = field.size(); if (field_size == 0) { field.resize(this->size()); } else if (field_size != this->size()) { std::stringstream err_stream; err_stream << "Field '" << field.get_name() << "' contains " << field_size << " entries, but the field collection " << "has " << this->size() << " pixels"; throw FieldCollectionError(err_stream.str()); } }); this->is_initialised = true; } //----------------------------------------------------------------------------// //! return subdomain resolutions template const typename GlobalFieldCollection::Ccoord & GlobalFieldCollection::get_sizes() const { return this->sizes; } //----------------------------------------------------------------------------// //! return subdomain locations template const typename GlobalFieldCollection::Ccoord & GlobalFieldCollection::get_locations() const { return this->locations; } //----------------------------------------------------------------------------// //! returns the cell coordinates corresponding to a linear index template typename GlobalFieldCollection::Ccoord GlobalFieldCollection::get_ccoord(size_t index) const { return CcoordOps::get_ccoord(this->get_sizes(), this->get_locations(), std::move(index)); } /* ---------------------------------------------------------------------- */ template typename GlobalFieldCollection::iterator GlobalFieldCollection::begin() const { return this->pixels.begin(); } /* ---------------------------------------------------------------------- */ template typename GlobalFieldCollection::iterator GlobalFieldCollection::end() const { return this->pixels.end(); } //-------------------------------------------------------------------------// //! returns the linear index corresponding to cell coordinates template template size_t GlobalFieldCollection::get_index(CcoordRef && ccoord) const { static_assert( std::is_same>>::value, "can only be called with values or references of Ccoord"); return CcoordOps::get_index(this->get_sizes(), this->get_locations(), std::forward(ccoord)); } -} // namespace muSpectre +} // namespace muGrid -#endif // SRC_COMMON_FIELD_COLLECTION_GLOBAL_HH_ +#endif // SRC_LIBMUGRID_FIELD_COLLECTION_GLOBAL_HH_ diff --git a/src/common/field_collection_local.hh b/src/libmugrid/field_collection_local.hh similarity index 94% rename from src/common/field_collection_local.hh rename to src/libmugrid/field_collection_local.hh index ea129f8..5ff3751 100644 --- a/src/common/field_collection_local.hh +++ b/src/libmugrid/field_collection_local.hh @@ -1,199 +1,199 @@ /** * @file field_collection_local.hh * * @author Till Junge * * @date 05 Nov 2017 * * @brief FieldCollection base-class for local fields * * Copyright © 2017 Till Junge * - * µSpectre is free software; you can redistribute it and/or + * µGrid is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * - * µSpectre is distributed in the hope that it will be useful, but + * µGrid is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with µSpectre; see the file COPYING. If not, write to the + * along with µGrid; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#ifndef SRC_COMMON_FIELD_COLLECTION_LOCAL_HH_ -#define SRC_COMMON_FIELD_COLLECTION_LOCAL_HH_ +#ifndef SRC_LIBMUGRID_FIELD_COLLECTION_LOCAL_HH_ +#define SRC_LIBMUGRID_FIELD_COLLECTION_LOCAL_HH_ -#include "common/field_collection_base.hh" +#include "field_collection_base.hh" -namespace muSpectre { +namespace muGrid { /** * forward declaration */ template class GlobalFieldCollection; /** `LocalFieldCollection` derives from `FieldCollectionBase` and stores * local fields, i.e. fields that are only defined for a subset of all pixels * in the computational domain. The coordinates of these active pixels are * explicitly stored by this field collection. * `LocalFieldCollection::add_pixel` allows to add individual pixels to the * field collection. */ template class LocalFieldCollection : public FieldCollectionBase> { public: //! for compile time check constexpr static bool Global{false}; //! base class using Parent = FieldCollectionBase>; //! helpful for functions that fill local fields from global fields using GlobalFieldCollection_t = GlobalFieldCollection; //! helpful for functions that fill local fields from global fields using LocalFieldCollection_t = LocalFieldCollection; using Ccoord = typename Parent::Ccoord; //!< cell coordinates type using Field_p = typename Parent::Field_p; //!< field pointer using ccoords_container = std::vector; //!< list of pixels //! iterator over managed pixels using iterator = typename ccoords_container::iterator; //! const iterator over managed pixels using const_iterator = typename ccoords_container::const_iterator; //! Default constructor LocalFieldCollection(); //! Copy constructor LocalFieldCollection(const LocalFieldCollection & other) = delete; //! Move constructor LocalFieldCollection(LocalFieldCollection && other) = delete; //! Destructor virtual ~LocalFieldCollection() = default; //! Copy assignment operator LocalFieldCollection & operator=(const LocalFieldCollection & other) = delete; //! Move assignment operator LocalFieldCollection & operator=(LocalFieldCollection && other) = delete; //! add a pixel/voxel to the field collection inline void add_pixel(const Ccoord & local_ccoord); /** allocate memory, etc. at this point, the field collection knows how many entries it should have from the size of the coords containes (which grows by one every time add_pixel is called. The job of initialise is to make sure that all fields are either of size 0, in which case they need to be allocated, or are of the same size as the product of 'sizes' any field of a different size is wrong TODO: check whether it makes sense to put a runtime check here **/ inline void initialise(); //! returns the linear index corresponding to cell coordinates template inline size_t get_index(CcoordRef && ccoord) const; //! returns the cell coordinates corresponding to a linear index inline Ccoord get_ccoord(size_t index) const; //! iterator to first pixel inline iterator begin() { return this->ccoords.begin(); } //! iterator past last pixel inline iterator end() { return this->ccoords.end(); } //! const iterator to first pixel inline const_iterator begin() const { return this->ccoords.cbegin(); } //! const iterator past last pixel inline const_iterator end() const { return this->ccoords.cend(); } //! return globalness at compile time static constexpr inline bool is_global() { return Global; } protected: //! container of pixel coords for non-global collections ccoords_container ccoords{}; //! container of indices for non-global collections (slow!) std::map indices{}; std::vector assigned_ratio{}; private: }; /* ---------------------------------------------------------------------- */ template LocalFieldCollection::LocalFieldCollection() : Parent() {} /* ---------------------------------------------------------------------- */ template void LocalFieldCollection::add_pixel(const Ccoord & local_ccoord) { if (this->is_initialised) { throw FieldCollectionError( "once a field collection has been initialised, you can't add new " "pixels."); } this->indices[local_ccoord] = this->ccoords.size(); this->ccoords.push_back(local_ccoord); this->size_++; } /* ---------------------------------------------------------------------- */ template void LocalFieldCollection::initialise() { if (this->is_initialised) { throw std::runtime_error("double initialisation"); } std::for_each( std::begin(this->fields), std::end(this->fields), [this](auto && item) { auto && field = *item.second; const auto field_size = field.size(); if (field_size == 0) { field.resize(this->size()); } else if (field_size != this->size()) { std::stringstream err_stream; err_stream << "Field '" << field.get_name() << "' contains " << field_size << " entries, but the field collection " << "has " << this->size() << " pixels"; throw FieldCollectionError(err_stream.str()); } }); this->is_initialised = true; } //----------------------------------------------------------------------------// //! returns the linear index corresponding to cell coordinates template template size_t LocalFieldCollection::get_index(CcoordRef && ccoord) const { static_assert( std::is_same>>::value, "can only be called with values or references of Ccoord"); return this->indices.at(std::forward(ccoord)); } //----------------------------------------------------------------------------// //! returns the cell coordinates corresponding to a linear index template typename LocalFieldCollection::Ccoord LocalFieldCollection::get_ccoord(size_t index) const { return this->ccoords[std::move(index)]; } -} // namespace muSpectre +} // namespace muGrid -#endif // SRC_COMMON_FIELD_COLLECTION_LOCAL_HH_ +#endif // SRC_LIBMUGRID_FIELD_COLLECTION_LOCAL_HH_ diff --git a/src/common/field_helpers.hh b/src/libmugrid/field_helpers.hh similarity index 82% rename from src/common/field_helpers.hh rename to src/libmugrid/field_helpers.hh index ff13a68..c55ffb8 100644 --- a/src/common/field_helpers.hh +++ b/src/libmugrid/field_helpers.hh @@ -1,59 +1,59 @@ /** * file field_helpers.hh * * @author Till Junge * * @date 30 Aug 2018 * * @brief helper functions that needed to be sequestered to avoid circular * inclusions * * Copyright © 2018 Till Junge * - * µSpectre is free software; you can redistribute it and/or + * µGrid is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * - * µSpectre is distributed in the hope that it will be useful, but + * µGrid is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with µSpectre; see the file COPYING. If not, write to the + * along with µGrid; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#ifndef SRC_COMMON_FIELD_HELPERS_HH_ -#define SRC_COMMON_FIELD_HELPERS_HH_ +#ifndef SRC_LIBMUGRID_FIELD_HELPERS_HH_ +#define SRC_LIBMUGRID_FIELD_HELPERS_HH_ #include -namespace muSpectre { +namespace muGrid { /** * Factory function, guarantees that only fields get created that * are properly registered and linked to a collection. */ template inline FieldType & make_field(std::string unique_name, FieldCollection & collection, Args &&... args) { std::unique_ptr ptr{ new FieldType(unique_name, collection, args...)}; auto & retref{*ptr}; collection.register_field(std::move(ptr)); return retref; } -} // namespace muSpectre +} // namespace muGrid -#endif // SRC_COMMON_FIELD_HELPERS_HH_ +#endif // SRC_LIBMUGRID_FIELD_HELPERS_HH_ diff --git a/src/common/field_map.hh b/src/libmugrid/field_map.hh similarity index 94% rename from src/common/field_map.hh rename to src/libmugrid/field_map.hh index 75cc556..19afcb7 100644 --- a/src/common/field_map.hh +++ b/src/libmugrid/field_map.hh @@ -1,259 +1,259 @@ /** * @file field_map.hh * * @author Till Junge * * @date 26 Sep 2017 * * @brief just and indirection to include all iterables defined for fields * * Copyright © 2017 Till Junge * - * µSpectre is free software; you can redistribute it and/or + * µGrid is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * - * µSpectre is distributed in the hope that it will be useful, but + * µGrid is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with µSpectre; see the file COPYING. If not, write to the + * along with µGrid; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#include "common/field_map_tensor.hh" -#include "common/field_map_matrixlike.hh" -#include "common/field_map_scalar.hh" +#include "field_map_tensor.hh" +#include "field_map_matrixlike.hh" +#include "field_map_scalar.hh" #include #include #include -#ifndef SRC_COMMON_FIELD_MAP_HH_ -#define SRC_COMMON_FIELD_MAP_HH_ +#ifndef SRC_LIBMUGRID_FIELD_MAP_HH_ +#define SRC_LIBMUGRID_FIELD_MAP_HH_ -namespace muSpectre { +namespace muGrid { /** * allows to iterate over raw data as if it were a FieldMap. This is * particularly useful when interacting with external solvers, such * as scipy and Eigen * @param EigenMap needs to be statically sized a Eigen::Map * * @warning This type is not safe for re-use. I.e., after there has * been an assignment to the underlying eigen array, the * `RawFieldMap` might be invalidated! */ template class RawFieldMap { public: /** * determining the constness of the mapped array required in order * to formulate the constructors const-correctly */ constexpr static bool IsConst{std::is_const< std::remove_pointer_t>::value}; //! short-hand for the basic scalar type using T = typename EigenMap::Scalar; //! raw pointer type to store using T_ptr = std::conditional_t; //! input array (~field) type to be mapped using FieldVec_t = std::conditional_t; //! Plain mapped Eigen type using EigenPlain = typename EigenMap::PlainObject; //! Default constructor RawFieldMap() = delete; //! constructor from a *contiguous* array RawFieldMap(Eigen::Map vec, Dim_t nb_rows = EigenMap::RowsAtCompileTime, Dim_t nb_cols = EigenMap::ColsAtCompileTime) : data{vec.data()}, nb_rows{nb_rows}, nb_cols{nb_cols}, nb_components{nb_rows * nb_cols}, nb_pixels(vec.size() / nb_components) { if ((nb_rows == Eigen::Dynamic) or(nb_cols == Eigen::Dynamic)) { throw FieldError( "You have to specify the number of rows and columns if you map a " "dynamically sized Eigen Map type."); } if ((nb_rows < 1) or(nb_cols < 1)) { throw FieldError("Only positive numbers of rows and columns make " "sense"); } if (vec.size() % this->nb_components != 0) { std::stringstream err{}; err << "The vector size of " << vec.size() << " is not an integer multiple of the size of value_type, which " << "is " << this->nb_components << "."; throw std::runtime_error(err.str()); } } //! constructor from a *contiguous* array RawFieldMap(Eigen::Ref vec, Dim_t nb_rows = EigenMap::RowsAtCompileTime, Dim_t nb_cols = EigenMap::ColsAtCompileTime) : data{vec.data()}, nb_rows{nb_rows}, nb_cols{nb_cols}, nb_components{nb_rows * nb_cols}, nb_pixels(vec.size() / nb_components) { if (vec.size() % this->nb_components != 0) { std::stringstream err{}; err << "The vector size of " << vec.size() << " is not an integer multiple of the size of value_type, which " << "is " << this->nb_components << "."; throw std::runtime_error(err.str()); } } //! Copy constructor RawFieldMap(const RawFieldMap & other) = delete; //! Move constructor RawFieldMap(RawFieldMap && other) = default; //! Destructor virtual ~RawFieldMap() = default; //! Copy assignment operator RawFieldMap & operator=(const RawFieldMap & other) = delete; //! Move assignment operator RawFieldMap & operator=(RawFieldMap && other) = delete; //! returns number of EigenMaps stored within the array size_t size() const { return this->nb_pixels; } //! forward declaration of iterator type template class iterator_t; using iterator = iterator_t; using const_iterator = iterator_t; //! returns an iterator to the first element iterator begin() { return iterator{*this, 0}; } const_iterator begin() const { return const_iterator{*this, 0}; } //! returns an iterator past the last element iterator end() { return iterator{*this, this->size()}; } const_iterator end() const { return const_iterator{*this, this->size()}; } //! evaluates the average of the field EigenPlain mean() const { using T_t = EigenPlain; T_t mean(T_t::Zero(this->nb_rows, this->nb_cols)); for (auto && val : *this) { mean += val; } mean /= this->size(); return mean; } protected: inline T_ptr get_data() { return data; } inline const T_ptr get_data() const { return data; } //! raw data pointer (ugly, I know) T_ptr data; const Dim_t nb_rows; const Dim_t nb_cols; const Dim_t nb_components; //! number of EigenMaps stored within the array size_t nb_pixels; private: }; /** * Small iterator class to be used with the RawFieldMap */ template template class RawFieldMap::iterator_t { public: //! short hand for the raw field map's type using Parent = RawFieldMap; //! the map needs to be friend in order to access the protected constructor friend Parent; //! stl compliance using value_type = std::conditional_t< IsConst, Eigen::Map, EigenMap>; using T_ptr = std::conditional_t; //! stl compliance using iterator_category = std::forward_iterator_tag; //! Default constructor iterator_t() = delete; //! Copy constructor iterator_t(const iterator_t & other) = default; //! Move constructor iterator_t(iterator_t && other) = default; //! Destructor virtual ~iterator_t() = default; //! Copy assignment operator iterator_t & operator=(const iterator_t & other) = default; //! Move assignment operator iterator_t & operator=(iterator_t && other) = default; //! pre-increment inline iterator_t & operator++() { ++this->index; return *this; } //! dereference inline value_type operator*() { return value_type(raw_ptr + this->map.nb_components * index, this->map.nb_rows, this->map.nb_cols); } //! inequality inline bool operator!=(const iterator_t & other) const { return this->index != other.index; } //! equality inline bool operator==(const iterator_t & other) const { return this->index == other.index; } protected: //! protected constructor iterator_t(const Parent & map, size_t start) : raw_ptr{map.get_data()}, map{map}, index{start} {} template iterator_t(std::enable_if_t map, size_t start) : raw_ptr{map.data}, map{map}, index{start} { static_assert(dummy_non_const == not IsConst, "SFINAE"); } //! raw data T_ptr raw_ptr; //! ref to underlying map const Parent & map; //! currently pointed-to element size_t index; private: }; -} // namespace muSpectre +} // namespace muGrid -#endif // SRC_COMMON_FIELD_MAP_HH_ +#endif // SRC_LIBMUGRID_FIELD_MAP_HH_ diff --git a/src/common/field_map_base.hh b/src/libmugrid/field_map_base.hh similarity index 98% rename from src/common/field_map_base.hh rename to src/libmugrid/field_map_base.hh index 4e3d107..d318acb 100644 --- a/src/common/field_map_base.hh +++ b/src/libmugrid/field_map_base.hh @@ -1,886 +1,886 @@ /** * @file field_map.hh * * @author Till Junge * * @date 12 Sep 2017 * * @brief Defined a strongly defines proxy that iterates efficiently over a * field * * Copyright © 2017 Till Junge * - * µSpectre is free software; you can redistribute it and/or + * µGrid is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * - * µSpectre is distributed in the hope that it will be useful, but + * µGrid is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with µSpectre; see the file COPYING. If not, write to the + * along with µGrid; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#ifndef SRC_COMMON_FIELD_MAP_BASE_HH_ -#define SRC_COMMON_FIELD_MAP_BASE_HH_ +#ifndef SRC_LIBMUGRID_FIELD_MAP_BASE_HH_ +#define SRC_LIBMUGRID_FIELD_MAP_BASE_HH_ -#include "common/field.hh" +#include "field.hh" #include "field_collection_base.hh" #include #include #include #include -namespace muSpectre { +namespace muGrid { namespace internal { /** * Forward-declaration */ template class TypedSizedFieldBase; //! little helper to automate creation of const maps without duplication template struct const_corrector { //! non-const type using type = typename T::reference; }; //! specialisation for constant case template struct const_corrector { //! const type using type = typename T::const_reference; }; //! convenience alias template using const_corrector_t = typename const_corrector::type; //----------------------------------------------------------------------------// /** * `FieldMap` provides two central mechanisms: * - Map a field (that knows only about the size of the underlying object, * onto the mathematical object (reprensented by the respective Eigen class) * that provides linear algebra functionality. * - Provide an iterator that allows to iterate over all pixels. * A field is represented by `FieldBase` or a derived class. * `FieldMap` has the specialisations `MatrixLikeFieldMap`, * `ScalarFieldMap` and `TensorFieldMap`. */ template class FieldMap { static_assert((NbComponents != 0), "Fields with now components make no sense."); /* * Eigen::Dynamic is equal to -1, and is a legal value, hence * the following peculiar check */ static_assert( (NbComponents > -2), "Fields with a negative number of components make no sense."); public: //! Fundamental type stored using Scalar = T; //! number of scalars per entry constexpr static auto nb_components{NbComponents}; //! non-constant version of field using TypedField_nc = std::conditional_t< (NbComponents >= 1), TypedSizedFieldBase, TypedField>; //! field type as seen from iterator using TypedField_t = std::conditional_t; using Field = typename TypedField_nc::Base; //!< iterated field type //! const-correct field type using Field_c = std::conditional_t; using size_type = std::size_t; //!< stl conformance using pointer = std::conditional_t; //!< stl conformance //! Default constructor FieldMap() = delete; //! constructor explicit FieldMap(Field_c & field); //! constructor with run-time cost (for python and debugging) template explicit FieldMap(TypedSizedFieldBase & field); //! Copy constructor FieldMap(const FieldMap & other) = default; //! Move constructor FieldMap(FieldMap && other) = default; //! Destructor virtual ~FieldMap() = default; //! Copy assignment operator FieldMap & operator=(const FieldMap & other) = delete; //! Move assignment operator FieldMap & operator=(FieldMap && other) = delete; //! give human-readable field map type virtual std::string info_string() const = 0; //! return field name inline const std::string & get_name() const; //! return my collection (for iterating) inline const FieldCollection & get_collection() const; //! member access needs to be implemented by inheriting classes // inline value_type operator[](size_t index); // inline value_type operator[](Ccoord ccord); //! check compatibility (must be called by all inheriting classes at the //! end of their constructors inline void check_compatibility(); //! convenience call to collection's size method inline size_t size() const; //! compile-time compatibility check template struct is_compatible; /** - * iterates over all pixels in the `muSpectre::FieldCollection` + * iterates over all pixels in the `muGrid::FieldCollection` * and dereferences to an Eigen map to the currently used field. */ template class iterator; /** * Simple iterable proxy wrapper object around a FieldMap. When * iterated over, rather than dereferencing to the reference * type of iterator, it dereferences to a tuple of the pixel, * and the reference type of iterator */ template class enumerator; TypedField_t & get_field() { return this->field; } protected: //! raw pointer to entry (for Eigen Map) inline pointer get_ptr_to_entry(size_t index); //! raw pointer to entry (for Eigen Map) inline const T * get_ptr_to_entry(size_t index) const; const FieldCollection & collection; //!< collection holding Field TypedField_t & field; //!< mapped Field }; /** - * iterates over all pixels in the `muSpectre::FieldCollection` + * iterates over all pixels in the `muGrid::FieldCollection` * and dereferences to an Eigen map to the currently used field. */ template template class FieldMap::iterator { static_assert(!((ConstIter == false) && (ConstField == true)), "You can't have a non-const iterator over a const " "field"); public: //! for use by enumerator using FullyTypedFieldMap_t = FullyTypedFieldMap; //! stl conformance using value_type = const_corrector_t; //! stl conformance using const_value_type = const_corrector_t; //! stl conformance using pointer = typename FullyTypedFieldMap::pointer; //! stl conformance using difference_type = std::ptrdiff_t; //! stl conformance using iterator_category = std::random_access_iterator_tag; //! cell coordinates type using Ccoord = typename FieldCollection::Ccoord; //! stl conformance using reference = typename FullyTypedFieldMap::reference; //! fully typed reference as seen by the iterator using TypedMap_t = std::conditional_t; //! Default constructor iterator() = delete; //! constructor inline iterator(TypedMap_t & fieldmap, bool begin = true); //! constructor for random access inline iterator(TypedMap_t & fieldmap, size_t index); //! Move constructor iterator(iterator && other) = default; //! Destructor virtual ~iterator() = default; //! Copy assignment operator iterator & operator=(const iterator & other) = default; //! Move assignment operator iterator & operator=(iterator && other) = default; //! pre-increment inline iterator & operator++(); //! post-increment inline iterator operator++(int); //! dereference inline value_type operator*(); //! dereference inline const_value_type operator*() const; //! member of pointer inline pointer operator->(); //! pre-decrement inline iterator & operator--(); //! post-decrement inline iterator operator--(int); //! access subscripting inline value_type operator[](difference_type diff); //! access subscripting inline const_value_type operator[](const difference_type diff) const; //! equality inline bool operator==(const iterator & other) const; //! inequality inline bool operator!=(const iterator & other) const; //! div. comparisons inline bool operator<(const iterator & other) const; //! div. comparisons inline bool operator<=(const iterator & other) const; //! div. comparisons inline bool operator>(const iterator & other) const; //! div. comparisons inline bool operator>=(const iterator & other) const; //! additions, subtractions and corresponding assignments inline iterator operator+(difference_type diff) const; //! additions, subtractions and corresponding assignments inline iterator operator-(difference_type diff) const; //! additions, subtractions and corresponding assignments inline iterator & operator+=(difference_type diff); //! additions, subtractions and corresponding assignments inline iterator & operator-=(difference_type diff); //! get pixel coordinates inline Ccoord get_ccoord() const; //! ostream operator (mainly for debugging) friend std::ostream & operator<<(std::ostream & os, const iterator & it) { if (ConstIter) { os << "const "; } os << "iterator on field '" << it.fieldmap.get_name() << "', entry " << it.index; return os; } protected: //! Copy constructor iterator(const iterator & other) = default; const FieldCollection & collection; //!< collection of the field TypedMap_t & fieldmap; //!< ref to the field itself size_t index; //!< index of currently pointed-to pixel }; /* ---------------------------------------------------------------------- */ template template class FieldMap::enumerator { public: //! fully typed reference as seen by the iterator using TypedMap_t = typename Iterator::TypedMap_t; //! Default constructor enumerator() = delete; //! constructor with field mapped enumerator(TypedMap_t & field_map) : field_map{field_map} {} /** * similar to iterators of the field map, but dereferences to a * tuple containing the cell coordinates and teh corresponding * entry */ class iterator; iterator begin() { return iterator(this->field_map); } iterator end() { return iterator(this->field_map, false); } protected: TypedMap_t & field_map; }; /* ---------------------------------------------------------------------- */ template template class FieldMap::enumerator::iterator { public: //! cell coordinates type using Ccoord = typename FieldCollection::Ccoord; //! stl conformance using value_type = std::tuple; //! stl conformance using const_value_type = std::tuple; //! stl conformance using difference_type = std::ptrdiff_t; //! stl conformance using iterator_category = std::random_access_iterator_tag; //! stl conformance using reference = std::tuple; //! Default constructor iterator() = delete; //! constructor for begin/end iterator(TypedMap_t & fieldmap, bool begin = true) : it{fieldmap, begin} {} //! constructor for random access iterator(TypedMap_t & fieldmap, size_t index) : it{fieldmap, index} {} //! constructor from iterator iterator(const SimpleIterator & it) : it{it} {} //! Copy constructor iterator(const iterator & other) = default; //! Move constructor iterator(iterator && other) = default; //! Destructor virtual ~iterator() = default; //! Copy assignment operator iterator & operator=(const iterator & other) = default; //! Move assignment operator iterator & operator=(iterator && other) = default; //! pre-increment iterator & operator++() { ++(this->it); return *this; } //! post-increment iterator operator++(int) { iterator current = *this; ++(this->it); return current; } //! dereference value_type operator*() { return value_type{it.get_ccoord(), *this->it}; } //! dereference const_value_type operator*() const { return const_value_type{it.get_ccoord(), *this->it}; } //! pre-decrement iterator & operator--() { --(this->it); return *this; } //! post-decrement iterator operator--(int) { iterator current = *this; --(this->it); return current; } //! access subscripting value_type operator[](difference_type diff) { SimpleIterator accessed{this->it + diff}; return *accessed; } //! access subscripting const_value_type operator[](const difference_type diff) const { SimpleIterator accessed{this->it + diff}; return *accessed; } //! equality bool operator==(const iterator & other) const { return this->it == other.it; } //! inequality bool operator!=(const iterator & other) const { return this->it != other.it; } //! div. comparisons bool operator<(const iterator & other) const { return this->it < other.it; } //! div. comparisons bool operator<=(const iterator & other) const { return this->it <= other.it; } //! div. comparisons bool operator>(const iterator & other) const { return this->it > other.it; } //! div. comparisons bool operator>=(const iterator & other) const { return this->it >= other.it; } //! additions, subtractions and corresponding assignments iterator operator+(difference_type diff) const { return iterator{this->it + diff}; } //! additions, subtractions and corresponding assignments iterator operator-(difference_type diff) const { return iterator{this->it - diff}; } //! additions, subtractions and corresponding assignments iterator & operator+=(difference_type diff) { this->it += diff; } //! additions, subtractions and corresponding assignments iterator & operator-=(difference_type diff) { this->it -= diff; } protected: SimpleIterator it; private: }; } // namespace internal namespace internal { /* ---------------------------------------------------------------------- */ template FieldMap::FieldMap( Field_c & field) : collection(field.get_collection()), field(static_cast(field)) { static_assert((NbComponents > 0) or(NbComponents == Eigen::Dynamic), "Only fields with more than 0 components allowed"); } /* ---------------------------------------------------------------------- */ template template FieldMap::FieldMap( TypedSizedFieldBase & field) : collection(field.get_collection()), field(static_cast(field)) { static_assert( std::is_same::value, "The field does not have the expected FieldCollection type"); static_assert(std::is_same::value, "The field does not have the expected Scalar type"); static_assert( (NbC == NbComponents), "The field does not have the expected number of components"); } /* ---------------------------------------------------------------------- */ template void FieldMap::check_compatibility() { if (typeid(T).hash_code() != this->field.get_stored_typeid().hash_code()) { std::string err{"Cannot create a Map of type '" + this->info_string() + "' for field '" + this->field.get_name() + "' of type '" + this->field.get_stored_typeid().name() + "'"}; throw FieldInterpretationError(err); } // check size compatibility if ((NbComponents != Dim_t(this->field.get_nb_components())) and (NbComponents != Eigen::Dynamic)) { throw FieldInterpretationError( "Cannot create a Map of type '" + this->info_string() + "' for field '" + this->field.get_name() + "' with " + std::to_string(this->field.get_nb_components()) + " components"); } } /* ---------------------------------------------------------------------- */ template size_t FieldMap::size() const { return this->collection.size(); } /* ---------------------------------------------------------------------- */ template template struct FieldMap::is_compatible { //! creates a more readable compile error constexpr static bool explain() { static_assert( std::is_same::value, "The field does not have the expected FieldCollection type"); static_assert(std::is_same::value, "The // field does not have the expected Scalar type"); static_assert( (TypedField_t::nb_components == NbComponents), "The field does not have the expected number of components"); // The static asserts wouldn't pass in the incompatible case, so this is // it return true; } //! evaluated compatibility constexpr static bool value{ std::is_base_of::value}; }; /* ---------------------------------------------------------------------- */ template const std::string & FieldMap::get_name() const { return this->field.get_name(); } /* ---------------------------------------------------------------------- */ template const FieldCollection & FieldMap::get_collection() const { return this->collection; } /* ---------------------------------------------------------------------- */ /* ---------------------------------------------------------------------- */ // Iterator implementations //! constructor template template FieldMap::iterator< FullyTypedFieldMap, ConstIter>::iterator(TypedMap_t & fieldmap, bool begin) : collection(fieldmap.get_collection()), fieldmap(fieldmap), index(begin ? 0 : fieldmap.field.size()) {} /* ---------------------------------------------------------------------- */ //! constructor for random access template template FieldMap::iterator< FullyTypedFieldMap, ConstIter>::iterator(TypedMap_t & fieldmap, size_t index) : collection(fieldmap.collection), fieldmap(fieldmap), index(index) {} /* ---------------------------------------------------------------------- */ //! pre-increment template template typename FieldMap:: template iterator & FieldMap::iterator:: operator++() { this->index++; return *this; } /* ---------------------------------------------------------------------- */ //! post-increment template template typename FieldMap:: template iterator FieldMap::iterator:: operator++(int) { iterator current = *this; this->index++; return current; } /* ---------------------------------------------------------------------- */ //! dereference template template typename FieldMap:: template iterator::value_type FieldMap::iterator:: operator*() { return this->fieldmap.operator[](this->index); } /* ---------------------------------------------------------------------- */ //! dereference template template typename FieldMap:: template iterator::const_value_type FieldMap::iterator:: operator*() const { return this->fieldmap.operator[](this->index); } /* ---------------------------------------------------------------------- */ //! member of pointer template template typename FullyTypedFieldMap::pointer FieldMap::iterator:: operator->() { return this->fieldmap.ptr_to_val_t(this->index); } /* ---------------------------------------------------------------------- */ //! pre-decrement template template typename FieldMap:: template iterator & FieldMap::iterator:: operator--() { this->index--; return *this; } /* ---------------------------------------------------------------------- */ //! post-decrement template template typename FieldMap:: template iterator FieldMap::iterator:: operator--(int) { iterator current = *this; this->index--; return current; } /* ---------------------------------------------------------------------- */ //! Access subscripting template template typename FieldMap:: template iterator::value_type FieldMap::iterator:: operator[](difference_type diff) { return this->fieldmap[this->index + diff]; } /* ---------------------------------------------------------------------- */ //! Access subscripting template template typename FieldMap:: template iterator::const_value_type FieldMap::iterator:: operator[](const difference_type diff) const { return this->fieldmap[this->index + diff]; } /* ---------------------------------------------------------------------- */ //! equality template template bool FieldMap::iterator:: operator==(const iterator & other) const { return (this->index == other.index); } /* ---------------------------------------------------------------------- */ //! inquality template template bool FieldMap::iterator:: operator!=(const iterator & other) const { return !(*this == other); } /* ---------------------------------------------------------------------- */ //! div. comparisons template template bool FieldMap::iterator:: operator<(const iterator & other) const { return (this->index < other.index); } template template bool FieldMap::iterator:: operator<=(const iterator & other) const { return (this->index <= other.index); } template template bool FieldMap::iterator:: operator>(const iterator & other) const { return (this->index > other.index); } template template bool FieldMap::iterator:: operator>=(const iterator & other) const { return (this->index >= other.index); } /* ---------------------------------------------------------------------- */ //! additions, subtractions and corresponding assignments template template typename FieldMap:: template iterator FieldMap::iterator:: operator+(difference_type diff) const { return iterator(this->fieldmap, this->index + diff); } template template typename FieldMap:: template iterator FieldMap::iterator:: operator-(difference_type diff) const { return iterator(this->fieldmap, this->index - diff); } template template typename FieldMap:: template iterator & FieldMap::iterator:: operator+=(difference_type diff) { this->index += diff; return *this; } template template typename FieldMap:: template iterator & FieldMap::iterator:: operator-=(difference_type diff) { this->index -= diff; return *this; } /* ---------------------------------------------------------------------- */ //! get pixel coordinates template template typename FieldCollection::Ccoord FieldMap::iterator< FullyTypedFieldMap, ConstIter>::get_ccoord() const { return this->collection.get_ccoord(this->index); } ////----------------------------------------------------------------------------// // template std::ostream & operator << (std::ostream &os, // const typename FieldMap:: // template iterator & it) { // os << "iterator on field '" // << it.field.get_name() // << "', entry " << it.index; // return os; //} /* ---------------------------------------------------------------------- */ template typename FieldMap::pointer FieldMap::get_ptr_to_entry( size_t index) { return this->field.get_ptr_to_entry(std::move(index)); } /* ---------------------------------------------------------------------- */ template const T * FieldMap::get_ptr_to_entry( size_t index) const { return this->field.get_ptr_to_entry(std::move(index)); } } // namespace internal -} // namespace muSpectre +} // namespace muGrid -#endif // SRC_COMMON_FIELD_MAP_BASE_HH_ +#endif // SRC_LIBMUGRID_FIELD_MAP_BASE_HH_ diff --git a/src/common/field_map_dynamic.hh b/src/libmugrid/field_map_dynamic.hh similarity index 94% rename from src/common/field_map_dynamic.hh rename to src/libmugrid/field_map_dynamic.hh index 0e8d024..b496ef3 100644 --- a/src/common/field_map_dynamic.hh +++ b/src/libmugrid/field_map_dynamic.hh @@ -1,220 +1,220 @@ /** * @file field_map_dynamic.hh * * @author Till Junge * * @date 24 Jul 2018 * * @brief Field map for dynamically sized maps. for use in non-critical * applications (i.e., i/o, postprocessing, etc, but *not* in a hot * loop * * Copyright © 2018 Till Junge * - * µSpectre is free software; you can redistribute it and/or + * µGrid is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * - * µSpectre is distributed in the hope that it will be useful, but + * µGrid is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with µSpectre; see the file COPYING. If not, write to the + * along with µGrid; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#ifndef SRC_COMMON_FIELD_MAP_DYNAMIC_HH_ -#define SRC_COMMON_FIELD_MAP_DYNAMIC_HH_ +#ifndef SRC_LIBMUGRID_FIELD_MAP_DYNAMIC_HH_ +#define SRC_LIBMUGRID_FIELD_MAP_DYNAMIC_HH_ -#include "common/field_map_base.hh" +#include "field_map_base.hh" -namespace muSpectre { +namespace muGrid { /** - * Maps onto any `muSpectre::TypedField` and lets you iterate over + * Maps onto any `muGrid::TypedField` and lets you iterate over * it in the form of `Eigen::Map`. This is significantly slower than the statically sized field * maps and should only be used in non-critical contexts. */ template class TypedFieldMap : public internal::FieldMap { public: //! base class using Parent = internal::FieldMap; //! sister class with all params equal, but ConstField guaranteed true using ConstMap = TypedFieldMap; //! cell coordinates type using Ccoord = Ccoord_t; //! plain Eigen type using Arr_t = Eigen::Array; using value_type = Eigen::Map; //!< stl conformance using const_reference = Eigen::Map; //!< stl conformance //! stl conformance using reference = std::conditional_t; // since it's a resource handle using size_type = typename Parent::size_type; //!< stl conformance using pointer = std::unique_ptr; //!< stl conformance //! polymorphic base field type (for debug and python) using Field = typename Parent::Field; //! polymorphic base field type (for debug and python) using Field_c = typename Parent::Field_c; //! stl conformance using const_iterator = typename Parent::template iterator; //! stl conformance using iterator = std::conditional_t>; //! stl conformance using reverse_iterator = std::reverse_iterator; //! stl conformance using const_reverse_iterator = std::reverse_iterator; //! enumerator over a constant scalar field using const_enumerator = typename Parent::template enumerator; //! enumerator over a scalar field using enumerator = std::conditional_t>; //! give access to the protected fields friend iterator; //! Default constructor TypedFieldMap() = delete; //! Constructor explicit TypedFieldMap(Field_c & field); //! Copy constructor TypedFieldMap(const TypedFieldMap & other) = delete; //! Move constructor TypedFieldMap(TypedFieldMap && other) = default; //! Destructor virtual ~TypedFieldMap() = default; //! Copy assignment operator TypedFieldMap & operator=(const TypedFieldMap & other) = delete; //! Assign a matrixlike value to every entry template inline TypedFieldMap & operator=(const Eigen::EigenBase & val); //! Move assignment operator TypedFieldMap & operator=(TypedFieldMap && other) = default; //! give human-readable field map type inline std::string info_string() const final; //! member access inline reference operator[](size_type index); //! member access inline reference operator[](const Ccoord & ccoord); //! member access inline const_reference operator[](size_type index) const; //! member access inline const_reference operator[](const Ccoord & ccoord) const; //! return an iterator to first entry of field inline iterator begin() { return iterator(*this); } //! return an iterator to first entry of field inline const_iterator cbegin() const { return const_iterator(*this); } //! return an iterator to first entry of field inline const_iterator begin() const { return this->cbegin(); } //! return an iterator past the last entry of field inline iterator end() { return iterator(*this, false); } //! return an iterator past the last entry of field inline const_iterator cend() const { return const_iterator(*this, false); } //! return an iterator past the last entry of field inline const_iterator end() const { return this->cend(); } /** * return an iterable proxy to this field that can be iterated * in Ccoord-value tuples */ enumerator enumerate() { return enumerator(*this); } /** * return an iterable proxy to this field that can be iterated * in Ccoord-value tuples */ const_enumerator enumerate() const { return const_enumerator(*this); } //! evaluate the average of the field inline Arr_t mean() const; protected: //! for sad, legacy iterator use inline pointer ptr_to_val_t(size_type index); private: }; //----------------------------------------------------------------------------// template TypedFieldMap::TypedFieldMap(Field_c & field) : Parent(field) { this->check_compatibility(); } //----------------------------------------------------------------------------// template std::string TypedFieldMap::info_string() const { std::stringstream info; info << "Dynamic(" << typeid(T).name() << ", " << this->field.get_nb_components() << ")"; return info.str(); } //----------------------------------------------------------------------------// template auto TypedFieldMap:: operator[](size_type index) -> reference { return reference{this->get_ptr_to_entry(index), Dim_t(this->field.get_nb_components())}; } //----------------------------------------------------------------------------// template auto TypedFieldMap:: operator[](const Ccoord & ccoord) -> reference { size_t index{this->collection.get_index(ccoord)}; return (*this)[index]; } //----------------------------------------------------------------------------// template auto TypedFieldMap:: operator[](size_type index) const -> const_reference { return const_reference{this->get_ptr_to_entry(index), Dim_t(this->field.get_nb_components())}; } //----------------------------------------------------------------------------// template auto TypedFieldMap:: operator[](const Ccoord & ccoord) const -> const_reference { size_t index{this->collection.get_index(ccoord)}; return (*this)[index]; } -} // namespace muSpectre +} // namespace muGrid -#endif // SRC_COMMON_FIELD_MAP_DYNAMIC_HH_ +#endif // SRC_LIBMUGRID_FIELD_MAP_DYNAMIC_HH_ diff --git a/src/common/field_map_matrixlike.hh b/src/libmugrid/field_map_matrixlike.hh similarity index 94% rename from src/common/field_map_matrixlike.hh rename to src/libmugrid/field_map_matrixlike.hh index 88f26d8..8d59e58 100644 --- a/src/common/field_map_matrixlike.hh +++ b/src/libmugrid/field_map_matrixlike.hh @@ -1,383 +1,383 @@ /** * @file field_map_matrixlike.hh * * @author Till Junge * * @date 26 Sep 2017 * * @brief Eigen-Matrix and -Array maps over strongly typed fields * * Copyright © 2017 Till Junge * - * µSpectre is free software; you can redistribute it and/or + * µGrid is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * - * µSpectre is distributed in the hope that it will be useful, but + * µGrid is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with µSpectre; see the file COPYING. If not, write to the + * along with µGrid; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#ifndef SRC_COMMON_FIELD_MAP_MATRIXLIKE_HH_ -#define SRC_COMMON_FIELD_MAP_MATRIXLIKE_HH_ +#ifndef SRC_LIBMUGRID_FIELD_MAP_MATRIXLIKE_HH_ +#define SRC_LIBMUGRID_FIELD_MAP_MATRIXLIKE_HH_ -#include "common/T4_map_proxy.hh" -#include "common/field_map_base.hh" +#include "T4_map_proxy.hh" +#include "field_map_base.hh" #include #include -namespace muSpectre { +namespace muGrid { namespace internal { /* ---------------------------------------------------------------------- */ /** * lists all matrix-like types consideres by - * `muSpectre::internal::MatrixLikeFieldMap` + * `muGrid::internal::MatrixLikeFieldMap` */ enum class Map_t { Matrix, //!< for wrapping `Eigen::Matrix` Array, //!< for wrapping `Eigen::Array` T4Matrix //!< for wrapping `Eigen::T4Matrix` }; /** * traits structure to define the name shown when a - * `muSpectre::MatrixLikeFieldMap` output into an ostream + * `muGrid::MatrixLikeFieldMap` output into an ostream */ template struct NameWrapper {}; - /// specialisation for `muSpectre::ArrayFieldMap` + /// specialisation for `muGrid::ArrayFieldMap` template <> struct NameWrapper { //! string to use for printing static std::string field_info_root() { return "Array"; } }; - /// specialisation for `muSpectre::MatrixFieldMap` + /// specialisation for `muGrid::MatrixFieldMap` template <> struct NameWrapper { //! string to use for printing static std::string field_info_root() { return "Matrix"; } }; - /// specialisation for `muSpectre::T4MatrixFieldMap` + /// specialisation for `muGrid::T4MatrixFieldMap` template <> struct NameWrapper { //! string to use for printing static std::string field_info_root() { return "T4Matrix"; } }; /* ---------------------------------------------------------------------- */ /*! * A `MatrixLikeFieldMap` is the base class for maps of matrices, arrays and * fourth-order tensors mapped onto matrices. * * It should never be necessary to call directly any of the * constructors if this class, but rather use the template aliases: - * - `muSpectre::ArrayFieldMap`: iterate in the form of `Eigen::Array<...>`. - * - `muSpectre::MatrixFieldMap`: iterate in the form of + * - `muGrid::ArrayFieldMap`: iterate in the form of `Eigen::Array<...>`. + * - `muGrid::MatrixFieldMap`: iterate in the form of * `Eigen::Matrix<...>`. - * - `muSpectre::T4MatrixFieldMap`: iterate in the form of - * `muSpectre::T4MatMap`. + * - `muGrid::T4MatrixFieldMap`: iterate in the form of + * `muGrid::T4MatMap`. */ template class MatrixLikeFieldMap : public FieldMap { public: //! base class using Parent = FieldMap; //! sister class with all params equal, but ConstField guaranteed true using ConstMap = MatrixLikeFieldMap; using T_t = EigenPlain; //!< plain Eigen type to map //! cell coordinates type using Ccoord = Ccoord_t; using value_type = EigenArray; //!< stl conformance using const_reference = EigenConstArray; //!< stl conformance //! stl conformance using reference = std::conditional_t; // since it's a resource handle using size_type = typename Parent::size_type; //!< stl conformance using pointer = std::unique_ptr; //!< stl conformance using Field = typename Parent::Field; //!< stl conformance using Field_c = typename Parent::Field_c; //!< stl conformance //! stl conformance using const_iterator = typename Parent::template iterator; //! stl conformance using iterator = std::conditional_t< ConstField, const_iterator, typename Parent::template iterator>; using reverse_iterator = std::reverse_iterator; //!< stl conformance //! stl conformance using const_reverse_iterator = std::reverse_iterator; //! enumerator over a constant scalar field using const_enumerator = typename Parent::template enumerator; //! enumerator over a scalar field using enumerator = std::conditional_t>; //! give access to the protected fields friend iterator; //! Default constructor MatrixLikeFieldMap() = delete; /** * Constructor using a (non-typed) field. Compatibility is enforced at * runtime. This should not be a performance concern, as this constructor * will not be called in anny inner loops (if used as intended). */ explicit MatrixLikeFieldMap(Field_c & field); /** * Constructor using a typed field. Compatibility is enforced * statically. It is not always possible to call this constructor, as the * type of the field might not be known at compile time. */ template MatrixLikeFieldMap(TypedSizedFieldBase & field) // NOLINT : Parent(field) {} //! Copy constructor MatrixLikeFieldMap(const MatrixLikeFieldMap & other) = delete; //! Move constructorxo MatrixLikeFieldMap(MatrixLikeFieldMap && other) = default; //! Destructor virtual ~MatrixLikeFieldMap() = default; //! Copy assignment operator MatrixLikeFieldMap & operator=(const MatrixLikeFieldMap & other) = delete; //! Move assignment operator MatrixLikeFieldMap & operator=(MatrixLikeFieldMap && other) = delete; //! Assign a matrixlike value to every entry template inline MatrixLikeFieldMap & operator=(const Eigen::EigenBase & val); //! give human-readable field map type inline std::string info_string() const final; //! member access inline reference operator[](size_type index); //! member access inline reference operator[](const Ccoord & ccoord); //! member access inline const_reference operator[](size_type index) const; //! member access inline const_reference operator[](const Ccoord & ccoord) const; //! return an iterator to head of field for ranges inline iterator begin() { return std::move(iterator(*this)); } //! return an iterator to head of field for ranges inline const_iterator cbegin() const { return const_iterator(*this); } //! return an iterator to head of field for ranges inline const_iterator begin() const { return this->cbegin(); } //! return an iterator to tail of field for ranges inline iterator end() { return iterator(*this, false); } //! return an iterator to tail of field for ranges inline const_iterator cend() const { return const_iterator(*this, false); } //! return an iterator to tail of field for ranges inline const_iterator end() const { return this->cend(); } /** * return an iterable proxy to this field that can be iterated * in Ccoord-value tuples */ enumerator enumerate() { return enumerator(*this); } /** * return an iterable proxy to this field that can be iterated * in Ccoord-value tuples */ const_enumerator enumerate() const { return const_enumerator(*this); } //! evaluate the average of the field inline T_t mean() const; protected: //! for sad, legacy iterator use inline pointer ptr_to_val_t(size_type index); static const std::string field_info_root() { return NameWrapper::field_info_root(); } //!< for printing and debug private: }; /* ---------------------------------------------------------------------- */ template MatrixLikeFieldMap::MatrixLikeFieldMap(Field_c & field) : Parent(field) { this->check_compatibility(); } /* ---------------------------------------------------------------------- */ //! human-readable field map type template std::string MatrixLikeFieldMap::info_string() const { std::stringstream info; info << this->field_info_root() << "(" << typeid(typename EigenArray::value_type).name() << ", " << EigenArray::RowsAtCompileTime << "x" << EigenArray::ColsAtCompileTime << ")"; return info.str(); } /* ---------------------------------------------------------------------- */ //! member access template typename MatrixLikeFieldMap::reference MatrixLikeFieldMap:: operator[](size_type index) { return reference(this->get_ptr_to_entry(index)); } template typename MatrixLikeFieldMap::reference MatrixLikeFieldMap:: operator[](const Ccoord & ccoord) { size_t && index{this->collection.get_index(ccoord)}; return reference(this->get_ptr_to_entry(index)); } /* ---------------------------------------------------------------------- */ //! member access template typename MatrixLikeFieldMap::const_reference MatrixLikeFieldMap:: operator[](size_type index) const { return const_reference(this->get_ptr_to_entry(index)); } template typename MatrixLikeFieldMap::const_reference MatrixLikeFieldMap:: operator[](const Ccoord & ccoord) const { size_t && index{this->collection.get_index(ccoord)}; return const_reference(this->get_ptr_to_entry(index)); } //----------------------------------------------------------------------------// template template MatrixLikeFieldMap & MatrixLikeFieldMap:: operator=(const Eigen::EigenBase & val) { for (auto && entry : *this) { entry = val; } return *this; } /* ---------------------------------------------------------------------- */ template typename MatrixLikeFieldMap::T_t MatrixLikeFieldMap::mean() const { T_t mean{T_t::Zero()}; for (auto && val : *this) { mean += val; } mean *= 1. / Real(this->size()); return mean; } /* ---------------------------------------------------------------------- */ template typename MatrixLikeFieldMap::pointer MatrixLikeFieldMap::ptr_to_val_t(size_type index) { return std::make_unique( this->get_ptr_to_entry(std::move(index))); } } // namespace internal /* ---------------------------------------------------------------------- */ //! short-hand for an Eigen matrix map as iterate template using MatrixFieldMap = internal::MatrixLikeFieldMap< FieldCollection, Eigen::Map>, Eigen::Map>, Eigen::Matrix, internal::Map_t::Matrix, ConstField>; /* ---------------------------------------------------------------------- */ //! short-hand for an Eigen matrix map as iterate template using T4MatrixFieldMap = internal::MatrixLikeFieldMap, T4MatMap, T4Mat, internal::Map_t::T4Matrix, MapConst>; /* ---------------------------------------------------------------------- */ //! short-hand for an Eigen array map as iterate template using ArrayFieldMap = internal::MatrixLikeFieldMap< FieldCollection, Eigen::Map>, Eigen::Map>, Eigen::Array, internal::Map_t::Array, ConstField>; -} // namespace muSpectre +} // namespace muGrid -#endif // SRC_COMMON_FIELD_MAP_MATRIXLIKE_HH_ +#endif // SRC_LIBMUGRID_FIELD_MAP_MATRIXLIKE_HH_ diff --git a/src/common/field_map_scalar.hh b/src/libmugrid/field_map_scalar.hh similarity index 94% rename from src/common/field_map_scalar.hh rename to src/libmugrid/field_map_scalar.hh index 374883f..668e774 100644 --- a/src/common/field_map_scalar.hh +++ b/src/libmugrid/field_map_scalar.hh @@ -1,242 +1,242 @@ /** * @file field_map_scalar.hh * * @author Till Junge * * @date 26 Sep 2017 * * @brief maps over scalar fields * * Copyright © 2017 Till Junge * - * µSpectre is free software; you can redistribute it and/or + * µGrid is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * - * µSpectre is distributed in the hope that it will be useful, but + * µGrid is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with µSpectre; see the file COPYING. If not, write to the + * along with µGrid; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#ifndef SRC_COMMON_FIELD_MAP_SCALAR_HH_ -#define SRC_COMMON_FIELD_MAP_SCALAR_HH_ +#ifndef SRC_LIBMUGRID_FIELD_MAP_SCALAR_HH_ +#define SRC_LIBMUGRID_FIELD_MAP_SCALAR_HH_ -#include "common/field_map_base.hh" +#include "field_map_base.hh" -namespace muSpectre { +namespace muGrid { /** * Implements maps on scalar fields (i.e. material properties, - * temperatures, etc). Maps onto a `muSpectre::internal::TypedSizedFieldBase` + * temperatures, etc). Maps onto a `muGrid::internal::TypedSizedFieldBase` * and lets you iterate over it in the form of the bare type of the field. */ template class ScalarFieldMap : public internal::FieldMap { public: //! base class using Parent = internal::FieldMap; //! sister class with all params equal, but ConstField guaranteed true using ConstMap = ScalarFieldMap; //! cell coordinates type using Ccoord = Ccoord_t; using value_type = T; //!< stl conformance using const_reference = const value_type &; //!< stl conformance //! stl conformance using reference = std::conditional_t; using size_type = typename Parent::size_type; //!< stl conformance using pointer = T *; //!< stl conformance using Field = typename Parent::Field; //!< stl conformance using Field_c = typename Parent::Field_c; //!< stl conformance //! stl conformance using const_iterator = typename Parent::template iterator; //! iterator over a scalar field using iterator = std::conditional_t>; using reverse_iterator = std::reverse_iterator; //!< stl conformance //! stl conformance using const_reverse_iterator = std::reverse_iterator; //! enumerator over a constant scalar field using const_enumerator = typename Parent::template enumerator; //! enumerator over a scalar field using enumerator = std::conditional_t>; //! give access to the protected fields friend iterator; //! Default constructor ScalarFieldMap() = delete; //! constructor explicit ScalarFieldMap(Field_c & field); //! Copy constructor ScalarFieldMap(const ScalarFieldMap & other) = default; //! Move constructor ScalarFieldMap(ScalarFieldMap && other) = default; //! Destructor virtual ~ScalarFieldMap() = default; //! Copy assignment operator ScalarFieldMap & operator=(const ScalarFieldMap & other) = delete; //! Move assignment operator ScalarFieldMap & operator=(ScalarFieldMap && other) = delete; //! Assign a value to every entry ScalarFieldMap & operator=(T val); //! give human-readable field map type inline std::string info_string() const final; //! member access inline reference operator[](size_type index); inline reference operator[](const Ccoord & ccoord); inline const_reference operator[](size_type index) const; inline const_reference operator[](const Ccoord & ccoord) const; //! return an iterator to the first pixel of the field iterator begin() { return iterator(*this); } //! return an iterator to the first pixel of the field const_iterator cbegin() const { return const_iterator(*this); } //! return an iterator to the first pixel of the field const_iterator begin() const { return this->cbegin(); } //! return an iterator to tail of field for ranges iterator end() { return iterator(*this, false); } //! return an iterator to tail of field for ranges const_iterator cend() const { return const_iterator(*this, false); } //! return an iterator to tail of field for ranges const_iterator end() const { return this->cend(); } /** * return an iterable proxy to this field that can be iterated * in Ccoord-value tuples */ enumerator enumerate() { return enumerator(*this); } /** * return an iterable proxy to this field that can be iterated * in Ccoord-value tuples */ const_enumerator enumerate() const { return const_enumerator(*this); } //! evaluate the average of the field inline T mean() const; protected: //! for sad, legacy iterator use inline pointer ptr_to_val_t(size_type index); //! type identifier for printing and debugging static const std::string field_info_root; private: }; /* ---------------------------------------------------------------------- */ template ScalarFieldMap::ScalarFieldMap( Field_c & field) : Parent(field) { this->check_compatibility(); } /* ---------------------------------------------------------------------- */ //! human-readable field map type template std::string ScalarFieldMap::info_string() const { std::stringstream info; info << "Scalar(" << typeid(T).name() << ")"; return info.str(); } /* ---------------------------------------------------------------------- */ template const std::string ScalarFieldMap::field_info_root{"Scalar"}; /* ---------------------------------------------------------------------- */ //! member access template typename ScalarFieldMap::reference ScalarFieldMap:: operator[](size_type index) { return this->get_ptr_to_entry(std::move(index))[0]; } /* ---------------------------------------------------------------------- */ //! member access template typename ScalarFieldMap::reference ScalarFieldMap:: operator[](const Ccoord & ccoord) { auto && index = this->collection.get_index(std::move(ccoord)); return this->get_ptr_to_entry(std::move(index))[0]; } /* ---------------------------------------------------------------------- */ //! member access template typename ScalarFieldMap::const_reference ScalarFieldMap:: operator[](size_type index) const { return this->get_ptr_to_entry(std::move(index))[0]; } /* ---------------------------------------------------------------------- */ //! member access template typename ScalarFieldMap::const_reference ScalarFieldMap:: operator[](const Ccoord & ccoord) const { auto && index = this->collection.get_index(std::move(ccoord)); return this->get_ptr_to_entry(std::move(index))[0]; } /* ---------------------------------------------------------------------- */ //! Assign a value to every entry template ScalarFieldMap & ScalarFieldMap::operator=(T val) { for (auto & scalar : *this) { scalar = val; } return *this; } /* ---------------------------------------------------------------------- */ template T ScalarFieldMap::mean() const { T mean{0}; for (auto && val : *this) { mean += val; } mean /= Real(this->size()); return mean; } -} // namespace muSpectre +} // namespace muGrid -#endif // SRC_COMMON_FIELD_MAP_SCALAR_HH_ +#endif // SRC_LIBMUGRID_FIELD_MAP_SCALAR_HH_ diff --git a/src/common/field_map_tensor.hh b/src/libmugrid/field_map_tensor.hh similarity index 95% rename from src/common/field_map_tensor.hh rename to src/libmugrid/field_map_tensor.hh index 0be64ea..8479905 100644 --- a/src/common/field_map_tensor.hh +++ b/src/libmugrid/field_map_tensor.hh @@ -1,293 +1,293 @@ /** * @file field_map_tensor.hh * * @author Till Junge * * @date 26 Sep 2017 * * @brief Defines an Eigen-Tensor map over strongly typed fields * * Copyright © 2017 Till Junge * - * µSpectre is free software; you can redistribute it and/or + * µGrid is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * - * µSpectre is distributed in the hope that it will be useful, but + * µGrid is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with µSpectre; see the file COPYING. If not, write to the + * along with µGrid; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#ifndef SRC_COMMON_FIELD_MAP_TENSOR_HH_ -#define SRC_COMMON_FIELD_MAP_TENSOR_HH_ +#ifndef SRC_LIBMUGRID_FIELD_MAP_TENSOR_HH_ +#define SRC_LIBMUGRID_FIELD_MAP_TENSOR_HH_ -#include "common/eigen_tools.hh" -#include "common/field_map_base.hh" +#include "eigen_tools.hh" +#include "field_map_base.hh" #include #include -namespace muSpectre { +namespace muGrid { /* ---------------------------------------------------------------------- */ /** - * Maps onto a `muSpectre::internal::TypedSizedFieldBase` and lets + * Maps onto a `muGrid::internal::TypedSizedFieldBase` and lets * you iterate over it in the form of `Eigen::TensorMap>` */ template class TensorFieldMap : public internal::FieldMap::Sizes::total_size, ConstField> { public: //! base class using Parent = internal::FieldMap; //! sister class with all params equal, but ConstField guaranteed true using ConstMap = TensorFieldMap; //! cell coordinates type using Ccoord = Ccoord_t; //! static tensor size using Sizes = typename SizesByOrder::Sizes; //! plain Eigen type using T_t = Eigen::TensorFixedSize; using value_type = Eigen::TensorMap; //!< stl conformance using const_reference = Eigen::TensorMap; //!< stl conformance //! stl conformance using reference = std::conditional_t; // since it's a resource handle using size_type = typename Parent::size_type; //!< stl conformance using pointer = std::unique_ptr; //!< stl conformance //! polymorphic base field type (for debug and python) using Field = typename Parent::Field; //! polymorphic base field type (for debug and python) using Field_c = typename Parent::Field_c; //! stl conformance using const_iterator = typename Parent::template iterator; //! stl conformance using iterator = std::conditional_t>; //! stl conformance using reverse_iterator = std::reverse_iterator; //! stl conformance using const_reverse_iterator = std::reverse_iterator; //! enumerator over a constant scalar field using const_enumerator = typename Parent::template enumerator; //! enumerator over a scalar field using enumerator = std::conditional_t>; //! give access to the protected fields friend iterator; //! Default constructor TensorFieldMap() = delete; //! constructor explicit TensorFieldMap(Field_c & field); //! Copy constructor TensorFieldMap(const TensorFieldMap & other) = delete; //! Move constructor TensorFieldMap(TensorFieldMap && other) = default; //! Destructor virtual ~TensorFieldMap() = default; //! Copy assignment operator TensorFieldMap & operator=(const TensorFieldMap & other) = delete; //! Assign a matrixlike value to every entry inline TensorFieldMap & operator=(const T_t & val); //! Move assignment operator TensorFieldMap & operator=(TensorFieldMap && other) = delete; //! give human-readable field map type inline std::string info_string() const final; //! member access inline reference operator[](size_type index); //! member access inline reference operator[](const Ccoord & ccoord); //! member access inline const_reference operator[](size_type index) const; //! member access inline const_reference operator[](const Ccoord & ccoord) const; //! return an iterator to first entry of field inline iterator begin() { return iterator(*this); } //! return an iterator to first entry of field inline const_iterator cbegin() const { return const_iterator(*this); } //! return an iterator to first entry of field inline const_iterator begin() const { return this->cbegin(); } //! return an iterator past the last entry of field inline iterator end() { return iterator(*this, false); } //! return an iterator past the last entry of field inline const_iterator cend() const { return const_iterator(*this, false); } //! return an iterator past the last entry of field inline const_iterator end() const { return this->cend(); } /** * return an iterable proxy to this field that can be iterated * in Ccoord-value tuples */ enumerator enumerate() { return enumerator(*this); } /** * return an iterable proxy to this field that can be iterated * in Ccoord-value tuples */ const_enumerator enumerate() const { return const_enumerator(*this); } //! evaluate the average of the field inline T_t mean() const; protected: //! for sad, legacy iterator use inline pointer ptr_to_val_t(size_type index); private: }; /* ---------------------------------------------------------------------- */ template TensorFieldMap::TensorFieldMap( Field_c & field) : Parent(field) { this->check_compatibility(); } /* ---------------------------------------------------------------------- */ //! human-readable field map type template std::string TensorFieldMap::info_string() const { std::stringstream info; info << "Tensor(" << typeid(T).name() << ", " << order << "_o, " << dim << "_d)"; return info.str(); } /* ---------------------------------------------------------------------- */ //! member access template typename TensorFieldMap::reference TensorFieldMap:: operator[](size_type index) { auto && lambda = [this, &index](auto &&... tens_sizes) { return reference(this->get_ptr_to_entry(index), tens_sizes...); }; return call_sizes(lambda); } template typename TensorFieldMap::reference TensorFieldMap:: operator[](const Ccoord & ccoord) { auto && index = this->collection.get_index(ccoord); auto && lambda = [this, &index](auto &&... sizes) { return reference(this->get_ptr_to_entry(index), sizes...); }; return call_sizes(lambda); } template typename TensorFieldMap::const_reference TensorFieldMap:: operator[](size_type index) const { // Warning: due to a inconsistency in Eigen's API, tensor maps // cannot be constructed from a const ptr, hence this nasty const // cast :( auto && lambda = [this, &index](auto &&... tens_sizes) { return const_reference(const_cast(this->get_ptr_to_entry(index)), tens_sizes...); }; return call_sizes(lambda); } template typename TensorFieldMap::const_reference TensorFieldMap:: operator[](const Ccoord & ccoord) const { auto && index = this->collection.get_index(ccoord); auto && lambda = [this, &index](auto &&... sizes) { return const_reference(const_cast(this->get_ptr_to_entry(index)), sizes...); }; return call_sizes(lambda); } /* ---------------------------------------------------------------------- */ template TensorFieldMap & TensorFieldMap:: operator=(const T_t & val) { for (auto && tens : *this) { tens = val; } return *this; } /* ---------------------------------------------------------------------- */ template typename TensorFieldMap::T_t TensorFieldMap::mean() const { T_t mean{T_t::Zero()}; for (auto && val : *this) { mean += val; } mean *= 1. / Real(this->size()); return mean; } /* ---------------------------------------------------------------------- */ //! for sad, legacy iterator use. Don't use unless you have to. template typename TensorFieldMap::pointer TensorFieldMap::ptr_to_val_t( size_type index) { auto && lambda = [this, &index](auto &&... tens_sizes) { return std::make_unique(this->get_ptr_to_entry(index), tens_sizes...); }; return call_sizes(lambda); } -} // namespace muSpectre +} // namespace muGrid -#endif // SRC_COMMON_FIELD_MAP_TENSOR_HH_ +#endif // SRC_LIBMUGRID_FIELD_MAP_TENSOR_HH_ diff --git a/src/common/field_typed.hh b/src/libmugrid/field_typed.hh similarity index 97% rename from src/common/field_typed.hh rename to src/libmugrid/field_typed.hh index 77f845d..af0e48b 100644 --- a/src/common/field_typed.hh +++ b/src/libmugrid/field_typed.hh @@ -1,531 +1,531 @@ /** * file field_typed.hh * * @author Till Junge * * @date 10 Apr 2018 * * @brief Typed Field for dynamically sized fields and base class for fields * of tensors, matrices, etc * * Copyright © 2018 Till Junge * - * µSpectre is free software; you can redistribute it and/or + * µGrid is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * - * µSpectre is distributed in the hope that it will be useful, but + * µGrid is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with µSpectre; see the file COPYING. If not, write to the + * along with µGrid; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#ifndef SRC_COMMON_FIELD_TYPED_HH_ -#define SRC_COMMON_FIELD_TYPED_HH_ +#ifndef SRC_LIBMUGRID_FIELD_TYPED_HH_ +#define SRC_LIBMUGRID_FIELD_TYPED_HH_ -#include "common/field_base.hh" -#include "common/field_helpers.hh" +#include "field_base.hh" +#include "field_helpers.hh" #include -namespace muSpectre { +namespace muGrid { /** * forward-declaration */ template class TypedFieldMap; namespace internal { /* ---------------------------------------------------------------------- */ //! declaraton for friending template class FieldMap; } // namespace internal /** * Dummy intermediate class to provide a run-time polymorphic * typed field. Mainly for binding Python. TypedField specifies methods * that return typed Eigen maps and vectors in addition to pointers to the * raw data. */ template class TypedField : public internal::FieldBase { friend class internal::FieldMap; friend class internal::FieldMap; static constexpr bool Global{FieldCollection::is_global()}; public: using Parent = internal::FieldBase; //!< base class //! for type checks when mapping this field using collection_t = typename Parent::collection_t; //! for filling global fields from local fields and vice-versa using LocalField_t = std::conditional_t< Global, TypedField, TypedField>; //! for filling global fields from local fields and vice-versa using GlobalField_t = std::conditional_t< Global, TypedField, TypedField>; using Scalar = T; //!< for type checks using Base = Parent; //!< for uniformity of interface //! Plain Eigen type to map using EigenRep_t = Eigen::Array; using EigenVecRep_t = Eigen::Matrix; //! map returned when accessing entire field using EigenMap_t = Eigen::Map; //! map returned when accessing entire const field using EigenMapConst_t = Eigen::Map; //! Plain eigen vector to map using EigenVec_t = Eigen::Map; //! vector map returned when accessing entire field using EigenVecConst_t = Eigen::Map; //! associated non-const field map using FieldMap_t = TypedFieldMap; //! associated const field map using ConstFieldMap_t = TypedFieldMap; /** * type stored (unfortunately, we can't statically size the second * dimension due to an Eigen bug, i.e., creating a row vector * reference to a column vector does not raise an error :( */ using Stored_t = Eigen::Array; //! storage container using Storage_t = std::vector>; //! Default constructor TypedField() = delete; //! constructor TypedField(std::string unique_name, FieldCollection & collection, size_t nb_components); /** * constructor for field proxies which piggy-back on existing * memory. These cannot be registered in field collections and * should only be used for transient temporaries */ TypedField(std::string unique_name, FieldCollection & collection, Eigen::Ref> vec, size_t nb_components); //! Copy constructor TypedField(const TypedField & other) = delete; //! Move constructor TypedField(TypedField && other) = default; //! Destructor virtual ~TypedField() = default; //! Copy assignment operator TypedField & operator=(const TypedField & other) = delete; //! Move assignment operator TypedField & operator=(TypedField && other) = delete; //! return type_id of stored type const std::type_info & get_stored_typeid() const final; //! safe reference cast static TypedField & check_ref(Base & other); //! safe reference cast static const TypedField & check_ref(const Base & other); size_t size() const final; //! add a pad region to the end of the field buffer; required for //! using this as e.g. an FFT workspace void set_pad_size(size_t pad_size_) final; //! initialise field to zero (do more complicated initialisations through //! fully typed maps) void set_zero() final; //! add a new value at the end of the field template inline void push_back(const Eigen::DenseBase & value); //! raw pointer to content (e.g., for Eigen maps) virtual T * data() { return this->get_ptr_to_entry(0); } //! raw pointer to content (e.g., for Eigen maps) virtual const T * data() const { return this->get_ptr_to_entry(0); } //! return a map representing the entire field as a single `Eigen::Array` EigenMap_t eigen(); //! return a map representing the entire field as a single `Eigen::Array` EigenMapConst_t eigen() const; //! return a map representing the entire field as a single Eigen vector EigenVec_t eigenvec(); //! return a map representing the entire field as a single Eigen vector EigenVecConst_t eigenvec() const; //! return a map representing the entire field as a single Eigen vector EigenVecConst_t const_eigenvec() const; /** * Convenience function to return a map onto this field. A map * allows iteration over all pixels. The map's iterator returns a * dynamically sized `Eigen::Map` the data associated with a * pixel. */ inline FieldMap_t get_map(); /** * Convenience function to return a map onto this field. A map * allows iteration over all pixels. The map's iterator returns a * dynamically sized `Eigen::Map` the data associated with a * pixel. */ inline ConstFieldMap_t get_map() const; /** * Convenience function to return a map onto this field. A map * allows iteration over all pixels. The map's iterator returns a * dynamically sized `Eigen::Map` the data associated with a * pixel. */ inline ConstFieldMap_t get_const_map() const; /** * creates a `TypedField` same size and type as this, but all * entries are zero. Convenience function */ inline TypedField & get_zeros_like(std::string unique_name) const; /** * Fill the content of the local field into the global field * (obviously only for pixels that actually are present in the * local field) */ template inline std::enable_if_t fill_from_local(const LocalField_t & local); /** * For pixels that are present in the local field, fill them with * the content of the global field at those pixels */ template inline std::enable_if_t fill_from_global(const GlobalField_t & global); protected: //! returns a raw pointer to the entry, for `Eigen::Map` inline T * get_ptr_to_entry(const size_t && index); //! returns a raw pointer to the entry, for `Eigen::Map` inline const T * get_ptr_to_entry(const size_t && index) const; //! set the storage size of this field inline void resize(size_t size) final; //! The actual storage container Storage_t values{}; /** * an unregistered typed field can be mapped onto an array of * existing values */ optional>> alt_values{}; /** * maintains a tally of the current size, as it cannot be reliably * determined from either `values` or `alt_values` alone. */ size_t current_size; /** * in order to accomodate both registered fields (who own and * manage their data) and unregistered temporary field proxies * (piggy-backing on a chunk of existing memory as e.g., a numpy * array) *efficiently*, the `get_ptr_to_entry` methods need to be * branchless. this means that we cannot decide on the fly whether * to return pointers pointing into values or into alt_values, we * need to maintain an (shudder) raw data pointer that is set * either at construction (for unregistered fields) or at any * resize event (which may invalidate existing pointers). For the * coder, this means that they need to be absolutely vigilant that * *any* operation on the values vector that invalidates iterators * needs to be followed by an update of data_ptr, or we will get * super annoying memory bugs. */ T * data_ptr{}; private: }; -} // namespace muSpectre +} // namespace muGrid -#include "common/field_map_dynamic.hh" +#include "field_map_dynamic.hh" -namespace muSpectre { +namespace muGrid { /* ---------------------------------------------------------------------- */ /* Implementations */ /* ---------------------------------------------------------------------- */ template TypedField::TypedField(std::string unique_name, FieldCollection & collection, size_t nb_components) : Parent(unique_name, nb_components, collection), current_size{0} {} /* ---------------------------------------------------------------------- */ template TypedField::TypedField( std::string unique_name, FieldCollection & collection, Eigen::Ref> vec, size_t nb_components) : Parent(unique_name, nb_components, collection), alt_values{vec}, current_size{vec.size() / nb_components}, data_ptr{vec.data()} { if (vec.size() % nb_components) { std::stringstream err{}; err << "The vector you supplied has a size of " << vec.size() << ", which is not a multiple of the number of components (" << nb_components << ")"; throw FieldError(err.str()); } if (current_size != collection.size()) { std::stringstream err{}; err << "The vector you supplied has the size for " << current_size << " pixels with " << nb_components << "components each, but the " << "field collection has " << collection.size() << " pixels."; throw FieldError(err.str()); } } /* ---------------------------------------------------------------------- */ //! return type_id of stored type template const std::type_info & TypedField::get_stored_typeid() const { return typeid(T); } /* ---------------------------------------------------------------------- */ template auto TypedField::eigen() -> EigenMap_t { return EigenMap_t(this->data(), this->get_nb_components(), this->size()); } /* ---------------------------------------------------------------------- */ template auto TypedField::eigen() const -> EigenMapConst_t { return EigenMapConst_t(this->data(), this->get_nb_components(), this->size()); } /* ---------------------------------------------------------------------- */ template auto TypedField::eigenvec() -> EigenVec_t { return EigenVec_t(this->data(), this->get_nb_components() * this->size(), 1); } /* ---------------------------------------------------------------------- */ template auto TypedField::eigenvec() const -> EigenVecConst_t { return EigenVecConst_t(this->data(), this->get_nb_components() * this->size(), 1); } /* ---------------------------------------------------------------------- */ template auto TypedField::const_eigenvec() const -> EigenVecConst_t { return EigenVecConst_t(this->data(), this->get_nb_components() * this->size()); } /* ---------------------------------------------------------------------- */ template auto TypedField::get_map() -> FieldMap_t { return FieldMap_t(*this); } /* ---------------------------------------------------------------------- */ template auto TypedField::get_map() const -> ConstFieldMap_t { return ConstFieldMap_t(*this); } /* ---------------------------------------------------------------------- */ template auto TypedField::get_const_map() const -> ConstFieldMap_t { return ConstFieldMap_t(*this); } /* ---------------------------------------------------------------------- */ template auto TypedField::get_zeros_like(std::string unique_name) const -> TypedField & { return make_field(unique_name, this->collection, this->nb_components); } /* ---------------------------------------------------------------------- */ template template std::enable_if_t TypedField::fill_from_local(const LocalField_t & local) { static_assert(IsGlobal == Global, "SFINAE parameter, do not touch"); if (not(local.get_nb_components() == this->get_nb_components())) { std::stringstream err_str{}; err_str << "Fields not compatible: You are trying to write a local " << local.get_nb_components() << "-component field into a global " << this->get_nb_components() << "-component field."; throw std::runtime_error(err_str.str()); } auto this_map{this->get_map()}; auto local_map{local.get_map()}; for (const auto && key_val : local_map.enumerate()) { const auto & key{std::get<0>(key_val)}; const auto & value{std::get<1>(key_val)}; this_map[key] = value; } } /* ---------------------------------------------------------------------- */ template template std::enable_if_t TypedField::fill_from_global( const GlobalField_t & global) { static_assert(IsLocal == not Global, "SFINAE parameter, do not touch"); if (not(global.get_nb_components() == this->get_nb_components())) { std::stringstream err_str{}; err_str << "Fields not compatible: You are trying to write a global " << global.get_nb_components() << "-component field into a local " << this->get_nb_components() << "-component field."; throw std::runtime_error(err_str.str()); } auto global_map{global.get_map()}; auto this_map{this->get_map()}; for (auto && key_val : this_map.enumerate()) { const auto & key{std::get<0>(key_val)}; auto & value{std::get<1>(key_val)}; value = global_map[key]; } } /* ---------------------------------------------------------------------- */ template void TypedField::resize(size_t size) { if (this->alt_values) { throw FieldError("Field proxies can't resize."); } this->current_size = size; this->values.resize(size * this->get_nb_components() + this->pad_size); this->data_ptr = &this->values.front(); } /* ---------------------------------------------------------------------- */ template void TypedField::set_zero() { std::fill(this->values.begin(), this->values.end(), T{}); } /* ---------------------------------------------------------------------- */ template auto TypedField::check_ref(Base & other) -> TypedField & { if (typeid(T).hash_code() != other.get_stored_typeid().hash_code()) { std::string err = "Cannot create a Reference of requested type " + ("for field '" + other.get_name() + "' of type '" + other.get_stored_typeid().name() + "'"); throw std::runtime_error(err); } return static_cast(other); } /* ---------------------------------------------------------------------- */ template auto TypedField::check_ref(const Base & other) -> const TypedField & { if (typeid(T).hash_code() != other.get_stored_typeid().hash_code()) { std::string err = "Cannot create a Reference of requested type " + ("for field '" + other.get_name() + "' of type '" + other.get_stored_typeid().name() + "'"); throw std::runtime_error(err); } return static_cast(other); } /* ---------------------------------------------------------------------- */ template size_t TypedField::size() const { return this->current_size; } /* ---------------------------------------------------------------------- */ template void TypedField::set_pad_size(size_t pad_size) { if (this->alt_values) { throw FieldError("You can't set the pad size of a field proxy."); } this->pad_size = pad_size; this->resize(this->size()); this->data_ptr = &this->values.front(); } /* ---------------------------------------------------------------------- */ template T * TypedField::get_ptr_to_entry(const size_t && index) { return this->data_ptr + this->get_nb_components() * std::move(index); } /* ---------------------------------------------------------------------- */ template const T * TypedField::get_ptr_to_entry( const size_t && index) const { return this->data_ptr + this->get_nb_components() * std::move(index); } /* ---------------------------------------------------------------------- */ template template void TypedField::push_back( const Eigen::DenseBase & value) { static_assert(not FieldCollection::Global, "You can only push_back data into local field collections"); if (value.cols() != 1) { std::stringstream err{}; err << "Expected a column vector, but received and array with " << value.cols() << " colums."; throw FieldError(err.str()); } if (value.rows() != static_cast(this->get_nb_components())) { std::stringstream err{}; err << "Expected a column vector of length " << this->get_nb_components() << ", but received one of length " << value.rows() << "."; throw FieldError(err.str()); } for (size_t i = 0; i < this->get_nb_components(); ++i) { this->values.push_back(value(i)); } ++this->current_size; this->data_ptr = &this->values.front(); } -} // namespace muSpectre +} // namespace muGrid -#endif // SRC_COMMON_FIELD_TYPED_HH_ +#endif // SRC_LIBMUGRID_FIELD_TYPED_HH_ diff --git a/src/libmugrid/grid_common.hh b/src/libmugrid/grid_common.hh new file mode 100644 index 0000000..b3790c6 --- /dev/null +++ b/src/libmugrid/grid_common.hh @@ -0,0 +1,127 @@ +/** + * @file grid_common.hh + * + * @author Till Junge + * + * @date 24 Jan 2019 + * + * @brief Small definitions of commonly used types throughout µgrid + * + * Copyright © 2019 Till Junge + * + * µgrid is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3, or (at + * your option) any later version. + * + * µgrid is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with µgrid; see the file COPYING. If not, write to the + * Free Software Foundation, Inc., 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + * + * Additional permission under GNU GPL version 3 section 7 + * + * If you modify this Program, or any covered work, by linking or combining it + * with proprietary FFT implementations or numerical libraries, containing parts + * covered by the terms of those libraries' licenses, the licensors of this + * Program grant you additional permission to convey the resulting work. + */ + +#include +#include +#include +#include + +#ifndef SRC_LIBMUGRID_GRID_COMMON_HH_ +#define SRC_LIBMUGRID_GRID_COMMON_HH_ + +namespace muGrid { + + /** + * Eigen uses signed integers for dimensions. For consistency, + µGrid uses them througout the code. needs to represent -1 for + eigen + */ + using Dim_t = int; + + constexpr Dim_t oneD{1}; //!< constant for a one-dimensional problem + constexpr Dim_t twoD{2}; //!< constant for a two-dimensional problem + constexpr Dim_t threeD{3}; //!< constant for a three-dimensional problem + constexpr Dim_t firstOrder{1}; //!< constant for vectors + constexpr Dim_t secondOrder{2}; //!< constant second-order tensors + constexpr Dim_t fourthOrder{4}; //!< constant fourth-order tensors + + //@{ + //! @anchor scalars + //! Scalar types used for mathematical calculations + using Uint = unsigned int; + using Int = int; + using Real = double; + using Complex = std::complex; + //@} + + //! Ccoord_t are cell coordinates, i.e. integer coordinates + template + using Ccoord_t = std::array; + //! Real space coordinates + template + using Rcoord_t = std::array; + + /** + * Allows inserting `muGrid::Ccoord_t` and `muGrid::Rcoord_t` + * into `std::ostream`s + */ + template + std::ostream & operator<<(std::ostream & os, + const std::array & index) { + os << "("; + for (size_t i = 0; i < dim - 1; ++i) { + os << index[i] << ", "; + } + os << index.back() << ")"; + return os; + } + + //! element-wise division + template + Rcoord_t operator/(const Rcoord_t & a, const Rcoord_t & b) { + Rcoord_t retval{a}; + for (size_t i = 0; i < dim; ++i) { + retval[i] /= b[i]; + } + return retval; + } + + //! element-wise division + template + Rcoord_t operator/(const Rcoord_t & a, const Ccoord_t & b) { + Rcoord_t retval{a}; + for (size_t i = 0; i < dim; ++i) { + retval[i] /= b[i]; + } + return retval; + } + + //! convenience definitions + constexpr Real pi{3.1415926535897932384626433}; + + //! compile-time potentiation required for field-size computations + template + constexpr R ipow(R base, I exponent) { + static_assert(std::is_integral::value, "Type must be integer"); + R retval{1}; + for (I i = 0; i < exponent; ++i) { + retval *= base; + } + return retval; + } +} // namespace muGrid + +#include "cpp_compliance.hh" + +#endif // SRC_LIBMUGRID_GRID_COMMON_HH_ diff --git a/src/common/iterators.hh b/src/libmugrid/iterators.hh similarity index 98% rename from src/common/iterators.hh rename to src/libmugrid/iterators.hh index dec4a59..e141652 100644 --- a/src/common/iterators.hh +++ b/src/libmugrid/iterators.hh @@ -1,367 +1,367 @@ /** * @file iterators.hh * * @author Nicolas Richart * * @date creation Wed Jul 19 2017 * * @brief iterator interfaces * * Copyright (©) 2010-2011 EPFL (Ecole Polytechnique Fédérale de Lausanne) * Laboratory (LSMS - Laboratoire de Simulation en Mécanique des Solides) * * Akantu is free software: you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * Akantu is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with Akantu. If not, see . * - * Above block was left intact as in akantu. µSpectre exercises the + * Above block was left intact as in akantu. µGrid exercises the * right to redistribute and modify the code below * */ /* -------------------------------------------------------------------------- */ #include #include /* -------------------------------------------------------------------------- */ -#ifndef SRC_COMMON_ITERATORS_HH_ -#define SRC_COMMON_ITERATORS_HH_ +#ifndef SRC_LIBMUGRID_ITERATORS_HH_ +#define SRC_LIBMUGRID_ITERATORS_HH_ namespace akantu { namespace tuple { /* ------------------------------------------------------------------------ */ namespace details { //! static for loop template struct Foreach { //! undocumented template static inline bool not_equal(Tuple && a, Tuple && b) { if (std::get(std::forward(a)) == std::get(std::forward(b))) return false; return Foreach::not_equal(std::forward(a), std::forward(b)); } }; /* ---------------------------------------------------------------------- */ //! static comparison template <> struct Foreach<0> { //! undocumented template static inline bool not_equal(Tuple && a, Tuple && b) { return std::get<0>(std::forward(a)) != std::get<0>(std::forward(b)); } }; //! eats up a bunch of arguments and returns them packed in a tuple template decltype(auto) make_tuple_no_decay(Ts &&... args) { return std::tuple(std::forward(args)...); } //! helper for static for loop template void foreach_impl(F && func, Tuple && tuple, std::index_sequence &&) { (void)std::initializer_list{ (std::forward(func)(std::get(std::forward(tuple))), 0)...}; } //! detail template decltype(auto) transform_impl(F && func, Tuple && tuple, std::index_sequence &&) { return make_tuple_no_decay( std::forward(func)(std::get(std::forward(tuple)))...); } }; // namespace details /* ------------------------------------------------------------------------ */ //! detail template bool are_not_equal(Tuple && a, Tuple && b) { return details::Foreach>::value>:: not_equal(std::forward(a), std::forward(b)); } //! detail template void foreach_(F && func, Tuple && tuple) { return details::foreach_impl( std::forward(func), std::forward(tuple), std::make_index_sequence< std::tuple_size>::value>{}); } //! detail template decltype(auto) transform(F && func, Tuple && tuple) { return details::transform_impl( std::forward(func), std::forward(tuple), std::make_index_sequence< std::tuple_size>::value>{}); } } // namespace tuple /* -------------------------------------------------------------------------- */ namespace iterators { //! iterator for emulation of python zip template class ZipIterator { private: using tuple_t = std::tuple; public: //! undocumented explicit ZipIterator(tuple_t iterators) : iterators(std::move(iterators)) {} //! undocumented decltype(auto) operator*() { return tuple::transform( [](auto && it) -> decltype(auto) { return *it; }, iterators); } //! undocumented ZipIterator & operator++() { tuple::foreach_([](auto && it) { ++it; }, iterators); return *this; } //! undocumented bool operator==(const ZipIterator & other) const { return not tuple::are_not_equal(iterators, other.iterators); } //! undocumented bool operator!=(const ZipIterator & other) const { return tuple::are_not_equal(iterators, other.iterators); } private: tuple_t iterators; }; } // namespace iterators /* -------------------------------------------------------------------------- */ //! emulates python zip() template decltype(auto) zip_iterator(std::tuple && iterators_tuple) { auto zip = iterators::ZipIterator( std::forward(iterators_tuple)); return zip; } /* -------------------------------------------------------------------------- */ namespace containers { //! helper for the emulation of python zip template class ZipContainer { using containers_t = std::tuple; public: //! undocumented explicit ZipContainer(Containers &&... containers) : containers(std::forward(containers)...) {} //! undocumented decltype(auto) begin() const { return zip_iterator( tuple::transform([](auto && c) { return c.begin(); }, std::forward(containers))); } //! undocumented decltype(auto) end() const { return zip_iterator( tuple::transform([](auto && c) { return c.end(); }, std::forward(containers))); } //! undocumented decltype(auto) begin() { return zip_iterator( tuple::transform([](auto && c) { return c.begin(); }, std::forward(containers))); } //! undocumented decltype(auto) end() { return zip_iterator( tuple::transform([](auto && c) { return c.end(); }, std::forward(containers))); } private: containers_t containers; }; } // namespace containers /* -------------------------------------------------------------------------- */ /** * emulates python's zip() */ template decltype(auto) zip(Containers &&... conts) { return containers::ZipContainer( std::forward(conts)...); } /* -------------------------------------------------------------------------- */ /* Arange */ /* -------------------------------------------------------------------------- */ namespace iterators { /** * emulates python's range iterator */ template class ArangeIterator { public: //! undocumented using value_type = T; //! undocumented using pointer = T *; //! undocumented using reference = T &; //! undocumented using iterator_category = std::input_iterator_tag; //! undocumented constexpr ArangeIterator(T value, T step) : value(value), step(step) {} //! undocumented constexpr ArangeIterator(const ArangeIterator &) = default; //! undocumented constexpr ArangeIterator & operator++() { value += step; return *this; } //! undocumented constexpr const T & operator*() const { return value; } //! undocumented constexpr bool operator==(const ArangeIterator & other) const { return (value == other.value) and (step == other.step); } //! undocumented constexpr bool operator!=(const ArangeIterator & other) const { return not operator==(other); } private: T value{0}; const T step{1}; }; } // namespace iterators namespace containers { //! helper class to generate range iterators template class ArangeContainer { public: //! undocumented using iterator = iterators::ArangeIterator; //! undocumented constexpr ArangeContainer(T start, T stop, T step = 1) : start(start), stop((stop - start) % step == 0 ? stop : start + (1 + (stop - start) / step) * step), step(step) {} //! undocumented explicit constexpr ArangeContainer(T stop) : ArangeContainer(0, stop, 1) {} //! undocumented constexpr T operator[](size_t i) { T val = start + i * step; assert(val < stop && "i is out of range"); return val; } //! undocumented constexpr T size() { return (stop - start) / step; } //! undocumented constexpr iterator begin() { return iterator(start, step); } //! undocumented constexpr iterator end() { return iterator(stop, step); } private: const T start{0}, stop{0}, step{1}; }; } // namespace containers /** * emulates python's range() */ template >::value>> inline decltype(auto) arange(const T & stop) { return containers::ArangeContainer(stop); } /** * emulates python's range() */ template >::value>> inline constexpr decltype(auto) arange(const T1 & start, const T2 & stop) { return containers::ArangeContainer>(start, stop); } /** * emulates python's range() */ template >::value>> inline constexpr decltype(auto) arange(const T1 & start, const T2 & stop, const T3 & step) { return containers::ArangeContainer>( start, stop, step); } /* -------------------------------------------------------------------------- */ /** * emulates python's enumerate */ template inline constexpr decltype(auto) enumerate(Container && container, size_t start_ = 0) { auto stop = std::forward(container).size(); decltype(stop) start = start_; return zip(arange(start, stop), std::forward(container)); } } // namespace akantu -#endif // SRC_COMMON_ITERATORS_HH_ +#endif // SRC_LIBMUGRID_ITERATORS_HH_ diff --git a/src/common/ref_array.hh b/src/libmugrid/ref_array.hh similarity index 89% rename from src/common/ref_array.hh rename to src/libmugrid/ref_array.hh index c9e11df..7af2deb 100644 --- a/src/common/ref_array.hh +++ b/src/libmugrid/ref_array.hh @@ -1,100 +1,100 @@ /** * file ref_array.hh * * @author Till Junge * * @date 04 Dec 2018 * * @brief convenience class to simulate an array of references * * Copyright © 2018 Till Junge * - * µSpectre is free software; you can redistribute it and/or + * µGrid is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * - * µSpectre is distributed in the hope that it will be useful, but + * µGrid is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with GNU Emacs; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#ifndef SRC_COMMON_REF_ARRAY_HH_ -#define SRC_COMMON_REF_ARRAY_HH_ +#ifndef SRC_LIBMUGRID_REF_ARRAY_HH_ +#define SRC_LIBMUGRID_REF_ARRAY_HH_ #include #include -#include "common/iterators.hh" +#include "iterators.hh" -namespace muSpectre { +namespace muGrid { namespace internal { template struct TypeChecker { constexpr static bool value{ std::is_same>::value and TypeChecker::value}; }; template struct TypeChecker { constexpr static bool value{ std::is_same>::value}; }; } // namespace internal template class RefArray { public: //! Default constructor RefArray() = delete; template explicit RefArray(Vals &... vals) : values{&vals...} { static_assert(internal::TypeChecker::value, "Only refs to type T allowed"); } //! Copy constructor RefArray(const RefArray & other) = default; //! Move constructor RefArray(RefArray && other) = default; //! Destructor virtual ~RefArray() = default; //! Copy assignment operator RefArray & operator=(const RefArray & other) = default; //! Move assignment operator RefArray & operator=(RefArray && other) = delete; T & operator[](size_t index) { return *this->values[index]; } constexpr T & operator[](size_t index) const { return *this->values[index]; } protected: std::array values{}; private: }; -} // namespace muSpectre +} // namespace muGrid -#endif // SRC_COMMON_REF_ARRAY_HH_ +#endif // SRC_LIBMUGRID_REF_ARRAY_HH_ diff --git a/src/common/statefield.hh b/src/libmugrid/statefield.hh similarity index 97% rename from src/common/statefield.hh rename to src/libmugrid/statefield.hh index 4a9c9b8..325db14 100644 --- a/src/common/statefield.hh +++ b/src/libmugrid/statefield.hh @@ -1,678 +1,676 @@ /** * file statefield.hh * * @author Till Junge * * @date 28 Feb 2018 * * @brief A state field is an abstraction of a field that can hold * current, as well as a chosen number of previous values. This is * useful for instance for internal state variables in plastic laws, * where a current, new, or trial state is computed based on its * previous state, and at convergence, this new state gets cycled into * the old, the old into the old-1 etc. The state field abstraction * helps doing this safely (i.e. only const references to the old * states are available, while the current state can be assigned * to/modified), and efficiently (i.e., no need to copy values from * new to old, we just cycle the labels). This file implements the * state field as well as state maps using the Field, FieldCollection - * and FieldMap abstractions of µSpectre + * and FieldMap abstractions of µGrid * * Copyright © 2018 Till Junge * - * µSpectre is free software; you can redistribute it and/or + * µGrid is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * - * µSpectre is distributed in the hope that it will be useful, but + * µGrid is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with µSpectre; see the file COPYING. If not, write to the + * along with µGrid; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#ifndef SRC_COMMON_STATEFIELD_HH_ -#define SRC_COMMON_STATEFIELD_HH_ +#ifndef SRC_LIBMUGRID_STATEFIELD_HH_ +#define SRC_LIBMUGRID_STATEFIELD_HH_ -#include "common/field_helpers.hh" -#include "common/field.hh" -#include "common/field_helpers.hh" -#include "common/field.hh" -#include "common/ref_array.hh" +#include "field_helpers.hh" +#include "field.hh" +#include "ref_array.hh" #include #include #include -namespace muSpectre { +namespace muGrid { /** * Forward-declaration */ template class TypedField; /** * Base class for state fields, useful for storing polymorphic references */ template class StateFieldBase { public: //! get naming prefix const std::string & get_prefix() const { return this->prefix; } //! get a ref to the `StateField` 's field collection const FieldCollection & get_collection() const { return this->collection; } virtual ~StateFieldBase() = default; /** * returns number of old states that are stored */ size_t get_nb_memory() const { return this->nb_memory; } //! return type_id of stored type virtual const std::type_info & get_stored_typeid() const = 0; /** * cycle the fields (current becomes old, old becomes older, * oldest becomes current) */ virtual void cycle() = 0; protected: //! constructor StateFieldBase(std::string unique_prefix, const FieldCollection & collection, size_t nb_memory = 1) : prefix{unique_prefix}, nb_memory{nb_memory}, collection{collection} {} /** * the unique prefix is used as the first part of the unique name * of the subfields belonging to this state field */ std::string prefix; /** * number of old states to store, defaults to 1 */ const size_t nb_memory; //! reference to the collection this statefield belongs to const FieldCollection & collection; }; /* ---------------------------------------------------------------------- */ template class TypedStateField : public StateFieldBase { public: //! Parent class using Parent = StateFieldBase; //! Typed field using TypedField_t = TypedField; //! returns a TypedField ref to the current value of this state field virtual TypedField_t & get_current_field() = 0; //! returns a const TypedField ref to an old value of this state field virtual const TypedField_t & get_old_field(size_t nb_steps_ago = 1) const = 0; //! returns a `StateField` reference if `other is a compatible state field inline static TypedStateField & check_ref(Parent & other) { // the following triggers and exception if the fields are incompatible if (typeid(T).hash_code() != other.get_stored_typeid().hash_code()) { std::stringstream err_str{}; err_str << "Cannot create a rerference of requested type " << "for statefield '" << other.get_prefix() << "' of type '" << other.get_stored_typeid().name() << "'"; throw std::runtime_error(err_str.str()); } return static_cast(other); } //! return type_id of stored type const std::type_info & get_stored_typeid() const final { return typeid(T); }; virtual ~TypedStateField() = default; protected: //! constructor TypedStateField(const std::string & unique_prefix, const FieldCollection & collection, size_t nb_memory) : Parent{unique_prefix, collection, nb_memory} {} }; /* ---------------------------------------------------------------------- */ template class TypedSizedStateField : public TypedStateField { public: //! Parent class using Parent = TypedStateField; //! the current (historically accurate) ordering of the fields using index_t = std::array; //! get the current ordering of the fields inline const index_t & get_indices() const { return this->indices; } //! destructor virtual ~TypedSizedStateField() = default; protected: //! constructor TypedSizedStateField(std::string unique_prefix, const FieldCollection & collection, index_t indices) : Parent{unique_prefix, collection, nb_memory}, indices{indices} {}; index_t indices; ///< these are cycled through }; //! early declaration template class StateFieldMap; namespace internal { template inline decltype(auto) build_fields_helper(std::string prefix, typename Field::Base::collection_t & collection, std::index_sequence) { auto get_field{[&prefix, &collection](size_t i) -> Field & { std::stringstream name_stream{}; name_stream << prefix << ", sub_field index " << i; return make_field(name_stream.str(), collection); }}; return RefArray(get_field(I)...); } /* ---------------------------------------------------------------------- */ template inline decltype(auto) build_indices(std::index_sequence) { return std::array{(size - I) % size...}; } } // namespace internal /** * A statefield is an abstraction around a Field that can hold a * current and `nb_memory` previous values. There are useful for * history variables, for instance. */ template class StateField : public TypedSizedStateField { public: //! the underlying field's collection type using FieldCollection_t = typename Field_t::Base::collection_t; //! base type for fields using Scalar = typename Field_t::Scalar; //! Base class for all state fields of same memory using Base = TypedSizedStateField; /** * storage of field refs (can't be a `std::array`, because arrays * of refs are explicitely forbidden */ using Fields_t = RefArray; //! Typed field using TypedField_t = TypedField; //! Default constructor StateField() = delete; //! Copy constructor StateField(const StateField & other) = delete; //! Move constructor StateField(StateField && other) = delete; //! Destructor virtual ~StateField() = default; //! Copy assignment operator StateField & operator=(const StateField & other) = delete; //! Move assignment operator StateField & operator=(StateField && other) = delete; //! get (modifiable) current field inline Field_t & current() { return this->fields[this->indices[0]]; } //! get (constant) previous field template inline const Field_t & old() { static_assert(nb_steps_ago <= nb_memory, "you can't go that far inte the past"); static_assert(nb_steps_ago > 0, "Did you mean to call current()?"); return this->fields[this->indices.at(nb_steps_ago)]; } //! returns a TypedField ref to the current value of this state field TypedField_t & get_current_field() final { return this->current(); } //! returns a const TypedField ref to an old value of this state field const TypedField_t & get_old_field(size_t nb_steps_ago = 1) const final { return this->fields[this->indices.at(nb_steps_ago)]; } //! factory function template friend StateFieldType & make_statefield(const std::string & unique_prefix, CollectionType & collection); //! returns a `StateField` reference if `other is a compatible state field inline static StateField & check_ref(Base & other) { // the following triggers and exception if the fields are incompatible Field_t::check_ref(other.fields[0]); return static_cast(other); } //! returns a const `StateField` reference if `other` is a compatible state //! field inline static const StateField & check_ref(const Base & other) { // the following triggers and exception if the fields are incompatible Field_t::check_ref(other.fields[0]); return static_cast(other); } //! get a ref to the `StateField` 's fields Fields_t & get_fields() { return this->fields; } /** * Pure convenience functions to get a MatrixFieldMap of * appropriate dimensions mapped to this field. You can also * create other types of maps, as long as they have the right * fundamental type (T), the correct size (nbComponents), and * memory (nb_memory). */ inline decltype(auto) get_map() { using FieldMap = decltype(this->fields[0].get_map()); return StateFieldMap(*this); } /** * Pure convenience functions to get a MatrixFieldMap of * appropriate dimensions mapped to this field. You can also * create other types of maps, as long as they have the right * fundamental type (T), the correct size (nbComponents), and * memory (nb_memory). */ inline decltype(auto) get_const_map() { using FieldMap = decltype(this->fields[0].get_const_map()); return StateFieldMap(*this); } /** * cycle the fields (current becomes old, old becomes older, * oldest becomes current) */ inline void cycle() final { for (auto & val : this->indices) { val = (val + 1) % (nb_memory + 1); } } protected: /** * Constructor. @param unique_prefix is used to create the names * of the fields that this abstraction creates in the background * @param collection is the field collection in which the * subfields will be stored */ inline StateField(const std::string & unique_prefix, FieldCollection_t & collection) : Base{unique_prefix, collection, internal::build_indices( std::make_index_sequence{})}, fields{internal::build_fields_helper( unique_prefix, collection, std::make_index_sequence{})} {} Fields_t fields; //!< container for the states private: }; namespace internal { template inline decltype(auto) build_maps_helper(Fields & fields, std::index_sequence) { return std::array{FieldMap(fields[I])...}; } } // namespace internal /* ---------------------------------------------------------------------- */ template inline StateFieldType & make_statefield(const std::string & unique_prefix, CollectionType & collection) { std::unique_ptr ptr{ new StateFieldType(unique_prefix, collection)}; auto & retref{*ptr}; collection.register_statefield(std::move(ptr)); return retref; } /** * extends the StateField <-> Field equivalence to StateFieldMap <-> FieldMap */ template class StateFieldMap { public: /** - * iterates over all pixels in the `muSpectre::FieldCollection` and + * iterates over all pixels in the `muGrid::FieldCollection` and * dereferences to a proxy giving access to the appropriate iterates * of the underlying `FieldMap` type. */ class iterator; //! stl conformance using reference = typename iterator::reference; //! stl conformance using value_type = typename iterator::value_type; //! stl conformance using size_type = typename iterator::size_type; //! field collection type where this state field can be stored using FieldCollection_t = typename FieldMap::Field::collection_t; //! Fundamental type stored using Scalar = typename FieldMap::Scalar; //! base class (must be at least sized) using TypedSizedStateField_t = TypedSizedStateField; //! for traits access using FieldMap_t = FieldMap; //! for traits access using ConstFieldMap_t = typename FieldMap::ConstMap; //! Default constructor StateFieldMap() = delete; //! constructor using a StateField template explicit StateFieldMap(StateField & statefield) : collection{statefield.get_collection()}, statefield{statefield}, maps{internal::build_maps_helper( statefield.get_fields(), std::make_index_sequence{})}, const_maps{ internal::build_maps_helper( statefield.get_fields(), std::make_index_sequence{})} { static_assert(std::is_base_of::value, "Not the right type of StateField ref"); } //! Copy constructor StateFieldMap(const StateFieldMap & other) = delete; //! Move constructor StateFieldMap(StateFieldMap && other) = default; //! Destructor virtual ~StateFieldMap() = default; //! Copy assignment operator StateFieldMap & operator=(const StateFieldMap & other) = delete; //! Move assignment operator StateFieldMap & operator=(StateFieldMap && other) = delete; //! access the wrapper to a given pixel directly value_type operator[](size_type index) { return *iterator(*this, index); } /** * return a ref to the current field map. useful for instance for * initialisations of `StateField` instances */ FieldMap & current() { return this->maps[this->statefield.get_indices()[0]]; } //! stl conformance iterator begin() { return iterator(*this, 0); } //! stl conformance iterator end() { return iterator(*this, this->collection.size()); } protected: const FieldCollection_t & collection; //!< collection holding the field TypedSizedStateField_t & statefield; //!< ref to the field itself std::array maps; //!< refs to the addressable maps; //! const refs to the addressable maps; std::array const_maps; private: }; /** * Iterator class used by the `StateFieldMap` */ template class StateFieldMap::iterator { public: class StateWrapper; using Ccoord = typename FieldMap::Ccoord; //!< cell coordinates type using value_type = StateWrapper; //!< stl conformance using const_value_type = value_type; //!< stl conformance using pointer_type = value_type *; //!< stl conformance using difference_type = std::ptrdiff_t; //!< stl conformance using size_type = size_t; //!< stl conformance using iterator_category = std::random_access_iterator_tag; //!< stl conformance using reference = StateWrapper; //!< stl conformance //! Default constructor iterator() = delete; //! constructor iterator(StateFieldMap & map, size_t index = 0) : index{index}, map{map} {}; //! Copy constructor iterator(const iterator & other) = default; //! Move constructor iterator(iterator && other) = default; //! Destructor virtual ~iterator() = default; //! Copy assignment operator iterator & operator=(const iterator & other) = default; //! Move assignment operator iterator & operator=(iterator && other) = default; //! pre-increment inline iterator & operator++() { this->index++; return *this; } //! post-increment inline iterator operator++(int) { iterator curr{*this}; this->index++; return curr; } //! dereference inline value_type operator*() { return value_type(*this); } //! pre-decrement inline iterator & operator--() { this->index--; return *this; } //! post-decrement inline iterator operator--(int) { iterator curr{*this}; this->index--; return curr; } //! access subscripting inline value_type operator[](difference_type diff) { return value_type{iterator{this->map, this->index + diff}}; } //! equality inline bool operator==(const iterator & other) const { return this->index == other.index; } //! inequality inline bool operator!=(const iterator & other) const { return this->index != other.index; } //! div. comparisons inline bool operator<(const iterator & other) const { return this->index < other.index; } //! div. comparisons inline bool operator<=(const iterator & other) const { return this->index <= other.index; } //! div. comparisons inline bool operator>(const iterator & other) const { return this->index > other.index; } //! div. comparisons inline bool operator>=(const iterator & other) const { return this->index >= other.index; } //! additions, subtractions and corresponding assignments inline iterator operator+(difference_type diff) const { return iterator{this->map, this - index + diff}; } //! additions, subtractions and corresponding assignments inline iterator operator-(difference_type diff) const { return iterator{this->map, this - index - diff}; } //! additions, subtractions and corresponding assignments inline iterator & operator+=(difference_type diff) { this->index += diff; return *this; } //! additions, subtractions and corresponding assignments inline iterator & operator-=(difference_type diff) { this->index -= diff; return *this; } //! get pixel coordinates inline Ccoord get_ccoord() const { return this->map.collection.get_ccoord(this->index); } //! access the index inline const size_t & get_index() const { return this->index; } protected: size_t index; //!< current pixel this iterator refers to StateFieldMap & map; //!< map over with `this` iterates }; namespace internal { //! FieldMap is an `Eigen::Map` or `Eigen::TensorMap` here template inline Array build_old_vals_helper(iterator & it, maps_t & maps, indices_t & indices, std::index_sequence) { return Array{maps[indices[I + 1]][it.get_index()]...}; } template inline Array build_old_vals(iterator & it, maps_t & maps, indices_t & indices) { return build_old_vals_helper(it, maps, indices, std::make_index_sequence{}); } } // namespace internal /** * Light-weight resource-handle representing the current and old * values of a field at a given pixel identified by an iterator * pointing to it */ template class StateFieldMap::iterator::StateWrapper { public: //! short-hand using iterator = typename StateFieldMap::iterator; //! short-hand using Ccoord = typename iterator::Ccoord; //! short-hand using Map = typename FieldMap::reference; //! short-hand using ConstMap = typename FieldMap::const_reference; /** * storage type differs depending on whether Map is a Reference type (in the * C++ sense) or not, because arrays of references are forbidden */ using Array_t = std::conditional_t< std::is_reference::value, RefArray, nb_memory>, std::array>; //! Default constructor StateWrapper() = delete; //! Copy constructor StateWrapper(const StateWrapper & other) = default; //! Move constructor StateWrapper(StateWrapper && other) = default; //! construct with `StateFieldMap::iterator` StateWrapper(iterator & it) : it{it}, current_val{ it.map.maps[it.map.statefield.get_indices()[0]][it.index]}, old_vals(internal::build_old_vals( it, it.map.const_maps, it.map.statefield.get_indices())) {} //! Destructor virtual ~StateWrapper() = default; //! Copy assignment operator StateWrapper & operator=(const StateWrapper & other) = default; //! Move assignment operator StateWrapper & operator=(StateWrapper && other) = default; //! returns reference to the currectly mapped value inline Map & current() { return this->current_val; } //! recurnts reference the the value that was current `nb_steps_ago` ago template inline const ConstMap & old() const { static_assert(nb_steps_ago <= nb_memory, "You have not stored that time step"); static_assert(nb_steps_ago > 0, "Did you mean to access the current value? If so, use " "current()"); return this->old_vals[nb_steps_ago - 1]; } //! read the coordinates of the current pixel inline Ccoord get_ccoord() const { return this->it.get_ccoord(); } protected: iterator & it; //!< ref to the iterator that dereferences to `this` Map current_val; //!< current value Array_t old_vals; //!< all stored old values }; -} // namespace muSpectre +} // namespace muGrid -#endif // SRC_COMMON_STATEFIELD_HH_ +#endif // SRC_LIBMUGRID_STATEFIELD_HH_ diff --git a/src/common/tensor_algebra.hh b/src/libmugrid/tensor_algebra.hh similarity index 94% rename from src/common/tensor_algebra.hh rename to src/libmugrid/tensor_algebra.hh index cf12935..d6db51e 100644 --- a/src/common/tensor_algebra.hh +++ b/src/libmugrid/tensor_algebra.hh @@ -1,380 +1,380 @@ /** * @file tensor_algebra.hh * * @author Till Junge * * @date 05 Nov 2017 * * @brief collection of compile-time quantities and algrebraic functions for * tensor operations * * Copyright © 2017 Till Junge * - * µSpectre is free software; you can redistribute it and/or + * µGrid is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * - * µSpectre is distributed in the hope that it will be useful, but + * µGrid is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with µSpectre; see the file COPYING. If not, write to the + * along with µGrid; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#ifndef SRC_COMMON_TENSOR_ALGEBRA_HH_ -#define SRC_COMMON_TENSOR_ALGEBRA_HH_ +#ifndef SRC_LIBMUGRID_TENSOR_ALGEBRA_HH_ +#define SRC_LIBMUGRID_TENSOR_ALGEBRA_HH_ -#include "common/T4_map_proxy.hh" -#include "common/common.hh" -#include "common/eigen_tools.hh" +#include "grid_common.hh" +#include "T4_map_proxy.hh" +#include "eigen_tools.hh" #include #include #include -namespace muSpectre { +namespace muGrid { namespace Tensors { //! second-order tensor representation template using Tens2_t = Eigen::TensorFixedSize>; //! fourth-order tensor representation template using Tens4_t = Eigen::TensorFixedSize>; //----------------------------------------------------------------------------// //! compile-time second-order identity template constexpr inline Tens2_t I2() { Tens2_t T; using Mat_t = Eigen::Matrix; Eigen::Map(&T(0, 0)) = Mat_t::Identity(); return T; } /* ---------------------------------------------------------------------- */ //! Check whether a given expression represents a Tensor specified order template struct is_tensor { //! evaluated test constexpr static bool value = (std::is_convertible>::value || std::is_convertible>::value || std::is_convertible>::value); }; /* ---------------------------------------------------------------------- */ /** compile-time outer tensor product as defined by Curnier * R_ijkl = A_ij.B_klxx * 0123 01 23 */ template constexpr inline decltype(auto) outer(T1 && A, T2 && B) { // Just make sure that the right type of parameters have been given constexpr Dim_t order{2}; static_assert(is_tensor::value, "T1 needs to be convertible to a second order Tensor"); static_assert(is_tensor::value, "T2 needs to be convertible to a second order Tensor"); // actual function std::array, 0> dims{}; return A.contract(B, dims); } /* ---------------------------------------------------------------------- */ /** compile-time underlined outer tensor product as defined by Curnier * R_ijkl = A_ik.B_jlxx * 0123 02 13 * 0213 01 23 <- this defines the shuffle order */ template constexpr inline decltype(auto) outer_under(T1 && A, T2 && B) { constexpr size_t order{4}; return outer(A, B).shuffle(std::array{{0, 2, 1, 3}}); } /* ---------------------------------------------------------------------- */ /** compile-time overlined outer tensor product as defined by Curnier * R_ijkl = A_il.B_jkxx * 0123 03 12 * 0231 01 23 <- this defines the shuffle order */ template constexpr inline decltype(auto) outer_over(T1 && A, T2 && B) { constexpr size_t order{4}; return outer(A, B).shuffle(std::array{{0, 2, 3, 1}}); } //! compile-time fourth-order symmetrising identity template constexpr inline Tens4_t I4S() { auto I = I2(); return 0.5 * (outer_under(I, I) + outer_over(I, I)); } } // namespace Tensors namespace Matrices { //! second-order tensor representation template using Tens2_t = Eigen::Matrix; //! fourth-order tensor representation template using Tens4_t = T4Mat; //----------------------------------------------------------------------------// //! compile-time second-order identity template constexpr inline Tens2_t I2() { return Tens2_t::Identity(); } /* ---------------------------------------------------------------------- */ /** compile-time outer tensor product as defined by Curnier * R_ijkl = A_ij.B_klxx * 0123 01 23 */ template constexpr inline decltype(auto) outer(T1 && A, T2 && B) { // Just make sure that the right type of parameters have been given constexpr Dim_t dim{EigenCheck::tensor_dim::value}; static_assert((dim == EigenCheck::tensor_dim::value), "A and B do not have the same dimension"); - Tens4_t product; for (Dim_t i = 0; i < dim; ++i) { for (Dim_t j = 0; j < dim; ++j) { for (Dim_t k = 0; k < dim; ++k) { for (Dim_t l = 0; l < dim; ++l) { get(product, i, j, k, l) = A(i, j) * B(k, l); } } } } return product; } /* ---------------------------------------------------------------------- */ /** compile-time underlined outer tensor product as defined by Curnier * R_ijkl = A_ik.B_jlxx * 0123 02 13 * 0213 01 23 <- this defines the shuffle order */ template constexpr inline decltype(auto) outer_under(T1 && A, T2 && B) { // Just make sure that the right type of parameters have been given constexpr Dim_t dim{EigenCheck::tensor_dim::value}; static_assert((dim == EigenCheck::tensor_dim::value), "A and B do not have the same dimension"); - Tens4_t product; for (Dim_t i = 0; i < dim; ++i) { for (Dim_t j = 0; j < dim; ++j) { for (Dim_t k = 0; k < dim; ++k) { for (Dim_t l = 0; l < dim; ++l) { get(product, i, j, k, l) = A(i, k) * B(j, l); } } } } return product; } /* ---------------------------------------------------------------------- */ /** compile-time overlined outer tensor product as defined by Curnier * R_ijkl = A_il.B_jkxx * 0123 03 12 * 0231 01 23 <- this defines the shuffle order */ template constexpr inline decltype(auto) outer_over(T1 && A, T2 && B) { // Just make sure that the right type of parameters have been given constexpr Dim_t dim{EigenCheck::tensor_dim::value}; static_assert((dim == EigenCheck::tensor_dim::value), "A and B do not have the same dimension"); - Tens4_t product; for (Dim_t i = 0; i < dim; ++i) { for (Dim_t j = 0; j < dim; ++j) { for (Dim_t k = 0; k < dim; ++k) { for (Dim_t l = 0; l < dim; ++l) { get(product, i, j, k, l) = A(i, l) * B(j, k); } } } } return product; } /** * Standart tensor multiplication */ template constexpr inline decltype(auto) tensmult(const Eigen::MatrixBase & A, const Eigen::MatrixBase & B) { constexpr Dim_t dim{T2::RowsAtCompileTime}; static_assert(dim == T2::ColsAtCompileTime, "B is not square"); static_assert(dim != Eigen::Dynamic, "B not statically sized"); static_assert(dim * dim == T4::RowsAtCompileTime, "A and B not compatible"); static_assert(T4::RowsAtCompileTime == T4::ColsAtCompileTime, "A is not square"); + Tens2_t result; result.setZero(); for (Dim_t i = 0; i < dim; ++i) { for (Dim_t j = 0; j < dim; ++j) { for (Dim_t k = 0; k < dim; ++k) { for (Dim_t l = 0; l < dim; ++l) { result(i, j) += get(A, i, j, k, l) * B(k, l); } } } } return result; } //! compile-time fourth-order tracer template constexpr inline Tens4_t Itrac() { auto I = I2(); return outer(I, I); } //! compile-time fourth-order identity template constexpr inline Tens4_t Iiden() { auto I = I2(); return outer_under(I, I); } //! compile-time fourth-order transposer template constexpr inline Tens4_t Itrns() { auto I = I2(); return outer_over(I, I); } //! compile-time fourth-order symmetriser template constexpr inline Tens4_t Isymm() { auto I = I2(); return 0.5 * (outer_under(I, I) + outer_over(I, I)); } namespace internal { /* ---------------------------------------------------------------------- */ template struct Dotter {}; /* ---------------------------------------------------------------------- */ template struct Dotter { template static constexpr decltype(auto) dot(T1 && t1, T2 && t2) { using T4_t = T4Mat::Scalar, Dim>; T4_t ret_val{T4_t::Zero()}; for (Int i = 0; i < Dim; ++i) { for (Int a = 0; a < Dim; ++a) { for (Int j = 0; j < Dim; ++j) { for (Int k = 0; k < Dim; ++k) { for (Int l = 0; l < Dim; ++l) { get(ret_val, i, j, k, l) += t1(i, a) * get(t2, a, j, k, l); } } } } } return ret_val; } }; /* ---------------------------------------------------------------------- */ template struct Dotter { template static constexpr decltype(auto) dot(T4 && t4, T2 && t2) { using T4_t = T4Mat::Scalar, Dim>; T4_t ret_val{T4_t::Zero()}; for (Int i = 0; i < Dim; ++i) { for (Int j = 0; j < Dim; ++j) { for (Int k = 0; k < Dim; ++k) { for (Int a = 0; a < Dim; ++a) { for (Int l = 0; l < Dim; ++l) { get(ret_val, i, j, k, l) += get(t4, i, j, k, a) * t2(a, l); } } } } } return ret_val; } }; /* ---------------------------------------------------------------------- */ template struct Dotter { template static constexpr decltype(auto) ddot(T1 && t1, T2 && t2) { return t1 * t2; } }; /* ---------------------------------------------------------------------- */ template struct Dotter { template static constexpr decltype(auto) ddot(T1 && t1, T2 && t2) { return (t1 * t2.transpose()).trace(); } }; } // namespace internal /* ---------------------------------------------------------------------- */ template decltype(auto) dot(T1 && t1, T2 && t2) { - constexpr Dim_t rank1{EigenCheck::tensor_rank::value}; - constexpr Dim_t rank2{EigenCheck::tensor_rank::value}; + using EigenCheck::tensor_rank; + constexpr Dim_t rank1{tensor_rank::value}; + constexpr Dim_t rank2{tensor_rank::value}; return internal::Dotter::dot(std::forward(t1), std::forward(t2)); } /* ---------------------------------------------------------------------- */ template decltype(auto) ddot(T1 && t1, T2 && t2) { - constexpr Dim_t rank1{EigenCheck::tensor_rank::value}; - constexpr Dim_t rank2{EigenCheck::tensor_rank::value}; + using EigenCheck::tensor_rank; + constexpr Dim_t rank1{tensor_rank::value}; + constexpr Dim_t rank2{tensor_rank::value}; return internal::Dotter::ddot(std::forward(t1), std::forward(t2)); } } // namespace Matrices -} // namespace muSpectre +} // namespace muGrid -#endif // SRC_COMMON_TENSOR_ALGEBRA_HH_ +#endif // SRC_LIBMUGRID_TENSOR_ALGEBRA_HH_ diff --git a/src/materials/material.hh~ b/src/materials/material.hh~ deleted file mode 100644 index e28b7d5..0000000 --- a/src/materials/material.hh~ +++ /dev/null @@ -1,84 +0,0 @@ -/** - * file material.hh - * - * @author Till Junge - * - * @date 25 Oct 2017 - * - * @brief Base class for materials (constitutive models) - * - * @section LICENCE - * - * Copyright (C) 2017 Till Junge - * - * µSpectre is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3, or (at - * your option) any later version. - * - * µSpectre is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with GNU Emacs; see the file COPYING. If not, write to the - * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA. - */ - -#include - -#include "common/common.hh" -#include "common/field_map_tensor.hh" - - -#ifndef MATERIAL_H -#define MATERIAL_H - -namespace muSpectre { - - //! DimS spatial dimension (dimension of problem - //! DimM material_dimension (dimension of constitutive law) - template - class MaterialBase - { - public: - //! Default constructor - MaterialBase() = delete; - - //! Construct by name - MaterialBase(std::string name); - - //! Copy constructor - MaterialBase(const MaterialBase &other) = delete; - - //! Move constructor - MaterialBase(MaterialBase &&other) noexcept = delete; - - //! Destructor - virtual ~MaterialBase() noexcept = default; - - //! Copy assignment operator - MaterialBase& operator=(const MaterialBase &other) = delete; - - //! Move assignment operator - MaterialBase& operator=(MaterialBase &&other) noexcept = delete; - - - //! take responsibility for a pixel identified by its cell coordinates - void add_pixel(const Ccoord & ccord); - - //! allocate memory, etc - virtual void initialize() = 0; - - //! computes the first Piola-Kirchhoff stress for finite strain problems - template - virtual void compute_stress( - - protected: - private: - }; -} // muSpectre - -#endif /* MATERIAL_H */ diff --git a/src/materials/material_base.cc b/src/materials/material_base.cc index 069ed78..49a240f 100644 --- a/src/materials/material_base.cc +++ b/src/materials/material_base.cc @@ -1,191 +1,193 @@ /** * @file material_base.cc * * @author Till Junge * * @date 01 Nov 2017 * * @brief implementation of material * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "materials/material_base.hh" namespace muSpectre { //----------------------------------------------------------------------------// template MaterialBase::MaterialBase(std::string name) : name(name) { static_assert((DimM == oneD) || (DimM == twoD) || (DimM == threeD), "only 1, 2, or threeD supported"); } /* ---------------------------------------------------------------------- */ template const std::string & MaterialBase::get_name() const { return this->name; } /* ---------------------------------------------------------------------- */ template void MaterialBase::add_pixel(const Ccoord & ccoord) { this->internal_fields.add_pixel(ccoord); } /* ---------------------------------------------------------------------- */ template void MaterialBase::add_pixel_split(const Ccoord & local_ccoord, Real ratio) { auto & this_mat = static_cast(*this); this_mat.add_pixel(local_ccoord); this->assigned_ratio.value().get().push_back(ratio); } /* ---------------------------------------------------------------------- */ template void MaterialBase::add_pixel_laminate(const Ccoord & local_ccoord, Real ratio, Rcoord normal_vec) { auto & this_mat = static_cast(*this); this_mat.add_pixel(local_ccoord); this->assigned_ratio.value().get().push_back(ratio); Eigen::Map> normal_vec_map(normal_vec.data()); this->assigned_normal_vec.value().get().push_back(normal_vec_map); } /* ---------------------------------------------------------------------- */ template void MaterialBase::allocate_optional_fields(SplitCell is_cell_split) { if (is_cell_split == SplitCell::simple || is_cell_split == SplitCell::laminate) { this->assigned_ratio = make_field("ratio", this->internal_fields); if (is_cell_split == SplitCell::laminate) { this->assigned_normal_vec = make_field("normal vector", this->internal_fields); // this->local_F = // make_field("local Strain", // this->internal_fields); // this->local_P = // make_field("local Stress", // this->internal_fields); // this->local_K = // make_field("local Tangent", // this->internal_fields); } } } /* ---------------------------------------------------------------------- */ template void MaterialBase::compute_stresses(const Field_t & F, Field_t & P, Formulation form, SplitCell is_cell_split) { this->compute_stresses(StrainField_t::check_ref(F), StressField_t::check_ref(P), form, is_cell_split); } /* ---------------------------------------------------------------------- */ template void MaterialBase::get_assigned_ratios( std::vector & pixel_assigned_ratios, Ccoord subdomain_resolutions, Ccoord subdomain_locations) { auto assigned_ratio_mapped = this->assigned_ratio.value().get().get_map(); for (auto && key_val : this->assigned_ratio.value().get().get_map().enumerate()) { const auto & ccoord = std::get<0>(key_val); const auto & val = std::get<1>(key_val); auto index = CcoordOps::get_index(subdomain_resolutions, subdomain_locations, ccoord); pixel_assigned_ratios[index] += val; } } /* ---------------------------------------------------------------------- */ template Real MaterialBase::get_assigned_ratio(Ccoord pixel) { return this->assigned_ratio.value().get().get_map()[pixel]; } //----------------------------------------------------------------------------// template void MaterialBase::compute_stresses_tangent( const Field_t & F, Field_t & P, Field_t & K, Formulation form, SplitCell is_cell_split) { this->compute_stresses_tangent( StrainField_t::check_ref(F), StressField_t::check_ref(P), TangentField_t::check_ref(K), form, is_cell_split); } template auto MaterialBase::get_real_field(std::string field_name) -> EigenMap { if (not this->internal_fields.check_field_exists(field_name)) { std::stringstream err{}; err << "Field '" << field_name << "' does not exist in material '" << this->name << "'."; - throw FieldCollectionError(err.str()); + throw muGrid::FieldCollectionError(err.str()); } auto & field{this->internal_fields[field_name]}; if (field.get_stored_typeid().hash_code() != typeid(Real).hash_code()) { std::stringstream err{}; err << "Field '" << field_name << "' is not real-valued"; - throw FieldCollectionError(err.str()); + throw muGrid::FieldCollectionError(err.str()); } - return static_cast &>(field).eigen(); + + return static_cast &>(field) + .eigen(); } /* ---------------------------------------------------------------------- */ template auto MaterialBase::make_C_voigt_from_col( T4Mat C_col) -> CVoigt_t { using VC_t = VoigtConversion; CVoigt_t C_voigt{CVoigt_t::Zero(vsize(DimM), vsize(DimM))}; for (int i{0}; i < DimM; ++i) { for (int j{0}; j < DimM; ++j) { for (int k{0}; k < DimM; ++k) { for (int l{0}; l < DimM; ++l) { C_voigt(VC_t::sym_mat(i, j), VC_t::sym_mat(k, l)) = get(C_col, i, j, k, l); } } } } return C_voigt; } /* ---------------------------------------------------------------------- */ template std::vector MaterialBase::list_fields() const { return this->internal_fields.list_fields(); } template class MaterialBase<2, 2>; template class MaterialBase<2, 3>; template class MaterialBase<3, 3>; } // namespace muSpectre diff --git a/src/materials/material_base.hh b/src/materials/material_base.hh index e269c69..86bdc21 100644 --- a/src/materials/material_base.hh +++ b/src/materials/material_base.hh @@ -1,245 +1,228 @@ /** * @file material_base.hh * * @author Till Junge * * @date 25 Oct 2017 * * @brief Base class for materials (constitutive models) * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_MATERIALS_MATERIAL_BASE_HH_ #define SRC_MATERIALS_MATERIAL_BASE_HH_ -#include "common/common.hh" -#include "common/field.hh" -#include "common/field_helpers.hh" -#include "common/field_collection.hh" -#include "common/voigt_conversion.hh" +#include "common/muSpectre_common.hh" + +#include +#include #include namespace muSpectre { //! DimS spatial dimension (dimension of problem //! DimM material_dimension (dimension of constitutive law) and /** * @a DimM is the material dimension (i.e., the dimension of constitutive * law; even for e.g. two-dimensional problems the constitutive law could * live in three-dimensional space for e.g. plane strain or stress problems) */ template class MaterialBase { public: //! typedefs for data handled by this interface //! global field collection for cell-wide fields, like stress, strain, etc - using GFieldCollection_t = GlobalFieldCollection; + using GFieldCollection_t = muGrid::GlobalFieldCollection; //! field collection for internal variables, such as eigen-strains, //! plastic strains, damage variables, etc, but also for managing which //! pixels the material is responsible for - using MFieldCollection_t = LocalFieldCollection; + using MFieldCollection_t = muGrid::LocalFieldCollection; using iterator = typename MFieldCollection_t::iterator; //!< pixel iterator //! polymorphic base class for fields only to be used for debugging - using Field_t = internal::FieldBase; + using Field_t = muGrid::internal::FieldBase; //! Full type for stress fields - using StressField_t = - TensorField; - using LocalStressField_t = - TensorField; + using StressField_t = muGrid::TensorField; //! Full type for strain fields using StrainField_t = StressField_t; using LocalStrainField_t = LocalStressField_t; //! Full type for tangent stiffness fields fields - using TangentField_t = - TensorField; - using LocalTangentField_t = - TensorField; - using MScalarField_t = ScalarField, Real>; - using MScalarFieldMap_t = - ScalarFieldMap, Real, true>; - using MVectorField_t = - TensorField, Real, firstOrder, DimM>; - - using ScalarField_t = ScalarField, Real>; - using VectorField_t = - TensorField, Real, firstOrder, DimM>; - - using CVoigt_t = Eigen::Matrix; - + using TangentField_t = muGrid::TensorField; using Ccoord = Ccoord_t; //!< cell coordinates type using Rcoord = Rcoord_t; //!< real coordinates type //! Default constructor MaterialBase() = delete; //! Construct by name explicit MaterialBase(std::string name); //! Copy constructor MaterialBase(const MaterialBase & other) = delete; //! Move constructor MaterialBase(MaterialBase && other) = delete; //! Destructor virtual ~MaterialBase() = default; //! Copy assignment operator MaterialBase & operator=(const MaterialBase & other) = delete; //! Move assignment operator MaterialBase & operator=(MaterialBase && other) = delete; /** * take responsibility for a pixel identified by its cell coordinates * WARNING: this won't work for materials with additional info per pixel * (as, e.g. for eigenstrain), we need to pass more parameters. Materials * of this type need to overload add_pixel */ virtual void add_pixel(const Ccoord & ccooord); virtual void add_pixel_split(const Ccoord & local_ccoord, Real ratio); virtual void add_pixel_laminate(const Ccoord & local_ccoord, Real ratio, Rcoord normal_vec); // this function is responsible for allocating fields in case cells are // split or laminate void allocate_optional_fields(SplitCell is_cell_split = SplitCell::no); //! allocate memory, etc, but also: wipe history variables! virtual void initialise() = 0; /** * for materials with state variables, these typically need to be * saved/updated an the end of each load increment, the virtual * base implementation does nothing, but materials with history * variables need to implement this */ virtual void save_history_variables() {} //! return the material's name const std::string & get_name() const; //! spatial dimension for static inheritance constexpr static Dim_t sdim() { return DimS; } //! material dimension for static inheritance constexpr static Dim_t mdim() { return DimM; } //! computes stress virtual void compute_stresses(const StrainField_t & F, StressField_t & P, Formulation form, SplitCell is_cell_split = SplitCell::no) = 0; /** * Convenience function to compute stresses, mostly for debugging and * testing. Has runtime-cost associated with compatibility-checking and * conversion of the Field_t arguments that can be avoided by using the * version with strongly typed field references */ void compute_stresses(const Field_t & F, Field_t & P, Formulation form, SplitCell is_cell_split = SplitCell::no); //! computes stress and tangent moduli virtual void compute_stresses_tangent(const StrainField_t & F, StressField_t & P, TangentField_t & K, Formulation form, SplitCell is_cell_split = SplitCell::no) = 0; /** * Convenience function to compute stresses and tangent moduli, mostly for * debugging and testing. Has runtime-cost associated with * compatibility-checking and conversion of the Field_t arguments that can * be avoided by using the version with strongly typed field references */ void compute_stresses_tangent(const Field_t & F, Field_t & P, Field_t & K, Formulation form, SplitCell is_cell_split = SplitCell::no); /** * returns a voigt notation of stiffness matrix converted form column major */ static auto make_C_voigt_from_col(T4Mat C_col) -> CVoigt_t; /** * This functio gives the corresponding ratio of the material * assigned to the material */ Real get_assigned_ratio(Ccoord pixel); // this function return the ratio of which the // input pixel is consisted of this material void get_assigned_ratios(std::vector & pixel_assigned_ratios, Ccoord subdomain_resolutions, Ccoord subdomain_locations); //! iterator to first pixel handled by this material inline iterator begin() { return this->internal_fields.begin(); } //! iterator past the last pixel handled by this material inline iterator end() { return this->internal_fields.end(); } //! number of pixels assigned to this material inline size_t size() const { return this->internal_fields.size(); } //! type to return real-valued fields in using EigenMap = Eigen::Map>; /** * return an internal field identified by its name as an Eigen Array */ EigenMap get_real_field(std::string field_name); /** * list the names of all internal fields */ std::vector list_fields() const; //! gives access to internal fields inline MFieldCollection_t & get_collection() { return this->internal_fields; } protected: const std::string name; //!< material's name (for output and debugging) MFieldCollection_t internal_fields{}; //!< storage for internal variables /** * //!< field holding the assigning ratio of the material * if the cell is split */ optional> assigned_ratio{}; /** *!< fields holding the: 1.normal vetor of the interface in laminate materials 2.local stress of the pixels 3 local stiffnesstangent materices of the pixels * if the cell is laminate */ optional> assigned_normal_vec{}; optional> local_stress_field{}; optional> local_tangent_field{}; private: }; } // namespace muSpectre #endif // SRC_MATERIALS_MATERIAL_BASE_HH_ diff --git a/src/materials/material_evaluator.hh b/src/materials/material_evaluator.hh index 32866ce..d22e277 100644 --- a/src/materials/material_evaluator.hh +++ b/src/materials/material_evaluator.hh @@ -1,267 +1,268 @@ /** * @file material_evaluator.hh * * @author Till Junge * * @date 12 Dec 2018 * * @brief Helper to evaluate material laws * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_MATERIALS_MATERIAL_EVALUATOR_HH_ #define SRC_MATERIALS_MATERIAL_EVALUATOR_HH_ -#include "common/common.hh" -#include "common/T4_map_proxy.hh" -#include "common/ccoord_operations.hh" +#include "common/muSpectre_common.hh" #include "materials/materials_toolbox.hh" -#include "common/field.hh" + +#include +#include +#include #include #include #include namespace muSpectre { /** * forward declaration to avoid incluning material_base.hh */ template class MaterialBase; template class MaterialEvaluator { public: using T2_t = Eigen::Matrix; - using T4_t = T4Mat; + using T4_t = muGrid::T4Mat; using T2_map = Eigen::Map; - using T4_map = T4MatMap; + using T4_map = muGrid::T4MatMap; using T2_const_map = Eigen::Map; - using T4_const_map = T4MatMap; + using T4_const_map = muGrid::T4MatMap; - using FieldColl_t = GlobalFieldCollection; - using T2Field_t = TensorField; - using T4Field_t = TensorField; + using FieldColl_t = muGrid::GlobalFieldCollection; + using T2Field_t = muGrid::TensorField; + using T4Field_t = muGrid::TensorField; //! Default constructor MaterialEvaluator() = delete; /** * constructor with a shared pointer to a Material */ explicit MaterialEvaluator( std::shared_ptr> material) - : material{material}, - collection{std::make_unique()}, - strain{make_field("gradient", *this->collection)}, - stress{make_field("stress", *this->collection)}, - tangent{make_field("tangent", *this->collection)} { - this->collection->initialise(CcoordOps::get_cube(1), {0}); + : material{material}, collection{std::make_unique()}, + strain{muGrid::make_field("gradient", *this->collection)}, + stress{muGrid::make_field("stress", *this->collection)}, + tangent{muGrid::make_field("tangent", *this->collection)} { + this->collection->initialise(muGrid::CcoordOps::get_cube(1), {0}); } //! Copy constructor MaterialEvaluator(const MaterialEvaluator & other) = delete; //! Move constructor MaterialEvaluator(MaterialEvaluator && other) = default; //! Destructor virtual ~MaterialEvaluator() = default; //! Copy assignment operator MaterialEvaluator & operator=(const MaterialEvaluator & other) = delete; //! Move assignment operator MaterialEvaluator & operator=(MaterialEvaluator && other) = default; /** * for materials with state variables. See `muSpectre::MaterialBase` for * details */ void save_history_variables() { this->material->save_history_variables(); } /** * Evaluates the underlying materials constitutive law and returns the * stress P or σ as a function of the placement gradient F or small strain * tensor ε depending on the formulation * (`muSpectre::Formulation::small_strain` for σ(ε), * `muSpectre::Formulation::finite_strain` for P(F)) */ inline T2_const_map evaluate_stress(const Eigen::Ref & grad, const Formulation & form); /** * Evaluates the underlying materials constitutive law and returns the the * stress P or σ and the tangent moduli K as a function of the placement * gradient F or small strain tensor ε depending on the formulation * (`muSpectre::Formulation::small_strain` for σ(ε), * `muSpectre::Formulation::finite_strain` for P(F)) */ inline std::tuple evaluate_stress_tangent(const Eigen::Ref & grad, const Formulation & form); /** * estimate the tangent using finite difference */ inline T4_t estimate_tangent(const Eigen::Ref & grad, const Formulation & form, const Real step, const FiniteDiff diff_type = FiniteDiff::centred); protected: /** * throws a runtime error if the material's per-pixel data has not been set. */ void check_init() const; std::shared_ptr> material; std::unique_ptr collection; T2Field_t & strain; T2Field_t & stress; T4Field_t & tangent; }; /* ---------------------------------------------------------------------- */ template - auto MaterialEvaluator::evaluate_stress( - const Eigen::Ref & grad, const Formulation & form) + auto + MaterialEvaluator::evaluate_stress(const Eigen::Ref & grad, + const Formulation & form) -> T2_const_map { this->check_init(); this->strain.get_map()[0] = grad; this->material->compute_stresses(this->strain, this->stress, form); return T2_const_map(this->stress.get_map()[0].data()); } /* ---------------------------------------------------------------------- */ template auto MaterialEvaluator::evaluate_stress_tangent( const Eigen::Ref & grad, const Formulation & form) -> std::tuple { this->check_init(); this->strain.get_map()[0] = grad; this->material->compute_stresses_tangent(this->strain, this->stress, - this->tangent, form); + this->tangent, form); return std::make_tuple(T2_const_map(this->stress.get_map()[0].data()), T4_const_map(this->tangent.get_map()[0].data())); } template void MaterialEvaluator::check_init() const { const auto & size{this->material->size()}; if (size < 1) { throw std::runtime_error( "Not initialised! You have to call `add_pixel(...)` on your material " "exactly one time before you can evaluate it."); } else if (size > 1) { std::stringstream error{}; error << "The material to be evaluated should have exactly one pixel " "added. You've added " << size << " pixels."; throw std::runtime_error(error.str()); } } /* ---------------------------------------------------------------------- */ template auto MaterialEvaluator::estimate_tangent( const Eigen::Ref & grad, const Formulation & form, const Real delta, const FiniteDiff diff_type) -> T4_t { using T2_vec = Eigen::Map>; T4_t tangent{T4_t::Zero()}; const T2_t stress{this->evaluate_stress(grad, form)}; auto fun{[&form, this](const auto & grad_) { return this->evaluate_stress(grad_, form); }}; auto symmetrise{ [](auto & eps) { eps = .5 * (eps + eps.transpose().eval()); }}; static_assert(Int(decltype(tangent.col(0))::SizeAtCompileTime) == Int(T2_t::SizeAtCompileTime), "wrong column size"); for (Dim_t i{}; i < DimM * DimM; ++i) { T2_t strain2{grad}; T2_vec strain2_vec{strain2.data()}; switch (diff_type) { case FiniteDiff::forward: { strain2_vec(i) += delta; if (form == Formulation::small_strain) { symmetrise(strain2); } T2_t del_f_del{(fun(strain2) - stress) / delta}; tangent.col(i) = T2_vec(del_f_del.data()); break; } case FiniteDiff::backward: { strain2_vec(i) -= delta; if (form == Formulation::small_strain) { symmetrise(strain2); } T2_t del_f_del{(stress - fun(strain2)) / delta}; tangent.col(i) = T2_vec(del_f_del.data()); break; } case FiniteDiff::centred: { T2_t strain1{grad}; T2_vec strain1_vec{strain1.data()}; strain1_vec(i) += delta; strain2_vec(i) -= delta; if (form == Formulation::small_strain) { symmetrise(strain1); symmetrise(strain2); } T2_t del_f_del{(fun(strain1).eval() - fun(strain2).eval()) / (2 * delta)}; tangent.col(i) = T2_vec(del_f_del.data()); break; } default: { throw std::runtime_error("Unknown FiniteDiff value"); break; } } static_assert(Int(decltype(tangent.col(i))::SizeAtCompileTime) == Int(T2_t::SizeAtCompileTime), "wrong column size"); } return tangent; } } // namespace muSpectre #endif // SRC_MATERIALS_MATERIAL_EVALUATOR_HH_ diff --git a/src/materials/material_hyper_elasto_plastic1.cc b/src/materials/material_hyper_elasto_plastic1.cc index 1c6236a..4bf1a1f 100644 --- a/src/materials/material_hyper_elasto_plastic1.cc +++ b/src/materials/material_hyper_elasto_plastic1.cc @@ -1,214 +1,216 @@ /** * @file material_hyper_elasto_plastic1.cc * * @author Till Junge * * @date 21 Feb 2018 * * @brief implementation for MaterialHyperElastoPlastic1 * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ -#include "common/common.hh" -#include "common/T4_map_proxy.hh" +#include "common/muSpectre_common.hh" #include "materials/stress_transformations_Kirchhoff.hh" #include "materials/material_hyper_elasto_plastic1.hh" +#include + namespace muSpectre { //--------------------------------------------------------------------------// template MaterialHyperElastoPlastic1::MaterialHyperElastoPlastic1( std::string name, Real young, Real poisson, Real tau_y0, Real H) : Parent{name}, - plast_flow_field{ - make_statefield>>( - "cumulated plastic flow εₚ", this->internal_fields)}, - F_prev_field{make_statefield< - StateField>>( + plast_flow_field{muGrid::make_statefield< + muGrid::StateField>>( + "cumulated plastic flow εₚ", this->internal_fields)}, + F_prev_field{muGrid::make_statefield>>( "Previous placement gradient Fᵗ", this->internal_fields)}, - be_prev_field{make_statefield< - StateField>>( + be_prev_field{muGrid::make_statefield>>( "Previous left Cauchy-Green deformation bₑᵗ", this->internal_fields)}, young{young}, poisson{poisson}, lambda{Hooke::compute_lambda(young, poisson)}, mu{Hooke::compute_mu(young, poisson)}, K{Hooke::compute_K(young, poisson)}, tau_y0{tau_y0}, H{H}, // the factor .5 comes from equation (18) in Geers 2003 // (https://doi.org/10.1016/j.cma.2003.07.014) C{0.5 * Hooke::compute_C_T4(lambda, mu)}, internal_variables{F_prev_field.get_map(), be_prev_field.get_map(), plast_flow_field.get_map()} {} /* ---------------------------------------------------------------------- */ template void MaterialHyperElastoPlastic1::save_history_variables() { this->plast_flow_field.cycle(); this->F_prev_field.cycle(); this->be_prev_field.cycle(); } /* ---------------------------------------------------------------------- */ template void MaterialHyperElastoPlastic1::initialise() { Parent::initialise(); this->F_prev_field.get_map().current() = Eigen::Matrix::Identity(); this->be_prev_field.get_map().current() = Eigen::Matrix::Identity(); this->save_history_variables(); } //--------------------------------------------------------------------------// template auto MaterialHyperElastoPlastic1::stress_n_internals_worker( const T2_t & F, StrainStRef_t & F_prev, StrainStRef_t & be_prev, FlowStRef_t & eps_p) -> Worker_t { // the notation in this function follows Geers 2003 // (https://doi.org/10.1016/j.cma.2003.07.014). // computation of trial state using Mat_t = Eigen::Matrix; Mat_t f{F * F_prev.old().inverse()}; // trial elastic left Cauchy–Green deformation tensor Mat_t be_star{f * be_prev.old() * f.transpose()}; - const Decomp_t spectral_decomp{spectral_decomposition(be_star)}; - Mat_t ln_be_star{logm_alt(spectral_decomp)}; + const muGrid::Decomp_t spectral_decomp{ + muGrid::spectral_decomposition(be_star)}; + Mat_t ln_be_star{muGrid::logm_alt(spectral_decomp)}; Mat_t tau_star{.5 * Hooke::evaluate_stress(this->lambda, this->mu, ln_be_star)}; // deviatoric part of Kirchhoff stress Mat_t tau_d_star{tau_star - tau_star.trace() / DimM * tau_star.Identity()}; Real tau_eq_star{std::sqrt( 3 * .5 * (tau_d_star.array() * tau_d_star.transpose().array()).sum())}; // tau_eq_star can only be zero if tau_d_star is identically zero, // so the following is not an approximation; Real division_safe_tau_eq_star{tau_eq_star + Real(tau_eq_star == 0.)}; Mat_t N_star{3 * .5 * tau_d_star / division_safe_tau_eq_star}; // this is eq (27), and the std::min enforces the Kuhn-Tucker relation (16) Real phi_star{ std::max(tau_eq_star - this->tau_y0 - this->H * eps_p.old(), 0.)}; // return mapping Real Del_gamma{phi_star / (this->H + 3 * this->mu)}; Mat_t tau{tau_star - 2 * Del_gamma * this->mu * N_star}; // update the previous values to the new ones F_prev.current() = F; - be_prev.current() = expm(ln_be_star - 2 * Del_gamma * N_star); + be_prev.current() = muGrid::expm(ln_be_star - 2 * Del_gamma * N_star); eps_p.current() = eps_p.old() + Del_gamma; // transmit info whether this is a plastic step or not bool is_plastic{phi_star > 0}; return Worker_t(std::move(tau), std::move(tau_eq_star), std::move(Del_gamma), std::move(N_star), std::move(is_plastic), spectral_decomp); } //--------------------------------------------------------------------------// template auto MaterialHyperElastoPlastic1::evaluate_stress( const T2_t & F, StrainStRef_t F_prev, StrainStRef_t be_prev, FlowStRef_t eps_p) -> T2_t { Eigen::Matrix tau; std::tie(tau, std::ignore, std::ignore, std::ignore, std::ignore, std::ignore) = this->stress_n_internals_worker(F, F_prev, be_prev, eps_p); return tau; } //--------------------------------------------------------------------------// template auto MaterialHyperElastoPlastic1::evaluate_stress_tangent( const T2_t & F, StrainStRef_t F_prev, StrainStRef_t be_prev, FlowStRef_t eps_p) -> std::tuple { //! after the stress computation, all internals are up to date auto && vals{this->stress_n_internals_worker(F, F_prev, be_prev, eps_p)}; auto & tau{std::get<0>(vals)}; auto & tau_eq_star{std::get<1>(vals)}; auto & Del_gamma{std::get<2>(vals)}; auto & N_star{std::get<3>(vals)}; auto & is_plastic{std::get<4>(vals)}; auto & spec_decomp{std::get<5>(vals)}; using Mat_t = Eigen::Matrix; using Vec_t = Eigen::Matrix; - using T4_t = T4Mat; + using T4_t = muGrid::T4Mat; auto compute_C4ep = [&]() { auto && a0 = Del_gamma * this->mu / tau_eq_star; auto && a1 = this->mu / (this->H + 3 * this->mu); - return T4Mat{ + return muGrid::T4Mat{ ((this->K / 2. - this->mu / 3 + a0 * this->mu) * Matrices::Itrac() + (1 - 3 * a0) * this->mu * Matrices::Isymm() + 2 * this->mu * (a0 - a1) * Matrices::outer(N_star, N_star))}; }; T4_t mat_tangent{is_plastic ? compute_C4ep() : this->C}; // compute derivative ∂ln(be_star)/∂be_star, see (77) through (80) T4_t dlnbe_dbe{T4_t::Zero()}; { const Vec_t & eig_vals{spec_decomp.eigenvalues()}; const Vec_t log_eig_vals{eig_vals.array().log().matrix()}; const Mat_t & eig_vecs{spec_decomp.eigenvectors()}; Mat_t g_vals{}; // see (78), (79) for (int i{0}; i < DimM; ++i) { g_vals(i, i) = 1 / eig_vals(i); for (int j{i + 1}; j < DimM; ++j) { if (std::abs((eig_vals(i) - eig_vals(j)) / eig_vals(i)) < 1e-12) { g_vals(i, j) = g_vals(j, i) = g_vals(i, i); } else { g_vals(i, j) = g_vals(j, i) = ((log_eig_vals(j) - log_eig_vals(i)) / (eig_vals(j) - eig_vals(i))); } } } for (int i{0}; i < DimM; ++i) { for (int j{0}; j < DimM; ++j) { Mat_t dyad = eig_vecs.col(i) * eig_vecs.col(j).transpose(); T4_t outerDyad = Matrices::outer(dyad, dyad.transpose()); dlnbe_dbe += g_vals(i, j) * outerDyad; } } } // compute variation δbe_star T2_t I{Matrices::I2()}; // computation of trial state Mat_t f{F * F_prev.old().inverse()}; // trial elastic left Cauchy–Green deformation tensor Mat_t be_star{f * be_prev.old() * f.transpose()}; T4_t dbe_dF{Matrices::outer_under(I, be_star) + Matrices::outer_over(be_star, I)}; // T4_t dtau_dbe{mat_tangent * dlnbe_dbe * dbe4s}; T4_t dtau_dF{mat_tangent * dlnbe_dbe * dbe_dF}; // return std::tuple(tau, dtau_dbe); return std::tuple(tau, dtau_dF); } template class MaterialHyperElastoPlastic1; template class MaterialHyperElastoPlastic1; template class MaterialHyperElastoPlastic1; } // namespace muSpectre diff --git a/src/materials/material_hyper_elasto_plastic1.hh b/src/materials/material_hyper_elasto_plastic1.hh index 81669b9..cc00bba 100644 --- a/src/materials/material_hyper_elasto_plastic1.hh +++ b/src/materials/material_hyper_elasto_plastic1.hh @@ -1,247 +1,255 @@ /** * @file material_hyper_elasto_plastic1.hh * * @author Till Junge * * @date 20 Feb 2018 * * @brief Material for logarithmic hyperelasto-plasticity, as defined in de * Geus 2017 (https://doi.org/10.1016/j.cma.2016.12.032) and further * explained in Geers 2003 (https://doi.org/10.1016/j.cma.2003.07.014) * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_MATERIALS_MATERIAL_HYPER_ELASTO_PLASTIC1_HH_ #define SRC_MATERIALS_MATERIAL_HYPER_ELASTO_PLASTIC1_HH_ #include "materials/material_muSpectre_base.hh" #include "materials/materials_toolbox.hh" -#include "common/eigen_tools.hh" -#include "common/statefield.hh" + +#include +#include #include namespace muSpectre { template class MaterialHyperElastoPlastic1; /** * traits for hyper-elastoplastic material */ template struct MaterialMuSpectre_traits> { //! global field collection using GFieldCollection_t = typename MaterialBase::GFieldCollection_t; //! expected map type for strain fields using StrainMap_t = - MatrixFieldMap; + muGrid::MatrixFieldMap; //! expected map type for stress fields - using StressMap_t = MatrixFieldMap; + using StressMap_t = + muGrid::MatrixFieldMap; //! expected map type for tangent stiffness fields - using TangentMap_t = T4MatrixFieldMap; + using TangentMap_t = + muGrid::T4MatrixFieldMap; //! declare what type of strain measure your law takes as input constexpr static auto strain_measure{StrainMeasure::Gradient}; //! declare what type of stress measure your law yields as output constexpr static auto stress_measure{StressMeasure::Kirchhoff}; //! local field collection used for internals - using LFieldColl_t = LocalFieldCollection; + using LFieldColl_t = muGrid::LocalFieldCollection; //! storage type for plastic flow measure (εₚ in the papers) - using LScalarMap_t = StateFieldMap>; + using LScalarMap_t = + muGrid::StateFieldMap>; /** * storage type for for previous gradient Fᵗ and elastic left * Cauchy-Green deformation tensor bₑᵗ */ - using LStrainMap_t = - StateFieldMap>; + using LStrainMap_t = muGrid::StateFieldMap< + muGrid::MatrixFieldMap>; /** * format in which to receive internals (previous gradient Fᵗ, * previous elastic lef Cauchy-Green deformation tensor bₑᵗ, and * the plastic flow measure εₚ */ using InternalVariables = std::tuple; }; /** * material implementation for hyper-elastoplastic constitutive law. Note for * developpers: this law is tested against a reference python implementation * in `py_comparison_test_material_hyper_elasto_plastic1.py` */ template class MaterialHyperElastoPlastic1 : public MaterialMuSpectre, DimS, DimM> { public: //! base class using Parent = MaterialMuSpectre, DimS, DimM>; using T2_t = Eigen::Matrix; - using T4_t = T4Mat; + using T4_t = muGrid::T4Mat; /** * type used to determine whether the * `muSpectre::MaterialMuSpectre::iterable_proxy` evaluate only * stresses or also tangent stiffnesses */ using NeedTangent = typename Parent::NeedTangent; //! shortcut to traits using traits = MaterialMuSpectre_traits; //! Hooke's law implementation using Hooke = typename MatTB::Hooke; //! type in which the previous strain state is referenced using StrainStRef_t = typename traits::LStrainMap_t::reference; //! type in which the previous plastic flow is referenced using FlowStRef_t = typename traits::LScalarMap_t::reference; //! Local FieldCollection type for field storage - using LColl_t = LocalFieldCollection; + using LColl_t = muGrid::LocalFieldCollection; //! Default constructor MaterialHyperElastoPlastic1() = delete; //! Constructor with name and material properties MaterialHyperElastoPlastic1(std::string name, Real young, Real poisson, Real tau_y0, Real H); //! Copy constructor MaterialHyperElastoPlastic1(const MaterialHyperElastoPlastic1 & other) = delete; //! Move constructor MaterialHyperElastoPlastic1(MaterialHyperElastoPlastic1 && other) = delete; //! Destructor virtual ~MaterialHyperElastoPlastic1() = default; //! Copy assignment operator MaterialHyperElastoPlastic1 & operator=(const MaterialHyperElastoPlastic1 & other) = delete; //! Move assignment operator MaterialHyperElastoPlastic1 & operator=(MaterialHyperElastoPlastic1 && other) = delete; /** * evaluates Kirchhoff stress given the current placement gradient * Fₜ, the previous Gradient Fₜ₋₁ and the cumulated plastic flow * εₚ */ T2_t evaluate_stress(const T2_t & F, StrainStRef_t F_prev, StrainStRef_t be_prev, FlowStRef_t plast_flow); /** * evaluates Kirchhoff stress and stiffness given the current placement * gradient Fₜ, the previous Gradient Fₜ₋₁ and the cumulated plastic flow εₚ */ std::tuple evaluate_stress_tangent(const T2_t & F, StrainStRef_t F_prev, StrainStRef_t be_prev, FlowStRef_t plast_flow); /** * The statefields need to be cycled at the end of each load increment */ void save_history_variables() override; /** * set the previous gradients to identity */ void initialise() final; /** * return the internals tuple */ typename traits::InternalVariables & get_internals() { return this->internal_variables; } //! getter for internal variable field εₚ - StateField> & get_plast_flow_field() { + muGrid::StateField> & + get_plast_flow_field() { return this->plast_flow_field; } //! getter for previous gradient field Fᵗ - StateField> & + muGrid::StateField> & get_F_prev_field() { return this->F_prev_field; } //! getterfor elastic left Cauchy-Green deformation tensor bₑᵗ - StateField> & + muGrid::StateField> & get_be_prev_field() { return this->be_prev_field; } /** * needed to accomodate the static-sized member variable C, see * http://eigen.tuxfamily.org/dox-devel/group__TopicStructHavingEigenMembers.html */ EIGEN_MAKE_ALIGNED_OPERATOR_NEW; protected: /** * worker function computing stresses and internal variables */ - using Worker_t = std::tuple>; + using Worker_t = + std::tuple>; Worker_t stress_n_internals_worker(const T2_t & F, StrainStRef_t & F_prev, StrainStRef_t & be_prev, FlowStRef_t & plast_flow); //! storage for cumulated plastic flow εₚ - StateField> & plast_flow_field; + muGrid::StateField> & plast_flow_field; //! storage for previous gradient Fᵗ - StateField> & F_prev_field; + muGrid::StateField> & + F_prev_field; //! storage for elastic left Cauchy-Green deformation tensor bₑᵗ - StateField> & be_prev_field; + muGrid::StateField> & + be_prev_field; // material properties - const Real young; //!< Young's modulus - const Real poisson; //!< Poisson's ratio - const Real lambda; //!< first Lamé constant - const Real mu; //!< second Lamé constant (shear modulus) - const Real K; //!< Bulk modulus - const Real tau_y0; //!< initial yield stress - const Real H; //!< hardening modulus - const T4Mat C; //!< stiffness tensor + const Real young; //!< Young's modulus + const Real poisson; //!< Poisson's ratio + const Real lambda; //!< first Lamé constant + const Real mu; //!< second Lamé constant (shear modulus) + const Real K; //!< Bulk modulus + const Real tau_y0; //!< initial yield stress + const Real H; //!< hardening modulus + const muGrid::T4Mat C; //!< stiffness tensor //! Field maps and state field maps over internal fields typename traits::InternalVariables internal_variables; }; } // namespace muSpectre #endif // SRC_MATERIALS_MATERIAL_HYPER_ELASTO_PLASTIC1_HH_ diff --git a/src/materials/material_linear_elastic1.hh b/src/materials/material_linear_elastic1.hh index cdc2505..8f05d62 100644 --- a/src/materials/material_linear_elastic1.hh +++ b/src/materials/material_linear_elastic1.hh @@ -1,190 +1,192 @@ /** * @file material_linear_elastic1.hh * * @author Till Junge * * @date 13 Nov 2017 * * @brief Implementation for linear elastic reference material like in de Geus * 2017. This follows the simplest and likely not most efficient * implementation (with exception of the Python law) * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC1_HH_ #define SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC1_HH_ -#include "common/common.hh" +#include "common/muSpectre_common.hh" #include "materials/stress_transformations_PK2.hh" #include "materials/material_muSpectre_base.hh" #include "materials/materials_toolbox.hh" namespace muSpectre { template class MaterialLinearElastic1; /** * traits for objective linear elasticity */ template struct MaterialMuSpectre_traits> { using Parent = MaterialMuSpectre_traits; //!< base for elasticity //! global field collection using GFieldCollection_t = typename MaterialBase::GFieldCollection_t; //! expected map type for strain fields using StrainMap_t = - MatrixFieldMap; + muGrid::MatrixFieldMap; //! expected map type for stress fields - using StressMap_t = MatrixFieldMap; + using StressMap_t = + muGrid::MatrixFieldMap; //! expected map type for tangent stiffness fields - using TangentMap_t = T4MatrixFieldMap; + using TangentMap_t = + muGrid::T4MatrixFieldMap; //! declare what type of strain measure your law takes as input constexpr static auto strain_measure{StrainMeasure::GreenLagrange}; //! declare what type of stress measure your law yields as output constexpr static auto stress_measure{StressMeasure::PK2}; //! elasticity without internal variables using InternalVariables = std::tuple<>; }; //! DimS spatial dimension (dimension of problem //! DimM material_dimension (dimension of constitutive law) /** * implements objective linear elasticity */ template class MaterialLinearElastic1 : public MaterialMuSpectre, DimS, DimM> { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW //! base class using Parent = MaterialMuSpectre; /** * type used to determine whether the * `muSpectre::MaterialMuSpectre::iterable_proxy` evaluate only * stresses or also tangent stiffnesses */ using NeedTangent = typename Parent::NeedTangent; //! global field collection using Stiffness_t = T4Mat; //! traits of this material using traits = MaterialMuSpectre_traits; //! this law does not have any internal variables using InternalVariables = typename traits::InternalVariables; //! Hooke's law implementation using Hooke = typename MatTB::Hooke; //! Default constructor MaterialLinearElastic1() = delete; //! Copy constructor MaterialLinearElastic1(const MaterialLinearElastic1 & other) = delete; //! Construct by name, Young's modulus and Poisson's ratio MaterialLinearElastic1(std::string name, Real young, Real poisson); //! Move constructor MaterialLinearElastic1(MaterialLinearElastic1 && other) = delete; //! Destructor virtual ~MaterialLinearElastic1() = default; //! Copy assignment operator MaterialLinearElastic1 & operator=(const MaterialLinearElastic1 & other) = delete; //! Move assignment operator MaterialLinearElastic1 & operator=(MaterialLinearElastic1 && other) = delete; /** * evaluates second Piola-Kirchhoff stress given the Green-Lagrange * strain (or Cauchy stress if called with a small strain tensor) */ template inline decltype(auto) evaluate_stress(s_t && E); /** * evaluates both second Piola-Kirchhoff stress and stiffness given * the Green-Lagrange strain (or Cauchy stress and stiffness if * called with a small strain tensor) */ template inline decltype(auto) evaluate_stress_tangent(s_t && E); /** * return the empty internals tuple */ InternalVariables & get_internals() { return this->internal_variables; } auto get_C() { return this->C; } protected: const Real young; //!< Young's modulus const Real poisson; //!< Poisson's ratio const Real lambda; //!< first Lamé constant const Real mu; //!< second Lamé constant (shear modulus) const Stiffness_t C; //!< stiffness tensor //! empty tuple InternalVariables internal_variables{}; private: }; /* ---------------------------------------------------------------------- */ template template auto MaterialLinearElastic1::evaluate_stress(s_t && E) -> decltype(auto) { return Hooke::evaluate_stress(this->lambda, this->mu, std::move(E)); } /* ---------------------------------------------------------------------- */ template template auto MaterialLinearElastic1::evaluate_stress_tangent(s_t && E) -> decltype(auto) { using Tangent_t = typename traits::TangentMap_t::reference; return Hooke::evaluate_stress( this->lambda, this->mu, Tangent_t(const_cast(this->C.data())), std::move(E)); } } // namespace muSpectre #endif // SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC1_HH_ diff --git a/src/materials/material_linear_elastic2.cc b/src/materials/material_linear_elastic2.cc index c05ddcb..e20fdeb 100644 --- a/src/materials/material_linear_elastic2.cc +++ b/src/materials/material_linear_elastic2.cc @@ -1,70 +1,71 @@ /** * @file material_linear_elastic2.cc * * @author Till Junge * * @date 04 Feb 2018 * * @brief implementation for linear elastic material with eigenstrain * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "materials/material_linear_elastic2.hh" namespace muSpectre { /* ---------------------------------------------------------------------- */ template MaterialLinearElastic2::MaterialLinearElastic2(std::string name, Real young, Real poisson) : Parent{name}, material{name, young, poisson}, - eigen_field{make_field("Eigenstrain", this->internal_fields)}, + eigen_field{ + muGrid::make_field("Eigenstrain", this->internal_fields)}, internal_variables(eigen_field.get_const_map()) {} /* ---------------------------------------------------------------------- */ template void MaterialLinearElastic2::add_pixel( const Ccoord_t & /*pixel*/) { throw std::runtime_error("this material needs pixels with and eigenstrain"); } /* ---------------------------------------------------------------------- */ template void MaterialLinearElastic2::add_pixel(const Ccoord_t & pixel, const StrainTensor & E_eig) { this->internal_fields.add_pixel(pixel); Eigen::Map> strain_array( E_eig.data()); this->eigen_field.push_back(strain_array); } template class MaterialLinearElastic2; template class MaterialLinearElastic2; template class MaterialLinearElastic2; } // namespace muSpectre diff --git a/src/materials/material_linear_elastic2.hh b/src/materials/material_linear_elastic2.hh index 861e874..8ed06ce 100644 --- a/src/materials/material_linear_elastic2.hh +++ b/src/materials/material_linear_elastic2.hh @@ -1,202 +1,206 @@ /** * @file material_linear_elastic2.hh * * @author Till Junge * * @date 03 Feb 2018 * * @brief linear elastic material with imposed eigenstrain and its * type traits. Uses the MaterialMuSpectre facilities to keep it * simple * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC2_HH_ #define SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC2_HH_ #include "materials/material_linear_elastic1.hh" -#include "common/field.hh" + +#include #include namespace muSpectre { template class MaterialLinearElastic2; /** * traits for objective linear elasticity with eigenstrain */ template struct MaterialMuSpectre_traits> { //! global field collection using GFieldCollection_t = typename MaterialBase::GFieldCollection_t; //! expected map type for strain fields using StrainMap_t = - MatrixFieldMap; + muGrid::MatrixFieldMap; //! expected map type for stress fields - using StressMap_t = MatrixFieldMap; + using StressMap_t = + muGrid::MatrixFieldMap; //! expected map type for tangent stiffness fields - using TangentMap_t = T4MatrixFieldMap; + using TangentMap_t = + muGrid::T4MatrixFieldMap; //! declare what type of strain measure your law takes as input constexpr static auto strain_measure{StrainMeasure::GreenLagrange}; //! declare what type of stress measure your law yields as output constexpr static auto stress_measure{StressMeasure::PK2}; //! local field_collections used for internals - using LFieldColl_t = LocalFieldCollection; + using LFieldColl_t = muGrid::LocalFieldCollection; //! local strain type - using LStrainMap_t = MatrixFieldMap; + using LStrainMap_t = + muGrid::MatrixFieldMap; //! elasticity with eigenstrain using InternalVariables = std::tuple; }; /** * implements objective linear elasticity with an eigenstrain per pixel */ template class MaterialLinearElastic2 : public MaterialMuSpectre, DimS, DimM> { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW //! base class using Parent = MaterialMuSpectre; //! type for stiffness tensor construction using Stiffness_t = Eigen::TensorFixedSize>; //! traits of this material using traits = MaterialMuSpectre_traits; //! Type of container used for storing eigenstrain using InternalVariables = typename traits::InternalVariables; //! Hooke's law implementation using Hooke = typename MatTB::Hooke; //! reference to any type that casts to a matrix using StrainTensor = Eigen::Ref>; //! Default constructor MaterialLinearElastic2() = delete; //! Construct by name, Young's modulus and Poisson's ratio MaterialLinearElastic2(std::string name, Real young, Real poisson); //! Copy constructor MaterialLinearElastic2(const MaterialLinearElastic2 & other) = delete; //! Move constructor MaterialLinearElastic2(MaterialLinearElastic2 && other) = delete; //! Destructor virtual ~MaterialLinearElastic2() = default; //! Copy assignment operator MaterialLinearElastic2 & operator=(const MaterialLinearElastic2 & other) = delete; //! Move assignment operator MaterialLinearElastic2 & operator=(MaterialLinearElastic2 && other) = delete; /** * evaluates second Piola-Kirchhoff stress given the Green-Lagrange * strain (or Cauchy stress if called with a small strain tensor) */ template inline decltype(auto) evaluate_stress(s_t && E, eigen_s_t && E_eig); /** * evaluates both second Piola-Kirchhoff stress and stiffness given * the Green-Lagrange strain (or Cauchy stress and stiffness if * called with a small strain tensor) */ template inline decltype(auto) evaluate_stress_tangent(s_t && E, eigen_s_t && E_eig); /** * return the internals tuple */ InternalVariables & get_internals() { return this->internal_variables; } /** * overload add_pixel to write into eigenstrain */ void add_pixel(const Ccoord_t & pixel) final; /** * overload add_pixel to write into eigenstrain */ void add_pixel(const Ccoord_t & pixel, const StrainTensor & E_eig); protected: //! linear material without eigenstrain used to compute response MaterialLinearElastic1 material; //! storage for eigenstrain - using Field_t = - TensorField, Real, secondOrder, DimM>; + using Field_t = muGrid::TensorField, + Real, secondOrder, DimM>; Field_t & eigen_field; //!< field holding the eigen strain per pixel //! tuple for iterable eigen_field InternalVariables internal_variables; }; /* ---------------------------------------------------------------------- */ template template auto MaterialLinearElastic2::evaluate_stress(s_t && E, eigen_s_t && E_eig) -> decltype(auto) { return this->material.evaluate_stress(E - E_eig); } /* ---------------------------------------------------------------------- */ template template auto MaterialLinearElastic2::evaluate_stress_tangent( s_t && E, eigen_s_t && E_eig) -> decltype(auto) { // using mat = Eigen::Matrix; // mat ecopy{E}; // mat eig_copy{E_eig}; // mat ediff{ecopy-eig_copy}; // std::cout << "eidff - (E-E_eig)" << std::endl << ediff-(E-E_eig) << // std::endl; std::cout << "P1 " << std::endl << // mat{std::get<0>(this->material.evaluate_stress_tangent(E-E_eig))} << // "" << std::endl; std::cout << "P2" << std::endl << // mat{std::get<0>(this->material.evaluate_stress_tangent(std::move(ediff)))} // << std::endl; return this->material.evaluate_stress_tangent(E - E_eig); } } // namespace muSpectre #endif // SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC2_HH_ diff --git a/src/materials/material_linear_elastic3.cc b/src/materials/material_linear_elastic3.cc index 6349c46..5b1850e 100644 --- a/src/materials/material_linear_elastic3.cc +++ b/src/materials/material_linear_elastic3.cc @@ -1,73 +1,73 @@ /** * @file material_linear_elastic3.cc * * @author Richard Leute MaterialLinearElastic3::MaterialLinearElastic3(std::string name) - : Parent{name}, C_field{make_field("local stiffness tensor", - this->internal_fields)}, + : Parent{name}, C_field{muGrid::make_field( + "local stiffness tensor", this->internal_fields)}, internal_variables(C_field.get_const_map()) {} /* ---------------------------------------------------------------------- */ template void MaterialLinearElastic3::add_pixel( const Ccoord_t & /*pixel*/) { throw std::runtime_error( "this material needs pixels with Youngs modulus and Poisson ratio."); } /* ---------------------------------------------------------------------- */ template void MaterialLinearElastic3::add_pixel( const Ccoord_t & pixel, const Real & Young, const Real & Poisson) { this->internal_fields.add_pixel(pixel); Real lambda = Hooke::compute_lambda(Young, Poisson); Real mu = Hooke::compute_mu(Young, Poisson); auto C_tensor = Hooke::compute_C(lambda, mu); Eigen::Map> C( C_tensor.data()); this->C_field.push_back(C); } template class MaterialLinearElastic3; template class MaterialLinearElastic3; template class MaterialLinearElastic3; } // namespace muSpectre diff --git a/src/materials/material_linear_elastic3.hh b/src/materials/material_linear_elastic3.hh index 27a4df2..5732eed 100644 --- a/src/materials/material_linear_elastic3.hh +++ b/src/materials/material_linear_elastic3.hh @@ -1,198 +1,201 @@ /** * @file material_linear_elastic3.hh * * @author Richard Leute * * @date 20 Feb 2018 * * @brief linear elastic material with distribution of stiffness properties. * Uses the MaterialMuSpectre facilities to keep it simple. * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC3_HH_ #define SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC3_HH_ #include "materials/material_linear_elastic1.hh" -#include "common/field.hh" -#include "common/tensor_algebra.hh" + +#include #include namespace muSpectre { template class MaterialLinearElastic3; /** * traits for objective linear elasticity with eigenstrain */ template struct MaterialMuSpectre_traits> { //! global field collection using GFieldCollection_t = typename MaterialBase::GFieldCollection_t; //! expected map type for strain fields using StrainMap_t = - MatrixFieldMap; + muGrid::MatrixFieldMap; //! expected map type for stress fields - using StressMap_t = MatrixFieldMap; + using StressMap_t = + muGrid::MatrixFieldMap; //! expected map type for tangent stiffness fields - using TangentMap_t = T4MatrixFieldMap; + using TangentMap_t = + muGrid::T4MatrixFieldMap; //! declare what type of strain measure your law takes as input constexpr static auto strain_measure{StrainMeasure::GreenLagrange}; //! declare what type of stress measure your law yields as output constexpr static auto stress_measure{StressMeasure::PK2}; //! local field_collections used for internals - using LFieldColl_t = LocalFieldCollection; + using LFieldColl_t = muGrid::LocalFieldCollection; //! local stiffness tensor type - using LStiffnessMap_t = T4MatrixFieldMap; + using LStiffnessMap_t = + muGrid::T4MatrixFieldMap; //! elasticity without internal variables using InternalVariables = std::tuple; }; /** * implements objective linear elasticity with an eigenstrain per pixel */ template class MaterialLinearElastic3 : public MaterialMuSpectre, DimS, DimM> { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW //! base class using Parent = MaterialMuSpectre; /** * type used to determine whether the * `muSpectre::MaterialMuSpectre::iterable_proxy` evaluate only * stresses or also tangent stiffnesses */ using NeedTangent = typename Parent::NeedTangent; //! global field collection using Stiffness_t = Eigen::TensorFixedSize>; //! traits of this material using traits = MaterialMuSpectre_traits; //! Type of container used for storing eigenstrain using InternalVariables = typename traits::InternalVariables; //! Hooke's law implementation using Hooke = typename MatTB::Hooke; //! Default constructor MaterialLinearElastic3() = delete; //! Construct by name explicit MaterialLinearElastic3(std::string name); //! Copy constructor MaterialLinearElastic3(const MaterialLinearElastic3 & other) = delete; //! Move constructor MaterialLinearElastic3(MaterialLinearElastic3 && other) = delete; //! Destructor virtual ~MaterialLinearElastic3() = default; //! Copy assignment operator MaterialLinearElastic3 & operator=(const MaterialLinearElastic3 & other) = delete; //! Move assignment operator MaterialLinearElastic3 & operator=(MaterialLinearElastic3 && other) = delete; /** * evaluates second Piola-Kirchhoff stress given the Green-Lagrange * strain (or Cauchy stress if called with a small strain tensor) * and the local stiffness tensor. */ template inline decltype(auto) evaluate_stress(s_t && E, stiffness_t && C); /** * evaluates both second Piola-Kirchhoff stress and stiffness given * the Green-Lagrange strain (or Cauchy stress and stiffness if * called with a small strain tensor) and the local stiffness tensor. */ template inline decltype(auto) evaluate_stress_tangent(s_t && E, stiffness_t && C); /** * return the empty internals tuple */ InternalVariables & get_internals() { return this->internal_variables; } /** * overload add_pixel to write into loacal stiffness tensor */ void add_pixel(const Ccoord_t & pixel) final; /** * overload add_pixel to write into local stiffness tensor */ void add_pixel(const Ccoord_t & pixel, const Real & Young, const Real & PoissonRatio); protected: //! storage for stiffness tensor - using Field_t = - TensorField, Real, fourthOrder, DimM>; + using Field_t = muGrid::TensorField, + Real, fourthOrder, DimM>; Field_t & C_field; //!< field of stiffness tensors //! tuple for iterable eigen_field InternalVariables internal_variables; private: }; /* ---------------------------------------------------------------------- */ template template auto MaterialLinearElastic3::evaluate_stress(s_t && E, stiffness_t && C) -> decltype(auto) { return Matrices::tensmult(C, E); } /* ---------------------------------------------------------------------- */ template template auto MaterialLinearElastic3::evaluate_stress_tangent( s_t && E, stiffness_t && C) -> decltype(auto) { return std::make_tuple(evaluate_stress(E, C), C); } } // namespace muSpectre #endif // SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC3_HH_ diff --git a/src/materials/material_linear_elastic4.cc b/src/materials/material_linear_elastic4.cc index 2999ef3..f957513 100644 --- a/src/materials/material_linear_elastic4.cc +++ b/src/materials/material_linear_elastic4.cc @@ -1,79 +1,79 @@ /** * @file material_linear_elastic4.cc * * @author Richard Leute MaterialLinearElastic4::MaterialLinearElastic4(std::string name) - : Parent{name}, lambda_field{make_field( + : Parent{name}, lambda_field{muGrid::make_field( "local first Lame constant", this->internal_fields)}, - mu_field{ - make_field("local second Lame constant(shear modulus)", - this->internal_fields)}, + mu_field{muGrid::make_field( + "local second Lame constant(shear modulus)", + this->internal_fields)}, internal_variables{lambda_field.get_const_map(), mu_field.get_const_map()} {} /* ---------------------------------------------------------------------- */ template - void MaterialLinearElastic4:: - add_pixel(const Ccoord_t & /*pixel*/) { - throw std::runtime_error - ("This material needs pixels with Youngs modulus and Poisson ratio."); + void MaterialLinearElastic4::add_pixel( + const Ccoord_t & /*pixel*/) { + throw std::runtime_error( + "This material needs pixels with Youngs modulus and Poisson ratio."); } /* ---------------------------------------------------------------------- */ template void MaterialLinearElastic4::add_pixel(const Ccoord_t & pixel, const Real & Young_modulus, const Real & Poisson_ratio) { this->internal_fields.add_pixel(pixel); // store the first(lambda) and second(mu) Lame constant in the field Real lambda = Hooke::compute_lambda(Young_modulus, Poisson_ratio); Real mu = Hooke::compute_mu(Young_modulus, Poisson_ratio); this->lambda_field.push_back(lambda); this->mu_field.push_back(mu); } template class MaterialLinearElastic4; template class MaterialLinearElastic4; template class MaterialLinearElastic4; } // namespace muSpectre diff --git a/src/materials/material_linear_elastic4.hh b/src/materials/material_linear_elastic4.hh index a4118d1..ea26731 100644 --- a/src/materials/material_linear_elastic4.hh +++ b/src/materials/material_linear_elastic4.hh @@ -1,209 +1,212 @@ /** * @file material_linear_elastic4.hh * * @author Richard Leute * * @date 15 March 2018 * * @brief linear elastic material with distribution of stiffness properties. * In difference to material_linear_elastic3 two Lame constants are * stored per pixel instead of the whole elastic matrix C. * Uses the MaterialMuSpectre facilities to keep it simple. * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC4_HH_ #define SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC4_HH_ #include "materials/material_linear_elastic1.hh" -#include "common/field.hh" -#include "common/tensor_algebra.hh" + +#include #include namespace muSpectre { template class MaterialLinearElastic4; /** * traits for objective linear elasticity with eigenstrain */ template struct MaterialMuSpectre_traits> { //! global field collection using GFieldCollection_t = typename MaterialBase::GFieldCollection_t; //! expected map type for strain fields using StrainMap_t = - MatrixFieldMap; + muGrid::MatrixFieldMap; //! expected map type for stress fields - using StressMap_t = MatrixFieldMap; + using StressMap_t = + muGrid::MatrixFieldMap; //! expected map type for tangent stiffness fields - using TangentMap_t = T4MatrixFieldMap; + using TangentMap_t = + muGrid::T4MatrixFieldMap; //! declare what type of strain measure your law takes as input constexpr static auto strain_measure{StrainMeasure::GreenLagrange}; //! declare what type of stress measure your law yields as output constexpr static auto stress_measure{StressMeasure::PK2}; //! local field_collections used for internals - using LFieldColl_t = LocalFieldCollection; + using LFieldColl_t = muGrid::LocalFieldCollection; //! local Lame constant type - using LLameConstantMap_t = ScalarFieldMap; + using LLameConstantMap_t = muGrid::ScalarFieldMap; //! elasticity without internal variables using InternalVariables = std::tuple; }; /** * implements objective linear elasticity with an eigenstrain per pixel */ template class MaterialLinearElastic4 : public MaterialMuSpectre, DimS, DimM> { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW //! base class using Parent = MaterialMuSpectre; /** * type used to determine whether the * `muSpectre::MaterialMuSpectre::iterable_proxy` evaluate only * stresses or also tangent stiffnesses */ using NeedTangent = typename Parent::NeedTangent; //! global field collection using Stiffness_t = Eigen::TensorFixedSize>; //! traits of this material using traits = MaterialMuSpectre_traits; //! Type of container used for storing eigenstrain using InternalVariables = typename traits::InternalVariables; //! Hooke's law implementation using Hooke = typename MatTB::Hooke; //! Default constructor MaterialLinearElastic4() = delete; //! Construct by name explicit MaterialLinearElastic4(std::string name); //! Copy constructor MaterialLinearElastic4(const MaterialLinearElastic4 & other) = delete; //! Move constructor MaterialLinearElastic4(MaterialLinearElastic4 && other) = delete; //! Destructor virtual ~MaterialLinearElastic4() = default; //! Copy assignment operator MaterialLinearElastic4 & operator=(const MaterialLinearElastic4 & other) = delete; //! Move assignment operator MaterialLinearElastic4 & operator=(MaterialLinearElastic4 && other) = delete; /** * evaluates second Piola-Kirchhoff stress given the Green-Lagrange * strain (or Cauchy stress if called with a small strain tensor), the first * Lame constant (lambda) and the second Lame constant (shear modulus/mu). */ template inline decltype(auto) evaluate_stress(s_t && E, const Real & lambda, const Real & mu); /** * evaluates both second Piola-Kirchhoff stress and stiffness given * the Green-Lagrange strain (or Cauchy stress and stiffness if * called with a small strain tensor), the first Lame constant (lambda) and * the second Lame constant (shear modulus/mu). */ template inline decltype(auto) evaluate_stress_tangent(s_t && E, const Real & lambda, const Real & mu); /** * return the empty internals tuple */ InternalVariables & get_internals() { return this->internal_variables; } /** * overload add_pixel to write into loacal stiffness tensor */ void add_pixel(const Ccoord_t & pixel) final; /** * overload add_pixel to write into local stiffness tensor */ - void add_pixel(const Ccoord_t & pixel, - const Real & Youngs_modulus, const Real & Poisson_ratio); + void add_pixel(const Ccoord_t & pixel, const Real & Youngs_modulus, + const Real & Poisson_ratio); protected: //! storage for first Lame constant 'lambda' //! and second Lame constant(shear modulus) 'mu' - using Field_t = MatrixField, Real, oneD, oneD>; + using Field_t = muGrid::MatrixField, + Real, oneD, oneD>; Field_t & lambda_field; Field_t & mu_field; //! tuple for iterable eigen_field InternalVariables internal_variables; private: }; /* ---------------------------------------------------------------------- */ template template auto MaterialLinearElastic4::evaluate_stress(s_t && E, const Real & lambda, const Real & mu) -> decltype(auto) { auto C = Hooke::compute_C_T4(lambda, mu); return Matrices::tensmult(C, E); } /* ---------------------------------------------------------------------- */ template template auto MaterialLinearElastic4::evaluate_stress_tangent( s_t && E, const Real & lambda, const Real & mu) -> decltype(auto) { - T4Mat C = Hooke::compute_C_T4(lambda, mu); + muGrid::T4Mat C = Hooke::compute_C_T4(lambda, mu); return std::make_tuple( this->evaluate_stress(std::forward(E), lambda, mu), C); } } // namespace muSpectre #endif // SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC4_HH_ diff --git a/src/materials/material_linear_elastic_generic1.cc b/src/materials/material_linear_elastic_generic1.cc index 5fd00b6..f46e3d0 100644 --- a/src/materials/material_linear_elastic_generic1.cc +++ b/src/materials/material_linear_elastic_generic1.cc @@ -1,74 +1,75 @@ /** * @file material_linear_elastic_generic1.cc * * @author Till Junge * * @date 21 Sep 2018 * * @brief implementation for MaterialLinearElasticGeneric * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "materials/material_linear_elastic_generic1.hh" #include "common/voigt_conversion.hh" namespace muSpectre { /* ---------------------------------------------------------------------- */ template MaterialLinearElasticGeneric1::MaterialLinearElasticGeneric1( const std::string & name, const CInput_t & C_voigt) - : Parent{name} { + : Parent{name} { + using muGrid::get; using VC_t = VoigtConversion; constexpr Dim_t VSize{vsize(DimM)}; if (not(C_voigt.rows() == VSize) or not(C_voigt.cols() == VSize)) { std::stringstream err_str{}; err_str << "The stiffness tensor should be input as a " << VSize << " × " << VSize << " Matrix in Voigt notation. You supplied" << " a " << C_voigt.rows() << " × " << C_voigt.cols() << " matrix"; } for (int i{0}; i < DimM; ++i) { for (int j{0}; j < DimM; ++j) { for (int k{0}; k < DimM; ++k) { for (int l{0}; l < DimM; ++l) { get(this->C, i, j, k, l) = C_voigt(VC_t::sym_mat(i, j), VC_t::sym_mat(k, l)); } } } } } /* ---------------------------------------------------------------------- */ template class MaterialLinearElasticGeneric1; template class MaterialLinearElasticGeneric1; template class MaterialLinearElasticGeneric1; } // namespace muSpectre diff --git a/src/materials/material_linear_elastic_generic1.hh b/src/materials/material_linear_elastic_generic1.hh index dc851d5..3855381 100644 --- a/src/materials/material_linear_elastic_generic1.hh +++ b/src/materials/material_linear_elastic_generic1.hh @@ -1,189 +1,190 @@ /** * @file material_linear_elastic_generic1.hh * * @author Till Junge * * @date 21 Sep 2018 * * @brief Implementation fo a generic linear elastic material that * stores the full elastic stiffness tensor. Convenient but not the * most efficient * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC_GENERIC1_HH_ #define SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC_GENERIC1_HH_ -#include "common/common.hh" +#include "common/muSpectre_common.hh" #include "materials/stress_transformations_PK2.hh" -#include "common/T4_map_proxy.hh" #include "materials/material_muSpectre_base.hh" -#include "common/tensor_algebra.hh" + +#include namespace muSpectre { /** * forward declaration */ template class MaterialLinearElasticGeneric1; /** * traits for use by MaterialMuSpectre for crtp */ template struct MaterialMuSpectre_traits> { //! global field collection using GFieldCollection_t = typename MaterialBase::GFieldCollection_t; //! expected map type for strain fields using StrainMap_t = - MatrixFieldMap; + muGrid::MatrixFieldMap; //! expected map type for stress fields - using StressMap_t = MatrixFieldMap; + using StressMap_t = + muGrid::MatrixFieldMap; //! expected map type for tangent stiffness fields - using TangentMap_t = T4MatrixFieldMap; + using TangentMap_t = + muGrid::T4MatrixFieldMap; //! declare what type of strain measure your law takes as input constexpr static auto strain_measure{StrainMeasure::GreenLagrange}; //! declare what type of stress measure your law yields as output constexpr static auto stress_measure{StressMeasure::PK2}; //! elasticity without internal variables using InternalVariables = std::tuple<>; }; /** * Linear elastic law defined by a full stiffness tensor. Very * generic, but not most efficient */ template class MaterialLinearElasticGeneric1 : public MaterialMuSpectre, DimS, DimM> { public: //! parent type using Parent = MaterialMuSpectre, DimS, DimM>; //! generic input tolerant to python input using CInput_t = Eigen::Ref, 0, Eigen::Stride>; using CVoigt_t = Eigen::Matrix; //! Default constructor MaterialLinearElasticGeneric1() = delete; /** * Constructor by name and stiffness tensor. * * @param name unique material name * @param C_voigt elastic tensor in Voigt notation */ MaterialLinearElasticGeneric1(const std::string & name, const CInput_t & C_voigt); //! Copy constructor MaterialLinearElasticGeneric1(const MaterialLinearElasticGeneric1 & other) = delete; //! Move constructor MaterialLinearElasticGeneric1(MaterialLinearElasticGeneric1 && other) = delete; //! Destructor virtual ~MaterialLinearElasticGeneric1() = default; //! Copy assignment operator MaterialLinearElasticGeneric1 & operator=(const MaterialLinearElasticGeneric1 & other) = delete; //! Move assignment operator MaterialLinearElasticGeneric1 & operator=(MaterialLinearElasticGeneric1 && other) = delete; //! see //! http://eigen.tuxfamily.org/dox/group__TopicStructHavingEigenMembers.html EIGEN_MAKE_ALIGNED_OPERATOR_NEW; /** * evaluates second Piola-Kirchhoff stress given the Green-Lagrange * strain (or Cauchy stress if called with a small strain tensor) */ template inline decltype(auto) evaluate_stress(const Eigen::MatrixBase & E); /** * evaluates both second Piola-Kirchhoff stress and stiffness given * the Green-Lagrange strain (or Cauchy stress and stiffness if * called with a small strain tensor) */ template inline decltype(auto) evaluate_stress_tangent(const Eigen::MatrixBase & E); /** * return the empty internals tuple */ std::tuple<> & get_internals() { return this->internal_variables; } /** * return a reference to the stiffness tensor */ - const T4Mat & get_C() const { return this->C; } + const muGrid::T4Mat & get_C() const { return this->C; } protected: - T4Mat C{}; //! stiffness tensor + muGrid::T4Mat C{}; //! stiffness tensor //! empty tuple std::tuple<> internal_variables{}; }; /* ---------------------------------------------------------------------- */ template template auto MaterialLinearElasticGeneric1::evaluate_stress( const Eigen::MatrixBase & E) -> decltype(auto) { static_assert(Derived::ColsAtCompileTime == DimM, "wrong input size"); static_assert(Derived::RowsAtCompileTime == DimM, "wrong input size"); return Matrices::tensmult(this->C, E); } /* ---------------------------------------------------------------------- */ template template auto MaterialLinearElasticGeneric1::evaluate_stress_tangent( const Eigen::MatrixBase & E) -> decltype(auto) { using Stress_t = decltype(this->evaluate_stress(E)); - using Stiffness_t = Eigen::Map>; + using Stiffness_t = Eigen::Map>; using Ret_t = std::tuple; - return Ret_t{this->evaluate_stress(E), - Stiffness_t(this->C.data())}; + return Ret_t{this->evaluate_stress(E), Stiffness_t(this->C.data())}; } } // namespace muSpectre #endif // SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC_GENERIC1_HH_ diff --git a/src/materials/material_linear_elastic_generic2.cc b/src/materials/material_linear_elastic_generic2.cc index fe22fb0..cce7a7f 100644 --- a/src/materials/material_linear_elastic_generic2.cc +++ b/src/materials/material_linear_elastic_generic2.cc @@ -1,68 +1,69 @@ /** * @file material_linear_elastic_generic2.cc * * @author Till Junge * * @date 20 Dec 2018 * * @brief Implementation for generic linear elastic law with eigenstrains * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "material_linear_elastic_generic2.hh" namespace muSpectre { /* ---------------------------------------------------------------------- */ template MaterialLinearElasticGeneric2::MaterialLinearElasticGeneric2( const std::string & name, const CInput_t & C_voigt) : Parent{name}, worker{name, C_voigt}, - eigen_field{make_field("Eigenstrain", this->internal_fields)}, + eigen_field{ + muGrid::make_field("Eigenstrain", this->internal_fields)}, internal_variables(eigen_field.get_const_map()) {} /* ---------------------------------------------------------------------- */ template void MaterialLinearElasticGeneric2::add_pixel( const Ccoord_t & /*pixel*/) { throw std::runtime_error("this material needs pixels with and eigenstrain"); } /* ---------------------------------------------------------------------- */ template void MaterialLinearElasticGeneric2::add_pixel( const Ccoord_t & pixel, const StrainTensor & E_eig) { this->internal_fields.add_pixel(pixel); Eigen::Map> strain_array( E_eig.data()); this->eigen_field.push_back(strain_array); } template class MaterialLinearElasticGeneric2; template class MaterialLinearElasticGeneric2; template class MaterialLinearElasticGeneric2; } // namespace muSpectre diff --git a/src/materials/material_linear_elastic_generic2.hh b/src/materials/material_linear_elastic_generic2.hh index 6690d08..22d2084 100644 --- a/src/materials/material_linear_elastic_generic2.hh +++ b/src/materials/material_linear_elastic_generic2.hh @@ -1,202 +1,207 @@ /** * @file material_linear_elastic_generic2.hh * * @author Till Junge * * @date 20 Dec 2018 * * @brief implementation of a generic linear elastic law with eigenstrains * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC_GENERIC2_HH_ #define SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC_GENERIC2_HH_ #include "material_linear_elastic_generic1.hh" namespace muSpectre { /** * forward declaration */ template class MaterialLinearElasticGeneric2; /** * traits for use by MaterialMuSpectre for crtp */ template struct MaterialMuSpectre_traits> { //! global field collection using GFieldCollection_t = typename MaterialBase::GFieldCollection_t; //! expected map type for strain fields using StrainMap_t = - MatrixFieldMap; + muGrid::MatrixFieldMap; //! expected map type for stress fields - using StressMap_t = MatrixFieldMap; + using StressMap_t = + muGrid::MatrixFieldMap; //! expected map type for tangent stiffness fields - using TangentMap_t = T4MatrixFieldMap; + using TangentMap_t = + muGrid::T4MatrixFieldMap; //! declare what type of strain measure your law takes as input constexpr static auto strain_measure{StrainMeasure::GreenLagrange}; //! declare what type of stress measure your law yields as output constexpr static auto stress_measure{StressMeasure::PK2}; //! local field_collections used for internals - using LFieldColl_t = LocalFieldCollection; + using LFieldColl_t = muGrid::LocalFieldCollection; //! local strain type - using LStrainMap_t = MatrixFieldMap; + using LStrainMap_t = + muGrid::MatrixFieldMap; //! elasticity with eigenstrain using InternalVariables = std::tuple; }; /** * Implementation proper of the class */ template class MaterialLinearElasticGeneric2 : public MaterialMuSpectre, DimS, DimM> { //! parent type using Parent = MaterialMuSpectre, DimS, DimM>; //! underlying worker class using Law_t = MaterialLinearElasticGeneric1; //! generic input tolerant to python input using CInput_t = typename Law_t::CInput_t; //! reference to any type that casts to a matrix using StrainTensor = Eigen::Ref>; //! traits of this material using traits = MaterialMuSpectre_traits; //! Type of container used for storing eigenstrain using InternalVariables_t = typename traits::InternalVariables; public: //! Default constructor MaterialLinearElasticGeneric2() = delete; //! Construct by name and elastic stiffness tensor MaterialLinearElasticGeneric2(const std::string & name, const CInput_t & C_voigt); //! Copy constructor MaterialLinearElasticGeneric2(const MaterialLinearElasticGeneric2 & other) = delete; //! Move constructor MaterialLinearElasticGeneric2(MaterialLinearElasticGeneric2 && other) = default; //! Destructor virtual ~MaterialLinearElasticGeneric2() = default; //! Copy assignment operator MaterialLinearElasticGeneric2 & operator=(const MaterialLinearElasticGeneric2 & other) = delete; //! Move assignment operator MaterialLinearElasticGeneric2 & operator=(MaterialLinearElasticGeneric2 && other) = default; //! see //! http://eigen.tuxfamily.org/dox/group__TopicStructHavingEigenMembers.html EIGEN_MAKE_ALIGNED_OPERATOR_NEW; /** * evaluates second Piola-Kirchhoff stress given the Green-Lagrange * strain (or Cauchy stress if called with a small strain tensor) */ template inline decltype(auto) evaluate_stress(const Eigen::MatrixBase & E, const Eigen::MatrixBase & E_eig); /** * evaluates both second Piola-Kirchhoff stress and stiffness given * the Green-Lagrange strain (or Cauchy stress and stiffness if * called with a small strain tensor) */ template inline decltype(auto) evaluate_stress_tangent(const Eigen::MatrixBase & E, const Eigen::MatrixBase & E_eig); /** * returns tuple with only the eigenstrain field */ InternalVariables_t & get_internals() { return this->internal_variables; } /** * return a reference to the stiffness tensor */ - const T4Mat & get_C() const { return this->worker.get_C(); } + const muGrid::T4Mat & get_C() const { + return this->worker.get_C(); + } /** * overload add_pixel to write into eigenstrain */ void add_pixel(const Ccoord_t & pixel) final; /** * overload add_pixel to write into eigenstrain */ void add_pixel(const Ccoord_t & pixel, const StrainTensor & E_eig); protected: Law_t worker; //! underlying law to be evaluated //! storage for eigenstrain - using Field_t = - TensorField, Real, secondOrder, DimM>; + using Field_t = muGrid::TensorField, + Real, secondOrder, DimM>; Field_t & eigen_field; //!< field holding the eigen strain per pixel InternalVariables_t internal_variables; }; /* ---------------------------------------------------------------------- */ template template auto MaterialLinearElasticGeneric2::evaluate_stress( const Eigen::MatrixBase & E, const Eigen::MatrixBase & E_eig) -> decltype(auto) { return this->worker.evaluate_stress(E - E_eig); } /* ---------------------------------------------------------------------- */ template template auto MaterialLinearElasticGeneric2::evaluate_stress_tangent( const Eigen::MatrixBase & E, const Eigen::MatrixBase & E_eig) -> decltype(auto) { return this->worker.evaluate_stress_tangent(E - E_eig); } } // namespace muSpectre #endif // SRC_MATERIALS_MATERIAL_LINEAR_ELASTIC_GENERIC2_HH_ diff --git a/src/materials/material_muSpectre_base.hh b/src/materials/material_muSpectre_base.hh index 99568c8..b8a08cb 100644 --- a/src/materials/material_muSpectre_base.hh +++ b/src/materials/material_muSpectre_base.hh @@ -1,1019 +1,1018 @@ /** * @file material_muSpectre_base.hh * * @author Till Junge * * @date 25 Oct 2017 * * @brief Base class for materials written for µSpectre specifically. These * can take full advantage of the configuration-change utilities of * µSpectre. The user can inherit from them to define new constitutive * laws and is merely required to provide the methods for computing the * second Piola-Kirchhoff stress and Tangent. This class uses the * "curiously recurring template parameter" to avoid virtual calls. * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_MATERIALS_MATERIAL_MUSPECTRE_BASE_HH_ #define SRC_MATERIALS_MATERIAL_MUSPECTRE_BASE_HH_ -#include "common/common.hh" +#include "common/muSpectre_common.hh" #include "materials/material_base.hh" #include "materials/materials_toolbox.hh" #include "laminate_homogenisation.hh" #include "materials/material_evaluator.hh" -#include "common/field_collection.hh" -#include "common/field.hh" -#include "common//utilities.hh" -#include "common/geometry.hh" + +#include +#include #include #include #include #include namespace muSpectre { // Forward declaration for factory function template class CellBase; /** * material traits are used by `muSpectre::MaterialMuSpectre` to * break the circular dependence created by the curiously recurring * template parameter. These traits must define * - these `muSpectre::FieldMap`s: * - `StrainMap_t`: typically a `muSpectre::MatrixFieldMap` for a * constant second-order `muSpectre::TensorField` * - `StressMap_t`: typically a `muSpectre::MatrixFieldMap` for a * writable secord-order `muSpectre::TensorField` * - `TangentMap_t`: typically a `muSpectre::T4MatrixFieldMap` for a * writable fourth-order `muSpectre::TensorField` * - `strain_measure`: the expected strain type (will be replaced by the * small-strain tensor ε * `muspectre::StrainMeasure::Infinitesimal` in small * strain computations) * - `stress_measure`: the measure of the returned stress. Is used by * `muspectre::MaterialMuSpectre` to transform it into * Cauchy stress (`muspectre::StressMeasure::Cauchy`) in * small-strain computations and into first * Piola-Kirchhoff stress `muspectre::StressMeasure::PK1` * in finite-strain computations * - `InternalVariables`: a tuple of `muSpectre::FieldMap`s containing * internal variables */ template struct MaterialMuSpectre_traits {}; template class MaterialMuSpectre; /** * Base class for most convenient implementation of materials */ template class MaterialMuSpectre : public MaterialBase { public: /** * type used to determine whether the * `muSpectre::MaterialMuSpectre::iterable_proxy evaluate only * stresses or also tangent stiffnesses */ using NeedTangent = MatTB::NeedTangent; using Parent = MaterialBase; //!< base class //! global field collection using GFieldCollection_t = typename Parent::GFieldCollection_t; //! expected type for stress fields using StressField_t = typename Parent::StressField_t; //! expected type for strain fields using StrainField_t = typename Parent::StrainField_t; //! expected type for tangent stiffness fields using TangentField_t = typename Parent::TangentField_t; using Ccoord = Ccoord_t; //!< cell coordinates type //! traits for the CRTP subclass using traits = MaterialMuSpectre_traits; // ! expected type to save stress tensor of the pixels of a certian material using LocalStressField_t = typename Parent::LocalStressField_t; // ! expected type to save stiffness ~ of the pixels of a certian material using LcoalTangentField_t = typename Parent::LocalTangentField_t; //! Default constructor MaterialMuSpectre() = delete; //! Construct by name explicit MaterialMuSpectre(std::string name); //! Copy constructor MaterialMuSpectre(const MaterialMuSpectre & other) = delete; //! Move constructor MaterialMuSpectre(MaterialMuSpectre && other) = delete; //! Destructor virtual ~MaterialMuSpectre() = default; //! Factory template static Material & make(CellBase & cell, ConstructorArgs &&... args); /** Factory * takes all arguments after the name of the underlying * Material's constructor. E.g., if the underlying material is a * `muSpectre::MaterialLinearElastic1`, these would be Young's * modulus and Poisson's ratio. */ template static std::tuple, MaterialEvaluator> make_evaluator(ConstructorArgs &&... args); //! Copy assignment operator MaterialMuSpectre & operator=(const MaterialMuSpectre & other) = delete; //! Move assignment operator MaterialMuSpectre & operator=(MaterialMuSpectre && other) = delete; //! allocate memory, etc void initialise() override; // this fucntion is speicalized to assign partial material to a pixel // void add_pixel_split(const Ccoord & local_ccoord, Real ratio = 1.0); template void add_pixel_split(const Ccoord_t & pixel, Real ratio, InternalArgs... args); void add_pixel_split(const Ccoord_t & pixel, Real ratio = 1.0) override; // add pixels intersecting to material to the material void add_split_pixels_precipitate(std::vector> intersected_pixles, std::vector intersection_ratios); //! computes stress using Parent::compute_stresses; using Parent::compute_stresses_tangent; void compute_stresses(const StrainField_t & F, StressField_t & P, Formulation form, SplitCell is_cell_split) final; //! computes stress and tangent modulus void compute_stresses_tangent(const StrainField_t & F, StressField_t & P, TangentField_t & K, Formulation form, SplitCell is_cell_split) override; protected: //! computes stress with the formulation available at compile time //! __attribute__ required by g++-6 and g++-7 because of this bug: //! https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80947 template inline void compute_stresses_worker(const StrainField_t & F, StressField_t & P) __attribute__((visibility("default"))); //! computes stress with the formulation available at compile time //! __attribute__ required by g++-6 and g++-7 because of this bug: //! https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80947 template inline void compute_stresses_worker(const StrainField_t & F, StressField_t & P, TangentField_t & K) __attribute__((visibility("default"))); //! this iterable class is a default for simple laws that just take a strain //! the iterable is just a templated wrapper to provide a range to iterate //! over that does or does not include tangent moduli template class iterable_proxy; /** * inheriting classes need to overload this function */ typename traits::InternalVariables & get_internals() { return static_cast(*this).get_internals(); } bool is_initialised{false}; //!< to handle double initialisation right private: }; /* ---------------------------------------------------------------------- */ template MaterialMuSpectre::MaterialMuSpectre(std::string name) : Parent(name) { using stress_compatible = typename traits::StressMap_t::template is_compatible; using strain_compatible = typename traits::StrainMap_t::template is_compatible; using tangent_compatible = typename traits::TangentMap_t::template is_compatible; static_assert((stress_compatible::value && stress_compatible::explain()), "The material's declared stress map is not compatible " "with the stress field. More info in previously shown " "assert."); static_assert((strain_compatible::value && strain_compatible::explain()), "The material's declared strain map is not compatible " "with the strain field. More info in previously shown " "assert."); static_assert((tangent_compatible::value && tangent_compatible::explain()), "The material's declared tangent map is not compatible " "with the tangent field. More info in previously shown " "assert."); } /* ---------------------------------------------------------------------- */ template template Material & MaterialMuSpectre::make(CellBase & cell, ConstructorArgs &&... args) { auto mat = std::make_unique(args...); auto & mat_ref = *mat; mat_ref.allocate_optional_fields(cell.get_splitness()); cell.add_material(std::move(mat)); return mat_ref; } /* ---------------------------------------------------------------------- */ template void MaterialMuSpectre::add_pixel_split( const Ccoord & local_ccoord, Real ratio) { auto & this_mat = static_cast(*this); this_mat.add_pixel(local_ccoord); this->assigned_ratio.value().get().push_back(ratio); } /* ---------------------------------------------------------------------- */ template template void MaterialMuSpectre::add_pixel_split( const Ccoord_t & pixel, Real ratio, InternalArgs... args) { auto & this_mat = static_cast(*this); this_mat.add_pixel(pixel, args...); this->assigned_ratio.value().get().push_back(ratio); } /* ---------------------------------------------------------------------- */ template void MaterialMuSpectre::add_split_pixels_precipitate( std::vector> intersected_pixels, std::vector intersection_ratios) { // assign precipitate materials: for (auto && tup : akantu::zip(intersected_pixels, intersection_ratios)) { auto pix = std::get<0>(tup); auto ratio = std::get<1>(tup); this->add_pixel_split(pix, ratio); } } template template std::tuple, MaterialEvaluator> MaterialMuSpectre::make_evaluator( ConstructorArgs &&... args) { auto mat = std::make_shared("name", args...); using Ret_t = std::tuple, MaterialEvaluator>; return Ret_t(mat, MaterialEvaluator{mat}); } /* ---------------------------------------------------------------------- */ template void MaterialMuSpectre::initialise() { if (!this->is_initialised) { this->internal_fields.initialise(); this->is_initialised = true; } } /* ---------------------------------------------------------------------- */ template void MaterialMuSpectre::compute_stresses( const StrainField_t & F, StressField_t & P, Formulation form, SplitCell is_cell_split) { switch (form) { case Formulation::finite_strain: { switch (is_cell_split) { case (SplitCell::no): { this->compute_stresses_worker(F, P); break; } case (SplitCell::simple): { this->compute_stresses_worker(F, P); break; } case (SplitCell::laminate): { this->compute_stresses_worker(F, P); break; } default: throw std::runtime_error("Unknown Splitness status"); } break; } case Formulation::small_strain: { switch (is_cell_split) { case (SplitCell::no): { this->compute_stresses_worker( F, P); break; } case (SplitCell::simple): { this->compute_stresses_worker(F, P); break; } case (SplitCell::laminate): { this->compute_stresses_worker(F, P); break; } default: throw std::runtime_error("Unknown Splitness status"); } break; } default: throw std::runtime_error("Unknown formulation"); break; } } /* ---------------------------------------------------------------------- */ template void MaterialMuSpectre:: compute_stresses_tangent(const StrainField_t & F, StressField_t & P, TangentField_t & K, Formulation form, SplitCell is_cell_split) { switch (form) { case Formulation::finite_strain: { switch (is_cell_split) { case (SplitCell::no): { this->compute_stresses_worker(F, P, K); break; } case (SplitCell::simple): { this->compute_stresses_worker(F, P, K); break; } case (SplitCell::laminate): { this->compute_stresses_worker(F, P, K); break; } default: throw std::runtime_error("Unknown Splitness status"); } break; } case Formulation::small_strain: { switch (is_cell_split) { case (SplitCell::no): { this->compute_stresses_worker( F, P, K); break; } case (SplitCell::simple): { this->compute_stresses_worker(F, P, K); break; } case (SplitCell::laminate): { this->compute_stresses_worker(F, P, K); break; } default: throw std::runtime_error("Unknown Splitness status"); } break; } default: throw std::runtime_error("Unknown formulation"); break; } } /* ---------------------------------------------------------------------- */ template template void MaterialMuSpectre::compute_stresses_worker( const StrainField_t & F, StressField_t & P, TangentField_t & K) { /* These lambdas are executed for every integration point. F contains the transformation gradient for finite strain calculations and the infinitesimal strain tensor in small strain problems The internal_variables tuple contains whatever internal variables Material declared (e.g., eigenstrain, strain rate, etc.) */ using Strains_t = std::tuple; using Stresses_t = std::tuple; auto constitutive_law_small_strain = [this](Strains_t Strains, Stresses_t Stresses, const Real & ratio, auto && internal_variables) { constexpr StrainMeasure stored_strain_m{get_stored_strain_type(Form)}; constexpr StrainMeasure expected_strain_m{ get_formulation_strain_type(Form, traits::strain_measure)}; auto & this_mat = static_cast(*this); // Transformation gradient is first in the strains tuple auto & grad = std::get<0>(Strains); auto && strain = MatTB::convert_strain(grad); // return value contains a tuple of rvalue_refs to both stress and // tangent moduli // for the case that pixels are not split auto non_split_pixel = [&strain, &this_mat, ratio, &Stresses, &internal_variables]() { Stresses = apply( [&strain, &this_mat](auto &&... internals) { return this_mat.evaluate_stress_tangent(std::move(strain), internals...); }, internal_variables); }; // for the case that pixels are split auto split_pixel = [&strain, &this_mat, ratio, &Stresses, &internal_variables]() { auto stress_tgt_contributions = apply( [&strain, &this_mat](auto &&... internals) { return this_mat.evaluate_stress_tangent(std::move(strain), internals...); }, internal_variables); auto && stress = std::get<0>(Stresses); auto && tangent = std::get<1>(Stresses); stress += ratio * std::get<0>(stress_tgt_contributions); tangent += ratio * std::get<1>(stress_tgt_contributions); }; auto laminate_pixel = []() {}; switch (is_cell_split) { case SplitCell::no: { non_split_pixel(); break; } case SplitCell::simple: { split_pixel(); break; } case SplitCell::laminate: { laminate_pixel(); break; } } }; auto constitutive_law_finite_strain = [this](Strains_t Strains, Stresses_t Stresses, const Real & ratio, auto && internal_variables) { constexpr StrainMeasure stored_strain_m{get_stored_strain_type(Form)}; constexpr StrainMeasure expected_strain_m{ get_formulation_strain_type(Form, traits::strain_measure)}; auto & this_mat = static_cast(*this); // Transformation gradient is first in the strains tuple auto & grad = std::get<0>(Strains); auto && strain = MatTB::convert_strain(grad); // return value contains a tuple of rvalue_refs to both stress // and tangent moduli // for the case that cells do not contain splitt cells auto non_split_pixel = [&strain, &this_mat, ratio, &Stresses, &internal_variables, &grad]() { auto stress_tgt = apply([&strain, &this_mat] (auto && ... internals) { return this_mat.evaluate_stress_tangent(std::move(strain), internals...);}, internal_variables); auto & stress = std::get<0>(stress_tgt); auto & tangent = std::get<1>(stress_tgt); Stresses = MatTB::PK1_stress( std::move(grad), std::move(stress), std::move(tangent)); }; // for the case that cells contain splitt cells auto split_pixel = [&strain, &this_mat, ratio, &Stresses, &internal_variables, &grad]() { auto stress_tgt = apply( [&strain, &this_mat](auto &&... internals) { return this_mat.evaluate_stress_tangent(std::move(strain), internals...); }, internal_variables); auto && stress_tgt_contributions = MatTB::PK1_stress( std::move(grad), std::move(std::get<0>(stress_tgt)), std::move(std::get<1>(stress_tgt))); auto && stress = std::get<0>(Stresses); auto && tangent = std::get<1>(Stresses); stress += ratio * std::get<0>(stress_tgt_contributions); tangent += ratio * std::get<1>(stress_tgt_contributions); }; auto laminate_pixel = [&strain, &this_mat, ratio, &Stresses, &internal_variables, &grad]() { auto stress_tgt = apply( [&strain, &this_mat](auto &&... internals) { return this_mat.evaluate_stress_tangent(std::move(strain), internals...); }, internal_variables); auto && stress_tgt_contributions = MatTB::PK1_stress( std::move(grad), std::move(std::get<0>(stress_tgt)), std::move(std::get<1>(stress_tgt))); auto && stress = std::get<0>(Stresses); auto && tangent = std::get<1>(Stresses); stress += ratio * std::get<0>(stress_tgt_contributions); tangent += ratio * std::get<1>(stress_tgt_contributions); }; switch (is_cell_split) { case SplitCell::no: { non_split_pixel(); break; } case SplitCell::simple: { split_pixel(); break; } case SplitCell::laminate: { laminate_pixel(); break; } } }; iterable_proxy fields{*this, F, P, K}; for (auto && arglist : fields) { /** * arglist is a tuple of three tuples containing only Lvalue * references (see value_tye in the class definition of * iterable_proxy::iterator). Tuples contain strains, stresses * and internal variables, respectively, */ // auto && stress_tgt = std::get<0>(tuples); // auto && inputs = std::get<1>(tuples);TODO:clean this static_assert(std::is_same( std::get<0>(arglist)))>>::value, "Type mismatch for strain reference, check iterator " "value_type"); static_assert(std::is_same( std::get<1>(arglist)))>>::value, "Type mismatch for stress reference, check iterator" "value_type"); static_assert(std::is_same( std::get<1>(arglist)))>>::value, "Type mismatch for tangent reference, check iterator" "value_type"); static_assert( std::is_same(arglist))>>::value, "Type mismatch for ratio reference, expected a real number"); switch (Form) { case Formulation::small_strain: { apply(constitutive_law_small_strain, std::move(arglist)); break; } case Formulation::finite_strain: { apply(constitutive_law_finite_strain, std::move(arglist)); break; } } } } /* ---------------------------------------------------------------------- */ template template void MaterialMuSpectre::compute_stresses_worker( const StrainField_t & F, StressField_t & P) { /* These lambdas are executed for every integration point. F contains the transformation gradient for finite strain calculations and the infinitesimal strain tensor in small strain problems The internal_variables tuple contains whatever internal variables Material declared (e.g., eigenstrain, strain rate, etc.) */ using Strains_t = std::tuple; using Stresses_t = std::tuple; auto constitutive_law_small_strain = [this](Strains_t Strains, Stresses_t Stresses, const Real & ratio, auto && internal_variables) { constexpr StrainMeasure stored_strain_m{get_stored_strain_type(Form)}; constexpr StrainMeasure expected_strain_m{ get_formulation_strain_type(Form, traits::strain_measure)}; auto & this_mat = static_cast(*this); // Transformation gradient is first in the strains tuple auto & grad = std::get<0>(Strains); auto && strain = MatTB::convert_strain(grad); // return value contains a tuple of rvalue_refs to both stress and tangent // moduli auto & sigma = std::get<0>(Stresses); // for the case that cell does not contain any split pixel auto non_split_pixel = [&strain, &this_mat, ratio, &sigma, &internal_variables]() { sigma = apply( [&strain, &this_mat](auto &&... internals) { return this_mat.evaluate_stress(std::move(strain), internals...); }, internal_variables); }; // for the case that cells contain splitt cells auto split_pixel = [&strain, &this_mat, &ratio, &sigma, &internal_variables]() { sigma += ratio * apply( [&strain, &this_mat](auto &&... internals) { return this_mat.evaluate_stress( std::move(strain), internals...); }, internal_variables); }; auto lamiante_pixel = []() {}; switch (is_cell_split) { case SplitCell::no: { non_split_pixel(); break; } case SplitCell::simple: { split_pixel(); break; } case SplitCell::laminate: { lamiante_pixel(); break; } } }; auto constitutive_law_finite_strain = [this](Strains_t Strains, Stresses_t && Stresses, const Real & ratio, auto && internal_variables) { constexpr StrainMeasure stored_strain_m{get_stored_strain_type(Form)}; constexpr StrainMeasure expected_strain_m{ get_formulation_strain_type(Form, traits::strain_measure)}; auto & this_mat = static_cast(*this); // Transformation gradient is first in the strains tuple auto & grad = std::get<0>(Strains); auto && strain = MatTB::convert_strain(grad); // TODO(junge): Figure this out: I can't std::move(internals...), // because if there are no internals, compilation fails with "no // matching function for call to ‘move()’'. These are tuples of // lvalue references, so it shouldn't be too bad, but still // irksome. // for the case that cell does not contain any split pixel auto non_split_pixel = [&strain, &this_mat, &ratio, &Stresses, &internal_variables, &grad]() { auto stress = apply( [&strain, &this_mat](auto &&... internals) { return this_mat.evaluate_stress(std::move(strain), internals...); }, internal_variables); - auto & P = get<0>(Stresses); + auto & P = std::get<0>(Stresses); P = MatTB::PK1_stress( grad, stress); }; // for the case that cells contain split cells auto split_pixel = [&strain, &this_mat, ratio, &Stresses, &internal_variables, &grad]() { auto stress = apply( [&strain, &this_mat](auto &&... internals) { return this_mat.evaluate_stress(std::move(strain), internals...); }, internal_variables); - auto && P = get<0>(Stresses); + auto && P = std::get<0>(Stresses); P += ratio * MatTB::PK1_stress( grad, stress); }; auto laminate_pixel = [&strain, &this_mat, ratio, &Stresses, internal_variables, &grad]() {}; switch (is_cell_split) { case SplitCell::no: { non_split_pixel(); break; } case SplitCell::simple: { split_pixel(); break; } case SplitCell::laminate: { laminate_pixel(); break; } } }; iterable_proxy fields{*this, F, P}; for (auto && arglist : fields) { /** * arglist is a tuple of three tuples containing only Lvalue * references (see value_type in the class definition of * iterable_proxy::iterator). Tuples contain strains, stresses * and internal variables, respectively, */ // auto && stress_tgt = std::get<0>(tuples); // auto && inputs = std::get<1>(tuples);TODO:clean this static_assert(std::is_same( std::get<0>(arglist)))>>::value, "Type mismatch for strain reference, check iterator " "value_type"); static_assert(std::is_same( std::get<1>(arglist)))>>::value, "Type mismatch for stress reference, check iterator" "value_type"); static_assert( std::is_same(arglist))>>::value, "Type mismatch for ratio reference, expected a real number"); switch (Form) { case Formulation::small_strain: { apply(constitutive_law_small_strain, std::move(arglist)); break; } case Formulation::finite_strain: { apply(constitutive_law_finite_strain, std::move(arglist)); break; } } } } /* ---------------------------------------------------------------------- */ //! this iterator class is a default for simple laws that just take a strain template template class MaterialMuSpectre::iterable_proxy { public: //! Default constructor iterable_proxy() = delete; /** * type used to determine whether the * `muSpectre::MaterialMuSpectre::iterable_proxy` evaluate only * stresses or also tangent stiffnesses */ using NeedTangent = typename MaterialMuSpectre::NeedTangent; /** Iterator uses the material's internal variables field collection to iterate selectively over the global fields (such as the transformation gradient F and first Piola-Kirchhoff stress P. **/ template iterable_proxy(MaterialMuSpectre & mat, const StrainField_t & F, StressField_t & P, std::enable_if_t & K) : material{mat}, strain_field{F}, stress_tup{P, K}, internals{material.get_internals()} {}; /** Iterator uses the material's internal variables field collection to iterate selectively over the global fields (such as the transformation gradient F and first Piola-Kirchhoff stress P. **/ template iterable_proxy(MaterialMuSpectre & mat, const StrainField_t & F, std::enable_if_t & P) : material{mat}, strain_field{F}, stress_tup{P}, internals{material.get_internals()} {}; //! Expected type for strain fields using StrainMap_t = typename traits::StrainMap_t; //! Expected type for stress fields using StressMap_t = typename traits::StressMap_t; //! Expected type for tangent stiffness fields using TangentMap_t = typename traits::TangentMap_t; //! expected type for strain values using Strain_t = typename traits::StrainMap_t::reference; //! expected type for stress values using Stress_t = typename traits::StressMap_t::reference; //! expected type for tangent stiffness values using Tangent_t = typename traits::TangentMap_t::reference; //! tuple of intervnal variables, depends on the material using InternalVariables = typename traits::InternalVariables; //! tuple containing a stress and possibly a tangent stiffness field using StressFieldTup = std::conditional_t<(NeedTgt == NeedTangent::yes), std::tuple, std::tuple>; //! tuple containing a stress and possibly a tangent stiffness field map using StressMapTup = std::conditional_t<(NeedTgt == NeedTangent::yes), std::tuple, std::tuple>; //! tuple containing a stress and possibly a tangent stiffness value ref using Stress_tTup = std::conditional_t<(NeedTgt == NeedTangent::yes), std::tuple, std::tuple>; //! Copy constructor iterable_proxy(const iterable_proxy & other) = default; //! Move constructor iterable_proxy(iterable_proxy && other) = default; //! Destructor virtual ~iterable_proxy() = default; //! Copy assignment operator iterable_proxy & operator=(const iterable_proxy & other) = default; //! Move assignment operator iterable_proxy & operator=(iterable_proxy && other) = default; /** * dereferences into a tuple containing strains, and internal * variables, as well as maps to the stress and potentially * stiffness maps where to write the response of a pixel */ class iterator { public: //! type to refer to internal variables owned by a CRTP material using InternalReferences = MatTB::ReferenceTuple_t; //! return type to be unpacked per pixel my the constitutive law using value_type = std::tuple, Stress_tTup, Real, InternalReferences>; using iterator_category = std::forward_iterator_tag; //!< stl conformance //! Default constructor iterator() = delete; /** Iterator uses the material's internal variables field collection to iterate selectively over the global fields (such as the transformation gradient F and first Piola-Kirchhoff stress P. **/ explicit iterator(const iterable_proxy & it, bool begin = true) : it{it}, strain_map{it.strain_field}, stress_map(it.stress_tup), index{begin ? 0 : it.material.internal_fields.size()} {} //! Copy constructor iterator(const iterator & other) = default; //! Move constructor iterator(iterator && other) = default; //! Destructor virtual ~iterator() = default; //! Copy assignment operator iterator & operator=(const iterator & other) = default; //! Move assignment operator iterator & operator=(iterator && other) = default; //! pre-increment inline iterator & operator++(); //! dereference inline value_type operator*(); //! inequality inline bool operator!=(const iterator & other) const; protected: const iterable_proxy & it; //!< ref to the proxy StrainMap_t strain_map; //!< map onto the global strain field //! map onto the global stress field and possibly tangent stiffness StressMapTup stress_map; size_t index; //!< index or pixel currently referred to }; //! returns iterator to first pixel if this material iterator begin() { return std::move(iterator(*this)); } //! returns iterator past the last pixel in this material iterator end() { return std::move(iterator(*this, false)); } protected: MaterialMuSpectre & material; //!< reference to the proxied material const StrainField_t & strain_field; //!< cell's global strain field //! references to the global stress field and perhaps tangent stiffness StressFieldTup stress_tup; //! references to the internal variables InternalVariables & internals; private: }; /* ---------------------------------------------------------------------- */ template template bool MaterialMuSpectre::iterable_proxy::iterator:: operator!=(const iterator & other) const { return (this->index != other.index); } /* ---------------------------------------------------------------------- */ template template typename MaterialMuSpectre::template iterable_proxy< NeedTgt, is_cell_split>::iterator & MaterialMuSpectre::iterable_proxy::iterator:: operator++() { this->index++; return *this; } /* ---------------------------------------------------------------------- */ template template typename MaterialMuSpectre::template iterable_proxy< NeedTgT, is_cell_split>::iterator::value_type MaterialMuSpectre::iterable_proxy< NeedTgT, is_cell_split>::iterator::operator*() { const Ccoord_t pixel{ this->it.material.internal_fields.get_ccoord(this->index)}; auto && strain = std::make_tuple(this->strain_map[pixel]); auto && ratio = 1.0; if (is_cell_split != SplitCell::no) { ratio = this->it.material.get_assigned_ratio(pixel); } auto && stresses = apply( [&pixel](auto &&... stress_tgt) { return std::make_tuple(stress_tgt[pixel]...); }, this->stress_map); auto && internal = this->it.material.get_internals(); const auto id{this->index}; auto && internals = apply( [id](auto &&... internals_) { return InternalReferences{internals_[id]...}; }, internal); return std::make_tuple(std::move(strain), std::move(stresses), std::move(ratio), std::move(internals)); } } // namespace muSpectre #endif // SRC_MATERIALS_MATERIAL_MUSPECTRE_BASE_HH_ diff --git a/src/materials/materials_toolbox.hh b/src/materials/materials_toolbox.hh index 0cfb90e..5e36325 100644 --- a/src/materials/materials_toolbox.hh +++ b/src/materials/materials_toolbox.hh @@ -1,603 +1,603 @@ /** * @file materials_toolbox.hh * * @author Till Junge * * @date 02 Nov 2017 * * @brief collection of common continuum mechanics tools * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_MATERIALS_MATERIALS_TOOLBOX_HH_ #define SRC_MATERIALS_MATERIALS_TOOLBOX_HH_ -#include "common/common.hh" -#include "common/tensor_algebra.hh" -#include "common/eigen_tools.hh" -#include "common/T4_map_proxy.hh" -#include "stress_transformations_PK1.hh" +#include "common/muSpectre_common.hh" + +#include +#include +#include #include #include #include #include #include #include #include namespace muSpectre { namespace MatTB { /** * thrown when generic materials-related runtime errors occur * (mostly continuum mechanics problems) */ class MaterialsToolboxError : public std::runtime_error { public: //! constructor explicit MaterialsToolboxError(const std::string & what) : std::runtime_error(what) {} //! constructor explicit MaterialsToolboxError(const char * what) : std::runtime_error(what) {} }; /* ---------------------------------------------------------------------- */ /** * Flag used to designate whether the material should compute both stress * and tangent moduli or only stress */ enum class NeedTangent { yes, //!< compute both stress and tangent moduli no //!< compute only stress }; /** * struct used to determine the exact type of a tuple of references obtained * when a bunch of iterators over fiel_maps are dereferenced and their * results are concatenated into a tuple */ template struct ReferenceTuple { //! use this type using type = std::tuple; }; /** * specialisation for tuples */ // template <> template struct ReferenceTuple> { //! use this type using type = typename ReferenceTuple::type; }; /** * helper type for ReferenceTuple */ template using ReferenceTuple_t = typename ReferenceTuple::type; /* ---------------------------------------------------------------------- */ namespace internal { /** Structure for functions returning one strain measure as a * function of another **/ template struct ConvertStrain { static_assert((In == StrainMeasure::Gradient) || (In == StrainMeasure::Infinitesimal), "This situation makes me suspect that you are not using " "MatTb as intended. Disable this assert only if you are " "sure about what you are doing."); //! returns the converted strain template inline static decltype(auto) compute(Strain_t && input) { // transparent case, in which no conversion is required: // just a perfect forwarding static_assert((In == Out), "This particular strain conversion is not implemented"); return std::forward(input); } }; /* ---------------------------------------------------------------------- */ /** Specialisation for getting Green-Lagrange strain from the transformation gradient E = ¹/₂ (C - I) = ¹/₂ (Fᵀ·F - I) **/ template <> struct ConvertStrain { //! returns the converted strain template inline static decltype(auto) compute(Strain_t && F) { return .5 * (F.transpose() * F - Strain_t::PlainObject::Identity()); } }; /* ---------------------------------------------------------------------- */ /** Specialisation for getting Left Cauchy-Green strain from the transformation gradient B = F·Fᵀ = V² **/ template <> struct ConvertStrain { //! returns the converted strain template inline static decltype(auto) compute(Strain_t && F) { return F * F.transpose(); } }; /* ---------------------------------------------------------------------- */ /** Specialisation for getting Right Cauchy-Green strain from the transformation gradient C = Fᵀ·F = U² **/ template <> struct ConvertStrain { //! returns the converted strain template inline static decltype(auto) compute(Strain_t && F) { return F.transpose() * F; } }; /* ---------------------------------------------------------------------- */ /** Specialisation for getting logarithmic (Hencky) strain from the transformation gradient E₀ = ¹/₂ ln C = ¹/₂ ln (Fᵀ·F) **/ template <> struct ConvertStrain { //! returns the converted strain template inline static decltype(auto) compute(Strain_t && F) { - constexpr Dim_t dim{EigenCheck::tensor_dim::value}; - return (.5 * logm(Eigen::Matrix{F.transpose() * F})) + constexpr Dim_t dim{muGrid::EigenCheck::tensor_dim::value}; + return (.5 * muGrid::logm( + Eigen::Matrix{F.transpose() * F})) .eval(); } }; } // namespace internal /* ---------------------------------------------------------------------- */ //! set of functions returning one strain measure as a function of //! another template decltype(auto) convert_strain(Strain_t && strain) { return internal::ConvertStrain::compute(std::move(strain)); } namespace internal { //! Base template for elastic modulus conversion template struct Converter { //! wrapped function (raison d'être) inline constexpr static Real compute(const Real & /*in1*/, const Real & /*in2*/) { // if no return has happened until now, the conversion is not // implemented yet static_assert( (In1 == In2), "This conversion has not been implemented yet, please add " "it here below as a specialisation of this function " "template. Check " "https://en.wikipedia.org/wiki/Lam%C3%A9_parameters for " "the formula."); return 0; } }; /** * Spectialisation for when the output is the first input */ template struct Converter { //! wrapped function (raison d'être) inline constexpr static Real compute(const Real & A, const Real & /*B*/) { return A; } }; /** * Spectialisation for when the output is the second input */ template struct Converter { //! wrapped function (raison d'être) inline constexpr static Real compute(const Real & /*A*/, const Real & B) { return B; } }; /** * Specialisation μ(E, ν) */ template <> struct Converter { //! wrapped function (raison d'être) inline constexpr static Real compute(const Real & E, const Real & nu) { return E / (2 * (1 + nu)); } }; /** * Specialisation λ(E, ν) */ template <> struct Converter { //! wrapped function (raison d'être) inline constexpr static Real compute(const Real & E, const Real & nu) { return E * nu / ((1 + nu) * (1 - 2 * nu)); } }; /** * Specialisation K(E, ν) */ template <> struct Converter { //! wrapped function (raison d'être) inline constexpr static Real compute(const Real & E, const Real & nu) { return E / (3 * (1 - 2 * nu)); } }; /** * Specialisation E(K, µ) */ template <> struct Converter { //! wrapped function (raison d'être) inline constexpr static Real compute(const Real & K, const Real & G) { return 9 * K * G / (3 * K + G); } }; /** * Specialisation ν(K, µ) */ template <> struct Converter { //! wrapped function (raison d'être) inline constexpr static Real compute(const Real & K, const Real & G) { return (3 * K - 2 * G) / (2 * (3 * K + G)); } }; /** * Specialisation E(λ, µ) */ template <> struct Converter { //! wrapped function (raison d'être) inline constexpr static Real compute(const Real & lambda, const Real & G) { return G * (3 * lambda + 2 * G) / (lambda + G); } }; /** * Specialisation λ(K, µ) */ template <> struct Converter { //! wrapped function (raison d'être) inline constexpr static Real compute(const Real & K, const Real & mu) { return K - 2. * mu / 3.; } }; /** * Specialisation K(λ, µ) */ template <> - struct Converter { //! wrapped function (raison d'être) inline constexpr static Real compute(const Real & lambda, const Real & G) { return lambda + (2 * G) / 3; } }; } // namespace internal /** * allows the conversion from any two distinct input moduli to a * chosen output modulus */ template inline constexpr Real convert_elastic_modulus(const Real & in1, const Real & in2) { // enforcing sanity static_assert((In1 != In2), "The input modulus types cannot be identical"); // enforcing independence from order in which moduli are supplied constexpr bool inverted{In1 > In2}; using Converter = std::conditional_t, internal::Converter>; if (inverted) { return Converter::compute(std::move(in2), std::move(in1)); } else { return Converter::compute(std::move(in1), std::move(in2)); } } //! static inline implementation of Hooke's law template struct Hooke { /** * compute Lamé's first constant * @param young: Young's modulus * @param poisson: Poisson's ratio */ inline static constexpr Real compute_lambda(const Real & young, const Real & poisson) { return convert_elastic_modulus(young, poisson); } /** * compute Lamé's second constant (i.e., shear modulus) * @param young: Young's modulus * @param poisson: Poisson's ratio */ inline static constexpr Real compute_mu(const Real & young, const Real & poisson) { return convert_elastic_modulus(young, poisson); } /** * compute the bulk modulus * @param young: Young's modulus * @param poisson: Poisson's ratio */ inline static constexpr Real compute_K(const Real & young, const Real & poisson) { return convert_elastic_modulus(young, poisson); } /** * compute the stiffness tensor * @param lambda: Lamé's first constant * @param mu: Lamé's second constant (i.e., shear modulus) */ inline static Eigen::TensorFixedSize> compute_C(const Real & lambda, const Real & mu) { return lambda * Tensors::outer(Tensors::I2(), Tensors::I2()) + 2 * mu * Tensors::I4S(); } /** * compute the stiffness tensor * @param lambda: Lamé's first constant * @param mu: Lamé's second constant (i.e., shear modulus) */ - inline static T4Mat compute_C_T4(const Real & lambda, - const Real & mu) { + inline static muGrid::T4Mat compute_C_T4(const Real & lambda, + const Real & mu) { return lambda * Matrices::Itrac() + 2 * mu * Matrices::Isymm(); } /** * return stress * @param lambda: First Lamé's constant * @param mu: Second Lamé's constant (i.e. shear modulus) * @param E: Green-Lagrange or small strain tensor */ template inline static decltype(auto) evaluate_stress(const Real & lambda, const Real & mu, s_t && E) { return E.trace() * lambda * Strain_t::Identity() + 2 * mu * E; } /** * return stress * @param C: stiffness tensor (Piola-Kirchhoff 2 (or σ) w.r.t to `E`) * @param E: Green-Lagrange or small strain tensor */ /*template inline static decltype(auto) evaluate_stress(const Tangent_t C, s_t && E) { return tensmult(C, E); }*/ /** * return stress and tangent stiffness * @param lambda: First Lamé's constant * @param mu: Second Lamé's constant (i.e. shear modulus) * @param E: Green-Lagrange or small strain tensor * @param C: stiffness tensor (Piola-Kirchhoff 2 (or σ) w.r.t to `E`) */ template inline static decltype(auto) evaluate_stress(const Real & lambda, const Real & mu, Tangent_t && C, s_t && E) { return std::make_tuple( std::move(evaluate_stress(lambda, mu, std::move(E))), std::move(C)); } }; namespace internal { /* ---------------------------------------------------------------------- */ template struct NumericalTangentHelper { - using T4_t = T4Mat; + using T4_t = muGrid::T4Mat; using T2_t = Eigen::Matrix; using T2_vec = Eigen::Map>; template static inline T4_t compute(FunType && fun, const Eigen::MatrixBase & strain, Real delta); }; /* ---------------------------------------------------------------------- */ template template auto NumericalTangentHelper::compute( FunType && fun, const Eigen::MatrixBase & strain, Real delta) -> T4_t { static_assert((FinDif == FiniteDiff::forward) or (FinDif == FiniteDiff::backward), "Not implemented"); T4_t tangent{T4_t::Zero()}; const T2_t fun_val{fun(strain)}; for (Dim_t i{}; i < Dim * Dim; ++i) { T2_t strain2{strain}; T2_vec strain_vec{strain2.data()}; switch (FinDif) { case FiniteDiff::forward: { strain_vec(i) += delta; T2_t del_f_del{(fun(strain2) - fun_val) / delta}; tangent.col(i) = T2_vec(del_f_del.data()); break; } case FiniteDiff::backward: { strain_vec(i) -= delta; T2_t del_f_del{(fun_val - fun(strain2)) / delta}; tangent.col(i) = T2_vec(del_f_del.data()); break; } } static_assert(Int(decltype(tangent.col(i))::SizeAtCompileTime) == Int(T2_t::SizeAtCompileTime), "wrong column size"); } return tangent; } /* ---------------------------------------------------------------------- */ template struct NumericalTangentHelper { - using T4_t = T4Mat; + using T4_t = muGrid::T4Mat; using T2_t = Eigen::Matrix; using T2_vec = Eigen::Map>; template static inline T4_t compute(FunType && fun, const Eigen::MatrixBase & strain, Real delta) { T4_t tangent{T4_t::Zero()}; for (Dim_t i{}; i < Dim * Dim; ++i) { T2_t strain1{strain}; T2_t strain2{strain}; T2_vec strain1_vec{strain1.data()}; T2_vec strain2_vec{strain2.data()}; strain1_vec(i) += delta; strain2_vec(i) -= delta; T2_t del_f_del{(fun(strain1).eval() - fun(strain2).eval()) / (2 * delta)}; tangent.col(i) = T2_vec(del_f_del.data()); static_assert(Int(decltype(tangent.col(i))::SizeAtCompileTime) == Int(T2_t::SizeAtCompileTime), "wrong column size"); } return tangent; } }; } // namespace internal /** * Helper function to numerically determine tangent, intended for * testing, rather than as a replacement for analytical tangents */ template - inline T4Mat compute_numerical_tangent( + inline muGrid::T4Mat compute_numerical_tangent( FunType && fun, const Eigen::MatrixBase & strain, Real delta) { static_assert(Derived::RowsAtCompileTime == Dim, "can't handle dynamic matrix"); static_assert(Derived::ColsAtCompileTime == Dim, "can't handle dynamic matrix"); using T2_t = Eigen::Matrix; using T2_vec = Eigen::Map>; static_assert( std::is_convertible>::value, "Function argument 'fun' needs to be a function taking " "one second-rank tensor as input and returning a " "second-rank tensor"); static_assert(Dim_t(T2_t::SizeAtCompileTime) == Dim_t(T2_vec::SizeAtCompileTime), "wrong map size"); return internal::NumericalTangentHelper::compute( std::forward(fun), strain, delta); } } // namespace MatTB } // namespace muSpectre #endif // SRC_MATERIALS_MATERIALS_TOOLBOX_HH_ diff --git a/src/materials/stress_transformations.hh b/src/materials/stress_transformations.hh index 50b52df..b8d23f9 100644 --- a/src/materials/stress_transformations.hh +++ b/src/materials/stress_transformations.hh @@ -1,67 +1,70 @@ /** * @file stress_transformations.hh * * @author Till Junge * * @date 29 Oct 2018 * * @brief isolation of stress conversions for quicker compilation * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ +#include "common/muSpectre_common.hh" +#include + #ifndef SRC_MATERIALS_STRESS_TRANSFORMATIONS_HH_ #define SRC_MATERIALS_STRESS_TRANSFORMATIONS_HH_ namespace muSpectre { namespace MatTB { /* ---------------------------------------------------------------------- */ //! set of functions returning an expression for PK2 stress based on template decltype(auto) PK1_stress(Strain_t && strain, Stress_t && stress) { - constexpr Dim_t dim{EigenCheck::tensor_dim::value}; - static_assert((dim == EigenCheck::tensor_dim::value), + constexpr Dim_t dim{muGrid::EigenCheck::tensor_dim::value}; + static_assert((dim == muGrid::EigenCheck::tensor_dim::value), "Stress and strain tensors have differing dimensions"); return internal::PK1_stress::compute( std::forward(strain), std::forward(stress)); } /* ---------------------------------------------------------------------- */ //! set of functions returning an expression for PK2 stress based on template decltype(auto) PK1_stress(Strain_t && strain, Stress_t && stress, Tangent_t && tangent) { - constexpr Dim_t dim{EigenCheck::tensor_dim::value}; - static_assert((dim == EigenCheck::tensor_dim::value), + constexpr Dim_t dim{muGrid::EigenCheck::tensor_dim::value}; + static_assert((dim == muGrid::EigenCheck::tensor_dim::value), "Stress and strain tensors have differing dimensions"); - static_assert((dim == EigenCheck::tensor_4_dim::value), + static_assert((dim == muGrid::EigenCheck::tensor_4_dim::value), "Stress and tangent tensors have differing dimensions"); return internal::PK1_stress::compute( std::forward(strain), std::forward(stress), std::forward(tangent)); } } // namespace MatTB } // namespace muSpectre #endif // SRC_MATERIALS_STRESS_TRANSFORMATIONS_HH_ diff --git a/src/materials/stress_transformations_Kirchhoff_impl.hh b/src/materials/stress_transformations_Kirchhoff_impl.hh index 68e57f4..22049bd 100644 --- a/src/materials/stress_transformations_Kirchhoff_impl.hh +++ b/src/materials/stress_transformations_Kirchhoff_impl.hh @@ -1,113 +1,114 @@ /** * @file stress_transformations_Kirchhoff_impl.hh * * @author Till Junge * * @date 29 Oct 2018 * * @brief Implementation of stress conversions for Kirchhoff stress * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #ifndef SRC_MATERIALS_STRESS_TRANSFORMATIONS_KIRCHHOFF_IMPL_HH_ #define SRC_MATERIALS_STRESS_TRANSFORMATIONS_KIRCHHOFF_IMPL_HH_ namespace muSpectre { namespace MatTB { namespace internal { /* ---------------------------------------------------------------------- */ /** * Specialisation for the case where we get Kirchhoff stress (τ) */ template struct PK1_stress : public PK1_stress { //! returns the converted stress template inline static decltype(auto) compute(Strain_t && F, Stress_t && tau) { return tau * F.inverse().transpose(); } }; /* ---------------------------------------------------------------------- */ /** * Specialisation for the case where we get Kirchhoff stress (τ) derived * with respect to Gradient */ template struct PK1_stress : public PK1_stress { //! short-hand using Parent = PK1_stress; using Parent::compute; //! returns the converted stress and stiffness template inline static decltype(auto) compute(Strain_t && F, Stress_t && tau, Tangent_t && C) { - using T4_t = T4Mat; + using muGrid::get; + using T4_t = muGrid::T4Mat; using Mat_t = Eigen::Matrix; Mat_t F_inv{F.inverse()}; T4_t increment{T4_t::Zero()}; for (int i{0}; i < Dim; ++i) { const int k{i}; for (int j{0}; j < Dim; ++j) { const int a{j}; for (int l{0}; l < Dim; ++l) { get(increment, i, j, k, l) -= tau(a, l); } } } T4_t Ka{C + increment}; T4_t Kb{T4_t::Zero()}; for (int i{0}; i < Dim; ++i) { for (int j{0}; j < Dim; ++j) { for (int k{0}; k < Dim; ++k) { for (int l{0}; l < Dim; ++l) { for (int a{0}; a < Dim; ++a) { for (int b{0}; b < Dim; ++b) { get(Kb, j, i, k, l) += F_inv(i, a) * get(Ka, a, j, k, b) * F_inv(l, b); } } } } } } Mat_t P = tau * F_inv.transpose(); return std::make_tuple(std::move(P), std::move(Kb)); } }; } // namespace internal } // namespace MatTB } // namespace muSpectre #endif // SRC_MATERIALS_STRESS_TRANSFORMATIONS_KIRCHHOFF_IMPL_HH_ diff --git a/src/materials/stress_transformations_PK1_impl.hh b/src/materials/stress_transformations_PK1_impl.hh index f8b1973..f0b6050 100644 --- a/src/materials/stress_transformations_PK1_impl.hh +++ b/src/materials/stress_transformations_PK1_impl.hh @@ -1,88 +1,87 @@ /** * @file stress_transformations_PK1_impl.hh * * @author Till Junge * * @date 29 Oct 2018 * * @brief implementation of stress conversion for PK1 stress * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #ifndef SRC_MATERIALS_STRESS_TRANSFORMATIONS_PK1_IMPL_HH_ #define SRC_MATERIALS_STRESS_TRANSFORMATIONS_PK1_IMPL_HH_ -#include "common/common.hh" -#include "common/tensor_algebra.hh" -#include "common/T4_map_proxy.hh" +#include "common/muSpectre_common.hh" +#include namespace muSpectre { namespace MatTB { namespace internal { /* ---------------------------------------------------------------------- */ /** Specialisation for the transparent case, where we already have PK1 stress **/ template struct PK1_stress : public PK1_stress { //! returns the converted stress template inline static decltype(auto) compute(Strain_t && /*dummy*/, Stress_t && P) { return std::forward(P); } }; /* ---------------------------------------------------------------------- */ /** Specialisation for the transparent case, where we already have PK1 stress *and* stiffness is given with respect to the transformation gradient **/ template struct PK1_stress : public PK1_stress { //! base class using Parent = PK1_stress; using Parent::compute; //! returns the converted stress and stiffness template inline static decltype(auto) compute(Strain_t && /*dummy*/, Stress_t && P, Tangent_t && K) { return std::make_tuple(std::forward(P), std::forward(K)); } }; } // namespace internal } // namespace MatTB } // namespace muSpectre #endif // SRC_MATERIALS_STRESS_TRANSFORMATIONS_PK1_IMPL_HH_ diff --git a/src/materials/stress_transformations_PK2_impl.hh b/src/materials/stress_transformations_PK2_impl.hh index b5d806b..e4361ef 100644 --- a/src/materials/stress_transformations_PK2_impl.hh +++ b/src/materials/stress_transformations_PK2_impl.hh @@ -1,151 +1,153 @@ /** * @file stress_transformations_PK2_impl.hh * * @author Till Junge * * @date 29 Oct 2018 * * @brief Implementation of stress conversions for PK2 stress * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #ifndef SRC_MATERIALS_STRESS_TRANSFORMATIONS_PK2_IMPL_HH_ #define SRC_MATERIALS_STRESS_TRANSFORMATIONS_PK2_IMPL_HH_ namespace muSpectre { namespace MatTB { namespace internal { /* ---------------------------------------------------------------------- */ /** * Specialisation for the case where we get material stress * (Piola-Kirchhoff-2, PK2) */ template struct PK1_stress : public PK1_stress { //! returns the converted stress template inline static decltype(auto) compute(Strain_t && F, Stress_t && S) { return F * S; } }; /* ---------------------------------------------------------------------- */ /** * Specialisation for the case where we get material stress * (Piola-Kirchhoff-2, PK2) derived with respect to * Green-Lagrange strain */ template struct PK1_stress : public PK1_stress { //! base class using Parent = PK1_stress; using Parent::compute; //! returns the converted stress and stiffness template inline static decltype(auto) compute(Strain_t && F, Stress_t && S, Tangent_t && C) { using T4 = typename std::remove_reference_t::PlainObject; - using Tmap = T4MatMap; + using Tmap = muGrid::T4MatMap; + using muGrid::get; + T4 K; Tmap Kmap{K.data()}; K.setZero(); for (int i = 0; i < Dim; ++i) { for (int m = 0; m < Dim; ++m) { for (int n = 0; n < Dim; ++n) { get(Kmap, i, m, i, n) += S(m, n); for (int j = 0; j < Dim; ++j) { for (int r = 0; r < Dim; ++r) { for (int s = 0; s < Dim; ++s) { get(Kmap, i, m, j, n) += F(i, r) * get(C, r, m, s, n) * (F(j, s)); } } } } } } auto && P = compute(std::forward(F), std::forward(S)); return std::make_tuple(std::move(P), std::move(K)); } }; /* ---------------------------------------------------------------------- */ /** * Specialisation for the case where we get material stress * (Piola-Kirchhoff-2, PK2) derived with respect to * the placement Gradient (F) */ template struct PK1_stress : public PK1_stress { //! base class using Parent = PK1_stress; using Parent::compute; //! returns the converted stress and stiffness template inline static decltype(auto) compute(Strain_t && F, Stress_t && S, Tangent_t && C) { using T4 = typename std::remove_reference_t::PlainObject; - using Tmap = T4MatMap; + using Tmap = muGrid::T4MatMap; T4 K; Tmap Kmap{K.data()}; K.setZero(); for (int i = 0; i < Dim; ++i) { for (int m = 0; m < Dim; ++m) { for (int n = 0; n < Dim; ++n) { get(Kmap, i, m, i, n) += S(m, n); for (int j = 0; j < Dim; ++j) { for (int r = 0; r < Dim; ++r) { get(Kmap, i, m, j, n) += F(i, r) * get(C, r, m, j, n); } } } } } auto && P = compute(std::forward(F), std::forward(S)); return std::make_tuple(std::move(P), std::move(K)); } }; } // namespace internal } // namespace MatTB } // namespace muSpectre #endif // SRC_MATERIALS_STRESS_TRANSFORMATIONS_PK2_IMPL_HH_ diff --git a/src/materials/stress_transformations_default_case.hh b/src/materials/stress_transformations_default_case.hh index 0f53fd1..d8bb2b2 100644 --- a/src/materials/stress_transformations_default_case.hh +++ b/src/materials/stress_transformations_default_case.hh @@ -1,79 +1,80 @@ /** * @file stress_transformations_default_case.hh * * @author Till Junge * * @date 29 Oct 2018 * * @brief default structure for stress conversions * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #ifndef SRC_MATERIALS_STRESS_TRANSFORMATIONS_DEFAULT_CASE_HH_ #define SRC_MATERIALS_STRESS_TRANSFORMATIONS_DEFAULT_CASE_HH_ -#include "common/common.hh" -#include "common/T4_map_proxy.hh" +#include "common/muSpectre_common.hh" + +#include namespace muSpectre { namespace MatTB { namespace internal { /** Structure for functions returning PK1 stress from other stress - *measures + *measures **/ template struct PK1_stress { //! returns the converted stress template inline static decltype(auto) compute(Strain_t && /*strain*/, Stress_t && /*stress*/) { // the following test always fails to generate a compile-time error static_assert((StressM == StressMeasure::Cauchy) && (StressM == StressMeasure::PK1), "The requested Stress conversion is not implemented. " "You either made a programming mistake or need to " "implement it as a specialisation of this function. " "See PK2stress for an example."); } //! returns the converted stress and stiffness template inline static decltype(auto) compute(Strain_t && /*strain*/, Stress_t && /*stress*/, Tangent_t && /*stiffness*/) { // the following test always fails to generate a compile-time error static_assert((StressM == StressMeasure::Cauchy) && (StressM == StressMeasure::PK1), "The requested Stress conversion is not implemented. " "You either made a programming mistake or need to " "implement it as a specialisation of this function. " "See PK2stress for an example."); } }; } // namespace internal } // namespace MatTB } // namespace muSpectre #endif // SRC_MATERIALS_STRESS_TRANSFORMATIONS_DEFAULT_CASE_HH_ diff --git a/src/projection/CMakeLists.txt b/src/projection/CMakeLists.txt new file mode 100644 index 0000000..c4730e3 --- /dev/null +++ b/src/projection/CMakeLists.txt @@ -0,0 +1,45 @@ +# ============================================================================= +# file CMakeLists.txt +# +# @author Till Junge +# +# @date 08 Jan 2018 +# +# @brief configuration for fft-related files +# +# @section LICENSE +# +# Copyright © 2018 Till Junge +# +# µSpectre is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public License as +# published by the Free Software Foundation, either version 3, or (at +# your option) any later version. +# +# µSpectre is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with µSpectre; see the file COPYING. If not, write to the +# Free Software Foundation, Inc., 59 Temple Place - Suite 330, +# Boston, MA 02111-1307, USA. +# +# Additional permission under GNU GPL version 3 section 7 +# +# If you modify this Program, or any covered work, by linking or combining it +# with proprietary FFT implementations or numerical libraries, containing parts +# covered by the terms of those libraries' licenses, the licensors of this +# Program grant you additional permission to convey the resulting work. +# ============================================================================= + +set (projection_SRC + ${CMAKE_CURRENT_SOURCE_DIR}/projection_base.cc + ${CMAKE_CURRENT_SOURCE_DIR}/projection_default.cc + ${CMAKE_CURRENT_SOURCE_DIR}/projection_finite_strain.cc + ${CMAKE_CURRENT_SOURCE_DIR}/projection_small_strain.cc + ${CMAKE_CURRENT_SOURCE_DIR}/projection_finite_strain_fast.cc + ) + +target_sources(muSpectre PRIVATE ${projection_SRC}) diff --git a/src/fft/projection_base.cc b/src/projection/projection_base.cc similarity index 95% rename from src/fft/projection_base.cc rename to src/projection/projection_base.cc index 966046c..25aba99 100644 --- a/src/fft/projection_base.cc +++ b/src/projection/projection_base.cc @@ -1,63 +1,63 @@ /** * @file projection_base.cc * * @author Till Junge * * @date 06 Dec 2017 * * @brief implementation of base class for projections * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#include "fft/projection_base.hh" +#include "projection/projection_base.hh" namespace muSpectre { /* ---------------------------------------------------------------------- */ template ProjectionBase::ProjectionBase(FFTEngine_ptr engine, Rcoord domain_lengths, Formulation form) : fft_engine{std::move(engine)}, domain_lengths{domain_lengths}, form{form}, projection_container{ this->fft_engine->get_field_collection()} { static_assert((DimS == FFTEngine::sdim), "spatial dimensions are incompatible"); if (this->get_nb_components() != fft_engine->get_nb_components()) { throw ProjectionError("Incompatible number of components per pixel"); } } /* ---------------------------------------------------------------------- */ template - void ProjectionBase::initialise(FFT_PlanFlags flags) { + void ProjectionBase::initialise(muFFT::FFT_PlanFlags flags) { fft_engine->initialise(flags); } template class ProjectionBase; template class ProjectionBase; template class ProjectionBase; } // namespace muSpectre diff --git a/src/fft/projection_base.hh b/src/projection/projection_base.hh similarity index 92% rename from src/fft/projection_base.hh rename to src/projection/projection_base.hh index 70a0f3a..5e0b55a 100644 --- a/src/fft/projection_base.hh +++ b/src/projection/projection_base.hh @@ -1,188 +1,189 @@ /** * @file projection_base.hh * * @author Till Junge * * @date 03 Dec 2017 * * @brief Base class for Projection operators * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#ifndef SRC_FFT_PROJECTION_BASE_HH_ -#define SRC_FFT_PROJECTION_BASE_HH_ +#ifndef SRC_PROJECTION_PROJECTION_BASE_HH_ +#define SRC_PROJECTION_PROJECTION_BASE_HH_ -#include "common/common.hh" -#include "common/field.hh" -#include "common/field_collection.hh" -#include "fft/fft_engine_base.hh" +#include "common/muSpectre_common.hh" +#include +#include +#include #include namespace muSpectre { /** * base class for projection related exceptions */ class ProjectionError : public std::runtime_error { public: //! constructor explicit ProjectionError(const std::string & what) : std::runtime_error(what) {} //! constructor explicit ProjectionError(const char * what) : std::runtime_error(what) {} }; template struct Projection_traits {}; /** * defines the interface which must be implemented by projection operators */ template class ProjectionBase { public: //! Eigen type to replace fields using Vector_t = Eigen::Matrix; //! type of fft_engine used - using FFTEngine = FFTEngineBase; + using FFTEngine = muFFT::FFTEngineBase; //! reference to fft engine is safely managed through a `std::unique_ptr` using FFTEngine_ptr = std::unique_ptr; //! cell coordinates type using Ccoord = typename FFTEngine::Ccoord; //! spatial coordinates type using Rcoord = Rcoord_t; //! global FieldCollection using GFieldCollection_t = typename FFTEngine::GFieldCollection_t; //! local FieldCollection (for Fourier-space pixels) using LFieldCollection_t = typename FFTEngine::LFieldCollection_t; //! Field type on which to apply the projection - using Field_t = TypedField; + using Field_t = muGrid::TypedField; /** * iterator over all pixels. This is taken from the FFT engine, * because depending on the real-to-complex FFT employed, only * roughly half of the pixels are present in Fourier space * (because of the hermitian nature of the transform) */ using iterator = typename FFTEngine::iterator; //! Default constructor ProjectionBase() = delete; //! Constructor with cell sizes ProjectionBase(FFTEngine_ptr engine, Rcoord domain_lengths, Formulation form); //! Copy constructor ProjectionBase(const ProjectionBase & other) = delete; //! Move constructor ProjectionBase(ProjectionBase && other) = default; //! Destructor virtual ~ProjectionBase() = default; //! Copy assignment operator ProjectionBase & operator=(const ProjectionBase & other) = delete; //! Move assignment operator ProjectionBase & operator=(ProjectionBase && other) = default; //! initialises the fft engine (plan the transform) - virtual void initialise(FFT_PlanFlags flags = FFT_PlanFlags::estimate); + virtual void + initialise(muFFT::FFT_PlanFlags flags = muFFT::FFT_PlanFlags::estimate); //! apply the projection operator to a field virtual void apply_projection(Field_t & field) = 0; //! returns the process-local resolutions of the cell const Ccoord & get_subdomain_resolutions() const { return this->fft_engine->get_subdomain_resolutions(); } //! returns the process-local locations of the cell const Ccoord & get_subdomain_locations() const { return this->fft_engine->get_subdomain_locations(); } //! returns the resolutions of the cell const Ccoord & get_domain_resolutions() const { return this->fft_engine->get_domain_resolutions(); } //! returns the physical sizes of the cell const Rcoord & get_domain_lengths() const { return this->domain_lengths; } /** * return the `muSpectre::Formulation` that is used in solving * this cell. This allows tho check whether a projection is * compatible with the chosen formulation */ const Formulation & get_formulation() const { return this->form; } //! return the raw projection operator. This is mainly intended //! for maintenance and debugging and should never be required in //! regular use virtual Eigen::Map get_operator() = 0; //! return the communicator object - const Communicator & get_communicator() const { + const auto & get_communicator() const { return this->fft_engine->get_communicator(); } /** * returns the number of rows and cols for the strain matrix type * (for full storage, the strain is stored in material_dim × * material_dim matrices, but in symmetriy storage, it is a column * vector) */ virtual std::array get_strain_shape() const = 0; //! get number of components to project per pixel virtual Dim_t get_nb_components() const { return DimM * DimM; } protected: //! handle on the fft_engine used FFTEngine_ptr fft_engine; const Rcoord domain_lengths; //!< physical sizes of the cell /** * formulation this projection can be applied to (determines * whether the projection enforces gradients, small strain tensor * or symmetric smal strain tensor */ const Formulation form; /** * A local `muSpectre::FieldCollection` to store the projection * operator per k-space point. This is a local rather than a * global collection, since the pixels considered depend on the * FFT implementation. See * http://www.fftw.org/fftw3_doc/Multi_002dDimensional-DFTs-of-Real-Data.html#Multi_002dDimensional-DFTs-of-Real-Data * for an example */ LFieldCollection_t & projection_container{}; private: }; } // namespace muSpectre -#endif // SRC_FFT_PROJECTION_BASE_HH_ +#endif // SRC_PROJECTION_PROJECTION_BASE_HH_ diff --git a/src/fft/projection_default.cc b/src/projection/projection_default.cc similarity index 93% rename from src/fft/projection_default.cc rename to src/projection/projection_default.cc index 078e412..9cb2f3d 100644 --- a/src/fft/projection_default.cc +++ b/src/projection/projection_default.cc @@ -1,78 +1,78 @@ /** * @file projection_default.cc * * @author Till Junge * * @date 14 Jan 2018 * * @brief Implementation default projection implementation * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#include "fft/projection_default.hh" -#include "fft/fft_engine_base.hh" +#include "projection/projection_default.hh" +#include namespace muSpectre { /* ---------------------------------------------------------------------- */ template ProjectionDefault::ProjectionDefault(FFTEngine_ptr engine, Rcoord lengths, Formulation form) : Parent{std::move(engine), lengths, form}, - Gfield{make_field("Projection Operator", - this->projection_container)}, + Gfield{muGrid::make_field("Projection Operator", + this->projection_container)}, Ghat{Gfield} {} /* ---------------------------------------------------------------------- */ template void ProjectionDefault::apply_projection(Field_t & field) { Vector_map field_map{this->fft_engine->fft(field)}; Real factor = this->fft_engine->normalisation(); for (auto && tup : akantu::zip(this->Ghat, field_map)) { auto & G{std::get<0>(tup)}; auto & f{std::get<1>(tup)}; f = factor * (G * f).eval(); } this->fft_engine->ifft(field); } /* ---------------------------------------------------------------------- */ template Eigen::Map ProjectionDefault::get_operator() { return this->Gfield.dyn_eigen(); } /* ---------------------------------------------------------------------- */ template std::array ProjectionDefault::get_strain_shape() const { return std::array{DimM, DimM}; } /* ---------------------------------------------------------------------- */ template class ProjectionDefault; template class ProjectionDefault; } // namespace muSpectre diff --git a/src/fft/projection_default.hh b/src/projection/projection_default.hh similarity index 84% rename from src/fft/projection_default.hh rename to src/projection/projection_default.hh index ce036c4..d311131 100644 --- a/src/fft/projection_default.hh +++ b/src/projection/projection_default.hh @@ -1,115 +1,116 @@ /** * @file projection_default.hh * * @author Till Junge * * @date 14 Jan 2018 * * @brief virtual base class for default projection implementation, where the * projection operator is stored as a full fourth-order tensor per * k-space point (as opposed to 'smart' faster implementations, such as * ProjectionFiniteStrainFast * * Copyright (C) 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#ifndef SRC_FFT_PROJECTION_DEFAULT_HH_ -#define SRC_FFT_PROJECTION_DEFAULT_HH_ +#ifndef SRC_PROJECTION_PROJECTION_DEFAULT_HH_ +#define SRC_PROJECTION_PROJECTION_DEFAULT_HH_ -#include "fft/projection_base.hh" +#include "projection/projection_base.hh" namespace muSpectre { /** * base class to inherit from if one implements a projection * operator that is stored in form of a fourth-order tensor of real * values per k-grid point */ template class ProjectionDefault : public ProjectionBase { public: using Parent = ProjectionBase; //!< base class using Vector_t = typename Parent::Vector_t; //!< to represent fields //! polymorphic FFT pointer type using FFTEngine_ptr = typename Parent::FFTEngine_ptr; using Ccoord = typename Parent::Ccoord; //!< cell coordinates type using Rcoord = typename Parent::Rcoord; //!< spatial coordinates type //! global field collection - using GFieldCollection_t = GlobalFieldCollection; + using GFieldCollection_t = muGrid::GlobalFieldCollection; //! local field collection for Fourier-space fields - using LFieldCollection_t = LocalFieldCollection; + using LFieldCollection_t = muGrid::LocalFieldCollection; //! Real space second order tensor fields (to be projected) - using Field_t = TypedField; + using Field_t = muGrid::TypedField; //! Fourier-space field containing the projection operator itself - using Proj_t = TensorField; + using Proj_t = + muGrid::TensorField; //! iterable form of the operator - using Proj_map = T4MatrixFieldMap; + using Proj_map = muGrid::T4MatrixFieldMap; //! vectorized version of the Fourier-space second-order tensor field using Vector_map = - MatrixFieldMap; + muGrid::MatrixFieldMap; //! Default constructor ProjectionDefault() = delete; //! Constructor with cell sizes and formulation ProjectionDefault(FFTEngine_ptr engine, Rcoord lengths, Formulation form); //! Copy constructor ProjectionDefault(const ProjectionDefault & other) = delete; //! Move constructor ProjectionDefault(ProjectionDefault && other) = default; //! Destructor virtual ~ProjectionDefault() = default; //! Copy assignment operator ProjectionDefault & operator=(const ProjectionDefault & other) = delete; //! Move assignment operator ProjectionDefault & operator=(ProjectionDefault && other) = delete; //! apply the projection operator to a field void apply_projection(Field_t & field) final; Eigen::Map get_operator() final; /** * returns the number of rows and cols for the strain matrix type * (for full storage, the strain is stored in material_dim × * material_dim matrices, but in symmetriy storage, it is a column * vector) */ std::array get_strain_shape() const final; - constexpr static Dim_t NbComponents() { return ipow(DimM, 2); } + constexpr static Dim_t NbComponents() { return muGrid::ipow(DimM, 2); } protected: Proj_t & Gfield; //!< field holding the operator Proj_map Ghat; //!< iterable version of operator }; } // namespace muSpectre -#endif // SRC_FFT_PROJECTION_DEFAULT_HH_ +#endif // SRC_PROJECTION_PROJECTION_DEFAULT_HH_ diff --git a/src/fft/projection_finite_strain.cc b/src/projection/projection_finite_strain.cc similarity index 89% rename from src/fft/projection_finite_strain.cc rename to src/projection/projection_finite_strain.cc index b195922..9a87192 100644 --- a/src/fft/projection_finite_strain.cc +++ b/src/projection/projection_finite_strain.cc @@ -1,97 +1,98 @@ /** * @file projection_finite_strain.cc * * @author Till Junge * * @date 05 Dec 2017 * * @brief implementation of standard finite strain projection operator * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#include "fft/projection_finite_strain.hh" -#include "common/field_map.hh" -#include "common/iterators.hh" -#include "common/tensor_algebra.hh" -#include "fft/fft_utils.hh" -#include "fft/fftw_engine.hh" +#include "projection/projection_finite_strain.hh" + +#include +#include +#include +#include #include "Eigen/Dense" namespace muSpectre { /* ---------------------------------------------------------------------- */ template ProjectionFiniteStrain::ProjectionFiniteStrain( FFTEngine_ptr engine, Rcoord lengths) : Parent{std::move(engine), lengths, Formulation::finite_strain} { for (auto res : this->fft_engine->get_domain_resolutions()) { if (res % 2 == 0) { throw ProjectionError( "Only an odd number of gridpoints in each direction is supported"); } } } /* ---------------------------------------------------------------------- */ template - void ProjectionFiniteStrain::initialise(FFT_PlanFlags flags) { + void + ProjectionFiniteStrain::initialise(muFFT::FFT_PlanFlags flags) { Parent::initialise(flags); - FFT_freqs fft_freqs(this->fft_engine->get_domain_resolutions(), - this->domain_lengths); + muFFT::FFT_freqs fft_freqs(this->fft_engine->get_domain_resolutions(), + this->domain_lengths); for (auto && tup : akantu::zip(*this->fft_engine, this->Ghat)) { const auto & ccoord = std::get<0>(tup); auto & G = std::get<1>(tup); auto xi = fft_freqs.get_unit_xi(ccoord); //! this is simplifiable using Curnier's Méthodes numériques, 6.69(c) G = Matrices::outer_under(Matrices::I2(), xi * xi.transpose()); // The commented block below corresponds to the original // definition of the operator in de Geus et // al. (https://doi.org/10.1016/j.cma.2016.12.032). However, // they use a bizarre definition of the double contraction // between fourth-order and second-order tensors that has a // built-in transpose operation (i.e., C = A:B <-> AᵢⱼₖₗBₗₖ = // Cᵢⱼ , note the inverted ₗₖ instead of ₖₗ), here, we define // the double contraction without the transposition. As a // result, the Projection operator produces the transpose of de // Geus's // for (Dim_t im = 0; im < DimS; ++im) { // for (Dim_t j = 0; j < DimS; ++j) { // for (Dim_t l = 0; l < DimS; ++l) { // get(G, im, j, l, im) = xi(j)*xi(l); // } // } // } } if (this->get_subdomain_locations() == Ccoord{}) { this->Ghat[0].setZero(); } } template class ProjectionFiniteStrain; template class ProjectionFiniteStrain; } // namespace muSpectre diff --git a/src/fft/projection_finite_strain.hh b/src/projection/projection_finite_strain.hh similarity index 82% rename from src/fft/projection_finite_strain.hh rename to src/projection/projection_finite_strain.hh index 796af6b..6592e6a 100644 --- a/src/fft/projection_finite_strain.hh +++ b/src/projection/projection_finite_strain.hh @@ -1,96 +1,97 @@ /** * @file projection_finite_strain.hh * * @author Till Junge * * @date 05 Dec 2017 * * @brief Class for standard finite-strain gradient projections see de Geus et * al. (https://doi.org/10.1016/j.cma.2016.12.032) for derivation * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#ifndef SRC_FFT_PROJECTION_FINITE_STRAIN_HH_ -#define SRC_FFT_PROJECTION_FINITE_STRAIN_HH_ +#ifndef SRC_PROJECTION_PROJECTION_FINITE_STRAIN_HH_ +#define SRC_PROJECTION_PROJECTION_FINITE_STRAIN_HH_ -#include "fft/projection_default.hh" -#include "common/common.hh" -#include "common/field_collection.hh" -#include "common/field_map.hh" +#include "projection/projection_default.hh" +#include "common/muSpectre_common.hh" +#include +#include namespace muSpectre { /** * Implements the finite strain gradient projection operator as * defined in de Geus et * al. (https://doi.org/10.1016/j.cma.2016.12.032) for derivation */ template class ProjectionFiniteStrain : public ProjectionDefault { public: using Parent = ProjectionDefault; //!< base class //! polymorphic pointer to FFT engines using FFTEngine_ptr = typename Parent::FFTEngine_ptr; using Ccoord = typename Parent::Ccoord; //!< cell coordinates type using Rcoord = typename Parent::Rcoord; //!< spatial coordinates type //! local field collection (for Fourier-space representations) - using LFieldCollection_t = LocalFieldCollection; + using LFieldCollection_t = muGrid::LocalFieldCollection; //! iterable operator - using Proj_map = T4MatrixFieldMap; + using Proj_map = muGrid::T4MatrixFieldMap; //! iterable vectorised version of the Fourier-space tensor field using Vector_map = - MatrixFieldMap; + muGrid::MatrixFieldMap; //! Default constructor ProjectionFiniteStrain() = delete; //! Constructor with fft_engine ProjectionFiniteStrain(FFTEngine_ptr engine, Rcoord lengths); //! Copy constructor ProjectionFiniteStrain(const ProjectionFiniteStrain & other) = delete; //! Move constructor ProjectionFiniteStrain(ProjectionFiniteStrain && other) = default; //! Destructor virtual ~ProjectionFiniteStrain() = default; //! Copy assignment operator ProjectionFiniteStrain & operator=(const ProjectionFiniteStrain & other) = delete; //! Move assignment operator ProjectionFiniteStrain & operator=(ProjectionFiniteStrain && other) = default; //! initialises the fft engine (plan the transform) - void initialise(FFT_PlanFlags flags = FFT_PlanFlags::estimate) final; + void initialise( + muFFT::FFT_PlanFlags flags = muFFT::FFT_PlanFlags::estimate) final; }; } // namespace muSpectre -#endif // SRC_FFT_PROJECTION_FINITE_STRAIN_HH_ +#endif // SRC_PROJECTION_PROJECTION_FINITE_STRAIN_HH_ diff --git a/src/fft/projection_finite_strain_fast.cc b/src/projection/projection_finite_strain_fast.cc similarity index 87% rename from src/fft/projection_finite_strain_fast.cc rename to src/projection/projection_finite_strain_fast.cc index e6bb5e0..b63350d 100644 --- a/src/fft/projection_finite_strain_fast.cc +++ b/src/projection/projection_finite_strain_fast.cc @@ -1,104 +1,105 @@ /** * @file projection_finite_strain_fast.cc * * @author Till Junge * * @date 12 Dec 2017 * * @brief implementation for fast projection in finite strain * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#include "fft/projection_finite_strain_fast.hh" -#include "fft/fft_utils.hh" -#include "common/tensor_algebra.hh" -#include "common/iterators.hh" +#include "projection/projection_finite_strain_fast.hh" + +#include +#include namespace muSpectre { /* ---------------------------------------------------------------------- */ template ProjectionFiniteStrainFast::ProjectionFiniteStrainFast( FFTEngine_ptr engine, Rcoord lengths) : Parent{std::move(engine), lengths, Formulation::finite_strain}, - xiField{make_field("Projection Operator", - this->projection_container)}, + xiField{muGrid::make_field("Projection Operator", + this->projection_container)}, xis(xiField) { for (auto res : this->fft_engine->get_domain_resolutions()) { if (res % 2 == 0) { throw ProjectionError( "Only an odd number of gridpoints in each direction is supported"); } } } /* ---------------------------------------------------------------------- */ template - void ProjectionFiniteStrainFast::initialise(FFT_PlanFlags flags) { + void ProjectionFiniteStrainFast::initialise( + muFFT::FFT_PlanFlags flags) { Parent::initialise(flags); - FFT_freqs fft_freqs(this->fft_engine->get_domain_resolutions(), - this->domain_lengths); + muFFT::FFT_freqs fft_freqs(this->fft_engine->get_domain_resolutions(), + this->domain_lengths); for (auto && tup : akantu::zip(*this->fft_engine, this->xis)) { const auto & ccoord = std::get<0>(tup); auto & xi = std::get<1>(tup); xi = fft_freqs.get_unit_xi(ccoord); } if (this->get_subdomain_locations() == Ccoord{}) { this->xis[0].setZero(); } } /* ---------------------------------------------------------------------- */ template void ProjectionFiniteStrainFast::apply_projection(Field_t & field) { Grad_map field_map{this->fft_engine->fft(field)}; Real factor = this->fft_engine->normalisation(); for (auto && tup : akantu::zip(this->xis, field_map)) { auto & xi{std::get<0>(tup)}; auto & f{std::get<1>(tup)}; f = factor * ((f * xi).eval() * xi.transpose()); } this->fft_engine->ifft(field); } /* ---------------------------------------------------------------------- */ template Eigen::Map ProjectionFiniteStrainFast::get_operator() { return this->xiField.dyn_eigen(); } /* ---------------------------------------------------------------------- */ template std::array ProjectionFiniteStrainFast::get_strain_shape() const { return std::array{DimM, DimM}; } /* ---------------------------------------------------------------------- */ template class ProjectionFiniteStrainFast; template class ProjectionFiniteStrainFast; } // namespace muSpectre diff --git a/src/fft/projection_finite_strain_fast.hh b/src/projection/projection_finite_strain_fast.hh similarity index 79% rename from src/fft/projection_finite_strain_fast.hh rename to src/projection/projection_finite_strain_fast.hh index f88d10b..26f2340 100644 --- a/src/fft/projection_finite_strain_fast.hh +++ b/src/projection/projection_finite_strain_fast.hh @@ -1,121 +1,124 @@ /** * @file projection_finite_strain_fast.hh * * @author Till Junge * * @date 12 Dec 2017 * * @brief Faster alternative to ProjectionFinitestrain * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#ifndef SRC_FFT_PROJECTION_FINITE_STRAIN_FAST_HH_ -#define SRC_FFT_PROJECTION_FINITE_STRAIN_FAST_HH_ +#ifndef SRC_PROJECTION_PROJECTION_FINITE_STRAIN_FAST_HH_ +#define SRC_PROJECTION_PROJECTION_FINITE_STRAIN_FAST_HH_ -#include "fft/projection_base.hh" -#include "common/common.hh" -#include "common/field_collection.hh" -#include "common/field_map.hh" +#include "projection/projection_base.hh" +#include "common/muSpectre_common.hh" +#include +#include namespace muSpectre { /** * replaces `muSpectre::ProjectionFiniteStrain` with a faster and * less memory-hungry alternative formulation. Use this if you don't * have a very good reason not to (and tell me (author) about it, * I'd be interested to hear it). */ template class ProjectionFiniteStrainFast : public ProjectionBase { public: using Parent = ProjectionBase; //!< base class //! polymorphic pointer to FFT engines using FFTEngine_ptr = typename Parent::FFTEngine_ptr; using Ccoord = typename Parent::Ccoord; //!< cell coordinates type using Rcoord = typename Parent::Rcoord; //!< spatial coordinates type //! global field collection (for real-space representations) - using GFieldCollection_t = GlobalFieldCollection; + using GFieldCollection_t = muGrid::GlobalFieldCollection; //! local field collection (for Fourier-space representations) - using LFieldCollection_t = LocalFieldCollection; + using LFieldCollection_t = muGrid::LocalFieldCollection; //! Real space second order tensor fields (to be projected) - using Field_t = TypedField; + using Field_t = muGrid::TypedField; //! Fourier-space field containing the projection operator itself - using Proj_t = TensorField; + using Proj_t = + muGrid::TensorField; //! iterable form of the operator - using Proj_map = MatrixFieldMap; + using Proj_map = muGrid::MatrixFieldMap; //! iterable Fourier-space second-order tensor field - using Grad_map = MatrixFieldMap; + using Grad_map = + muGrid::MatrixFieldMap; //! Default constructor ProjectionFiniteStrainFast() = delete; //! Constructor with fft_engine ProjectionFiniteStrainFast(FFTEngine_ptr engine, Rcoord lengths); //! Copy constructor ProjectionFiniteStrainFast(const ProjectionFiniteStrainFast & other) = delete; //! Move constructor ProjectionFiniteStrainFast(ProjectionFiniteStrainFast && other) = default; //! Destructor virtual ~ProjectionFiniteStrainFast() = default; //! Copy assignment operator ProjectionFiniteStrainFast & operator=(const ProjectionFiniteStrainFast & other) = delete; //! Move assignment operator ProjectionFiniteStrainFast & operator=(ProjectionFiniteStrainFast && other) = default; //! initialises the fft engine (plan the transform) - void initialise(FFT_PlanFlags flags = FFT_PlanFlags::estimate) final; + void initialise( + muFFT::FFT_PlanFlags flags = muFFT::FFT_PlanFlags::estimate) final; //! apply the projection operator to a field void apply_projection(Field_t & field) final; Eigen::Map get_operator() final; /** * returns the number of rows and cols for the strain matrix type * (for full storage, the strain is stored in material_dim × * material_dim matrices, but in symmetriy storage, it is a column * vector) */ std::array get_strain_shape() const final; - constexpr static Dim_t NbComponents() { return ipow(DimM, 2); } + constexpr static Dim_t NbComponents() { return muGrid::ipow(DimM, 2); } protected: Proj_t & xiField; //!< field of normalised wave vectors Proj_map xis; //!< iterable normalised wave vectors }; } // namespace muSpectre -#endif // SRC_FFT_PROJECTION_FINITE_STRAIN_FAST_HH_ +#endif // SRC_PROJECTION_PROJECTION_FINITE_STRAIN_FAST_HH_ diff --git a/src/fft/projection_small_strain.cc b/src/projection/projection_small_strain.cc similarity index 90% rename from src/fft/projection_small_strain.cc rename to src/projection/projection_small_strain.cc index 7f5d77f..89b20f7 100644 --- a/src/fft/projection_small_strain.cc +++ b/src/projection/projection_small_strain.cc @@ -1,89 +1,91 @@ /** * @file projection_small_strain.cc * * @author Till Junge * * @date 14 Jan 2018 * * @brief Implementation for ProjectionSmallStrain * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#include "fft/projection_small_strain.hh" -#include "fft/fft_utils.hh" +#include "projection/projection_small_strain.hh" +#include namespace muSpectre { /* ---------------------------------------------------------------------- */ template ProjectionSmallStrain::ProjectionSmallStrain(FFTEngine_ptr engine, Rcoord lengths) : Parent{std::move(engine), lengths, Formulation::small_strain} { for (auto res : this->fft_engine->get_domain_resolutions()) { if (res % 2 == 0) { throw ProjectionError( "Only an odd number of gridpoints in each direction is supported"); } } } /* ---------------------------------------------------------------------- */ template - void ProjectionSmallStrain::initialise(FFT_PlanFlags flags) { + void + ProjectionSmallStrain::initialise(muFFT::FFT_PlanFlags flags) { + using muGrid::get; Parent::initialise(flags); - FFT_freqs fft_freqs(this->fft_engine->get_domain_resolutions(), - this->domain_lengths); + muFFT::FFT_freqs fft_freqs(this->fft_engine->get_domain_resolutions(), + this->domain_lengths); for (auto && tup : akantu::zip(*this->fft_engine, this->Ghat)) { const auto & ccoord = std::get<0>(tup); auto & G = std::get<1>(tup); auto xi = fft_freqs.get_unit_xi(ccoord); auto kron = [](const Dim_t i, const Dim_t j) -> Real { return (i == j) ? 1. : 0.; }; for (Dim_t i{0}; i < DimS; ++i) { for (Dim_t j{0}; j < DimS; ++j) { for (Dim_t l{0}; l < DimS; ++l) { for (Dim_t m{0}; m < DimS; ++m) { Real & g = get(G, i, j, l, m); g = 0.5 * (xi(i) * kron(j, l) * xi(m) + xi(i) * kron(j, m) * xi(l) + xi(j) * kron(i, l) * xi(m) + xi(j) * kron(i, m) * xi(l)) - xi(i) * xi(j) * xi(l) * xi(m); } } } } } if (this->get_subdomain_locations() == Ccoord{}) { this->Ghat[0].setZero(); } } template class ProjectionSmallStrain; template class ProjectionSmallStrain; } // namespace muSpectre diff --git a/src/fft/projection_small_strain.hh b/src/projection/projection_small_strain.hh similarity index 84% rename from src/fft/projection_small_strain.hh rename to src/projection/projection_small_strain.hh index 324eef1..cd8cd8b 100644 --- a/src/fft/projection_small_strain.hh +++ b/src/projection/projection_small_strain.hh @@ -1,98 +1,100 @@ /** * @file projection_small_strain.cc * * @author Till Junge * * @date 14 Jan 2018 * * @brief Small strain projection operator as defined in Appendix A1 of * DOI: 10.1002/nme.5481 ("A finite element perspective on nonlinear * FFT-based micromechanical simulations", Int. J. Numer. Meth. Engng * 2017; 111 :903–926) * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#ifndef SRC_FFT_PROJECTION_SMALL_STRAIN_HH_ -#define SRC_FFT_PROJECTION_SMALL_STRAIN_HH_ +#ifndef SRC_PROJECTION_PROJECTION_SMALL_STRAIN_HH_ +#define SRC_PROJECTION_PROJECTION_SMALL_STRAIN_HH_ -#include "fft/projection_default.hh" +#include "projection/projection_default.hh" namespace muSpectre { /** * Implements the small strain projection operator as defined in * Appendix A1 of DOI: 10.1002/nme.5481 ("A finite element * perspective on nonlinear FFT-based micromechanical * simulations", Int. J. Numer. Meth. Engng 2017; 111 * :903–926) */ template class ProjectionSmallStrain : public ProjectionDefault { public: using Parent = ProjectionDefault; //!< base class //! polymorphic pointer to FFT engines using FFTEngine_ptr = typename Parent::FFTEngine_ptr; using Ccoord = typename Parent::Ccoord; //!< cell coordinates type using Rcoord = typename Parent::Rcoord; //!< spatial coordinates type //! local field collection (for Fourier-space representations) - using LFieldCollection_t = LocalFieldCollection; + using LFieldCollection_t = muGrid::LocalFieldCollection; //! Fourier-space field containing the projection operator itself - using Proj_t = TensorField; + using Proj_t = + muGrid::TensorField; //! iterable operator - using Proj_map = T4MatrixFieldMap; + using Proj_map = muGrid::T4MatrixFieldMap; //! iterable vectorised version of the Fourier-space tensor field using Vector_map = - MatrixFieldMap; + muGrid::MatrixFieldMap; //! Default constructor ProjectionSmallStrain() = delete; //! Constructor with fft_engine ProjectionSmallStrain(FFTEngine_ptr engine, Rcoord lengths); //! Copy constructor ProjectionSmallStrain(const ProjectionSmallStrain & other) = delete; //! Move constructor ProjectionSmallStrain(ProjectionSmallStrain && other) = default; //! Destructor virtual ~ProjectionSmallStrain() = default; //! Copy assignment operator ProjectionSmallStrain & operator=(const ProjectionSmallStrain & other) = delete; //! Move assignment operator ProjectionSmallStrain & operator=(ProjectionSmallStrain && other) = delete; //! initialises the fft engine (plan the transform) - void initialise(FFT_PlanFlags flags = FFT_PlanFlags::estimate) final; + void initialise( + muFFT::FFT_PlanFlags flags = muFFT::FFT_PlanFlags::estimate) final; }; } // namespace muSpectre -#endif // SRC_FFT_PROJECTION_SMALL_STRAIN_HH_ +#endif // SRC_PROJECTION_PROJECTION_SMALL_STRAIN_HH_ diff --git a/src/solver/deprecated_solver_base.cc b/src/solver/deprecated_solver_base.cc index f3b6196..c3699fa 100644 --- a/src/solver/deprecated_solver_base.cc +++ b/src/solver/deprecated_solver_base.cc @@ -1,68 +1,68 @@ /** * @file deprecated_solver_base.cc * * @author Till Junge * * @date 18 Dec 2017 * * @brief definitions for solvers * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "solver/deprecated_solver_base.hh" #include "solver/deprecated_solver_cg.hh" -#include "common/field.hh" -#include "common/iterators.hh" +#include +#include #include #include namespace muSpectre { //--------------------------------------------------------------------------// template DeprecatedSolverBase::DeprecatedSolverBase(Cell_t & cell, Real tol, Uint maxiter, bool verbose) : cell{cell}, tol{tol}, maxiter{maxiter}, verbose{verbose} {} /* ---------------------------------------------------------------------- */ template void DeprecatedSolverBase::reset_counter() { this->counter = 0; } /* ---------------------------------------------------------------------- */ template Uint DeprecatedSolverBase::get_counter() const { return this->counter; } template class DeprecatedSolverBase; // template class DeprecatedSolverBase; template class DeprecatedSolverBase; } // namespace muSpectre diff --git a/src/solver/deprecated_solver_base.hh b/src/solver/deprecated_solver_base.hh index 579680f..57c020e 100644 --- a/src/solver/deprecated_solver_base.hh +++ b/src/solver/deprecated_solver_base.hh @@ -1,160 +1,159 @@ /** * @file deprecated_solver_base.hh * * @author Till Junge * * @date 18 Dec 2017 * * @brief Base class for solvers * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_SOLVER_DEPRECATED_SOLVER_BASE_HH_ #define SRC_SOLVER_DEPRECATED_SOLVER_BASE_HH_ #include "solver/solver_common.hh" -#include "common/common.hh" +#include "common/muSpectre_common.hh" #include "cell/cell_base.hh" -#include "common/tensor_algebra.hh" #include #include namespace muSpectre { /* ---------------------------------------------------------------------- */ /** * Virtual base class for solvers. Any implementation of this interface can be * used with the solver functions prototyped in solvers.hh */ template class DeprecatedSolverBase { public: /** * Enum to describe in what kind the solver relies tangent stiffnesses */ enum class TangentRequirement { NoNeed, NeedEffect, NeedTangents }; using Cell_t = CellBase; //!< Cell type using Ccoord = Ccoord_t; //!< cell coordinates type //! Field collection to store temporary fields in - using Collection_t = GlobalFieldCollection; + using Collection_t = muGrid::GlobalFieldCollection; //! Input vector for solvers using SolvVectorIn = Eigen::Ref; //! Input vector for solvers using SolvVectorInC = Eigen::Ref; //! Output vector for solvers using SolvVectorOut = Eigen::VectorXd; //! Default constructor DeprecatedSolverBase() = delete; //! Constructor with domain resolutions DeprecatedSolverBase(Cell_t & cell, Real tol, Uint maxiter = 0, bool verbose = false); //! Copy constructor DeprecatedSolverBase(const DeprecatedSolverBase & other) = delete; //! Move constructor DeprecatedSolverBase(DeprecatedSolverBase && other) = default; //! Destructor virtual ~DeprecatedSolverBase() = default; //! Copy assignment operator DeprecatedSolverBase & operator=(const DeprecatedSolverBase & other) = delete; //! Move assignment operator DeprecatedSolverBase & operator=(DeprecatedSolverBase && other) = default; //! Allocate fields used during the solution virtual void initialise() { this->collection.initialise(this->cell.get_subdomain_resolutions(), this->cell.get_subdomain_locations()); } //! determine whether this solver requires full tangent stiffnesses bool need_tangents() const { return (this->get_tangent_req() == TangentRequirement::NeedTangents); } //! determine whether this solver requires evaluation of directional tangent bool need_effect() const { return (this->get_tangent_req() == TangentRequirement::NeedEffect); } //! determine whether this solver has no need for tangents bool no_need_tangent() const { return (this->get_tangent_req() == TangentRequirement::NoNeed); } //! returns whether the solver has converged virtual bool has_converged() const = 0; //! reset the iteration counter to zero void reset_counter(); //! get the count of how many solve steps have been executed since //! construction of most recent counter reset Uint get_counter() const; //! executes the solver virtual SolvVectorOut solve(const SolvVectorInC rhs, SolvVectorIn x_0) = 0; //! return a reference to the cell Cell_t & get_cell() { return cell; } //! read the current maximum number of iterations setting Uint get_maxiter() const { return this->maxiter; } //! set the maximum number of iterations void set_maxiter(Uint val) { this->maxiter = val; } //! read the current tolerance setting Real get_tol() const { return this->tol; } //! set the torelance setting void set_tol(Real val) { this->tol = val; } //! returns the name of the solver virtual std::string name() const = 0; protected: //! returns the tangent requirements of this solver virtual TangentRequirement get_tangent_req() const = 0; Cell_t & cell; //!< reference to the cell Real tol; //!< convergence tolerance Uint maxiter; //!< maximum number of iterations bool verbose; //!< whether or not to write information to the std output Uint counter{0}; //!< iteration counter //! storage for internal fields to avoid reallocations between calls Collection_t collection{}; private: }; } // namespace muSpectre #endif // SRC_SOLVER_DEPRECATED_SOLVER_BASE_HH_ diff --git a/src/solver/deprecated_solver_cg.cc b/src/solver/deprecated_solver_cg.cc index 1b3ae91..dc92c93 100644 --- a/src/solver/deprecated_solver_cg.cc +++ b/src/solver/deprecated_solver_cg.cc @@ -1,138 +1,140 @@ /** * @file deprecated_solver_cg.cc * * @author Till Junge * * @date 20 Dec 2017 * * @brief Implementation of cg solver * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "solver/deprecated_solver_cg.hh" #include "solver/solver_common.hh" #include #include #include +#include namespace muSpectre { /* ---------------------------------------------------------------------- */ template DeprecatedSolverCG::DeprecatedSolverCG(Cell_t & cell, Real tol, Uint maxiter, bool verbose) - : Parent(cell, tol, maxiter, verbose), r_k{make_field( + : Parent(cell, tol, maxiter, verbose), r_k{muGrid::make_field( "residual r_k", this->collection)}, - p_k{make_field("search direction r_k", this->collection)}, - Ap_k{make_field("Effect of tangent A*p_k", this->collection)} { - } + p_k{muGrid::make_field("search direction r_k", + this->collection)}, + Ap_k{muGrid::make_field("Effect of tangent A*p_k", + this->collection)} {} /* ---------------------------------------------------------------------- */ template void DeprecatedSolverCG::solve(const Field_t & rhs, Field_t & x_f) { x_f.eigenvec() = this->solve(rhs.eigenvec(), x_f.eigenvec()); } //----------------------------------------------------------------------------// template typename DeprecatedSolverCG::SolvVectorOut DeprecatedSolverCG::solve(const SolvVectorInC rhs, SolvVectorIn x_0) { - const Communicator & comm = this->cell.get_communicator(); + const muFFT::Communicator & comm = this->cell.get_communicator(); // Following implementation of algorithm 5.2 in Nocedal's Numerical // Optimization (p. 112) auto r = this->r_k.eigen(); auto p = this->p_k.eigen(); auto Ap = this->Ap_k.eigen(); typename Field_t::EigenMap_t x(x_0.data(), r.rows(), r.cols()); // initialisation of algo r = this->cell.directional_stiffness_with_copy(x); r -= typename Field_t::ConstEigenMap_t(rhs.data(), r.rows(), r.cols()); p = -r; this->converged = false; Real rdr = comm.sum((r * r).sum()); Real rhs_norm2 = comm.sum(rhs.squaredNorm()); - Real tol2 = ipow(this->tol, 2) * rhs_norm2; + Real tol2 = muGrid::ipow(this->tol, 2) * rhs_norm2; size_t count_width{}; // for output formatting in verbose case if (this->verbose) { count_width = size_t(std::log10(this->maxiter)) + 1; } for (Uint i = 0; i < this->maxiter && (rdr > tol2 || i == 0); ++i, ++this->counter) { Ap = this->cell.directional_stiffness_with_copy(p); Real alpha = rdr / comm.sum((p * Ap).sum()); x += alpha * p; r += alpha * Ap; Real new_rdr = comm.sum((r * r).sum()); Real beta = new_rdr / rdr; rdr = new_rdr; if (this->verbose && comm.rank() == 0) { std::cout << " at CG step " << std::setw(count_width) << i << ": |r|/|b| = " << std::setw(15) << std::sqrt(rdr / rhs_norm2) << ", cg_tol = " << this->tol << std::endl; } p = -r + beta * p; } if (rdr < tol2) { this->converged = true; } else { std::stringstream err{}; err << " After " << this->counter << " steps, the solver " << " FAILED with |r|/|b| = " << std::setw(15) << std::sqrt(rdr / rhs_norm2) << ", cg_tol = " << this->tol << std::endl; throw ConvergenceError("Conjugate gradient has not converged." + err.str()); } return x_0; } /* ---------------------------------------------------------------------- */ template typename DeprecatedSolverCG::Tg_req_t DeprecatedSolverCG::get_tangent_req() const { return tangent_requirement; } template class DeprecatedSolverCG; // template class DeprecatedSolverCG; template class DeprecatedSolverCG; } // namespace muSpectre diff --git a/src/solver/deprecated_solver_cg.hh b/src/solver/deprecated_solver_cg.hh index 2432b25..0e4a48c 100644 --- a/src/solver/deprecated_solver_cg.hh +++ b/src/solver/deprecated_solver_cg.hh @@ -1,120 +1,120 @@ /** * @file deprecated_solver_cg.hh * * @author Till Junge * * @date 20 Dec 2017 * * @brief class for a simple implementation of a conjugate gradient * solver. This follows algorithm 5.2 in Nocedal's Numerical * Optimization (p 112) * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_SOLVER_DEPRECATED_SOLVER_CG_HH_ #define SRC_SOLVER_DEPRECATED_SOLVER_CG_HH_ #include "solver/deprecated_solver_base.hh" -#include "common/communicator.hh" -#include "common/field.hh" +#include +#include #include namespace muSpectre { /** * implements the `muSpectre::DeprecatedSolverBase` interface using a * conjugate gradient solver. This particular class is useful for * trouble shooting, as it can be made very verbose, but for * production runs, it is probably better to use * `muSpectre::DeprecatedSolverCGEigen`. */ template class DeprecatedSolverCG : public DeprecatedSolverBase { public: using Parent = DeprecatedSolverBase; //!< base class //! Input vector for solvers using SolvVectorIn = typename Parent::SolvVectorIn; //! Input vector for solvers using SolvVectorInC = typename Parent::SolvVectorInC; //! Output vector for solvers using SolvVectorOut = typename Parent::SolvVectorOut; using Cell_t = typename Parent::Cell_t; //!< cell type using Ccoord = typename Parent::Ccoord; //!< cell coordinates type //! kind of tangent that is required using Tg_req_t = typename Parent::TangentRequirement; //! cg only needs to handle fields that look like strain and stress - using Field_t = - TensorField; + using Field_t = muGrid::TensorField; //! conjugate gradient needs directional stiffness constexpr static Tg_req_t tangent_requirement{Tg_req_t::NeedEffect}; //! Default constructor DeprecatedSolverCG() = delete; //! Constructor with domain resolutions, etc, DeprecatedSolverCG(Cell_t & cell, Real tol, Uint maxiter = 0, bool verbose = false); //! Copy constructor DeprecatedSolverCG(const DeprecatedSolverCG & other) = delete; //! Move constructor DeprecatedSolverCG(DeprecatedSolverCG && other) = default; //! Destructor virtual ~DeprecatedSolverCG() = default; //! Copy assignment operator DeprecatedSolverCG & operator=(const DeprecatedSolverCG & other) = delete; //! Move assignment operator DeprecatedSolverCG & operator=(DeprecatedSolverCG && other) = default; bool has_converged() const final { return this->converged; } //! actual solver void solve(const Field_t & rhs, Field_t & x); // this simplistic implementation has no initialisation phase so the default // is ok SolvVectorOut solve(const SolvVectorInC rhs, SolvVectorIn x_0) final; std::string name() const final { return "CG"; } protected: //! returns `muSpectre::Tg_req_t::NeedEffect` Tg_req_t get_tangent_req() const final; Field_t & r_k; //!< residual Field_t & p_k; //!< search direction Field_t & Ap_k; //!< effect of tangent on search direction bool converged{false}; //!< whether the solver has converged }; } // namespace muSpectre #endif // SRC_SOLVER_DEPRECATED_SOLVER_CG_HH_ diff --git a/src/solver/deprecated_solver_cg_eigen.hh b/src/solver/deprecated_solver_cg_eigen.hh index 9102c59..c97351a 100644 --- a/src/solver/deprecated_solver_cg_eigen.hh +++ b/src/solver/deprecated_solver_cg_eigen.hh @@ -1,258 +1,259 @@ /** * @file deprecated_solver_cg_eigen.hh * * @author Till Junge * * @date 19 Jan 2018 * * @brief binding to Eigen's conjugate gradient solver * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_SOLVER_DEPRECATED_SOLVER_CG_EIGEN_HH_ #define SRC_SOLVER_DEPRECATED_SOLVER_CG_EIGEN_HH_ #include "solver/deprecated_solver_base.hh" #include +#include // needed for the IterativeSolvers... #include #include namespace muSpectre { template class DeprecatedSolverEigen; template class DeprecatedSolverCGEigen; template class DeprecatedSolverGMRESEigen; template class DeprecatedSolverBiCGSTABEigen; template class DeprecatedSolverDGMRESEigen; template class DeprecatedSolverMINRESEigen; namespace internal { template struct DeprecatedSolver_traits {}; //! traits for the Eigen conjugate gradient solver template struct DeprecatedSolver_traits> { //! Eigen Iterative DeprecatedSolver using DeprecatedSolver = Eigen::ConjugateGradient< typename DeprecatedSolverEigen, DimS, DimM>::Adaptor, Eigen::Lower | Eigen::Upper, Eigen::IdentityPreconditioner>; }; //! traits for the Eigen GMRES solver template struct DeprecatedSolver_traits> { //! Eigen Iterative DeprecatedSolver using DeprecatedSolver = Eigen::GMRES< typename DeprecatedSolverEigen, DimS, DimM>::Adaptor, Eigen::IdentityPreconditioner>; }; //! traits for the Eigen BiCGSTAB solver template struct DeprecatedSolver_traits> { //! Eigen Iterative DeprecatedSolver using DeprecatedSolver = Eigen::BiCGSTAB< typename DeprecatedSolverEigen< DeprecatedSolverBiCGSTABEigen, DimS, DimM>::Adaptor, Eigen::IdentityPreconditioner>; }; //! traits for the Eigen DGMRES solver template struct DeprecatedSolver_traits> { //! Eigen Iterative DeprecatedSolver using DeprecatedSolver = Eigen::DGMRES< typename DeprecatedSolverEigen< DeprecatedSolverDGMRESEigen, DimS, DimM>::Adaptor, Eigen::IdentityPreconditioner>; }; //! traits for the Eigen MINRES solver template struct DeprecatedSolver_traits> { //! Eigen Iterative DeprecatedSolver using DeprecatedSolver = Eigen::MINRES< typename DeprecatedSolverEigen< DeprecatedSolverMINRESEigen, DimS, DimM>::Adaptor, Eigen::Lower | Eigen::Upper, Eigen::IdentityPreconditioner>; }; } // namespace internal /** * base class for iterative solvers from Eigen */ template class DeprecatedSolverEigen : public DeprecatedSolverBase { public: using Parent = DeprecatedSolverBase; //!< base class //! Input vector for solvers using SolvVectorIn = typename Parent::SolvVectorIn; //! Input vector for solvers using SolvVectorInC = typename Parent::SolvVectorInC; //! Output vector for solvers using SolvVectorOut = typename Parent::SolvVectorOut; using Cell_t = typename Parent::Cell_t; //!< cell type using Ccoord = typename Parent::Ccoord; //!< cell coordinates type //! kind of tangent that is required using Tg_req_t = typename Parent::TangentRequirement; //! handle for the cell to fit Eigen's sparse matrix interface using Adaptor = typename Cell_t::Adaptor; //! traits obtained from CRTP using DeprecatedSolver = typename internal::DeprecatedSolver_traits< DeprecatedSolverType>::DeprecatedSolver; //! All Eigen solvers need directional stiffness constexpr static Tg_req_t tangent_requirement{Tg_req_t::NeedEffect}; //! Default constructor DeprecatedSolverEigen() = delete; //! Constructor with domain resolutions, etc, DeprecatedSolverEigen(Cell_t & cell, Real tol, Uint maxiter = 0, bool verbose = false); //! Copy constructor DeprecatedSolverEigen(const DeprecatedSolverEigen & other) = delete; //! Move constructor DeprecatedSolverEigen(DeprecatedSolverEigen && other) = default; //! Destructor virtual ~DeprecatedSolverEigen() = default; //! Copy assignment operator DeprecatedSolverEigen & operator=(const DeprecatedSolverEigen & other) = delete; //! Move assignment operator DeprecatedSolverEigen & operator=(DeprecatedSolverEigen && other) = default; //! returns whether the solver has converged bool has_converged() const final { return this->solver.info() == Eigen::Success; } //! Allocate fields used during the solution void initialise() final; //! executes the solver SolvVectorOut solve(const SolvVectorInC rhs, SolvVectorIn x_0) final; protected: //! returns `muSpectre::Tg_req_t::NeedEffect` Tg_req_t get_tangent_req() const final; Adaptor adaptor; //!< cell handle DeprecatedSolver solver; //!< Eigen's Iterative solver }; /** * Binding to Eigen's conjugate gradient solver */ template class DeprecatedSolverCGEigen : public DeprecatedSolverEigen, DimS, DimM> { public: using DeprecatedSolverEigen, DimS, DimM>::DeprecatedSolverEigen; std::string name() const final { return "CG"; } }; /** * Binding to Eigen's GMRES solver */ template class DeprecatedSolverGMRESEigen : public DeprecatedSolverEigen, DimS, DimM> { public: using DeprecatedSolverEigen, DimS, DimM>::DeprecatedSolverEigen; std::string name() const final { return "GMRES"; } }; /** * Binding to Eigen's BiCGSTAB solver */ template class DeprecatedSolverBiCGSTABEigen : public DeprecatedSolverEigen, DimS, DimM> { public: using DeprecatedSolverEigen, DimS, DimM>::DeprecatedSolverEigen; //! DeprecatedSolver's name std::string name() const final { return "BiCGSTAB"; } }; /** * Binding to Eigen's DGMRES solver */ template class DeprecatedSolverDGMRESEigen : public DeprecatedSolverEigen, DimS, DimM> { public: using DeprecatedSolverEigen, DimS, DimM>::DeprecatedSolverEigen; //! DeprecatedSolver's name std::string name() const final { return "DGMRES"; } }; /** * Binding to Eigen's MINRES solver */ template class DeprecatedSolverMINRESEigen : public DeprecatedSolverEigen, DimS, DimM> { public: using DeprecatedSolverEigen, DimS, DimM>::DeprecatedSolverEigen; //! DeprecatedSolver's name std::string name() const final { return "MINRES"; } }; } // namespace muSpectre #endif // SRC_SOLVER_DEPRECATED_SOLVER_CG_EIGEN_HH_ diff --git a/src/solver/deprecated_solvers.cc b/src/solver/deprecated_solvers.cc index eee0b94..fffaac3 100644 --- a/src/solver/deprecated_solvers.cc +++ b/src/solver/deprecated_solvers.cc @@ -1,397 +1,398 @@ /** * @file solvers.cc * * @author Till Junge * * @date 20 Dec 2017 * * @brief implementation of solver functions * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "solver/deprecated_solvers.hh" #include "solver/deprecated_solver_cg.hh" -#include "common/iterators.hh" +#include #include #include #include +#include namespace muSpectre { template std::vector deprecated_de_geus(CellBase & cell, const GradIncrements & delFs, DeprecatedSolverBase & solver, Real newton_tol, Real equil_tol, Dim_t verbose) { using Field_t = typename MaterialBase::StrainField_t; - const Communicator & comm = cell.get_communicator(); - auto solver_fields{std::make_unique>()}; + const auto & comm = cell.get_communicator(); + auto solver_fields{std::make_unique>()}; solver_fields->initialise(cell.get_subdomain_resolutions(), cell.get_subdomain_locations()); // Corresponds to symbol δF or δε - auto & incrF{make_field("δF", *solver_fields)}; + auto & incrF{muGrid::make_field("δF", *solver_fields)}; // Corresponds to symbol ΔF or Δε - auto & DeltaF{make_field("ΔF", *solver_fields)}; + auto & DeltaF{muGrid::make_field("ΔF", *solver_fields)}; // field to store the rhs for cg calculations - auto & rhs{make_field("rhs", *solver_fields)}; + auto & rhs{muGrid::make_field("rhs", *solver_fields)}; solver.initialise(); if (solver.get_maxiter() == 0) { solver.set_maxiter(cell.size() * DimM * DimM * 10); } size_t count_width{}; const auto form{cell.get_formulation()}; std::string strain_symb{}; if (verbose > 0 && comm.rank() == 0) { // setup of algorithm 5.2 in Nocedal, Numerical Optimization (p. 111) std::cout << "de Geus-" << solver.name() << " for "; switch (form) { case Formulation::small_strain: { strain_symb = "ε"; std::cout << "small"; break; } case Formulation::finite_strain: { strain_symb = "F"; std::cout << "finite"; break; } default: throw SolverError("unknown formulation"); break; } std::cout << " strain with" << std::endl << "newton_tol = " << newton_tol << ", cg_tol = " << solver.get_tol() << " maxiter = " << solver.get_maxiter() << " and Δ" << strain_symb << " =" << std::endl; for (auto && tup : akantu::enumerate(delFs)) { auto && counter{std::get<0>(tup)}; auto && grad{std::get<1>(tup)}; std::cout << "Step " << counter + 1 << ":" << std::endl << grad << std::endl; } count_width = size_t(std::log10(solver.get_maxiter())) + 1; } // initialise F = I or ε = 0 auto & F{cell.get_strain()}; switch (form) { case Formulation::finite_strain: { F.get_map() = Matrices::I2(); break; } case Formulation::small_strain: { F.get_map() = Matrices::I2().Zero(); for (const auto & delF : delFs) { if (!check_symmetry(delF)) { throw SolverError("all Δε must be symmetric!"); } } break; } default: throw SolverError("Unknown formulation"); break; } // initialise return value std::vector ret_val{}; Grad_t previous_grad{Grad_t::Zero()}; for (const auto & delF : delFs) { // incremental loop std::string message{"Has not converged"}; Real incrNorm{2 * newton_tol}, gradNorm{1}; Real stressNorm{2 * equil_tol}; bool has_converged{false}; auto convergence_test = [&incrNorm, &gradNorm, &newton_tol, &stressNorm, &equil_tol, &message, &has_converged]() { bool incr_test = incrNorm / gradNorm <= newton_tol; bool stress_test = stressNorm < equil_tol; if (incr_test) { message = "Residual tolerance reached"; } else if (stress_test) { message = "Reached stress divergence tolerance"; } has_converged = incr_test || stress_test; return has_converged; }; Uint newt_iter{0}; for (; (newt_iter < solver.get_maxiter()) && (!has_converged || (newt_iter == 1)); ++newt_iter) { // obtain material response auto res_tup{cell.evaluate_stress_tangent(F)}; auto & P{std::get<0>(res_tup)}; auto & K{std::get<1>(res_tup)}; auto tangent_effect = [&cell, &K](const Field_t & dF, Field_t & dP) { cell.directional_stiffness(K, dF, dP); }; if (newt_iter == 0) { DeltaF.get_map() = -(delF - previous_grad); // neg sign because rhs tangent_effect(DeltaF, rhs); stressNorm = std::sqrt(comm.sum(rhs.eigen().matrix().squaredNorm())); if (convergence_test()) { break; } incrF.eigenvec() = solver.solve(rhs.eigenvec(), incrF.eigenvec()); F.eigen() -= DeltaF.eigen(); } else { rhs.eigen() = -P.eigen(); cell.project(rhs); stressNorm = std::sqrt(comm.sum(rhs.eigen().matrix().squaredNorm())); if (convergence_test()) { break; } incrF.eigen() = 0; incrF.eigenvec() = solver.solve(rhs.eigenvec(), incrF.eigenvec()); } F.eigen() += incrF.eigen(); incrNorm = std::sqrt(comm.sum(incrF.eigen().matrix().squaredNorm())); gradNorm = std::sqrt(comm.sum(F.eigen().matrix().squaredNorm())); if (verbose > 0 && comm.rank() == 0) { std::cout << "at Newton step " << std::setw(count_width) << newt_iter << ", |δ" << strain_symb << "|/|Δ" << strain_symb << "| = " << std::setw(17) << incrNorm / gradNorm << ", tol = " << newton_tol << std::endl; if (verbose - 1 > 1) { std::cout << "<" << strain_symb << "> =" << std::endl << F.get_map().mean() << std::endl; } } convergence_test(); } // update previous gradient previous_grad = delF; ret_val.push_back(OptimizeResult{ F.eigen(), cell.get_stress().eigen(), has_converged, Int(has_converged), message, newt_iter, solver.get_counter(), form}); // store history variables here cell.save_history_variables(); } return ret_val; } //! instantiation for two-dimensional cells template std::vector deprecated_de_geus(CellBase & cell, const GradIncrements & delF0, DeprecatedSolverBase & solver, Real newton_tol, Real equil_tol, Dim_t verbose); //! instantiation for three-dimensional cells template std::vector deprecated_de_geus(CellBase & cell, const GradIncrements & delF0, DeprecatedSolverBase & solver, Real newton_tol, Real equil_tol, Dim_t verbose); /* ---------------------------------------------------------------------- */ template std::vector deprecated_newton_cg(CellBase & cell, const GradIncrements & delFs, DeprecatedSolverBase & solver, Real newton_tol, Real equil_tol, Dim_t verbose) { using Field_t = typename MaterialBase::StrainField_t; - const Communicator & comm = cell.get_communicator(); - auto solver_fields{std::make_unique>()}; + const auto & comm = cell.get_communicator(); + auto solver_fields{std::make_unique>()}; solver_fields->initialise(cell.get_subdomain_resolutions(), cell.get_subdomain_locations()); // Corresponds to symbol δF or δε - auto & incrF{make_field("δF", *solver_fields)}; + auto & incrF{muGrid::make_field("δF", *solver_fields)}; // field to store the rhs for cg calculations - auto & rhs{make_field("rhs", *solver_fields)}; + auto & rhs{muGrid::make_field("rhs", *solver_fields)}; solver.initialise(); if (solver.get_maxiter() == 0) { solver.set_maxiter(cell.size() * DimM * DimM * 10); } size_t count_width{}; const auto form{cell.get_formulation()}; std::string strain_symb{}; if (verbose > 0 && comm.rank() == 0) { // setup of algorithm 5.2 in Nocedal, Numerical Optimization (p. 111) std::cout << "Newton-" << solver.name() << " for "; switch (form) { case Formulation::small_strain: { strain_symb = "ε"; std::cout << "small"; break; } case Formulation::finite_strain: { strain_symb = "F"; std::cout << "finite"; break; } default: throw SolverError("unknown formulation"); break; } std::cout << " strain with" << std::endl << "newton_tol = " << newton_tol << ", cg_tol = " << solver.get_tol() << " maxiter = " << solver.get_maxiter() << " and Δ" << strain_symb << " =" << std::endl; for (auto && tup : akantu::enumerate(delFs)) { auto && counter{std::get<0>(tup)}; auto && grad{std::get<1>(tup)}; std::cout << "Step " << counter + 1 << ":" << std::endl << grad << std::endl; } count_width = size_t(std::log10(solver.get_maxiter())) + 1; } // initialise F = I or ε = 0 auto & F{cell.get_strain()}; switch (cell.get_formulation()) { case Formulation::finite_strain: { F.get_map() = Matrices::I2(); break; } case Formulation::small_strain: { F.get_map() = Matrices::I2().Zero(); for (const auto & delF : delFs) { if (!check_symmetry(delF)) { throw SolverError("all Δε must be symmetric!"); } } break; } default: throw SolverError("Unknown formulation"); break; } // initialise return value std::vector ret_val{}; Grad_t previous_grad{Grad_t::Zero()}; for (const auto & delF : delFs) { // incremental loop // apply macroscopic strain increment for (auto && grad : F.get_map()) { grad += delF - previous_grad; } std::string message{"Has not converged"}; Real incrNorm{2 * newton_tol}, gradNorm{1}; Real stressNorm{2 * equil_tol}; bool has_converged{false}; auto convergence_test = [&incrNorm, &gradNorm, &newton_tol, &stressNorm, &equil_tol, &message, &has_converged]() { bool incr_test = incrNorm / gradNorm <= newton_tol; bool stress_test = stressNorm < equil_tol; if (incr_test) { message = "Residual tolerance reached"; } else if (stress_test) { message = "Reached stress divergence tolerance"; } has_converged = incr_test || stress_test; return has_converged; }; Uint newt_iter{0}; for (; newt_iter < solver.get_maxiter() && !has_converged; ++newt_iter) { // obtain material response auto res_tup{cell.evaluate_stress_tangent(F)}; auto & P{std::get<0>(res_tup)}; rhs.eigen() = -P.eigen(); cell.project(rhs); stressNorm = std::sqrt(comm.sum(rhs.eigen().matrix().squaredNorm())); if (convergence_test()) { break; } incrF.eigen() = 0; incrF.eigenvec() = solver.solve(rhs.eigenvec(), incrF.eigenvec()); F.eigen() += incrF.eigen(); incrNorm = std::sqrt(comm.sum(incrF.eigen().matrix().squaredNorm())); gradNorm = std::sqrt(comm.sum(F.eigen().matrix().squaredNorm())); if (verbose > 0 && comm.rank() == 0) { std::cout << "at Newton step " << std::setw(count_width) << newt_iter << ", |δ" << strain_symb << "|/|Δ" << strain_symb << "| = " << std::setw(17) << incrNorm / gradNorm << ", tol = " << newton_tol << std::endl; if (verbose - 1 > 1) { std::cout << "<" << strain_symb << "> =" << std::endl << F.get_map().mean() << std::endl; } } convergence_test(); } // update previous gradient previous_grad = delF; ret_val.push_back(OptimizeResult{F.eigen(), cell.get_stress().eigen(), convergence_test(), Int(convergence_test()), message, newt_iter, solver.get_counter(), form}); // store history variables for next load increment cell.save_history_variables(); } return ret_val; } //! instantiation for two-dimensional cells template std::vector deprecated_newton_cg(CellBase & cell, const GradIncrements & delF0, DeprecatedSolverBase & solver, Real newton_tol, Real equil_tol, Dim_t verbose); //! instantiation for three-dimensional cells template std::vector deprecated_newton_cg(CellBase & cell, const GradIncrements & delF0, DeprecatedSolverBase & solver, Real newton_tol, Real equil_tol, Dim_t verbose); } // namespace muSpectre diff --git a/src/solver/solver_cg.cc b/src/solver/solver_cg.cc index 88ae0ce..efbf50c 100644 --- a/src/solver/solver_cg.cc +++ b/src/solver/solver_cg.cc @@ -1,110 +1,111 @@ /** * file solver_cg.cc * * @author Till Junge * * @date 24 Apr 2018 * * @brief implements SolverCG * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "solver/solver_cg.hh" -#include "common/communicator.hh" +#include #include #include +#include namespace muSpectre { /* ---------------------------------------------------------------------- */ SolverCG::SolverCG(Cell & cell, Real tol, Uint maxiter, bool verbose) : Parent(cell, tol, maxiter, verbose), r_k(cell.get_nb_dof()), p_k(cell.get_nb_dof()), Ap_k(cell.get_nb_dof()), x_k(cell.get_nb_dof()) {} /* ---------------------------------------------------------------------- */ auto SolverCG::solve(const ConstVector_ref rhs) -> Vector_map { this->x_k.setZero(); - const Communicator & comm = this->cell.get_communicator(); + const auto & comm = this->cell.get_communicator(); // Following implementation of algorithm 5.2 in Nocedal's // Numerical Optimization (p. 112) // initialisation of algorithm this->r_k = (this->cell.evaluate_projected_directional_stiffness(this->x_k) - rhs); this->p_k = -this->r_k; this->converged = false; Real rdr = comm.sum(this->r_k.dot(this->r_k)); Real rhs_norm2 = comm.sum(rhs.squaredNorm()); - Real tol2 = ipow(this->tol, 2) * rhs_norm2; + Real tol2 = muGrid::ipow(this->tol, 2) * rhs_norm2; size_t count_width{}; // for output formatting in verbose case if (this->verbose) { count_width = size_t(std::log10(this->maxiter)) + 1; } for (Uint i = 0; i < this->maxiter && (rdr > tol2 || i == 0); ++i, ++this->counter) { this->Ap_k = this->cell.evaluate_projected_directional_stiffness(this->p_k); Real alpha = rdr / comm.sum(this->p_k.dot(this->Ap_k)); this->x_k += alpha * this->p_k; this->r_k += alpha * this->Ap_k; Real new_rdr = comm.sum(this->r_k.dot(this->r_k)); Real beta = new_rdr / rdr; rdr = new_rdr; if (this->verbose && comm.rank() == 0) { std::cout << " at CG step " << std::setw(count_width) << i << ": |r|/|b| = " << std::setw(15) << std::sqrt(rdr / rhs_norm2) << ", cg_tol = " << this->tol << std::endl; } this->p_k = -this->r_k + beta * this->p_k; } if (rdr < tol2) { this->converged = true; } else { std::stringstream err{}; err << " After " << this->counter << " steps, the solver " << " FAILED with |r|/|b| = " << std::setw(15) << std::sqrt(rdr / rhs_norm2) << ", cg_tol = " << this->tol << std::endl; throw ConvergenceError("Conjugate gradient has not converged." + err.str()); } return Vector_map(this->x_k.data(), this->x_k.size()); } } // namespace muSpectre diff --git a/src/solver/solver_common.hh b/src/solver/solver_common.hh index 6744387..150a37e 100644 --- a/src/solver/solver_common.hh +++ b/src/solver/solver_common.hh @@ -1,103 +1,102 @@ /** * @file solver_common.hh * * @author Till Junge * * @date 28 Dec 2017 * * @brief Errors raised by solvers and other common utilities * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_SOLVER_SOLVER_COMMON_HH_ #define SRC_SOLVER_SOLVER_COMMON_HH_ -#include "common/common.hh" -#include "common/tensor_algebra.hh" +#include "common/muSpectre_common.hh" #include #include namespace muSpectre { /** * emulates scipy.optimize.OptimizeResult */ struct OptimizeResult { //! Strain ε or Gradient F at solution Eigen::ArrayXXd grad; //! Cauchy stress σ or first Piola-Kirchhoff stress P at solution Eigen::ArrayXXd stress; //! whether or not the solver exited successfully bool success; //! Termination status of the optimizer. Its value depends on the //! underlying solver. Refer to message for details. Int status; //! Description of the cause of the termination. std::string message; //! number of iterations Uint nb_it; //! number of cell evaluations Uint nb_fev; //! continuum mechanic flag Formulation formulation; }; /** * Field type that solvers expect gradients to be expressed in */ template using Grad_t = Matrices::Tens2_t; /** * multiple increments can be submitted at once (useful for * path-dependent materials) */ template using GradIncrements = std::vector, Eigen::aligned_allocator>>; /* ---------------------------------------------------------------------- */ class SolverError : public std::runtime_error { using runtime_error::runtime_error; }; /* ---------------------------------------------------------------------- */ class ConvergenceError : public SolverError { using SolverError::SolverError; }; /* ---------------------------------------------------------------------- */ /** * check whether a strain is symmetric, for the purposes of small * strain problems */ bool check_symmetry(const Eigen::Ref & eps, Real rel_tol = 1e-8); } // namespace muSpectre #endif // SRC_SOLVER_SOLVER_COMMON_HH_ diff --git a/src/solver/solver_eigen.hh b/src/solver/solver_eigen.hh index d2b43ba..cf530bd 100644 --- a/src/solver/solver_eigen.hh +++ b/src/solver/solver_eigen.hh @@ -1,207 +1,208 @@ /** * file solver_eigen.hh * * @author Till Junge * * @date 15 May 2018 * * @brief Bindings to Eigen's iterative solvers * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef SRC_SOLVER_SOLVER_EIGEN_HH_ #define SRC_SOLVER_SOLVER_EIGEN_HH_ #include "solver/solver_base.hh" #include "cell/cell_base.hh" #include +#include #include namespace muSpectre { template class SolverEigen; class SolverCGEigen; class SolverGMRESEigen; class SolverBiCGSTABEigen; class SolverDGMRESEigen; class SolverMINRESEigen; namespace internal { template struct Solver_traits {}; //! traits for the Eigen conjugate gradient solver template <> struct Solver_traits { //! Eigen Iterative Solver using Solver = Eigen::ConjugateGradient; }; //! traits for the Eigen GMRES solver template <> struct Solver_traits { //! Eigen Iterative Solver using Solver = Eigen::GMRES; }; //! traits for the Eigen BiCGSTAB solver template <> struct Solver_traits { //! Eigen Iterative Solver using Solver = Eigen::BiCGSTAB; }; //! traits for the Eigen DGMRES solver template <> struct Solver_traits { //! Eigen Iterative Solver using Solver = Eigen::DGMRES; }; //! traits for the Eigen MINRES solver template <> struct Solver_traits { //! Eigen Iterative Solver using Solver = Eigen::MINRES; }; } // namespace internal /** * base class for iterative solvers from Eigen */ template class SolverEigen : public SolverBase { public: using Parent = SolverBase; //!< base class //! traits obtained from CRTP using Solver = typename internal::Solver_traits::Solver; //! Input vectors for solver using ConstVector_ref = Parent::ConstVector_ref; //! Output vector for solver using Vector_map = Parent::Vector_map; //! storage for output vector using Vector_t = Parent::Vector_t; //! Default constructor SolverEigen() = delete; //! Constructor with domain resolutions, etc, SolverEigen(Cell & cell, Real tol, Uint maxiter = 0, bool verbose = false); //! Copy constructor SolverEigen(const SolverEigen & other) = delete; //! Move constructor SolverEigen(SolverEigen && other) = default; //! Destructor virtual ~SolverEigen() = default; //! Copy assignment operator SolverEigen & operator=(const SolverEigen & other) = delete; //! Move assignment operator SolverEigen & operator=(SolverEigen && other) = default; //! Allocate fields used during the solution void initialise() final; //! executes the solver Vector_map solve(const ConstVector_ref rhs) final; protected: Cell::Adaptor adaptor; //!< cell handle Solver solver; //!< Eigen's Iterative solver Vector_t result; //!< storage for result }; /** * Binding to Eigen's conjugate gradient solver */ class SolverCGEigen : public SolverEigen { public: using SolverEigen::SolverEigen; std::string get_name() const final { return "CG"; } }; /** * Binding to Eigen's GMRES solver */ class SolverGMRESEigen : public SolverEigen { public: using SolverEigen::SolverEigen; std::string get_name() const final { return "GMRES"; } }; /** * Binding to Eigen's BiCGSTAB solver */ class SolverBiCGSTABEigen : public SolverEigen { public: using SolverEigen::SolverEigen; //! Solver's name std::string get_name() const final { return "BiCGSTAB"; } }; /** * Binding to Eigen's DGMRES solver */ class SolverDGMRESEigen : public SolverEigen { public: using SolverEigen::SolverEigen; //! Solver's name std::string get_name() const final { return "DGMRES"; } }; /** * Binding to Eigen's MINRES solver */ class SolverMINRESEigen : public SolverEigen { public: using SolverEigen::SolverEigen; //! Solver's name std::string get_name() const final { return "MINRES"; } }; } // namespace muSpectre #endif // SRC_SOLVER_SOLVER_EIGEN_HH_ diff --git a/src/solver/solvers.cc b/src/solver/solvers.cc index d8d1cd3..bd2de08 100644 --- a/src/solver/solvers.cc +++ b/src/solver/solvers.cc @@ -1,482 +1,484 @@ /** * file solvers.cc * * @author Till Junge * * @date 24 Apr 2018 * * @brief implementation of dynamic newton-cg solver * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "solver/solvers.hh" -#include "common/iterators.hh" + +#include #include #include +#include namespace muSpectre { Eigen::IOFormat format(Eigen::FullPrecision, 0, ", ", ",\n", "[", "]", "[", "]"); //--------------------------------------------------------------------------// std::vector newton_cg(Cell & cell, const LoadSteps_t & load_steps, SolverBase & solver, Real newton_tol, Real equil_tol, Dim_t verbose) { - const Communicator & comm = cell.get_communicator(); + const auto & comm = cell.get_communicator(); using Vector_t = Eigen::Matrix; using Matrix_t = Eigen::Matrix; // Corresponds to symbol δF or δε Vector_t incrF(cell.get_nb_dof()); // field to store the rhs for cg calculations Vector_t rhs(cell.get_nb_dof()); solver.initialise(); size_t count_width{}; const auto form{cell.get_formulation()}; std::string strain_symb{}; if (verbose > 0 && comm.rank() == 0) { // setup of algorithm 5.2 in Nocedal, Numerical Optimization (p. 111) std::cout << "Newton-" << solver.get_name() << " for "; switch (form) { case Formulation::small_strain: { strain_symb = "ε"; std::cout << "small"; break; } case Formulation::finite_strain: { strain_symb = "F"; std::cout << "finite"; break; } default: throw SolverError("unknown formulation"); break; } std::cout << " strain with" << std::endl << "newton_tol = " << newton_tol << ", cg_tol = " << solver.get_tol() << " maxiter = " << solver.get_maxiter() << " and " << strain_symb << " from " << strain_symb << "₁ =" << std::endl << load_steps.front() << std::endl << " to " << strain_symb << "ₙ =" << std::endl << load_steps.back() << std::endl << "in increments of Δ" << strain_symb << " =" << std::endl << (load_steps.back() - load_steps.front()) / load_steps.size() << std::endl; count_width = size_t(std::log10(solver.get_maxiter())) + 1; } auto shape{cell.get_strain_shape()}; switch (form) { case Formulation::finite_strain: { cell.set_uniform_strain(Matrix_t::Identity(shape[0], shape[1])); for (const auto & delF : load_steps) { if (not((delF.rows() == shape[0]) and(delF.cols() == shape[1]))) { std::stringstream err{}; err << "Load increments need to be given in " << shape[0] << "×" << shape[1] << " matrices, but I got a " << delF.rows() << "×" << delF.cols() << " matrix:" << std::endl << delF; throw SolverError(err.str()); } } break; } case Formulation::small_strain: { cell.set_uniform_strain(Matrix_t::Zero(shape[0], shape[1])); for (const auto & delF : load_steps) { if (not((delF.rows() == shape[0]) and(delF.cols() == shape[1]))) { std::stringstream err{}; err << "Load increments need to be given in " << shape[0] << "×" << shape[1] << " matrices, but I got a " << delF.rows() << "×" << delF.cols() << " matrix:" << std::endl << delF; throw SolverError(err.str()); } if (not check_symmetry(delF)) { throw SolverError("all Δε must be symmetric!"); } } break; } default: throw SolverError("Unknown strain measure"); break; } // initialise return value std::vector ret_val{}; // storage for the previous mean strain (to compute ΔF or Δε) Matrix_t previous_macro_strain{load_steps.back().Zero(shape[0], shape[1])}; auto F{cell.get_strain_vector()}; //! incremental loop for (const auto & tup : akantu::enumerate(load_steps)) { const auto & strain_step{std::get<0>(tup)}; const auto & macro_strain{std::get<1>(tup)}; if ((verbose > 0) and (comm.rank() == 0)) { std::cout << "at Load step " << std::setw(count_width) << strain_step + 1 << std::endl; } - using StrainMap_t = RawFieldMap>; + using StrainMap_t = muGrid::RawFieldMap>; for (auto && strain : StrainMap_t(F, shape[0], shape[1])) { strain += macro_strain - previous_macro_strain; } std::string message{"Has not converged"}; Real incr_norm{2 * newton_tol}, grad_norm{1}; Real stress_norm{2 * equil_tol}; bool has_converged{false}; auto convergence_test = [&incr_norm, &grad_norm, &newton_tol, &stress_norm, &equil_tol, &message, &has_converged]() { bool incr_test = incr_norm / grad_norm <= newton_tol; bool stress_test = stress_norm < equil_tol; if (incr_test) { message = "Residual tolerance reached"; } else if (stress_test) { message = "Reached stress divergence tolerance"; } has_converged = incr_test || stress_test; return has_converged; }; Uint newt_iter{0}; for (; newt_iter < solver.get_maxiter() && !has_converged; ++newt_iter) { // obtain material response auto res_tup{cell.evaluate_stress_tangent()}; auto & P{std::get<0>(res_tup)}; rhs = -P; cell.apply_projection(rhs); stress_norm = std::sqrt(comm.sum(rhs.squaredNorm())); if (convergence_test()) { break; } try { incrF = solver.solve(rhs); } catch (ConvergenceError & error) { std::stringstream err{}; err << "Failure at load step " << strain_step + 1 << " of " << load_steps.size() << ". In Newton-Raphson step " << newt_iter << ":" << std::endl << error.what() << std::endl << "The applied boundary condition is Δ" << strain_symb << " =" << std::endl << macro_strain << std::endl << "and the load increment is Δ" << strain_symb << " =" << std::endl << macro_strain - previous_macro_strain << std::endl; throw ConvergenceError(err.str()); } F += incrF; incr_norm = std::sqrt(comm.sum(incrF.squaredNorm())); grad_norm = std::sqrt(comm.sum(F.squaredNorm())); if ((verbose > 1) and (comm.rank() == 0)) { std::cout << "at Newton step " << std::setw(count_width) << newt_iter << ", |δ" << strain_symb << "|/|Δ" << strain_symb << "| = " << std::setw(17) << incr_norm / grad_norm << ", tol = " << newton_tol << std::endl; if (verbose - 1 > 1) { std::cout << "<" << strain_symb << "> =" << std::endl << StrainMap_t(F, shape[0], shape[1]).mean() << std::endl; } } convergence_test(); } if (newt_iter == solver.get_maxiter()) { std::stringstream err{}; err << "Failure at load step " << strain_step + 1 << " of " << load_steps.size() << ". Newton-Raphson failed to converge. " << "The applied boundary condition is Δ" << strain_symb << " =" << std::endl << macro_strain << std::endl << "and the load increment is Δ" << strain_symb << " =" << std::endl << macro_strain - previous_macro_strain << std::endl; throw ConvergenceError(err.str()); } // update previous macroscopic strain previous_macro_strain = macro_strain; // store results ret_val.emplace_back( OptimizeResult{F, cell.get_stress_vector(), convergence_test(), Int(convergence_test()), message, newt_iter, solver.get_counter(), form}); // store history variables for next load increment cell.save_history_variables(); } return ret_val; } //----------------------------------------------------------------------------// std::vector de_geus(Cell & cell, const LoadSteps_t & load_steps, SolverBase & solver, Real newton_tol, Real equil_tol, Dim_t verbose) { - const Communicator & comm = cell.get_communicator(); + const auto & comm = cell.get_communicator(); using Vector_t = Eigen::Matrix; using Matrix_t = Eigen::Matrix; // Corresponds to symbol δF or δε Vector_t incrF(cell.get_nb_dof()); // Corresponds to symbol ΔF or Δε Vector_t DeltaF(cell.get_nb_dof()); // field to store the rhs for cg calculations Vector_t rhs(cell.get_nb_dof()); solver.initialise(); size_t count_width{}; const auto form{cell.get_formulation()}; std::string strain_symb{}; if (verbose > 0 && comm.rank() == 0) { // setup of algorithm 5.2 in Nocedal, Numerical Optimization (p. 111) std::cout << "de Geus-" << solver.get_name() << " for "; switch (form) { case Formulation::small_strain: { strain_symb = "ε"; std::cout << "small"; break; } case Formulation::finite_strain: { strain_symb = "F"; std::cout << "finite"; break; } default: throw SolverError("unknown formulation"); break; } std::cout << " strain with" << std::endl << "newton_tol = " << newton_tol << ", cg_tol = " << solver.get_tol() << " maxiter = " << solver.get_maxiter() << " and " << strain_symb << " from " << strain_symb << "₁ =" << std::endl << load_steps.front() << std::endl << " to " << strain_symb << "ₙ =" << std::endl << load_steps.back() << std::endl << "in increments of Δ" << strain_symb << " =" << std::endl << (load_steps.back() - load_steps.front()) / load_steps.size() << std::endl; count_width = size_t(std::log10(solver.get_maxiter())) + 1; } auto shape{cell.get_strain_shape()}; Matrix_t default_strain_val{}; switch (form) { case Formulation::finite_strain: { cell.set_uniform_strain(Matrix_t::Identity(shape[0], shape[1])); for (const auto & delF : load_steps) { auto rows = delF.rows(); auto cols = delF.cols(); if (not((rows == shape[0]) and(cols == shape[1]))) { std::stringstream err{}; err << "Load increments need to be given in " << shape[0] << "×" << shape[1] << " matrices, but I got a " << delF.rows() << "×" << delF.cols() << " matrix:" << std::endl << delF; throw SolverError(err.str()); } } break; } case Formulation::small_strain: { cell.set_uniform_strain(Matrix_t::Zero(shape[0], shape[1])); for (const auto & delF : load_steps) { if (not((delF.rows() == shape[0]) and(delF.cols() == shape[1]))) { std::stringstream err{}; err << "Load increments need to be given in " << shape[0] << "×" << shape[1] << " matrices, but I got a " << delF.rows() << "×" << delF.cols() << " matrix:" << std::endl << delF; throw SolverError(err.str()); } if (not check_symmetry(delF)) { throw SolverError("all Δε must be symmetric!"); } } break; } default: throw SolverError("Unknown strain measure"); break; } // initialise return value std::vector ret_val{}; // storage for the previous mean strain (to compute ΔF or Δε) Matrix_t previous_macro_strain{load_steps.back().Zero(shape[0], shape[1])}; auto F{cell.get_strain_vector()}; //! incremental loop for (const auto & tup : akantu::enumerate(load_steps)) { const auto & strain_step{std::get<0>(tup)}; const auto & macro_strain{std::get<1>(tup)}; - using StrainMap_t = RawFieldMap>; + using StrainMap_t = muGrid::RawFieldMap>; if ((verbose > 0) and (comm.rank() == 0)) { std::cout << "at Load step " << std::setw(count_width) << strain_step + 1 << ", " << strain_symb << " =" << std::endl << (macro_strain + default_strain_val).format(format) << std::endl; } std::string message{"Has not converged"}; Real incr_norm{2 * newton_tol}, grad_norm{1}; Real stress_norm{2 * equil_tol}; bool has_converged{false}; auto convergence_test = [&incr_norm, &grad_norm, &newton_tol, &stress_norm, &equil_tol, &message, &has_converged]() { bool incr_test = incr_norm / grad_norm <= newton_tol; bool stress_test = stress_norm < equil_tol; if (incr_test) { message = "Residual tolerance reached"; } else if (stress_test) { message = "Reached stress divergence tolerance"; } has_converged = incr_test || stress_test; return has_converged; }; Uint newt_iter{0}; for (; ((newt_iter < solver.get_maxiter()) and (!has_converged)) or (newt_iter < 2); ++newt_iter) { // obtain material response auto res_tup{cell.evaluate_stress_tangent()}; auto & P{std::get<0>(res_tup)}; try { if (newt_iter == 0) { for (auto && strain : StrainMap_t(DeltaF, shape[0], shape[1])) { strain = macro_strain - previous_macro_strain; } rhs = -cell.evaluate_projected_directional_stiffness(DeltaF); F += DeltaF; stress_norm = std::sqrt(comm.sum(rhs.matrix().squaredNorm())); if (stress_norm < equil_tol) { incrF.setZero(); } else { incrF = solver.solve(rhs); } } else { rhs = -P; cell.apply_projection(rhs); stress_norm = std::sqrt(comm.sum(rhs.matrix().squaredNorm())); if (stress_norm < equil_tol) { incrF.setZero(); } else { incrF = solver.solve(rhs); } } } catch (ConvergenceError & error) { std::stringstream err{}; err << "Failure at load step " << strain_step + 1 << " of " << load_steps.size() << ". In Newton-Raphson step " << newt_iter << ":" << std::endl << error.what() << std::endl << "The applied boundary condition is Δ" << strain_symb << " =" << std::endl << macro_strain << std::endl << "and the load increment is Δ" << strain_symb << " =" << std::endl << macro_strain - previous_macro_strain << std::endl; throw ConvergenceError(err.str()); } F += incrF; incr_norm = std::sqrt(comm.sum(incrF.squaredNorm())); grad_norm = std::sqrt(comm.sum(F.squaredNorm())); if ((verbose > 0) and (comm.rank() == 0)) { std::cout << "at Newton step " << std::setw(count_width) << newt_iter << ", |δ" << strain_symb << "|/|Δ" << strain_symb << "| = " << std::setw(17) << incr_norm / grad_norm << ", tol = " << newton_tol << std::endl; if (verbose - 1 > 1) { std::cout << "<" << strain_symb << "> =" << std::endl << StrainMap_t(F, shape[0], shape[1]).mean() << std::endl; } } convergence_test(); } if (newt_iter == solver.get_maxiter()) { std::stringstream err{}; err << "Failure at load step " << strain_step + 1 << " of " << load_steps.size() << ". Newton-Raphson failed to converge. " << "The applied boundary condition is Δ" << strain_symb << " =" << std::endl << macro_strain << std::endl << "and the load increment is Δ" << strain_symb << " =" << std::endl << macro_strain - previous_macro_strain << std::endl; throw ConvergenceError(err.str()); } // update previous macroscopic strain previous_macro_strain = macro_strain; // store results ret_val.emplace_back( OptimizeResult{F, cell.get_stress_vector(), convergence_test(), Int(convergence_test()), message, newt_iter, solver.get_counter(), form}); // store history variables for next load increment cell.save_history_variables(); } return ret_val; } } // namespace muSpectre diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt new file mode 100644 index 0000000..468a4a4 --- /dev/null +++ b/tests/CMakeLists.txt @@ -0,0 +1,122 @@ +# ============================================================================= +# file CMakeLists.txt +# +# @author Till Junge +# +# @date 08 Jan 2018 +# +# @brief Main configuration file +# +# @section LICENSE +# +# Copyright © 2018 Till Junge +# +# µSpectre is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public License as +# published by the Free Software Foundation, either version 3, or (at +# your option) any later version. +# +# µSpectre is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with µSpectre; see the file COPYING. If not, write to the +# Free Software Foundation, Inc., 59 Temple Place - Suite 330, +# Boston, MA 02111-1307, USA. +# +# Additional permission under GNU GPL version 3 section 7 +# +# If you modify this Program, or any covered work, by linking or combining it +# with proprietary FFT implementations or numerical libraries, containing parts +# covered by the terms of those libraries' licenses, the licensors of this +# Program grant you additional permission to convey the resulting work. +# ============================================================================= + +find_package(Boost COMPONENTS unit_test_framework REQUIRED) + +function(get_test_name test_name test_fname prefix) + get_filename_component(test_fname_we ${test_fname} NAME_WE) + string(REGEX REPLACE "(${prefix}_?)(.*)" "\\2" _test_name "${test_fname_we}") + set(${test_name} ${_test_name} PARENT_SCOPE) +endfunction() + +add_subdirectory(libmugrid) +if(MUCHOICE MATCHES "muGrid") + return() +endif() + +add_subdirectory(libmufft) +if(MUCHOICE MATCHES "muFFT") + return() +endif() + +set(muspectre_tests) + +macro(muSpectre_add_test) + muTools_add_test(${ARGN} LINK_LIBRARIES ${MUSPECTRE_NAMESPACE}muSpectre TEST_LIST muspectre_tests) +endmacro() + + +# build library tests +file(GLOB TEST_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/test_*.cc") +muSpectre_add_test(main_test_suite + SOURCES main_test_suite.cc ${TEST_SRCS} + TYPE BOOST --report_level=detailed) + +muSpectre_add_test(mattb_test + SOURCES main_test_suite.cc test_materials_toolbox.cc + TYPE BOOST --report_level=detailed) + +############################################################################## +# build py_comparison tests +file(GLOB PY_COMP_TEST_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/py_comparison_*.cc") +find_package(PythonInterp ${MUSPECTRE_PYTHON_MAJOR_VERSION} REQUIRED) +foreach(py_comp_test ${PY_COMP_TEST_SRCS}) + get_test_name(py_comp_test_name ${py_comp_test} "py_comparison_test") + set(py_comp_test_fname "py_comparison_test_${py_comp_test_name}") + + pybind11_add_module(${py_comp_test_name} ${py_comp_test}) + target_link_libraries(${py_comp_test_name} PRIVATE muSpectre::muSpectre) + + configure_file( + "${py_comp_test_fname}.py" + "${CMAKE_CURRENT_BINARY_DIR}/${py_comp_test_fname}.py" + COPYONLY) + muSpectre_add_test(${py_comp_test_fname} + TYPE PYTHON "${py_comp_test_fname}.py") +endforeach(py_comp_test ${PY_COMP_TEST_SRCS}) + +############################################################################## +# copy python test + +file(GLOB PY_TEST_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/python_*.py") +foreach(pytest ${PY_TEST_SRCS}) + get_filename_component(pytest_name ${pytest} NAME) + configure_file( + ${pytest} + "${CMAKE_CURRENT_BINARY_DIR}/${pytest_name}" + COPYONLY) +endforeach(pytest ${PY_TEST_SRCS}) +muSpectre_add_test(python_binding_test TYPE PYTHON python_binding_tests.py) + +if(${MUSPECTRE_MPI_PARALLEL}) + # add MPI tests + file(GLOB TEST_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/mpi_test_*.cc") + + muSpectre_add_test(mpi_main_test_suite1 + SOURCES mpi_main_test_suite.cc ${TEST_SRCS} + TARGET mpi_main_test_suite + TYPE BOOST MPI_NB_PROCS 1 --report_level=detailed) + muSpectre_add_test(mpi_main_test_suite2 + TARGET mpi_main_test_suite + TYPE BOOST MPI_NB_PROCS 2 --report_level=detailed) + + muSpectre_add_test(python_mpi_binding_test1 TYPE PYTHON MPI_NB_PROCS 1 + python_mpi_binding_tests.py) + muSpectre_add_test(python_mpi_binding_test2 TYPE PYTHON MPI_NB_PROCS 2 + python_mpi_binding_tests.py) +endif() + +add_custom_target(test_muspectre DEPENDS ${muspectre_tests}) diff --git a/tests/libmufft/CMakeLists.txt b/tests/libmufft/CMakeLists.txt new file mode 100644 index 0000000..7e370e3 --- /dev/null +++ b/tests/libmufft/CMakeLists.txt @@ -0,0 +1,77 @@ +# ============================================================================= +# file CMakeLists.txt +# +# @author Till Junge +# +# @date 08 Jan 2018 +# +# @brief Main configuration file +# +# @section LICENSE +# +# Copyright © 2018 Till Junge +# +# µSpectre is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public License as +# published by the Free Software Foundation, either version 3, or (at +# your option) any later version. +# +# µSpectre is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with µSpectre; see the file COPYING. If not, write to the +# Free Software Foundation, Inc., 59 Temple Place - Suite 330, +# Boston, MA 02111-1307, USA. +# +# Additional permission under GNU GPL version 3 section 7 +# +# If you modify this Program, or any covered work, by linking or combining it +# with proprietary FFT implementations or numerical libraries, containing parts +# covered by the terms of those libraries' licenses, the licensors of this +# Program grant you additional permission to convey the resulting work. +# ============================================================================= +set(mufft_tests) + +macro(muFFT_add_test) + muTools_add_test(${ARGN} LINK_LIBRARIES ${MUFFT_NAMESPACE}muFFT TEST_LIST mufft_tests) +endmacro() + +# build library tests +file(GLOB TEST_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/test_*.cc") +muFFT_add_test(main_mufft_test_suite + SOURCES main_test_suite.cc ${TEST_SRCS} + TYPE BOOST --report_level=detailed) + +file(GLOB PY_TEST_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/python_*.py") +foreach(pytest ${PY_TEST_SRCS}) + get_filename_component(pytest_name ${pytest} NAME) + configure_file( + ${pytest} + "${CMAKE_CURRENT_BINARY_DIR}/${pytest_name}" + COPYONLY) +endforeach(pytest ${PY_TEST_SRCS}) +muFFT_add_test(mufft_python_binding_test TYPE + PYTHON "${CMAKE_CURRENT_BINARY_DIR}/python_binding_tests.py") + +if(${MUSPECTRE_MPI_PARALLEL}) + # add MPI tests + file(GLOB TEST_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/mpi_test_*.cc") + + muFFT_add_test(mufft_mpi_main_test_suite1 + SOURCES mpi_main_test_suite.cc ${TEST_SRCS} + TARGET mpi_main_test_suite + TYPE BOOST MPI_NB_PROCS 1 --report_level=detailed) + muFFT_add_test(mufft_mpi_main_test_suite2 + TARGET mpi_main_test_suite + TYPE BOOST MPI_NB_PROCS 2 --report_level=detailed) + + muFFT_add_test(mufft_python_mpi_binding_test1 TYPE PYTHON MPI_NB_PROCS 1 + python_mpi_binding_tests.py) + muFFT_add_test(mufft_python_mpi_binding_test2 TYPE PYTHON MPI_NB_PROCS 2 + python_mpi_binding_tests.py) +endif() + +add_custom_target(test_mufft DEPENDS ${mufft_tests}) diff --git a/tests/tests.hh b/tests/libmufft/main_test_suite.cc similarity index 76% copy from tests/tests.hh copy to tests/libmufft/main_test_suite.cc index 4cb70de..6e5e995 100644 --- a/tests/tests.hh +++ b/tests/libmufft/main_test_suite.cc @@ -1,49 +1,39 @@ /** - * @file tests.hh + * @file main_test_suite.cc * * @author Till Junge * - * @date 10 May 2017 + * @date 01 May 2017 * - * @brief common defs for tests + * @brief Main test suite. Running this suite tests all available tests for + * µSpectre * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ +#define BOOST_TEST_MODULE base_test test +#define BOOST_TEST_MAIN +#define BOOST_TEST_DYN_LINK -#include "common/common.hh" #include -#include - -#ifndef TESTS_TESTS_HH_ -#define TESTS_TESTS_HH_ - -namespace muSpectre { - - constexpr Real tol = 1e-14 * 100; // it's in percent - constexpr Real finite_diff_tol = 1e-7; // it's in percent - -} // namespace muSpectre - -#endif // TESTS_TESTS_HH_ diff --git a/tests/mpi_context.hh b/tests/libmufft/mpi_context.hh similarity index 91% copy from tests/mpi_context.hh copy to tests/libmufft/mpi_context.hh index 88536d6..cad0b16 100644 --- a/tests/mpi_context.hh +++ b/tests/libmufft/mpi_context.hh @@ -1,71 +1,71 @@ /** * @file mpi_initializer.cc * * @author Lars Pastewka * * @date 07 Mar 2018 * * @brief Singleton for initialization and tear down of MPI. * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#ifndef TESTS_MPI_CONTEXT_HH_ -#define TESTS_MPI_CONTEXT_HH_ +#ifndef TESTS_LIBMUFFT_MPI_CONTEXT_HH_ +#define TESTS_LIBMUFFT_MPI_CONTEXT_HH_ -#include "common/communicator.hh" +#include -namespace muSpectre { +namespace muFFT { /*! * MPI context singleton. Initialize MPI once when needed. */ class MPIContext { public: Communicator comm; static MPIContext & get_context() { static MPIContext context; return context; } private: MPIContext() : comm(Communicator(MPI_COMM_WORLD)) { MPI_Init(&boost::unit_test::framework::master_test_suite().argc, &boost::unit_test::framework::master_test_suite().argv); } ~MPIContext() { // Wait for all processes to finish before calling finalize. MPI_Barrier(comm.get_mpi_comm()); MPI_Finalize(); } public: MPIContext(MPIContext const &) = delete; void operator=(MPIContext const &) = delete; }; -} // namespace muSpectre +} // namespace muFFT -#endif // TESTS_MPI_CONTEXT_HH_ +#endif // TESTS_LIBMUFFT_MPI_CONTEXT_HH_ diff --git a/tests/tests.hh b/tests/libmufft/mpi_main_test_suite.cc similarity index 73% copy from tests/tests.hh copy to tests/libmufft/mpi_main_test_suite.cc index 4cb70de..a80803d 100644 --- a/tests/tests.hh +++ b/tests/libmufft/mpi_main_test_suite.cc @@ -1,49 +1,39 @@ /** - * @file tests.hh + * @file mpi_main_test_suite.cc * - * @author Till Junge + * @author Lars Pastewka * - * @date 10 May 2017 + * @date 07 Mar 2018 * - * @brief common defs for tests + * @brief Main test suite for MPI specific modules. Running this suite tests + * all available tests for µSpectre that depend on MPI. * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ +#define BOOST_TEST_MODULE base_test test +#define BOOST_TEST_MAIN +#define BOOST_TEST_DYN_LINK -#include "common/common.hh" #include -#include - -#ifndef TESTS_TESTS_HH_ -#define TESTS_TESTS_HH_ - -namespace muSpectre { - - constexpr Real tol = 1e-14 * 100; // it's in percent - constexpr Real finite_diff_tol = 1e-7; // it's in percent - -} // namespace muSpectre - -#endif // TESTS_TESTS_HH_ diff --git a/tests/mpi_test_fft_engine.cc b/tests/libmufft/mpi_test_fft_engine.cc similarity index 81% rename from tests/mpi_test_fft_engine.cc rename to tests/libmufft/mpi_test_fft_engine.cc index 3658a73..4ab4fe7 100644 --- a/tests/mpi_test_fft_engine.cc +++ b/tests/libmufft/mpi_test_fft_engine.cc @@ -1,182 +1,188 @@ /** * @file mpi_test_fft_engine.cc * * @author Lars Pastewka * * @date 06 Mar 2017 * * @brief tests for MPI-parallel fft engine implementations * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #define BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS #define BOOST_MPL_LIMIT_LIST_SIZE 50 #include #include "tests.hh" #include "mpi_context.hh" -#include "fft/fftw_engine.hh" +#include #ifdef WITH_FFTWMPI -#include "fft/fftwmpi_engine.hh" +#include #endif #ifdef WITH_PFFT -#include "fft/pfft_engine.hh" +#include #endif -#include "common/ccoord_operations.hh" -#include "common/field_collection.hh" -#include "common/field_map.hh" -#include "common/iterators.hh" +#include +#include +#include +#include -namespace muSpectre { +namespace muFFT { + using muFFT::tol; BOOST_AUTO_TEST_SUITE(mpi_fft_engine); /* ---------------------------------------------------------------------- */ template struct FFTW_fixture { constexpr static Dim_t box_resolution{resolution}; constexpr static Dim_t serial_engine{serial}; constexpr static Real box_length{4.5}; constexpr static Dim_t sdim{Engine::sdim}; constexpr static Dim_t nb_components{sdim * sdim}; constexpr static Ccoord_t res() { - return CcoordOps::get_cube(box_resolution); + return muGrid::CcoordOps::get_cube(box_resolution); } FFTW_fixture() : engine(res(), nb_components, MPIContext::get_context().comm) {} Engine engine; }; template struct FFTW_fixture_python_segfault { constexpr static Dim_t serial_engine{false}; constexpr static Dim_t dim{twoD}; constexpr static Dim_t sdim{twoD}; constexpr static Dim_t mdim{twoD}; + constexpr static Dim_t nb_components{sdim * sdim}; constexpr static Ccoord_t res() { return {6, 4}; } FFTW_fixture_python_segfault() - : engine{res(), MPIContext::get_context().comm} {} + : engine{res(), nb_components, MPIContext::get_context().comm} {} Engine engine; }; using fixlist = boost::mpl::list< #ifdef WITH_FFTWMPI FFTW_fixture, 3>, FFTW_fixture, 3>, FFTW_fixture, 4>, FFTW_fixture, 4>, FFTW_fixture_python_segfault>, #endif #ifdef WITH_PFFT FFTW_fixture, 3>, FFTW_fixture, 3>, FFTW_fixture, 4>, FFTW_fixture, 4>, FFTW_fixture_python_segfault>, #endif FFTW_fixture, 3, true>>; /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE_TEMPLATE(Constructor_test, Fix, fixlist, Fix) { Communicator & comm = MPIContext::get_context().comm; if (Fix::serial_engine && comm.size() > 1) { return; } else { BOOST_CHECK_NO_THROW(Fix::engine.initialise(FFT_PlanFlags::estimate)); } BOOST_CHECK_EQUAL(comm.sum(Fix::engine.size()), - CcoordOps::get_size(Fix::res())); + muGrid::CcoordOps::get_size(Fix::res())); } /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE_TEMPLATE(fft_test, Fix, fixlist, Fix) { if (Fix::serial_engine && Fix::engine.get_communicator().size() > 1) { // dont test serial engies in parallel return; } else { Fix::engine.initialise(FFT_PlanFlags::estimate); } constexpr Dim_t order{2}; - using FC_t = GlobalFieldCollection; + using FC_t = muGrid::GlobalFieldCollection; FC_t fc; auto & input{ - make_field>("input", fc)}; + muGrid::make_field>( + "input", fc)}; auto & ref{ - make_field>("reference", fc)}; + muGrid::make_field>( + "reference", fc)}; auto & result{ - make_field>("result", fc)}; + muGrid::make_field>( + "result", fc)}; fc.initialise(Fix::engine.get_subdomain_resolutions(), Fix::engine.get_subdomain_locations()); - using map_t = MatrixFieldMap; + using map_t = muGrid::MatrixFieldMap; map_t inmap{input}; auto refmap{map_t{ref}}; auto resultmap{map_t{result}}; size_t cntr{0}; for (auto tup : akantu::zip(inmap, refmap)) { cntr++; auto & in_{std::get<0>(tup)}; auto & ref_{std::get<1>(tup)}; in_.setRandom(); ref_ = in_; } auto & complex_field = Fix::engine.fft(input); - using cmap_t = MatrixFieldMap, Complex, - Fix::sdim, Fix::sdim>; + using cmap_t = + muGrid::MatrixFieldMap, Complex, + Fix::sdim, Fix::sdim>; cmap_t complex_map(complex_field); if (Fix::engine.get_subdomain_locations() == - CcoordOps::get_cube(0)) { + muGrid::CcoordOps::get_cube(0)) { // Check that 0,0 location has no imaginary part. Real error = complex_map[0].imag().norm(); BOOST_CHECK_LT(error, tol); } /* make sure, the engine has not modified input (which is unfortunately const-casted internally, hence this test) */ for (auto && tup : akantu::zip(inmap, refmap)) { Real error{(std::get<0>(tup) - std::get<1>(tup)).norm()}; BOOST_CHECK_LT(error, tol); } /* make sure that the ifft of fft returns the original*/ Fix::engine.ifft(result); for (auto && tup : akantu::zip(resultmap, refmap)) { Real error{ (std::get<0>(tup) * Fix::engine.normalisation() - std::get<1>(tup)) .norm()}; BOOST_CHECK_LT(error, tol); if (error > tol) { std::cout << std::get<0>(tup).array() / std::get<1>(tup).array() << std::endl << std::endl; } } } BOOST_AUTO_TEST_SUITE_END(); -} // namespace muSpectre +} // namespace muFFT diff --git a/tests/python_mpi_binding_tests.py b/tests/libmufft/python_binding_tests.py old mode 100755 new mode 100644 similarity index 87% copy from tests/python_mpi_binding_tests.py copy to tests/libmufft/python_binding_tests.py index 21c4215..7a6e0ec --- a/tests/python_mpi_binding_tests.py +++ b/tests/libmufft/python_binding_tests.py @@ -1,47 +1,47 @@ #!/usr/bin/env python3 """ -file python_mpi_binding_tests.py +file python_binding_tests.py @author Till Junge @date 09 Jan 2018 -@brief Unit tests for python bindings with MPI support +@brief Unit tests for python bindings @section LICENCE Copyright © 2018 Till Junge µSpectre is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3, or (at your option) any later version. µSpectre is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with µSpectre; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with proprietary FFT implementations or numerical libraries, containing parts covered by the terms of those libraries' licenses, the licensors of this Program grant you additional permission to convey the resulting work. """ import unittest import numpy as np from python_test_imports import µ -from python_mpi_projection_tests import * -from python_mpi_material_linear_elastic4_test import * +from python_fft_tests import FFT_Check +from python_projection_tests import * if __name__ == '__main__': unittest.main() diff --git a/tests/python_fft_tests.py b/tests/libmufft/python_fft_tests.py similarity index 100% rename from tests/python_fft_tests.py rename to tests/libmufft/python_fft_tests.py diff --git a/tests/python_goose_ref.py b/tests/libmufft/python_goose_ref.py similarity index 100% rename from tests/python_goose_ref.py rename to tests/libmufft/python_goose_ref.py diff --git a/tests/python_mpi_binding_tests.py b/tests/libmufft/python_mpi_binding_tests.py old mode 100755 new mode 100644 similarity index 85% copy from tests/python_mpi_binding_tests.py copy to tests/libmufft/python_mpi_binding_tests.py index 21c4215..5c8eeca --- a/tests/python_mpi_binding_tests.py +++ b/tests/libmufft/python_mpi_binding_tests.py @@ -1,47 +1,45 @@ #!/usr/bin/env python3 +# -*- coding:utf-8 -*- """ -file python_mpi_binding_tests.py +@file python_mpi_binding_tests.py @author Till Junge -@date 09 Jan 2018 +@date 28 Feb 2019 @brief Unit tests for python bindings with MPI support -@section LICENCE - -Copyright © 2018 Till Junge +Copyright © 2019 Till Junge µSpectre is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public License as +modify it under the terms of the GNU General Lesser Public License as published by the Free Software Foundation, either version 3, or (at your option) any later version. µSpectre is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with µSpectre; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with proprietary FFT implementations or numerical libraries, containing parts covered by the terms of those libraries' licenses, the licensors of this Program grant you additional permission to convey the resulting work. """ import unittest import numpy as np from python_test_imports import µ from python_mpi_projection_tests import * -from python_mpi_material_linear_elastic4_test import * if __name__ == '__main__': unittest.main() diff --git a/tests/python_mpi_projection_tests.py b/tests/libmufft/python_mpi_projection_tests.py similarity index 100% rename from tests/python_mpi_projection_tests.py rename to tests/libmufft/python_mpi_projection_tests.py diff --git a/tests/python_projection_tests.py b/tests/libmufft/python_projection_tests.py similarity index 100% rename from tests/python_projection_tests.py rename to tests/libmufft/python_projection_tests.py diff --git a/tests/python_test_imports.py b/tests/libmufft/python_test_imports.py similarity index 84% copy from tests/python_test_imports.py copy to tests/libmufft/python_test_imports.py index be9192b..3d72fc1 100644 --- a/tests/python_test_imports.py +++ b/tests/libmufft/python_test_imports.py @@ -1,53 +1,57 @@ #!/usr/bin/env python3 # -*- coding:utf-8 -*- """ file python_test_imports.py @author Till Junge @date 18 Jan 2018 @brief prepares sys.path to load muSpectre @section LICENSE Copyright © 2018 Till Junge µSpectre is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3, or (at your option) any later version. µSpectre is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with µSpectre; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with proprietary FFT implementations or numerical libraries, containing parts covered by the terms of those libraries' licenses, the licensors of this Program grant you additional permission to convey the resulting work. """ import sys import os +project_home = os.path.join(os.getcwd(), '../..') + # Default path of the library -sys.path.insert(0, os.path.join(os.getcwd(), "language_bindings/python")) +sys.path.insert(0, os.path.join(project_home, + "language_bindings/python")) # Path of the library when compiling with Xcode -sys.path.insert(0, os.path.join(os.getcwd(), "language_bindings/python/Debug")) +sys.path.insert(0, os.path.join(project_home, + "language_bindings/python/Debug")) try: import muSpectre as µ import muSpectre except ImportError as err: print(err) sys.exit(-1) diff --git a/tests/test_fft_utils.cc b/tests/libmufft/test_fft_utils.cc similarity index 91% rename from tests/test_fft_utils.cc rename to tests/libmufft/test_fft_utils.cc index aea4609..faafe72 100644 --- a/tests/test_fft_utils.cc +++ b/tests/libmufft/test_fft_utils.cc @@ -1,88 +1,90 @@ /** * @file test_fft_utils.cc * * @author Till Junge * * @date 11 Dec 2017 * * @brief test the small utility functions used by the fft engines and * projections * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include #include "tests.hh" -#include "fft/fft_utils.hh" +#include -namespace muSpectre { +namespace muFFT { BOOST_AUTO_TEST_SUITE(fft_utils); BOOST_AUTO_TEST_CASE(fft_freqs_test) { // simply comparing to np.fft.fftfreq(12, 1/12.) const std::valarray ref{0., 1., 2., 3., 4., 5., -6., -5., -4., -3., -2., -1.}; auto res{fft_freqs(12)}; Real error = std::abs(res - ref).sum(); BOOST_CHECK_EQUAL(error, 0.); } BOOST_AUTO_TEST_CASE(fft_freqs_test_length) { // simply comparing to np.fft.fftfreq(10) const std::valarray ref{0., 0.1, 0.2, 0.3, 0.4, -0.5, -0.4, -0.3, -0.2, -0.1}; auto res{fft_freqs(10, 10.)}; Real error = std::abs(res - ref).sum(); BOOST_CHECK_EQUAL(error, 0.); } BOOST_AUTO_TEST_CASE(wave_vector_computation) { // here, build a FFT_freqs and check it returns the correct xi's constexpr Dim_t dim{twoD}; FFT_freqs freq_struc{{12, 10}, {1., 10.}}; Ccoord_t ccoord1{2, 3}; auto xi{freq_struc.get_xi(ccoord1)}; auto unit_xi{freq_struc.get_unit_xi(ccoord1)}; typename FFT_freqs::Vector ref; ref << 2., .3; // from above tests BOOST_CHECK_LT((xi - ref).norm(), tol); - BOOST_CHECK_LT(std::abs(xi.dot(unit_xi) - xi.norm()), xi.norm() * tol); + BOOST_CHECK_LT(std::abs(xi.dot(unit_xi) - xi.norm()), + xi.norm() * tol); BOOST_CHECK_LT(std::abs(unit_xi.norm() - 1.), tol); ccoord1 = {7, 8}; xi = freq_struc.get_xi(ccoord1); unit_xi = freq_struc.get_unit_xi(ccoord1); ref << -5., -.2; BOOST_CHECK_LT((xi - ref).norm(), tol); - BOOST_CHECK_LT(std::abs(xi.dot(unit_xi) - xi.norm()), xi.norm() * tol); + BOOST_CHECK_LT(std::abs(xi.dot(unit_xi) - xi.norm()), + xi.norm() * tol); BOOST_CHECK_LT(std::abs(unit_xi.norm() - 1.), tol); } BOOST_AUTO_TEST_SUITE_END(); -} // namespace muSpectre +} // namespace muFFT diff --git a/tests/test_fftw_engine.cc b/tests/libmufft/test_fftw_engine.cc similarity index 80% rename from tests/test_fftw_engine.cc rename to tests/libmufft/test_fftw_engine.cc index 20a6d7c..998502a 100644 --- a/tests/test_fftw_engine.cc +++ b/tests/libmufft/test_fftw_engine.cc @@ -1,144 +1,150 @@ /** * @file test_fftw_engine.cc * * @author Till Junge * * @date 05 Dec 2017 * * @brief tests for the fftw fft engine implementation * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#include - #include "tests.hh" -#include "fft/fftw_engine.hh" -#include "common/ccoord_operations.hh" -#include "common/field_collection.hh" -#include "common/field_map.hh" -#include "common/iterators.hh" -namespace muSpectre { +#include +#include +#include +#include +#include + +#include +#include +namespace muFFT { BOOST_AUTO_TEST_SUITE(fftw_engine); /* ---------------------------------------------------------------------- */ template struct FFTW_fixture { constexpr static Dim_t box_resolution{resolution}; constexpr static Real box_length{4.5}; constexpr static Dim_t sdim{DimS}; constexpr static Dim_t mdim{DimM}; constexpr static Ccoord_t res() { - return CcoordOps::get_cube(box_resolution); + return muGrid::CcoordOps::get_cube(box_resolution); } constexpr static Ccoord_t loc() { - return CcoordOps::get_cube(0); + return muGrid::CcoordOps::get_cube(0); } FFTW_fixture() : engine(res(), DimM * DimM) {} FFTWEngine engine; }; struct FFTW_fixture_python_segfault { constexpr static Dim_t dim{twoD}; constexpr static Dim_t sdim{twoD}; constexpr static Dim_t mdim{twoD}; constexpr static Ccoord_t res() { return {6, 4}; } constexpr static Ccoord_t loc() { return {0, 0}; } FFTW_fixture_python_segfault() : engine{res(), mdim * mdim} {} FFTWEngine engine; }; using fixlist = boost::mpl::list< FFTW_fixture, FFTW_fixture, FFTW_fixture, FFTW_fixture, FFTW_fixture, FFTW_fixture, FFTW_fixture_python_segfault>; /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE_TEMPLATE(Constructor_test, Fix, fixlist, Fix) { BOOST_CHECK_NO_THROW(Fix::engine.initialise(FFT_PlanFlags::estimate)); - BOOST_CHECK_EQUAL(Fix::engine.size(), CcoordOps::get_size(Fix::res())); + BOOST_CHECK_EQUAL(Fix::engine.size(), + muGrid::CcoordOps::get_size(Fix::res())); } /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE_TEMPLATE(fft_test, Fix, fixlist, Fix) { Fix::engine.initialise(FFT_PlanFlags::estimate); constexpr Dim_t order{2}; - using FC_t = GlobalFieldCollection; + using FC_t = muGrid::GlobalFieldCollection; FC_t fc; auto & input{ - make_field>("input", fc)}; + muGrid::make_field>( + "input", fc)}; auto & ref{ - make_field>("reference", fc)}; + muGrid::make_field>( + "reference", fc)}; auto & result{ - make_field>("result", fc)}; + muGrid::make_field>( + "result", fc)}; fc.initialise(Fix::res(), Fix::loc()); - using map_t = MatrixFieldMap; + using map_t = muGrid::MatrixFieldMap; map_t inmap{input}; auto refmap{map_t{ref}}; auto resultmap{map_t{result}}; size_t cntr{0}; for (auto tup : akantu::zip(inmap, refmap)) { cntr++; auto & in_{std::get<0>(tup)}; auto & ref_{std::get<1>(tup)}; in_.setRandom(); ref_ = in_; } auto & complex_field = Fix::engine.fft(input); - using cmap_t = MatrixFieldMap, Complex, - Fix::mdim, Fix::mdim>; + using cmap_t = + muGrid::MatrixFieldMap, Complex, + Fix::mdim, Fix::mdim>; cmap_t complex_map(complex_field); Real error = complex_map[0].imag().norm(); BOOST_CHECK_LT(error, tol); /* make sure, the engine has not modified input (which is unfortunately const-casted internally, hence this test) */ for (auto && tup : akantu::zip(inmap, refmap)) { Real error{(std::get<0>(tup) - std::get<1>(tup)).norm()}; BOOST_CHECK_LT(error, tol); } /* make sure that the ifft of fft returns the original*/ Fix::engine.ifft(result); for (auto && tup : akantu::zip(resultmap, refmap)) { Real error{ (std::get<0>(tup) * Fix::engine.normalisation() - std::get<1>(tup)) .norm()}; BOOST_CHECK_LT(error, tol); if (error > tol) { std::cout << std::get<0>(tup).array() / std::get<1>(tup).array() << std::endl << std::endl; } } } BOOST_AUTO_TEST_SUITE_END(); -} // namespace muSpectre +} // namespace muFFT diff --git a/src/common/field_collection.hh b/tests/libmufft/tests.hh similarity index 75% rename from src/common/field_collection.hh rename to tests/libmufft/tests.hh index 7b057a5..edf5d6f 100644 --- a/src/common/field_collection.hh +++ b/tests/libmufft/tests.hh @@ -1,42 +1,49 @@ /** - * @file field_collection.hh + * @file tests.hh * * @author Till Junge * - * @date 07 Sep 2017 + * @date 10 May 2017 * - * @brief Provides pixel-iterable containers for scalar and tensorial fields, - * addressable by field name + * @brief common defs for tests * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#ifndef SRC_COMMON_FIELD_COLLECTION_HH_ -#define SRC_COMMON_FIELD_COLLECTION_HH_ +#include "../libmugrid/tests.hh" -#include "common/field_collection_global.hh" -#include "common/field_collection_local.hh" +#include -#endif // SRC_COMMON_FIELD_COLLECTION_HH_ +#include +#include + +#ifndef TESTS_LIBMUFFT_TESTS_HH_ +#define TESTS_LIBMUFFT_TESTS_HH_ + +namespace muFFT { + using muGrid::tol; +} // namespace muFFT + +#endif // TESTS_LIBMUFFT_TESTS_HH_ diff --git a/tests/libmugrid/CMakeLists.txt b/tests/libmugrid/CMakeLists.txt new file mode 100644 index 0000000..68174d1 --- /dev/null +++ b/tests/libmugrid/CMakeLists.txt @@ -0,0 +1,56 @@ +# ============================================================================= +# file CMakeLists.txt +# +# @author Till Junge +# +# @date 08 Jan 2018 +# +# @brief Main configuration file +# +# @section LICENSE +# +# Copyright © 2018 Till Junge +# +# µSpectre is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public License as +# published by the Free Software Foundation, either version 3, or (at +# your option) any later version. +# +# µSpectre is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with µSpectre; see the file COPYING. If not, write to the +# Free Software Foundation, Inc., 59 Temple Place - Suite 330, +# Boston, MA 02111-1307, USA. +# +# Additional permission under GNU GPL version 3 section 7 +# +# If you modify this Program, or any covered work, by linking or combining it +# with proprietary FFT implementations or numerical libraries, containing parts +# covered by the terms of those libraries' licenses, the licensors of this +# Program grant you additional permission to convey the resulting work. +# ============================================================================= +set(mugrid_tests) +macro(muGrid_add_test) + muTools_add_test(${ARGN} LINK_LIBRARIES ${MUGRID_NAMESPACE}muGrid TEST_LIST mugrid_tests) +endmacro() + +file(GLOB HEADER_TEST_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/header*.cc") +foreach(header_test ${HEADER_TEST_SRCS}) + get_test_name(test_name ${header_test} ".*_test") + + muGrid_add_test(${test_name} + SOURCES main_test_suite.cc ${header_test} + TYPE BOOST --report_level=detailed) +endforeach(header_test ${HEADER_TEST_SRCS}) + +# build library tests +file(GLOB TEST_SRCS "${CMAKE_CURRENT_SOURCE_DIR}/test_*.cc") +muGrid_add_test(main_mugrid_test_suite + SOURCES main_test_suite.cc ${TEST_SRCS} + TYPE BOOST --report_level=detailed) + +add_custom_target(test_mugrid DEPENDS ${mugrid_tests}) diff --git a/tests/header_test_ccoord_operations.cc b/tests/libmugrid/header_test_ccoord_operations.cc similarity index 97% rename from tests/header_test_ccoord_operations.cc rename to tests/libmugrid/header_test_ccoord_operations.cc index fb9b0e7..c50abf1 100644 --- a/tests/header_test_ccoord_operations.cc +++ b/tests/libmugrid/header_test_ccoord_operations.cc @@ -1,157 +1,155 @@ /** * @file test_ccoord_operations.cc * * @author Till Junge * * @date 03 Dec 2017 * * @brief tests for cell coordinate operations * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include -#include "common/common.hh" -#include "common/ccoord_operations.hh" -#include "tests/test_goodies.hh" +#include +#include "test_goodies.hh" #include "tests.hh" -namespace muSpectre { - +namespace muGrid { BOOST_AUTO_TEST_SUITE(ccoords_operations); BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_cube, Fix, testGoodies::dimlist, Fix) { constexpr auto dim{Fix::dim}; using Ccoord = Ccoord_t; constexpr Dim_t size{5}; constexpr Ccoord cube = CcoordOps::get_cube(size); Ccoord ref_cube; for (Dim_t i = 0; i < dim; ++i) { ref_cube[i] = size; } BOOST_CHECK_EQUAL_COLLECTIONS(ref_cube.begin(), ref_cube.end(), cube.begin(), cube.end()); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_hermitian, Fix, testGoodies::dimlist, Fix) { constexpr auto dim{Fix::dim}; using Ccoord = Ccoord_t; constexpr Dim_t size{5}; constexpr Ccoord cube = CcoordOps::get_cube(size); constexpr Ccoord herm = CcoordOps::get_hermitian_sizes(cube); Ccoord ref_cube = cube; ref_cube.back() = (cube.back() + 1) / 2; BOOST_CHECK_EQUAL_COLLECTIONS(ref_cube.begin(), ref_cube.end(), herm.begin(), herm.end()); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_size, Fix, testGoodies::dimlist, Fix) { constexpr auto dim{Fix::dim}; using Ccoord = Ccoord_t; constexpr Dim_t size{5}; constexpr Ccoord cube = CcoordOps::get_cube(size); BOOST_CHECK_EQUAL(CcoordOps::get_size(cube), ipow(size, dim)); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_stride_size, Fix, testGoodies::dimlist, Fix) { constexpr auto dim{Fix::dim}; using Ccoord = Ccoord_t; constexpr Dim_t size{5}; constexpr Ccoord cube = CcoordOps::get_cube(size); constexpr Ccoord stride = CcoordOps::get_default_strides(cube); BOOST_CHECK_EQUAL(CcoordOps::get_size_from_strides(cube, stride), ipow(size, dim)); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_index, Fix, testGoodies::dimlist, Fix) { constexpr auto dim{Fix::dim}; using Ccoord = Ccoord_t; testGoodies::RandRange rng; Ccoord sizes{}; for (Dim_t i{0}; i < dim; ++i) { sizes[i] = rng.randval(2, 5); } Ccoord stride = CcoordOps::get_default_strides(sizes); Ccoord locations{}; const size_t nb_pix{CcoordOps::get_size(sizes)}; for (size_t i{0}; i < nb_pix; ++i) { BOOST_CHECK_EQUAL( i, CcoordOps::get_index_from_strides( stride, CcoordOps::get_ccoord(sizes, locations, i))); } } BOOST_AUTO_TEST_CASE(vector_test) { constexpr Ccoord_t c3{1, 2, 3}; constexpr Ccoord_t c2{c3[0], c3[1]}; constexpr Rcoord_t s3{1.3, 2.8, 5.7}; constexpr Rcoord_t s2{s3[0], s3[1]}; Eigen::Matrix v2; v2 << s3[0], s3[1]; Eigen::Matrix v3; v3 << s3[0], s3[1], s3[2]; auto vec2{CcoordOps::get_vector(c2, v2(1))}; auto vec3{CcoordOps::get_vector(c3, v3(1))}; for (Dim_t i = 0; i < twoD; ++i) { BOOST_CHECK_EQUAL(c2[i] * v2(1), vec2[i]); } for (Dim_t i = 0; i < threeD; ++i) { BOOST_CHECK_EQUAL(c3[i] * v3(1), vec3[i]); } vec2 = CcoordOps::get_vector(c2, v2); vec3 = CcoordOps::get_vector(c3, v3); for (Dim_t i = 0; i < twoD; ++i) { BOOST_CHECK_EQUAL(c2[i] * v2(i), vec2[i]); BOOST_CHECK_EQUAL(vec2[i], CcoordOps::get_vector(c2, s2)[i]); } for (Dim_t i = 0; i < threeD; ++i) { BOOST_CHECK_EQUAL(c3[i] * v3(i), vec3[i]); BOOST_CHECK_EQUAL(vec3[i], CcoordOps::get_vector(c3, s3)[i]); } } BOOST_AUTO_TEST_SUITE_END(); -} // namespace muSpectre +} // namespace muGrid diff --git a/tests/header_test_eigen_tools.cc b/tests/libmugrid/header_test_eigen_tools.cc similarity index 97% rename from tests/header_test_eigen_tools.cc rename to tests/libmugrid/header_test_eigen_tools.cc index 55270d2..06d638c 100644 --- a/tests/header_test_eigen_tools.cc +++ b/tests/libmugrid/header_test_eigen_tools.cc @@ -1,132 +1,133 @@ /** * @file header_test_eigen_tools.cc * * @author Till Junge * * @date 07 Mar 2018 * * @brief test the eigen_tools * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#include "common/eigen_tools.hh" #include "tests.hh" +#include +#include -namespace muSpectre { +namespace muGrid { BOOST_AUTO_TEST_SUITE(eigen_tools); BOOST_AUTO_TEST_CASE(exponential_test) { using Mat_t = Eigen::Matrix; Mat_t input{}; input << 0, .25 * pi, 0, .25 * pi, 0, 0, 0, 0, 1; Mat_t output{}; output << 1.32460909, 0.86867096, 0, 0.86867096, 1.32460909, 0, 0, 0, 2.71828183; auto my_output{expm(input)}; Real error{(my_output - output).norm()}; BOOST_CHECK_LT(error, 1e-8); if (error >= 1e-8) { std::cout << "input:" << std::endl << input << std::endl; std::cout << "output:" << std::endl << output << std::endl; std::cout << "my_output:" << std::endl << my_output << std::endl; } } BOOST_AUTO_TEST_CASE(log_m_test) { using Mat_t = Eigen::Matrix; Mat_t input{}; constexpr Real log_tol{1e-8}; input << 1.32460909, 0.86867096, 0, 0.86867096, 1.32460909, 0, 0, 0, 2.71828183; Mat_t output{}; output << 0, .25 * pi, 0, .25 * pi, 0, 0, 0, 0, 1; auto my_output{logm(input)}; Real error{(my_output - output).norm() / output.norm()}; BOOST_CHECK_LT(error, log_tol); if (error >= log_tol) { std::cout << "input:" << std::endl << input << std::endl; std::cout << "output:" << std::endl << output << std::endl; std::cout << "my_output:" << std::endl << my_output << std::endl; } input << 1.0001000000000002, 0.010000000000000116, 0, 0.010000000000000061, 1.0000000000000002, 0, 0, 0, 1; // from scipy.linalg.logm output << 4.99991667e-05, 9.99983334e-03, 0.00000000e+00, 9.99983334e-03, -4.99991667e-05, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00; my_output = logm(input); error = (my_output - output).norm() / output.norm(); BOOST_CHECK_LT(error, log_tol); if (error >= log_tol) { std::cout << "input:" << std::endl << input << std::endl; std::cout << "output:" << std::endl << output << std::endl; std::cout << "my_output:" << std::endl << my_output << std::endl; } input << 1.0001000000000002, 0.010000000000000116, 0, 0.010000000000000061, 1.0000000000000002, 0, 0, 0, 1; input = input.transpose().eval(); // from scipy.linalg.logm output << 4.99991667e-05, 9.99983334e-03, 0.00000000e+00, 9.99983334e-03, -4.99991667e-05, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00; my_output = logm(input); error = (my_output - output).norm() / output.norm(); BOOST_CHECK_LT(error, log_tol); if (error >= log_tol) { std::cout << "input:" << std::endl << input << std::endl; std::cout << "output:" << std::endl << output << std::endl; std::cout << "my_output:" << std::endl << my_output << std::endl; } Mat_t my_output_alt{logm_alt(input)}; error = (my_output_alt - output).norm() / output.norm(); BOOST_CHECK_LT(error, log_tol); if (error >= log_tol) { std::cout << "input:" << std::endl << input << std::endl; std::cout << "output:" << std::endl << output << std::endl; std::cout << "my_output:" << std::endl << my_output_alt << std::endl; } } BOOST_AUTO_TEST_SUITE_END(); -} // namespace muSpectre +} // namespace muGrid diff --git a/tests/header_test_field_collections.cc b/tests/libmugrid/header_test_field_collections.cc similarity index 99% rename from tests/header_test_field_collections.cc rename to tests/libmugrid/header_test_field_collections.cc index db79fe2..add296d 100644 --- a/tests/header_test_field_collections.cc +++ b/tests/libmugrid/header_test_field_collections.cc @@ -1,707 +1,707 @@ /** * @file header_test_field_collections_1.cc * * @author Till Junge * * @date 20 Sep 2017 * * @brief Test the FieldCollection classes which provide fast optimized * iterators over run-time typed fields * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "test_field_collections.hh" -#include "common/field_map_dynamic.hh" +#include -namespace muSpectre { +namespace muGrid { BOOST_AUTO_TEST_SUITE(field_collection_tests); BOOST_AUTO_TEST_CASE(simple) { constexpr Dim_t sdim = 2; using FC_t = GlobalFieldCollection; FC_t fc; BOOST_CHECK_EQUAL(FC_t::spatial_dim(), sdim); BOOST_CHECK_EQUAL(fc.get_spatial_dim(), sdim); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(Simple_construction_test, F, test_collections, F) { BOOST_CHECK_EQUAL(F::FC_t::spatial_dim(), F::sdim()); BOOST_CHECK_EQUAL(F::fc.get_spatial_dim(), F::sdim()); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(get_field2_test, F, test_collections, F) { const auto order{2}; using FC_t = typename F::FC_t; using TF_t = TensorField; auto && myfield = make_field("TensorField real 2", F::fc); using TensorMap = TensorFieldMap; using MatrixMap = MatrixFieldMap; using ArrayMap = ArrayFieldMap; TensorMap TFM(myfield); MatrixMap MFM(myfield); ArrayMap AFM(myfield); BOOST_CHECK_EQUAL(TFM.info_string(), "Tensor(d, " + std::to_string(order) + "_o, " + std::to_string(F::mdim()) + "_d)"); BOOST_CHECK_EQUAL(MFM.info_string(), "Matrix(d, " + std::to_string(F::mdim()) + "x" + std::to_string(F::mdim()) + ")"); BOOST_CHECK_EQUAL(AFM.info_string(), "Array(d, " + std::to_string(F::mdim()) + "x" + std::to_string(F::mdim()) + ")"); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(multi_field_test, F, mult_collections, F) { using FC_t = typename F::FC_t; // possible maptypes for Real tensor fields using T_type = Real; using T_TFM1_t = TensorFieldMap; - using T_TFM2_t = - TensorFieldMap; //! dangerous + using T_TFM2_t = TensorFieldMap; //! dangerous using T4_Map_t = T4MatrixFieldMap; // impossible maptypes for Real tensor fields using T_SFM_t = ScalarFieldMap; using T_MFM_t = MatrixFieldMap; using T_AFM_t = ArrayFieldMap; using T_MFMw1_t = MatrixFieldMap; using T_MFMw2_t = MatrixFieldMap; using T_MFMw3_t = MatrixFieldMap; const std::string T_name{"Tensorfield Real o4"}; const std::string T_name_w{"TensorField Real o4 wrongname"}; BOOST_CHECK_THROW(T_SFM_t(F::fc.at(T_name)), FieldInterpretationError); BOOST_CHECK_NO_THROW(T_TFM1_t(F::fc.at(T_name))); BOOST_CHECK_NO_THROW(T_TFM2_t(F::fc.at(T_name))); BOOST_CHECK_NO_THROW(T4_Map_t(F::fc.at(T_name))); BOOST_CHECK_THROW(T4_Map_t(F::fc.at(T_name_w)), std::out_of_range); BOOST_CHECK_THROW(T_MFM_t(F::fc.at(T_name)), FieldInterpretationError); BOOST_CHECK_THROW(T_AFM_t(F::fc.at(T_name)), FieldInterpretationError); BOOST_CHECK_THROW(T_MFMw1_t(F::fc.at(T_name)), FieldInterpretationError); BOOST_CHECK_THROW(T_MFMw2_t(F::fc.at(T_name)), FieldInterpretationError); BOOST_CHECK_THROW(T_MFMw2_t(F::fc.at(T_name)), FieldInterpretationError); BOOST_CHECK_THROW(T_MFMw3_t(F::fc.at(T_name)), FieldInterpretationError); BOOST_CHECK_THROW(T_SFM_t(F::fc.at(T_name_w)), std::out_of_range); // possible maptypes for integer scalar fields using S_type = Int; using S_SFM_t = ScalarFieldMap; using S_TFM1_t = TensorFieldMap; using S_TFM2_t = TensorFieldMap; using S_MFM_t = MatrixFieldMap; using S_AFM_t = ArrayFieldMap; using S4_Map_t = T4MatrixFieldMap; // impossible maptypes for integer scalar fields using S_MFMw1_t = MatrixFieldMap; using S_MFMw2_t = MatrixFieldMap; using S_MFMw3_t = MatrixFieldMap; const std::string S_name{"integer Scalar"}; const std::string S_name_w{"integer Scalar wrongname"}; BOOST_CHECK_NO_THROW(S_SFM_t(F::fc.at(S_name))); BOOST_CHECK_NO_THROW(S_TFM1_t(F::fc.at(S_name))); BOOST_CHECK_NO_THROW(S_TFM2_t(F::fc.at(S_name))); BOOST_CHECK_NO_THROW(S_MFM_t(F::fc.at(S_name))); BOOST_CHECK_NO_THROW(S_AFM_t(F::fc.at(S_name))); BOOST_CHECK_NO_THROW(S4_Map_t(F::fc.at(S_name))); BOOST_CHECK_THROW(S_MFMw1_t(F::fc.at(S_name)), FieldInterpretationError); BOOST_CHECK_THROW(T4_Map_t(F::fc.at(S_name)), FieldInterpretationError); BOOST_CHECK_THROW(S_MFMw2_t(F::fc.at(S_name)), FieldInterpretationError); BOOST_CHECK_THROW(S_MFMw2_t(F::fc.at(S_name)), FieldInterpretationError); BOOST_CHECK_THROW(S_MFMw3_t(F::fc.at(S_name)), FieldInterpretationError); BOOST_CHECK_THROW(S_SFM_t(F::fc.at(S_name_w)), std::out_of_range); // possible maptypes for complex matrix fields using M_type = Complex; using M_MFM_t = MatrixFieldMap; using M_AFM_t = ArrayFieldMap; // impossible maptypes for complex matrix fields using M_SFM_t = ScalarFieldMap; using M_MFMw1_t = MatrixFieldMap; using M_MFMw2_t = MatrixFieldMap; using M_MFMw3_t = MatrixFieldMap; const std::string M_name{"Matrixfield Complex sdim x mdim"}; const std::string M_name_w{"Matrixfield Complex sdim x mdim wrongname"}; BOOST_CHECK_THROW(M_SFM_t(F::fc.at(M_name)), FieldInterpretationError); BOOST_CHECK_NO_THROW(M_MFM_t(F::fc.at(M_name))); BOOST_CHECK_NO_THROW(M_AFM_t(F::fc.at(M_name))); BOOST_CHECK_THROW(M_MFMw1_t(F::fc.at(M_name)), FieldInterpretationError); BOOST_CHECK_THROW(M_MFMw2_t(F::fc.at(M_name)), FieldInterpretationError); BOOST_CHECK_THROW(M_MFMw2_t(F::fc.at(M_name)), FieldInterpretationError); BOOST_CHECK_THROW(M_MFMw3_t(F::fc.at(M_name)), FieldInterpretationError); BOOST_CHECK_THROW(M_SFM_t(F::fc.at(M_name_w)), std::out_of_range); } /* ---------------------------------------------------------------------- */ //! Check whether fields can be initialized using mult_collections_t = boost::mpl::list, FC_multi_fixture<2, 3, true>, FC_multi_fixture<3, 3, true>>; using mult_collections_f = boost::mpl::list, FC_multi_fixture<2, 3, false>, FC_multi_fixture<3, 3, false>>; BOOST_FIXTURE_TEST_CASE_TEMPLATE(init_test_glob, F, mult_collections_t, F) { Ccoord_t size; Ccoord_t loc{}; for (auto && s : size) { s = 3; } BOOST_CHECK_NO_THROW(F::fc.initialise(size, loc)); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(init_test_loca, F, mult_collections_f, F) { testGoodies::RandRange rng; for (int i = 0; i < 7; ++i) { Ccoord_t pixel; for (auto && s : pixel) { s = rng.randval(0, 7); } F::fc.add_pixel(pixel); } BOOST_CHECK_NO_THROW(F::fc.initialise()); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(init_test_loca_with_push_back, F, mult_collections_f, F) { constexpr auto mdim{F::mdim()}; constexpr int nb_pix{7}; testGoodies::RandRange rng{}; using ftype = internal::TypedSizedFieldBase; using stype = Eigen::Array; auto & field = static_cast(F::fc["Tensorfield Real o4"]); field.push_back(stype()); for (int i = 0; i < nb_pix; ++i) { Ccoord_t pixel; for (auto && s : pixel) { s = rng.randval(0, 7); } F::fc.add_pixel(pixel); } BOOST_CHECK_THROW(F::fc.initialise(), FieldCollectionError); for (int i = 0; i < nb_pix - 1; ++i) { field.push_back(stype()); } BOOST_CHECK_NO_THROW(F::fc.initialise()); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(iter_field_test, F, iter_collections, F) { using FC_t = typename F::Parent::FC_t; using Tensor4Map = TensorFieldMap; Tensor4Map T4map{F::fc["Tensorfield Real o4"]}; TypedFieldMap dyn_map{F::fc["Tensorfield Real o4"]}; F::fc["Tensorfield Real o4"].set_zero(); for (auto && tens : T4map) { BOOST_CHECK_EQUAL(Real(Eigen::Tensor(tens.abs().sum().eval())()), 0); } for (auto && tens : T4map) { tens.setRandom(); } for (auto && tup : akantu::zip(T4map, dyn_map)) { auto & tens = std::get<0>(tup); auto & dyn = std::get<1>(tup); constexpr Dim_t nb_comp{ipow(F::mdim(), order)}; Eigen::Map> tens_arr(tens.data()); Real error{(dyn - tens_arr).matrix().norm()}; BOOST_CHECK_EQUAL(error, 0); } using Tensor2Map = TensorFieldMap; using MSqMap = MatrixFieldMap; using ASqMap = ArrayFieldMap; using A2Map = ArrayFieldMap; using WrongMap = ArrayFieldMap; Tensor2Map T2map{F::fc["Tensorfield Real o2"]}; MSqMap Mmap{F::fc["Tensorfield Real o2"]}; ASqMap Amap{F::fc["Tensorfield Real o2"]}; A2Map DynMap{F::fc["Dynamically sized Field"]}; auto & fc_ref{F::fc}; BOOST_CHECK_THROW(WrongMap{fc_ref["Dynamically sized Field"]}, FieldInterpretationError); auto t2_it = T2map.begin(); auto t2_it_end = T2map.end(); auto m_it = Mmap.begin(); auto a_it = Amap.begin(); for (; t2_it != t2_it_end; ++t2_it, ++m_it, ++a_it) { t2_it->setRandom(); auto && m = *m_it; bool comp = (m == a_it->matrix()); BOOST_CHECK(comp); } size_t counter{0}; for (auto val : DynMap) { ++counter; val += val.Ones() * counter; } counter = 0; for (auto val : DynMap) { ++counter; val -= val.Ones() * counter; auto error{val.matrix().norm()}; BOOST_CHECK_LT(error, tol); } using ScalarMap = ScalarFieldMap; ScalarMap s_map{F::fc["integer Scalar"]}; for (Uint i = 0; i < s_map.size(); ++i) { s_map[i] = i; } counter = 0; for (const auto & val : s_map) { BOOST_CHECK_EQUAL(counter++, val); } } BOOST_FIXTURE_TEST_CASE_TEMPLATE(ccoord_indexing_test, F, glob_iter_colls, F) { using FC_t = typename F::Parent::FC_t; using ScalarMap = ScalarFieldMap; ScalarMap s_map{F::fc["integer Scalar"]}; for (Uint i = 0; i < s_map.size(); ++i) { s_map[i] = i; } for (size_t i = 0; i < CcoordOps::get_size(F::fc.get_sizes()); ++i) { BOOST_CHECK_EQUAL( CcoordOps::get_index(F::fc.get_sizes(), F::fc.get_locations(), CcoordOps::get_ccoord(F::fc.get_sizes(), F::fc.get_locations(), i)), i); } } BOOST_FIXTURE_TEST_CASE_TEMPLATE(iterator_methods_test, F, iter_collections, F) { using FC_t = typename F::Parent::FC_t; using Tensor4Map = TensorFieldMap; Tensor4Map T4map{F::fc["Tensorfield Real o4"]}; using it_t = typename Tensor4Map::iterator; std::ptrdiff_t diff{ 3}; // arbitrary, as long as it is smaller than the container size // check constructors auto itstart = T4map.begin(); // standard way of obtaining iterator auto itend = T4map.end(); // ditto it_t it1{T4map}; it_t it2{T4map, false}; it_t it3{T4map, size_t(diff)}; BOOST_CHECK(itstart == itstart); BOOST_CHECK(itstart != itend); BOOST_CHECK_EQUAL(itstart, it1); BOOST_CHECK_EQUAL(itend, it2); // check ostream operator std::stringstream response; response << it3; BOOST_CHECK_EQUAL( response.str(), std::string("iterator on field 'Tensorfield Real o4', entry ") + std::to_string(diff)); // check move and assigment constructor (and operator+) it_t it_repl{T4map}; it_t itmove = std::move(T4map.begin()); it_t it4 = it1 + diff; it_t it7 = it4 - diff; // BOOST_CHECK_EQUAL(itcopy, it1); BOOST_CHECK_EQUAL(itmove, it1); BOOST_CHECK_EQUAL(it4, it3); BOOST_CHECK_EQUAL(it7, it1); // check increments/decrements BOOST_CHECK_EQUAL(it1++, it_repl); // post-increment BOOST_CHECK_EQUAL(it1, it_repl + 1); BOOST_CHECK_EQUAL(--it1, it_repl); // pre -decrement BOOST_CHECK_EQUAL(++it1, it_repl + 1); // pre -increment BOOST_CHECK_EQUAL(it1--, it_repl + 1); // post-decrement BOOST_CHECK_EQUAL(it1, it_repl); // dereference and member-of-pointer check Eigen::Tensor Tens = *it1; Eigen::Tensor Tens2 = *itstart; Eigen::Tensor check = (Tens == Tens2).all(); BOOST_CHECK_EQUAL(static_cast(check()), true); BOOST_CHECK_NO_THROW(itstart->setZero()); // check access subscripting auto T3a = *it3; auto T3b = itstart[diff]; BOOST_CHECK( static_cast(Eigen::Tensor((T3a == T3b).all())())); // div. comparisons BOOST_CHECK_LT(itstart, itend); BOOST_CHECK(!(itend < itstart)); BOOST_CHECK(!(itstart < itstart)); BOOST_CHECK_LE(itstart, itend); BOOST_CHECK_LE(itstart, itstart); BOOST_CHECK(!(itend <= itstart)); BOOST_CHECK_GT(itend, itstart); BOOST_CHECK(!(itend > itend)); BOOST_CHECK(!(itstart > itend)); BOOST_CHECK_GE(itend, itstart); BOOST_CHECK_GE(itend, itend); BOOST_CHECK(!(itstart >= itend)); // check assignment increment/decrement BOOST_CHECK_EQUAL(it1 += diff, it3); BOOST_CHECK_EQUAL(it1 -= diff, itstart); // check cell coordinates using Ccoord = Ccoord_t; Ccoord a{itstart.get_ccoord()}; Ccoord b{0}; // Weirdly, boost::has_left_shift::value is false for // Ccoords, even though the operator is implemented :( // BOOST_CHECK_EQUAL(a, b); bool check2 = (a == b); BOOST_CHECK(check2); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(const_tensor_iter_test, F, iter_collections, F) { using FC_t = typename F::Parent::FC_t; using Tensor4Map = TensorFieldMap; Tensor4Map T4map{F::fc["Tensorfield Real o4"]}; using T_t = typename Tensor4Map::T_t; Eigen::TensorMap Tens2(T4map[0].data(), F::Parent::sdim(), F::Parent::sdim(), F::Parent::sdim(), F::Parent::sdim()); for (auto it = T4map.cbegin(); it != T4map.cend(); ++it) { // maps to const tensors can't be initialised with a const pointer this // sucks auto && tens = *it; auto && ptr = tens.data(); static_assert( std::is_pointer>::value, "should be getting a pointer"); // static_assert(std::is_const>::value, // "should be const"); // If Tensor were written well, above static_assert should pass, and the // following check shouldn't. If it get triggered, it means that a newer // version of Eigen now does have const-correct // TensorMap. This means that const-correct field maps // are then also possible for tensors BOOST_CHECK(!std::is_const>::value); } } BOOST_FIXTURE_TEST_CASE_TEMPLATE(const_matrix_iter_test, F, iter_collections, F) { using FC_t = typename F::Parent::FC_t; using MatrixMap = MatrixFieldMap; MatrixMap Mmap{F::fc["Matrixfield Complex sdim x mdim"]}; for (auto it = Mmap.cbegin(); it != Mmap.cend(); ++it) { // maps to const tensors can't be initialised with a const pointer this // sucks auto && mat = *it; auto && ptr = mat.data(); static_assert( std::is_pointer>::value, "should be getting a pointer"); // static_assert(std::is_const>::value, // "should be const"); // If Matrix were written well, above static_assert should pass, and the // following check shouldn't. If it get triggered, it means that a newer // version of Eigen now does have const-correct // MatrixMap. This means that const-correct field maps // are then also possible for matrices BOOST_CHECK(!std::is_const>::value); } } BOOST_FIXTURE_TEST_CASE_TEMPLATE(const_scalar_iter_test, F, iter_collections, F) { using FC_t = typename F::Parent::FC_t; using ScalarMap = ScalarFieldMap; ScalarMap Smap{F::fc["integer Scalar"]}; for (auto it = Smap.cbegin(); it != Smap.cend(); ++it) { auto && scal = *it; static_assert( std::is_const>::value, "referred type should be const"); static_assert(std::is_lvalue_reference::value, "Should have returned an lvalue ref"); } } /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE_TEMPLATE(assignment_test, Fix, iter_collections, Fix) { auto t4map{Fix::t4_field.get_map()}; auto t2map{Fix::t2_field.get_map()}; auto scmap{Fix::sc_field.get_map()}; auto m2map{Fix::m2_field.get_map()}; auto dymap{Fix::dyn_field.get_map()}; auto t4map_c{Fix::t4_field.get_const_map()}; auto t2map_c{Fix::t2_field.get_const_map()}; auto scmap_c{Fix::sc_field.get_const_map()}; auto m2map_c{Fix::m2_field.get_const_map()}; auto dymap_c{Fix::dyn_field.get_const_map()}; const auto t4map_val{Matrices::Isymm()}; t4map = t4map_val; const auto t2map_val{Matrices::I2()}; t2map = t2map_val; const Int scmap_val{1}; scmap = scmap_val; Eigen::Matrix m2map_val; m2map_val.setRandom(); m2map = m2map_val; const size_t nb_pts{Fix::fc.size()}; testGoodies::RandRange rnd{}; BOOST_CHECK_EQUAL((t4map[rnd.randval(0, nb_pts - 1)] - t4map_val).norm(), 0.); BOOST_CHECK_EQUAL((t2map[rnd.randval(0, nb_pts - 1)] - t2map_val).norm(), 0.); BOOST_CHECK_EQUAL((scmap[rnd.randval(0, nb_pts - 1)] - scmap_val), 0.); BOOST_CHECK_EQUAL((m2map[rnd.randval(0, nb_pts - 1)] - m2map_val).norm(), 0.); } /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE_TEMPLATE(Eigentest, Fix, iter_collections, Fix) { auto t4eigen = Fix::t4_field.eigen(); auto t2eigen = Fix::t2_field.eigen(); BOOST_CHECK_EQUAL(t4eigen.rows(), ipow(Fix::mdim(), 4)); BOOST_CHECK_EQUAL(t4eigen.cols(), Fix::t4_field.size()); using T2_t = typename Eigen::Matrix; T2_t test_mat; test_mat.setRandom(); Eigen::Map> test_map( test_mat.data()); t2eigen.col(0) = test_map; BOOST_CHECK_EQUAL((Fix::t2_field.get_map()[0] - test_mat).norm(), 0.); } /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE_TEMPLATE(field_proxy_test, Fix, iter_collections, Fix) { Eigen::VectorXd t4values{Fix::t4_field.eigenvec()}; using FieldProxy_t = TypedField; //! create a field proxy FieldProxy_t proxy("proxy to 'Tensorfield Real o4'", Fix::fc, t4values, Fix::t4_field.get_nb_components()); Eigen::VectorXd wrong_size_not_multiple{ Eigen::VectorXd::Zero(t4values.size() + 1)}; BOOST_CHECK_THROW(FieldProxy_t("size not a multiple of nb_components", Fix::fc, wrong_size_not_multiple, Fix::t4_field.get_nb_components()), FieldError); Eigen::VectorXd wrong_size_but_multiple{Eigen::VectorXd::Zero( t4values.size() + Fix::t4_field.get_nb_components())}; BOOST_CHECK_THROW(FieldProxy_t("size wrong multiple of nb_components", Fix::fc, wrong_size_but_multiple, Fix::t4_field.get_nb_components()), FieldError); using Tensor4Map = T4MatrixFieldMap; Tensor4Map ref_map{Fix::t4_field}; Tensor4Map proxy_map{proxy}; for (auto tup : akantu::zip(ref_map, proxy_map)) { auto & ref = std::get<0>(tup); auto & prox = std::get<1>(tup); BOOST_CHECK_EQUAL((ref - prox).norm(), 0); } } /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE_TEMPLATE(field_proxy_of_existing_field, Fix, iter_collections, Fix) { Eigen::Ref t4values{Fix::t4_field.eigenvec()}; using FieldProxy_t = TypedField; //! create a field proxy FieldProxy_t proxy("proxy to 'Tensorfield Real o4'", Fix::fc, t4values, Fix::t4_field.get_nb_components()); using Tensor4Map = T4MatrixFieldMap; Tensor4Map ref_map{Fix::t4_field}; Tensor4Map proxy_map{proxy}; for (auto tup : akantu::zip(ref_map, proxy_map)) { auto & ref = std::get<0>(tup); auto & prox = std::get<1>(tup); prox += prox.Identity(); BOOST_CHECK_EQUAL((ref - prox).norm(), 0); } } /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE_TEMPLATE(typed_field_getter, Fix, mult_collections, Fix) { constexpr auto mdim{Fix::mdim()}; auto & fc{Fix::fc}; auto & field = fc.template get_typed_field("Tensorfield Real o4"); BOOST_CHECK_EQUAL(field.get_nb_components(), ipow(mdim, fourthOrder)); } /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE_TEMPLATE(enumeration, Fix, iter_collections, Fix) { auto t4map{Fix::t4_field.get_map()}; auto t2map{Fix::t2_field.get_map()}; auto scmap{Fix::sc_field.get_map()}; auto m2map{Fix::m2_field.get_map()}; auto dymap{Fix::dyn_field.get_map()}; for (auto && tup : akantu::zip(scmap.get_collection(), scmap, scmap.enumerate())) { const auto & ccoord_ref = std::get<0>(tup); const auto & val_ref = std::get<1>(tup); const auto & key_val = std::get<2>(tup); const auto & ccoord = std::get<0>(key_val); const auto & val = std::get<1>(key_val); for (auto && ccoords : akantu::zip(ccoord_ref, ccoord)) { const auto & ref{std::get<0>(ccoords)}; const auto & val{std::get<1>(ccoords)}; BOOST_CHECK_EQUAL(ref, val); } const auto error{std::abs(val - val_ref)}; BOOST_CHECK_EQUAL(error, 0); } for (auto && tup : akantu::zip(t4map.get_collection(), t4map, t4map.enumerate())) { const auto & ccoord_ref = std::get<0>(tup); const auto & val_ref = std::get<1>(tup); const auto & key_val = std::get<2>(tup); const auto & ccoord = std::get<0>(key_val); const auto & val = std::get<1>(key_val); for (auto && ccoords : akantu::zip(ccoord_ref, ccoord)) { const auto & ref{std::get<0>(ccoords)}; const auto & val{std::get<1>(ccoords)}; BOOST_CHECK_EQUAL(ref, val); } const auto error{(val - val_ref).norm()}; BOOST_CHECK_EQUAL(error, 0); } for (auto && tup : akantu::zip(t2map.get_collection(), t2map, t2map.enumerate())) { const auto & ccoord_ref = std::get<0>(tup); const auto & val_ref = std::get<1>(tup); const auto & key_val = std::get<2>(tup); const auto & ccoord = std::get<0>(key_val); const auto & val = std::get<1>(key_val); for (auto && ccoords : akantu::zip(ccoord_ref, ccoord)) { const auto & ref{std::get<0>(ccoords)}; const auto & val{std::get<1>(ccoords)}; BOOST_CHECK_EQUAL(ref, val); } const auto error{(val - val_ref).norm()}; BOOST_CHECK_EQUAL(error, 0); } for (auto && tup : akantu::zip(m2map.get_collection(), m2map, m2map.enumerate())) { const auto & ccoord_ref = std::get<0>(tup); const auto & val_ref = std::get<1>(tup); const auto & key_val = std::get<2>(tup); const auto & ccoord = std::get<0>(key_val); const auto & val = std::get<1>(key_val); for (auto && ccoords : akantu::zip(ccoord_ref, ccoord)) { const auto & ref{std::get<0>(ccoords)}; const auto & val{std::get<1>(ccoords)}; BOOST_CHECK_EQUAL(ref, val); } const auto error{(val - val_ref).norm()}; BOOST_CHECK_EQUAL(error, 0); } for (auto && tup : akantu::zip(dymap.get_collection(), dymap, dymap.enumerate())) { const auto & ccoord_ref = std::get<0>(tup); const auto & val_ref = std::get<1>(tup); const auto & key_val = std::get<2>(tup); const auto & ccoord = std::get<0>(key_val); const auto & val = std::get<1>(key_val); for (auto && ccoords : akantu::zip(ccoord_ref, ccoord)) { const auto & ref{std::get<0>(ccoords)}; const auto & val{std::get<1>(ccoords)}; BOOST_CHECK_EQUAL(ref, val); } const auto error{(val - val_ref).matrix().norm()}; BOOST_CHECK_EQUAL(error, 0); } } BOOST_AUTO_TEST_SUITE_END(); -} // namespace muSpectre +} // namespace muGrid diff --git a/tests/header_test_fields.cc b/tests/libmugrid/header_test_fields.cc similarity index 98% rename from tests/header_test_fields.cc rename to tests/libmugrid/header_test_fields.cc index 509be20..c105424 100644 --- a/tests/header_test_fields.cc +++ b/tests/libmugrid/header_test_fields.cc @@ -1,273 +1,273 @@ /** * @file header_test_fields.cc * * @author Till Junge * * @date 20 Sep 2017 * * @brief Test Fields that are used in FieldCollections * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "tests.hh" -#include "common/field_collection.hh" -#include "common/field.hh" -#include "common/ccoord_operations.hh" +#include +#include +#include #include #include -namespace muSpectre { +namespace muGrid { BOOST_AUTO_TEST_SUITE(field_test); template struct FieldFixture { constexpr static bool IsGlobal{Global}; constexpr static Dim_t Order{secondOrder}; constexpr static Dim_t SDim{twoD}; constexpr static Dim_t MDim{threeD}; constexpr static Dim_t NbComponents{ipow(MDim, Order)}; using FieldColl_t = std::conditional_t, LocalFieldCollection>; using TField_t = TensorField; using MField_t = MatrixField; using DField_t = TypedField; FieldFixture() : tensor_field{make_field("TensorField", this->fc)}, matrix_field{make_field("MatrixField", this->fc)}, dynamic_field1{make_field( "Dynamically sized field with correct number of" " components", this->fc, ipow(MDim, Order))}, dynamic_field2{make_field( "Dynamically sized field with incorrect number" " of components", this->fc, NbComponents + 1)} {} ~FieldFixture() = default; FieldColl_t fc{}; TField_t & tensor_field; MField_t & matrix_field; DField_t & dynamic_field1; DField_t & dynamic_field2; }; using field_fixtures = boost::mpl::list, FieldFixture>; /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE(size_check_global, FieldFixture) { // check that fields are initialised with empty vector BOOST_CHECK_EQUAL(tensor_field.size(), 0); BOOST_CHECK_EQUAL(dynamic_field1.size(), 0); BOOST_CHECK_EQUAL(dynamic_field2.size(), 0); // check that returned size is correct Dim_t len{2}; auto sizes{CcoordOps::get_cube(len)}; fc.initialise(sizes, {}); auto nb_pixels{CcoordOps::get_size(sizes)}; BOOST_CHECK_EQUAL(tensor_field.size(), nb_pixels); BOOST_CHECK_EQUAL(dynamic_field1.size(), nb_pixels); BOOST_CHECK_EQUAL(dynamic_field2.size(), nb_pixels); constexpr Dim_t pad_size{3}; tensor_field.set_pad_size(pad_size); dynamic_field1.set_pad_size(pad_size); dynamic_field2.set_pad_size(pad_size); // check that setting pad size won't change logical size BOOST_CHECK_EQUAL(tensor_field.size(), nb_pixels); BOOST_CHECK_EQUAL(dynamic_field1.size(), nb_pixels); BOOST_CHECK_EQUAL(dynamic_field2.size(), nb_pixels); } /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE(size_check_local, FieldFixture) { // check that fields are initialised with empty vector BOOST_CHECK_EQUAL(tensor_field.size(), 0); BOOST_CHECK_EQUAL(dynamic_field1.size(), 0); BOOST_CHECK_EQUAL(dynamic_field2.size(), 0); // check that returned size is correct Dim_t nb_pixels{3}; Eigen::Array new_elem; Eigen::Array wrong_elem; for (Dim_t i{0}; i < NbComponents; ++i) { new_elem(i) = i; wrong_elem(i) = .1 * i; } for (Dim_t i{0}; i < nb_pixels; ++i) { tensor_field.push_back(new_elem); dynamic_field1.push_back(new_elem); BOOST_CHECK_THROW(dynamic_field1.push_back(wrong_elem), FieldError); BOOST_CHECK_THROW(dynamic_field2.push_back(new_elem), FieldError); } BOOST_CHECK_EQUAL(tensor_field.size(), nb_pixels); BOOST_CHECK_EQUAL(dynamic_field1.size(), nb_pixels); BOOST_CHECK_EQUAL(dynamic_field2.size(), 0); for (Dim_t i{0}; i < nb_pixels; ++i) { fc.add_pixel({i}); } fc.initialise(); BOOST_CHECK_EQUAL(tensor_field.size(), nb_pixels); BOOST_CHECK_EQUAL(dynamic_field1.size(), nb_pixels); BOOST_CHECK_EQUAL(dynamic_field2.size(), nb_pixels); BOOST_CHECK_EQUAL(tensor_field.get_pad_size(), 0); BOOST_CHECK_EQUAL(dynamic_field1.get_pad_size(), 0); BOOST_CHECK_EQUAL(dynamic_field2.get_pad_size(), 0); constexpr Dim_t pad_size{3}; tensor_field.set_pad_size(pad_size); dynamic_field1.set_pad_size(pad_size); dynamic_field2.set_pad_size(pad_size); BOOST_CHECK_EQUAL(tensor_field.get_pad_size(), pad_size); BOOST_CHECK_EQUAL(dynamic_field1.get_pad_size(), pad_size); BOOST_CHECK_EQUAL(dynamic_field2.get_pad_size(), pad_size); // check that setting pad size won't change logical size BOOST_CHECK_EQUAL(tensor_field.size(), nb_pixels); BOOST_CHECK_EQUAL(dynamic_field1.size(), nb_pixels); BOOST_CHECK_EQUAL(dynamic_field2.size(), nb_pixels); } BOOST_AUTO_TEST_CASE(simple_creation) { constexpr Dim_t sdim{twoD}; constexpr Dim_t mdim{twoD}; constexpr Dim_t order{fourthOrder}; using FC_t = GlobalFieldCollection; FC_t fc; using TF_t = TensorField; auto & field{make_field("TensorField 1", fc)}; // check that fields are initialised with empty vector BOOST_CHECK_EQUAL(field.size(), 0); Dim_t len{2}; fc.initialise(CcoordOps::get_cube(len), {}); // check that returned size is correct BOOST_CHECK_EQUAL(field.size(), ipow(len, sdim)); // check that setting pad size won't change logical size field.set_pad_size(24); BOOST_CHECK_EQUAL(field.size(), ipow(len, sdim)); } BOOST_AUTO_TEST_CASE(dynamic_field_creation) { constexpr Dim_t sdim{threeD}; Dim_t nb_components{2}; using FC_t = GlobalFieldCollection; FC_t fc{}; make_field>("Dynamic Field", fc, nb_components); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(get_zeros_like, Fix, field_fixtures, Fix) { auto & t_clone{Fix::tensor_field.get_zeros_like("tensor clone")}; static_assert(std::is_same, typename Fix::TField_t>::value, "wrong overloaded function"); auto & m_clone{Fix::matrix_field.get_zeros_like("matrix clone")}; static_assert(std::is_same, typename Fix::MField_t>::value, "wrong overloaded function"); using FieldColl_t = typename Fix::FieldColl_t; using T = typename Fix::TField_t::Scalar; TypedField & t_ref{t_clone}; auto & typed_clone{t_ref.get_zeros_like("dynamically sized clone")}; static_assert(std::is_same, TypedField>::value, "Field type incorrectly deduced"); BOOST_CHECK_EQUAL(typed_clone.get_nb_components(), t_clone.get_nb_components()); auto & dyn_clone{Fix::dynamic_field1.get_zeros_like("dynamic clone")}; static_assert( std::is_same::value, "mismatch"); BOOST_CHECK_EQUAL(typed_clone.get_nb_components(), dyn_clone.get_nb_components()); } /* ---------------------------------------------------------------------- */ BOOST_AUTO_TEST_CASE(fill_global_local) { FieldFixture global; FieldFixture local; constexpr Dim_t len{2}; constexpr auto sizes{CcoordOps::get_cube::SDim>(len)}; global.fc.initialise(sizes, {}); local.fc.add_pixel({1, 1}); local.fc.add_pixel({0, 1}); local.fc.initialise(); // fill the local matrix field and then transfer it to the global field for (auto mat : local.matrix_field.get_map()) { mat.setRandom(); } global.matrix_field.fill_from_local(local.matrix_field); for (const auto & ccoord : local.fc) { const auto & a{local.matrix_field.get_map()[ccoord]}; const auto & b{global.matrix_field.get_map()[ccoord]}; const Real error{(a - b).norm()}; BOOST_CHECK_EQUAL(error, 0.); } // fill the global tensor field and then transfer it to the global field for (auto mat : global.tensor_field.get_map()) { mat.setRandom(); } local.tensor_field.fill_from_global(global.tensor_field); for (const auto & ccoord : local.fc) { const auto & a{local.matrix_field.get_map()[ccoord]}; const auto & b{global.matrix_field.get_map()[ccoord]}; const Real error{(a - b).norm()}; BOOST_CHECK_EQUAL(error, 0.); } BOOST_CHECK_THROW(local.tensor_field.fill_from_global(global.matrix_field), std::runtime_error); BOOST_CHECK_THROW(global.tensor_field.fill_from_local(local.matrix_field), std::runtime_error); } BOOST_AUTO_TEST_SUITE_END(); -} // namespace muSpectre +} // namespace muGrid diff --git a/tests/header_test_raw_field_map.cc b/tests/libmugrid/header_test_raw_field_map.cc similarity index 97% rename from tests/header_test_raw_field_map.cc rename to tests/libmugrid/header_test_raw_field_map.cc index 40b01fb..1b079fe 100644 --- a/tests/header_test_raw_field_map.cc +++ b/tests/libmugrid/header_test_raw_field_map.cc @@ -1,100 +1,100 @@ /** * file header_test_raw_field_map.cc * * @author Till Junge * * @date 17 Apr 2018 * * @brief tests for the raw field map type * * @section LICENSE * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "test_field_collections.hh" -#include "common/field_map.hh" +#include -namespace muSpectre { +namespace muGrid { BOOST_AUTO_TEST_SUITE(raw_field_map_tests); BOOST_FIXTURE_TEST_CASE_TEMPLATE(iter_field_test, F, iter_collections, F) { using FC_t = typename F::Parent::FC_t; using MSqMap = MatrixFieldMap; MSqMap Mmap{F::fc["Tensorfield Real o2"]}; auto m_it = Mmap.begin(); auto m_it_end = Mmap.end(); RawFieldMap< Eigen::Map>> raw_map{Mmap.get_field().eigenvec()}; for (auto && mat : Mmap) { mat.setRandom(); } for (auto tup : akantu::zip(Mmap, raw_map)) { auto & mat_A = std::get<0>(tup); auto & mat_B = std::get<1>(tup); BOOST_CHECK_EQUAL((mat_A - mat_B).norm(), 0.); } Mmap.get_field().eigenvec().setZero(); for (auto && mat : raw_map) { mat.setIdentity(); } for (auto && mat : Mmap) { BOOST_CHECK_EQUAL((mat - mat.Identity()).norm(), 0.); } } BOOST_AUTO_TEST_CASE(Const_correctness_test) { Eigen::VectorXd vec1(12); vec1.setRandom(); RawFieldMap> map1{vec1}; static_assert(not map1.IsConst, "should not have been const"); RawFieldMap> cmap1{vec1}; static_assert(cmap1.IsConst, "should have been const"); const Eigen::VectorXd vec2{vec1}; RawFieldMap> cmap2{vec2}; } BOOST_AUTO_TEST_CASE(incompatible_size_check) { Eigen::VectorXd vec1(11); using RawFieldMap_t = RawFieldMap>; BOOST_CHECK_THROW(RawFieldMap_t{vec1}, std::runtime_error); } BOOST_AUTO_TEST_SUITE_END(); -} // namespace muSpectre +} // namespace muGrid diff --git a/tests/header_test_ref_array.cc b/tests/libmugrid/header_test_ref_array.cc similarity index 95% rename from tests/header_test_ref_array.cc rename to tests/libmugrid/header_test_ref_array.cc index b11e4dd..5ac6a69 100644 --- a/tests/header_test_ref_array.cc +++ b/tests/libmugrid/header_test_ref_array.cc @@ -1,52 +1,53 @@ /** * @file header_test_ref_array.cc * * @author Till Junge * * @date 04 Dec 2018 * * @brief tests for the RefArray convenience struct * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#include "common/ref_array.hh" #include "tests.hh" -namespace muSpectre { +#include + +namespace muGrid { BOOST_AUTO_TEST_SUITE(RefArray_tests); BOOST_AUTO_TEST_CASE(two_d_test) { std::array values{2, 3}; RefArray refs{values[0], values[1]}; BOOST_CHECK_EQUAL(values[0], refs[0]); BOOST_CHECK_EQUAL(values[1], refs[1]); } BOOST_AUTO_TEST_SUITE_END(); -} // namespace muSpectre +} // namespace muGrid diff --git a/tests/header_test_statefields.cc b/tests/libmugrid/header_test_statefields.cc similarity index 98% rename from tests/header_test_statefields.cc rename to tests/libmugrid/header_test_statefields.cc index e409c2b..6d09522 100644 --- a/tests/header_test_statefields.cc +++ b/tests/libmugrid/header_test_statefields.cc @@ -1,299 +1,300 @@ /** * file header_test_statefields.cc * * @author Till Junge * * @date 01 Mar 2018 * * @brief Test the StateField abstraction and the associated maps * * @section LICENSE * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ - -#include "common/field.hh" -#include "common/field_collection.hh" -#include "common/statefield.hh" -#include "common/ccoord_operations.hh" #include "tests.hh" +#include +#include +#include +#include + #include #include +#include -namespace muSpectre { +namespace muGrid { template struct SF_Fixture { using FC_t = std::conditional_t, LocalFieldCollection>; using Field_t = TensorField; using ScalField_t = ScalarField; constexpr static size_t nb_mem{2}; constexpr static Dim_t sdim{DimS}; constexpr static Dim_t mdim{DimM}; constexpr static bool global{Global}; constexpr static size_t get_nb_mem() { return nb_mem; } constexpr static Dim_t get_sdim() { return sdim; } constexpr static Dim_t get_mdim() { return mdim; } constexpr static bool get_global() { return global; } SF_Fixture() : fc{}, sf{make_statefield>("prefix", fc)}, scalar_f{ make_statefield>("scalar", fc)}, self{*this} {} FC_t fc; StateField & sf; StateField & scalar_f; SF_Fixture & self; }; using typelist = boost::mpl::list< SF_Fixture, SF_Fixture, SF_Fixture, SF_Fixture, SF_Fixture, SF_Fixture>; BOOST_AUTO_TEST_SUITE(statefield); BOOST_AUTO_TEST_CASE(old_values_test) { constexpr Dim_t Dim{twoD}; constexpr size_t NbMem{2}; constexpr bool verbose{false}; using FC_t = LocalFieldCollection; FC_t fc{}; using Field_t = ScalarField; auto & statefield{make_statefield>("name", fc)}; fc.add_pixel({}); fc.initialise(); for (size_t i{0}; i < NbMem + 1; ++i) { statefield.current().eigen() = i + 1; if (verbose) { std::cout << "current = " << statefield.current().eigen() << std::endl << "old 1 = " << statefield.old().eigen() << std::endl << "old 2 = " << statefield.template old<2>().eigen() << std::endl << "indices = " << statefield.get_indices() << std::endl << std::endl; } statefield.cycle(); } BOOST_CHECK_EQUAL(statefield.current().eigen()(0), 1); BOOST_CHECK_EQUAL(statefield.old().eigen()(0), 3); BOOST_CHECK_EQUAL(statefield.template old<2>().eigen()(0), 2); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(constructor_test, Fix, typelist, Fix) { const std::string ref{"prefix"}; const std::string & fix{Fix::sf.get_prefix()}; BOOST_CHECK_EQUAL(ref, fix); } namespace internal { template struct init { static void run(Fixture_t & fix) { constexpr Dim_t dim{std::remove_reference_t::sdim}; fix.fc.initialise(CcoordOps::get_cube(3), CcoordOps::get_cube(0)); } }; template struct init { static void run(Fixture_t & fix) { constexpr Dim_t dim{std::remove_reference_t::sdim}; CcoordOps::Pixels pixels(CcoordOps::get_cube(3), CcoordOps::get_cube(0)); for (auto && pix : pixels) { fix.fc.add_pixel(pix); } fix.fc.initialise(); } }; } // namespace internal BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_iteration, Fix, typelist, Fix) { internal::init::run(Fix::self); constexpr Dim_t mdim{Fix::mdim}; constexpr bool verbose{false}; using StateFMap = StateFieldMap, Fix::nb_mem>; StateFMap matrix_map(Fix::sf); for (size_t i = 0; i < Fix::nb_mem + 1; ++i) { for (auto && wrapper : matrix_map) { wrapper.current() += (i + 1) * wrapper.current().Identity(); if (verbose) { std::cout << "pixel " << wrapper.get_ccoord() << ", memory cycle " << i << std::endl; std::cout << wrapper.current() << std::endl; std::cout << wrapper.old() << std::endl; std::cout << wrapper.template old<2>() << std::endl << std::endl; } } Fix::sf.cycle(); } for (auto && wrapper : matrix_map) { auto I{wrapper.current().Identity()}; Real error{(wrapper.current() - I).norm()}; BOOST_CHECK_LT(error, tol); error = (wrapper.old() - 3 * I).norm(); BOOST_CHECK_LT(error, tol); error = (wrapper.template old<2>() - 2 * I).norm(); BOOST_CHECK_LT(error, tol); } } BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_default_map, Fix, typelist, Fix) { internal::init::run(Fix::self); constexpr bool verbose{false}; auto matrix_map{Fix::sf.get_map()}; for (size_t i = 0; i < Fix::nb_mem + 1; ++i) { for (auto && wrapper : matrix_map) { wrapper.current() += (i + 1) * wrapper.current().Identity(); if (verbose) { std::cout << "pixel " << wrapper.get_ccoord() << ", memory cycle " << i << std::endl; std::cout << wrapper.current() << std::endl; std::cout << wrapper.old() << std::endl; std::cout << wrapper.template old<2>() << std::endl << std::endl; } } Fix::sf.cycle(); } auto matrix_const_map{Fix::sf.get_const_map()}; for (auto && wrapper : matrix_const_map) { auto I{wrapper.current().Identity()}; Real error{(wrapper.current() - I).norm()}; BOOST_CHECK_LT(error, tol); error = (wrapper.old() - 3 * I).norm(); BOOST_CHECK_LT(error, tol); error = (wrapper.template old<2>() - 2 * I).norm(); BOOST_CHECK_LT(error, tol); } } BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_scalar_map, Fix, typelist, Fix) { internal::init::run(Fix::self); constexpr bool verbose{false}; auto scalar_map{Fix::scalar_f.get_map()}; for (size_t i = 0; i < Fix::nb_mem + 1; ++i) { for (auto && wrapper : scalar_map) { wrapper.current() += (i + 1); if (verbose) { std::cout << "pixel " << wrapper.get_ccoord() << ", memory cycle " << i << std::endl; std::cout << wrapper.current() << std::endl; std::cout << wrapper.old() << std::endl; std::cout << wrapper.template old<2>() << std::endl << std::endl; } } Fix::scalar_f.cycle(); } auto scalar_const_map{Fix::scalar_f.get_const_map()}; BOOST_CHECK_EQUAL(scalar_const_map[0].current(), scalar_const_map[1].current()); for (auto wrapper : scalar_const_map) { Real error{wrapper.current() - 1}; BOOST_CHECK_LT(error, tol); error = wrapper.old() - 3; BOOST_CHECK_LT(error, tol); error = wrapper.template old<2>() - 2; BOOST_CHECK_LT(error, tol); } } /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE_TEMPLATE(Polymorphic_access_by_name, Fix, typelist, Fix) { internal::init::run(Fix::self); // constexpr bool verbose{true}; auto & tensor_field = Fix::fc.get_statefield("prefix"); BOOST_CHECK_EQUAL(tensor_field.get_nb_memory(), Fix::get_nb_mem()); auto & field = Fix::fc.template get_current("prefix"); BOOST_CHECK_EQUAL(field.get_nb_components(), ipow(Fix::get_mdim(), secondOrder)); BOOST_CHECK_THROW(Fix::fc.template get_current("prefix"), std::runtime_error); auto & old_field = Fix::fc.template get_old("prefix"); BOOST_CHECK_EQUAL(old_field.get_nb_components(), field.get_nb_components()); BOOST_CHECK_THROW( Fix::fc.template get_old("prefix", Fix::get_nb_mem() + 1), std::out_of_range); auto & statefield{Fix::fc.get_statefield("prefix")}; auto & typed_statefield{ Fix::fc.template get_typed_statefield("prefix")}; auto map{ArrayFieldMap( typed_statefield.get_current_field())}; for (auto arr : map) { arr.setConstant(1); } Eigen::ArrayXXd field_copy{field.eigen()}; statefield.cycle(); auto & alt_old_field{typed_statefield.get_old_field()}; Real err{(field_copy - alt_old_field.eigen()).matrix().norm() / field_copy.matrix().norm()}; BOOST_CHECK_LT(err, tol); if (not(err < tol)) { std::cout << field_copy << std::endl << std::endl << typed_statefield.get_current_field().eigen() << std::endl << std::endl << typed_statefield.get_old_field(1).eigen() << std::endl << std::endl << typed_statefield.get_old_field(2).eigen() << std::endl; } } BOOST_AUTO_TEST_SUITE_END(); -} // namespace muSpectre +} // namespace muGrid diff --git a/tests/header_test_t4_map.cc b/tests/libmugrid/header_test_t4_map.cc similarity index 98% rename from tests/header_test_t4_map.cc rename to tests/libmugrid/header_test_t4_map.cc index 2c082e4..6c4f244 100644 --- a/tests/header_test_t4_map.cc +++ b/tests/libmugrid/header_test_t4_map.cc @@ -1,201 +1,199 @@ /** * @file header_test_t4_map.cc * * @author Till Junge * * @date 20 Nov 2017 * * @brief Test the fourth-order map on second-order tensor implementation * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include #include #include #include - -#include "common/common.hh" +#include #include "tests.hh" #include "test_goodies.hh" -#include "common/T4_map_proxy.hh" -namespace muSpectre { +namespace muGrid { BOOST_AUTO_TEST_SUITE(T4map_tests); /** * Test fixture for construction of T4Map for the time being, symmetry is not * exploited */ template struct T4_fixture { T4_fixture() : matrix{}, tensor(matrix.data()) {} EIGEN_MAKE_ALIGNED_OPERATOR_NEW; using M4 = T4Mat; using T4 = T4MatMap; constexpr static Dim_t dim{Dim}; M4 matrix; T4 tensor; }; using fix_collection = boost::mpl::list, T4_fixture>; BOOST_FIXTURE_TEST_CASE_TEMPLATE(Simple_construction_test, F, fix_collection, F) { BOOST_CHECK_EQUAL(F::tensor.cols(), F::dim * F::dim); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(write_access_test, F, fix_collection, F) { auto & t4 = F::tensor; constexpr Dim_t dim{F::dim}; Eigen::TensorFixedSize> t4c; Eigen::Map t4c_map(t4c.data()); for (Dim_t i = 0; i < F::dim; ++i) { for (Dim_t j = 0; j < F::dim; ++j) { for (Dim_t k = 0; k < F::dim; ++k) { for (Dim_t l = 0; l < F::dim; ++l) { get(t4, i, j, k, l) = 1000 * (i + 1) + 100 * (j + 1) + 10 * (k + 1) + l + 1; t4c(i, j, k, l) = 1000 * (i + 1) + 100 * (j + 1) + 10 * (k + 1) + l + 1; } } } } for (Dim_t i = 0; i < ipow(dim, 4); ++i) { BOOST_CHECK_EQUAL(F::matrix.data()[i], t4c.data()[i]); } } BOOST_FIXTURE_TEST_CASE_TEMPLATE(numpy_compatibility, F, fix_collection, F) { auto & t4 = F::tensor; typename F::M4 numpy_ref{}; if (F::dim == twoD) { numpy_ref << 1111., 1112., 1121., 1122., 1211., 1212., 1221., 1222., 2111., 2112., 2121., 2122., 2211., 2212., 2221., 2222.; } else { numpy_ref << 1111., 1112., 1113., 1121., 1122., 1123., 1131., 1132., 1133., 1211., 1212., 1213., 1221., 1222., 1223., 1231., 1232., 1233., 1311., 1312., 1313., 1321., 1322., 1323., 1331., 1332., 1333., 2111., 2112., 2113., 2121., 2122., 2123., 2131., 2132., 2133., 2211., 2212., 2213., 2221., 2222., 2223., 2231., 2232., 2233., 2311., 2312., 2313., 2321., 2322., 2323., 2331., 2332., 2333., 3111., 3112., 3113., 3121., 3122., 3123., 3131., 3132., 3133., 3211., 3212., 3213., 3221., 3222., 3223., 3231., 3232., 3233., 3311., 3312., 3313., 3321., 3322., 3323., 3331., 3332., 3333.; } for (Dim_t i = 0; i < F::dim; ++i) { for (Dim_t j = 0; j < F::dim; ++j) { for (Dim_t k = 0; k < F::dim; ++k) { for (Dim_t l = 0; l < F::dim; ++l) { get(t4, i, j, k, l) = 1000 * (i + 1) + 100 * (j + 1) + 10 * (k + 1) + l + 1; } } } } Real error{(t4 - testGoodies::from_numpy(numpy_ref)).norm()}; BOOST_CHECK_EQUAL(error, 0); if (error != 0) { std::cout << "T4:" << std::endl << t4 << std::endl; std::cout << "reshuffled np:" << std::endl << testGoodies::from_numpy(numpy_ref) << std::endl; std::cout << "original np:" << std::endl << numpy_ref << std::endl; } } BOOST_FIXTURE_TEST_CASE_TEMPLATE(numpy_right_trans, F, fix_collection, F) { auto & t4 = F::tensor; typename F::M4 numpy_ref{}; if (F::dim == twoD) { numpy_ref << 1111., 1121., 1112., 1122., 1211., 1221., 1212., 1222., 2111., 2121., 2112., 2122., 2211., 2221., 2212., 2222.; } else { numpy_ref << 1111., 1121., 1131., 1112., 1122., 1132., 1113., 1123., 1133., 1211., 1221., 1231., 1212., 1222., 1232., 1213., 1223., 1233., 1311., 1321., 1331., 1312., 1322., 1332., 1313., 1323., 1333., 2111., 2121., 2131., 2112., 2122., 2132., 2113., 2123., 2133., 2211., 2221., 2231., 2212., 2222., 2232., 2213., 2223., 2233., 2311., 2321., 2331., 2312., 2322., 2332., 2313., 2323., 2333., 3111., 3121., 3131., 3112., 3122., 3132., 3113., 3123., 3133., 3211., 3221., 3231., 3212., 3222., 3232., 3213., 3223., 3233., 3311., 3321., 3331., 3312., 3322., 3332., 3313., 3323., 3333.; } for (Dim_t i = 0; i < F::dim; ++i) { for (Dim_t j = 0; j < F::dim; ++j) { for (Dim_t k = 0; k < F::dim; ++k) { for (Dim_t l = 0; l < F::dim; ++l) { get(t4, i, j, k, l) = 1000 * (i + 1) + 100 * (j + 1) + 10 * (k + 1) + l + 1; } } } } Real error{(t4 - testGoodies::right_transpose(numpy_ref)).norm()}; BOOST_CHECK_EQUAL(error, 0); if (error != 0) { std::cout << "T4:" << std::endl << t4 << std::endl; std::cout << "reshuffled np:" << std::endl << testGoodies::from_numpy(numpy_ref) << std::endl; std::cout << "original np:" << std::endl << numpy_ref << std::endl; } } BOOST_FIXTURE_TEST_CASE_TEMPLATE(assign_matrix_test, F, fix_collection, F) { decltype(F::matrix) matrix; matrix.setRandom(); F::tensor = matrix; for (Dim_t i = 0; i < ipow(F::dim, 4); ++i) { BOOST_CHECK_EQUAL(F::matrix.data()[i], matrix.data()[i]); } } BOOST_AUTO_TEST_CASE(Return_ref_from_const_test) { constexpr Dim_t dim{2}; using T = int; using M4 = Eigen::Matrix; using M4c = const Eigen::Matrix; using T4 = T4MatMap; using T4c = T4MatMap; M4 mat; mat.setRandom(); M4c cmat{mat}; T4 tensor{mat.data()}; T4c ctensor{mat.data()}; T a = get(tensor, 0, 0, 0, 1); T b = get(ctensor, 0, 0, 0, 1); BOOST_CHECK_EQUAL(a, b); } BOOST_AUTO_TEST_SUITE_END(); -} // namespace muSpectre +} // namespace muGrid diff --git a/tests/header_test_tensor_algebra.cc b/tests/libmugrid/header_test_tensor_algebra.cc similarity index 98% rename from tests/header_test_tensor_algebra.cc rename to tests/libmugrid/header_test_tensor_algebra.cc index 7db7f91..00bffad 100644 --- a/tests/header_test_tensor_algebra.cc +++ b/tests/libmugrid/header_test_tensor_algebra.cc @@ -1,296 +1,296 @@ /** * @file header_test_tensor_algebra.cc * * @author Till Junge * * @date 05 Nov 2017 * * @brief Tests for the tensor algebra functions * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include #include -#include "common/tensor_algebra.hh" #include "tests.hh" -#include "tests/test_goodies.hh" - -namespace muSpectre { +#include "test_goodies.hh" +#include +#include +namespace muGrid { BOOST_AUTO_TEST_SUITE(tensor_algebra) auto TerrNorm = [](auto && t) { return Eigen::Tensor(t.abs().sum())(); }; /* ---------------------------------------------------------------------- */ BOOST_AUTO_TEST_CASE(tensor_outer_product_test) { constexpr Dim_t dim{2}; Eigen::TensorFixedSize> A, B; // use prime numbers so that every multiple is uniquely identifiable A.setValues({{1, 2}, {3, 7}}); B.setValues({{11, 13}, {17, 19}}); Eigen::TensorFixedSize> Res1, Res2, Res3; for (Dim_t i = 0; i < dim; ++i) { for (Dim_t j = 0; j < dim; ++j) { for (Dim_t k = 0; k < dim; ++k) { for (Dim_t l = 0; l < dim; ++l) { Res1(i, j, k, l) = A(i, j) * B(k, l); Res2(i, j, k, l) = A(i, k) * B(j, l); Res3(i, j, k, l) = A(i, l) * B(j, k); } } } } Real error = TerrNorm(Res1 - Tensors::outer(A, B)); BOOST_CHECK_LT(error, tol); error = TerrNorm(Res2 - Tensors::outer_under(A, B)); BOOST_CHECK_LT(error, tol); error = TerrNorm(Res3 - Tensors::outer_over(A, B)); if (error > tol) { std::cout << "reference:" << std::endl << Res3 << std::endl; std::cout << "result:" << std::endl << Tensors::outer_over(A, B) << std::endl; std::cout << "A:" << std::endl << A << std::endl; std::cout << "B" << std::endl << B << std::endl; decltype(Res3) tmp = Tensors::outer_over(A, B); for (Dim_t i = 0; i < dim; ++i) { for (Dim_t j = 0; j < dim; ++j) { for (Dim_t k = 0; k < dim; ++k) { for (Dim_t l = 0; l < dim; ++l) { std::cout << "for (" << i << ", " << j << ", " << k << ", " << l << "), ref: " << std::setw(3) << Res3(i, j, k, l) << ", res: " << std::setw(3) << tmp(i, j, k, l) << std::endl; } } } } } BOOST_CHECK_LT(error, tol); error = TerrNorm(Res3 - Tensors::outer(A, B)); BOOST_CHECK_GT(error, tol); }; BOOST_FIXTURE_TEST_CASE_TEMPLATE(outer_products, Fix, testGoodies::dimlist, Fix) { constexpr auto dim{Fix::dim}; using T2 = Tensors::Tens2_t; using M2 = Matrices::Tens2_t; using Map2 = Eigen::Map; using T4 = Tensors::Tens4_t; using M4 = Matrices::Tens4_t; using Map4 = Eigen::Map; T2 A, B; T4 RT; A.setRandom(); B.setRandom(); Map2 Amap(A.data()); Map2 Bmap(B.data()); M2 C, D; M4 RM; C = Amap; D = Bmap; auto error = [](const T4 & A, const M4 & B) { return (B - Map4(A.data())).norm(); }; // Check outer product RT = Tensors::outer(A, B); RM = Matrices::outer(C, D); BOOST_CHECK_LT(error(RT, RM), tol); // Check outer_under product RT = Tensors::outer_under(A, B); RM = Matrices::outer_under(C, D); BOOST_CHECK_LT(error(RT, RM), tol); // Check outer_over product RT = Tensors::outer_over(A, B); RM = Matrices::outer_over(C, D); BOOST_CHECK_LT(error(RT, RM), tol); } BOOST_AUTO_TEST_CASE(tensor_multiplication) { constexpr Dim_t dim{2}; using Strain_t = Eigen::TensorFixedSize>; Strain_t A, B; A.setValues({{1, 2}, {3, 7}}); B.setValues({{11, 13}, {17, 19}}); Strain_t FF1 = A * B; // element-wise multiplication std::array, 1> prod_dims{Eigen::IndexPair{1, 0}}; Strain_t FF2 = A.contract(B, prod_dims); // correct option 1 Strain_t FF3; using Mat_t = Eigen::Map>; // following only works for evaluated tensors (which already have data()) Mat_t(FF3.data()) = Mat_t(A.data()) * Mat_t(B.data()); Strain_t ref; ref.setZero(); for (Dim_t i = 0; i < dim; ++i) { for (Dim_t j = 0; j < dim; ++j) { for (Dim_t a = 0; a < dim; ++a) { ref(i, j) += A(i, a) * B(a, j); } } } using Strain_tw = Eigen::TensorFixedSize>; Strain_tw C; C.setConstant(100); // static_assert(!std::is_convertible::value, // "Tensors not size-protected"); if (std::is_convertible::value) { // std::cout << "this is not good, should I abandon Tensors?"; } // this test seems useless. I use to detect if Eigen changed the // default tensor product Real error = TerrNorm(FF1 - ref); if (error < tol) { std::cout << "A =" << std::endl << A << std::endl; std::cout << "B =" << std::endl << B << std::endl; std::cout << "FF1 =" << std::endl << FF1 << std::endl; std::cout << "ref =" << std::endl << ref << std::endl; } BOOST_CHECK_GT(error, tol); error = TerrNorm(FF2 - ref); if (error > tol) { std::cout << "A =" << std::endl << A << std::endl; std::cout << "B =" << std::endl << B << std::endl; std::cout << "FF2 =" << std::endl << FF2 << std::endl; std::cout << "ref =" << std::endl << ref << std::endl; } BOOST_CHECK_LT(error, tol); error = TerrNorm(FF3 - ref); if (error > tol) { std::cout << "A =" << std::endl << A << std::endl; std::cout << "B =" << std::endl << B << std::endl; std::cout << "FF3 =" << std::endl << FF3 << std::endl; std::cout << "ref =" << std::endl << ref << std::endl; } BOOST_CHECK_LT(error, tol); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_tensmult, Fix, testGoodies::dimlist, Fix) { using Matrices::Tens2_t; using Matrices::Tens4_t; using Matrices::tensmult; constexpr Dim_t dim{Fix::dim}; using T4 = Tens4_t; using T2 = Tens2_t; using V2 = Eigen::Matrix; T4 C; C.setRandom(); T2 E; E.setRandom(); Eigen::Map Ev(E.data()); T2 R = tensmult(C, E); auto error = (Eigen::Map(R.data()) - C * Ev).norm(); BOOST_CHECK_LT(error, tol); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_tracer, Fix, testGoodies::dimlist, Fix) { using Matrices::Tens2_t; using Matrices::Tens4_t; using Matrices::tensmult; constexpr Dim_t dim{Fix::dim}; using T2 = Tens2_t; auto tracer = Matrices::Itrac(); T2 F; F.setRandom(); auto Ftrac = tensmult(tracer, F); auto error = (Ftrac - F.trace() * F.Identity()).norm(); BOOST_CHECK_LT(error, tol); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_identity, Fix, testGoodies::dimlist, Fix) { using Matrices::Tens2_t; using Matrices::Tens4_t; using Matrices::tensmult; constexpr Dim_t dim{Fix::dim}; using T2 = Tens2_t; auto ident = Matrices::Iiden(); T2 F; F.setRandom(); auto Fiden = tensmult(ident, F); auto error = (Fiden - F).norm(); BOOST_CHECK_LT(error, tol); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_transposer, Fix, testGoodies::dimlist, Fix) { using Matrices::Tens2_t; using Matrices::Tens4_t; using Matrices::tensmult; constexpr Dim_t dim{Fix::dim}; using T2 = Tens2_t; auto trnst = Matrices::Itrns(); T2 F; F.setRandom(); auto Ftrns = tensmult(trnst, F); auto error = (Ftrns - F.transpose()).norm(); BOOST_CHECK_LT(error, tol); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_symmetriser, Fix, testGoodies::dimlist, Fix) { using Matrices::Tens2_t; using Matrices::Tens4_t; using Matrices::tensmult; constexpr Dim_t dim{Fix::dim}; using T2 = Tens2_t; auto symmt = Matrices::Isymm(); T2 F; F.setRandom(); auto Fsymm = tensmult(symmt, F); auto error = (Fsymm - .5 * (F + F.transpose())).norm(); BOOST_CHECK_LT(error, tol); } BOOST_AUTO_TEST_SUITE_END(); -} // namespace muSpectre +} // namespace muGrid diff --git a/tests/tests.hh b/tests/libmugrid/main_test_suite.cc similarity index 76% copy from tests/tests.hh copy to tests/libmugrid/main_test_suite.cc index 4cb70de..6e5e995 100644 --- a/tests/tests.hh +++ b/tests/libmugrid/main_test_suite.cc @@ -1,49 +1,39 @@ /** - * @file tests.hh + * @file main_test_suite.cc * * @author Till Junge * - * @date 10 May 2017 + * @date 01 May 2017 * - * @brief common defs for tests + * @brief Main test suite. Running this suite tests all available tests for + * µSpectre * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ +#define BOOST_TEST_MODULE base_test test +#define BOOST_TEST_MAIN +#define BOOST_TEST_DYN_LINK -#include "common/common.hh" #include -#include - -#ifndef TESTS_TESTS_HH_ -#define TESTS_TESTS_HH_ - -namespace muSpectre { - - constexpr Real tol = 1e-14 * 100; // it's in percent - constexpr Real finite_diff_tol = 1e-7; // it's in percent - -} // namespace muSpectre - -#endif // TESTS_TESTS_HH_ diff --git a/tests/test_field_collections.hh b/tests/libmugrid/test_field_collections.hh similarity index 93% rename from tests/test_field_collections.hh rename to tests/libmugrid/test_field_collections.hh index b238956..d0a82e1 100644 --- a/tests/test_field_collections.hh +++ b/tests/libmugrid/test_field_collections.hh @@ -1,161 +1,161 @@ /** * @file test_field_collections.hh * * @author Till Junge * * @date 23 Nov 2017 * * @brief declares fixtures for field_collection tests, so that they can be * split * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#ifndef TESTS_TEST_FIELD_COLLECTIONS_HH_ -#define TESTS_TEST_FIELD_COLLECTIONS_HH_ +#ifndef TESTS_LIBMUGRID_TEST_FIELD_COLLECTIONS_HH_ +#define TESTS_LIBMUGRID_TEST_FIELD_COLLECTIONS_HH_ + +#include "test_goodies.hh" +#include "tests.hh" + +#include +#include +#include +#include #include #include #include #include #include #include -#include "common/common.hh" -#include "common/ccoord_operations.hh" -#include "tests/test_goodies.hh" -#include "tests.hh" -#include "common/field_collection.hh" -#include "common/field.hh" -#include "common/field_map.hh" - -namespace muSpectre { +namespace muGrid { //! Test fixture for simple tests on single field in collection template struct FC_fixture : public std::conditional_t, LocalFieldCollection> { FC_fixture() : fc() {} inline static constexpr Dim_t sdim() { return DimS; } inline static constexpr Dim_t mdim() { return DimM; } inline static constexpr bool global() { return Global; } using FC_t = std::conditional_t, LocalFieldCollection>; FC_t fc; }; using test_collections = boost::mpl::list, FC_fixture<2, 3, true>, FC_fixture<3, 3, true>, FC_fixture<2, 2, false>, FC_fixture<2, 3, false>, FC_fixture<3, 3, false>>; constexpr Dim_t order{4}, matrix_order{2}; //! Test fixture for multiple fields in the collection template struct FC_multi_fixture { using FC_t = std::conditional_t, LocalFieldCollection>; using T4_t = TensorField; using T2_t = TensorField; using Sc_t = ScalarField; using M2_t = MatrixField; using Dyn_t = TypedField; FC_multi_fixture() : fc(), t4_field{make_field("Tensorfield Real o4", fc)}, // Real tensor field t2_field{make_field("Tensorfield Real o2", fc)}, // Real tensor field sc_field{ make_field("integer Scalar", fc)}, // integer scalar field m2_field{make_field("Matrixfield Complex sdim x mdim", fc)}, // complex matrix field dyn_field{make_field("Dynamically sized Field", fc, 12)} {} inline static constexpr Dim_t sdim() { return DimS; } inline static constexpr Dim_t mdim() { return DimM; } inline static constexpr bool global() { return Global; } FC_t fc; T4_t & t4_field; T2_t & t2_field; Sc_t & sc_field; M2_t & m2_field; Dyn_t & dyn_field; }; using mult_collections = boost::mpl::list< FC_multi_fixture<2, 2, true>, FC_multi_fixture<2, 3, true>, FC_multi_fixture<3, 3, true>, FC_multi_fixture<2, 2, false>, FC_multi_fixture<2, 3, false>, FC_multi_fixture<3, 3, false>>; //! Test fixture for iterators over multiple fields template struct FC_iterator_fixture : public FC_multi_fixture { using Parent = FC_multi_fixture; FC_iterator_fixture() : Parent() { this->fill(); } template std::enable_if_t fill() { static_assert(Global == isGlobal, "You're breaking my SFINAE plan"); Ccoord_t size; Ccoord_t loc{}; for (auto && s : size) { s = cube_size(); } this->fc.initialise(size, loc); } template std::enable_if_t fill(int dummy = 0) { static_assert(notGlobal != Global, "You're breaking my SFINAE plan"); testGoodies::RandRange rng; this->fc.add_pixel({0, 0}); for (int i = 0 * dummy; i < sele_size(); ++i) { Ccoord_t pixel; for (auto && s : pixel) { s = rng.randval(0, 7); } this->fc.add_pixel(pixel); } this->fc.initialise(); } constexpr static Dim_t cube_size() { return 3; } constexpr static Dim_t sele_size() { return 7; } }; using iter_collections = boost::mpl::list< FC_iterator_fixture<2, 2, true>, FC_iterator_fixture<2, 3, true>, FC_iterator_fixture<3, 3, true>, FC_iterator_fixture<2, 2, false>, FC_iterator_fixture<2, 3, false>, FC_iterator_fixture<3, 3, false>>; using glob_iter_colls = boost::mpl::list, FC_iterator_fixture<2, 3, true>, FC_iterator_fixture<3, 3, true>>; -} // namespace muSpectre +} // namespace muGrid -#endif // TESTS_TEST_FIELD_COLLECTIONS_HH_ +#endif // TESTS_LIBMUGRID_TEST_FIELD_COLLECTIONS_HH_ diff --git a/tests/test_field_collections_1.cc b/tests/libmugrid/test_field_collections_1.cc similarity index 99% rename from tests/test_field_collections_1.cc rename to tests/libmugrid/test_field_collections_1.cc index cb3260c..9d4a7a3 100644 --- a/tests/test_field_collections_1.cc +++ b/tests/libmugrid/test_field_collections_1.cc @@ -1,222 +1,222 @@ /** * @file test_field_collections_1.cc * * @author Till Junge * * @date 20 Sep 2017 * * @brief Test the FieldCollection classes which provide fast optimized * iterators over run-time typed fields * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "test_field_collections.hh" -namespace muSpectre { +namespace muGrid { BOOST_AUTO_TEST_SUITE(field_collection_tests); BOOST_AUTO_TEST_CASE(simple) { constexpr Dim_t sdim = 2; using FC_t = GlobalFieldCollection; FC_t fc; BOOST_CHECK_EQUAL(FC_t::spatial_dim(), sdim); BOOST_CHECK_EQUAL(fc.get_spatial_dim(), sdim); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(Simple_construction_test, F, test_collections, F) { BOOST_CHECK_EQUAL(F::FC_t::spatial_dim(), F::sdim()); BOOST_CHECK_EQUAL(F::fc.get_spatial_dim(), F::sdim()); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(get_field2_test, F, test_collections, F) { const auto order{2}; using FC_t = typename F::FC_t; using TF_t = TensorField; auto && myfield = make_field("TensorField real 2", F::fc); using TensorMap = TensorFieldMap; using MatrixMap = MatrixFieldMap; using ArrayMap = ArrayFieldMap; TensorMap TFM(myfield); MatrixMap MFM(myfield); ArrayMap AFM(myfield); BOOST_CHECK_EQUAL(TFM.info_string(), "Tensor(d, " + std::to_string(order) + "_o, " + std::to_string(F::mdim()) + "_d)"); BOOST_CHECK_EQUAL(MFM.info_string(), "Matrix(d, " + std::to_string(F::mdim()) + "x" + std::to_string(F::mdim()) + ")"); BOOST_CHECK_EQUAL(AFM.info_string(), "Array(d, " + std::to_string(F::mdim()) + "x" + std::to_string(F::mdim()) + ")"); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(multi_field_test, F, mult_collections, F) { using FC_t = typename F::FC_t; // possible maptypes for Real tensor fields using T_type = Real; using T_TFM1_t = TensorFieldMap; using T_TFM2_t = TensorFieldMap; //! dangerous using T4_Map_t = T4MatrixFieldMap; // impossible maptypes for Real tensor fields using T_SFM_t = ScalarFieldMap; using T_MFM_t = MatrixFieldMap; using T_AFM_t = ArrayFieldMap; using T_MFMw1_t = MatrixFieldMap; using T_MFMw2_t = MatrixFieldMap; using T_MFMw3_t = MatrixFieldMap; const std::string T_name{"Tensorfield Real o4"}; const std::string T_name_w{"TensorField Real o4 wrongname"}; BOOST_CHECK_THROW(T_SFM_t(F::fc.at(T_name)), FieldInterpretationError); BOOST_CHECK_NO_THROW(T_TFM1_t(F::fc.at(T_name))); BOOST_CHECK_NO_THROW(T_TFM2_t(F::fc.at(T_name))); BOOST_CHECK_NO_THROW(T4_Map_t(F::fc.at(T_name))); BOOST_CHECK_THROW(T4_Map_t(F::fc.at(T_name_w)), std::out_of_range); BOOST_CHECK_THROW(T_MFM_t(F::fc.at(T_name)), FieldInterpretationError); BOOST_CHECK_THROW(T_AFM_t(F::fc.at(T_name)), FieldInterpretationError); BOOST_CHECK_THROW(T_MFMw1_t(F::fc.at(T_name)), FieldInterpretationError); BOOST_CHECK_THROW(T_MFMw2_t(F::fc.at(T_name)), FieldInterpretationError); BOOST_CHECK_THROW(T_MFMw2_t(F::fc.at(T_name)), FieldInterpretationError); BOOST_CHECK_THROW(T_MFMw3_t(F::fc.at(T_name)), FieldInterpretationError); BOOST_CHECK_THROW(T_SFM_t(F::fc.at(T_name_w)), std::out_of_range); // possible maptypes for integer scalar fields using S_type = Int; using S_SFM_t = ScalarFieldMap; using S_TFM1_t = TensorFieldMap; using S_TFM2_t = TensorFieldMap; using S_MFM_t = MatrixFieldMap; using S_AFM_t = ArrayFieldMap; using S4_Map_t = T4MatrixFieldMap; // impossible maptypes for integer scalar fields using S_MFMw1_t = MatrixFieldMap; using S_MFMw2_t = MatrixFieldMap; using S_MFMw3_t = MatrixFieldMap; const std::string S_name{"integer Scalar"}; const std::string S_name_w{"integer Scalar wrongname"}; BOOST_CHECK_NO_THROW(S_SFM_t(F::fc.at(S_name))); BOOST_CHECK_NO_THROW(S_TFM1_t(F::fc.at(S_name))); BOOST_CHECK_NO_THROW(S_TFM2_t(F::fc.at(S_name))); BOOST_CHECK_NO_THROW(S_MFM_t(F::fc.at(S_name))); BOOST_CHECK_NO_THROW(S_AFM_t(F::fc.at(S_name))); BOOST_CHECK_NO_THROW(S4_Map_t(F::fc.at(S_name))); BOOST_CHECK_THROW(S_MFMw1_t(F::fc.at(S_name)), FieldInterpretationError); BOOST_CHECK_THROW(T4_Map_t(F::fc.at(S_name)), FieldInterpretationError); BOOST_CHECK_THROW(S_MFMw2_t(F::fc.at(S_name)), FieldInterpretationError); BOOST_CHECK_THROW(S_MFMw2_t(F::fc.at(S_name)), FieldInterpretationError); BOOST_CHECK_THROW(S_MFMw3_t(F::fc.at(S_name)), FieldInterpretationError); BOOST_CHECK_THROW(S_SFM_t(F::fc.at(S_name_w)), std::out_of_range); // possible maptypes for complex matrix fields using M_type = Complex; using M_MFM_t = MatrixFieldMap; using M_AFM_t = ArrayFieldMap; // impossible maptypes for complex matrix fields using M_SFM_t = ScalarFieldMap; using M_MFMw1_t = MatrixFieldMap; using M_MFMw2_t = MatrixFieldMap; using M_MFMw3_t = MatrixFieldMap; const std::string M_name{"Matrixfield Complex sdim x mdim"}; const std::string M_name_w{"Matrixfield Complex sdim x mdim wrongname"}; BOOST_CHECK_THROW(M_SFM_t(F::fc.at(M_name)), FieldInterpretationError); BOOST_CHECK_NO_THROW(M_MFM_t(F::fc.at(M_name))); BOOST_CHECK_NO_THROW(M_AFM_t(F::fc.at(M_name))); BOOST_CHECK_THROW(M_MFMw1_t(F::fc.at(M_name)), FieldInterpretationError); BOOST_CHECK_THROW(M_MFMw2_t(F::fc.at(M_name)), FieldInterpretationError); BOOST_CHECK_THROW(M_MFMw2_t(F::fc.at(M_name)), FieldInterpretationError); BOOST_CHECK_THROW(M_MFMw3_t(F::fc.at(M_name)), FieldInterpretationError); BOOST_CHECK_THROW(M_SFM_t(F::fc.at(M_name_w)), std::out_of_range); } /* ---------------------------------------------------------------------- */ //! Check whether fields can be initialized using mult_collections_t = boost::mpl::list, FC_multi_fixture<2, 3, true>, FC_multi_fixture<3, 3, true>>; using mult_collections_f = boost::mpl::list, FC_multi_fixture<2, 3, false>, FC_multi_fixture<3, 3, false>>; BOOST_FIXTURE_TEST_CASE_TEMPLATE(init_test_glob, F, mult_collections_t, F) { Ccoord_t size; Ccoord_t loc{}; for (auto && s : size) { s = 3; } BOOST_CHECK_NO_THROW(F::fc.initialise(size, loc)); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(init_test_loca, F, mult_collections_f, F) { testGoodies::RandRange rng; for (int i = 0; i < 7; ++i) { Ccoord_t pixel; for (auto && s : pixel) { s = rng.randval(0, 7); } F::fc.add_pixel(pixel); } BOOST_CHECK_NO_THROW(F::fc.initialise()); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(init_test_loca_with_push_back, F, mult_collections_f, F) { constexpr auto mdim{F::mdim()}; constexpr int nb_pix{7}; testGoodies::RandRange rng{}; using ftype = internal::TypedSizedFieldBase; using stype = Eigen::Array; auto & field = static_cast(F::fc["Tensorfield Real o4"]); field.push_back(stype()); for (int i = 0; i < nb_pix; ++i) { Ccoord_t pixel; for (auto && s : pixel) { s = rng.randval(0, 7); } F::fc.add_pixel(pixel); } BOOST_CHECK_THROW(F::fc.initialise(), FieldCollectionError); for (int i = 0; i < nb_pix - 1; ++i) { field.push_back(stype()); } BOOST_CHECK_NO_THROW(F::fc.initialise()); } BOOST_AUTO_TEST_SUITE_END(); -} // namespace muSpectre +} // namespace muGrid diff --git a/tests/test_field_collections_2.cc b/tests/libmugrid/test_field_collections_2.cc similarity index 99% rename from tests/test_field_collections_2.cc rename to tests/libmugrid/test_field_collections_2.cc index a5645c8..47275d2 100644 --- a/tests/test_field_collections_2.cc +++ b/tests/libmugrid/test_field_collections_2.cc @@ -1,308 +1,308 @@ /** * @file test_field_collections_2.cc * * @author Till Junge * * @date 23 Nov 2017 * * @brief Continuation of tests from test_field_collection.cc, split for faster * compilation * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "test_field_collections.hh" -#include "common/field_map_dynamic.hh" +#include -namespace muSpectre { +namespace muGrid { BOOST_AUTO_TEST_SUITE(field_collection_tests); BOOST_FIXTURE_TEST_CASE_TEMPLATE(iter_field_test, F, iter_collections, F) { using FC_t = typename F::Parent::FC_t; using Tensor4Map = TensorFieldMap; Tensor4Map T4map{F::fc["Tensorfield Real o4"]}; TypedFieldMap dyn_map{F::fc["Tensorfield Real o4"]}; F::fc["Tensorfield Real o4"].set_zero(); for (auto && tens : T4map) { BOOST_CHECK_EQUAL(Real(Eigen::Tensor(tens.abs().sum().eval())()), 0); } for (auto && tens : T4map) { tens.setRandom(); } for (auto && tup : akantu::zip(T4map, dyn_map)) { auto & tens = std::get<0>(tup); auto & dyn = std::get<1>(tup); constexpr Dim_t nb_comp{ipow(F::mdim(), order)}; Eigen::Map> tens_arr(tens.data()); Real error{(dyn - tens_arr).matrix().norm()}; BOOST_CHECK_EQUAL(error, 0); } using Tensor2Map = TensorFieldMap; using MSqMap = MatrixFieldMap; using ASqMap = ArrayFieldMap; using A2Map = ArrayFieldMap; using WrongMap = ArrayFieldMap; Tensor2Map T2map{F::fc["Tensorfield Real o2"]}; MSqMap Mmap{F::fc["Tensorfield Real o2"]}; ASqMap Amap{F::fc["Tensorfield Real o2"]}; A2Map DynMap{F::fc["Dynamically sized Field"]}; auto & fc_ref{F::fc}; BOOST_CHECK_THROW(WrongMap{fc_ref["Dynamically sized Field"]}, FieldInterpretationError); auto t2_it = T2map.begin(); auto t2_it_end = T2map.end(); auto m_it = Mmap.begin(); auto a_it = Amap.begin(); for (; t2_it != t2_it_end; ++t2_it, ++m_it, ++a_it) { t2_it->setRandom(); auto && m = *m_it; bool comp = (m == a_it->matrix()); BOOST_CHECK(comp); } size_t counter{0}; for (auto val : DynMap) { ++counter; val += val.Ones() * counter; } counter = 0; for (auto val : DynMap) { ++counter; val -= val.Ones() * counter; auto error{val.matrix().norm()}; BOOST_CHECK_LT(error, tol); } using ScalarMap = ScalarFieldMap; ScalarMap s_map{F::fc["integer Scalar"]}; for (Uint i = 0; i < s_map.size(); ++i) { s_map[i] = i; } counter = 0; for (const auto & val : s_map) { BOOST_CHECK_EQUAL(counter++, val); } } BOOST_FIXTURE_TEST_CASE_TEMPLATE(ccoord_indexing_test, F, glob_iter_colls, F) { using FC_t = typename F::Parent::FC_t; using ScalarMap = ScalarFieldMap; ScalarMap s_map{F::fc["integer Scalar"]}; for (Uint i = 0; i < s_map.size(); ++i) { s_map[i] = i; } for (size_t i = 0; i < CcoordOps::get_size(F::fc.get_sizes()); ++i) { BOOST_CHECK_EQUAL( CcoordOps::get_index(F::fc.get_sizes(), F::fc.get_locations(), CcoordOps::get_ccoord(F::fc.get_sizes(), F::fc.get_locations(), i)), i); } } BOOST_FIXTURE_TEST_CASE_TEMPLATE(iterator_methods_test, F, iter_collections, F) { using FC_t = typename F::Parent::FC_t; using Tensor4Map = TensorFieldMap; Tensor4Map T4map{F::fc["Tensorfield Real o4"]}; using it_t = typename Tensor4Map::iterator; std::ptrdiff_t diff{ 3}; // arbitrary, as long as it is smaller than the container size // check constructors auto itstart = T4map.begin(); // standard way of obtaining iterator auto itend = T4map.end(); // ditto it_t it1{T4map}; it_t it2{T4map, false}; it_t it3{T4map, size_t(diff)}; BOOST_CHECK(itstart == itstart); BOOST_CHECK(itstart != itend); BOOST_CHECK_EQUAL(itstart, it1); BOOST_CHECK_EQUAL(itend, it2); // check ostream operator std::stringstream response; response << it3; BOOST_CHECK_EQUAL( response.str(), std::string("iterator on field 'Tensorfield Real o4', entry ") + std::to_string(diff)); // check move and assigment constructor (and operator+) it_t it_repl{T4map}; it_t itmove = std::move(T4map.begin()); it_t it4 = it1 + diff; it_t it7 = it4 - diff; BOOST_CHECK_EQUAL(itmove, it1); BOOST_CHECK_EQUAL(it4, it3); BOOST_CHECK_EQUAL(it7, it1); // check increments/decrements BOOST_CHECK_EQUAL(it1++, it_repl); // post-increment BOOST_CHECK_EQUAL(it1, it_repl + 1); BOOST_CHECK_EQUAL(--it1, it_repl); // pre -decrement BOOST_CHECK_EQUAL(++it1, it_repl + 1); // pre -increment BOOST_CHECK_EQUAL(it1--, it_repl + 1); // post-decrement BOOST_CHECK_EQUAL(it1, it_repl); // dereference and member-of-pointer check Eigen::Tensor Tens = *it1; Eigen::Tensor Tens2 = *itstart; Eigen::Tensor check = (Tens == Tens2).all(); BOOST_CHECK_EQUAL(static_cast(check()), true); BOOST_CHECK_NO_THROW(itstart->setZero()); // check access subscripting auto T3a = *it3; auto T3b = itstart[diff]; BOOST_CHECK( static_cast(Eigen::Tensor((T3a == T3b).all())())); // div. comparisons BOOST_CHECK_LT(itstart, itend); BOOST_CHECK(!(itend < itstart)); BOOST_CHECK(!(itstart < itstart)); BOOST_CHECK_LE(itstart, itend); BOOST_CHECK_LE(itstart, itstart); BOOST_CHECK(!(itend <= itstart)); BOOST_CHECK_GT(itend, itstart); BOOST_CHECK(!(itend > itend)); BOOST_CHECK(!(itstart > itend)); BOOST_CHECK_GE(itend, itstart); BOOST_CHECK_GE(itend, itend); BOOST_CHECK(!(itstart >= itend)); // check assignment increment/decrement BOOST_CHECK_EQUAL(it1 += diff, it3); BOOST_CHECK_EQUAL(it1 -= diff, itstart); // check cell coordinates using Ccoord = Ccoord_t; Ccoord a{itstart.get_ccoord()}; Ccoord b{0}; // Weirdly, boost::has_left_shift::value is false for // Ccoords, even though the operator is implemented :(, hence we can't write // BOOST_CHECK_EQUAL(a, b); // Workaround: bool check2 = (a == b); BOOST_CHECK(check2); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(const_tensor_iter_test, F, iter_collections, F) { using FC_t = typename F::Parent::FC_t; using Tensor4Map = TensorFieldMap; Tensor4Map T4map{F::fc["Tensorfield Real o4"]}; using T_t = typename Tensor4Map::T_t; Eigen::TensorMap Tens2(T4map[0].data(), F::Parent::sdim(), F::Parent::sdim(), F::Parent::sdim(), F::Parent::sdim()); for (auto it = T4map.cbegin(); it != T4map.cend(); ++it) { // maps to const tensors can't be initialised with a const pointer this // sucks auto && tens = *it; auto && ptr = tens.data(); static_assert( std::is_pointer>::value, "should be getting a pointer"); // static_assert(std::is_const>::value, // "should be const"); // If Tensor were written well, above static_assert should pass, and the // following check shouldn't. If it get triggered, it means that a newer // version of Eigen now does have const-correct // TensorMap. This means that const-correct field maps // are then also possible for tensors BOOST_CHECK(!std::is_const>::value); } } BOOST_FIXTURE_TEST_CASE_TEMPLATE(const_matrix_iter_test, F, iter_collections, F) { using FC_t = typename F::Parent::FC_t; using MatrixMap = MatrixFieldMap; MatrixMap Mmap{F::fc["Matrixfield Complex sdim x mdim"]}; for (auto it = Mmap.cbegin(); it != Mmap.cend(); ++it) { // maps to const tensors can't be initialised with a const pointer this // sucks auto && mat = *it; auto && ptr = mat.data(); static_assert( std::is_pointer>::value, "should be getting a pointer"); // static_assert(std::is_const>::value, // "should be const"); // If Matrix were written well, above static_assert should pass, and the // following check shouldn't. If it get triggered, it means that a newer // version of Eigen now does have const-correct // MatrixMap. This means that const-correct field maps // are then also possible for matrices BOOST_CHECK(!std::is_const>::value); } } BOOST_FIXTURE_TEST_CASE_TEMPLATE(const_scalar_iter_test, F, iter_collections, F) { using FC_t = typename F::Parent::FC_t; using ScalarMap = ScalarFieldMap; ScalarMap Smap{F::fc["integer Scalar"]}; for (auto it = Smap.cbegin(); it != Smap.cend(); ++it) { auto && scal = *it; static_assert( std::is_const>::value, "referred type should be const"); static_assert(std::is_lvalue_reference::value, "Should have returned an lvalue ref"); } } BOOST_AUTO_TEST_SUITE_END(); -} // namespace muSpectre +} // namespace muGrid diff --git a/tests/test_field_collections_3.cc b/tests/libmugrid/test_field_collections_3.cc similarity index 98% rename from tests/test_field_collections_3.cc rename to tests/libmugrid/test_field_collections_3.cc index 0fd7e5d..f25833e 100644 --- a/tests/test_field_collections_3.cc +++ b/tests/libmugrid/test_field_collections_3.cc @@ -1,163 +1,164 @@ /** * @file test_field_collections_3.cc * * @author Till Junge * * @date 19 Dec 2017 * * @brief Continuation of tests from test_field_collection_2.cc, split for * faster compilation * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "test_field_collections.hh" -#include "tests/test_goodies.hh" -#include "common/tensor_algebra.hh" +#include "test_goodies.hh" + +#include #include -namespace muSpectre { +namespace muGrid { BOOST_AUTO_TEST_SUITE(field_collection_tests); /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE_TEMPLATE(assignment_test, Fix, iter_collections, Fix) { auto t4map = Fix::t4_field.get_map(); auto t2map = Fix::t2_field.get_map(); auto scmap = Fix::sc_field.get_map(); auto m2map = Fix::m2_field.get_map(); const auto t4map_val{Matrices::Isymm()}; t4map = t4map_val; const auto t2map_val{Matrices::I2()}; t2map = t2map_val; const Int scmap_val{1}; scmap = scmap_val; Eigen::Matrix m2map_val; m2map_val.setRandom(); m2map = m2map_val; const size_t nb_pts{Fix::fc.size()}; testGoodies::RandRange rnd{}; BOOST_CHECK_EQUAL((t4map[rnd.randval(0, nb_pts - 1)] - t4map_val).norm(), 0.); BOOST_CHECK_EQUAL((t2map[rnd.randval(0, nb_pts - 1)] - t2map_val).norm(), 0.); BOOST_CHECK_EQUAL((scmap[rnd.randval(0, nb_pts - 1)] - scmap_val), 0.); BOOST_CHECK_EQUAL((m2map[rnd.randval(0, nb_pts - 1)] - m2map_val).norm(), 0.); } /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE_TEMPLATE(Eigentest, Fix, iter_collections, Fix) { auto t4eigen = Fix::t4_field.eigen(); auto t2eigen = Fix::t2_field.eigen(); BOOST_CHECK_EQUAL(t4eigen.rows(), ipow(Fix::mdim(), 4)); BOOST_CHECK_EQUAL(t4eigen.cols(), Fix::t4_field.size()); using T2_t = typename Eigen::Matrix; T2_t test_mat; test_mat.setRandom(); Eigen::Map> test_map( test_mat.data()); t2eigen.col(0) = test_map; BOOST_CHECK_EQUAL((Fix::t2_field.get_map()[0] - test_mat).norm(), 0.); } /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE_TEMPLATE(field_proxy_test, Fix, iter_collections, Fix) { Eigen::VectorXd t4values{Fix::t4_field.eigenvec()}; using FieldProxy_t = TypedField; //! create a field proxy FieldProxy_t proxy("proxy to 'Tensorfield Real o4'", Fix::fc, t4values, Fix::t4_field.get_nb_components()); Eigen::VectorXd wrong_size_not_multiple{ Eigen::VectorXd::Zero(t4values.size() + 1)}; BOOST_CHECK_THROW(FieldProxy_t("size not a multiple of nb_components", Fix::fc, wrong_size_not_multiple, Fix::t4_field.get_nb_components()), FieldError); Eigen::VectorXd wrong_size_but_multiple{Eigen::VectorXd::Zero( t4values.size() + Fix::t4_field.get_nb_components())}; BOOST_CHECK_THROW(FieldProxy_t("size wrong multiple of nb_components", Fix::fc, wrong_size_but_multiple, Fix::t4_field.get_nb_components()), FieldError); using Tensor4Map = T4MatrixFieldMap; Tensor4Map ref_map{Fix::t4_field}; Tensor4Map proxy_map{proxy}; for (auto tup : akantu::zip(ref_map, proxy_map)) { auto & ref = std::get<0>(tup); auto & prox = std::get<1>(tup); BOOST_CHECK_EQUAL((ref - prox).norm(), 0); } } /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE_TEMPLATE(field_proxy_of_existing_field, Fix, iter_collections, Fix) { Eigen::Ref t4values{Fix::t4_field.eigenvec()}; using FieldProxy_t = TypedField; //! create a field proxy FieldProxy_t proxy("proxy to 'Tensorfield Real o4'", Fix::fc, t4values, Fix::t4_field.get_nb_components()); using Tensor4Map = T4MatrixFieldMap; Tensor4Map ref_map{Fix::t4_field}; Tensor4Map proxy_map{proxy}; for (auto tup : akantu::zip(ref_map, proxy_map)) { auto & ref = std::get<0>(tup); auto & prox = std::get<1>(tup); prox += prox.Identity(); BOOST_CHECK_EQUAL((ref - prox).norm(), 0); } } /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE_TEMPLATE(typed_field_getter, Fix, mult_collections, Fix) { constexpr auto mdim{Fix::mdim()}; auto & fc{Fix::fc}; auto & field = fc.template get_typed_field("Tensorfield Real o4"); BOOST_CHECK_EQUAL(field.get_nb_components(), ipow(mdim, fourthOrder)); } BOOST_AUTO_TEST_SUITE_END(); -} // namespace muSpectre +} // namespace muGrid diff --git a/tests/test_goodies.hh b/tests/libmugrid/test_goodies.hh similarity index 97% rename from tests/test_goodies.hh rename to tests/libmugrid/test_goodies.hh index 9637e40..c92a0aa 100644 --- a/tests/test_goodies.hh +++ b/tests/libmugrid/test_goodies.hh @@ -1,228 +1,228 @@ /** * @file test_goodies.hh * * @author Till Junge * * @date 27 Sep 2017 * * @brief helpers for testing * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#ifndef TESTS_TEST_GOODIES_HH_ -#define TESTS_TEST_GOODIES_HH_ - -#include "common/tensor_algebra.hh" +#ifndef TESTS_LIBMUGRID_TEST_GOODIES_HH_ +#define TESTS_LIBMUGRID_TEST_GOODIES_HH_ +#include +#include #include #include #include -namespace muSpectre { +namespace muGrid { namespace testGoodies { template struct dimFixture { constexpr static Dim_t dim{Dim}; }; using dimlist = boost::mpl::list, dimFixture, dimFixture>; /* ---------------------------------------------------------------------- */ template class RandRange { public: RandRange() : rd(), gen(rd()) {} template std::enable_if_t::value, dummyT> randval(T && lower, T && upper) { static_assert(std::is_same::value, "SFINAE"); auto distro = std::uniform_real_distribution(lower, upper); return distro(this->gen); } template std::enable_if_t::value, dummyT> randval(T && lower, T && upper) { static_assert(std::is_same::value, "SFINAE"); auto distro = std::uniform_int_distribution(lower, upper); return distro(this->gen); } private: std::random_device rd; std::default_random_engine gen; }; /** * explicit computation of linearisation of PK1 stress for an * objective Hooke's law. This implementation is not meant to be * efficient, but te reflect exactly the formulation in Curnier * 2000, "Méthodes numériques en mécanique des solides" for * reference and testing */ template decltype(auto) objective_hooke_explicit(Real lambda, Real mu, const Matrices::Tens2_t & F) { using Matrices::Tens2_t; using Matrices::Tens4_t; using Matrices::tensmult; using T2 = Tens2_t; using T4 = Tens4_t; T2 P; T2 I = P.Identity(); T4 K; // See Curnier, 2000, "Méthodes numériques en mécanique des // solides", p 252, (6.95b) Real Fjrjr = (F.array() * F.array()).sum(); T2 Fjrjm = F.transpose() * F; P.setZero(); for (Dim_t i = 0; i < Dim; ++i) { for (Dim_t m = 0; m < Dim; ++m) { P(i, m) += lambda / 2 * (Fjrjr - Dim) * F(i, m); for (Dim_t r = 0; r < Dim; ++r) { P(i, m) += mu * F(i, r) * (Fjrjm(r, m) - I(r, m)); } } } // See Curnier, 2000, "Méthodes numériques en mécanique des solides", p // 252 Real Fkrkr = (F.array() * F.array()).sum(); T2 Fkmkn = F.transpose() * F; T2 Fisjs = F * F.transpose(); K.setZero(); for (Dim_t i = 0; i < Dim; ++i) { for (Dim_t j = 0; j < Dim; ++j) { for (Dim_t m = 0; m < Dim; ++m) { for (Dim_t n = 0; n < Dim; ++n) { get(K, i, m, j, n) = (lambda * ((Fkrkr - Dim) / 2 * I(i, j) * I(m, n) + F(i, m) * F(j, n)) + mu * (I(i, j) * Fkmkn(m, n) + Fisjs(i, j) * I(m, n) - I(i, j) * I(m, n) + F(i, n) * F(j, m))); } } } } return std::make_tuple(P, K); } /** * takes a 4th-rank tensor and returns a copy with the last two * dimensions switched. This is particularly useful to check for * identity between a stiffness tensors computed the regular way * and the Geers way. For testing, not efficient. */ template inline auto right_transpose(const Eigen::MatrixBase & t4) -> Eigen::Matrix { constexpr Dim_t Rows{Derived::RowsAtCompileTime}; constexpr Dim_t Cols{Derived::ColsAtCompileTime}; constexpr Dim_t DimSq{Rows}; using T = typename Derived::Scalar; static_assert(Rows == Cols, "only square problems"); constexpr Dim_t Dim{ct_sqrt(DimSq)}; static_assert((Dim == twoD) or (Dim == threeD), "only two- and three-dimensional problems"); static_assert(ipow(Dim, 2) == DimSq, "The array is not a valid fourth order tensor"); T4Mat retval{T4Mat::Zero()}; /** * Note: this looks like it's doing a left transpose, but in * reality, np is rowmajor in all directions, so from numpy to * eigen, we need to transpose left, center, and * right. Therefore, if we want to right-transpose, then we need * to transpose once left, once center, and *twice* right, which * is equal to just left and center transpose. Center-transpose * happens automatically when eigen parses the input (which is * naturally written in rowmajor but interpreted into colmajor), * so all that's left to do is (ironically) the subsequent * left-transpose */ for (int i{0}; i < Dim; ++i) { for (int j{0}; j < Dim; ++j) { for (int k{0}; k < Dim; ++k) { for (int l{0}; l < Dim; ++l) { get(retval, i, j, k, l) = get(t4, j, i, k, l); } } } } return retval; } /** * recomputes a colmajor representation of a fourth-rank rowmajor * tensor. this is useful when comparing to reference results * computed in numpy */ template inline auto from_numpy(const Eigen::MatrixBase & t4_np) -> Eigen::Matrix { constexpr Dim_t Rows{Derived::RowsAtCompileTime}; constexpr Dim_t Cols{Derived::ColsAtCompileTime}; constexpr Dim_t DimSq{Rows}; using T = typename Derived::Scalar; static_assert(Rows == Cols, "only square problems"); constexpr Dim_t Dim{ct_sqrt(DimSq)}; static_assert((Dim == twoD) or (Dim == threeD), "only two- and three-dimensional problems"); static_assert(ipow(Dim, 2) == DimSq, "The array is not a valid fourth order tensor"); T4Mat retval{T4Mat::Zero()}; T4Mat intermediate{T4Mat::Zero()}; // transpose rows for (int row{0}; row < DimSq; ++row) { for (int i{0}; i < Dim; ++i) { for (int j{0}; j < Dim; ++j) { intermediate(row, i + Dim * j) = t4_np(row, i * Dim + j); } } } // transpose columns for (int col{0}; col < DimSq; ++col) { for (int i{0}; i < Dim; ++i) { for (int j{0}; j < Dim; ++j) { retval(i + Dim * j, col) = intermediate(i * Dim + j, col); } } } return retval; } } // namespace testGoodies -} // namespace muSpectre +} // namespace muGrid -#endif // TESTS_TEST_GOODIES_HH_ +#endif // TESTS_LIBMUGRID_TEST_GOODIES_HH_ diff --git a/tests/tests.hh b/tests/libmugrid/tests.hh similarity index 88% copy from tests/tests.hh copy to tests/libmugrid/tests.hh index 4cb70de..105561d 100644 --- a/tests/tests.hh +++ b/tests/libmugrid/tests.hh @@ -1,49 +1,49 @@ /** * @file tests.hh * * @author Till Junge * * @date 10 May 2017 * * @brief common defs for tests * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ +#include -#include "common/common.hh" #include #include -#ifndef TESTS_TESTS_HH_ -#define TESTS_TESTS_HH_ +#ifndef TESTS_LIBMUGRID_TESTS_HH_ +#define TESTS_LIBMUGRID_TESTS_HH_ -namespace muSpectre { +namespace muGrid { constexpr Real tol = 1e-14 * 100; // it's in percent constexpr Real finite_diff_tol = 1e-7; // it's in percent -} // namespace muSpectre +} // namespace muGrid -#endif // TESTS_TESTS_HH_ +#endif // TESTS_LIBMUGRID_TESTS_HH_ diff --git a/tests/mpi_context.hh b/tests/mpi_context.hh index 88536d6..dc22d6b 100644 --- a/tests/mpi_context.hh +++ b/tests/mpi_context.hh @@ -1,71 +1,71 @@ /** * @file mpi_initializer.cc * * @author Lars Pastewka * * @date 07 Mar 2018 * * @brief Singleton for initialization and tear down of MPI. * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #ifndef TESTS_MPI_CONTEXT_HH_ #define TESTS_MPI_CONTEXT_HH_ -#include "common/communicator.hh" +#include -namespace muSpectre { +namespace muFFT { /*! * MPI context singleton. Initialize MPI once when needed. */ class MPIContext { public: Communicator comm; static MPIContext & get_context() { static MPIContext context; return context; } private: MPIContext() : comm(Communicator(MPI_COMM_WORLD)) { MPI_Init(&boost::unit_test::framework::master_test_suite().argc, &boost::unit_test::framework::master_test_suite().argv); } ~MPIContext() { // Wait for all processes to finish before calling finalize. MPI_Barrier(comm.get_mpi_comm()); MPI_Finalize(); } public: MPIContext(MPIContext const &) = delete; void operator=(MPIContext const &) = delete; }; -} // namespace muSpectre +} // namespace muFFT #endif // TESTS_MPI_CONTEXT_HH_ diff --git a/tests/mpi_test_projection.hh b/tests/mpi_test_projection.hh index f2cb487..f1746d9 100644 --- a/tests/mpi_test_projection.hh +++ b/tests/mpi_test_projection.hh @@ -1,107 +1,107 @@ /** * @file test_projection.hh * * @author Till Junge * * @date 16 Jan 2018 * * @brief common declarations for testing both the small and finite strain * projection operators * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "tests.hh" #include "mpi_context.hh" #include #include #ifndef TESTS_MPI_TEST_PROJECTION_HH_ #define TESTS_MPI_TEST_PROJECTION_HH_ -namespace muSpectre { +namespace muFFT { /* ---------------------------------------------------------------------- */ template struct Sizes {}; template <> struct Sizes { constexpr static Ccoord_t get_resolution() { return Ccoord_t{3, 5}; } constexpr static Rcoord_t get_lengths() { return Rcoord_t{3.4, 5.8}; } }; template <> struct Sizes { constexpr static Ccoord_t get_resolution() { return Ccoord_t{3, 5, 7}; } constexpr static Rcoord_t get_lengths() { return Rcoord_t{3.4, 5.8, 6.7}; } }; template struct Squares {}; template <> struct Squares { constexpr static Ccoord_t get_resolution() { return Ccoord_t{5, 5}; } constexpr static Rcoord_t get_lengths() { return Rcoord_t{5, 5}; } }; template <> struct Squares { constexpr static Ccoord_t get_resolution() { return Ccoord_t{7, 7, 7}; } constexpr static Rcoord_t get_lengths() { return Rcoord_t{7, 7, 7}; } }; /* ---------------------------------------------------------------------- */ template struct ProjectionFixture { using Parent = Proj; constexpr static Dim_t sdim{DimS}; constexpr static Dim_t mdim{DimM}; constexpr static bool is_parallel{parallel}; ProjectionFixture() : projector(std::make_unique(SizeGiver::get_resolution(), - ipow(mdim, 2), + muGrid::ipow(mdim, 2), MPIContext::get_context().comm), SizeGiver::get_lengths()) {} Parent projector; }; -} // namespace muSpectre +} // namespace muFFT #endif // TESTS_MPI_TEST_PROJECTION_HH_ diff --git a/tests/mpi_test_projection_finite.cc b/tests/mpi_test_projection_finite.cc index 6af4162..ad5614c 100644 --- a/tests/mpi_test_projection_finite.cc +++ b/tests/mpi_test_projection_finite.cc @@ -1,194 +1,199 @@ /** * @file test_projection_finite.cc * * @author Till Junge * * @date 07 Dec 2017 * * @brief tests for standard finite strain projection operator * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #define BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS #define BOOST_MPL_LIMIT_LIST_SIZE 50 -#include "fft/projection_finite_strain.hh" -#include "fft/projection_finite_strain_fast.hh" -#include "fft/fft_utils.hh" +#include "projection/projection_finite_strain.hh" +#include "projection/projection_finite_strain_fast.hh" #include "mpi_test_projection.hh" -#include "fft/fftw_engine.hh" +#include +#include #ifdef WITH_FFTWMPI -#include "fft/fftwmpi_engine.hh" +#include #endif #ifdef WITH_PFFT -#include "fft/pfft_engine.hh" +#include #endif #include -namespace muSpectre { +namespace muFFT { + using muSpectre::ProjectionFiniteStrain; + using muSpectre::ProjectionFiniteStrainFast; + using muSpectre::tol; BOOST_AUTO_TEST_SUITE(mpi_projection_finite_strain); /* ---------------------------------------------------------------------- */ using fixlist = boost::mpl::list< #ifdef WITH_FFTWMPI ProjectionFixture, ProjectionFiniteStrain, FFTWMPIEngine>, ProjectionFixture, ProjectionFiniteStrain, FFTWMPIEngine>, ProjectionFixture, ProjectionFiniteStrain, FFTWMPIEngine>, ProjectionFixture, ProjectionFiniteStrain, FFTWMPIEngine>, ProjectionFixture, ProjectionFiniteStrainFast, FFTWMPIEngine>, ProjectionFixture, ProjectionFiniteStrainFast, FFTWMPIEngine>, ProjectionFixture, ProjectionFiniteStrainFast, FFTWMPIEngine>, ProjectionFixture, ProjectionFiniteStrainFast, FFTWMPIEngine>, #endif #ifdef WITH_PFFT ProjectionFixture, ProjectionFiniteStrain, PFFTEngine>, ProjectionFixture, ProjectionFiniteStrain, PFFTEngine>, ProjectionFixture, ProjectionFiniteStrain, PFFTEngine>, ProjectionFixture, ProjectionFiniteStrain, PFFTEngine>, ProjectionFixture, ProjectionFiniteStrainFast, PFFTEngine>, ProjectionFixture, ProjectionFiniteStrainFast, PFFTEngine>, ProjectionFixture, ProjectionFiniteStrainFast, PFFTEngine>, ProjectionFixture, ProjectionFiniteStrainFast, PFFTEngine>, #endif ProjectionFixture, ProjectionFiniteStrain, FFTWEngine, false>>; /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE_TEMPLATE(constructor_test, fix, fixlist, fix) { if (fix::is_parallel || fix::projector.get_communicator().size() == 1) { BOOST_CHECK_NO_THROW(fix::projector.initialise(FFT_PlanFlags::estimate)); } } /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE_TEMPLATE(Gradient_preservation_test, fix, fixlist, fix) { if (!fix::is_parallel || fix::projector.get_communicator().size() > 1) { return; } // create a gradient field with a zero mean gradient and verify // that the projection preserves it constexpr Dim_t dim{fix::sdim}, sdim{fix::sdim}, mdim{fix::mdim}; static_assert( dim == fix::mdim, "These tests assume that the material and spatial dimension are " "identical"); - using Fields = GlobalFieldCollection; - using FieldT = TensorField; - using FieldMap = MatrixFieldMap; + using Fields = muGrid::GlobalFieldCollection; + using FieldT = muGrid::TensorField; + using FieldMap = muGrid::MatrixFieldMap; using Vector = Eigen::Matrix; Fields fields{}; - FieldT & f_grad{make_field("gradient", fields)}; - FieldT & f_var{make_field("working field", fields)}; + FieldT & f_grad{muGrid::make_field("gradient", fields)}; + FieldT & f_var{muGrid::make_field("working field", fields)}; FieldMap grad(f_grad); FieldMap var(f_var); fields.initialise(fix::projector.get_subdomain_resolutions(), fix::projector.get_subdomain_locations()); Vector k; for (Dim_t i = 0; i < dim; ++i) { // the wave vector has to be such that it leads to an integer // number of periods in each length of the domain - k(i) = (i + 1) * 2 * pi / fix::projector.get_domain_lengths()[i]; + k(i) = (i + 1) * 2 * muGrid::pi / fix::projector.get_domain_lengths()[i]; } + using muGrid::operator/; for (auto && tup : akantu::zip(fields, grad, var)) { auto & ccoord = std::get<0>(tup); auto & g = std::get<1>(tup); auto & v = std::get<2>(tup); - Vector vec = CcoordOps::get_vector( + Vector vec = muGrid::CcoordOps::get_vector( ccoord, fix::projector.get_domain_lengths() / fix::projector.get_domain_resolutions()); g.row(0) = k.transpose() * cos(k.dot(vec)); v.row(0) = g.row(0); } fix::projector.initialise(FFT_PlanFlags::estimate); fix::projector.apply_projection(f_var); + using muGrid::operator<<; for (auto && tup : akantu::zip(fields, grad, var)) { auto & ccoord = std::get<0>(tup); auto & g = std::get<1>(tup); auto & v = std::get<2>(tup); Real error = (g - v).norm(); BOOST_CHECK_LT(error, tol); if (error >= tol) { - Vector vec = CcoordOps::get_vector( + Vector vec = muGrid::CcoordOps::get_vector( ccoord, fix::projector.get_domain_lengths() / fix::projector.get_domain_resolutions()); std::cout << std::endl << "grad_ref :" << std::endl << g << std::endl; std::cout << std::endl << "grad_proj :" << std::endl << v << std::endl; std::cout << std::endl << "ccoord :" << std::endl << ccoord << std::endl; std::cout << std::endl << "vector :" << std::endl << vec.transpose() << std::endl; } } } BOOST_AUTO_TEST_SUITE_END(); -} // namespace muSpectre +} // namespace muFFT diff --git a/tests/mpi_test_projection_small.cc b/tests/mpi_test_projection_small.cc index 5b7644b..b80d10e 100644 --- a/tests/mpi_test_projection_small.cc +++ b/tests/mpi_test_projection_small.cc @@ -1,176 +1,180 @@ /** * @file test_projection_small.cc * * @author Till Junge * * @date 16 Jan 2018 * * @brief tests for standard small strain projection operator * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #define BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS #define BOOST_MPL_LIMIT_LIST_SIZE 50 -#include "fft/projection_small_strain.hh" +#include "projection/projection_small_strain.hh" #include "mpi_test_projection.hh" -#include "fft/fft_utils.hh" -#include "fft/fftw_engine.hh" +#include +#include #ifdef WITH_FFTWMPI -#include "fft/fftwmpi_engine.hh" +#include #endif #ifdef WITH_PFFT -#include "fft/pfft_engine.hh" +#include #endif #include -namespace muSpectre { +namespace muFFT { + using muSpectre::ProjectionSmallStrain; + using muSpectre::tol; + using muGrid::operator/; + using muGrid::operator<<; BOOST_AUTO_TEST_SUITE(mpi_projection_small_strain); using fixlist = boost::mpl::list< #ifdef WITH_FFTWMPI ProjectionFixture, ProjectionSmallStrain, FFTWMPIEngine>, ProjectionFixture, ProjectionSmallStrain, FFTWMPIEngine>, ProjectionFixture, ProjectionSmallStrain, FFTWMPIEngine>, ProjectionFixture, ProjectionSmallStrain, FFTWMPIEngine>, #endif #ifdef WITH_PFFT ProjectionFixture, ProjectionSmallStrain, PFFTEngine>, ProjectionFixture, ProjectionSmallStrain, PFFTEngine>, ProjectionFixture, ProjectionSmallStrain, PFFTEngine>, ProjectionFixture, ProjectionSmallStrain, PFFTEngine>, #endif ProjectionFixture, ProjectionSmallStrain, FFTWEngine, false>>; /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE_TEMPLATE(constructor_test, fix, fixlist, fix) { if (fix::is_parallel || fix::projector.get_communicator().size() == 1) { BOOST_CHECK_NO_THROW(fix::projector.initialise(FFT_PlanFlags::estimate)); } } /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE_TEMPLATE(Gradient_preservation_test, fix, fixlist, fix) { if (!fix::is_parallel || fix::projector.get_communicator().size() > 1) { return; } // create a gradient field with a zero mean gradient and verify // that the projection preserves it constexpr Dim_t dim{fix::sdim}, sdim{fix::sdim}, mdim{fix::mdim}; static_assert( dim == fix::mdim, "These tests assume that the material and spatial dimension are " "identical"); - using Fields = GlobalFieldCollection; - using FieldT = TensorField; - using FieldMap = MatrixFieldMap; + using Fields = muGrid::GlobalFieldCollection; + using FieldT = muGrid::TensorField; + using FieldMap = muGrid::MatrixFieldMap; using Vector = Eigen::Matrix; Fields fields{}; - FieldT & f_grad{make_field("strain", fields)}; - FieldT & f_var{make_field("working field", fields)}; + FieldT & f_grad{muGrid::make_field("strain", fields)}; + FieldT & f_var{muGrid::make_field("working field", fields)}; FieldMap grad(f_grad); FieldMap var(f_var); fields.initialise(fix::projector.get_subdomain_resolutions(), fix::projector.get_subdomain_locations()); Vector k; for (Dim_t i = 0; i < dim; ++i) { // the wave vector has to be such that it leads to an integer // number of periods in each length of the domain - k(i) = (i + 1) * 2 * pi / fix::projector.get_domain_lengths()[i]; + k(i) = (i + 1) * 2 * muGrid::pi / fix::projector.get_domain_lengths()[i]; } for (auto && tup : akantu::zip(fields, grad, var)) { auto & ccoord = std::get<0>(tup); auto & g = std::get<1>(tup); auto & v = std::get<2>(tup); - Vector vec = CcoordOps::get_vector( + Vector vec = muGrid::CcoordOps::get_vector( ccoord, fix::projector.get_domain_lengths() / fix::projector.get_domain_resolutions()); g.row(0) << k.transpose() * cos(k.dot(vec)); // We need to add I to the term, because this field has a net // zero gradient, which leads to a net -I strain g = 0.5 * ((g - g.Identity()).transpose() + (g - g.Identity())).eval() + g.Identity(); v = g; } fix::projector.initialise(FFT_PlanFlags::estimate); fix::projector.apply_projection(f_var); constexpr bool verbose{false}; for (auto && tup : akantu::zip(fields, grad, var)) { auto & ccoord = std::get<0>(tup); auto & g = std::get<1>(tup); auto & v = std::get<2>(tup); - Vector vec = CcoordOps::get_vector( + Vector vec = muGrid::CcoordOps::get_vector( ccoord, fix::projector.get_domain_lengths() / fix::projector.get_domain_resolutions()); Real error = (g - v).norm(); BOOST_CHECK_LT(error, tol); if ((error >= tol) || verbose) { std::cout << std::endl << "grad_ref :" << std::endl << g << std::endl; std::cout << std::endl << "grad_proj :" << std::endl << v << std::endl; std::cout << std::endl << "ccoord :" << std::endl << ccoord << std::endl; std::cout << std::endl << "vector :" << std::endl << vec.transpose() << std::endl; std::cout << "means:" << std::endl << ":" << std::endl << grad.mean() << std::endl << ":" << std::endl << var.mean(); } } } BOOST_AUTO_TEST_SUITE_END(); -} // namespace muSpectre +} // namespace muFFT diff --git a/tests/mpi_test_solver_newton_cg.cc b/tests/mpi_test_solver_newton_cg.cc index 9d40cff..beae644 100644 --- a/tests/mpi_test_solver_newton_cg.cc +++ b/tests/mpi_test_solver_newton_cg.cc @@ -1,224 +1,225 @@ /** * @file test_solver_newton_cg.cc * * @author Till Junge * * @date 20 Dec 2017 * * @brief Tests for the standard Newton-Raphson + Conjugate Gradient solver * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "tests.hh" #include "mpi_context.hh" #include "solver/deprecated_solvers.hh" #include "solver/deprecated_solver_cg.hh" #include "solver/deprecated_solver_cg_eigen.hh" -#include "fft/fftwmpi_engine.hh" -#include "fft/projection_finite_strain_fast.hh" +#include "projection/projection_finite_strain_fast.hh" #include "materials/material_linear_elastic1.hh" -#include "common/iterators.hh" -#include "common/ccoord_operations.hh" #include "cell/cell_factory.hh" +#include +#include +#include + namespace muSpectre { BOOST_AUTO_TEST_SUITE(newton_cg_tests); BOOST_AUTO_TEST_CASE(manual_construction_test) { - const Communicator & comm = MPIContext::get_context().comm; + const auto & comm = muFFT::MPIContext::get_context().comm; // constexpr Dim_t dim{twoD}; constexpr Dim_t dim{threeD}; // constexpr Ccoord_t resolutions{3, 3}; // constexpr Rcoord_t lengths{2.3, 2.7}; constexpr Ccoord_t resolutions{5, 5, 5}; constexpr Rcoord_t lengths{5, 5, 5}; - auto fft_ptr{ - std::make_unique>(resolutions, dim * dim, comm)}; + auto fft_ptr{std::make_unique>(resolutions, + dim * dim, comm)}; auto proj_ptr{std::make_unique>( std::move(fft_ptr), lengths)}; CellBase sys(std::move(proj_ptr)); using Mat_t = MaterialLinearElastic1; // const Real Young{210e9}, Poisson{.33}; const Real Young{1.0030648180242636}, Poisson{0.29930675909878679}; // const Real lambda{Young*Poisson/((1+Poisson)*(1-2*Poisson))}; // const Real mu{Young/(2*(1+Poisson))}; auto & Material_hard = Mat_t::make(sys, "hard", 10 * Young, Poisson); auto & Material_soft = Mat_t::make(sys, "soft", Young, Poisson); auto & loc = sys.get_subdomain_locations(); for (auto && tup : akantu::enumerate(sys)) { auto && pixel = std::get<1>(tup); if (loc == Ccoord_t{0, 0} && std::get<0>(tup) == 0) { Material_hard.add_pixel(pixel); } else { Material_soft.add_pixel(pixel); } } sys.initialise(); Grad_t delF0; delF0 << 0, 1., 0, 0, 0, 0, 0, 0, 0; constexpr Real cg_tol{1e-8}, newton_tol{1e-5}; - constexpr Uint maxiter{CcoordOps::get_size(resolutions) * - ipow(dim, secondOrder) * 10}; + constexpr Uint maxiter{muGrid::CcoordOps::get_size(resolutions) * + muGrid::ipow(dim, secondOrder) * 10}; constexpr bool verbose{false}; GradIncrements grads; grads.push_back(delF0); DeprecatedSolverCG cg{sys, cg_tol, maxiter, static_cast(verbose)}; Eigen::ArrayXXd res1{ deprecated_de_geus(sys, grads, cg, newton_tol, verbose)[0].grad}; DeprecatedSolverCG cg2{sys, cg_tol, maxiter, static_cast(verbose)}; Eigen::ArrayXXd res2{ deprecated_newton_cg(sys, grads, cg2, newton_tol, verbose)[0].grad}; BOOST_CHECK_LE(abs(res1 - res2).mean(), cg_tol); } BOOST_AUTO_TEST_CASE(small_strain_patch_test) { - const Communicator & comm = MPIContext::get_context().comm; + const auto & comm = muFFT::MPIContext::get_context().comm; constexpr Dim_t dim{twoD}; using Ccoord = Ccoord_t; using Rcoord = Rcoord_t; - constexpr Ccoord resolutions{CcoordOps::get_cube(3)}; - constexpr Rcoord lengths{CcoordOps::get_cube(1.)}; + constexpr Ccoord resolutions{muGrid::CcoordOps::get_cube(3)}; + constexpr Rcoord lengths{muGrid::CcoordOps::get_cube(1.)}; constexpr Formulation form{Formulation::small_strain}; // number of layers in the hard material constexpr Uint nb_lays{1}; constexpr Real contrast{2}; static_assert(nb_lays < resolutions[0], "the number or layers in the hard material must be smaller " "than the total number of layers in dimension 0"); auto sys{make_parallel_cell(resolutions, lengths, form, comm)}; using Mat_t = MaterialLinearElastic1; constexpr Real Young{2.}, Poisson{.33}; auto material_hard{ std::make_unique("hard", contrast * Young, Poisson)}; auto material_soft{std::make_unique("soft", Young, Poisson)}; for (const auto & pixel : sys) { if (pixel[0] < Dim_t(nb_lays)) { material_hard->add_pixel(pixel); } else { material_soft->add_pixel(pixel); } } sys.add_material(std::move(material_hard)); sys.add_material(std::move(material_soft)); sys.initialise(); Grad_t delEps0{Grad_t::Zero()}; constexpr Real eps0 = 1.; // delEps0(0, 1) = delEps0(1, 0) = eps0; delEps0(0, 0) = eps0; constexpr Real cg_tol{1e-8}, newton_tol{1e-5}, equil_tol{1e-10}; constexpr Uint maxiter{dim * 10}; constexpr Dim_t verbose{0}; DeprecatedSolverCGEigen cg{sys, cg_tol, maxiter, static_cast(verbose)}; auto result = deprecated_de_geus(sys, delEps0, cg, newton_tol, equil_tol, verbose); if (verbose) { std::cout << "result:" << std::endl << result.grad << std::endl; std::cout << "mean strain = " << std::endl << sys.get_strain().get_map().mean() << std::endl; } /** * verification of resultant strains: subscript ₕ for hard and ₛ * for soft, Nₕ is nb_lays and Nₜₒₜ is resolutions, k is contrast * * Δl = εl = Δlₕ + Δlₛ = εₕlₕ+εₛlₛ * => ε = εₕ Nₕ/Nₜₒₜ + εₛ (Nₜₒₜ-Nₕ)/Nₜₒₜ * * σ is constant across all layers * σₕ = σₛ * => Eₕ εₕ = Eₛ εₛ * => εₕ = 1/k εₛ * => ε / (1/k Nₕ/Nₜₒₜ + (Nₜₒₜ-Nₕ)/Nₜₒₜ) = εₛ */ constexpr Real factor{1 / contrast * Real(nb_lays) / resolutions[0] + 1. - nb_lays / Real(resolutions[0])}; constexpr Real eps_soft{eps0 / factor}; constexpr Real eps_hard{eps_soft / contrast}; if (verbose) { std::cout << "εₕ = " << eps_hard << ", εₛ = " << eps_soft << std::endl; std::cout << "ε = εₕ Nₕ/Nₜₒₜ + εₛ (Nₜₒₜ-Nₕ)/Nₜₒₜ" << std::endl; } Grad_t Eps_hard; Eps_hard << eps_hard, 0, 0, 0; Grad_t Eps_soft; Eps_soft << eps_soft, 0, 0, 0; // verify uniaxial tension patch test for (const auto & pixel : sys) { if (pixel[0] < Dim_t(nb_lays)) { BOOST_CHECK_LE((Eps_hard - sys.get_strain().get_map()[pixel]).norm(), tol); } else { BOOST_CHECK_LE((Eps_soft - sys.get_strain().get_map()[pixel]).norm(), tol); } } delEps0 = Grad_t::Zero(); delEps0(0, 1) = delEps0(1, 0) = eps0; DeprecatedSolverCG cg2{sys, cg_tol, maxiter, static_cast(verbose)}; result = deprecated_newton_cg(sys, delEps0, cg2, newton_tol, equil_tol, verbose); Eps_hard << 0, eps_hard, eps_hard, 0; Eps_soft << 0, eps_soft, eps_soft, 0; // verify pure shear patch test for (const auto & pixel : sys) { if (pixel[0] < Dim_t(nb_lays)) { BOOST_CHECK_LE((Eps_hard - sys.get_strain().get_map()[pixel]).norm(), tol); } else { BOOST_CHECK_LE((Eps_soft - sys.get_strain().get_map()[pixel]).norm(), tol); } } } BOOST_AUTO_TEST_SUITE_END(); } // namespace muSpectre diff --git a/tests/python_binding_tests.py b/tests/python_binding_tests.py index b7f5653..4936b0c 100755 --- a/tests/python_binding_tests.py +++ b/tests/python_binding_tests.py @@ -1,219 +1,217 @@ #!/usr/bin/env python3 """ file python_binding_tests.py @author Till Junge @date 09 Jan 2018 @brief Unit tests for python bindings @section LICENCE Copyright © 2018 Till Junge µSpectre is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3, or (at your option) any later version. µSpectre is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with µSpectre; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with proprietary FFT implementations or numerical libraries, containing parts covered by the terms of those libraries' licenses, the licensors of this Program grant you additional permission to convey the resulting work. """ import unittest import numpy as np from python_test_imports import µ -from python_fft_tests import FFT_Check -from python_projection_tests import * from python_material_linear_elastic3_test import MaterialLinearElastic3_Check from python_material_linear_elastic4_test import MaterialLinearElastic4_Check from python_material_linear_elastic_generic1_test import MaterialLinearElasticGeneric1_Check from python_material_linear_elastic_generic2_test import MaterialLinearElasticGeneric2_Check from python_comparison_test_material_linear_elastic1 import MatTest as MatTest1 from python_field_tests import FieldCollection_Check from python_exact_reference_elastic_test import LinearElastic_Check from python_field_tests import FieldCollection_Check from python_muSpectre_gradient_integration_test import \ MuSpectre_gradient_integration_Check from python_material_evaluator_test import MaterialEvaluator_Check class CellCheck(unittest.TestCase): def test_Construction(self): """ Simple check for cell constructors """ resolution = [5,7] lengths = [5.2, 8.3] formulation = µ.Formulation.small_strain try: sys = µ.Cell(resolution, lengths, formulation) mat = µ.material.MaterialLinearElastic1_2d.make(sys, "material", 210e9, .33) except Exception as err: print(err) raise err class MaterialLinearElastic1_2dCheck(unittest.TestCase): def setUp(self): self.resolution = [5,7] self.lengths = [5.2, 8.3] self.formulation = µ.Formulation.small_strain self.sys = µ.Cell(self.resolution, self.lengths, self.formulation) self.mat = µ.material.MaterialLinearElastic1_2d.make( self.sys, "material", 210e9, .33) def test_add_material(self): self.mat.add_pixel([2,1]) class SolverCheck(unittest.TestCase): def setUp(self): self.resolution = [3, 3]#[5,7] self.lengths = [3., 3.]#[5.2, 8.3] self.formulation = µ.Formulation.finite_strain self.sys = µ.Cell(self.resolution, self.lengths, self.formulation) self.hard = µ.material.MaterialLinearElastic1_2d.make( self.sys, "hard", 210e9, .33) self.soft = µ.material.MaterialLinearElastic1_2d.make( self.sys, "soft", 70e9, .33) def test_solve(self): for i, pixel in enumerate(self.sys): if i < 3: self.hard.add_pixel(pixel) else: self.soft.add_pixel(pixel) self.sys.initialise() tol = 1e-6 Del0 = np.array([[0, .1], [0, 0]]) maxiter = 100 verbose = 0 solver=µ.solvers.SolverCG(self.sys, tol, maxiter, verbose) r = µ.solvers.de_geus(self.sys, Del0, solver,tol, verbose) #print(r) class EigenStrainCheck(unittest.TestCase): def setUp(self): self.resolution = [3, 3]#[5,7] self.lengths = [3., 3.]#[5.2, 8.3] self.formulation = µ.Formulation.small_strain self.cell1 = µ.Cell(self.resolution, self.lengths, self.formulation) self.cell2 = µ.Cell(self.resolution, self.lengths, self.formulation) self.mat1 = µ.material.MaterialLinearElastic1_2d.make( self.cell1, "simple", 210e9, .33) self.mat2 = µ.material.MaterialLinearElastic2_2d.make( self.cell2, "eigen", 210e9, .33) self.mat3 = µ.material.MaterialLinearElastic2_2d.make( self.cell2, "eigen2", 120e9, .33) def test_globalisation(self): for pixel in self.cell2: self.mat2.add_pixel(pixel, np.random.rand(2,2)) loc_eigenstrain = self.mat2.collection.get_real_field("Eigenstrain").array glo_eigenstrain = self.cell2.get_globalised_internal_real_array("Eigenstrain") error = np.linalg.norm(loc_eigenstrain-glo_eigenstrain) self.assertEqual(error, 0) def test_globalisation_constant(self): for i, pixel in enumerate(self.cell2): if i%2 == 0: self.mat2.add_pixel(pixel, np.ones((2,2))) else: self.mat3.add_pixel(pixel, np.ones((2,2))) glo_eigenstrain = self.cell2.get_globalised_internal_real_array("Eigenstrain") error = np.linalg.norm(glo_eigenstrain-1) self.assertEqual(error, 0) def test_globalisation(self): for pixel in self.cell2: self.mat2.add_pixel(pixel, np.random.rand(2,2)) loc_eigenstrain = self.mat2.collection.get_real_field("Eigenstrain").array glo_eigenstrain = self.cell2.get_globalised_internal_real_array("Eigenstrain") error = np.linalg.norm(loc_eigenstrain-glo_eigenstrain) self.assertEqual(error, 0) def test_solve(self): verbose_test = False if verbose_test: print("start test_solve") grad = np.array([[1.1, .2], [ .3, 1.5]]) gl_strain = -0.5*(grad.T.dot(grad) - np.eye(2)) gl_strain = -0.5*(grad.T + grad - 2*np.eye(2)) grad = -gl_strain if verbose_test: print("grad =\n{}\ngl_strain =\n{}".format(grad, gl_strain)) for i, pixel in enumerate(self.cell1): self.mat1.add_pixel(pixel) self.mat2.add_pixel(pixel, gl_strain) self.cell1.initialise() self.cell2.initialise() tol = 1e-6 Del0_1 = grad Del0_2 = np.zeros_like(grad) maxiter = 2 verbose = 0 def solve(cell, grad): solver=µ.solvers.SolverCG(cell, tol, maxiter, verbose) r = µ.solvers.newton_cg(cell, grad, solver, tol, tol, verbose) return r results = [solve(cell, del0) for (cell, del0) in zip((self.cell1, self.cell2), (Del0_1, Del0_2))] P1 = results[0].stress P2 = results[1].stress error = np.linalg.norm(P1-P2)/np.linalg.norm(.5*(P1+P2)) if verbose_test: print("cell 1, no eigenstrain") print("P1:\n{}".format(P1[:,0])) print("F1:\n{}".format(results[0].grad[:,0])) print("cell 2, with eigenstrain") print("P2:\n{}".format(P2[:,0])) print("F2:\n{}".format(results[1].grad[:,0])) print("end test_solve") self.assertLess(error, tol) if __name__ == '__main__': unittest.main() diff --git a/tests/python_mpi_binding_tests.py b/tests/python_mpi_binding_tests.py index 21c4215..c2d3383 100755 --- a/tests/python_mpi_binding_tests.py +++ b/tests/python_mpi_binding_tests.py @@ -1,47 +1,44 @@ #!/usr/bin/env python3 """ file python_mpi_binding_tests.py @author Till Junge @date 09 Jan 2018 @brief Unit tests for python bindings with MPI support -@section LICENCE - Copyright © 2018 Till Junge µSpectre is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3, or (at your option) any later version. µSpectre is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with µSpectre; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with proprietary FFT implementations or numerical libraries, containing parts covered by the terms of those libraries' licenses, the licensors of this Program grant you additional permission to convey the resulting work. """ import unittest import numpy as np from python_test_imports import µ -from python_mpi_projection_tests import * from python_mpi_material_linear_elastic4_test import * if __name__ == '__main__': unittest.main() diff --git a/tests/python_test_imports.py b/tests/python_test_imports.py index be9192b..c55416f 100644 --- a/tests/python_test_imports.py +++ b/tests/python_test_imports.py @@ -1,53 +1,54 @@ #!/usr/bin/env python3 # -*- coding:utf-8 -*- """ file python_test_imports.py @author Till Junge @date 18 Jan 2018 @brief prepares sys.path to load muSpectre @section LICENSE Copyright © 2018 Till Junge µSpectre is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3, or (at your option) any later version. µSpectre is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with µSpectre; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Additional permission under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with proprietary FFT implementations or numerical libraries, containing parts covered by the terms of those libraries' licenses, the licensors of this Program grant you additional permission to convey the resulting work. """ import sys import os # Default path of the library -sys.path.insert(0, os.path.join(os.getcwd(), "language_bindings/python")) +sys.path.insert(0, os.path.join(os.getcwd(), "../language_bindings/python")) +print("current working directory: '{}'".format(os.getcwd())) # Path of the library when compiling with Xcode -sys.path.insert(0, os.path.join(os.getcwd(), "language_bindings/python/Debug")) +sys.path.insert(0, os.path.join(os.getcwd(), "../language_bindings/python/Debug")) try: import muSpectre as µ import muSpectre except ImportError as err: print(err) sys.exit(-1) diff --git a/tests/test_cell_base.cc b/tests/test_cell_base.cc index 8d45cf1..ee8066d 100644 --- a/tests/test_cell_base.cc +++ b/tests/test_cell_base.cc @@ -1,324 +1,327 @@ /** * @file test_cell_base.cc * * @author Till Junge * * @date 14 Dec 2017 * * @brief Tests for the basic cell class * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include #include #include "tests.hh" -#include "common/common.hh" -#include "common/iterators.hh" -#include "common/field_map.hh" -#include "tests/test_goodies.hh" -#include "cell/cell_factory.hh" -#include "materials/material_linear_elastic1.hh" +#include "libmugrid/test_goodies.hh" + +#include +#include +#include +#include namespace muSpectre { + using muGrid::make_field; + using muGrid::TypedField; BOOST_AUTO_TEST_SUITE(cell_base); template struct Sizes {}; template <> struct Sizes { constexpr static Dim_t sdim{twoD}; constexpr static Ccoord_t get_resolution() { return Ccoord_t{3, 5}; } constexpr static Rcoord_t get_lengths() { return Rcoord_t{3.4, 5.8}; } }; template <> struct Sizes { constexpr static Dim_t sdim{threeD}; constexpr static Ccoord_t get_resolution() { return Ccoord_t{3, 5, 7}; } constexpr static Rcoord_t get_lengths() { return Rcoord_t{3.4, 5.8, 6.7}; } }; template struct CellBaseFixture : CellBase { constexpr static Dim_t sdim{DimS}; constexpr static Dim_t mdim{DimM}; constexpr static Formulation formulation{form}; CellBaseFixture() : CellBase{std::move( cell_input(Sizes::get_resolution(), Sizes::get_lengths(), form))} {} }; using fixlist = boost::mpl::list< CellBaseFixture, CellBaseFixture, CellBaseFixture, CellBaseFixture>; BOOST_AUTO_TEST_CASE(manual_construction) { constexpr Dim_t dim{twoD}; Ccoord_t resolutions{3, 3}; Rcoord_t lengths{2.3, 2.7}; Formulation form{Formulation::finite_strain}; - auto fft_ptr{std::make_unique>(resolutions, dim * dim)}; + auto fft_ptr{ + std::make_unique>(resolutions, dim * dim)}; auto proj_ptr{std::make_unique>( std::move(fft_ptr), lengths)}; CellBase sys{std::move(proj_ptr)}; auto sys2{make_cell(resolutions, lengths, form)}; auto sys2b{std::move(sys2)}; BOOST_CHECK_EQUAL(sys2b.size(), sys.size()); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(constructor_test, fix, fixlist, fix) { BOOST_CHECK_THROW(fix::check_material_coverage(), std::runtime_error); BOOST_CHECK_THROW(fix::initialise(), std::runtime_error); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(add_material_test, fix, fixlist, fix) { constexpr Dim_t dim{fix::sdim}; using Material_t = MaterialLinearElastic1; auto Material_hard = std::make_unique("hard", 210e9, .33); BOOST_CHECK_NO_THROW(fix::add_material(std::move(Material_hard))); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(simple_evaluation_test, fix, fixlist, fix) { constexpr Dim_t dim{fix::sdim}; constexpr Formulation form{fix::formulation}; using Mat_t = MaterialLinearElastic1; const Real Young{210e9}, Poisson{.33}; const Real lambda{Young * Poisson / ((1 + Poisson) * (1 - 2 * Poisson))}; const Real mu{Young / (2 * (1 + Poisson))}; auto Material_hard = std::make_unique("hard", Young, Poisson); for (auto && pixel : *this) { Material_hard->add_pixel(pixel); } fix::add_material(std::move(Material_hard)); auto & F = fix::get_strain(); auto F_map = F.get_map(); // finite strain formulation expects the deformation gradient F, // while small strain expects infinitesimal strain ε for (auto grad : F_map) { switch (form) { case Formulation::finite_strain: { grad = grad.Identity(); break; } case Formulation::small_strain: { grad = grad.Zero(); break; } default: BOOST_CHECK(false); break; } } auto res_tup{fix::evaluate_stress_tangent(F)}; auto stress{std::get<0>(res_tup).get_map()}; auto tangent{std::get<1>(res_tup).get_map()}; - auto tup = - testGoodies::objective_hooke_explicit(lambda, mu, Matrices::I2()); + auto tup = muGrid::testGoodies::objective_hooke_explicit( + lambda, mu, Matrices::I2()); auto P_ref = std::get<0>(tup); for (auto mat : stress) { Real norm = (mat - P_ref).norm(); BOOST_CHECK_EQUAL(norm, 0.); } auto tan_ref = std::get<1>(tup); for (const auto tan : tangent) { Real norm = (tan - tan_ref).norm(); BOOST_CHECK_EQUAL(norm, 0.); } } BOOST_FIXTURE_TEST_CASE_TEMPLATE(evaluation_test, fix, fixlist, fix) { constexpr Dim_t dim{fix::sdim}; using Mat_t = MaterialLinearElastic1; auto Material_hard = std::make_unique("hard", 210e9, .33); auto Material_soft = std::make_unique("soft", 70e9, .3); for (auto && cnt_pixel : akantu::enumerate(*this)) { auto counter = std::get<0>(cnt_pixel); auto && pixel = std::get<1>(cnt_pixel); if (counter < 5) { Material_hard->add_pixel(pixel); } else { Material_soft->add_pixel(pixel); } } fix::add_material(std::move(Material_hard)); fix::add_material(std::move(Material_soft)); auto & F = fix::get_strain(); fix::evaluate_stress_tangent(F); fix::evaluate_stress_tangent(F); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(evaluation_test_new_interface, fix, fixlist, fix) { constexpr Dim_t dim{fix::sdim}; using Mat_t = MaterialLinearElastic1; auto Material_hard = std::make_unique("hard", 210e9, .33); auto Material_soft = std::make_unique("soft", 70e9, .3); for (auto && cnt_pixel : akantu::enumerate(*this)) { auto counter = std::get<0>(cnt_pixel); auto && pixel = std::get<1>(cnt_pixel); if (counter < 5) { Material_hard->add_pixel(pixel); } else { Material_soft->add_pixel(pixel); } } fix::add_material(std::move(Material_hard)); fix::add_material(std::move(Material_soft)); auto F_vec = fix::get_strain_vector(); F_vec.setZero(); fix::evaluate_stress_tangent(); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_managed_fields, Fix, fixlist, Fix) { Cell & dyn_handle{*this}; CellBase & base_handle{*this}; const std::string name1{"aaa"}; constexpr size_t nb_comp{5}; auto new_dyn_array{dyn_handle.get_managed_real_array(name1, nb_comp)}; BOOST_CHECK_EQUAL(new_dyn_array.rows(), nb_comp); BOOST_CHECK_EQUAL(new_dyn_array.cols(), dyn_handle.size()); BOOST_CHECK_THROW(dyn_handle.get_managed_real_array(name1, nb_comp + 1), std::runtime_error); auto & new_field{base_handle.get_managed_real_field(name1, nb_comp)}; BOOST_CHECK_EQUAL(new_field.get_nb_components(), nb_comp); BOOST_CHECK_EQUAL(new_field.size(), dyn_handle.size()); BOOST_CHECK_THROW(base_handle.get_managed_real_field(name1, nb_comp + 1), std::runtime_error); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_globalised_fields, Fix, fixlist, Fix) { constexpr Dim_t Dim{Fix::sdim}; using Mat_t = MaterialLinearElastic1; using LColl_t = typename Mat_t::MFieldCollection_t; auto & material_soft{Mat_t::make(*this, "soft", 70e9, .3)}; auto & material_hard{Mat_t::make(*this, "hard", 210e9, .3)}; for (auto && tup : akantu::enumerate(*this)) { const auto & i{std::get<0>(tup)}; const auto & pixel{std::get<1>(tup)}; if (i % 2) { material_soft.add_pixel(pixel); } else { material_hard.add_pixel(pixel); } } material_soft.initialise(); material_hard.initialise(); auto & col_soft{material_soft.get_collection()}; auto & col_hard{material_hard.get_collection()}; // compatible fields: const std::string compatible_name{"compatible"}; auto & compatible_soft{ make_field>(compatible_name, col_soft, Dim)}; auto & compatible_hard{ make_field>(compatible_name, col_hard, Dim)}; auto pixler = [](auto & field) { auto map{field.get_map()}; for (auto && tup : map.enumerate()) { const auto & pixel{std::get<0>(tup)}; auto & val{std::get<1>(tup)}; for (Dim_t i{0}; i < Dim; ++i) { val(i) = pixel[i]; } } }; pixler(compatible_soft); pixler(compatible_hard); auto & global_compatible_field{ this->get_globalised_internal_real_field(compatible_name)}; auto glo_map{global_compatible_field.get_map()}; for (auto && tup : glo_map.enumerate()) { const auto & pixel{std::get<0>(tup)}; const auto & val(std::get<1>(tup)); using Map_t = Eigen::Map>; Real err{ (val - Map_t(pixel.data()).template cast()).matrix().norm()}; BOOST_CHECK_LT(err, tol); } // incompatible fields: const std::string incompatible_name{"incompatible"}; make_field>(incompatible_name, col_soft, Dim); make_field>(incompatible_name, col_hard, Dim + 1); BOOST_CHECK_THROW( this->get_globalised_internal_real_field(incompatible_name), std::runtime_error); // wrong name/ inexistant field const std::string wrong_name{"wrong_name"}; BOOST_CHECK_THROW(this->get_globalised_internal_real_field(wrong_name), std::runtime_error); // wrong scalar type: const std::string wrong_scalar_name{"wrong_scalar"}; make_field>(wrong_scalar_name, col_soft, Dim); make_field>(wrong_scalar_name, col_hard, Dim); BOOST_CHECK_THROW( this->get_globalised_internal_real_field(wrong_scalar_name), std::runtime_error); } BOOST_AUTO_TEST_SUITE_END(); } // namespace muSpectre diff --git a/tests/test_geometry.cc b/tests/test_geometry.cc index 6d933ff..3d1e228 100644 --- a/tests/test_geometry.cc +++ b/tests/test_geometry.cc @@ -1,324 +1,328 @@ /** * file test_geometry.cc * * @author Till Junge * * @date 19 Apr 2018 * * @brief Tests for tensor rotations * * @section LICENSE * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#include "common/geometry.hh" #include "tests.hh" -#include "test_goodies.hh" -#include "common/T4_map_proxy.hh" +#include "libmugrid/test_goodies.hh" + +#include +#include #include #include #include +#include namespace muSpectre { enum class IsAligned { yes, no }; BOOST_AUTO_TEST_SUITE(geometry); /* ---------------------------------------------------------------------- */ template struct RotationFixture { static constexpr Dim_t Dim{Dim_}; using Vec_t = Eigen::Matrix; using Mat_t = Eigen::Matrix; - using Ten_t = T4Mat; + + using Ten_t = muGrid::T4Mat; static constexpr Dim_t get_Dim() { return Dim_; } using Rot_t = RotatorBase; explicit RotationFixture(Rot_t rot_mat_inp) : rot_mat{rot_mat_inp}, rotator(rot_mat) {} Vec_t v{Vec_t::Random()}; Mat_t m{Mat_t::Random()}; Ten_t t{Ten_t::Random()}; Mat_t rot_mat; Rot_t rotator; testGoodies::RandRange rr{}; }; template struct RotationAngleFixture { static constexpr Dim_t Dim{Dim_}; using Parent = RotationFixture; using Vec_t = Eigen::Matrix; using Mat_t = Eigen::Matrix; - using Ten_t = T4Mat; + using Ten_t = muGrid::T4Mat; + using Angles_t = Eigen::Matrix; using RotAng_t = RotatorAngle; static constexpr RotationOrder EulerOrder{Rot}; static constexpr Dim_t get_Dim() { return Dim_; } RotationAngleFixture() : rotator{euler} {} Vec_t v{Vec_t::Random()}; Mat_t m{Mat_t::Random()}; Ten_t t{Ten_t::Random()}; Angles_t euler{2 * pi * Angles_t::Random()}; RotatorAngle rotator; }; template struct RotationTwoVecFixture { static constexpr Dim_t Dim{Dim_}; using Parent = RotationFixture; using Vec_t = Eigen::Matrix; using Mat_t = Eigen::Matrix; using Ten_t = T4Mat; static constexpr Dim_t get_Dim() { return Dim_; } RotationTwoVecFixture() : vec_ref{this->ref_vec_maker()}, vec_des{this->des_vec_maker()}, rotator(vec_ref, vec_des) {} Vec_t ref_vec_maker() { Vec_t ret_vec{Vec_t::Random()}; return ret_vec / ret_vec.norm(); } Vec_t des_vec_maker() { if (is_aligned == IsAligned::yes) { return -this->vec_ref; } else { Vec_t ret_vec{Vec_t::Random()}; return ret_vec / ret_vec.norm(); } } Vec_t v{Vec_t::Random()}; Mat_t m{Mat_t::Random()}; Ten_t t{Ten_t::Random()}; Vec_t vec_ref{Vec_t::Random()}; Vec_t vec_des{Vec_t::Random()}; RotatorTwoVec rotator; }; /* ---------------------------------------------------------------------- */ template struct RotationNormalFixture { static constexpr Dim_t Dim{Dim_}; using Parent = RotationFixture; using Vec_t = Eigen::Matrix; using Mat_t = Eigen::Matrix; using Ten_t = T4Mat; static constexpr Dim_t get_Dim() { return Dim_; } RotationNormalFixture() : vec_norm{this->vec_maker()}, rotator(vec_norm) {} Vec_t vec_maker() { if (is_aligned == IsAligned::yes) { return -Vec_t::UnitX(); } else { Vec_t ret_vec{Vec_t::Random()}; return ret_vec / ret_vec.norm(); } } Vec_t v{Vec_t::Random()}; Mat_t m{Mat_t::Random()}; Ten_t t{Ten_t::Random()}; Vec_t vec_norm; RotatorNormal rotator; }; /* ---------------------------------------------------------------------- */ using fix_list = boost::mpl::list< RotationAngleFixture, RotationAngleFixture, RotationNormalFixture, RotationNormalFixture, RotationTwoVecFixture, RotationTwoVecFixture>; /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE_TEMPLATE(rotation_test, Fix, fix_list, Fix) { using Vec_t = typename Fix::Vec_t; using Mat_t = typename Fix::Mat_t; using Ten_t = typename Fix::Ten_t; constexpr const Dim_t Dim{Fix::get_Dim()}; Vec_t & v{Fix::v}; Mat_t & m{Fix::m}; Ten_t & t{Fix::t}; const Mat_t & R{Fix::rotator.get_rot_mat()}; Vec_t v_ref{R * v}; Mat_t m_ref{R * m * R.transpose()}; Ten_t t_ref{Ten_t::Zero()}; for (int i = 0; i < Dim; ++i) { for (int a = 0; a < Dim; ++a) { for (int l = 0; l < Dim; ++l) { for (int b = 0; b < Dim; ++b) { for (int m = 0; m < Dim; ++m) { for (int n = 0; n < Dim; ++n) { for (int o = 0; o < Dim; ++o) { for (int p = 0; p < Dim; ++p) { - get(t_ref, a, b, o, p) += R(a, i) * R(b, l) * - get(t, i, l, m, n) * R(o, m) * - R(p, n); + muGrid::get(t_ref, a, b, o, p) += + R(a, i) * R(b, l) * muGrid::get(t, i, l, m, n) * + R(o, m) * R(p, n); } } } } } } } } Vec_t v_rotator(Fix::rotator.rotate(v)); Mat_t m_rotator(Fix::rotator.rotate(m)); Ten_t t_rotator(Fix::rotator.rotate(t)); auto v_error{(v_rotator - v_ref).norm() / v_ref.norm()}; BOOST_CHECK_LT(v_error, tol); auto m_error{(m_rotator - m_ref).norm() / m_ref.norm()}; BOOST_CHECK_LT(m_error, tol); auto t_error{(t_rotator - t_ref).norm() / t_ref.norm()}; BOOST_CHECK_LT(t_error, tol); if (t_error >= tol) { std::cout << "t4_reference:" << std::endl << t_ref << std::endl; std::cout << "t4_rotator:" << std::endl << t_rotator << std::endl; } Vec_t v_back{Fix::rotator.rotate_back(v_rotator)}; Mat_t m_back{Fix::rotator.rotate_back(m_rotator)}; Ten_t t_back{Fix::rotator.rotate_back(t_rotator)}; v_error = (v_back - v).norm() / v.norm(); BOOST_CHECK_LT(v_error, tol); m_error = (m_back - m).norm() / m.norm(); BOOST_CHECK_LT(m_error, tol); t_error = (t_back - t).norm() / t.norm(); BOOST_CHECK_LT(t_error, tol); } /* ---------------------------------------------------------------------- */ using threeD_list = boost::mpl::list< RotationAngleFixture>; /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE_TEMPLATE(rotation_matrix_test, Fix, threeD_list, Fix) { using Mat_t = typename Fix::Mat_t; auto c{Eigen::cos(Fix::euler.array())}; Real c_1{c[0]}, c_2{c[1]}, c_3{c[2]}; auto s{Eigen::sin(Fix::euler.array())}; Real s_1{s[0]}, s_2{s[1]}, s_3{s[2]}; Mat_t rot_ref; switch (Fix::EulerOrder) { case RotationOrder::ZXYTaitBryan: { rot_ref << c_1 * c_3 - s_1 * s_2 * s_3, -c_2 * s_1, c_1 * s_3 + c_3 * s_1 * s_2, c_3 * s_1 + c_1 * s_2 * s_3, c_1 * c_2, s_1 * s_3 - c_1 * c_3 * s_2, -c_2 * s_3, s_2, c_2 * c_3; break; } default: { BOOST_CHECK(false); break; } } auto err{(rot_ref - Fix::rotator.get_rot_mat()).norm()}; BOOST_CHECK_LT(err, tol); if (not(err < tol)) { std::cout << "Reference:" << std::endl << rot_ref << std::endl; std::cout << "Rotator:" << std::endl << Fix::rotator.get_rot_mat() << std::endl; } } /* ---------------------------------------------------------------------- */ using twovec_list = boost::mpl::list, RotationTwoVecFixture, RotationTwoVecFixture, RotationTwoVecFixture>; /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE_TEMPLATE(rotation_twovec_test, Fix, twovec_list, Fix) { using Vec_t = typename Fix::Vec_t; Vec_t vec_ref{Fix::vec_ref}; Vec_t vec_des{Fix::vec_des}; Vec_t vec_res{Fix::rotator.rotate(vec_ref)}; Vec_t vec_back{Fix::rotator.rotate_back(vec_res)}; auto err_f{(vec_res - vec_des).norm()}; BOOST_CHECK_LT(err_f, tol); if (err_f >= tol) { std::cout << "Destination:" << std::endl << vec_des << std::endl; std::cout << "Rotated:" << std::endl << vec_res << std::endl; } auto err_b{(vec_back - vec_ref).norm()}; BOOST_CHECK_LT(err_b, tol); if (err_b >= tol) { std::cout << "Refrence:" << std::endl << vec_ref << std::endl; std::cout << "Rotated Back:" << std::endl << vec_back << std::endl; } } /* ---------------------------------------------------------------------- */ using normal_list = boost::mpl::list, RotationNormalFixture, RotationNormalFixture, RotationNormalFixture>; /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE_TEMPLATE(rotation_normal_test, Fix, normal_list, Fix) { using Vec_t = typename Fix::Vec_t; Vec_t vec_ref{Fix::vec_norm}; Vec_t vec_des{Vec_t::UnitX()}; Vec_t vec_res{Fix::rotator.rotate_back(vec_ref)}; Vec_t vec_back{Fix::rotator.rotate(vec_res)}; auto err_f{(vec_res - vec_des).norm()}; BOOST_CHECK_LT(err_f, tol); if (err_f >= tol) { std::cout << "Destination:" << std::endl << vec_des << std::endl; std::cout << "Rotated:" << std::endl << vec_res << std::endl; } auto err_b{(vec_back - vec_ref).norm()}; BOOST_CHECK_LT(err_b, tol); if (err_b >= tol) { std::cout << "Refrence:" << std::endl << vec_ref << std::endl; std::cout << "Rotated Back:" << std::endl << vec_back << std::endl; } } BOOST_AUTO_TEST_SUITE_END(); } // namespace muSpectre diff --git a/tests/test_material_evaluator.cc b/tests/test_material_evaluator.cc index 44630ea..3429adb 100644 --- a/tests/test_material_evaluator.cc +++ b/tests/test_material_evaluator.cc @@ -1,288 +1,287 @@ /** * @file test_material_evaluator.cc * * @author Till Junge * * @date 13 Jan 2019 * * @brief tests for the material evaluator mechanism * * Copyright © 2019 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "tests.hh" -#include "common/T4_map_proxy.hh" #include "materials/material_linear_elastic2.hh" #include "materials/material_evaluator.hh" +#include + #include "Eigen/Dense" namespace muSpectre { BOOST_AUTO_TEST_SUITE(material_evaluator_tests); /* ---------------------------------------------------------------------- */ BOOST_AUTO_TEST_CASE(without_per_pixel_data) { using Mat_t = MaterialLinearElastic1; constexpr Real Young{210e9}; constexpr Real Poisson{.33}; auto mat_eval = Mat_t::make_evaluator(Young, Poisson); auto & mat = *std::get<0>(mat_eval); auto & evaluator = std::get<1>(mat_eval); using T2_t = Eigen::Matrix; - using T4_t = T4Mat; + using T4_t = muGrid::T4Mat; const T2_t F{(T2_t::Random() - (T2_t::Ones() * .5)) * 1e-4 + T2_t::Identity()}; const T2_t eps{ .5 * ((F - T2_t::Identity()) + (F - T2_t::Identity()).transpose())}; /* * at this point, the evaluator has been created, but the underlying * material still has zero pixels. Evaluation is not yet possible, and * trying to do so has to fail with an explicit error message */ BOOST_CHECK_THROW(evaluator.evaluate_stress(eps, Formulation::small_strain), std::runtime_error); mat.add_pixel({}); const T2_t sigma{evaluator.evaluate_stress(eps, Formulation::small_strain)}; const T2_t P{evaluator.evaluate_stress(F, Formulation::finite_strain)}; auto J{F.determinant()}; auto P_reconstruct{J * sigma * F.inverse().transpose()}; auto error_comp{[](const auto & a, const auto & b) { return (a - b).norm() / (a + b).norm(); }}; auto error{error_comp(P, P_reconstruct)}; constexpr Real small_strain_tol{1e-3}; if (not(error <= small_strain_tol)) { std::cout << "F =" << std::endl << F << std::endl; std::cout << "ε =" << std::endl << eps << std::endl; std::cout << "P =" << std::endl << P << std::endl; std::cout << "σ =" << std::endl << sigma << std::endl; std::cout << "P_reconstructed =" << std::endl << P_reconstruct << std::endl; } BOOST_CHECK_LE(error, small_strain_tol); T2_t sigma2, P2; T4_t C, K; std::tie(sigma2, C) = - evaluator.evaluate_stress_tangent(eps, Formulation::small_strain); + evaluator.evaluate_stress_tangent(eps, Formulation::small_strain); std::tie(P2, K) = - evaluator.evaluate_stress_tangent(F, Formulation::finite_strain); + evaluator.evaluate_stress_tangent(F, Formulation::finite_strain); error = error_comp(sigma2, sigma); BOOST_CHECK_LE(error, tol); error = error_comp(P2, P); BOOST_CHECK_LE(error, tol); error = error_comp(C, K); if (not(error <= small_strain_tol)) { std::cout << "F =" << std::endl << F << std::endl; std::cout << "ε =" << std::endl << eps << std::endl; std::cout << "P =" << std::endl << P << std::endl; std::cout << "σ =" << std::endl << sigma << std::endl; std::cout << "K =" << std::endl << K << std::endl; std::cout << "C =" << std::endl << C << std::endl; } BOOST_CHECK_LE(error, small_strain_tol); - mat.add_pixel({1}); /* * Now, the material has two pixels, and evaluating it would be ambiguous. * It should fail with an explicit error message */ BOOST_CHECK_THROW(evaluator.evaluate_stress(eps, Formulation::small_strain), std::runtime_error); } /* ---------------------------------------------------------------------- */ BOOST_AUTO_TEST_CASE(with_per_pixel_data) { using Mat_t = MaterialLinearElastic2; constexpr Real Young{210e9}; constexpr Real Poisson{.33}; auto mat_eval{Mat_t::make_evaluator(Young, Poisson)}; auto & mat{*std::get<0>(mat_eval)}; auto & evaluator{std::get<1>(mat_eval)}; - using T2_t = Eigen::Matrix; - using T4_t = T4Mat; + using T4_t = muGrid::T4Mat; const T2_t F{(T2_t::Random() - (T2_t::Ones() * .5)) * 1e-4 + T2_t::Identity()}; const T2_t eps{ .5 * ((F - T2_t::Identity()) + (F - T2_t::Identity()).transpose())}; BOOST_CHECK_THROW(evaluator.evaluate_stress(eps, Formulation::small_strain), std::runtime_error); T2_t eigen_strain{[](auto x) { return 1e-4 * (x + x.transpose()); }(T2_t::Random() - T2_t::Ones() * .5)}; mat.add_pixel({}, eigen_strain); const T2_t sigma{evaluator.evaluate_stress(eps, Formulation::small_strain)}; const T2_t P{evaluator.evaluate_stress(F, Formulation::finite_strain)}; auto J{F.determinant()}; auto P_reconstruct{J * sigma * F.inverse().transpose()}; auto error_comp{[](const auto & a, const auto & b) { return (a - b).norm() / (a + b).norm(); }}; auto error{error_comp(P, P_reconstruct)}; constexpr Real small_strain_tol{1e-3}; if (not(error <= small_strain_tol)) { std::cout << "F =" << std::endl << F << std::endl; std::cout << "ε =" << std::endl << eps << std::endl; std::cout << "P =" << std::endl << P << std::endl; std::cout << "σ =" << std::endl << sigma << std::endl; std::cout << "P_reconstructed =" << std::endl << P_reconstruct << std::endl; } BOOST_CHECK_LE(error, small_strain_tol); T2_t sigma2, P2; T4_t C, K; std::tie(sigma2, C) = - evaluator.evaluate_stress_tangent(eps, Formulation::small_strain); + evaluator.evaluate_stress_tangent(eps, Formulation::small_strain); std::tie(P2, K) = - evaluator.evaluate_stress_tangent(F, Formulation::finite_strain); + evaluator.evaluate_stress_tangent(F, Formulation::finite_strain); error = error_comp(sigma2, sigma); BOOST_CHECK_LE(error, tol); error = error_comp(P2, P); BOOST_CHECK_LE(error, tol); error = error_comp(C, K); if (not(error <= small_strain_tol)) { std::cout << "F =" << std::endl << F << std::endl; std::cout << "ε =" << std::endl << eps << std::endl; std::cout << "P =" << std::endl << P << std::endl; std::cout << "σ =" << std::endl << sigma << std::endl; std::cout << "K =" << std::endl << K << std::endl; std::cout << "C =" << std::endl << C << std::endl; } BOOST_CHECK_LE(error, small_strain_tol); } /* ---------------------------------------------------------------------- */ BOOST_AUTO_TEST_CASE(tangent_estimation) { using Mat_t = MaterialLinearElastic1; constexpr Real Young{210e9}; constexpr Real Poisson{.33}; auto mat_eval = Mat_t::make_evaluator(Young, Poisson); auto & mat = *std::get<0>(mat_eval); auto & evaluator = std::get<1>(mat_eval); using T2_t = Eigen::Matrix; - using T4_t = T4Mat; + using T4_t = muGrid::T4Mat; const T2_t F{(T2_t::Random() - (T2_t::Ones() * .5)) * 1e-4 + T2_t::Identity()}; const T2_t eps{ .5 * ((F - T2_t::Identity()) + (F - T2_t::Identity()).transpose())}; BOOST_CHECK_THROW(evaluator.evaluate_stress(eps, Formulation::small_strain), std::runtime_error); mat.add_pixel({}); T2_t sigma, P; T4_t C, K; std::tie(sigma, C) = - evaluator.evaluate_stress_tangent(eps, Formulation::small_strain); + evaluator.evaluate_stress_tangent(eps, Formulation::small_strain); std::tie(P, K) = - evaluator.evaluate_stress_tangent(F, Formulation::finite_strain); + evaluator.evaluate_stress_tangent(F, Formulation::finite_strain); constexpr Real linear_step{1.}; constexpr Real nonlin_step{1.e-6}; T4_t C_estim{evaluator.estimate_tangent(eps, Formulation::small_strain, linear_step)}; - T4_t K_estim{evaluator.estimate_tangent(F, Formulation::finite_strain, - nonlin_step)}; + T4_t K_estim{ + evaluator.estimate_tangent(F, Formulation::finite_strain, nonlin_step)}; auto error_comp{[](const auto & a, const auto & b) { return (a - b).norm() / (a + b).norm(); }}; constexpr Real finite_diff_tol{1e-9}; - Real error {error_comp(K, K_estim)}; + Real error{error_comp(K, K_estim)}; if (not(error <= finite_diff_tol)) { std::cout << "K =" << std::endl << K << std::endl; std::cout << "K_estim =" << std::endl << K_estim << std::endl; } BOOST_CHECK_LE(error, finite_diff_tol); error = error_comp(C, C_estim); if (not(error <= tol)) { std::cout << "centred difference:" << std::endl; std::cout << "C =" << std::endl << C << std::endl; std::cout << "C_estim =" << std::endl << C_estim << std::endl; } BOOST_CHECK_LE(error, tol); C_estim = evaluator.estimate_tangent(eps, Formulation::small_strain, linear_step, FiniteDiff::forward); error = error_comp(C, C_estim); if (not(error <= tol)) { std::cout << "forward difference:" << std::endl; std::cout << "C =" << std::endl << C << std::endl; std::cout << "C_estim =" << std::endl << C_estim << std::endl; } BOOST_CHECK_LE(error, tol); C_estim = evaluator.estimate_tangent(eps, Formulation::small_strain, linear_step, FiniteDiff::backward); error = error_comp(C, C_estim); if (not(error <= tol)) { std::cout << "backward difference:" << std::endl; std::cout << "C =" << std::endl << C << std::endl; std::cout << "C_estim =" << std::endl << C_estim << std::endl; } BOOST_CHECK_LE(error, tol); -} + } BOOST_AUTO_TEST_SUITE_END(); } // namespace muSpectre diff --git a/tests/test_material_hyper_elasto_plastic1.cc b/tests/test_material_hyper_elasto_plastic1.cc index 7c7b281..4fb6df3 100644 --- a/tests/test_material_hyper_elasto_plastic1.cc +++ b/tests/test_material_hyper_elasto_plastic1.cc @@ -1,425 +1,430 @@ /** * @file test_material_hyper_elasto_plastic1.cc * * @author Till Junge * * @date 25 Feb 2018 * * @brief Tests for the large-strain Simo-type plastic law implemented * using MaterialMuSpectre * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#include "boost/mpl/list.hpp" - -#include "materials/stress_transformations_Kirchhoff.hh" -#include "materials/material_hyper_elasto_plastic1.hh" -#include "materials/materials_toolbox.hh" #include "tests.hh" -#include "test_goodies.hh" +#include "libmugrid/test_goodies.hh" + +#include +#include +#include + +#include namespace muSpectre { BOOST_AUTO_TEST_SUITE(material_hyper_elasto_plastic_1); template struct MaterialFixture { using Mat = Mat_t; constexpr static Real K{.833}; // bulk modulus constexpr static Real mu{.386}; // shear modulus constexpr static Real H{.004}; // hardening modulus constexpr static Real tau_y0{.003}; // initial yield stress constexpr static Real young{MatTB::convert_elastic_modulus< ElasticModulus::Young, ElasticModulus::Bulk, ElasticModulus::Shear>( K, mu)}; constexpr static Real poisson{MatTB::convert_elastic_modulus< ElasticModulus::Poisson, ElasticModulus::Bulk, ElasticModulus::Shear>( K, mu)}; MaterialFixture() : mat("Name", young, poisson, tau_y0, H) {} constexpr static Dim_t sdim{Mat_t::sdim()}; constexpr static Dim_t mdim{Mat_t::mdim()}; Mat_t mat; }; using mats = boost::mpl::list< MaterialFixture>, MaterialFixture>, MaterialFixture>>; BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_constructor, Fix, mats, Fix) { BOOST_CHECK_EQUAL("Name", Fix::mat.get_name()); auto & mat{Fix::mat}; auto sdim{Fix::sdim}; auto mdim{Fix::mdim}; BOOST_CHECK_EQUAL(sdim, mat.sdim()); BOOST_CHECK_EQUAL(mdim, mat.mdim()); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_evaluate_stress, Fix, mats, Fix) { // This test uses precomputed reference values (computed using // elasto-plasticity.py) for the 3d case only // need higher tol because of printout precision of reference solutions constexpr Real hi_tol{1e-8}; constexpr Dim_t mdim{Fix::mdim}, sdim{Fix::sdim}; constexpr bool has_precomputed_values{(mdim == sdim) && (mdim == threeD)}; constexpr bool verbose{false}; using Strain_t = Eigen::Matrix; using traits = MaterialMuSpectre_traits>; using LColl_t = typename traits::LFieldColl_t; - using StrainStField_t = - StateField>; - using FlowStField_t = StateField>; + using StrainStField_t = muGrid::StateField< + muGrid::TensorField>; + using FlowStField_t = + muGrid::StateField>; // using StrainStRef_t = typename traits::LStrainMap_t::reference; // using ScalarStRef_t = typename traits::LScalarMap_t::reference; // create statefields LColl_t coll{}; coll.add_pixel({0}); coll.initialise(); - auto & F_{make_statefield("previous gradient", coll)}; - auto & be_{ - make_statefield("previous elastic strain", coll)}; - auto & eps_{make_statefield("plastic flow", coll)}; + auto & F_{ + muGrid::make_statefield("previous gradient", coll)}; + auto & be_{muGrid::make_statefield( + "previous elastic strain", coll)}; + auto & eps_{muGrid::make_statefield("plastic flow", coll)}; auto F_prev{F_.get_map()}; F_prev[0].current() = Strain_t::Identity(); auto be_prev{be_.get_map()}; be_prev[0].current() = Strain_t::Identity(); auto eps_prev{eps_.get_map()}; eps_prev[0].current() = 0; // elastic deformation Strain_t F{Strain_t::Identity()}; F(0, 1) = 1e-5; F_.cycle(); be_.cycle(); eps_.cycle(); Strain_t stress{ Fix::mat.evaluate_stress(F, F_prev[0], be_prev[0], eps_prev[0])}; if (has_precomputed_values) { Strain_t tau_ref{}; tau_ref << 1.92999522e-11, 3.86000000e-06, 0.00000000e+00, 3.86000000e-06, -1.93000510e-11, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, -2.95741950e-17; Real error{(tau_ref - stress).norm() / tau_ref.norm()}; BOOST_CHECK_LT(error, hi_tol); Strain_t be_ref{}; be_ref << 1.00000000e+00, 1.00000000e-05, 0.00000000e+00, 1.00000000e-05, 1.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.00000000e+00; error = (be_ref - be_prev[0].current()).norm() / be_ref.norm(); BOOST_CHECK_LT(error, hi_tol); Real ep_ref{0}; error = ep_ref - eps_prev[0].current(); BOOST_CHECK_LT(error, hi_tol); } if (verbose) { std::cout << "τ =" << std::endl << stress << std::endl; std::cout << "F =" << std::endl << F << std::endl; std::cout << "Fₜ =" << std::endl << F_prev[0].current() << std::endl; std::cout << "bₑ =" << std::endl << be_prev[0].current() << std::endl; std::cout << "εₚ =" << std::endl << eps_prev[0].current() << std::endl; } F_.cycle(); be_.cycle(); eps_.cycle(); // plastic deformation F(0, 1) = .2; stress = Fix::mat.evaluate_stress(F, F_prev[0], be_prev[0], eps_prev[0]); if (has_precomputed_values) { Strain_t tau_ref{}; tau_ref << 1.98151335e-04, 1.98151335e-03, 0.00000000e+00, 1.98151335e-03, -1.98151335e-04, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.60615155e-16; Real error{(tau_ref - stress).norm() / tau_ref.norm()}; BOOST_CHECK_LT(error, hi_tol); Strain_t be_ref{}; be_ref << 1.00052666, 0.00513348, 0., 0.00513348, 0.99949996, 0., 0., 0., 1.; error = (be_ref - be_prev[0].current()).norm() / be_ref.norm(); BOOST_CHECK_LT(error, hi_tol); Real ep_ref{0.11229988}; error = (ep_ref - eps_prev[0].current()) / ep_ref; BOOST_CHECK_LT(error, hi_tol); } if (verbose) { std::cout << "Post Cycle" << std::endl; std::cout << "τ =" << std::endl << stress << std::endl << "F =" << std::endl << F << std::endl << "Fₜ =" << std::endl << F_prev[0].current() << std::endl << "bₑ =" << std::endl << be_prev[0].current() << std::endl << "εₚ =" << std::endl << eps_prev[0].current() << std::endl; } } BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_evaluate_stiffness, Fix, mats, Fix) { // This test uses precomputed reference values (computed using // elasto-plasticity.py) for the 3d case only // need higher tol because of printout precision of reference solutions constexpr Real hi_tol{2e-7}; constexpr Dim_t mdim{Fix::mdim}, sdim{Fix::sdim}; constexpr bool has_precomputed_values{(mdim == sdim) && (mdim == threeD)}; constexpr bool verbose{has_precomputed_values && false}; using Strain_t = Eigen::Matrix; - using Stiffness_t = T4Mat; + using Stiffness_t = muGrid::T4Mat; using traits = MaterialMuSpectre_traits>; using LColl_t = typename traits::LFieldColl_t; - using StrainStField_t = - StateField>; - using FlowStField_t = StateField>; + using StrainStField_t = muGrid::StateField< + muGrid::TensorField>; + using FlowStField_t = + muGrid::StateField>; // using StrainStRef_t = typename traits::LStrainMap_t::reference; // using ScalarStRef_t = typename traits::LScalarMap_t::reference; // create statefields LColl_t coll{}; coll.add_pixel({0}); coll.initialise(); - auto & F_{make_statefield("previous gradient", coll)}; - auto & be_{ - make_statefield("previous elastic strain", coll)}; - auto & eps_{make_statefield("plastic flow", coll)}; + auto & F_{ + muGrid::make_statefield("previous gradient", coll)}; + auto & be_{muGrid::make_statefield( + "previous elastic strain", coll)}; + auto & eps_{muGrid::make_statefield("plastic flow", coll)}; auto F_prev{F_.get_map()}; F_prev[0].current() = Strain_t::Identity(); auto be_prev{be_.get_map()}; be_prev[0].current() = Strain_t::Identity(); auto eps_prev{eps_.get_map()}; eps_prev[0].current() = 0; // elastic deformation Strain_t F{Strain_t::Identity()}; F(0, 1) = 1e-5; F_.cycle(); be_.cycle(); eps_.cycle(); Strain_t stress{}; Stiffness_t stiffness{}; std::tie(stress, stiffness) = Fix::mat.evaluate_stress_tangent(F, F_prev[0], be_prev[0], eps_prev[0]); if (has_precomputed_values) { Strain_t tau_ref{}; tau_ref << 1.92999522e-11, 3.86000000e-06, 0.00000000e+00, 3.86000000e-06, -1.93000510e-11, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, -2.95741950e-17; Real error{(tau_ref - stress).norm() / tau_ref.norm()}; BOOST_CHECK_LT(error, hi_tol); Strain_t be_ref{}; be_ref << 1.00000000e+00, 1.00000000e-05, 0.00000000e+00, 1.00000000e-05, 1.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.00000000e+00; error = (be_ref - be_prev[0].current()).norm() / be_ref.norm(); BOOST_CHECK_LT(error, hi_tol); Real ep_ref{0}; error = ep_ref - eps_prev[0].current(); BOOST_CHECK_LT(error, hi_tol); Stiffness_t temp; temp << 1.34766667e+00, 3.86000000e-06, 0.00000000e+00, -3.86000000e-06, 5.75666667e-01, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 5.75666667e-01, -3.61540123e-17, 3.86000000e-01, 0.00000000e+00, 3.86000000e-01, 7.12911684e-17, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 3.86000000e-01, 0.00000000e+00, 0.00000000e+00, -1.93000000e-06, 3.86000000e-01, 1.93000000e-06, 0.00000000e+00, -3.61540123e-17, 3.86000000e-01, 0.00000000e+00, 3.86000000e-01, 7.12911684e-17, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 5.75666667e-01, -3.86000000e-06, 0.00000000e+00, 3.86000000e-06, 1.34766667e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 5.75666667e-01, 0.00000000e+00, 0.00000000e+00, -1.93000000e-06, 0.00000000e+00, 0.00000000e+00, 3.86000000e-01, 1.93000000e-06, 3.86000000e-01, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 3.86000000e-01, 0.00000000e+00, 0.00000000e+00, -1.93000000e-06, 3.86000000e-01, 1.93000000e-06, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, -1.93000000e-06, 0.00000000e+00, 0.00000000e+00, 3.86000000e-01, 1.93000000e-06, 3.86000000e-01, 0.00000000e+00, 5.75666667e-01, 2.61999996e-17, 0.00000000e+00, 2.61999996e-17, 5.75666667e-01, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.34766667e+00; - Stiffness_t K4b_ref{testGoodies::from_numpy(temp)}; + Stiffness_t K4b_ref{muGrid::testGoodies::from_numpy(temp)}; error = (K4b_ref - stiffness).norm() / K4b_ref.norm(); BOOST_CHECK_LT(error, hi_tol); if (not(error < hi_tol)) { std::cout << "stiffness reference:\n" << K4b_ref << std::endl; std::cout << "stiffness computed:\n" << stiffness << std::endl; } } if (verbose) { std::cout << "C₄ =" << std::endl << stiffness << std::endl; } F_.cycle(); be_.cycle(); eps_.cycle(); // plastic deformation F(0, 1) = .2; std::tie(stress, stiffness) = Fix::mat.evaluate_stress_tangent(F, F_prev[0], be_prev[0], eps_prev[0]); if (has_precomputed_values) { Strain_t tau_ref{}; tau_ref << 1.98151335e-04, 1.98151335e-03, 0.00000000e+00, 1.98151335e-03, -1.98151335e-04, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.60615155e-16; Real error{(tau_ref - stress).norm() / tau_ref.norm()}; BOOST_CHECK_LT(error, hi_tol); Strain_t be_ref{}; be_ref << 1.00052666, 0.00513348, 0., 0.00513348, 0.99949996, 0., 0., 0., 1.; error = (be_ref - be_prev[0].current()).norm() / be_ref.norm(); BOOST_CHECK_LT(error, hi_tol); Real ep_ref{0.11229988}; error = (ep_ref - eps_prev[0].current()) / ep_ref; BOOST_CHECK_LT(error, hi_tol); Stiffness_t temp{}; temp << 8.46343327e-01, 1.11250597e-03, 0.00000000e+00, -2.85052074e-03, 8.26305692e-01, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 8.26350980e-01, -8.69007382e-04, 1.21749295e-03, 0.00000000e+00, 1.61379562e-03, 8.69007382e-04, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 5.58242059e-18, 0.00000000e+00, 0.00000000e+00, 9.90756677e-03, 0.00000000e+00, 0.00000000e+00, -9.90756677e-04, 1.01057181e-02, 9.90756677e-04, 0.00000000e+00, -8.69007382e-04, 1.21749295e-03, 0.00000000e+00, 1.61379562e-03, 8.69007382e-04, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 5.58242059e-18, 8.26305692e-01, -1.11250597e-03, 0.00000000e+00, 2.85052074e-03, 8.46343327e-01, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 8.26350980e-01, 0.00000000e+00, 0.00000000e+00, -9.90756677e-04, 0.00000000e+00, 0.00000000e+00, 1.01057181e-02, 9.90756677e-04, 9.90756677e-03, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 9.90756677e-03, 0.00000000e+00, 0.00000000e+00, -9.90756677e-04, 1.01057181e-02, 9.90756677e-04, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, -9.90756677e-04, 0.00000000e+00, 0.00000000e+00, 1.01057181e-02, 9.90756677e-04, 9.90756677e-03, 0.00000000e+00, 8.26350980e-01, 0.00000000e+00, 0.00000000e+00, 1.38777878e-17, 8.26350980e-01, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 8.46298039e-01; - Stiffness_t K4b_ref{testGoodies::from_numpy(temp)}; + Stiffness_t K4b_ref{muGrid::testGoodies::from_numpy(temp)}; error = (K4b_ref - stiffness).norm() / K4b_ref.norm(); error = (K4b_ref - stiffness).norm() / K4b_ref.norm(); BOOST_CHECK_LT(error, hi_tol); if (not(error < hi_tol)) { std::cout << "stiffness reference:\n" << K4b_ref << std::endl; std::cout << "stiffness computed:\n" << stiffness << std::endl; } // check also whether pull_back is correct Stiffness_t intermediate{stiffness}; Stiffness_t zero_mediate{Stiffness_t::Zero()}; for (int i{0}; i < mdim; ++i) { for (int j{0}; j < mdim; ++j) { for (int m{0}; m < mdim; ++m) { const auto & k{i}; const auto & l{j}; // k,m inverted for right transpose - get(zero_mediate, i, j, k, m) -= stress(l, m); - get(intermediate, i, j, k, m) -= stress(l, m); + muGrid::get(zero_mediate, i, j, k, m) -= stress(l, m); + muGrid::get(intermediate, i, j, k, m) -= stress(l, m); } } } temp << 8.46145176e-01, -8.69007382e-04, 0.00000000e+00, -2.85052074e-03, 8.26305692e-01, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 8.26350980e-01, -2.85052074e-03, 1.41564428e-03, 0.00000000e+00, 1.61379562e-03, 8.69007382e-04, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 5.58242059e-18, 0.00000000e+00, 0.00000000e+00, 9.90756677e-03, 0.00000000e+00, 0.00000000e+00, -9.90756677e-04, 1.01057181e-02, 9.90756677e-04, 0.00000000e+00, -8.69007382e-04, 1.21749295e-03, 0.00000000e+00, 1.41564428e-03, -1.11250597e-03, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 5.58242059e-18, 8.26305692e-01, -1.11250597e-03, 0.00000000e+00, 8.69007382e-04, 8.46541479e-01, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 8.26350980e-01, 0.00000000e+00, 0.00000000e+00, -9.90756677e-04, 0.00000000e+00, 0.00000000e+00, 1.01057181e-02, 9.90756677e-04, 9.90756677e-03, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 9.90756677e-03, 0.00000000e+00, 0.00000000e+00, -9.90756677e-04, 9.90756677e-03, -9.90756677e-04, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, -9.90756677e-04, 0.00000000e+00, 0.00000000e+00, 1.01057181e-02, -9.90756677e-04, 1.01057181e-02, 0.00000000e+00, 8.26350980e-01, 0.00000000e+00, 0.00000000e+00, 1.38777878e-17, 8.26350980e-01, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 8.46298039e-01; - Stiffness_t K4c_ref{testGoodies::from_numpy(temp)}; + Stiffness_t K4c_ref{muGrid::testGoodies::from_numpy(temp)}; error = (K4b_ref + zero_mediate - K4c_ref).norm() / zero_mediate.norm(); BOOST_CHECK_LT(error, hi_tol); // rel error on small difference between // inexacly read doubles if (not(error < hi_tol)) { std::cout << "decrement reference:\n" << K4c_ref - K4b_ref << std::endl; std::cout << "zero_mediate computed:\n" << zero_mediate << std::endl; } error = (K4c_ref - intermediate).norm() / K4c_ref.norm(); BOOST_CHECK_LT(error, hi_tol); if (not(error < hi_tol)) { std::cout << "stiffness reference:\n" << K4c_ref << std::endl; std::cout << "stiffness computed:\n" << intermediate << std::endl; std::cout << "zero-mediate computed:\n" << zero_mediate << std::endl; std::cout << "difference:\n" << K4c_ref - intermediate << std::endl; } } if (verbose) { std::cout << "Post Cycle" << std::endl; std::cout << "C₄ =" << std::endl << stiffness << std::endl; } } /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE_TEMPLATE(stress_strain_test, Fix, mats, Fix) {} BOOST_AUTO_TEST_SUITE_END(); } // namespace muSpectre diff --git a/tests/test_material_linear_elastic1.cc b/tests/test_material_linear_elastic1.cc index e588d4c..a47f911 100644 --- a/tests/test_material_linear_elastic1.cc +++ b/tests/test_material_linear_elastic1.cc @@ -1,235 +1,238 @@ /** * @file test_material_linear_elastic1.cc * * @author Till Junge * * @date 28 Nov 2017 * * @brief Tests for the large-strain, objective Hooke's law, implemented in * the convenient strategy (i.e., using MaterialMuSpectre), also used * to test parts of MaterialLinearElastic2 * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#include +#include "tests.hh" +#include "libmugrid/test_goodies.hh" + +#include +#include +#include +#include + +#include #include #include -#include "materials/material_linear_elastic1.hh" -#include "materials/material_linear_elastic2.hh" -#include "tests.hh" -#include "tests/test_goodies.hh" -#include "common/field_collection.hh" -#include "common/iterators.hh" namespace muSpectre { BOOST_AUTO_TEST_SUITE(material_linear_elastic_1); template struct MaterialFixture { using Mat = Mat_t; constexpr static Real lambda{2}, mu{1.5}; constexpr static Real young{mu * (3 * lambda + 2 * mu) / (lambda + mu)}; constexpr static Real poisson{lambda / (2 * (lambda + mu))}; MaterialFixture() : mat("Name", young, poisson) {} constexpr static Dim_t sdim{Mat_t::sdim()}; constexpr static Dim_t mdim{Mat_t::mdim()}; Mat_t mat; }; template struct has_internals { constexpr static bool value{false}; }; template struct has_internals> { constexpr static bool value{true}; }; using mat_list = boost::mpl::list>, MaterialFixture>, MaterialFixture>, MaterialFixture>, MaterialFixture>, MaterialFixture>>; BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_constructor, Fix, mat_list, Fix) { BOOST_CHECK_EQUAL("Name", Fix::mat.get_name()); auto & mat{Fix::mat}; auto sdim{Fix::sdim}; auto mdim{Fix::mdim}; BOOST_CHECK_EQUAL(sdim, mat.sdim()); BOOST_CHECK_EQUAL(mdim, mat.mdim()); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_add_pixel, Fix, mat_list, Fix) { auto & mat{Fix::mat}; constexpr Dim_t sdim{Fix::sdim}; - testGoodies::RandRange rng; + muGrid::testGoodies::RandRange rng; const Dim_t nb_pixel{7}, box_size{17}; using Ccoord = Ccoord_t; for (Dim_t i = 0; i < nb_pixel; ++i) { Ccoord c; for (Dim_t j = 0; j < sdim; ++j) { c[j] = rng.randval(0, box_size); } if (!has_internals::value) { BOOST_CHECK_NO_THROW(mat.add_pixel(c)); } } BOOST_CHECK_NO_THROW(mat.initialise()); } template struct MaterialFixtureFilled : public MaterialFixture { using Mat = Mat_t; constexpr static Dim_t box_size{3}; MaterialFixtureFilled() : MaterialFixture() { using Ccoord = Ccoord_t; - Ccoord cube{CcoordOps::get_cube(box_size)}; - CcoordOps::Pixels pixels(cube); + Ccoord cube{muGrid::CcoordOps::get_cube(box_size)}; + muGrid::CcoordOps::Pixels pixels(cube); for (auto pixel : pixels) { this->mat.add_pixel(pixel); } this->mat.initialise(); } }; using mat_fill = boost::mpl::list< MaterialFixtureFilled>, MaterialFixtureFilled>, MaterialFixtureFilled>>; BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_evaluate_law, Fix, mat_fill, Fix) { - constexpr auto cube{CcoordOps::get_cube(Fix::box_size)}; - constexpr auto loc{CcoordOps::get_cube(0)}; + constexpr auto cube{muGrid::CcoordOps::get_cube(Fix::box_size)}; + constexpr auto loc{muGrid::CcoordOps::get_cube(0)}; auto & mat{Fix::mat}; - using FC_t = GlobalFieldCollection; + using FC_t = muGrid::GlobalFieldCollection; FC_t globalfields; - auto & F{make_field( + auto & F{muGrid::make_field( "Transformation Gradient", globalfields)}; - auto & P1 = make_field( + auto & P1 = muGrid::make_field( "Nominal Stress1", globalfields); // to be computed alone - auto & P2 = make_field( + auto & P2 = muGrid::make_field( "Nominal Stress2", globalfields); // to be computed with tangent - auto & K = make_field( + auto & K = muGrid::make_field( "Tangent Moduli", globalfields); // to be computed with tangent - auto & Pr = make_field( + auto & Pr = muGrid::make_field( "Nominal Stress reference", globalfields); - auto & Kr = make_field( + auto & Kr = muGrid::make_field( "Tangent Moduli reference", globalfields); // to be computed with tangent globalfields.initialise(cube, loc); static_assert( std::is_same::value, "oh oh"); static_assert( std::is_same::value, "oh oh"); static_assert(std::is_same::value, "oh oh"); static_assert( std::is_same::value, "oh oh"); static_assert(std::is_same::value, "oh oh"); static_assert(std::is_same::value, "oh oh"); using traits = MaterialMuSpectre_traits; { // block to contain not-constant gradient map typename traits::StressMap_t grad_map( globalfields["Transformation Gradient"]); for (auto F_ : grad_map) { F_.setRandom(); } grad_map[0] = grad_map[0].Identity(); // identifiable gradients for debug grad_map[1] = 1.2 * grad_map[1].Identity(); // ditto } // compute stresses using material mat.compute_stresses(globalfields["Transformation Gradient"], globalfields["Nominal Stress1"], Formulation::finite_strain, SplitCell::no); // compute stresses and tangent moduli using material BOOST_CHECK_THROW( mat.compute_stresses_tangent(globalfields["Transformation Gradient"], globalfields["Nominal Stress2"], globalfields["Nominal Stress2"], Formulation::finite_strain), std::runtime_error); mat.compute_stresses_tangent(globalfields["Transformation Gradient"], globalfields["Nominal Stress2"], globalfields["Tangent Moduli"], Formulation::finite_strain); typename traits::StrainMap_t Fmap(globalfields["Transformation Gradient"]); typename traits::StressMap_t Pmap_ref( globalfields["Nominal Stress reference"]); typename traits::TangentMap_t Kmap_ref( globalfields["Tangent Moduli reference"]); for (auto tup : akantu::zip(Fmap, Pmap_ref, Kmap_ref)) { auto F_ = std::get<0>(tup); auto P_ = std::get<1>(tup); auto K_ = std::get<2>(tup); - std::tie(P_, K_) = testGoodies::objective_hooke_explicit( - Fix::lambda, Fix::mu, F_); + std::tie(P_, K_) = + muGrid::testGoodies::objective_hooke_explicit(Fix::lambda, + Fix::mu, F_); } typename traits::StressMap_t Pmap_1(globalfields["Nominal Stress1"]); for (auto tup : akantu::zip(Pmap_ref, Pmap_1)) { auto P_r = std::get<0>(tup); auto P_1 = std::get<1>(tup); Real error = (P_r - P_1).norm(); BOOST_CHECK_LT(error, tol); } typename traits::StressMap_t Pmap_2(globalfields["Nominal Stress2"]); typename traits::TangentMap_t Kmap(globalfields["Tangent Moduli"]); for (auto tup : akantu::zip(Pmap_ref, Pmap_2, Kmap_ref, Kmap)) { auto P_r = std::get<0>(tup); auto P = std::get<1>(tup); Real error = (P_r - P).norm(); BOOST_CHECK_LT(error, tol); auto K_r = std::get<2>(tup); auto K = std::get<3>(tup); error = (K_r - K).norm(); BOOST_CHECK_LT(error, tol); } } BOOST_AUTO_TEST_SUITE_END(); } // namespace muSpectre diff --git a/tests/test_material_linear_elastic2.cc b/tests/test_material_linear_elastic2.cc index 56222ab..a77057a 100644 --- a/tests/test_material_linear_elastic2.cc +++ b/tests/test_material_linear_elastic2.cc @@ -1,280 +1,282 @@ /** * @file test_material_linear_elastic2.cc * * @author Till Junge * * @date 04 Feb 2018 * * @brief Tests for the objective Hooke's law with eigenstrains, * (tests that do not require add_pixel are integrated into * `test_material_linear_elastic1.cc` * * @section LICENSE * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ +#include "tests.hh" +#include "libmugrid/test_goodies.hh" -#include +#include +#include +#include +#include #include #include -#include "materials/material_linear_elastic2.hh" -#include "tests.hh" -#include "tests/test_goodies.hh" -#include "common/field_collection.hh" -#include "common/iterators.hh" + namespace muSpectre { BOOST_AUTO_TEST_SUITE(material_linear_elastic_2); template struct MaterialFixture { using Mat = Mat_t; constexpr static Real lambda{2}, mu{1.5}; constexpr static Real young{mu * (3 * lambda + 2 * mu) / (lambda + mu)}; constexpr static Real poisson{lambda / (2 * (lambda + mu))}; MaterialFixture() : mat("Name", young, poisson) {} constexpr static Dim_t sdim{Mat_t::sdim()}; constexpr static Dim_t mdim{Mat_t::mdim()}; Mat_t mat; }; using mat_list = boost::mpl::list>, MaterialFixture>, MaterialFixture>>; BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_constructor, Fix, mat_list, Fix) { BOOST_CHECK_EQUAL("Name", Fix::mat.get_name()); auto & mat{Fix::mat}; auto sdim{Fix::sdim}; auto mdim{Fix::mdim}; BOOST_CHECK_EQUAL(sdim, mat.sdim()); BOOST_CHECK_EQUAL(mdim, mat.mdim()); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_add_pixel, Fix, mat_list, Fix) { auto & mat{Fix::mat}; constexpr Dim_t sdim{Fix::sdim}; - testGoodies::RandRange rng; + muGrid::testGoodies::RandRange rng; const Dim_t nb_pixel{7}, box_size{17}; using Ccoord = Ccoord_t; for (Dim_t i = 0; i < nb_pixel; ++i) { Ccoord c; for (Dim_t j = 0; j < sdim; ++j) { c[j] = rng.randval(0, box_size); } Eigen::Matrix Zero = Eigen::Matrix::Zero(); BOOST_CHECK_NO_THROW(mat.add_pixel(c, Zero)); } BOOST_CHECK_NO_THROW(mat.initialise()); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_eigenstrain_equivalence, Fix, mat_list, Fix) { auto & mat{Fix::mat}; const Dim_t nb_pixel{2}; - constexpr auto cube{CcoordOps::get_cube(nb_pixel)}; - constexpr auto loc{CcoordOps::get_cube(0)}; + constexpr auto cube{muGrid::CcoordOps::get_cube(nb_pixel)}; + constexpr auto loc{muGrid::CcoordOps::get_cube(0)}; using Mat_t = Eigen::Matrix; - using FC_t = GlobalFieldCollection; + using FC_t = muGrid::GlobalFieldCollection; FC_t globalfields; - auto & F_f{make_field( + auto & F_f{muGrid::make_field( "Transformation Gradient", globalfields)}; - auto & P1_f = make_field( + auto & P1_f = muGrid::make_field( "Nominal Stress1", globalfields); // to be computed alone - auto & K_f = make_field( + auto & K_f = muGrid::make_field( "Tangent Moduli", globalfields); // to be computed with tangent globalfields.initialise(cube, loc); Mat_t zero{Mat_t::Zero()}; Mat_t F{Mat_t::Random() / 100 + Mat_t::Identity()}; Mat_t strain{-.5 * (F + F.transpose()) - Mat_t::Identity()}; using Ccoord = Ccoord_t; Ccoord pix0{0}; Ccoord pix1{1}; mat.add_pixel(pix0, zero); mat.add_pixel(pix1, strain); mat.initialise(); F_f.get_map()[pix0] = -strain; F_f.get_map()[pix1] = zero; mat.compute_stresses_tangent(F_f, P1_f, K_f, Formulation::small_strain); Real error{(P1_f.get_map()[pix0] - P1_f.get_map()[pix1]).norm()}; Real tol{1e-12}; if (error >= tol) { std::cout << "error = " << error << " >= " << tol << " = tol" << std::endl; std::cout << "P(0) =" << std::endl << P1_f.get_map()[pix0] << std::endl; std::cout << "P(1) =" << std::endl << P1_f.get_map()[pix1] << std::endl; } BOOST_CHECK_LT(error, tol); } template struct MaterialFixtureFilled : public MaterialFixture { using Par = MaterialFixture; using Mat = Mat_t; constexpr static Dim_t box_size{3}; MaterialFixtureFilled() : MaterialFixture() { using Ccoord = Ccoord_t; - Ccoord cube{CcoordOps::get_cube(box_size)}; - CcoordOps::Pixels pixels(cube); + Ccoord cube{muGrid::CcoordOps::get_cube(box_size)}; + muGrid::CcoordOps::Pixels pixels(cube); for (auto pixel : pixels) { Eigen::Matrix Zero = Eigen::Matrix::Zero(); this->mat.add_pixel(pixel, Zero); } this->mat.initialise(); } }; using mat_fill = boost::mpl::list< MaterialFixtureFilled>, MaterialFixtureFilled>, MaterialFixtureFilled>>; BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_evaluate_law, Fix, mat_fill, Fix) { - constexpr auto cube{CcoordOps::get_cube(Fix::box_size)}; - constexpr auto loc{CcoordOps::get_cube(0)}; + constexpr auto cube{muGrid::CcoordOps::get_cube(Fix::box_size)}; + constexpr auto loc{muGrid::CcoordOps::get_cube(0)}; auto & mat{Fix::mat}; - using FC_t = GlobalFieldCollection; + using FC_t = muGrid::GlobalFieldCollection; FC_t globalfields; - auto & F{make_field( + auto & F{muGrid::make_field( "Transformation Gradient", globalfields)}; - auto & P1 = make_field( + auto & P1 = muGrid::make_field( "Nominal Stress1", globalfields); // to be computed alone - auto & P2 = make_field( + auto & P2 = muGrid::make_field( "Nominal Stress2", globalfields); // to be computed with tangent - auto & K = make_field( + auto & K = muGrid::make_field( "Tangent Moduli", globalfields); // to be computed with tangent - auto & Pr = make_field( + auto & Pr = muGrid::make_field( "Nominal Stress reference", globalfields); - auto & Kr = make_field( + auto & Kr = muGrid::make_field( "Tangent Moduli reference", globalfields); // to be computed with tangent globalfields.initialise(cube, loc); static_assert( std::is_same::value, "oh oh"); static_assert( std::is_same::value, "oh oh"); static_assert(std::is_same::value, "oh oh"); static_assert( std::is_same::value, "oh oh"); static_assert(std::is_same::value, "oh oh"); static_assert(std::is_same::value, "oh oh"); using traits = MaterialMuSpectre_traits; { // block to contain not-constant gradient map typename traits::StressMap_t grad_map( globalfields["Transformation Gradient"]); for (auto F_ : grad_map) { F_.setRandom(); } grad_map[0] = grad_map[0].Identity(); // identifiable gradients for debug grad_map[1] = 1.2 * grad_map[1].Identity(); // ditto } // compute stresses using material mat.compute_stresses(globalfields["Transformation Gradient"], globalfields["Nominal Stress1"], Formulation::finite_strain); // compute stresses and tangent moduli using material BOOST_CHECK_THROW( mat.compute_stresses_tangent(globalfields["Transformation Gradient"], globalfields["Nominal Stress2"], globalfields["Nominal Stress2"], Formulation::finite_strain), std::runtime_error); mat.compute_stresses_tangent(globalfields["Transformation Gradient"], globalfields["Nominal Stress2"], globalfields["Tangent Moduli"], Formulation::finite_strain); typename traits::StrainMap_t Fmap(globalfields["Transformation Gradient"]); typename traits::StressMap_t Pmap_ref( globalfields["Nominal Stress reference"]); typename traits::TangentMap_t Kmap_ref( globalfields["Tangent Moduli reference"]); for (auto tup : akantu::zip(Fmap, Pmap_ref, Kmap_ref)) { auto F_ = std::get<0>(tup); auto P_ = std::get<1>(tup); auto K_ = std::get<2>(tup); - std::tie(P_, K_) = testGoodies::objective_hooke_explicit( - Fix::lambda, Fix::mu, F_); + std::tie(P_, K_) = + muGrid::testGoodies::objective_hooke_explicit(Fix::lambda, + Fix::mu, F_); } typename traits::StressMap_t Pmap_1(globalfields["Nominal Stress1"]); for (auto tup : akantu::zip(Pmap_ref, Pmap_1)) { auto P_r = std::get<0>(tup); auto P_1 = std::get<1>(tup); Real error = (P_r - P_1).norm(); BOOST_CHECK_LT(error, tol); } typename traits::StressMap_t Pmap_2(globalfields["Nominal Stress2"]); typename traits::TangentMap_t Kmap(globalfields["Tangent Moduli"]); for (auto tup : akantu::zip(Pmap_ref, Pmap_2, Kmap_ref, Kmap)) { auto P_r = std::get<0>(tup); auto P = std::get<1>(tup); Real error = (P_r - P).norm(); if (error >= tol) { std::cout << "error = " << error << " >= " << tol << " = tol" << std::endl; std::cout << "P(0) =" << std::endl << P_r << std::endl; std::cout << "P(1) =" << std::endl << P << std::endl; } BOOST_CHECK_LT(error, tol); auto K_r = std::get<2>(tup); auto K = std::get<3>(tup); error = (K_r - K).norm(); BOOST_CHECK_LT(error, tol); } } BOOST_AUTO_TEST_SUITE_END(); } // namespace muSpectre diff --git a/tests/test_material_linear_elastic3.cc b/tests/test_material_linear_elastic3.cc index a25b0c8..6278737 100644 --- a/tests/test_material_linear_elastic3.cc +++ b/tests/test_material_linear_elastic3.cc @@ -1,92 +1,92 @@ /** * @file test_material_linear_elastic3.cc * * @author Richard Leute * * @date 21 Feb 2018 * * @brief description * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include #include "tests.hh" #include "materials/material_linear_elastic3.hh" #include "materials/materials_toolbox.hh" -#include "common/T4_map_proxy.hh" -#include "cmath" +#include +#include namespace muSpectre { BOOST_AUTO_TEST_SUITE(material_linear_elastic_3); template struct MaterialFixture { using Material_t = Mat_t; Material_t mat; MaterialFixture() : mat("name") { mat.add_pixel({0}, Young, Poisson); } Real Young{10}; Real Poisson{0.3}; }; using mat_list = boost::mpl::list>, MaterialFixture>, MaterialFixture>>; BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_constructor, Fix, mat_list, Fix){}; BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_response, Fix, mat_list, Fix) { constexpr Dim_t Dim{Fix::Material_t::Parent::Parent::mdim()}; Eigen::Matrix E; E.setZero(); E(0, 0) = 0.001; E(1, 0) = E(0, 1) = 0.005; - using Hooke = - MatTB::Hooke, T4Mat>; + using Hooke = MatTB::Hooke, + muGrid::T4Mat>; Real lambda = Hooke::compute_lambda(Fix::Young, Fix::Poisson); Real mu = Hooke::compute_mu(Fix::Young, Fix::Poisson); auto C = Hooke::compute_C(lambda, mu); - T4MatMap Cmap{C.data()}; + muGrid::T4MatMap Cmap{C.data()}; Eigen::Matrix stress = Fix::mat.evaluate_stress(E, Cmap); Real sigma00 = lambda * E(0, 0) + 2 * mu * E(0, 0); Real sigma01 = 2 * mu * E(0, 1); Real sigma11 = lambda * E(0, 0); BOOST_CHECK_LT(std::abs(stress(0, 0) - sigma00), tol); BOOST_CHECK_LT(std::abs(stress(0, 1) - sigma01), tol); BOOST_CHECK_LT(std::abs(stress(1, 0) - sigma01), tol); BOOST_CHECK_LT(std::abs(stress(1, 1) - sigma11), tol); if (Dim == threeD) { for (int i = 0; i < Dim - 1; ++i) { BOOST_CHECK_LT(std::abs(stress(2, i)), tol); BOOST_CHECK_LT(std::abs(stress(i, 2)), tol); } BOOST_CHECK_LT(std::abs(stress(2, 2) - sigma11), tol); } }; BOOST_AUTO_TEST_SUITE_END(); } // namespace muSpectre diff --git a/tests/test_material_linear_elastic4.cc b/tests/test_material_linear_elastic4.cc index 5677597..d048898 100644 --- a/tests/test_material_linear_elastic4.cc +++ b/tests/test_material_linear_elastic4.cc @@ -1,97 +1,97 @@ /** * @file test_material_linear_elastic4.cc * * @author Richard Leute * * @date 27 Mar 2018 * * @brief description * * Copyright © 2018 Richard Leute * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include #include "tests.hh" #include "materials/material_linear_elastic4.hh" #include "materials/materials_toolbox.hh" -#include "common/T4_map_proxy.hh" -#include "cmath" +#include +#include namespace muSpectre { BOOST_AUTO_TEST_SUITE(material_linear_elastic_4); template struct MaterialFixture { using Material_t = Mat_t; Material_t mat; MaterialFixture() : mat("name") { mat.add_pixel({0}, Youngs_modulus, Poisson_ratio); } Real Youngs_modulus{10}; Real Poisson_ratio{0.3}; }; using mat_list = boost::mpl::list>, MaterialFixture>, MaterialFixture>>; BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_constructor, Fix, mat_list, Fix){}; BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_response, Fix, mat_list, Fix) { constexpr Dim_t Dim{Fix::Material_t::Parent::Parent::mdim()}; Eigen::Matrix E; E.setZero(); E(0, 0) = 0.001; E(1, 0) = E(0, 1) = 0.005; - using Hooke = - MatTB::Hooke, T4Mat>; + using Hooke = MatTB::Hooke, + muGrid::T4Mat>; Real lambda = Hooke::compute_lambda(Fix::Youngs_modulus, Fix::Poisson_ratio); Real mu = Hooke::compute_mu(Fix::Youngs_modulus, Fix::Poisson_ratio); Eigen::Matrix stress = Fix::mat.evaluate_stress(E, lambda, mu); Real sigma00 = lambda * E(0, 0) + 2 * mu * E(0, 0); Real sigma01 = 2 * mu * E(0, 1); Real sigma11 = lambda * E(0, 0); BOOST_CHECK_LT(std::abs(stress(0, 0) - sigma00), tol); BOOST_CHECK_LT(std::abs(stress(0, 1) - sigma01), tol); BOOST_CHECK_LT(std::abs(stress(1, 0) - sigma01), tol); BOOST_CHECK_LT(std::abs(stress(1, 1) - sigma11), tol); if (Dim == threeD) { for (int i = 0; i < Dim - 1; ++i) { BOOST_CHECK_LT(std::abs(stress(2, i)), tol); BOOST_CHECK_LT(std::abs(stress(i, 2)), tol); } BOOST_CHECK_LT(std::abs(stress(2, 2) - sigma11), tol); } }; BOOST_AUTO_TEST_SUITE_END(); } // namespace muSpectre diff --git a/tests/test_material_linear_elastic_generic.cc b/tests/test_material_linear_elastic_generic.cc index 315ab1f..2a1b3dd 100644 --- a/tests/test_material_linear_elastic_generic.cc +++ b/tests/test_material_linear_elastic_generic.cc @@ -1,93 +1,93 @@ /** * @file test_material_linear_elastic_generic.cc * * @author Till Junge * * @date 21 Sep 2018 * * @brief test for the generic linear elastic law * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "tests.hh" #include "materials/material_linear_elastic_generic1.hh" #include "materials/materials_toolbox.hh" #include namespace muSpectre { BOOST_AUTO_TEST_SUITE(material_linear_elastic_generic); template struct MatFixture { using Mat_t = MaterialLinearElasticGeneric1; using T2_t = Eigen::Matrix; - using T4_t = T4Mat; + using T4_t = muGrid::T4Mat; using V_t = Eigen::Matrix; constexpr static Real lambda{2}, mu{1.5}; constexpr static Real get_lambda() { return lambda; } constexpr static Real get_mu() { return mu; } constexpr static Real young{mu * (3 * lambda + 2 * mu) / (lambda + mu)}; constexpr static Real poisson{lambda / (2 * (lambda + mu))}; using Hooke = MatTB::Hooke; MatFixture() : C_voigt{get_C_voigt()}, mat("material", this->C_voigt) {} static V_t get_C_voigt() { V_t C{}; C.setZero(); C.template topLeftCorner().setConstant(get_lambda()); C.template topLeftCorner() += 2 * get_mu() * T2_t::Identity(); constexpr Dim_t Rest{vsize(Dim) - Dim}; using Rest_t = Eigen::Matrix; C.template bottomRightCorner() += get_mu() * Rest_t::Identity(); return C; } V_t C_voigt; Mat_t mat; }; using mats = boost::mpl::list, MatFixture>; BOOST_FIXTURE_TEST_CASE_TEMPLATE(C_test, Fix, mats, Fix) { const auto ref_C{ Fix::Hooke::compute_C_T4(Fix::get_lambda(), Fix::get_mu())}; Real error{(ref_C - Fix::mat.get_C()).norm()}; BOOST_CHECK_LT(error, tol); if (not(error < tol)) { std::cout << "ref:" << std::endl << ref_C << std::endl; std::cout << "new:" << std::endl << Fix::mat.get_C() << std::endl; } } BOOST_AUTO_TEST_SUITE_END(); } // namespace muSpectre diff --git a/tests/test_materials_toolbox.cc b/tests/test_materials_toolbox.cc index 92fb176..b06f270 100644 --- a/tests/test_materials_toolbox.cc +++ b/tests/test_materials_toolbox.cc @@ -1,375 +1,372 @@ /** * @file test_materials_toolbox.cc * * @author Till Junge * * @date 05 Nov 2017 * * @brief Tests for the materials toolbox * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#include - #include "tests.hh" -#include "materials/materials_toolbox.hh" -#include "materials/stress_transformations_default_case.hh" -#include "materials/stress_transformations_PK1_impl.hh" -#include "materials/stress_transformations_PK2_impl.hh" -#include "materials/stress_transformations.hh" -#include "common/T4_map_proxy.hh" -#include "common/tensor_algebra.hh" -#include "tests/test_goodies.hh" +#include "libmugrid/test_goodies.hh" + +#include +#include +#include +#include +#include +#include #include +#include namespace muSpectre { BOOST_AUTO_TEST_SUITE(materials_toolbox) BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_strain_conversion, Fix, - testGoodies::dimlist, Fix) { + muGrid::testGoodies::dimlist, Fix) { constexpr Dim_t dim{Fix::dim}; using T2 = Eigen::Matrix; T2 F{(T2::Random() - .5 * T2::Ones()) / 20 + T2::Identity()}; // checking Green-Lagrange T2 Eref = .5 * (F.transpose() * F - T2::Identity()); T2 E_tb = MatTB::convert_strain( Eigen::Map>(F.data())); Real error = (Eref - E_tb).norm(); BOOST_CHECK_LT(error, tol); // checking Left Cauchy-Green Eref = F * F.transpose(); E_tb = MatTB::convert_strain(F); error = (Eref - E_tb).norm(); BOOST_CHECK_LT(error, tol); // checking Right Cauchy-Green Eref = F.transpose() * F; E_tb = MatTB::convert_strain(F); error = (Eref - E_tb).norm(); BOOST_CHECK_LT(error, tol); // checking Hencky (logarithmic) strain Eref = F.transpose() * F; Eigen::SelfAdjointEigenSolver EigSolv(Eref); Eref.setZero(); for (size_t i{0}; i < dim; ++i) { auto && vec = EigSolv.eigenvectors().col(i); auto && val = EigSolv.eigenvalues()(i); Eref += .5 * std::log(val) * vec * vec.transpose(); } E_tb = MatTB::convert_strain(F); error = (Eref - E_tb).norm(); BOOST_CHECK_LT(error, tol); auto F_tb = MatTB::convert_strain( F); error = (F - F_tb).norm(); BOOST_CHECK_LT(error, tol); } BOOST_FIXTURE_TEST_CASE_TEMPLATE(dumb_tensor_mult_test, Fix, - testGoodies::dimlist, Fix) { + muGrid::testGoodies::dimlist, Fix) { constexpr Dim_t dim{Fix::dim}; - using T4 = T4Mat; + using T4 = muGrid::T4Mat; T4 A, B, R1, R2; A.setRandom(); B.setRandom(); R1 = A * B; R2.setZero(); for (Dim_t i = 0; i < dim; ++i) { for (Dim_t j = 0; j < dim; ++j) { for (Dim_t a = 0; a < dim; ++a) { for (Dim_t b = 0; b < dim; ++b) { for (Dim_t k = 0; k < dim; ++k) { for (Dim_t l = 0; l < dim; ++l) { - get(R2, i, j, k, l) += get(A, i, j, a, b) * get(B, a, b, k, l); + muGrid::get(R2, i, j, k, l) += + muGrid::get(A, i, j, a, b) * muGrid::get(B, a, b, k, l); } } } } } } auto error{(R1 - R2).norm()}; BOOST_CHECK_LT(error, tol); } - BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_PK1_stress, Fix, testGoodies::dimlist, - Fix) { + BOOST_FIXTURE_TEST_CASE_TEMPLATE(test_PK1_stress, Fix, + muGrid::testGoodies::dimlist, Fix) { using Matrices::Tens2_t; using Matrices::Tens4_t; using Matrices::tensmult; constexpr Dim_t dim{Fix::dim}; using T2 = Eigen::Matrix; - using T4 = T4Mat; - testGoodies::RandRange rng; + using T4 = muGrid::T4Mat; + muGrid::testGoodies::RandRange rng; T2 F = T2::Identity() * 2; // F.setRandom(); T2 E_tb = MatTB::convert_strain( Eigen::Map>(F.data())); Real lambda = 3; // rng.randval(1, 2); Real mu = 4; // rng.randval(1,2); T4 J = Matrices::Itrac(); T2 I = Matrices::I2(); T4 I4 = Matrices::Isymm(); T4 C = lambda * J + 2 * mu * I4; T2 S = Matrices::tensmult(C, E_tb); T2 Sref = lambda * E_tb.trace() * I + 2 * mu * E_tb; auto error{(Sref - S).norm()}; BOOST_CHECK_LT(error, tol); T4 K = Matrices::outer_under(I, S) + Matrices::outer_under(F, I) * C * Matrices::outer_under(F.transpose(), I); // See Curnier, 2000, "Méthodes numériques en mécanique des solides", p 252 T4 Kref; Real Fkrkr = (F.array() * F.array()).sum(); T2 Fkmkn = F.transpose() * F; T2 Fisjs = F * F.transpose(); Kref.setZero(); for (Dim_t i = 0; i < dim; ++i) { for (Dim_t j = 0; j < dim; ++j) { for (Dim_t m = 0; m < dim; ++m) { for (Dim_t n = 0; n < dim; ++n) { - get(Kref, i, m, j, n) = + muGrid::get(Kref, i, m, j, n) = (lambda * ((Fkrkr - dim) / 2 * I(i, j) * I(m, n) + F(i, m) * F(j, n)) + mu * (I(i, j) * Fkmkn(m, n) + Fisjs(i, j) * I(m, n) - I(i, j) * I(m, n) + F(i, n) * F(j, m))); } } } } error = (Kref - K).norm(); BOOST_CHECK_LT(error, tol); T2 P = MatTB::PK1_stress( F, S); T2 Pref = F * S; error = (P - Pref).norm(); BOOST_CHECK_LT(error, tol); auto && stress_tgt = MatTB::PK1_stress( F, S, C); T2 P_t = std::move(std::get<0>(stress_tgt)); T4 K_t = std::move(std::get<1>(stress_tgt)); error = (P_t - Pref).norm(); BOOST_CHECK_LT(error, tol); error = (K_t - Kref).norm(); BOOST_CHECK_LT(error, tol); auto && stress_tgt_trivial = MatTB::PK1_stress(F, P, K); T2 P_u = std::move(std::get<0>(stress_tgt_trivial)); T4 K_u = std::move(std::get<1>(stress_tgt_trivial)); error = (P_u - Pref).norm(); BOOST_CHECK_LT(error, tol); error = (K_u - Kref).norm(); BOOST_CHECK_LT(error, tol); T2 P_g; T4 K_g; - std::tie(P_g, K_g) = testGoodies::objective_hooke_explicit(lambda, mu, F); + std::tie(P_g, K_g) = + muGrid::testGoodies::objective_hooke_explicit(lambda, mu, F); error = (P_g - Pref).norm(); BOOST_CHECK_LT(error, tol); error = (K_g - Kref).norm(); BOOST_CHECK_LT(error, tol); } BOOST_AUTO_TEST_CASE(elastic_modulus_conversions) { // define original input constexpr Real E{123.456}; constexpr Real nu{.3}; using MatTB::convert_elastic_modulus; // derived values constexpr Real K{ convert_elastic_modulus(E, nu)}; constexpr Real lambda{ convert_elastic_modulus(E, nu)}; constexpr Real mu{ convert_elastic_modulus(E, nu)}; // recover original inputs Real comp = convert_elastic_modulus(K, mu); Real err = E - comp; BOOST_CHECK_LT(err, tol); comp = convert_elastic_modulus(K, mu); err = nu - comp; BOOST_CHECK_LT(err, tol); comp = convert_elastic_modulus(lambda, mu); err = E - comp; BOOST_CHECK_LT(err, tol); // check inversion resistance Real compA = convert_elastic_modulus(K, mu); Real compB = convert_elastic_modulus(mu, K); BOOST_CHECK_EQUAL(compA, compB); // check trivial self-returning comp = convert_elastic_modulus(K, mu); BOOST_CHECK_EQUAL(K, comp); comp = convert_elastic_modulus(K, mu); BOOST_CHECK_EQUAL(mu, comp); // check alternative calculation of computed values comp = convert_elastic_modulus( K, mu); // alternative for "Shear" BOOST_CHECK_LE(std::abs((comp - lambda) / lambda), tol); } template struct FiniteDifferencesHolder { constexpr static FiniteDiff value{FinDiff}; }; using FinDiffList = boost::mpl::list, FiniteDifferencesHolder, FiniteDifferencesHolder>; - /* --------------------------------------------------- - ------------------- */ - // // BOOST_FIXTURE_TEST_CASE_TEMPLATE(numerical_tangent_test, Fix, - // FinDiffList, - // // Fix) { - // // constexpr Dim_t Dim{twoD}; - // // using T4_t = T4Mat; - // // using T2_t = Eigen::Matrix; - - // // bool verbose{false}; - - // // T4_t Q{}; - // // Q << 1., 2., 0., 0., 0., 1.66666667, 0., 0., 0., 0., - // // 2.33333333, 0., 0., 0.,0., 3.; - // // if (verbose) { - // // std::cout << Q << std::endl << std::endl; - // // } - - // // T2_t B{}; - // // B << 2., 3.33333333, 2.66666667, 4.; - // // if (verbose) { - // // std::cout << B << std::endl << std::endl; - // // } - - // // auto fun = [&](const T2_t & x) -> T2_t { - // // using cmap_t = Eigen::Map>; - // // using map_t = Eigen::Map>; - // // cmap_t x_vec{x.data()}; - // // T2_t ret_val{}; - // // map_t(ret_val.data()) = Q * x_vec + cmap_t(B.data()); - // // return ret_val; - // // }; - - // // T2_t temp_res = fun(T2_t::Ones()); - // // if (verbose) { - // // std::cout << temp_res << std::endl << std::endl; - // // } - - // // T4_t numerical_tangent{MatTB::compute_numerical_tangent( - // // fun, T2_t::Ones(), 1e-2)}; - - // // if (verbose) { - // // std::cout << numerical_tangent << std::endl << std::endl; - // // } - - // // Real error{(numerical_tangent - Q).norm() / Q.norm()}; - - // // BOOST_CHECK_LT(error, tol); - // // if (not(error < tol)) { - // // switch (Fix::value) { - // // case FiniteDiff::backward: { - // // std::cout << "backward difference: " << std::endl; - // // break; - // // } - // // case FiniteDiff::forward: { - // // std::cout << "forward difference: " << std::endl; - // // break; - // // } - // // case FiniteDiff::centred: { - // // std::cout << "centered difference: " << std::endl; - // // break; - // // } - // // } - - // // std::cout << "error = " << error << std::endl; - // // std::cout << "numerical tangent:\n" << numerical_tangent << - // std::endl; - // // std::cout << "reference:\n" << Q << std::endl; - // // } - // // } + /* ---------------------------------------------------------------------- */ + BOOST_FIXTURE_TEST_CASE_TEMPLATE(numerical_tangent_test, Fix, FinDiffList, + Fix) { + constexpr Dim_t Dim{twoD}; + using T4_t = muGrid::T4Mat; + using T2_t = Eigen::Matrix; + + bool verbose{false}; + + T4_t Q{}; + Q << 1., 2., 0., 0., 0., 1.66666667, 0., 0., 0., 0., 2.33333333, 0., 0., 0., + 0., 3.; + if (verbose) { + std::cout << Q << std::endl << std::endl; + } + + T2_t B{}; + B << 2., 3.33333333, 2.66666667, 4.; + if (verbose) { + std::cout << B << std::endl << std::endl; + } + + auto fun = [&](const T2_t & x) -> T2_t { + using cmap_t = Eigen::Map>; + using map_t = Eigen::Map>; + cmap_t x_vec{x.data()}; + T2_t ret_val{}; + map_t(ret_val.data()) = Q * x_vec + cmap_t(B.data()); + return ret_val; + }; + + T2_t temp_res = fun(T2_t::Ones()); + if (verbose) { + std::cout << temp_res << std::endl << std::endl; + } + + T4_t numerical_tangent{MatTB::compute_numerical_tangent( + fun, T2_t::Ones(), 1e-2)}; + + if (verbose) { + std::cout << numerical_tangent << std::endl << std::endl; + } + + Real error{(numerical_tangent - Q).norm() / Q.norm()}; + + BOOST_CHECK_LT(error, tol); + if (not(error < tol)) { + switch (Fix::value) { + case FiniteDiff::backward: { + std::cout << "backward difference: " << std::endl; + break; + } + case FiniteDiff::forward: { + std::cout << "forward difference: " << std::endl; + break; + } + case FiniteDiff::centred: { + std::cout << "centered difference: " << std::endl; + break; + } + } + + std::cout << "error = " << error << std::endl; + std::cout << "numerical tangent:\n" << numerical_tangent << std::endl; + std::cout << "reference:\n" << Q << std::endl; + } + } BOOST_AUTO_TEST_SUITE_END(); } // namespace muSpectre diff --git a/tests/test_projection.hh b/tests/test_projection.hh index 9888732..0020ff4 100644 --- a/tests/test_projection.hh +++ b/tests/test_projection.hh @@ -1,105 +1,106 @@ /** * @file test_projection.hh * * @author Till Junge * * @date 16 Jan 2018 * * @brief common declarations for testing both the small and finite strain * projection operators * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "tests.hh" -#include "fft/fftw_engine.hh" +#include #include #include +#include #ifndef TESTS_TEST_PROJECTION_HH_ #define TESTS_TEST_PROJECTION_HH_ namespace muSpectre { /* ---------------------------------------------------------------------- */ template struct Sizes {}; template <> struct Sizes { constexpr static Ccoord_t get_resolution() { return Ccoord_t{3, 5}; } constexpr static Rcoord_t get_lengths() { return Rcoord_t{3.4, 5.8}; } }; template <> struct Sizes { constexpr static Ccoord_t get_resolution() { return Ccoord_t{3, 5, 7}; } constexpr static Rcoord_t get_lengths() { return Rcoord_t{3.4, 5.8, 6.7}; } }; template struct Squares {}; template <> struct Squares { constexpr static Ccoord_t get_resolution() { return Ccoord_t{5, 5}; } constexpr static Rcoord_t get_lengths() { return Rcoord_t{5, 5}; } }; template <> struct Squares { constexpr static Ccoord_t get_resolution() { return Ccoord_t{7, 7, 7}; } constexpr static Rcoord_t get_lengths() { return Rcoord_t{7, 7, 7}; } }; /* ---------------------------------------------------------------------- */ template struct ProjectionFixture { - using Engine = FFTWEngine; + using Engine = muFFT::FFTWEngine; using Parent = Proj; constexpr static Dim_t sdim{DimS}; constexpr static Dim_t mdim{DimM}; ProjectionFixture() : projector(std::make_unique(SizeGiver::get_resolution(), mdim * mdim), SizeGiver::get_lengths()) {} Parent projector; }; } // namespace muSpectre #endif // TESTS_TEST_PROJECTION_HH_ diff --git a/tests/test_projection_finite.cc b/tests/test_projection_finite.cc index ade47fb..9109ea4 100644 --- a/tests/test_projection_finite.cc +++ b/tests/test_projection_finite.cc @@ -1,150 +1,151 @@ /** * @file test_projection_finite.cc * * @author Till Junge * * @date 07 Dec 2017 * * @brief tests for standard finite strain projection operator * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#include "fft/projection_finite_strain.hh" -#include "fft/projection_finite_strain_fast.hh" -#include "fft/fft_utils.hh" +#include "projection/projection_finite_strain.hh" +#include "projection/projection_finite_strain_fast.hh" +#include #include "test_projection.hh" #include namespace muSpectre { BOOST_AUTO_TEST_SUITE(projection_finite_strain); /* ---------------------------------------------------------------------- */ using fixlist = boost::mpl::list< ProjectionFixture, ProjectionFiniteStrain>, ProjectionFixture, ProjectionFiniteStrain>, ProjectionFixture, ProjectionFiniteStrain>, ProjectionFixture, ProjectionFiniteStrain>, ProjectionFixture, ProjectionFiniteStrainFast>, ProjectionFixture, ProjectionFiniteStrainFast>, ProjectionFixture, ProjectionFiniteStrainFast>, ProjectionFixture, ProjectionFiniteStrainFast>>; /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE_TEMPLATE(constructor_test, fix, fixlist, fix) { - BOOST_CHECK_NO_THROW(fix::projector.initialise(FFT_PlanFlags::estimate)); + BOOST_CHECK_NO_THROW( + fix::projector.initialise(muFFT::FFT_PlanFlags::estimate)); } /* ---------------------------------------------------------------------- */ BOOST_AUTO_TEST_CASE(even_grid_test) { - using Engine = FFTWEngine; + using Engine = muFFT::FFTWEngine; using proj = ProjectionFiniteStrainFast; auto engine = std::make_unique(Ccoord_t{2, 2}, 2 * 2); BOOST_CHECK_THROW(proj(std::move(engine), Rcoord_t{4.3, 4.3}), std::runtime_error); } /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE_TEMPLATE(Gradient_preservation_test, fix, fixlist, fix) { // create a gradient field with a zero mean gradient and verify // that the projection preserves it constexpr Dim_t dim{fix::sdim}, sdim{fix::sdim}, mdim{fix::mdim}; static_assert( dim == fix::mdim, "These tests assume that the material and spatial dimension are " "identical"); - using Fields = GlobalFieldCollection; - using FieldT = TensorField; - using FieldMap = MatrixFieldMap; + using Fields = muGrid::GlobalFieldCollection; + using FieldT = muGrid::TensorField; + using FieldMap = muGrid::MatrixFieldMap; using Vector = Eigen::Matrix; Fields fields{}; - FieldT & f_grad{make_field("gradient", fields)}; - FieldT & f_var{make_field("working field", fields)}; + FieldT & f_grad{muGrid::make_field("gradient", fields)}; + FieldT & f_var{muGrid::make_field("working field", fields)}; FieldMap grad(f_grad); FieldMap var(f_var); fields.initialise(fix::projector.get_subdomain_resolutions(), fix::projector.get_subdomain_locations()); - FFT_freqs freqs{fix::projector.get_domain_resolutions(), - fix::projector.get_domain_lengths()}; + muFFT::FFT_freqs freqs{fix::projector.get_domain_resolutions(), + fix::projector.get_domain_lengths()}; Vector k; for (Dim_t i = 0; i < dim; ++i) { // the wave vector has to be such that it leads to an integer // number of periods in each length of the domain - k(i) = (i + 1) * 2 * pi / fix::projector.get_domain_lengths()[i]; + k(i) = (i + 1) * 2 * muGrid::pi / fix::projector.get_domain_lengths()[i]; } + using muGrid::operator/; for (auto && tup : akantu::zip(fields, grad, var)) { auto & ccoord = std::get<0>(tup); auto & g = std::get<1>(tup); auto & v = std::get<2>(tup); - Vector vec = CcoordOps::get_vector( + Vector vec = muGrid::CcoordOps::get_vector( ccoord, fix::projector.get_domain_lengths() / fix::projector.get_domain_resolutions()); g.row(0) = k.transpose() * cos(k.dot(vec)); v.row(0) = g.row(0); } - fix::projector.initialise(FFT_PlanFlags::estimate); + fix::projector.initialise(muFFT::FFT_PlanFlags::estimate); fix::projector.apply_projection(f_var); for (auto && tup : akantu::zip(fields, grad, var)) { auto & ccoord = std::get<0>(tup); auto & g = std::get<1>(tup); auto & v = std::get<2>(tup); - Vector vec = CcoordOps::get_vector( + Vector vec = muGrid::CcoordOps::get_vector( ccoord, fix::projector.get_domain_lengths() / fix::projector.get_domain_resolutions()); Real error = (g - v).norm(); BOOST_CHECK_LT(error, tol); if (error >= tol) { std::cout << std::endl << "grad_ref :" << std::endl << g << std::endl; std::cout << std::endl << "grad_proj :" << std::endl << v << std::endl; - std::cout << std::endl - << "ccoord :" << std::endl - << ccoord << std::endl; + std::cout << std::endl << "ccoord :" << std::endl; + muGrid::operator<<(std::cout, ccoord) << std::endl; std::cout << std::endl << "vector :" << std::endl << vec.transpose() << std::endl; } } } BOOST_AUTO_TEST_SUITE_END(); } // namespace muSpectre diff --git a/tests/test_projection_small.cc b/tests/test_projection_small.cc index 29787f5..0e57519 100644 --- a/tests/test_projection_small.cc +++ b/tests/test_projection_small.cc @@ -1,143 +1,145 @@ /** * @file test_projection_small.cc * * @author Till Junge * * @date 16 Jan 2018 * * @brief tests for standard small strain projection operator * * Copyright © 2018 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#include "fft/projection_small_strain.hh" #include "test_projection.hh" -#include "fft/fft_utils.hh" +#include "projection/projection_small_strain.hh" +#include #include namespace muSpectre { BOOST_AUTO_TEST_SUITE(projection_small_strain); using fixlist = boost::mpl::list< ProjectionFixture, ProjectionSmallStrain>, ProjectionFixture, ProjectionSmallStrain>, ProjectionFixture, ProjectionSmallStrain>, ProjectionFixture, ProjectionSmallStrain>>; /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE_TEMPLATE(constructor_test, fix, fixlist, fix) { - BOOST_CHECK_NO_THROW(fix::projector.initialise(FFT_PlanFlags::estimate)); + BOOST_CHECK_NO_THROW( + fix::projector.initialise(muFFT::FFT_PlanFlags::estimate)); } /* ---------------------------------------------------------------------- */ BOOST_FIXTURE_TEST_CASE_TEMPLATE(Gradient_preservation_test, fix, fixlist, fix) { // create a gradient field with a zero mean gradient and verify // that the projection preserves it constexpr Dim_t dim{fix::sdim}, sdim{fix::sdim}, mdim{fix::mdim}; static_assert( dim == fix::mdim, "These tests assume that the material and spatial dimension are " "identical"); - using Fields = GlobalFieldCollection; - using FieldT = TensorField; - using FieldMap = MatrixFieldMap; + using Fields = muGrid::GlobalFieldCollection; + using FieldT = muGrid::TensorField; + using FieldMap = muGrid::MatrixFieldMap; using Vector = Eigen::Matrix; Fields fields{}; - FieldT & f_grad{make_field("strain", fields)}; - FieldT & f_var{make_field("working field", fields)}; + FieldT & f_grad{muGrid::make_field("strain", fields)}; + FieldT & f_var{muGrid::make_field("working field", fields)}; FieldMap grad(f_grad); FieldMap var(f_var); fields.initialise(fix::projector.get_subdomain_resolutions(), fix::projector.get_subdomain_locations()); - FFT_freqs freqs{fix::projector.get_domain_resolutions(), - fix::projector.get_domain_lengths()}; + muFFT::FFT_freqs freqs{fix::projector.get_domain_resolutions(), + fix::projector.get_domain_lengths()}; Vector k; for (Dim_t i = 0; i < dim; ++i) { // the wave vector has to be such that it leads to an integer // number of periods in each length of the domain - k(i) = (i + 1) * 2 * pi / fix::projector.get_domain_lengths()[i]; + k(i) = (i + 1) * 2 * muGrid::pi / fix::projector.get_domain_lengths()[i]; } + using muGrid::operator/; for (auto && tup : akantu::zip(fields, grad, var)) { auto & ccoord = std::get<0>(tup); auto & g = std::get<1>(tup); auto & v = std::get<2>(tup); - Vector vec = CcoordOps::get_vector( + Vector vec = muGrid::CcoordOps::get_vector( ccoord, fix::projector.get_domain_lengths() / fix::projector.get_domain_resolutions()); g.row(0) << k.transpose() * cos(k.dot(vec)); // We need to add I to the term, because this field has a net // zero gradient, which leads to a net -I strain g = 0.5 * ((g - g.Identity()).transpose() + (g - g.Identity())).eval() + g.Identity(); v = g; } - fix::projector.initialise(FFT_PlanFlags::estimate); + fix::projector.initialise(muFFT::FFT_PlanFlags::estimate); fix::projector.apply_projection(f_var); + using muGrid::operator/; constexpr bool verbose{false}; for (auto && tup : akantu::zip(fields, grad, var)) { auto & ccoord = std::get<0>(tup); auto & g = std::get<1>(tup); auto & v = std::get<2>(tup); - Vector vec = CcoordOps::get_vector( + Vector vec = muGrid::CcoordOps::get_vector( ccoord, fix::projector.get_domain_lengths() / fix::projector.get_domain_resolutions()); Real error = (g - v).norm(); BOOST_CHECK_LT(error, tol); if ((error >= tol) || verbose) { std::cout << std::endl << "grad_ref :" << std::endl << g << std::endl; std::cout << std::endl << "grad_proj :" << std::endl << v << std::endl; - std::cout << std::endl - << "ccoord :" << std::endl - << ccoord << std::endl; + std::cout << std::endl << "ccoord :" << std::endl; + muGrid::operator<<(std::cout, ccoord) << std::endl; std::cout << std::endl << "vector :" << std::endl << vec.transpose() << std::endl; std::cout << "means:" << std::endl << ":" << std::endl << grad.mean() << std::endl << ":" << std::endl << var.mean(); } } } BOOST_AUTO_TEST_SUITE_END(); } // namespace muSpectre diff --git a/tests/test_solver_newton_cg.cc b/tests/test_solver_newton_cg.cc index 394d728..fca2a6a 100644 --- a/tests/test_solver_newton_cg.cc +++ b/tests/test_solver_newton_cg.cc @@ -1,483 +1,483 @@ /** * @file test_solver_newton_cg.cc * * @author Till Junge * * @date 20 Dec 2017 * * @brief Tests for the standard Newton-Raphson + Conjugate Gradient solver * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ #include "tests.hh" #include "solver/solvers.hh" #include "solver/solver_cg.hh" #include "solver/solver_eigen.hh" #include "solver/deprecated_solvers.hh" #include "solver/deprecated_solver_cg.hh" #include "solver/deprecated_solver_cg_eigen.hh" -#include "fft/fftw_engine.hh" -#include "fft/projection_finite_strain_fast.hh" +#include "projection/projection_finite_strain_fast.hh" #include "materials/material_linear_elastic1.hh" -#include "materials/material_orthotropic.hh" -#include "common/iterators.hh" -#include "common/ccoord_operations.hh" -#include "common/common.hh" #include "cell/cell_factory.hh" +#include +#include +#include + #include namespace muSpectre { BOOST_AUTO_TEST_SUITE(newton_cg_tests); BOOST_AUTO_TEST_CASE(manual_construction_test) { // constexpr Dim_t dim{twoD}; constexpr Dim_t dim{threeD}; // constexpr Ccoord_t resolutions{3, 3}; // constexpr Rcoord_t lengths{2.3, 2.7}; constexpr Ccoord_t resolutions{5, 5, 5}; constexpr Rcoord_t lengths{5, 5, 5}; - auto fft_ptr{std::make_unique>(resolutions, ipow(dim, 2))}; + auto fft_ptr{std::make_unique>( + resolutions, muGrid::ipow(dim, 2))}; auto proj_ptr{std::make_unique>( std::move(fft_ptr), lengths)}; CellBase sys(std::move(proj_ptr)); using Mat_t = MaterialLinearElastic1; // const Real Young{210e9}, Poisson{.33}; const Real Young{1.0030648180242636}, Poisson{0.29930675909878679}; // const Real lambda{Young*Poisson/((1+Poisson)*(1-2*Poisson))}; // const Real mu{Young/(2*(1+Poisson))}; auto & Material_hard = Mat_t::make(sys, "hard", 10 * Young, Poisson); auto & Material_soft = Mat_t::make(sys, "soft", Young, Poisson); for (auto && tup : akantu::enumerate(sys)) { auto && pixel = std::get<1>(tup); if (std::get<0>(tup) == 0) { Material_hard.add_pixel(pixel); } else { Material_soft.add_pixel(pixel); } } sys.initialise(); Grad_t delF0; delF0 << 0, 1., 0, 0, 0, 0, 0, 0, 0; constexpr Real cg_tol{1e-8}, newton_tol{1e-5}; - constexpr Uint maxiter{CcoordOps::get_size(resolutions) * - ipow(dim, secondOrder) * 10}; + constexpr Uint maxiter{muGrid::CcoordOps::get_size(resolutions) * + muGrid::ipow(dim, secondOrder) * 10}; constexpr bool verbose{false}; GradIncrements grads; grads.push_back(delF0); DeprecatedSolverCG cg{sys, cg_tol, maxiter, static_cast(verbose)}; Eigen::ArrayXXd res1{ deprecated_de_geus(sys, grads, cg, newton_tol, verbose)[0].grad}; DeprecatedSolverCG cg2{sys, cg_tol, maxiter, static_cast(verbose)}; Eigen::ArrayXXd res2{ deprecated_newton_cg(sys, grads, cg2, newton_tol, verbose)[0].grad}; BOOST_CHECK_LE(abs(res1 - res2).mean(), cg_tol); } BOOST_AUTO_TEST_CASE(small_strain_patch_test) { constexpr Dim_t dim{twoD}; using Ccoord = Ccoord_t; using Rcoord = Rcoord_t; - constexpr Ccoord resolutions{CcoordOps::get_cube(3)}; - constexpr Rcoord lengths{CcoordOps::get_cube(1.)}; + constexpr Ccoord resolutions{muGrid::CcoordOps::get_cube(3)}; + constexpr Rcoord lengths{muGrid::CcoordOps::get_cube(1.)}; constexpr Formulation form{Formulation::small_strain}; // number of layers in the hard material constexpr Uint nb_lays{1}; constexpr Real contrast{2}; static_assert(nb_lays < resolutions[0], "the number or layers in the hard material must be smaller " "than the total number of layers in dimension 0"); auto sys{make_cell(resolutions, lengths, form)}; using Mat_t = MaterialLinearElastic1; constexpr Real Young{2.}, Poisson{.33}; auto material_hard{ std::make_unique("hard", contrast * Young, Poisson)}; auto material_soft{std::make_unique("soft", Young, Poisson)}; for (const auto & pixel : sys) { if (pixel[0] < Dim_t(nb_lays)) { material_hard->add_pixel(pixel); } else { material_soft->add_pixel(pixel); } } sys.add_material(std::move(material_hard)); sys.add_material(std::move(material_soft)); sys.initialise(); Grad_t delEps0{Grad_t::Zero()}; constexpr Real eps0 = 1.; // delEps0(0, 1) = delEps0(1, 0) = eps0; delEps0(0, 0) = eps0; constexpr Real cg_tol{1e-8}, newton_tol{1e-5}, equil_tol{1e-10}; constexpr Uint maxiter{dim * 10}; constexpr Dim_t verbose{0}; DeprecatedSolverCGEigen cg{sys, cg_tol, maxiter, static_cast(verbose)}; auto result = deprecated_newton_cg( sys, delEps0, cg, newton_tol, // de_geus(sys, delEps0, cg, newton_tol, equil_tol, verbose); if (verbose) { std::cout << "result:" << std::endl << result.grad << std::endl; std::cout << "mean strain = " << std::endl << sys.get_strain().get_map().mean() << std::endl; } /** * verification of resultant strains: subscript ₕ for hard and ₛ * for soft, Nₕ is nb_lays and Nₜₒₜ is resolutions, k is contrast * * Δl = εl = Δlₕ + Δlₛ = εₕlₕ+εₛlₛ * => ε = εₕ Nₕ/Nₜₒₜ + εₛ (Nₜₒₜ-Nₕ)/Nₜₒₜ * * σ is constant across all layers * σₕ = σₛ * => Eₕ εₕ = Eₛ εₛ * => εₕ = 1/k εₛ * => ε / (1/k Nₕ/Nₜₒₜ + (Nₜₒₜ-Nₕ)/Nₜₒₜ) = εₛ */ constexpr Real factor{1 / contrast * Real(nb_lays) / resolutions[0] + 1. - nb_lays / Real(resolutions[0])}; constexpr Real eps_soft{eps0 / factor}; constexpr Real eps_hard{eps_soft / contrast}; if (verbose) { std::cout << "εₕ = " << eps_hard << ", εₛ = " << eps_soft << std::endl; std::cout << "ε = εₕ Nₕ/Nₜₒₜ + εₛ (Nₜₒₜ-Nₕ)/Nₜₒₜ" << std::endl; } Grad_t Eps_hard; Eps_hard << eps_hard, 0, 0, 0; Grad_t Eps_soft; Eps_soft << eps_soft, 0, 0, 0; // verify uniaxial tension patch test for (const auto & pixel : sys) { if (pixel[0] < Dim_t(nb_lays)) { BOOST_CHECK_LE((Eps_hard - sys.get_strain().get_map()[pixel]).norm(), tol); } else { BOOST_CHECK_LE((Eps_soft - sys.get_strain().get_map()[pixel]).norm(), tol); } } delEps0 = Grad_t::Zero(); delEps0(0, 1) = delEps0(1, 0) = eps0; DeprecatedSolverCG cg2{sys, cg_tol, maxiter, static_cast(verbose)}; result = deprecated_newton_cg(sys, delEps0, cg2, newton_tol, equil_tol, verbose); Eps_hard << 0, eps_hard, eps_hard, 0; Eps_soft << 0, eps_soft, eps_soft, 0; // verify pure shear patch test for (const auto & pixel : sys) { if (pixel[0] < Dim_t(nb_lays)) { BOOST_CHECK_LE((Eps_hard - sys.get_strain().get_map()[pixel]).norm(), tol); } else { BOOST_CHECK_LE((Eps_soft - sys.get_strain().get_map()[pixel]).norm(), tol); } } } template struct SolverFixture { using type = SolverType; }; using SolverList = boost::mpl::list< SolverFixture, SolverFixture, SolverFixture, SolverFixture, SolverFixture, SolverFixture>; BOOST_FIXTURE_TEST_CASE_TEMPLATE(small_strain_patch_dynamic_solver, Fix, SolverList, Fix) { // BOOST_AUTO_TEST_CASE(small_strain_patch_test_dynamic_solver) { constexpr Dim_t dim{twoD}; using Ccoord = Ccoord_t; using Rcoord = Rcoord_t; - constexpr Ccoord resolutions{CcoordOps::get_cube(3)}; - constexpr Rcoord lengths{CcoordOps::get_cube(1.)}; + constexpr Ccoord resolutions{muGrid::CcoordOps::get_cube(3)}; + constexpr Rcoord lengths{muGrid::CcoordOps::get_cube(1.)}; constexpr Formulation form{Formulation::small_strain}; // number of layers in the hard material constexpr Uint nb_lays{1}; constexpr Real contrast{2}; static_assert(nb_lays < resolutions[0], "the number or layers in the hard material must be smaller " "than the total number of layers in dimension 0"); auto sys{make_cell(resolutions, lengths, form)}; using Mat_t = MaterialLinearElastic1; constexpr Real Young{2.}, Poisson{.33}; auto material_hard{ std::make_unique("hard", contrast * Young, Poisson)}; auto material_soft{std::make_unique("soft", Young, Poisson)}; for (const auto & pixel : sys) { if (pixel[0] < Dim_t(nb_lays)) { material_hard->add_pixel(pixel); } else { material_soft->add_pixel(pixel); } } sys.add_material(std::move(material_hard)); sys.add_material(std::move(material_soft)); sys.initialise(); Grad_t delEps0{Grad_t::Zero()}; constexpr Real eps0 = 1.; // delEps0(0, 1) = delEps0(1, 0) = eps0; delEps0(0, 0) = eps0; constexpr Real cg_tol{1e-8}, newton_tol{1e-5}, equil_tol{1e-10}; constexpr Uint maxiter{dim * 10}; constexpr Dim_t verbose{0}; using Solver_t = typename Fix::type; Solver_t cg{sys, cg_tol, maxiter, static_cast(verbose)}; auto result = newton_cg(sys, delEps0, cg, newton_tol, equil_tol, verbose); if (verbose) { std::cout << "result:" << std::endl << result.grad << std::endl; std::cout << "mean strain = " << std::endl << sys.get_strain().get_map().mean() << std::endl; } /** * verification of resultant strains: subscript ₕ for hard and ₛ * for soft, Nₕ is nb_lays and Nₜₒₜ is resolutions, k is contrast * * Δl = εl = Δlₕ + Δlₛ = εₕlₕ+εₛlₛ * => ε = εₕ Nₕ/Nₜₒₜ + εₛ (Nₜₒₜ-Nₕ)/Nₜₒₜ * * σ is constant across all layers * σₕ = σₛ * => Eₕ εₕ = Eₛ εₛ * => εₕ = 1/k εₛ * => ε / (1/k Nₕ/Nₜₒₜ + (Nₜₒₜ-Nₕ)/Nₜₒₜ) = εₛ */ constexpr Real factor{1 / contrast * Real(nb_lays) / resolutions[0] + 1. - nb_lays / Real(resolutions[0])}; constexpr Real eps_soft{eps0 / factor}; constexpr Real eps_hard{eps_soft / contrast}; if (verbose) { std::cout << "εₕ = " << eps_hard << ", εₛ = " << eps_soft << std::endl; std::cout << "ε = εₕ Nₕ/Nₜₒₜ + εₛ (Nₜₒₜ-Nₕ)/Nₜₒₜ" << std::endl; } Grad_t Eps_hard; Eps_hard << eps_hard, 0, 0, 0; Grad_t Eps_soft; Eps_soft << eps_soft, 0, 0, 0; // verify uniaxial tension patch test for (const auto & pixel : sys) { if (pixel[0] < Dim_t(nb_lays)) { BOOST_CHECK_LE((Eps_hard - sys.get_strain().get_map()[pixel]).norm(), tol); } else { BOOST_CHECK_LE((Eps_soft - sys.get_strain().get_map()[pixel]).norm(), tol); } } delEps0 = Grad_t::Zero(); delEps0(0, 1) = delEps0(1, 0) = eps0; Solver_t cg2{sys, cg_tol, maxiter, static_cast(verbose)}; result = de_geus(sys, delEps0, cg2, newton_tol, equil_tol, verbose); Eps_hard << 0, eps_hard, eps_hard, 0; Eps_soft << 0, eps_soft, eps_soft, 0; // verify pure shear patch test for (const auto & pixel : sys) { if (pixel[0] < Dim_t(nb_lays)) { BOOST_CHECK_LE((Eps_hard - sys.get_strain().get_map()[pixel]).norm(), tol); } else { BOOST_CHECK_LE((Eps_soft - sys.get_strain().get_map()[pixel]).norm(), tol); } } } BOOST_AUTO_TEST_CASE(small_strain_patch_test_new_interface_manual) { constexpr Dim_t dim{twoD}; using Ccoord = Ccoord_t; using Rcoord = Rcoord_t; - constexpr Ccoord resolutions{CcoordOps::get_cube(3)}; - constexpr Rcoord lengths{CcoordOps::get_cube(1.)}; + constexpr Ccoord resolutions{muGrid::CcoordOps::get_cube(3)}; + constexpr Rcoord lengths{muGrid::CcoordOps::get_cube(1.)}; constexpr Formulation form{Formulation::small_strain}; // number of layers in the hard material constexpr Uint nb_lays{1}; constexpr Real contrast{2}; static_assert(nb_lays < resolutions[0], "the number or layers in the hard material must be smaller " "than the total number of layers in dimension 0"); auto sys{make_cell(resolutions, lengths, form)}; using Mat_t = MaterialLinearElastic1; constexpr Real Young{2.}, Poisson{.33}; auto material_hard{ std::make_unique("hard", contrast * Young, Poisson)}; auto material_soft{std::make_unique("soft", Young, Poisson)}; for (const auto & pixel : sys) { if (pixel[0] < Dim_t(nb_lays)) { material_hard->add_pixel(pixel); } else { material_soft->add_pixel(pixel); } } sys.add_material(std::move(material_hard)); sys.add_material(std::move(material_soft)); Grad_t delEps0{Grad_t::Zero()}; constexpr Real eps0 = 1.; // delEps0(0, 1) = delEps0(1, 0) = eps0; delEps0(0, 0) = eps0; constexpr Real cg_tol{1e-8}; constexpr Uint maxiter{dim * 10}; constexpr Dim_t verbose{0}; DeprecatedSolverCGEigen cg{sys, cg_tol, maxiter, static_cast(verbose)}; auto F = sys.get_strain_vector(); F.setZero(); sys.evaluate_stress_tangent(); Eigen::VectorXd DelF(sys.get_nb_dof()); - using RMap_t = RawFieldMap>>; + using RMap_t = muGrid::RawFieldMap>>; for (auto tmp : RMap_t(DelF)) { tmp = delEps0; } Eigen::VectorXd rhs = -sys.evaluate_projected_directional_stiffness(DelF); F += DelF; DelF.setZero(); cg.initialise(); Eigen::Map(DelF.data(), DelF.size()) = cg.solve(rhs, DelF); F += DelF; if (verbose) { std::cout << "result:" << std::endl << F << std::endl; std::cout << "mean strain = " << std::endl << sys.get_strain().get_map().mean() << std::endl; } /** * verification of resultant strains: subscript ₕ for hard and ₛ * for soft, Nₕ is nb_lays and Nₜₒₜ is resolutions, k is contrast * * Δl = εl = Δlₕ + Δlₛ = εₕlₕ+εₛlₛ * => ε = εₕ Nₕ/Nₜₒₜ + εₛ (Nₜₒₜ-Nₕ)/Nₜₒₜ * * σ is constant across all layers * σₕ = σₛ * => Eₕ εₕ = Eₛ εₛ * => εₕ = 1/k εₛ * => ε / (1/k Nₕ/Nₜₒₜ + (Nₜₒₜ-Nₕ)/Nₜₒₜ) = εₛ */ constexpr Real factor{1 / contrast * Real(nb_lays) / resolutions[0] + 1. - nb_lays / Real(resolutions[0])}; constexpr Real eps_soft{eps0 / factor}; constexpr Real eps_hard{eps_soft / contrast}; if (verbose) { std::cout << "εₕ = " << eps_hard << ", εₛ = " << eps_soft << std::endl; std::cout << "ε = εₕ Nₕ/Nₜₒₜ + εₛ (Nₜₒₜ-Nₕ)/Nₜₒₜ" << std::endl; } Grad_t Eps_hard; Eps_hard << eps_hard, 0, 0, 0; Grad_t Eps_soft; Eps_soft << eps_soft, 0, 0, 0; // verify uniaxial tension patch test for (const auto & pixel : sys) { if (pixel[0] < Dim_t(nb_lays)) { BOOST_CHECK_LE((Eps_hard - sys.get_strain().get_map()[pixel]).norm(), tol); } else { BOOST_CHECK_LE((Eps_soft - sys.get_strain().get_map()[pixel]).norm(), tol); } } delEps0.setZero(); delEps0(0, 1) = delEps0(1, 0) = eps0; DeprecatedSolverCG cg2{sys, cg_tol, maxiter, static_cast(verbose)}; F.setZero(); sys.evaluate_stress_tangent(); for (auto tmp : RMap_t(DelF)) { tmp = delEps0; } rhs = -sys.evaluate_projected_directional_stiffness(DelF); F += DelF; DelF.setZero(); cg2.initialise(); DelF = cg2.solve(rhs, DelF); F += DelF; Eps_hard << 0, eps_hard, eps_hard, 0; Eps_soft << 0, eps_soft, eps_soft, 0; // verify pure shear patch test for (const auto & pixel : sys) { if (pixel[0] < Dim_t(nb_lays)) { BOOST_CHECK_LE((Eps_hard - sys.get_strain().get_map()[pixel]).norm(), tol); } else { BOOST_CHECK_LE((Eps_soft - sys.get_strain().get_map()[pixel]).norm(), tol); } } } BOOST_AUTO_TEST_SUITE_END(); } // namespace muSpectre diff --git a/tests/tests.hh b/tests/tests.hh index 4cb70de..836e293 100644 --- a/tests/tests.hh +++ b/tests/tests.hh @@ -1,49 +1,49 @@ /** * @file tests.hh * * @author Till Junge * * @date 10 May 2017 * * @brief common defs for tests * * Copyright © 2017 Till Junge * * µSpectre is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3, or (at * your option) any later version. * * µSpectre is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with µSpectre; see the file COPYING. If not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * * Boston, MA 02111-1307, USA. * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining it * with proprietary FFT implementations or numerical libraries, containing parts * covered by the terms of those libraries' licenses, the licensors of this * Program grant you additional permission to convey the resulting work. */ -#include "common/common.hh" +#include "libmugrid/tests.hh" + +#include #include #include #ifndef TESTS_TESTS_HH_ #define TESTS_TESTS_HH_ namespace muSpectre { - - constexpr Real tol = 1e-14 * 100; // it's in percent + using muGrid::tol; constexpr Real finite_diff_tol = 1e-7; // it's in percent - } // namespace muSpectre #endif // TESTS_TESTS_HH_