diff --git a/CMakeLists.txt b/CMakeLists.txt index 133e36f..fa08220 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,211 +1,212 @@ # ============================================================================= # 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 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. # ============================================================================= cmake_minimum_required(VERSION 3.0.0) project(µSpectre) 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(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}) 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}) include(muspectreTools) if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang" OR "${CMAKE_CXX_COMPILER_ID}" STREQUAL "AppleClang") # using Clang add_compile_options(-Wno-missing-braces) elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") # using GCC add_compile_options(-Wno-non-virtual-dtor) string( TOLOWER "${CMAKE_BUILD_TYPE}" build_type ) if ("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() add_external_package(Eigen3 VERSION 3.3.0 CONFIG) add_external_package(pybind11 VERSION 2.2 CONFIG) include_directories( ${CMAKE_SOURCE_DIR}/src ${CMAKE_SOURCE_DIR} ) if(APPLE) 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 tests file( GLOB TEST_SRCS "${CMAKE_SOURCE_DIR}/tests/test_*.cc") add_executable(main_test_suite tests/main_test_suite.cc ${TEST_SRCS}) target_link_libraries(main_test_suite ${Boost_LIBRARIES} muSpectre) muSpectre_add_test(main_test_suite TYPE BOOST main_test_suite --report_level=detailed) ############################################################################## # 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}) find_package(PythonInterp ${MUSPECTRE_PYTHON_MAJOR_VERSION} REQUIRED) 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}) ################################################################################ # compile the library add_compile_options( -Werror) add_subdirectory( ${CMAKE_SOURCE_DIR}/src/ ) add_subdirectory( ${CMAKE_SOURCE_DIR}/language_bindings/ ) if (${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}) endif (${MAKE_EXAMPLES}) ################################################################################ # compile benchmarks if(${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}) diff --git a/bin/demonstrator1.cc b/bin/demonstrator1.cc index 194d513..6888d4b 100644 --- a/bin/demonstrator1.cc +++ b/bin/demonstrator1.cc @@ -1,141 +1,139 @@ /** * @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 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 #include #include "external/cxxopts.hpp" #include "common/common.hh" #include "common/ccoord_operations.hh" #include "cell/cell_factory.hh" #include "materials/material_linear_elastic1.hh" -#include "solver/solvers.hh" -#include "solver/solver_cg.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 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{std::make_unique("soft", E, nu)}; - auto Material_hard{std::make_unique("hard", 10*E, nu)}; + 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); + Material_hard.add_pixel(pixel); counter ++; } else { - Material_soft->add_pixel(pixel); + Material_soft.add_pixel(pixel); } } 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); 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}; - SolverCG cg{cell, cg_tol, maxiter, bool(verbose)}; - de_geus(cell, grads, cg, newton_tol, verbose); + DeprecatedSolverCG cg{cell, cg_tol, maxiter, bool(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 09c9f77..8ec224d 100644 --- a/bin/demonstrator2.cc +++ b/bin/demonstrator2.cc @@ -1,90 +1,90 @@ /** * @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 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 #include #include "common/common.hh" #include "common/ccoord_operations.hh" #include "cell/cell_factory.hh" #include "materials/material_linear_elastic1.hh" #include "solver/solvers.hh" #include "solver/solver_cg.hh" using namespace muSpectre; 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; - Grad_t DeltaF{Grad_t::Zero()}; + 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, bool(verbose)}; + SolverCG cg{cell, cg_tol, maxiter, bool(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/demonstrator1.cc b/bin/demonstrator_dynamic_solve.cc similarity index 88% copy from bin/demonstrator1.cc copy to bin/demonstrator_dynamic_solve.cc index 194d513..c54a6d9 100644 --- a/bin/demonstrator1.cc +++ b/bin/demonstrator_dynamic_solve.cc @@ -1,141 +1,139 @@ /** * @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 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 #include #include "external/cxxopts.hpp" #include "common/common.hh" #include "common/ccoord_operations.hh" #include "cell/cell_factory.hh" #include "materials/material_linear_elastic1.hh" #include "solver/solvers.hh" #include "solver/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 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{std::make_unique("soft", E, nu)}; - auto Material_hard{std::make_unique("hard", 10*E, nu)}; + 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); + Material_hard.add_pixel(pixel); counter ++; } else { - Material_soft->add_pixel(pixel); + Material_soft.add_pixel(pixel); } } 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); constexpr Real newton_tol{1e-4}; constexpr Real cg_tol{1e-7}; const Uint maxiter = nb_dofs; - Grad_t DeltaF{Grad_t::Zero()}; + Eigen::MatrixXd DeltaF{Eigen::MatrixXd::Zero(dim, dim)}; DeltaF(0, 1) = .1; Dim_t verbose {1}; auto start = std::chrono::high_resolution_clock::now(); - GradIncrements grads{DeltaF}; - SolverCG cg{cell, cg_tol, maxiter, bool(verbose)}; - de_geus(cell, grads, cg, newton_tol, verbose); + LoadSteps_t loads{DeltaF}; + SolverCG cg{cell, cg_tol, maxiter, bool(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 1e6719d..bfe63b6 100644 --- a/bin/demonstrator_mpi.cc +++ b/bin/demonstrator_mpi.cc @@ -1,153 +1,153 @@ /** * 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 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 #include #include "external/cxxopts.hpp" #include "common/common.hh" #include "common/ccoord_operations.hh" #include "cell/cell_factory.hh" #include "materials/material_linear_elastic1.hh" #include "solver/solvers.hh" #include "solver/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 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)}; 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)}; { 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); constexpr Real newton_tol{1e-4}; constexpr Real cg_tol{1e-7}; const Uint maxiter = nb_dofs; - Grad_t DeltaF{Grad_t::Zero()}; + Eigen::MatrixXd DeltaF{Eigen::MatrixXd::Zero(dim, dim)}; DeltaF(0, 1) = .1; Dim_t verbose {1}; auto start = std::chrono::high_resolution_clock::now(); - GradIncrements grads{DeltaF}; - SolverCG cg{cell, cg_tol, maxiter, bool(verbose)}; + LoadSteps_t grads{DeltaF}; + SolverCG cg{cell, cg_tol, maxiter, bool(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 0c25e3d..dff918b 100644 --- a/bin/hyper-elasticity.cc +++ b/bin/hyper-elasticity.cc @@ -1,90 +1,90 @@ /** * @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 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 "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{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}; - Grad_t dF_bar{Grad_t::Zero()}; + Eigen::MatrixXd dF_bar{Eigen::MatrixXd::Zero(dim, dim)}; dF_bar(0, 1) = 1.; - SolverCG cg{cell, cg_tol, maxiter, verbose}; + 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 6a10699..5b7d838 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 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/iterators.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; 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}; 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}; - Grad_t Del0{}; + Eigen::MatrixXd Del0{}; Del0 << 0, .1, 0, 0; Uint maxiter{31}; Dim_t verbose{3}; - SolverCG cg{rve, tol, maxiter, bool(verbose)}; + SolverCG cg{rve, tol, maxiter, bool(verbose)}; auto res = de_geus(rve, Del0, cg, tol, verbose); std::cout << res.grad.transpose() << std::endl; return 0; } diff --git a/language_bindings/python/bind_py_cell.cc b/language_bindings/python/bind_py_cell.cc index c17f496..82afac3 100644 --- a/language_bindings/python/bind_py_cell.cc +++ b/language_bindings/python/bind_py_cell.cc @@ -1,213 +1,210 @@ /** * @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 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/ccoord_operations.hh" #include "cell/cell_factory.hh" #include "cell/cell_base.hh" #ifdef WITH_FFTWMPI #include "fft/fftwmpi_engine.hh" #endif #ifdef WITH_PFFT #include "fft/pfft_engine.hh" #endif #include #include #include "pybind11/eigen.h" #include #include using namespace muSpectre; namespace py=pybind11; using namespace pybind11::literals; /** * 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> (std::move(res), std::move(lens), std::move(form), std::move(Communicator(MPI_Comm(comm)))); }, "resolutions"_a, "lengths"_a=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 make_cell(std::move(res), std::move(lens), std::move(form)); }, "resolutions"_a, "lengths"_a=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>( + 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); } /** * 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 = CellBase; - py::class_(mod, name.c_str()) + 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=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_field(in_name); auto & output = cell.get_managed_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_field(in_name); input.eigen() = v; cell.project(input); return input.eigen(); }, "field"_a) .def("get_strain",[](sys_t & s) { return Eigen::ArrayXXd(s.get_strain().eigen()); }) .def("get_stress",[](sys_t & s) { return Eigen::ArrayXXd(s.get_stress().eigen()); }) .def("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; cell.evaluate_stress_tangent(strain); }, "strain"_a) .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); } void add_cell_base(py::module & mod) { + py::class_(mod, "Cell"); add_cell_base_helper (mod); add_cell_base_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); } diff --git a/language_bindings/python/bind_py_fftengine.cc b/language_bindings/python/bind_py_fftengine.cc index ec76db3..5007523 100644 --- a/language_bindings/python/bind_py_fftengine.cc +++ b/language_bindings/python/bind_py_fftengine.cc @@ -1,110 +1,114 @@ /** * @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 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 "fft/fftw_engine.hh" #ifdef WITH_FFTWMPI #include "fft/fftwmpi_engine.hh" #endif #ifdef WITH_PFFT #include "fft/pfft_engine.hh" #endif #include "bind_py_declarations.hh" #include #include #include using namespace muSpectre; namespace py=pybind11; using namespace pybind11::literals; 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, size_t comm) { - return new Engine(res, std::move(Communicator(MPI_Comm(comm)))); - }), - "resolutions"_a, - "communicator"_a=size_t(MPI_COMM_SELF)) + .def(py::init([](Ccoord res, Dim_t nb_components, size_t comm) { + return new Engine(res, nb_components, + std::move(Communicator(MPI_Comm(comm)))); + }), + "resolutions"_a, + "nb_components"_a, + "communicator"_a=size_t(MPI_COMM_SELF)) #else - .def(py::init()) + .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{make_field("temp_field", coll)}; + Field_t & temp{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{make_field("temp_field", coll)}; + Field_t & temp{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=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, twoD>(fft, "FFTW_2d"); - add_engine_helper, threeD>(fft, "FFTW_3d"); + add_engine_helper, twoD>(fft, "FFTW_2d"); + add_engine_helper, threeD>(fft, "FFTW_3d"); #ifdef WITH_FFTWMPI - add_engine_helper, twoD>(fft, "FFTWMPI_2d"); - add_engine_helper, threeD>(fft, "FFTWMPI_3d"); + add_engine_helper, twoD>(fft, "FFTWMPI_2d"); + add_engine_helper, 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, twoD>(fft, "PFFT_2d"); + add_engine_helper, threeD>(fft, "PFFT_3d"); #endif add_projections(fft); } diff --git a/language_bindings/python/bind_py_projections.cc b/language_bindings/python/bind_py_projections.cc index 5f02dc4..f9560e6 100644 --- a/language_bindings/python/bind_py_projections.cc +++ b/language_bindings/python/bind_py_projections.cc @@ -1,194 +1,198 @@ /** * @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 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 "fft/projection_small_strain.hh" #include "fft/projection_finite_strain.hh" #include "fft/projection_finite_strain_fast.hh" #include "fft/fftw_engine.hh" #ifdef WITH_FFTWMPI #include "fft/fftwmpi_engine.hh" #endif #ifdef WITH_PFFT #include "fft/pfft_engine.hh" #endif #include #include #include #include #include using namespace muSpectre; namespace py=pybind11; using namespace pybind11::literals; /** * "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 = Ccoord_t; using Rcoord = 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> - (res, std::move(Communicator(MPI_Comm(comm)))); + auto engine = std::make_unique> + (res, Proj::NbComponents(), std::move(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>(res); + 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> - (res, std::move(Communicator(MPI_Comm(comm)))); + auto engine = std::make_unique> + (res, Proj::NbComponents(), + std::move(Communicator(MPI_Comm(comm)))); return Proj(std::move(engine), lengths); } #endif #ifdef WITH_PFFT else if (fft == "pfft") { - auto engine = std::make_unique> - (res, std::move(Communicator(MPI_Comm(comm)))); + auto engine = std::make_unique> + (res, Proj::NbComponents(), + std::move(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=FFT_PlanFlags::estimate, "initialises the fft engine (plan the transform)") .def("apply_projection", [](Proj & proj, py::EigenDRef v){ - typename FFTEngineBase::GFieldCollection_t coll{}; + typename FFTEngineBase::GFieldCollection_t coll{}; Eigen::Index subdomain_size = 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{make_field("temp_field", coll)}; + Field_t & temp{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< ProjectionSmallStrain< twoD, twoD>, twoD>(mod, "ProjectionSmallStrain"); add_proj_helper< ProjectionSmallStrain, threeD>(mod, "ProjectionSmallStrain"); add_proj_helper< ProjectionFiniteStrain< twoD, twoD>, twoD>(mod, "ProjectionFiniteStrain"); add_proj_helper< ProjectionFiniteStrain, threeD>(mod, "ProjectionFiniteStrain"); add_proj_helper< ProjectionFiniteStrainFast< twoD, twoD>, twoD>(mod, "ProjectionFiniteStrainFast"); add_proj_helper< ProjectionFiniteStrainFast, 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 13a3b36..12d63e7 100644 --- a/language_bindings/python/bind_py_solvers.cc +++ b/language_bindings/python/bind_py_solvers.cc @@ -1,177 +1,154 @@ /** * @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 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 "solver/solvers.hh" #include "solver/solver_cg.hh" -#include "solver/solver_cg_eigen.hh" +#include "solver/solver_eigen.hh" #include #include #include using namespace muSpectre; namespace py=pybind11; using namespace pybind11::literals; /** * Solvers instanciated for cells with equal spatial and material dimension */ -template -void add_iterative_solver_helper(py::module & mod, std::string name_start) { - using sys = CellBase; - std::stringstream name{}; - name << name_start << '_' << sdim << 'd'; - py::class_(mod, name.str().c_str()) - .def(py::init(), +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::name); - mod.def(name_start.c_str(), - [](sys& cell, Real tol, Uint maxiter, bool verbose) { - return std::make_unique(cell, tol, maxiter, verbose); - }, - "cell"_a, - "tol"_a, - "maxiter"_a, - "verbose"_a=false); -} - -template -void add_iterative_solver_dispatcher(py::module & mod) { - std::stringstream name{}; - name << "SolverBase_" << sdim << 'd'; - 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"); + .def("name", &Solver::get_name); } void add_iterative_solver(py::module & mod) { - add_iterative_solver_dispatcher< twoD>(mod); - add_iterative_solver_dispatcher(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"); } -template void add_newton_cg_helper(py::module & mod) { const char name []{"newton_cg"}; - constexpr Dim_t mdim{sdim}; - using sys = CellBase; - using solver = SolverBase; - using grad = Grad_t; - using grad_vec = GradIncrements; + using solver = SolverBase; + using grad = py::EigenDRef; + using grad_vec = LoadSteps_t; mod.def(name, - [](sys & s, const grad & g, solver & so, Real nt, + [](Cell & s, const grad & g, solver & so, Real nt, Real eqt, Dim_t verb) -> OptimizeResult { - return newton_cg(s, g, so, nt, eqt, verb); + 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, - [](sys & s, const grad_vec & g, solver & so, Real nt, + [](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); } -template void add_de_geus_helper(py::module & mod) { const char name []{"de_geus"}; - constexpr Dim_t mdim{sdim}; - using sys = CellBase; - using solver = SolverBase; - using grad = Grad_t; - using grad_vec = GradIncrements; + using solver = SolverBase; + using grad = py::EigenDRef; + using grad_vec = LoadSteps_t; mod.def(name, - [](sys & s, const grad & g, solver & so, Real nt, + [](Cell & s, const grad & g, solver & so, Real nt, Real eqt, Dim_t verb) -> OptimizeResult { - return de_geus(s, g, so, nt, eqt, verb); + 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, - [](sys & s, const grad_vec & g, solver & so, Real nt, + [](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); } -template void add_solver_helper(py::module & mod) { - add_newton_cg_helper(mod); - add_de_geus_helper (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); add_iterative_solver(solvers); - add_solver_helper(solvers); - add_solver_helper(solvers); + add_solver_helper(solvers); } diff --git a/language_bindings/python/muSpectre/fft.py b/language_bindings/python/muSpectre/fft.py index a191b50..ae9b569 100644 --- a/language_bindings/python/muSpectre/fft.py +++ b/language_bindings/python/muSpectre/fft.py @@ -1,140 +1,142 @@ # # @file fft.py # # @author Lars Pastewka # # @date 27 Mar 2018 # # @brief Wrapper for muSpectre's FFT engines # # 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. # try: from mpi4py import MPI except ImportError: MPI = None import _muSpectre # This is a list of FFT engines that are potentially available. _factories = {'fftw': ('FFTW_2d', 'FFTW_3d', False), 'fftwmpi': ('FFTWMPI_2d', 'FFTWMPI_3d', True), 'pfft': ('PFFT_2d', 'PFFT_3d', True), 'p3dfft': ('P3DFFT_2d', 'P3DFFT_3d', True)} _projections = {_muSpectre.Formulation.finite_strain: 'FiniteStrainFast', _muSpectre.Formulation.small_strain: 'SmallStrain'} # Detect FFT engines. This is a convenience dictionary that allows enumeration # of all engines that have been compiled into the library. fft_engines = [] for fft, (factory_name_2d, factory_name_3d, is_parallel) in _factories.items(): if factory_name_2d in _muSpectre.fft.__dict__ and \ factory_name_3d in _muSpectre.fft.__dict__: fft_engines += [(fft, is_parallel)] -def FFT(resolutions, fft='fftw', communicator=None): +def FFT(resolutions, nb_components, fft='fftw', communicator=None): """ Instantiate a muSpectre FFT class. Parameters ---------- resolutions: list Grid resolutions in the Cartesian directions. + nb_components: int + number of degrees of freedom per pixel in the transform fft: string FFT engine to use. Options are 'fftw', 'fftwmpi', 'pfft' and 'p3dfft'. Default is 'fftw'. communicator: mpi4py communicator mpi4py communicator object passed to parallel FFT engines. Note that the default 'fftw' engine does not support parallel execution. Returns ------- cell: object Return a muSpectre Cell object. """ try: factory_name_2d, factory_name_3d, is_parallel = _factories[fft] except KeyError: raise KeyError("Unknown FFT engine '{}'.".format(fft)) if len(resolutions) == 2: factory_name = factory_name_2d elif len(resolutions) == 3: factory_name = factory_name_3d else: raise ValueError('{}-d transforms are not supported' .format(len(resolutions))) try: factory = _muSpectre.fft.__dict__[factory_name] except KeyError: raise KeyError("FFT engine '{}' has not been compiled into the " "muSpectre library.".format(factory_name)) if is_parallel: if MPI is None: raise RuntimeError('Parallel solver requested but mpi4py could' ' not be imported.') if communicator is None: communicator = MPI.COMM_SELF - return factory(resolutions, MPI._handleof(communicator)) + return factory(resolutions, nb_components, MPI._handleof(communicator)) else: if communicator is not None: raise ValueError("FFT engine '{}' does not support parallel " "execution.".format(fft)) - return factory(resolutions) + return factory(resolutions, nb_components) def Projection(resolutions, lengths, formulation=_muSpectre.Formulation.finite_strain, fft='fftw', communicator=None): """ Instantiate a muSpectre Projection class. Parameters ---------- resolutions: list Grid resolutions in the Cartesian directions. formulation: muSpectre.Formulation Determines whether to use finite or small strain formulation. fft: string FFT engine to use. Options are 'fftw', 'fftwmpi', 'pfft' and 'p3dfft'. Default is 'fftw'. communicator: mpi4py communicator mpi4py communicator object passed to parallel FFT engines. Note that the default 'fftw' engine does not support parallel execution. Returns ------- cell: object Return a muSpectre Cell object. """ factory_name = 'Projection{}_{}d'.format(_projections[formulation], len(resolutions)) try: factory = _muSpectre.fft.__dict__[factory_name] except KeyError: raise KeyError("Projection engine '{}' has not been compiled into the " "muSpectre library.".format(factory_name)) if communicator is None: communicator = MPI.COMM_SELF return factory(resolutions, lengths, fft, MPI._handleof(communicator)) diff --git a/src/cell/cell_base.cc b/src/cell/cell_base.cc index 97004c4..9801afa 100644 --- a/src/cell/cell_base.cc +++ b/src/cell/cell_base.cc @@ -1,295 +1,405 @@ /** * @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 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 "cell/cell_base.hh" #include "common/ccoord_operations.hh" #include "common/iterators.hh" #include "common/tensor_algebra.hh" #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)}, projection{std::move(projection_)}, form{projection->get_formulation()} { } /* ---------------------------------------------------------------------- */ 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) { + 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->form); + } + + 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->form); + } + 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 + ("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 + << ") × " << 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_field(out_name); + + auto Kmap{this->K.value().get().get_map()}; + auto delPmap{delP.get_map()}; + 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 + void CellBase::apply_projection(Eigen::Ref vec) { + 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->form); } 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) { + 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::SolvVectorOut - CellBase::directional_stiffness_vec(const SolvVectorIn &delF) { + 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->nb_dof()) { + if (delF.size() != this->get_nb_dof()) { std::stringstream err{}; err << "input should be of size ndof = ¶(" << this->subdomain_resolutions - << ") × " << DimS << "² = "<< this->nb_dof() << " but I got " + << ") × " << 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_field(out_name); auto & in_tempref = this->get_managed_field(in_name); - SolvVectorOut(in_tempref.data(), this->nb_dof()) = delF; + Vector_ref(in_tempref.data(), this->get_nb_dof()) = delF; this->directional_stiffness(this->K.value(), in_tempref, out_tempref); - return SolvVectorOut(out_tempref.data(), this->nb_dof()); + 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_field(out_name); auto & in_tempref = this->get_managed_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); } else { throw std::runtime_error ("K does not exist"); } } return this->K.value(); } /* ---------------------------------------------------------------------- */ template typename CellBase::StrainField_t & CellBase::get_managed_field(std::string unique_name) { if (!this->fields->check_field_exists(unique_name)) { return make_field(unique_name, *this->fields); } else { return static_cast(this->fields->at(unique_name)); } } /* ---------------------------------------------------------------------- */ template void CellBase::initialise(FFT_PlanFlags flags) { // check that all pixels have been assigned exactly one material this->check_material_coverage(); + for (auto && mat: this->materials) { + mat->initialise(); + } // resize all global fields (strain, stress, etc) this->fields->initialise(this->subdomain_resolutions, this->subdomain_locations); // initialise the projection and compute the fft plan this->projection->initialise(flags); this->initialised = true; } - /* ---------------------------------------------------------------------- */ - template - void CellBase::initialise_materials(bool stiffness) { - for (auto && mat: this->materials) { - mat->initialise(stiffness); - } - } - /* ---------------------------------------------------------------------- */ 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 - CellAdaptor> - CellBase::get_adaptor() { + auto CellBase::get_adaptor() -> Adaptor { return Adaptor(*this); } /* ---------------------------------------------------------------------- */ template void CellBase::check_material_coverage() { auto nb_pixels = 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& assignment{assignments.at(index)}; if (assignment != nullptr) { std::stringstream err{}; err << "Pixel " << 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(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 << ", "; } err << "and that cannot be handled"; throw std::runtime_error(err.str()); } } template class CellBase; template class CellBase; } // muSpectre diff --git a/src/cell/cell_base.hh b/src/cell/cell_base.hh index 018ae27..f6849a2 100644 --- a/src/cell/cell_base.hh +++ b/src/cell/cell_base.hh @@ -1,313 +1,511 @@ /** * @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 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 CELL_BASE_H #define CELL_BASE_H #include "common/common.hh" #include "common/ccoord_operations.hh" #include "common/field.hh" #include "common/utilities.hh" #include "materials/material_base.hh" #include "fft/projection_base.hh" #include "cell/cell_traits.hh" #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; + + /** + * 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; + + //! 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; + + //! return the communicator object + virtual const 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; + + /** + * 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; + + + /** + * 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 + 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; //! 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; //! expected type for strain fields using StrainField_t = TensorField; //! expected type for stress fields using StressField_t = TensorField; //! expected type for tangent stiffness fields using TangentField_t = TensorField; //! combined stress and tangent field using FullResponse_t = std::tuple; //! iterator type over all cell pixel's using iterator = typename CcoordOps::Pixels::iterator; - //! input vector for solvers - using SolvVectorIn = Eigen::Ref; - //! output vector for solvers - using SolvVectorOut = Eigen::Map; + + //! 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; + + //! sparse matrix emulation - using Adaptor = CellAdaptor; + using Adaptor = Parent::Adaptor; //! Default constructor CellBase() = delete; //! constructor using sizes and resolution CellBase(Projection_ptr projection); //! Copy constructor CellBase(const CellBase &other) = delete; //! Move constructor CellBase(CellBase &&other) = default; //! 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. + */ + virtual 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 + */ + virtual ConstVector_ref get_stress_vector() const override; + + /** + * evaluates and returns the stress for the currently set strain + */ + virtual ConstVector_ref evaluate_stress() override; + + /** + * evaluates and returns the stress and stiffness for the currently set strain + */ + virtual std::array evaluate_stress_tangent() 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) + */ + virtual 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 override 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 override final; + + /** + * applies the projection operator in-place on the input vector + */ + void apply_projection(Eigen::Ref vec) override final; + + + + /** + * set uniform strain (typically used to initialise problems + */ + void set_uniform_strain(const Eigen::Ref &) override; + + /** * evaluates all materials */ 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 */ - SolvVectorOut directional_stiffness_vec(const SolvVectorIn & delF); + 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_field(std::string unique_name); /** * 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); - /** - * initialise materials (including resetting any history variables) - */ - void initialise_materials(bool stiffness=false); /** * 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(); + void save_history_variables() override 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 {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;} /** * formulation is hard set by the choice of the projection class */ - const Formulation & get_formulation() const { + const Formulation & get_formulation() const override final { return this->projection->get_formulation();} - //! for handling double initialisations right - bool is_initialised() const {return this->initialised;} - /** * 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(); + Adaptor get_adaptor() override; //! returns the number of degrees of freedom in the cell - Dim_t nb_dof() const {return this->size()*ipow(DimS, 2);}; + Dim_t get_nb_dof() const override {return this->size()*ipow(DimS, 2);}; //! return the communicator object - const Communicator & get_communicator() const { + virtual const Communicator & get_communicator() const override { return this->projection->get_communicator(); } - + protected: //! make sure that every pixel is assigned to one and only one material 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 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 - bool initialised{false}; //!< to handle double initialisation right const Formulation form; //!< formulation for solution private: }; /** - * lightweight resource handle wrapping a `muSpectre::CellBase` or + * 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 CellAdaptor(Cell & cell):cell{cell}{} //!returns the number of logical rows - Eigen::Index rows() const {return this->cell.nb_dof();} + 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 }; } // muSpectre namespace Eigen { namespace internal { //! Implementation of `muSpectre::CellAdaptor` * `Eigen::DenseVector` through a //! specialization of `Eigen::internal::generic_product_impl`: template struct generic_product_impl // GEMV stands for matrix-vector : 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.directional_stiffness_vec(rhs); + dst.noalias() += const_cast(lhs).cell. + evaluate_projected_directional_stiffness(rhs); } }; } } #endif /* CELL_BASE_H */ diff --git a/src/cell/cell_factory.hh b/src/cell/cell_factory.hh index 93a70b7..c826b78 100644 --- a/src/cell/cell_factory.hh +++ b/src/cell/cell_factory.hh @@ -1,157 +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 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 CELL_FACTORY_H #define CELL_FACTORY_H #include "common/common.hh" #include "common/ccoord_operations.hh" #include "cell/cell_base.hh" #include "fft/projection_finite_strain_fast.hh" #include "fft/projection_small_strain.hh" #include "fft/fftw_engine.hh" #ifdef WITH_MPI #include "common/communicator.hh" #include "fft/fftwmpi_engine.hh" #endif #include namespace muSpectre { /** * Create a unique ptr to a Projection operator (with appropriate * FFT_engine) to be used in a cell constructor */ template > + typename FFTEngine=FFTWEngine> inline std::unique_ptr> cell_input(Ccoord_t resolutions, Rcoord_t lengths, Formulation form) { - auto fft_ptr{std::make_unique(resolutions)}; + 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=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; } #ifdef WITH_MPI /** * Create a unique ptr to a parallel Projection operator (with appropriate * FFT_engine) to be used in a cell constructor */ template > + typename FFTEngine=FFTWMPIEngine> inline std::unique_ptr> parallel_cell_input(Ccoord_t resolutions, Rcoord_t lengths, Formulation form, const Communicator & comm) { - auto fft_ptr{std::make_unique(resolutions, 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=FFTWMPIEngine> inline Cell make_parallel_cell(Ccoord_t resolutions, Rcoord_t lengths, Formulation form, const Communicator & comm) { auto && input = parallel_cell_input(resolutions, lengths, form, comm); auto cell{Cell{std::move(input)}}; return cell; } #endif /* WITH_MPI */ } // muSpectre #endif /* CELL_FACTORY_H */ diff --git a/src/common/common.hh b/src/common/common.hh index cafe1cd..9db6790 100644 --- a/src/common/common.hh +++ b/src/common/common.hh @@ -1,282 +1,311 @@ /** * @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 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 #include #include #include #include #ifndef COMMON_H #define COMMON_H 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; 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 `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; } //! 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; } /** * 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 σ(ε) + finite_strain, //!< causes evaluation in PK1(F) + small_strain, //!< causes evaluation in σ(ε) + small_strain_sym //!< symmetric storage as vector ε }; + + /** + * 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); + 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; } } } // muSpectre #ifndef EXPLICITLY_TURNED_ON_CXX17 #include "common/utilities.hh" #endif #endif /* COMMON_H */ diff --git a/src/common/field.hh b/src/common/field.hh index c3b6a88..16b9df2 100644 --- a/src/common/field.hh +++ b/src/common/field.hh @@ -1,1068 +1,662 @@ /** * @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 * 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 FIELD_H #define FIELD_H #include "common/T4_map_proxy.hh" +#include "field_typed.hh" #include #include #include #include #include #include #include #include #include #include namespace muSpectre { - /* ---------------------------------------------------------------------- */ - /** - * 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 - * 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 my collection (for iterating) - 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 - friend typename FieldCollection::Parent; - - 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 - const FieldCollection & collection; - size_t pad_size; //!< size of padding region at end of buffer - private: - }; - - - /** - * Dummy intermediate class to provide a run-time polymorphic - * typed field. Mainly for binding Python. TypedFieldBase specifies methods - * that return typed Eigen maps and vectors in addition to pointers to the - * raw data. - */ - template - class TypedFieldBase: public FieldBase - { - public: - using Parent = FieldBase; //!< base class - //! for type checks when mapping this field - using collection_t = typename Parent::collection_t; - using Scalar = T; //!< for type checks - using Base = Parent; //!< for uniformity of interface - //! Plain Eigen type to map - using EigenRep = Eigen::Array; - //! map returned when iterating over field - using EigenMap = Eigen::Map; - //! Plain eigen vector to map - using EigenVec = Eigen::Map; - //! vector map returned when iterating over field - using EigenVecConst = Eigen::Map; - //! Default constructor - TypedFieldBase() = delete; - - //! constructor - TypedFieldBase(std::string unique_name, - size_t nb_components, - FieldCollection& collection); - - //! Copy constructor - TypedFieldBase(const TypedFieldBase &other) = delete; - - //! Move constructor - TypedFieldBase(TypedFieldBase &&other) = delete; - - //! Destructor - virtual ~TypedFieldBase() = default; - - //! Copy assignment operator - TypedFieldBase& operator=(const TypedFieldBase &other) = delete; - - //! Move assignment operator - TypedFieldBase& operator=(TypedFieldBase &&other) = delete; - - //! return type_id of stored type - virtual const std::type_info & get_stored_typeid() const override final; - - virtual size_t size() const override = 0; - - //! initialise field to zero (do more complicated initialisations through - //! fully typed maps) - virtual void set_zero() override = 0; - - //! raw pointer to content (e.g., for Eigen maps) - virtual T* data() = 0; - //! raw pointer to content (e.g., for Eigen maps) - virtual const T* data() const = 0; - - //! return a map representing the entire field as a single `Eigen::Array` - EigenMap eigen(); - //! return a map representing the entire field as a single Eigen vector - EigenVec eigenvec(); - //! return a map representing the entire field as a single Eigen vector - EigenVecConst eigenvec() const; - - protected: - private: - }; - /* ---------------------------------------------------------------------- */ //! 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 TypedFieldBase + template + class TypedSizedFieldBase: public TypedField { friend class FieldMap; friend class FieldMap; public: //! for compatibility checks constexpr static auto nb_components{NbComponents}; - using Parent = TypedFieldBase; //!< base class + using Parent = TypedField; //!< base class using Scalar = T; //!< for type checking using Base = typename Parent::Base; //!< root base class //! type stored if ArrayStore is true - using StoredType = Eigen::Array; + using Stored_t = Eigen::Array; //! storage container - using StorageType = std::conditional_t - >, - std::vector>>; + using Storage_t = typename Parent::Storage_t; //! Plain type that is being mapped (Eigen lingo) - using EigenRep = Eigen::Array; + using EigenRep_t = Eigen::Array; //! maps returned when iterating over field - using EigenMap = std::conditional_t< - ArrayStore, - Eigen::Map>, - Eigen::Map>; + using EigenMap_t = Eigen::Map; //! maps returned when iterating over field - using ConstEigenMap = std::conditional_t< - ArrayStore, - Eigen::Map>, - Eigen::Map>; + using ConstEigenMap_t = Eigen::Map; //! constructor TypedSizedFieldBase(std::string unique_name, FieldCollection& collection); virtual ~TypedSizedFieldBase() = default; - //! initialise field to zero (do more complicated initialisations through - //! fully typed maps) - inline void set_zero() override final; - - //! add a new value at the end of the field - template - inline void push_back(const - std::enable_if_t & - value); - //! add a new value at the end of the field - template - inline std::enable_if_t push_back(const StoredType & value); + inline void push_back(const Stored_t & value); //! add a new scalar value at the end of the field template inline std::enable_if_t push_back(const T & value); - //! Number of stored arrays (i.e. total number of stored - //! scalars/NbComponents) - size_t size() const override 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_) override final; - /** * 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 raw pointer to stored data (necessary for Eigen maps) - inline T* data() override final {return this->get_ptr_to_entry(0);} - //! return raw pointer to stored data (necessary for Eigen maps) - inline const T* data() const override final {return this->get_ptr_to_entry(0);} - //! return a map representing the entire field as a single `Eigen::Array` - inline EigenMap eigen(); + inline EigenMap_t eigen(); //! return a map representing the entire field as a single `Eigen::Array` - inline ConstEigenMap eigen() const; + 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 dyn_eigen() {return Parent::eigen();} + inline typename Parent::EigenMap_t dyn_eigen() {return Parent::eigen();} //! inner product between compatible fields - template - inline Real inner_product(const TypedSizedFieldBase & other) const; + template + inline Real inner_product(const TypedSizedFieldBase< + FieldCollection, T2, NbComponents> & other) const; protected: //! returns a raw pointer to the entry, for `Eigen::Map` - template - inline std::enable_if_t get_ptr_to_entry(const size_t&& index); + inline T* get_ptr_to_entry(const size_t&& index); //! returns a raw pointer to the entry, for `Eigen::Map` - template - inline std::enable_if_t - get_ptr_to_entry(const size_t&& index) const; - - //! returns a raw pointer to the entry, for `Eigen::Map` - template - inline T* get_ptr_to_entry(std::enable_if_t index); - - //! returns a raw pointer to the entry, for `Eigen::Map` - template inline const T* - get_ptr_to_entry(std::enable_if_t index) const; - - //! set the storage size of this field - inline virtual void resize(size_t size) override final; + get_ptr_to_entry(const size_t&& index) const; - //! The actual storage container - StorageType values{}; }; } // internal /* ---------------------------------------------------------------------- */ /** * The `TensorField` is a subclass of `muSpectre::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 + 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. */ 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. */ 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. */ decltype(auto) get_map() const; protected: //! constructor protected! TensorField(std::string unique_name, FieldCollection & collection); private: }; /* ---------------------------------------------------------------------- */ /** * The `MatrixField` is subclass of `muSpectre::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 + 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. */ 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. */ 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. */ decltype(auto) get_map() const; protected: //! constructor protected! MatrixField(std::string unique_name, FieldCollection & collection); private: }; /* ---------------------------------------------------------------------- */ //! convenience alias ( template using ScalarField = MatrixField; /* ---------------------------------------------------------------------- */ // Implementations + /* ---------------------------------------------------------------------- */ namespace internal { - /* ---------------------------------------------------------------------- */ - 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; - } - - /* ---------------------------------------------------------------------- */ - template - TypedFieldBase:: - TypedFieldBase(std::string unique_name, size_t nb_components, - FieldCollection & collection) - :Parent(unique_name, nb_components, collection) - {} - - /* ---------------------------------------------------------------------- */ - //! return type_id of stored type - template - const std::type_info & TypedFieldBase:: - get_stored_typeid() const { - return typeid(T); - } - - /* ---------------------------------------------------------------------- */ - template - typename TypedFieldBase::EigenMap - TypedFieldBase:: - eigen() { - return EigenMap(this->data(), this->get_nb_components(), this->size()); - } - - /* ---------------------------------------------------------------------- */ - template - typename TypedFieldBase::EigenVec - TypedFieldBase:: - eigenvec() { - return EigenVec(this->data(), this->get_nb_components() * this->size()); - } - - /* ---------------------------------------------------------------------- */ - template - typename TypedFieldBase::EigenVecConst - TypedFieldBase:: - eigenvec() const{ - return EigenVecConst(this->data(), this->get_nb_components() * this->size()); - } - /* ---------------------------------------------------------------------- */ - template - TypedSizedFieldBase:: + template + TypedSizedFieldBase:: TypedSizedFieldBase(std::string unique_name, FieldCollection & collection) - :Parent(unique_name, NbComponents, 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 - void - TypedSizedFieldBase:: - set_zero() { - std::fill(this->values.begin(), this->values.end(), T{}); - } - - /* ---------------------------------------------------------------------- */ - template - size_t TypedSizedFieldBase:: - size() const { - if (ArrayStore) { - return this->values.size() - this->pad_size; - } else { - return (this->values.size() - this->pad_size)/NbComponents; - } - } - - /* ---------------------------------------------------------------------- */ - template - TypedSizedFieldBase & - TypedSizedFieldBase:: + template + TypedSizedFieldBase & + TypedSizedFieldBase:: check_ref(Base & other) { 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); } //check size compatibility if (NbComponents != other.get_nb_components()) { throw std::runtime_error ("Cannot create a Reference to a field with " + std::to_string(NbComponents) + " components " + "for field '" + other.get_name() + "' with " + std::to_string(other.get_nb_components()) + " components"); } return static_cast(other); } /* ---------------------------------------------------------------------- */ - template - const TypedSizedFieldBase & - TypedSizedFieldBase:: + 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 requested type " << "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()) { throw std::runtime_error ("Cannot create a Reference to a field with " + std::to_string(NbComponents) + " components " + "for field '" + other.get_name() + "' with " + std::to_string(other.get_nb_components()) + " components"); } return static_cast(other); } /* ---------------------------------------------------------------------- */ - template - typename TypedSizedFieldBase::EigenMap - TypedSizedFieldBase:: - eigen() { - return EigenMap(this->data(), NbComponents, this->size()); + template + auto TypedSizedFieldBase:: + eigen() -> EigenMap_t{ + return EigenMap_t(this->data(), NbComponents, this->size()); } /* ---------------------------------------------------------------------- */ - template - typename TypedSizedFieldBase::ConstEigenMap - TypedSizedFieldBase:: - eigen() const { - return ConstEigenMap(this->data(), NbComponents, this->size()); + template + auto TypedSizedFieldBase:: + eigen() const -> ConstEigenMap_t{ + return ConstEigenMap_t(this->data(), NbComponents, this->size()); } /* ---------------------------------------------------------------------- */ - template - template + template + template Real - TypedSizedFieldBase:: - inner_product(const TypedSizedFieldBase & other) const { + TypedSizedFieldBase:: + inner_product(const TypedSizedFieldBase & other) const { return (this->eigen() * other.eigen()).sum(); } - /* ---------------------------------------------------------------------- */ - template - template - std::enable_if_t - TypedSizedFieldBase:: + template + T* TypedSizedFieldBase:: get_ptr_to_entry(const size_t&& index) { - static_assert (isArray == ArrayStore, "SFINAE"); - return &this->values[std::move(index)](0, 0); + return this->data_ptr + NbComponents*std::move(index); } /* ---------------------------------------------------------------------- */ - template - template - T* TypedSizedFieldBase:: - get_ptr_to_entry(std::enable_if_t index) { - static_assert (noArray != ArrayStore, "SFINAE"); - return &this->values[NbComponents*std::move(index)]; - } - - /* ---------------------------------------------------------------------- */ - template - template - std::enable_if_t - TypedSizedFieldBase:: + template + const T* TypedSizedFieldBase:: get_ptr_to_entry(const size_t&& index) const { - static_assert (isArray == ArrayStore, "SFINAE"); - return &this->values[std::move(index)](0, 0); - } - - /* ---------------------------------------------------------------------- */ - template - template - const T* TypedSizedFieldBase:: - get_ptr_to_entry(std::enable_if_t index) const { - static_assert (noArray != ArrayStore, "SFINAE"); - return &this->values[NbComponents*std::move(index)]; - } - - /* ---------------------------------------------------------------------- */ - template - void TypedSizedFieldBase:: - set_pad_size(size_t pad_size) { - if (ArrayStore) { - this->values.resize(this->size() + pad_size); - } else { - this->values.resize(this->size()*NbComponents + pad_size); - } - this->pad_size = pad_size; - } - - /* ---------------------------------------------------------------------- */ - template - void TypedSizedFieldBase:: - resize(size_t size) { - if (ArrayStore) { - this->values.resize(size); - } else { - this->values.resize(size*NbComponents); - } - } - - /* ---------------------------------------------------------------------- */ - template - template - void - TypedSizedFieldBase:: - push_back(const std::enable_if_t & value) { - static_assert(isArrayStore == ArrayStore, "SFINAE"); - this->values.push_back(value); + return this->data_ptr + NbComponents*std::move(index); } /* ---------------------------------------------------------------------- */ - template - template - std::enable_if_t - TypedSizedFieldBase:: - push_back(const StoredType & value) { - static_assert(componentStore != ArrayStore, "SFINAE"); + template + void TypedSizedFieldBase:: + push_back(const Stored_t & value) { + 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 template std::enable_if_t - TypedSizedFieldBase:: + 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(); } } // internal /* ---------------------------------------------------------------------- */ //! Factory function, guarantees that only fields get created that are //! properly registered and linked to a collection. - template + 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; } /* ---------------------------------------------------------------------- */ 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; } } // muSpectre #include "common/field_map.hh" namespace muSpectre { namespace internal { /* ---------------------------------------------------------------------- */ /** * defines the default mapped type obtained when calling * `muSpectre::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()` */ template struct matrix_map_type { //! mapping type using type = MatrixFieldMap; }; //! specialisation to scalar fields template struct matrix_map_type { //! mapping type using type = ScalarFieldMap; }; } // internal /* ---------------------------------------------------------------------- */ template decltype(auto) TensorField:: get_map() { constexpr bool map_constness{false}; using RawMap_t = typename internal::tensor_map_type::type; return RawMap_t(*this); } /* ---------------------------------------------------------------------- */ template decltype(auto) TensorField:: get_const_map() { constexpr bool map_constness{true}; using RawMap_t = typename internal::tensor_map_type::type; return RawMap_t(*this); } /* ---------------------------------------------------------------------- */ template decltype(auto) TensorField:: get_map() const { constexpr bool map_constness{true}; using RawMap_t = typename internal::tensor_map_type::type; return RawMap_t(*this); } /* ---------------------------------------------------------------------- */ template decltype(auto) MatrixField:: get_map() { constexpr bool map_constness{false}; using RawMap_t = typename internal::matrix_map_type::type; return RawMap_t(*this); } /* ---------------------------------------------------------------------- */ template decltype(auto) MatrixField:: get_const_map() { constexpr bool map_constness{true}; using RawMap_t = typename internal::matrix_map_type::type; return RawMap_t(*this); } /* ---------------------------------------------------------------------- */ template decltype(auto) MatrixField:: get_map() const { constexpr bool map_constness{true}; using RawMap_t = typename internal::matrix_map_type::type; return RawMap_t(*this); } } // muSpectre #endif /* FIELD_H */ diff --git a/src/common/field_base.hh b/src/common/field_base.hh new file mode 100644 index 0000000..2c29501 --- /dev/null +++ b/src/common/field_base.hh @@ -0,0 +1,211 @@ +/** + * file field_base.hh + * + * @author Till Junge + * + * @date 10 Apr 2018 + * + * @brief Virtual base class for fields + * + * @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 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 FIELD_BASE_H +#define FIELD_BASE_H + +#include +#include + +namespace muSpectre { + + /* ---------------------------------------------------------------------- */ + /** + * 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 + * 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 my collection (for iterating) + 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 + friend typename FieldCollection::Parent; + + 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 + const FieldCollection & collection; + size_t pad_size; //!< size of padding region at end of buffer + private: + }; + + + /* ---------------------------------------------------------------------- */ + // 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; + } + + } // internal + + +} // muSpectre + +#endif /* FIELD_BASE_H */ diff --git a/src/common/field_collection_global.hh b/src/common/field_collection_global.hh index 12b8503..7252c9b 100644 --- a/src/common/field_collection_global.hh +++ b/src/common/field_collection_global.hh @@ -1,205 +1,208 @@ /** * @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 * 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 FIELD_COLLECTION_GLOBAL_H #define FIELD_COLLECTION_GLOBAL_H #include "common/field_collection_base.hh" #include "common/ccoord_operations.hh" namespace muSpectre { /* ---------------------------------------------------------------------- */ /** `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 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(); //!< returns iterator to first pixel inline iterator end(); //!< returns iterator past the last pixel //! return spatial dimension (template parameter) static constexpr inline Dim_t spatial_dim() {return DimS;} protected: //! number of discretisation cells in each of the DimS spatial directions Ccoord sizes{}; 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() { return this->pixels.begin(); } /* ---------------------------------------------------------------------- */ template typename GlobalFieldCollection::iterator GlobalFieldCollection::end() { 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< Ccoord, std::remove_const_t< std::remove_reference_t>>::value, "can only be called with values or references of Ccoord"); return CcoordOps::get_index(this->get_sizes(), this->get_locations(), std::forward(ccoord)); } } // muSpectre #endif /* FIELD_COLLECTION_GLOBAL_H */ diff --git a/src/common/field_collection_local.hh b/src/common/field_collection_local.hh index 004e786..1039eee 100644 --- a/src/common/field_collection_local.hh +++ b/src/common/field_collection_local.hh @@ -1,181 +1,184 @@ /** * @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 * 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 FIELD_COLLECTION_LOCAL_H #define FIELD_COLLECTION_LOCAL_H #include "common/field_collection_base.hh" namespace muSpectre { /* ---------------------------------------------------------------------- */ /** `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>; 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; //! 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();} protected: //! container of pixel coords for non-global collections ccoords_container ccoords{}; //! container of indices for non-global collections (slow!) std::map indices{}; 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< Ccoord, std::remove_const_t< std::remove_reference_t>>::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)]; } } // muSpectre #endif /* FIELD_COLLECTION_LOCAL_H */ diff --git a/src/common/field_map.hh b/src/common/field_map.hh index 5de3c8a..006bbdd 100644 --- a/src/common/field_map.hh +++ b/src/common/field_map.hh @@ -1,204 +1,271 @@ /** * @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 * 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/field_map_tensor.hh" #include "common/field_map_matrixlike.hh" #include "common/field_map_scalar.hh" #include #include #include #ifndef FIELD_MAP_H #define FIELD_MAP_H namespace muSpectre { /** * 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 + //! short-hand for the basic scalar type using T = typename EigenMap::Scalar; - // raw pointer type to store + //! raw pointer type to store using T_ptr = std::conditional_t; - // input array (~field) type to be mapped + //! 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): - data{vec.data()}, nb_pixels{vec.size()/NbComponents} + 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 (vec.size() % NbComponents != 0) { + 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 " << NbComponents << "."; + << "is " << this->nb_components << "."; throw std::runtime_error(err.str()); } } //! constructor from a *contiguous* array - RawFieldMap(Eigen::Ref vec): - data{vec.data()}, nb_pixels{vec.size()/NbComponents} + 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() % NbComponents != 0) { + 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 " << NbComponents << "."; + << "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 - class iterator; + 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->data, 0};} + 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->data, this->size()};} + 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: - //! statically known size of the mapped type - constexpr static size_t NbComponents{EigenMap::SizeAtCompileTime}; + 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 - class RawFieldMap::iterator + 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 = EigenMap; + using value_type = std::conditional_t + , + EigenMap>; + using T_ptr = std::conditional_t; //! stl compliance using iterator_category = std::forward_iterator_tag; //! Default constructor - iterator() = delete; + iterator_t() = delete; //! Copy constructor - iterator(const iterator &other) = default; + iterator_t(const iterator_t &other) = default; //! Move constructor - iterator(iterator &&other) = default; + iterator_t(iterator_t &&other) = default; //! Destructor - virtual ~iterator() = default; + virtual ~iterator_t() = default; //! Copy assignment operator - iterator& operator=(const iterator &other) = default; + iterator_t& operator=(const iterator_t &other) = default; //! Move assignment operator - iterator& operator=(iterator &&other) = default; + iterator_t& operator=(iterator_t &&other) = default; //! pre-increment - inline iterator & operator++() { + inline iterator_t & operator++() { ++this->index; return *this; } //! dereference inline value_type operator *() { - return EigenMap(raw_map + Parent::NbComponents*index); + return value_type(raw_ptr + this->map.nb_components*index, + this->map.nb_rows, this->map.nb_cols); } //! inequality - inline bool operator != (const iterator & other) const { + inline bool operator != (const iterator_t & other) const { return this->index != other.index; } //! equality - inline bool operator == (const iterator & other) const { + inline bool operator == (const iterator_t & other) const { return this->index == other.index; } protected: - //! protected constructor - iterator (Parent::T_ptr raw_map, size_t start): - raw_map{raw_map}, index{start} {} + 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 - Parent::T_ptr raw_map; + T_ptr raw_ptr; + //! ref to underlying map + const Parent & map; //! currently pointed-to element size_t index; private: }; } // muSpectre #endif /* FIELD_MAP_H */ diff --git a/src/common/field_typed.hh b/src/common/field_typed.hh new file mode 100644 index 0000000..b14a5f5 --- /dev/null +++ b/src/common/field_typed.hh @@ -0,0 +1,327 @@ +/** + * 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 + * + * @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 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 FIELD_TYPED_H +#define FIELD_TYPED_H + +#include "field_base.hh" + +#include + +namespace muSpectre { + + /** + * 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 + { + public: + using Parent = internal::FieldBase; //!< base class + //! for type checks when mapping this field + using collection_t = typename Parent::collection_t; + using Scalar = T; //!< for type checks + using Base = Parent; //!< for uniformity of interface + //! Plain Eigen type to map + using EigenRep_t = Eigen::Array; + //! map returned when iterating over field + using EigenMap_t = Eigen::Map; + //! Plain eigen vector to map + using EigenVec_t = Eigen::Map; + //! vector map returned when iterating over field + using EigenVecConst_t = Eigen::Map; + + /** + * 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 + virtual const std::type_info & get_stored_typeid() const override final; + + virtual size_t size() const override 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_) override final; + + //! initialise field to zero (do more complicated initialisations through + //! fully typed maps) + virtual void set_zero() override final; + + //! add a new value at the end of the field + inline void push_back(const Stored_t & 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 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; + + 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 virtual void resize(size_t size) override 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: + }; + + /* ---------------------------------------------------------------------- */ + /* 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::eigenvec() -> EigenVec_t { + return EigenVec_t(this->data(), this->get_nb_components() * this->size()); + } + + /* ---------------------------------------------------------------------- */ + template + auto TypedField:: eigenvec() const -> EigenVecConst_t { + return EigenVecConst_t(this->data(), this->get_nb_components() * this->size()); + } + + /* ---------------------------------------------------------------------- */ + template + auto TypedField:: const_eigenvec() const -> EigenVecConst_t { + return EigenVecConst_t(this->data(), this->get_nb_components() * this->size()); + } + + /* ---------------------------------------------------------------------- */ + 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 + 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 + void TypedField:: + push_back(const Stored_t & 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(); + } + +} // muSpectre + +#endif /* FIELD_TYPED_H */ diff --git a/src/common/voigt_conversion.hh b/src/common/voigt_conversion.hh index f3b9455..429ba68 100644 --- a/src/common/voigt_conversion.hh +++ b/src/common/voigt_conversion.hh @@ -1,174 +1,162 @@ /** * @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 VOIGT_CONVERSION_H #define VOIGT_CONVERSION_H #include "common/common.hh" #include #include #include namespace muSpectre { - /** - * 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; - } - } - /** * implements a bunch of static functions to convert between full * and Voigt notation of tensors */ template class VoigtConversion { public: VoigtConversion(); virtual ~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); public: //! matrix of vector index I as function of tensor indices i,j const static Eigen::Matrix mat; //! matrix of vector index I as function of tensor indices i,j const static Eigen::Matrix sym_mat; //! array of matrix indices ij as function of vector index I const static Eigen::Matrixvec; //! factors to multiply the strain by for voigt notation const static Eigen::Matrix factors; }; //----------------------------------------------------------------------------// 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); } } } // muSpectre #endif /* VOIGT_CONVERSION_H */ diff --git a/src/fft/fft_engine_base.cc b/src/fft/fft_engine_base.cc index 1036a88..b603837 100644 --- a/src/fft/fft_engine_base.cc +++ b/src/fft/fft_engine_base.cc @@ -1,65 +1,67 @@ /** * @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 * 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 "fft/fft_engine_base.hh" namespace muSpectre { /* ---------------------------------------------------------------------- */ - template - FFTEngineBase::FFTEngineBase(Ccoord resolutions, - Communicator comm) + 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_locations{}, domain_resolutions{resolutions}, - work{make_field("work space", work_space_container)}, - norm_factor{1./CcoordOps::get_size(domain_resolutions)} + work{make_field + ("work space", work_space_container, nb_components)}, + norm_factor{1./CcoordOps::get_size(domain_resolutions)}, + nb_components{nb_components} {} /* ---------------------------------------------------------------------- */ - template - void FFTEngineBase::initialise(FFT_PlanFlags /*plan_flags*/) { + template + void FFTEngineBase::initialise(FFT_PlanFlags /*plan_flags*/) { this->work_space_container.initialise(); } /* ---------------------------------------------------------------------- */ - template - size_t FFTEngineBase::size() const { + template + size_t FFTEngineBase::size() const { return CcoordOps::get_size(this->subdomain_resolutions); } /* ---------------------------------------------------------------------- */ - template - size_t FFTEngineBase::workspace_size() const { + 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; + template class FFTEngineBase; } // muSpectre diff --git a/src/fft/fft_engine_base.hh b/src/fft/fft_engine_base.hh index 450b9b7..ecefa5e 100644 --- a/src/fft/fft_engine_base.hh +++ b/src/fft/fft_engine_base.hh @@ -1,159 +1,163 @@ /** * @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 * 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 FFT_ENGINE_BASE_H #define FFT_ENGINE_BASE_H #include "common/common.hh" #include "common/communicator.hh" #include "common/field_collection.hh" namespace muSpectre { /** * Virtual base class for FFT engines. To be implemented by all * FFT_engine implementations. */ - template + template class FFTEngineBase { public: constexpr static Dim_t sdim{DimS}; //!< spatial dimension of the cell - constexpr static Dim_t mdim{DimM}; //!< material dimension of the cell //! cell coordinates type using Ccoord = Ccoord_t; //! global FieldCollection using GFieldCollection_t = GlobalFieldCollection; //! local FieldCollection (for Fourier-space pixels) using LFieldCollection_t = LocalFieldCollection; //! Field type on which to apply the projection - using Field_t = TensorField; + using Field_t = TypedField; /** * Field type holding a Fourier-space representation of a * real-valued second-order tensor field */ - using Workspace_t = TensorField; + using Workspace_t = TypedField; /** * iterator over Fourier-space discretisation point */ using iterator = typename LFieldCollection_t::iterator; //! Default constructor FFTEngineBase() = delete; //! Constructor with cell resolutions - FFTEngineBase(Ccoord resolutions, Communicator comm=Communicator()); + 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: }; } // muSpectre #endif /* FFT_ENGINE_BASE_H */ diff --git a/src/fft/fftw_engine.cc b/src/fft/fftw_engine.cc index 3c98987..40fd5f5 100644 --- a/src/fft/fftw_engine.cc +++ b/src/fft/fftw_engine.cc @@ -1,155 +1,155 @@ /** * @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 * 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/ccoord_operations.hh" #include "fft/fftw_engine.hh" namespace muSpectre { - template - FFTWEngine::FFTWEngine(Ccoord resolutions, Communicator comm) - :Parent{resolutions, comm} + 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: CcoordOps::Pixels(this->fourier_resolutions)) { this->work_space_container.add_pixel(pixel); } } /* ---------------------------------------------------------------------- */ - template - void FFTWEngine::initialise(FFT_PlanFlags plan_flags) { + 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 = DimS; - std::array narr; + 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 = Field_t::nb_components; + int howmany = this->nb_components; //temporary buffer for plan size_t alloc_size = (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 { + template + FFTWEngine::~FFTWEngine() noexcept { fftw_destroy_plan(this->plan_fft); fftw_destroy_plan(this->plan_ifft); // TODO: 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) { + 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)) { throw std::runtime_error("size mismatch"); } fftw_execute_dft_r2c(this->plan_fft, field.data(), reinterpret_cast(this->work.data())); return this->work; } /* ---------------------------------------------------------------------- */ - template + template void - FFTWEngine::ifft (Field_t & field) const { + 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)) { 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; - template class FFTWEngine; + template class FFTWEngine; + template class FFTWEngine; } // muSpectre diff --git a/src/fft/fftw_engine.hh b/src/fft/fftw_engine.hh index 13907f6..8e099bd 100644 --- a/src/fft/fftw_engine.hh +++ b/src/fft/fftw_engine.hh @@ -1,90 +1,91 @@ /** * @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 * 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 FFTW_ENGINE_H #define FFTW_ENGINE_H #include "fft/fft_engine_base.hh" #include namespace muSpectre { /** * implements the `muSpectre::FftEngine_Base` interface using the * FFTW library */ - template - class FFTWEngine: public FFTEngineBase + template + class FFTWEngine: public FFTEngineBase { public: - using Parent = FFTEngineBase; //!< base class + 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, Communicator comm=Communicator()); + 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 virtual void initialise(FFT_PlanFlags plan_flags) override; //! forward transform virtual Workspace_t & fft(Field_t & field) override; //! inverse transform virtual 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 private: }; } // muSpectre #endif /* FFTW_ENGINE_H */ diff --git a/src/fft/fftwmpi_engine.cc b/src/fft/fftwmpi_engine.cc index f5d6bf2..1085f3d 100644 --- a/src/fft/fftwmpi_engine.cc +++ b/src/fft/fftwmpi_engine.cc @@ -1,235 +1,235 @@ /** * @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 * 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/ccoord_operations.hh" #include "fft/fftwmpi_engine.hh" namespace muSpectre { - template - int FFTWMPIEngine::nb_engines{0}; - - template - FFTWMPIEngine::FFTWMPIEngine(Ccoord resolutions, - Communicator comm) - :Parent{resolutions, comm} + 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::array narr; std::copy(this->domain_resolutions.begin(), this->domain_resolutions.end(), narr.begin()); - narr[DimS-1] = this->domain_resolutions[DimS-1]/2+1; + 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(DimS, narr.data(), - Field_t::nb_components, + 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< - DimS==2, - CcoordOps::Pixels, - CcoordOps::Pixels + Dim==2, + CcoordOps::Pixels, + CcoordOps::Pixels >(this->fourier_resolutions, this->fourier_locations)) { this->work_space_container.add_pixel(pixel); } } /* ---------------------------------------------------------------------- */ - template - void FFTWMPIEngine::initialise(FFT_PlanFlags plan_flags) { + 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 (long(this->work.size()*Field_t::nb_components) < this->workspace_size) { + if (long(this->work.size()*this->nb_components) < this->workspace_size) { this->work.set_pad_size(this->workspace_size - - Field_t::nb_components*this->work.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::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( - DimS, narr.data(), Field_t::nb_components, FFTW_MPI_DEFAULT_BLOCK, + 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( - DimS, narr.data(), Field_t::nb_components, FFTW_MPI_DEFAULT_BLOCK, + 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 { + 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: 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) { + 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)) { 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 = (Field_t::nb_components* - this->subdomain_resolutions[DimS-1]); - ptrdiff_t wstride = (Field_t::nb_components*2* - (this->subdomain_resolutions[DimS-1]/2+1)); - ptrdiff_t n = field.size()/this->subdomain_resolutions[DimS-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 + template void - FFTWMPIEngine::ifft (Field_t & field) const { + 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)) { 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{ - Field_t::nb_components*this->subdomain_resolutions[DimS-1] + this->nb_components*this->subdomain_resolutions[Dim-1] }; ptrdiff_t wstride{ - Field_t::nb_components*2*(this->subdomain_resolutions[DimS-1]/2+1) + this->nb_components*2*(this->subdomain_resolutions[Dim-1]/2+1) }; - ptrdiff_t n(field.size()/this->subdomain_resolutions[DimS-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; - template class FFTWMPIEngine; + template class FFTWMPIEngine; + template class FFTWMPIEngine; } // muSpectre diff --git a/src/fft/fftwmpi_engine.hh b/src/fft/fftwmpi_engine.hh index 7ce4fe7..0a8a3a1 100644 --- a/src/fft/fftwmpi_engine.hh +++ b/src/fft/fftwmpi_engine.hh @@ -1,93 +1,94 @@ /** * @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 * 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 FFTWMPI_ENGINE_H #define FFTWMPI_ENGINE_H #include "fft/fft_engine_base.hh" #include namespace muSpectre { /** * implements the `muSpectre::FFTEngineBase` interface using the * FFTW library */ - template - class FFTWMPIEngine: public FFTEngineBase + template + class FFTWMPIEngine: public FFTEngineBase { public: - using Parent = FFTEngineBase; //!< base class + 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, Communicator comm=Communicator()); + 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 virtual void initialise(FFT_PlanFlags plan_flags) override; //! forward transform virtual Workspace_t & fft(Field_t & field) override; //! inverse transform virtual 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 private: }; } // muSpectre #endif /* FFTWMPI_ENGINE_H */ diff --git a/src/fft/projection_base.cc b/src/fft/projection_base.cc index c291fc6..ec5455b 100644 --- a/src/fft/projection_base.cc +++ b/src/fft/projection_base.cc @@ -1,57 +1,58 @@ /** * @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 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 "fft/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"); - static_assert((DimM == FFTEngine::mdim), - "material 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) { fft_engine->initialise(flags); } template class ProjectionBase; template class ProjectionBase; template class ProjectionBase; } // muSpectre diff --git a/src/fft/projection_base.hh b/src/fft/projection_base.hh index 96bad7b..658b32c 100644 --- a/src/fft/projection_base.hh +++ b/src/fft/projection_base.hh @@ -1,169 +1,184 @@ /** * @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 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 PROJECTION_BASE_H #define PROJECTION_BASE_H #include "common/common.hh" #include "common/field_collection.hh" #include "common/field.hh" #include "fft/fft_engine_base.hh" #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 = 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 = typename FFTEngine::Field_t; + using Field_t = 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); //! 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 { 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: }; } // muSpectre #endif /* PROJECTION_BASE_H */ diff --git a/src/fft/projection_default.cc b/src/fft/projection_default.cc index 426ddf1..ca294f6 100644 --- a/src/fft/projection_default.cc +++ b/src/fft/projection_default.cc @@ -1,66 +1,73 @@ /** * @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 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 "fft/projection_default.hh" #include "fft/fft_engine_base.hh" 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)}, 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; } // muSpectre diff --git a/src/fft/projection_default.hh b/src/fft/projection_default.hh index 9c2cbab..4a5248e 100644 --- a/src/fft/projection_default.hh +++ b/src/fft/projection_default.hh @@ -1,99 +1,109 @@ /** * @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 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 PROJECTION_DEFAULT_H #define PROJECTION_DEFAULT_H #include "fft/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; //! local field collection for Fourier-space fields using LFieldCollection_t = LocalFieldCollection; //! Real space second order tensor fields (to be projected) - using Field_t = TensorField; + using Field_t = TypedField; //! Fourier-space field containing the projection operator itself using Proj_t = TensorField; //! iterable form of the operator using Proj_map = T4MatrixFieldMap; //! vectorized version of the Fourier-space second-order tensor field using Vector_map = 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) override final; Eigen::Map get_operator() override 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 override final; + + constexpr static Dim_t NbComponents() {return ipow(DimM, 2);} protected: Proj_t & Gfield; //!< field holding the operator Proj_map Ghat; //!< iterable version of operator private: }; } // muSpectre #endif /* PROJECTION_DEFAULT_H */ diff --git a/src/fft/projection_finite_strain_fast.cc b/src/fft/projection_finite_strain_fast.cc index dd3300c..60040f0 100644 --- a/src/fft/projection_finite_strain_fast.cc +++ b/src/fft/projection_finite_strain_fast.cc @@ -1,92 +1,100 @@ /** * @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 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 "fft/projection_finite_strain_fast.hh" #include "fft/fft_utils.hh" #include "common/tensor_algebra.hh" #include "common/iterators.hh" 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)}, 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) { Parent::initialise(flags); 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; } // muSpectre diff --git a/src/fft/projection_finite_strain_fast.hh b/src/fft/projection_finite_strain_fast.hh index 8a09407..861ef85 100644 --- a/src/fft/projection_finite_strain_fast.hh +++ b/src/fft/projection_finite_strain_fast.hh @@ -1,106 +1,115 @@ /** * @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 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 PROJECTION_FINITE_STRAIN_FAST_H #define PROJECTION_FINITE_STRAIN_FAST_H #include "fft/projection_base.hh" #include "common/common.hh" #include "common/field_collection.hh" #include "common/field_map.hh" 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; //! local field collection (for Fourier-space representations) using LFieldCollection_t = LocalFieldCollection; //! Real space second order tensor fields (to be projected) - using Field_t = TensorField; + using Field_t = TypedField; //! Fourier-space field containing the projection operator itself using Proj_t = TensorField; //! iterable form of the operator using Proj_map = MatrixFieldMap; //! iterable Fourier-space second-order tensor field using Grad_map = 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) virtual void initialise(FFT_PlanFlags flags = FFT_PlanFlags::estimate) override final; //! apply the projection operator to a field void apply_projection(Field_t & field) override final; Eigen::Map get_operator() override 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 override final; + + constexpr static Dim_t NbComponents(){return ipow(DimM, 2);} protected: Proj_t & xiField; //!< field of normalised wave vectors Proj_map xis; //!< iterable normalised wave vectors private: }; } // muSpectre #endif /* PROJECTION_FINITE_STRAIN_FAST_H */ diff --git a/src/materials/material_base.hh b/src/materials/material_base.hh index 1e78be3..9d1365c 100644 --- a/src/materials/material_base.hh +++ b/src/materials/material_base.hh @@ -1,161 +1,161 @@ /** * @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 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 MATERIAL_BASE_H #define MATERIAL_BASE_H #include "common/common.hh" #include "common/field.hh" #include "common/field_collection.hh" #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; //! 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 iterator = typename MFieldCollection_t::iterator; //!< pixel iterator //! polymorphic base class for fields only to be used for debugging using Field_t = internal::FieldBase; //! Full type for stress fields using StressField_t = TensorField; //! Full type for strain fields using StrainField_t = StressField_t; //! Full type for tangent stiffness fields fields using TangentField_t = TensorField; using Ccoord = Ccoord_t; //!< cell coordinates type //! Default constructor MaterialBase() = delete; //! Construct by name 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 tye need to overload add_pixel */ virtual void add_pixel(const Ccoord & ccooord); //! allocate memory, etc, but also: wipe history variables! - virtual void initialise(bool stiffness = false) = 0; + 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) = 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); //! computes stress and tangent moduli virtual void compute_stresses_tangent(const StrainField_t & F, StressField_t & P, TangentField_t & K, Formulation form) = 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); //! 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();} protected: const std::string name; //!< material's name (for output and debugging) MFieldCollection_t internal_fields{};//!< storage for internal variables private: }; } // muSpectre #endif /* MATERIAL_BASE_H */ diff --git a/src/materials/material_hyper_elasto_plastic1.cc b/src/materials/material_hyper_elasto_plastic1.cc index e774f47..9f4ecb7 100644 --- a/src/materials/material_hyper_elasto_plastic1.cc +++ b/src/materials/material_hyper_elasto_plastic1.cc @@ -1,77 +1,77 @@ /** * @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 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 "materials/material_hyper_elasto_plastic1.hh" namespace muSpectre { //----------------------------------------------------------------------------// 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()} {} /* ---------------------------------------------------------------------- */ 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(bool /*stiffness*/) { + 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 class MaterialHyperElastoPlastic1< twoD, twoD>; template class MaterialHyperElastoPlastic1< twoD, threeD>; template class MaterialHyperElastoPlastic1; } // muSpectre diff --git a/src/materials/material_hyper_elasto_plastic1.hh b/src/materials/material_hyper_elasto_plastic1.hh index 4e0ae06..a7ce609 100644 --- a/src/materials/material_hyper_elasto_plastic1.hh +++ b/src/materials/material_hyper_elasto_plastic1.hh @@ -1,307 +1,307 @@ /** * @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 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 MATERIAL_HYPER_ELASTO_PLASTIC1_H #define MATERIAL_HYPER_ELASTO_PLASTIC1_H #include "materials/material_muSpectre_base.hh" #include "materials/materials_toolbox.hh" #include "common/eigen_tools.hh" #include "common/statefield.hh" #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; //! expected map type for stress fields using StressMap_t = MatrixFieldMap; //! expected map type for tangent stiffness fields using TangentMap_t = 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; //! storage type for plastic flow measure (εₚ in the papers) using LScalarMap_t = StateFieldMap>; /** * storage type for for previous gradient Fᵗ and elastic left * Cauchy-Green deformation tensor bₑᵗ */ using LStrainMap_t = StateFieldMap< 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 */ template class MaterialHyperElastoPlastic1: public MaterialMuSpectre, DimS, DimM> { public: //! base class using Parent = MaterialMuSpectre , DimS, DimM>; /** * 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; //! 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 * εₚ */ template inline decltype(auto) evaluate_stress(grad_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 * εₚ */ template inline decltype(auto) evaluate_stress_tangent(grad_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 */ virtual void save_history_variables() override; /** * set the previous gradients to identity */ - virtual void initialise(bool stiffness=false) override final; + virtual void initialise() override final; /** * return the internals tuple */ typename traits::InternalVariables & get_internals() { return this->internal_variables;}; protected: /** * worker function computing stresses and internal variables */ template inline decltype(auto) stress_n_internals_worker(grad_t && F, StrainStRef_t& F_prev, StrainStRef_t& be_prev, FlowStRef_t& plast_flow); //! Local FieldCollection type for field storage using LColl_t = LocalFieldCollection; //! storage for cumulated plastic flow εₚ StateField> plast_flow_field; //! storage for previous gradient Fᵗ StateField> F_prev_field; //! storage for elastic left Cauchy-Green deformation tensor bₑᵗ 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 //! Field maps and state field maps over internal fields typename traits::InternalVariables internal_variables; private: }; //----------------------------------------------------------------------------// template template decltype(auto) MaterialHyperElastoPlastic1:: stress_n_internals_worker(grad_t && F, StrainStRef_t& F_prev, StrainStRef_t& be_prev, FlowStRef_t& eps_p) { // 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; auto && f{F*F_prev.old().inverse()}; Mat_t be_star{f*be_prev.old()*f.transpose()}; Mat_t ln_be_star{logm(std::move(be_star))}; 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()}; auto && tau_eq_star{std::sqrt(3*.5*(tau_d_star.array()* tau_d_star.transpose().array()).sum())}; Mat_t N_star{3*.5*tau_d_star/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)}; auto && tau{tau_star - 2*Del_gamma*this->mu*N_star}; /////auto && tau_eq{tau_eq_star - 3*this->mu*Del_gamma}; // update the previous values to the new ones F_prev.current() = F; ln_be_star -= 2*Del_gamma*N_star; be_prev.current() = expm(std::move(ln_be_star)); eps_p.current() += Del_gamma; // transmit info whether this is a plastic step or not bool is_plastic{phi_star > 0}; return std::tuple (std::move(tau), std::move(tau_eq_star), std::move(Del_gamma), std::move(N_star), std::move(is_plastic)); } //----------------------------------------------------------------------------// template template decltype(auto) MaterialHyperElastoPlastic1:: evaluate_stress(grad_t && F, StrainStRef_t F_prev, StrainStRef_t be_prev, FlowStRef_t eps_p) { auto retval(std::move(std::get<0>(this->stress_n_internals_worker (std::forward(F), F_prev, be_prev, eps_p)))); return retval; } //----------------------------------------------------------------------------// template template decltype(auto) MaterialHyperElastoPlastic1:: evaluate_stress_tangent(grad_t && F, StrainStRef_t F_prev, StrainStRef_t be_prev, FlowStRef_t eps_p) { //! after the stress computation, all internals are up to date auto && vals{this->stress_n_internals_worker (std::forward(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)}; if (is_plastic) { auto && a0 = Del_gamma*this->mu/tau_eq_star; auto && a1 = this->mu/(this->H + 3*this->mu); return std::make_tuple(std::move(tau), 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))}); } else { return std::make_tuple(std::move(tau), T4Mat{this->C}); } } } // muSpectre #endif /* MATERIAL_HYPER_ELASTO_PLASTIC1_H */ diff --git a/src/materials/material_muSpectre_base.hh b/src/materials/material_muSpectre_base.hh index 2e8117a..9fb5bea 100644 --- a/src/materials/material_muSpectre_base.hh +++ b/src/materials/material_muSpectre_base.hh @@ -1,718 +1,718 @@ /** * @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 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 MATERIAL_MUSPECTRE_BASE_H #define MATERIAL_MUSPECTRE_BASE_H #include "common/common.hh" #include "materials/material_base.hh" #include "materials/materials_toolbox.hh" #include "common/field_collection.hh" #include "common/field.hh" #include "common//utilities.hh" #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; //! traits for the CRTP subclass using traits = MaterialMuSpectre_traits; //! Default constructor MaterialMuSpectre() = delete; //! Construct by name 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); //! Copy assignment operator MaterialMuSpectre& operator=(const MaterialMuSpectre &other) = delete; //! Move assignment operator MaterialMuSpectre& operator=(MaterialMuSpectre &&other) = delete; //! allocate memory, etc - virtual void initialise(bool stiffness = false) override; + virtual void initialise() override; using Parent::compute_stresses; using Parent::compute_stresses_tangent; //! computes stress virtual void compute_stresses(const StrainField_t & F, StressField_t & P, Formulation form) override final; //! computes stress and tangent modulus virtual void compute_stresses_tangent(const StrainField_t & F, StressField_t & P, TangentField_t & K, Formulation form) override final; 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 with internal variables 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; cell.add_material(std::move(mat)); return mat_ref; } /* ---------------------------------------------------------------------- */ template void MaterialMuSpectre:: - initialise(bool /*stiffness*/) { + 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) { switch (form) { case Formulation::finite_strain: { this->template compute_stresses_worker(F, P); break; } case Formulation::small_strain: { this->template compute_stresses_worker(F, P); 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) { switch (form) { case Formulation::finite_strain: { this->template compute_stresses_worker(F, P, K); break; } case Formulation::small_strain: { this->template compute_stresses_worker(F, P, K); 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, 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 & F = std::get<0>(Strains); auto && strain = MatTB::convert_strain(F); // return value contains a tuple of rvalue_refs to both stress and tangent moduli Stresses = apply([&strain, &this_mat] (auto && ... internals) { return this_mat.evaluate_stress_tangent(std::move(strain), internals...);}, internal_variables); }; auto constitutive_law_finite_strain = [this] (Strains_t Strains, Stresses_t Stresses, 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: 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. // return value contains a tuple of rvalue_refs to both stress // and tangent moduli 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)); }; 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"); 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, 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 & F = std::get<0>(Strains); auto && strain = MatTB::convert_strain(F); // return value contains a tuple of rvalue_refs to both stress and tangent moduli auto & sigma = std::get<0>(Stresses); sigma = apply([&strain, &this_mat] (auto && ... internals) { return this_mat.evaluate_stress(std::move(strain), internals...);}, internal_variables); }; auto constitutive_law_finite_strain = [this] (Strains_t Strains, Stresses_t && Stresses, 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 & F = std::get<0>(Strains); auto && strain = MatTB::convert_strain(F); // TODO: 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. // return value contains a tuple of rvalue_refs to both stress // and tangent moduli auto && stress = apply([&strain, &this_mat] (auto && ... internals) { return this_mat.evaluate_stress(std::move(strain), internals...);}, internal_variables); auto & P = get<0>(Stresses); P = MatTB::PK1_stress (F, stress); }; iterable_proxy fields{*this, F, P}; 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"); 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, 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. **/ 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 private: }; //! 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:: iterator & MaterialMuSpectre::iterable_proxy::iterator:: operator++() { this->index++; return *this; } /* ---------------------------------------------------------------------- */ template template typename MaterialMuSpectre:: template iterable_proxy::iterator:: value_type MaterialMuSpectre::iterable_proxy::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 && 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(internals)); } } // muSpectre #endif /* MATERIAL_MUSPECTRE_BASE_H */ diff --git a/src/solver/CMakeLists.txt b/src/solver/CMakeLists.txt index 5090f84..040d5f5 100644 --- a/src/solver/CMakeLists.txt +++ b/src/solver/CMakeLists.txt @@ -1,37 +1,42 @@ # ============================================================================= # file CMakeLists.txt # # @author Till Junge # # @date 08 Jan 2018 # # @brief configuration for solvers # # @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 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. # ============================================================================= set (solvers_SRC + ${CMAKE_CURRENT_SOURCE_DIR}/solver_common.cc + ${CMAKE_CURRENT_SOURCE_DIR}/deprecated_solver_base.cc + ${CMAKE_CURRENT_SOURCE_DIR}/deprecated_solver_cg.cc + ${CMAKE_CURRENT_SOURCE_DIR}/deprecated_solver_cg_eigen.cc + ${CMAKE_CURRENT_SOURCE_DIR}/deprecated_solvers.cc ${CMAKE_CURRENT_SOURCE_DIR}/solver_base.cc - ${CMAKE_CURRENT_SOURCE_DIR}/solver_cg.cc - ${CMAKE_CURRENT_SOURCE_DIR}/solver_cg_eigen.cc ${CMAKE_CURRENT_SOURCE_DIR}/solvers.cc + ${CMAKE_CURRENT_SOURCE_DIR}/solver_cg.cc + ${CMAKE_CURRENT_SOURCE_DIR}/solver_eigen.cc ) target_sources(muSpectre PRIVATE ${solvers_SRC}) diff --git a/src/solver/solver_base.cc b/src/solver/deprecated_solver_base.cc similarity index 75% copy from src/solver/solver_base.cc copy to src/solver/deprecated_solver_base.cc index 79395db..bd7df31 100644 --- a/src/solver/solver_base.cc +++ b/src/solver/deprecated_solver_base.cc @@ -1,63 +1,63 @@ /** - * @file solver_base.cc + * @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 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 "solver/solver_base.hh" -#include "solver/solver_cg.hh" +#include "solver/deprecated_solver_base.hh" +#include "solver/deprecated_solver_cg.hh" #include "common/field.hh" #include "common/iterators.hh" #include #include namespace muSpectre { //----------------------------------------------------------------------------// template - SolverBase::SolverBase(Cell_t & cell, Real tol, Uint maxiter, + DeprecatedSolverBase::DeprecatedSolverBase(Cell_t & cell, Real tol, Uint maxiter, bool verbose ) : cell{cell}, tol{tol}, maxiter{maxiter}, verbose{verbose} {} /* ---------------------------------------------------------------------- */ template - void SolverBase::reset_counter() { + void DeprecatedSolverBase::reset_counter() { this->counter = 0; } /* ---------------------------------------------------------------------- */ template - Uint SolverBase::get_counter() const { + Uint DeprecatedSolverBase::get_counter() const { return this->counter; } - template class SolverBase; - //template class SolverBase; - template class SolverBase; + template class DeprecatedSolverBase; + //template class DeprecatedSolverBase; + template class DeprecatedSolverBase; } // muSpectre diff --git a/src/solver/solver_base.hh b/src/solver/deprecated_solver_base.hh similarity index 86% copy from src/solver/solver_base.hh copy to src/solver/deprecated_solver_base.hh index 1d82b33..94e3939 100644 --- a/src/solver/solver_base.hh +++ b/src/solver/deprecated_solver_base.hh @@ -1,148 +1,148 @@ /** - * @file solver_base.hh + * @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 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 SOLVER_BASE_H -#define SOLVER_BASE_H +#ifndef DEPRECATED_SOLVER_BASE_H +#define DEPRECATED_SOLVER_BASE_H -#include "solver/solver_error.hh" +#include "solver/solver_common.hh" #include "common/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 SolverBase + 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; //! 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 - SolverBase() = delete; + DeprecatedSolverBase() = delete; //! Constructor with domain resolutions - SolverBase(Cell_t & cell, Real tol, Uint maxiter=0, bool verbose =false); + DeprecatedSolverBase(Cell_t & cell, Real tol, Uint maxiter=0, bool verbose =false); //! Copy constructor - SolverBase(const SolverBase &other) = delete; + DeprecatedSolverBase(const DeprecatedSolverBase &other) = delete; //! Move constructor - SolverBase(SolverBase &&other) = default; + DeprecatedSolverBase(DeprecatedSolverBase &&other) = default; //! Destructor - virtual ~SolverBase() = default; + virtual ~DeprecatedSolverBase() = default; //! Copy assignment operator - SolverBase& operator=(const SolverBase &other) = delete; + DeprecatedSolverBase& operator=(const DeprecatedSolverBase &other) = delete; //! Move assignment operator - SolverBase& operator=(SolverBase &&other) = default; + 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: }; } // muSpectre -#endif /* SOLVER_BASE_H */ +#endif /* DEPRECATED_SOLVER_BASE_H */ diff --git a/src/solver/solver_cg.cc b/src/solver/deprecated_solver_cg.cc similarity index 81% copy from src/solver/solver_cg.cc copy to src/solver/deprecated_solver_cg.cc index 98072ad..e71f4e6 100644 --- a/src/solver/solver_cg.cc +++ b/src/solver/deprecated_solver_cg.cc @@ -1,129 +1,129 @@ /** - * @file solver_cg.cc + * @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 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 "solver/solver_cg.hh" -#include "solver/solver_error.hh" +#include "solver/deprecated_solver_cg.hh" +#include "solver/solver_common.hh" #include #include #include namespace muSpectre { /* ---------------------------------------------------------------------- */ template - SolverCG::SolverCG(Cell_t& cell, Real tol, Uint maxiter, + DeprecatedSolverCG::DeprecatedSolverCG(Cell_t& cell, Real tol, Uint maxiter, bool verbose) :Parent(cell, tol, maxiter, verbose), r_k{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)} {} /* ---------------------------------------------------------------------- */ template - void SolverCG::solve(const Field_t & rhs, + void DeprecatedSolverCG::solve(const Field_t & rhs, Field_t & x_f) { x_f.eigenvec() = this->solve(rhs.eigenvec(), x_f.eigenvec()); }; //----------------------------------------------------------------------------// template - typename SolverCG::SolvVectorOut - SolverCG::solve(const SolvVectorInC rhs, SolvVectorIn x_0) { + typename DeprecatedSolverCG::SolvVectorOut + DeprecatedSolverCG::solve(const SolvVectorInC rhs, SolvVectorIn x_0) { const 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 x(x_0.data(), r.rows(), r.cols()); + 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(rhs.data(), r.rows(), r.cols()); + 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; 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 SolverCG::Tg_req_t - SolverCG::get_tangent_req() const { + typename DeprecatedSolverCG::Tg_req_t + DeprecatedSolverCG::get_tangent_req() const { return tangent_requirement; } - template class SolverCG; - //template class SolverCG; - template class SolverCG; + template class DeprecatedSolverCG; + //template class DeprecatedSolverCG; + template class DeprecatedSolverCG; } // muSpectre diff --git a/src/solver/solver_cg.hh b/src/solver/deprecated_solver_cg.hh similarity index 78% copy from src/solver/solver_cg.hh copy to src/solver/deprecated_solver_cg.hh index bd04de8..173f41b 100644 --- a/src/solver/solver_cg.hh +++ b/src/solver/deprecated_solver_cg.hh @@ -1,114 +1,114 @@ /** - * @file solver_cg.hh + * @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 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 SOLVER_CG_H -#define SOLVER_CG_H +#ifndef DEPRECATED_SOLVER_CG_H +#define DEPRECATED_SOLVER_CG_H -#include "solver/solver_base.hh" +#include "solver/deprecated_solver_base.hh" #include "common/communicator.hh" #include "common/field.hh" #include namespace muSpectre { /** - * implements the `muSpectre::SolverBase` interface using a + * 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::SolverCGEigen`. + * `muSpectre::DeprecatedSolverCGEigen`. */ template - class SolverCG: public SolverBase + class DeprecatedSolverCG: public DeprecatedSolverBase { public: - using Parent = SolverBase; //!< base class + 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< typename Parent::Collection_t, Real, secondOrder, DimM>; //! conjugate gradient needs directional stiffness constexpr static Tg_req_t tangent_requirement{Tg_req_t::NeedEffect}; //! Default constructor - SolverCG() = delete; + DeprecatedSolverCG() = delete; //! Constructor with domain resolutions, etc, - SolverCG(Cell_t& cell, Real tol, Uint maxiter=0, bool verbose=false); + DeprecatedSolverCG(Cell_t& cell, Real tol, Uint maxiter=0, bool verbose=false); //! Copy constructor - SolverCG(const SolverCG &other) = delete; + DeprecatedSolverCG(const DeprecatedSolverCG &other) = delete; //! Move constructor - SolverCG(SolverCG &&other) = default; + DeprecatedSolverCG(DeprecatedSolverCG &&other) = default; //! Destructor - virtual ~SolverCG() = default; + virtual ~DeprecatedSolverCG() = default; //! Copy assignment operator - SolverCG& operator=(const SolverCG &other) = delete; + DeprecatedSolverCG& operator=(const DeprecatedSolverCG &other) = delete; //! Move assignment operator - SolverCG& operator=(SolverCG &&other) = default; + DeprecatedSolverCG& operator=(DeprecatedSolverCG &&other) = default; bool has_converged() const override 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) override final; std::string name() const override final {return "CG";} protected: //! returns `muSpectre::Tg_req_t::NeedEffect` Tg_req_t get_tangent_req() const override 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 private: }; } // muSpectre -#endif /* SOLVER_CG_H */ +#endif /* DEPRECATED_SOLVER_CG_H */ diff --git a/src/solver/deprecated_solver_cg_eigen.cc b/src/solver/deprecated_solver_cg_eigen.cc new file mode 100644 index 0000000..2d73b29 --- /dev/null +++ b/src/solver/deprecated_solver_cg_eigen.cc @@ -0,0 +1,110 @@ +/** + * @file deprecated_solver_cg_eigen.cc + * + * @author Till Junge + * + * @date 19 Jan 2018 + * + * @brief implementation for binding to Eigen's conjugate gradient solver + * + * Copyright (C) 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 "deprecated_solver_cg_eigen.hh" + +#include +#include + +namespace muSpectre { + + //----------------------------------------------------------------------------// + template + DeprecatedSolverEigen::DeprecatedSolverEigen(Cell_t& cell, Real tol, Uint maxiter, + bool verbose) + :Parent(cell, tol, maxiter, verbose), + adaptor{cell.get_adaptor()}, + solver{} + {} + + //----------------------------------------------------------------------------// + template + void + DeprecatedSolverEigen::initialise() { + this->solver.setTolerance(this->tol); + this->solver.setMaxIterations(this->maxiter); + this->solver.compute(this->adaptor); + } + + //----------------------------------------------------------------------------// + template + typename DeprecatedSolverEigen::SolvVectorOut + DeprecatedSolverEigen::solve(const SolvVectorInC rhs, SolvVectorIn x_0) { + auto & this_solver = static_cast (*this); + SolvVectorOut retval = this->solver.solveWithGuess(rhs, x_0); + this->counter += this->solver.iterations(); + if (this->solver.info() != Eigen::Success) { + std::stringstream err {}; + err << this_solver.name() << " has not converged," + << " After " << this->solver.iterations() << " steps, the solver " + << " FAILED with |r|/|b| = " + << std::setw(15) << this->solver.error() + << ", cg_tol = " << this->tol << std::endl; + throw ConvergenceError(err.str()); + } + if (this->verbose) { + std::cout << " After " << this->solver.iterations() << " " + << this_solver.name() << " steps, |r|/|b| = " + << std::setw(15) << this->solver.error() + << ", cg_tol = " << this->tol << std::endl; + } + return retval; + } + + /* ---------------------------------------------------------------------- */ + template + typename DeprecatedSolverEigen::Tg_req_t + DeprecatedSolverEigen::get_tangent_req() const { + return tangent_requirement; + } + + template class DeprecatedSolverEigen, twoD, twoD>; + template class DeprecatedSolverEigen, threeD, threeD>; + template class DeprecatedSolverCGEigen; + template class DeprecatedSolverCGEigen; + + template class DeprecatedSolverEigen, twoD, twoD>; + template class DeprecatedSolverEigen, threeD, threeD>; + template class DeprecatedSolverGMRESEigen; + template class DeprecatedSolverGMRESEigen; + + template class DeprecatedSolverEigen, twoD, twoD>; + template class DeprecatedSolverEigen, threeD, threeD>; + template class DeprecatedSolverBiCGSTABEigen; + template class DeprecatedSolverBiCGSTABEigen; + + template class DeprecatedSolverEigen, twoD, twoD>; + template class DeprecatedSolverEigen, threeD, threeD>; + template class DeprecatedSolverDGMRESEigen; + template class DeprecatedSolverDGMRESEigen; + + template class DeprecatedSolverEigen, twoD, twoD>; + template class DeprecatedSolverEigen, threeD, threeD>; + template class DeprecatedSolverMINRESEigen; + template class DeprecatedSolverMINRESEigen; + +} // muSpectre diff --git a/src/solver/solver_cg_eigen.hh b/src/solver/deprecated_solver_cg_eigen.hh similarity index 55% rename from src/solver/solver_cg_eigen.hh rename to src/solver/deprecated_solver_cg_eigen.hh index 65dd93b..fb4374b 100644 --- a/src/solver/solver_cg_eigen.hh +++ b/src/solver/deprecated_solver_cg_eigen.hh @@ -1,242 +1,242 @@ /** - * @file solver_cg_eigen.hh + * @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 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 SOLVER_EIGEN_H -#define SOLVER_EIGEN_H +#ifndef DEPRECATED_SOLVER_EIGEN_H +#define DEPRECATED_SOLVER_EIGEN_H -#include "solver/solver_base.hh" +#include "solver/deprecated_solver_base.hh" #include #include #include namespace muSpectre { - template - class SolverEigen; + template + class DeprecatedSolverEigen; template - class SolverCGEigen; + class DeprecatedSolverCGEigen; template - class SolverGMRESEigen; + class DeprecatedSolverGMRESEigen; template - class SolverBiCGSTABEigen; + class DeprecatedSolverBiCGSTABEigen; template - class SolverDGMRESEigen; + class DeprecatedSolverDGMRESEigen; template - class SolverMINRESEigen; + class DeprecatedSolverMINRESEigen; namespace internal { - template - struct Solver_traits { + template + struct DeprecatedSolver_traits { }; //! traits for the Eigen conjugate gradient solver template - struct Solver_traits> { - //! Eigen Iterative Solver - using Solver = - Eigen::ConjugateGradient, + struct DeprecatedSolver_traits> { + //! Eigen Iterative DeprecatedSolver + using DeprecatedSolver = + Eigen::ConjugateGradient, DimS, DimM>::Adaptor, Eigen::Lower|Eigen::Upper, Eigen::IdentityPreconditioner>; }; //! traits for the Eigen GMRES solver template - struct Solver_traits> { - //! Eigen Iterative Solver - using Solver = - Eigen::GMRES, + struct DeprecatedSolver_traits> { + //! Eigen Iterative DeprecatedSolver + using DeprecatedSolver = + Eigen::GMRES, DimS, DimM>::Adaptor, Eigen::IdentityPreconditioner>; }; //! traits for the Eigen BiCGSTAB solver template - struct Solver_traits> { - //! Eigen Iterative Solver - using Solver = - Eigen::BiCGSTAB, + struct DeprecatedSolver_traits> { + //! Eigen Iterative DeprecatedSolver + using DeprecatedSolver = + Eigen::BiCGSTAB, DimS, DimM>::Adaptor, Eigen::IdentityPreconditioner>; }; //! traits for the Eigen DGMRES solver template - struct Solver_traits> { - //! Eigen Iterative Solver - using Solver = - Eigen::DGMRES, + struct DeprecatedSolver_traits> { + //! Eigen Iterative DeprecatedSolver + using DeprecatedSolver = + Eigen::DGMRES, DimS, DimM>::Adaptor, Eigen::IdentityPreconditioner>; }; //! traits for the Eigen MINRES solver template - struct Solver_traits> { - //! Eigen Iterative Solver - using Solver = - Eigen::MINRES, + struct DeprecatedSolver_traits> { + //! Eigen Iterative DeprecatedSolver + using DeprecatedSolver = + Eigen::MINRES, DimS, DimM>::Adaptor, Eigen::Lower|Eigen::Upper, Eigen::IdentityPreconditioner>; }; } // internal /** * base class for iterative solvers from Eigen */ - template - class SolverEigen: public SolverBase + template + class DeprecatedSolverEigen: public DeprecatedSolverBase { public: - using Parent = SolverBase; //!< base class + 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 Solver = typename internal::Solver_traits::Solver; + using DeprecatedSolver = typename internal::DeprecatedSolver_traits::DeprecatedSolver; //! All Eigen solvers need directional stiffness constexpr static Tg_req_t tangent_requirement{Tg_req_t::NeedEffect}; //! Default constructor - SolverEigen() = delete; + DeprecatedSolverEigen() = delete; //! Constructor with domain resolutions, etc, - SolverEigen(Cell_t& cell, Real tol, Uint maxiter=0, bool verbose =false); + DeprecatedSolverEigen(Cell_t& cell, Real tol, Uint maxiter=0, bool verbose =false); //! Copy constructor - SolverEigen(const SolverEigen &other) = delete; + DeprecatedSolverEigen(const DeprecatedSolverEigen &other) = delete; //! Move constructor - SolverEigen(SolverEigen &&other) = default; + DeprecatedSolverEigen(DeprecatedSolverEigen &&other) = default; //! Destructor - virtual ~SolverEigen() = default; + virtual ~DeprecatedSolverEigen() = default; //! Copy assignment operator - SolverEigen& operator=(const SolverEigen &other) = delete; + DeprecatedSolverEigen& operator=(const DeprecatedSolverEigen &other) = delete; //! Move assignment operator - SolverEigen& operator=(SolverEigen &&other) = default; + DeprecatedSolverEigen& operator=(DeprecatedSolverEigen &&other) = default; //! returns whether the solver has converged bool has_converged() const override final {return this->solver.info() == Eigen::Success;} //! Allocate fields used during the solution void initialise() override final; //! executes the solver SolvVectorOut solve(const SolvVectorInC rhs, SolvVectorIn x_0) override final; protected: //! returns `muSpectre::Tg_req_t::NeedEffect` Tg_req_t get_tangent_req() const override final; Adaptor adaptor; //!< cell handle - Solver solver; //!< Eigen's Iterative solver + DeprecatedSolver solver; //!< Eigen's Iterative solver }; /** * Binding to Eigen's conjugate gradient solver */ template - class SolverCGEigen: - public SolverEigen, DimS, DimM> { + class DeprecatedSolverCGEigen: + public DeprecatedSolverEigen, DimS, DimM> { public: - using SolverEigen, DimS, DimM>::SolverEigen; + using DeprecatedSolverEigen, DimS, DimM>::DeprecatedSolverEigen; std::string name() const override final {return "CG";} }; /** * Binding to Eigen's GMRES solver */ template - class SolverGMRESEigen: - public SolverEigen, DimS, DimM> { + class DeprecatedSolverGMRESEigen: + public DeprecatedSolverEigen, DimS, DimM> { public: - using SolverEigen, DimS, DimM>::SolverEigen; + using DeprecatedSolverEigen, DimS, DimM>::DeprecatedSolverEigen; std::string name() const override final {return "GMRES";} }; /** * Binding to Eigen's BiCGSTAB solver */ template - class SolverBiCGSTABEigen: - public SolverEigen, DimS, DimM> { + class DeprecatedSolverBiCGSTABEigen: + public DeprecatedSolverEigen, DimS, DimM> { public: - using SolverEigen, DimS, DimM>::SolverEigen; - //! Solver's name + using DeprecatedSolverEigen, DimS, DimM>::DeprecatedSolverEigen; + //! DeprecatedSolver's name std::string name() const override final {return "BiCGSTAB";} }; /** * Binding to Eigen's DGMRES solver */ template - class SolverDGMRESEigen: - public SolverEigen, DimS, DimM> { + class DeprecatedSolverDGMRESEigen: + public DeprecatedSolverEigen, DimS, DimM> { public: - using SolverEigen, DimS, DimM>::SolverEigen; - //! Solver's name + using DeprecatedSolverEigen, DimS, DimM>::DeprecatedSolverEigen; + //! DeprecatedSolver's name std::string name() const override final {return "DGMRES";} }; /** * Binding to Eigen's MINRES solver */ template - class SolverMINRESEigen: - public SolverEigen, DimS, DimM> { + class DeprecatedSolverMINRESEigen: + public DeprecatedSolverEigen, DimS, DimM> { public: - using SolverEigen, DimS, DimM>::SolverEigen; - //! Solver's name + using DeprecatedSolverEigen, DimS, DimM>::DeprecatedSolverEigen; + //! DeprecatedSolver's name std::string name() const override final {return "MINRES";} }; } // muSpectre -#endif /* SOLVER_EIGEN_H */ +#endif /* DEPRECATED_SOLVER_EIGEN_H */ diff --git a/src/solver/solvers.cc b/src/solver/deprecated_solvers.cc similarity index 84% copy from src/solver/solvers.cc copy to src/solver/deprecated_solvers.cc index 94e3b60..447a2a4 100644 --- a/src/solver/solvers.cc +++ b/src/solver/deprecated_solvers.cc @@ -1,432 +1,416 @@ /** * @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 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 "solver/solvers.hh" -#include "solver/solver_cg.hh" +#include "solver/deprecated_solvers.hh" +#include "solver/deprecated_solver_cg.hh" #include "common/iterators.hh" #include #include #include namespace muSpectre { template std::vector - de_geus (CellBase & cell, const GradIncrements & delFs, - SolverBase & solver, Real newton_tol, - Real equil_tol, - Dim_t verbose) { + 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>()}; solver_fields->initialise(cell.get_subdomain_resolutions(), cell.get_subdomain_locations()); // Corresponds to symbol δF or δε auto & incrF{make_field("δF", *solver_fields)}; // Corresponds to symbol ΔF or Δε auto & DeltaF{make_field("ΔF", *solver_fields)}; // field to store the rhs for cg calculations auto & rhs{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 << " =" <(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{}; - // initialise materials - constexpr bool need_tangent{true}; - cell.initialise_materials(need_tangent); - 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()}); // store history variables here cell.save_history_variables(); } return ret_val; } //! instantiation for two-dimensional cells template std::vector - de_geus (CellBase & cell, const GradIncrements& delF0, - SolverBase & solver, Real newton_tol, - Real equil_tol, - Dim_t verbose); - - // template typename CellBase::StrainField_t & - // de_geus (CellBase & cell, const GradIncrements& delF0, - // const Real cg_tol, const Real newton_tol, Uint maxiter, - // Dim_t verbose); + 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 - de_geus (CellBase & cell, const GradIncrements& delF0, - SolverBase & solver, Real newton_tol, - Real equil_tol, - Dim_t verbose); + deprecated_de_geus (CellBase & cell, + const GradIncrements& delF0, + DeprecatedSolverBase & solver, + Real newton_tol, + Real equil_tol, + Dim_t verbose); /* ---------------------------------------------------------------------- */ template std::vector - newton_cg (CellBase & cell, const GradIncrements & delFs, - SolverBase & solver, Real newton_tol, - Real equil_tol, - Dim_t verbose) { + 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>()}; solver_fields->initialise(cell.get_subdomain_resolutions(), cell.get_subdomain_locations()); // Corresponds to symbol δF or δε auto & incrF{make_field("δF", *solver_fields)}; // field to store the rhs for cg calculations auto & rhs{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 = "Fy"; + 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 << " =" <(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{}; - // initialise materials - constexpr bool need_tangent{true}; - cell.initialise_materials(need_tangent); - 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()}); //store history variables for next load increment cell.save_history_variables(); } return ret_val; } //! instantiation for two-dimensional cells template std::vector - newton_cg (CellBase & cell, const GradIncrements& delF0, - SolverBase & solver, Real newton_tol, - Real equil_tol, - Dim_t verbose); - - // template typename CellBase::StrainField_t & - // newton_cg (CellBase & cell, const GradIncrements& delF0, - // const Real cg_tol, const Real newton_tol, Uint maxiter, - // Dim_t verbose); + 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 - newton_cg (CellBase & cell, const GradIncrements& delF0, - SolverBase & solver, Real newton_tol, - Real equil_tol, - Dim_t verbose); - - - /* ---------------------------------------------------------------------- */ - bool check_symmetry(const Eigen::Ref& eps, - Real rel_tol){ - return (rel_tol >= (eps-eps.transpose()).matrix().norm()/eps.matrix().norm() || - rel_tol >= eps.matrix().norm()); - } - + deprecated_newton_cg (CellBase & cell, + const GradIncrements& delF0, + DeprecatedSolverBase & solver, + Real newton_tol, + Real equil_tol, + Dim_t verbose); } // muSpectre diff --git a/src/solver/deprecated_solvers.hh b/src/solver/deprecated_solvers.hh new file mode 100644 index 0000000..9dd9327 --- /dev/null +++ b/src/solver/deprecated_solvers.hh @@ -0,0 +1,104 @@ +/** + * @file solvers.hh + * + * @author Till Junge + * + * @date 20 Dec 2017 + * + * @brief Free functions for solving + * + * 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 DEPRECATED_SOLVERS_H +#define DEPRECATED_SOLVERS_H + +#include "solver/solver_common.hh" +#include "solver/deprecated_solver_base.hh" + +#include + +#include +#include + +namespace muSpectre { + + /* ---------------------------------------------------------------------- */ + /** + * Uses the Newton-conjugate Gradient method to find the static + * equilibrium of a cell given a series of mean applied strains + */ + template + std::vector + deprecated_newton_cg (CellBase & cell, + const GradIncrements & delF0, + DeprecatedSolverBase & solver, + Real newton_tol, + Real equil_tol, + Dim_t verbose = 0); + + /* ---------------------------------------------------------------------- */ + /** + * Uses the Newton-conjugate Gradient method to find the static + * equilibrium of a cell given a mean applied strain + */ + template + inline OptimizeResult + deprecated_newton_cg (CellBase & cell, const Grad_t & delF0, + DeprecatedSolverBase & solver, + Real newton_tol, + Real equil_tol, + Dim_t verbose = 0){ + return deprecated_newton_cg(cell, GradIncrements{delF0}, + solver, newton_tol, equil_tol, verbose)[0]; + } + + /* ---------------------------------------------------------------------- */ + /** + * Uses the method proposed by de Geus method to find the static + * equilibrium of a cell given a series of mean applied strains + */ + template + std::vector + deprecated_de_geus (CellBase & cell, + const GradIncrements & delF0, + DeprecatedSolverBase & solver, + Real newton_tol, + Real equil_tol, + Dim_t verbose = 0); + + /* ---------------------------------------------------------------------- */ + /** + * Uses the method proposed by de Geus method to find the static + * equilibrium of a cell given a mean applied strain + */ + template + OptimizeResult + deprecated_de_geus (CellBase & cell, const Grad_t & delF0, + DeprecatedSolverBase & solver, + Real newton_tol, + Real equil_tol, + Dim_t verbose = 0){ + return deprecated_de_geus(cell, GradIncrements{delF0}, + solver, newton_tol, equil_tol, verbose)[0]; + } + + +} // muSpectre + +#endif /* DEPRECATED_SOLVERS_H */ diff --git a/src/solver/solver_base.cc b/src/solver/solver_base.cc index 79395db..ff3b889 100644 --- a/src/solver/solver_base.cc +++ b/src/solver/solver_base.cc @@ -1,63 +1,65 @@ /** - * @file solver_base.cc + * file solver_base.cc * * @author Till Junge * - * @date 18 Dec 2017 + * @date 24 Apr 2018 * - * @brief definitions for solvers + * @brief implementation of SolverBase * - * Copyright © 2017 Till Junge + * @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 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 "solver/solver_base.hh" -#include "solver/solver_cg.hh" -#include "common/field.hh" -#include "common/iterators.hh" - -#include -#include - namespace muSpectre { - //----------------------------------------------------------------------------// - template - SolverBase::SolverBase(Cell_t & cell, Real tol, Uint maxiter, - bool verbose ) - : cell{cell}, tol{tol}, maxiter{maxiter}, verbose{verbose} + /* ---------------------------------------------------------------------- */ + SolverBase::SolverBase(Cell & cell, Real tol, Uint maxiter, bool verbose): + cell(cell), tol{tol}, maxiter{maxiter}, verbose{verbose} {} + /* ---------------------------------------------------------------------- */ + bool SolverBase::has_converged() const { + return this->converged; + } /* ---------------------------------------------------------------------- */ - template - void SolverBase::reset_counter() { + void SolverBase::reset_counter() { this->counter = 0; + this->converged = false; } /* ---------------------------------------------------------------------- */ - template - Uint SolverBase::get_counter() const { + Uint SolverBase::get_counter() const { return this->counter; } - template class SolverBase; - //template class SolverBase; - template class SolverBase; + /* ---------------------------------------------------------------------- */ + Real SolverBase::get_tol() const { + return this->tol; + } + + /* ---------------------------------------------------------------------- */ + Uint SolverBase::get_maxiter() const { + return this->maxiter; + } } // muSpectre diff --git a/src/solver/solver_base.hh b/src/solver/solver_base.hh index 1d82b33..331ecbf 100644 --- a/src/solver/solver_base.hh +++ b/src/solver/solver_base.hh @@ -1,148 +1,120 @@ /** - * @file solver_base.hh + * file solver_base.hh * * @author Till Junge * - * @date 18 Dec 2017 + * @date 24 Apr 2018 * - * @brief Base class for solvers + * @brief Base class for iterative solvers for linear systems of equations * - * Copyright © 2017 Till Junge + * @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 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 SOLVER_BASE_H #define SOLVER_BASE_H -#include "solver/solver_error.hh" -#include "common/common.hh" +#include "solver/solver_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 + * Virtual base class for solvers. An implementation of this interface + * can be used with the solution strategies in solvers.hh */ - template class SolverBase { 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; + + //! underlying vector type + using Vector_t = Eigen::Matrix; //! Input vector for solvers - using SolvVectorIn = Eigen::Ref; + using Vector_ref = Eigen::Ref; //! Input vector for solvers - using SolvVectorInC = Eigen::Ref; + using ConstVector_ref = Eigen::Ref; //! Output vector for solvers - using SolvVectorOut = Eigen::VectorXd; - + using Vector_map = Eigen::Map; //! Default constructor SolverBase() = delete; - //! Constructor with domain resolutions - SolverBase(Cell_t & cell, Real tol, Uint maxiter=0, bool verbose =false); + /** + * Constructor takes a Cell, tolerance, max number of iterations + * and verbosity flag as input + */ + SolverBase(Cell & cell, Real tol, Uint maxiter, bool verbose=false); //! Copy constructor SolverBase(const SolverBase &other) = delete; //! Move constructor SolverBase(SolverBase &&other) = default; //! Destructor virtual ~SolverBase() = default; //! Copy assignment operator SolverBase& operator=(const SolverBase &other) = delete; //! Move assignment operator SolverBase& operator=(SolverBase &&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);} + virtual void initialise() = 0; //! returns whether the solver has converged - virtual bool has_converged() const = 0; + bool has_converged() const ; //! 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; + //! returns the max number of iterations + Uint get_maxiter() const; - //! return a reference to the cell - Cell_t & get_cell() {return cell;} + //! returns the resolution tolerance + Real get_tol() const; - //! 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;} + //! returns the solver's name (i.e. 'CG', 'GMRES', etc) + virtual std::string get_name() const = 0; - //! 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; + //! run the solve operation + virtual Vector_map solve(const ConstVector_ref rhs) = 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{}; + Cell & cell; //!< reference to the problem's cell + Real tol; //!< convergence tolerance + Uint maxiter; //!< maximum allowed number of iterations + bool verbose; //!< whether to write information to the stdout + Uint counter{0}; //!< iteration counter + bool converged{false}; //!< whether the solver has converged + private: }; + } // muSpectre #endif /* SOLVER_BASE_H */ diff --git a/src/solver/solver_cg.cc b/src/solver/solver_cg.cc index 98072ad..2b38b29 100644 --- a/src/solver/solver_cg.cc +++ b/src/solver/solver_cg.cc @@ -1,129 +1,109 @@ /** - * @file solver_cg.cc + * file solver_cg.cc * * @author Till Junge * - * @date 20 Dec 2017 + * @date 24 Apr 2018 * - * @brief Implementation of cg solver + * @brief implements SolverCG * - * Copyright © 2017 Till Junge + * @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 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 "solver/solver_cg.hh" -#include "solver/solver_error.hh" +#include "common/communicator.hh" #include -#include #include + namespace muSpectre { /* ---------------------------------------------------------------------- */ - template - SolverCG::SolverCG(Cell_t& cell, Real tol, Uint maxiter, - bool verbose) - :Parent(cell, tol, maxiter, verbose), - r_k{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)} + 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()) {} - /* ---------------------------------------------------------------------- */ - template - void SolverCG::solve(const Field_t & rhs, - Field_t & x_f) { - x_f.eigenvec() = this->solve(rhs.eigenvec(), x_f.eigenvec()); - }; - - //----------------------------------------------------------------------------// - template - typename SolverCG::SolvVectorOut - SolverCG::solve(const SolvVectorInC rhs, SolvVectorIn x_0) { + auto SolverCG::solve(const ConstVector_ref rhs) -> Vector_map { + this->x_k.setZero(); const 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 x(x_0.data(), r.rows(), r.cols()); - - // initialisation of algo - r = this->cell.directional_stiffness_with_copy(x); - r -= typename Field_t::ConstEigenMap(rhs.data(), r.rows(), r.cols()); - p = -r; + // 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((r*r).sum()); + + 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 = 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); + this->Ap_k = this->cell.evaluate_projected_directional_stiffness(this->p_k); - Real alpha = rdr/comm.sum((p*Ap).sum()); + Real alpha = rdr/comm.sum(this->p_k.dot(this->Ap_k)); - x += alpha * p; - r += alpha * Ap; + this->x_k += alpha * this->p_k; + this->r_k += alpha * this->Ap_k; - Real new_rdr = comm.sum((r*r).sum()); + 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; } - p = -r+beta*p; + this->p_k = - this->r_k + beta * this->p_k; } + if (rdr < tol2) { - this->converged=true; + this->converged = true; } else { - std::stringstream err {}; + 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; + return Vector_map(this->x_k.data(), this->x_k.size()); } - /* ---------------------------------------------------------------------- */ - template - typename SolverCG::Tg_req_t - SolverCG::get_tangent_req() const { - return tangent_requirement; - } - template class SolverCG; - //template class SolverCG; - template class SolverCG; } // muSpectre diff --git a/src/solver/solver_cg.hh b/src/solver/solver_cg.hh index bd04de8..3a803ea 100644 --- a/src/solver/solver_cg.hh +++ b/src/solver/solver_cg.hh @@ -1,114 +1,105 @@ /** - * @file solver_cg.hh + * file solver_cg.hh * * @author Till Junge * - * @date 20 Dec 2017 + * @date 24 Apr 2018 * - * @brief class for a simple implementation of a conjugate gradient - * solver. This follows algorithm 5.2 in Nocedal's Numerical - * Optimization (p 112) + * @brief class fo a simple implementation of a conjugate gradient solver. + * This follows algorithm 5.2 in Nocedal's Numerical Optimization + * (p 112) * - * Copyright © 2017 Till Junge + * @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 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 SOLVER_CG_H #define SOLVER_CG_H #include "solver/solver_base.hh" -#include "common/communicator.hh" -#include "common/field.hh" - -#include namespace muSpectre { /** * implements the `muSpectre::SolverBase` 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::SolverCGEigen`. */ - template - class SolverCG: public SolverBase + class SolverCG: public SolverBase { public: - using Parent = SolverBase; //!< base class + using Parent = SolverBase; //!< standard short-hand for base class + //! for storage of fields + using Vector_t = Parent::Vector_t; //! Input vector for solvers - using SolvVectorIn = typename Parent::SolvVectorIn; + using Vector_ref = Parent::Vector_ref; //! Input vector for solvers - using SolvVectorInC = typename Parent::SolvVectorInC; + using ConstVector_ref = Parent::ConstVector_ref; //! 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< - typename Parent::Collection_t, Real, secondOrder, DimM>; - - //! conjugate gradient needs directional stiffness - constexpr static Tg_req_t tangent_requirement{Tg_req_t::NeedEffect}; + using Vector_map = Parent::Vector_map; + //! Default constructor SolverCG() = delete; - //! Constructor with domain resolutions, etc, - SolverCG(Cell_t& cell, Real tol, Uint maxiter=0, bool verbose=false); - //! Copy constructor SolverCG(const SolverCG &other) = delete; + /** + * Constructor takes a Cell, tolerance, max number of iterations + * and verbosity flag as input + */ + SolverCG(Cell & cell, Real tol, Uint maxiter, bool verbose=false); + //! Move constructor SolverCG(SolverCG &&other) = default; //! Destructor virtual ~SolverCG() = default; //! Copy assignment operator SolverCG& operator=(const SolverCG &other) = delete; //! Move assignment operator SolverCG& operator=(SolverCG &&other) = default; - bool has_converged() const override final {return this->converged;} + //! initialisation does not need to do anything in this case + void initialise() override final {}; - //! actual solver - void solve(const Field_t & rhs, - Field_t & x); + //! returns the solver's name + std::string get_name() const override final {return "CG";} - // this simplistic implementation has no initialisation phase so the default is ok + //! the actual solver + Vector_map solve(const ConstVector_ref rhs) override final; - SolvVectorOut solve(const SolvVectorInC rhs, SolvVectorIn x_0) override final; + - std::string name() const override final {return "CG";} protected: - //! returns `muSpectre::Tg_req_t::NeedEffect` - Tg_req_t get_tangent_req() const override 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 + Vector_t r_k; //!< residual + Vector_t p_k; //!< search direction + Vector_t Ap_k; //!< directional stiffness + Vector_t x_k; //!< current solution private: }; } // muSpectre #endif /* SOLVER_CG_H */ diff --git a/src/solver/solver_cg_eigen.cc b/src/solver/solver_cg_eigen.cc deleted file mode 100644 index 73150a4..0000000 --- a/src/solver/solver_cg_eigen.cc +++ /dev/null @@ -1,110 +0,0 @@ -/** - * @file solver_cg_eigen.cc - * - * @author Till Junge - * - * @date 19 Jan 2018 - * - * @brief implementation for binding to Eigen's conjugate gradient solver - * - * Copyright (C) 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 "solver_cg_eigen.hh" - -#include -#include - -namespace muSpectre { - - //----------------------------------------------------------------------------// - template - SolverEigen::SolverEigen(Cell_t& cell, Real tol, Uint maxiter, - bool verbose) - :Parent(cell, tol, maxiter, verbose), - adaptor{cell.get_adaptor()}, - solver{} - {} - - //----------------------------------------------------------------------------// - template - void - SolverEigen::initialise() { - this->solver.setTolerance(this->tol); - this->solver.setMaxIterations(this->maxiter); - this->solver.compute(this->adaptor); - } - - //----------------------------------------------------------------------------// - template - typename SolverEigen::SolvVectorOut - SolverEigen::solve(const SolvVectorInC rhs, SolvVectorIn x_0) { - auto & this_solver = static_cast (*this); - SolvVectorOut retval = this->solver.solveWithGuess(rhs, x_0); - this->counter += this->solver.iterations(); - if (this->solver.info() != Eigen::Success) { - std::stringstream err {}; - err << this_solver.name() << " has not converged," - << " After " << this->solver.iterations() << " steps, the solver " - << " FAILED with |r|/|b| = " - << std::setw(15) << this->solver.error() - << ", cg_tol = " << this->tol << std::endl; - throw ConvergenceError(err.str()); - } - if (this->verbose) { - std::cout << " After " << this->solver.iterations() << " " - << this_solver.name() << " steps, |r|/|b| = " - << std::setw(15) << this->solver.error() - << ", cg_tol = " << this->tol << std::endl; - } - return retval; - } - - /* ---------------------------------------------------------------------- */ - template - typename SolverEigen::Tg_req_t - SolverEigen::get_tangent_req() const { - return tangent_requirement; - } - - template class SolverEigen, twoD, twoD>; - template class SolverEigen, threeD, threeD>; - template class SolverCGEigen; - template class SolverCGEigen; - - template class SolverEigen, twoD, twoD>; - template class SolverEigen, threeD, threeD>; - template class SolverGMRESEigen; - template class SolverGMRESEigen; - - template class SolverEigen, twoD, twoD>; - template class SolverEigen, threeD, threeD>; - template class SolverBiCGSTABEigen; - template class SolverBiCGSTABEigen; - - template class SolverEigen, twoD, twoD>; - template class SolverEigen, threeD, threeD>; - template class SolverDGMRESEigen; - template class SolverDGMRESEigen; - - template class SolverEigen, twoD, twoD>; - template class SolverEigen, threeD, threeD>; - template class SolverMINRESEigen; - template class SolverMINRESEigen; - -} // muSpectre diff --git a/src/solver/solver_error.hh b/src/solver/solver_common.cc similarity index 58% rename from src/solver/solver_error.hh rename to src/solver/solver_common.cc index c7cdad5..85c0cbc 100644 --- a/src/solver/solver_error.hh +++ b/src/solver/solver_common.cc @@ -1,46 +1,42 @@ /** - * @file solver_error.hh + * file solver_common.cc * - * @author Till Junge + * @author Till Junge * - * @date 28 Dec 2017 + * @date 15 May 2018 * - * @brief Errors raised by solvers + * @brief implementation for solver utilities * - * Copyright © 2017 Till Junge + * @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 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 SOLVER_ERROR_H -#define SOLVER_ERROR_H - -#include - +#include "solver/solver_common.hh" namespace muSpectre { - class SolverError: public std::runtime_error { - using runtime_error::runtime_error; - }; - - class ConvergenceError: public SolverError { - using SolverError::SolverError; - }; + /* ---------------------------------------------------------------------- */ + bool check_symmetry(const Eigen::Ref& eps, + Real rel_tol){ + return (rel_tol >= (eps-eps.transpose()).matrix().norm()/eps.matrix().norm() || + rel_tol >= eps.matrix().norm()); + } } // muSpectre -#endif /* SOLVER_ERROR_H */ diff --git a/src/solver/solvers.hh b/src/solver/solver_common.hh similarity index 50% copy from src/solver/solvers.hh copy to src/solver/solver_common.hh index 0396f78..fc7ae61 100644 --- a/src/solver/solvers.hh +++ b/src/solver/solver_common.hh @@ -1,141 +1,97 @@ /** - * @file solvers.hh + * @file solver_common.hh * - * @author Till Junge + * @author Till Junge * - * @date 20 Dec 2017 + * @date 28 Dec 2017 * - * @brief Free functions for solving + * @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 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 SOLVERS_H -#define SOLVERS_H +#ifndef SOLVER_COMMON_H +#define SOLVER_COMMON_H -#include "solver/solver_base.hh" +#include "common/common.hh" +#include "common/tensor_algebra.hh" #include -#include -#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; }; /** * 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>>; - /* ---------------------------------------------------------------------- */ - /** - * Uses the Newton-conjugate Gradient method to find the static - * equilibrium of a cell given a series of mean applied strains - */ - template - std::vector - newton_cg (CellBase & cell, - const GradIncrements & delF0, - SolverBase & solver, Real newton_tol, - Real equil_tol, - Dim_t verbose = 0); - - /* ---------------------------------------------------------------------- */ - /** - * Uses the Newton-conjugate Gradient method to find the static - * equilibrium of a cell given a mean applied strain - */ - template - inline OptimizeResult - newton_cg (CellBase & cell, const Grad_t & delF0, - SolverBase & solver, Real newton_tol, - Real equil_tol, - Dim_t verbose = 0){ - return newton_cg(cell, GradIncrements{delF0}, - solver, newton_tol, equil_tol, verbose)[0]; - } /* ---------------------------------------------------------------------- */ - /** - * Uses the method proposed by de Geus method to find the static - * equilibrium of a cell given a series of mean applied strains - */ - template - std::vector - de_geus (CellBase & cell, - const GradIncrements & delF0, - SolverBase & solver, Real newton_tol, - Real equil_tol, - Dim_t verbose = 0); + class SolverError: public std::runtime_error { + using runtime_error::runtime_error; + }; /* ---------------------------------------------------------------------- */ - /** - * Uses the method proposed by de Geus method to find the static - * equilibrium of a cell given a mean applied strain - */ - template - OptimizeResult - de_geus (CellBase & cell, const Grad_t & delF0, - SolverBase & solver, Real newton_tol, - Real equil_tol, - Dim_t verbose = 0){ - return de_geus(cell, GradIncrements{delF0}, - solver, newton_tol, equil_tol, verbose)[0]; - } + 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); } // muSpectre -#endif /* SOLVERS_H */ + +#endif /* SOLVER_COMMON_H */ diff --git a/src/solver/solver_eigen.cc b/src/solver/solver_eigen.cc new file mode 100644 index 0000000..494068d --- /dev/null +++ b/src/solver/solver_eigen.cc @@ -0,0 +1,93 @@ +/** + * file solver_eigen.cc + * + * @author Till Junge + * + * @date 15 May 2018 + * + * @brief Implementations for bindings to Eigen's iterative solvers + * + * @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 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 "solver/solver_eigen.hh" + +#include +#include + + +namespace muSpectre { + + /* ---------------------------------------------------------------------- */ + template + SolverEigen::SolverEigen(Cell& cell, Real tol, + Uint maxiter, bool verbose): + Parent(cell, tol, maxiter, verbose), + adaptor{cell.get_adaptor()}, + solver{}, + result{} + {} + + /* ---------------------------------------------------------------------- */ + template + void SolverEigen::initialise() { + this->solver.setTolerance(this->get_tol()); + this->solver.setMaxIterations(this->get_maxiter()); + this->solver.compute(this->adaptor); + } + + /* ---------------------------------------------------------------------- */ + template + auto SolverEigen::solve(const ConstVector_ref rhs) + -> Vector_map { + // for crtp + auto & this_solver = static_cast (*this); + this->result = this->solver.solve(rhs); + this->counter += this->solver.iterations(); + + if (this->solver.info() != Eigen::Success) { + std::stringstream err {}; + err << this_solver.get_name() << " has not converged," + << " After " << this->solver.iterations() << " steps, the solver " + << " FAILED with |r|/|b| = " + << std::setw(15) << this->solver.error() + << ", cg_tol = " << this->tol << std::endl; + throw ConvergenceError(err.str()); + } + + if (this->verbose) { + std::cout << " After " << this->solver.iterations() << " " + << this_solver.get_name() << " steps, |r|/|b| = " + << std::setw(15) << this->solver.error() + << ", cg_tol = " << this->tol << std::endl; + + } + return Vector_map(this->result.data(), this->result.size()); + } + + + /* ---------------------------------------------------------------------- */ + template class SolverEigen; + template class SolverEigen; + template class SolverEigen; + template class SolverEigen; + template class SolverEigen; + +} // muSpectre diff --git a/src/solver/solver_eigen.hh b/src/solver/solver_eigen.hh new file mode 100644 index 0000000..c4a6cdc --- /dev/null +++ b/src/solver/solver_eigen.hh @@ -0,0 +1,215 @@ +/** + * file solver_eigen.hh + * + * @author Till Junge + * + * @date 15 May 2018 + * + * @brief Bindings to Eigen's iterative solvers + * + * @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 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 SOLVER_EIGEN_H +#define SOLVER_EIGEN_H + +#include "solver/solver_base.hh" +#include "cell/cell_base.hh" + +#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; + }; + + } // 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() override final; + + //! executes the solver + Vector_map solve(const ConstVector_ref rhs) override 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 override final {return "CG";} + }; + + /** + * Binding to Eigen's GMRES solver + */ + class SolverGMRESEigen: + public SolverEigen { + public: + using SolverEigen::SolverEigen; + std::string get_name() const override 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 override 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 override 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 override final {return "MINRES";} + }; + +} // muSpectre + +#endif /* SOLVER_EIGEN_H */ diff --git a/src/solver/solvers.cc b/src/solver/solvers.cc index 94e3b60..53f0b0b 100644 --- a/src/solver/solvers.cc +++ b/src/solver/solvers.cc @@ -1,432 +1,404 @@ /** - * @file solvers.cc + * file solvers.cc * * @author Till Junge * - * @date 20 Dec 2017 + * @date 24 Apr 2018 * - * @brief implementation of solver functions + * @brief implementation of dynamic newton-cg solver * - * Copyright © 2017 Till Junge + * @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 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 "solver/solvers.hh" -#include "solver/solver_cg.hh" -#include "common/iterators.hh" +#include "solvers.hh" -#include +#include #include -#include namespace muSpectre { - template + //----------------------------------------------------------------------------// std::vector - de_geus (CellBase & cell, const GradIncrements & delFs, - SolverBase & solver, Real newton_tol, - Real equil_tol, - Dim_t verbose) { - using Field_t = typename MaterialBase::StrainField_t; + 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(); - 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)}; + using Vector_t = Eigen::Matrix; + using Matrix_t = Eigen::Matrix; - // Corresponds to symbol ΔF or Δε - auto & DeltaF{make_field("ΔF", *solver_fields)}; + // Corresponds to symbol δF or δε + Vector_t incrF(cell.get_nb_dof()); // field to store the rhs for cg calculations - auto & rhs{make_field("rhs", *solver_fields)}; + Vector_t rhs(cell.get_nb_dof()); 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 "; + 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 << " =" <(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()}; + auto shape{cell.get_strain_shape()}; + switch (form) { case Formulation::finite_strain: { - F.get_map() = Matrices::I2(); + 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: { - F.get_map() = Matrices::I2().Zero(); - for (const auto & delF: delFs) { - if (!check_symmetry(delF)) { + 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 formulation"); + throw SolverError("Unknown strain measure"); break; } // initialise return value std::vector ret_val{}; - // initialise materials - constexpr bool need_tangent{true}; - cell.initialise_materials(need_tangent); + // storage for the previous mean strain (to compute ΔF or Δε) + Matrix_t previous_macro_strain{load_steps.back().Zero(shape[0], shape[1])}; - Grad_t previous_grad{Grad_t::Zero()}; - for (const auto & delF: delFs) { //incremental loop + auto F{cell.get_strain_vector()}; + //! incremental loop + for (const auto & macro_strain: load_steps) { + using StrainMap_t = RawFieldMap>; + for (auto && strain: StrainMap_t(F, shape[0], shape[1])) { + strain += macro_strain - previous_macro_strain; + } std::string message{"Has not converged"}; - Real incrNorm{2*newton_tol}, gradNorm{1}; - Real stressNorm{2*equil_tol}; + Real incr_norm{2*newton_tol}, grad_norm{1}; + Real stress_norm{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; + + 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==1)); + newt_iter < solver.get_maxiter() && !has_converged; ++newt_iter) { - // obtain material response - auto res_tup{cell.evaluate_stress_tangent(F)}; + auto res_tup{cell.evaluate_stress_tangent()}; 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); - }; + rhs = -P; + cell.apply_projection(rhs); + stress_norm = std::sqrt(comm.sum(rhs.squaredNorm())); - - 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()); + if (convergence_test()) { + break; } - F.eigen() += incrF.eigen(); + //! this is a potentially avoidable copy TODO: check this out + incrF = solver.solve(rhs); + + F += incrF; - incrNorm = std::sqrt(comm.sum(incrF.eigen().matrix().squaredNorm())); - gradNorm = std::sqrt(comm.sum(F.eigen().matrix().squaredNorm())); - if (verbose > 0 && comm.rank() == 0) { + 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) << incrNorm/gradNorm + << "| = " << std::setw(17) << incr_norm/grad_norm << ", tol = " << newton_tol << std::endl; + if (verbose-1>1) { std::cout << "<" << strain_symb << "> =" << std::endl - << F.get_map().mean() << std::endl; + << StrainMap_t(F, shape[0], shape[1]).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()}); + // update previous macroscopic strain + previous_macro_strain = macro_strain; - // store history variables here - cell.save_history_variables(); + // store results + ret_val.emplace_back(OptimizeResult{F, cell.get_stress_vector(), + convergence_test(), Int(convergence_test()), + message, newt_iter, solver.get_counter()}); + // store history variables for next load increment + cell.save_history_variables(); } return ret_val; - } - //! instantiation for two-dimensional cells - template std::vector - de_geus (CellBase & cell, const GradIncrements& delF0, - SolverBase & solver, Real newton_tol, - Real equil_tol, - Dim_t verbose); - - // template typename CellBase::StrainField_t & - // de_geus (CellBase & cell, const GradIncrements& delF0, - // const Real cg_tol, const Real newton_tol, Uint maxiter, - // Dim_t verbose); - - //! instantiation for three-dimensional cells - template std::vector - de_geus (CellBase & cell, const GradIncrements& delF0, - SolverBase & solver, Real newton_tol, - Real equil_tol, - Dim_t verbose); - - /* ---------------------------------------------------------------------- */ - template + //----------------------------------------------------------------------------// std::vector - newton_cg (CellBase & cell, const GradIncrements & delFs, - SolverBase & solver, Real newton_tol, - Real equil_tol, - Dim_t verbose) { - using Field_t = typename MaterialBase::StrainField_t; + 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(); - auto solver_fields{std::make_unique>()}; - solver_fields->initialise(cell.get_subdomain_resolutions(), - cell.get_subdomain_locations()); + + using Vector_t = Eigen::Matrix; + using Matrix_t = Eigen::Matrix; // Corresponds to symbol δF or δε - auto & incrF{make_field("δF", *solver_fields)}; + 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 - auto & rhs{make_field("rhs", *solver_fields)}; + Vector_t rhs(cell.get_nb_dof()); 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 "; + 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 = "Fy"; + 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 << " =" <(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()) { + auto shape{cell.get_strain_shape()}; + + switch (form) { case Formulation::finite_strain: { - F.get_map() = Matrices::I2(); + 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: { - F.get_map() = Matrices::I2().Zero(); - for (const auto & delF: delFs) { - if (!check_symmetry(delF)) { + 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 formulation"); + throw SolverError("Unknown strain measure"); break; } // initialise return value std::vector ret_val{}; - // initialise materials - constexpr bool need_tangent{true}; - cell.initialise_materials(need_tangent); + // storage for the previous mean strain (to compute ΔF or Δε) + Matrix_t previous_macro_strain{load_steps.back().Zero(shape[0], shape[1])}; - 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; - } + auto F{cell.get_strain_vector()}; + //! incremental loop + for (const auto & macro_strain: load_steps) { + using StrainMap_t = RawFieldMap>; std::string message{"Has not converged"}; - Real incrNorm{2*newton_tol}, gradNorm{1}; - Real stressNorm{2*equil_tol}; + Real incr_norm{2*newton_tol}, grad_norm{1}; + Real stress_norm{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; + + 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(F)}; + auto res_tup{cell.evaluate_stress_tangent()}; 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; + 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); + stress_norm = std::sqrt(comm.sum(rhs.matrix().squaredNorm())); + if (convergence_test()) { + break; + } + incrF = solver.solve(rhs); + F += DeltaF; + } + else { + rhs = -P; + cell.apply_projection(rhs); + stress_norm = std::sqrt(comm.sum(rhs.matrix().squaredNorm())); + if (convergence_test()) { + break; + } + incrF = solver.solve(rhs); } - incrF.eigen() = 0; - - incrF.eigenvec() = solver.solve(rhs.eigenvec(), incrF.eigenvec()); + F += incrF; - F.eigen() += incrF.eigen(); + incr_norm = std::sqrt(comm.sum(incrF.squaredNorm())); + grad_norm = std::sqrt(comm.sum(F.squaredNorm())); - incrNorm = std::sqrt(comm.sum(incrF.eigen().matrix().squaredNorm())); - gradNorm = std::sqrt(comm.sum(F.eigen().matrix().squaredNorm())); - if (verbose > 0 && comm.rank() == 0) { + 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) << incrNorm/gradNorm + << "| = " << std::setw(17) << incr_norm/grad_norm << ", tol = " << newton_tol << std::endl; if (verbose-1>1) { std::cout << "<" << strain_symb << "> =" << std::endl - << F.get_map().mean() << std::endl; + << StrainMap_t(F, shape[0], shape[1]).mean() << std::endl; } } convergence_test(); - } - // update previous gradient - previous_grad = delF; - ret_val.push_back(OptimizeResult{F.eigen(), cell.get_stress().eigen(), + + // 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()}); + message, newt_iter, solver.get_counter()}); - //store history variables for next load increment + // store history variables for next load increment cell.save_history_variables(); - } return ret_val; - } - - //! instantiation for two-dimensional cells - template std::vector - newton_cg (CellBase & cell, const GradIncrements& delF0, - SolverBase & solver, Real newton_tol, - Real equil_tol, - Dim_t verbose); - - // template typename CellBase::StrainField_t & - // newton_cg (CellBase & cell, const GradIncrements& delF0, - // const Real cg_tol, const Real newton_tol, Uint maxiter, - // Dim_t verbose); - - //! instantiation for three-dimensional cells - template std::vector - newton_cg (CellBase & cell, const GradIncrements& delF0, - SolverBase & solver, Real newton_tol, - Real equil_tol, - Dim_t verbose); - - - /* ---------------------------------------------------------------------- */ - bool check_symmetry(const Eigen::Ref& eps, - Real rel_tol){ - return (rel_tol >= (eps-eps.transpose()).matrix().norm()/eps.matrix().norm() || - rel_tol >= eps.matrix().norm()); - } - - } // muSpectre diff --git a/src/solver/solvers.hh b/src/solver/solvers.hh index 0396f78..391c7b6 100644 --- a/src/solver/solvers.hh +++ b/src/solver/solvers.hh @@ -1,141 +1,100 @@ /** - * @file solvers.hh + * file solvers.hh * * @author Till Junge * - * @date 20 Dec 2017 + * @date 24 Apr 2018 * - * @brief Free functions for solving + * @brief Free functions for solving rve problems * - * Copyright © 2017 Till Junge + * @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 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 SOLVERS_H #define SOLVERS_H #include "solver/solver_base.hh" #include #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; - }; - - /** - * 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>>; + using LoadSteps_t = std::vector; - /* ---------------------------------------------------------------------- */ /** * Uses the Newton-conjugate Gradient method to find the static * equilibrium of a cell given a series of mean applied strains */ - template std::vector - newton_cg (CellBase & cell, - const GradIncrements & delF0, - SolverBase & solver, Real newton_tol, - Real equil_tol, - Dim_t verbose = 0); + newton_cg(Cell & cell, + const LoadSteps_t & load_steps, + SolverBase & solver, Real newton_tol, + Real equil_tol, + Dim_t verbose = 0); - /* ---------------------------------------------------------------------- */ /** * Uses the Newton-conjugate Gradient method to find the static * equilibrium of a cell given a mean applied strain */ - template - inline OptimizeResult - newton_cg (CellBase & cell, const Grad_t & delF0, - SolverBase & solver, Real newton_tol, - Real equil_tol, - Dim_t verbose = 0){ - return newton_cg(cell, GradIncrements{delF0}, - solver, newton_tol, equil_tol, verbose)[0]; + OptimizeResult + newton_cg(Cell & cell, + const Eigen::Ref load_step, + SolverBase & solver, Real newton_tol, + Real equil_tol, + Dim_t verbose = 0) { + LoadSteps_t load_steps{load_step}; + return newton_cg(cell, load_steps, solver, newton_tol, + equil_tol, verbose).front(); } /* ---------------------------------------------------------------------- */ /** * Uses the method proposed by de Geus method to find the static * equilibrium of a cell given a series of mean applied strains */ - template std::vector - de_geus (CellBase & cell, - const GradIncrements & delF0, - SolverBase & solver, Real newton_tol, - Real equil_tol, - Dim_t verbose = 0); + de_geus(Cell & cell, + const LoadSteps_t & load_steps, + SolverBase & solver, Real newton_tol, + Real equil_tol, + Dim_t verbose = 0); /* ---------------------------------------------------------------------- */ /** * Uses the method proposed by de Geus method to find the static * equilibrium of a cell given a mean applied strain */ - template OptimizeResult - de_geus (CellBase & cell, const Grad_t & delF0, - SolverBase & solver, Real newton_tol, - Real equil_tol, - Dim_t verbose = 0){ - return de_geus(cell, GradIncrements{delF0}, + de_geus(Cell & cell, + const Eigen::Ref load_step, + SolverBase & solver, Real newton_tol, + Real equil_tol, + Dim_t verbose = 0){ + return de_geus(cell, LoadSteps_t{load_step}, solver, newton_tol, equil_tol, verbose)[0]; } - /* ---------------------------------------------------------------------- */ - /** - * 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); - } // muSpectre #endif /* SOLVERS_H */ diff --git a/tests/mpi_test_fft_engine.cc b/tests/mpi_test_fft_engine.cc index 962a11e..ec694f0 100644 --- a/tests/mpi_test_fft_engine.cc +++ b/tests/mpi_test_fft_engine.cc @@ -1,175 +1,171 @@ /** * @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 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. */ #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" #ifdef WITH_FFTWMPI #include "fft/fftwmpi_engine.hh" #endif #ifdef WITH_PFFT #include "fft/pfft_engine.hh" #endif #include "common/ccoord_operations.hh" #include "common/field_collection.hh" #include "common/field_map.hh" #include "common/iterators.hh" namespace muSpectre { 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 mdim{Engine::mdim}; + constexpr static Dim_t nb_components{sdim*sdim}; constexpr static Ccoord_t res() { return CcoordOps::get_cube(box_resolution); } - FFTW_fixture(): engine(res(), MPIContext::get_context().comm) {} + 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 Ccoord_t res() {return {6, 4};} FFTW_fixture_python_segfault(): engine{res(), MPIContext::get_context().comm} {} Engine engine; }; using fixlist = boost::mpl::list< #ifdef WITH_FFTWMPI - FFTW_fixture, 3>, - FFTW_fixture, 3>, - FFTW_fixture, 3>, - FFTW_fixture, 4>, - FFTW_fixture, 4>, - FFTW_fixture, 4>, - FFTW_fixture_python_segfault>, + 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, 3>, - FFTW_fixture, 4>, - FFTW_fixture, 4>, - FFTW_fixture, 4>, - FFTW_fixture_python_segfault>, + FFTW_fixture, 3>, + FFTW_fixture, 3>, + FFTW_fixture, 4>, + FFTW_fixture, 4>, + FFTW_fixture_python_segfault>, #endif - FFTW_fixture, 3, true>>; + 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())); } /* ---------------------------------------------------------------------- */ 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; FC_t fc; - auto & input{make_field>("input", fc)}; - auto & ref {make_field>("reference", fc)}; - auto & result{make_field>("result", fc)}; + auto & input{make_field>("input", fc)}; + auto & ref {make_field>("reference", fc)}; + auto & result{make_field>("result", fc)}; fc.initialise(Fix::engine.get_subdomain_resolutions(), Fix::engine.get_subdomain_locations()); - using map_t = MatrixFieldMap; + using map_t = 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 = MatrixFieldMap, Complex, Fix::sdim, Fix::sdim>; cmap_t complex_map(complex_field); if (Fix::engine.get_subdomain_locations() == 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(); } // muSpectre diff --git a/tests/mpi_test_projection.hh b/tests/mpi_test_projection.hh index dae7c39..dfb8b34 100644 --- a/tests/mpi_test_projection.hh +++ b/tests/mpi_test_projection.hh @@ -1,88 +1,89 @@ /** * @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 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 "tests.hh" #include "mpi_context.hh" #include #include 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 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), MPIContext::get_context().comm), SizeGiver::get_lengths()){} Parent projector; }; } // muSpectre diff --git a/tests/mpi_test_projection_finite.cc b/tests/mpi_test_projection_finite.cc index 6a12061..5f28022 100644 --- a/tests/mpi_test_projection_finite.cc +++ b/tests/mpi_test_projection_finite.cc @@ -1,185 +1,185 @@ /** * @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 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. */ #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 "mpi_test_projection.hh" #include "fft/fftw_engine.hh" #ifdef WITH_FFTWMPI #include "fft/fftwmpi_engine.hh" #endif #ifdef WITH_PFFT #include "fft/pfft_engine.hh" #endif #include namespace muSpectre { BOOST_AUTO_TEST_SUITE(mpi_projection_finite_strain); /* ---------------------------------------------------------------------- */ using fixlist = boost::mpl::list< #ifdef WITH_FFTWMPI ProjectionFixture, ProjectionFiniteStrain, - FFTWMPIEngine>, + FFTWMPIEngine>, ProjectionFixture, ProjectionFiniteStrain, - FFTWMPIEngine>, + FFTWMPIEngine>, ProjectionFixture, ProjectionFiniteStrain, - FFTWMPIEngine>, + FFTWMPIEngine>, ProjectionFixture, ProjectionFiniteStrain, - FFTWMPIEngine>, + FFTWMPIEngine>, ProjectionFixture, ProjectionFiniteStrainFast, - FFTWMPIEngine>, + FFTWMPIEngine>, ProjectionFixture, ProjectionFiniteStrainFast, - FFTWMPIEngine>, + FFTWMPIEngine>, ProjectionFixture, ProjectionFiniteStrainFast, - FFTWMPIEngine>, + FFTWMPIEngine>, ProjectionFixture, ProjectionFiniteStrainFast, - FFTWMPIEngine>, + FFTWMPIEngine>, #endif #ifdef WITH_PFFT ProjectionFixture, ProjectionFiniteStrain, - PFFTEngine>, + PFFTEngine>, ProjectionFixture, ProjectionFiniteStrain, - PFFTEngine>, + PFFTEngine>, ProjectionFixture, ProjectionFiniteStrain, - PFFTEngine>, + PFFTEngine>, ProjectionFixture, ProjectionFiniteStrain, - PFFTEngine>, + PFFTEngine>, ProjectionFixture, ProjectionFiniteStrainFast, - PFFTEngine>, + PFFTEngine>, ProjectionFixture, ProjectionFiniteStrainFast, - PFFTEngine>, + PFFTEngine>, ProjectionFixture, ProjectionFiniteStrainFast, - PFFTEngine>, + PFFTEngine>, ProjectionFixture, ProjectionFiniteStrainFast, - PFFTEngine>, + PFFTEngine>, #endif ProjectionFixture, ProjectionFiniteStrain, - FFTWEngine, + 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 Vector = Eigen::Matrix; Fields fields{}; FieldT & f_grad{make_field("gradient", fields)}; FieldT & f_var{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]; } 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(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); 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(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(); } // muSpectre diff --git a/tests/mpi_test_projection_small.cc b/tests/mpi_test_projection_small.cc index a87ea52..ef0c0d5 100644 --- a/tests/mpi_test_projection_small.cc +++ b/tests/mpi_test_projection_small.cc @@ -1,170 +1,170 @@ /** * @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 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. */ #define BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS #define BOOST_MPL_LIMIT_LIST_SIZE 50 #include "fft/projection_small_strain.hh" #include "mpi_test_projection.hh" #include "fft/fft_utils.hh" #include "fft/fftw_engine.hh" #ifdef WITH_FFTWMPI #include "fft/fftwmpi_engine.hh" #endif #ifdef WITH_PFFT #include "fft/pfft_engine.hh" #endif #include namespace muSpectre { BOOST_AUTO_TEST_SUITE(mpi_projection_small_strain); using fixlist = boost::mpl::list< #ifdef WITH_FFTWMPI ProjectionFixture, ProjectionSmallStrain, - FFTWMPIEngine>, + FFTWMPIEngine>, ProjectionFixture, ProjectionSmallStrain, - FFTWMPIEngine>, + FFTWMPIEngine>, ProjectionFixture, ProjectionSmallStrain, - FFTWMPIEngine>, + FFTWMPIEngine>, ProjectionFixture, ProjectionSmallStrain, - FFTWMPIEngine>, + FFTWMPIEngine>, #endif #ifdef WITH_PFFT ProjectionFixture, ProjectionSmallStrain, - PFFTEngine>, + PFFTEngine>, ProjectionFixture, ProjectionSmallStrain, - PFFTEngine>, + PFFTEngine>, ProjectionFixture, ProjectionSmallStrain, - PFFTEngine>, + PFFTEngine>, ProjectionFixture, ProjectionSmallStrain, - PFFTEngine>, + PFFTEngine>, #endif ProjectionFixture, ProjectionSmallStrain, - FFTWEngine, + 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 Vector = Eigen::Matrix; Fields fields{}; FieldT & f_grad{make_field("strain", fields)}; FieldT & f_var{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]; } 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(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(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(); } // muSpectre diff --git a/tests/mpi_test_solver_newton_cg.cc b/tests/mpi_test_solver_newton_cg.cc index e7ea9c9..c0b6c48 100644 --- a/tests/mpi_test_solver_newton_cg.cc +++ b/tests/mpi_test_solver_newton_cg.cc @@ -1,200 +1,200 @@ /** * @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 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 "tests.hh" #include "mpi_context.hh" -#include "solver/solvers.hh" -#include "solver/solver_cg.hh" -#include "solver/solver_cg_eigen.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 "materials/material_linear_elastic1.hh" #include "common/iterators.hh" #include "common/ccoord_operations.hh" #include "cell/cell_factory.hh" namespace muSpectre { BOOST_AUTO_TEST_SUITE(newton_cg_tests); BOOST_AUTO_TEST_CASE(manual_construction_test) { const Communicator & comm = 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, 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 bool verbose{false}; GradIncrements grads; grads.push_back(delF0); - SolverCG cg{sys, cg_tol, maxiter, bool(verbose)}; - Eigen::ArrayXXd res1{de_geus(sys, grads, cg, newton_tol, verbose)[0].grad}; + DeprecatedSolverCG cg{sys, cg_tol, maxiter, bool(verbose)}; + Eigen::ArrayXXd res1{deprecated_de_geus(sys, grads, cg, newton_tol, verbose)[0].grad}; - SolverCG cg2{sys, cg_tol, maxiter, bool(verbose)}; - Eigen::ArrayXXd res2{newton_cg(sys, grads, cg2, newton_tol, verbose)[0].grad}; + DeprecatedSolverCG cg2{sys, cg_tol, maxiter, bool(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; 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 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}; - SolverCGEigen cg{sys, cg_tol, maxiter, bool(verbose)}; - auto result = de_geus(sys, delEps0, cg, newton_tol, + DeprecatedSolverCGEigen cg{sys, cg_tol, maxiter, bool(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; - SolverCG cg2{sys, cg_tol, maxiter, bool(verbose)}; - result = newton_cg(sys, delEps0, cg2, newton_tol, + DeprecatedSolverCG cg2{sys, cg_tol, maxiter, bool(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(); } // muSpectre diff --git a/tests/python_fft_tests.py b/tests/python_fft_tests.py index de93da2..9ba6d5a 100644 --- a/tests/python_fft_tests.py +++ b/tests/python_fft_tests.py @@ -1,97 +1,97 @@ #!/usr/bin/env python3 # -*- coding:utf-8 -*- """ file python_fft_tests.py @author Till Junge @date 17 Jan 2018 @brief Compare µSpectre's fft implementations to numpy reference @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 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. """ import unittest import numpy as np from python_test_imports import µ try: from mpi4py import MPI comm = MPI.COMM_WORLD except ImportError: comm = None class FFT_Check(unittest.TestCase): def setUp(self): self.resolution = [6, 4] self.dim = len(self.resolution) self.engines = [('fftw', False), ('fftwmpi', True), ('pfft', True)] self.tol = 1e-14 * np.prod(self.resolution) def test_forward_transform(self): for engine_str, transposed in self.engines: try: - engine = µ.fft.FFT(self.resolution, fft=engine_str) + engine = µ.fft.FFT(self.resolution, self.dim**2, fft=engine_str) except KeyError: # This FFT engine has not been compiled into the code. Skip # test. continue engine.initialise() in_arr = np.random.random([*self.resolution, self.dim, self.dim]) out_ref = np.fft.rfftn(in_arr, axes=(0, 1)) if transposed: out_ref = out_ref.swapaxes(0, 1) out_msp = engine.fft(in_arr.reshape(-1, self.dim**2).T).T err = np.linalg.norm(out_ref - out_msp.reshape(out_ref.shape)) self.assertTrue(err < self.tol) def test_reverse_transform(self): for engine_str, transposed in self.engines: try: - engine = µ.fft.FFT(self.resolution, fft=engine_str) + engine = µ.fft.FFT(self.resolution, self.dim**2, fft=engine_str) except KeyError: # This FFT engine has not been compiled into the code. Skip # test. continue engine.initialise() complex_res = µ.get_hermitian_sizes(self.resolution) in_arr = np.zeros([*complex_res, self.dim, self.dim], dtype=complex) in_arr.real = np.random.random(in_arr.shape) in_arr.imag = np.random.random(in_arr.shape) out_ref = np.fft.irfftn(in_arr, axes=(0, 1)) if transposed: in_arr = in_arr.swapaxes(0, 1) out_msp = engine.ifft(in_arr.reshape(-1, self.dim**2).T).T out_msp *= engine.normalisation() err = np.linalg.norm(out_ref - out_msp.reshape(out_ref.shape)) self.assertTrue(err < self.tol) if __name__ == '__main__': unittest.main() diff --git a/tests/python_material_linear_elastic3_test.py b/tests/python_material_linear_elastic3_test.py index 6bde8e7..9f6fc6a 100644 --- a/tests/python_material_linear_elastic3_test.py +++ b/tests/python_material_linear_elastic3_test.py @@ -1,76 +1,78 @@ #!/usr/bin/env python3 # -*- coding:utf-8 -*- """ @file python_material_linear_elastic3.py @author Richard Leute @date 20 Feb 2018 @brief description @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 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. """ import unittest import numpy as np from python_test_imports import µ class MaterialLinearElastic3_Check(unittest.TestCase): """ Check the implementation of the fourth order stiffness tensor C for each cell. Assign the same Youngs modulus and Poisson ratio to each cell, calculate the stress and compare the result with stress=2*mu*Del0 (Hooke law for small symmetric strains). """ def setUp(self): self.resolution = [5,5] self.lengths = [2.5, 3.1] self.formulation = µ.Formulation.small_strain self.sys = µ.Cell(self.resolution, self.lengths, self.formulation) + self.dim = len(self.lengths) self.mat = µ.material.MaterialLinearElastic3_2d.make( self.sys, "material") def test_solver(self): Young = 10. Poisson = 0.3 for i, pixel in enumerate(self.sys): self.mat.add_pixel(pixel, Young, Poisson) self.sys.initialise() tol = 1e-6 Del0 = np.array([[0, 0.025], [0.025, 0]]) maxiter = 100 - verbose = 1 + verbose = False solver=µ.solvers.SolverCG(self.sys, tol, maxiter, verbose) r = µ.solvers.newton_cg(self.sys, Del0, solver, tol, tol, verbose) #compare the computed stress with the trivial by hand computed stress mu = (Young/(2*(1+Poisson))) stress = 2*mu*Del0 - self.assertLess(np.linalg.norm(r.stress-stress.reshape(-1,1)), 1e-8) + self.assertLess(np.linalg.norm(r.stress.reshape(-1, self.dim**2) - + stress.reshape(1, self.dim**2)), 1e-8) diff --git a/tests/python_material_linear_elastic4_test.py b/tests/python_material_linear_elastic4_test.py index 70a2e4e..25566ec 100644 --- a/tests/python_material_linear_elastic4_test.py +++ b/tests/python_material_linear_elastic4_test.py @@ -1,77 +1,79 @@ #!/usr/bin/env python3 # -*- coding:utf-8 -*- """ @file python_material_linear_elastic4_test.py @author Richard Leute @date 27 Mar 2018 @brief description @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 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. """ import unittest import numpy as np from python_test_imports import µ class MaterialLinearElastic4_Check(unittest.TestCase): """ Check the implementation of storing the first and second Lame constant in each cell. Assign the same Youngs modulus and Poisson ratio to each cell, from which the two Lame constants are internally computed. Then calculate the stress and compare the result with stress=2*mu*Del0 (Hooke law for small symmetric strains). """ def setUp(self): self.resolution = [7,7] self.lengths = [2.3, 3.9] self.formulation = µ.Formulation.small_strain self.sys = µ.Cell(self.resolution, self.lengths, self.formulation) + self.dim = len (self.lengths) self.mat = µ.material.MaterialLinearElastic4_2d.make( self.sys, "material") def test_solver(self): Youngs_modulus = 10. Poisson_ratio = 0.3 for i, pixel in enumerate(self.sys): self.mat.add_pixel(pixel, Youngs_modulus, Poisson_ratio) self.sys.initialise() tol = 1e-6 Del0 = np.array([[0, 0.025], [0.025, 0]]) maxiter = 100 - verbose = 1 + verbose = False solver=µ.solvers.SolverCG(self.sys, tol, maxiter, verbose) r = µ.solvers.newton_cg(self.sys, Del0, solver, tol, tol, verbose) #compare the computed stress with the trivial by hand computed stress mu = (Youngs_modulus/(2*(1+Poisson_ratio))) stress = 2*mu*Del0 - self.assertLess(np.linalg.norm(r.stress-stress.reshape(-1,1)), 1e-8) + self.assertLess(np.linalg.norm(r.stress.reshape(-1, self.dim**2) - + stress.reshape(1,self.dim**2)), 1e-8) diff --git a/tests/test_cell_base.cc b/tests/test_cell_base.cc index 0dcc84d..205f8e7 100644 --- a/tests/test_cell_base.cc +++ b/tests/test_cell_base.cc @@ -1,194 +1,219 @@ /** * @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 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 #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" namespace muSpectre { 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>; 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)}; + 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; } } - fix::initialise_materials(); 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 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::initialise_materials(); 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_AUTO_TEST_SUITE_END(); } // muSpectre diff --git a/tests/test_fftw_engine.cc b/tests/test_fftw_engine.cc index 3fdb161..ff57ebe 100644 --- a/tests/test_fftw_engine.cc +++ b/tests/test_fftw_engine.cc @@ -1,132 +1,132 @@ /** * @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 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 "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 { 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); } constexpr static Ccoord_t loc() { return CcoordOps::get_cube(0); } - FFTW_fixture() : engine(res()) {} - FFTWEngine engine; + 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()} {} - FFTWEngine engine; + FFTW_fixture_python_segfault() : engine{res(), mdim*mdim} {} + FFTWEngine engine; }; using fixlist = boost::mpl::list, FFTW_fixture< twoD, threeD, 3>, FFTW_fixture, FFTW_fixture< twoD, twoD, 4>, FFTW_fixture< twoD, threeD, 4>, 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_FIXTURE_TEST_CASE_TEMPLATE(fft_test, Fix, fixlist, Fix) { Fix::engine.initialise(FFT_PlanFlags::estimate); constexpr Dim_t order{2}; using FC_t = GlobalFieldCollection; FC_t fc; auto & input{make_field>("input", fc)}; auto & ref {make_field>("reference", fc)}; auto & result{make_field>("result", fc)}; fc.initialise(Fix::res(), Fix::loc()); using map_t = 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>; 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(); } // muSpectre diff --git a/tests/test_field_collections_header.hh b/tests/test_field_collections.hh similarity index 95% rename from tests/test_field_collections_header.hh rename to tests/test_field_collections.hh index 4d8bb71..6457686 100644 --- a/tests/test_field_collections_header.hh +++ b/tests/test_field_collections.hh @@ -1,163 +1,166 @@ /** - * @file test_field_collections_header.hh + * @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 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 TEST_FIELD_COLLECTIONS_HEADER_H -#define TEST_FIELD_COLLECTIONS_HEADER_H +#ifndef TEST_FIELD_COLLECTIONS_H +#define TEST_FIELD_COLLECTIONS_H #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 { //! 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 + 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, 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, 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>>; } // muSpectre -#endif /* TEST_FIELD_COLLECTIONS_HEADER_H */ +#endif /* TEST_FIELD_COLLECTIONS_H */ diff --git a/tests/test_field_collections.cc b/tests/test_field_collections_1.cc similarity index 99% rename from tests/test_field_collections.cc rename to tests/test_field_collections_1.cc index 481505c..44a5988 100644 --- a/tests/test_field_collections.cc +++ b/tests/test_field_collections_1.cc @@ -1,221 +1,221 @@ /** - * @file test_field_collections.cc + * @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 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 "test_field_collections_header.hh" +#include "test_field_collections.hh" namespace muSpectre { 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< decltype(F::fc), Real, mdim*mdim*mdim*mdim>; using stype = Eigen::Array; auto & field = reinterpret_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(); } // muSpectre diff --git a/tests/test_field_collections_2.cc b/tests/test_field_collections_2.cc index 3aace04..c3c4201 100644 --- a/tests/test_field_collections_2.cc +++ b/tests/test_field_collections_2.cc @@ -1,254 +1,275 @@ /** * @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 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 "test_field_collections_header.hh" +#include "test_field_collections.hh" namespace muSpectre { 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"]}; F::fc["Tensorfield Real o4"].set_zero(); for (auto && tens:T4map) { BOOST_CHECK_EQUAL(Real(Eigen::Tensor(tens.abs().sum().eval())()), 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; } - Uint counter{0}; + 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 copy, move, and assigment constructor (and operator+) it_t itcopy = it1; it_t itmove = std::move(T4map.begin()); it_t it4 = it1+diff; it_t it5(it2); it_t tmp(it2); it_t it6(std::move(tmp)); it_t it7 = it4 -diff; BOOST_CHECK_EQUAL(itcopy, it1); BOOST_CHECK_EQUAL(itmove, it1); BOOST_CHECK_EQUAL(it4, it3); BOOST_CHECK_EQUAL(it5, it2); BOOST_CHECK_EQUAL(it6, it5); BOOST_CHECK_EQUAL(it7, it1); // check increments/decrements BOOST_CHECK_EQUAL(it1++, itcopy); // post-increment BOOST_CHECK_EQUAL(it1, itcopy+1); BOOST_CHECK_EQUAL(--it1, itcopy); // pre -decrement BOOST_CHECK_EQUAL(++it1, itcopy+1); // pre -increment BOOST_CHECK_EQUAL(it1--, itcopy+1); // post-decrement BOOST_CHECK_EQUAL(it1, itcopy); // dereference and member-of-pointer check Eigen::Tensor Tens = *it1; Eigen::Tensor Tens2 = *itstart; Eigen::Tensor check = (Tens==Tens2).all(); BOOST_CHECK_EQUAL(bool(check()), true); BOOST_CHECK_NO_THROW(itstart->setZero()); //check access subscripting auto T3a = *it3; auto T3b = itstart[diff]; BOOST_CHECK(bool(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_AUTO_TEST_SUITE_END(); } // muSpectre diff --git a/tests/test_field_collections_3.cc b/tests/test_field_collections_3.cc index 524cd6b..2ba1ada 100644 --- a/tests/test_field_collections_3.cc +++ b/tests/test_field_collections_3.cc @@ -1,83 +1,143 @@ /** * @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 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 "test_field_collections_header.hh" +#include "test_field_collections.hh" #include "tests/test_goodies.hh" #include "common/tensor_algebra.hh" namespace muSpectre { 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_AUTO_TEST_SUITE_END(); } // muSpectre diff --git a/tests/test_fields.cc b/tests/test_fields.cc index 2826202..0f985c3 100644 --- a/tests/test_fields.cc +++ b/tests/test_fields.cc @@ -1,49 +1,190 @@ /** * @file 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 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 "tests.hh" #include "common/field_collection.hh" #include "common/field.hh" +#include "common/ccoord_operations.hh" + +#include + +#include namespace muSpectre { 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 DField_t = TypedField; + + FieldFixture() + : tensor_field{make_field("TensorField", 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; + 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; FC_t fc; using TF_t = TensorField; - make_field("TensorField 1", fc); + 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_AUTO_TEST_SUITE_END(); } // muSpectre diff --git a/tests/test_projection.hh b/tests/test_projection.hh index a6371e2..d3b4d68 100644 --- a/tests/test_projection.hh +++ b/tests/test_projection.hh @@ -1,86 +1,86 @@ /** * @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 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 "tests.hh" #include "fft/fftw_engine.hh" #include #include 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 = FFTWEngine; using Parent = Proj; constexpr static Dim_t sdim{DimS}; constexpr static Dim_t mdim{DimM}; ProjectionFixture() - : projector(std::make_unique(SizeGiver::get_resolution()), + : projector(std::make_unique(SizeGiver::get_resolution(), mdim*mdim), SizeGiver::get_lengths()) {} Parent projector; }; } // muSpectre diff --git a/tests/test_projection_finite.cc b/tests/test_projection_finite.cc index 916f0b3..d1e5145 100644 --- a/tests/test_projection_finite.cc +++ b/tests/test_projection_finite.cc @@ -1,137 +1,137 @@ /** * @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 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 "fft/projection_finite_strain.hh" #include "fft/projection_finite_strain_fast.hh" #include "fft/fft_utils.hh" #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_AUTO_TEST_CASE(even_grid_test) { - using Engine = FFTWEngine; + using Engine = FFTWEngine; using proj = ProjectionFiniteStrainFast; - auto engine = std::make_unique(Ccoord_t{2, 2}); + 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 Vector = Eigen::Matrix; Fields fields{}; FieldT & f_grad{make_field("gradient", fields)}; FieldT & f_var{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()}; 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]; ; } 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(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); 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(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 << "vector :" << std::endl << vec.transpose() << std::endl; } } } BOOST_AUTO_TEST_SUITE_END(); } // muSpectre diff --git a/tests/test_raw_field_map.cc b/tests/test_raw_field_map.cc index e548bfa..6eaf611 100644 --- a/tests/test_raw_field_map.cc +++ b/tests/test_raw_field_map.cc @@ -1,93 +1,93 @@ /** * file 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 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 "test_field_collections_header.hh" +#include "test_field_collections.hh" #include "common/field_map.hh" namespace muSpectre { 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>> 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(); } // muSpectre diff --git a/tests/test_solver_newton_cg.cc b/tests/test_solver_newton_cg.cc index 76c228f..f32b9c2 100644 --- a/tests/test_solver_newton_cg.cc +++ b/tests/test_solver_newton_cg.cc @@ -1,195 +1,446 @@ /** * @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 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 "tests.hh" #include "solver/solvers.hh" #include "solver/solver_cg.hh" -#include "solver/solver_cg_eigen.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 "materials/material_linear_elastic1.hh" #include "common/iterators.hh" #include "common/ccoord_operations.hh" #include "cell/cell_factory.hh" +#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)}; + auto fft_ptr{std::make_unique>(resolutions, 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 bool verbose{false}; GradIncrements grads; grads.push_back(delF0); - SolverCG cg{sys, cg_tol, maxiter, bool(verbose)}; - Eigen::ArrayXXd res1{de_geus(sys, grads, cg, newton_tol, verbose)[0].grad}; + DeprecatedSolverCG cg{sys, cg_tol, maxiter, bool(verbose)}; + Eigen::ArrayXXd res1{deprecated_de_geus(sys, grads, cg, newton_tol, verbose)[0].grad}; - SolverCG cg2{sys, cg_tol, maxiter, bool(verbose)}; - Eigen::ArrayXXd res2{newton_cg(sys, grads, cg2, newton_tol, verbose)[0].grad}; + DeprecatedSolverCG cg2{sys, cg_tol, maxiter, bool(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 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}; - SolverCGEigen cg{sys, cg_tol, maxiter, bool(verbose)}; - auto result = de_geus(sys, delEps0, cg, newton_tol, + DeprecatedSolverCGEigen cg{sys, cg_tol, maxiter, bool(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; - SolverCG cg2{sys, cg_tol, maxiter, bool(verbose)}; - result = newton_cg(sys, delEps0, cg2, newton_tol, + DeprecatedSolverCG cg2{sys, cg_tol, maxiter, bool(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>; + + 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 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, bool(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, bool(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 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, bool(verbose)}; + auto F = sys.get_strain_vector(); + F.setZero(); + sys.evaluate_stress_tangent(); + Eigen::VectorXd DelF(sys.get_nb_dof()); + using RMap_t = 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, bool(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(); } // muSpectre